From 75457c70447854d4f8550ed849cd75906cc3f06f Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Zolt=C3=A1n=20Nagy?= Date: Thu, 6 Jun 2019 20:54:23 +0100 Subject: [PATCH 01/15] Upgrade to libtcod 1.6.7 --- .idea/modules.xml | 8 + .idea/tcod-rs.iml | 15 + .idea/vcs.xml | 6 + .idea/workspace.xml | 292 +++++++++ tcod_sys/Cargo.toml | 2 +- tcod_sys/libtcod/LIBTCOD-LICENSE.txt | 9 +- tcod_sys/libtcod/README-linux-SDL2.md | 2 +- tcod_sys/libtcod/README.md | 4 +- tcod_sys/libtcod/include/bresenham.h | 44 +- tcod_sys/libtcod/include/bresenham.hpp | 26 +- tcod_sys/libtcod/include/bsp.h | 12 +- tcod_sys/libtcod/include/bsp.hpp | 100 +-- tcod_sys/libtcod/include/color.h | 58 +- tcod_sys/libtcod/include/color.hpp | 48 +- tcod_sys/libtcod/include/console.h | 17 +- tcod_sys/libtcod/include/console.hpp | 13 +- tcod_sys/libtcod/include/console_rexpaint.h | 50 ++ tcod_sys/libtcod/include/console_types.h | 50 +- tcod_sys/libtcod/include/fov.h | 10 +- tcod_sys/libtcod/include/fov.hpp | 78 +-- tcod_sys/libtcod/include/fov_types.h | 10 +- tcod_sys/libtcod/include/gui/button.hpp | 50 ++ tcod_sys/libtcod/include/gui/container.hpp | 44 ++ tcod_sys/libtcod/include/gui/flatlist.hpp | 52 ++ tcod_sys/libtcod/include/gui/gui.hpp | 48 ++ .../libtcod/include/gui/gui_portability.hpp | 49 ++ tcod_sys/libtcod/include/gui/hbox.hpp | 36 ++ tcod_sys/libtcod/include/gui/image.hpp | 42 ++ tcod_sys/libtcod/include/gui/label.hpp | 42 ++ tcod_sys/libtcod/include/gui/radiobutton.hpp | 51 ++ tcod_sys/libtcod/include/gui/slider.hpp | 58 ++ tcod_sys/libtcod/include/gui/statusbar.hpp | 36 ++ tcod_sys/libtcod/include/gui/textbox.hpp | 54 ++ tcod_sys/libtcod/include/gui/togglebutton.hpp | 45 ++ tcod_sys/libtcod/include/gui/toolbar.hpp | 44 ++ tcod_sys/libtcod/include/gui/vbox.hpp | 38 ++ tcod_sys/libtcod/include/gui/widget.hpp | 87 +++ tcod_sys/libtcod/include/heightmap.h | 13 +- tcod_sys/libtcod/include/heightmap.hpp | 9 +- tcod_sys/libtcod/include/howto.hpp | 10 +- tcod_sys/libtcod/include/image.h | 13 +- tcod_sys/libtcod/include/image.hpp | 102 +-- tcod_sys/libtcod/include/lex.h | 10 +- tcod_sys/libtcod/include/lex.hpp | 15 +- tcod_sys/libtcod/include/libtcod.h | 11 +- tcod_sys/libtcod/include/libtcod.hpp | 10 +- tcod_sys/libtcod/include/libtcod_int.h | 35 +- .../libtcod/include/libtcod_portability.h | 20 +- tcod_sys/libtcod/include/libtcod_utility.h | 6 +- tcod_sys/libtcod/include/libtcod_version.h | 10 +- tcod_sys/libtcod/include/list.h | 10 +- tcod_sys/libtcod/include/list.hpp | 128 ++-- tcod_sys/libtcod/include/mersenne.h | 10 +- tcod_sys/libtcod/include/mersenne.hpp | 10 +- tcod_sys/libtcod/include/mersenne_types.h | 10 +- tcod_sys/libtcod/include/mouse.h | 10 +- tcod_sys/libtcod/include/mouse.hpp | 10 +- tcod_sys/libtcod/include/mouse_types.h | 16 +- tcod_sys/libtcod/include/namegen.h | 9 +- tcod_sys/libtcod/include/namegen.hpp | 33 +- tcod_sys/libtcod/include/noise.h | 10 +- tcod_sys/libtcod/include/noise.hpp | 16 +- tcod_sys/libtcod/include/noise_defaults.h | 27 + tcod_sys/libtcod/include/parser.h | 10 +- tcod_sys/libtcod/include/parser.hpp | 10 +- tcod_sys/libtcod/include/path.h | 10 +- tcod_sys/libtcod/include/path.hpp | 11 +- tcod_sys/libtcod/include/sys.h | 20 +- tcod_sys/libtcod/include/sys.hpp | 32 +- tcod_sys/libtcod/include/tree.h | 10 +- tcod_sys/libtcod/include/tree.hpp | 10 +- tcod_sys/libtcod/include/txtfield.h | 11 +- tcod_sys/libtcod/include/txtfield.hpp | 10 +- tcod_sys/libtcod/include/wrappers.h | 9 +- tcod_sys/libtcod/include/zip.h | 10 +- tcod_sys/libtcod/include/zip.hpp | 82 +-- tcod_sys/libtcod/src/bresenham.cpp | 17 +- tcod_sys/libtcod/src/bresenham_c.c | 113 +++- tcod_sys/libtcod/src/bsp.cpp | 10 +- tcod_sys/libtcod/src/bsp_c.c | 13 +- tcod_sys/libtcod/src/color.cpp | 10 +- tcod_sys/libtcod/src/color_c.c | 583 ++++++++++-------- tcod_sys/libtcod/src/console.cpp | 9 +- tcod_sys/libtcod/src/console_c.c | 112 +++- tcod_sys/libtcod/src/console_rexpaint.c | 442 ++++++------- tcod_sys/libtcod/src/fov.cpp | 9 +- tcod_sys/libtcod/src/fov_c.c | 10 +- .../libtcod/src/fov_circular_raycasting.c | 17 +- tcod_sys/libtcod/src/fov_diamond_raycasting.c | 9 +- tcod_sys/libtcod/src/fov_permissive2.c | 20 +- .../libtcod/src/fov_recursive_shadowcasting.c | 10 +- tcod_sys/libtcod/src/fov_restrictive.c | 10 +- tcod_sys/libtcod/src/gui/README.txt | 1 + tcod_sys/libtcod/src/gui/button.cpp | 101 +++ tcod_sys/libtcod/src/gui/container.cpp | 62 ++ tcod_sys/libtcod/src/gui/flatlist.cpp | 114 ++++ tcod_sys/libtcod/src/gui/hbox.cpp | 51 ++ tcod_sys/libtcod/src/gui/image.cpp | 49 ++ tcod_sys/libtcod/src/gui/label.cpp | 48 ++ tcod_sys/libtcod/src/gui/radiobutton.cpp | 64 ++ tcod_sys/libtcod/src/gui/slider.cpp | 131 ++++ tcod_sys/libtcod/src/gui/statusbar.cpp | 37 ++ tcod_sys/libtcod/src/gui/textbox.cpp | 159 +++++ tcod_sys/libtcod/src/gui/togglebutton.cpp | 52 ++ tcod_sys/libtcod/src/gui/toolbar.cpp | 125 ++++ tcod_sys/libtcod/src/gui/vbox.cpp | 48 ++ tcod_sys/libtcod/src/gui/widget.cpp | 145 +++++ tcod_sys/libtcod/src/heightmap.cpp | 10 +- tcod_sys/libtcod/src/heightmap_c.c | 11 +- tcod_sys/libtcod/src/image.cpp | 11 +- tcod_sys/libtcod/src/image_c.c | 29 +- tcod_sys/libtcod/src/lex.cpp | 10 +- tcod_sys/libtcod/src/lex_c.c | 20 +- tcod_sys/libtcod/src/list_c.c | 10 +- tcod_sys/libtcod/src/mersenne.cpp | 9 +- tcod_sys/libtcod/src/mersenne_c.c | 9 +- tcod_sys/libtcod/src/mouse.cpp | 9 +- tcod_sys/libtcod/src/namegen.cpp | 9 +- tcod_sys/libtcod/src/namegen_c.c | 10 +- tcod_sys/libtcod/src/noise.cpp | 9 +- tcod_sys/libtcod/src/noise_c.c | 9 +- tcod_sys/libtcod/src/parser.cpp | 10 +- tcod_sys/libtcod/src/parser_c.c | 10 +- tcod_sys/libtcod/src/path.cpp | 10 +- tcod_sys/libtcod/src/path_c.c | 9 +- tcod_sys/libtcod/src/sys.cpp | 23 +- tcod_sys/libtcod/src/sys_c.c | 27 +- tcod_sys/libtcod/src/sys_opengl_c.c | 56 +- tcod_sys/libtcod/src/sys_sdl2_c.c | 51 +- tcod_sys/libtcod/src/sys_sdl_c.c | 97 +-- tcod_sys/libtcod/src/sys_sdl_img_bmp.c | 13 +- tcod_sys/libtcod/src/sys_sdl_img_png.c | 19 +- tcod_sys/libtcod/src/tree_c.c | 9 +- tcod_sys/libtcod/src/txtfield.cpp | 14 +- tcod_sys/libtcod/src/txtfield_c.c | 17 +- tcod_sys/libtcod/src/wrappers.c | 11 +- tcod_sys/libtcod/src/zip.cpp | 9 +- tcod_sys/libtcod/src/zip_c.c | 9 +- 138 files changed, 4123 insertions(+), 1445 deletions(-) create mode 100644 .idea/modules.xml create mode 100644 .idea/tcod-rs.iml create mode 100644 .idea/vcs.xml create mode 100644 .idea/workspace.xml create mode 100644 tcod_sys/libtcod/include/console_rexpaint.h create mode 100644 tcod_sys/libtcod/include/gui/button.hpp create mode 100644 tcod_sys/libtcod/include/gui/container.hpp create mode 100644 tcod_sys/libtcod/include/gui/flatlist.hpp create mode 100644 tcod_sys/libtcod/include/gui/gui.hpp create mode 100644 tcod_sys/libtcod/include/gui/gui_portability.hpp create mode 100644 tcod_sys/libtcod/include/gui/hbox.hpp create mode 100644 tcod_sys/libtcod/include/gui/image.hpp create mode 100644 tcod_sys/libtcod/include/gui/label.hpp create mode 100644 tcod_sys/libtcod/include/gui/radiobutton.hpp create mode 100644 tcod_sys/libtcod/include/gui/slider.hpp create mode 100644 tcod_sys/libtcod/include/gui/statusbar.hpp create mode 100644 tcod_sys/libtcod/include/gui/textbox.hpp create mode 100644 tcod_sys/libtcod/include/gui/togglebutton.hpp create mode 100644 tcod_sys/libtcod/include/gui/toolbar.hpp create mode 100644 tcod_sys/libtcod/include/gui/vbox.hpp create mode 100644 tcod_sys/libtcod/include/gui/widget.hpp create mode 100644 tcod_sys/libtcod/src/gui/README.txt create mode 100644 tcod_sys/libtcod/src/gui/button.cpp create mode 100644 tcod_sys/libtcod/src/gui/container.cpp create mode 100644 tcod_sys/libtcod/src/gui/flatlist.cpp create mode 100644 tcod_sys/libtcod/src/gui/hbox.cpp create mode 100644 tcod_sys/libtcod/src/gui/image.cpp create mode 100644 tcod_sys/libtcod/src/gui/label.cpp create mode 100644 tcod_sys/libtcod/src/gui/radiobutton.cpp create mode 100644 tcod_sys/libtcod/src/gui/slider.cpp create mode 100644 tcod_sys/libtcod/src/gui/statusbar.cpp create mode 100644 tcod_sys/libtcod/src/gui/textbox.cpp create mode 100644 tcod_sys/libtcod/src/gui/togglebutton.cpp create mode 100644 tcod_sys/libtcod/src/gui/toolbar.cpp create mode 100644 tcod_sys/libtcod/src/gui/vbox.cpp create mode 100644 tcod_sys/libtcod/src/gui/widget.cpp diff --git a/.idea/modules.xml b/.idea/modules.xml new file mode 100644 index 000000000..373ae6621 --- /dev/null +++ b/.idea/modules.xml @@ -0,0 +1,8 @@ + + + + + + + + \ No newline at end of file diff --git a/.idea/tcod-rs.iml b/.idea/tcod-rs.iml new file mode 100644 index 000000000..f270a3310 --- /dev/null +++ b/.idea/tcod-rs.iml @@ -0,0 +1,15 @@ + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/.idea/vcs.xml b/.idea/vcs.xml new file mode 100644 index 000000000..35eb1ddfb --- /dev/null +++ b/.idea/vcs.xml @@ -0,0 +1,6 @@ + + + + + + \ No newline at end of file diff --git a/.idea/workspace.xml b/.idea/workspace.xml new file mode 100644 index 000000000..87e8520be --- /dev/null +++ b/.idea/workspace.xml @@ -0,0 +1,292 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + @@ -234,16 +314,22 @@ + + + + + + + + + - - - - - + + @@ -251,11 +337,14 @@ - - + + + + + @@ -273,18 +362,60 @@ - + + + - + - + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + - - + + + + + + + + + diff --git a/tcod_sys/Cargo.toml b/tcod_sys/Cargo.toml index de9383bc2..7856ae29e 100644 --- a/tcod_sys/Cargo.toml +++ b/tcod_sys/Cargo.toml @@ -1,7 +1,7 @@ [package] name = "tcod-sys" description = "Raw FFI bindings & build script to link against libtcod." -version = "5.2.0" +version = "5.3.0" license = "WTFPL" homepage = "https://github.com/tomassedovic/tcod-rs" repository = "https://github.com/tomassedovic/tcod-rs/tree/master/tcod-sys" diff --git a/tcod_sys/build.rs b/tcod_sys/build.rs index ec81a1200..99b1bd633 100644 --- a/tcod_sys/build.rs +++ b/tcod_sys/build.rs @@ -16,8 +16,8 @@ fn build_libz(libz_sources: &[&str]) { } fn build_libtcod_objects(mut config: cc::Build, sources: &[&str]) { - config.include("libtcod/include"); - config.include("libtcod/src/vendor"); + config.include("libtcod/src/libtcod"); + config.include("libtcod/src/vendor/utf8proc"); config.include("libtcod/src/vendor/zlib"); for c_file in sources { config.file(c_file); @@ -146,40 +146,76 @@ fn main() { ]; let vendor_sources = &[ - "libtcod/src/vendor/stb.c" + "libtcod/src/vendor/stb.c", + "libtcod/src/vendor/lodepng.cpp", + "libtcod/src/vendor/utf8proc/utf8proc.c", ]; let libtcod_sources = &[ - "libtcod/src/bresenham_c.c", - "libtcod/src/bsp_c.c", - "libtcod/src/color_c.c", - "libtcod/src/console_c.c", - "libtcod/src/console_rexpaint.c", - "libtcod/src/fov_c.c", - "libtcod/src/fov_circular_raycasting.c", - "libtcod/src/fov_diamond_raycasting.c", - "libtcod/src/fov_permissive2.c", - "libtcod/src/fov_recursive_shadowcasting.c", - "libtcod/src/fov_restrictive.c", - "libtcod/src/heightmap_c.c", - "libtcod/src/image_c.c", - "libtcod/src/lex_c.c", - "libtcod/src/list_c.c", - "libtcod/src/mersenne_c.c", - "libtcod/src/namegen_c.c", - "libtcod/src/noise_c.c", - "libtcod/src/parser_c.c", - "libtcod/src/path_c.c", - "libtcod/src/sys_c.c", - "libtcod/src/sys_sdl2_c.c", - "libtcod/src/sys_sdl_c.c", - "libtcod/src/sys_sdl_img_bmp.c", - "libtcod/src/sys_sdl_img_png.c", - "libtcod/src/tree_c.c", - "libtcod/src/txtfield_c.c", - "libtcod/src/wrappers.c", - "libtcod/src/zip_c.c", - "libtcod/src/png/lodepng.c", + "libtcod/src/libtcod/bresenham_c.c", + "libtcod/src/libtcod/bsp_c.c", + "libtcod/src/libtcod/color_c.c", + "libtcod/src/libtcod/console.cpp", + "libtcod/src/libtcod/console_c.cpp", + "libtcod/src/libtcod/console_printing.c", + "libtcod/src/libtcod/console_rexpaint.c", + "libtcod/src/libtcod/fov_c.c", + "libtcod/src/libtcod/fov_circular_raycasting.c", + "libtcod/src/libtcod/fov_diamond_raycasting.c", + "libtcod/src/libtcod/fov_permissive2.c", + "libtcod/src/libtcod/fov_recursive_shadowcasting.c", + "libtcod/src/libtcod/fov_restrictive.c", + "libtcod/src/libtcod/heightmap_c.c", + "libtcod/src/libtcod/image.cpp", + "libtcod/src/libtcod/image_c.c", + "libtcod/src/libtcod/lex_c.c", + "libtcod/src/libtcod/list_c.c", + "libtcod/src/libtcod/mersenne_c.c", + "libtcod/src/libtcod/namegen_c.c", + "libtcod/src/libtcod/noise_c.c", + "libtcod/src/libtcod/parser_c.c", + "libtcod/src/libtcod/path_c.c", + "libtcod/src/libtcod/sys_c.cpp", + "libtcod/src/libtcod/sys_opengl_c.cpp", + "libtcod/src/libtcod/sys_sdl2_c.cpp", + "libtcod/src/libtcod/sys_sdl_c.cpp", + "libtcod/src/libtcod/sys_sdl_img_bmp.cpp", + "libtcod/src/libtcod/sys_sdl_img_png.cpp", + "libtcod/src/libtcod/tree_c.c", + "libtcod/src/libtcod/txtfield_c.c", + "libtcod/src/libtcod/wrappers.c", + "libtcod/src/libtcod/zip_c.c", + // color + "libtcod/src/libtcod/color/canvas.cpp", + // engine + "libtcod/src/libtcod/engine/backend.cpp", + "libtcod/src/libtcod/engine/display.cpp", + "libtcod/src/libtcod/engine/globals.cpp", + // gui + // "libtcod/src/libtcod/gui/button.cpp", + // "libtcod/src/libtcod/gui/container.cpp", + // "libtcod/src/libtcod/gui/flatlist.cpp", + // "libtcod/src/libtcod/gui/hbox.cpp", + // "libtcod/src/libtcod/gui/image.cpp", + // "libtcod/src/libtcod/gui/label.cpp", + // "libtcod/src/libtcod/gui/radiobutton.cpp", + // "libtcod/src/libtcod/gui/slider.cpp", + // "libtcod/src/libtcod/gui/statusbar.cpp", + // "libtcod/src/libtcod/gui/textbox.cpp", + // "libtcod/src/libtcod/gui/togglebutton.cpp", + // "libtcod/src/libtcod/gui/toolbar.cpp", + // "libtcod/src/libtcod/gui/vbox.cpp", + // "libtcod/src/libtcod/gui/widget.cpp", + // sdl2 + "libtcod/src/libtcod/sdl2/legacy_backend.cpp", + "libtcod/src/libtcod/sdl2/sdl2_alias.cpp", + "libtcod/src/libtcod/sdl2/sdl2_display.cpp", + "libtcod/src/libtcod/sdl2/sdl2_renderer.cpp", + // tileset + "libtcod/src/libtcod/tileset/observer.cpp", + "libtcod/src/libtcod/tileset/tile.cpp", + "libtcod/src/libtcod/tileset/tileset.cpp", + "libtcod/src/libtcod/tileset/tilesheet.cpp", ]; if target.contains("linux") { @@ -215,7 +251,7 @@ fn main() { config.flag("-shared"); config.flag("-o"); config.flag(dst.join("libtcod.dylib").to_str().unwrap()); - for c_file in libtcod_sources { + for c_file in libtcod_sources.iter() { config.flag(dst.join(c_file).with_extension("o").to_str().unwrap()); } config.flag(dst.join("libz.a").to_str().unwrap()); @@ -254,13 +290,15 @@ fn main() { fs::create_dir(dst.join("lib")).unwrap(); config.flag(&format!("-Wl,--out-implib,{}", dst.join("lib/libtcod.a").display())); config.include(Path::new("libtcod").join("src").join("vendor")); + config.include(Path::new("libtcod").join("src").join("vendor").join("utf8proc")); config.include(Path::new("libtcod").join("src").join("vendor").join("zlib")); - config.include(Path::new("libtcod").join("include")); - for c_file in libz_sources.iter().chain(libtcod_sources).chain(vendor_sources) { + config.include(Path::new("libtcod").join("src").join("libtcod")); + for c_file in libz_sources.iter().chain(libtcod_sources.iter()).chain(vendor_sources) { let path = c_file.split('/').fold(PathBuf::new(), |path, segment| path.join(segment)); config.flag(src.join(path).to_str().unwrap()); } config.flag("-mwindows"); + config.flag("-EHsc"); config.flag("-L"); config.flag(sdl_lib_dir.to_str().unwrap()); config.flag("-lSDL2"); @@ -289,12 +327,20 @@ fn main() { config.flag("/DNO_OPENGL"); config.flag("/DNDEBUG"); config.flag("/DLIBTCOD_EXPORTS"); + config.flag("/EHsc"); config.flag(&format!("/Fo:{}\\", dst.to_str().unwrap())); config.include(sdl_include_dir.to_str().unwrap()); config.include(Path::new("libtcod").join("src").join("vendor")); + config.include(Path::new("libtcod").join("src").join("vendor").join("utf8proc")); config.include(Path::new("libtcod").join("src").join("vendor").join("zlib")); - config.include(Path::new("libtcod").join("include")); - for c_file in libz_sources.iter().chain(vendor_sources).chain(libtcod_sources) { + config.include(Path::new("libtcod").join("src").join("libtcod")); + config.include(Path::new("libtcod").join("src").join("libtcod").join("color")); + config.include(Path::new("libtcod").join("src").join("libtcod").join("engine")); + config.include(Path::new("libtcod").join("src").join("libtcod").join("gui")); + config.include(Path::new("libtcod").join("src").join("libtcod").join("sdl2")); + config.include(Path::new("libtcod").join("src").join("libtcod").join("tileset")); + config.include(Path::new("libtcod").join("src").join("libtcod").join("utility")); + for c_file in libz_sources.iter().chain(vendor_sources).chain(libtcod_sources.iter()) { // Make sure the path is in the Windows format. This // shouldn't matter but it's distracting when debugging // build script issues. diff --git a/tcod_sys/libtcod/LIBTCOD-CREDITS.txt b/tcod_sys/libtcod/LIBTCOD-CREDITS.txt index cfbcea982..70a8d6bc0 100644 --- a/tcod_sys/libtcod/LIBTCOD-CREDITS.txt +++ b/tcod_sys/libtcod/LIBTCOD-CREDITS.txt @@ -9,6 +9,9 @@ Products : - stb_sprintf, originally by Jeff Roberts / RAD Game Tools, 2015/10/20 http://github.com/nothings/stb (modified to compile for C89) +- utf8proc + https://github.com/JuliaStrings/utf8proc + (modified to be statically linkable, and to compile for C89) Many thanks to everyone who provided feedback and patches, and especially : - Dominik 'Mingos' Marczuk for the restrictive shadowcasting fov, djikstra diff --git a/tcod_sys/libtcod/README.md b/tcod_sys/libtcod/README.md index 3d31eaeeb..06c4b7d3e 100644 --- a/tcod_sys/libtcod/README.md +++ b/tcod_sys/libtcod/README.md @@ -1,12 +1,24 @@ -[TOC] +# Table of contents # -## Introduction ## + * [Table of contents](#table-of-contents) + * [Introduction](#introduction) + * [What can it do?](#what-can-it-do) + * [How do I get set up?](#how-do-i-get-set-up) + * [Using one of our downloads](#using-one-of-our-downloads) + * [Compiling from source](#compiling-from-source) + * [Getting Started](#getting-started) -libtcod is a free, fast, portable and uncomplicated API for roguelike developers providing an advanced true color console, input, and lots of other utilities frequently used in roguelikes. +# Introduction # -Status: [![Build status](https://ci.appveyor.com/api/projects/status/6jh07hq205iy0mlh/branch/default?svg=true)](https://ci.appveyor.com/project/rmtew/libtcod/branch/default) +libtcod is a free, fast, portable and uncomplicated API for roguelike +developers providing an advanced true color console, input, and lots of other +utilities frequently used in roguelikes. -## What can it do? ## +Status: +[![Build status](https://ci.appveyor.com/api/projects/status/pemepxo2221f8heo/branch/master?svg=true)](https://ci.appveyor.com/project/HexDecimal/libtcod-6e1jk/branch/master) +[![Build Status](https://travis-ci.org/libtcod/libtcod.svg?branch=master)](https://travis-ci.org/libtcod/libtcod) + +# What can it do? # If you want to get a quick overview of the features that libtcod provides, check out the [Features](https://bitbucket.org/libtcod/libtcod/wiki/Features) page. @@ -14,43 +26,82 @@ If you want to get a quick overview of games which have used libtcod, check out libtcod is also well known for it's [easy to follow tutorial](http://www.roguebasin.com/index.php?title=Complete_Roguelike_Tutorial,_using_python%2Blibtcod), which many people have used to get started developing a roguelike. Follow the relevant links the tutorial gives, and it will point you to the right locations. -## How do I get set up? ## - -### Using one of our downloads ### - -Currently, only Windows binaries are available from the Bitbucket [download section](https://bitbucket.org/libtcod/libtcod/downloads) for this project. If you are programming in C or C++, various sample projects are included within the source code which can be used as examples of various features. For those who wish to program in Python which is the only scripting language support that has been contributed so far, the basics are described in [part 1](http://www.roguebasin.com/index.php?title=Complete_Roguelike_Tutorial,_using_python%2Blibtcod,_part_1#Setting_it_up) of the tutorial. - -Two builds are currently provided for each release: - -* 32 bit (Win32, SDL2 only) binaries also including source code. -* 64 bit (x64, SDL2 only) binaries also including source code. - -**Warning:** If you download these builds, run `samples.exe` as your very first action. If you are unable to and get an error about `vcruntime140.dll` being missing, you need to install the two [Visual Studio 2015 runtimes](https://www.microsoft.com/en-us/download/details.aspx?id=53587). Make sure you install the 32-bit runtime. And make sure you also install the 64-bit runtime. Then run `samples.exe` again, and it should now work. Whether you plan to develop in C, C++, Python or some other language, this is required. - -### Compiling from source ### - -These are the recommended places to obtain the source code from: - -* The latest source code release snapshot on the [downloads page](https://bitbucket.org/libtcod/libtcod/downloads). -* Clone the repository with Mercurial and checkout the tag for the latest version in the `default` branch. -* Clone the repository and checkout the bleeding edge from the tip in the default branch. - -All compilation methods, currently including Visual Studio (Windows), SCons (Windows, Linux, MacOS) and autotools (Linux, MacOS), are located within the `build/` subdirectory. - -Windows users who prefer to use Visual Studio directly can either run the top-level 'build.bat' script, or locate and open the provided solution directly using Visual Studio. The solution is currently for Visual Studio 2015, and the [free community edition](https://www.visualstudio.com/vs/community/) is highly recommended. - -Autotools is a standard approach used for decades, and if you are not familiar with it, you can Bing (or Google) the topic and learn more. Explicit instructions for Linux, which should be relevant, are [provided here](README-linux-SDL2.md). SCons is another popular approach, and explicit instructions are [provided here](https://bitbucket.org/libtcod/libtcod/src/tip/build/scons/?at=default) for those who prefer. - -MacOS users with a working Homebrew installation, can install the necessary dependencies with `brew install autoconf automake libtool pkg-build sdl2`. To build from the current development version of libtcod (rather than downloading a source package), `brew install mercurial`. Then follow [the directions](README-linux-SDL2.md) for building libtcod on Linux (just the final section). Note that the actual libraries will be in libtcod/build/autotools/.lib, with several symlinks. - -#### SDL2 #### - -[SDL2](http://hg.libsdl.org/SDL) is the latest version of SDL. Release 2.0.5 (changeset 007dfe83abf8) of SDL2, is currently used for the official Windows builds. If you choose to use a different version of SDL2, please be sure to mention it in any issues you create. And if you are using the bleeding edge (the latest unreleased/untagged changes), please rule out that this is the cause of any problems you encounter, before creating issues. - -## Getting Started ## - -The latest documentation is updated with every significant change made to libtcod. You can find it in [the doc directory](https://bitbucket.org/libtcod/libtcod/src/tip/doc/index2.html?at=default&fileviewer=file-view-default). Similarly, [the changelog](https://bitbucket.org/libtcod/libtcod/src/tip/libtcod-CHANGELOG.txt?at=default) provides a high level overview of the things you might need to be aware of when later updating libtcod. - -libtcod comes with a sample application, implementations of which are provided in each of C ([samples_c.c](https://bitbucket.org/libtcod/libtcod/src/tip/samples/samples_c.c?at=default)), C++ ([samples_cpp.cpp](https://bitbucket.org/libtcod/libtcod/src/tip/samples/samples_cpp.cpp?at=default)) and Python ([samples_py.py](https://bitbucket.org/libtcod/libtcod/src/tip/python/samples_py.py?at=default)). This provides a decent overview of the basic features, in an interactive fashion. Each should be identical for the most part, so if you are using Windows, downloading the precompiled binaries and running the included `samples.exe` which is compiled from the C source code, should be representative of the other versions. - -The popular [Python tutorial](http://www.roguebasin.com/index.php?title=Complete_Roguelike_Tutorial,_using_python%2Blibtcod) is a good way to both build up a simple roguelike, and get familiar with the basics of libtcod. \ No newline at end of file +# How do I get set up? # + +## Using one of our downloads ## + +Windows and MacOS binaries are available from the +[GitHub Releases page](https://github.com/libtcod/libtcod/releases). + +If you are programming in C or C++, various sample projects are included within +the repository which can be used as examples of various features. + +For those who wish to program in Python which is the only scripting language +support that has been contributed so far, the basics are described in +[part 1](http://www.roguebasin.com/index.php?title=Complete_Roguelike_Tutorial,_using_python%2Blibtcod,_part_1#Setting_it_up) +of the tutorial. +It's currently recommended to install libtcodpy via +[python-tdl](https://github.com/HexDecimal/python-tdl) rather than using the +libtcodpy package included in this repository. + +**Warning:** If you download these builds, run `samples.exe` as your very first +action. +If you are unable to and get an error about `vcruntime140.dll` being missing, +you need to install the two +[Visual Studio 2015 runtimes](https://www.microsoft.com/en-us/download/details.aspx?id=53587). +Make sure you install the 32-bit runtime. +And make sure you also install the 64-bit runtime. +Then run `samples.exe` again, and it should now work. +Whether you plan to develop in C, C++, Python or some other language, this is +required. + +## Compiling from source ## + +You can clone with Mercurial via the +[BitBucket repository](https://bitbucket.org/libtcod/libtcod), or with Git via +the [GitHub repository](https://github.com/libtcod/libtcod). +You can then checkout a specific tag or get the in-development version from +the default or master branches. + +All compilation methods, currently including Visual Studio (Windows), +SCons (Windows, Linux, MacOS) and Autotools (Linux, MacOS), are located within +the `build/` subdirectory. + +Windows users who prefer to use Visual Studio directly can either run the +top-level 'build.bat' script, or locate and open the provided solution directly +using Visual Studio. +The solution is currently for Visual Studio 2015, and the +[free community edition](https://www.visualstudio.com/vs/community/) is highly +recommended. + +SCons automatically downloads SDL2 and can be used on all platforms. +Instructions are +[provided here](https://github.com/libtcod/libtcod/tree/master/build/scons). +The current release builds are built using SCons. + +Autotools is a common standard on Linux, and can be used for MacOS. +Instructions are +[provided here](https://github.com/libtcod/libtcod/tree/master/build/autotools). + +If you ever need to statically compile libtcod the easiest method would be to +use the `src/libtcod_c.c` and `src/libtcod.cpp` source files, which include all +the other sources. Further instructions are included in those files. + +# Getting Started # + +The latest documentation is [here](https://libtcod.readthedocs.io/en/latest). +Currently it's very incomplete, so most people will want to read the +[1.5.1 documentation](http://roguecentral.org/doryen/data/libtcod/doc/1.5.1/index2.html?c=true&cpp=true&cs=false&py=true&lua=false) +instead. + +libtcod comes with a sample application, implementations of which are provided +in each of +C ([samples_c.c](https://bitbucket.org/libtcod/libtcod/src/tip/samples/samples_c.c?at=default)), +C++ ([samples_cpp.cpp](https://bitbucket.org/libtcod/libtcod/src/tip/samples/samples_cpp.cpp?at=default)), +and Python ([samples_py.py](https://bitbucket.org/libtcod/libtcod/src/tip/python/samples_py.py?at=default)). +This provides a decent overview of the basic features, in an interactive +fashion. +Each should be identical for the most part, so if you are using Windows, +downloading the pre-compiled binaries and running the included `samples.exe` +which is compiled from the C source code, should be representative of the other +versions. diff --git a/tcod_sys/libtcod/include/external/pstdint.h b/tcod_sys/libtcod/include/external/pstdint.h deleted file mode 100644 index f4a30815a..000000000 --- a/tcod_sys/libtcod/include/external/pstdint.h +++ /dev/null @@ -1,919 +0,0 @@ -/* A portable stdint.h - **************************************************************************** - * BSD License: - **************************************************************************** - * - * Copyright (c) 2005-2016 Paul Hsieh - * All rights reserved. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions - * are met: - * - * 1. Redistributions of source code must retain the above copyright - * notice, this list of conditions and the following disclaimer. - * 2. Redistributions in binary form must reproduce the above copyright - * notice, this list of conditions and the following disclaimer in the - * documentation and/or other materials provided with the distribution. - * 3. The name of the author may not be used to endorse or promote products - * derived from this software without specific prior written permission. - * - * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR - * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES - * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, - * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, - * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY - * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT - * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF - * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - * - **************************************************************************** - * - * Version 0.1.16.0 - * - * The ANSI C standard committee, for the C99 standard, specified the - * inclusion of a new standard include file called stdint.h. This is - * a very useful and long desired include file which contains several - * very precise definitions for integer scalar types that is critically - * important for making several classes of applications portable - * including cryptography, hashing, variable length integer libraries - * and so on. But for most developers its likely useful just for - * programming sanity. - * - * The problem is that some compiler vendors chose to ignore the C99 - * standard and some older compilers have no opportunity to be updated. - * Because of this situation, simply including stdint.h in your code - * makes it unportable. - * - * So that's what this file is all about. It's an attempt to build a - * single universal include file that works on as many platforms as - * possible to deliver what stdint.h is supposed to. Even compilers - * that already come with stdint.h can use this file instead without - * any loss of functionality. A few things that should be noted about - * this file: - * - * 1) It is not guaranteed to be portable and/or present an identical - * interface on all platforms. The extreme variability of the - * ANSI C standard makes this an impossibility right from the - * very get go. Its really only meant to be useful for the vast - * majority of platforms that possess the capability of - * implementing usefully and precisely defined, standard sized - * integer scalars. Systems which are not intrinsically 2s - * complement may produce invalid constants. - * - * 2) There is an unavoidable use of non-reserved symbols. - * - * 3) Other standard include files are invoked. - * - * 4) This file may come in conflict with future platforms that do - * include stdint.h. The hope is that one or the other can be - * used with no real difference. - * - * 5) In the current version, if your platform can't represent - * int32_t, int16_t and int8_t, it just dumps out with a compiler - * error. - * - * 6) 64 bit integers may or may not be defined. Test for their - * presence with the test: #ifdef INT64_MAX or #ifdef UINT64_MAX. - * Note that this is different from the C99 specification which - * requires the existence of 64 bit support in the compiler. If - * this is not defined for your platform, yet it is capable of - * dealing with 64 bits then it is because this file has not yet - * been extended to cover all of your system's capabilities. - * - * 7) (u)intptr_t may or may not be defined. Test for its presence - * with the test: #ifdef PTRDIFF_MAX. If this is not defined - * for your platform, then it is because this file has not yet - * been extended to cover all of your system's capabilities, not - * because its optional. - * - * 8) The following might not been defined even if your platform is - * capable of defining it: - * - * WCHAR_MIN - * WCHAR_MAX - * (u)int64_t - * PTRDIFF_MIN - * PTRDIFF_MAX - * (u)intptr_t - * - * 9) The following have not been defined: - * - * WINT_MIN - * WINT_MAX - * - * 10) The criteria for defining (u)int_least(*)_t isn't clear, - * except for systems which don't have a type that precisely - * defined 8, 16, or 32 bit types (which this include file does - * not support anyways). Default definitions have been given. - * - * 11) The criteria for defining (u)int_fast(*)_t isn't something I - * would trust to any particular compiler vendor or the ANSI C - * committee. It is well known that "compatible systems" are - * commonly created that have very different performance - * characteristics from the systems they are compatible with, - * especially those whose vendors make both the compiler and the - * system. Default definitions have been given, but its strongly - * recommended that users never use these definitions for any - * reason (they do *NOT* deliver any serious guarantee of - * improved performance -- not in this file, nor any vendor's - * stdint.h). - * - * 12) The following macros: - * - * PRINTF_INTMAX_MODIFIER - * PRINTF_INT64_MODIFIER - * PRINTF_INT32_MODIFIER - * PRINTF_INT16_MODIFIER - * PRINTF_LEAST64_MODIFIER - * PRINTF_LEAST32_MODIFIER - * PRINTF_LEAST16_MODIFIER - * PRINTF_INTPTR_MODIFIER - * - * are strings which have been defined as the modifiers required - * for the "d", "u" and "x" printf formats to correctly output - * (u)intmax_t, (u)int64_t, (u)int32_t, (u)int16_t, (u)least64_t, - * (u)least32_t, (u)least16_t and (u)intptr_t types respectively. - * PRINTF_INTPTR_MODIFIER is not defined for some systems which - * provide their own stdint.h. PRINTF_INT64_MODIFIER is not - * defined if INT64_MAX is not defined. These are an extension - * beyond what C99 specifies must be in stdint.h. - * - * In addition, the following macros are defined: - * - * PRINTF_INTMAX_HEX_WIDTH - * PRINTF_INT64_HEX_WIDTH - * PRINTF_INT32_HEX_WIDTH - * PRINTF_INT16_HEX_WIDTH - * PRINTF_INT8_HEX_WIDTH - * PRINTF_INTMAX_DEC_WIDTH - * PRINTF_INT64_DEC_WIDTH - * PRINTF_INT32_DEC_WIDTH - * PRINTF_INT16_DEC_WIDTH - * PRINTF_UINT8_DEC_WIDTH - * PRINTF_UINTMAX_DEC_WIDTH - * PRINTF_UINT64_DEC_WIDTH - * PRINTF_UINT32_DEC_WIDTH - * PRINTF_UINT16_DEC_WIDTH - * PRINTF_UINT8_DEC_WIDTH - * - * Which specifies the maximum number of characters required to - * print the number of that type in either hexadecimal or decimal. - * These are an extension beyond what C99 specifies must be in - * stdint.h. - * - * Compilers tested (all with 0 warnings at their highest respective - * settings): Borland Turbo C 2.0, WATCOM C/C++ 11.0 (16 bits and 32 - * bits), Microsoft Visual C++ 6.0 (32 bit), Microsoft Visual Studio - * .net (VC7), Intel C++ 4.0, GNU gcc v3.3.3 - * - * This file should be considered a work in progress. Suggestions for - * improvements, especially those which increase coverage are strongly - * encouraged. - * - * Acknowledgements - * - * The following people have made significant contributions to the - * development and testing of this file: - * - * Chris Howie - * John Steele Scott - * Dave Thorup - * John Dill - * Florian Wobbe - * Christopher Sean Morrison - * Mikkel Fahnoe Jorgensen - * - */ - -#include -#include -#include - -/* - * For gcc with _STDINT_H, fill in the PRINTF_INT*_MODIFIER macros, and - * do nothing else. On the Mac OS X version of gcc this is _STDINT_H_. - */ - -#if ((defined(__SUNPRO_C) && __SUNPRO_C >= 0x570) || (defined(_MSC_VER) && _MSC_VER >= 1600) || (defined(__STDC__) && __STDC__ && defined(__STDC_VERSION__) && __STDC_VERSION__ >= 199901L) || (defined (__WATCOMC__) && (defined (_STDINT_H_INCLUDED) || __WATCOMC__ >= 1250)) || (defined(__GNUC__) && (__GNUC__ > 3 || defined(_STDINT_H) || defined(_STDINT_H_) || defined (__UINT_FAST64_TYPE__)) )) && !defined (_PSTDINT_H_INCLUDED) -#include -#define _PSTDINT_H_INCLUDED -# if defined(__GNUC__) && (defined(__x86_64__) || defined(__ppc64__)) && !(defined(__APPLE__) && defined(__MACH__)) -# ifndef PRINTF_INT64_MODIFIER -# define PRINTF_INT64_MODIFIER "l" -# endif -# ifndef PRINTF_INT32_MODIFIER -# define PRINTF_INT32_MODIFIER "" -# endif -# else -# ifndef PRINTF_INT64_MODIFIER -# define PRINTF_INT64_MODIFIER "ll" -# endif -# ifndef PRINTF_INT32_MODIFIER -# if (UINT_MAX == UINT32_MAX) -# define PRINTF_INT32_MODIFIER "" -# else -# define PRINTF_INT32_MODIFIER "l" -# endif -# endif -# endif -# ifndef PRINTF_INT16_MODIFIER -# define PRINTF_INT16_MODIFIER "h" -# endif -# ifndef PRINTF_INTMAX_MODIFIER -# define PRINTF_INTMAX_MODIFIER PRINTF_INT64_MODIFIER -# endif -# ifndef PRINTF_INT64_HEX_WIDTH -# define PRINTF_INT64_HEX_WIDTH "16" -# endif -# ifndef PRINTF_UINT64_HEX_WIDTH -# define PRINTF_UINT64_HEX_WIDTH "16" -# endif -# ifndef PRINTF_INT32_HEX_WIDTH -# define PRINTF_INT32_HEX_WIDTH "8" -# endif -# ifndef PRINTF_UINT32_HEX_WIDTH -# define PRINTF_UINT32_HEX_WIDTH "8" -# endif -# ifndef PRINTF_INT16_HEX_WIDTH -# define PRINTF_INT16_HEX_WIDTH "4" -# endif -# ifndef PRINTF_UINT16_HEX_WIDTH -# define PRINTF_UINT16_HEX_WIDTH "4" -# endif -# ifndef PRINTF_INT8_HEX_WIDTH -# define PRINTF_INT8_HEX_WIDTH "2" -# endif -# ifndef PRINTF_UINT8_HEX_WIDTH -# define PRINTF_UINT8_HEX_WIDTH "2" -# endif -# ifndef PRINTF_INT64_DEC_WIDTH -# define PRINTF_INT64_DEC_WIDTH "19" -# endif -# ifndef PRINTF_UINT64_DEC_WIDTH -# define PRINTF_UINT64_DEC_WIDTH "20" -# endif -# ifndef PRINTF_INT32_DEC_WIDTH -# define PRINTF_INT32_DEC_WIDTH "10" -# endif -# ifndef PRINTF_UINT32_DEC_WIDTH -# define PRINTF_UINT32_DEC_WIDTH "10" -# endif -# ifndef PRINTF_INT16_DEC_WIDTH -# define PRINTF_INT16_DEC_WIDTH "5" -# endif -# ifndef PRINTF_UINT16_DEC_WIDTH -# define PRINTF_UINT16_DEC_WIDTH "5" -# endif -# ifndef PRINTF_INT8_DEC_WIDTH -# define PRINTF_INT8_DEC_WIDTH "3" -# endif -# ifndef PRINTF_UINT8_DEC_WIDTH -# define PRINTF_UINT8_DEC_WIDTH "3" -# endif -# ifndef PRINTF_INTMAX_HEX_WIDTH -# define PRINTF_INTMAX_HEX_WIDTH PRINTF_UINT64_HEX_WIDTH -# endif -# ifndef PRINTF_UINTMAX_HEX_WIDTH -# define PRINTF_UINTMAX_HEX_WIDTH PRINTF_UINT64_HEX_WIDTH -# endif -# ifndef PRINTF_INTMAX_DEC_WIDTH -# define PRINTF_INTMAX_DEC_WIDTH PRINTF_UINT64_DEC_WIDTH -# endif -# ifndef PRINTF_UINTMAX_DEC_WIDTH -# define PRINTF_UINTMAX_DEC_WIDTH PRINTF_UINT64_DEC_WIDTH -# endif - -/* - * Something really weird is going on with Open Watcom. Just pull some of - * these duplicated definitions from Open Watcom's stdint.h file for now. - */ - -# if defined (__WATCOMC__) && __WATCOMC__ >= 1250 -# if !defined (INT64_C) -# define INT64_C(x) (x + (INT64_MAX - INT64_MAX)) -# endif -# if !defined (UINT64_C) -# define UINT64_C(x) (x + (UINT64_MAX - UINT64_MAX)) -# endif -# if !defined (INT32_C) -# define INT32_C(x) (x + (INT32_MAX - INT32_MAX)) -# endif -# if !defined (UINT32_C) -# define UINT32_C(x) (x + (UINT32_MAX - UINT32_MAX)) -# endif -# if !defined (INT16_C) -# define INT16_C(x) (x) -# endif -# if !defined (UINT16_C) -# define UINT16_C(x) (x) -# endif -# if !defined (INT8_C) -# define INT8_C(x) (x) -# endif -# if !defined (UINT8_C) -# define UINT8_C(x) (x) -# endif -# if !defined (UINT64_MAX) -# define UINT64_MAX 18446744073709551615ULL -# endif -# if !defined (INT64_MAX) -# define INT64_MAX 9223372036854775807LL -# endif -# if !defined (UINT32_MAX) -# define UINT32_MAX 4294967295UL -# endif -# if !defined (INT32_MAX) -# define INT32_MAX 2147483647L -# endif -# if !defined (INTMAX_MAX) -# define INTMAX_MAX INT64_MAX -# endif -# if !defined (INTMAX_MIN) -# define INTMAX_MIN INT64_MIN -# endif -# endif -#endif - -/* - * I have no idea what is the truly correct thing to do on older Solaris. - * From some online discussions, this seems to be what is being - * recommended. For people who actually are developing on older Solaris, - * what I would like to know is, does this define all of the relevant - * macros of a complete stdint.h? Remember, in pstdint.h 64 bit is - * considered optional. - */ - -#if (defined(__SUNPRO_C) && __SUNPRO_C >= 0x420) && !defined(_PSTDINT_H_INCLUDED) -#include -#define _PSTDINT_H_INCLUDED -#endif - -#ifndef _PSTDINT_H_INCLUDED -#define _PSTDINT_H_INCLUDED - -#ifndef SIZE_MAX -# define SIZE_MAX ((size_t)-1) -#endif - -/* - * Deduce the type assignments from limits.h under the assumption that - * integer sizes in bits are powers of 2, and follow the ANSI - * definitions. - */ - -#ifndef UINT8_MAX -# define UINT8_MAX 0xff -#endif -#if !defined(uint8_t) && !defined(_UINT8_T) && !defined(vxWorks) -# if (UCHAR_MAX == UINT8_MAX) || defined (S_SPLINT_S) - typedef unsigned char uint8_t; -# define UINT8_C(v) ((uint8_t) v) -# else -# error "Platform not supported" -# endif -#endif - -#ifndef INT8_MAX -# define INT8_MAX 0x7f -#endif -#ifndef INT8_MIN -# define INT8_MIN INT8_C(0x80) -#endif -#if !defined(int8_t) && !defined(_INT8_T) && !defined(vxWorks) -# if (SCHAR_MAX == INT8_MAX) || defined (S_SPLINT_S) - typedef signed char int8_t; -# define INT8_C(v) ((int8_t) v) -# else -# error "Platform not supported" -# endif -#endif - -#ifndef UINT16_MAX -# define UINT16_MAX 0xffff -#endif -#if !defined(uint16_t) && !defined(_UINT16_T) && !defined(vxWorks) -#if (UINT_MAX == UINT16_MAX) || defined (S_SPLINT_S) - typedef unsigned int uint16_t; -# ifndef PRINTF_INT16_MODIFIER -# define PRINTF_INT16_MODIFIER "" -# endif -# define UINT16_C(v) ((uint16_t) (v)) -#elif (USHRT_MAX == UINT16_MAX) - typedef unsigned short uint16_t; -# define UINT16_C(v) ((uint16_t) (v)) -# ifndef PRINTF_INT16_MODIFIER -# define PRINTF_INT16_MODIFIER "h" -# endif -#else -#error "Platform not supported" -#endif -#endif - -#ifndef INT16_MAX -# define INT16_MAX 0x7fff -#endif -#ifndef INT16_MIN -# define INT16_MIN INT16_C(0x8000) -#endif -#if !defined(int16_t) && !defined(_INT16_T) && !defined(vxWorks) -#if (INT_MAX == INT16_MAX) || defined (S_SPLINT_S) - typedef signed int int16_t; -# define INT16_C(v) ((int16_t) (v)) -# ifndef PRINTF_INT16_MODIFIER -# define PRINTF_INT16_MODIFIER "" -# endif -#elif (SHRT_MAX == INT16_MAX) - typedef signed short int16_t; -# define INT16_C(v) ((int16_t) (v)) -# ifndef PRINTF_INT16_MODIFIER -# define PRINTF_INT16_MODIFIER "h" -# endif -#else -#error "Platform not supported" -#endif -#endif - -#ifndef UINT32_MAX -# define UINT32_MAX (0xffffffffUL) -#endif -#if !defined(uint32_t) && !defined(_UINT32_T) && !defined(vxWorks) -#if (ULONG_MAX == UINT32_MAX) || defined (S_SPLINT_S) - typedef unsigned long uint32_t; -# define UINT32_C(v) v ## UL -# ifndef PRINTF_INT32_MODIFIER -# define PRINTF_INT32_MODIFIER "l" -# endif -#elif (UINT_MAX == UINT32_MAX) - typedef unsigned int uint32_t; -# ifndef PRINTF_INT32_MODIFIER -# define PRINTF_INT32_MODIFIER "" -# endif -# define UINT32_C(v) v ## U -#elif (USHRT_MAX == UINT32_MAX) - typedef unsigned short uint32_t; -# define UINT32_C(v) ((unsigned short) (v)) -# ifndef PRINTF_INT32_MODIFIER -# define PRINTF_INT32_MODIFIER "" -# endif -#else -#error "Platform not supported" -#endif -#endif - -#ifndef INT32_MAX -# define INT32_MAX (0x7fffffffL) -#endif -#ifndef INT32_MIN -# define INT32_MIN INT32_C(0x80000000) -#endif -#if !defined(int32_t) && !defined(_INT32_T) && !defined(vxWorks) -#if (LONG_MAX == INT32_MAX) || defined (S_SPLINT_S) - typedef signed long int32_t; -# define INT32_C(v) v ## L -# ifndef PRINTF_INT32_MODIFIER -# define PRINTF_INT32_MODIFIER "l" -# endif -#elif (INT_MAX == INT32_MAX) - typedef signed int int32_t; -# define INT32_C(v) v -# ifndef PRINTF_INT32_MODIFIER -# define PRINTF_INT32_MODIFIER "" -# endif -#elif (SHRT_MAX == INT32_MAX) - typedef signed short int32_t; -# define INT32_C(v) ((short) (v)) -# ifndef PRINTF_INT32_MODIFIER -# define PRINTF_INT32_MODIFIER "" -# endif -#else -#error "Platform not supported" -#endif -#endif - -/* - * The macro stdint_int64_defined is temporarily used to record - * whether or not 64 integer support is available. It must be - * defined for any 64 integer extensions for new platforms that are - * added. - */ - -#undef stdint_int64_defined -#if (defined(__STDC__) && defined(__STDC_VERSION__)) || defined (S_SPLINT_S) -# if (__STDC__ && __STDC_VERSION__ >= 199901L) || defined (S_SPLINT_S) -# define stdint_int64_defined - typedef long long int64_t; - typedef unsigned long long uint64_t; -# define UINT64_C(v) v ## ULL -# define INT64_C(v) v ## LL -# ifndef PRINTF_INT64_MODIFIER -# define PRINTF_INT64_MODIFIER "ll" -# endif -# endif -#endif - -#if !defined (stdint_int64_defined) -# if defined(__GNUC__) && !defined(vxWorks) -# define stdint_int64_defined - __extension__ typedef long long int64_t; - __extension__ typedef unsigned long long uint64_t; -# define UINT64_C(v) v ## ULL -# define INT64_C(v) v ## LL -# ifndef PRINTF_INT64_MODIFIER -# define PRINTF_INT64_MODIFIER "ll" -# endif -# elif defined(__MWERKS__) || defined (__SUNPRO_C) || defined (__SUNPRO_CC) || defined (__APPLE_CC__) || defined (_LONG_LONG) || defined (_CRAYC) || defined (S_SPLINT_S) -# define stdint_int64_defined - typedef long long int64_t; - typedef unsigned long long uint64_t; -# define UINT64_C(v) v ## ULL -# define INT64_C(v) v ## LL -# ifndef PRINTF_INT64_MODIFIER -# define PRINTF_INT64_MODIFIER "ll" -# endif -# elif (defined(__WATCOMC__) && defined(__WATCOM_INT64__)) || (defined(_MSC_VER) && _INTEGRAL_MAX_BITS >= 64) || (defined (__BORLANDC__) && __BORLANDC__ > 0x460) || defined (__alpha) || defined (__DECC) -# define stdint_int64_defined - typedef __int64 int64_t; - typedef unsigned __int64 uint64_t; -# define UINT64_C(v) v ## UI64 -# define INT64_C(v) v ## I64 -# ifndef PRINTF_INT64_MODIFIER -# define PRINTF_INT64_MODIFIER "I64" -# endif -# endif -#endif - -#if !defined (LONG_LONG_MAX) && defined (INT64_C) -# define LONG_LONG_MAX INT64_C (9223372036854775807) -#endif -#ifndef ULONG_LONG_MAX -# define ULONG_LONG_MAX UINT64_C (18446744073709551615) -#endif - -#if !defined (INT64_MAX) && defined (INT64_C) -# define INT64_MAX INT64_C (9223372036854775807) -#endif -#if !defined (INT64_MIN) && defined (INT64_C) -# define INT64_MIN INT64_C (-9223372036854775808) -#endif -#if !defined (UINT64_MAX) && defined (INT64_C) -# define UINT64_MAX UINT64_C (18446744073709551615) -#endif - -/* - * Width of hexadecimal for number field. - */ - -#ifndef PRINTF_INT64_HEX_WIDTH -# define PRINTF_INT64_HEX_WIDTH "16" -#endif -#ifndef PRINTF_INT32_HEX_WIDTH -# define PRINTF_INT32_HEX_WIDTH "8" -#endif -#ifndef PRINTF_INT16_HEX_WIDTH -# define PRINTF_INT16_HEX_WIDTH "4" -#endif -#ifndef PRINTF_INT8_HEX_WIDTH -# define PRINTF_INT8_HEX_WIDTH "2" -#endif -#ifndef PRINTF_INT64_DEC_WIDTH -# define PRINTF_INT64_DEC_WIDTH "19" -#endif -#ifndef PRINTF_INT32_DEC_WIDTH -# define PRINTF_INT32_DEC_WIDTH "10" -#endif -#ifndef PRINTF_INT16_DEC_WIDTH -# define PRINTF_INT16_DEC_WIDTH "5" -#endif -#ifndef PRINTF_INT8_DEC_WIDTH -# define PRINTF_INT8_DEC_WIDTH "3" -#endif -#ifndef PRINTF_UINT64_DEC_WIDTH -# define PRINTF_UINT64_DEC_WIDTH "20" -#endif -#ifndef PRINTF_UINT32_DEC_WIDTH -# define PRINTF_UINT32_DEC_WIDTH "10" -#endif -#ifndef PRINTF_UINT16_DEC_WIDTH -# define PRINTF_UINT16_DEC_WIDTH "5" -#endif -#ifndef PRINTF_UINT8_DEC_WIDTH -# define PRINTF_UINT8_DEC_WIDTH "3" -#endif - -/* - * Ok, lets not worry about 128 bit integers for now. Moore's law says - * we don't need to worry about that until about 2040 at which point - * we'll have bigger things to worry about. - */ - -#ifdef stdint_int64_defined - typedef int64_t intmax_t; - typedef uint64_t uintmax_t; -# define INTMAX_MAX INT64_MAX -# define INTMAX_MIN INT64_MIN -# define UINTMAX_MAX UINT64_MAX -# define UINTMAX_C(v) UINT64_C(v) -# define INTMAX_C(v) INT64_C(v) -# ifndef PRINTF_INTMAX_MODIFIER -# define PRINTF_INTMAX_MODIFIER PRINTF_INT64_MODIFIER -# endif -# ifndef PRINTF_INTMAX_HEX_WIDTH -# define PRINTF_INTMAX_HEX_WIDTH PRINTF_INT64_HEX_WIDTH -# endif -# ifndef PRINTF_INTMAX_DEC_WIDTH -# define PRINTF_INTMAX_DEC_WIDTH PRINTF_INT64_DEC_WIDTH -# endif -#else - typedef int32_t intmax_t; - typedef uint32_t uintmax_t; -# define INTMAX_MAX INT32_MAX -# define UINTMAX_MAX UINT32_MAX -# define UINTMAX_C(v) UINT32_C(v) -# define INTMAX_C(v) INT32_C(v) -# ifndef PRINTF_INTMAX_MODIFIER -# define PRINTF_INTMAX_MODIFIER PRINTF_INT32_MODIFIER -# endif -# ifndef PRINTF_INTMAX_HEX_WIDTH -# define PRINTF_INTMAX_HEX_WIDTH PRINTF_INT32_HEX_WIDTH -# endif -# ifndef PRINTF_INTMAX_DEC_WIDTH -# define PRINTF_INTMAX_DEC_WIDTH PRINTF_INT32_DEC_WIDTH -# endif -#endif - -/* - * Because this file currently only supports platforms which have - * precise powers of 2 as bit sizes for the default integers, the - * least definitions are all trivial. Its possible that a future - * version of this file could have different definitions. - */ - -#ifndef stdint_least_defined - typedef int8_t int_least8_t; - typedef uint8_t uint_least8_t; - typedef int16_t int_least16_t; - typedef uint16_t uint_least16_t; - typedef int32_t int_least32_t; - typedef uint32_t uint_least32_t; -# define PRINTF_LEAST32_MODIFIER PRINTF_INT32_MODIFIER -# define PRINTF_LEAST16_MODIFIER PRINTF_INT16_MODIFIER -# define UINT_LEAST8_MAX UINT8_MAX -# define INT_LEAST8_MAX INT8_MAX -# define UINT_LEAST16_MAX UINT16_MAX -# define INT_LEAST16_MAX INT16_MAX -# define UINT_LEAST32_MAX UINT32_MAX -# define INT_LEAST32_MAX INT32_MAX -# define INT_LEAST8_MIN INT8_MIN -# define INT_LEAST16_MIN INT16_MIN -# define INT_LEAST32_MIN INT32_MIN -# ifdef stdint_int64_defined - typedef int64_t int_least64_t; - typedef uint64_t uint_least64_t; -# define PRINTF_LEAST64_MODIFIER PRINTF_INT64_MODIFIER -# define UINT_LEAST64_MAX UINT64_MAX -# define INT_LEAST64_MAX INT64_MAX -# define INT_LEAST64_MIN INT64_MIN -# endif -#endif -#undef stdint_least_defined - -/* - * The ANSI C committee has defined *int*_fast*_t types as well. This, - * of course, defies rationality -- you can't know what will be fast - * just from the type itself. Even for a given architecture, compatible - * implementations might have different performance characteristics. - * Developers are warned to stay away from these types when using this - * or any other stdint.h. - */ - -typedef int_least8_t int_fast8_t; -typedef uint_least8_t uint_fast8_t; -typedef int_least16_t int_fast16_t; -typedef uint_least16_t uint_fast16_t; -typedef int_least32_t int_fast32_t; -typedef uint_least32_t uint_fast32_t; -#define UINT_FAST8_MAX UINT_LEAST8_MAX -#define INT_FAST8_MAX INT_LEAST8_MAX -#define UINT_FAST16_MAX UINT_LEAST16_MAX -#define INT_FAST16_MAX INT_LEAST16_MAX -#define UINT_FAST32_MAX UINT_LEAST32_MAX -#define INT_FAST32_MAX INT_LEAST32_MAX -#define INT_FAST8_MIN INT_LEAST8_MIN -#define INT_FAST16_MIN INT_LEAST16_MIN -#define INT_FAST32_MIN INT_LEAST32_MIN -#ifdef stdint_int64_defined - typedef int_least64_t int_fast64_t; - typedef uint_least64_t uint_fast64_t; -# define UINT_FAST64_MAX UINT_LEAST64_MAX -# define INT_FAST64_MAX INT_LEAST64_MAX -# define INT_FAST64_MIN INT_LEAST64_MIN -#endif - -#undef stdint_int64_defined - -/* - * Whatever piecemeal, per compiler thing we can do about the wchar_t - * type limits. - */ - -#if defined(__WATCOMC__) || defined(_MSC_VER) || defined (__GNUC__) && !defined(vxWorks) -# include -# ifndef WCHAR_MIN -# define WCHAR_MIN 0 -# endif -# ifndef WCHAR_MAX -# define WCHAR_MAX ((wchar_t)-1) -# endif -#endif - -/* - * Whatever piecemeal, per compiler/platform thing we can do about the - * (u)intptr_t types and limits. - */ - -#if (defined (_MSC_VER) && defined (_UINTPTR_T_DEFINED)) || defined (_UINTPTR_T) -# define STDINT_H_UINTPTR_T_DEFINED -#endif - -#ifndef STDINT_H_UINTPTR_T_DEFINED -# if defined (__alpha__) || defined (__ia64__) || defined (__x86_64__) || defined (_WIN64) || defined (__ppc64__) -# define stdint_intptr_bits 64 -# elif defined (__WATCOMC__) || defined (__TURBOC__) -# if defined(__TINY__) || defined(__SMALL__) || defined(__MEDIUM__) -# define stdint_intptr_bits 16 -# else -# define stdint_intptr_bits 32 -# endif -# elif defined (__i386__) || defined (_WIN32) || defined (WIN32) || defined (__ppc64__) -# define stdint_intptr_bits 32 -# elif defined (__INTEL_COMPILER) -/* TODO -- what did Intel do about x86-64? */ -# else -/* #error "This platform might not be supported yet" */ -# endif - -# ifdef stdint_intptr_bits -# define stdint_intptr_glue3_i(a,b,c) a##b##c -# define stdint_intptr_glue3(a,b,c) stdint_intptr_glue3_i(a,b,c) -# ifndef PRINTF_INTPTR_MODIFIER -# define PRINTF_INTPTR_MODIFIER stdint_intptr_glue3(PRINTF_INT,stdint_intptr_bits,_MODIFIER) -# endif -# ifndef PTRDIFF_MAX -# define PTRDIFF_MAX stdint_intptr_glue3(INT,stdint_intptr_bits,_MAX) -# endif -# ifndef PTRDIFF_MIN -# define PTRDIFF_MIN stdint_intptr_glue3(INT,stdint_intptr_bits,_MIN) -# endif -# ifndef UINTPTR_MAX -# define UINTPTR_MAX stdint_intptr_glue3(UINT,stdint_intptr_bits,_MAX) -# endif -# ifndef INTPTR_MAX -# define INTPTR_MAX stdint_intptr_glue3(INT,stdint_intptr_bits,_MAX) -# endif -# ifndef INTPTR_MIN -# define INTPTR_MIN stdint_intptr_glue3(INT,stdint_intptr_bits,_MIN) -# endif -# ifndef INTPTR_C -# define INTPTR_C(x) stdint_intptr_glue3(INT,stdint_intptr_bits,_C)(x) -# endif -# ifndef UINTPTR_C -# define UINTPTR_C(x) stdint_intptr_glue3(UINT,stdint_intptr_bits,_C)(x) -# endif - typedef stdint_intptr_glue3(uint,stdint_intptr_bits,_t) uintptr_t; - typedef stdint_intptr_glue3( int,stdint_intptr_bits,_t) intptr_t; -# else -/* TODO -- This following is likely wrong for some platforms, and does - nothing for the definition of uintptr_t. */ - typedef ptrdiff_t intptr_t; -# endif -# define STDINT_H_UINTPTR_T_DEFINED -#endif - -/* - * Assumes sig_atomic_t is signed and we have a 2s complement machine. - */ - -#ifndef SIG_ATOMIC_MAX -# define SIG_ATOMIC_MAX ((((sig_atomic_t) 1) << (sizeof (sig_atomic_t)*CHAR_BIT-1)) - 1) -#endif - -#endif - -#if defined (__TEST_PSTDINT_FOR_CORRECTNESS) - -/* - * Please compile with the maximum warning settings to make sure macros are - * not defined more than once. - */ - -#include -#include -#include - -#define glue3_aux(x,y,z) x ## y ## z -#define glue3(x,y,z) glue3_aux(x,y,z) - -#define DECLU(bits) glue3(uint,bits,_t) glue3(u,bits,) = glue3(UINT,bits,_C) (0); -#define DECLI(bits) glue3(int,bits,_t) glue3(i,bits,) = glue3(INT,bits,_C) (0); - -#define DECL(us,bits) glue3(DECL,us,) (bits) - -#define TESTUMAX(bits) glue3(u,bits,) = ~glue3(u,bits,); if (glue3(UINT,bits,_MAX) != glue3(u,bits,)) printf ("Something wrong with UINT%d_MAX\n", bits) - -#define REPORTERROR(msg) { err_n++; if (err_first <= 0) err_first = __LINE__; printf msg; } - -#define X_SIZE_MAX ((size_t)-1) - -int main () { - int err_n = 0; - int err_first = 0; - DECL(I,8) - DECL(U,8) - DECL(I,16) - DECL(U,16) - DECL(I,32) - DECL(U,32) -#ifdef INT64_MAX - DECL(I,64) - DECL(U,64) -#endif - intmax_t imax = INTMAX_C(0); - uintmax_t umax = UINTMAX_C(0); - char str0[256], str1[256]; - - sprintf (str0, "%" PRINTF_INT32_MODIFIER "d", INT32_C(2147483647)); - if (0 != strcmp (str0, "2147483647")) REPORTERROR (("Something wrong with PRINTF_INT32_MODIFIER : %s\n", str0)); - if (atoi(PRINTF_INT32_DEC_WIDTH) != (int) strlen(str0)) REPORTERROR (("Something wrong with PRINTF_INT32_DEC_WIDTH : %s\n", PRINTF_INT32_DEC_WIDTH)); - sprintf (str0, "%" PRINTF_INT32_MODIFIER "u", UINT32_C(4294967295)); - if (0 != strcmp (str0, "4294967295")) REPORTERROR (("Something wrong with PRINTF_INT32_MODIFIER : %s\n", str0)); - if (atoi(PRINTF_UINT32_DEC_WIDTH) != (int) strlen(str0)) REPORTERROR (("Something wrong with PRINTF_UINT32_DEC_WIDTH : %s\n", PRINTF_UINT32_DEC_WIDTH)); -#ifdef INT64_MAX - sprintf (str1, "%" PRINTF_INT64_MODIFIER "d", INT64_C(9223372036854775807)); - if (0 != strcmp (str1, "9223372036854775807")) REPORTERROR (("Something wrong with PRINTF_INT32_MODIFIER : %s\n", str1)); - if (atoi(PRINTF_INT64_DEC_WIDTH) != (int) strlen(str1)) REPORTERROR (("Something wrong with PRINTF_INT64_DEC_WIDTH : %s, %d\n", PRINTF_INT64_DEC_WIDTH, (int) strlen(str1))); - sprintf (str1, "%" PRINTF_INT64_MODIFIER "u", UINT64_C(18446744073709550591)); - if (0 != strcmp (str1, "18446744073709550591")) REPORTERROR (("Something wrong with PRINTF_INT32_MODIFIER : %s\n", str1)); - if (atoi(PRINTF_UINT64_DEC_WIDTH) != (int) strlen(str1)) REPORTERROR (("Something wrong with PRINTF_UINT64_DEC_WIDTH : %s, %d\n", PRINTF_UINT64_DEC_WIDTH, (int) strlen(str1))); -#endif - - sprintf (str0, "%d %x\n", 0, ~0); - - sprintf (str1, "%d %x\n", i8, ~0); - if (0 != strcmp (str0, str1)) REPORTERROR (("Something wrong with i8 : %s\n", str1)); - sprintf (str1, "%u %x\n", u8, ~0); - if (0 != strcmp (str0, str1)) REPORTERROR (("Something wrong with u8 : %s\n", str1)); - sprintf (str1, "%d %x\n", i16, ~0); - if (0 != strcmp (str0, str1)) REPORTERROR (("Something wrong with i16 : %s\n", str1)); - sprintf (str1, "%u %x\n", u16, ~0); - if (0 != strcmp (str0, str1)) REPORTERROR (("Something wrong with u16 : %s\n", str1)); - sprintf (str1, "%" PRINTF_INT32_MODIFIER "d %x\n", i32, ~0); - if (0 != strcmp (str0, str1)) REPORTERROR (("Something wrong with i32 : %s\n", str1)); - sprintf (str1, "%" PRINTF_INT32_MODIFIER "u %x\n", u32, ~0); - if (0 != strcmp (str0, str1)) REPORTERROR (("Something wrong with u32 : %s\n", str1)); -#ifdef INT64_MAX - sprintf (str1, "%" PRINTF_INT64_MODIFIER "d %x\n", i64, ~0); - if (0 != strcmp (str0, str1)) REPORTERROR (("Something wrong with i64 : %s\n", str1)); -#endif - sprintf (str1, "%" PRINTF_INTMAX_MODIFIER "d %x\n", imax, ~0); - if (0 != strcmp (str0, str1)) REPORTERROR (("Something wrong with imax : %s\n", str1)); - sprintf (str1, "%" PRINTF_INTMAX_MODIFIER "u %x\n", umax, ~0); - if (0 != strcmp (str0, str1)) REPORTERROR (("Something wrong with umax : %s\n", str1)); - - TESTUMAX(8); - TESTUMAX(16); - TESTUMAX(32); -#ifdef INT64_MAX - TESTUMAX(64); -#endif - -#define STR(v) #v -#define Q(v) printf ("sizeof " STR(v) " = %u\n", (unsigned) sizeof (v)); - if (err_n) { - printf ("pstdint.h is not correct. Please use sizes below to correct it:\n"); - } - - Q(int) - Q(unsigned) - Q(long int) - Q(short int) - Q(int8_t) - Q(int16_t) - Q(int32_t) -#ifdef INT64_MAX - Q(int64_t) -#endif - -#if UINT_MAX < X_SIZE_MAX - printf ("UINT_MAX < X_SIZE_MAX\n"); -#else - printf ("UINT_MAX >= X_SIZE_MAX\n"); -#endif - printf ("%" PRINTF_INT64_MODIFIER "u vs %" PRINTF_INT64_MODIFIER "u\n", UINT_MAX, X_SIZE_MAX); - - return EXIT_SUCCESS; -} - -#endif diff --git a/tcod_sys/libtcod/include/howto.hpp b/tcod_sys/libtcod/include/howto.hpp deleted file mode 100644 index afc32c11d..000000000 --- a/tcod_sys/libtcod/include/howto.hpp +++ /dev/null @@ -1,155 +0,0 @@ -/* -* libtcod -* Copyright (c) 2008-2018 Jice & Mingos & rmtew -* All rights reserved. -* -* Redistribution and use in source and binary forms, with or without -* modification, are permitted provided that the following conditions are met: -* * Redistributions of source code must retain the above copyright -* notice, this list of conditions and the following disclaimer. -* * Redistributions in binary form must reproduce the above copyright -* notice, this list of conditions and the following disclaimer in the -* documentation and/or other materials provided with the distribution. -* * The name of Jice or Mingos may not be used to endorse or promote -* products derived from this software without specific prior written -* permission. -* -* THIS SOFTWARE IS PROVIDED BY JICE, MINGOS AND RMTEW ``AS IS'' AND ANY -* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED -* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE -* DISCLAIMED. IN NO EVENT SHALL JICE, MINGOS OR RMTEW BE LIABLE FOR ANY -* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES -* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; -* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND -* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS -* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. -*/ -/* This file contains no code. It's only an input for doctcod */ - -/** - @PageName compile_libtcod - @PageCategory Howtos - @PageTitle How to compile libtcod - @PageDesc This page contains howtos about how to get the latest libtcod source code and compile it. -*/ - -/** - @PageName compile_libtcod_mingw - @PageFather compile_libtcod - @PageTitle On Windows with Mingw - @PageDesc

Mingw installation

- Download the latest version of Mingw from this address : - http://sourceforge.net/projects/mingw/files/ - - The latest installer should be at the top of the page with a name starting with mingw-get-inst.. - - - - Download and run the program. Follow the installation steps. Be sure to check the "Use pre-packaged repository" option : - - - - The latest version might be less stable and might not work with a precompiled libtcod. - - When you arrive at the component selection screen, check C compiler, C++ compiler and MSys system : - - - - Keep on following the installation steps until the installation is finished. Now you have a "Mingw Shell" program in your start menu. This is the terminal you will use to compile and debug your game. - -

TortoiseHg installation

- In order to get the latest version of libtcod, you need a mercurial client. - Go to the download page and grab the client corresponding to your version of Windows : - http://tortoisehg.bitbucket.org/download/index.html - - Follow the installation wizard using the default configuration. Once the installation is finished, restart your computer. - - Now you should be able to use mercurial (hg) from the Mingw Shell. To check if everything is ok, start a shell and type "which hg" : - - - -

Getting libtcod source code

- In Mingw Shell, type : -
hg clone https://bitbucket.org/jice/libtcod
- - This might take some time so grab a beer. Once it's finished, a libtcod directory has been created. - You can check the documentation (the same you're currently reading) in libtcod/doc/index2.html. - The headers are in libtcod/include. - The source code in libtcod/src. - -

Compiling libtcod

- Go in libtcod's main directory : -
cd libtcod
- And start the compilation : -
make -f makefiles/makefile-mingw
- The compilation make take a few seconds depending on your CPU speed. Once it's finished, compile the samples : -
make -f makefiles/makefile-samples-mingw
- Check that everything is ok by running the samples : -
./samples_cpp
-*/ - -/** - @PageName compile_libtcod_linux - @PageFather compile_libtcod - @PageTitle On Linux - @PageDesc

Linux compilation

- On a freshly installed Ubuntu : - Get the tools : -
sudo apt-get install gcc g++ make upx electric-fence libsdl1.2-dev mercurial
- - Get the latest sources : -
hg clone https://bitbucket.org/jice/libtcod
- - Compile the library : -
cd libtcod/
-
make -f makefiles/makefile-linux clean all
- - Compile the samples : -
make -f makefiles/makefile-samples-linux
- - Enjoy : -
./samples_cpp
-*/ - -/** - @PageName compile_libtcod_codelite - @PageFather compile_libtcod - @PageTitle Using CodeLite - @PageDesc TODO -*/ - -/** - @PageName compile_libtcod_haiku - @PageFather compile_libtcod - @PageTitle On Haiku - @PageDesc TODO -*/ - -/** - @PageName start_project - @PageCategory Howtos - @PageTitle How to start a project - @PageDesc This page contains howtos about how to create a project from scratch -*/ - -/** - @PageName start_mingw - @PageFather start_project - @PageTitle On Windows with Mingw - @PageDesc TODO -*/ - -/** - @PageName start_linux - @PageFather start_project - @PageTitle On Linux - @PageDesc TODO -*/ - -/** - @PageName start_codelite - @PageFather start_project - @PageTitle Using CodeLite - @PageDesc TODO -*/ diff --git a/tcod_sys/libtcod/src/fov_c.c b/tcod_sys/libtcod/src/fov_c.c deleted file mode 100644 index 553e8ab29..000000000 --- a/tcod_sys/libtcod/src/fov_c.c +++ /dev/null @@ -1,150 +0,0 @@ -/* -* libtcod -* Copyright (c) 2008-2018 Jice & Mingos & rmtew -* All rights reserved. -* -* Redistribution and use in source and binary forms, with or without -* modification, are permitted provided that the following conditions are met: -* * Redistributions of source code must retain the above copyright -* notice, this list of conditions and the following disclaimer. -* * Redistributions in binary form must reproduce the above copyright -* notice, this list of conditions and the following disclaimer in the -* documentation and/or other materials provided with the distribution. -* * The name of Jice or Mingos may not be used to endorse or promote -* products derived from this software without specific prior written -* permission. -* -* THIS SOFTWARE IS PROVIDED BY JICE, MINGOS AND RMTEW ``AS IS'' AND ANY -* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED -* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE -* DISCLAIMED. IN NO EVENT SHALL JICE, MINGOS OR RMTEW BE LIABLE FOR ANY -* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES -* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; -* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND -* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS -* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. -*/ -#include - -#include -#include - -#include - -TCOD_map_t TCOD_map_new(int width, int height) { - map_t *map=NULL; - TCOD_IFNOT(width > 0 && height > 0) return NULL; - map=(map_t *)calloc(sizeof(map_t),1); - map->width=width; - map->height=height; - map->nbcells=width*height; - map->cells=(cell_t *)calloc(sizeof(cell_t),map->nbcells); - return map; -} - -void TCOD_map_copy(TCOD_map_t source, TCOD_map_t dest) { - map_t *source_int = (map_t *)source; - map_t *dest_int = (map_t *)dest; - TCOD_IFNOT(source != NULL && dest != NULL) return; - if ( dest_int->nbcells != source_int->nbcells ) { - free(dest_int->cells); - dest_int->cells=(cell_t *)malloc(sizeof(cell_t)*dest_int->nbcells); - } - dest_int->width=source_int->width; - dest_int->height=source_int->height; - dest_int->nbcells=source_int->nbcells; - memcpy(dest_int->cells, source_int->cells, sizeof(cell_t) * source_int->nbcells); -} - -void TCOD_map_clear(TCOD_map_t map, bool transparent, bool walkable) { - int i; - map_t *m = (map_t *)map; - cell_t *cell; - TCOD_IFNOT(map != NULL) return; - cell=m->cells; - for (i = 0; i < m->nbcells; i++) { - cell->transparent = transparent; - cell->walkable = walkable; - cell->fov = 0; - cell++; - } -} - -void TCOD_map_set_properties(TCOD_map_t map, int x, int y, bool is_transparent, bool is_walkable) { - map_t *m = (map_t *)map; - TCOD_IFNOT(map != NULL) return; - TCOD_IFNOT((unsigned)x < (unsigned)m->width && (unsigned)y < (unsigned)m->height) return; - m->cells[x+y*m->width].transparent=is_transparent; - m->cells[x+y*m->width].walkable=is_walkable; -} - -void TCOD_map_delete(TCOD_map_t map) { - map_t *m = (map_t *)map; - TCOD_IFNOT(map != NULL) return; - free(m->cells); - free(m); -} - -void TCOD_map_compute_fov(TCOD_map_t map, int player_x, int player_y, int max_radius, bool light_walls, TCOD_fov_algorithm_t algo) { - TCOD_IFNOT(map != NULL) return; - switch(algo) { - case FOV_BASIC : TCOD_map_compute_fov_circular_raycasting(map,player_x,player_y,max_radius,light_walls); break; - case FOV_DIAMOND : TCOD_map_compute_fov_diamond_raycasting(map,player_x,player_y,max_radius,light_walls); break; - case FOV_SHADOW : TCOD_map_compute_fov_recursive_shadowcasting(map,player_x,player_y,max_radius,light_walls); break; - case FOV_PERMISSIVE_0 : - case FOV_PERMISSIVE_1 : - case FOV_PERMISSIVE_2 : - case FOV_PERMISSIVE_3 : - case FOV_PERMISSIVE_4 : - case FOV_PERMISSIVE_5 : - case FOV_PERMISSIVE_6 : - case FOV_PERMISSIVE_7 : - case FOV_PERMISSIVE_8 : - TCOD_map_compute_fov_permissive2(map,player_x,player_y,max_radius,light_walls, algo-FOV_PERMISSIVE_0); - break; - case FOV_RESTRICTIVE : TCOD_map_compute_fov_restrictive_shadowcasting(map,player_x,player_y,max_radius,light_walls); break; - default:break; - } -} - -bool TCOD_map_is_in_fov(TCOD_map_t map, int x, int y) { - map_t *m = (map_t *)map; - TCOD_IFNOT(map != NULL && (unsigned)x < (unsigned)m->width && (unsigned)y < (unsigned)m->height) return false; - return m->cells[x+y*m->width].fov == 1; -} - -void TCOD_map_set_in_fov(TCOD_map_t map, int x, int y, bool fov) { - map_t *m = (map_t *)map; - TCOD_IFNOT(map != NULL && (unsigned)x < (unsigned)m->width && (unsigned)y < (unsigned)m->height) return; - m->cells[x+y*m->width].fov = fov ? 1:0; -} - -bool TCOD_map_is_transparent(TCOD_map_t map, int x, int y) { - map_t *m = (map_t *)map; - TCOD_IFNOT(map != NULL && (unsigned)x < (unsigned)m->width && (unsigned)y < (unsigned)m->height) return false; - return m->cells[x+y*m->width].transparent; -} - -bool TCOD_map_is_walkable(TCOD_map_t map, int x, int y) { - map_t *m = (map_t *)map; - TCOD_IFNOT(map != NULL && (unsigned)x < (unsigned)m->width && (unsigned)y < (unsigned)m->height) return false; - return m->cells[x+y*m->width].walkable; -} -int TCOD_map_get_width(TCOD_map_t map) { - map_t *m = (map_t *)map; - TCOD_IFNOT(map != NULL) return 0; - return m->width; -} - -int TCOD_map_get_height(TCOD_map_t map) { - map_t *m = (map_t *)map; - TCOD_IFNOT(map != NULL) return 0; - return m->height; -} - -int TCOD_map_get_nb_cells(TCOD_map_t map) { - map_t *m = (map_t *)map; - TCOD_IFNOT(map != NULL) return 0; - return m->nbcells; -} diff --git a/tcod_sys/libtcod/src/bresenham.cpp b/tcod_sys/libtcod/src/libtcod/bresenham.cpp similarity index 96% rename from tcod_sys/libtcod/src/bresenham.cpp rename to tcod_sys/libtcod/src/libtcod/bresenham.cpp index 7ec503f0d..358220a70 100644 --- a/tcod_sys/libtcod/src/bresenham.cpp +++ b/tcod_sys/libtcod/src/libtcod/bresenham.cpp @@ -1,49 +1,49 @@ -/* -* libtcod -* Copyright (c) 2008-2018 Jice & Mingos & rmtew -* All rights reserved. -* -* Redistribution and use in source and binary forms, with or without -* modification, are permitted provided that the following conditions are met: -* * Redistributions of source code must retain the above copyright -* notice, this list of conditions and the following disclaimer. -* * Redistributions in binary form must reproduce the above copyright -* notice, this list of conditions and the following disclaimer in the -* documentation and/or other materials provided with the distribution. -* * The name of Jice or Mingos may not be used to endorse or promote -* products derived from this software without specific prior written -* permission. -* -* THIS SOFTWARE IS PROVIDED BY JICE, MINGOS AND RMTEW ``AS IS'' AND ANY -* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED -* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE -* DISCLAIMED. IN NO EVENT SHALL JICE, MINGOS OR RMTEW BE LIABLE FOR ANY -* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES -* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; -* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND -* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS -* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. -*/ -#include - -// ********** bresenham line drawing ********** -void TCODLine::init(int xFrom, int yFrom, int xTo, int yTo) { - TCOD_line_init(xFrom,yFrom,xTo,yTo); -} - -bool TCODLine::step(int *xCur, int *yCur) { - return TCOD_line_step(xCur,yCur) != 0; -} - -static TCODLineListener *line_listener=NULL; - -// C to C++ bridge -extern "C" bool internalListener(int x,int y) { - return line_listener->putPoint(x,y) ? 1 : 0; -} - -bool TCODLine::line(int xFrom, int yFrom, int xTo, int yTo, TCODLineListener *plistener) { - line_listener=plistener; - return TCOD_line(xFrom,yFrom,xTo,yTo,internalListener) != 0; -} +/* +* libtcod +* Copyright (c) 2008-2018 Jice & Mingos & rmtew +* All rights reserved. +* +* Redistribution and use in source and binary forms, with or without +* modification, are permitted provided that the following conditions are met: +* * Redistributions of source code must retain the above copyright +* notice, this list of conditions and the following disclaimer. +* * Redistributions in binary form must reproduce the above copyright +* notice, this list of conditions and the following disclaimer in the +* documentation and/or other materials provided with the distribution. +* * The name of Jice or Mingos may not be used to endorse or promote +* products derived from this software without specific prior written +* permission. +* +* THIS SOFTWARE IS PROVIDED BY JICE, MINGOS AND RMTEW ``AS IS'' AND ANY +* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED +* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE +* DISCLAIMED. IN NO EVENT SHALL JICE, MINGOS OR RMTEW BE LIABLE FOR ANY +* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES +* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; +* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND +* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS +* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +*/ +#include "bresenham.hpp" + +// ********** bresenham line drawing ********** +void TCODLine::init(int xFrom, int yFrom, int xTo, int yTo) { + TCOD_line_init(xFrom,yFrom,xTo,yTo); +} + +bool TCODLine::step(int *xCur, int *yCur) { + return TCOD_line_step(xCur,yCur) != 0; +} + +static TCODLineListener *line_listener=NULL; + +// C to C++ bridge +extern "C" bool internalListener(int x,int y) { + return line_listener->putPoint(x,y) ? 1 : 0; +} + +bool TCODLine::line(int xFrom, int yFrom, int xTo, int yTo, TCODLineListener *plistener) { + line_listener=plistener; + return TCOD_line(xFrom,yFrom,xTo,yTo,internalListener) != 0; +} diff --git a/tcod_sys/libtcod/include/bresenham.h b/tcod_sys/libtcod/src/libtcod/bresenham.h similarity index 92% rename from tcod_sys/libtcod/include/bresenham.h rename to tcod_sys/libtcod/src/libtcod/bresenham.h index c21200ffa..7b8e9b313 100644 --- a/tcod_sys/libtcod/include/bresenham.h +++ b/tcod_sys/libtcod/src/libtcod/bresenham.h @@ -28,7 +28,7 @@ #ifndef _TCOD_BRESENHAM_H #define _TCOD_BRESENHAM_H -#include "libtcod_portability.h" +#include "portability.h" #ifdef __cplusplus extern "C" { @@ -46,10 +46,11 @@ extern "C" { */ typedef bool (*TCOD_line_listener_t) (int x, int y); -TCOD_DEPRECATED TCODLIB_API +TCODLIB_API TCOD_DEPRECATED( + "This function is not reentrant. Use TCOD_line_init_mt instead.") void TCOD_line_init(int xFrom, int yFrom, int xTo, int yTo); -TCOD_DEPRECATED TCODLIB_API +TCODLIB_API TCOD_DEPRECATED("This function is not reentrant.") bool TCOD_line_step(int *xCur, int *yCur); /* advance one step. returns true if we reach destination */ /* atomic callback function. Stops when the callback returns false */ @@ -72,7 +73,7 @@ typedef struct { TCODLIB_API void TCOD_line_init_mt(int xFrom, int yFrom, int xTo, int yTo, TCOD_bresenham_data_t *data); TCODLIB_API bool TCOD_line_step_mt(int *xCur, int *yCur, TCOD_bresenham_data_t *data); -TCOD_DEPRECATED +TCOD_DEPRECATED("Use TCOD_line instead.") TCODLIB_API bool TCOD_line_mt(int xFrom, int yFrom, int xTo, int yTo, TCOD_line_listener_t listener, TCOD_bresenham_data_t *data); #ifdef __cplusplus } diff --git a/tcod_sys/libtcod/include/bresenham.hpp b/tcod_sys/libtcod/src/libtcod/bresenham.hpp similarity index 100% rename from tcod_sys/libtcod/include/bresenham.hpp rename to tcod_sys/libtcod/src/libtcod/bresenham.hpp diff --git a/tcod_sys/libtcod/src/bresenham_c.c b/tcod_sys/libtcod/src/libtcod/bresenham_c.c similarity index 96% rename from tcod_sys/libtcod/src/bresenham_c.c rename to tcod_sys/libtcod/src/libtcod/bresenham_c.c index cc3fbde21..41a66a4d3 100644 --- a/tcod_sys/libtcod/src/bresenham_c.c +++ b/tcod_sys/libtcod/src/libtcod/bresenham_c.c @@ -1,189 +1,189 @@ -/* -* libtcod -* Copyright (c) 2008-2018 Jice & Mingos & rmtew -* All rights reserved. -* -* Redistribution and use in source and binary forms, with or without -* modification, are permitted provided that the following conditions are met: -* * Redistributions of source code must retain the above copyright -* notice, this list of conditions and the following disclaimer. -* * Redistributions in binary form must reproduce the above copyright -* notice, this list of conditions and the following disclaimer in the -* documentation and/or other materials provided with the distribution. -* * The name of Jice or Mingos may not be used to endorse or promote -* products derived from this software without specific prior written -* permission. -* -* THIS SOFTWARE IS PROVIDED BY JICE, MINGOS AND RMTEW ``AS IS'' AND ANY -* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED -* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE -* DISCLAIMED. IN NO EVENT SHALL JICE, MINGOS OR RMTEW BE LIABLE FOR ANY -* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES -* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; -* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND -* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS -* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. -*/ -#include -/** - * \file bresenham_c.c - * \brief bresenham line drawing - */ -/* This static variable is deprecated since 1.6 */ -static TCOD_bresenham_data_t bresenham_data; -/** - * \brief Initialize a TCOD_bresenham_data_t struct. - * - * \param xFrom The starting x position. - * \param yFrom The starting y position. - * \param xTo The ending x position. - * \param yTo The ending y position. - * \param data Pointer to a TCOD_bresenham_data_t struct. - * - * After calling this function you use TCOD_line_step_mt to iterate - * over the individual points on the line. - */ -void TCOD_line_init_mt(int xFrom, int yFrom, int xTo, int yTo, TCOD_bresenham_data_t *data) { - data->origx=xFrom; - data->origy=yFrom; - data->destx=xTo; - data->desty=yTo; - data->deltax=xTo - xFrom; - data->deltay=yTo - yFrom; - if ( data->deltax > 0 ) { - data->stepx=1; - } else if ( data->deltax < 0 ){ - data->stepx=-1; - } else data->stepx=0; - if ( data->deltay > 0 ) { - data->stepy=1; - } else if ( data->deltay < 0 ){ - data->stepy=-1; - } else data->stepy = 0; - if ( data->stepx*data->deltax > data->stepy*data->deltay ) { - data->e = data->stepx*data->deltax; - data->deltax *= 2; - data->deltay *= 2; - } else { - data->e = data->stepy*data->deltay; - data->deltax *= 2; - data->deltay *= 2; - } -} -/** - * \brief Get the next point on a line, returns true once the line has ended. - * - * \param xCur An int pointer to fill with the next x position. - * \param yCur An int pointer to fill with the next y position. - * \param data Pointer to a initialized TCOD_bresenham_data_t struct. - * \return true after the ending point has been reached. - * - * The starting point is excluded by this function. - * After the ending point is reached, the next call will return true. - */ -bool TCOD_line_step_mt(int *xCur, int *yCur, TCOD_bresenham_data_t *data) { - if ( data->stepx*data->deltax > data->stepy*data->deltay ) { - if ( data->origx == data->destx ) return true; - data->origx+=data->stepx; - data->e -= data->stepy*data->deltay; - if ( data->e < 0) { - data->origy+=data->stepy; - data->e+=data->stepx*data->deltax; - } - } else { - if ( data->origy == data->desty ) return true; - data->origy+=data->stepy; - data->e -= data->stepx*data->deltax; - if ( data->e < 0) { - data->origx+=data->stepx; - data->e+=data->stepy*data->deltay; - } - } - *xCur=data->origx; - *yCur=data->origy; - return false; -} -/** - * \brief Iterate over a line using a callback. - * - * \param xo The origin x position. - * \param yo The origin y position. - * \param xd The destination x position. - * \param yd The destination y position. - * \param listener A TCOD_line_listener_t callback. - * \param data Pointer to a TCOD_bresenham_data_t struct. - * \return true if the line was completely exhausted by the callback. - * - * \verbatim embed:rst:leading-asterisk - * .. deprecated:: 1.6.6 - * The `data` parameter for this call is redundant, you should call - * :any:`TCOD_line` instead. - * \endverbatim - */ -bool TCOD_line_mt(int xo, int yo, int xd, int yd, TCOD_line_listener_t listener, TCOD_bresenham_data_t *data) { - TCOD_line_init_mt(xo,yo,xd,yd,data); - do { - if (! listener(xo,yo)) return false; - } while (! TCOD_line_step_mt(&xo,&yo,data)); - return true; -} -/** - * \brief Initialize a line using a global state. - * - * \param xFrom The starting x position. - * \param yFrom The starting y position. - * \param xTo The ending x position. - * \param yTo The ending y position. - * - * \verbatim embed:rst:leading-asterisk - * .. deprecated:: 1.6.6 - * This function is not reentrant and will fail if a new line is started - * before the last is finished processing. - * - * Use :any:`TCOD_line_init_mt` instead. - * \endverbatim - */ -void TCOD_line_init(int xFrom, int yFrom, int xTo, int yTo) { - TCOD_line_init_mt(xFrom,yFrom,xTo,yTo,&bresenham_data); -} -/** - * \brief Get the next point in a line, returns true once the line has ended. - * - * \param xCur An int pointer to fill with the next x position. - * \param yCur An int pointer to fill with the next y position. - * \return true once the ending point has been reached. - * - * The starting point is excluded by this function. - * After the ending point is reached, the next call will return true. - * - * \verbatim embed:rst:leading-asterisk - * .. deprecated:: 1.6.6 - * This function is not reentrant and will fail if a new line is started - * before the last is finished processing. - * - * Use :any:`TCOD_line_step_mt` instead. - * \endverbatim - */ -bool TCOD_line_step(int *xCur, int *yCur) { - return TCOD_line_step_mt(xCur,yCur,&bresenham_data); -} -/** - * \brief Iterate over a line using a callback. - * - * \param xo The origin x position. - * \param yo The origin y position. - * \param xd The destination x position. - * \param yd The destination y position. - * \param listener A TCOD_line_listener_t callback. - * \return true if the line was completely exhausted by the callback. - * - * \verbatim embed:rst:leading-asterisk - * .. versionchanged:: 1.6.6 - * This function is now reentrant. - * \endverbatim - */ -bool TCOD_line(int xo, int yo, int xd, int yd, TCOD_line_listener_t listener) { - TCOD_bresenham_data_t bresenham_data; - return TCOD_line_mt(xo,yo,xd,yd,listener,&bresenham_data); -} +/* +* libtcod +* Copyright (c) 2008-2018 Jice & Mingos & rmtew +* All rights reserved. +* +* Redistribution and use in source and binary forms, with or without +* modification, are permitted provided that the following conditions are met: +* * Redistributions of source code must retain the above copyright +* notice, this list of conditions and the following disclaimer. +* * Redistributions in binary form must reproduce the above copyright +* notice, this list of conditions and the following disclaimer in the +* documentation and/or other materials provided with the distribution. +* * The name of Jice or Mingos may not be used to endorse or promote +* products derived from this software without specific prior written +* permission. +* +* THIS SOFTWARE IS PROVIDED BY JICE, MINGOS AND RMTEW ``AS IS'' AND ANY +* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED +* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE +* DISCLAIMED. IN NO EVENT SHALL JICE, MINGOS OR RMTEW BE LIABLE FOR ANY +* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES +* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; +* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND +* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS +* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +*/ +#include "bresenham.h" +/** + * \file bresenham_c.c + * \brief bresenham line drawing + */ +/* This static variable is deprecated since 1.6 */ +static TCOD_bresenham_data_t bresenham_data; +/** + * \brief Initialize a TCOD_bresenham_data_t struct. + * + * \param xFrom The starting x position. + * \param yFrom The starting y position. + * \param xTo The ending x position. + * \param yTo The ending y position. + * \param data Pointer to a TCOD_bresenham_data_t struct. + * + * After calling this function you use TCOD_line_step_mt to iterate + * over the individual points on the line. + */ +void TCOD_line_init_mt(int xFrom, int yFrom, int xTo, int yTo, TCOD_bresenham_data_t *data) { + data->origx=xFrom; + data->origy=yFrom; + data->destx=xTo; + data->desty=yTo; + data->deltax=xTo - xFrom; + data->deltay=yTo - yFrom; + if ( data->deltax > 0 ) { + data->stepx=1; + } else if ( data->deltax < 0 ){ + data->stepx=-1; + } else data->stepx=0; + if ( data->deltay > 0 ) { + data->stepy=1; + } else if ( data->deltay < 0 ){ + data->stepy=-1; + } else data->stepy = 0; + if ( data->stepx*data->deltax > data->stepy*data->deltay ) { + data->e = data->stepx*data->deltax; + data->deltax *= 2; + data->deltay *= 2; + } else { + data->e = data->stepy*data->deltay; + data->deltax *= 2; + data->deltay *= 2; + } +} +/** + * \brief Get the next point on a line, returns true once the line has ended. + * + * \param xCur An int pointer to fill with the next x position. + * \param yCur An int pointer to fill with the next y position. + * \param data Pointer to a initialized TCOD_bresenham_data_t struct. + * \return true after the ending point has been reached. + * + * The starting point is excluded by this function. + * After the ending point is reached, the next call will return true. + */ +bool TCOD_line_step_mt(int *xCur, int *yCur, TCOD_bresenham_data_t *data) { + if ( data->stepx*data->deltax > data->stepy*data->deltay ) { + if ( data->origx == data->destx ) return true; + data->origx+=data->stepx; + data->e -= data->stepy*data->deltay; + if ( data->e < 0) { + data->origy+=data->stepy; + data->e+=data->stepx*data->deltax; + } + } else { + if ( data->origy == data->desty ) return true; + data->origy+=data->stepy; + data->e -= data->stepx*data->deltax; + if ( data->e < 0) { + data->origx+=data->stepx; + data->e+=data->stepy*data->deltay; + } + } + *xCur=data->origx; + *yCur=data->origy; + return false; +} +/** + * \brief Iterate over a line using a callback. + * + * \param xo The origin x position. + * \param yo The origin y position. + * \param xd The destination x position. + * \param yd The destination y position. + * \param listener A TCOD_line_listener_t callback. + * \param data Pointer to a TCOD_bresenham_data_t struct. + * \return true if the line was completely exhausted by the callback. + * + * \verbatim embed:rst:leading-asterisk + * .. deprecated:: 1.6.6 + * The `data` parameter for this call is redundant, you should call + * :any:`TCOD_line` instead. + * \endverbatim + */ +bool TCOD_line_mt(int xo, int yo, int xd, int yd, TCOD_line_listener_t listener, TCOD_bresenham_data_t *data) { + TCOD_line_init_mt(xo,yo,xd,yd,data); + do { + if (! listener(xo,yo)) return false; + } while (! TCOD_line_step_mt(&xo,&yo,data)); + return true; +} +/** + * \brief Initialize a line using a global state. + * + * \param xFrom The starting x position. + * \param yFrom The starting y position. + * \param xTo The ending x position. + * \param yTo The ending y position. + * + * \verbatim embed:rst:leading-asterisk + * .. deprecated:: 1.6.6 + * This function is not reentrant and will fail if a new line is started + * before the last is finished processing. + * + * Use :any:`TCOD_line_init_mt` instead. + * \endverbatim + */ +void TCOD_line_init(int xFrom, int yFrom, int xTo, int yTo) { + TCOD_line_init_mt(xFrom,yFrom,xTo,yTo,&bresenham_data); +} +/** + * \brief Get the next point in a line, returns true once the line has ended. + * + * \param xCur An int pointer to fill with the next x position. + * \param yCur An int pointer to fill with the next y position. + * \return true once the ending point has been reached. + * + * The starting point is excluded by this function. + * After the ending point is reached, the next call will return true. + * + * \verbatim embed:rst:leading-asterisk + * .. deprecated:: 1.6.6 + * This function is not reentrant and will fail if a new line is started + * before the last is finished processing. + * + * Use :any:`TCOD_line_step_mt` instead. + * \endverbatim + */ +bool TCOD_line_step(int *xCur, int *yCur) { + return TCOD_line_step_mt(xCur,yCur,&bresenham_data); +} +/** + * \brief Iterate over a line using a callback. + * + * \param xo The origin x position. + * \param yo The origin y position. + * \param xd The destination x position. + * \param yd The destination y position. + * \param listener A TCOD_line_listener_t callback. + * \return true if the line was completely exhausted by the callback. + * + * \verbatim embed:rst:leading-asterisk + * .. versionchanged:: 1.6.6 + * This function is now reentrant. + * \endverbatim + */ +bool TCOD_line(int xo, int yo, int xd, int yd, TCOD_line_listener_t listener) { + TCOD_bresenham_data_t bresenham_data; + return TCOD_line_mt(xo,yo,xd,yd,listener,&bresenham_data); +} diff --git a/tcod_sys/libtcod/src/bsp.cpp b/tcod_sys/libtcod/src/libtcod/bsp.cpp similarity index 96% rename from tcod_sys/libtcod/src/bsp.cpp rename to tcod_sys/libtcod/src/libtcod/bsp.cpp index 4f7cb7f31..6c17d4d17 100644 --- a/tcod_sys/libtcod/src/bsp.cpp +++ b/tcod_sys/libtcod/src/libtcod/bsp.cpp @@ -1,168 +1,168 @@ -/* -* libtcod -* Copyright (c) 2008-2018 Jice & Mingos & rmtew -* All rights reserved. -* -* Redistribution and use in source and binary forms, with or without -* modification, are permitted provided that the following conditions are met: -* * Redistributions of source code must retain the above copyright -* notice, this list of conditions and the following disclaimer. -* * Redistributions in binary form must reproduce the above copyright -* notice, this list of conditions and the following disclaimer in the -* documentation and/or other materials provided with the distribution. -* * The name of Jice or Mingos may not be used to endorse or promote -* products derived from this software without specific prior written -* permission. -* -* THIS SOFTWARE IS PROVIDED BY JICE, MINGOS AND RMTEW ``AS IS'' AND ANY -* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED -* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE -* DISCLAIMED. IN NO EVENT SHALL JICE, MINGOS OR RMTEW BE LIABLE FOR ANY -* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES -* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; -* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND -* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS -* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. -*/ -#include - -TCODBsp::TCODBsp(TCODBsp *father, bool left) { - if ( father->horizontal ) { - x=father->x; - w=father->w; - y = left ? father->y : father->position; - h = left ? father->position - y: father->y + father->h - father->position; - } else { - y=father->y; - h=father->h; - x = left ? father->x : father->position; - w = left ? father->position - x: father->x + father->w - father->position; - } - level=father->level+1; -} - -TCODBsp::~TCODBsp() { - removeSons(); -} - -bool TCODBsp::traversePreOrder(ITCODBspCallback *listener, void *userData) { - if (!listener->visitNode(this,userData)) return false; - if ( getLeft() && !getLeft()->traversePreOrder(listener,userData) ) return false; - if ( getRight() && !getRight()->traversePreOrder(listener,userData)) return false; - return true; -} - -bool TCODBsp::traverseInOrder(ITCODBspCallback *listener, void *userData) { - if ( getLeft() && !getLeft()->traverseInOrder(listener,userData) ) return false; - if (!listener->visitNode(this,userData)) return false; - if ( getRight() && !getRight()->traverseInOrder(listener,userData)) return false; - return true; -} - -bool TCODBsp::traversePostOrder(ITCODBspCallback *listener,void *userData) { - if ( getLeft() && !getLeft()->traversePostOrder(listener,userData)) return false; - if ( getRight() && !getRight()->traversePostOrder(listener,userData)) return false; - if (!listener->visitNode(this,userData)) return false; - return true; -} - -bool TCODBsp::traverseLevelOrder(ITCODBspCallback *listener, void *userData) { - TCODList stack; - stack.push(this); - while ( ! stack.isEmpty() ) { - TCODBsp *node=stack.get(0); - stack.remove(node); - if ( node->getLeft() ) stack.push(node->getLeft()); - if ( node->getRight() ) stack.push(node->getRight()); - if (!listener->visitNode(node,userData)) return false; - } - return true; -} - -bool TCODBsp::traverseInvertedLevelOrder(ITCODBspCallback *listener, void *userData) { - TCODList stack1; - TCODList stack2; - stack1.push(this); - while ( ! stack1.isEmpty() ) { - TCODBsp *node=stack1.get(0); - stack2.push(node); - stack1.remove(node); - if ( node->getLeft() ) stack1.push(node->getLeft()); - if ( node->getRight() ) stack1.push(node->getRight()); - } - while ( ! stack2.isEmpty() ) { - TCODBsp *node=stack2.pop(); - if (!listener->visitNode(node,userData)) return false; - } - return true; -} - -void TCODBsp::removeSons() { - TCODBsp *node=(TCODBsp *)sons; - while ( node ) { - TCODBsp *nextNode=(TCODBsp *)node->next; - node->removeSons(); - delete node; - node=nextNode; - } - sons=NULL; -} - -void TCODBsp::splitOnce(bool horizontal, int position) { - this->horizontal = horizontal; - this->position=position; - addSon(new TCODBsp(this,true)); - addSon(new TCODBsp(this,false)); -} - -void TCODBsp::splitRecursive(TCODRandom *randomizer, int nb, int minHSize, int minVSize, float maxHRatio, float maxVRatio) { - if ( nb == 0 || (w < 2*minHSize && h < 2*minVSize ) ) return; - bool horiz; - if (! randomizer ) randomizer=TCODRandom::getInstance(); - // promote square rooms - if ( h < 2*minVSize || w > h * maxHRatio ) horiz = false; - else if ( w < 2*minHSize || h > w * maxVRatio) horiz = true; - else horiz = randomizer->getInt(0,1) == 0; - int position; - if ( horiz ) { - position = randomizer->getInt(y+minVSize,y+h-minVSize); - } else { - position = randomizer->getInt(x+minHSize,x+w-minHSize); - } - splitOnce(horiz,position); - getLeft()->splitRecursive(randomizer,nb-1,minHSize,minVSize,maxHRatio,maxVRatio); - getRight()->splitRecursive(randomizer,nb-1,minHSize,minVSize,maxHRatio,maxVRatio); -} - -void TCODBsp::resize(int x,int y, int w, int h) { - this->x=x; - this->y=y; - this->w=w; - this->h=h; - if ( getLeft() ) { - if ( horizontal ) { - getLeft()->resize(x,y,w,position-y); - getRight()->resize(x,position,w,y+h-position); - } else { - getLeft()->resize(x,y,position-x,h); - getRight()->resize(position,y,x+w-position,h); - } - } -} - -bool TCODBsp::contains(int px, int py) const { - return (px >= x && py >= y && px < x+w && py < y+h); -} - -TCODBsp *TCODBsp::findNode(int px, int py) { - if ( ! contains(px,py) ) return NULL; - if ( ! isLeaf() ) { - TCODBsp *left,*right; - left=getLeft(); - if ( left->contains(px,py) ) return left->findNode(px,py); - right=getRight(); - if ( right->contains(px,py) ) return right->findNode(px,py); - } - return this; -} +/* +* libtcod +* Copyright (c) 2008-2018 Jice & Mingos & rmtew +* All rights reserved. +* +* Redistribution and use in source and binary forms, with or without +* modification, are permitted provided that the following conditions are met: +* * Redistributions of source code must retain the above copyright +* notice, this list of conditions and the following disclaimer. +* * Redistributions in binary form must reproduce the above copyright +* notice, this list of conditions and the following disclaimer in the +* documentation and/or other materials provided with the distribution. +* * The name of Jice or Mingos may not be used to endorse or promote +* products derived from this software without specific prior written +* permission. +* +* THIS SOFTWARE IS PROVIDED BY JICE, MINGOS AND RMTEW ``AS IS'' AND ANY +* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED +* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE +* DISCLAIMED. IN NO EVENT SHALL JICE, MINGOS OR RMTEW BE LIABLE FOR ANY +* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES +* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; +* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND +* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS +* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +*/ +#include "bsp.hpp" + +TCODBsp::TCODBsp(TCODBsp *father, bool left) { + if ( father->horizontal ) { + x=father->x; + w=father->w; + y = left ? father->y : father->position; + h = left ? father->position - y: father->y + father->h - father->position; + } else { + y=father->y; + h=father->h; + x = left ? father->x : father->position; + w = left ? father->position - x: father->x + father->w - father->position; + } + level=father->level+1; +} + +TCODBsp::~TCODBsp() { + removeSons(); +} + +bool TCODBsp::traversePreOrder(ITCODBspCallback *listener, void *userData) { + if (!listener->visitNode(this,userData)) return false; + if ( getLeft() && !getLeft()->traversePreOrder(listener,userData) ) return false; + if ( getRight() && !getRight()->traversePreOrder(listener,userData)) return false; + return true; +} + +bool TCODBsp::traverseInOrder(ITCODBspCallback *listener, void *userData) { + if ( getLeft() && !getLeft()->traverseInOrder(listener,userData) ) return false; + if (!listener->visitNode(this,userData)) return false; + if ( getRight() && !getRight()->traverseInOrder(listener,userData)) return false; + return true; +} + +bool TCODBsp::traversePostOrder(ITCODBspCallback *listener,void *userData) { + if ( getLeft() && !getLeft()->traversePostOrder(listener,userData)) return false; + if ( getRight() && !getRight()->traversePostOrder(listener,userData)) return false; + if (!listener->visitNode(this,userData)) return false; + return true; +} + +bool TCODBsp::traverseLevelOrder(ITCODBspCallback *listener, void *userData) { + TCODList stack; + stack.push(this); + while ( ! stack.isEmpty() ) { + TCODBsp *node=stack.get(0); + stack.remove(node); + if ( node->getLeft() ) stack.push(node->getLeft()); + if ( node->getRight() ) stack.push(node->getRight()); + if (!listener->visitNode(node,userData)) return false; + } + return true; +} + +bool TCODBsp::traverseInvertedLevelOrder(ITCODBspCallback *listener, void *userData) { + TCODList stack1; + TCODList stack2; + stack1.push(this); + while ( ! stack1.isEmpty() ) { + TCODBsp *node=stack1.get(0); + stack2.push(node); + stack1.remove(node); + if ( node->getLeft() ) stack1.push(node->getLeft()); + if ( node->getRight() ) stack1.push(node->getRight()); + } + while ( ! stack2.isEmpty() ) { + TCODBsp *node=stack2.pop(); + if (!listener->visitNode(node,userData)) return false; + } + return true; +} + +void TCODBsp::removeSons() { + TCODBsp *node=(TCODBsp *)sons; + while ( node ) { + TCODBsp *nextNode=(TCODBsp *)node->next; + node->removeSons(); + delete node; + node=nextNode; + } + sons=NULL; +} + +void TCODBsp::splitOnce(bool horizontal, int position) { + this->horizontal = horizontal; + this->position=position; + addSon(new TCODBsp(this,true)); + addSon(new TCODBsp(this,false)); +} + +void TCODBsp::splitRecursive(TCODRandom *randomizer, int nb, int minHSize, int minVSize, float maxHRatio, float maxVRatio) { + if ( nb == 0 || (w < 2*minHSize && h < 2*minVSize ) ) return; + bool horiz; + if (! randomizer ) randomizer=TCODRandom::getInstance(); + // promote square rooms + if ( h < 2*minVSize || w > h * maxHRatio ) horiz = false; + else if ( w < 2*minHSize || h > w * maxVRatio) horiz = true; + else horiz = randomizer->getInt(0,1) == 0; + int position; + if ( horiz ) { + position = randomizer->getInt(y+minVSize,y+h-minVSize); + } else { + position = randomizer->getInt(x+minHSize,x+w-minHSize); + } + splitOnce(horiz,position); + getLeft()->splitRecursive(randomizer,nb-1,minHSize,minVSize,maxHRatio,maxVRatio); + getRight()->splitRecursive(randomizer,nb-1,minHSize,minVSize,maxHRatio,maxVRatio); +} + +void TCODBsp::resize(int x,int y, int w, int h) { + this->x=x; + this->y=y; + this->w=w; + this->h=h; + if ( getLeft() ) { + if ( horizontal ) { + getLeft()->resize(x,y,w,position-y); + getRight()->resize(x,position,w,y+h-position); + } else { + getLeft()->resize(x,y,position-x,h); + getRight()->resize(position,y,x+w-position,h); + } + } +} + +bool TCODBsp::contains(int px, int py) const { + return (px >= x && py >= y && px < x+w && py < y+h); +} + +TCODBsp *TCODBsp::findNode(int px, int py) { + if ( ! contains(px,py) ) return NULL; + if ( ! isLeaf() ) { + TCODBsp *left,*right; + left=getLeft(); + if ( left->contains(px,py) ) return left->findNode(px,py); + right=getRight(); + if ( right->contains(px,py) ) return right->findNode(px,py); + } + return this; +} diff --git a/tcod_sys/libtcod/include/bsp.h b/tcod_sys/libtcod/src/libtcod/bsp.h similarity index 99% rename from tcod_sys/libtcod/include/bsp.h rename to tcod_sys/libtcod/src/libtcod/bsp.h index 00783700f..782caef6b 100644 --- a/tcod_sys/libtcod/include/bsp.h +++ b/tcod_sys/libtcod/src/libtcod/bsp.h @@ -28,7 +28,7 @@ #ifndef _TCOD_BSP_H #define _TCOD_BSP_H -#include "libtcod_portability.h" +#include "portability.h" #include "mersenne_types.h" #include "tree.h" diff --git a/tcod_sys/libtcod/include/bsp.hpp b/tcod_sys/libtcod/src/libtcod/bsp.hpp similarity index 100% rename from tcod_sys/libtcod/include/bsp.hpp rename to tcod_sys/libtcod/src/libtcod/bsp.hpp diff --git a/tcod_sys/libtcod/src/bsp_c.c b/tcod_sys/libtcod/src/libtcod/bsp_c.c similarity index 96% rename from tcod_sys/libtcod/src/bsp_c.c rename to tcod_sys/libtcod/src/libtcod/bsp_c.c index a959966d7..cec227fbd 100644 --- a/tcod_sys/libtcod/src/bsp_c.c +++ b/tcod_sys/libtcod/src/libtcod/bsp_c.c @@ -1,216 +1,216 @@ -/* -* libtcod -* Copyright (c) 2008-2018 Jice & Mingos & rmtew -* All rights reserved. -* -* Redistribution and use in source and binary forms, with or without -* modification, are permitted provided that the following conditions are met: -* * Redistributions of source code must retain the above copyright -* notice, this list of conditions and the following disclaimer. -* * Redistributions in binary form must reproduce the above copyright -* notice, this list of conditions and the following disclaimer in the -* documentation and/or other materials provided with the distribution. -* * The name of Jice or Mingos may not be used to endorse or promote -* products derived from this software without specific prior written -* permission. -* -* THIS SOFTWARE IS PROVIDED BY JICE, MINGOS AND RMTEW ``AS IS'' AND ANY -* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED -* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE -* DISCLAIMED. IN NO EVENT SHALL JICE, MINGOS OR RMTEW BE LIABLE FOR ANY -* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES -* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; -* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND -* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS -* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. -*/ -#include - -#include - -#include -#include - -TCOD_bsp_t *TCOD_bsp_new(void) { - return (TCOD_bsp_t *)calloc(sizeof(TCOD_bsp_t),1); -} - -TCOD_bsp_t *TCOD_bsp_new_with_size(int x,int y,int w, int h) { - TCOD_bsp_t *bsp=(TCOD_bsp_t *)calloc(sizeof(TCOD_bsp_t),1); - bsp->x=x; - bsp->y=y; - bsp->w=w; - bsp->h=h; - return bsp; -} - -TCOD_bsp_t * TCOD_bsp_left(TCOD_bsp_t *node) { - return (TCOD_bsp_t *)node->tree.sons; -} - -TCOD_bsp_t * TCOD_bsp_right(TCOD_bsp_t *node) { - return node->tree.sons ? (TCOD_bsp_t *)node->tree.sons->next : NULL; -} - -TCOD_bsp_t * TCOD_bsp_father(TCOD_bsp_t *node) { - return (TCOD_bsp_t *)node->tree.father; -} - -bool TCOD_bsp_is_leaf(TCOD_bsp_t *node) { - return node->tree.sons==NULL; -} - -void TCOD_bsp_delete(TCOD_bsp_t *node) { - TCOD_bsp_remove_sons(node); - free(node); -} - -static TCOD_bsp_t *TCOD_bsp_new_intern(TCOD_bsp_t *father, bool left) { - TCOD_bsp_t *bsp=(TCOD_bsp_t *)calloc(sizeof(TCOD_bsp_t),1); - if ( father->horizontal ) { - bsp->x=father->x; - bsp->w=father->w; - bsp->y = left ? father->y : father->position; - bsp->h = left ? father->position - bsp->y: father->y + father->h - father->position; - } else { - bsp->y=father->y; - bsp->h=father->h; - bsp->x = left ? father->x : father->position; - bsp->w = left ? father->position - bsp->x: father->x + father->w - father->position; - } - bsp->level=father->level+1; - return bsp; -} - -bool TCOD_bsp_traverse_pre_order(TCOD_bsp_t *node, TCOD_bsp_callback_t listener, void *userData) { - if (!listener(node,userData)) return false; - if ( TCOD_bsp_left(node) && !TCOD_bsp_traverse_pre_order(TCOD_bsp_left(node),listener,userData)) return false; - if ( TCOD_bsp_right(node) && !TCOD_bsp_traverse_pre_order(TCOD_bsp_right(node),listener,userData)) return false; - return true; -} - -bool TCOD_bsp_traverse_in_order(TCOD_bsp_t *node, TCOD_bsp_callback_t listener, void *userData) { - if ( TCOD_bsp_left(node) && !TCOD_bsp_traverse_in_order(TCOD_bsp_left(node),listener,userData)) return false; - if (!listener(node,userData)) return false; - if ( TCOD_bsp_right(node) && !TCOD_bsp_traverse_in_order(TCOD_bsp_right(node),listener,userData)) return false; - return true; -} - -bool TCOD_bsp_traverse_post_order(TCOD_bsp_t *node, TCOD_bsp_callback_t listener, void *userData) { - if ( TCOD_bsp_left(node) && !TCOD_bsp_traverse_post_order(TCOD_bsp_left(node),listener,userData)) return false; - if ( TCOD_bsp_right(node) && !TCOD_bsp_traverse_post_order(TCOD_bsp_right(node),listener,userData)) return false; - if (!listener(node,userData)) return false; - return true; -} - -bool TCOD_bsp_traverse_level_order(TCOD_bsp_t *node, TCOD_bsp_callback_t listener, void *userData) { - TCOD_list_t stack=TCOD_list_new(); - TCOD_list_push(stack,node); - while ( ! TCOD_list_is_empty(stack) ) { - TCOD_bsp_t *node=(TCOD_bsp_t *)TCOD_list_get(stack,0); - TCOD_list_remove(stack,node); - if ( TCOD_bsp_left(node) ) TCOD_list_push(stack,TCOD_bsp_left(node)); - if ( TCOD_bsp_right(node) ) TCOD_list_push(stack,TCOD_bsp_right(node)); - if (!listener(node,userData)) { - TCOD_list_delete(stack); - return false; - } - } - TCOD_list_delete(stack); - return true; -} - -bool TCOD_bsp_traverse_inverted_level_order(TCOD_bsp_t *node, TCOD_bsp_callback_t listener, void *userData) { - TCOD_list_t stack1=TCOD_list_new(); - TCOD_list_t stack2=TCOD_list_new(); - TCOD_list_push(stack1,node); - while ( ! TCOD_list_is_empty(stack1) ) { - TCOD_bsp_t *node=(TCOD_bsp_t *)TCOD_list_get(stack1,0); - TCOD_list_push(stack2,node); - TCOD_list_remove(stack1,node); - if ( TCOD_bsp_left(node) ) TCOD_list_push(stack1,TCOD_bsp_left(node)); - if ( TCOD_bsp_right(node) ) TCOD_list_push(stack1,TCOD_bsp_right(node)); - } - while ( ! TCOD_list_is_empty(stack2) ) { - TCOD_bsp_t *node=(TCOD_bsp_t *)TCOD_list_pop(stack2); - if (!listener(node,userData)) { - TCOD_list_delete(stack1); - TCOD_list_delete(stack2); - return false; - } - } - TCOD_list_delete(stack1); - TCOD_list_delete(stack2); - return true; -} - -void TCOD_bsp_remove_sons(TCOD_bsp_t *root) { - TCOD_bsp_t *node=(TCOD_bsp_t *)root->tree.sons; - while ( node ) { - TCOD_bsp_t *nextNode=(TCOD_bsp_t *)node->tree.next; - TCOD_bsp_remove_sons(node); - free( node ); - node=nextNode; - } - root->tree.sons=NULL; -} - -void TCOD_bsp_split_once(TCOD_bsp_t *node, bool horizontal, int position) { - node->horizontal = horizontal; - node->position=position; - TCOD_tree_add_son(&node->tree,&TCOD_bsp_new_intern(node,true)->tree); - TCOD_tree_add_son(&node->tree,&TCOD_bsp_new_intern(node,false)->tree); -} - -void TCOD_bsp_split_recursive(TCOD_bsp_t *node, TCOD_random_t randomizer, int nb, - int minHSize, int minVSize, float maxHRatio, float maxVRatio) { - bool horiz; - int position; - if ( nb == 0 || (node->w < 2*minHSize && node->h < 2*minVSize ) ) return; - if (! randomizer ) randomizer=TCOD_random_get_instance(); - /* promote square rooms */ - if ( node->h < 2*minVSize || node->w > node->h * maxHRatio ) horiz = false; - else if ( node->w < 2*minHSize || node->h > node->w * maxVRatio) horiz = true; - else horiz = (TCOD_random_get_int(randomizer,0,1) == 0); - if ( horiz ) { - position = TCOD_random_get_int(randomizer,node->y+minVSize,node->y+node->h-minVSize); - } else { - position = TCOD_random_get_int(randomizer,node->x+minHSize,node->x+node->w-minHSize); - } - TCOD_bsp_split_once(node,horiz,position); - TCOD_bsp_split_recursive(TCOD_bsp_left(node),randomizer,nb-1,minHSize,minVSize,maxHRatio,maxVRatio); - TCOD_bsp_split_recursive(TCOD_bsp_right(node),randomizer,nb-1,minHSize,minVSize,maxHRatio,maxVRatio); -} - -void TCOD_bsp_resize(TCOD_bsp_t *node, int x,int y, int w, int h) { - node->x=x; - node->y=y; - node->w=w; - node->h=h; - if ( TCOD_bsp_left(node) ) { - if ( node->horizontal ) { - TCOD_bsp_resize(TCOD_bsp_left(node),x,y,w,node->position-y); - TCOD_bsp_resize(TCOD_bsp_right(node),x,node->position,w,y+h-node->position); - } else { - TCOD_bsp_resize(TCOD_bsp_left(node),x,y,node->position-x,h); - TCOD_bsp_resize(TCOD_bsp_right(node),node->position,y,x+w-node->position,h); - } - } -} - -bool TCOD_bsp_contains(TCOD_bsp_t *node, int x, int y) { - return (x >= node->x && y >= node->y && x < node->x+node->w && y < node->y+node->h); -} - -TCOD_bsp_t * TCOD_bsp_find_node(TCOD_bsp_t *node, int x, int y) { - if ( ! TCOD_bsp_contains(node,x,y) ) return NULL; - if ( ! TCOD_bsp_is_leaf(node) ) { - TCOD_bsp_t *left,*right; - left=TCOD_bsp_left(node); - if ( TCOD_bsp_contains(left,x,y) ) return TCOD_bsp_find_node(left,x,y); - right=TCOD_bsp_right(node); - if ( TCOD_bsp_contains(right,x,y) ) return TCOD_bsp_find_node(right,x,y); - } - return node; -} +/* +* libtcod +* Copyright (c) 2008-2018 Jice & Mingos & rmtew +* All rights reserved. +* +* Redistribution and use in source and binary forms, with or without +* modification, are permitted provided that the following conditions are met: +* * Redistributions of source code must retain the above copyright +* notice, this list of conditions and the following disclaimer. +* * Redistributions in binary form must reproduce the above copyright +* notice, this list of conditions and the following disclaimer in the +* documentation and/or other materials provided with the distribution. +* * The name of Jice or Mingos may not be used to endorse or promote +* products derived from this software without specific prior written +* permission. +* +* THIS SOFTWARE IS PROVIDED BY JICE, MINGOS AND RMTEW ``AS IS'' AND ANY +* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED +* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE +* DISCLAIMED. IN NO EVENT SHALL JICE, MINGOS OR RMTEW BE LIABLE FOR ANY +* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES +* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; +* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND +* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS +* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +*/ +#include "bsp.h" + +#include + +#include "list.h" +#include "mersenne.h" + +TCOD_bsp_t *TCOD_bsp_new(void) { + return (TCOD_bsp_t *)calloc(sizeof(TCOD_bsp_t),1); +} + +TCOD_bsp_t *TCOD_bsp_new_with_size(int x,int y,int w, int h) { + TCOD_bsp_t *bsp=(TCOD_bsp_t *)calloc(sizeof(TCOD_bsp_t),1); + bsp->x=x; + bsp->y=y; + bsp->w=w; + bsp->h=h; + return bsp; +} + +TCOD_bsp_t * TCOD_bsp_left(TCOD_bsp_t *node) { + return (TCOD_bsp_t *)node->tree.sons; +} + +TCOD_bsp_t * TCOD_bsp_right(TCOD_bsp_t *node) { + return node->tree.sons ? (TCOD_bsp_t *)node->tree.sons->next : NULL; +} + +TCOD_bsp_t * TCOD_bsp_father(TCOD_bsp_t *node) { + return (TCOD_bsp_t *)node->tree.father; +} + +bool TCOD_bsp_is_leaf(TCOD_bsp_t *node) { + return node->tree.sons==NULL; +} + +void TCOD_bsp_delete(TCOD_bsp_t *node) { + TCOD_bsp_remove_sons(node); + free(node); +} + +static TCOD_bsp_t *TCOD_bsp_new_intern(TCOD_bsp_t *father, bool left) { + TCOD_bsp_t *bsp=(TCOD_bsp_t *)calloc(sizeof(TCOD_bsp_t),1); + if ( father->horizontal ) { + bsp->x=father->x; + bsp->w=father->w; + bsp->y = left ? father->y : father->position; + bsp->h = left ? father->position - bsp->y: father->y + father->h - father->position; + } else { + bsp->y=father->y; + bsp->h=father->h; + bsp->x = left ? father->x : father->position; + bsp->w = left ? father->position - bsp->x: father->x + father->w - father->position; + } + bsp->level=father->level+1; + return bsp; +} + +bool TCOD_bsp_traverse_pre_order(TCOD_bsp_t *node, TCOD_bsp_callback_t listener, void *userData) { + if (!listener(node,userData)) return false; + if ( TCOD_bsp_left(node) && !TCOD_bsp_traverse_pre_order(TCOD_bsp_left(node),listener,userData)) return false; + if ( TCOD_bsp_right(node) && !TCOD_bsp_traverse_pre_order(TCOD_bsp_right(node),listener,userData)) return false; + return true; +} + +bool TCOD_bsp_traverse_in_order(TCOD_bsp_t *node, TCOD_bsp_callback_t listener, void *userData) { + if ( TCOD_bsp_left(node) && !TCOD_bsp_traverse_in_order(TCOD_bsp_left(node),listener,userData)) return false; + if (!listener(node,userData)) return false; + if ( TCOD_bsp_right(node) && !TCOD_bsp_traverse_in_order(TCOD_bsp_right(node),listener,userData)) return false; + return true; +} + +bool TCOD_bsp_traverse_post_order(TCOD_bsp_t *node, TCOD_bsp_callback_t listener, void *userData) { + if ( TCOD_bsp_left(node) && !TCOD_bsp_traverse_post_order(TCOD_bsp_left(node),listener,userData)) return false; + if ( TCOD_bsp_right(node) && !TCOD_bsp_traverse_post_order(TCOD_bsp_right(node),listener,userData)) return false; + if (!listener(node,userData)) return false; + return true; +} + +bool TCOD_bsp_traverse_level_order(TCOD_bsp_t *node, TCOD_bsp_callback_t listener, void *userData) { + TCOD_list_t stack=TCOD_list_new(); + TCOD_list_push(stack,node); + while ( ! TCOD_list_is_empty(stack) ) { + TCOD_bsp_t *node=(TCOD_bsp_t *)TCOD_list_get(stack,0); + TCOD_list_remove(stack,node); + if ( TCOD_bsp_left(node) ) TCOD_list_push(stack,TCOD_bsp_left(node)); + if ( TCOD_bsp_right(node) ) TCOD_list_push(stack,TCOD_bsp_right(node)); + if (!listener(node,userData)) { + TCOD_list_delete(stack); + return false; + } + } + TCOD_list_delete(stack); + return true; +} + +bool TCOD_bsp_traverse_inverted_level_order(TCOD_bsp_t *node, TCOD_bsp_callback_t listener, void *userData) { + TCOD_list_t stack1=TCOD_list_new(); + TCOD_list_t stack2=TCOD_list_new(); + TCOD_list_push(stack1,node); + while ( ! TCOD_list_is_empty(stack1) ) { + TCOD_bsp_t *node=(TCOD_bsp_t *)TCOD_list_get(stack1,0); + TCOD_list_push(stack2,node); + TCOD_list_remove(stack1,node); + if ( TCOD_bsp_left(node) ) TCOD_list_push(stack1,TCOD_bsp_left(node)); + if ( TCOD_bsp_right(node) ) TCOD_list_push(stack1,TCOD_bsp_right(node)); + } + while ( ! TCOD_list_is_empty(stack2) ) { + TCOD_bsp_t *node=(TCOD_bsp_t *)TCOD_list_pop(stack2); + if (!listener(node,userData)) { + TCOD_list_delete(stack1); + TCOD_list_delete(stack2); + return false; + } + } + TCOD_list_delete(stack1); + TCOD_list_delete(stack2); + return true; +} + +void TCOD_bsp_remove_sons(TCOD_bsp_t *root) { + TCOD_bsp_t *node=(TCOD_bsp_t *)root->tree.sons; + while ( node ) { + TCOD_bsp_t *nextNode=(TCOD_bsp_t *)node->tree.next; + TCOD_bsp_remove_sons(node); + free( node ); + node=nextNode; + } + root->tree.sons=NULL; +} + +void TCOD_bsp_split_once(TCOD_bsp_t *node, bool horizontal, int position) { + node->horizontal = horizontal; + node->position=position; + TCOD_tree_add_son(&node->tree,&TCOD_bsp_new_intern(node,true)->tree); + TCOD_tree_add_son(&node->tree,&TCOD_bsp_new_intern(node,false)->tree); +} + +void TCOD_bsp_split_recursive(TCOD_bsp_t *node, TCOD_random_t randomizer, int nb, + int minHSize, int minVSize, float maxHRatio, float maxVRatio) { + bool horiz; + int position; + if ( nb == 0 || (node->w < 2*minHSize && node->h < 2*minVSize ) ) return; + if (! randomizer ) randomizer=TCOD_random_get_instance(); + /* promote square rooms */ + if ( node->h < 2*minVSize || node->w > node->h * maxHRatio ) horiz = false; + else if ( node->w < 2*minHSize || node->h > node->w * maxVRatio) horiz = true; + else horiz = (TCOD_random_get_int(randomizer,0,1) == 0); + if ( horiz ) { + position = TCOD_random_get_int(randomizer,node->y+minVSize,node->y+node->h-minVSize); + } else { + position = TCOD_random_get_int(randomizer,node->x+minHSize,node->x+node->w-minHSize); + } + TCOD_bsp_split_once(node,horiz,position); + TCOD_bsp_split_recursive(TCOD_bsp_left(node),randomizer,nb-1,minHSize,minVSize,maxHRatio,maxVRatio); + TCOD_bsp_split_recursive(TCOD_bsp_right(node),randomizer,nb-1,minHSize,minVSize,maxHRatio,maxVRatio); +} + +void TCOD_bsp_resize(TCOD_bsp_t *node, int x,int y, int w, int h) { + node->x=x; + node->y=y; + node->w=w; + node->h=h; + if ( TCOD_bsp_left(node) ) { + if ( node->horizontal ) { + TCOD_bsp_resize(TCOD_bsp_left(node),x,y,w,node->position-y); + TCOD_bsp_resize(TCOD_bsp_right(node),x,node->position,w,y+h-node->position); + } else { + TCOD_bsp_resize(TCOD_bsp_left(node),x,y,node->position-x,h); + TCOD_bsp_resize(TCOD_bsp_right(node),node->position,y,x+w-node->position,h); + } + } +} + +bool TCOD_bsp_contains(TCOD_bsp_t *node, int x, int y) { + return (x >= node->x && y >= node->y && x < node->x+node->w && y < node->y+node->h); +} + +TCOD_bsp_t * TCOD_bsp_find_node(TCOD_bsp_t *node, int x, int y) { + if ( ! TCOD_bsp_contains(node,x,y) ) return NULL; + if ( ! TCOD_bsp_is_leaf(node) ) { + TCOD_bsp_t *left,*right; + left=TCOD_bsp_left(node); + if ( TCOD_bsp_contains(left,x,y) ) return TCOD_bsp_find_node(left,x,y); + right=TCOD_bsp_right(node); + if ( TCOD_bsp_contains(right,x,y) ) return TCOD_bsp_find_node(right,x,y); + } + return node; +} diff --git a/tcod_sys/libtcod/src/color.cpp b/tcod_sys/libtcod/src/libtcod/color.cpp similarity index 98% rename from tcod_sys/libtcod/src/color.cpp rename to tcod_sys/libtcod/src/libtcod/color.cpp index 29e1a167e..7928377dc 100644 --- a/tcod_sys/libtcod/src/color.cpp +++ b/tcod_sys/libtcod/src/libtcod/color.cpp @@ -1,349 +1,349 @@ -/* -* libtcod -* Copyright (c) 2008-2018 Jice & Mingos & rmtew -* All rights reserved. -* -* Redistribution and use in source and binary forms, with or without -* modification, are permitted provided that the following conditions are met: -* * Redistributions of source code must retain the above copyright -* notice, this list of conditions and the following disclaimer. -* * Redistributions in binary form must reproduce the above copyright -* notice, this list of conditions and the following disclaimer in the -* documentation and/or other materials provided with the distribution. -* * The name of Jice or Mingos may not be used to endorse or promote -* products derived from this software without specific prior written -* permission. -* -* THIS SOFTWARE IS PROVIDED BY JICE, MINGOS AND RMTEW ``AS IS'' AND ANY -* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED -* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE -* DISCLAIMED. IN NO EVENT SHALL JICE, MINGOS OR RMTEW BE LIABLE FOR ANY -* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES -* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; -* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND -* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS -* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. -*/ -#include - -#include - -// grey levels -const TCODColor TCODColor::black(TCOD_BLACK); -const TCODColor TCODColor::darkestGrey(TCOD_DARKEST_GREY); -const TCODColor TCODColor::darkerGrey(TCOD_DARKER_GREY); -const TCODColor TCODColor::darkGrey(TCOD_DARK_GREY); -const TCODColor TCODColor::grey(TCOD_GREY); -const TCODColor TCODColor::lightGrey(TCOD_LIGHT_GREY); -const TCODColor TCODColor::lighterGrey(TCOD_LIGHTER_GREY); -const TCODColor TCODColor::lightestGrey(TCOD_LIGHTEST_GREY); -const TCODColor TCODColor::white(TCOD_WHITE); - -//sepia -const TCODColor TCODColor::darkestSepia(TCOD_DARKEST_SEPIA); -const TCODColor TCODColor::darkerSepia(TCOD_DARKER_SEPIA); -const TCODColor TCODColor::darkSepia(TCOD_DARK_SEPIA); -const TCODColor TCODColor::sepia(TCOD_SEPIA); -const TCODColor TCODColor::lightSepia(TCOD_LIGHT_SEPIA); -const TCODColor TCODColor::lighterSepia(TCOD_LIGHTER_SEPIA); -const TCODColor TCODColor::lightestSepia(TCOD_LIGHTEST_SEPIA); - -// standard colors -const TCODColor TCODColor::red(TCOD_RED); -const TCODColor TCODColor::flame(TCOD_FLAME); -const TCODColor TCODColor::orange(TCOD_ORANGE); -const TCODColor TCODColor::amber(TCOD_AMBER); -const TCODColor TCODColor::yellow(TCOD_YELLOW); -const TCODColor TCODColor::lime(TCOD_LIME); -const TCODColor TCODColor::chartreuse(TCOD_CHARTREUSE); -const TCODColor TCODColor::green(TCOD_GREEN); -const TCODColor TCODColor::sea(TCOD_SEA); -const TCODColor TCODColor::turquoise(TCOD_TURQUOISE); -const TCODColor TCODColor::cyan(TCOD_CYAN); -const TCODColor TCODColor::sky(TCOD_SKY); -const TCODColor TCODColor::azure(TCOD_AZURE); -const TCODColor TCODColor::blue(TCOD_BLUE); -const TCODColor TCODColor::han(TCOD_HAN); -const TCODColor TCODColor::violet(TCOD_VIOLET); -const TCODColor TCODColor::purple(TCOD_PURPLE); -const TCODColor TCODColor::fuchsia(TCOD_FUCHSIA); -const TCODColor TCODColor::magenta(TCOD_MAGENTA); -const TCODColor TCODColor::pink(TCOD_PINK); -const TCODColor TCODColor::crimson(TCOD_CRIMSON); - -// dark colors -const TCODColor TCODColor::darkRed(TCOD_DARK_RED); -const TCODColor TCODColor::darkFlame(TCOD_DARK_FLAME); -const TCODColor TCODColor::darkOrange(TCOD_DARK_ORANGE); -const TCODColor TCODColor::darkAmber(TCOD_DARK_AMBER); -const TCODColor TCODColor::darkYellow(TCOD_DARK_YELLOW); -const TCODColor TCODColor::darkLime(TCOD_DARK_LIME); -const TCODColor TCODColor::darkChartreuse(TCOD_DARK_CHARTREUSE); -const TCODColor TCODColor::darkGreen(TCOD_DARK_GREEN); -const TCODColor TCODColor::darkSea(TCOD_DARK_SEA); -const TCODColor TCODColor::darkTurquoise(TCOD_DARK_TURQUOISE); -const TCODColor TCODColor::darkCyan(TCOD_DARK_CYAN); -const TCODColor TCODColor::darkSky(TCOD_DARK_SKY); -const TCODColor TCODColor::darkAzure(TCOD_DARK_AZURE); -const TCODColor TCODColor::darkBlue(TCOD_DARK_BLUE); -const TCODColor TCODColor::darkHan(TCOD_DARK_HAN); -const TCODColor TCODColor::darkViolet(TCOD_DARK_VIOLET); -const TCODColor TCODColor::darkPurple(TCOD_DARK_PURPLE); -const TCODColor TCODColor::darkFuchsia(TCOD_DARK_FUCHSIA); -const TCODColor TCODColor::darkMagenta(TCOD_DARK_MAGENTA); -const TCODColor TCODColor::darkPink(TCOD_DARK_PINK); -const TCODColor TCODColor::darkCrimson(TCOD_DARK_CRIMSON); - -// darker colors -const TCODColor TCODColor::darkerRed(TCOD_DARKER_RED); -const TCODColor TCODColor::darkerFlame(TCOD_DARKER_FLAME); -const TCODColor TCODColor::darkerOrange(TCOD_DARKER_ORANGE); -const TCODColor TCODColor::darkerAmber(TCOD_DARKER_AMBER); -const TCODColor TCODColor::darkerYellow(TCOD_DARKER_YELLOW); -const TCODColor TCODColor::darkerLime(TCOD_DARKER_LIME); -const TCODColor TCODColor::darkerChartreuse(TCOD_DARKER_CHARTREUSE); -const TCODColor TCODColor::darkerGreen(TCOD_DARKER_GREEN); -const TCODColor TCODColor::darkerSea(TCOD_DARKER_SEA); -const TCODColor TCODColor::darkerTurquoise(TCOD_DARKER_TURQUOISE); -const TCODColor TCODColor::darkerCyan(TCOD_DARKER_CYAN); -const TCODColor TCODColor::darkerSky(TCOD_DARKER_SKY); -const TCODColor TCODColor::darkerAzure(TCOD_DARKER_AZURE); -const TCODColor TCODColor::darkerBlue(TCOD_DARKER_BLUE); -const TCODColor TCODColor::darkerHan(TCOD_DARKER_HAN); -const TCODColor TCODColor::darkerViolet(TCOD_DARKER_VIOLET); -const TCODColor TCODColor::darkerPurple(TCOD_DARKER_PURPLE); -const TCODColor TCODColor::darkerFuchsia(TCOD_DARKER_FUCHSIA); -const TCODColor TCODColor::darkerMagenta(TCOD_DARKER_MAGENTA); -const TCODColor TCODColor::darkerPink(TCOD_DARKER_PINK); -const TCODColor TCODColor::darkerCrimson(TCOD_DARKER_CRIMSON); - -// darkest colors -const TCODColor TCODColor::darkestRed(TCOD_DARKEST_RED); -const TCODColor TCODColor::darkestFlame(TCOD_DARKEST_FLAME); -const TCODColor TCODColor::darkestOrange(TCOD_DARKEST_ORANGE); -const TCODColor TCODColor::darkestAmber(TCOD_DARKEST_AMBER); -const TCODColor TCODColor::darkestYellow(TCOD_DARKEST_YELLOW); -const TCODColor TCODColor::darkestLime(TCOD_DARKEST_LIME); -const TCODColor TCODColor::darkestChartreuse(TCOD_DARKEST_CHARTREUSE); -const TCODColor TCODColor::darkestGreen(TCOD_DARKEST_GREEN); -const TCODColor TCODColor::darkestSea(TCOD_DARKEST_SEA); -const TCODColor TCODColor::darkestTurquoise(TCOD_DARKEST_TURQUOISE); -const TCODColor TCODColor::darkestCyan(TCOD_DARKEST_CYAN); -const TCODColor TCODColor::darkestSky(TCOD_DARKEST_SKY); -const TCODColor TCODColor::darkestAzure(TCOD_DARKEST_AZURE); -const TCODColor TCODColor::darkestBlue(TCOD_DARKEST_BLUE); -const TCODColor TCODColor::darkestHan(TCOD_DARKEST_HAN); -const TCODColor TCODColor::darkestViolet(TCOD_DARKEST_VIOLET); -const TCODColor TCODColor::darkestPurple(TCOD_DARKEST_PURPLE); -const TCODColor TCODColor::darkestFuchsia(TCOD_DARKEST_FUCHSIA); -const TCODColor TCODColor::darkestMagenta(TCOD_DARKEST_MAGENTA); -const TCODColor TCODColor::darkestPink(TCOD_DARKEST_PINK); -const TCODColor TCODColor::darkestCrimson(TCOD_DARKEST_CRIMSON); - -// light colors -const TCODColor TCODColor::lightRed(TCOD_LIGHT_RED); -const TCODColor TCODColor::lightFlame(TCOD_LIGHT_FLAME); -const TCODColor TCODColor::lightOrange(TCOD_LIGHT_ORANGE); -const TCODColor TCODColor::lightAmber(TCOD_LIGHT_AMBER); -const TCODColor TCODColor::lightYellow(TCOD_LIGHT_YELLOW); -const TCODColor TCODColor::lightLime(TCOD_LIGHT_LIME); -const TCODColor TCODColor::lightChartreuse(TCOD_LIGHT_CHARTREUSE); -const TCODColor TCODColor::lightGreen(TCOD_LIGHT_GREEN); -const TCODColor TCODColor::lightSea(TCOD_LIGHT_SEA); -const TCODColor TCODColor::lightTurquoise(TCOD_LIGHT_TURQUOISE); -const TCODColor TCODColor::lightCyan(TCOD_LIGHT_CYAN); -const TCODColor TCODColor::lightSky(TCOD_LIGHT_SKY); -const TCODColor TCODColor::lightAzure(TCOD_LIGHT_AZURE); -const TCODColor TCODColor::lightBlue(TCOD_LIGHT_BLUE); -const TCODColor TCODColor::lightHan(TCOD_LIGHT_HAN); -const TCODColor TCODColor::lightViolet(TCOD_LIGHT_VIOLET); -const TCODColor TCODColor::lightPurple(TCOD_LIGHT_PURPLE); -const TCODColor TCODColor::lightFuchsia(TCOD_LIGHT_FUCHSIA); -const TCODColor TCODColor::lightMagenta(TCOD_LIGHT_MAGENTA); -const TCODColor TCODColor::lightPink(TCOD_LIGHT_PINK); -const TCODColor TCODColor::lightCrimson(TCOD_LIGHT_CRIMSON); - -// lighter colors -const TCODColor TCODColor::lighterRed(TCOD_LIGHTER_RED); -const TCODColor TCODColor::lighterFlame(TCOD_LIGHTER_FLAME); -const TCODColor TCODColor::lighterOrange(TCOD_LIGHTER_ORANGE); -const TCODColor TCODColor::lighterAmber(TCOD_LIGHTER_AMBER); -const TCODColor TCODColor::lighterYellow(TCOD_LIGHTER_YELLOW); -const TCODColor TCODColor::lighterLime(TCOD_LIGHTER_LIME); -const TCODColor TCODColor::lighterChartreuse(TCOD_LIGHTER_CHARTREUSE); -const TCODColor TCODColor::lighterGreen(TCOD_LIGHTER_GREEN); -const TCODColor TCODColor::lighterSea(TCOD_LIGHTER_SEA); -const TCODColor TCODColor::lighterTurquoise(TCOD_LIGHTER_TURQUOISE); -const TCODColor TCODColor::lighterCyan(TCOD_LIGHTER_CYAN); -const TCODColor TCODColor::lighterSky(TCOD_LIGHTER_SKY); -const TCODColor TCODColor::lighterAzure(TCOD_LIGHTER_AZURE); -const TCODColor TCODColor::lighterBlue(TCOD_LIGHTER_BLUE); -const TCODColor TCODColor::lighterHan(TCOD_LIGHTER_HAN); -const TCODColor TCODColor::lighterViolet(TCOD_LIGHTER_VIOLET); -const TCODColor TCODColor::lighterPurple(TCOD_LIGHTER_PURPLE); -const TCODColor TCODColor::lighterFuchsia(TCOD_LIGHTER_FUCHSIA); -const TCODColor TCODColor::lighterMagenta(TCOD_LIGHTER_MAGENTA); -const TCODColor TCODColor::lighterPink(TCOD_LIGHTER_PINK); -const TCODColor TCODColor::lighterCrimson(TCOD_LIGHTER_CRIMSON); - -// lightest colors -const TCODColor TCODColor::lightestRed(TCOD_LIGHTEST_RED); -const TCODColor TCODColor::lightestFlame(TCOD_LIGHTEST_FLAME); -const TCODColor TCODColor::lightestOrange(TCOD_LIGHTEST_ORANGE); -const TCODColor TCODColor::lightestAmber(TCOD_LIGHTEST_AMBER); -const TCODColor TCODColor::lightestYellow(TCOD_LIGHTEST_YELLOW); -const TCODColor TCODColor::lightestLime(TCOD_LIGHTEST_LIME); -const TCODColor TCODColor::lightestChartreuse(TCOD_LIGHTEST_CHARTREUSE); -const TCODColor TCODColor::lightestGreen(TCOD_LIGHTEST_GREEN); -const TCODColor TCODColor::lightestSea(TCOD_LIGHTEST_SEA); -const TCODColor TCODColor::lightestTurquoise(TCOD_LIGHTEST_TURQUOISE); -const TCODColor TCODColor::lightestCyan(TCOD_LIGHTEST_CYAN); -const TCODColor TCODColor::lightestSky(TCOD_LIGHTEST_SKY); -const TCODColor TCODColor::lightestAzure(TCOD_LIGHTEST_AZURE); -const TCODColor TCODColor::lightestBlue(TCOD_LIGHTEST_BLUE); -const TCODColor TCODColor::lightestHan(TCOD_LIGHTEST_HAN); -const TCODColor TCODColor::lightestViolet(TCOD_LIGHTEST_VIOLET); -const TCODColor TCODColor::lightestPurple(TCOD_LIGHTEST_PURPLE); -const TCODColor TCODColor::lightestFuchsia(TCOD_LIGHTEST_FUCHSIA); -const TCODColor TCODColor::lightestMagenta(TCOD_LIGHTEST_MAGENTA); -const TCODColor TCODColor::lightestPink(TCOD_LIGHTEST_PINK); -const TCODColor TCODColor::lightestCrimson(TCOD_LIGHTEST_CRIMSON); - -// desaturated colors -const TCODColor TCODColor::desaturatedRed(TCOD_DESATURATED_RED); -const TCODColor TCODColor::desaturatedFlame(TCOD_DESATURATED_FLAME); -const TCODColor TCODColor::desaturatedOrange(TCOD_DESATURATED_ORANGE); -const TCODColor TCODColor::desaturatedAmber(TCOD_DESATURATED_AMBER); -const TCODColor TCODColor::desaturatedYellow(TCOD_DESATURATED_YELLOW); -const TCODColor TCODColor::desaturatedLime(TCOD_DESATURATED_LIME); -const TCODColor TCODColor::desaturatedChartreuse(TCOD_DESATURATED_CHARTREUSE); -const TCODColor TCODColor::desaturatedGreen(TCOD_DESATURATED_GREEN); -const TCODColor TCODColor::desaturatedSea(TCOD_DESATURATED_SEA); -const TCODColor TCODColor::desaturatedTurquoise(TCOD_DESATURATED_TURQUOISE); -const TCODColor TCODColor::desaturatedCyan(TCOD_DESATURATED_CYAN); -const TCODColor TCODColor::desaturatedSky(TCOD_DESATURATED_SKY); -const TCODColor TCODColor::desaturatedAzure(TCOD_DESATURATED_AZURE); -const TCODColor TCODColor::desaturatedBlue(TCOD_DESATURATED_BLUE); -const TCODColor TCODColor::desaturatedHan(TCOD_DESATURATED_HAN); -const TCODColor TCODColor::desaturatedViolet(TCOD_DESATURATED_VIOLET); -const TCODColor TCODColor::desaturatedPurple(TCOD_DESATURATED_PURPLE); -const TCODColor TCODColor::desaturatedFuchsia(TCOD_DESATURATED_FUCHSIA); -const TCODColor TCODColor::desaturatedMagenta(TCOD_DESATURATED_MAGENTA); -const TCODColor TCODColor::desaturatedPink(TCOD_DESATURATED_PINK); -const TCODColor TCODColor::desaturatedCrimson(TCOD_DESATURATED_CRIMSON); - -//special -const TCODColor TCODColor::brass(TCOD_BRASS); -const TCODColor TCODColor::copper(TCOD_COPPER); -const TCODColor TCODColor::gold(TCOD_GOLD); -const TCODColor TCODColor::silver(TCOD_SILVER); - -//miscellaneous -const TCODColor TCODColor::celadon(TCOD_CELADON); -const TCODColor TCODColor::peach(TCOD_PEACH); - -#ifndef TCOD_HAIKU -// color array -const TCODColor TCODColor::colors[TCOD_COLOR_NB][TCOD_COLOR_LEVELS] = { - {TCODColor(TCOD_DESATURATED_RED),TCODColor(TCOD_LIGHTEST_RED),TCODColor(TCOD_LIGHTER_RED),TCODColor(TCOD_LIGHT_RED),TCODColor(TCOD_RED),TCODColor(TCOD_DARK_RED),TCODColor(TCOD_DARKER_RED),TCODColor(TCOD_DARKEST_RED)}, - {TCODColor(TCOD_DESATURATED_FLAME),TCODColor(TCOD_LIGHTEST_FLAME),TCODColor(TCOD_LIGHTER_FLAME),TCODColor(TCOD_LIGHT_FLAME),TCODColor(TCOD_FLAME),TCODColor(TCOD_DARK_FLAME),TCODColor(TCOD_DARKER_FLAME),TCODColor(TCOD_DARKEST_FLAME)}, - {TCODColor(TCOD_DESATURATED_ORANGE),TCODColor(TCOD_LIGHTEST_ORANGE),TCODColor(TCOD_LIGHTER_ORANGE),TCODColor(TCOD_LIGHT_ORANGE),TCODColor(TCOD_ORANGE),TCODColor(TCOD_DARK_ORANGE),TCODColor(TCOD_DARKER_ORANGE),TCODColor(TCOD_DARKEST_ORANGE)}, - {TCODColor(TCOD_DESATURATED_AMBER),TCODColor(TCOD_LIGHTEST_AMBER),TCODColor(TCOD_LIGHTER_AMBER),TCODColor(TCOD_LIGHT_AMBER),TCODColor(TCOD_AMBER),TCODColor(TCOD_DARK_AMBER),TCODColor(TCOD_DARKER_AMBER),TCODColor(TCOD_DARKEST_AMBER)}, - {TCODColor(TCOD_DESATURATED_YELLOW),TCODColor(TCOD_LIGHTEST_YELLOW),TCODColor(TCOD_LIGHTER_YELLOW),TCODColor(TCOD_LIGHT_YELLOW),TCODColor(TCOD_YELLOW),TCODColor(TCOD_DARK_YELLOW),TCODColor(TCOD_DARKER_YELLOW),TCODColor(TCOD_DARKEST_YELLOW)}, - {TCODColor(TCOD_DESATURATED_LIME),TCODColor(TCOD_LIGHTEST_LIME),TCODColor(TCOD_LIGHTER_LIME),TCODColor(TCOD_LIGHT_LIME),TCODColor(TCOD_LIME),TCODColor(TCOD_DARK_LIME),TCODColor(TCOD_DARKER_LIME),TCODColor(TCOD_DARKEST_LIME)}, - {TCODColor(TCOD_DESATURATED_CHARTREUSE),TCODColor(TCOD_LIGHTEST_CHARTREUSE),TCODColor(TCOD_LIGHTER_CHARTREUSE),TCODColor(TCOD_LIGHT_CHARTREUSE),TCODColor(TCOD_CHARTREUSE),TCODColor(TCOD_DARK_CHARTREUSE),TCODColor(TCOD_DARKER_CHARTREUSE),TCODColor(TCOD_DARKEST_CHARTREUSE)}, - {TCODColor(TCOD_DESATURATED_GREEN),TCODColor(TCOD_LIGHTEST_GREEN),TCODColor(TCOD_LIGHTER_GREEN),TCODColor(TCOD_LIGHT_GREEN),TCODColor(TCOD_GREEN),TCODColor(TCOD_DARK_GREEN),TCODColor(TCOD_DARKER_GREEN),TCODColor(TCOD_DARKEST_GREEN)}, - {TCODColor(TCOD_DESATURATED_SEA),TCODColor(TCOD_LIGHTEST_SEA),TCODColor(TCOD_LIGHTER_SEA),TCODColor(TCOD_LIGHT_SEA),TCODColor(TCOD_SEA),TCODColor(TCOD_DARK_SEA),TCODColor(TCOD_DARKER_SEA),TCODColor(TCOD_DARKEST_SEA)}, - {TCODColor(TCOD_DESATURATED_TURQUOISE),TCODColor(TCOD_LIGHTEST_TURQUOISE),TCODColor(TCOD_LIGHTER_TURQUOISE),TCODColor(TCOD_LIGHT_TURQUOISE),TCODColor(TCOD_TURQUOISE),TCODColor(TCOD_DARK_TURQUOISE),TCODColor(TCOD_DARKER_TURQUOISE),TCODColor(TCOD_DARKEST_TURQUOISE)}, - {TCODColor(TCOD_DESATURATED_CYAN),TCODColor(TCOD_LIGHTEST_CYAN),TCODColor(TCOD_LIGHTER_CYAN),TCODColor(TCOD_LIGHT_CYAN),TCODColor(TCOD_CYAN),TCODColor(TCOD_DARK_CYAN),TCODColor(TCOD_DARKER_CYAN),TCODColor(TCOD_DARKEST_CYAN)}, - {TCODColor(TCOD_DESATURATED_SKY),TCODColor(TCOD_LIGHTEST_SKY),TCODColor(TCOD_LIGHTER_SKY),TCODColor(TCOD_LIGHT_SKY),TCODColor(TCOD_SKY),TCODColor(TCOD_DARK_SKY),TCODColor(TCOD_DARKER_SKY),TCODColor(TCOD_DARKEST_SKY)}, - {TCODColor(TCOD_DESATURATED_AZURE),TCODColor(TCOD_LIGHTEST_AZURE),TCODColor(TCOD_LIGHTER_AZURE),TCODColor(TCOD_LIGHT_AZURE),TCODColor(TCOD_AZURE),TCODColor(TCOD_DARK_AZURE),TCODColor(TCOD_DARKER_AZURE),TCODColor(TCOD_DARKEST_AZURE)}, - {TCODColor(TCOD_DESATURATED_BLUE),TCODColor(TCOD_LIGHTEST_BLUE),TCODColor(TCOD_LIGHTER_BLUE),TCODColor(TCOD_LIGHT_BLUE),TCODColor(TCOD_BLUE),TCODColor(TCOD_DARK_BLUE),TCODColor(TCOD_DARKER_BLUE),TCODColor(TCOD_DARKEST_BLUE)}, - {TCODColor(TCOD_DESATURATED_HAN),TCODColor(TCOD_LIGHTEST_HAN),TCODColor(TCOD_LIGHTER_HAN),TCODColor(TCOD_LIGHT_HAN),TCODColor(TCOD_HAN),TCODColor(TCOD_DARK_HAN),TCODColor(TCOD_DARKER_HAN),TCODColor(TCOD_DARKEST_HAN)}, - {TCODColor(TCOD_DESATURATED_VIOLET),TCODColor(TCOD_LIGHTEST_VIOLET),TCODColor(TCOD_LIGHTER_VIOLET),TCODColor(TCOD_LIGHT_VIOLET),TCODColor(TCOD_VIOLET),TCODColor(TCOD_DARK_VIOLET),TCODColor(TCOD_DARKER_VIOLET),TCODColor(TCOD_DARKEST_VIOLET)}, - {TCODColor(TCOD_DESATURATED_PURPLE),TCODColor(TCOD_LIGHTEST_PURPLE),TCODColor(TCOD_LIGHTER_PURPLE),TCODColor(TCOD_LIGHT_PURPLE),TCODColor(TCOD_PURPLE),TCODColor(TCOD_DARK_PURPLE),TCODColor(TCOD_DARKER_PURPLE),TCODColor(TCOD_DARKEST_PURPLE)}, - {TCODColor(TCOD_DESATURATED_FUCHSIA),TCODColor(TCOD_LIGHTEST_FUCHSIA),TCODColor(TCOD_LIGHTER_FUCHSIA),TCODColor(TCOD_LIGHT_FUCHSIA),TCODColor(TCOD_FUCHSIA),TCODColor(TCOD_DARK_FUCHSIA),TCODColor(TCOD_DARKER_FUCHSIA),TCODColor(TCOD_DARKEST_FUCHSIA)}, - {TCODColor(TCOD_DESATURATED_MAGENTA),TCODColor(TCOD_LIGHTEST_MAGENTA),TCODColor(TCOD_LIGHTER_MAGENTA),TCODColor(TCOD_LIGHT_MAGENTA),TCODColor(TCOD_MAGENTA),TCODColor(TCOD_DARK_MAGENTA),TCODColor(TCOD_DARKER_MAGENTA),TCODColor(TCOD_DARKEST_MAGENTA)}, - {TCODColor(TCOD_DESATURATED_PINK),TCODColor(TCOD_LIGHTEST_PINK),TCODColor(TCOD_LIGHTER_PINK),TCODColor(TCOD_LIGHT_PINK),TCODColor(TCOD_PINK),TCODColor(TCOD_DARK_PINK),TCODColor(TCOD_DARKER_PINK),TCODColor(TCOD_DARKEST_PINK)}, - {TCODColor(TCOD_DESATURATED_CRIMSON),TCODColor(TCOD_LIGHTEST_CRIMSON),TCODColor(TCOD_LIGHTER_CRIMSON),TCODColor(TCOD_LIGHT_CRIMSON),TCODColor(TCOD_CRIMSON),TCODColor(TCOD_DARK_CRIMSON),TCODColor(TCOD_DARKER_CRIMSON),TCODColor(TCOD_DARKEST_CRIMSON)} -}; -#endif - -TCODColor::TCODColor(float h, float s, float v) { - //setHSV(h,s,v); - TCOD_color_t c = TCOD_color_HSV(h,s,v); - r = c.r; g = c.g; b = c.b; -} - -void TCODColor::setHSV(float h, float s, float v) { - TCOD_color_t c; - TCOD_color_set_HSV(&c,h,s,v); - r = c.r; g = c.g; b = c.b; -} - -void TCODColor::setHue (float h) { - TCOD_color_t c = { r, g, b }; - TCOD_color_set_hue (&c, h); - r = c.r; g = c.g; b = c.b; -} - -void TCODColor::setSaturation (float s) { - TCOD_color_t c = { r, g, b }; - TCOD_color_set_saturation (&c, s); - r = c.r; g = c.g; b = c.b; -} - -void TCODColor::setValue (float v) { - TCOD_color_t c = { r, g, b }; - TCOD_color_set_value (&c, v); - r = c.r; g = c.g; b = c.b; -} - -void TCODColor::getHSV(float *h, float *s, float *v) const { - TCOD_color_t c={r,g,b}; - TCOD_color_get_HSV(c,h,s,v); -} - -float TCODColor::getHue () { - TCOD_color_t c = { r, g, b }; - return TCOD_color_get_hue(c); -} - -float TCODColor::getSaturation () { - TCOD_color_t c = { r, g, b }; - return TCOD_color_get_saturation(c); -} - -float TCODColor::getValue () { - TCOD_color_t c = { r, g, b }; - return TCOD_color_get_value(c); -} - -void TCODColor::shiftHue (float hshift) { - TCOD_color_t c = { r, g, b }; - TCOD_color_shift_hue (&c, hshift); - r = c.r; g = c.g; b = c.b; -} - -void TCODColor::scaleHSV (float sscale, float vscale) { - TCOD_color_t c = {r,g,b}; - TCOD_color_scale_HSV(&c,sscale,vscale); - r = c.r; g = c.g; b = c.b; -} - -// non member operators -TCODColor operator *(float value, const TCODColor &c) { - return c*value; -} - -void TCODColor::genMap(TCODColor *map, int nbKey, TCODColor const *keyColor, int const *keyIndex) { - for (int segment=0; segment < nbKey-1; segment++) { - int idxStart=keyIndex[segment]; - int idxEnd=keyIndex[segment+1]; - int idx; - for ( idx=idxStart;idx <= idxEnd; idx++) { - map[idx]=TCODColor::lerp(keyColor[segment],keyColor[segment+1],(float)(idx-idxStart)/(idxEnd-idxStart)); - } - } -} +/* +* libtcod +* Copyright (c) 2008-2018 Jice & Mingos & rmtew +* All rights reserved. +* +* Redistribution and use in source and binary forms, with or without +* modification, are permitted provided that the following conditions are met: +* * Redistributions of source code must retain the above copyright +* notice, this list of conditions and the following disclaimer. +* * Redistributions in binary form must reproduce the above copyright +* notice, this list of conditions and the following disclaimer in the +* documentation and/or other materials provided with the distribution. +* * The name of Jice or Mingos may not be used to endorse or promote +* products derived from this software without specific prior written +* permission. +* +* THIS SOFTWARE IS PROVIDED BY JICE, MINGOS AND RMTEW ``AS IS'' AND ANY +* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED +* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE +* DISCLAIMED. IN NO EVENT SHALL JICE, MINGOS OR RMTEW BE LIABLE FOR ANY +* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES +* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; +* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND +* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS +* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +*/ +#include "color.hpp" + +#include "libtcod_int.h" + +// grey levels +const TCODColor TCODColor::black(TCOD_BLACK); +const TCODColor TCODColor::darkestGrey(TCOD_DARKEST_GREY); +const TCODColor TCODColor::darkerGrey(TCOD_DARKER_GREY); +const TCODColor TCODColor::darkGrey(TCOD_DARK_GREY); +const TCODColor TCODColor::grey(TCOD_GREY); +const TCODColor TCODColor::lightGrey(TCOD_LIGHT_GREY); +const TCODColor TCODColor::lighterGrey(TCOD_LIGHTER_GREY); +const TCODColor TCODColor::lightestGrey(TCOD_LIGHTEST_GREY); +const TCODColor TCODColor::white(TCOD_WHITE); + +//sepia +const TCODColor TCODColor::darkestSepia(TCOD_DARKEST_SEPIA); +const TCODColor TCODColor::darkerSepia(TCOD_DARKER_SEPIA); +const TCODColor TCODColor::darkSepia(TCOD_DARK_SEPIA); +const TCODColor TCODColor::sepia(TCOD_SEPIA); +const TCODColor TCODColor::lightSepia(TCOD_LIGHT_SEPIA); +const TCODColor TCODColor::lighterSepia(TCOD_LIGHTER_SEPIA); +const TCODColor TCODColor::lightestSepia(TCOD_LIGHTEST_SEPIA); + +// standard colors +const TCODColor TCODColor::red(TCOD_RED); +const TCODColor TCODColor::flame(TCOD_FLAME); +const TCODColor TCODColor::orange(TCOD_ORANGE); +const TCODColor TCODColor::amber(TCOD_AMBER); +const TCODColor TCODColor::yellow(TCOD_YELLOW); +const TCODColor TCODColor::lime(TCOD_LIME); +const TCODColor TCODColor::chartreuse(TCOD_CHARTREUSE); +const TCODColor TCODColor::green(TCOD_GREEN); +const TCODColor TCODColor::sea(TCOD_SEA); +const TCODColor TCODColor::turquoise(TCOD_TURQUOISE); +const TCODColor TCODColor::cyan(TCOD_CYAN); +const TCODColor TCODColor::sky(TCOD_SKY); +const TCODColor TCODColor::azure(TCOD_AZURE); +const TCODColor TCODColor::blue(TCOD_BLUE); +const TCODColor TCODColor::han(TCOD_HAN); +const TCODColor TCODColor::violet(TCOD_VIOLET); +const TCODColor TCODColor::purple(TCOD_PURPLE); +const TCODColor TCODColor::fuchsia(TCOD_FUCHSIA); +const TCODColor TCODColor::magenta(TCOD_MAGENTA); +const TCODColor TCODColor::pink(TCOD_PINK); +const TCODColor TCODColor::crimson(TCOD_CRIMSON); + +// dark colors +const TCODColor TCODColor::darkRed(TCOD_DARK_RED); +const TCODColor TCODColor::darkFlame(TCOD_DARK_FLAME); +const TCODColor TCODColor::darkOrange(TCOD_DARK_ORANGE); +const TCODColor TCODColor::darkAmber(TCOD_DARK_AMBER); +const TCODColor TCODColor::darkYellow(TCOD_DARK_YELLOW); +const TCODColor TCODColor::darkLime(TCOD_DARK_LIME); +const TCODColor TCODColor::darkChartreuse(TCOD_DARK_CHARTREUSE); +const TCODColor TCODColor::darkGreen(TCOD_DARK_GREEN); +const TCODColor TCODColor::darkSea(TCOD_DARK_SEA); +const TCODColor TCODColor::darkTurquoise(TCOD_DARK_TURQUOISE); +const TCODColor TCODColor::darkCyan(TCOD_DARK_CYAN); +const TCODColor TCODColor::darkSky(TCOD_DARK_SKY); +const TCODColor TCODColor::darkAzure(TCOD_DARK_AZURE); +const TCODColor TCODColor::darkBlue(TCOD_DARK_BLUE); +const TCODColor TCODColor::darkHan(TCOD_DARK_HAN); +const TCODColor TCODColor::darkViolet(TCOD_DARK_VIOLET); +const TCODColor TCODColor::darkPurple(TCOD_DARK_PURPLE); +const TCODColor TCODColor::darkFuchsia(TCOD_DARK_FUCHSIA); +const TCODColor TCODColor::darkMagenta(TCOD_DARK_MAGENTA); +const TCODColor TCODColor::darkPink(TCOD_DARK_PINK); +const TCODColor TCODColor::darkCrimson(TCOD_DARK_CRIMSON); + +// darker colors +const TCODColor TCODColor::darkerRed(TCOD_DARKER_RED); +const TCODColor TCODColor::darkerFlame(TCOD_DARKER_FLAME); +const TCODColor TCODColor::darkerOrange(TCOD_DARKER_ORANGE); +const TCODColor TCODColor::darkerAmber(TCOD_DARKER_AMBER); +const TCODColor TCODColor::darkerYellow(TCOD_DARKER_YELLOW); +const TCODColor TCODColor::darkerLime(TCOD_DARKER_LIME); +const TCODColor TCODColor::darkerChartreuse(TCOD_DARKER_CHARTREUSE); +const TCODColor TCODColor::darkerGreen(TCOD_DARKER_GREEN); +const TCODColor TCODColor::darkerSea(TCOD_DARKER_SEA); +const TCODColor TCODColor::darkerTurquoise(TCOD_DARKER_TURQUOISE); +const TCODColor TCODColor::darkerCyan(TCOD_DARKER_CYAN); +const TCODColor TCODColor::darkerSky(TCOD_DARKER_SKY); +const TCODColor TCODColor::darkerAzure(TCOD_DARKER_AZURE); +const TCODColor TCODColor::darkerBlue(TCOD_DARKER_BLUE); +const TCODColor TCODColor::darkerHan(TCOD_DARKER_HAN); +const TCODColor TCODColor::darkerViolet(TCOD_DARKER_VIOLET); +const TCODColor TCODColor::darkerPurple(TCOD_DARKER_PURPLE); +const TCODColor TCODColor::darkerFuchsia(TCOD_DARKER_FUCHSIA); +const TCODColor TCODColor::darkerMagenta(TCOD_DARKER_MAGENTA); +const TCODColor TCODColor::darkerPink(TCOD_DARKER_PINK); +const TCODColor TCODColor::darkerCrimson(TCOD_DARKER_CRIMSON); + +// darkest colors +const TCODColor TCODColor::darkestRed(TCOD_DARKEST_RED); +const TCODColor TCODColor::darkestFlame(TCOD_DARKEST_FLAME); +const TCODColor TCODColor::darkestOrange(TCOD_DARKEST_ORANGE); +const TCODColor TCODColor::darkestAmber(TCOD_DARKEST_AMBER); +const TCODColor TCODColor::darkestYellow(TCOD_DARKEST_YELLOW); +const TCODColor TCODColor::darkestLime(TCOD_DARKEST_LIME); +const TCODColor TCODColor::darkestChartreuse(TCOD_DARKEST_CHARTREUSE); +const TCODColor TCODColor::darkestGreen(TCOD_DARKEST_GREEN); +const TCODColor TCODColor::darkestSea(TCOD_DARKEST_SEA); +const TCODColor TCODColor::darkestTurquoise(TCOD_DARKEST_TURQUOISE); +const TCODColor TCODColor::darkestCyan(TCOD_DARKEST_CYAN); +const TCODColor TCODColor::darkestSky(TCOD_DARKEST_SKY); +const TCODColor TCODColor::darkestAzure(TCOD_DARKEST_AZURE); +const TCODColor TCODColor::darkestBlue(TCOD_DARKEST_BLUE); +const TCODColor TCODColor::darkestHan(TCOD_DARKEST_HAN); +const TCODColor TCODColor::darkestViolet(TCOD_DARKEST_VIOLET); +const TCODColor TCODColor::darkestPurple(TCOD_DARKEST_PURPLE); +const TCODColor TCODColor::darkestFuchsia(TCOD_DARKEST_FUCHSIA); +const TCODColor TCODColor::darkestMagenta(TCOD_DARKEST_MAGENTA); +const TCODColor TCODColor::darkestPink(TCOD_DARKEST_PINK); +const TCODColor TCODColor::darkestCrimson(TCOD_DARKEST_CRIMSON); + +// light colors +const TCODColor TCODColor::lightRed(TCOD_LIGHT_RED); +const TCODColor TCODColor::lightFlame(TCOD_LIGHT_FLAME); +const TCODColor TCODColor::lightOrange(TCOD_LIGHT_ORANGE); +const TCODColor TCODColor::lightAmber(TCOD_LIGHT_AMBER); +const TCODColor TCODColor::lightYellow(TCOD_LIGHT_YELLOW); +const TCODColor TCODColor::lightLime(TCOD_LIGHT_LIME); +const TCODColor TCODColor::lightChartreuse(TCOD_LIGHT_CHARTREUSE); +const TCODColor TCODColor::lightGreen(TCOD_LIGHT_GREEN); +const TCODColor TCODColor::lightSea(TCOD_LIGHT_SEA); +const TCODColor TCODColor::lightTurquoise(TCOD_LIGHT_TURQUOISE); +const TCODColor TCODColor::lightCyan(TCOD_LIGHT_CYAN); +const TCODColor TCODColor::lightSky(TCOD_LIGHT_SKY); +const TCODColor TCODColor::lightAzure(TCOD_LIGHT_AZURE); +const TCODColor TCODColor::lightBlue(TCOD_LIGHT_BLUE); +const TCODColor TCODColor::lightHan(TCOD_LIGHT_HAN); +const TCODColor TCODColor::lightViolet(TCOD_LIGHT_VIOLET); +const TCODColor TCODColor::lightPurple(TCOD_LIGHT_PURPLE); +const TCODColor TCODColor::lightFuchsia(TCOD_LIGHT_FUCHSIA); +const TCODColor TCODColor::lightMagenta(TCOD_LIGHT_MAGENTA); +const TCODColor TCODColor::lightPink(TCOD_LIGHT_PINK); +const TCODColor TCODColor::lightCrimson(TCOD_LIGHT_CRIMSON); + +// lighter colors +const TCODColor TCODColor::lighterRed(TCOD_LIGHTER_RED); +const TCODColor TCODColor::lighterFlame(TCOD_LIGHTER_FLAME); +const TCODColor TCODColor::lighterOrange(TCOD_LIGHTER_ORANGE); +const TCODColor TCODColor::lighterAmber(TCOD_LIGHTER_AMBER); +const TCODColor TCODColor::lighterYellow(TCOD_LIGHTER_YELLOW); +const TCODColor TCODColor::lighterLime(TCOD_LIGHTER_LIME); +const TCODColor TCODColor::lighterChartreuse(TCOD_LIGHTER_CHARTREUSE); +const TCODColor TCODColor::lighterGreen(TCOD_LIGHTER_GREEN); +const TCODColor TCODColor::lighterSea(TCOD_LIGHTER_SEA); +const TCODColor TCODColor::lighterTurquoise(TCOD_LIGHTER_TURQUOISE); +const TCODColor TCODColor::lighterCyan(TCOD_LIGHTER_CYAN); +const TCODColor TCODColor::lighterSky(TCOD_LIGHTER_SKY); +const TCODColor TCODColor::lighterAzure(TCOD_LIGHTER_AZURE); +const TCODColor TCODColor::lighterBlue(TCOD_LIGHTER_BLUE); +const TCODColor TCODColor::lighterHan(TCOD_LIGHTER_HAN); +const TCODColor TCODColor::lighterViolet(TCOD_LIGHTER_VIOLET); +const TCODColor TCODColor::lighterPurple(TCOD_LIGHTER_PURPLE); +const TCODColor TCODColor::lighterFuchsia(TCOD_LIGHTER_FUCHSIA); +const TCODColor TCODColor::lighterMagenta(TCOD_LIGHTER_MAGENTA); +const TCODColor TCODColor::lighterPink(TCOD_LIGHTER_PINK); +const TCODColor TCODColor::lighterCrimson(TCOD_LIGHTER_CRIMSON); + +// lightest colors +const TCODColor TCODColor::lightestRed(TCOD_LIGHTEST_RED); +const TCODColor TCODColor::lightestFlame(TCOD_LIGHTEST_FLAME); +const TCODColor TCODColor::lightestOrange(TCOD_LIGHTEST_ORANGE); +const TCODColor TCODColor::lightestAmber(TCOD_LIGHTEST_AMBER); +const TCODColor TCODColor::lightestYellow(TCOD_LIGHTEST_YELLOW); +const TCODColor TCODColor::lightestLime(TCOD_LIGHTEST_LIME); +const TCODColor TCODColor::lightestChartreuse(TCOD_LIGHTEST_CHARTREUSE); +const TCODColor TCODColor::lightestGreen(TCOD_LIGHTEST_GREEN); +const TCODColor TCODColor::lightestSea(TCOD_LIGHTEST_SEA); +const TCODColor TCODColor::lightestTurquoise(TCOD_LIGHTEST_TURQUOISE); +const TCODColor TCODColor::lightestCyan(TCOD_LIGHTEST_CYAN); +const TCODColor TCODColor::lightestSky(TCOD_LIGHTEST_SKY); +const TCODColor TCODColor::lightestAzure(TCOD_LIGHTEST_AZURE); +const TCODColor TCODColor::lightestBlue(TCOD_LIGHTEST_BLUE); +const TCODColor TCODColor::lightestHan(TCOD_LIGHTEST_HAN); +const TCODColor TCODColor::lightestViolet(TCOD_LIGHTEST_VIOLET); +const TCODColor TCODColor::lightestPurple(TCOD_LIGHTEST_PURPLE); +const TCODColor TCODColor::lightestFuchsia(TCOD_LIGHTEST_FUCHSIA); +const TCODColor TCODColor::lightestMagenta(TCOD_LIGHTEST_MAGENTA); +const TCODColor TCODColor::lightestPink(TCOD_LIGHTEST_PINK); +const TCODColor TCODColor::lightestCrimson(TCOD_LIGHTEST_CRIMSON); + +// desaturated colors +const TCODColor TCODColor::desaturatedRed(TCOD_DESATURATED_RED); +const TCODColor TCODColor::desaturatedFlame(TCOD_DESATURATED_FLAME); +const TCODColor TCODColor::desaturatedOrange(TCOD_DESATURATED_ORANGE); +const TCODColor TCODColor::desaturatedAmber(TCOD_DESATURATED_AMBER); +const TCODColor TCODColor::desaturatedYellow(TCOD_DESATURATED_YELLOW); +const TCODColor TCODColor::desaturatedLime(TCOD_DESATURATED_LIME); +const TCODColor TCODColor::desaturatedChartreuse(TCOD_DESATURATED_CHARTREUSE); +const TCODColor TCODColor::desaturatedGreen(TCOD_DESATURATED_GREEN); +const TCODColor TCODColor::desaturatedSea(TCOD_DESATURATED_SEA); +const TCODColor TCODColor::desaturatedTurquoise(TCOD_DESATURATED_TURQUOISE); +const TCODColor TCODColor::desaturatedCyan(TCOD_DESATURATED_CYAN); +const TCODColor TCODColor::desaturatedSky(TCOD_DESATURATED_SKY); +const TCODColor TCODColor::desaturatedAzure(TCOD_DESATURATED_AZURE); +const TCODColor TCODColor::desaturatedBlue(TCOD_DESATURATED_BLUE); +const TCODColor TCODColor::desaturatedHan(TCOD_DESATURATED_HAN); +const TCODColor TCODColor::desaturatedViolet(TCOD_DESATURATED_VIOLET); +const TCODColor TCODColor::desaturatedPurple(TCOD_DESATURATED_PURPLE); +const TCODColor TCODColor::desaturatedFuchsia(TCOD_DESATURATED_FUCHSIA); +const TCODColor TCODColor::desaturatedMagenta(TCOD_DESATURATED_MAGENTA); +const TCODColor TCODColor::desaturatedPink(TCOD_DESATURATED_PINK); +const TCODColor TCODColor::desaturatedCrimson(TCOD_DESATURATED_CRIMSON); + +//special +const TCODColor TCODColor::brass(TCOD_BRASS); +const TCODColor TCODColor::copper(TCOD_COPPER); +const TCODColor TCODColor::gold(TCOD_GOLD); +const TCODColor TCODColor::silver(TCOD_SILVER); + +//miscellaneous +const TCODColor TCODColor::celadon(TCOD_CELADON); +const TCODColor TCODColor::peach(TCOD_PEACH); + +#ifndef TCOD_HAIKU +// color array +const TCODColor TCODColor::colors[TCOD_COLOR_NB][TCOD_COLOR_LEVELS] = { + {TCODColor(TCOD_DESATURATED_RED),TCODColor(TCOD_LIGHTEST_RED),TCODColor(TCOD_LIGHTER_RED),TCODColor(TCOD_LIGHT_RED),TCODColor(TCOD_RED),TCODColor(TCOD_DARK_RED),TCODColor(TCOD_DARKER_RED),TCODColor(TCOD_DARKEST_RED)}, + {TCODColor(TCOD_DESATURATED_FLAME),TCODColor(TCOD_LIGHTEST_FLAME),TCODColor(TCOD_LIGHTER_FLAME),TCODColor(TCOD_LIGHT_FLAME),TCODColor(TCOD_FLAME),TCODColor(TCOD_DARK_FLAME),TCODColor(TCOD_DARKER_FLAME),TCODColor(TCOD_DARKEST_FLAME)}, + {TCODColor(TCOD_DESATURATED_ORANGE),TCODColor(TCOD_LIGHTEST_ORANGE),TCODColor(TCOD_LIGHTER_ORANGE),TCODColor(TCOD_LIGHT_ORANGE),TCODColor(TCOD_ORANGE),TCODColor(TCOD_DARK_ORANGE),TCODColor(TCOD_DARKER_ORANGE),TCODColor(TCOD_DARKEST_ORANGE)}, + {TCODColor(TCOD_DESATURATED_AMBER),TCODColor(TCOD_LIGHTEST_AMBER),TCODColor(TCOD_LIGHTER_AMBER),TCODColor(TCOD_LIGHT_AMBER),TCODColor(TCOD_AMBER),TCODColor(TCOD_DARK_AMBER),TCODColor(TCOD_DARKER_AMBER),TCODColor(TCOD_DARKEST_AMBER)}, + {TCODColor(TCOD_DESATURATED_YELLOW),TCODColor(TCOD_LIGHTEST_YELLOW),TCODColor(TCOD_LIGHTER_YELLOW),TCODColor(TCOD_LIGHT_YELLOW),TCODColor(TCOD_YELLOW),TCODColor(TCOD_DARK_YELLOW),TCODColor(TCOD_DARKER_YELLOW),TCODColor(TCOD_DARKEST_YELLOW)}, + {TCODColor(TCOD_DESATURATED_LIME),TCODColor(TCOD_LIGHTEST_LIME),TCODColor(TCOD_LIGHTER_LIME),TCODColor(TCOD_LIGHT_LIME),TCODColor(TCOD_LIME),TCODColor(TCOD_DARK_LIME),TCODColor(TCOD_DARKER_LIME),TCODColor(TCOD_DARKEST_LIME)}, + {TCODColor(TCOD_DESATURATED_CHARTREUSE),TCODColor(TCOD_LIGHTEST_CHARTREUSE),TCODColor(TCOD_LIGHTER_CHARTREUSE),TCODColor(TCOD_LIGHT_CHARTREUSE),TCODColor(TCOD_CHARTREUSE),TCODColor(TCOD_DARK_CHARTREUSE),TCODColor(TCOD_DARKER_CHARTREUSE),TCODColor(TCOD_DARKEST_CHARTREUSE)}, + {TCODColor(TCOD_DESATURATED_GREEN),TCODColor(TCOD_LIGHTEST_GREEN),TCODColor(TCOD_LIGHTER_GREEN),TCODColor(TCOD_LIGHT_GREEN),TCODColor(TCOD_GREEN),TCODColor(TCOD_DARK_GREEN),TCODColor(TCOD_DARKER_GREEN),TCODColor(TCOD_DARKEST_GREEN)}, + {TCODColor(TCOD_DESATURATED_SEA),TCODColor(TCOD_LIGHTEST_SEA),TCODColor(TCOD_LIGHTER_SEA),TCODColor(TCOD_LIGHT_SEA),TCODColor(TCOD_SEA),TCODColor(TCOD_DARK_SEA),TCODColor(TCOD_DARKER_SEA),TCODColor(TCOD_DARKEST_SEA)}, + {TCODColor(TCOD_DESATURATED_TURQUOISE),TCODColor(TCOD_LIGHTEST_TURQUOISE),TCODColor(TCOD_LIGHTER_TURQUOISE),TCODColor(TCOD_LIGHT_TURQUOISE),TCODColor(TCOD_TURQUOISE),TCODColor(TCOD_DARK_TURQUOISE),TCODColor(TCOD_DARKER_TURQUOISE),TCODColor(TCOD_DARKEST_TURQUOISE)}, + {TCODColor(TCOD_DESATURATED_CYAN),TCODColor(TCOD_LIGHTEST_CYAN),TCODColor(TCOD_LIGHTER_CYAN),TCODColor(TCOD_LIGHT_CYAN),TCODColor(TCOD_CYAN),TCODColor(TCOD_DARK_CYAN),TCODColor(TCOD_DARKER_CYAN),TCODColor(TCOD_DARKEST_CYAN)}, + {TCODColor(TCOD_DESATURATED_SKY),TCODColor(TCOD_LIGHTEST_SKY),TCODColor(TCOD_LIGHTER_SKY),TCODColor(TCOD_LIGHT_SKY),TCODColor(TCOD_SKY),TCODColor(TCOD_DARK_SKY),TCODColor(TCOD_DARKER_SKY),TCODColor(TCOD_DARKEST_SKY)}, + {TCODColor(TCOD_DESATURATED_AZURE),TCODColor(TCOD_LIGHTEST_AZURE),TCODColor(TCOD_LIGHTER_AZURE),TCODColor(TCOD_LIGHT_AZURE),TCODColor(TCOD_AZURE),TCODColor(TCOD_DARK_AZURE),TCODColor(TCOD_DARKER_AZURE),TCODColor(TCOD_DARKEST_AZURE)}, + {TCODColor(TCOD_DESATURATED_BLUE),TCODColor(TCOD_LIGHTEST_BLUE),TCODColor(TCOD_LIGHTER_BLUE),TCODColor(TCOD_LIGHT_BLUE),TCODColor(TCOD_BLUE),TCODColor(TCOD_DARK_BLUE),TCODColor(TCOD_DARKER_BLUE),TCODColor(TCOD_DARKEST_BLUE)}, + {TCODColor(TCOD_DESATURATED_HAN),TCODColor(TCOD_LIGHTEST_HAN),TCODColor(TCOD_LIGHTER_HAN),TCODColor(TCOD_LIGHT_HAN),TCODColor(TCOD_HAN),TCODColor(TCOD_DARK_HAN),TCODColor(TCOD_DARKER_HAN),TCODColor(TCOD_DARKEST_HAN)}, + {TCODColor(TCOD_DESATURATED_VIOLET),TCODColor(TCOD_LIGHTEST_VIOLET),TCODColor(TCOD_LIGHTER_VIOLET),TCODColor(TCOD_LIGHT_VIOLET),TCODColor(TCOD_VIOLET),TCODColor(TCOD_DARK_VIOLET),TCODColor(TCOD_DARKER_VIOLET),TCODColor(TCOD_DARKEST_VIOLET)}, + {TCODColor(TCOD_DESATURATED_PURPLE),TCODColor(TCOD_LIGHTEST_PURPLE),TCODColor(TCOD_LIGHTER_PURPLE),TCODColor(TCOD_LIGHT_PURPLE),TCODColor(TCOD_PURPLE),TCODColor(TCOD_DARK_PURPLE),TCODColor(TCOD_DARKER_PURPLE),TCODColor(TCOD_DARKEST_PURPLE)}, + {TCODColor(TCOD_DESATURATED_FUCHSIA),TCODColor(TCOD_LIGHTEST_FUCHSIA),TCODColor(TCOD_LIGHTER_FUCHSIA),TCODColor(TCOD_LIGHT_FUCHSIA),TCODColor(TCOD_FUCHSIA),TCODColor(TCOD_DARK_FUCHSIA),TCODColor(TCOD_DARKER_FUCHSIA),TCODColor(TCOD_DARKEST_FUCHSIA)}, + {TCODColor(TCOD_DESATURATED_MAGENTA),TCODColor(TCOD_LIGHTEST_MAGENTA),TCODColor(TCOD_LIGHTER_MAGENTA),TCODColor(TCOD_LIGHT_MAGENTA),TCODColor(TCOD_MAGENTA),TCODColor(TCOD_DARK_MAGENTA),TCODColor(TCOD_DARKER_MAGENTA),TCODColor(TCOD_DARKEST_MAGENTA)}, + {TCODColor(TCOD_DESATURATED_PINK),TCODColor(TCOD_LIGHTEST_PINK),TCODColor(TCOD_LIGHTER_PINK),TCODColor(TCOD_LIGHT_PINK),TCODColor(TCOD_PINK),TCODColor(TCOD_DARK_PINK),TCODColor(TCOD_DARKER_PINK),TCODColor(TCOD_DARKEST_PINK)}, + {TCODColor(TCOD_DESATURATED_CRIMSON),TCODColor(TCOD_LIGHTEST_CRIMSON),TCODColor(TCOD_LIGHTER_CRIMSON),TCODColor(TCOD_LIGHT_CRIMSON),TCODColor(TCOD_CRIMSON),TCODColor(TCOD_DARK_CRIMSON),TCODColor(TCOD_DARKER_CRIMSON),TCODColor(TCOD_DARKEST_CRIMSON)} +}; +#endif + +TCODColor::TCODColor(float h, float s, float v) { + //setHSV(h,s,v); + TCOD_color_t c = TCOD_color_HSV(h,s,v); + r = c.r; g = c.g; b = c.b; +} + +void TCODColor::setHSV(float h, float s, float v) { + TCOD_color_t c; + TCOD_color_set_HSV(&c,h,s,v); + r = c.r; g = c.g; b = c.b; +} + +void TCODColor::setHue (float h) { + TCOD_color_t c = { r, g, b }; + TCOD_color_set_hue (&c, h); + r = c.r; g = c.g; b = c.b; +} + +void TCODColor::setSaturation (float s) { + TCOD_color_t c = { r, g, b }; + TCOD_color_set_saturation (&c, s); + r = c.r; g = c.g; b = c.b; +} + +void TCODColor::setValue (float v) { + TCOD_color_t c = { r, g, b }; + TCOD_color_set_value (&c, v); + r = c.r; g = c.g; b = c.b; +} + +void TCODColor::getHSV(float *h, float *s, float *v) const { + TCOD_color_t c={r,g,b}; + TCOD_color_get_HSV(c,h,s,v); +} + +float TCODColor::getHue () { + TCOD_color_t c = { r, g, b }; + return TCOD_color_get_hue(c); +} + +float TCODColor::getSaturation () { + TCOD_color_t c = { r, g, b }; + return TCOD_color_get_saturation(c); +} + +float TCODColor::getValue () { + TCOD_color_t c = { r, g, b }; + return TCOD_color_get_value(c); +} + +void TCODColor::shiftHue (float hshift) { + TCOD_color_t c = { r, g, b }; + TCOD_color_shift_hue (&c, hshift); + r = c.r; g = c.g; b = c.b; +} + +void TCODColor::scaleHSV (float sscale, float vscale) { + TCOD_color_t c = {r,g,b}; + TCOD_color_scale_HSV(&c,sscale,vscale); + r = c.r; g = c.g; b = c.b; +} + +// non member operators +TCODColor operator *(float value, const TCODColor &c) { + return c*value; +} + +void TCODColor::genMap(TCODColor *map, int nbKey, TCODColor const *keyColor, int const *keyIndex) { + for (int segment=0; segment < nbKey-1; segment++) { + int idxStart=keyIndex[segment]; + int idxEnd=keyIndex[segment+1]; + int idx; + for ( idx=idxStart;idx <= idxEnd; idx++) { + map[idx]=TCODColor::lerp(keyColor[segment],keyColor[segment+1],(float)(idx-idxStart)/(idxEnd-idxStart)); + } + } +} diff --git a/tcod_sys/libtcod/include/color.h b/tcod_sys/libtcod/src/libtcod/color.h similarity index 99% rename from tcod_sys/libtcod/include/color.h rename to tcod_sys/libtcod/src/libtcod/color.h index a3d109c3d..67e52bfcd 100644 --- a/tcod_sys/libtcod/include/color.h +++ b/tcod_sys/libtcod/src/libtcod/color.h @@ -28,7 +28,7 @@ #ifndef _TCOD_COLOR_H #define _TCOD_COLOR_H -#include "libtcod_portability.h" +#include "portability.h" #ifdef __cplusplus extern "C" { diff --git a/tcod_sys/libtcod/include/color.hpp b/tcod_sys/libtcod/src/libtcod/color.hpp similarity index 99% rename from tcod_sys/libtcod/include/color.hpp rename to tcod_sys/libtcod/src/libtcod/color.hpp index 557fbe314..d88881763 100644 --- a/tcod_sys/libtcod/include/color.hpp +++ b/tcod_sys/libtcod/src/libtcod/color.hpp @@ -29,7 +29,7 @@ #define _TCOD_COLOR_HPP #include "color.h" -#include "libtcod_utility.h" +#include "utility.h" // color constants uses to generate @ColorTable /** @ColorCategory STANDARD COLORS diff --git a/tcod_sys/libtcod/src/libtcod/color/canvas.cpp b/tcod_sys/libtcod/src/libtcod/color/canvas.cpp new file mode 100644 index 000000000..3116dd578 --- /dev/null +++ b/tcod_sys/libtcod/src/libtcod/color/canvas.cpp @@ -0,0 +1,29 @@ + +#include "canvas.h" + +#include + +#include "../../vendor/lodepng.h" + +namespace tcod { +namespace image { +Image load(const std::string& filename) +{ + unsigned img_width, img_height; + std::vector img_data; + if (lodepng::decode(img_data, img_width, img_height, filename)) { + throw std::runtime_error("File not found: " + filename); + } + Image image(img_width, img_height); + std::vector::iterator img_iter = img_data.begin(); + for (int y = 0; y < image.height(); ++y) { + for (int x = 0; x < image.width(); ++x) { + image.at(x, y) = ColorRGBA{ + img_iter[0], img_iter[1], img_iter[2], img_iter[3]}; + img_iter += 4; + } + } + return image; +} +} // namespace image +} // namespace tcod diff --git a/tcod_sys/libtcod/src/libtcod/color/canvas.h b/tcod_sys/libtcod/src/libtcod/color/canvas.h new file mode 100644 index 000000000..e7f41a13c --- /dev/null +++ b/tcod_sys/libtcod/src/libtcod/color/canvas.h @@ -0,0 +1,21 @@ + +#ifndef LIBTCOD_COLOR_CANVAS_H_ +#define LIBTCOD_COLOR_CANVAS_H_ +#ifdef __cplusplus +#include +#endif // __cplusplus + +#include "color.h" +#include "../utility/vector2.h" +#ifdef __cplusplus +namespace tcod { +namespace image { +/** + * A Common Vector2 type used for 2d images. + */ +typedef Vector2 Image; +Image load(const std::string& filename); +} // namespace image +} // namespace tcod +#endif /* __cplusplus */ +#endif /* LIBTCOD_COLOR_CANVAS_H_ */ diff --git a/tcod_sys/libtcod/src/libtcod/color/color.h b/tcod_sys/libtcod/src/libtcod/color/color.h new file mode 100644 index 000000000..7c5392646 --- /dev/null +++ b/tcod_sys/libtcod/src/libtcod/color/color.h @@ -0,0 +1,12 @@ + +#ifndef LIBTCOD_COLOR_COLOR_H_ +#define LIBTCOD_COLOR_COLOR_H_ +#include +#ifdef __cplusplus +namespace tcod { +struct ColorRGBA { + uint8_t r, g, b, a; +}; +} // namespace tcod +#endif /* __cplusplus */ +#endif /* LIBTCOD_COLOR_COLOR_H_ */ diff --git a/tcod_sys/libtcod/src/color_c.c b/tcod_sys/libtcod/src/libtcod/color_c.c similarity index 97% rename from tcod_sys/libtcod/src/color_c.c rename to tcod_sys/libtcod/src/libtcod/color_c.c index 728f2893a..319d14f38 100644 --- a/tcod_sys/libtcod/src/color_c.c +++ b/tcod_sys/libtcod/src/libtcod/color_c.c @@ -1,612 +1,612 @@ -/* -* libtcod -* Copyright (c) 2008-2018 Jice & Mingos & rmtew -* All rights reserved. -* -* Redistribution and use in source and binary forms, with or without -* modification, are permitted provided that the following conditions are met: -* * Redistributions of source code must retain the above copyright -* notice, this list of conditions and the following disclaimer. -* * Redistributions in binary form must reproduce the above copyright -* notice, this list of conditions and the following disclaimer in the -* documentation and/or other materials provided with the distribution. -* * The name of Jice or Mingos may not be used to endorse or promote -* products derived from this software without specific prior written -* permission. -* -* THIS SOFTWARE IS PROVIDED BY JICE, MINGOS AND RMTEW ``AS IS'' AND ANY -* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED -* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE -* DISCLAIMED. IN NO EVENT SHALL JICE, MINGOS OR RMTEW BE LIABLE FOR ANY -* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES -* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; -* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND -* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS -* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. -*/ -#include - -#include - -#include -#include - -/* grey levels */ -const TCOD_color_t TCOD_black={TCOD_BLACK}; -const TCOD_color_t TCOD_darkest_grey={TCOD_DARKEST_GREY}; -const TCOD_color_t TCOD_darker_grey={TCOD_DARKER_GREY}; -const TCOD_color_t TCOD_dark_grey={TCOD_DARK_GREY}; -const TCOD_color_t TCOD_grey={TCOD_GREY}; -const TCOD_color_t TCOD_light_grey={TCOD_LIGHT_GREY}; -const TCOD_color_t TCOD_lighter_grey={TCOD_LIGHTER_GREY}; -const TCOD_color_t TCOD_lightest_grey={TCOD_LIGHTEST_GREY}; -const TCOD_color_t TCOD_darkest_gray={TCOD_DARKEST_GREY}; -const TCOD_color_t TCOD_darker_gray={TCOD_DARKER_GREY}; -const TCOD_color_t TCOD_dark_gray={TCOD_DARK_GREY}; -const TCOD_color_t TCOD_gray={TCOD_GREY}; -const TCOD_color_t TCOD_light_gray={TCOD_LIGHT_GREY}; -const TCOD_color_t TCOD_lighter_gray={TCOD_LIGHTER_GREY}; -const TCOD_color_t TCOD_lightest_gray={TCOD_LIGHTEST_GREY}; -const TCOD_color_t TCOD_white={TCOD_WHITE}; - -/* sepia */ -const TCOD_color_t TCOD_darkest_sepia={TCOD_DARKEST_SEPIA}; -const TCOD_color_t TCOD_darker_sepia={TCOD_DARKER_SEPIA}; -const TCOD_color_t TCOD_dark_sepia={TCOD_DARK_SEPIA}; -const TCOD_color_t TCOD_sepia={TCOD_SEPIA}; -const TCOD_color_t TCOD_light_sepia={TCOD_LIGHT_SEPIA}; -const TCOD_color_t TCOD_lighter_sepia={TCOD_LIGHTER_SEPIA}; -const TCOD_color_t TCOD_lightest_sepia={TCOD_LIGHTEST_SEPIA}; - -/* standard colors */ -const TCOD_color_t TCOD_red = {TCOD_RED}; -const TCOD_color_t TCOD_flame = {TCOD_FLAME}; -const TCOD_color_t TCOD_orange = {TCOD_ORANGE}; -const TCOD_color_t TCOD_amber = {TCOD_AMBER}; -const TCOD_color_t TCOD_yellow = {TCOD_YELLOW}; -const TCOD_color_t TCOD_lime = {TCOD_LIME}; -const TCOD_color_t TCOD_chartreuse = {TCOD_CHARTREUSE}; -const TCOD_color_t TCOD_green = {TCOD_GREEN}; -const TCOD_color_t TCOD_sea = {TCOD_SEA}; -const TCOD_color_t TCOD_turquoise = {TCOD_TURQUOISE}; -const TCOD_color_t TCOD_cyan = {TCOD_CYAN}; -const TCOD_color_t TCOD_sky = {TCOD_SKY}; -const TCOD_color_t TCOD_azure = {TCOD_AZURE}; -const TCOD_color_t TCOD_blue = {TCOD_BLUE}; -const TCOD_color_t TCOD_han = {TCOD_HAN}; -const TCOD_color_t TCOD_violet = {TCOD_VIOLET}; -const TCOD_color_t TCOD_purple = {TCOD_PURPLE}; -const TCOD_color_t TCOD_fuchsia = {TCOD_FUCHSIA}; -const TCOD_color_t TCOD_magenta = {TCOD_MAGENTA}; -const TCOD_color_t TCOD_pink = {TCOD_PINK}; -const TCOD_color_t TCOD_crimson = {TCOD_CRIMSON}; - -/* dark colors */ -const TCOD_color_t TCOD_dark_red = {TCOD_DARK_RED}; -const TCOD_color_t TCOD_dark_flame = {TCOD_DARK_FLAME}; -const TCOD_color_t TCOD_dark_orange = {TCOD_DARK_ORANGE}; -const TCOD_color_t TCOD_dark_amber = {TCOD_DARK_AMBER}; -const TCOD_color_t TCOD_dark_yellow = {TCOD_DARK_YELLOW}; -const TCOD_color_t TCOD_dark_lime = {TCOD_DARK_LIME}; -const TCOD_color_t TCOD_dark_chartreuse = {TCOD_DARK_CHARTREUSE}; -const TCOD_color_t TCOD_dark_green = {TCOD_DARK_GREEN}; -const TCOD_color_t TCOD_dark_sea = {TCOD_DARK_SEA}; -const TCOD_color_t TCOD_dark_turquoise = {TCOD_DARK_TURQUOISE}; -const TCOD_color_t TCOD_dark_cyan = {TCOD_DARK_CYAN}; -const TCOD_color_t TCOD_dark_sky = {TCOD_DARK_SKY}; -const TCOD_color_t TCOD_dark_azure = {TCOD_DARK_AZURE}; -const TCOD_color_t TCOD_dark_blue = {TCOD_DARK_BLUE}; -const TCOD_color_t TCOD_dark_han = {TCOD_DARK_HAN}; -const TCOD_color_t TCOD_dark_violet = {TCOD_DARK_VIOLET}; -const TCOD_color_t TCOD_dark_purple = {TCOD_DARK_PURPLE}; -const TCOD_color_t TCOD_dark_fuchsia = {TCOD_DARK_FUCHSIA}; -const TCOD_color_t TCOD_dark_magenta = {TCOD_DARK_MAGENTA}; -const TCOD_color_t TCOD_dark_pink = {TCOD_DARK_PINK}; -const TCOD_color_t TCOD_dark_crimson = {TCOD_DARK_CRIMSON}; - -/* darker colors */ -const TCOD_color_t TCOD_darker_red = {TCOD_DARKER_RED}; -const TCOD_color_t TCOD_darker_flame = {TCOD_DARKER_FLAME}; -const TCOD_color_t TCOD_darker_orange = {TCOD_DARKER_ORANGE}; -const TCOD_color_t TCOD_darker_amber = {TCOD_DARKER_AMBER}; -const TCOD_color_t TCOD_darker_yellow = {TCOD_DARKER_YELLOW}; -const TCOD_color_t TCOD_darker_lime = {TCOD_DARKER_LIME}; -const TCOD_color_t TCOD_darker_chartreuse = {TCOD_DARKER_CHARTREUSE}; -const TCOD_color_t TCOD_darker_green = {TCOD_DARKER_GREEN}; -const TCOD_color_t TCOD_darker_sea = {TCOD_DARKER_SEA}; -const TCOD_color_t TCOD_darker_turquoise = {TCOD_DARKER_TURQUOISE}; -const TCOD_color_t TCOD_darker_cyan = {TCOD_DARKER_CYAN}; -const TCOD_color_t TCOD_darker_sky = {TCOD_DARKER_SKY}; -const TCOD_color_t TCOD_darker_azure = {TCOD_DARKER_AZURE}; -const TCOD_color_t TCOD_darker_blue = {TCOD_DARKER_BLUE}; -const TCOD_color_t TCOD_darker_han = {TCOD_DARKER_HAN}; -const TCOD_color_t TCOD_darker_violet = {TCOD_DARKER_VIOLET}; -const TCOD_color_t TCOD_darker_purple = {TCOD_DARKER_PURPLE}; -const TCOD_color_t TCOD_darker_fuchsia = {TCOD_DARKER_FUCHSIA}; -const TCOD_color_t TCOD_darker_magenta = {TCOD_DARKER_MAGENTA}; -const TCOD_color_t TCOD_darker_pink = {TCOD_DARKER_PINK}; -const TCOD_color_t TCOD_darker_crimson = {TCOD_DARKER_CRIMSON}; - -/* darkest colors */ -const TCOD_color_t TCOD_darkest_red = {TCOD_DARKEST_RED}; -const TCOD_color_t TCOD_darkest_flame = {TCOD_DARKEST_FLAME}; -const TCOD_color_t TCOD_darkest_orange = {TCOD_DARKEST_ORANGE}; -const TCOD_color_t TCOD_darkest_amber = {TCOD_DARKEST_AMBER}; -const TCOD_color_t TCOD_darkest_yellow = {TCOD_DARKEST_YELLOW}; -const TCOD_color_t TCOD_darkest_lime = {TCOD_DARKEST_LIME}; -const TCOD_color_t TCOD_darkest_chartreuse = {TCOD_DARKEST_CHARTREUSE}; -const TCOD_color_t TCOD_darkest_green = {TCOD_DARKEST_GREEN}; -const TCOD_color_t TCOD_darkest_sea = {TCOD_DARKEST_SEA}; -const TCOD_color_t TCOD_darkest_turquoise = {TCOD_DARKEST_TURQUOISE}; -const TCOD_color_t TCOD_darkest_cyan = {TCOD_DARKEST_CYAN}; -const TCOD_color_t TCOD_darkest_sky = {TCOD_DARKEST_SKY}; -const TCOD_color_t TCOD_darkest_azure = {TCOD_DARKEST_AZURE}; -const TCOD_color_t TCOD_darkest_blue = {TCOD_DARKEST_BLUE}; -const TCOD_color_t TCOD_darkest_han = {TCOD_DARKEST_HAN}; -const TCOD_color_t TCOD_darkest_violet = {TCOD_DARKEST_VIOLET}; -const TCOD_color_t TCOD_darkest_purple = {TCOD_DARKEST_PURPLE}; -const TCOD_color_t TCOD_darkest_fuchsia = {TCOD_DARKEST_FUCHSIA}; -const TCOD_color_t TCOD_darkest_magenta = {TCOD_DARKEST_MAGENTA}; -const TCOD_color_t TCOD_darkest_pink = {TCOD_DARKEST_PINK}; -const TCOD_color_t TCOD_darkest_crimson = {TCOD_DARKEST_CRIMSON}; - -/* light colors */ -const TCOD_color_t TCOD_light_red = {TCOD_LIGHT_RED}; -const TCOD_color_t TCOD_light_flame = {TCOD_LIGHT_FLAME}; -const TCOD_color_t TCOD_light_orange = {TCOD_LIGHT_ORANGE}; -const TCOD_color_t TCOD_light_amber = {TCOD_LIGHT_AMBER}; -const TCOD_color_t TCOD_light_yellow = {TCOD_LIGHT_YELLOW}; -const TCOD_color_t TCOD_light_lime = {TCOD_LIGHT_LIME}; -const TCOD_color_t TCOD_light_chartreuse = {TCOD_LIGHT_CHARTREUSE}; -const TCOD_color_t TCOD_light_green = {TCOD_LIGHT_GREEN}; -const TCOD_color_t TCOD_light_sea = {TCOD_LIGHT_SEA}; -const TCOD_color_t TCOD_light_turquoise = {TCOD_LIGHT_TURQUOISE}; -const TCOD_color_t TCOD_light_cyan = {TCOD_LIGHT_CYAN}; -const TCOD_color_t TCOD_light_sky = {TCOD_LIGHT_SKY}; -const TCOD_color_t TCOD_light_azure = {TCOD_LIGHT_AZURE}; -const TCOD_color_t TCOD_light_blue = {TCOD_LIGHT_BLUE}; -const TCOD_color_t TCOD_light_han = {TCOD_LIGHT_HAN}; -const TCOD_color_t TCOD_light_violet = {TCOD_LIGHT_VIOLET}; -const TCOD_color_t TCOD_light_purple = {TCOD_LIGHT_PURPLE}; -const TCOD_color_t TCOD_light_fuchsia = {TCOD_LIGHT_FUCHSIA}; -const TCOD_color_t TCOD_light_magenta = {TCOD_LIGHT_MAGENTA}; -const TCOD_color_t TCOD_light_pink = {TCOD_LIGHT_PINK}; -const TCOD_color_t TCOD_light_crimson = {TCOD_LIGHT_CRIMSON}; - -/*lighter colors */ -const TCOD_color_t TCOD_lighter_red = {TCOD_LIGHTER_RED}; -const TCOD_color_t TCOD_lighter_flame = {TCOD_LIGHTER_FLAME}; -const TCOD_color_t TCOD_lighter_orange = {TCOD_LIGHTER_ORANGE}; -const TCOD_color_t TCOD_lighter_amber = {TCOD_LIGHTER_AMBER}; -const TCOD_color_t TCOD_lighter_yellow = {TCOD_LIGHTER_YELLOW}; -const TCOD_color_t TCOD_lighter_lime = {TCOD_LIGHTER_LIME}; -const TCOD_color_t TCOD_lighter_chartreuse = {TCOD_LIGHTER_CHARTREUSE}; -const TCOD_color_t TCOD_lighter_green = {TCOD_LIGHTER_GREEN}; -const TCOD_color_t TCOD_lighter_sea = {TCOD_LIGHTER_SEA}; -const TCOD_color_t TCOD_lighter_turquoise = {TCOD_LIGHTER_TURQUOISE}; -const TCOD_color_t TCOD_lighter_cyan = {TCOD_LIGHTER_CYAN}; -const TCOD_color_t TCOD_lighter_sky = {TCOD_LIGHTER_SKY}; -const TCOD_color_t TCOD_lighter_azure = {TCOD_LIGHTER_AZURE}; -const TCOD_color_t TCOD_lighter_blue = {TCOD_LIGHTER_BLUE}; -const TCOD_color_t TCOD_lighter_han = {TCOD_LIGHTER_HAN}; -const TCOD_color_t TCOD_lighter_violet = {TCOD_LIGHTER_VIOLET}; -const TCOD_color_t TCOD_lighter_purple = {TCOD_LIGHTER_PURPLE}; -const TCOD_color_t TCOD_lighter_fuchsia = {TCOD_LIGHTER_FUCHSIA}; -const TCOD_color_t TCOD_lighter_magenta = {TCOD_LIGHTER_MAGENTA}; -const TCOD_color_t TCOD_lighter_pink = {TCOD_LIGHTER_PINK}; -const TCOD_color_t TCOD_lighter_crimson = {TCOD_LIGHTER_CRIMSON}; - -/* lightest colors */ -const TCOD_color_t TCOD_lightest_red = {TCOD_LIGHTEST_RED}; -const TCOD_color_t TCOD_lightest_flame = {TCOD_LIGHTEST_FLAME}; -const TCOD_color_t TCOD_lightest_orange = {TCOD_LIGHTEST_ORANGE}; -const TCOD_color_t TCOD_lightest_amber = {TCOD_LIGHTEST_AMBER}; -const TCOD_color_t TCOD_lightest_yellow = {TCOD_LIGHTEST_YELLOW}; -const TCOD_color_t TCOD_lightest_lime = {TCOD_LIGHTEST_LIME}; -const TCOD_color_t TCOD_lightest_chartreuse = {TCOD_LIGHTEST_CHARTREUSE}; -const TCOD_color_t TCOD_lightest_green = {TCOD_LIGHTEST_GREEN}; -const TCOD_color_t TCOD_lightest_sea = {TCOD_LIGHTEST_SEA}; -const TCOD_color_t TCOD_lightest_turquoise = {TCOD_LIGHTEST_TURQUOISE}; -const TCOD_color_t TCOD_lightest_cyan = {TCOD_LIGHTEST_CYAN}; -const TCOD_color_t TCOD_lightest_sky = {TCOD_LIGHTEST_SKY}; -const TCOD_color_t TCOD_lightest_azure = {TCOD_LIGHTEST_AZURE}; -const TCOD_color_t TCOD_lightest_blue = {TCOD_LIGHTEST_BLUE}; -const TCOD_color_t TCOD_lightest_han = {TCOD_LIGHTEST_HAN}; -const TCOD_color_t TCOD_lightest_violet = {TCOD_LIGHTEST_VIOLET}; -const TCOD_color_t TCOD_lightest_purple = {TCOD_LIGHTEST_PURPLE}; -const TCOD_color_t TCOD_lightest_fuchsia = {TCOD_LIGHTEST_FUCHSIA}; -const TCOD_color_t TCOD_lightest_magenta = {TCOD_LIGHTEST_MAGENTA}; -const TCOD_color_t TCOD_lightest_pink = {TCOD_LIGHTEST_PINK}; -const TCOD_color_t TCOD_lightest_crimson = {TCOD_LIGHTEST_CRIMSON}; - -/* desaturated colors */ -const TCOD_color_t TCOD_desaturated_red = {TCOD_DESATURATED_RED}; -const TCOD_color_t TCOD_desaturated_flame = {TCOD_DESATURATED_FLAME}; -const TCOD_color_t TCOD_desaturated_orange = {TCOD_DESATURATED_ORANGE}; -const TCOD_color_t TCOD_desaturated_amber = {TCOD_DESATURATED_AMBER}; -const TCOD_color_t TCOD_desaturated_yellow = {TCOD_DESATURATED_YELLOW}; -const TCOD_color_t TCOD_desaturated_lime = {TCOD_DESATURATED_LIME}; -const TCOD_color_t TCOD_desaturated_chartreuse = {TCOD_DESATURATED_CHARTREUSE}; -const TCOD_color_t TCOD_desaturated_green = {TCOD_DESATURATED_GREEN}; -const TCOD_color_t TCOD_desaturated_sea = {TCOD_DESATURATED_SEA}; -const TCOD_color_t TCOD_desaturated_turquoise = {TCOD_DESATURATED_TURQUOISE}; -const TCOD_color_t TCOD_desaturated_cyan = {TCOD_DESATURATED_CYAN}; -const TCOD_color_t TCOD_desaturated_sky = {TCOD_DESATURATED_SKY}; -const TCOD_color_t TCOD_desaturated_azure = {TCOD_DESATURATED_AZURE}; -const TCOD_color_t TCOD_desaturated_blue = {TCOD_DESATURATED_BLUE}; -const TCOD_color_t TCOD_desaturated_han = {TCOD_DESATURATED_HAN}; -const TCOD_color_t TCOD_desaturated_violet = {TCOD_DESATURATED_VIOLET}; -const TCOD_color_t TCOD_desaturated_purple = {TCOD_DESATURATED_PURPLE}; -const TCOD_color_t TCOD_desaturated_fuchsia = {TCOD_DESATURATED_FUCHSIA}; -const TCOD_color_t TCOD_desaturated_magenta = {TCOD_DESATURATED_MAGENTA}; -const TCOD_color_t TCOD_desaturated_pink = {TCOD_DESATURATED_PINK}; -const TCOD_color_t TCOD_desaturated_crimson = {TCOD_DESATURATED_CRIMSON}; - -/* metallic */ -const TCOD_color_t TCOD_brass = {TCOD_BRASS}; -const TCOD_color_t TCOD_copper = {TCOD_COPPER}; -const TCOD_color_t TCOD_gold = {TCOD_GOLD}; -const TCOD_color_t TCOD_silver = {TCOD_SILVER}; - -/* miscellaneous */ -const TCOD_color_t TCOD_celadon = {TCOD_CELADON}; -const TCOD_color_t TCOD_peach = {TCOD_PEACH}; - -/* color array */ -const TCOD_color_t TCOD_colors[TCOD_COLOR_NB][TCOD_COLOR_LEVELS] = { - {{TCOD_DESATURATED_RED},{TCOD_LIGHTEST_RED},{TCOD_LIGHTER_RED},{TCOD_LIGHT_RED},{TCOD_RED},{TCOD_DARK_RED},{TCOD_DARKER_RED},{TCOD_DARKEST_RED}}, - {{TCOD_DESATURATED_FLAME},{TCOD_LIGHTEST_FLAME},{TCOD_LIGHTER_FLAME},{TCOD_LIGHT_FLAME},{TCOD_FLAME},{TCOD_DARK_FLAME},{TCOD_DARKER_FLAME},{TCOD_DARKEST_FLAME}}, - {{TCOD_DESATURATED_ORANGE},{TCOD_LIGHTEST_ORANGE},{TCOD_LIGHTER_ORANGE},{TCOD_LIGHT_ORANGE},{TCOD_ORANGE},{TCOD_DARK_ORANGE},{TCOD_DARKER_ORANGE},{TCOD_DARKEST_ORANGE}}, - {{TCOD_DESATURATED_AMBER},{TCOD_LIGHTEST_AMBER},{TCOD_LIGHTER_AMBER},{TCOD_LIGHT_AMBER},{TCOD_AMBER},{TCOD_DARK_AMBER},{TCOD_DARKER_AMBER},{TCOD_DARKEST_AMBER}}, - {{TCOD_DESATURATED_YELLOW},{TCOD_LIGHTEST_YELLOW},{TCOD_LIGHTER_YELLOW},{TCOD_LIGHT_YELLOW},{TCOD_YELLOW},{TCOD_DARK_YELLOW},{TCOD_DARKER_YELLOW},{TCOD_DARKEST_YELLOW}}, - {{TCOD_DESATURATED_LIME},{TCOD_LIGHTEST_LIME},{TCOD_LIGHTER_LIME},{TCOD_LIGHT_LIME},{TCOD_LIME},{TCOD_DARK_LIME},{TCOD_DARKER_LIME},{TCOD_DARKEST_LIME}}, - {{TCOD_DESATURATED_CHARTREUSE},{TCOD_LIGHTEST_CHARTREUSE},{TCOD_LIGHTER_CHARTREUSE},{TCOD_LIGHT_CHARTREUSE},{TCOD_CHARTREUSE},{TCOD_DARK_CHARTREUSE},{TCOD_DARKER_CHARTREUSE},{TCOD_DARKEST_CHARTREUSE}}, - {{TCOD_DESATURATED_GREEN},{TCOD_LIGHTEST_GREEN},{TCOD_LIGHTER_GREEN},{TCOD_LIGHT_GREEN},{TCOD_GREEN},{TCOD_DARK_GREEN},{TCOD_DARKER_GREEN},{TCOD_DARKEST_GREEN}}, - {{TCOD_DESATURATED_SEA},{TCOD_LIGHTEST_SEA},{TCOD_LIGHTER_SEA},{TCOD_LIGHT_SEA},{TCOD_SEA},{TCOD_DARK_SEA},{TCOD_DARKER_SEA},{TCOD_DARKEST_SEA}}, - {{TCOD_DESATURATED_TURQUOISE},{TCOD_LIGHTEST_TURQUOISE},{TCOD_LIGHTER_TURQUOISE},{TCOD_LIGHT_TURQUOISE},{TCOD_TURQUOISE},{TCOD_DARK_TURQUOISE},{TCOD_DARKER_TURQUOISE},{TCOD_DARKEST_TURQUOISE}}, - {{TCOD_DESATURATED_CYAN},{TCOD_LIGHTEST_CYAN},{TCOD_LIGHTER_CYAN},{TCOD_LIGHT_CYAN},{TCOD_CYAN},{TCOD_DARK_CYAN},{TCOD_DARKER_CYAN},{TCOD_DARKEST_CYAN}}, - {{TCOD_DESATURATED_SKY},{TCOD_LIGHTEST_SKY},{TCOD_LIGHTER_SKY},{TCOD_LIGHT_SKY},{TCOD_SKY},{TCOD_DARK_SKY},{TCOD_DARKER_SKY},{TCOD_DARKEST_SKY}}, - {{TCOD_DESATURATED_AZURE},{TCOD_LIGHTEST_AZURE},{TCOD_LIGHTER_AZURE},{TCOD_LIGHT_AZURE},{TCOD_AZURE},{TCOD_DARK_AZURE},{TCOD_DARKER_AZURE},{TCOD_DARKEST_AZURE}}, - {{TCOD_DESATURATED_BLUE},{TCOD_LIGHTEST_BLUE},{TCOD_LIGHTER_BLUE},{TCOD_LIGHT_BLUE},{TCOD_BLUE},{TCOD_DARK_BLUE},{TCOD_DARKER_BLUE},{TCOD_DARKEST_BLUE}}, - {{TCOD_DESATURATED_HAN},{TCOD_LIGHTEST_HAN},{TCOD_LIGHTER_HAN},{TCOD_LIGHT_HAN},{TCOD_HAN},{TCOD_DARK_HAN},{TCOD_DARKER_HAN},{TCOD_DARKEST_HAN}}, - {{TCOD_DESATURATED_VIOLET},{TCOD_LIGHTEST_VIOLET},{TCOD_LIGHTER_VIOLET},{TCOD_LIGHT_VIOLET},{TCOD_VIOLET},{TCOD_DARK_VIOLET},{TCOD_DARKER_VIOLET},{TCOD_DARKEST_VIOLET}}, - {{TCOD_DESATURATED_PURPLE},{TCOD_LIGHTEST_PURPLE},{TCOD_LIGHTER_PURPLE},{TCOD_LIGHT_PURPLE},{TCOD_PURPLE},{TCOD_DARK_PURPLE},{TCOD_DARKER_PURPLE},{TCOD_DARKEST_PURPLE}}, - {{TCOD_DESATURATED_FUCHSIA},{TCOD_LIGHTEST_FUCHSIA},{TCOD_LIGHTER_FUCHSIA},{TCOD_LIGHT_FUCHSIA},{TCOD_FUCHSIA},{TCOD_DARK_FUCHSIA},{TCOD_DARKER_FUCHSIA},{TCOD_DARKEST_FUCHSIA}}, - {{TCOD_DESATURATED_MAGENTA},{TCOD_LIGHTEST_MAGENTA},{TCOD_LIGHTER_MAGENTA},{TCOD_LIGHT_MAGENTA},{TCOD_MAGENTA},{TCOD_DARK_MAGENTA},{TCOD_DARKER_MAGENTA},{TCOD_DARKEST_MAGENTA}}, - {{TCOD_DESATURATED_PINK},{TCOD_LIGHTEST_PINK},{TCOD_LIGHTER_PINK},{TCOD_LIGHT_PINK},{TCOD_PINK},{TCOD_DARK_PINK},{TCOD_DARKER_PINK},{TCOD_DARKEST_PINK}}, - {{TCOD_DESATURATED_CRIMSON},{TCOD_LIGHTEST_CRIMSON},{TCOD_LIGHTER_CRIMSON},{TCOD_LIGHT_CRIMSON},{TCOD_CRIMSON},{TCOD_DARK_CRIMSON},{TCOD_DARKER_CRIMSON},{TCOD_DARKEST_CRIMSON}} -}; -/** - * \brief Return a new TCOD_color_t from RGB values. - * - * This function is redundant, you should use a braced initializer instead: - * - * TCOD_color_t white = {255, 255, 255}; - */ -TCOD_color_t TCOD_color_RGB(uint8_t r, uint8_t g, uint8_t b) { - TCOD_color_t new_color = {r, g, b}; - return new_color; -} -/** - * \brief Return a new TCOD_color_t from HSV values. - * - * \param hue The colors hue (in degrees.) - * \param saturation The colors saturation (from 0 to 1) - * \param value The colors value (from 0 to 1) - * \return A new TCOD_color_t struct. - * - * The saturation and value parameters are automatically clamped to 0 and 1. - * - * TCOD_color_t light_blue = TCOD_color_HSV(240.0f, 0.75f, 1.0f); - * - * Use TCOD_color_set_HSV to fill an existing struct with HSV values. - */ -TCOD_color_t TCOD_color_HSV(float hue, float saturation, float value) { - TCOD_color_t new_color; - TCOD_color_set_HSV(&new_color, hue, saturation, value); - return new_color; -} -/** - * \brief Return a true value if c1 and c2 are equal. - */ -bool TCOD_color_equals(TCOD_color_t c1, TCOD_color_t c2) { - return (c1.r == c2.r && c1.g == c2.g && c1.b == c2.b); -} -/** - * \brief Add two colors together and return the result. - * - * \param c1 The first color. - * \param c2 The second color. - * \return A new TCOD_color_t struct with the result. - */ -TCOD_color_t TCOD_color_add(TCOD_color_t c1, TCOD_color_t c2) { - TCOD_color_t new_color = { - (uint8_t)MIN(255, (int)c1.r + c2.r), - (uint8_t)MIN(255, (int)c1.g + c2.g), - (uint8_t)MIN(255, (int)c1.b + c2.b)}; - return new_color; -} -/** - * \brief Subtract c2 from c1 and return the result. - * - * \param c1 The first color. - * \param c2 The second color. - * \return A new TCOD_color_t struct with the result. - */ -TCOD_color_t TCOD_color_subtract(TCOD_color_t c1, TCOD_color_t c2) { - TCOD_color_t new_color = { - (uint8_t)MAX(0, (int)c1.r - c2.r), - (uint8_t)MAX(0, (int)c1.g - c2.g), - (uint8_t)MAX(0, (int)c1.b - c2.b)}; - return new_color; -} -/** - * \brief Multiply two colors together and return the result. - * - * \param c1 The first color. - * \param c2 The second color. - * \return A new TCOD_color_t struct with the result. - */ -TCOD_color_t TCOD_color_multiply(TCOD_color_t c1, TCOD_color_t c2) { - TCOD_color_t new_color = { - (uint8_t)(((int)c1.r) * c2.r / 255), - (uint8_t)(((int)c1.g) * c2.g / 255), - (uint8_t)(((int)c1.b) * c2.b / 255)}; - return new_color; -} -/** - * \brief Multiply a color with a scalar value and return the result. - * - * \param c1 The color to multiply. - * \param value The scalar float. - * \return A new TCOD_color_t struct with the result. - */ -TCOD_color_t TCOD_color_multiply_scalar(TCOD_color_t c1, float value) { - TCOD_color_t new_color = { - (uint8_t)CLAMP(0.0f, 255.0f, (float)c1.r * value), - (uint8_t)CLAMP(0.0f, 255.0f, (float)c1.g * value), - (uint8_t)CLAMP(0.0f, 255.0f, (float)c1.b * value)}; - return new_color; -} -/** - * \brief Interpolate two colors together and return the result. - * - * \param c1 The first color (where coef if 0) - * \param c2 The second color (where coef if 1) - * \param coef The coefficient. - * \return A new TCOD_color_t struct with the result. - */ -TCOD_color_t TCOD_color_lerp(TCOD_color_t c1, TCOD_color_t c2, float coef) { - TCOD_color_t new_color = { - (uint8_t)(c1.r + (c2.r - c1.r) * coef), - (uint8_t)(c1.g + (c2.g - c1.g) * coef), - (uint8_t)(c1.b + (c2.b - c1.b) * coef)}; - return new_color; -} -/* Return floor modulo for double values. */ -static double fabsmod(double x, double n) { - double m = fmod(x, n); - return m < 0 ? m+n : m; -} - -/** - * \brief Sets a colors values from HSV values. - * - * \param color The color to be changed. - * \param hue The colors hue (in degrees.) - * \param saturation The colors saturation (from 0 to 1) - * \param value The colors value (from 0 to 1) - */ -void TCOD_color_set_HSV(TCOD_color_t *color, - float hue, float saturation, float value) { - int hue_section; - float hue_fraction, p, q, t; - - saturation = CLAMP(0.0f, 1.0f, saturation); - value = CLAMP(0.0f, 1.0f, value); - if( saturation == 0.0f ) { /* achromatic (grey) */ - color->r = color->g = color->b = (uint8_t)(value * 255.0f + 0.5f); - return; - } - - hue = (float)fabsmod(hue, 360.0f); - hue /= 60.0f; /* sector 0 to 5 */ - hue_section = (int)floor(hue); - hue_fraction = hue - hue_section; /* fraction between sections */ - p = value * (1 - saturation); - q = value * (1 - saturation * hue_fraction); - t = value * (1 - saturation * (1 - hue_fraction)); - - switch (hue_section) { - default: - case 0: /* red/yellow */ - color->r = (uint8_t)(value * 255.0f + 0.5f); - color->g = (uint8_t)(t * 255.0f + 0.5f); - color->b = (uint8_t)(p * 255.0f + 0.5f); - break; - case 1: /* yellow/green */ - color->r = (uint8_t)(q * 255.0f + 0.5f); - color->g = (uint8_t)(value * 255.0f + 0.5f); - color->b = (uint8_t)(p * 255.0f + 0.5f); - break; - case 2: /* green/cyan */ - color->r = (uint8_t)(p * 255.0f + 0.5f); - color->g = (uint8_t)(value * 255.0f + 0.5f); - color->b = (uint8_t)(t * 255.0f + 0.5f); - break; - case 3: /* cyan/blue */ - color->r = (uint8_t)(p * 255.0f + 0.5f); - color->g = (uint8_t)(q * 255.0f + 0.5f); - color->b = (uint8_t)(value * 255.0f + 0.5f); - break; - case 4: /* blue/purple */ - color->r = (uint8_t)(t * 255.0f + 0.5f); - color->g = (uint8_t)(p * 255.0f + 0.5f); - color->b = (uint8_t)(value * 255.0f + 0.5f); - break; - case 5: /* purple/red */ - color->r = (uint8_t)(value * 255.0f + 0.5f); - color->g = (uint8_t)(p * 255.0f + 0.5f); - color->b = (uint8_t)(q * 255.0f + 0.5f); - break; - } -} -/** - * \brief Get a set of HSV values from a color. - * - * \param color The color - * \param hue Pointer to a float, filled with the hue. (degrees) - * \param saturation Pointer to a float, filled with the saturation. (0 to 1) - * \param value Pointer to a float, filled with the value. (0 to 1) - * - * The hue, saturation, and value parameters can not be NULL pointers, - */ -void TCOD_color_get_HSV(TCOD_color_t color, - float *hue, float *saturation, float *value) { - *hue = TCOD_color_get_hue(color); - *saturation = TCOD_color_get_saturation(color); - *value = TCOD_color_get_value(color); - return; -} -/** - * \brief Return a colors hue. - * - * \param color A color struct. - * \return The colors hue. (degrees) - */ -float TCOD_color_get_hue(TCOD_color_t color) { - uint8_t max = MAX(color.r, MAX(color.g, color.b)); - uint8_t min = MIN(color.r, MIN(color.g, color.b)); - float delta = (float)max - (float)min; - float hue; /* degrees */ - if (delta == 0.0f) { return 0.0f; } /* achromatic, including black */ - if (color.r == max) { - hue = (float)(color.g - color.b) / delta; - } else if (color.g == max) { - hue = 2.0f + (float)(color.b - color.r) / delta; - } else { - hue = 4.0f + (float)(color.r - color.g) / delta; - } - hue *= 60.0f; - hue = (float)fabsmod(hue, 360.0f); - return hue; -} -/** - * \brief Change a colors hue. - * - * \param color Pointer to a color struct. - * \param hue The hue in degrees. - */ -void TCOD_color_set_hue(TCOD_color_t *color, float hue) { - TCOD_color_set_HSV(color, - hue, - TCOD_color_get_saturation(*color), - TCOD_color_get_value(*color)); -} -/** - * \brief Return a colors saturation. - * - * \param color A color struct. - * \return The colors saturation. (0 to 1) - */ -float TCOD_color_get_saturation (TCOD_color_t color) { - float max = (float)(MAX(color.r, MAX(color.g, color.b))) / 255.0f; - float min = (float)(MIN(color.r, MIN(color.g, color.b))) / 255.0f; - float delta = max - min; - if (max == 0.0f) { return 0.0f; } - return delta / max; -} -/** - * \brief Change a colors saturation. - * - * \param color Pointer to a color struct. - * \param saturation The desired saturation value. - */ -void TCOD_color_set_saturation(TCOD_color_t *color, float saturation) { - TCOD_color_set_HSV(color, - TCOD_color_get_hue(*color), - saturation, - TCOD_color_get_value(*color)); -} -/** - * \brief Get a colors value. - * - * \param color A color struct. - * \return The colors value. (0 to 1) - */ -float TCOD_color_get_value(TCOD_color_t color) { - return (float)(MAX(color.r, MAX(color.g, color.b))) / 255.0f; -} -/** - * \brief Change a colors value. - * - * \param color Pointer to a color struct. - * \param value The desired value. - */ -void TCOD_color_set_value(TCOD_color_t *color, float value) { - TCOD_color_set_HSV(color, - TCOD_color_get_hue(*color), - TCOD_color_get_saturation(*color), - value); -} -/** - * \brief Shift a colors hue by an amount. - * - * \param color Pointer to a color struct. - * \param hue_shift The distance to shift the hue, in degrees. - */ -void TCOD_color_shift_hue(TCOD_color_t *color, float hue_shift) { - if (hue_shift == 0.0f) { return; } - TCOD_color_set_HSV(color, - TCOD_color_get_hue(*color) + hue_shift, - TCOD_color_get_saturation(*color), - TCOD_color_get_value(*color)); -} -/** - * \brief Scale a colors saturation and value. - * - * \param color Pointer to a color struct. - * \param saturation_coef Multiplier for this colors saturation. - * \param value_coef Multiplier for this colors value. - */ -void TCOD_color_scale_HSV(TCOD_color_t *color, - float saturation_coef, float value_coef) { - TCOD_color_set_HSV(color, - TCOD_color_get_hue(*color), - TCOD_color_get_saturation(*color) * saturation_coef, - TCOD_color_get_value(*color) * value_coef); -} -/** - * \brief Generate an interpolated gradient of colors. - * - * \param map Array to fill with the new gradient. - * \param nb_key The array size of the key_color and key_index parameters. - * \param key_color An array of colors to use, in order. - * \param key_index An array mapping key_color items to the map array. - * - * \verbatim embed:rst:leading-asterisk - * .. code-block:: c - * - * TCOD_color_t[256] gradient; - * TCOD_color_t[4] key_color = {TCOD_black, TCOD_dark_amber, - * TCOD_cyan, TCOD_white}; - * int[4] key_index = {0, 64, 192, 255}; - * TCOD_color_gen_map(&gradient, 4, &key_color, &key_index); - * \endverbatim - */ -void TCOD_color_gen_map(TCOD_color_t *map, int nb_key, - const TCOD_color_t *key_color, const int *key_index) { - int segment = 0; - for (segment = 0; segment < nb_key - 1; ++segment) { - int idx_start = key_index[segment]; - int idx_end = key_index[segment + 1]; - int idx; - for (idx = idx_start; idx <= idx_end; ++idx) { - map[idx] = TCOD_color_lerp( - key_color[segment], - key_color[segment + 1], - (float)(idx - idx_start) / (idx_end - idx_start)); - } - } -} +/* +* libtcod +* Copyright (c) 2008-2018 Jice & Mingos & rmtew +* All rights reserved. +* +* Redistribution and use in source and binary forms, with or without +* modification, are permitted provided that the following conditions are met: +* * Redistributions of source code must retain the above copyright +* notice, this list of conditions and the following disclaimer. +* * Redistributions in binary form must reproduce the above copyright +* notice, this list of conditions and the following disclaimer in the +* documentation and/or other materials provided with the distribution. +* * The name of Jice or Mingos may not be used to endorse or promote +* products derived from this software without specific prior written +* permission. +* +* THIS SOFTWARE IS PROVIDED BY JICE, MINGOS AND RMTEW ``AS IS'' AND ANY +* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED +* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE +* DISCLAIMED. IN NO EVENT SHALL JICE, MINGOS OR RMTEW BE LIABLE FOR ANY +* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES +* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; +* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND +* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS +* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +*/ +#include "color.h" + +#include + +#include "libtcod_int.h" +#include "utility.h" + +/* grey levels */ +const TCOD_color_t TCOD_black={TCOD_BLACK}; +const TCOD_color_t TCOD_darkest_grey={TCOD_DARKEST_GREY}; +const TCOD_color_t TCOD_darker_grey={TCOD_DARKER_GREY}; +const TCOD_color_t TCOD_dark_grey={TCOD_DARK_GREY}; +const TCOD_color_t TCOD_grey={TCOD_GREY}; +const TCOD_color_t TCOD_light_grey={TCOD_LIGHT_GREY}; +const TCOD_color_t TCOD_lighter_grey={TCOD_LIGHTER_GREY}; +const TCOD_color_t TCOD_lightest_grey={TCOD_LIGHTEST_GREY}; +const TCOD_color_t TCOD_darkest_gray={TCOD_DARKEST_GREY}; +const TCOD_color_t TCOD_darker_gray={TCOD_DARKER_GREY}; +const TCOD_color_t TCOD_dark_gray={TCOD_DARK_GREY}; +const TCOD_color_t TCOD_gray={TCOD_GREY}; +const TCOD_color_t TCOD_light_gray={TCOD_LIGHT_GREY}; +const TCOD_color_t TCOD_lighter_gray={TCOD_LIGHTER_GREY}; +const TCOD_color_t TCOD_lightest_gray={TCOD_LIGHTEST_GREY}; +const TCOD_color_t TCOD_white={TCOD_WHITE}; + +/* sepia */ +const TCOD_color_t TCOD_darkest_sepia={TCOD_DARKEST_SEPIA}; +const TCOD_color_t TCOD_darker_sepia={TCOD_DARKER_SEPIA}; +const TCOD_color_t TCOD_dark_sepia={TCOD_DARK_SEPIA}; +const TCOD_color_t TCOD_sepia={TCOD_SEPIA}; +const TCOD_color_t TCOD_light_sepia={TCOD_LIGHT_SEPIA}; +const TCOD_color_t TCOD_lighter_sepia={TCOD_LIGHTER_SEPIA}; +const TCOD_color_t TCOD_lightest_sepia={TCOD_LIGHTEST_SEPIA}; + +/* standard colors */ +const TCOD_color_t TCOD_red = {TCOD_RED}; +const TCOD_color_t TCOD_flame = {TCOD_FLAME}; +const TCOD_color_t TCOD_orange = {TCOD_ORANGE}; +const TCOD_color_t TCOD_amber = {TCOD_AMBER}; +const TCOD_color_t TCOD_yellow = {TCOD_YELLOW}; +const TCOD_color_t TCOD_lime = {TCOD_LIME}; +const TCOD_color_t TCOD_chartreuse = {TCOD_CHARTREUSE}; +const TCOD_color_t TCOD_green = {TCOD_GREEN}; +const TCOD_color_t TCOD_sea = {TCOD_SEA}; +const TCOD_color_t TCOD_turquoise = {TCOD_TURQUOISE}; +const TCOD_color_t TCOD_cyan = {TCOD_CYAN}; +const TCOD_color_t TCOD_sky = {TCOD_SKY}; +const TCOD_color_t TCOD_azure = {TCOD_AZURE}; +const TCOD_color_t TCOD_blue = {TCOD_BLUE}; +const TCOD_color_t TCOD_han = {TCOD_HAN}; +const TCOD_color_t TCOD_violet = {TCOD_VIOLET}; +const TCOD_color_t TCOD_purple = {TCOD_PURPLE}; +const TCOD_color_t TCOD_fuchsia = {TCOD_FUCHSIA}; +const TCOD_color_t TCOD_magenta = {TCOD_MAGENTA}; +const TCOD_color_t TCOD_pink = {TCOD_PINK}; +const TCOD_color_t TCOD_crimson = {TCOD_CRIMSON}; + +/* dark colors */ +const TCOD_color_t TCOD_dark_red = {TCOD_DARK_RED}; +const TCOD_color_t TCOD_dark_flame = {TCOD_DARK_FLAME}; +const TCOD_color_t TCOD_dark_orange = {TCOD_DARK_ORANGE}; +const TCOD_color_t TCOD_dark_amber = {TCOD_DARK_AMBER}; +const TCOD_color_t TCOD_dark_yellow = {TCOD_DARK_YELLOW}; +const TCOD_color_t TCOD_dark_lime = {TCOD_DARK_LIME}; +const TCOD_color_t TCOD_dark_chartreuse = {TCOD_DARK_CHARTREUSE}; +const TCOD_color_t TCOD_dark_green = {TCOD_DARK_GREEN}; +const TCOD_color_t TCOD_dark_sea = {TCOD_DARK_SEA}; +const TCOD_color_t TCOD_dark_turquoise = {TCOD_DARK_TURQUOISE}; +const TCOD_color_t TCOD_dark_cyan = {TCOD_DARK_CYAN}; +const TCOD_color_t TCOD_dark_sky = {TCOD_DARK_SKY}; +const TCOD_color_t TCOD_dark_azure = {TCOD_DARK_AZURE}; +const TCOD_color_t TCOD_dark_blue = {TCOD_DARK_BLUE}; +const TCOD_color_t TCOD_dark_han = {TCOD_DARK_HAN}; +const TCOD_color_t TCOD_dark_violet = {TCOD_DARK_VIOLET}; +const TCOD_color_t TCOD_dark_purple = {TCOD_DARK_PURPLE}; +const TCOD_color_t TCOD_dark_fuchsia = {TCOD_DARK_FUCHSIA}; +const TCOD_color_t TCOD_dark_magenta = {TCOD_DARK_MAGENTA}; +const TCOD_color_t TCOD_dark_pink = {TCOD_DARK_PINK}; +const TCOD_color_t TCOD_dark_crimson = {TCOD_DARK_CRIMSON}; + +/* darker colors */ +const TCOD_color_t TCOD_darker_red = {TCOD_DARKER_RED}; +const TCOD_color_t TCOD_darker_flame = {TCOD_DARKER_FLAME}; +const TCOD_color_t TCOD_darker_orange = {TCOD_DARKER_ORANGE}; +const TCOD_color_t TCOD_darker_amber = {TCOD_DARKER_AMBER}; +const TCOD_color_t TCOD_darker_yellow = {TCOD_DARKER_YELLOW}; +const TCOD_color_t TCOD_darker_lime = {TCOD_DARKER_LIME}; +const TCOD_color_t TCOD_darker_chartreuse = {TCOD_DARKER_CHARTREUSE}; +const TCOD_color_t TCOD_darker_green = {TCOD_DARKER_GREEN}; +const TCOD_color_t TCOD_darker_sea = {TCOD_DARKER_SEA}; +const TCOD_color_t TCOD_darker_turquoise = {TCOD_DARKER_TURQUOISE}; +const TCOD_color_t TCOD_darker_cyan = {TCOD_DARKER_CYAN}; +const TCOD_color_t TCOD_darker_sky = {TCOD_DARKER_SKY}; +const TCOD_color_t TCOD_darker_azure = {TCOD_DARKER_AZURE}; +const TCOD_color_t TCOD_darker_blue = {TCOD_DARKER_BLUE}; +const TCOD_color_t TCOD_darker_han = {TCOD_DARKER_HAN}; +const TCOD_color_t TCOD_darker_violet = {TCOD_DARKER_VIOLET}; +const TCOD_color_t TCOD_darker_purple = {TCOD_DARKER_PURPLE}; +const TCOD_color_t TCOD_darker_fuchsia = {TCOD_DARKER_FUCHSIA}; +const TCOD_color_t TCOD_darker_magenta = {TCOD_DARKER_MAGENTA}; +const TCOD_color_t TCOD_darker_pink = {TCOD_DARKER_PINK}; +const TCOD_color_t TCOD_darker_crimson = {TCOD_DARKER_CRIMSON}; + +/* darkest colors */ +const TCOD_color_t TCOD_darkest_red = {TCOD_DARKEST_RED}; +const TCOD_color_t TCOD_darkest_flame = {TCOD_DARKEST_FLAME}; +const TCOD_color_t TCOD_darkest_orange = {TCOD_DARKEST_ORANGE}; +const TCOD_color_t TCOD_darkest_amber = {TCOD_DARKEST_AMBER}; +const TCOD_color_t TCOD_darkest_yellow = {TCOD_DARKEST_YELLOW}; +const TCOD_color_t TCOD_darkest_lime = {TCOD_DARKEST_LIME}; +const TCOD_color_t TCOD_darkest_chartreuse = {TCOD_DARKEST_CHARTREUSE}; +const TCOD_color_t TCOD_darkest_green = {TCOD_DARKEST_GREEN}; +const TCOD_color_t TCOD_darkest_sea = {TCOD_DARKEST_SEA}; +const TCOD_color_t TCOD_darkest_turquoise = {TCOD_DARKEST_TURQUOISE}; +const TCOD_color_t TCOD_darkest_cyan = {TCOD_DARKEST_CYAN}; +const TCOD_color_t TCOD_darkest_sky = {TCOD_DARKEST_SKY}; +const TCOD_color_t TCOD_darkest_azure = {TCOD_DARKEST_AZURE}; +const TCOD_color_t TCOD_darkest_blue = {TCOD_DARKEST_BLUE}; +const TCOD_color_t TCOD_darkest_han = {TCOD_DARKEST_HAN}; +const TCOD_color_t TCOD_darkest_violet = {TCOD_DARKEST_VIOLET}; +const TCOD_color_t TCOD_darkest_purple = {TCOD_DARKEST_PURPLE}; +const TCOD_color_t TCOD_darkest_fuchsia = {TCOD_DARKEST_FUCHSIA}; +const TCOD_color_t TCOD_darkest_magenta = {TCOD_DARKEST_MAGENTA}; +const TCOD_color_t TCOD_darkest_pink = {TCOD_DARKEST_PINK}; +const TCOD_color_t TCOD_darkest_crimson = {TCOD_DARKEST_CRIMSON}; + +/* light colors */ +const TCOD_color_t TCOD_light_red = {TCOD_LIGHT_RED}; +const TCOD_color_t TCOD_light_flame = {TCOD_LIGHT_FLAME}; +const TCOD_color_t TCOD_light_orange = {TCOD_LIGHT_ORANGE}; +const TCOD_color_t TCOD_light_amber = {TCOD_LIGHT_AMBER}; +const TCOD_color_t TCOD_light_yellow = {TCOD_LIGHT_YELLOW}; +const TCOD_color_t TCOD_light_lime = {TCOD_LIGHT_LIME}; +const TCOD_color_t TCOD_light_chartreuse = {TCOD_LIGHT_CHARTREUSE}; +const TCOD_color_t TCOD_light_green = {TCOD_LIGHT_GREEN}; +const TCOD_color_t TCOD_light_sea = {TCOD_LIGHT_SEA}; +const TCOD_color_t TCOD_light_turquoise = {TCOD_LIGHT_TURQUOISE}; +const TCOD_color_t TCOD_light_cyan = {TCOD_LIGHT_CYAN}; +const TCOD_color_t TCOD_light_sky = {TCOD_LIGHT_SKY}; +const TCOD_color_t TCOD_light_azure = {TCOD_LIGHT_AZURE}; +const TCOD_color_t TCOD_light_blue = {TCOD_LIGHT_BLUE}; +const TCOD_color_t TCOD_light_han = {TCOD_LIGHT_HAN}; +const TCOD_color_t TCOD_light_violet = {TCOD_LIGHT_VIOLET}; +const TCOD_color_t TCOD_light_purple = {TCOD_LIGHT_PURPLE}; +const TCOD_color_t TCOD_light_fuchsia = {TCOD_LIGHT_FUCHSIA}; +const TCOD_color_t TCOD_light_magenta = {TCOD_LIGHT_MAGENTA}; +const TCOD_color_t TCOD_light_pink = {TCOD_LIGHT_PINK}; +const TCOD_color_t TCOD_light_crimson = {TCOD_LIGHT_CRIMSON}; + +/*lighter colors */ +const TCOD_color_t TCOD_lighter_red = {TCOD_LIGHTER_RED}; +const TCOD_color_t TCOD_lighter_flame = {TCOD_LIGHTER_FLAME}; +const TCOD_color_t TCOD_lighter_orange = {TCOD_LIGHTER_ORANGE}; +const TCOD_color_t TCOD_lighter_amber = {TCOD_LIGHTER_AMBER}; +const TCOD_color_t TCOD_lighter_yellow = {TCOD_LIGHTER_YELLOW}; +const TCOD_color_t TCOD_lighter_lime = {TCOD_LIGHTER_LIME}; +const TCOD_color_t TCOD_lighter_chartreuse = {TCOD_LIGHTER_CHARTREUSE}; +const TCOD_color_t TCOD_lighter_green = {TCOD_LIGHTER_GREEN}; +const TCOD_color_t TCOD_lighter_sea = {TCOD_LIGHTER_SEA}; +const TCOD_color_t TCOD_lighter_turquoise = {TCOD_LIGHTER_TURQUOISE}; +const TCOD_color_t TCOD_lighter_cyan = {TCOD_LIGHTER_CYAN}; +const TCOD_color_t TCOD_lighter_sky = {TCOD_LIGHTER_SKY}; +const TCOD_color_t TCOD_lighter_azure = {TCOD_LIGHTER_AZURE}; +const TCOD_color_t TCOD_lighter_blue = {TCOD_LIGHTER_BLUE}; +const TCOD_color_t TCOD_lighter_han = {TCOD_LIGHTER_HAN}; +const TCOD_color_t TCOD_lighter_violet = {TCOD_LIGHTER_VIOLET}; +const TCOD_color_t TCOD_lighter_purple = {TCOD_LIGHTER_PURPLE}; +const TCOD_color_t TCOD_lighter_fuchsia = {TCOD_LIGHTER_FUCHSIA}; +const TCOD_color_t TCOD_lighter_magenta = {TCOD_LIGHTER_MAGENTA}; +const TCOD_color_t TCOD_lighter_pink = {TCOD_LIGHTER_PINK}; +const TCOD_color_t TCOD_lighter_crimson = {TCOD_LIGHTER_CRIMSON}; + +/* lightest colors */ +const TCOD_color_t TCOD_lightest_red = {TCOD_LIGHTEST_RED}; +const TCOD_color_t TCOD_lightest_flame = {TCOD_LIGHTEST_FLAME}; +const TCOD_color_t TCOD_lightest_orange = {TCOD_LIGHTEST_ORANGE}; +const TCOD_color_t TCOD_lightest_amber = {TCOD_LIGHTEST_AMBER}; +const TCOD_color_t TCOD_lightest_yellow = {TCOD_LIGHTEST_YELLOW}; +const TCOD_color_t TCOD_lightest_lime = {TCOD_LIGHTEST_LIME}; +const TCOD_color_t TCOD_lightest_chartreuse = {TCOD_LIGHTEST_CHARTREUSE}; +const TCOD_color_t TCOD_lightest_green = {TCOD_LIGHTEST_GREEN}; +const TCOD_color_t TCOD_lightest_sea = {TCOD_LIGHTEST_SEA}; +const TCOD_color_t TCOD_lightest_turquoise = {TCOD_LIGHTEST_TURQUOISE}; +const TCOD_color_t TCOD_lightest_cyan = {TCOD_LIGHTEST_CYAN}; +const TCOD_color_t TCOD_lightest_sky = {TCOD_LIGHTEST_SKY}; +const TCOD_color_t TCOD_lightest_azure = {TCOD_LIGHTEST_AZURE}; +const TCOD_color_t TCOD_lightest_blue = {TCOD_LIGHTEST_BLUE}; +const TCOD_color_t TCOD_lightest_han = {TCOD_LIGHTEST_HAN}; +const TCOD_color_t TCOD_lightest_violet = {TCOD_LIGHTEST_VIOLET}; +const TCOD_color_t TCOD_lightest_purple = {TCOD_LIGHTEST_PURPLE}; +const TCOD_color_t TCOD_lightest_fuchsia = {TCOD_LIGHTEST_FUCHSIA}; +const TCOD_color_t TCOD_lightest_magenta = {TCOD_LIGHTEST_MAGENTA}; +const TCOD_color_t TCOD_lightest_pink = {TCOD_LIGHTEST_PINK}; +const TCOD_color_t TCOD_lightest_crimson = {TCOD_LIGHTEST_CRIMSON}; + +/* desaturated colors */ +const TCOD_color_t TCOD_desaturated_red = {TCOD_DESATURATED_RED}; +const TCOD_color_t TCOD_desaturated_flame = {TCOD_DESATURATED_FLAME}; +const TCOD_color_t TCOD_desaturated_orange = {TCOD_DESATURATED_ORANGE}; +const TCOD_color_t TCOD_desaturated_amber = {TCOD_DESATURATED_AMBER}; +const TCOD_color_t TCOD_desaturated_yellow = {TCOD_DESATURATED_YELLOW}; +const TCOD_color_t TCOD_desaturated_lime = {TCOD_DESATURATED_LIME}; +const TCOD_color_t TCOD_desaturated_chartreuse = {TCOD_DESATURATED_CHARTREUSE}; +const TCOD_color_t TCOD_desaturated_green = {TCOD_DESATURATED_GREEN}; +const TCOD_color_t TCOD_desaturated_sea = {TCOD_DESATURATED_SEA}; +const TCOD_color_t TCOD_desaturated_turquoise = {TCOD_DESATURATED_TURQUOISE}; +const TCOD_color_t TCOD_desaturated_cyan = {TCOD_DESATURATED_CYAN}; +const TCOD_color_t TCOD_desaturated_sky = {TCOD_DESATURATED_SKY}; +const TCOD_color_t TCOD_desaturated_azure = {TCOD_DESATURATED_AZURE}; +const TCOD_color_t TCOD_desaturated_blue = {TCOD_DESATURATED_BLUE}; +const TCOD_color_t TCOD_desaturated_han = {TCOD_DESATURATED_HAN}; +const TCOD_color_t TCOD_desaturated_violet = {TCOD_DESATURATED_VIOLET}; +const TCOD_color_t TCOD_desaturated_purple = {TCOD_DESATURATED_PURPLE}; +const TCOD_color_t TCOD_desaturated_fuchsia = {TCOD_DESATURATED_FUCHSIA}; +const TCOD_color_t TCOD_desaturated_magenta = {TCOD_DESATURATED_MAGENTA}; +const TCOD_color_t TCOD_desaturated_pink = {TCOD_DESATURATED_PINK}; +const TCOD_color_t TCOD_desaturated_crimson = {TCOD_DESATURATED_CRIMSON}; + +/* metallic */ +const TCOD_color_t TCOD_brass = {TCOD_BRASS}; +const TCOD_color_t TCOD_copper = {TCOD_COPPER}; +const TCOD_color_t TCOD_gold = {TCOD_GOLD}; +const TCOD_color_t TCOD_silver = {TCOD_SILVER}; + +/* miscellaneous */ +const TCOD_color_t TCOD_celadon = {TCOD_CELADON}; +const TCOD_color_t TCOD_peach = {TCOD_PEACH}; + +/* color array */ +const TCOD_color_t TCOD_colors[TCOD_COLOR_NB][TCOD_COLOR_LEVELS] = { + {{TCOD_DESATURATED_RED},{TCOD_LIGHTEST_RED},{TCOD_LIGHTER_RED},{TCOD_LIGHT_RED},{TCOD_RED},{TCOD_DARK_RED},{TCOD_DARKER_RED},{TCOD_DARKEST_RED}}, + {{TCOD_DESATURATED_FLAME},{TCOD_LIGHTEST_FLAME},{TCOD_LIGHTER_FLAME},{TCOD_LIGHT_FLAME},{TCOD_FLAME},{TCOD_DARK_FLAME},{TCOD_DARKER_FLAME},{TCOD_DARKEST_FLAME}}, + {{TCOD_DESATURATED_ORANGE},{TCOD_LIGHTEST_ORANGE},{TCOD_LIGHTER_ORANGE},{TCOD_LIGHT_ORANGE},{TCOD_ORANGE},{TCOD_DARK_ORANGE},{TCOD_DARKER_ORANGE},{TCOD_DARKEST_ORANGE}}, + {{TCOD_DESATURATED_AMBER},{TCOD_LIGHTEST_AMBER},{TCOD_LIGHTER_AMBER},{TCOD_LIGHT_AMBER},{TCOD_AMBER},{TCOD_DARK_AMBER},{TCOD_DARKER_AMBER},{TCOD_DARKEST_AMBER}}, + {{TCOD_DESATURATED_YELLOW},{TCOD_LIGHTEST_YELLOW},{TCOD_LIGHTER_YELLOW},{TCOD_LIGHT_YELLOW},{TCOD_YELLOW},{TCOD_DARK_YELLOW},{TCOD_DARKER_YELLOW},{TCOD_DARKEST_YELLOW}}, + {{TCOD_DESATURATED_LIME},{TCOD_LIGHTEST_LIME},{TCOD_LIGHTER_LIME},{TCOD_LIGHT_LIME},{TCOD_LIME},{TCOD_DARK_LIME},{TCOD_DARKER_LIME},{TCOD_DARKEST_LIME}}, + {{TCOD_DESATURATED_CHARTREUSE},{TCOD_LIGHTEST_CHARTREUSE},{TCOD_LIGHTER_CHARTREUSE},{TCOD_LIGHT_CHARTREUSE},{TCOD_CHARTREUSE},{TCOD_DARK_CHARTREUSE},{TCOD_DARKER_CHARTREUSE},{TCOD_DARKEST_CHARTREUSE}}, + {{TCOD_DESATURATED_GREEN},{TCOD_LIGHTEST_GREEN},{TCOD_LIGHTER_GREEN},{TCOD_LIGHT_GREEN},{TCOD_GREEN},{TCOD_DARK_GREEN},{TCOD_DARKER_GREEN},{TCOD_DARKEST_GREEN}}, + {{TCOD_DESATURATED_SEA},{TCOD_LIGHTEST_SEA},{TCOD_LIGHTER_SEA},{TCOD_LIGHT_SEA},{TCOD_SEA},{TCOD_DARK_SEA},{TCOD_DARKER_SEA},{TCOD_DARKEST_SEA}}, + {{TCOD_DESATURATED_TURQUOISE},{TCOD_LIGHTEST_TURQUOISE},{TCOD_LIGHTER_TURQUOISE},{TCOD_LIGHT_TURQUOISE},{TCOD_TURQUOISE},{TCOD_DARK_TURQUOISE},{TCOD_DARKER_TURQUOISE},{TCOD_DARKEST_TURQUOISE}}, + {{TCOD_DESATURATED_CYAN},{TCOD_LIGHTEST_CYAN},{TCOD_LIGHTER_CYAN},{TCOD_LIGHT_CYAN},{TCOD_CYAN},{TCOD_DARK_CYAN},{TCOD_DARKER_CYAN},{TCOD_DARKEST_CYAN}}, + {{TCOD_DESATURATED_SKY},{TCOD_LIGHTEST_SKY},{TCOD_LIGHTER_SKY},{TCOD_LIGHT_SKY},{TCOD_SKY},{TCOD_DARK_SKY},{TCOD_DARKER_SKY},{TCOD_DARKEST_SKY}}, + {{TCOD_DESATURATED_AZURE},{TCOD_LIGHTEST_AZURE},{TCOD_LIGHTER_AZURE},{TCOD_LIGHT_AZURE},{TCOD_AZURE},{TCOD_DARK_AZURE},{TCOD_DARKER_AZURE},{TCOD_DARKEST_AZURE}}, + {{TCOD_DESATURATED_BLUE},{TCOD_LIGHTEST_BLUE},{TCOD_LIGHTER_BLUE},{TCOD_LIGHT_BLUE},{TCOD_BLUE},{TCOD_DARK_BLUE},{TCOD_DARKER_BLUE},{TCOD_DARKEST_BLUE}}, + {{TCOD_DESATURATED_HAN},{TCOD_LIGHTEST_HAN},{TCOD_LIGHTER_HAN},{TCOD_LIGHT_HAN},{TCOD_HAN},{TCOD_DARK_HAN},{TCOD_DARKER_HAN},{TCOD_DARKEST_HAN}}, + {{TCOD_DESATURATED_VIOLET},{TCOD_LIGHTEST_VIOLET},{TCOD_LIGHTER_VIOLET},{TCOD_LIGHT_VIOLET},{TCOD_VIOLET},{TCOD_DARK_VIOLET},{TCOD_DARKER_VIOLET},{TCOD_DARKEST_VIOLET}}, + {{TCOD_DESATURATED_PURPLE},{TCOD_LIGHTEST_PURPLE},{TCOD_LIGHTER_PURPLE},{TCOD_LIGHT_PURPLE},{TCOD_PURPLE},{TCOD_DARK_PURPLE},{TCOD_DARKER_PURPLE},{TCOD_DARKEST_PURPLE}}, + {{TCOD_DESATURATED_FUCHSIA},{TCOD_LIGHTEST_FUCHSIA},{TCOD_LIGHTER_FUCHSIA},{TCOD_LIGHT_FUCHSIA},{TCOD_FUCHSIA},{TCOD_DARK_FUCHSIA},{TCOD_DARKER_FUCHSIA},{TCOD_DARKEST_FUCHSIA}}, + {{TCOD_DESATURATED_MAGENTA},{TCOD_LIGHTEST_MAGENTA},{TCOD_LIGHTER_MAGENTA},{TCOD_LIGHT_MAGENTA},{TCOD_MAGENTA},{TCOD_DARK_MAGENTA},{TCOD_DARKER_MAGENTA},{TCOD_DARKEST_MAGENTA}}, + {{TCOD_DESATURATED_PINK},{TCOD_LIGHTEST_PINK},{TCOD_LIGHTER_PINK},{TCOD_LIGHT_PINK},{TCOD_PINK},{TCOD_DARK_PINK},{TCOD_DARKER_PINK},{TCOD_DARKEST_PINK}}, + {{TCOD_DESATURATED_CRIMSON},{TCOD_LIGHTEST_CRIMSON},{TCOD_LIGHTER_CRIMSON},{TCOD_LIGHT_CRIMSON},{TCOD_CRIMSON},{TCOD_DARK_CRIMSON},{TCOD_DARKER_CRIMSON},{TCOD_DARKEST_CRIMSON}} +}; +/** + * \brief Return a new TCOD_color_t from RGB values. + * + * This function is redundant, you should use a braced initializer instead: + * + * TCOD_color_t white = {255, 255, 255}; + */ +TCOD_color_t TCOD_color_RGB(uint8_t r, uint8_t g, uint8_t b) { + TCOD_color_t new_color = {r, g, b}; + return new_color; +} +/** + * \brief Return a new TCOD_color_t from HSV values. + * + * \param hue The colors hue (in degrees.) + * \param saturation The colors saturation (from 0 to 1) + * \param value The colors value (from 0 to 1) + * \return A new TCOD_color_t struct. + * + * The saturation and value parameters are automatically clamped to 0 and 1. + * + * TCOD_color_t light_blue = TCOD_color_HSV(240.0f, 0.75f, 1.0f); + * + * Use TCOD_color_set_HSV to fill an existing struct with HSV values. + */ +TCOD_color_t TCOD_color_HSV(float hue, float saturation, float value) { + TCOD_color_t new_color; + TCOD_color_set_HSV(&new_color, hue, saturation, value); + return new_color; +} +/** + * \brief Return a true value if c1 and c2 are equal. + */ +bool TCOD_color_equals(TCOD_color_t c1, TCOD_color_t c2) { + return (c1.r == c2.r && c1.g == c2.g && c1.b == c2.b); +} +/** + * \brief Add two colors together and return the result. + * + * \param c1 The first color. + * \param c2 The second color. + * \return A new TCOD_color_t struct with the result. + */ +TCOD_color_t TCOD_color_add(TCOD_color_t c1, TCOD_color_t c2) { + TCOD_color_t new_color = { + (uint8_t)MIN(255, (int)c1.r + c2.r), + (uint8_t)MIN(255, (int)c1.g + c2.g), + (uint8_t)MIN(255, (int)c1.b + c2.b)}; + return new_color; +} +/** + * \brief Subtract c2 from c1 and return the result. + * + * \param c1 The first color. + * \param c2 The second color. + * \return A new TCOD_color_t struct with the result. + */ +TCOD_color_t TCOD_color_subtract(TCOD_color_t c1, TCOD_color_t c2) { + TCOD_color_t new_color = { + (uint8_t)MAX(0, (int)c1.r - c2.r), + (uint8_t)MAX(0, (int)c1.g - c2.g), + (uint8_t)MAX(0, (int)c1.b - c2.b)}; + return new_color; +} +/** + * \brief Multiply two colors together and return the result. + * + * \param c1 The first color. + * \param c2 The second color. + * \return A new TCOD_color_t struct with the result. + */ +TCOD_color_t TCOD_color_multiply(TCOD_color_t c1, TCOD_color_t c2) { + TCOD_color_t new_color = { + (uint8_t)(((int)c1.r) * c2.r / 255), + (uint8_t)(((int)c1.g) * c2.g / 255), + (uint8_t)(((int)c1.b) * c2.b / 255)}; + return new_color; +} +/** + * \brief Multiply a color with a scalar value and return the result. + * + * \param c1 The color to multiply. + * \param value The scalar float. + * \return A new TCOD_color_t struct with the result. + */ +TCOD_color_t TCOD_color_multiply_scalar(TCOD_color_t c1, float value) { + TCOD_color_t new_color = { + (uint8_t)CLAMP(0.0f, 255.0f, (float)c1.r * value), + (uint8_t)CLAMP(0.0f, 255.0f, (float)c1.g * value), + (uint8_t)CLAMP(0.0f, 255.0f, (float)c1.b * value)}; + return new_color; +} +/** + * \brief Interpolate two colors together and return the result. + * + * \param c1 The first color (where coef if 0) + * \param c2 The second color (where coef if 1) + * \param coef The coefficient. + * \return A new TCOD_color_t struct with the result. + */ +TCOD_color_t TCOD_color_lerp(TCOD_color_t c1, TCOD_color_t c2, float coef) { + TCOD_color_t new_color = { + (uint8_t)(c1.r + (c2.r - c1.r) * coef), + (uint8_t)(c1.g + (c2.g - c1.g) * coef), + (uint8_t)(c1.b + (c2.b - c1.b) * coef)}; + return new_color; +} +/* Return floor modulo for double values. */ +static double fabsmod(double x, double n) { + double m = fmod(x, n); + return m < 0 ? m+n : m; +} + +/** + * \brief Sets a colors values from HSV values. + * + * \param color The color to be changed. + * \param hue The colors hue (in degrees.) + * \param saturation The colors saturation (from 0 to 1) + * \param value The colors value (from 0 to 1) + */ +void TCOD_color_set_HSV(TCOD_color_t *color, + float hue, float saturation, float value) { + int hue_section; + float hue_fraction, p, q, t; + + saturation = CLAMP(0.0f, 1.0f, saturation); + value = CLAMP(0.0f, 1.0f, value); + if( saturation == 0.0f ) { /* achromatic (grey) */ + color->r = color->g = color->b = (uint8_t)(value * 255.0f + 0.5f); + return; + } + + hue = (float)fabsmod(hue, 360.0f); + hue /= 60.0f; /* sector 0 to 5 */ + hue_section = (int)floor(hue); + hue_fraction = hue - hue_section; /* fraction between sections */ + p = value * (1 - saturation); + q = value * (1 - saturation * hue_fraction); + t = value * (1 - saturation * (1 - hue_fraction)); + + switch (hue_section) { + default: + case 0: /* red/yellow */ + color->r = (uint8_t)(value * 255.0f + 0.5f); + color->g = (uint8_t)(t * 255.0f + 0.5f); + color->b = (uint8_t)(p * 255.0f + 0.5f); + break; + case 1: /* yellow/green */ + color->r = (uint8_t)(q * 255.0f + 0.5f); + color->g = (uint8_t)(value * 255.0f + 0.5f); + color->b = (uint8_t)(p * 255.0f + 0.5f); + break; + case 2: /* green/cyan */ + color->r = (uint8_t)(p * 255.0f + 0.5f); + color->g = (uint8_t)(value * 255.0f + 0.5f); + color->b = (uint8_t)(t * 255.0f + 0.5f); + break; + case 3: /* cyan/blue */ + color->r = (uint8_t)(p * 255.0f + 0.5f); + color->g = (uint8_t)(q * 255.0f + 0.5f); + color->b = (uint8_t)(value * 255.0f + 0.5f); + break; + case 4: /* blue/purple */ + color->r = (uint8_t)(t * 255.0f + 0.5f); + color->g = (uint8_t)(p * 255.0f + 0.5f); + color->b = (uint8_t)(value * 255.0f + 0.5f); + break; + case 5: /* purple/red */ + color->r = (uint8_t)(value * 255.0f + 0.5f); + color->g = (uint8_t)(p * 255.0f + 0.5f); + color->b = (uint8_t)(q * 255.0f + 0.5f); + break; + } +} +/** + * \brief Get a set of HSV values from a color. + * + * \param color The color + * \param hue Pointer to a float, filled with the hue. (degrees) + * \param saturation Pointer to a float, filled with the saturation. (0 to 1) + * \param value Pointer to a float, filled with the value. (0 to 1) + * + * The hue, saturation, and value parameters can not be NULL pointers, + */ +void TCOD_color_get_HSV(TCOD_color_t color, + float *hue, float *saturation, float *value) { + *hue = TCOD_color_get_hue(color); + *saturation = TCOD_color_get_saturation(color); + *value = TCOD_color_get_value(color); + return; +} +/** + * \brief Return a colors hue. + * + * \param color A color struct. + * \return The colors hue. (degrees) + */ +float TCOD_color_get_hue(TCOD_color_t color) { + uint8_t max = MAX(color.r, MAX(color.g, color.b)); + uint8_t min = MIN(color.r, MIN(color.g, color.b)); + float delta = (float)max - (float)min; + float hue; /* degrees */ + if (delta == 0.0f) { return 0.0f; } /* achromatic, including black */ + if (color.r == max) { + hue = (float)(color.g - color.b) / delta; + } else if (color.g == max) { + hue = 2.0f + (float)(color.b - color.r) / delta; + } else { + hue = 4.0f + (float)(color.r - color.g) / delta; + } + hue *= 60.0f; + hue = (float)fabsmod(hue, 360.0f); + return hue; +} +/** + * \brief Change a colors hue. + * + * \param color Pointer to a color struct. + * \param hue The hue in degrees. + */ +void TCOD_color_set_hue(TCOD_color_t *color, float hue) { + TCOD_color_set_HSV(color, + hue, + TCOD_color_get_saturation(*color), + TCOD_color_get_value(*color)); +} +/** + * \brief Return a colors saturation. + * + * \param color A color struct. + * \return The colors saturation. (0 to 1) + */ +float TCOD_color_get_saturation (TCOD_color_t color) { + float max = (float)(MAX(color.r, MAX(color.g, color.b))) / 255.0f; + float min = (float)(MIN(color.r, MIN(color.g, color.b))) / 255.0f; + float delta = max - min; + if (max == 0.0f) { return 0.0f; } + return delta / max; +} +/** + * \brief Change a colors saturation. + * + * \param color Pointer to a color struct. + * \param saturation The desired saturation value. + */ +void TCOD_color_set_saturation(TCOD_color_t *color, float saturation) { + TCOD_color_set_HSV(color, + TCOD_color_get_hue(*color), + saturation, + TCOD_color_get_value(*color)); +} +/** + * \brief Get a colors value. + * + * \param color A color struct. + * \return The colors value. (0 to 1) + */ +float TCOD_color_get_value(TCOD_color_t color) { + return (float)(MAX(color.r, MAX(color.g, color.b))) / 255.0f; +} +/** + * \brief Change a colors value. + * + * \param color Pointer to a color struct. + * \param value The desired value. + */ +void TCOD_color_set_value(TCOD_color_t *color, float value) { + TCOD_color_set_HSV(color, + TCOD_color_get_hue(*color), + TCOD_color_get_saturation(*color), + value); +} +/** + * \brief Shift a colors hue by an amount. + * + * \param color Pointer to a color struct. + * \param hue_shift The distance to shift the hue, in degrees. + */ +void TCOD_color_shift_hue(TCOD_color_t *color, float hue_shift) { + if (hue_shift == 0.0f) { return; } + TCOD_color_set_HSV(color, + TCOD_color_get_hue(*color) + hue_shift, + TCOD_color_get_saturation(*color), + TCOD_color_get_value(*color)); +} +/** + * \brief Scale a colors saturation and value. + * + * \param color Pointer to a color struct. + * \param saturation_coef Multiplier for this colors saturation. + * \param value_coef Multiplier for this colors value. + */ +void TCOD_color_scale_HSV(TCOD_color_t *color, + float saturation_coef, float value_coef) { + TCOD_color_set_HSV(color, + TCOD_color_get_hue(*color), + TCOD_color_get_saturation(*color) * saturation_coef, + TCOD_color_get_value(*color) * value_coef); +} +/** + * \brief Generate an interpolated gradient of colors. + * + * \param map Array to fill with the new gradient. + * \param nb_key The array size of the key_color and key_index parameters. + * \param key_color An array of colors to use, in order. + * \param key_index An array mapping key_color items to the map array. + * + * \verbatim embed:rst:leading-asterisk + * .. code-block:: c + * + * TCOD_color_t[256] gradient; + * TCOD_color_t[4] key_color = {TCOD_black, TCOD_dark_amber, + * TCOD_cyan, TCOD_white}; + * int[4] key_index = {0, 64, 192, 255}; + * TCOD_color_gen_map(&gradient, 4, &key_color, &key_index); + * \endverbatim + */ +void TCOD_color_gen_map(TCOD_color_t *map, int nb_key, + const TCOD_color_t *key_color, const int *key_index) { + int segment = 0; + for (segment = 0; segment < nb_key - 1; ++segment) { + int idx_start = key_index[segment]; + int idx_end = key_index[segment + 1]; + int idx; + for (idx = idx_start; idx <= idx_end; ++idx) { + map[idx] = TCOD_color_lerp( + key_color[segment], + key_color[segment + 1], + (float)(idx - idx_start) / (idx_end - idx_start)); + } + } +} diff --git a/tcod_sys/libtcod/src/console.cpp b/tcod_sys/libtcod/src/libtcod/console.cpp similarity index 86% rename from tcod_sys/libtcod/src/console.cpp rename to tcod_sys/libtcod/src/libtcod/console.cpp index 34fb53e2a..d1ccb639f 100644 --- a/tcod_sys/libtcod/src/console.cpp +++ b/tcod_sys/libtcod/src/libtcod/console.cpp @@ -1,441 +1,454 @@ -/* -* libtcod -* Copyright (c) 2008-2018 Jice & Mingos & rmtew -* All rights reserved. -* -* Redistribution and use in source and binary forms, with or without -* modification, are permitted provided that the following conditions are met: -* * Redistributions of source code must retain the above copyright -* notice, this list of conditions and the following disclaimer. -* * Redistributions in binary form must reproduce the above copyright -* notice, this list of conditions and the following disclaimer in the -* documentation and/or other materials provided with the distribution. -* * The name of Jice or Mingos may not be used to endorse or promote -* products derived from this software without specific prior written -* permission. -* -* THIS SOFTWARE IS PROVIDED BY JICE, MINGOS AND RMTEW ``AS IS'' AND ANY -* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED -* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE -* DISCLAIMED. IN NO EVENT SHALL JICE, MINGOS OR RMTEW BE LIABLE FOR ANY -* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES -* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; -* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND -* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS -* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. -*/ -#include - -#include -#include -#include - -#include -#include - -#ifdef TCOD_CONSOLE_SUPPORT - -TCODConsole * TCODConsole::root = NULL; - -TCODConsole::TCODConsole() {} -TCODConsole::TCODConsole(int w, int h) { - data = TCOD_console_new(w,h); -} - -TCODConsole::TCODConsole(const char *filename) { - data = TCOD_console_from_file(filename); -} - -bool TCODConsole::loadAsc(const char *filename) { - return TCOD_console_load_asc(data,filename) != 0; -} -bool TCODConsole::saveAsc(const char *filename) const { - return TCOD_console_save_asc(data,filename) != 0; -} -bool TCODConsole::saveApf(const char *filename) const { - return TCOD_console_save_apf(data,filename) != 0; -} -bool TCODConsole::loadApf(const char *filename) { - return TCOD_console_load_apf(data,filename) != 0; -} - -void TCODConsole::setCustomFont(const char *fontFile, int flags,int nbCharHoriz, int nbCharVertic) { - TCOD_console_set_custom_font(fontFile,flags,nbCharHoriz,nbCharVertic); -} - -void TCODConsole::mapAsciiCodeToFont(int asciiCode, int fontCharX, int fontCharY) { - TCOD_console_map_ascii_code_to_font(asciiCode,fontCharX,fontCharY); -} - -void TCODConsole::mapAsciiCodesToFont(int firstAsciiCode, int nbCodes, int fontCharX, int fontCharY) { - TCOD_console_map_ascii_codes_to_font(firstAsciiCode,nbCodes,fontCharX,fontCharY); -} - -void TCODConsole::mapStringToFont(const char *s, int fontCharX, int fontCharY) { - TCOD_console_map_string_to_font(s, fontCharX, fontCharY); -} - -void TCODConsole::setDirty(int x, int y, int w, int h) { - TCOD_console_set_dirty(x,y,w,h); -} - -TCOD_key_t TCODConsole::checkForKeypress(int flags) { - return TCOD_sys_check_for_keypress(flags); -} - -TCOD_key_t TCODConsole::waitForKeypress(bool flush) { - return TCOD_sys_wait_for_keypress(flush); -} - -bool TCODConsole::isWindowClosed() { - return TCOD_console_is_window_closed() != 0; -} - -bool TCODConsole::hasMouseFocus() { - return TCOD_console_has_mouse_focus() != 0; -} - -bool TCODConsole::isActive() { - return TCOD_console_is_active() != 0; -} - -int TCODConsole::getWidth() const { - return TCOD_console_get_width(data); -} - -int TCODConsole::getHeight() const { - return TCOD_console_get_height(data); -} - -void TCODConsole::setColorControl(TCOD_colctrl_t con, const TCODColor &fore, const TCODColor &back) { - TCOD_color_t b={back.r,back.g,back.b},f={fore.r,fore.g,fore.b}; - TCOD_console_set_color_control(con,f,b); -} - -TCODColor TCODConsole::getDefaultBackground() const { - TCOD_color_t c= TCOD_console_get_default_background(data); - TCODColor ret; - ret.r=c.r; - ret.g=c.g; - ret.b=c.b; - return ret; -} -TCODColor TCODConsole::getDefaultForeground() const { - return TCOD_console_get_default_foreground(data); -} -void TCODConsole::setDefaultBackground(TCODColor back) { - TCOD_color_t b={back.r,back.g,back.b}; - TCOD_console_set_default_background(data,b); -} -void TCODConsole::setDefaultForeground(TCODColor fore) { - TCOD_color_t b={fore.r,fore.g,fore.b}; - TCOD_console_set_default_foreground(data,b); -} - -#ifndef TCOD_BARE -void TCODConsole::setWindowTitle(const char *title) { - TCOD_sys_set_window_title(title); -} -#endif - -void TCODConsole::initRoot(int w, int h, const char *title, bool fullscreen, TCOD_renderer_t renderer) { - TCODConsole *con=new TCODConsole(); - TCOD_console_init_root(w,h,title,fullscreen,renderer); - con->data=TCOD_ctx.root; - TCODConsole::root=con; -} - -void TCODConsole::setFullscreen(bool fullscreen) { - TCOD_console_set_fullscreen(fullscreen); -} - -bool TCODConsole::isFullscreen() { - return TCOD_console_is_fullscreen() != 0; -} - -void TCODConsole::setBackgroundFlag(TCOD_bkgnd_flag_t bkgnd_flag) { - TCOD_console_set_background_flag(data,bkgnd_flag); -} - -TCOD_bkgnd_flag_t TCODConsole::getBackgroundFlag() const { - return TCOD_console_get_background_flag(data); -} - -void TCODConsole::setAlignment(TCOD_alignment_t alignment) { - TCOD_console_set_alignment(data,alignment); -} - -TCOD_alignment_t TCODConsole::getAlignment() const { - return TCOD_console_get_alignment(data); -} - -TCODConsole::~TCODConsole() { - TCOD_console_delete(data); -} - -void TCODConsole::blit(const TCODConsole *srcCon,int xSrc, int ySrc, int wSrc, int hSrc, - TCODConsole *dstCon, int xDst, int yDst, float foreground_alpha, float background_alpha) { - TCOD_console_blit(srcCon->data,xSrc,ySrc,wSrc,hSrc,dstCon->data,xDst,yDst,foreground_alpha, background_alpha); -} - - -void TCODConsole::flush() { - TCOD_console_flush(); -} - -void TCODConsole::setFade(uint8_t val, const TCODColor &fade) { - TCOD_color_t f= {fade.r,fade.g,fade.b}; - TCOD_console_set_fade(val,f); -} - -uint8_t TCODConsole::getFade() { - return TCOD_console_get_fade(); -} - -TCODColor TCODConsole::getFadingColor() { - return TCOD_console_get_fading_color(); -} - -void TCODConsole::putChar(int x, int y, int c, TCOD_bkgnd_flag_t flag) { - TCOD_console_put_char(data,x,y,c,flag); -} - -void TCODConsole::putCharEx(int x, int y, int c, const TCODColor &fore, const TCODColor &back) { - TCOD_color_t f={fore.r,fore.g,fore.b}; - TCOD_color_t b={back.r,back.g,back.b}; - TCOD_console_put_char_ex(data,x,y,c,f,b); -} - -void TCODConsole::clear() { - TCOD_console_clear(data); -} - -TCODColor TCODConsole::getCharBackground(int x, int y) const { - return TCOD_console_get_char_background(data,x,y); -} -void TCODConsole::setCharForeground(int x,int y, const TCODColor &col) { - TCOD_color_t c={col.r,col.g,col.b}; - TCOD_console_set_char_foreground(data,x,y,c); -} -TCODColor TCODConsole::getCharForeground(int x, int y) const { - return TCOD_console_get_char_foreground(data,x,y); -} - -int TCODConsole::getChar(int x, int y) const { - return TCOD_console_get_char(data,x,y); -} - -void TCODConsole::setCharBackground(int x, int y, const TCODColor &col, TCOD_bkgnd_flag_t flag) { - TCOD_color_t c={col.r,col.g,col.b}; - TCOD_console_set_char_background(data,x,y,c,flag); -} - -void TCODConsole::setChar(int x, int y, int c) { - TCOD_console_set_char(data,x,y,c); -} - -void TCODConsole::rect(int x,int y, int rw, int rh, bool clear, TCOD_bkgnd_flag_t flag) { - TCOD_console_rect(data,x,y,rw,rh,clear,flag); -} - -void TCODConsole::hline(int x,int y, int l, TCOD_bkgnd_flag_t flag) { - TCOD_console_hline(data,x,y,l,flag); -} - -void TCODConsole::vline(int x,int y, int l, TCOD_bkgnd_flag_t flag) { - TCOD_console_vline(data,x,y,l,flag); -} - -/* -TCODImage *TCODConsole::getForegroundColorImage() { - return new TCODImage(TCOD_console_get_foreground_color_image(data)); -} - -TCODImage *TCODConsole::getBackgroundColorImage() { - return new TCODImage(TCOD_console_get_background_color_image(data)); -} -*/ - -void TCODConsole::printFrame(int x,int y,int w,int h, bool empty, TCOD_bkgnd_flag_t flag, const char *fmt , ...) { - if ( fmt ) { - va_list ap; - va_start(ap,fmt); - TCOD_console_print_frame(data,x,y,w,h,empty,flag,TCOD_console_vsprint(fmt,ap)); - va_end(ap); - } else { - TCOD_console_print_frame(data,x,y,w,h,empty,flag,NULL); - } -} - -void TCODConsole::print(int x, int y, const char *fmt, ...) { - va_list ap; - TCOD_console_data_t *dat=(TCOD_console_data_t *)data; - TCOD_IFNOT ( dat != NULL ) return; - va_start(ap,fmt); - TCOD_console_print_internal(data,x,y,0,0,dat->bkgnd_flag,dat->alignment, - TCOD_console_vsprint(fmt,ap),false,false); - va_end(ap); -} - -void TCODConsole::printEx(int x, int y, TCOD_bkgnd_flag_t flag, TCOD_alignment_t alignment, const char *fmt, ...) { - va_list ap; - va_start(ap,fmt); - TCOD_console_print_internal(data,x,y,0,0,flag,alignment,TCOD_console_vsprint(fmt,ap),false,false); - va_end(ap); -} - - -/* -void TCODConsole::printLine(int x, int y, TCOD_bkgnd_flag_t flag, TCOD_print_location_t location, const char *fmt, ...) { - va_list ap; - va_start(ap,fmt); - switch(location) - { - case TCOD_PRINT_LEFT: - TCOD_console_print(data,x,y,getWidth()-x,getHeight()-y,flag,LEFT,TCOD_console_vsprint(fmt,ap),false,false); - break; - case TCOD_PRINT_RIGHT: - TCOD_console_print(data,x,y,x+1,getHeight()-y,flag,RIGHT,TCOD_console_vsprint(fmt,ap),false,false); - break; - case TCOD_PRINT_CENTER: - TCOD_console_print(data,x,y,getWidth(),getHeight()-y,flag,CENTER,TCOD_console_vsprint(fmt,ap),false,false); - break; - default: - TCOD_ASSERT(0); - break; - } - va_end(ap); -} -*/ - -int TCODConsole::printRect(int x, int y, int w, int h, const char *fmt, ...) { - va_list ap; - TCOD_console_data_t *dat=(TCOD_console_data_t *)data; - TCOD_IFNOT ( dat != NULL ) return 0; - va_start(ap,fmt); - int ret = TCOD_console_print_internal(data,x,y,w,h,dat->bkgnd_flag,dat->alignment,TCOD_console_vsprint(fmt,ap),true,false); - va_end(ap); - return ret; -} - -int TCODConsole::printRectEx(int x, int y, int w, int h, TCOD_bkgnd_flag_t flag, - TCOD_alignment_t alignment, const char *fmt, ...) { - va_list ap; - va_start(ap,fmt); - int ret = TCOD_console_print_internal(data,x,y,w,h,flag,alignment,TCOD_console_vsprint(fmt,ap),true,false); - va_end(ap); - return ret; -} - -int TCODConsole::getHeightRect(int x, int y, int w, int h, const char *fmt, ...) { - va_list ap; - va_start(ap,fmt); - int ret = TCOD_console_print_internal(data,x,y,w,h,TCOD_BKGND_NONE,TCOD_LEFT,TCOD_console_vsprint(fmt,ap),true,true); - va_end(ap); - return ret; -} - -bool TCODConsole::isKeyPressed(TCOD_keycode_t key) { - return TCOD_console_is_key_pressed(key) != 0; -} -void TCODConsole::setKeyColor(const TCODColor &col) { - TCOD_color_t c={col.r,col.g,col.b}; - TCOD_console_set_key_color(data,c); -} - -void TCODConsole::credits() { - TCOD_console_credits(); -} - -void TCODConsole::resetCredits() { - TCOD_console_credits_reset(); -} - -bool TCODConsole::renderCredits(int x, int y, bool alpha) { - return TCOD_console_credits_render(x,y,alpha) != 0; -} - -#ifndef NO_UNICODE -void TCODConsole::mapStringToFont(const wchar_t *s, int fontCharX, int fontCharY) { - TCOD_console_map_string_to_font_utf(s, fontCharX, fontCharY); -} - -void TCODConsole::print(int x, int y, const wchar_t *fmt, ...) { - va_list ap; - TCOD_console_data_t *dat=(TCOD_console_data_t *)data; - TCOD_IFNOT ( dat != NULL ) return; - va_start(ap,fmt); - TCOD_console_print_internal_utf(data,x,y,0,0,dat->bkgnd_flag,dat->alignment,TCOD_console_vsprint_utf(fmt,ap),false,false); - va_end(ap); -} - -void TCODConsole::printEx(int x, int y, TCOD_bkgnd_flag_t flag, TCOD_alignment_t alignment, const wchar_t *fmt, ...) { - va_list ap; - va_start(ap,fmt); - TCOD_console_print_internal_utf(data,x,y,0,0,flag,alignment,TCOD_console_vsprint_utf(fmt,ap),false,false); - va_end(ap); -} - -int TCODConsole::printRect(int x, int y, int w, int h, const wchar_t *fmt, ...) { - va_list ap; - TCOD_console_data_t *dat=(TCOD_console_data_t *)data; - TCOD_IFNOT ( dat != NULL ) return 0; - va_start(ap,fmt); - int ret = TCOD_console_print_internal_utf(data,x,y,w,h,dat->bkgnd_flag,dat->alignment, - TCOD_console_vsprint_utf(fmt,ap),true,false); - va_end(ap); - return ret; -} - -int TCODConsole::printRectEx(int x, int y, int w, int h, TCOD_bkgnd_flag_t flag, - TCOD_alignment_t alignment, const wchar_t *fmt, ...) { - va_list ap; - va_start(ap,fmt); - int ret = TCOD_console_print_internal_utf(data,x,y,w,h,flag,alignment, - TCOD_console_vsprint_utf(fmt,ap),true,false); - va_end(ap); - return ret; -} - -int TCODConsole::getHeightRect(int x, int y, int w, int h, const wchar_t *fmt, ...) { - va_list ap; - va_start(ap,fmt); - int ret = TCOD_console_print_internal_utf(data,x,y,w,h,TCOD_BKGND_NONE,TCOD_LEFT,TCOD_console_vsprint_utf(fmt,ap),true,true); - va_end(ap); - return ret; -} - -// color control string formatting utilities for swigged language - -// ctrl = TCOD_COLCTRL_1...TCOD_COLCTRL_5 or TCOD_COLCTRL_STOP -#define NB_BUFFERS 10 -const char *TCODConsole::getColorControlString( TCOD_colctrl_t ctrl ) { - static char buf[NB_BUFFERS][2]; - static int buf_nb=0; - const char *ret; - buf[buf_nb][0]=ctrl; - buf[buf_nb][1]=0; - ret = (const char *)(&buf[buf_nb][0]); - buf_nb = (buf_nb+1) % NB_BUFFERS; - return ret; -} - -// ctrl = TCOD_COLCTRL_FORE_RGB or TCOD_COLCTRL_BACK_RGB -const char *TCODConsole::getRGBColorControlString( TCOD_colctrl_t ctrl, const TCODColor & col ) { - static char buf[NB_BUFFERS][5]; - static int buf_nb=0; - const char *ret; - buf[buf_nb][0]=ctrl; - buf[buf_nb][1]=col.r; - buf[buf_nb][2]=col.g; - buf[buf_nb][3]=col.b; - buf[buf_nb][4]=0; - ret = (const char *)(&buf[buf_nb][0]); - buf_nb = (buf_nb+1) % NB_BUFFERS; - return ret; -} - -#endif - -#endif /* TCOD_CONSOLE_SUPPORT */ +/* +* libtcod +* Copyright (c) 2008-2018 Jice & Mingos & rmtew +* All rights reserved. +* +* Redistribution and use in source and binary forms, with or without +* modification, are permitted provided that the following conditions are met: +* * Redistributions of source code must retain the above copyright +* notice, this list of conditions and the following disclaimer. +* * Redistributions in binary form must reproduce the above copyright +* notice, this list of conditions and the following disclaimer in the +* documentation and/or other materials provided with the distribution. +* * The name of Jice or Mingos may not be used to endorse or promote +* products derived from this software without specific prior written +* permission. +* +* THIS SOFTWARE IS PROVIDED BY JICE, MINGOS AND RMTEW ``AS IS'' AND ANY +* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED +* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE +* DISCLAIMED. IN NO EVENT SHALL JICE, MINGOS OR RMTEW BE LIABLE FOR ANY +* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES +* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; +* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND +* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS +* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +*/ +#include "console.hpp" + +#include +#include +#include + +#include "libtcod_int.h" +#include "image.hpp" + +#ifdef TCOD_CONSOLE_SUPPORT + +TCODConsole* TCODConsole::root = new TCODConsole(); + +TCODConsole::TCODConsole() {} +TCODConsole::TCODConsole(int w, int h) { + data = TCOD_console_new(w,h); +} + +TCODConsole::TCODConsole(const char *filename) { + data = TCOD_console_from_file(filename); +} + +bool TCODConsole::loadAsc(const char *filename) { + return TCOD_console_load_asc(data,filename) != 0; +} +bool TCODConsole::saveAsc(const char *filename) const { + return TCOD_console_save_asc(data,filename) != 0; +} +bool TCODConsole::saveApf(const char *filename) const { + return TCOD_console_save_apf(data,filename) != 0; +} +bool TCODConsole::loadApf(const char *filename) { + return TCOD_console_load_apf(data,filename) != 0; +} + +void TCODConsole::setCustomFont(const char *fontFile, int flags,int nbCharHoriz, int nbCharVertic) { + TCOD_console_set_custom_font(fontFile,flags,nbCharHoriz,nbCharVertic); +} + +void TCODConsole::mapAsciiCodeToFont(int asciiCode, int fontCharX, int fontCharY) { + TCOD_console_map_ascii_code_to_font(asciiCode,fontCharX,fontCharY); +} + +void TCODConsole::mapAsciiCodesToFont(int firstAsciiCode, int nbCodes, int fontCharX, int fontCharY) { + TCOD_console_map_ascii_codes_to_font(firstAsciiCode,nbCodes,fontCharX,fontCharY); +} + +void TCODConsole::mapStringToFont(const char *s, int fontCharX, int fontCharY) { + TCOD_console_map_string_to_font(s, fontCharX, fontCharY); +} + +void TCODConsole::setDirty(int x, int y, int w, int h) { + TCOD_console_set_dirty(x,y,w,h); +} + +TCOD_key_t TCODConsole::checkForKeypress(int flags) { + return TCOD_sys_check_for_keypress(flags); +} + +TCOD_key_t TCODConsole::waitForKeypress(bool flush) { + return TCOD_sys_wait_for_keypress(flush); +} + +bool TCODConsole::isWindowClosed() { + return TCOD_console_is_window_closed() != 0; +} + +bool TCODConsole::hasMouseFocus() { + return TCOD_console_has_mouse_focus() != 0; +} + +bool TCODConsole::isActive() { + return TCOD_console_is_active() != 0; +} + +int TCODConsole::getWidth() const { + return TCOD_console_get_width(data); +} + +int TCODConsole::getHeight() const { + return TCOD_console_get_height(data); +} + +void TCODConsole::setColorControl(TCOD_colctrl_t con, const TCODColor &fore, const TCODColor &back) { + TCOD_color_t b={back.r,back.g,back.b},f={fore.r,fore.g,fore.b}; + TCOD_console_set_color_control(con,f,b); +} + +TCODColor TCODConsole::getDefaultBackground() const { + TCOD_color_t c= TCOD_console_get_default_background(data); + TCODColor ret; + ret.r=c.r; + ret.g=c.g; + ret.b=c.b; + return ret; +} +TCODColor TCODConsole::getDefaultForeground() const { + return TCOD_console_get_default_foreground(data); +} +void TCODConsole::setDefaultBackground(TCODColor back) { + TCOD_color_t b={back.r,back.g,back.b}; + TCOD_console_set_default_background(data,b); +} +void TCODConsole::setDefaultForeground(TCODColor fore) { + TCOD_color_t b={fore.r,fore.g,fore.b}; + TCOD_console_set_default_foreground(data,b); +} + +#ifndef TCOD_BARE +void TCODConsole::setWindowTitle(const char *title) { + TCOD_sys_set_window_title(title); +} +#endif + +void TCODConsole::initRoot(int w, int h, const char *title, bool fullscreen, + TCOD_renderer_t renderer) +{ + TCOD_console_init_root(w, h, title, fullscreen, renderer); +} + +void TCODConsole::setFullscreen(bool fullscreen) { + TCOD_console_set_fullscreen(fullscreen); +} + +bool TCODConsole::isFullscreen() { + return TCOD_console_is_fullscreen() != 0; +} + +void TCODConsole::setBackgroundFlag(TCOD_bkgnd_flag_t bkgnd_flag) { + TCOD_console_set_background_flag(data,bkgnd_flag); +} + +TCOD_bkgnd_flag_t TCODConsole::getBackgroundFlag() const { + return TCOD_console_get_background_flag(data); +} + +void TCODConsole::setAlignment(TCOD_alignment_t alignment) { + TCOD_console_set_alignment(data,alignment); +} + +TCOD_alignment_t TCODConsole::getAlignment() const { + return TCOD_console_get_alignment(data); +} + +TCODConsole::~TCODConsole() { + TCOD_console_delete(data); +} + +void TCODConsole::blit(const TCODConsole *srcCon,int xSrc, int ySrc, int wSrc, int hSrc, + TCODConsole *dstCon, int xDst, int yDst, float foreground_alpha, float background_alpha) { + TCOD_console_blit(srcCon->data,xSrc,ySrc,wSrc,hSrc,dstCon->data,xDst,yDst,foreground_alpha, background_alpha); +} + + +void TCODConsole::flush() { + TCOD_console_flush(); +} + +void TCODConsole::setFade(uint8_t val, const TCODColor &fade) { + TCOD_color_t f= {fade.r,fade.g,fade.b}; + TCOD_console_set_fade(val,f); +} + +uint8_t TCODConsole::getFade() { + return TCOD_console_get_fade(); +} + +TCODColor TCODConsole::getFadingColor() { + return TCOD_console_get_fading_color(); +} + +void TCODConsole::putChar(int x, int y, int c, TCOD_bkgnd_flag_t flag) { + TCOD_console_put_char(data,x,y,c,flag); +} + +void TCODConsole::putCharEx(int x, int y, int c, const TCODColor &fore, const TCODColor &back) { + TCOD_color_t f={fore.r,fore.g,fore.b}; + TCOD_color_t b={back.r,back.g,back.b}; + TCOD_console_put_char_ex(data,x,y,c,f,b); +} + +void TCODConsole::clear() { + TCOD_console_clear(data); +} + +TCODColor TCODConsole::getCharBackground(int x, int y) const { + return TCOD_console_get_char_background(data,x,y); +} +void TCODConsole::setCharForeground(int x,int y, const TCODColor &col) { + TCOD_color_t c={col.r,col.g,col.b}; + TCOD_console_set_char_foreground(data,x,y,c); +} +TCODColor TCODConsole::getCharForeground(int x, int y) const { + return TCOD_console_get_char_foreground(data,x,y); +} + +int TCODConsole::getChar(int x, int y) const { + return TCOD_console_get_char(data,x,y); +} + +void TCODConsole::setCharBackground(int x, int y, const TCODColor &col, TCOD_bkgnd_flag_t flag) { + TCOD_color_t c={col.r,col.g,col.b}; + TCOD_console_set_char_background(data,x,y,c,flag); +} + +void TCODConsole::setChar(int x, int y, int c) { + TCOD_console_set_char(data,x,y,c); +} + +void TCODConsole::rect(int x,int y, int rw, int rh, bool clear, TCOD_bkgnd_flag_t flag) { + TCOD_console_rect(data,x,y,rw,rh,clear,flag); +} + +void TCODConsole::hline(int x,int y, int l, TCOD_bkgnd_flag_t flag) { + TCOD_console_hline(data,x,y,l,flag); +} + +void TCODConsole::vline(int x,int y, int l, TCOD_bkgnd_flag_t flag) { + TCOD_console_vline(data,x,y,l,flag); +} + +void TCODConsole::printFrame(int x,int y,int w,int h, bool empty, TCOD_bkgnd_flag_t flag, const char *fmt , ...) { + if ( fmt ) { + va_list ap; + va_start(ap,fmt); + TCOD_console_print_frame(data,x,y,w,h,empty,flag,TCOD_console_vsprint(fmt,ap)); + va_end(ap); + } else { + TCOD_console_print_frame(data,x,y,w,h,empty,flag,NULL); + } +} +/** Deprecated EASCII function. */ +void TCODConsole::print(int x, int y, const char *fmt, ...) { + va_list ap; + va_start(ap, fmt); + TCOD_console_print_internal( + data, x, y, 0, 0, data->bkgnd_flag, data->alignment, + TCOD_console_vsprint(fmt, ap), false, false); + va_end(ap); +} +void TCODConsole::print(int x, int y, const std::string &str) { + this->print(x, y, str, data->alignment, data->bkgnd_flag); +} +void TCODConsole::print(int x, int y, const std::string &str, + TCOD_alignment_t alignment, TCOD_bkgnd_flag_t flag) { + TCOD_console_print_internal_utf8_( + data, x, y, 0, 0, flag, alignment, + reinterpret_cast(str.c_str()), false, false); +} +void TCODConsole::printf(int x, int y, const char *fmt, ...) { + va_list ap; + va_start(ap, fmt); + this->print(x, y, std::string(TCOD_console_vsprint(fmt, ap))); + va_end(ap); +} +void TCODConsole::printf(int x, int y, TCOD_bkgnd_flag_t flag, + TCOD_alignment_t alignment, const char *fmt, ...) { + va_list ap; + va_start(ap, fmt); + this->print(x, y, std::string(TCOD_console_vsprint(fmt, ap)), + alignment, flag); + va_end(ap); +} +/** Deprecated EASCII function. */ +void TCODConsole::printEx(int x, int y, TCOD_bkgnd_flag_t flag, + TCOD_alignment_t alignment, const char *fmt, ...) { + va_list ap; + va_start(ap, fmt); + TCOD_console_print_internal(data, x, y, 0, 0, flag, alignment, + TCOD_console_vsprint(fmt,ap), false, false); + va_end(ap); +} + + +/* +void TCODConsole::printLine(int x, int y, TCOD_bkgnd_flag_t flag, TCOD_print_location_t location, const char *fmt, ...) { + va_list ap; + va_start(ap,fmt); + switch(location) + { + case TCOD_PRINT_LEFT: + TCOD_console_print(data,x,y,getWidth()-x,getHeight()-y,flag,LEFT,TCOD_console_vsprint(fmt,ap),false,false); + break; + case TCOD_PRINT_RIGHT: + TCOD_console_print(data,x,y,x+1,getHeight()-y,flag,RIGHT,TCOD_console_vsprint(fmt,ap),false,false); + break; + case TCOD_PRINT_CENTER: + TCOD_console_print(data,x,y,getWidth(),getHeight()-y,flag,CENTER,TCOD_console_vsprint(fmt,ap),false,false); + break; + default: + TCOD_ASSERT(0); + break; + } + va_end(ap); +} +*/ + +int TCODConsole::printRect(int x, int y, int w, int h, const char *fmt, ...) { + va_list ap; + struct TCOD_Console *dat=(struct TCOD_Console *)data; + TCOD_IFNOT ( dat != NULL ) return 0; + va_start(ap,fmt); + int ret = TCOD_console_print_internal(data,x,y,w,h,dat->bkgnd_flag,dat->alignment,TCOD_console_vsprint(fmt,ap),true,false); + va_end(ap); + return ret; +} + +int TCODConsole::printRectEx(int x, int y, int w, int h, TCOD_bkgnd_flag_t flag, + TCOD_alignment_t alignment, const char *fmt, ...) { + va_list ap; + va_start(ap,fmt); + int ret = TCOD_console_print_internal(data,x,y,w,h,flag,alignment,TCOD_console_vsprint(fmt,ap),true,false); + va_end(ap); + return ret; +} + +int TCODConsole::getHeightRect(int x, int y, int w, int h, const char *fmt, ...) { + va_list ap; + va_start(ap,fmt); + int ret = TCOD_console_print_internal(data,x,y,w,h,TCOD_BKGND_NONE,TCOD_LEFT,TCOD_console_vsprint(fmt,ap),true,true); + va_end(ap); + return ret; +} + +bool TCODConsole::isKeyPressed(TCOD_keycode_t key) { + return TCOD_console_is_key_pressed(key) != 0; +} +void TCODConsole::setKeyColor(const TCODColor &col) { + TCOD_color_t c={col.r,col.g,col.b}; + TCOD_console_set_key_color(data,c); +} + +void TCODConsole::credits() { + TCOD_console_credits(); +} + +void TCODConsole::resetCredits() { + TCOD_console_credits_reset(); +} + +bool TCODConsole::renderCredits(int x, int y, bool alpha) { + return TCOD_console_credits_render(x,y,alpha) != 0; +} + +#ifndef NO_UNICODE +void TCODConsole::mapStringToFont(const wchar_t *s, int fontCharX, int fontCharY) { + TCOD_console_map_string_to_font_utf(s, fontCharX, fontCharY); +} + +void TCODConsole::print(int x, int y, const wchar_t *fmt, ...) { + va_list ap; + struct TCOD_Console *dat=(struct TCOD_Console *)data; + TCOD_IFNOT ( dat != NULL ) return; + va_start(ap,fmt); + TCOD_console_print_internal_utf(data,x,y,0,0,dat->bkgnd_flag,dat->alignment,TCOD_console_vsprint_utf(fmt,ap),false,false); + va_end(ap); +} + +void TCODConsole::printEx(int x, int y, TCOD_bkgnd_flag_t flag, TCOD_alignment_t alignment, const wchar_t *fmt, ...) { + va_list ap; + va_start(ap,fmt); + TCOD_console_print_internal_utf(data,x,y,0,0,flag,alignment,TCOD_console_vsprint_utf(fmt,ap),false,false); + va_end(ap); +} + +int TCODConsole::printRect(int x, int y, int w, int h, const wchar_t *fmt, ...) { + va_list ap; + struct TCOD_Console *dat=(struct TCOD_Console *)data; + TCOD_IFNOT ( dat != NULL ) return 0; + va_start(ap,fmt); + int ret = TCOD_console_print_internal_utf(data,x,y,w,h,dat->bkgnd_flag,dat->alignment, + TCOD_console_vsprint_utf(fmt,ap),true,false); + va_end(ap); + return ret; +} + +int TCODConsole::printRectEx(int x, int y, int w, int h, TCOD_bkgnd_flag_t flag, + TCOD_alignment_t alignment, const wchar_t *fmt, ...) { + va_list ap; + va_start(ap,fmt); + int ret = TCOD_console_print_internal_utf(data,x,y,w,h,flag,alignment, + TCOD_console_vsprint_utf(fmt,ap),true,false); + va_end(ap); + return ret; +} + +int TCODConsole::getHeightRect(int x, int y, int w, int h, const wchar_t *fmt, ...) { + va_list ap; + va_start(ap,fmt); + int ret = TCOD_console_print_internal_utf(data,x,y,w,h,TCOD_BKGND_NONE,TCOD_LEFT,TCOD_console_vsprint_utf(fmt,ap),true,true); + va_end(ap); + return ret; +} + +// color control string formatting utilities for swigged language + +// ctrl = TCOD_COLCTRL_1...TCOD_COLCTRL_5 or TCOD_COLCTRL_STOP +#define NB_BUFFERS 10 +const char *TCODConsole::getColorControlString( TCOD_colctrl_t ctrl ) { + static char buf[NB_BUFFERS][2]; + static int buf_nb=0; + const char *ret; + buf[buf_nb][0]=ctrl; + buf[buf_nb][1]=0; + ret = (const char *)(&buf[buf_nb][0]); + buf_nb = (buf_nb+1) % NB_BUFFERS; + return ret; +} + +// ctrl = TCOD_COLCTRL_FORE_RGB or TCOD_COLCTRL_BACK_RGB +const char *TCODConsole::getRGBColorControlString( TCOD_colctrl_t ctrl, const TCODColor & col ) { + static char buf[NB_BUFFERS][5]; + static int buf_nb=0; + const char *ret; + buf[buf_nb][0]=ctrl; + buf[buf_nb][1]=col.r; + buf[buf_nb][2]=col.g; + buf[buf_nb][3]=col.b; + buf[buf_nb][4]=0; + ret = (const char *)(&buf[buf_nb][0]); + buf_nb = (buf_nb+1) % NB_BUFFERS; + return ret; +} + +#endif + +#endif /* TCOD_CONSOLE_SUPPORT */ diff --git a/tcod_sys/libtcod/include/console.h b/tcod_sys/libtcod/src/libtcod/console.h similarity index 80% rename from tcod_sys/libtcod/include/console.h rename to tcod_sys/libtcod/src/libtcod/console.h index cab348adb..05bfc69a4 100644 --- a/tcod_sys/libtcod/include/console.h +++ b/tcod_sys/libtcod/src/libtcod/console.h @@ -28,7 +28,7 @@ #ifndef _TCOD_CONSOLE_H #define _TCOD_CONSOLE_H -#include "libtcod_portability.h" +#include "portability.h" #ifdef TCOD_CONSOLE_SUPPORT @@ -45,6 +45,7 @@ extern "C" { #define TCOD_BKGND_ADDALPHA(alpha) ((TCOD_bkgnd_flag_t)(TCOD_BKGND_ADDA|(((uint8_t)(alpha*255))<<8))) TCODLIB_API void TCOD_console_init_root(int w, int h, const char * title, bool fullscreen, TCOD_renderer_t renderer); +TCODLIB_API void TCOD_quit(void); TCODLIB_API void TCOD_console_set_window_title(const char *title); TCODLIB_API void TCOD_console_set_fullscreen(bool fullscreen); TCODLIB_API bool TCOD_console_is_fullscreen(void); @@ -71,9 +72,14 @@ TCODLIB_API void TCOD_console_set_background_flag(TCOD_console_t con,TCOD_bkgnd_ TCODLIB_API TCOD_bkgnd_flag_t TCOD_console_get_background_flag(TCOD_console_t con); TCODLIB_API void TCOD_console_set_alignment(TCOD_console_t con,TCOD_alignment_t alignment); TCODLIB_API TCOD_alignment_t TCOD_console_get_alignment(TCOD_console_t con); + +TCOD_DEPRECATED("Use TCOD_console_printf instead.") TCODLIB_API void TCOD_console_print(TCOD_console_t con,int x, int y, const char *fmt, ...); +TCOD_DEPRECATED("Use TCOD_console_printf_ex instead.") TCODLIB_API void TCOD_console_print_ex(TCOD_console_t con,int x, int y, TCOD_bkgnd_flag_t flag, TCOD_alignment_t alignment, const char *fmt, ...); +TCOD_DEPRECATED("Use TCOD_console_printf_rect instead.") TCODLIB_API int TCOD_console_print_rect(TCOD_console_t con,int x, int y, int w, int h, const char *fmt, ...); +TCOD_DEPRECATED("Use TCOD_console_printf_rect_ex instead.") TCODLIB_API int TCOD_console_print_rect_ex(TCOD_console_t con,int x, int y, int w, int h, TCOD_bkgnd_flag_t flag, TCOD_alignment_t alignment, const char *fmt, ...); TCODLIB_API int TCOD_console_get_height_rect(TCOD_console_t con,int x, int y, int w, int h, const char *fmt, ...); @@ -85,9 +91,13 @@ TCODLIB_API void TCOD_console_print_frame(TCOD_console_t con,int x,int y,int w,i #ifndef NO_UNICODE /* unicode support */ TCODLIB_API void TCOD_console_map_string_to_font_utf(const wchar_t *s, int fontCharX, int fontCharY); +TCOD_DEPRECATED("Use TCOD_console_printf instead.") TCODLIB_API void TCOD_console_print_utf(TCOD_console_t con,int x, int y, const wchar_t *fmt, ...); +TCOD_DEPRECATED("Use TCOD_console_printf_ex instead.") TCODLIB_API void TCOD_console_print_ex_utf(TCOD_console_t con,int x, int y, TCOD_bkgnd_flag_t flag, TCOD_alignment_t alignment, const wchar_t *fmt, ...); +TCOD_DEPRECATED("Use TCOD_console_printf_rect instead.") TCODLIB_API int TCOD_console_print_rect_utf(TCOD_console_t con,int x, int y, int w, int h, const wchar_t *fmt, ...); +TCOD_DEPRECATED("Use TCOD_console_printf_rect_ex instead.") TCODLIB_API int TCOD_console_print_rect_ex_utf(TCOD_console_t con,int x, int y, int w, int h, TCOD_bkgnd_flag_t flag, TCOD_alignment_t alignment, const wchar_t *fmt, ...); TCODLIB_API int TCOD_console_get_height_rect_utf(TCOD_console_t con,int x, int y, int w, int h, const wchar_t *fmt, ...); #endif @@ -99,9 +109,6 @@ TCODLIB_API TCOD_color_t TCOD_console_get_char_background(TCOD_console_t con,int TCODLIB_API TCOD_color_t TCOD_console_get_char_foreground(TCOD_console_t con,int x, int y); TCODLIB_API int TCOD_console_get_char(TCOD_console_t con,int x, int y); -TCODLIB_API TCOD_image_t TCOD_console_get_background_color_image(TCOD_console_t con); -TCODLIB_API TCOD_image_t TCOD_console_get_foreground_color_image(TCOD_console_t con); - TCODLIB_API void TCOD_console_set_fade(uint8_t val, TCOD_color_t fade); TCODLIB_API uint8_t TCOD_console_get_fade(void); TCODLIB_API TCOD_color_t TCOD_console_get_fading_color(void); @@ -126,11 +133,41 @@ TCODLIB_API int TCOD_console_get_width(TCOD_console_t con); TCODLIB_API int TCOD_console_get_height(TCOD_console_t con); TCODLIB_API void TCOD_console_set_key_color(TCOD_console_t con,TCOD_color_t col); TCODLIB_API void TCOD_console_blit(TCOD_console_t src,int xSrc, int ySrc, int wSrc, int hSrc, TCOD_console_t dst, int xDst, int yDst, float foreground_alpha, float background_alpha); +TCODLIB_API void TCOD_console_blit_key_color( + TCOD_console_t src,int xSrc, int ySrc, int wSrc, int hSrc, + TCOD_console_t dst, int xDst, int yDst, + float foreground_alpha, float background_alpha, TCOD_color_t *key_color); TCODLIB_API void TCOD_console_delete(TCOD_console_t console); TCODLIB_API void TCOD_console_credits(void); TCODLIB_API void TCOD_console_credits_reset(void); TCODLIB_API bool TCOD_console_credits_render(int x, int y, bool alpha); + +/* UTF-8 functions */ +TCODLIB_API void TCOD_console_printf(TCOD_console_t con, int x, int y, + const char *fmt, ...); +TCODLIB_API void TCOD_console_printf_ex( + TCOD_console_t con, int x, int y, TCOD_bkgnd_flag_t flag, + TCOD_alignment_t alignment, const char *fmt, ...); +TCODLIB_API int TCOD_console_printf_rect( + TCOD_console_t con, int x, int y, int w, int h, const char *fmt, ...); +TCODLIB_API int TCOD_console_printf_rect_ex( + TCOD_console_t con,int x, int y, int w, int h, + TCOD_bkgnd_flag_t flag, TCOD_alignment_t alignment, const char *fmt, ...); +TCODLIB_API +void TCOD_console_printf_frame(struct TCOD_Console *con, + int x, int y, int w, int h, int empty, + TCOD_bkgnd_flag_t flag, const char *fmt, ...); +TCODLIB_API +int TCOD_console_get_height_rect_fmt(struct TCOD_Console *con, + int x, int y, int w, int h, + const char *fmt, ...); + +/* Private internal functions. */ +int TCOD_console_print_internal_utf8_( + TCOD_console_t con, int x, int y, int max_width, int max_height, + TCOD_bkgnd_flag_t flag, TCOD_alignment_t align, + const unsigned char *string, int can_split, int count_only); #ifdef __cplusplus } #endif diff --git a/tcod_sys/libtcod/include/console.hpp b/tcod_sys/libtcod/src/libtcod/console.hpp similarity index 94% rename from tcod_sys/libtcod/include/console.hpp rename to tcod_sys/libtcod/src/libtcod/console.hpp index 8accd6543..065bf4200 100644 --- a/tcod_sys/libtcod/include/console.hpp +++ b/tcod_sys/libtcod/src/libtcod/console.hpp @@ -1,1791 +1,1798 @@ -/* -* libtcod -* Copyright (c) 2008-2018 Jice & Mingos & rmtew -* All rights reserved. -* -* Redistribution and use in source and binary forms, with or without -* modification, are permitted provided that the following conditions are met: -* * Redistributions of source code must retain the above copyright -* notice, this list of conditions and the following disclaimer. -* * Redistributions in binary form must reproduce the above copyright -* notice, this list of conditions and the following disclaimer in the -* documentation and/or other materials provided with the distribution. -* * The name of Jice or Mingos may not be used to endorse or promote -* products derived from this software without specific prior written -* permission. -* -* THIS SOFTWARE IS PROVIDED BY JICE, MINGOS AND RMTEW ``AS IS'' AND ANY -* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED -* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE -* DISCLAIMED. IN NO EVENT SHALL JICE, MINGOS OR RMTEW BE LIABLE FOR ANY -* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES -* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; -* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND -* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS -* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. -*/ -#ifndef _TCOD_CONSOLE_HPP -#define _TCOD_CONSOLE_HPP - -#include "console.h" -#include "console_rexpaint.h" - -#ifdef TCOD_CONSOLE_SUPPORT - -#include "image.hpp" -#include "color.hpp" - -class TCODImage; -/** - @PageName console - @PageCategory Core - @PageTitle Console - @PageDesc The console emulator handles the rendering of the game screen and the keyboard input. -Classic real time game loop: - @Cpp - TCODConsole::initRoot(80,50,"my game",false); - TCODSystem::setFps(25); // limit framerate to 25 frames per second - while (!endGame && !TCODConsole::isWindowClosed()) { - TCOD_key_t key; - TCODSystem::checkForEvent(TCOD_EVENT_KEY_PRESS,&key,NULL); - updateWorld (key, TCODSystem::getLastFrameLength()); - // updateWorld(TCOD_key_t key, float elapsed) (using key if key.vk != TCODK_NONE) - // use elapsed to scale any update that is time dependent. - // ... draw world+GUI on TCODConsole::root - TCODConsole::flush(); - } - @Lua - tcod.console.initRoot(80,50,"my game", false) - root=libtcod.TCODConsole_root - tcod.system.setFps(25) - while not tcod.console.isWindowClosed() do - -- ... draw on root - tcod.console.flush() - key=tcod.console.checkForKeypress() - -- ... update world, using key and tcod.system.getLastFrameLength - end - -*/ -/** - @PageName console - @FuncDesc Classic turn by turn game loop: - @Cpp - TCODConsole::initRoot(80,50,"my game",false); - while (!endGame && !TCODConsole::isWindowClosed()) { - // ... draw on TCODConsole::root - TCODConsole::flush(); - TCOD_key_t key; - TCODConsole::waitForEvent(TCOD_EVENT_KEY_PRESS,&key,NULL,true); - //... update world, using key - } -*/ - -class TCODLIB_API TCODConsole { -public : - /** - @PageName console_init - @PageTitle Initializing the console - @PageFather console - */ - - static TCODConsole *root; - - /** - @PageName console_init_root - @PageTitle Creating the game window - @PageFather console_init - @Cpp static void TCODConsole::initRoot (int w, int h, const char * title, bool fullscreen = false, TCOD_renderer_t renderer = TCOD_RENDERER_SDL) - @C void TCOD_console_init_root (int w, int h, const char * title, bool fullscreen, TCOD_renderer_t renderer) - @Py console_init_root (w, h, title, fullscreen = False, renderer = RENDERER_SDL) - @C# - static void TCODConsole::initRoot(int w, int h, string title) - static void TCODConsole::initRoot(int w, int h, string title, bool fullscreen) - static void TCODConsole::initRoot(int w, int h, string title, bool fullscreen, TCODRendererType renderer) - @Lua - tcod.console.initRoot(w,h,title) -- fullscreen = false, renderer = SDL - tcod.console.initRoot(w,h,title,fullscreen) -- renderer = SDL - tcod.console.initRoot(w,h,title,fullscreen,renderer) - -- renderers : tcod.GLSL, tcod.OpenGL, tcod.SDL - @Param w,h size of the console(in characters). The default font in libtcod (./terminal.png) uses 8x8 pixels characters. - You can change the font by calling TCODConsole::setCustomFont before calling initRoot. - @Param title title of the window. It's not visible when you are in fullscreen. - Note 1 : you can dynamically change the window title with TCODConsole::setWindowTitle - @Param fullscreen whether you start in windowed or fullscreen mode. - Note 1 : you can dynamically change this mode with TCODConsole::setFullscreen - Note 2 : you can get current mode with TCODConsole::isFullscreen - @Param renderer which renderer to use. Possible values are : - * TCOD_RENDERER_GLSL : works only on video cards with pixel shaders - * TCOD_RENDERER_OPENGL : works on all video cards supporting OpenGL 1.4 - * TCOD_RENDERER_SDL : should work everywhere! - Note 1: if you select a renderer that is not supported by the player's machine, libtcod scan the lower renderers until it finds a working one. - Note 2: on recent video cards, GLSL results in up to 900% increase of framerates in the true color sample compared to SDL renderer. - Note 3: whatever renderer you use, it can always be overridden by the player through the libtcod.cfg file. - Note 4: you can dynamically change the renderer after calling initRoot with TCODSystem::setRenderer. - Note 5: you can get current renderer with TCODSystem::getRenderer. It might be different from the one you set in initRoot in case it's not supported on the player's computer. - @CppEx TCODConsole::initRoot(80, 50, "The Chronicles Of Doryen v0.1"); - @CEx TCOD_console_init_root(80, 50, "The Chronicles Of Doryen v0.1", false, TCOD_RENDERER_OPENGL); - @PyEx libtcod.console_init_root(80, 50, 'The Chronicles Of Doryen v0.1') - @LuaEx tcod.console.initRoot(80,50,"The Chronicles Of Doryen v0.1") - */ - static void initRoot(int w, int h, const char * title, bool fullscreen = false, TCOD_renderer_t renderer=TCOD_RENDERER_SDL); - - /** - @PageName console_set_custom_font - @PageTitle Using a custom bitmap font - @PageFather console_init - @FuncTitle setCustomFont - @FuncDesc This function allows you to use a bitmap font (png or bmp) with custom character size or layout. - It should be called before initializing the root console with initRoot. - Once this function is called, you can define your own custom mappings using mapping functions -
Different font layouts
- - - - -
ASCII_INROWASCII_INCOLTCOD
-
    -
  • ascii, in columns : characters 0 to 15 are in the first column. The space character is at coordinates 2,0.
  • -
  • ascii, in rows : characters 0 to 15 are in the first row. The space character is at coordinates 0,2.
  • -
  • tcod : special mapping. Not all ascii values are mapped. The space character is at coordinates 0,0.
  • -
-
Different font types
- - - - -
standard
(non antialiased)
antialiased
(32 bits PNG)
antialiased
(greyscale)
-
    -
  • standard : transparency is given by a key color automatically detected by looking at the color of the space character
  • -
  • 32 bits : transparency is given by the png alpha layer. The font color does not matter but it must be desaturated
  • -
  • greyscale : transparency is given by the pixel value. You can use white characters on black background or black characters on white background. The background color is automatically detected by looking at the color of the space character
  • -
- Examples of fonts can be found in libtcod's fonts directory. Check the Readme file there. - @Cpp static void TCODConsole::setCustomFont(const char *fontFile, int flags=TCOD_FONT_LAYOUT_ASCII_INCOL,int nbCharHoriz=0, int nbCharVertic=0) - @C void TCOD_console_set_custom_font(const char *fontFile, int flags,int nb_char_horiz, int nb_char_vertic) - @Py console_set_custom_font(fontFile, flags=FONT_LAYOUT_ASCII_INCOL,nb_char_horiz=0, nb_char_vertic=0) - @C# - static void TCODConsole::setCustomFont(string fontFile) - static void TCODConsole::setCustomFont(string fontFile, int flags) - static void TCODConsole::setCustomFont(string fontFile, int flags, int nbCharHoriz) - static void TCODConsole::setCustomFont(string fontFile, int flags, int nbCharHoriz, int nbCharVertic) - @Lua - tcod.console.setCustomFont(fontFile) - tcod.console.setCustomFont(fontFile, flags) - tcod.console.setCustomFont(fontFile, nbCharHoriz) - tcod.console.setCustomFont(fontFile, flags, nbCharHoriz, nbCharVertic) - -- flags : tcod.LayoutAsciiInColumn, tcod.LayoutAsciiInRow, tcod.LayoutTCOD, tcod.Greyscale - @Param fontFile Name of a .bmp or .png file containing the font. - @Param flags Used to define the characters layout in the bitmap and the font type : - TCOD_FONT_LAYOUT_ASCII_INCOL : characters in ASCII order, code 0-15 in the first column - TCOD_FONT_LAYOUT_ASCII_INROW : characters in ASCII order, code 0-15 in the first row - TCOD_FONT_LAYOUT_TCOD : simplified layout. See examples below. - TCOD_FONT_TYPE_GREYSCALE : create an anti-aliased font from a greyscale bitmap - For Python, remove TCOD _ : - libtcod.FONT_LAYOUT_ASCII_INCOL - @Param nbCharHoriz,nbCharVertic Number of characters in the font. - Should be 16x16 for ASCII layouts, 32x8 for TCOD layout. - But you can use any other layout. - If set to 0, there are deduced from the font layout flag. - @CppEx - TCODConsole::setCustomFont("standard_8x8_ascii_in_col_font.bmp",TCOD_FONT_LAYOUT_ASCII_INCOL); - TCODConsole::setCustomFont("32bits_8x8_ascii_in_row_font.png",TCOD_FONT_LAYOUT_ASCII_INROW); - TCODConsole::setCustomFont("greyscale_8x8_tcod_font.png",TCOD_FONT_LAYOUT_TCOD | TCOD_FONT_TYPE_GREYSCALE); - @CEx - TCOD_console_set_custom_font("standard_8x8_ascii_in_col_font.bmp",TCOD_FONT_LAYOUT_ASCII_INCOL,16,16); - TCOD_console_set_custom_font("32bits_8x8_ascii_in_row_font.png",TCOD_FONT_LAYOUT_ASCII_INROW,32,8); - TCOD_console_set_custom_font("greyscale_8x8_tcod_font.png",TCOD_FONT_LAYOUT_TCOD | TCOD_FONT_TYPE_GREYSCALE,32,8); - @PyEx - libtcod.console_set_custom_font("standard_8x8_ascii_in_col_font.bmp",libtcod.FONT_LAYOUT_ASCII_INCOL) - libtcod.console_set_custom_font("32bits_8x8_ascii_in_row_font.png",libtcod.FONT_LAYOUT_ASCII_INROW) - libtcod.console_set_custom_font("greyscale_8x8_tcod_font.png",libtcod.FONT_LAYOUT_TCOD | libtcod.FONT_TYPE_GREYSCALE) - @LuaEx - tcod.console.setCustomFont("standard_8x8_ascii_in_col_font.bmp",tcod.LayoutAsciiInColumn); - tcod.console.setCustomFont("32bits_8x8_ascii_in_row_font.png",tcod.LayoutAsciiInRow); - tcod.console.setCustomFont("greyscale_8x8_tcod_font.png",tcod.LayoutTCOD + tcod.Greyscale); - */ - static void setCustomFont(const char *fontFile, int flags=TCOD_FONT_LAYOUT_ASCII_INCOL,int nbCharHoriz=0, int nbCharVertic=0); - - /** - @PageName console_map - @PageTitle Using custom characters mapping - @PageFather console_init - @FuncTitle Mapping a single ASCII code to a character - @PageDesc These functions allow you to map characters in the bitmap font to ASCII codes. - They should be called after initializing the root console with initRoot. - You can dynamically change the characters mapping at any time, allowing to use several fonts in the same screen. - @Cpp static void TCODConsole::mapAsciiCodeToFont(int asciiCode, int fontCharX, int fontCharY) - @C void TCOD_console_map_ascii_code_to_font(int asciiCode, int fontCharX, int fontCharY) - @Py console_map_ascii_code_to_font(asciiCode, fontCharX, fontCharY) - @C# static void TCODConsole::mapAsciiCodeToFont(int asciiCode, int fontCharX, int fontCharY) - @Lua tcod.console.mapAsciiCodeToFont(asciiCode, fontCharX, fontCharY) - @Param asciiCode ASCII code to map. - @Param fontCharX,fontCharY Coordinate of the character in the bitmap font (in characters, not pixels). - */ - static void mapAsciiCodeToFont(int asciiCode, int fontCharX, int fontCharY); - - /** - @PageName console_map - @FuncTitle Mapping consecutive ASCII codes to consecutive characters - @Cpp static void TCODConsole::mapAsciiCodesToFont(int firstAsciiCode, int nbCodes, int fontCharX, int fontCharY) - @C void TCOD_console_map_ascii_codes_to_font(int firstAsciiCode, int nbCodes, int fontCharX, int fontCharY) - @Py console_map_ascii_codes_to_font(firstAsciiCode, nbCodes, fontCharX, fontCharY) - @C# static void TCODConsole::mapAsciiCodesToFont(int firstAsciiCode, int nbCodes, int fontCharX, int fontCharY) - @Lua tcod.console.mapAsciiCodesToFont(firstAsciiCode, nbCodes, fontCharX, fontCharY) - @Param firstAsciiCode first ASCII code to map - @Param nbCodes number of consecutive ASCII codes to map - @Param fontCharX,fontCharY coordinate of the character in the bitmap font (in characters, not pixels) corresponding to the first ASCII code - */ - static void mapAsciiCodesToFont(int firstAsciiCode, int nbCodes, int fontCharX, int fontCharY); - - /** - @PageName console_map - @FuncTitle Mapping ASCII code from a string to consecutive characters - @Cpp static void TCODConsole::mapStringToFont(const char *s, int fontCharX, int fontCharY) - @C void TCOD_console_map_string_to_font(const char *s, int fontCharX, int fontCharY) - @Py console_map_string_to_font(s, fontCharX, fontCharY) - @C# static void TCODConsole::mapStringToFont(string s, int fontCharX, int fontCharY) - @Lua tcod.console.mapStringToFont(s, fontCharX, fontCharY) - @Param s string containing the ASCII codes to map - @Param fontCharX,fontCharY coordinate of the character in the bitmap font (in characters, not pixels) corresponding to the first ASCII code in the string - */ - static void mapStringToFont(const char *s, int fontCharX, int fontCharY); - - /** - @PageName console_fullscreen - @PageTitle Fullscreen mode - @PageFather console_init - @FuncTitle Getting the current mode - @FuncDesc This function returns true if the current mode is fullscreen. - @Cpp static bool TCODConsole::isFullscreen() - @C bool TCOD_console_is_fullscreen() - @Py console_is_fullscreen() - @C# static bool TCODConsole::isFullscreen() - @Lua tcod.console.isFullscreen() - */ - static bool isFullscreen(); - /** - @PageName console_fullscreen - @FuncTitle Switching between windowed and fullscreen modes - @FuncDesc This function switches the root console to fullscreen or windowed mode. - Note that there is no predefined key combination to switch to/from fullscreen. You have to do this in your own code. - @Cpp static void TCODConsole::setFullscreen(bool fullscreen) - @C void TCOD_console_set_fullscreen(bool fullscreen) - @Py console_set_fullscreen(fullscreen) - @C# static void TCODConsole::setFullscreen(bool fullscreen) - @Lua tcod.console.setFullscreen(fullscreen) - @Param fullscreen true to switch to fullscreen mode. - false to switch to windowed mode. - @CppEx - TCOD_key_t key; - TCODConsole::checkForEvent(TCOD_EVENT_KEY_PRESS,&key,NULL); - if ( key.vk == TCODK_ENTER && key.lalt ) - TCODConsole::setFullscreen(!TCODConsole::isFullscreen()); - @CEx - TCOD_key_t key; - TCOD_console_check_for_event(TCOD_EVENT_KEY_PRESS,&key,NULL); - if ( key.vk == TCODK_ENTER && key.lalt ) - TCOD_console_set_fullscreen(!TCOD_console_is_fullscreen()); - @PyEx - key=Key() - libtcod.console_check_for_event(libtcod.EVENT_KEY_PRESS,key,0) - if key.vk == libtcod.KEY_ENTER and key.lalt : - libtcod.console_set_fullscreen(not libtcod.console_is_fullscreen()) - @LuaEx - key=tcod.console.checkForKeypress() - if key.KeyCode == tcod.Enter and key.LeftAlt then - tcod.console.setFullscreen(not tcod.console.isFullscreen()) - end - */ - static void setFullscreen(bool fullscreen); - - /** - @PageName console_window - @PageFather console_init - @PageTitle Communicate with the window manager - @FuncTitle Changing the window title - @FuncDesc This function dynamically changes the title of the game window. - Note that the window title is not visible while in fullscreen. - @Cpp static void TCODConsole::setWindowTitle(const char *title) - @C void TCOD_console_set_window_title(const char *title) - @Py console_set_window_title(title) - @C# static void TCODConsole::setWindowTitle(string title) - @Lua tcod.console.setWindowTitle(title) - @Param title New title of the game window - */ - static void setWindowTitle(const char *title); - - /** - @PageName console_window - @FuncTitle Handling "close window" events - @FuncDesc When you start the program, this returns false. Once a "close window" event has been sent by the window manager, it will always return true. You're supposed to exit cleanly the game. - @Cpp static bool TCODConsole::isWindowClosed() - @C bool TCOD_console_is_window_closed() - @Py console_is_window_closed() - @C# static bool TCODConsole::isWindowClosed() - @Lua tcod.console.isWindowClosed() - */ - static bool isWindowClosed(); - - /** - @PageName console_window - @FuncTitle Check if the mouse cursor is inside the game window - @FuncDesc Returns true if the mouse cursor is inside the game window area and the game window is the active application. - @Cpp static bool TCODConsole::hasMouseFocus() - @C bool TCOD_console_has_mouse_focus() - @Py console_has_mouse_focus() - */ - static bool hasMouseFocus(); - - /** - @PageName console_window - @FuncTitle Check if the game application is active - @FuncDesc Returns false if the game window is not the active window or is iconified. - @Cpp static bool TCODConsole::isActive() - @C bool TCOD_console_is_active() - @Py console_is_active() - */ - static bool isActive(); - - /** - @PageName console_credits - @PageTitle libtcod's credits - @PageFather console_init - @PageDesc Use these functions to display credits, as seen in the samples. - @FuncTitle Using a separate credit page - @FuncDesc You can print a "Powered by libtcod x.y.z" screen during your game startup simply by calling this function after initRoot. - The credits screen can be skipped by pressing any key. - @Cpp static void TCODConsole::credits() - @C void TCOD_console_credits() - @Py console_credits() - @C# static void TCODConsole::credits() - @Lua tcod.console.credits() - */ - static void credits(); - - /** - @PageName console_credits - @FuncTitle Embedding credits in an existing page - @FuncDesc You can also print the credits on one of your game screens (your main menu for example) by calling this function in your main loop. - This function returns true when the credits screen is finished, indicating that you no longer need to call it. - @Cpp static bool TCODConsole::renderCredits(int x, int y, bool alpha) - @C bool TCOD_console_credits_render(int x, int y, bool alpha) - @Py bool TCOD_console_credits_render(int x, int y, bool alpha) - @C# static bool TCODConsole::renderCredits(int x, int y, bool alpha) - @Lua tcod.console.renderCredits(x, y, alpha) - @Param x,y Position of the credits text in your root console - @Param alpha If true, credits are transparently added on top of the existing screen. - For this to work, this function must be placed between your screen rendering code and the console flush. - @CppEx - TCODConsole::initRoot(80,50,"The Chronicles Of Doryen v0.1",false); // initialize the root console - bool endCredits=false; - while ( ! TCODConsole::isWindowClosed() ) { // your game loop - // your game rendering here... - // render transparent credits near the center of the screen - if (! endCredits ) endCredits=TCODConsole::renderCredits(35,25,true); - TCODConsole::flush(); - } - @CEx - TCOD_console_init_root(80,50,"The Chronicles Of Doryen v0.1",false); - bool end_credits=false; - while ( ! TCOD_console_is_window_closed() ) { - // your game rendering here... - // render transparent credits near the center of the screen - if (! end_credits ) end_credits=TCOD_console_credits_render(35,25,true); - TCOD_console_flush(); - } - @PyEx - libtcod.console_init_root(80,50,"The Chronicles Of Doryen v0.1",False) - end_credits=False - while not libtcod.console_is_window_closed() : - // your game rendering here... - // render transparent credits near the center of the screen - if (not end_credits ) : end_credits=libtcod.console_credits_render(35,25,True) - libtcod.console_flush() - @LuaEx - tcod.console.initRoot(80,50,"The Chronicles Of Doryen v0.1") -- initialize the root console - endCredits=false - while not tcod.console.isWindowClosed() do -- your game loop - -- your game rendering here... - -- render transparent credits near the center of the screen - if not endCredits then endCredits=tcod.console.renderCredits(35,25,true) end - tcod.console.flush() - end - */ - static bool renderCredits(int x, int y, bool alpha); - - /** - @PageName console_credits - @FuncTitle Restart the credits animation - @FuncDesc When using rederCredits, you can restart the credits animation from the beginning before it's finished by calling this function. - @Cpp static void TCODConsole::resetCredits() - @C void TCOD_console_credits_reset() - @Py console_credits_reset() - @C# static void TCODConsole::resetCredits() - @Lua tcod.console.resetCredits() - */ - static void resetCredits(); - - /** - @PageName console_draw - @PageTitle Drawing on the root console - @PageFather console - */ - - /** - @PageName console_draw_basic - @PageTitle Basic printing functions - @PageFather console_draw - @FuncTitle Setting the default background color - @FuncDesc This function changes the default background color for a console. The default background color is used by several drawing functions like clear, putChar, ... - @Cpp void TCODConsole::setDefaultBackground(TCODColor back) - @C void TCOD_console_set_default_background(TCOD_console_t con,TCOD_color_t back) - @Py console_set_default_background(con,back) - @C# void TCODConsole::setBackgroundColor(TCODColor back) - @Lua Console:setBackgroundColor(back) - @Param con in the C and Python versions, the offscreen console handler or NULL for the root console - @Param back the new default background color for this console - @CppEx TCODConsole::root->setDefaultBackground(myColor) - @CEx TCOD_console_set_default_background(NULL, my_color) - @PyEx litbcod.console_set_default_background(0, my_color) - @Lua libtcod.TCODConsole_root:setBackgroundColor( myColor ) - */ - void setDefaultBackground(TCODColor back); - - /** - @PageName console_draw_basic - @FuncTitle Setting the default foreground color - @FuncDesc This function changes the default foreground color for a console. The default foreground color is used by several drawing functions like clear, putChar, ... - @Cpp void TCODConsole::setDefaultForeground(TCODColor fore) - @C void TCOD_console_set_default_foreground(TCOD_console_t con,TCOD_color_t fore) - @Py console_set_default_foreground(con, fore) - @C# void TCODConsole::setForegroundColor(TCODColor fore) - @Lua Console:setForegroundColor(fore) - @Param con in the C and Python versions, the offscreen console handler or NULL for the root console - @Param fore the new default foreground color for this console - @CppEx TCODConsole::root->setDefaultForeground(myColor) - @CEx TCOD_console_set_default_foreground(NULL, my_color) - @PyEx litbcod.console_set_default_foreground(0, my_color) - @LuaEx libtcod.TCODConsole_root:setForegroundColor( myColor ) - */ - void setDefaultForeground(TCODColor fore); - - /** - @PageName console_draw_basic - @FuncTitle Clearing a console - @FuncDesc This function modifies all cells of a console : - * set the cell's background color to the console default background color - * set the cell's foreground color to the console default foreground color - * set the cell's ASCII code to 32 (space) - @Cpp void TCODConsole::clear() - @C void TCOD_console_clear(TCOD_console_t con) - @Py console_clear(con) - @C# void TCODConsole::clear() - @Lua Console:clear() - @Param con in the C and Python versions, the offscreen console handler or NULL for the root console - */ - void clear(); - - /** - @PageName console_draw_basic - @FuncTitle Setting the background color of a cell - @FuncDesc This function modifies the background color of a cell, leaving other properties (foreground color and ASCII code) unchanged. - @Cpp void TCODConsole::setCharBackground(int x, int y, const TCODColor &col, TCOD_bkgnd_flag_t flag = TCOD_BKGND_SET) - @C void TCOD_console_set_char_background(TCOD_console_t con,int x, int y, TCOD_color_t col, TCOD_bkgnd_flag_t flag) - @Py console_set_char_background(con, x, y, col, flag=BKGND_SET) - @C# - void TCODConsole::setCharBackground(int x, int y, TCODColor col) - void TCODConsole::setCharBackground(int x, int y, TCODColor col, TCODBackgroundFlag flag) - @Lua - Console:setCharBackground(x, y, col) - Console:setCharBackground(x, y, col, flag) - @Param con in the C and Python versions, the offscreen console handler or NULL for the root console - @Param x,y coordinates of the cell in the console. - 0 <= x < console width - 0 <= y < console height - @Param col the background color to use. You can use color constants - @Param flag this flag defines how the cell's background color is modified. See TCOD_bkgnd_flag_t - */ - void setCharBackground(int x, int y, const TCODColor &col, TCOD_bkgnd_flag_t flag = TCOD_BKGND_SET); - /** - @PageName console_draw_basic - @FuncTitle Setting the foreground color of a cell - @FuncDesc This function modifies the foreground color of a cell, leaving other properties (background color and ASCII code) unchanged. - @Cpp void TCODConsole::setCharForeground(int x, int y, const TCODColor &col) - @C void TCOD_console_set_char_foreground(TCOD_console_t con,int x, int y, TCOD_color_t col) - @Py console_set_char_foreground(con, x, y, col) - @C# void TCODConsole::setCharForeground(int x, int y, TCODColor col) - @Lua Console:setCharForeground(x, y, col) - @Param con in the C and Python versions, the offscreen console handler or NULL for the root console - @Param x,y coordinates of the cell in the console. - 0 <= x < console width - 0 <= y < console height - @Param col the foreground color to use. You can use color constants - */ - void setCharForeground(int x, int y, const TCODColor &col); - - /** - @PageName console_draw_basic - @FuncTitle Setting the ASCII code of a cell - @FuncDesc This function modifies the ASCII code of a cell, leaving other properties (background and foreground colors) unchanged. - Note that since a clear console has both background and foreground colors set to black for every cell, using setchar will produce black characters on black background. Use putchar instead. - @Cpp void TCODConsole::setChar(int x, int y, int c) - @C void TCOD_console_set_char(TCOD_console_t con,int x, int y, int c) - @Py console_set_char(con, x, y, c) - @C# void TCODConsole::setChar(int x, int y, int c) - @Lua Console:setChar(x, y, c) - @Param con in the C and Python versions, the offscreen console handler or NULL for the root console - @Param x,y coordinates of the cell in the console. - 0 <= x < console width - 0 <= y < console height - @Param c the new ASCII code for the cell. You can use ASCII constants - */ - void setChar(int x, int y, int c); - - /** - @PageName console_draw_basic - @FuncTitle Setting every property of a cell using default colors - @FuncDesc This function modifies every property of a cell : - * update the cell's background color according to the console default background color (see TCOD_bkgnd_flag_t). - * set the cell's foreground color to the console default foreground color - * set the cell's ASCII code to c - @Cpp void TCODConsole::putChar(int x, int y, int c, TCOD_bkgnd_flag_t flag = TCOD_BKGND_DEFAULT) - @C void TCOD_console_put_char(TCOD_console_t con,int x, int y, int c, TCOD_bkgnd_flag_t flag) - @Py console_put_char( con, x, y, c, flag=BKGND_DEFAULT) - @C# - void TCODConsole::putChar(int x, int y, int c) - void TCODConsole::putChar(int x, int y, int c, TCODBackgroundFlag flag) - @Lua - Console:putChar(x, y, c) - Console:putChar(x, y, c, flag) - @Param con in the C and Python versions, the offscreen console handler or NULL for the root console - @Param x,y coordinates of the cell in the console. - 0 <= x < console width - 0 <= y < console height - @Param c the new ASCII code for the cell. You can use ASCII constants - @Param flag this flag defines how the cell's background color is modified. See TCOD_bkgnd_flag_t - */ - void putChar(int x, int y, int c, TCOD_bkgnd_flag_t flag = TCOD_BKGND_DEFAULT); - - /** - @PageName console_draw_basic - @FuncTitle Setting every property of a cell using specific colors - @FuncDesc This function modifies every property of a cell : - * set the cell's background color to back. - * set the cell's foreground color to fore. - * set the cell's ASCII code to c. - @Cpp void TCODConsole::putCharEx(int x, int y, int c, const TCODColor & fore, const TCODColor & back) - @C void TCOD_console_put_char_ex(TCOD_console_t con,int x, int y, int c, TCOD_color_t fore, TCOD_color_t back) - @Py console_put_char_ex( con, x, y, c, fore, back) - @C# void TCODConsole::putCharEx(int x, int y, int c, TCODColor fore, TCODColor back) - @Lua Console:putCharEx(x, y, c, fore, back) - @Param con in the C and Python versions, the offscreen console handler or NULL for the root console - @Param x,y coordinates of the cell in the console. - 0 <= x < console width - 0 <= y < console height - @Param c the new ASCII code for the cell. You can use ASCII constants - @Param fore,back new foreground and background colors for this cell - */ - void putCharEx(int x, int y, int c, const TCODColor &fore, const TCODColor &back); - - /** - @PageName console_bkgnd_flag_t - @PageTitle Background effect flags - @PageFather console_draw - @PageDesc This flag is used by most functions that modify a cell background color. It defines how the console's current background color is used to modify the cell's existing background color : - TCOD_BKGND_NONE : the cell's background color is not modified. - TCOD_BKGND_SET : the cell's background color is replaced by the console's default background color : newbk = curbk. - TCOD_BKGND_MULTIPLY : the cell's background color is multiplied by the console's default background color : newbk = oldbk * curbk - TCOD_BKGND_LIGHTEN : newbk = MAX(oldbk,curbk) - TCOD_BKGND_DARKEN : newbk = MIN(oldbk,curbk) - TCOD_BKGND_SCREEN : newbk = white - (white - oldbk) * (white - curbk) // inverse of multiply : (1-newbk) = (1-oldbk)*(1-curbk) - TCOD_BKGND_COLOR_DODGE : newbk = curbk / (white - oldbk) - TCOD_BKGND_COLOR_BURN : newbk = white - (white - oldbk) / curbk - TCOD_BKGND_ADD : newbk = oldbk + curbk - TCOD_BKGND_ADDALPHA(alpha) : newbk = oldbk + alpha*curbk - TCOD_BKGND_BURN : newbk = oldbk + curbk - white - TCOD_BKGND_OVERLAY : newbk = curbk.x <= 0.5 ? 2*curbk*oldbk : white - 2*(white-curbk)*(white-oldbk) - TCOD_BKGND_ALPHA(alpha) : newbk = (1.0f-alpha)*oldbk + alpha*(curbk-oldbk) - TCOD_BKGND_DEFAULT : use the console's default background flag - Note that TCOD_BKGND_ALPHA and TCOD_BKGND_ADDALPHA are MACROS that needs a float parameter between (0.0 and 1.0). TCOD_BKGND_ALPH and TCOD_BKGND_ADDA should not be used directly (else they will have the same effect as TCOD_BKGND_NONE). - For Python, remove TCOD_ : libtcod.BKGND_NONE - For C# : None, Set, Multiply, Lighten, Darken, Screen, ColodDodge, ColorBurn, Add, Burn Overlay, Default - With lua, use tcod.None, ..., tcod.Default, BUT tcod.console.Alpha(value) and tcod.console.AddAlpha(value) - */ - - /** - @PageName console_print - @PageTitle String drawing functions - @PageFather console_draw - @FuncTitle Setting the default background flag - @FuncDesc This function defines the background mode (see TCOD_bkgnd_flag_t) for the console. - This default mode is used by several functions (print, printRect, ...) - @Cpp void TCODConsole::setBackgroundFlag(TCOD_bkgnd_flag_t flag) - @C void TCOD_console_set_background_flag(TCOD_console_t con,TCOD_bkgnd_flag_t flag) - @Py console_set_background_flag(con, flag) - @C# void TCODConsole::setBackgroundFlag(TCODBackgroundFlag flag) - @Lua Console:setBackgroundFlag(flag) - @Param con in the C and Python versions, the offscreen console handler or NULL for the root console - @Param flag this flag defines how the cell's background color is modified. See TCOD_bkgnd_flag_t - */ - void setBackgroundFlag(TCOD_bkgnd_flag_t flag); - - /** - @PageName console_print - @FuncTitle Getting the default background flag - @FuncDesc This function returns the background mode (see TCOD_bkgnd_flag_t) for the console. - This default mode is used by several functions (print, printRect, ...) - @Cpp TCOD_bkgnd_flag_t TCODConsole::getBackgroundFlag() const - @C TCOD_bkgnd_flag_t TCOD_console_get_background_flag(TCOD_console_t con) - @Py console_get_background_flag(con) - @C# TCODBackgroundFlag TCODConsole::getBackgroundFlag() - @Lua Console:getBackgroundFlag() - @Param con in the C and Python versions, the offscreen console handler or NULL for the root console - */ - TCOD_bkgnd_flag_t getBackgroundFlag() const; - - /** - @PageName console_print - @FuncTitle Setting the default alignment - @FuncDesc This function defines the default alignment (see TCOD_alignment_t) for the console. - This default alignment is used by several functions (print, printRect, ...). - Values for alignment : TCOD_LEFT, TCOD_CENTER, TCOD_RIGHT (in Python, remove TCOD_ : libtcod.LEFT). - For C# and Lua : LeftAlignment, RightAlignment, CenterAlignment - @Cpp void TCODConsole::setAlignment(TCOD_alignment_t alignment) - @C void TCOD_console_set_alignment(TCOD_console_t con,TCOD_bkgnd_flag_t alignment) - @Py console_set_alignment(con, alignment) - @C# void TCODConsole::setAlignment(TCODAlignment alignment) - @Lua Console:setAlignment(alignment) - @Param con in the C and Python versions, the offscreen console handler or NULL for the root console - @Param alignment defines how the strings are printed on screen. - */ - void setAlignment(TCOD_alignment_t alignment); - - /** - @PageName console_print - @FuncTitle Getting the default alignment - @FuncDesc This function returns the default alignment (see TCOD_alignment_t) for the console. - This default mode is used by several functions (print, printRect, ...). - Values for alignment : TCOD_LEFT, TCOD_CENTER, TCOD_RIGHT (in Python, remove TCOD_ : libtcod.LEFT). - For C# and Lua : LeftAlignment, RightAlignment, CenterAlignment - @Cpp TCOD_alignment_t TCODConsole::getAlignment() const - @C TCOD_alignment_t TCOD_console_get_alignment(TCOD_console_t con) - @Py console_get_alignment(con) - @C# TCODAlignment TCODConsole::getAlignment() - @Lua Console:getAlignment() - @Param con in the C and Python versions, the offscreen console handler or NULL for the root console - */ - TCOD_alignment_t getAlignment() const; - - /** - @PageName console_print - @FuncTitle Printing a string with default parameters - @FuncDesc This function print a string at a specific position using current default alignment, background flag, foreground and background colors. - @Cpp void TCODConsole::print(int x, int y, const char *fmt, ...) - @C void TCOD_console_print(TCOD_console_t con,int x, int y, const char *fmt, ...) - @Py console_print(con, x, y, fmt) - @C# void TCODConsole::print(int x, int y, string fmt) - @Lua Console:print(x, y, fmt) - @Param con in the C and Python versions, the offscreen console handler or NULL for the root console - @Param x,y coordinate of the character in the console, depending on the default alignment for this console : - * TCOD_LEFT : leftmost character of the string - * TCOD_CENTER : center character of the string - * TCOD_RIGHT : rightmost character of the string - @Param fmt printf-like format string, eventually followed by parameters. You can use control codes to change the colors inside the string, except in C#. - */ - void print(int x, int y, const char *fmt, ...); - - /** - @PageName console_print - @FuncTitle Printing a string with specific alignment and background mode - @FuncDesc This function print a string at a specific position using specific alignment and background flag, but default foreground and background colors. - @Cpp void TCODConsole::printEx(int x, int y, TCOD_bkgnd_flag_t flag, TCOD_alignment_t alignment, const char *fmt, ...) - @C void TCOD_console_print_ex(TCOD_console_t con,int x, int y, TCOD_bkgnd_flag_t flag, TCOD_alignment_t alignment, const char *fmt, ...) - @Py console_print_ex(con, x, y, flag, alignment, fmt) - @C# void TCODConsole::printEx(int x, int y, TCODBackgroundFlag flag, TCODAlignment alignment, string fmt) - @Lua Console::printEx(x, y, flag, alignment, fmt) - @Param con in the C and Python versions, the offscreen console handler or NULL for the root console - @Param x,y coordinate of the character in the console, depending on the alignment : - * TCOD_LEFT : leftmost character of the string - * TCOD_CENTER : center character of the string - * TCOD_RIGHT : rightmost character of the string - @Param flag this flag defines how the cell's background color is modified. See TCOD_bkgnd_flag_t - @Param alignment defines how the strings are printed on screen. - @Param fmt printf-like format string, eventually followed by parameters. You can use control codes to change the colors inside the string, except in C#. - */ - void printEx(int x, int y, TCOD_bkgnd_flag_t flag, TCOD_alignment_t alignment, const char *fmt, ...); - - /** - @PageName console_print - @FuncTitle Printing a string with default parameters and autowrap - @FuncDesc This function draws a string in a rectangle inside the console, using default colors, alignment and background mode. - If the string reaches the borders of the rectangle, carriage returns are inserted. - If h > 0 and the bottom of the rectangle is reached, the string is truncated. If h = 0, the string is only truncated if it reaches the bottom of the console. - The function returns the height (number of console lines) of the printed string. - @Cpp int TCODConsole::printRect(int x, int y, int w, int h, const char *fmt, ...) - @C int TCOD_console_print_rect(TCOD_console_t con,int x, int y, int w, int h, const char *fmt, ...) - @Py console_print_rect(con, x, y, w, h, fmt) - @C# int TCODConsole::printRect(int x, int y, int w, int h, string fmt) - @Lua Console:printRect(x, y, w, h, fmt) - @Param con in the C and Python versions, the offscreen console handler or NULL for the root console - @Param x,y coordinate of the character in the console, depending on the alignment : - * TCOD_LEFT : leftmost character of the string - * TCOD_CENTER : center character of the string - * TCOD_RIGHT : rightmost character of the string - @Param w,h size of the rectangle - x <= x+w < console width - y <= y+h < console height - @Param fmt printf-like format string, eventually followed by parameters. You can use control codes to change the colors inside the string, except in C#. - */ - int printRect(int x, int y, int w, int h, const char *fmt, ...); - - /** - @PageName console_print - @FuncTitle Printing a string with specific alignment and background mode and autowrap - @FuncDesc This function draws a string in a rectangle inside the console, using default colors, but specific alignment and background mode. - If the string reaches the borders of the rectangle, carriage returns are inserted. - If h > 0 and the bottom of the rectangle is reached, the string is truncated. If h = 0, the string is only truncated if it reaches the bottom of the console. - The function returns the height (number of console lines) of the printed string. - @Cpp int TCODConsole::printRectEx(int x, int y, int w, int h, TCOD_bkgnd_flag_t flag, TCOD_alignment_t alignment, const char *fmt, ...) - @C int TCOD_console_print_rect_ex(TCOD_console_t con,int x, int y, int w, int h, TCOD_bkgnd_flag_t flag, TCOD_alignment_t alignment, const char *fmt, ...) - @Py console_print_rect_ex(con, x, y, w, h, flag, alignment, fmt) - @C# int TCODConsole::printRectEx(int x, int y, int w, int h, TCODBackgroundFlag flag, TCODAlignment alignment, string fmt) - @Lua Console:printRectEx(x, y, w, h, flag, alignment, fmt) - @Param con in the C and Python versions, the offscreen console handler or NULL for the root console - @Param x,y coordinate of the character in the console, depending on the alignment : - * TCOD_LEFT : leftmost character of the string - * TCOD_CENTER : center character of the string - * TCOD_RIGHT : rightmost character of the string - @Param w,h size of the rectangle - x <= x+w < console width - y <= y+h < console height - @Param flag this flag defines how the cell's background color is modified. See TCOD_bkgnd_flag_t - @Param alignment defines how the strings are printed on screen. - @Param fmt printf-like format string, eventually followed by parameters. You can use control codes to change the colors inside the string, except in C#. - */ - int printRectEx(int x, int y, int w, int h, TCOD_bkgnd_flag_t flag, TCOD_alignment_t alignment, const char *fmt, ...); - - /** - @PageName console_print - @FuncTitle Compute the height of an autowrapped string - @FuncDesc This function returns the expected height of an autowrapped string without actually printing the string with printRect or printRectEx - @Cpp int TCODConsole::getHeightRect(int x, int y, int w, int h, const char *fmt, ...) - - @C int TCOD_console_get_height_rect(TCOD_console_t con,int x, int y, int w, int h, const char *fmt, ...) - @Py console_get_height_rect(con, x, y, w, h, fmt) - @C# int TCODConsole::getHeightRect(int x, int y, int w, int h, string fmt) - @Lua Console:getHeightRect(x, y, w, h, fmt) - @Param con in the C and Python versions, the offscreen console handler or NULL for the root console - @Param x,y coordinate of the rectangle upper-left corner in the console - @Param w,h size of the rectangle - x <= x+w < console width - y <= y+h < console height - @Param fmt printf-like format string, eventually followed by parameters. You can use control codes to change the colors inside the string, except in C#. - */ - int getHeightRect(int x, int y, int w, int h, const char *fmt, ...); - - /** - @PageName console_print - @FuncTitle Changing the colors while printing a string - @FuncDesc If you want to draw a string using different colors for each word, the basic solution is to call a string printing function several times, changing the default colors between each call. - The TCOD library offers a simpler way to do this, allowing you to draw a string using different colors in a single call. For this, you have to insert color control codes in your string. - A color control code is associated with a color set (a foreground color and a background color). If you insert this code in your string, the next characters will use the colors associated with the color control code. - There are 5 predefined color control codes : - For Python, remove TCOD_ : libtcod.COLCTRL_1 - TCOD_COLCTRL_1 - TCOD_COLCTRL_2 - TCOD_COLCTRL_3 - TCOD_COLCTRL_4 - TCOD_COLCTRL_5 - To associate a color with a code, use setColorControl. - To go back to the console's default colors, insert in your string the color stop control code : - TCOD_COLCTRL_STOP - - You can also use any color without assigning it to a control code, using the generic control codes : - TCOD_COLCTRL_FORE_RGB - TCOD_COLCTRL_BACK_RGB - - Those controls respectively change the foreground and background color used to print the string characters. In the string, you must insert the r,g,b components of the color (between 1 and 255. The value 0 is forbidden because it represents the end of the string in C/C++) immediately after this code. - @Cpp static void TCODConsole::setColorControl(TCOD_colctrl_t con, const TCODColor &fore, const TCODColor &back) - @C void TCOD_console_set_color_control(TCOD_colctrl_t con, TCOD_color_t fore, TCOD_color_t back) - @Py console_set_color_control(con,fore,back) - @C# Not supported directly, use getRGBColorControlString and getColorControlString. - @Lua Not supported - @Param con the color control TCOD_COLCTRL_x, 1<=x<=5 - @Param fore foreground color when this control is activated - @Param back background color when this control is activated - @CppEx - // A string with a red over black word, using predefined color control codes - TCODConsole::setColorControl(TCOD_COLCTRL_1,TCODColor::red,TCODColor::black); - TCODConsole::root->print(1,1,"String with a %cred%c word.",TCOD_COLCTRL_1,TCOD_COLCTRL_STOP); - // A string with a red over black word, using generic color control codes - TCODConsole::root->print(1,1,"String with a %c%c%c%c%c%c%c%cred%c word.", - TCOD_COLCTRL_FORE_RGB,255,1,1,TCOD_COLCTRL_BACK_RGB,1,1,1,TCOD_COLCTRL_STOP); - // A string with a red over black word, using generic color control codes - TCODConsole::root->print(1,1,"String with a %c%c%c%c%c%c%c%cred%c word.", - TCOD_COLCTRL_FORE_RGB,255,1,1,TCOD_COLCTRL_BACK_RGB,1,1,1,TCOD_COLCTRL_STOP); - @CEx - // A string with a red over black word, using predefined color control codes - TCOD_console_set_color_control(TCOD_COLCTRL_1,red,black); - TCOD_console_print(NULL,1,1,"String with a %cred%c word.",TCOD_COLCTRL_1,TCOD_COLCTRL_STOP); - // A string with a red word (over default background color), using generic color control codes - TCOD_console_print(NULL,1,1,"String with a %c%c%c%cred%c word.", - TCOD_COLCTRL_FORE_RGB,255,1,1,TCOD_COLCTRL_STOP); - // A string with a red over black word, using generic color control codes - TCOD_console_print(NULL,1,1,"String with a %c%c%c%c%c%c%c%cred%c word.", - TCOD_COLCTRL_FORE_RGB,255,1,1,TCOD_COLCTRL_BACK_RGB,1,1,1,TCOD_COLCTRL_STOP); - @PyEx - # A string with a red over black word, using predefined color control codes - libtcod.console_set_color_control(libtcod.COLCTRL_1,litbcod.red,litbcod.black) - libtcod.console_print(0,1,1,"String with a %cred%c word."%(libtcod.COLCTRL_1,libtcod.COLCTRL_STOP)) - # A string with a red word (over default background color), using generic color control codes - litbcod.console_print(0,1,1,"String with a %c%c%c%cred%c word."%(libtcod.COLCTRL_FORE_RGB,255,1,1,libtcod.COLCTRL_STOP)) - # A string with a red over black word, using generic color control codes - libtcod.console_print(0,1,1,"String with a %c%c%c%c%c%c%c%cred%c word."% - (libtcod.COLCTRL_FORE_RGB,255,1,1,libtcod.COLCTRL_BACK_RGB,1,1,1,libtcod.COLCTRL_STOP)) - - @C#Ex - TCODConsole.root.print(1,1,String.Format("String with a {0}red{1} word.", - TCODConsole.getRGBColorControlString(ColorControlForeground,TCODColor.red), - TCODConsole.getColorControlString(ColorControlStop)); - */ - static void setColorControl(TCOD_colctrl_t con, const TCODColor &fore, const TCODColor &back); - -#ifndef NO_UNICODE - /** - @PageName console_print - @FuncTitle Unicode functions - @FuncDesc those functions are similar to their ASCII equivalent, but work with unicode strings (wchar_t in C/C++). - Note that unicode is not supported in the Python wrapper. - @Cpp static void TCODConsole::mapStringToFont(const wchar_t *s, int fontCharX, int fontCharY) - @C void TCOD_console_map_string_to_font_utf(const wchar_t *s, int fontCharX, int fontCharY) - */ - static void mapStringToFont(const wchar_t *s, int fontCharX, int fontCharY); - /** - @PageName console_print - @Cpp void TCODConsole::print(int x, int y, const wchar_t *fmt, ...) - @C void TCOD_console_print_utf(TCOD_console_t con,int x, int y, const wchar_t *fmt, ...) - */ - void print(int x, int y, const wchar_t *fmt, ...); - /** - @PageName console_print - @Cpp void TCODConsole::printEx(int x, int y, TCOD_bkgnd_flag_t flag, TCOD_alignment_t alignment, const wchar_t *fmt, ...) - @C void TCOD_console_print_ex_utf(TCOD_console_t con,int x, int y, TCOD_bkgnd_flag_t flag, TCOD_alignment_t alignment, const wchar_t *fmt, ...) - */ - void printEx(int x, int y, TCOD_bkgnd_flag_t flag, TCOD_alignment_t alignment, const wchar_t *fmt, ...); - /** - @PageName console_print - @Cpp int TCODConsole::printRect(int x, int y, int w, int h, const wchar_t *fmt, ...) - @C int TCOD_console_print_rect_utf(TCOD_console_t con,int x, int y, int w, int h, const wchar_t *fmt, ...) - */ - int printRect(int x, int y, int w, int h, const wchar_t *fmt, ...); - - /** - @PageName console_print - @Cpp int TCODConsole::printRectEx(int x, int y, int w, int h, TCOD_bkgnd_flag_t flag, TCOD_alignment_t alignment, const wchar_t *fmt, ...) - @C int TCOD_console_print_rect_ex_utf(TCOD_console_t con,int x, int y, int w, int h, TCOD_bkgnd_flag_t flag, TCOD_alignment_t alignment, const wchar_t *fmt, ...) - */ - int printRectEx(int x, int y, int w, int h, TCOD_bkgnd_flag_t flag, TCOD_alignment_t alignment, const wchar_t *fmt, ...); - - /** - @PageName console_print - @Cpp int TCODConsole::getHeightRect(int x, int y, int w, int h, const wchar_t *fmt, ...) - @C int TCOD_console_get_height_rect_utf(TCOD_console_t con,int x, int y, int w, int h, const wchar_t *fmt, ...) - */ - int getHeightRect(int x, int y, int w, int h, const wchar_t *fmt, ...); -#endif - - /** - @PageName console_advanced - @PageFather console_draw - @PageTitle Advanced printing functions - @FuncTitle Filling a rectangle with the background color - @FuncDesc Fill a rectangle inside a console. For each cell in the rectangle : - * set the cell's background color to the console default background color - * if clear is true, set the cell's ASCII code to 32 (space) - @Cpp void TCODConsole::rect(int x, int y, int w, int h, bool clear, TCOD_bkgnd_flag_t flag = TCOD_BKGND_DEFAULT) - @C void TCOD_console_rect(TCOD_console_t con,int x, int y, int w, int h, bool clear, TCOD_bkgnd_flag_t flag) - @Py console_rect(con,x, y, w, h, clear, flag=BKGND_DEFAULT) - @C# - void TCODConsole::rect(int x, int y, int w, int h, bool clear) - void TCODConsole::rect(int x, int y, int w, int h, bool clear, TCODBackgroundFlag flag) - @Lua - Console:rect(x, y, w, h, clear) - Console:rect(x, y, w, h, clear, flag) - @Param con in the C and Python versions, the offscreen console handler or NULL for the root console - @Param x,y coordinates of rectangle upper-left corner in the console. - 0 <= x < console width - 0 <= y < console height - @Param w,h size of the rectangle in the console. - x <= x+w < console width - y <= y+h < console height - @Param clear if true, all characters inside the rectangle are set to ASCII code 32 (space). - If false, only the background color is modified - @Param flag this flag defines how the cell's background color is modified. See TCOD_bkgnd_flag_t - */ - void rect(int x, int y, int w, int h, bool clear, TCOD_bkgnd_flag_t flag = TCOD_BKGND_DEFAULT); - - /** - @PageName console_advanced - @FuncTitle Drawing an horizontal line - @FuncDesc Draws an horizontal line in the console, using ASCII code TCOD_CHAR_HLINE (196), and the console's default background/foreground colors. - @Cpp void TCODConsole::hline(int x,int y, int l, TCOD_bkgnd_flag_t flag = TCOD_BKGND_DEFAULT) - @C void TCOD_console_hline(TCOD_console_t con,int x,int y, int l, TCOD_bkgnd_flag_t flag) - @Py console_hline(con,x,y,l,flag=BKGND_DEFAULT) - @C# - void TCODConsole::hline(int x,int y, int l) - void TCODConsole::hline(int x,int y, int l, TCODBackgroundFlag flag) - @Lua - Console:hline(x,y, l) - Console:hline(x,y, l, flag) - @Param con in the C and Python versions, the offscreen console handler or NULL for the root console - @Param x,y Coordinates of the line's left end in the console. - 0 <= x < console width - 0 <= y < console height - @Param l The length of the line in cells 1 <= l <= console width - x - @Param flag this flag defines how the cell's background color is modified. See TCOD_bkgnd_flag_t - */ - void hline(int x,int y, int l, TCOD_bkgnd_flag_t flag = TCOD_BKGND_DEFAULT); - - /** - @PageName console_advanced - @FuncTitle Drawing an vertical line - @FuncDesc Draws an vertical line in the console, using ASCII code TCOD_CHAR_VLINE (179), and the console's default background/foreground colors. - @Cpp void TCODConsole::vline(int x,int y, int l, TCOD_bkgnd_flag_t flag = TCOD_BKGND_DEFAULT) - @C void TCOD_console_vline(TCOD_console_t con,int x,int y, int l, TCOD_bkgnd_flag_t flag) - @Py console_vline(con,x,y,l,flag=BKGND_DEFAULT) - @C# - void TCODConsole::vline(int x,int y, int l) - void TCODConsole::vline(int x,int y, int l, TCODBackgroundFlag flag) - @Lua - Console:vline(x,y, l) - Console:vline(x,y, l, flag) - @Param con in the C and Python versions, the offscreen console handler or NULL for the root console - @Param x,y Coordinates of the line's upper end in the console. - 0 <= x < console width - 0 <= y < console height - @Param l The length of the line in cells 1 <= l <= console height - y - @Param flag this flag defines how the cell's background color is modified. See TCOD_bkgnd_flag_t - */ - void vline(int x,int y, int l, TCOD_bkgnd_flag_t flag = TCOD_BKGND_DEFAULT); - - /** - @PageName console_advanced - @FuncTitle Drawing a window frame - @FuncDesc This function calls the rect function using the supplied background mode flag, then draws a rectangle with the console's default foreground color. If fmt is not NULL, it is printed on the top of the rectangle, using inverted colors. - @Cpp void TCODConsole::printFrame(int x,int y,int w,int h, bool clear=true, TCOD_bkgnd_flag_t flag = TCOD_BKGND_DEFAULT, const char *fmt=NULL, ...) - @C void TCOD_console_print_frame(TCOD_console_t con,int x,int y,int w,int h, bool clear, TCOD_bkgnd_flag_t flag, const char *fmt, ...) - @Py console_print_frame(con,x, y, w, h, clear=True, flag=BKGND_DEFAULT, fmt=0) - @C# - void TCODConsole::printFrame(int x,int y, int w,int h) - void TCODConsole::printFrame(int x,int y, int w,int h, bool clear) - void TCODConsole::printFrame(int x,int y, int w,int h, bool clear, TCODBackgroundFlag flag) - void TCODConsole::printFrame(int x,int y, int w,int h, bool clear, TCODBackgroundFlag flag, string fmt) - @Lua - Console:printFrame(x,y, w,h) - Console:printFrame(x,y, w,h, clear) - Console:printFrame(x,y, w,h, clear, flag) - Console:printFrame(x,y, w,h, clear, flag, fmt) - @Param con in the C and Python versions, the offscreen console handler or NULL for the root console - @Param x,y Coordinates of the rectangle's upper-left corner in the console. - 0 <= x < console width - 0 <= y < console height - @Param w,h size of the rectangle in the console. - x <= x+w < console width - y <= y+h < console height - @Param clear if true, all characters inside the rectangle are set to ASCII code 32 (space). - If false, only the background color is modified - @Param flag this flag defines how the cell's background color is modified. See TCOD_bkgnd_flag_t - @Param fmt if NULL, the function only draws a rectangle. - Else, printf-like format string, eventually followed by parameters. You can use control codes to change the colors inside the string. - */ - void printFrame(int x,int y,int w,int h, bool clear=true, TCOD_bkgnd_flag_t flag = TCOD_BKGND_DEFAULT, const char *fmt=NULL, ...); - - /** - @PageName console_advanced - @FuncTitle Manipulating foreground colors as an image - @FuncDesc This function obtains the image containing the console foreground colors. - @Cpp TCODImage *TCODConsole::getForegroundImage() - @C TCOD_image_t TCOD_console_get_foreground_color_image(TCOD_console_t con) - @Py console_get_foreground_image(con) - */ - TCODImage *getForegroundColorImage(); - - /** - @PageName console_advanced - @FuncTitle Manipulating background colors as an image - @FuncDesc This function obtains the image containing the console background colors. - @Cpp TCODImage *TCODConsole::getBackgroundImage() - @C TCOD_image_t TCOD_console_get_background_color_image(TCOD_console_t con) - @Py console_get_background_image(con) - */ - TCODImage *getBackgroundColorImage(); - - /** - @PageName console_read - @PageTitle Reading the content of the console - @PageFather console_draw - @FuncTitle Get the console's width - @FuncDesc This function returns the width of a console (either the root console or an offscreen console) - @Cpp int TCODConsole::getWidth() const - @C int TCOD_console_get_width(TCOD_console_t con) - @Py console_get_width(con) - @C# int TCODConsole::getWidth() - @Lua Console:getWidth() - @Param con in the C and Python versions, the offscreen console handler or NULL for the root console - */ - int getWidth() const; - - /** - @PageName console_read - @FuncTitle Get the console's height - @FuncDesc This function returns the height of a console (either the root console or an offscreen console) - @Cpp int TCODConsole::getHeight() const - @C int TCOD_console_get_height(TCOD_console_t con) - @Py console_get_height(con) - @C# int TCODConsole::getHeight() - @Lua Console:getHeight() - @Param con in the C and Python versions, the offscreen console handler or NULL for the root console - */ - int getHeight() const; - - /** - @PageName console_read - @FuncTitle Reading the default background color - @FuncDesc This function returns the default background color of a console. - @Cpp TCODColor TCODConsole::getDefaultBackground() const - @C TCOD_color_t TCOD_console_get_default_background(TCOD_console_t con) - @Py console_get_default_background(con) - @C# TCODColor TCODConsole::getBackgroundColor() - @Lua Console:getBackgroundColor() - @Param con in the C and Python versions, the offscreen console handler or NULL for the root console - */ - TCODColor getDefaultBackground() const; - - /** - @PageName console_read - @FuncTitle Reading the default foreground color - @FuncDesc This function returns the default foreground color of a console. - @Cpp TCODColor TCODConsole::getDefaultForeground() const - @C TCOD_color_t TCOD_console_get_default_foreground(TCOD_console_t con) - @Py console_get_default_foreground(con) - @C# TCODColor TCODConsole::getForegroundColor() - @Lua Console:getForegroundColor() - @Param con in the C and Python versions, the offscreen console handler or NULL for the root console - */ - TCODColor getDefaultForeground() const; - - /** - @PageName console_read - @FuncTitle Reading the background color of a cell - @FuncDesc This function returns the background color of a cell. - @Cpp TCODColor TCODConsole::getCharBackground(int x, int y) const - @C TCOD_color_t TCOD_console_get_char_background(TCOD_console_t con,int x, int y) - @Py console_get_char_background(con,x,y) - @C# TCODColor TCODConsole::getCharBackground(int x, int y) - @Lua Console::getCharBackground(x, y) - @Param con in the C and Python versions, the offscreen console handler or NULL for the root console - @Param x,y coordinates of the cell in the console. - 0 <= x < console width - 0 <= y < console height - */ - TCODColor getCharBackground(int x, int y) const; - - /** - @PageName console_read - @FuncTitle Reading the foreground color of a cell - @FuncDesc This function returns the foreground color of a cell. - @Cpp TCODColor TCODConsole::getCharForeground(int x, int y) const - @C TCOD_color_t TCOD_console_get_char_foreground(TCOD_console_t con,int x, int y) - @Py console_get_char_foreground(con,x,y) - @C# TCODColor TCODConsole::getCharForeground(int x, int y) - @Lua Console::getCharForeground(x, y) - @Param con in the C and Python versions, the offscreen console handler or NULL for the root console - @Param x,y coordinates of the cell in the console. - 0 <= x < console width - 0 <= y < console height - */ - TCODColor getCharForeground(int x, int y) const; - - /** - @PageName console_read - @FuncTitle Reading the ASCII code of a cell - @FuncDesc This function returns the ASCII code of a cell. - @Cpp int TCODConsole::getChar(int x, int y) const - @C int TCOD_console_get_char(TCOD_console_t con,int x, int y) - @Py console_get_char(con,x,y) - @C# int TCODConsole::getChar(int x, int y) - @Lua Console::getChar(x, y) - @Param con in the C and Python versions, the offscreen console handler or NULL for the root console - @Param x,y coordinates of the cell in the console. - 0 <= x < console width - 0 <= y < console height - */ - int getChar(int x, int y) const; - - /** - @PageName console_fading - @PageTitle Screen fading functions - @PageFather console_draw - @PageDesc Use these functions to easily fade to/from a color - @FuncTitle Changing the fading parameters - @FuncDesc This function defines the fading parameters, allowing to easily fade the game screen to/from a color. Once they are defined, the fading parameters are valid for ever. You don't have to call setFade for each rendered frame (unless you change the fading parameters). - @Cpp static void TCODConsole::setFade(uint8_t fade, const TCODColor &fadingColor) - @C void TCOD_console_set_fade(uint8_t fade, TCOD_color_t fadingColor) - @Py console_set_fade(fade, fadingColor) - @C# static void TCODConsole::setFade(byte fade, TCODColor fadingColor) - @Lua tcod.console.setFade(fade, fadingColor) - @Param fade the fading amount. 0 => the screen is filled with the fading color. 255 => no fading effect - @Param fadingColor the color to use during the console flushing operation - @CppEx - for (int fade=255; fade >= 0; fade --) { - TCODConsole::setFade(fade,TCODColor::black); - TCODConsole::flush(); - } - @CEx - int fade; - for (fade=255; fade >= 0; fade --) { - TCOD_console_setFade(fade,TCOD_black); - TCOD_console_flush(); - } - @PyEx - for fade in range(255,0) : - libtcod.console_setFade(fade,libtcod.black) - libtcod.console_flush() - @LuaEx - for fade=255,0,-1 do - tcod.console.setFade(fade,tcod.color.black) - tcod.console.flush() - end - */ - static void setFade(uint8_t fade, const TCODColor &fadingColor); - - /** - @PageName console_fading - @FuncTitle Reading the fade amount - @FuncDesc This function returns the current fade amount, previously defined by setFade. - @Cpp static uint8_t TCODConsole::getFade() - @C uint8_t TCOD_console_get_fade() - @Py console_get_fade() - @C# static byte TCODConsole::getFade() - @Lua tcod.console.getFade() - */ - static uint8_t getFade(); - - /** - @PageName console_fading - @FuncTitle Reading the fading color - @FuncDesc This function returns the current fading color, previously defined by setFade. - @Cpp static TCODColor TCODConsole::getFadingColor() - @C TCOD_color_t TCOD_console_get_fading_color() - @Py console_get_fading_color() - @C# static TCODColor TCODConsole::getFadingColor() - @Lua tcod.console.getFadingColor() - */ - static TCODColor getFadingColor(); - - /** - @PageName console_flush - @PageFather console - @PageTitle Flushing the root console - @FuncDesc Once the root console is initialized, you can use one of the printing functions to change the background colors, the foreground colors or the ASCII characters on the console. - Once you've finished rendering the root console, you have to actually apply the updates to the screen with this function. - @Cpp static void TCODConsole::flush() - @C void TCOD_console_flush() - @Py console_flush() - @C# static void TCODConsole::flush() - @Lua tcod.console.flush() - */ - static void flush(); - - /** - @PageName console_ascii - @PageTitle ASCII constants - @PageFather console_draw - @FuncDesc Some useful graphic characters in the terminal.bmp font. For the Python version, remove TCOD_ from the constants. C# and Lua is in parenthesis : - Single line walls: - TCOD_CHAR_HLINE=196 (HorzLine) - TCOD_CHAR_VLINE=179 (VertLine) - TCOD_CHAR_NE=191 (NE) - TCOD_CHAR_NW=218 (NW) - TCOD_CHAR_SE=217 (SE) - TCOD_CHAR_SW=192 (SW) - - Double lines walls: - TCOD_CHAR_DHLINE=205 (DoubleHorzLine) - TCOD_CHAR_DVLINE=186 (DoubleVertLine) - TCOD_CHAR_DNE=187 (DoubleNE) - TCOD_CHAR_DNW=201 (DoubleNW) - TCOD_CHAR_DSE=188 (DoubleSE) - TCOD_CHAR_DSW=200 (DoubleSW) - - Single line vertical/horizontal junctions (T junctions): - TCOD_CHAR_TEEW=180 (TeeWest) - TCOD_CHAR_TEEE=195 (TeeEast) - TCOD_CHAR_TEEN=193 (TeeNorth) - TCOD_CHAR_TEES=194 (TeeSouth) - - Double line vertical/horizontal junctions (T junctions): - TCOD_CHAR_DTEEW=185 (DoubleTeeWest) - TCOD_CHAR_DTEEE=204 (DoubleTeeEast) - TCOD_CHAR_DTEEN=202 (DoubleTeeNorth) - TCOD_CHAR_DTEES=203 (DoubleTeeSouth) - - Block characters: - TCOD_CHAR_BLOCK1=176 (Block1) - TCOD_CHAR_BLOCK2=177 (Block2) - TCOD_CHAR_BLOCK3=178 (Block3) - - Cross-junction between two single line walls: - TCOD_CHAR_CROSS=197 (Cross) - - Arrows: - TCOD_CHAR_ARROW_N=24 (ArrowNorth) - TCOD_CHAR_ARROW_S=25 (ArrowSouth) - TCOD_CHAR_ARROW_E=26 (ArrowEast) - TCOD_CHAR_ARROW_W=27 (ArrowWest) - - Arrows without tail: - TCOD_CHAR_ARROW2_N=30 (ArrowNorthNoTail) - TCOD_CHAR_ARROW2_S=31 (ArrowSouthNoTail) - TCOD_CHAR_ARROW2_E=16 (ArrowEastNoTail) - TCOD_CHAR_ARROW2_W=17 (ArrowWestNoTail) - - Double arrows: - TCOD_CHAR_DARROW_H=29 (DoubleArrowHorz) - TCOD_CHAR_ARROW_V=18 (DoubleArrowVert) - - GUI stuff: - TCOD_CHAR_CHECKBOX_UNSET=224 - TCOD_CHAR_CHECKBOX_SET=225 - TCOD_CHAR_RADIO_UNSET=9 - TCOD_CHAR_RADIO_SET=10 - - Sub-pixel resolution kit: - TCOD_CHAR_SUBP_NW=226 (SubpixelNorthWest) - TCOD_CHAR_SUBP_NE=227 (SubpixelNorthEast) - TCOD_CHAR_SUBP_N=228 (SubpixelNorth) - TCOD_CHAR_SUBP_SE=229 (SubpixelSouthEast) - TCOD_CHAR_SUBP_DIAG=230 (SubpixelDiagonal) - TCOD_CHAR_SUBP_E=231 (SubpixelEast) - TCOD_CHAR_SUBP_SW=232 (SubpixelSouthWest) - - Miscellaneous characters: - TCOD_CHAR_SMILY = 1 (Smilie) - TCOD_CHAR_SMILY_INV = 2 (SmilieInv) - TCOD_CHAR_HEART = 3 (Heart) - TCOD_CHAR_DIAMOND = 4 (Diamond) - TCOD_CHAR_CLUB = 5 (Club) - TCOD_CHAR_SPADE = 6 (Spade) - TCOD_CHAR_BULLET = 7 (Bullet) - TCOD_CHAR_BULLET_INV = 8 (BulletInv) - TCOD_CHAR_MALE = 11 (Male) - TCOD_CHAR_FEMALE = 12 (Female) - TCOD_CHAR_NOTE = 13 (Note) - TCOD_CHAR_NOTE_DOUBLE = 14 (NoteDouble) - TCOD_CHAR_LIGHT = 15 (Light) - TCOD_CHAR_EXCLAM_DOUBLE = 19 (ExclamationDouble) - TCOD_CHAR_PILCROW = 20 (Pilcrow) - TCOD_CHAR_SECTION = 21 (Section) - TCOD_CHAR_POUND = 156 (Pound) - TCOD_CHAR_MULTIPLICATION = 158 (Multiplication) - TCOD_CHAR_FUNCTION = 159 (Function) - TCOD_CHAR_RESERVED = 169 (Reserved) - TCOD_CHAR_HALF = 171 (Half) - TCOD_CHAR_ONE_QUARTER = 172 (OneQuarter) - TCOD_CHAR_COPYRIGHT = 184 (Copyright) - TCOD_CHAR_CENT = 189 (Cent) - TCOD_CHAR_YEN = 190 (Yen) - TCOD_CHAR_CURRENCY = 207 (Currency) - TCOD_CHAR_THREE_QUARTERS = 243 (ThreeQuarters) - TCOD_CHAR_DIVISION = 246 (Division) - TCOD_CHAR_GRADE = 248 (Grade) - TCOD_CHAR_UMLAUT = 249 (Umlaut) - TCOD_CHAR_POW1 = 251 (Pow1) - TCOD_CHAR_POW3 = 252 (Pow2) - TCOD_CHAR_POW2 = 253 (Pow3) - TCOD_CHAR_BULLET_SQUARE = 254 (BulletSquare) - */ - - /** - @PageName console_input - @PageTitle Handling user input - @PageDesc The user handling functions allow you to get keyboard and mouse input from the user, either for turn by turn games (the function wait until the user press a key or a mouse button), or real time games (non blocking function). - WARNING : those functions also handle screen redraw event, so TCODConsole::flush function won't redraw screen if no user input function is called ! - @PageFather console - */ - - /* deprecated as of 1.5.1 */ - static TCOD_key_t waitForKeypress(bool flush); - /* deprecated as of 1.5.1 */ - static TCOD_key_t checkForKeypress(int flags=TCOD_KEY_RELEASED); - - /** - @PageName console_blocking_input - @PageCategory Core - @PageFather console_input - @PageTitle Blocking user input - @PageDesc This function stops the application until an event occurs. - */ - - /** - @PageName console_non_blocking_input - @PageTitle Non blocking user input - @PageFather console_input - @FuncDesc The preferred way to check for user input is to use checkForEvent below, but you can also get the status of any special key at any time with : - @Cpp static bool TCODConsole::isKeyPressed(TCOD_keycode_t key) - @C bool TCOD_console_is_key_pressed(TCOD_keycode_t key) - @Py console_is_key_pressed(key) - @C# static bool TCODConsole::isKeyPressed(TCODKeyCode key) - @Lua tcod.console.isKeyPressed(key) - @Param key Any key code defined in keycode_t except TCODK_CHAR (Char) and TCODK_NONE (NoKey) - */ - static bool isKeyPressed(TCOD_keycode_t key); - - /** - @PageName console_key_t - @PageTitle Keyboard event structure - @PageFather console_input - @PageDesc This structure contains information about a key pressed/released by the user. - @C - typedef struct { - TCOD_keycode_t vk; - char c; - char text[32]; - bool pressed; - bool lalt; - bool lctrl; - bool lmeta; - bool ralt; - bool rctrl; - bool rmeta; - bool shift; - } TCOD_key_t; - @Lua - key.KeyCode - key.Character - key.Text - key.Pressed - key.LeftAlt - key.LeftControl - key.LeftMeta - key.RightAlt - key.RightControl - key.RightMeta - key.Shift - @Param vk An arbitrary value representing the physical key on the keyboard. Possible values are stored in the TCOD_keycode_t enum. If no key was pressed, the value is TCODK_NONE - @Param c If the key correspond to a printable character, the character is stored in this field. Else, this field contains 0. - @Param text If vk is TCODK_TEXT, this will contain the text entered by the user. - @Param pressed true if the event is a key pressed, or false for a key released. - @Param lalt This field represents the status of the left Alt key : true => pressed, false => released. - @Param lctrl This field represents the status of the left Control key : true => pressed, false => released. - @Param lmeta This field represents the status of the left Meta (Windows/Command/..) key : true => pressed, false => released. - @Param ralt This field represents the status of the right Alt key : true => pressed, false => released. - @Param rctrl This field represents the status of the right Control key : true => pressed, false => released. - @Param rmeta This field represents the status of the right Meta (Windows/Command/..) key : true => pressed, false => released. - @Param shift This field represents the status of the shift key : true => pressed, false => released. - */ - - /** - @PageName console_mouse_t - @PageTitle Mouse event structure - @PageFather console_input - @PageDesc This structure contains information about a mouse move/press/release event. - @C - typedef struct { - int x,y; - int dx,dy; - int cx,cy; - int dcx,dcy; - bool lbutton; - bool rbutton; - bool mbutton; - bool lbutton_pressed; - bool rbutton_pressed; - bool mbutton_pressed; - bool wheel_up; - bool wheel_down; - } TCOD_mouse_t; - @Param x,y Absolute position of the mouse cursor in pixels relative to the window top-left corner. - @Param dx,dy Movement of the mouse cursor since the last call in pixels. - @Param cx,cy Coordinates of the console cell under the mouse cursor (pixel coordinates divided by the font size). - @Param dcx,dcy Movement of the mouse since the last call in console cells (pixel coordinates divided by the font size). - @Param lbutton true if the left button is pressed. - @Param rbutton true if the right button is pressed. - @Param mbutton true if the middle button (or the wheel) is pressed. - @Param lbutton_pressed true if the left button was pressed and released. - @Param rbutton_pressed true if the right button was pressed and released. - @Param mbutton_pressed true if the middle button was pressed and released. - @Param wheel_up true if the wheel was rolled up. - @Param wheel_down true if the wheel was rolled down. - */ - - /** - @PageName console_keycode_t - @PageTitle Key codes - @PageFather console_input - @PageDesc TCOD_keycode_t is a libtcod specific code representing a key on the keyboard. - For Python, replace TCODK by KEY: libtcod.KEY_NONE. C# and Lua, the value is in parenthesis. Possible values are : - When no key was pressed (see checkForEvent) : TCOD_NONE (NoKey) - Special keys : - TCODK_ESCAPE (Escape) - TCODK_BACKSPACE (Backspace) - TCODK_TAB (Tab) - TCODK_ENTER (Enter) - TCODK_SHIFT (Shift) - TCODK_CONTROL (Control) - TCODK_ALT (Alt) - TCODK_PAUSE (Pause) - TCODK_CAPSLOCK (CapsLock) - TCODK_PAGEUP (PageUp) - TCODK_PAGEDOWN (PageDown) - TCODK_END (End) - TCODK_HOME (Home) - TCODK_UP (Up) - TCODK_LEFT (Left) - TCODK_RIGHT (Right) - TCODK_DOWN (Down) - TCODK_PRINTSCREEN (Printscreen) - TCODK_INSERT (Insert) - TCODK_DELETE (Delete) - TCODK_LWIN (Lwin) - TCODK_RWIN (Rwin) - TCODK_APPS (Apps) - TCODK_KPADD (KeypadAdd) - TCODK_KPSUB (KeypadSubtract) - TCODK_KPDIV (KeypadDivide) - TCODK_KPMUL (KeypadMultiply) - TCODK_KPDEC (KeypadDecimal) - TCODK_KPENTER (KeypadEnter) - TCODK_F1 (F1) - TCODK_F2 (F2) - TCODK_F3 (F3) - TCODK_F4 (F4) - TCODK_F5 (F5) - TCODK_F6 (F6) - TCODK_F7 (F7) - TCODK_F8 (F8) - TCODK_F9 (F9) - TCODK_F10 (F10) - TCODK_F11 (F11) - TCODK_F12 (F12) - TCODK_NUMLOCK (Numlock) - TCODK_SCROLLLOCK (Scrolllock) - TCODK_SPACE (Space) - - numeric keys : - - TCODK_0 (Zero) - TCODK_1 (One) - TCODK_2 (Two) - TCODK_3 (Three) - TCODK_4 (Four) - TCODK_5 (Five) - TCODK_6 (Six) - TCODK_7 (Seven) - TCODK_8 (Eight) - TCODK_9 (Nine) - TCODK_KP0 (KeypadZero) - TCODK_KP1 (KeypadOne) - TCODK_KP2 (KeypadTwo) - TCODK_KP3 (KeypadThree) - TCODK_KP4 (KeypadFour) - TCODK_KP5 (KeypadFive) - TCODK_KP6 (KeypadSix) - TCODK_KP7 (KeypadSeven) - TCODK_KP8 (KeypadEight) - TCODK_KP9 (KeypadNine) - - Any other (printable) key : - - TCODK_CHAR (Char) - - Codes starting with TCODK_KP represents keys on the numeric keypad (if available). - */ - - /** - @PageName console_offscreen - @PageFather console - @PageTitle Using off-screen consoles - @PageDesc The offscreen consoles allow you to draw on secondary consoles as you would do with the root console. You can then blit those secondary consoles on the root console. This allows you to use local coordinate space while rendering a portion of the final screen, and easily move components of the screen without modifying the rendering functions. - @FuncTitle Creating an offscreen console - @FuncDesc You can create as many off-screen consoles as you want by using this function. You can draw on them as you would do with the root console, but you cannot flush them to the screen. Else, you can blit them on other consoles, including the root console. See blit. The C version of this function returns a console handler that you can use in most console drawing functions. - @Cpp TCODConsole::TCODConsole(int w, int h) - @C TCOD_console_t TCOD_console_new(int w, int h) - @Py console_new(w,h) - @C# TCODConsole::TCODConsole(int w, int h) - @Lua tcod.Console(w,h) - @Param w,h the console size. - 0 < w - 0 < h - @CppEx - // Creating a 40x20 offscreen console, filling it with red and blitting it on the root console at position 5,5 - TCODConsole *offscreenConsole = new TCODConsole(40,20); - offscreenConsole->setDefaultBackground(TCODColor::red); - offscreenConsole->clear(); - TCODConsole::blit(offscreenConsole,0,0,40,20,TCODConsole::root,5,5,255); - @CEx - TCOD_console_t offscreen_console = TCOD_console_new(40,20); - TCOD_console_set_default_background(offscreen_console,TCOD_red); - TCOD_console_clear(offscreen_console); - TCOD_console_blit(offscreen_console,0,0,40,20,NULL,5,5,255); - @PyEx - offscreen_console = libtcod.console_new(40,20) - libtcod.console_set_background_color(offscreen_console,libtcod.red) - libtcod.console_clear(offscreen_console) - libtcod.console_blit(offscreen_console,0,0,40,20,0,5,5,255) - @LuaEx - -- Creating a 40x20 offscreen console, filling it with red and blitting it on the root console at position 5,5 - offscreenConsole = tcod.Console(40,20) - offscreenConsole:setBackgroundColor(tcod.color.red) - offscreenConsole:clear() - tcod.console.blit(offscreenConsole,0,0,40,20,libtcod.TCODConsole_root,5,5,255) - */ - TCODConsole(int w, int h); - - /** - @PageName console_offscreen - @FuncTitle Creating an offscreen console from a .asc or .apf file - @FuncDesc You can create an offscreen console from a file created with Ascii Paint with this constructor - @Cpp TCODConsole::TCODConsole(const char *filename) - @C TCOD_console_t TCOD_console_from_file(const char *filename) - @Param filename path to the .asc or .apf file created with Ascii Paint - @CppEx - // Creating an offscreen console, filling it with data from the .asc file - TCODConsole *offscreenConsole = new TCODConsole("myfile.asc"); - @CEx - TCOD_console_t offscreen_console = TCOD_console_from_file("myfile.apf"); - */ - TCODConsole(const char *filename); - - /** - @PageName console_offscreen - @FuncTitle Loading an offscreen console from a .asc file - @FuncDesc You can load data from a file created with Ascii Paint with this function. When needed, the console will be resized to fit the file size. The function returns false if it couldn't read the file. - @Cpp bool TCODConsole::loadAsc(const char *filename) - @C bool TCOD_console_load_asc(TCOD_console_t con, const char *filename) - @Param con in the C and Python versions, the offscreen console handler - @Param filename path to the .asc file created with Ascii Paint - @CppEx - // Creating a 40x20 offscreen console - TCODConsole *offscreenConsole = new TCODConsole(40,20); - // possibly resizing it and filling it with data from the .asc file - offscreenConsole->loadAsc("myfile.asc"); - @CEx - TCOD_console_t offscreen_console = TCOD_console_new(40,20); - TCOD_console_load_asc(offscreen_console,"myfile.asc"); - */ - bool loadAsc(const char *filename); - /** - @PageName console_offscreen - @FuncTitle Loading an offscreen console from a .apf file - @FuncDesc You can load data from a file created with Ascii Paint with this function. When needed, the console will be resized to fit the file size. The function returns false if it couldn't read the file. - @Cpp bool TCODConsole::loadApf(const char *filename) - @C bool TCOD_console_load_apf(TCOD_console_t con, const char *filename) - @Param con in the C and Python versions, the offscreen console handler - - @Param filename path to the .apf file created with Ascii Paint - - @CppEx - // Creating a 40x20 offscreen console - TCODConsole *offscreenConsole = new TCODConsole(40,20); - // possibly resizing it and filling it with data from the .apf file - offscreenConsole->loadApf("myfile.apf"); - @CEx - TCOD_console_t offscreen_console = TCOD_console_new(40,20); - TCOD_console_load_apf(offscreen_console,"myfile.asc"); - */ - bool loadApf(const char *filename); - - /** - @PageName console_offscreen - @FuncTitle Saving a console to a .asc file - @FuncDesc You can save data from a console to Ascii Paint format with this function. The function returns false if it couldn't write the file. This is the only ASC function that works also with the root console ! - @Cpp bool TCODConsole::saveAsc(const char *filename) const - @C bool TCOD_console_save_asc(TCOD_console_t con, const char *filename) - @Param con in the C and Python versions, the offscreen console handler or NULL for the root console - @Param filename path to the .asc file to be created - @CppEx - console->saveAsc("myfile.asc"); - @CEx - TCOD_console_save_asc(console,"myfile.asc"); - */ - bool saveAsc(const char *filename) const; - - /** - @PageName console_offscreen - @FuncTitle Saving a console to a .apf file - @FuncDesc You can save data from a console to Ascii Paint format with this function. The function returns false if it couldn't write the file. This is the only ASC function that works also with the root console ! - @Cpp bool TCODConsole::saveApf(const char *filename) const - @C bool TCOD_console_save_apf(TCOD_console_t con, const char *filename) - @Param con in the C and Python versions, the offscreen console handler or NULL for the root console - @Param filename path to the .apf file to be created - @CppEx - console->saveApf("myfile.apf"); - @CEx - TCOD_console_save_apf(console,"myfile.apf"); - */ - bool saveApf(const char *filename) const; - - bool loadXp(const char *filename) { - return TCOD_console_load_xp(data, filename) != 0; - } - bool saveXp(const char *filename, int compress_level) { - return TCOD_console_save_xp(data, filename, compress_level) != 0; - } - - /** - @PageName console_offscreen - @FuncTitle Blitting a console on another one - @FuncDesc This function allows you to blit a rectangular area of the source console at a specific position on a destination console. It can also simulate alpha transparency with the fade parameter. - @Cpp static void blit(const TCODConsole *src,int xSrc, int ySrc, int wSrc, int hSrc, TCODConsole *dst, int xDst, int yDst, float foregroundAlpha=1.0f, float backgroundAlpha=1.0f) - @C void TCOD_console_blit(TCOD_console_t src,int xSrc, int ySrc, int wSrc, int hSrc, TCOD_console_t dst, int xDst, int yDst, float foreground_alpha, float background_alpha) - @Py console_blit(src,xSrc,ySrc,xSrc,hSrc,dst,xDst,yDst,foregroundAlpha=1.0,backgroundAlpha=1.0) - @C# - static void TCODConsole::blit(TCODConsole src, int xSrc, int ySrc, int wSrc, int hSrc, TCODConsole dst, int xDst, int yDst) - static void TCODConsole::blit(TCODConsole src, int xSrc, int ySrc, int wSrc, int hSrc, TCODConsole dst, int xDst, int yDst, float foreground_alpha) - static void TCODConsole::blit(TCODConsole src, int xSrc, int ySrc, int wSrc, int hSrc, TCODConsole dst, int xDst, int yDst, float foreground_alpha, float background_alpha) - @Lua - tcod.console.blit(src, xSrc, ySrc, wSrc, hSrc, dst, xDst, yDst) - tcod.console.blit(src, xSrc, ySrc, wSrc, hSrc, dst, xDst, yDst, foreground_alpha) - tcod.console.blit(src, xSrc, ySrc, wSrc, hSrc, dst, xDst, yDst, foreground_alpha, background_alpha) - @Param src The source console that must be blitted on another one. - @Param xSrc,ySrc,wSrc,hSrc The rectangular area of the source console that will be blitted. If wSrc and/or hSrc == 0, the source console width/height are used - @Param dst The destination console. - @Param xDst,yDst Where to blit the upper-left corner of the source area in the destination console. - @Param foregroundAlpha,backgroundAlpha Alpha transparency of the blitted console. - 0.0 => The source console is completely transparent. This function does nothing. - 1.0 => The source console is opaque. Its cells replace the destination cells. - 0 < fade < 1.0 => The source console is partially blitted, simulating real transparency. - @CppEx - // Cross-fading between two offscreen consoles. We use two offscreen consoles with the same size as the root console. We render a different screen on each offscreen console. When the user hits a key, we do a cross-fading from the first screen to the second screen. - TCODConsole *off1 = new TCODConsole(80,50); - TCODConsole *off2 = new TCODConsole(80,50); - ... print screen1 on off1 - ... print screen2 of off2 - // render screen1 in the game window - TCODConsole::blit(off1,0,0,80,50,TCODConsole::root,0,0); - TCODConsole::flush(); - // wait or a keypress - TCODConsole::waitForKeypress(true); - // do a cross-fading from off1 to off2 - for (int i=1; i <= 255; i++) { - TCODConsole::blit(off1,0,0,80,50,TCODConsole::root,0,0); // renders the first screen (opaque) - TCODConsole::blit(off2,0,0,80,50,TCODConsole::root,0,0,i/255.0,i/255.0); // renders the second screen (transparent) - TCODConsole::flush(); - } - @CEx - TCOD_console_t off1 = TCOD_console_new(80,50); - TCOD_console_t off2 = TCOD_console_new(80,50); - int i; - ... print screen1 on off1 - ... print screen2 of off2 - // render screen1 in the game window - TCOD_console_blit(off1,0,0,80,50,NULL,0,0,1.0,1.0); - TCOD_console_flush(); - // wait or a keypress - TCOD_console_wait_for_keypress(true); - // do a cross-fading from off1 to off2 - for (i=1; i <= 255; i++) { - TCOD_console_blit(off1,0,0,80,50,NULL,0,0,1.0,1.0); // renders the first screen (opaque) - TCOD_console_blit(off2,0,0,80,50,NULL,0,0,i/255.0,i/255.0); // renders the second screen (transparent) - TCOD_console_flush(); - } - @PyEx - off1 = libtcod.console_new(80,50) - off2 = libtcod.console_new(80,50) - ... print screen1 on off1 - ... print screen2 of off2 - # render screen1 in the game window - libtcod.console_blit(off1,0,0,80,50,0,0,0) - libtcod.console_flush() - # wait or a keypress - libtcod.console_wait_for_keypress(True) - # do a cross-fading from off1 to off2 - for i in range(1,256) : - litbcod.console_blit(off1,0,0,80,50,0,0,0) # renders the first screen (opaque) - litbcod.console_blit(off2,0,0,80,50,0,0,0,i/255.0,i/255.0) # renders the second screen (transparent) - litbcod.console_flush() - @LuaEx - -- Cross-fading between two offscreen consoles. We use two offscreen consoles with the same size as the root console. We render a different screen on each offscreen console. When the user hits a key, we do a cross-fading from the first screen to the second screen. - off1 = tcod.Console(80,50) - off2 = tcod.Console(80,50) - ... print screen1 on off1 - ... print screen2 of off2 - -- render screen1 in the game window - root=libtcod.TCODConsole_root - tcod.console.blit(off1,0,0,80,50,root,0,0) - tcod.console.flush() - -- wait or a keypress - tcod.console.waitForKeypress(true) - -- do a cross-fading from off1 to off2 - for i=1,255,1 do - tcod.console.blit(off1,0,0,80,50,root,0,0) -- renders the first screen (opaque) - tcod.console.blit(off2,0,0,80,50,root,0,0,i/255,i/255) -- renders the second screen (transparent) - tcod.console.flush() - end - */ - static void blit(const TCODConsole *src,int xSrc, int ySrc, int wSrc, int hSrc, TCODConsole *dst, int xDst, int yDst, float foreground_alpha=1.0f, float background_alpha=1.0f); - /** - @PageName console_offscreen - @FuncTitle Define a blit-transparent color - @FuncDesc This function defines a transparent background color for an offscreen console. All cells with this background color are ignored by the blit operation. You can use it to blit only some parts of the console. - @Cpp void TCODConsole::setKeyColor(const TCODColor &col) - @C void TCOD_console_set_key_color(TCOD_console_t con,TCOD_color_t col) - @Py console_set_key_color(con,col) - @C# void TCODConsole::setKeyColor(TCODColor col) - @Lua Console:setKeyColor(col) - @Param con in the C and Python versions, the offscreen console handler or NULL for the root console - @Param col the transparent background color - */ - void setKeyColor(const TCODColor &col); - /** - @PageName console_offscreen - @FuncTitle Destroying an offscreen console - @FuncDesc Use this function to destroy an offscreen console and release any resources allocated. Don't use it on the root console. - @Cpp TCODConsole::~TCODConsole() - @C void TCOD_console_delete(TCOD_console_t con) - @Py console_delete(con) - @C# void TCODConsole::Dispose() - @Lua through garbage collector - @Param con in the C and Python versions, the offscreen console handler - @CppEx - TCODConsole *off1 = new TCODConsole(80,50); - ... use off1 - delete off1; // destroy the offscreen console - @CEx - TCOD_console_t off1 = TCOD_console_new(80,50); - ... use off1 - TCOD_console_delete(off1); // destroy the offscreen console - @PyEx - off1 = libtcod.console_new(80,50) - ... use off1 - libtcod.console_delete(off1) # destroy the offscreen console - @LuaEx - off1 = tcod.Console(80,50) - ... use off1 - off1=nil -- release the reference - */ - virtual ~TCODConsole(); - - void setDirty(int x, int y, int w, int h); - - - TCODConsole(TCOD_console_t con) : data(con) {} - - // ctrl = TCOD_COLCTRL_1...TCOD_COLCTRL_5 or TCOD_COLCTRL_STOP - static const char *getColorControlString( TCOD_colctrl_t ctrl ); - // ctrl = TCOD_COLCTRL_FORE_RGB or TCOD_COLCTRL_BACK_RGB - static const char *getRGBColorControlString( TCOD_colctrl_t ctrl, const TCODColor & col ); - -protected : - friend class TCODImage; - friend class TCODZip; - friend class TCODText; - TCODConsole(); - TCOD_console_t data; -}; - -#endif /* TCOD_CONSOLE_SUPPORT */ - -#endif /* _TCOD_CONSOLE_HPP */ +/* +* libtcod +* Copyright (c) 2008-2018 Jice & Mingos & rmtew +* All rights reserved. +* +* Redistribution and use in source and binary forms, with or without +* modification, are permitted provided that the following conditions are met: +* * Redistributions of source code must retain the above copyright +* notice, this list of conditions and the following disclaimer. +* * Redistributions in binary form must reproduce the above copyright +* notice, this list of conditions and the following disclaimer in the +* documentation and/or other materials provided with the distribution. +* * The name of Jice or Mingos may not be used to endorse or promote +* products derived from this software without specific prior written +* permission. +* +* THIS SOFTWARE IS PROVIDED BY JICE, MINGOS AND RMTEW ``AS IS'' AND ANY +* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED +* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE +* DISCLAIMED. IN NO EVENT SHALL JICE, MINGOS OR RMTEW BE LIABLE FOR ANY +* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES +* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; +* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND +* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS +* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +*/ +#ifndef _TCOD_CONSOLE_HPP +#define _TCOD_CONSOLE_HPP + +#include + +#include "console.h" +#include "console_rexpaint.h" + +#ifdef TCOD_CONSOLE_SUPPORT + +#include "image.hpp" +#include "color.hpp" + +class TCODImage; +/** + @PageName console + @PageCategory Core + @PageTitle Console + @PageDesc The console emulator handles the rendering of the game screen and the keyboard input. +Classic real time game loop: + @Cpp + TCODConsole::initRoot(80,50,"my game",false); + TCODSystem::setFps(25); // limit framerate to 25 frames per second + while (!endGame && !TCODConsole::isWindowClosed()) { + TCOD_key_t key; + TCODSystem::checkForEvent(TCOD_EVENT_KEY_PRESS,&key,NULL); + updateWorld (key, TCODSystem::getLastFrameLength()); + // updateWorld(TCOD_key_t key, float elapsed) (using key if key.vk != TCODK_NONE) + // use elapsed to scale any update that is time dependent. + // ... draw world+GUI on TCODConsole::root + TCODConsole::flush(); + } + @Lua + tcod.console.initRoot(80,50,"my game", false) + root=libtcod.TCODConsole_root + tcod.system.setFps(25) + while not tcod.console.isWindowClosed() do + -- ... draw on root + tcod.console.flush() + key=tcod.console.checkForKeypress() + -- ... update world, using key and tcod.system.getLastFrameLength + end + +*/ +/** + @PageName console + @FuncDesc Classic turn by turn game loop: + @Cpp + TCODConsole::initRoot(80,50,"my game",false); + while (!endGame && !TCODConsole::isWindowClosed()) { + // ... draw on TCODConsole::root + TCODConsole::flush(); + TCOD_key_t key; + TCODConsole::waitForEvent(TCOD_EVENT_KEY_PRESS,&key,NULL,true); + //... update world, using key + } +*/ + +class TCODLIB_API TCODConsole { +public : + /** + @PageName console_init + @PageTitle Initializing the console + @PageFather console + */ + + static TCODConsole *root; + + /** + @PageName console_init_root + @PageTitle Creating the game window + @PageFather console_init + @Cpp static void TCODConsole::initRoot (int w, int h, const char * title, bool fullscreen = false, TCOD_renderer_t renderer = TCOD_RENDERER_SDL) + @C void TCOD_console_init_root (int w, int h, const char * title, bool fullscreen, TCOD_renderer_t renderer) + @Py console_init_root (w, h, title, fullscreen = False, renderer = RENDERER_SDL) + @C# + static void TCODConsole::initRoot(int w, int h, string title) + static void TCODConsole::initRoot(int w, int h, string title, bool fullscreen) + static void TCODConsole::initRoot(int w, int h, string title, bool fullscreen, TCODRendererType renderer) + @Lua + tcod.console.initRoot(w,h,title) -- fullscreen = false, renderer = SDL + tcod.console.initRoot(w,h,title,fullscreen) -- renderer = SDL + tcod.console.initRoot(w,h,title,fullscreen,renderer) + -- renderers : tcod.GLSL, tcod.OpenGL, tcod.SDL + @Param w,h size of the console(in characters). The default font in libtcod (./terminal.png) uses 8x8 pixels characters. + You can change the font by calling TCODConsole::setCustomFont before calling initRoot. + @Param title title of the window. It's not visible when you are in fullscreen. + Note 1 : you can dynamically change the window title with TCODConsole::setWindowTitle + @Param fullscreen whether you start in windowed or fullscreen mode. + Note 1 : you can dynamically change this mode with TCODConsole::setFullscreen + Note 2 : you can get current mode with TCODConsole::isFullscreen + @Param renderer which renderer to use. Possible values are : + * TCOD_RENDERER_GLSL : works only on video cards with pixel shaders + * TCOD_RENDERER_OPENGL : works on all video cards supporting OpenGL 1.4 + * TCOD_RENDERER_SDL : should work everywhere! + Note 1: if you select a renderer that is not supported by the player's machine, libtcod scan the lower renderers until it finds a working one. + Note 2: on recent video cards, GLSL results in up to 900% increase of framerates in the true color sample compared to SDL renderer. + Note 3: whatever renderer you use, it can always be overridden by the player through the libtcod.cfg file. + Note 4: you can dynamically change the renderer after calling initRoot with TCODSystem::setRenderer. + Note 5: you can get current renderer with TCODSystem::getRenderer. It might be different from the one you set in initRoot in case it's not supported on the player's computer. + @CppEx TCODConsole::initRoot(80, 50, "The Chronicles Of Doryen v0.1"); + @CEx TCOD_console_init_root(80, 50, "The Chronicles Of Doryen v0.1", false, TCOD_RENDERER_OPENGL); + @PyEx libtcod.console_init_root(80, 50, 'The Chronicles Of Doryen v0.1') + @LuaEx tcod.console.initRoot(80,50,"The Chronicles Of Doryen v0.1") + */ + static void initRoot(int w, int h, const char * title, bool fullscreen = false, TCOD_renderer_t renderer=TCOD_RENDERER_SDL); + + /** + @PageName console_set_custom_font + @PageTitle Using a custom bitmap font + @PageFather console_init + @FuncTitle setCustomFont + @FuncDesc This function allows you to use a bitmap font (png or bmp) with custom character size or layout. + It should be called before initializing the root console with initRoot. + Once this function is called, you can define your own custom mappings using mapping functions +
Different font layouts
+ + + + +
ASCII_INROWASCII_INCOLTCOD
+
    +
  • ascii, in columns : characters 0 to 15 are in the first column. The space character is at coordinates 2,0.
  • +
  • ascii, in rows : characters 0 to 15 are in the first row. The space character is at coordinates 0,2.
  • +
  • tcod : special mapping. Not all ascii values are mapped. The space character is at coordinates 0,0.
  • +
+
Different font types
+ + + + +
standard
(non antialiased)
antialiased
(32 bits PNG)
antialiased
(greyscale)
+
    +
  • standard : transparency is given by a key color automatically detected by looking at the color of the space character
  • +
  • 32 bits : transparency is given by the png alpha layer. The font color does not matter but it must be desaturated
  • +
  • greyscale : transparency is given by the pixel value. You can use white characters on black background or black characters on white background. The background color is automatically detected by looking at the color of the space character
  • +
+ Examples of fonts can be found in libtcod's fonts directory. Check the Readme file there. + @Cpp static void TCODConsole::setCustomFont(const char *fontFile, int flags=TCOD_FONT_LAYOUT_ASCII_INCOL,int nbCharHoriz=0, int nbCharVertic=0) + @C void TCOD_console_set_custom_font(const char *fontFile, int flags,int nb_char_horiz, int nb_char_vertic) + @Py console_set_custom_font(fontFile, flags=FONT_LAYOUT_ASCII_INCOL,nb_char_horiz=0, nb_char_vertic=0) + @C# + static void TCODConsole::setCustomFont(string fontFile) + static void TCODConsole::setCustomFont(string fontFile, int flags) + static void TCODConsole::setCustomFont(string fontFile, int flags, int nbCharHoriz) + static void TCODConsole::setCustomFont(string fontFile, int flags, int nbCharHoriz, int nbCharVertic) + @Lua + tcod.console.setCustomFont(fontFile) + tcod.console.setCustomFont(fontFile, flags) + tcod.console.setCustomFont(fontFile, nbCharHoriz) + tcod.console.setCustomFont(fontFile, flags, nbCharHoriz, nbCharVertic) + -- flags : tcod.LayoutAsciiInColumn, tcod.LayoutAsciiInRow, tcod.LayoutTCOD, tcod.Greyscale + @Param fontFile Name of a .bmp or .png file containing the font. + @Param flags Used to define the characters layout in the bitmap and the font type : + TCOD_FONT_LAYOUT_ASCII_INCOL : characters in ASCII order, code 0-15 in the first column + TCOD_FONT_LAYOUT_ASCII_INROW : characters in ASCII order, code 0-15 in the first row + TCOD_FONT_LAYOUT_TCOD : simplified layout. See examples below. + TCOD_FONT_TYPE_GREYSCALE : create an anti-aliased font from a greyscale bitmap + For Python, remove TCOD _ : + libtcod.FONT_LAYOUT_ASCII_INCOL + @Param nbCharHoriz,nbCharVertic Number of characters in the font. + Should be 16x16 for ASCII layouts, 32x8 for TCOD layout. + But you can use any other layout. + If set to 0, there are deduced from the font layout flag. + @CppEx + TCODConsole::setCustomFont("standard_8x8_ascii_in_col_font.bmp",TCOD_FONT_LAYOUT_ASCII_INCOL); + TCODConsole::setCustomFont("32bits_8x8_ascii_in_row_font.png",TCOD_FONT_LAYOUT_ASCII_INROW); + TCODConsole::setCustomFont("greyscale_8x8_tcod_font.png",TCOD_FONT_LAYOUT_TCOD | TCOD_FONT_TYPE_GREYSCALE); + @CEx + TCOD_console_set_custom_font("standard_8x8_ascii_in_col_font.bmp",TCOD_FONT_LAYOUT_ASCII_INCOL,16,16); + TCOD_console_set_custom_font("32bits_8x8_ascii_in_row_font.png",TCOD_FONT_LAYOUT_ASCII_INROW,32,8); + TCOD_console_set_custom_font("greyscale_8x8_tcod_font.png",TCOD_FONT_LAYOUT_TCOD | TCOD_FONT_TYPE_GREYSCALE,32,8); + @PyEx + libtcod.console_set_custom_font("standard_8x8_ascii_in_col_font.bmp",libtcod.FONT_LAYOUT_ASCII_INCOL) + libtcod.console_set_custom_font("32bits_8x8_ascii_in_row_font.png",libtcod.FONT_LAYOUT_ASCII_INROW) + libtcod.console_set_custom_font("greyscale_8x8_tcod_font.png",libtcod.FONT_LAYOUT_TCOD | libtcod.FONT_TYPE_GREYSCALE) + @LuaEx + tcod.console.setCustomFont("standard_8x8_ascii_in_col_font.bmp",tcod.LayoutAsciiInColumn); + tcod.console.setCustomFont("32bits_8x8_ascii_in_row_font.png",tcod.LayoutAsciiInRow); + tcod.console.setCustomFont("greyscale_8x8_tcod_font.png",tcod.LayoutTCOD + tcod.Greyscale); + */ + static void setCustomFont(const char *fontFile, int flags=TCOD_FONT_LAYOUT_ASCII_INCOL,int nbCharHoriz=0, int nbCharVertic=0); + + /** + @PageName console_map + @PageTitle Using custom characters mapping + @PageFather console_init + @FuncTitle Mapping a single ASCII code to a character + @PageDesc These functions allow you to map characters in the bitmap font to ASCII codes. + They should be called after initializing the root console with initRoot. + You can dynamically change the characters mapping at any time, allowing to use several fonts in the same screen. + @Cpp static void TCODConsole::mapAsciiCodeToFont(int asciiCode, int fontCharX, int fontCharY) + @C void TCOD_console_map_ascii_code_to_font(int asciiCode, int fontCharX, int fontCharY) + @Py console_map_ascii_code_to_font(asciiCode, fontCharX, fontCharY) + @C# static void TCODConsole::mapAsciiCodeToFont(int asciiCode, int fontCharX, int fontCharY) + @Lua tcod.console.mapAsciiCodeToFont(asciiCode, fontCharX, fontCharY) + @Param asciiCode ASCII code to map. + @Param fontCharX,fontCharY Coordinate of the character in the bitmap font (in characters, not pixels). + */ + static void mapAsciiCodeToFont(int asciiCode, int fontCharX, int fontCharY); + + /** + @PageName console_map + @FuncTitle Mapping consecutive ASCII codes to consecutive characters + @Cpp static void TCODConsole::mapAsciiCodesToFont(int firstAsciiCode, int nbCodes, int fontCharX, int fontCharY) + @C void TCOD_console_map_ascii_codes_to_font(int firstAsciiCode, int nbCodes, int fontCharX, int fontCharY) + @Py console_map_ascii_codes_to_font(firstAsciiCode, nbCodes, fontCharX, fontCharY) + @C# static void TCODConsole::mapAsciiCodesToFont(int firstAsciiCode, int nbCodes, int fontCharX, int fontCharY) + @Lua tcod.console.mapAsciiCodesToFont(firstAsciiCode, nbCodes, fontCharX, fontCharY) + @Param firstAsciiCode first ASCII code to map + @Param nbCodes number of consecutive ASCII codes to map + @Param fontCharX,fontCharY coordinate of the character in the bitmap font (in characters, not pixels) corresponding to the first ASCII code + */ + static void mapAsciiCodesToFont(int firstAsciiCode, int nbCodes, int fontCharX, int fontCharY); + + /** + @PageName console_map + @FuncTitle Mapping ASCII code from a string to consecutive characters + @Cpp static void TCODConsole::mapStringToFont(const char *s, int fontCharX, int fontCharY) + @C void TCOD_console_map_string_to_font(const char *s, int fontCharX, int fontCharY) + @Py console_map_string_to_font(s, fontCharX, fontCharY) + @C# static void TCODConsole::mapStringToFont(string s, int fontCharX, int fontCharY) + @Lua tcod.console.mapStringToFont(s, fontCharX, fontCharY) + @Param s string containing the ASCII codes to map + @Param fontCharX,fontCharY coordinate of the character in the bitmap font (in characters, not pixels) corresponding to the first ASCII code in the string + */ + static void mapStringToFont(const char *s, int fontCharX, int fontCharY); + + /** + @PageName console_fullscreen + @PageTitle Fullscreen mode + @PageFather console_init + @FuncTitle Getting the current mode + @FuncDesc This function returns true if the current mode is fullscreen. + @Cpp static bool TCODConsole::isFullscreen() + @C bool TCOD_console_is_fullscreen() + @Py console_is_fullscreen() + @C# static bool TCODConsole::isFullscreen() + @Lua tcod.console.isFullscreen() + */ + static bool isFullscreen(); + /** + @PageName console_fullscreen + @FuncTitle Switching between windowed and fullscreen modes + @FuncDesc This function switches the root console to fullscreen or windowed mode. + Note that there is no predefined key combination to switch to/from fullscreen. You have to do this in your own code. + @Cpp static void TCODConsole::setFullscreen(bool fullscreen) + @C void TCOD_console_set_fullscreen(bool fullscreen) + @Py console_set_fullscreen(fullscreen) + @C# static void TCODConsole::setFullscreen(bool fullscreen) + @Lua tcod.console.setFullscreen(fullscreen) + @Param fullscreen true to switch to fullscreen mode. + false to switch to windowed mode. + @CppEx + TCOD_key_t key; + TCODConsole::checkForEvent(TCOD_EVENT_KEY_PRESS,&key,NULL); + if ( key.vk == TCODK_ENTER && key.lalt ) + TCODConsole::setFullscreen(!TCODConsole::isFullscreen()); + @CEx + TCOD_key_t key; + TCOD_console_check_for_event(TCOD_EVENT_KEY_PRESS,&key,NULL); + if ( key.vk == TCODK_ENTER && key.lalt ) + TCOD_console_set_fullscreen(!TCOD_console_is_fullscreen()); + @PyEx + key=Key() + libtcod.console_check_for_event(libtcod.EVENT_KEY_PRESS,key,0) + if key.vk == libtcod.KEY_ENTER and key.lalt : + libtcod.console_set_fullscreen(not libtcod.console_is_fullscreen()) + @LuaEx + key=tcod.console.checkForKeypress() + if key.KeyCode == tcod.Enter and key.LeftAlt then + tcod.console.setFullscreen(not tcod.console.isFullscreen()) + end + */ + static void setFullscreen(bool fullscreen); + + /** + @PageName console_window + @PageFather console_init + @PageTitle Communicate with the window manager + @FuncTitle Changing the window title + @FuncDesc This function dynamically changes the title of the game window. + Note that the window title is not visible while in fullscreen. + @Cpp static void TCODConsole::setWindowTitle(const char *title) + @C void TCOD_console_set_window_title(const char *title) + @Py console_set_window_title(title) + @C# static void TCODConsole::setWindowTitle(string title) + @Lua tcod.console.setWindowTitle(title) + @Param title New title of the game window + */ + static void setWindowTitle(const char *title); + + /** + @PageName console_window + @FuncTitle Handling "close window" events + @FuncDesc When you start the program, this returns false. Once a "close window" event has been sent by the window manager, it will always return true. You're supposed to exit cleanly the game. + @Cpp static bool TCODConsole::isWindowClosed() + @C bool TCOD_console_is_window_closed() + @Py console_is_window_closed() + @C# static bool TCODConsole::isWindowClosed() + @Lua tcod.console.isWindowClosed() + */ + static bool isWindowClosed(); + + /** + @PageName console_window + @FuncTitle Check if the mouse cursor is inside the game window + @FuncDesc Returns true if the mouse cursor is inside the game window area and the game window is the active application. + @Cpp static bool TCODConsole::hasMouseFocus() + @C bool TCOD_console_has_mouse_focus() + @Py console_has_mouse_focus() + */ + static bool hasMouseFocus(); + + /** + @PageName console_window + @FuncTitle Check if the game application is active + @FuncDesc Returns false if the game window is not the active window or is iconified. + @Cpp static bool TCODConsole::isActive() + @C bool TCOD_console_is_active() + @Py console_is_active() + */ + static bool isActive(); + + /** + @PageName console_credits + @PageTitle libtcod's credits + @PageFather console_init + @PageDesc Use these functions to display credits, as seen in the samples. + @FuncTitle Using a separate credit page + @FuncDesc You can print a "Powered by libtcod x.y.z" screen during your game startup simply by calling this function after initRoot. + The credits screen can be skipped by pressing any key. + @Cpp static void TCODConsole::credits() + @C void TCOD_console_credits() + @Py console_credits() + @C# static void TCODConsole::credits() + @Lua tcod.console.credits() + */ + static void credits(); + + /** + @PageName console_credits + @FuncTitle Embedding credits in an existing page + @FuncDesc You can also print the credits on one of your game screens (your main menu for example) by calling this function in your main loop. + This function returns true when the credits screen is finished, indicating that you no longer need to call it. + @Cpp static bool TCODConsole::renderCredits(int x, int y, bool alpha) + @C bool TCOD_console_credits_render(int x, int y, bool alpha) + @Py bool TCOD_console_credits_render(int x, int y, bool alpha) + @C# static bool TCODConsole::renderCredits(int x, int y, bool alpha) + @Lua tcod.console.renderCredits(x, y, alpha) + @Param x,y Position of the credits text in your root console + @Param alpha If true, credits are transparently added on top of the existing screen. + For this to work, this function must be placed between your screen rendering code and the console flush. + @CppEx + TCODConsole::initRoot(80,50,"The Chronicles Of Doryen v0.1",false); // initialize the root console + bool endCredits=false; + while ( ! TCODConsole::isWindowClosed() ) { // your game loop + // your game rendering here... + // render transparent credits near the center of the screen + if (! endCredits ) endCredits=TCODConsole::renderCredits(35,25,true); + TCODConsole::flush(); + } + @CEx + TCOD_console_init_root(80,50,"The Chronicles Of Doryen v0.1",false); + bool end_credits=false; + while ( ! TCOD_console_is_window_closed() ) { + // your game rendering here... + // render transparent credits near the center of the screen + if (! end_credits ) end_credits=TCOD_console_credits_render(35,25,true); + TCOD_console_flush(); + } + @PyEx + libtcod.console_init_root(80,50,"The Chronicles Of Doryen v0.1",False) + end_credits=False + while not libtcod.console_is_window_closed() : + // your game rendering here... + // render transparent credits near the center of the screen + if (not end_credits ) : end_credits=libtcod.console_credits_render(35,25,True) + libtcod.console_flush() + @LuaEx + tcod.console.initRoot(80,50,"The Chronicles Of Doryen v0.1") -- initialize the root console + endCredits=false + while not tcod.console.isWindowClosed() do -- your game loop + -- your game rendering here... + -- render transparent credits near the center of the screen + if not endCredits then endCredits=tcod.console.renderCredits(35,25,true) end + tcod.console.flush() + end + */ + static bool renderCredits(int x, int y, bool alpha); + + /** + @PageName console_credits + @FuncTitle Restart the credits animation + @FuncDesc When using rederCredits, you can restart the credits animation from the beginning before it's finished by calling this function. + @Cpp static void TCODConsole::resetCredits() + @C void TCOD_console_credits_reset() + @Py console_credits_reset() + @C# static void TCODConsole::resetCredits() + @Lua tcod.console.resetCredits() + */ + static void resetCredits(); + + /** + @PageName console_draw + @PageTitle Drawing on the root console + @PageFather console + */ + + /** + @PageName console_draw_basic + @PageTitle Basic printing functions + @PageFather console_draw + @FuncTitle Setting the default background color + @FuncDesc This function changes the default background color for a console. The default background color is used by several drawing functions like clear, putChar, ... + @Cpp void TCODConsole::setDefaultBackground(TCODColor back) + @C void TCOD_console_set_default_background(TCOD_console_t con,TCOD_color_t back) + @Py console_set_default_background(con,back) + @C# void TCODConsole::setBackgroundColor(TCODColor back) + @Lua Console:setBackgroundColor(back) + @Param con in the C and Python versions, the offscreen console handler or NULL for the root console + @Param back the new default background color for this console + @CppEx TCODConsole::root->setDefaultBackground(myColor) + @CEx TCOD_console_set_default_background(NULL, my_color) + @PyEx litbcod.console_set_default_background(0, my_color) + @Lua libtcod.TCODConsole_root:setBackgroundColor( myColor ) + */ + void setDefaultBackground(TCODColor back); + + /** + @PageName console_draw_basic + @FuncTitle Setting the default foreground color + @FuncDesc This function changes the default foreground color for a console. The default foreground color is used by several drawing functions like clear, putChar, ... + @Cpp void TCODConsole::setDefaultForeground(TCODColor fore) + @C void TCOD_console_set_default_foreground(TCOD_console_t con,TCOD_color_t fore) + @Py console_set_default_foreground(con, fore) + @C# void TCODConsole::setForegroundColor(TCODColor fore) + @Lua Console:setForegroundColor(fore) + @Param con in the C and Python versions, the offscreen console handler or NULL for the root console + @Param fore the new default foreground color for this console + @CppEx TCODConsole::root->setDefaultForeground(myColor) + @CEx TCOD_console_set_default_foreground(NULL, my_color) + @PyEx litbcod.console_set_default_foreground(0, my_color) + @LuaEx libtcod.TCODConsole_root:setForegroundColor( myColor ) + */ + void setDefaultForeground(TCODColor fore); + + /** + @PageName console_draw_basic + @FuncTitle Clearing a console + @FuncDesc This function modifies all cells of a console : + * set the cell's background color to the console default background color + * set the cell's foreground color to the console default foreground color + * set the cell's ASCII code to 32 (space) + @Cpp void TCODConsole::clear() + @C void TCOD_console_clear(TCOD_console_t con) + @Py console_clear(con) + @C# void TCODConsole::clear() + @Lua Console:clear() + @Param con in the C and Python versions, the offscreen console handler or NULL for the root console + */ + void clear(); + + /** + @PageName console_draw_basic + @FuncTitle Setting the background color of a cell + @FuncDesc This function modifies the background color of a cell, leaving other properties (foreground color and ASCII code) unchanged. + @Cpp void TCODConsole::setCharBackground(int x, int y, const TCODColor &col, TCOD_bkgnd_flag_t flag = TCOD_BKGND_SET) + @C void TCOD_console_set_char_background(TCOD_console_t con,int x, int y, TCOD_color_t col, TCOD_bkgnd_flag_t flag) + @Py console_set_char_background(con, x, y, col, flag=BKGND_SET) + @C# + void TCODConsole::setCharBackground(int x, int y, TCODColor col) + void TCODConsole::setCharBackground(int x, int y, TCODColor col, TCODBackgroundFlag flag) + @Lua + Console:setCharBackground(x, y, col) + Console:setCharBackground(x, y, col, flag) + @Param con in the C and Python versions, the offscreen console handler or NULL for the root console + @Param x,y coordinates of the cell in the console. + 0 <= x < console width + 0 <= y < console height + @Param col the background color to use. You can use color constants + @Param flag this flag defines how the cell's background color is modified. See TCOD_bkgnd_flag_t + */ + void setCharBackground(int x, int y, const TCODColor &col, TCOD_bkgnd_flag_t flag = TCOD_BKGND_SET); + /** + @PageName console_draw_basic + @FuncTitle Setting the foreground color of a cell + @FuncDesc This function modifies the foreground color of a cell, leaving other properties (background color and ASCII code) unchanged. + @Cpp void TCODConsole::setCharForeground(int x, int y, const TCODColor &col) + @C void TCOD_console_set_char_foreground(TCOD_console_t con,int x, int y, TCOD_color_t col) + @Py console_set_char_foreground(con, x, y, col) + @C# void TCODConsole::setCharForeground(int x, int y, TCODColor col) + @Lua Console:setCharForeground(x, y, col) + @Param con in the C and Python versions, the offscreen console handler or NULL for the root console + @Param x,y coordinates of the cell in the console. + 0 <= x < console width + 0 <= y < console height + @Param col the foreground color to use. You can use color constants + */ + void setCharForeground(int x, int y, const TCODColor &col); + + /** + @PageName console_draw_basic + @FuncTitle Setting the ASCII code of a cell + @FuncDesc This function modifies the ASCII code of a cell, leaving other properties (background and foreground colors) unchanged. + Note that since a clear console has both background and foreground colors set to black for every cell, using setchar will produce black characters on black background. Use putchar instead. + @Cpp void TCODConsole::setChar(int x, int y, int c) + @C void TCOD_console_set_char(TCOD_console_t con,int x, int y, int c) + @Py console_set_char(con, x, y, c) + @C# void TCODConsole::setChar(int x, int y, int c) + @Lua Console:setChar(x, y, c) + @Param con in the C and Python versions, the offscreen console handler or NULL for the root console + @Param x,y coordinates of the cell in the console. + 0 <= x < console width + 0 <= y < console height + @Param c the new ASCII code for the cell. You can use ASCII constants + */ + void setChar(int x, int y, int c); + + /** + @PageName console_draw_basic + @FuncTitle Setting every property of a cell using default colors + @FuncDesc This function modifies every property of a cell : + * update the cell's background color according to the console default background color (see TCOD_bkgnd_flag_t). + * set the cell's foreground color to the console default foreground color + * set the cell's ASCII code to c + @Cpp void TCODConsole::putChar(int x, int y, int c, TCOD_bkgnd_flag_t flag = TCOD_BKGND_DEFAULT) + @C void TCOD_console_put_char(TCOD_console_t con,int x, int y, int c, TCOD_bkgnd_flag_t flag) + @Py console_put_char( con, x, y, c, flag=BKGND_DEFAULT) + @C# + void TCODConsole::putChar(int x, int y, int c) + void TCODConsole::putChar(int x, int y, int c, TCODBackgroundFlag flag) + @Lua + Console:putChar(x, y, c) + Console:putChar(x, y, c, flag) + @Param con in the C and Python versions, the offscreen console handler or NULL for the root console + @Param x,y coordinates of the cell in the console. + 0 <= x < console width + 0 <= y < console height + @Param c the new ASCII code for the cell. You can use ASCII constants + @Param flag this flag defines how the cell's background color is modified. See TCOD_bkgnd_flag_t + */ + void putChar(int x, int y, int c, TCOD_bkgnd_flag_t flag = TCOD_BKGND_DEFAULT); + + /** + @PageName console_draw_basic + @FuncTitle Setting every property of a cell using specific colors + @FuncDesc This function modifies every property of a cell : + * set the cell's background color to back. + * set the cell's foreground color to fore. + * set the cell's ASCII code to c. + @Cpp void TCODConsole::putCharEx(int x, int y, int c, const TCODColor & fore, const TCODColor & back) + @C void TCOD_console_put_char_ex(TCOD_console_t con,int x, int y, int c, TCOD_color_t fore, TCOD_color_t back) + @Py console_put_char_ex( con, x, y, c, fore, back) + @C# void TCODConsole::putCharEx(int x, int y, int c, TCODColor fore, TCODColor back) + @Lua Console:putCharEx(x, y, c, fore, back) + @Param con in the C and Python versions, the offscreen console handler or NULL for the root console + @Param x,y coordinates of the cell in the console. + 0 <= x < console width + 0 <= y < console height + @Param c the new ASCII code for the cell. You can use ASCII constants + @Param fore,back new foreground and background colors for this cell + */ + void putCharEx(int x, int y, int c, const TCODColor &fore, const TCODColor &back); + + /** + @PageName console_bkgnd_flag_t + @PageTitle Background effect flags + @PageFather console_draw + @PageDesc This flag is used by most functions that modify a cell background color. It defines how the console's current background color is used to modify the cell's existing background color : + TCOD_BKGND_NONE : the cell's background color is not modified. + TCOD_BKGND_SET : the cell's background color is replaced by the console's default background color : newbk = curbk. + TCOD_BKGND_MULTIPLY : the cell's background color is multiplied by the console's default background color : newbk = oldbk * curbk + TCOD_BKGND_LIGHTEN : newbk = MAX(oldbk,curbk) + TCOD_BKGND_DARKEN : newbk = MIN(oldbk,curbk) + TCOD_BKGND_SCREEN : newbk = white - (white - oldbk) * (white - curbk) // inverse of multiply : (1-newbk) = (1-oldbk)*(1-curbk) + TCOD_BKGND_COLOR_DODGE : newbk = curbk / (white - oldbk) + TCOD_BKGND_COLOR_BURN : newbk = white - (white - oldbk) / curbk + TCOD_BKGND_ADD : newbk = oldbk + curbk + TCOD_BKGND_ADDALPHA(alpha) : newbk = oldbk + alpha*curbk + TCOD_BKGND_BURN : newbk = oldbk + curbk - white + TCOD_BKGND_OVERLAY : newbk = curbk.x <= 0.5 ? 2*curbk*oldbk : white - 2*(white-curbk)*(white-oldbk) + TCOD_BKGND_ALPHA(alpha) : newbk = (1.0f-alpha)*oldbk + alpha*(curbk-oldbk) + TCOD_BKGND_DEFAULT : use the console's default background flag + Note that TCOD_BKGND_ALPHA and TCOD_BKGND_ADDALPHA are MACROS that needs a float parameter between (0.0 and 1.0). TCOD_BKGND_ALPH and TCOD_BKGND_ADDA should not be used directly (else they will have the same effect as TCOD_BKGND_NONE). + For Python, remove TCOD_ : libtcod.BKGND_NONE + For C# : None, Set, Multiply, Lighten, Darken, Screen, ColodDodge, ColorBurn, Add, Burn Overlay, Default + With lua, use tcod.None, ..., tcod.Default, BUT tcod.console.Alpha(value) and tcod.console.AddAlpha(value) + */ + + /** + @PageName console_print + @PageTitle String drawing functions + @PageFather console_draw + @FuncTitle Setting the default background flag + @FuncDesc This function defines the background mode (see TCOD_bkgnd_flag_t) for the console. + This default mode is used by several functions (print, printRect, ...) + @Cpp void TCODConsole::setBackgroundFlag(TCOD_bkgnd_flag_t flag) + @C void TCOD_console_set_background_flag(TCOD_console_t con,TCOD_bkgnd_flag_t flag) + @Py console_set_background_flag(con, flag) + @C# void TCODConsole::setBackgroundFlag(TCODBackgroundFlag flag) + @Lua Console:setBackgroundFlag(flag) + @Param con in the C and Python versions, the offscreen console handler or NULL for the root console + @Param flag this flag defines how the cell's background color is modified. See TCOD_bkgnd_flag_t + */ + void setBackgroundFlag(TCOD_bkgnd_flag_t flag); + + /** + @PageName console_print + @FuncTitle Getting the default background flag + @FuncDesc This function returns the background mode (see TCOD_bkgnd_flag_t) for the console. + This default mode is used by several functions (print, printRect, ...) + @Cpp TCOD_bkgnd_flag_t TCODConsole::getBackgroundFlag() const + @C TCOD_bkgnd_flag_t TCOD_console_get_background_flag(TCOD_console_t con) + @Py console_get_background_flag(con) + @C# TCODBackgroundFlag TCODConsole::getBackgroundFlag() + @Lua Console:getBackgroundFlag() + @Param con in the C and Python versions, the offscreen console handler or NULL for the root console + */ + TCOD_bkgnd_flag_t getBackgroundFlag() const; + + /** + @PageName console_print + @FuncTitle Setting the default alignment + @FuncDesc This function defines the default alignment (see TCOD_alignment_t) for the console. + This default alignment is used by several functions (print, printRect, ...). + Values for alignment : TCOD_LEFT, TCOD_CENTER, TCOD_RIGHT (in Python, remove TCOD_ : libtcod.LEFT). + For C# and Lua : LeftAlignment, RightAlignment, CenterAlignment + @Cpp void TCODConsole::setAlignment(TCOD_alignment_t alignment) + @C void TCOD_console_set_alignment(TCOD_console_t con,TCOD_bkgnd_flag_t alignment) + @Py console_set_alignment(con, alignment) + @C# void TCODConsole::setAlignment(TCODAlignment alignment) + @Lua Console:setAlignment(alignment) + @Param con in the C and Python versions, the offscreen console handler or NULL for the root console + @Param alignment defines how the strings are printed on screen. + */ + void setAlignment(TCOD_alignment_t alignment); + + /** + @PageName console_print + @FuncTitle Getting the default alignment + @FuncDesc This function returns the default alignment (see TCOD_alignment_t) for the console. + This default mode is used by several functions (print, printRect, ...). + Values for alignment : TCOD_LEFT, TCOD_CENTER, TCOD_RIGHT (in Python, remove TCOD_ : libtcod.LEFT). + For C# and Lua : LeftAlignment, RightAlignment, CenterAlignment + @Cpp TCOD_alignment_t TCODConsole::getAlignment() const + @C TCOD_alignment_t TCOD_console_get_alignment(TCOD_console_t con) + @Py console_get_alignment(con) + @C# TCODAlignment TCODConsole::getAlignment() + @Lua Console:getAlignment() + @Param con in the C and Python versions, the offscreen console handler or NULL for the root console + */ + TCOD_alignment_t getAlignment() const; + /** + * Print an EASCII formatted string to the console. + * /rst + * .. deprecated:: 1.8 + * EASCII is being phased out. Use TCODConsole::printf or one of the + * UTF-8 overloads. + * /endrst + */ + TCOD_DEPRECATED("Use TCODConsole::printf or the std::string overload for" + " this function.") + void print(int x, int y, const char *fmt, ...); + /** + * Print a UTF-8 string to the console. + * + * This method will use this consoles default alignment, blend mode, and + * colors. + * /rst + * .. versionadded:: 1.8 + * /endrst + */ + void print(int x, int y, const std::string &str); + /** + * Print a UTF-8 string to the console with specific alignment and blend + * mode. + * /rst + * .. versionadded:: 1.8 + * /endrst + */ + void print(int x, int y, const std::string &str, + TCOD_alignment_t alignment, TCOD_bkgnd_flag_t flag); + /** + * Format and print a UTF-8 string to the console. + * + * This method will use this consoles default alignment, blend mode, and + * colors. + * /rst + * .. versionadded:: 1.8 + * /endrst + */ + void printf(int x, int y, const char *fmt, ...); + /** + * Format and print a UTF-8 string to the console with specific alignment + * and blend mode. + * /rst + * .. versionadded:: 1.8 + * /endrst + */ + void printf(int x, int y, TCOD_bkgnd_flag_t flag, TCOD_alignment_t alignment, + const char *fmt, ...); + /** + * Print an EASCII formatted string to the console. + * /rst + * .. deprecated:: 1.8 + * Use `TCODConsole::print` or `TCODConsole::printf`. + * These functions have overloads for specifying flag and alignment. + * /endrst + */ + TCOD_DEPRECATED("Use TCODConsole::print or TCODConsole::printf instead of" + " this function.") + void printEx(int x, int y, TCOD_bkgnd_flag_t flag, + TCOD_alignment_t alignment, const char *fmt, ...); + /** + @PageName console_print + @FuncTitle Printing a string with default parameters and autowrap + @FuncDesc This function draws a string in a rectangle inside the console, using default colors, alignment and background mode. + If the string reaches the borders of the rectangle, carriage returns are inserted. + If h > 0 and the bottom of the rectangle is reached, the string is truncated. If h = 0, the string is only truncated if it reaches the bottom of the console. + The function returns the height (number of console lines) of the printed string. + @Cpp int TCODConsole::printRect(int x, int y, int w, int h, const char *fmt, ...) + @C int TCOD_console_print_rect(TCOD_console_t con,int x, int y, int w, int h, const char *fmt, ...) + @Py console_print_rect(con, x, y, w, h, fmt) + @C# int TCODConsole::printRect(int x, int y, int w, int h, string fmt) + @Lua Console:printRect(x, y, w, h, fmt) + @Param con in the C and Python versions, the offscreen console handler or NULL for the root console + @Param x,y coordinate of the character in the console, depending on the alignment : + * TCOD_LEFT : leftmost character of the string + * TCOD_CENTER : center character of the string + * TCOD_RIGHT : rightmost character of the string + @Param w,h size of the rectangle + x <= x+w < console width + y <= y+h < console height + @Param fmt printf-like format string, eventually followed by parameters. You can use control codes to change the colors inside the string, except in C#. + */ + int printRect(int x, int y, int w, int h, const char *fmt, ...); + + /** + @PageName console_print + @FuncTitle Printing a string with specific alignment and background mode and autowrap + @FuncDesc This function draws a string in a rectangle inside the console, using default colors, but specific alignment and background mode. + If the string reaches the borders of the rectangle, carriage returns are inserted. + If h > 0 and the bottom of the rectangle is reached, the string is truncated. If h = 0, the string is only truncated if it reaches the bottom of the console. + The function returns the height (number of console lines) of the printed string. + @Cpp int TCODConsole::printRectEx(int x, int y, int w, int h, TCOD_bkgnd_flag_t flag, TCOD_alignment_t alignment, const char *fmt, ...) + @C int TCOD_console_print_rect_ex(TCOD_console_t con,int x, int y, int w, int h, TCOD_bkgnd_flag_t flag, TCOD_alignment_t alignment, const char *fmt, ...) + @Py console_print_rect_ex(con, x, y, w, h, flag, alignment, fmt) + @C# int TCODConsole::printRectEx(int x, int y, int w, int h, TCODBackgroundFlag flag, TCODAlignment alignment, string fmt) + @Lua Console:printRectEx(x, y, w, h, flag, alignment, fmt) + @Param con in the C and Python versions, the offscreen console handler or NULL for the root console + @Param x,y coordinate of the character in the console, depending on the alignment : + * TCOD_LEFT : leftmost character of the string + * TCOD_CENTER : center character of the string + * TCOD_RIGHT : rightmost character of the string + @Param w,h size of the rectangle + x <= x+w < console width + y <= y+h < console height + @Param flag this flag defines how the cell's background color is modified. See TCOD_bkgnd_flag_t + @Param alignment defines how the strings are printed on screen. + @Param fmt printf-like format string, eventually followed by parameters. You can use control codes to change the colors inside the string, except in C#. + */ + int printRectEx(int x, int y, int w, int h, TCOD_bkgnd_flag_t flag, TCOD_alignment_t alignment, const char *fmt, ...); + + /** + @PageName console_print + @FuncTitle Compute the height of an autowrapped string + @FuncDesc This function returns the expected height of an autowrapped string without actually printing the string with printRect or printRectEx + @Cpp int TCODConsole::getHeightRect(int x, int y, int w, int h, const char *fmt, ...) + + @C int TCOD_console_get_height_rect(TCOD_console_t con,int x, int y, int w, int h, const char *fmt, ...) + @Py console_get_height_rect(con, x, y, w, h, fmt) + @C# int TCODConsole::getHeightRect(int x, int y, int w, int h, string fmt) + @Lua Console:getHeightRect(x, y, w, h, fmt) + @Param con in the C and Python versions, the offscreen console handler or NULL for the root console + @Param x,y coordinate of the rectangle upper-left corner in the console + @Param w,h size of the rectangle + x <= x+w < console width + y <= y+h < console height + @Param fmt printf-like format string, eventually followed by parameters. You can use control codes to change the colors inside the string, except in C#. + */ + int getHeightRect(int x, int y, int w, int h, const char *fmt, ...); + + /** + @PageName console_print + @FuncTitle Changing the colors while printing a string + @FuncDesc If you want to draw a string using different colors for each word, the basic solution is to call a string printing function several times, changing the default colors between each call. + The TCOD library offers a simpler way to do this, allowing you to draw a string using different colors in a single call. For this, you have to insert color control codes in your string. + A color control code is associated with a color set (a foreground color and a background color). If you insert this code in your string, the next characters will use the colors associated with the color control code. + There are 5 predefined color control codes : + For Python, remove TCOD_ : libtcod.COLCTRL_1 + TCOD_COLCTRL_1 + TCOD_COLCTRL_2 + TCOD_COLCTRL_3 + TCOD_COLCTRL_4 + TCOD_COLCTRL_5 + To associate a color with a code, use setColorControl. + To go back to the console's default colors, insert in your string the color stop control code : + TCOD_COLCTRL_STOP + + You can also use any color without assigning it to a control code, using the generic control codes : + TCOD_COLCTRL_FORE_RGB + TCOD_COLCTRL_BACK_RGB + + Those controls respectively change the foreground and background color used to print the string characters. In the string, you must insert the r,g,b components of the color (between 1 and 255. The value 0 is forbidden because it represents the end of the string in C/C++) immediately after this code. + @Cpp static void TCODConsole::setColorControl(TCOD_colctrl_t con, const TCODColor &fore, const TCODColor &back) + @C void TCOD_console_set_color_control(TCOD_colctrl_t con, TCOD_color_t fore, TCOD_color_t back) + @Py console_set_color_control(con,fore,back) + @C# Not supported directly, use getRGBColorControlString and getColorControlString. + @Lua Not supported + @Param con the color control TCOD_COLCTRL_x, 1<=x<=5 + @Param fore foreground color when this control is activated + @Param back background color when this control is activated + @CppEx + // A string with a red over black word, using predefined color control codes + TCODConsole::setColorControl(TCOD_COLCTRL_1,TCODColor::red,TCODColor::black); + TCODConsole::root->print(1,1,"String with a %cred%c word.",TCOD_COLCTRL_1,TCOD_COLCTRL_STOP); + // A string with a red over black word, using generic color control codes + TCODConsole::root->print(1,1,"String with a %c%c%c%c%c%c%c%cred%c word.", + TCOD_COLCTRL_FORE_RGB,255,1,1,TCOD_COLCTRL_BACK_RGB,1,1,1,TCOD_COLCTRL_STOP); + // A string with a red over black word, using generic color control codes + TCODConsole::root->print(1,1,"String with a %c%c%c%c%c%c%c%cred%c word.", + TCOD_COLCTRL_FORE_RGB,255,1,1,TCOD_COLCTRL_BACK_RGB,1,1,1,TCOD_COLCTRL_STOP); + @CEx + // A string with a red over black word, using predefined color control codes + TCOD_console_set_color_control(TCOD_COLCTRL_1,red,black); + TCOD_console_print(NULL,1,1,"String with a %cred%c word.",TCOD_COLCTRL_1,TCOD_COLCTRL_STOP); + // A string with a red word (over default background color), using generic color control codes + TCOD_console_print(NULL,1,1,"String with a %c%c%c%cred%c word.", + TCOD_COLCTRL_FORE_RGB,255,1,1,TCOD_COLCTRL_STOP); + // A string with a red over black word, using generic color control codes + TCOD_console_print(NULL,1,1,"String with a %c%c%c%c%c%c%c%cred%c word.", + TCOD_COLCTRL_FORE_RGB,255,1,1,TCOD_COLCTRL_BACK_RGB,1,1,1,TCOD_COLCTRL_STOP); + @PyEx + # A string with a red over black word, using predefined color control codes + libtcod.console_set_color_control(libtcod.COLCTRL_1,litbcod.red,litbcod.black) + libtcod.console_print(0,1,1,"String with a %cred%c word."%(libtcod.COLCTRL_1,libtcod.COLCTRL_STOP)) + # A string with a red word (over default background color), using generic color control codes + litbcod.console_print(0,1,1,"String with a %c%c%c%cred%c word."%(libtcod.COLCTRL_FORE_RGB,255,1,1,libtcod.COLCTRL_STOP)) + # A string with a red over black word, using generic color control codes + libtcod.console_print(0,1,1,"String with a %c%c%c%c%c%c%c%cred%c word."% + (libtcod.COLCTRL_FORE_RGB,255,1,1,libtcod.COLCTRL_BACK_RGB,1,1,1,libtcod.COLCTRL_STOP)) + + @C#Ex + TCODConsole.root.print(1,1,String.Format("String with a {0}red{1} word.", + TCODConsole.getRGBColorControlString(ColorControlForeground,TCODColor.red), + TCODConsole.getColorControlString(ColorControlStop)); + */ + static void setColorControl(TCOD_colctrl_t con, const TCODColor &fore, const TCODColor &back); + +#ifndef NO_UNICODE + /** + @PageName console_print + @FuncTitle Unicode functions + @FuncDesc those functions are similar to their ASCII equivalent, but work with unicode strings (wchar_t in C/C++). + Note that unicode is not supported in the Python wrapper. + @Cpp static void TCODConsole::mapStringToFont(const wchar_t *s, int fontCharX, int fontCharY) + @C void TCOD_console_map_string_to_font_utf(const wchar_t *s, int fontCharX, int fontCharY) + */ + static void mapStringToFont(const wchar_t *s, int fontCharX, int fontCharY); + /** + @PageName console_print + @Cpp void TCODConsole::print(int x, int y, const wchar_t *fmt, ...) + @C void TCOD_console_print_utf(TCOD_console_t con,int x, int y, const wchar_t *fmt, ...) + */ + void print(int x, int y, const wchar_t *fmt, ...); + /** + @PageName console_print + @Cpp void TCODConsole::printEx(int x, int y, TCOD_bkgnd_flag_t flag, TCOD_alignment_t alignment, const wchar_t *fmt, ...) + @C void TCOD_console_print_ex_utf(TCOD_console_t con,int x, int y, TCOD_bkgnd_flag_t flag, TCOD_alignment_t alignment, const wchar_t *fmt, ...) + */ + void printEx(int x, int y, TCOD_bkgnd_flag_t flag, TCOD_alignment_t alignment, const wchar_t *fmt, ...); + /** + @PageName console_print + @Cpp int TCODConsole::printRect(int x, int y, int w, int h, const wchar_t *fmt, ...) + @C int TCOD_console_print_rect_utf(TCOD_console_t con,int x, int y, int w, int h, const wchar_t *fmt, ...) + */ + int printRect(int x, int y, int w, int h, const wchar_t *fmt, ...); + + /** + @PageName console_print + @Cpp int TCODConsole::printRectEx(int x, int y, int w, int h, TCOD_bkgnd_flag_t flag, TCOD_alignment_t alignment, const wchar_t *fmt, ...) + @C int TCOD_console_print_rect_ex_utf(TCOD_console_t con,int x, int y, int w, int h, TCOD_bkgnd_flag_t flag, TCOD_alignment_t alignment, const wchar_t *fmt, ...) + */ + int printRectEx(int x, int y, int w, int h, TCOD_bkgnd_flag_t flag, TCOD_alignment_t alignment, const wchar_t *fmt, ...); + + /** + @PageName console_print + @Cpp int TCODConsole::getHeightRect(int x, int y, int w, int h, const wchar_t *fmt, ...) + @C int TCOD_console_get_height_rect_utf(TCOD_console_t con,int x, int y, int w, int h, const wchar_t *fmt, ...) + */ + int getHeightRect(int x, int y, int w, int h, const wchar_t *fmt, ...); +#endif + + /** + @PageName console_advanced + @PageFather console_draw + @PageTitle Advanced printing functions + @FuncTitle Filling a rectangle with the background color + @FuncDesc Fill a rectangle inside a console. For each cell in the rectangle : + * set the cell's background color to the console default background color + * if clear is true, set the cell's ASCII code to 32 (space) + @Cpp void TCODConsole::rect(int x, int y, int w, int h, bool clear, TCOD_bkgnd_flag_t flag = TCOD_BKGND_DEFAULT) + @C void TCOD_console_rect(TCOD_console_t con,int x, int y, int w, int h, bool clear, TCOD_bkgnd_flag_t flag) + @Py console_rect(con,x, y, w, h, clear, flag=BKGND_DEFAULT) + @C# + void TCODConsole::rect(int x, int y, int w, int h, bool clear) + void TCODConsole::rect(int x, int y, int w, int h, bool clear, TCODBackgroundFlag flag) + @Lua + Console:rect(x, y, w, h, clear) + Console:rect(x, y, w, h, clear, flag) + @Param con in the C and Python versions, the offscreen console handler or NULL for the root console + @Param x,y coordinates of rectangle upper-left corner in the console. + 0 <= x < console width + 0 <= y < console height + @Param w,h size of the rectangle in the console. + x <= x+w < console width + y <= y+h < console height + @Param clear if true, all characters inside the rectangle are set to ASCII code 32 (space). + If false, only the background color is modified + @Param flag this flag defines how the cell's background color is modified. See TCOD_bkgnd_flag_t + */ + void rect(int x, int y, int w, int h, bool clear, TCOD_bkgnd_flag_t flag = TCOD_BKGND_DEFAULT); + + /** + @PageName console_advanced + @FuncTitle Drawing an horizontal line + @FuncDesc Draws an horizontal line in the console, using ASCII code TCOD_CHAR_HLINE (196), and the console's default background/foreground colors. + @Cpp void TCODConsole::hline(int x,int y, int l, TCOD_bkgnd_flag_t flag = TCOD_BKGND_DEFAULT) + @C void TCOD_console_hline(TCOD_console_t con,int x,int y, int l, TCOD_bkgnd_flag_t flag) + @Py console_hline(con,x,y,l,flag=BKGND_DEFAULT) + @C# + void TCODConsole::hline(int x,int y, int l) + void TCODConsole::hline(int x,int y, int l, TCODBackgroundFlag flag) + @Lua + Console:hline(x,y, l) + Console:hline(x,y, l, flag) + @Param con in the C and Python versions, the offscreen console handler or NULL for the root console + @Param x,y Coordinates of the line's left end in the console. + 0 <= x < console width + 0 <= y < console height + @Param l The length of the line in cells 1 <= l <= console width - x + @Param flag this flag defines how the cell's background color is modified. See TCOD_bkgnd_flag_t + */ + void hline(int x,int y, int l, TCOD_bkgnd_flag_t flag = TCOD_BKGND_DEFAULT); + + /** + @PageName console_advanced + @FuncTitle Drawing an vertical line + @FuncDesc Draws an vertical line in the console, using ASCII code TCOD_CHAR_VLINE (179), and the console's default background/foreground colors. + @Cpp void TCODConsole::vline(int x,int y, int l, TCOD_bkgnd_flag_t flag = TCOD_BKGND_DEFAULT) + @C void TCOD_console_vline(TCOD_console_t con,int x,int y, int l, TCOD_bkgnd_flag_t flag) + @Py console_vline(con,x,y,l,flag=BKGND_DEFAULT) + @C# + void TCODConsole::vline(int x,int y, int l) + void TCODConsole::vline(int x,int y, int l, TCODBackgroundFlag flag) + @Lua + Console:vline(x,y, l) + Console:vline(x,y, l, flag) + @Param con in the C and Python versions, the offscreen console handler or NULL for the root console + @Param x,y Coordinates of the line's upper end in the console. + 0 <= x < console width + 0 <= y < console height + @Param l The length of the line in cells 1 <= l <= console height - y + @Param flag this flag defines how the cell's background color is modified. See TCOD_bkgnd_flag_t + */ + void vline(int x,int y, int l, TCOD_bkgnd_flag_t flag = TCOD_BKGND_DEFAULT); + + /** + @PageName console_advanced + @FuncTitle Drawing a window frame + @FuncDesc This function calls the rect function using the supplied background mode flag, then draws a rectangle with the console's default foreground color. If fmt is not NULL, it is printed on the top of the rectangle, using inverted colors. + @Cpp void TCODConsole::printFrame(int x,int y,int w,int h, bool clear=true, TCOD_bkgnd_flag_t flag = TCOD_BKGND_DEFAULT, const char *fmt=NULL, ...) + @C void TCOD_console_print_frame(TCOD_console_t con,int x,int y,int w,int h, bool clear, TCOD_bkgnd_flag_t flag, const char *fmt, ...) + @Py console_print_frame(con,x, y, w, h, clear=True, flag=BKGND_DEFAULT, fmt=0) + @C# + void TCODConsole::printFrame(int x,int y, int w,int h) + void TCODConsole::printFrame(int x,int y, int w,int h, bool clear) + void TCODConsole::printFrame(int x,int y, int w,int h, bool clear, TCODBackgroundFlag flag) + void TCODConsole::printFrame(int x,int y, int w,int h, bool clear, TCODBackgroundFlag flag, string fmt) + @Lua + Console:printFrame(x,y, w,h) + Console:printFrame(x,y, w,h, clear) + Console:printFrame(x,y, w,h, clear, flag) + Console:printFrame(x,y, w,h, clear, flag, fmt) + @Param con in the C and Python versions, the offscreen console handler or NULL for the root console + @Param x,y Coordinates of the rectangle's upper-left corner in the console. + 0 <= x < console width + 0 <= y < console height + @Param w,h size of the rectangle in the console. + x <= x+w < console width + y <= y+h < console height + @Param clear if true, all characters inside the rectangle are set to ASCII code 32 (space). + If false, only the background color is modified + @Param flag this flag defines how the cell's background color is modified. See TCOD_bkgnd_flag_t + @Param fmt if NULL, the function only draws a rectangle. + Else, printf-like format string, eventually followed by parameters. You can use control codes to change the colors inside the string. + */ + void printFrame(int x,int y,int w,int h, bool clear=true, TCOD_bkgnd_flag_t flag = TCOD_BKGND_DEFAULT, const char *fmt=NULL, ...); + + /** + @PageName console_read + @PageTitle Reading the content of the console + @PageFather console_draw + @FuncTitle Get the console's width + @FuncDesc This function returns the width of a console (either the root console or an offscreen console) + @Cpp int TCODConsole::getWidth() const + @C int TCOD_console_get_width(TCOD_console_t con) + @Py console_get_width(con) + @C# int TCODConsole::getWidth() + @Lua Console:getWidth() + @Param con in the C and Python versions, the offscreen console handler or NULL for the root console + */ + int getWidth() const; + + /** + @PageName console_read + @FuncTitle Get the console's height + @FuncDesc This function returns the height of a console (either the root console or an offscreen console) + @Cpp int TCODConsole::getHeight() const + @C int TCOD_console_get_height(TCOD_console_t con) + @Py console_get_height(con) + @C# int TCODConsole::getHeight() + @Lua Console:getHeight() + @Param con in the C and Python versions, the offscreen console handler or NULL for the root console + */ + int getHeight() const; + + /** + @PageName console_read + @FuncTitle Reading the default background color + @FuncDesc This function returns the default background color of a console. + @Cpp TCODColor TCODConsole::getDefaultBackground() const + @C TCOD_color_t TCOD_console_get_default_background(TCOD_console_t con) + @Py console_get_default_background(con) + @C# TCODColor TCODConsole::getBackgroundColor() + @Lua Console:getBackgroundColor() + @Param con in the C and Python versions, the offscreen console handler or NULL for the root console + */ + TCODColor getDefaultBackground() const; + + /** + @PageName console_read + @FuncTitle Reading the default foreground color + @FuncDesc This function returns the default foreground color of a console. + @Cpp TCODColor TCODConsole::getDefaultForeground() const + @C TCOD_color_t TCOD_console_get_default_foreground(TCOD_console_t con) + @Py console_get_default_foreground(con) + @C# TCODColor TCODConsole::getForegroundColor() + @Lua Console:getForegroundColor() + @Param con in the C and Python versions, the offscreen console handler or NULL for the root console + */ + TCODColor getDefaultForeground() const; + + /** + @PageName console_read + @FuncTitle Reading the background color of a cell + @FuncDesc This function returns the background color of a cell. + @Cpp TCODColor TCODConsole::getCharBackground(int x, int y) const + @C TCOD_color_t TCOD_console_get_char_background(TCOD_console_t con,int x, int y) + @Py console_get_char_background(con,x,y) + @C# TCODColor TCODConsole::getCharBackground(int x, int y) + @Lua Console::getCharBackground(x, y) + @Param con in the C and Python versions, the offscreen console handler or NULL for the root console + @Param x,y coordinates of the cell in the console. + 0 <= x < console width + 0 <= y < console height + */ + TCODColor getCharBackground(int x, int y) const; + + /** + @PageName console_read + @FuncTitle Reading the foreground color of a cell + @FuncDesc This function returns the foreground color of a cell. + @Cpp TCODColor TCODConsole::getCharForeground(int x, int y) const + @C TCOD_color_t TCOD_console_get_char_foreground(TCOD_console_t con,int x, int y) + @Py console_get_char_foreground(con,x,y) + @C# TCODColor TCODConsole::getCharForeground(int x, int y) + @Lua Console::getCharForeground(x, y) + @Param con in the C and Python versions, the offscreen console handler or NULL for the root console + @Param x,y coordinates of the cell in the console. + 0 <= x < console width + 0 <= y < console height + */ + TCODColor getCharForeground(int x, int y) const; + + /** + @PageName console_read + @FuncTitle Reading the ASCII code of a cell + @FuncDesc This function returns the ASCII code of a cell. + @Cpp int TCODConsole::getChar(int x, int y) const + @C int TCOD_console_get_char(TCOD_console_t con,int x, int y) + @Py console_get_char(con,x,y) + @C# int TCODConsole::getChar(int x, int y) + @Lua Console::getChar(x, y) + @Param con in the C and Python versions, the offscreen console handler or NULL for the root console + @Param x,y coordinates of the cell in the console. + 0 <= x < console width + 0 <= y < console height + */ + int getChar(int x, int y) const; + + /** + @PageName console_fading + @PageTitle Screen fading functions + @PageFather console_draw + @PageDesc Use these functions to easily fade to/from a color + @FuncTitle Changing the fading parameters + @FuncDesc This function defines the fading parameters, allowing to easily fade the game screen to/from a color. Once they are defined, the fading parameters are valid for ever. You don't have to call setFade for each rendered frame (unless you change the fading parameters). + @Cpp static void TCODConsole::setFade(uint8_t fade, const TCODColor &fadingColor) + @C void TCOD_console_set_fade(uint8_t fade, TCOD_color_t fadingColor) + @Py console_set_fade(fade, fadingColor) + @C# static void TCODConsole::setFade(byte fade, TCODColor fadingColor) + @Lua tcod.console.setFade(fade, fadingColor) + @Param fade the fading amount. 0 => the screen is filled with the fading color. 255 => no fading effect + @Param fadingColor the color to use during the console flushing operation + @CppEx + for (int fade=255; fade >= 0; fade --) { + TCODConsole::setFade(fade,TCODColor::black); + TCODConsole::flush(); + } + @CEx + int fade; + for (fade=255; fade >= 0; fade --) { + TCOD_console_setFade(fade,TCOD_black); + TCOD_console_flush(); + } + @PyEx + for fade in range(255,0) : + libtcod.console_setFade(fade,libtcod.black) + libtcod.console_flush() + @LuaEx + for fade=255,0,-1 do + tcod.console.setFade(fade,tcod.color.black) + tcod.console.flush() + end + */ + static void setFade(uint8_t fade, const TCODColor &fadingColor); + + /** + @PageName console_fading + @FuncTitle Reading the fade amount + @FuncDesc This function returns the current fade amount, previously defined by setFade. + @Cpp static uint8_t TCODConsole::getFade() + @C uint8_t TCOD_console_get_fade() + @Py console_get_fade() + @C# static byte TCODConsole::getFade() + @Lua tcod.console.getFade() + */ + static uint8_t getFade(); + + /** + @PageName console_fading + @FuncTitle Reading the fading color + @FuncDesc This function returns the current fading color, previously defined by setFade. + @Cpp static TCODColor TCODConsole::getFadingColor() + @C TCOD_color_t TCOD_console_get_fading_color() + @Py console_get_fading_color() + @C# static TCODColor TCODConsole::getFadingColor() + @Lua tcod.console.getFadingColor() + */ + static TCODColor getFadingColor(); + + /** + @PageName console_flush + @PageFather console + @PageTitle Flushing the root console + @FuncDesc Once the root console is initialized, you can use one of the printing functions to change the background colors, the foreground colors or the ASCII characters on the console. + Once you've finished rendering the root console, you have to actually apply the updates to the screen with this function. + @Cpp static void TCODConsole::flush() + @C void TCOD_console_flush() + @Py console_flush() + @C# static void TCODConsole::flush() + @Lua tcod.console.flush() + */ + static void flush(); + + /** + @PageName console_ascii + @PageTitle ASCII constants + @PageFather console_draw + @FuncDesc Some useful graphic characters in the terminal.bmp font. For the Python version, remove TCOD_ from the constants. C# and Lua is in parenthesis : + Single line walls: + TCOD_CHAR_HLINE=196 (HorzLine) + TCOD_CHAR_VLINE=179 (VertLine) + TCOD_CHAR_NE=191 (NE) + TCOD_CHAR_NW=218 (NW) + TCOD_CHAR_SE=217 (SE) + TCOD_CHAR_SW=192 (SW) + + Double lines walls: + TCOD_CHAR_DHLINE=205 (DoubleHorzLine) + TCOD_CHAR_DVLINE=186 (DoubleVertLine) + TCOD_CHAR_DNE=187 (DoubleNE) + TCOD_CHAR_DNW=201 (DoubleNW) + TCOD_CHAR_DSE=188 (DoubleSE) + TCOD_CHAR_DSW=200 (DoubleSW) + + Single line vertical/horizontal junctions (T junctions): + TCOD_CHAR_TEEW=180 (TeeWest) + TCOD_CHAR_TEEE=195 (TeeEast) + TCOD_CHAR_TEEN=193 (TeeNorth) + TCOD_CHAR_TEES=194 (TeeSouth) + + Double line vertical/horizontal junctions (T junctions): + TCOD_CHAR_DTEEW=185 (DoubleTeeWest) + TCOD_CHAR_DTEEE=204 (DoubleTeeEast) + TCOD_CHAR_DTEEN=202 (DoubleTeeNorth) + TCOD_CHAR_DTEES=203 (DoubleTeeSouth) + + Block characters: + TCOD_CHAR_BLOCK1=176 (Block1) + TCOD_CHAR_BLOCK2=177 (Block2) + TCOD_CHAR_BLOCK3=178 (Block3) + + Cross-junction between two single line walls: + TCOD_CHAR_CROSS=197 (Cross) + + Arrows: + TCOD_CHAR_ARROW_N=24 (ArrowNorth) + TCOD_CHAR_ARROW_S=25 (ArrowSouth) + TCOD_CHAR_ARROW_E=26 (ArrowEast) + TCOD_CHAR_ARROW_W=27 (ArrowWest) + + Arrows without tail: + TCOD_CHAR_ARROW2_N=30 (ArrowNorthNoTail) + TCOD_CHAR_ARROW2_S=31 (ArrowSouthNoTail) + TCOD_CHAR_ARROW2_E=16 (ArrowEastNoTail) + TCOD_CHAR_ARROW2_W=17 (ArrowWestNoTail) + + Double arrows: + TCOD_CHAR_DARROW_H=29 (DoubleArrowHorz) + TCOD_CHAR_ARROW_V=18 (DoubleArrowVert) + + GUI stuff: + TCOD_CHAR_CHECKBOX_UNSET=224 + TCOD_CHAR_CHECKBOX_SET=225 + TCOD_CHAR_RADIO_UNSET=9 + TCOD_CHAR_RADIO_SET=10 + + Sub-pixel resolution kit: + TCOD_CHAR_SUBP_NW=226 (SubpixelNorthWest) + TCOD_CHAR_SUBP_NE=227 (SubpixelNorthEast) + TCOD_CHAR_SUBP_N=228 (SubpixelNorth) + TCOD_CHAR_SUBP_SE=229 (SubpixelSouthEast) + TCOD_CHAR_SUBP_DIAG=230 (SubpixelDiagonal) + TCOD_CHAR_SUBP_E=231 (SubpixelEast) + TCOD_CHAR_SUBP_SW=232 (SubpixelSouthWest) + + Miscellaneous characters: + TCOD_CHAR_SMILY = 1 (Smilie) + TCOD_CHAR_SMILY_INV = 2 (SmilieInv) + TCOD_CHAR_HEART = 3 (Heart) + TCOD_CHAR_DIAMOND = 4 (Diamond) + TCOD_CHAR_CLUB = 5 (Club) + TCOD_CHAR_SPADE = 6 (Spade) + TCOD_CHAR_BULLET = 7 (Bullet) + TCOD_CHAR_BULLET_INV = 8 (BulletInv) + TCOD_CHAR_MALE = 11 (Male) + TCOD_CHAR_FEMALE = 12 (Female) + TCOD_CHAR_NOTE = 13 (Note) + TCOD_CHAR_NOTE_DOUBLE = 14 (NoteDouble) + TCOD_CHAR_LIGHT = 15 (Light) + TCOD_CHAR_EXCLAM_DOUBLE = 19 (ExclamationDouble) + TCOD_CHAR_PILCROW = 20 (Pilcrow) + TCOD_CHAR_SECTION = 21 (Section) + TCOD_CHAR_POUND = 156 (Pound) + TCOD_CHAR_MULTIPLICATION = 158 (Multiplication) + TCOD_CHAR_FUNCTION = 159 (Function) + TCOD_CHAR_RESERVED = 169 (Reserved) + TCOD_CHAR_HALF = 171 (Half) + TCOD_CHAR_ONE_QUARTER = 172 (OneQuarter) + TCOD_CHAR_COPYRIGHT = 184 (Copyright) + TCOD_CHAR_CENT = 189 (Cent) + TCOD_CHAR_YEN = 190 (Yen) + TCOD_CHAR_CURRENCY = 207 (Currency) + TCOD_CHAR_THREE_QUARTERS = 243 (ThreeQuarters) + TCOD_CHAR_DIVISION = 246 (Division) + TCOD_CHAR_GRADE = 248 (Grade) + TCOD_CHAR_UMLAUT = 249 (Umlaut) + TCOD_CHAR_POW1 = 251 (Pow1) + TCOD_CHAR_POW3 = 252 (Pow2) + TCOD_CHAR_POW2 = 253 (Pow3) + TCOD_CHAR_BULLET_SQUARE = 254 (BulletSquare) + */ + + /** + @PageName console_input + @PageTitle Handling user input + @PageDesc The user handling functions allow you to get keyboard and mouse input from the user, either for turn by turn games (the function wait until the user press a key or a mouse button), or real time games (non blocking function). + WARNING : those functions also handle screen redraw event, so TCODConsole::flush function won't redraw screen if no user input function is called ! + @PageFather console + */ + + /* deprecated as of 1.5.1 */ + static TCOD_key_t waitForKeypress(bool flush); + /* deprecated as of 1.5.1 */ + static TCOD_key_t checkForKeypress(int flags=TCOD_KEY_RELEASED); + + /** + @PageName console_blocking_input + @PageCategory Core + @PageFather console_input + @PageTitle Blocking user input + @PageDesc This function stops the application until an event occurs. + */ + + /** + @PageName console_non_blocking_input + @PageTitle Non blocking user input + @PageFather console_input + @FuncDesc The preferred way to check for user input is to use checkForEvent below, but you can also get the status of any special key at any time with : + @Cpp static bool TCODConsole::isKeyPressed(TCOD_keycode_t key) + @C bool TCOD_console_is_key_pressed(TCOD_keycode_t key) + @Py console_is_key_pressed(key) + @C# static bool TCODConsole::isKeyPressed(TCODKeyCode key) + @Lua tcod.console.isKeyPressed(key) + @Param key Any key code defined in keycode_t except TCODK_CHAR (Char) and TCODK_NONE (NoKey) + */ + static bool isKeyPressed(TCOD_keycode_t key); + + /** + @PageName console_key_t + @PageTitle Keyboard event structure + @PageFather console_input + @PageDesc This structure contains information about a key pressed/released by the user. + @C + typedef struct { + TCOD_keycode_t vk; + char c; + char text[32]; + bool pressed; + bool lalt; + bool lctrl; + bool lmeta; + bool ralt; + bool rctrl; + bool rmeta; + bool shift; + } TCOD_key_t; + @Lua + key.KeyCode + key.Character + key.Text + key.Pressed + key.LeftAlt + key.LeftControl + key.LeftMeta + key.RightAlt + key.RightControl + key.RightMeta + key.Shift + @Param vk An arbitrary value representing the physical key on the keyboard. Possible values are stored in the TCOD_keycode_t enum. If no key was pressed, the value is TCODK_NONE + @Param c If the key correspond to a printable character, the character is stored in this field. Else, this field contains 0. + @Param text If vk is TCODK_TEXT, this will contain the text entered by the user. + @Param pressed true if the event is a key pressed, or false for a key released. + @Param lalt This field represents the status of the left Alt key : true => pressed, false => released. + @Param lctrl This field represents the status of the left Control key : true => pressed, false => released. + @Param lmeta This field represents the status of the left Meta (Windows/Command/..) key : true => pressed, false => released. + @Param ralt This field represents the status of the right Alt key : true => pressed, false => released. + @Param rctrl This field represents the status of the right Control key : true => pressed, false => released. + @Param rmeta This field represents the status of the right Meta (Windows/Command/..) key : true => pressed, false => released. + @Param shift This field represents the status of the shift key : true => pressed, false => released. + */ + + /** + @PageName console_mouse_t + @PageTitle Mouse event structure + @PageFather console_input + @PageDesc This structure contains information about a mouse move/press/release event. + @C + typedef struct { + int x,y; + int dx,dy; + int cx,cy; + int dcx,dcy; + bool lbutton; + bool rbutton; + bool mbutton; + bool lbutton_pressed; + bool rbutton_pressed; + bool mbutton_pressed; + bool wheel_up; + bool wheel_down; + } TCOD_mouse_t; + @Param x,y Absolute position of the mouse cursor in pixels relative to the window top-left corner. + @Param dx,dy Movement of the mouse cursor since the last call in pixels. + @Param cx,cy Coordinates of the console cell under the mouse cursor (pixel coordinates divided by the font size). + @Param dcx,dcy Movement of the mouse since the last call in console cells (pixel coordinates divided by the font size). + @Param lbutton true if the left button is pressed. + @Param rbutton true if the right button is pressed. + @Param mbutton true if the middle button (or the wheel) is pressed. + @Param lbutton_pressed true if the left button was pressed and released. + @Param rbutton_pressed true if the right button was pressed and released. + @Param mbutton_pressed true if the middle button was pressed and released. + @Param wheel_up true if the wheel was rolled up. + @Param wheel_down true if the wheel was rolled down. + */ + + /** + @PageName console_keycode_t + @PageTitle Key codes + @PageFather console_input + @PageDesc TCOD_keycode_t is a libtcod specific code representing a key on the keyboard. + For Python, replace TCODK by KEY: libtcod.KEY_NONE. C# and Lua, the value is in parenthesis. Possible values are : + When no key was pressed (see checkForEvent) : TCOD_NONE (NoKey) + Special keys : + TCODK_ESCAPE (Escape) + TCODK_BACKSPACE (Backspace) + TCODK_TAB (Tab) + TCODK_ENTER (Enter) + TCODK_SHIFT (Shift) + TCODK_CONTROL (Control) + TCODK_ALT (Alt) + TCODK_PAUSE (Pause) + TCODK_CAPSLOCK (CapsLock) + TCODK_PAGEUP (PageUp) + TCODK_PAGEDOWN (PageDown) + TCODK_END (End) + TCODK_HOME (Home) + TCODK_UP (Up) + TCODK_LEFT (Left) + TCODK_RIGHT (Right) + TCODK_DOWN (Down) + TCODK_PRINTSCREEN (Printscreen) + TCODK_INSERT (Insert) + TCODK_DELETE (Delete) + TCODK_LWIN (Lwin) + TCODK_RWIN (Rwin) + TCODK_APPS (Apps) + TCODK_KPADD (KeypadAdd) + TCODK_KPSUB (KeypadSubtract) + TCODK_KPDIV (KeypadDivide) + TCODK_KPMUL (KeypadMultiply) + TCODK_KPDEC (KeypadDecimal) + TCODK_KPENTER (KeypadEnter) + TCODK_F1 (F1) + TCODK_F2 (F2) + TCODK_F3 (F3) + TCODK_F4 (F4) + TCODK_F5 (F5) + TCODK_F6 (F6) + TCODK_F7 (F7) + TCODK_F8 (F8) + TCODK_F9 (F9) + TCODK_F10 (F10) + TCODK_F11 (F11) + TCODK_F12 (F12) + TCODK_NUMLOCK (Numlock) + TCODK_SCROLLLOCK (Scrolllock) + TCODK_SPACE (Space) + + numeric keys : + + TCODK_0 (Zero) + TCODK_1 (One) + TCODK_2 (Two) + TCODK_3 (Three) + TCODK_4 (Four) + TCODK_5 (Five) + TCODK_6 (Six) + TCODK_7 (Seven) + TCODK_8 (Eight) + TCODK_9 (Nine) + TCODK_KP0 (KeypadZero) + TCODK_KP1 (KeypadOne) + TCODK_KP2 (KeypadTwo) + TCODK_KP3 (KeypadThree) + TCODK_KP4 (KeypadFour) + TCODK_KP5 (KeypadFive) + TCODK_KP6 (KeypadSix) + TCODK_KP7 (KeypadSeven) + TCODK_KP8 (KeypadEight) + TCODK_KP9 (KeypadNine) + + Any other (printable) key : + + TCODK_CHAR (Char) + + Codes starting with TCODK_KP represents keys on the numeric keypad (if available). + */ + + /** + @PageName console_offscreen + @PageFather console + @PageTitle Using off-screen consoles + @PageDesc The offscreen consoles allow you to draw on secondary consoles as you would do with the root console. You can then blit those secondary consoles on the root console. This allows you to use local coordinate space while rendering a portion of the final screen, and easily move components of the screen without modifying the rendering functions. + @FuncTitle Creating an offscreen console + @FuncDesc You can create as many off-screen consoles as you want by using this function. You can draw on them as you would do with the root console, but you cannot flush them to the screen. Else, you can blit them on other consoles, including the root console. See blit. The C version of this function returns a console handler that you can use in most console drawing functions. + @Cpp TCODConsole::TCODConsole(int w, int h) + @C TCOD_console_t TCOD_console_new(int w, int h) + @Py console_new(w,h) + @C# TCODConsole::TCODConsole(int w, int h) + @Lua tcod.Console(w,h) + @Param w,h the console size. + 0 < w + 0 < h + @CppEx + // Creating a 40x20 offscreen console, filling it with red and blitting it on the root console at position 5,5 + TCODConsole *offscreenConsole = new TCODConsole(40,20); + offscreenConsole->setDefaultBackground(TCODColor::red); + offscreenConsole->clear(); + TCODConsole::blit(offscreenConsole,0,0,40,20,TCODConsole::root,5,5,255); + @CEx + TCOD_console_t offscreen_console = TCOD_console_new(40,20); + TCOD_console_set_default_background(offscreen_console,TCOD_red); + TCOD_console_clear(offscreen_console); + TCOD_console_blit(offscreen_console,0,0,40,20,NULL,5,5,255); + @PyEx + offscreen_console = libtcod.console_new(40,20) + libtcod.console_set_background_color(offscreen_console,libtcod.red) + libtcod.console_clear(offscreen_console) + libtcod.console_blit(offscreen_console,0,0,40,20,0,5,5,255) + @LuaEx + -- Creating a 40x20 offscreen console, filling it with red and blitting it on the root console at position 5,5 + offscreenConsole = tcod.Console(40,20) + offscreenConsole:setBackgroundColor(tcod.color.red) + offscreenConsole:clear() + tcod.console.blit(offscreenConsole,0,0,40,20,libtcod.TCODConsole_root,5,5,255) + */ + TCODConsole(int w, int h); + + /** + @PageName console_offscreen + @FuncTitle Creating an offscreen console from a .asc or .apf file + @FuncDesc You can create an offscreen console from a file created with Ascii Paint with this constructor + @Cpp TCODConsole::TCODConsole(const char *filename) + @C TCOD_console_t TCOD_console_from_file(const char *filename) + @Param filename path to the .asc or .apf file created with Ascii Paint + @CppEx + // Creating an offscreen console, filling it with data from the .asc file + TCODConsole *offscreenConsole = new TCODConsole("myfile.asc"); + @CEx + TCOD_console_t offscreen_console = TCOD_console_from_file("myfile.apf"); + */ + TCODConsole(const char *filename); + + /** + @PageName console_offscreen + @FuncTitle Loading an offscreen console from a .asc file + @FuncDesc You can load data from a file created with Ascii Paint with this function. When needed, the console will be resized to fit the file size. The function returns false if it couldn't read the file. + @Cpp bool TCODConsole::loadAsc(const char *filename) + @C bool TCOD_console_load_asc(TCOD_console_t con, const char *filename) + @Param con in the C and Python versions, the offscreen console handler + @Param filename path to the .asc file created with Ascii Paint + @CppEx + // Creating a 40x20 offscreen console + TCODConsole *offscreenConsole = new TCODConsole(40,20); + // possibly resizing it and filling it with data from the .asc file + offscreenConsole->loadAsc("myfile.asc"); + @CEx + TCOD_console_t offscreen_console = TCOD_console_new(40,20); + TCOD_console_load_asc(offscreen_console,"myfile.asc"); + */ + bool loadAsc(const char *filename); + /** + @PageName console_offscreen + @FuncTitle Loading an offscreen console from a .apf file + @FuncDesc You can load data from a file created with Ascii Paint with this function. When needed, the console will be resized to fit the file size. The function returns false if it couldn't read the file. + @Cpp bool TCODConsole::loadApf(const char *filename) + @C bool TCOD_console_load_apf(TCOD_console_t con, const char *filename) + @Param con in the C and Python versions, the offscreen console handler + + @Param filename path to the .apf file created with Ascii Paint + + @CppEx + // Creating a 40x20 offscreen console + TCODConsole *offscreenConsole = new TCODConsole(40,20); + // possibly resizing it and filling it with data from the .apf file + offscreenConsole->loadApf("myfile.apf"); + @CEx + TCOD_console_t offscreen_console = TCOD_console_new(40,20); + TCOD_console_load_apf(offscreen_console,"myfile.asc"); + */ + bool loadApf(const char *filename); + + /** + @PageName console_offscreen + @FuncTitle Saving a console to a .asc file + @FuncDesc You can save data from a console to Ascii Paint format with this function. The function returns false if it couldn't write the file. This is the only ASC function that works also with the root console ! + @Cpp bool TCODConsole::saveAsc(const char *filename) const + @C bool TCOD_console_save_asc(TCOD_console_t con, const char *filename) + @Param con in the C and Python versions, the offscreen console handler or NULL for the root console + @Param filename path to the .asc file to be created + @CppEx + console->saveAsc("myfile.asc"); + @CEx + TCOD_console_save_asc(console,"myfile.asc"); + */ + bool saveAsc(const char *filename) const; + + /** + @PageName console_offscreen + @FuncTitle Saving a console to a .apf file + @FuncDesc You can save data from a console to Ascii Paint format with this function. The function returns false if it couldn't write the file. This is the only ASC function that works also with the root console ! + @Cpp bool TCODConsole::saveApf(const char *filename) const + @C bool TCOD_console_save_apf(TCOD_console_t con, const char *filename) + @Param con in the C and Python versions, the offscreen console handler or NULL for the root console + @Param filename path to the .apf file to be created + @CppEx + console->saveApf("myfile.apf"); + @CEx + TCOD_console_save_apf(console,"myfile.apf"); + */ + bool saveApf(const char *filename) const; + + bool loadXp(const char *filename) { + return TCOD_console_load_xp(data, filename) != 0; + } + bool saveXp(const char *filename, int compress_level) { + return TCOD_console_save_xp(data, filename, compress_level) != 0; + } + + /** + @PageName console_offscreen + @FuncTitle Blitting a console on another one + @FuncDesc This function allows you to blit a rectangular area of the source console at a specific position on a destination console. It can also simulate alpha transparency with the fade parameter. + @Cpp static void blit(const TCODConsole *src,int xSrc, int ySrc, int wSrc, int hSrc, TCODConsole *dst, int xDst, int yDst, float foregroundAlpha=1.0f, float backgroundAlpha=1.0f) + @C void TCOD_console_blit(TCOD_console_t src,int xSrc, int ySrc, int wSrc, int hSrc, TCOD_console_t dst, int xDst, int yDst, float foreground_alpha, float background_alpha) + @Py console_blit(src,xSrc,ySrc,xSrc,hSrc,dst,xDst,yDst,foregroundAlpha=1.0,backgroundAlpha=1.0) + @C# + static void TCODConsole::blit(TCODConsole src, int xSrc, int ySrc, int wSrc, int hSrc, TCODConsole dst, int xDst, int yDst) + static void TCODConsole::blit(TCODConsole src, int xSrc, int ySrc, int wSrc, int hSrc, TCODConsole dst, int xDst, int yDst, float foreground_alpha) + static void TCODConsole::blit(TCODConsole src, int xSrc, int ySrc, int wSrc, int hSrc, TCODConsole dst, int xDst, int yDst, float foreground_alpha, float background_alpha) + @Lua + tcod.console.blit(src, xSrc, ySrc, wSrc, hSrc, dst, xDst, yDst) + tcod.console.blit(src, xSrc, ySrc, wSrc, hSrc, dst, xDst, yDst, foreground_alpha) + tcod.console.blit(src, xSrc, ySrc, wSrc, hSrc, dst, xDst, yDst, foreground_alpha, background_alpha) + @Param src The source console that must be blitted on another one. + @Param xSrc,ySrc,wSrc,hSrc The rectangular area of the source console that will be blitted. If wSrc and/or hSrc == 0, the source console width/height are used + @Param dst The destination console. + @Param xDst,yDst Where to blit the upper-left corner of the source area in the destination console. + @Param foregroundAlpha,backgroundAlpha Alpha transparency of the blitted console. + 0.0 => The source console is completely transparent. This function does nothing. + 1.0 => The source console is opaque. Its cells replace the destination cells. + 0 < fade < 1.0 => The source console is partially blitted, simulating real transparency. + @CppEx + // Cross-fading between two offscreen consoles. We use two offscreen consoles with the same size as the root console. We render a different screen on each offscreen console. When the user hits a key, we do a cross-fading from the first screen to the second screen. + TCODConsole *off1 = new TCODConsole(80,50); + TCODConsole *off2 = new TCODConsole(80,50); + ... print screen1 on off1 + ... print screen2 of off2 + // render screen1 in the game window + TCODConsole::blit(off1,0,0,80,50,TCODConsole::root,0,0); + TCODConsole::flush(); + // wait or a keypress + TCODConsole::waitForKeypress(true); + // do a cross-fading from off1 to off2 + for (int i=1; i <= 255; i++) { + TCODConsole::blit(off1,0,0,80,50,TCODConsole::root,0,0); // renders the first screen (opaque) + TCODConsole::blit(off2,0,0,80,50,TCODConsole::root,0,0,i/255.0,i/255.0); // renders the second screen (transparent) + TCODConsole::flush(); + } + @CEx + TCOD_console_t off1 = TCOD_console_new(80,50); + TCOD_console_t off2 = TCOD_console_new(80,50); + int i; + ... print screen1 on off1 + ... print screen2 of off2 + // render screen1 in the game window + TCOD_console_blit(off1,0,0,80,50,NULL,0,0,1.0,1.0); + TCOD_console_flush(); + // wait or a keypress + TCOD_console_wait_for_keypress(true); + // do a cross-fading from off1 to off2 + for (i=1; i <= 255; i++) { + TCOD_console_blit(off1,0,0,80,50,NULL,0,0,1.0,1.0); // renders the first screen (opaque) + TCOD_console_blit(off2,0,0,80,50,NULL,0,0,i/255.0,i/255.0); // renders the second screen (transparent) + TCOD_console_flush(); + } + @PyEx + off1 = libtcod.console_new(80,50) + off2 = libtcod.console_new(80,50) + ... print screen1 on off1 + ... print screen2 of off2 + # render screen1 in the game window + libtcod.console_blit(off1,0,0,80,50,0,0,0) + libtcod.console_flush() + # wait or a keypress + libtcod.console_wait_for_keypress(True) + # do a cross-fading from off1 to off2 + for i in range(1,256) : + litbcod.console_blit(off1,0,0,80,50,0,0,0) # renders the first screen (opaque) + litbcod.console_blit(off2,0,0,80,50,0,0,0,i/255.0,i/255.0) # renders the second screen (transparent) + litbcod.console_flush() + @LuaEx + -- Cross-fading between two offscreen consoles. We use two offscreen consoles with the same size as the root console. We render a different screen on each offscreen console. When the user hits a key, we do a cross-fading from the first screen to the second screen. + off1 = tcod.Console(80,50) + off2 = tcod.Console(80,50) + ... print screen1 on off1 + ... print screen2 of off2 + -- render screen1 in the game window + root=libtcod.TCODConsole_root + tcod.console.blit(off1,0,0,80,50,root,0,0) + tcod.console.flush() + -- wait or a keypress + tcod.console.waitForKeypress(true) + -- do a cross-fading from off1 to off2 + for i=1,255,1 do + tcod.console.blit(off1,0,0,80,50,root,0,0) -- renders the first screen (opaque) + tcod.console.blit(off2,0,0,80,50,root,0,0,i/255,i/255) -- renders the second screen (transparent) + tcod.console.flush() + end + */ + static void blit(const TCODConsole *src,int xSrc, int ySrc, int wSrc, int hSrc, TCODConsole *dst, int xDst, int yDst, float foreground_alpha=1.0f, float background_alpha=1.0f); + /** + @PageName console_offscreen + @FuncTitle Define a blit-transparent color + @FuncDesc This function defines a transparent background color for an offscreen console. All cells with this background color are ignored by the blit operation. You can use it to blit only some parts of the console. + @Cpp void TCODConsole::setKeyColor(const TCODColor &col) + @C void TCOD_console_set_key_color(TCOD_console_t con,TCOD_color_t col) + @Py console_set_key_color(con,col) + @C# void TCODConsole::setKeyColor(TCODColor col) + @Lua Console:setKeyColor(col) + @Param con in the C and Python versions, the offscreen console handler or NULL for the root console + @Param col the transparent background color + */ + void setKeyColor(const TCODColor &col); + /** + @PageName console_offscreen + @FuncTitle Destroying an offscreen console + @FuncDesc Use this function to destroy an offscreen console and release any resources allocated. Don't use it on the root console. + @Cpp TCODConsole::~TCODConsole() + @C void TCOD_console_delete(TCOD_console_t con) + @Py console_delete(con) + @C# void TCODConsole::Dispose() + @Lua through garbage collector + @Param con in the C and Python versions, the offscreen console handler + @CppEx + TCODConsole *off1 = new TCODConsole(80,50); + ... use off1 + delete off1; // destroy the offscreen console + @CEx + TCOD_console_t off1 = TCOD_console_new(80,50); + ... use off1 + TCOD_console_delete(off1); // destroy the offscreen console + @PyEx + off1 = libtcod.console_new(80,50) + ... use off1 + libtcod.console_delete(off1) # destroy the offscreen console + @LuaEx + off1 = tcod.Console(80,50) + ... use off1 + off1=nil -- release the reference + */ + virtual ~TCODConsole(); + + void setDirty(int x, int y, int w, int h); + + + TCODConsole(TCOD_console_t con) : data(con) {} + + // ctrl = TCOD_COLCTRL_1...TCOD_COLCTRL_5 or TCOD_COLCTRL_STOP + static const char *getColorControlString( TCOD_colctrl_t ctrl ); + // ctrl = TCOD_COLCTRL_FORE_RGB or TCOD_COLCTRL_BACK_RGB + static const char *getRGBColorControlString( TCOD_colctrl_t ctrl, const TCODColor & col ); + +protected : + friend class TCODImage; + friend class TCODZip; + friend class TCODText; + friend TCODLIB_API void TCOD_console_init_root( + int w, int h, const char* title, + bool fullscreen, TCOD_renderer_t renderer); + TCODConsole(); + TCOD_console_t data; +}; + +#endif /* TCOD_CONSOLE_SUPPORT */ + +#endif /* _TCOD_CONSOLE_HPP */ diff --git a/tcod_sys/libtcod/src/console_c.c b/tcod_sys/libtcod/src/libtcod/console_c.cpp similarity index 65% rename from tcod_sys/libtcod/src/console_c.c rename to tcod_sys/libtcod/src/libtcod/console_c.cpp index ee21eb319..f4dd84d5e 100644 --- a/tcod_sys/libtcod/src/console_c.c +++ b/tcod_sys/libtcod/src/libtcod/console_c.cpp @@ -1,2620 +1,2121 @@ -/* -* libtcod -* Copyright (c) 2008-2018 Jice & Mingos & rmtew -* All rights reserved. -* -* Redistribution and use in source and binary forms, with or without -* modification, are permitted provided that the following conditions are met: -* * Redistributions of source code must retain the above copyright -* notice, this list of conditions and the following disclaimer. -* * Redistributions in binary form must reproduce the above copyright -* notice, this list of conditions and the following disclaimer in the -* documentation and/or other materials provided with the distribution. -* * The name of Jice or Mingos may not be used to endorse or promote -* products derived from this software without specific prior written -* permission. -* -* THIS SOFTWARE IS PROVIDED BY JICE, MINGOS AND RMTEW ``AS IS'' AND ANY -* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED -* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE -* DISCLAIMED. IN NO EVENT SHALL JICE, MINGOS OR RMTEW BE LIABLE FOR ANY -* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES -* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; -* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND -* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS -* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. -*/ -#include - -#include -#include -#include -#include -#include -#ifndef NO_UNICODE -#include -#include -#endif - -#include "vendor/stb_sprintf.h" -#include -#include -#include -#include -#include -#include - -#ifdef TCOD_CONSOLE_SUPPORT - -#if defined( TCOD_VISUAL_STUDIO ) -static const char *version_string ="libtcod "TCOD_STRVERSION; -#else -static const char *version_string __attribute__((unused)) ="libtcod "TCOD_STRVERSION; -#endif - -TCOD_internal_context_t TCOD_ctx={ - /* number of characters in the bitmap font */ - 16,16, - /* font type and layout */ - false,false,false, - /* character size in font */ - 8,8, - "terminal.png","", - NULL,NULL,NULL,0,false,0,0,0,0,0,0, -#ifndef TCOD_BARE - /* default renderer to use */ - TCOD_RENDERER_GLSL, - NULL, -#endif - /* fading data */ - {0,0,0},255, - /*key state*/ - {0}, - /* window closed ? */ - false, - /* mouse focus ? */ - false, - /* application active ? */ - true, -}; - -static TCOD_color_t color_control_fore[TCOD_COLCTRL_NUMBER]; -static TCOD_color_t color_control_back[TCOD_COLCTRL_NUMBER]; -/** - * Assign a foreground and background color to a color control index. - * - * \param con Index to change, e.g. `TCOD_COLCTRL_1` - * \param fore Foreground color to assign to this index. - * \param back Background color to assign to this index. - */ -void TCOD_console_set_color_control(TCOD_colctrl_t con, TCOD_color_t fore, TCOD_color_t back) { - TCOD_IFNOT(con >= TCOD_COLCTRL_1 && con <= TCOD_COLCTRL_NUMBER ) return; - color_control_fore[con-1]=fore; - color_control_back[con-1]=back; -} -/** - * Return a new console with a specific number of columns and rows. - * - * \param w Number of columns. - * \param h Number of columns. - * \return A pointer to the new console, or NULL on error. - */ -TCOD_console_t TCOD_console_new(int w, int h) { - TCOD_IFNOT(w > 0 && h > 0 ) { - return NULL; - } else { - TCOD_console_data_t *con=(TCOD_console_data_t *)calloc(sizeof(TCOD_console_data_t),1); - if (!con) { return NULL; } - con->w=w; - con->h=h; - TCOD_console_init(con,NULL,false); /* NOTE: CHECK THIS FOR ERORS */ - if(TCOD_ctx.root) { - con->alignment=TCOD_ctx.root->alignment; - con->bkgnd_flag=TCOD_ctx.root->bkgnd_flag; - } - return (TCOD_console_t)con; - } -} -/** - * Return immediately with a recently pressed key. - * - * \param flags A TCOD_event_t bit-field, for example: `TCOD_EVENT_KEY_PRESS` - * \return A TCOD_key_t struct with a recently pressed key. - * If no event exists then the `vk` attribute will be `TCODK_NONE` - */ -TCOD_key_t TCOD_console_check_for_keypress(int flags) { - return TCOD_sys_check_for_keypress(flags); -} -/** - * Wait for a key press event, then return it. - * - * \param flush If 1 then the event queue will be cleared before waiting for - * the next event. This should always be 0. - * \return A TCOD_key_t struct with the most recent key data. - * - * Do not solve input lag issues by arbitrarily dropping events! - */ -TCOD_key_t TCOD_console_wait_for_keypress(bool flush) { - return TCOD_sys_wait_for_keypress(flush); -} -/** - * Return true if the window is closing. - */ -bool TCOD_console_is_window_closed(void) { - return TCOD_ctx.is_window_closed; -} -/** - * Return true if the window has mouse focus. - */ -bool TCOD_console_has_mouse_focus(void) { - return TCOD_ctx.app_has_mouse_focus; -} -#ifndef TCOD_BARE -/** - * Return true if the window has keyboard focus. - * - * \verbatim embed:rst:leading-asterisk - * .. versionchanged: 1.7 - * This function was previously broken. It now keeps track of keyboard - * focus. - * \endverbatim - */ -bool TCOD_console_is_active(void) { - return TCOD_ctx.app_is_active; -} -#endif -/** - * Change the title string of the active window. - * - * \param title A utf8 string. - */ -void TCOD_console_set_window_title(const char *title) { - TCOD_sys_set_window_title(title); -} -/** - * Set the display to be full-screen or windowed. - * - * \param fullscreen If true the display will go full-screen. - */ -void TCOD_console_set_fullscreen(bool fullscreen) { - TCOD_IFNOT(TCOD_ctx.root != NULL) return; - TCOD_sys_set_fullscreen(fullscreen); - TCOD_ctx.fullscreen=fullscreen; -} -/** - * Return true if the display is full-screen. - */ -bool TCOD_console_is_fullscreen(void) { - return TCOD_ctx.fullscreen; -} -/** - * Set a consoles default background flag. - * - * \param con A console pointer. - * \param flag One of `TCOD_bkgnd_flag_t`. - */ -void TCOD_console_set_background_flag(TCOD_console_t con,TCOD_bkgnd_flag_t flag) { - TCOD_console_data_t *dat=con ? (TCOD_console_data_t *)con : TCOD_ctx.root; - TCOD_IFNOT ( dat != NULL ) return; - dat->bkgnd_flag=flag; -} -/** - * Return a consoles default background flag. - */ -TCOD_bkgnd_flag_t TCOD_console_get_background_flag(TCOD_console_t con) { - TCOD_console_data_t *dat=con ? (TCOD_console_data_t *)con : TCOD_ctx.root; - TCOD_IFNOT ( dat != NULL ) return TCOD_BKGND_NONE; - return dat->bkgnd_flag; -} -/** - * Set a consoles default alignment. - * - * \param con A console pointer. - * \param alignment One of TCOD_alignment_t - */ -void TCOD_console_set_alignment(TCOD_console_t con,TCOD_alignment_t alignment) { - TCOD_console_data_t *dat=con ? (TCOD_console_data_t *)con : TCOD_ctx.root; - TCOD_IFNOT ( dat != NULL ) return; - dat->alignment=alignment; -} -/** - * Return a consoles default alignment. - */ -TCOD_alignment_t TCOD_console_get_alignment(TCOD_console_t con) { - TCOD_console_data_t *dat=con ? (TCOD_console_data_t *)con : TCOD_ctx.root; - TCOD_IFNOT ( dat != NULL ) return TCOD_LEFT; - return dat->alignment; -} - -static void TCOD_console_data_free(TCOD_console_data_t *dat) { - if (dat->fg_colors) TCOD_image_delete(dat->fg_colors); - if (dat->bg_colors) TCOD_image_delete(dat->bg_colors); - free(dat->ch_array); -} -/** - * Delete a console. - * - * \param con A console pointer. - * - * If the console being deleted is the root console, then the display will be - * uninitialized. - */ -void TCOD_console_delete(TCOD_console_t con) { - TCOD_console_data_t *dat=(TCOD_console_data_t *)(con); - if (! dat ) { - dat=TCOD_ctx.root; - TCOD_sys_uninit(); - TCOD_ctx.root=NULL; - } - TCOD_console_data_free(dat); - free(dat); -} -/** - * Blit from one console to another. - * - * \param srcCon Pointer to the source console. - * \param xSrc The left region of the source console to blit from. - * \param ySrc The top region of the source console to blit from. - * \param wSrc The width of the region to blit from. - * If 0 then it will fill to the maximum width. - * \param hSrc The height of the region to blit from. - * If 0 then it will fill to the maximum height. - * \param dstCon Pointer to the destination console. - * \param xDst The left corner to blit onto the destination console. - * \param yDst The top corner to blit onto the destination console. - * \param foreground_alpha Foreground blending alpha. - * \param background_alpha Background blending alpha. - * - * If the source console has a key color, this function will use it. - */ -void TCOD_console_blit(TCOD_console_t srcCon, int xSrc, int ySrc, int wSrc, int hSrc, - TCOD_console_t dstCon, int xDst, int yDst, float foreground_alpha, float background_alpha) { - TCOD_console_data_t *src = srcCon ? (TCOD_console_data_t *)srcCon : TCOD_ctx.root; - TCOD_console_data_t *dst = dstCon ? (TCOD_console_data_t *)dstCon : TCOD_ctx.root; - TCOD_color_t *srcFgColors, *srcBgColors, *dstFgColors, *dstBgColors; - bool srcHasKeyColor; - TCOD_color_t srcKeyColor; - int cx, cy; - if (wSrc == 0) wSrc = src->w; - if (hSrc == 0) hSrc = src->h; - TCOD_IFNOT(wSrc > 0 && hSrc > 0) return; - TCOD_IFNOT(xDst + wSrc >= 0 && yDst + hSrc >= 0 && xDst < dst->w && yDst < dst->h) return; - TCOD_image_get_key_data(src->bg_colors, &srcHasKeyColor, &srcKeyColor); - srcFgColors = TCOD_image_get_colors(src->fg_colors); - srcBgColors = TCOD_image_get_colors(src->bg_colors); - dstFgColors = TCOD_image_get_colors(dst->fg_colors); - dstBgColors = TCOD_image_get_colors(dst->bg_colors); - for (cx = xSrc; cx < xSrc + wSrc; cx++) { - for (cy = ySrc; cy < ySrc + hSrc; cy++) { - /* check if we're outside the dest console */ - int dx = cx - xSrc + xDst; - int dy = cy - ySrc + yDst; - int dst_idx = dy * dst->w + dx; - int src_idx = cy * src->w + cx; - int srcChar, dstChar; - TCOD_color_t srcFgColor, srcBgColor, dstFgColor, dstBgColor; - if ((unsigned)cx >= (unsigned)src->w || (unsigned)cy >= (unsigned)src->h) continue; - if ((unsigned)dx >= (unsigned)dst->w || (unsigned)dy >= (unsigned)dst->h) continue; - srcChar = src->ch_array[src_idx]; - srcFgColor = srcFgColors[src_idx]; - srcBgColor = srcBgColors[src_idx]; - /* check if source pixel is transparent */ - if (srcHasKeyColor && - srcBgColor.r == srcKeyColor.r && srcBgColor.g == srcKeyColor.g && srcBgColor.b == srcKeyColor.b) - continue; - - if (foreground_alpha == 1.0f && background_alpha == 1.0f) { - dstChar = srcChar; - dstFgColor = srcFgColor; - dstBgColor = srcBgColor; - } - else { - dstChar = dst->ch_array[dst_idx]; - dstFgColor = dstFgColors[dst_idx]; - dstBgColor = dstBgColors[dst_idx]; - - dstBgColor = TCOD_color_lerp(dstBgColor, srcBgColor, background_alpha); - if (srcChar == ' ') { - dstFgColor = TCOD_color_lerp(dstFgColor, srcBgColor, background_alpha); - } - else if (dstChar == ' ') { - dstChar = srcChar; - dstFgColor = TCOD_color_lerp(dstBgColor, srcFgColor, foreground_alpha); - } - else if (dstChar == srcChar) { - dstFgColor = TCOD_color_lerp(dstFgColor, srcFgColor, foreground_alpha); - } - else { - if (foreground_alpha < 0.5f) { - dstFgColor = TCOD_color_lerp(dstFgColor, dstBgColor, - foreground_alpha * 2); - } - else { - dstChar = srcChar; - dstFgColor = TCOD_color_lerp(dstBgColor, srcFgColor, - (foreground_alpha - 0.5f) * 2); - } - } - } - dstFgColors[dst_idx] = dstFgColor; - dstBgColors[dst_idx] = dstBgColor; - dst->ch_array[dst_idx] = dstChar; - } - } - TCOD_image_invalidate_mipmaps(dst->fg_colors); - TCOD_image_invalidate_mipmaps(dst->bg_colors); -} -/** - * Render and present the root console to the active display. - */ -void TCOD_console_flush(void) { - TCOD_IFNOT(TCOD_ctx.root != NULL) return; - TCOD_sys_flush(true); -} -/** - * Fade the color of the display. - * - * \param val Where at 255 colors are normal and at 0 colors are completely - * faded. - * \param fadecol Color to fade towards. - */ -void TCOD_console_set_fade(uint8_t val, TCOD_color_t fadecol) { - TCOD_ctx.fade=val; - TCOD_ctx.fading_color=fadecol; -} -/** - * Return the fade value. - * - * \return At 255 colors are normal and at 0 colors are completely faded. - */ -uint8_t TCOD_console_get_fade(void) { - return TCOD_ctx.fade; -} -/** - * Return the fade color. - * - * \return The current fading color. - */ -TCOD_color_t TCOD_console_get_fading_color(void) { - return TCOD_ctx.fading_color; -} -/** - * Draw a character on a console using the default colors. - * - * \param con A console pointer. - * \param x The X coordinate, the left-most position being 0. - * \param y The Y coordinate, the top-most position being 0. - * \param c The character code to place. - * \param flag A TCOD_bkgnd_flag_t flag. - */ -void TCOD_console_put_char(TCOD_console_t con, int x, int y, int c, TCOD_bkgnd_flag_t flag) { - int offset; - TCOD_console_data_t *dat = con ? (TCOD_console_data_t *)con : TCOD_ctx.root; - TCOD_IFNOT(dat != NULL && (unsigned)(x) < (unsigned)dat->w && (unsigned)(y) < (unsigned)dat->h) return; - offset = y * dat->w + x; - dat->ch_array[offset] = c; - TCOD_image_put_pixel(dat->fg_colors, x, y, dat->fore); - TCOD_console_set_char_background(con, x, y, dat->back, (TCOD_bkgnd_flag_t)flag); -} -/** - * Draw a character on the console with the given colors. - * - * \param con A console pointer. - * \param x The X coordinate, the left-most position being 0. - * \param y The Y coordinate, the top-most position being 0. - * \param c The character code to place. - * \param fore The foreground color. - * \param back The background color. This color will not be blended. - */ -void TCOD_console_put_char_ex(TCOD_console_t con, int x, int y, int c, TCOD_color_t fore, TCOD_color_t back) { - int offset; - TCOD_console_data_t *dat = con ? (TCOD_console_data_t *)con : TCOD_ctx.root; - TCOD_IFNOT(dat != NULL && (unsigned)(x) < (unsigned)dat->w && (unsigned)(y) < (unsigned)dat->h) return; - offset = y * dat->w + x; - dat->ch_array[offset] = c; - TCOD_image_put_pixel(dat->fg_colors, x, y, fore); - TCOD_image_put_pixel(dat->bg_colors, x, y, back); -} -/** - * Manually mark a region of a console as dirty. - */ -void TCOD_console_set_dirty(int dx, int dy, int dw, int dh) { - TCOD_sys_set_dirty(dx, dy, dw, dh); -} -/** - * Clear a console to its default colors and the space character code. - */ -void TCOD_console_clear(TCOD_console_t con) { - int i; - TCOD_console_data_t *dat = con ? (TCOD_console_data_t *)con : TCOD_ctx.root; - TCOD_IFNOT(dat != NULL) return; - for (i = 0; i < dat->w * dat->h; i++) { - dat->ch_array[i] = ' '; - } - TCOD_image_clear(dat->fg_colors, dat->fore); - TCOD_image_clear(dat->bg_colors, dat->back); - /* clear the sdl renderer cache */ - TCOD_sys_set_dirty(0, 0, dat->w, dat->h); -} -/** - * Return the background color of a console at x,y - * - * \param con A console pointer. - * \param x The X coordinate, the left-most position being 0. - * \param y The Y coordinate, the top-most position being 0. - * \return A TCOD_color_t struct with a copy of the background color. - */ -TCOD_color_t TCOD_console_get_char_background(TCOD_console_t con, int x, int y) { - TCOD_console_data_t *dat = con ? (TCOD_console_data_t *)con : TCOD_ctx.root; - TCOD_IFNOT(dat != NULL - && (unsigned)(x) < (unsigned)dat->w && (unsigned)(y) < (unsigned)dat->h) - return TCOD_black; - return TCOD_image_get_pixel(dat->bg_colors, x, y); -} -/** - * Change the foreground color of a console tile. - * - * \param con A console pointer. - * \param x The X coordinate, the left-most position being 0. - * \param y The Y coordinate, the top-most position being 0. - * \param col The foreground color to set. - */ -void TCOD_console_set_char_foreground(TCOD_console_t con, int x, int y, TCOD_color_t col) { - TCOD_console_data_t *dat = con ? (TCOD_console_data_t *)con : TCOD_ctx.root; - if ((unsigned)(x) >= (unsigned)dat->w || (unsigned)(y) >= (unsigned)dat->h) return; - TCOD_IFNOT(dat != NULL - && (unsigned)(x) < (unsigned)dat->w && (unsigned)(y) < (unsigned)dat->h) - return; - TCOD_image_put_pixel(dat->fg_colors, x, y, col); -} -/** - * Return the foreground color of a console at x,y - * - * \param con A console pointer. - * \param x The X coordinate, the left-most position being 0. - * \param y The Y coordinate, the top-most position being 0. - * \return A TCOD_color_t struct with a copy of the foreground color. - */ -TCOD_color_t TCOD_console_get_char_foreground(TCOD_console_t con, int x, int y) { - TCOD_console_data_t *dat = con ? (TCOD_console_data_t *)con : TCOD_ctx.root; - TCOD_IFNOT(dat != NULL - && (unsigned)(x) < (unsigned)dat->w && (unsigned)(y) < (unsigned)dat->h) - return TCOD_white; - return TCOD_image_get_pixel(dat->fg_colors, x, y); -} -/** - * Return a character code of a console at x,y - * - * \param con A console pointer. - * \param x The X coordinate, the left-most position being 0. - * \param y The Y coordinate, the top-most position being 0. - * \return The character code. - */ -int TCOD_console_get_char(TCOD_console_t con, int x, int y) { - TCOD_console_data_t *dat = con ? (TCOD_console_data_t *)con : TCOD_ctx.root; - TCOD_IFNOT(dat != NULL - && (unsigned)(x) < (unsigned)dat->w && (unsigned)(y) < (unsigned)dat->h) - return 0; - return dat->ch_array[y * dat->w + x]; -} -/** - * Blend a background color onto a console tile. - * - * \param con A console pointer. - * \param x The X coordinate, the left-most position being 0. - * \param y The Y coordinate, the top-most position being 0. - * \param col The background color to blend. - * \param flag The blend mode to use. - */ -void TCOD_console_set_char_background(TCOD_console_t con, int x, int y, TCOD_color_t col, TCOD_bkgnd_flag_t flag) { - TCOD_color_t *back; - int newr, newg, newb; - int alpha; - TCOD_console_data_t *dat = con ? (TCOD_console_data_t *)con : TCOD_ctx.root; - TCOD_IFNOT(dat != NULL - && (unsigned)(x) < (unsigned)dat->w && (unsigned)(y) < (unsigned)dat->h) - return; - back = &(TCOD_image_get_colors(dat->bg_colors)[y*dat->w + x]); - if (flag == TCOD_BKGND_DEFAULT) flag = dat->bkgnd_flag; - switch (flag & 0xff) { - case TCOD_BKGND_SET: *back = col; break; - case TCOD_BKGND_MULTIPLY: *back = TCOD_color_multiply(*back, col); break; - case TCOD_BKGND_LIGHTEN: - back->r = MAX(back->r, col.r); - back->g = MAX(back->g, col.g); - back->b = MAX(back->b, col.b); - break; - case TCOD_BKGND_DARKEN: - back->r = MIN(back->r, col.r); - back->g = MIN(back->g, col.g); - back->b = MIN(back->b, col.b); - break; - case TCOD_BKGND_SCREEN: - /* newbk = white - (white - oldbk) * (white - curbk) */ - back->r = (uint8_t)(255 - (int)(255 - back->r)*(255 - col.r) / 255); - back->g = (uint8_t)(255 - (int)(255 - back->g)*(255 - col.g) / 255); - back->b = (uint8_t)(255 - (int)(255 - back->b)*(255 - col.b) / 255); - break; - case TCOD_BKGND_COLOR_DODGE: - /* newbk = curbk / (white - oldbk) */ - if (back->r != 255) newr = (int)(255 * col.r) / (255 - back->r); - else newr = 255; - if (back->g != 255) newg = (int)(255 * col.g) / (255 - back->g); - else newg = 255; - if (back->b != 255) newb = (int)(255 * col.b) / (255 - back->b); - else newb = 255; - back->r = (uint8_t)CLAMP(0, 255, newr); - back->g = (uint8_t)CLAMP(0, 255, newg); - back->b = (uint8_t)CLAMP(0, 255, newb); - break; - case TCOD_BKGND_COLOR_BURN: - /* newbk = white - (white - oldbk) / curbk */ - if (col.r > 0) newr = 255 - (int)(255 * (255 - back->r)) / col.r; - else newr = 0; - if (col.g > 0) newg = 255 - (int)(255 * (255 - back->g)) / col.g; - else newg = 0; - if (col.b > 0) newb = 255 - (int)(255 * (255 - back->b)) / col.b; - else newb = 0; - back->r = (uint8_t)CLAMP(0, 255, newr); - back->g = (uint8_t)CLAMP(0, 255, newg); - back->b = (uint8_t)CLAMP(0, 255, newb); - break; - case TCOD_BKGND_ADD: - /* newbk = oldbk + curbk */ - newr = (int)(back->r) + col.r; - newg = (int)(back->g) + col.g; - newb = (int)(back->b) + col.b; - back->r = (uint8_t)CLAMP(0, 255, newr); - back->g = (uint8_t)CLAMP(0, 255, newg); - back->b = (uint8_t)CLAMP(0, 255, newb); - break; - case TCOD_BKGND_ADDA: - alpha = (flag >> 8); - /* newbk = oldbk + alpha * curbk */ - newr = (int)(back->r) + alpha * col.r / 255; - newg = (int)(back->g) + alpha * col.g / 255; - newb = (int)(back->b) + alpha * col.b / 255; - back->r = (uint8_t)CLAMP(0, 255, newr); - back->g = (uint8_t)CLAMP(0, 255, newg); - back->b = (uint8_t)CLAMP(0, 255, newb); - break; - case TCOD_BKGND_BURN: - /* newbk = oldbk + curbk - white */ - newr = (int)(back->r) + col.r - 255; - newg = (int)(back->g) + col.g - 255; - newb = (int)(back->b) + col.b - 255; - back->r = (uint8_t)CLAMP(0, 255, newr); - back->g = (uint8_t)CLAMP(0, 255, newg); - back->b = (uint8_t)CLAMP(0, 255, newb); - break; - case TCOD_BKGND_OVERLAY: - /* newbk = curbk.x <= 0.5 ? 2*curbk*oldbk : white - 2*(white-curbk)*(white-oldbk) */ - newr = col.r <= 128 ? 2 * (int)(col.r) * back->r / 255 : 255 - 2 * (int)(255 - col.r)*(255 - back->r) / 255; - newg = col.g <= 128 ? 2 * (int)(col.g) * back->g / 255 : 255 - 2 * (int)(255 - col.g)*(255 - back->g) / 255; - newb = col.b <= 128 ? 2 * (int)(col.b) * back->b / 255 : 255 - 2 * (int)(255 - col.b)*(255 - back->b) / 255; - back->r = (uint8_t)CLAMP(0, 255, newr); - back->g = (uint8_t)CLAMP(0, 255, newg); - back->b = (uint8_t)CLAMP(0, 255, newb); - break; - case TCOD_BKGND_ALPH: - /* newbk = (1.0f-alpha)*oldbk + alpha*(curbk-oldbk) */ - alpha = (flag >> 8); - *back = TCOD_color_lerp(*back, col, (float)(alpha / 255.0f)); - break; - default: break; - } -} -/** - * Change a character on a console tile, without changing its colors. - * - * \param con A console pointer. - * \param x The X coordinate, the left-most position being 0. - * \param y The Y coordinate, the top-most position being 0. - * \param c The character code to set. - */ -void TCOD_console_set_char(TCOD_console_t con, int x, int y, int c) { - TCOD_console_data_t *dat = con ? (TCOD_console_data_t *)con : TCOD_ctx.root; - if ((unsigned)(x) >= (unsigned)dat->w || (unsigned)(y) >= (unsigned)dat->h) return; - dat->ch_array[y * dat->w + x] = c; -} - -static void TCOD_console_clamp(int cx, int cy, int cw, int ch, int *x, int *y, int *w, int *h) { - if (*x + *w > cw) *w = cw - *x; - if (*y + *h > ch) *h = ch - *y; - if (*x < cx) { - *w -= cx - *x; - *x = cx; - } - if (*y < cy) { - *h -= cy - *y; - *y = cy; - } -} -/** - * Draw a rectangle onto a console. - * - * \param con A console pointer. - * \param x The starting region, the left-most position being 0. - * \param y The starting region, the top-most position being 0. - * \param rw The width of the rectangle. - * \param rh The height of the rectangle. - * \param clear If true the drawing region will be filled with spaces. - * \param flag The blending flag to use. - */ -void TCOD_console_rect(TCOD_console_t con, int x, int y, int rw, int rh, bool clear, TCOD_bkgnd_flag_t flag) { - int cx, cy; - TCOD_console_data_t *dat = con ? (TCOD_console_data_t *)con : TCOD_ctx.root; - TCOD_IFNOT(dat != NULL) return; - TCOD_ASSERT((unsigned)(x) < (unsigned)dat->w && (unsigned)(y) < (unsigned)dat->h); - TCOD_ASSERT(x + rw <= dat->w && y + rh <= dat->h); - - TCOD_console_clamp(0, 0, dat->w, dat->h, &x, &y, &rw, &rh); - TCOD_IFNOT(rw > 0 && rh > 0) return; - for (cx = x; cx < x + rw; cx++) { - for (cy = y; cyback, flag); - if (clear) { - dat->ch_array[cx + cy*dat->w] = ' '; - } - } - } -} -/** - * Draw a horizontal line using the default colors. - * - * \param con A console pointer. - * \param x The starting X coordinate, the left-most position being 0. - * \param y The starting Y coordinate, the top-most position being 0. - * \param l The width of the line. - * \param flag The blending flag. - * - * This function makes assumptions about the fonts character encoding. - * It will fail if the font encoding is not `cp437`. - */ -void TCOD_console_hline(TCOD_console_t con,int x,int y, int l, TCOD_bkgnd_flag_t flag) { - int i; - for (i=x; i< x+l; i++) TCOD_console_put_char(con,i,y,TCOD_CHAR_HLINE,flag); -} -/** - * Draw a vertical line using the default colors. - * - * \param con A console pointer. - * \param x The starting X coordinate, the left-most position being 0. - * \param y The starting Y coordinate, the top-most position being 0. - * \param l The height of the line. - * \param flag The blending flag. - * - * This function makes assumptions about the fonts character encoding. - * It will fail if the font encoding is not `cp437`. - */ -void TCOD_console_vline(TCOD_console_t con,int x,int y, int l, TCOD_bkgnd_flag_t flag) { - int i; - for (i=y; i< y+l; i++) TCOD_console_put_char(con,x,i,TCOD_CHAR_VLINE,flag); -} - -char *TCOD_console_vsprint(const char *fmt, va_list ap) { - #define NB_BUFFERS 10 - #define INITIAL_SIZE 512 - /* several static buffers in case the function is used more than once in a single function call */ - static char *msg[NB_BUFFERS]={NULL}; - static int buflen[NB_BUFFERS]={0}; - static int curbuf=0; - char *ret; - bool ok=false; - if (!msg[0]) { - int i; - for (i=0; i < NB_BUFFERS; i++) { - buflen[i]=INITIAL_SIZE; - msg[i]=(char *)calloc(sizeof(char),INITIAL_SIZE); - } - } - do { - /* warning ! depending on the compiler, vsnprintf return -1 or - the expected string length if the buffer is not big enough */ - int len = stbsp_vsnprintf(msg[curbuf],buflen[curbuf],fmt,ap); - ok=true; - if (len < 0 || len >= buflen[curbuf]) { - /* buffer too small. */ - if ( len > 0 ) { - while ( buflen[curbuf] < len+1 ) buflen[curbuf]*=2; - } else { - buflen[curbuf]*=2; - } - free( msg[curbuf] ); - msg[curbuf]=(char *)calloc(sizeof(char),buflen[curbuf]); - ok=false; - } - } while (! ok); - ret=msg[curbuf]; - curbuf = (curbuf+1)%NB_BUFFERS; - return ret; -} -/** - * Print a string inside of a framed region on a console, using default - * colors and alignment. - * - * \param con A console pointer. - * \param x The starting X coordinate, the left-most position being 0. - * \param y The starting Y coordinate, the top-most position being 0. - * \param w The width of the frame. - * \param h The height of the frame. - * \param empty If true the characters inside of the frame will be cleared - * with spaces. - * \param flag The blending flag. - * \param fmt A format string as if passed to printf. - * \param ... Variadic arguments as if passed to printf. - * - * This function makes assumptions about the fonts character encoding. - * It will fail if the font encoding is not `cp437`. - */ -void TCOD_console_print_frame(TCOD_console_t con,int x,int y,int w,int h, bool empty, TCOD_bkgnd_flag_t flag, const char *fmt, ...) { - TCOD_console_data_t *dat=con ? (TCOD_console_data_t *)con : TCOD_ctx.root; - TCOD_console_put_char(con,x,y,TCOD_CHAR_NW,flag); - TCOD_console_put_char(con,x+w-1,y,TCOD_CHAR_NE,flag); - TCOD_console_put_char(con,x,y+h-1,TCOD_CHAR_SW,flag); - TCOD_console_put_char(con,x+w-1,y+h-1,TCOD_CHAR_SE,flag); - TCOD_console_hline(con,x+1,y,w-2,flag); - TCOD_console_hline(con,x+1,y+h-1,w-2,flag); - if ( h > 2 ) { - TCOD_console_vline(con,x,y+1,h-2,flag); - TCOD_console_vline(con,x+w-1,y+1,h-2,flag); - if ( empty ) { - TCOD_console_rect(con,x+1,y+1,w-2,h-2,true,flag); - } - } - if (fmt) { - va_list ap; - int xs; - TCOD_color_t tmp; - char *title; - va_start(ap,fmt); - title = TCOD_console_vsprint(fmt,ap); - va_end(ap); - title[w-3]=0; /* truncate if needed */ - xs = x + (w-(int)strlen(title)-2)/2; - tmp=dat->back; /* swap colors */ - dat->back=dat->fore; - dat->fore=tmp; - TCOD_console_print_ex(con,xs,y,TCOD_BKGND_SET,TCOD_LEFT," %s ",title); - tmp=dat->back; /* swap colors */ - dat->back=dat->fore; - dat->fore=tmp; - } -} -/** - * Print a string on a console, using default colors and alignment. - * - * \param con A console pointer. - * \param x The starting X coordinate, the left-most position being 0. - * \param y The starting Y coordinate, the top-most position being 0. - * \param fmt A format string as if passed to printf. - * \param ... Variadic arguments as if passed to printf. - */ -void TCOD_console_print(TCOD_console_t con,int x, int y, const char *fmt, ...) { - va_list ap; - TCOD_console_data_t *dat=con ? (TCOD_console_data_t *)con : TCOD_ctx.root; - TCOD_IFNOT ( dat != NULL ) return; - va_start(ap,fmt); - TCOD_console_print_internal(con,x,y,0,0,dat->bkgnd_flag, - dat->alignment,TCOD_console_vsprint(fmt,ap), false, false); - va_end(ap); -} -/** - * Print a string on a console, using default colors. - * - * \param con A console pointer. - * \param x The starting X coordinate, the left-most position being 0. - * \param y The starting Y coordinate, the top-most position being 0. - * \param flag The blending flag. - * \param alignment The font alignment to use. - * \param fmt A format string as if passed to printf. - * \param ... Variadic arguments as if passed to printf. - */ -void TCOD_console_print_ex(TCOD_console_t con,int x, int y, - TCOD_bkgnd_flag_t flag, TCOD_alignment_t alignment, const char *fmt, ...) { - va_list ap; - TCOD_console_data_t *dat=con ? (TCOD_console_data_t *)con : TCOD_ctx.root; - TCOD_IFNOT ( dat != NULL ) return; - va_start(ap,fmt); - TCOD_console_print_internal(con,x,y,0,0,flag,alignment, - TCOD_console_vsprint(fmt,ap), false, false); - va_end(ap); -} -/** - * Print a string on a console constrained to a rectangle, using default - * colors and alignment. - * - * \param con A console pointer. - * \param x The starting X coordinate, the left-most position being 0. - * \param y The starting Y coordinate, the top-most position being 0. - * \param w The width of the region. - * If 0 then the maximum width will be used. - * \param h The height of the region. - * If 0 then the maximum height will be used. - * \param fmt A format string as if passed to printf. - * \param ... Variadic arguments as if passed to printf. - * \return The number of lines actually printed. - */ -int TCOD_console_print_rect(TCOD_console_t con,int x, int y, int w, int h, const char *fmt, ...) { - int ret; - va_list ap; - TCOD_console_data_t *dat=con ? (TCOD_console_data_t *)con : TCOD_ctx.root; - TCOD_IFNOT ( dat != NULL ) return 0; - va_start(ap,fmt); - ret = TCOD_console_print_internal(con,x,y,w,h,dat->bkgnd_flag,dat->alignment, - TCOD_console_vsprint(fmt,ap), true, false); - va_end(ap); - return ret; -} -/** - * Print a string on a console constrained to a rectangle, using default - * colors. - * - * \param con A console pointer. - * \param x The starting X coordinate, the left-most position being 0. - * \param y The starting Y coordinate, the top-most position being 0. - * \param w The width of the region. - * If 0 then the maximum width will be used. - * \param h The height of the region. - * If 0 then the maximum height will be used. - * \param flag The blending flag. - * \param alignment The font alignment to use. - * \param fmt A format string as if passed to printf. - * \param ... Variadic arguments as if passed to printf. - * \return The number of lines actually printed. - */ -int TCOD_console_print_rect_ex(TCOD_console_t con,int x, int y, int w, int h, - TCOD_bkgnd_flag_t flag, TCOD_alignment_t alignment,const char *fmt, ...) { - int ret; - va_list ap; - va_start(ap,fmt); - ret = TCOD_console_print_internal(con,x,y,w,h,flag,alignment,TCOD_console_vsprint(fmt,ap), true, false); - va_end(ap); - return ret; -} -/** - * Return the number of lines that would be printed by the - * - * \param con A console pointer. - * \param x The starting X coordinate, the left-most position being 0. - * \param y The starting Y coordinate, the top-most position being 0. - * \param w The width of the region. - * If 0 then the maximum width will be used. - * \param h The height of the region. - * If 0 then the maximum height will be used. - * \param fmt A format string as if passed to printf. - * \param ... Variadic arguments as if passed to printf. - * \return The number of lines that would have been printed. - */ -int TCOD_console_get_height_rect(TCOD_console_t con,int x, int y, int w, int h, const char *fmt, ...) { - int ret; - va_list ap; - va_start(ap,fmt); - ret = TCOD_console_print_internal(con,x,y,w,h,TCOD_BKGND_NONE,TCOD_LEFT,TCOD_console_vsprint(fmt,ap), true, true); - va_end(ap); - return ret; -} - -/* non public methods */ -int TCOD_console_stringLength(const unsigned char *s) { - int l=0; - while (*s) { - if ( *s == (int)TCOD_COLCTRL_FORE_RGB || *s == (int)TCOD_COLCTRL_BACK_RGB ) s+=3; - else if ( (unsigned)(*s) > (unsigned)TCOD_COLCTRL_STOP ) l++; - s++; - } - return l; -} - -unsigned char * TCOD_console_forward(unsigned char *s,int l) { - while ( *s && l > 0 ) { - if ( *s == (int)TCOD_COLCTRL_FORE_RGB || *s == (int)TCOD_COLCTRL_BACK_RGB ) s+=3; - else if ( *s > (int)TCOD_COLCTRL_STOP ) l--; - s++; - } - return s; -} - -unsigned char *TCOD_console_strchr(unsigned char *s, unsigned char c) { - while ( *s && *s != c ) { - if ( *s == (int)TCOD_COLCTRL_FORE_RGB || *s == (int)TCOD_COLCTRL_BACK_RGB ) s+=3; - s++; - } - return (*s ? s : NULL); -} - -int TCOD_console_print_internal(TCOD_console_t con,int x,int y, int rw, int rh, TCOD_bkgnd_flag_t flag, - TCOD_alignment_t align, char *msg, bool can_split, bool count_only) { - unsigned char *c=(unsigned char *)msg; - int cx=0,cy=y; - int minx,maxx,miny,maxy; - TCOD_color_t oldFore; - TCOD_color_t oldBack; - TCOD_console_data_t *dat=con ? (TCOD_console_data_t *)con : TCOD_ctx.root; - TCOD_IFNOT ( dat != NULL - && (unsigned)(x) < (unsigned)dat->w && (unsigned)(y) < (unsigned)dat->h ) - return 0; - TCOD_IFNOT(msg != NULL) return 0; - if ( rh == 0 ) rh = dat->h-y; - if ( rw == 0 ) switch(align) { - case TCOD_LEFT : rw = dat->w-x; break; - case TCOD_RIGHT : rw=x+1; break; - case TCOD_CENTER : default : rw=dat->w; break; - } - oldFore=dat->fore; - oldBack=dat->back; - miny=y; - maxy=dat->h-1; - if (rh > 0) maxy=MIN(maxy,y+rh-1); - switch (align) { - case TCOD_LEFT : minx=MAX(0,x); maxx=MIN(dat->w-1,x+rw-1); break; - case TCOD_RIGHT : minx=MAX(0,x-rw+1); maxx=MIN(dat->w-1,x); break; - case TCOD_CENTER : default : minx=MAX(0,x-rw/2); maxx=MIN(dat->w-1,x+rw/2); break; - } - - do { - /* get \n delimited sub-message */ - unsigned char *end=TCOD_console_strchr(c,'\n'); - char bak=0; - int cl; - unsigned char *split=NULL; - if ( end ) *end=0; - cl= TCOD_console_stringLength(c); - /* find starting x */ - switch (align) { - case TCOD_LEFT : cx=x; break; - case TCOD_RIGHT : cx=x-cl+1; break; - case TCOD_CENTER : cx= x-cl/2;break; - } - /* check if the string is completely out of the minx,miny,maxx,maxy frame */ - if ( cy >= miny && cy <= maxy && cx <= maxx && cx+cl -1 >= minx ) { - if ( can_split && cy <= maxy ) { - /* if partially out of screen, try to split the sub-message */ - if ( cx < minx ) split = TCOD_console_forward(c, align == TCOD_CENTER ? cl-2*(minx-cx) : cl-(minx-cx)); - else if ( align == TCOD_CENTER ) { - if ( cx + cl/2 > maxx+1 ) split = TCOD_console_forward(c, maxx+1 - cx); - } else { - if ( cx + cl > maxx+1 ) split = TCOD_console_forward(c, maxx+1 - cx); - } - } - if ( split ) { - unsigned char *oldsplit=split; - while ( ! isspace(*split) && split > c ) split --; - if (end) *end='\n'; - if (!isspace(*split) ) { - split=oldsplit; - } - end=split; - bak=*split; - *split=0; - cl=TCOD_console_stringLength(c); - switch (align) { - case TCOD_LEFT : cx=x; break; - case TCOD_RIGHT : cx=x-cl+1; break; - case TCOD_CENTER : cx= x-cl/2;break; - } - } - if ( cx < minx ) { - /* truncate left part */ - c += minx-cx; - cl -= minx-cx; - cx=minx; - } - if ( cx + cl > maxx+1 ) { - /* truncate right part */ - split = TCOD_console_forward(c, maxx+1 - cx); - *split=0; - } - /* render the sub-message */ - if ( cy >= 0 && cy < dat->h ) - while (*c) { - if ( *c >= TCOD_COLCTRL_1 && *c <= TCOD_COLCTRL_NUMBER ) { - dat->fore=color_control_fore[(int)(*c)-1]; - dat->back=color_control_back[(int)(*c)-1]; - } else if ( *c == TCOD_COLCTRL_FORE_RGB ) { - c++; - dat->fore.r=*c++; - dat->fore.g=*c++; - dat->fore.b=*c; - } else if ( *c == TCOD_COLCTRL_BACK_RGB ) { - c++; - dat->back.r=*c++; - dat->back.g=*c++; - dat->back.b=*c; - } else if ( *c == TCOD_COLCTRL_STOP ) { - dat->fore=oldFore; - dat->back=oldBack; - } else { - if (! count_only) TCOD_console_put_char(con,cx,cy,(int)(*c),flag); - cx++; - } - c++; - } - } - if ( end ) { - /* next line */ - if ( split && ! isspace(bak) ) { - *end=bak; - c=end; - } else { - c=end+1; - } - cy++; - } else c=NULL; - } while ( c && cy < dat->h && (rh == 0 || cy < y+rh) ); - return cy-y+1; -} - -#ifndef NO_UNICODE - -wchar_t *TCOD_console_strchr_utf(wchar_t *s, char c) { - while ( *s && *s != c ) { - if ( *s == (int)TCOD_COLCTRL_FORE_RGB || *s == (int)TCOD_COLCTRL_BACK_RGB ) s+=3; - s++; - } - return (*s ? s : NULL); -} - -void TCOD_console_map_string_to_font_utf(const wchar_t *s, int fontCharX, int fontCharY) { - TCOD_IFNOT(s != NULL) return; - while (*s) { - TCOD_sys_map_ascii_to_font(*s, fontCharX, fontCharY); - fontCharX++; - if ( fontCharX == TCOD_ctx.fontNbCharHoriz ) { - fontCharX=0; - fontCharY++; - } - s++; - } -} - -wchar_t *TCOD_console_vsprint_utf(const wchar_t *fmt, va_list ap) { - #define NB_BUFFERS 10 - #define INITIAL_SIZE 512 - /* several static buffers in case the function is used more than once in a single function call */ - static wchar_t *msg[NB_BUFFERS]={NULL}; - static int buflen[NB_BUFFERS]={0}; - static int curbuf=0; - wchar_t *ret; - bool ok=false; - if (!msg[0]) { - int i; - for (i=0; i < NB_BUFFERS; i++) { - buflen[i]=INITIAL_SIZE; - msg[i]=(wchar_t *)calloc(sizeof(wchar_t),INITIAL_SIZE); - } - } - do { - /* warning ! depending on the compiler, vsnprintf return -1 or - the expected string length if the buffer is not big enough */ - int len = vsnwprintf(msg[curbuf],buflen[curbuf],fmt,ap); - ok=true; - if (len < 0 || len >= buflen[curbuf]) { - /* buffer too small. */ - if ( len > 0 ) { - while ( buflen[curbuf] < len+1 ) buflen[curbuf]*=2; - } else { - buflen[curbuf]*=2; - } - free( msg[curbuf] ); - msg[curbuf]=(wchar_t *)calloc(sizeof(wchar_t),buflen[curbuf]); - ok=false; - } - } while (! ok); - ret=msg[curbuf]; - curbuf = (curbuf+1)%NB_BUFFERS; - return ret; -} - - -int TCOD_console_stringLength_utf(const wchar_t *s) { - int l=0; - while (*s) { - if ( *s == (int)TCOD_COLCTRL_FORE_RGB || *s == (int)TCOD_COLCTRL_BACK_RGB ) s+=3; - else if ( *s > (int)TCOD_COLCTRL_STOP ) l++; - s++; - } - return l; -} - -wchar_t * TCOD_console_forward_utf(wchar_t *s,int l) { - while ( *s && l > 0 ) { - if ( *s == (int)TCOD_COLCTRL_FORE_RGB || *s == (int)TCOD_COLCTRL_BACK_RGB ) s+=3; - else if ( *s > (int)TCOD_COLCTRL_STOP ) l--; - s++; - } - return s; -} - -int TCOD_console_print_internal_utf(TCOD_console_t con,int x,int y, int rw, int rh, TCOD_bkgnd_flag_t flag, - TCOD_alignment_t align, wchar_t *msg, bool can_split, bool count_only) { - wchar_t *c=msg; - int cx=0,cy=y; - int minx,maxx,miny,maxy; - TCOD_color_t oldFore; - TCOD_color_t oldBack; - TCOD_console_data_t *dat=con ? (TCOD_console_data_t *)con : TCOD_ctx.root; - TCOD_IFNOT ( dat != NULL - && (unsigned)(x) < (unsigned)dat->w && (unsigned)(y) < (unsigned)dat->h ) - return 0; - TCOD_IFNOT(msg != NULL) return 0; - if ( rh == 0 ) rh = dat->h-y; - if ( rw == 0 ) switch(align) { - case TCOD_LEFT : rw = dat->w-x; break; - case TCOD_RIGHT : rw=x+1; break; - case TCOD_CENTER : default : rw=dat->w; break; - } - oldFore=dat->fore; - oldBack=dat->back; - miny=y; - maxy=dat->h-1; - if (rh > 0) maxy=MIN(maxy,y+rh-1); - switch (align) { - case TCOD_LEFT : minx=MAX(0,x); maxx=MIN(dat->w-1,x+rw-1); break; - case TCOD_RIGHT : minx=MAX(0,x-rw+1); maxx=MIN(dat->w-1,x); break; - case TCOD_CENTER : default : minx=MAX(0,x-rw/2); maxx=MIN(dat->w-1,x+rw/2); break; - } - - do { - /* get \n delimited sub-message */ - wchar_t *end=TCOD_console_strchr_utf(c,'\n'); - wchar_t bak=0; - int cl; - wchar_t *split=NULL; - if ( end ) *end=0; - cl= TCOD_console_stringLength_utf(c); - /* find starting x */ - switch (align) { - case TCOD_LEFT : cx=x; break; - case TCOD_RIGHT : cx=x-cl+1; break; - case TCOD_CENTER : cx= x-cl/2;break; - } - /* check if the string is completely out of the minx,miny,maxx,maxy frame */ - if ( cy >= miny && cy <= maxy && cx <= maxx && cx+cl -1 >= minx ) { - if ( can_split && cy < maxy ) { - /* if partially out of screen, try to split the sub-message */ - if ( cx < minx ) split = TCOD_console_forward_utf(c, align == TCOD_CENTER ? cl-2*(minx-cx) : cl-(minx-cx)); - else if ( align==TCOD_CENTER ) { - if ( cx + cl/2 > maxx+1 ) split = TCOD_console_forward_utf(c, maxx+1 - cx); - } else { - if ( cx + cl > maxx+1 ) split = TCOD_console_forward_utf(c, maxx+1 - cx); - } - } - if ( split ) { - wchar_t *oldsplit=split; - while ( ! iswspace(*split) && split > c ) split --; - if (end) *end='\n'; - if (!iswspace(*split) ) { - split=oldsplit; - } - end=split; - bak=*split; - *split=0; - cl=TCOD_console_stringLength_utf(c); - switch (align) { - case TCOD_LEFT : cx=x; break; - case TCOD_RIGHT : cx=x-cl+1; break; - case TCOD_CENTER : cx= x-cl/2;break; - } - } - if ( cx < minx ) { - /* truncate left part */ - c += minx-cx; - cl -= minx-cx; - cx=minx; - } - if ( cx + cl > maxx+1 ) { - /* truncate right part */ - split = TCOD_console_forward_utf(c, maxx+1 - cx); - *split=0; - } - /* render the sub-message */ - if ( cy >= 0 && cy < dat->h ) - while (*c) { - if ( *c >= TCOD_COLCTRL_1 && *c <= TCOD_COLCTRL_NUMBER ) { - dat->fore=color_control_fore[(int)(*c)-1]; - dat->back=color_control_back[(int)(*c)-1]; - } else if ( *c == TCOD_COLCTRL_FORE_RGB ) { - c++; - dat->fore.r=(uint8_t)(*c++); - dat->fore.g=(uint8_t)(*c++); - dat->fore.b=(uint8_t)(*c); - } else if ( *c == TCOD_COLCTRL_BACK_RGB ) { - c++; - dat->back.r=(uint8_t)(*c++); - dat->back.g=(uint8_t)(*c++); - dat->back.b=(uint8_t)(*c); - } else if ( *c == TCOD_COLCTRL_STOP ) { - dat->fore=oldFore; - dat->back=oldBack; - } else { - if (! count_only) TCOD_console_put_char(con,cx,cy,(int)(*c),flag); - cx++; - } - c++; - } - } - if ( end ) { - /* next line */ - if ( split && ! iswspace(bak) ) { - *end=bak; - c=end; - } else { - c=end+1; - } - cy++; - } else c=NULL; - } while ( c && cy < dat->h && (rh == 0 || cy < y+rh) ); - return cy-y+1; -} - -void TCOD_console_print_utf(TCOD_console_t con,int x, int y, const wchar_t *fmt, ...) { - va_list ap; - TCOD_console_data_t *dat=con ? (TCOD_console_data_t *)con : TCOD_ctx.root; - TCOD_IFNOT ( dat != NULL ) return; - va_start(ap,fmt); - TCOD_console_print_internal_utf(con,x,y,0,0,dat->bkgnd_flag,dat->alignment, - TCOD_console_vsprint_utf(fmt,ap), false, false); - va_end(ap); -} - -void TCOD_console_print_ex_utf(TCOD_console_t con,int x, int y, - TCOD_bkgnd_flag_t flag, TCOD_alignment_t alignment, const wchar_t *fmt, ...) { - va_list ap; - TCOD_console_data_t *dat=con ? (TCOD_console_data_t *)con : TCOD_ctx.root; - TCOD_IFNOT ( dat != NULL ) return; - va_start(ap,fmt); - TCOD_console_print_internal_utf(con,x,y,0,0,flag,alignment,TCOD_console_vsprint_utf(fmt,ap), false, false); - va_end(ap); -} - -int TCOD_console_print_rect_utf(TCOD_console_t con,int x, int y, int w, int h, - const wchar_t *fmt, ...) { - int ret; - va_list ap; - TCOD_console_data_t *dat=con ? (TCOD_console_data_t *)con : TCOD_ctx.root; - TCOD_IFNOT ( dat != NULL ) return 0; - va_start(ap,fmt); - ret = TCOD_console_print_internal_utf(con,x,y,w,h,dat->bkgnd_flag,dat->alignment, - TCOD_console_vsprint_utf(fmt,ap), true, false); - va_end(ap); - return ret; -} - -int TCOD_console_print_rect_ex_utf(TCOD_console_t con,int x, int y, int w, int h, - TCOD_bkgnd_flag_t flag, TCOD_alignment_t alignment, const wchar_t *fmt, ...) { - int ret; - va_list ap; - va_start(ap,fmt); - ret=TCOD_console_print_internal_utf(con,x,y,w,h,flag,alignment,TCOD_console_vsprint_utf(fmt,ap), true, false); - va_end(ap); - return ret; -} - -int TCOD_console_get_height_rect_utf(TCOD_console_t con,int x, int y, int w, int h, const wchar_t *fmt, ...) { - int ret; - va_list ap; - va_start(ap,fmt); - ret = TCOD_console_print_internal_utf(con,x,y,w,h,TCOD_BKGND_NONE,TCOD_LEFT,TCOD_console_vsprint_utf(fmt,ap), true, true); - va_end(ap); - return ret; -} - -#endif -/** - * \brief Initialize the libtcod graphical engine. - * - * \param w The width in tiles. - * \param h The height in tiles. - * \param title The title for the window. - * \param fullscreen Fullscreen option. - * \param renderer Which renderer to use when rendering the console. - * - * You may want to call TCOD_console_set_custom_font BEFORE calling this - * function. By default this function loads libtcod's `terminal.png` image - * from the working directory. - */ -void TCOD_console_init_root(int w, int h, const char*title, bool fullscreen, TCOD_renderer_t renderer) { - TCOD_IF(w > 0 && h > 0) { - TCOD_console_data_t *con=(TCOD_console_data_t *)calloc(sizeof(TCOD_console_data_t),1); - int i; - con->w=w; - con->h=h; - TCOD_ctx.root=con; -#ifndef TCOD_BARE - TCOD_ctx.renderer=renderer; -#endif - for (i=0; i < TCOD_COLCTRL_NUMBER; i++) { - color_control_fore[i]=TCOD_white; - color_control_back[i]=TCOD_black; - } - TCOD_console_init((TCOD_console_t)con,title,fullscreen); - } -} - -static void TCOD_console_data_alloc(TCOD_console_data_t *dat) { - dat->ch_array = (int *)calloc(sizeof(int), dat->w*dat->h); - dat->fg_colors = TCOD_image_new(dat->w, dat->h); - dat->bg_colors = TCOD_image_new(dat->w, dat->h); -} - -bool TCOD_console_init(TCOD_console_t con,const char *title, bool fullscreen) { - int i; - TCOD_console_data_t *dat=con ? (TCOD_console_data_t *)con : TCOD_ctx.root; - TCOD_IFNOT(dat != NULL) return false; - dat->fore=TCOD_white; - dat->back=TCOD_black; - - TCOD_console_data_alloc(dat); - - dat->bkgnd_flag=TCOD_BKGND_NONE; - dat->alignment=TCOD_LEFT; - for (i=0; i< dat->w*dat->h; i++) { - dat->ch_array[i] = ' '; - } - if ( title ) { - if (! TCOD_sys_init(dat, fullscreen) ) return false; - TCOD_sys_set_window_title(title); - } - return true; -} - -void TCOD_console_set_default_foreground(TCOD_console_t con,TCOD_color_t col) { - TCOD_console_data_t *dat=con ? (TCOD_console_data_t *)con : TCOD_ctx.root; - TCOD_IFNOT(dat != NULL) return; - dat->fore=col; -} - -void TCOD_console_set_default_background(TCOD_console_t con,TCOD_color_t col) { - TCOD_console_data_t *dat=con ? (TCOD_console_data_t *)con : TCOD_ctx.root; - TCOD_IFNOT(dat != NULL) return; - dat->back=col; -} - -TCOD_color_t TCOD_console_get_default_foreground(TCOD_console_t con) { - TCOD_console_data_t *dat=con ? (TCOD_console_data_t *)con : TCOD_ctx.root; - TCOD_IFNOT(dat != NULL) return TCOD_white; - return dat->fore; -} - -TCOD_color_t TCOD_console_get_default_background(TCOD_console_t con) { - TCOD_console_data_t *dat=con ? (TCOD_console_data_t *)con : TCOD_ctx.root; - TCOD_IFNOT(dat != NULL) return TCOD_black; - return dat->back; -} - -int TCOD_console_get_width(TCOD_console_t con) { - TCOD_console_data_t *dat=con ? (TCOD_console_data_t *)con : TCOD_ctx.root; - TCOD_IFNOT(dat != NULL) return 0; - return dat->w; -} - -int TCOD_console_get_height(TCOD_console_t con) { - TCOD_console_data_t *dat=con ? (TCOD_console_data_t *)con : TCOD_ctx.root; - TCOD_IFNOT(dat != NULL) return 0; - return dat->h; -} - -TCOD_image_t TCOD_console_get_foreground_color_image(TCOD_console_t con) { - TCOD_console_data_t *dat = con ? (TCOD_console_data_t *)con : TCOD_ctx.root; - TCOD_IFNOT(dat != NULL) return NULL; - return dat->fg_colors; -} - -TCOD_image_t TCOD_console_get_background_color_image(TCOD_console_t con) { - TCOD_console_data_t *dat = con ? (TCOD_console_data_t *)con : TCOD_ctx.root; - TCOD_IFNOT(dat != NULL) return NULL; - return dat->bg_colors; -} -/** - * \brief Set a font image to be loaded during initialization. - * - * \param fontFile The path to a font image. - * \param flags A TCOD_font_flags_t bit-field describing the font image - * contents. - * \param nb_char_horiz The number of columns in the font image. - * \param nb_char_vertic The number of rows in the font image. - * - * `fontFile` will be case-sensitive depending on the platform. - */ -void TCOD_console_set_custom_font(const char *fontFile, int flags,int nb_char_horiz, int nb_char_vertic) { - TCOD_sys_set_custom_font(fontFile, nb_char_horiz, nb_char_vertic, flags); -} -/** - * \brief Remap a character code to a tile. - * - * \param asciiCode Character code to modify. - * \param fontCharX X tile-coordinate, starting from the left at zero. - * \param fontCharY Y tile-coordinate, starting from the top at zero. - * - * X,Y parameters are the coordinate of the tile, not pixel-coordinates. - */ -void TCOD_console_map_ascii_code_to_font(int asciiCode, int fontCharX, int fontCharY) { - /* cannot change mapping before initRoot is called */ - TCOD_IFNOT(TCOD_ctx.root != NULL) return; - TCOD_sys_map_ascii_to_font(asciiCode, fontCharX, fontCharY); -} -/** - * \brief Remap a series of character codes to a row of tiles. - * - * \param asciiCode The starting character code. - * \param nbCodes Number of character codes to assign. - * \param fontCharX First X tile-coordinate, starting from the left at zero. - * \param fontCharY First Y tile-coordinate, starting from the top at zero. - * - * This function always assigns tiles in row-major order, even if the - * TCOD_FONT_LAYOUT_ASCII_INCOL flag was set. - */ -void TCOD_console_map_ascii_codes_to_font(int asciiCode, int nbCodes, int fontCharX, int fontCharY) { - int c; - /* cannot change mapping before initRoot is called */ - TCOD_IFNOT(TCOD_ctx.root != NULL) return; - TCOD_IFNOT(asciiCode >= 0 && asciiCode+nbCodes <= TCOD_ctx.max_font_chars) return; - for (c=asciiCode; c < asciiCode+nbCodes; c++ ) { - TCOD_sys_map_ascii_to_font(c, fontCharX, fontCharY); - fontCharX++; - if ( fontCharX == TCOD_ctx.fontNbCharHoriz ) { - fontCharX=0; - fontCharY++; - } - } -} -/** - * \brief Remap a string of character codes to a row of tiles. - * - * \param s A null-terminated string. - * \param fontCharX First X tile-coordinate, starting from the left at zero. - * \param fontCharY First Y tile-coordinate, starting from the top at zero. - * - * This function always assigns tiles in row-major order, even if the - * TCOD_FONT_LAYOUT_ASCII_INCOL flag was set. - */ -void TCOD_console_map_string_to_font(const char *s, int fontCharX, int fontCharY) { - TCOD_IFNOT(s != NULL) return; - /* cannot change mapping before initRoot is called */ - TCOD_IFNOT(TCOD_ctx.root != NULL) return; - while (*s) { - TCOD_console_map_ascii_code_to_font(*s, fontCharX, fontCharY); - fontCharX++; - if ( fontCharX == TCOD_ctx.fontNbCharHoriz ) { - fontCharX=0; - fontCharY++; - } - s++; - } -} - -bool TCOD_console_is_key_pressed(TCOD_keycode_t key) { - return TCOD_sys_is_key_pressed(key); -} -void TCOD_console_set_key_color(TCOD_console_t con,TCOD_color_t col) { - TCOD_console_data_t *dat=con ? (TCOD_console_data_t *)con : TCOD_ctx.root; - TCOD_IFNOT(dat != NULL) return; - TCOD_image_set_key_color(dat->bg_colors, col); -} - -void TCOD_console_credits(void) { - bool end=false; - int x=TCOD_console_get_width(NULL)/2-6; - int y=TCOD_console_get_height(NULL)/2; - int fade=260; - TCOD_sys_save_fps(); - TCOD_sys_set_fps(25); - while (!end ) { - TCOD_key_t k; - end=TCOD_console_credits_render(x,y,false); - TCOD_sys_check_for_event(TCOD_EVENT_KEY_PRESS,&k,NULL); - if ( fade == 260 && k.vk != TCODK_NONE ) { - fade -= 10; - } - TCOD_console_flush(); - if ( fade < 260 ) { - fade -= 10; - TCOD_console_set_fade(fade,TCOD_black); - if ( fade == 0 ) end=true; - } - } - TCOD_console_set_fade(255,TCOD_black); - TCOD_sys_restore_fps(); -} - -static bool init2=false; - -void TCOD_console_credits_reset(void) { - init2=false; -} - -bool TCOD_console_credits_render(int x, int y, bool alpha) { - static char poweredby[128]; - static float char_heat[128]; - static int char_x[128]; - static int char_y[128]; - static bool init1=false; - static int len,len1,cw=-1,ch=-1; - static float xstr; - static TCOD_color_t colmap[64]; - static TCOD_color_t colmap_light[64]; - static TCOD_noise_t noise; - static TCOD_color_t colkeys[4] = { - {255,255,204}, - {255,204,0}, - {255,102,0}, - {102,153,255}, - }; - static TCOD_color_t colkeys_light[4] = { - {255,255,204}, - {128,128,77}, - {51,51,31}, - {0,0,0}, - }; - static int colpos[4]={ - 0,21,42,63 - }; - static TCOD_image_t img=NULL; - int i,xc,yc,xi,yi,j; - static int left,right,top,bottom; - float sparklex,sparkley,sparklerad,sparklerad2,noisex; - /* mini particule system */ -#define MAX_PARTICULES 50 - static float pheat[MAX_PARTICULES]; - static float px[MAX_PARTICULES],py[MAX_PARTICULES], pvx[MAX_PARTICULES],pvy[MAX_PARTICULES]; - static int nbpart=0, firstpart=0; - static float partDelay=0.1f; - float elapsed=TCOD_sys_get_last_frame_length(); - TCOD_color_t fbackup; /* backup fg color */ - - if (!init1) { - /* initialize all static data, colormaps, ... */ - TCOD_color_t col; - TCOD_color_gen_map(colmap,4,colkeys,colpos); - TCOD_color_gen_map(colmap_light,4,colkeys_light,colpos); - sprintf(poweredby,"Powered by\n%s",version_string); - noise=TCOD_noise_new(1,TCOD_NOISE_DEFAULT_HURST,TCOD_NOISE_DEFAULT_LACUNARITY,NULL); - len=(int)strlen(poweredby); - len1=11; /* sizeof "Powered by\n" */ - left=MAX(x-4,0); - top=MAX(y-4,0); - col= TCOD_console_get_default_background(NULL); - TCOD_console_set_default_background(NULL,TCOD_black); - TCOD_console_set_default_background(NULL,col); - init1=true; - } - if (!init2) { - /* reset the credits vars ... */ - int curx,cury; - xstr=-4.0f; - curx=x; - cury=y; - for (i=0; i < len ;i++) { - char_heat[i]=-1; - char_x[i]=curx; - char_y[i]=cury; - curx++; - if ( poweredby[i] == '\n' ) { - curx=x; - cury++; - } - } - nbpart=firstpart=0; - init2=true; - } - if (TCOD_console_get_width(NULL) != cw || TCOD_console_get_height(NULL)!=ch) { - /* console size has changed */ - int width,height; - cw=TCOD_console_get_width(NULL); - ch=TCOD_console_get_height(NULL); - right=MIN(x+len,cw-1); - bottom=MIN(y+6,ch-1); - width=right - left + 1; - height=bottom - top + 1; - if ( img ) TCOD_image_delete(img); - img = TCOD_image_new(width*2,height*2); - } - fbackup=TCOD_console_get_default_foreground(NULL); - if ( xstr < (float)len1 ) { - sparklex=x+xstr; - sparkley=(float)y; - } else { - sparklex=x-len1+xstr; - sparkley=(float)y+1; - } - noisex=xstr*6; - sparklerad=3.0f+2*TCOD_noise_get(noise,&noisex); - if ( xstr >= len-1 ) sparklerad -= (xstr-len+1)*4.0f; - else if ( xstr < 0.0f ) sparklerad += xstr*4.0f; - else if ( poweredby[ (int)(xstr+0.5f) ] == ' ' || poweredby[ (int)(xstr+0.5f) ] == '\n' ) sparklerad/=2; - sparklerad2=sparklerad*sparklerad*4; - - /* draw the light */ - for (xc=left*2,xi=0; xc < (right+1)*2; xc++,xi++) { - for (yc=top*2,yi=0; yc < (bottom+1)*2; yc++,yi++) { - float dist=((xc-2*sparklex)*(xc-2*sparklex)+(yc-2*sparkley)*(yc-2*sparkley)); - TCOD_color_t pixcol; - if ( sparklerad >= 0.0f && dist < sparklerad2 ) { - int colidx=63-(int)(63*(sparklerad2-dist)/sparklerad2) + TCOD_random_get_int(NULL,-10,10); - colidx=CLAMP(0,63,colidx); - pixcol=colmap_light[colidx]; - } else { - pixcol=TCOD_black; - } - if ( alpha ) { - /* console cells have following flag values : - 1 2 - 4 8 - flag indicates which subcell uses foreground color */ - static int asciiToFlag[] = { - 1, /* TCOD_CHAR_SUBP_NW */ - 2, /* TCOD_CHAR_SUBP_NE */ - 3, /* TCOD_CHAR_SUBP_N */ - 8, /* TCOD_CHAR_SUBP_SE */ - 9, /* TCOD_CHAR_SUBP_DIAG */ - 10, /* TCOD_CHAR_SUBP_E */ - 4, /* TCOD_CHAR_SUBP_SW */ - }; - int conc= TCOD_console_get_char(NULL,xc/2,yc/2); - TCOD_color_t bk=TCOD_console_get_char_background(NULL,xc/2,yc/2); - if ( conc >= TCOD_CHAR_SUBP_NW && conc <= TCOD_CHAR_SUBP_SW ) { - /* merge two subcell chars... - get the flag for the existing cell on root console */ - int bkflag=asciiToFlag[conc - TCOD_CHAR_SUBP_NW ]; - int xflag = (xc & 1); - int yflag = (yc & 1); - /* get the flag for the current subcell */ - int credflag = (1+3*yflag) * (xflag+1); - if ( (credflag & bkflag) != 0 ) { - /* the color for this subcell on root console - is foreground, not background */ - bk = TCOD_console_get_char_foreground(NULL,xc/2,yc/2); - } - } - pixcol.r = MIN(255,(int)(bk.r)+pixcol.r); - pixcol.g = MIN(255,(int)(bk.g)+pixcol.g); - pixcol.b = MIN(255,(int)(bk.b)+pixcol.b); - } - TCOD_image_put_pixel(img,xi,yi,pixcol); - } - } - - /* draw and update the particules */ - j=nbpart;i=firstpart; - while (j > 0) { - int colidx=(int)(64*(1.0f-pheat[i])); - TCOD_color_t col; - colidx=MIN(63,colidx); - col=colmap[colidx]; - if ( (int)py[i]< (bottom-top+1)*2 ) { - int ipx = (int)px[i]; - int ipy = (int)py[i]; - float fpx = px[i]-ipx; - float fpy = py[i]-ipy; - TCOD_color_t col2=TCOD_image_get_pixel(img,ipx,ipy); - col2=TCOD_color_lerp(col,col2,0.5f*(fpx+fpy)); - TCOD_image_put_pixel(img,ipx,ipy,col2); - col2=TCOD_image_get_pixel(img,ipx+1,ipy); - col2=TCOD_color_lerp(col2,col,fpx); - TCOD_image_put_pixel(img,ipx+1,ipy,col2); - col2=TCOD_image_get_pixel(img,ipx,ipy+1); - col2=TCOD_color_lerp(col2,col,fpy); - TCOD_image_put_pixel(img,ipx,ipy+1,col2); - } else pvy[i]=-pvy[i] * 0.5f; - pvx[i] *= (1.0f-elapsed); - pvy[i] += (1.0f-pheat[i])*elapsed*300.0f; - px[i] += pvx[i]*elapsed; - py[i] += pvy[i]*elapsed; - pheat[i] -= elapsed*0.3f; - if ( pheat[i] < 0.0f ) { - firstpart = (firstpart+1)%MAX_PARTICULES; - nbpart--; - } - i = (i+1)%MAX_PARTICULES; - j--; - } - partDelay -= elapsed; - if ( partDelay < 0.0f && nbpart < MAX_PARTICULES && sparklerad > 2.0f ) { - /* fire a new particule */ - int lastpart = firstpart; - int nb=nbpart; - while (nb > 0 ) { - lastpart = ( lastpart + 1 )%MAX_PARTICULES; - nb--; - } - nbpart++; - px[lastpart] = 2*(sparklex-left); - py[lastpart] = 2*(sparkley-top)+2; - pvx[lastpart] = TCOD_random_get_float(NULL,-5.0f,5.0f); - pvy[lastpart] = TCOD_random_get_float(NULL,-0.5f, -15.0f); - pheat[lastpart] = 1.0f; - partDelay += 0.1f; - } - TCOD_image_blit_2x(img,NULL,left,top,0,0,-1,-1); - /* draw the text */ - for (i=0; i < len ;i++) { - if ( char_heat[i] >= 0.0f && poweredby[i]!='\n') { - int colidx=(int)(64*char_heat[i]); - TCOD_color_t col; - colidx=MIN(63,colidx); - col=colmap[colidx]; - if ( xstr >= len ) { - float coef=(xstr-len)/len; - if ( alpha ) { - TCOD_color_t fore=TCOD_console_get_char_background(NULL,char_x[i],char_y[i]); - int r=(int)(coef*fore.r + (1.0f-coef)*col.r); - int g=(int)(coef*fore.g + (1.0f-coef)*col.g); - int b=(int)(coef*fore.b + (1.0f-coef)*col.b); - col.r = CLAMP(0,255,r); - col.g = CLAMP(0,255,g); - col.b = CLAMP(0,255,b); - TCOD_console_set_char_foreground(NULL,char_x[i],char_y[i],col); - } else { - col=TCOD_color_lerp(col,TCOD_black,coef); - } - } - TCOD_console_set_char(NULL,char_x[i],char_y[i],poweredby[i]); - TCOD_console_set_char_foreground(NULL,char_x[i],char_y[i],col); - } - } - /* update letters heat */ - xstr += elapsed * 4; - for (i=0; i < (int)(xstr+0.5f); i++) { - char_heat[i]=(xstr-i)/(len/2); - } - /* restore fg color */ - TCOD_console_set_default_foreground(NULL,fbackup); - if ( xstr <= 2*len ) return false; - init2=false; - return true; -} - -static void TCOD_console_read_asc(TCOD_console_t con,FILE *f,int width, int height, float version) { - int x,y; - TCOD_console_data_t *dat=con ? (TCOD_console_data_t *)con : TCOD_ctx.root; - TCOD_IFNOT(dat != NULL) return; - while(fgetc(f) != '#'); - for(x = 0; x < width; x++) { - for(y = 0; y < height; y++) { - TCOD_color_t fore,back; - int c = fgetc(f); - fore.r = fgetc(f); - fore.g = fgetc(f); - fore.b = fgetc(f); - back.r = fgetc(f); - back.g = fgetc(f); - back.b = fgetc(f); - /* skip solid/walkable info */ - if ( version >= 0.3f ) { - fgetc(f); - fgetc(f); - } - TCOD_console_put_char_ex(con,x,y,c,fore,back); - } - } - fclose(f); -} - -static void TCOD_console_read_apf(TCOD_console_t con,FILE *f,int width, int height, float version) { -} - -static int string_ends_with(const char *str, const char *suffix) { - size_t str_len = strlen(str); - size_t suffix_len = strlen(suffix); - return - (str_len >= suffix_len) && - (0 == strcmp(str + (str_len-suffix_len), suffix)); -} - -TCOD_console_t TCOD_console_from_file(const char *filename) { - float version; - int width,height; - TCOD_console_t con; - FILE *f; - TCOD_IFNOT( filename != NULL ) { - return NULL; - } - if (string_ends_with(filename, ".xp")) { - return TCOD_console_from_xp(filename); - } - f=fopen(filename,"rb"); - TCOD_IFNOT( f!=NULL ) { - return NULL; - } - if (fscanf(f, "ASCII-Paint v%g", &version) != 1 ) { - fclose(f); - return NULL; - } - if (fscanf(f, "%i %i", &width, &height) != 2 ) { - fclose(f); - return NULL; - } - TCOD_IFNOT ( width > 0 && height > 0) { - fclose(f); - return NULL; - } - con=TCOD_console_new(width,height); - if (string_ends_with(filename, ".asc")) { - TCOD_console_read_asc(con,f,width,height,version); - } else { - TCOD_console_read_apf(con,f,width,height,version); - } - return con; -} - -bool TCOD_console_load_asc(TCOD_console_t pcon, const char *filename) { - float version; - int width,height; - FILE *f; - TCOD_console_data_t *con=pcon ? (TCOD_console_data_t *)pcon : TCOD_ctx.root; - TCOD_IFNOT(con != NULL) return false; - TCOD_IFNOT( filename != NULL ) { - return false; - } - f=fopen(filename,"rb"); - TCOD_IFNOT( f!=NULL ) { - return false; - } - if (fscanf(f, "ASCII-Paint v%g", &version) != 1 ) { - fclose(f); - return false; - } - if (fscanf(f, "%i %i", &width, &height) != 2 ) { - fclose(f); - return false; - } - TCOD_IFNOT ( width > 0 && height > 0) { - fclose(f); - return false; - } - if ( con->w != width || con->h != height ) { - /* resize console */ - TCOD_console_data_free(con); - con->w = width; - con->h = height; - TCOD_console_data_alloc(con); - } - TCOD_console_read_asc(con,f,width,height,version); - return true; -} - -bool TCOD_console_save_asc(TCOD_console_t pcon, const char *filename) { - static float version = 0.3f; - FILE *f; - int x,y; - TCOD_console_data_t *con=pcon ? (TCOD_console_data_t *)pcon : TCOD_ctx.root; - TCOD_IFNOT(con != NULL) return false; - TCOD_IFNOT( filename != NULL ) { - return false; - } - TCOD_IFNOT(con->w > 0 && con->h > 0) return false; - f=fopen(filename,"wb"); - TCOD_IFNOT( f != NULL ) return false; - fprintf(f, "ASCII-Paint v%g\n", version); - fprintf(f, "%i %i\n", con->w, con->h); - fputc('#', f); - for(x = 0; x < con->w; x++) { - for(y = 0; y < con->h; y++) { - TCOD_color_t fore,back; - int c=TCOD_console_get_char(con,x,y); - fore=TCOD_console_get_char_foreground(con,x,y); - back=TCOD_console_get_char_background(con,x,y); - fputc(c, f); - fputc(fore.r,f); - fputc(fore.g,f); - fputc(fore.b,f); - fputc(back.r,f); - fputc(back.g,f); - fputc(back.b,f); - fputc(0,f); /* solid */ - fputc(1,f); /* walkable */ - } - } - fclose(f); - return true; -} - -static bool hasDetectedBigEndianness = false; -static bool isBigEndian; -void detectBigEndianness(void) { - if (!hasDetectedBigEndianness){ - uint32_t Value32; - uint8_t *VPtr = (uint8_t *)&Value32; - VPtr[0] = VPtr[1] = VPtr[2] = 0; VPtr[3] = 1; - if(Value32 == 1) isBigEndian = true; - else isBigEndian = false; - hasDetectedBigEndianness = true; - } -} - -uint16_t bswap16(uint16_t s){ - uint8_t* ps = (uint8_t*)&s; - uint16_t res; - uint8_t* pres = (uint8_t*)&res; - pres[0] = ps[1]; - pres[1] = ps[0]; - return res; -} - -uint32_t bswap32(uint32_t s){ - uint8_t *ps=(uint8_t *)(&s); - uint32_t res; - uint8_t *pres=(uint8_t *)&res; - pres[0]=ps[3]; - pres[1]=ps[2]; - pres[2]=ps[1]; - pres[3]=ps[0]; - return res; -} - -uint16_t l16(uint16_t s){ - if (isBigEndian) return bswap16(s); else return s; -} - -uint32_t l32(uint32_t s){ - if (isBigEndian) return bswap32(s); else return s; -} - -/* fix the endianness */ -void fix16(uint16_t* u){ - *u = l16(*u); -} - -void fix32(uint32_t* u){ - *u = l32(*u); -} - -/************ RIFF helpers */ - -uint32_t fourCC(const char* c){ - return (*(uint32_t*)c); -} - -/* checks if u equals str */ -bool fourCCequals(uint32_t u, const char* str){ - return fourCC(str)==u; -} - -void fromFourCC(uint32_t u, char*s){ - const char* c = (const char*)(&u); - s[0]=c[0]; - s[1]=c[1]; - s[2]=c[2]; - s[3]=c[3]; - s[4]=0; -} - -void put8(uint8_t d, FILE* fp){ - fwrite(&d,1,1,fp); -} - -void put16(uint16_t d, FILE* fp){ - fwrite(&d,2,1,fp); -} - -void put32(uint32_t d, FILE* fp){ - fwrite(&d,4,1,fp); -} - -void putFourCC(const char* c, FILE* fp){ - put32(fourCC(c),fp); -} - -void putData(void* what, int length, FILE* fp){ - fwrite(what,length,1,fp); -} - -bool get8(uint8_t* u, FILE* fp){ - return 1==fread((void*)u, sizeof(uint8_t),1,fp); -} - -bool get16(uint16_t* u, FILE* fp){ - return 1==fread((void*)u, sizeof(uint16_t),1,fp); -} - -bool get32(uint32_t* u, FILE* fp){ - return 1==fread((void*)u, sizeof(uint32_t),1,fp); -} - -bool getData(void* u, size_t sz, FILE* fp){ - return 1==fread(u, sz,1,fp); -} - - -/********* APF RIFF structures */ - -typedef struct { - uint32_t show_grid; - uint32_t grid_width; - uint32_t grid_height; -} SettingsDataV1; - -#define FILTER_TYPE_UNCOMPRESSED 0 -#define FORMAT_TYPE_CRGBRGB 0 - -typedef struct { - uint32_t width; - uint32_t height; - uint32_t filter; - uint32_t format; -} ImageDetailsV1; - -/* Layers */ - -typedef struct { - uint32_t name; - uint32_t mode; - uint32_t index; - uint32_t dataSize; -} LayerV1 ; - -typedef struct { - uint32_t name; - uint32_t mode; - uint32_t fgalpha; - uint32_t bgalpha; - uint32_t visible; - uint32_t index; - uint32_t dataSize; -} LayerV2; - -/* fix the endianness */ -void fixSettings(SettingsDataV1* s){ - fix32(&s->show_grid); - fix32(&s->grid_width); - fix32(&s->grid_height); -} - -void fixImage(ImageDetailsV1* v){ - fix32(&v->width); - fix32(&v->height); - fix32(&v->filter); - fix32(&v->format); -} - -void fixLayerv1(LayerV1* l){ - fix32(&l->mode); - fix32(&l->index); - fix32(&l->dataSize); -} - -void fixLayerv2(LayerV2* l){ - fix32(&l->mode); - fix32(&l->fgalpha); - fix32(&l->bgalpha); - fix32(&l->visible); - fix32(&l->index); - fix32(&l->dataSize); -} - - -/*********** ApfFile */ - -bool TCOD_console_save_apf(TCOD_console_t pcon, const char *filename) { - TCOD_console_data_t *con=pcon ? (TCOD_console_data_t *)pcon : TCOD_ctx.root; - FILE* fp ; - TCOD_IFNOT(con != NULL) return false; - detectBigEndianness(); - - fp = fopen(filename, "wb"); - if(fp == NULL) { - return false; - } - else { - int x,y; - uint32_t riffSize = 0; - uint32_t imgDetailsSize ; - SettingsDataV1 settingsData; - ImageDetailsV1 imgData; - fpos_t posRiffSize; - uint32_t settingsSz ; - uint32_t layerImageSize ; - uint32_t layerChunkSize ; - /* riff header*/ - putFourCC("RIFF",fp); - fgetpos(fp,&posRiffSize); - put32(0,fp); - - /* APF_ header */ - putFourCC("apf ",fp); - riffSize += 4; - - /* settings */ - settingsData.show_grid = 0; - settingsData.grid_width = 8; - settingsData.grid_height = 8; - settingsSz = sizeof(uint32_t) + sizeof settingsData; - putFourCC("sett",fp); - put32(l32(settingsSz),fp); - put32(l32(1),fp); - putData((void*)&settingsData,sizeof settingsData,fp); - if (settingsSz&1){ - put8(0,fp); - riffSize++; - } - riffSize += 4+4+settingsSz; - - /* image details */ - imgData.width = con->w; - imgData.height = con->h; - imgData.filter = 0; - imgData.format = 0; - imgDetailsSize = sizeof(uint32_t) + sizeof imgData; - putFourCC("imgd",fp); - put32(l32(imgDetailsSize),fp); - put32(l32(1),fp); - putData((void*)&imgData,sizeof imgData,fp); - if (imgDetailsSize&1){ - put8(0,fp); - riffSize++; - } - riffSize += 4+4+imgDetailsSize; - - /* now write the layers as a RIFF list - the first layer is the lowest layer - Assume imgData filter = uncompressed, and imgData format = CRGB */ - layerImageSize = imgData.width*imgData.height*7; - layerChunkSize = sizeof(uint32_t) /* version */ - + sizeof(LayerV2) /* header */ - + layerImageSize; /* data */ - - putFourCC("layr",fp); /* layer */ - put32(l32(layerChunkSize),fp); - /* VERSION -> */ - put32(l32(2),fp); - /* Data */ - putFourCC("LAY0",fp); - put32(l32(0),fp); - put32(l32(255),fp); - put32(l32(255),fp); - put32(l32(1),fp); - put32(l32(0),fp); - put32(l32(layerImageSize),fp); - - /* now write out the data */ - - for(x = 0; x < con->w; x++) { - for(y = 0; y < con->h; y++) { - TCOD_color_t fore,back; - int c=TCOD_console_get_char(con,x,y); - fore=TCOD_console_get_char_foreground(con,x,y); - back=TCOD_console_get_char_background(con,x,y); - put8(c, fp); - put8(fore.r,fp); - put8(fore.g,fp); - put8(fore.b,fp); - put8(back.r,fp); - put8(back.g,fp); - put8(back.b,fp); - } - } - - if (layerChunkSize&1){ - put8(0,fp); /* padding bit */ - riffSize++; - } - - riffSize += 2*sizeof(uint32_t)+layerChunkSize; - - fsetpos(fp,&posRiffSize); - put32(l32(riffSize),fp); - } - - fclose(fp); - return true; -} - -typedef struct { - LayerV1 headerv1; - LayerV2 headerv2; - uint8_t* data; /* dynamically allocated */ -} LayerData; - -typedef struct { - ImageDetailsV1 details; - SettingsDataV1 settings; - LayerData layer; -} Data; - -bool TCOD_console_load_apf(TCOD_console_t pcon, const char *filename) { - uint32_t sett = fourCC("sett"); - uint32_t imgd = fourCC("imgd"); - /* - uint32_t LIST = fourCC("LIST"); - uint32_t LAYR = fourCC("LAYR"); - */ - uint32_t layr = fourCC("layr"); - FILE* fp ; - Data data; - TCOD_console_data_t *con=pcon ? (TCOD_console_data_t *)pcon : TCOD_ctx.root; - TCOD_IFNOT(con != NULL) return false; - - detectBigEndianness(); - data.details.width = 1; - data.details.height = 1; - data.details.filter = 0; - data.details.format = 0; - - data.settings.show_grid = true; - data.settings.grid_width = 10; - data.settings.grid_height = 10; - - #define ERR(x) {printf("Error: %s\n. Aborting operation.",x); return false;} - #define ERR_NEWER(x) {printf("Error: It looks like this file was made with a newer version of Ascii-Paint\n. In particular the %s field. Aborting operation.",x); return false;} - - fp = fopen(filename, "rb"); - if(fp == NULL) { - printf("The file %s could not be loaded.\n", filename); - return false; - } - else { - /* read the header */ - uint32_t riff; - uint32_t riffSize; - int index = 0; - int x,y; - uint8_t *imgData; - bool keepGoing = true; - if (! get32(&riff,fp) || ! fourCCequals(riff,"RIFF")){ - ERR("File doesn't have a RIFF header"); - } - if (!get32(&riffSize,fp)) ERR("No RIFF size field!"); - fix32(&riffSize); - - while(keepGoing && fp){ /* for each subfield, try to find the APF_ field */ - uint32_t apf; - if (! get32(&apf,fp)) break; - if (fourCCequals(apf,"apf ") || fourCCequals(apf,"APF ")){ - /* Process APF segment */ - while(keepGoing && fp){ - uint32_t seg; - if (! get32(&seg,fp)){ - keepGoing = false; - break; - } - else { - if (seg==sett){ - /* size */ - uint32_t sz; - uint32_t ver; - SettingsDataV1 settingsData; - - get32(&sz,fp); - fix32(&sz); - /* version */ - get32(&ver,fp); - fix32(&ver); - if (ver!=1) ERR_NEWER("settings"); - /* ver must be 1 */ - if (! getData((void*)&settingsData,sizeof settingsData,fp)) ERR("Can't read settings."); - data.settings = settingsData; - fixSettings(&data.settings); - - } - else if (seg==imgd){ - /* sz */ - uint32_t sz; - uint32_t ver; - ImageDetailsV1 dets; - - get32(&sz,fp); - fix32(&sz); - /* version */ - get32(&ver,fp); - fix32(&ver); - if (ver!=1) ERR_NEWER("image details"); - /* ver must be 1 */ - if (! getData((void*)&dets, sizeof dets, fp)) ERR("Can't read image details."); - data.details = dets; - fixImage(&data.details); - - /* get canvas ready */ - TCOD_IFNOT ( data.details.width > 0 && data.details.height > 0) { - fclose(fp); - return false; - } - if ( con->w != data.details.width || con->h != data.details.height ) { - /* resize console */ - TCOD_console_data_free(con); - con->w = data.details.width; - con->h = data.details.height; - TCOD_console_data_alloc(con); - } - - } - else if (seg==layr){ - uint32_t sz; - uint32_t ver; - - get32(&sz,fp); - fix32(&sz); - /* version */ - get32(&ver,fp); - fix32(&ver); - if (ver>2) ERR_NEWER("layer spec"); - - if (ver==1){ - if (! getData((void*)&data.layer.headerv1, sizeof( LayerV1 ), fp)) ERR("Can't read layer header."); - fixLayerv1(&data.layer.headerv1); - - /* Read in the data chunk*/ - data.layer.data = (uint8_t*)malloc(sizeof(uint8_t)*data.layer.headerv1.dataSize); - getData((void*) data.layer.data, data.layer.headerv1.dataSize, fp); - } - else if (ver==2){ - if (! getData((void*)&data.layer.headerv2, sizeof( LayerV2 ), fp)) ERR("Can't read layer header."); - fixLayerv2(&data.layer.headerv2); - - /* Read in the data chunk */ - data.layer.data = (uint8_t*)malloc(sizeof(uint8_t)*data.layer.headerv2.dataSize); - getData((void*) data.layer.data, data.layer.headerv2.dataSize, fp); - - } - } - else { - /* skip unknown segment */ - uint32_t sz; - get32(&sz,fp); - fix32(&sz); - fseek(fp,sz,SEEK_CUR); - } - } - } - - /* we're done! */ - keepGoing = false; - } - else { - /* skip this segment */ - uint32_t sz; - get32(&sz,fp); - fseek(fp,sz,SEEK_CUR); - } - } - - imgData = data.layer.data; - for(x = 0; x < con->w; x++) { - for(y = 0; y < con->h; y++) { - TCOD_color_t fore,back; - int c = (unsigned char)(imgData[index++]); - fore.r = (uint8_t)(imgData[index++]); - fore.g = (uint8_t)(imgData[index++]); - fore.b = (uint8_t)(imgData[index++]); - back.r = (uint8_t)(imgData[index++]); - back.g = (uint8_t)(imgData[index++]); - back.b = (uint8_t)(imgData[index++]); - TCOD_console_put_char_ex(con,x,y,c,fore,back); - } - } - - free (data.layer.data); - } - fclose(fp); - - return true; -} -/* - -bool ApfFile::Load(std::string filename){ - detectBigEndianness(); - - uint32_t sett = fourCC("sett"); - uint32_t imgd = fourCC("imgd"); - uint32_t LIST = fourCC("LIST"); - uint32_t LAYR = fourCC("LAYR"); - uint32_t layr = fourCC("layr"); - - Data data; // File data - - data.details.width = 1; - data.details.height = 1; - data.details.filter = FILTER_TYPE_UNCOMPRESSED; - data.details.format = FORMAT_TYPE_CRGBRGB; - - data.settings.show_grid = true; - data.settings.grid_width = 10; - data.settings.grid_height = 10; - - data.currentLayer = NULL; - - #define ERR(x) {printf("Error: %s\n. Aborting operation.",x); return false;} - #define ERR_NEWER(x) {printf("Error: It looks like this file was made with a newer version of Ascii-Paint\n. In particular the %s field. Aborting operation.",x); return false;} - - FILE* fp = fopen(filename.c_str(), "rb"); - if(fp == NULL) { - printf("The file %s could not be loaded.\n", filename.c_str()); - return false; - } - else { - // read the header - uint32_t riff; - if (not get32(&riff,fp) - or - not fourCCequals(riff,"RIFF")){ - ERR("File doesn't have a RIFF header"); - } - // else - uint32_t riffSize; - if (!get32(&riffSize,fp)) ERR("No RIFF size field!"); - fix(&riffSize); - - bool keepGoing = true; - while(keepGoing and fp){ // for each subfield, try to find the APF_ field - uint32_t apf; - if (not get32(&apf,fp)) break; - if (fourCCequals(apf,"apf ") or fourCCequals(apf,"APF ")){ - // Process APF segment - while(keepGoing and fp){ - uint32_t seg; - if (not get32(&seg,fp)){ - keepGoing = false; - break; - } - else { - if (seg==sett){ - // size - uint32_t sz; - get32(&sz,fp); - fix(&sz); - // version - uint32_t ver; - get32(&ver,fp); - fix(&ver); - if (ver!=1) ERR_NEWER("settings"); - // ver must be 1 - SettingsDataV1 settingsData; - if (not getData((void*)&settingsData,sizeof settingsData,fp)) ERR("Can't read settings."); - data.settings = settingsData; - fix(&data.settings); - - // Change app settings - app->setGridDimensions(data.settings.grid_width,data.settings.grid_height); - app->setShowGrid(data.settings.show_grid==1); - } - else if (seg==imgd){ - // sz - uint32_t sz; - get32(&sz,fp); - fix(&sz); - // version - uint32_t ver; - get32(&ver,fp); - fix(&ver); - if (ver!=1) ERR_NEWER("image details"); - // ver must be 1 - ImageDetailsV1 dets; - if (not getData((void*)&dets, sizeof dets, fp)) ERR("Can't read image details."); - data.details = dets; - fix(&data.details); - - // get canvas ready - app->canvasWidth = data.details.width; - app->canvasHeight = data.details.height; - app->initCanvas(); - - // delete new layer - app->deleteLayer(app->getCurrentLayer()->name); - - } - else if (seg==layr){ - // printf("Found a layer\n"); - - // sz - uint32_t sz; - get32(&sz,fp); - fix(&sz); - // version - uint32_t ver; - get32(&ver,fp); - fix(&ver); - if (ver>2) ERR_NEWER("layer spec"); - - if (ver==1){ - LayerV1 layerHeader; - if (not getData((void*)&layerHeader, sizeof layerHeader, fp)) ERR("Can't read layer header."); - fix(&layerHeader); - - // creat new layer data - LayerData* ld = new LayerData; - ld->header = layerHeader; // already fix'd - ld->data = new uint8[ld->header.dataSize]; - - // Read in the data chunk - getData((void*) ld->data, ld->header.dataSize, fp); - - // push layer onto the list - data.currentLayer = ld; - data.layers.push(ld); - } - else if (ver==2){ - LayerV2 layerHeader; - if (not getData((void*)&layerHeader, sizeof layerHeader, fp)) ERR("Can't read layer header."); - fix(&layerHeader); - - // creat new layer data - LayerData* ld = new LayerData; - ld->header = layerHeader; // already fix'd - ld->data = new uint8[ld->header.dataSize]; - - // Read in the data chunk - getData((void*) ld->data, ld->header.dataSize, fp); - - // push layer onto the list - data.currentLayer = ld; - data.layers.push(ld); - } - } - else { - // skip unknown segment - uint32_t sz; - get32(&sz,fp); - fix(&sz); - fseek(fp,sz,SEEK_CUR); - } - } - } - - // we're done! - keepGoing = false; - } - else { - // skip this segment - uint32_t sz; - get32(&sz,fp); - fseek(fp,sz,SEEK_CUR); - } - } - - // finally, copy the layers into the current document - for(int i=0;iaddNewLayer(); - - // Parse layer header - l->name = fromFourCC(ld->header.name); - l->fgalpha = ld->header.fgalpha; - l->bgalpha = ld->header.bgalpha; - l->visible = (ld->header.visible==1); - // l->compositingMode = - - // Copy data into currently selected canvas - uint8_t* imgData = ld->data; - CanvasImage *img = new CanvasImage; - // Write the brush data for every brush in the image - int index = 0; - for(int x = 0; x < app->canvasWidth; x++) { - for(int y = 0; y < app->canvasHeight; y++) { - Brush b; - b.symbol = (unsigned char)(imgData[index++]); - b.fore.r = (uint8_t)(imgData[index++]); - b.fore.g = (uint8_t)(imgData[index++]); - b.fore.b = (uint8_t)(imgData[index++]); - b.back.r = (uint8_t)(imgData[index++]); - b.back.g = (uint8_t)(imgData[index++]); - b.back.b = (uint8_t)(imgData[index++]); - b.solid = true; // deprecated - b.walkable = true; // deprecated - img->push_back(b); - } - } - - app->setCanvasImage(*img); - delete img; - } - - // then free all the temporary layer data - for(int i=0;idata; - delete data.layers.get(i); - } - - // and update the layer widget - app->gui->layerWidget->regenerateLayerList(); - } - fclose(fp); - - return true; -} -*/ - -#endif /* TCOD_CONSOLE_SUPPORT */ +/* +* libtcod +* Copyright (c) 2008-2018 Jice & Mingos & rmtew +* All rights reserved. +* +* Redistribution and use in source and binary forms, with or without +* modification, are permitted provided that the following conditions are met: +* * Redistributions of source code must retain the above copyright +* notice, this list of conditions and the following disclaimer. +* * Redistributions in binary form must reproduce the above copyright +* notice, this list of conditions and the following disclaimer in the +* documentation and/or other materials provided with the distribution. +* * The name of Jice or Mingos may not be used to endorse or promote +* products derived from this software without specific prior written +* permission. +* +* THIS SOFTWARE IS PROVIDED BY JICE, MINGOS AND RMTEW ``AS IS'' AND ANY +* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED +* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE +* DISCLAIMED. IN NO EVENT SHALL JICE, MINGOS OR RMTEW BE LIABLE FOR ANY +* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES +* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; +* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND +* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS +* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +*/ +#include "console.h" + +#include +#include +#include +#include +#include +#include + +#include +#include "console.hpp" +#include "console_rexpaint.h" +#include "noise.h" +#include "mersenne.h" +#include "libtcod_int.h" +#include "utility.h" +#include "version.h" +#include "engine/globals.h" +#include "sdl2/sdl2_display.h" +#include "tileset/tileset.h" +#include "tileset/tilesheet.h" + +#ifdef TCOD_CONSOLE_SUPPORT + +#if defined( TCOD_VISUAL_STUDIO ) +static const char *version_string = "libtcod " TCOD_STRVERSION; +#else +static const char *version_string __attribute__((unused)) = "libtcod " TCOD_STRVERSION; +#endif + +TCOD_internal_context_t TCOD_ctx={ + /* number of characters in the bitmap font */ + 16,16, + /* font type and layout */ + false,false,false, + /* character size in font */ + 8,8, + "terminal.png","", + NULL,NULL,NULL,0,false,0,0,0,0,0,0, +#ifndef TCOD_BARE + /* default renderer to use */ + TCOD_RENDERER_GLSL, + NULL, +#endif + /* fading data */ + {0,0,0},255, + /*key state*/ + {}, + /* window closed ? */ + false, + /* mouse focus ? */ + false, + /* application active ? */ + true, +}; + +/** + * Codec for TCOD_FONT_LAYOUT_TCOD. + * + * Converts from EASCII code-point -> raw tile position. + */ +static constexpr std::array tcod_codec_{ + 0, 0, 0, 0, 0, 0, 0, 0, 0, 76, 77, 0, 0, 0, 0, 0, /* 0 to 15 */ + 71, 70, 72, 0, 0, 0, 0, 0, 64, 65, 67, 66, 0, 73, 68, 69, /* 16 to 31 */ + 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, /* 32 to 47 */ + 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, /* 48 to 63 */ + 32, 96, 97, 98, 99,100,101,102,103,104,105,106,107,108,109,110, /* 64 to 79 */ +111,112,113,114,115,116,117,118,119,120,121, 33, 34, 35, 36, 37, /* 80 to 95 */ + 38,128,129,130,131,132,133,134,135,136,137,138,139,140,141,142, /* 96 to 111 */ +143,144,145,146,147,148,149,150,151,152,153, 39, 40, 41, 42, 0, /* 112 to 127 */ + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* 128 to 143 */ + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* 144 to 159 */ + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* 160 to 175 */ + 43, 44, 45, 46, 49, 0, 0, 0, 0, 81, 78, 87, 88, 0, 0, 55, /* 176 to 191 */ + 53, 50, 52, 51, 47, 48, 0, 0, 85, 86, 82, 84, 83, 79, 80, 0, /* 192 to 207 */ + 0, 0, 0, 0, 0, 0, 0, 0, 0, 56, 54, 0, 0, 0, 0, 0, /* 208 to 223 */ + 74, 75, 57, 58, 59, 60, 61, 62, 63, 0, 0, 0, 0, 0, 0, 0, /* 224 to 239 */ + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* 240 to 255 */ +}; +/** + * Return a new console with a specific number of columns and rows. + * + * \param w Number of columns. + * \param h Number of columns. + * \return A pointer to the new console, or NULL on error. + */ +TCOD_console_t TCOD_console_new(int w, int h) { + TCOD_IFNOT(w > 0 && h > 0 ) { + return NULL; + } else { + struct TCOD_Console *con=(struct TCOD_Console *)calloc(sizeof(struct TCOD_Console),1); + if (!con) { return NULL; } + con->w=w; + con->h=h; + TCOD_console_init(con,NULL,false); /* NOTE: CHECK THIS FOR ERORS */ + if(TCOD_ctx.root) { + con->alignment=TCOD_ctx.root->alignment; + con->bkgnd_flag=TCOD_ctx.root->bkgnd_flag; + } + return (TCOD_console_t)con; + } +} +/** + * Return immediately with a recently pressed key. + * + * \param flags A TCOD_event_t bit-field, for example: `TCOD_EVENT_KEY_PRESS` + * \return A TCOD_key_t struct with a recently pressed key. + * If no event exists then the `vk` attribute will be `TCODK_NONE` + */ +TCOD_key_t TCOD_console_check_for_keypress(int flags) { + return TCOD_sys_check_for_keypress(flags); +} +/** + * Wait for a key press event, then return it. + * + * \param flush If 1 then the event queue will be cleared before waiting for + * the next event. This should always be 0. + * \return A TCOD_key_t struct with the most recent key data. + * + * Do not solve input lag issues by arbitrarily dropping events! + */ +TCOD_key_t TCOD_console_wait_for_keypress(bool flush) { + return TCOD_sys_wait_for_keypress(flush); +} +/** + * Return true if the window is closing. + */ +bool TCOD_console_is_window_closed(void) { + return TCOD_ctx.is_window_closed; +} +/** + * Return true if the window has mouse focus. + */ +bool TCOD_console_has_mouse_focus(void) { + return TCOD_ctx.app_has_mouse_focus; +} +#ifndef TCOD_BARE +/** + * Return true if the window has keyboard focus. + * + * \verbatim embed:rst:leading-asterisk + * .. versionchanged: 1.7 + * This function was previously broken. It now keeps track of keyboard + * focus. + * \endverbatim + */ +bool TCOD_console_is_active(void) { + return TCOD_ctx.app_is_active; +} +#endif +/** + * Change the title string of the active window. + * + * \param title A utf8 string. + */ +void TCOD_console_set_window_title(const char *title) { + TCOD_sys_set_window_title(title); +} +/** + * Set the display to be full-screen or windowed. + * + * \param fullscreen If true the display will go full-screen. + */ +void TCOD_console_set_fullscreen(bool fullscreen) { + TCOD_IFNOT(TCOD_ctx.root != NULL) return; + TCOD_sys_set_fullscreen(fullscreen); + TCOD_ctx.fullscreen=fullscreen; +} +/** + * Return true if the display is full-screen. + */ +bool TCOD_console_is_fullscreen(void) { + return TCOD_ctx.fullscreen; +} +/** + * Set a consoles default background flag. + * + * \param con A console pointer. + * \param flag One of `TCOD_bkgnd_flag_t`. + */ +void TCOD_console_set_background_flag(TCOD_console_t con,TCOD_bkgnd_flag_t flag) { + struct TCOD_Console *dat=con ? (struct TCOD_Console *)con : TCOD_ctx.root; + TCOD_IFNOT ( dat != NULL ) return; + dat->bkgnd_flag=flag; +} +/** + * Return a consoles default background flag. + */ +TCOD_bkgnd_flag_t TCOD_console_get_background_flag(TCOD_console_t con) { + struct TCOD_Console *dat=con ? (struct TCOD_Console *)con : TCOD_ctx.root; + TCOD_IFNOT ( dat != NULL ) return TCOD_BKGND_NONE; + return dat->bkgnd_flag; +} +/** + * Set a consoles default alignment. + * + * \param con A console pointer. + * \param alignment One of TCOD_alignment_t + */ +void TCOD_console_set_alignment(TCOD_console_t con,TCOD_alignment_t alignment) { + struct TCOD_Console *dat=con ? (struct TCOD_Console *)con : TCOD_ctx.root; + TCOD_IFNOT ( dat != NULL ) return; + dat->alignment=alignment; +} +/** + * Return a consoles default alignment. + */ +TCOD_alignment_t TCOD_console_get_alignment(TCOD_console_t con) { + struct TCOD_Console *dat=con ? (struct TCOD_Console *)con : TCOD_ctx.root; + TCOD_IFNOT ( dat != NULL ) return TCOD_LEFT; + return dat->alignment; +} + +void TCOD_console_data_free(struct TCOD_Console *dat) +{ + if (!dat) { return; } + free(dat->ch_array); + free(dat->fg_array); + free(dat->bg_array); + dat->ch_array = NULL; + dat->fg_array = NULL; + dat->bg_array = NULL; +} +/** + * Delete a console. + * + * \param con A console pointer. + * + * If the console being deleted is the root console, then the display will be + * uninitialized. + */ +void TCOD_console_delete(TCOD_console_t con) +{ + if (con) { + TCOD_console_data_free(con); + free(con); + } else { + TCOD_sys_shutdown(); + con=TCOD_ctx.root; + TCOD_ctx.root=NULL; + } +} +/** + * Shutdown libtcod. This must be called before your program exits. + * /rst + * .. versionadded:: 1.8 + * /endrst + */ +void TCOD_quit(void) +{ + TCOD_console_delete(NULL); +} + +void TCOD_console_blit_key_color( + TCOD_console_t srcCon, int xSrc, int ySrc, int wSrc, int hSrc, + TCOD_console_t dstCon, int xDst, int yDst, + float foreground_alpha, float background_alpha, TCOD_color_t *key_color) { + struct TCOD_Console *src = srcCon ? (struct TCOD_Console *)srcCon : TCOD_ctx.root; + struct TCOD_Console *dst = dstCon ? (struct TCOD_Console *)dstCon : TCOD_ctx.root; + TCOD_color_t *srcFgColors, *srcBgColors, *dstFgColors, *dstBgColors; + int cx, cy; + if (wSrc == 0) wSrc = src->w; + if (hSrc == 0) hSrc = src->h; + TCOD_IFNOT(wSrc > 0 && hSrc > 0) return; + TCOD_IFNOT(xDst + wSrc >= 0 && yDst + hSrc >= 0 && xDst < dst->w && yDst < dst->h) return; + srcFgColors = src->fg_array; + srcBgColors = src->bg_array; + dstFgColors = dst->fg_array; + dstBgColors = dst->bg_array; + for (cx = xSrc; cx < xSrc + wSrc; cx++) { + for (cy = ySrc; cy < ySrc + hSrc; cy++) { + /* check if we're outside the dest console */ + int dx = cx - xSrc + xDst; + int dy = cy - ySrc + yDst; + int dst_idx = dy * dst->w + dx; + int src_idx = cy * src->w + cx; + int srcChar, dstChar; + TCOD_color_t srcFgColor, srcBgColor, dstFgColor, dstBgColor; + if ((unsigned)cx >= (unsigned)src->w || (unsigned)cy >= (unsigned)src->h) continue; + if ((unsigned)dx >= (unsigned)dst->w || (unsigned)dy >= (unsigned)dst->h) continue; + srcChar = src->ch_array[src_idx]; + srcFgColor = srcFgColors[src_idx]; + srcBgColor = srcBgColors[src_idx]; + /* check if source pixel is transparent */ + if (key_color && + srcBgColor.r == key_color->r && + srcBgColor.g == key_color->g && + srcBgColor.b == key_color->b) { continue; } + + if (foreground_alpha == 1.0f && background_alpha == 1.0f) { + dstChar = srcChar; + dstFgColor = srcFgColor; + dstBgColor = srcBgColor; + } + else { + dstChar = dst->ch_array[dst_idx]; + dstFgColor = dstFgColors[dst_idx]; + dstBgColor = dstBgColors[dst_idx]; + + dstBgColor = TCOD_color_lerp(dstBgColor, srcBgColor, background_alpha); + if (srcChar == ' ') { + dstFgColor = TCOD_color_lerp(dstFgColor, srcBgColor, background_alpha); + } + else if (dstChar == ' ') { + dstChar = srcChar; + dstFgColor = TCOD_color_lerp(dstBgColor, srcFgColor, foreground_alpha); + } + else if (dstChar == srcChar) { + dstFgColor = TCOD_color_lerp(dstFgColor, srcFgColor, foreground_alpha); + } + else { + if (foreground_alpha < 0.5f) { + dstFgColor = TCOD_color_lerp(dstFgColor, dstBgColor, + foreground_alpha * 2); + } + else { + dstChar = srcChar; + dstFgColor = TCOD_color_lerp(dstBgColor, srcFgColor, + (foreground_alpha - 0.5f) * 2); + } + } + } + dstFgColors[dst_idx] = dstFgColor; + dstBgColors[dst_idx] = dstBgColor; + dst->ch_array[dst_idx] = dstChar; + } + } +} +/** + * Blit from one console to another. + * + * \param srcCon Pointer to the source console. + * \param xSrc The left region of the source console to blit from. + * \param ySrc The top region of the source console to blit from. + * \param wSrc The width of the region to blit from. + * If 0 then it will fill to the maximum width. + * \param hSrc The height of the region to blit from. + * If 0 then it will fill to the maximum height. + * \param dstCon Pointer to the destination console. + * \param xDst The left corner to blit onto the destination console. + * \param yDst The top corner to blit onto the destination console. + * \param foreground_alpha Foreground blending alpha. + * \param background_alpha Background blending alpha. + * + * If the source console has a key color, this function will use it. + */ +void TCOD_console_blit( + TCOD_console_t srcCon, int xSrc, int ySrc, int wSrc, int hSrc, + TCOD_console_t dstCon, int xDst, int yDst, + float foreground_alpha, float background_alpha) { + struct TCOD_Console *src = srcCon ? (struct TCOD_Console *)srcCon : TCOD_ctx.root; + TCOD_console_blit_key_color( + srcCon, xSrc, ySrc, wSrc, hSrc, dstCon, xDst, yDst, + foreground_alpha, background_alpha, + (src->has_key_color ? &src->key_color : NULL) + ); + } +/** + * Render and present the root console to the active display. + */ +void TCOD_console_flush(void) { + TCOD_sys_flush(true); +} +/** + * Fade the color of the display. + * + * \param val Where at 255 colors are normal and at 0 colors are completely + * faded. + * \param fadecol Color to fade towards. + */ +void TCOD_console_set_fade(uint8_t val, TCOD_color_t fadecol) { + TCOD_ctx.fade=val; + TCOD_ctx.fading_color=fadecol; +} +/** + * Return the fade value. + * + * \return At 255 colors are normal and at 0 colors are completely faded. + */ +uint8_t TCOD_console_get_fade(void) { + return TCOD_ctx.fade; +} +/** + * Return the fade color. + * + * \return The current fading color. + */ +TCOD_color_t TCOD_console_get_fading_color(void) { + return TCOD_ctx.fading_color; +} +/** + * Draw a character on a console using the default colors. + * + * \param con A console pointer. + * \param x The X coordinate, the left-most position being 0. + * \param y The Y coordinate, the top-most position being 0. + * \param c The character code to place. + * \param flag A TCOD_bkgnd_flag_t flag. + */ +void TCOD_console_put_char(TCOD_console_t con, int x, int y, int c, TCOD_bkgnd_flag_t flag) { + int offset; + struct TCOD_Console *dat = con ? (struct TCOD_Console *)con : TCOD_ctx.root; + TCOD_IFNOT(dat != NULL && (unsigned)(x) < (unsigned)dat->w && (unsigned)(y) < (unsigned)dat->h) return; + offset = y * dat->w + x; + dat->ch_array[offset] = c; + TCOD_console_set_char_foreground(dat, x, y, dat->fore); + TCOD_console_set_char_background(con, x, y, dat->back, (TCOD_bkgnd_flag_t)flag); +} +/** + * Draw a character on the console with the given colors. + * + * \param con A console pointer. + * \param x The X coordinate, the left-most position being 0. + * \param y The Y coordinate, the top-most position being 0. + * \param c The character code to place. + * \param fore The foreground color. + * \param back The background color. This color will not be blended. + */ +void TCOD_console_put_char_ex(TCOD_console_t con, int x, int y, int c, TCOD_color_t fore, TCOD_color_t back) { + int offset; + struct TCOD_Console *dat = con ? (struct TCOD_Console *)con : TCOD_ctx.root; + TCOD_IFNOT(dat != NULL && (unsigned)(x) < (unsigned)dat->w && (unsigned)(y) < (unsigned)dat->h) return; + offset = y * dat->w + x; + dat->ch_array[offset] = c; + TCOD_console_set_char_foreground(dat, x, y, fore); + TCOD_console_set_char_background(dat, x, y, back, TCOD_BKGND_SET); +} +/** + * Manually mark a region of a console as dirty. + */ +void TCOD_console_set_dirty(int dx, int dy, int dw, int dh) { + TCOD_sys_set_dirty(dx, dy, dw, dh); +} +/** + * Clear a console to its default colors and the space character code. + */ +void TCOD_console_clear(TCOD_console_t con) { + int i; + struct TCOD_Console *dat = con ? (struct TCOD_Console *)con : TCOD_ctx.root; + TCOD_IFNOT(dat != NULL) return; + for (i = 0; i < dat->w * dat->h; i++) { + dat->ch_array[i] = ' '; + dat->fg_array[i] = dat->fore; + dat->bg_array[i] = dat->back; + } + /* clear the sdl renderer cache */ + TCOD_sys_set_dirty(0, 0, dat->w, dat->h); +} +/** + * Return the background color of a console at x,y + * + * \param con A console pointer. + * \param x The X coordinate, the left-most position being 0. + * \param y The Y coordinate, the top-most position being 0. + * \return A TCOD_color_t struct with a copy of the background color. + */ +TCOD_color_t TCOD_console_get_char_background(TCOD_console_t con, int x, int y) { + struct TCOD_Console *dat = con ? (struct TCOD_Console *)con : TCOD_ctx.root; + TCOD_IFNOT(dat != NULL + && (unsigned)(x) < (unsigned)dat->w && (unsigned)(y) < (unsigned)dat->h) + return TCOD_black; + return dat->bg_array[y * dat->w + x]; +} +/** + * Change the foreground color of a console tile. + * + * \param con A console pointer. + * \param x The X coordinate, the left-most position being 0. + * \param y The Y coordinate, the top-most position being 0. + * \param col The foreground color to set. + */ +void TCOD_console_set_char_foreground(TCOD_console_t con, int x, int y, TCOD_color_t col) { + struct TCOD_Console *dat = con ? (struct TCOD_Console *)con : TCOD_ctx.root; + if ((unsigned)(x) >= (unsigned)dat->w || (unsigned)(y) >= (unsigned)dat->h) return; + TCOD_IFNOT(dat != NULL + && (unsigned)(x) < (unsigned)dat->w && (unsigned)(y) < (unsigned)dat->h) + return; + dat->fg_array[y * dat->w + x] = col; +} +/** + * Return the foreground color of a console at x,y + * + * \param con A console pointer. + * \param x The X coordinate, the left-most position being 0. + * \param y The Y coordinate, the top-most position being 0. + * \return A TCOD_color_t struct with a copy of the foreground color. + */ +TCOD_color_t TCOD_console_get_char_foreground(TCOD_console_t con, int x, int y) { + struct TCOD_Console *dat = con ? (struct TCOD_Console *)con : TCOD_ctx.root; + TCOD_IFNOT(dat != NULL + && (unsigned)(x) < (unsigned)dat->w && (unsigned)(y) < (unsigned)dat->h) + return TCOD_white; + return dat->fg_array[y * dat->w + x]; +} +/** + * Return a character code of a console at x,y + * + * \param con A console pointer. + * \param x The X coordinate, the left-most position being 0. + * \param y The Y coordinate, the top-most position being 0. + * \return The character code. + */ +int TCOD_console_get_char(TCOD_console_t con, int x, int y) { + struct TCOD_Console *dat = con ? (struct TCOD_Console *)con : TCOD_ctx.root; + TCOD_IFNOT(dat != NULL + && (unsigned)(x) < (unsigned)dat->w && (unsigned)(y) < (unsigned)dat->h) + return 0; + return dat->ch_array[y * dat->w + x]; +} +/** + * Blend a background color onto a console tile. + * + * \param con A console pointer. + * \param x The X coordinate, the left-most position being 0. + * \param y The Y coordinate, the top-most position being 0. + * \param col The background color to blend. + * \param flag The blend mode to use. + */ +void TCOD_console_set_char_background(TCOD_console_t con, int x, int y, TCOD_color_t col, TCOD_bkgnd_flag_t flag) { + TCOD_color_t *back; + int newr, newg, newb; + int alpha; + struct TCOD_Console *dat = con ? (struct TCOD_Console *)con : TCOD_ctx.root; + TCOD_IFNOT(dat != NULL + && (unsigned)(x) < (unsigned)dat->w && (unsigned)(y) < (unsigned)dat->h) + return; + back = &(dat->bg_array[y*dat->w + x]); + if (flag == TCOD_BKGND_DEFAULT) flag = dat->bkgnd_flag; + switch (flag & 0xff) { + case TCOD_BKGND_SET: *back = col; break; + case TCOD_BKGND_MULTIPLY: *back = TCOD_color_multiply(*back, col); break; + case TCOD_BKGND_LIGHTEN: + back->r = MAX(back->r, col.r); + back->g = MAX(back->g, col.g); + back->b = MAX(back->b, col.b); + break; + case TCOD_BKGND_DARKEN: + back->r = MIN(back->r, col.r); + back->g = MIN(back->g, col.g); + back->b = MIN(back->b, col.b); + break; + case TCOD_BKGND_SCREEN: + /* newbk = white - (white - oldbk) * (white - curbk) */ + back->r = (uint8_t)(255 - (int)(255 - back->r)*(255 - col.r) / 255); + back->g = (uint8_t)(255 - (int)(255 - back->g)*(255 - col.g) / 255); + back->b = (uint8_t)(255 - (int)(255 - back->b)*(255 - col.b) / 255); + break; + case TCOD_BKGND_COLOR_DODGE: + /* newbk = curbk / (white - oldbk) */ + if (back->r != 255) newr = (int)(255 * col.r) / (255 - back->r); + else newr = 255; + if (back->g != 255) newg = (int)(255 * col.g) / (255 - back->g); + else newg = 255; + if (back->b != 255) newb = (int)(255 * col.b) / (255 - back->b); + else newb = 255; + back->r = (uint8_t)CLAMP(0, 255, newr); + back->g = (uint8_t)CLAMP(0, 255, newg); + back->b = (uint8_t)CLAMP(0, 255, newb); + break; + case TCOD_BKGND_COLOR_BURN: + /* newbk = white - (white - oldbk) / curbk */ + if (col.r > 0) newr = 255 - (int)(255 * (255 - back->r)) / col.r; + else newr = 0; + if (col.g > 0) newg = 255 - (int)(255 * (255 - back->g)) / col.g; + else newg = 0; + if (col.b > 0) newb = 255 - (int)(255 * (255 - back->b)) / col.b; + else newb = 0; + back->r = (uint8_t)CLAMP(0, 255, newr); + back->g = (uint8_t)CLAMP(0, 255, newg); + back->b = (uint8_t)CLAMP(0, 255, newb); + break; + case TCOD_BKGND_ADD: + /* newbk = oldbk + curbk */ + newr = (int)(back->r) + col.r; + newg = (int)(back->g) + col.g; + newb = (int)(back->b) + col.b; + back->r = (uint8_t)CLAMP(0, 255, newr); + back->g = (uint8_t)CLAMP(0, 255, newg); + back->b = (uint8_t)CLAMP(0, 255, newb); + break; + case TCOD_BKGND_ADDA: + alpha = (flag >> 8); + /* newbk = oldbk + alpha * curbk */ + newr = (int)(back->r) + alpha * col.r / 255; + newg = (int)(back->g) + alpha * col.g / 255; + newb = (int)(back->b) + alpha * col.b / 255; + back->r = (uint8_t)CLAMP(0, 255, newr); + back->g = (uint8_t)CLAMP(0, 255, newg); + back->b = (uint8_t)CLAMP(0, 255, newb); + break; + case TCOD_BKGND_BURN: + /* newbk = oldbk + curbk - white */ + newr = (int)(back->r) + col.r - 255; + newg = (int)(back->g) + col.g - 255; + newb = (int)(back->b) + col.b - 255; + back->r = (uint8_t)CLAMP(0, 255, newr); + back->g = (uint8_t)CLAMP(0, 255, newg); + back->b = (uint8_t)CLAMP(0, 255, newb); + break; + case TCOD_BKGND_OVERLAY: + /* newbk = curbk.x <= 0.5 ? 2*curbk*oldbk : white - 2*(white-curbk)*(white-oldbk) */ + newr = col.r <= 128 ? 2 * (int)(col.r) * back->r / 255 : 255 - 2 * (int)(255 - col.r)*(255 - back->r) / 255; + newg = col.g <= 128 ? 2 * (int)(col.g) * back->g / 255 : 255 - 2 * (int)(255 - col.g)*(255 - back->g) / 255; + newb = col.b <= 128 ? 2 * (int)(col.b) * back->b / 255 : 255 - 2 * (int)(255 - col.b)*(255 - back->b) / 255; + back->r = (uint8_t)CLAMP(0, 255, newr); + back->g = (uint8_t)CLAMP(0, 255, newg); + back->b = (uint8_t)CLAMP(0, 255, newb); + break; + case TCOD_BKGND_ALPH: + /* newbk = (1.0f-alpha)*oldbk + alpha*(curbk-oldbk) */ + alpha = (flag >> 8); + *back = TCOD_color_lerp(*back, col, (float)(alpha / 255.0f)); + break; + default: break; + } +} +/** + * Change a character on a console tile, without changing its colors. + * + * \param con A console pointer. + * \param x The X coordinate, the left-most position being 0. + * \param y The Y coordinate, the top-most position being 0. + * \param c The character code to set. + */ +void TCOD_console_set_char(TCOD_console_t con, int x, int y, int c) { + struct TCOD_Console *dat = con ? (struct TCOD_Console *)con : TCOD_ctx.root; + if ((unsigned)(x) >= (unsigned)dat->w || (unsigned)(y) >= (unsigned)dat->h) return; + dat->ch_array[y * dat->w + x] = c; +} + +static void TCOD_console_clamp(int cx, int cy, int cw, int ch, int *x, int *y, int *w, int *h) { + if (*x + *w > cw) *w = cw - *x; + if (*y + *h > ch) *h = ch - *y; + if (*x < cx) { + *w -= cx - *x; + *x = cx; + } + if (*y < cy) { + *h -= cy - *y; + *y = cy; + } +} +/** + * Draw a rectangle onto a console. + * + * \param con A console pointer. + * \param x The starting region, the left-most position being 0. + * \param y The starting region, the top-most position being 0. + * \param rw The width of the rectangle. + * \param rh The height of the rectangle. + * \param clear If true the drawing region will be filled with spaces. + * \param flag The blending flag to use. + */ +void TCOD_console_rect(TCOD_console_t con, int x, int y, int rw, int rh, bool clear, TCOD_bkgnd_flag_t flag) { + int cx, cy; + struct TCOD_Console *dat = con ? (struct TCOD_Console *)con : TCOD_ctx.root; + TCOD_IFNOT(dat != NULL) return; + TCOD_ASSERT((unsigned)(x) < (unsigned)dat->w && (unsigned)(y) < (unsigned)dat->h); + TCOD_ASSERT(x + rw <= dat->w && y + rh <= dat->h); + + TCOD_console_clamp(0, 0, dat->w, dat->h, &x, &y, &rw, &rh); + TCOD_IFNOT(rw > 0 && rh > 0) return; + for (cx = x; cx < x + rw; cx++) { + for (cy = y; cyback, flag); + if (clear) { + dat->ch_array[cx + cy*dat->w] = ' '; + } + } + } +} +/** + * Draw a horizontal line using the default colors. + * + * \param con A console pointer. + * \param x The starting X coordinate, the left-most position being 0. + * \param y The starting Y coordinate, the top-most position being 0. + * \param l The width of the line. + * \param flag The blending flag. + * + * This function makes assumptions about the fonts character encoding. + * It will fail if the font encoding is not `cp437`. + */ +void TCOD_console_hline(TCOD_console_t con,int x,int y, int l, TCOD_bkgnd_flag_t flag) { + int i; + for (i=x; i< x+l; i++) TCOD_console_put_char(con,i,y,TCOD_CHAR_HLINE,flag); +} +/** + * Draw a vertical line using the default colors. + * + * \param con A console pointer. + * \param x The starting X coordinate, the left-most position being 0. + * \param y The starting Y coordinate, the top-most position being 0. + * \param l The height of the line. + * \param flag The blending flag. + * + * This function makes assumptions about the fonts character encoding. + * It will fail if the font encoding is not `cp437`. + */ +void TCOD_console_vline(TCOD_console_t con,int x,int y, int l, TCOD_bkgnd_flag_t flag) { + int i; + for (i=y; i< y+l; i++) TCOD_console_put_char(con,x,i,TCOD_CHAR_VLINE,flag); +} +/** + * \brief Initialize the libtcod graphical engine. + * + * \param w The width in tiles. + * \param h The height in tiles. + * \param title The title for the window. + * \param fullscreen Fullscreen option. + * \param renderer Which renderer to use when rendering the console. + * + * You may want to call TCOD_console_set_custom_font BEFORE calling this + * function. By default this function loads libtcod's `terminal.png` image + * from the working directory. + * + * Afterwards TCOD_quit must be called before the program exits. + */ +void TCOD_console_init_root(int w, int h, const char* title, bool fullscreen, + TCOD_renderer_t renderer) +{ + TCOD_IF(w > 0 && h > 0) { + TCOD_console_delete(NULL); + TCODConsole::root->data = TCOD_ctx.root = TCOD_console_new(w, h); +#ifndef TCOD_BARE + TCOD_ctx.renderer=renderer; +#endif + strncpy(TCOD_ctx.window_title, title, sizeof(TCOD_ctx.window_title) - 1); + TCOD_ctx.fullscreen = fullscreen; + switch (renderer) { + case TCOD_RENDERER_SDL2: { + auto tileset = tcod::engine::get_tileset(); + if (!tileset) { throw; } + auto display = std::make_shared( + tileset, + std::make_pair(tileset->get_tile_width() * w, + tileset->get_tile_height() * h), + (SDL_WINDOW_RESIZABLE | + (fullscreen ? SDL_WINDOW_FULLSCREEN_DESKTOP : 0)), + std::string(title)); + tcod::engine::set_display(display); + break; + } + default: + TCOD_console_init(TCOD_ctx.root, TCOD_ctx.window_title, + TCOD_ctx.fullscreen); + break; + } + } +} + +static void TCOD_console_data_alloc(struct TCOD_Console *dat) { + if (!dat->ch_array) { + dat->ch_array = static_cast( + calloc(sizeof(int), dat->w * dat->h)); + } + if (!dat->fg_array) { + dat->fg_array = static_cast( + calloc(sizeof(TCOD_color_t), dat->w * dat->h)); + } + if (!dat->bg_array) { + dat->bg_array = static_cast( + calloc(sizeof(TCOD_color_t), dat->w * dat->h)); + } +} + +bool TCOD_console_init(TCOD_console_t con,const char *title, bool fullscreen) { + int i; + struct TCOD_Console *dat=con ? (struct TCOD_Console *)con : TCOD_ctx.root; + TCOD_IFNOT(dat != NULL) return false; + dat->fore=TCOD_white; + dat->back=TCOD_black; + + TCOD_console_data_alloc(dat); + + dat->bkgnd_flag=TCOD_BKGND_NONE; + dat->alignment=TCOD_LEFT; + for (i=0; i< dat->w*dat->h; i++) { + dat->ch_array[i] = ' '; + } + if ( title ) { + if (! TCOD_sys_init(dat, fullscreen) ) return false; + TCOD_sys_set_window_title(title); + } + return true; +} + +void TCOD_console_set_default_foreground(TCOD_console_t con,TCOD_color_t col) { + struct TCOD_Console *dat=con ? (struct TCOD_Console *)con : TCOD_ctx.root; + TCOD_IFNOT(dat != NULL) return; + dat->fore=col; +} + +void TCOD_console_set_default_background(TCOD_console_t con,TCOD_color_t col) { + struct TCOD_Console *dat=con ? (struct TCOD_Console *)con : TCOD_ctx.root; + TCOD_IFNOT(dat != NULL) return; + dat->back=col; +} + +TCOD_color_t TCOD_console_get_default_foreground(TCOD_console_t con) { + struct TCOD_Console *dat=con ? (struct TCOD_Console *)con : TCOD_ctx.root; + TCOD_IFNOT(dat != NULL) return TCOD_white; + return dat->fore; +} + +TCOD_color_t TCOD_console_get_default_background(TCOD_console_t con) { + struct TCOD_Console *dat=con ? (struct TCOD_Console *)con : TCOD_ctx.root; + TCOD_IFNOT(dat != NULL) return TCOD_black; + return dat->back; +} + +int TCOD_console_get_width(TCOD_console_t con) { + struct TCOD_Console *dat=con ? (struct TCOD_Console *)con : TCOD_ctx.root; + TCOD_IFNOT(dat != NULL) return 0; + return dat->w; +} + +int TCOD_console_get_height(TCOD_console_t con) { + struct TCOD_Console *dat=con ? (struct TCOD_Console *)con : TCOD_ctx.root; + TCOD_IFNOT(dat != NULL) return 0; + return dat->h; +} +/** + * \brief Set a font image to be loaded during initialization. + * + * \param fontFile The path to a font image. + * \param flags A TCOD_font_flags_t bit-field describing the font image + * contents. + * \param nb_char_horiz The number of columns in the font image. + * \param nb_char_vertic The number of rows in the font image. + * + * `fontFile` will be case-sensitive depending on the platform. + */ +void TCOD_console_set_custom_font(const char *fontFile, int flags, + int nb_char_horiz, int nb_char_vertic) +{ + strcpy(TCOD_ctx.font_file, fontFile); + /* if layout not defined, assume ASCII_INCOL */ + if (!(flags & (TCOD_FONT_LAYOUT_ASCII_INCOL + | TCOD_FONT_LAYOUT_ASCII_INROW | TCOD_FONT_LAYOUT_TCOD))) { + flags |= TCOD_FONT_LAYOUT_ASCII_INCOL; + } + TCOD_ctx.font_in_row = ((flags & TCOD_FONT_LAYOUT_ASCII_INROW) != 0); + TCOD_ctx.font_greyscale = ((flags & TCOD_FONT_TYPE_GREYSCALE) != 0 ); + TCOD_ctx.font_tcod_layout = ((flags & TCOD_FONT_LAYOUT_TCOD) != 0 ); + if (nb_char_horiz > 0) { + TCOD_ctx.fontNbCharHoriz = nb_char_horiz; + TCOD_ctx.fontNbCharVertic = nb_char_vertic; + } else { + if ( ( flags & TCOD_FONT_LAYOUT_ASCII_INROW ) || ( flags & TCOD_FONT_LAYOUT_ASCII_INCOL ) ) { + TCOD_ctx.fontNbCharHoriz = nb_char_horiz = 16; + TCOD_ctx.fontNbCharVertic = nb_char_vertic = 16; + } else { + TCOD_ctx.fontNbCharHoriz = nb_char_horiz = 32; + TCOD_ctx.fontNbCharVertic = nb_char_vertic = 8; + } + } + if (TCOD_ctx.font_tcod_layout) { TCOD_ctx.font_in_row = true; } + TCOD_sys_set_custom_font(fontFile, nb_char_horiz, nb_char_vertic, flags); + + using tcod::image::Image; + using tcod::tileset::Tileset; + using tcod::tileset::Tilesheet; + + try { + Image image = tcod::image::load(TCOD_ctx.font_file); + auto tilesheet = std::make_shared( + image, std::make_pair(nb_char_horiz, nb_char_vertic)); + tcod::engine::set_tilesheet(tilesheet); + + auto tileset = std::make_shared(tilesheet->get_tile_width(), + tilesheet->get_tile_height()); + tcod::engine::set_tileset(tileset); + if (flags & TCOD_FONT_LAYOUT_TCOD) { + for (int i = 0; i < static_cast(tcod_codec_.size()); ++i) { + tileset->set_tile(i, tilesheet->get_tile(tcod_codec_.at(i))); + } + } else if (flags & TCOD_FONT_LAYOUT_ASCII_INROW) { + for (int i = 0; i < tilesheet->count(); ++i) { + tileset->set_tile(i, tilesheet->get_tile(i)); + } + } else if (flags & TCOD_FONT_LAYOUT_ASCII_INCOL) { + for (int x = 0; x < tilesheet->get_columns(); ++x) { + for (int y = 0; y < tilesheet->get_rows(); ++y) { + int i = x * tilesheet->get_rows() + y; + tileset->set_tile(i, tilesheet->get_tile(x, y)); + } + } + } + } catch (const std::runtime_error&) { + // Ignore any runtime error, will likely catch a missing file error. + return; + } catch (const std::logic_error&) { + return; // Ignore logic errors from constructing objects. + } +} +/** + * \brief Remap a character code to a tile. + * + * \param asciiCode Character code to modify. + * \param fontCharX X tile-coordinate, starting from the left at zero. + * \param fontCharY Y tile-coordinate, starting from the top at zero. + * + * X,Y parameters are the coordinate of the tile, not pixel-coordinates. + */ +void TCOD_console_map_ascii_code_to_font(int asciiCode, int fontCharX, int fontCharY) { + /* cannot change mapping before initRoot is called */ + TCOD_IFNOT(TCOD_ctx.root != NULL) return; + TCOD_sys_map_ascii_to_font(asciiCode, fontCharX, fontCharY); +} +/** + * \brief Remap a series of character codes to a row of tiles. + * + * \param asciiCode The starting character code. + * \param nbCodes Number of character codes to assign. + * \param fontCharX First X tile-coordinate, starting from the left at zero. + * \param fontCharY First Y tile-coordinate, starting from the top at zero. + * + * This function always assigns tiles in row-major order, even if the + * TCOD_FONT_LAYOUT_ASCII_INCOL flag was set. + */ +void TCOD_console_map_ascii_codes_to_font(int asciiCode, int nbCodes, int fontCharX, int fontCharY) { + int c; + /* cannot change mapping before initRoot is called */ + TCOD_IFNOT(TCOD_ctx.root != NULL) return; + TCOD_IFNOT(asciiCode >= 0 && asciiCode+nbCodes <= TCOD_ctx.max_font_chars) return; + for (c=asciiCode; c < asciiCode+nbCodes; c++ ) { + TCOD_sys_map_ascii_to_font(c, fontCharX, fontCharY); + fontCharX++; + if ( fontCharX == TCOD_ctx.fontNbCharHoriz ) { + fontCharX=0; + fontCharY++; + } + } +} +/** + * \brief Remap a string of character codes to a row of tiles. + * + * \param s A null-terminated string. + * \param fontCharX First X tile-coordinate, starting from the left at zero. + * \param fontCharY First Y tile-coordinate, starting from the top at zero. + * + * This function always assigns tiles in row-major order, even if the + * TCOD_FONT_LAYOUT_ASCII_INCOL flag was set. + */ +void TCOD_console_map_string_to_font(const char *s, int fontCharX, int fontCharY) { + TCOD_IFNOT(s != NULL) return; + /* cannot change mapping before initRoot is called */ + TCOD_IFNOT(TCOD_ctx.root != NULL) return; + while (*s) { + TCOD_console_map_ascii_code_to_font(*s, fontCharX, fontCharY); + fontCharX++; + if ( fontCharX == TCOD_ctx.fontNbCharHoriz ) { + fontCharX=0; + fontCharY++; + } + s++; + } +} + +bool TCOD_console_is_key_pressed(TCOD_keycode_t key) { + return TCOD_sys_is_key_pressed(key); +} +void TCOD_console_set_key_color(TCOD_console_t con,TCOD_color_t col) { + struct TCOD_Console *dat=con ? (struct TCOD_Console *)con : TCOD_ctx.root; + if (!dat) { return; } + dat->has_key_color = 1; + dat->key_color = col; +} + +void TCOD_console_credits(void) { + bool end=false; + int x=TCOD_console_get_width(NULL)/2-6; + int y=TCOD_console_get_height(NULL)/2; + int fade=260; + TCOD_sys_save_fps(); + TCOD_sys_set_fps(25); + while (!end ) { + TCOD_key_t k; + end=TCOD_console_credits_render(x,y,false); + TCOD_sys_check_for_event(TCOD_EVENT_KEY_PRESS,&k,NULL); + if ( fade == 260 && k.vk != TCODK_NONE ) { + fade -= 10; + } + TCOD_console_flush(); + if ( fade < 260 ) { + fade -= 10; + TCOD_console_set_fade(fade,TCOD_black); + if ( fade == 0 ) end=true; + } + } + TCOD_console_set_fade(255,TCOD_black); + TCOD_sys_restore_fps(); +} + +static bool init2=false; + +void TCOD_console_credits_reset(void) { + init2=false; +} + +bool TCOD_console_credits_render(int x, int y, bool alpha) { + static char poweredby[128]; + static float char_heat[128]; + static int char_x[128]; + static int char_y[128]; + static bool init1=false; + static int len,len1,cw=-1,ch=-1; + static float xstr; + static TCOD_color_t colmap[64]; + static TCOD_color_t colmap_light[64]; + static TCOD_noise_t noise; + static TCOD_color_t colkeys[4] = { + {255,255,204}, + {255,204,0}, + {255,102,0}, + {102,153,255}, + }; + static TCOD_color_t colkeys_light[4] = { + {255,255,204}, + {128,128,77}, + {51,51,31}, + {0,0,0}, + }; + static int colpos[4]={ + 0,21,42,63 + }; + static TCOD_image_t img=NULL; + int i,xc,yc,xi,yi,j; + static int left,right,top,bottom; + float sparklex,sparkley,sparklerad,sparklerad2,noisex; + /* mini particule system */ +#define MAX_PARTICULES 50 + static float pheat[MAX_PARTICULES]; + static float px[MAX_PARTICULES],py[MAX_PARTICULES], pvx[MAX_PARTICULES],pvy[MAX_PARTICULES]; + static int nbpart=0, firstpart=0; + static float partDelay=0.1f; + float elapsed=TCOD_sys_get_last_frame_length(); + TCOD_color_t fbackup; /* backup fg color */ + + if (!init1) { + /* initialize all static data, colormaps, ... */ + TCOD_color_t col; + TCOD_color_gen_map(colmap,4,colkeys,colpos); + TCOD_color_gen_map(colmap_light,4,colkeys_light,colpos); + sprintf(poweredby,"Powered by\n%s",version_string); + noise=TCOD_noise_new(1,TCOD_NOISE_DEFAULT_HURST,TCOD_NOISE_DEFAULT_LACUNARITY,NULL); + len=(int)strlen(poweredby); + len1=11; /* sizeof "Powered by\n" */ + left=MAX(x-4,0); + top=MAX(y-4,0); + col= TCOD_console_get_default_background(NULL); + TCOD_console_set_default_background(NULL,TCOD_black); + TCOD_console_set_default_background(NULL,col); + init1=true; + } + if (!init2) { + /* reset the credits vars ... */ + int curx,cury; + xstr=-4.0f; + curx=x; + cury=y; + for (i=0; i < len ;i++) { + char_heat[i]=-1; + char_x[i]=curx; + char_y[i]=cury; + curx++; + if ( poweredby[i] == '\n' ) { + curx=x; + cury++; + } + } + nbpart=firstpart=0; + init2=true; + } + if (TCOD_console_get_width(NULL) != cw || TCOD_console_get_height(NULL)!=ch) { + /* console size has changed */ + int width,height; + cw=TCOD_console_get_width(NULL); + ch=TCOD_console_get_height(NULL); + right=MIN(x+len,cw-1); + bottom=MIN(y+6,ch-1); + width=right - left + 1; + height=bottom - top + 1; + if ( img ) TCOD_image_delete(img); + img = TCOD_image_new(width*2,height*2); + } + fbackup=TCOD_console_get_default_foreground(NULL); + if ( xstr < (float)len1 ) { + sparklex=x+xstr; + sparkley=(float)y; + } else { + sparklex=x-len1+xstr; + sparkley=(float)y+1; + } + noisex=xstr*6; + sparklerad=3.0f+2*TCOD_noise_get(noise,&noisex); + if ( xstr >= len-1 ) sparklerad -= (xstr-len+1)*4.0f; + else if ( xstr < 0.0f ) sparklerad += xstr*4.0f; + else if ( poweredby[ (int)(xstr+0.5f) ] == ' ' || poweredby[ (int)(xstr+0.5f) ] == '\n' ) sparklerad/=2; + sparklerad2=sparklerad*sparklerad*4; + + /* draw the light */ + for (xc=left*2,xi=0; xc < (right+1)*2; xc++,xi++) { + for (yc=top*2,yi=0; yc < (bottom+1)*2; yc++,yi++) { + float dist=((xc-2*sparklex)*(xc-2*sparklex)+(yc-2*sparkley)*(yc-2*sparkley)); + TCOD_color_t pixcol; + if ( sparklerad >= 0.0f && dist < sparklerad2 ) { + int colidx=63-(int)(63*(sparklerad2-dist)/sparklerad2) + TCOD_random_get_int(NULL,-10,10); + colidx=CLAMP(0,63,colidx); + pixcol=colmap_light[colidx]; + } else { + pixcol=TCOD_black; + } + if ( alpha ) { + /* console cells have following flag values : + 1 2 + 4 8 + flag indicates which subcell uses foreground color */ + static int asciiToFlag[] = { + 1, /* TCOD_CHAR_SUBP_NW */ + 2, /* TCOD_CHAR_SUBP_NE */ + 3, /* TCOD_CHAR_SUBP_N */ + 8, /* TCOD_CHAR_SUBP_SE */ + 9, /* TCOD_CHAR_SUBP_DIAG */ + 10, /* TCOD_CHAR_SUBP_E */ + 4, /* TCOD_CHAR_SUBP_SW */ + }; + int conc= TCOD_console_get_char(NULL,xc/2,yc/2); + TCOD_color_t bk=TCOD_console_get_char_background(NULL,xc/2,yc/2); + if ( conc >= TCOD_CHAR_SUBP_NW && conc <= TCOD_CHAR_SUBP_SW ) { + /* merge two subcell chars... + get the flag for the existing cell on root console */ + int bkflag=asciiToFlag[conc - TCOD_CHAR_SUBP_NW ]; + int xflag = (xc & 1); + int yflag = (yc & 1); + /* get the flag for the current subcell */ + int credflag = (1+3*yflag) * (xflag+1); + if ( (credflag & bkflag) != 0 ) { + /* the color for this subcell on root console + is foreground, not background */ + bk = TCOD_console_get_char_foreground(NULL,xc/2,yc/2); + } + } + pixcol.r = MIN(255,(int)(bk.r)+pixcol.r); + pixcol.g = MIN(255,(int)(bk.g)+pixcol.g); + pixcol.b = MIN(255,(int)(bk.b)+pixcol.b); + } + TCOD_image_put_pixel(img,xi,yi,pixcol); + } + } + + /* draw and update the particules */ + j=nbpart;i=firstpart; + while (j > 0) { + int colidx=(int)(64*(1.0f-pheat[i])); + TCOD_color_t col; + colidx=MIN(63,colidx); + col=colmap[colidx]; + if ( (int)py[i]< (bottom-top+1)*2 ) { + int ipx = (int)px[i]; + int ipy = (int)py[i]; + float fpx = px[i]-ipx; + float fpy = py[i]-ipy; + TCOD_color_t col2=TCOD_image_get_pixel(img,ipx,ipy); + col2=TCOD_color_lerp(col,col2,0.5f*(fpx+fpy)); + TCOD_image_put_pixel(img,ipx,ipy,col2); + col2=TCOD_image_get_pixel(img,ipx+1,ipy); + col2=TCOD_color_lerp(col2,col,fpx); + TCOD_image_put_pixel(img,ipx+1,ipy,col2); + col2=TCOD_image_get_pixel(img,ipx,ipy+1); + col2=TCOD_color_lerp(col2,col,fpy); + TCOD_image_put_pixel(img,ipx,ipy+1,col2); + } else pvy[i]=-pvy[i] * 0.5f; + pvx[i] *= (1.0f-elapsed); + pvy[i] += (1.0f-pheat[i])*elapsed*300.0f; + px[i] += pvx[i]*elapsed; + py[i] += pvy[i]*elapsed; + pheat[i] -= elapsed*0.3f; + if ( pheat[i] < 0.0f ) { + firstpart = (firstpart+1)%MAX_PARTICULES; + nbpart--; + } + i = (i+1)%MAX_PARTICULES; + j--; + } + partDelay -= elapsed; + if ( partDelay < 0.0f && nbpart < MAX_PARTICULES && sparklerad > 2.0f ) { + /* fire a new particule */ + int lastpart = firstpart; + int nb=nbpart; + while (nb > 0 ) { + lastpart = ( lastpart + 1 )%MAX_PARTICULES; + nb--; + } + nbpart++; + px[lastpart] = 2*(sparklex-left); + py[lastpart] = 2*(sparkley-top)+2; + pvx[lastpart] = TCOD_random_get_float(NULL,-5.0f,5.0f); + pvy[lastpart] = TCOD_random_get_float(NULL,-0.5f, -15.0f); + pheat[lastpart] = 1.0f; + partDelay += 0.1f; + } + TCOD_image_blit_2x(img,NULL,left,top,0,0,-1,-1); + /* draw the text */ + for (i=0; i < len ;i++) { + if ( char_heat[i] >= 0.0f && poweredby[i]!='\n') { + int colidx=(int)(64*char_heat[i]); + TCOD_color_t col; + colidx=MIN(63,colidx); + col=colmap[colidx]; + if ( xstr >= len ) { + float coef=(xstr-len)/len; + if ( alpha ) { + TCOD_color_t fore=TCOD_console_get_char_background(NULL,char_x[i],char_y[i]); + int r=(int)(coef*fore.r + (1.0f-coef)*col.r); + int g=(int)(coef*fore.g + (1.0f-coef)*col.g); + int b=(int)(coef*fore.b + (1.0f-coef)*col.b); + col.r = CLAMP(0,255,r); + col.g = CLAMP(0,255,g); + col.b = CLAMP(0,255,b); + TCOD_console_set_char_foreground(NULL,char_x[i],char_y[i],col); + } else { + col=TCOD_color_lerp(col,TCOD_black,coef); + } + } + TCOD_console_set_char(NULL,char_x[i],char_y[i],poweredby[i]); + TCOD_console_set_char_foreground(NULL,char_x[i],char_y[i],col); + } + } + /* update letters heat */ + xstr += elapsed * 4; + for (i=0; i < (int)(xstr+0.5f); i++) { + char_heat[i]=(xstr-i)/(len/2); + } + /* restore fg color */ + TCOD_console_set_default_foreground(NULL,fbackup); + if ( xstr <= 2*len ) return false; + init2=false; + return true; +} + +static void TCOD_console_read_asc(TCOD_console_t con,FILE *f,int width, int height, float version) { + int x,y; + struct TCOD_Console *dat=con ? (struct TCOD_Console *)con : TCOD_ctx.root; + TCOD_IFNOT(dat != NULL) return; + while(fgetc(f) != '#'); + for(x = 0; x < width; x++) { + for(y = 0; y < height; y++) { + TCOD_color_t fore,back; + int c = fgetc(f); + fore.r = fgetc(f); + fore.g = fgetc(f); + fore.b = fgetc(f); + back.r = fgetc(f); + back.g = fgetc(f); + back.b = fgetc(f); + /* skip solid/walkable info */ + if ( version >= 0.3f ) { + fgetc(f); + fgetc(f); + } + TCOD_console_put_char_ex(con,x,y,c,fore,back); + } + } + fclose(f); +} + +static void TCOD_console_read_apf(TCOD_console_t con,FILE *f,int width, int height, float version) { +} + +static int string_ends_with(const char *str, const char *suffix) { + size_t str_len = strlen(str); + size_t suffix_len = strlen(suffix); + return + (str_len >= suffix_len) && + (0 == strcmp(str + (str_len-suffix_len), suffix)); +} + +TCOD_console_t TCOD_console_from_file(const char *filename) { + float version; + int width,height; + TCOD_console_t con; + FILE *f; + TCOD_IFNOT( filename != NULL ) { + return NULL; + } + if (string_ends_with(filename, ".xp")) { + return TCOD_console_from_xp(filename); + } + f=fopen(filename,"rb"); + TCOD_IFNOT( f!=NULL ) { + return NULL; + } + if (fscanf(f, "ASCII-Paint v%g", &version) != 1 ) { + fclose(f); + return NULL; + } + if (fscanf(f, "%i %i", &width, &height) != 2 ) { + fclose(f); + return NULL; + } + TCOD_IFNOT ( width > 0 && height > 0) { + fclose(f); + return NULL; + } + con=TCOD_console_new(width,height); + if (string_ends_with(filename, ".asc")) { + TCOD_console_read_asc(con,f,width,height,version); + } else { + TCOD_console_read_apf(con,f,width,height,version); + } + return con; +} + +bool TCOD_console_load_asc(TCOD_console_t pcon, const char *filename) { + float version; + int width,height; + FILE *f; + struct TCOD_Console *con=pcon ? (struct TCOD_Console *)pcon : TCOD_ctx.root; + TCOD_IFNOT(con != NULL) return false; + TCOD_IFNOT( filename != NULL ) { + return false; + } + f=fopen(filename,"rb"); + TCOD_IFNOT( f!=NULL ) { + return false; + } + if (fscanf(f, "ASCII-Paint v%g", &version) != 1 ) { + fclose(f); + return false; + } + if (fscanf(f, "%i %i", &width, &height) != 2 ) { + fclose(f); + return false; + } + TCOD_IFNOT ( width > 0 && height > 0) { + fclose(f); + return false; + } + if ( con->w != width || con->h != height ) { + /* resize console */ + TCOD_console_data_free(con); + con->w = width; + con->h = height; + TCOD_console_data_alloc(con); + } + TCOD_console_read_asc(con,f,width,height,version); + return true; +} + +bool TCOD_console_save_asc(TCOD_console_t pcon, const char *filename) { + static float version = 0.3f; + FILE *f; + int x,y; + struct TCOD_Console *con=pcon ? (struct TCOD_Console *)pcon : TCOD_ctx.root; + TCOD_IFNOT(con != NULL) return false; + TCOD_IFNOT( filename != NULL ) { + return false; + } + TCOD_IFNOT(con->w > 0 && con->h > 0) return false; + f=fopen(filename,"wb"); + TCOD_IFNOT( f != NULL ) return false; + fprintf(f, "ASCII-Paint v%g\n", version); + fprintf(f, "%i %i\n", con->w, con->h); + fputc('#', f); + for(x = 0; x < con->w; x++) { + for(y = 0; y < con->h; y++) { + TCOD_color_t fore,back; + int c=TCOD_console_get_char(con,x,y); + fore=TCOD_console_get_char_foreground(con,x,y); + back=TCOD_console_get_char_background(con,x,y); + fputc(c, f); + fputc(fore.r,f); + fputc(fore.g,f); + fputc(fore.b,f); + fputc(back.r,f); + fputc(back.g,f); + fputc(back.b,f); + fputc(0,f); /* solid */ + fputc(1,f); /* walkable */ + } + } + fclose(f); + return true; +} + +static bool hasDetectedBigEndianness = false; +static bool isBigEndian; +void detectBigEndianness(void) { + if (!hasDetectedBigEndianness){ + uint32_t Value32; + uint8_t *VPtr = (uint8_t *)&Value32; + VPtr[0] = VPtr[1] = VPtr[2] = 0; VPtr[3] = 1; + if(Value32 == 1) isBigEndian = true; + else isBigEndian = false; + hasDetectedBigEndianness = true; + } +} + +uint16_t bswap16(uint16_t s){ + uint8_t* ps = (uint8_t*)&s; + uint16_t res; + uint8_t* pres = (uint8_t*)&res; + pres[0] = ps[1]; + pres[1] = ps[0]; + return res; +} + +uint32_t bswap32(uint32_t s){ + uint8_t *ps=(uint8_t *)(&s); + uint32_t res; + uint8_t *pres=(uint8_t *)&res; + pres[0]=ps[3]; + pres[1]=ps[2]; + pres[2]=ps[1]; + pres[3]=ps[0]; + return res; +} + +uint16_t l16(uint16_t s){ + if (isBigEndian) return bswap16(s); else return s; +} + +uint32_t l32(uint32_t s){ + if (isBigEndian) return bswap32(s); else return s; +} + +/* fix the endianness */ +void fix16(uint16_t* u){ + *u = l16(*u); +} + +void fix32(uint32_t* u){ + *u = l32(*u); +} + +/************ RIFF helpers */ + +uint32_t fourCC(const char* c){ + return (*(uint32_t*)c); +} + +/* checks if u equals str */ +bool fourCCequals(uint32_t u, const char* str){ + return fourCC(str)==u; +} + +void fromFourCC(uint32_t u, char*s){ + const char* c = (const char*)(&u); + s[0]=c[0]; + s[1]=c[1]; + s[2]=c[2]; + s[3]=c[3]; + s[4]=0; +} + +void put8(uint8_t d, FILE* fp){ + fwrite(&d,1,1,fp); +} + +void put16(uint16_t d, FILE* fp){ + fwrite(&d,2,1,fp); +} + +void put32(uint32_t d, FILE* fp){ + fwrite(&d,4,1,fp); +} + +void putFourCC(const char* c, FILE* fp){ + put32(fourCC(c),fp); +} + +void putData(void* what, int length, FILE* fp){ + fwrite(what,length,1,fp); +} + +bool get8(uint8_t* u, FILE* fp){ + return 1==fread((void*)u, sizeof(uint8_t),1,fp); +} + +bool get16(uint16_t* u, FILE* fp){ + return 1==fread((void*)u, sizeof(uint16_t),1,fp); +} + +bool get32(uint32_t* u, FILE* fp){ + return 1==fread((void*)u, sizeof(uint32_t),1,fp); +} + +bool getData(void* u, size_t sz, FILE* fp){ + return 1==fread(u, sz,1,fp); +} + + +/********* APF RIFF structures */ + +typedef struct { + uint32_t show_grid; + uint32_t grid_width; + uint32_t grid_height; +} SettingsDataV1; + +#define FILTER_TYPE_UNCOMPRESSED 0 +#define FORMAT_TYPE_CRGBRGB 0 + +typedef struct { + uint32_t width; + uint32_t height; + uint32_t filter; + uint32_t format; +} ImageDetailsV1; + +/* Layers */ + +typedef struct { + uint32_t name; + uint32_t mode; + uint32_t index; + uint32_t dataSize; +} LayerV1 ; + +typedef struct { + uint32_t name; + uint32_t mode; + uint32_t fgalpha; + uint32_t bgalpha; + uint32_t visible; + uint32_t index; + uint32_t dataSize; +} LayerV2; + +/* fix the endianness */ +void fixSettings(SettingsDataV1* s){ + fix32(&s->show_grid); + fix32(&s->grid_width); + fix32(&s->grid_height); +} + +void fixImage(ImageDetailsV1* v){ + fix32(&v->width); + fix32(&v->height); + fix32(&v->filter); + fix32(&v->format); +} + +void fixLayerv1(LayerV1* l){ + fix32(&l->mode); + fix32(&l->index); + fix32(&l->dataSize); +} + +void fixLayerv2(LayerV2* l){ + fix32(&l->mode); + fix32(&l->fgalpha); + fix32(&l->bgalpha); + fix32(&l->visible); + fix32(&l->index); + fix32(&l->dataSize); +} + + +/*********** ApfFile */ + +bool TCOD_console_save_apf(TCOD_console_t pcon, const char *filename) { + struct TCOD_Console *con=pcon ? (struct TCOD_Console *)pcon : TCOD_ctx.root; + FILE* fp ; + TCOD_IFNOT(con != NULL) return false; + detectBigEndianness(); + + fp = fopen(filename, "wb"); + if(fp == NULL) { + return false; + } + else { + int x,y; + uint32_t riffSize = 0; + uint32_t imgDetailsSize ; + SettingsDataV1 settingsData; + ImageDetailsV1 imgData; + fpos_t posRiffSize; + uint32_t settingsSz ; + uint32_t layerImageSize ; + uint32_t layerChunkSize ; + /* riff header*/ + putFourCC("RIFF",fp); + fgetpos(fp,&posRiffSize); + put32(0,fp); + + /* APF_ header */ + putFourCC("apf ",fp); + riffSize += 4; + + /* settings */ + settingsData.show_grid = 0; + settingsData.grid_width = 8; + settingsData.grid_height = 8; + settingsSz = sizeof(uint32_t) + sizeof settingsData; + putFourCC("sett",fp); + put32(l32(settingsSz),fp); + put32(l32(1),fp); + putData((void*)&settingsData,sizeof settingsData,fp); + if (settingsSz&1){ + put8(0,fp); + riffSize++; + } + riffSize += 4+4+settingsSz; + + /* image details */ + imgData.width = con->w; + imgData.height = con->h; + imgData.filter = 0; + imgData.format = 0; + imgDetailsSize = sizeof(uint32_t) + sizeof imgData; + putFourCC("imgd",fp); + put32(l32(imgDetailsSize),fp); + put32(l32(1),fp); + putData((void*)&imgData,sizeof imgData,fp); + if (imgDetailsSize&1){ + put8(0,fp); + riffSize++; + } + riffSize += 4+4+imgDetailsSize; + + /* now write the layers as a RIFF list + the first layer is the lowest layer + Assume imgData filter = uncompressed, and imgData format = CRGB */ + layerImageSize = imgData.width*imgData.height*7; + layerChunkSize = sizeof(uint32_t) /* version */ + + sizeof(LayerV2) /* header */ + + layerImageSize; /* data */ + + putFourCC("layr",fp); /* layer */ + put32(l32(layerChunkSize),fp); + /* VERSION -> */ + put32(l32(2),fp); + /* Data */ + putFourCC("LAY0",fp); + put32(l32(0),fp); + put32(l32(255),fp); + put32(l32(255),fp); + put32(l32(1),fp); + put32(l32(0),fp); + put32(l32(layerImageSize),fp); + + /* now write out the data */ + + for(x = 0; x < con->w; x++) { + for(y = 0; y < con->h; y++) { + TCOD_color_t fore,back; + int c=TCOD_console_get_char(con,x,y); + fore=TCOD_console_get_char_foreground(con,x,y); + back=TCOD_console_get_char_background(con,x,y); + put8(c, fp); + put8(fore.r,fp); + put8(fore.g,fp); + put8(fore.b,fp); + put8(back.r,fp); + put8(back.g,fp); + put8(back.b,fp); + } + } + + if (layerChunkSize&1){ + put8(0,fp); /* padding bit */ + riffSize++; + } + + riffSize += 2*sizeof(uint32_t)+layerChunkSize; + + fsetpos(fp,&posRiffSize); + put32(l32(riffSize),fp); + } + + fclose(fp); + return true; +} + +typedef struct { + LayerV1 headerv1; + LayerV2 headerv2; + uint8_t* data; /* dynamically allocated */ +} LayerData; + +typedef struct { + ImageDetailsV1 details; + SettingsDataV1 settings; + LayerData layer; +} Data; + +bool TCOD_console_load_apf(TCOD_console_t pcon, const char *filename) { + uint32_t sett = fourCC("sett"); + uint32_t imgd = fourCC("imgd"); + /* + uint32_t LIST = fourCC("LIST"); + uint32_t LAYR = fourCC("LAYR"); + */ + uint32_t layr = fourCC("layr"); + FILE* fp ; + Data data; + struct TCOD_Console *con=pcon ? (struct TCOD_Console *)pcon : TCOD_ctx.root; + TCOD_IFNOT(con != NULL) return false; + + detectBigEndianness(); + data.details.width = 1; + data.details.height = 1; + data.details.filter = 0; + data.details.format = 0; + + data.settings.show_grid = true; + data.settings.grid_width = 10; + data.settings.grid_height = 10; + + #define ERR(x) {printf("Error: %s\n. Aborting operation.",x); return false;} + #define ERR_NEWER(x) {printf("Error: It looks like this file was made with a newer version of Ascii-Paint\n. In particular the %s field. Aborting operation.",x); return false;} + + fp = fopen(filename, "rb"); + if(fp == NULL) { + printf("The file %s could not be loaded.\n", filename); + return false; + } + else { + /* read the header */ + uint32_t riff; + uint32_t riffSize; + int index = 0; + int x,y; + uint8_t *imgData; + bool keepGoing = true; + if (! get32(&riff,fp) || ! fourCCequals(riff,"RIFF")){ + ERR("File doesn't have a RIFF header"); + } + if (!get32(&riffSize,fp)) ERR("No RIFF size field!"); + fix32(&riffSize); + + while(keepGoing && fp){ /* for each subfield, try to find the APF_ field */ + uint32_t apf; + if (! get32(&apf,fp)) break; + if (fourCCequals(apf,"apf ") || fourCCequals(apf,"APF ")){ + /* Process APF segment */ + while(keepGoing && fp){ + uint32_t seg; + if (! get32(&seg,fp)){ + keepGoing = false; + break; + } + else { + if (seg==sett){ + /* size */ + uint32_t sz; + uint32_t ver; + SettingsDataV1 settingsData; + + get32(&sz,fp); + fix32(&sz); + /* version */ + get32(&ver,fp); + fix32(&ver); + if (ver!=1) ERR_NEWER("settings"); + /* ver must be 1 */ + if (! getData((void*)&settingsData,sizeof settingsData,fp)) ERR("Can't read settings."); + data.settings = settingsData; + fixSettings(&data.settings); + + } + else if (seg==imgd){ + /* sz */ + uint32_t sz; + uint32_t ver; + ImageDetailsV1 dets; + + get32(&sz,fp); + fix32(&sz); + /* version */ + get32(&ver,fp); + fix32(&ver); + if (ver!=1) ERR_NEWER("image details"); + /* ver must be 1 */ + if (! getData((void*)&dets, sizeof dets, fp)) ERR("Can't read image details."); + data.details = dets; + fixImage(&data.details); + + /* get canvas ready */ + TCOD_IFNOT ( data.details.width > 0 && data.details.height > 0) { + fclose(fp); + return false; + } + if (con->w != static_cast(data.details.width) || con->h != static_cast(data.details.height)) { + /* resize console */ + TCOD_console_data_free(con); + con->w = data.details.width; + con->h = data.details.height; + TCOD_console_data_alloc(con); + } + + } + else if (seg==layr){ + uint32_t sz; + uint32_t ver; + + get32(&sz,fp); + fix32(&sz); + /* version */ + get32(&ver,fp); + fix32(&ver); + if (ver>2) ERR_NEWER("layer spec"); + + if (ver==1){ + if (! getData((void*)&data.layer.headerv1, sizeof( LayerV1 ), fp)) ERR("Can't read layer header."); + fixLayerv1(&data.layer.headerv1); + + /* Read in the data chunk*/ + data.layer.data = (uint8_t*)malloc(sizeof(uint8_t)*data.layer.headerv1.dataSize); + getData((void*) data.layer.data, data.layer.headerv1.dataSize, fp); + } + else if (ver==2){ + if (! getData((void*)&data.layer.headerv2, sizeof( LayerV2 ), fp)) ERR("Can't read layer header."); + fixLayerv2(&data.layer.headerv2); + + /* Read in the data chunk */ + data.layer.data = (uint8_t*)malloc(sizeof(uint8_t)*data.layer.headerv2.dataSize); + getData((void*) data.layer.data, data.layer.headerv2.dataSize, fp); + + } + } + else { + /* skip unknown segment */ + uint32_t sz; + get32(&sz,fp); + fix32(&sz); + fseek(fp,sz,SEEK_CUR); + } + } + } + + /* we're done! */ + keepGoing = false; + } + else { + /* skip this segment */ + uint32_t sz; + get32(&sz,fp); + fseek(fp,sz,SEEK_CUR); + } + } + + imgData = data.layer.data; + for(x = 0; x < con->w; x++) { + for(y = 0; y < con->h; y++) { + TCOD_color_t fore,back; + int c = (unsigned char)(imgData[index++]); + fore.r = (uint8_t)(imgData[index++]); + fore.g = (uint8_t)(imgData[index++]); + fore.b = (uint8_t)(imgData[index++]); + back.r = (uint8_t)(imgData[index++]); + back.g = (uint8_t)(imgData[index++]); + back.b = (uint8_t)(imgData[index++]); + TCOD_console_put_char_ex(con,x,y,c,fore,back); + } + } + + free (data.layer.data); + } + fclose(fp); + + return true; +} +/* + +bool ApfFile::Load(std::string filename){ + detectBigEndianness(); + + uint32_t sett = fourCC("sett"); + uint32_t imgd = fourCC("imgd"); + uint32_t LIST = fourCC("LIST"); + uint32_t LAYR = fourCC("LAYR"); + uint32_t layr = fourCC("layr"); + + Data data; // File data + + data.details.width = 1; + data.details.height = 1; + data.details.filter = FILTER_TYPE_UNCOMPRESSED; + data.details.format = FORMAT_TYPE_CRGBRGB; + + data.settings.show_grid = true; + data.settings.grid_width = 10; + data.settings.grid_height = 10; + + data.currentLayer = NULL; + + #define ERR(x) {printf("Error: %s\n. Aborting operation.",x); return false;} + #define ERR_NEWER(x) {printf("Error: It looks like this file was made with a newer version of Ascii-Paint\n. In particular the %s field. Aborting operation.",x); return false;} + + FILE* fp = fopen(filename.c_str(), "rb"); + if(fp == NULL) { + printf("The file %s could not be loaded.\n", filename.c_str()); + return false; + } + else { + // read the header + uint32_t riff; + if (not get32(&riff,fp) + or + not fourCCequals(riff,"RIFF")){ + ERR("File doesn't have a RIFF header"); + } + // else + uint32_t riffSize; + if (!get32(&riffSize,fp)) ERR("No RIFF size field!"); + fix(&riffSize); + + bool keepGoing = true; + while(keepGoing and fp){ // for each subfield, try to find the APF_ field + uint32_t apf; + if (not get32(&apf,fp)) break; + if (fourCCequals(apf,"apf ") or fourCCequals(apf,"APF ")){ + // Process APF segment + while(keepGoing and fp){ + uint32_t seg; + if (not get32(&seg,fp)){ + keepGoing = false; + break; + } + else { + if (seg==sett){ + // size + uint32_t sz; + get32(&sz,fp); + fix(&sz); + // version + uint32_t ver; + get32(&ver,fp); + fix(&ver); + if (ver!=1) ERR_NEWER("settings"); + // ver must be 1 + SettingsDataV1 settingsData; + if (not getData((void*)&settingsData,sizeof settingsData,fp)) ERR("Can't read settings."); + data.settings = settingsData; + fix(&data.settings); + + // Change app settings + app->setGridDimensions(data.settings.grid_width,data.settings.grid_height); + app->setShowGrid(data.settings.show_grid==1); + } + else if (seg==imgd){ + // sz + uint32_t sz; + get32(&sz,fp); + fix(&sz); + // version + uint32_t ver; + get32(&ver,fp); + fix(&ver); + if (ver!=1) ERR_NEWER("image details"); + // ver must be 1 + ImageDetailsV1 dets; + if (not getData((void*)&dets, sizeof dets, fp)) ERR("Can't read image details."); + data.details = dets; + fix(&data.details); + + // get canvas ready + app->canvasWidth = data.details.width; + app->canvasHeight = data.details.height; + app->initCanvas(); + + // delete new layer + app->deleteLayer(app->getCurrentLayer()->name); + + } + else if (seg==layr){ + // printf("Found a layer\n"); + + // sz + uint32_t sz; + get32(&sz,fp); + fix(&sz); + // version + uint32_t ver; + get32(&ver,fp); + fix(&ver); + if (ver>2) ERR_NEWER("layer spec"); + + if (ver==1){ + LayerV1 layerHeader; + if (not getData((void*)&layerHeader, sizeof layerHeader, fp)) ERR("Can't read layer header."); + fix(&layerHeader); + + // creat new layer data + LayerData* ld = new LayerData; + ld->header = layerHeader; // already fix'd + ld->data = new uint8[ld->header.dataSize]; + + // Read in the data chunk + getData((void*) ld->data, ld->header.dataSize, fp); + + // push layer onto the list + data.currentLayer = ld; + data.layers.push(ld); + } + else if (ver==2){ + LayerV2 layerHeader; + if (not getData((void*)&layerHeader, sizeof layerHeader, fp)) ERR("Can't read layer header."); + fix(&layerHeader); + + // creat new layer data + LayerData* ld = new LayerData; + ld->header = layerHeader; // already fix'd + ld->data = new uint8[ld->header.dataSize]; + + // Read in the data chunk + getData((void*) ld->data, ld->header.dataSize, fp); + + // push layer onto the list + data.currentLayer = ld; + data.layers.push(ld); + } + } + else { + // skip unknown segment + uint32_t sz; + get32(&sz,fp); + fix(&sz); + fseek(fp,sz,SEEK_CUR); + } + } + } + + // we're done! + keepGoing = false; + } + else { + // skip this segment + uint32_t sz; + get32(&sz,fp); + fseek(fp,sz,SEEK_CUR); + } + } + + // finally, copy the layers into the current document + for(int i=0;iaddNewLayer(); + + // Parse layer header + l->name = fromFourCC(ld->header.name); + l->fgalpha = ld->header.fgalpha; + l->bgalpha = ld->header.bgalpha; + l->visible = (ld->header.visible==1); + // l->compositingMode = + + // Copy data into currently selected canvas + uint8_t* imgData = ld->data; + CanvasImage *img = new CanvasImage; + // Write the brush data for every brush in the image + int index = 0; + for(int x = 0; x < app->canvasWidth; x++) { + for(int y = 0; y < app->canvasHeight; y++) { + Brush b; + b.symbol = (unsigned char)(imgData[index++]); + b.fore.r = (uint8_t)(imgData[index++]); + b.fore.g = (uint8_t)(imgData[index++]); + b.fore.b = (uint8_t)(imgData[index++]); + b.back.r = (uint8_t)(imgData[index++]); + b.back.g = (uint8_t)(imgData[index++]); + b.back.b = (uint8_t)(imgData[index++]); + b.solid = true; // deprecated + b.walkable = true; // deprecated + img->push_back(b); + } + } + + app->setCanvasImage(*img); + delete img; + } + + // then free all the temporary layer data + for(int i=0;idata; + delete data.layers.get(i); + } + + // and update the layer widget + app->gui->layerWidget->regenerateLayerList(); + } + fclose(fp); + + return true; +} +*/ + +#endif /* TCOD_CONSOLE_SUPPORT */ diff --git a/tcod_sys/libtcod/src/libtcod/console_printing.c b/tcod_sys/libtcod/src/libtcod/console_printing.c new file mode 100644 index 000000000..6be861dfe --- /dev/null +++ b/tcod_sys/libtcod/src/libtcod/console_printing.c @@ -0,0 +1,1086 @@ +/* +* libtcod +* Copyright (c) 2008-2018 Jice & Mingos & rmtew +* All rights reserved. +* +* Redistribution and use in source and binary forms, with or without +* modification, are permitted provided that the following conditions are met: +* * Redistributions of source code must retain the above copyright +* notice, this list of conditions and the following disclaimer. +* * Redistributions in binary form must reproduce the above copyright +* notice, this list of conditions and the following disclaimer in the +* documentation and/or other materials provided with the distribution. +* * The name of Jice or Mingos may not be used to endorse or promote +* products derived from this software without specific prior written +* permission. +* +* THIS SOFTWARE IS PROVIDED BY JICE, MINGOS AND RMTEW ``AS IS'' AND ANY +* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED +* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE +* DISCLAIMED. IN NO EVENT SHALL JICE, MINGOS OR RMTEW BE LIABLE FOR ANY +* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES +* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; +* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND +* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS +* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +*/ +#include "console.h" + +#include +#include +#include +#include +#include +#ifndef NO_UNICODE +#include +#include +#endif + +#include "../vendor/stb_sprintf.h" +#include "../vendor/utf8proc/utf8proc.h" +#include "libtcod_int.h" +#include "utility.h" +static TCOD_color_t color_control_fore[TCOD_COLCTRL_NUMBER] = { + {255, 255, 255}, {255, 255, 255}, {255, 255, 255}, {255, 255, 255}, + {255, 255, 255}}; +static TCOD_color_t color_control_back[TCOD_COLCTRL_NUMBER]; +/** + * Assign a foreground and background color to a color control index. + * + * \param con Index to change, e.g. `TCOD_COLCTRL_1` + * \param fore Foreground color to assign to this index. + * \param back Background color to assign to this index. + */ +void TCOD_console_set_color_control(TCOD_colctrl_t con, TCOD_color_t fore, TCOD_color_t back) { + TCOD_IFNOT(con >= TCOD_COLCTRL_1 && con <= TCOD_COLCTRL_NUMBER ) return; + color_control_fore[con-1]=fore; + color_control_back[con-1]=back; +} +char *TCOD_console_vsprint(const char *fmt, va_list ap) { + #define NB_BUFFERS 10 + #define INITIAL_SIZE 512 + /* several static buffers in case the function is used more than once in a single function call */ + static char *msg[NB_BUFFERS]={NULL}; + static int buflen[NB_BUFFERS]={0}; + static int curbuf=0; + char *ret; + bool ok=false; + if (!msg[0]) { + int i; + for (i=0; i < NB_BUFFERS; i++) { + buflen[i]=INITIAL_SIZE; + msg[i]=(char *)calloc(sizeof(char),INITIAL_SIZE); + } + } + do { + /* warning ! depending on the compiler, vsnprintf return -1 or + the expected string length if the buffer is not big enough */ + int len = stbsp_vsnprintf(msg[curbuf],buflen[curbuf],fmt,ap); + ok=true; + if (len < 0 || len >= buflen[curbuf]) { + /* buffer too small. */ + if ( len > 0 ) { + while ( buflen[curbuf] < len+1 ) buflen[curbuf]*=2; + } else { + buflen[curbuf]*=2; + } + free( msg[curbuf] ); + msg[curbuf]=(char *)calloc(sizeof(char),buflen[curbuf]); + ok=false; + } + } while (! ok); + ret=msg[curbuf]; + curbuf = (curbuf+1)%NB_BUFFERS; + return ret; +} +/** + * Print a titled, framed region on a console, using default colors and + * alignment. + * + * \param con A console pointer. + * \param x The starting X coordinate, the left-most position being 0. + * \param y The starting Y coordinate, the top-most position being 0. + * \param w The width of the frame. + * \param h The height of the frame. + * \param empty If true the characters inside of the frame will be cleared + * with spaces. + * \param flag The blending flag. + * \param fmt A format string as if passed to printf. + * \param ... Variadic arguments as if passed to printf. + * + * This function makes assumptions about the fonts character encoding. + * It will fail if the font encoding is not `cp437`. + */ +void TCOD_console_print_frame(TCOD_console_t con,int x,int y,int w,int h, bool empty, TCOD_bkgnd_flag_t flag, const char *fmt, ...) { + struct TCOD_Console *dat=con ? (struct TCOD_Console *)con : TCOD_ctx.root; + TCOD_console_put_char(con,x,y,TCOD_CHAR_NW,flag); + TCOD_console_put_char(con,x+w-1,y,TCOD_CHAR_NE,flag); + TCOD_console_put_char(con,x,y+h-1,TCOD_CHAR_SW,flag); + TCOD_console_put_char(con,x+w-1,y+h-1,TCOD_CHAR_SE,flag); + TCOD_console_hline(con,x+1,y,w-2,flag); + TCOD_console_hline(con,x+1,y+h-1,w-2,flag); + if ( h > 2 ) { + TCOD_console_vline(con,x,y+1,h-2,flag); + TCOD_console_vline(con,x+w-1,y+1,h-2,flag); + if ( empty ) { + TCOD_console_rect(con,x+1,y+1,w-2,h-2,true,flag); + } + } + if (fmt) { + va_list ap; + int xs; + TCOD_color_t tmp; + char *title; + va_start(ap,fmt); + title = TCOD_console_vsprint(fmt,ap); + va_end(ap); + title[w-3]=0; /* truncate if needed */ + xs = x + (w-(int)strlen(title)-2)/2; + tmp=dat->back; /* swap colors */ + dat->back=dat->fore; + dat->fore=tmp; + TCOD_console_print_ex(con,xs,y,TCOD_BKGND_SET,TCOD_LEFT," %s ",title); + tmp=dat->back; /* swap colors */ + dat->back=dat->fore; + dat->fore=tmp; + } +} +/** + * Print a string on a console, using default colors and alignment. + * + * \param con A console pointer. + * \param x The starting X coordinate, the left-most position being 0. + * \param y The starting Y coordinate, the top-most position being 0. + * \param fmt A format string as if passed to printf. + * \param ... Variadic arguments as if passed to printf. + */ +void TCOD_console_print(TCOD_console_t con,int x, int y, const char *fmt, ...) { + va_list ap; + struct TCOD_Console *dat=con ? (struct TCOD_Console *)con : TCOD_ctx.root; + TCOD_IFNOT ( dat != NULL ) return; + va_start(ap,fmt); + TCOD_console_print_internal(con,x,y,0,0,dat->bkgnd_flag, + dat->alignment,TCOD_console_vsprint(fmt,ap), false, false); + va_end(ap); +} +/** + * Print a string on a console, using default colors. + * + * \param con A console pointer. + * \param x The starting X coordinate, the left-most position being 0. + * \param y The starting Y coordinate, the top-most position being 0. + * \param flag The blending flag. + * \param alignment The font alignment to use. + * \param fmt A format string as if passed to printf. + * \param ... Variadic arguments as if passed to printf. + */ +void TCOD_console_print_ex(TCOD_console_t con,int x, int y, + TCOD_bkgnd_flag_t flag, TCOD_alignment_t alignment, const char *fmt, ...) { + va_list ap; + struct TCOD_Console *dat=con ? (struct TCOD_Console *)con : TCOD_ctx.root; + TCOD_IFNOT ( dat != NULL ) return; + va_start(ap,fmt); + TCOD_console_print_internal(con,x,y,0,0,flag,alignment, + TCOD_console_vsprint(fmt,ap), false, false); + va_end(ap); +} +/** + * Print a string on a console constrained to a rectangle, using default + * colors and alignment. + * + * \param con A console pointer. + * \param x The starting X coordinate, the left-most position being 0. + * \param y The starting Y coordinate, the top-most position being 0. + * \param w The width of the region. + * If 0 then the maximum width will be used. + * \param h The height of the region. + * If 0 then the maximum height will be used. + * \param fmt A format string as if passed to printf. + * \param ... Variadic arguments as if passed to printf. + * \return The number of lines actually printed. + */ +int TCOD_console_print_rect(TCOD_console_t con,int x, int y, int w, int h, const char *fmt, ...) { + int ret; + va_list ap; + struct TCOD_Console *dat=con ? (struct TCOD_Console *)con : TCOD_ctx.root; + TCOD_IFNOT ( dat != NULL ) return 0; + va_start(ap,fmt); + ret = TCOD_console_print_internal(con,x,y,w,h,dat->bkgnd_flag,dat->alignment, + TCOD_console_vsprint(fmt,ap), true, false); + va_end(ap); + return ret; +} +/** + * Print a string on a console constrained to a rectangle, using default + * colors. + * + * \param con A console pointer. + * \param x The starting X coordinate, the left-most position being 0. + * \param y The starting Y coordinate, the top-most position being 0. + * \param w The width of the region. + * If 0 then the maximum width will be used. + * \param h The height of the region. + * If 0 then the maximum height will be used. + * \param flag The blending flag. + * \param alignment The font alignment to use. + * \param fmt A format string as if passed to printf. + * \param ... Variadic arguments as if passed to printf. + * \return The number of lines actually printed. + */ +int TCOD_console_print_rect_ex(TCOD_console_t con,int x, int y, int w, int h, + TCOD_bkgnd_flag_t flag, TCOD_alignment_t alignment,const char *fmt, ...) { + int ret; + va_list ap; + va_start(ap,fmt); + ret = TCOD_console_print_internal(con,x,y,w,h,flag,alignment,TCOD_console_vsprint(fmt,ap), true, false); + va_end(ap); + return ret; +} +/** + * Return the number of lines that would be printed by the + * + * \param con A console pointer. + * \param x The starting X coordinate, the left-most position being 0. + * \param y The starting Y coordinate, the top-most position being 0. + * \param w The width of the region. + * If 0 then the maximum width will be used. + * \param h The height of the region. + * If 0 then the maximum height will be used. + * \param fmt A format string as if passed to printf. + * \param ... Variadic arguments as if passed to printf. + * \return The number of lines that would have been printed. + */ +int TCOD_console_get_height_rect(TCOD_console_t con,int x, int y, int w, int h, const char *fmt, ...) { + int ret; + va_list ap; + va_start(ap,fmt); + ret = TCOD_console_print_internal(con,x,y,w,h,TCOD_BKGND_NONE,TCOD_LEFT,TCOD_console_vsprint(fmt,ap), true, true); + va_end(ap); + return ret; +} + +/* non public methods */ +int TCOD_console_stringLength(const unsigned char *s) { + int l=0; + while (*s) { + if ( *s == (int)TCOD_COLCTRL_FORE_RGB || *s == (int)TCOD_COLCTRL_BACK_RGB ) s+=3; + else if ( (unsigned)(*s) > (unsigned)TCOD_COLCTRL_STOP ) l++; + s++; + } + return l; +} + +unsigned char * TCOD_console_forward(unsigned char *s,int l) { + while ( *s && l > 0 ) { + if ( *s == (int)TCOD_COLCTRL_FORE_RGB || *s == (int)TCOD_COLCTRL_BACK_RGB ) s+=3; + else if ( *s > (int)TCOD_COLCTRL_STOP ) l--; + s++; + } + return s; +} + +unsigned char *TCOD_console_strchr(unsigned char *s, unsigned char c) { + while ( *s && *s != c ) { + if ( *s == (int)TCOD_COLCTRL_FORE_RGB || *s == (int)TCOD_COLCTRL_BACK_RGB ) s+=3; + s++; + } + return (*s ? s : NULL); +} + +int TCOD_console_print_internal(TCOD_console_t con,int x,int y, int rw, int rh, TCOD_bkgnd_flag_t flag, + TCOD_alignment_t align, char *msg, bool can_split, bool count_only) { + unsigned char *c=(unsigned char *)msg; + int cx=0,cy=y; + int minx,maxx,miny,maxy; + TCOD_color_t oldFore; + TCOD_color_t oldBack; + struct TCOD_Console *dat=con ? (struct TCOD_Console *)con : TCOD_ctx.root; + TCOD_IFNOT ( dat != NULL + && (unsigned)(x) < (unsigned)dat->w && (unsigned)(y) < (unsigned)dat->h ) + return 0; + TCOD_IFNOT(msg != NULL) return 0; + if ( rh == 0 ) rh = dat->h-y; + if ( rw == 0 ) switch(align) { + case TCOD_LEFT : rw = dat->w-x; break; + case TCOD_RIGHT : rw=x+1; break; + case TCOD_CENTER : default : rw=dat->w; break; + } + oldFore=dat->fore; + oldBack=dat->back; + miny=y; + maxy=dat->h-1; + if (rh > 0) maxy=MIN(maxy,y+rh-1); + switch (align) { + case TCOD_LEFT : minx=MAX(0,x); maxx=MIN(dat->w-1,x+rw-1); break; + case TCOD_RIGHT : minx=MAX(0,x-rw+1); maxx=MIN(dat->w-1,x); break; + case TCOD_CENTER : default : minx=MAX(0,x-rw/2); maxx=MIN(dat->w-1,x+rw/2); break; + } + + do { + /* get \n delimited sub-message */ + unsigned char *end=TCOD_console_strchr(c,'\n'); + char bak=0; + int cl; + unsigned char *split=NULL; + if ( end ) *end=0; + cl= TCOD_console_stringLength(c); + /* find starting x */ + switch (align) { + case TCOD_LEFT : cx=x; break; + case TCOD_RIGHT : cx=x-cl+1; break; + case TCOD_CENTER : cx= x-cl/2;break; + } + /* check if the string is completely out of the minx,miny,maxx,maxy frame */ + if ( cy >= miny && cy <= maxy && cx <= maxx && cx+cl -1 >= minx ) { + if ( can_split && cy <= maxy ) { + /* if partially out of screen, try to split the sub-message */ + if ( cx < minx ) split = TCOD_console_forward(c, align == TCOD_CENTER ? cl-2*(minx-cx) : cl-(minx-cx)); + else if ( align == TCOD_CENTER ) { + if ( cx + cl/2 > maxx+1 ) split = TCOD_console_forward(c, maxx+1 - cx); + } else { + if ( cx + cl > maxx+1 ) split = TCOD_console_forward(c, maxx+1 - cx); + } + } + if ( split ) { + unsigned char *oldsplit=split; + while ( ! isspace(*split) && split > c ) split --; + if (end) *end='\n'; + if (!isspace(*split) ) { + split=oldsplit; + } + end=split; + bak=*split; + *split=0; + cl=TCOD_console_stringLength(c); + switch (align) { + case TCOD_LEFT : cx=x; break; + case TCOD_RIGHT : cx=x-cl+1; break; + case TCOD_CENTER : cx= x-cl/2;break; + } + } + if ( cx < minx ) { + /* truncate left part */ + c += minx-cx; + cl -= minx-cx; + cx=minx; + } + if ( cx + cl > maxx+1 ) { + /* truncate right part */ + split = TCOD_console_forward(c, maxx+1 - cx); + *split=0; + } + /* render the sub-message */ + if ( cy >= 0 && cy < dat->h ) + while (*c) { + if ( *c >= TCOD_COLCTRL_1 && *c <= TCOD_COLCTRL_NUMBER ) { + dat->fore=color_control_fore[(int)(*c)-1]; + dat->back=color_control_back[(int)(*c)-1]; + } else if ( *c == TCOD_COLCTRL_FORE_RGB ) { + c++; + dat->fore.r=*c++; + dat->fore.g=*c++; + dat->fore.b=*c; + } else if ( *c == TCOD_COLCTRL_BACK_RGB ) { + c++; + dat->back.r=*c++; + dat->back.g=*c++; + dat->back.b=*c; + } else if ( *c == TCOD_COLCTRL_STOP ) { + dat->fore=oldFore; + dat->back=oldBack; + } else { + if (! count_only) TCOD_console_put_char(con,cx,cy,(int)(*c),flag); + cx++; + } + c++; + } + } + if ( end ) { + /* next line */ + if ( split && ! isspace(bak) ) { + *end=bak; + c=end; + } else { + c=end+1; + } + cy++; + } else c=NULL; + } while ( c && cy < dat->h && (rh == 0 || cy < y+rh) ); + return cy-y+1; +} + +#ifndef NO_UNICODE + +wchar_t *TCOD_console_strchr_utf(wchar_t *s, char c) { + while ( *s && *s != c ) { + if ( *s == (int)TCOD_COLCTRL_FORE_RGB || *s == (int)TCOD_COLCTRL_BACK_RGB ) s+=3; + s++; + } + return (*s ? s : NULL); +} + +void TCOD_console_map_string_to_font_utf(const wchar_t *s, int fontCharX, int fontCharY) { + TCOD_IFNOT(s != NULL) return; + while (*s) { + TCOD_sys_map_ascii_to_font(*s, fontCharX, fontCharY); + fontCharX++; + if ( fontCharX == TCOD_ctx.fontNbCharHoriz ) { + fontCharX=0; + fontCharY++; + } + s++; + } +} + +wchar_t *TCOD_console_vsprint_utf(const wchar_t *fmt, va_list ap) { + #define NB_BUFFERS 10 + #define INITIAL_SIZE 512 + /* several static buffers in case the function is used more than once in a single function call */ + static wchar_t *msg[NB_BUFFERS]={NULL}; + static int buflen[NB_BUFFERS]={0}; + static int curbuf=0; + wchar_t *ret; + bool ok=false; + if (!msg[0]) { + int i; + for (i=0; i < NB_BUFFERS; i++) { + buflen[i]=INITIAL_SIZE; + msg[i]=(wchar_t *)calloc(sizeof(wchar_t),INITIAL_SIZE); + } + } + do { + /* warning ! depending on the compiler, vsnprintf return -1 or + the expected string length if the buffer is not big enough */ + int len = vswprintf(msg[curbuf],buflen[curbuf],fmt,ap); + ok=true; + if (len < 0 || len >= buflen[curbuf]) { + /* buffer too small. */ + if ( len > 0 ) { + while ( buflen[curbuf] < len+1 ) buflen[curbuf]*=2; + } else { + buflen[curbuf]*=2; + } + free( msg[curbuf] ); + msg[curbuf]=(wchar_t *)calloc(sizeof(wchar_t),buflen[curbuf]); + ok=false; + } + } while (! ok); + ret=msg[curbuf]; + curbuf = (curbuf+1)%NB_BUFFERS; + return ret; +} + + +int TCOD_console_stringLength_utf(const wchar_t *s) { + int l=0; + while (*s) { + if ( *s == (int)TCOD_COLCTRL_FORE_RGB || *s == (int)TCOD_COLCTRL_BACK_RGB ) s+=3; + else if ( *s > (int)TCOD_COLCTRL_STOP ) l++; + s++; + } + return l; +} + +wchar_t * TCOD_console_forward_utf(wchar_t *s,int l) { + while ( *s && l > 0 ) { + if ( *s == (int)TCOD_COLCTRL_FORE_RGB || *s == (int)TCOD_COLCTRL_BACK_RGB ) s+=3; + else if ( *s > (int)TCOD_COLCTRL_STOP ) l--; + s++; + } + return s; +} + +int TCOD_console_print_internal_utf(TCOD_console_t con,int x,int y, int rw, int rh, TCOD_bkgnd_flag_t flag, + TCOD_alignment_t align, wchar_t *msg, bool can_split, bool count_only) { + wchar_t *c=msg; + int cx=0,cy=y; + int minx,maxx,miny,maxy; + TCOD_color_t oldFore; + TCOD_color_t oldBack; + struct TCOD_Console *dat=con ? (struct TCOD_Console *)con : TCOD_ctx.root; + TCOD_IFNOT ( dat != NULL + && (unsigned)(x) < (unsigned)dat->w && (unsigned)(y) < (unsigned)dat->h ) + return 0; + TCOD_IFNOT(msg != NULL) return 0; + if ( rh == 0 ) rh = dat->h-y; + if ( rw == 0 ) switch(align) { + case TCOD_LEFT : rw = dat->w-x; break; + case TCOD_RIGHT : rw=x+1; break; + case TCOD_CENTER : default : rw=dat->w; break; + } + oldFore=dat->fore; + oldBack=dat->back; + miny=y; + maxy=dat->h-1; + if (rh > 0) maxy=MIN(maxy,y+rh-1); + switch (align) { + case TCOD_LEFT : minx=MAX(0,x); maxx=MIN(dat->w-1,x+rw-1); break; + case TCOD_RIGHT : minx=MAX(0,x-rw+1); maxx=MIN(dat->w-1,x); break; + case TCOD_CENTER : default : minx=MAX(0,x-rw/2); maxx=MIN(dat->w-1,x+rw/2); break; + } + + do { + /* get \n delimited sub-message */ + wchar_t *end=TCOD_console_strchr_utf(c,'\n'); + wchar_t bak=0; + int cl; + wchar_t *split=NULL; + if ( end ) *end=0; + cl= TCOD_console_stringLength_utf(c); + /* find starting x */ + switch (align) { + case TCOD_LEFT : cx=x; break; + case TCOD_RIGHT : cx=x-cl+1; break; + case TCOD_CENTER : cx= x-cl/2;break; + } + /* check if the string is completely out of the minx,miny,maxx,maxy frame */ + if ( cy >= miny && cy <= maxy && cx <= maxx && cx+cl -1 >= minx ) { + if ( can_split && cy < maxy ) { + /* if partially out of screen, try to split the sub-message */ + if ( cx < minx ) split = TCOD_console_forward_utf(c, align == TCOD_CENTER ? cl-2*(minx-cx) : cl-(minx-cx)); + else if ( align==TCOD_CENTER ) { + if ( cx + cl/2 > maxx+1 ) split = TCOD_console_forward_utf(c, maxx+1 - cx); + } else { + if ( cx + cl > maxx+1 ) split = TCOD_console_forward_utf(c, maxx+1 - cx); + } + } + if ( split ) { + wchar_t *oldsplit=split; + while ( ! iswspace(*split) && split > c ) split --; + if (end) *end='\n'; + if (!iswspace(*split) ) { + split=oldsplit; + } + end=split; + bak=*split; + *split=0; + cl=TCOD_console_stringLength_utf(c); + switch (align) { + case TCOD_LEFT : cx=x; break; + case TCOD_RIGHT : cx=x-cl+1; break; + case TCOD_CENTER : cx= x-cl/2;break; + } + } + if ( cx < minx ) { + /* truncate left part */ + c += minx-cx; + cl -= minx-cx; + cx=minx; + } + if ( cx + cl > maxx+1 ) { + /* truncate right part */ + split = TCOD_console_forward_utf(c, maxx+1 - cx); + *split=0; + } + /* render the sub-message */ + if ( cy >= 0 && cy < dat->h ) + while (*c) { + if ( *c >= TCOD_COLCTRL_1 && *c <= TCOD_COLCTRL_NUMBER ) { + dat->fore=color_control_fore[(int)(*c)-1]; + dat->back=color_control_back[(int)(*c)-1]; + } else if ( *c == TCOD_COLCTRL_FORE_RGB ) { + c++; + dat->fore.r=(uint8_t)(*c++); + dat->fore.g=(uint8_t)(*c++); + dat->fore.b=(uint8_t)(*c); + } else if ( *c == TCOD_COLCTRL_BACK_RGB ) { + c++; + dat->back.r=(uint8_t)(*c++); + dat->back.g=(uint8_t)(*c++); + dat->back.b=(uint8_t)(*c); + } else if ( *c == TCOD_COLCTRL_STOP ) { + dat->fore=oldFore; + dat->back=oldBack; + } else { + if (! count_only) TCOD_console_put_char(con,cx,cy,(int)(*c),flag); + cx++; + } + c++; + } + } + if ( end ) { + /* next line */ + if ( split && ! iswspace(bak) ) { + *end=bak; + c=end; + } else { + c=end+1; + } + cy++; + } else c=NULL; + } while ( c && cy < dat->h && (rh == 0 || cy < y+rh) ); + return cy-y+1; +} +/** + * /rst + * .. deprecated:: 1.8 + * Use :any:`TCOD_console_printf` instead. + * /endrst + */ +void TCOD_console_print_utf(TCOD_console_t con,int x, int y, const wchar_t *fmt, ...) { + va_list ap; + struct TCOD_Console *dat=con ? (struct TCOD_Console *)con : TCOD_ctx.root; + TCOD_IFNOT ( dat != NULL ) return; + va_start(ap,fmt); + TCOD_console_print_internal_utf(con,x,y,0,0,dat->bkgnd_flag,dat->alignment, + TCOD_console_vsprint_utf(fmt,ap), false, false); + va_end(ap); +} +/** + * /rst + * .. deprecated:: 1.8 + * Use :any:`TCOD_console_printf_ex` instead. + * /endrst + */ +void TCOD_console_print_ex_utf(TCOD_console_t con,int x, int y, + TCOD_bkgnd_flag_t flag, TCOD_alignment_t alignment, const wchar_t *fmt, ...) { + va_list ap; + struct TCOD_Console *dat=con ? (struct TCOD_Console *)con : TCOD_ctx.root; + TCOD_IFNOT ( dat != NULL ) return; + va_start(ap,fmt); + TCOD_console_print_internal_utf(con,x,y,0,0,flag,alignment,TCOD_console_vsprint_utf(fmt,ap), false, false); + va_end(ap); +} + +int TCOD_console_print_rect_utf(TCOD_console_t con,int x, int y, int w, int h, + const wchar_t *fmt, ...) { + int ret; + va_list ap; + struct TCOD_Console *dat=con ? (struct TCOD_Console *)con : TCOD_ctx.root; + TCOD_IFNOT ( dat != NULL ) return 0; + va_start(ap,fmt); + ret = TCOD_console_print_internal_utf(con,x,y,w,h,dat->bkgnd_flag,dat->alignment, + TCOD_console_vsprint_utf(fmt,ap), true, false); + va_end(ap); + return ret; +} +/** + * /rst + * .. deprecated:: 1.8 + * Use :any:`TCOD_console_printf_rect_ex` instead. + * /endrst + */ +int TCOD_console_print_rect_ex_utf(TCOD_console_t con,int x, int y, int w, int h, + TCOD_bkgnd_flag_t flag, TCOD_alignment_t alignment, const wchar_t *fmt, ...) { + int ret; + va_list ap; + va_start(ap,fmt); + ret=TCOD_console_print_internal_utf(con,x,y,w,h,flag,alignment,TCOD_console_vsprint_utf(fmt,ap), true, false); + va_end(ap); + return ret; +} +/** + * /rst + * .. deprecated:: 1.8 + * /endrst + */ +int TCOD_console_get_height_rect_utf(TCOD_console_t con,int x, int y, int w, int h, const wchar_t *fmt, ...) { + int ret; + va_list ap; + va_start(ap,fmt); + ret = TCOD_console_print_internal_utf(con,x,y,w,h,TCOD_BKGND_NONE,TCOD_LEFT,TCOD_console_vsprint_utf(fmt,ap), true, true); + va_end(ap); + return ret; +} + +#endif /* NO_UNICODE */ +/** + * Outputs the bounding box used for printing. + * + * If `max_width` or `max_height` are zero, they will be set automatically. + */ +static int TCOD_get_print_bounds( + const struct TCOD_Console *con, TCOD_alignment_t align, int x, int y, + int *max_width, int *max_height, + int *left, int *right, int *top, int *bottom) { + if (!con) { return -1; } + /* Set default width/height if either is zero. */ + if (*max_height == 0) { *max_height = con->h - y; } + if (*max_width == 0 ) { + switch(align) { + default: case TCOD_LEFT: + *max_width = con->w - x; + break; + case TCOD_RIGHT: + *max_width = x + 1; + break; + case TCOD_CENTER: + *max_width = con->w; + break; + } + } + /* Return printing boundary. */ + *top = y; + *bottom = MIN(con->h - 1, y + *max_height - 1); + switch (align) { + case TCOD_LEFT: + *left = x; + *right = x + *max_width - 1; + break; + case TCOD_RIGHT: + *left = x - *max_width + 1; + *right = x; + break; + case TCOD_CENTER: default: + *left = x - *max_width / 2; + *right = x + *max_width / 2; + break; + } + *left = MAX(0, *left); + *right = MIN(*right, con->w - 1); + return 0; +} +/** + * Parse ALL color codes on a utf8 string, returns the total length of the + * string parsed. + * + * Any `TCOD_color_t` parameters can be NULL. + */ +static utf8proc_ssize_t TCOD_utf8_parse_color( + const unsigned char *str, TCOD_color_t *fg_color, TCOD_color_t *bg_color, + const TCOD_color_t *old_fg_color, const TCOD_color_t *old_bg_color) { + const unsigned char *start = str; + utf8proc_int32_t codepoint; + utf8proc_ssize_t code_size; + code_size = utf8proc_iterate(str, -1, &codepoint); + str += code_size; + if (TCOD_COLCTRL_1 <= codepoint && codepoint <= TCOD_COLCTRL_NUMBER) { + /* Read colors from the color control array. */ + int color_index = codepoint - TCOD_COLCTRL_1; + if (fg_color) { *fg_color = color_control_fore[color_index]; } + if (bg_color) { *bg_color = color_control_back[color_index]; } + return code_size + TCOD_utf8_parse_color(str, fg_color, bg_color, + old_fg_color, old_bg_color); + } else if (codepoint == TCOD_COLCTRL_STOP) { + /* Return colors to their original color. */ + if (fg_color && old_fg_color) { *fg_color = *old_fg_color; } + if (bg_color && old_bg_color) { *bg_color = *old_bg_color; } + return code_size + TCOD_utf8_parse_color(str, fg_color, bg_color, + old_fg_color, old_bg_color); + } else if (codepoint == TCOD_COLCTRL_FORE_RGB + || codepoint == TCOD_COLCTRL_BACK_RGB) { + /* Read the next 3 code-points as 8-bit RGB color values. */ + unsigned char *color_array = NULL; + int i; + if (codepoint == TCOD_COLCTRL_FORE_RGB && fg_color) { + color_array = (unsigned char *)fg_color; + } else if (codepoint == TCOD_COLCTRL_BACK_RGB && bg_color) { + color_array = (unsigned char *)bg_color; + } + for (i = 0; i < 3; ++i) { + code_size = utf8proc_iterate(str, -1, &codepoint); + if (code_size < 0) { break; } + if (color_array) { color_array[i] = (unsigned char)codepoint; } + str += code_size; + } + code_size = str - start; + return code_size + TCOD_utf8_parse_color(str, fg_color, bg_color, + old_fg_color, old_bg_color); + } else { + return 0; /* `str` is not on any color codes. */ + } +} +/** + * Check for and return the length of ALL control codes at `str`. + */ +static utf8proc_ssize_t TCOD_utf8_skip_control_codes( + const unsigned char *str) { + return TCOD_utf8_parse_color(str, NULL, NULL, NULL, NULL); +} + +/* + * Check if the specified character is any line-break character + */ +static bool TCOD_utf8_is_newline_character(const utf8proc_property_t *property) +{ + switch (property->category) { + case UTF8PROC_CATEGORY_ZL: /* Separator, line */ + case UTF8PROC_CATEGORY_ZP: /* Separator, paragraph */ + return true; + + case UTF8PROC_CATEGORY_CC: /* Other, control */ + switch(property->boundclass) + { + case UTF8PROC_BOUNDCLASS_CR: // carriage return - \r + case UTF8PROC_BOUNDCLASS_LF: // line feed - \n + return true; + + default: + break; + } + break; + + default: + break; + } + return false; +} + +/** + * Get the next line-break or null terminator, or break the string before + * `max_width`. + * + * Return 0 if a line-break or null terminator was found, or 1 if the line was + * automatically split. + */ +int TCOD_utf8_next_split( + const unsigned char *str, int max_width, int can_split, + const unsigned char **endpoint, utf8proc_ssize_t *total_width) { + const unsigned char *break_point = NULL; + *total_width = 0; + *endpoint = str; + while (*str != '\0') { + utf8proc_int32_t codepoint; + utf8proc_ssize_t code_size; + const utf8proc_property_t *property; + + str += TCOD_utf8_skip_control_codes(str); + code_size = utf8proc_iterate(str, -1, &codepoint); + property = utf8proc_get_property(codepoint); + if (code_size <= 0) { break; } + if (can_split && *total_width > 0 + && *total_width + (int)property->charwidth > max_width) { + *endpoint = str; + if (break_point) { *endpoint = break_point; } + return 1; + } + switch (property->category) { + case UTF8PROC_CATEGORY_PD: /* Punctuation, dash */ + case UTF8PROC_CATEGORY_ZS: /* Separator, space */ + break_point = str; + break; + default: + break; + } + + if(TCOD_utf8_is_newline_character(property)) { + *endpoint = str; + return 0; + } + + str += code_size; + *total_width += 1; + } + *endpoint = str; + return 0; +} +/** + * Internal UTF-8 printer. + */ +int TCOD_console_print_internal_utf8_( + TCOD_console_t con, int x, int y, int max_width, int max_height, + TCOD_bkgnd_flag_t flag, TCOD_alignment_t align, + const unsigned char *string, int can_split, int count_only) { + int left, right, top, bottom; /* Print bounding box. */ + TCOD_color_t old_fg, old_bg; + int cursor_x = 0; + con = con ? con : TCOD_ctx.root; + if (!con || !string) { return 0; } + old_fg = con->fore; + old_bg = con->back; + TCOD_get_print_bounds(con, align, x, y, &max_width, &max_height, + &left, &right, &top, &bottom); + while (*string != '\0' && top <= bottom) { + const unsigned char *line_break; + utf8proc_ssize_t line_width; + utf8proc_int32_t codepoint; + utf8proc_ssize_t code_size; + const utf8proc_property_t *property; + int split_status; + code_size = utf8proc_iterate(string, -1, &codepoint); + if (code_size < 0) { return -1; } + property = utf8proc_get_property(codepoint); + /* Check for newlines. */ + if(TCOD_utf8_is_newline_character(property)) + { + string += code_size; + if(property->category == UTF8PROC_CATEGORY_ZP) + { + top += 2; + } + else { + top += 1; + } + continue; + } + + /* Get the next line of characters. */ + split_status = TCOD_utf8_next_split(string, max_width, can_split, + &line_break, &line_width); + switch (align) { + default: + case TCOD_LEFT: + cursor_x = x; + break; + case TCOD_RIGHT: + cursor_x = x - line_width; + break; + case TCOD_CENTER: + cursor_x = x - line_width / 2; + break; + } + while (string < line_break) { + /* Actually render this line of characters. */ + string += TCOD_utf8_parse_color(string, &con->fore, &con->back, + &old_fg, &old_bg); + string += code_size = utf8proc_iterate(string, -1, &codepoint); + if (code_size < 0) { return -1; } + if (!count_only && left <= cursor_x && cursor_x <= right) { + TCOD_console_put_char(con, cursor_x, top, codepoint, flag); + } + cursor_x += 1; + } + /* Ignore any extra spaces. */ + while (string != '\0') { + code_size = utf8proc_iterate(string, -1, &codepoint); + if (code_size < 0) { return -1; } + property = utf8proc_get_property(codepoint); + if (property->category == UTF8PROC_CATEGORY_ZS) { /* Separator, space */ + string += code_size; + } else { + break; + } + } + /* If there was an automatic split earlier then the top is moved down. */ + if (split_status == 1) { + top += 1; + } + } + return MIN(top, bottom) - y + 1; +} +/** + * Format and print a UTF-8 string to a console. + * /rst + * .. versionadded:: 1.8 + * /endrst + */ +void TCOD_console_printf_ex(struct TCOD_Console *con, int x, int y, + TCOD_bkgnd_flag_t flag, TCOD_alignment_t alignment, + const char *fmt, ...) { + va_list ap; + va_start(ap, fmt); + TCOD_console_print_internal_utf8_( + con, x, y, 0, 0, flag, alignment, + (const unsigned char *)TCOD_console_vsprint(fmt, ap), false, false); + va_end(ap); +} +/** + * Format and print a UTF-8 string to a console. + * /rst + * .. versionadded:: 1.8 + * /endrst + */ +void TCOD_console_printf(struct TCOD_Console *con, int x, int y, + const char *fmt, ...) { + va_list ap; + con = con ? con : TCOD_ctx.root; + if (!con) { return; } + va_start(ap, fmt); + TCOD_console_print_internal_utf8_( + con, x, y, 0, 0, con->bkgnd_flag, con->alignment, + (const unsigned char *)TCOD_console_vsprint(fmt, ap), false, false); + va_end(ap); +} +/** + * Format and print a UTF-8 string to a console. + * /rst + * .. versionadded:: 1.8 + * /endrst + */ +int TCOD_console_printf_rect_ex(struct TCOD_Console *con, + int x, int y, int w, int h, + TCOD_bkgnd_flag_t flag, TCOD_alignment_t alignment,const char *fmt, ...) { + int ret; + va_list ap; + va_start(ap, fmt); + ret = TCOD_console_print_internal_utf8_( + con, x, y, w, h, flag, alignment, + (const unsigned char *)TCOD_console_vsprint(fmt, ap), true, false); + va_end(ap); + return ret; +} +/** + * Format and print a UTF-8 string to a console. + * /rst + * .. versionadded:: 1.8 + * /endrst + */ +int TCOD_console_printf_rect(struct TCOD_Console *con, + int x, int y, int w, int h, const char *fmt, ...) { + int ret; + va_list ap; + con = con ? con : TCOD_ctx.root; + if (!con) { return 0; } + va_start(ap, fmt); + ret = TCOD_console_print_internal_utf8_( + con, x, y, w, h, con->bkgnd_flag,con->alignment, + (const unsigned char *)TCOD_console_vsprint(fmt, ap), true, false); + va_end(ap); + return ret; +} +/** + * Return the number of lines that would be printed by this formatted string. + */ +int TCOD_console_get_height_rect_fmt(struct TCOD_Console *con, + int x, int y, int w, int h, + const char *fmt, ...) { + int ret; + va_list ap; + va_start(ap, fmt); + ret = TCOD_console_print_internal_utf8_( + con, x, y, w, h, TCOD_BKGND_NONE, TCOD_LEFT, + (const unsigned char *)TCOD_console_vsprint(fmt, ap), true, true); + va_end(ap); + return ret; +} +/** + * Print a framed and optionally titled region to a console, using default + * colors and alignment. + * + * This function uses Unicode box-drawing characters and a UTF-8 formatted + * string. + */ +void TCOD_console_printf_frame(struct TCOD_Console *con, + int x, int y, int w, int h, int empty, + TCOD_bkgnd_flag_t flag, const char *fmt, ...) { + const int left = x; + const int right = x + w - 1; + const int top = y; + const int bottom = y + h - 1; + int i; + con = con ? con : TCOD_ctx.root; + TCOD_console_put_char(con, left, top, 0x250C, flag); /* ┌ */ + TCOD_console_put_char(con, right, top, 0x2510, flag); /* ┠*/ + TCOD_console_put_char(con, left, bottom, 0x2514, flag); /* └ */ + TCOD_console_put_char(con, right, bottom, 0x2518, flag); /* ┘ */ + for (i = left + 1; i < right - 1; ++i) { + TCOD_console_put_char(con, i, top, 0x2500, flag); /* ─ */ + TCOD_console_put_char(con, i, bottom, 0x2500,flag); + } + for (i = top + 1; i < bottom - 1; ++i) { + TCOD_console_put_char(con, left, i, 0x2502, flag); /* │ */ + TCOD_console_put_char(con, right, i, 0x2502, flag); + } + if (empty) { + TCOD_console_rect(con, left + 1, top + 1, right - 1, bottom - 1, true, + flag); + } + if (fmt && con) { + va_list ap; + TCOD_color_t tmp; + /* swap colors */ + tmp = con->back; + con->back = con->fore; + con->fore = tmp; + /* print the title */ + va_start(ap,fmt); + TCOD_console_printf_rect_ex(con, x + w / 2, y, w, 1, + TCOD_BKGND_SET, TCOD_CENTER, " %s ", TCOD_console_vsprint(fmt, ap)); + va_end(ap); + /* swap colors */ + tmp = con->back; + con->back = con->fore; + con->fore = tmp; + } +} diff --git a/tcod_sys/libtcod/src/console_rexpaint.c b/tcod_sys/libtcod/src/libtcod/console_rexpaint.c similarity index 98% rename from tcod_sys/libtcod/src/console_rexpaint.c rename to tcod_sys/libtcod/src/libtcod/console_rexpaint.c index 862b00985..497979a93 100644 --- a/tcod_sys/libtcod/src/console_rexpaint.c +++ b/tcod_sys/libtcod/src/libtcod/console_rexpaint.c @@ -25,7 +25,7 @@ * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ -#include +#include "console_rexpaint.h" #ifdef TCOD_CONSOLE_SUPPORT @@ -33,11 +33,10 @@ #include -#include -#include -#include /* Needed only for TCOD_fatal */ -#include -#include +#include "console.h" +#include "libtcod_int.h" /* Needed only for TCOD_fatal */ +#include "console_types.h" +#include "color.h" /* Convert a little-endian number to native memory order. */ static uint32_t decode_little_endian(uint32_t data) { @@ -322,7 +321,7 @@ bool TCOD_console_save_xp( * This function can save any number of layers with multiple * different sizes. * - * The REXPaint tool only supports files with up to 4 layers where + * The REXPaint tool only supports files with up to 9 layers where * all layers are the same size. */ bool TCOD_console_list_save_xp( diff --git a/tcod_sys/libtcod/include/console_rexpaint.h b/tcod_sys/libtcod/src/libtcod/console_rexpaint.h similarity index 98% rename from tcod_sys/libtcod/include/console_rexpaint.h rename to tcod_sys/libtcod/src/libtcod/console_rexpaint.h index 043d821f8..3b957f84e 100644 --- a/tcod_sys/libtcod/include/console_rexpaint.h +++ b/tcod_sys/libtcod/src/libtcod/console_rexpaint.h @@ -28,7 +28,7 @@ #ifndef TCOD_CONSOLE_REXPAINT_H_ #define TCOD_CONSOLE_REXPAINT_H_ -#include "libtcod_portability.h" +#include "portability.h" #include "console.h" #ifdef __cplusplus diff --git a/tcod_sys/libtcod/include/console_types.h b/tcod_sys/libtcod/src/libtcod/console_types.h similarity index 88% rename from tcod_sys/libtcod/include/console_types.h rename to tcod_sys/libtcod/src/libtcod/console_types.h index 054190fdf..4aa75ae83 100644 --- a/tcod_sys/libtcod/include/console_types.h +++ b/tcod_sys/libtcod/src/libtcod/console_types.h @@ -1,305 +1,332 @@ -/* -* libtcod -* Copyright (c) 2008-2018 Jice & Mingos & rmtew -* All rights reserved. -* -* Redistribution and use in source and binary forms, with or without -* modification, are permitted provided that the following conditions are met: -* * Redistributions of source code must retain the above copyright -* notice, this list of conditions and the following disclaimer. -* * Redistributions in binary form must reproduce the above copyright -* notice, this list of conditions and the following disclaimer in the -* documentation and/or other materials provided with the distribution. -* * The name of Jice or Mingos may not be used to endorse or promote -* products derived from this software without specific prior written -* permission. -* -* THIS SOFTWARE IS PROVIDED BY JICE, MINGOS AND RMTEW ``AS IS'' AND ANY -* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED -* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE -* DISCLAIMED. IN NO EVENT SHALL JICE, MINGOS OR RMTEW BE LIABLE FOR ANY -* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES -* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; -* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND -* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS -* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. -*/ -#ifndef _TCOD_CONSOLE_TYPES_H -#define _TCOD_CONSOLE_TYPES_H - -#include "libtcod_portability.h" - -typedef void * TCOD_console_t; - -typedef enum { - TCODK_NONE, - TCODK_ESCAPE, - TCODK_BACKSPACE, - TCODK_TAB, - TCODK_ENTER, - TCODK_SHIFT, - TCODK_CONTROL, - TCODK_ALT, - TCODK_PAUSE, - TCODK_CAPSLOCK, - TCODK_PAGEUP, - TCODK_PAGEDOWN, - TCODK_END, - TCODK_HOME, - TCODK_UP, - TCODK_LEFT, - TCODK_RIGHT, - TCODK_DOWN, - TCODK_PRINTSCREEN, - TCODK_INSERT, - TCODK_DELETE, - TCODK_LWIN, - TCODK_RWIN, - TCODK_APPS, - TCODK_0, - TCODK_1, - TCODK_2, - TCODK_3, - TCODK_4, - TCODK_5, - TCODK_6, - TCODK_7, - TCODK_8, - TCODK_9, - TCODK_KP0, - TCODK_KP1, - TCODK_KP2, - TCODK_KP3, - TCODK_KP4, - TCODK_KP5, - TCODK_KP6, - TCODK_KP7, - TCODK_KP8, - TCODK_KP9, - TCODK_KPADD, - TCODK_KPSUB, - TCODK_KPDIV, - TCODK_KPMUL, - TCODK_KPDEC, - TCODK_KPENTER, - TCODK_F1, - TCODK_F2, - TCODK_F3, - TCODK_F4, - TCODK_F5, - TCODK_F6, - TCODK_F7, - TCODK_F8, - TCODK_F9, - TCODK_F10, - TCODK_F11, - TCODK_F12, - TCODK_NUMLOCK, - TCODK_SCROLLLOCK, - TCODK_SPACE, - TCODK_CHAR, - TCODK_TEXT -} TCOD_keycode_t; - -#define TCOD_KEY_TEXT_SIZE 32 - -/* key data : special code or character or text */ -typedef struct { - TCOD_keycode_t vk; /* key code */ - char c; /* character if vk == TCODK_CHAR else 0 */ - char text[TCOD_KEY_TEXT_SIZE]; /* text if vk == TCODK_TEXT else text[0] == '\0' */ - bool pressed ; /* does this correspond to a key press or key release event ? */ - bool lalt ; - bool lctrl ; - bool lmeta ; - bool ralt ; - bool rctrl ; - bool rmeta ; - bool shift ; -} TCOD_key_t; - -typedef enum { - /* single walls */ - TCOD_CHAR_HLINE=196, - TCOD_CHAR_VLINE=179, - TCOD_CHAR_NE=191, - TCOD_CHAR_NW=218, - TCOD_CHAR_SE=217, - TCOD_CHAR_SW=192, - TCOD_CHAR_TEEW=180, - TCOD_CHAR_TEEE=195, - TCOD_CHAR_TEEN=193, - TCOD_CHAR_TEES=194, - TCOD_CHAR_CROSS=197, - /* double walls */ - TCOD_CHAR_DHLINE=205, - TCOD_CHAR_DVLINE=186, - TCOD_CHAR_DNE=187, - TCOD_CHAR_DNW=201, - TCOD_CHAR_DSE=188, - TCOD_CHAR_DSW=200, - TCOD_CHAR_DTEEW=185, - TCOD_CHAR_DTEEE=204, - TCOD_CHAR_DTEEN=202, - TCOD_CHAR_DTEES=203, - TCOD_CHAR_DCROSS=206, - /* blocks */ - TCOD_CHAR_BLOCK1=176, - TCOD_CHAR_BLOCK2=177, - TCOD_CHAR_BLOCK3=178, - /* arrows */ - TCOD_CHAR_ARROW_N=24, - TCOD_CHAR_ARROW_S=25, - TCOD_CHAR_ARROW_E=26, - TCOD_CHAR_ARROW_W=27, - /* arrows without tail */ - TCOD_CHAR_ARROW2_N=30, - TCOD_CHAR_ARROW2_S=31, - TCOD_CHAR_ARROW2_E=16, - TCOD_CHAR_ARROW2_W=17, - /* double arrows */ - TCOD_CHAR_DARROW_H=29, - TCOD_CHAR_DARROW_V=18, - /* GUI stuff */ - TCOD_CHAR_CHECKBOX_UNSET=224, - TCOD_CHAR_CHECKBOX_SET=225, - TCOD_CHAR_RADIO_UNSET=9, - TCOD_CHAR_RADIO_SET=10, - /* sub-pixel resolution kit */ - TCOD_CHAR_SUBP_NW=226, - TCOD_CHAR_SUBP_NE=227, - TCOD_CHAR_SUBP_N=228, - TCOD_CHAR_SUBP_SE=229, - TCOD_CHAR_SUBP_DIAG=230, - TCOD_CHAR_SUBP_E=231, - TCOD_CHAR_SUBP_SW=232, - /* miscellaneous */ - TCOD_CHAR_SMILIE = 1, - TCOD_CHAR_SMILIE_INV = 2, - TCOD_CHAR_HEART = 3, - TCOD_CHAR_DIAMOND = 4, - TCOD_CHAR_CLUB = 5, - TCOD_CHAR_SPADE = 6, - TCOD_CHAR_BULLET = 7, - TCOD_CHAR_BULLET_INV = 8, - TCOD_CHAR_MALE = 11, - TCOD_CHAR_FEMALE = 12, - TCOD_CHAR_NOTE = 13, - TCOD_CHAR_NOTE_DOUBLE = 14, - TCOD_CHAR_LIGHT = 15, - TCOD_CHAR_EXCLAM_DOUBLE = 19, - TCOD_CHAR_PILCROW = 20, - TCOD_CHAR_SECTION = 21, - TCOD_CHAR_POUND = 156, - TCOD_CHAR_MULTIPLICATION = 158, - TCOD_CHAR_FUNCTION = 159, - TCOD_CHAR_RESERVED = 169, - TCOD_CHAR_HALF = 171, - TCOD_CHAR_ONE_QUARTER = 172, - TCOD_CHAR_COPYRIGHT = 184, - TCOD_CHAR_CENT = 189, - TCOD_CHAR_YEN = 190, - TCOD_CHAR_CURRENCY = 207, - TCOD_CHAR_THREE_QUARTERS = 243, - TCOD_CHAR_DIVISION = 246, - TCOD_CHAR_GRADE = 248, - TCOD_CHAR_UMLAUT = 249, - TCOD_CHAR_POW1 = 251, - TCOD_CHAR_POW3 = 252, - TCOD_CHAR_POW2 = 253, - TCOD_CHAR_BULLET_SQUARE = 254, - /* diacritics */ -} TCOD_chars_t; - -typedef enum { - TCOD_COLCTRL_1 = 1, - TCOD_COLCTRL_2, - TCOD_COLCTRL_3, - TCOD_COLCTRL_4, - TCOD_COLCTRL_5, - TCOD_COLCTRL_NUMBER=5, - TCOD_COLCTRL_FORE_RGB, - TCOD_COLCTRL_BACK_RGB, - TCOD_COLCTRL_STOP -} TCOD_colctrl_t; - -typedef enum { - TCOD_BKGND_NONE, - TCOD_BKGND_SET, - TCOD_BKGND_MULTIPLY, - TCOD_BKGND_LIGHTEN, - TCOD_BKGND_DARKEN, - TCOD_BKGND_SCREEN, - TCOD_BKGND_COLOR_DODGE, - TCOD_BKGND_COLOR_BURN, - TCOD_BKGND_ADD, - TCOD_BKGND_ADDA, - TCOD_BKGND_BURN, - TCOD_BKGND_OVERLAY, - TCOD_BKGND_ALPH, - TCOD_BKGND_DEFAULT -} TCOD_bkgnd_flag_t; - -typedef enum { - TCOD_KEY_PRESSED=1, - TCOD_KEY_RELEASED=2, -} TCOD_key_status_t; - -/** - * These font flags can be OR'd together into a bit-field and passed to - * TCOD_console_set_custom_font - */ -typedef enum { - /** Tiles are arranged in column-major order. - * - * 0 3 6 - * 1 4 7 - * 2 5 8 - */ - TCOD_FONT_LAYOUT_ASCII_INCOL=1, - /** Tiles are arranged in row-major order. - * - * 0 1 2 - * 3 4 5 - * 6 7 8 - */ - TCOD_FONT_LAYOUT_ASCII_INROW=2, - /** Converts all tiles into a monochrome gradient. */ - TCOD_FONT_TYPE_GREYSCALE=4, - TCOD_FONT_TYPE_GRAYSCALE=4, - /** A unique layout used by some of libtcod's fonts. */ - TCOD_FONT_LAYOUT_TCOD=8, -} TCOD_font_flags_t; -/** - * The available renderers. - */ -typedef enum { - /** An OpenGL implementation using a shader. */ - TCOD_RENDERER_GLSL, - /** - * An OpenGL implementation without a shader. - * - * Performs worse than TCOD_RENDERER_GLSL without many benefits. - */ - TCOD_RENDERER_OPENGL, - /** - * A software based renderer. - * - * The font file is loaded into RAM instead of VRAM in this implementation. - */ - TCOD_RENDERER_SDL, - TCOD_NB_RENDERERS, -} TCOD_renderer_t; - -/** - * \enum TCOD_alignment_t - * - * Print justification options. - */ -typedef enum { - TCOD_LEFT, - TCOD_RIGHT, - TCOD_CENTER -} TCOD_alignment_t; -#endif /* _TCOD_CONSOLE_TYPES_H */ +/* +* libtcod +* Copyright (c) 2008-2018 Jice & Mingos & rmtew +* All rights reserved. +* +* Redistribution and use in source and binary forms, with or without +* modification, are permitted provided that the following conditions are met: +* * Redistributions of source code must retain the above copyright +* notice, this list of conditions and the following disclaimer. +* * Redistributions in binary form must reproduce the above copyright +* notice, this list of conditions and the following disclaimer in the +* documentation and/or other materials provided with the distribution. +* * The name of Jice or Mingos may not be used to endorse or promote +* products derived from this software without specific prior written +* permission. +* +* THIS SOFTWARE IS PROVIDED BY JICE, MINGOS AND RMTEW ``AS IS'' AND ANY +* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED +* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE +* DISCLAIMED. IN NO EVENT SHALL JICE, MINGOS OR RMTEW BE LIABLE FOR ANY +* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES +* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; +* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND +* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS +* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +*/ +#ifndef _TCOD_CONSOLE_TYPES_H +#define _TCOD_CONSOLE_TYPES_H + +#include "portability.h" +#include "color.h" + +typedef enum { + TCODK_NONE, + TCODK_ESCAPE, + TCODK_BACKSPACE, + TCODK_TAB, + TCODK_ENTER, + TCODK_SHIFT, + TCODK_CONTROL, + TCODK_ALT, + TCODK_PAUSE, + TCODK_CAPSLOCK, + TCODK_PAGEUP, + TCODK_PAGEDOWN, + TCODK_END, + TCODK_HOME, + TCODK_UP, + TCODK_LEFT, + TCODK_RIGHT, + TCODK_DOWN, + TCODK_PRINTSCREEN, + TCODK_INSERT, + TCODK_DELETE, + TCODK_LWIN, + TCODK_RWIN, + TCODK_APPS, + TCODK_0, + TCODK_1, + TCODK_2, + TCODK_3, + TCODK_4, + TCODK_5, + TCODK_6, + TCODK_7, + TCODK_8, + TCODK_9, + TCODK_KP0, + TCODK_KP1, + TCODK_KP2, + TCODK_KP3, + TCODK_KP4, + TCODK_KP5, + TCODK_KP6, + TCODK_KP7, + TCODK_KP8, + TCODK_KP9, + TCODK_KPADD, + TCODK_KPSUB, + TCODK_KPDIV, + TCODK_KPMUL, + TCODK_KPDEC, + TCODK_KPENTER, + TCODK_F1, + TCODK_F2, + TCODK_F3, + TCODK_F4, + TCODK_F5, + TCODK_F6, + TCODK_F7, + TCODK_F8, + TCODK_F9, + TCODK_F10, + TCODK_F11, + TCODK_F12, + TCODK_NUMLOCK, + TCODK_SCROLLLOCK, + TCODK_SPACE, + TCODK_CHAR, + TCODK_TEXT +} TCOD_keycode_t; + +#define TCOD_KEY_TEXT_SIZE 32 + +/* key data : special code or character or text */ +typedef struct { + TCOD_keycode_t vk; /* key code */ + char c; /* character if vk == TCODK_CHAR else 0 */ + char text[TCOD_KEY_TEXT_SIZE]; /* text if vk == TCODK_TEXT else text[0] == '\0' */ + bool pressed ; /* does this correspond to a key press or key release event ? */ + bool lalt ; + bool lctrl ; + bool lmeta ; + bool ralt ; + bool rctrl ; + bool rmeta ; + bool shift ; +} TCOD_key_t; + +typedef enum { + /* single walls */ + TCOD_CHAR_HLINE=196, + TCOD_CHAR_VLINE=179, + TCOD_CHAR_NE=191, + TCOD_CHAR_NW=218, + TCOD_CHAR_SE=217, + TCOD_CHAR_SW=192, + TCOD_CHAR_TEEW=180, + TCOD_CHAR_TEEE=195, + TCOD_CHAR_TEEN=193, + TCOD_CHAR_TEES=194, + TCOD_CHAR_CROSS=197, + /* double walls */ + TCOD_CHAR_DHLINE=205, + TCOD_CHAR_DVLINE=186, + TCOD_CHAR_DNE=187, + TCOD_CHAR_DNW=201, + TCOD_CHAR_DSE=188, + TCOD_CHAR_DSW=200, + TCOD_CHAR_DTEEW=185, + TCOD_CHAR_DTEEE=204, + TCOD_CHAR_DTEEN=202, + TCOD_CHAR_DTEES=203, + TCOD_CHAR_DCROSS=206, + /* blocks */ + TCOD_CHAR_BLOCK1=176, + TCOD_CHAR_BLOCK2=177, + TCOD_CHAR_BLOCK3=178, + /* arrows */ + TCOD_CHAR_ARROW_N=24, + TCOD_CHAR_ARROW_S=25, + TCOD_CHAR_ARROW_E=26, + TCOD_CHAR_ARROW_W=27, + /* arrows without tail */ + TCOD_CHAR_ARROW2_N=30, + TCOD_CHAR_ARROW2_S=31, + TCOD_CHAR_ARROW2_E=16, + TCOD_CHAR_ARROW2_W=17, + /* double arrows */ + TCOD_CHAR_DARROW_H=29, + TCOD_CHAR_DARROW_V=18, + /* GUI stuff */ + TCOD_CHAR_CHECKBOX_UNSET=224, + TCOD_CHAR_CHECKBOX_SET=225, + TCOD_CHAR_RADIO_UNSET=9, + TCOD_CHAR_RADIO_SET=10, + /* sub-pixel resolution kit */ + TCOD_CHAR_SUBP_NW=226, + TCOD_CHAR_SUBP_NE=227, + TCOD_CHAR_SUBP_N=228, + TCOD_CHAR_SUBP_SE=229, + TCOD_CHAR_SUBP_DIAG=230, + TCOD_CHAR_SUBP_E=231, + TCOD_CHAR_SUBP_SW=232, + /* miscellaneous */ + TCOD_CHAR_SMILIE = 1, + TCOD_CHAR_SMILIE_INV = 2, + TCOD_CHAR_HEART = 3, + TCOD_CHAR_DIAMOND = 4, + TCOD_CHAR_CLUB = 5, + TCOD_CHAR_SPADE = 6, + TCOD_CHAR_BULLET = 7, + TCOD_CHAR_BULLET_INV = 8, + TCOD_CHAR_MALE = 11, + TCOD_CHAR_FEMALE = 12, + TCOD_CHAR_NOTE = 13, + TCOD_CHAR_NOTE_DOUBLE = 14, + TCOD_CHAR_LIGHT = 15, + TCOD_CHAR_EXCLAM_DOUBLE = 19, + TCOD_CHAR_PILCROW = 20, + TCOD_CHAR_SECTION = 21, + TCOD_CHAR_POUND = 156, + TCOD_CHAR_MULTIPLICATION = 158, + TCOD_CHAR_FUNCTION = 159, + TCOD_CHAR_RESERVED = 169, + TCOD_CHAR_HALF = 171, + TCOD_CHAR_ONE_QUARTER = 172, + TCOD_CHAR_COPYRIGHT = 184, + TCOD_CHAR_CENT = 189, + TCOD_CHAR_YEN = 190, + TCOD_CHAR_CURRENCY = 207, + TCOD_CHAR_THREE_QUARTERS = 243, + TCOD_CHAR_DIVISION = 246, + TCOD_CHAR_GRADE = 248, + TCOD_CHAR_UMLAUT = 249, + TCOD_CHAR_POW1 = 251, + TCOD_CHAR_POW3 = 252, + TCOD_CHAR_POW2 = 253, + TCOD_CHAR_BULLET_SQUARE = 254, + /* diacritics */ +} TCOD_chars_t; + +typedef enum { + TCOD_COLCTRL_1 = 1, + TCOD_COLCTRL_2, + TCOD_COLCTRL_3, + TCOD_COLCTRL_4, + TCOD_COLCTRL_5, + TCOD_COLCTRL_NUMBER=5, + TCOD_COLCTRL_FORE_RGB, + TCOD_COLCTRL_BACK_RGB, + TCOD_COLCTRL_STOP +} TCOD_colctrl_t; + +typedef enum { + TCOD_BKGND_NONE, + TCOD_BKGND_SET, + TCOD_BKGND_MULTIPLY, + TCOD_BKGND_LIGHTEN, + TCOD_BKGND_DARKEN, + TCOD_BKGND_SCREEN, + TCOD_BKGND_COLOR_DODGE, + TCOD_BKGND_COLOR_BURN, + TCOD_BKGND_ADD, + TCOD_BKGND_ADDA, + TCOD_BKGND_BURN, + TCOD_BKGND_OVERLAY, + TCOD_BKGND_ALPH, + TCOD_BKGND_DEFAULT +} TCOD_bkgnd_flag_t; + +typedef enum { + TCOD_KEY_PRESSED=1, + TCOD_KEY_RELEASED=2, +} TCOD_key_status_t; + +/** + * These font flags can be OR'd together into a bit-field and passed to + * TCOD_console_set_custom_font + */ +typedef enum { + /** Tiles are arranged in column-major order. + * + * 0 3 6 + * 1 4 7 + * 2 5 8 + */ + TCOD_FONT_LAYOUT_ASCII_INCOL=1, + /** Tiles are arranged in row-major order. + * + * 0 1 2 + * 3 4 5 + * 6 7 8 + */ + TCOD_FONT_LAYOUT_ASCII_INROW=2, + /** Converts all tiles into a monochrome gradient. */ + TCOD_FONT_TYPE_GREYSCALE=4, + TCOD_FONT_TYPE_GRAYSCALE=4, + /** A unique layout used by some of libtcod's fonts. */ + TCOD_FONT_LAYOUT_TCOD=8, +} TCOD_font_flags_t; +/** + * The available renderers. + */ +typedef enum { + /** An OpenGL implementation using a shader. */ + TCOD_RENDERER_GLSL, + /** + * An OpenGL implementation without a shader. + * + * Performs worse than TCOD_RENDERER_GLSL without many benefits. + */ + TCOD_RENDERER_OPENGL, + /** + * A software based renderer. + * + * The font file is loaded into RAM instead of VRAM in this implementation. + */ + TCOD_RENDERER_SDL, + /** + * A new SDL2 renderer. Allows the window to be resized. + * /rst + * .. versionadded:: 1.8 + * /endrst + */ + TCOD_RENDERER_SDL2, + TCOD_NB_RENDERERS, +} TCOD_renderer_t; + +/** + * \enum TCOD_alignment_t + * + * Print justification options. + */ +typedef enum { + TCOD_LEFT, + TCOD_RIGHT, + TCOD_CENTER +} TCOD_alignment_t; + +/** Private console struct. */ +typedef struct TCOD_Console { + /** Character code array. */ + int *ch_array; + /** Pointers to arrays of TCOD_color_t colors. */ + TCOD_color_t *fg_array, *bg_array; + /** Console width and height (in characters, not pixels.) */ + int w,h; + /** Default background operator for print & print_rect functions. */ + TCOD_bkgnd_flag_t bkgnd_flag; + /** Default alignment for print & print_rect functions. */ + TCOD_alignment_t alignment; + /** Foreground (text) and background colors. */ + TCOD_color_t fore, back; + /** True if a key color is being used. */ + bool has_key_color; + /** The current key color for this console. */ + TCOD_color_t key_color; +} TCOD_Console; +typedef TCOD_Console *TCOD_console_t; +#endif /* _TCOD_CONSOLE_TYPES_H */ diff --git a/tcod_sys/libtcod/src/libtcod/engine/backend.cpp b/tcod_sys/libtcod/src/libtcod/engine/backend.cpp new file mode 100644 index 000000000..33668d290 --- /dev/null +++ b/tcod_sys/libtcod/src/libtcod/engine/backend.cpp @@ -0,0 +1,2 @@ + +#include "backend.h" diff --git a/tcod_sys/libtcod/src/libtcod/engine/backend.h b/tcod_sys/libtcod/src/libtcod/engine/backend.h new file mode 100644 index 000000000..dd26541a9 --- /dev/null +++ b/tcod_sys/libtcod/src/libtcod/engine/backend.h @@ -0,0 +1,37 @@ + +#ifndef LIBTCOD_ENGINE_BACKEND_H_ +#define LIBTCOD_ENGINE_BACKEND_H_ + +#ifdef __cplusplus +#include +#endif /* __cplusplus */ + +#include "../console_types.h" +#include "../mouse_types.h" +#include "../sys.h" + +#ifdef __cplusplus +namespace tcod { +namespace engine { +class Backend { + public: + virtual ~Backend() = default; + /** + * Legacy wait for event virtual function. + */ + virtual TCOD_event_t legacy_wait_for_event( + int eventMask, TCOD_key_t *key, TCOD_mouse_t *mouse, bool flush) { + return TCOD_EVENT_NONE; + } + /** + * Legacy check for event virtual function. + */ + virtual TCOD_event_t legacy_check_for_event( + int eventMask, TCOD_key_t *key, TCOD_mouse_t *mouse) { + return TCOD_EVENT_NONE; + } +}; +} // namespace engine +} // namespace tcod +#endif /* __cplusplus */ +#endif /* LIBTCOD_ENGINE_BACKEND_H_ */ diff --git a/tcod_sys/libtcod/src/libtcod/engine/display.cpp b/tcod_sys/libtcod/src/libtcod/engine/display.cpp new file mode 100644 index 000000000..c8d7bf73c --- /dev/null +++ b/tcod_sys/libtcod/src/libtcod/engine/display.cpp @@ -0,0 +1,2 @@ + +#include "display.h" diff --git a/tcod_sys/libtcod/src/libtcod/engine/display.h b/tcod_sys/libtcod/src/libtcod/engine/display.h new file mode 100644 index 000000000..8b70f10eb --- /dev/null +++ b/tcod_sys/libtcod/src/libtcod/engine/display.h @@ -0,0 +1,43 @@ + +#ifndef LIBTCOD_ENGINE_DISPLAY_H_ +#define LIBTCOD_ENGINE_DISPLAY_H_ + +#ifdef __cplusplus +#include +#endif // __cplusplus + +#include "../tileset/tileset.h" +#include "../console_types.h" + +#ifdef __cplusplus +namespace tcod { +namespace engine { +using tcod::tileset::Tileset; +class Display { + public: + virtual ~Display() = default; + virtual void set_tileset(std::shared_ptr tileset) = 0; + virtual void set_title(const std::string title) = 0; + virtual std::string get_title() = 0; + virtual void present(const TCOD_Console*) = 0; +}; +/** + * Incomplete interface for subclasses which don't need an SDL2 window. + */ +class TerminalDisplay: public Display { + public: + virtual void set_tileset(std::shared_ptr tileset) override + {} + virtual void set_title(const std::string title) override + {} + virtual std::string get_title() override + { + return {}; + } +}; +} // namespace sdl2 +} // namespace tcod +#endif // __cplusplus +#endif // LIBTCOD_ENGINE_DISPLAY_H_ + + diff --git a/tcod_sys/libtcod/src/libtcod/engine/globals.cpp b/tcod_sys/libtcod/src/libtcod/engine/globals.cpp new file mode 100644 index 000000000..ea00c17c7 --- /dev/null +++ b/tcod_sys/libtcod/src/libtcod/engine/globals.cpp @@ -0,0 +1,46 @@ + +#include "globals.h" + +#include + +namespace tcod { +namespace engine { +std::shared_ptr active_backend = nullptr; +std::shared_ptr active_display = nullptr; +std::shared_ptr active_tileset = nullptr; +std::shared_ptr active_tilesheet = nullptr; + +void set_backend(std::shared_ptr backend) +{ + active_backend = backend; +} +std::shared_ptr get_backend() +{ + return active_backend; +} +void set_display(std::shared_ptr display) +{ + active_display = display; +} +std::shared_ptr get_display() +{ + return active_display; +} +void set_tileset(std::shared_ptr tileset) +{ + active_tileset = tileset; +} +auto get_tileset() -> std::shared_ptr +{ + return active_tileset; +} +void set_tilesheet(std::shared_ptr sheet) +{ + active_tilesheet = sheet; +} +auto get_tilesheet() -> std::shared_ptr +{ + return active_tilesheet; +} +} // namespace sdl2 +} // namespace tcod diff --git a/tcod_sys/libtcod/src/libtcod/engine/globals.h b/tcod_sys/libtcod/src/libtcod/engine/globals.h new file mode 100644 index 000000000..0f9b55f0e --- /dev/null +++ b/tcod_sys/libtcod/src/libtcod/engine/globals.h @@ -0,0 +1,45 @@ + +#ifndef LIBTCOD_ENGINE_GLOBALS_H_ +#define LIBTCOD_ENGINE_GLOBALS_H_ + +#ifdef __cplusplus +#include +#endif // __cplusplus + +#include "backend.h" +#include "display.h" +#include "../tileset/tileset.h" +#include "../tileset/tilesheet.h" + +#ifdef __cplusplus +namespace tcod { +namespace engine { +using tileset::Tileset; +using tileset::Tilesheet; +/** + * Replace the active backend with a new instance, can be nullptr. + */ +void set_backend(std::shared_ptr backend); +/** + * Return a shared pointer to the active backend. Might be nullptr. + */ +std::shared_ptr get_backend(); +/** + * Replace the active display with a new instance, can be nullptr. + */ +void set_display(std::shared_ptr display); +/** + * Return a shared pointer to the active display. Might be nullptr. + */ +std::shared_ptr get_display(); + +void set_tileset(std::shared_ptr tileset); +auto get_tileset() -> std::shared_ptr; +void set_tilesheet(std::shared_ptr sheet); +auto get_tilesheet() -> std::shared_ptr; +} // namespace sdl2 +} // namespace tcod +#endif // __cplusplus +#endif // LIBTCOD_ENGINE_GLOBALS_H_ + + diff --git a/tcod_sys/libtcod/src/fov.cpp b/tcod_sys/libtcod/src/libtcod/fov.cpp similarity index 96% rename from tcod_sys/libtcod/src/fov.cpp rename to tcod_sys/libtcod/src/libtcod/fov.cpp index c04214fad..6a0c3fe47 100644 --- a/tcod_sys/libtcod/src/fov.cpp +++ b/tcod_sys/libtcod/src/libtcod/fov.cpp @@ -1,80 +1,80 @@ -/* -* libtcod -* Copyright (c) 2008-2018 Jice & Mingos & rmtew -* All rights reserved. -* -* Redistribution and use in source and binary forms, with or without -* modification, are permitted provided that the following conditions are met: -* * Redistributions of source code must retain the above copyright -* notice, this list of conditions and the following disclaimer. -* * Redistributions in binary form must reproduce the above copyright -* notice, this list of conditions and the following disclaimer in the -* documentation and/or other materials provided with the distribution. -* * The name of Jice or Mingos may not be used to endorse or promote -* products derived from this software without specific prior written -* permission. -* -* THIS SOFTWARE IS PROVIDED BY JICE, MINGOS AND RMTEW ``AS IS'' AND ANY -* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED -* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE -* DISCLAIMED. IN NO EVENT SHALL JICE, MINGOS OR RMTEW BE LIABLE FOR ANY -* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES -* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; -* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND -* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS -* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. -*/ -#include - -TCODMap::TCODMap(int width,int height) { - data = TCOD_map_new(width,height); -} - -void TCODMap::clear(bool transparent, bool walkable) { - TCOD_map_clear(data,transparent,walkable); -} - -void TCODMap::setProperties(int x, int y, bool isTransparent, bool isWalkable) { - TCOD_map_set_properties(data,x,y,isTransparent,isWalkable); -} - -void TCODMap::copy(const TCODMap *source) { - TCOD_map_copy(source->data,data); -} - -void TCODMap::computeFov(int x, int y, int maxRadius, bool light_walls, TCOD_fov_algorithm_t algo) { - TCOD_map_compute_fov(data,x,y,maxRadius,light_walls, algo); -} - -bool TCODMap::isInFov(int x, int y) const { - return TCOD_map_is_in_fov(data,x,y) != 0; -} - -void TCODMap::setInFov(int x,int y, bool fov) { - TCOD_map_set_in_fov(data, x, y, fov); -} - -bool TCODMap::isTransparent(int x, int y) const { - return TCOD_map_is_transparent(data,x,y) != 0; -} - -bool TCODMap::isWalkable(int x, int y) const { - return TCOD_map_is_walkable(data,x,y) != 0; -} - -int TCODMap::getWidth() const { - return TCOD_map_get_width(data); -} - -int TCODMap::getHeight() const { - return TCOD_map_get_height(data); -} - -int TCODMap::getNbCells() const { - return TCOD_map_get_nb_cells(data); -} - -TCODMap::~TCODMap() { - TCOD_map_delete(data); -} +/* +* libtcod +* Copyright (c) 2008-2018 Jice & Mingos & rmtew +* All rights reserved. +* +* Redistribution and use in source and binary forms, with or without +* modification, are permitted provided that the following conditions are met: +* * Redistributions of source code must retain the above copyright +* notice, this list of conditions and the following disclaimer. +* * Redistributions in binary form must reproduce the above copyright +* notice, this list of conditions and the following disclaimer in the +* documentation and/or other materials provided with the distribution. +* * The name of Jice or Mingos may not be used to endorse or promote +* products derived from this software without specific prior written +* permission. +* +* THIS SOFTWARE IS PROVIDED BY JICE, MINGOS AND RMTEW ``AS IS'' AND ANY +* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED +* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE +* DISCLAIMED. IN NO EVENT SHALL JICE, MINGOS OR RMTEW BE LIABLE FOR ANY +* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES +* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; +* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND +* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS +* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +*/ +#include "fov.hpp" + +TCODMap::TCODMap(int width,int height) { + data = TCOD_map_new(width,height); +} + +void TCODMap::clear(bool transparent, bool walkable) { + TCOD_map_clear(data,transparent,walkable); +} + +void TCODMap::setProperties(int x, int y, bool isTransparent, bool isWalkable) { + TCOD_map_set_properties(data,x,y,isTransparent,isWalkable); +} + +void TCODMap::copy(const TCODMap *source) { + TCOD_map_copy(source->data,data); +} + +void TCODMap::computeFov(int x, int y, int maxRadius, bool light_walls, TCOD_fov_algorithm_t algo) { + TCOD_map_compute_fov(data,x,y,maxRadius,light_walls, algo); +} + +bool TCODMap::isInFov(int x, int y) const { + return TCOD_map_is_in_fov(data,x,y) != 0; +} + +void TCODMap::setInFov(int x,int y, bool fov) { + TCOD_map_set_in_fov(data, x, y, fov); +} + +bool TCODMap::isTransparent(int x, int y) const { + return TCOD_map_is_transparent(data,x,y) != 0; +} + +bool TCODMap::isWalkable(int x, int y) const { + return TCOD_map_is_walkable(data,x,y) != 0; +} + +int TCODMap::getWidth() const { + return TCOD_map_get_width(data); +} + +int TCODMap::getHeight() const { + return TCOD_map_get_height(data); +} + +int TCODMap::getNbCells() const { + return TCOD_map_get_nb_cells(data); +} + +TCODMap::~TCODMap() { + TCOD_map_delete(data); +} diff --git a/tcod_sys/libtcod/include/fov.h b/tcod_sys/libtcod/src/libtcod/fov.h similarity index 66% rename from tcod_sys/libtcod/include/fov.h rename to tcod_sys/libtcod/src/libtcod/fov.h index d574deece..39d013fd4 100644 --- a/tcod_sys/libtcod/include/fov.h +++ b/tcod_sys/libtcod/src/libtcod/fov.h @@ -28,35 +28,39 @@ #ifndef _TCOD_FOV_H #define _TCOD_FOV_H -#include "libtcod_portability.h" +#include "portability.h" #include "fov_types.h" #ifdef __cplusplus extern "C" { #endif /* allocate a new map */ -TCODLIB_API TCOD_map_t TCOD_map_new(int width, int height); +TCODLIB_API TCOD_Map *TCOD_map_new(int width, int height); /* set all cells as solid rock (cannot see through nor walk) */ -TCODLIB_API void TCOD_map_clear(TCOD_map_t map, bool transparent, bool walkable); +TCODLIB_API void TCOD_map_clear(TCOD_Map *map, + bool transparent, bool walkable); /* copy a map to another, reallocating it when needed */ -TCODLIB_API void TCOD_map_copy(TCOD_map_t source, TCOD_map_t dest); +TCODLIB_API void TCOD_map_copy(const TCOD_Map *source, TCOD_Map *dest); /* change a cell properties */ -TCODLIB_API void TCOD_map_set_properties(TCOD_map_t map, int x, int y, bool is_transparent, bool is_walkable); +TCODLIB_API void TCOD_map_set_properties( + TCOD_Map *map, int x, int y, bool is_transparent, bool is_walkable); /* destroy a map */ -TCODLIB_API void TCOD_map_delete(TCOD_map_t map); +TCODLIB_API void TCOD_map_delete(TCOD_Map *map); /* calculate the field of view (potentially visible cells from player_x,player_y) */ -TCODLIB_API void TCOD_map_compute_fov(TCOD_map_t map, int player_x, int player_y, int max_radius, bool light_walls, TCOD_fov_algorithm_t algo); +TCODLIB_API void TCOD_map_compute_fov( + TCOD_Map *map, int player_x, int player_y, int max_radius, + bool light_walls, TCOD_fov_algorithm_t algo); /* check if a cell is in the last computed field of view */ -TCODLIB_API bool TCOD_map_is_in_fov(TCOD_map_t map, int x, int y); -TCODLIB_API void TCOD_map_set_in_fov(TCOD_map_t map, int x, int y, bool fov); +TCODLIB_API bool TCOD_map_is_in_fov(const TCOD_Map *map, int x, int y); +TCODLIB_API void TCOD_map_set_in_fov(TCOD_Map *map, int x, int y, bool fov); /* retrieve properties from the map */ -TCODLIB_API bool TCOD_map_is_transparent(TCOD_map_t map, int x, int y); -TCODLIB_API bool TCOD_map_is_walkable(TCOD_map_t map, int x, int y); -TCODLIB_API int TCOD_map_get_width(TCOD_map_t map); -TCODLIB_API int TCOD_map_get_height(TCOD_map_t map); -TCODLIB_API int TCOD_map_get_nb_cells(TCOD_map_t map); +TCODLIB_API bool TCOD_map_is_transparent(const TCOD_Map *map, int x, int y); +TCODLIB_API bool TCOD_map_is_walkable(TCOD_Map *map, int x, int y); +TCODLIB_API int TCOD_map_get_width(const TCOD_Map *map); +TCODLIB_API int TCOD_map_get_height(const TCOD_Map *map); +TCODLIB_API int TCOD_map_get_nb_cells(const TCOD_Map *map); #ifdef __cplusplus } #endif diff --git a/tcod_sys/libtcod/include/fov.hpp b/tcod_sys/libtcod/src/libtcod/fov.hpp similarity index 97% rename from tcod_sys/libtcod/include/fov.hpp rename to tcod_sys/libtcod/src/libtcod/fov.hpp index 2ea0d0f33..b0d894289 100644 --- a/tcod_sys/libtcod/include/fov.hpp +++ b/tcod_sys/libtcod/src/libtcod/fov.hpp @@ -1,256 +1,256 @@ -/* -* libtcod -* Copyright (c) 2008-2018 Jice & Mingos & rmtew -* All rights reserved. -* -* Redistribution and use in source and binary forms, with or without -* modification, are permitted provided that the following conditions are met: -* * Redistributions of source code must retain the above copyright -* notice, this list of conditions and the following disclaimer. -* * Redistributions in binary form must reproduce the above copyright -* notice, this list of conditions and the following disclaimer in the -* documentation and/or other materials provided with the distribution. -* * The name of Jice or Mingos may not be used to endorse or promote -* products derived from this software without specific prior written -* permission. -* -* THIS SOFTWARE IS PROVIDED BY JICE, MINGOS AND RMTEW ``AS IS'' AND ANY -* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED -* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE -* DISCLAIMED. IN NO EVENT SHALL JICE, MINGOS OR RMTEW BE LIABLE FOR ANY -* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES -* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; -* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND -* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS -* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. -*/ -#ifndef _TCOD_FOV_HPP -#define _TCOD_FOV_HPP - -#include "fov.h" - -class TCODPath; -/** - @PageName fov - @PageCategory Roguelike toolkits - @PageTitle Field of view - @PageDesc This toolkit allows one to easily calculate the potential visible set of map cells from the player position. -A cell is potentially visible if the line of sight from the player to the cell in unobstructed. - */ - -class TCODLIB_API TCODMap { - public : - /** - @PageName fov_init - @PageFather fov - @PageTitle Building the map - @FuncTitle Creating the map object - @FuncDesc First, you have to allocate a map of the same size as your dungeon. - @Cpp TCODMap::TCODMap (int width, int height) - @C TCOD_map_t TCOD_map_new (int width, int height) - @Py map_new (width, height) - @C# TCODMap::TCODMap(int width, int height) - @Param width, height The size of the map (in map cells). - */ - TCODMap(int width, int height); - - /** - @PageName fov_init - @PageFather fov - @FuncTitle Defining the cell properties - @FuncDesc Then, build your dungeon by defining which cells let the light pass (by default, all cells block the light) and which cells are walkable (by default, all cells are not-walkable). - @Cpp void TCODMap::setProperties (int x, int y, bool isTransparent, bool isWalkable) - @C void TCOD_map_set_properties (TCOD_map_t map, int x, int y, bool is_transparent, bool is_walkable) - @Py map_set_properties (map, x, y, is_transparent, is_walkable) - @C# void TCODMap::setProperties (int x, int y, bool isTransparent, bool isWalkable) - @Param map In the C version, the map handler returned by the TCOD_map_new function. - @Param x, y Coordinate of the cell that we want to update. - @Param isTransparent If true, this cell will let the light pass else it will block the light. - @Param isWalkable If true, creatures can walk true this cell (it is not a wall). - */ - void setProperties(int x,int y, bool isTransparent, bool isWalkable); - - /** - @PageName fov_init - @PageFather fov - @FuncTitle Clearing the map - @FuncDesc You can clear an existing map (setting all cells to the chosen walkable/transparent values) with: - @Cpp void TCODMap::clear (bool transparent = false, bool walkable = false) - @C void TCOD_map_clear (TCOD_map_t map, bool transparent, bool walkable) - @Py map_clear (map, transparent = False, walkable = False) - @C# - void TCODMap::clear() - void TCODMap::clear(bool transparent) - void TCODMap::clear(bool transparent, bool walkable) - @Param map In the C version, the map handler returned by the TCOD_map_new function. - @Param walkable Whether the cells should be walkable. - @Param transparent Whether the cells should be transparent. - */ - void clear(bool transparent=false, bool walkable=false); - - /** - @PageName fov_init - @PageFather fov - @FuncTitle Copying a map - @FuncDesc You can copy an existing map into another. You have to allocate the destination map first. - @Cpp void TCODMap::copy (const TCODMap * source) - @C void TCOD_map_copy (TCOD_map_t source, TCOD_map_t dest) - @Py map_copy (source, dest) - @C# void TCODMap::copy (TCODMap source) - @Param source The map containing the source data. - @Param dest In C and Python version, the map where data is copied. - @CppEx - TCODMap * map = new TCODMap(50,50); // allocate the map - map->setProperties(10,10,true,true); // set a cell as 'empty' - TCODMap * map2 = new TCODMap(10,10); // allocate another map - map2->copy(map); // copy map data into map2, reallocating it to 50x50 - @CEx - TCOD_map_t map = TCOD_map_new(50,50); - TCOD_map_t map2 = TCOD_map_new(10,10); - TCOD_map_set_properties(map,10,10,true,true); - TCOD_map_copy(map,map2); - @PyEx - map = libtcod.map_new(50,50) - map2 = libtcod.map_new(10,10) - libtcod.map_set_properties(map,10,10,True,True) - libtcod.map_copy(map,map2) - */ - void copy (const TCODMap *source); - - /** - @PageName fov_compute - @PageTitle Computing the field of view - @PageFather fov - @FuncDesc Once your map is allocated and empty cells have been defined, you can calculate the field of view with : -
typedef enum { FOV_BASIC,
-               FOV_DIAMOND,
-               FOV_SHADOW,
-               FOV_PERMISSIVE_0,FOV_PERMISSIVE_1,FOV_PERMISSIVE_2,FOV_PERMISSIVE_3,
-               FOV_PERMISSIVE_4,FOV_PERMISSIVE_5,FOV_PERMISSIVE_6,FOV_PERMISSIVE_7,FOV_PERMISSIVE_8,
-               FOV_RESTRICTIVE,
-               NB_FOV_ALGORITHMS } TCOD_fov_algorithm_t;
-            
- * FOV_BASIC : classic libtcod fov algorithm (ray casted from the player to all the cells on the submap perimeter) - * FOV_DIAMOND : based on this algorithm - * FOV_SHADOW : based on this algorithm - * FOV_PERMISSIVE_x : based on this algorithm - Permissive has a variable permissiveness parameter. You can either use the constants FOV_PERMISSIVE_x, x between 0 (the less permissive) and 8 (the more permissive), or using the macro FOV_PERMISSIVE(x). - * FOV_RESTRICTIVE : Mingos' Restrictive Precise Angle Shadowcasting (MRPAS). Original implementation here. Comparison of the algorithms : - Check this. - @Cpp void TCODMap::computeFov(int playerX,int playerY, int maxRadius=0,bool light_walls = true, TCOD_fov_algorithm_t algo = FOV_BASIC) - @C void TCOD_map_compute_fov(TCOD_map_t map, int player_x, int player_y, int max_radius, bool light_walls, TCOD_fov_algorithm_t algo) - @Py map_compute_fov(map, player_x, player_y, max_radius=0, light_walls=True, algo=FOV_BASIC ) - @C# - void TCODMap::computeFov(int playerX, int playerY) - void TCODMap::computeFov(int playerX, int playerY, int maxRadius) - void TCODMap::computeFov(int playerX, int playerY, int maxRadius,bool light_walls) - void TCODMap::computeFov(int playerX, int playerY, int maxRadius,bool light_walls, TCODFOVTypes algo) - @Param map In the C version, the map handler returned by the TCOD_map_new function. - @Param player_x,player_y Position of the player in the map. - 0 <= player_x < map width. - 0 <= player_y < map height. - @Param maxRadius If > 0, the fov is only computed up to maxRadius cells away from the player. Else, the range is unlimited. - @Param light_walls Whether the wall cells near ground cells in fov must be in fov too. - @Param algo FOV algorithm to use. - @CppEx - TCODMap *map = new TCODMap(50,50); // allocate the map - map->setProperties(10,10,true,true); // set a cell as 'empty' - map->computeFov(10,10); // calculate fov from the cell 10x10 (basic raycasting, unlimited range, walls lighting on) - @CEx - TCOD_map_t map = TCOD_map_new(50,50); - TCOD_map_set_properties(map,10,10,true,true); - TCOD_map_compute_fov(map,10,10,0,true,FOV_SHADOW); // using shadow casting - @PyEx - map = libtcod.map_new(50,50) - libtcod.map_set_properties(map,10,10,True,True) - libtcod.map_compute_fov(map,10,10,0,True,libtcod.FOV_PERMISSIVE(2)) - */ - void computeFov(int playerX,int playerY, int maxRadius = 0,bool light_walls = true, TCOD_fov_algorithm_t algo = FOV_BASIC); - - /** - @PageName fov_get - @PageFather fov - @PageTitle Reading fov information - @FuncTitle Checking if a cell is in fov - @FuncDesc Once your computed the field of view, you can know if a cell is visible with : - @Cpp bool TCODMap::isInFov(int x, int y) const - @C bool TCOD_map_is_in_fov(TCOD_map_t map, int x, int y) - @Py map_is_in_fov(map, x, y) - @C# bool TCODMap::isInFov(int x, int y) - @Param map In the C version, the map handler returned by the TCOD_map_new function. - @Param x,y Coordinates of the cell we want to check. - 0 <= x < map width. - 0 <= y < map height. - @CppEx - TCODMap *map = new TCODMap(50,50); // allocate the map - map->setProperties(10,10,true,true); // set a cell as 'empty' - map->computeFov(10,10); // calculate fov from the cell 10x10 - bool visible=map->isInFov(10,10); // is the cell 10x10 visible ? - @CEx - TCOD_map_t map = TCOD_map_new(50,50); - TCOD_map_set_properties(map,10,10,true,true); - TCOD_map_compute_fov(map,10,10); - bool visible = TCOD_map_is_in_fov(map,10,10); - @PyEx - map = libtcod.map_new(50,50) - libtcod.map_set_properties(map,10,10,True,True) - libtcod.map_compute_fov(map,10,10) - visible = libtcod.map_is_in_fov(map,10,10) - */ - bool isInFov(int x,int y) const; - /** - @PageName fov_get - @FuncTitle Checking a cell transparency/walkability - @FuncDesc You can also retrieve transparent/walkable information with : - @Cpp - bool TCODMap::isTransparent(int x, int y) const - bool TCODMap::isWalkable(int x, int y) const - @C - bool TCOD_map_is_transparent(TCOD_map_t map, int x, int y) - bool TCOD_map_is_walkable(TCOD_map_t map, int x, int y) - @Py - map_is_transparent(map, x, y) - map_is_walkable(map, x, y) - @C# - bool TCODMap::isTransparent(int x, int y) - bool TCODMap::isWalkable(int x, int y) - @Param map In the C version, the map handler returned by the TCOD_map_new function. - @Param x,y Coordinates of the cell we want to check. - 0 <= x < map width. - 0 <= y < map height. - */ - bool isTransparent(int x, int y) const; - bool isWalkable(int x, int y) const; - - /** - @PageName fov_get - @FuncTitle Getting the map size - @FuncDesc You can retrieve the map size with : - @Cpp - int TCODMap::getWidth() const - int TCODMap::getHeight() const - @C - int TCOD_map_get_width(TCOD_map_t map) - int TCOD_map_get_height(TCOD_map_t map) - @Py - map_get_width(map) - map_get_height(map) - @C# - int TCODMap::getWidth() - int TCODMap::getHeight() - @Param map In the C version, the map handler returned by the TCOD_map_new function. - */ - int getWidth() const; - int getHeight() const; - - virtual ~TCODMap(); - void setInFov(int x,int y, bool fov); - int getNbCells() const; - friend class TCODLIB_API TCODPath; - friend class TCODLIB_API TCODDijkstra; -// protected : - TCOD_map_t data; -}; - -#endif +/* +* libtcod +* Copyright (c) 2008-2018 Jice & Mingos & rmtew +* All rights reserved. +* +* Redistribution and use in source and binary forms, with or without +* modification, are permitted provided that the following conditions are met: +* * Redistributions of source code must retain the above copyright +* notice, this list of conditions and the following disclaimer. +* * Redistributions in binary form must reproduce the above copyright +* notice, this list of conditions and the following disclaimer in the +* documentation and/or other materials provided with the distribution. +* * The name of Jice or Mingos may not be used to endorse or promote +* products derived from this software without specific prior written +* permission. +* +* THIS SOFTWARE IS PROVIDED BY JICE, MINGOS AND RMTEW ``AS IS'' AND ANY +* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED +* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE +* DISCLAIMED. IN NO EVENT SHALL JICE, MINGOS OR RMTEW BE LIABLE FOR ANY +* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES +* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; +* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND +* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS +* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +*/ +#ifndef _TCOD_FOV_HPP +#define _TCOD_FOV_HPP + +#include "fov.h" + +class TCODPath; +/** + @PageName fov + @PageCategory Roguelike toolkits + @PageTitle Field of view + @PageDesc This toolkit allows one to easily calculate the potential visible set of map cells from the player position. +A cell is potentially visible if the line of sight from the player to the cell in unobstructed. + */ + +class TCODLIB_API TCODMap { + public : + /** + @PageName fov_init + @PageFather fov + @PageTitle Building the map + @FuncTitle Creating the map object + @FuncDesc First, you have to allocate a map of the same size as your dungeon. + @Cpp TCODMap::TCODMap (int width, int height) + @C TCOD_map_t TCOD_map_new (int width, int height) + @Py map_new (width, height) + @C# TCODMap::TCODMap(int width, int height) + @Param width, height The size of the map (in map cells). + */ + TCODMap(int width, int height); + + /** + @PageName fov_init + @PageFather fov + @FuncTitle Defining the cell properties + @FuncDesc Then, build your dungeon by defining which cells let the light pass (by default, all cells block the light) and which cells are walkable (by default, all cells are not-walkable). + @Cpp void TCODMap::setProperties (int x, int y, bool isTransparent, bool isWalkable) + @C void TCOD_map_set_properties (TCOD_map_t map, int x, int y, bool is_transparent, bool is_walkable) + @Py map_set_properties (map, x, y, is_transparent, is_walkable) + @C# void TCODMap::setProperties (int x, int y, bool isTransparent, bool isWalkable) + @Param map In the C version, the map handler returned by the TCOD_map_new function. + @Param x, y Coordinate of the cell that we want to update. + @Param isTransparent If true, this cell will let the light pass else it will block the light. + @Param isWalkable If true, creatures can walk true this cell (it is not a wall). + */ + void setProperties(int x,int y, bool isTransparent, bool isWalkable); + + /** + @PageName fov_init + @PageFather fov + @FuncTitle Clearing the map + @FuncDesc You can clear an existing map (setting all cells to the chosen walkable/transparent values) with: + @Cpp void TCODMap::clear (bool transparent = false, bool walkable = false) + @C void TCOD_map_clear (TCOD_map_t map, bool transparent, bool walkable) + @Py map_clear (map, transparent = False, walkable = False) + @C# + void TCODMap::clear() + void TCODMap::clear(bool transparent) + void TCODMap::clear(bool transparent, bool walkable) + @Param map In the C version, the map handler returned by the TCOD_map_new function. + @Param walkable Whether the cells should be walkable. + @Param transparent Whether the cells should be transparent. + */ + void clear(bool transparent=false, bool walkable=false); + + /** + @PageName fov_init + @PageFather fov + @FuncTitle Copying a map + @FuncDesc You can copy an existing map into another. You have to allocate the destination map first. + @Cpp void TCODMap::copy (const TCODMap * source) + @C void TCOD_map_copy (TCOD_map_t source, TCOD_map_t dest) + @Py map_copy (source, dest) + @C# void TCODMap::copy (TCODMap source) + @Param source The map containing the source data. + @Param dest In C and Python version, the map where data is copied. + @CppEx + TCODMap * map = new TCODMap(50,50); // allocate the map + map->setProperties(10,10,true,true); // set a cell as 'empty' + TCODMap * map2 = new TCODMap(10,10); // allocate another map + map2->copy(map); // copy map data into map2, reallocating it to 50x50 + @CEx + TCOD_map_t map = TCOD_map_new(50,50); + TCOD_map_t map2 = TCOD_map_new(10,10); + TCOD_map_set_properties(map,10,10,true,true); + TCOD_map_copy(map,map2); + @PyEx + map = libtcod.map_new(50,50) + map2 = libtcod.map_new(10,10) + libtcod.map_set_properties(map,10,10,True,True) + libtcod.map_copy(map,map2) + */ + void copy (const TCODMap *source); + + /** + @PageName fov_compute + @PageTitle Computing the field of view + @PageFather fov + @FuncDesc Once your map is allocated and empty cells have been defined, you can calculate the field of view with : +
typedef enum { FOV_BASIC,
+               FOV_DIAMOND,
+               FOV_SHADOW,
+               FOV_PERMISSIVE_0,FOV_PERMISSIVE_1,FOV_PERMISSIVE_2,FOV_PERMISSIVE_3,
+               FOV_PERMISSIVE_4,FOV_PERMISSIVE_5,FOV_PERMISSIVE_6,FOV_PERMISSIVE_7,FOV_PERMISSIVE_8,
+               FOV_RESTRICTIVE,
+               NB_FOV_ALGORITHMS } TCOD_fov_algorithm_t;
+            
+ * FOV_BASIC : classic libtcod fov algorithm (ray casted from the player to all the cells on the submap perimeter) + * FOV_DIAMOND : based on this algorithm + * FOV_SHADOW : based on this algorithm + * FOV_PERMISSIVE_x : based on this algorithm + Permissive has a variable permissiveness parameter. You can either use the constants FOV_PERMISSIVE_x, x between 0 (the less permissive) and 8 (the more permissive), or using the macro FOV_PERMISSIVE(x). + * FOV_RESTRICTIVE : Mingos' Restrictive Precise Angle Shadowcasting (MRPAS). Original implementation here. Comparison of the algorithms : + Check this. + @Cpp void TCODMap::computeFov(int playerX,int playerY, int maxRadius=0,bool light_walls = true, TCOD_fov_algorithm_t algo = FOV_BASIC) + @C void TCOD_map_compute_fov(TCOD_map_t map, int player_x, int player_y, int max_radius, bool light_walls, TCOD_fov_algorithm_t algo) + @Py map_compute_fov(map, player_x, player_y, max_radius=0, light_walls=True, algo=FOV_BASIC ) + @C# + void TCODMap::computeFov(int playerX, int playerY) + void TCODMap::computeFov(int playerX, int playerY, int maxRadius) + void TCODMap::computeFov(int playerX, int playerY, int maxRadius,bool light_walls) + void TCODMap::computeFov(int playerX, int playerY, int maxRadius,bool light_walls, TCODFOVTypes algo) + @Param map In the C version, the map handler returned by the TCOD_map_new function. + @Param player_x,player_y Position of the player in the map. + 0 <= player_x < map width. + 0 <= player_y < map height. + @Param maxRadius If > 0, the fov is only computed up to maxRadius cells away from the player. Else, the range is unlimited. + @Param light_walls Whether the wall cells near ground cells in fov must be in fov too. + @Param algo FOV algorithm to use. + @CppEx + TCODMap *map = new TCODMap(50,50); // allocate the map + map->setProperties(10,10,true,true); // set a cell as 'empty' + map->computeFov(10,10); // calculate fov from the cell 10x10 (basic raycasting, unlimited range, walls lighting on) + @CEx + TCOD_map_t map = TCOD_map_new(50,50); + TCOD_map_set_properties(map,10,10,true,true); + TCOD_map_compute_fov(map,10,10,0,true,FOV_SHADOW); // using shadow casting + @PyEx + map = libtcod.map_new(50,50) + libtcod.map_set_properties(map,10,10,True,True) + libtcod.map_compute_fov(map,10,10,0,True,libtcod.FOV_PERMISSIVE(2)) + */ + void computeFov(int playerX,int playerY, int maxRadius = 0,bool light_walls = true, TCOD_fov_algorithm_t algo = FOV_BASIC); + + /** + @PageName fov_get + @PageFather fov + @PageTitle Reading fov information + @FuncTitle Checking if a cell is in fov + @FuncDesc Once your computed the field of view, you can know if a cell is visible with : + @Cpp bool TCODMap::isInFov(int x, int y) const + @C bool TCOD_map_is_in_fov(TCOD_map_t map, int x, int y) + @Py map_is_in_fov(map, x, y) + @C# bool TCODMap::isInFov(int x, int y) + @Param map In the C version, the map handler returned by the TCOD_map_new function. + @Param x,y Coordinates of the cell we want to check. + 0 <= x < map width. + 0 <= y < map height. + @CppEx + TCODMap *map = new TCODMap(50,50); // allocate the map + map->setProperties(10,10,true,true); // set a cell as 'empty' + map->computeFov(10,10); // calculate fov from the cell 10x10 + bool visible=map->isInFov(10,10); // is the cell 10x10 visible ? + @CEx + TCOD_map_t map = TCOD_map_new(50,50); + TCOD_map_set_properties(map,10,10,true,true); + TCOD_map_compute_fov(map,10,10); + bool visible = TCOD_map_is_in_fov(map,10,10); + @PyEx + map = libtcod.map_new(50,50) + libtcod.map_set_properties(map,10,10,True,True) + libtcod.map_compute_fov(map,10,10) + visible = libtcod.map_is_in_fov(map,10,10) + */ + bool isInFov(int x,int y) const; + /** + @PageName fov_get + @FuncTitle Checking a cell transparency/walkability + @FuncDesc You can also retrieve transparent/walkable information with : + @Cpp + bool TCODMap::isTransparent(int x, int y) const + bool TCODMap::isWalkable(int x, int y) const + @C + bool TCOD_map_is_transparent(TCOD_map_t map, int x, int y) + bool TCOD_map_is_walkable(TCOD_map_t map, int x, int y) + @Py + map_is_transparent(map, x, y) + map_is_walkable(map, x, y) + @C# + bool TCODMap::isTransparent(int x, int y) + bool TCODMap::isWalkable(int x, int y) + @Param map In the C version, the map handler returned by the TCOD_map_new function. + @Param x,y Coordinates of the cell we want to check. + 0 <= x < map width. + 0 <= y < map height. + */ + bool isTransparent(int x, int y) const; + bool isWalkable(int x, int y) const; + + /** + @PageName fov_get + @FuncTitle Getting the map size + @FuncDesc You can retrieve the map size with : + @Cpp + int TCODMap::getWidth() const + int TCODMap::getHeight() const + @C + int TCOD_map_get_width(TCOD_map_t map) + int TCOD_map_get_height(TCOD_map_t map) + @Py + map_get_width(map) + map_get_height(map) + @C# + int TCODMap::getWidth() + int TCODMap::getHeight() + @Param map In the C version, the map handler returned by the TCOD_map_new function. + */ + int getWidth() const; + int getHeight() const; + + virtual ~TCODMap(); + void setInFov(int x,int y, bool fov); + int getNbCells() const; + friend class TCODLIB_API TCODPath; + friend class TCODLIB_API TCODDijkstra; +// protected : + TCOD_map_t data; +}; + +#endif diff --git a/tcod_sys/libtcod/src/libtcod/fov_c.c b/tcod_sys/libtcod/src/libtcod/fov_c.c new file mode 100644 index 000000000..dd0ead99e --- /dev/null +++ b/tcod_sys/libtcod/src/libtcod/fov_c.c @@ -0,0 +1,206 @@ +/* +* libtcod +* Copyright (c) 2008-2018 Jice & Mingos & rmtew +* All rights reserved. +* +* Redistribution and use in source and binary forms, with or without +* modification, are permitted provided that the following conditions are met: +* * Redistributions of source code must retain the above copyright +* notice, this list of conditions and the following disclaimer. +* * Redistributions in binary form must reproduce the above copyright +* notice, this list of conditions and the following disclaimer in the +* documentation and/or other materials provided with the distribution. +* * The name of Jice or Mingos may not be used to endorse or promote +* products derived from this software without specific prior written +* permission. +* +* THIS SOFTWARE IS PROVIDED BY JICE, MINGOS AND RMTEW ``AS IS'' AND ANY +* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED +* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE +* DISCLAIMED. IN NO EVENT SHALL JICE, MINGOS OR RMTEW BE LIABLE FOR ANY +* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES +* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; +* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND +* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS +* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +*/ +#include "fov.h" + +#include +#include + +#include "libtcod_int.h" +/** + * Return a new TCOD_Map with `width` and `height`. + */ +struct TCOD_Map *TCOD_map_new(int width, int height) { + struct TCOD_Map *map = NULL; + if (width <= 0 || height <= 0) { return NULL; } + map = (struct TCOD_Map *)calloc(sizeof(struct TCOD_Map), 1); + map->width = width; + map->height = height; + map->nbcells = width * height; + map->cells = (struct TCOD_MapCell *)calloc(sizeof(struct TCOD_MapCell), + map->nbcells); + return map; +} +/** + * Clone map data from `source` to `dest`. + * + * `dest` will be resized to match `source` if necessary. + */ +void TCOD_map_copy(const struct TCOD_Map *source, struct TCOD_Map *dest) { + if (!source || !dest) { return; } + if (dest->nbcells != source->nbcells) { + free(dest->cells); + dest->cells = (struct TCOD_MapCell *)malloc(sizeof(struct TCOD_MapCell) + * dest->nbcells); + } + dest->width = source->width; + dest->height = source->height; + dest->nbcells = source->nbcells; + memcpy(dest->cells, source->cells, sizeof(struct TCOD_MapCell) + * source->nbcells); +} +/** + * Set all cell values on `map` to the given parameters. + * + * This call also zeroes out the field of view flag. + */ +void TCOD_map_clear(struct TCOD_Map *map, bool transparent, bool walkable) { + int i; + if (!map) { return; } + for (i = 0; i < map->nbcells; ++i) { + map->cells[i].transparent = transparent; + map->cells[i].walkable = walkable; + map->cells[i].fov = 0; + } +} +/** + * Return true if `x` and `y` are in the boundaries of `map`. + * + * Returns false if `map` is NULL. + */ +static int TCOD_map_in_bounds(const struct TCOD_Map *map, int x, int y) { + return map && 0 <= x && x < map->width && 0 <= y && y < map->height; +} +/** + * Set the properties of a single cell. + */ +void TCOD_map_set_properties(struct TCOD_Map *map, int x, int y, + bool is_transparent, bool is_walkable) { + if (!TCOD_map_in_bounds(map, x, y)) { return; } + map->cells[x + y * map->width].transparent = is_transparent; + map->cells[x + y * map->width].walkable = is_walkable; +} +/** + * Free all memory belonging to `map`. + */ +void TCOD_map_delete(struct TCOD_Map *map) { + if (!map) { return; } + free(map->cells); + free(map); +} +/** + * Calculate the field-of-view. + * + * /rst + * `player_x` and `player_y` are the used as the field-of-view source. + * + * `max_radius` is the maximum distance for the field-of-view algorithm. + * + * If `light_walls` is false then only transparent cells will be touched by + * the field-of-view. + * + * `algo` is one of the :any:`TCOD_fov_algorithm_t` algorithms. + * + * After this call you may check if a cell is within the field-of-view by + * calling :any:`TCOD_map_is_in_fov`. + * /endrst + */ +void TCOD_map_compute_fov(struct TCOD_Map *map, int player_x, int player_y, + int max_radius, bool light_walls, + TCOD_fov_algorithm_t algo) { + if (!map) { return; } + switch(algo) { + case FOV_BASIC: + TCOD_map_compute_fov_circular_raycasting(map, player_x, player_y, + max_radius, light_walls); + return; + case FOV_DIAMOND: + TCOD_map_compute_fov_diamond_raycasting(map, player_x, player_y, + max_radius, light_walls); + return; + case FOV_SHADOW: + TCOD_map_compute_fov_recursive_shadowcasting(map, player_x, player_y, + max_radius, light_walls); + return; + case FOV_PERMISSIVE_0: + case FOV_PERMISSIVE_1: + case FOV_PERMISSIVE_2: + case FOV_PERMISSIVE_3: + case FOV_PERMISSIVE_4: + case FOV_PERMISSIVE_5: + case FOV_PERMISSIVE_6: + case FOV_PERMISSIVE_7: + case FOV_PERMISSIVE_8: + TCOD_map_compute_fov_permissive2(map, player_x, player_y, max_radius, + light_walls, algo - FOV_PERMISSIVE_0); + return; + case FOV_RESTRICTIVE: + TCOD_map_compute_fov_restrictive_shadowcasting(map, player_x, player_y, + max_radius, light_walls); + return; + default: return; + } +} +/** + * Return true if this cell was touched by the current field-of-view. + */ +bool TCOD_map_is_in_fov(const struct TCOD_Map *map, int x, int y) { + if (!TCOD_map_in_bounds(map, x, y)) { return 0; } + return map->cells[x + y * map->width].fov; +} +/** + * Set the fov flag on a specific cell. + */ +void TCOD_map_set_in_fov(struct TCOD_Map *map, int x, int y, bool fov) { + if (!TCOD_map_in_bounds(map, x, y)) { return; } + map->cells[x + y * map->width].fov = fov; +} +/** + * Return true if this cell is transparent. + */ +bool TCOD_map_is_transparent(const struct TCOD_Map *map, int x, int y) { + if (!TCOD_map_in_bounds(map, x, y)) { return 0; } + return map->cells[x + y * map->width].transparent; +} +/** + * Return true if this cell is walkable. + */ +bool TCOD_map_is_walkable(struct TCOD_Map *map, int x, int y) { + if (!TCOD_map_in_bounds(map, x, y)) { return 0; } + return map->cells[x + y * map->width].walkable; +} +/** + * Return the width of `map`. + */ +int TCOD_map_get_width(const struct TCOD_Map *map) { + if (!map) { return 0; } + return map->width; +} +/** + * Return the height of `map`. + */ +int TCOD_map_get_height(const struct TCOD_Map *map) { + if (!map) { return 0; } + return map->height; +} +/** + * Return the total number of cells in `map`. + */ +int TCOD_map_get_nb_cells(const struct TCOD_Map *map) { + if (!map) { return 0; } + return map->nbcells; +} diff --git a/tcod_sys/libtcod/src/fov_circular_raycasting.c b/tcod_sys/libtcod/src/libtcod/fov_circular_raycasting.c similarity index 91% rename from tcod_sys/libtcod/src/fov_circular_raycasting.c rename to tcod_sys/libtcod/src/libtcod/fov_circular_raycasting.c index aafb3c7bc..4f25d6b1c 100644 --- a/tcod_sys/libtcod/src/fov_circular_raycasting.c +++ b/tcod_sys/libtcod/src/libtcod/fov_circular_raycasting.c @@ -1,240 +1,240 @@ -/* -* libtcod -* Copyright (c) 2008-2018 Jice & Mingos & rmtew -* All rights reserved. -* -* Redistribution and use in source and binary forms, with or without -* modification, are permitted provided that the following conditions are met: -* * Redistributions of source code must retain the above copyright -* notice, this list of conditions and the following disclaimer. -* * Redistributions in binary form must reproduce the above copyright -* notice, this list of conditions and the following disclaimer in the -* documentation and/or other materials provided with the distribution. -* * The name of Jice or Mingos may not be used to endorse or promote -* products derived from this software without specific prior written -* permission. -* -* THIS SOFTWARE IS PROVIDED BY JICE, MINGOS AND RMTEW ``AS IS'' AND ANY -* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED -* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE -* DISCLAIMED. IN NO EVENT SHALL JICE, MINGOS OR RMTEW BE LIABLE FOR ANY -* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES -* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; -* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND -* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS -* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. -*/ -#include - -#include -#include -#include - -#include -#include -#include - -static void cast_ray(map_t *map, int xo, int yo, int xd, int yd, int r2,bool light_walls) { - int curx=xo,cury=yo; - bool in=false; - bool blocked=false; - bool end=false; - int offset; - TCOD_bresenham_data_t bresenham_data; - TCOD_line_init_mt(xo,yo,xd,yd,&bresenham_data); - offset=curx+cury*map->width; - if ( 0 <= offset && offset < map->nbcells ) { - in=true; - map->cells[offset].fov=1; - } - while (!end) { - end = TCOD_line_step_mt(&curx,&cury,&bresenham_data); /* reached xd,yd */ - offset=curx+cury*map->width; - if ( r2 > 0 ) { - /* check radius */ - int cur_radius=(curx-xo)*(curx-xo)+(cury-yo)*(cury-yo); - if ( cur_radius > r2 ) return; - } - if ( 0 <= offset && offset < map->nbcells ) { - in=true; - if ( !blocked && ! map->cells[offset].transparent ) { - blocked=true; - } else if ( blocked ) { - return; /* wall */ - } - if ( light_walls || ! blocked ) map->cells[offset].fov=1; - } else if (in) return; /* ray out of map */ - } -} - -void TCOD_map_postproc(map_t *map,int x0,int y0, int x1, int y1, int dx, int dy) { - int cx,cy; - for (cx=x0; cx <= x1; cx++) { - for (cy=y0;cy <= y1; cy ++ ) { - int x2 = cx+dx; - int y2 = cy+dy; - unsigned int offset=cx+cy*map->width; - if ( offset < (unsigned)map->nbcells && map->cells[offset].fov == 1 - && map->cells[offset].transparent ) { - if ( x2 >= x0 && x2 <= x1 ) { - unsigned int offset2=x2+cy*map->width; - if ( offset2 < (unsigned)map->nbcells && ! map->cells[offset2].transparent ) - map->cells[offset2].fov=1; - } - if ( y2 >= y0 && y2 <= y1 ) { - unsigned int offset2=cx+y2*map->width; - if ( offset2 < (unsigned)map->nbcells && ! map->cells[offset2].transparent ) - map->cells[offset2].fov=1; - } - if ( x2 >= x0 && x2 <= x1 && y2 >= y0 && y2 <= y1 ) { - unsigned int offset2=x2+y2*map->width; - if ( offset2 < (unsigned)map->nbcells && ! map->cells[offset2].transparent ) - map->cells[offset2].fov=1; - } - } - } - } -} - - -void TCOD_map_compute_fov_circular_raycastingi(TCOD_map_t map, int player_x, int player_y, int max_radius, bool light_walls) { - int xo,yo; - map_t *m = (map_t *)map; - /* circular ray casting */ - int xmin=0, ymin=0, xmax=m->width, ymax=m->height; - int c; - int r2=max_radius*max_radius; - if ( max_radius > 0 ) { - xmin=MAX(0,player_x-max_radius); - ymin=MAX(0,player_y-max_radius); - xmax=MIN(m->width,player_x+max_radius+1); - ymax=MIN(m->height,player_y+max_radius+1); - } - for (c=m->nbcells-1; c >= 0; c--) { - m->cells[c].fov=0; - } - xo=xmin; yo=ymin; - while ( xo < xmax ) { - cast_ray(m,player_x,player_y,xo++,yo,r2,light_walls); - } - xo=xmax-1;yo=ymin+1; - while ( yo < ymax ) { - cast_ray(m,player_x,player_y,xo,yo++,r2,light_walls); - } - xo=xmax-2;yo=ymax-1; - while ( xo >= 0 ) { - cast_ray(m,player_x,player_y,xo--,yo,r2,light_walls); - } - xo=xmin;yo=ymax-2; - while ( yo > 0 ) { - cast_ray(m,player_x,player_y,xo,yo--,r2,light_walls); - } - if ( light_walls ) { - /* post-processing artefact fix */ - TCOD_map_postproc(m,xmin,ymin,player_x,player_y,-1,-1); - TCOD_map_postproc(m,player_x,ymin,xmax-1,player_y,1,-1); - TCOD_map_postproc(m,xmin,player_y,player_x,ymax-1,-1,1); - TCOD_map_postproc(m,player_x,player_y,xmax-1,ymax-1,1,1); - } -} - -#if 0 -#define CELL_RADIUS 0.4f -#define RAY_RADIUS 0.2f -static bool ray_blocked(map_t *map,float x, float y, int cx, int cy) { - int offset=cx+cy*map->width; - float d; - if ( (unsigned)offset >= (unsigned)map->nbcells ) return false; /* out of the map */ - if ( map->cells[offset].transparent ) return false; /* empty cell */ - d=(cx-x+0.5f)*(cx-x+0.5f)+(cy-y+0.5f)*(cy-y+0.5f); - return d < (CELL_RADIUS+RAY_RADIUS)*(CELL_RADIUS+RAY_RADIUS); -} -static void cast_rayf(map_t *map, int xo, int yo, int xd, int yd, int r2,bool light_walls) { - float fxo=xo+0.5f, fyo=yo+0.5f; - float curx=fxo, cury=fyo; - float fxd=xd+0.5f; - float fyd=yd+0.5f; - bool in=false; - bool end=false; - int offset; - float dx=(float)(fxd-curx), dy=(float)(fyd-cury),idx,idy; - if ( dx == 0 && dy == 0 ) return; - if ( fabs(dx) > fabs(dy) ) { - idy = (float)(dy/fabs(dx)); - idx = (float)(dx/fabs(dx)); - } else { - idx = (float)(dx/fabs(dy)); - idy = (float)(dy/fabs(dy)); - } - offset=(int)(curx)+(int)(cury)*map->width; - if ( (unsigned)offset < (unsigned)map->nbcells ) { - in=true; - map->cells[offset].fov=1; - } - while (!end) { - int cx,cy; - curx+=idx; - cury+=idy; - cx=(int)curx; - cy=(int)cury; - end = (cx==xd && cy==yd); - offset=cx+cy*map->width; - if ( r2 > 0 ) { - /* check radius */ - int cur_radius=(int)((curx-fxo)*(curx-fxo)+(cury-fyo)*(cury-fyo)); - if ( cur_radius > r2 ) return; - } - if ( (unsigned)offset < (unsigned)map->nbcells ) { - in=true; - if ( ray_blocked(map,curx,cury,cx,cy) ) return; - if ( curx+RAY_RADIUS > cx+0.5f-CELL_RADIUS && ray_blocked(map,curx,cury,cx+1,cy) ) return; - if ( curx-RAY_RADIUS < cx-0.5f+CELL_RADIUS && ray_blocked(map,curx,cury,cx-1,cy) ) return; - if ( cury+RAY_RADIUS > cy+0.5f-CELL_RADIUS && ray_blocked(map,curx,cury,cx,cy+1) ) return; - if ( cury-RAY_RADIUS < cy-0.5f+CELL_RADIUS && ray_blocked(map,curx,cury,cx,cy-1) ) return; - map->cells[offset].fov=1; - } else if (in) return; /* ray out of map */ - } -} -#endif - -void TCOD_map_compute_fov_circular_raycasting(TCOD_map_t map, int player_x, int player_y, int max_radius, bool light_walls) { - int xo,yo; - map_t *m = (map_t *)map; - /* circular ray casting */ - int xmin=0, ymin=0, xmax=m->width, ymax=m->height; - int c; - int r2=max_radius*max_radius; - if ( max_radius > 0 ) { - xmin=MAX(0,player_x-max_radius); - ymin=MAX(0,player_y-max_radius); - xmax=MIN(m->width,player_x+max_radius+1); - ymax=MIN(m->height,player_y+max_radius+1); - } - for (c=m->nbcells-1; c >= 0; c--) { - m->cells[c].fov=0; - } - xo=xmin; yo=ymin; - while ( xo < xmax ) { - cast_ray(m,player_x,player_y,xo++,yo,r2,light_walls); - } - xo=xmax-1;yo=ymin+1; - while ( yo < ymax ) { - cast_ray(m,player_x,player_y,xo,yo++,r2,light_walls); - } - xo=xmax-2;yo=ymax-1; - while ( xo >= 0 ) { - cast_ray(m,player_x,player_y,xo--,yo,r2,light_walls); - } - xo=xmin;yo=ymax-2; - while ( yo > 0 ) { - cast_ray(m,player_x,player_y,xo,yo--,r2,light_walls); - } - if ( light_walls ) { - /* post-processing artefact fix */ - TCOD_map_postproc(m,xmin,ymin,player_x,player_y,-1,-1); - TCOD_map_postproc(m,player_x,ymin,xmax-1,player_y,1,-1); - TCOD_map_postproc(m,xmin,player_y,player_x,ymax-1,-1,1); - TCOD_map_postproc(m,player_x,player_y,xmax-1,ymax-1,1,1); - } -} +/* +* libtcod +* Copyright (c) 2008-2018 Jice & Mingos & rmtew +* All rights reserved. +* +* Redistribution and use in source and binary forms, with or without +* modification, are permitted provided that the following conditions are met: +* * Redistributions of source code must retain the above copyright +* notice, this list of conditions and the following disclaimer. +* * Redistributions in binary form must reproduce the above copyright +* notice, this list of conditions and the following disclaimer in the +* documentation and/or other materials provided with the distribution. +* * The name of Jice or Mingos may not be used to endorse or promote +* products derived from this software without specific prior written +* permission. +* +* THIS SOFTWARE IS PROVIDED BY JICE, MINGOS AND RMTEW ``AS IS'' AND ANY +* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED +* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE +* DISCLAIMED. IN NO EVENT SHALL JICE, MINGOS OR RMTEW BE LIABLE FOR ANY +* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES +* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; +* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND +* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS +* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +*/ +#include "fov.h" + +#include +#include +#include + +#include "bresenham.h" +#include "libtcod_int.h" +#include "utility.h" + +static void cast_ray(struct TCOD_Map *map, int xo, int yo, int xd, int yd, int r2,bool light_walls) { + int curx=xo,cury=yo; + bool in=false; + bool blocked=false; + bool end=false; + int offset; + TCOD_bresenham_data_t bresenham_data; + TCOD_line_init_mt(xo,yo,xd,yd,&bresenham_data); + offset=curx+cury*map->width; + if ( 0 <= offset && offset < map->nbcells ) { + in=true; + map->cells[offset].fov=1; + } + while (!end) { + end = TCOD_line_step_mt(&curx,&cury,&bresenham_data); /* reached xd,yd */ + offset=curx+cury*map->width; + if ( r2 > 0 ) { + /* check radius */ + int cur_radius=(curx-xo)*(curx-xo)+(cury-yo)*(cury-yo); + if ( cur_radius > r2 ) return; + } + if ( 0 <= offset && offset < map->nbcells ) { + in=true; + if ( !blocked && ! map->cells[offset].transparent ) { + blocked=true; + } else if ( blocked ) { + return; /* wall */ + } + if ( light_walls || ! blocked ) map->cells[offset].fov=1; + } else if (in) return; /* ray out of map */ + } +} + +void TCOD_map_postproc(struct TCOD_Map *map,int x0,int y0, int x1, int y1, int dx, int dy) { + int cx,cy; + for (cx=x0; cx <= x1; cx++) { + for (cy=y0;cy <= y1; cy ++ ) { + int x2 = cx+dx; + int y2 = cy+dy; + unsigned int offset=cx+cy*map->width; + if ( offset < (unsigned)map->nbcells && map->cells[offset].fov == 1 + && map->cells[offset].transparent ) { + if ( x2 >= x0 && x2 <= x1 ) { + unsigned int offset2=x2+cy*map->width; + if ( offset2 < (unsigned)map->nbcells && ! map->cells[offset2].transparent ) + map->cells[offset2].fov=1; + } + if ( y2 >= y0 && y2 <= y1 ) { + unsigned int offset2=cx+y2*map->width; + if ( offset2 < (unsigned)map->nbcells && ! map->cells[offset2].transparent ) + map->cells[offset2].fov=1; + } + if ( x2 >= x0 && x2 <= x1 && y2 >= y0 && y2 <= y1 ) { + unsigned int offset2=x2+y2*map->width; + if ( offset2 < (unsigned)map->nbcells && ! map->cells[offset2].transparent ) + map->cells[offset2].fov=1; + } + } + } + } +} + + +void TCOD_map_compute_fov_circular_raycastingi(TCOD_map_t map, int player_x, int player_y, int max_radius, bool light_walls) { + int xo,yo; + struct TCOD_Map *m = (struct TCOD_Map *)map; + /* circular ray casting */ + int xmin=0, ymin=0, xmax=m->width, ymax=m->height; + int c; + int r2=max_radius*max_radius; + if ( max_radius > 0 ) { + xmin=MAX(0,player_x-max_radius); + ymin=MAX(0,player_y-max_radius); + xmax=MIN(m->width,player_x+max_radius+1); + ymax=MIN(m->height,player_y+max_radius+1); + } + for (c=m->nbcells-1; c >= 0; c--) { + m->cells[c].fov=0; + } + xo=xmin; yo=ymin; + while ( xo < xmax ) { + cast_ray(m,player_x,player_y,xo++,yo,r2,light_walls); + } + xo=xmax-1;yo=ymin+1; + while ( yo < ymax ) { + cast_ray(m,player_x,player_y,xo,yo++,r2,light_walls); + } + xo=xmax-2;yo=ymax-1; + while ( xo >= 0 ) { + cast_ray(m,player_x,player_y,xo--,yo,r2,light_walls); + } + xo=xmin;yo=ymax-2; + while ( yo > 0 ) { + cast_ray(m,player_x,player_y,xo,yo--,r2,light_walls); + } + if ( light_walls ) { + /* post-processing artefact fix */ + TCOD_map_postproc(m,xmin,ymin,player_x,player_y,-1,-1); + TCOD_map_postproc(m,player_x,ymin,xmax-1,player_y,1,-1); + TCOD_map_postproc(m,xmin,player_y,player_x,ymax-1,-1,1); + TCOD_map_postproc(m,player_x,player_y,xmax-1,ymax-1,1,1); + } +} + +#if 0 +#define CELL_RADIUS 0.4f +#define RAY_RADIUS 0.2f +static bool ray_blocked(struct TCOD_Map *map,float x, float y, int cx, int cy) { + int offset=cx+cy*map->width; + float d; + if ( (unsigned)offset >= (unsigned)map->nbcells ) return false; /* out of the map */ + if ( map->cells[offset].transparent ) return false; /* empty cell */ + d=(cx-x+0.5f)*(cx-x+0.5f)+(cy-y+0.5f)*(cy-y+0.5f); + return d < (CELL_RADIUS+RAY_RADIUS)*(CELL_RADIUS+RAY_RADIUS); +} +static void cast_rayf(struct TCOD_Map *map, int xo, int yo, int xd, int yd, int r2,bool light_walls) { + float fxo=xo+0.5f, fyo=yo+0.5f; + float curx=fxo, cury=fyo; + float fxd=xd+0.5f; + float fyd=yd+0.5f; + bool in=false; + bool end=false; + int offset; + float dx=(float)(fxd-curx), dy=(float)(fyd-cury),idx,idy; + if ( dx == 0 && dy == 0 ) return; + if ( fabs(dx) > fabs(dy) ) { + idy = (float)(dy/fabs(dx)); + idx = (float)(dx/fabs(dx)); + } else { + idx = (float)(dx/fabs(dy)); + idy = (float)(dy/fabs(dy)); + } + offset=(int)(curx)+(int)(cury)*map->width; + if ( (unsigned)offset < (unsigned)map->nbcells ) { + in=true; + map->cells[offset].fov=1; + } + while (!end) { + int cx,cy; + curx+=idx; + cury+=idy; + cx=(int)curx; + cy=(int)cury; + end = (cx==xd && cy==yd); + offset=cx+cy*map->width; + if ( r2 > 0 ) { + /* check radius */ + int cur_radius=(int)((curx-fxo)*(curx-fxo)+(cury-fyo)*(cury-fyo)); + if ( cur_radius > r2 ) return; + } + if ( (unsigned)offset < (unsigned)map->nbcells ) { + in=true; + if ( ray_blocked(map,curx,cury,cx,cy) ) return; + if ( curx+RAY_RADIUS > cx+0.5f-CELL_RADIUS && ray_blocked(map,curx,cury,cx+1,cy) ) return; + if ( curx-RAY_RADIUS < cx-0.5f+CELL_RADIUS && ray_blocked(map,curx,cury,cx-1,cy) ) return; + if ( cury+RAY_RADIUS > cy+0.5f-CELL_RADIUS && ray_blocked(map,curx,cury,cx,cy+1) ) return; + if ( cury-RAY_RADIUS < cy-0.5f+CELL_RADIUS && ray_blocked(map,curx,cury,cx,cy-1) ) return; + map->cells[offset].fov=1; + } else if (in) return; /* ray out of map */ + } +} +#endif + +void TCOD_map_compute_fov_circular_raycasting(TCOD_map_t map, int player_x, int player_y, int max_radius, bool light_walls) { + int xo,yo; + struct TCOD_Map *m = (struct TCOD_Map *)map; + /* circular ray casting */ + int xmin=0, ymin=0, xmax=m->width, ymax=m->height; + int c; + int r2=max_radius*max_radius; + if ( max_radius > 0 ) { + xmin=MAX(0,player_x-max_radius); + ymin=MAX(0,player_y-max_radius); + xmax=MIN(m->width,player_x+max_radius+1); + ymax=MIN(m->height,player_y+max_radius+1); + } + for (c=m->nbcells-1; c >= 0; c--) { + m->cells[c].fov=0; + } + xo=xmin; yo=ymin; + while ( xo < xmax ) { + cast_ray(m,player_x,player_y,xo++,yo,r2,light_walls); + } + xo=xmax-1;yo=ymin+1; + while ( yo < ymax ) { + cast_ray(m,player_x,player_y,xo,yo++,r2,light_walls); + } + xo=xmax-2;yo=ymax-1; + while ( xo >= 0 ) { + cast_ray(m,player_x,player_y,xo--,yo,r2,light_walls); + } + xo=xmin;yo=ymax-2; + while ( yo > 0 ) { + cast_ray(m,player_x,player_y,xo,yo--,r2,light_walls); + } + if ( light_walls ) { + /* post-processing artefact fix */ + TCOD_map_postproc(m,xmin,ymin,player_x,player_y,-1,-1); + TCOD_map_postproc(m,player_x,ymin,xmax-1,player_y,1,-1); + TCOD_map_postproc(m,xmin,player_y,player_x,ymax-1,-1,1); + TCOD_map_postproc(m,player_x,player_y,xmax-1,ymax-1,1,1); + } +} diff --git a/tcod_sys/libtcod/src/fov_diamond_raycasting.c b/tcod_sys/libtcod/src/libtcod/fov_diamond_raycasting.c similarity index 91% rename from tcod_sys/libtcod/src/fov_diamond_raycasting.c rename to tcod_sys/libtcod/src/libtcod/fov_diamond_raycasting.c index b02eefe5d..bf280d2e6 100644 --- a/tcod_sys/libtcod/src/fov_diamond_raycasting.c +++ b/tcod_sys/libtcod/src/libtcod/fov_diamond_raycasting.c @@ -1,207 +1,207 @@ -/* -* libtcod -* Copyright (c) 2008-2018 Jice & Mingos & rmtew -* All rights reserved. -* -* Redistribution and use in source and binary forms, with or without -* modification, are permitted provided that the following conditions are met: -* * Redistributions of source code must retain the above copyright -* notice, this list of conditions and the following disclaimer. -* * Redistributions in binary form must reproduce the above copyright -* notice, this list of conditions and the following disclaimer in the -* documentation and/or other materials provided with the distribution. -* * The name of Jice or Mingos may not be used to endorse or promote -* products derived from this software without specific prior written -* permission. -* -* THIS SOFTWARE IS PROVIDED BY JICE, MINGOS AND RMTEW ``AS IS'' AND ANY -* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED -* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE -* DISCLAIMED. IN NO EVENT SHALL JICE, MINGOS OR RMTEW BE LIABLE FOR ANY -* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES -* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; -* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND -* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS -* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. -*/ -#include - -#include -#include - -#include -#include - -typedef struct _ray_data_t { - int xloc,yloc; /* position */ - int xob,yob; /* obscurity vector */ - int xerr,yerr; /* bresenham error */ - struct _ray_data_t * xinput, * yinput; /* offset of input rays */ - bool added; /* already in the fov */ - bool ignore; /* non visible. don't bother processing it */ -} ray_data_t; - -static int origx,origy; /* fov origin */ -static ray_data_t **raymap; /* result rays */ -static ray_data_t *raymap2; /* temporary rays */ -static int perimidx; - -static ray_data_t *new_ray(map_t *m,int x, int y) { - ray_data_t *r; - if ( (unsigned) (x+origx) >= (unsigned)m->width ) return NULL; - if ( (unsigned) (y+origy) >= (unsigned)m->height ) return NULL; - r=&raymap2[ x+origx + (y+origy)*m->width ]; - r->xloc=x; - r->yloc=y; - return r; -} - -static void processRay(map_t *m, TCOD_list_t perim, ray_data_t *new_ray, ray_data_t *input_ray) { - if ( new_ray ) { - int mapx=origx+new_ray->xloc; - int mapy=origy+new_ray->yloc; - int newrayidx; - newrayidx=mapx+mapy*m->width; - if ( new_ray->yloc == input_ray->yloc ) new_ray->xinput=input_ray; - else new_ray->yinput=input_ray; - if (! new_ray->added) { - TCOD_list_push(perim,new_ray); - new_ray->added=true; - raymap[newrayidx] = new_ray; - } - } -} - -#define IS_OBSCURE(r) ((r->xerr > 0 && r->xerr <= r->xob) || (r->yerr > 0 && r->yerr <= r->yob) ) - -static void process_x_input(ray_data_t *new_ray, ray_data_t *xinput) { - if ( xinput->xob == 0 && xinput->yob == 0 ) return; - if ( xinput->xerr > 0 && new_ray->xob == 0) { - new_ray->xerr = xinput->xerr - xinput->yob; - new_ray->yerr = xinput->yerr + xinput->yob; - new_ray->xob=xinput->xob; - new_ray->yob=xinput->yob; - } - if ( xinput->yerr <= 0 && xinput->yob > 0 && xinput->xerr > 0) { - new_ray->yerr = xinput->yerr + xinput->yob; - new_ray->xerr = xinput->xerr - xinput->yob; - new_ray->xob=xinput->xob; - new_ray->yob=xinput->yob; - } -} - -static void process_y_input(ray_data_t *new_ray, ray_data_t *yinput) { - if ( yinput->xob == 0 && yinput->yob == 0 ) return; - if ( yinput->yerr > 0 && new_ray->yob == 0) { - new_ray->yerr = yinput->yerr - yinput->xob; - new_ray->xerr = yinput->xerr + yinput->xob; - new_ray->xob=yinput->xob; - new_ray->yob=yinput->yob; - } - if ( yinput->xerr <= 0 && yinput->xob > 0 && yinput->yerr > 0) { - new_ray->yerr = yinput->yerr - yinput->xob; - new_ray->xerr = yinput->xerr + yinput->xob; - new_ray->xob=yinput->xob; - new_ray->yob=yinput->yob; - } -} - -static void merge_input(map_t *m, ray_data_t *r) { - int rayidx=r->xloc+origx+(r->yloc+origy)*m->width; - ray_data_t *xi=r->xinput; - ray_data_t *yi=r->yinput; - if ( xi ) process_x_input(r,xi); - if ( yi ) process_y_input(r,yi); - if ( ! xi ) { - if ( IS_OBSCURE(yi) ) r->ignore=true; - } else if ( ! yi ) { - if ( IS_OBSCURE(xi) ) r->ignore=true; - } else if ( IS_OBSCURE(xi) && IS_OBSCURE(yi) ) { - r->ignore=true; - } - if (! r->ignore && !m->cells[rayidx].transparent) { - r->xerr = r->xob = ABS(r->xloc); - r->yerr = r->yob = ABS(r->yloc); - } -} - -static void expandPerimeterFrom(map_t *m,TCOD_list_t perim,ray_data_t *r) { - if ( r->xloc >= 0 ) { - processRay(m,perim,new_ray(m,r->xloc+1,r->yloc),r); - } - if ( r->xloc <= 0 ) { - processRay(m,perim,new_ray(m,r->xloc-1,r->yloc),r); - } - if ( r->yloc >= 0 ) { - processRay(m,perim,new_ray(m,r->xloc,r->yloc+1),r); - } - if ( r->yloc <= 0 ) { - processRay(m,perim,new_ray(m,r->xloc,r->yloc-1),r); - } -} - - -void TCOD_map_compute_fov_diamond_raycasting(TCOD_map_t map, int player_x, int player_y, int max_radius, bool light_walls) { - map_t *m = (map_t *)map; - TCOD_list_t perim=TCOD_list_allocate(m->nbcells); - cell_t *c; - ray_data_t **r; - int nbcells; - int r2=max_radius*max_radius; - - perimidx=0; - raymap=(ray_data_t **)calloc(sizeof(ray_data_t*),m->nbcells); - raymap2=(ray_data_t *)calloc(sizeof(ray_data_t),m->nbcells); - origx=player_x; - origy=player_y; - expandPerimeterFrom(m,perim,new_ray(m,0,0)); - while ( perimidx < TCOD_list_size(perim) ) { - ray_data_t *ray=(ray_data_t *)TCOD_list_get(perim,perimidx); - int distance = 0; - if ( r2 > 0 ) distance = ((ray->xloc * ray->xloc) + (ray->yloc * ray->yloc)); - perimidx++; - if ( distance <= r2) { - merge_input(m, ray); - if ( !ray->ignore ) expandPerimeterFrom(m,perim,ray); - } else ray->ignore=true; - } - - /* set fov data */ - c=m->cells; - r=raymap; - nbcells=m->nbcells; - while ( nbcells!= 0 ) { - if ( *r == NULL || (*r)->ignore - || ((*r)->xerr > 0 && (*r)->xerr <= (*r)->xob ) - || ((*r)->yerr > 0 && (*r)->yerr <= (*r)->yob ) - ) { - c->fov=0; - } else { - c->fov=1; - } - c++; - r++; - nbcells--; - } - m->cells[origx+origy*m->width].fov=1; - - /* light walls */ - if ( light_walls ) { - int xmin=0, ymin=0, xmax=m->width, ymax=m->height; - if ( max_radius > 0 ) { - xmin=MAX(0,player_x-max_radius); - ymin=MAX(0,player_y-max_radius); - xmax=MIN(m->width,player_x+max_radius+1); - ymax=MIN(m->height,player_y+max_radius+1); - } - TCOD_map_postproc(m,xmin,ymin,player_x,player_y,-1,-1); - TCOD_map_postproc(m,player_x,ymin,xmax-1,player_y,1,-1); - TCOD_map_postproc(m,xmin,player_y,player_x,ymax-1,-1,1); - TCOD_map_postproc(m,player_x,player_y,xmax-1,ymax-1,1,1); - } - - free(raymap); - free(raymap2); - TCOD_list_delete(perim); -} +/* +* libtcod +* Copyright (c) 2008-2018 Jice & Mingos & rmtew +* All rights reserved. +* +* Redistribution and use in source and binary forms, with or without +* modification, are permitted provided that the following conditions are met: +* * Redistributions of source code must retain the above copyright +* notice, this list of conditions and the following disclaimer. +* * Redistributions in binary form must reproduce the above copyright +* notice, this list of conditions and the following disclaimer in the +* documentation and/or other materials provided with the distribution. +* * The name of Jice or Mingos may not be used to endorse or promote +* products derived from this software without specific prior written +* permission. +* +* THIS SOFTWARE IS PROVIDED BY JICE, MINGOS AND RMTEW ``AS IS'' AND ANY +* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED +* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE +* DISCLAIMED. IN NO EVENT SHALL JICE, MINGOS OR RMTEW BE LIABLE FOR ANY +* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES +* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; +* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND +* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS +* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +*/ +#include "fov.h" + +#include +#include + +#include "libtcod_int.h" +#include "utility.h" + +typedef struct _ray_data_t { + int xloc,yloc; /* position */ + int xob,yob; /* obscurity vector */ + int xerr,yerr; /* bresenham error */ + struct _ray_data_t * xinput, * yinput; /* offset of input rays */ + bool added; /* already in the fov */ + bool ignore; /* non visible. don't bother processing it */ +} ray_data_t; + +static int origx,origy; /* fov origin */ +static ray_data_t **raymap; /* result rays */ +static ray_data_t *raymap2; /* temporary rays */ +static int perimidx; + +static ray_data_t *new_ray(struct TCOD_Map *m,int x, int y) { + ray_data_t *r; + if ( (unsigned) (x+origx) >= (unsigned)m->width ) return NULL; + if ( (unsigned) (y+origy) >= (unsigned)m->height ) return NULL; + r=&raymap2[ x+origx + (y+origy)*m->width ]; + r->xloc=x; + r->yloc=y; + return r; +} + +static void processRay(struct TCOD_Map *m, TCOD_list_t perim, ray_data_t *new_ray, ray_data_t *input_ray) { + if ( new_ray ) { + int mapx=origx+new_ray->xloc; + int mapy=origy+new_ray->yloc; + int newrayidx; + newrayidx=mapx+mapy*m->width; + if ( new_ray->yloc == input_ray->yloc ) new_ray->xinput=input_ray; + else new_ray->yinput=input_ray; + if (! new_ray->added) { + TCOD_list_push(perim,new_ray); + new_ray->added=true; + raymap[newrayidx] = new_ray; + } + } +} + +#define IS_OBSCURE(r) ((r->xerr > 0 && r->xerr <= r->xob) || (r->yerr > 0 && r->yerr <= r->yob) ) + +static void process_x_input(ray_data_t *new_ray, ray_data_t *xinput) { + if ( xinput->xob == 0 && xinput->yob == 0 ) return; + if ( xinput->xerr > 0 && new_ray->xob == 0) { + new_ray->xerr = xinput->xerr - xinput->yob; + new_ray->yerr = xinput->yerr + xinput->yob; + new_ray->xob=xinput->xob; + new_ray->yob=xinput->yob; + } + if ( xinput->yerr <= 0 && xinput->yob > 0 && xinput->xerr > 0) { + new_ray->yerr = xinput->yerr + xinput->yob; + new_ray->xerr = xinput->xerr - xinput->yob; + new_ray->xob=xinput->xob; + new_ray->yob=xinput->yob; + } +} + +static void process_y_input(ray_data_t *new_ray, ray_data_t *yinput) { + if ( yinput->xob == 0 && yinput->yob == 0 ) return; + if ( yinput->yerr > 0 && new_ray->yob == 0) { + new_ray->yerr = yinput->yerr - yinput->xob; + new_ray->xerr = yinput->xerr + yinput->xob; + new_ray->xob=yinput->xob; + new_ray->yob=yinput->yob; + } + if ( yinput->xerr <= 0 && yinput->xob > 0 && yinput->yerr > 0) { + new_ray->yerr = yinput->yerr - yinput->xob; + new_ray->xerr = yinput->xerr + yinput->xob; + new_ray->xob=yinput->xob; + new_ray->yob=yinput->yob; + } +} + +static void merge_input(struct TCOD_Map *m, ray_data_t *r) { + int rayidx=r->xloc+origx+(r->yloc+origy)*m->width; + ray_data_t *xi=r->xinput; + ray_data_t *yi=r->yinput; + if ( xi ) process_x_input(r,xi); + if ( yi ) process_y_input(r,yi); + if ( ! xi ) { + if ( IS_OBSCURE(yi) ) r->ignore=true; + } else if ( ! yi ) { + if ( IS_OBSCURE(xi) ) r->ignore=true; + } else if ( IS_OBSCURE(xi) && IS_OBSCURE(yi) ) { + r->ignore=true; + } + if (! r->ignore && !m->cells[rayidx].transparent) { + r->xerr = r->xob = ABS(r->xloc); + r->yerr = r->yob = ABS(r->yloc); + } +} + +static void expandPerimeterFrom(struct TCOD_Map *m,TCOD_list_t perim,ray_data_t *r) { + if ( r->xloc >= 0 ) { + processRay(m,perim,new_ray(m,r->xloc+1,r->yloc),r); + } + if ( r->xloc <= 0 ) { + processRay(m,perim,new_ray(m,r->xloc-1,r->yloc),r); + } + if ( r->yloc >= 0 ) { + processRay(m,perim,new_ray(m,r->xloc,r->yloc+1),r); + } + if ( r->yloc <= 0 ) { + processRay(m,perim,new_ray(m,r->xloc,r->yloc-1),r); + } +} + + +void TCOD_map_compute_fov_diamond_raycasting(TCOD_map_t map, int player_x, int player_y, int max_radius, bool light_walls) { + struct TCOD_Map *m = (struct TCOD_Map *)map; + TCOD_list_t perim=TCOD_list_allocate(m->nbcells); + struct TCOD_MapCell *c; + ray_data_t **r; + int nbcells; + int r2=max_radius*max_radius; + + perimidx=0; + raymap=(ray_data_t **)calloc(sizeof(ray_data_t*),m->nbcells); + raymap2=(ray_data_t *)calloc(sizeof(ray_data_t),m->nbcells); + origx=player_x; + origy=player_y; + expandPerimeterFrom(m,perim,new_ray(m,0,0)); + while ( perimidx < TCOD_list_size(perim) ) { + ray_data_t *ray=(ray_data_t *)TCOD_list_get(perim,perimidx); + int distance = 0; + if ( r2 > 0 ) distance = ((ray->xloc * ray->xloc) + (ray->yloc * ray->yloc)); + perimidx++; + if ( distance <= r2) { + merge_input(m, ray); + if ( !ray->ignore ) expandPerimeterFrom(m,perim,ray); + } else ray->ignore=true; + } + + /* set fov data */ + c=m->cells; + r=raymap; + nbcells=m->nbcells; + while ( nbcells!= 0 ) { + if ( *r == NULL || (*r)->ignore + || ((*r)->xerr > 0 && (*r)->xerr <= (*r)->xob ) + || ((*r)->yerr > 0 && (*r)->yerr <= (*r)->yob ) + ) { + c->fov=0; + } else { + c->fov=1; + } + c++; + r++; + nbcells--; + } + m->cells[origx+origy*m->width].fov=1; + + /* light walls */ + if ( light_walls ) { + int xmin=0, ymin=0, xmax=m->width, ymax=m->height; + if ( max_radius > 0 ) { + xmin=MAX(0,player_x-max_radius); + ymin=MAX(0,player_y-max_radius); + xmax=MIN(m->width,player_x+max_radius+1); + ymax=MIN(m->height,player_y+max_radius+1); + } + TCOD_map_postproc(m,xmin,ymin,player_x,player_y,-1,-1); + TCOD_map_postproc(m,player_x,ymin,xmax-1,player_y,1,-1); + TCOD_map_postproc(m,xmin,player_y,player_x,ymax-1,-1,1); + TCOD_map_postproc(m,player_x,player_y,xmax-1,ymax-1,1,1); + } + + free(raymap); + free(raymap2); + TCOD_list_delete(perim); +} diff --git a/tcod_sys/libtcod/src/fov_permissive2.c b/tcod_sys/libtcod/src/libtcod/fov_permissive2.c similarity index 92% rename from tcod_sys/libtcod/src/fov_permissive2.c rename to tcod_sys/libtcod/src/libtcod/fov_permissive2.c index 3d9f96bc6..1551e6fb1 100644 --- a/tcod_sys/libtcod/src/fov_permissive2.c +++ b/tcod_sys/libtcod/src/libtcod/fov_permissive2.c @@ -1,256 +1,256 @@ -/* -* libtcod -* Copyright (c) 2008-2018 Jice & Mingos & rmtew -* All rights reserved. -* -* Redistribution and use in source and binary forms, with or without -* modification, are permitted provided that the following conditions are met: -* * Redistributions of source code must retain the above copyright -* notice, this list of conditions and the following disclaimer. -* * Redistributions in binary form must reproduce the above copyright -* notice, this list of conditions and the following disclaimer in the -* documentation and/or other materials provided with the distribution. -* * The name of Jice or Mingos may not be used to endorse or promote -* products derived from this software without specific prior written -* permission. -* -* THIS SOFTWARE IS PROVIDED BY JICE, MINGOS AND RMTEW ``AS IS'' AND ANY -* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED -* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE -* DISCLAIMED. IN NO EVENT SHALL JICE, MINGOS OR RMTEW BE LIABLE FOR ANY -* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES -* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; -* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND -* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS -* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. -*/ -#include - -#include -#include -#include - -#include -#include - -/* The size of each square in units */ -#define STEP_SIZE 16 - -/* Jonathon Duerig enhanced permissive FOV */ -typedef struct { - int xi,yi,xf,yf; -} line_t; - -/* Defines the parameters of the permissiveness */ -/* Derived values defining the actual part of the square used as a range. */ -static int offset; -static int limit; - -typedef struct _viewbump_t { - int x,y; - int refcount; - struct _viewbump_t *parent; -} viewbump_t; - -typedef struct { - line_t shallow_line; - line_t steep_line; - viewbump_t *shallow_bump; - viewbump_t *steep_bump; -} view_t; - -static view_t **current_view=NULL; -static view_t *views=NULL; -static viewbump_t *bumps=NULL; -static int bumpidx=0; - -#define RELATIVE_SLOPE(l,x,y) (((l)->yf-(l)->yi)*((l)->xf-(x)) - ((l)->xf-(l)->xi)*((l)->yf-(y))) -#define BELOW(l,x,y) (RELATIVE_SLOPE(l,x,y) > 0) -#define BELOW_OR_COLINEAR(l,x,y) (RELATIVE_SLOPE(l,x,y) >= 0) -#define ABOVE(l,x,y) (RELATIVE_SLOPE(l,x,y) < 0) -#define ABOVE_OR_COLINEAR(l,x,y) (RELATIVE_SLOPE(l,x,y) <= 0) -#define COLINEAR(l,x,y) (RELATIVE_SLOPE(l,x,y) == 0) -#define LINE_COLINEAR(l,l2) (COLINEAR(l,(l2)->xi,(l2)->yi) && COLINEAR(l,(l2)->xf,(l2)->yf)) - -static bool is_blocked(map_t *map, view_t *view, int startX, int startY, int x, int y, int dx, int dy, bool light_walls) { - int posx=x*dx/STEP_SIZE+startX; - int posy=y*dy/STEP_SIZE+startY; - int offset=posx + (posy)*map->width; - bool blocked=!map->cells[offset].transparent; - if (! blocked || light_walls) map->cells[offset].fov=1; - return blocked; -} - -static void add_shallow_bump(int x, int y, view_t *view) { - viewbump_t *shallow, *curbump; - view->shallow_line.xf=x; - view->shallow_line.yf=y; - shallow= &bumps[bumpidx++]; - shallow->x=x; - shallow->y=y; - shallow->parent=view->shallow_bump; - view->shallow_bump=shallow; - curbump=view->steep_bump; - while ( curbump ) { - if ( ABOVE(&view->shallow_line,curbump->x,curbump->y)) { - view->shallow_line.xi=curbump->x; - view->shallow_line.yi=curbump->y; - } - curbump=curbump->parent; - } -} - -static void add_steep_bump(int x, int y, view_t *view) { - viewbump_t *steep, *curbump; - view->steep_line.xf=x; - view->steep_line.yf=y; - steep=&bumps[bumpidx++]; - steep->x=x; - steep->y=y; - steep->parent=view->steep_bump; - view->steep_bump=steep; - curbump=view->shallow_bump; - while ( curbump ) { - if ( BELOW(&view->steep_line,curbump->x,curbump->y)) { - view->steep_line.xi=curbump->x; - view->steep_line.yi=curbump->y; - } - curbump=curbump->parent; - } -} - -static bool check_view(TCOD_list_t active_views, view_t **it) { - view_t *view=*it; - line_t *shallow_line=&view->shallow_line; - line_t *steep_line=&view->steep_line; - if (LINE_COLINEAR(shallow_line,steep_line) - && (COLINEAR(shallow_line,offset,limit) - || COLINEAR(shallow_line,limit,offset)) ){ -/*printf ("deleting view %x\n",it); */ - /* slow ! */ - TCOD_list_remove_iterator(active_views,(void **)it); - return false; - } - return true; -} - -static void visit_coords(map_t *m,int startX, int startY, int x, int y, int dx, int dy, - TCOD_list_t active_views, bool light_walls) { - /* top left */ - int tlx=x, tly=y+STEP_SIZE; - /* bottom right */ - int brx=x+STEP_SIZE, bry=y; - view_t *view=NULL; - while (current_view != (view_t **)TCOD_list_end(active_views)) { - view=*current_view; - if ( ! BELOW_OR_COLINEAR(&view->steep_line,brx,bry) ) { - break; - } - current_view++; - } - if ( current_view == (view_t **)TCOD_list_end(active_views) || ABOVE_OR_COLINEAR(&view->shallow_line,tlx,tly)) { - /* no more active view */ - return; - } - if ( !is_blocked(m,view,startX,startY,x,y,dx,dy,light_walls) ) return; - if ( ABOVE(&view->shallow_line,brx,bry) - && BELOW(&view->steep_line,tlx,tly)) { - /* view blocked */ - /* slow ! */ - TCOD_list_remove_iterator(active_views,(void **)current_view); - } else if ( ABOVE(&view->shallow_line,brx,bry)) { - /* shallow bump */ - add_shallow_bump(tlx,tly,view); - check_view(active_views,current_view); - } else if (BELOW(&view->steep_line,tlx,tly)) { - /* steep bump */ - add_steep_bump(brx,bry,view); - check_view(active_views,current_view); - } else { - /* view split */ - int offset=startX+x*dx/STEP_SIZE + (startY+y*dy/STEP_SIZE)*m->width; - view_t *shallower_view= & views[offset]; - int view_index=(int)(current_view - (view_t **)TCOD_list_begin(active_views)); - view_t **shallower_view_it; - view_t **steeper_view_it; - *shallower_view=**current_view; - /* slow ! */ - shallower_view_it = (view_t **)TCOD_list_insert_before(active_views,shallower_view,view_index); - steeper_view_it=shallower_view_it+1; - current_view=shallower_view_it; - add_steep_bump(brx,bry,shallower_view); - if (!check_view(active_views,shallower_view_it)) steeper_view_it--; - add_shallow_bump(tlx,tly,*steeper_view_it); - check_view(active_views,steeper_view_it); - if ( view_index > TCOD_list_size(active_views)) current_view=(view_t **)TCOD_list_end(active_views); - } -} - -static void check_quadrant(map_t *m,int startX,int startY,int dx, int dy, int extentX,int extentY, bool light_walls) { - TCOD_list_t active_views=TCOD_list_new(); - line_t shallow_line={offset,limit,extentX*STEP_SIZE,0}; - line_t steep_line={limit,offset,0,extentY*STEP_SIZE}; - int maxI=extentX+extentY,i=1; - view_t *view= &views[startX+startY*m->width]; - - view->shallow_line=shallow_line; - view->steep_line=steep_line; - view->shallow_bump=NULL; - view->steep_bump=NULL; - TCOD_list_push(active_views,view); - current_view=(view_t **)TCOD_list_begin(active_views); - while ( i != maxI+1 && ! TCOD_list_is_empty(active_views) ) { - int startJ=MAX(i-extentX,0); - int maxJ=MIN(i,extentY); - int j=startJ; - while ( j != maxJ+1 && ! TCOD_list_is_empty(active_views) && current_view != (view_t **)TCOD_list_end(active_views) ) { - int x=(i - j)*STEP_SIZE; - int y=j*STEP_SIZE; - visit_coords(m,startX,startY,x,y,dx,dy,active_views, light_walls); - j++; - } - i++; - current_view=(view_t **)TCOD_list_begin(active_views); - } - TCOD_list_delete(active_views); -} - -void TCOD_map_compute_fov_permissive2(TCOD_map_t map, int player_x, int player_y, int max_radius, bool light_walls, int fovType) { - int c,minx,maxx,miny,maxy; - map_t *m = (map_t *)map; - if ( (unsigned)fovType>8 ) TCOD_fatal("Bad permissiveness %d for FOV_PERMISSIVE. Accepted range is [0,8].\n",fovType); - offset=8-fovType; - limit=8+fovType; - /* clean the map */ - for (c=m->nbcells-1; c >= 0; c--) { - m->cells[c].fov=0; - } - m->cells[player_x+player_y*m->width].fov=1; - /* preallocate views and bumps */ - views=(view_t *)calloc(sizeof(view_t),m->width*m->height); - bumps=(viewbump_t *)calloc(sizeof(viewbump_t),m->width*m->height); - /* set the fov range */ - if ( max_radius > 0 ) { - minx=MIN(player_x,max_radius); - maxx=MIN(m->width-player_x-1,max_radius); - miny=MIN(player_y,max_radius); - maxy=MIN(m->height-player_y-1,max_radius); - } else { - minx=player_x; - maxx=m->width-player_x-1; - miny=player_y; - maxy=m->height-player_y-1; - } - /* calculate fov. precise permissive field of view */ - bumpidx=0; - check_quadrant(m,player_x,player_y,1,1,maxx,maxy, light_walls); - bumpidx=0; - check_quadrant(m,player_x,player_y,1,-1,maxx,miny, light_walls); - bumpidx=0; - check_quadrant(m,player_x,player_y,-1,-1,minx,miny, light_walls); - bumpidx=0; - check_quadrant(m,player_x,player_y,-1,1,minx,maxy, light_walls); - free(bumps); - free(views); -} +/* +* libtcod +* Copyright (c) 2008-2018 Jice & Mingos & rmtew +* All rights reserved. +* +* Redistribution and use in source and binary forms, with or without +* modification, are permitted provided that the following conditions are met: +* * Redistributions of source code must retain the above copyright +* notice, this list of conditions and the following disclaimer. +* * Redistributions in binary form must reproduce the above copyright +* notice, this list of conditions and the following disclaimer in the +* documentation and/or other materials provided with the distribution. +* * The name of Jice or Mingos may not be used to endorse or promote +* products derived from this software without specific prior written +* permission. +* +* THIS SOFTWARE IS PROVIDED BY JICE, MINGOS AND RMTEW ``AS IS'' AND ANY +* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED +* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE +* DISCLAIMED. IN NO EVENT SHALL JICE, MINGOS OR RMTEW BE LIABLE FOR ANY +* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES +* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; +* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND +* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS +* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +*/ +#include "fov.h" + +#include +#include +#include + +#include "libtcod_int.h" +#include "utility.h" + +/* The size of each square in units */ +#define STEP_SIZE 16 + +/* Jonathon Duerig enhanced permissive FOV */ +typedef struct { + int xi,yi,xf,yf; +} line_t; + +/* Defines the parameters of the permissiveness */ +/* Derived values defining the actual part of the square used as a range. */ +static int offset; +static int limit; + +typedef struct _viewbump_t { + int x,y; + int refcount; + struct _viewbump_t *parent; +} viewbump_t; + +typedef struct { + line_t shallow_line; + line_t steep_line; + viewbump_t *shallow_bump; + viewbump_t *steep_bump; +} view_t; + +static view_t **current_view=NULL; +static view_t *views=NULL; +static viewbump_t *bumps=NULL; +static int bumpidx=0; + +#define RELATIVE_SLOPE(l,x,y) (((l)->yf-(l)->yi)*((l)->xf-(x)) - ((l)->xf-(l)->xi)*((l)->yf-(y))) +#define BELOW(l,x,y) (RELATIVE_SLOPE(l,x,y) > 0) +#define BELOW_OR_COLINEAR(l,x,y) (RELATIVE_SLOPE(l,x,y) >= 0) +#define ABOVE(l,x,y) (RELATIVE_SLOPE(l,x,y) < 0) +#define ABOVE_OR_COLINEAR(l,x,y) (RELATIVE_SLOPE(l,x,y) <= 0) +#define COLINEAR(l,x,y) (RELATIVE_SLOPE(l,x,y) == 0) +#define LINE_COLINEAR(l,l2) (COLINEAR(l,(l2)->xi,(l2)->yi) && COLINEAR(l,(l2)->xf,(l2)->yf)) + +static bool is_blocked(struct TCOD_Map *map, view_t *view, int startX, int startY, int x, int y, int dx, int dy, bool light_walls) { + int posx=x*dx/STEP_SIZE+startX; + int posy=y*dy/STEP_SIZE+startY; + int offset=posx + (posy)*map->width; + bool blocked=!map->cells[offset].transparent; + if (! blocked || light_walls) map->cells[offset].fov=1; + return blocked; +} + +static void add_shallow_bump(int x, int y, view_t *view) { + viewbump_t *shallow, *curbump; + view->shallow_line.xf=x; + view->shallow_line.yf=y; + shallow= &bumps[bumpidx++]; + shallow->x=x; + shallow->y=y; + shallow->parent=view->shallow_bump; + view->shallow_bump=shallow; + curbump=view->steep_bump; + while ( curbump ) { + if ( ABOVE(&view->shallow_line,curbump->x,curbump->y)) { + view->shallow_line.xi=curbump->x; + view->shallow_line.yi=curbump->y; + } + curbump=curbump->parent; + } +} + +static void add_steep_bump(int x, int y, view_t *view) { + viewbump_t *steep, *curbump; + view->steep_line.xf=x; + view->steep_line.yf=y; + steep=&bumps[bumpidx++]; + steep->x=x; + steep->y=y; + steep->parent=view->steep_bump; + view->steep_bump=steep; + curbump=view->shallow_bump; + while ( curbump ) { + if ( BELOW(&view->steep_line,curbump->x,curbump->y)) { + view->steep_line.xi=curbump->x; + view->steep_line.yi=curbump->y; + } + curbump=curbump->parent; + } +} + +static bool check_view(TCOD_list_t active_views, view_t **it) { + view_t *view=*it; + line_t *shallow_line=&view->shallow_line; + line_t *steep_line=&view->steep_line; + if (LINE_COLINEAR(shallow_line,steep_line) + && (COLINEAR(shallow_line,offset,limit) + || COLINEAR(shallow_line,limit,offset)) ){ +/*printf ("deleting view %x\n",it); */ + /* slow ! */ + TCOD_list_remove_iterator(active_views,(void **)it); + return false; + } + return true; +} + +static void visit_coords(struct TCOD_Map *m,int startX, int startY, int x, int y, int dx, int dy, + TCOD_list_t active_views, bool light_walls) { + /* top left */ + int tlx=x, tly=y+STEP_SIZE; + /* bottom right */ + int brx=x+STEP_SIZE, bry=y; + view_t *view=NULL; + while (current_view != (view_t **)TCOD_list_end(active_views)) { + view=*current_view; + if ( ! BELOW_OR_COLINEAR(&view->steep_line,brx,bry) ) { + break; + } + current_view++; + } + if ( current_view == (view_t **)TCOD_list_end(active_views) || ABOVE_OR_COLINEAR(&view->shallow_line,tlx,tly)) { + /* no more active view */ + return; + } + if ( !is_blocked(m,view,startX,startY,x,y,dx,dy,light_walls) ) return; + if ( ABOVE(&view->shallow_line,brx,bry) + && BELOW(&view->steep_line,tlx,tly)) { + /* view blocked */ + /* slow ! */ + TCOD_list_remove_iterator(active_views,(void **)current_view); + } else if ( ABOVE(&view->shallow_line,brx,bry)) { + /* shallow bump */ + add_shallow_bump(tlx,tly,view); + check_view(active_views,current_view); + } else if (BELOW(&view->steep_line,tlx,tly)) { + /* steep bump */ + add_steep_bump(brx,bry,view); + check_view(active_views,current_view); + } else { + /* view split */ + int offset=startX+x*dx/STEP_SIZE + (startY+y*dy/STEP_SIZE)*m->width; + view_t *shallower_view= & views[offset]; + int view_index=(int)(current_view - (view_t **)TCOD_list_begin(active_views)); + view_t **shallower_view_it; + view_t **steeper_view_it; + *shallower_view=**current_view; + /* slow ! */ + shallower_view_it = (view_t **)TCOD_list_insert_before(active_views,shallower_view,view_index); + steeper_view_it=shallower_view_it+1; + current_view=shallower_view_it; + add_steep_bump(brx,bry,shallower_view); + if (!check_view(active_views,shallower_view_it)) steeper_view_it--; + add_shallow_bump(tlx,tly,*steeper_view_it); + check_view(active_views,steeper_view_it); + if ( view_index > TCOD_list_size(active_views)) current_view=(view_t **)TCOD_list_end(active_views); + } +} + +static void check_quadrant(struct TCOD_Map *m,int startX,int startY,int dx, int dy, int extentX,int extentY, bool light_walls) { + TCOD_list_t active_views=TCOD_list_new(); + line_t shallow_line={offset,limit,extentX*STEP_SIZE,0}; + line_t steep_line={limit,offset,0,extentY*STEP_SIZE}; + int maxI=extentX+extentY,i=1; + view_t *view= &views[startX+startY*m->width]; + + view->shallow_line=shallow_line; + view->steep_line=steep_line; + view->shallow_bump=NULL; + view->steep_bump=NULL; + TCOD_list_push(active_views,view); + current_view=(view_t **)TCOD_list_begin(active_views); + while ( i != maxI+1 && ! TCOD_list_is_empty(active_views) ) { + int startJ=MAX(i-extentX,0); + int maxJ=MIN(i,extentY); + int j=startJ; + while ( j != maxJ+1 && ! TCOD_list_is_empty(active_views) && current_view != (view_t **)TCOD_list_end(active_views) ) { + int x=(i - j)*STEP_SIZE; + int y=j*STEP_SIZE; + visit_coords(m,startX,startY,x,y,dx,dy,active_views, light_walls); + j++; + } + i++; + current_view=(view_t **)TCOD_list_begin(active_views); + } + TCOD_list_delete(active_views); +} + +void TCOD_map_compute_fov_permissive2(TCOD_map_t map, int player_x, int player_y, int max_radius, bool light_walls, int fovType) { + int c,minx,maxx,miny,maxy; + struct TCOD_Map *m = (struct TCOD_Map *)map; + if ( (unsigned)fovType>8 ) TCOD_fatal("Bad permissiveness %d for FOV_PERMISSIVE. Accepted range is [0,8].\n",fovType); + offset=8-fovType; + limit=8+fovType; + /* clean the map */ + for (c=m->nbcells-1; c >= 0; c--) { + m->cells[c].fov=0; + } + m->cells[player_x+player_y*m->width].fov=1; + /* preallocate views and bumps */ + views=(view_t *)calloc(sizeof(view_t),m->width*m->height); + bumps=(viewbump_t *)calloc(sizeof(viewbump_t),m->width*m->height); + /* set the fov range */ + if ( max_radius > 0 ) { + minx=MIN(player_x,max_radius); + maxx=MIN(m->width-player_x-1,max_radius); + miny=MIN(player_y,max_radius); + maxy=MIN(m->height-player_y-1,max_radius); + } else { + minx=player_x; + maxx=m->width-player_x-1; + miny=player_y; + maxy=m->height-player_y-1; + } + /* calculate fov. precise permissive field of view */ + bumpidx=0; + check_quadrant(m,player_x,player_y,1,1,maxx,maxy, light_walls); + bumpidx=0; + check_quadrant(m,player_x,player_y,1,-1,maxx,miny, light_walls); + bumpidx=0; + check_quadrant(m,player_x,player_y,-1,-1,minx,miny, light_walls); + bumpidx=0; + check_quadrant(m,player_x,player_y,-1,1,minx,maxy, light_walls); + free(bumps); + free(views); +} diff --git a/tcod_sys/libtcod/src/fov_recursive_shadowcasting.c b/tcod_sys/libtcod/src/libtcod/fov_recursive_shadowcasting.c similarity index 92% rename from tcod_sys/libtcod/src/fov_recursive_shadowcasting.c rename to tcod_sys/libtcod/src/libtcod/fov_recursive_shadowcasting.c index 2814e9652..7d772ca0a 100644 --- a/tcod_sys/libtcod/src/fov_recursive_shadowcasting.c +++ b/tcod_sys/libtcod/src/libtcod/fov_recursive_shadowcasting.c @@ -1,108 +1,108 @@ -/* -* libtcod -* Copyright (c) 2008-2018 Jice & Mingos & rmtew -* All rights reserved. -* -* Redistribution and use in source and binary forms, with or without -* modification, are permitted provided that the following conditions are met: -* * Redistributions of source code must retain the above copyright -* notice, this list of conditions and the following disclaimer. -* * Redistributions in binary form must reproduce the above copyright -* notice, this list of conditions and the following disclaimer in the -* documentation and/or other materials provided with the distribution. -* * The name of Jice or Mingos may not be used to endorse or promote -* products derived from this software without specific prior written -* permission. -* -* THIS SOFTWARE IS PROVIDED BY JICE, MINGOS AND RMTEW ``AS IS'' AND ANY -* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED -* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE -* DISCLAIMED. IN NO EVENT SHALL JICE, MINGOS OR RMTEW BE LIABLE FOR ANY -* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES -* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; -* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND -* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS -* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. -*/ -#include - -#include -#include -#include - -#include -#include - -static int mult[4][8]= { - {1,0,0,-1,-1,0,0,1}, - {0,1,-1,0,0,-1,1,0}, - {0,1,1,0,0,-1,-1,0}, - {1,0,0,1,-1,0,0,-1}, -}; - -static void cast_light(map_t *map,int cx, int cy,int row,float start, float end, int radius, int r2, - int xx, int xy, int yx, int yy, int id, bool light_walls) { - int j; - float new_start=0.0f; - if ( start < end ) return; - for (j=row; j< radius+1; j++) { - int dx=-j-1; - int dy=-j; - bool blocked=false; - while ( dx <= 0 ) { - int X,Y; - dx++; - X=cx+dx*xx+dy*xy; - Y=cy+dx*yx+dy*yy; - if ((unsigned)X < (unsigned)map->width && (unsigned)Y < (unsigned)map->height) { - float l_slope,r_slope; - int offset; - offset=X+Y*map->width; - l_slope=(dx-0.5f)/(dy+0.5f); - r_slope=(dx+0.5f)/(dy-0.5f); - if( start < r_slope ) continue; - else if( end > l_slope ) break; - if ( dx*dx+dy*dy <= r2 - && (light_walls || map->cells[offset].transparent)) map->cells[offset].fov=1; - if ( blocked ) { - if (!map->cells[offset].transparent) { - new_start=r_slope; - continue; - } else { - blocked=false; - start=new_start; - } - } else { - if (!map->cells[offset].transparent && j < radius ) { - blocked=true; - cast_light(map,cx,cy,j+1,start,l_slope,radius,r2,xx,xy,yx,yy,id+1,light_walls); - new_start=r_slope; - } - } - } - } - if ( blocked ) break; - } -} - -void TCOD_map_compute_fov_recursive_shadowcasting(TCOD_map_t map, int player_x, int player_y, int max_radius, bool light_walls) { - int oct,c,r2; - map_t *m = (map_t *)map; - /* clean the map */ - for (c=m->nbcells-1; c >= 0; c--) { - m->cells[c].fov=0; - } - if ( max_radius == 0 ) { - int max_radius_x=m->width-player_x; - int max_radius_y=m->height-player_y; - max_radius_x=MAX(max_radius_x,player_x); - max_radius_y=MAX(max_radius_y,player_y); - max_radius = (int)(sqrt(max_radius_x*max_radius_x+max_radius_y*max_radius_y))+1; - } - r2=max_radius*max_radius; - /* recursive shadow casting */ - for (oct=0; oct < 8; oct++) cast_light(m,player_x,player_y,1,1.0,0.0,max_radius,r2, - mult[0][oct],mult[1][oct],mult[2][oct],mult[3][oct],0,light_walls); - m->cells[player_x+player_y*m->width].fov=1; -} +/* +* libtcod +* Copyright (c) 2008-2018 Jice & Mingos & rmtew +* All rights reserved. +* +* Redistribution and use in source and binary forms, with or without +* modification, are permitted provided that the following conditions are met: +* * Redistributions of source code must retain the above copyright +* notice, this list of conditions and the following disclaimer. +* * Redistributions in binary form must reproduce the above copyright +* notice, this list of conditions and the following disclaimer in the +* documentation and/or other materials provided with the distribution. +* * The name of Jice or Mingos may not be used to endorse or promote +* products derived from this software without specific prior written +* permission. +* +* THIS SOFTWARE IS PROVIDED BY JICE, MINGOS AND RMTEW ``AS IS'' AND ANY +* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED +* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE +* DISCLAIMED. IN NO EVENT SHALL JICE, MINGOS OR RMTEW BE LIABLE FOR ANY +* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES +* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; +* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND +* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS +* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +*/ +#include "fov.h" + +#include +#include +#include + +#include "libtcod_int.h" +#include "utility.h" + +static int mult[4][8]= { + {1,0,0,-1,-1,0,0,1}, + {0,1,-1,0,0,-1,1,0}, + {0,1,1,0,0,-1,-1,0}, + {1,0,0,1,-1,0,0,-1}, +}; + +static void cast_light(struct TCOD_Map *map,int cx, int cy,int row,float start, float end, int radius, int r2, + int xx, int xy, int yx, int yy, int id, bool light_walls) { + int j; + float new_start=0.0f; + if ( start < end ) return; + for (j=row; j< radius+1; j++) { + int dx=-j-1; + int dy=-j; + bool blocked=false; + while ( dx <= 0 ) { + int X,Y; + dx++; + X=cx+dx*xx+dy*xy; + Y=cy+dx*yx+dy*yy; + if ((unsigned)X < (unsigned)map->width && (unsigned)Y < (unsigned)map->height) { + float l_slope,r_slope; + int offset; + offset=X+Y*map->width; + l_slope=(dx-0.5f)/(dy+0.5f); + r_slope=(dx+0.5f)/(dy-0.5f); + if( start < r_slope ) continue; + else if( end > l_slope ) break; + if ( dx*dx+dy*dy <= r2 + && (light_walls || map->cells[offset].transparent)) map->cells[offset].fov=1; + if ( blocked ) { + if (!map->cells[offset].transparent) { + new_start=r_slope; + continue; + } else { + blocked=false; + start=new_start; + } + } else { + if (!map->cells[offset].transparent && j < radius ) { + blocked=true; + cast_light(map,cx,cy,j+1,start,l_slope,radius,r2,xx,xy,yx,yy,id+1,light_walls); + new_start=r_slope; + } + } + } + } + if ( blocked ) break; + } +} + +void TCOD_map_compute_fov_recursive_shadowcasting(TCOD_map_t map, int player_x, int player_y, int max_radius, bool light_walls) { + int oct,c,r2; + struct TCOD_Map *m = (struct TCOD_Map *)map; + /* clean the map */ + for (c=m->nbcells-1; c >= 0; c--) { + m->cells[c].fov=0; + } + if ( max_radius == 0 ) { + int max_radius_x=m->width-player_x; + int max_radius_y=m->height-player_y; + max_radius_x=MAX(max_radius_x,player_x); + max_radius_y=MAX(max_radius_y,player_y); + max_radius = (int)(sqrt(max_radius_x*max_radius_x+max_radius_y*max_radius_y))+1; + } + r2=max_radius*max_radius; + /* recursive shadow casting */ + for (oct=0; oct < 8; oct++) cast_light(m,player_x,player_y,1,1.0,0.0,max_radius,r2, + mult[0][oct],mult[1][oct],mult[2][oct],mult[3][oct],0,light_walls); + m->cells[player_x+player_y*m->width].fov=1; +} diff --git a/tcod_sys/libtcod/src/fov_restrictive.c b/tcod_sys/libtcod/src/libtcod/fov_restrictive.c similarity index 94% rename from tcod_sys/libtcod/src/fov_restrictive.c rename to tcod_sys/libtcod/src/libtcod/fov_restrictive.c index 277484fc1..5cf1b2540 100644 --- a/tcod_sys/libtcod/src/fov_restrictive.c +++ b/tcod_sys/libtcod/src/libtcod/fov_restrictive.c @@ -1,295 +1,295 @@ -/* -* libtcod -* Copyright (c) 2008-2018 Jice & Mingos & rmtew -* All rights reserved. -* -* Redistribution and use in source and binary forms, with or without -* modification, are permitted provided that the following conditions are met: -* * Redistributions of source code must retain the above copyright -* notice, this list of conditions and the following disclaimer. -* * Redistributions in binary form must reproduce the above copyright -* notice, this list of conditions and the following disclaimer in the -* documentation and/or other materials provided with the distribution. -* * The name of Jice or Mingos may not be used to endorse or promote -* products derived from this software without specific prior written -* permission. -* -* THIS SOFTWARE IS PROVIDED BY JICE, MINGOS AND RMTEW ``AS IS'' AND ANY -* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED -* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE -* DISCLAIMED. IN NO EVENT SHALL JICE, MINGOS OR RMTEW BE LIABLE FOR ANY -* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES -* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; -* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND -* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS -* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. -*/ -/* -* Mingos' Restrictive Precise Angle Shadowcasting (MRPAS) v1.2 -*/ -#include - -#include /* for NULL in VS */ - -#include -#include - -/* angle ranges */ -double * start_angle = NULL; -double * end_angle = NULL; -/* number of allocated angle pairs */ -int allocated = 0; - -void TCOD_map_compute_fov_restrictive_shadowcasting_quadrant (map_t *m, int player_x, int player_y, int max_radius, bool light_walls, int dx, int dy) { - /* octant: vertical edge */ - { - int iteration = 1; /* iteration of the algo for this octant */ - bool done = false; - int total_obstacles = 0; - int obstacles_in_last_line = 0; - double min_angle = 0.0; - int x; - int y; - - /* do while there are unblocked slopes left and the algo is within the map's boundaries - scan progressive lines/columns from the PC outwards */ - y = player_y+dy; /* the outer slope's coordinates (first processed line) */ - if (y < 0 || y >= m->height) { - done = true; - } - while (!done) { - /* process cells in the line */ - double slopes_per_cell = 1.0 / (double)(iteration); - double half_slopes = slopes_per_cell * 0.5; - int processed_cell = (int)((min_angle + half_slopes) / slopes_per_cell); - int minx = MAX(0, player_x - iteration); - int maxx = MIN(m->width - 1, player_x + iteration); - done = true; - for (x = player_x + (processed_cell * dx); x >= minx && x <= maxx; x+=dx) { - int c = x + (y * m->width); - /* calculate slopes per cell */ - bool visible = true; - bool extended = false; - double centre_slope = (double)processed_cell * slopes_per_cell; - double start_slope = centre_slope - half_slopes; - double end_slope = centre_slope + half_slopes; - if (obstacles_in_last_line > 0) { - if ( - !( - m->cells[c-(m->width * dy)].fov && - m->cells[c-(m->width * dy)].transparent - ) && - !( - m->cells[c-(m->width * dy) - dx].fov && - m->cells[c-(m->width * dy) - dx].transparent - ) - ) { - visible = false; - } else { - int idx; - for (idx = 0; idx < obstacles_in_last_line && visible; ++idx) { - if ( - start_slope <= end_angle[idx] && - end_slope >= start_angle[idx] - ) { - if (m->cells[c].transparent) { - if ( - centre_slope > start_angle[idx] && - centre_slope < end_angle[idx] - ) { - visible = false; - } - } else { - if ( - start_slope >= start_angle[idx] && - end_slope <= end_angle[idx] - ) { - visible = false; - } else { - start_angle[idx] = MIN(start_angle[idx], start_slope); - end_angle[idx] = MAX(end_angle[idx], end_slope); - extended = true; - } - } - } - } - } - } - if (visible) { - done = false; - m->cells[c].fov = true; - /* if the cell is opaque, block the adjacent slopes */ - if (!m->cells[c].transparent) { - if (min_angle >= start_slope) { - min_angle = end_slope; - /* if min_angle is applied to the last cell in line, nothing more - needs to be checked. */ - if (processed_cell == iteration) { - done = true; - } - } else if (!extended) { - start_angle[total_obstacles] = start_slope; - end_angle[total_obstacles++] = end_slope; - } - if (!light_walls) { - m->cells[c].fov = false; - } - } - } - processed_cell++; - } - if (iteration == max_radius) { - done = true; - } - iteration++; - obstacles_in_last_line = total_obstacles; - y += dy; - if (y < 0 || y >= m->height) { - done = true; - } - } - } - - /* octant: horizontal edge */ - { - int iteration = 1; /* iteration of the algo for this octant */ - bool done = false; - int total_obstacles = 0; - int obstacles_in_last_line = 0; - double min_angle = 0.0; - int x; - int y; - - /* do while there are unblocked slopes left and the algo is within the map's boundaries - scan progressive lines/columns from the PC outwards */ - x = player_x+dx; /*the outer slope's coordinates (first processed line) */ - if (x < 0 || x >= m->width) { - done = true; - } - while (!done) { - /* process cells in the line */ - double slopes_per_cell = 1.0 / (double)(iteration); - double half_slopes = slopes_per_cell * 0.5; - int processed_cell = (int)((min_angle + half_slopes) / slopes_per_cell); - int miny = MAX(0, player_y - iteration); - int maxy = MIN(m->height - 1, player_y + iteration); - done = true; - for (y = player_y + (processed_cell * dy); y >= miny && y <= maxy; y += dy) { - int c = x + (y * m->width); - /* calculate slopes per cell */ - bool visible = true; - bool extended = false; - double centre_slope = (double)processed_cell * slopes_per_cell; - double start_slope = centre_slope - half_slopes; - double end_slope = centre_slope + half_slopes; - if (obstacles_in_last_line > 0) { - if ( - !( - m->cells[c-dx].fov && - m->cells[c-dx].transparent - ) && - !( - m->cells[c-(m->width * dy) - dx].fov && - m->cells[c-(m->width * dy) - dx].transparent - ) - ) { - visible = false; - } else { - int idx; - for (idx = 0; idx < obstacles_in_last_line && visible; ++idx) { - if ( - start_slope <= end_angle[idx] && - end_slope >= start_angle[idx] - ) { - if (m->cells[c].transparent) { - if ( - centre_slope > start_angle[idx] && - centre_slope < end_angle[idx] - ) { - visible = false; - } - } else { - if ( - start_slope >= start_angle[idx] && - end_slope <= end_angle[idx] - ) { - visible = false; - } else { - start_angle[idx] = MIN(start_angle[idx], start_slope); - end_angle[idx] = MAX(end_angle[idx], end_slope); - extended = true; - } - } - ++idx; - } - } - } - } - if (visible) { - done = false; - m->cells[c].fov = true; - /* if the cell is opaque, block the adjacent slopes */ - if (!m->cells[c].transparent) { - if (min_angle >= start_slope) { - min_angle = end_slope; - /* if min_angle is applied to the last cell in line, nothing more - needs to be checked. */ - if (processed_cell == iteration) { - done = true; - } - } else if (!extended) { - start_angle[total_obstacles] = start_slope; - end_angle[total_obstacles++] = end_slope; - } - if (!light_walls) { - m->cells[c].fov = false; - } - } - } - processed_cell++; - } - if (iteration == max_radius) { - done = true; - } - iteration++; - obstacles_in_last_line = total_obstacles; - x += dx; - if (x < 0 || x >= m->width) { - done = true; - } - } - } -} - -void TCOD_map_compute_fov_restrictive_shadowcasting(TCOD_map_t map, int player_x, int player_y, int max_radius, bool light_walls) { - map_t *m = (map_t *)map; - int max_obstacles; - int c; - - /* first, zero the FOV map */ - for(c = m->nbcells - 1; c >= 0; c--) { - m->cells[c].fov = false; - } - - /* calculate an approximated (excessive, just in case) maximum number of obstacles per octant */ - max_obstacles = m->nbcells / 7; - - /* check memory for angles */ - if (max_obstacles > allocated) { - allocated = max_obstacles; - if (start_angle != NULL) free(start_angle); - if (end_angle != NULL) free(end_angle); - start_angle = (double*)calloc(max_obstacles, sizeof(double)); - end_angle = (double*)calloc(max_obstacles, sizeof(double)); - } - - /* set PC's position as visible */ - m->cells[player_x+(player_y*m->width)].fov = true; - - /* compute the 4 quadrants of the map */ - TCOD_map_compute_fov_restrictive_shadowcasting_quadrant (m, player_x, player_y, max_radius, light_walls, 1, 1); - TCOD_map_compute_fov_restrictive_shadowcasting_quadrant (m, player_x, player_y, max_radius, light_walls, 1, -1); - TCOD_map_compute_fov_restrictive_shadowcasting_quadrant (m, player_x, player_y, max_radius, light_walls, -1, 1); - TCOD_map_compute_fov_restrictive_shadowcasting_quadrant (m, player_x, player_y, max_radius, light_walls, -1, -1); -} +/* +* libtcod +* Copyright (c) 2008-2018 Jice & Mingos & rmtew +* All rights reserved. +* +* Redistribution and use in source and binary forms, with or without +* modification, are permitted provided that the following conditions are met: +* * Redistributions of source code must retain the above copyright +* notice, this list of conditions and the following disclaimer. +* * Redistributions in binary form must reproduce the above copyright +* notice, this list of conditions and the following disclaimer in the +* documentation and/or other materials provided with the distribution. +* * The name of Jice or Mingos may not be used to endorse or promote +* products derived from this software without specific prior written +* permission. +* +* THIS SOFTWARE IS PROVIDED BY JICE, MINGOS AND RMTEW ``AS IS'' AND ANY +* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED +* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE +* DISCLAIMED. IN NO EVENT SHALL JICE, MINGOS OR RMTEW BE LIABLE FOR ANY +* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES +* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; +* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND +* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS +* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +*/ +/* +* Mingos' Restrictive Precise Angle Shadowcasting (MRPAS) v1.2 +*/ +#include "fov.h" + +#include /* for NULL in VS */ + +#include "libtcod_int.h" +#include "utility.h" + +/* angle ranges */ +double * start_angle = NULL; +double * end_angle = NULL; +/* number of allocated angle pairs */ +int allocated = 0; + +void TCOD_map_compute_fov_restrictive_shadowcasting_quadrant (struct TCOD_Map *m, int player_x, int player_y, int max_radius, bool light_walls, int dx, int dy) { + /* octant: vertical edge */ + { + int iteration = 1; /* iteration of the algo for this octant */ + bool done = false; + int total_obstacles = 0; + int obstacles_in_last_line = 0; + double min_angle = 0.0; + int x; + int y; + + /* do while there are unblocked slopes left and the algo is within the map's boundaries + scan progressive lines/columns from the PC outwards */ + y = player_y+dy; /* the outer slope's coordinates (first processed line) */ + if (y < 0 || y >= m->height) { + done = true; + } + while (!done) { + /* process cells in the line */ + double slopes_per_cell = 1.0 / (double)(iteration); + double half_slopes = slopes_per_cell * 0.5; + int processed_cell = (int)((min_angle + half_slopes) / slopes_per_cell); + int minx = MAX(0, player_x - iteration); + int maxx = MIN(m->width - 1, player_x + iteration); + done = true; + for (x = player_x + (processed_cell * dx); x >= minx && x <= maxx; x+=dx) { + int c = x + (y * m->width); + /* calculate slopes per cell */ + bool visible = true; + bool extended = false; + double centre_slope = (double)processed_cell * slopes_per_cell; + double start_slope = centre_slope - half_slopes; + double end_slope = centre_slope + half_slopes; + if (obstacles_in_last_line > 0) { + if ( + !( + m->cells[c-(m->width * dy)].fov && + m->cells[c-(m->width * dy)].transparent + ) && + !( + m->cells[c-(m->width * dy) - dx].fov && + m->cells[c-(m->width * dy) - dx].transparent + ) + ) { + visible = false; + } else { + int idx; + for (idx = 0; idx < obstacles_in_last_line && visible; ++idx) { + if ( + start_slope <= end_angle[idx] && + end_slope >= start_angle[idx] + ) { + if (m->cells[c].transparent) { + if ( + centre_slope > start_angle[idx] && + centre_slope < end_angle[idx] + ) { + visible = false; + } + } else { + if ( + start_slope >= start_angle[idx] && + end_slope <= end_angle[idx] + ) { + visible = false; + } else { + start_angle[idx] = MIN(start_angle[idx], start_slope); + end_angle[idx] = MAX(end_angle[idx], end_slope); + extended = true; + } + } + } + } + } + } + if (visible) { + done = false; + m->cells[c].fov = true; + /* if the cell is opaque, block the adjacent slopes */ + if (!m->cells[c].transparent) { + if (min_angle >= start_slope) { + min_angle = end_slope; + /* if min_angle is applied to the last cell in line, nothing more + needs to be checked. */ + if (processed_cell == iteration) { + done = true; + } + } else if (!extended) { + start_angle[total_obstacles] = start_slope; + end_angle[total_obstacles++] = end_slope; + } + if (!light_walls) { + m->cells[c].fov = false; + } + } + } + processed_cell++; + } + if (iteration == max_radius) { + done = true; + } + iteration++; + obstacles_in_last_line = total_obstacles; + y += dy; + if (y < 0 || y >= m->height) { + done = true; + } + } + } + + /* octant: horizontal edge */ + { + int iteration = 1; /* iteration of the algo for this octant */ + bool done = false; + int total_obstacles = 0; + int obstacles_in_last_line = 0; + double min_angle = 0.0; + int x; + int y; + + /* do while there are unblocked slopes left and the algo is within the map's boundaries + scan progressive lines/columns from the PC outwards */ + x = player_x+dx; /*the outer slope's coordinates (first processed line) */ + if (x < 0 || x >= m->width) { + done = true; + } + while (!done) { + /* process cells in the line */ + double slopes_per_cell = 1.0 / (double)(iteration); + double half_slopes = slopes_per_cell * 0.5; + int processed_cell = (int)((min_angle + half_slopes) / slopes_per_cell); + int miny = MAX(0, player_y - iteration); + int maxy = MIN(m->height - 1, player_y + iteration); + done = true; + for (y = player_y + (processed_cell * dy); y >= miny && y <= maxy; y += dy) { + int c = x + (y * m->width); + /* calculate slopes per cell */ + bool visible = true; + bool extended = false; + double centre_slope = (double)processed_cell * slopes_per_cell; + double start_slope = centre_slope - half_slopes; + double end_slope = centre_slope + half_slopes; + if (obstacles_in_last_line > 0) { + if ( + !( + m->cells[c-dx].fov && + m->cells[c-dx].transparent + ) && + !( + m->cells[c-(m->width * dy) - dx].fov && + m->cells[c-(m->width * dy) - dx].transparent + ) + ) { + visible = false; + } else { + int idx; + for (idx = 0; idx < obstacles_in_last_line && visible; ++idx) { + if ( + start_slope <= end_angle[idx] && + end_slope >= start_angle[idx] + ) { + if (m->cells[c].transparent) { + if ( + centre_slope > start_angle[idx] && + centre_slope < end_angle[idx] + ) { + visible = false; + } + } else { + if ( + start_slope >= start_angle[idx] && + end_slope <= end_angle[idx] + ) { + visible = false; + } else { + start_angle[idx] = MIN(start_angle[idx], start_slope); + end_angle[idx] = MAX(end_angle[idx], end_slope); + extended = true; + } + } + ++idx; + } + } + } + } + if (visible) { + done = false; + m->cells[c].fov = true; + /* if the cell is opaque, block the adjacent slopes */ + if (!m->cells[c].transparent) { + if (min_angle >= start_slope) { + min_angle = end_slope; + /* if min_angle is applied to the last cell in line, nothing more + needs to be checked. */ + if (processed_cell == iteration) { + done = true; + } + } else if (!extended) { + start_angle[total_obstacles] = start_slope; + end_angle[total_obstacles++] = end_slope; + } + if (!light_walls) { + m->cells[c].fov = false; + } + } + } + processed_cell++; + } + if (iteration == max_radius) { + done = true; + } + iteration++; + obstacles_in_last_line = total_obstacles; + x += dx; + if (x < 0 || x >= m->width) { + done = true; + } + } + } +} + +void TCOD_map_compute_fov_restrictive_shadowcasting(TCOD_map_t map, int player_x, int player_y, int max_radius, bool light_walls) { + struct TCOD_Map *m = (struct TCOD_Map *)map; + int max_obstacles; + int c; + + /* first, zero the FOV map */ + for(c = m->nbcells - 1; c >= 0; c--) { + m->cells[c].fov = false; + } + + /* calculate an approximated (excessive, just in case) maximum number of obstacles per octant */ + max_obstacles = m->nbcells / 7; + + /* check memory for angles */ + if (max_obstacles > allocated) { + allocated = max_obstacles; + if (start_angle != NULL) free(start_angle); + if (end_angle != NULL) free(end_angle); + start_angle = (double*)calloc(max_obstacles, sizeof(double)); + end_angle = (double*)calloc(max_obstacles, sizeof(double)); + } + + /* set PC's position as visible */ + m->cells[player_x+(player_y*m->width)].fov = true; + + /* compute the 4 quadrants of the map */ + TCOD_map_compute_fov_restrictive_shadowcasting_quadrant (m, player_x, player_y, max_radius, light_walls, 1, 1); + TCOD_map_compute_fov_restrictive_shadowcasting_quadrant (m, player_x, player_y, max_radius, light_walls, 1, -1); + TCOD_map_compute_fov_restrictive_shadowcasting_quadrant (m, player_x, player_y, max_radius, light_walls, -1, 1); + TCOD_map_compute_fov_restrictive_shadowcasting_quadrant (m, player_x, player_y, max_radius, light_walls, -1, -1); +} diff --git a/tcod_sys/libtcod/include/fov_types.h b/tcod_sys/libtcod/src/libtcod/fov_types.h similarity index 57% rename from tcod_sys/libtcod/include/fov_types.h rename to tcod_sys/libtcod/src/libtcod/fov_types.h index 200464788..fd25d8c2c 100644 --- a/tcod_sys/libtcod/include/fov_types.h +++ b/tcod_sys/libtcod/src/libtcod/fov_types.h @@ -1,62 +1,83 @@ -/* -* libtcod -* Copyright (c) 2008-2018 Jice & Mingos & rmtew -* All rights reserved. -* -* Redistribution and use in source and binary forms, with or without -* modification, are permitted provided that the following conditions are met: -* * Redistributions of source code must retain the above copyright -* notice, this list of conditions and the following disclaimer. -* * Redistributions in binary form must reproduce the above copyright -* notice, this list of conditions and the following disclaimer in the -* documentation and/or other materials provided with the distribution. -* * The name of Jice or Mingos may not be used to endorse or promote -* products derived from this software without specific prior written -* permission. -* -* THIS SOFTWARE IS PROVIDED BY JICE, MINGOS AND RMTEW ``AS IS'' AND ANY -* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED -* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE -* DISCLAIMED. IN NO EVENT SHALL JICE, MINGOS OR RMTEW BE LIABLE FOR ANY -* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES -* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; -* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND -* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS -* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. -*/ -#ifndef _TCOD_FOV_TYPES_H -#define _TCOD_FOV_TYPES_H - -#ifdef __cplusplus -extern "C" { -#endif -typedef void *TCOD_map_t; - -/* FOV_BASIC : http://roguebasin.roguelikedevelopment.org/index.php?title=Ray_casting - FOV_DIAMOND : http://www.geocities.com/temerra/los_rays.html - FOV_SHADOW : http://roguebasin.roguelikedevelopment.org/index.php?title=FOV_using_recursive_shadowcasting - FOV_PERMISSIVE : http://roguebasin.roguelikedevelopment.org/index.php?title=Precise_Permissive_Field_of_View - FOV_RESTRICTIVE : Mingos' Restrictive Precise Angle Shadowcasting (contribution by Mingos) */ - -typedef enum { - FOV_BASIC, - FOV_DIAMOND, - FOV_SHADOW, - FOV_PERMISSIVE_0, - FOV_PERMISSIVE_1, - FOV_PERMISSIVE_2, - FOV_PERMISSIVE_3, - FOV_PERMISSIVE_4, - FOV_PERMISSIVE_5, - FOV_PERMISSIVE_6, - FOV_PERMISSIVE_7, - FOV_PERMISSIVE_8, - FOV_RESTRICTIVE, - NB_FOV_ALGORITHMS } TCOD_fov_algorithm_t; -#define FOV_PERMISSIVE(x) ((TCOD_fov_algorithm_t)(FOV_PERMISSIVE_0 + (x))) - -#ifdef __cplusplus -} -#endif -#endif /* _TCOD_FOV_TYPES_H */ +/* +* libtcod +* Copyright (c) 2008-2018 Jice & Mingos & rmtew +* All rights reserved. +* +* Redistribution and use in source and binary forms, with or without +* modification, are permitted provided that the following conditions are met: +* * Redistributions of source code must retain the above copyright +* notice, this list of conditions and the following disclaimer. +* * Redistributions in binary form must reproduce the above copyright +* notice, this list of conditions and the following disclaimer in the +* documentation and/or other materials provided with the distribution. +* * The name of Jice or Mingos may not be used to endorse or promote +* products derived from this software without specific prior written +* permission. +* +* THIS SOFTWARE IS PROVIDED BY JICE, MINGOS AND RMTEW ``AS IS'' AND ANY +* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED +* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE +* DISCLAIMED. IN NO EVENT SHALL JICE, MINGOS OR RMTEW BE LIABLE FOR ANY +* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES +* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; +* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND +* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS +* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +*/ +#ifndef TCOD_FOV_TYPES_H_ +#define TCOD_FOV_TYPES_H_ +#include "portability.h" +/** + * Private map cell struct. + */ +struct TCOD_MapCell { + bool transparent; + bool walkable; + bool fov; +}; +/** + * Private map struct. + */ +typedef struct TCOD_Map { + int width; + int height; + int nbcells; + struct TCOD_MapCell *cells; +} TCOD_Map; +typedef TCOD_Map *TCOD_map_t; +/** + * Field-of-view options. + */ +typedef enum { + /** + * Basic: http://roguebasin.roguelikedevelopment.org/index.php?title=Ray_casting + */ + FOV_BASIC, + /** + * Diamond: http://www.geocities.com/temerra/los_rays.html + */ + FOV_DIAMOND, + /** + * Shadow casting: http://roguebasin.roguelikedevelopment.org/index.php?title=FOV_using_recursive_shadowcasting + */ + FOV_SHADOW, + /** + * Permissive: http://roguebasin.roguelikedevelopment.org/index.php?title=Precise_Permissive_Field_of_View + */ + FOV_PERMISSIVE_0, + FOV_PERMISSIVE_1, + FOV_PERMISSIVE_2, + FOV_PERMISSIVE_3, + FOV_PERMISSIVE_4, + FOV_PERMISSIVE_5, + FOV_PERMISSIVE_6, + FOV_PERMISSIVE_7, + FOV_PERMISSIVE_8, + /** + * Mingos' Restrictive Precise Angle Shadowcasting (contribution by Mingos) + */ + FOV_RESTRICTIVE, + NB_FOV_ALGORITHMS } TCOD_fov_algorithm_t; +#define FOV_PERMISSIVE(x) ((TCOD_fov_algorithm_t)(FOV_PERMISSIVE_0 + (x))) +#endif /* TCOD_FOV_TYPES_H_ */ diff --git a/tcod_sys/libtcod/src/gui/README.txt b/tcod_sys/libtcod/src/libtcod/gui/README.txt similarity index 100% rename from tcod_sys/libtcod/src/gui/README.txt rename to tcod_sys/libtcod/src/libtcod/gui/README.txt diff --git a/tcod_sys/libtcod/src/gui/button.cpp b/tcod_sys/libtcod/src/libtcod/gui/button.cpp similarity index 99% rename from tcod_sys/libtcod/src/gui/button.cpp rename to tcod_sys/libtcod/src/libtcod/gui/button.cpp index 87533ed7a..f5c8fc1d7 100644 --- a/tcod_sys/libtcod/src/gui/button.cpp +++ b/tcod_sys/libtcod/src/libtcod/gui/button.cpp @@ -25,7 +25,7 @@ * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ -#include +#include "button.hpp" #include diff --git a/tcod_sys/libtcod/include/gui/button.hpp b/tcod_sys/libtcod/src/libtcod/gui/button.hpp similarity index 100% rename from tcod_sys/libtcod/include/gui/button.hpp rename to tcod_sys/libtcod/src/libtcod/gui/button.hpp diff --git a/tcod_sys/libtcod/src/gui/container.cpp b/tcod_sys/libtcod/src/libtcod/gui/container.cpp similarity index 98% rename from tcod_sys/libtcod/src/gui/container.cpp rename to tcod_sys/libtcod/src/libtcod/gui/container.cpp index b98caf92c..4f6e14bfd 100644 --- a/tcod_sys/libtcod/src/gui/container.cpp +++ b/tcod_sys/libtcod/src/libtcod/gui/container.cpp @@ -25,7 +25,7 @@ * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ -#include +#include "container.hpp" Container::~Container() { content.clearAndDelete(); diff --git a/tcod_sys/libtcod/include/gui/container.hpp b/tcod_sys/libtcod/src/libtcod/gui/container.hpp similarity index 100% rename from tcod_sys/libtcod/include/gui/container.hpp rename to tcod_sys/libtcod/src/libtcod/gui/container.hpp diff --git a/tcod_sys/libtcod/src/gui/flatlist.cpp b/tcod_sys/libtcod/src/libtcod/gui/flatlist.cpp similarity index 99% rename from tcod_sys/libtcod/src/gui/flatlist.cpp rename to tcod_sys/libtcod/src/libtcod/gui/flatlist.cpp index 7cdf84b07..5c3187d1b 100644 --- a/tcod_sys/libtcod/src/gui/flatlist.cpp +++ b/tcod_sys/libtcod/src/libtcod/gui/flatlist.cpp @@ -25,7 +25,7 @@ * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ -#include +#include "flatlist.hpp" #include #include diff --git a/tcod_sys/libtcod/include/gui/flatlist.hpp b/tcod_sys/libtcod/src/libtcod/gui/flatlist.hpp similarity index 100% rename from tcod_sys/libtcod/include/gui/flatlist.hpp rename to tcod_sys/libtcod/src/libtcod/gui/flatlist.hpp diff --git a/tcod_sys/libtcod/include/gui/gui.hpp b/tcod_sys/libtcod/src/libtcod/gui/gui.hpp similarity index 100% rename from tcod_sys/libtcod/include/gui/gui.hpp rename to tcod_sys/libtcod/src/libtcod/gui/gui.hpp diff --git a/tcod_sys/libtcod/include/gui/gui_portability.hpp b/tcod_sys/libtcod/src/libtcod/gui/gui_portability.hpp similarity index 96% rename from tcod_sys/libtcod/include/gui/gui_portability.hpp rename to tcod_sys/libtcod/src/libtcod/gui/gui_portability.hpp index f89c9741c..99418a836 100644 --- a/tcod_sys/libtcod/include/gui/gui_portability.hpp +++ b/tcod_sys/libtcod/src/libtcod/gui/gui_portability.hpp @@ -28,7 +28,7 @@ #ifndef TCOD_GUI_PORTABILITY_HPP #define TCOD_GUI_PORTABILITY_HPP -#include "../libtcod_portability.h" +#include "../portability.h" #ifdef TCOD_VISUAL_STUDIO #pragma warning(disable:4996) @@ -37,7 +37,7 @@ // DLL export #ifdef TCOD_WINDOWS -#ifdef LIBTCOD_GUI_EXPORTS +#ifdef LIBTCOD_EXPORTS #define TCODLIB_GUI_API __declspec(dllexport) #else #define TCODLIB_GUI_API __declspec(dllimport) diff --git a/tcod_sys/libtcod/src/gui/hbox.cpp b/tcod_sys/libtcod/src/libtcod/gui/hbox.cpp similarity index 99% rename from tcod_sys/libtcod/src/gui/hbox.cpp rename to tcod_sys/libtcod/src/libtcod/gui/hbox.cpp index 057f5edaf..50af338c5 100644 --- a/tcod_sys/libtcod/src/gui/hbox.cpp +++ b/tcod_sys/libtcod/src/libtcod/gui/hbox.cpp @@ -25,7 +25,7 @@ * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ -#include +#include "hbox.hpp" HBox::HBox(int x, int y, int padding) : VBox(x,y,padding) { } diff --git a/tcod_sys/libtcod/include/gui/hbox.hpp b/tcod_sys/libtcod/src/libtcod/gui/hbox.hpp similarity index 100% rename from tcod_sys/libtcod/include/gui/hbox.hpp rename to tcod_sys/libtcod/src/libtcod/gui/hbox.hpp diff --git a/tcod_sys/libtcod/src/gui/image.cpp b/tcod_sys/libtcod/src/libtcod/gui/image.cpp similarity index 96% rename from tcod_sys/libtcod/src/gui/image.cpp rename to tcod_sys/libtcod/src/libtcod/gui/image.cpp index fe7fecca1..f0d86c2e1 100644 --- a/tcod_sys/libtcod/src/gui/image.cpp +++ b/tcod_sys/libtcod/src/libtcod/gui/image.cpp @@ -25,7 +25,7 @@ * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ -#include /* header conflict with image.hpp */ +#include "image.hpp" Image::Image(int x,int y,int w, int h, const char *tip) : Widget(x,y,w,h), back(TCODColor::black) { if ( tip ) setTip(tip); diff --git a/tcod_sys/libtcod/include/gui/image.hpp b/tcod_sys/libtcod/src/libtcod/gui/image.hpp similarity index 100% rename from tcod_sys/libtcod/include/gui/image.hpp rename to tcod_sys/libtcod/src/libtcod/gui/image.hpp diff --git a/tcod_sys/libtcod/src/gui/label.cpp b/tcod_sys/libtcod/src/libtcod/gui/label.cpp similarity index 98% rename from tcod_sys/libtcod/src/gui/label.cpp rename to tcod_sys/libtcod/src/libtcod/gui/label.cpp index 68cfcdce2..03b74ca75 100644 --- a/tcod_sys/libtcod/src/gui/label.cpp +++ b/tcod_sys/libtcod/src/libtcod/gui/label.cpp @@ -25,7 +25,7 @@ * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ -#include +#include "label.hpp" Label::Label(int x, int y, const char *label, const char *tip) : Widget(x,y,0,1) { this->label=label; diff --git a/tcod_sys/libtcod/include/gui/label.hpp b/tcod_sys/libtcod/src/libtcod/gui/label.hpp similarity index 100% rename from tcod_sys/libtcod/include/gui/label.hpp rename to tcod_sys/libtcod/src/libtcod/gui/label.hpp diff --git a/tcod_sys/libtcod/src/gui/radiobutton.cpp b/tcod_sys/libtcod/src/libtcod/gui/radiobutton.cpp similarity index 98% rename from tcod_sys/libtcod/src/gui/radiobutton.cpp rename to tcod_sys/libtcod/src/libtcod/gui/radiobutton.cpp index d06653407..d0cfa11ea 100644 --- a/tcod_sys/libtcod/src/gui/radiobutton.cpp +++ b/tcod_sys/libtcod/src/libtcod/gui/radiobutton.cpp @@ -25,7 +25,7 @@ * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ -#include +#include "radiobutton.hpp" RadioButton *RadioButton::groupSelect[512]; int RadioButton::defaultGroup=0; diff --git a/tcod_sys/libtcod/include/gui/radiobutton.hpp b/tcod_sys/libtcod/src/libtcod/gui/radiobutton.hpp similarity index 100% rename from tcod_sys/libtcod/include/gui/radiobutton.hpp rename to tcod_sys/libtcod/src/libtcod/gui/radiobutton.hpp diff --git a/tcod_sys/libtcod/src/gui/slider.cpp b/tcod_sys/libtcod/src/libtcod/gui/slider.cpp similarity index 99% rename from tcod_sys/libtcod/src/gui/slider.cpp rename to tcod_sys/libtcod/src/libtcod/gui/slider.cpp index b79dd46da..a9d3b3b39 100644 --- a/tcod_sys/libtcod/src/gui/slider.cpp +++ b/tcod_sys/libtcod/src/libtcod/gui/slider.cpp @@ -25,7 +25,7 @@ * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ -#include +#include "slider.hpp" #include #include diff --git a/tcod_sys/libtcod/include/gui/slider.hpp b/tcod_sys/libtcod/src/libtcod/gui/slider.hpp similarity index 100% rename from tcod_sys/libtcod/include/gui/slider.hpp rename to tcod_sys/libtcod/src/libtcod/gui/slider.hpp diff --git a/tcod_sys/libtcod/src/gui/statusbar.cpp b/tcod_sys/libtcod/src/libtcod/gui/statusbar.cpp similarity index 98% rename from tcod_sys/libtcod/src/gui/statusbar.cpp rename to tcod_sys/libtcod/src/libtcod/gui/statusbar.cpp index c09aaaccf..7d1940f93 100644 --- a/tcod_sys/libtcod/src/gui/statusbar.cpp +++ b/tcod_sys/libtcod/src/libtcod/gui/statusbar.cpp @@ -25,7 +25,7 @@ * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ -#include +#include "statusbar.hpp" void StatusBar::render() { con->setDefaultBackground(back); diff --git a/tcod_sys/libtcod/include/gui/statusbar.hpp b/tcod_sys/libtcod/src/libtcod/gui/statusbar.hpp similarity index 100% rename from tcod_sys/libtcod/include/gui/statusbar.hpp rename to tcod_sys/libtcod/src/libtcod/gui/statusbar.hpp diff --git a/tcod_sys/libtcod/src/gui/textbox.cpp b/tcod_sys/libtcod/src/libtcod/gui/textbox.cpp similarity index 99% rename from tcod_sys/libtcod/src/gui/textbox.cpp rename to tcod_sys/libtcod/src/libtcod/gui/textbox.cpp index 801eb1515..d163d01b8 100644 --- a/tcod_sys/libtcod/src/gui/textbox.cpp +++ b/tcod_sys/libtcod/src/libtcod/gui/textbox.cpp @@ -25,7 +25,7 @@ * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ -#include +#include "textbox.hpp" #include #include diff --git a/tcod_sys/libtcod/include/gui/textbox.hpp b/tcod_sys/libtcod/src/libtcod/gui/textbox.hpp similarity index 100% rename from tcod_sys/libtcod/include/gui/textbox.hpp rename to tcod_sys/libtcod/src/libtcod/gui/textbox.hpp diff --git a/tcod_sys/libtcod/src/gui/togglebutton.cpp b/tcod_sys/libtcod/src/libtcod/gui/togglebutton.cpp similarity index 98% rename from tcod_sys/libtcod/src/gui/togglebutton.cpp rename to tcod_sys/libtcod/src/libtcod/gui/togglebutton.cpp index c29dc974c..b07f75164 100644 --- a/tcod_sys/libtcod/src/gui/togglebutton.cpp +++ b/tcod_sys/libtcod/src/libtcod/gui/togglebutton.cpp @@ -25,7 +25,7 @@ * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ -#include +#include "togglebutton.hpp" #include diff --git a/tcod_sys/libtcod/include/gui/togglebutton.hpp b/tcod_sys/libtcod/src/libtcod/gui/togglebutton.hpp similarity index 100% rename from tcod_sys/libtcod/include/gui/togglebutton.hpp rename to tcod_sys/libtcod/src/libtcod/gui/togglebutton.hpp diff --git a/tcod_sys/libtcod/src/gui/toolbar.cpp b/tcod_sys/libtcod/src/libtcod/gui/toolbar.cpp similarity index 99% rename from tcod_sys/libtcod/src/gui/toolbar.cpp rename to tcod_sys/libtcod/src/libtcod/gui/toolbar.cpp index f3add4c92..c0a5eeceb 100644 --- a/tcod_sys/libtcod/src/gui/toolbar.cpp +++ b/tcod_sys/libtcod/src/libtcod/gui/toolbar.cpp @@ -25,7 +25,7 @@ * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ -#include +#include "toolbar.hpp" #include diff --git a/tcod_sys/libtcod/include/gui/toolbar.hpp b/tcod_sys/libtcod/src/libtcod/gui/toolbar.hpp similarity index 100% rename from tcod_sys/libtcod/include/gui/toolbar.hpp rename to tcod_sys/libtcod/src/libtcod/gui/toolbar.hpp diff --git a/tcod_sys/libtcod/src/gui/vbox.cpp b/tcod_sys/libtcod/src/libtcod/gui/vbox.cpp similarity index 98% rename from tcod_sys/libtcod/src/gui/vbox.cpp rename to tcod_sys/libtcod/src/libtcod/gui/vbox.cpp index 5b7d90831..92a306cd5 100644 --- a/tcod_sys/libtcod/src/gui/vbox.cpp +++ b/tcod_sys/libtcod/src/libtcod/gui/vbox.cpp @@ -25,7 +25,7 @@ * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ -#include +#include "vbox.hpp" void VBox::computeSize() { int cury=y; diff --git a/tcod_sys/libtcod/include/gui/vbox.hpp b/tcod_sys/libtcod/src/libtcod/gui/vbox.hpp similarity index 100% rename from tcod_sys/libtcod/include/gui/vbox.hpp rename to tcod_sys/libtcod/src/libtcod/gui/vbox.hpp diff --git a/tcod_sys/libtcod/src/gui/widget.cpp b/tcod_sys/libtcod/src/libtcod/gui/widget.cpp similarity index 98% rename from tcod_sys/libtcod/src/gui/widget.cpp rename to tcod_sys/libtcod/src/libtcod/gui/widget.cpp index 0dc0e5bfa..0a19b4e92 100644 --- a/tcod_sys/libtcod/src/gui/widget.cpp +++ b/tcod_sys/libtcod/src/libtcod/gui/widget.cpp @@ -25,11 +25,11 @@ * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ -#include +#include "widget.hpp" #include -#include +#include "../sys.hpp" TCODColor Widget::back=TCODColor(40,40,120); TCODColor Widget::fore=TCODColor(220,220,180); diff --git a/tcod_sys/libtcod/include/gui/widget.hpp b/tcod_sys/libtcod/src/libtcod/gui/widget.hpp similarity index 100% rename from tcod_sys/libtcod/include/gui/widget.hpp rename to tcod_sys/libtcod/src/libtcod/gui/widget.hpp diff --git a/tcod_sys/libtcod/src/heightmap.cpp b/tcod_sys/libtcod/src/libtcod/heightmap.cpp similarity index 97% rename from tcod_sys/libtcod/src/heightmap.cpp rename to tcod_sys/libtcod/src/libtcod/heightmap.cpp index f1c568d67..7afb75a6c 100644 --- a/tcod_sys/libtcod/src/heightmap.cpp +++ b/tcod_sys/libtcod/src/libtcod/heightmap.cpp @@ -1,178 +1,178 @@ -/* -* libtcod -* Copyright (c) 2008-2018 Jice & Mingos & rmtew -* All rights reserved. -* -* Redistribution and use in source and binary forms, with or without -* modification, are permitted provided that the following conditions are met: -* * Redistributions of source code must retain the above copyright -* notice, this list of conditions and the following disclaimer. -* * Redistributions in binary form must reproduce the above copyright -* notice, this list of conditions and the following disclaimer in the -* documentation and/or other materials provided with the distribution. -* * The name of Jice or Mingos may not be used to endorse or promote -* products derived from this software without specific prior written -* permission. -* -* THIS SOFTWARE IS PROVIDED BY JICE, MINGOS AND RMTEW ``AS IS'' AND ANY -* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED -* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE -* DISCLAIMED. IN NO EVENT SHALL JICE, MINGOS OR RMTEW BE LIABLE FOR ANY -* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES -* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; -* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND -* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS -* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. -*/ -#include - -#include - -#include - -TCODHeightMap::TCODHeightMap(int w, int h) : w(w),h(h) { - values = new float[w*h]; - memset(values,0,sizeof(float)*w*h); -} -TCODHeightMap::~TCODHeightMap() { - delete [] values; -} - -void TCODHeightMap::clear() { - TCOD_heightmap_t hm={w,h,values}; - TCOD_heightmap_clear(&hm); -} -void TCODHeightMap::normalize(float newMin, float newMax) { - TCOD_heightmap_t hm={w,h,values}; - TCOD_heightmap_normalize(&hm,newMin,newMax); -} - -void TCODHeightMap::getMinMax(float *min, float *max) const { - TCOD_heightmap_t hm={w,h,values}; - TCOD_heightmap_get_minmax(&hm,min,max); -} - -void TCODHeightMap::addHill(float hx, float hy, float hradius, float height) { - TCOD_heightmap_t hm={w,h,values}; - TCOD_heightmap_add_hill(&hm,hx,hy,hradius,height); -} - -void TCODHeightMap::digHill(float hx, float hy, float hradius, float height) { - TCOD_heightmap_t hm={w,h,values}; - TCOD_heightmap_dig_hill(&hm,hx,hy,hradius,height); -} - -void TCODHeightMap::copy(const TCODHeightMap *source) { - TCOD_heightmap_t hm_source={source->w,source->h,source->values}; - TCOD_heightmap_t hm_dest={w,h,values}; - TCOD_heightmap_copy(&hm_source,&hm_dest); -} - -void TCODHeightMap::addFbm(TCODNoise *noise, float mulx, float muly, float addx, float addy, float octaves, float delta, float scale) { - TCOD_heightmap_t hm={w,h,values}; - TCOD_heightmap_add_fbm(&hm,noise->data,mulx,muly,addx,addy,octaves,delta,scale); -} -void TCODHeightMap::scaleFbm(TCODNoise *noise, float mulx, float muly, float addx, float addy, float octaves, float delta, float scale) { - TCOD_heightmap_t hm={w,h,values}; - TCOD_heightmap_scale_fbm(&hm,noise->data,mulx,muly,addx,addy,octaves,delta,scale); -} - -float TCODHeightMap::getInterpolatedValue(float x, float y) const { - TCOD_heightmap_t hm={w,h,values}; - return TCOD_heightmap_get_interpolated_value(&hm,x,y); -} - -void TCODHeightMap::getNormal(float x, float y,float n[3], float waterHeight) const { - TCOD_heightmap_t hm={w,h,values}; - return TCOD_heightmap_get_normal(&hm,x,y,n,waterHeight); -} - -void TCODHeightMap::digBezier(int px[4], int py[4], float startRadius, float startDepth, float endRadius, float endDepth) { - TCOD_heightmap_t hm={w,h,values}; - TCOD_heightmap_dig_bezier(&hm,px,py,startRadius,startDepth,endRadius,endDepth); -} - -bool TCODHeightMap::hasLandOnBorder(float seaLevel) const { - TCOD_heightmap_t hm={w,h,values}; - return TCOD_heightmap_has_land_on_border(&hm,seaLevel) != 0; -} - -void TCODHeightMap::islandify(float seaLevel,TCODRandom *rnd) { - TCOD_heightmap_t hm={w,h,values}; - return TCOD_heightmap_islandify(&hm,seaLevel,rnd->data); -} - -void TCODHeightMap::add(float f) { - TCOD_heightmap_t hm={w,h,values}; - TCOD_heightmap_add(&hm,f); -} - -int TCODHeightMap::countCells(float min,float max) const { - TCOD_heightmap_t hm={w,h,values}; - return TCOD_heightmap_count_cells(&hm,min,max); -} - -void TCODHeightMap::scale(float f) { - TCOD_heightmap_t hm={w,h,values}; - TCOD_heightmap_scale(&hm,f); -} - -void TCODHeightMap::clamp(float min, float max) { - TCOD_heightmap_t hm={w,h,values}; - TCOD_heightmap_clamp(&hm,min,max); -} - -void TCODHeightMap::lerp(const TCODHeightMap *a, const TCODHeightMap *b,float coef) { - TCOD_heightmap_t hm1={a->w,a->h,a->values}; - TCOD_heightmap_t hm2={b->w,b->h,b->values}; - TCOD_heightmap_t hmres={w,h,values}; - TCOD_heightmap_lerp_hm(&hm1,&hm2,&hmres,coef); -} - -void TCODHeightMap::add(const TCODHeightMap *a, const TCODHeightMap *b) { - TCOD_heightmap_t hm1={a->w,a->h,a->values}; - TCOD_heightmap_t hm2={b->w,b->h,b->values}; - TCOD_heightmap_t hmres={w,h,values}; - TCOD_heightmap_add_hm(&hm1,&hm2,&hmres); -} - -void TCODHeightMap::multiply(const TCODHeightMap *a, const TCODHeightMap *b) { - TCOD_heightmap_t hm1={a->w,a->h,a->values}; - TCOD_heightmap_t hm2={b->w,b->h,b->values}; - TCOD_heightmap_t hmres={w,h,values}; - TCOD_heightmap_multiply_hm(&hm1,&hm2,&hmres); -} - -float TCODHeightMap::getSlope(int x, int y) const { - TCOD_heightmap_t hm={w,h,values}; - return TCOD_heightmap_get_slope(&hm,x,y); -} - -void TCODHeightMap::rainErosion(int nbDrops, float erosionCoef,float agregationCoef, TCODRandom *rnd) { - TCOD_heightmap_t hm={w,h,values}; - TCOD_heightmap_rain_erosion(&hm, nbDrops, erosionCoef, agregationCoef, rnd->data); -} - -void TCODHeightMap::kernelTransform(int kernelSize, const int *dx, const int *dy, const float *weight, float minLevel,float maxLevel) { - TCOD_heightmap_t hm={w,h,values}; - TCOD_heightmap_kernel_transform(&hm, kernelSize,dx,dy,weight,minLevel, maxLevel); -} - -void TCODHeightMap::addVoronoi(int nbPoints, int nbCoef, const float *coef,TCODRandom *rnd) { - TCOD_heightmap_t hm={w,h,values}; - TCOD_heightmap_add_voronoi(&hm, nbPoints, nbCoef, coef, rnd->data); -} - -#if 0 -void TCODHeightMap::heatErosion(int nbPass,float minSlope,float erosionCoef,float agregationCoef,TCODRandom *rnd) { - TCOD_heightmap_t hm={w,h,values}; - TCOD_heightmap_heat_erosion(&hm, nbPass, minSlope, erosionCoef, agregationCoef, rnd->data); -} -#endif - -void TCODHeightMap::midPointDisplacement(TCODRandom *rnd, float roughness) { - TCOD_heightmap_t hm={w,h,values}; - if ( ! rnd ) rnd = TCODRandom::getInstance(); - TCOD_heightmap_mid_point_displacement(&hm, rnd->data, roughness); -} +/* +* libtcod +* Copyright (c) 2008-2018 Jice & Mingos & rmtew +* All rights reserved. +* +* Redistribution and use in source and binary forms, with or without +* modification, are permitted provided that the following conditions are met: +* * Redistributions of source code must retain the above copyright +* notice, this list of conditions and the following disclaimer. +* * Redistributions in binary form must reproduce the above copyright +* notice, this list of conditions and the following disclaimer in the +* documentation and/or other materials provided with the distribution. +* * The name of Jice or Mingos may not be used to endorse or promote +* products derived from this software without specific prior written +* permission. +* +* THIS SOFTWARE IS PROVIDED BY JICE, MINGOS AND RMTEW ``AS IS'' AND ANY +* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED +* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE +* DISCLAIMED. IN NO EVENT SHALL JICE, MINGOS OR RMTEW BE LIABLE FOR ANY +* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES +* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; +* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND +* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS +* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +*/ +#include "heightmap.hpp" + +#include + +#include + +TCODHeightMap::TCODHeightMap(int w, int h) : w(w),h(h) { + values = new float[w*h]; + memset(values,0,sizeof(float)*w*h); +} +TCODHeightMap::~TCODHeightMap() { + delete [] values; +} + +void TCODHeightMap::clear() { + TCOD_heightmap_t hm={w,h,values}; + TCOD_heightmap_clear(&hm); +} +void TCODHeightMap::normalize(float newMin, float newMax) { + TCOD_heightmap_t hm={w,h,values}; + TCOD_heightmap_normalize(&hm,newMin,newMax); +} + +void TCODHeightMap::getMinMax(float *min, float *max) const { + TCOD_heightmap_t hm={w,h,values}; + TCOD_heightmap_get_minmax(&hm,min,max); +} + +void TCODHeightMap::addHill(float hx, float hy, float hradius, float height) { + TCOD_heightmap_t hm={w,h,values}; + TCOD_heightmap_add_hill(&hm,hx,hy,hradius,height); +} + +void TCODHeightMap::digHill(float hx, float hy, float hradius, float height) { + TCOD_heightmap_t hm={w,h,values}; + TCOD_heightmap_dig_hill(&hm,hx,hy,hradius,height); +} + +void TCODHeightMap::copy(const TCODHeightMap *source) { + TCOD_heightmap_t hm_source={source->w,source->h,source->values}; + TCOD_heightmap_t hm_dest={w,h,values}; + TCOD_heightmap_copy(&hm_source,&hm_dest); +} + +void TCODHeightMap::addFbm(TCODNoise *noise, float mulx, float muly, float addx, float addy, float octaves, float delta, float scale) { + TCOD_heightmap_t hm={w,h,values}; + TCOD_heightmap_add_fbm(&hm,noise->data,mulx,muly,addx,addy,octaves,delta,scale); +} +void TCODHeightMap::scaleFbm(TCODNoise *noise, float mulx, float muly, float addx, float addy, float octaves, float delta, float scale) { + TCOD_heightmap_t hm={w,h,values}; + TCOD_heightmap_scale_fbm(&hm,noise->data,mulx,muly,addx,addy,octaves,delta,scale); +} + +float TCODHeightMap::getInterpolatedValue(float x, float y) const { + TCOD_heightmap_t hm={w,h,values}; + return TCOD_heightmap_get_interpolated_value(&hm,x,y); +} + +void TCODHeightMap::getNormal(float x, float y,float n[3], float waterHeight) const { + TCOD_heightmap_t hm={w,h,values}; + return TCOD_heightmap_get_normal(&hm,x,y,n,waterHeight); +} + +void TCODHeightMap::digBezier(int px[4], int py[4], float startRadius, float startDepth, float endRadius, float endDepth) { + TCOD_heightmap_t hm={w,h,values}; + TCOD_heightmap_dig_bezier(&hm,px,py,startRadius,startDepth,endRadius,endDepth); +} + +bool TCODHeightMap::hasLandOnBorder(float seaLevel) const { + TCOD_heightmap_t hm={w,h,values}; + return TCOD_heightmap_has_land_on_border(&hm,seaLevel) != 0; +} + +void TCODHeightMap::islandify(float seaLevel,TCODRandom *rnd) { + TCOD_heightmap_t hm={w,h,values}; + return TCOD_heightmap_islandify(&hm,seaLevel,rnd->data); +} + +void TCODHeightMap::add(float f) { + TCOD_heightmap_t hm={w,h,values}; + TCOD_heightmap_add(&hm,f); +} + +int TCODHeightMap::countCells(float min,float max) const { + TCOD_heightmap_t hm={w,h,values}; + return TCOD_heightmap_count_cells(&hm,min,max); +} + +void TCODHeightMap::scale(float f) { + TCOD_heightmap_t hm={w,h,values}; + TCOD_heightmap_scale(&hm,f); +} + +void TCODHeightMap::clamp(float min, float max) { + TCOD_heightmap_t hm={w,h,values}; + TCOD_heightmap_clamp(&hm,min,max); +} + +void TCODHeightMap::lerp(const TCODHeightMap *a, const TCODHeightMap *b,float coef) { + TCOD_heightmap_t hm1={a->w,a->h,a->values}; + TCOD_heightmap_t hm2={b->w,b->h,b->values}; + TCOD_heightmap_t hmres={w,h,values}; + TCOD_heightmap_lerp_hm(&hm1,&hm2,&hmres,coef); +} + +void TCODHeightMap::add(const TCODHeightMap *a, const TCODHeightMap *b) { + TCOD_heightmap_t hm1={a->w,a->h,a->values}; + TCOD_heightmap_t hm2={b->w,b->h,b->values}; + TCOD_heightmap_t hmres={w,h,values}; + TCOD_heightmap_add_hm(&hm1,&hm2,&hmres); +} + +void TCODHeightMap::multiply(const TCODHeightMap *a, const TCODHeightMap *b) { + TCOD_heightmap_t hm1={a->w,a->h,a->values}; + TCOD_heightmap_t hm2={b->w,b->h,b->values}; + TCOD_heightmap_t hmres={w,h,values}; + TCOD_heightmap_multiply_hm(&hm1,&hm2,&hmres); +} + +float TCODHeightMap::getSlope(int x, int y) const { + TCOD_heightmap_t hm={w,h,values}; + return TCOD_heightmap_get_slope(&hm,x,y); +} + +void TCODHeightMap::rainErosion(int nbDrops, float erosionCoef,float agregationCoef, TCODRandom *rnd) { + TCOD_heightmap_t hm={w,h,values}; + TCOD_heightmap_rain_erosion(&hm, nbDrops, erosionCoef, agregationCoef, rnd->data); +} + +void TCODHeightMap::kernelTransform(int kernelSize, const int *dx, const int *dy, const float *weight, float minLevel,float maxLevel) { + TCOD_heightmap_t hm={w,h,values}; + TCOD_heightmap_kernel_transform(&hm, kernelSize,dx,dy,weight,minLevel, maxLevel); +} + +void TCODHeightMap::addVoronoi(int nbPoints, int nbCoef, const float *coef,TCODRandom *rnd) { + TCOD_heightmap_t hm={w,h,values}; + TCOD_heightmap_add_voronoi(&hm, nbPoints, nbCoef, coef, rnd->data); +} + +#if 0 +void TCODHeightMap::heatErosion(int nbPass,float minSlope,float erosionCoef,float agregationCoef,TCODRandom *rnd) { + TCOD_heightmap_t hm={w,h,values}; + TCOD_heightmap_heat_erosion(&hm, nbPass, minSlope, erosionCoef, agregationCoef, rnd->data); +} +#endif + +void TCODHeightMap::midPointDisplacement(TCODRandom *rnd, float roughness) { + TCOD_heightmap_t hm={w,h,values}; + if ( ! rnd ) rnd = TCODRandom::getInstance(); + TCOD_heightmap_mid_point_displacement(&hm, rnd->data, roughness); +} diff --git a/tcod_sys/libtcod/include/heightmap.h b/tcod_sys/libtcod/src/libtcod/heightmap.h similarity index 99% rename from tcod_sys/libtcod/include/heightmap.h rename to tcod_sys/libtcod/src/libtcod/heightmap.h index f113829f8..e65c211ec 100644 --- a/tcod_sys/libtcod/include/heightmap.h +++ b/tcod_sys/libtcod/src/libtcod/heightmap.h @@ -28,7 +28,7 @@ #ifndef _TCOD_HEIGHTMAP_H #define _TCOD_HEIGHTMAP_H -#include "libtcod_portability.h" +#include "portability.h" #include "mersenne_types.h" #include "noise.h" diff --git a/tcod_sys/libtcod/include/heightmap.hpp b/tcod_sys/libtcod/src/libtcod/heightmap.hpp similarity index 100% rename from tcod_sys/libtcod/include/heightmap.hpp rename to tcod_sys/libtcod/src/libtcod/heightmap.hpp diff --git a/tcod_sys/libtcod/src/heightmap_c.c b/tcod_sys/libtcod/src/libtcod/heightmap_c.c similarity index 96% rename from tcod_sys/libtcod/src/heightmap_c.c rename to tcod_sys/libtcod/src/libtcod/heightmap_c.c index d8937f2ed..bf7a7a6a5 100644 --- a/tcod_sys/libtcod/src/heightmap_c.c +++ b/tcod_sys/libtcod/src/libtcod/heightmap_c.c @@ -1,562 +1,562 @@ -/* -* libtcod -* Copyright (c) 2008-2018 Jice & Mingos & rmtew -* All rights reserved. -* -* Redistribution and use in source and binary forms, with or without -* modification, are permitted provided that the following conditions are met: -* * Redistributions of source code must retain the above copyright -* notice, this list of conditions and the following disclaimer. -* * Redistributions in binary form must reproduce the above copyright -* notice, this list of conditions and the following disclaimer in the -* documentation and/or other materials provided with the distribution. -* * The name of Jice or Mingos may not be used to endorse or promote -* products derived from this software without specific prior written -* permission. -* -* THIS SOFTWARE IS PROVIDED BY JICE, MINGOS AND RMTEW ``AS IS'' AND ANY -* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED -* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE -* DISCLAIMED. IN NO EVENT SHALL JICE, MINGOS OR RMTEW BE LIABLE FOR ANY -* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES -* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; -* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND -* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS -* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. -*/ -#include - -#include -#include -#include - -#include -#include - -#define GET_VALUE(hm,x,y) (hm)->values[(x)+(y)*(hm)->w] - -TCOD_heightmap_t *TCOD_heightmap_new(int w,int h) { - TCOD_heightmap_t *hm=(TCOD_heightmap_t *)malloc(sizeof(TCOD_heightmap_t)); - hm->values = (float *)calloc(sizeof(float),w*h); - hm->w=w; - hm->h=h; - return hm; -} -void TCOD_heightmap_delete(TCOD_heightmap_t *hm) { - free(hm->values); - free(hm); -} - -void TCOD_heightmap_clear(TCOD_heightmap_t *hm) { - memset(hm->values,0,hm->w*hm->h*sizeof(float)); -} - -float TCOD_heightmap_get_value(const TCOD_heightmap_t *hm, int x, int y) { - return GET_VALUE(hm,x,y); -} - -void TCOD_heightmap_set_value(TCOD_heightmap_t *hm, int x, int y, float value) { - GET_VALUE(hm,x,y)=value; -} - -void TCOD_heightmap_get_minmax(const TCOD_heightmap_t *hm, float *min, float *max) { - float curmax=hm->values[0]; - float curmin=hm->values[0]; - int x,y; - float *value = hm->values; - /* get max and min height */ - for (y=0; y < hm->h; y++) { - for (x=0; x < hm->w; x++) { - float val=*value; - if ( val > curmax ) curmax = val; - else if ( val < curmin ) curmin = val; - value++; - } - } - *min=curmin; - *max=curmax; -} - -void TCOD_heightmap_normalize(TCOD_heightmap_t *hm, float min, float max) { - float curmin,curmax; - int x,y; - float invmax; - float *value = hm->values; - TCOD_heightmap_get_minmax(hm,&curmin,&curmax); - if (curmax - curmin == 0.0f) invmax=0.0f; - else invmax = (max-min) / (curmax-curmin); - /* normalize */ - for (y=0; y < hm->h; y++) { - for (x=0; x < hm->w; x++) { - *value = min + (*value - curmin) * invmax ; - value++; - } - } -} -void TCOD_heightmap_add_hill(TCOD_heightmap_t *hm, float hx, float hy, float hradius, float hheight) { - int x,y; - float hradius2=hradius*hradius; - float coef=hheight / hradius2; - int minx=(int)MAX(0,hx-hradius); - int maxx=(int)MIN(hm->w,hx+hradius); - int miny=(int)MAX(0,hy-hradius); - int maxy=(int)MIN(hm->h,hy+hradius); - for (x=minx; x < maxx; x++) { - float xdist=( x - hx )*( x - hx ); - for (y=miny; y < maxy; y++) { - float z = hradius2 - xdist - (y - hy)*(y - hy); - if ( z > 0.0 ) GET_VALUE(hm,x,y) += z * coef; - } - } -} - -void TCOD_heightmap_dig_hill(TCOD_heightmap_t *hm, float hx, float hy, float hradius, float hheight) { - int x,y; - float hradius2=hradius*hradius; - float coef=hheight / hradius2; - int minx=(int)MAX(0,hx-hradius); - int maxx=(int)MIN(hm->w,hx+hradius); - int miny=(int)MAX(0,hy-hradius); - int maxy=(int)MIN(hm->h,hy+hradius); - for (x=minx; x < maxx; x++) { - float xdist=( x - hx )*( x - hx ); - for (y=miny; y < maxy; y++) { - float dist=xdist + (y - hy)*(y - hy); - if ( dist < hradius2 ) { - float z = (hradius2 - dist) * coef; - if ( hheight > 0.0 ) { - if ( GET_VALUE(hm,x,y) < z ) GET_VALUE(hm,x,y) = z; - } else { - if ( GET_VALUE(hm,x,y) > z ) GET_VALUE(hm,x,y) = z; - } - } - } - } -} - -void TCOD_heightmap_copy(const TCOD_heightmap_t *hm_source,TCOD_heightmap_t *hm_dest) { - if ( hm_source->w != hm_dest->w || hm_source->h != hm_dest->h) return; - memcpy(hm_dest->values,hm_source->values,sizeof(float)*hm_source->w*hm_source->h); -} - -void TCOD_heightmap_add_fbm(TCOD_heightmap_t *hm, TCOD_noise_t noise,float mulx, float muly, float addx, float addy, float octaves, float delta, float scale) { - int x,y; - float xcoef=mulx / hm->w; - float ycoef=muly / hm->h; - float min=1.0f; - float max=0.0f; - for (x=0; x < hm->w; x++) { - float f[2]; - int offset=x; - f[0] = (x + addx) * xcoef; - for (y=0; y < hm->h; y++) { - float value; - f[1] = (y + addy)*ycoef; - value=delta+TCOD_noise_get_fbm(noise,f,octaves)*scale; - hm->values[offset] += value; - if ( value < min ) min = value; - if ( value > max ) max=value; - offset+=hm->w; - } - } -} -void TCOD_heightmap_scale_fbm(TCOD_heightmap_t *hm, TCOD_noise_t noise,float mulx, float muly, float addx, float addy, float octaves, float delta, float scale) { - int x,y; - float xcoef=mulx / hm->w; - float ycoef=muly / hm->h; - for (x=0; x < hm->w; x++) { - float f[2]; - int offset=x; - f[0] = (x + addx) * xcoef; - for (y=0; y < hm->h; y++) { - f[1] = (y + addy)*ycoef; - hm->values[offset] *= (delta+TCOD_noise_get_fbm(noise,f,octaves)*scale); - offset+=hm->w; - } - } -} - -float TCOD_heightmap_get_interpolated_value(const TCOD_heightmap_t *hm, float x, float y) { - int ix = (int) x; - int iy = (int) y; - if ( ix >= hm->w-1 || iy >= hm->h-1 ) { - return GET_VALUE(hm,ix,iy); - } else { - float dx = x - ix; - float dy = y - iy; - float c1 = GET_VALUE(hm,ix,iy); - float c2 = GET_VALUE(hm,ix+1,iy); - float c3 = GET_VALUE(hm,ix,iy+1); - float c4 = GET_VALUE(hm,ix+1,iy+1); - float top = (1.0f-dx)*c1 + dx*c2; - float bottom = (1.0f-dx)*c3 + dx*c4; - return (1.0f-dy)*top + dy*bottom; - } -} - -void TCOD_heightmap_get_normal(const TCOD_heightmap_t *hm, float x, float y, float n[3], float waterLevel) { - float h0,hx,hy,invlen; /* map heights at x,y x+1,y and x,y+1 */ - n[0]=0.0f;n[1]=0.0f;n[2]=1.0f; - if ( x >= hm->w-1 || y >= hm->h-1 ) return; - h0 = TCOD_heightmap_get_interpolated_value(hm,x,y); - if ( h0 < waterLevel ) h0=waterLevel; - hx = TCOD_heightmap_get_interpolated_value(hm,x+1,y); - if ( hx < waterLevel ) hx=waterLevel; - hy = TCOD_heightmap_get_interpolated_value(hm,x,y+1); - if ( hy < waterLevel ) hy=waterLevel; - /* vx = 1 vy = 0 */ - /* 0 1 */ - /* hx-h0 hy-h0 */ - /* vz = vx cross vy */ - n[0] = 255*(h0-hx); - n[1] = 255*(h0-hy); - n[2] = 16.0f; - /* normalize */ - invlen=1.0f / (float)sqrt(n[0]*n[0]+n[1]*n[1]+n[2]*n[2]); - n[0]*=invlen; - n[1]*=invlen; - n[2]*=invlen; -} - -void TCOD_heightmap_dig_bezier(TCOD_heightmap_t *hm, int px[4], int py[4], float startRadius, float startDepth, float endRadius, float endDepth) { - int xFrom=px[0]; - int yFrom=py[0]; - float t; - for ( t=0.0f;t <= 1.0f ; t += 0.001f ) { - int xTo,yTo; - float it=1.0f-t; - xTo=(int)(px[0]*it*it*it + 3*px[1]*t*it*it + 3*px[2]*t*t*it + px[3]*t*t*t); - yTo=(int)(py[0]*it*it*it + 3*py[1]*t*it*it + 3*py[2]*t*t*it + py[3]*t*t*t); - if ( xTo != xFrom || yTo != yFrom ) { - float radius=startRadius+(endRadius-startRadius)*t; - float depth=startDepth+(endDepth-startDepth)*t; - TCOD_heightmap_dig_hill(hm,(float)xTo,(float)yTo,radius,depth); - xFrom=xTo; - yFrom=yTo; - } - } -} - -bool TCOD_heightmap_has_land_on_border(const TCOD_heightmap_t *hm, float waterLevel) { - int x,y; - for (x=0; x < hm->w; x++) { - if ( GET_VALUE(hm,x,0) > waterLevel - || GET_VALUE(hm,x,hm->h-1) > waterLevel ) { - return true; - } - } - for (y=0; y < hm->h; y++) { - if ( GET_VALUE(hm,0,y) > waterLevel - || GET_VALUE(hm,hm->w-1,y) > waterLevel ) { - return true; - } - } - return false; -} - -void TCOD_heightmap_islandify(TCOD_heightmap_t *hm, float seaLevel,TCOD_random_t rnd) { - /* TODO */ -} - -void TCOD_heightmap_add(TCOD_heightmap_t *hm, float value) { - int i; - for (i=0; i < hm->w*hm->h; i++ ) hm->values[i]+=value; -} - -int TCOD_heightmap_count_cells(const TCOD_heightmap_t *hm, float min, float max) { - int count=0,i; - for (i=0; i < hm->w*hm->h; i++ ) if (hm->values[i] >= min && hm->values[i] <= max) count++; - return count; -} - -void TCOD_heightmap_scale(TCOD_heightmap_t *hm, float value) { - int i; - for (i=0; i < hm->w*hm->h; i++ ) hm->values[i]*=value; -} - -void TCOD_heightmap_clamp(TCOD_heightmap_t *hm, float min, float max) { - int i; - for (i=0; i < hm->w*hm->h; i++ ) { - hm->values[i]=CLAMP(min,max,hm->values[i]); - } -} - -void TCOD_heightmap_lerp_hm(const TCOD_heightmap_t *hm1, const TCOD_heightmap_t *hm2, TCOD_heightmap_t *hmres, float coef) { - int i; - if ( hm1->w != hm2->w || hm1->h != hm2->h - || hm1->w != hmres->w || hm1->h != hmres->h - ) { - return; - } - for (i=0; i < hm1->w*hm1->h; i++ ) { - hmres->values[i]=hm1->values[i]+(hm2->values[i]-hm1->values[i])*coef; - } -} - -void TCOD_heightmap_add_hm(const TCOD_heightmap_t *hm1, const TCOD_heightmap_t *hm2, TCOD_heightmap_t *hmres) { - int i; - if ( hm1->w != hm2->w || hm1->h != hm2->h - || hm1->w != hmres->w || hm1->h != hmres->h - ) { - return; - } - for (i=0; i < hm1->w*hm1->h; i++ ) { - hmres->values[i]=hm1->values[i]+hm2->values[i]; - } -} - -void TCOD_heightmap_multiply_hm(const TCOD_heightmap_t *hm1, const TCOD_heightmap_t *hm2, TCOD_heightmap_t *hmres) { - int i; - if ( hm1->w != hm2->w || hm1->h != hm2->h - || hm1->w != hmres->w || hm1->h != hmres->h - ) { - return; - } - for (i=0; i < hm1->w*hm1->h; i++ ) { - hmres->values[i]=hm1->values[i]*hm2->values[i]; - } -} - - -float TCOD_heightmap_get_slope(const TCOD_heightmap_t *hm, int x, int y) { - static int dix[8]={-1,0,1,-1,1,-1,0,1}; - static int diy[8]={-1,-1,-1,0,0,1,1,1}; - float mindy=0.0f,maxdy=0.0f; - float v=GET_VALUE(hm,x,y); - int i; - for (i=0; i < 8; i++ ) { - int nx=x+dix[i]; - int ny=y+diy[i]; - if ( nx >= 0 && nx < hm->w && ny >= 0 && ny < hm->h ) { - float nslope=(GET_VALUE(hm,nx,ny)-v); - if ( nslope > maxdy ) { - maxdy=nslope; - } else if ( nslope < mindy ) { - mindy=nslope; - } - } - } - return (float)atan2(maxdy+mindy,1.0f); -} - -void TCOD_heightmap_rain_erosion(TCOD_heightmap_t *hm, int nbDrops,float erosionCoef,float agregationCoef,TCOD_random_t rnd) { - while ( nbDrops > 0 ) { - int curx=TCOD_random_get_int(rnd,0,hm->w-1); - int cury=TCOD_random_get_int(rnd,0,hm->h-1); - static int dx[8]={-1,0,1,-1,1,-1,0,1}; - static int dy[8]={-1,-1,-1,0,0,1,1,1}; - float slope=0.0f; - float sediment=0.0f; - do { - int nextx=0,nexty=0,i; - float v=GET_VALUE(hm,curx,cury); - /* calculate slope at x,y */ - slope=0.0f; - for (i=0; i < 8; i++ ) { - int nx=curx+dx[i]; - int ny=cury+dy[i]; - if ( nx >= 0 && nx < hm->w && ny >= 0 && ny < hm->h ) { - float nslope=v-GET_VALUE(hm,nx,ny); - if ( nslope > slope ) { - slope=nslope; - nextx=nx; - nexty=ny; - } - } - } - if ( slope > 0.0f ) { -/* GET_VALUE(hm,curx,cury) *= 1.0f - (erosionCoef * slope); */ - GET_VALUE(hm,curx,cury) -= erosionCoef * slope; - curx=nextx; - cury=nexty; - sediment+=slope; - } else { -/* GET_VALUE(hm,curx,cury) *= 1.0f + (agregationCoef*sediment); */ - GET_VALUE(hm,curx,cury) += agregationCoef*sediment; - } - } while ( slope > 0.0f ); - nbDrops--; - } -} - -#if 0 -static void setMPDHeight(TCOD_heightmap_t *hm, TCOD_random_t rnd,int x,int y, float z, float offset); -static void setMDPHeightSquare(TCOD_heightmap_t *hm, TCOD_random_t rnd,int x, int y, int initsz, int sz,float offset); - -void TCOD_heightmap_heat_erosion(TCOD_heightmap_t *hm, int nbPass,float minSlope,float erosionCoef,float agregationCoef,TCOD_random_t rnd) { - int x; - while ( nbPass > 0 ) { - for (x=0; x < hm->w; x++) { - int offset=x,y; - for (y=0; y < hm->h; y++) { - static int dx[8]={-1,0,1,-1,1,-1,0,1}; - static int dy[8]={-1,-1,-1,0,0,1,1,1}; - int nextx=0,nexty=0,i; - float v=hm->values[offset]; - /* calculate slope at x,y */ - float slope=0.0f; - for (i=0; i < 8; i++ ) { /* 4 : von neumann neighbourhood 8 : moore neighbourhood */ - int nx=x+dx[i]; - int ny=y+dy[i]; - if ( nx >= 0 && nx < hm->w && ny >= 0 && ny < hm->h ) { - float nslope=v-GET_VALUE(hm,nx,ny); - if ( nslope > slope ) { - slope=nslope; - nextx=nx; - nexty=ny; - } - } - } - if ( slope > minSlope ) { - GET_VALUE(hm,x,y) -= erosionCoef*(slope-minSlope); - GET_VALUE(hm,nextx,nexty) += agregationCoef*(slope-minSlope); - } - offset+=hm->w; - } - } - nbPass--; - } -} -#endif - -void TCOD_heightmap_kernel_transform(TCOD_heightmap_t *hm, int kernelsize, const int *dx, const int *dy, const float *weight, float minLevel,float maxLevel) { - int x,y; - for (x=0; x < hm->w; x++) { - int offset=x; - for (y=0; y < hm->h; y++) { - if ( hm->values[offset] >= minLevel && hm->values[offset] <= maxLevel ) { - float val=0.0f; - float totalWeight=0.0f; - int i; - for (i=0; i < kernelsize; i++ ) { - int nx=x+dx[i]; - int ny=y+dy[i]; - if ( nx >= 0 && nx < hm->w && ny >= 0 && ny < hm->h ) { - val+=weight[i]*GET_VALUE(hm,nx,ny); - totalWeight+=weight[i]; - } - } - hm->values[offset]=val/totalWeight; - } - offset+=hm->w; - } - } - -} - -void TCOD_heightmap_add_voronoi(TCOD_heightmap_t *hm, int nbPoints, int nbCoef, const float *coef,TCOD_random_t rnd) { - typedef struct { - int x,y; - float dist; - } point_t; - point_t *pt; - int i,x,y; - if ( nbPoints <= 0 ) return; - pt=(point_t *)malloc(sizeof(point_t)*nbPoints); - for (i=0; i < nbPoints; i++ ) { - pt[i].x = TCOD_random_get_int(rnd,0,hm->w-1); - pt[i].y = TCOD_random_get_int(rnd,0,hm->h-1); - } - for (x=0; x < hm->w; x++) { - int offset=x; - for (y=0; y < hm->h; y++) { - /* calculate distance to voronoi points */ - for (i=0; i < nbPoints; i++ ) { - pt[i].dist = (float)(pt[i].x-x)*(pt[i].x-x)+(pt[i].y-y)*(pt[i].y-y); - } - for (i=0; i < nbCoef; i++ ) { - /* get closest point */ - float minDist=1E8f; - int idx=-1,j; - for (j=0; j < nbPoints; j++ ) { - if ( pt[j].dist < minDist ) { - idx=j; - minDist=pt[j].dist; - } - } - hm->values[offset]+=coef[i]*pt[idx].dist; - pt[idx].dist=1E8f; - } - offset+= hm->w; - } - } - free(pt); -} - -static void setMPDHeight(TCOD_heightmap_t *hm, TCOD_random_t rnd,int x,int y, float z, float offset); -static void setMDPHeightSquare(TCOD_heightmap_t *hm, TCOD_random_t rnd,int x, int y, int initsz, int sz,float offset); - -void TCOD_heightmap_mid_point_displacement(TCOD_heightmap_t *hm, TCOD_random_t rnd, float roughness) { - int step = 1; - float offset = 1.0f; - int initsz = MIN(hm->w,hm->h)-1; - int sz = initsz; - hm->values[0] = TCOD_random_get_float(rnd,0.0f,1.0f); - hm->values[sz-1] = TCOD_random_get_float(rnd,0.0f,1.0f); - hm->values[(sz-1)*sz] = TCOD_random_get_float(rnd,0.0f,1.0f); - hm->values[sz*sz-1] = TCOD_random_get_float(rnd,0.0f,1.0f); - while (sz > 0) { - int x,y; - /* diamond step */ - for (x=0; x < step; x++ ) { - for (y=0; y < step; y++ ) { - int diamondx = sz / 2 + x * sz; - int diamondy = sz / 2 + y * sz; - float z= GET_VALUE(hm,x*sz,y*sz); - z += GET_VALUE(hm,(x+1)*sz,y*sz); - z += GET_VALUE(hm,(x+1)*sz,(y+1)*sz); - z += GET_VALUE(hm,x*sz,(y+1)*sz); - z *= 0.25f; - setMPDHeight(hm,rnd,diamondx,diamondy,z,offset); - } - } - offset*=roughness; - /* square step */ - for (x=0; x < step; x++ ) { - for (y=0; y < step; y++ ) { - int diamondx = sz / 2 + x * sz; - int diamondy = sz / 2 + y * sz; - /* north */ - setMDPHeightSquare(hm, rnd, diamondx, diamondy-sz/2, initsz,sz/2, offset); - /* south */ - setMDPHeightSquare(hm, rnd, diamondx, diamondy+sz/2, initsz,sz/2, offset); - /* west */ - setMDPHeightSquare(hm, rnd, diamondx-sz/2, diamondy, initsz,sz/2, offset); - /* east */ - setMDPHeightSquare(hm, rnd, diamondx+sz/2, diamondy, initsz,sz/2, offset); - } - } - sz /= 2; - step *= 2; - } -} - -/* private stuff */ -static void setMPDHeight(TCOD_heightmap_t *hm, TCOD_random_t rnd,int x,int y, float z, float offset) { - z += TCOD_random_get_float(rnd,-offset,offset); - GET_VALUE(hm,x,y)=z; -} - -static void setMDPHeightSquare(TCOD_heightmap_t *hm, TCOD_random_t rnd,int x, int y, int initsz, int sz,float offset) { - float z=0; - int count=0; - if ( y >= sz ) { - z += GET_VALUE(hm,x,y-sz); - count++; - } - if ( x >= sz ) { - z += GET_VALUE(hm,x-sz,y); - count++; - } - if ( y+sz < initsz ) { - z += GET_VALUE(hm,x,y+sz); - count++; - } - if ( x+sz < initsz ) { - z += GET_VALUE(hm,x+sz,y); - count++; - } - z /= count; - setMPDHeight(hm,rnd,x,y,z,offset); -} +/* +* libtcod +* Copyright (c) 2008-2018 Jice & Mingos & rmtew +* All rights reserved. +* +* Redistribution and use in source and binary forms, with or without +* modification, are permitted provided that the following conditions are met: +* * Redistributions of source code must retain the above copyright +* notice, this list of conditions and the following disclaimer. +* * Redistributions in binary form must reproduce the above copyright +* notice, this list of conditions and the following disclaimer in the +* documentation and/or other materials provided with the distribution. +* * The name of Jice or Mingos may not be used to endorse or promote +* products derived from this software without specific prior written +* permission. +* +* THIS SOFTWARE IS PROVIDED BY JICE, MINGOS AND RMTEW ``AS IS'' AND ANY +* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED +* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE +* DISCLAIMED. IN NO EVENT SHALL JICE, MINGOS OR RMTEW BE LIABLE FOR ANY +* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES +* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; +* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND +* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS +* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +*/ +#include "heightmap.h" + +#include +#include +#include + +#include "utility.h" +#include "mersenne.h" + +#define GET_VALUE(hm,x,y) (hm)->values[(x)+(y)*(hm)->w] + +TCOD_heightmap_t *TCOD_heightmap_new(int w,int h) { + TCOD_heightmap_t *hm=(TCOD_heightmap_t *)malloc(sizeof(TCOD_heightmap_t)); + hm->values = (float *)calloc(sizeof(float),w*h); + hm->w=w; + hm->h=h; + return hm; +} +void TCOD_heightmap_delete(TCOD_heightmap_t *hm) { + free(hm->values); + free(hm); +} + +void TCOD_heightmap_clear(TCOD_heightmap_t *hm) { + memset(hm->values,0,hm->w*hm->h*sizeof(float)); +} + +float TCOD_heightmap_get_value(const TCOD_heightmap_t *hm, int x, int y) { + return GET_VALUE(hm,x,y); +} + +void TCOD_heightmap_set_value(TCOD_heightmap_t *hm, int x, int y, float value) { + GET_VALUE(hm,x,y)=value; +} + +void TCOD_heightmap_get_minmax(const TCOD_heightmap_t *hm, float *min, float *max) { + float curmax=hm->values[0]; + float curmin=hm->values[0]; + int x,y; + float *value = hm->values; + /* get max and min height */ + for (y=0; y < hm->h; y++) { + for (x=0; x < hm->w; x++) { + float val=*value; + if ( val > curmax ) curmax = val; + else if ( val < curmin ) curmin = val; + value++; + } + } + *min=curmin; + *max=curmax; +} + +void TCOD_heightmap_normalize(TCOD_heightmap_t *hm, float min, float max) { + float curmin,curmax; + int x,y; + float invmax; + float *value = hm->values; + TCOD_heightmap_get_minmax(hm,&curmin,&curmax); + if (curmax - curmin == 0.0f) invmax=0.0f; + else invmax = (max-min) / (curmax-curmin); + /* normalize */ + for (y=0; y < hm->h; y++) { + for (x=0; x < hm->w; x++) { + *value = min + (*value - curmin) * invmax ; + value++; + } + } +} +void TCOD_heightmap_add_hill(TCOD_heightmap_t *hm, float hx, float hy, float hradius, float hheight) { + int x,y; + float hradius2=hradius*hradius; + float coef=hheight / hradius2; + int minx=(int)MAX(0,hx-hradius); + int maxx=(int)MIN(hm->w,hx+hradius); + int miny=(int)MAX(0,hy-hradius); + int maxy=(int)MIN(hm->h,hy+hradius); + for (x=minx; x < maxx; x++) { + float xdist=( x - hx )*( x - hx ); + for (y=miny; y < maxy; y++) { + float z = hradius2 - xdist - (y - hy)*(y - hy); + if ( z > 0.0 ) GET_VALUE(hm,x,y) += z * coef; + } + } +} + +void TCOD_heightmap_dig_hill(TCOD_heightmap_t *hm, float hx, float hy, float hradius, float hheight) { + int x,y; + float hradius2=hradius*hradius; + float coef=hheight / hradius2; + int minx=(int)MAX(0,hx-hradius); + int maxx=(int)MIN(hm->w,hx+hradius); + int miny=(int)MAX(0,hy-hradius); + int maxy=(int)MIN(hm->h,hy+hradius); + for (x=minx; x < maxx; x++) { + float xdist=( x - hx )*( x - hx ); + for (y=miny; y < maxy; y++) { + float dist=xdist + (y - hy)*(y - hy); + if ( dist < hradius2 ) { + float z = (hradius2 - dist) * coef; + if ( hheight > 0.0 ) { + if ( GET_VALUE(hm,x,y) < z ) GET_VALUE(hm,x,y) = z; + } else { + if ( GET_VALUE(hm,x,y) > z ) GET_VALUE(hm,x,y) = z; + } + } + } + } +} + +void TCOD_heightmap_copy(const TCOD_heightmap_t *hm_source,TCOD_heightmap_t *hm_dest) { + if ( hm_source->w != hm_dest->w || hm_source->h != hm_dest->h) return; + memcpy(hm_dest->values,hm_source->values,sizeof(float)*hm_source->w*hm_source->h); +} + +void TCOD_heightmap_add_fbm(TCOD_heightmap_t *hm, TCOD_noise_t noise,float mulx, float muly, float addx, float addy, float octaves, float delta, float scale) { + int x,y; + float xcoef=mulx / hm->w; + float ycoef=muly / hm->h; + float min=1.0f; + float max=0.0f; + for (x=0; x < hm->w; x++) { + float f[2]; + int offset=x; + f[0] = (x + addx) * xcoef; + for (y=0; y < hm->h; y++) { + float value; + f[1] = (y + addy)*ycoef; + value=delta+TCOD_noise_get_fbm(noise,f,octaves)*scale; + hm->values[offset] += value; + if ( value < min ) min = value; + if ( value > max ) max=value; + offset+=hm->w; + } + } +} +void TCOD_heightmap_scale_fbm(TCOD_heightmap_t *hm, TCOD_noise_t noise,float mulx, float muly, float addx, float addy, float octaves, float delta, float scale) { + int x,y; + float xcoef=mulx / hm->w; + float ycoef=muly / hm->h; + for (x=0; x < hm->w; x++) { + float f[2]; + int offset=x; + f[0] = (x + addx) * xcoef; + for (y=0; y < hm->h; y++) { + f[1] = (y + addy)*ycoef; + hm->values[offset] *= (delta+TCOD_noise_get_fbm(noise,f,octaves)*scale); + offset+=hm->w; + } + } +} + +float TCOD_heightmap_get_interpolated_value(const TCOD_heightmap_t *hm, float x, float y) { + int ix = (int) x; + int iy = (int) y; + if ( ix >= hm->w-1 || iy >= hm->h-1 ) { + return GET_VALUE(hm,ix,iy); + } else { + float dx = x - ix; + float dy = y - iy; + float c1 = GET_VALUE(hm,ix,iy); + float c2 = GET_VALUE(hm,ix+1,iy); + float c3 = GET_VALUE(hm,ix,iy+1); + float c4 = GET_VALUE(hm,ix+1,iy+1); + float top = (1.0f-dx)*c1 + dx*c2; + float bottom = (1.0f-dx)*c3 + dx*c4; + return (1.0f-dy)*top + dy*bottom; + } +} + +void TCOD_heightmap_get_normal(const TCOD_heightmap_t *hm, float x, float y, float n[3], float waterLevel) { + float h0,hx,hy,invlen; /* map heights at x,y x+1,y and x,y+1 */ + n[0]=0.0f;n[1]=0.0f;n[2]=1.0f; + if ( x >= hm->w-1 || y >= hm->h-1 ) return; + h0 = TCOD_heightmap_get_interpolated_value(hm,x,y); + if ( h0 < waterLevel ) h0=waterLevel; + hx = TCOD_heightmap_get_interpolated_value(hm,x+1,y); + if ( hx < waterLevel ) hx=waterLevel; + hy = TCOD_heightmap_get_interpolated_value(hm,x,y+1); + if ( hy < waterLevel ) hy=waterLevel; + /* vx = 1 vy = 0 */ + /* 0 1 */ + /* hx-h0 hy-h0 */ + /* vz = vx cross vy */ + n[0] = 255*(h0-hx); + n[1] = 255*(h0-hy); + n[2] = 16.0f; + /* normalize */ + invlen=1.0f / (float)sqrt(n[0]*n[0]+n[1]*n[1]+n[2]*n[2]); + n[0]*=invlen; + n[1]*=invlen; + n[2]*=invlen; +} + +void TCOD_heightmap_dig_bezier(TCOD_heightmap_t *hm, int px[4], int py[4], float startRadius, float startDepth, float endRadius, float endDepth) { + int xFrom=px[0]; + int yFrom=py[0]; + float t; + for ( t=0.0f;t <= 1.0f ; t += 0.001f ) { + int xTo,yTo; + float it=1.0f-t; + xTo=(int)(px[0]*it*it*it + 3*px[1]*t*it*it + 3*px[2]*t*t*it + px[3]*t*t*t); + yTo=(int)(py[0]*it*it*it + 3*py[1]*t*it*it + 3*py[2]*t*t*it + py[3]*t*t*t); + if ( xTo != xFrom || yTo != yFrom ) { + float radius=startRadius+(endRadius-startRadius)*t; + float depth=startDepth+(endDepth-startDepth)*t; + TCOD_heightmap_dig_hill(hm,(float)xTo,(float)yTo,radius,depth); + xFrom=xTo; + yFrom=yTo; + } + } +} + +bool TCOD_heightmap_has_land_on_border(const TCOD_heightmap_t *hm, float waterLevel) { + int x,y; + for (x=0; x < hm->w; x++) { + if ( GET_VALUE(hm,x,0) > waterLevel + || GET_VALUE(hm,x,hm->h-1) > waterLevel ) { + return true; + } + } + for (y=0; y < hm->h; y++) { + if ( GET_VALUE(hm,0,y) > waterLevel + || GET_VALUE(hm,hm->w-1,y) > waterLevel ) { + return true; + } + } + return false; +} + +void TCOD_heightmap_islandify(TCOD_heightmap_t *hm, float seaLevel,TCOD_random_t rnd) { + /* TODO */ +} + +void TCOD_heightmap_add(TCOD_heightmap_t *hm, float value) { + int i; + for (i=0; i < hm->w*hm->h; i++ ) hm->values[i]+=value; +} + +int TCOD_heightmap_count_cells(const TCOD_heightmap_t *hm, float min, float max) { + int count=0,i; + for (i=0; i < hm->w*hm->h; i++ ) if (hm->values[i] >= min && hm->values[i] <= max) count++; + return count; +} + +void TCOD_heightmap_scale(TCOD_heightmap_t *hm, float value) { + int i; + for (i=0; i < hm->w*hm->h; i++ ) hm->values[i]*=value; +} + +void TCOD_heightmap_clamp(TCOD_heightmap_t *hm, float min, float max) { + int i; + for (i=0; i < hm->w*hm->h; i++ ) { + hm->values[i]=CLAMP(min,max,hm->values[i]); + } +} + +void TCOD_heightmap_lerp_hm(const TCOD_heightmap_t *hm1, const TCOD_heightmap_t *hm2, TCOD_heightmap_t *hmres, float coef) { + int i; + if ( hm1->w != hm2->w || hm1->h != hm2->h + || hm1->w != hmres->w || hm1->h != hmres->h + ) { + return; + } + for (i=0; i < hm1->w*hm1->h; i++ ) { + hmres->values[i]=hm1->values[i]+(hm2->values[i]-hm1->values[i])*coef; + } +} + +void TCOD_heightmap_add_hm(const TCOD_heightmap_t *hm1, const TCOD_heightmap_t *hm2, TCOD_heightmap_t *hmres) { + int i; + if ( hm1->w != hm2->w || hm1->h != hm2->h + || hm1->w != hmres->w || hm1->h != hmres->h + ) { + return; + } + for (i=0; i < hm1->w*hm1->h; i++ ) { + hmres->values[i]=hm1->values[i]+hm2->values[i]; + } +} + +void TCOD_heightmap_multiply_hm(const TCOD_heightmap_t *hm1, const TCOD_heightmap_t *hm2, TCOD_heightmap_t *hmres) { + int i; + if ( hm1->w != hm2->w || hm1->h != hm2->h + || hm1->w != hmres->w || hm1->h != hmres->h + ) { + return; + } + for (i=0; i < hm1->w*hm1->h; i++ ) { + hmres->values[i]=hm1->values[i]*hm2->values[i]; + } +} + + +float TCOD_heightmap_get_slope(const TCOD_heightmap_t *hm, int x, int y) { + static int dix[8]={-1,0,1,-1,1,-1,0,1}; + static int diy[8]={-1,-1,-1,0,0,1,1,1}; + float mindy=0.0f,maxdy=0.0f; + float v=GET_VALUE(hm,x,y); + int i; + for (i=0; i < 8; i++ ) { + int nx=x+dix[i]; + int ny=y+diy[i]; + if ( nx >= 0 && nx < hm->w && ny >= 0 && ny < hm->h ) { + float nslope=(GET_VALUE(hm,nx,ny)-v); + if ( nslope > maxdy ) { + maxdy=nslope; + } else if ( nslope < mindy ) { + mindy=nslope; + } + } + } + return (float)atan2(maxdy+mindy,1.0f); +} + +void TCOD_heightmap_rain_erosion(TCOD_heightmap_t *hm, int nbDrops,float erosionCoef,float agregationCoef,TCOD_random_t rnd) { + while ( nbDrops > 0 ) { + int curx=TCOD_random_get_int(rnd,0,hm->w-1); + int cury=TCOD_random_get_int(rnd,0,hm->h-1); + static int dx[8]={-1,0,1,-1,1,-1,0,1}; + static int dy[8]={-1,-1,-1,0,0,1,1,1}; + float slope=0.0f; + float sediment=0.0f; + do { + int nextx=0,nexty=0,i; + float v=GET_VALUE(hm,curx,cury); + /* calculate slope at x,y */ + slope=0.0f; + for (i=0; i < 8; i++ ) { + int nx=curx+dx[i]; + int ny=cury+dy[i]; + if ( nx >= 0 && nx < hm->w && ny >= 0 && ny < hm->h ) { + float nslope=v-GET_VALUE(hm,nx,ny); + if ( nslope > slope ) { + slope=nslope; + nextx=nx; + nexty=ny; + } + } + } + if ( slope > 0.0f ) { +/* GET_VALUE(hm,curx,cury) *= 1.0f - (erosionCoef * slope); */ + GET_VALUE(hm,curx,cury) -= erosionCoef * slope; + curx=nextx; + cury=nexty; + sediment+=slope; + } else { +/* GET_VALUE(hm,curx,cury) *= 1.0f + (agregationCoef*sediment); */ + GET_VALUE(hm,curx,cury) += agregationCoef*sediment; + } + } while ( slope > 0.0f ); + nbDrops--; + } +} + +#if 0 +static void setMPDHeight(TCOD_heightmap_t *hm, TCOD_random_t rnd,int x,int y, float z, float offset); +static void setMDPHeightSquare(TCOD_heightmap_t *hm, TCOD_random_t rnd,int x, int y, int initsz, int sz,float offset); + +void TCOD_heightmap_heat_erosion(TCOD_heightmap_t *hm, int nbPass,float minSlope,float erosionCoef,float agregationCoef,TCOD_random_t rnd) { + int x; + while ( nbPass > 0 ) { + for (x=0; x < hm->w; x++) { + int offset=x,y; + for (y=0; y < hm->h; y++) { + static int dx[8]={-1,0,1,-1,1,-1,0,1}; + static int dy[8]={-1,-1,-1,0,0,1,1,1}; + int nextx=0,nexty=0,i; + float v=hm->values[offset]; + /* calculate slope at x,y */ + float slope=0.0f; + for (i=0; i < 8; i++ ) { /* 4 : von neumann neighbourhood 8 : moore neighbourhood */ + int nx=x+dx[i]; + int ny=y+dy[i]; + if ( nx >= 0 && nx < hm->w && ny >= 0 && ny < hm->h ) { + float nslope=v-GET_VALUE(hm,nx,ny); + if ( nslope > slope ) { + slope=nslope; + nextx=nx; + nexty=ny; + } + } + } + if ( slope > minSlope ) { + GET_VALUE(hm,x,y) -= erosionCoef*(slope-minSlope); + GET_VALUE(hm,nextx,nexty) += agregationCoef*(slope-minSlope); + } + offset+=hm->w; + } + } + nbPass--; + } +} +#endif + +void TCOD_heightmap_kernel_transform(TCOD_heightmap_t *hm, int kernelsize, const int *dx, const int *dy, const float *weight, float minLevel,float maxLevel) { + int x,y; + for (x=0; x < hm->w; x++) { + int offset=x; + for (y=0; y < hm->h; y++) { + if ( hm->values[offset] >= minLevel && hm->values[offset] <= maxLevel ) { + float val=0.0f; + float totalWeight=0.0f; + int i; + for (i=0; i < kernelsize; i++ ) { + int nx=x+dx[i]; + int ny=y+dy[i]; + if ( nx >= 0 && nx < hm->w && ny >= 0 && ny < hm->h ) { + val+=weight[i]*GET_VALUE(hm,nx,ny); + totalWeight+=weight[i]; + } + } + hm->values[offset]=val/totalWeight; + } + offset+=hm->w; + } + } + +} + +void TCOD_heightmap_add_voronoi(TCOD_heightmap_t *hm, int nbPoints, int nbCoef, const float *coef,TCOD_random_t rnd) { + typedef struct { + int x,y; + float dist; + } point_t; + point_t *pt; + int i,x,y; + if ( nbPoints <= 0 ) return; + pt=(point_t *)malloc(sizeof(point_t)*nbPoints); + for (i=0; i < nbPoints; i++ ) { + pt[i].x = TCOD_random_get_int(rnd,0,hm->w-1); + pt[i].y = TCOD_random_get_int(rnd,0,hm->h-1); + } + for (x=0; x < hm->w; x++) { + int offset=x; + for (y=0; y < hm->h; y++) { + /* calculate distance to voronoi points */ + for (i=0; i < nbPoints; i++ ) { + pt[i].dist = (float)(pt[i].x-x)*(pt[i].x-x)+(pt[i].y-y)*(pt[i].y-y); + } + for (i=0; i < nbCoef; i++ ) { + /* get closest point */ + float minDist=1E8f; + int idx=-1,j; + for (j=0; j < nbPoints; j++ ) { + if ( pt[j].dist < minDist ) { + idx=j; + minDist=pt[j].dist; + } + } + hm->values[offset]+=coef[i]*pt[idx].dist; + pt[idx].dist=1E8f; + } + offset+= hm->w; + } + } + free(pt); +} + +static void setMPDHeight(TCOD_heightmap_t *hm, TCOD_random_t rnd,int x,int y, float z, float offset); +static void setMDPHeightSquare(TCOD_heightmap_t *hm, TCOD_random_t rnd,int x, int y, int initsz, int sz,float offset); + +void TCOD_heightmap_mid_point_displacement(TCOD_heightmap_t *hm, TCOD_random_t rnd, float roughness) { + int step = 1; + float offset = 1.0f; + int initsz = MIN(hm->w,hm->h)-1; + int sz = initsz; + hm->values[0] = TCOD_random_get_float(rnd,0.0f,1.0f); + hm->values[sz-1] = TCOD_random_get_float(rnd,0.0f,1.0f); + hm->values[(sz-1)*sz] = TCOD_random_get_float(rnd,0.0f,1.0f); + hm->values[sz*sz-1] = TCOD_random_get_float(rnd,0.0f,1.0f); + while (sz > 0) { + int x,y; + /* diamond step */ + for (x=0; x < step; x++ ) { + for (y=0; y < step; y++ ) { + int diamondx = sz / 2 + x * sz; + int diamondy = sz / 2 + y * sz; + float z= GET_VALUE(hm,x*sz,y*sz); + z += GET_VALUE(hm,(x+1)*sz,y*sz); + z += GET_VALUE(hm,(x+1)*sz,(y+1)*sz); + z += GET_VALUE(hm,x*sz,(y+1)*sz); + z *= 0.25f; + setMPDHeight(hm,rnd,diamondx,diamondy,z,offset); + } + } + offset*=roughness; + /* square step */ + for (x=0; x < step; x++ ) { + for (y=0; y < step; y++ ) { + int diamondx = sz / 2 + x * sz; + int diamondy = sz / 2 + y * sz; + /* north */ + setMDPHeightSquare(hm, rnd, diamondx, diamondy-sz/2, initsz,sz/2, offset); + /* south */ + setMDPHeightSquare(hm, rnd, diamondx, diamondy+sz/2, initsz,sz/2, offset); + /* west */ + setMDPHeightSquare(hm, rnd, diamondx-sz/2, diamondy, initsz,sz/2, offset); + /* east */ + setMDPHeightSquare(hm, rnd, diamondx+sz/2, diamondy, initsz,sz/2, offset); + } + } + sz /= 2; + step *= 2; + } +} + +/* private stuff */ +static void setMPDHeight(TCOD_heightmap_t *hm, TCOD_random_t rnd,int x,int y, float z, float offset) { + z += TCOD_random_get_float(rnd,-offset,offset); + GET_VALUE(hm,x,y)=z; +} + +static void setMDPHeightSquare(TCOD_heightmap_t *hm, TCOD_random_t rnd,int x, int y, int initsz, int sz,float offset) { + float z=0; + int count=0; + if ( y >= sz ) { + z += GET_VALUE(hm,x,y-sz); + count++; + } + if ( x >= sz ) { + z += GET_VALUE(hm,x-sz,y); + count++; + } + if ( y+sz < initsz ) { + z += GET_VALUE(hm,x,y+sz); + count++; + } + if ( x+sz < initsz ) { + z += GET_VALUE(hm,x+sz,y); + count++; + } + z /= count; + setMPDHeight(hm,rnd,x,y,z,offset); +} diff --git a/tcod_sys/libtcod/src/image.cpp b/tcod_sys/libtcod/src/libtcod/image.cpp similarity index 93% rename from tcod_sys/libtcod/src/image.cpp rename to tcod_sys/libtcod/src/libtcod/image.cpp index ae8e916d1..bc5827509 100644 --- a/tcod_sys/libtcod/src/image.cpp +++ b/tcod_sys/libtcod/src/libtcod/image.cpp @@ -1,134 +1,134 @@ -/* -* libtcod -* Copyright (c) 2008-2018 Jice & Mingos & rmtew -* All rights reserved. -* -* Redistribution and use in source and binary forms, with or without -* modification, are permitted provided that the following conditions are met: -* * Redistributions of source code must retain the above copyright -* notice, this list of conditions and the following disclaimer. -* * Redistributions in binary form must reproduce the above copyright -* notice, this list of conditions and the following disclaimer in the -* documentation and/or other materials provided with the distribution. -* * The name of Jice or Mingos may not be used to endorse or promote -* products derived from this software without specific prior written -* permission. -* -* THIS SOFTWARE IS PROVIDED BY JICE, MINGOS AND RMTEW ``AS IS'' AND ANY -* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED -* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE -* DISCLAIMED. IN NO EVENT SHALL JICE, MINGOS OR RMTEW BE LIABLE FOR ANY -* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES -* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; -* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND -* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS -* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. -*/ -#include - -#ifdef TCOD_IMAGE_SUPPORT - -TCODImage::TCODImage(const char *filename) : deleteData(true) { - data=(void *)TCOD_image_load(filename); -} - -TCODImage::TCODImage(int width, int height) : deleteData(true) { - data=(void *)TCOD_image_new(width,height); -} - -#ifdef TCOD_CONSOLE_SUPPORT -TCODImage::TCODImage(const TCODConsole *con) { - data=(void *)TCOD_image_from_console(con->data); -} -#endif - -void TCODImage::clear(const TCODColor col) { - TCOD_color_t ccol; - ccol.r=col.r; - ccol.g=col.g; - ccol.b=col.b; - TCOD_image_clear(data,ccol); -} - -void TCODImage::getSize(int *w,int *h) const { - TCOD_image_get_size(data,w,h); -} - -TCODImage::~TCODImage() { - if ( deleteData ) TCOD_image_delete(data); -} - -TCODColor TCODImage::getPixel(int x, int y) const { - return TCOD_image_get_pixel(data,x,y); -} - -int TCODImage::getAlpha(int x,int y) const { - return TCOD_image_get_alpha(data,x,y); -} - -TCODColor TCODImage::getMipmapPixel(float x0,float y0, float x1, float y1) { - return TCOD_image_get_mipmap_pixel(data,x0,y0,x1,y1); -} - -void TCODImage::putPixel(int x, int y, const TCODColor col) { - TCOD_color_t ccol = {col.r,col.g,col.b}; - TCOD_image_put_pixel(data,x,y,ccol); -} - -#ifdef TCOD_CONSOLE_SUPPORT -void TCODImage::blit(TCODConsole *console, float x, float y, TCOD_bkgnd_flag_t bkgnd_flag, float scalex, float scaley, float angle) const { - TCOD_image_blit(data,console->data,x,y,bkgnd_flag,scalex,scaley,angle); -} - -void TCODImage::blitRect(TCODConsole *console, int x, int y, int w, int h, TCOD_bkgnd_flag_t bkgnd_flag) const { - TCOD_image_blit_rect(data,console->data,x,y,w,h,bkgnd_flag); -} -#endif /* TCOD_CONSOLE_SUPPORT */ - -void TCODImage::save(const char *filename) const { - TCOD_image_save(data,filename); -} - -void TCODImage::setKeyColor(const TCODColor keyColor) { - TCOD_color_t ccol = {keyColor.r,keyColor.g,keyColor.b}; - TCOD_image_set_key_color(data,ccol); -} - -bool TCODImage::isPixelTransparent(int x, int y) const { - return TCOD_image_is_pixel_transparent(data,x,y) != 0; -} - -#ifdef TCOD_CONSOLE_SUPPORT -void TCODImage::refreshConsole(const TCODConsole *console) { - TCOD_image_refresh_console(data,console->data); -} -#endif /* TCOD_CONSOLE_SUPPORT */ - -void TCODImage::invert() { - TCOD_image_invert(data); -} - -void TCODImage::hflip() { - TCOD_image_hflip(data); -} - -void TCODImage::rotate90(int numRotations) { - TCOD_image_rotate90(data,numRotations); -} - -void TCODImage::vflip() { - TCOD_image_vflip(data); -} - -void TCODImage::scale(int neww, int newh) { - TCOD_image_scale(data,neww,newh); -} - -#ifdef TCOD_CONSOLE_SUPPORT -void TCODImage::blit2x(TCODConsole *dest, int dx, int dy, int sx, int sy, int w, int h) const { - TCOD_image_blit_2x(data,dest->data,dx,dy,sx,sy,w,h); -} -#endif /* TCOD_CONSOLE_SUPPORT */ - -#endif /* TCOD_IMAGE_SUPPORT */ +/* +* libtcod +* Copyright (c) 2008-2018 Jice & Mingos & rmtew +* All rights reserved. +* +* Redistribution and use in source and binary forms, with or without +* modification, are permitted provided that the following conditions are met: +* * Redistributions of source code must retain the above copyright +* notice, this list of conditions and the following disclaimer. +* * Redistributions in binary form must reproduce the above copyright +* notice, this list of conditions and the following disclaimer in the +* documentation and/or other materials provided with the distribution. +* * The name of Jice or Mingos may not be used to endorse or promote +* products derived from this software without specific prior written +* permission. +* +* THIS SOFTWARE IS PROVIDED BY JICE, MINGOS AND RMTEW ``AS IS'' AND ANY +* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED +* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE +* DISCLAIMED. IN NO EVENT SHALL JICE, MINGOS OR RMTEW BE LIABLE FOR ANY +* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES +* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; +* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND +* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS +* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +*/ +#include "image.hpp" + +#ifdef TCOD_IMAGE_SUPPORT + +TCODImage::TCODImage(const char *filename) : deleteData(true) { + data = TCOD_image_load(filename); +} + +TCODImage::TCODImage(int width, int height) : deleteData(true) { + data = TCOD_image_new(width,height); +} + +#ifdef TCOD_CONSOLE_SUPPORT +TCODImage::TCODImage(const TCODConsole *con) { + data = TCOD_image_from_console(con->data); +} +#endif + +void TCODImage::clear(const TCODColor col) { + TCOD_color_t ccol; + ccol.r=col.r; + ccol.g=col.g; + ccol.b=col.b; + TCOD_image_clear(data,ccol); +} + +void TCODImage::getSize(int *w,int *h) const { + TCOD_image_get_size(data,w,h); +} + +TCODImage::~TCODImage() { + if ( deleteData ) TCOD_image_delete(data); +} + +TCODColor TCODImage::getPixel(int x, int y) const { + return TCOD_image_get_pixel(data,x,y); +} + +int TCODImage::getAlpha(int x,int y) const { + return TCOD_image_get_alpha(data,x,y); +} + +TCODColor TCODImage::getMipmapPixel(float x0,float y0, float x1, float y1) { + return TCOD_image_get_mipmap_pixel(data,x0,y0,x1,y1); +} + +void TCODImage::putPixel(int x, int y, const TCODColor col) { + TCOD_color_t ccol = {col.r,col.g,col.b}; + TCOD_image_put_pixel(data,x,y,ccol); +} + +#ifdef TCOD_CONSOLE_SUPPORT +void TCODImage::blit(TCODConsole *console, float x, float y, TCOD_bkgnd_flag_t bkgnd_flag, float scalex, float scaley, float angle) const { + TCOD_image_blit(data,console->data,x,y,bkgnd_flag,scalex,scaley,angle); +} + +void TCODImage::blitRect(TCODConsole *console, int x, int y, int w, int h, TCOD_bkgnd_flag_t bkgnd_flag) const { + TCOD_image_blit_rect(data,console->data,x,y,w,h,bkgnd_flag); +} +#endif /* TCOD_CONSOLE_SUPPORT */ + +void TCODImage::save(const char *filename) const { + TCOD_image_save(data,filename); +} + +void TCODImage::setKeyColor(const TCODColor keyColor) { + TCOD_color_t ccol = {keyColor.r,keyColor.g,keyColor.b}; + TCOD_image_set_key_color(data,ccol); +} + +bool TCODImage::isPixelTransparent(int x, int y) const { + return TCOD_image_is_pixel_transparent(data,x,y) != 0; +} + +#ifdef TCOD_CONSOLE_SUPPORT +void TCODImage::refreshConsole(const TCODConsole *console) { + TCOD_image_refresh_console(data,console->data); +} +#endif /* TCOD_CONSOLE_SUPPORT */ + +void TCODImage::invert() { + TCOD_image_invert(data); +} + +void TCODImage::hflip() { + TCOD_image_hflip(data); +} + +void TCODImage::rotate90(int numRotations) { + TCOD_image_rotate90(data,numRotations); +} + +void TCODImage::vflip() { + TCOD_image_vflip(data); +} + +void TCODImage::scale(int neww, int newh) { + TCOD_image_scale(data,neww,newh); +} + +#ifdef TCOD_CONSOLE_SUPPORT +void TCODImage::blit2x(TCODConsole *dest, int dx, int dy, int sx, int sy, int w, int h) const { + TCOD_image_blit_2x(data,dest->data,dx,dy,sx,sy,w,h); +} +#endif /* TCOD_CONSOLE_SUPPORT */ + +#endif /* TCOD_IMAGE_SUPPORT */ diff --git a/tcod_sys/libtcod/include/image.h b/tcod_sys/libtcod/src/libtcod/image.h similarity index 97% rename from tcod_sys/libtcod/include/image.h rename to tcod_sys/libtcod/src/libtcod/image.h index 3a81c5717..0d2212d04 100644 --- a/tcod_sys/libtcod/include/image.h +++ b/tcod_sys/libtcod/src/libtcod/image.h @@ -28,7 +28,7 @@ #ifndef _TCOD_IMAGE_H #define _TCOD_IMAGE_H -#include "libtcod_portability.h" +#include "portability.h" #include "color.h" #ifdef TCOD_IMAGE_SUPPORT @@ -38,7 +38,9 @@ #ifdef __cplusplus extern "C" { #endif -typedef void *TCOD_image_t; +struct TCOD_Image; + +typedef struct TCOD_Image *TCOD_image_t; TCODLIB_API TCOD_image_t TCOD_image_new(int width, int height); #ifdef TCOD_CONSOLE_SUPPORT diff --git a/tcod_sys/libtcod/include/image.hpp b/tcod_sys/libtcod/src/libtcod/image.hpp similarity index 99% rename from tcod_sys/libtcod/include/image.hpp rename to tcod_sys/libtcod/src/libtcod/image.hpp index ad90548ff..3cd960b0f 100644 --- a/tcod_sys/libtcod/include/image.hpp +++ b/tcod_sys/libtcod/src/libtcod/image.hpp @@ -457,7 +457,7 @@ public : protected : friend class TCODLIB_API TCODSystem; friend class TCODLIB_API TCODZip; - void *data; + struct TCOD_Image *data; bool deleteData; }; diff --git a/tcod_sys/libtcod/src/image_c.c b/tcod_sys/libtcod/src/libtcod/image_c.c similarity index 95% rename from tcod_sys/libtcod/src/image_c.c rename to tcod_sys/libtcod/src/libtcod/image_c.c index 89f89cd42..4a8348b3a 100644 --- a/tcod_sys/libtcod/src/image_c.c +++ b/tcod_sys/libtcod/src/libtcod/image_c.c @@ -1,866 +1,868 @@ -/* -* libtcod -* Copyright (c) 2008-2018 Jice & Mingos & rmtew -* All rights reserved. -* -* Redistribution and use in source and binary forms, with or without -* modification, are permitted provided that the following conditions are met: -* * Redistributions of source code must retain the above copyright -* notice, this list of conditions and the following disclaimer. -* * Redistributions in binary form must reproduce the above copyright -* notice, this list of conditions and the following disclaimer in the -* documentation and/or other materials provided with the distribution. -* * The name of Jice or Mingos may not be used to endorse or promote -* products derived from this software without specific prior written -* permission. -* -* THIS SOFTWARE IS PROVIDED BY JICE, MINGOS AND RMTEW ``AS IS'' AND ANY -* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED -* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE -* DISCLAIMED. IN NO EVENT SHALL JICE, MINGOS OR RMTEW BE LIABLE FOR ANY -* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES -* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; -* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND -* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS -* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. -*/ -#include "libtcod_portability.h" -#ifdef TCOD_IMAGE_SUPPORT -#include - -#include -#include -#include -#include - -#include -#include -#include - -typedef struct { - int width,height; - float fwidth,fheight; - TCOD_color_t *buf; - bool dirty; -} mipmap_t; - -typedef struct { - void *sys_img; - int nb_mipmaps; - mipmap_t *mipmaps; - TCOD_color_t key_color; - bool has_key_color; -} image_data_t; - -/* -Internal libtcod optimisation, direct colour manipulation in the images primary mipmap. -*/ -TCOD_color_t *TCOD_image_get_colors(TCOD_image_t *image) { - image_data_t *img = ((image_data_t *)image); - return img->mipmaps[0].buf; -} - -void TCOD_image_get_key_data(TCOD_image_t image, bool *has_key_color, TCOD_color_t *key_color) { - image_data_t *img = ((image_data_t *)image); - *has_key_color = img->has_key_color; - *key_color = img->key_color; -} - -void TCOD_image_invalidate_mipmaps(TCOD_image_t *image) { - int i; - image_data_t *img = ((image_data_t *)image); - for (i = 1; i < img->nb_mipmaps; i++) { - img->mipmaps[i].dirty = true; - } -} - -static int TCOD_image_get_mipmap_levels(int width, int height) { - int curw=width; - int curh=height; - int nb_mipmap=0; - while ( curw > 0 && curh > 0 ) { - nb_mipmap++; - curw >>= 1; - curh >>= 1; - } - return nb_mipmap; -} - -static void TCOD_image_generate_mip(image_data_t *img, int mip) { - mipmap_t *orig=&img->mipmaps[0]; - mipmap_t *cur =&img->mipmaps[mip]; - int x,y; - if (! cur->buf) { - cur->buf=(TCOD_color_t *)calloc(sizeof(TCOD_color_t),cur->width*cur->height); - } - cur->dirty=false; - for (x=0; x < cur->width; x++) { - for (y=0; y < cur->height; y++) { - int r=0,g=0,b=0, count=0; - int sx,sy; - TCOD_color_t *col; - for (sx=(x << mip); sx < ((x+1)<width; - count++; - r+=orig->buf[offset].r; - g+=orig->buf[offset].g; - b+=orig->buf[offset].b; - } - } - r /= count; - g /= count; - b /= count; - col = &cur->buf[x+y*cur->width]; - col->r=r; - col->g=g; - col->b=b; - } - } -} - -/* -Internal way of copying rendering fg/bg color frame data. -*/ -bool TCOD_image_mipmap_copy_internal(TCOD_image_t srcImage, TCOD_image_t dstImage) { - int i; - image_data_t *img_src = (image_data_t *)srcImage; - image_data_t *img_dst = (image_data_t *)dstImage; - if (!img_src->mipmaps || img_src->sys_img || !img_dst->mipmaps || img_dst->sys_img) /* Both internal images. */ - return false; - if (img_src->mipmaps[0].width != img_dst->mipmaps[0].width || img_src->mipmaps[0].height != img_dst->mipmaps[0].height) - return false; - /* Copy all mipmaps? */ - img_dst->mipmaps[0].dirty = img_src->mipmaps[0].dirty; - memcpy(img_dst->mipmaps[0].buf, img_src->mipmaps[0].buf, sizeof(TCOD_color_t)*(img_src->mipmaps[0].width)*(img_src->mipmaps[0].height)); - for (i = 1; i < img_src->nb_mipmaps; i++) - img_dst->mipmaps[i].dirty = true; - return true; -} - -static void TCOD_image_init_mipmaps(image_data_t *img) { - int w,h,i,x,y; - float fw,fh; - if (! img->sys_img ) return; - TCOD_sys_get_image_size(img->sys_img,&w,&h); - img->nb_mipmaps=TCOD_image_get_mipmap_levels(w,h); - img->mipmaps = (mipmap_t *)calloc(sizeof(mipmap_t),img->nb_mipmaps); - img->mipmaps[0].buf = (TCOD_color_t *)calloc(sizeof(TCOD_color_t),w*h); - for (x=0; x < w; x++) { - for (y=0;y < h; y++) { - img->mipmaps[0].buf[x+y*w]=TCOD_sys_get_image_pixel(img->sys_img,x,y); - } - } - fw=(float)w; - fh=(float)h; - for ( i=0; i < img->nb_mipmaps; i++) { - img->mipmaps[i].width=w; - img->mipmaps[i].height=h; - img->mipmaps[i].fwidth=fw; - img->mipmaps[i].fheight=fh; - img->mipmaps[i].dirty=true; - w >>= 1; - h >>= 1; - fw *= 0.5f; - fh *= 0.5f; - } - img->mipmaps[0].dirty=false; -} - -void TCOD_image_clear(TCOD_image_t image, TCOD_color_t color) { - int i; - image_data_t *img=(image_data_t *)image; - if ( !img->mipmaps && !img->sys_img) return; /* no image data */ - if ( ! img->mipmaps ) { - TCOD_image_init_mipmaps(img); - } - for (i=0; i< img->mipmaps[0].width*img->mipmaps[0].height; i++) { - img->mipmaps[0].buf[i] = color; - } - for ( i=1; i < img->nb_mipmaps; i++) { - img->mipmaps[i].dirty=true; - } -} - -TCOD_image_t TCOD_image_new(int width, int height) { - int i; - float fw,fh; - image_data_t *ret=(image_data_t *)calloc(sizeof(image_data_t),1); - ret->nb_mipmaps=TCOD_image_get_mipmap_levels(width,height); - ret->mipmaps = (mipmap_t *)calloc(sizeof(mipmap_t),ret->nb_mipmaps); - ret->mipmaps[0].buf = (TCOD_color_t *)calloc(sizeof(TCOD_color_t),width*height); - - for (i=0; i< width*height; i++) { - ret->mipmaps[0].buf[i] = TCOD_black; - } - fw=(float)width; - fh=(float)height; - for ( i=0; i < ret->nb_mipmaps; i++) { - ret->mipmaps[i].width=width; - ret->mipmaps[i].height=height; - ret->mipmaps[i].fwidth=fw; - ret->mipmaps[i].fheight=fh; - width >>= 1; - height >>= 1; - fw *= 0.5f; - fh *= 0.5f; - } - return (TCOD_image_t)ret; -} - -TCOD_image_t TCOD_image_load(const char *filename) { - image_data_t *ret=(image_data_t *)calloc(sizeof(image_data_t),1); - ret->sys_img=TCOD_sys_load_image(filename); - return (TCOD_image_t)ret; -} - -void TCOD_image_get_size(TCOD_image_t image, int *w,int *h) { - image_data_t *img=(image_data_t *)image; - if ( !img->mipmaps && !img->sys_img) return; /* no image data */ - if ( img->mipmaps ) { - *w = img->mipmaps[0].width; - *h = img->mipmaps[0].height; - } else { - TCOD_sys_get_image_size(img->sys_img,w,h); - } -} - -TCOD_color_t TCOD_image_get_pixel(TCOD_image_t image,int x, int y) { - image_data_t *img=(image_data_t *)image; - if ( !img->mipmaps && !img->sys_img) return TCOD_black; /* no image data */ - if ( img->mipmaps ) { - if ( x >= 0 && x < img->mipmaps[0].width - && y >= 0 && y < img->mipmaps[0].height ) { - return img->mipmaps[0].buf[x+y*img->mipmaps[0].width]; - } else { - return TCOD_black; - } - } else { - return TCOD_sys_get_image_pixel(img->sys_img,x,y); - } -} - -int TCOD_image_get_alpha(TCOD_image_t image,int x, int y) { - image_data_t *img=(image_data_t *)image; - if ( img->sys_img ) { - return TCOD_sys_get_image_alpha(img->sys_img,x,y); - } else return 255; -} - -TCOD_color_t TCOD_image_get_mipmap_pixel(TCOD_image_t image,float x0,float y0, float x1, float y1) { - int texel_xsize,texel_ysize, texel_size, texel_x,texel_y; - int cur_size=1; - int mip=0; - image_data_t *img=(image_data_t *)image; - if ( !img->mipmaps && !img->sys_img) return TCOD_black; /* no image data */ - if (!img->mipmaps) TCOD_image_init_mipmaps(img); - texel_xsize=(int)(x1-x0); - texel_ysize=(int)(y1-y0); - texel_size=texel_xsize < texel_ysize ? texel_ysize : texel_xsize; - while ( mip < img->nb_mipmaps-1 && cur_size < texel_size ) { - mip++; - cur_size <<= 1; - } - if ( mip > 0 ) mip --; - texel_x=(int)(x0*(img->mipmaps[mip].width)/img->mipmaps[0].fwidth); - texel_y=(int)(y0*(img->mipmaps[mip].height)/img->mipmaps[0].fheight); - - if (img->mipmaps[mip].buf == NULL || img->mipmaps[mip].dirty) { - TCOD_image_generate_mip(img,mip); - } - if ( texel_x < 0 || texel_y < 0 || texel_x >= img->mipmaps[mip].width || texel_y >= img->mipmaps[mip].height ) - return TCOD_black; - return img->mipmaps[mip].buf[texel_x+texel_y*img->mipmaps[mip].width]; -} - -void TCOD_image_put_pixel(TCOD_image_t image,int x, int y,TCOD_color_t col) { - image_data_t *img=(image_data_t *)image; - if ( !img->mipmaps && !img->sys_img) return; /* no image data */ - if ( ! img->mipmaps ) { - TCOD_image_init_mipmaps(img); - } - if ( x >= 0 && x < img->mipmaps[0].width - && y >= 0 && y < img->mipmaps[0].height ) { - int mip; - img->mipmaps[0].buf[x+y*img->mipmaps[0].width] = col; - for (mip=1; mip < img->nb_mipmaps; mip++) { - img->mipmaps[mip].dirty=true; - } - } -} - -void TCOD_image_delete_internal(TCOD_image_t image) { - image_data_t *img=(image_data_t *)image; - if ( img->mipmaps ) { - int i; - for ( i=0; i < img->nb_mipmaps; i++) { - if ( img->mipmaps[i].buf ) free(img->mipmaps[i].buf); - } - free(img->mipmaps); - } - if ( img->sys_img ) { -#ifndef TCOD_BARE - TCOD_sys_delete_bitmap(img->sys_img); -#endif - } -} - -void TCOD_image_delete(TCOD_image_t image) { - TCOD_image_delete_internal(image); - free(image); -} - -bool TCOD_image_is_pixel_transparent(TCOD_image_t image, int x, int y) { - image_data_t *img=(image_data_t *)image; - TCOD_color_t col=TCOD_image_get_pixel(image,x,y); - if ( img->has_key_color && img->key_color.r == col.r - && img->key_color.g == col.g && img->key_color.b == col.b ) { - return true; - } - if ( TCOD_image_get_alpha(image,x,y) == 0 ) return true; - return false; -} - -#ifdef TCOD_CONSOLE_SUPPORT - -void TCOD_image_blit(TCOD_image_t image, TCOD_console_t console, float x, float y, - TCOD_bkgnd_flag_t bkgnd_flag, float scalex, float scaley, float angle) { - int width,height; - float rx,ry; - image_data_t *img=(image_data_t *)image; - if ( scalex == 0.0f || scaley == 0.0f || bkgnd_flag == TCOD_BKGND_NONE ) return; - TCOD_image_get_size(image,&width,&height); - rx = x - width * 0.5f; - ry = y - height * 0.5f; - if ( scalex == 1.0f && scaley == 1.0f && angle == 0.0f && rx == ((int)rx) && ry == ((int)ry)) { - /* clip the image */ - int ix = (int)(x - width*0.5f); - int iy = (int)(y - height*0.5f); - int minx=MAX(ix,0); - int miny=MAX(iy,0); - int maxx=MIN(ix+width,TCOD_console_get_width(console)); - int maxy=MIN(iy+height,TCOD_console_get_height(console)); - int offx=0,offy=0; - int cx,cy; - if ( ix < 0 ) offx=-ix; - if ( iy < 0 ) offy=-iy; - for (cx=minx; cx < maxx; cx ++) { - for (cy=miny; cy < maxy; cy ++) { - TCOD_color_t col=TCOD_image_get_pixel(image,cx-minx+offx,cy-miny+offy); - if ( !img->has_key_color || img->key_color.r != col.r - || img->key_color.g != col.g || img->key_color.b != col.b ) { - TCOD_console_set_char_background(console,cx,cy,col,bkgnd_flag); - } - } - } - } else { - float iw=width/2*scalex; - float ih=height/2*scaley; - /* get the coordinates of the image corners in the console */ - float newx_x = (float)cos(angle); - float newx_y = -(float)sin(angle); - float newy_x = newx_y; - float newy_y = -newx_x; - float x0,y0,x1,y1,x2,y2,x3,y3; /* image corners coordinates */ - int rx,ry,rw,rh; /* rectangular area in the console */ - int cx,cy; - int minx,miny,maxx,maxy; - float invscalex,invscaley; - /* 0 = P - w/2 x' +h/2 y' */ - x0 = x-iw*newx_x+ih*newy_x; - y0 = y-iw*newx_y+ih*newy_y; - /* 1 = P + w/2 x' + h/2 y' */ - x1 = x+iw*newx_x+ih*newy_x; - y1 = y+iw*newx_y+ih*newy_y; - /* 2 = P + w/2 x' - h/2 y' */ - x2 = x+iw*newx_x-ih*newy_x; - y2 = y+iw*newx_y-ih*newy_y; - /* 3 = P - w/2 x' - h/2 y' */ - x3 = x-iw*newx_x-ih*newy_x; - y3 = y-iw*newx_y-ih*newy_y; - /* get the affected rectangular area in the console */ - rx=(int)(MIN(MIN(x0,x1),MIN(x2,x3))); - ry=(int)(MIN(MIN(y0,y1),MIN(y2,y3))); - rw=(int)(MAX(MAX(x0,x1),MAX(x2,x3))) - rx; - rh=(int)(MAX(MAX(y0,y1),MAX(y2,y3))) - ry; - /* clip it */ - minx=MAX(rx,0); - miny=MAX(ry,0); - maxx=MIN(rx+rw,TCOD_console_get_width(console)); - maxy=MIN(ry+rh,TCOD_console_get_height(console)); - invscalex=1.0f / scalex; - invscaley=1.0f / scaley; - for (cx=minx; cx < maxx; cx ++) { - for (cy=miny; cy < maxy; cy ++) { - float ix,iy; - TCOD_color_t col; - /* map the console pixel to the image world */ - ix = (iw+ (cx-x) * newx_x + (cy-y) *(-newy_x))*invscalex; - iy = (ih + (cx-x) * (newx_y) - (cy-y)*newy_y)*invscaley; - col = TCOD_image_get_pixel(image,(int)(ix),(int)(iy)); - if ( !img->has_key_color || img->key_color.r != col.r - || img->key_color.g != col.g || img->key_color.b != col.b ) { - if ( scalex < 1.0f || scaley < 1.0f ) { - col = TCOD_image_get_mipmap_pixel(image,ix,iy,ix+1.0f,iy+1.0f); - } - TCOD_console_set_char_background(console,cx,cy,col,bkgnd_flag); - } - } - } - } -} - -void TCOD_image_blit_rect(TCOD_image_t image, TCOD_console_t console, int x, int y, - int w, int h, TCOD_bkgnd_flag_t bkgnd_flag) { - int width,height; - float scalex,scaley; - TCOD_image_get_size(image,&width,&height); - if ( w == -1 ) w=width; - if ( h == -1 ) h=height; - if ( w <= 0 || h <= 0 || bkgnd_flag == TCOD_BKGND_NONE ) return; - scalex = (float)(w)/width; - scaley = (float)(h)/height; - TCOD_image_blit(image,console,x+w*0.5f,y+h*0.5f,bkgnd_flag,scalex,scaley,0.0f); -} - -TCOD_image_t TCOD_image_from_console(TCOD_console_t console) { - image_data_t *ret; - void *bitmap=TCOD_sys_create_bitmap_for_console(console); - ret=(image_data_t *)calloc(sizeof(image_data_t),1); - ret->sys_img=bitmap; - TCOD_image_refresh_console((TCOD_image_t)ret,console); - return (TCOD_image_t)ret; -} - -void TCOD_image_refresh_console(TCOD_image_t image, TCOD_console_t console) { - image_data_t *img=(image_data_t *)image; - console = (console?console:TCOD_ctx.root); - /* We're copying the state and clearing part of the copy, no need to delete/free. */ - TCOD_sys_console_to_bitmap( - img->sys_img, (TCOD_console_data_t*)console, NULL); -} - -#endif /* TCOD_CONSOLE_SUPPORT */ - -void TCOD_image_save(TCOD_image_t image, const char *filename) { - image_data_t *img=(image_data_t *)image; - void *bitmap=NULL; - bool must_free=false; - if ( img->sys_img ) { - bitmap=img->sys_img; - } else if ( img->mipmaps ){ - bitmap=TCOD_sys_create_bitmap(img->mipmaps[0].width, img->mipmaps[0].height, img->mipmaps[0].buf); - must_free=true; - } - if (bitmap) { - TCOD_sys_save_bitmap(bitmap, filename); - if ( must_free ) { - TCOD_sys_delete_bitmap(bitmap); - } - } -} - -void TCOD_image_set_key_color(TCOD_image_t image, TCOD_color_t key_color) { - image_data_t *img=(image_data_t *)image; - img->has_key_color=true; - img->key_color=key_color; -} - -void TCOD_image_invert(TCOD_image_t image) { - int i,mip; - int width,height; - image_data_t *img=(image_data_t *)image; - if ( !img->mipmaps && !img->sys_img) return; /* no image data */ - if ( ! img->mipmaps ) { - TCOD_image_init_mipmaps(img); - } - TCOD_image_get_size(image,&width,&height); - for (i=0; i< width*height; i++) { - TCOD_color_t col=img->mipmaps[0].buf[i]; - col.r=255-col.r; - col.g=255-col.g; - col.b=255-col.b; - img->mipmaps[0].buf[i] = col; - } - for (mip=1; mip < img->nb_mipmaps; mip++) { - img->mipmaps[mip].dirty=true; - } -} - -void TCOD_image_hflip(TCOD_image_t image) { - int px,py; - int width,height; - TCOD_image_get_size(image,&width,&height); - for (py = 0; py < height; py++ ) { - for (px = 0; px < width/2; px++ ) { - TCOD_color_t col1=TCOD_image_get_pixel(image,px,py); - TCOD_color_t col2=TCOD_image_get_pixel(image,width-1-px,py); - TCOD_image_put_pixel(image,px,py,col2); - TCOD_image_put_pixel(image,width-1-px,py,col1); - } - } -} - -void TCOD_image_vflip(TCOD_image_t image) { - int px,py; - int width,height; - TCOD_image_get_size(image,&width,&height); - for (px = 0; px < width; px++ ) { - for (py = 0; py < height/2; py++ ) { - TCOD_color_t col1=TCOD_image_get_pixel(image,px,py); - TCOD_color_t col2=TCOD_image_get_pixel(image,px,height-1-py); - TCOD_image_put_pixel(image,px,py,col2); - TCOD_image_put_pixel(image,px,height-1-py,col1); - } - } -} - -void TCOD_image_rotate90(TCOD_image_t image, int numRotations) { - int px,py; - int width,height; - numRotations = numRotations % 4; - if (numRotations == 0 ) return; - if ( numRotations < 0 ) numRotations += 4; - TCOD_image_get_size(image,&width,&height); - if (numRotations == 1) { - /* rotate 90 degrees */ - TCOD_image_t newImg=TCOD_image_new(height,width); - image_data_t *img=(image_data_t *)image; - image_data_t *img2=(image_data_t *)newImg; - for (px = 0; px < width; px++ ) { - for (py = 0; py < height; py++ ) { - TCOD_color_t col1=TCOD_image_get_pixel(image,px,py); - TCOD_image_put_pixel(newImg,height-1-py,px,col1); - } - } - TCOD_image_delete_internal(image); - /* update img with the new image content */ - img->mipmaps = img2->mipmaps; - img->sys_img=NULL; - img->nb_mipmaps=img2->nb_mipmaps; - free(img2); - } else if ( numRotations == 2 ) { - /* rotate 180 degrees */ - int maxy=height/2 + ((height & 1) == 1? 1 : 0 ); - for (px = 0; px < width; px++ ) { - for (py = 0; py < maxy; py++ ) { - if ( py != height-1-py || px < width/2 ) { - TCOD_color_t col1=TCOD_image_get_pixel(image,px,py); - TCOD_color_t col2=TCOD_image_get_pixel(image,width-1-px,height-1-py); - TCOD_image_put_pixel(image,px,py,col2); - TCOD_image_put_pixel(image,width-1-px,height-1-py,col1); - } - } - } - } else if (numRotations == 3) { - /* rotate 270 degrees */ - TCOD_image_t newImg=TCOD_image_new(height,width); - image_data_t *img=(image_data_t *)image; - image_data_t *img2=(image_data_t *)newImg; - for (px = 0; px < width; px++ ) { - for (py = 0; py < height; py++ ) { - TCOD_color_t col1=TCOD_image_get_pixel(image,px,py); - TCOD_image_put_pixel(newImg,py,width-1-px,col1); - } - } - TCOD_image_delete_internal(image); - /* update img with the new image content */ - img->mipmaps = img2->mipmaps; - img->sys_img=NULL; - img->nb_mipmaps=img2->nb_mipmaps; - free(img2); - } -} - -void TCOD_image_scale(TCOD_image_t image, int neww, int newh) { - image_data_t *img=(image_data_t *)image; - int px,py; - int width,height; - image_data_t *newimg; - TCOD_image_get_size(image,&width,&height); - if ( neww==width && newh==height ) return; - if ( neww == 0 || newh == 0 ) return; - newimg=(image_data_t *)TCOD_image_new(neww,newh); - - if ( neww < width && newh < height ) { - /* scale down image, using supersampling */ - for (py = 0; py < newh; py++ ) { - float y0 = (float)(py) * height / newh; - float y0floor = (float)floor(y0); - float y0weight = 1.0f - (y0 - y0floor); - int iy0 = (int)y0floor; - - float y1 = (float)(py+1) * height / newh; - float y1floor = (float)floor(y1-0.00001); - float y1weight = (y1 - y1floor); - int iy1 = (int)y1floor; - - for (px = 0; px < neww; px++ ) { - TCOD_color_t col; - float x0 = (float)(px) * width / neww; - float x0floor = (float)floor(x0); - float x0weight = 1.0f - (x0 - x0floor); - int ix0 = (int)x0floor; - - float x1 = (float)(px+1) * width / neww; - float x1floor = (float)floor(x1- 0.00001); - float x1weight = (x1 - x1floor); - int ix1 = (int)x1floor; - - float r=0,g=0,b=0,sumweight=0.0f; - int srcx,srcy; - /* left & right fractional edges */ - for (srcy=(int)(y0+1); srcy < (int)y1; srcy++) { - TCOD_color_t col_left=TCOD_image_get_pixel(image,ix0,srcy); - TCOD_color_t col_right=TCOD_image_get_pixel(image,ix1,srcy); - r += col_left.r * x0weight + col_right.r * x1weight; - g += col_left.g * x0weight + col_right.g * x1weight; - b += col_left.b * x0weight + col_right.b * x1weight; - sumweight += x0weight+x1weight; - } - /* top & bottom fractional edges */ - for (srcx = (int)(x0+1); srcx < (int)x1; srcx++) { - TCOD_color_t col_top=TCOD_image_get_pixel(image,srcx,iy0); - TCOD_color_t col_bottom=TCOD_image_get_pixel(image,srcx,iy1); - r += col_top.r * y0weight + col_bottom.r * y1weight; - g += col_top.g * y0weight + col_bottom.g * y1weight; - b += col_top.b * y0weight + col_bottom.b * y1weight; - sumweight += y0weight+y1weight; - } - /* center */ - for (srcy=(int)(y0+1); srcy < (int)y1; srcy++) { - for (srcx = (int)(x0+1); srcx < (int)x1; srcx++) { - TCOD_color_t col=TCOD_image_get_pixel(image,srcx,srcy); - r += col.r; - g += col.g; - b += col.b; - sumweight += 1.0f; - } - } - /* corners */ - col=TCOD_image_get_pixel(image,ix0,iy0); - r += col.r * (x0weight * y0weight); - g += col.g * (x0weight * y0weight); - b += col.b * (x0weight * y0weight); - sumweight += x0weight * y0weight; - col=TCOD_image_get_pixel(image,ix0,iy1); - r += col.r * (x0weight * y1weight); - g += col.g * (x0weight * y1weight); - b += col.b * (x0weight * y1weight); - sumweight += x0weight * y1weight; - col=TCOD_image_get_pixel(image,ix1,iy1); - r += col.r * (x1weight * y1weight); - g += col.g * (x1weight * y1weight); - b += col.b * (x1weight * y1weight); - sumweight += x1weight * y1weight; - col=TCOD_image_get_pixel(image,ix1,iy0); - r += col.r * (x1weight * y0weight); - g += col.g * (x1weight * y0weight); - b += col.b * (x1weight * y0weight); - sumweight += x1weight * y0weight; - sumweight = 1.0f / sumweight; - r = r*sumweight + 0.5f; - g = g*sumweight + 0.5f; - b = b*sumweight + 0.5f; - col.r=(int)r; - col.g=(int)g; - col.b=(int)b; - TCOD_image_put_pixel(newimg,px,py,col); - } - } - } else { - /* scale up image, using nearest neightbor */ - for (py = 0; py < newh; py++ ) { - int srcy = py * height / newh; - for (px = 0; px < neww; px++ ) { - int srcx = px * width / neww; - TCOD_color_t col=TCOD_image_get_pixel(image,srcx,srcy); - TCOD_image_put_pixel(newimg,px,py,col); - } - } - } - - /* destroy old image */ - TCOD_image_delete_internal(image); - /* update img with the new image content */ - img->mipmaps = newimg->mipmaps; - img->sys_img=NULL; - img->nb_mipmaps=newimg->nb_mipmaps; - free(newimg); -} - - -/* distance between two colors */ -int rgbdist(const TCOD_color_t *c1,const TCOD_color_t *c2) { - int dr=(int)(c1->r)-c2->r; - int dg=(int)(c1->g)-c2->g; - int db=(int)(c1->b)-c2->b; - return dr*dr+dg*dg+db*db; -} - -void getPattern(TCOD_color_t desired[4], TCOD_color_t palette[2], int *nbCols, int *ascii) { - /* adapted from Jeff Lait's code posted on r.g.r.d */ - int flag=0; - /* - pixels have following flag values : - X 1 - 2 4 - flag indicates which pixels uses foreground color (palette[1]) - */ - static int flagToAscii[8] = { - 0, - TCOD_CHAR_SUBP_NE,TCOD_CHAR_SUBP_SW,-TCOD_CHAR_SUBP_DIAG,TCOD_CHAR_SUBP_SE, - TCOD_CHAR_SUBP_E,-TCOD_CHAR_SUBP_N,-TCOD_CHAR_SUBP_NW - }; - int weight[2] = { 0, 0 }; - int i; - - /* First colour trivial. */ - palette[0] = desired[0]; - - /* Ignore all duplicates... */ - for (i = 1; i < 4; i++) { - if (desired[i].r != palette[0].r || desired[i].g != palette[0].g || desired[i].b != palette[0].b) - break; - } - - /* All the same. */ - if (i == 4) { - *nbCols=1; - return; - } - weight[0] = i; - - /* Found a second colour... */ - palette[1] = desired[i]; - weight[1] = 1; - flag |= 1<<(i-1); - *nbCols = 2; - /* remaining colours */ - i++; - while (i< 4) { - if (desired[i].r == palette[0].r && desired[i].g == palette[0].g && desired[i].b == palette[0].b) { - weight[0]++; - } else if (desired[i].r == palette[1].r && desired[i].g == palette[1].g && desired[i].b == palette[1].b) { - flag |= 1<<(i-1); - weight[1]++; - } else { - /* Bah, too many colours, */ - /* merge the two nearest */ - int dist0i=rgbdist(&desired[i], &palette[0]); - int dist1i=rgbdist(&desired[i], &palette[1]); - int dist01=rgbdist(&palette[0],&palette[1]); - if ( dist0i < dist1i ) { - if ( dist0i <= dist01 ) { - /* merge 0 and i */ - palette[0]=TCOD_color_lerp(desired[i],palette[0],weight[0]/(1.0f+weight[0])); - weight[0]++; - } else { - /* merge 0 and 1 */ - palette[0]=TCOD_color_lerp(palette[0],palette[1],(float)(weight[1])/(weight[0]+weight[1])); - weight[0]++; - palette[1]=desired[i]; - flag=1<<(i-1); - } - } else { - if ( dist1i <= dist01 ) { - /* merge 1 and i */ - palette[1]=TCOD_color_lerp(desired[i],palette[1],weight[1]/(1.0f+weight[1])); - weight[1]++; - flag|=1<<(i-1); - } else { - /* merge 0 and 1 */ - palette[0]=TCOD_color_lerp(palette[0],palette[1],(float)(weight[1])/(weight[0]+weight[1])); - weight[0]++; - palette[1]=desired[i]; - flag=1<<(i-1); - } - } - } - i++; - } - *ascii=flagToAscii[flag]; -} - -#ifdef TCOD_CONSOLE_SUPPORT - -void TCOD_image_blit_2x(TCOD_image_t image, TCOD_console_t con, int dx, int dy, int sx, int sy, int w, int h) { - TCOD_color_t grid[4]; - TCOD_color_t cols[2]; - int nbCols; - int width,height,ascii,cx,cy; - TCOD_console_data_t *dat = con ? (TCOD_console_data_t *)(con) : TCOD_ctx.root; - image_data_t *img=(image_data_t *)image; - int maxx,maxy; - TCOD_IFNOT(image != NULL && dat != NULL) return; - - TCOD_image_get_size(image,&width,&height); - if ( w == -1 ) w=width; - if ( h == -1 ) h=height; - - /* check that the sx,sy/w,h rectangle is inside the image */ - TCOD_ASSERT(sx >= 0 && sy >= 0 && sx+w <= width && sy+h <= height); - TCOD_IFNOT(w > 0 && h > 0) return; - - sx=MAX(0,sx); - sy=MAX(0,sy); - w = MIN(w,width-sx); - h = MIN(h,height-sy); - - maxx=dx+w/2 <= dat->w ? w : (dat->w-dx)*2; - maxy=dy+h/2 <= dat->h ? h : (dat->h-dy)*2; - /* check that the image is not blitted outside the console */ - TCOD_IFNOT(dx+maxx/2 >= 0 && dy+maxy/2 >= 0 && dx < dat->w && dy < dat->h) return; - maxx+=sx; - maxy+=sy; - - for (cx=sx; cx < maxx; cx += 2) { - for (cy=sy; cy < maxy; cy += 2) { - /* get the 2x2 super pixel colors from the image */ - int conx=dx+(cx-sx)/2; - int cony=dy+(cy-sy)/2; - TCOD_color_t consoleBack=TCOD_console_get_char_background(con,conx,cony); - grid[0]=TCOD_image_get_pixel(image,cx,cy); - if ( img->has_key_color && grid[0].r == img->key_color.r && grid[0].g == img->key_color.g && grid[0].b == img->key_color.b) - grid[0]=consoleBack; - if ( cx < maxx-1 ) { - grid[1]=TCOD_image_get_pixel(image,cx+1,cy); - if ( img->has_key_color && grid[1].r == img->key_color.r && grid[1].g == img->key_color.g && grid[1].b == img->key_color.b) - grid[1]=consoleBack; - } else grid[1]=consoleBack; - if ( cy < maxy-1 ) { - grid[2]=TCOD_image_get_pixel(image,cx,cy+1); - if ( img->has_key_color && grid[2].r == img->key_color.r && grid[2].g == img->key_color.g && grid[2].b == img->key_color.b) - grid[2]=consoleBack; - } else grid[2]=consoleBack; - if ( cx < maxx-1 && cy < maxy-1 ) { - grid[3]=TCOD_image_get_pixel(image,cx+1,cy+1); - if ( img->has_key_color && grid[3].r == img->key_color.r && grid[3].g == img->key_color.g && grid[3].b == img->key_color.b) - grid[3]=consoleBack; - } else grid[3]=consoleBack; - /* analyse color, posterize, get pattern */ - getPattern(grid,cols,&nbCols,&ascii); - if ( nbCols == 1 ) { - /* single color */ - TCOD_console_set_char_background(con,conx,cony,cols[0],TCOD_BKGND_SET); - TCOD_console_set_char(con,conx,cony,' '); - } else { - if ( ascii >= 0 ) { - TCOD_console_set_char_background(con,conx,cony,cols[0],TCOD_BKGND_SET); - TCOD_console_set_char_foreground(con,conx,cony,cols[1]); - TCOD_console_set_char(con,conx,cony,ascii); - } else { - /* negative ascii code means we need to invert back/fore colors */ - TCOD_console_set_char_background(con,conx,cony,cols[1],TCOD_BKGND_SET); - TCOD_console_set_char_foreground(con,conx,cony,cols[0]); - TCOD_console_set_char(con,conx,cony,-ascii); - } - } - } - } -} - -#endif /* TCOD_CONSOLE_SUPPORT */ - -#endif /* TCOD_IMAGE_SUPPORT */ +/* +* libtcod +* Copyright (c) 2008-2018 Jice & Mingos & rmtew +* All rights reserved. +* +* Redistribution and use in source and binary forms, with or without +* modification, are permitted provided that the following conditions are met: +* * Redistributions of source code must retain the above copyright +* notice, this list of conditions and the following disclaimer. +* * Redistributions in binary form must reproduce the above copyright +* notice, this list of conditions and the following disclaimer in the +* documentation and/or other materials provided with the distribution. +* * The name of Jice or Mingos may not be used to endorse or promote +* products derived from this software without specific prior written +* permission. +* +* THIS SOFTWARE IS PROVIDED BY JICE, MINGOS AND RMTEW ``AS IS'' AND ANY +* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED +* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE +* DISCLAIMED. IN NO EVENT SHALL JICE, MINGOS OR RMTEW BE LIABLE FOR ANY +* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES +* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; +* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND +* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS +* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +*/ +#include "portability.h" +#ifdef TCOD_IMAGE_SUPPORT +#include "image.h" + +#include +#include +#include +#include + +#include "console.h" +#include "libtcod_int.h" +#include "utility.h" + +typedef struct { + int width,height; + float fwidth,fheight; + TCOD_color_t *buf; + bool dirty; +} mipmap_t; + +struct TCOD_Image { + void *sys_img; + int nb_mipmaps; + mipmap_t *mipmaps; + TCOD_color_t key_color; + bool has_key_color; +}; + +typedef struct TCOD_Image image_data_t; + +/* +Internal libtcod optimisation, direct colour manipulation in the images primary mipmap. +*/ +TCOD_color_t *TCOD_image_get_colors(TCOD_image_t *image) { + image_data_t *img = ((image_data_t *)image); + return img->mipmaps[0].buf; +} + +void TCOD_image_get_key_data(TCOD_image_t image, bool *has_key_color, TCOD_color_t *key_color) { + image_data_t *img = ((image_data_t *)image); + *has_key_color = img->has_key_color; + *key_color = img->key_color; +} + +void TCOD_image_invalidate_mipmaps(TCOD_image_t *image) { + int i; + image_data_t *img = ((image_data_t *)image); + for (i = 1; i < img->nb_mipmaps; i++) { + img->mipmaps[i].dirty = true; + } +} + +static int TCOD_image_get_mipmap_levels(int width, int height) { + int curw=width; + int curh=height; + int nb_mipmap=0; + while ( curw > 0 && curh > 0 ) { + nb_mipmap++; + curw >>= 1; + curh >>= 1; + } + return nb_mipmap; +} + +static void TCOD_image_generate_mip(image_data_t *img, int mip) { + mipmap_t *orig=&img->mipmaps[0]; + mipmap_t *cur =&img->mipmaps[mip]; + int x,y; + if (! cur->buf) { + cur->buf=(TCOD_color_t *)calloc(sizeof(TCOD_color_t),cur->width*cur->height); + } + cur->dirty=false; + for (x=0; x < cur->width; x++) { + for (y=0; y < cur->height; y++) { + int r=0,g=0,b=0, count=0; + int sx,sy; + TCOD_color_t *col; + for (sx=(x << mip); sx < ((x+1)<width; + count++; + r+=orig->buf[offset].r; + g+=orig->buf[offset].g; + b+=orig->buf[offset].b; + } + } + r /= count; + g /= count; + b /= count; + col = &cur->buf[x+y*cur->width]; + col->r=r; + col->g=g; + col->b=b; + } + } +} + +/* +Internal way of copying rendering fg/bg color frame data. +*/ +bool TCOD_image_mipmap_copy_internal(TCOD_image_t srcImage, TCOD_image_t dstImage) { + int i; + image_data_t *img_src = (image_data_t *)srcImage; + image_data_t *img_dst = (image_data_t *)dstImage; + if (!img_src->mipmaps || img_src->sys_img || !img_dst->mipmaps || img_dst->sys_img) /* Both internal images. */ + return false; + if (img_src->mipmaps[0].width != img_dst->mipmaps[0].width || img_src->mipmaps[0].height != img_dst->mipmaps[0].height) + return false; + /* Copy all mipmaps? */ + img_dst->mipmaps[0].dirty = img_src->mipmaps[0].dirty; + memcpy(img_dst->mipmaps[0].buf, img_src->mipmaps[0].buf, sizeof(TCOD_color_t)*(img_src->mipmaps[0].width)*(img_src->mipmaps[0].height)); + for (i = 1; i < img_src->nb_mipmaps; i++) + img_dst->mipmaps[i].dirty = true; + return true; +} + +static void TCOD_image_init_mipmaps(image_data_t *img) { + int w,h,i,x,y; + float fw,fh; + if (! img->sys_img ) return; + TCOD_sys_get_image_size(img->sys_img,&w,&h); + img->nb_mipmaps=TCOD_image_get_mipmap_levels(w,h); + img->mipmaps = (mipmap_t *)calloc(sizeof(mipmap_t),img->nb_mipmaps); + img->mipmaps[0].buf = (TCOD_color_t *)calloc(sizeof(TCOD_color_t),w*h); + for (x=0; x < w; x++) { + for (y=0;y < h; y++) { + img->mipmaps[0].buf[x+y*w]=TCOD_sys_get_image_pixel(img->sys_img,x,y); + } + } + fw=(float)w; + fh=(float)h; + for ( i=0; i < img->nb_mipmaps; i++) { + img->mipmaps[i].width=w; + img->mipmaps[i].height=h; + img->mipmaps[i].fwidth=fw; + img->mipmaps[i].fheight=fh; + img->mipmaps[i].dirty=true; + w >>= 1; + h >>= 1; + fw *= 0.5f; + fh *= 0.5f; + } + img->mipmaps[0].dirty=false; +} + +void TCOD_image_clear(TCOD_image_t image, TCOD_color_t color) { + int i; + image_data_t *img=(image_data_t *)image; + if ( !img->mipmaps && !img->sys_img) return; /* no image data */ + if ( ! img->mipmaps ) { + TCOD_image_init_mipmaps(img); + } + for (i=0; i< img->mipmaps[0].width*img->mipmaps[0].height; i++) { + img->mipmaps[0].buf[i] = color; + } + for ( i=1; i < img->nb_mipmaps; i++) { + img->mipmaps[i].dirty=true; + } +} + +TCOD_image_t TCOD_image_new(int width, int height) { + int i; + float fw,fh; + image_data_t *ret=(image_data_t *)calloc(sizeof(image_data_t),1); + ret->nb_mipmaps=TCOD_image_get_mipmap_levels(width,height); + ret->mipmaps = (mipmap_t *)calloc(sizeof(mipmap_t),ret->nb_mipmaps); + ret->mipmaps[0].buf = (TCOD_color_t *)calloc(sizeof(TCOD_color_t),width*height); + + for (i=0; i< width*height; i++) { + ret->mipmaps[0].buf[i] = TCOD_black; + } + fw=(float)width; + fh=(float)height; + for ( i=0; i < ret->nb_mipmaps; i++) { + ret->mipmaps[i].width=width; + ret->mipmaps[i].height=height; + ret->mipmaps[i].fwidth=fw; + ret->mipmaps[i].fheight=fh; + width >>= 1; + height >>= 1; + fw *= 0.5f; + fh *= 0.5f; + } + return (TCOD_image_t)ret; +} + +TCOD_image_t TCOD_image_load(const char *filename) { + image_data_t *ret=(image_data_t *)calloc(sizeof(image_data_t),1); + ret->sys_img=TCOD_sys_load_image(filename); + return (TCOD_image_t)ret; +} + +void TCOD_image_get_size(TCOD_image_t image, int *w,int *h) { + image_data_t *img=(image_data_t *)image; + if ( !img->mipmaps && !img->sys_img) return; /* no image data */ + if ( img->mipmaps ) { + *w = img->mipmaps[0].width; + *h = img->mipmaps[0].height; + } else { + TCOD_sys_get_image_size(img->sys_img,w,h); + } +} + +TCOD_color_t TCOD_image_get_pixel(TCOD_image_t image,int x, int y) { + image_data_t *img=(image_data_t *)image; + if ( !img->mipmaps && !img->sys_img) return TCOD_black; /* no image data */ + if ( img->mipmaps ) { + if ( x >= 0 && x < img->mipmaps[0].width + && y >= 0 && y < img->mipmaps[0].height ) { + return img->mipmaps[0].buf[x+y*img->mipmaps[0].width]; + } else { + return TCOD_black; + } + } else { + return TCOD_sys_get_image_pixel(img->sys_img,x,y); + } +} + +int TCOD_image_get_alpha(TCOD_image_t image,int x, int y) { + image_data_t *img=(image_data_t *)image; + if ( img->sys_img ) { + return TCOD_sys_get_image_alpha(img->sys_img,x,y); + } else return 255; +} + +TCOD_color_t TCOD_image_get_mipmap_pixel(TCOD_image_t image,float x0,float y0, float x1, float y1) { + int texel_xsize,texel_ysize, texel_size, texel_x,texel_y; + int cur_size=1; + int mip=0; + image_data_t *img=(image_data_t *)image; + if ( !img->mipmaps && !img->sys_img) return TCOD_black; /* no image data */ + if (!img->mipmaps) TCOD_image_init_mipmaps(img); + texel_xsize=(int)(x1-x0); + texel_ysize=(int)(y1-y0); + texel_size=texel_xsize < texel_ysize ? texel_ysize : texel_xsize; + while ( mip < img->nb_mipmaps-1 && cur_size < texel_size ) { + mip++; + cur_size <<= 1; + } + if ( mip > 0 ) mip --; + texel_x=(int)(x0*(img->mipmaps[mip].width)/img->mipmaps[0].fwidth); + texel_y=(int)(y0*(img->mipmaps[mip].height)/img->mipmaps[0].fheight); + + if (img->mipmaps[mip].buf == NULL || img->mipmaps[mip].dirty) { + TCOD_image_generate_mip(img,mip); + } + if ( texel_x < 0 || texel_y < 0 || texel_x >= img->mipmaps[mip].width || texel_y >= img->mipmaps[mip].height ) + return TCOD_black; + return img->mipmaps[mip].buf[texel_x+texel_y*img->mipmaps[mip].width]; +} + +void TCOD_image_put_pixel(TCOD_image_t image,int x, int y,TCOD_color_t col) { + image_data_t *img=(image_data_t *)image; + if ( !img->mipmaps && !img->sys_img) return; /* no image data */ + if ( ! img->mipmaps ) { + TCOD_image_init_mipmaps(img); + } + if ( x >= 0 && x < img->mipmaps[0].width + && y >= 0 && y < img->mipmaps[0].height ) { + int mip; + img->mipmaps[0].buf[x+y*img->mipmaps[0].width] = col; + for (mip=1; mip < img->nb_mipmaps; mip++) { + img->mipmaps[mip].dirty=true; + } + } +} + +void TCOD_image_delete_internal(TCOD_image_t image) { + image_data_t *img=(image_data_t *)image; + if ( img->mipmaps ) { + int i; + for ( i=0; i < img->nb_mipmaps; i++) { + if ( img->mipmaps[i].buf ) free(img->mipmaps[i].buf); + } + free(img->mipmaps); + } + if ( img->sys_img ) { +#ifndef TCOD_BARE + TCOD_sys_delete_bitmap(img->sys_img); +#endif + } +} + +void TCOD_image_delete(TCOD_image_t image) { + TCOD_image_delete_internal(image); + free(image); +} + +bool TCOD_image_is_pixel_transparent(TCOD_image_t image, int x, int y) { + image_data_t *img=(image_data_t *)image; + TCOD_color_t col=TCOD_image_get_pixel(image,x,y); + if ( img->has_key_color && img->key_color.r == col.r + && img->key_color.g == col.g && img->key_color.b == col.b ) { + return true; + } + if ( TCOD_image_get_alpha(image,x,y) == 0 ) return true; + return false; +} + +#ifdef TCOD_CONSOLE_SUPPORT + +void TCOD_image_blit(TCOD_image_t image, TCOD_console_t console, float x, float y, + TCOD_bkgnd_flag_t bkgnd_flag, float scalex, float scaley, float angle) { + int width,height; + float rx,ry; + image_data_t *img=(image_data_t *)image; + if ( scalex == 0.0f || scaley == 0.0f || bkgnd_flag == TCOD_BKGND_NONE ) return; + TCOD_image_get_size(image,&width,&height); + rx = x - width * 0.5f; + ry = y - height * 0.5f; + if ( scalex == 1.0f && scaley == 1.0f && angle == 0.0f && rx == ((int)rx) && ry == ((int)ry)) { + /* clip the image */ + int ix = (int)(x - width*0.5f); + int iy = (int)(y - height*0.5f); + int minx=MAX(ix,0); + int miny=MAX(iy,0); + int maxx=MIN(ix+width,TCOD_console_get_width(console)); + int maxy=MIN(iy+height,TCOD_console_get_height(console)); + int offx=0,offy=0; + int cx,cy; + if ( ix < 0 ) offx=-ix; + if ( iy < 0 ) offy=-iy; + for (cx=minx; cx < maxx; cx ++) { + for (cy=miny; cy < maxy; cy ++) { + TCOD_color_t col=TCOD_image_get_pixel(image,cx-minx+offx,cy-miny+offy); + if ( !img->has_key_color || img->key_color.r != col.r + || img->key_color.g != col.g || img->key_color.b != col.b ) { + TCOD_console_set_char_background(console,cx,cy,col,bkgnd_flag); + } + } + } + } else { + float iw=width/2*scalex; + float ih=height/2*scaley; + /* get the coordinates of the image corners in the console */ + float newx_x = (float)cos(angle); + float newx_y = -(float)sin(angle); + float newy_x = newx_y; + float newy_y = -newx_x; + float x0,y0,x1,y1,x2,y2,x3,y3; /* image corners coordinates */ + int rx,ry,rw,rh; /* rectangular area in the console */ + int cx,cy; + int minx,miny,maxx,maxy; + float invscalex,invscaley; + /* 0 = P - w/2 x' +h/2 y' */ + x0 = x-iw*newx_x+ih*newy_x; + y0 = y-iw*newx_y+ih*newy_y; + /* 1 = P + w/2 x' + h/2 y' */ + x1 = x+iw*newx_x+ih*newy_x; + y1 = y+iw*newx_y+ih*newy_y; + /* 2 = P + w/2 x' - h/2 y' */ + x2 = x+iw*newx_x-ih*newy_x; + y2 = y+iw*newx_y-ih*newy_y; + /* 3 = P - w/2 x' - h/2 y' */ + x3 = x-iw*newx_x-ih*newy_x; + y3 = y-iw*newx_y-ih*newy_y; + /* get the affected rectangular area in the console */ + rx=(int)(MIN(MIN(x0,x1),MIN(x2,x3))); + ry=(int)(MIN(MIN(y0,y1),MIN(y2,y3))); + rw=(int)(MAX(MAX(x0,x1),MAX(x2,x3))) - rx; + rh=(int)(MAX(MAX(y0,y1),MAX(y2,y3))) - ry; + /* clip it */ + minx=MAX(rx,0); + miny=MAX(ry,0); + maxx=MIN(rx+rw,TCOD_console_get_width(console)); + maxy=MIN(ry+rh,TCOD_console_get_height(console)); + invscalex=1.0f / scalex; + invscaley=1.0f / scaley; + for (cx=minx; cx < maxx; cx ++) { + for (cy=miny; cy < maxy; cy ++) { + float ix,iy; + TCOD_color_t col; + /* map the console pixel to the image world */ + ix = (iw+ (cx-x) * newx_x + (cy-y) *(-newy_x))*invscalex; + iy = (ih + (cx-x) * (newx_y) - (cy-y)*newy_y)*invscaley; + col = TCOD_image_get_pixel(image,(int)(ix),(int)(iy)); + if ( !img->has_key_color || img->key_color.r != col.r + || img->key_color.g != col.g || img->key_color.b != col.b ) { + if ( scalex < 1.0f || scaley < 1.0f ) { + col = TCOD_image_get_mipmap_pixel(image,ix,iy,ix+1.0f,iy+1.0f); + } + TCOD_console_set_char_background(console,cx,cy,col,bkgnd_flag); + } + } + } + } +} + +void TCOD_image_blit_rect(TCOD_image_t image, TCOD_console_t console, int x, int y, + int w, int h, TCOD_bkgnd_flag_t bkgnd_flag) { + int width,height; + float scalex,scaley; + TCOD_image_get_size(image,&width,&height); + if ( w == -1 ) w=width; + if ( h == -1 ) h=height; + if ( w <= 0 || h <= 0 || bkgnd_flag == TCOD_BKGND_NONE ) return; + scalex = (float)(w)/width; + scaley = (float)(h)/height; + TCOD_image_blit(image,console,x+w*0.5f,y+h*0.5f,bkgnd_flag,scalex,scaley,0.0f); +} + +TCOD_image_t TCOD_image_from_console(TCOD_console_t console) { + image_data_t *ret; + void *bitmap=TCOD_sys_create_bitmap_for_console(console); + ret=(image_data_t *)calloc(sizeof(image_data_t),1); + ret->sys_img=bitmap; + TCOD_image_refresh_console((TCOD_image_t)ret,console); + return (TCOD_image_t)ret; +} + +void TCOD_image_refresh_console(TCOD_image_t image, TCOD_console_t console) { + image_data_t *img=(image_data_t *)image; + console = (console?console:TCOD_ctx.root); + /* We're copying the state and clearing part of the copy, no need to delete/free. */ + TCOD_sys_console_to_bitmap( + img->sys_img, (struct TCOD_Console*)console, NULL); +} + +#endif /* TCOD_CONSOLE_SUPPORT */ + +void TCOD_image_save(TCOD_image_t image, const char *filename) { + image_data_t *img=(image_data_t *)image; + void *bitmap=NULL; + bool must_free=false; + if ( img->sys_img ) { + bitmap=img->sys_img; + } else if ( img->mipmaps ){ + bitmap=TCOD_sys_create_bitmap(img->mipmaps[0].width, img->mipmaps[0].height, img->mipmaps[0].buf); + must_free=true; + } + if (bitmap) { + TCOD_sys_save_bitmap(bitmap, filename); + if ( must_free ) { + TCOD_sys_delete_bitmap(bitmap); + } + } +} + +void TCOD_image_set_key_color(TCOD_image_t image, TCOD_color_t key_color) { + image_data_t *img=(image_data_t *)image; + img->has_key_color=true; + img->key_color=key_color; +} + +void TCOD_image_invert(TCOD_image_t image) { + int i,mip; + int width,height; + image_data_t *img=(image_data_t *)image; + if ( !img->mipmaps && !img->sys_img) return; /* no image data */ + if ( ! img->mipmaps ) { + TCOD_image_init_mipmaps(img); + } + TCOD_image_get_size(image,&width,&height); + for (i=0; i< width*height; i++) { + TCOD_color_t col=img->mipmaps[0].buf[i]; + col.r=255-col.r; + col.g=255-col.g; + col.b=255-col.b; + img->mipmaps[0].buf[i] = col; + } + for (mip=1; mip < img->nb_mipmaps; mip++) { + img->mipmaps[mip].dirty=true; + } +} + +void TCOD_image_hflip(TCOD_image_t image) { + int px,py; + int width,height; + TCOD_image_get_size(image,&width,&height); + for (py = 0; py < height; py++ ) { + for (px = 0; px < width/2; px++ ) { + TCOD_color_t col1=TCOD_image_get_pixel(image,px,py); + TCOD_color_t col2=TCOD_image_get_pixel(image,width-1-px,py); + TCOD_image_put_pixel(image,px,py,col2); + TCOD_image_put_pixel(image,width-1-px,py,col1); + } + } +} + +void TCOD_image_vflip(TCOD_image_t image) { + int px,py; + int width,height; + TCOD_image_get_size(image,&width,&height); + for (px = 0; px < width; px++ ) { + for (py = 0; py < height/2; py++ ) { + TCOD_color_t col1=TCOD_image_get_pixel(image,px,py); + TCOD_color_t col2=TCOD_image_get_pixel(image,px,height-1-py); + TCOD_image_put_pixel(image,px,py,col2); + TCOD_image_put_pixel(image,px,height-1-py,col1); + } + } +} + +void TCOD_image_rotate90(TCOD_image_t image, int numRotations) { + int px,py; + int width,height; + numRotations = numRotations % 4; + if (numRotations == 0 ) return; + if ( numRotations < 0 ) numRotations += 4; + TCOD_image_get_size(image,&width,&height); + if (numRotations == 1) { + /* rotate 90 degrees */ + TCOD_image_t newImg=TCOD_image_new(height,width); + image_data_t *img=(image_data_t *)image; + image_data_t *img2=(image_data_t *)newImg; + for (px = 0; px < width; px++ ) { + for (py = 0; py < height; py++ ) { + TCOD_color_t col1=TCOD_image_get_pixel(image,px,py); + TCOD_image_put_pixel(newImg,height-1-py,px,col1); + } + } + TCOD_image_delete_internal(image); + /* update img with the new image content */ + img->mipmaps = img2->mipmaps; + img->sys_img=NULL; + img->nb_mipmaps=img2->nb_mipmaps; + free(img2); + } else if ( numRotations == 2 ) { + /* rotate 180 degrees */ + int maxy=height/2 + ((height & 1) == 1? 1 : 0 ); + for (px = 0; px < width; px++ ) { + for (py = 0; py < maxy; py++ ) { + if ( py != height-1-py || px < width/2 ) { + TCOD_color_t col1=TCOD_image_get_pixel(image,px,py); + TCOD_color_t col2=TCOD_image_get_pixel(image,width-1-px,height-1-py); + TCOD_image_put_pixel(image,px,py,col2); + TCOD_image_put_pixel(image,width-1-px,height-1-py,col1); + } + } + } + } else if (numRotations == 3) { + /* rotate 270 degrees */ + TCOD_image_t newImg=TCOD_image_new(height,width); + image_data_t *img=(image_data_t *)image; + image_data_t *img2=(image_data_t *)newImg; + for (px = 0; px < width; px++ ) { + for (py = 0; py < height; py++ ) { + TCOD_color_t col1=TCOD_image_get_pixel(image,px,py); + TCOD_image_put_pixel(newImg,py,width-1-px,col1); + } + } + TCOD_image_delete_internal(image); + /* update img with the new image content */ + img->mipmaps = img2->mipmaps; + img->sys_img=NULL; + img->nb_mipmaps=img2->nb_mipmaps; + free(img2); + } +} + +void TCOD_image_scale(TCOD_image_t image, int neww, int newh) { + image_data_t *img=(image_data_t *)image; + int px,py; + int width,height; + image_data_t *newimg; + TCOD_image_get_size(image,&width,&height); + if ( neww==width && newh==height ) return; + if ( neww == 0 || newh == 0 ) return; + newimg=(image_data_t *)TCOD_image_new(neww,newh); + + if ( neww < width && newh < height ) { + /* scale down image, using supersampling */ + for (py = 0; py < newh; py++ ) { + float y0 = (float)(py) * height / newh; + float y0floor = (float)floor(y0); + float y0weight = 1.0f - (y0 - y0floor); + int iy0 = (int)y0floor; + + float y1 = (float)(py+1) * height / newh; + float y1floor = (float)floor(y1-0.00001); + float y1weight = (y1 - y1floor); + int iy1 = (int)y1floor; + + for (px = 0; px < neww; px++ ) { + TCOD_color_t col; + float x0 = (float)(px) * width / neww; + float x0floor = (float)floor(x0); + float x0weight = 1.0f - (x0 - x0floor); + int ix0 = (int)x0floor; + + float x1 = (float)(px+1) * width / neww; + float x1floor = (float)floor(x1- 0.00001); + float x1weight = (x1 - x1floor); + int ix1 = (int)x1floor; + + float r=0,g=0,b=0,sumweight=0.0f; + int srcx,srcy; + /* left & right fractional edges */ + for (srcy=(int)(y0+1); srcy < (int)y1; srcy++) { + TCOD_color_t col_left=TCOD_image_get_pixel(image,ix0,srcy); + TCOD_color_t col_right=TCOD_image_get_pixel(image,ix1,srcy); + r += col_left.r * x0weight + col_right.r * x1weight; + g += col_left.g * x0weight + col_right.g * x1weight; + b += col_left.b * x0weight + col_right.b * x1weight; + sumweight += x0weight+x1weight; + } + /* top & bottom fractional edges */ + for (srcx = (int)(x0+1); srcx < (int)x1; srcx++) { + TCOD_color_t col_top=TCOD_image_get_pixel(image,srcx,iy0); + TCOD_color_t col_bottom=TCOD_image_get_pixel(image,srcx,iy1); + r += col_top.r * y0weight + col_bottom.r * y1weight; + g += col_top.g * y0weight + col_bottom.g * y1weight; + b += col_top.b * y0weight + col_bottom.b * y1weight; + sumweight += y0weight+y1weight; + } + /* center */ + for (srcy=(int)(y0+1); srcy < (int)y1; srcy++) { + for (srcx = (int)(x0+1); srcx < (int)x1; srcx++) { + TCOD_color_t col=TCOD_image_get_pixel(image,srcx,srcy); + r += col.r; + g += col.g; + b += col.b; + sumweight += 1.0f; + } + } + /* corners */ + col=TCOD_image_get_pixel(image,ix0,iy0); + r += col.r * (x0weight * y0weight); + g += col.g * (x0weight * y0weight); + b += col.b * (x0weight * y0weight); + sumweight += x0weight * y0weight; + col=TCOD_image_get_pixel(image,ix0,iy1); + r += col.r * (x0weight * y1weight); + g += col.g * (x0weight * y1weight); + b += col.b * (x0weight * y1weight); + sumweight += x0weight * y1weight; + col=TCOD_image_get_pixel(image,ix1,iy1); + r += col.r * (x1weight * y1weight); + g += col.g * (x1weight * y1weight); + b += col.b * (x1weight * y1weight); + sumweight += x1weight * y1weight; + col=TCOD_image_get_pixel(image,ix1,iy0); + r += col.r * (x1weight * y0weight); + g += col.g * (x1weight * y0weight); + b += col.b * (x1weight * y0weight); + sumweight += x1weight * y0weight; + sumweight = 1.0f / sumweight; + r = r*sumweight + 0.5f; + g = g*sumweight + 0.5f; + b = b*sumweight + 0.5f; + col.r=(int)r; + col.g=(int)g; + col.b=(int)b; + TCOD_image_put_pixel(newimg,px,py,col); + } + } + } else { + /* scale up image, using nearest neightbor */ + for (py = 0; py < newh; py++ ) { + int srcy = py * height / newh; + for (px = 0; px < neww; px++ ) { + int srcx = px * width / neww; + TCOD_color_t col=TCOD_image_get_pixel(image,srcx,srcy); + TCOD_image_put_pixel(newimg,px,py,col); + } + } + } + + /* destroy old image */ + TCOD_image_delete_internal(image); + /* update img with the new image content */ + img->mipmaps = newimg->mipmaps; + img->sys_img=NULL; + img->nb_mipmaps=newimg->nb_mipmaps; + free(newimg); +} + + +/* distance between two colors */ +int rgbdist(const TCOD_color_t *c1,const TCOD_color_t *c2) { + int dr=(int)(c1->r)-c2->r; + int dg=(int)(c1->g)-c2->g; + int db=(int)(c1->b)-c2->b; + return dr*dr+dg*dg+db*db; +} + +void getPattern(TCOD_color_t desired[4], TCOD_color_t palette[2], int *nbCols, int *ascii) { + /* adapted from Jeff Lait's code posted on r.g.r.d */ + int flag=0; + /* + pixels have following flag values : + X 1 + 2 4 + flag indicates which pixels uses foreground color (palette[1]) + */ + static int flagToAscii[8] = { + 0, + TCOD_CHAR_SUBP_NE,TCOD_CHAR_SUBP_SW,-TCOD_CHAR_SUBP_DIAG,TCOD_CHAR_SUBP_SE, + TCOD_CHAR_SUBP_E,-TCOD_CHAR_SUBP_N,-TCOD_CHAR_SUBP_NW + }; + int weight[2] = { 0, 0 }; + int i; + + /* First colour trivial. */ + palette[0] = desired[0]; + + /* Ignore all duplicates... */ + for (i = 1; i < 4; i++) { + if (desired[i].r != palette[0].r || desired[i].g != palette[0].g || desired[i].b != palette[0].b) + break; + } + + /* All the same. */ + if (i == 4) { + *nbCols=1; + return; + } + weight[0] = i; + + /* Found a second colour... */ + palette[1] = desired[i]; + weight[1] = 1; + flag |= 1<<(i-1); + *nbCols = 2; + /* remaining colours */ + i++; + while (i< 4) { + if (desired[i].r == palette[0].r && desired[i].g == palette[0].g && desired[i].b == palette[0].b) { + weight[0]++; + } else if (desired[i].r == palette[1].r && desired[i].g == palette[1].g && desired[i].b == palette[1].b) { + flag |= 1<<(i-1); + weight[1]++; + } else { + /* Bah, too many colours, */ + /* merge the two nearest */ + int dist0i=rgbdist(&desired[i], &palette[0]); + int dist1i=rgbdist(&desired[i], &palette[1]); + int dist01=rgbdist(&palette[0],&palette[1]); + if ( dist0i < dist1i ) { + if ( dist0i <= dist01 ) { + /* merge 0 and i */ + palette[0]=TCOD_color_lerp(desired[i],palette[0],weight[0]/(1.0f+weight[0])); + weight[0]++; + } else { + /* merge 0 and 1 */ + palette[0]=TCOD_color_lerp(palette[0],palette[1],(float)(weight[1])/(weight[0]+weight[1])); + weight[0]++; + palette[1]=desired[i]; + flag=1<<(i-1); + } + } else { + if ( dist1i <= dist01 ) { + /* merge 1 and i */ + palette[1]=TCOD_color_lerp(desired[i],palette[1],weight[1]/(1.0f+weight[1])); + weight[1]++; + flag|=1<<(i-1); + } else { + /* merge 0 and 1 */ + palette[0]=TCOD_color_lerp(palette[0],palette[1],(float)(weight[1])/(weight[0]+weight[1])); + weight[0]++; + palette[1]=desired[i]; + flag=1<<(i-1); + } + } + } + i++; + } + *ascii=flagToAscii[flag]; +} + +#ifdef TCOD_CONSOLE_SUPPORT + +void TCOD_image_blit_2x(TCOD_image_t image, TCOD_console_t con, int dx, int dy, int sx, int sy, int w, int h) { + TCOD_color_t grid[4]; + TCOD_color_t cols[2]; + int nbCols; + int width,height,ascii,cx,cy; + struct TCOD_Console *dat = con ? (struct TCOD_Console *)(con) : TCOD_ctx.root; + image_data_t *img=(image_data_t *)image; + int maxx,maxy; + TCOD_IFNOT(image != NULL && dat != NULL) return; + + TCOD_image_get_size(image,&width,&height); + if ( w == -1 ) w=width; + if ( h == -1 ) h=height; + + /* check that the sx,sy/w,h rectangle is inside the image */ + TCOD_ASSERT(sx >= 0 && sy >= 0 && sx+w <= width && sy+h <= height); + TCOD_IFNOT(w > 0 && h > 0) return; + + sx=MAX(0,sx); + sy=MAX(0,sy); + w = MIN(w,width-sx); + h = MIN(h,height-sy); + + maxx=dx+w/2 <= dat->w ? w : (dat->w-dx)*2; + maxy=dy+h/2 <= dat->h ? h : (dat->h-dy)*2; + /* check that the image is not blitted outside the console */ + TCOD_IFNOT(dx+maxx/2 >= 0 && dy+maxy/2 >= 0 && dx < dat->w && dy < dat->h) return; + maxx+=sx; + maxy+=sy; + + for (cx=sx; cx < maxx; cx += 2) { + for (cy=sy; cy < maxy; cy += 2) { + /* get the 2x2 super pixel colors from the image */ + int conx=dx+(cx-sx)/2; + int cony=dy+(cy-sy)/2; + TCOD_color_t consoleBack=TCOD_console_get_char_background(con,conx,cony); + grid[0]=TCOD_image_get_pixel(image,cx,cy); + if ( img->has_key_color && grid[0].r == img->key_color.r && grid[0].g == img->key_color.g && grid[0].b == img->key_color.b) + grid[0]=consoleBack; + if ( cx < maxx-1 ) { + grid[1]=TCOD_image_get_pixel(image,cx+1,cy); + if ( img->has_key_color && grid[1].r == img->key_color.r && grid[1].g == img->key_color.g && grid[1].b == img->key_color.b) + grid[1]=consoleBack; + } else grid[1]=consoleBack; + if ( cy < maxy-1 ) { + grid[2]=TCOD_image_get_pixel(image,cx,cy+1); + if ( img->has_key_color && grid[2].r == img->key_color.r && grid[2].g == img->key_color.g && grid[2].b == img->key_color.b) + grid[2]=consoleBack; + } else grid[2]=consoleBack; + if ( cx < maxx-1 && cy < maxy-1 ) { + grid[3]=TCOD_image_get_pixel(image,cx+1,cy+1); + if ( img->has_key_color && grid[3].r == img->key_color.r && grid[3].g == img->key_color.g && grid[3].b == img->key_color.b) + grid[3]=consoleBack; + } else grid[3]=consoleBack; + /* analyse color, posterize, get pattern */ + getPattern(grid,cols,&nbCols,&ascii); + if ( nbCols == 1 ) { + /* single color */ + TCOD_console_set_char_background(con,conx,cony,cols[0],TCOD_BKGND_SET); + TCOD_console_set_char(con,conx,cony,' '); + } else { + if ( ascii >= 0 ) { + TCOD_console_set_char_background(con,conx,cony,cols[0],TCOD_BKGND_SET); + TCOD_console_set_char_foreground(con,conx,cony,cols[1]); + TCOD_console_set_char(con,conx,cony,ascii); + } else { + /* negative ascii code means we need to invert back/fore colors */ + TCOD_console_set_char_background(con,conx,cony,cols[1],TCOD_BKGND_SET); + TCOD_console_set_char_foreground(con,conx,cony,cols[0]); + TCOD_console_set_char(con,conx,cony,-ascii); + } + } + } + } +} + +#endif /* TCOD_CONSOLE_SUPPORT */ + +#endif /* TCOD_IMAGE_SUPPORT */ diff --git a/tcod_sys/libtcod/src/lex.cpp b/tcod_sys/libtcod/src/libtcod/lex.cpp similarity index 96% rename from tcod_sys/libtcod/src/lex.cpp rename to tcod_sys/libtcod/src/libtcod/lex.cpp index 7fc49a9ab..834719554 100644 --- a/tcod_sys/libtcod/src/lex.cpp +++ b/tcod_sys/libtcod/src/libtcod/lex.cpp @@ -1,106 +1,106 @@ -/* -* libtcod -* Copyright (c) 2008-2018 Jice & Mingos & rmtew -* All rights reserved. -* -* Redistribution and use in source and binary forms, with or without -* modification, are permitted provided that the following conditions are met: -* * Redistributions of source code must retain the above copyright -* notice, this list of conditions and the following disclaimer. -* * Redistributions in binary form must reproduce the above copyright -* notice, this list of conditions and the following disclaimer in the -* documentation and/or other materials provided with the distribution. -* * The name of Jice or Mingos may not be used to endorse or promote -* products derived from this software without specific prior written -* permission. -* -* THIS SOFTWARE IS PROVIDED BY JICE, MINGOS AND RMTEW ``AS IS'' AND ANY -* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED -* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE -* DISCLAIMED. IN NO EVENT SHALL JICE, MINGOS OR RMTEW BE LIABLE FOR ANY -* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES -* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; -* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND -* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS -* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. -*/ -#include "lex.hpp" - -#include -#include -#include -#include -#include - -#include - -TCODLex::TCODLex( const char **_symbols, const char **_keywords, const char *simpleComment, - const char *commentStart, const char *commentStop, const char *javadocCommentStart, - const char *_stringDelim, int _flags) -{ - data=(void *)TCOD_lex_new(_symbols,_keywords,simpleComment,commentStart,commentStop,javadocCommentStart,_stringDelim,_flags); - -} - -TCODLex::TCODLex() -{ - data= (void *)TCOD_lex_new_intern(); -} - -TCODLex::~TCODLex() -{ - TCOD_lex_delete((TCOD_lex_t *)data); -} - -char *TCODLex::getLastJavadoc() -{ - return TCOD_lex_get_last_javadoc((TCOD_lex_t *)data); -} - - -void TCODLex::setDataBuffer(char *dat) -{ - TCOD_lex_set_data_buffer((TCOD_lex_t *)data,dat); -} - -bool TCODLex::setDataFile(const char *_filename) -{ - return TCOD_lex_set_data_file((TCOD_lex_t *)data,_filename) != 0; -} - -int TCODLex::parse() -{ - return TCOD_lex_parse((TCOD_lex_t *)data); -} - - -int TCODLex::parseUntil(int tokenType) -{ - return TCOD_lex_parse_until_token_type((TCOD_lex_t *)data,tokenType); -} - -int TCODLex::parseUntil(const char *tokenValue) -{ - return TCOD_lex_parse_until_token_value((TCOD_lex_t *)data,tokenValue); -} - -void TCODLex::savepoint(TCODLex *savepoint) -{ - TCOD_lex_savepoint((TCOD_lex_t *)data,(TCOD_lex_t *)(savepoint->data)); -} - -void TCODLex::restore(TCODLex *savepoint) -{ - TCOD_lex_restore((TCOD_lex_t *)data,(TCOD_lex_t *)(savepoint->data)); -} - -bool TCODLex::expect(int tokenType) -{ - return TCOD_lex_expect_token_type((TCOD_lex_t *)data,tokenType) != 0; -} - -bool TCODLex::expect(int tokenType, const char *tokenValue) -{ - return TCOD_lex_expect_token_value((TCOD_lex_t *)data,tokenType,tokenValue) != 0; -} +/* +* libtcod +* Copyright (c) 2008-2018 Jice & Mingos & rmtew +* All rights reserved. +* +* Redistribution and use in source and binary forms, with or without +* modification, are permitted provided that the following conditions are met: +* * Redistributions of source code must retain the above copyright +* notice, this list of conditions and the following disclaimer. +* * Redistributions in binary form must reproduce the above copyright +* notice, this list of conditions and the following disclaimer in the +* documentation and/or other materials provided with the distribution. +* * The name of Jice or Mingos may not be used to endorse or promote +* products derived from this software without specific prior written +* permission. +* +* THIS SOFTWARE IS PROVIDED BY JICE, MINGOS AND RMTEW ``AS IS'' AND ANY +* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED +* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE +* DISCLAIMED. IN NO EVENT SHALL JICE, MINGOS OR RMTEW BE LIABLE FOR ANY +* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES +* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; +* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND +* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS +* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +*/ +#include "lex.hpp" + +#include +#include +#include +#include +#include + +#include "libtcod_int.h" + +TCODLex::TCODLex( const char **_symbols, const char **_keywords, const char *simpleComment, + const char *commentStart, const char *commentStop, const char *javadocCommentStart, + const char *_stringDelim, int _flags) +{ + data=(void *)TCOD_lex_new(_symbols,_keywords,simpleComment,commentStart,commentStop,javadocCommentStart,_stringDelim,_flags); + +} + +TCODLex::TCODLex() +{ + data= (void *)TCOD_lex_new_intern(); +} + +TCODLex::~TCODLex() +{ + TCOD_lex_delete((TCOD_lex_t *)data); +} + +char *TCODLex::getLastJavadoc() +{ + return TCOD_lex_get_last_javadoc((TCOD_lex_t *)data); +} + + +void TCODLex::setDataBuffer(char *dat) +{ + TCOD_lex_set_data_buffer((TCOD_lex_t *)data,dat); +} + +bool TCODLex::setDataFile(const char *_filename) +{ + return TCOD_lex_set_data_file((TCOD_lex_t *)data,_filename) != 0; +} + +int TCODLex::parse() +{ + return TCOD_lex_parse((TCOD_lex_t *)data); +} + + +int TCODLex::parseUntil(int tokenType) +{ + return TCOD_lex_parse_until_token_type((TCOD_lex_t *)data,tokenType); +} + +int TCODLex::parseUntil(const char *tokenValue) +{ + return TCOD_lex_parse_until_token_value((TCOD_lex_t *)data,tokenValue); +} + +void TCODLex::savepoint(TCODLex *savepoint) +{ + TCOD_lex_savepoint((TCOD_lex_t *)data,(TCOD_lex_t *)(savepoint->data)); +} + +void TCODLex::restore(TCODLex *savepoint) +{ + TCOD_lex_restore((TCOD_lex_t *)data,(TCOD_lex_t *)(savepoint->data)); +} + +bool TCODLex::expect(int tokenType) +{ + return TCOD_lex_expect_token_type((TCOD_lex_t *)data,tokenType) != 0; +} + +bool TCODLex::expect(int tokenType, const char *tokenValue) +{ + return TCOD_lex_expect_token_value((TCOD_lex_t *)data,tokenType,tokenValue) != 0; +} diff --git a/tcod_sys/libtcod/include/lex.h b/tcod_sys/libtcod/src/libtcod/lex.h similarity index 96% rename from tcod_sys/libtcod/include/lex.h rename to tcod_sys/libtcod/src/libtcod/lex.h index fe92b7ac4..81c7aefb0 100644 --- a/tcod_sys/libtcod/include/lex.h +++ b/tcod_sys/libtcod/src/libtcod/lex.h @@ -1,109 +1,109 @@ -/* -* libtcod -* Copyright (c) 2008-2018 Jice & Mingos & rmtew -* All rights reserved. -* -* Redistribution and use in source and binary forms, with or without -* modification, are permitted provided that the following conditions are met: -* * Redistributions of source code must retain the above copyright -* notice, this list of conditions and the following disclaimer. -* * Redistributions in binary form must reproduce the above copyright -* notice, this list of conditions and the following disclaimer in the -* documentation and/or other materials provided with the distribution. -* * The name of Jice or Mingos may not be used to endorse or promote -* products derived from this software without specific prior written -* permission. -* -* THIS SOFTWARE IS PROVIDED BY JICE, MINGOS AND RMTEW ``AS IS'' AND ANY -* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED -* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE -* DISCLAIMED. IN NO EVENT SHALL JICE, MINGOS OR RMTEW BE LIABLE FOR ANY -* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES -* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; -* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND -* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS -* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. -*/ -/* - * This is a libtcod internal module. - * Use at your own risks... - */ -#ifndef _TCOD_LEX_H -#define _TCOD_LEX_H - -#include "libtcod_portability.h" - -#ifdef __cplusplus -extern "C" { -#endif - -#define TCOD_LEX_FLAG_NOCASE 1 -#define TCOD_LEX_FLAG_NESTING_COMMENT 2 -#define TCOD_LEX_FLAG_TOKENIZE_COMMENTS 4 - -#define TCOD_LEX_ERROR -1 -#define TCOD_LEX_UNKNOWN 0 -#define TCOD_LEX_SYMBOL 1 -#define TCOD_LEX_KEYWORD 2 -#define TCOD_LEX_IDEN 3 -#define TCOD_LEX_STRING 4 -#define TCOD_LEX_INTEGER 5 -#define TCOD_LEX_FLOAT 6 -#define TCOD_LEX_CHAR 7 -#define TCOD_LEX_EOF 8 -#define TCOD_LEX_COMMENT 9 - -#define TCOD_LEX_MAX_SYMBOLS 100 -#define TCOD_LEX_SYMBOL_SIZE 5 -#define TCOD_LEX_MAX_KEYWORDS 100 -#define TCOD_LEX_KEYWORD_SIZE 20 - -typedef struct { - int file_line, token_type, token_int_val, token_idx; - float token_float_val; - char *tok; - int toklen; - char lastStringDelim; - char *pos; - char *buf; - char *filename; - char *last_javadoc_comment; - /* private stuff */ - int nb_symbols, nb_keywords, flags; - char symbols[ TCOD_LEX_MAX_SYMBOLS][ TCOD_LEX_SYMBOL_SIZE ], - keywords[ TCOD_LEX_MAX_KEYWORDS ][ TCOD_LEX_KEYWORD_SIZE ]; - const char *simpleCmt; - const char *cmtStart, *cmtStop, *javadocCmtStart; - const char *stringDelim; - bool javadoc_read; - bool allocBuf; - bool savept; /* is this object a savepoint (no free in destructor) */ -} TCOD_lex_t; - -TCODLIB_API TCOD_lex_t *TCOD_lex_new_intern(void); -TCODLIB_API TCOD_lex_t *TCOD_lex_new(const char **symbols, const char **keywords, const char *simpleComment, - const char *commentStart, const char *commentStop, const char *javadocCommentStart, const char *stringDelim, int flags); -TCODLIB_API void TCOD_lex_delete(TCOD_lex_t *lex); - -TCODLIB_API void TCOD_lex_set_data_buffer(TCOD_lex_t *lex,char *dat); -TCODLIB_API bool TCOD_lex_set_data_file(TCOD_lex_t *lex,const char *filename); - -TCODLIB_API int TCOD_lex_parse(TCOD_lex_t *lex); -TCODLIB_API int TCOD_lex_parse_until_token_type(TCOD_lex_t *lex,int token_type); -TCODLIB_API int TCOD_lex_parse_until_token_value(TCOD_lex_t *lex,const char *token_value); - -TCODLIB_API bool TCOD_lex_expect_token_type(TCOD_lex_t *lex,int token_type); -TCODLIB_API bool TCOD_lex_expect_token_value(TCOD_lex_t *lex,int token_type,const char *token_value); - -TCODLIB_API void TCOD_lex_savepoint(TCOD_lex_t *lex,TCOD_lex_t *savept); -TCODLIB_API void TCOD_lex_restore(TCOD_lex_t *lex,TCOD_lex_t *savept); -TCODLIB_API char *TCOD_lex_get_last_javadoc(TCOD_lex_t *lex); -TCODLIB_API const char *TCOD_lex_get_token_name(int token_type); -TCODLIB_API char *TCOD_lex_get_last_error(void); - -TCODLIB_API int TCOD_lex_hextoint(char c); -#ifdef __cplusplus -} -#endif -#endif +/* +* libtcod +* Copyright (c) 2008-2018 Jice & Mingos & rmtew +* All rights reserved. +* +* Redistribution and use in source and binary forms, with or without +* modification, are permitted provided that the following conditions are met: +* * Redistributions of source code must retain the above copyright +* notice, this list of conditions and the following disclaimer. +* * Redistributions in binary form must reproduce the above copyright +* notice, this list of conditions and the following disclaimer in the +* documentation and/or other materials provided with the distribution. +* * The name of Jice or Mingos may not be used to endorse or promote +* products derived from this software without specific prior written +* permission. +* +* THIS SOFTWARE IS PROVIDED BY JICE, MINGOS AND RMTEW ``AS IS'' AND ANY +* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED +* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE +* DISCLAIMED. IN NO EVENT SHALL JICE, MINGOS OR RMTEW BE LIABLE FOR ANY +* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES +* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; +* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND +* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS +* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +*/ +/* + * This is a libtcod internal module. + * Use at your own risks... + */ +#ifndef _TCOD_LEX_H +#define _TCOD_LEX_H + +#include "portability.h" + +#ifdef __cplusplus +extern "C" { +#endif + +#define TCOD_LEX_FLAG_NOCASE 1 +#define TCOD_LEX_FLAG_NESTING_COMMENT 2 +#define TCOD_LEX_FLAG_TOKENIZE_COMMENTS 4 + +#define TCOD_LEX_ERROR -1 +#define TCOD_LEX_UNKNOWN 0 +#define TCOD_LEX_SYMBOL 1 +#define TCOD_LEX_KEYWORD 2 +#define TCOD_LEX_IDEN 3 +#define TCOD_LEX_STRING 4 +#define TCOD_LEX_INTEGER 5 +#define TCOD_LEX_FLOAT 6 +#define TCOD_LEX_CHAR 7 +#define TCOD_LEX_EOF 8 +#define TCOD_LEX_COMMENT 9 + +#define TCOD_LEX_MAX_SYMBOLS 100 +#define TCOD_LEX_SYMBOL_SIZE 5 +#define TCOD_LEX_MAX_KEYWORDS 100 +#define TCOD_LEX_KEYWORD_SIZE 20 + +typedef struct { + int file_line, token_type, token_int_val, token_idx; + float token_float_val; + char *tok; + int toklen; + char lastStringDelim; + char *pos; + char *buf; + char *filename; + char *last_javadoc_comment; + /* private stuff */ + int nb_symbols, nb_keywords, flags; + char symbols[ TCOD_LEX_MAX_SYMBOLS][ TCOD_LEX_SYMBOL_SIZE ], + keywords[ TCOD_LEX_MAX_KEYWORDS ][ TCOD_LEX_KEYWORD_SIZE ]; + const char *simpleCmt; + const char *cmtStart, *cmtStop, *javadocCmtStart; + const char *stringDelim; + bool javadoc_read; + bool allocBuf; + bool savept; /* is this object a savepoint (no free in destructor) */ +} TCOD_lex_t; + +TCODLIB_API TCOD_lex_t *TCOD_lex_new_intern(void); +TCODLIB_API TCOD_lex_t *TCOD_lex_new(const char **symbols, const char **keywords, const char *simpleComment, + const char *commentStart, const char *commentStop, const char *javadocCommentStart, const char *stringDelim, int flags); +TCODLIB_API void TCOD_lex_delete(TCOD_lex_t *lex); + +TCODLIB_API void TCOD_lex_set_data_buffer(TCOD_lex_t *lex,char *dat); +TCODLIB_API bool TCOD_lex_set_data_file(TCOD_lex_t *lex,const char *filename); + +TCODLIB_API int TCOD_lex_parse(TCOD_lex_t *lex); +TCODLIB_API int TCOD_lex_parse_until_token_type(TCOD_lex_t *lex,int token_type); +TCODLIB_API int TCOD_lex_parse_until_token_value(TCOD_lex_t *lex,const char *token_value); + +TCODLIB_API bool TCOD_lex_expect_token_type(TCOD_lex_t *lex,int token_type); +TCODLIB_API bool TCOD_lex_expect_token_value(TCOD_lex_t *lex,int token_type,const char *token_value); + +TCODLIB_API void TCOD_lex_savepoint(TCOD_lex_t *lex,TCOD_lex_t *savept); +TCODLIB_API void TCOD_lex_restore(TCOD_lex_t *lex,TCOD_lex_t *savept); +TCODLIB_API char *TCOD_lex_get_last_javadoc(TCOD_lex_t *lex); +TCODLIB_API const char *TCOD_lex_get_token_name(int token_type); +TCODLIB_API char *TCOD_lex_get_last_error(void); + +TCODLIB_API int TCOD_lex_hextoint(char c); +#ifdef __cplusplus +} +#endif +#endif diff --git a/tcod_sys/libtcod/include/lex.hpp b/tcod_sys/libtcod/src/libtcod/lex.hpp similarity index 100% rename from tcod_sys/libtcod/include/lex.hpp rename to tcod_sys/libtcod/src/libtcod/lex.hpp diff --git a/tcod_sys/libtcod/src/lex_c.c b/tcod_sys/libtcod/src/libtcod/lex_c.c similarity index 96% rename from tcod_sys/libtcod/src/lex_c.c rename to tcod_sys/libtcod/src/libtcod/lex_c.c index 525a3b210..d8c8aa17b 100644 --- a/tcod_sys/libtcod/src/lex_c.c +++ b/tcod_sys/libtcod/src/libtcod/lex_c.c @@ -1,702 +1,702 @@ -/* -* libtcod -* Copyright (c) 2008-2018 Jice & Mingos & rmtew -* All rights reserved. -* -* Redistribution and use in source and binary forms, with or without -* modification, are permitted provided that the following conditions are met: -* * Redistributions of source code must retain the above copyright -* notice, this list of conditions and the following disclaimer. -* * Redistributions in binary form must reproduce the above copyright -* notice, this list of conditions and the following disclaimer in the -* documentation and/or other materials provided with the distribution. -* * The name of Jice or Mingos may not be used to endorse or promote -* products derived from this software without specific prior written -* permission. -* -* THIS SOFTWARE IS PROVIDED BY JICE, MINGOS AND RMTEW ``AS IS'' AND ANY -* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED -* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE -* DISCLAIMED. IN NO EVENT SHALL JICE, MINGOS OR RMTEW BE LIABLE FOR ANY -* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES -* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; -* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND -* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS -* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. -*/ -#include - -#include -#include -#include -#include - -#define MAX_JAVADOC_COMMENT_SIZE 16384 - -/* damn ANSI C does not know strdup, strcasecmp, strncasecmp */ -char *TCOD_strdup(const char *str) { - size_t l = strlen(str) + 1; - char *duplicate = malloc(l); - if (duplicate) { strcpy(duplicate, str); } - return duplicate; -} - -int TCOD_strcasecmp(const char *s1, const char *s2) { - unsigned char c1,c2; - do { - c1 = *s1++; - c2 = *s2++; - c1 = (unsigned char) tolower( (unsigned char) c1); - c2 = (unsigned char) tolower( (unsigned char) c2); - } while((c1 == c2) && (c1 != '\0')); - return (int) c1-c2; -} - -int TCOD_strncasecmp(const char *s1, const char *s2, size_t n) { - unsigned char c1,c2; - do { - c1 = *s1++; - c2 = *s2++; - c1 = (unsigned char) tolower( (unsigned char) c1); - c2 = (unsigned char) tolower( (unsigned char) c2); - n--; - } while((c1 == c2) && (c1 != '\0') && n > 0); - return (int) c1-c2; -} - -static const char * TCOD_LEX_names[] = { - "unknown token", - "symbol", - "keyword", - "identifier", - "string", - "integer", - "float", - "char", - "eof" -}; - -static char *TCOD_last_error=NULL; - -const char *TCOD_lex_get_token_name(int token_type) { return TCOD_LEX_names[token_type]; } - -static void allocate_tok(TCOD_lex_t *lex, int len) { - if ( lex->toklen > len ) return; - while ( lex->toklen <= len ) lex->toklen *= 2; - lex->tok = (char *)realloc(lex->tok,lex->toklen); -} - - -char *TCOD_lex_get_last_error(void) { - return TCOD_last_error; -} - -TCOD_lex_t *TCOD_lex_new_intern(void) { - return (TCOD_lex_t *)calloc(1,sizeof(TCOD_lex_t)); -} - -TCOD_lex_t * TCOD_lex_new( const char **_symbols, const char **_keywords, const char *simpleComment, - const char *commentStart, const char *commentStop, const char *javadocCommentStart, - const char *_stringDelim, int _flags) -{ - TCOD_lex_t *lex=(TCOD_lex_t *)TCOD_lex_new_intern(); - lex->flags = _flags; - lex->last_javadoc_comment = (char *)calloc(sizeof(char),MAX_JAVADOC_COMMENT_SIZE ); - if ( _symbols ) - { - while ( _symbols[ lex->nb_symbols ] ) - { - if ( strlen( _symbols[ lex->nb_symbols ] ) >= TCOD_LEX_SYMBOL_SIZE ) - { - static char msg[255]; - sprintf (msg, "symbol '%s' too long (max size %d)", - _symbols[ lex->nb_symbols ], TCOD_LEX_SYMBOL_SIZE ); - TCOD_last_error=TCOD_strdup(msg); - TCOD_lex_delete (lex); - return NULL; - } - strcpy(lex->symbols[ lex->nb_symbols ], _symbols[ lex->nb_symbols ] ); - lex->nb_symbols++; - } - } - if ( _keywords ) - { - while ( _keywords[ lex->nb_keywords ] ) - { - if ( strlen( _keywords[ lex->nb_keywords ] ) >= TCOD_LEX_KEYWORD_SIZE ) - { - static char msg[255]; - sprintf(msg,"keyword '%s' too long (max size %d)", - _keywords[ lex->nb_keywords ], TCOD_LEX_KEYWORD_SIZE); - TCOD_last_error=TCOD_strdup(msg); - TCOD_lex_delete (lex); - return NULL; - } - if ( lex->flags & TCOD_LEX_FLAG_NOCASE ) - { - char *ptr = (char *)_keywords[ lex->nb_keywords ]; - while ( *ptr ) - { - *ptr = (char)toupper( *ptr); - ptr++; - } - } - strcpy(lex->keywords[ lex->nb_keywords ], _keywords[ lex->nb_keywords ] ); - lex->nb_keywords++; - } - } - lex->simpleCmt = simpleComment; - lex->cmtStart = commentStart; - lex->cmtStop = commentStop; - lex->javadocCmtStart = javadocCommentStart; - lex->stringDelim = _stringDelim; - lex->lastStringDelim='\0'; - lex->tok = (char *)calloc(sizeof(char),256); - lex->toklen=256; - return (TCOD_lex_t *)lex; -} - -char *TCOD_lex_get_last_javadoc(TCOD_lex_t *lex) -{ - if ( ! lex->javadoc_read && lex->last_javadoc_comment[0] != '\0' ) - { - lex->javadoc_read=true; - return lex->last_javadoc_comment; - } - lex->javadoc_read=false; - lex->last_javadoc_comment[0]='\0'; - return NULL; -} - -void TCOD_lex_delete(TCOD_lex_t *lex) -{ - if ( ! lex->savept ) - { - if ( lex->filename ) free( lex->filename ); - if ( lex->buf && lex->allocBuf ) free(lex->buf); - if ( lex->last_javadoc_comment ) free(lex->last_javadoc_comment); - } - lex->filename=NULL; - lex->buf = NULL; - lex->allocBuf=false; - if ( lex->tok ) free(lex->tok); - free(lex); -} - -void TCOD_lex_set_data_buffer_internal(TCOD_lex_t *lex) -{ - lex->file_line = 1; - lex->pos = lex->buf; - lex->token_type = TCOD_LEX_UNKNOWN; - lex->token_int_val = 0; - lex->token_float_val = 0.0; - lex->token_idx = -1; - lex->tok[0] = '\0'; -} - - -void TCOD_lex_set_data_buffer(TCOD_lex_t *lex,char *dat) -{ - lex->buf = dat; - lex->allocBuf = false; - TCOD_lex_set_data_buffer_internal(lex); -} - -bool TCOD_lex_set_data_file(TCOD_lex_t *lex, const char *_filename) -{ - FILE *f; - char *ptr; - long size; - if ( ! _filename ) { - TCOD_last_error = (char *)"Lex.setDatafile(NULL) called"; - return false; - } - f = fopen( _filename, "rb" ); - if ( f == NULL ) - { - static char msg[255]; - sprintf(msg, "Cannot open '%s'", _filename); - TCOD_last_error=TCOD_strdup(msg); - return false; - } - fseek(f, 0, SEEK_END); - size = ftell(f); - fclose(f); - f = fopen( _filename, "r" ); - - lex->buf = (char*)calloc(sizeof(char),(size + 1)); - lex->filename = TCOD_strdup( _filename ); - if ( lex->buf == NULL || lex->filename == NULL ) - { - fclose(f); - if ( lex->buf ) free(lex->buf); - if ( lex->filename ) { - free( lex->filename ); - } - TCOD_last_error=(char *)"Out of memory"; - return false; - } - ptr=lex->buf; - /* can't rely on size to read because of MS/DOS dumb CR/LF handling */ - while ( fgets(ptr, size,f ) ) - { - ptr += strlen(ptr); - } - fclose(f); - TCOD_lex_set_data_buffer_internal(lex); - lex->allocBuf=true; - return true; -} - -void TCOD_lex_get_new_line(TCOD_lex_t *lex) -{ - if ( *(lex->pos) == '\n' ) - { - lex->file_line ++; - lex->pos++; - } -} - -#ifdef TCOD_VISUAL_STUDIO -#pragma warning(disable:4127) /* conditional expression is constant */ -#endif - -int TCOD_lex_get_space(TCOD_lex_t *lex) -{ - char c; - char *startPos=NULL; - while ( 1 ) - { - while ( (c = *lex->pos) <= ' ') - { - if (c=='\n') - TCOD_lex_get_new_line(lex); - else if (c == 0) - return TCOD_LEX_EOF; /* end of file */ - else lex->pos++; - } - if ( lex->simpleCmt && strncmp(lex->pos, lex->simpleCmt, strlen(lex->simpleCmt)) == 0 ) - { - if ( ! startPos ) startPos = lex->pos; - while ( *lex->pos != '\0' && *lex->pos != '\n' ) - lex->pos++; - TCOD_lex_get_new_line(lex); - continue; - } - if ( lex->cmtStart && lex->cmtStop && strncmp(lex->pos, lex->cmtStart, strlen(lex->cmtStart)) == 0 ) - { - int isJavadoc=( lex->javadocCmtStart && strncmp(lex->pos, lex->javadocCmtStart, strlen(lex->javadocCmtStart)) == 0 ); - int cmtLevel=1; - char *javadocStart = NULL; - if ( ! startPos ) startPos = lex->pos; - if ( isJavadoc ) - { - javadocStart=lex->pos+strlen(lex->javadocCmtStart); - while ( isspace(*javadocStart) ) javadocStart++; - } - lex->pos++; - do - { - if ( *lex->pos == '\n' ) - { - TCOD_lex_get_new_line(lex); - } - else - lex->pos++; - if ( *lex->pos == '\0' ) - return TCOD_LEX_EOF; - if ( (lex->flags & TCOD_LEX_FLAG_NESTING_COMMENT) && strncmp(lex->pos-1, lex->cmtStart, strlen(lex->cmtStart)) == 0) cmtLevel++; - if ( strncmp(lex->pos-1, lex->cmtStop, strlen(lex->cmtStop)) == 0) cmtLevel--; - } while ( cmtLevel > 0 ); - lex->pos++; - if ( isJavadoc ) - { - char *src, *dst; - char *end = lex->pos - strlen(lex->cmtStop); - while ( isspace(*end) && end > javadocStart ) end --; - src = javadocStart; - dst = lex->last_javadoc_comment; - while ( src < end ) - { - /* skip heading spaces */ - while ( src < end && isspace(*src) && *src != '\n') src ++; - /* copy comment line */ - while ( src < end && *src != '\n' ) *dst++ = *src++; - if ( *src == '\n' ) *dst++ = *src++; - } - /* remove trailing spaces */ - while ( dst > lex->last_javadoc_comment && isspace (*(dst-1)) ) dst --; - *dst = '\0'; - lex->javadoc_read=false; - } - continue; - } - break; - } - if ( (lex->flags & TCOD_LEX_FLAG_TOKENIZE_COMMENTS) && startPos && lex->pos > startPos ) { - int len = (int)(lex->pos - startPos); - allocate_tok(lex, len+1); - strncpy(lex->tok,startPos,len); - lex->tok[len]=0; - lex->token_type = TCOD_LEX_COMMENT; - lex->token_idx = -1; - return TCOD_LEX_COMMENT; - } - return TCOD_LEX_UNKNOWN; -} - - - -int TCOD_lex_hextoint(char c) { - int v=toupper(c); - if ( v >= '0' && v <= '9' ) return v-'0'; - return 10 + (v-'A'); -} - -static bool TCOD_lex_get_special_char(TCOD_lex_t *lex, char *c) { - *c = *(++(lex->pos) ); - - switch ( *c ) - { - case 'n' : *c='\n'; break; - case 't' : *c='\t'; break; - case 'r' : *c='\r'; break; - case '\\' : - case '\"' : - case '\'' : - break; - case 'x' : - { - /* hexadecimal value "\x80" */ - int value=0; - bool hasHex=false; - *c = *(++(lex->pos) ); - while (( *c >= '0' && *c <= '9' ) || (*c >= 'a' && *c <= 'f') || (*c >= 'A' && *c <= 'F') ) { - hasHex=true; - value <<= 4; - value += TCOD_lex_hextoint(*c); - *c = *(++(lex->pos) ); - } - if (! hasHex ) { - TCOD_last_error=(char *)"\\x must be followed by an hexadecimal value"; - return false; - } - *c = value; - lex->pos--; - } - break; - case '0' : - case '1' : - case '2' : - case '3' : - case '4' : - case '5' : - case '6' : - case '7' : - { - /* octal value "\200" */ - int value=0; - while ( *c >= '0' && *c <= '7' ) { - value <<= 3; - value += (*c - '0'); - *c = *(++(lex->pos) ); - } - *c = value; - lex->pos--; - } - break; - default : - TCOD_last_error=(char *)"bad escape sequence inside quote"; - return false; - } - return true; -} - -int TCOD_lex_get_string(TCOD_lex_t *lex) -{ - char c; - int len = 0; - do - { - c= *(++(lex->pos)); - if ( c == '\0' ) { - TCOD_last_error=(char *)"EOF inside quote"; - return TCOD_LEX_ERROR; - } - if ( c == '\n' ) { - TCOD_last_error=(char *)"newline inside quote"; - return TCOD_LEX_ERROR; - } - if ( c== '\\' ) - { - if ( ! TCOD_lex_get_special_char(lex,&c) ) return TCOD_LEX_ERROR; - } - else if ( c == lex->lastStringDelim ) - { - allocate_tok(lex, len); - lex->tok[ len ] = '\0'; - lex->token_type = TCOD_LEX_STRING; - lex->token_idx = -1; - lex->pos++; - return TCOD_LEX_STRING; - } - allocate_tok(lex, len); - lex->tok[ len++ ] = c; - } while ( 1 ); -} - -#ifdef TCOD_VISUAL_STUDIO -#pragma warning(default:4127) /* conditional expression is constant */ -#endif - -int TCOD_lex_get_number(TCOD_lex_t *lex) -{ - int c; - int len; - char *ptr; - int bhex = 0, bfloat = 0; - - len = 0; - if ( *lex->pos == '-' ) - { - allocate_tok(lex, len); - lex->tok[ len ++ ] = '-'; - lex->pos++; - } - - c = toupper(*lex->pos); - - if ( c == '0' && ( lex->pos[1] == 'x' || lex->pos[1]=='X') ) - { - bhex = 1; - allocate_tok(lex, len); - lex->tok[ len ++ ] = '0'; - lex->pos++; - c = toupper( * (lex->pos)); - } - do - { - allocate_tok(lex, len); - lex->tok[ len++ ] = (char)c; - lex->pos++; - if ( c == '.' ) - { - if ( bhex ) { - TCOD_last_error=(char *)"bad constant format"; - return TCOD_LEX_ERROR; - } - bfloat = 1; - } - c = toupper(*lex->pos); - } while ((c >= '0' && c<= '9') - || ( bhex && c >= 'A' && c <= 'F' ) - || c == '.' ); - allocate_tok(lex, len); - lex->tok[len] = 0; - - if ( !bfloat ) - { - lex->token_int_val = strtol( lex->tok, &ptr, 0 ); - lex->token_float_val = (float)lex->token_int_val; - lex->token_type = TCOD_LEX_INTEGER; - lex->token_idx = -1; - return TCOD_LEX_INTEGER; - } - else - { - lex->token_float_val = (float)atof( lex->tok ); - lex->token_type = TCOD_LEX_FLOAT; - lex->token_idx = -1; - return TCOD_LEX_FLOAT; - } -} - -int TCOD_lex_get_char(TCOD_lex_t *lex) -{ - char c; - c= *(++(lex->pos)); - - if ( c == '\0' ) { - TCOD_last_error=(char *)"EOF inside simple quote"; - return TCOD_LEX_ERROR; - } - if ( c == '\n' ) { - TCOD_last_error=(char *)"newline inside simple quote"; - return TCOD_LEX_ERROR; - } - if ( c== '\\' ) - { - if ( ! TCOD_lex_get_special_char(lex,&c) ) return TCOD_LEX_ERROR; - lex->pos++; - } - else - lex->pos++; - - if ( *lex->pos != '\'' ) { - TCOD_last_error= (char *)"bad character inside simple quote" ; - return TCOD_LEX_ERROR; - } - lex->pos ++; - lex->tok[ 0 ] = c; - lex->tok[ 1 ] = '\0'; - lex->token_type = TCOD_LEX_CHAR; - lex->token_int_val = (int)c; - lex->token_idx = -1; - return TCOD_LEX_CHAR; -} - -int TCOD_lex_get_symbol(TCOD_lex_t *lex) -{ - int symb = 0; - static char msg[255]; - - while ( symb < lex->nb_symbols ) - { - if ( ( ( lex->flags & TCOD_LEX_FLAG_NOCASE ) - && TCOD_strncasecmp( lex->symbols[ symb ], lex->pos, strlen( lex->symbols[ symb ] ) ) == 0 ) - || ( strncmp( lex->symbols[ symb ], lex->pos, strlen( lex->symbols[ symb ] ) ) == 0 ) ) - { - strcpy( lex->tok, lex->symbols[ symb ] ); - lex->pos += strlen( lex->symbols[ symb ] ); - lex->token_idx = symb; - lex->token_type = TCOD_LEX_SYMBOL; - return TCOD_LEX_SYMBOL; - } - symb ++; - } - - lex->pos++; - sprintf(msg, "unknown symbol %.10s", lex->pos-1 ); - TCOD_last_error=TCOD_strdup(msg); - return TCOD_LEX_ERROR; -} - -int TCOD_lex_get_iden(TCOD_lex_t *lex) -{ - char c = *lex->pos; - int len = 0, key = 0; - - do - { - allocate_tok(lex, len); - lex->tok[ len++ ] = c; - c = *( ++ (lex->pos) ); - } while ( ( c >= 'a' && c <= 'z' ) - || ( c >= 'A' && c <= 'Z' ) - || ( c >= '0' && c <= '9' ) - || c == '_' ); - allocate_tok(lex, len); - lex->tok[len ] = 0; - - while ( key < lex->nb_keywords ) - { - if ( strcmp( lex->tok, lex->keywords[ key ] ) == 0 - || ( lex->flags & TCOD_LEX_FLAG_NOCASE && TCOD_strcasecmp( lex->tok, lex->keywords[ key ] ) == 0 )) - { - lex->token_type = TCOD_LEX_KEYWORD; - lex->token_idx = key; - return TCOD_LEX_KEYWORD; - } - key ++; - } - - lex->token_type = TCOD_LEX_IDEN; - lex->token_idx = -1; - return TCOD_LEX_IDEN; -} - -int TCOD_lex_parse(TCOD_lex_t *lex) -{ - char *ptr; - int token; - - token = TCOD_lex_get_space(lex); - if ( token == TCOD_LEX_ERROR ) return token; - ptr = lex->pos; - if ( token != TCOD_LEX_UNKNOWN ) - { - lex->token_type = token; - return token; - } - if ( strchr(lex->stringDelim, *ptr) ) - { - lex->lastStringDelim=*ptr; - return TCOD_lex_get_string(lex); - } - if ( *ptr == '\'' ) - { - return TCOD_lex_get_char(lex); - } - if ( isdigit( (int)(*ptr) ) - || ( *ptr == '-' && isdigit( (int)(ptr[1]) ) ) - ) - { - return TCOD_lex_get_number(lex); - } - if ( ( *ptr >= 'a' && *ptr <= 'z' ) || ( *ptr >= 'A' && *ptr <= 'Z' ) - || *ptr == '_' ) - { - return TCOD_lex_get_iden(lex); - } - return TCOD_lex_get_symbol(lex); -} - - -int TCOD_lex_parse_until_token_type(TCOD_lex_t *lex,int tokenType) -{ - int token; - token = TCOD_lex_parse(lex); - if ( token == TCOD_LEX_ERROR ) return token; - while ( token != TCOD_LEX_EOF ) - { - if ( token == tokenType ) - return token; - token = TCOD_lex_parse(lex); - if ( token == TCOD_LEX_ERROR ) return token; - } - return token; -} - -int TCOD_lex_parse_until_token_value(TCOD_lex_t *lex, const char *tokenValue) -{ - int token; - token = TCOD_lex_parse(lex); - if ( token == TCOD_LEX_ERROR ) return token; - { - while ( token != TCOD_LEX_EOF ) - if ( strcmp( lex->tok, tokenValue ) == 0 - || ( ( lex->flags & TCOD_LEX_FLAG_NOCASE ) && TCOD_strcasecmp(lex->tok, tokenValue ) == 0 ) ) - return token; - token = TCOD_lex_parse(lex); - if ( token == TCOD_LEX_ERROR ) return token; - } - return token; -} - -void TCOD_lex_savepoint(TCOD_lex_t *lex,TCOD_lex_t *_savept) -{ - TCOD_lex_t *savept=(TCOD_lex_t *)_savept; - *savept = *lex; - savept->tok = (char *)calloc(sizeof(char),lex->toklen); - strcpy(savept->tok,lex->tok); - savept->savept=true; -} - -void TCOD_lex_restore(TCOD_lex_t *lex,TCOD_lex_t *_savept) -{ - TCOD_lex_t *savept=(TCOD_lex_t *)_savept; - *lex = *savept; - lex->savept=false; -} - -bool TCOD_lex_expect_token_type(TCOD_lex_t *lex,int token_type) -{ - return (TCOD_lex_parse(lex) == token_type); -} - -bool TCOD_lex_expect_token_value(TCOD_lex_t *lex,int token_type, const char *token_value) -{ - TCOD_lex_parse(lex); - return (token_type == lex->token_type && strcmp(lex->tok, token_value) == 0 ); -} +/* +* libtcod +* Copyright (c) 2008-2018 Jice & Mingos & rmtew +* All rights reserved. +* +* Redistribution and use in source and binary forms, with or without +* modification, are permitted provided that the following conditions are met: +* * Redistributions of source code must retain the above copyright +* notice, this list of conditions and the following disclaimer. +* * Redistributions in binary form must reproduce the above copyright +* notice, this list of conditions and the following disclaimer in the +* documentation and/or other materials provided with the distribution. +* * The name of Jice or Mingos may not be used to endorse or promote +* products derived from this software without specific prior written +* permission. +* +* THIS SOFTWARE IS PROVIDED BY JICE, MINGOS AND RMTEW ``AS IS'' AND ANY +* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED +* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE +* DISCLAIMED. IN NO EVENT SHALL JICE, MINGOS OR RMTEW BE LIABLE FOR ANY +* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES +* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; +* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND +* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS +* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +*/ +#include "lex.h" + +#include +#include +#include +#include + +#define MAX_JAVADOC_COMMENT_SIZE 16384 + +/* damn ANSI C does not know strdup, strcasecmp, strncasecmp */ +char *TCOD_strdup(const char *str) { + size_t l = strlen(str) + 1; + char *duplicate = malloc(l); + if (duplicate) { strcpy(duplicate, str); } + return duplicate; +} + +int TCOD_strcasecmp(const char *s1, const char *s2) { + unsigned char c1,c2; + do { + c1 = *s1++; + c2 = *s2++; + c1 = (unsigned char) tolower( (unsigned char) c1); + c2 = (unsigned char) tolower( (unsigned char) c2); + } while((c1 == c2) && (c1 != '\0')); + return (int) c1-c2; +} + +int TCOD_strncasecmp(const char *s1, const char *s2, size_t n) { + unsigned char c1,c2; + do { + c1 = *s1++; + c2 = *s2++; + c1 = (unsigned char) tolower( (unsigned char) c1); + c2 = (unsigned char) tolower( (unsigned char) c2); + n--; + } while((c1 == c2) && (c1 != '\0') && n > 0); + return (int) c1-c2; +} + +static const char * TCOD_LEX_names[] = { + "unknown token", + "symbol", + "keyword", + "identifier", + "string", + "integer", + "float", + "char", + "eof" +}; + +static char *TCOD_last_error=NULL; + +const char *TCOD_lex_get_token_name(int token_type) { return TCOD_LEX_names[token_type]; } + +static void allocate_tok(TCOD_lex_t *lex, int len) { + if ( lex->toklen > len ) return; + while ( lex->toklen <= len ) lex->toklen *= 2; + lex->tok = (char *)realloc(lex->tok,lex->toklen); +} + + +char *TCOD_lex_get_last_error(void) { + return TCOD_last_error; +} + +TCOD_lex_t *TCOD_lex_new_intern(void) { + return (TCOD_lex_t *)calloc(1,sizeof(TCOD_lex_t)); +} + +TCOD_lex_t * TCOD_lex_new( const char **_symbols, const char **_keywords, const char *simpleComment, + const char *commentStart, const char *commentStop, const char *javadocCommentStart, + const char *_stringDelim, int _flags) +{ + TCOD_lex_t *lex=(TCOD_lex_t *)TCOD_lex_new_intern(); + lex->flags = _flags; + lex->last_javadoc_comment = (char *)calloc(sizeof(char),MAX_JAVADOC_COMMENT_SIZE ); + if ( _symbols ) + { + while ( _symbols[ lex->nb_symbols ] ) + { + if ( strlen( _symbols[ lex->nb_symbols ] ) >= TCOD_LEX_SYMBOL_SIZE ) + { + static char msg[255]; + sprintf (msg, "symbol '%s' too long (max size %d)", + _symbols[ lex->nb_symbols ], TCOD_LEX_SYMBOL_SIZE ); + TCOD_last_error=TCOD_strdup(msg); + TCOD_lex_delete (lex); + return NULL; + } + strcpy(lex->symbols[ lex->nb_symbols ], _symbols[ lex->nb_symbols ] ); + lex->nb_symbols++; + } + } + if ( _keywords ) + { + while ( _keywords[ lex->nb_keywords ] ) + { + if ( strlen( _keywords[ lex->nb_keywords ] ) >= TCOD_LEX_KEYWORD_SIZE ) + { + static char msg[255]; + sprintf(msg,"keyword '%s' too long (max size %d)", + _keywords[ lex->nb_keywords ], TCOD_LEX_KEYWORD_SIZE); + TCOD_last_error=TCOD_strdup(msg); + TCOD_lex_delete (lex); + return NULL; + } + if ( lex->flags & TCOD_LEX_FLAG_NOCASE ) + { + char *ptr = (char *)_keywords[ lex->nb_keywords ]; + while ( *ptr ) + { + *ptr = (char)toupper( *ptr); + ptr++; + } + } + strcpy(lex->keywords[ lex->nb_keywords ], _keywords[ lex->nb_keywords ] ); + lex->nb_keywords++; + } + } + lex->simpleCmt = simpleComment; + lex->cmtStart = commentStart; + lex->cmtStop = commentStop; + lex->javadocCmtStart = javadocCommentStart; + lex->stringDelim = _stringDelim; + lex->lastStringDelim='\0'; + lex->tok = (char *)calloc(sizeof(char),256); + lex->toklen=256; + return (TCOD_lex_t *)lex; +} + +char *TCOD_lex_get_last_javadoc(TCOD_lex_t *lex) +{ + if ( ! lex->javadoc_read && lex->last_javadoc_comment[0] != '\0' ) + { + lex->javadoc_read=true; + return lex->last_javadoc_comment; + } + lex->javadoc_read=false; + lex->last_javadoc_comment[0]='\0'; + return NULL; +} + +void TCOD_lex_delete(TCOD_lex_t *lex) +{ + if ( ! lex->savept ) + { + if ( lex->filename ) free( lex->filename ); + if ( lex->buf && lex->allocBuf ) free(lex->buf); + if ( lex->last_javadoc_comment ) free(lex->last_javadoc_comment); + } + lex->filename=NULL; + lex->buf = NULL; + lex->allocBuf=false; + if ( lex->tok ) free(lex->tok); + free(lex); +} + +void TCOD_lex_set_data_buffer_internal(TCOD_lex_t *lex) +{ + lex->file_line = 1; + lex->pos = lex->buf; + lex->token_type = TCOD_LEX_UNKNOWN; + lex->token_int_val = 0; + lex->token_float_val = 0.0; + lex->token_idx = -1; + lex->tok[0] = '\0'; +} + + +void TCOD_lex_set_data_buffer(TCOD_lex_t *lex,char *dat) +{ + lex->buf = dat; + lex->allocBuf = false; + TCOD_lex_set_data_buffer_internal(lex); +} + +bool TCOD_lex_set_data_file(TCOD_lex_t *lex, const char *_filename) +{ + FILE *f; + char *ptr; + long size; + if ( ! _filename ) { + TCOD_last_error = (char *)"Lex.setDatafile(NULL) called"; + return false; + } + f = fopen( _filename, "rb" ); + if ( f == NULL ) + { + static char msg[255]; + sprintf(msg, "Cannot open '%s'", _filename); + TCOD_last_error=TCOD_strdup(msg); + return false; + } + fseek(f, 0, SEEK_END); + size = ftell(f); + fclose(f); + f = fopen( _filename, "r" ); + + lex->buf = (char*)calloc(sizeof(char),(size + 1)); + lex->filename = TCOD_strdup( _filename ); + if ( lex->buf == NULL || lex->filename == NULL ) + { + fclose(f); + if ( lex->buf ) free(lex->buf); + if ( lex->filename ) { + free( lex->filename ); + } + TCOD_last_error=(char *)"Out of memory"; + return false; + } + ptr=lex->buf; + /* can't rely on size to read because of MS/DOS dumb CR/LF handling */ + while ( fgets(ptr, size,f ) ) + { + ptr += strlen(ptr); + } + fclose(f); + TCOD_lex_set_data_buffer_internal(lex); + lex->allocBuf=true; + return true; +} + +void TCOD_lex_get_new_line(TCOD_lex_t *lex) +{ + if ( *(lex->pos) == '\n' ) + { + lex->file_line ++; + lex->pos++; + } +} + +#ifdef TCOD_VISUAL_STUDIO +#pragma warning(disable:4127) /* conditional expression is constant */ +#endif + +int TCOD_lex_get_space(TCOD_lex_t *lex) +{ + char c; + char *startPos=NULL; + while ( 1 ) + { + while ( (c = *lex->pos) <= ' ') + { + if (c=='\n') + TCOD_lex_get_new_line(lex); + else if (c == 0) + return TCOD_LEX_EOF; /* end of file */ + else lex->pos++; + } + if ( lex->simpleCmt && strncmp(lex->pos, lex->simpleCmt, strlen(lex->simpleCmt)) == 0 ) + { + if ( ! startPos ) startPos = lex->pos; + while ( *lex->pos != '\0' && *lex->pos != '\n' ) + lex->pos++; + TCOD_lex_get_new_line(lex); + continue; + } + if ( lex->cmtStart && lex->cmtStop && strncmp(lex->pos, lex->cmtStart, strlen(lex->cmtStart)) == 0 ) + { + int isJavadoc=( lex->javadocCmtStart && strncmp(lex->pos, lex->javadocCmtStart, strlen(lex->javadocCmtStart)) == 0 ); + int cmtLevel=1; + char *javadocStart = NULL; + if ( ! startPos ) startPos = lex->pos; + if ( isJavadoc ) + { + javadocStart=lex->pos+strlen(lex->javadocCmtStart); + while ( isspace(*javadocStart) ) javadocStart++; + } + lex->pos++; + do + { + if ( *lex->pos == '\n' ) + { + TCOD_lex_get_new_line(lex); + } + else + lex->pos++; + if ( *lex->pos == '\0' ) + return TCOD_LEX_EOF; + if ( (lex->flags & TCOD_LEX_FLAG_NESTING_COMMENT) && strncmp(lex->pos-1, lex->cmtStart, strlen(lex->cmtStart)) == 0) cmtLevel++; + if ( strncmp(lex->pos-1, lex->cmtStop, strlen(lex->cmtStop)) == 0) cmtLevel--; + } while ( cmtLevel > 0 ); + lex->pos++; + if ( isJavadoc ) + { + char *src, *dst; + char *end = lex->pos - strlen(lex->cmtStop); + while ( isspace(*end) && end > javadocStart ) end --; + src = javadocStart; + dst = lex->last_javadoc_comment; + while ( src < end ) + { + /* skip heading spaces */ + while ( src < end && isspace(*src) && *src != '\n') src ++; + /* copy comment line */ + while ( src < end && *src != '\n' ) *dst++ = *src++; + if ( *src == '\n' ) *dst++ = *src++; + } + /* remove trailing spaces */ + while ( dst > lex->last_javadoc_comment && isspace (*(dst-1)) ) dst --; + *dst = '\0'; + lex->javadoc_read=false; + } + continue; + } + break; + } + if ( (lex->flags & TCOD_LEX_FLAG_TOKENIZE_COMMENTS) && startPos && lex->pos > startPos ) { + int len = (int)(lex->pos - startPos); + allocate_tok(lex, len+1); + strncpy(lex->tok,startPos,len); + lex->tok[len]=0; + lex->token_type = TCOD_LEX_COMMENT; + lex->token_idx = -1; + return TCOD_LEX_COMMENT; + } + return TCOD_LEX_UNKNOWN; +} + + + +int TCOD_lex_hextoint(char c) { + int v=toupper(c); + if ( v >= '0' && v <= '9' ) return v-'0'; + return 10 + (v-'A'); +} + +static bool TCOD_lex_get_special_char(TCOD_lex_t *lex, char *c) { + *c = *(++(lex->pos) ); + + switch ( *c ) + { + case 'n' : *c='\n'; break; + case 't' : *c='\t'; break; + case 'r' : *c='\r'; break; + case '\\' : + case '\"' : + case '\'' : + break; + case 'x' : + { + /* hexadecimal value "\x80" */ + int value=0; + bool hasHex=false; + *c = *(++(lex->pos) ); + while (( *c >= '0' && *c <= '9' ) || (*c >= 'a' && *c <= 'f') || (*c >= 'A' && *c <= 'F') ) { + hasHex=true; + value <<= 4; + value += TCOD_lex_hextoint(*c); + *c = *(++(lex->pos) ); + } + if (! hasHex ) { + TCOD_last_error=(char *)"\\x must be followed by an hexadecimal value"; + return false; + } + *c = value; + lex->pos--; + } + break; + case '0' : + case '1' : + case '2' : + case '3' : + case '4' : + case '5' : + case '6' : + case '7' : + { + /* octal value "\200" */ + int value=0; + while ( *c >= '0' && *c <= '7' ) { + value <<= 3; + value += (*c - '0'); + *c = *(++(lex->pos) ); + } + *c = value; + lex->pos--; + } + break; + default : + TCOD_last_error=(char *)"bad escape sequence inside quote"; + return false; + } + return true; +} + +int TCOD_lex_get_string(TCOD_lex_t *lex) +{ + char c; + int len = 0; + do + { + c= *(++(lex->pos)); + if ( c == '\0' ) { + TCOD_last_error=(char *)"EOF inside quote"; + return TCOD_LEX_ERROR; + } + if ( c == '\n' ) { + TCOD_last_error=(char *)"newline inside quote"; + return TCOD_LEX_ERROR; + } + if ( c== '\\' ) + { + if ( ! TCOD_lex_get_special_char(lex,&c) ) return TCOD_LEX_ERROR; + } + else if ( c == lex->lastStringDelim ) + { + allocate_tok(lex, len); + lex->tok[ len ] = '\0'; + lex->token_type = TCOD_LEX_STRING; + lex->token_idx = -1; + lex->pos++; + return TCOD_LEX_STRING; + } + allocate_tok(lex, len); + lex->tok[ len++ ] = c; + } while ( 1 ); +} + +#ifdef TCOD_VISUAL_STUDIO +#pragma warning(default:4127) /* conditional expression is constant */ +#endif + +int TCOD_lex_get_number(TCOD_lex_t *lex) +{ + int c; + int len; + char *ptr; + int bhex = 0, bfloat = 0; + + len = 0; + if ( *lex->pos == '-' ) + { + allocate_tok(lex, len); + lex->tok[ len ++ ] = '-'; + lex->pos++; + } + + c = toupper(*lex->pos); + + if ( c == '0' && ( lex->pos[1] == 'x' || lex->pos[1]=='X') ) + { + bhex = 1; + allocate_tok(lex, len); + lex->tok[ len ++ ] = '0'; + lex->pos++; + c = toupper( * (lex->pos)); + } + do + { + allocate_tok(lex, len); + lex->tok[ len++ ] = (char)c; + lex->pos++; + if ( c == '.' ) + { + if ( bhex ) { + TCOD_last_error=(char *)"bad constant format"; + return TCOD_LEX_ERROR; + } + bfloat = 1; + } + c = toupper(*lex->pos); + } while ((c >= '0' && c<= '9') + || ( bhex && c >= 'A' && c <= 'F' ) + || c == '.' ); + allocate_tok(lex, len); + lex->tok[len] = 0; + + if ( !bfloat ) + { + lex->token_int_val = strtol( lex->tok, &ptr, 0 ); + lex->token_float_val = (float)lex->token_int_val; + lex->token_type = TCOD_LEX_INTEGER; + lex->token_idx = -1; + return TCOD_LEX_INTEGER; + } + else + { + lex->token_float_val = (float)atof( lex->tok ); + lex->token_type = TCOD_LEX_FLOAT; + lex->token_idx = -1; + return TCOD_LEX_FLOAT; + } +} + +int TCOD_lex_get_char(TCOD_lex_t *lex) +{ + char c; + c= *(++(lex->pos)); + + if ( c == '\0' ) { + TCOD_last_error=(char *)"EOF inside simple quote"; + return TCOD_LEX_ERROR; + } + if ( c == '\n' ) { + TCOD_last_error=(char *)"newline inside simple quote"; + return TCOD_LEX_ERROR; + } + if ( c== '\\' ) + { + if ( ! TCOD_lex_get_special_char(lex,&c) ) return TCOD_LEX_ERROR; + lex->pos++; + } + else + lex->pos++; + + if ( *lex->pos != '\'' ) { + TCOD_last_error= (char *)"bad character inside simple quote" ; + return TCOD_LEX_ERROR; + } + lex->pos ++; + lex->tok[ 0 ] = c; + lex->tok[ 1 ] = '\0'; + lex->token_type = TCOD_LEX_CHAR; + lex->token_int_val = (int)c; + lex->token_idx = -1; + return TCOD_LEX_CHAR; +} + +int TCOD_lex_get_symbol(TCOD_lex_t *lex) +{ + int symb = 0; + static char msg[255]; + + while ( symb < lex->nb_symbols ) + { + if ( ( ( lex->flags & TCOD_LEX_FLAG_NOCASE ) + && TCOD_strncasecmp( lex->symbols[ symb ], lex->pos, strlen( lex->symbols[ symb ] ) ) == 0 ) + || ( strncmp( lex->symbols[ symb ], lex->pos, strlen( lex->symbols[ symb ] ) ) == 0 ) ) + { + strcpy( lex->tok, lex->symbols[ symb ] ); + lex->pos += strlen( lex->symbols[ symb ] ); + lex->token_idx = symb; + lex->token_type = TCOD_LEX_SYMBOL; + return TCOD_LEX_SYMBOL; + } + symb ++; + } + + lex->pos++; + sprintf(msg, "unknown symbol %.10s", lex->pos-1 ); + TCOD_last_error=TCOD_strdup(msg); + return TCOD_LEX_ERROR; +} + +int TCOD_lex_get_iden(TCOD_lex_t *lex) +{ + char c = *lex->pos; + int len = 0, key = 0; + + do + { + allocate_tok(lex, len); + lex->tok[ len++ ] = c; + c = *( ++ (lex->pos) ); + } while ( ( c >= 'a' && c <= 'z' ) + || ( c >= 'A' && c <= 'Z' ) + || ( c >= '0' && c <= '9' ) + || c == '_' ); + allocate_tok(lex, len); + lex->tok[len ] = 0; + + while ( key < lex->nb_keywords ) + { + if ( strcmp( lex->tok, lex->keywords[ key ] ) == 0 + || ( lex->flags & TCOD_LEX_FLAG_NOCASE && TCOD_strcasecmp( lex->tok, lex->keywords[ key ] ) == 0 )) + { + lex->token_type = TCOD_LEX_KEYWORD; + lex->token_idx = key; + return TCOD_LEX_KEYWORD; + } + key ++; + } + + lex->token_type = TCOD_LEX_IDEN; + lex->token_idx = -1; + return TCOD_LEX_IDEN; +} + +int TCOD_lex_parse(TCOD_lex_t *lex) +{ + char *ptr; + int token; + + token = TCOD_lex_get_space(lex); + if ( token == TCOD_LEX_ERROR ) return token; + ptr = lex->pos; + if ( token != TCOD_LEX_UNKNOWN ) + { + lex->token_type = token; + return token; + } + if ( strchr(lex->stringDelim, *ptr) ) + { + lex->lastStringDelim=*ptr; + return TCOD_lex_get_string(lex); + } + if ( *ptr == '\'' ) + { + return TCOD_lex_get_char(lex); + } + if ( isdigit( (int)(*ptr) ) + || ( *ptr == '-' && isdigit( (int)(ptr[1]) ) ) + ) + { + return TCOD_lex_get_number(lex); + } + if ( ( *ptr >= 'a' && *ptr <= 'z' ) || ( *ptr >= 'A' && *ptr <= 'Z' ) + || *ptr == '_' ) + { + return TCOD_lex_get_iden(lex); + } + return TCOD_lex_get_symbol(lex); +} + + +int TCOD_lex_parse_until_token_type(TCOD_lex_t *lex,int tokenType) +{ + int token; + token = TCOD_lex_parse(lex); + if ( token == TCOD_LEX_ERROR ) return token; + while ( token != TCOD_LEX_EOF ) + { + if ( token == tokenType ) + return token; + token = TCOD_lex_parse(lex); + if ( token == TCOD_LEX_ERROR ) return token; + } + return token; +} + +int TCOD_lex_parse_until_token_value(TCOD_lex_t *lex, const char *tokenValue) +{ + int token; + token = TCOD_lex_parse(lex); + if ( token == TCOD_LEX_ERROR ) return token; + { + while ( token != TCOD_LEX_EOF ) + if ( strcmp( lex->tok, tokenValue ) == 0 + || ( ( lex->flags & TCOD_LEX_FLAG_NOCASE ) && TCOD_strcasecmp(lex->tok, tokenValue ) == 0 ) ) + return token; + token = TCOD_lex_parse(lex); + if ( token == TCOD_LEX_ERROR ) return token; + } + return token; +} + +void TCOD_lex_savepoint(TCOD_lex_t *lex,TCOD_lex_t *_savept) +{ + TCOD_lex_t *savept=(TCOD_lex_t *)_savept; + *savept = *lex; + savept->tok = (char *)calloc(sizeof(char),lex->toklen); + strcpy(savept->tok,lex->tok); + savept->savept=true; +} + +void TCOD_lex_restore(TCOD_lex_t *lex,TCOD_lex_t *_savept) +{ + TCOD_lex_t *savept=(TCOD_lex_t *)_savept; + *lex = *savept; + lex->savept=false; +} + +bool TCOD_lex_expect_token_type(TCOD_lex_t *lex,int token_type) +{ + return (TCOD_lex_parse(lex) == token_type); +} + +bool TCOD_lex_expect_token_value(TCOD_lex_t *lex,int token_type, const char *token_value) +{ + TCOD_lex_parse(lex); + return (token_type == lex->token_type && strcmp(lex->tok, token_value) == 0 ); +} diff --git a/tcod_sys/libtcod/include/libtcod.h b/tcod_sys/libtcod/src/libtcod/libtcod.h similarity index 76% rename from tcod_sys/libtcod/include/libtcod.h rename to tcod_sys/libtcod/src/libtcod/libtcod.h index 138a18fc3..1be4bfa2d 100644 --- a/tcod_sys/libtcod/include/libtcod.h +++ b/tcod_sys/libtcod/src/libtcod/libtcod.h @@ -1,56 +1,82 @@ -/* -* libtcod -* Copyright (c) 2008-2018 Jice & Mingos & rmtew -* All rights reserved. -* -* Redistribution and use in source and binary forms, with or without -* modification, are permitted provided that the following conditions are met: -* * Redistributions of source code must retain the above copyright -* notice, this list of conditions and the following disclaimer. -* * Redistributions in binary form must reproduce the above copyright -* notice, this list of conditions and the following disclaimer in the -* documentation and/or other materials provided with the distribution. -* * The name of Jice or Mingos may not be used to endorse or promote -* products derived from this software without specific prior written -* permission. -* -* THIS SOFTWARE IS PROVIDED BY JICE, MINGOS AND RMTEW ``AS IS'' AND ANY -* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED -* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE -* DISCLAIMED. IN NO EVENT SHALL JICE, MINGOS OR RMTEW BE LIABLE FOR ANY -* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES -* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; -* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND -* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS -* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. -*/ -#ifndef _LIBTCOD_H -#define _LIBTCOD_H - -#include "libtcod_portability.h" -#include "libtcod_utility.h" -#include "libtcod_version.h" - -#include "bresenham.h" -#include "bsp.h" -#include "color.h" -#include "console.h" -#include "console_rexpaint.h" -#include "fov.h" -#include "heightmap.h" -#include "image.h" -#include "lex.h" -#include "list.h" -#include "mersenne.h" -#include "mouse.h" -#include "namegen.h" -#include "noise.h" -#include "path.h" -#include "parser.h" -#include "sys.h" -#include "tree.h" -#include "txtfield.h" -#include "zip.h" - -#endif +/* +* libtcod +* Copyright (c) 2008-2018 Jice & Mingos & rmtew +* All rights reserved. +* +* Redistribution and use in source and binary forms, with or without +* modification, are permitted provided that the following conditions are met: +* * Redistributions of source code must retain the above copyright +* notice, this list of conditions and the following disclaimer. +* * Redistributions in binary form must reproduce the above copyright +* notice, this list of conditions and the following disclaimer in the +* documentation and/or other materials provided with the distribution. +* * The name of Jice or Mingos may not be used to endorse or promote +* products derived from this software without specific prior written +* permission. +* +* THIS SOFTWARE IS PROVIDED BY JICE, MINGOS AND RMTEW ``AS IS'' AND ANY +* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED +* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE +* DISCLAIMED. IN NO EVENT SHALL JICE, MINGOS OR RMTEW BE LIABLE FOR ANY +* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES +* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; +* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND +* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS +* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +*/ +#ifndef _LIBTCOD_H +#define _LIBTCOD_H + +#include "portability.h" +#include "utility.h" +#include "version.h" + +#include "bresenham.h" +#include "bsp.h" +#include "color.h" +#include "console.h" +#include "console_rexpaint.h" +#include "fov.h" +#include "heightmap.h" +#include "image.h" +#include "lex.h" +#include "list.h" +#include "mersenne.h" +#include "mouse.h" +#include "namegen.h" +#include "noise.h" +#include "path.h" +#include "parser.h" +#include "sys.h" +#include "tree.h" +#include "txtfield.h" +#include "zip.h" + +#include "tileset/observer.h" +#include "tileset/tileset.h" +#include "tileset/tile.h" + +#ifdef __cplusplus +#include "bresenham.hpp" +#include "bsp.hpp" +#include "color.hpp" +#include "console.hpp" +#include "fov.hpp" +#include "heightmap.hpp" +#include "image.hpp" +#include "lex.hpp" +#include "list.hpp" +#include "mersenne.hpp" +#include "mouse.hpp" +#include "namegen.hpp" +#include "noise.hpp" +#include "parser.hpp" +#include "path.hpp" +#include "sys.hpp" +#include "tree.hpp" +#include "txtfield.hpp" +#include "zip.hpp" +#endif // __cplusplus + +#endif diff --git a/tcod_sys/libtcod/include/libtcod.hpp b/tcod_sys/libtcod/src/libtcod/libtcod.hpp similarity index 75% rename from tcod_sys/libtcod/include/libtcod.hpp rename to tcod_sys/libtcod/src/libtcod/libtcod.hpp index 7134208db..cdc816599 100644 --- a/tcod_sys/libtcod/include/libtcod.hpp +++ b/tcod_sys/libtcod/src/libtcod/libtcod.hpp @@ -1,53 +1,28 @@ -/* -* libtcod -* Copyright (c) 2008-2018 Jice & Mingos & rmtew -* All rights reserved. -* -* Redistribution and use in source and binary forms, with or without -* modification, are permitted provided that the following conditions are met: -* * Redistributions of source code must retain the above copyright -* notice, this list of conditions and the following disclaimer. -* * Redistributions in binary form must reproduce the above copyright -* notice, this list of conditions and the following disclaimer in the -* documentation and/or other materials provided with the distribution. -* * The name of Jice or Mingos may not be used to endorse or promote -* products derived from this software without specific prior written -* permission. -* -* THIS SOFTWARE IS PROVIDED BY JICE, MINGOS AND RMTEW ``AS IS'' AND ANY -* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED -* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE -* DISCLAIMED. IN NO EVENT SHALL JICE, MINGOS OR RMTEW BE LIABLE FOR ANY -* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES -* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; -* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND -* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS -* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. -*/ -#ifndef _LIBTCOD_HPP -#define _LIBTCOD_HPP - -#include "libtcod.h" - -#include "bresenham.hpp" -#include "bsp.hpp" -#include "color.hpp" -#include "console.hpp" -#include "fov.hpp" -#include "heightmap.hpp" -#include "image.hpp" -#include "lex.hpp" -#include "list.hpp" -#include "mersenne.hpp" -#include "mouse.hpp" -#include "namegen.hpp" -#include "noise.hpp" -#include "parser.hpp" -#include "path.hpp" -#include "sys.hpp" -#include "tree.hpp" -#include "txtfield.hpp" -#include "zip.hpp" - -#endif +/* +* libtcod +* Copyright (c) 2008-2018 Jice & Mingos & rmtew +* All rights reserved. +* +* Redistribution and use in source and binary forms, with or without +* modification, are permitted provided that the following conditions are met: +* * Redistributions of source code must retain the above copyright +* notice, this list of conditions and the following disclaimer. +* * Redistributions in binary form must reproduce the above copyright +* notice, this list of conditions and the following disclaimer in the +* documentation and/or other materials provided with the distribution. +* * The name of Jice or Mingos may not be used to endorse or promote +* products derived from this software without specific prior written +* permission. +* +* THIS SOFTWARE IS PROVIDED BY JICE, MINGOS AND RMTEW ``AS IS'' AND ANY +* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED +* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE +* DISCLAIMED. IN NO EVENT SHALL JICE, MINGOS OR RMTEW BE LIABLE FOR ANY +* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES +* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; +* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND +* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS +* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +*/ +#include "libtcod.h" diff --git a/tcod_sys/libtcod/include/libtcod_int.h b/tcod_sys/libtcod/src/libtcod/libtcod_int.h similarity index 90% rename from tcod_sys/libtcod/include/libtcod_int.h rename to tcod_sys/libtcod/src/libtcod/libtcod_int.h index efe5d3698..7a82b67f3 100644 --- a/tcod_sys/libtcod/include/libtcod_int.h +++ b/tcod_sys/libtcod/src/libtcod/libtcod_int.h @@ -1,566 +1,537 @@ -/* -* libtcod -* Copyright (c) 2008-2018 Jice & Mingos & rmtew -* All rights reserved. -* -* Redistribution and use in source and binary forms, with or without -* modification, are permitted provided that the following conditions are met: -* * Redistributions of source code must retain the above copyright -* notice, this list of conditions and the following disclaimer. -* * Redistributions in binary form must reproduce the above copyright -* notice, this list of conditions and the following disclaimer in the -* documentation and/or other materials provided with the distribution. -* * The name of Jice or Mingos may not be used to endorse or promote -* products derived from this software without specific prior written -* permission. -* -* THIS SOFTWARE IS PROVIDED BY JICE, MINGOS AND RMTEW ``AS IS'' AND ANY -* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED -* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE -* DISCLAIMED. IN NO EVENT SHALL JICE, MINGOS OR RMTEW BE LIABLE FOR ANY -* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES -* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; -* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND -* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS -* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. -*/ -#ifndef _TCODLIB_INT_H -#define _TCODLIB_INT_H -#include -#include -#if defined(__ANDROID__) -#include -#endif - -#include "libtcod_portability.h" -#include "color.h" -#include "console_types.h" -#include "fov.h" -#include "fov_types.h" -#include "mersenne_types.h" -#include "sys.h" - -/* tcodlib internal stuff */ -#ifdef __cplusplus -extern "C" { -#endif - -/* SDL2 forward declarations */ -struct SDL_Surface; -struct SDL_Window; -struct SDL_Renderer; - -#ifdef TCOD_CONSOLE_SUPPORT -typedef struct { - int *ch_array; /* character code array */ - TCOD_image_t fg_colors, bg_colors; - /* console width and height (in characters,not pixels) */ - int w,h; - /* default background operator for print & print_rect functions */ - TCOD_bkgnd_flag_t bkgnd_flag; - /* default alignment for print & print_rect functions */ - TCOD_alignment_t alignment; - /* foreground (text), background colors */ - TCOD_color_t fore, back; -} TCOD_console_data_t; -#endif - -/* fov internal stuff */ -typedef struct { - bool transparent:1; - bool walkable:1; - bool fov:1; -} cell_t; - -typedef struct { - int width; - int height; - int nbcells; - cell_t *cells; -} map_t; - -/* pseudorandom number generator toolkit */ -typedef struct { - /* algorithm identifier */ - TCOD_random_algo_t algo; - /* distribution */ - TCOD_distribution_t distribution; - /* Mersenne Twister stuff */ - uint32_t mt[624]; - int cur_mt; - /* Complementary-Multiply-With-Carry stuff */ - /* shared with Generalised Feedback Shift Register */ - uint32_t Q[4096], c; - int cur; -} mersenne_data_t; - -typedef struct { - /* number of characters in the bitmap font */ - int fontNbCharHoriz; - int fontNbCharVertic; - /* font type and layout */ - bool font_tcod_layout; - bool font_in_row; - bool font_greyscale; - /* character size in font */ - int font_width; - int font_height; - char font_file[512]; - char window_title[512]; - /* ascii code to tcod layout converter */ - int *ascii_to_tcod; - /* whether each character in the font is a colored tile */ - bool *colored; -#ifdef TCOD_CONSOLE_SUPPORT - /* the root console */ - TCOD_console_data_t *root; - /* nb chars in the font */ - int max_font_chars; - /* fullscreen data */ - bool fullscreen; - int fullscreen_offsetx; - int fullscreen_offsety; - /* asked by the user */ - int fullscreen_width; - int fullscreen_height; - /* actual resolution */ - int actual_fullscreen_width; - int actual_fullscreen_height; -#endif -#ifndef TCOD_BARE - /* renderer to use */ - TCOD_renderer_t renderer; - /* user post-processing callback */ - SDL_renderer_t sdl_cbk; -#endif - /* fading data */ - TCOD_color_t fading_color; - uint8_t fade; -#ifdef TCOD_CONSOLE_SUPPORT - TCOD_key_t key_state; -#endif -#ifndef TCOD_BARE - /* application window was closed */ - bool is_window_closed; - /* application has mouse focus */ - bool app_has_mouse_focus; - /* application is active (not iconified) */ - bool app_is_active; -#endif -} TCOD_internal_context_t; - -extern TCOD_internal_context_t TCOD_ctx; - -#if defined(__ANDROID__) && !defined(NDEBUG) -#include -#ifdef printf -#undef printf -#endif -#ifdef vprintf -#undef vprintf -#endif -#define printf(args...) __android_log_print(ANDROID_LOG_INFO, "libtcod", ## args) -#define vprintf(args...) __android_log_vprint(ANDROID_LOG_INFO, "libtcod", ## args) - -#ifdef assert -#undef assert -#endif -#define assert(cond) if(!(cond)) __android_log_assert(#cond, "libtcod", "assertion failed: %s", #cond) -#endif - -#ifdef NDEBUG -#define TCOD_IF(x) if (x) -#define TCOD_IFNOT(x) if (!(x)) -#define TCOD_ASSERT(x) -#define TCOD_LOG(x) -#else -#define TCOD_IF(x) assert(x); -#define TCOD_IFNOT(x) assert(x); if (0) -#define TCOD_ASSERT(x) assert(x) -#define TCOD_LOG(x) printf x -#endif - -#if !defined(TCOD_BARE) && !defined(NO_OPENGL) -/* opengl utilities */ -void TCOD_opengl_init_attributes(void); -bool TCOD_opengl_init_state(int conw, int conh, void *font_tex); -void TCOD_opengl_uninit_state(void); -bool TCOD_opengl_init_shaders(void); -bool TCOD_opengl_render(int oldFade, bool *ascii_updated, TCOD_console_data_t *console, TCOD_console_data_t *cache); -void TCOD_opengl_swap(void); -void * TCOD_opengl_get_screen(void); -#endif - -#ifdef TCOD_IMAGE_SUPPORT -/* image internal stuff */ -bool TCOD_image_mipmap_copy_internal(TCOD_image_t srcImage, TCOD_image_t dstImage); -TCOD_color_t *TCOD_image_get_colors(TCOD_image_t *image); -void TCOD_image_invalidate_mipmaps(TCOD_image_t *image); -void TCOD_image_get_key_data(TCOD_image_t image, bool *has_key_color, TCOD_color_t *key_color); -#endif - -/* fov internal stuff */ -void TCOD_map_compute_fov_circular_raycasting(TCOD_map_t map, int player_x, int player_y, int max_radius, bool light_walls); -void TCOD_map_compute_fov_diamond_raycasting(TCOD_map_t map, int player_x, int player_y, int max_radius, bool light_walls); -void TCOD_map_compute_fov_recursive_shadowcasting(TCOD_map_t map, int player_x, int player_y, int max_radius, bool light_walls); -void TCOD_map_compute_fov_permissive2(TCOD_map_t map, int player_x, int player_y, int max_radius, bool light_walls, int fovType); -void TCOD_map_compute_fov_restrictive_shadowcasting(TCOD_map_t map, int player_x, int player_y, int max_radius, bool light_walls); -void TCOD_map_postproc(map_t *map,int x0,int y0, int x1, int y1, int dx, int dy); - -#ifdef TCOD_CONSOLE_SUPPORT -/* TCODConsole non public methods*/ -bool TCOD_console_init(TCOD_console_t con,const char *title, bool fullscreen); -int TCOD_console_print_internal(TCOD_console_t con,int x,int y, int w, int h, TCOD_bkgnd_flag_t flag, TCOD_alignment_t align, char *msg, bool can_split, bool count_only); -int TCOD_console_stringLength(const unsigned char *s); -unsigned char * TCOD_console_forward(unsigned char *s,int l); -char *TCOD_console_vsprint(const char *fmt, va_list ap); -#endif - -/* fatal errors */ -void TCOD_fatal(const char *fmt, ...); -void TCOD_fatal_nopar(const char *msg); - -/* TCODSystem non public methods */ -#ifdef TCOD_CONSOLE_SUPPORT -bool TCOD_sys_init(TCOD_console_data_t *console, bool fullscreen); -void TCOD_sys_uninit(void); -void TCOD_sys_set_custom_font(const char *font_name,int nb_ch, int nb_cv,int flags); -void TCOD_sys_map_ascii_to_font(int asciiCode, int fontCharX, int fontCharY); -void *TCOD_sys_create_bitmap_for_console(TCOD_console_t console); -void TCOD_sys_save_bitmap(void *bitmap, const char *filename); -void *TCOD_sys_create_bitmap(int width, int height, TCOD_color_t *buf); -void TCOD_sys_delete_bitmap(void *bitmap); -void TCOD_sys_console_to_bitmap(void *bitmap, TCOD_console_data_t *console, - TCOD_console_data_t *cache); -TCODLIB_API void *TCOD_sys_get_surface(int width, int height, bool alpha); -void TCOD_sys_save_fps(void); -void TCOD_sys_restore_fps(void); -void TCOD_sys_set_dirty(int dx, int dy, int dw, int dh); -void TCOD_sys_set_dirty_character_code(int ch); -int TCOD_get_tileid_for_charcode_(int charcode); - -/* switch fullscreen mode */ -void TCOD_sys_set_fullscreen(bool fullscreen); -void TCOD_sys_set_clear_screen(void); -void TCOD_sys_set_scale_factor(float value); -void TCOD_sys_convert_console_to_screen_coords(int cx, int cy, int *sx, int *sy); -void TCOD_sys_convert_screen_to_console_coords(int sx, int sy, int *cx, int *cy); -void TCOD_sys_flush(bool render); -TCOD_key_t TCOD_sys_check_for_keypress(int flags); -TCOD_key_t TCOD_sys_wait_for_keypress(bool flush); -bool TCOD_sys_is_key_pressed(TCOD_keycode_t key); -void TCOD_sys_set_window_title(const char *title); -#endif - -/* UTF-8 stuff */ -#ifndef NO_UNICODE -wchar_t *TCOD_console_vsprint_utf(const wchar_t *fmt, va_list ap); -int TCOD_console_print_internal_utf(TCOD_console_t con,int x,int y, int rw, int rh, TCOD_bkgnd_flag_t flag, - TCOD_alignment_t align, wchar_t *msg, bool can_split, bool count_only); -#endif - -#ifdef TCOD_IMAGE_SUPPORT -/* image manipulation */ -TCODLIB_API void *TCOD_sys_load_image(const char *filename); -void TCOD_sys_get_image_size(const void *image, int *w,int *h); -TCOD_color_t TCOD_sys_get_image_pixel(const void *image,int x, int y); -int TCOD_sys_get_image_alpha(const void *image,int x, int y); -bool TCOD_sys_check_magic_number(const char *filename, size_t size, uint8_t *data); -#endif - -/* TCOD_list nonpublic methods */ -void TCOD_list_set_size(TCOD_list_t l, int size); - -#ifndef TCOD_BARE -/* - SDL12/SDL2 abstraction layer -*/ -typedef struct TCOD_SDL_driver_t { - float scale_xc; - float scale_yc; - - /* get a fullscreen mode suitable for the console */ - void (*get_closest_mode)(int *w, int *h); - /* render the console on a surface/texture */ - void (*render)(struct TCOD_SDL_driver_t *sdl, void *vbitmap, TCOD_console_data_t *console); - /* create a new surface */ - struct SDL_Surface *(*create_surface) (int width, int height, bool with_alpha); - /* create the game window */ - void (*create_window)(int w, int h, bool fullscreen); - /* destroy the game window */ - void (*destroy_window)(void); - /* switch fullscreen on/off */ - void (*set_fullscreen)(bool fullscreen); - /* change the game window title */ - void (*set_window_title)(const char *title); - /* save game screenshot */ - void (*save_screenshot)(const char *filename); - /* get desktop resolution */ - void (*get_current_resolution)(int *w, int *h); - /* change the mouse cursor position */ - void (*set_mouse_position)(int x, int y); - /* clipboard */ - char *(*get_clipboard_text)(void); - bool (*set_clipboard_text)(const char *text); - /* android compatible file access functions */ - bool (*file_read)(const char *filename, unsigned char **buf, size_t *size); - bool (*file_exists)(const char * filename); - bool (*file_write)(const char *filename, unsigned char *buf, uint32_t size); - /* clean stuff */ - void (*shutdown)(void); - /* get root cache */ - TCOD_console_data_t *(*get_root_console_cache)(void); -} TCOD_SDL_driver_t; - -/* defined in TCOD_sys_sdl12_c.c and TCOD_sys_sdl2_c.c */ -TCOD_SDL_driver_t *SDL_implementation_factory(void); - -void find_resolution(void); -void TCOD_sys_init_screen_offset(void); -typedef struct { - float force_recalc; - float last_scale_xc, last_scale_yc; - float last_scale_factor; - float last_fullscreen; - - float min_scale_factor; - - float src_height_width_ratio; - float dst_height_width_ratio; - int src_x0, src_y0; - int src_copy_width, src_copy_height; - int src_proportionate_width, src_proportionate_height; - int dst_display_width, dst_display_height; - int dst_offset_x, dst_offset_y; - int surface_width, surface_height; -} scale_data_t; -extern scale_data_t scale_data; - -extern float scale_factor; -extern struct SDL_Surface* charmap; -extern struct SDL_Window* window; -extern struct SDL_Renderer* renderer; -extern char *last_clipboard_text; -#endif - -/* SDL & OpenGL */ -extern int oldFade; - -/* color values */ -#define TCOD_BLACK 0,0,0 -#define TCOD_DARKEST_GREY 31,31,31 -#define TCOD_DARKER_GREY 63,63,63 -#define TCOD_DARK_GREY 95,95,95 -#define TCOD_GREY 127,127,127 -#define TCOD_LIGHT_GREY 159,159,159 -#define TCOD_LIGHTER_GREY 191,191,191 -#define TCOD_LIGHTEST_GREY 223,223,223 -#define TCOD_WHITE 255,255,255 - -#define TCOD_DARKEST_SEPIA 31,24,15 -#define TCOD_DARKER_SEPIA 63,50,31 -#define TCOD_DARK_SEPIA 94,75,47 -#define TCOD_SEPIA 127,101,63 -#define TCOD_LIGHT_SEPIA 158,134,100 -#define TCOD_LIGHTER_SEPIA 191,171,143 -#define TCOD_LIGHTEST_SEPIA 222,211,195 - -/* desaturated */ -#define TCOD_DESATURATED_RED 127,63,63 -#define TCOD_DESATURATED_FLAME 127,79,63 -#define TCOD_DESATURATED_ORANGE 127,95,63 -#define TCOD_DESATURATED_AMBER 127,111,63 -#define TCOD_DESATURATED_YELLOW 127,127,63 -#define TCOD_DESATURATED_LIME 111,127,63 -#define TCOD_DESATURATED_CHARTREUSE 95,127,63 -#define TCOD_DESATURATED_GREEN 63,127,63 -#define TCOD_DESATURATED_SEA 63,127,95 -#define TCOD_DESATURATED_TURQUOISE 63,127,111 -#define TCOD_DESATURATED_CYAN 63,127,127 -#define TCOD_DESATURATED_SKY 63,111,127 -#define TCOD_DESATURATED_AZURE 63,95,127 -#define TCOD_DESATURATED_BLUE 63,63,127 -#define TCOD_DESATURATED_HAN 79,63,127 -#define TCOD_DESATURATED_VIOLET 95,63,127 -#define TCOD_DESATURATED_PURPLE 111,63,127 -#define TCOD_DESATURATED_FUCHSIA 127,63,127 -#define TCOD_DESATURATED_MAGENTA 127,63,111 -#define TCOD_DESATURATED_PINK 127,63,95 -#define TCOD_DESATURATED_CRIMSON 127,63,79 - -/* lightest */ -#define TCOD_LIGHTEST_RED 255,191,191 -#define TCOD_LIGHTEST_FLAME 255,207,191 -#define TCOD_LIGHTEST_ORANGE 255,223,191 -#define TCOD_LIGHTEST_AMBER 255,239,191 -#define TCOD_LIGHTEST_YELLOW 255,255,191 -#define TCOD_LIGHTEST_LIME 239,255,191 -#define TCOD_LIGHTEST_CHARTREUSE 223,255,191 -#define TCOD_LIGHTEST_GREEN 191,255,191 -#define TCOD_LIGHTEST_SEA 191,255,223 -#define TCOD_LIGHTEST_TURQUOISE 191,255,239 -#define TCOD_LIGHTEST_CYAN 191,255,255 -#define TCOD_LIGHTEST_SKY 191,239,255 -#define TCOD_LIGHTEST_AZURE 191,223,255 -#define TCOD_LIGHTEST_BLUE 191,191,255 -#define TCOD_LIGHTEST_HAN 207,191,255 -#define TCOD_LIGHTEST_VIOLET 223,191,255 -#define TCOD_LIGHTEST_PURPLE 239,191,255 -#define TCOD_LIGHTEST_FUCHSIA 255,191,255 -#define TCOD_LIGHTEST_MAGENTA 255,191,239 -#define TCOD_LIGHTEST_PINK 255,191,223 -#define TCOD_LIGHTEST_CRIMSON 255,191,207 - -/* lighter */ -#define TCOD_LIGHTER_RED 255,127,127 -#define TCOD_LIGHTER_FLAME 255,159,127 -#define TCOD_LIGHTER_ORANGE 255,191,127 -#define TCOD_LIGHTER_AMBER 255,223,127 -#define TCOD_LIGHTER_YELLOW 255,255,127 -#define TCOD_LIGHTER_LIME 223,255,127 -#define TCOD_LIGHTER_CHARTREUSE 191,255,127 -#define TCOD_LIGHTER_GREEN 127,255,127 -#define TCOD_LIGHTER_SEA 127,255,191 -#define TCOD_LIGHTER_TURQUOISE 127,255,223 -#define TCOD_LIGHTER_CYAN 127,255,255 -#define TCOD_LIGHTER_SKY 127,223,255 -#define TCOD_LIGHTER_AZURE 127,191,255 -#define TCOD_LIGHTER_BLUE 127,127,255 -#define TCOD_LIGHTER_HAN 159,127,255 -#define TCOD_LIGHTER_VIOLET 191,127,255 -#define TCOD_LIGHTER_PURPLE 223,127,255 -#define TCOD_LIGHTER_FUCHSIA 255,127,255 -#define TCOD_LIGHTER_MAGENTA 255,127,223 -#define TCOD_LIGHTER_PINK 255,127,191 -#define TCOD_LIGHTER_CRIMSON 255,127,159 - -/* light */ -#define TCOD_LIGHT_RED 255,63,63 -#define TCOD_LIGHT_FLAME 255,111,63 -#define TCOD_LIGHT_ORANGE 255,159,63 -#define TCOD_LIGHT_AMBER 255,207,63 -#define TCOD_LIGHT_YELLOW 255,255,63 -#define TCOD_LIGHT_LIME 207,255,63 -#define TCOD_LIGHT_CHARTREUSE 159,255,63 -#define TCOD_LIGHT_GREEN 63,255,63 -#define TCOD_LIGHT_SEA 63,255,159 -#define TCOD_LIGHT_TURQUOISE 63,255,207 -#define TCOD_LIGHT_CYAN 63,255,255 -#define TCOD_LIGHT_SKY 63,207,255 -#define TCOD_LIGHT_AZURE 63,159,255 -#define TCOD_LIGHT_BLUE 63,63,255 -#define TCOD_LIGHT_HAN 111,63,255 -#define TCOD_LIGHT_VIOLET 159,63,255 -#define TCOD_LIGHT_PURPLE 207,63,255 -#define TCOD_LIGHT_FUCHSIA 255,63,255 -#define TCOD_LIGHT_MAGENTA 255,63,207 -#define TCOD_LIGHT_PINK 255,63,159 -#define TCOD_LIGHT_CRIMSON 255,63,111 - -/* normal */ -#define TCOD_RED 255,0,0 -#define TCOD_FLAME 255,63,0 -#define TCOD_ORANGE 255,127,0 -#define TCOD_AMBER 255,191,0 -#define TCOD_YELLOW 255,255,0 -#define TCOD_LIME 191,255,0 -#define TCOD_CHARTREUSE 127,255,0 -#define TCOD_GREEN 0,255,0 -#define TCOD_SEA 0,255,127 -#define TCOD_TURQUOISE 0,255,191 -#define TCOD_CYAN 0,255,255 -#define TCOD_SKY 0,191,255 -#define TCOD_AZURE 0,127,255 -#define TCOD_BLUE 0,0,255 -#define TCOD_HAN 63,0,255 -#define TCOD_VIOLET 127,0,255 -#define TCOD_PURPLE 191,0,255 -#define TCOD_FUCHSIA 255,0,255 -#define TCOD_MAGENTA 255,0,191 -#define TCOD_PINK 255,0,127 -#define TCOD_CRIMSON 255,0,63 - -/* dark */ -#define TCOD_DARK_RED 191,0,0 -#define TCOD_DARK_FLAME 191,47,0 -#define TCOD_DARK_ORANGE 191,95,0 -#define TCOD_DARK_AMBER 191,143,0 -#define TCOD_DARK_YELLOW 191,191,0 -#define TCOD_DARK_LIME 143,191,0 -#define TCOD_DARK_CHARTREUSE 95,191,0 -#define TCOD_DARK_GREEN 0,191,0 -#define TCOD_DARK_SEA 0,191,95 -#define TCOD_DARK_TURQUOISE 0,191,143 -#define TCOD_DARK_CYAN 0,191,191 -#define TCOD_DARK_SKY 0,143,191 -#define TCOD_DARK_AZURE 0,95,191 -#define TCOD_DARK_BLUE 0,0,191 -#define TCOD_DARK_HAN 47,0,191 -#define TCOD_DARK_VIOLET 95,0,191 -#define TCOD_DARK_PURPLE 143,0,191 -#define TCOD_DARK_FUCHSIA 191,0,191 -#define TCOD_DARK_MAGENTA 191,0,143 -#define TCOD_DARK_PINK 191,0,95 -#define TCOD_DARK_CRIMSON 191,0,47 - -/* darker */ -#define TCOD_DARKER_RED 127,0,0 -#define TCOD_DARKER_FLAME 127,31,0 -#define TCOD_DARKER_ORANGE 127,63,0 -#define TCOD_DARKER_AMBER 127,95,0 -#define TCOD_DARKER_YELLOW 127,127,0 -#define TCOD_DARKER_LIME 95,127,0 -#define TCOD_DARKER_CHARTREUSE 63,127,0 -#define TCOD_DARKER_GREEN 0,127,0 -#define TCOD_DARKER_SEA 0,127,63 -#define TCOD_DARKER_TURQUOISE 0,127,95 -#define TCOD_DARKER_CYAN 0,127,127 -#define TCOD_DARKER_SKY 0,95,127 -#define TCOD_DARKER_AZURE 0,63,127 -#define TCOD_DARKER_BLUE 0,0,127 -#define TCOD_DARKER_HAN 31,0,127 -#define TCOD_DARKER_VIOLET 63,0,127 -#define TCOD_DARKER_PURPLE 95,0,127 -#define TCOD_DARKER_FUCHSIA 127,0,127 -#define TCOD_DARKER_MAGENTA 127,0,95 -#define TCOD_DARKER_PINK 127,0,63 -#define TCOD_DARKER_CRIMSON 127,0,31 - -/* darkest */ -#define TCOD_DARKEST_RED 63,0,0 -#define TCOD_DARKEST_FLAME 63,15,0 -#define TCOD_DARKEST_ORANGE 63,31,0 -#define TCOD_DARKEST_AMBER 63,47,0 -#define TCOD_DARKEST_YELLOW 63,63,0 -#define TCOD_DARKEST_LIME 47,63,0 -#define TCOD_DARKEST_CHARTREUSE 31,63,0 -#define TCOD_DARKEST_GREEN 0,63,0 -#define TCOD_DARKEST_SEA 0,63,31 -#define TCOD_DARKEST_TURQUOISE 0,63,47 -#define TCOD_DARKEST_CYAN 0,63,63 -#define TCOD_DARKEST_SKY 0,47,63 -#define TCOD_DARKEST_AZURE 0,31,63 -#define TCOD_DARKEST_BLUE 0,0,63 -#define TCOD_DARKEST_HAN 15,0,63 -#define TCOD_DARKEST_VIOLET 31,0,63 -#define TCOD_DARKEST_PURPLE 47,0,63 -#define TCOD_DARKEST_FUCHSIA 63,0,63 -#define TCOD_DARKEST_MAGENTA 63,0,47 -#define TCOD_DARKEST_PINK 63,0,31 -#define TCOD_DARKEST_CRIMSON 63,0,15 - -/* metallic */ -#define TCOD_BRASS 191,151,96 -#define TCOD_COPPER 197,136,124 -#define TCOD_GOLD 229,191,0 -#define TCOD_SILVER 203,203,203 - -/* miscellaneous */ -#define TCOD_CELADON 172,255,175 -#define TCOD_PEACH 255,159,127 - -#ifdef __cplusplus -} -#endif -#endif +/* +* libtcod +* Copyright (c) 2008-2018 Jice & Mingos & rmtew +* All rights reserved. +* +* Redistribution and use in source and binary forms, with or without +* modification, are permitted provided that the following conditions are met: +* * Redistributions of source code must retain the above copyright +* notice, this list of conditions and the following disclaimer. +* * Redistributions in binary form must reproduce the above copyright +* notice, this list of conditions and the following disclaimer in the +* documentation and/or other materials provided with the distribution. +* * The name of Jice or Mingos may not be used to endorse or promote +* products derived from this software without specific prior written +* permission. +* +* THIS SOFTWARE IS PROVIDED BY JICE, MINGOS AND RMTEW ``AS IS'' AND ANY +* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED +* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE +* DISCLAIMED. IN NO EVENT SHALL JICE, MINGOS OR RMTEW BE LIABLE FOR ANY +* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES +* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; +* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND +* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS +* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +*/ +#ifndef _TCODLIB_INT_H +#define _TCODLIB_INT_H +#include +#include +#if defined(__ANDROID__) +#include +#endif + +#include "portability.h" +#include "color.h" +#include "console_types.h" +#include "fov.h" +#include "fov_types.h" +#include "mersenne_types.h" +#include "sys.h" + +/* tcodlib internal stuff */ +#ifdef __cplusplus +extern "C" { +#endif + +/* SDL2 forward declarations */ +struct SDL_Surface; +struct SDL_Window; +struct SDL_Renderer; + +/* pseudorandom number generator toolkit */ +typedef struct TCOD_Random { + /* algorithm identifier */ + TCOD_random_algo_t algo; + /* distribution */ + TCOD_distribution_t distribution; + /* Mersenne Twister stuff */ + uint32_t mt[624]; + int cur_mt; + /* Complementary-Multiply-With-Carry stuff */ + /* shared with Generalised Feedback Shift Register */ + uint32_t Q[4096], c; + int cur; +} mersenne_data_t; + +typedef struct { + /* number of characters in the bitmap font */ + int fontNbCharHoriz; + int fontNbCharVertic; + /* font type and layout */ + bool font_tcod_layout; + bool font_in_row; + bool font_greyscale; + /* character size in font */ + int font_width; + int font_height; + char font_file[512]; + char window_title[512]; + /* ascii code to tcod layout converter */ + int *ascii_to_tcod; + /* whether each character in the font is a colored tile */ + bool *colored; +#ifdef TCOD_CONSOLE_SUPPORT + /* the root console */ + struct TCOD_Console *root; + /* nb chars in the font */ + int max_font_chars; + /* fullscreen data */ + bool fullscreen; + int fullscreen_offsetx; + int fullscreen_offsety; + /* asked by the user */ + int fullscreen_width; + int fullscreen_height; + /* actual resolution */ + int actual_fullscreen_width; + int actual_fullscreen_height; +#endif +#ifndef TCOD_BARE + /* renderer to use */ + TCOD_renderer_t renderer; + /* user post-processing callback */ + SDL_renderer_t sdl_cbk; +#endif + /* fading data */ + TCOD_color_t fading_color; + uint8_t fade; +#ifdef TCOD_CONSOLE_SUPPORT + TCOD_key_t key_state; +#endif +#ifndef TCOD_BARE + /* application window was closed */ + bool is_window_closed; + /* application has mouse focus */ + bool app_has_mouse_focus; + /* application is active (not iconified) */ + bool app_is_active; +#endif +} TCOD_internal_context_t; + +extern TCOD_internal_context_t TCOD_ctx; + +#if defined(__ANDROID__) && !defined(NDEBUG) +#include +#ifdef printf +#undef printf +#endif +#ifdef vprintf +#undef vprintf +#endif +#define printf(args...) __android_log_print(ANDROID_LOG_INFO, "libtcod", ## args) +#define vprintf(args...) __android_log_vprint(ANDROID_LOG_INFO, "libtcod", ## args) + +#ifdef assert +#undef assert +#endif +#define assert(cond) if(!(cond)) __android_log_assert(#cond, "libtcod", "assertion failed: %s", #cond) +#endif + +#ifdef NDEBUG +#define TCOD_IF(x) if (x) +#define TCOD_IFNOT(x) if (!(x)) +#define TCOD_ASSERT(x) +#define TCOD_LOG(x) +#else +#define TCOD_IF(x) assert(x); +#define TCOD_IFNOT(x) assert(x); if (0) +#define TCOD_ASSERT(x) assert(x) +#define TCOD_LOG(x) printf x +#endif + +#if !defined(TCOD_BARE) && !defined(NO_OPENGL) +/* opengl utilities */ +void TCOD_opengl_init_attributes(void); +bool TCOD_opengl_init_state(int conw, int conh, void *font_tex); +void TCOD_opengl_uninit_state(void); +bool TCOD_opengl_init_shaders(void); +bool TCOD_opengl_render(int oldFade, bool *ascii_updated, struct TCOD_Console *console, struct TCOD_Console *cache); +void TCOD_opengl_swap(void); +void * TCOD_opengl_get_screen(void); +#endif + +#ifdef TCOD_IMAGE_SUPPORT +/* image internal stuff */ +bool TCOD_image_mipmap_copy_internal(TCOD_image_t srcImage, TCOD_image_t dstImage); +TCOD_color_t *TCOD_image_get_colors(TCOD_image_t *image); +void TCOD_image_invalidate_mipmaps(TCOD_image_t *image); +void TCOD_image_get_key_data(TCOD_image_t image, bool *has_key_color, TCOD_color_t *key_color); +#endif + +/* fov internal stuff */ +void TCOD_map_compute_fov_circular_raycasting(TCOD_map_t map, int player_x, int player_y, int max_radius, bool light_walls); +void TCOD_map_compute_fov_diamond_raycasting(TCOD_map_t map, int player_x, int player_y, int max_radius, bool light_walls); +void TCOD_map_compute_fov_recursive_shadowcasting(TCOD_map_t map, int player_x, int player_y, int max_radius, bool light_walls); +void TCOD_map_compute_fov_permissive2(TCOD_map_t map, int player_x, int player_y, int max_radius, bool light_walls, int fovType); +void TCOD_map_compute_fov_restrictive_shadowcasting(TCOD_map_t map, int player_x, int player_y, int max_radius, bool light_walls); +void TCOD_map_postproc(TCOD_map_t map,int x0,int y0, int x1, int y1, int dx, int dy); + +#ifdef TCOD_CONSOLE_SUPPORT +/* TCODConsole non public methods*/ +bool TCOD_console_init(TCOD_console_t con,const char *title, bool fullscreen); +int TCOD_console_print_internal(TCOD_console_t con,int x,int y, int w, int h, TCOD_bkgnd_flag_t flag, TCOD_alignment_t align, char *msg, bool can_split, bool count_only); +int TCOD_console_stringLength(const unsigned char *s); +unsigned char * TCOD_console_forward(unsigned char *s,int l); +char *TCOD_console_vsprint(const char *fmt, va_list ap); +#endif + +/* fatal errors */ +void TCOD_fatal(const char *fmt, ...); +void TCOD_fatal_nopar(const char *msg); + +/* TCODSystem non public methods */ +#ifdef TCOD_CONSOLE_SUPPORT +void TCOD_console_data_free(struct TCOD_Console *dat); +bool TCOD_sys_init(struct TCOD_Console *console, bool fullscreen); +void TCOD_sys_set_custom_font(const char *font_name,int nb_ch, int nb_cv,int flags); +void TCOD_sys_map_ascii_to_font(int asciiCode, int fontCharX, int fontCharY); +void *TCOD_sys_create_bitmap_for_console(TCOD_console_t console); +void TCOD_sys_save_bitmap(void *bitmap, const char *filename); +void *TCOD_sys_create_bitmap(int width, int height, TCOD_color_t *buf); +void TCOD_sys_delete_bitmap(void *bitmap); +void TCOD_sys_console_to_bitmap(void *bitmap, struct TCOD_Console *console, + struct TCOD_Console *cache); +TCODLIB_API void *TCOD_sys_get_surface(int width, int height, bool alpha); +void TCOD_sys_save_fps(void); +void TCOD_sys_restore_fps(void); +void TCOD_sys_set_dirty(int dx, int dy, int dw, int dh); +void TCOD_sys_set_dirty_character_code(int ch); +int TCOD_get_tileid_for_charcode_(int charcode); + +/* switch fullscreen mode */ +void TCOD_sys_set_fullscreen(bool fullscreen); +void TCOD_sys_set_clear_screen(void); +void TCOD_sys_set_scale_factor(float value); +void TCOD_sys_convert_console_to_screen_coords(int cx, int cy, int *sx, int *sy); +void TCOD_sys_convert_screen_to_console_coords(int sx, int sy, int *cx, int *cy); +void TCOD_sys_flush(bool render); +TCOD_key_t TCOD_sys_check_for_keypress(int flags); +TCOD_key_t TCOD_sys_wait_for_keypress(bool flush); +bool TCOD_sys_is_key_pressed(TCOD_keycode_t key); +void TCOD_sys_set_window_title(const char *title); +#endif + +/* UTF-8 stuff */ +#ifndef NO_UNICODE +wchar_t *TCOD_console_vsprint_utf(const wchar_t *fmt, va_list ap); +int TCOD_console_print_internal_utf(TCOD_console_t con,int x,int y, int rw, int rh, TCOD_bkgnd_flag_t flag, + TCOD_alignment_t align, wchar_t *msg, bool can_split, bool count_only); +#endif + +#ifdef TCOD_IMAGE_SUPPORT +/* image manipulation */ +TCODLIB_API void *TCOD_sys_load_image(const char *filename); +void TCOD_sys_get_image_size(const void *image, int *w,int *h); +TCOD_color_t TCOD_sys_get_image_pixel(const void *image,int x, int y); +int TCOD_sys_get_image_alpha(const void *image,int x, int y); +bool TCOD_sys_check_magic_number(const char *filename, size_t size, uint8_t *data); +#endif + +/* TCOD_list nonpublic methods */ +void TCOD_list_set_size(TCOD_list_t l, int size); + +#ifndef TCOD_BARE +/* + SDL12/SDL2 abstraction layer +*/ +typedef struct TCOD_SDL_driver_t { + float scale_xc; + float scale_yc; + + /* get a fullscreen mode suitable for the console */ + void (*get_closest_mode)(int *w, int *h); + /* render the console on a surface/texture */ + void (*render)(struct TCOD_SDL_driver_t *sdl, void *vbitmap, struct TCOD_Console *console); + /* create a new surface */ + struct SDL_Surface *(*create_surface) (int width, int height, bool with_alpha); + /* create the game window */ + void (*create_window)(int w, int h, bool fullscreen); + /* destroy the game window */ + void (*destroy_window)(void); + /* switch fullscreen on/off */ + void (*set_fullscreen)(bool fullscreen); + /* change the game window title */ + void (*set_window_title)(const char *title); + /* save game screenshot */ + void (*save_screenshot)(const char *filename); + /* get desktop resolution */ + void (*get_current_resolution)(int *w, int *h); + /* change the mouse cursor position */ + void (*set_mouse_position)(int x, int y); + /* clipboard */ + char *(*get_clipboard_text)(void); + bool (*set_clipboard_text)(const char *text); + /* android compatible file access functions */ + bool (*file_read)(const char *filename, unsigned char **buf, size_t *size); + bool (*file_exists)(const char * filename); + bool (*file_write)(const char *filename, unsigned char *buf, uint32_t size); + /* clean stuff */ + void (*shutdown)(void); + /* get root cache */ + struct TCOD_Console *(*get_root_console_cache)(void); +} TCOD_SDL_driver_t; + +/* defined in TCOD_sys_sdl12_c.c and TCOD_sys_sdl2_c.c */ +TCOD_SDL_driver_t *SDL_implementation_factory(void); + +void find_resolution(void); +void TCOD_sys_init_screen_offset(void); +typedef struct { + float force_recalc; + float last_scale_xc, last_scale_yc; + float last_scale_factor; + float last_fullscreen; + + float min_scale_factor; + + float src_height_width_ratio; + float dst_height_width_ratio; + int src_x0, src_y0; + int src_copy_width, src_copy_height; + int src_proportionate_width, src_proportionate_height; + int dst_display_width, dst_display_height; + int dst_offset_x, dst_offset_y; + int surface_width, surface_height; +} scale_data_t; +extern scale_data_t scale_data; + +extern float scale_factor; +extern struct SDL_Surface* charmap; +extern struct SDL_Window* window; +extern struct SDL_Renderer* renderer; +extern char *last_clipboard_text; +#endif + +/* SDL & OpenGL */ +extern int oldFade; + +/* color values */ +#define TCOD_BLACK 0,0,0 +#define TCOD_DARKEST_GREY 31,31,31 +#define TCOD_DARKER_GREY 63,63,63 +#define TCOD_DARK_GREY 95,95,95 +#define TCOD_GREY 127,127,127 +#define TCOD_LIGHT_GREY 159,159,159 +#define TCOD_LIGHTER_GREY 191,191,191 +#define TCOD_LIGHTEST_GREY 223,223,223 +#define TCOD_WHITE 255,255,255 + +#define TCOD_DARKEST_SEPIA 31,24,15 +#define TCOD_DARKER_SEPIA 63,50,31 +#define TCOD_DARK_SEPIA 94,75,47 +#define TCOD_SEPIA 127,101,63 +#define TCOD_LIGHT_SEPIA 158,134,100 +#define TCOD_LIGHTER_SEPIA 191,171,143 +#define TCOD_LIGHTEST_SEPIA 222,211,195 + +/* desaturated */ +#define TCOD_DESATURATED_RED 127,63,63 +#define TCOD_DESATURATED_FLAME 127,79,63 +#define TCOD_DESATURATED_ORANGE 127,95,63 +#define TCOD_DESATURATED_AMBER 127,111,63 +#define TCOD_DESATURATED_YELLOW 127,127,63 +#define TCOD_DESATURATED_LIME 111,127,63 +#define TCOD_DESATURATED_CHARTREUSE 95,127,63 +#define TCOD_DESATURATED_GREEN 63,127,63 +#define TCOD_DESATURATED_SEA 63,127,95 +#define TCOD_DESATURATED_TURQUOISE 63,127,111 +#define TCOD_DESATURATED_CYAN 63,127,127 +#define TCOD_DESATURATED_SKY 63,111,127 +#define TCOD_DESATURATED_AZURE 63,95,127 +#define TCOD_DESATURATED_BLUE 63,63,127 +#define TCOD_DESATURATED_HAN 79,63,127 +#define TCOD_DESATURATED_VIOLET 95,63,127 +#define TCOD_DESATURATED_PURPLE 111,63,127 +#define TCOD_DESATURATED_FUCHSIA 127,63,127 +#define TCOD_DESATURATED_MAGENTA 127,63,111 +#define TCOD_DESATURATED_PINK 127,63,95 +#define TCOD_DESATURATED_CRIMSON 127,63,79 + +/* lightest */ +#define TCOD_LIGHTEST_RED 255,191,191 +#define TCOD_LIGHTEST_FLAME 255,207,191 +#define TCOD_LIGHTEST_ORANGE 255,223,191 +#define TCOD_LIGHTEST_AMBER 255,239,191 +#define TCOD_LIGHTEST_YELLOW 255,255,191 +#define TCOD_LIGHTEST_LIME 239,255,191 +#define TCOD_LIGHTEST_CHARTREUSE 223,255,191 +#define TCOD_LIGHTEST_GREEN 191,255,191 +#define TCOD_LIGHTEST_SEA 191,255,223 +#define TCOD_LIGHTEST_TURQUOISE 191,255,239 +#define TCOD_LIGHTEST_CYAN 191,255,255 +#define TCOD_LIGHTEST_SKY 191,239,255 +#define TCOD_LIGHTEST_AZURE 191,223,255 +#define TCOD_LIGHTEST_BLUE 191,191,255 +#define TCOD_LIGHTEST_HAN 207,191,255 +#define TCOD_LIGHTEST_VIOLET 223,191,255 +#define TCOD_LIGHTEST_PURPLE 239,191,255 +#define TCOD_LIGHTEST_FUCHSIA 255,191,255 +#define TCOD_LIGHTEST_MAGENTA 255,191,239 +#define TCOD_LIGHTEST_PINK 255,191,223 +#define TCOD_LIGHTEST_CRIMSON 255,191,207 + +/* lighter */ +#define TCOD_LIGHTER_RED 255,127,127 +#define TCOD_LIGHTER_FLAME 255,159,127 +#define TCOD_LIGHTER_ORANGE 255,191,127 +#define TCOD_LIGHTER_AMBER 255,223,127 +#define TCOD_LIGHTER_YELLOW 255,255,127 +#define TCOD_LIGHTER_LIME 223,255,127 +#define TCOD_LIGHTER_CHARTREUSE 191,255,127 +#define TCOD_LIGHTER_GREEN 127,255,127 +#define TCOD_LIGHTER_SEA 127,255,191 +#define TCOD_LIGHTER_TURQUOISE 127,255,223 +#define TCOD_LIGHTER_CYAN 127,255,255 +#define TCOD_LIGHTER_SKY 127,223,255 +#define TCOD_LIGHTER_AZURE 127,191,255 +#define TCOD_LIGHTER_BLUE 127,127,255 +#define TCOD_LIGHTER_HAN 159,127,255 +#define TCOD_LIGHTER_VIOLET 191,127,255 +#define TCOD_LIGHTER_PURPLE 223,127,255 +#define TCOD_LIGHTER_FUCHSIA 255,127,255 +#define TCOD_LIGHTER_MAGENTA 255,127,223 +#define TCOD_LIGHTER_PINK 255,127,191 +#define TCOD_LIGHTER_CRIMSON 255,127,159 + +/* light */ +#define TCOD_LIGHT_RED 255,63,63 +#define TCOD_LIGHT_FLAME 255,111,63 +#define TCOD_LIGHT_ORANGE 255,159,63 +#define TCOD_LIGHT_AMBER 255,207,63 +#define TCOD_LIGHT_YELLOW 255,255,63 +#define TCOD_LIGHT_LIME 207,255,63 +#define TCOD_LIGHT_CHARTREUSE 159,255,63 +#define TCOD_LIGHT_GREEN 63,255,63 +#define TCOD_LIGHT_SEA 63,255,159 +#define TCOD_LIGHT_TURQUOISE 63,255,207 +#define TCOD_LIGHT_CYAN 63,255,255 +#define TCOD_LIGHT_SKY 63,207,255 +#define TCOD_LIGHT_AZURE 63,159,255 +#define TCOD_LIGHT_BLUE 63,63,255 +#define TCOD_LIGHT_HAN 111,63,255 +#define TCOD_LIGHT_VIOLET 159,63,255 +#define TCOD_LIGHT_PURPLE 207,63,255 +#define TCOD_LIGHT_FUCHSIA 255,63,255 +#define TCOD_LIGHT_MAGENTA 255,63,207 +#define TCOD_LIGHT_PINK 255,63,159 +#define TCOD_LIGHT_CRIMSON 255,63,111 + +/* normal */ +#define TCOD_RED 255,0,0 +#define TCOD_FLAME 255,63,0 +#define TCOD_ORANGE 255,127,0 +#define TCOD_AMBER 255,191,0 +#define TCOD_YELLOW 255,255,0 +#define TCOD_LIME 191,255,0 +#define TCOD_CHARTREUSE 127,255,0 +#define TCOD_GREEN 0,255,0 +#define TCOD_SEA 0,255,127 +#define TCOD_TURQUOISE 0,255,191 +#define TCOD_CYAN 0,255,255 +#define TCOD_SKY 0,191,255 +#define TCOD_AZURE 0,127,255 +#define TCOD_BLUE 0,0,255 +#define TCOD_HAN 63,0,255 +#define TCOD_VIOLET 127,0,255 +#define TCOD_PURPLE 191,0,255 +#define TCOD_FUCHSIA 255,0,255 +#define TCOD_MAGENTA 255,0,191 +#define TCOD_PINK 255,0,127 +#define TCOD_CRIMSON 255,0,63 + +/* dark */ +#define TCOD_DARK_RED 191,0,0 +#define TCOD_DARK_FLAME 191,47,0 +#define TCOD_DARK_ORANGE 191,95,0 +#define TCOD_DARK_AMBER 191,143,0 +#define TCOD_DARK_YELLOW 191,191,0 +#define TCOD_DARK_LIME 143,191,0 +#define TCOD_DARK_CHARTREUSE 95,191,0 +#define TCOD_DARK_GREEN 0,191,0 +#define TCOD_DARK_SEA 0,191,95 +#define TCOD_DARK_TURQUOISE 0,191,143 +#define TCOD_DARK_CYAN 0,191,191 +#define TCOD_DARK_SKY 0,143,191 +#define TCOD_DARK_AZURE 0,95,191 +#define TCOD_DARK_BLUE 0,0,191 +#define TCOD_DARK_HAN 47,0,191 +#define TCOD_DARK_VIOLET 95,0,191 +#define TCOD_DARK_PURPLE 143,0,191 +#define TCOD_DARK_FUCHSIA 191,0,191 +#define TCOD_DARK_MAGENTA 191,0,143 +#define TCOD_DARK_PINK 191,0,95 +#define TCOD_DARK_CRIMSON 191,0,47 + +/* darker */ +#define TCOD_DARKER_RED 127,0,0 +#define TCOD_DARKER_FLAME 127,31,0 +#define TCOD_DARKER_ORANGE 127,63,0 +#define TCOD_DARKER_AMBER 127,95,0 +#define TCOD_DARKER_YELLOW 127,127,0 +#define TCOD_DARKER_LIME 95,127,0 +#define TCOD_DARKER_CHARTREUSE 63,127,0 +#define TCOD_DARKER_GREEN 0,127,0 +#define TCOD_DARKER_SEA 0,127,63 +#define TCOD_DARKER_TURQUOISE 0,127,95 +#define TCOD_DARKER_CYAN 0,127,127 +#define TCOD_DARKER_SKY 0,95,127 +#define TCOD_DARKER_AZURE 0,63,127 +#define TCOD_DARKER_BLUE 0,0,127 +#define TCOD_DARKER_HAN 31,0,127 +#define TCOD_DARKER_VIOLET 63,0,127 +#define TCOD_DARKER_PURPLE 95,0,127 +#define TCOD_DARKER_FUCHSIA 127,0,127 +#define TCOD_DARKER_MAGENTA 127,0,95 +#define TCOD_DARKER_PINK 127,0,63 +#define TCOD_DARKER_CRIMSON 127,0,31 + +/* darkest */ +#define TCOD_DARKEST_RED 63,0,0 +#define TCOD_DARKEST_FLAME 63,15,0 +#define TCOD_DARKEST_ORANGE 63,31,0 +#define TCOD_DARKEST_AMBER 63,47,0 +#define TCOD_DARKEST_YELLOW 63,63,0 +#define TCOD_DARKEST_LIME 47,63,0 +#define TCOD_DARKEST_CHARTREUSE 31,63,0 +#define TCOD_DARKEST_GREEN 0,63,0 +#define TCOD_DARKEST_SEA 0,63,31 +#define TCOD_DARKEST_TURQUOISE 0,63,47 +#define TCOD_DARKEST_CYAN 0,63,63 +#define TCOD_DARKEST_SKY 0,47,63 +#define TCOD_DARKEST_AZURE 0,31,63 +#define TCOD_DARKEST_BLUE 0,0,63 +#define TCOD_DARKEST_HAN 15,0,63 +#define TCOD_DARKEST_VIOLET 31,0,63 +#define TCOD_DARKEST_PURPLE 47,0,63 +#define TCOD_DARKEST_FUCHSIA 63,0,63 +#define TCOD_DARKEST_MAGENTA 63,0,47 +#define TCOD_DARKEST_PINK 63,0,31 +#define TCOD_DARKEST_CRIMSON 63,0,15 + +/* metallic */ +#define TCOD_BRASS 191,151,96 +#define TCOD_COPPER 197,136,124 +#define TCOD_GOLD 229,191,0 +#define TCOD_SILVER 203,203,203 + +/* miscellaneous */ +#define TCOD_CELADON 172,255,175 +#define TCOD_PEACH 255,159,127 + +#ifdef __cplusplus +} +#endif +#endif diff --git a/tcod_sys/libtcod/include/list.h b/tcod_sys/libtcod/src/libtcod/list.h similarity index 97% rename from tcod_sys/libtcod/include/list.h rename to tcod_sys/libtcod/src/libtcod/list.h index 15514aa1d..85c0892a2 100644 --- a/tcod_sys/libtcod/include/list.h +++ b/tcod_sys/libtcod/src/libtcod/list.h @@ -28,13 +28,15 @@ #ifndef _TCOD_LIST_H #define _TCOD_LIST_H -#include "libtcod_portability.h" +#include "portability.h" #ifdef __cplusplus extern "C" { #endif -typedef void *TCOD_list_t; +struct TCOD_List; + +typedef struct TCOD_List *TCOD_list_t; TCODLIB_API TCOD_list_t TCOD_list_new(void); TCODLIB_API TCOD_list_t TCOD_list_allocate(int nb_elements); diff --git a/tcod_sys/libtcod/include/list.hpp b/tcod_sys/libtcod/src/libtcod/list.hpp similarity index 100% rename from tcod_sys/libtcod/include/list.hpp rename to tcod_sys/libtcod/src/libtcod/list.hpp diff --git a/tcod_sys/libtcod/src/libtcod/list_c.c b/tcod_sys/libtcod/src/libtcod/list_c.c new file mode 100644 index 000000000..7a0a6a430 --- /dev/null +++ b/tcod_sys/libtcod/src/libtcod/list_c.c @@ -0,0 +1,302 @@ +/* +* libtcod +* Copyright (c) 2008-2018 Jice & Mingos & rmtew +* All rights reserved. +* +* Redistribution and use in source and binary forms, with or without +* modification, are permitted provided that the following conditions are met: +* * Redistributions of source code must retain the above copyright +* notice, this list of conditions and the following disclaimer. +* * Redistributions in binary form must reproduce the above copyright +* notice, this list of conditions and the following disclaimer in the +* documentation and/or other materials provided with the distribution. +* * The name of Jice or Mingos may not be used to endorse or promote +* products derived from this software without specific prior written +* permission. +* +* THIS SOFTWARE IS PROVIDED BY JICE, MINGOS AND RMTEW ``AS IS'' AND ANY +* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED +* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE +* DISCLAIMED. IN NO EVENT SHALL JICE, MINGOS OR RMTEW BE LIABLE FOR ANY +* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES +* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; +* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND +* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS +* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +*/ +#include "list.h" + +#include /* calloc */ +#include /* NULL/memcpy */ + +#include "utility.h" +/** + * A lightweight and generic container that provides array, list, and stack + * paradigms. + */ +struct TCOD_List { + /** + * A pointer to an array of void pointers. + */ + void **array; + /** The current count of items in the array. */ + int fillSize; + /** The maximum number of items that `array` can currently hold. */ + int allocSize; +}; +/** + * Initialize or expand the array of a TCOD_list_t struct. + * + * If `l->allocSize` is zero then a new array is allocated, and allocSize is + * set. If `l->allocSize` is not zero then the allocated size is doubled. + */ +static void TCOD_list_allocate_int(TCOD_list_t l) { + void **newArray; + int newSize = l->allocSize * 2; + if (newSize == 0) { newSize = 16; } + newArray = (void **)calloc(sizeof(void *), newSize); + if (l->array) { + if (l->fillSize > 0) { + memcpy(newArray, l->array, sizeof(void *) * l->fillSize); + } + free(l->array); + } + l->array = newArray; + l->allocSize = newSize; +} +/** + * Set the number of items in a list. + * + * The new size will be no more than `l->allocSize`. + */ +void TCOD_list_set_size(TCOD_list_t l, int size) { + l->fillSize = MIN(size, l->allocSize); +} +/** + * Return a new list. + */ +TCOD_list_t TCOD_list_new(void) { + return (TCOD_list_t)calloc(1, sizeof(struct TCOD_List)); +} +/** + * Return a new list which can hold up to `nb_elements` items. + */ +TCOD_list_t TCOD_list_allocate(int nb_elements) { + TCOD_list_t l = TCOD_list_new(); + l->array = (void **)calloc(sizeof(void *), nb_elements); + l->allocSize = nb_elements; + return l; +} +/** + * Return a new copy of `l`. + */ +TCOD_list_t TCOD_list_duplicate(TCOD_list_t l) { + int i = 0; + void **t; + TCOD_list_t ret = TCOD_list_allocate(l->allocSize); + ret->fillSize = l->fillSize; + for (t = TCOD_list_begin(l); t != TCOD_list_end(l); ++t) { + ret->array[i++] = *t; + } + return ret; +} +/** + * Delete a list. + * + * This only frees the list itself, if the list contains any pointers then + * those will need to be freed separately. + */ +void TCOD_list_delete(TCOD_list_t l) { + if (l) { + free(l->array); + } + free(l); +} +/** + * Add `elt` to the end of a list. + */ +void TCOD_list_push(TCOD_list_t l, const void *elt) { + if (l->fillSize + 1 >= l->allocSize) { TCOD_list_allocate_int(l); } + l->array[l->fillSize++] = (void *)elt; +} +/** + * Remove the last item from a list and return it. + * + * If the list is empty this will return NULL. + */ +void * TCOD_list_pop(TCOD_list_t l) { + if (l->fillSize == 0) { return NULL; } + return l->array[--(l->fillSize)]; +} +/** + * Return the list item from the list, without removing it. + * + * If the list is empty this will return NULL. + */ +void * TCOD_list_peek(TCOD_list_t l) { + if (l->fillSize == 0) { return NULL; } + return l->array[l->fillSize - 1]; +} +/** + * Add all items from `l2` to the end of `l`. + */ +void TCOD_list_add_all(TCOD_list_t l, TCOD_list_t l2) { + void **curElt; + for (curElt = TCOD_list_begin(l2); curElt != TCOD_list_end(l2); ++curElt) { + TCOD_list_push(l, *curElt); + } +} +/** + * Return the item at index `idx`. + */ +void * TCOD_list_get(TCOD_list_t l,int idx) { + return l->array[idx]; +} +/** + * Set the item at `idx` to `elt`. + * + * The list will automatically resize to fit and item at `idx`. + */ +void TCOD_list_set(TCOD_list_t l,const void *elt, int idx) { + if (idx < 0) { return; } + while (l->allocSize < idx + 1) { TCOD_list_allocate_int(l); } + l->array[idx] = (void *)elt; + if (idx + 1 > l->fillSize) l->fillSize = idx + 1; +} +/** + * Return a pointer to the beginning of the list. + */ +void ** TCOD_list_begin(TCOD_list_t l) { + if (l->fillSize == 0) { return (void **)NULL; } + return &l->array[0]; +} +/** + * Return a pointer to the end of the list. + */ +void ** TCOD_list_end(TCOD_list_t l) { + if (l->fillSize == 0) { return (void **)NULL; } + return &l->array[l->fillSize]; +} +/** + * Reverse the order of the list. + */ +void TCOD_list_reverse(TCOD_list_t l) { + void **head = TCOD_list_begin(l); + void **tail = TCOD_list_end(l) - 1; + while (head < tail) { + void *tmp = *head; + *head = *tail; + *tail = tmp; + ++head; + --tail; + } +} +/** + * Remove an item from the list and return a new iterator. + */ +void **TCOD_list_remove_iterator(TCOD_list_t l, void **elt) { + void **curElt; + for (curElt = elt; curElt < TCOD_list_end(l) - 1; ++curElt) { + *curElt = *(curElt + 1); + } + l->fillSize--; + if (l->fillSize == 0) { + return ((void **)NULL) - 1; + } else { + return elt - 1; + } +} +/** + * Remove an item from the list. + */ +void TCOD_list_remove(TCOD_list_t l, const void *elt) { + void **curElt; + for (curElt = TCOD_list_begin(l); curElt != TCOD_list_end(l); ++curElt) { + if (*curElt == elt) { + TCOD_list_remove_iterator(l, curElt); + return; + } + } +} +/** + * Remove an item from the list and return a new iterator. + * + * This fast version replaces the removed item with the item at the end of the + * list. This is faster but does not preserve the list order. + */ +void **TCOD_list_remove_iterator_fast(TCOD_list_t l, void **elt) { + *elt = l->array[l->fillSize-1]; + l->fillSize--; + if (l->fillSize == 0) { + return ((void **)NULL) - 1; + } else { + return elt - 1; + } +} +/** + * Remove an item from the list, not preserving the list order. + * + * The removed item is replaced with the item from the end of the list. + * This is faster but does not preserve the list order. + */ +void TCOD_list_remove_fast(TCOD_list_t l, const void *elt) { + void **curElt; + for (curElt = TCOD_list_begin(l); curElt != TCOD_list_end(l); ++curElt) { + if (*curElt == elt) { + TCOD_list_remove_iterator_fast(l, curElt); + return; + } + } +} +/** + * Return true if `elt` is in the list. + */ +bool TCOD_list_contains(TCOD_list_t l,const void *elt) { + void **curElt; + for (curElt = TCOD_list_begin(l); curElt != TCOD_list_end(l); ++curElt) { + if (*curElt == elt) { return true; } + } + return false; +} +/** + * Remove ALL items from a list. + */ +void TCOD_list_clear(TCOD_list_t l) { + l->fillSize = 0; +} +/** + * Call free() on all items on the list, then remove them. + */ +void TCOD_list_clear_and_delete(TCOD_list_t l) { + void **curElt; + for (curElt = TCOD_list_begin(l); curElt != TCOD_list_end(l); ++curElt) { + free(*curElt); + } + l->fillSize = 0; +} +/** + * Return the current count of items in a list. + */ +int TCOD_list_size(TCOD_list_t l) { + return l->fillSize; +} +/** + * Insert `elt` on the index before `before`. + */ +void **TCOD_list_insert_before(TCOD_list_t l,const void *elt,int before) { + int idx; + if (l->fillSize+1 >= l->allocSize) { TCOD_list_allocate_int(l); } + for (idx = l->fillSize; idx > before; --idx) { + l->array[idx] = l->array[idx - 1]; + } + l->array[before] = (void *)elt; + l->fillSize++; + return &l->array[before]; +} +/** + * Return true if this list is empty. + */ +bool TCOD_list_is_empty(TCOD_list_t l) { + return (l->fillSize == 0); +} diff --git a/tcod_sys/libtcod/src/mersenne.cpp b/tcod_sys/libtcod/src/libtcod/mersenne.cpp similarity index 95% rename from tcod_sys/libtcod/src/mersenne.cpp rename to tcod_sys/libtcod/src/libtcod/mersenne.cpp index bab46be81..ef1bb568d 100644 --- a/tcod_sys/libtcod/src/mersenne.cpp +++ b/tcod_sys/libtcod/src/libtcod/mersenne.cpp @@ -1,63 +1,63 @@ -/* -* libtcod -* Copyright (c) 2008-2018 Jice & Mingos & rmtew -* All rights reserved. -* -* Redistribution and use in source and binary forms, with or without -* modification, are permitted provided that the following conditions are met: -* * Redistributions of source code must retain the above copyright -* notice, this list of conditions and the following disclaimer. -* * Redistributions in binary form must reproduce the above copyright -* notice, this list of conditions and the following disclaimer in the -* documentation and/or other materials provided with the distribution. -* * The name of Jice or Mingos may not be used to endorse or promote -* products derived from this software without specific prior written -* permission. -* -* THIS SOFTWARE IS PROVIDED BY JICE, MINGOS AND RMTEW ``AS IS'' AND ANY -* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED -* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE -* DISCLAIMED. IN NO EVENT SHALL JICE, MINGOS OR RMTEW BE LIABLE FOR ANY -* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES -* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; -* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND -* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS -* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. -*/ -#include - -#include - -#include - -static TCODRandom *instance=(TCODRandom *)NULL; - -TCODRandom *TCODRandom::getInstance(void) { - if (! instance ) { - instance=new TCODRandom(TCOD_RNG_CMWC,true); - } - return instance; -} - -TCODRandom::TCODRandom(TCOD_random_algo_t algo, bool allocate) { - if ( allocate ) data = TCOD_random_new(algo); -} - -TCODRandom::TCODRandom(uint32_t seed, TCOD_random_algo_t algo) { - data=TCOD_random_new_from_seed(algo, seed); -} - -TCODRandom::~TCODRandom() { - TCOD_random_delete(data); -} - -TCODRandom *TCODRandom::save() const { - TCODRandom *ret=new TCODRandom(((mersenne_data_t *)data)->algo,false); - ret->data=TCOD_random_save(data); - return ret; -} - -void TCODRandom::restore(const TCODRandom *backup) { - TCOD_random_restore(data,backup->data); -} +/* +* libtcod +* Copyright (c) 2008-2018 Jice & Mingos & rmtew +* All rights reserved. +* +* Redistribution and use in source and binary forms, with or without +* modification, are permitted provided that the following conditions are met: +* * Redistributions of source code must retain the above copyright +* notice, this list of conditions and the following disclaimer. +* * Redistributions in binary form must reproduce the above copyright +* notice, this list of conditions and the following disclaimer in the +* documentation and/or other materials provided with the distribution. +* * The name of Jice or Mingos may not be used to endorse or promote +* products derived from this software without specific prior written +* permission. +* +* THIS SOFTWARE IS PROVIDED BY JICE, MINGOS AND RMTEW ``AS IS'' AND ANY +* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED +* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE +* DISCLAIMED. IN NO EVENT SHALL JICE, MINGOS OR RMTEW BE LIABLE FOR ANY +* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES +* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; +* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND +* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS +* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +*/ +#include "mersenne.hpp" + +#include + +#include "libtcod_int.h" + +static TCODRandom *instance=(TCODRandom *)NULL; + +TCODRandom *TCODRandom::getInstance(void) { + if (! instance ) { + instance=new TCODRandom(TCOD_RNG_CMWC,true); + } + return instance; +} + +TCODRandom::TCODRandom(TCOD_random_algo_t algo, bool allocate) { + if ( allocate ) data = TCOD_random_new(algo); +} + +TCODRandom::TCODRandom(uint32_t seed, TCOD_random_algo_t algo) { + data=TCOD_random_new_from_seed(algo, seed); +} + +TCODRandom::~TCODRandom() { + TCOD_random_delete(data); +} + +TCODRandom *TCODRandom::save() const { + TCODRandom *ret=new TCODRandom(((mersenne_data_t *)data)->algo,false); + ret->data=TCOD_random_save(data); + return ret; +} + +void TCODRandom::restore(const TCODRandom *backup) { + TCOD_random_restore(data,backup->data); +} diff --git a/tcod_sys/libtcod/include/mersenne.h b/tcod_sys/libtcod/src/libtcod/mersenne.h similarity index 98% rename from tcod_sys/libtcod/include/mersenne.h rename to tcod_sys/libtcod/src/libtcod/mersenne.h index c2bef0fb8..1deaa012f 100644 --- a/tcod_sys/libtcod/include/mersenne.h +++ b/tcod_sys/libtcod/src/libtcod/mersenne.h @@ -28,7 +28,7 @@ #ifndef _TCOD_RANDOM_H #define _TCOD_RANDOM_H -#include "libtcod_portability.h" +#include "portability.h" #include "mersenne_types.h" #ifdef __cplusplus diff --git a/tcod_sys/libtcod/include/mersenne.hpp b/tcod_sys/libtcod/src/libtcod/mersenne.hpp similarity index 100% rename from tcod_sys/libtcod/include/mersenne.hpp rename to tcod_sys/libtcod/src/libtcod/mersenne.hpp diff --git a/tcod_sys/libtcod/src/mersenne_c.c b/tcod_sys/libtcod/src/libtcod/mersenne_c.c similarity index 96% rename from tcod_sys/libtcod/src/mersenne_c.c rename to tcod_sys/libtcod/src/libtcod/mersenne_c.c index 6ce7dbfbf..b57ed1573 100644 --- a/tcod_sys/libtcod/src/mersenne_c.c +++ b/tcod_sys/libtcod/src/libtcod/mersenne_c.c @@ -1,545 +1,545 @@ -/* -* libtcod -* Copyright (c) 2008-2018 Jice & Mingos & rmtew -* All rights reserved. -* -* Redistribution and use in source and binary forms, with or without -* modification, are permitted provided that the following conditions are met: -* * Redistributions of source code must retain the above copyright -* notice, this list of conditions and the following disclaimer. -* * Redistributions in binary form must reproduce the above copyright -* notice, this list of conditions and the following disclaimer in the -* documentation and/or other materials provided with the distribution. -* * The name of Jice or Mingos may not be used to endorse or promote -* products derived from this software without specific prior written -* permission. -* -* THIS SOFTWARE IS PROVIDED BY JICE, MINGOS AND RMTEW ``AS IS'' AND ANY -* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED -* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE -* DISCLAIMED. IN NO EVENT SHALL JICE, MINGOS OR RMTEW BE LIABLE FOR ANY -* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES -* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; -* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND -* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS -* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. -*/ -#include - -#include -#include -#include -#include - -#include -#include - -static TCOD_random_t instance=NULL; -static float rand_div=1.0f/(float)(0xffffffff); -static double rand_div_double = 1.0 / (double)(0xffffffff); - -/* initialize the mersenne twister array */ -static void mt_init(uint32_t seed, uint32_t mt[624] ) -{ - int i; - mt[0]= seed; - for (i=1; i<624; i++) { - mt[i] = (1812433253 * (mt[i-1] ^ (mt[i-1] >> 30)) + i); - } -} - -/* get the next random value from the mersenne twister array */ -static uint32_t mt_rand(uint32_t mt[624], int *cur_mt) -{ -#define MT_HIGH_BIT 0x80000000UL -#define MT_LOW_BITS 0x7fffffffUL - uint32_t y; - - if (*cur_mt == 624) { - /* our 624 sequence is finished. generate a new one */ - int i; - - for (i=0;i<623;i++) { - y = ( mt[i] & MT_HIGH_BIT ) | ( mt[i+1] & MT_LOW_BITS ); - if ( y & 1 ) { - /* odd y */ - mt[i] = mt[ (i + 397) % 624 ] ^ (y >> 1) ^ 2567483615UL; - } else { - /* even y */ - mt[i] = mt[ (i + 397) % 624 ] ^ (y >> 1); - } - } - y = ( mt[623] & MT_HIGH_BIT ) | ( mt[0] & MT_LOW_BITS ); - if ( y & 1 ) { - /* odd y */ - mt[623] = mt[396] ^ (y >> 1) ^ 2567483615UL; - } else { - mt[623] = mt[396] ^ (y >> 1); - } - - *cur_mt = 0; - } - - y = mt[(*cur_mt)++]; - y ^= (y >> 11); - y ^= (y << 7) & 2636928640UL; - y ^= (y << 15) & 4022730752UL; - y ^= (y >> 18); - return y; -} - -/* get a random float between 0 and 1 */ -static float frandom01(mersenne_data_t *r) { - return (float)mt_rand(r->mt,&r->cur_mt)*rand_div; -} - -/* string hashing function */ -/* not used (yet) -static uint32_t hash(const char *data,int len) { - uint32_t hash = 0; - uint32_t x; - int i; - for(i = 0; i < len; data++, i++) { - hash = (hash << 4) + (*data); - if((x = hash & 0xF0000000L) != 0) { - hash ^= (x >> 24); - hash &= ~x; - } - } - return (hash & 0x7FFFFFFF); -} -*/ - -/* get a random number from the CMWC */ -#define CMWC_GET_NUMBER(num) { unsigned long long t; uint32_t x; r->cur=(r->cur+1)&4095; t=18782LL*r->Q[r->cur]+r->c; r->c=(t>>32); x=(uint32_t)(t+r->c); if (x < r->c) { x++; r->c++; } if((x+1)==0) { r->c++; x=0; } num = (uint32_t)(r->Q[r->cur] = 0xfffffffe - x); } - -TCOD_random_t TCOD_random_new(TCOD_random_algo_t algo) { - return TCOD_random_new_from_seed(algo,(uint32_t)time(0)); -} - -TCOD_random_t TCOD_random_get_instance(void) { - if (! instance ) { - instance=TCOD_random_new(TCOD_RNG_CMWC); - } - return instance; -} - -TCOD_random_t TCOD_random_new_from_seed(TCOD_random_algo_t algo, uint32_t seed) { - mersenne_data_t *r = (mersenne_data_t *)calloc(sizeof(mersenne_data_t),1); - /* Mersenne Twister */ - if (algo == TCOD_RNG_MT) { - r->algo = TCOD_RNG_MT; - r->cur_mt=624; - mt_init(seed,r->mt); - } - /* Complementary-Multiply-With-Carry or Generalised Feedback Shift Register */ - else { - int i; - /* fill the Q array with pseudorandom seeds */ - uint32_t s = seed; - for (i = 0; i < 4096; i++) r->Q[i] = s = (s * 1103515245) + 12345; /* glibc LCG */ - r->c = ((s * 1103515245) + 12345) % 809430660; /* this max value is recommended by George Marsaglia */ - r->cur = 0; - r->algo = TCOD_RNG_CMWC; - } - r->distribution = TCOD_DISTRIBUTION_LINEAR; - return (TCOD_random_t)r; -} - - -int TCOD_random_get_i(TCOD_random_t mersenne, int min, int max) { - mersenne_data_t *r; - int delta; - if (max==min) return min; - else if (max < min) { - int tmp=max; - max=min; - min=tmp; - } - if (!mersenne) mersenne=TCOD_random_get_instance(); - r=(mersenne_data_t *)mersenne; - delta = max - min + 1; - /* return a number from the Mersenne Twister */ - if (r->algo == TCOD_RNG_MT) return ( mt_rand(r->mt,&r->cur_mt) % delta ) + min; - /* or from the CMWC */ - else { - uint32_t number; - CMWC_GET_NUMBER(number) - return number % delta + min; - } -} - -float TCOD_random_get_f(TCOD_random_t mersenne,float min, float max) { - mersenne_data_t *r; - float delta,f; - if (max==min) return min; - else if (max < min) { - float tmp=max; - max=min; - min=tmp; - } - if (!mersenne) mersenne=TCOD_random_get_instance(); - r=(mersenne_data_t *)mersenne; - delta = max - min; - /* Mersenne Twister */ - if (r->algo == TCOD_RNG_MT) f = delta * frandom01(r); - /* CMWC */ - else { - uint32_t number; - CMWC_GET_NUMBER(number) - f = (float)(number) * rand_div * delta; - } - return min + f; -} - -double TCOD_random_get_d(TCOD_random_t mersenne, double min, double max) { - mersenne_data_t *r; - double delta,f; - if (max==min) return min; - else if (max < min) { - double tmp=max; - max=min; - min=tmp; - } - if (!mersenne) mersenne=TCOD_random_get_instance(); - r=(mersenne_data_t *)mersenne; - delta = max - min; - /* Mersenne Twister */ - if (r->algo == TCOD_RNG_MT) f = delta * (double)frandom01(r); - /* CMWC */ - else { - uint32_t number; - CMWC_GET_NUMBER(number) - f = (double)(number) * rand_div_double * delta; - } - return min + f; -} - -void TCOD_random_delete(TCOD_random_t mersenne) { - TCOD_IFNOT(mersenne != NULL) return; - if ( mersenne == instance ) instance = NULL; - free(mersenne); -} -TCOD_random_t TCOD_random_save(TCOD_random_t mersenne) { - mersenne_data_t *ret=(mersenne_data_t *)malloc(sizeof(mersenne_data_t)); - if (!mersenne) mersenne=TCOD_random_get_instance(); - memcpy(ret,mersenne,sizeof(mersenne_data_t)); - return (TCOD_random_t)ret; -} - -void TCOD_random_restore(TCOD_random_t mersenne, TCOD_random_t backup) { - if (!mersenne) mersenne=TCOD_random_get_instance(); - memcpy(mersenne,backup,sizeof(mersenne_data_t)); -} - -/* Box-Muller transform (Gaussian distribution) */ - -double TCOD_random_get_gaussian_double (TCOD_random_t mersenne, double mean, double std_deviation) { - double x1, x2, w, y1; - static double y2; - static bool again = false; - double ret; - if (again) - ret = mean + y2 * std_deviation; - else { - mersenne_data_t *r = NULL; - if (!mersenne) mersenne=TCOD_random_get_instance(); - r = (mersenne_data_t *)mersenne; - /* MT */ - if (r->algo == TCOD_RNG_MT) { - do { - x1 = frandom01(r) * 2.0 - 1.0; - x2 = frandom01(r) * 2.0 - 1.0; - w = x1 * x1 + x2 * x2; - } while (w >= 1.0); - } - /* CMWC */ - else { - uint32_t number; - do { - CMWC_GET_NUMBER(number) - x1 = number * rand_div_double * 2.0 - 1.0; - CMWC_GET_NUMBER(number) - x2 = number * rand_div_double * 2.0 - 1.0; - w = x1 * x1 + x2 * x2; - } while (w >= 1.0); - } - w = sqrt((-2.0 * log(w)) / w); - y1 = x1 * w; - y2 = x2 * w; - ret = mean + y1 * std_deviation; - } - again = !again; - return ret; -} - -float TCOD_random_get_gaussian_float (TCOD_random_t mersenne, float mean, float std_deviation) { - return (float)TCOD_random_get_gaussian_double(mersenne, (double)mean, (double)std_deviation); -} - -int TCOD_random_get_gaussian_int (TCOD_random_t mersenne, int mean, int std_deviation) { - double num = TCOD_random_get_gaussian_double(mersenne,(double)mean,(double)std_deviation); - return (num >= 0.0 ? (int)(num + 0.5) : (int)(num - 0.5)); -} - -/* Box-Muller, ranges */ - -double TCOD_random_get_gaussian_double_range (TCOD_random_t mersenne, double min, double max) { - double mean, std_deviation, ret; - if (min > max) { - double tmp = max; - max = min; - min = tmp; - } - mean = (min + max) / 2; - std_deviation = (max - min) / 6.0; /* 6.0 is used because of the three-sigma rule */ - ret = TCOD_random_get_gaussian_double(mersenne, mean, std_deviation); - return CLAMP(min,max,ret); -} - -float TCOD_random_get_gaussian_float_range (TCOD_random_t mersenne, float min, float max) { - if (min > max) { - float tmp = max; - max = min; - min = tmp; - } - return (float)TCOD_random_get_gaussian_double_range (mersenne, (double)min, (double)max); -} - -int TCOD_random_get_gaussian_int_range (TCOD_random_t mersenne, int min, int max) { - double num; - int ret; - if (min > max) { - int tmp = max; - max = min; - min = tmp; - } - num = TCOD_random_get_gaussian_double_range (mersenne, (double)min, (double)max); - ret = (num >= 0.0 ? (int)(num + 0.5) : (int)(num - 0.5)); - return CLAMP(min,max,ret); -} - -/* Box-Muller, ranges with a custom mean */ - -double TCOD_random_get_gaussian_double_range_custom (TCOD_random_t mersenne, double min, double max, double mean) { - double d1, d2, std_deviation, ret; - if (min > max) { - double tmp = max; - max = min; - min = tmp; - } - d1 = max - mean; - d2 = mean - min; - std_deviation = MAX(d1,d2) / 3.0; - ret = TCOD_random_get_gaussian_double(mersenne, mean, std_deviation); - return CLAMP(min,max,ret); -} - -float TCOD_random_get_gaussian_float_range_custom (TCOD_random_t mersenne, float min, float max, float mean) { - if (min > max) { - float tmp = max; - max = min; - min = tmp; - } - return (float)TCOD_random_get_gaussian_double_range_custom (mersenne, (double)min, (double)max, (double)mean); -} - -int TCOD_random_get_gaussian_int_range_custom (TCOD_random_t mersenne, int min, int max, int mean) { - double num; - int ret; - if (min > max) { - int tmp = max; - max = min; - min = tmp; - } - num = TCOD_random_get_gaussian_double_range_custom (mersenne, (double)min, (double)max, (double)mean); - ret = (num >= 0.0 ? (int)(num + 0.5) : (int)(num - 0.5)); - return CLAMP(min,max,ret); -} - -/* Box-Muller, inverted distribution */ - -double TCOD_random_get_gaussian_double_inv (TCOD_random_t mersenne, double mean, double std_deviation) { - double num = TCOD_random_get_gaussian_double(mersenne,mean,std_deviation); - return (num >= mean ? num - (3 * std_deviation) : num + (3 * std_deviation)); -} - -float TCOD_random_get_gaussian_float_inv (TCOD_random_t mersenne, float mean, float std_deviation) { - double num = TCOD_random_get_gaussian_double(mersenne,(double)mean,(double)std_deviation); - return (num >= mean ? (float)(num - (3 * std_deviation)) : (float)(num + (3 * std_deviation))); -} - -int TCOD_random_get_gaussian_int_inv (TCOD_random_t mersenne, int mean, int std_deviation) { - double num = TCOD_random_get_gaussian_double(mersenne,(double)mean,(double)std_deviation); - int inum = (num >= 0.0 ? (int)(num + 0.5) : (int)(num - 0.5)); - return (num >= mean ? inum - (3 * std_deviation) : inum + (3 * std_deviation)); -} - -/* Box-Muller, ranges, inverted distribution */ - -double TCOD_random_get_gaussian_double_range_inv (TCOD_random_t mersenne, double min, double max) { - double mean, std_deviation, ret; - if (min > max) { - double tmp = max; - max = min; - min = tmp; - } - mean = (min + max) / 2.0; - std_deviation = (max - min) / 6.0; /* 6.0 is used because of the three-sigma rule */ - ret = TCOD_random_get_gaussian_double_inv(mersenne, mean, std_deviation); - return CLAMP(min,max,ret); -} - -float TCOD_random_get_gaussian_float_range_inv (TCOD_random_t mersenne, float min, float max) { - float ret = (float)TCOD_random_get_gaussian_double_range_inv(mersenne, (double)min, (double)max); - return CLAMP(min,max,ret); -} - -int TCOD_random_get_gaussian_int_range_inv (TCOD_random_t mersenne, int min, int max) { - double num = TCOD_random_get_gaussian_double_range_inv(mersenne, (double)min, (double)max); - int ret = (num >= 0.0 ? (int)(num + 0.5) : (int)(num - 0.5)); - return CLAMP(min,max,ret); -} - -/* Box-Muller, ranges with a custom mean, inverted distribution */ - -double TCOD_random_get_gaussian_double_range_custom_inv (TCOD_random_t mersenne, double min, double max, double mean) { - double d1, d2, std_deviation, ret; - if (min > max) { - double tmp = max; - max = min; - min = tmp; - } - d1 = max - mean; - d2 = mean - min; - std_deviation = MAX(d1,d2) / 3.0; - ret = TCOD_random_get_gaussian_double_inv(mersenne, mean, std_deviation); - return CLAMP(min,max,ret); -} - -float TCOD_random_get_gaussian_float_range_custom_inv (TCOD_random_t mersenne, float min, float max, float mean) { - float ret = (float)TCOD_random_get_gaussian_double_range_custom_inv(mersenne, (double)min, (double)max, (double)mean); - return CLAMP(min,max,ret); -} - -int TCOD_random_get_gaussian_int_range_custom_inv (TCOD_random_t mersenne, int min, int max, int mean) { - double num = TCOD_random_get_gaussian_double_range_custom_inv(mersenne, (double)min, (double)max, (double)mean); - int ret = (num >= 0.0 ? (int)(num + 0.5) : (int)(num - 0.5)); - return CLAMP(min,max,ret); -} - -void TCOD_random_set_distribution (TCOD_random_t mersenne, TCOD_distribution_t distribution) { - mersenne_data_t *r = NULL; - if (!mersenne) mersenne=TCOD_random_get_instance(); - r = (mersenne_data_t *)mersenne; - r->distribution = distribution; -} - -int TCOD_random_get_int (TCOD_random_t mersenne, int min, int max) { - if (!mersenne) mersenne=TCOD_random_get_instance(); - switch (((mersenne_data_t *)mersenne)->distribution) { - case TCOD_DISTRIBUTION_LINEAR: return TCOD_random_get_i(mersenne, min, max); break; - case TCOD_DISTRIBUTION_GAUSSIAN: return TCOD_random_get_gaussian_int(mersenne, min, max); break; - case TCOD_DISTRIBUTION_GAUSSIAN_INVERSE: return TCOD_random_get_gaussian_int_inv(mersenne, min, max); break; - case TCOD_DISTRIBUTION_GAUSSIAN_RANGE: return TCOD_random_get_gaussian_int_range(mersenne, min, max); break; - case TCOD_DISTRIBUTION_GAUSSIAN_RANGE_INVERSE: return TCOD_random_get_gaussian_int_range_inv(mersenne, min, max); break; - default: return TCOD_random_get_i(mersenne, min, max); break; - } -} - -float TCOD_random_get_float (TCOD_random_t mersenne, float min, float max) { - if (!mersenne) mersenne=TCOD_random_get_instance(); - switch (((mersenne_data_t *)mersenne)->distribution) { - case TCOD_DISTRIBUTION_LINEAR: return TCOD_random_get_f(mersenne, min, max); break; - case TCOD_DISTRIBUTION_GAUSSIAN: return TCOD_random_get_gaussian_float(mersenne, min, max); break; - case TCOD_DISTRIBUTION_GAUSSIAN_INVERSE: return TCOD_random_get_gaussian_float_inv(mersenne, min, max); break; - case TCOD_DISTRIBUTION_GAUSSIAN_RANGE: return TCOD_random_get_gaussian_float_range(mersenne, min, max); break; - case TCOD_DISTRIBUTION_GAUSSIAN_RANGE_INVERSE: return TCOD_random_get_gaussian_float_range_inv(mersenne, min, max); break; - default: return TCOD_random_get_f(mersenne, min, max); break; - } -} - -double TCOD_random_get_double (TCOD_random_t mersenne, double min, double max) { - if (!mersenne) mersenne=TCOD_random_get_instance(); - switch (((mersenne_data_t *)mersenne)->distribution) { - case TCOD_DISTRIBUTION_LINEAR: return TCOD_random_get_d(mersenne, min, max); break; - case TCOD_DISTRIBUTION_GAUSSIAN: return TCOD_random_get_gaussian_double(mersenne, min, max); break; - case TCOD_DISTRIBUTION_GAUSSIAN_INVERSE: return TCOD_random_get_gaussian_double_inv(mersenne, min, max); break; - case TCOD_DISTRIBUTION_GAUSSIAN_RANGE: return TCOD_random_get_gaussian_double_range(mersenne, min, max); break; - case TCOD_DISTRIBUTION_GAUSSIAN_RANGE_INVERSE: return TCOD_random_get_gaussian_double_range_inv(mersenne, min, max); break; - default: return TCOD_random_get_d(mersenne, min, max); break; - } -} - -int TCOD_random_get_int_mean (TCOD_random_t mersenne, int min, int max, int mean) { - if (!mersenne) mersenne=TCOD_random_get_instance(); - switch (((mersenne_data_t *)mersenne)->distribution) { - case TCOD_DISTRIBUTION_GAUSSIAN_INVERSE: - case TCOD_DISTRIBUTION_GAUSSIAN_RANGE_INVERSE: return TCOD_random_get_gaussian_int_range_custom_inv(mersenne, min, max, mean); break; - default: return TCOD_random_get_gaussian_int_range_custom(mersenne, min, max, mean); break; - } -} - -float TCOD_random_get_float_mean (TCOD_random_t mersenne, float min, float max, float mean) { - if (!mersenne) mersenne=TCOD_random_get_instance(); - switch (((mersenne_data_t *)mersenne)->distribution) { - case TCOD_DISTRIBUTION_GAUSSIAN_INVERSE: - case TCOD_DISTRIBUTION_GAUSSIAN_RANGE_INVERSE: return TCOD_random_get_gaussian_float_range_custom_inv(mersenne, min, max, mean); break; - default: return TCOD_random_get_gaussian_float_range_custom(mersenne, min, max, mean); break; - } -} - -double TCOD_random_get_double_mean (TCOD_random_t mersenne, double min, double max, double mean) { - if (!mersenne) mersenne=TCOD_random_get_instance(); - switch (((mersenne_data_t *)mersenne)->distribution) { - case TCOD_DISTRIBUTION_GAUSSIAN_INVERSE: - case TCOD_DISTRIBUTION_GAUSSIAN_RANGE_INVERSE: return TCOD_random_get_gaussian_double_range_custom_inv(mersenne, min, max, mean); break; - default: return TCOD_random_get_gaussian_double_range_custom(mersenne, min, max, mean); break; - } -} - -TCOD_dice_t TCOD_random_dice_new (const char * s) { - TCOD_dice_t d = { 1, 1, 1.0f, 0.0f }; - char * ptr = (char *)s; - char tmp[128]; - size_t l; - /* get multiplier */ - if ((l = strcspn(ptr,"*x")) < strlen(ptr)) { - strcpy(tmp,ptr); - tmp[l] = '\0'; - d.multiplier = (float)atof(tmp); - ptr += l + 1; - } - /* get rolls */ - l = strcspn(ptr,"dD"); - strcpy(tmp,ptr); - tmp[l] = '\0'; - d.nb_rolls = atoi(tmp); - ptr += l + 1; - /* get faces */ - l = strcspn(ptr,"-+"); - strcpy(tmp,ptr); - tmp[l] = '\0'; - d.nb_faces = atoi(tmp); - ptr += l; - /* get addsub */ - if (strlen(ptr) > 0) { - int sign = (*ptr == '+') ? 1 : (-1); - ptr++; - d.addsub = (float)(atof(ptr) * sign); - } - return d; -} - -int TCOD_random_dice_roll (TCOD_random_t mersenne, TCOD_dice_t dice) { - int rolls; - int result = 0; - for (rolls = 0; rolls < dice.nb_rolls; rolls++) - result += TCOD_random_get_i(mersenne,1,dice.nb_faces); - return (int)((result + dice.addsub) * dice.multiplier); -} - -int TCOD_random_dice_roll_s (TCOD_random_t mersenne, const char * s) { - return TCOD_random_dice_roll(mersenne,TCOD_random_dice_new(s)); -} +/* +* libtcod +* Copyright (c) 2008-2018 Jice & Mingos & rmtew +* All rights reserved. +* +* Redistribution and use in source and binary forms, with or without +* modification, are permitted provided that the following conditions are met: +* * Redistributions of source code must retain the above copyright +* notice, this list of conditions and the following disclaimer. +* * Redistributions in binary form must reproduce the above copyright +* notice, this list of conditions and the following disclaimer in the +* documentation and/or other materials provided with the distribution. +* * The name of Jice or Mingos may not be used to endorse or promote +* products derived from this software without specific prior written +* permission. +* +* THIS SOFTWARE IS PROVIDED BY JICE, MINGOS AND RMTEW ``AS IS'' AND ANY +* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED +* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE +* DISCLAIMED. IN NO EVENT SHALL JICE, MINGOS OR RMTEW BE LIABLE FOR ANY +* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES +* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; +* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND +* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS +* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +*/ +#include "mersenne.h" + +#include +#include +#include +#include + +#include "libtcod_int.h" +#include "utility.h" + +static TCOD_random_t instance=NULL; +static float rand_div=1.0f/(float)(0xffffffff); +static double rand_div_double = 1.0 / (double)(0xffffffff); + +/* initialize the mersenne twister array */ +static void mt_init(uint32_t seed, uint32_t mt[624] ) +{ + int i; + mt[0]= seed; + for (i=1; i<624; i++) { + mt[i] = (1812433253 * (mt[i-1] ^ (mt[i-1] >> 30)) + i); + } +} + +/* get the next random value from the mersenne twister array */ +static uint32_t mt_rand(uint32_t mt[624], int *cur_mt) +{ +#define MT_HIGH_BIT 0x80000000UL +#define MT_LOW_BITS 0x7fffffffUL + uint32_t y; + + if (*cur_mt == 624) { + /* our 624 sequence is finished. generate a new one */ + int i; + + for (i=0;i<623;i++) { + y = ( mt[i] & MT_HIGH_BIT ) | ( mt[i+1] & MT_LOW_BITS ); + if ( y & 1 ) { + /* odd y */ + mt[i] = mt[ (i + 397) % 624 ] ^ (y >> 1) ^ 2567483615UL; + } else { + /* even y */ + mt[i] = mt[ (i + 397) % 624 ] ^ (y >> 1); + } + } + y = ( mt[623] & MT_HIGH_BIT ) | ( mt[0] & MT_LOW_BITS ); + if ( y & 1 ) { + /* odd y */ + mt[623] = mt[396] ^ (y >> 1) ^ 2567483615UL; + } else { + mt[623] = mt[396] ^ (y >> 1); + } + + *cur_mt = 0; + } + + y = mt[(*cur_mt)++]; + y ^= (y >> 11); + y ^= (y << 7) & 2636928640UL; + y ^= (y << 15) & 4022730752UL; + y ^= (y >> 18); + return y; +} + +/* get a random float between 0 and 1 */ +static float frandom01(mersenne_data_t *r) { + return (float)mt_rand(r->mt,&r->cur_mt)*rand_div; +} + +/* string hashing function */ +/* not used (yet) +static uint32_t hash(const char *data,int len) { + uint32_t hash = 0; + uint32_t x; + int i; + for(i = 0; i < len; data++, i++) { + hash = (hash << 4) + (*data); + if((x = hash & 0xF0000000L) != 0) { + hash ^= (x >> 24); + hash &= ~x; + } + } + return (hash & 0x7FFFFFFF); +} +*/ + +/* get a random number from the CMWC */ +#define CMWC_GET_NUMBER(num) { unsigned long long t; uint32_t x; r->cur=(r->cur+1)&4095; t=18782LL*r->Q[r->cur]+r->c; r->c=(t>>32); x=(uint32_t)(t+r->c); if (x < r->c) { x++; r->c++; } if((x+1)==0) { r->c++; x=0; } num = (uint32_t)(r->Q[r->cur] = 0xfffffffe - x); } + +TCOD_random_t TCOD_random_new(TCOD_random_algo_t algo) { + return TCOD_random_new_from_seed(algo,(uint32_t)time(0)); +} + +TCOD_random_t TCOD_random_get_instance(void) { + if (! instance ) { + instance=TCOD_random_new(TCOD_RNG_CMWC); + } + return instance; +} + +TCOD_random_t TCOD_random_new_from_seed(TCOD_random_algo_t algo, uint32_t seed) { + mersenne_data_t *r = (mersenne_data_t *)calloc(sizeof(mersenne_data_t),1); + /* Mersenne Twister */ + if (algo == TCOD_RNG_MT) { + r->algo = TCOD_RNG_MT; + r->cur_mt=624; + mt_init(seed,r->mt); + } + /* Complementary-Multiply-With-Carry or Generalised Feedback Shift Register */ + else { + int i; + /* fill the Q array with pseudorandom seeds */ + uint32_t s = seed; + for (i = 0; i < 4096; i++) r->Q[i] = s = (s * 1103515245) + 12345; /* glibc LCG */ + r->c = ((s * 1103515245) + 12345) % 809430660; /* this max value is recommended by George Marsaglia */ + r->cur = 0; + r->algo = TCOD_RNG_CMWC; + } + r->distribution = TCOD_DISTRIBUTION_LINEAR; + return (TCOD_random_t)r; +} + + +int TCOD_random_get_i(TCOD_random_t mersenne, int min, int max) { + mersenne_data_t *r; + int delta; + if (max==min) return min; + else if (max < min) { + int tmp=max; + max=min; + min=tmp; + } + if (!mersenne) mersenne=TCOD_random_get_instance(); + r=(mersenne_data_t *)mersenne; + delta = max - min + 1; + /* return a number from the Mersenne Twister */ + if (r->algo == TCOD_RNG_MT) return ( mt_rand(r->mt,&r->cur_mt) % delta ) + min; + /* or from the CMWC */ + else { + uint32_t number; + CMWC_GET_NUMBER(number) + return number % delta + min; + } +} + +float TCOD_random_get_f(TCOD_random_t mersenne,float min, float max) { + mersenne_data_t *r; + float delta,f; + if (max==min) return min; + else if (max < min) { + float tmp=max; + max=min; + min=tmp; + } + if (!mersenne) mersenne=TCOD_random_get_instance(); + r=(mersenne_data_t *)mersenne; + delta = max - min; + /* Mersenne Twister */ + if (r->algo == TCOD_RNG_MT) f = delta * frandom01(r); + /* CMWC */ + else { + uint32_t number; + CMWC_GET_NUMBER(number) + f = (float)(number) * rand_div * delta; + } + return min + f; +} + +double TCOD_random_get_d(TCOD_random_t mersenne, double min, double max) { + mersenne_data_t *r; + double delta,f; + if (max==min) return min; + else if (max < min) { + double tmp=max; + max=min; + min=tmp; + } + if (!mersenne) mersenne=TCOD_random_get_instance(); + r=(mersenne_data_t *)mersenne; + delta = max - min; + /* Mersenne Twister */ + if (r->algo == TCOD_RNG_MT) f = delta * (double)frandom01(r); + /* CMWC */ + else { + uint32_t number; + CMWC_GET_NUMBER(number) + f = (double)(number) * rand_div_double * delta; + } + return min + f; +} + +void TCOD_random_delete(TCOD_random_t mersenne) { + TCOD_IFNOT(mersenne != NULL) return; + if ( mersenne == instance ) instance = NULL; + free(mersenne); +} +TCOD_random_t TCOD_random_save(TCOD_random_t mersenne) { + mersenne_data_t *ret=(mersenne_data_t *)malloc(sizeof(mersenne_data_t)); + if (!mersenne) mersenne=TCOD_random_get_instance(); + memcpy(ret,mersenne,sizeof(mersenne_data_t)); + return (TCOD_random_t)ret; +} + +void TCOD_random_restore(TCOD_random_t mersenne, TCOD_random_t backup) { + if (!mersenne) mersenne=TCOD_random_get_instance(); + memcpy(mersenne,backup,sizeof(mersenne_data_t)); +} + +/* Box-Muller transform (Gaussian distribution) */ + +double TCOD_random_get_gaussian_double (TCOD_random_t mersenne, double mean, double std_deviation) { + double x1, x2, w, y1; + static double y2; + static bool again = false; + double ret; + if (again) + ret = mean + y2 * std_deviation; + else { + mersenne_data_t *r = NULL; + if (!mersenne) mersenne=TCOD_random_get_instance(); + r = (mersenne_data_t *)mersenne; + /* MT */ + if (r->algo == TCOD_RNG_MT) { + do { + x1 = frandom01(r) * 2.0 - 1.0; + x2 = frandom01(r) * 2.0 - 1.0; + w = x1 * x1 + x2 * x2; + } while (w >= 1.0); + } + /* CMWC */ + else { + uint32_t number; + do { + CMWC_GET_NUMBER(number) + x1 = number * rand_div_double * 2.0 - 1.0; + CMWC_GET_NUMBER(number) + x2 = number * rand_div_double * 2.0 - 1.0; + w = x1 * x1 + x2 * x2; + } while (w >= 1.0); + } + w = sqrt((-2.0 * log(w)) / w); + y1 = x1 * w; + y2 = x2 * w; + ret = mean + y1 * std_deviation; + } + again = !again; + return ret; +} + +float TCOD_random_get_gaussian_float (TCOD_random_t mersenne, float mean, float std_deviation) { + return (float)TCOD_random_get_gaussian_double(mersenne, (double)mean, (double)std_deviation); +} + +int TCOD_random_get_gaussian_int (TCOD_random_t mersenne, int mean, int std_deviation) { + double num = TCOD_random_get_gaussian_double(mersenne,(double)mean,(double)std_deviation); + return (num >= 0.0 ? (int)(num + 0.5) : (int)(num - 0.5)); +} + +/* Box-Muller, ranges */ + +double TCOD_random_get_gaussian_double_range (TCOD_random_t mersenne, double min, double max) { + double mean, std_deviation, ret; + if (min > max) { + double tmp = max; + max = min; + min = tmp; + } + mean = (min + max) / 2; + std_deviation = (max - min) / 6.0; /* 6.0 is used because of the three-sigma rule */ + ret = TCOD_random_get_gaussian_double(mersenne, mean, std_deviation); + return CLAMP(min,max,ret); +} + +float TCOD_random_get_gaussian_float_range (TCOD_random_t mersenne, float min, float max) { + if (min > max) { + float tmp = max; + max = min; + min = tmp; + } + return (float)TCOD_random_get_gaussian_double_range (mersenne, (double)min, (double)max); +} + +int TCOD_random_get_gaussian_int_range (TCOD_random_t mersenne, int min, int max) { + double num; + int ret; + if (min > max) { + int tmp = max; + max = min; + min = tmp; + } + num = TCOD_random_get_gaussian_double_range (mersenne, (double)min, (double)max); + ret = (num >= 0.0 ? (int)(num + 0.5) : (int)(num - 0.5)); + return CLAMP(min,max,ret); +} + +/* Box-Muller, ranges with a custom mean */ + +double TCOD_random_get_gaussian_double_range_custom (TCOD_random_t mersenne, double min, double max, double mean) { + double d1, d2, std_deviation, ret; + if (min > max) { + double tmp = max; + max = min; + min = tmp; + } + d1 = max - mean; + d2 = mean - min; + std_deviation = MAX(d1,d2) / 3.0; + ret = TCOD_random_get_gaussian_double(mersenne, mean, std_deviation); + return CLAMP(min,max,ret); +} + +float TCOD_random_get_gaussian_float_range_custom (TCOD_random_t mersenne, float min, float max, float mean) { + if (min > max) { + float tmp = max; + max = min; + min = tmp; + } + return (float)TCOD_random_get_gaussian_double_range_custom (mersenne, (double)min, (double)max, (double)mean); +} + +int TCOD_random_get_gaussian_int_range_custom (TCOD_random_t mersenne, int min, int max, int mean) { + double num; + int ret; + if (min > max) { + int tmp = max; + max = min; + min = tmp; + } + num = TCOD_random_get_gaussian_double_range_custom (mersenne, (double)min, (double)max, (double)mean); + ret = (num >= 0.0 ? (int)(num + 0.5) : (int)(num - 0.5)); + return CLAMP(min,max,ret); +} + +/* Box-Muller, inverted distribution */ + +double TCOD_random_get_gaussian_double_inv (TCOD_random_t mersenne, double mean, double std_deviation) { + double num = TCOD_random_get_gaussian_double(mersenne,mean,std_deviation); + return (num >= mean ? num - (3 * std_deviation) : num + (3 * std_deviation)); +} + +float TCOD_random_get_gaussian_float_inv (TCOD_random_t mersenne, float mean, float std_deviation) { + double num = TCOD_random_get_gaussian_double(mersenne,(double)mean,(double)std_deviation); + return (num >= mean ? (float)(num - (3 * std_deviation)) : (float)(num + (3 * std_deviation))); +} + +int TCOD_random_get_gaussian_int_inv (TCOD_random_t mersenne, int mean, int std_deviation) { + double num = TCOD_random_get_gaussian_double(mersenne,(double)mean,(double)std_deviation); + int inum = (num >= 0.0 ? (int)(num + 0.5) : (int)(num - 0.5)); + return (num >= mean ? inum - (3 * std_deviation) : inum + (3 * std_deviation)); +} + +/* Box-Muller, ranges, inverted distribution */ + +double TCOD_random_get_gaussian_double_range_inv (TCOD_random_t mersenne, double min, double max) { + double mean, std_deviation, ret; + if (min > max) { + double tmp = max; + max = min; + min = tmp; + } + mean = (min + max) / 2.0; + std_deviation = (max - min) / 6.0; /* 6.0 is used because of the three-sigma rule */ + ret = TCOD_random_get_gaussian_double_inv(mersenne, mean, std_deviation); + return CLAMP(min,max,ret); +} + +float TCOD_random_get_gaussian_float_range_inv (TCOD_random_t mersenne, float min, float max) { + float ret = (float)TCOD_random_get_gaussian_double_range_inv(mersenne, (double)min, (double)max); + return CLAMP(min,max,ret); +} + +int TCOD_random_get_gaussian_int_range_inv (TCOD_random_t mersenne, int min, int max) { + double num = TCOD_random_get_gaussian_double_range_inv(mersenne, (double)min, (double)max); + int ret = (num >= 0.0 ? (int)(num + 0.5) : (int)(num - 0.5)); + return CLAMP(min,max,ret); +} + +/* Box-Muller, ranges with a custom mean, inverted distribution */ + +double TCOD_random_get_gaussian_double_range_custom_inv (TCOD_random_t mersenne, double min, double max, double mean) { + double d1, d2, std_deviation, ret; + if (min > max) { + double tmp = max; + max = min; + min = tmp; + } + d1 = max - mean; + d2 = mean - min; + std_deviation = MAX(d1,d2) / 3.0; + ret = TCOD_random_get_gaussian_double_inv(mersenne, mean, std_deviation); + return CLAMP(min,max,ret); +} + +float TCOD_random_get_gaussian_float_range_custom_inv (TCOD_random_t mersenne, float min, float max, float mean) { + float ret = (float)TCOD_random_get_gaussian_double_range_custom_inv(mersenne, (double)min, (double)max, (double)mean); + return CLAMP(min,max,ret); +} + +int TCOD_random_get_gaussian_int_range_custom_inv (TCOD_random_t mersenne, int min, int max, int mean) { + double num = TCOD_random_get_gaussian_double_range_custom_inv(mersenne, (double)min, (double)max, (double)mean); + int ret = (num >= 0.0 ? (int)(num + 0.5) : (int)(num - 0.5)); + return CLAMP(min,max,ret); +} + +void TCOD_random_set_distribution (TCOD_random_t mersenne, TCOD_distribution_t distribution) { + mersenne_data_t *r = NULL; + if (!mersenne) mersenne=TCOD_random_get_instance(); + r = (mersenne_data_t *)mersenne; + r->distribution = distribution; +} + +int TCOD_random_get_int (TCOD_random_t mersenne, int min, int max) { + if (!mersenne) mersenne=TCOD_random_get_instance(); + switch (((mersenne_data_t *)mersenne)->distribution) { + case TCOD_DISTRIBUTION_LINEAR: return TCOD_random_get_i(mersenne, min, max); break; + case TCOD_DISTRIBUTION_GAUSSIAN: return TCOD_random_get_gaussian_int(mersenne, min, max); break; + case TCOD_DISTRIBUTION_GAUSSIAN_INVERSE: return TCOD_random_get_gaussian_int_inv(mersenne, min, max); break; + case TCOD_DISTRIBUTION_GAUSSIAN_RANGE: return TCOD_random_get_gaussian_int_range(mersenne, min, max); break; + case TCOD_DISTRIBUTION_GAUSSIAN_RANGE_INVERSE: return TCOD_random_get_gaussian_int_range_inv(mersenne, min, max); break; + default: return TCOD_random_get_i(mersenne, min, max); break; + } +} + +float TCOD_random_get_float (TCOD_random_t mersenne, float min, float max) { + if (!mersenne) mersenne=TCOD_random_get_instance(); + switch (((mersenne_data_t *)mersenne)->distribution) { + case TCOD_DISTRIBUTION_LINEAR: return TCOD_random_get_f(mersenne, min, max); break; + case TCOD_DISTRIBUTION_GAUSSIAN: return TCOD_random_get_gaussian_float(mersenne, min, max); break; + case TCOD_DISTRIBUTION_GAUSSIAN_INVERSE: return TCOD_random_get_gaussian_float_inv(mersenne, min, max); break; + case TCOD_DISTRIBUTION_GAUSSIAN_RANGE: return TCOD_random_get_gaussian_float_range(mersenne, min, max); break; + case TCOD_DISTRIBUTION_GAUSSIAN_RANGE_INVERSE: return TCOD_random_get_gaussian_float_range_inv(mersenne, min, max); break; + default: return TCOD_random_get_f(mersenne, min, max); break; + } +} + +double TCOD_random_get_double (TCOD_random_t mersenne, double min, double max) { + if (!mersenne) mersenne=TCOD_random_get_instance(); + switch (((mersenne_data_t *)mersenne)->distribution) { + case TCOD_DISTRIBUTION_LINEAR: return TCOD_random_get_d(mersenne, min, max); break; + case TCOD_DISTRIBUTION_GAUSSIAN: return TCOD_random_get_gaussian_double(mersenne, min, max); break; + case TCOD_DISTRIBUTION_GAUSSIAN_INVERSE: return TCOD_random_get_gaussian_double_inv(mersenne, min, max); break; + case TCOD_DISTRIBUTION_GAUSSIAN_RANGE: return TCOD_random_get_gaussian_double_range(mersenne, min, max); break; + case TCOD_DISTRIBUTION_GAUSSIAN_RANGE_INVERSE: return TCOD_random_get_gaussian_double_range_inv(mersenne, min, max); break; + default: return TCOD_random_get_d(mersenne, min, max); break; + } +} + +int TCOD_random_get_int_mean (TCOD_random_t mersenne, int min, int max, int mean) { + if (!mersenne) mersenne=TCOD_random_get_instance(); + switch (((mersenne_data_t *)mersenne)->distribution) { + case TCOD_DISTRIBUTION_GAUSSIAN_INVERSE: + case TCOD_DISTRIBUTION_GAUSSIAN_RANGE_INVERSE: return TCOD_random_get_gaussian_int_range_custom_inv(mersenne, min, max, mean); break; + default: return TCOD_random_get_gaussian_int_range_custom(mersenne, min, max, mean); break; + } +} + +float TCOD_random_get_float_mean (TCOD_random_t mersenne, float min, float max, float mean) { + if (!mersenne) mersenne=TCOD_random_get_instance(); + switch (((mersenne_data_t *)mersenne)->distribution) { + case TCOD_DISTRIBUTION_GAUSSIAN_INVERSE: + case TCOD_DISTRIBUTION_GAUSSIAN_RANGE_INVERSE: return TCOD_random_get_gaussian_float_range_custom_inv(mersenne, min, max, mean); break; + default: return TCOD_random_get_gaussian_float_range_custom(mersenne, min, max, mean); break; + } +} + +double TCOD_random_get_double_mean (TCOD_random_t mersenne, double min, double max, double mean) { + if (!mersenne) mersenne=TCOD_random_get_instance(); + switch (((mersenne_data_t *)mersenne)->distribution) { + case TCOD_DISTRIBUTION_GAUSSIAN_INVERSE: + case TCOD_DISTRIBUTION_GAUSSIAN_RANGE_INVERSE: return TCOD_random_get_gaussian_double_range_custom_inv(mersenne, min, max, mean); break; + default: return TCOD_random_get_gaussian_double_range_custom(mersenne, min, max, mean); break; + } +} + +TCOD_dice_t TCOD_random_dice_new (const char * s) { + TCOD_dice_t d = { 1, 1, 1.0f, 0.0f }; + char * ptr = (char *)s; + char tmp[128]; + size_t l; + /* get multiplier */ + if ((l = strcspn(ptr,"*x")) < strlen(ptr)) { + strcpy(tmp,ptr); + tmp[l] = '\0'; + d.multiplier = (float)atof(tmp); + ptr += l + 1; + } + /* get rolls */ + l = strcspn(ptr,"dD"); + strcpy(tmp,ptr); + tmp[l] = '\0'; + d.nb_rolls = atoi(tmp); + ptr += l + 1; + /* get faces */ + l = strcspn(ptr,"-+"); + strcpy(tmp,ptr); + tmp[l] = '\0'; + d.nb_faces = atoi(tmp); + ptr += l; + /* get addsub */ + if (strlen(ptr) > 0) { + int sign = (*ptr == '+') ? 1 : (-1); + ptr++; + d.addsub = (float)(atof(ptr) * sign); + } + return d; +} + +int TCOD_random_dice_roll (TCOD_random_t mersenne, TCOD_dice_t dice) { + int rolls; + int result = 0; + for (rolls = 0; rolls < dice.nb_rolls; rolls++) + result += TCOD_random_get_i(mersenne,1,dice.nb_faces); + return (int)((result + dice.addsub) * dice.multiplier); +} + +int TCOD_random_dice_roll_s (TCOD_random_t mersenne, const char * s) { + return TCOD_random_dice_roll(mersenne,TCOD_random_dice_new(s)); +} diff --git a/tcod_sys/libtcod/include/mersenne_types.h b/tcod_sys/libtcod/src/libtcod/mersenne_types.h similarity index 96% rename from tcod_sys/libtcod/include/mersenne_types.h rename to tcod_sys/libtcod/src/libtcod/mersenne_types.h index 2d62d5420..66cb43690 100644 --- a/tcod_sys/libtcod/include/mersenne_types.h +++ b/tcod_sys/libtcod/src/libtcod/mersenne_types.h @@ -1,54 +1,54 @@ -/* -* libtcod -* Copyright (c) 2008-2018 Jice & Mingos & rmtew -* All rights reserved. -* -* Redistribution and use in source and binary forms, with or without -* modification, are permitted provided that the following conditions are met: -* * Redistributions of source code must retain the above copyright -* notice, this list of conditions and the following disclaimer. -* * Redistributions in binary form must reproduce the above copyright -* notice, this list of conditions and the following disclaimer in the -* documentation and/or other materials provided with the distribution. -* * The name of Jice or Mingos may not be used to endorse or promote -* products derived from this software without specific prior written -* permission. -* -* THIS SOFTWARE IS PROVIDED BY JICE, MINGOS AND RMTEW ``AS IS'' AND ANY -* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED -* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE -* DISCLAIMED. IN NO EVENT SHALL JICE, MINGOS OR RMTEW BE LIABLE FOR ANY -* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES -* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; -* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND -* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS -* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. -*/ -#ifndef _TCOD_RANDOM_TYPES_H -#define _TCOD_RANDOM_TYPES_H - -typedef void *TCOD_random_t; - -/* dice roll */ -typedef struct { - int nb_rolls; - int nb_faces; - float multiplier; - float addsub; -} TCOD_dice_t; - -/* PRNG algorithms */ -typedef enum { - TCOD_RNG_MT, - TCOD_RNG_CMWC -} TCOD_random_algo_t; - -typedef enum { - TCOD_DISTRIBUTION_LINEAR, - TCOD_DISTRIBUTION_GAUSSIAN, - TCOD_DISTRIBUTION_GAUSSIAN_RANGE, - TCOD_DISTRIBUTION_GAUSSIAN_INVERSE, - TCOD_DISTRIBUTION_GAUSSIAN_RANGE_INVERSE -} TCOD_distribution_t; -#endif /* _TCOD_RANDOM_TYPES_H */ +/* +* libtcod +* Copyright (c) 2008-2018 Jice & Mingos & rmtew +* All rights reserved. +* +* Redistribution and use in source and binary forms, with or without +* modification, are permitted provided that the following conditions are met: +* * Redistributions of source code must retain the above copyright +* notice, this list of conditions and the following disclaimer. +* * Redistributions in binary form must reproduce the above copyright +* notice, this list of conditions and the following disclaimer in the +* documentation and/or other materials provided with the distribution. +* * The name of Jice or Mingos may not be used to endorse or promote +* products derived from this software without specific prior written +* permission. +* +* THIS SOFTWARE IS PROVIDED BY JICE, MINGOS AND RMTEW ``AS IS'' AND ANY +* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED +* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE +* DISCLAIMED. IN NO EVENT SHALL JICE, MINGOS OR RMTEW BE LIABLE FOR ANY +* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES +* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; +* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND +* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS +* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +*/ +#ifndef _TCOD_RANDOM_TYPES_H +#define _TCOD_RANDOM_TYPES_H +struct TCOD_Random; +typedef struct TCOD_Random *TCOD_random_t; + +/* dice roll */ +typedef struct { + int nb_rolls; + int nb_faces; + float multiplier; + float addsub; +} TCOD_dice_t; + +/* PRNG algorithms */ +typedef enum { + TCOD_RNG_MT, + TCOD_RNG_CMWC +} TCOD_random_algo_t; + +typedef enum { + TCOD_DISTRIBUTION_LINEAR, + TCOD_DISTRIBUTION_GAUSSIAN, + TCOD_DISTRIBUTION_GAUSSIAN_RANGE, + TCOD_DISTRIBUTION_GAUSSIAN_INVERSE, + TCOD_DISTRIBUTION_GAUSSIAN_RANGE_INVERSE +} TCOD_distribution_t; +#endif /* _TCOD_RANDOM_TYPES_H */ diff --git a/tcod_sys/libtcod/src/mouse.cpp b/tcod_sys/libtcod/src/libtcod/mouse.cpp similarity index 96% rename from tcod_sys/libtcod/src/mouse.cpp rename to tcod_sys/libtcod/src/libtcod/mouse.cpp index b131f87d6..af33c3c78 100644 --- a/tcod_sys/libtcod/src/mouse.cpp +++ b/tcod_sys/libtcod/src/libtcod/mouse.cpp @@ -1,48 +1,48 @@ -/* -* libtcod -* Copyright (c) 2008-2018 Jice & Mingos & rmtew -* All rights reserved. -* -* Redistribution and use in source and binary forms, with or without -* modification, are permitted provided that the following conditions are met: -* * Redistributions of source code must retain the above copyright -* notice, this list of conditions and the following disclaimer. -* * Redistributions in binary form must reproduce the above copyright -* notice, this list of conditions and the following disclaimer in the -* documentation and/or other materials provided with the distribution. -* * The name of Jice or Mingos may not be used to endorse or promote -* products derived from this software without specific prior written -* permission. -* -* THIS SOFTWARE IS PROVIDED BY JICE, MINGOS AND RMTEW ``AS IS'' AND ANY -* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED -* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE -* DISCLAIMED. IN NO EVENT SHALL JICE, MINGOS OR RMTEW BE LIABLE FOR ANY -* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES -* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; -* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND -* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS -* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. -*/ -#include - -#ifdef TCOD_CONSOLE_SUPPORT - -void TCODMouse::showCursor(bool visible) { - TCOD_mouse_show_cursor(visible); -} - -bool TCODMouse::isCursorVisible() { - return TCOD_mouse_is_cursor_visible() != 0; -} - -void TCODMouse::move(int x, int y) { - TCOD_mouse_move(x,y); -} - -TCOD_mouse_t TCODMouse::getStatus() { - return TCOD_mouse_get_status(); -} - -#endif +/* +* libtcod +* Copyright (c) 2008-2018 Jice & Mingos & rmtew +* All rights reserved. +* +* Redistribution and use in source and binary forms, with or without +* modification, are permitted provided that the following conditions are met: +* * Redistributions of source code must retain the above copyright +* notice, this list of conditions and the following disclaimer. +* * Redistributions in binary form must reproduce the above copyright +* notice, this list of conditions and the following disclaimer in the +* documentation and/or other materials provided with the distribution. +* * The name of Jice or Mingos may not be used to endorse or promote +* products derived from this software without specific prior written +* permission. +* +* THIS SOFTWARE IS PROVIDED BY JICE, MINGOS AND RMTEW ``AS IS'' AND ANY +* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED +* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE +* DISCLAIMED. IN NO EVENT SHALL JICE, MINGOS OR RMTEW BE LIABLE FOR ANY +* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES +* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; +* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND +* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS +* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +*/ +#include "mouse.hpp" + +#ifdef TCOD_CONSOLE_SUPPORT + +void TCODMouse::showCursor(bool visible) { + TCOD_mouse_show_cursor(visible); +} + +bool TCODMouse::isCursorVisible() { + return TCOD_mouse_is_cursor_visible() != 0; +} + +void TCODMouse::move(int x, int y) { + TCOD_mouse_move(x,y); +} + +TCOD_mouse_t TCODMouse::getStatus() { + return TCOD_mouse_get_status(); +} + +#endif diff --git a/tcod_sys/libtcod/include/mouse.h b/tcod_sys/libtcod/src/libtcod/mouse.h similarity index 98% rename from tcod_sys/libtcod/include/mouse.h rename to tcod_sys/libtcod/src/libtcod/mouse.h index 0cad0e22a..223080ae9 100644 --- a/tcod_sys/libtcod/include/mouse.h +++ b/tcod_sys/libtcod/src/libtcod/mouse.h @@ -28,7 +28,7 @@ #ifndef _TCOD_MOUSE_H #define _TCOD_MOUSE_H -#include "libtcod_portability.h" +#include "portability.h" #ifdef TCOD_CONSOLE_SUPPORT diff --git a/tcod_sys/libtcod/include/mouse.hpp b/tcod_sys/libtcod/src/libtcod/mouse.hpp similarity index 100% rename from tcod_sys/libtcod/include/mouse.hpp rename to tcod_sys/libtcod/src/libtcod/mouse.hpp diff --git a/tcod_sys/libtcod/include/mouse_types.h b/tcod_sys/libtcod/src/libtcod/mouse_types.h similarity index 93% rename from tcod_sys/libtcod/include/mouse_types.h rename to tcod_sys/libtcod/src/libtcod/mouse_types.h index c48ac429e..fa3a425b5 100644 --- a/tcod_sys/libtcod/include/mouse_types.h +++ b/tcod_sys/libtcod/src/libtcod/mouse_types.h @@ -1,54 +1,47 @@ -/* -* libtcod -* Copyright (c) 2008-2018 Jice & Mingos & rmtew -* All rights reserved. -* -* Redistribution and use in source and binary forms, with or without -* modification, are permitted provided that the following conditions are met: -* * Redistributions of source code must retain the above copyright -* notice, this list of conditions and the following disclaimer. -* * Redistributions in binary form must reproduce the above copyright -* notice, this list of conditions and the following disclaimer in the -* documentation and/or other materials provided with the distribution. -* * The name of Jice or Mingos may not be used to endorse or promote -* products derived from this software without specific prior written -* permission. -* -* THIS SOFTWARE IS PROVIDED BY JICE, MINGOS AND RMTEW ``AS IS'' AND ANY -* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED -* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE -* DISCLAIMED. IN NO EVENT SHALL JICE, MINGOS OR RMTEW BE LIABLE FOR ANY -* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES -* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; -* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND -* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS -* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. -*/ -#ifndef _TCOD_MOUSE_TYPES_H -#define _TCOD_MOUSE_TYPES_H - -#include "libtcod_portability.h" - -#ifdef __cplusplus -extern "C" { -#endif -/* mouse data */ -typedef struct { - int x,y; /* absolute position */ - int dx,dy; /* movement since last update in pixels */ - int cx,cy; /* cell coordinates in the root console */ - int dcx,dcy; /* movement since last update in console cells */ - bool lbutton ; /* left button status */ - bool rbutton ; /* right button status */ - bool mbutton ; /* middle button status */ - bool lbutton_pressed ; /* left button pressed event */ - bool rbutton_pressed ; /* right button pressed event */ - bool mbutton_pressed ; /* middle button pressed event */ - bool wheel_up ; /* wheel up event */ - bool wheel_down ; /* wheel down event */ -} TCOD_mouse_t; -#ifdef __cplusplus -} -#endif -#endif /* _TCOD_MOUSE_TYPES_H */ +/* +* libtcod +* Copyright (c) 2008-2018 Jice & Mingos & rmtew +* All rights reserved. +* +* Redistribution and use in source and binary forms, with or without +* modification, are permitted provided that the following conditions are met: +* * Redistributions of source code must retain the above copyright +* notice, this list of conditions and the following disclaimer. +* * Redistributions in binary form must reproduce the above copyright +* notice, this list of conditions and the following disclaimer in the +* documentation and/or other materials provided with the distribution. +* * The name of Jice or Mingos may not be used to endorse or promote +* products derived from this software without specific prior written +* permission. +* +* THIS SOFTWARE IS PROVIDED BY JICE, MINGOS AND RMTEW ``AS IS'' AND ANY +* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED +* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE +* DISCLAIMED. IN NO EVENT SHALL JICE, MINGOS OR RMTEW BE LIABLE FOR ANY +* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES +* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; +* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND +* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS +* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +*/ +#ifndef _TCOD_MOUSE_TYPES_H +#define _TCOD_MOUSE_TYPES_H + +#include "portability.h" +/* mouse data */ +typedef struct { + int x,y; /* absolute position */ + int dx,dy; /* movement since last update in pixels */ + int cx,cy; /* cell coordinates in the root console */ + int dcx,dcy; /* movement since last update in console cells */ + bool lbutton ; /* left button status */ + bool rbutton ; /* right button status */ + bool mbutton ; /* middle button status */ + bool lbutton_pressed ; /* left button pressed event */ + bool rbutton_pressed ; /* right button pressed event */ + bool mbutton_pressed ; /* middle button pressed event */ + bool wheel_up ; /* wheel up event */ + bool wheel_down ; /* wheel down event */ +} TCOD_mouse_t; +#endif /* _TCOD_MOUSE_TYPES_H */ diff --git a/tcod_sys/libtcod/src/namegen.cpp b/tcod_sys/libtcod/src/libtcod/namegen.cpp similarity index 96% rename from tcod_sys/libtcod/src/namegen.cpp rename to tcod_sys/libtcod/src/libtcod/namegen.cpp index 55fab1f56..4d405dfe4 100644 --- a/tcod_sys/libtcod/src/namegen.cpp +++ b/tcod_sys/libtcod/src/libtcod/namegen.cpp @@ -1,52 +1,52 @@ -/* -* libtcod -* Copyright (c) 2008-2018 Jice & Mingos & rmtew -* All rights reserved. -* -* Redistribution and use in source and binary forms, with or without -* modification, are permitted provided that the following conditions are met: -* * Redistributions of source code must retain the above copyright -* notice, this list of conditions and the following disclaimer. -* * Redistributions in binary form must reproduce the above copyright -* notice, this list of conditions and the following disclaimer in the -* documentation and/or other materials provided with the distribution. -* * The name of Jice or Mingos may not be used to endorse or promote -* products derived from this software without specific prior written -* permission. -* -* THIS SOFTWARE IS PROVIDED BY JICE, MINGOS AND RMTEW ``AS IS'' AND ANY -* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED -* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE -* DISCLAIMED. IN NO EVENT SHALL JICE, MINGOS OR RMTEW BE LIABLE FOR ANY -* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES -* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; -* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND -* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS -* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. -*/ -/* -* Mingos' NameGen -* This file was written by Dominik "Mingos" Marczuk. -*/ -#include - -void TCODNamegen::parse (const char * filename, TCODRandom * random) { - TCOD_namegen_parse (filename, random ? random->data : NULL); -} - -char * TCODNamegen::generate (char * name, bool allocate) { - return TCOD_namegen_generate (name, allocate); -} - -char * TCODNamegen::generateCustom (char * name, char * rule, bool allocate) { - return TCOD_namegen_generate_custom (name, rule, allocate); -} - -TCOD_list_t TCODNamegen::getSets (void) { - return TCOD_namegen_get_sets (); -} - -void TCODNamegen::destroy (void) { - TCOD_namegen_destroy (); -} +/* +* libtcod +* Copyright (c) 2008-2018 Jice & Mingos & rmtew +* All rights reserved. +* +* Redistribution and use in source and binary forms, with or without +* modification, are permitted provided that the following conditions are met: +* * Redistributions of source code must retain the above copyright +* notice, this list of conditions and the following disclaimer. +* * Redistributions in binary form must reproduce the above copyright +* notice, this list of conditions and the following disclaimer in the +* documentation and/or other materials provided with the distribution. +* * The name of Jice or Mingos may not be used to endorse or promote +* products derived from this software without specific prior written +* permission. +* +* THIS SOFTWARE IS PROVIDED BY JICE, MINGOS AND RMTEW ``AS IS'' AND ANY +* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED +* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE +* DISCLAIMED. IN NO EVENT SHALL JICE, MINGOS OR RMTEW BE LIABLE FOR ANY +* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES +* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; +* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND +* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS +* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +*/ +/* +* Mingos' NameGen +* This file was written by Dominik "Mingos" Marczuk. +*/ +#include "namegen.hpp" + +void TCODNamegen::parse (const char * filename, TCODRandom * random) { + TCOD_namegen_parse (filename, random ? random->data : NULL); +} + +char * TCODNamegen::generate (char * name, bool allocate) { + return TCOD_namegen_generate (name, allocate); +} + +char * TCODNamegen::generateCustom (char * name, char * rule, bool allocate) { + return TCOD_namegen_generate_custom (name, rule, allocate); +} + +TCOD_list_t TCODNamegen::getSets (void) { + return TCOD_namegen_get_sets (); +} + +void TCODNamegen::destroy (void) { + TCOD_namegen_destroy (); +} diff --git a/tcod_sys/libtcod/include/namegen.h b/tcod_sys/libtcod/src/libtcod/namegen.h similarity index 94% rename from tcod_sys/libtcod/include/namegen.h rename to tcod_sys/libtcod/src/libtcod/namegen.h index 6783a0094..8b7463f75 100644 --- a/tcod_sys/libtcod/include/namegen.h +++ b/tcod_sys/libtcod/src/libtcod/namegen.h @@ -1,59 +1,60 @@ -/* -* libtcod -* Copyright (c) 2008-2018 Jice & Mingos & rmtew -* All rights reserved. -* -* Redistribution and use in source and binary forms, with or without -* modification, are permitted provided that the following conditions are met: -* * Redistributions of source code must retain the above copyright -* notice, this list of conditions and the following disclaimer. -* * Redistributions in binary form must reproduce the above copyright -* notice, this list of conditions and the following disclaimer in the -* documentation and/or other materials provided with the distribution. -* * The name of Jice or Mingos may not be used to endorse or promote -* products derived from this software without specific prior written -* permission. -* -* THIS SOFTWARE IS PROVIDED BY JICE, MINGOS AND RMTEW ``AS IS'' AND ANY -* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED -* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE -* DISCLAIMED. IN NO EVENT SHALL JICE, MINGOS OR RMTEW BE LIABLE FOR ANY -* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES -* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; -* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND -* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS -* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. -*/ -/* -* Mingos' NameGen -* This file was written by Dominik "Mingos" Marczuk. -*/ - -#ifndef _TCOD_NAMEGEN_H -#define _TCOD_NAMEGEN_H - -#include "libtcod_portability.h" -#include "list.h" -#include "mersenne.h" - -#ifdef __cplusplus -extern "C" { -#endif -/* the generator typedef */ -typedef void * TCOD_namegen_t; - -/* parse a file with syllable sets */ -TCODLIB_API void TCOD_namegen_parse (const char * filename, TCOD_random_t random); -/* generate a name */ -TCODLIB_API char * TCOD_namegen_generate (char * name, bool allocate); -/* generate a name using a custom generation rule */ -TCODLIB_API char * TCOD_namegen_generate_custom (char * name, char * rule, bool allocate); -/* retrieve the list of all available syllable set names */ -TCODLIB_API TCOD_list_t TCOD_namegen_get_sets (void); -/* delete a generator */ -TCODLIB_API void TCOD_namegen_destroy (void); -#ifdef __cplusplus -} -#endif -#endif +/* +* libtcod +* Copyright (c) 2008-2018 Jice & Mingos & rmtew +* All rights reserved. +* +* Redistribution and use in source and binary forms, with or without +* modification, are permitted provided that the following conditions are met: +* * Redistributions of source code must retain the above copyright +* notice, this list of conditions and the following disclaimer. +* * Redistributions in binary form must reproduce the above copyright +* notice, this list of conditions and the following disclaimer in the +* documentation and/or other materials provided with the distribution. +* * The name of Jice or Mingos may not be used to endorse or promote +* products derived from this software without specific prior written +* permission. +* +* THIS SOFTWARE IS PROVIDED BY JICE, MINGOS AND RMTEW ``AS IS'' AND ANY +* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED +* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE +* DISCLAIMED. IN NO EVENT SHALL JICE, MINGOS OR RMTEW BE LIABLE FOR ANY +* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES +* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; +* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND +* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS +* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +*/ +/* +* Mingos' NameGen +* This file was written by Dominik "Mingos" Marczuk. +*/ + +#ifndef _TCOD_NAMEGEN_H +#define _TCOD_NAMEGEN_H + +#include "portability.h" +#include "list.h" +#include "mersenne.h" + +#ifdef __cplusplus +extern "C" { +#endif +/* the generator typedef */ +struct TCOD_NameGen; +typedef struct TCOD_NameGen *TCOD_namegen_t; + +/* parse a file with syllable sets */ +TCODLIB_API void TCOD_namegen_parse (const char * filename, TCOD_random_t random); +/* generate a name */ +TCODLIB_API char * TCOD_namegen_generate (char * name, bool allocate); +/* generate a name using a custom generation rule */ +TCODLIB_API char * TCOD_namegen_generate_custom (char * name, char * rule, bool allocate); +/* retrieve the list of all available syllable set names */ +TCODLIB_API TCOD_list_t TCOD_namegen_get_sets (void); +/* delete a generator */ +TCODLIB_API void TCOD_namegen_destroy (void); +#ifdef __cplusplus +} +#endif +#endif diff --git a/tcod_sys/libtcod/include/namegen.hpp b/tcod_sys/libtcod/src/libtcod/namegen.hpp similarity index 98% rename from tcod_sys/libtcod/include/namegen.hpp rename to tcod_sys/libtcod/src/libtcod/namegen.hpp index 82a07d8c2..36a253a1f 100644 --- a/tcod_sys/libtcod/include/namegen.hpp +++ b/tcod_sys/libtcod/src/libtcod/namegen.hpp @@ -1,294 +1,294 @@ -/* -* libtcod -* Copyright (c) 2008-2018 Jice & Mingos & rmtew -* All rights reserved. -* -* Redistribution and use in source and binary forms, with or without -* modification, are permitted provided that the following conditions are met: -* * Redistributions of source code must retain the above copyright -* notice, this list of conditions and the following disclaimer. -* * Redistributions in binary form must reproduce the above copyright -* notice, this list of conditions and the following disclaimer in the -* documentation and/or other materials provided with the distribution. -* * The name of Jice or Mingos may not be used to endorse or promote -* products derived from this software without specific prior written -* permission. -* -* THIS SOFTWARE IS PROVIDED BY JICE, MINGOS AND RMTEW ``AS IS'' AND ANY -* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED -* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE -* DISCLAIMED. IN NO EVENT SHALL JICE, MINGOS OR RMTEW BE LIABLE FOR ANY -* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES -* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; -* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND -* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS -* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. -*/ -/* -* Mingos' NameGen -* This file was written by Dominik "Mingos" Marczuk. -*/ - -#ifndef _TCOD_NAMEGEN_HPP -#define _TCOD_NAMEGEN_HPP - -#include "list.hpp" -#include "mersenne.hpp" -#include "namegen.h" -/** - @PageName namegen - @PageCategory Roguelike toolkits - @PageTitle Name generator - @PageDesc This tool allows one to generate random names out of custom made syllable sets. - */ -class TCODLIB_API TCODNamegen { - public: - /** - @PageName namegen_init - @PageFather namegen - @PageTitle Creating a generator - @FuncDesc In order to be able to generate names, the name generator needs to be fed proper data. It will then be ready to generate random names defined in the file(s) it is fed. Syllable set parsing is achieved via the following. - Note 1: Each file will be parsed once only. If, for some reason, you would like to parse the same file twice, you will need to destroy the generator first, which will empty the list of parsed files along with erasing all the data retrieved from those files. - - Note 2: The generator can be fed data multiple times if you have it in separate files. Just make sure the structure names in them aren't duplicated, otherwise they will be silently ignored. - - Note 3: In the C++ version, you are not obliged to specify the random number generator. If you skip it in the function call, the generator will assume you would like to use an instance of the default generator. - - @Cpp static void TCODNamegen::parse (const char * filename, TCODRandom * random = NULL) - @C void TCOD_namegen_parse (const char * filename, TCOD_random_t random) - @Py namegen_parse (filename, random = 0) - @C# - static void TCODNameGenerator::parse(string filename) - static void TCODNameGenerator::parse(string filename, TCODRandom random) - @Param filename The file where the desired syllable set is saved, along with its relative parh, for instance, "data/names.txt". - @Param random A random number generator object. Use NULL for the default random number generator - @CppEx - TCODNamegen::parse("data/names.txt",TCODRandom::getInstance()); - TCODNamegen::parse("data/names2.txt"); - @CEx TCOD_namegen_parse("data/names.txt",TCOD_random_get_instance()); - @PyEx libtcod.namegen_parse('data/names.txt') - */ - static void parse (const char * filename, TCODRandom * random = NULL); - - /** - @PageName namegen_init - @FuncTitle Destroying a generator - @FuncDesc To release the resources used by a name generator, you may call: - This will free all memory used by the generator. In order to generate a name again, you have to parse a file again. - @Cpp static void TCODNamegen::destroy (void) - @C void TCOD_namegen_destroy (void) - @Py namegen_destroy () - @C# static void TCODNameGenerator::destroy() - */ - static void destroy (void); - - /** - @PageName namegen_generate - @PageTitle Generating a name - @PageFather namegen - @FuncTitle Generating a default name - @FuncDesc The following will output a random name generated using one of the generation rules specified in the syllable set: - Should you choose to allocate memory for the output, you need to remember to deallocate it once you don't need the name anymore using the free() function. This applies to C++ as well (delete won't work - you have to use free()). - - On the other hand, should you choose not to allocate memory, be aware that subsequent calls will overwrite the previously returned pointer, so make sure to copy the output using strcpy(), strdup() or other means of your choosing. - - The name you specify needs to be in one of the files the generator has previously parsed (see Creating a generator). If such a name doesn't exist, a warning will be displayed and NULL will be returned. - @Cpp static char * TCODNamegen::generate (char * name, bool allocate = false) - @C char * TCOD_namegen_generate (char * name, bool allocate) - @Py namegen_generate (name, allocate = 0) - @C# string TCODNameGenerator::generate (string name) - @Param name The structure name you wish to refer to, for instance, "celtic female". - For more about how structure names work, please refer to those chapters. - @Param allocate Whether memory should be allocated for the output or not. - @CppEx - TCODNamegen::parse("data/names.txt",TCODRandom::getInstance()); - char * myName = TCODNamegen::generate("fantasy female"); - @CEx - TCOD_namegen_parse("data/names.txt",TCOD_random_get_instance()); - char * my_name = TCOD_namegen_generate("Celtic male",false); - @PyEx - libtcod.namegen_parse('data/names.txt') - name = libtcod.namegen_generate('Nordic female') - */ - static char * generate (char * name, bool allocate = false); - - /** - @PageName namegen_generate - @FuncTitle Generating a custom name - @FuncDesc It is also possible to generate a name using custom generation rules. This overrides the random choice of a generation rule from the syllable set. Please refer to chapter 16.5 to learn about the name generation rules syntax. - @Cpp static char * TCODNamegen::generateCustom (char * name, char * rule, bool allocate = false) - @C char * TCOD_namegen_generate_custom (char * name, char * rule, bool allocate) - @Py namegen_generate_custom (name, rule, allocate = 0) - @C# string TCODNameGenerator::generateCustom (string name, string rule) - @Param name The structure name you wish to refer to, for instance, "celtic female". - For more about how structure names work, please refer to those chapters. - @Param rule The name generation rule. See this chapter for more details. - @Param allocate Whether memory should be allocated for the output or not. - @CppEx - TCODNamegen::parse("data/names.txt",TCODRandom::getInstance()); - char * myName = TCODNamegen::generateCustom("Nordic male","$s$e"); - @CEx - TCOD_namegen_parse("data/names.txt",TCOD_random_get_instance()); - char * my_name = TCOD_namegen_generate_custom("Mesopotamian female","$s$e",false); - @PyEx - libtcod.namegen_parse('data/names.txt') - name = libtcod.namegen_generate_custom('Nordic female','$s$e') - */ - static char * generateCustom (char * name, char * rule, bool allocate = false); - - /** - @PageName namegen_generate - @FuncTitle Retrieving available set names - @FuncDesc If you wish to check the sylable set names that are currently available, you may call: - This will create a list with all the available syllable set names. Remember to delete that list after you don't need it anymore! - @Cpp static TCODList TCODNamegen::getSets () - @C TCOD_list_t TCOD_namegen_get_sets () - @Py namegen_get_sets () - @C# static IEnumerable TCODNameGenerator::getSets() - */ - static TCOD_list_t getSets (void); - - /** - @PageName namegen_file - @PageFather namegen - @PageTitle Syllable set configuration - @PageDesc Configuring the syllable set is vital to obtaining high quality randomly generated names. Please refer to the following subchapters for detailed information: - */ - - /** - @PageName namegen_file_1 - @PageFather namegen_file - @PageTitle Syllable set basic structure - @PageDesc The syllable sets need to be written in one or more text files that will be opened and parsed by the generator. - -The data uses a standard TCODParser file and data should be inserted according to the general rules of creating a configuration file. For more information, please refer to The libtcod config file format. - -The structure type that's defined in the generator is "name". This structure type must also be accompanied by a structure name. It will be used for identification purposes in the generator. For instance, if you use a structure name "fantasy female", you will be able to access this syllable set by creating a generator using "fantasy female" syllables. In the initialisation function, this is the "const char * name" argument. - -The structure contains different members, all of which must be of TCOD_TYPE_STRING type. The tokens inside the strings, be them phonemes or syllables, form a single string, but are separated with separator characters. Characters used for token separation are all characters that are not Latin upper- or lowercase characters, dashes or apostrophes. A comma, a space or a comma+space are all perfectly valid, human-readable separators. In order to use a character inside a string that would normally be considered a separator, precede it with a slash (eg. "/:", "/.", "/!", etc.). An exception to this rule is the space character, which can also be achieved by using an underscore (eg. "the_Great"). - -The structure members that may thus be defined are: -

phonemesVocals -phonemesConsonants -syllablesPre -syllablesStart -syllablesMiddle -syllablesEnd -syllablesPost -

- -All of those strings are considered optional. However, if you don't define a string, but reference it in the name generation rules, you will see a warning displayed on stderr about missing data. - */ - - /** - @PageName namegen_file_2 - @PageFather namegen_file - @PageTitle Illegal strings - @PageDesc Another optional property is -

illegal

- -This property contains strings that are considered illegal and thus not desired in your names. Should a generated name contain any of the tokens specified in this string, it will be discarded and replaced by a new one. Illegal strings may be as short as single characters or as long as entire names. However, it is best to create a syllable set that generates very few names that sound bad. Otherwise, the illegal list might become very long. - -Be aware that the generator will automatically correct or reject certain words, so you don't need to place every undesired possibility in this string. - -The generator will correct the following: - - * leading spaces ("_NAME") - * ending spaces ("NAME_") - * double spaces ("NAME1__NAME2") - -It will generate a new name in the following cases: - - * triple characters ("Raaagnar") - * two-character adjacent repetitions ("Bobofur" is wrong, but "Bombofur" is OK) - * three-character (or more) repetitions, whether adjacent or not ("Bombombur", "Dagbjoerdag", "Gwaerdygwaern") - -Remember that all of this is case-insensitive, so you don't need to care about uppercase/lowercase distinction in your illegal strings. - */ - - /** - @PageName namegen_file_3 - @PageFather namegen_file - @PageTitle Rules - @PageDesc There's one last string that's contained within the structure: -

rules

- -It is mandatory, so not defining it will trigger an error. It defines how the generator should join the supplied data in order to generate a name. This string uses a syntax of its own, which is also used when specifying a rule when generating a custom name (see chapter 16.2). - -The rules are parsed pretty much the same way as all other strings, so all rules regarding separators and special characters apply as well. However, you can additionally use a set of wildcards and frequency markers. Each wildcard is preceded by the dollar sign ('$'), while frequency markers are preceded by the per cent sign ('%'). Here's the complete wildcard list: - - - - - - - - - - - - - -
WildcardExampleDescription
$[INT]P$P, $25PUse a random Pre syllable.
The optional integer value denotes the per cent chance of adding the syllable.
$[INT]s$s, $25sUse a random Start syllable.
$[INT]m$m, $25mUse a random Middle syllable.
$[INT]e$e, $25eUse a random End syllable.
$[INT]p$p, $25pUse a random Post syllable.
$[INT]v$v, $25vUse a random vocal.
$[INT]c$c, $25cUse a random consonant.
$[INT]?$?, $25?Use a random phoneme (vocal or consonant).
%INT%50, %25Frequency marker. Denotes the per cent chance for the rule to be accepted if it's picked.
If the rule is not accepted, another roll is made to choose a name generation rule.
It's used to reduce the frequency a given rule is chosen with.
This marker may only appear at the beginning of a rule.
- */ - - /** - @PageName namegen_file_4 - @PageFather namegen_file - @PageTitle Example structure - @PageDesc Consider this example structure. It does not contain syllables, but rather full names. -

name "king" { - syllablesStart = "Alexander, Augustus, Casimir, Henry, John, Louis, Sigismund," - "Stanislao, Stephen, Wenceslaus" - syllablesMiddle = "I, II, III, IV, V" - syllablesEnd = "Bathory, Herman, Jogaila, Lambert, of_Bohemia, of_France," - "of_Hungary, of_Masovia, of_Poland, of_Valois, of_Varna, Probus," - "Spindleshanks, Tanglefoot, the_Bearded, the_Black, the_Bold, the_Brave," - "the_Chaste, the_Curly, the_Elbow-high, the_Exile, the_Great," - "the_Jagiellonian, the_Just, the_Old, the_Pious, the_Restorer, the_Saxon," - "the_Strong, the_Wheelwright, the_White, Vasa, Wrymouth" - rules = "%50$s, $s_$m, $s_$50m_$e" -}

- -The above structure only uses three syllable lists and has three different rules. Let's analyse them one by one. - -%50$s - this will simply output a random Start syllable, but this rule is not intended to be picked with the same frequency as the others, so the frequency marker at the beginning ("%50") ensures that 50% of the time this syllable will be rejected and a different one will be picked. - -$s_$m - this will output a Start syllable and a Middle syllable, separated with a space. - -$s_$50m_$e - This will output a Start syllable, followed by a Middle syllable, followed by an End sylable, all separated with spaces. However, the Middle syllable has only 50% chance of appearing at all, so 50% of the time the rule will actually produce a Start syllable followed directly by an End syllable, separated with a space. - -As you may have noticed, the third rule may produce a double space if the Middle syllable is not chosen. You do not have to worry about such cases, as the generator will automatically reduce all double spaces to single spaces, and leading/ending spaces will be removed completely. - -Output from this example set would contain kings' names based on the names of real monarchs of Poland. Have a look at the sample: -

Alexander IV -Alexander -Sigismund -Stanislao V -Stanislao -Henry I of Poland -Augustus V -Stanislao I the Pious -Sigismund IV the Brave -John the Great -Henry the Old -John the Bold -Stanislao II the Saxon -Wenceslaus of France -John Probus -Louis V -Wenceslaus Lambert -Stanislao Spindleshanks -Henry Herman -Alexander the Old -Louis V the Curly -Wenceslaus II -Augustus IV -Alexander V -Augustus Probus -

- */ -}; - -#endif +/* +* libtcod +* Copyright (c) 2008-2018 Jice & Mingos & rmtew +* All rights reserved. +* +* Redistribution and use in source and binary forms, with or without +* modification, are permitted provided that the following conditions are met: +* * Redistributions of source code must retain the above copyright +* notice, this list of conditions and the following disclaimer. +* * Redistributions in binary form must reproduce the above copyright +* notice, this list of conditions and the following disclaimer in the +* documentation and/or other materials provided with the distribution. +* * The name of Jice or Mingos may not be used to endorse or promote +* products derived from this software without specific prior written +* permission. +* +* THIS SOFTWARE IS PROVIDED BY JICE, MINGOS AND RMTEW ``AS IS'' AND ANY +* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED +* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE +* DISCLAIMED. IN NO EVENT SHALL JICE, MINGOS OR RMTEW BE LIABLE FOR ANY +* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES +* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; +* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND +* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS +* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +*/ +/* +* Mingos' NameGen +* This file was written by Dominik "Mingos" Marczuk. +*/ + +#ifndef _TCOD_NAMEGEN_HPP +#define _TCOD_NAMEGEN_HPP + +#include "list.hpp" +#include "mersenne.hpp" +#include "namegen.h" +/** + @PageName namegen + @PageCategory Roguelike toolkits + @PageTitle Name generator + @PageDesc This tool allows one to generate random names out of custom made syllable sets. + */ +class TCODLIB_API TCODNamegen { + public: + /** + @PageName namegen_init + @PageFather namegen + @PageTitle Creating a generator + @FuncDesc In order to be able to generate names, the name generator needs to be fed proper data. It will then be ready to generate random names defined in the file(s) it is fed. Syllable set parsing is achieved via the following. + Note 1: Each file will be parsed once only. If, for some reason, you would like to parse the same file twice, you will need to destroy the generator first, which will empty the list of parsed files along with erasing all the data retrieved from those files. + + Note 2: The generator can be fed data multiple times if you have it in separate files. Just make sure the structure names in them aren't duplicated, otherwise they will be silently ignored. + + Note 3: In the C++ version, you are not obliged to specify the random number generator. If you skip it in the function call, the generator will assume you would like to use an instance of the default generator. + + @Cpp static void TCODNamegen::parse (const char * filename, TCODRandom * random = NULL) + @C void TCOD_namegen_parse (const char * filename, TCOD_random_t random) + @Py namegen_parse (filename, random = 0) + @C# + static void TCODNameGenerator::parse(string filename) + static void TCODNameGenerator::parse(string filename, TCODRandom random) + @Param filename The file where the desired syllable set is saved, along with its relative parh, for instance, "data/names.txt". + @Param random A random number generator object. Use NULL for the default random number generator + @CppEx + TCODNamegen::parse("data/names.txt",TCODRandom::getInstance()); + TCODNamegen::parse("data/names2.txt"); + @CEx TCOD_namegen_parse("data/names.txt",TCOD_random_get_instance()); + @PyEx libtcod.namegen_parse('data/names.txt') + */ + static void parse (const char * filename, TCODRandom * random = NULL); + + /** + @PageName namegen_init + @FuncTitle Destroying a generator + @FuncDesc To release the resources used by a name generator, you may call: + This will free all memory used by the generator. In order to generate a name again, you have to parse a file again. + @Cpp static void TCODNamegen::destroy (void) + @C void TCOD_namegen_destroy (void) + @Py namegen_destroy () + @C# static void TCODNameGenerator::destroy() + */ + static void destroy (void); + + /** + @PageName namegen_generate + @PageTitle Generating a name + @PageFather namegen + @FuncTitle Generating a default name + @FuncDesc The following will output a random name generated using one of the generation rules specified in the syllable set: + Should you choose to allocate memory for the output, you need to remember to deallocate it once you don't need the name anymore using the free() function. This applies to C++ as well (delete won't work - you have to use free()). + + On the other hand, should you choose not to allocate memory, be aware that subsequent calls will overwrite the previously returned pointer, so make sure to copy the output using strcpy(), strdup() or other means of your choosing. + + The name you specify needs to be in one of the files the generator has previously parsed (see Creating a generator). If such a name doesn't exist, a warning will be displayed and NULL will be returned. + @Cpp static char * TCODNamegen::generate (char * name, bool allocate = false) + @C char * TCOD_namegen_generate (char * name, bool allocate) + @Py namegen_generate (name, allocate = 0) + @C# string TCODNameGenerator::generate (string name) + @Param name The structure name you wish to refer to, for instance, "celtic female". + For more about how structure names work, please refer to those chapters. + @Param allocate Whether memory should be allocated for the output or not. + @CppEx + TCODNamegen::parse("data/names.txt",TCODRandom::getInstance()); + char * myName = TCODNamegen::generate("fantasy female"); + @CEx + TCOD_namegen_parse("data/names.txt",TCOD_random_get_instance()); + char * my_name = TCOD_namegen_generate("Celtic male",false); + @PyEx + libtcod.namegen_parse('data/names.txt') + name = libtcod.namegen_generate('Nordic female') + */ + static char * generate (char * name, bool allocate = false); + + /** + @PageName namegen_generate + @FuncTitle Generating a custom name + @FuncDesc It is also possible to generate a name using custom generation rules. This overrides the random choice of a generation rule from the syllable set. Please refer to chapter 16.5 to learn about the name generation rules syntax. + @Cpp static char * TCODNamegen::generateCustom (char * name, char * rule, bool allocate = false) + @C char * TCOD_namegen_generate_custom (char * name, char * rule, bool allocate) + @Py namegen_generate_custom (name, rule, allocate = 0) + @C# string TCODNameGenerator::generateCustom (string name, string rule) + @Param name The structure name you wish to refer to, for instance, "celtic female". + For more about how structure names work, please refer to those chapters. + @Param rule The name generation rule. See this chapter for more details. + @Param allocate Whether memory should be allocated for the output or not. + @CppEx + TCODNamegen::parse("data/names.txt",TCODRandom::getInstance()); + char * myName = TCODNamegen::generateCustom("Nordic male","$s$e"); + @CEx + TCOD_namegen_parse("data/names.txt",TCOD_random_get_instance()); + char * my_name = TCOD_namegen_generate_custom("Mesopotamian female","$s$e",false); + @PyEx + libtcod.namegen_parse('data/names.txt') + name = libtcod.namegen_generate_custom('Nordic female','$s$e') + */ + static char * generateCustom (char * name, char * rule, bool allocate = false); + + /** + @PageName namegen_generate + @FuncTitle Retrieving available set names + @FuncDesc If you wish to check the sylable set names that are currently available, you may call: + This will create a list with all the available syllable set names. Remember to delete that list after you don't need it anymore! + @Cpp static TCODList TCODNamegen::getSets () + @C TCOD_list_t TCOD_namegen_get_sets () + @Py namegen_get_sets () + @C# static IEnumerable TCODNameGenerator::getSets() + */ + static TCOD_list_t getSets (void); + + /** + @PageName namegen_file + @PageFather namegen + @PageTitle Syllable set configuration + @PageDesc Configuring the syllable set is vital to obtaining high quality randomly generated names. Please refer to the following subchapters for detailed information: + */ + + /** + @PageName namegen_file_1 + @PageFather namegen_file + @PageTitle Syllable set basic structure + @PageDesc The syllable sets need to be written in one or more text files that will be opened and parsed by the generator. + +The data uses a standard TCODParser file and data should be inserted according to the general rules of creating a configuration file. For more information, please refer to The libtcod config file format. + +The structure type that's defined in the generator is "name". This structure type must also be accompanied by a structure name. It will be used for identification purposes in the generator. For instance, if you use a structure name "fantasy female", you will be able to access this syllable set by creating a generator using "fantasy female" syllables. In the initialisation function, this is the "const char * name" argument. + +The structure contains different members, all of which must be of TCOD_TYPE_STRING type. The tokens inside the strings, be them phonemes or syllables, form a single string, but are separated with separator characters. Characters used for token separation are all characters that are not Latin upper- or lowercase characters, dashes or apostrophes. A comma, a space or a comma+space are all perfectly valid, human-readable separators. In order to use a character inside a string that would normally be considered a separator, precede it with a slash (eg. "/:", "/.", "/!", etc.). An exception to this rule is the space character, which can also be achieved by using an underscore (eg. "the_Great"). + +The structure members that may thus be defined are: +

phonemesVocals +phonemesConsonants +syllablesPre +syllablesStart +syllablesMiddle +syllablesEnd +syllablesPost +

+ +All of those strings are considered optional. However, if you don't define a string, but reference it in the name generation rules, you will see a warning displayed on stderr about missing data. + */ + + /** + @PageName namegen_file_2 + @PageFather namegen_file + @PageTitle Illegal strings + @PageDesc Another optional property is +

illegal

+ +This property contains strings that are considered illegal and thus not desired in your names. Should a generated name contain any of the tokens specified in this string, it will be discarded and replaced by a new one. Illegal strings may be as short as single characters or as long as entire names. However, it is best to create a syllable set that generates very few names that sound bad. Otherwise, the illegal list might become very long. + +Be aware that the generator will automatically correct or reject certain words, so you don't need to place every undesired possibility in this string. + +The generator will correct the following: + + * leading spaces ("_NAME") + * ending spaces ("NAME_") + * double spaces ("NAME1__NAME2") + +It will generate a new name in the following cases: + + * triple characters ("Raaagnar") + * two-character adjacent repetitions ("Bobofur" is wrong, but "Bombofur" is OK) + * three-character (or more) repetitions, whether adjacent or not ("Bombombur", "Dagbjoerdag", "Gwaerdygwaern") + +Remember that all of this is case-insensitive, so you don't need to care about uppercase/lowercase distinction in your illegal strings. + */ + + /** + @PageName namegen_file_3 + @PageFather namegen_file + @PageTitle Rules + @PageDesc There's one last string that's contained within the structure: +

rules

+ +It is mandatory, so not defining it will trigger an error. It defines how the generator should join the supplied data in order to generate a name. This string uses a syntax of its own, which is also used when specifying a rule when generating a custom name (see chapter 16.2). + +The rules are parsed pretty much the same way as all other strings, so all rules regarding separators and special characters apply as well. However, you can additionally use a set of wildcards and frequency markers. Each wildcard is preceded by the dollar sign ('$'), while frequency markers are preceded by the per cent sign ('%'). Here's the complete wildcard list: + + + + + + + + + + + + + +
WildcardExampleDescription
$[INT]P$P, $25PUse a random Pre syllable.
The optional integer value denotes the per cent chance of adding the syllable.
$[INT]s$s, $25sUse a random Start syllable.
$[INT]m$m, $25mUse a random Middle syllable.
$[INT]e$e, $25eUse a random End syllable.
$[INT]p$p, $25pUse a random Post syllable.
$[INT]v$v, $25vUse a random vocal.
$[INT]c$c, $25cUse a random consonant.
$[INT]?$?, $25?Use a random phoneme (vocal or consonant).
%INT%50, %25Frequency marker. Denotes the per cent chance for the rule to be accepted if it's picked.
If the rule is not accepted, another roll is made to choose a name generation rule.
It's used to reduce the frequency a given rule is chosen with.
This marker may only appear at the beginning of a rule.
+ */ + + /** + @PageName namegen_file_4 + @PageFather namegen_file + @PageTitle Example structure + @PageDesc Consider this example structure. It does not contain syllables, but rather full names. +

name "king" { + syllablesStart = "Alexander, Augustus, Casimir, Henry, John, Louis, Sigismund," + "Stanislao, Stephen, Wenceslaus" + syllablesMiddle = "I, II, III, IV, V" + syllablesEnd = "Bathory, Herman, Jogaila, Lambert, of_Bohemia, of_France," + "of_Hungary, of_Masovia, of_Poland, of_Valois, of_Varna, Probus," + "Spindleshanks, Tanglefoot, the_Bearded, the_Black, the_Bold, the_Brave," + "the_Chaste, the_Curly, the_Elbow-high, the_Exile, the_Great," + "the_Jagiellonian, the_Just, the_Old, the_Pious, the_Restorer, the_Saxon," + "the_Strong, the_Wheelwright, the_White, Vasa, Wrymouth" + rules = "%50$s, $s_$m, $s_$50m_$e" +}

+ +The above structure only uses three syllable lists and has three different rules. Let's analyse them one by one. + +%50$s - this will simply output a random Start syllable, but this rule is not intended to be picked with the same frequency as the others, so the frequency marker at the beginning ("%50") ensures that 50% of the time this syllable will be rejected and a different one will be picked. + +$s_$m - this will output a Start syllable and a Middle syllable, separated with a space. + +$s_$50m_$e - This will output a Start syllable, followed by a Middle syllable, followed by an End sylable, all separated with spaces. However, the Middle syllable has only 50% chance of appearing at all, so 50% of the time the rule will actually produce a Start syllable followed directly by an End syllable, separated with a space. + +As you may have noticed, the third rule may produce a double space if the Middle syllable is not chosen. You do not have to worry about such cases, as the generator will automatically reduce all double spaces to single spaces, and leading/ending spaces will be removed completely. + +Output from this example set would contain kings' names based on the names of real monarchs of Poland. Have a look at the sample: +

Alexander IV +Alexander +Sigismund +Stanislao V +Stanislao +Henry I of Poland +Augustus V +Stanislao I the Pious +Sigismund IV the Brave +John the Great +Henry the Old +John the Bold +Stanislao II the Saxon +Wenceslaus of France +John Probus +Louis V +Wenceslaus Lambert +Stanislao Spindleshanks +Henry Herman +Alexander the Old +Louis V the Curly +Wenceslaus II +Augustus IV +Alexander V +Augustus Probus +

+ */ +}; + +#endif diff --git a/tcod_sys/libtcod/src/namegen_c.c b/tcod_sys/libtcod/src/libtcod/namegen_c.c similarity index 97% rename from tcod_sys/libtcod/src/namegen_c.c rename to tcod_sys/libtcod/src/libtcod/namegen_c.c index dc699a2c5..c2d890df4 100644 --- a/tcod_sys/libtcod/src/namegen_c.c +++ b/tcod_sys/libtcod/src/libtcod/namegen_c.c @@ -1,641 +1,641 @@ -/* -* libtcod -* Copyright (c) 2008-2018 Jice & Mingos & rmtew -* All rights reserved. -* -* Redistribution and use in source and binary forms, with or without -* modification, are permitted provided that the following conditions are met: -* * Redistributions of source code must retain the above copyright -* notice, this list of conditions and the following disclaimer. -* * Redistributions in binary form must reproduce the above copyright -* notice, this list of conditions and the following disclaimer in the -* documentation and/or other materials provided with the distribution. -* * The name of Jice or Mingos may not be used to endorse or promote -* products derived from this software without specific prior written -* permission. -* -* THIS SOFTWARE IS PROVIDED BY JICE, MINGOS AND RMTEW ``AS IS'' AND ANY -* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED -* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE -* DISCLAIMED. IN NO EVENT SHALL JICE, MINGOS OR RMTEW BE LIABLE FOR ANY -* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES -* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; -* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND -* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS -* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. -*/ -/* -* Mingos' NameGen -* This file was written by Dominik "Mingos" Marczuk. -*/ -#include - -#include -#include -#include -#include - -#include - -/* ------------ * - * the typedefs * - * ------------ */ - -/* the struct containing a definition of an unprocessed syllable set */ -typedef struct { - char * name; - char * vocals; - char * consonants; - char * pre; - char * start; - char * middle; - char * end; - char * post; - char * illegal; - char * rules; -} namegen_syllables_t; - -/* and the generator struct */ -typedef struct { - /* the name that will be called */ - char * name; - /* needs to use a random number generator */ - TCOD_random_t random; - /* the lists with all the data */ - TCOD_list_t vocals; - TCOD_list_t consonants; - TCOD_list_t syllables_pre; - TCOD_list_t syllables_start; - TCOD_list_t syllables_middle; - TCOD_list_t syllables_end; - TCOD_list_t syllables_post; - TCOD_list_t illegal_strings; - TCOD_list_t rules; -} namegen_t; - -/* ------------------- * - * variables and stuff * - * ------------------- */ - -/* the list containing the generators */ -TCOD_list_t namegen_generators_list = NULL; - -/* the file parser */ -TCOD_parser_t namegen_parser; -/* parsed files list */ -TCOD_list_t parsed_files = NULL; -/* the data that will be filled out */ -namegen_syllables_t * parser_data = NULL; -namegen_t * parser_output = NULL; -/* this one's needed to correctly update the generators with RNG pointer */ -TCOD_random_t namegen_random; - -/* the string that will be pointed to upon generating a name */ -char * namegen_name = NULL; -/* for keeping track of the size of output names */ -size_t namegen_name_size; - -/* ------------------------------------ * - * stuff to operate on the syllable set * - * ------------------------------------ */ - -/* initialise a syllable set */ -namegen_syllables_t * namegen_syllables_new (void) { - namegen_syllables_t * data = calloc(sizeof(namegen_syllables_t),1); - return data; -} - -/* free a syllables set */ -void namegen_syllables_delete (namegen_syllables_t * data) { - if (data->vocals) free(data->vocals); - if (data->consonants) free(data->consonants); - if (data->pre) free(data->pre); - if (data->start) free(data->start); - if (data->middle) free(data->middle); - if (data->end) free(data->end); - if (data->post) free(data->post); - if (data->illegal) free(data->illegal); - if (data->rules) free(data->rules); - free(data->name); - free(data); -} - -/* ---------------------------------- * - * stuff to operate on the generators * - * ---------------------------------- */ - -/* create a new generator */ -namegen_t * namegen_generator_new (void) { - namegen_t * data = malloc(sizeof(namegen_t)); - data->name = NULL; - /* assign the rng */ - data->random = TCOD_random_get_instance(); - /* create the lists */ - data->vocals = TCOD_list_new(); - data->consonants = TCOD_list_new(); - data->syllables_pre = TCOD_list_new(); - data->syllables_start = TCOD_list_new(); - data->syllables_middle = TCOD_list_new(); - data->syllables_end = TCOD_list_new(); - data->syllables_post = TCOD_list_new(); - data->illegal_strings = TCOD_list_new(); - data->rules = TCOD_list_new(); - return (TCOD_namegen_t)data; -} - -/* check whether a given generator already exists */ -bool namegen_generator_check (const char * name) { - /* if the list is not created yet, create it */ - if (namegen_generators_list == NULL) { - namegen_generators_list = TCOD_list_new(); - return false; - } - /* otherwise, scan it for the name */ - else { - namegen_t ** it; - for (it = (namegen_t**)TCOD_list_begin(namegen_generators_list); it < (namegen_t**)TCOD_list_end(namegen_generators_list); it++) { - if (strcmp((*it)->name,name) == 0) return true; - } - return false; - } -} - -/* retrieve available generator names */ -void namegen_get_sets_on_error (void) { - namegen_t ** it; - fprintf (stderr,"Registered syllable sets are:\n"); - for (it = (namegen_t**)TCOD_list_begin(namegen_generators_list); it < (namegen_t**)TCOD_list_end(namegen_generators_list); it++) { - fprintf (stderr," * \"%s\"\n",(*it)->name); - } -} - -/* get the appropriate syllables set */ -namegen_t * namegen_generator_get (const char * name) { - if (namegen_generator_check(name) == true) { - namegen_t ** it; - for (it = (namegen_t**)TCOD_list_begin(namegen_generators_list); it != (namegen_t**)TCOD_list_end(namegen_generators_list); it++) { - if (strcmp((*it)->name,name) == 0) return (*it); - } - } - /* and if there's no such set... */ - else - fprintf(stderr,"Generator \"%s\" could not be retrieved.\n",name); - return NULL; -} - - - -/* destroy a generator */ -void namegen_generator_delete (namegen_t * generator) { - namegen_t * data = generator; - free(data->name); - data->random = NULL; - TCOD_list_clear_and_delete(data->vocals); - TCOD_list_clear_and_delete(data->consonants); - TCOD_list_clear_and_delete(data->syllables_pre); - TCOD_list_clear_and_delete(data->syllables_start); - TCOD_list_clear_and_delete(data->syllables_middle); - TCOD_list_clear_and_delete(data->syllables_end); - TCOD_list_clear_and_delete(data->syllables_post); - TCOD_list_clear_and_delete(data->illegal_strings); - TCOD_list_clear_and_delete(data->rules); - free(data); -} - -/* ------------------------------ * - * Populating namegen_t with data * - * ------------------------------ */ - -/* fill the pointed list with syllable data by extracting tokens */ -void namegen_populate_list (char * source, TCOD_list_t list, bool wildcards) { - size_t len = strlen(source); - size_t i = 0; - char * token = malloc(strlen(source)+1); /* tokens will typically be many and very short, but let's be cautious. What if the entire string is a single token?*/ - memset(token,'\0',strlen(source)+1); - do { - /* do the tokenising using an iterator immitation :) */ - char * it = source + i; - /* append a normal character */ - if ((*it >= 'a' && *it <= 'z') || (*it >= 'A' && *it <= 'Z') || *it == '\'' || *it == '-') - strncat(token,it,1); - /* special character */ - else if (*it == '/') { - if (wildcards == true) strncat(token,it++,2); - else strncat(token,++it,1); - i++; - } - /* underscore is converted to space */ - else if (*it == '_') { - if (wildcards == true) strncat(token,it,1); - else strcat(token," "); - } - /* add wildcards if they are allowed */ - else if (wildcards == true && (*it == '$' || *it == '%' || (*it >= '0' && *it <= '9'))) - strncat(token,it,1); - /* all other characters are treated as separators and cause adding the current token to the list */ - else if (strlen(token) > 0) { - TCOD_list_push(list,TCOD_strdup(token)); - memset(token,'\0',strlen(source)+1); - } - } while (++i <= len); - free(token); -} - -/* populate all lists of a namegen_t struct */ -void namegen_populate (namegen_t * dst, namegen_syllables_t * src) { - if (dst == NULL || src == NULL) { - fprintf(stderr,"Couldn't populate the name generator with data.\n"); - exit(1); - } - if (src->vocals != NULL) namegen_populate_list (src->vocals,dst->vocals,false); - if (src->consonants != NULL) namegen_populate_list (src->consonants,dst->consonants,false); - if (src->pre != NULL) namegen_populate_list (src->pre,dst->syllables_pre,false); - if (src->start != NULL) namegen_populate_list (src->start,dst->syllables_start,false); - if (src->middle != NULL) namegen_populate_list (src->middle,dst->syllables_middle,false); - if (src->end != NULL) namegen_populate_list (src->end,dst->syllables_end,false); - if (src->post != NULL) namegen_populate_list (src->post,dst->syllables_post,false); - if (src->illegal != NULL) namegen_populate_list (src->illegal,dst->illegal_strings,false); - if (src->rules != NULL) namegen_populate_list (src->rules,dst->rules,true); - dst->name = TCOD_strdup(src->name); -} - -/* -------------------- * - * parser-related stuff * - * -------------------- */ - -/* preparing the parser */ -void namegen_parser_prepare (void) { - static bool namegen_parser_ready = false; - if (namegen_parser_ready == true) return; - else { - TCOD_parser_struct_t parser_name ; - namegen_parser = TCOD_parser_new(); - parser_name = TCOD_parser_new_struct(namegen_parser, "name"); - TCOD_struct_add_property(parser_name, "phonemesVocals", TCOD_TYPE_STRING, false); - TCOD_struct_add_property(parser_name, "phonemesConsonants", TCOD_TYPE_STRING, false); - TCOD_struct_add_property(parser_name, "syllablesPre", TCOD_TYPE_STRING, false); - TCOD_struct_add_property(parser_name, "syllablesStart", TCOD_TYPE_STRING, false); - TCOD_struct_add_property(parser_name, "syllablesMiddle", TCOD_TYPE_STRING, false); - TCOD_struct_add_property(parser_name, "syllablesEnd", TCOD_TYPE_STRING, false); - TCOD_struct_add_property(parser_name, "syllablesPost", TCOD_TYPE_STRING, false); - TCOD_struct_add_property(parser_name, "illegal", TCOD_TYPE_STRING, false); - TCOD_struct_add_property(parser_name, "rules", TCOD_TYPE_STRING, true); - namegen_parser_ready = true; - } -} - -/* parser listener */ -bool namegen_parser_new_struct (TCOD_parser_struct_t str, const char *name) { - parser_data = namegen_syllables_new(); - return true; -} - -bool namegen_parser_flag (const char *name) { - return true; -} - -bool namegen_parser_property(const char *name, TCOD_value_type_t type, TCOD_value_t value) { - if (strcmp(name,"syllablesStart") == 0) parser_data->start = TCOD_strdup(value.s); - else if (strcmp(name,"syllablesMiddle") == 0) parser_data->middle = TCOD_strdup(value.s); - else if (strcmp(name,"syllablesEnd") == 0) parser_data->end = TCOD_strdup(value.s); - else if (strcmp(name,"syllablesPre") == 0) parser_data->pre = TCOD_strdup(value.s); - else if (strcmp(name,"syllablesPost") == 0) parser_data->post = TCOD_strdup(value.s); - else if (strcmp(name,"phonemesVocals") == 0) parser_data->vocals = TCOD_strdup(value.s); - else if (strcmp(name,"phonemesConsonants") == 0) parser_data->consonants = TCOD_strdup(value.s); - else if (strcmp(name,"rules") == 0) parser_data->rules = TCOD_strdup(value.s); - else if (strcmp(name,"illegal") == 0) { /* illegal strings are converted to lowercase */ - char * str ; - int i; - parser_data->illegal = TCOD_strdup(value.s); - str = parser_data->illegal; - for(i = 0; i < (int)strlen(str); i++) str[i] = (char)(tolower(str[i])); - } - else return false; - return true; -} - -bool namegen_parser_end_struct(TCOD_parser_struct_t str, const char *name) { - /* if there's no syllable set by this name, add it to the list */ - if (namegen_generator_check(name) == false) { - parser_data->name = TCOD_strdup(name); - parser_output = namegen_generator_new(); - namegen_populate(parser_output,parser_data); - parser_output->random = namegen_random; - if (namegen_generators_list == NULL) namegen_generators_list = TCOD_list_new(); - TCOD_list_push(namegen_generators_list, (const void*)parser_output); - } - /* free the allocated memory to prevent a memory leak */ - namegen_syllables_delete(parser_data); - return true; -} - -void namegen_parser_error(const char *msg) { - fprintf(stderr,"%s\n",msg); - exit(1); -} - -TCOD_parser_listener_t namegen_listener = { - namegen_parser_new_struct, - namegen_parser_flag, - namegen_parser_property, - namegen_parser_end_struct, - namegen_parser_error -}; - -/* run the parser */ -void namegen_parser_run (const char * filename) { - char ** it; - /* prepare the parser --- this will be executed only once */ - namegen_parser_prepare(); - if (parsed_files == NULL) parsed_files = TCOD_list_new(); - if (TCOD_list_size(parsed_files) > 0) { - for (it = (char **)TCOD_list_begin(parsed_files); it != (char **)TCOD_list_end(parsed_files); it++) - if (strcmp(*it,filename) == 0) return; - } - /* if the file hasn't been parsed yet, add its name to the list so that it's never parsed twice */ - TCOD_list_push(parsed_files,(const void *)TCOD_strdup(filename)); - /* run the parser */ - TCOD_parser_run(namegen_parser,filename,&namegen_listener); -} - -/* --------------- * - * rubbish pruning * - * --------------- */ - -/* search for occurrences of triple characters (case-insensitive) */ -bool namegen_word_has_triples (char * str) { - char * it = str; - char c = (char)(tolower(*it)); - int cnt = 1; - bool has_triples = false; - it++; - while (*it != '\0') { - if ((char)(tolower(*it)) == c) cnt++; - else { - cnt = 1; - c = (char)(tolower(*it)); - } - if (cnt >= 3) has_triples = true; - it++; - } - return has_triples; -} - -/* search for occurrences of illegal strings */ -bool namegen_word_has_illegal (namegen_t * data, char * str) { - /* convert word to lowercase */ - char * haystack = TCOD_strdup(str); - int i; - for(i = 0; i < (int)strlen(haystack); i++) haystack[i] = (char)(tolower(haystack[i])); - /* look for illegal strings */ - if (TCOD_list_size(data->illegal_strings) > 0) { - char ** it; - for (it = (char**)TCOD_list_begin(data->illegal_strings); it != (char**)TCOD_list_end(data->illegal_strings); it++) { - if (strstr(haystack,*it) != NULL) { - free(haystack); - return true; - } - } - } - free(haystack); - return false; -} - -/* removes double spaces, as well as leading and ending spaces */ -void namegen_word_prune_spaces (char * str) { - char * s; - char * data = str; - /* remove leading spaces */ - while (data[0] == ' ') memmove (data, data+1, strlen(data)); - /* reduce double spaces to single spaces */ - while ((s = strstr(data," ")) != NULL) memmove (s, s+1, strlen(s)); - /* remove the final space */ - while (data[strlen(data)-1] == ' ') data[strlen(data)-1] = '\0'; -} - -/* prune repeated "syllables", such as Arnarn */ -bool namegen_word_prune_syllables (char *str) { - char * data = TCOD_strdup(str); - size_t len = strlen(data); /* length of the string */ - char check[8]; - size_t i; /* iteration in for loops */ - /* change to lowercase */ - for (i = 0; i < len; i++) data[i] = (char)(tolower(data[i])); - /* start pruning */ - /* 2-character direct repetitions */ - for (i = 0; i < len - 4; i++) { - memset(check,'\0',8); - strncpy(check,data+i,2); - strncat(check,data+i,2); - if (strstr(data,check) != NULL) { - free(data); - return true; - } - } - /* 3-character repetitions (anywhere in the word) - prunes everything, even 10-char repetitions */ - for (i = 0; i < len - 6; i++) { - memset(check,'\0',8); - strncpy(check,data+i,3); - if (strstr(data+i+3,check) != NULL) { - free(data); - return true; - } - } - free(data); - return false; -} - -/* everything stacked together */ -bool namegen_word_is_ok (namegen_t * data, char * str) { - namegen_word_prune_spaces(str); - return - (strlen(str)>0) & - (!namegen_word_has_triples(str)) & - (!namegen_word_has_illegal(data,str)) & - (!namegen_word_prune_syllables(str)); -} - -/* ---------------------------- * - * publicly available functions * - * ---------------------------- */ - -/* parse a new syllable sets file - allocates a new data structure and fills it with necessary content */ -void TCOD_namegen_parse (const char * filename, TCOD_random_t random) { - /* check for file existence */ - FILE * in = fopen(filename,"r"); - if (in == NULL) { - fprintf(stderr,"File \"%s\" not found!\n",filename); - return; - } - fclose(in); - /* set namegen RNG */ - namegen_random = random; - /* run the proper parser - add the file's contents to the data structures */ - namegen_parser_run(filename); -} - -/* generate a name using a given generation rule */ -char * TCOD_namegen_generate_custom (char * name, char * rule, bool allocate) { - namegen_t * data; - size_t buflen = 1024; - char * buf ; - size_t rule_len ; - if (namegen_generator_check(name)) data = namegen_generator_get(name); - else { - fprintf(stderr,"The name \"%s\" has not been found.\n",name); - namegen_get_sets_on_error(); - return NULL; - } - buf = malloc(buflen); - rule_len = strlen(rule); - /* let the show begin! */ - do { - char * it = rule; - memset(buf,'\0',buflen); - while (it <= rule + rule_len) { - /* make sure the buffer is large enough */ - if (strlen(buf) >= buflen) { - char * tmp ; - while (strlen(buf) >= buflen) buflen *= 2; - tmp = malloc(buflen); - strcpy(tmp,buf); - free(buf); - buf = tmp; - } - /* append a normal character */ - if ((*it >= 'a' && *it <= 'z') || (*it >= 'A' && *it <= 'Z') || *it == '\'' || *it == '-') - strncat(buf,it,1); - /* special character */ - else if (*it == '/') { - it++; - strncat(buf,it,1); - } - /* underscore is converted to space */ - else if (*it == '_') strcat(buf," "); - /* interpret a wildcard */ - else if (*it == '$') { - int chance = 100; - it++; - /* food for the randomiser */ - if (*it >= '0' && *it <= '9') { - chance = 0; - while (*it >= '0' && *it <= '9') { - chance *= 10; - chance += (int)(*it) - (int)('0'); - it++; - } - } - /* ok, so the chance of wildcard occurrence is calculated, now evaluate it */ - if (chance >= TCOD_random_get_int(data->random,0,100)) { - TCOD_list_t lst; - switch (*it) { - case 'P': lst = data->syllables_pre; break; - case 's': lst = data->syllables_start; break; - case 'm': lst = data->syllables_middle; break; - case 'e': lst = data->syllables_end; break; - case 'p': lst = data->syllables_post; break; - case 'v': lst = data->vocals; break; - case 'c': lst = data->consonants; break; - case '?': lst = (TCOD_random_get_int(data->random,0,1) == 0 ? data->vocals : data->consonants); break; - default: - fprintf(stderr,"Wrong rules syntax encountered!\n"); - exit(1); - break; - } - if (TCOD_list_size(lst) == 0) - fprintf(stderr,"No data found in the requested string (wildcard *%c). Check your name generation rule %s.\n",*it,rule); - else - strcat(buf,(char*)TCOD_list_get(lst,TCOD_random_get_int(data->random,0,TCOD_list_size(lst)-1))); - } - } - it++; - } - } while (!namegen_word_is_ok(data,buf)); - /* prune the spare spaces out */ - namegen_word_prune_spaces(buf); - /* return the name accordingly */ - if (allocate == true) return buf; - else { - /* take care of ensuring the recipient is sized properly */ - if (namegen_name == NULL) { - namegen_name_size = 64; - namegen_name = malloc (namegen_name_size); - } - while (strlen(buf) > namegen_name_size - 1) { - namegen_name_size *= 2; - free(namegen_name); - namegen_name = malloc(namegen_name_size); - } - strcpy(namegen_name,buf); - free(buf); - return namegen_name; - } -} - -/* generate a name with one of the rules from the file */ -char * TCOD_namegen_generate (char * name, bool allocate) { - namegen_t * data; - int rule_number; - int chance; - char * rule_rolled; - int truncation; - char * rule_parsed ; - char * ret ; - if (namegen_generator_check(name)) data = namegen_generator_get(name); - else { - fprintf(stderr,"The name \"%s\" has not been found.\n",name); - namegen_get_sets_on_error(); - return NULL; - } - /* check if the rules list is present */ - if (TCOD_list_size(data->rules) == 0) { - fprintf(stderr,"The rules list is empty!\n"); - exit(1); - } - /* choose the rule */ - do { - rule_number = TCOD_random_get_int(data->random,0,TCOD_list_size(data->rules)-1); - rule_rolled = (char*)TCOD_list_get(data->rules,rule_number); - chance = 100; - truncation = 0; - if (rule_rolled[0] == '%') { - truncation = 1; - chance = 0; - while (rule_rolled[truncation] >= '0' && rule_rolled[truncation] <= '9') { - chance *= 10; - chance += (int)(rule_rolled[truncation]) - (int)('0'); - truncation++; - } - } - } while (TCOD_random_get_int(data->random,0,100) > chance); - /* OK, we've got ourselves a new rule! */ - rule_parsed = TCOD_strdup(rule_rolled+truncation); - ret = TCOD_namegen_generate_custom(name,rule_parsed,allocate); - free(rule_parsed); - return ret; -} - -/* retrieve the list of all available syllable set names */ -TCOD_list_t TCOD_namegen_get_sets (void) { - TCOD_list_t l = TCOD_list_new(); - if (namegen_generators_list != NULL) { - namegen_t ** it; - for (it = (namegen_t**)TCOD_list_begin(namegen_generators_list); it < (namegen_t**)TCOD_list_end(namegen_generators_list); it++) { - TCOD_list_push(l,(const void*)((*it)->name)); - } - } - return l; -} - -/* delete all the generators */ -void TCOD_namegen_destroy (void) { - /* delete all generators */ - namegen_t ** it; - for (it = (namegen_t**)TCOD_list_begin(namegen_generators_list); it < (namegen_t**)TCOD_list_end(namegen_generators_list); it++) - namegen_generator_delete(*it); - /* clear the generators list */ - TCOD_list_clear(namegen_generators_list); - /* get rid of the parsed files list */ - TCOD_list_clear_and_delete(parsed_files); -} +/* +* libtcod +* Copyright (c) 2008-2018 Jice & Mingos & rmtew +* All rights reserved. +* +* Redistribution and use in source and binary forms, with or without +* modification, are permitted provided that the following conditions are met: +* * Redistributions of source code must retain the above copyright +* notice, this list of conditions and the following disclaimer. +* * Redistributions in binary form must reproduce the above copyright +* notice, this list of conditions and the following disclaimer in the +* documentation and/or other materials provided with the distribution. +* * The name of Jice or Mingos may not be used to endorse or promote +* products derived from this software without specific prior written +* permission. +* +* THIS SOFTWARE IS PROVIDED BY JICE, MINGOS AND RMTEW ``AS IS'' AND ANY +* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED +* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE +* DISCLAIMED. IN NO EVENT SHALL JICE, MINGOS OR RMTEW BE LIABLE FOR ANY +* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES +* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; +* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND +* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS +* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +*/ +/* +* Mingos' NameGen +* This file was written by Dominik "Mingos" Marczuk. +*/ +#include "namegen.h" + +#include +#include +#include +#include + +#include "parser.h" + +/* ------------ * + * the typedefs * + * ------------ */ + +/* the struct containing a definition of an unprocessed syllable set */ +typedef struct { + char * name; + char * vocals; + char * consonants; + char * pre; + char * start; + char * middle; + char * end; + char * post; + char * illegal; + char * rules; +} namegen_syllables_t; + +/* and the generator struct */ +typedef struct TCOD_NameGen { + /* the name that will be called */ + char * name; + /* needs to use a random number generator */ + TCOD_random_t random; + /* the lists with all the data */ + TCOD_list_t vocals; + TCOD_list_t consonants; + TCOD_list_t syllables_pre; + TCOD_list_t syllables_start; + TCOD_list_t syllables_middle; + TCOD_list_t syllables_end; + TCOD_list_t syllables_post; + TCOD_list_t illegal_strings; + TCOD_list_t rules; +} namegen_t; + +/* ------------------- * + * variables and stuff * + * ------------------- */ + +/* the list containing the generators */ +TCOD_list_t namegen_generators_list = NULL; + +/* the file parser */ +TCOD_parser_t namegen_parser; +/* parsed files list */ +TCOD_list_t parsed_files = NULL; +/* the data that will be filled out */ +namegen_syllables_t * parser_data = NULL; +namegen_t * parser_output = NULL; +/* this one's needed to correctly update the generators with RNG pointer */ +TCOD_random_t namegen_random; + +/* the string that will be pointed to upon generating a name */ +char * namegen_name = NULL; +/* for keeping track of the size of output names */ +size_t namegen_name_size; + +/* ------------------------------------ * + * stuff to operate on the syllable set * + * ------------------------------------ */ + +/* initialise a syllable set */ +namegen_syllables_t * namegen_syllables_new (void) { + namegen_syllables_t * data = calloc(sizeof(namegen_syllables_t),1); + return data; +} + +/* free a syllables set */ +void namegen_syllables_delete (namegen_syllables_t * data) { + if (data->vocals) free(data->vocals); + if (data->consonants) free(data->consonants); + if (data->pre) free(data->pre); + if (data->start) free(data->start); + if (data->middle) free(data->middle); + if (data->end) free(data->end); + if (data->post) free(data->post); + if (data->illegal) free(data->illegal); + if (data->rules) free(data->rules); + free(data->name); + free(data); +} + +/* ---------------------------------- * + * stuff to operate on the generators * + * ---------------------------------- */ + +/* create a new generator */ +namegen_t * namegen_generator_new (void) { + namegen_t * data = malloc(sizeof(namegen_t)); + data->name = NULL; + /* assign the rng */ + data->random = TCOD_random_get_instance(); + /* create the lists */ + data->vocals = TCOD_list_new(); + data->consonants = TCOD_list_new(); + data->syllables_pre = TCOD_list_new(); + data->syllables_start = TCOD_list_new(); + data->syllables_middle = TCOD_list_new(); + data->syllables_end = TCOD_list_new(); + data->syllables_post = TCOD_list_new(); + data->illegal_strings = TCOD_list_new(); + data->rules = TCOD_list_new(); + return (TCOD_namegen_t)data; +} + +/* check whether a given generator already exists */ +bool namegen_generator_check (const char * name) { + /* if the list is not created yet, create it */ + if (namegen_generators_list == NULL) { + namegen_generators_list = TCOD_list_new(); + return false; + } + /* otherwise, scan it for the name */ + else { + namegen_t ** it; + for (it = (namegen_t**)TCOD_list_begin(namegen_generators_list); it < (namegen_t**)TCOD_list_end(namegen_generators_list); it++) { + if (strcmp((*it)->name,name) == 0) return true; + } + return false; + } +} + +/* retrieve available generator names */ +void namegen_get_sets_on_error (void) { + namegen_t ** it; + fprintf (stderr,"Registered syllable sets are:\n"); + for (it = (namegen_t**)TCOD_list_begin(namegen_generators_list); it < (namegen_t**)TCOD_list_end(namegen_generators_list); it++) { + fprintf (stderr," * \"%s\"\n",(*it)->name); + } +} + +/* get the appropriate syllables set */ +namegen_t * namegen_generator_get (const char * name) { + if (namegen_generator_check(name) == true) { + namegen_t ** it; + for (it = (namegen_t**)TCOD_list_begin(namegen_generators_list); it != (namegen_t**)TCOD_list_end(namegen_generators_list); it++) { + if (strcmp((*it)->name,name) == 0) return (*it); + } + } + /* and if there's no such set... */ + else + fprintf(stderr,"Generator \"%s\" could not be retrieved.\n",name); + return NULL; +} + + + +/* destroy a generator */ +void namegen_generator_delete (namegen_t * generator) { + namegen_t * data = generator; + free(data->name); + data->random = NULL; + TCOD_list_clear_and_delete(data->vocals); + TCOD_list_clear_and_delete(data->consonants); + TCOD_list_clear_and_delete(data->syllables_pre); + TCOD_list_clear_and_delete(data->syllables_start); + TCOD_list_clear_and_delete(data->syllables_middle); + TCOD_list_clear_and_delete(data->syllables_end); + TCOD_list_clear_and_delete(data->syllables_post); + TCOD_list_clear_and_delete(data->illegal_strings); + TCOD_list_clear_and_delete(data->rules); + free(data); +} + +/* ------------------------------ * + * Populating namegen_t with data * + * ------------------------------ */ + +/* fill the pointed list with syllable data by extracting tokens */ +void namegen_populate_list (char * source, TCOD_list_t list, bool wildcards) { + size_t len = strlen(source); + size_t i = 0; + char * token = malloc(strlen(source)+1); /* tokens will typically be many and very short, but let's be cautious. What if the entire string is a single token?*/ + memset(token,'\0',strlen(source)+1); + do { + /* do the tokenising using an iterator immitation :) */ + char * it = source + i; + /* append a normal character */ + if ((*it >= 'a' && *it <= 'z') || (*it >= 'A' && *it <= 'Z') || *it == '\'' || *it == '-') + strncat(token,it,1); + /* special character */ + else if (*it == '/') { + if (wildcards == true) strncat(token,it++,2); + else strncat(token,++it,1); + i++; + } + /* underscore is converted to space */ + else if (*it == '_') { + if (wildcards == true) strncat(token,it,1); + else strcat(token," "); + } + /* add wildcards if they are allowed */ + else if (wildcards == true && (*it == '$' || *it == '%' || (*it >= '0' && *it <= '9'))) + strncat(token,it,1); + /* all other characters are treated as separators and cause adding the current token to the list */ + else if (strlen(token) > 0) { + TCOD_list_push(list,TCOD_strdup(token)); + memset(token,'\0',strlen(source)+1); + } + } while (++i <= len); + free(token); +} + +/* populate all lists of a namegen_t struct */ +void namegen_populate (namegen_t * dst, namegen_syllables_t * src) { + if (dst == NULL || src == NULL) { + fprintf(stderr,"Couldn't populate the name generator with data.\n"); + exit(1); + } + if (src->vocals != NULL) namegen_populate_list (src->vocals,dst->vocals,false); + if (src->consonants != NULL) namegen_populate_list (src->consonants,dst->consonants,false); + if (src->pre != NULL) namegen_populate_list (src->pre,dst->syllables_pre,false); + if (src->start != NULL) namegen_populate_list (src->start,dst->syllables_start,false); + if (src->middle != NULL) namegen_populate_list (src->middle,dst->syllables_middle,false); + if (src->end != NULL) namegen_populate_list (src->end,dst->syllables_end,false); + if (src->post != NULL) namegen_populate_list (src->post,dst->syllables_post,false); + if (src->illegal != NULL) namegen_populate_list (src->illegal,dst->illegal_strings,false); + if (src->rules != NULL) namegen_populate_list (src->rules,dst->rules,true); + dst->name = TCOD_strdup(src->name); +} + +/* -------------------- * + * parser-related stuff * + * -------------------- */ + +/* preparing the parser */ +void namegen_parser_prepare (void) { + static bool namegen_parser_ready = false; + if (namegen_parser_ready == true) return; + else { + TCOD_parser_struct_t parser_name ; + namegen_parser = TCOD_parser_new(); + parser_name = TCOD_parser_new_struct(namegen_parser, "name"); + TCOD_struct_add_property(parser_name, "phonemesVocals", TCOD_TYPE_STRING, false); + TCOD_struct_add_property(parser_name, "phonemesConsonants", TCOD_TYPE_STRING, false); + TCOD_struct_add_property(parser_name, "syllablesPre", TCOD_TYPE_STRING, false); + TCOD_struct_add_property(parser_name, "syllablesStart", TCOD_TYPE_STRING, false); + TCOD_struct_add_property(parser_name, "syllablesMiddle", TCOD_TYPE_STRING, false); + TCOD_struct_add_property(parser_name, "syllablesEnd", TCOD_TYPE_STRING, false); + TCOD_struct_add_property(parser_name, "syllablesPost", TCOD_TYPE_STRING, false); + TCOD_struct_add_property(parser_name, "illegal", TCOD_TYPE_STRING, false); + TCOD_struct_add_property(parser_name, "rules", TCOD_TYPE_STRING, true); + namegen_parser_ready = true; + } +} + +/* parser listener */ +bool namegen_parser_new_struct (TCOD_parser_struct_t str, const char *name) { + parser_data = namegen_syllables_new(); + return true; +} + +bool namegen_parser_flag (const char *name) { + return true; +} + +bool namegen_parser_property(const char *name, TCOD_value_type_t type, TCOD_value_t value) { + if (strcmp(name,"syllablesStart") == 0) parser_data->start = TCOD_strdup(value.s); + else if (strcmp(name,"syllablesMiddle") == 0) parser_data->middle = TCOD_strdup(value.s); + else if (strcmp(name,"syllablesEnd") == 0) parser_data->end = TCOD_strdup(value.s); + else if (strcmp(name,"syllablesPre") == 0) parser_data->pre = TCOD_strdup(value.s); + else if (strcmp(name,"syllablesPost") == 0) parser_data->post = TCOD_strdup(value.s); + else if (strcmp(name,"phonemesVocals") == 0) parser_data->vocals = TCOD_strdup(value.s); + else if (strcmp(name,"phonemesConsonants") == 0) parser_data->consonants = TCOD_strdup(value.s); + else if (strcmp(name,"rules") == 0) parser_data->rules = TCOD_strdup(value.s); + else if (strcmp(name,"illegal") == 0) { /* illegal strings are converted to lowercase */ + char * str ; + int i; + parser_data->illegal = TCOD_strdup(value.s); + str = parser_data->illegal; + for(i = 0; i < (int)strlen(str); i++) str[i] = (char)(tolower(str[i])); + } + else return false; + return true; +} + +bool namegen_parser_end_struct(TCOD_parser_struct_t str, const char *name) { + /* if there's no syllable set by this name, add it to the list */ + if (namegen_generator_check(name) == false) { + parser_data->name = TCOD_strdup(name); + parser_output = namegen_generator_new(); + namegen_populate(parser_output,parser_data); + parser_output->random = namegen_random; + if (namegen_generators_list == NULL) namegen_generators_list = TCOD_list_new(); + TCOD_list_push(namegen_generators_list, (const void*)parser_output); + } + /* free the allocated memory to prevent a memory leak */ + namegen_syllables_delete(parser_data); + return true; +} + +void namegen_parser_error(const char *msg) { + fprintf(stderr,"%s\n",msg); + exit(1); +} + +TCOD_parser_listener_t namegen_listener = { + namegen_parser_new_struct, + namegen_parser_flag, + namegen_parser_property, + namegen_parser_end_struct, + namegen_parser_error +}; + +/* run the parser */ +void namegen_parser_run (const char * filename) { + char ** it; + /* prepare the parser --- this will be executed only once */ + namegen_parser_prepare(); + if (parsed_files == NULL) parsed_files = TCOD_list_new(); + if (TCOD_list_size(parsed_files) > 0) { + for (it = (char **)TCOD_list_begin(parsed_files); it != (char **)TCOD_list_end(parsed_files); it++) + if (strcmp(*it,filename) == 0) return; + } + /* if the file hasn't been parsed yet, add its name to the list so that it's never parsed twice */ + TCOD_list_push(parsed_files,(const void *)TCOD_strdup(filename)); + /* run the parser */ + TCOD_parser_run(namegen_parser,filename,&namegen_listener); +} + +/* --------------- * + * rubbish pruning * + * --------------- */ + +/* search for occurrences of triple characters (case-insensitive) */ +bool namegen_word_has_triples (char * str) { + char * it = str; + char c = (char)(tolower(*it)); + int cnt = 1; + bool has_triples = false; + it++; + while (*it != '\0') { + if ((char)(tolower(*it)) == c) cnt++; + else { + cnt = 1; + c = (char)(tolower(*it)); + } + if (cnt >= 3) has_triples = true; + it++; + } + return has_triples; +} + +/* search for occurrences of illegal strings */ +bool namegen_word_has_illegal (namegen_t * data, char * str) { + /* convert word to lowercase */ + char * haystack = TCOD_strdup(str); + int i; + for(i = 0; i < (int)strlen(haystack); i++) haystack[i] = (char)(tolower(haystack[i])); + /* look for illegal strings */ + if (TCOD_list_size(data->illegal_strings) > 0) { + char ** it; + for (it = (char**)TCOD_list_begin(data->illegal_strings); it != (char**)TCOD_list_end(data->illegal_strings); it++) { + if (strstr(haystack,*it) != NULL) { + free(haystack); + return true; + } + } + } + free(haystack); + return false; +} + +/* removes double spaces, as well as leading and ending spaces */ +void namegen_word_prune_spaces (char * str) { + char * s; + char * data = str; + /* remove leading spaces */ + while (data[0] == ' ') memmove (data, data+1, strlen(data)); + /* reduce double spaces to single spaces */ + while ((s = strstr(data," ")) != NULL) memmove (s, s+1, strlen(s)); + /* remove the final space */ + while (data[strlen(data)-1] == ' ') data[strlen(data)-1] = '\0'; +} + +/* prune repeated "syllables", such as Arnarn */ +bool namegen_word_prune_syllables (char *str) { + char * data = TCOD_strdup(str); + size_t len = strlen(data); /* length of the string */ + char check[8]; + size_t i; /* iteration in for loops */ + /* change to lowercase */ + for (i = 0; i < len; i++) data[i] = (char)(tolower(data[i])); + /* start pruning */ + /* 2-character direct repetitions */ + for (i = 0; i < len - 4; i++) { + memset(check,'\0',8); + strncpy(check,data+i,2); + strncat(check,data+i,2); + if (strstr(data,check) != NULL) { + free(data); + return true; + } + } + /* 3-character repetitions (anywhere in the word) - prunes everything, even 10-char repetitions */ + for (i = 0; i < len - 6; i++) { + memset(check,'\0',8); + strncpy(check,data+i,3); + if (strstr(data+i+3,check) != NULL) { + free(data); + return true; + } + } + free(data); + return false; +} + +/* everything stacked together */ +bool namegen_word_is_ok (namegen_t * data, char * str) { + namegen_word_prune_spaces(str); + return + (strlen(str)>0) & + (!namegen_word_has_triples(str)) & + (!namegen_word_has_illegal(data,str)) & + (!namegen_word_prune_syllables(str)); +} + +/* ---------------------------- * + * publicly available functions * + * ---------------------------- */ + +/* parse a new syllable sets file - allocates a new data structure and fills it with necessary content */ +void TCOD_namegen_parse (const char * filename, TCOD_random_t random) { + /* check for file existence */ + FILE * in = fopen(filename,"r"); + if (in == NULL) { + fprintf(stderr,"File \"%s\" not found!\n",filename); + return; + } + fclose(in); + /* set namegen RNG */ + namegen_random = random; + /* run the proper parser - add the file's contents to the data structures */ + namegen_parser_run(filename); +} + +/* generate a name using a given generation rule */ +char * TCOD_namegen_generate_custom (char * name, char * rule, bool allocate) { + namegen_t * data; + size_t buflen = 1024; + char * buf ; + size_t rule_len ; + if (namegen_generator_check(name)) data = namegen_generator_get(name); + else { + fprintf(stderr,"The name \"%s\" has not been found.\n",name); + namegen_get_sets_on_error(); + return NULL; + } + buf = malloc(buflen); + rule_len = strlen(rule); + /* let the show begin! */ + do { + char * it = rule; + memset(buf,'\0',buflen); + while (it <= rule + rule_len) { + /* make sure the buffer is large enough */ + if (strlen(buf) >= buflen) { + char * tmp ; + while (strlen(buf) >= buflen) buflen *= 2; + tmp = malloc(buflen); + strcpy(tmp,buf); + free(buf); + buf = tmp; + } + /* append a normal character */ + if ((*it >= 'a' && *it <= 'z') || (*it >= 'A' && *it <= 'Z') || *it == '\'' || *it == '-') + strncat(buf,it,1); + /* special character */ + else if (*it == '/') { + it++; + strncat(buf,it,1); + } + /* underscore is converted to space */ + else if (*it == '_') strcat(buf," "); + /* interpret a wildcard */ + else if (*it == '$') { + int chance = 100; + it++; + /* food for the randomiser */ + if (*it >= '0' && *it <= '9') { + chance = 0; + while (*it >= '0' && *it <= '9') { + chance *= 10; + chance += (int)(*it) - (int)('0'); + it++; + } + } + /* ok, so the chance of wildcard occurrence is calculated, now evaluate it */ + if (chance >= TCOD_random_get_int(data->random,0,100)) { + TCOD_list_t lst; + switch (*it) { + case 'P': lst = data->syllables_pre; break; + case 's': lst = data->syllables_start; break; + case 'm': lst = data->syllables_middle; break; + case 'e': lst = data->syllables_end; break; + case 'p': lst = data->syllables_post; break; + case 'v': lst = data->vocals; break; + case 'c': lst = data->consonants; break; + case '?': lst = (TCOD_random_get_int(data->random,0,1) == 0 ? data->vocals : data->consonants); break; + default: + fprintf(stderr,"Wrong rules syntax encountered!\n"); + exit(1); + break; + } + if (TCOD_list_size(lst) == 0) + fprintf(stderr,"No data found in the requested string (wildcard *%c). Check your name generation rule %s.\n",*it,rule); + else + strcat(buf,(char*)TCOD_list_get(lst,TCOD_random_get_int(data->random,0,TCOD_list_size(lst)-1))); + } + } + it++; + } + } while (!namegen_word_is_ok(data,buf)); + /* prune the spare spaces out */ + namegen_word_prune_spaces(buf); + /* return the name accordingly */ + if (allocate == true) return buf; + else { + /* take care of ensuring the recipient is sized properly */ + if (namegen_name == NULL) { + namegen_name_size = 64; + namegen_name = malloc (namegen_name_size); + } + while (strlen(buf) > namegen_name_size - 1) { + namegen_name_size *= 2; + free(namegen_name); + namegen_name = malloc(namegen_name_size); + } + strcpy(namegen_name,buf); + free(buf); + return namegen_name; + } +} + +/* generate a name with one of the rules from the file */ +char * TCOD_namegen_generate (char * name, bool allocate) { + namegen_t * data; + int rule_number; + int chance; + char * rule_rolled; + int truncation; + char * rule_parsed ; + char * ret ; + if (namegen_generator_check(name)) data = namegen_generator_get(name); + else { + fprintf(stderr,"The name \"%s\" has not been found.\n",name); + namegen_get_sets_on_error(); + return NULL; + } + /* check if the rules list is present */ + if (TCOD_list_size(data->rules) == 0) { + fprintf(stderr,"The rules list is empty!\n"); + exit(1); + } + /* choose the rule */ + do { + rule_number = TCOD_random_get_int(data->random,0,TCOD_list_size(data->rules)-1); + rule_rolled = (char*)TCOD_list_get(data->rules,rule_number); + chance = 100; + truncation = 0; + if (rule_rolled[0] == '%') { + truncation = 1; + chance = 0; + while (rule_rolled[truncation] >= '0' && rule_rolled[truncation] <= '9') { + chance *= 10; + chance += (int)(rule_rolled[truncation]) - (int)('0'); + truncation++; + } + } + } while (TCOD_random_get_int(data->random,0,100) > chance); + /* OK, we've got ourselves a new rule! */ + rule_parsed = TCOD_strdup(rule_rolled+truncation); + ret = TCOD_namegen_generate_custom(name,rule_parsed,allocate); + free(rule_parsed); + return ret; +} + +/* retrieve the list of all available syllable set names */ +TCOD_list_t TCOD_namegen_get_sets (void) { + TCOD_list_t l = TCOD_list_new(); + if (namegen_generators_list != NULL) { + namegen_t ** it; + for (it = (namegen_t**)TCOD_list_begin(namegen_generators_list); it < (namegen_t**)TCOD_list_end(namegen_generators_list); it++) { + TCOD_list_push(l,(const void*)((*it)->name)); + } + } + return l; +} + +/* delete all the generators */ +void TCOD_namegen_destroy (void) { + /* delete all generators */ + namegen_t ** it; + for (it = (namegen_t**)TCOD_list_begin(namegen_generators_list); it < (namegen_t**)TCOD_list_end(namegen_generators_list); it++) + namegen_generator_delete(*it); + /* clear the generators list */ + TCOD_list_clear(namegen_generators_list); + /* get rid of the parsed files list */ + TCOD_list_clear_and_delete(parsed_files); +} diff --git a/tcod_sys/libtcod/src/noise.cpp b/tcod_sys/libtcod/src/libtcod/noise.cpp similarity index 97% rename from tcod_sys/libtcod/src/noise.cpp rename to tcod_sys/libtcod/src/libtcod/noise.cpp index d731cb9dc..cce723f70 100644 --- a/tcod_sys/libtcod/src/noise.cpp +++ b/tcod_sys/libtcod/src/libtcod/noise.cpp @@ -1,72 +1,72 @@ -/* -* libtcod -* Copyright (c) 2008-2018 Jice & Mingos & rmtew -* All rights reserved. -* -* Redistribution and use in source and binary forms, with or without -* modification, are permitted provided that the following conditions are met: -* * Redistributions of source code must retain the above copyright -* notice, this list of conditions and the following disclaimer. -* * Redistributions in binary form must reproduce the above copyright -* notice, this list of conditions and the following disclaimer in the -* documentation and/or other materials provided with the distribution. -* * The name of Jice or Mingos may not be used to endorse or promote -* products derived from this software without specific prior written -* permission. -* -* THIS SOFTWARE IS PROVIDED BY JICE, MINGOS AND RMTEW ``AS IS'' AND ANY -* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED -* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE -* DISCLAIMED. IN NO EVENT SHALL JICE, MINGOS OR RMTEW BE LIABLE FOR ANY -* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES -* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; -* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND -* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS -* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. -*/ -#include - -#include -TCODNoise::TCODNoise(int dimensions, TCOD_noise_type_t type) { - data = TCOD_noise_new(dimensions, TCOD_NOISE_DEFAULT_HURST, TCOD_NOISE_DEFAULT_LACUNARITY, TCODRandom::getInstance()->data); - TCOD_noise_set_type(data,type); -} - -TCODNoise::TCODNoise(int dimensions, TCODRandom *random, TCOD_noise_type_t type) { - data = TCOD_noise_new(dimensions, TCOD_NOISE_DEFAULT_HURST, TCOD_NOISE_DEFAULT_LACUNARITY, random->data); - TCOD_noise_set_type(data,type); -} - -TCODNoise::TCODNoise(int dimensions, float hurst, float lacunarity, TCOD_noise_type_t type) { - data = TCOD_noise_new(dimensions, hurst, lacunarity, TCODRandom::getInstance()->data); - TCOD_noise_set_type(data,type); -} - -TCODNoise::TCODNoise(int dimensions, float hurst, float lacunarity, TCODRandom *random, TCOD_noise_type_t type) { - data = TCOD_noise_new(dimensions, hurst, lacunarity, random->data); - TCOD_noise_set_type(data,type); -} - -void TCODNoise::setType(TCOD_noise_type_t type) { - TCOD_noise_set_type(data,type); -} - -float TCODNoise::get (float *f, TCOD_noise_type_t type) { - if (type == TCOD_NOISE_DEFAULT) return TCOD_noise_get(data,f); - else return TCOD_noise_get_ex(data,f,type); -} - -float TCODNoise::getFbm (float *f, float octaves, TCOD_noise_type_t type) { - if (type == TCOD_NOISE_DEFAULT) return TCOD_noise_get_fbm(data,f,octaves); - else return TCOD_noise_get_fbm_ex(data,f,octaves,type); -} - -float TCODNoise::getTurbulence (float *f, float octaves, TCOD_noise_type_t type) { - if (type == TCOD_NOISE_DEFAULT) return TCOD_noise_get_turbulence(data,f,octaves); - else return TCOD_noise_get_turbulence_ex(data,f,octaves,type); -} - -TCODNoise::~TCODNoise() { - TCOD_noise_delete(data); -} +/* +* libtcod +* Copyright (c) 2008-2018 Jice & Mingos & rmtew +* All rights reserved. +* +* Redistribution and use in source and binary forms, with or without +* modification, are permitted provided that the following conditions are met: +* * Redistributions of source code must retain the above copyright +* notice, this list of conditions and the following disclaimer. +* * Redistributions in binary form must reproduce the above copyright +* notice, this list of conditions and the following disclaimer in the +* documentation and/or other materials provided with the distribution. +* * The name of Jice or Mingos may not be used to endorse or promote +* products derived from this software without specific prior written +* permission. +* +* THIS SOFTWARE IS PROVIDED BY JICE, MINGOS AND RMTEW ``AS IS'' AND ANY +* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED +* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE +* DISCLAIMED. IN NO EVENT SHALL JICE, MINGOS OR RMTEW BE LIABLE FOR ANY +* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES +* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; +* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND +* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS +* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +*/ +#include "noise.hpp" + +#include +TCODNoise::TCODNoise(int dimensions, TCOD_noise_type_t type) { + data = TCOD_noise_new(dimensions, TCOD_NOISE_DEFAULT_HURST, TCOD_NOISE_DEFAULT_LACUNARITY, TCODRandom::getInstance()->data); + TCOD_noise_set_type(data,type); +} + +TCODNoise::TCODNoise(int dimensions, TCODRandom *random, TCOD_noise_type_t type) { + data = TCOD_noise_new(dimensions, TCOD_NOISE_DEFAULT_HURST, TCOD_NOISE_DEFAULT_LACUNARITY, random->data); + TCOD_noise_set_type(data,type); +} + +TCODNoise::TCODNoise(int dimensions, float hurst, float lacunarity, TCOD_noise_type_t type) { + data = TCOD_noise_new(dimensions, hurst, lacunarity, TCODRandom::getInstance()->data); + TCOD_noise_set_type(data,type); +} + +TCODNoise::TCODNoise(int dimensions, float hurst, float lacunarity, TCODRandom *random, TCOD_noise_type_t type) { + data = TCOD_noise_new(dimensions, hurst, lacunarity, random->data); + TCOD_noise_set_type(data,type); +} + +void TCODNoise::setType(TCOD_noise_type_t type) { + TCOD_noise_set_type(data,type); +} + +float TCODNoise::get (float *f, TCOD_noise_type_t type) { + if (type == TCOD_NOISE_DEFAULT) return TCOD_noise_get(data,f); + else return TCOD_noise_get_ex(data,f,type); +} + +float TCODNoise::getFbm (float *f, float octaves, TCOD_noise_type_t type) { + if (type == TCOD_NOISE_DEFAULT) return TCOD_noise_get_fbm(data,f,octaves); + else return TCOD_noise_get_fbm_ex(data,f,octaves,type); +} + +float TCODNoise::getTurbulence (float *f, float octaves, TCOD_noise_type_t type) { + if (type == TCOD_NOISE_DEFAULT) return TCOD_noise_get_turbulence(data,f,octaves); + else return TCOD_noise_get_turbulence_ex(data,f,octaves,type); +} + +TCODNoise::~TCODNoise() { + TCOD_noise_delete(data); +} diff --git a/tcod_sys/libtcod/include/noise.h b/tcod_sys/libtcod/src/libtcod/noise.h similarity index 85% rename from tcod_sys/libtcod/include/noise.h rename to tcod_sys/libtcod/src/libtcod/noise.h index e812a7053..d8afab8ba 100644 --- a/tcod_sys/libtcod/include/noise.h +++ b/tcod_sys/libtcod/src/libtcod/noise.h @@ -28,13 +28,9 @@ #ifndef _TCOD_PERLIN_H #define _TCOD_PERLIN_H -#include "libtcod_portability.h" +#include "portability.h" #include "mersenne_types.h" - -#ifdef __cplusplus -extern "C" { -#endif -typedef void *TCOD_noise_t; +#include "noise_defaults.h" typedef enum { TCOD_NOISE_PERLIN = 1, @@ -43,8 +39,25 @@ typedef enum { TCOD_NOISE_DEFAULT = 0 } TCOD_noise_type_t; -#include "noise_defaults.h" - +typedef struct TCOD_Noise { + int ndim; + /** Randomized map of indexes into buffer */ + unsigned char map[256]; + /** Random 256 x ndim buffer */ + float buffer[256][TCOD_NOISE_MAX_DIMENSIONS]; + /* fractal stuff */ + float H; + float lacunarity; + float exponent[TCOD_NOISE_MAX_OCTAVES]; + float *waveletTileData; + TCOD_random_t rand; + /* noise type */ + TCOD_noise_type_t noise_type; +} TCOD_Noise; +typedef TCOD_Noise *TCOD_noise_t; +#ifdef __cplusplus +extern "C" { +#endif /* create a new noise object */ TCODLIB_API TCOD_noise_t TCOD_noise_new(int dimensions, float hurst, float lacunarity, TCOD_random_t random); diff --git a/tcod_sys/libtcod/include/noise.hpp b/tcod_sys/libtcod/src/libtcod/noise.hpp similarity index 100% rename from tcod_sys/libtcod/include/noise.hpp rename to tcod_sys/libtcod/src/libtcod/noise.hpp diff --git a/tcod_sys/libtcod/src/noise_c.c b/tcod_sys/libtcod/src/libtcod/noise_c.c similarity index 95% rename from tcod_sys/libtcod/src/noise_c.c rename to tcod_sys/libtcod/src/libtcod/noise_c.c index c91d23491..02c10d716 100644 --- a/tcod_sys/libtcod/src/noise_c.c +++ b/tcod_sys/libtcod/src/libtcod/noise_c.c @@ -1,805 +1,793 @@ -/* -* libtcod -* Copyright (c) 2008-2018 Jice & Mingos & rmtew -* All rights reserved. -* -* Redistribution and use in source and binary forms, with or without -* modification, are permitted provided that the following conditions are met: -* * Redistributions of source code must retain the above copyright -* notice, this list of conditions and the following disclaimer. -* * Redistributions in binary form must reproduce the above copyright -* notice, this list of conditions and the following disclaimer in the -* documentation and/or other materials provided with the distribution. -* * The name of Jice or Mingos may not be used to endorse or promote -* products derived from this software without specific prior written -* permission. -* -* THIS SOFTWARE IS PROVIDED BY JICE, MINGOS AND RMTEW ``AS IS'' AND ANY -* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED -* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE -* DISCLAIMED. IN NO EVENT SHALL JICE, MINGOS OR RMTEW BE LIABLE FOR ANY -* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES -* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; -* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND -* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS -* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. -*/ -#include - -#include -#include -#include - -#include -#include - -#define WAVELET_TILE_SIZE 32 -#define WAVELET_ARAD 16 - -#define SIMPLEX_SCALE 0.5f -#define WAVELET_SCALE 2.0f - -typedef struct { - int ndim; - unsigned char map[256]; /* Randomized map of indexes into buffer */ - float buffer[256][TCOD_NOISE_MAX_DIMENSIONS]; /* Random 256 x ndim buffer */ - /* fractal stuff */ - float H; - float lacunarity; - float exponent[TCOD_NOISE_MAX_OCTAVES]; - float *waveletTileData; - TCOD_random_t rand; - /* noise type */ - TCOD_noise_type_t noise_type; -} perlin_data_t; - -static float lattice( perlin_data_t *data, int ix, float fx, int iy, float fy, int iz, float fz, int iw, float fw) -{ - int n[4] = {ix, iy, iz, iw}; - float f[4] = {fx, fy, fz, fw}; - int nIndex = 0; - int i; - float value = 0; - for(i=0; indim; i++) - nIndex = data->map[(nIndex + n[i]) & 0xFF]; - for(i=0; indim; i++) - value += data->buffer[nIndex][i] * f[i]; - return value; -} - -#define DEFAULT_SEED 0x15687436 -#define DELTA 1e-6f -#define SWAP(a, b, t) t = a; a = b; b = t - -#define FLOOR(a) ((a)> 0 ? ((int)a) : (((int)a)-1) ) -#define CUBIC(a) ( a * a * (3 - 2*a) ) - -static void normalize(perlin_data_t *data, float *f) -{ - float magnitude = 0; - int i; - for(i=0; indim; i++) - magnitude += f[i]*f[i]; - magnitude = 1.0f / (float)sqrt(magnitude); - for(i=0; indim; i++) - f[i] *= magnitude; -} - - -TCOD_noise_t TCOD_noise_new(int ndim, float hurst, float lacunarity, TCOD_random_t random) -{ - perlin_data_t *data=(perlin_data_t *)calloc(sizeof(perlin_data_t),1); - int i, j; - unsigned char tmp; - float f = 1; - data->rand = random ? random : TCOD_random_get_instance(); - data->ndim = ndim; - for(i=0; i<256; i++) - { - data->map[i] = (unsigned char)i; - for(j=0; jndim; j++) - data->buffer[i][j] = TCOD_random_get_float(data->rand,-0.5, 0.5); - normalize(data,data->buffer[i]); - } - - while(--i) - { - j = TCOD_random_get_int(data->rand,0, 255); - SWAP(data->map[i], data->map[j], tmp); - } - - data->H = hurst; - data->lacunarity = lacunarity; - for(i=0; iexponent[i] = 1.0f / f; - f *= lacunarity; - } - data->noise_type = TCOD_NOISE_DEFAULT; - return (TCOD_noise_t)data; -} - -float TCOD_noise_perlin( TCOD_noise_t noise, float *f ) -{ - perlin_data_t *data=(perlin_data_t *)noise; - int n[TCOD_NOISE_MAX_DIMENSIONS]; /* Indexes to pass to lattice function */ - int i; - float r[TCOD_NOISE_MAX_DIMENSIONS]; /* Remainders to pass to lattice function */ - float w[TCOD_NOISE_MAX_DIMENSIONS]; /* Cubic values to pass to interpolation function */ - float value; - - for(i=0; indim; i++) - { - n[i] = FLOOR(f[i]); - r[i] = f[i] - n[i]; - w[i] = CUBIC(r[i]); - } - - switch(data->ndim) - { - case 1: - value = LERP(lattice(data,n[0], r[0],0,0,0,0,0,0), - lattice(data,n[0]+1, r[0]-1,0,0,0,0,0,0), - w[0]); - break; - case 2: - value = LERP(LERP(lattice(data,n[0], r[0], n[1], r[1],0,0,0,0), - lattice(data,n[0]+1, r[0]-1, n[1], r[1],0,0,0,0), - w[0]), - LERP(lattice(data,n[0], r[0], n[1]+1, r[1]-1,0,0,0,0), - lattice(data,n[0]+1, r[0]-1, n[1]+1, r[1]-1,0,0,0,0), - w[0]), - w[1]); - break; - case 3: - value = LERP(LERP(LERP(lattice(data,n[0], r[0], n[1], r[1], n[2], r[2],0,0), - lattice(data,n[0]+1, r[0]-1, n[1], r[1], n[2], r[2],0,0), - w[0]), - LERP(lattice(data,n[0], r[0], n[1]+1, r[1]-1, n[2], r[2],0,0), - lattice(data,n[0]+1, r[0]-1, n[1]+1, r[1]-1, n[2], r[2],0,0), - w[0]), - w[1]), - LERP(LERP(lattice(data,n[0], r[0], n[1], r[1], n[2]+1, r[2]-1,0,0), - lattice(data,n[0]+1, r[0]-1, n[1], r[1], n[2]+1, r[2]-1,0,0), - w[0]), - LERP(lattice(data,n[0], r[0], n[1]+1, r[1]-1, n[2]+1, r[2]-1,0,0), - lattice(data,n[0]+1, r[0]-1, n[1]+1, r[1]-1, n[2]+1, r[2]-1,0,0), - w[0]), - w[1]), - w[2]); - break; - case 4: - default: - value = LERP(LERP(LERP(LERP(lattice(data,n[0], r[0], n[1], r[1], n[2], r[2], n[3], r[3]), - lattice(data,n[0]+1, r[0]-1, n[1], r[1], n[2], r[2], n[3], r[3]), - w[0]), - LERP(lattice(data,n[0], r[0], n[1]+1, r[1]-1, n[2], r[2], n[3], r[3]), - lattice(data,n[0]+1, r[0]-1, n[1]+1, r[1]-1, n[2], r[2], n[3], r[3]), - w[0]), - w[1]), - LERP(LERP(lattice(data,n[0], r[0], n[1], r[1], n[2]+1, r[2]-1, n[3], r[3]), - lattice(data,n[0]+1, r[0]-1, n[1], r[1], n[2]+1, r[2]-1, n[3], r[3]), - w[0]), - LERP(lattice(data,n[0], r[0], n[1]+1, r[1]-1, n[2]+1, r[2]-1,0,0), - lattice(data,n[0]+1, r[0]-1, n[1]+1, r[1]-1, n[2]+1, r[2]-1, n[3], r[3]), - w[0]), - w[1]), - w[2]), - LERP(LERP(LERP(lattice(data,n[0], r[0], n[1], r[1], n[2], r[2], n[3]+1, r[3]-1), - lattice(data,n[0]+1, r[0]-1, n[1], r[1], n[2], r[2], n[3]+1, r[3]-1), - w[0]), - LERP(lattice(data,n[0], r[0], n[1]+1, r[1]-1, n[2], r[2], n[3]+1, r[3]-1), - lattice(data,n[0]+1, r[0]-1, n[1]+1, r[1]-1, n[2], r[2], n[3]+1, r[3]-1), - w[0]), - w[1]), - LERP(LERP(lattice(data,n[0], r[0], n[1], r[1], n[2]+1, r[2]-1, n[3]+1, r[3]-1), - lattice(data,n[0]+1, r[0]-1, n[1], r[1], n[2]+1, r[2]-1, n[3]+1, r[3]-1), - w[0]), - LERP(lattice(data,n[0], r[0], n[1]+1, r[1]-1, n[2]+1, r[2]-1,0,0), - lattice(data,n[0]+1, r[0]-1, n[1]+1, r[1]-1, n[2]+1, r[2]-1, n[3]+1, r[3]-1), - w[0]), - w[1]), - w[2]), - w[3]); - break; - } - return CLAMP(-0.99999f, 0.99999f, value); -} - -static int absmod(int x, int n) { - int m=x%n; - return m < 0 ? m+n : m; -} - -/* simplex noise, adapted from Ken Perlin's presentation at Siggraph 2001 */ -/* and Stefan Gustavson implementation */ - -#define TCOD_NOISE_SIMPLEX_GRADIENT_1D(n,h,x) { float grad; h &= 0xF; grad=1.0f+(h & 7); if ( h & 8 ) grad = -grad; n = grad * x; } - -#define TCOD_NOISE_SIMPLEX_GRADIENT_2D(n,h,x,y) { float u,v; h &= 0x7; if ( h < 4 ) { u=x; v=2.0f*y; } else { u=y; v=2.0f*x; } n = ((h & 1) ? -u : u) + ((h & 2) ? -v :v ); } - -#define TCOD_NOISE_SIMPLEX_GRADIENT_3D(n,h,x,y,z) { float u,v; h &= 0xF; u = (h < 8 ? x : y); v = (h < 4 ? y : ( h == 12 || h == 14 ? x : z ) ); n= ((h & 1) ? -u : u ) + ((h & 2) ? -v : v); } - -#define TCOD_NOISE_SIMPLEX_GRADIENT_4D(n,h,x,y,z,t) { float u,v,w; h &= 0x1F; u = (h < 24 ? x:y); v = (h < 16 ? y:z); w = (h < 8 ? z:t); n= ((h & 1) ? -u : u ) + ((h & 2) ? -v : v) + ((h & 4) ? -w : w);} - -static float simplex[64][4] = { - {0,1,2,3},{0,1,3,2},{0,0,0,0},{0,2,3,1},{0,0,0,0},{0,0,0,0},{0,0,0,0},{1,2,3,0}, - {0,2,1,3},{0,0,0,0},{0,3,1,2},{0,3,2,1},{0,0,0,0},{0,0,0,0},{0,0,0,0},{1,3,2,0}, - {0,0,0,0},{0,0,0,0},{0,0,0,0},{0,0,0,0},{0,0,0,0},{0,0,0,0},{0,0,0,0},{0,0,0,0}, - {1,2,0,3},{0,0,0,0},{1,3,0,2},{0,0,0,0},{0,0,0,0},{0,0,0,0},{2,3,0,1},{2,3,1,0}, - {1,0,2,3},{1,0,3,2},{0,0,0,0},{0,0,0,0},{0,0,0,0},{2,0,3,1},{0,0,0,0},{2,1,3,0}, - {0,0,0,0},{0,0,0,0},{0,0,0,0},{0,0,0,0},{0,0,0,0},{0,0,0,0},{0,0,0,0},{0,0,0,0}, - {2,0,1,3},{0,0,0,0},{0,0,0,0},{0,0,0,0},{3,0,1,2},{3,0,2,1},{0,0,0,0},{3,1,2,0}, - {2,1,0,3},{0,0,0,0},{0,0,0,0},{0,0,0,0},{3,1,0,2},{0,0,0,0},{3,2,0,1},{3,2,1,0}, - -}; - -float TCOD_noise_simplex(TCOD_noise_t noise, float *f) { - perlin_data_t *data=(perlin_data_t *)noise; - switch(data->ndim) { - case 1 : - { - int i0=(int)FLOOR(f[0]*SIMPLEX_SCALE); - int i1=i0+1; - float x0 = f[0]*SIMPLEX_SCALE - i0; - float x1 = x0 - 1.0f; - float t0 = 1.0f - x0*x0; - float t1 = 1.0f - x1*x1; - float n0,n1; - t0 = t0*t0; - t1 = t1*t1; - i0=data->map[i0&0xFF]; - TCOD_NOISE_SIMPLEX_GRADIENT_1D(n0,i0,x0); - n0*=t0*t0; - i1=data->map[i1&0xFF]; - TCOD_NOISE_SIMPLEX_GRADIENT_1D(n1,i1,x1); - n1*=t1*t1; - return 0.25f * (n0+n1); - } - break; - case 2 : - { - #define F2 0.366025403f /* 0.5f * (sqrtf(3.0f)-1.0f); */ - #define G2 0.211324865f /* (3.0f - sqrtf(3.0f))/6.0f; */ - - float s = (f[0]+f[1])*F2*SIMPLEX_SCALE; - float xs = f[0]*SIMPLEX_SCALE+s; - float ys = f[1]*SIMPLEX_SCALE+s; - int i=FLOOR(xs); - int j=FLOOR(ys); - float t = (i+j)*G2; - float xo = i-t; - float yo = j-t; - float x0 = f[0]*SIMPLEX_SCALE-xo; - float y0 = f[1]*SIMPLEX_SCALE-yo; - int i1,j1,ii = absmod(i ,256),jj = absmod(j, 256); - float n0,n1,n2,x1,y1,x2,y2,t0,t1,t2; - if ( x0 > y0 ) { - i1=1;j1=0; - } else { - i1=0;j1=1; - } - x1 = x0 - i1 + G2; - y1 = y0 - j1 + G2; - x2 = x0 - 1.0f + 2.0f * G2; - y2 = y0 - 1.0f + 2.0f * G2; - t0 = 0.5f - x0*x0 - y0*y0; - if ( t0 < 0.0f ) { - n0 = 0.0f; - } else { - int idx = (ii + data->map[jj])&0xFF; - t0 *= t0; - idx=data->map[idx]; - TCOD_NOISE_SIMPLEX_GRADIENT_2D(n0,idx,x0,y0); - n0 *= t0*t0; - } - t1 = 0.5f - x1*x1 -y1*y1; - if ( t1 < 0.0f ) { - n1 = 0.0f; - } else { - int idx = (ii + i1 + data->map[(jj+j1)&0xFF]) & 0xFF; - t1 *= t1; - idx=data->map[idx]; - TCOD_NOISE_SIMPLEX_GRADIENT_2D(n1,idx,x1,y1); - n1 *= t1*t1; - } - t2 = 0.5f - x2*x2 -y2*y2; - if ( t2 < 0.0f ) { - n2 = 0.0f; - } else { - int idx = (ii + 1 + data->map[(jj+1)&0xFF]) & 0xFF; - t2 *= t2; - idx=data->map[idx]; - TCOD_NOISE_SIMPLEX_GRADIENT_2D(n2,idx,x2,y2); - n2 *= t2*t2; - } - return 40.0f * (n0+n1+n2); - } - break; - case 3 : - { - #define F3 0.333333333f - #define G3 0.166666667f - float n0,n1,n2,n3; - float s =(f[0]+f[1]+f[2])*F3*SIMPLEX_SCALE; - float xs=f[0]*SIMPLEX_SCALE+s; - float ys=f[1]*SIMPLEX_SCALE+s; - float zs=f[2]*SIMPLEX_SCALE+s; - int i=FLOOR(xs); - int j=FLOOR(ys); - int k=FLOOR(zs); - float t=(float)(i+j+k)*G3; - float xo = i-t; - float yo = j-t; - float zo = k-t; - float x0 = f[0]*SIMPLEX_SCALE-xo; - float y0 = f[1]*SIMPLEX_SCALE-yo; - float z0 = f[2]*SIMPLEX_SCALE-zo; - int i1,j1,k1,i2,j2,k2,ii,jj,kk; - float x1,y1,z1,x2,y2,z2,x3,y3,z3,t0,t1,t2,t3; - if ( x0 >= y0 ) { - if ( y0 >= z0 ) { - i1=1;j1=0;k1=0;i2=1;j2=1;k2=0; - } else if ( x0 >= z0 ) { - i1=1;j1=0;k1=0;i2=1;j2=0;k2=1; - } else { - i1=0;j1=0;k1=1;i2=1;j2=0;k2=1; - } - } else { - if ( y0 < z0 ) { - i1=0;j1=0;k1=1;i2=0;j2=1;k2=1; - } else if ( x0 < z0 ) { - i1=0;j1=1;k1=0;i2=0;j2=1;k2=1; - } else { - i1=0;j1=1;k1=0;i2=1;j2=1;k2=0; - } - } - x1 = x0 -i1 + G3; - y1 = y0 -j1 + G3; - z1 = z0 -k1 + G3; - x2 = x0 -i2 + 2.0f*G3; - y2 = y0 -j2 + 2.0f*G3; - z2 = z0 -k2 + 2.0f*G3; - x3 = x0 - 1.0f +3.0f * G3; - y3 = y0 - 1.0f +3.0f * G3; - z3 = z0 - 1.0f +3.0f * G3; - ii = absmod(i, 256); - jj = absmod(j, 256); - kk = absmod(k, 256); - t0 = 0.6f - x0*x0 -y0*y0 -z0*z0; - if ( t0 < 0.0f ) n0 = 0.0f; - else { - int idx = data->map[ (ii + data->map[ (jj + data->map[ kk ]) &0xFF ])& 0xFF ]; - t0 *= t0; - TCOD_NOISE_SIMPLEX_GRADIENT_3D(n0,idx,x0,y0,z0); - n0 *= t0*t0; - } - t1 = 0.6f - x1*x1 -y1*y1 -z1*z1; - if ( t1 < 0.0f ) n1 = 0.0f; - else { - int idx = data->map[ (ii + i1 + data->map[ (jj + j1 + data->map[ (kk + k1)& 0xFF ]) &0xFF ])& 0xFF ]; - t1 *= t1; - TCOD_NOISE_SIMPLEX_GRADIENT_3D(n1,idx,x1,y1,z1); - n1 *= t1*t1; - } - t2 = 0.6f - x2*x2 -y2*y2 -z2*z2; - if ( t2 < 0.0f ) n2 = 0.0f; - else { - int idx = data->map[ (ii + i2 + data->map[ (jj + j2 + data->map[ (kk + k2)& 0xFF ]) &0xFF ])& 0xFF ]; - t2 *= t2; - TCOD_NOISE_SIMPLEX_GRADIENT_3D(n2,idx,x2,y2,z2); - n2 *= t2*t2; - } - t3 = 0.6f - x3*x3 -y3*y3 -z3*z3; - if ( t3 < 0.0f ) n3 = 0.0f; - else { - int idx = data->map[ (ii + 1 + data->map[ (jj + 1 + data->map[ (kk + 1)& 0xFF ]) &0xFF ])& 0xFF ]; - t3 *= t3; - TCOD_NOISE_SIMPLEX_GRADIENT_3D(n3,idx,x3,y3,z3); - n3 *= t3*t3; - } - return 32.0f * (n0+n1+n2+n3); - - } - break; - case 4 : - { - #define F4 0.309016994f /* (sqrtf(5.0f)-1.0f)/4.0f */ - #define G4 0.138196601f /* (5.0f - sqrtf(5.0f))/20.0f */ - float n0,n1,n2,n3,n4; - float s = (f[0]+f[1]+f[2]+f[3])*F4 * SIMPLEX_SCALE; - float xs=f[0]*SIMPLEX_SCALE+s; - float ys=f[1]*SIMPLEX_SCALE+s; - float zs=f[2]*SIMPLEX_SCALE+s; - float ws=f[3]*SIMPLEX_SCALE+s; - int i=FLOOR(xs); - int j=FLOOR(ys); - int k=FLOOR(zs); - int l=FLOOR(ws); - float t=(float)(i+j+k+l)*G4; - float xo = i-t; - float yo = j-t; - float zo = k-t; - float wo = l-t; - float x0 = f[0]*SIMPLEX_SCALE-xo; - float y0 = f[1]*SIMPLEX_SCALE-yo; - float z0 = f[2]*SIMPLEX_SCALE-zo; - float w0 = f[3]*SIMPLEX_SCALE-wo; - int c1 = (x0 > y0 ? 32 : 0); - int c2 = (x0 > z0 ? 16 : 0); - int c3 = (y0 > z0 ? 8 : 0); - int c4 = (x0 > w0 ? 4 : 0); - int c5 = (y0 > w0 ? 2 : 0); - int c6 = (z0 > w0 ? 1 : 0); - int c = c1+c2+c3+c4+c5+c6; - - - int i1,j1,k1,l1,i2,j2,k2,l2,i3,j3,k3,l3,ii,jj,kk,ll; - float x1,y1,z1,w1,x2,y2,z2,w2,x3,y3,z3,w3,x4,y4,z4,w4,t0,t1,t2,t3,t4; - i1 = simplex[c][0] >= 3 ? 1:0; - j1 = simplex[c][1] >= 3 ? 1:0; - k1 = simplex[c][2] >= 3 ? 1:0; - l1 = simplex[c][3] >= 3 ? 1:0; - - i2 = simplex[c][0] >= 2 ? 1:0; - j2 = simplex[c][1] >= 2 ? 1:0; - k2 = simplex[c][2] >= 2 ? 1:0; - l2 = simplex[c][3] >= 2 ? 1:0; - - i3 = simplex[c][0] >= 1 ? 1:0; - j3 = simplex[c][1] >= 1 ? 1:0; - k3 = simplex[c][2] >= 1 ? 1:0; - l3 = simplex[c][3] >= 1 ? 1:0; - - x1 = x0 -i1 + G4; - y1 = y0 -j1 + G4; - z1 = z0 -k1 + G4; - w1 = w0 -l1 + G4; - x2 = x0 -i2 + 2.0f*G4; - y2 = y0 -j2 + 2.0f*G4; - z2 = z0 -k2 + 2.0f*G4; - w2 = w0 -l2 + 2.0f*G4; - x3 = x0 -i3 + 3.0f*G4; - y3 = y0 -j3 + 3.0f*G4; - z3 = z0 -k3 + 3.0f*G4; - w3 = w0 -l3 + 3.0f*G4; - x4 = x0 - 1.0f +4.0f * G4; - y4 = y0 - 1.0f +4.0f * G4; - z4 = z0 - 1.0f +4.0f * G4; - w4 = w0 - 1.0f +4.0f * G4; - - ii = absmod(i, 256); - jj = absmod(j, 256); - kk = absmod(k, 256); - ll = absmod(l, 256); - - t0 = 0.6f - x0*x0 -y0*y0 -z0*z0 -w0*w0; - if ( t0 < 0.0f ) n0 = 0.0f; - else { - int idx = data->map[ (ii + data->map[ (jj + data->map[ (kk + data->map[ ll ] ) &0xFF]) &0xFF ])& 0xFF ]; - t0 *= t0; - TCOD_NOISE_SIMPLEX_GRADIENT_4D(n0,idx,x0,y0,z0,w0); - n0 *= t0*t0; - } - t1 = 0.6f - x1*x1 -y1*y1 -z1*z1 -w1*w1; - if ( t1 < 0.0f ) n1 = 0.0f; - else { - int idx = data->map[ (ii + i1 + data->map[ (jj + j1 + data->map[ (kk + k1 + data->map[ (ll+l1)&0xFF])& 0xFF ]) &0xFF ])& 0xFF ]; - t1 *= t1; - TCOD_NOISE_SIMPLEX_GRADIENT_4D(n1,idx,x1,y1,z1,w1); - n1 *= t1*t1; - } - t2 = 0.6f - x2*x2 -y2*y2 -z2*z2 -w2*w2; - if ( t2 < 0.0f ) n2 = 0.0f; - else { - int idx = data->map[ (ii + i2 + data->map[ (jj + j2 + data->map[ (kk + k2 + data->map[(ll+l2)&0xFF])& 0xFF ]) &0xFF ])& 0xFF ]; - t2 *= t2; - TCOD_NOISE_SIMPLEX_GRADIENT_4D(n2,idx,x2,y2,z2,w2); - n2 *= t2*t2; - } - t3 = 0.6f - x3*x3 -y3*y3 -z3*z3 -w3*w3; - if ( t3 < 0.0f ) n3 = 0.0f; - else { - int idx = data->map[ (ii + i3 + data->map[ (jj + j3 + data->map[ (kk + k3 + data->map[(ll+l3)&0xFF])& 0xFF ]) &0xFF ])& 0xFF ]; - t3 *= t3; - TCOD_NOISE_SIMPLEX_GRADIENT_4D(n3,idx,x3,y3,z3,w3); - n3 *= t3*t3; - } - t4 = 0.6f - x4*x4 -y4*y4 -z4*z4 -w4*w4; - if ( t4 < 0.0f ) n4 = 0.0f; - else { - int idx = data->map[ (ii + 1 + data->map[ (jj + 1 + data->map[ (kk + 1 + data->map[(ll+1)&0xFF])& 0xFF ]) &0xFF ])& 0xFF ]; - t4 *= t4; - TCOD_NOISE_SIMPLEX_GRADIENT_4D(n4,idx,x4,y4,z4,w4); - n4 *= t4*t4; - } - return 27.0f * (n0+n1+n2+n3+n4); - - } - break; - } - return 0.0f; -} - -typedef float (*TCOD_noise_func_t)( TCOD_noise_t noise, float *f ); - -static float TCOD_noise_fbm_int(TCOD_noise_t noise, float *f, float octaves, TCOD_noise_func_t func ) { - float tf[TCOD_NOISE_MAX_DIMENSIONS]; - perlin_data_t *data=(perlin_data_t *)noise; - /* Initialize locals */ - double value = 0; - int i,j; - memcpy(tf,f,sizeof(float)*data->ndim); - - /* Inner loop of spectral construction, where the fractal is built */ - for(i=0; i<(int)octaves; i++) - { - value += (double)(func(noise,tf)) * data->exponent[i]; - for (j=0; j < data->ndim; j++) tf[j] *= data->lacunarity; - } - - /* Take care of remainder in octaves */ - octaves -= (int)octaves; - if(octaves > DELTA) - value += (double)(octaves * func(noise,tf)) * data->exponent[i]; - return CLAMP(-0.99999f, 0.99999f, (float)value); -} - -float TCOD_noise_fbm_perlin( TCOD_noise_t noise, float *f, float octaves ) -{ - return TCOD_noise_fbm_int(noise,f,octaves,TCOD_noise_perlin); -} - -float TCOD_noise_fbm_simplex( TCOD_noise_t noise, float *f, float octaves ) -{ - return TCOD_noise_fbm_int(noise,f,octaves,TCOD_noise_simplex); -} - -static float TCOD_noise_turbulence_int( TCOD_noise_t noise, float *f, float octaves, TCOD_noise_func_t func ) -{ - float tf[TCOD_NOISE_MAX_DIMENSIONS]; - perlin_data_t *data=(perlin_data_t *)noise; - /* Initialize locals */ - double value = 0; - int i,j; - memcpy(tf,f,sizeof(float)*data->ndim); - - /* Inner loop of spectral construction, where the fractal is built */ - for(i=0; i<(int)octaves; i++) - { - float nval=func(noise,tf); - value += (double)(ABS(nval)) * data->exponent[i]; - for (j=0; j < data->ndim; j++) tf[j] *= data->lacunarity; - } - - /* Take care of remainder in octaves */ - octaves -= (int)octaves; - if(octaves > DELTA) { - float nval=func(noise,tf); - value += (double)(octaves * ABS(nval)) * data->exponent[i]; - } - return CLAMP(-0.99999f, 0.99999f, (float)value); -} - -float TCOD_noise_turbulence_perlin( TCOD_noise_t noise, float *f, float octaves ) { - return TCOD_noise_turbulence_int(noise,f,octaves,TCOD_noise_perlin); -} - -float TCOD_noise_turbulence_simplex( TCOD_noise_t noise, float *f, float octaves ) { - return TCOD_noise_turbulence_int(noise,f,octaves,TCOD_noise_simplex); -} - -/* wavelet noise, adapted from Robert L. Cook and Tony Derose 'Wavelet noise' paper */ - -static void TCOD_noise_wavelet_downsample(float *from, float *to, int stride) { - static float acoeffs[2*WAVELET_ARAD]= { - 0.000334f, -0.001528f, 0.000410f, 0.003545f, -0.000938f, -0.008233f, 0.002172f, 0.019120f, - -0.005040f,-0.044412f, 0.011655f, 0.103311f, -0.025936f, -0.243780f, 0.033979f, 0.655340f, - 0.655340f, 0.033979f,-0.243780f,-0.025936f, 0.103311f, 0.011655f,-0.044412f,-0.005040f, - 0.019120f, 0.002172f,-0.008233f,-0.000938f, 0.003546f, 0.000410f,-0.001528f, 0.000334f, - }; - static float *a = &acoeffs[WAVELET_ARAD]; - int i; - for (i=0; i < WAVELET_TILE_SIZE/2; i++) { - int k; - to[i*stride]=0; - for (k=2*i-WAVELET_ARAD; k <2*i+WAVELET_ARAD; k++) { - to[i*stride] += a[k-2*i]* from[ absmod(k,WAVELET_TILE_SIZE) * stride ]; - } - } -} - -static void TCOD_noise_wavelet_upsample(float *from, float *to, int stride) { - static float pcoeffs[4]= { 0.25f, 0.75f, 0.75f, 0.25f }; - static float *p = &pcoeffs[2]; - int i; - for (i=0; i < WAVELET_TILE_SIZE; i++) { - int k; - to[i*stride]=0; - for (k=i/2; k rand,-1.0f,1.0f); - } - for (iy=0; iy < WAVELET_TILE_SIZE; iy++ ) { - for (iz=0; iz < WAVELET_TILE_SIZE; iz++ ) { - i = iy * WAVELET_TILE_SIZE + iz * WAVELET_TILE_SIZE * WAVELET_TILE_SIZE; - TCOD_noise_wavelet_downsample(&noise[i], &temp1[i], 1); - TCOD_noise_wavelet_upsample(&temp1[i], &temp2[i], 1); - } - } - for (ix=0; ix < WAVELET_TILE_SIZE; ix++ ) { - for (iz=0; iz < WAVELET_TILE_SIZE; iz++ ) { - i = ix + iz * WAVELET_TILE_SIZE * WAVELET_TILE_SIZE; - TCOD_noise_wavelet_downsample(&temp2[i], &temp1[i], WAVELET_TILE_SIZE); - TCOD_noise_wavelet_upsample(&temp1[i], &temp2[i], WAVELET_TILE_SIZE); - } - } - for (ix=0; ix < WAVELET_TILE_SIZE; ix++ ) { - for (iy=0; iy < WAVELET_TILE_SIZE; iy++ ) { - i = ix + iy * WAVELET_TILE_SIZE; - TCOD_noise_wavelet_downsample(&temp2[i], &temp1[i], WAVELET_TILE_SIZE * WAVELET_TILE_SIZE); - TCOD_noise_wavelet_upsample(&temp1[i], &temp2[i], WAVELET_TILE_SIZE * WAVELET_TILE_SIZE); - } - } - for (i=0; i < WAVELET_TILE_SIZE*WAVELET_TILE_SIZE*WAVELET_TILE_SIZE; i++ ) { - noise[i] -= temp2[i]; - } - offset = WAVELET_TILE_SIZE/2; - if ( (offset & 1) == 0 ) offset++; - for (i=0,ix=0; ix < WAVELET_TILE_SIZE; ix++ ) { - for (iy=0; iy < WAVELET_TILE_SIZE; iy++ ) { - for (iz=0; iz < WAVELET_TILE_SIZE; iz++ ) { - temp1[i++]=noise[ absmod(ix+offset,WAVELET_TILE_SIZE) - + absmod(iy+offset,WAVELET_TILE_SIZE)*WAVELET_TILE_SIZE - + absmod(iz+offset,WAVELET_TILE_SIZE)*WAVELET_TILE_SIZE*WAVELET_TILE_SIZE - ]; - } - } - } - for (i=0; i < WAVELET_TILE_SIZE*WAVELET_TILE_SIZE*WAVELET_TILE_SIZE; i++ ) { - noise[i] += temp1[i]; - } - data->waveletTileData=noise; - free(temp1); - free(temp2); -} - -float TCOD_noise_wavelet (TCOD_noise_t noise, float *f) { - perlin_data_t *data=(perlin_data_t *)noise; - float pf[3]; - int i; - int p[3],c[3],mid[3],n=WAVELET_TILE_SIZE; - float w[3][3],t,result=0.0f; - if ( data->ndim > 3 ) return 0.0f; /* not supported */ - if (! data->waveletTileData ) TCOD_noise_wavelet_init(noise); - for (i=0; i < data->ndim; i++ ) pf[i]=f[i]*WAVELET_SCALE; - for (i=data->ndim; i < 3; i++ ) pf[i]=0.0f; - for (i=0; i < 3; i++ ) { - mid[i]=(int)ceil(pf[i]-0.5f); - t=mid[i] - (pf[i]-0.5f); - w[i][0]=t*t*0.5f; - w[i][2]=(1.0f-t)*(1.0f-t)*0.5f; - w[i][1]=1.0f - w[i][0]-w[i][2]; - } - for (p[2]=-1; p[2]<=1; p[2]++) { - for (p[1]=-1; p[1]<=1; p[1]++) { - for (p[0]=-1; p[0]<=1; p[0]++) { - float weight=1.0f; - for (i=0;i<3;i++) { - c[i]=absmod(mid[i]+p[i],n); - weight *= w[i][p[i]+1]; - } - result += weight * data->waveletTileData[ c[2]*n*n + c[1]*n + c[0] ]; - } - } - } - return CLAMP(-1.0f,1.0f,result); -} - -float TCOD_noise_fbm_wavelet(TCOD_noise_t noise, float *f, float octaves) { - return TCOD_noise_fbm_int(noise,f,octaves,TCOD_noise_wavelet); -} - -float TCOD_noise_turbulence_wavelet(TCOD_noise_t noise, float *f, float octaves) { - return TCOD_noise_turbulence_int(noise,f,octaves,TCOD_noise_wavelet); -} - -void TCOD_noise_set_type (TCOD_noise_t noise, TCOD_noise_type_t type) { - ((perlin_data_t *)noise)->noise_type = type; -} - -float TCOD_noise_get_ex (TCOD_noise_t noise, float *f, TCOD_noise_type_t type) { - switch (type) { - case (TCOD_NOISE_PERLIN): return TCOD_noise_perlin(noise,f); break; - case (TCOD_NOISE_SIMPLEX): return TCOD_noise_simplex(noise,f); break; - case (TCOD_NOISE_WAVELET): return TCOD_noise_wavelet(noise,f); break; - default: - switch (((perlin_data_t *)noise)->noise_type) { - case (TCOD_NOISE_PERLIN): return TCOD_noise_perlin(noise,f); break; - case (TCOD_NOISE_SIMPLEX): return TCOD_noise_simplex(noise,f); break; - case (TCOD_NOISE_WAVELET): return TCOD_noise_wavelet(noise,f); break; - default: return TCOD_noise_simplex(noise,f); break; - } - break; - } -} - -float TCOD_noise_get_fbm_ex (TCOD_noise_t noise, float *f, float octaves, TCOD_noise_type_t type) { - switch (type) { - case (TCOD_NOISE_PERLIN): return TCOD_noise_fbm_perlin(noise,f,octaves); break; - case (TCOD_NOISE_SIMPLEX): return TCOD_noise_fbm_simplex(noise,f,octaves); break; - case (TCOD_NOISE_WAVELET): return TCOD_noise_fbm_wavelet(noise,f,octaves); break; - default: - switch (((perlin_data_t *)noise)->noise_type) { - case (TCOD_NOISE_PERLIN): return TCOD_noise_fbm_perlin(noise,f,octaves); break; - case (TCOD_NOISE_SIMPLEX): return TCOD_noise_fbm_simplex(noise,f,octaves); break; - case (TCOD_NOISE_WAVELET): return TCOD_noise_fbm_wavelet(noise,f,octaves); break; - default: return TCOD_noise_fbm_simplex(noise,f,octaves); break; - } - break; - } -} - -float TCOD_noise_get_turbulence_ex (TCOD_noise_t noise, float *f, float octaves, TCOD_noise_type_t type) { - switch (type) { - case (TCOD_NOISE_PERLIN): return TCOD_noise_turbulence_perlin(noise,f,octaves); break; - case (TCOD_NOISE_SIMPLEX): return TCOD_noise_turbulence_simplex(noise,f,octaves); break; - case (TCOD_NOISE_WAVELET): return TCOD_noise_turbulence_wavelet(noise,f,octaves); break; - default: - switch (((perlin_data_t *)noise)->noise_type) { - case (TCOD_NOISE_PERLIN): return TCOD_noise_turbulence_perlin(noise,f,octaves); break; - case (TCOD_NOISE_SIMPLEX): return TCOD_noise_turbulence_simplex(noise,f,octaves); break; - case (TCOD_NOISE_WAVELET): return TCOD_noise_turbulence_wavelet(noise,f,octaves); break; - default: return TCOD_noise_turbulence_simplex(noise,f,octaves); break; - } - break; - } -} - -float TCOD_noise_get (TCOD_noise_t noise, float *f) { - switch (((perlin_data_t *)noise)->noise_type) { - case (TCOD_NOISE_PERLIN): return TCOD_noise_perlin(noise,f); break; - case (TCOD_NOISE_SIMPLEX): return TCOD_noise_simplex(noise,f); break; - case (TCOD_NOISE_WAVELET): return TCOD_noise_wavelet(noise,f); break; - default: return TCOD_noise_simplex(noise,f); break; - } -} - -float TCOD_noise_get_fbm (TCOD_noise_t noise, float *f, float octaves) { - switch (((perlin_data_t *)noise)->noise_type) { - case (TCOD_NOISE_PERLIN): return TCOD_noise_fbm_perlin(noise,f,octaves); break; - case (TCOD_NOISE_SIMPLEX): return TCOD_noise_fbm_simplex(noise,f,octaves); break; - case (TCOD_NOISE_WAVELET): return TCOD_noise_fbm_wavelet(noise,f,octaves); break; - default: return TCOD_noise_fbm_simplex(noise,f,octaves); break; - } -} - -float TCOD_noise_get_turbulence (TCOD_noise_t noise, float *f, float octaves) { - switch (((perlin_data_t *)noise)->noise_type) { - case (TCOD_NOISE_PERLIN): return TCOD_noise_turbulence_perlin(noise,f,octaves); break; - case (TCOD_NOISE_SIMPLEX): return TCOD_noise_turbulence_simplex(noise,f,octaves); break; - case (TCOD_NOISE_WAVELET): return TCOD_noise_turbulence_wavelet(noise,f,octaves); break; - default: return TCOD_noise_turbulence_simplex(noise,f,octaves); break; - } -} - -void TCOD_noise_delete(TCOD_noise_t noise) { - if (((perlin_data_t *)noise)->waveletTileData) { - free(((perlin_data_t *)noise)->waveletTileData); - } - free((perlin_data_t *)noise); -} +/* +* libtcod +* Copyright (c) 2008-2018 Jice & Mingos & rmtew +* All rights reserved. +* +* Redistribution and use in source and binary forms, with or without +* modification, are permitted provided that the following conditions are met: +* * Redistributions of source code must retain the above copyright +* notice, this list of conditions and the following disclaimer. +* * Redistributions in binary form must reproduce the above copyright +* notice, this list of conditions and the following disclaimer in the +* documentation and/or other materials provided with the distribution. +* * The name of Jice or Mingos may not be used to endorse or promote +* products derived from this software without specific prior written +* permission. +* +* THIS SOFTWARE IS PROVIDED BY JICE, MINGOS AND RMTEW ``AS IS'' AND ANY +* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED +* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE +* DISCLAIMED. IN NO EVENT SHALL JICE, MINGOS OR RMTEW BE LIABLE FOR ANY +* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES +* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; +* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND +* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS +* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +*/ +#include "noise.h" + +#include +#include +#include + +#include "mersenne.h" +#include "utility.h" + +#define WAVELET_TILE_SIZE 32 +#define WAVELET_ARAD 16 + +#define SIMPLEX_SCALE 0.5f +#define WAVELET_SCALE 2.0f + +typedef TCOD_Noise perlin_data_t; + +static float lattice( perlin_data_t *data, int ix, float fx, int iy, float fy, int iz, float fz, int iw, float fw) +{ + int n[4] = {ix, iy, iz, iw}; + float f[4] = {fx, fy, fz, fw}; + int nIndex = 0; + int i; + float value = 0; + for(i=0; indim; i++) + nIndex = data->map[(nIndex + n[i]) & 0xFF]; + for(i=0; indim; i++) + value += data->buffer[nIndex][i] * f[i]; + return value; +} + +#define DEFAULT_SEED 0x15687436 +#define DELTA 1e-6f +#define SWAP(a, b, t) t = a; a = b; b = t + +#define FLOOR(a) ((a)> 0 ? ((int)a) : (((int)a)-1) ) +#define CUBIC(a) ( a * a * (3 - 2*a) ) + +static void normalize(perlin_data_t *data, float *f) +{ + float magnitude = 0; + int i; + for(i=0; indim; i++) + magnitude += f[i]*f[i]; + magnitude = 1.0f / (float)sqrt(magnitude); + for(i=0; indim; i++) + f[i] *= magnitude; +} + + +TCOD_noise_t TCOD_noise_new(int ndim, float hurst, float lacunarity, TCOD_random_t random) +{ + perlin_data_t *data=(perlin_data_t *)calloc(sizeof(perlin_data_t),1); + int i, j; + unsigned char tmp; + float f = 1; + data->rand = random ? random : TCOD_random_get_instance(); + data->ndim = ndim; + for(i=0; i<256; i++) + { + data->map[i] = (unsigned char)i; + for(j=0; jndim; j++) + data->buffer[i][j] = TCOD_random_get_float(data->rand,-0.5, 0.5); + normalize(data,data->buffer[i]); + } + + while(--i) + { + j = TCOD_random_get_int(data->rand,0, 255); + SWAP(data->map[i], data->map[j], tmp); + } + + data->H = hurst; + data->lacunarity = lacunarity; + for(i=0; iexponent[i] = 1.0f / f; + f *= lacunarity; + } + data->noise_type = TCOD_NOISE_DEFAULT; + return (TCOD_noise_t)data; +} + +float TCOD_noise_perlin( TCOD_noise_t noise, float *f ) +{ + perlin_data_t *data=(perlin_data_t *)noise; + int n[TCOD_NOISE_MAX_DIMENSIONS]; /* Indexes to pass to lattice function */ + int i; + float r[TCOD_NOISE_MAX_DIMENSIONS]; /* Remainders to pass to lattice function */ + float w[TCOD_NOISE_MAX_DIMENSIONS]; /* Cubic values to pass to interpolation function */ + float value; + + for(i=0; indim; i++) + { + n[i] = FLOOR(f[i]); + r[i] = f[i] - n[i]; + w[i] = CUBIC(r[i]); + } + + switch(data->ndim) + { + case 1: + value = LERP(lattice(data,n[0], r[0],0,0,0,0,0,0), + lattice(data,n[0]+1, r[0]-1,0,0,0,0,0,0), + w[0]); + break; + case 2: + value = LERP(LERP(lattice(data,n[0], r[0], n[1], r[1],0,0,0,0), + lattice(data,n[0]+1, r[0]-1, n[1], r[1],0,0,0,0), + w[0]), + LERP(lattice(data,n[0], r[0], n[1]+1, r[1]-1,0,0,0,0), + lattice(data,n[0]+1, r[0]-1, n[1]+1, r[1]-1,0,0,0,0), + w[0]), + w[1]); + break; + case 3: + value = LERP(LERP(LERP(lattice(data,n[0], r[0], n[1], r[1], n[2], r[2],0,0), + lattice(data,n[0]+1, r[0]-1, n[1], r[1], n[2], r[2],0,0), + w[0]), + LERP(lattice(data,n[0], r[0], n[1]+1, r[1]-1, n[2], r[2],0,0), + lattice(data,n[0]+1, r[0]-1, n[1]+1, r[1]-1, n[2], r[2],0,0), + w[0]), + w[1]), + LERP(LERP(lattice(data,n[0], r[0], n[1], r[1], n[2]+1, r[2]-1,0,0), + lattice(data,n[0]+1, r[0]-1, n[1], r[1], n[2]+1, r[2]-1,0,0), + w[0]), + LERP(lattice(data,n[0], r[0], n[1]+1, r[1]-1, n[2]+1, r[2]-1,0,0), + lattice(data,n[0]+1, r[0]-1, n[1]+1, r[1]-1, n[2]+1, r[2]-1,0,0), + w[0]), + w[1]), + w[2]); + break; + case 4: + default: + value = LERP(LERP(LERP(LERP(lattice(data,n[0], r[0], n[1], r[1], n[2], r[2], n[3], r[3]), + lattice(data,n[0]+1, r[0]-1, n[1], r[1], n[2], r[2], n[3], r[3]), + w[0]), + LERP(lattice(data,n[0], r[0], n[1]+1, r[1]-1, n[2], r[2], n[3], r[3]), + lattice(data,n[0]+1, r[0]-1, n[1]+1, r[1]-1, n[2], r[2], n[3], r[3]), + w[0]), + w[1]), + LERP(LERP(lattice(data,n[0], r[0], n[1], r[1], n[2]+1, r[2]-1, n[3], r[3]), + lattice(data,n[0]+1, r[0]-1, n[1], r[1], n[2]+1, r[2]-1, n[3], r[3]), + w[0]), + LERP(lattice(data,n[0], r[0], n[1]+1, r[1]-1, n[2]+1, r[2]-1,0,0), + lattice(data,n[0]+1, r[0]-1, n[1]+1, r[1]-1, n[2]+1, r[2]-1, n[3], r[3]), + w[0]), + w[1]), + w[2]), + LERP(LERP(LERP(lattice(data,n[0], r[0], n[1], r[1], n[2], r[2], n[3]+1, r[3]-1), + lattice(data,n[0]+1, r[0]-1, n[1], r[1], n[2], r[2], n[3]+1, r[3]-1), + w[0]), + LERP(lattice(data,n[0], r[0], n[1]+1, r[1]-1, n[2], r[2], n[3]+1, r[3]-1), + lattice(data,n[0]+1, r[0]-1, n[1]+1, r[1]-1, n[2], r[2], n[3]+1, r[3]-1), + w[0]), + w[1]), + LERP(LERP(lattice(data,n[0], r[0], n[1], r[1], n[2]+1, r[2]-1, n[3]+1, r[3]-1), + lattice(data,n[0]+1, r[0]-1, n[1], r[1], n[2]+1, r[2]-1, n[3]+1, r[3]-1), + w[0]), + LERP(lattice(data,n[0], r[0], n[1]+1, r[1]-1, n[2]+1, r[2]-1,0,0), + lattice(data,n[0]+1, r[0]-1, n[1]+1, r[1]-1, n[2]+1, r[2]-1, n[3]+1, r[3]-1), + w[0]), + w[1]), + w[2]), + w[3]); + break; + } + return CLAMP(-0.99999f, 0.99999f, value); +} + +static int absmod(int x, int n) { + int m=x%n; + return m < 0 ? m+n : m; +} + +/* simplex noise, adapted from Ken Perlin's presentation at Siggraph 2001 */ +/* and Stefan Gustavson implementation */ + +#define TCOD_NOISE_SIMPLEX_GRADIENT_1D(n,h,x) { float grad; h &= 0xF; grad=1.0f+(h & 7); if ( h & 8 ) grad = -grad; n = grad * x; } + +#define TCOD_NOISE_SIMPLEX_GRADIENT_2D(n,h,x,y) { float u,v; h &= 0x7; if ( h < 4 ) { u=x; v=2.0f*y; } else { u=y; v=2.0f*x; } n = ((h & 1) ? -u : u) + ((h & 2) ? -v :v ); } + +#define TCOD_NOISE_SIMPLEX_GRADIENT_3D(n,h,x,y,z) { float u,v; h &= 0xF; u = (h < 8 ? x : y); v = (h < 4 ? y : ( h == 12 || h == 14 ? x : z ) ); n= ((h & 1) ? -u : u ) + ((h & 2) ? -v : v); } + +#define TCOD_NOISE_SIMPLEX_GRADIENT_4D(n,h,x,y,z,t) { float u,v,w; h &= 0x1F; u = (h < 24 ? x:y); v = (h < 16 ? y:z); w = (h < 8 ? z:t); n= ((h & 1) ? -u : u ) + ((h & 2) ? -v : v) + ((h & 4) ? -w : w);} + +static float simplex[64][4] = { + {0,1,2,3},{0,1,3,2},{0,0,0,0},{0,2,3,1},{0,0,0,0},{0,0,0,0},{0,0,0,0},{1,2,3,0}, + {0,2,1,3},{0,0,0,0},{0,3,1,2},{0,3,2,1},{0,0,0,0},{0,0,0,0},{0,0,0,0},{1,3,2,0}, + {0,0,0,0},{0,0,0,0},{0,0,0,0},{0,0,0,0},{0,0,0,0},{0,0,0,0},{0,0,0,0},{0,0,0,0}, + {1,2,0,3},{0,0,0,0},{1,3,0,2},{0,0,0,0},{0,0,0,0},{0,0,0,0},{2,3,0,1},{2,3,1,0}, + {1,0,2,3},{1,0,3,2},{0,0,0,0},{0,0,0,0},{0,0,0,0},{2,0,3,1},{0,0,0,0},{2,1,3,0}, + {0,0,0,0},{0,0,0,0},{0,0,0,0},{0,0,0,0},{0,0,0,0},{0,0,0,0},{0,0,0,0},{0,0,0,0}, + {2,0,1,3},{0,0,0,0},{0,0,0,0},{0,0,0,0},{3,0,1,2},{3,0,2,1},{0,0,0,0},{3,1,2,0}, + {2,1,0,3},{0,0,0,0},{0,0,0,0},{0,0,0,0},{3,1,0,2},{0,0,0,0},{3,2,0,1},{3,2,1,0}, + +}; + +float TCOD_noise_simplex(TCOD_noise_t noise, float *f) { + perlin_data_t *data=(perlin_data_t *)noise; + switch(data->ndim) { + case 1 : + { + int i0=(int)FLOOR(f[0]*SIMPLEX_SCALE); + int i1=i0+1; + float x0 = f[0]*SIMPLEX_SCALE - i0; + float x1 = x0 - 1.0f; + float t0 = 1.0f - x0*x0; + float t1 = 1.0f - x1*x1; + float n0,n1; + t0 = t0*t0; + t1 = t1*t1; + i0=data->map[i0&0xFF]; + TCOD_NOISE_SIMPLEX_GRADIENT_1D(n0,i0,x0); + n0*=t0*t0; + i1=data->map[i1&0xFF]; + TCOD_NOISE_SIMPLEX_GRADIENT_1D(n1,i1,x1); + n1*=t1*t1; + return 0.25f * (n0+n1); + } + break; + case 2 : + { + #define F2 0.366025403f /* 0.5f * (sqrtf(3.0f)-1.0f); */ + #define G2 0.211324865f /* (3.0f - sqrtf(3.0f))/6.0f; */ + + float s = (f[0]+f[1])*F2*SIMPLEX_SCALE; + float xs = f[0]*SIMPLEX_SCALE+s; + float ys = f[1]*SIMPLEX_SCALE+s; + int i=FLOOR(xs); + int j=FLOOR(ys); + float t = (i+j)*G2; + float xo = i-t; + float yo = j-t; + float x0 = f[0]*SIMPLEX_SCALE-xo; + float y0 = f[1]*SIMPLEX_SCALE-yo; + int i1,j1,ii = absmod(i ,256),jj = absmod(j, 256); + float n0,n1,n2,x1,y1,x2,y2,t0,t1,t2; + if ( x0 > y0 ) { + i1=1;j1=0; + } else { + i1=0;j1=1; + } + x1 = x0 - i1 + G2; + y1 = y0 - j1 + G2; + x2 = x0 - 1.0f + 2.0f * G2; + y2 = y0 - 1.0f + 2.0f * G2; + t0 = 0.5f - x0*x0 - y0*y0; + if ( t0 < 0.0f ) { + n0 = 0.0f; + } else { + int idx = (ii + data->map[jj])&0xFF; + t0 *= t0; + idx=data->map[idx]; + TCOD_NOISE_SIMPLEX_GRADIENT_2D(n0,idx,x0,y0); + n0 *= t0*t0; + } + t1 = 0.5f - x1*x1 -y1*y1; + if ( t1 < 0.0f ) { + n1 = 0.0f; + } else { + int idx = (ii + i1 + data->map[(jj+j1)&0xFF]) & 0xFF; + t1 *= t1; + idx=data->map[idx]; + TCOD_NOISE_SIMPLEX_GRADIENT_2D(n1,idx,x1,y1); + n1 *= t1*t1; + } + t2 = 0.5f - x2*x2 -y2*y2; + if ( t2 < 0.0f ) { + n2 = 0.0f; + } else { + int idx = (ii + 1 + data->map[(jj+1)&0xFF]) & 0xFF; + t2 *= t2; + idx=data->map[idx]; + TCOD_NOISE_SIMPLEX_GRADIENT_2D(n2,idx,x2,y2); + n2 *= t2*t2; + } + return 40.0f * (n0+n1+n2); + } + break; + case 3 : + { + #define F3 0.333333333f + #define G3 0.166666667f + float n0,n1,n2,n3; + float s =(f[0]+f[1]+f[2])*F3*SIMPLEX_SCALE; + float xs=f[0]*SIMPLEX_SCALE+s; + float ys=f[1]*SIMPLEX_SCALE+s; + float zs=f[2]*SIMPLEX_SCALE+s; + int i=FLOOR(xs); + int j=FLOOR(ys); + int k=FLOOR(zs); + float t=(float)(i+j+k)*G3; + float xo = i-t; + float yo = j-t; + float zo = k-t; + float x0 = f[0]*SIMPLEX_SCALE-xo; + float y0 = f[1]*SIMPLEX_SCALE-yo; + float z0 = f[2]*SIMPLEX_SCALE-zo; + int i1,j1,k1,i2,j2,k2,ii,jj,kk; + float x1,y1,z1,x2,y2,z2,x3,y3,z3,t0,t1,t2,t3; + if ( x0 >= y0 ) { + if ( y0 >= z0 ) { + i1=1;j1=0;k1=0;i2=1;j2=1;k2=0; + } else if ( x0 >= z0 ) { + i1=1;j1=0;k1=0;i2=1;j2=0;k2=1; + } else { + i1=0;j1=0;k1=1;i2=1;j2=0;k2=1; + } + } else { + if ( y0 < z0 ) { + i1=0;j1=0;k1=1;i2=0;j2=1;k2=1; + } else if ( x0 < z0 ) { + i1=0;j1=1;k1=0;i2=0;j2=1;k2=1; + } else { + i1=0;j1=1;k1=0;i2=1;j2=1;k2=0; + } + } + x1 = x0 -i1 + G3; + y1 = y0 -j1 + G3; + z1 = z0 -k1 + G3; + x2 = x0 -i2 + 2.0f*G3; + y2 = y0 -j2 + 2.0f*G3; + z2 = z0 -k2 + 2.0f*G3; + x3 = x0 - 1.0f +3.0f * G3; + y3 = y0 - 1.0f +3.0f * G3; + z3 = z0 - 1.0f +3.0f * G3; + ii = absmod(i, 256); + jj = absmod(j, 256); + kk = absmod(k, 256); + t0 = 0.6f - x0*x0 -y0*y0 -z0*z0; + if ( t0 < 0.0f ) n0 = 0.0f; + else { + int idx = data->map[ (ii + data->map[ (jj + data->map[ kk ]) &0xFF ])& 0xFF ]; + t0 *= t0; + TCOD_NOISE_SIMPLEX_GRADIENT_3D(n0,idx,x0,y0,z0); + n0 *= t0*t0; + } + t1 = 0.6f - x1*x1 -y1*y1 -z1*z1; + if ( t1 < 0.0f ) n1 = 0.0f; + else { + int idx = data->map[ (ii + i1 + data->map[ (jj + j1 + data->map[ (kk + k1)& 0xFF ]) &0xFF ])& 0xFF ]; + t1 *= t1; + TCOD_NOISE_SIMPLEX_GRADIENT_3D(n1,idx,x1,y1,z1); + n1 *= t1*t1; + } + t2 = 0.6f - x2*x2 -y2*y2 -z2*z2; + if ( t2 < 0.0f ) n2 = 0.0f; + else { + int idx = data->map[ (ii + i2 + data->map[ (jj + j2 + data->map[ (kk + k2)& 0xFF ]) &0xFF ])& 0xFF ]; + t2 *= t2; + TCOD_NOISE_SIMPLEX_GRADIENT_3D(n2,idx,x2,y2,z2); + n2 *= t2*t2; + } + t3 = 0.6f - x3*x3 -y3*y3 -z3*z3; + if ( t3 < 0.0f ) n3 = 0.0f; + else { + int idx = data->map[ (ii + 1 + data->map[ (jj + 1 + data->map[ (kk + 1)& 0xFF ]) &0xFF ])& 0xFF ]; + t3 *= t3; + TCOD_NOISE_SIMPLEX_GRADIENT_3D(n3,idx,x3,y3,z3); + n3 *= t3*t3; + } + return 32.0f * (n0+n1+n2+n3); + + } + break; + case 4 : + { + #define F4 0.309016994f /* (sqrtf(5.0f)-1.0f)/4.0f */ + #define G4 0.138196601f /* (5.0f - sqrtf(5.0f))/20.0f */ + float n0,n1,n2,n3,n4; + float s = (f[0]+f[1]+f[2]+f[3])*F4 * SIMPLEX_SCALE; + float xs=f[0]*SIMPLEX_SCALE+s; + float ys=f[1]*SIMPLEX_SCALE+s; + float zs=f[2]*SIMPLEX_SCALE+s; + float ws=f[3]*SIMPLEX_SCALE+s; + int i=FLOOR(xs); + int j=FLOOR(ys); + int k=FLOOR(zs); + int l=FLOOR(ws); + float t=(float)(i+j+k+l)*G4; + float xo = i-t; + float yo = j-t; + float zo = k-t; + float wo = l-t; + float x0 = f[0]*SIMPLEX_SCALE-xo; + float y0 = f[1]*SIMPLEX_SCALE-yo; + float z0 = f[2]*SIMPLEX_SCALE-zo; + float w0 = f[3]*SIMPLEX_SCALE-wo; + int c1 = (x0 > y0 ? 32 : 0); + int c2 = (x0 > z0 ? 16 : 0); + int c3 = (y0 > z0 ? 8 : 0); + int c4 = (x0 > w0 ? 4 : 0); + int c5 = (y0 > w0 ? 2 : 0); + int c6 = (z0 > w0 ? 1 : 0); + int c = c1+c2+c3+c4+c5+c6; + + + int i1,j1,k1,l1,i2,j2,k2,l2,i3,j3,k3,l3,ii,jj,kk,ll; + float x1,y1,z1,w1,x2,y2,z2,w2,x3,y3,z3,w3,x4,y4,z4,w4,t0,t1,t2,t3,t4; + i1 = simplex[c][0] >= 3 ? 1:0; + j1 = simplex[c][1] >= 3 ? 1:0; + k1 = simplex[c][2] >= 3 ? 1:0; + l1 = simplex[c][3] >= 3 ? 1:0; + + i2 = simplex[c][0] >= 2 ? 1:0; + j2 = simplex[c][1] >= 2 ? 1:0; + k2 = simplex[c][2] >= 2 ? 1:0; + l2 = simplex[c][3] >= 2 ? 1:0; + + i3 = simplex[c][0] >= 1 ? 1:0; + j3 = simplex[c][1] >= 1 ? 1:0; + k3 = simplex[c][2] >= 1 ? 1:0; + l3 = simplex[c][3] >= 1 ? 1:0; + + x1 = x0 -i1 + G4; + y1 = y0 -j1 + G4; + z1 = z0 -k1 + G4; + w1 = w0 -l1 + G4; + x2 = x0 -i2 + 2.0f*G4; + y2 = y0 -j2 + 2.0f*G4; + z2 = z0 -k2 + 2.0f*G4; + w2 = w0 -l2 + 2.0f*G4; + x3 = x0 -i3 + 3.0f*G4; + y3 = y0 -j3 + 3.0f*G4; + z3 = z0 -k3 + 3.0f*G4; + w3 = w0 -l3 + 3.0f*G4; + x4 = x0 - 1.0f +4.0f * G4; + y4 = y0 - 1.0f +4.0f * G4; + z4 = z0 - 1.0f +4.0f * G4; + w4 = w0 - 1.0f +4.0f * G4; + + ii = absmod(i, 256); + jj = absmod(j, 256); + kk = absmod(k, 256); + ll = absmod(l, 256); + + t0 = 0.6f - x0*x0 -y0*y0 -z0*z0 -w0*w0; + if ( t0 < 0.0f ) n0 = 0.0f; + else { + int idx = data->map[ (ii + data->map[ (jj + data->map[ (kk + data->map[ ll ] ) &0xFF]) &0xFF ])& 0xFF ]; + t0 *= t0; + TCOD_NOISE_SIMPLEX_GRADIENT_4D(n0,idx,x0,y0,z0,w0); + n0 *= t0*t0; + } + t1 = 0.6f - x1*x1 -y1*y1 -z1*z1 -w1*w1; + if ( t1 < 0.0f ) n1 = 0.0f; + else { + int idx = data->map[ (ii + i1 + data->map[ (jj + j1 + data->map[ (kk + k1 + data->map[ (ll+l1)&0xFF])& 0xFF ]) &0xFF ])& 0xFF ]; + t1 *= t1; + TCOD_NOISE_SIMPLEX_GRADIENT_4D(n1,idx,x1,y1,z1,w1); + n1 *= t1*t1; + } + t2 = 0.6f - x2*x2 -y2*y2 -z2*z2 -w2*w2; + if ( t2 < 0.0f ) n2 = 0.0f; + else { + int idx = data->map[ (ii + i2 + data->map[ (jj + j2 + data->map[ (kk + k2 + data->map[(ll+l2)&0xFF])& 0xFF ]) &0xFF ])& 0xFF ]; + t2 *= t2; + TCOD_NOISE_SIMPLEX_GRADIENT_4D(n2,idx,x2,y2,z2,w2); + n2 *= t2*t2; + } + t3 = 0.6f - x3*x3 -y3*y3 -z3*z3 -w3*w3; + if ( t3 < 0.0f ) n3 = 0.0f; + else { + int idx = data->map[ (ii + i3 + data->map[ (jj + j3 + data->map[ (kk + k3 + data->map[(ll+l3)&0xFF])& 0xFF ]) &0xFF ])& 0xFF ]; + t3 *= t3; + TCOD_NOISE_SIMPLEX_GRADIENT_4D(n3,idx,x3,y3,z3,w3); + n3 *= t3*t3; + } + t4 = 0.6f - x4*x4 -y4*y4 -z4*z4 -w4*w4; + if ( t4 < 0.0f ) n4 = 0.0f; + else { + int idx = data->map[ (ii + 1 + data->map[ (jj + 1 + data->map[ (kk + 1 + data->map[(ll+1)&0xFF])& 0xFF ]) &0xFF ])& 0xFF ]; + t4 *= t4; + TCOD_NOISE_SIMPLEX_GRADIENT_4D(n4,idx,x4,y4,z4,w4); + n4 *= t4*t4; + } + return 27.0f * (n0+n1+n2+n3+n4); + + } + break; + } + return 0.0f; +} + +typedef float (*TCOD_noise_func_t)( TCOD_noise_t noise, float *f ); + +static float TCOD_noise_fbm_int(TCOD_noise_t noise, float *f, float octaves, TCOD_noise_func_t func ) { + float tf[TCOD_NOISE_MAX_DIMENSIONS]; + perlin_data_t *data=(perlin_data_t *)noise; + /* Initialize locals */ + double value = 0; + int i,j; + memcpy(tf,f,sizeof(float)*data->ndim); + + /* Inner loop of spectral construction, where the fractal is built */ + for(i=0; i<(int)octaves; i++) + { + value += (double)(func(noise,tf)) * data->exponent[i]; + for (j=0; j < data->ndim; j++) tf[j] *= data->lacunarity; + } + + /* Take care of remainder in octaves */ + octaves -= (int)octaves; + if(octaves > DELTA) + value += (double)(octaves * func(noise,tf)) * data->exponent[i]; + return CLAMP(-0.99999f, 0.99999f, (float)value); +} + +float TCOD_noise_fbm_perlin( TCOD_noise_t noise, float *f, float octaves ) +{ + return TCOD_noise_fbm_int(noise,f,octaves,TCOD_noise_perlin); +} + +float TCOD_noise_fbm_simplex( TCOD_noise_t noise, float *f, float octaves ) +{ + return TCOD_noise_fbm_int(noise,f,octaves,TCOD_noise_simplex); +} + +static float TCOD_noise_turbulence_int( TCOD_noise_t noise, float *f, float octaves, TCOD_noise_func_t func ) +{ + float tf[TCOD_NOISE_MAX_DIMENSIONS]; + perlin_data_t *data=(perlin_data_t *)noise; + /* Initialize locals */ + double value = 0; + int i,j; + memcpy(tf,f,sizeof(float)*data->ndim); + + /* Inner loop of spectral construction, where the fractal is built */ + for(i=0; i<(int)octaves; i++) + { + float nval=func(noise,tf); + value += (double)(ABS(nval)) * data->exponent[i]; + for (j=0; j < data->ndim; j++) tf[j] *= data->lacunarity; + } + + /* Take care of remainder in octaves */ + octaves -= (int)octaves; + if(octaves > DELTA) { + float nval=func(noise,tf); + value += (double)(octaves * ABS(nval)) * data->exponent[i]; + } + return CLAMP(-0.99999f, 0.99999f, (float)value); +} + +float TCOD_noise_turbulence_perlin( TCOD_noise_t noise, float *f, float octaves ) { + return TCOD_noise_turbulence_int(noise,f,octaves,TCOD_noise_perlin); +} + +float TCOD_noise_turbulence_simplex( TCOD_noise_t noise, float *f, float octaves ) { + return TCOD_noise_turbulence_int(noise,f,octaves,TCOD_noise_simplex); +} + +/* wavelet noise, adapted from Robert L. Cook and Tony Derose 'Wavelet noise' paper */ + +static void TCOD_noise_wavelet_downsample(float *from, float *to, int stride) { + static float acoeffs[2*WAVELET_ARAD]= { + 0.000334f, -0.001528f, 0.000410f, 0.003545f, -0.000938f, -0.008233f, 0.002172f, 0.019120f, + -0.005040f,-0.044412f, 0.011655f, 0.103311f, -0.025936f, -0.243780f, 0.033979f, 0.655340f, + 0.655340f, 0.033979f,-0.243780f,-0.025936f, 0.103311f, 0.011655f,-0.044412f,-0.005040f, + 0.019120f, 0.002172f,-0.008233f,-0.000938f, 0.003546f, 0.000410f,-0.001528f, 0.000334f, + }; + static float *a = &acoeffs[WAVELET_ARAD]; + int i; + for (i=0; i < WAVELET_TILE_SIZE/2; i++) { + int k; + to[i*stride]=0; + for (k=2*i-WAVELET_ARAD; k <2*i+WAVELET_ARAD; k++) { + to[i*stride] += a[k-2*i]* from[ absmod(k,WAVELET_TILE_SIZE) * stride ]; + } + } +} + +static void TCOD_noise_wavelet_upsample(float *from, float *to, int stride) { + static float pcoeffs[4]= { 0.25f, 0.75f, 0.75f, 0.25f }; + static float *p = &pcoeffs[2]; + int i; + for (i=0; i < WAVELET_TILE_SIZE; i++) { + int k; + to[i*stride]=0; + for (k=i/2; k rand,-1.0f,1.0f); + } + for (iy=0; iy < WAVELET_TILE_SIZE; iy++ ) { + for (iz=0; iz < WAVELET_TILE_SIZE; iz++ ) { + i = iy * WAVELET_TILE_SIZE + iz * WAVELET_TILE_SIZE * WAVELET_TILE_SIZE; + TCOD_noise_wavelet_downsample(&noise[i], &temp1[i], 1); + TCOD_noise_wavelet_upsample(&temp1[i], &temp2[i], 1); + } + } + for (ix=0; ix < WAVELET_TILE_SIZE; ix++ ) { + for (iz=0; iz < WAVELET_TILE_SIZE; iz++ ) { + i = ix + iz * WAVELET_TILE_SIZE * WAVELET_TILE_SIZE; + TCOD_noise_wavelet_downsample(&temp2[i], &temp1[i], WAVELET_TILE_SIZE); + TCOD_noise_wavelet_upsample(&temp1[i], &temp2[i], WAVELET_TILE_SIZE); + } + } + for (ix=0; ix < WAVELET_TILE_SIZE; ix++ ) { + for (iy=0; iy < WAVELET_TILE_SIZE; iy++ ) { + i = ix + iy * WAVELET_TILE_SIZE; + TCOD_noise_wavelet_downsample(&temp2[i], &temp1[i], WAVELET_TILE_SIZE * WAVELET_TILE_SIZE); + TCOD_noise_wavelet_upsample(&temp1[i], &temp2[i], WAVELET_TILE_SIZE * WAVELET_TILE_SIZE); + } + } + for (i=0; i < WAVELET_TILE_SIZE*WAVELET_TILE_SIZE*WAVELET_TILE_SIZE; i++ ) { + noise[i] -= temp2[i]; + } + offset = WAVELET_TILE_SIZE/2; + if ( (offset & 1) == 0 ) offset++; + for (i=0,ix=0; ix < WAVELET_TILE_SIZE; ix++ ) { + for (iy=0; iy < WAVELET_TILE_SIZE; iy++ ) { + for (iz=0; iz < WAVELET_TILE_SIZE; iz++ ) { + temp1[i++]=noise[ absmod(ix+offset,WAVELET_TILE_SIZE) + + absmod(iy+offset,WAVELET_TILE_SIZE)*WAVELET_TILE_SIZE + + absmod(iz+offset,WAVELET_TILE_SIZE)*WAVELET_TILE_SIZE*WAVELET_TILE_SIZE + ]; + } + } + } + for (i=0; i < WAVELET_TILE_SIZE*WAVELET_TILE_SIZE*WAVELET_TILE_SIZE; i++ ) { + noise[i] += temp1[i]; + } + data->waveletTileData=noise; + free(temp1); + free(temp2); +} + +float TCOD_noise_wavelet (TCOD_noise_t noise, float *f) { + perlin_data_t *data=(perlin_data_t *)noise; + float pf[3]; + int i; + int p[3],c[3],mid[3],n=WAVELET_TILE_SIZE; + float w[3][3],t,result=0.0f; + if ( data->ndim > 3 ) return 0.0f; /* not supported */ + if (! data->waveletTileData ) TCOD_noise_wavelet_init(noise); + for (i=0; i < data->ndim; i++ ) pf[i]=f[i]*WAVELET_SCALE; + for (i=data->ndim; i < 3; i++ ) pf[i]=0.0f; + for (i=0; i < 3; i++ ) { + mid[i]=(int)ceil(pf[i]-0.5f); + t=mid[i] - (pf[i]-0.5f); + w[i][0]=t*t*0.5f; + w[i][2]=(1.0f-t)*(1.0f-t)*0.5f; + w[i][1]=1.0f - w[i][0]-w[i][2]; + } + for (p[2]=-1; p[2]<=1; p[2]++) { + for (p[1]=-1; p[1]<=1; p[1]++) { + for (p[0]=-1; p[0]<=1; p[0]++) { + float weight=1.0f; + for (i=0;i<3;i++) { + c[i]=absmod(mid[i]+p[i],n); + weight *= w[i][p[i]+1]; + } + result += weight * data->waveletTileData[ c[2]*n*n + c[1]*n + c[0] ]; + } + } + } + return CLAMP(-1.0f,1.0f,result); +} + +float TCOD_noise_fbm_wavelet(TCOD_noise_t noise, float *f, float octaves) { + return TCOD_noise_fbm_int(noise,f,octaves,TCOD_noise_wavelet); +} + +float TCOD_noise_turbulence_wavelet(TCOD_noise_t noise, float *f, float octaves) { + return TCOD_noise_turbulence_int(noise,f,octaves,TCOD_noise_wavelet); +} + +void TCOD_noise_set_type (TCOD_noise_t noise, TCOD_noise_type_t type) { + ((perlin_data_t *)noise)->noise_type = type; +} + +float TCOD_noise_get_ex (TCOD_noise_t noise, float *f, TCOD_noise_type_t type) { + switch (type) { + case (TCOD_NOISE_PERLIN): return TCOD_noise_perlin(noise,f); break; + case (TCOD_NOISE_SIMPLEX): return TCOD_noise_simplex(noise,f); break; + case (TCOD_NOISE_WAVELET): return TCOD_noise_wavelet(noise,f); break; + default: + switch (((perlin_data_t *)noise)->noise_type) { + case (TCOD_NOISE_PERLIN): return TCOD_noise_perlin(noise,f); break; + case (TCOD_NOISE_SIMPLEX): return TCOD_noise_simplex(noise,f); break; + case (TCOD_NOISE_WAVELET): return TCOD_noise_wavelet(noise,f); break; + default: return TCOD_noise_simplex(noise,f); break; + } + break; + } +} + +float TCOD_noise_get_fbm_ex (TCOD_noise_t noise, float *f, float octaves, TCOD_noise_type_t type) { + switch (type) { + case (TCOD_NOISE_PERLIN): return TCOD_noise_fbm_perlin(noise,f,octaves); break; + case (TCOD_NOISE_SIMPLEX): return TCOD_noise_fbm_simplex(noise,f,octaves); break; + case (TCOD_NOISE_WAVELET): return TCOD_noise_fbm_wavelet(noise,f,octaves); break; + default: + switch (((perlin_data_t *)noise)->noise_type) { + case (TCOD_NOISE_PERLIN): return TCOD_noise_fbm_perlin(noise,f,octaves); break; + case (TCOD_NOISE_SIMPLEX): return TCOD_noise_fbm_simplex(noise,f,octaves); break; + case (TCOD_NOISE_WAVELET): return TCOD_noise_fbm_wavelet(noise,f,octaves); break; + default: return TCOD_noise_fbm_simplex(noise,f,octaves); break; + } + break; + } +} + +float TCOD_noise_get_turbulence_ex (TCOD_noise_t noise, float *f, float octaves, TCOD_noise_type_t type) { + switch (type) { + case (TCOD_NOISE_PERLIN): return TCOD_noise_turbulence_perlin(noise,f,octaves); break; + case (TCOD_NOISE_SIMPLEX): return TCOD_noise_turbulence_simplex(noise,f,octaves); break; + case (TCOD_NOISE_WAVELET): return TCOD_noise_turbulence_wavelet(noise,f,octaves); break; + default: + switch (((perlin_data_t *)noise)->noise_type) { + case (TCOD_NOISE_PERLIN): return TCOD_noise_turbulence_perlin(noise,f,octaves); break; + case (TCOD_NOISE_SIMPLEX): return TCOD_noise_turbulence_simplex(noise,f,octaves); break; + case (TCOD_NOISE_WAVELET): return TCOD_noise_turbulence_wavelet(noise,f,octaves); break; + default: return TCOD_noise_turbulence_simplex(noise,f,octaves); break; + } + break; + } +} + +float TCOD_noise_get (TCOD_noise_t noise, float *f) { + switch (((perlin_data_t *)noise)->noise_type) { + case (TCOD_NOISE_PERLIN): return TCOD_noise_perlin(noise,f); break; + case (TCOD_NOISE_SIMPLEX): return TCOD_noise_simplex(noise,f); break; + case (TCOD_NOISE_WAVELET): return TCOD_noise_wavelet(noise,f); break; + default: return TCOD_noise_simplex(noise,f); break; + } +} + +float TCOD_noise_get_fbm (TCOD_noise_t noise, float *f, float octaves) { + switch (((perlin_data_t *)noise)->noise_type) { + case (TCOD_NOISE_PERLIN): return TCOD_noise_fbm_perlin(noise,f,octaves); break; + case (TCOD_NOISE_SIMPLEX): return TCOD_noise_fbm_simplex(noise,f,octaves); break; + case (TCOD_NOISE_WAVELET): return TCOD_noise_fbm_wavelet(noise,f,octaves); break; + default: return TCOD_noise_fbm_simplex(noise,f,octaves); break; + } +} + +float TCOD_noise_get_turbulence (TCOD_noise_t noise, float *f, float octaves) { + switch (((perlin_data_t *)noise)->noise_type) { + case (TCOD_NOISE_PERLIN): return TCOD_noise_turbulence_perlin(noise,f,octaves); break; + case (TCOD_NOISE_SIMPLEX): return TCOD_noise_turbulence_simplex(noise,f,octaves); break; + case (TCOD_NOISE_WAVELET): return TCOD_noise_turbulence_wavelet(noise,f,octaves); break; + default: return TCOD_noise_turbulence_simplex(noise,f,octaves); break; + } +} + +void TCOD_noise_delete(TCOD_noise_t noise) { + if (((perlin_data_t *)noise)->waveletTileData) { + free(((perlin_data_t *)noise)->waveletTileData); + } + free((perlin_data_t *)noise); +} diff --git a/tcod_sys/libtcod/include/noise_defaults.h b/tcod_sys/libtcod/src/libtcod/noise_defaults.h similarity index 98% rename from tcod_sys/libtcod/include/noise_defaults.h rename to tcod_sys/libtcod/src/libtcod/noise_defaults.h index 9277ff7de..14f9e0497 100644 --- a/tcod_sys/libtcod/include/noise_defaults.h +++ b/tcod_sys/libtcod/src/libtcod/noise_defaults.h @@ -1,36 +1,36 @@ -/* -* libtcod -* Copyright (c) 2008-2018 Jice & Mingos & rmtew -* All rights reserved. -* -* Redistribution and use in source and binary forms, with or without -* modification, are permitted provided that the following conditions are met: -* * Redistributions of source code must retain the above copyright -* notice, this list of conditions and the following disclaimer. -* * Redistributions in binary form must reproduce the above copyright -* notice, this list of conditions and the following disclaimer in the -* documentation and/or other materials provided with the distribution. -* * The name of Jice or Mingos may not be used to endorse or promote -* products derived from this software without specific prior written -* permission. -* -* THIS SOFTWARE IS PROVIDED BY JICE, MINGOS AND RMTEW ``AS IS'' AND ANY -* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED -* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE -* DISCLAIMED. IN NO EVENT SHALL JICE, MINGOS OR RMTEW BE LIABLE FOR ANY -* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES -* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; -* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND -* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS -* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. -*/ -#ifndef _TCOD_NOISE_DEFAULTS -#define _TCOD_NOISE_DEFAULTS - -#define TCOD_NOISE_MAX_OCTAVES 128 -#define TCOD_NOISE_MAX_DIMENSIONS 4 -#define TCOD_NOISE_DEFAULT_HURST 0.5f -#define TCOD_NOISE_DEFAULT_LACUNARITY 2.0f - -#endif /* _TCOD_NOISE_DEFAULTS */ +/* +* libtcod +* Copyright (c) 2008-2018 Jice & Mingos & rmtew +* All rights reserved. +* +* Redistribution and use in source and binary forms, with or without +* modification, are permitted provided that the following conditions are met: +* * Redistributions of source code must retain the above copyright +* notice, this list of conditions and the following disclaimer. +* * Redistributions in binary form must reproduce the above copyright +* notice, this list of conditions and the following disclaimer in the +* documentation and/or other materials provided with the distribution. +* * The name of Jice or Mingos may not be used to endorse or promote +* products derived from this software without specific prior written +* permission. +* +* THIS SOFTWARE IS PROVIDED BY JICE, MINGOS AND RMTEW ``AS IS'' AND ANY +* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED +* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE +* DISCLAIMED. IN NO EVENT SHALL JICE, MINGOS OR RMTEW BE LIABLE FOR ANY +* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES +* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; +* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND +* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS +* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +*/ +#ifndef _TCOD_NOISE_DEFAULTS +#define _TCOD_NOISE_DEFAULTS + +#define TCOD_NOISE_MAX_OCTAVES 128 +#define TCOD_NOISE_MAX_DIMENSIONS 4 +#define TCOD_NOISE_DEFAULT_HURST 0.5f +#define TCOD_NOISE_DEFAULT_LACUNARITY 2.0f + +#endif /* _TCOD_NOISE_DEFAULTS */ diff --git a/tcod_sys/libtcod/src/parser.cpp b/tcod_sys/libtcod/src/libtcod/parser.cpp similarity index 96% rename from tcod_sys/libtcod/src/parser.cpp rename to tcod_sys/libtcod/src/libtcod/parser.cpp index 2aa8a8b48..f3ca217d4 100644 --- a/tcod_sys/libtcod/src/parser.cpp +++ b/tcod_sys/libtcod/src/libtcod/parser.cpp @@ -1,189 +1,189 @@ -/* -* libtcod -* Copyright (c) 2008-2018 Jice & Mingos & rmtew -* All rights reserved. -* -* Redistribution and use in source and binary forms, with or without -* modification, are permitted provided that the following conditions are met: -* * Redistributions of source code must retain the above copyright -* notice, this list of conditions and the following disclaimer. -* * Redistributions in binary form must reproduce the above copyright -* notice, this list of conditions and the following disclaimer in the -* documentation and/or other materials provided with the distribution. -* * The name of Jice or Mingos may not be used to endorse or promote -* products derived from this software without specific prior written -* permission. -* -* THIS SOFTWARE IS PROVIDED BY JICE, MINGOS AND RMTEW ``AS IS'' AND ANY -* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED -* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE -* DISCLAIMED. IN NO EVENT SHALL JICE, MINGOS OR RMTEW BE LIABLE FOR ANY -* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES -* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; -* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND -* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS -* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. -*/ -#include - -#include -#include -#include -#include -#include - -const char *TCODParserStruct::getName() const { - return TCOD_struct_get_name(data); -} - -TCODParserStruct* TCODParserStruct::addProperty(const char *propname, TCOD_value_type_t type, bool mandatory) { - TCOD_struct_add_property(data,propname,type,mandatory); - return this; -} - -TCODParserStruct* TCODParserStruct::addListProperty(const char *propname, TCOD_value_type_t type, bool mandatory) { - TCOD_struct_add_list_property(data,propname,type,mandatory); - return this; -} - -TCODParserStruct* TCODParserStruct::addValueList(const char *propname, const char **value_list, bool mandatory) { - TCOD_struct_add_value_list(data,propname,value_list,mandatory); - return this; -} - -TCODParserStruct* TCODParserStruct::addFlag(const char *propname) { - TCOD_struct_add_flag(data,propname); - return this; -} - -TCODParserStruct* TCODParserStruct::addStructure(TCODParserStruct *sub_entity) { - TCOD_struct_add_structure(data,sub_entity->data); - return this; -} - -bool TCODParserStruct::isPropertyMandatory(const char *propname) const { - return TCOD_struct_is_mandatory(data,propname) != 0; -} - -TCOD_value_type_t TCODParserStruct::getPropertyType(const char *propname) const { - return TCOD_struct_get_type(data,propname); -} - -TCODParserStruct *TCODParser::newStructure(const char *name) { - TCODParserStruct *ent = new TCODParserStruct(); - ent->data = TCOD_parser_new_struct(data,(char *)name); - defs.push(ent); - return ent; -} - -static ITCODParserListener *listener=NULL; -static TCODParser *parser=NULL; -extern "C" bool new_struct(TCOD_parser_struct_t def,const char *name) { - for ( TCODParserStruct **idef=parser->defs.begin(); idef != parser->defs.end(); idef++) { - if ( (*idef)->data == def ) { - return listener->parserNewStruct(parser,*idef,name) ? 1 : 0; - } - } - // not found. autodeclaring struct - TCODParserStruct *idef = new TCODParserStruct(); - idef->data = def; - parser->defs.push(idef); - return listener->parserNewStruct(parser,idef,name) ? 1 : 0; -} -extern "C" bool new_flag(const char *name) { - return listener->parserFlag(parser,name) ? 1 : 0; -} -extern "C" bool new_property(const char *propname, TCOD_value_type_t type, TCOD_value_t value) { - return listener->parserProperty(parser,propname,type, value) ? 1 : 0; -} -extern "C" bool end_struct(TCOD_parser_struct_t def, const char *name) { - for ( TCODParserStruct **idef=parser->defs.begin(); idef != parser->defs.end(); idef++) { - if ( (*idef)->data == def ) { - return listener->parserEndStruct(parser,*idef,name) ? 1 : 0; - } - } - return 0; -} - -extern "C" void error(const char *msg) { - listener->error(msg); -} - -static TCOD_parser_listener_t c_to_cpp_listener = { - new_struct, - new_flag, - new_property, - end_struct, - error -}; - -TCODParser::TCODParser() { - data = TCOD_parser_new(); -} - -TCODParser::~TCODParser() { - TCOD_parser_delete(data); -} - -void TCODParser::run(const char *filename, ITCODParserListener *_listener) { - listener=_listener; - parser=this; - if ( listener ) TCOD_parser_run(data,(char *)filename,&c_to_cpp_listener); - else TCOD_parser_run(data,(char *)filename, NULL); -} - -TCOD_value_type_t TCODParser::newCustomType(TCOD_parser_custom_t custom_type_parser) { - return TCOD_parser_new_custom_type(data,custom_type_parser); -} - -void TCODParser::error(const char *msg, ...) { - char buf[2048]; - va_list ap; - va_start(ap,msg); - vsprintf(buf,msg,ap); - va_end(ap); - TCOD_parser_error(buf); -} - -// default parser - -bool TCODParser::hasProperty(const char *name) const { - return TCOD_parser_has_property(data,name) != 0; -} - -bool TCODParser::getBoolProperty(const char *name) const { - return TCOD_parser_get_bool_property(data,name) != 0; -} - -int TCODParser::getIntProperty(const char *name) const { - return TCOD_parser_get_int_property(data,name); -} - -int TCODParser::getCharProperty(const char *name) const { - return TCOD_parser_get_char_property(data,name); -} - -float TCODParser::getFloatProperty(const char *name) const { - return TCOD_parser_get_float_property(data,name); -} - -TCODColor TCODParser::getColorProperty(const char *name) const { - return TCOD_parser_get_color_property(data,name); -} - -TCOD_dice_t TCODParser::getDiceProperty(const char *name) const { - return TCOD_parser_get_dice_property(data,name); -} - -const char * TCODParser::getStringProperty(const char *name) const { - return TCOD_parser_get_string_property(data,name); -} - -void * TCODParser::getCustomProperty(const char *name) const { - return TCOD_parser_get_custom_property(data,name); -} - -TCOD_list_t TCODParser::getListProperty(const char *name, TCOD_value_type_t type) const { - return TCOD_parser_get_list_property(data,name,type); -} +/* +* libtcod +* Copyright (c) 2008-2018 Jice & Mingos & rmtew +* All rights reserved. +* +* Redistribution and use in source and binary forms, with or without +* modification, are permitted provided that the following conditions are met: +* * Redistributions of source code must retain the above copyright +* notice, this list of conditions and the following disclaimer. +* * Redistributions in binary form must reproduce the above copyright +* notice, this list of conditions and the following disclaimer in the +* documentation and/or other materials provided with the distribution. +* * The name of Jice or Mingos may not be used to endorse or promote +* products derived from this software without specific prior written +* permission. +* +* THIS SOFTWARE IS PROVIDED BY JICE, MINGOS AND RMTEW ``AS IS'' AND ANY +* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED +* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE +* DISCLAIMED. IN NO EVENT SHALL JICE, MINGOS OR RMTEW BE LIABLE FOR ANY +* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES +* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; +* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND +* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS +* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +*/ +#include "parser.hpp" + +#include +#include +#include +#include +#include + +const char *TCODParserStruct::getName() const { + return TCOD_struct_get_name(data); +} + +TCODParserStruct* TCODParserStruct::addProperty(const char *propname, TCOD_value_type_t type, bool mandatory) { + TCOD_struct_add_property(data,propname,type,mandatory); + return this; +} + +TCODParserStruct* TCODParserStruct::addListProperty(const char *propname, TCOD_value_type_t type, bool mandatory) { + TCOD_struct_add_list_property(data,propname,type,mandatory); + return this; +} + +TCODParserStruct* TCODParserStruct::addValueList(const char *propname, const char **value_list, bool mandatory) { + TCOD_struct_add_value_list(data,propname,value_list,mandatory); + return this; +} + +TCODParserStruct* TCODParserStruct::addFlag(const char *propname) { + TCOD_struct_add_flag(data,propname); + return this; +} + +TCODParserStruct* TCODParserStruct::addStructure(TCODParserStruct *sub_entity) { + TCOD_struct_add_structure(data,sub_entity->data); + return this; +} + +bool TCODParserStruct::isPropertyMandatory(const char *propname) const { + return TCOD_struct_is_mandatory(data,propname) != 0; +} + +TCOD_value_type_t TCODParserStruct::getPropertyType(const char *propname) const { + return TCOD_struct_get_type(data,propname); +} + +TCODParserStruct *TCODParser::newStructure(const char *name) { + TCODParserStruct *ent = new TCODParserStruct(); + ent->data = TCOD_parser_new_struct(data,(char *)name); + defs.push(ent); + return ent; +} + +static ITCODParserListener *listener=NULL; +static TCODParser *parser=NULL; +extern "C" bool new_struct(TCOD_parser_struct_t def,const char *name) { + for ( TCODParserStruct **idef=parser->defs.begin(); idef != parser->defs.end(); idef++) { + if ( (*idef)->data == def ) { + return listener->parserNewStruct(parser,*idef,name) ? 1 : 0; + } + } + // not found. autodeclaring struct + TCODParserStruct *idef = new TCODParserStruct(); + idef->data = def; + parser->defs.push(idef); + return listener->parserNewStruct(parser,idef,name) ? 1 : 0; +} +extern "C" bool new_flag(const char *name) { + return listener->parserFlag(parser,name) ? 1 : 0; +} +extern "C" bool new_property(const char *propname, TCOD_value_type_t type, TCOD_value_t value) { + return listener->parserProperty(parser,propname,type, value) ? 1 : 0; +} +extern "C" bool end_struct(TCOD_parser_struct_t def, const char *name) { + for ( TCODParserStruct **idef=parser->defs.begin(); idef != parser->defs.end(); idef++) { + if ( (*idef)->data == def ) { + return listener->parserEndStruct(parser,*idef,name) ? 1 : 0; + } + } + return 0; +} + +extern "C" void error(const char *msg) { + listener->error(msg); +} + +static TCOD_parser_listener_t c_to_cpp_listener = { + new_struct, + new_flag, + new_property, + end_struct, + error +}; + +TCODParser::TCODParser() { + data = TCOD_parser_new(); +} + +TCODParser::~TCODParser() { + TCOD_parser_delete(data); +} + +void TCODParser::run(const char *filename, ITCODParserListener *_listener) { + listener=_listener; + parser=this; + if ( listener ) TCOD_parser_run(data,(char *)filename,&c_to_cpp_listener); + else TCOD_parser_run(data,(char *)filename, NULL); +} + +TCOD_value_type_t TCODParser::newCustomType(TCOD_parser_custom_t custom_type_parser) { + return TCOD_parser_new_custom_type(data,custom_type_parser); +} + +void TCODParser::error(const char *msg, ...) { + char buf[2048]; + va_list ap; + va_start(ap,msg); + vsprintf(buf,msg,ap); + va_end(ap); + TCOD_parser_error(buf); +} + +// default parser + +bool TCODParser::hasProperty(const char *name) const { + return TCOD_parser_has_property(data,name) != 0; +} + +bool TCODParser::getBoolProperty(const char *name) const { + return TCOD_parser_get_bool_property(data,name) != 0; +} + +int TCODParser::getIntProperty(const char *name) const { + return TCOD_parser_get_int_property(data,name); +} + +int TCODParser::getCharProperty(const char *name) const { + return TCOD_parser_get_char_property(data,name); +} + +float TCODParser::getFloatProperty(const char *name) const { + return TCOD_parser_get_float_property(data,name); +} + +TCODColor TCODParser::getColorProperty(const char *name) const { + return TCOD_parser_get_color_property(data,name); +} + +TCOD_dice_t TCODParser::getDiceProperty(const char *name) const { + return TCOD_parser_get_dice_property(data,name); +} + +const char * TCODParser::getStringProperty(const char *name) const { + return TCOD_parser_get_string_property(data,name); +} + +void * TCODParser::getCustomProperty(const char *name) const { + return TCOD_parser_get_custom_property(data,name); +} + +TCOD_list_t TCODParser::getListProperty(const char *name, TCOD_value_type_t type) const { + return TCOD_parser_get_list_property(data,name,type); +} diff --git a/tcod_sys/libtcod/include/parser.h b/tcod_sys/libtcod/src/libtcod/parser.h similarity index 96% rename from tcod_sys/libtcod/include/parser.h rename to tcod_sys/libtcod/src/libtcod/parser.h index 2f1110ff8..67b62ec90 100644 --- a/tcod_sys/libtcod/include/parser.h +++ b/tcod_sys/libtcod/src/libtcod/parser.h @@ -28,7 +28,7 @@ #ifndef _TCOD_PARSER_H #define _TCOD_PARSER_H -#include "libtcod_portability.h" +#include "portability.h" #include "color.h" #include "list.h" #include "lex.h" @@ -96,7 +96,8 @@ typedef union { } TCOD_value_t; /* parser structures */ -typedef void *TCOD_parser_struct_t; +struct TCOD_ParserStruct; +typedef struct TCOD_ParserStruct *TCOD_parser_struct_t; TCODLIB_API const char *TCOD_struct_get_name(TCOD_parser_struct_t def); TCODLIB_API void TCOD_struct_add_property(TCOD_parser_struct_t def, const char *name,TCOD_value_type_t type, bool mandatory); TCODLIB_API void TCOD_struct_add_list_property(TCOD_parser_struct_t def, const char *name,TCOD_value_type_t type, bool mandatory); @@ -121,7 +122,8 @@ typedef struct { typedef TCOD_value_t (*TCOD_parser_custom_t)(TCOD_lex_t *lex, TCOD_parser_listener_t *listener, TCOD_parser_struct_t str, char *propname); /* the parser */ -typedef void *TCOD_parser_t; +struct TCOD_Parser; +typedef struct TCOD_Parser *TCOD_parser_t; TCODLIB_API TCOD_parser_t TCOD_parser_new(void); TCODLIB_API TCOD_parser_struct_t TCOD_parser_new_struct(TCOD_parser_t parser, char *name); @@ -145,7 +147,7 @@ TCODLIB_API TCOD_list_t TCOD_parser_get_list_property(TCOD_parser_t parser, cons /* parser internals (may be used by custom type parsers) */ /* parser structures */ -typedef struct { +typedef struct TCOD_ParserStruct { char *name; /* entity type name */ /* list of flags */ TCOD_list_t flags; @@ -157,7 +159,7 @@ typedef struct { TCOD_list_t structs; } TCOD_struct_int_t; /* the parser */ -typedef struct { +typedef struct TCOD_Parser { /* list of structures */ TCOD_list_t structs; /* list of custom type parsers */ diff --git a/tcod_sys/libtcod/include/parser.hpp b/tcod_sys/libtcod/src/libtcod/parser.hpp similarity index 100% rename from tcod_sys/libtcod/include/parser.hpp rename to tcod_sys/libtcod/src/libtcod/parser.hpp diff --git a/tcod_sys/libtcod/src/parser_c.c b/tcod_sys/libtcod/src/libtcod/parser_c.c similarity index 95% rename from tcod_sys/libtcod/src/parser_c.c rename to tcod_sys/libtcod/src/libtcod/parser_c.c index c9d5d6b72..44023a983 100644 --- a/tcod_sys/libtcod/src/parser_c.c +++ b/tcod_sys/libtcod/src/libtcod/parser_c.c @@ -1,933 +1,933 @@ -/* -* libtcod -* Copyright (c) 2008-2018 Jice & Mingos & rmtew -* All rights reserved. -* -* Redistribution and use in source and binary forms, with or without -* modification, are permitted provided that the following conditions are met: -* * Redistributions of source code must retain the above copyright -* notice, this list of conditions and the following disclaimer. -* * Redistributions in binary form must reproduce the above copyright -* notice, this list of conditions and the following disclaimer in the -* documentation and/or other materials provided with the distribution. -* * The name of Jice or Mingos may not be used to endorse or promote -* products derived from this software without specific prior written -* permission. -* -* THIS SOFTWARE IS PROVIDED BY JICE, MINGOS AND RMTEW ``AS IS'' AND ANY -* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED -* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE -* DISCLAIMED. IN NO EVENT SHALL JICE, MINGOS OR RMTEW BE LIABLE FOR ANY -* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES -* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; -* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND -* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS -* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. -*/ -#include - -#include -#include -#include -#include - -#include - -#define BIG_NAME_LEN 128 - -#define DEF_NAME(d) (((TCOD_struct_int_t *)d)->name) -#define DEF_FLAGS(d) (((TCOD_struct_int_t *)d)->flags) -#define DEF_PROPS(d) (((TCOD_struct_int_t *)d)->props) -#define DEF_LISTS(d) (((TCOD_struct_int_t *)d)->lists) - -/* definition property */ -typedef struct { - char *name; - TCOD_value_type_t value; - bool mandat; -} TCOD_struct_prop_t; - -static TCOD_lex_t *lex=NULL; - -static const char *symbols[] = { - "{","}","=","/","+","-","[","]",",","#",NULL -}; - -static const char *keywords[] = { - "struct","bool","char","int","float","string","color","dice",NULL -}; - -static TCOD_parser_listener_t *listener=NULL; - -static bool default_new_struct(TCOD_parser_struct_t str,const char *name); -static bool default_new_flag(const char *name); -static bool default_new_property(const char *propname, TCOD_value_type_t type, TCOD_value_t value); -static bool default_end_struct(TCOD_parser_struct_t str, const char *name); -static void default_error(const char *msg); - -static TCOD_parser_listener_t default_listener = { - default_new_struct, - default_new_flag, - default_new_property, - default_end_struct, - default_error -}; - -static bool string_copy(char *dest, char *source, int len) { - if ( source == NULL ) return false; - strncpy(dest,source,len); - dest[len-1]='\0'; - if ( strlen(source) >= (unsigned)len ) return false; - return true; -} - -void TCOD_parser_error(const char *msg, ...) { - char buf[2048]; - char buf2[2048]; - va_list ap; - va_start(ap,msg); - vsprintf(buf,msg,ap); - va_end(ap); - sprintf(buf2,"error in %s line %d : %s",lex->filename,lex->file_line,buf); - listener->error(buf2); - lex->token_type = TCOD_LEX_ERROR; -} - -const char *TCOD_struct_get_name(TCOD_parser_struct_t def) { - return ((TCOD_struct_int_t *)def)->name; -} - -/* add a property to an entity definition */ -void TCOD_struct_add_property(TCOD_parser_struct_t def,const char *name,TCOD_value_type_t type, bool mandatory) { - TCOD_struct_prop_t *prop=(TCOD_struct_prop_t *)calloc(1,sizeof(TCOD_struct_prop_t)); - prop->name=TCOD_strdup(name); - prop->value=type; - prop->mandat=mandatory; - TCOD_list_push(DEF_PROPS(def),(void *)prop); -} - -/* add a list property to an entity definition */ -void TCOD_struct_add_list_property(TCOD_parser_struct_t def,const char *name,TCOD_value_type_t type, bool mandatory) { - TCOD_struct_add_property(def,name,type|TCOD_TYPE_LIST,mandatory); -} - -void TCOD_struct_add_value_list_sized(TCOD_parser_struct_t def,const char *name, const char **value_list, int size, bool mandatory) { - char ** newArray = NULL; - /* duplicate value list to avoid issues with C# garbage collector */ - TCOD_value_type_t type = (TCOD_value_type_t)((int)TCOD_TYPE_VALUELIST00 + TCOD_list_size(DEF_LISTS(def))); - int i = 0; - - if(size) newArray = calloc(size+1, sizeof(char*)); - - for(i = 0 ; i < size ; i++) - newArray[i] = TCOD_strdup(value_list[i]); - newArray[size] = NULL; - - TCOD_struct_add_property(def,name,type,mandatory); - TCOD_list_push(DEF_LISTS(def),(void *)newArray); -} - -/* add a value-list property to an entity definition */ -void TCOD_struct_add_value_list(TCOD_parser_struct_t def,const char *name, const char **value_list, bool mandatory) { - int size = 0; - if(value_list) - { - while(value_list[size] != NULL) - { - size++; - }; - } - TCOD_struct_add_value_list_sized(def, name, value_list, size, mandatory); -} - - -/* add a flag (simplified bool value) to an entity definition */ -/* a flag cannot be mandatory. if present => true, if omitted => false */ -void TCOD_struct_add_flag(TCOD_parser_struct_t def,const char *propname) { - TCOD_list_push(DEF_FLAGS(def),(void *)TCOD_strdup(propname)); -} - -/* add a sub-entity to an entity definition */ -void TCOD_struct_add_structure(TCOD_parser_struct_t def, TCOD_parser_struct_t sub_definition) { - TCOD_list_push(((TCOD_struct_int_t *)def)->structs,(const void *)sub_definition); -} - -/* check if given property is mandatory for this entity definition */ -bool TCOD_struct_is_mandatory(TCOD_parser_struct_t def, const char *propname) { - TCOD_struct_prop_t **iprop; - for (iprop=(TCOD_struct_prop_t **)TCOD_list_begin(DEF_PROPS(def)); iprop!=(TCOD_struct_prop_t **)TCOD_list_end(DEF_PROPS(def));iprop++) { - if ( strcmp((*iprop)->name,propname) == 0 ) return (*iprop)->mandat; - } - return false; -} - -/* returns the type of given property */ -/* NONE if the property does not exist */ -TCOD_value_type_t TCOD_struct_get_type(TCOD_parser_struct_t def, const char *propname) { - TCOD_struct_prop_t **iprop; - char **iflag; - for (iprop=(TCOD_struct_prop_t **)TCOD_list_begin(DEF_PROPS(def)); iprop!=(TCOD_struct_prop_t **)TCOD_list_end(DEF_PROPS(def));iprop++) { - if ( strcmp((*iprop)->name,propname) == 0 ) return (*iprop)->value; - } - for (iflag=(char **)TCOD_list_begin(DEF_FLAGS(def)); iflag!=(char **)TCOD_list_end(DEF_FLAGS(def));iflag++) { - if ( strcmp((*iflag),propname) == 0 ) return TCOD_TYPE_BOOL; - } - return TCOD_TYPE_NONE; -} - -TCOD_value_t TCOD_parse_bool_value(void) { - TCOD_value_t ret; - if ( strcmp(lex->tok,"true") == 0 ) ret.b=true; - else if ( strcmp(lex->tok,"false") == 0 ) ret.b=false; - else TCOD_parser_error("parseBoolValue : unknown value %s for bool. 'true' or 'false' expected",lex->tok); - return ret; -} - -TCOD_value_t TCOD_parse_char_value(void) { - TCOD_value_t ret; - if ( lex->token_type != TCOD_LEX_CHAR && lex->token_type != TCOD_LEX_INTEGER ) - TCOD_parser_error("parseCharValue : char constant expected instead of '%s'",lex->tok); - ret.c=lex->token_int_val; - return ret; -} - -TCOD_value_t TCOD_parse_integer_value(void) { - TCOD_value_t ret; - if ( lex->token_type != TCOD_LEX_INTEGER ) - TCOD_parser_error("parseIntegerValue : integer constant expected instead of '%s'",lex->tok); - ret.i=lex->token_int_val; - return ret; -} - -TCOD_value_t TCOD_parse_float_value(void) { - TCOD_value_t ret; - if ( lex->token_type != TCOD_LEX_FLOAT && lex->token_type != TCOD_LEX_INTEGER ) - TCOD_parser_error("parseFloatValue : float constant expected instead of '%s'",lex->tok); - if ( lex->token_type == TCOD_LEX_FLOAT ) ret.f=lex->token_float_val; - else ret.f=(float)lex->token_int_val; - return ret; -} - -TCOD_value_t TCOD_parse_string_value(void) { - TCOD_value_t ret; - TCOD_list_t l; - bool end=false; - char **s; - size_t slen=0; - l=TCOD_list_new(); - if ( lex->token_type != TCOD_LEX_STRING ) TCOD_parser_error("parseStringValue : string constant expected instead of '%s'",lex->tok); - while ( !end ) { - TCOD_lex_t save; - TCOD_list_push(l,(void *)TCOD_strdup(lex->tok)); - TCOD_lex_savepoint(lex,&save); - if (TCOD_lex_parse(lex) != TCOD_LEX_STRING) { - end=true; - TCOD_lex_restore(lex,&save); - } - } - for (s=(char **)TCOD_list_begin(l); s != (char **)TCOD_list_end(l); s++ ) { - slen += strlen(*s); - } - ret.s=(char *)calloc(sizeof(char),slen+1); - for (s=(char **)TCOD_list_begin(l); s != (char **)TCOD_list_end(l); s++ ) { - strcat(ret.s,*s); - free(*s); - } - TCOD_list_delete(l); - return ret; -} - -TCOD_value_t TCOD_parse_color_value(void) { - TCOD_value_t ret; - if ( lex->token_type == TCOD_LEX_SYMBOL && lex->tok[0]=='#') { - char tmp[128]=""; - int tok=TCOD_lex_parse(lex); - /* format : col = #FFFFFF */ - strcat(tmp,"#"); - if ( tok == TCOD_LEX_IDEN || tok == TCOD_LEX_INTEGER ) { - strcat(tmp,lex->tok); - strcpy(lex->tok,tmp); - if ( strlen(lex->tok) < 7 && tok == TCOD_LEX_INTEGER ) { - /* special case of #12AABB => symbol # + - integer 12 + iden AABB */ - tok=TCOD_lex_parse(lex); - if ( tok == TCOD_LEX_IDEN ) { - strcat(tmp,lex->tok); - strcpy(lex->tok,tmp); - } - } - lex->token_type = TCOD_LEX_STRING; - } - } - if ( lex->token_type != TCOD_LEX_STRING ) TCOD_parser_error("parseColorValue : string constant expected instead of '%s'",lex->tok); - if (lex->tok[0] == '#') { - int r,g,b; - if ( strlen(lex->tok) != 7 ) TCOD_parser_error("parseColorValue : bad color format. '#rrggbb' expected instead of '%s'",lex->tok); - /* web format : #rrggbb */ - r=(TCOD_lex_hextoint(lex->tok[1])<<4) + TCOD_lex_hextoint(lex->tok[2]); - g=(TCOD_lex_hextoint(lex->tok[3])<<4) + TCOD_lex_hextoint(lex->tok[4]); - b=(TCOD_lex_hextoint(lex->tok[5])<<4) + TCOD_lex_hextoint(lex->tok[6]); - ret.col.r=r; - ret.col.g=g; - ret.col.b=b; - } else { - /* standard format : rrr,ggg,bbb */ - char *begin=lex->tok; - char *end=strchr(begin,','); - bool ok=true; - if (! end) ok=false; - else { - *end=0; - ret.col.r=atoi(begin); - begin=end+1; - end=strchr(begin,','); - if ( !end ) ok=false; - else { - ret.col.g=atoi(begin); - begin=end+1; - ret.col.b=atoi(begin); - } - - } - if (!ok) TCOD_parser_error("parseColorValue : bad color format 'rrr,ggg,bbb' expected instead of '%s'",lex->tok); - } - return ret; -} - -TCOD_value_t TCOD_parse_dice_value(void) { - /* dice format : [(x|*)](D|d)[(+|-)] */ - TCOD_value_t ret; - bool minus=false; - char *begin; - char *ptr; - ret.dice.multiplier=1.0f; - ret.dice.addsub=0.0f; - begin=lex->tok; - ptr=strchr(begin,'x'); - if (! ptr ) ptr=strchr(begin,'*'); - if ( ptr ) { - /* parse multiplier */ - *ptr=0; - ret.dice.multiplier=(float)atof(lex->tok); - begin=ptr+1; - } - ptr=strchr(begin,'D'); - if (!ptr ) ptr=strchr(begin,'d'); - if (! ptr ) TCOD_parser_error("parseDiceValue : bad dice format. [(x|*)](D|d)[(+|-)] expected instead of '%s'",lex->tok); - *ptr=0; - /* parse nb_rolls */ - ret.dice.nb_rolls=atoi(begin); - begin=ptr+1; - ptr=strchr(begin,'+'); - if (! ptr) { - ptr = strchr(begin,'-'); - if ( ptr ) minus=true; - } - if (ptr) *ptr=0; - /* parse nb_faces */ - ret.dice.nb_faces=atoi(begin); - if ( ptr ) { - /* parse addsub */ - begin=ptr+1; - ret.dice.addsub=(float)atof(begin); - if ( minus ) ret.dice.addsub=-ret.dice.addsub; - } - return ret; -} - -TCOD_value_t TCOD_parse_value_list_value(TCOD_struct_int_t *def,int listnum) { - TCOD_value_t ret; - int i=0; - char *value; - char **value_list=TCOD_list_get(def->lists,listnum); - if ( lex->token_type != TCOD_LEX_STRING) TCOD_parser_error("parseValueListValue : string constant expected instead of '%s'",lex->tok); - value= value_list[i]; - while ( value ) { - if ( strcmp(lex->tok,value) == 0 ) break; - i++; - value=value_list[i]; - } - if (! value ) TCOD_parser_error("parseValueListValue : incorrect value '%s'",lex->tok); - ret.s = value; - return ret; -} - - -TCOD_value_t TCOD_parse_property_value(TCOD_parser_int_t *parser, TCOD_parser_struct_t def, char *propname, bool list) { - TCOD_value_type_t type=TCOD_struct_get_type(def,propname); - TCOD_value_t ret={0}; - if (! list ) type &= ~ TCOD_TYPE_LIST; - if ( type & TCOD_TYPE_LIST ) { - type &= ~ TCOD_TYPE_LIST; - if ( strcmp(lex->tok,"[") != 0 ) { - TCOD_parser_error("'[' expected for list value instead of '%s'",lex->tok); - } - ret.list=TCOD_list_new(); - do { - TCOD_value_t val; - int tok=TCOD_lex_parse(lex); - if ( tok == TCOD_LEX_EOF || tok == TCOD_LEX_ERROR ) { - TCOD_parser_error("Missing ']' in list value"); - } - val=TCOD_parse_property_value(parser,def,propname,false); - if ( type == TCOD_TYPE_STRING || (type >= TCOD_TYPE_VALUELIST00 && type <= TCOD_TYPE_VALUELIST15 ) ) { - TCOD_list_push(ret.list,TCOD_strdup(val.s)); - } else { - TCOD_list_push(ret.list,val.custom); - } - TCOD_lex_parse(lex); - if ( strcmp(lex->tok,",") != 0 && strcmp(lex->tok,"]") != 0 ) { - TCOD_parser_error("',' or ']' expected in list value instead of '%s'",lex->tok); - } - } while ( strcmp(lex->tok,"]") != 0 ); - } else { - switch (type) { - case TCOD_TYPE_BOOL : return TCOD_parse_bool_value(); break; - case TCOD_TYPE_CHAR : return TCOD_parse_char_value(); break; - case TCOD_TYPE_INT : return TCOD_parse_integer_value(); break; - case TCOD_TYPE_FLOAT : return TCOD_parse_float_value(); break; - case TCOD_TYPE_STRING : return TCOD_parse_string_value(); break; - case TCOD_TYPE_COLOR : return TCOD_parse_color_value(); break; - case TCOD_TYPE_DICE : return TCOD_parse_dice_value(); break; - case TCOD_TYPE_VALUELIST00 : - case TCOD_TYPE_VALUELIST01 : - case TCOD_TYPE_VALUELIST02 : - case TCOD_TYPE_VALUELIST03 : - case TCOD_TYPE_VALUELIST04 : - case TCOD_TYPE_VALUELIST05 : - case TCOD_TYPE_VALUELIST06 : - case TCOD_TYPE_VALUELIST07 : - case TCOD_TYPE_VALUELIST08 : - case TCOD_TYPE_VALUELIST09 : - case TCOD_TYPE_VALUELIST10 : - case TCOD_TYPE_VALUELIST11 : - case TCOD_TYPE_VALUELIST12 : - case TCOD_TYPE_VALUELIST13 : - case TCOD_TYPE_VALUELIST14 : - case TCOD_TYPE_VALUELIST15 : { - int listnum = type - TCOD_TYPE_VALUELIST00; - return TCOD_parse_value_list_value((TCOD_struct_int_t *)def,listnum); break; - } - case TCOD_TYPE_CUSTOM00 : - case TCOD_TYPE_CUSTOM01 : - case TCOD_TYPE_CUSTOM02 : - case TCOD_TYPE_CUSTOM03 : - case TCOD_TYPE_CUSTOM04 : - case TCOD_TYPE_CUSTOM05 : - case TCOD_TYPE_CUSTOM06 : - case TCOD_TYPE_CUSTOM07 : - case TCOD_TYPE_CUSTOM08 : - case TCOD_TYPE_CUSTOM09 : - case TCOD_TYPE_CUSTOM10 : - case TCOD_TYPE_CUSTOM11 : - case TCOD_TYPE_CUSTOM12 : - case TCOD_TYPE_CUSTOM13 : - case TCOD_TYPE_CUSTOM14 : - case TCOD_TYPE_CUSTOM15 : - if ( parser->customs[type - TCOD_TYPE_CUSTOM00] ) { - return parser->customs[type-TCOD_TYPE_CUSTOM00](lex,listener,def,propname); - } else { - TCOD_parser_error("parse_property_value : no custom parser for property type %d for entity %s prop %s", - type,DEF_NAME(def),propname); - } - break; - default : TCOD_parser_error("parse_property_value : unknown property type %d for entity %s prop %s", - type,DEF_NAME(def),propname); break; - } - } - return ret; -} - -static bool TCOD_parser_parse_entity(TCOD_parser_int_t *parser, TCOD_struct_int_t *def) { - char *name=NULL; - if ( TCOD_lex_parse(lex) == TCOD_LEX_STRING ) { - /* entity type name */ - name=TCOD_strdup(lex->tok); - TCOD_lex_parse(lex); - } - if ( strcmp(lex->tok,"{") != 0 ) { - TCOD_parser_error("Parser::parseEntity : '{' expected"); - return false; - } - TCOD_lex_parse(lex); - while ( strcmp(lex->tok,"}") != 0 ) { - bool found=false; - char **iflag; - bool dynStruct=false; - TCOD_value_type_t dynType = TCOD_TYPE_NONE; - if ( lex->token_type == TCOD_LEX_KEYWORD ) { - /* dynamic property declaration */ - if ( strcmp(lex->tok,"bool") == 0 ) dynType=TCOD_TYPE_BOOL; - else if ( strcmp(lex->tok,"char") == 0 ) dynType=TCOD_TYPE_CHAR; - else if ( strcmp(lex->tok,"int") == 0 ) dynType=TCOD_TYPE_INT; - else if ( strcmp(lex->tok,"float") == 0 ) dynType=TCOD_TYPE_FLOAT; - else if ( strcmp(lex->tok,"string") == 0 ) dynType=TCOD_TYPE_STRING; - else if ( strcmp(lex->tok,"color") == 0 ) dynType=TCOD_TYPE_COLOR; - else if ( strcmp(lex->tok,"dice") == 0 ) dynType=TCOD_TYPE_DICE; - else if ( strcmp(lex->tok,"struct") == 0 ) dynStruct=true; - else { - TCOD_parser_error("Parser::parseEntity : dynamic declaration of '%s' not supported",lex->tok); - return false; - } - /* TODO : dynamically declared sub-structures */ - TCOD_lex_parse(lex); - if ( strcmp(lex->tok,"[") == 0 ) { - if ( dynType == TCOD_TYPE_NONE ) { - TCOD_parser_error("Parser::parseEntity : unexpected symbol '['"); - return false; - } - TCOD_lex_parse(lex); - if ( strcmp(lex->tok,"]") != 0 ) { - TCOD_parser_error("Parser::parseEntity : syntax error. ']' expected instead of '%s'",lex->tok); - return false; - } - dynType |= TCOD_TYPE_LIST; - TCOD_lex_parse(lex); - } - } - /* parse entity type content */ - if ( lex->token_type != TCOD_LEX_IDEN ) { - TCOD_parser_error("Parser::parseEntity : identifier expected"); - return false; - } - /* is it a flag ? */ - if (! dynStruct && dynType == TCOD_TYPE_NONE) { - for (iflag=(char **)TCOD_list_begin(def->flags);iflag!=(char **)TCOD_list_end(def->flags); iflag++) { - if ( strcmp(*iflag,lex->tok) == 0 ) { - found=true; - if (!listener->new_flag(lex->tok)) return false; - break; - } - } - } - if (!found && ! dynStruct) { - do { - /* is it a property ? */ - TCOD_struct_prop_t **iprop; - for (iprop=(TCOD_struct_prop_t **)TCOD_list_begin(def->props); iprop!=(TCOD_struct_prop_t **)TCOD_list_end(def->props);iprop++) { - if ( strcmp((*iprop)->name,lex->tok) == 0 ) { - char propname[BIG_NAME_LEN]; - string_copy(propname,lex->tok,BIG_NAME_LEN); - TCOD_lex_parse(lex); - if ( strcmp(lex->tok,"=") != 0 ) { - TCOD_parser_error("Parser::parseEntity : '=' expected"); - return false; - } - TCOD_lex_parse(lex); - if (!listener->new_property(propname,TCOD_struct_get_type(def,propname), - TCOD_parse_property_value(parser, (TCOD_parser_struct_t *)def,propname,true))) return false; - if ( lex->token_type == TCOD_LEX_ERROR ) return false; - found=true; - break; - } - } - if ( !found && dynType != TCOD_TYPE_NONE ) { - /* dynamically add a property to the current structure */ - TCOD_struct_add_property(def,lex->tok,dynType,false); - } - } while ( ! found && dynType != TCOD_TYPE_NONE); - } - if (! found ) { - /* is it a sub-entity type */ - char id[BIG_NAME_LEN*2 + 2]; - bool blockFound=false; - do { - TCOD_lex_t save; - char type[BIG_NAME_LEN]; - char *subname=NULL; - bool named=false; - TCOD_lex_savepoint(lex,&save); - string_copy(type,lex->tok,BIG_NAME_LEN); - strcpy(id,type); - if ( TCOD_lex_parse(lex) == TCOD_LEX_STRING ) { - /* # */ - TCOD_struct_int_t **sub; - strcat(id,"#"); - strcat(id,lex->tok); - named=true; - subname=TCOD_strdup(lex->tok); - TCOD_lex_restore(lex,&save); - for ( sub = (TCOD_struct_int_t **)TCOD_list_begin(def->structs); - sub != (TCOD_struct_int_t **)TCOD_list_end(def->structs); sub ++ ) { - if ( strcmp((*sub)->name,id) == 0 ) { - if (!listener->new_struct((TCOD_parser_struct_t *)(*sub),lex->tok)) return false; - if (!TCOD_parser_parse_entity(parser,*sub)) return false; - blockFound=true; - found=true; - break; - } - } - } else { - TCOD_lex_restore(lex,&save); - } - if (! blockFound ) { - /* alone */ - TCOD_struct_int_t **sub; - for ( sub = (TCOD_struct_int_t **)TCOD_list_begin(def->structs); - sub != (TCOD_struct_int_t **)TCOD_list_end(def->structs); sub ++ ) { - if ( strcmp((*sub)->name,type) == 0 ) { - if (!listener->new_struct((TCOD_parser_struct_t *)(*sub),subname)) return false; - if (!TCOD_parser_parse_entity(parser,*sub)) return false; - blockFound=true; - found=true; - break; - } - } - } - if (! blockFound && dynStruct ) { - /* unknown structure. auto-declaration */ - TCOD_struct_int_t **idef; - TCOD_struct_int_t *s=NULL; - for (idef=(TCOD_struct_int_t **)TCOD_list_begin(parser->structs); idef!=(TCOD_struct_int_t **)TCOD_list_end(parser->structs); idef ++) { - if ( strcmp((*idef)->name,id) == 0 ) { - s=*idef; - break; - } - } - if ( s == NULL && named ) { - /* look for general definition for entity # */ - for (idef=(TCOD_struct_int_t **)TCOD_list_begin(parser->structs); idef!=(TCOD_struct_int_t **)TCOD_list_end(parser->structs); idef ++) { - if ( strcmp((*idef)->name,type) == 0 ) { - s=*idef; - break; - } - } - } - if ( s == NULL ) { - /* dyn struct not found. create it */ - s = TCOD_parser_new_struct(parser,type); - } - TCOD_struct_add_structure(def,s); - } - } while (!blockFound && dynStruct ); - if (! blockFound ) { - TCOD_parser_error("Parser::parseEntity : entity type %s does not contain %s", - def->name,id); - return false; - } - } - TCOD_lex_parse(lex); - } - if (!listener->end_struct((TCOD_parser_struct_t *)def,name)) return false; - return true; -} - -/****************************************/ -/* generic parser */ -/****************************************/ - -TCOD_parser_t TCOD_parser_new(void) { - TCOD_parser_int_t *ent = (TCOD_parser_int_t*)calloc(1,sizeof(TCOD_parser_int_t)); - ent->structs=TCOD_list_new(); - return (TCOD_parser_t) ent; -} - -TCOD_value_type_t TCOD_parser_new_custom_type(TCOD_parser_t parser, TCOD_parser_custom_t custom_type_parser) { - TCOD_parser_int_t *p=(TCOD_parser_int_t *)parser; - TCOD_value_type_t type= TCOD_TYPE_CUSTOM00; - while ( p->customs[ type - TCOD_TYPE_CUSTOM00 ] && type < TCOD_TYPE_CUSTOM15 ) type=(TCOD_value_type_t)(type+1); - if ( p->customs[ type - TCOD_TYPE_CUSTOM00 ] ) { - /* no more custom types slots available */ - return TCOD_TYPE_NONE; - } - p->customs[type - TCOD_TYPE_CUSTOM00] = custom_type_parser; - return type; -} - -TCOD_parser_struct_t TCOD_parser_new_struct(TCOD_parser_t parser, char *name) { - TCOD_struct_int_t *ent = (TCOD_struct_int_t*)calloc(1,sizeof(TCOD_struct_int_t)); - ent->name=TCOD_strdup(name); - ent->flags=TCOD_list_new(); - ent->props=TCOD_list_new(); - ent->lists=TCOD_list_new(); - ent->structs=TCOD_list_new(); - TCOD_list_push(((TCOD_parser_int_t *)parser)->structs,ent); - return (TCOD_parser_struct_t )ent; -} - -void TCOD_parser_delete(TCOD_parser_t parser) { - TCOD_parser_int_t *p=(TCOD_parser_int_t *)parser; - TCOD_struct_int_t **idef; - TCOD_struct_prop_t **propCleanup; - - char *** listCleanup; - int listSize = 0; - - for (idef=(TCOD_struct_int_t **)TCOD_list_begin(p->structs); idef!= (TCOD_struct_int_t **)TCOD_list_end(p->structs); idef++) { - free((*idef)->name); - - for ( propCleanup = (TCOD_struct_prop_t**) TCOD_list_begin((*idef)->props); propCleanup != (TCOD_struct_prop_t**)TCOD_list_end((*idef)->props); propCleanup++ ) { - free((*propCleanup)->name); - } - TCOD_list_clear_and_delete((*idef)->props); - - - for ( listCleanup = (char ***) TCOD_list_begin((*idef)->lists); listCleanup != (char ***)TCOD_list_end((*idef)->lists); listCleanup++ ) { - while((*listCleanup)[listSize] != NULL) { - free((*listCleanup)[listSize]); - listSize++; - } - } - TCOD_list_clear_and_delete((*idef)->lists); - } - TCOD_list_clear_and_delete(p->structs); -} - -/* parse a file */ -static TCOD_list_t *default_props; -/* triggers callbacks in the listener for each event during parsing */ -void TCOD_parser_run(TCOD_parser_t parser, const char *filename, TCOD_parser_listener_t *_listener) { - TCOD_parser_int_t *p=(TCOD_parser_int_t *)parser; - if (! _listener && ! p->props ) p->props=TCOD_list_new(); - listener=_listener ? _listener : &default_listener; - default_props = p->props; - lex=TCOD_lex_new(symbols,keywords,"//","/*","*/",NULL,"\"",TCOD_LEX_FLAG_NESTING_COMMENT); - if (!TCOD_lex_set_data_file(lex,(char *)filename)) { - char buf[1024]; - sprintf(buf,"Fatal error : %s\n",TCOD_lex_get_last_error()); - listener->error(buf); - return; - } - while (1) { - bool named=false; - char id[ BIG_NAME_LEN*2 + 2 ]; - char type[ BIG_NAME_LEN ]; - TCOD_lex_t save; - TCOD_struct_int_t *def=NULL; - TCOD_struct_int_t **idef; - bool dynStruct=false; - TCOD_lex_parse(lex); - if ( lex->token_type == TCOD_LEX_EOF || lex->token_type == TCOD_LEX_ERROR ) break; - if ( lex->token_type == TCOD_LEX_KEYWORD ) { - if ( strcmp(lex->tok,"struct") == 0) { - /* level 0 dynamic structure declaration */ - dynStruct=true; - TCOD_lex_parse(lex); - } else { - TCOD_parser_error("Parser::parse : unexpected keyword '%s'",lex->tok); - return; - } - } - /* get entity type */ - if ( lex->token_type != TCOD_LEX_IDEN ) { - TCOD_parser_error("Parser::parse : identifier token expected"); - return; - } - string_copy(type,lex->tok,BIG_NAME_LEN); - strcpy(id,type); - TCOD_lex_savepoint(lex,&save); - if ( TCOD_lex_parse(lex) == TCOD_LEX_STRING ) { - /* named entity. id = # */ - strcat(id,"#"); - if ( strlen(lex->tok) >= BIG_NAME_LEN ) { - TCOD_parser_error("Parser::parse : name %s too long. Max %d characters", - lex->tok,BIG_NAME_LEN-1); - return; - } - strcat(id,lex->tok); - named=true; - } - TCOD_lex_restore(lex,&save); - do { - /* look for a definition for id */ - for (idef=(TCOD_struct_int_t **)TCOD_list_begin(p->structs); idef!=(TCOD_struct_int_t **)TCOD_list_end(p->structs); idef ++) { - if ( strcmp((*idef)->name,id) == 0 ) { - def=*idef; - break; - } - } - if ( def == NULL && named ) { - /* look for general definition for entity # */ - for (idef=(TCOD_struct_int_t **)TCOD_list_begin(p->structs); idef!=(TCOD_struct_int_t **)TCOD_list_end(p->structs); idef ++) { - if ( strcmp((*idef)->name,type) == 0 ) { - def=(*idef); - break; - } - } - } - if ( def == NULL && dynStruct ) { - /* dyn struct not found. create it */ - TCOD_parser_new_struct(parser,type); - } - } while ( def == NULL && dynStruct ); - if (def == NULL ) { - TCOD_parser_error("Parser::parse : unknown entity type %s",type); - return; - } else { - if (!listener->new_struct((TCOD_parser_struct_t)def,named ? strchr(id,'#')+1 : NULL )) return; - if (!TCOD_parser_parse_entity(p,def)) return; - } - } - if (lex->token_type == TCOD_LEX_ERROR) { - TCOD_parser_error("Parser::parse : error while parsing"); - return; - } - TCOD_lex_delete(lex); -} -/* default parser listener */ -typedef struct { - char *name; - TCOD_value_type_t type; - TCOD_value_t value; -} prop_t; -static char cur_prop_name[512]=""; -static bool default_new_struct(TCOD_parser_struct_t str,const char *name) { - if ( cur_prop_name[0] ) strcat(cur_prop_name,"."); - strcat(cur_prop_name,((TCOD_struct_int_t *)str)->name); - return true; -} - -static bool default_new_flag(const char *name) { - char tmp[512]; - prop_t *prop=(prop_t *)calloc(sizeof(prop_t),1); - sprintf(tmp,"%s.%s",cur_prop_name,name); - prop->name=TCOD_strdup(tmp); - prop->type=TCOD_TYPE_BOOL; - prop->value.b=true; - TCOD_list_push(default_props,prop); - return true; -} - -static bool default_new_property(const char *propname, TCOD_value_type_t type, TCOD_value_t value) { - char tmp[512]; - prop_t *prop=(prop_t *)calloc(sizeof(prop_t),1); - sprintf(tmp,"%s.%s",cur_prop_name,propname); - prop->name=TCOD_strdup(tmp); - prop->type=type; - prop->value=value; - TCOD_list_push(default_props,prop); - return true; -} - -static bool default_end_struct(TCOD_parser_struct_t str, const char *name) { - char *ptr=strrchr(cur_prop_name,'.'); - if ( ptr ) *ptr='\0'; - else cur_prop_name[0]='\0'; - return true; -} - -static void default_error(const char *msg) { - TCOD_fatal_nopar(msg); -} - -static const TCOD_value_t * TCOD_get_property(TCOD_parser_t parser, TCOD_value_type_t expectedType, const char *name) { - void **it; - char tmp[512],err[512]; - char *ptr,*curname; - TCOD_struct_int_t *str=NULL; - TCOD_value_type_t type; - TCOD_parser_int_t *p=(TCOD_parser_int_t *)parser; - if (! p->props ) return NULL; - for (it=TCOD_list_begin(p->props);it!=TCOD_list_end(p->props);it++) { - prop_t *prop=*((prop_t **)it); - if (strcmp(prop->name,name) == 0 ) { - /* property found. check type */ - if ( expectedType == TCOD_TYPE_STRING && prop->type >= TCOD_TYPE_VALUELIST00 - && prop->type <= TCOD_TYPE_VALUELIST15 ) return &prop->value; - if ( expectedType == TCOD_TYPE_CUSTOM00 && prop->type >= TCOD_TYPE_CUSTOM00 - && prop->type <= TCOD_TYPE_CUSTOM15 ) return &prop->value; - if (prop->type != expectedType ) { - sprintf(err,"Fatal error ! Try to read property '%s' width bad type\n",name); - default_error(err); - } - return &prop->value; - } - } - /* property not found. Check if it exists */ - strcpy(tmp,name); - ptr=strchr(tmp,'.'); - curname=tmp; - sprintf(err,"Fatal error ! Try to read unknown property '%s'\n",name); - while ( ptr ) { - bool found=false; - *ptr=0; - for (it=TCOD_list_begin(p->structs);!found && it!=TCOD_list_end(p->structs);it++) { - str=*((TCOD_struct_int_t **)it); - if ( strcmp(str->name,curname) == 0 ) found=true; - } - if ( ! found ) { - /* one of the structures is unknown */ - default_error(err); - } - curname=ptr+1; - ptr=strchr(curname,'.'); - } - if ( ! str ) { - /* no structure in name */ - default_error(err); - } - type = TCOD_struct_get_type((TCOD_parser_struct_t) str, curname); - if ( type == TCOD_TYPE_NONE ) { - /* property does not exist in structure */ - default_error(err); - } - /* optional property not defined in the file => ok */ - return NULL; -} - -bool TCOD_parser_has_property(TCOD_parser_t parser, const char *name) { - void **it; - TCOD_parser_int_t *p=(TCOD_parser_int_t *)parser; - if (! p->props ) return false; - for (it=TCOD_list_begin(p->props);it!=TCOD_list_end(p->props);it++) { - prop_t *prop=*((prop_t **)it); - if (strcmp(prop->name,name) == 0 ) { - return true; - } - } - return false; -} - -bool TCOD_parser_get_bool_property(TCOD_parser_t parser, const char *name) { - const TCOD_value_t *value=TCOD_get_property(parser,TCOD_TYPE_BOOL,name); - return value ? value->b : false; -} - -int TCOD_parser_get_int_property(TCOD_parser_t parser, const char *name) { - const TCOD_value_t *value=TCOD_get_property(parser,TCOD_TYPE_INT,name); - return value ? value->i : 0; -} - -int TCOD_parser_get_char_property(TCOD_parser_t parser, const char *name) { - const TCOD_value_t *value=TCOD_get_property(parser,TCOD_TYPE_CHAR,name); - return value ? value->c : 0; -} - -float TCOD_parser_get_float_property(TCOD_parser_t parser, const char *name) { - const TCOD_value_t *value=TCOD_get_property(parser,TCOD_TYPE_FLOAT,name); - return value ? value->f : 0.0f; -} - -const char * TCOD_parser_get_string_property(TCOD_parser_t parser, const char *name) { - const TCOD_value_t *value=TCOD_get_property(parser,TCOD_TYPE_STRING,name); - return value ? value->s : NULL; -} - -TCOD_color_t TCOD_parser_get_color_property(TCOD_parser_t parser, const char *name) { - const TCOD_value_t *value=TCOD_get_property(parser,TCOD_TYPE_COLOR,name); - return value ? value->col : TCOD_black; -} - -TCOD_dice_t TCOD_parser_get_dice_property(TCOD_parser_t parser, const char *name) { - static TCOD_dice_t default_dice={0,0,0.0f,0.0f}; - const TCOD_value_t *value=TCOD_get_property(parser,TCOD_TYPE_DICE,name); - return value ? value->dice : default_dice; -} - -void TCOD_parser_get_dice_property_py(TCOD_parser_t parser, const char *name, TCOD_dice_t *dice) { - *dice=TCOD_parser_get_dice_property(parser,name); -} - -void * TCOD_parser_get_custom_property(TCOD_parser_t parser, const char *name) { - const TCOD_value_t *value=TCOD_get_property(parser,TCOD_TYPE_CUSTOM00,name); - return value ? value->custom : NULL; -} - -TCOD_list_t TCOD_parser_get_list_property(TCOD_parser_t parser, const char *name, TCOD_value_type_t type) { - static TCOD_list_t empty_list=NULL; - const TCOD_value_t *value; - if (! empty_list ) empty_list=TCOD_list_new(); - value=TCOD_get_property(parser,TCOD_TYPE_LIST|type,name); - return value ? value->list : empty_list; -} +/* +* libtcod +* Copyright (c) 2008-2018 Jice & Mingos & rmtew +* All rights reserved. +* +* Redistribution and use in source and binary forms, with or without +* modification, are permitted provided that the following conditions are met: +* * Redistributions of source code must retain the above copyright +* notice, this list of conditions and the following disclaimer. +* * Redistributions in binary form must reproduce the above copyright +* notice, this list of conditions and the following disclaimer in the +* documentation and/or other materials provided with the distribution. +* * The name of Jice or Mingos may not be used to endorse or promote +* products derived from this software without specific prior written +* permission. +* +* THIS SOFTWARE IS PROVIDED BY JICE, MINGOS AND RMTEW ``AS IS'' AND ANY +* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED +* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE +* DISCLAIMED. IN NO EVENT SHALL JICE, MINGOS OR RMTEW BE LIABLE FOR ANY +* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES +* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; +* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND +* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS +* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +*/ +#include "parser.h" + +#include +#include +#include +#include + +#include "libtcod_int.h" + +#define BIG_NAME_LEN 128 + +#define DEF_NAME(d) (((TCOD_struct_int_t *)d)->name) +#define DEF_FLAGS(d) (((TCOD_struct_int_t *)d)->flags) +#define DEF_PROPS(d) (((TCOD_struct_int_t *)d)->props) +#define DEF_LISTS(d) (((TCOD_struct_int_t *)d)->lists) + +/* definition property */ +typedef struct { + char *name; + TCOD_value_type_t value; + bool mandat; +} TCOD_struct_prop_t; + +static TCOD_lex_t *lex=NULL; + +static const char *symbols[] = { + "{","}","=","/","+","-","[","]",",","#",NULL +}; + +static const char *keywords[] = { + "struct","bool","char","int","float","string","color","dice",NULL +}; + +static TCOD_parser_listener_t *listener=NULL; + +static bool default_new_struct(TCOD_parser_struct_t str,const char *name); +static bool default_new_flag(const char *name); +static bool default_new_property(const char *propname, TCOD_value_type_t type, TCOD_value_t value); +static bool default_end_struct(TCOD_parser_struct_t str, const char *name); +static void default_error(const char *msg); + +static TCOD_parser_listener_t default_listener = { + default_new_struct, + default_new_flag, + default_new_property, + default_end_struct, + default_error +}; + +static bool string_copy(char *dest, char *source, int len) { + if ( source == NULL ) return false; + strncpy(dest,source,len); + dest[len-1]='\0'; + if ( strlen(source) >= (unsigned)len ) return false; + return true; +} + +void TCOD_parser_error(const char *msg, ...) { + char buf[2048]; + char buf2[2048]; + va_list ap; + va_start(ap,msg); + vsprintf(buf,msg,ap); + va_end(ap); + sprintf(buf2,"error in %s line %d : %s",lex->filename,lex->file_line,buf); + listener->error(buf2); + lex->token_type = TCOD_LEX_ERROR; +} + +const char *TCOD_struct_get_name(TCOD_parser_struct_t def) { + return ((TCOD_struct_int_t *)def)->name; +} + +/* add a property to an entity definition */ +void TCOD_struct_add_property(TCOD_parser_struct_t def,const char *name,TCOD_value_type_t type, bool mandatory) { + TCOD_struct_prop_t *prop=(TCOD_struct_prop_t *)calloc(1,sizeof(TCOD_struct_prop_t)); + prop->name=TCOD_strdup(name); + prop->value=type; + prop->mandat=mandatory; + TCOD_list_push(DEF_PROPS(def),(void *)prop); +} + +/* add a list property to an entity definition */ +void TCOD_struct_add_list_property(TCOD_parser_struct_t def,const char *name,TCOD_value_type_t type, bool mandatory) { + TCOD_struct_add_property(def,name,type|TCOD_TYPE_LIST,mandatory); +} + +void TCOD_struct_add_value_list_sized(TCOD_parser_struct_t def,const char *name, const char **value_list, int size, bool mandatory) { + char ** newArray = NULL; + /* duplicate value list to avoid issues with C# garbage collector */ + TCOD_value_type_t type = (TCOD_value_type_t)((int)TCOD_TYPE_VALUELIST00 + TCOD_list_size(DEF_LISTS(def))); + int i = 0; + + if(size) newArray = calloc(size+1, sizeof(char*)); + + for(i = 0 ; i < size ; i++) + newArray[i] = TCOD_strdup(value_list[i]); + newArray[size] = NULL; + + TCOD_struct_add_property(def,name,type,mandatory); + TCOD_list_push(DEF_LISTS(def),(void *)newArray); +} + +/* add a value-list property to an entity definition */ +void TCOD_struct_add_value_list(TCOD_parser_struct_t def,const char *name, const char **value_list, bool mandatory) { + int size = 0; + if(value_list) + { + while(value_list[size] != NULL) + { + size++; + }; + } + TCOD_struct_add_value_list_sized(def, name, value_list, size, mandatory); +} + + +/* add a flag (simplified bool value) to an entity definition */ +/* a flag cannot be mandatory. if present => true, if omitted => false */ +void TCOD_struct_add_flag(TCOD_parser_struct_t def,const char *propname) { + TCOD_list_push(DEF_FLAGS(def),(void *)TCOD_strdup(propname)); +} + +/* add a sub-entity to an entity definition */ +void TCOD_struct_add_structure(TCOD_parser_struct_t def, TCOD_parser_struct_t sub_definition) { + TCOD_list_push(((TCOD_struct_int_t *)def)->structs,(const void *)sub_definition); +} + +/* check if given property is mandatory for this entity definition */ +bool TCOD_struct_is_mandatory(TCOD_parser_struct_t def, const char *propname) { + TCOD_struct_prop_t **iprop; + for (iprop=(TCOD_struct_prop_t **)TCOD_list_begin(DEF_PROPS(def)); iprop!=(TCOD_struct_prop_t **)TCOD_list_end(DEF_PROPS(def));iprop++) { + if ( strcmp((*iprop)->name,propname) == 0 ) return (*iprop)->mandat; + } + return false; +} + +/* returns the type of given property */ +/* NONE if the property does not exist */ +TCOD_value_type_t TCOD_struct_get_type(TCOD_parser_struct_t def, const char *propname) { + TCOD_struct_prop_t **iprop; + char **iflag; + for (iprop=(TCOD_struct_prop_t **)TCOD_list_begin(DEF_PROPS(def)); iprop!=(TCOD_struct_prop_t **)TCOD_list_end(DEF_PROPS(def));iprop++) { + if ( strcmp((*iprop)->name,propname) == 0 ) return (*iprop)->value; + } + for (iflag=(char **)TCOD_list_begin(DEF_FLAGS(def)); iflag!=(char **)TCOD_list_end(DEF_FLAGS(def));iflag++) { + if ( strcmp((*iflag),propname) == 0 ) return TCOD_TYPE_BOOL; + } + return TCOD_TYPE_NONE; +} + +TCOD_value_t TCOD_parse_bool_value(void) { + TCOD_value_t ret; + if ( strcmp(lex->tok,"true") == 0 ) ret.b=true; + else if ( strcmp(lex->tok,"false") == 0 ) ret.b=false; + else TCOD_parser_error("parseBoolValue : unknown value %s for bool. 'true' or 'false' expected",lex->tok); + return ret; +} + +TCOD_value_t TCOD_parse_char_value(void) { + TCOD_value_t ret; + if ( lex->token_type != TCOD_LEX_CHAR && lex->token_type != TCOD_LEX_INTEGER ) + TCOD_parser_error("parseCharValue : char constant expected instead of '%s'",lex->tok); + ret.c=lex->token_int_val; + return ret; +} + +TCOD_value_t TCOD_parse_integer_value(void) { + TCOD_value_t ret; + if ( lex->token_type != TCOD_LEX_INTEGER ) + TCOD_parser_error("parseIntegerValue : integer constant expected instead of '%s'",lex->tok); + ret.i=lex->token_int_val; + return ret; +} + +TCOD_value_t TCOD_parse_float_value(void) { + TCOD_value_t ret; + if ( lex->token_type != TCOD_LEX_FLOAT && lex->token_type != TCOD_LEX_INTEGER ) + TCOD_parser_error("parseFloatValue : float constant expected instead of '%s'",lex->tok); + if ( lex->token_type == TCOD_LEX_FLOAT ) ret.f=lex->token_float_val; + else ret.f=(float)lex->token_int_val; + return ret; +} + +TCOD_value_t TCOD_parse_string_value(void) { + TCOD_value_t ret; + TCOD_list_t l; + bool end=false; + char **s; + size_t slen=0; + l=TCOD_list_new(); + if ( lex->token_type != TCOD_LEX_STRING ) TCOD_parser_error("parseStringValue : string constant expected instead of '%s'",lex->tok); + while ( !end ) { + TCOD_lex_t save; + TCOD_list_push(l,(void *)TCOD_strdup(lex->tok)); + TCOD_lex_savepoint(lex,&save); + if (TCOD_lex_parse(lex) != TCOD_LEX_STRING) { + end=true; + TCOD_lex_restore(lex,&save); + } + } + for (s=(char **)TCOD_list_begin(l); s != (char **)TCOD_list_end(l); s++ ) { + slen += strlen(*s); + } + ret.s=(char *)calloc(sizeof(char),slen+1); + for (s=(char **)TCOD_list_begin(l); s != (char **)TCOD_list_end(l); s++ ) { + strcat(ret.s,*s); + free(*s); + } + TCOD_list_delete(l); + return ret; +} + +TCOD_value_t TCOD_parse_color_value(void) { + TCOD_value_t ret; + if ( lex->token_type == TCOD_LEX_SYMBOL && lex->tok[0]=='#') { + char tmp[128]=""; + int tok=TCOD_lex_parse(lex); + /* format : col = #FFFFFF */ + strcat(tmp,"#"); + if ( tok == TCOD_LEX_IDEN || tok == TCOD_LEX_INTEGER ) { + strcat(tmp,lex->tok); + strcpy(lex->tok,tmp); + if ( strlen(lex->tok) < 7 && tok == TCOD_LEX_INTEGER ) { + /* special case of #12AABB => symbol # + + integer 12 + iden AABB */ + tok=TCOD_lex_parse(lex); + if ( tok == TCOD_LEX_IDEN ) { + strcat(tmp,lex->tok); + strcpy(lex->tok,tmp); + } + } + lex->token_type = TCOD_LEX_STRING; + } + } + if ( lex->token_type != TCOD_LEX_STRING ) TCOD_parser_error("parseColorValue : string constant expected instead of '%s'",lex->tok); + if (lex->tok[0] == '#') { + int r,g,b; + if ( strlen(lex->tok) != 7 ) TCOD_parser_error("parseColorValue : bad color format. '#rrggbb' expected instead of '%s'",lex->tok); + /* web format : #rrggbb */ + r=(TCOD_lex_hextoint(lex->tok[1])<<4) + TCOD_lex_hextoint(lex->tok[2]); + g=(TCOD_lex_hextoint(lex->tok[3])<<4) + TCOD_lex_hextoint(lex->tok[4]); + b=(TCOD_lex_hextoint(lex->tok[5])<<4) + TCOD_lex_hextoint(lex->tok[6]); + ret.col.r=r; + ret.col.g=g; + ret.col.b=b; + } else { + /* standard format : rrr,ggg,bbb */ + char *begin=lex->tok; + char *end=strchr(begin,','); + bool ok=true; + if (! end) ok=false; + else { + *end=0; + ret.col.r=atoi(begin); + begin=end+1; + end=strchr(begin,','); + if ( !end ) ok=false; + else { + ret.col.g=atoi(begin); + begin=end+1; + ret.col.b=atoi(begin); + } + + } + if (!ok) TCOD_parser_error("parseColorValue : bad color format 'rrr,ggg,bbb' expected instead of '%s'",lex->tok); + } + return ret; +} + +TCOD_value_t TCOD_parse_dice_value(void) { + /* dice format : [(x|*)](D|d)[(+|-)] */ + TCOD_value_t ret; + bool minus=false; + char *begin; + char *ptr; + ret.dice.multiplier=1.0f; + ret.dice.addsub=0.0f; + begin=lex->tok; + ptr=strchr(begin,'x'); + if (! ptr ) ptr=strchr(begin,'*'); + if ( ptr ) { + /* parse multiplier */ + *ptr=0; + ret.dice.multiplier=(float)atof(lex->tok); + begin=ptr+1; + } + ptr=strchr(begin,'D'); + if (!ptr ) ptr=strchr(begin,'d'); + if (! ptr ) TCOD_parser_error("parseDiceValue : bad dice format. [(x|*)](D|d)[(+|-)] expected instead of '%s'",lex->tok); + *ptr=0; + /* parse nb_rolls */ + ret.dice.nb_rolls=atoi(begin); + begin=ptr+1; + ptr=strchr(begin,'+'); + if (! ptr) { + ptr = strchr(begin,'-'); + if ( ptr ) minus=true; + } + if (ptr) *ptr=0; + /* parse nb_faces */ + ret.dice.nb_faces=atoi(begin); + if ( ptr ) { + /* parse addsub */ + begin=ptr+1; + ret.dice.addsub=(float)atof(begin); + if ( minus ) ret.dice.addsub=-ret.dice.addsub; + } + return ret; +} + +TCOD_value_t TCOD_parse_value_list_value(TCOD_struct_int_t *def,int listnum) { + TCOD_value_t ret; + int i=0; + char *value; + char **value_list=TCOD_list_get(def->lists,listnum); + if ( lex->token_type != TCOD_LEX_STRING) TCOD_parser_error("parseValueListValue : string constant expected instead of '%s'",lex->tok); + value= value_list[i]; + while ( value ) { + if ( strcmp(lex->tok,value) == 0 ) break; + i++; + value=value_list[i]; + } + if (! value ) TCOD_parser_error("parseValueListValue : incorrect value '%s'",lex->tok); + ret.s = value; + return ret; +} + + +TCOD_value_t TCOD_parse_property_value(TCOD_parser_int_t *parser, TCOD_parser_struct_t def, char *propname, bool list) { + TCOD_value_type_t type=TCOD_struct_get_type(def,propname); + TCOD_value_t ret={0}; + if (! list ) type &= ~ TCOD_TYPE_LIST; + if ( type & TCOD_TYPE_LIST ) { + type &= ~ TCOD_TYPE_LIST; + if ( strcmp(lex->tok,"[") != 0 ) { + TCOD_parser_error("'[' expected for list value instead of '%s'",lex->tok); + } + ret.list=TCOD_list_new(); + do { + TCOD_value_t val; + int tok=TCOD_lex_parse(lex); + if ( tok == TCOD_LEX_EOF || tok == TCOD_LEX_ERROR ) { + TCOD_parser_error("Missing ']' in list value"); + } + val=TCOD_parse_property_value(parser,def,propname,false); + if ( type == TCOD_TYPE_STRING || (type >= TCOD_TYPE_VALUELIST00 && type <= TCOD_TYPE_VALUELIST15 ) ) { + TCOD_list_push(ret.list,TCOD_strdup(val.s)); + } else { + TCOD_list_push(ret.list,val.custom); + } + TCOD_lex_parse(lex); + if ( strcmp(lex->tok,",") != 0 && strcmp(lex->tok,"]") != 0 ) { + TCOD_parser_error("',' or ']' expected in list value instead of '%s'",lex->tok); + } + } while ( strcmp(lex->tok,"]") != 0 ); + } else { + switch (type) { + case TCOD_TYPE_BOOL : return TCOD_parse_bool_value(); break; + case TCOD_TYPE_CHAR : return TCOD_parse_char_value(); break; + case TCOD_TYPE_INT : return TCOD_parse_integer_value(); break; + case TCOD_TYPE_FLOAT : return TCOD_parse_float_value(); break; + case TCOD_TYPE_STRING : return TCOD_parse_string_value(); break; + case TCOD_TYPE_COLOR : return TCOD_parse_color_value(); break; + case TCOD_TYPE_DICE : return TCOD_parse_dice_value(); break; + case TCOD_TYPE_VALUELIST00 : + case TCOD_TYPE_VALUELIST01 : + case TCOD_TYPE_VALUELIST02 : + case TCOD_TYPE_VALUELIST03 : + case TCOD_TYPE_VALUELIST04 : + case TCOD_TYPE_VALUELIST05 : + case TCOD_TYPE_VALUELIST06 : + case TCOD_TYPE_VALUELIST07 : + case TCOD_TYPE_VALUELIST08 : + case TCOD_TYPE_VALUELIST09 : + case TCOD_TYPE_VALUELIST10 : + case TCOD_TYPE_VALUELIST11 : + case TCOD_TYPE_VALUELIST12 : + case TCOD_TYPE_VALUELIST13 : + case TCOD_TYPE_VALUELIST14 : + case TCOD_TYPE_VALUELIST15 : { + int listnum = type - TCOD_TYPE_VALUELIST00; + return TCOD_parse_value_list_value((TCOD_struct_int_t *)def,listnum); break; + } + case TCOD_TYPE_CUSTOM00 : + case TCOD_TYPE_CUSTOM01 : + case TCOD_TYPE_CUSTOM02 : + case TCOD_TYPE_CUSTOM03 : + case TCOD_TYPE_CUSTOM04 : + case TCOD_TYPE_CUSTOM05 : + case TCOD_TYPE_CUSTOM06 : + case TCOD_TYPE_CUSTOM07 : + case TCOD_TYPE_CUSTOM08 : + case TCOD_TYPE_CUSTOM09 : + case TCOD_TYPE_CUSTOM10 : + case TCOD_TYPE_CUSTOM11 : + case TCOD_TYPE_CUSTOM12 : + case TCOD_TYPE_CUSTOM13 : + case TCOD_TYPE_CUSTOM14 : + case TCOD_TYPE_CUSTOM15 : + if ( parser->customs[type - TCOD_TYPE_CUSTOM00] ) { + return parser->customs[type-TCOD_TYPE_CUSTOM00](lex,listener,def,propname); + } else { + TCOD_parser_error("parse_property_value : no custom parser for property type %d for entity %s prop %s", + type,DEF_NAME(def),propname); + } + break; + default : TCOD_parser_error("parse_property_value : unknown property type %d for entity %s prop %s", + type,DEF_NAME(def),propname); break; + } + } + return ret; +} + +static bool TCOD_parser_parse_entity(TCOD_parser_int_t *parser, TCOD_struct_int_t *def) { + char *name=NULL; + if ( TCOD_lex_parse(lex) == TCOD_LEX_STRING ) { + /* entity type name */ + name=TCOD_strdup(lex->tok); + TCOD_lex_parse(lex); + } + if ( strcmp(lex->tok,"{") != 0 ) { + TCOD_parser_error("Parser::parseEntity : '{' expected"); + return false; + } + TCOD_lex_parse(lex); + while ( strcmp(lex->tok,"}") != 0 ) { + bool found=false; + char **iflag; + bool dynStruct=false; + TCOD_value_type_t dynType = TCOD_TYPE_NONE; + if ( lex->token_type == TCOD_LEX_KEYWORD ) { + /* dynamic property declaration */ + if ( strcmp(lex->tok,"bool") == 0 ) dynType=TCOD_TYPE_BOOL; + else if ( strcmp(lex->tok,"char") == 0 ) dynType=TCOD_TYPE_CHAR; + else if ( strcmp(lex->tok,"int") == 0 ) dynType=TCOD_TYPE_INT; + else if ( strcmp(lex->tok,"float") == 0 ) dynType=TCOD_TYPE_FLOAT; + else if ( strcmp(lex->tok,"string") == 0 ) dynType=TCOD_TYPE_STRING; + else if ( strcmp(lex->tok,"color") == 0 ) dynType=TCOD_TYPE_COLOR; + else if ( strcmp(lex->tok,"dice") == 0 ) dynType=TCOD_TYPE_DICE; + else if ( strcmp(lex->tok,"struct") == 0 ) dynStruct=true; + else { + TCOD_parser_error("Parser::parseEntity : dynamic declaration of '%s' not supported",lex->tok); + return false; + } + /* TODO : dynamically declared sub-structures */ + TCOD_lex_parse(lex); + if ( strcmp(lex->tok,"[") == 0 ) { + if ( dynType == TCOD_TYPE_NONE ) { + TCOD_parser_error("Parser::parseEntity : unexpected symbol '['"); + return false; + } + TCOD_lex_parse(lex); + if ( strcmp(lex->tok,"]") != 0 ) { + TCOD_parser_error("Parser::parseEntity : syntax error. ']' expected instead of '%s'",lex->tok); + return false; + } + dynType |= TCOD_TYPE_LIST; + TCOD_lex_parse(lex); + } + } + /* parse entity type content */ + if ( lex->token_type != TCOD_LEX_IDEN ) { + TCOD_parser_error("Parser::parseEntity : identifier expected"); + return false; + } + /* is it a flag ? */ + if (! dynStruct && dynType == TCOD_TYPE_NONE) { + for (iflag=(char **)TCOD_list_begin(def->flags);iflag!=(char **)TCOD_list_end(def->flags); iflag++) { + if ( strcmp(*iflag,lex->tok) == 0 ) { + found=true; + if (!listener->new_flag(lex->tok)) return false; + break; + } + } + } + if (!found && ! dynStruct) { + do { + /* is it a property ? */ + TCOD_struct_prop_t **iprop; + for (iprop=(TCOD_struct_prop_t **)TCOD_list_begin(def->props); iprop!=(TCOD_struct_prop_t **)TCOD_list_end(def->props);iprop++) { + if ( strcmp((*iprop)->name,lex->tok) == 0 ) { + char propname[BIG_NAME_LEN]; + string_copy(propname,lex->tok,BIG_NAME_LEN); + TCOD_lex_parse(lex); + if ( strcmp(lex->tok,"=") != 0 ) { + TCOD_parser_error("Parser::parseEntity : '=' expected"); + return false; + } + TCOD_lex_parse(lex); + if (!listener->new_property(propname,TCOD_struct_get_type(def,propname), + TCOD_parse_property_value(parser, def, propname, true))) return false; + if ( lex->token_type == TCOD_LEX_ERROR ) return false; + found=true; + break; + } + } + if ( !found && dynType != TCOD_TYPE_NONE ) { + /* dynamically add a property to the current structure */ + TCOD_struct_add_property(def,lex->tok,dynType,false); + } + } while ( ! found && dynType != TCOD_TYPE_NONE); + } + if (! found ) { + /* is it a sub-entity type */ + char id[BIG_NAME_LEN*2 + 2]; + bool blockFound=false; + do { + TCOD_lex_t save; + char type[BIG_NAME_LEN]; + char *subname=NULL; + bool named=false; + TCOD_lex_savepoint(lex,&save); + string_copy(type,lex->tok,BIG_NAME_LEN); + strcpy(id,type); + if ( TCOD_lex_parse(lex) == TCOD_LEX_STRING ) { + /* # */ + TCOD_struct_int_t **sub; + strcat(id,"#"); + strcat(id,lex->tok); + named=true; + subname=TCOD_strdup(lex->tok); + TCOD_lex_restore(lex,&save); + for ( sub = (TCOD_struct_int_t **)TCOD_list_begin(def->structs); + sub != (TCOD_struct_int_t **)TCOD_list_end(def->structs); sub ++ ) { + if ( strcmp((*sub)->name,id) == 0 ) { + if (!listener->new_struct(*sub, lex->tok)) return false; + if (!TCOD_parser_parse_entity(parser,*sub)) return false; + blockFound=true; + found=true; + break; + } + } + } else { + TCOD_lex_restore(lex,&save); + } + if (! blockFound ) { + /* alone */ + TCOD_struct_int_t **sub; + for ( sub = (TCOD_struct_int_t **)TCOD_list_begin(def->structs); + sub != (TCOD_struct_int_t **)TCOD_list_end(def->structs); sub ++ ) { + if ( strcmp((*sub)->name,type) == 0 ) { + if (!listener->new_struct(*sub, subname)) return false; + if (!TCOD_parser_parse_entity(parser,*sub)) return false; + blockFound=true; + found=true; + break; + } + } + } + if (! blockFound && dynStruct ) { + /* unknown structure. auto-declaration */ + TCOD_struct_int_t **idef; + TCOD_struct_int_t *s=NULL; + for (idef=(TCOD_struct_int_t **)TCOD_list_begin(parser->structs); idef!=(TCOD_struct_int_t **)TCOD_list_end(parser->structs); idef ++) { + if ( strcmp((*idef)->name,id) == 0 ) { + s=*idef; + break; + } + } + if ( s == NULL && named ) { + /* look for general definition for entity # */ + for (idef=(TCOD_struct_int_t **)TCOD_list_begin(parser->structs); idef!=(TCOD_struct_int_t **)TCOD_list_end(parser->structs); idef ++) { + if ( strcmp((*idef)->name,type) == 0 ) { + s=*idef; + break; + } + } + } + if ( s == NULL ) { + /* dyn struct not found. create it */ + s = TCOD_parser_new_struct(parser,type); + } + TCOD_struct_add_structure(def,s); + } + } while (!blockFound && dynStruct ); + if (! blockFound ) { + TCOD_parser_error("Parser::parseEntity : entity type %s does not contain %s", + def->name,id); + return false; + } + } + TCOD_lex_parse(lex); + } + if (!listener->end_struct(def, name)) return false; + return true; +} + +/****************************************/ +/* generic parser */ +/****************************************/ + +TCOD_parser_t TCOD_parser_new(void) { + TCOD_parser_int_t *ent = (TCOD_parser_int_t*)calloc(1,sizeof(TCOD_parser_int_t)); + ent->structs=TCOD_list_new(); + return (TCOD_parser_t) ent; +} + +TCOD_value_type_t TCOD_parser_new_custom_type(TCOD_parser_t parser, TCOD_parser_custom_t custom_type_parser) { + TCOD_parser_int_t *p=(TCOD_parser_int_t *)parser; + TCOD_value_type_t type= TCOD_TYPE_CUSTOM00; + while ( p->customs[ type - TCOD_TYPE_CUSTOM00 ] && type < TCOD_TYPE_CUSTOM15 ) type=(TCOD_value_type_t)(type+1); + if ( p->customs[ type - TCOD_TYPE_CUSTOM00 ] ) { + /* no more custom types slots available */ + return TCOD_TYPE_NONE; + } + p->customs[type - TCOD_TYPE_CUSTOM00] = custom_type_parser; + return type; +} + +TCOD_parser_struct_t TCOD_parser_new_struct(TCOD_parser_t parser, char *name) { + TCOD_struct_int_t *ent = (TCOD_struct_int_t*)calloc(1,sizeof(TCOD_struct_int_t)); + ent->name=TCOD_strdup(name); + ent->flags=TCOD_list_new(); + ent->props=TCOD_list_new(); + ent->lists=TCOD_list_new(); + ent->structs=TCOD_list_new(); + TCOD_list_push(((TCOD_parser_int_t *)parser)->structs,ent); + return (TCOD_parser_struct_t )ent; +} + +void TCOD_parser_delete(TCOD_parser_t parser) { + TCOD_parser_int_t *p=(TCOD_parser_int_t *)parser; + TCOD_struct_int_t **idef; + TCOD_struct_prop_t **propCleanup; + + char *** listCleanup; + int listSize = 0; + + for (idef=(TCOD_struct_int_t **)TCOD_list_begin(p->structs); idef!= (TCOD_struct_int_t **)TCOD_list_end(p->structs); idef++) { + free((*idef)->name); + + for ( propCleanup = (TCOD_struct_prop_t**) TCOD_list_begin((*idef)->props); propCleanup != (TCOD_struct_prop_t**)TCOD_list_end((*idef)->props); propCleanup++ ) { + free((*propCleanup)->name); + } + TCOD_list_clear_and_delete((*idef)->props); + + + for ( listCleanup = (char ***) TCOD_list_begin((*idef)->lists); listCleanup != (char ***)TCOD_list_end((*idef)->lists); listCleanup++ ) { + while((*listCleanup)[listSize] != NULL) { + free((*listCleanup)[listSize]); + listSize++; + } + } + TCOD_list_clear_and_delete((*idef)->lists); + } + TCOD_list_clear_and_delete(p->structs); +} + +/* parse a file */ +static struct TCOD_List *default_props; +/* triggers callbacks in the listener for each event during parsing */ +void TCOD_parser_run(TCOD_parser_t parser, const char *filename, TCOD_parser_listener_t *_listener) { + TCOD_parser_int_t *p=(TCOD_parser_int_t *)parser; + if (! _listener && ! p->props ) p->props=TCOD_list_new(); + listener=_listener ? _listener : &default_listener; + default_props = p->props; + lex=TCOD_lex_new(symbols,keywords,"//","/*","*/",NULL,"\"",TCOD_LEX_FLAG_NESTING_COMMENT); + if (!TCOD_lex_set_data_file(lex,(char *)filename)) { + char buf[1024]; + sprintf(buf,"Fatal error : %s\n",TCOD_lex_get_last_error()); + listener->error(buf); + return; + } + while (1) { + bool named=false; + char id[ BIG_NAME_LEN*2 + 2 ]; + char type[ BIG_NAME_LEN ]; + TCOD_lex_t save; + TCOD_struct_int_t *def=NULL; + TCOD_struct_int_t **idef; + bool dynStruct=false; + TCOD_lex_parse(lex); + if ( lex->token_type == TCOD_LEX_EOF || lex->token_type == TCOD_LEX_ERROR ) break; + if ( lex->token_type == TCOD_LEX_KEYWORD ) { + if ( strcmp(lex->tok,"struct") == 0) { + /* level 0 dynamic structure declaration */ + dynStruct=true; + TCOD_lex_parse(lex); + } else { + TCOD_parser_error("Parser::parse : unexpected keyword '%s'",lex->tok); + return; + } + } + /* get entity type */ + if ( lex->token_type != TCOD_LEX_IDEN ) { + TCOD_parser_error("Parser::parse : identifier token expected"); + return; + } + string_copy(type,lex->tok,BIG_NAME_LEN); + strcpy(id,type); + TCOD_lex_savepoint(lex,&save); + if ( TCOD_lex_parse(lex) == TCOD_LEX_STRING ) { + /* named entity. id = # */ + strcat(id,"#"); + if ( strlen(lex->tok) >= BIG_NAME_LEN ) { + TCOD_parser_error("Parser::parse : name %s too long. Max %d characters", + lex->tok,BIG_NAME_LEN-1); + return; + } + strcat(id,lex->tok); + named=true; + } + TCOD_lex_restore(lex,&save); + do { + /* look for a definition for id */ + for (idef=(TCOD_struct_int_t **)TCOD_list_begin(p->structs); idef!=(TCOD_struct_int_t **)TCOD_list_end(p->structs); idef ++) { + if ( strcmp((*idef)->name,id) == 0 ) { + def=*idef; + break; + } + } + if ( def == NULL && named ) { + /* look for general definition for entity # */ + for (idef=(TCOD_struct_int_t **)TCOD_list_begin(p->structs); idef!=(TCOD_struct_int_t **)TCOD_list_end(p->structs); idef ++) { + if ( strcmp((*idef)->name,type) == 0 ) { + def=(*idef); + break; + } + } + } + if ( def == NULL && dynStruct ) { + /* dyn struct not found. create it */ + TCOD_parser_new_struct(parser,type); + } + } while ( def == NULL && dynStruct ); + if (def == NULL ) { + TCOD_parser_error("Parser::parse : unknown entity type %s",type); + return; + } else { + if (!listener->new_struct((TCOD_parser_struct_t)def,named ? strchr(id,'#')+1 : NULL )) return; + if (!TCOD_parser_parse_entity(p,def)) return; + } + } + if (lex->token_type == TCOD_LEX_ERROR) { + TCOD_parser_error("Parser::parse : error while parsing"); + return; + } + TCOD_lex_delete(lex); +} +/* default parser listener */ +typedef struct { + char *name; + TCOD_value_type_t type; + TCOD_value_t value; +} prop_t; +static char cur_prop_name[512]=""; +static bool default_new_struct(TCOD_parser_struct_t str,const char *name) { + if ( cur_prop_name[0] ) strcat(cur_prop_name,"."); + strcat(cur_prop_name,((TCOD_struct_int_t *)str)->name); + return true; +} + +static bool default_new_flag(const char *name) { + char tmp[512]; + prop_t *prop=(prop_t *)calloc(sizeof(prop_t),1); + sprintf(tmp,"%s.%s",cur_prop_name,name); + prop->name=TCOD_strdup(tmp); + prop->type=TCOD_TYPE_BOOL; + prop->value.b=true; + TCOD_list_push(default_props,prop); + return true; +} + +static bool default_new_property(const char *propname, TCOD_value_type_t type, TCOD_value_t value) { + char tmp[512]; + prop_t *prop=(prop_t *)calloc(sizeof(prop_t),1); + sprintf(tmp,"%s.%s",cur_prop_name,propname); + prop->name=TCOD_strdup(tmp); + prop->type=type; + prop->value=value; + TCOD_list_push(default_props,prop); + return true; +} + +static bool default_end_struct(TCOD_parser_struct_t str, const char *name) { + char *ptr=strrchr(cur_prop_name,'.'); + if ( ptr ) *ptr='\0'; + else cur_prop_name[0]='\0'; + return true; +} + +static void default_error(const char *msg) { + TCOD_fatal_nopar(msg); +} + +static const TCOD_value_t * TCOD_get_property(TCOD_parser_t parser, TCOD_value_type_t expectedType, const char *name) { + void **it; + char tmp[512],err[512]; + char *ptr,*curname; + TCOD_struct_int_t *str=NULL; + TCOD_value_type_t type; + TCOD_parser_int_t *p=(TCOD_parser_int_t *)parser; + if (! p->props ) return NULL; + for (it=TCOD_list_begin(p->props);it!=TCOD_list_end(p->props);it++) { + prop_t *prop=*((prop_t **)it); + if (strcmp(prop->name,name) == 0 ) { + /* property found. check type */ + if ( expectedType == TCOD_TYPE_STRING && prop->type >= TCOD_TYPE_VALUELIST00 + && prop->type <= TCOD_TYPE_VALUELIST15 ) return &prop->value; + if ( expectedType == TCOD_TYPE_CUSTOM00 && prop->type >= TCOD_TYPE_CUSTOM00 + && prop->type <= TCOD_TYPE_CUSTOM15 ) return &prop->value; + if (prop->type != expectedType ) { + sprintf(err,"Fatal error ! Try to read property '%s' width bad type\n",name); + default_error(err); + } + return &prop->value; + } + } + /* property not found. Check if it exists */ + strcpy(tmp,name); + ptr=strchr(tmp,'.'); + curname=tmp; + sprintf(err,"Fatal error ! Try to read unknown property '%s'\n",name); + while ( ptr ) { + bool found=false; + *ptr=0; + for (it=TCOD_list_begin(p->structs);!found && it!=TCOD_list_end(p->structs);it++) { + str=*((TCOD_struct_int_t **)it); + if ( strcmp(str->name,curname) == 0 ) found=true; + } + if ( ! found ) { + /* one of the structures is unknown */ + default_error(err); + } + curname=ptr+1; + ptr=strchr(curname,'.'); + } + if ( ! str ) { + /* no structure in name */ + default_error(err); + } + type = TCOD_struct_get_type((TCOD_parser_struct_t) str, curname); + if ( type == TCOD_TYPE_NONE ) { + /* property does not exist in structure */ + default_error(err); + } + /* optional property not defined in the file => ok */ + return NULL; +} + +bool TCOD_parser_has_property(TCOD_parser_t parser, const char *name) { + void **it; + TCOD_parser_int_t *p=(TCOD_parser_int_t *)parser; + if (! p->props ) return false; + for (it=TCOD_list_begin(p->props);it!=TCOD_list_end(p->props);it++) { + prop_t *prop=*((prop_t **)it); + if (strcmp(prop->name,name) == 0 ) { + return true; + } + } + return false; +} + +bool TCOD_parser_get_bool_property(TCOD_parser_t parser, const char *name) { + const TCOD_value_t *value=TCOD_get_property(parser,TCOD_TYPE_BOOL,name); + return value ? value->b : false; +} + +int TCOD_parser_get_int_property(TCOD_parser_t parser, const char *name) { + const TCOD_value_t *value=TCOD_get_property(parser,TCOD_TYPE_INT,name); + return value ? value->i : 0; +} + +int TCOD_parser_get_char_property(TCOD_parser_t parser, const char *name) { + const TCOD_value_t *value=TCOD_get_property(parser,TCOD_TYPE_CHAR,name); + return value ? value->c : 0; +} + +float TCOD_parser_get_float_property(TCOD_parser_t parser, const char *name) { + const TCOD_value_t *value=TCOD_get_property(parser,TCOD_TYPE_FLOAT,name); + return value ? value->f : 0.0f; +} + +const char * TCOD_parser_get_string_property(TCOD_parser_t parser, const char *name) { + const TCOD_value_t *value=TCOD_get_property(parser,TCOD_TYPE_STRING,name); + return value ? value->s : NULL; +} + +TCOD_color_t TCOD_parser_get_color_property(TCOD_parser_t parser, const char *name) { + const TCOD_value_t *value=TCOD_get_property(parser,TCOD_TYPE_COLOR,name); + return value ? value->col : TCOD_black; +} + +TCOD_dice_t TCOD_parser_get_dice_property(TCOD_parser_t parser, const char *name) { + static TCOD_dice_t default_dice={0,0,0.0f,0.0f}; + const TCOD_value_t *value=TCOD_get_property(parser,TCOD_TYPE_DICE,name); + return value ? value->dice : default_dice; +} + +void TCOD_parser_get_dice_property_py(TCOD_parser_t parser, const char *name, TCOD_dice_t *dice) { + *dice=TCOD_parser_get_dice_property(parser,name); +} + +void * TCOD_parser_get_custom_property(TCOD_parser_t parser, const char *name) { + const TCOD_value_t *value=TCOD_get_property(parser,TCOD_TYPE_CUSTOM00,name); + return value ? value->custom : NULL; +} + +TCOD_list_t TCOD_parser_get_list_property(TCOD_parser_t parser, const char *name, TCOD_value_type_t type) { + static TCOD_list_t empty_list=NULL; + const TCOD_value_t *value; + if (! empty_list ) empty_list=TCOD_list_new(); + value=TCOD_get_property(parser,TCOD_TYPE_LIST|type,name); + return value ? value->list : empty_list; +} diff --git a/tcod_sys/libtcod/src/path.cpp b/tcod_sys/libtcod/src/libtcod/path.cpp similarity index 90% rename from tcod_sys/libtcod/src/path.cpp rename to tcod_sys/libtcod/src/libtcod/path.cpp index d1edd69c7..0fa1b2a88 100644 --- a/tcod_sys/libtcod/src/path.cpp +++ b/tcod_sys/libtcod/src/libtcod/path.cpp @@ -1,139 +1,139 @@ -/* -* libtcod -* Copyright (c) 2008-2018 Jice & Mingos & rmtew -* All rights reserved. -* -* Redistribution and use in source and binary forms, with or without -* modification, are permitted provided that the following conditions are met: -* * Redistributions of source code must retain the above copyright -* notice, this list of conditions and the following disclaimer. -* * Redistributions in binary form must reproduce the above copyright -* notice, this list of conditions and the following disclaimer in the -* documentation and/or other materials provided with the distribution. -* * The name of Jice or Mingos may not be used to endorse or promote -* products derived from this software without specific prior written -* permission. -* -* THIS SOFTWARE IS PROVIDED BY JICE, MINGOS AND RMTEW ``AS IS'' AND ANY -* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED -* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE -* DISCLAIMED. IN NO EVENT SHALL JICE, MINGOS OR RMTEW BE LIABLE FOR ANY -* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES -* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; -* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND -* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS -* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. -*/ -#include - - -TCODPath::TCODPath(const TCODMap *map, float diagonalCost) { - data=(void *)TCOD_path_new_using_map(map->data,diagonalCost); -} - -TCODPath::~TCODPath() { - TCOD_path_delete(data); -} - -float TCOD_path_func(int xFrom, int yFrom, int xTo,int yTo, void *data) { - TCODPath::WrapperData *cppData=(TCODPath::WrapperData *)data; - return cppData->listener->getWalkCost(xFrom,yFrom,xTo,yTo,cppData->userData); -} - -TCODPath::TCODPath(int width, int height, const ITCODPathCallback *listener, void *userData, float diagonalCost) { - cppData.listener=listener; - cppData.userData=userData; - data=(void *)TCOD_path_new_using_function(width, height, TCOD_path_func, (void *)&cppData,diagonalCost); -} - - -bool TCODPath::compute(int ox, int oy, int dx, int dy) { - return TCOD_path_compute(data,ox,oy,dx,dy) != 0; -} - -bool TCODPath::walk(int *x, int *y, bool recalculateWhenNeeded) { - return TCOD_path_walk(data,x,y,recalculateWhenNeeded) != 0; -} - -bool TCODPath::isEmpty() const { - return TCOD_path_is_empty(data) != 0; -} - -void TCODPath::reverse() { - TCOD_path_reverse(data); -} - -int TCODPath::size() const { - return TCOD_path_size(data); -} - -void TCODPath::get(int index, int *x, int *y) const { - return TCOD_path_get(data,index,x,y); -} - -void TCODPath::getOrigin(int *x,int *y) const { - TCOD_path_get_origin(data,x,y); -} - -void TCODPath::getDestination(int *x,int *y) const { - TCOD_path_get_destination(data,x,y); -} - -// ----------------- // -// Dijkstra // -// written by Mingos // -// ----------------- // - -//ctor -TCODDijkstra::TCODDijkstra (TCODMap *map, float diagonalCost) { - data = TCOD_dijkstra_new(map->data,diagonalCost); -} - -//another ctor -TCODDijkstra::TCODDijkstra (int width, int height, const ITCODPathCallback *listener, void *userData, float diagonalCost) { - cppData.listener=listener; - cppData.userData=userData; - data=(void *)TCOD_dijkstra_new_using_function(width, height, TCOD_path_func, (void *)&cppData,diagonalCost); -} - -//dtor -TCODDijkstra::~TCODDijkstra (void) { - TCOD_dijkstra_delete(data); -} - -//compute distances grid -void TCODDijkstra::compute (int rootX, int rootY) { - TCOD_dijkstra_compute(data,rootX,rootY); -} - -//retrieve distance to a given cell -float TCODDijkstra::getDistance (int x, int y) { - return TCOD_dijkstra_get_distance(data,x,y); -} - -//create a path -bool TCODDijkstra::setPath (int toX, int toY) { - return (TCOD_dijkstra_path_set(data,toX,toY) != 0); -} - -void TCODDijkstra::reverse() { - TCOD_dijkstra_reverse(data); -} - -//walk a path -bool TCODDijkstra::walk (int *x, int *y) { - return TCOD_dijkstra_path_walk(data,x,y) != 0; -} - -bool TCODDijkstra::isEmpty() const { - return TCOD_dijkstra_is_empty(data) != 0; -} - -int TCODDijkstra::size() const { - return TCOD_dijkstra_size(data); -} - -void TCODDijkstra::get(int index, int *x, int *y) const { - return TCOD_dijkstra_get(data,index,x,y); -} +/* +* libtcod +* Copyright (c) 2008-2018 Jice & Mingos & rmtew +* All rights reserved. +* +* Redistribution and use in source and binary forms, with or without +* modification, are permitted provided that the following conditions are met: +* * Redistributions of source code must retain the above copyright +* notice, this list of conditions and the following disclaimer. +* * Redistributions in binary form must reproduce the above copyright +* notice, this list of conditions and the following disclaimer in the +* documentation and/or other materials provided with the distribution. +* * The name of Jice or Mingos may not be used to endorse or promote +* products derived from this software without specific prior written +* permission. +* +* THIS SOFTWARE IS PROVIDED BY JICE, MINGOS AND RMTEW ``AS IS'' AND ANY +* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED +* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE +* DISCLAIMED. IN NO EVENT SHALL JICE, MINGOS OR RMTEW BE LIABLE FOR ANY +* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES +* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; +* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND +* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS +* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +*/ +#include "path.hpp" + + +TCODPath::TCODPath(const TCODMap *map, float diagonalCost) { + data = TCOD_path_new_using_map(map->data, diagonalCost); +} + +TCODPath::~TCODPath() { + TCOD_path_delete(data); +} + +float TCOD_path_func(int xFrom, int yFrom, int xTo,int yTo, void *data) { + TCODPath::WrapperData *cppData=(TCODPath::WrapperData *)data; + return cppData->listener->getWalkCost(xFrom,yFrom,xTo,yTo,cppData->userData); +} + +TCODPath::TCODPath(int width, int height, const ITCODPathCallback *listener, void *userData, float diagonalCost) { + cppData.listener=listener; + cppData.userData=userData; + data = TCOD_path_new_using_function(width, height, TCOD_path_func, (void *)&cppData, diagonalCost); +} + + +bool TCODPath::compute(int ox, int oy, int dx, int dy) { + return TCOD_path_compute(data,ox,oy,dx,dy) != 0; +} + +bool TCODPath::walk(int *x, int *y, bool recalculateWhenNeeded) { + return TCOD_path_walk(data,x,y,recalculateWhenNeeded) != 0; +} + +bool TCODPath::isEmpty() const { + return TCOD_path_is_empty(data) != 0; +} + +void TCODPath::reverse() { + TCOD_path_reverse(data); +} + +int TCODPath::size() const { + return TCOD_path_size(data); +} + +void TCODPath::get(int index, int *x, int *y) const { + return TCOD_path_get(data,index,x,y); +} + +void TCODPath::getOrigin(int *x,int *y) const { + TCOD_path_get_origin(data,x,y); +} + +void TCODPath::getDestination(int *x,int *y) const { + TCOD_path_get_destination(data,x,y); +} + +// ----------------- // +// Dijkstra // +// written by Mingos // +// ----------------- // + +//ctor +TCODDijkstra::TCODDijkstra (TCODMap *map, float diagonalCost) { + data = TCOD_dijkstra_new(map->data,diagonalCost); +} + +//another ctor +TCODDijkstra::TCODDijkstra (int width, int height, const ITCODPathCallback *listener, void *userData, float diagonalCost) { + cppData.listener=listener; + cppData.userData=userData; + data = TCOD_dijkstra_new_using_function(width, height, TCOD_path_func, (void *)&cppData,diagonalCost); +} + +//dtor +TCODDijkstra::~TCODDijkstra (void) { + TCOD_dijkstra_delete(data); +} + +//compute distances grid +void TCODDijkstra::compute (int rootX, int rootY) { + TCOD_dijkstra_compute(data,rootX,rootY); +} + +//retrieve distance to a given cell +float TCODDijkstra::getDistance (int x, int y) { + return TCOD_dijkstra_get_distance(data,x,y); +} + +//create a path +bool TCODDijkstra::setPath (int toX, int toY) { + return (TCOD_dijkstra_path_set(data,toX,toY) != 0); +} + +void TCODDijkstra::reverse() { + TCOD_dijkstra_reverse(data); +} + +//walk a path +bool TCODDijkstra::walk (int *x, int *y) { + return TCOD_dijkstra_path_walk(data,x,y) != 0; +} + +bool TCODDijkstra::isEmpty() const { + return TCOD_dijkstra_is_empty(data) != 0; +} + +int TCODDijkstra::size() const { + return TCOD_dijkstra_size(data); +} + +void TCODDijkstra::get(int index, int *x, int *y) const { + return TCOD_dijkstra_get(data,index,x,y); +} diff --git a/tcod_sys/libtcod/include/path.h b/tcod_sys/libtcod/src/libtcod/path.h similarity index 95% rename from tcod_sys/libtcod/include/path.h rename to tcod_sys/libtcod/src/libtcod/path.h index 28e2c2f99..7d7efd131 100644 --- a/tcod_sys/libtcod/include/path.h +++ b/tcod_sys/libtcod/src/libtcod/path.h @@ -1,71 +1,73 @@ -/* -* libtcod -* Copyright (c) 2008-2018 Jice & Mingos & rmtew -* All rights reserved. -* -* Redistribution and use in source and binary forms, with or without -* modification, are permitted provided that the following conditions are met: -* * Redistributions of source code must retain the above copyright -* notice, this list of conditions and the following disclaimer. -* * Redistributions in binary form must reproduce the above copyright -* notice, this list of conditions and the following disclaimer in the -* documentation and/or other materials provided with the distribution. -* * The name of Jice or Mingos may not be used to endorse or promote -* products derived from this software without specific prior written -* permission. -* -* THIS SOFTWARE IS PROVIDED BY JICE, MINGOS AND RMTEW ``AS IS'' AND ANY -* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED -* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE -* DISCLAIMED. IN NO EVENT SHALL JICE, MINGOS OR RMTEW BE LIABLE FOR ANY -* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES -* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; -* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND -* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS -* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. -*/ -#ifndef _TCOD_PATH_H -#define _TCOD_PATH_H - -#include "libtcod_portability.h" -#include "fov_types.h" - -#ifdef __cplusplus -extern "C" { -#endif -typedef float (*TCOD_path_func_t)( int xFrom, int yFrom, int xTo, int yTo, void *user_data ); -typedef void *TCOD_path_t; - -TCODLIB_API TCOD_path_t TCOD_path_new_using_map(TCOD_map_t map, float diagonalCost); -TCODLIB_API TCOD_path_t TCOD_path_new_using_function(int map_width, int map_height, TCOD_path_func_t func, void *user_data, float diagonalCost); - -TCODLIB_API bool TCOD_path_compute(TCOD_path_t path, int ox,int oy, int dx, int dy); -TCODLIB_API bool TCOD_path_walk(TCOD_path_t path, int *x, int *y, bool recalculate_when_needed); -TCODLIB_API bool TCOD_path_is_empty(TCOD_path_t path); -TCODLIB_API int TCOD_path_size(TCOD_path_t path); -TCODLIB_API void TCOD_path_reverse(TCOD_path_t path); -TCODLIB_API void TCOD_path_get(TCOD_path_t path, int index, int *x, int *y); -TCODLIB_API void TCOD_path_get_origin(TCOD_path_t path, int *x, int *y); -TCODLIB_API void TCOD_path_get_destination(TCOD_path_t path, int *x, int *y); -TCODLIB_API void TCOD_path_delete(TCOD_path_t path); - -/* Dijkstra stuff - by Mingos*/ - -typedef void *TCOD_dijkstra_t; - -TCODLIB_API TCOD_dijkstra_t TCOD_dijkstra_new (TCOD_map_t map, float diagonalCost); -TCODLIB_API TCOD_dijkstra_t TCOD_dijkstra_new_using_function(int map_width, int map_height, TCOD_path_func_t func, void *user_data, float diagonalCost); -TCODLIB_API void TCOD_dijkstra_compute (TCOD_dijkstra_t dijkstra, int root_x, int root_y); -TCODLIB_API float TCOD_dijkstra_get_distance (TCOD_dijkstra_t dijkstra, int x, int y); -TCODLIB_API bool TCOD_dijkstra_path_set (TCOD_dijkstra_t dijkstra, int x, int y); -TCODLIB_API bool TCOD_dijkstra_is_empty(TCOD_dijkstra_t path); -TCODLIB_API int TCOD_dijkstra_size(TCOD_dijkstra_t path); -TCODLIB_API void TCOD_dijkstra_reverse(TCOD_dijkstra_t path); -TCODLIB_API void TCOD_dijkstra_get(TCOD_dijkstra_t path, int index, int *x, int *y); -TCODLIB_API bool TCOD_dijkstra_path_walk (TCOD_dijkstra_t dijkstra, int *x, int *y); -TCODLIB_API void TCOD_dijkstra_delete (TCOD_dijkstra_t dijkstra); -#ifdef __cplusplus -} -#endif -#endif +/* +* libtcod +* Copyright (c) 2008-2018 Jice & Mingos & rmtew +* All rights reserved. +* +* Redistribution and use in source and binary forms, with or without +* modification, are permitted provided that the following conditions are met: +* * Redistributions of source code must retain the above copyright +* notice, this list of conditions and the following disclaimer. +* * Redistributions in binary form must reproduce the above copyright +* notice, this list of conditions and the following disclaimer in the +* documentation and/or other materials provided with the distribution. +* * The name of Jice or Mingos may not be used to endorse or promote +* products derived from this software without specific prior written +* permission. +* +* THIS SOFTWARE IS PROVIDED BY JICE, MINGOS AND RMTEW ``AS IS'' AND ANY +* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED +* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE +* DISCLAIMED. IN NO EVENT SHALL JICE, MINGOS OR RMTEW BE LIABLE FOR ANY +* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES +* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; +* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND +* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS +* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +*/ +#ifndef _TCOD_PATH_H +#define _TCOD_PATH_H + +#include "portability.h" +#include "fov_types.h" + +#ifdef __cplusplus +extern "C" { +#endif +typedef float (*TCOD_path_func_t)( int xFrom, int yFrom, int xTo, int yTo, void *user_data ); +struct TCOD_Path; +typedef struct TCOD_Path *TCOD_path_t; + +TCODLIB_API TCOD_path_t TCOD_path_new_using_map(TCOD_map_t map, float diagonalCost); +TCODLIB_API TCOD_path_t TCOD_path_new_using_function(int map_width, int map_height, TCOD_path_func_t func, void *user_data, float diagonalCost); + +TCODLIB_API bool TCOD_path_compute(TCOD_path_t path, int ox,int oy, int dx, int dy); +TCODLIB_API bool TCOD_path_walk(TCOD_path_t path, int *x, int *y, bool recalculate_when_needed); +TCODLIB_API bool TCOD_path_is_empty(TCOD_path_t path); +TCODLIB_API int TCOD_path_size(TCOD_path_t path); +TCODLIB_API void TCOD_path_reverse(TCOD_path_t path); +TCODLIB_API void TCOD_path_get(TCOD_path_t path, int index, int *x, int *y); +TCODLIB_API void TCOD_path_get_origin(TCOD_path_t path, int *x, int *y); +TCODLIB_API void TCOD_path_get_destination(TCOD_path_t path, int *x, int *y); +TCODLIB_API void TCOD_path_delete(TCOD_path_t path); + +/* Dijkstra stuff - by Mingos*/ + +struct TCOD_Dijkstra; +typedef struct TCOD_Dijkstra *TCOD_dijkstra_t; + +TCODLIB_API TCOD_dijkstra_t TCOD_dijkstra_new (TCOD_map_t map, float diagonalCost); +TCODLIB_API TCOD_dijkstra_t TCOD_dijkstra_new_using_function(int map_width, int map_height, TCOD_path_func_t func, void *user_data, float diagonalCost); +TCODLIB_API void TCOD_dijkstra_compute (TCOD_dijkstra_t dijkstra, int root_x, int root_y); +TCODLIB_API float TCOD_dijkstra_get_distance (TCOD_dijkstra_t dijkstra, int x, int y); +TCODLIB_API bool TCOD_dijkstra_path_set (TCOD_dijkstra_t dijkstra, int x, int y); +TCODLIB_API bool TCOD_dijkstra_is_empty(TCOD_dijkstra_t path); +TCODLIB_API int TCOD_dijkstra_size(TCOD_dijkstra_t path); +TCODLIB_API void TCOD_dijkstra_reverse(TCOD_dijkstra_t path); +TCODLIB_API void TCOD_dijkstra_get(TCOD_dijkstra_t path, int index, int *x, int *y); +TCODLIB_API bool TCOD_dijkstra_path_walk (TCOD_dijkstra_t dijkstra, int *x, int *y); +TCODLIB_API void TCOD_dijkstra_delete (TCOD_dijkstra_t dijkstra); +#ifdef __cplusplus +} +#endif +#endif diff --git a/tcod_sys/libtcod/include/path.hpp b/tcod_sys/libtcod/src/libtcod/path.hpp similarity index 97% rename from tcod_sys/libtcod/include/path.hpp rename to tcod_sys/libtcod/src/libtcod/path.hpp index d32c7228b..830607fd1 100644 --- a/tcod_sys/libtcod/include/path.hpp +++ b/tcod_sys/libtcod/src/libtcod/path.hpp @@ -1,554 +1,554 @@ -/* -* libtcod -* Copyright (c) 2008-2018 Jice & Mingos & rmtew -* All rights reserved. -* -* Redistribution and use in source and binary forms, with or without -* modification, are permitted provided that the following conditions are met: -* * Redistributions of source code must retain the above copyright -* notice, this list of conditions and the following disclaimer. -* * Redistributions in binary form must reproduce the above copyright -* notice, this list of conditions and the following disclaimer in the -* documentation and/or other materials provided with the distribution. -* * The name of Jice or Mingos may not be used to endorse or promote -* products derived from this software without specific prior written -* permission. -* -* THIS SOFTWARE IS PROVIDED BY JICE, MINGOS AND RMTEW ``AS IS'' AND ANY -* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED -* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE -* DISCLAIMED. IN NO EVENT SHALL JICE, MINGOS OR RMTEW BE LIABLE FOR ANY -* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES -* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; -* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND -* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS -* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. -*/ -#ifndef _TCOD_PATH_HPP -#define _TCOD_PATH_HPP - -#include "fov.hpp" -#include "path.h" - -class TCODLIB_API ITCODPathCallback { -public : - virtual ~ITCODPathCallback() {} - virtual float getWalkCost( int xFrom, int yFrom, int xTo, int yTo, void *userData ) const = 0; -}; - -/** - @PageName path - @PageTitle Path finding - @PageCategory Roguelike toolkits - @PageDesc This toolkit allows one to easily calculate the optimal path between two points in your dungeon by using either the A* algorithm or Dijkstra's algorithm. -Please note that the paths generated with the two algorithms may differ slightly. Due to how they're implemented, A* will usually prefer diagonal moves over orthogonal, while Dijkstra will have the opposite preference. In other words, paths from point X to point Y will look like this: -
-Dijkstra:      A*:
-..........   ..........
-.X........   .X*.......
-..*.......   ...**.....
-...*......   .....**...
-....****Y.   .......*Y.
-..........   ..........
-
- */ -class TCODLIB_API TCODPath { -public : - /** - @PageName path_init - @PageFather path - @PageTitle Creating a path - @FuncTitle Allocating a pathfinder from a map - @FuncDesc First, you have to allocate a path using a map from the Field of view module. - @Cpp - TCODPath::TCODPath(const TCODMap *map, float diagonalCost=1.41f) - TCODDijkstra::TCODDijkstra(const TCODMap *map, float diagonalCost=1.41f) - @C - TCOD_path_t TCOD_path_new_using_map(TCOD_map_t map, float diagonalCost) - TCOD_dijkstra_t TCOD_dijkstra_new(TCOD_map_t map, float diagonalCost) - @Py - path_new_using_map(map, diagonalCost=1.41) - dijkstra_new(map, diagonalCost=1.41) - @C# - TCODPath(TCODMap map, float diagonalCost) - TCODPath(TCODMap map) - TCODDijkstra(TCODMap map, float diagonalCost) - TCODDijkstra(TCODMap map) - @Param map The map. The path finder will use the 'walkable' property of the cells to find a path. - @Param diagonalCost Cost of a diagonal movement compared to an horizontal or vertical movement. On a standard cartesian map, it should be sqrt(2) (1.41f). - It you want the same cost for all movements, use 1.0f. - If you don't want the path finder to use diagonal movements, use 0.0f. - @CppEx - // A* : - TCODMap *myMap = new TCODMap(50,50); - TCODPath *path = new TCODPath(myMap); // allocate the path - // Dijkstra: - TCODMap *myMap = new TCODMap(50,50); - TCODDijkstra *dijkstra = new TCODDijkstra(myMap); // allocate the path - @CEx - // A* : - TCOD_map_t my_map=TCOD_map_new(50,50,true); - TCOD_path_t path = TCOD_path_new_using_map(my_map,1.41f); - // Dijkstra : - TCOD_map_t my_map=TCOD_map_new(50,50,true); - TCOD_dijkstra_t dijk = TCOD_dijkstra_new(my_map,1.41f); - @PyEx - # A* : - my_map=libtcod.map_new(50,50,True) - path = libtcod.path_new_using_map(my_map) - # Dijkstra - my_map=libtcod.map_new(50,50,True) - dijk = libtcod.dijkstra_new(my_map) - */ - TCODPath(const TCODMap *map, float diagonalCost=1.41f); - /** - @PageName path_init - @FuncTitle Allocating a pathfinder using a callback - @FuncDesc Since the walkable status of a cell may depend on a lot of parameters (the creature type, the weather, the terrain type...), you can also create a path by providing a function rather than relying on a TCODMap. - @Cpp - // Callback : - class ITCODPathCallback { - public: virtual float getWalkCost( int xFrom, int yFrom, int xTo, int yTo, void *userData ) const = 0; - }; - // A* constructor: - TCODPath::TCODPath(int width, int height, const ITCODPathCallback *callback, void *userData, float diagonalCost=1.41f) - // Dijkstra constructor - TCODDijkstra::TCODDijkstra(int width, int height, const ITCODPathCallback *callback, void *userData, float diagonalCost=1.41f) - @C - typedef float (*TCOD_path_func_t)( int xFrom, int yFrom, int xTo, int yTo, void *user_data ) - TCOD_path_t TCOD_path_new_using_function(int width, int height, TCOD_path_func_t callback, void *user_data, float diagonalCost) - TCOD_dijkstra_t TCOD_dijkstra_new_using_function(int width, int height, TCOD_path_func_t callback, void *user_data, float diagonalCost) - @Py - def path_func(xFrom,yFrom,xTo,yTo,userData) : ... - path_new_using_function(width, height, path_func, user_data=0, diagonalCost=1.41) - dijkstra_new_using_function(width, height, path_func, user_data=0, diagonalCost=1.41) - @C# - TCODPath(int width, int height, ITCODPathCallback listener, float diagonalCost) - TCODPath(int width, int height, ITCODPathCallback listener) - TCODDijkstra(int width, int height, ITCODPathCallback listener, float diagonalCost) - TCODDijkstra(int width, int height, ITCODPathCallback listener) - @Param width,height The size of the map (in map cells). - @Param callback A custom function that must return the walk cost from coordinates xFrom,yFrom to coordinates xTo,yTo. - The cost must be > 0.0f if the cell xTo,yTo is walkable. - It must be equal to 0.0f if it's not. - You must not take additional cost due to diagonal movements into account as it's already done by the pathfinder. - @Param userData Custom data that will be passed to the function. - @Param diagonalCost Cost of a diagonal movement compared to an horizontal or vertical movement. On a standard cartesian map, it should be sqrt(2) (1.41f). - It you want the same cost for all movements, use 1.0f. - If you don't want the path finder to use diagonal movements, use 0.0f. - @CppEx - class MyCallback : public ITCODPathCallback { - public : - float getWalkCost(int xFrom, int yFrom, int xTo, int yTo, void *userData ) const { ... } - }; - TCODPath *path = new TCODPath(50,50,new MyCallback(),NULL); // allocate the path - TCODDijkstra *dijkstra = new TCODDijkstra(50,50,new MyCallback(),NULL); // allocate Dijkstra - @CEx - float my_func(int xFrom, int yFrom, int xTo, int yTo, void *user_data) { ... } - TCOD_path_t path = TCOD_path_new_using_function(50,50,my_func,NULL,1.41f); - TCOD_dijkstra_t dijkstra = TCOD_dijkstra_new_using_function(50,50,my_func,NULL,1.41f); - @PyEx - def my_func(xFrom, yFrom, xTo, yTo, user_data) : - # return a float cost for this movement - return 1.0 - path = libtcod.path_new_using_function(50,50,my_func) - dijkstra = libtcod.dijkstra_new_using_function(50,50,my_func) - */ - TCODPath(int width, int height, const ITCODPathCallback *listener, void *userData, float diagonalCost=1.41f); - - /** - @PageName path_init - @FuncTitle Destroying a path - @FuncDesc To release the resources used by a path, destroy it with : - @Cpp - TCODPath::~TCODPath() - TCODDijkstra::~TCODDijkstra() - @C - void TCOD_path_delete(TCOD_path_t path) - void TCOD_dijkstra_delete(TCOD_dijkstra_t dijkstra) - @Py - path_delete(path) - dijkstra_delete(dijkstra) - @C# - void TCODPath::Dispose() - void TCODDijkstra::Dispose() - @Param path In the C version, the path handler returned by one of the TCOD_path_new_* function. - @Param dijkstra In the C version, the path handler returned by one of the TCOD_dijkstra_new* function. - @CppEx - TCODPath *path = new TCODPath(myMap); // allocate the path - // use the path... - delete path; // destroy the path - - TCODDijkstra *dijkstra = new TCODDijkstra(myMap); // allocate the path - // use the path... - delete dijkstra; // destroy the path - @CEx - TCOD_path_t path = TCOD_path_new_using_map(my_map); - // use the path ... - TCOD_path_delete(path); - - TCOD_dijkstra_t dijkstra = TCOD_dijkstra_new(my_map); - // use the path ... - TCOD_dijkstra_delete(dijkstra); - @PyEx - path = libtcod.path_new_using_map(my_map) - # use the path ... - libtcod.path_delete(path) - - dijkstra = libtcod.dijkstra_new(my_map) - # use the path ... - libtcod.dijkstra_delete(dijkstra) - */ - virtual ~TCODPath(); - - /** - @PageName path_compute - @PageFather path - @PageTitle Computing the path - @FuncTitle Computing an A* path - @FuncDesc Once you created a TCODPath object, you can compute the path between two points: - @Cpp bool TCODPath::compute(int ox, int oy, int dx, int dy) - @C bool TCOD_path_compute(TCOD_path_t path, int ox,int oy, int dx, int dy) - @Py path_compute(path, ox, oy, dx, dy) - @C# void TCODPath::compute(int ox, int oy, int dx, int dy) - @Param path In the C version, the path handler returned by a creation function. - @Param ox,oy Coordinates of the origin of the path. - @Param dx,dy Coordinates of the destination of the path. - Both points should be inside the map, and at a walkable position. The function returns false if there is no possible path. - @CppEx - TCODMap *myMap = new TCODMap(50,50); - TCODPath *path = new TCODPath(myMap); // allocate the path - path->compute(5,5,25,25); // calculate path from 5,5 to 25,25 - @CEx - TCOD_map_t my_map=TCOD_map_new(50,50); - TCOD_path_t path = TCOD_path_new_using_map(my_map); - TCOD_path_compute(path,5,5,25,25); - @PyEx - my_map=libtcod.map_new(50,50) - path = libtcod.path_new_using_map(my_map) - libtcod.path_compute(path,5,5,25,25) - */ - bool compute(int ox, int oy, int dx, int dy); - - /** - @PageName path_compute - @FuncTitle Reversing a path - @FuncDesc Once you computed a path, you can exchange origin and destination : - @Cpp - void TCODPath::reverse() - void TCODDijkstra::reverse() - @C - void TCOD_path_reverse(TCOD_path_t path) - void TCOD_dijkstra_reverse(TCOD_dijkstra_t dijkstra) - @Py - path_reverse(path) - dijkstra_reverse(dijkstra) - @C# - void TCODPath::reverse() - void TCODDijkstra::reverse() - @Param path In the C version, the path handler returned by a creation function. - @CppEx - TCODMap *myMap = new TCODMap(50,50); - TCODPath *path = new TCODPath(myMap); // allocate the path - path->compute(5,5,25,25); // calculate path from 5,5 to 25,25 - path->reverse(); // now the path goes from 25,25 to 5,5 - @CEx - TCOD_map_t my_map=TCOD_map_new(50,50); - TCOD_path_t path = TCOD_path_new_using_map(my_map); - TCOD_path_compute(path,5,5,25,25); // calculate path from 5,5 to 25,25 - TCOD_path_reverse(path); // now the path goes from 25,25 to 5,5 - @PyEx - my_map=libtcod.map_new(50,50) - path = libtcod.path_new_using_map(my_map) - libtcod.path_compute(path,5,5,25,25) # calculate path from 5,5 to 25,25 - libtcod.path_reverse(path) # now the path goes from 25,25 to 5,5 - */ - void reverse(); - - - /** - @PageName path_read - @PageTitle Reading path information - @PageFather path - @PageDescDesc Once the path has been computed, you can get information about it using of one those functions. - @FuncTitle Getting the path origin and destination - @FuncDesc - You can read the current origin and destination cells with getOrigin/getDestination. - Note that when you walk the path, the origin changes at each step. - @Cpp - void TCODPath::getOrigin(int *x,int *y) const - void TCODPath::getDestination(int *x,int *y) const - @C - void TCOD_path_get_origin(TCOD_path_t path, int *x, int *y) - void TCOD_path_get_destination(TCOD_path_t path, int *x, int *y) - @Py - path_get_origin(path) # returns x,y - path_get_destination(path) # returns x,y - @C# - void TCODPath::getOrigin(out int x, out int y) - void TCODPath::getDestination(out int x, out int y) - @Param path In the C version, the path handler returned by a creation function. - @Param x,y The function returns the cell coordinates in these variables - */ - void getOrigin(int *x,int *y) const; - void getDestination(int *x,int *y) const; - - /** - @PageName path_read - @FuncTitle Getting the path length - @FuncDesc You can get the number of steps needed to reach destination : - @Cpp - int TCODPath::size() const - int TCODDijkstra::size() const - @C - int TCOD_path_size(TCOD_path_t path) - int TCOD_dijkstra_size(TCOD_dijkstra_t dijkstra) - @Py - path_size(path) - dijkstra_size(dijkstra) - @C# - int TCODPath::size() - int TCODDijkstra::size() - @Param path, dijkstra In the C version, the path handler returned by a creation function. - */ - int size() const; - - /** - @PageName path_read - @FuncTitle Read the path cells' coordinates - @FuncDesc You can get the coordinates of each point along the path : - @Cpp - void TCODPath::get(int index, int *x, int *y) const - void TCODDijkstra::get(int index, int *x, int *y) const - @C - void TCOD_path_get(TCOD_path_t path, int index, int *x, int *y) - void TCOD_dijkstra_get(TCOD_dijkstra_t dijkstra, int index, int *x, int *y) - @Py - path_get(path, index) # returns x,y - dijkstra_get(dijkstra, index) # returns x,y - @C# - int TCODPath::size() - int TCODDijkstra::size() - @Param path, dijkstra In the C version, the path handler returned by a creation function. - @Param index Step number. - 0 <= index < path size - @Param x,y Address of the variables receiving the coordinates of the point. - @CppEx - for (int i=0; i < path->size(); i++ ) { - int x,y; - path->get(i,&x,&y); - printf ("Astar coord : %d %d\n", x,y ); - } - for (int i=0; i < dijkstra->size(); i++ ) { - int x,y; - dijkstra->get(i,&x,&y); - printf ("Dijkstra coord : %d %d\n", x,y ); - } - @CEx - int i; - for (i=0; i < TCOD_path_size(path); i++ ) { - int x,y; - TCOD_path_get(path,i,&x,&y); - printf ("Astar coord : %d %d\n", x,y ); - } - for (i=0; i < TCOD_dijkstra_size(dijkstra); i++ ) { - int x,y; - TCOD_dijkstra_get(dijkstra,i,&x,&y); - printf ("Dijsktra coord : %d %d\n", x,y ); - } - @PyEx - for i in range (libtcod.path_size(path)) : - x,y=libtcod.path_get(path,i) - print 'Astar coord : ',x,y - for i in range (libtcod.dijkstra_size(dijkstra)) : - x,y=libtcod.dijkstra_get(dijkstra,i) - print 'Dijkstra coord : ',x,y - */ - void get(int index, int *x, int *y) const; - - /** - @PageName path_read - @FuncTitle Checking if the path is empty - @FuncDesc If you want a creature to follow the path, a more convenient way is to walk the path : - You know when you reached destination when the path is empty : - @Cpp - bool TCODPath::isEmpty() const - bool TCODDijkstra::isEmpty() const - @C - bool TCOD_path_is_empty(TCOD_path_t path) - bool TCOD_dijkstra_is_empty(TCOD_dijkstra_t dijkstra) - @Py - path_is_empty(path) - dijkstra_is_empty(dijkstra) - @C# - bool TCODPath::isEmpty() - bool TCODDijkstra::isEmpty() - @Param path, dijkstra In the C version, the path handler returned by a creation function. - */ - bool isEmpty() const; - - /** - @PageName path_read - @FuncTitle Walking the path - @FuncDesc You can walk the path and go to the next step with : - Note that walking the path consume one step (and decrease the path size by one). The function returns false if recalculateWhenNeeded is false and the next cell on the path is no longer walkable, or if recalculateWhenNeeded is true, the next cell on the path is no longer walkable and no other path has been found. Also note that recalculateWhenNeeded only applies to A*. - @Cpp - bool TCODPath::walk(int *x, int *y, bool recalculateWhenNeeded) - bool TCODDijkstra::walk(int *x, int *y) - @C - bool TCOD_path_walk(TCOD_path_t path, int *x, int *y, bool recalculate_when_needed) - bool TCOD_dijkstra_walk(TCOD_dijkstra_t dijkstra, int *x, int *y) - @Py - path_walk(TCOD_path_t path, recalculate_when_needed) # returns x,y or None,None if no path - dijkstra_walk(TCOD_dijkstra_t dijkstra) - @C# - bool TCODPath::walk(ref int x, ref int y, bool recalculateWhenNeeded) - bool TCODDijkstra::walk(ref int x, ref int y) - @Param path, dijkstra In the C version, the path handler returned by a creation function. - @Param x,y Address of the variables receiving the coordinates of the next point. - @Param recalculateWhenNeeded If the next point is no longer walkable (another creature may be in the way), recalculate a new path and walk it. - @CppEx - while (! path->isEmpty()) { - int x,y; - if (path->walk(&x,&y,true)) { - printf ("Astar coord: %d %d\n",x,y ); - } else { - printf ("I'm stuck!\n" ); - break; - } - } - while (! dijkstra->isEmpty()) { - int x,y; - if (dijkstra->walk(&x,&y)) { - printf ("Dijkstra coord: %d %d\n",x,y ); - } else { - printf ("I'm stuck!\n" ); - break; - } - } - @CEx - while (! TCOD_path_is_empty(path)) { - int x,y; - if (TCOD_path_walk(path,&x,&y,true)) { - printf ("Astar coord: %d %d\n",x,y ); - } else { - printf ("I'm stuck!\n" ); - break; - } - } - while (! TCOD_dijkstra_is_empty(dijkstra)) { - int x,y; - if (TCOD_dijkstra_walk(dijkstra,&x,&y)) { - printf ("Dijkstra coord: %d %d\n",x,y ); - } else { - printf ("I'm stuck!\n" ); - break; - } - } - @PyEx - while not libtcod.path_is_empty(path)) : - x,y=libtcod.path_walk(path,True) - if not x is None : - print 'Astar coord: ',x,y - else : - print "I'm stuck!" - break - while not libtcod.dijkstra_is_empty(dijkstra)) : - x,y=libtcod.dijkstra_walk(dijkstra,True) - if not x is None : - print 'Dijkstra coord: ',x,y - else : - print "I'm stuck!" - break - */ - bool walk(int *x, int *y, bool recalculateWhenNeeded); - -protected : - friend float TCOD_path_func(int xFrom, int yFrom, int xTo,int yTo, void *data); - TCOD_path_t data; - struct WrapperData { - void *userData; - const ITCODPathCallback *listener; - } cppData; -}; - -//Dijkstra kit -class TCODLIB_API TCODDijkstra { - public: - TCODDijkstra (TCODMap *map, float diagonalCost=1.41f); - TCODDijkstra (int width, int height, const ITCODPathCallback *listener, void *userData, float diagonalCost=1.41f); - ~TCODDijkstra (void); - /** - @PageName path_compute - @FuncTitle Computing a Dijkstra grid - @FuncDesc In case of Dijkstra, this works in a slightly different way. In order to be able to compute a path, Dijkstra must first analyse the distances from the selected root (origin) node to all other nodes: - @Cpp void TCODDijkstra::compute(int rootX, int rootY) - @C void TCOD_dijkstra_compute(TCOD_dijkstra_t dijkstra, int root_x, int root_y) - @Py dijkstra_compute(dijkstra, root_x, root_y) - @C# void TCODDijkstra::compute(int rootX, int rootY) - @Param dijkstra In the C version, the path handler returned by a creation function. - @Param root_x,root_y Coordinates of the root node (origin) of the path. - The coordinates should be inside the map, at a walkable position. Otherwise, the function's behaviour will be undefined. - */ - void compute (int rootX, int rootY); - - /** - @PageName path_compute - @FuncTitle Computing a path from a Dijkstra grid - @FuncDesc After the map is analysed and all the distances from the root node are known, an unlimited number of paths can be set, all originating at the root node, using: - The path setting function will return true if there's a path from the root node to the destination node. Otherwise, it will return false. - @Cpp bool TCODDijkstra::setPath(int toX, int toY) - @C bool TCOD_dijkstra_path_set(TCOD_dijkstra_t dijkstra, int to_x, int to_y) - @Py dijkstra_path_set(dijkstra, to_x, to_y) - @C# bool TCODDijkstra::setPath(int toX, int toY) - @Param dijkstra In the C version, the path handler returned by a creation function. - @Param to_x,to_y Coordinates of the destination node of the path. - @CppEx - TCODMap *myMap = new TCODMap(50,50); - TCODDijkstra *dijkstra = new TCODDijkstra(myMap); // allocate the path - dijkstra->compute(25,25); // calculate distance from 25,25 to all other nodes - dijkstra->setPath(5,5); // calculate a path to node 5,5 - dijkstra->setPath(45,45); //calculate another path from the same origin - @CEx - TCOD_map_t my_map=TCOD_map_new(50,50); - TCOD_dijkstra_t dijkstra = TCOD_dijkstra_new(my_map); - TCOD_dijkstra_compute(dijkstra,25,25); - TCOD_dijkstra_path_set(dijkstra,5,5); - TCOD_dijkstra_path_set(dijkstra,45,45); - @PyEx - my_map=libtcod.map_new(50,50) - dijkstra = libtcod.dijkstra_new(my_map) - libtcod.dijkstra_compute(dijkstra,25,25) - libtcod.dijkstra_path_set(dijkstra,5,5) - libtcod.dijkstra_path_set(dijkstra,45,45) - */ - bool setPath (int toX, int toY); - - /** - @PageName path_read - @FuncTitle Getting the distance from a cell to the root node - @FuncDesc You can get the distance of any set of coordinates from the root node: - Note that if the coordinates x,y are outside of the map or are a non-walkable position, the function will return -1.0f. This functionality is only available for Dijkstra's algorithm. - @Cpp float TCODDijkstra::getDistance(int x, int y) - @C float TCOD_dijkstra_get_distance(TCOD_dijkstra_t dijkstra, int x, int y) - @Py dijkstra_get_distance(dijkstra, x, y) - @C# float TCODDijkstra::getDistance(int x, int y) - @Param dijkstra In the C version, the path handler returned by a creation function. - @Param x,y The coordinates whose distance from the root node are to be checked - */ - float getDistance (int x, int y); - bool walk (int *x, int *y); - bool isEmpty() const; - void reverse(); - int size() const; - void get(int index, int *x, int *y) const; - private: - TCOD_dijkstra_t data; - struct WrapperData { - void *userData; - const ITCODPathCallback *listener; - } cppData; -}; - -#endif +/* +* libtcod +* Copyright (c) 2008-2018 Jice & Mingos & rmtew +* All rights reserved. +* +* Redistribution and use in source and binary forms, with or without +* modification, are permitted provided that the following conditions are met: +* * Redistributions of source code must retain the above copyright +* notice, this list of conditions and the following disclaimer. +* * Redistributions in binary form must reproduce the above copyright +* notice, this list of conditions and the following disclaimer in the +* documentation and/or other materials provided with the distribution. +* * The name of Jice or Mingos may not be used to endorse or promote +* products derived from this software without specific prior written +* permission. +* +* THIS SOFTWARE IS PROVIDED BY JICE, MINGOS AND RMTEW ``AS IS'' AND ANY +* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED +* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE +* DISCLAIMED. IN NO EVENT SHALL JICE, MINGOS OR RMTEW BE LIABLE FOR ANY +* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES +* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; +* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND +* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS +* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +*/ +#ifndef _TCOD_PATH_HPP +#define _TCOD_PATH_HPP + +#include "fov.hpp" +#include "path.h" + +class TCODLIB_API ITCODPathCallback { +public : + virtual ~ITCODPathCallback() {} + virtual float getWalkCost( int xFrom, int yFrom, int xTo, int yTo, void *userData ) const = 0; +}; + +/** + @PageName path + @PageTitle Path finding + @PageCategory Roguelike toolkits + @PageDesc This toolkit allows one to easily calculate the optimal path between two points in your dungeon by using either the A* algorithm or Dijkstra's algorithm. +Please note that the paths generated with the two algorithms may differ slightly. Due to how they're implemented, A* will usually prefer diagonal moves over orthogonal, while Dijkstra will have the opposite preference. In other words, paths from point X to point Y will look like this: +
+Dijkstra:      A*:
+..........   ..........
+.X........   .X*.......
+..*.......   ...**.....
+...*......   .....**...
+....****Y.   .......*Y.
+..........   ..........
+
+ */ +class TCODLIB_API TCODPath { +public : + /** + @PageName path_init + @PageFather path + @PageTitle Creating a path + @FuncTitle Allocating a pathfinder from a map + @FuncDesc First, you have to allocate a path using a map from the Field of view module. + @Cpp + TCODPath::TCODPath(const TCODMap *map, float diagonalCost=1.41f) + TCODDijkstra::TCODDijkstra(const TCODMap *map, float diagonalCost=1.41f) + @C + TCOD_path_t TCOD_path_new_using_map(TCOD_map_t map, float diagonalCost) + TCOD_dijkstra_t TCOD_dijkstra_new(TCOD_map_t map, float diagonalCost) + @Py + path_new_using_map(map, diagonalCost=1.41) + dijkstra_new(map, diagonalCost=1.41) + @C# + TCODPath(TCODMap map, float diagonalCost) + TCODPath(TCODMap map) + TCODDijkstra(TCODMap map, float diagonalCost) + TCODDijkstra(TCODMap map) + @Param map The map. The path finder will use the 'walkable' property of the cells to find a path. + @Param diagonalCost Cost of a diagonal movement compared to an horizontal or vertical movement. On a standard cartesian map, it should be sqrt(2) (1.41f). + It you want the same cost for all movements, use 1.0f. + If you don't want the path finder to use diagonal movements, use 0.0f. + @CppEx + // A* : + TCODMap *myMap = new TCODMap(50,50); + TCODPath *path = new TCODPath(myMap); // allocate the path + // Dijkstra: + TCODMap *myMap = new TCODMap(50,50); + TCODDijkstra *dijkstra = new TCODDijkstra(myMap); // allocate the path + @CEx + // A* : + TCOD_map_t my_map=TCOD_map_new(50,50,true); + TCOD_path_t path = TCOD_path_new_using_map(my_map,1.41f); + // Dijkstra : + TCOD_map_t my_map=TCOD_map_new(50,50,true); + TCOD_dijkstra_t dijk = TCOD_dijkstra_new(my_map,1.41f); + @PyEx + # A* : + my_map=libtcod.map_new(50,50,True) + path = libtcod.path_new_using_map(my_map) + # Dijkstra + my_map=libtcod.map_new(50,50,True) + dijk = libtcod.dijkstra_new(my_map) + */ + TCODPath(const TCODMap *map, float diagonalCost=1.41f); + /** + @PageName path_init + @FuncTitle Allocating a pathfinder using a callback + @FuncDesc Since the walkable status of a cell may depend on a lot of parameters (the creature type, the weather, the terrain type...), you can also create a path by providing a function rather than relying on a TCODMap. + @Cpp + // Callback : + class ITCODPathCallback { + public: virtual float getWalkCost( int xFrom, int yFrom, int xTo, int yTo, void *userData ) const = 0; + }; + // A* constructor: + TCODPath::TCODPath(int width, int height, const ITCODPathCallback *callback, void *userData, float diagonalCost=1.41f) + // Dijkstra constructor + TCODDijkstra::TCODDijkstra(int width, int height, const ITCODPathCallback *callback, void *userData, float diagonalCost=1.41f) + @C + typedef float (*TCOD_path_func_t)( int xFrom, int yFrom, int xTo, int yTo, void *user_data ) + TCOD_path_t TCOD_path_new_using_function(int width, int height, TCOD_path_func_t callback, void *user_data, float diagonalCost) + TCOD_dijkstra_t TCOD_dijkstra_new_using_function(int width, int height, TCOD_path_func_t callback, void *user_data, float diagonalCost) + @Py + def path_func(xFrom,yFrom,xTo,yTo,userData) : ... + path_new_using_function(width, height, path_func, user_data=0, diagonalCost=1.41) + dijkstra_new_using_function(width, height, path_func, user_data=0, diagonalCost=1.41) + @C# + TCODPath(int width, int height, ITCODPathCallback listener, float diagonalCost) + TCODPath(int width, int height, ITCODPathCallback listener) + TCODDijkstra(int width, int height, ITCODPathCallback listener, float diagonalCost) + TCODDijkstra(int width, int height, ITCODPathCallback listener) + @Param width,height The size of the map (in map cells). + @Param callback A custom function that must return the walk cost from coordinates xFrom,yFrom to coordinates xTo,yTo. + The cost must be > 0.0f if the cell xTo,yTo is walkable. + It must be equal to 0.0f if it's not. + You must not take additional cost due to diagonal movements into account as it's already done by the pathfinder. + @Param userData Custom data that will be passed to the function. + @Param diagonalCost Cost of a diagonal movement compared to an horizontal or vertical movement. On a standard cartesian map, it should be sqrt(2) (1.41f). + It you want the same cost for all movements, use 1.0f. + If you don't want the path finder to use diagonal movements, use 0.0f. + @CppEx + class MyCallback : public ITCODPathCallback { + public : + float getWalkCost(int xFrom, int yFrom, int xTo, int yTo, void *userData ) const { ... } + }; + TCODPath *path = new TCODPath(50,50,new MyCallback(),NULL); // allocate the path + TCODDijkstra *dijkstra = new TCODDijkstra(50,50,new MyCallback(),NULL); // allocate Dijkstra + @CEx + float my_func(int xFrom, int yFrom, int xTo, int yTo, void *user_data) { ... } + TCOD_path_t path = TCOD_path_new_using_function(50,50,my_func,NULL,1.41f); + TCOD_dijkstra_t dijkstra = TCOD_dijkstra_new_using_function(50,50,my_func,NULL,1.41f); + @PyEx + def my_func(xFrom, yFrom, xTo, yTo, user_data) : + # return a float cost for this movement + return 1.0 + path = libtcod.path_new_using_function(50,50,my_func) + dijkstra = libtcod.dijkstra_new_using_function(50,50,my_func) + */ + TCODPath(int width, int height, const ITCODPathCallback *listener, void *userData, float diagonalCost=1.41f); + + /** + @PageName path_init + @FuncTitle Destroying a path + @FuncDesc To release the resources used by a path, destroy it with : + @Cpp + TCODPath::~TCODPath() + TCODDijkstra::~TCODDijkstra() + @C + void TCOD_path_delete(TCOD_path_t path) + void TCOD_dijkstra_delete(TCOD_dijkstra_t dijkstra) + @Py + path_delete(path) + dijkstra_delete(dijkstra) + @C# + void TCODPath::Dispose() + void TCODDijkstra::Dispose() + @Param path In the C version, the path handler returned by one of the TCOD_path_new_* function. + @Param dijkstra In the C version, the path handler returned by one of the TCOD_dijkstra_new* function. + @CppEx + TCODPath *path = new TCODPath(myMap); // allocate the path + // use the path... + delete path; // destroy the path + + TCODDijkstra *dijkstra = new TCODDijkstra(myMap); // allocate the path + // use the path... + delete dijkstra; // destroy the path + @CEx + TCOD_path_t path = TCOD_path_new_using_map(my_map); + // use the path ... + TCOD_path_delete(path); + + TCOD_dijkstra_t dijkstra = TCOD_dijkstra_new(my_map); + // use the path ... + TCOD_dijkstra_delete(dijkstra); + @PyEx + path = libtcod.path_new_using_map(my_map) + # use the path ... + libtcod.path_delete(path) + + dijkstra = libtcod.dijkstra_new(my_map) + # use the path ... + libtcod.dijkstra_delete(dijkstra) + */ + virtual ~TCODPath(); + + /** + @PageName path_compute + @PageFather path + @PageTitle Computing the path + @FuncTitle Computing an A* path + @FuncDesc Once you created a TCODPath object, you can compute the path between two points: + @Cpp bool TCODPath::compute(int ox, int oy, int dx, int dy) + @C bool TCOD_path_compute(TCOD_path_t path, int ox,int oy, int dx, int dy) + @Py path_compute(path, ox, oy, dx, dy) + @C# void TCODPath::compute(int ox, int oy, int dx, int dy) + @Param path In the C version, the path handler returned by a creation function. + @Param ox,oy Coordinates of the origin of the path. + @Param dx,dy Coordinates of the destination of the path. + Both points should be inside the map, and at a walkable position. The function returns false if there is no possible path. + @CppEx + TCODMap *myMap = new TCODMap(50,50); + TCODPath *path = new TCODPath(myMap); // allocate the path + path->compute(5,5,25,25); // calculate path from 5,5 to 25,25 + @CEx + TCOD_map_t my_map=TCOD_map_new(50,50); + TCOD_path_t path = TCOD_path_new_using_map(my_map); + TCOD_path_compute(path,5,5,25,25); + @PyEx + my_map=libtcod.map_new(50,50) + path = libtcod.path_new_using_map(my_map) + libtcod.path_compute(path,5,5,25,25) + */ + bool compute(int ox, int oy, int dx, int dy); + + /** + @PageName path_compute + @FuncTitle Reversing a path + @FuncDesc Once you computed a path, you can exchange origin and destination : + @Cpp + void TCODPath::reverse() + void TCODDijkstra::reverse() + @C + void TCOD_path_reverse(TCOD_path_t path) + void TCOD_dijkstra_reverse(TCOD_dijkstra_t dijkstra) + @Py + path_reverse(path) + dijkstra_reverse(dijkstra) + @C# + void TCODPath::reverse() + void TCODDijkstra::reverse() + @Param path In the C version, the path handler returned by a creation function. + @CppEx + TCODMap *myMap = new TCODMap(50,50); + TCODPath *path = new TCODPath(myMap); // allocate the path + path->compute(5,5,25,25); // calculate path from 5,5 to 25,25 + path->reverse(); // now the path goes from 25,25 to 5,5 + @CEx + TCOD_map_t my_map=TCOD_map_new(50,50); + TCOD_path_t path = TCOD_path_new_using_map(my_map); + TCOD_path_compute(path,5,5,25,25); // calculate path from 5,5 to 25,25 + TCOD_path_reverse(path); // now the path goes from 25,25 to 5,5 + @PyEx + my_map=libtcod.map_new(50,50) + path = libtcod.path_new_using_map(my_map) + libtcod.path_compute(path,5,5,25,25) # calculate path from 5,5 to 25,25 + libtcod.path_reverse(path) # now the path goes from 25,25 to 5,5 + */ + void reverse(); + + + /** + @PageName path_read + @PageTitle Reading path information + @PageFather path + @PageDescDesc Once the path has been computed, you can get information about it using of one those functions. + @FuncTitle Getting the path origin and destination + @FuncDesc + You can read the current origin and destination cells with getOrigin/getDestination. + Note that when you walk the path, the origin changes at each step. + @Cpp + void TCODPath::getOrigin(int *x,int *y) const + void TCODPath::getDestination(int *x,int *y) const + @C + void TCOD_path_get_origin(TCOD_path_t path, int *x, int *y) + void TCOD_path_get_destination(TCOD_path_t path, int *x, int *y) + @Py + path_get_origin(path) # returns x,y + path_get_destination(path) # returns x,y + @C# + void TCODPath::getOrigin(out int x, out int y) + void TCODPath::getDestination(out int x, out int y) + @Param path In the C version, the path handler returned by a creation function. + @Param x,y The function returns the cell coordinates in these variables + */ + void getOrigin(int *x,int *y) const; + void getDestination(int *x,int *y) const; + + /** + @PageName path_read + @FuncTitle Getting the path length + @FuncDesc You can get the number of steps needed to reach destination : + @Cpp + int TCODPath::size() const + int TCODDijkstra::size() const + @C + int TCOD_path_size(TCOD_path_t path) + int TCOD_dijkstra_size(TCOD_dijkstra_t dijkstra) + @Py + path_size(path) + dijkstra_size(dijkstra) + @C# + int TCODPath::size() + int TCODDijkstra::size() + @Param path, dijkstra In the C version, the path handler returned by a creation function. + */ + int size() const; + + /** + @PageName path_read + @FuncTitle Read the path cells' coordinates + @FuncDesc You can get the coordinates of each point along the path : + @Cpp + void TCODPath::get(int index, int *x, int *y) const + void TCODDijkstra::get(int index, int *x, int *y) const + @C + void TCOD_path_get(TCOD_path_t path, int index, int *x, int *y) + void TCOD_dijkstra_get(TCOD_dijkstra_t dijkstra, int index, int *x, int *y) + @Py + path_get(path, index) # returns x,y + dijkstra_get(dijkstra, index) # returns x,y + @C# + int TCODPath::size() + int TCODDijkstra::size() + @Param path, dijkstra In the C version, the path handler returned by a creation function. + @Param index Step number. + 0 <= index < path size + @Param x,y Address of the variables receiving the coordinates of the point. + @CppEx + for (int i=0; i < path->size(); i++ ) { + int x,y; + path->get(i,&x,&y); + printf ("Astar coord : %d %d\n", x,y ); + } + for (int i=0; i < dijkstra->size(); i++ ) { + int x,y; + dijkstra->get(i,&x,&y); + printf ("Dijkstra coord : %d %d\n", x,y ); + } + @CEx + int i; + for (i=0; i < TCOD_path_size(path); i++ ) { + int x,y; + TCOD_path_get(path,i,&x,&y); + printf ("Astar coord : %d %d\n", x,y ); + } + for (i=0; i < TCOD_dijkstra_size(dijkstra); i++ ) { + int x,y; + TCOD_dijkstra_get(dijkstra,i,&x,&y); + printf ("Dijsktra coord : %d %d\n", x,y ); + } + @PyEx + for i in range (libtcod.path_size(path)) : + x,y=libtcod.path_get(path,i) + print 'Astar coord : ',x,y + for i in range (libtcod.dijkstra_size(dijkstra)) : + x,y=libtcod.dijkstra_get(dijkstra,i) + print 'Dijkstra coord : ',x,y + */ + void get(int index, int *x, int *y) const; + + /** + @PageName path_read + @FuncTitle Checking if the path is empty + @FuncDesc If you want a creature to follow the path, a more convenient way is to walk the path : + You know when you reached destination when the path is empty : + @Cpp + bool TCODPath::isEmpty() const + bool TCODDijkstra::isEmpty() const + @C + bool TCOD_path_is_empty(TCOD_path_t path) + bool TCOD_dijkstra_is_empty(TCOD_dijkstra_t dijkstra) + @Py + path_is_empty(path) + dijkstra_is_empty(dijkstra) + @C# + bool TCODPath::isEmpty() + bool TCODDijkstra::isEmpty() + @Param path, dijkstra In the C version, the path handler returned by a creation function. + */ + bool isEmpty() const; + + /** + @PageName path_read + @FuncTitle Walking the path + @FuncDesc You can walk the path and go to the next step with : + Note that walking the path consume one step (and decrease the path size by one). The function returns false if recalculateWhenNeeded is false and the next cell on the path is no longer walkable, or if recalculateWhenNeeded is true, the next cell on the path is no longer walkable and no other path has been found. Also note that recalculateWhenNeeded only applies to A*. + @Cpp + bool TCODPath::walk(int *x, int *y, bool recalculateWhenNeeded) + bool TCODDijkstra::walk(int *x, int *y) + @C + bool TCOD_path_walk(TCOD_path_t path, int *x, int *y, bool recalculate_when_needed) + bool TCOD_dijkstra_walk(TCOD_dijkstra_t dijkstra, int *x, int *y) + @Py + path_walk(TCOD_path_t path, recalculate_when_needed) # returns x,y or None,None if no path + dijkstra_walk(TCOD_dijkstra_t dijkstra) + @C# + bool TCODPath::walk(ref int x, ref int y, bool recalculateWhenNeeded) + bool TCODDijkstra::walk(ref int x, ref int y) + @Param path, dijkstra In the C version, the path handler returned by a creation function. + @Param x,y Address of the variables receiving the coordinates of the next point. + @Param recalculateWhenNeeded If the next point is no longer walkable (another creature may be in the way), recalculate a new path and walk it. + @CppEx + while (! path->isEmpty()) { + int x,y; + if (path->walk(&x,&y,true)) { + printf ("Astar coord: %d %d\n",x,y ); + } else { + printf ("I'm stuck!\n" ); + break; + } + } + while (! dijkstra->isEmpty()) { + int x,y; + if (dijkstra->walk(&x,&y)) { + printf ("Dijkstra coord: %d %d\n",x,y ); + } else { + printf ("I'm stuck!\n" ); + break; + } + } + @CEx + while (! TCOD_path_is_empty(path)) { + int x,y; + if (TCOD_path_walk(path,&x,&y,true)) { + printf ("Astar coord: %d %d\n",x,y ); + } else { + printf ("I'm stuck!\n" ); + break; + } + } + while (! TCOD_dijkstra_is_empty(dijkstra)) { + int x,y; + if (TCOD_dijkstra_walk(dijkstra,&x,&y)) { + printf ("Dijkstra coord: %d %d\n",x,y ); + } else { + printf ("I'm stuck!\n" ); + break; + } + } + @PyEx + while not libtcod.path_is_empty(path)) : + x,y=libtcod.path_walk(path,True) + if not x is None : + print 'Astar coord: ',x,y + else : + print "I'm stuck!" + break + while not libtcod.dijkstra_is_empty(dijkstra)) : + x,y=libtcod.dijkstra_walk(dijkstra,True) + if not x is None : + print 'Dijkstra coord: ',x,y + else : + print "I'm stuck!" + break + */ + bool walk(int *x, int *y, bool recalculateWhenNeeded); + +protected : + friend float TCOD_path_func(int xFrom, int yFrom, int xTo,int yTo, void *data); + TCOD_path_t data; + struct WrapperData { + void *userData; + const ITCODPathCallback *listener; + } cppData; +}; + +//Dijkstra kit +class TCODLIB_API TCODDijkstra { + public: + TCODDijkstra (TCODMap *map, float diagonalCost=1.41f); + TCODDijkstra (int width, int height, const ITCODPathCallback *listener, void *userData, float diagonalCost=1.41f); + ~TCODDijkstra (void); + /** + @PageName path_compute + @FuncTitle Computing a Dijkstra grid + @FuncDesc In case of Dijkstra, this works in a slightly different way. In order to be able to compute a path, Dijkstra must first analyse the distances from the selected root (origin) node to all other nodes: + @Cpp void TCODDijkstra::compute(int rootX, int rootY) + @C void TCOD_dijkstra_compute(TCOD_dijkstra_t dijkstra, int root_x, int root_y) + @Py dijkstra_compute(dijkstra, root_x, root_y) + @C# void TCODDijkstra::compute(int rootX, int rootY) + @Param dijkstra In the C version, the path handler returned by a creation function. + @Param root_x,root_y Coordinates of the root node (origin) of the path. + The coordinates should be inside the map, at a walkable position. Otherwise, the function's behaviour will be undefined. + */ + void compute (int rootX, int rootY); + + /** + @PageName path_compute + @FuncTitle Computing a path from a Dijkstra grid + @FuncDesc After the map is analysed and all the distances from the root node are known, an unlimited number of paths can be set, all originating at the root node, using: + The path setting function will return true if there's a path from the root node to the destination node. Otherwise, it will return false. + @Cpp bool TCODDijkstra::setPath(int toX, int toY) + @C bool TCOD_dijkstra_path_set(TCOD_dijkstra_t dijkstra, int to_x, int to_y) + @Py dijkstra_path_set(dijkstra, to_x, to_y) + @C# bool TCODDijkstra::setPath(int toX, int toY) + @Param dijkstra In the C version, the path handler returned by a creation function. + @Param to_x,to_y Coordinates of the destination node of the path. + @CppEx + TCODMap *myMap = new TCODMap(50,50); + TCODDijkstra *dijkstra = new TCODDijkstra(myMap); // allocate the path + dijkstra->compute(25,25); // calculate distance from 25,25 to all other nodes + dijkstra->setPath(5,5); // calculate a path to node 5,5 + dijkstra->setPath(45,45); //calculate another path from the same origin + @CEx + TCOD_map_t my_map=TCOD_map_new(50,50); + TCOD_dijkstra_t dijkstra = TCOD_dijkstra_new(my_map); + TCOD_dijkstra_compute(dijkstra,25,25); + TCOD_dijkstra_path_set(dijkstra,5,5); + TCOD_dijkstra_path_set(dijkstra,45,45); + @PyEx + my_map=libtcod.map_new(50,50) + dijkstra = libtcod.dijkstra_new(my_map) + libtcod.dijkstra_compute(dijkstra,25,25) + libtcod.dijkstra_path_set(dijkstra,5,5) + libtcod.dijkstra_path_set(dijkstra,45,45) + */ + bool setPath (int toX, int toY); + + /** + @PageName path_read + @FuncTitle Getting the distance from a cell to the root node + @FuncDesc You can get the distance of any set of coordinates from the root node: + Note that if the coordinates x,y are outside of the map or are a non-walkable position, the function will return -1.0f. This functionality is only available for Dijkstra's algorithm. + @Cpp float TCODDijkstra::getDistance(int x, int y) + @C float TCOD_dijkstra_get_distance(TCOD_dijkstra_t dijkstra, int x, int y) + @Py dijkstra_get_distance(dijkstra, x, y) + @C# float TCODDijkstra::getDistance(int x, int y) + @Param dijkstra In the C version, the path handler returned by a creation function. + @Param x,y The coordinates whose distance from the root node are to be checked + */ + float getDistance (int x, int y); + bool walk (int *x, int *y); + bool isEmpty() const; + void reverse(); + int size() const; + void get(int index, int *x, int *y) const; + private: + TCOD_dijkstra_t data; + struct WrapperData { + void *userData; + const ITCODPathCallback *listener; + } cppData; +}; + +#endif diff --git a/tcod_sys/libtcod/src/path_c.c b/tcod_sys/libtcod/src/libtcod/path_c.c similarity index 96% rename from tcod_sys/libtcod/src/path_c.c rename to tcod_sys/libtcod/src/libtcod/path_c.c index d1142d5c3..254dbb6c8 100644 --- a/tcod_sys/libtcod/src/path_c.c +++ b/tcod_sys/libtcod/src/libtcod/path_c.c @@ -1,692 +1,692 @@ -/* -* libtcod -* Copyright (c) 2008-2018 Jice & Mingos & rmtew -* All rights reserved. -* -* Redistribution and use in source and binary forms, with or without -* modification, are permitted provided that the following conditions are met: -* * Redistributions of source code must retain the above copyright -* notice, this list of conditions and the following disclaimer. -* * Redistributions in binary form must reproduce the above copyright -* notice, this list of conditions and the following disclaimer in the -* documentation and/or other materials provided with the distribution. -* * The name of Jice or Mingos may not be used to endorse or promote -* products derived from this software without specific prior written -* permission. -* -* THIS SOFTWARE IS PROVIDED BY JICE, MINGOS AND RMTEW ``AS IS'' AND ANY -* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED -* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE -* DISCLAIMED. IN NO EVENT SHALL JICE, MINGOS OR RMTEW BE LIABLE FOR ANY -* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES -* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; -* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND -* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS -* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. -*/ -#include - -#include -#include -#include -#include - -#include -enum { NORTH_WEST,NORTH, NORTH_EAST, WEST,NONE,EAST, SOUTH_WEST,SOUTH,SOUTH_EAST }; -typedef unsigned char dir_t; - -/* convert dir_t to dx,dy */ -static int dirx[]={-1,0,1,-1,0,1,-1,0,1}; -static int diry[]={-1,-1,-1,0,0,0,1,1,1}; -static int invdir[] = {SOUTH_EAST,SOUTH,SOUTH_WEST,EAST,NONE,WEST,NORTH_EAST,NORTH,NORTH_WEST}; - -typedef struct { - int ox,oy; /* coordinates of the creature position */ - int dx,dy; /* coordinates of the creature's destination */ - TCOD_list_t path; /* list of dir_t to follow the path */ - int w,h; /* map size */ - float *grid; /* wxh djikstra distance grid (covered distance) */ - float *heur; /* wxh A* score grid (covered distance + estimated remaining distance) */ - dir_t *prev; /* wxh 'previous' grid : direction to the previous cell */ - float diagonalCost; - TCOD_list_t heap; /* min_heap used in the algorithm. stores the offset in grid/heur (offset=x+y*w) */ - TCOD_map_t map; - TCOD_path_func_t func; - void *user_data; -} TCOD_path_data_t; - -/* small layer on top of TCOD_list_t to implement a binary heap (min_heap) */ -static void heap_sift_down(TCOD_path_data_t *path, TCOD_list_t heap) { - /* sift-down : move the first element of the heap down to its right place */ - int cur=0; - int end = TCOD_list_size(heap)-1; - int child=1; - uintptr_t *array=(uintptr_t *)TCOD_list_begin(heap); - while ( child <= end ) { - int toSwap=cur; - uintptr_t off_cur=array[cur]; - float cur_dist=path->heur[off_cur]; - float swapValue=cur_dist; - uintptr_t off_child=array[child]; - float child_dist=path->heur[off_child]; - if ( child_dist < cur_dist ) { - toSwap=child; - swapValue=child_dist; - } - if ( child < end ) { - /* get the min between child and child+1 */ - uintptr_t off_child2=array[child+1]; - float child2_dist=path->heur[off_child2]; - if ( swapValue > child2_dist ) { - toSwap=child+1; - swapValue=child2_dist; - } - } - if ( toSwap != cur ) { - /* get down one level */ - uintptr_t tmp = array[toSwap]; - array[toSwap]=array[cur]; - array[cur]=tmp; - cur=toSwap; - } else return; - child=cur*2+1; - } -} - -static void heap_sift_up(TCOD_path_data_t *path, TCOD_list_t heap) { - /* sift-up : move the last element of the heap up to its right place */ - int end = TCOD_list_size(heap)-1; - int child=end; - uintptr_t *array=(uintptr_t *)TCOD_list_begin(heap); - while ( child > 0 ) { - uintptr_t off_child=array[child]; - float child_dist=path->heur[off_child]; - int parent = (child-1)/2; - uintptr_t off_parent=array[parent]; - float parent_dist=path->heur[off_parent]; - if ( parent_dist > child_dist ) { - /* get up one level */ - uintptr_t tmp = array[child]; - array[child]=array[parent]; - array[parent]=tmp; - child=parent; - } else return; - } -} - -/* add a coordinate pair in the heap so that the heap root always contains the minimum A* score */ -static void heap_add(TCOD_path_data_t *path, TCOD_list_t heap, int x, int y) { - /* append the new value to the end of the heap */ - uintptr_t off=x+y*path->w; - TCOD_list_push(heap,(void *)off); - /* bubble the value up to its real position */ - heap_sift_up(path,heap); -} - -/* get the coordinate pair with the minimum A* score from the heap */ -static uint32_t heap_get(TCOD_path_data_t *path,TCOD_list_t heap) { - /* return the first value of the heap (minimum score) */ - uintptr_t *array=(uintptr_t *)TCOD_list_begin(heap); - int end=TCOD_list_size(heap)-1; - uint32_t off=(uint32_t)(array[0]); - /* take the last element and put it at first position (heap root) */ - array[0] = array[end]; - TCOD_list_pop(heap); - /* and bubble it down to its real position */ - heap_sift_down(path,heap); - return off; -} - -/* this is the slow part, when we change the heuristic of a cell already in the heap */ -static void heap_reorder(TCOD_path_data_t *path, uint32_t offset) { - uintptr_t *array=(uintptr_t *)TCOD_list_begin(path->heap); - uintptr_t *end=(uintptr_t *)TCOD_list_end(path->heap); - uintptr_t *cur=array; - uintptr_t off_idx=0; - float value; - int idx=0; - int heap_size=TCOD_list_size(path->heap); - /* find the node corresponding to offset ... SLOW !! */ - while (cur != end) { - if (*cur == offset ) break; - cur++;idx++; - } - if ( cur == end ) return; - off_idx=array[idx]; - value=path->heur[off_idx]; - if ( idx > 0 ) { - int parent=(idx-1)/2; - /* compare to its parent */ - uintptr_t off_parent=array[parent]; - float parent_value=path->heur[off_parent]; - if (value < parent_value) { - /* smaller. bubble it up */ - while ( idx > 0 && value < parent_value ) { - /* swap with parent */ - array[parent]=off_idx; - array[idx] = off_parent; - idx=parent; - if ( idx > 0 ) { - parent=(idx-1)/2; - off_parent=array[parent]; - parent_value=path->heur[off_parent]; - } - } - return; - } - } - /* compare to its sons */ - while ( idx*2+1 < heap_size ) { - int child=idx*2+1; - uintptr_t off_child=array[child]; - int toSwap=idx; - int child2; - float swapValue=value; - if ( path->heur[off_child] < value ) { - /* swap with son1 ? */ - toSwap=child; - swapValue=path->heur[off_child]; - } - child2 = child+1; - if ( child2 < heap_size ) { - uintptr_t off_child2=array[child2]; - if ( path->heur[off_child2] < swapValue) { - /* swap with son2 */ - toSwap=child2; - } - } - if ( toSwap != idx ) { - /* bigger. bubble it down */ - uintptr_t tmp = array[toSwap]; - array[toSwap]=array[idx]; - array[idx] = tmp; - idx=toSwap; - } else return; - } -} - - -/* private functions */ -static void TCOD_path_push_cell(TCOD_path_data_t *path, int x, int y); -static void TCOD_path_get_cell(TCOD_path_data_t *path, int *x, int *y, float *distance); -static void TCOD_path_set_cells(TCOD_path_data_t *path); -static float TCOD_path_walk_cost(TCOD_path_data_t *path, int xFrom, int yFrom, int xTo, int yTo); - -static TCOD_path_data_t *TCOD_path_new_intern(int w, int h) { - TCOD_path_data_t *path=(TCOD_path_data_t *)calloc(sizeof(TCOD_path_data_t),1); - path->w=w; - path->h=h; - path->grid=(float *)calloc(sizeof(float),w*h); - path->heur=(float *)calloc(sizeof(float),w*h); - path->prev=(dir_t *)calloc(sizeof(dir_t),w*h); - if (! path->grid || ! path->heur || ! path->prev ) { - TCOD_fatal("Fatal error : path finding module cannot allocate djikstra grids (size %dx%d)\n",w,h); - exit(1); - } - path->path=TCOD_list_new(); - path->heap=TCOD_list_new(); - return path; -} - -TCOD_path_t TCOD_path_new_using_map(TCOD_map_t map, float diagonalCost) { - TCOD_path_data_t *path; - TCOD_IFNOT(map != NULL) return NULL; - path=TCOD_path_new_intern(TCOD_map_get_width(map),TCOD_map_get_height(map)); - path->map=map; - path->diagonalCost=diagonalCost; - return (TCOD_path_t)path; -} - -TCOD_path_t TCOD_path_new_using_function(int map_width, int map_height, TCOD_path_func_t func, void *user_data, float diagonalCost) { - TCOD_path_data_t *path; - TCOD_IFNOT(func != NULL && map_width > 0 && map_height > 0) return NULL; - path=TCOD_path_new_intern(map_width,map_height); - path->func=func; - path->user_data=user_data; - path->diagonalCost=diagonalCost; - return (TCOD_path_t)path; -} - -bool TCOD_path_compute(TCOD_path_t p, int ox,int oy, int dx, int dy) { - TCOD_path_data_t *path=(TCOD_path_data_t *)p; - TCOD_IFNOT(p != NULL) return false; - path->ox=ox; - path->oy=oy; - path->dx=dx; - path->dy=dy; - TCOD_list_clear(path->path); - TCOD_list_clear(path->heap); - if ( ox == dx && oy == dy ) return true; /* trivial case */ - /* check that origin and destination are inside the map */ - TCOD_IFNOT((unsigned)ox < (unsigned)path->w && (unsigned)oy < (unsigned)path->h) return false; - TCOD_IFNOT((unsigned)dx < (unsigned)path->w && (unsigned)dy < (unsigned)path->h) return false; - /* initialize djikstra grids */ - memset(path->grid,0,sizeof(float)*path->w*path->h); - memset(path->prev,NONE,sizeof(dir_t)*path->w*path->h); - path->heur[ ox + oy * path->w ] = 1.0f; /* anything != 0 */ - TCOD_path_push_cell(path,ox,oy); /* put the origin cell as a bootstrap */ - /* fill the djikstra grid until we reach dx,dy */ - TCOD_path_set_cells(path); - if ( path->grid[dx + dy * path->w] == 0 ) return false; /* no path found */ - /* there is a path. retrieve it */ - do { - /* walk from destination to origin, using the 'prev' array */ - int step=path->prev[ dx + dy * path->w ]; - TCOD_list_push(path->path,(void *)(uintptr_t)step); - dx -= dirx[step]; - dy -= diry[step]; - } while ( dx != ox || dy != oy ); - return true; -} - -void TCOD_path_reverse(TCOD_path_t p) { - int tmp,i; - TCOD_path_data_t *path=(TCOD_path_data_t *)p; - TCOD_IFNOT(p != NULL) return ; - tmp=path->ox; - path->ox=path->dx; - path->dx=tmp; - tmp=path->oy; - path->oy=path->dy; - path->dy=tmp; - for (i=0; i < TCOD_list_size(path->path); i++) { - int d=(int)(uintptr_t)TCOD_list_get(path->path,i); - d = invdir[d]; - TCOD_list_set(path->path,(void *)(uintptr_t)d,i); - } -} - -bool TCOD_path_walk(TCOD_path_t p, int *x, int *y, bool recalculate_when_needed) { - int newx,newy; - int d; - TCOD_path_data_t *path=(TCOD_path_data_t *)p; - TCOD_IFNOT(p != NULL) return false; - if ( TCOD_path_is_empty(path) ) return false; - d=(int)(uintptr_t)TCOD_list_pop(path->path); - newx=path->ox + dirx[d]; - newy=path->oy + diry[d]; - /* check if the path is still valid */ - if ( TCOD_path_walk_cost(path,path->ox,path->oy,newx,newy) <= 0.0f ) { - /* path is blocked */ - if (! recalculate_when_needed ) return false; /* don't walk */ - /* calculate a new path */ - if (! TCOD_path_compute(path, path->ox,path->oy, path->dx,path->dy) ) return false ; /* cannot find a new path */ - return TCOD_path_walk(p,x,y,true); /* walk along the new path */ - } - if ( x ) *x=newx; - if ( y ) *y=newy; - path->ox=newx; - path->oy=newy; - return true; -} - -bool TCOD_path_is_empty(TCOD_path_t p) { - TCOD_path_data_t *path=(TCOD_path_data_t *)p; - TCOD_IFNOT(p != NULL) return true; - return TCOD_list_is_empty(path->path); -} - -int TCOD_path_size(TCOD_path_t p) { - TCOD_path_data_t *path=(TCOD_path_data_t *)p; - TCOD_IFNOT(p != NULL) return 0; - return TCOD_list_size(path->path); -} - -void TCOD_path_get(TCOD_path_t p, int index, int *x, int *y) { - int pos; - TCOD_path_data_t *path=(TCOD_path_data_t *)p; - TCOD_IFNOT(p != NULL) return; - if ( x ) *x=path->ox; - if ( y ) *y=path->oy; - pos = TCOD_list_size(path->path)-1; - do { - int step=(int)(uintptr_t)TCOD_list_get(path->path,pos); - if ( x ) *x += dirx[step]; - if ( y ) *y += diry[step]; - pos--;index--; - } while (index >= 0); -} - -void TCOD_path_delete(TCOD_path_t p) { - TCOD_path_data_t *path=(TCOD_path_data_t *)p; - TCOD_IFNOT(p != NULL) return; - if ( path->grid ) free(path->grid); - if ( path->heur ) free(path->heur); - if ( path->prev ) free(path->prev); - if ( path->path ) TCOD_list_delete(path->path); - if ( path->heap ) TCOD_list_delete(path->heap); - free(path); -} - -/* private stuff */ -/* add a new unvisited cells to the cells-to-treat list - * the list is in fact a min_heap. Cell at index i has its sons at 2*i+1 and 2*i+2 - */ -static void TCOD_path_push_cell(TCOD_path_data_t *path, int x, int y) { - heap_add(path,path->heap,x,y); -} - -/* get the best cell from the heap */ -static void TCOD_path_get_cell(TCOD_path_data_t *path, int *x, int *y, float *distance) { - uint32_t offset = heap_get(path,path->heap); - *x=(offset % path->w); - *y=(offset / path->w); - *distance=path->grid[offset]; -} -/* fill the grid, starting from the origin until we reach the destination */ -static void TCOD_path_set_cells(TCOD_path_data_t *path) { - while ( path->grid[path->dx + path->dy * path->w ] == 0 && ! TCOD_list_is_empty(path->heap) ) { - - int x,y,i,imax; - float distance; - TCOD_path_get_cell(path,&x,&y,&distance); - imax= ( path->diagonalCost == 0.0f ? 4 : 8) ; - for (i=0; i < imax; i++ ) { - /* convert i to dx,dy */ - static int idirx[]={0,-1,1,0,-1,1,-1,1}; - static int idiry[]={-1,0,0,1,-1,-1,1,1}; - /* convert i to direction */ - static dir_t prevdirs[] = { - NORTH, WEST, EAST, SOUTH, NORTH_WEST, NORTH_EAST,SOUTH_WEST,SOUTH_EAST - }; - /* coordinate of the adjacent cell */ - int cx=x+idirx[i]; - int cy=y+idiry[i]; - if ( cx >= 0 && cy >= 0 && cx < path->w && cy < path->h ) { - float walk_cost = TCOD_path_walk_cost(path,x,y,cx,cy); - if ( walk_cost > 0.0f ) { - /* in of the map and walkable */ - float covered=distance + walk_cost * (i>=4 ? path->diagonalCost : 1.0f); - float previousCovered = path->grid[cx + cy * path->w ]; - if ( previousCovered == 0 ) { - /* put a new cell in the heap */ - int offset=cx + cy * path->w; - /* A* heuristic : remaining distance */ - float remaining=(float)sqrt((cx-path->dx)*(cx-path->dx)+(cy-path->dy)*(cy-path->dy)); - path->grid[ offset ] = covered; - path->heur[ offset ] = covered + remaining; - path->prev[ offset ] = prevdirs[i]; - TCOD_path_push_cell(path,cx,cy); - } else if ( previousCovered > covered ) { - /* we found a better path to a cell already in the heap */ - int offset=cx + cy * path->w; - path->grid[ offset ] = covered; - path->heur[ offset ] -= (previousCovered - covered); /* fix the A* score */ - path->prev[ offset ] = prevdirs[i]; - /* reorder the heap */ - heap_reorder(path,offset); - } - } - } - } - } -} - -/* check if a cell is walkable (from the pathfinder point of view) */ -static float TCOD_path_walk_cost(TCOD_path_data_t *path, int xFrom, int yFrom, int xTo, int yTo) { - if ( path->map ) return TCOD_map_is_walkable(path->map,xTo,yTo) ? 1.0f : 0.0f; - return path->func(xFrom,yFrom,xTo,yTo,path->user_data); -} - -void TCOD_path_get_origin(TCOD_path_t p, int *x, int *y) { - TCOD_path_data_t *path=(TCOD_path_data_t *)p; - TCOD_IFNOT(p != NULL) return; - if ( x ) *x=path->ox; - if ( y ) *y=path->oy; -} - -void TCOD_path_get_destination(TCOD_path_t p, int *x, int *y) { - TCOD_path_data_t *path=(TCOD_path_data_t *)p; - TCOD_IFNOT(p != NULL) return; - if ( x ) *x=path->dx; - if ( y ) *y=path->dy; -} - -/* ------------------------------------------------------- * - * Dijkstra * - * written by Mingos * - * ----------------- * - * A floodfill-like algo that will calculate all distances * - * to all accessible cells (nodes) from a given root node. * - * ------------------------------------------------------- */ - -/* Dijkstra data structure */ -typedef struct { - int diagonal_cost; - int width, height, nodes_max; - TCOD_map_t map; /* a TCODMap with walkability data */ - TCOD_path_func_t func; - void *user_data; - unsigned int * distances; /* distances grid */ - unsigned int * nodes; /* the processed nodes */ - TCOD_list_t path; -} dijkstra_t; - -/* create a Dijkstra object */ -TCOD_dijkstra_t TCOD_dijkstra_new (TCOD_map_t map, float diagonalCost) { - dijkstra_t * data ; - TCOD_IFNOT(map != NULL) return NULL; - data = malloc(sizeof(dijkstra_t)); - data->map = map; - data->func = NULL; - data->user_data=NULL; - data->distances = malloc(TCOD_map_get_nb_cells(data->map)*sizeof(int)); - data->nodes = malloc(TCOD_map_get_nb_cells(data->map)*sizeof(int)); - data->diagonal_cost = (int)((diagonalCost * 100.0f)+0.1f); /* because (int)(1.41f*100.0f) == 140!!! */ - data->width = TCOD_map_get_width(data->map); - data->height = TCOD_map_get_height(data->map); - data->nodes_max = TCOD_map_get_nb_cells(data->map); - data->path = TCOD_list_new(); - return (TCOD_dijkstra_t)data; -} - -TCOD_dijkstra_t TCOD_dijkstra_new_using_function(int map_width, int map_height, TCOD_path_func_t func, void *user_data, float diagonalCost) { - dijkstra_t * data; - TCOD_IFNOT(func != NULL && map_width > 0 && map_height > 0) return NULL; - data = malloc(sizeof(dijkstra_t)); - data->map = NULL; - data->func = func; - data->user_data=user_data; - data->distances = malloc(map_width*map_height*sizeof(int)*4); - data->nodes = malloc(map_width*map_height*sizeof(int)*4); - data->diagonal_cost = (int)((diagonalCost * 100.0f)+0.1f); /* because (int)(1.41f*100.0f) == 140!!! */ - data->width = map_width; - data->height = map_height; - data->nodes_max = map_width*map_height; - data->path = TCOD_list_new(); - return (TCOD_dijkstra_t)data; -} - - -/* compute a Dijkstra grid */ -void TCOD_dijkstra_compute (TCOD_dijkstra_t dijkstra, int root_x, int root_y) { - dijkstra_t * data = (dijkstra_t*)dijkstra; - /* map size data */ - unsigned int mx = data->width; - unsigned int my = data->height; - unsigned int mmax = data->nodes_max; - /* encode the root coords in one integer */ - unsigned int root = (root_y * mx) + root_x; - /* some stuff to walk through the nodes table */ - unsigned int index = 0; /* the index of the first node in queue */ - unsigned int last_index = 1; /* total nb of registered queue indices */ - unsigned int * nodes = data->nodes; /* table of nodes to which the indices above apply */ - /* ok, here's the order of node processing: W, S, E, N, NW, NE, SE, SW */ - static int dx[8] = { -1, 0, 1, 0, -1, 1, 1, -1 }; - static int dy[8] = { 0, -1, 0, 1, -1, -1, 1, 1 }; - /* and distances for each index */ - int dd[8] = { 100, 100, 100, 100, data->diagonal_cost, data->diagonal_cost, data->diagonal_cost, data->diagonal_cost }; - /* if diagonal_cost is 0, disallow diagonal moves */ - int imax = (data->diagonal_cost == 0 ? 4 : 8); - /* aight, now set the distances table and set everything to infinity */ - unsigned int * distances = data->distances; - TCOD_IFNOT(data != NULL) return; - TCOD_IFNOT((unsigned)root_x < (unsigned)mx && (unsigned)root_y < (unsigned)my) return; - memset(distances,0xFFFFFFFF,mmax*sizeof(int)); - memset(nodes,0xFFFFFFFF,mmax*sizeof(int)); - /* data for root node is known... */ - distances[root] = 0; - nodes[index] = root; /*set starting note to root */ - /* and the loop */ - do { - unsigned int x, y; - int i; - if (nodes[index] == 0xFFFFFFFF) { - continue; - } - - /* coordinates of currently processed node */ - x = nodes[index] % mx; - y = nodes[index] / mx; - - /* check adjacent nodes */ - for(i=0;imap ) dt += dd[i]; - else { - /* distance given by the user callback */ - userDist=data->func(x,y,tx,ty,data->user_data); - dt += (unsigned int)(userDist*dd[i]); - } - /* ..., encode coordinates, ... */ - new_node = (ty * mx) + tx; - /* and check if the node's eligible for queuing */ - if (distances[new_node] > dt) { - unsigned int j; - /* if not walkable, don't process it */ - if (data->map && !TCOD_map_is_walkable(data->map,tx,ty)) continue; - else if ( data->func && userDist <= 0.0f ) continue; - distances[new_node] = dt; /* set processed node's distance */ - /* place the processed node in the queue before the last queued node with greater distance */ - j = last_index - 1; - while (distances[nodes[j]] >= distances[new_node]) { - /* this ensures that if the node has been queued previously, but with a higher distance, it's removed */ - if (nodes[j] == new_node) { - int k = j; - while ((unsigned)k <= last_index) { - nodes[k] = nodes[k+1]; - k++; - } - last_index--; - } - else nodes[j+1] = nodes[j]; - j--; - } - last_index++; /* increase total indices count */ - nodes[j+1] = new_node; /* and finally put the node where it belongs in the queue */ - } - } - } - } while (mmax > ++index); -} - -/* get distance from source */ -float TCOD_dijkstra_get_distance (TCOD_dijkstra_t dijkstra, int x, int y) { - dijkstra_t * data = (dijkstra_t*)dijkstra; - unsigned int * distances; - TCOD_IFNOT(data != NULL) return -1.0f; - TCOD_IFNOT ((unsigned)x < (unsigned)data->width && (unsigned)y < (unsigned)data->height) return -1.0f; - if (data->distances[(y*data->width)+x] == 0xFFFFFFFF) return -1.0f; - distances = data->distances; - return ((float)distances[(y * data->width) + x] * 0.01f); -} - -unsigned int dijkstra_get_int_distance (dijkstra_t * data, int x, int y) { - unsigned int * distances = data->distances; - return distances[(y * data->width) + x]; -} - -/* create a path */ -bool TCOD_dijkstra_path_set (TCOD_dijkstra_t dijkstra, int x, int y) { - dijkstra_t * data = (dijkstra_t*)dijkstra; - int px = x, py = y; - static int dx[9] = { -1, 0, 1, 0, -1, 1, 1, -1, 0 }; - static int dy[9] = { 0, -1, 0, 1, -1, -1, 1, 1, 0 }; - unsigned int distances[8] = {0}; - int lowest_index; - int imax = (data->diagonal_cost == 0 ? 4 : 8); - TCOD_IFNOT(data != NULL) return false; - TCOD_IFNOT((unsigned)x < (unsigned)data->width && (unsigned)y < (unsigned)data->height) return false; - /* check that destination is reachable */ - if ( dijkstra_get_int_distance(data,x,y) == 0xFFFFFFFF ) return false; - TCOD_list_clear(data->path); - do { - unsigned int lowest; - int i; - TCOD_list_push(data->path,(const void*)(uintptr_t)((py * data->width) + px)); - for(i=0;iwidth && (unsigned)cy < (unsigned)data->height) distances[i] = dijkstra_get_int_distance(data,cx,cy); - else distances[i] = 0xFFFFFFFF; - } - lowest = dijkstra_get_int_distance(data,px,py); - lowest_index = 8; - for(i=0;ipath); - return true; -} - -void TCOD_dijkstra_reverse(TCOD_dijkstra_t dijkstra) { - dijkstra_t * data = (dijkstra_t*)dijkstra; - TCOD_IFNOT(data != NULL) return; - TCOD_list_reverse(data->path); -} - -/* walk the path */ -bool TCOD_dijkstra_path_walk (TCOD_dijkstra_t dijkstra, int *x, int *y) { - dijkstra_t * data = (dijkstra_t*)dijkstra; - TCOD_IFNOT(data != NULL) return false; - if (TCOD_list_is_empty(data->path)) return false; - else { - unsigned int node = (unsigned int)(uintptr_t)TCOD_list_pop(data->path); - if ( x ) *x = (int)(node % data->width); - if ( y ) *y = (int)(node / data->width); - } - return true; -} - -/* delete a Dijkstra object */ -void TCOD_dijkstra_delete (TCOD_dijkstra_t dijkstra) { - dijkstra_t * data = (dijkstra_t*)dijkstra; - TCOD_IFNOT(data != NULL) return; - if ( data->distances ) free(data->distances); - if ( data->nodes ) free(data->nodes); - if ( data->path ) TCOD_list_delete(data->path); - free(data); -} - -bool TCOD_dijkstra_is_empty(TCOD_dijkstra_t p) { - dijkstra_t * data = (dijkstra_t*)p; - TCOD_IFNOT(data != NULL) return true; - return TCOD_list_is_empty(data->path); -} - -int TCOD_dijkstra_size(TCOD_dijkstra_t p) { - dijkstra_t * data = (dijkstra_t*)p; - TCOD_IFNOT(data != NULL) return 0; - return TCOD_list_size(data->path); -} - -void TCOD_dijkstra_get(TCOD_dijkstra_t p, int index, int *x, int *y) { - dijkstra_t * data = (dijkstra_t*)p; - unsigned int node ; - TCOD_IFNOT(data != NULL) return; - node = (unsigned int)(uintptr_t)TCOD_list_get(data->path,TCOD_list_size(data->path)-index-1); - if ( x ) *x = (int)(node % data->width); - if ( y ) *y = (int)(node / data->width); -} +/* +* libtcod +* Copyright (c) 2008-2018 Jice & Mingos & rmtew +* All rights reserved. +* +* Redistribution and use in source and binary forms, with or without +* modification, are permitted provided that the following conditions are met: +* * Redistributions of source code must retain the above copyright +* notice, this list of conditions and the following disclaimer. +* * Redistributions in binary form must reproduce the above copyright +* notice, this list of conditions and the following disclaimer in the +* documentation and/or other materials provided with the distribution. +* * The name of Jice or Mingos may not be used to endorse or promote +* products derived from this software without specific prior written +* permission. +* +* THIS SOFTWARE IS PROVIDED BY JICE, MINGOS AND RMTEW ``AS IS'' AND ANY +* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED +* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE +* DISCLAIMED. IN NO EVENT SHALL JICE, MINGOS OR RMTEW BE LIABLE FOR ANY +* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES +* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; +* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND +* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS +* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +*/ +#include "path.h" + +#include +#include +#include +#include + +#include "libtcod_int.h" +enum { NORTH_WEST,NORTH, NORTH_EAST, WEST,NONE,EAST, SOUTH_WEST,SOUTH,SOUTH_EAST }; +typedef unsigned char dir_t; + +/* convert dir_t to dx,dy */ +static int dirx[]={-1,0,1,-1,0,1,-1,0,1}; +static int diry[]={-1,-1,-1,0,0,0,1,1,1}; +static int invdir[] = {SOUTH_EAST,SOUTH,SOUTH_WEST,EAST,NONE,WEST,NORTH_EAST,NORTH,NORTH_WEST}; + +typedef struct TCOD_Path { + int ox,oy; /* coordinates of the creature position */ + int dx,dy; /* coordinates of the creature's destination */ + TCOD_list_t path; /* list of dir_t to follow the path */ + int w,h; /* map size */ + float *grid; /* wxh djikstra distance grid (covered distance) */ + float *heur; /* wxh A* score grid (covered distance + estimated remaining distance) */ + dir_t *prev; /* wxh 'previous' grid : direction to the previous cell */ + float diagonalCost; + TCOD_list_t heap; /* min_heap used in the algorithm. stores the offset in grid/heur (offset=x+y*w) */ + TCOD_map_t map; + TCOD_path_func_t func; + void *user_data; +} TCOD_path_data_t; + +/* small layer on top of TCOD_list_t to implement a binary heap (min_heap) */ +static void heap_sift_down(TCOD_path_data_t *path, TCOD_list_t heap) { + /* sift-down : move the first element of the heap down to its right place */ + int cur=0; + int end = TCOD_list_size(heap)-1; + int child=1; + uintptr_t *array=(uintptr_t *)TCOD_list_begin(heap); + while ( child <= end ) { + int toSwap=cur; + uintptr_t off_cur=array[cur]; + float cur_dist=path->heur[off_cur]; + float swapValue=cur_dist; + uintptr_t off_child=array[child]; + float child_dist=path->heur[off_child]; + if ( child_dist < cur_dist ) { + toSwap=child; + swapValue=child_dist; + } + if ( child < end ) { + /* get the min between child and child+1 */ + uintptr_t off_child2=array[child+1]; + float child2_dist=path->heur[off_child2]; + if ( swapValue > child2_dist ) { + toSwap=child+1; + swapValue=child2_dist; + } + } + if ( toSwap != cur ) { + /* get down one level */ + uintptr_t tmp = array[toSwap]; + array[toSwap]=array[cur]; + array[cur]=tmp; + cur=toSwap; + } else return; + child=cur*2+1; + } +} + +static void heap_sift_up(TCOD_path_data_t *path, TCOD_list_t heap) { + /* sift-up : move the last element of the heap up to its right place */ + int end = TCOD_list_size(heap)-1; + int child=end; + uintptr_t *array=(uintptr_t *)TCOD_list_begin(heap); + while ( child > 0 ) { + uintptr_t off_child=array[child]; + float child_dist=path->heur[off_child]; + int parent = (child-1)/2; + uintptr_t off_parent=array[parent]; + float parent_dist=path->heur[off_parent]; + if ( parent_dist > child_dist ) { + /* get up one level */ + uintptr_t tmp = array[child]; + array[child]=array[parent]; + array[parent]=tmp; + child=parent; + } else return; + } +} + +/* add a coordinate pair in the heap so that the heap root always contains the minimum A* score */ +static void heap_add(TCOD_path_data_t *path, TCOD_list_t heap, int x, int y) { + /* append the new value to the end of the heap */ + uintptr_t off=x+y*path->w; + TCOD_list_push(heap,(void *)off); + /* bubble the value up to its real position */ + heap_sift_up(path,heap); +} + +/* get the coordinate pair with the minimum A* score from the heap */ +static uint32_t heap_get(TCOD_path_data_t *path,TCOD_list_t heap) { + /* return the first value of the heap (minimum score) */ + uintptr_t *array=(uintptr_t *)TCOD_list_begin(heap); + int end=TCOD_list_size(heap)-1; + uint32_t off=(uint32_t)(array[0]); + /* take the last element and put it at first position (heap root) */ + array[0] = array[end]; + TCOD_list_pop(heap); + /* and bubble it down to its real position */ + heap_sift_down(path,heap); + return off; +} + +/* this is the slow part, when we change the heuristic of a cell already in the heap */ +static void heap_reorder(TCOD_path_data_t *path, uint32_t offset) { + uintptr_t *array=(uintptr_t *)TCOD_list_begin(path->heap); + uintptr_t *end=(uintptr_t *)TCOD_list_end(path->heap); + uintptr_t *cur=array; + uintptr_t off_idx=0; + float value; + int idx=0; + int heap_size=TCOD_list_size(path->heap); + /* find the node corresponding to offset ... SLOW !! */ + while (cur != end) { + if (*cur == offset ) break; + cur++;idx++; + } + if ( cur == end ) return; + off_idx=array[idx]; + value=path->heur[off_idx]; + if ( idx > 0 ) { + int parent=(idx-1)/2; + /* compare to its parent */ + uintptr_t off_parent=array[parent]; + float parent_value=path->heur[off_parent]; + if (value < parent_value) { + /* smaller. bubble it up */ + while ( idx > 0 && value < parent_value ) { + /* swap with parent */ + array[parent]=off_idx; + array[idx] = off_parent; + idx=parent; + if ( idx > 0 ) { + parent=(idx-1)/2; + off_parent=array[parent]; + parent_value=path->heur[off_parent]; + } + } + return; + } + } + /* compare to its sons */ + while ( idx*2+1 < heap_size ) { + int child=idx*2+1; + uintptr_t off_child=array[child]; + int toSwap=idx; + int child2; + float swapValue=value; + if ( path->heur[off_child] < value ) { + /* swap with son1 ? */ + toSwap=child; + swapValue=path->heur[off_child]; + } + child2 = child+1; + if ( child2 < heap_size ) { + uintptr_t off_child2=array[child2]; + if ( path->heur[off_child2] < swapValue) { + /* swap with son2 */ + toSwap=child2; + } + } + if ( toSwap != idx ) { + /* bigger. bubble it down */ + uintptr_t tmp = array[toSwap]; + array[toSwap]=array[idx]; + array[idx] = tmp; + idx=toSwap; + } else return; + } +} + + +/* private functions */ +static void TCOD_path_push_cell(TCOD_path_data_t *path, int x, int y); +static void TCOD_path_get_cell(TCOD_path_data_t *path, int *x, int *y, float *distance); +static void TCOD_path_set_cells(TCOD_path_data_t *path); +static float TCOD_path_walk_cost(TCOD_path_data_t *path, int xFrom, int yFrom, int xTo, int yTo); + +static TCOD_path_data_t *TCOD_path_new_intern(int w, int h) { + TCOD_path_data_t *path=(TCOD_path_data_t *)calloc(sizeof(TCOD_path_data_t),1); + path->w=w; + path->h=h; + path->grid=(float *)calloc(sizeof(float),w*h); + path->heur=(float *)calloc(sizeof(float),w*h); + path->prev=(dir_t *)calloc(sizeof(dir_t),w*h); + if (! path->grid || ! path->heur || ! path->prev ) { + TCOD_fatal("Fatal error : path finding module cannot allocate djikstra grids (size %dx%d)\n",w,h); + exit(1); + } + path->path=TCOD_list_new(); + path->heap=TCOD_list_new(); + return path; +} + +TCOD_path_t TCOD_path_new_using_map(TCOD_map_t map, float diagonalCost) { + TCOD_path_data_t *path; + TCOD_IFNOT(map != NULL) return NULL; + path=TCOD_path_new_intern(TCOD_map_get_width(map),TCOD_map_get_height(map)); + path->map=map; + path->diagonalCost=diagonalCost; + return (TCOD_path_t)path; +} + +TCOD_path_t TCOD_path_new_using_function(int map_width, int map_height, TCOD_path_func_t func, void *user_data, float diagonalCost) { + TCOD_path_data_t *path; + TCOD_IFNOT(func != NULL && map_width > 0 && map_height > 0) return NULL; + path=TCOD_path_new_intern(map_width,map_height); + path->func=func; + path->user_data=user_data; + path->diagonalCost=diagonalCost; + return (TCOD_path_t)path; +} + +bool TCOD_path_compute(TCOD_path_t p, int ox,int oy, int dx, int dy) { + TCOD_path_data_t *path=(TCOD_path_data_t *)p; + TCOD_IFNOT(p != NULL) return false; + path->ox=ox; + path->oy=oy; + path->dx=dx; + path->dy=dy; + TCOD_list_clear(path->path); + TCOD_list_clear(path->heap); + if ( ox == dx && oy == dy ) return true; /* trivial case */ + /* check that origin and destination are inside the map */ + TCOD_IFNOT((unsigned)ox < (unsigned)path->w && (unsigned)oy < (unsigned)path->h) return false; + TCOD_IFNOT((unsigned)dx < (unsigned)path->w && (unsigned)dy < (unsigned)path->h) return false; + /* initialize djikstra grids */ + memset(path->grid,0,sizeof(float)*path->w*path->h); + memset(path->prev,NONE,sizeof(dir_t)*path->w*path->h); + path->heur[ ox + oy * path->w ] = 1.0f; /* anything != 0 */ + TCOD_path_push_cell(path,ox,oy); /* put the origin cell as a bootstrap */ + /* fill the djikstra grid until we reach dx,dy */ + TCOD_path_set_cells(path); + if ( path->grid[dx + dy * path->w] == 0 ) return false; /* no path found */ + /* there is a path. retrieve it */ + do { + /* walk from destination to origin, using the 'prev' array */ + int step=path->prev[ dx + dy * path->w ]; + TCOD_list_push(path->path,(void *)(uintptr_t)step); + dx -= dirx[step]; + dy -= diry[step]; + } while ( dx != ox || dy != oy ); + return true; +} + +void TCOD_path_reverse(TCOD_path_t p) { + int tmp,i; + TCOD_path_data_t *path=(TCOD_path_data_t *)p; + TCOD_IFNOT(p != NULL) return ; + tmp=path->ox; + path->ox=path->dx; + path->dx=tmp; + tmp=path->oy; + path->oy=path->dy; + path->dy=tmp; + for (i=0; i < TCOD_list_size(path->path); i++) { + int d=(int)(uintptr_t)TCOD_list_get(path->path,i); + d = invdir[d]; + TCOD_list_set(path->path,(void *)(uintptr_t)d,i); + } +} + +bool TCOD_path_walk(TCOD_path_t p, int *x, int *y, bool recalculate_when_needed) { + int newx,newy; + int d; + TCOD_path_data_t *path=(TCOD_path_data_t *)p; + TCOD_IFNOT(p != NULL) return false; + if ( TCOD_path_is_empty(path) ) return false; + d=(int)(uintptr_t)TCOD_list_pop(path->path); + newx=path->ox + dirx[d]; + newy=path->oy + diry[d]; + /* check if the path is still valid */ + if ( TCOD_path_walk_cost(path,path->ox,path->oy,newx,newy) <= 0.0f ) { + /* path is blocked */ + if (! recalculate_when_needed ) return false; /* don't walk */ + /* calculate a new path */ + if (! TCOD_path_compute(path, path->ox,path->oy, path->dx,path->dy) ) return false ; /* cannot find a new path */ + return TCOD_path_walk(p,x,y,true); /* walk along the new path */ + } + if ( x ) *x=newx; + if ( y ) *y=newy; + path->ox=newx; + path->oy=newy; + return true; +} + +bool TCOD_path_is_empty(TCOD_path_t p) { + TCOD_path_data_t *path=(TCOD_path_data_t *)p; + TCOD_IFNOT(p != NULL) return true; + return TCOD_list_is_empty(path->path); +} + +int TCOD_path_size(TCOD_path_t p) { + TCOD_path_data_t *path=(TCOD_path_data_t *)p; + TCOD_IFNOT(p != NULL) return 0; + return TCOD_list_size(path->path); +} + +void TCOD_path_get(TCOD_path_t p, int index, int *x, int *y) { + int pos; + TCOD_path_data_t *path=(TCOD_path_data_t *)p; + TCOD_IFNOT(p != NULL) return; + if ( x ) *x=path->ox; + if ( y ) *y=path->oy; + pos = TCOD_list_size(path->path)-1; + do { + int step=(int)(uintptr_t)TCOD_list_get(path->path,pos); + if ( x ) *x += dirx[step]; + if ( y ) *y += diry[step]; + pos--;index--; + } while (index >= 0); +} + +void TCOD_path_delete(TCOD_path_t p) { + TCOD_path_data_t *path=(TCOD_path_data_t *)p; + TCOD_IFNOT(p != NULL) return; + if ( path->grid ) free(path->grid); + if ( path->heur ) free(path->heur); + if ( path->prev ) free(path->prev); + if ( path->path ) TCOD_list_delete(path->path); + if ( path->heap ) TCOD_list_delete(path->heap); + free(path); +} + +/* private stuff */ +/* add a new unvisited cells to the cells-to-treat list + * the list is in fact a min_heap. Cell at index i has its sons at 2*i+1 and 2*i+2 + */ +static void TCOD_path_push_cell(TCOD_path_data_t *path, int x, int y) { + heap_add(path,path->heap,x,y); +} + +/* get the best cell from the heap */ +static void TCOD_path_get_cell(TCOD_path_data_t *path, int *x, int *y, float *distance) { + uint32_t offset = heap_get(path,path->heap); + *x=(offset % path->w); + *y=(offset / path->w); + *distance=path->grid[offset]; +} +/* fill the grid, starting from the origin until we reach the destination */ +static void TCOD_path_set_cells(TCOD_path_data_t *path) { + while ( path->grid[path->dx + path->dy * path->w ] == 0 && ! TCOD_list_is_empty(path->heap) ) { + + int x,y,i,imax; + float distance; + TCOD_path_get_cell(path,&x,&y,&distance); + imax= ( path->diagonalCost == 0.0f ? 4 : 8) ; + for (i=0; i < imax; i++ ) { + /* convert i to dx,dy */ + static int idirx[]={0,-1,1,0,-1,1,-1,1}; + static int idiry[]={-1,0,0,1,-1,-1,1,1}; + /* convert i to direction */ + static dir_t prevdirs[] = { + NORTH, WEST, EAST, SOUTH, NORTH_WEST, NORTH_EAST,SOUTH_WEST,SOUTH_EAST + }; + /* coordinate of the adjacent cell */ + int cx=x+idirx[i]; + int cy=y+idiry[i]; + if ( cx >= 0 && cy >= 0 && cx < path->w && cy < path->h ) { + float walk_cost = TCOD_path_walk_cost(path,x,y,cx,cy); + if ( walk_cost > 0.0f ) { + /* in of the map and walkable */ + float covered=distance + walk_cost * (i>=4 ? path->diagonalCost : 1.0f); + float previousCovered = path->grid[cx + cy * path->w ]; + if ( previousCovered == 0 ) { + /* put a new cell in the heap */ + int offset=cx + cy * path->w; + /* A* heuristic : remaining distance */ + float remaining=(float)sqrt((cx-path->dx)*(cx-path->dx)+(cy-path->dy)*(cy-path->dy)); + path->grid[ offset ] = covered; + path->heur[ offset ] = covered + remaining; + path->prev[ offset ] = prevdirs[i]; + TCOD_path_push_cell(path,cx,cy); + } else if ( previousCovered > covered ) { + /* we found a better path to a cell already in the heap */ + int offset=cx + cy * path->w; + path->grid[ offset ] = covered; + path->heur[ offset ] -= (previousCovered - covered); /* fix the A* score */ + path->prev[ offset ] = prevdirs[i]; + /* reorder the heap */ + heap_reorder(path,offset); + } + } + } + } + } +} + +/* check if a cell is walkable (from the pathfinder point of view) */ +static float TCOD_path_walk_cost(TCOD_path_data_t *path, int xFrom, int yFrom, int xTo, int yTo) { + if ( path->map ) return TCOD_map_is_walkable(path->map,xTo,yTo) ? 1.0f : 0.0f; + return path->func(xFrom,yFrom,xTo,yTo,path->user_data); +} + +void TCOD_path_get_origin(TCOD_path_t p, int *x, int *y) { + TCOD_path_data_t *path=(TCOD_path_data_t *)p; + TCOD_IFNOT(p != NULL) return; + if ( x ) *x=path->ox; + if ( y ) *y=path->oy; +} + +void TCOD_path_get_destination(TCOD_path_t p, int *x, int *y) { + TCOD_path_data_t *path=(TCOD_path_data_t *)p; + TCOD_IFNOT(p != NULL) return; + if ( x ) *x=path->dx; + if ( y ) *y=path->dy; +} + +/* ------------------------------------------------------- * + * Dijkstra * + * written by Mingos * + * ----------------- * + * A floodfill-like algo that will calculate all distances * + * to all accessible cells (nodes) from a given root node. * + * ------------------------------------------------------- */ + +/* Dijkstra data structure */ +typedef struct TCOD_Dijkstra { + int diagonal_cost; + int width, height, nodes_max; + TCOD_map_t map; /* a TCODMap with walkability data */ + TCOD_path_func_t func; + void *user_data; + unsigned int * distances; /* distances grid */ + unsigned int * nodes; /* the processed nodes */ + TCOD_list_t path; +} dijkstra_t; + +/* create a Dijkstra object */ +TCOD_dijkstra_t TCOD_dijkstra_new (TCOD_map_t map, float diagonalCost) { + dijkstra_t * data ; + TCOD_IFNOT(map != NULL) return NULL; + data = malloc(sizeof(dijkstra_t)); + data->map = map; + data->func = NULL; + data->user_data=NULL; + data->distances = malloc(TCOD_map_get_nb_cells(data->map)*sizeof(int)); + data->nodes = malloc(TCOD_map_get_nb_cells(data->map)*sizeof(int)); + data->diagonal_cost = (int)((diagonalCost * 100.0f)+0.1f); /* because (int)(1.41f*100.0f) == 140!!! */ + data->width = TCOD_map_get_width(data->map); + data->height = TCOD_map_get_height(data->map); + data->nodes_max = TCOD_map_get_nb_cells(data->map); + data->path = TCOD_list_new(); + return (TCOD_dijkstra_t)data; +} + +TCOD_dijkstra_t TCOD_dijkstra_new_using_function(int map_width, int map_height, TCOD_path_func_t func, void *user_data, float diagonalCost) { + dijkstra_t * data; + TCOD_IFNOT(func != NULL && map_width > 0 && map_height > 0) return NULL; + data = malloc(sizeof(dijkstra_t)); + data->map = NULL; + data->func = func; + data->user_data=user_data; + data->distances = malloc(map_width*map_height*sizeof(int)*4); + data->nodes = malloc(map_width*map_height*sizeof(int)*4); + data->diagonal_cost = (int)((diagonalCost * 100.0f)+0.1f); /* because (int)(1.41f*100.0f) == 140!!! */ + data->width = map_width; + data->height = map_height; + data->nodes_max = map_width*map_height; + data->path = TCOD_list_new(); + return (TCOD_dijkstra_t)data; +} + + +/* compute a Dijkstra grid */ +void TCOD_dijkstra_compute (TCOD_dijkstra_t dijkstra, int root_x, int root_y) { + dijkstra_t * data = (dijkstra_t*)dijkstra; + /* map size data */ + unsigned int mx = data->width; + unsigned int my = data->height; + unsigned int mmax = data->nodes_max; + /* encode the root coords in one integer */ + unsigned int root = (root_y * mx) + root_x; + /* some stuff to walk through the nodes table */ + unsigned int index = 0; /* the index of the first node in queue */ + unsigned int last_index = 1; /* total nb of registered queue indices */ + unsigned int * nodes = data->nodes; /* table of nodes to which the indices above apply */ + /* ok, here's the order of node processing: W, S, E, N, NW, NE, SE, SW */ + static int dx[8] = { -1, 0, 1, 0, -1, 1, 1, -1 }; + static int dy[8] = { 0, -1, 0, 1, -1, -1, 1, 1 }; + /* and distances for each index */ + int dd[8] = { 100, 100, 100, 100, data->diagonal_cost, data->diagonal_cost, data->diagonal_cost, data->diagonal_cost }; + /* if diagonal_cost is 0, disallow diagonal moves */ + int imax = (data->diagonal_cost == 0 ? 4 : 8); + /* aight, now set the distances table and set everything to infinity */ + unsigned int * distances = data->distances; + TCOD_IFNOT(data != NULL) return; + TCOD_IFNOT((unsigned)root_x < (unsigned)mx && (unsigned)root_y < (unsigned)my) return; + memset(distances,0xFFFFFFFF,mmax*sizeof(int)); + memset(nodes,0xFFFFFFFF,mmax*sizeof(int)); + /* data for root node is known... */ + distances[root] = 0; + nodes[index] = root; /*set starting note to root */ + /* and the loop */ + do { + unsigned int x, y; + int i; + if (nodes[index] == 0xFFFFFFFF) { + continue; + } + + /* coordinates of currently processed node */ + x = nodes[index] % mx; + y = nodes[index] / mx; + + /* check adjacent nodes */ + for(i=0;imap ) dt += dd[i]; + else { + /* distance given by the user callback */ + userDist=data->func(x,y,tx,ty,data->user_data); + dt += (unsigned int)(userDist*dd[i]); + } + /* ..., encode coordinates, ... */ + new_node = (ty * mx) + tx; + /* and check if the node's eligible for queuing */ + if (distances[new_node] > dt) { + unsigned int j; + /* if not walkable, don't process it */ + if (data->map && !TCOD_map_is_walkable(data->map,tx,ty)) continue; + else if ( data->func && userDist <= 0.0f ) continue; + distances[new_node] = dt; /* set processed node's distance */ + /* place the processed node in the queue before the last queued node with greater distance */ + j = last_index - 1; + while (distances[nodes[j]] >= distances[new_node]) { + /* this ensures that if the node has been queued previously, but with a higher distance, it's removed */ + if (nodes[j] == new_node) { + int k = j; + while ((unsigned)k <= last_index) { + nodes[k] = nodes[k+1]; + k++; + } + last_index--; + } + else nodes[j+1] = nodes[j]; + j--; + } + last_index++; /* increase total indices count */ + nodes[j+1] = new_node; /* and finally put the node where it belongs in the queue */ + } + } + } + } while (mmax > ++index); +} + +/* get distance from source */ +float TCOD_dijkstra_get_distance (TCOD_dijkstra_t dijkstra, int x, int y) { + dijkstra_t * data = (dijkstra_t*)dijkstra; + unsigned int * distances; + TCOD_IFNOT(data != NULL) return -1.0f; + TCOD_IFNOT ((unsigned)x < (unsigned)data->width && (unsigned)y < (unsigned)data->height) return -1.0f; + if (data->distances[(y*data->width)+x] == 0xFFFFFFFF) return -1.0f; + distances = data->distances; + return ((float)distances[(y * data->width) + x] * 0.01f); +} + +unsigned int dijkstra_get_int_distance (dijkstra_t * data, int x, int y) { + unsigned int * distances = data->distances; + return distances[(y * data->width) + x]; +} + +/* create a path */ +bool TCOD_dijkstra_path_set (TCOD_dijkstra_t dijkstra, int x, int y) { + dijkstra_t * data = (dijkstra_t*)dijkstra; + int px = x, py = y; + static int dx[9] = { -1, 0, 1, 0, -1, 1, 1, -1, 0 }; + static int dy[9] = { 0, -1, 0, 1, -1, -1, 1, 1, 0 }; + unsigned int distances[8] = {0}; + int lowest_index; + int imax = (data->diagonal_cost == 0 ? 4 : 8); + TCOD_IFNOT(data != NULL) return false; + TCOD_IFNOT((unsigned)x < (unsigned)data->width && (unsigned)y < (unsigned)data->height) return false; + /* check that destination is reachable */ + if ( dijkstra_get_int_distance(data,x,y) == 0xFFFFFFFF ) return false; + TCOD_list_clear(data->path); + do { + unsigned int lowest; + int i; + TCOD_list_push(data->path,(const void*)(uintptr_t)((py * data->width) + px)); + for(i=0;iwidth && (unsigned)cy < (unsigned)data->height) distances[i] = dijkstra_get_int_distance(data,cx,cy); + else distances[i] = 0xFFFFFFFF; + } + lowest = dijkstra_get_int_distance(data,px,py); + lowest_index = 8; + for(i=0;ipath); + return true; +} + +void TCOD_dijkstra_reverse(TCOD_dijkstra_t dijkstra) { + dijkstra_t * data = (dijkstra_t*)dijkstra; + TCOD_IFNOT(data != NULL) return; + TCOD_list_reverse(data->path); +} + +/* walk the path */ +bool TCOD_dijkstra_path_walk (TCOD_dijkstra_t dijkstra, int *x, int *y) { + dijkstra_t * data = (dijkstra_t*)dijkstra; + TCOD_IFNOT(data != NULL) return false; + if (TCOD_list_is_empty(data->path)) return false; + else { + unsigned int node = (unsigned int)(uintptr_t)TCOD_list_pop(data->path); + if ( x ) *x = (int)(node % data->width); + if ( y ) *y = (int)(node / data->width); + } + return true; +} + +/* delete a Dijkstra object */ +void TCOD_dijkstra_delete (TCOD_dijkstra_t dijkstra) { + dijkstra_t * data = (dijkstra_t*)dijkstra; + TCOD_IFNOT(data != NULL) return; + if ( data->distances ) free(data->distances); + if ( data->nodes ) free(data->nodes); + if ( data->path ) TCOD_list_delete(data->path); + free(data); +} + +bool TCOD_dijkstra_is_empty(TCOD_dijkstra_t p) { + dijkstra_t * data = (dijkstra_t*)p; + TCOD_IFNOT(data != NULL) return true; + return TCOD_list_is_empty(data->path); +} + +int TCOD_dijkstra_size(TCOD_dijkstra_t p) { + dijkstra_t * data = (dijkstra_t*)p; + TCOD_IFNOT(data != NULL) return 0; + return TCOD_list_size(data->path); +} + +void TCOD_dijkstra_get(TCOD_dijkstra_t p, int index, int *x, int *y) { + dijkstra_t * data = (dijkstra_t*)p; + unsigned int node ; + TCOD_IFNOT(data != NULL) return; + node = (unsigned int)(uintptr_t)TCOD_list_get(data->path,TCOD_list_size(data->path)-index-1); + if ( x ) *x = (int)(node % data->width); + if ( y ) *y = (int)(node / data->width); +} diff --git a/tcod_sys/libtcod/include/libtcod_portability.h b/tcod_sys/libtcod/src/libtcod/portability.h similarity index 85% rename from tcod_sys/libtcod/include/libtcod_portability.h rename to tcod_sys/libtcod/src/libtcod/portability.h index 3bf9c9ecc..3da5110b7 100644 --- a/tcod_sys/libtcod/include/libtcod_portability.h +++ b/tcod_sys/libtcod/src/libtcod/portability.h @@ -133,21 +133,10 @@ #endif /* int types */ -#include "external/pstdint.h" +#include /* bool type */ -#ifndef __bool_true_false_are_defined -#ifndef __cplusplus -#if defined(_MSC_VER) && _MSC_VER < 1800 -typedef uint8_t bool; -#define true 1 -#define false 0 -#define __bool_true_false_are_defined 1 -#else #include -#endif -#endif /* __cplusplus */ -#endif /* __bool_true_false_are_defined */ #ifdef __cplusplus extern "C" { @@ -158,23 +147,24 @@ TCODLIB_API char *TCOD_strdup(const char *s); TCODLIB_API int TCOD_strcasecmp(const char *s1, const char *s2); TCODLIB_API int TCOD_strncasecmp(const char *s1, const char *s2, size_t n); -#if defined(TCOD_WINDOWS) -char *strcasestr (const char *haystack, const char *needle); -#endif -#if defined(TCOD_LINUX) || defined(TCOD_HAIKU) || defined(TCOD_FREEBSD) || defined(TCOD_MACOSX) -#define vsnwprintf vswprintf -#endif -#ifdef TCOD_WINDOWS -#define vsnwprintf _vsnwprintf -#endif +/* Define vswprintf across platforms. */ +#ifdef _WIN32 +#define vswprintf _vsnwprintf /* Windows */ +#endif /* _WIN32 */ /* cross platform deprecation */ -#if defined(_MSC_VER) -#define TCOD_DEPRECATED __declspec(deprecated) +#if defined(__cplusplus) && __cplusplus >= 201402L +#define TCOD_DEPRECATED(msg) [[deprecated(msg)]] +#define TCOD_DEPRECATED_NOMESSAGE [[deprecated]] +#elif defined(_MSC_VER) +#define TCOD_DEPRECATED(msg) __declspec(deprecated(msg)) +#define TCOD_DEPRECATED_NOMESSAGE __declspec(deprecated) #elif defined(__GNUC__) -#define TCOD_DEPRECATED __attribute__ ((deprecated)) +#define TCOD_DEPRECATED(msg) __attribute__ ((deprecated)) +#define TCOD_DEPRECATED_NOMESSAGE __attribute__ ((deprecated)) #else -#define TCOD_DEPRECATED +#define TCOD_DEPRECATED(msg) +#define TCOD_DEPRECATED_NOMESSAGE #endif #ifdef __cplusplus diff --git a/tcod_sys/libtcod/src/libtcod/sdl2/legacy_backend.cpp b/tcod_sys/libtcod/src/libtcod/sdl2/legacy_backend.cpp new file mode 100644 index 000000000..edac786e4 --- /dev/null +++ b/tcod_sys/libtcod/src/libtcod/sdl2/legacy_backend.cpp @@ -0,0 +1,2 @@ + +#include "legacy_backend.h" diff --git a/tcod_sys/libtcod/src/libtcod/sdl2/legacy_backend.h b/tcod_sys/libtcod/src/libtcod/sdl2/legacy_backend.h new file mode 100644 index 000000000..d09eaf669 --- /dev/null +++ b/tcod_sys/libtcod/src/libtcod/sdl2/legacy_backend.h @@ -0,0 +1,11 @@ + +#ifndef LIBTCOD_SDL2_LEGACY_BACKEND_H_ +#define LIBTCOD_SDL2_LEGACY_BACKEND_H_ + +#ifdef __cplusplus +namespace tcod { +namespace sdl2 { +} // namespace sdl2 +} // namespace tcod +#endif /* __cplusplus */ +#endif /* LIBTCOD_SDL2_LEGACY_BACKEND_H_ */ diff --git a/tcod_sys/libtcod/src/libtcod/sdl2/sdl2_alias.cpp b/tcod_sys/libtcod/src/libtcod/sdl2/sdl2_alias.cpp new file mode 100644 index 000000000..00bd82832 --- /dev/null +++ b/tcod_sys/libtcod/src/libtcod/sdl2/sdl2_alias.cpp @@ -0,0 +1,132 @@ + +#include "sdl2_alias.h" + +#include +#include +#include +#include +#include + +#include +namespace tcod { +namespace sdl2 { +using image::Image; + +struct sdl_deleter +{ + void operator()(SDL_Window *p) const { SDL_DestroyWindow(p); } + void operator()(SDL_Renderer *p) const { SDL_DestroyRenderer(p); } + void operator()(SDL_Texture *p) const { SDL_DestroyTexture(p); } +}; + +std::map, + std::weak_ptr> sdl2_alias_pool = {}; + +class SDL2InternalTilesetAlias_: public TilesetObserver { + public: + using key_type = std::tuple; + SDL2InternalTilesetAlias_(struct SDL_Renderer* renderer, + std::shared_ptr tileset) + : TilesetObserver(tileset), renderer_(renderer), texture_(nullptr) + { + SDL_AddEventWatch(on_sdl_event, this); + if (!renderer_) { + throw std::invalid_argument("renderer cannot be nullptr."); + } + sync_alias(); + } + ~SDL2InternalTilesetAlias_() { + SDL_DelEventWatch(on_sdl_event, this); + } + SDL_Texture* get_texture_alias() + { + return texture_.get(); + } + struct SDL_Renderer* renderer_; + struct std::unique_ptr texture_; + protected: + virtual void on_tileset_changed( + const std::vector> &changes) override + { + sync_alias(); + } + private: + void clear_alias() + { + texture_ = nullptr; + } + void sync_alias() + { + clear_alias(); + const std::vector& tiles = tileset_->get_tiles(); + int tile_width = tileset_->get_tile_width(); + int tile_height = tileset_->get_tile_height(); + int width = tile_width * tiles.size(); + int height = tile_height; + texture_ = std::unique_ptr( + SDL_CreateTexture(renderer_, SDL_PIXELFORMAT_RGBA32, + SDL_TEXTUREACCESS_STATIC, width, height), + sdl_deleter()); + Image alias(width, height); + for (size_t i = 0; i < tiles.size(); ++i) { + Image tile = tiles.at(i).get_image(); + for (int y = 0; y < tile_height; ++y) { + for (int x = 0; x < tile_width; ++x) { + alias.at(x + tile_width * i, y) = tile.at(x, y); + } + } + } + SDL_UpdateTexture(texture_.get(), nullptr, alias.data(), + sizeof(alias.at(0,0)) * alias.width()); + } + static int on_sdl_event(void* userdata, SDL_Event* event) + { + auto this_ = static_cast(userdata); + switch (event->type) { + case SDL_RENDER_DEVICE_RESET: // Lost all textures. + this_->sync_alias(); + break; + } + return 0; + } +}; + +SDL2TilesetAlias::SDL2TilesetAlias(struct SDL_Renderer* renderer, + std::shared_ptr tileset) +{ + static std::mutex mutex; + std::unique_lock lock(mutex); + SDL2InternalTilesetAlias_::key_type key = + std::make_tuple(tileset.get(), renderer); + alias_ = sdl2_alias_pool[key].lock(); + if (!alias_) { + sdl2_alias_pool[key] = alias_ = + std::make_shared(renderer, tileset); + } +} + +std::shared_ptr& SDL2TilesetAlias::get_tileset() +{ + return alias_->get_tileset(); +} + +SDL_Texture* SDL2TilesetAlias::get_texture_alias() +{ + return alias_->texture_.get(); +} +SDL_Rect SDL2TilesetAlias::get_char_rect(int codepoint) { + auto& charmap = alias_->get_tileset()->get_character_map(); + int tile_index = 0; + if (static_cast(codepoint) < charmap.size()) { + tile_index = charmap.at(codepoint); + } + return SDL_Rect{ + alias_->get_tileset()->get_tile_width() * tile_index, + 0, + alias_->get_tileset()->get_tile_width(), + alias_->get_tileset()->get_tile_height(), + }; +} + +} // namespace sdl2 +} // namespace tcod diff --git a/tcod_sys/libtcod/src/libtcod/sdl2/sdl2_alias.h b/tcod_sys/libtcod/src/libtcod/sdl2/sdl2_alias.h new file mode 100644 index 000000000..acfc9c6e1 --- /dev/null +++ b/tcod_sys/libtcod/src/libtcod/sdl2/sdl2_alias.h @@ -0,0 +1,35 @@ + +#ifndef LIBTCOD_SDL2_SDL2_ALIAS_H_ +#define LIBTCOD_SDL2_SDL2_ALIAS_H_ +#include + +#include "../tileset/observer.h" +#ifdef __cplusplus +struct SDL_Renderer; +struct SDL_Texture; +struct SDL_Rect; + +namespace tcod { +namespace sdl2 { +using tileset::Tile; +using tileset::Tileset; +using tileset::TilesetObserver; +class SDL2InternalTilesetAlias_; + +class SDL2TilesetAlias { + public: + SDL2TilesetAlias() = default; + SDL2TilesetAlias(struct SDL_Renderer* renderer, + std::shared_ptr tileset); + + std::shared_ptr& get_tileset(); + + SDL_Texture* get_texture_alias(); + SDL_Rect get_char_rect(int codepoint); + private: + std::shared_ptr alias_; +}; +} // namespace sdl2 +} // namespace tcod +#endif // __cplusplus +#endif // LIBTCOD_SDL2_SDL2_ALIAS_H_ diff --git a/tcod_sys/libtcod/src/libtcod/sdl2/sdl2_display.cpp b/tcod_sys/libtcod/src/libtcod/sdl2/sdl2_display.cpp new file mode 100644 index 000000000..cfbc19f71 --- /dev/null +++ b/tcod_sys/libtcod/src/libtcod/sdl2/sdl2_display.cpp @@ -0,0 +1,73 @@ + +#include "sdl2_display.h" + +#include +#include + +#include "../console.h" +#include "../libtcod_int.h" + +#include + +namespace tcod { +namespace sdl2 { +WindowedDisplay::WindowedDisplay(std::pair window_size, + int window_flags, const std::string& title) +{ + int width = window_size.first; + int height = window_size.second; + if (width < 0 || height < 0) { + throw std::invalid_argument("width and height must be non-negative."); + } + if (SDL_Init(SDL_INIT_VIDEO | SDL_INIT_EVENTS | SDL_INIT_TIMER)) { + throw std::runtime_error(SDL_GetError()); + } + window_ = std::shared_ptr( + SDL_CreateWindow( + title.c_str(), SDL_WINDOWPOS_UNDEFINED, SDL_WINDOWPOS_UNDEFINED, + width, height, window_flags), + [](SDL_Window* window){ SDL_DestroyWindow(window); }); + if (!window_) { throw std::runtime_error(SDL_GetError()); } +} +void WindowedDisplay::set_title(const std::string title) +{ + if (!window_) { throw std::logic_error("Unresolved class invariant."); } + SDL_SetWindowTitle(window_.get(), title.c_str()); +} +std::string WindowedDisplay::get_title() +{ + if (!window_) { throw std::logic_error("Unresolved class invariant."); } + return std::string(SDL_GetWindowTitle(window_.get())); +} + +SDL2Display::SDL2Display(std::shared_ptr tileset, + std::pair window_size, int window_flags, + const std::string& title) +: WindowedDisplay(window_size, window_flags, title) +{ + // Configure SDL2 renderer. + renderer_ = std::shared_ptr( + SDL_CreateRenderer(get_window(), -1, SDL_RENDERER_TARGETTEXTURE), + [](SDL_Renderer* renderer){ SDL_DestroyRenderer(renderer); }); + if (!renderer_) { throw std::runtime_error(SDL_GetError()); } + // Configure libtcod renderer. + set_tileset(tileset); +} +void SDL2Display::set_tileset(std::shared_ptr tileset) +{ + if (!renderer_) { throw std::logic_error("Unresolved class invariant."); } + if (!tileset) { + throw std::invalid_argument("tileset must not be nullptr."); + } + tcod_renderer_ = SDL2Renderer(renderer_.get(), tileset); +} +void SDL2Display::present(const TCOD_Console* console) +{ + if (!renderer_) { throw std::logic_error("Unresolved class invariant."); } + SDL_Texture* backbuffer = tcod_renderer_.render(console); + SDL_RenderClear(renderer_.get()); + SDL_RenderCopy(renderer_.get(), backbuffer, nullptr, nullptr); + SDL_RenderPresent(renderer_.get()); +} +} // namespace sdl2 +} // namespace tcod diff --git a/tcod_sys/libtcod/src/libtcod/sdl2/sdl2_display.h b/tcod_sys/libtcod/src/libtcod/sdl2/sdl2_display.h new file mode 100644 index 000000000..a50c4740d --- /dev/null +++ b/tcod_sys/libtcod/src/libtcod/sdl2/sdl2_display.h @@ -0,0 +1,51 @@ + +#ifndef LIBTCOD_SDL2_SDL2_DISPLAY_H_ +#define LIBTCOD_SDL2_SDL2_DISPLAY_H_ + +#ifdef __cplusplus +#include +#include +#include +#endif // __cplusplus + +#include "sdl2_renderer.h" +#include "../engine/display.h" + +struct SDL_Window; +struct SDL_Renderer; +#ifdef __cplusplus +namespace tcod { +namespace sdl2 { +/** + * Incomplete interface for subclasses expecting an SDL2 window. + */ +class WindowedDisplay: public engine::Display { + public: + WindowedDisplay(std::pair window_size, int window_flags, + const std::string& title); + virtual void set_title(const std::string title) override; + virtual std::string get_title() override; + SDL_Window* get_window() { return window_.get(); } + private: + std::shared_ptr window_; +}; +/** + * Display interface using a basic SDL2 renderer. + */ +class SDL2Display: public WindowedDisplay { + public: + SDL2Display( + std::shared_ptr tileset, + std::pair window_size, + int window_flags, + const std::string& title); + virtual void set_tileset(std::shared_ptr tileset) override; + virtual void present(const TCOD_Console*) override; + private: + std::shared_ptr renderer_; + SDL2Renderer tcod_renderer_; +}; +} // namespace sdl2 +} // namespace tcod +#endif // __cplusplus +#endif // LIBTCOD_SDL2_SDL2_DISPLAY_H_ diff --git a/tcod_sys/libtcod/src/libtcod/sdl2/sdl2_renderer.cpp b/tcod_sys/libtcod/src/libtcod/sdl2/sdl2_renderer.cpp new file mode 100644 index 000000000..16d1e2743 --- /dev/null +++ b/tcod_sys/libtcod/src/libtcod/sdl2/sdl2_renderer.cpp @@ -0,0 +1,80 @@ + +#include "sdl2_renderer.h" + +#include + +#include +namespace tcod { +namespace sdl2 { +using tileset::Tileset; +SDL2Renderer::~SDL2Renderer() +{ + if (texture_ && !SDL_WasInit(SDL_INIT_VIDEO)) { + SDL_DestroyTexture(texture_); + } +} + +struct SDL_Texture* SDL2Renderer::render(const TCOD_Console* console) +{ + if (!console) { throw; } + if (console->w != cache_.width() || console->h != cache_.height()) { + if (texture_) { + SDL_DestroyTexture(texture_); + texture_ = nullptr; + } + } + if (!texture_) { + cache_ = cache_type(console->w, console->h); + const uint32_t format = 0; + texture_ = SDL_CreateTexture(renderer_, format, SDL_TEXTUREACCESS_TARGET, + tileset_->get_tile_width() * console->w, + tileset_->get_tile_height() * console->h); + if(!texture_) { throw std::runtime_error(SDL_GetError()); } + } + SDL_SetRenderTarget(renderer_, texture_); + SDL_Texture* alias_texture = alias_.get_texture_alias(); + SDL_SetRenderDrawBlendMode(renderer_, SDL_BLENDMODE_NONE); + SDL_SetTextureBlendMode(alias_texture, SDL_BLENDMODE_BLEND); + SDL_SetTextureAlphaMod(alias_texture, 0xff); + for (int y = 0; y < console->h; ++y) { + for (int x = 0; x < console->w; ++x) { + const int i = console->w * y + x; // console index + const int ch = console->ch_array[i]; + const TCOD_color_t fg = console->fg_array[i]; + const TCOD_color_t bg = console->bg_array[i]; + int& cache_ch = std::get<0>(cache_.at(x, y)); + ColorRGBA& cache_fg = std::get<1>(cache_.at(x, y)); + ColorRGBA& cache_bg = std::get<2>(cache_.at(x, y)); + if (cache_ch == ch && + cache_fg.r == fg.r && cache_fg.g == fg.g && cache_fg.b == fg.b && + cache_bg.r == bg.r && cache_bg.g == bg.g && cache_bg.b == bg.b) { + continue; // This tile was already rendered on a previous frame. + } + cache_ch = ch; + cache_fg.r = fg.r; + cache_fg.b = fg.b; + cache_fg.g = fg.g; + cache_bg.r = bg.r; + cache_bg.b = bg.b; + cache_bg.g = bg.g; + const SDL_Rect dest_rect{ + x * tileset_->get_tile_width(), + y * tileset_->get_tile_height(), + tileset_->get_tile_width(), + tileset_->get_tile_height(), + }; + SDL_SetRenderDrawColor(renderer_, bg.r, bg.g, bg.b, 0xff); + SDL_RenderFillRect(renderer_, &dest_rect); + if (fg.r != bg.r || fg.g != bg.g || fg.b != bg.b) { + SDL_SetTextureColorMod(alias_texture, fg.r, fg.g, fg.b); + const SDL_Rect alias_rect = alias_.get_char_rect(ch); + SDL_RenderCopy(renderer_, alias_texture, + &alias_rect, &dest_rect); + } + } + } + SDL_SetRenderTarget(renderer_, nullptr); + return texture_; +} +} // namespace sdl2 +} // namespace tcod diff --git a/tcod_sys/libtcod/src/libtcod/sdl2/sdl2_renderer.h b/tcod_sys/libtcod/src/libtcod/sdl2/sdl2_renderer.h new file mode 100644 index 000000000..cf82bbed0 --- /dev/null +++ b/tcod_sys/libtcod/src/libtcod/sdl2/sdl2_renderer.h @@ -0,0 +1,46 @@ + +#ifndef LIBTCOD_SDL2_SDL2_RENDERER_H_ +#define LIBTCOD_SDL2_SDL2_RENDERER_H_ +#ifdef __cplusplus +#include +#endif /* __cplusplus */ + +#include "sdl2_alias.h" +#include "../color/color.h" +#include "../console_types.h" +#include "../tileset/observer.h" +#include "../tileset/tileset.h" +#include "../utility/vector2.h" +#ifdef __cplusplus +struct SDL_Renderer; +struct SDL_Texture; +namespace tcod { +namespace sdl2 { +using tcod::tileset::Tileset; +class SDL2Renderer: public TilesetObserver { + public: + SDL2Renderer() + {} + SDL2Renderer(struct SDL_Renderer* renderer, SDL2TilesetAlias alias) + : TilesetObserver(alias.get_tileset()), alias_{alias}, renderer_{renderer} + {} + + SDL2Renderer(struct SDL_Renderer* renderer, + std::shared_ptr tileset) + : SDL2Renderer(renderer, SDL2TilesetAlias(renderer, tileset)) + {} + + ~SDL2Renderer(); + + struct SDL_Texture* render(const TCOD_Console* console); + private: + using cache_type = Vector2>; + SDL2TilesetAlias alias_; + cache_type cache_; + struct SDL_Renderer* renderer_; + struct SDL_Texture* texture_ = nullptr; +}; +} // namespace sdl2 +} // namespace tcod +#endif /* __cplusplus */ +#endif /* LIBTCOD_SDL2_SDL2_RENDERER_H_ */ diff --git a/tcod_sys/libtcod/src/sys.cpp b/tcod_sys/libtcod/src/libtcod/sys.cpp similarity index 96% rename from tcod_sys/libtcod/src/sys.cpp rename to tcod_sys/libtcod/src/libtcod/sys.cpp index f89e60690..d231ce19e 100644 --- a/tcod_sys/libtcod/src/sys.cpp +++ b/tcod_sys/libtcod/src/libtcod/sys.cpp @@ -1,242 +1,242 @@ -/* -* libtcod -* Copyright (c) 2008-2018 Jice & Mingos & rmtew -* All rights reserved. -* -* Redistribution and use in source and binary forms, with or without -* modification, are permitted provided that the following conditions are met: -* * Redistributions of source code must retain the above copyright -* notice, this list of conditions and the following disclaimer. -* * Redistributions in binary form must reproduce the above copyright -* notice, this list of conditions and the following disclaimer in the -* documentation and/or other materials provided with the distribution. -* * The name of Jice or Mingos may not be used to endorse or promote -* products derived from this software without specific prior written -* permission. -* -* THIS SOFTWARE IS PROVIDED BY JICE, MINGOS AND RMTEW ``AS IS'' AND ANY -* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED -* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE -* DISCLAIMED. IN NO EVENT SHALL JICE, MINGOS OR RMTEW BE LIABLE FOR ANY -* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES -* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; -* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND -* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS -* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. -*/ -#include - -#include -#include - -#ifdef TCOD_OSUTIL_SUPPORT -void TCODSystem::sleepMilli(uint32_t milliseconds) { - TCOD_sys_sleep_milli(milliseconds); -} - -uint32_t TCODSystem::getElapsedMilli() { - return TCOD_sys_elapsed_milli(); -} - -float TCODSystem::getElapsedSeconds() { - return TCOD_sys_elapsed_seconds(); -} -#endif - -#ifndef TCOD_BARE -void TCODSystem::saveScreenshot(const char *filename) { - TCOD_sys_save_screenshot(filename); -} - -void TCODSystem::forceFullscreenResolution(int width, int height) { - TCOD_sys_force_fullscreen_resolution(width, height); -} - -void TCODSystem::setRenderer(TCOD_renderer_t renderer) { - TCOD_sys_set_renderer(renderer); -} -TCOD_event_t TCODSystem::waitForEvent(int eventMask, TCOD_key_t *key, TCOD_mouse_t *mouse, bool flush) { - return TCOD_sys_wait_for_event(eventMask,key,mouse,flush); -} - -TCOD_event_t TCODSystem::checkForEvent(int eventMask, TCOD_key_t *key, TCOD_mouse_t *mouse) { - return TCOD_sys_check_for_event(eventMask,key,mouse); -} - -TCOD_renderer_t TCODSystem::getRenderer() { - return TCOD_sys_get_renderer(); -} -#endif - -#ifdef TCOD_OSUTIL_SUPPORT -void TCODSystem::setFps(int val) { - TCOD_sys_set_fps(val); -} - -int TCODSystem::getFps() { - return TCOD_sys_get_fps(); -} - -float TCODSystem::getLastFrameLength() { - return TCOD_sys_get_last_frame_length(); -} -#endif - -#ifndef TCOD_BARE -void TCODSystem::getCurrentResolution(int *w, int *h) { - TCOD_sys_get_current_resolution(w, h); -} - -void TCODSystem::getFullscreenOffsets(int *offx, int *offy) { - TCOD_sys_get_fullscreen_offsets(offx, offy); -} - -void TCODSystem::updateChar(int asciiCode, int fontx, int fonty,const TCODImage *img,int x,int y) { - TCOD_sys_update_char(asciiCode,fontx,fonty,img->data,x,y); -} - -void TCODSystem::getCharSize(int *w, int *h) { - TCOD_sys_get_char_size(w, h); -} -#endif - -// filesystem stuff -bool TCODSystem::createDirectory(const char *path) { - return TCOD_sys_create_directory(path) != 0; -} - -bool TCODSystem::deleteFile(const char *path) { - return TCOD_sys_delete_file(path) != 0; -} - -bool TCODSystem::deleteDirectory(const char *path) { - return TCOD_sys_delete_directory(path) != 0; -} - -bool TCODSystem::isDirectory(const char *path) { - return TCOD_sys_is_directory(path) != 0; -} - -TCOD_list_t TCODSystem::getDirectoryContent(const char *path, const char *pattern) { - return TCOD_sys_get_directory_content(path,pattern); -} - -bool TCODSystem::fileExists(const char * filename, ...) { - FILE * in; - bool ret = false; - char f[1024]; - va_list ap; - va_start(ap,filename); - vsprintf(f,filename,ap); - va_end(ap); - in = fopen(f,"rb"); - if (in != NULL) { - ret = true; - fclose(in); - } - return ret; -} - -bool TCODSystem::readFile(const char *filename, unsigned char **buf, size_t *size) { - return TCOD_sys_read_file(filename,buf,size) != 0; -} - -bool TCODSystem::writeFile(const char *filename, unsigned char *buf, uint32_t size) { - return TCOD_sys_write_file(filename,buf,size) != 0; -} - -#ifndef TCOD_BARE -// clipboard stuff -bool TCODSystem::setClipboard(const char *value) { - return TCOD_sys_clipboard_set(value) != 0; -} - -char *TCODSystem::getClipboard() { - return TCOD_sys_clipboard_get(); -} -#endif - -// thread stuff -int TCODSystem::getNumCores() { - return TCOD_sys_get_num_cores(); -} - -TCOD_thread_t TCODSystem::newThread(int (*func)(void *), void *data) { - return TCOD_thread_new(func,data); -} - -void TCODSystem::deleteThread(TCOD_thread_t th) { - TCOD_thread_delete(th); -} - -void TCODSystem::waitThread(TCOD_thread_t th) { - TCOD_thread_wait(th); -} - -// mutex -TCOD_mutex_t TCODSystem::newMutex() { - return TCOD_mutex_new(); -} - -void TCODSystem::mutexIn(TCOD_mutex_t mut) { - TCOD_mutex_in(mut); -} - -void TCODSystem::mutexOut(TCOD_mutex_t mut) { - TCOD_mutex_out(mut); -} - -void TCODSystem::deleteMutex(TCOD_mutex_t mut) { - TCOD_mutex_delete(mut); -} - -// semaphore -TCOD_semaphore_t TCODSystem::newSemaphore(int initVal) { - return TCOD_semaphore_new(initVal); -} - -void TCODSystem::lockSemaphore(TCOD_semaphore_t sem) { - TCOD_semaphore_lock(sem); -} - -void TCODSystem::unlockSemaphore(TCOD_semaphore_t sem) { - TCOD_semaphore_unlock(sem); -} - -void TCODSystem::deleteSemaphore( TCOD_semaphore_t sem) { - TCOD_semaphore_delete(sem); -} - -// condition -TCOD_cond_t TCODSystem::newCondition() { - return TCOD_condition_new(); -} - -void TCODSystem::signalCondition(TCOD_cond_t cond) { - TCOD_condition_signal(cond); -} - -void TCODSystem::broadcastCondition(TCOD_cond_t cond) { - TCOD_condition_broadcast(cond); -} - -void TCODSystem::waitCondition(TCOD_cond_t cond, TCOD_mutex_t mut) { - TCOD_condition_wait(cond, mut); -} - -void TCODSystem::deleteCondition( TCOD_cond_t cond) { - TCOD_condition_delete(cond); -} - -// custom post-renderer -static ITCODSDLRenderer *post_renderer=NULL; -extern "C" void TCOD_CRenderer(void *sdl_surface) { - if ( post_renderer ) post_renderer->render(sdl_surface); -} -void TCODSystem::registerSDLRenderer(ITCODSDLRenderer *renderer) { - ::post_renderer = renderer; -#ifndef TCOD_BARE - TCOD_sys_register_SDL_renderer(TCOD_CRenderer); -#endif -} +/* +* libtcod +* Copyright (c) 2008-2018 Jice & Mingos & rmtew +* All rights reserved. +* +* Redistribution and use in source and binary forms, with or without +* modification, are permitted provided that the following conditions are met: +* * Redistributions of source code must retain the above copyright +* notice, this list of conditions and the following disclaimer. +* * Redistributions in binary form must reproduce the above copyright +* notice, this list of conditions and the following disclaimer in the +* documentation and/or other materials provided with the distribution. +* * The name of Jice or Mingos may not be used to endorse or promote +* products derived from this software without specific prior written +* permission. +* +* THIS SOFTWARE IS PROVIDED BY JICE, MINGOS AND RMTEW ``AS IS'' AND ANY +* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED +* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE +* DISCLAIMED. IN NO EVENT SHALL JICE, MINGOS OR RMTEW BE LIABLE FOR ANY +* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES +* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; +* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND +* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS +* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +*/ +#include "sys.hpp" + +#include +#include + +#ifdef TCOD_OSUTIL_SUPPORT +void TCODSystem::sleepMilli(uint32_t milliseconds) { + TCOD_sys_sleep_milli(milliseconds); +} + +uint32_t TCODSystem::getElapsedMilli() { + return TCOD_sys_elapsed_milli(); +} + +float TCODSystem::getElapsedSeconds() { + return TCOD_sys_elapsed_seconds(); +} +#endif + +#ifndef TCOD_BARE +void TCODSystem::saveScreenshot(const char *filename) { + TCOD_sys_save_screenshot(filename); +} + +void TCODSystem::forceFullscreenResolution(int width, int height) { + TCOD_sys_force_fullscreen_resolution(width, height); +} + +void TCODSystem::setRenderer(TCOD_renderer_t renderer) { + TCOD_sys_set_renderer(renderer); +} +TCOD_event_t TCODSystem::waitForEvent(int eventMask, TCOD_key_t *key, TCOD_mouse_t *mouse, bool flush) { + return TCOD_sys_wait_for_event(eventMask,key,mouse,flush); +} + +TCOD_event_t TCODSystem::checkForEvent(int eventMask, TCOD_key_t *key, TCOD_mouse_t *mouse) { + return TCOD_sys_check_for_event(eventMask,key,mouse); +} + +TCOD_renderer_t TCODSystem::getRenderer() { + return TCOD_sys_get_renderer(); +} +#endif + +#ifdef TCOD_OSUTIL_SUPPORT +void TCODSystem::setFps(int val) { + TCOD_sys_set_fps(val); +} + +int TCODSystem::getFps() { + return TCOD_sys_get_fps(); +} + +float TCODSystem::getLastFrameLength() { + return TCOD_sys_get_last_frame_length(); +} +#endif + +#ifndef TCOD_BARE +void TCODSystem::getCurrentResolution(int *w, int *h) { + TCOD_sys_get_current_resolution(w, h); +} + +void TCODSystem::getFullscreenOffsets(int *offx, int *offy) { + TCOD_sys_get_fullscreen_offsets(offx, offy); +} + +void TCODSystem::updateChar(int asciiCode, int fontx, int fonty,const TCODImage *img,int x,int y) { + TCOD_sys_update_char(asciiCode,fontx,fonty,img->data,x,y); +} + +void TCODSystem::getCharSize(int *w, int *h) { + TCOD_sys_get_char_size(w, h); +} +#endif + +// filesystem stuff +bool TCODSystem::createDirectory(const char *path) { + return TCOD_sys_create_directory(path) != 0; +} + +bool TCODSystem::deleteFile(const char *path) { + return TCOD_sys_delete_file(path) != 0; +} + +bool TCODSystem::deleteDirectory(const char *path) { + return TCOD_sys_delete_directory(path) != 0; +} + +bool TCODSystem::isDirectory(const char *path) { + return TCOD_sys_is_directory(path) != 0; +} + +TCOD_list_t TCODSystem::getDirectoryContent(const char *path, const char *pattern) { + return TCOD_sys_get_directory_content(path,pattern); +} + +bool TCODSystem::fileExists(const char * filename, ...) { + FILE * in; + bool ret = false; + char f[1024]; + va_list ap; + va_start(ap,filename); + vsprintf(f,filename,ap); + va_end(ap); + in = fopen(f,"rb"); + if (in != NULL) { + ret = true; + fclose(in); + } + return ret; +} + +bool TCODSystem::readFile(const char *filename, unsigned char **buf, size_t *size) { + return TCOD_sys_read_file(filename,buf,size) != 0; +} + +bool TCODSystem::writeFile(const char *filename, unsigned char *buf, uint32_t size) { + return TCOD_sys_write_file(filename,buf,size) != 0; +} + +#ifndef TCOD_BARE +// clipboard stuff +bool TCODSystem::setClipboard(const char *value) { + return TCOD_sys_clipboard_set(value) != 0; +} + +char *TCODSystem::getClipboard() { + return TCOD_sys_clipboard_get(); +} +#endif + +// thread stuff +int TCODSystem::getNumCores() { + return TCOD_sys_get_num_cores(); +} + +TCOD_thread_t TCODSystem::newThread(int (*func)(void *), void *data) { + return TCOD_thread_new(func,data); +} + +void TCODSystem::deleteThread(TCOD_thread_t th) { + TCOD_thread_delete(th); +} + +void TCODSystem::waitThread(TCOD_thread_t th) { + TCOD_thread_wait(th); +} + +// mutex +TCOD_mutex_t TCODSystem::newMutex() { + return TCOD_mutex_new(); +} + +void TCODSystem::mutexIn(TCOD_mutex_t mut) { + TCOD_mutex_in(mut); +} + +void TCODSystem::mutexOut(TCOD_mutex_t mut) { + TCOD_mutex_out(mut); +} + +void TCODSystem::deleteMutex(TCOD_mutex_t mut) { + TCOD_mutex_delete(mut); +} + +// semaphore +TCOD_semaphore_t TCODSystem::newSemaphore(int initVal) { + return TCOD_semaphore_new(initVal); +} + +void TCODSystem::lockSemaphore(TCOD_semaphore_t sem) { + TCOD_semaphore_lock(sem); +} + +void TCODSystem::unlockSemaphore(TCOD_semaphore_t sem) { + TCOD_semaphore_unlock(sem); +} + +void TCODSystem::deleteSemaphore( TCOD_semaphore_t sem) { + TCOD_semaphore_delete(sem); +} + +// condition +TCOD_cond_t TCODSystem::newCondition() { + return TCOD_condition_new(); +} + +void TCODSystem::signalCondition(TCOD_cond_t cond) { + TCOD_condition_signal(cond); +} + +void TCODSystem::broadcastCondition(TCOD_cond_t cond) { + TCOD_condition_broadcast(cond); +} + +void TCODSystem::waitCondition(TCOD_cond_t cond, TCOD_mutex_t mut) { + TCOD_condition_wait(cond, mut); +} + +void TCODSystem::deleteCondition( TCOD_cond_t cond) { + TCOD_condition_delete(cond); +} + +// custom post-renderer +static ITCODSDLRenderer *post_renderer=NULL; +extern "C" void TCOD_CRenderer(void *sdl_surface) { + if ( post_renderer ) post_renderer->render(sdl_surface); +} +void TCODSystem::registerSDLRenderer(ITCODSDLRenderer *renderer) { + ::post_renderer = renderer; +#ifndef TCOD_BARE + TCOD_sys_register_SDL_renderer(TCOD_CRenderer); +#endif +} diff --git a/tcod_sys/libtcod/include/sys.h b/tcod_sys/libtcod/src/libtcod/sys.h similarity index 87% rename from tcod_sys/libtcod/include/sys.h rename to tcod_sys/libtcod/src/libtcod/sys.h index d6169b19d..17073d07e 100644 --- a/tcod_sys/libtcod/include/sys.h +++ b/tcod_sys/libtcod/src/libtcod/sys.h @@ -1,147 +1,177 @@ -/* -* libtcod -* Copyright (c) 2008-2018 Jice & Mingos & rmtew -* All rights reserved. -* -* Redistribution and use in source and binary forms, with or without -* modification, are permitted provided that the following conditions are met: -* * Redistributions of source code must retain the above copyright -* notice, this list of conditions and the following disclaimer. -* * Redistributions in binary form must reproduce the above copyright -* notice, this list of conditions and the following disclaimer in the -* documentation and/or other materials provided with the distribution. -* * The name of Jice or Mingos may not be used to endorse or promote -* products derived from this software without specific prior written -* permission. -* -* THIS SOFTWARE IS PROVIDED BY JICE, MINGOS AND RMTEW ``AS IS'' AND ANY -* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED -* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE -* DISCLAIMED. IN NO EVENT SHALL JICE, MINGOS OR RMTEW BE LIABLE FOR ANY -* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES -* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; -* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND -* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS -* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. -*/ -#ifndef _TCOD_SYS_H -#define _TCOD_SYS_H - -#include "libtcod_portability.h" -#include "list.h" -#include "image.h" -#include "mouse_types.h" - -#ifdef __cplusplus -extern "C" { -#endif -TCODLIB_API void TCOD_sys_startup(void); -TCODLIB_API void TCOD_sys_shutdown(void); - -#ifdef TCOD_OSUTIL_SUPPORT -TCODLIB_API uint32_t TCOD_sys_elapsed_milli(void); -TCODLIB_API float TCOD_sys_elapsed_seconds(void); -TCODLIB_API void TCOD_sys_sleep_milli(uint32_t val); -TCODLIB_API void TCOD_sys_set_fps(int val); -TCODLIB_API int TCOD_sys_get_fps(void); -TCODLIB_API float TCOD_sys_get_last_frame_length(void); -#endif - -#ifndef TCOD_BARE -TCODLIB_API void TCOD_sys_save_screenshot(const char *filename); -TCODLIB_API void TCOD_sys_force_fullscreen_resolution(int width, int height); -TCODLIB_API void TCOD_sys_set_renderer(TCOD_renderer_t renderer); -TCODLIB_API TCOD_renderer_t TCOD_sys_get_renderer(void); -TCODLIB_API void TCOD_sys_get_current_resolution(int *w, int *h); -TCODLIB_API void TCOD_sys_get_fullscreen_offsets(int *offx, int *offy); -TCODLIB_API void TCOD_sys_get_char_size(int *w, int *h); -#endif - -#ifdef TCOD_IMAGE_SUPPORT -TCODLIB_API void TCOD_sys_update_char(int asciiCode, int fontx, int fonty, TCOD_image_t img, int x, int y); -#endif - -#ifndef TCOD_BARE -TCODLIB_API void *TCOD_sys_get_SDL_window(void); -TCODLIB_API void *TCOD_sys_get_SDL_renderer(void); -#endif - -#ifndef TCOD_BARE -typedef enum { - TCOD_EVENT_NONE=0, - TCOD_EVENT_KEY_PRESS=1, - TCOD_EVENT_KEY_RELEASE=2, - TCOD_EVENT_KEY=TCOD_EVENT_KEY_PRESS|TCOD_EVENT_KEY_RELEASE, - TCOD_EVENT_MOUSE_MOVE=4, - TCOD_EVENT_MOUSE_PRESS=8, - TCOD_EVENT_MOUSE_RELEASE=16, - TCOD_EVENT_MOUSE=TCOD_EVENT_MOUSE_MOVE|TCOD_EVENT_MOUSE_PRESS|TCOD_EVENT_MOUSE_RELEASE, -/* #ifdef TCOD_TOUCH_INPUT */ - TCOD_EVENT_FINGER_MOVE=32, - TCOD_EVENT_FINGER_PRESS=64, - TCOD_EVENT_FINGER_RELEASE=128, - TCOD_EVENT_FINGER=TCOD_EVENT_FINGER_MOVE|TCOD_EVENT_FINGER_PRESS|TCOD_EVENT_FINGER_RELEASE, -/* #endif */ - TCOD_EVENT_ANY=TCOD_EVENT_KEY|TCOD_EVENT_MOUSE|TCOD_EVENT_FINGER, -} TCOD_event_t; -TCODLIB_API TCOD_event_t TCOD_sys_wait_for_event(int eventMask, TCOD_key_t *key, TCOD_mouse_t *mouse, bool flush); -TCODLIB_API TCOD_event_t TCOD_sys_check_for_event(int eventMask, TCOD_key_t *key, TCOD_mouse_t *mouse); -#endif - -/* filesystem stuff */ -TCODLIB_API bool TCOD_sys_create_directory(const char *path); -TCODLIB_API bool TCOD_sys_delete_file(const char *path); -TCODLIB_API bool TCOD_sys_delete_directory(const char *path); -TCODLIB_API bool TCOD_sys_is_directory(const char *path); -TCODLIB_API TCOD_list_t TCOD_sys_get_directory_content(const char *path, const char *pattern); -TCODLIB_API bool TCOD_sys_file_exists(const char * filename, ...); -TCODLIB_API bool TCOD_sys_read_file(const char *filename, unsigned char **buf, size_t *size); -TCODLIB_API bool TCOD_sys_write_file(const char *filename, unsigned char *buf, uint32_t size); - -#ifndef TCOD_BARE -/* clipboard */ -TCODLIB_API bool TCOD_sys_clipboard_set(const char *value); -TCODLIB_API char *TCOD_sys_clipboard_get(void); -#endif - -/* thread stuff */ -typedef void *TCOD_thread_t; -typedef void *TCOD_semaphore_t; -typedef void *TCOD_mutex_t; -typedef void *TCOD_cond_t; -/* threads */ -TCODLIB_API TCOD_thread_t TCOD_thread_new(int (*func)(void *), void *data); -TCODLIB_API void TCOD_thread_delete(TCOD_thread_t th); -TCODLIB_API int TCOD_sys_get_num_cores(void); -TCODLIB_API void TCOD_thread_wait(TCOD_thread_t th); -/* mutex */ -TCODLIB_API TCOD_mutex_t TCOD_mutex_new(void); -TCODLIB_API void TCOD_mutex_in(TCOD_mutex_t mut); -TCODLIB_API void TCOD_mutex_out(TCOD_mutex_t mut); -TCODLIB_API void TCOD_mutex_delete(TCOD_mutex_t mut); -/* semaphore */ -TCODLIB_API TCOD_semaphore_t TCOD_semaphore_new(int initVal); -TCODLIB_API void TCOD_semaphore_lock(TCOD_semaphore_t sem); -TCODLIB_API void TCOD_semaphore_unlock(TCOD_semaphore_t sem); -TCODLIB_API void TCOD_semaphore_delete( TCOD_semaphore_t sem); -/* condition */ -TCODLIB_API TCOD_cond_t TCOD_condition_new(void); -TCODLIB_API void TCOD_condition_signal(TCOD_cond_t sem); -TCODLIB_API void TCOD_condition_broadcast(TCOD_cond_t sem); -TCODLIB_API void TCOD_condition_wait(TCOD_cond_t sem, TCOD_mutex_t mut); -TCODLIB_API void TCOD_condition_delete( TCOD_cond_t sem); -/* dynamic library */ -typedef void *TCOD_library_t; -TCODLIB_API TCOD_library_t TCOD_load_library(const char *path); -TCODLIB_API void * TCOD_get_function_address(TCOD_library_t library, const char *function_name); -TCODLIB_API void TCOD_close_library(TCOD_library_t); -/* SDL renderer callback */ -#ifndef TCOD_BARE -typedef void (*SDL_renderer_t) (void *sdl_renderer); -TCODLIB_API void TCOD_sys_register_SDL_renderer(SDL_renderer_t renderer); -#endif -#ifdef __cplusplus -} -#endif -#endif +/* +* libtcod +* Copyright (c) 2008-2018 Jice & Mingos & rmtew +* All rights reserved. +* +* Redistribution and use in source and binary forms, with or without +* modification, are permitted provided that the following conditions are met: +* * Redistributions of source code must retain the above copyright +* notice, this list of conditions and the following disclaimer. +* * Redistributions in binary form must reproduce the above copyright +* notice, this list of conditions and the following disclaimer in the +* documentation and/or other materials provided with the distribution. +* * The name of Jice or Mingos may not be used to endorse or promote +* products derived from this software without specific prior written +* permission. +* +* THIS SOFTWARE IS PROVIDED BY JICE, MINGOS AND RMTEW ``AS IS'' AND ANY +* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED +* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE +* DISCLAIMED. IN NO EVENT SHALL JICE, MINGOS OR RMTEW BE LIABLE FOR ANY +* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES +* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; +* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND +* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS +* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +*/ +#ifndef _TCOD_SYS_H +#define _TCOD_SYS_H + +#include "portability.h" +#include "list.h" +#include "image.h" +#include "mouse_types.h" + +#ifdef __cplusplus +extern "C" { +#endif +TCODLIB_API void TCOD_sys_startup(void); +TCODLIB_API void TCOD_sys_shutdown(void); + +#ifdef TCOD_OSUTIL_SUPPORT +TCODLIB_API uint32_t TCOD_sys_elapsed_milli(void); +TCODLIB_API float TCOD_sys_elapsed_seconds(void); +TCODLIB_API void TCOD_sys_sleep_milli(uint32_t val); +TCODLIB_API void TCOD_sys_set_fps(int val); +TCODLIB_API int TCOD_sys_get_fps(void); +TCODLIB_API float TCOD_sys_get_last_frame_length(void); +#endif + +#ifndef TCOD_BARE +TCODLIB_API void TCOD_sys_save_screenshot(const char *filename); +TCODLIB_API void TCOD_sys_force_fullscreen_resolution(int width, int height); +TCODLIB_API void TCOD_sys_set_renderer(TCOD_renderer_t renderer); +TCODLIB_API TCOD_renderer_t TCOD_sys_get_renderer(void); +TCODLIB_API void TCOD_sys_get_current_resolution(int *w, int *h); +TCODLIB_API void TCOD_sys_get_fullscreen_offsets(int *offx, int *offy); +TCODLIB_API void TCOD_sys_get_char_size(int *w, int *h); +#endif + +#ifdef TCOD_IMAGE_SUPPORT +TCODLIB_API void TCOD_sys_update_char(int asciiCode, int fontx, int fonty, TCOD_image_t img, int x, int y); +#endif + +#ifndef TCOD_BARE +TCODLIB_API void *TCOD_sys_get_SDL_window(void); +TCODLIB_API void *TCOD_sys_get_SDL_renderer(void); +#endif + +#ifndef TCOD_BARE +typedef enum { + TCOD_EVENT_NONE=0, + TCOD_EVENT_KEY_PRESS=1, + TCOD_EVENT_KEY_RELEASE=2, + TCOD_EVENT_KEY=TCOD_EVENT_KEY_PRESS|TCOD_EVENT_KEY_RELEASE, + TCOD_EVENT_MOUSE_MOVE=4, + TCOD_EVENT_MOUSE_PRESS=8, + TCOD_EVENT_MOUSE_RELEASE=16, + TCOD_EVENT_MOUSE=TCOD_EVENT_MOUSE_MOVE|TCOD_EVENT_MOUSE_PRESS|TCOD_EVENT_MOUSE_RELEASE, +/* #ifdef TCOD_TOUCH_INPUT */ + TCOD_EVENT_FINGER_MOVE=32, + TCOD_EVENT_FINGER_PRESS=64, + TCOD_EVENT_FINGER_RELEASE=128, + TCOD_EVENT_FINGER=TCOD_EVENT_FINGER_MOVE|TCOD_EVENT_FINGER_PRESS|TCOD_EVENT_FINGER_RELEASE, +/* #endif */ + TCOD_EVENT_ANY=TCOD_EVENT_KEY|TCOD_EVENT_MOUSE|TCOD_EVENT_FINGER, +} TCOD_event_t; +TCODLIB_API TCOD_event_t TCOD_sys_wait_for_event(int eventMask, TCOD_key_t *key, TCOD_mouse_t *mouse, bool flush); +TCODLIB_API TCOD_event_t TCOD_sys_check_for_event(int eventMask, TCOD_key_t *key, TCOD_mouse_t *mouse); +#endif + +/* filesystem stuff */ +TCOD_DEPRECATED_NOMESSAGE +TCODLIB_API bool TCOD_sys_create_directory(const char *path); +TCOD_DEPRECATED_NOMESSAGE +TCODLIB_API bool TCOD_sys_delete_file(const char *path); +TCOD_DEPRECATED_NOMESSAGE +TCODLIB_API bool TCOD_sys_delete_directory(const char *path); +TCOD_DEPRECATED_NOMESSAGE +TCODLIB_API bool TCOD_sys_is_directory(const char *path); +TCOD_DEPRECATED_NOMESSAGE +TCODLIB_API TCOD_list_t TCOD_sys_get_directory_content(const char *path, const char *pattern); +TCOD_DEPRECATED_NOMESSAGE +TCODLIB_API bool TCOD_sys_file_exists(const char * filename, ...); +TCOD_DEPRECATED_NOMESSAGE +TCODLIB_API bool TCOD_sys_read_file(const char *filename, unsigned char **buf, size_t *size); +TCOD_DEPRECATED_NOMESSAGE +TCODLIB_API bool TCOD_sys_write_file(const char *filename, unsigned char *buf, uint32_t size); + +#ifndef TCOD_BARE +/* clipboard */ +TCOD_DEPRECATED("Use the SDL2 API to handle the clipboard.") +TCODLIB_API bool TCOD_sys_clipboard_set(const char *value); +TCOD_DEPRECATED("Use the SDL2 API to handle the clipboard.") +TCODLIB_API char *TCOD_sys_clipboard_get(void); +#endif + +/* thread stuff */ +typedef void *TCOD_thread_t; +typedef void *TCOD_semaphore_t; +typedef void *TCOD_mutex_t; +typedef void *TCOD_cond_t; +/* threads */ +TCOD_DEPRECATED_NOMESSAGE +TCODLIB_API TCOD_thread_t TCOD_thread_new(int (*func)(void *), void *data); +TCOD_DEPRECATED_NOMESSAGE +TCODLIB_API void TCOD_thread_delete(TCOD_thread_t th); +TCOD_DEPRECATED_NOMESSAGE +TCODLIB_API int TCOD_sys_get_num_cores(void); +TCOD_DEPRECATED_NOMESSAGE +TCODLIB_API void TCOD_thread_wait(TCOD_thread_t th); +/* mutex */ +TCOD_DEPRECATED_NOMESSAGE +TCODLIB_API TCOD_mutex_t TCOD_mutex_new(void); +TCOD_DEPRECATED_NOMESSAGE +TCODLIB_API void TCOD_mutex_in(TCOD_mutex_t mut); +TCOD_DEPRECATED_NOMESSAGE +TCODLIB_API void TCOD_mutex_out(TCOD_mutex_t mut); +TCOD_DEPRECATED_NOMESSAGE +TCODLIB_API void TCOD_mutex_delete(TCOD_mutex_t mut); +/* semaphore */ +TCOD_DEPRECATED_NOMESSAGE +TCODLIB_API TCOD_semaphore_t TCOD_semaphore_new(int initVal); +TCOD_DEPRECATED_NOMESSAGE +TCODLIB_API void TCOD_semaphore_lock(TCOD_semaphore_t sem); +TCOD_DEPRECATED_NOMESSAGE +TCODLIB_API void TCOD_semaphore_unlock(TCOD_semaphore_t sem); +TCOD_DEPRECATED_NOMESSAGE +TCODLIB_API void TCOD_semaphore_delete( TCOD_semaphore_t sem); +/* condition */ +TCOD_DEPRECATED_NOMESSAGE +TCODLIB_API TCOD_cond_t TCOD_condition_new(void); +TCOD_DEPRECATED_NOMESSAGE +TCODLIB_API void TCOD_condition_signal(TCOD_cond_t sem); +TCOD_DEPRECATED_NOMESSAGE +TCODLIB_API void TCOD_condition_broadcast(TCOD_cond_t sem); +TCOD_DEPRECATED_NOMESSAGE +TCODLIB_API void TCOD_condition_wait(TCOD_cond_t sem, TCOD_mutex_t mut); +TCOD_DEPRECATED_NOMESSAGE +TCODLIB_API void TCOD_condition_delete( TCOD_cond_t sem); +/* dynamic library */ +typedef void *TCOD_library_t; +TCOD_DEPRECATED_NOMESSAGE +TCODLIB_API TCOD_library_t TCOD_load_library(const char *path); +TCOD_DEPRECATED_NOMESSAGE +TCODLIB_API void * TCOD_get_function_address(TCOD_library_t library, const char *function_name); +TCOD_DEPRECATED_NOMESSAGE +TCODLIB_API void TCOD_close_library(TCOD_library_t); +/* SDL renderer callback */ +#ifndef TCOD_BARE +typedef void (*SDL_renderer_t) (void *sdl_renderer); +TCODLIB_API void TCOD_sys_register_SDL_renderer(SDL_renderer_t renderer); +#endif +#ifdef __cplusplus +} +#endif +#endif diff --git a/tcod_sys/libtcod/include/sys.hpp b/tcod_sys/libtcod/src/libtcod/sys.hpp similarity index 97% rename from tcod_sys/libtcod/include/sys.hpp rename to tcod_sys/libtcod/src/libtcod/sys.hpp index c344ef47d..0363c585e 100644 --- a/tcod_sys/libtcod/include/sys.hpp +++ b/tcod_sys/libtcod/src/libtcod/sys.hpp @@ -1,561 +1,561 @@ -/* -* libtcod -* Copyright (c) 2008-2018 Jice & Mingos & rmtew -* All rights reserved. -* -* Redistribution and use in source and binary forms, with or without -* modification, are permitted provided that the following conditions are met: -* * Redistributions of source code must retain the above copyright -* notice, this list of conditions and the following disclaimer. -* * Redistributions in binary form must reproduce the above copyright -* notice, this list of conditions and the following disclaimer in the -* documentation and/or other materials provided with the distribution. -* * The name of Jice or Mingos may not be used to endorse or promote -* products derived from this software without specific prior written -* permission. -* -* THIS SOFTWARE IS PROVIDED BY JICE, MINGOS AND RMTEW ``AS IS'' AND ANY -* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED -* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE -* DISCLAIMED. IN NO EVENT SHALL JICE, MINGOS OR RMTEW BE LIABLE FOR ANY -* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES -* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; -* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND -* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS -* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. -*/ -#ifndef _TCOD_SYS_HPP -#define _TCOD_SYS_HPP - -#include "image.hpp" -#include "mouse.hpp" -#include "sys.h" -/** - - @PageName system - @PageCategory Core - @PageTitle System layer - @PageDesc This toolkit contains some system specific miscellaneous utilities. Use them is you want your code to be easily portable. - */ - -class TCODLIB_API ITCODSDLRenderer { -public : - virtual ~ITCODSDLRenderer() {} - virtual void render(void *sdlSurface) = 0; -}; - -class TCODLIB_API TCODSystem { -public : - /** - @PageName system_time - @PageFather system - @PageTitle High precision time functions - @PageDesc These are functions specifically aimed at real time game development. - @FuncTitle Limit the frames per second - @FuncDesc The setFps function allows you to limit the number of frames per second. - If a frame is rendered faster than expected, the TCOD_console_flush function will wait so that the frame rate never exceed this value. - You can call this function during your game initialization. - You can dynamically change the frame rate. Just call this function once again. - You should always limit the frame rate, except during benchmarks, else your game will use 100% of the CPU power - @Cpp static void TCODSystem::setFps(int val) - @C void TCOD_sys_set_fps(int val) - @Py sys_set_fps(val) - @C# static void TCODSystem::setFps(int val) - @Lua tcod.system.setFps(val) - @Param val Maximum number of frames per second. 0 means unlimited frame rate. - */ - static void setFps(int val); - - /** - @PageName system_time - @FuncTitle Get the number of frames rendered during the last second - @FuncDesc The value returned by this function is updated every second. - @Cpp static int TCODSystem::getFps() - @C int TCOD_sys_get_fps() - @Py sys_get_fps() - @C# static int TCODSystem::getFps() - @Lua tcod.system.getFps() - */ - static int getFps(); - - /** - @PageName system_time - @FuncTitle Get the duration of the last frame - @FuncDesc This function returns the length in seconds of the last rendered frame. - You can use this value to update every time dependent object in the world. - @Cpp static float TCODSystem::getLastFrameLength() - @C float TCOD_sys_get_last_frame_length() - @Py sys_get_last_frame_length() - @C# static float TCODSystem::getLastFrameLength() - @Lua tcod.system.getLastFrameLength() - @CppEx - // moving an objet at 5 console cells per second - float x=0,y=0; // object coordinates - x += 5 * TCODSystem::getLastFrameLength(); - TCODConsole::root->putChar((int)(x),(int)(y),'X'); - @CEx - float x=0,y=0; - x += 5 * TCOD_sys_get_last_frame_length(); - TCOD_console_put_char(NULL,(int)(x),(int)(y),'X'); - @PyEx - x=0.0 - y=0.0 - x += 5 * libtcod.sys_get_last_frame_length() - libtcod.console_put_char(0,int(x),int(y),'X') - @LuaEx - -- moving an objet at 5 console cells per second - x=0 - y=0 -- object coordinates - x = x + 5 * tcod.system.getLastFrameLength() - libtcod.TCODConsole_root:putChar(x,y,'X') - */ - static float getLastFrameLength(); - -#ifdef TCOD_OSUTIL_SUPPORT - /** - @PageName system_time - @FuncTitle Pause the program - @FuncDesc Use this function to stop the program execution for a specified number of milliseconds. - @Cpp static void TCODSystem::sleepMilli(uint32_t val) - @C void TCOD_sys_sleep_milli(uint32_t val) - @Py sys_sleep_milli(val) - @C# static void TCODSystem::sleepMilli(uint val) - @Lua tcod.system.sleepMilli(val) - @Param val number of milliseconds before the function returns - */ - static void sleepMilli(uint32_t val); - - /** - @PageName system_time - @FuncTitle Get global timer in milliseconds - @FuncDesc This function returns the number of milliseconds since the program has started. - @Cpp static uint32_t TCODSystem::getElapsedMilli() - @C uint32_t TCOD_sys_elapsed_milli() - @Py sys_elapsed_milli() - @C# static uint TCODSystem::getElapsedMilli() - @Lua tcod.system.getElapsedMilli() - */ - static uint32_t getElapsedMilli(); - - /** - @PageName system_time - @FuncTitle Get global timer in seconds - @FuncDesc This function returns the number of seconds since the program has started. - @Cpp static float TCODSystem::getElapsedSeconds() - @C float TCOD_sys_elapsed_seconds() - @Py sys_elapsed_seconds() - @C# static float TCODSystem::getElapsedSeconds() - @Lua tcod.system.getElapsedSeconds() - */ - static float getElapsedSeconds(); -#endif - -#ifdef TCOD_CONSOLE_SUPPORT - /** - @PageName console_blocking_input - @FuncTitle Waiting for any event (mouse or keyboard) - @FuncDesc This function waits for an event from the user. The eventMask shows what events we're waiting for. - The return value indicate what event was actually triggered. Values in key and mouse structures are updated accordingly. - If flush is false, the function waits only if there are no pending events, else it returns the first event in the buffer. - @Cpp typedef enum { - TCOD_EVENT_NONE=0, - TCOD_EVENT_KEY_PRESS=1, - TCOD_EVENT_KEY_RELEASE=2, - TCOD_EVENT_KEY=TCOD_EVENT_KEY_PRESS|TCOD_EVENT_KEY_RELEASE, - TCOD_EVENT_MOUSE_MOVE=4, - TCOD_EVENT_MOUSE_PRESS=8, - TCOD_EVENT_MOUSE_RELEASE=16, - TCOD_EVENT_MOUSE=TCOD_EVENT_MOUSE_MOVE|TCOD_EVENT_MOUSE_PRESS|TCOD_EVENT_MOUSE_RELEASE, - TCOD_EVENT_ANY=TCOD_EVENT_KEY|TCOD_EVENT_MOUSE, - } TCOD_event_t; - static TCOD_event_t TCODSystem::waitForEvent(int eventMask, TCOD_key_t *key, TCOD_mouse_t *mouse, bool flush) - @C TCOD_event_t TCOD_sys_wait_for_event(int eventMask, TCOD_key_t *key, TCOD_mouse_t *mouse, bool flush) - @Py sys_wait_for_event(eventMask,key,mouse,flush) - @Param eventMask event types to wait for (other types are discarded) - @Param key updated in case of a key event. Can be null if eventMask contains no key event type - @Param mouse updated in case of a mouse event. Can be null if eventMask contains no mouse event type - @Param flush if true, all pending events are flushed from the buffer. Else, return the first available event - @CppEx - TCOD_key_t key; - TCOD_mouse_t mouse; - TCOD_event_t ev = TCODSystem::waitForEvent(TCOD_EVENT_ANY,&key,&mouse,true); - if ( ev == TCOD_EVENT_KEY_PRESS && key.c == 'i' ) { ... open inventory ... } - @CEx - TCOD_key_t key; - TCOD_mouse_t mouse; - TCOD_event_t ev = TCOD_sys_wait_for_event(TCOD_EVENT_ANY,&key,&mouse,true); - if ( ev == TCOD_EVENT_KEY_PRESS && key.c == 'i' ) { ... open inventory ... } - */ - static TCOD_event_t waitForEvent(int eventMask, TCOD_key_t *key, TCOD_mouse_t *mouse, bool flush); - - /** - @PageName console_non_blocking_input - @FuncTitle Checking for any event (mouse or keyboard) - @FuncDesc This function checks if an event from the user is in the buffer. The eventMask shows what events we're waiting for. - The return value indicate what event was actually found. Values in key and mouse structures are updated accordingly. - @Cpp typedef enum { - TCOD_EVENT_KEY_PRESS=1, - TCOD_EVENT_KEY_RELEASE=2, - TCOD_EVENT_KEY=TCOD_EVENT_KEY_PRESS|TCOD_EVENT_KEY_RELEASE, - TCOD_EVENT_MOUSE_MOVE=4, - TCOD_EVENT_MOUSE_PRESS=8, - TCOD_EVENT_MOUSE_RELEASE=16, - TCOD_EVENT_MOUSE=TCOD_EVENT_MOUSE_MOVE|TCOD_EVENT_MOUSE_PRESS|TCOD_EVENT_MOUSE_RELEASE, - TCOD_EVENT_ANY=TCOD_EVENT_KEY|TCOD_EVENT_MOUSE, - } TCOD_event_t; - static TCOD_event_t TCODSystem::checkForEvent(int eventMask, TCOD_key_t *key, TCOD_mouse_t *mouse) - @C TCOD_event_t TCOD_sys_check_for_event(int eventMask, TCOD_key_t *key, TCOD_mouse_t *mouse) - @Py sys_check_for_event(eventMask,key,mouse) - @Param eventMask event types to wait for (other types are discarded) - @Param key updated in case of a key event. Can be null if eventMask contains no key event type - @Param mouse updated in case of a mouse event. Can be null if eventMask contains no mouse event type - @CppEx - TCOD_key_t key; - TCOD_mouse_t mouse; - TCOD_event_t ev = TCODSystem::checkForEvent(TCOD_EVENT_ANY,&key,&mouse); - if ( ev == TCOD_EVENT_KEY_PRESS && key.c == 'i' ) { ... open inventory ... } - @CEx - TCOD_key_t key; - TCOD_mouse_t mouse; - TCOD_event_t ev = TCOD_sys_check_for_event(TCOD_EVENT_ANY,&key,&mouse); - if ( ev == TCOD_EVENT_KEY_PRESS && key.c == 'i' ) { ... open inventory ... } - */ - static TCOD_event_t checkForEvent(int eventMask, TCOD_key_t *key, TCOD_mouse_t *mouse); -#endif - -#ifndef TCOD_BARE - /** - @PageName system_screenshots - @PageFather system - @PageTitle Easy screenshots - @FuncDesc This function allows you to save the current game screen in a png file, or possibly a bmp file if you provide a filename ending with .bmp. - @Cpp static void TCODSystem::saveScreenshot(const char *filename) - @C void TCOD_sys_save_screenshot(const char *filename) - @Py sys_save_screenshot(filename) - @C# static void TCODSystem::saveScreenshot(string filename); - @Lua tcod.system.saveScreenshot(filename) - @Param filename Name of the file. If NULL, a filename is automatically generated with the form "./screenshotNNN.png", NNN being the first free number (if a file named screenshot000.png already exist, screenshot001.png will be used, and so on...). - */ - static void saveScreenshot(const char *filename); -#endif - - /** - @PageName system_filesystem - @PageFather system - @PageTitle Filesystem utilities - @PageDesc Those are a few function that cannot be easily implemented in a portable way in C/C++. They have no Python wrapper since Python provides its own builtin functions. All those functions return false if an error occurred. - @FuncTitle Create a directory - @Cpp static bool TCODSystem::createDirectory(const char *path) - @C bool TCOD_sys_create_directory(const char *path) - @Param path Directory path. The immediate father directory (/..) must exist and be writable. - */ - static bool createDirectory(const char *path); - - /** - @PageName system_filesystem - @FuncTitle Delete an empty directory - @Cpp static bool TCODSystem::deleteDirectory(const char *path) - @C bool TCOD_sys_delete_directory(const char *path) - @Param path directory path. This directory must exist, be writable and empty - */ - static bool deleteDirectory(const char *path); - - /** - @PageName system_filesystem - @FuncTitle Delete a file - @Cpp static bool TCODSystem::deleteFile(const char *path) - @C bool TCOD_sys_delete_file(const char *path) - @Param path File path. This file must exist and be writable. - */ - static bool deleteFile(const char *path); - - /** - @PageName system_filesystem - @FuncTitle Check if a path is a directory - @Cpp static bool TCODSystem::isDirectory(const char *path) - @C bool TCOD_sys_is_directory(const char *path) - @Param path a path to check - */ - static bool isDirectory(const char *path); - - /** - @PageName system_filesystem - @FuncTitle List files in a directory - @FuncDesc To get the list of entries in a directory (including sub-directories, except . and ..). - The returned list is allocated by the function and must be deleted by you. All the const char * inside must be also freed with TCODList::clearAndDelete. - @Cpp static TCODList TCODSystem::getDirectoryContent(const char *path, const char *pattern) - @C TCOD_list_t TCOD_sys_get_directory_content(const char *path) - @Param path a directory - @Param pattern If NULL or empty, returns all directory entries. Else returns only entries matching the pattern. The pattern is NOT a regular expression. It can only handle one '*' wildcard. Examples : *.png, saveGame*, font*.png - */ - static TCOD_list_t getDirectoryContent(const char *path, const char *pattern); - - /** - @PageName system_filesystem - @FuncTitle Check if a given file exists - @FuncDesc In order to check whether a given file exists in the filesystem. Useful for detecting errors caused by missing files. - @Cpp static bool TCODSystem::fileExists(const char *filename, ...) - @C bool TCOD_sys_file_exists(const char * filename, ...) - @Param filename the file name, using printf-like formatting - @Param ... optional arguments for filename formatting - @CppEx - if (!TCODSystem::fileExists("myfile.%s","txt")) { - fprintf(stderr,"no such file!"); - } - @CEx - if (!TCOD_sys_file_exists("myfile.%s","txt")) { - fprintf(stderr,"no such file!"); - } - */ - static bool fileExists(const char * filename, ...); - /** - @PageName system_filesystem - @FuncTitle Read the content of a file into memory - @FuncDesc This is a portable function to read the content of a file from disk or from the application apk (android). - buf must be freed with free(buf). - @Cpp static bool TCODSystem::readFile(const char *filename, unsigned char **buf, uint32_t *size) - @C bool TCOD_sys_read_file(const char *filename, unsigned char **buf, uint32_t *size) - @Param filename the file name - @Param buf a buffer to be allocated and filled with the file content - @Param size the size of the allocated buffer. - @CppEx - unsigned char *buf; - uint32_t size; - if (TCODSystem::readFile("myfile.dat",&buf,&size)) { - // do something with buf - free(buf); - } - @CEx - if (TCOD_sys_read_file("myfile.dat",&buf,&size)) { - // do something with buf - free(buf); - } - */ - static bool readFile(const char *filename, unsigned char **buf, size_t *size); - /** - @PageName system_filesystem - @FuncTitle Write the content of a memory buffer to a file - @FuncDesc This is a portable function to write some data to a file. - @Cpp static bool TCODSystem::writeFile(const char *filename, unsigned char *buf, uint32_t size) - @C bool TCOD_sys_write_file(const char *filename, unsigned char *buf, uint32_t size) - @Param filename the file name - @Param buf a buffer containing the data to write - @Param size the number of bytes to write. - @CppEx - TCODSystem::writeFile("myfile.dat",buf,size)); - @CEx - TCOD_sys_write_file("myfile.dat",buf,size)); - */ - static bool writeFile(const char *filename, unsigned char *buf, uint32_t size); - /** - @PageName system_sdlcbk - @PageFather system - @PageTitle Draw custom graphics on top of the root console - @PageDesc You can register a callback that will be called after the libtcod rendering phase, but before the screen buffer is swapped. This callback receives the screen SDL_Surface reference. - This makes it possible to use any SDL drawing functions (including openGL) on top of the libtcod console. - @FuncTitle Render custom graphics - @FuncDesc To disable the custom renderer, call the same method with a NULL parameter. - Note that to keep libtcod from requiring the SDL headers, the callback parameter is a void pointer. You have to include SDL headers and cast it to SDL_Surface in your code. - @Cpp - class TCODLIB_API ITCODSDLRenderer { - public : - virtual void render(void *sdlSurface) = 0; - }; - static void TCODSystem::registerSDLRenderer(ITCODSDLRenderer *callback); - @C - typedef void (*SDL_renderer_t) (void *sdl_surface); - void TCOD_sys_register_SDL_renderer(SDL_renderer_t callback) - @Py - def renderer ( sdl_surface ) : ... - TCOD_sys_register_SDL_renderer( callback ) - @Param callback The renderer to call before swapping the screen buffer. If NULL, custom rendering is disabled - @CppEx - class MyRenderer : public ITCODSDLRenderer { - public : - void render(void *sdlSurface) { - SDL_Surface *s = (SDL_Surface *)sdlSurface; - ... draw something on s - } - }; - TCODSystem::registerSDLRenderer(new MyRenderer()); - @CEx - void my_renderer( void *sdl_surface ) { - SDL_Surface *s = (SDL_Surface *)sdl_surface; - ... draw something on s - } - TCOD_sys_register_SDL_renderer(my_renderer); - @Py - def my_renderer(sdl_surface) : - ... draw something on sdl_surface using pygame - libtcod.sys_register_SDL_renderer(my_renderer) - */ - static void registerSDLRenderer(ITCODSDLRenderer *renderer); - - /** - @PageName system_sdlcbk - @FuncTitle Managing screen redraw - @FuncDesc libtcod is not aware of the part of the screen your SDL renderer has updated. If no change occurred in the console, it won't redraw them except if you tell him to do so with this function - @Cpp void TCODConsole::setDirty(int x, int y, int w, int h) - @C void TCOD_console_set_dirty(int x, int y, int w, int h) - @Py TCOD_console_set_dirty(x, y, w, h) - @Param x,y,w,h Part of the root console you want to redraw even if nothing has changed in the console back/fore/char. - */ - -#ifndef TCOD_BARE - /** - @PageName system_misc - @PageFather system - @PageTitle Miscellaneous utilities - @FuncTitle Using a custom resolution for the fullscreen mode - @FuncDesc This function allows you to force the use of a specific resolution in fullscreen mode. - The default resolution depends on the root console size and the font character size. - @Cpp static void TCODSystem::forceFullscreenResolution(int width, int height) - @C void TCOD_sys_force_fullscreen_resolution(int width, int height) - @Py sys_force_fullscreen_resolution(width, height) - @C# static void TCODSystem::forceFullscreenResolution(int width, int height); - @Lua tcod.system.forceFullscreenResolution(width,height) - @Param width,height Resolution to use when switching to fullscreen. - Will use the smallest available resolution so that : - resolution width >= width and resolution width >= root console width * font char width - resolution width >= height and resolution height >= root console height * font char height - @CppEx - TCODSystem::forceFullscreenResolution(800,600); // use 800x600 in fullscreen instead of 640x400 - TCODConsole::initRoot(80,50,"",true); // 80x50 console with 8x8 char => 640x400 default resolution - @CEx - TCOD_sys_force_fullscreen_resolution(800,600); - TCOD_console_init_root(80,50,"",true); - @PyEx - libtcod.sys_force_fullscreen_resolution(800,600) - libtcod.console_init_root(80,50,"",True) - @LuaEx - tcod.system.forceFullscreenResolution(800,600) -- use 800x600 in fullscreen instead of 640x400 - tcod.console.initRoot(80,50,"",true) -- 80x50 console with 8x8 char => 640x400 default resolution - */ - static void forceFullscreenResolution(int width, int height); - - /** - @PageName system_misc - @FuncTitle Get current resolution - @FuncDesc You can get the current screen resolution with getCurrentResolution. You can use it for example to get the desktop resolution before initializing the root console. - @Cpp static void TCODSystem::getCurrentResolution(int *width, int *height) - @C void TCOD_sys_get_current_resolution(int *width, int *height) - @Py sys_get_current_resolution() # returns w,h - @C# static void TCODSystem::getCurrentResolution(out int w, out int h); - @Param width,height contains current resolution when the function returns - */ - static void getCurrentResolution(int *w, int *h); - /** - @PageName system_misc - @FuncTitle Get fullscreen offset - @FuncDesc If the fullscreen resolution does not matches the console size in pixels, black borders are added. This function returns the position in pixels of the console top left corner in the screen. - @Cpp static void TCODSystem::getFullscreenOffsets(int *offx, int *offy) - @C void TCOD_sys_get_fullscreen_offsets(int *offx, int *offy) - @C# static void TCODSystem::getFullscreenOffsets(out int offx, out int offy); - @Param offx,offy contains the position of the console on the screen when using fullscreen mode. - */ - static void getFullscreenOffsets(int *offx, int *offy); - - /** - @PageName system_misc - @FuncTitle Get the font size - @FuncDesc You can get the size of the characters in the font - @Cpp static void TCODSystem::getCharSize(int *width, int *height) - @C void TCOD_sys_get_char_size(int *width, int *height) - @Py sys_get_char_size() # returns w,h - @C# static void TCODSystem::getCharSize(out int w, out int h); - @Param width,height contains a character size when the function returns - */ - static void getCharSize(int *w, int *h); - - /** - @PageName system_misc - @FuncTitle Dynamically updating the font bitmap - @FuncDesc You can dynamically change the bitmap of a character in the font. All cells using this ascii code will be updated at next flush call. - @Cpp static void TCODSystem::updateChar(int asciiCode, int fontx, int fonty,const TCODImage *img,int x,int y) - @C void TCOD_sys_update_char(int asciiCode, int fontx, int fonty, TCOD_image_t img, int x, int y) - @Py sys_update_char(asciiCode,fontx,fonty,img,x,y) - @Param asciiCode ascii code corresponding to the character to update - @Param fontx,fonty coordinate of the character in the bitmap font (in characters, not pixels) - @Param img image containing the new character bitmap - @Param x,y position in pixels of the top-left corner of the character in the image - */ - static void updateChar(int asciiCode, int fontx, int fonty,const TCODImage *img,int x,int y); -#endif - -#ifndef TCOD_BARE - /** - @PageName system_misc - @FuncTitle Dynamically change libtcod's internal renderer - @FuncDesc As of 1.5.1, libtcod contains 3 different renderers : - * SDL : historic libtcod renderer. Should work and be pretty fast everywhere - * OpenGL : requires OpenGL compatible video card. Might be much faster or much slower than SDL, depending on the drivers - * GLSDL : requires OpenGL 1.4 compatible video card with GL_ARB_shader_objects extension. Blazing fast if you have the proper hardware and drivers. - This function switches the current renderer dynamically. - @Cpp static void TCODSystem::setRenderer(TCOD_renderer_t renderer) - @C void TCOD_sys_set_renderer(TCOD_renderer_t renderer) - @Py sys_set_renderer(renderer) - @C# static void TCODSystem::setRenderer(TCODRendererType renderer); - @Param renderer Either TCOD_RENDERER_GLSL, TCOD_RENDERER_OPENGL or TCOD_RENDERER_SDL - */ - static void setRenderer(TCOD_renderer_t renderer); - - /** - @PageName system_misc - @FuncTitle Get the current internal renderer - @Cpp static TCOD_renderer_t TCODSystem::getRenderer() - @C TCOD_renderer_t TCOD_sys_get_renderer() - @Py sys_get_renderer() - @C# static TCODRendererType TCODSystem::getRenderer(); - */ - static TCOD_renderer_t getRenderer(); - - /** - @PageName system_clipboard - @PageTitle Clipboard integration - @PageDesc With these functions, you can copy data in your operating system's clipboard from the game or retrieve data from the clipboard. - @PageFather system - @FuncTitle Set current clipboard contents - @FuncDesc Takes UTF-8 text and copies it into the system clipboard. On Linux, because an application cannot access the system clipboard unless a window is open, if no window is open the call will do nothing. - @Cpp static bool TCODSystem::setClipboard(const char *value) - @C bool TCOD_sys_clipboard_set(const char *value) - @Py sys_clipboard_set(value) - @Param value UTF-8 text to copy into the clipboard - */ - static bool setClipboard(const char *value); - - /** - @PageName system_clipboard - @FuncTitle Get current clipboard contents - @FuncDesc Returns the UTF-8 text currently in the system clipboard. On Linux, because an application cannot access the system clipboard unless a window is open, if no window is open an empty string will be returned. For C and C++, note that the pointer is borrowed, and libtcod will take care of freeing the memory. - @Cpp static char *TCODSystem::getClipboard() - @C char *TCOD_sys_clipboard_get() - @Py sys_clipboard_get() # Returns UTF-8 string - */ - static char *getClipboard(); -#endif - - // thread stuff - static int getNumCores(); - static TCOD_thread_t newThread(int (*func)(void *), void *data); - static void deleteThread(TCOD_thread_t th); - static void waitThread(TCOD_thread_t th); - // mutex - static TCOD_mutex_t newMutex(); - static void mutexIn(TCOD_mutex_t mut); - static void mutexOut(TCOD_mutex_t mut); - static void deleteMutex(TCOD_mutex_t mut); - // semaphore - static TCOD_semaphore_t newSemaphore(int initVal); - static void lockSemaphore(TCOD_semaphore_t sem); - static void unlockSemaphore(TCOD_semaphore_t sem); - static void deleteSemaphore( TCOD_semaphore_t sem); - // condition - static TCOD_cond_t newCondition(); - static void signalCondition(TCOD_cond_t sem); - static void broadcastCondition(TCOD_cond_t sem); - static void waitCondition(TCOD_cond_t sem, TCOD_mutex_t mut); - static void deleteCondition( TCOD_cond_t sem); -}; - -#endif +/* +* libtcod +* Copyright (c) 2008-2018 Jice & Mingos & rmtew +* All rights reserved. +* +* Redistribution and use in source and binary forms, with or without +* modification, are permitted provided that the following conditions are met: +* * Redistributions of source code must retain the above copyright +* notice, this list of conditions and the following disclaimer. +* * Redistributions in binary form must reproduce the above copyright +* notice, this list of conditions and the following disclaimer in the +* documentation and/or other materials provided with the distribution. +* * The name of Jice or Mingos may not be used to endorse or promote +* products derived from this software without specific prior written +* permission. +* +* THIS SOFTWARE IS PROVIDED BY JICE, MINGOS AND RMTEW ``AS IS'' AND ANY +* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED +* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE +* DISCLAIMED. IN NO EVENT SHALL JICE, MINGOS OR RMTEW BE LIABLE FOR ANY +* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES +* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; +* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND +* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS +* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +*/ +#ifndef _TCOD_SYS_HPP +#define _TCOD_SYS_HPP + +#include "image.hpp" +#include "mouse.hpp" +#include "sys.h" +/** + + @PageName system + @PageCategory Core + @PageTitle System layer + @PageDesc This toolkit contains some system specific miscellaneous utilities. Use them is you want your code to be easily portable. + */ + +class TCODLIB_API ITCODSDLRenderer { +public : + virtual ~ITCODSDLRenderer() {} + virtual void render(void *sdlSurface) = 0; +}; + +class TCODLIB_API TCODSystem { +public : + /** + @PageName system_time + @PageFather system + @PageTitle High precision time functions + @PageDesc These are functions specifically aimed at real time game development. + @FuncTitle Limit the frames per second + @FuncDesc The setFps function allows you to limit the number of frames per second. + If a frame is rendered faster than expected, the TCOD_console_flush function will wait so that the frame rate never exceed this value. + You can call this function during your game initialization. + You can dynamically change the frame rate. Just call this function once again. + You should always limit the frame rate, except during benchmarks, else your game will use 100% of the CPU power + @Cpp static void TCODSystem::setFps(int val) + @C void TCOD_sys_set_fps(int val) + @Py sys_set_fps(val) + @C# static void TCODSystem::setFps(int val) + @Lua tcod.system.setFps(val) + @Param val Maximum number of frames per second. 0 means unlimited frame rate. + */ + static void setFps(int val); + + /** + @PageName system_time + @FuncTitle Get the number of frames rendered during the last second + @FuncDesc The value returned by this function is updated every second. + @Cpp static int TCODSystem::getFps() + @C int TCOD_sys_get_fps() + @Py sys_get_fps() + @C# static int TCODSystem::getFps() + @Lua tcod.system.getFps() + */ + static int getFps(); + + /** + @PageName system_time + @FuncTitle Get the duration of the last frame + @FuncDesc This function returns the length in seconds of the last rendered frame. + You can use this value to update every time dependent object in the world. + @Cpp static float TCODSystem::getLastFrameLength() + @C float TCOD_sys_get_last_frame_length() + @Py sys_get_last_frame_length() + @C# static float TCODSystem::getLastFrameLength() + @Lua tcod.system.getLastFrameLength() + @CppEx + // moving an objet at 5 console cells per second + float x=0,y=0; // object coordinates + x += 5 * TCODSystem::getLastFrameLength(); + TCODConsole::root->putChar((int)(x),(int)(y),'X'); + @CEx + float x=0,y=0; + x += 5 * TCOD_sys_get_last_frame_length(); + TCOD_console_put_char(NULL,(int)(x),(int)(y),'X'); + @PyEx + x=0.0 + y=0.0 + x += 5 * libtcod.sys_get_last_frame_length() + libtcod.console_put_char(0,int(x),int(y),'X') + @LuaEx + -- moving an objet at 5 console cells per second + x=0 + y=0 -- object coordinates + x = x + 5 * tcod.system.getLastFrameLength() + libtcod.TCODConsole_root:putChar(x,y,'X') + */ + static float getLastFrameLength(); + +#ifdef TCOD_OSUTIL_SUPPORT + /** + @PageName system_time + @FuncTitle Pause the program + @FuncDesc Use this function to stop the program execution for a specified number of milliseconds. + @Cpp static void TCODSystem::sleepMilli(uint32_t val) + @C void TCOD_sys_sleep_milli(uint32_t val) + @Py sys_sleep_milli(val) + @C# static void TCODSystem::sleepMilli(uint val) + @Lua tcod.system.sleepMilli(val) + @Param val number of milliseconds before the function returns + */ + static void sleepMilli(uint32_t val); + + /** + @PageName system_time + @FuncTitle Get global timer in milliseconds + @FuncDesc This function returns the number of milliseconds since the program has started. + @Cpp static uint32_t TCODSystem::getElapsedMilli() + @C uint32_t TCOD_sys_elapsed_milli() + @Py sys_elapsed_milli() + @C# static uint TCODSystem::getElapsedMilli() + @Lua tcod.system.getElapsedMilli() + */ + static uint32_t getElapsedMilli(); + + /** + @PageName system_time + @FuncTitle Get global timer in seconds + @FuncDesc This function returns the number of seconds since the program has started. + @Cpp static float TCODSystem::getElapsedSeconds() + @C float TCOD_sys_elapsed_seconds() + @Py sys_elapsed_seconds() + @C# static float TCODSystem::getElapsedSeconds() + @Lua tcod.system.getElapsedSeconds() + */ + static float getElapsedSeconds(); +#endif + +#ifdef TCOD_CONSOLE_SUPPORT + /** + @PageName console_blocking_input + @FuncTitle Waiting for any event (mouse or keyboard) + @FuncDesc This function waits for an event from the user. The eventMask shows what events we're waiting for. + The return value indicate what event was actually triggered. Values in key and mouse structures are updated accordingly. + If flush is false, the function waits only if there are no pending events, else it returns the first event in the buffer. + @Cpp typedef enum { + TCOD_EVENT_NONE=0, + TCOD_EVENT_KEY_PRESS=1, + TCOD_EVENT_KEY_RELEASE=2, + TCOD_EVENT_KEY=TCOD_EVENT_KEY_PRESS|TCOD_EVENT_KEY_RELEASE, + TCOD_EVENT_MOUSE_MOVE=4, + TCOD_EVENT_MOUSE_PRESS=8, + TCOD_EVENT_MOUSE_RELEASE=16, + TCOD_EVENT_MOUSE=TCOD_EVENT_MOUSE_MOVE|TCOD_EVENT_MOUSE_PRESS|TCOD_EVENT_MOUSE_RELEASE, + TCOD_EVENT_ANY=TCOD_EVENT_KEY|TCOD_EVENT_MOUSE, + } TCOD_event_t; + static TCOD_event_t TCODSystem::waitForEvent(int eventMask, TCOD_key_t *key, TCOD_mouse_t *mouse, bool flush) + @C TCOD_event_t TCOD_sys_wait_for_event(int eventMask, TCOD_key_t *key, TCOD_mouse_t *mouse, bool flush) + @Py sys_wait_for_event(eventMask,key,mouse,flush) + @Param eventMask event types to wait for (other types are discarded) + @Param key updated in case of a key event. Can be null if eventMask contains no key event type + @Param mouse updated in case of a mouse event. Can be null if eventMask contains no mouse event type + @Param flush if true, all pending events are flushed from the buffer. Else, return the first available event + @CppEx + TCOD_key_t key; + TCOD_mouse_t mouse; + TCOD_event_t ev = TCODSystem::waitForEvent(TCOD_EVENT_ANY,&key,&mouse,true); + if ( ev == TCOD_EVENT_KEY_PRESS && key.c == 'i' ) { ... open inventory ... } + @CEx + TCOD_key_t key; + TCOD_mouse_t mouse; + TCOD_event_t ev = TCOD_sys_wait_for_event(TCOD_EVENT_ANY,&key,&mouse,true); + if ( ev == TCOD_EVENT_KEY_PRESS && key.c == 'i' ) { ... open inventory ... } + */ + static TCOD_event_t waitForEvent(int eventMask, TCOD_key_t *key, TCOD_mouse_t *mouse, bool flush); + + /** + @PageName console_non_blocking_input + @FuncTitle Checking for any event (mouse or keyboard) + @FuncDesc This function checks if an event from the user is in the buffer. The eventMask shows what events we're waiting for. + The return value indicate what event was actually found. Values in key and mouse structures are updated accordingly. + @Cpp typedef enum { + TCOD_EVENT_KEY_PRESS=1, + TCOD_EVENT_KEY_RELEASE=2, + TCOD_EVENT_KEY=TCOD_EVENT_KEY_PRESS|TCOD_EVENT_KEY_RELEASE, + TCOD_EVENT_MOUSE_MOVE=4, + TCOD_EVENT_MOUSE_PRESS=8, + TCOD_EVENT_MOUSE_RELEASE=16, + TCOD_EVENT_MOUSE=TCOD_EVENT_MOUSE_MOVE|TCOD_EVENT_MOUSE_PRESS|TCOD_EVENT_MOUSE_RELEASE, + TCOD_EVENT_ANY=TCOD_EVENT_KEY|TCOD_EVENT_MOUSE, + } TCOD_event_t; + static TCOD_event_t TCODSystem::checkForEvent(int eventMask, TCOD_key_t *key, TCOD_mouse_t *mouse) + @C TCOD_event_t TCOD_sys_check_for_event(int eventMask, TCOD_key_t *key, TCOD_mouse_t *mouse) + @Py sys_check_for_event(eventMask,key,mouse) + @Param eventMask event types to wait for (other types are discarded) + @Param key updated in case of a key event. Can be null if eventMask contains no key event type + @Param mouse updated in case of a mouse event. Can be null if eventMask contains no mouse event type + @CppEx + TCOD_key_t key; + TCOD_mouse_t mouse; + TCOD_event_t ev = TCODSystem::checkForEvent(TCOD_EVENT_ANY,&key,&mouse); + if ( ev == TCOD_EVENT_KEY_PRESS && key.c == 'i' ) { ... open inventory ... } + @CEx + TCOD_key_t key; + TCOD_mouse_t mouse; + TCOD_event_t ev = TCOD_sys_check_for_event(TCOD_EVENT_ANY,&key,&mouse); + if ( ev == TCOD_EVENT_KEY_PRESS && key.c == 'i' ) { ... open inventory ... } + */ + static TCOD_event_t checkForEvent(int eventMask, TCOD_key_t *key, TCOD_mouse_t *mouse); +#endif + +#ifndef TCOD_BARE + /** + @PageName system_screenshots + @PageFather system + @PageTitle Easy screenshots + @FuncDesc This function allows you to save the current game screen in a png file, or possibly a bmp file if you provide a filename ending with .bmp. + @Cpp static void TCODSystem::saveScreenshot(const char *filename) + @C void TCOD_sys_save_screenshot(const char *filename) + @Py sys_save_screenshot(filename) + @C# static void TCODSystem::saveScreenshot(string filename); + @Lua tcod.system.saveScreenshot(filename) + @Param filename Name of the file. If NULL, a filename is automatically generated with the form "./screenshotNNN.png", NNN being the first free number (if a file named screenshot000.png already exist, screenshot001.png will be used, and so on...). + */ + static void saveScreenshot(const char *filename); +#endif + + /** + @PageName system_filesystem + @PageFather system + @PageTitle Filesystem utilities + @PageDesc Those are a few function that cannot be easily implemented in a portable way in C/C++. They have no Python wrapper since Python provides its own builtin functions. All those functions return false if an error occurred. + @FuncTitle Create a directory + @Cpp static bool TCODSystem::createDirectory(const char *path) + @C bool TCOD_sys_create_directory(const char *path) + @Param path Directory path. The immediate father directory (/..) must exist and be writable. + */ + static bool createDirectory(const char *path); + + /** + @PageName system_filesystem + @FuncTitle Delete an empty directory + @Cpp static bool TCODSystem::deleteDirectory(const char *path) + @C bool TCOD_sys_delete_directory(const char *path) + @Param path directory path. This directory must exist, be writable and empty + */ + static bool deleteDirectory(const char *path); + + /** + @PageName system_filesystem + @FuncTitle Delete a file + @Cpp static bool TCODSystem::deleteFile(const char *path) + @C bool TCOD_sys_delete_file(const char *path) + @Param path File path. This file must exist and be writable. + */ + static bool deleteFile(const char *path); + + /** + @PageName system_filesystem + @FuncTitle Check if a path is a directory + @Cpp static bool TCODSystem::isDirectory(const char *path) + @C bool TCOD_sys_is_directory(const char *path) + @Param path a path to check + */ + static bool isDirectory(const char *path); + + /** + @PageName system_filesystem + @FuncTitle List files in a directory + @FuncDesc To get the list of entries in a directory (including sub-directories, except . and ..). + The returned list is allocated by the function and must be deleted by you. All the const char * inside must be also freed with TCODList::clearAndDelete. + @Cpp static TCODList TCODSystem::getDirectoryContent(const char *path, const char *pattern) + @C TCOD_list_t TCOD_sys_get_directory_content(const char *path) + @Param path a directory + @Param pattern If NULL or empty, returns all directory entries. Else returns only entries matching the pattern. The pattern is NOT a regular expression. It can only handle one '*' wildcard. Examples : *.png, saveGame*, font*.png + */ + static TCOD_list_t getDirectoryContent(const char *path, const char *pattern); + + /** + @PageName system_filesystem + @FuncTitle Check if a given file exists + @FuncDesc In order to check whether a given file exists in the filesystem. Useful for detecting errors caused by missing files. + @Cpp static bool TCODSystem::fileExists(const char *filename, ...) + @C bool TCOD_sys_file_exists(const char * filename, ...) + @Param filename the file name, using printf-like formatting + @Param ... optional arguments for filename formatting + @CppEx + if (!TCODSystem::fileExists("myfile.%s","txt")) { + fprintf(stderr,"no such file!"); + } + @CEx + if (!TCOD_sys_file_exists("myfile.%s","txt")) { + fprintf(stderr,"no such file!"); + } + */ + static bool fileExists(const char * filename, ...); + /** + @PageName system_filesystem + @FuncTitle Read the content of a file into memory + @FuncDesc This is a portable function to read the content of a file from disk or from the application apk (android). + buf must be freed with free(buf). + @Cpp static bool TCODSystem::readFile(const char *filename, unsigned char **buf, uint32_t *size) + @C bool TCOD_sys_read_file(const char *filename, unsigned char **buf, uint32_t *size) + @Param filename the file name + @Param buf a buffer to be allocated and filled with the file content + @Param size the size of the allocated buffer. + @CppEx + unsigned char *buf; + uint32_t size; + if (TCODSystem::readFile("myfile.dat",&buf,&size)) { + // do something with buf + free(buf); + } + @CEx + if (TCOD_sys_read_file("myfile.dat",&buf,&size)) { + // do something with buf + free(buf); + } + */ + static bool readFile(const char *filename, unsigned char **buf, size_t *size); + /** + @PageName system_filesystem + @FuncTitle Write the content of a memory buffer to a file + @FuncDesc This is a portable function to write some data to a file. + @Cpp static bool TCODSystem::writeFile(const char *filename, unsigned char *buf, uint32_t size) + @C bool TCOD_sys_write_file(const char *filename, unsigned char *buf, uint32_t size) + @Param filename the file name + @Param buf a buffer containing the data to write + @Param size the number of bytes to write. + @CppEx + TCODSystem::writeFile("myfile.dat",buf,size)); + @CEx + TCOD_sys_write_file("myfile.dat",buf,size)); + */ + static bool writeFile(const char *filename, unsigned char *buf, uint32_t size); + /** + @PageName system_sdlcbk + @PageFather system + @PageTitle Draw custom graphics on top of the root console + @PageDesc You can register a callback that will be called after the libtcod rendering phase, but before the screen buffer is swapped. This callback receives the screen SDL_Surface reference. + This makes it possible to use any SDL drawing functions (including openGL) on top of the libtcod console. + @FuncTitle Render custom graphics + @FuncDesc To disable the custom renderer, call the same method with a NULL parameter. + Note that to keep libtcod from requiring the SDL headers, the callback parameter is a void pointer. You have to include SDL headers and cast it to SDL_Surface in your code. + @Cpp + class TCODLIB_API ITCODSDLRenderer { + public : + virtual void render(void *sdlSurface) = 0; + }; + static void TCODSystem::registerSDLRenderer(ITCODSDLRenderer *callback); + @C + typedef void (*SDL_renderer_t) (void *sdl_surface); + void TCOD_sys_register_SDL_renderer(SDL_renderer_t callback) + @Py + def renderer ( sdl_surface ) : ... + TCOD_sys_register_SDL_renderer( callback ) + @Param callback The renderer to call before swapping the screen buffer. If NULL, custom rendering is disabled + @CppEx + class MyRenderer : public ITCODSDLRenderer { + public : + void render(void *sdlSurface) { + SDL_Surface *s = (SDL_Surface *)sdlSurface; + ... draw something on s + } + }; + TCODSystem::registerSDLRenderer(new MyRenderer()); + @CEx + void my_renderer( void *sdl_surface ) { + SDL_Surface *s = (SDL_Surface *)sdl_surface; + ... draw something on s + } + TCOD_sys_register_SDL_renderer(my_renderer); + @Py + def my_renderer(sdl_surface) : + ... draw something on sdl_surface using pygame + libtcod.sys_register_SDL_renderer(my_renderer) + */ + static void registerSDLRenderer(ITCODSDLRenderer *renderer); + + /** + @PageName system_sdlcbk + @FuncTitle Managing screen redraw + @FuncDesc libtcod is not aware of the part of the screen your SDL renderer has updated. If no change occurred in the console, it won't redraw them except if you tell him to do so with this function + @Cpp void TCODConsole::setDirty(int x, int y, int w, int h) + @C void TCOD_console_set_dirty(int x, int y, int w, int h) + @Py TCOD_console_set_dirty(x, y, w, h) + @Param x,y,w,h Part of the root console you want to redraw even if nothing has changed in the console back/fore/char. + */ + +#ifndef TCOD_BARE + /** + @PageName system_misc + @PageFather system + @PageTitle Miscellaneous utilities + @FuncTitle Using a custom resolution for the fullscreen mode + @FuncDesc This function allows you to force the use of a specific resolution in fullscreen mode. + The default resolution depends on the root console size and the font character size. + @Cpp static void TCODSystem::forceFullscreenResolution(int width, int height) + @C void TCOD_sys_force_fullscreen_resolution(int width, int height) + @Py sys_force_fullscreen_resolution(width, height) + @C# static void TCODSystem::forceFullscreenResolution(int width, int height); + @Lua tcod.system.forceFullscreenResolution(width,height) + @Param width,height Resolution to use when switching to fullscreen. + Will use the smallest available resolution so that : + resolution width >= width and resolution width >= root console width * font char width + resolution width >= height and resolution height >= root console height * font char height + @CppEx + TCODSystem::forceFullscreenResolution(800,600); // use 800x600 in fullscreen instead of 640x400 + TCODConsole::initRoot(80,50,"",true); // 80x50 console with 8x8 char => 640x400 default resolution + @CEx + TCOD_sys_force_fullscreen_resolution(800,600); + TCOD_console_init_root(80,50,"",true); + @PyEx + libtcod.sys_force_fullscreen_resolution(800,600) + libtcod.console_init_root(80,50,"",True) + @LuaEx + tcod.system.forceFullscreenResolution(800,600) -- use 800x600 in fullscreen instead of 640x400 + tcod.console.initRoot(80,50,"",true) -- 80x50 console with 8x8 char => 640x400 default resolution + */ + static void forceFullscreenResolution(int width, int height); + + /** + @PageName system_misc + @FuncTitle Get current resolution + @FuncDesc You can get the current screen resolution with getCurrentResolution. You can use it for example to get the desktop resolution before initializing the root console. + @Cpp static void TCODSystem::getCurrentResolution(int *width, int *height) + @C void TCOD_sys_get_current_resolution(int *width, int *height) + @Py sys_get_current_resolution() # returns w,h + @C# static void TCODSystem::getCurrentResolution(out int w, out int h); + @Param width,height contains current resolution when the function returns + */ + static void getCurrentResolution(int *w, int *h); + /** + @PageName system_misc + @FuncTitle Get fullscreen offset + @FuncDesc If the fullscreen resolution does not matches the console size in pixels, black borders are added. This function returns the position in pixels of the console top left corner in the screen. + @Cpp static void TCODSystem::getFullscreenOffsets(int *offx, int *offy) + @C void TCOD_sys_get_fullscreen_offsets(int *offx, int *offy) + @C# static void TCODSystem::getFullscreenOffsets(out int offx, out int offy); + @Param offx,offy contains the position of the console on the screen when using fullscreen mode. + */ + static void getFullscreenOffsets(int *offx, int *offy); + + /** + @PageName system_misc + @FuncTitle Get the font size + @FuncDesc You can get the size of the characters in the font + @Cpp static void TCODSystem::getCharSize(int *width, int *height) + @C void TCOD_sys_get_char_size(int *width, int *height) + @Py sys_get_char_size() # returns w,h + @C# static void TCODSystem::getCharSize(out int w, out int h); + @Param width,height contains a character size when the function returns + */ + static void getCharSize(int *w, int *h); + + /** + @PageName system_misc + @FuncTitle Dynamically updating the font bitmap + @FuncDesc You can dynamically change the bitmap of a character in the font. All cells using this ascii code will be updated at next flush call. + @Cpp static void TCODSystem::updateChar(int asciiCode, int fontx, int fonty,const TCODImage *img,int x,int y) + @C void TCOD_sys_update_char(int asciiCode, int fontx, int fonty, TCOD_image_t img, int x, int y) + @Py sys_update_char(asciiCode,fontx,fonty,img,x,y) + @Param asciiCode ascii code corresponding to the character to update + @Param fontx,fonty coordinate of the character in the bitmap font (in characters, not pixels) + @Param img image containing the new character bitmap + @Param x,y position in pixels of the top-left corner of the character in the image + */ + static void updateChar(int asciiCode, int fontx, int fonty,const TCODImage *img,int x,int y); +#endif + +#ifndef TCOD_BARE + /** + @PageName system_misc + @FuncTitle Dynamically change libtcod's internal renderer + @FuncDesc As of 1.5.1, libtcod contains 3 different renderers : + * SDL : historic libtcod renderer. Should work and be pretty fast everywhere + * OpenGL : requires OpenGL compatible video card. Might be much faster or much slower than SDL, depending on the drivers + * GLSDL : requires OpenGL 1.4 compatible video card with GL_ARB_shader_objects extension. Blazing fast if you have the proper hardware and drivers. + This function switches the current renderer dynamically. + @Cpp static void TCODSystem::setRenderer(TCOD_renderer_t renderer) + @C void TCOD_sys_set_renderer(TCOD_renderer_t renderer) + @Py sys_set_renderer(renderer) + @C# static void TCODSystem::setRenderer(TCODRendererType renderer); + @Param renderer Either TCOD_RENDERER_GLSL, TCOD_RENDERER_OPENGL or TCOD_RENDERER_SDL + */ + static void setRenderer(TCOD_renderer_t renderer); + + /** + @PageName system_misc + @FuncTitle Get the current internal renderer + @Cpp static TCOD_renderer_t TCODSystem::getRenderer() + @C TCOD_renderer_t TCOD_sys_get_renderer() + @Py sys_get_renderer() + @C# static TCODRendererType TCODSystem::getRenderer(); + */ + static TCOD_renderer_t getRenderer(); + + /** + @PageName system_clipboard + @PageTitle Clipboard integration + @PageDesc With these functions, you can copy data in your operating system's clipboard from the game or retrieve data from the clipboard. + @PageFather system + @FuncTitle Set current clipboard contents + @FuncDesc Takes UTF-8 text and copies it into the system clipboard. On Linux, because an application cannot access the system clipboard unless a window is open, if no window is open the call will do nothing. + @Cpp static bool TCODSystem::setClipboard(const char *value) + @C bool TCOD_sys_clipboard_set(const char *value) + @Py sys_clipboard_set(value) + @Param value UTF-8 text to copy into the clipboard + */ + static bool setClipboard(const char *value); + + /** + @PageName system_clipboard + @FuncTitle Get current clipboard contents + @FuncDesc Returns the UTF-8 text currently in the system clipboard. On Linux, because an application cannot access the system clipboard unless a window is open, if no window is open an empty string will be returned. For C and C++, note that the pointer is borrowed, and libtcod will take care of freeing the memory. + @Cpp static char *TCODSystem::getClipboard() + @C char *TCOD_sys_clipboard_get() + @Py sys_clipboard_get() # Returns UTF-8 string + */ + static char *getClipboard(); +#endif + + // thread stuff + static int getNumCores(); + static TCOD_thread_t newThread(int (*func)(void *), void *data); + static void deleteThread(TCOD_thread_t th); + static void waitThread(TCOD_thread_t th); + // mutex + static TCOD_mutex_t newMutex(); + static void mutexIn(TCOD_mutex_t mut); + static void mutexOut(TCOD_mutex_t mut); + static void deleteMutex(TCOD_mutex_t mut); + // semaphore + static TCOD_semaphore_t newSemaphore(int initVal); + static void lockSemaphore(TCOD_semaphore_t sem); + static void unlockSemaphore(TCOD_semaphore_t sem); + static void deleteSemaphore( TCOD_semaphore_t sem); + // condition + static TCOD_cond_t newCondition(); + static void signalCondition(TCOD_cond_t sem); + static void broadcastCondition(TCOD_cond_t sem); + static void waitCondition(TCOD_cond_t sem, TCOD_mutex_t mut); + static void deleteCondition( TCOD_cond_t sem); +}; + +#endif diff --git a/tcod_sys/libtcod/src/sys_c.c b/tcod_sys/libtcod/src/libtcod/sys_c.cpp similarity index 95% rename from tcod_sys/libtcod/src/sys_c.c rename to tcod_sys/libtcod/src/libtcod/sys_c.cpp index 4689d7bff..6dd8733db 100644 --- a/tcod_sys/libtcod/src/sys_c.c +++ b/tcod_sys/libtcod/src/libtcod/sys_c.cpp @@ -1,559 +1,560 @@ -/* -* libtcod -* Copyright (c) 2008-2018 Jice & Mingos & rmtew -* All rights reserved. -* -* Redistribution and use in source and binary forms, with or without -* modification, are permitted provided that the following conditions are met: -* * Redistributions of source code must retain the above copyright -* notice, this list of conditions and the following disclaimer. -* * Redistributions in binary form must reproduce the above copyright -* notice, this list of conditions and the following disclaimer in the -* documentation and/or other materials provided with the distribution. -* * The name of Jice or Mingos may not be used to endorse or promote -* products derived from this software without specific prior written -* permission. -* -* THIS SOFTWARE IS PROVIDED BY JICE, MINGOS AND RMTEW ``AS IS'' AND ANY -* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED -* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE -* DISCLAIMED. IN NO EVENT SHALL JICE, MINGOS OR RMTEW BE LIABLE FOR ANY -* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES -* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; -* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND -* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS -* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. -*/ -#include - -#include -#include -#include -#include -#include -#include - -#if defined (__APPLE__) && defined (__MACH__) -/* Is this necessary now the custom clipboard stuff is gone? */ -#include -#endif -#include "libtcod_int.h" -#include "libtcod_version.h" -#ifdef TCOD_WINDOWS -#include -#else -#include -#include -#include -#include -#include -#include -#include -#include -#endif - -bool TCOD_sys_create_directory(const char *path) { -#ifdef TCOD_WINDOWS - return (CreateDirectory(path,NULL) != 0 || GetLastError() == ERROR_ALREADY_EXISTS); -#else - return mkdir(path,0755) == 0 || errno == EEXIST; -#endif -} - -bool TCOD_sys_delete_file(const char *path) { -#ifdef TCOD_WINDOWS - return DeleteFile(path) != 0; -#else - return unlink(path) == 0 || errno == ENOENT; -#endif -} - -bool TCOD_sys_delete_directory(const char *path) { -#ifdef TCOD_WINDOWS - return RemoveDirectory(path) != 0; -#else - return rmdir(path) == 0 || errno == ENOENT; -#endif -} - - -bool TCOD_sys_is_directory(const char *path) { -#ifdef TCOD_WINDOWS - DWORD type=GetFileAttributes(path); - return ( type & FILE_ATTRIBUTE_DIRECTORY) != 0 ; -#else - DIR *d=opendir(path); - if ( d ) { closedir(d); return true; } - return false; -#endif -} - - -static bool filename_match(const char *name, const char *pattern) { - char *ptr; - if ( pattern == NULL || pattern[0] == 0 ) return true; - ptr=strchr(pattern,'*'); - if ( ! ptr ) return strcmp(name,pattern) == 0; - if ( ptr != name && strncmp(name,pattern, ptr - pattern) != 0 ) return false; - return strcmp( name + strlen(name) - strlen(ptr+1), ptr+1) == 0; -} - -TCOD_list_t TCOD_sys_get_directory_content(const char *path, const char *pattern) { - TCOD_list_t list=TCOD_list_new(); -#ifdef TCOD_WINDOWS - WIN32_FIND_DATA FileData; - HANDLE hList; - char dname[ 512 ]; - sprintf(dname, "%s\\*",path); - hList = FindFirstFile(dname, &FileData); - if (hList == INVALID_HANDLE_VALUE) - { - return list; - } - do - { - if ( ! (strcmp(FileData.cFileName,".") == 0 || strcmp(FileData.cFileName,"..") == 0 ) ) - { - if ( filename_match(FileData.cFileName,pattern) ) - TCOD_list_push(list,TCOD_strdup(FileData.cFileName)); - } - - } while ( FindNextFile(hList, &FileData) ); - FindClose(hList); -#else - DIR *dir = opendir(path); - struct dirent *dirent = NULL; - if ( ! dir ) return list; - while ( ( dirent = readdir(dir) ) ) - { - if ( ! (strcmp(dirent->d_name,".") == 0 || strcmp(dirent->d_name,"..") == 0 ) ) - { - if ( filename_match(dirent->d_name,pattern) ) - TCOD_list_push(list,TCOD_strdup(dirent->d_name)); - } - } - closedir(dir); -#endif - return list; -} - -/* thread stuff */ -#ifdef TCOD_WINDOWS -/* Helper function to count set bits in the processor mask. */ -static DWORD CountSetBits(ULONG_PTR bitMask) -{ - DWORD LSHIFT = sizeof(ULONG_PTR)*8 - 1; - DWORD bitSetCount = 0; - ULONG_PTR bitTest = (ULONG_PTR)1 << LSHIFT; - DWORD i; - - for (i = 0; i <= LSHIFT; ++i) - { - bitSetCount += ((bitMask & bitTest)?1:0); - bitTest/=2; - } - - return bitSetCount; -} -#endif - -int TCOD_sys_get_num_cores(void) { -#ifdef TCOD_WINDOWS - /* what a crap !!! works only on xp sp3 & vista */ - typedef enum _PROCESSOR_CACHE_TYPE { - CacheUnified, - CacheInstruction, - CacheData, - CacheTrace - } PROCESSOR_CACHE_TYPE; - - typedef struct _CACHE_DESCRIPTOR { - BYTE Level; - BYTE Associativity; - WORD LineSize; - DWORD Size; - PROCESSOR_CACHE_TYPE Type; - } CACHE_DESCRIPTOR; - typedef enum _LOGICAL_PROCESSOR_RELATIONSHIP { - RelationProcessorCore, - RelationNumaNode, - RelationCache, - RelationProcessorPackage - } LOGICAL_PROCESSOR_RELATIONSHIP; - - typedef struct _SYSTEM_LOGICAL_PROCESSOR_INFORMATION { - ULONG_PTR ProcessorMask; - LOGICAL_PROCESSOR_RELATIONSHIP Relationship; - union { - struct { - BYTE Flags; - } ProcessorCore; - struct { - DWORD NodeNumber; - } NumaNode; - CACHE_DESCRIPTOR Cache; - ULONGLONG Reserved[2]; - }; - } SYSTEM_LOGICAL_PROCESSOR_INFORMATION, - *PSYSTEM_LOGICAL_PROCESSOR_INFORMATION; - typedef BOOL (WINAPI *LPFN_GLPI)( - PSYSTEM_LOGICAL_PROCESSOR_INFORMATION, - PDWORD); - - LPFN_GLPI glpi; - BOOL done = FALSE; - PSYSTEM_LOGICAL_PROCESSOR_INFORMATION buffer = NULL; - PSYSTEM_LOGICAL_PROCESSOR_INFORMATION ptr = NULL; - DWORD returnLength = 0; - DWORD logicalProcessorCount = 0; - DWORD byteOffset = 0; - - glpi = (LPFN_GLPI) GetProcAddress( - GetModuleHandle(TEXT("kernel32")), - "GetLogicalProcessorInformation"); - if (! glpi) { - return 1; - } - - while (!done) { - DWORD rc = glpi(buffer, &returnLength); - - if (FALSE == rc) - { - if (GetLastError() == ERROR_INSUFFICIENT_BUFFER) { - if (buffer) - free(buffer); - - buffer = (PSYSTEM_LOGICAL_PROCESSOR_INFORMATION)malloc( - returnLength); - - if (NULL == buffer) { - return 1; - } - } else { - return 1; - } - } else { - done = TRUE; - } - } - - ptr = buffer; - - while (byteOffset + sizeof(SYSTEM_LOGICAL_PROCESSOR_INFORMATION) <= returnLength) { - switch (ptr->Relationship) { - case RelationProcessorCore: - /* A hyperthreaded core supplies more than one logical processor. */ - logicalProcessorCount += CountSetBits(ptr->ProcessorMask); - break; - default: break; - } - byteOffset += sizeof(SYSTEM_LOGICAL_PROCESSOR_INFORMATION); - ptr++; - } - - free(buffer); - - return logicalProcessorCount; -#else - return sysconf(_SC_NPROCESSORS_ONLN); -#endif -} - -TCOD_thread_t TCOD_thread_new(int (*func)(void *), void *data) -{ -#ifdef TCOD_WINDOWS - HANDLE ret = CreateThread(NULL,0,(DWORD (WINAPI *)( LPVOID ))func,data,0,NULL); - return (TCOD_thread_t)ret; -#else - pthread_t id; - int iret; - pthread_attr_t attr; - pthread_attr_init(&attr); - pthread_attr_setdetachstate(&attr,PTHREAD_CREATE_DETACHED); - iret =pthread_create(&id,&attr,(void *(*)(void *))func,data); - if ( iret != 0 ) id=0; - return (TCOD_thread_t)id; -#endif -} - -void TCOD_thread_delete(TCOD_thread_t th) -{ -#ifdef TCOD_WINDOWS - CloseHandle((HANDLE)th); -#endif -} - -void TCOD_thread_wait(TCOD_thread_t th) { -#ifdef TCOD_WINDOWS - WaitForSingleObject((HANDLE)th,INFINITE); -#else - pthread_t id=(pthread_t)th; - pthread_join(id,NULL); -#endif -} - -TCOD_mutex_t TCOD_mutex_new() -{ -#ifdef TCOD_WINDOWS - CRITICAL_SECTION *cs = (CRITICAL_SECTION *)calloc(sizeof(CRITICAL_SECTION),1); - InitializeCriticalSection(cs); - return (TCOD_mutex_t)cs; -#else - static pthread_mutex_t tmp=PTHREAD_MUTEX_INITIALIZER; - pthread_mutex_t *mut = (pthread_mutex_t *)calloc(sizeof(pthread_mutex_t),1); - *mut = tmp; - return (TCOD_mutex_t)mut; -#endif -} - -void TCOD_mutex_in(TCOD_mutex_t mut) -{ -#ifdef TCOD_WINDOWS - EnterCriticalSection((CRITICAL_SECTION *)mut); -#else - pthread_mutex_lock((pthread_mutex_t *)mut); -#endif -} - -void TCOD_mutex_out(TCOD_mutex_t mut) -{ -#ifdef TCOD_WINDOWS - LeaveCriticalSection((CRITICAL_SECTION *)mut); -#else - pthread_mutex_unlock((pthread_mutex_t *)mut); -#endif -} - -void TCOD_mutex_delete(TCOD_mutex_t mut) -{ -#ifdef TCOD_WINDOWS - DeleteCriticalSection((CRITICAL_SECTION *)mut); - free(mut); -#else - pthread_mutex_destroy((pthread_mutex_t *)mut); - free(mut); -#endif -} - -TCOD_semaphore_t TCOD_semaphore_new(int initVal) -{ -#ifdef TCOD_WINDOWS - HANDLE ret = CreateSemaphore(NULL,initVal,255,NULL); - return (TCOD_semaphore_t)ret; -#else - sem_t *ret = (sem_t *)calloc(sizeof(sem_t),1); - if ( ret ) sem_init(ret,0,initVal); - return (TCOD_semaphore_t) ret; -#endif -} - -void TCOD_semaphore_lock(TCOD_semaphore_t sem) -{ -#ifdef TCOD_WINDOWS - WaitForSingleObject((HANDLE)sem,INFINITE); -#else - if ( sem ) sem_wait((sem_t *)sem); -#endif -} - -void TCOD_semaphore_unlock(TCOD_semaphore_t sem) -{ -#ifdef TCOD_WINDOWS - ReleaseSemaphore((HANDLE)sem,1,NULL); -#else - if ( sem ) sem_post((sem_t *)sem); -#endif -} - -void TCOD_semaphore_delete( TCOD_semaphore_t sem) -{ -#ifdef TCOD_WINDOWS - CloseHandle((HANDLE)sem); -#else - if ( sem ) - { - sem_destroy((sem_t *)sem); - free (sem); - } -#endif -} - -#ifdef TCOD_WINDOWS -/* poor win32 API has no thread conditions */ -typedef struct { - int nbSignals; - int nbWaiting; - TCOD_mutex_t mutex; - TCOD_semaphore_t waiting; - TCOD_semaphore_t waitDone; -} cond_t; -#endif - -TCOD_cond_t TCOD_condition_new(void) { -#ifdef TCOD_WINDOWS - cond_t *ret = (cond_t *)calloc(sizeof(cond_t),1); - ret->mutex = TCOD_mutex_new(); - ret->waiting = TCOD_semaphore_new(0); - ret->waitDone = TCOD_semaphore_new(0); - return (TCOD_cond_t)ret; -#else - pthread_cond_t *ret = (pthread_cond_t *)calloc(sizeof(pthread_cond_t),1); - if ( ret ) pthread_cond_init(ret,NULL); - return (TCOD_cond_t) ret; -#endif -} - -void TCOD_condition_signal(TCOD_cond_t pcond) { -#ifdef TCOD_WINDOWS - cond_t *cond=(cond_t *)pcond; - if ( cond ) { - TCOD_mutex_in(cond->mutex); - if ( cond->nbWaiting > cond->nbSignals ) { - cond->nbSignals++; - TCOD_semaphore_unlock(cond->waiting); - TCOD_mutex_out(cond->mutex); - TCOD_semaphore_lock(cond->waitDone); - } else { - TCOD_mutex_out(cond->mutex); - } - } -#else - if ( pcond ) { - pthread_cond_signal((pthread_cond_t *)pcond); - } -#endif -} - -void TCOD_condition_broadcast(TCOD_cond_t pcond) { -#ifdef TCOD_WINDOWS - cond_t *cond=(cond_t *)pcond; - if ( cond ) { - TCOD_mutex_in(cond->mutex); - if ( cond->nbWaiting > cond->nbSignals ) { - int nbUnlock=cond->nbWaiting-cond->nbSignals; - int i; - cond->nbSignals=cond->nbWaiting; - for (i=nbUnlock; i > 0; i--) { - TCOD_semaphore_unlock(cond->waiting); - } - TCOD_mutex_out(cond->mutex); - for (i=nbUnlock; i > 0; i--) { - TCOD_semaphore_lock(cond->waitDone); - } - } else { - TCOD_mutex_out(cond->mutex); - } - } -#else - if ( pcond ) { - pthread_cond_broadcast((pthread_cond_t *)pcond); - } -#endif -} - -void TCOD_condition_wait(TCOD_cond_t pcond, TCOD_mutex_t mut) { -#ifdef TCOD_WINDOWS - cond_t *cond=(cond_t *)pcond; - if ( cond ) { - TCOD_mutex_in(cond->mutex); - cond->nbWaiting++; - TCOD_mutex_out(cond->mutex); - TCOD_mutex_out(mut); - TCOD_semaphore_lock(cond->waiting); - TCOD_mutex_in(cond->mutex); - if ( cond->nbSignals > 0 ) { - TCOD_semaphore_unlock(cond->waitDone); - cond->nbSignals--; - } - cond->nbWaiting--; - TCOD_mutex_out(cond->mutex); - } -#else - if ( pcond && mut ) { - pthread_cond_wait((pthread_cond_t *)pcond, (pthread_mutex_t *)mut); - } -#endif -} - -void TCOD_condition_delete( TCOD_cond_t pcond) { -#ifdef TCOD_WINDOWS - cond_t *cond=(cond_t *)pcond; - if ( cond ) { - TCOD_mutex_delete(cond->mutex); - TCOD_semaphore_delete(cond->waiting); - TCOD_semaphore_delete(cond->waitDone); - free(cond); - } -#else - if ( pcond ) { - pthread_cond_destroy((pthread_cond_t *)pcond); - free (pcond); - } -#endif -} - -#ifndef TCOD_BARE -void TCOD_sys_get_fullscreen_offsets(int *offx, int *offy) { - if ( offx ) *offx = TCOD_ctx.fullscreen_offsetx; - if ( offy ) *offy = TCOD_ctx.fullscreen_offsety; -} -#else -void TCOD_sys_startup(void) { - //TCOD_ctx.max_font_chars = 256; - //alloc_ascii_tables(); -} - -void TCOD_sys_shutdown(void) { -} - -bool TCOD_sys_read_file(const char *filename, unsigned char **buf, size_t *size) { - return false; -} - -bool TCOD_sys_write_file(const char *filename, unsigned char *buf, uint32_t size) { - return false; -} -#endif /* TCOD_BARE */ - -void TCOD_fatal(const char *fmt, ...) { - va_list ap; - TCOD_sys_shutdown(); - printf("%s\n", TCOD_STRVERSIONNAME); - va_start(ap, fmt); - vprintf(fmt, ap); - va_end(ap); - printf("\n"); - exit(1); -} - -void TCOD_fatal_nopar(const char *msg) { - TCOD_sys_shutdown(); - printf("%s\n%s\n", TCOD_STRVERSIONNAME, msg); - exit(1); -} - -/* dynamic library support */ -#ifdef TCOD_WINDOWS -TCOD_library_t TCOD_load_library(const char *path) { - return (TCOD_library_t)LoadLibrary(path); -} -void * TCOD_get_function_address(TCOD_library_t library, const char *function_name) { - return (void *)GetProcAddress((HMODULE)library,function_name); -} -void TCOD_close_library(TCOD_library_t library) { - FreeLibrary((HMODULE)library); -} -#else -TCOD_library_t TCOD_load_library(const char *path) { - void *l=dlopen(path,RTLD_LAZY); - return (TCOD_library_t)l; -} -void * TCOD_get_function_address(TCOD_library_t library, const char *function_name) { - return dlsym(library,(char *)function_name); -} -void TCOD_close_library(TCOD_library_t library) { - dlclose(library); -} -#endif +/* +* libtcod +* Copyright (c) 2008-2018 Jice & Mingos & rmtew +* All rights reserved. +* +* Redistribution and use in source and binary forms, with or without +* modification, are permitted provided that the following conditions are met: +* * Redistributions of source code must retain the above copyright +* notice, this list of conditions and the following disclaimer. +* * Redistributions in binary form must reproduce the above copyright +* notice, this list of conditions and the following disclaimer in the +* documentation and/or other materials provided with the distribution. +* * The name of Jice or Mingos may not be used to endorse or promote +* products derived from this software without specific prior written +* permission. +* +* THIS SOFTWARE IS PROVIDED BY JICE, MINGOS AND RMTEW ``AS IS'' AND ANY +* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED +* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE +* DISCLAIMED. IN NO EVENT SHALL JICE, MINGOS OR RMTEW BE LIABLE FOR ANY +* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES +* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; +* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND +* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS +* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +*/ +#include "sys.h" + +#include +#include +#include +#include +#include +#include + +#if defined (__APPLE__) && defined (__MACH__) +/* Is this necessary now the custom clipboard stuff is gone? */ +#include +#endif +#include "libtcod_int.h" +#include "version.h" +#ifdef TCOD_WINDOWS +#define NOMINMAX +#include +#else +#include +#include +#include +#include +#include +#include +#include +#include +#endif + +bool TCOD_sys_create_directory(const char *path) { +#ifdef TCOD_WINDOWS + return (CreateDirectory(path,NULL) != 0 || GetLastError() == ERROR_ALREADY_EXISTS); +#else + return mkdir(path,0755) == 0 || errno == EEXIST; +#endif +} + +bool TCOD_sys_delete_file(const char *path) { +#ifdef TCOD_WINDOWS + return DeleteFile(path) != 0; +#else + return unlink(path) == 0 || errno == ENOENT; +#endif +} + +bool TCOD_sys_delete_directory(const char *path) { +#ifdef TCOD_WINDOWS + return RemoveDirectory(path) != 0; +#else + return rmdir(path) == 0 || errno == ENOENT; +#endif +} + + +bool TCOD_sys_is_directory(const char *path) { +#ifdef TCOD_WINDOWS + DWORD type=GetFileAttributes(path); + return ( type & FILE_ATTRIBUTE_DIRECTORY) != 0 ; +#else + DIR *d=opendir(path); + if ( d ) { closedir(d); return true; } + return false; +#endif +} + + +static bool filename_match(const char *name, const char *pattern) { + const char *ptr; + if ( pattern == NULL || pattern[0] == 0 ) return true; + ptr=strchr(pattern,'*'); + if ( ! ptr ) return strcmp(name,pattern) == 0; + if ( ptr != name && strncmp(name,pattern, ptr - pattern) != 0 ) return false; + return strcmp( name + strlen(name) - strlen(ptr+1), ptr+1) == 0; +} + +TCOD_list_t TCOD_sys_get_directory_content(const char *path, const char *pattern) { + TCOD_list_t list=TCOD_list_new(); +#ifdef TCOD_WINDOWS + WIN32_FIND_DATA FileData; + HANDLE hList; + char dname[ 512 ]; + sprintf(dname, "%s\\*",path); + hList = FindFirstFile(dname, &FileData); + if (hList == INVALID_HANDLE_VALUE) + { + return list; + } + do + { + if ( ! (strcmp(FileData.cFileName,".") == 0 || strcmp(FileData.cFileName,"..") == 0 ) ) + { + if ( filename_match(FileData.cFileName,pattern) ) + TCOD_list_push(list,TCOD_strdup(FileData.cFileName)); + } + + } while ( FindNextFile(hList, &FileData) ); + FindClose(hList); +#else + DIR *dir = opendir(path); + struct dirent *dirent = NULL; + if ( ! dir ) return list; + while ( ( dirent = readdir(dir) ) ) + { + if ( ! (strcmp(dirent->d_name,".") == 0 || strcmp(dirent->d_name,"..") == 0 ) ) + { + if ( filename_match(dirent->d_name,pattern) ) + TCOD_list_push(list,TCOD_strdup(dirent->d_name)); + } + } + closedir(dir); +#endif + return list; +} + +/* thread stuff */ +#ifdef TCOD_WINDOWS +/* Helper function to count set bits in the processor mask. */ +static DWORD CountSetBits(ULONG_PTR bitMask) +{ + DWORD LSHIFT = sizeof(ULONG_PTR)*8 - 1; + DWORD bitSetCount = 0; + ULONG_PTR bitTest = (ULONG_PTR)1 << LSHIFT; + DWORD i; + + for (i = 0; i <= LSHIFT; ++i) + { + bitSetCount += ((bitMask & bitTest)?1:0); + bitTest/=2; + } + + return bitSetCount; +} +#endif + +int TCOD_sys_get_num_cores(void) { +#ifdef TCOD_WINDOWS + /* what a crap !!! works only on xp sp3 & vista */ + typedef enum _PROCESSOR_CACHE_TYPE { + CacheUnified, + CacheInstruction, + CacheData, + CacheTrace + } PROCESSOR_CACHE_TYPE; + + typedef struct _CACHE_DESCRIPTOR { + BYTE Level; + BYTE Associativity; + WORD LineSize; + DWORD Size; + PROCESSOR_CACHE_TYPE Type; + } CACHE_DESCRIPTOR; + typedef enum _LOGICAL_PROCESSOR_RELATIONSHIP { + RelationProcessorCore, + RelationNumaNode, + RelationCache, + RelationProcessorPackage + } LOGICAL_PROCESSOR_RELATIONSHIP; + + typedef struct _SYSTEM_LOGICAL_PROCESSOR_INFORMATION { + ULONG_PTR ProcessorMask; + LOGICAL_PROCESSOR_RELATIONSHIP Relationship; + union { + struct { + BYTE Flags; + } ProcessorCore; + struct { + DWORD NodeNumber; + } NumaNode; + CACHE_DESCRIPTOR Cache; + ULONGLONG Reserved[2]; + }; + } SYSTEM_LOGICAL_PROCESSOR_INFORMATION, + *PSYSTEM_LOGICAL_PROCESSOR_INFORMATION; + typedef BOOL (WINAPI *LPFN_GLPI)( + PSYSTEM_LOGICAL_PROCESSOR_INFORMATION, + PDWORD); + + LPFN_GLPI glpi; + BOOL done = FALSE; + PSYSTEM_LOGICAL_PROCESSOR_INFORMATION buffer = NULL; + PSYSTEM_LOGICAL_PROCESSOR_INFORMATION ptr = NULL; + DWORD returnLength = 0; + DWORD logicalProcessorCount = 0; + DWORD byteOffset = 0; + + glpi = (LPFN_GLPI) GetProcAddress( + GetModuleHandle(TEXT("kernel32")), + "GetLogicalProcessorInformation"); + if (! glpi) { + return 1; + } + + while (!done) { + DWORD rc = glpi(buffer, &returnLength); + + if (FALSE == rc) + { + if (GetLastError() == ERROR_INSUFFICIENT_BUFFER) { + if (buffer) + free(buffer); + + buffer = (PSYSTEM_LOGICAL_PROCESSOR_INFORMATION)malloc( + returnLength); + + if (NULL == buffer) { + return 1; + } + } else { + return 1; + } + } else { + done = TRUE; + } + } + + ptr = buffer; + + while (byteOffset + sizeof(SYSTEM_LOGICAL_PROCESSOR_INFORMATION) <= returnLength) { + switch (ptr->Relationship) { + case RelationProcessorCore: + /* A hyperthreaded core supplies more than one logical processor. */ + logicalProcessorCount += CountSetBits(ptr->ProcessorMask); + break; + default: break; + } + byteOffset += sizeof(SYSTEM_LOGICAL_PROCESSOR_INFORMATION); + ptr++; + } + + free(buffer); + + return logicalProcessorCount; +#else + return sysconf(_SC_NPROCESSORS_ONLN); +#endif +} + +TCOD_thread_t TCOD_thread_new(int (*func)(void *), void *data) +{ +#ifdef TCOD_WINDOWS + HANDLE ret = CreateThread(NULL,0,(DWORD (WINAPI *)( LPVOID ))func,data,0,NULL); + return (TCOD_thread_t)ret; +#else + pthread_t id; + int iret; + pthread_attr_t attr; + pthread_attr_init(&attr); + pthread_attr_setdetachstate(&attr,PTHREAD_CREATE_DETACHED); + iret =pthread_create(&id,&attr,(void *(*)(void *))func,data); + if ( iret != 0 ) id=0; + return (TCOD_thread_t)id; +#endif +} + +void TCOD_thread_delete(TCOD_thread_t th) +{ +#ifdef TCOD_WINDOWS + CloseHandle((HANDLE)th); +#endif +} + +void TCOD_thread_wait(TCOD_thread_t th) { +#ifdef TCOD_WINDOWS + WaitForSingleObject((HANDLE)th,INFINITE); +#else + pthread_t id=(pthread_t)th; + pthread_join(id,NULL); +#endif +} + +TCOD_mutex_t TCOD_mutex_new() +{ +#ifdef TCOD_WINDOWS + CRITICAL_SECTION *cs = (CRITICAL_SECTION *)calloc(sizeof(CRITICAL_SECTION),1); + InitializeCriticalSection(cs); + return (TCOD_mutex_t)cs; +#else + static pthread_mutex_t tmp=PTHREAD_MUTEX_INITIALIZER; + pthread_mutex_t *mut = (pthread_mutex_t *)calloc(sizeof(pthread_mutex_t),1); + *mut = tmp; + return (TCOD_mutex_t)mut; +#endif +} + +void TCOD_mutex_in(TCOD_mutex_t mut) +{ +#ifdef TCOD_WINDOWS + EnterCriticalSection((CRITICAL_SECTION *)mut); +#else + pthread_mutex_lock((pthread_mutex_t *)mut); +#endif +} + +void TCOD_mutex_out(TCOD_mutex_t mut) +{ +#ifdef TCOD_WINDOWS + LeaveCriticalSection((CRITICAL_SECTION *)mut); +#else + pthread_mutex_unlock((pthread_mutex_t *)mut); +#endif +} + +void TCOD_mutex_delete(TCOD_mutex_t mut) +{ +#ifdef TCOD_WINDOWS + DeleteCriticalSection((CRITICAL_SECTION *)mut); + free(mut); +#else + pthread_mutex_destroy((pthread_mutex_t *)mut); + free(mut); +#endif +} + +TCOD_semaphore_t TCOD_semaphore_new(int initVal) +{ +#ifdef TCOD_WINDOWS + HANDLE ret = CreateSemaphore(NULL,initVal,255,NULL); + return (TCOD_semaphore_t)ret; +#else + sem_t *ret = (sem_t *)calloc(sizeof(sem_t),1); + if ( ret ) sem_init(ret,0,initVal); + return (TCOD_semaphore_t) ret; +#endif +} + +void TCOD_semaphore_lock(TCOD_semaphore_t sem) +{ +#ifdef TCOD_WINDOWS + WaitForSingleObject((HANDLE)sem,INFINITE); +#else + if ( sem ) sem_wait((sem_t *)sem); +#endif +} + +void TCOD_semaphore_unlock(TCOD_semaphore_t sem) +{ +#ifdef TCOD_WINDOWS + ReleaseSemaphore((HANDLE)sem,1,NULL); +#else + if ( sem ) sem_post((sem_t *)sem); +#endif +} + +void TCOD_semaphore_delete( TCOD_semaphore_t sem) +{ +#ifdef TCOD_WINDOWS + CloseHandle((HANDLE)sem); +#else + if ( sem ) + { + sem_destroy((sem_t *)sem); + free (sem); + } +#endif +} + +#ifdef TCOD_WINDOWS +/* poor win32 API has no thread conditions */ +typedef struct { + int nbSignals; + int nbWaiting; + TCOD_mutex_t mutex; + TCOD_semaphore_t waiting; + TCOD_semaphore_t waitDone; +} cond_t; +#endif + +TCOD_cond_t TCOD_condition_new(void) { +#ifdef TCOD_WINDOWS + cond_t *ret = (cond_t *)calloc(sizeof(cond_t),1); + ret->mutex = TCOD_mutex_new(); + ret->waiting = TCOD_semaphore_new(0); + ret->waitDone = TCOD_semaphore_new(0); + return (TCOD_cond_t)ret; +#else + pthread_cond_t *ret = (pthread_cond_t *)calloc(sizeof(pthread_cond_t),1); + if ( ret ) pthread_cond_init(ret,NULL); + return (TCOD_cond_t) ret; +#endif +} + +void TCOD_condition_signal(TCOD_cond_t pcond) { +#ifdef TCOD_WINDOWS + cond_t *cond=(cond_t *)pcond; + if ( cond ) { + TCOD_mutex_in(cond->mutex); + if ( cond->nbWaiting > cond->nbSignals ) { + cond->nbSignals++; + TCOD_semaphore_unlock(cond->waiting); + TCOD_mutex_out(cond->mutex); + TCOD_semaphore_lock(cond->waitDone); + } else { + TCOD_mutex_out(cond->mutex); + } + } +#else + if ( pcond ) { + pthread_cond_signal((pthread_cond_t *)pcond); + } +#endif +} + +void TCOD_condition_broadcast(TCOD_cond_t pcond) { +#ifdef TCOD_WINDOWS + cond_t *cond=(cond_t *)pcond; + if ( cond ) { + TCOD_mutex_in(cond->mutex); + if ( cond->nbWaiting > cond->nbSignals ) { + int nbUnlock=cond->nbWaiting-cond->nbSignals; + int i; + cond->nbSignals=cond->nbWaiting; + for (i=nbUnlock; i > 0; i--) { + TCOD_semaphore_unlock(cond->waiting); + } + TCOD_mutex_out(cond->mutex); + for (i=nbUnlock; i > 0; i--) { + TCOD_semaphore_lock(cond->waitDone); + } + } else { + TCOD_mutex_out(cond->mutex); + } + } +#else + if ( pcond ) { + pthread_cond_broadcast((pthread_cond_t *)pcond); + } +#endif +} + +void TCOD_condition_wait(TCOD_cond_t pcond, TCOD_mutex_t mut) { +#ifdef TCOD_WINDOWS + cond_t *cond=(cond_t *)pcond; + if ( cond ) { + TCOD_mutex_in(cond->mutex); + cond->nbWaiting++; + TCOD_mutex_out(cond->mutex); + TCOD_mutex_out(mut); + TCOD_semaphore_lock(cond->waiting); + TCOD_mutex_in(cond->mutex); + if ( cond->nbSignals > 0 ) { + TCOD_semaphore_unlock(cond->waitDone); + cond->nbSignals--; + } + cond->nbWaiting--; + TCOD_mutex_out(cond->mutex); + } +#else + if ( pcond && mut ) { + pthread_cond_wait((pthread_cond_t *)pcond, (pthread_mutex_t *)mut); + } +#endif +} + +void TCOD_condition_delete( TCOD_cond_t pcond) { +#ifdef TCOD_WINDOWS + cond_t *cond=(cond_t *)pcond; + if ( cond ) { + TCOD_mutex_delete(cond->mutex); + TCOD_semaphore_delete(cond->waiting); + TCOD_semaphore_delete(cond->waitDone); + free(cond); + } +#else + if ( pcond ) { + pthread_cond_destroy((pthread_cond_t *)pcond); + free (pcond); + } +#endif +} + +#ifndef TCOD_BARE +void TCOD_sys_get_fullscreen_offsets(int *offx, int *offy) { + if ( offx ) *offx = TCOD_ctx.fullscreen_offsetx; + if ( offy ) *offy = TCOD_ctx.fullscreen_offsety; +} +#else +void TCOD_sys_startup(void) { + //TCOD_ctx.max_font_chars = 256; + //alloc_ascii_tables(); +} + +void TCOD_sys_shutdown(void) { +} + +bool TCOD_sys_read_file(const char *filename, unsigned char **buf, size_t *size) { + return false; +} + +bool TCOD_sys_write_file(const char *filename, unsigned char *buf, uint32_t size) { + return false; +} +#endif /* TCOD_BARE */ + +void TCOD_fatal(const char *fmt, ...) { + va_list ap; + TCOD_sys_shutdown(); + printf("%s\n", TCOD_STRVERSIONNAME); + va_start(ap, fmt); + vprintf(fmt, ap); + va_end(ap); + printf("\n"); + exit(1); +} + +void TCOD_fatal_nopar(const char *msg) { + TCOD_sys_shutdown(); + printf("%s\n%s\n", TCOD_STRVERSIONNAME, msg); + exit(1); +} + +/* dynamic library support */ +#ifdef TCOD_WINDOWS +TCOD_library_t TCOD_load_library(const char *path) { + return (TCOD_library_t)LoadLibrary(path); +} +void * TCOD_get_function_address(TCOD_library_t library, const char *function_name) { + return (void *)GetProcAddress((HMODULE)library,function_name); +} +void TCOD_close_library(TCOD_library_t library) { + FreeLibrary((HMODULE)library); +} +#else +TCOD_library_t TCOD_load_library(const char *path) { + void *l=dlopen(path,RTLD_LAZY); + return (TCOD_library_t)l; +} +void * TCOD_get_function_address(TCOD_library_t library, const char *function_name) { + return dlsym(library,(char *)function_name); +} +void TCOD_close_library(TCOD_library_t library) { + dlclose(library); +} +#endif diff --git a/tcod_sys/libtcod/src/sys_opengl_c.c b/tcod_sys/libtcod/src/libtcod/sys_opengl_c.cpp similarity index 95% rename from tcod_sys/libtcod/src/sys_opengl_c.c rename to tcod_sys/libtcod/src/libtcod/sys_opengl_c.cpp index eecfd948d..33dcd687d 100644 --- a/tcod_sys/libtcod/src/sys_opengl_c.c +++ b/tcod_sys/libtcod/src/libtcod/sys_opengl_c.cpp @@ -1,688 +1,688 @@ -/* -* libtcod -* Copyright (c) 2008-2018 Jice & Mingos & rmtew -* All rights reserved. -* -* Redistribution and use in source and binary forms, with or without -* modification, are permitted provided that the following conditions are met: -* * Redistributions of source code must retain the above copyright -* notice, this list of conditions and the following disclaimer. -* * Redistributions in binary form must reproduce the above copyright -* notice, this list of conditions and the following disclaimer in the -* documentation and/or other materials provided with the distribution. -* * The name of Jice or Mingos may not be used to endorse or promote -* products derived from this software without specific prior written -* permission. -* -* THIS SOFTWARE IS PROVIDED BY JICE, MINGOS AND RMTEW ``AS IS'' AND ANY -* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED -* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE -* DISCLAIMED. IN NO EVENT SHALL JICE, MINGOS OR RMTEW BE LIABLE FOR ANY -* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES -* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; -* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND -* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS -* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. -*/ -/* - * This renderer is mostly copied and pasted from Antagonist's SkyFire GLSL roguelike engine - */ -#ifndef TCOD_BARE -#include - -#include "libtcod_int.h" -#include "console.h" - -#ifndef NO_OPENGL -#include -#include -#include - -#define CHECKGL( GLcall ) \ - GLcall; \ - if(!_CheckGL_Error( #GLcall, __FILE__, __LINE__)) \ - return false; - -#ifdef NDEBUG -#define DBGCHECKGL(GLcall) GLcall -#else -#define DBGCHECKGL CHECKGL -#endif - -typedef enum -{ - Character, - ForeCol, - BackCol, - ConsoleDataEnumSize -} ConsoleDataEnum; -/* JBR04152012 - Made Character a 4 byte value here to support extended characters like other renderers. - Seems like it should be possible to make it a two byte value using GL_UNSIGNED_SHORT_5_6_5_REV in updateTex, - but I can't seem to get the math right in the shader code, it always loses precision somewhere, - resulting in incorrect characters. */ -const int ConsoleDataAlignment[3] = {4, 3, 3 }; - -static const char *TCOD_con_vertex_shader = -#ifndef NDEBUG -"#version 110\n" -#endif -"uniform vec2 termsize; " - -"void main(void) " -"{ " - -" gl_Position = gl_Vertex; " - -" gl_TexCoord[0] = gl_MultiTexCoord0; " -" gl_TexCoord[0].x = gl_TexCoord[0].x*termsize.x; " -" gl_TexCoord[0].y = gl_TexCoord[0].y*termsize.y; " -"} " -; - -static const char *TCOD_con_pixel_shader = -#ifndef NDEBUG -"#version 110\n" -#endif -"uniform sampler2D font; " -"uniform sampler2D term; " -"uniform sampler2D termfcol; " -"uniform sampler2D termbcol; " - -"uniform float fontw; " -"uniform vec2 fontcoef; " -"uniform vec2 termsize; " -"uniform vec2 termcoef; " - -"void main(void) " -"{ " -" vec2 rawCoord = gl_TexCoord[0].xy; " /* varying from [0, termsize) in x and y */ -" vec2 conPos = floor(rawCoord); " /* console integer position */ -" vec2 pixPos = fract(rawCoord); " /* pixel offset within console position */ -" pixPos = vec2(pixPos.x*fontcoef.x,pixPos.y*fontcoef.y); " /* Correct pixel offset for font tex location */ - -" vec2 address = vec2(conPos.x*termcoef.x,conPos.y*termcoef.y); " -" address=address+vec2(0.001, 0.001); " -" vec4 charvec = texture2D(term,address);" -" float inchar = (charvec.r * 256.0) + (charvec.g * 256.0 * 256.0);" /* character */ -" vec4 tcharfcol = texture2D(termfcol, address); " /* front color */ -" vec4 tcharbcol = texture2D(termbcol, address); " /* back color */ - -" vec4 tchar = vec4(mod(floor(inchar),floor(fontw)),floor(inchar/fontw), 0.0, 0.0); " /* 1D index to 2D index map for character */ - -" gl_FragColor = texture2D(font, vec2((tchar.x*fontcoef.x),(tchar.y*fontcoef.y))+pixPos.xy); " /* magic func: finds pixel value in font file */ -" gl_FragColor=gl_FragColor.a*tcharfcol+(1.0-gl_FragColor.a)*tcharbcol; " /* Coloring stage */ -"} " -; - -bool _CheckGL_Error(const char* GLcall, const char* file, const int line) -{ - GLenum errCode; - if((errCode = glGetError())!=GL_NO_ERROR) - { - printf("OPENGL ERROR #%i: in file %s on line %i\n",errCode,file, line); - printf("OPENGL Call: %s\n",GLcall); - return false; - } - return true; -} - -/* called before creating window */ -void TCOD_opengl_init_attributes(void) { - static bool first=true; - if ( first ) { - SDL_GL_SetAttribute(SDL_GL_DOUBLEBUFFER, 1); - SDL_GL_SetAttribute(SDL_GL_RED_SIZE, 8); - SDL_GL_SetAttribute(SDL_GL_BLUE_SIZE, 8); - SDL_GL_SetAttribute(SDL_GL_GREEN_SIZE,8); - SDL_GL_SetAttribute(SDL_GL_BUFFER_SIZE, 32 ); - /* ATI driver bug : enabling this might result in red screen */ - /* SDL_GL_SetAttribute(SDL_GL_ACCELERATED_VISUAL, 1); */ - first=false; - } -} - -/* console size (power of 2 and cells) */ -static int POTconwidth, POTconheight, conwidth, conheight; -/* programs and shaders handles */ -static GLhandleARB conProgram, conVertShader, conFragShader; -/* font texture handle */ -static GLuint font_tex; -/* font power of 2 size and pixels */ -static int POTfontwidth,POTfontheight, fontwidth,fontheight; -/* console data */ -static GLuint Tex[ConsoleDataEnumSize]; -static unsigned char *data[ConsoleDataEnumSize]; -static bool dirty[ConsoleDataEnumSize]; - -/* extension function pointers */ -static PFNGLCREATESHADEROBJECTARBPROC glCreateShaderObjectARB=0; -static PFNGLGETOBJECTPARAMETERIVARBPROC glGetObjectParameterivARB=0; -static PFNGLSHADERSOURCEARBPROC glShaderSourceARB=0; -static PFNGLCOMPILESHADERARBPROC glCompileShaderARB=0; -static PFNGLGETINFOLOGARBPROC glGetInfoLogARB=0; -static PFNGLCREATEPROGRAMOBJECTARBPROC glCreateProgramObjectARB=0; -static PFNGLATTACHOBJECTARBPROC glAttachObjectARB=0; -static PFNGLLINKPROGRAMARBPROC glLinkProgramARB=0; -static PFNGLUSEPROGRAMOBJECTARBPROC glUseProgramObjectARB=0; -static PFNGLUNIFORM2FARBPROC glUniform2fARB=0; -static PFNGLGETUNIFORMLOCATIONARBPROC glGetUniformLocationARB=0; -static PFNGLUNIFORM1FARBPROC glUniform1fARB=0; -static PFNGLUNIFORM1IARBPROC glUniform1iARB=0; -static PFNGLACTIVETEXTUREPROC glActiveTextureF=0; - -static SDL_GLContext glcontext; - -void TCOD_opengl_uninit_state() { - SDL_GL_DeleteContext(glcontext); -} - -/* call after creating window */ -bool TCOD_opengl_init_state(int conw, int conh, void *font) { - SDL_Surface *font_surf=(SDL_Surface *)font; - SDL_PixelFormat *my_format=SDL_AllocFormat(SDL_GetWindowPixelFormat(window)); - - /* convert font for opengl */ - uint32_t rmask, gmask, bmask, amask; - SDL_Surface *temp; - SDL_Surface *temp_alpha; - - glcontext = SDL_GL_CreateContext(window); - - /* check opengl extensions */ - if ( TCOD_ctx.renderer == TCOD_RENDERER_GLSL ) { - bool hasShader = false; - const char *glexts=(const char *)glGetString(GL_EXTENSIONS); - if (glexts ) { - hasShader = (strstr(glexts,"GL_ARB_shader_objects") != NULL); - } - if (! hasShader ) { - TCOD_LOG(("Missing GL_ARB_shader_objects extension. Falling back to fixed pipeline...\n")); - TCOD_ctx.renderer = TCOD_RENDERER_OPENGL; - } - } - - /* set extensions functions pointers */ - glCreateShaderObjectARB=(PFNGLCREATESHADEROBJECTARBPROC)SDL_GL_GetProcAddress("glCreateShaderObjectARB"); - glGetObjectParameterivARB=(PFNGLGETOBJECTPARAMETERIVARBPROC)SDL_GL_GetProcAddress("glGetObjectParameterivARB"); - glShaderSourceARB=(PFNGLSHADERSOURCEARBPROC)SDL_GL_GetProcAddress("glShaderSourceARB"); - glCompileShaderARB=(PFNGLCOMPILESHADERARBPROC)SDL_GL_GetProcAddress("glCompileShaderARB"); - glGetInfoLogARB=(PFNGLGETINFOLOGARBPROC)SDL_GL_GetProcAddress("glGetInfoLogARB"); - glCreateProgramObjectARB=(PFNGLCREATEPROGRAMOBJECTARBPROC)SDL_GL_GetProcAddress("glCreateProgramObjectARB"); - glAttachObjectARB=(PFNGLATTACHOBJECTARBPROC)SDL_GL_GetProcAddress("glAttachObjectARB"); - glLinkProgramARB=(PFNGLLINKPROGRAMARBPROC)SDL_GL_GetProcAddress("glLinkProgramARB"); - glUseProgramObjectARB=(PFNGLUSEPROGRAMOBJECTARBPROC)SDL_GL_GetProcAddress("glUseProgramObjectARB"); - glUniform2fARB=(PFNGLUNIFORM2FARBPROC)SDL_GL_GetProcAddress("glUniform2fARB"); - glGetUniformLocationARB=(PFNGLGETUNIFORMLOCATIONARBPROC)SDL_GL_GetProcAddress("glGetUniformLocationARB"); - glUniform1fARB=(PFNGLUNIFORM1FARBPROC)SDL_GL_GetProcAddress("glUniform1fARB"); - glUniform1iARB=(PFNGLUNIFORM1IARBPROC)SDL_GL_GetProcAddress("glUniform1iARB"); - glActiveTextureF=(PFNGLACTIVETEXTUREPROC)SDL_GL_GetProcAddress("glActiveTexture"); - - /* set opengl state */ - glEnable(GL_TEXTURE_2D); - glClearColor(1.0f, 1.0f, 0.0f, 0.0f); - glPixelStorei(GL_UNPACK_ALIGNMENT, 1); - glClear( GL_COLOR_BUFFER_BIT ); - glMatrixMode( GL_PROJECTION ); - glLoadIdentity(); - if ( TCOD_ctx.renderer == TCOD_RENDERER_GLSL ) { - glOrtho(0, conw, 0, conh, -1.0f, 1.0f); - glDisable (GL_BLEND); - } else { - glOrtho(0, conw, conh, 0.0f, -1.0f, 1.0f); - glEnable (GL_BLEND); - glBlendFunc (GL_ONE, GL_ONE_MINUS_SRC_ALPHA); - } - - glMatrixMode( GL_MODELVIEW ); - glLoadIdentity(); -/*#ifdef TCOD_WINDOWS */ - if ( ! TCOD_ctx.fullscreen ) { - /* turn vsync off in windowed mode */ - typedef bool (APIENTRY *PFNWGLSWAPINTERVALFARPROC)(int); - PFNWGLSWAPINTERVALFARPROC wglSwapIntervalEXT = 0; - - wglSwapIntervalEXT = (PFNWGLSWAPINTERVALFARPROC)SDL_GL_GetProcAddress("wglSwapIntervalEXT"); - - if (wglSwapIntervalEXT) wglSwapIntervalEXT(0); - } -/*#endif */ - - /* compute pot size */ - conwidth=conw; - conheight=conh; - POTconwidth=POTconheight=1; - while ( POTconwidth < conw ) POTconwidth *= 2; - while ( POTconheight < conh ) POTconheight *= 2; - - - #if SDL_BYTEORDER == SDL_BIG_ENDIAN - rmask = 0xff000000; - gmask = 0x00ff0000; - bmask = 0x0000ff00; - amask = 0x000000ff; - #else - rmask = 0x000000ff; - gmask = 0x0000ff00; - bmask = 0x00ff0000; - amask = 0xff000000; - #endif - - fontwidth=font_surf->w; - fontheight=font_surf->h; - POTfontwidth=POTfontheight=1; - while ( POTfontwidth < fontwidth ) POTfontwidth *= 2; - while ( POTfontheight < fontheight ) POTfontheight *= 2; - - SDL_SetColorKey(font_surf, 1, SDL_MapRGB(font_surf->format, 0, 0, 0)); - my_format->Amask = amask; - temp_alpha = SDL_ConvertSurface(font_surf, my_format, 0); - SDL_FreeFormat(my_format); - - temp = SDL_CreateRGBSurface(SDL_SWSURFACE, POTfontwidth, POTfontheight, 32, bmask, gmask, rmask, amask); /*BGRA */ - - SDL_BlitSurface(temp_alpha, NULL, temp, NULL); - SDL_FreeSurface(temp_alpha); - - CHECKGL(glGenTextures(1, &font_tex)); - CHECKGL(glBindTexture(GL_TEXTURE_2D, font_tex)); - SDL_LockSurface(temp); - - glTexParameteri( GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST ); - glTexParameteri( GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST ); - - CHECKGL(glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, temp->w, temp->h, 0, GL_BGRA, GL_UNSIGNED_BYTE, temp->pixels)); - SDL_UnlockSurface(temp); - SDL_FreeSurface(temp); - return true; -} - -static GLhandleARB loadShader(const char *txt, GLuint type) { - int success; - int infologLength = 0; - int charsWritten = 0; - char *infoLog; - GLhandleARB v = glCreateShaderObjectARB(type); - glShaderSourceARB(v, 1, &txt, 0); - glCompileShaderARB(v); - - glGetObjectParameterivARB(v, GL_COMPILE_STATUS, &success); - if(success!=GL_TRUE) - { - /* something went wrong */ - glGetObjectParameterivARB(v, GL_INFO_LOG_LENGTH,&infologLength); - if(infologLength>0) - { - infoLog = (char *)malloc(infologLength); - glGetInfoLogARB(v, infologLength, &charsWritten, infoLog); - printf("GLSL ERROR : %s\n",infoLog); - free(infoLog); - } - return 0; - } - - return v; -} - -static bool loadProgram(const char *vertShaderCode, const char *fragShaderCode, - GLhandleARB *vertShader, GLhandleARB *fragShader, GLhandleARB *prog) { - /* Create and load Program and Shaders */ - int success; - *prog = DBGCHECKGL(glCreateProgramObjectARB()); - - *vertShader = loadShader(vertShaderCode, GL_VERTEX_SHADER); - if ( *vertShader == 0 ) return false; - glAttachObjectARB(*prog, *vertShader); - - *fragShader = loadShader(fragShaderCode, GL_FRAGMENT_SHADER); - if ( *fragShader == 0 ) return false; - glAttachObjectARB(*prog, *fragShader); - - glLinkProgramARB(*prog); - - glGetObjectParameterivARB(*prog, GL_LINK_STATUS, &success); - if(success!=GL_TRUE) - { - /* something went wrong */ - int infologLength = 0; - int charsWritten = 0; - char *infoLog; - glGetObjectParameterivARB(*prog, GL_INFO_LOG_LENGTH,&infologLength); - if (infologLength > 0) - { - infoLog = (char *)malloc(infologLength); - glGetInfoLogARB(*prog, infologLength, &charsWritten, infoLog); - printf("OPENGL ERROR: Program link Error"); - printf("%s\n",infoLog); - free(infoLog); - } - return false; - } - return true; -} - -bool TCOD_opengl_init_shaders(void) { - int i; - TCOD_color_t *fCol; - if ( TCOD_ctx.renderer == TCOD_RENDERER_GLSL ) { - if (! loadProgram(TCOD_con_vertex_shader, TCOD_con_pixel_shader, &conVertShader, &conFragShader, &conProgram ) ) return false; - } - /* Host side data init */ - for(i = 0; i< ConsoleDataEnumSize; i++) - { - data[i] = (unsigned char *)calloc(conwidth*conheight,ConsoleDataAlignment[i]); - dirty[i]=true; - } - /* Initialize ForeCol to 255, 255, 255, 255 */ - fCol = (TCOD_color_t *)data[ForeCol]; - for( i = 0; i < conwidth*conheight; i++) - { - fCol[i].r=255; - fCol[i].g=255; - fCol[i].b=255; - } - - /* Generate Textures */ - glGenTextures(3, Tex); - - /* Character Texture */ - CHECKGL(glBindTexture(GL_TEXTURE_2D, Tex[Character])); - - CHECKGL(glTexParameteri( GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST )); - CHECKGL(glTexParameteri( GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST )); - - CHECKGL(glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, POTconwidth, POTconheight, 0, GL_LUMINANCE, GL_UNSIGNED_BYTE, 0)); - - - /* ForeCol Texture */ - CHECKGL(glBindTexture(GL_TEXTURE_2D, Tex[ForeCol])); - - CHECKGL(glTexParameteri( GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST )); - CHECKGL(glTexParameteri( GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST )); - - CHECKGL(glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, POTconwidth, POTconheight, 0, GL_RGB, GL_UNSIGNED_BYTE, 0)); - - /* BackCol Texture */ - CHECKGL(glBindTexture(GL_TEXTURE_2D, Tex[BackCol])); - - CHECKGL(glTexParameteri( GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST )); - CHECKGL(glTexParameteri( GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST )); - - CHECKGL(glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, POTconwidth, POTconheight, 0, GL_RGB, GL_UNSIGNED_BYTE, 0)); - - CHECKGL(glBindTexture(GL_TEXTURE_2D, 0)); - - return true; -} - -static bool updateTex(ConsoleDataEnum dataType) { - GLenum Type=0; - DBGCHECKGL(glBindTexture(GL_TEXTURE_2D, Tex[dataType])); - - switch(ConsoleDataAlignment[dataType]) - { - case 1: - Type = GL_RED; - break; - /*case 2: - Type = GL_RG; - break; */ - case 3: - Type = GL_RGB; - break; - case 4: - Type = GL_RGBA; - break; - } - /*glPixelStorei(GL_UNPACK_ALIGNMENT, 1); */ - DBGCHECKGL(glTexSubImage2D(GL_TEXTURE_2D, 0, 0, 0, conwidth, conheight, Type, GL_UNSIGNED_BYTE, data[dataType])); - - DBGCHECKGL(glBindTexture(GL_TEXTURE_2D,0)); - return true; -} - -static void updateChar(ConsoleDataEnum dataType, int BufferPos, unsigned char *c, int length, int offset) { - int i; - dirty[dataType] = true; /* Set dirty so Texture gets updated next frame */ - - for(i = 0; ich_array; - int *oc; - nfg = TCOD_image_get_colors(console->fg_colors); - nbg = TCOD_image_get_colors(console->bg_colors); - if (track_changes) { - oc = cache->ch_array; - ofg = TCOD_image_get_colors(cache->fg_colors); - obg = TCOD_image_get_colors(cache->bg_colors); - } - /* update opengl data */ - /* TODO use function pointers so that libtcod's putchar directly updates opengl data */ - for (y=0;yr != obg->r || nbg->g != obg->g || nbg->b != obg->b || - nfg->r != ofg->r || nfg->g != ofg->g || nfg->b != ofg->b || - *c != *oc) { - changed=true; - } - } - if ( changed ) { - TCOD_opengl_putchar_ex(x, y, TCOD_get_tileid_for_charcode_(*c), *nfg, *nbg); - } - c++; - nfg++; - nbg++; - if (track_changes) { - oc++; - ofg++; - obg++; - } - } - } - - /* check if any of the textures have changed since they were last uploaded */ - for( i = 0; i< ConsoleDataEnumSize; i++) - { - if(dirty[i]) - { - updateTex((ConsoleDataEnum)i); - dirty[i] = false; - } - } - if ( TCOD_ctx.renderer == TCOD_RENDERER_OPENGL ) { - /* fixed pipeline for video cards without pixel shader support */ - /* draw the background as a single quad */ - float texw=(float)conwidth/POTconwidth; - float texh=(float)conheight/POTconheight; - float fonw=(float)fontwidth/(TCOD_ctx.fontNbCharHoriz*POTfontwidth); - float fonh=(float)fontheight/(TCOD_ctx.fontNbCharVertic*POTfontheight); - DBGCHECKGL(glBindTexture(GL_TEXTURE_2D, Tex[BackCol])); - DBGCHECKGL(glBegin(GL_QUADS); - glColor3f(1.0,1.0,1.0); - glTexCoord2f( 0.0, 0.0 ); - glVertex2i( 0, 0); - glTexCoord2f( 0.0, texh); - glVertex2i( 0, conheight ); - glTexCoord2f( texw, texh ); - glVertex2i( conwidth, conheight); - glTexCoord2f( texw, 0.0 ); - glVertex2i( conwidth, 0 ); - glEnd()); - /* draw the characters (one quad per cell) */ - DBGCHECKGL(glBindTexture(GL_TEXTURE_2D, font_tex)); - - c = console->ch_array; - nfg = TCOD_image_get_colors(console->fg_colors); - nbg = TCOD_image_get_colors(console->bg_colors); - for (y=0;yValidate()); */ - - DBGCHECKGL(glBegin(GL_QUADS); - glTexCoord2f(0.0f, 1.0f); - glVertex3f(-1.0f,-1.0f,0.0f); - glTexCoord2f(1.0f, 1.0f); - glVertex3f(1.0f,-1.0f,0.0f); - glTexCoord2f(1.0f, 0.0f); - glVertex3f(1.0f,1.0f, 0.0f); - glTexCoord2f(0.0f, 0.0f); - glVertex3f(-1.0f,1.0f,0.0f); - glEnd()); - - DBGCHECKGL(glBindTexture(GL_TEXTURE_2D, 0)); - - DBGCHECKGL(glUseProgramObjectARB(0)); - } - /* fading overlay */ - if ( fade != 255 ) { - int x=0,y=0; - if ( TCOD_ctx.fullscreen ) { - x=TCOD_ctx.fullscreen_offsetx/TCOD_ctx.font_width; - y=TCOD_ctx.fullscreen_offsety/TCOD_ctx.font_height; - } - glBegin( GL_QUADS ); - glColor4f(TCOD_ctx.fading_color.r/255.0f,TCOD_ctx.fading_color.g/255.0f,TCOD_ctx.fading_color.b/255.0f,1.0f-fade/255.0f); - glVertex2i( x, y); - glVertex2i( x, y+conheight ); - glVertex2i( x+conwidth, y+conheight ); - glVertex2i( x+conwidth, y); - glEnd(); - } - return true; -} - -void TCOD_opengl_swap(void) { - SDL_GL_SwapWindow(window); -} - -void * TCOD_opengl_get_screen(void) { - SDL_Surface *surf; - int pixw,pixh,offx=0,offy=0,x,y; - uint32_t mask,nmask; - - /* allocate a pixel buffer */ - pixw=TCOD_ctx.root->w * TCOD_ctx.font_width; - pixh=TCOD_ctx.root->h * TCOD_ctx.font_height; - surf=TCOD_sys_get_surface(pixw,pixh,false); - if ( TCOD_ctx.fullscreen ) { - offx=TCOD_ctx.fullscreen_offsetx; - offy=TCOD_ctx.fullscreen_offsety; - } - - /* get pixel data from opengl */ - glPushClientAttrib( GL_CLIENT_PIXEL_STORE_BIT ); - glPixelStorei(GL_PACK_ROW_LENGTH, 0); - glPixelStorei(GL_PACK_ALIGNMENT, 1); - glReadPixels(offx,offy,pixw,pixh, GL_RGB, GL_UNSIGNED_BYTE, surf->pixels); - glPopClientAttrib(); - - /* vertical flip (opengl has lower-left origin, SDL upper left) */ - mask=surf->format->Rmask|surf->format->Gmask|surf->format->Bmask; - nmask=~mask; - for (x=0; x < surf->w; x++) { - for (y=0; y < surf->h/2; y++) { - int offsrc=x*3+y*surf->pitch; - int offdst=x*3+(surf->h-1-y)*surf->pitch; - uint32_t *pixsrc = (uint32_t *)(((uint8_t*)surf->pixels)+offsrc); - uint32_t *pixdst = (uint32_t *)(((uint8_t*)surf->pixels)+offdst); - uint32_t tmp = *pixsrc; - *pixsrc = ((*pixsrc) & nmask) | ((*pixdst) & mask); - *pixdst = ((*pixdst) & nmask) | (tmp & mask); - } - } - - return (void *)surf; -} - -#endif /* NO_OPENGL */ - -#endif /* TCOD_BARE */ +/* +* libtcod +* Copyright (c) 2008-2018 Jice & Mingos & rmtew +* All rights reserved. +* +* Redistribution and use in source and binary forms, with or without +* modification, are permitted provided that the following conditions are met: +* * Redistributions of source code must retain the above copyright +* notice, this list of conditions and the following disclaimer. +* * Redistributions in binary form must reproduce the above copyright +* notice, this list of conditions and the following disclaimer in the +* documentation and/or other materials provided with the distribution. +* * The name of Jice or Mingos may not be used to endorse or promote +* products derived from this software without specific prior written +* permission. +* +* THIS SOFTWARE IS PROVIDED BY JICE, MINGOS AND RMTEW ``AS IS'' AND ANY +* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED +* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE +* DISCLAIMED. IN NO EVENT SHALL JICE, MINGOS OR RMTEW BE LIABLE FOR ANY +* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES +* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; +* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND +* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS +* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +*/ +/* + * This renderer is mostly copied and pasted from Antagonist's SkyFire GLSL roguelike engine + */ +#ifndef TCOD_BARE +#include "sys.h" + +#include "libtcod_int.h" +#include "console.h" + +#ifndef NO_OPENGL +#include +#include +#include + +#define CHECKGL( GLcall ) \ + GLcall; \ + if(!_CheckGL_Error( #GLcall, __FILE__, __LINE__)) \ + return false; + +#ifdef NDEBUG +#define DBGCHECKGL(GLcall) GLcall +#else +#define DBGCHECKGL CHECKGL +#endif + +typedef enum +{ + Character, + ForeCol, + BackCol, + ConsoleDataEnumSize +} ConsoleDataEnum; +/* JBR04152012 - Made Character a 4 byte value here to support extended characters like other renderers. + Seems like it should be possible to make it a two byte value using GL_UNSIGNED_SHORT_5_6_5_REV in updateTex, + but I can't seem to get the math right in the shader code, it always loses precision somewhere, + resulting in incorrect characters. */ +const int ConsoleDataAlignment[3] = {4, 3, 3 }; + +static const char *TCOD_con_vertex_shader = +#ifndef NDEBUG +"#version 110\n" +#endif +"uniform vec2 termsize; " + +"void main(void) " +"{ " + +" gl_Position = gl_Vertex; " + +" gl_TexCoord[0] = gl_MultiTexCoord0; " +" gl_TexCoord[0].x = gl_TexCoord[0].x*termsize.x; " +" gl_TexCoord[0].y = gl_TexCoord[0].y*termsize.y; " +"} " +; + +static const char *TCOD_con_pixel_shader = +#ifndef NDEBUG +"#version 110\n" +#endif +"uniform sampler2D font; " +"uniform sampler2D term; " +"uniform sampler2D termfcol; " +"uniform sampler2D termbcol; " + +"uniform float fontw; " +"uniform vec2 fontcoef; " +"uniform vec2 termsize; " +"uniform vec2 termcoef; " + +"void main(void) " +"{ " +" vec2 rawCoord = gl_TexCoord[0].xy; " /* varying from [0, termsize) in x and y */ +" vec2 conPos = floor(rawCoord); " /* console integer position */ +" vec2 pixPos = fract(rawCoord); " /* pixel offset within console position */ +" pixPos = vec2(pixPos.x*fontcoef.x,pixPos.y*fontcoef.y); " /* Correct pixel offset for font tex location */ + +" vec2 address = vec2(conPos.x*termcoef.x,conPos.y*termcoef.y); " +" address=address+vec2(0.001, 0.001); " +" vec4 charvec = texture2D(term,address);" +" float inchar = (charvec.r * 256.0) + (charvec.g * 256.0 * 256.0);" /* character */ +" vec4 tcharfcol = texture2D(termfcol, address); " /* front color */ +" vec4 tcharbcol = texture2D(termbcol, address); " /* back color */ + +" vec4 tchar = vec4(mod(floor(inchar),floor(fontw)),floor(inchar/fontw), 0.0, 0.0); " /* 1D index to 2D index map for character */ + +" gl_FragColor = texture2D(font, vec2((tchar.x*fontcoef.x),(tchar.y*fontcoef.y))+pixPos.xy); " /* magic func: finds pixel value in font file */ +" gl_FragColor=gl_FragColor.a*tcharfcol+(1.0-gl_FragColor.a)*tcharbcol; " /* Coloring stage */ +"} " +; + +bool _CheckGL_Error(const char* GLcall, const char* file, const int line) +{ + GLenum errCode; + if((errCode = glGetError())!=GL_NO_ERROR) + { + printf("OPENGL ERROR #%i: in file %s on line %i\n",errCode,file, line); + printf("OPENGL Call: %s\n",GLcall); + return false; + } + return true; +} + +/* called before creating window */ +void TCOD_opengl_init_attributes(void) { + static bool first=true; + if ( first ) { + SDL_GL_SetAttribute(SDL_GL_DOUBLEBUFFER, 1); + SDL_GL_SetAttribute(SDL_GL_RED_SIZE, 8); + SDL_GL_SetAttribute(SDL_GL_BLUE_SIZE, 8); + SDL_GL_SetAttribute(SDL_GL_GREEN_SIZE,8); + SDL_GL_SetAttribute(SDL_GL_BUFFER_SIZE, 32 ); + /* ATI driver bug : enabling this might result in red screen */ + /* SDL_GL_SetAttribute(SDL_GL_ACCELERATED_VISUAL, 1); */ + first=false; + } +} + +/* console size (power of 2 and cells) */ +static int POTconwidth, POTconheight, conwidth, conheight; +/* programs and shaders handles */ +static GLhandleARB conProgram, conVertShader, conFragShader; +/* font texture handle */ +static GLuint font_tex; +/* font power of 2 size and pixels */ +static int POTfontwidth,POTfontheight, fontwidth,fontheight; +/* console data */ +static GLuint Tex[ConsoleDataEnumSize]; +static unsigned char *data[ConsoleDataEnumSize]; +static bool dirty[ConsoleDataEnumSize]; + +/* extension function pointers */ +static PFNGLCREATESHADEROBJECTARBPROC glCreateShaderObjectARB=0; +static PFNGLGETOBJECTPARAMETERIVARBPROC glGetObjectParameterivARB=0; +static PFNGLSHADERSOURCEARBPROC glShaderSourceARB=0; +static PFNGLCOMPILESHADERARBPROC glCompileShaderARB=0; +static PFNGLGETINFOLOGARBPROC glGetInfoLogARB=0; +static PFNGLCREATEPROGRAMOBJECTARBPROC glCreateProgramObjectARB=0; +static PFNGLATTACHOBJECTARBPROC glAttachObjectARB=0; +static PFNGLLINKPROGRAMARBPROC glLinkProgramARB=0; +static PFNGLUSEPROGRAMOBJECTARBPROC glUseProgramObjectARB=0; +static PFNGLUNIFORM2FARBPROC glUniform2fARB=0; +static PFNGLGETUNIFORMLOCATIONARBPROC glGetUniformLocationARB=0; +static PFNGLUNIFORM1FARBPROC glUniform1fARB=0; +static PFNGLUNIFORM1IARBPROC glUniform1iARB=0; +static PFNGLACTIVETEXTUREPROC glActiveTextureF=0; + +static SDL_GLContext glcontext; + +void TCOD_opengl_uninit_state() { + SDL_GL_DeleteContext(glcontext); +} + +/* call after creating window */ +bool TCOD_opengl_init_state(int conw, int conh, void *font) { + SDL_Surface *font_surf=(SDL_Surface *)font; + SDL_PixelFormat *my_format=SDL_AllocFormat(SDL_GetWindowPixelFormat(window)); + + /* convert font for opengl */ + uint32_t rmask, gmask, bmask, amask; + SDL_Surface *temp; + SDL_Surface *temp_alpha; + + glcontext = SDL_GL_CreateContext(window); + + /* check opengl extensions */ + if ( TCOD_ctx.renderer == TCOD_RENDERER_GLSL ) { + bool hasShader = false; + const char *glexts=(const char *)glGetString(GL_EXTENSIONS); + if (glexts ) { + hasShader = (strstr(glexts,"GL_ARB_shader_objects") != NULL); + } + if (! hasShader ) { + TCOD_LOG(("Missing GL_ARB_shader_objects extension. Falling back to fixed pipeline...\n")); + TCOD_ctx.renderer = TCOD_RENDERER_OPENGL; + } + } + + /* set extensions functions pointers */ + glCreateShaderObjectARB=(PFNGLCREATESHADEROBJECTARBPROC)SDL_GL_GetProcAddress("glCreateShaderObjectARB"); + glGetObjectParameterivARB=(PFNGLGETOBJECTPARAMETERIVARBPROC)SDL_GL_GetProcAddress("glGetObjectParameterivARB"); + glShaderSourceARB=(PFNGLSHADERSOURCEARBPROC)SDL_GL_GetProcAddress("glShaderSourceARB"); + glCompileShaderARB=(PFNGLCOMPILESHADERARBPROC)SDL_GL_GetProcAddress("glCompileShaderARB"); + glGetInfoLogARB=(PFNGLGETINFOLOGARBPROC)SDL_GL_GetProcAddress("glGetInfoLogARB"); + glCreateProgramObjectARB=(PFNGLCREATEPROGRAMOBJECTARBPROC)SDL_GL_GetProcAddress("glCreateProgramObjectARB"); + glAttachObjectARB=(PFNGLATTACHOBJECTARBPROC)SDL_GL_GetProcAddress("glAttachObjectARB"); + glLinkProgramARB=(PFNGLLINKPROGRAMARBPROC)SDL_GL_GetProcAddress("glLinkProgramARB"); + glUseProgramObjectARB=(PFNGLUSEPROGRAMOBJECTARBPROC)SDL_GL_GetProcAddress("glUseProgramObjectARB"); + glUniform2fARB=(PFNGLUNIFORM2FARBPROC)SDL_GL_GetProcAddress("glUniform2fARB"); + glGetUniformLocationARB=(PFNGLGETUNIFORMLOCATIONARBPROC)SDL_GL_GetProcAddress("glGetUniformLocationARB"); + glUniform1fARB=(PFNGLUNIFORM1FARBPROC)SDL_GL_GetProcAddress("glUniform1fARB"); + glUniform1iARB=(PFNGLUNIFORM1IARBPROC)SDL_GL_GetProcAddress("glUniform1iARB"); + glActiveTextureF=(PFNGLACTIVETEXTUREPROC)SDL_GL_GetProcAddress("glActiveTexture"); + + /* set opengl state */ + glEnable(GL_TEXTURE_2D); + glClearColor(1.0f, 1.0f, 0.0f, 0.0f); + glPixelStorei(GL_UNPACK_ALIGNMENT, 1); + glClear( GL_COLOR_BUFFER_BIT ); + glMatrixMode( GL_PROJECTION ); + glLoadIdentity(); + if ( TCOD_ctx.renderer == TCOD_RENDERER_GLSL ) { + glOrtho(0, conw, 0, conh, -1.0f, 1.0f); + glDisable (GL_BLEND); + } else { + glOrtho(0, conw, conh, 0.0f, -1.0f, 1.0f); + glEnable (GL_BLEND); + glBlendFunc (GL_ONE, GL_ONE_MINUS_SRC_ALPHA); + } + + glMatrixMode( GL_MODELVIEW ); + glLoadIdentity(); +/*#ifdef TCOD_WINDOWS */ + if ( ! TCOD_ctx.fullscreen ) { + /* turn vsync off in windowed mode */ + typedef bool (APIENTRY *PFNWGLSWAPINTERVALFARPROC)(int); + PFNWGLSWAPINTERVALFARPROC wglSwapIntervalEXT = 0; + + wglSwapIntervalEXT = (PFNWGLSWAPINTERVALFARPROC)SDL_GL_GetProcAddress("wglSwapIntervalEXT"); + + if (wglSwapIntervalEXT) wglSwapIntervalEXT(0); + } +/*#endif */ + + /* compute pot size */ + conwidth=conw; + conheight=conh; + POTconwidth=POTconheight=1; + while ( POTconwidth < conw ) POTconwidth *= 2; + while ( POTconheight < conh ) POTconheight *= 2; + + + #if SDL_BYTEORDER == SDL_BIG_ENDIAN + rmask = 0xff000000; + gmask = 0x00ff0000; + bmask = 0x0000ff00; + amask = 0x000000ff; + #else + rmask = 0x000000ff; + gmask = 0x0000ff00; + bmask = 0x00ff0000; + amask = 0xff000000; + #endif + + fontwidth=font_surf->w; + fontheight=font_surf->h; + POTfontwidth=POTfontheight=1; + while ( POTfontwidth < fontwidth ) POTfontwidth *= 2; + while ( POTfontheight < fontheight ) POTfontheight *= 2; + + SDL_SetColorKey(font_surf, 1, SDL_MapRGB(font_surf->format, 0, 0, 0)); + my_format->Amask = amask; + temp_alpha = SDL_ConvertSurface(font_surf, my_format, 0); + SDL_FreeFormat(my_format); + + temp = SDL_CreateRGBSurface(SDL_SWSURFACE, POTfontwidth, POTfontheight, 32, bmask, gmask, rmask, amask); /*BGRA */ + + SDL_BlitSurface(temp_alpha, NULL, temp, NULL); + SDL_FreeSurface(temp_alpha); + + CHECKGL(glGenTextures(1, &font_tex)); + CHECKGL(glBindTexture(GL_TEXTURE_2D, font_tex)); + SDL_LockSurface(temp); + + glTexParameteri( GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST ); + glTexParameteri( GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST ); + + CHECKGL(glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, temp->w, temp->h, 0, GL_BGRA, GL_UNSIGNED_BYTE, temp->pixels)); + SDL_UnlockSurface(temp); + SDL_FreeSurface(temp); + return true; +} + +static GLhandleARB loadShader(const char *txt, GLuint type) { + int success; + int infologLength = 0; + int charsWritten = 0; + char *infoLog; + GLhandleARB v = glCreateShaderObjectARB(type); + glShaderSourceARB(v, 1, &txt, 0); + glCompileShaderARB(v); + + glGetObjectParameterivARB(v, GL_COMPILE_STATUS, &success); + if(success!=GL_TRUE) + { + /* something went wrong */ + glGetObjectParameterivARB(v, GL_INFO_LOG_LENGTH,&infologLength); + if(infologLength>0) + { + infoLog = (char *)malloc(infologLength); + glGetInfoLogARB(v, infologLength, &charsWritten, infoLog); + printf("GLSL ERROR : %s\n",infoLog); + free(infoLog); + } + return 0; + } + + return v; +} + +static bool loadProgram(const char *vertShaderCode, const char *fragShaderCode, + GLhandleARB *vertShader, GLhandleARB *fragShader, GLhandleARB *prog) { + /* Create and load Program and Shaders */ + int success; + *prog = DBGCHECKGL(glCreateProgramObjectARB()); + + *vertShader = loadShader(vertShaderCode, GL_VERTEX_SHADER); + if ( *vertShader == 0 ) return false; + glAttachObjectARB(*prog, *vertShader); + + *fragShader = loadShader(fragShaderCode, GL_FRAGMENT_SHADER); + if ( *fragShader == 0 ) return false; + glAttachObjectARB(*prog, *fragShader); + + glLinkProgramARB(*prog); + + glGetObjectParameterivARB(*prog, GL_LINK_STATUS, &success); + if(success!=GL_TRUE) + { + /* something went wrong */ + int infologLength = 0; + int charsWritten = 0; + char *infoLog; + glGetObjectParameterivARB(*prog, GL_INFO_LOG_LENGTH,&infologLength); + if (infologLength > 0) + { + infoLog = (char *)malloc(infologLength); + glGetInfoLogARB(*prog, infologLength, &charsWritten, infoLog); + printf("OPENGL ERROR: Program link Error"); + printf("%s\n",infoLog); + free(infoLog); + } + return false; + } + return true; +} + +bool TCOD_opengl_init_shaders(void) { + int i; + TCOD_color_t *fCol; + if ( TCOD_ctx.renderer == TCOD_RENDERER_GLSL ) { + if (! loadProgram(TCOD_con_vertex_shader, TCOD_con_pixel_shader, &conVertShader, &conFragShader, &conProgram ) ) return false; + } + /* Host side data init */ + for(i = 0; i< ConsoleDataEnumSize; i++) + { + data[i] = (unsigned char *)calloc(conwidth*conheight,ConsoleDataAlignment[i]); + dirty[i]=true; + } + /* Initialize ForeCol to 255, 255, 255, 255 */ + fCol = (TCOD_color_t *)data[ForeCol]; + for( i = 0; i < conwidth*conheight; i++) + { + fCol[i].r=255; + fCol[i].g=255; + fCol[i].b=255; + } + + /* Generate Textures */ + glGenTextures(3, Tex); + + /* Character Texture */ + CHECKGL(glBindTexture(GL_TEXTURE_2D, Tex[Character])); + + CHECKGL(glTexParameteri( GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST )); + CHECKGL(glTexParameteri( GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST )); + + CHECKGL(glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, POTconwidth, POTconheight, 0, GL_LUMINANCE, GL_UNSIGNED_BYTE, 0)); + + + /* ForeCol Texture */ + CHECKGL(glBindTexture(GL_TEXTURE_2D, Tex[ForeCol])); + + CHECKGL(glTexParameteri( GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST )); + CHECKGL(glTexParameteri( GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST )); + + CHECKGL(glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, POTconwidth, POTconheight, 0, GL_RGB, GL_UNSIGNED_BYTE, 0)); + + /* BackCol Texture */ + CHECKGL(glBindTexture(GL_TEXTURE_2D, Tex[BackCol])); + + CHECKGL(glTexParameteri( GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST )); + CHECKGL(glTexParameteri( GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST )); + + CHECKGL(glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, POTconwidth, POTconheight, 0, GL_RGB, GL_UNSIGNED_BYTE, 0)); + + CHECKGL(glBindTexture(GL_TEXTURE_2D, 0)); + + return true; +} + +static bool updateTex(ConsoleDataEnum dataType) { + GLenum Type=0; + DBGCHECKGL(glBindTexture(GL_TEXTURE_2D, Tex[dataType])); + + switch(ConsoleDataAlignment[dataType]) + { + case 1: + Type = GL_RED; + break; + /*case 2: + Type = GL_RG; + break; */ + case 3: + Type = GL_RGB; + break; + case 4: + Type = GL_RGBA; + break; + } + /*glPixelStorei(GL_UNPACK_ALIGNMENT, 1); */ + DBGCHECKGL(glTexSubImage2D(GL_TEXTURE_2D, 0, 0, 0, conwidth, conheight, Type, GL_UNSIGNED_BYTE, data[dataType])); + + DBGCHECKGL(glBindTexture(GL_TEXTURE_2D,0)); + return true; +} + +static void updateChar(ConsoleDataEnum dataType, int BufferPos, unsigned char *c, int length, int offset) { + int i; + dirty[dataType] = true; /* Set dirty so Texture gets updated next frame */ + + for(i = 0; ich_array; + int *oc; + nfg = console->fg_array; + nbg = console->bg_array; + if (track_changes) { + oc = cache->ch_array; + ofg = cache->fg_array; + obg = cache->bg_array; + } + /* update opengl data */ + /* TODO use function pointers so that libtcod's putchar directly updates opengl data */ + for (y=0;yr != obg->r || nbg->g != obg->g || nbg->b != obg->b || + nfg->r != ofg->r || nfg->g != ofg->g || nfg->b != ofg->b || + *c != *oc) { + changed=true; + } + } + if ( changed ) { + TCOD_opengl_putchar_ex(x, y, TCOD_get_tileid_for_charcode_(*c), *nfg, *nbg); + } + c++; + nfg++; + nbg++; + if (track_changes) { + oc++; + ofg++; + obg++; + } + } + } + + /* check if any of the textures have changed since they were last uploaded */ + for( i = 0; i< ConsoleDataEnumSize; i++) + { + if(dirty[i]) + { + updateTex((ConsoleDataEnum)i); + dirty[i] = false; + } + } + if ( TCOD_ctx.renderer == TCOD_RENDERER_OPENGL ) { + /* fixed pipeline for video cards without pixel shader support */ + /* draw the background as a single quad */ + float texw=(float)conwidth/POTconwidth; + float texh=(float)conheight/POTconheight; + float fonw=(float)fontwidth/(TCOD_ctx.fontNbCharHoriz*POTfontwidth); + float fonh=(float)fontheight/(TCOD_ctx.fontNbCharVertic*POTfontheight); + DBGCHECKGL(glBindTexture(GL_TEXTURE_2D, Tex[BackCol])); + DBGCHECKGL(glBegin(GL_QUADS); + glColor3f(1.0,1.0,1.0); + glTexCoord2f( 0.0, 0.0 ); + glVertex2i( 0, 0); + glTexCoord2f( 0.0, texh); + glVertex2i( 0, conheight ); + glTexCoord2f( texw, texh ); + glVertex2i( conwidth, conheight); + glTexCoord2f( texw, 0.0 ); + glVertex2i( conwidth, 0 ); + glEnd()); + /* draw the characters (one quad per cell) */ + DBGCHECKGL(glBindTexture(GL_TEXTURE_2D, font_tex)); + + c = console->ch_array; + nfg = console->fg_array; + nbg = console->bg_array; + for (y=0;yValidate()); */ + + DBGCHECKGL(glBegin(GL_QUADS); + glTexCoord2f(0.0f, 1.0f); + glVertex3f(-1.0f,-1.0f,0.0f); + glTexCoord2f(1.0f, 1.0f); + glVertex3f(1.0f,-1.0f,0.0f); + glTexCoord2f(1.0f, 0.0f); + glVertex3f(1.0f,1.0f, 0.0f); + glTexCoord2f(0.0f, 0.0f); + glVertex3f(-1.0f,1.0f,0.0f); + glEnd()); + + DBGCHECKGL(glBindTexture(GL_TEXTURE_2D, 0)); + + DBGCHECKGL(glUseProgramObjectARB(0)); + } + /* fading overlay */ + if ( fade != 255 ) { + int x=0,y=0; + if ( TCOD_ctx.fullscreen ) { + x=TCOD_ctx.fullscreen_offsetx/TCOD_ctx.font_width; + y=TCOD_ctx.fullscreen_offsety/TCOD_ctx.font_height; + } + glBegin( GL_QUADS ); + glColor4f(TCOD_ctx.fading_color.r/255.0f,TCOD_ctx.fading_color.g/255.0f,TCOD_ctx.fading_color.b/255.0f,1.0f-fade/255.0f); + glVertex2i( x, y); + glVertex2i( x, y+conheight ); + glVertex2i( x+conwidth, y+conheight ); + glVertex2i( x+conwidth, y); + glEnd(); + } + return true; +} + +void TCOD_opengl_swap(void) { + SDL_GL_SwapWindow(window); +} + +void * TCOD_opengl_get_screen(void) { + SDL_Surface *surf; + int pixw,pixh,offx=0,offy=0,x,y; + uint32_t mask,nmask; + + /* allocate a pixel buffer */ + pixw=TCOD_ctx.root->w * TCOD_ctx.font_width; + pixh=TCOD_ctx.root->h * TCOD_ctx.font_height; + surf=(SDL_Surface*)TCOD_sys_get_surface(pixw,pixh,false); + if ( TCOD_ctx.fullscreen ) { + offx=TCOD_ctx.fullscreen_offsetx; + offy=TCOD_ctx.fullscreen_offsety; + } + + /* get pixel data from opengl */ + glPushClientAttrib( GL_CLIENT_PIXEL_STORE_BIT ); + glPixelStorei(GL_PACK_ROW_LENGTH, 0); + glPixelStorei(GL_PACK_ALIGNMENT, 1); + glReadPixels(offx,offy,pixw,pixh, GL_RGB, GL_UNSIGNED_BYTE, surf->pixels); + glPopClientAttrib(); + + /* vertical flip (opengl has lower-left origin, SDL upper left) */ + mask=surf->format->Rmask|surf->format->Gmask|surf->format->Bmask; + nmask=~mask; + for (x=0; x < surf->w; x++) { + for (y=0; y < surf->h/2; y++) { + int offsrc=x*3+y*surf->pitch; + int offdst=x*3+(surf->h-1-y)*surf->pitch; + uint32_t *pixsrc = (uint32_t *)(((uint8_t*)surf->pixels)+offsrc); + uint32_t *pixdst = (uint32_t *)(((uint8_t*)surf->pixels)+offdst); + uint32_t tmp = *pixsrc; + *pixsrc = ((*pixsrc) & nmask) | ((*pixdst) & mask); + *pixdst = ((*pixdst) & nmask) | (tmp & mask); + } + } + + return (void *)surf; +} + +#endif /* NO_OPENGL */ + +#endif /* TCOD_BARE */ diff --git a/tcod_sys/libtcod/src/libtcod/sys_sdl2_c.cpp b/tcod_sys/libtcod/src/libtcod/sys_sdl2_c.cpp new file mode 100644 index 000000000..8bb6324e6 --- /dev/null +++ b/tcod_sys/libtcod/src/libtcod/sys_sdl2_c.cpp @@ -0,0 +1,1060 @@ +/* +* libtcod +* Copyright (c) 2008-2018 Jice & Mingos & rmtew +* All rights reserved. +* +* Redistribution and use in source and binary forms, with or without +* modification, are permitted provided that the following conditions are met: +* * Redistributions of source code must retain the above copyright +* notice, this list of conditions and the following disclaimer. +* * Redistributions in binary form must reproduce the above copyright +* notice, this list of conditions and the following disclaimer in the +* documentation and/or other materials provided with the distribution. +* * The name of Jice or Mingos may not be used to endorse or promote +* products derived from this software without specific prior written +* permission. +* +* THIS SOFTWARE IS PROVIDED BY JICE, MINGOS AND RMTEW ``AS IS'' AND ANY +* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED +* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE +* DISCLAIMED. IN NO EVENT SHALL JICE, MINGOS OR RMTEW BE LIABLE FOR ANY +* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES +* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; +* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND +* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS +* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +*/ +#ifndef TCOD_BARE + +#include + +#include +#include + +#include + +#include +#include +#include + +static SDL_Surface* scale_screen=NULL; +static bool clear_screen=false; +static TCOD_console_data_t *root_console_cache; /* cache for previous values */ + +/* This just forces a complete redraw, bypassing the usual rendering of changes. */ +void TCOD_sys_set_clear_screen(void) { + clear_screen=true; +} + +static void get_closest_mode(int *w, int *h) { + SDL_DisplayMode wantedmode, closestmode; + wantedmode.w = *w; + wantedmode.h = *h; + wantedmode.format = 0; /* don't care for rest. */ + wantedmode.refresh_rate = 0; + wantedmode.driverdata = 0; + if (SDL_GetClosestDisplayMode(window?SDL_GetWindowDisplayIndex(window):0, &wantedmode, &closestmode) == &closestmode) { + *w=closestmode.w; + *h=closestmode.h; + } +} + +/* + * Separate out the actual rendering, so that render to texture can be done. + */ +static void actual_rendering(void) { + SDL_Rect srcRect, dstRect; + SDL_Texture *texture; + + if (scale_data.min_scale_factor - 1e-3f > scale_factor) { + /* Prepare for the unscaled and centered copy of the entire console. */ + srcRect.x=0; srcRect.y=0; srcRect.w=scale_screen->w; srcRect.h=scale_screen->h; + if (TCOD_ctx.fullscreen) { + dstRect.x=TCOD_ctx.fullscreen_offsetx; dstRect.y=TCOD_ctx.fullscreen_offsety; + } else { + dstRect.x=0; dstRect.y=0; + } + dstRect.w=scale_screen->w; dstRect.h=scale_screen->h; + } else { + /* Prepare for the scaled copy of the displayed console area. */ + srcRect.x=scale_data.src_x0; srcRect.y=scale_data.src_y0; srcRect.w=scale_data.src_copy_width; srcRect.h=scale_data.src_copy_height; + dstRect.x=scale_data.dst_offset_x; dstRect.y=scale_data.dst_offset_y; + dstRect.w=scale_data.dst_display_width; dstRect.h=scale_data.dst_display_height; + } + if ( TCOD_ctx.sdl_cbk ) { + TCOD_ctx.sdl_cbk((void *)scale_screen); + } + texture = SDL_CreateTextureFromSurface(renderer, scale_screen); + SDL_RenderCopy(renderer, texture, &srcRect, &dstRect); + SDL_DestroyTexture(texture); +} + +/* Return an up-to-date cache for the root console, create or resize the cache + if needed */ +static TCOD_console_data_t *ensure_cache(TCOD_console_data_t* root) { + if (!root_console_cache || + root_console_cache->w != root->w || + root_console_cache->h != root->h) { + if (root_console_cache) { TCOD_console_delete(root_console_cache); } + root_console_cache = TCOD_console_new(root->w, root->h); + } + return root_console_cache; +} + +/* In order to avoid rendering race conditions and the ensuing segmentation + * faults, this should only be called when it would normally be and not + * specifically to force screen refreshes. To this end, and to avoid + * threading complications it takes care of special cases internally. */ +static void render(TCOD_SDL_driver_t *sdl, void *vbitmap, TCOD_console_data_t *console) { + if ( TCOD_ctx.renderer == TCOD_RENDERER_SDL ) { + int console_width_p = console->w * TCOD_ctx.font_width; + int console_height_p = console->h * TCOD_ctx.font_height; + + /* Make a bitmap of exact rendering size and correct format. */ + if (scale_screen == NULL) { + int bpp; + uint32_t rmask, gmask, bmask, amask; + if (SDL_PixelFormatEnumToMasks(SDL_GetWindowPixelFormat(window), &bpp, &rmask, &gmask, &bmask, &amask) == SDL_FALSE) { + TCOD_fatal("SDL : failed to create scaling surface : indeterminate window pixel format"); + return; + } + scale_screen=SDL_CreateRGBSurface(SDL_SWSURFACE,console_width_p,console_height_p,bpp,rmask,gmask,bmask,amask); + if (scale_screen == NULL) { + TCOD_fatal("SDL : failed to create scaling surface"); + return; + } + } else if (clear_screen) { + clear_screen=false; + SDL_FillRect(scale_screen,0,0); + /* Implicitly do complete console redraw, not just tracked changes. */ + TCOD_console_set_dirty(0, 0, console->w, console->h); + } + + TCOD_sys_console_to_bitmap(scale_screen, console, ensure_cache(console)); + + /* Scale the rendered bitmap to the screen, preserving aspect ratio, and blit it. + * This data is also used for console coordinate resolution.. */ + if (scale_data.last_scale_factor != scale_factor || scale_data.last_scale_xc != sdl->scale_xc || scale_data.last_scale_yc != sdl->scale_yc || + scale_data.last_fullscreen != TCOD_ctx.fullscreen || scale_data.force_recalc) { + /* Preserve old value of input variables, to enable recalculation if they change. */ + scale_data.last_scale_factor = scale_factor; + scale_data.last_scale_xc = sdl->scale_xc; + scale_data.last_scale_yc = sdl->scale_yc; + scale_data.last_fullscreen = TCOD_ctx.fullscreen; + scale_data.force_recalc = 0; + + if (scale_data.last_fullscreen) { + scale_data.surface_width = TCOD_ctx.actual_fullscreen_width; + scale_data.surface_height = TCOD_ctx.actual_fullscreen_height; + } else { + scale_data.surface_width = console_width_p; + scale_data.surface_height = console_height_p; + } + scale_data.min_scale_factor = MAX((float)console_width_p/scale_data.surface_width, (float)console_height_p/scale_data.surface_height); + if (scale_data.min_scale_factor > 1.0f) + scale_data.min_scale_factor = 1.0f; + /*printf("min_scale_factor %0.3f = MAX(%d/%d, %d/%d)", scale_data.min_scale_factor, console_width_p, scale_data.surface_width, console_height_p, scale_data.surface_height);*/ + + scale_data.dst_height_width_ratio = (float)scale_data.surface_height/scale_data.surface_width; + scale_data.src_proportionate_width = (int)(console_width_p / scale_factor); + scale_data.src_proportionate_height = (int)((console_width_p * scale_data.dst_height_width_ratio) / scale_factor); + + /* Work out how much of the console to copy. */ + scale_data.src_x0 = (int)((sdl->scale_xc * console_width_p) - (0.5f * scale_data.src_proportionate_width)); + if (scale_data.src_x0 + scale_data.src_proportionate_width > console_width_p) + scale_data.src_x0 = console_width_p - scale_data.src_proportionate_width; + if (scale_data.src_x0 < 0) + scale_data.src_x0 = 0; + scale_data.src_copy_width = scale_data.src_proportionate_width; + if (scale_data.src_x0 + scale_data.src_copy_width > console_width_p) + scale_data.src_copy_width = console_width_p - scale_data.src_x0; + + scale_data.src_y0 = (int)((sdl->scale_yc * console_height_p) - (0.5f * scale_data.src_proportionate_height)); + if (scale_data.src_y0 + scale_data.src_proportionate_height > console_height_p) + scale_data.src_y0 = console_height_p - scale_data.src_proportionate_height; + if (scale_data.src_y0 < 0) + scale_data.src_y0 = 0; + scale_data.src_copy_height = scale_data.src_proportionate_height; + if (scale_data.src_y0 + scale_data.src_copy_height > console_height_p) + scale_data.src_copy_height = console_height_p - scale_data.src_y0; + + scale_data.dst_display_width = (scale_data.src_copy_width * scale_data.surface_width) / scale_data.src_proportionate_width; + scale_data.dst_display_height = (scale_data.src_copy_height * scale_data.surface_height) / scale_data.src_proportionate_height; + scale_data.dst_offset_x = (scale_data.surface_width - scale_data.dst_display_width)/2; + scale_data.dst_offset_y = (scale_data.surface_height - scale_data.dst_display_height)/2; + } + + SDL_RenderClear(renderer); + actual_rendering(); + SDL_RenderPresent(renderer); + } +#ifndef NO_OPENGL + else { + TCOD_opengl_render(oldFade, NULL, console, ensure_cache(console)); + TCOD_opengl_swap(); + } +#endif + oldFade=(int)TCOD_console_get_fade(); +} + +/* Return the current root console cache if it exists, or NULL. */ +static TCOD_console_data_t *get_root_console_cache(void){ + return root_console_cache; +} + +static SDL_Surface *create_surface(int width, int height, bool with_alpha) { + uint32_t rmask,gmask,bmask,amask; + SDL_Surface *bitmap; + int flags=SDL_SWSURFACE; + + if ( with_alpha ) { + if ( SDL_BYTEORDER == SDL_LIL_ENDIAN ) { + rmask=0x000000FF; + gmask=0x0000FF00; + bmask=0x00FF0000; + amask=0xFF000000; + } else { + rmask=0xFF000000; + gmask=0x00FF0000; + bmask=0x0000FF00; + amask=0x000000FF; + } + } else { + if ( SDL_BYTEORDER == SDL_LIL_ENDIAN ) { + rmask=0x0000FF; + gmask=0x00FF00; + bmask=0xFF0000; + } else { + rmask=0xFF0000; + gmask=0x00FF00; + bmask=0x0000FF; + } + amask=0; + } + bitmap=SDL_CreateRGBSurface(flags,width,height, + with_alpha ? 32:24, + rmask,gmask,bmask,amask); + if ( with_alpha ) { + SDL_SetSurfaceAlphaMod(bitmap, 255); + } + return (void *)bitmap; +} + +static void create_window(int w, int h, bool fullscreen) { + uint32_t winflags = SDL_WINDOW_SHOWN | SDL_WINDOW_OPENGL; +#if defined(TCOD_ANDROID) + /* Android should always be fullscreen. */ + TCOD_ctx.fullscreen = fullscreen = true; +#endif + if ( fullscreen ) { + find_resolution(); +#ifndef NO_OPENGL + if (TCOD_ctx.renderer != TCOD_RENDERER_SDL ) { + TCOD_opengl_init_attributes(); + winflags |= SDL_WINDOW_FULLSCREEN | SDL_WINDOW_BORDERLESS | SDL_WINDOW_OPENGL; +# if defined(TCOD_ANDROID) && defined(FUTURE_SUPPORT) + winflags |= SDL_WINDOW_RESIZABLE; +# endif + window = SDL_CreateWindow(TCOD_ctx.window_title,SDL_WINDOWPOS_CENTERED,SDL_WINDOWPOS_CENTERED,TCOD_ctx.actual_fullscreen_width,TCOD_ctx.actual_fullscreen_height,winflags); + if ( window && TCOD_opengl_init_state(w, h, charmap) && TCOD_opengl_init_shaders() ) { + TCOD_LOG(("Using %s renderer...\n",TCOD_ctx.renderer == TCOD_RENDERER_GLSL ? "GLSL" : "OPENGL")); + } else { + TCOD_LOG(("Fallback to SDL renderer...\n")); + TCOD_ctx.renderer = TCOD_RENDERER_SDL; + } + } +#endif + if (TCOD_ctx.renderer == TCOD_RENDERER_SDL ) { + winflags |= SDL_WINDOW_FULLSCREEN | SDL_WINDOW_BORDERLESS; +# if defined(TCOD_ANDROID) && defined(FUTURE_SUPPORT) + winflags |= SDL_WINDOW_RESIZABLE; +# endif + window = SDL_CreateWindow(TCOD_ctx.window_title,SDL_WINDOWPOS_CENTERED, SDL_WINDOWPOS_CENTERED, TCOD_ctx.actual_fullscreen_width,TCOD_ctx.actual_fullscreen_height,winflags); + if ( window == NULL ) TCOD_fatal("SDL : cannot set fullscreen video mode: %s", SDL_GetError()); + } + SDL_ShowCursor(0); + SDL_GetWindowSize(window,&TCOD_ctx.actual_fullscreen_width,&TCOD_ctx.actual_fullscreen_height); + TCOD_sys_init_screen_offset(); + } else { +#ifndef NO_OPENGL + if (TCOD_ctx.renderer != TCOD_RENDERER_SDL ) { + TCOD_opengl_init_attributes(); + winflags |= SDL_WINDOW_OPENGL; + window = SDL_CreateWindow(TCOD_ctx.window_title,SDL_WINDOWPOS_CENTERED,SDL_WINDOWPOS_CENTERED,w*TCOD_ctx.font_width,h*TCOD_ctx.font_height,winflags); + if ( window && TCOD_opengl_init_state(w, h, charmap) && TCOD_opengl_init_shaders() ) { + TCOD_LOG(("Using %s renderer...\n",TCOD_ctx.renderer == TCOD_RENDERER_GLSL ? "GLSL" : "OPENGL")); + } else { + TCOD_LOG(("Fallback to SDL renderer...\n")); + TCOD_ctx.renderer = TCOD_RENDERER_SDL; + } + } +#endif + if (TCOD_ctx.renderer == TCOD_RENDERER_SDL ) { + window = SDL_CreateWindow(TCOD_ctx.window_title,SDL_WINDOWPOS_CENTERED,SDL_WINDOWPOS_CENTERED,w*TCOD_ctx.font_width,h*TCOD_ctx.font_height,winflags); + SDL_PumpEvents(); + SDL_SetWindowSize(window,w*TCOD_ctx.font_width,h*TCOD_ctx.font_height); + TCOD_LOG(("Using SDL renderer...\n")); + } + if ( window == NULL ) TCOD_fatal("Cannot create SDL window: %s", SDL_GetError()); + } + if (TCOD_ctx.renderer == TCOD_RENDERER_SDL ) { + renderer = SDL_CreateRenderer(window, -1, SDL_RENDERER_ACCELERATED); + if ( renderer == NULL ) TCOD_fatal("Cannot create SDL renderer: %s", SDL_GetError()); + SDL_SetRenderDrawColor(renderer, 0, 0, 0, SDL_ALPHA_OPAQUE); + } +} + +static void destroy_window(void) { +#ifndef NO_OPENGL + if (TCOD_ctx.renderer == TCOD_RENDERER_OPENGL || TCOD_ctx.renderer == TCOD_RENDERER_GLSL) { + TCOD_opengl_uninit_state(); + } +#endif + if (scale_screen) { + SDL_FreeSurface(scale_screen); + scale_screen = NULL; + } + if (renderer) { + SDL_DestroyRenderer(renderer); + renderer = NULL; + } + if (window) { + SDL_DestroyWindow(window); + window = NULL; + } +} + +static void set_fullscreen(bool fullscreen) { + bool mouseOn=SDL_ShowCursor(-1); + if ( fullscreen ) { + find_resolution(); + SDL_SetWindowFullscreen(window, fullscreen); + SDL_ShowCursor(mouseOn ? 1:0); + SDL_GetWindowSize(window,&TCOD_ctx.actual_fullscreen_width,&TCOD_ctx.actual_fullscreen_height); + TCOD_sys_init_screen_offset(); + } else { + SDL_SetWindowFullscreen(window, fullscreen); + SDL_ShowCursor(mouseOn ? 1:0); + TCOD_ctx.fullscreen_offsetx=0; + TCOD_ctx.fullscreen_offsety=0; + } + TCOD_ctx.fullscreen=fullscreen; + oldFade=-1; /* to redraw the whole screen */ +} + +static void set_window_title(const char *title) { + SDL_SetWindowTitle(window, title); +} + +static void save_screenshot(const char *filename) { + if ( TCOD_ctx.renderer == TCOD_RENDERER_SDL ) { + /* This would be a lot easier if image saving could do textures. */ + SDL_Rect rect; + uint32_t format; + SDL_Texture *texture; + SDL_RenderGetViewport(renderer, &rect); + format = SDL_GetWindowPixelFormat(window); + texture = SDL_CreateTexture(renderer, format, SDL_TEXTUREACCESS_TARGET, rect.w, rect.h); + if (0 != texture) { + if (SDL_SetRenderTarget(renderer, texture)) { + void *pixels; + int pitch, access; + + actual_rendering(); + SDL_SetRenderTarget(renderer, NULL); + + rect.x = rect.y = rect.w = rect.h = 0; + if (-1 != SDL_QueryTexture(texture, &format, &access, &rect.w, &rect.h) && + -1 != SDL_LockTexture(texture, NULL, &pixels, &pitch)) { + int depth; + uint32_t rmask, gmask, bmask, amask; + if (SDL_TRUE == SDL_PixelFormatEnumToMasks(format, &depth, &rmask, &gmask, &bmask, &amask)) { + SDL_Surface *surface = SDL_CreateRGBSurfaceFrom(pixels, rect.w, rect.h, depth, pitch, rmask, gmask, bmask, amask); + TCOD_sys_save_bitmap((void *)surface,filename); + SDL_FreeSurface(surface); + } else + TCOD_LOG(("TCOD_sys_save_screenshot - failed call to SDL_PixelFormatEnumToMasks")); + + SDL_UnlockTexture(texture); + } else + TCOD_LOG(("TCOD_sys_save_screenshot - failed call to SDL_QueryTexture or SDL_LockTexture")); + } else + TCOD_LOG(("TCOD_sys_save_screenshot - failed call to SDL_SetRenderTarget")); + SDL_DestroyTexture(texture); + } else + TCOD_LOG(("TCOD_sys_save_screenshot - failed call to SDL_CreateTexture")); +#ifndef NO_OPENGL + } else { + SDL_Surface *screenshot=(SDL_Surface *)TCOD_opengl_get_screen(); + TCOD_sys_save_bitmap((void *)screenshot,filename); + SDL_FreeSurface(screenshot); +#endif + } +} +/* get desktop resolution */ +static void get_current_resolution(int *w, int *h) { + int displayidx; + SDL_Rect rect = { 0, 0, 0, 0 }; + if (window) { + TCOD_IFNOT(window) return; + displayidx = SDL_GetWindowDisplayIndex(window); + TCOD_IFNOT(displayidx >= 0) return; + } else { + /* No window if no console, but user can want to know res before opening one. */ + TCOD_IFNOT(SDL_GetNumVideoDisplays() > 0) return; + displayidx = 0; + } + TCOD_IFNOT(SDL_GetDisplayBounds(displayidx, &rect) == 0) return; + *w=rect.w; + *h=rect.h; +} + +static void set_mouse_position(int x, int y) { + SDL_WarpMouseInWindow(window, (uint16_t)x,(uint16_t)y); +} + +static char *get_clipboard_text(void) { +#ifdef TCOD_LINUX + /* + X11 clipboard is inaccessible without an open window. + https://bugzilla.libsdl.org/show_bug.cgi?id=3222 + */ + if (!window) + return ""; +#endif + + /* + We hold onto the last clipboard text pointer SDL gave us. + For C API callers it can be considered a borrowed reference. + For Python ctypes API callers, the contents are copied into the Python string that is constructed from it. + */ + if (last_clipboard_text) { + SDL_free(last_clipboard_text); + last_clipboard_text = NULL; + } + last_clipboard_text = SDL_GetClipboardText(); + return last_clipboard_text; +} + +static bool set_clipboard_text(const char *text) { +#ifdef TCOD_LINUX + /* + X11 clipboard is inaccessible without an open window. + https://bugzilla.libsdl.org/show_bug.cgi?id=3222 + */ + if (!window) + return false; +#endif + + return SDL_SetClipboardText(text) == 0; +} + +/* android compatible file access functions */ +static bool file_read(const char *filename, unsigned char **buf, size_t *size) { + int64_t filesize; + /* get file size */ + SDL_RWops *rwops= SDL_RWFromFile(filename,"rb"); + if (!rwops) return false; + SDL_RWseek(rwops,0,RW_SEEK_END); + filesize=SDL_RWtell(rwops); + SDL_RWseek(rwops,0,RW_SEEK_SET); + /* allocate buffer */ + *buf = (unsigned char *)malloc(sizeof(unsigned char)*filesize); + /* read from file */ + if (SDL_RWread(rwops,*buf,sizeof(unsigned char),filesize) != filesize) { + SDL_RWclose(rwops); + free(*buf); + return false; + } + SDL_RWclose(rwops); + *size=filesize; + return true; +} + +static bool file_exists(const char * filename) { + SDL_RWops *rwops; + rwops = SDL_RWFromFile(filename,"rb"); + if (rwops) { + SDL_RWclose(rwops); + return true; + } + return false; +} + +static bool file_write(const char *filename, unsigned char *buf, uint32_t size) { + SDL_RWops *rwops= SDL_RWFromFile(filename,"wb"); + if (!rwops) return false; + SDL_RWwrite(rwops,buf,sizeof(unsigned char),size); + SDL_RWclose(rwops); + return true; +} + +static void shutdown_(void) { + if (last_clipboard_text) { + SDL_free(last_clipboard_text); + last_clipboard_text = NULL; + } + if (root_console_cache) { + TCOD_console_delete(root_console_cache); + root_console_cache = NULL; + } +} + +TCOD_SDL_driver_t *SDL_implementation_factory(void) { + TCOD_SDL_driver_t *ret=(TCOD_SDL_driver_t *)calloc(1,sizeof(TCOD_SDL_driver_t)); + ret->scale_xc = 0.5f; + ret->scale_yc = 0.5f; + + ret->get_closest_mode = get_closest_mode; + ret->render = render; + ret->create_surface = create_surface; + ret->create_window = create_window; + ret->destroy_window = destroy_window; + ret->set_fullscreen = set_fullscreen; + ret->set_window_title = set_window_title; + ret->save_screenshot = save_screenshot; + ret->get_current_resolution = get_current_resolution; + ret->set_mouse_position = set_mouse_position; + ret->get_clipboard_text = get_clipboard_text; + ret->set_clipboard_text = set_clipboard_text; + ret->file_read = file_read; + ret->file_exists = file_exists; + ret->file_write = file_write; + ret->shutdown = shutdown_; + ret->get_root_console_cache = get_root_console_cache; + return ret; +} + +#endif /* TCOD_BARE */ +======= +/* +* libtcod +* Copyright (c) 2008-2018 Jice & Mingos & rmtew +* All rights reserved. +* +* Redistribution and use in source and binary forms, with or without +* modification, are permitted provided that the following conditions are met: +* * Redistributions of source code must retain the above copyright +* notice, this list of conditions and the following disclaimer. +* * Redistributions in binary form must reproduce the above copyright +* notice, this list of conditions and the following disclaimer in the +* documentation and/or other materials provided with the distribution. +* * The name of Jice or Mingos may not be used to endorse or promote +* products derived from this software without specific prior written +* permission. +* +* THIS SOFTWARE IS PROVIDED BY JICE, MINGOS AND RMTEW ``AS IS'' AND ANY +* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED +* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE +* DISCLAIMED. IN NO EVENT SHALL JICE, MINGOS OR RMTEW BE LIABLE FOR ANY +* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES +* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; +* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND +* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS +* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +*/ +#ifndef TCOD_BARE +#include "sys.h" + +#include +#include + +#include + +#include "console.h" +#include "libtcod_int.h" +#include "utility.h" + +static SDL_Surface* scale_screen=NULL; +static bool clear_screen=false; +static struct TCOD_Console *root_console_cache; /* cache for previous values */ + +/* This just forces a complete redraw, bypassing the usual rendering of changes. */ +void TCOD_sys_set_clear_screen(void) { + clear_screen=true; +} + +static void get_closest_mode(int *w, int *h) { + SDL_DisplayMode wantedmode, closestmode; + wantedmode.w = *w; + wantedmode.h = *h; + wantedmode.format = 0; /* don't care for rest. */ + wantedmode.refresh_rate = 0; + wantedmode.driverdata = 0; + if (SDL_GetClosestDisplayMode(window?SDL_GetWindowDisplayIndex(window):0, &wantedmode, &closestmode) == &closestmode) { + *w=closestmode.w; + *h=closestmode.h; + } +} + +/* + * Separate out the actual rendering, so that render to texture can be done. + */ +static void actual_rendering(void) { + SDL_Rect srcRect, dstRect; + SDL_Texture *texture; + + if (scale_data.min_scale_factor - 1e-3f > scale_factor) { + /* Prepare for the unscaled and centered copy of the entire console. */ + srcRect.x=0; srcRect.y=0; srcRect.w=scale_screen->w; srcRect.h=scale_screen->h; + if (TCOD_ctx.fullscreen) { + dstRect.x=TCOD_ctx.fullscreen_offsetx; dstRect.y=TCOD_ctx.fullscreen_offsety; + } else { + dstRect.x=0; dstRect.y=0; + } + dstRect.w=scale_screen->w; dstRect.h=scale_screen->h; + } else { + /* Prepare for the scaled copy of the displayed console area. */ + srcRect.x=scale_data.src_x0; srcRect.y=scale_data.src_y0; srcRect.w=scale_data.src_copy_width; srcRect.h=scale_data.src_copy_height; + dstRect.x=scale_data.dst_offset_x; dstRect.y=scale_data.dst_offset_y; + dstRect.w=scale_data.dst_display_width; dstRect.h=scale_data.dst_display_height; + } + if ( TCOD_ctx.sdl_cbk ) { + TCOD_ctx.sdl_cbk((void *)scale_screen); + } + texture = SDL_CreateTextureFromSurface(renderer, scale_screen); + SDL_RenderCopy(renderer, texture, &srcRect, &dstRect); + SDL_DestroyTexture(texture); +} + +/* Return an up-to-date cache for the root console, create or resize the cache + if needed */ +static struct TCOD_Console *ensure_cache(struct TCOD_Console* root) { + if (!root_console_cache || + root_console_cache->w != root->w || + root_console_cache->h != root->h) { + if (root_console_cache) { TCOD_console_delete(root_console_cache); } + root_console_cache = TCOD_console_new(root->w, root->h); + } + return root_console_cache; +} + +/* In order to avoid rendering race conditions and the ensuing segmentation + * faults, this should only be called when it would normally be and not + * specifically to force screen refreshes. To this end, and to avoid + * threading complications it takes care of special cases internally. */ +static void render(TCOD_SDL_driver_t *sdl, void *vbitmap, struct TCOD_Console *console) { + if ( TCOD_ctx.renderer == TCOD_RENDERER_SDL ) { + int console_width_p = console->w * TCOD_ctx.font_width; + int console_height_p = console->h * TCOD_ctx.font_height; + + /* Make a bitmap of exact rendering size and correct format. */ + if (scale_screen == NULL) { + int bpp; + uint32_t rmask, gmask, bmask, amask; + if (SDL_PixelFormatEnumToMasks(SDL_GetWindowPixelFormat(window), &bpp, &rmask, &gmask, &bmask, &amask) == SDL_FALSE) { + TCOD_fatal("SDL : failed to create scaling surface : indeterminate window pixel format"); + return; + } + scale_screen=SDL_CreateRGBSurface(SDL_SWSURFACE,console_width_p,console_height_p,bpp,rmask,gmask,bmask,amask); + if (scale_screen == NULL) { + TCOD_fatal("SDL : failed to create scaling surface"); + return; + } + } else if (clear_screen) { + clear_screen=false; + SDL_FillRect(scale_screen,0,0); + /* Implicitly do complete console redraw, not just tracked changes. */ + TCOD_console_set_dirty(0, 0, console->w, console->h); + } + + TCOD_sys_console_to_bitmap(scale_screen, console, ensure_cache(console)); + + /* Scale the rendered bitmap to the screen, preserving aspect ratio, and blit it. + * This data is also used for console coordinate resolution.. */ + if (scale_data.last_scale_factor != scale_factor || scale_data.last_scale_xc != sdl->scale_xc || scale_data.last_scale_yc != sdl->scale_yc || + scale_data.last_fullscreen != TCOD_ctx.fullscreen || scale_data.force_recalc) { + /* Preserve old value of input variables, to enable recalculation if they change. */ + scale_data.last_scale_factor = scale_factor; + scale_data.last_scale_xc = sdl->scale_xc; + scale_data.last_scale_yc = sdl->scale_yc; + scale_data.last_fullscreen = TCOD_ctx.fullscreen; + scale_data.force_recalc = 0; + + if (scale_data.last_fullscreen) { + scale_data.surface_width = TCOD_ctx.actual_fullscreen_width; + scale_data.surface_height = TCOD_ctx.actual_fullscreen_height; + } else { + scale_data.surface_width = console_width_p; + scale_data.surface_height = console_height_p; + } + scale_data.min_scale_factor = MAX((float)console_width_p/scale_data.surface_width, (float)console_height_p/scale_data.surface_height); + if (scale_data.min_scale_factor > 1.0f) + scale_data.min_scale_factor = 1.0f; + /*printf("min_scale_factor %0.3f = MAX(%d/%d, %d/%d)", scale_data.min_scale_factor, console_width_p, scale_data.surface_width, console_height_p, scale_data.surface_height);*/ + + scale_data.dst_height_width_ratio = (float)scale_data.surface_height/scale_data.surface_width; + scale_data.src_proportionate_width = (int)(console_width_p / scale_factor); + scale_data.src_proportionate_height = (int)((console_width_p * scale_data.dst_height_width_ratio) / scale_factor); + + /* Work out how much of the console to copy. */ + scale_data.src_x0 = (int)((sdl->scale_xc * console_width_p) - (0.5f * scale_data.src_proportionate_width)); + if (scale_data.src_x0 + scale_data.src_proportionate_width > console_width_p) + scale_data.src_x0 = console_width_p - scale_data.src_proportionate_width; + if (scale_data.src_x0 < 0) + scale_data.src_x0 = 0; + scale_data.src_copy_width = scale_data.src_proportionate_width; + if (scale_data.src_x0 + scale_data.src_copy_width > console_width_p) + scale_data.src_copy_width = console_width_p - scale_data.src_x0; + + scale_data.src_y0 = (int)((sdl->scale_yc * console_height_p) - (0.5f * scale_data.src_proportionate_height)); + if (scale_data.src_y0 + scale_data.src_proportionate_height > console_height_p) + scale_data.src_y0 = console_height_p - scale_data.src_proportionate_height; + if (scale_data.src_y0 < 0) + scale_data.src_y0 = 0; + scale_data.src_copy_height = scale_data.src_proportionate_height; + if (scale_data.src_y0 + scale_data.src_copy_height > console_height_p) + scale_data.src_copy_height = console_height_p - scale_data.src_y0; + + scale_data.dst_display_width = (scale_data.src_copy_width * scale_data.surface_width) / scale_data.src_proportionate_width; + scale_data.dst_display_height = (scale_data.src_copy_height * scale_data.surface_height) / scale_data.src_proportionate_height; + scale_data.dst_offset_x = (scale_data.surface_width - scale_data.dst_display_width)/2; + scale_data.dst_offset_y = (scale_data.surface_height - scale_data.dst_display_height)/2; + } + + SDL_RenderClear(renderer); + actual_rendering(); + SDL_RenderPresent(renderer); + } +#ifndef NO_OPENGL + else { + TCOD_opengl_render(oldFade, NULL, console, ensure_cache(console)); + TCOD_opengl_swap(); + } +#endif + oldFade=(int)TCOD_console_get_fade(); +} + +/* Return the current root console cache if it exists, or NULL. */ +static struct TCOD_Console *get_root_console_cache(void){ + return root_console_cache; +} + +static SDL_Surface *create_surface(int width, int height, bool with_alpha) { + uint32_t rmask,gmask,bmask,amask; + SDL_Surface *bitmap; + int flags=SDL_SWSURFACE; + + if ( with_alpha ) { + if ( SDL_BYTEORDER == SDL_LIL_ENDIAN ) { + rmask=0x000000FF; + gmask=0x0000FF00; + bmask=0x00FF0000; + amask=0xFF000000; + } else { + rmask=0xFF000000; + gmask=0x00FF0000; + bmask=0x0000FF00; + amask=0x000000FF; + } + } else { + if ( SDL_BYTEORDER == SDL_LIL_ENDIAN ) { + rmask=0x0000FF; + gmask=0x00FF00; + bmask=0xFF0000; + } else { + rmask=0xFF0000; + gmask=0x00FF00; + bmask=0x0000FF; + } + amask=0; + } + bitmap=SDL_CreateRGBSurface(flags,width,height, + with_alpha ? 32:24, + rmask,gmask,bmask,amask); + if ( with_alpha ) { + SDL_SetSurfaceAlphaMod(bitmap, 255); + } + return bitmap; +} + +static void create_window(int w, int h, bool fullscreen) { + uint32_t winflags = SDL_WINDOW_SHOWN | SDL_WINDOW_OPENGL; +#if defined(TCOD_ANDROID) + /* Android should always be fullscreen. */ + TCOD_ctx.fullscreen = fullscreen = true; +#endif + if ( fullscreen ) { + find_resolution(); +#ifndef NO_OPENGL + if (TCOD_ctx.renderer != TCOD_RENDERER_SDL ) { + TCOD_opengl_init_attributes(); + winflags |= SDL_WINDOW_FULLSCREEN | SDL_WINDOW_BORDERLESS | SDL_WINDOW_OPENGL; +# if defined(TCOD_ANDROID) && defined(FUTURE_SUPPORT) + winflags |= SDL_WINDOW_RESIZABLE; +# endif + window = SDL_CreateWindow(TCOD_ctx.window_title,SDL_WINDOWPOS_CENTERED,SDL_WINDOWPOS_CENTERED,TCOD_ctx.actual_fullscreen_width,TCOD_ctx.actual_fullscreen_height,winflags); + if ( window && TCOD_opengl_init_state(w, h, charmap) && TCOD_opengl_init_shaders() ) { + TCOD_LOG(("Using %s renderer...\n",TCOD_ctx.renderer == TCOD_RENDERER_GLSL ? "GLSL" : "OPENGL")); + } else { + TCOD_LOG(("Fallback to SDL renderer...\n")); + TCOD_ctx.renderer = TCOD_RENDERER_SDL; + } + } +#endif + if (TCOD_ctx.renderer == TCOD_RENDERER_SDL ) { + winflags |= SDL_WINDOW_FULLSCREEN | SDL_WINDOW_BORDERLESS; +# if defined(TCOD_ANDROID) && defined(FUTURE_SUPPORT) + winflags |= SDL_WINDOW_RESIZABLE; +# endif + window = SDL_CreateWindow(TCOD_ctx.window_title,SDL_WINDOWPOS_CENTERED, SDL_WINDOWPOS_CENTERED, TCOD_ctx.actual_fullscreen_width,TCOD_ctx.actual_fullscreen_height,winflags); + if ( window == NULL ) TCOD_fatal("SDL : cannot set fullscreen video mode: %s", SDL_GetError()); + } + SDL_ShowCursor(0); + SDL_GetWindowSize(window,&TCOD_ctx.actual_fullscreen_width,&TCOD_ctx.actual_fullscreen_height); + TCOD_sys_init_screen_offset(); + } else { +#ifndef NO_OPENGL + if (TCOD_ctx.renderer != TCOD_RENDERER_SDL ) { + TCOD_opengl_init_attributes(); + winflags |= SDL_WINDOW_OPENGL; + window = SDL_CreateWindow(TCOD_ctx.window_title,SDL_WINDOWPOS_CENTERED,SDL_WINDOWPOS_CENTERED,w*TCOD_ctx.font_width,h*TCOD_ctx.font_height,winflags); + if ( window && TCOD_opengl_init_state(w, h, charmap) && TCOD_opengl_init_shaders() ) { + TCOD_LOG(("Using %s renderer...\n",TCOD_ctx.renderer == TCOD_RENDERER_GLSL ? "GLSL" : "OPENGL")); + } else { + TCOD_LOG(("Fallback to SDL renderer...\n")); + TCOD_ctx.renderer = TCOD_RENDERER_SDL; + } + } +#endif + if (TCOD_ctx.renderer == TCOD_RENDERER_SDL ) { + window = SDL_CreateWindow(TCOD_ctx.window_title,SDL_WINDOWPOS_CENTERED,SDL_WINDOWPOS_CENTERED,w*TCOD_ctx.font_width,h*TCOD_ctx.font_height,winflags); + TCOD_LOG(("Using SDL renderer...\n")); + } + if ( window == NULL ) TCOD_fatal("Cannot create SDL window: %s", SDL_GetError()); + } + if (TCOD_ctx.renderer == TCOD_RENDERER_SDL ) { + renderer = SDL_CreateRenderer(window, -1, SDL_RENDERER_ACCELERATED); + if ( renderer == NULL ) TCOD_fatal("Cannot create SDL renderer: %s", SDL_GetError()); + SDL_SetRenderDrawColor(renderer, 0, 0, 0, SDL_ALPHA_OPAQUE); + } +} + +static void destroy_window(void) { +#ifndef NO_OPENGL + if (TCOD_ctx.renderer == TCOD_RENDERER_OPENGL || TCOD_ctx.renderer == TCOD_RENDERER_GLSL) { + TCOD_opengl_uninit_state(); + } +#endif + if (scale_screen) { + SDL_FreeSurface(scale_screen); + scale_screen = NULL; + } + if (renderer) { + SDL_DestroyRenderer(renderer); + renderer = NULL; + } + if (window) { + SDL_DestroyWindow(window); + window = NULL; + } + if (root_console_cache) { + TCOD_console_delete(root_console_cache); + root_console_cache = NULL; + } +} + +static void set_fullscreen(bool fullscreen) { + bool mouseOn=SDL_ShowCursor(-1); + if ( fullscreen ) { + find_resolution(); + SDL_SetWindowFullscreen(window, fullscreen); + SDL_ShowCursor(mouseOn ? 1:0); + SDL_GetWindowSize(window,&TCOD_ctx.actual_fullscreen_width,&TCOD_ctx.actual_fullscreen_height); + TCOD_sys_init_screen_offset(); + } else { + SDL_SetWindowFullscreen(window, fullscreen); + SDL_ShowCursor(mouseOn ? 1:0); + TCOD_ctx.fullscreen_offsetx=0; + TCOD_ctx.fullscreen_offsety=0; + } + TCOD_ctx.fullscreen=fullscreen; + oldFade=-1; /* to redraw the whole screen */ +} + +static void set_window_title(const char *title) { + SDL_SetWindowTitle(window, title); +} + +static void save_screenshot(const char *filename) { + if ( TCOD_ctx.renderer == TCOD_RENDERER_SDL ) { + /* This would be a lot easier if image saving could do textures. */ + SDL_Rect rect; + uint32_t format; + SDL_Texture *texture; + SDL_RenderGetViewport(renderer, &rect); + format = SDL_GetWindowPixelFormat(window); + texture = SDL_CreateTexture(renderer, format, SDL_TEXTUREACCESS_TARGET, rect.w, rect.h); + if (0 != texture) { + if (SDL_SetRenderTarget(renderer, texture)) { + void *pixels; + int pitch, access; + + actual_rendering(); + SDL_SetRenderTarget(renderer, NULL); + + rect.x = rect.y = rect.w = rect.h = 0; + if (-1 != SDL_QueryTexture(texture, &format, &access, &rect.w, &rect.h) && + -1 != SDL_LockTexture(texture, NULL, &pixels, &pitch)) { + int depth; + uint32_t rmask, gmask, bmask, amask; + if (SDL_TRUE == SDL_PixelFormatEnumToMasks(format, &depth, &rmask, &gmask, &bmask, &amask)) { + SDL_Surface *surface = SDL_CreateRGBSurfaceFrom(pixels, rect.w, rect.h, depth, pitch, rmask, gmask, bmask, amask); + TCOD_sys_save_bitmap((void *)surface,filename); + SDL_FreeSurface(surface); + } else + TCOD_LOG(("TCOD_sys_save_screenshot - failed call to SDL_PixelFormatEnumToMasks")); + + SDL_UnlockTexture(texture); + } else + TCOD_LOG(("TCOD_sys_save_screenshot - failed call to SDL_QueryTexture or SDL_LockTexture")); + } else + TCOD_LOG(("TCOD_sys_save_screenshot - failed call to SDL_SetRenderTarget")); + SDL_DestroyTexture(texture); + } else + TCOD_LOG(("TCOD_sys_save_screenshot - failed call to SDL_CreateTexture")); +#ifndef NO_OPENGL + } else { + SDL_Surface *screenshot=(SDL_Surface *)TCOD_opengl_get_screen(); + TCOD_sys_save_bitmap((void *)screenshot,filename); + SDL_FreeSurface(screenshot); +#endif + } +} +/* get desktop resolution */ +static void get_current_resolution(int *w, int *h) { + int displayidx; + SDL_Rect rect = { 0, 0, 0, 0 }; + if (window) { + TCOD_IFNOT(window) return; + displayidx = SDL_GetWindowDisplayIndex(window); + TCOD_IFNOT(displayidx >= 0) return; + } else { + /* No window if no console, but user can want to know res before opening one. */ + TCOD_IFNOT(SDL_GetNumVideoDisplays() > 0) return; + displayidx = 0; + } + TCOD_IFNOT(SDL_GetDisplayBounds(displayidx, &rect) == 0) return; + *w=rect.w; + *h=rect.h; +} + +static void set_mouse_position(int x, int y) { + SDL_WarpMouseInWindow(window, (uint16_t)x,(uint16_t)y); +} + +static char *get_clipboard_text(void) { +#ifdef TCOD_LINUX + /* + X11 clipboard is inaccessible without an open window. + https://bugzilla.libsdl.org/show_bug.cgi?id=3222 + */ + if (!window) + return ""; +#endif + + /* + We hold onto the last clipboard text pointer SDL gave us. + For C API callers it can be considered a borrowed reference. + For Python ctypes API callers, the contents are copied into the Python string that is constructed from it. + */ + if (last_clipboard_text) { + SDL_free(last_clipboard_text); + last_clipboard_text = NULL; + } + last_clipboard_text = SDL_GetClipboardText(); + return last_clipboard_text; +} + +static bool set_clipboard_text(const char *text) { +#ifdef TCOD_LINUX + /* + X11 clipboard is inaccessible without an open window. + https://bugzilla.libsdl.org/show_bug.cgi?id=3222 + */ + if (!window) + return false; +#endif + + return SDL_SetClipboardText(text) == 0; +} + +/* android compatible file access functions */ +static bool file_read(const char *filename, unsigned char **buf, size_t *size) { + int64_t filesize; + /* get file size */ + SDL_RWops *rwops= SDL_RWFromFile(filename,"rb"); + if (!rwops) return false; + SDL_RWseek(rwops,0,RW_SEEK_END); + filesize=SDL_RWtell(rwops); + SDL_RWseek(rwops,0,RW_SEEK_SET); + /* allocate buffer */ + *buf = (unsigned char *)malloc(sizeof(unsigned char)*filesize); + /* read from file */ + if (SDL_RWread(rwops,*buf,sizeof(unsigned char),filesize) != filesize) { + SDL_RWclose(rwops); + free(*buf); + return false; + } + SDL_RWclose(rwops); + *size=filesize; + return true; +} + +static bool file_exists(const char * filename) { + SDL_RWops *rwops; + rwops = SDL_RWFromFile(filename,"rb"); + if (rwops) { + SDL_RWclose(rwops); + return true; + } + return false; +} + +static bool file_write(const char *filename, unsigned char *buf, uint32_t size) { + SDL_RWops *rwops= SDL_RWFromFile(filename,"wb"); + if (!rwops) return false; + SDL_RWwrite(rwops,buf,sizeof(unsigned char),size); + SDL_RWclose(rwops); + return true; +} + +static void shutdown_(void) { + if (last_clipboard_text) { + SDL_free(last_clipboard_text); + last_clipboard_text = NULL; + } + if (root_console_cache) { + TCOD_console_delete(root_console_cache); + root_console_cache = NULL; + } +} + +TCOD_SDL_driver_t *SDL_implementation_factory(void) { + TCOD_SDL_driver_t *ret=(TCOD_SDL_driver_t *)calloc(1,sizeof(TCOD_SDL_driver_t)); + ret->scale_xc = 0.5f; + ret->scale_yc = 0.5f; + + ret->get_closest_mode = get_closest_mode; + ret->render = render; + ret->create_surface = create_surface; + ret->create_window = create_window; + ret->destroy_window = destroy_window; + ret->set_fullscreen = set_fullscreen; + ret->set_window_title = set_window_title; + ret->save_screenshot = save_screenshot; + ret->get_current_resolution = get_current_resolution; + ret->set_mouse_position = set_mouse_position; + ret->get_clipboard_text = get_clipboard_text; + ret->set_clipboard_text = set_clipboard_text; + ret->file_read = file_read; + ret->file_exists = file_exists; + ret->file_write = file_write; + ret->shutdown = shutdown_; + ret->get_root_console_cache = get_root_console_cache; + return ret; +} + +#endif /* TCOD_BARE */ diff --git a/tcod_sys/libtcod/src/sys_sdl_c.c b/tcod_sys/libtcod/src/libtcod/sys_sdl_c.cpp similarity index 81% rename from tcod_sys/libtcod/src/sys_sdl_c.c rename to tcod_sys/libtcod/src/libtcod/sys_sdl_c.cpp index b39d7665e..d4614d676 100644 --- a/tcod_sys/libtcod/src/sys_sdl_c.c +++ b/tcod_sys/libtcod/src/libtcod/sys_sdl_c.cpp @@ -1,1768 +1,1805 @@ -/* -* libtcod -* Copyright (c) 2008-2018 Jice & Mingos & rmtew -* All rights reserved. -* -* Redistribution and use in source and binary forms, with or without -* modification, are permitted provided that the following conditions are met: -* * Redistributions of source code must retain the above copyright -* notice, this list of conditions and the following disclaimer. -* * Redistributions in binary form must reproduce the above copyright -* notice, this list of conditions and the following disclaimer in the -* documentation and/or other materials provided with the distribution. -* * The name of Jice or Mingos may not be used to endorse or promote -* products derived from this software without specific prior written -* permission. -* -* THIS SOFTWARE IS PROVIDED BY JICE, MINGOS AND RMTEW ``AS IS'' AND ANY -* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED -* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE -* DISCLAIMED. IN NO EVENT SHALL JICE, MINGOS OR RMTEW BE LIABLE FOR ANY -* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES -* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; -* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND -* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS -* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. -*/ -#ifndef TCOD_BARE -#include -#include - -#include -#include -#include -#include - -#include - -#include -#include -#include - -static TCOD_SDL_driver_t *sdl=NULL; - - -/* library initialization function */ -#ifdef TCOD_WINDOWS -#include -BOOL APIENTRY DllMain( HINSTANCE hModule, DWORD reason, LPVOID reserved) { - switch (reason ) { - case DLL_PROCESS_ATTACH : sdl = SDL_implementation_factory(); break; - default : break; - } - return TRUE; -} -#else - void __attribute__ ((constructor)) DllMain(void) { - sdl = SDL_implementation_factory(); - } -#endif - -#if defined(__ANDROID__) -#define TCOD_TOUCH_INPUT -#define MAX_TOUCH_FINGERS 5 - -typedef struct { - int nupdates; /* how many updates have happened since the first finger was pressed. */ - uint32_t ticks0; /* current number of ticks at start of touch event sequence. */ - SDL_FingerID finger_id; /* the last finger which was pressed. */ - int coords[MAX_TOUCH_FINGERS][2]; /* absolute position of each finger. */ - int coords_delta[MAX_TOUCH_FINGERS][2]; /* absolute position of each finger. */ - int consolecoords[MAX_TOUCH_FINGERS][2]; /* cell coordinates in the root console for each finger. */ - int consolecoords_delta[MAX_TOUCH_FINGERS][2]; /* cell coordinates in the root console for each finger. */ - int nfingers; /* number of unique fingers employed at any time during this. */ - int nfingerspressed; /* number of those fingers currently still pressed. */ - SDL_FingerID finger_ids[MAX_TOUCH_FINGERS]; - char fingerspressed[MAX_TOUCH_FINGERS]; -} TCOD_touch_t; -#endif - -/* to enable bitmap locking. Is there any use ?? makes the OSX port renderer to fail */ -/*#define USE_SDL_LOCKS */ - -/* image support stuff */ -bool TCOD_sys_check_bmp(const char *filename); -SDL_Surface *TCOD_sys_read_bmp(const char *filename); -void TCOD_sys_write_bmp(const SDL_Surface *surf, const char *filename); -bool TCOD_sys_check_png(const char *filename); -SDL_Surface *TCOD_sys_read_png(const char *filename); -void TCOD_sys_write_png(const SDL_Surface *surf, const char *filename); - -typedef struct { - char *extension; - bool (*check_type)(const char *filename); - SDL_Surface *(*read)(const char *filename); - void (*write)(const SDL_Surface *surf, const char *filename); -} image_support_t; - -static image_support_t image_type[] = { - { "BMP", TCOD_sys_check_bmp, TCOD_sys_read_bmp, TCOD_sys_write_bmp }, - { "PNG", TCOD_sys_check_png, TCOD_sys_read_png, TCOD_sys_write_png }, - { NULL, NULL, NULL, NULL }, -}; - -scale_data_t scale_data={0}; -SDL_Window* window=NULL; -SDL_Renderer* renderer=NULL; -float scale_factor=1.0f; -SDL_Surface* charmap=NULL; -char *last_clipboard_text = NULL; -static bool has_startup=false; -#define MAX_SCALE_FACTOR 5.0f - -/* font transparent color */ -static TCOD_color_t fontKeyCol={0,0,0}; - -static uint32_t sdl_key=0, rgb_mask=0, nrgb_mask=0; - -/* mouse stuff */ -static bool mousebl=false; -static bool mousebm=false; -static bool mousebr=false; -static bool mouse_force_bl=false; -static bool mouse_force_bm=false; -static bool mouse_force_br=false; -#ifdef TCOD_TOUCH_INPUT -static bool mouse_touch=true; -#endif - -/* minimum length for a frame (when fps are limited) */ -static int min_frame_length=0; -static int min_frame_length_backup=0; -/* number of frames in the last second */ -static int fps=0; -/* current number of frames */ -static int cur_fps=0; -/* length of the last rendering loop */ -static float last_frame_length=0.0f; - -static TCOD_color_t *charcols=NULL; -static bool *first_draw=NULL; -static bool key_status[TCODK_CHAR+1]; -int oldFade=-1; - -/* convert SDL vk to a char (depends on the keyboard layout) */ -typedef struct { - SDL_Keycode sdl_key; - int tcod_key; -} vk_to_c_entry; -#define NUM_VK_TO_C_ENTRIES 10 -static vk_to_c_entry vk_to_c[NUM_VK_TO_C_ENTRIES]; - -/* convert ASCII code to TCOD layout position */ -static int init_ascii_to_tcod[256] = { - 0, 0, 0, 0, 0, 0, 0, 0, 0, 76, 77, 0, 0, 0, 0, 0, /* ASCII 0 to 15 */ - 71, 70, 72, 0, 0, 0, 0, 0, 64, 65, 67, 66, 0, 73, 68, 69, /* ASCII 16 to 31 */ - 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, /* ASCII 32 to 47 */ - 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, /* ASCII 48 to 63 */ - 32, 96, 97, 98, 99,100,101,102,103,104,105,106,107,108,109,110, /* ASCII 64 to 79 */ -111,112,113,114,115,116,117,118,119,120,121, 33, 34, 35, 36, 37, /* ASCII 80 to 95 */ - 38,128,129,130,131,132,133,134,135,136,137,138,139,140,141,142, /* ASCII 96 to 111 */ -143,144,145,146,147,148,149,150,151,152,153, 39, 40, 41, 42, 0, /* ASCII 112 to 127 */ - 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* ASCII 128 to 143 */ - 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* ASCII 144 to 159 */ - 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* ASCII 160 to 175 */ - 43, 44, 45, 46, 49, 0, 0, 0, 0, 81, 78, 87, 88, 0, 0, 55, /* ASCII 176 to 191 */ - 53, 50, 52, 51, 47, 48, 0, 0, 85, 86, 82, 84, 83, 79, 80, 0, /* ASCII 192 to 207 */ - 0, 0, 0, 0, 0, 0, 0, 0, 0, 56, 54, 0, 0, 0, 0, 0, /* ASCII 208 to 223 */ - 74, 75, 57, 58, 59, 60, 61, 62, 63, 0, 0, 0, 0, 0, 0, 0, /* ASCII 224 to 239 */ - 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* ASCII 240 to 255 */ -}; - -static void alloc_ascii_tables(void) { - if ( TCOD_ctx.ascii_to_tcod ) free(TCOD_ctx.ascii_to_tcod); - if ( charcols ) { - free(charcols); - free(first_draw); - } - - TCOD_ctx.ascii_to_tcod = (int *)calloc(sizeof(int),TCOD_ctx.max_font_chars); - charcols = (TCOD_color_t *)calloc(sizeof(TCOD_color_t),TCOD_ctx.max_font_chars); - first_draw =(bool *)calloc(sizeof(bool),TCOD_ctx.max_font_chars); - memcpy(TCOD_ctx.ascii_to_tcod,init_ascii_to_tcod,sizeof(int)*256); -} -/** Reallocate the TCOD_ctx.ascii_to_tcod array, usually to make it bigger. - */ -static int realloc_ascii_tables(int new_size) { - int *new_table = realloc(TCOD_ctx.ascii_to_tcod, sizeof(int) * new_size); - int i; - if (!new_table) { - return -1; /* failed to realloc table (old table pointer is still good) */ - } - /* any new array indexes are undefined and need to be filled with zeros */ - for (i = TCOD_ctx.max_font_chars; i < new_size; ++i) { - new_table[i] = 0; - } - TCOD_ctx.ascii_to_tcod = new_table; - TCOD_ctx.max_font_chars = new_size; - return 0; -} - -static void check_ascii_to_tcod(void) { - if ( TCOD_ctx.fontNbCharHoriz * TCOD_ctx.fontNbCharVertic != TCOD_ctx.max_font_chars ) { - TCOD_ctx.max_font_chars=TCOD_ctx.fontNbCharHoriz * TCOD_ctx.fontNbCharVertic; - alloc_ascii_tables(); - } -} - -void TCOD_sys_register_SDL_renderer(SDL_renderer_t renderer) { - TCOD_ctx.sdl_cbk=renderer; -} -/** See TCOD_console_map_ascii_code_to_font */ -void TCOD_sys_map_ascii_to_font(int asciiCode, int fontCharX, int fontCharY) { - if (asciiCode <= 0) { return; } /* can't reassign 0 or negatives */ - if (asciiCode >= TCOD_ctx.max_font_chars) { - /* reduce total allocations by resizing in increments of 256 */ - if (realloc_ascii_tables((asciiCode & 0xff) + 1)) { - return; /* Failed to realloc table (old table pointer is still good) */ - } - } - TCOD_ctx.ascii_to_tcod[asciiCode] = - fontCharX + fontCharY * TCOD_ctx.fontNbCharHoriz; -} - -void TCOD_sys_load_font(void) { - int i; - bool hasTransparent=false; - int x,y; - - if ( charmap ) SDL_FreeSurface(charmap); - charmap=TCOD_sys_load_image(TCOD_ctx.font_file); - if (charmap == NULL ) TCOD_fatal("SDL : cannot load %s",TCOD_ctx.font_file); - if ( (float)(charmap->w / TCOD_ctx.fontNbCharHoriz) != charmap->w / TCOD_ctx.fontNbCharHoriz - || (float)(charmap->h / TCOD_ctx.fontNbCharVertic) != charmap->h / TCOD_ctx.fontNbCharVertic ) TCOD_fatal(" %s size is not a multiple of font layout (%dx%d)\n", - TCOD_ctx.font_file,TCOD_ctx.fontNbCharHoriz,TCOD_ctx.fontNbCharVertic); - TCOD_ctx.font_width=charmap->w/TCOD_ctx.fontNbCharHoriz; - TCOD_ctx.font_height=charmap->h/TCOD_ctx.fontNbCharVertic; - /* allocated bool array for colored flags */ - if ( TCOD_ctx.colored ) free(TCOD_ctx.colored); - TCOD_ctx.colored=(bool *)calloc(sizeof(bool), TCOD_ctx.fontNbCharHoriz*TCOD_ctx.fontNbCharVertic); - check_ascii_to_tcod(); - /* figure out what kind of font we have */ - /* check if the alpha layer is actually used */ - if ( charmap->format->BytesPerPixel == 4 ) { - TCOD_LOG(("32bits font... checking for alpha layer... ")); - for (x=0; !hasTransparent && x < charmap->w; x ++ ) { - for (y=0;!hasTransparent && y < charmap->h; y++ ) { - uint8_t*pixel=(uint8_t*)(charmap->pixels) + y * charmap->pitch + x * charmap->format->BytesPerPixel; - uint8_t alpha=*((pixel)+charmap->format->Ashift/8); - if ( alpha < 255 ) { - hasTransparent=true; - } - } - } - TCOD_LOG((hasTransparent ? "present\n" : "not present\n")); - } else if ( charmap->format->BytesPerPixel != 3 ) { - /* convert to 24 bits */ - SDL_Surface *temp; - TCOD_LOG(("font bpp < 24. converting to 24bits\n")); - temp=(SDL_Surface *)TCOD_sys_get_surface(charmap->w,charmap->h,false); - SDL_BlitSurface(charmap,NULL,temp,NULL); - SDL_FreeSurface(charmap); - charmap=temp; - } else { - TCOD_LOG(("24 bits font.\n")); - } - if (! hasTransparent ) { - /* alpha layer not used */ - int keyx,keyy; - uint8_t*pixel; - /* the key color is found on the character corresponding to space ' ' */ - if ( TCOD_ctx.font_tcod_layout ) { - keyx = TCOD_ctx.font_width/2; - keyy = TCOD_ctx.font_height/2; - } else if (TCOD_ctx.font_in_row) { - keyx = ((int)(' ') % TCOD_ctx.fontNbCharHoriz ) * TCOD_ctx.font_width + TCOD_ctx.font_width/2; - keyy = ((int)(' ') / TCOD_ctx.fontNbCharHoriz ) * TCOD_ctx.font_height + TCOD_ctx.font_height/2; - } else { - keyx = ((int)(' ') / TCOD_ctx.fontNbCharVertic ) * TCOD_ctx.font_width + TCOD_ctx.font_width/2; - keyy = ((int)(' ') % TCOD_ctx.fontNbCharVertic ) * TCOD_ctx.font_height + TCOD_ctx.font_height/2; - } - pixel=(uint8_t*)(charmap->pixels) + keyy * charmap->pitch + keyx * charmap->format->BytesPerPixel; - fontKeyCol.r=*((pixel)+charmap->format->Rshift/8); - fontKeyCol.g=*((pixel)+charmap->format->Gshift/8); - fontKeyCol.b=*((pixel)+charmap->format->Bshift/8); - TCOD_LOG(("key color : %d %d %d\n",fontKeyCol.r,fontKeyCol.g,fontKeyCol.b)); - if ( ! TCOD_ctx.font_greyscale && charmap->format->BytesPerPixel == 4 ) { - /* 32 bits font but alpha layer not used. convert to 24 bits (faster) */ - SDL_Surface *temp; - TCOD_LOG(("32bits font with no alpha => converting to faster 24 bits\n")); - temp=(SDL_Surface *)TCOD_sys_get_surface(charmap->w,charmap->h,false); - SDL_BlitSurface(charmap,NULL,temp,NULL); - SDL_FreeSurface(charmap); - charmap=temp; - } - } - /* detect colored tiles */ - for (i=0; i < TCOD_ctx.fontNbCharHoriz*TCOD_ctx.fontNbCharVertic; i++ ) { - int px,py,cx,cy; - bool end=false; - cx=(i%TCOD_ctx.fontNbCharHoriz); - cy=(i/TCOD_ctx.fontNbCharHoriz); - for( px=0; !end && px < TCOD_ctx.font_width; px++ ) { - for (py=0; !end && py < TCOD_ctx.font_height; py++ ) { - uint8_t*pixel=(uint8_t*)(charmap->pixels) + (cy*TCOD_ctx.font_height+py) * charmap->pitch - + (cx*TCOD_ctx.font_width+px) * charmap->format->BytesPerPixel; - uint8_t r=*((pixel)+charmap->format->Rshift/8); - uint8_t g=*((pixel)+charmap->format->Gshift/8); - uint8_t b=*((pixel)+charmap->format->Bshift/8); - if ( charmap->format->BytesPerPixel == 3 ) { - /* ignore key color */ - if ( r == fontKeyCol.r && g == fontKeyCol.g && b == fontKeyCol.b ) continue; - } - /* colored tile if a pixel is not desaturated */ - if ( r != g || g !=b || b != r ) { - TCOD_ctx.colored[i]=true; - TCOD_LOG(("character for ascii code %d is colored\n",i)); - end=true; - } - } - } - } - /* convert 24/32 bits greyscale to 32bits font with alpha layer */ - if ( ! hasTransparent && TCOD_ctx.font_greyscale ) { - bool invert=( fontKeyCol.r > 128 ); /* black on white font ? */ - /* convert the surface to 32 bits if needed */ - if ( charmap->format->BytesPerPixel != 4 ) { - SDL_Surface *temp; - TCOD_LOG(("24bits greyscale font. converting to 32bits\n")); - temp=(SDL_Surface *)TCOD_sys_get_surface(charmap->w,charmap->h,true); - SDL_BlitSurface(charmap,NULL,temp,NULL); - SDL_FreeSurface(charmap); - charmap=temp; - } - for (i=0; i < TCOD_ctx.fontNbCharHoriz*TCOD_ctx.fontNbCharVertic; i++ ) { - int cx,cy; - cx=(i%TCOD_ctx.fontNbCharHoriz); - cy=(i/TCOD_ctx.fontNbCharHoriz); - /* fill the surface with white (except colored tiles), use alpha layer for characters */ - for (x=cx*TCOD_ctx.font_width; x < (cx+1)*TCOD_ctx.font_width; x ++ ) { - for (y=cy*TCOD_ctx.font_height;y < (cy+1)*TCOD_ctx.font_height; y++ ) { - if ( ! TCOD_ctx.colored[i]) { - uint8_t*pixel=(uint8_t*)(charmap->pixels) + y * charmap->pitch + x * charmap->format->BytesPerPixel; - uint8_t r=*((pixel)+charmap->format->Rshift/8); - *((pixel)+charmap->format->Ashift/8) = (invert ? 255-r : r); - *((pixel)+charmap->format->Rshift/8)=255; - *((pixel)+charmap->format->Gshift/8)=255; - *((pixel)+charmap->format->Bshift/8)=255; - } else { - uint8_t*pixel=(uint8_t*)(charmap->pixels) + y * charmap->pitch + x * charmap->format->BytesPerPixel; - uint8_t r=*((pixel)+charmap->format->Rshift/8); - uint8_t g=*((pixel)+charmap->format->Gshift/8); - uint8_t b=*((pixel)+charmap->format->Bshift/8); - if ( r == fontKeyCol.r && g == fontKeyCol.g && b == fontKeyCol.b ) { - *((pixel)+charmap->format->Ashift/8) = 0; - } else { - *((pixel)+charmap->format->Ashift/8) = 255; - } - } - } - } - } - } - sdl_key=SDL_MapRGB(charmap->format,fontKeyCol.r,fontKeyCol.g,fontKeyCol.b); - rgb_mask=charmap->format->Rmask|charmap->format->Gmask|charmap->format->Bmask; - nrgb_mask = ~ rgb_mask; - sdl_key &= rgb_mask; /* remove the alpha part */ - if ( charmap->format->BytesPerPixel == 3 ) SDL_SetColorKey(charmap,SDL_TRUE|SDL_RLEACCEL,sdl_key); - for (i=0; i < TCOD_ctx.fontNbCharHoriz*TCOD_ctx.fontNbCharVertic; i++ ) { - charcols[i]=fontKeyCol; - first_draw[i]=true; - } - check_ascii_to_tcod(); - if (!TCOD_ctx.font_tcod_layout) { - /* apply standard ascii mapping */ - if ( TCOD_ctx.font_in_row ) { - /* for font in row */ - for (i=0; i < TCOD_ctx.max_font_chars; i++ ) TCOD_ctx.ascii_to_tcod[i]=i; - } else { - /* for font in column */ - for (i=0; i < TCOD_ctx.max_font_chars; i++ ) { - int fy = i % TCOD_ctx.fontNbCharVertic; - int fx = i / TCOD_ctx.fontNbCharVertic; - TCOD_ctx.ascii_to_tcod[i]=fx + fy * TCOD_ctx.fontNbCharHoriz; - } - } - } -} - -void TCOD_sys_set_custom_font(const char *fontFile,int nb_ch, int nb_cv, int flags) { - strcpy(TCOD_ctx.font_file,fontFile); - /* if layout not defined, assume ASCII_INCOL */ - if (flags == 0 || flags == TCOD_FONT_TYPE_GREYSCALE) flags |= TCOD_FONT_LAYOUT_ASCII_INCOL; - TCOD_ctx.font_in_row=((flags & TCOD_FONT_LAYOUT_ASCII_INROW) != 0); - TCOD_ctx.font_greyscale = ((flags & TCOD_FONT_TYPE_GREYSCALE) != 0 ); - TCOD_ctx.font_tcod_layout = ((flags & TCOD_FONT_LAYOUT_TCOD) != 0 ); - if ( nb_ch> 0 ) { - TCOD_ctx.fontNbCharHoriz=nb_ch; - TCOD_ctx.fontNbCharVertic=nb_cv; - } else { - if ( ( flags & TCOD_FONT_LAYOUT_ASCII_INROW ) || ( flags & TCOD_FONT_LAYOUT_ASCII_INCOL ) ) { - TCOD_ctx.fontNbCharHoriz=16; - TCOD_ctx.fontNbCharVertic=16; - } else { - TCOD_ctx.fontNbCharHoriz=32; - TCOD_ctx.fontNbCharVertic=8; - } - } - if ( TCOD_ctx.font_tcod_layout ) TCOD_ctx.font_in_row=true; - check_ascii_to_tcod(); - /* - screw up things on linux64. apparently, useless - TCOD_sys_load_font(); - */ -} - -void find_resolution(void) { - TCOD_ctx.actual_fullscreen_width=TCOD_ctx.fullscreen_width>TCOD_ctx.root->w*TCOD_ctx.font_width?TCOD_ctx.fullscreen_width:TCOD_ctx.root->w*TCOD_ctx.font_width; - TCOD_ctx.actual_fullscreen_height=TCOD_ctx.fullscreen_height>TCOD_ctx.root->h*TCOD_ctx.font_height?TCOD_ctx.fullscreen_height:TCOD_ctx.root->h*TCOD_ctx.font_height; - sdl->get_closest_mode(&TCOD_ctx.actual_fullscreen_width,&TCOD_ctx.actual_fullscreen_height); -} - -void *TCOD_sys_create_bitmap_for_console(TCOD_console_t console) { - int w,h; - w = TCOD_console_get_width(console) * TCOD_ctx.font_width; - h = TCOD_console_get_height(console) * TCOD_ctx.font_height; - return TCOD_sys_get_surface(w,h,false); -} - -static void TCOD_sys_render(void *vbitmap, TCOD_console_data_t* console) { - sdl->render(sdl, vbitmap, console); -} - -void TCOD_sys_console_to_bitmap(void *vbitmap, - TCOD_console_data_t* console, TCOD_console_data_t* cache) { - static SDL_Surface *charmap_backup=NULL; - SDL_Surface *bitmap = (SDL_Surface *)vbitmap; - int x,y; - uint32_t sdl_back=0, sdl_fore=0; - TCOD_color_t fading_color = TCOD_console_get_fading_color(); - int fade = (int)TCOD_console_get_fade(); - /* can only track changes on the root console */ - bool track_changes = (cache && oldFade == fade); - uint8_t bpp = charmap->format->BytesPerPixel; - int *c = console->ch_array; - int *oc; - TCOD_color_t *ofg, *obg, *nfg, *nbg; - int hdelta; - if ( bpp == 4 ) { - hdelta=(charmap->pitch - TCOD_ctx.font_width*bpp)/4; - } else { - hdelta=(charmap->pitch - TCOD_ctx.font_width*bpp); - } - nfg = TCOD_image_get_colors(console->fg_colors); - nbg = TCOD_image_get_colors(console->bg_colors); - if (track_changes) { - oc = cache->ch_array; - ofg = TCOD_image_get_colors(cache->fg_colors); - obg = TCOD_image_get_colors(cache->bg_colors); - } - if ( charmap_backup == NULL ) { - charmap_backup=(SDL_Surface *)TCOD_sys_get_surface(charmap->w,charmap->h,true); - SDL_BlitSurface(charmap,NULL,charmap_backup,NULL); - } -#ifdef USE_SDL_LOCKS - if ( SDL_MUSTLOCK( bitmap ) && SDL_LockSurface( bitmap ) < 0 ) return; -#endif - for (y = 0; y < console->h; y++) { - for (x = 0; x < console->w; x++) { - SDL_Rect srcRect,dstRect; - bool changed=true; - if ( track_changes ) { - changed=false; - if ( - nbg->r != obg->r || nbg->g != obg->g || nbg->b != obg->b || - nfg->r != ofg->r || nfg->g != ofg->g || nfg->b != ofg->b || - *c != *oc) { - changed=true; - } - } - if ( changed ) { - TCOD_color_t b=*nbg; - dstRect.x=x*TCOD_ctx.font_width; - dstRect.y=y*TCOD_ctx.font_height; - dstRect.w=TCOD_ctx.font_width; - dstRect.h=TCOD_ctx.font_height; - /* draw background */ - if ( fade != 255 ) { - b.r = ((int)b.r) * fade / 255 + ((int)fading_color.r) * (255-fade)/255; - b.g = ((int)b.g) * fade / 255 + ((int)fading_color.g) * (255-fade)/255; - b.b = ((int)b.b) * fade / 255 + ((int)fading_color.b) * (255-fade)/255; - } - sdl_back=SDL_MapRGB(bitmap->format,b.r,b.g,b.b); - SDL_FillRect(bitmap,&dstRect,sdl_back); - if ( *c != ' ' ) { - /* draw foreground */ - int ascii = TCOD_get_tileid_for_charcode_(*c); - TCOD_color_t *curtext = &charcols[ascii]; - bool first = first_draw[ascii]; - TCOD_color_t f=*nfg; - - if ( fade != 255 ) { - f.r = ((int)f.r) * fade / 255 + ((int)fading_color.r) * (255-fade)/255; - f.g = ((int)f.g) * fade / 255 + ((int)fading_color.g) * (255-fade)/255; - f.b = ((int)f.b) * fade / 255 + ((int)fading_color.b) * (255-fade)/255; - } - /* only draw character if foreground color != background color */ - if ( f.r != b.r || f.g != b.g || f.b != b.b ) { - if ( charmap->format->Amask == 0 - && f.r == fontKeyCol.r && f.g == fontKeyCol.g && f.b == fontKeyCol.b ) { - /* cannot draw with the key color... */ - if ( f.r < 255 ) f.r++; else f.r--; - } - srcRect.x = (ascii%TCOD_ctx.fontNbCharHoriz)*TCOD_ctx.font_width; - srcRect.y = (ascii/TCOD_ctx.fontNbCharHoriz)*TCOD_ctx.font_height; - srcRect.w=TCOD_ctx.font_width; - srcRect.h=TCOD_ctx.font_height; - - if ( charmap && (first || curtext->r != f.r || curtext->g != f.g || curtext->b!=f.b) ) { - /* change the character color in the font */ - first_draw[ascii]=false; - sdl_fore=SDL_MapRGB(charmap->format,f.r,f.g,f.b) & rgb_mask; - *curtext=f; -#ifdef USE_SDL_LOCKS - if ( SDL_MUSTLOCK(charmap) ) { - if ( SDL_LockSurface(charmap) < 0 ) return; - } -#endif - if ( bpp == 4 ) { - /* 32 bits font : fill the whole character with foreground color */ - uint32_t *pix = (uint32_t *)(((uint8_t*)charmap->pixels)+srcRect.x*bpp + srcRect.y*charmap->pitch); - int h=TCOD_ctx.font_height; - if ( ! TCOD_ctx.colored[ascii] ) { - while ( h-- ) { - int w=TCOD_ctx.font_width; - while ( w-- ) { - (*pix) &= nrgb_mask; - (*pix) |= sdl_fore; - pix++; - } - pix += hdelta; - } - } else { - /* colored character : multiply color with foreground color */ - uint32_t *pixorig = (uint32_t *)(((uint8_t*)charmap_backup->pixels)+srcRect.x*bpp + srcRect.y*charmap_backup->pitch); - int hdelta_backup=(charmap_backup->pitch - TCOD_ctx.font_width*4)/4; - while (h> 0) { - int w=TCOD_ctx.font_width; - while ( w > 0 ) { - int r=(int)(*((uint8_t*)(pixorig)+charmap_backup->format->Rshift/8)); - int g=(int)(*((uint8_t*)(pixorig)+charmap_backup->format->Gshift/8)); - int b=(int)(*((uint8_t*)(pixorig)+charmap_backup->format->Bshift/8)); - (*pix) &= nrgb_mask; /* erase the color */ - r = r * f.r / 255; - g = g * f.g / 255; - b = b * f.b / 255; - /* set the new color */ - (*pix) |= (r<format->Rshift)|(g<format->Gshift)|(b<format->Bshift); - w--; - pix++; - pixorig++; - } - h--; - pix += hdelta; - pixorig += hdelta_backup; - } - } - } else { - /* 24 bits font : fill only non key color pixels */ - uint32_t *pix = (uint32_t *)(((uint8_t*)charmap->pixels)+srcRect.x*bpp + srcRect.y*charmap->pitch); - int h=TCOD_ctx.font_height; - if ( ! TCOD_ctx.colored[ascii] ) { - while ( h-- ) { - int w=TCOD_ctx.font_width; - while ( w-- ) { - if (((*pix) & rgb_mask) != sdl_key ) { - (*pix) &= nrgb_mask; - (*pix) |= sdl_fore; - } - pix = (uint32_t *) (((uint8_t*)pix)+3); - } - pix = (uint32_t *) (((uint8_t*)pix)+hdelta); - } - } else { - /* colored character : multiply color with foreground color */ - uint32_t *pixorig = (uint32_t *)(((uint8_t*)charmap_backup->pixels)+srcRect.x*4 + srcRect.y*charmap_backup->pitch); - /* charmap_backup is always 32 bits */ - int hdelta_backup=(charmap_backup->pitch - TCOD_ctx.font_width*4)/4; - while (h> 0) { - int w=TCOD_ctx.font_width; - while ( w > 0 ) { - if (((*pixorig) & rgb_mask) != sdl_key ) { - int r=(int)(*((uint8_t*)(pixorig)+charmap_backup->format->Rshift/8)); - int g=(int)(*((uint8_t*)(pixorig)+charmap_backup->format->Gshift/8)); - int b=(int)(*((uint8_t*)(pixorig)+charmap_backup->format->Bshift/8)); - (*pix) &= nrgb_mask; /* erase the color */ - r = r * f.r / 255; - g = g * f.g / 255; - b = b * f.b / 255; - /* set the new color */ - (*pix) |= (r<format->Rshift)|(g<format->Gshift)|(b<format->Bshift); - } - w--; - pix = (uint32_t *) (((uint8_t*)pix)+3); - pixorig ++; - } - h--; - pix = (uint32_t *) (((uint8_t*)pix)+hdelta); - pixorig += hdelta_backup; - } - } - } -#ifdef USE_SDL_LOCKS - if ( SDL_MUSTLOCK(charmap) ) { - SDL_UnlockSurface(charmap); - } -#endif - } - SDL_BlitSurface(charmap,&srcRect,bitmap,&dstRect); - } - } - } - c++; - nfg++; - nbg++; - if (track_changes) { - oc++; - ofg++; - obg++; - } - } - } -#ifdef USE_SDL_LOCKS - if ( SDL_MUSTLOCK( bitmap ) ) SDL_UnlockSurface( bitmap ); -#endif - if (cache) { - /* update previous values cache */ - memcpy(cache->ch_array, console->ch_array, - sizeof(console->ch_array[0]) * console->w * console->h); - TCOD_image_mipmap_copy_internal(console->fg_colors, cache->fg_colors); - TCOD_image_mipmap_copy_internal(console->bg_colors, cache->bg_colors); - } -} - -void *TCOD_sys_get_surface(int width, int height, bool alpha) { - return sdl->create_surface(width,height,alpha); -} - -void TCOD_sys_update_char(int asciiCode, int fontx, int fonty, TCOD_image_t img, int x, int y) { - int px,py; - int iw,ih; - static TCOD_color_t pink={255,0,255}; - TCOD_sys_map_ascii_to_font(asciiCode,fontx,fonty); - TCOD_image_get_size(img,&iw,&ih); - for (px=0; px < TCOD_ctx.font_width; px ++ ) { - for (py=0;py < TCOD_ctx.font_height; py++ ) { - TCOD_color_t col=TCOD_white; - uint8_t*pixel; - uint8_t bpp; - if ( (unsigned)(x+px) < (unsigned)iw && (unsigned)(y+py) < (unsigned)ih ) { - col=TCOD_image_get_pixel(img,x+px,y+py); - } - pixel=(uint8_t*)(charmap->pixels) + (fonty*TCOD_ctx.font_height+py) * charmap->pitch + (fontx*TCOD_ctx.font_width+px) * charmap->format->BytesPerPixel; - bpp = charmap->format->BytesPerPixel; - if (bpp == 4 ) { - *((pixel)+charmap->format->Ashift/8) = col.r; - *((pixel)+charmap->format->Rshift/8)=255; - *((pixel)+charmap->format->Gshift/8)=255; - *((pixel)+charmap->format->Bshift/8)=255; - } else { - *((pixel)+charmap->format->Rshift/8)=col.r; - *((pixel)+charmap->format->Gshift/8)=col.g; - *((pixel)+charmap->format->Bshift/8)=col.b; - } - } - } - charcols[asciiCode]=pink; - TCOD_sys_set_dirty_character_code(asciiCode); -} - -void TCOD_sys_startup(void) { - if (has_startup) return; -#ifndef NDEBUG - SDL_LogSetAllPriority(SDL_LOG_PRIORITY_VERBOSE); -#endif - TCOD_IFNOT(SDL_Init(SDL_INIT_VIDEO) >= 0 ) return; - memset(&TCOD_ctx.key_state,0,sizeof(TCOD_key_t)); - TCOD_ctx.max_font_chars=256; - alloc_ascii_tables(); -#ifndef NO_OPENGL - TCOD_opengl_init_attributes(); -#endif - - has_startup=true; -} - -void TCOD_sys_shutdown(void) { - if (!has_startup) return; - TCOD_sys_uninit(); - sdl->shutdown(); - SDL_Quit(); - memset(&scale_data, 0, sizeof(scale_data_t)); - has_startup = false; -} - -static void TCOD_sys_load_player_config(void) { - const char *renderer; - const char *font; - int fullscreenWidth,fullscreenHeight; - - /* define file structure */ - TCOD_parser_t parser=TCOD_parser_new(); - TCOD_parser_struct_t libtcod = TCOD_parser_new_struct(parser, "libtcod"); - TCOD_struct_add_property(libtcod, "renderer", TCOD_TYPE_STRING, false); - TCOD_struct_add_property(libtcod, "font", TCOD_TYPE_STRING, false); - TCOD_struct_add_property(libtcod, "fontInRow", TCOD_TYPE_BOOL, false); - TCOD_struct_add_property(libtcod, "fontGreyscale", TCOD_TYPE_BOOL, false); - TCOD_struct_add_property(libtcod, "fontTcodLayout", TCOD_TYPE_BOOL, false); - TCOD_struct_add_property(libtcod, "fontNbCharHoriz", TCOD_TYPE_INT, false); - TCOD_struct_add_property(libtcod, "fontNbCharVertic", TCOD_TYPE_INT, false); - TCOD_struct_add_property(libtcod, "fullscreen", TCOD_TYPE_BOOL, false); - TCOD_struct_add_property(libtcod, "fullscreenWidth", TCOD_TYPE_INT, false); - TCOD_struct_add_property(libtcod, "fullscreenHeight", TCOD_TYPE_INT, false); - TCOD_struct_add_property(libtcod, "fullscreenScaling", TCOD_TYPE_BOOL, false); - - /* parse file */ - TCOD_parser_run(parser,"./libtcod.cfg",NULL); - - /* set user preferences */ - renderer=TCOD_parser_get_string_property(parser, "libtcod.renderer"); - if ( renderer != NULL ) { - /* custom renderer */ - if ( TCOD_strcasecmp(renderer,"GLSL") == 0 ) TCOD_ctx.renderer=TCOD_RENDERER_GLSL; - else if ( TCOD_strcasecmp(renderer,"OPENGL") == 0 ) TCOD_ctx.renderer=TCOD_RENDERER_OPENGL; - else if ( TCOD_strcasecmp(renderer,"SDL") == 0 ) TCOD_ctx.renderer=TCOD_RENDERER_SDL; - else printf ("Warning : unknown renderer '%s' in libtcod.cfg\n", renderer); - } - font=TCOD_parser_get_string_property(parser, "libtcod.font"); - if ( font != NULL ) { - /* custom font */ - if ( TCOD_sys_file_exists(font)) { - int fontNbCharHoriz,fontNbCharVertic; - strcpy(TCOD_ctx.font_file,font); - TCOD_ctx.font_in_row=TCOD_parser_get_bool_property(parser,"libtcod.fontInRow"); - TCOD_ctx.font_greyscale=TCOD_parser_get_bool_property(parser,"libtcod.fontGreyscale"); - TCOD_ctx.font_tcod_layout=TCOD_parser_get_bool_property(parser,"libtcod.fontTcodLayout"); - fontNbCharHoriz=TCOD_parser_get_int_property(parser,"libtcod.fontNbCharHoriz"); - fontNbCharVertic=TCOD_parser_get_int_property(parser,"libtcod.fontNbCharVertic"); - if ( fontNbCharHoriz > 0 ) TCOD_ctx.fontNbCharHoriz=fontNbCharHoriz; - if ( fontNbCharVertic > 0 ) TCOD_ctx.fontNbCharVertic=fontNbCharVertic; - if ( charmap ) { - SDL_FreeSurface(charmap); - charmap=NULL; - } - } else { - printf ("Warning : font file '%s' does not exist\n",font); - } - } - /* custom fullscreen resolution */ - TCOD_ctx.fullscreen=TCOD_parser_get_bool_property(parser,"libtcod.fullscreen"); - fullscreenWidth=TCOD_parser_get_int_property(parser,"libtcod.fullscreenWidth"); - fullscreenHeight=TCOD_parser_get_int_property(parser,"libtcod.fullscreenHeight"); - if ( fullscreenWidth > 0 ) TCOD_ctx.fullscreen_width=fullscreenWidth; - if ( fullscreenHeight > 0 ) TCOD_ctx.fullscreen_height=fullscreenHeight; -} - - -TCOD_renderer_t TCOD_sys_get_renderer(void) { - return TCOD_ctx.renderer; -} - -void TCOD_sys_set_renderer(TCOD_renderer_t renderer) { - if ( renderer == TCOD_ctx.renderer ) return; - TCOD_ctx.renderer=renderer; - TCOD_sys_uninit(); - TCOD_sys_init(TCOD_ctx.root, TCOD_ctx.fullscreen); - TCOD_console_set_window_title(TCOD_ctx.window_title); - TCOD_console_set_dirty(0,0,TCOD_ctx.root->w,TCOD_ctx.root->h); -} - -void TCOD_sys_init_screen_offset(void) { - TCOD_ctx.fullscreen_offsetx=(TCOD_ctx.actual_fullscreen_width-TCOD_ctx.root->w*TCOD_ctx.font_width)/2; - TCOD_ctx.fullscreen_offsety=(TCOD_ctx.actual_fullscreen_height-TCOD_ctx.root->h*TCOD_ctx.font_height)/2; -} - -bool TCOD_sys_init(TCOD_console_data_t *console, bool fullscreen) { - static TCOD_renderer_t last_renderer=TCOD_RENDERER_SDL; - static char last_font[512]=""; - TCOD_sys_startup(); - /* check if there is a user (player) config file */ - if ( TCOD_sys_file_exists("./libtcod.cfg")) { - /* yes, read it */ - TCOD_sys_load_player_config(); - if (TCOD_ctx.fullscreen) fullscreen=true; - } - if (last_renderer != TCOD_ctx.renderer || ! charmap || strcmp(last_font,TCOD_ctx.font_file) != 0) { - /* reload the font when switching renderer to restore original character colors */ - TCOD_sys_load_font(); - } - sdl->create_window(console->w, console->h, fullscreen); - memset(key_status,0,sizeof(bool)*(TCODK_CHAR+1)); - - return true; -} - -void TCOD_sys_uninit(void) { - if (!has_startup) return; - sdl->destroy_window(); -} - -static char *TCOD_strcasestr (const char *haystack, const char *needle) { - const char *p, *startn = 0, *np = 0; - - for (p = haystack; *p; p++) { - if (np) { - if (toupper(*p) == toupper(*np)) { - if (!*++np) - return (char *)startn; - } else - np = 0; - } else if (toupper(*p) == toupper(*needle)) { - np = needle + 1; - startn = p; - } - } - - return 0; -} - -void TCOD_sys_save_bitmap(void *bitmap, const char *filename) { - image_support_t *img=image_type; - while ( img->extension != NULL && TCOD_strcasestr(filename,img->extension) == NULL ) img++; - if ( img->extension == NULL || img->write == NULL ) img=image_type; /* default to bmp */ - img->write((SDL_Surface *)bitmap,filename); -} - -void TCOD_sys_save_screenshot(const char *filename) { - char buf[128]; - int idx = 0; - while (!filename) { - /* generate filename */ - FILE *access_file = NULL; - sprintf(buf, "./screenshot%03d.png", idx); - access_file = fopen(buf, "rb"); - if (!access_file) { - filename = buf; - } else { - idx++; - fclose(access_file); - } - } - sdl->save_screenshot(filename); -} - -void TCOD_sys_set_fullscreen(bool fullscreen) { - TCOD_ctx.fullscreen=fullscreen; - sdl->set_fullscreen(fullscreen); -} - -void TCOD_sys_set_scale_factor(float value) { - float old_scale_factor = scale_factor; - scale_factor = value; - if (scale_factor + 1e-3 < scale_data.min_scale_factor) - scale_factor = scale_data.min_scale_factor; - else if (scale_factor - 1e-3 > MAX_SCALE_FACTOR) - scale_factor = MAX_SCALE_FACTOR; - /*printf("scale_factor: %0.3f -> %0.3f (wanted: %0.3f)", old_scale_factor, scale_factor, value);*/ -} - -void TCOD_sys_set_window_title(const char *title) { - strcpy(TCOD_ctx.window_title,title); - sdl->set_window_title(title); -} - -void TCOD_sys_flush(bool render) { - static uint32_t old_time,new_time=0, elapsed=0; - int32_t frame_time,time_to_wait; - if ( render ) { - TCOD_sys_render(NULL, TCOD_ctx.root); - } - old_time=new_time; - new_time=TCOD_sys_elapsed_milli(); - /* If TCOD has been terminated and restarted. */ - if (old_time > new_time) - old_time = elapsed = 0; - if ( new_time / 1000 != elapsed ) { - /* update fps every second */ - fps=cur_fps; - cur_fps=0; - elapsed=new_time/1000; - } - /* if too fast, wait */ - frame_time=(new_time - old_time); - last_frame_length = frame_time * 0.001f; - cur_fps++; - time_to_wait=min_frame_length-frame_time; - if (old_time > 0 && time_to_wait > 0) { - TCOD_sys_sleep_milli(time_to_wait); - new_time = TCOD_sys_elapsed_milli(); - frame_time=(new_time - old_time); - } - last_frame_length = frame_time * 0.001f; -} - -static char TCOD_sys_get_vk(SDL_Keycode sdl_key) { - int i; - for (i = 0; i < NUM_VK_TO_C_ENTRIES; i++) { - if (vk_to_c[i].sdl_key == sdl_key) { - vk_to_c[i].sdl_key = 0; - return vk_to_c[i].tcod_key; - } - } - return 0; -} - -static void TCOD_sys_set_vk(SDL_Keycode sdl_key, char tcod_key) { - int i; - for (i = 0; i < NUM_VK_TO_C_ENTRIES; i++) { - if (vk_to_c[i].sdl_key == 0) { - vk_to_c[i].sdl_key = sdl_key; - vk_to_c[i].tcod_key = tcod_key; - break; - } - } -} - -static void TCOD_sys_convert_event(SDL_Event *ev, TCOD_key_t *ret) { - SDL_KeyboardEvent *kev=&ev->key; - /* SDL2 does not map keycodes and modifiers to characters, this is on the developer. - Presumably in order to avoid problems with different keyboard layouts, they - are expected to write their own key mapping editing code for the user. */ - if (SDLK_SCANCODE_MASK == (kev->keysym.sym & SDLK_SCANCODE_MASK)) - ret->c = 0; - else - ret->c = kev->keysym.sym; - if ( ( kev->keysym.mod & (KMOD_LCTRL|KMOD_RCTRL) ) != 0 ) { - /* when pressing CTRL-A, we don't get unicode for 'a', but unicode for CTRL-A = 1. Fix it */ - if ( kev->keysym.sym >= SDLK_a && kev->keysym.sym <= SDLK_z ) { - ret->c = 'a'+(kev->keysym.sym - SDLK_a); - } - } - if ( ev->type == SDL_KEYDOWN ) TCOD_sys_set_vk(kev->keysym.sym, ret->c); - else if (ev->type == SDL_KEYUP ) ret->c = TCOD_sys_get_vk(kev->keysym.sym); - switch(kev->keysym.sym) { - case SDLK_ESCAPE : ret->vk=TCODK_ESCAPE;break; - case SDLK_SPACE : ret->vk=TCODK_SPACE; break; - case SDLK_BACKSPACE : ret->vk=TCODK_BACKSPACE;break; - case SDLK_TAB : ret->vk=TCODK_TAB;break; - case SDLK_RETURN : ret->vk=TCODK_ENTER;break; - case SDLK_PAUSE : ret->vk=TCODK_PAUSE;break; - case SDLK_PAGEUP : ret->vk=TCODK_PAGEUP;break; - case SDLK_PAGEDOWN : ret->vk=TCODK_PAGEDOWN;break; - case SDLK_HOME : ret->vk=TCODK_HOME;break; - case SDLK_END : ret->vk=TCODK_END;break; - case SDLK_DELETE : ret->vk=TCODK_DELETE;break; - case SDLK_INSERT : ret->vk=TCODK_INSERT; break; - case SDLK_LALT : case SDLK_RALT : ret->vk=TCODK_ALT;break; - case SDLK_LCTRL : case SDLK_RCTRL : ret->vk=TCODK_CONTROL;break; - case SDLK_LSHIFT : case SDLK_RSHIFT : ret->vk=TCODK_SHIFT;break; - case SDLK_PRINTSCREEN : ret->vk=TCODK_PRINTSCREEN;break; - case SDLK_LEFT : ret->vk=TCODK_LEFT;break; - case SDLK_UP : ret->vk=TCODK_UP;break; - case SDLK_RIGHT : ret->vk=TCODK_RIGHT;break; - case SDLK_DOWN : ret->vk=TCODK_DOWN;break; - case SDLK_F1 : ret->vk=TCODK_F1;break; - case SDLK_F2 : ret->vk=TCODK_F2;break; - case SDLK_F3 : ret->vk=TCODK_F3;break; - case SDLK_F4 : ret->vk=TCODK_F4;break; - case SDLK_F5 : ret->vk=TCODK_F5;break; - case SDLK_F6 : ret->vk=TCODK_F6;break; - case SDLK_F7 : ret->vk=TCODK_F7;break; - case SDLK_F8 : ret->vk=TCODK_F8;break; - case SDLK_F9 : ret->vk=TCODK_F9;break; - case SDLK_F10 : ret->vk=TCODK_F10;break; - case SDLK_F11 : ret->vk=TCODK_F11;break; - case SDLK_F12 : ret->vk=TCODK_F12;break; - case SDLK_0 : ret->vk=TCODK_0;break; - case SDLK_1 : ret->vk=TCODK_1;break; - case SDLK_2 : ret->vk=TCODK_2;break; - case SDLK_3 : ret->vk=TCODK_3;break; - case SDLK_4 : ret->vk=TCODK_4;break; - case SDLK_5 : ret->vk=TCODK_5;break; - case SDLK_6 : ret->vk=TCODK_6;break; - case SDLK_7 : ret->vk=TCODK_7;break; - case SDLK_8 : ret->vk=TCODK_8;break; - case SDLK_9 : ret->vk=TCODK_9;break; - case SDLK_RGUI : ret->vk=TCODK_RWIN;break; - case SDLK_LGUI : ret->vk=TCODK_LWIN;break; - case SDLK_NUMLOCKCLEAR : ret->vk=TCODK_NUMLOCK;break; - case SDLK_KP_0 : ret->vk=TCODK_KP0;break; - case SDLK_KP_1 : ret->vk=TCODK_KP1;break; - case SDLK_KP_2 : ret->vk=TCODK_KP2;break; - case SDLK_KP_3 : ret->vk=TCODK_KP3;break; - case SDLK_KP_4 : ret->vk=TCODK_KP4;break; - case SDLK_KP_5 : ret->vk=TCODK_KP5;break; - case SDLK_KP_6 : ret->vk=TCODK_KP6;break; - case SDLK_KP_7 : ret->vk=TCODK_KP7;break; - case SDLK_KP_8 : ret->vk=TCODK_KP8;break; - case SDLK_KP_9 : ret->vk=TCODK_KP9;break; - case SDLK_KP_DIVIDE : ret->vk=TCODK_KPDIV;break; - case SDLK_KP_MULTIPLY : ret->vk=TCODK_KPMUL;break; - case SDLK_KP_PLUS : ret->vk=TCODK_KPADD;break; - case SDLK_KP_MINUS : ret->vk=TCODK_KPSUB;break; - case SDLK_KP_ENTER : ret->vk=TCODK_KPENTER;break; - case SDLK_KP_PERIOD : ret->vk=TCODK_KPDEC;break; - default : ret->vk=TCODK_CHAR; break; - } - -} - -static TCOD_key_t TCOD_sys_SDLtoTCOD(SDL_Event *ev, int flags) { - TCOD_key_t *ret = &TCOD_ctx.key_state; - ret->vk=TCODK_NONE; - ret->c=0; - ret->pressed=0; - switch (ev->type) { - /* handled in TCOD_sys_handle_event */ - /* - case SDL_QUIT : - case SDL_VIDEOEXPOSE : - case SDL_MOUSEBUTTONDOWN : { - case SDL_MOUSEBUTTONUP : { - break; - */ - case SDL_KEYUP : { - SDL_KeyboardEvent *kev=&ev->key; - TCOD_key_t tmpkey; - switch(kev->keysym.sym) { - case SDLK_LALT : ret->lalt=0; break; - case SDLK_RALT : ret->ralt=0; break; - case SDLK_LCTRL : ret->lctrl=0; break; - case SDLK_RCTRL : ret->rctrl=0; break; - case SDLK_LSHIFT : ret->shift=0; break; - case SDLK_RSHIFT : ret->shift=0; break; - case SDLK_LGUI : ret->lmeta=0; break; - case SDLK_RGUI : ret->rmeta=0; break; - default:break; - } - TCOD_sys_convert_event(ev,&tmpkey); - key_status[tmpkey.vk]=false; - if ( flags & TCOD_KEY_RELEASED ) { - ret->vk=tmpkey.vk; - ret->c=tmpkey.c; - ret->pressed=0; - } - } - break; - case SDL_KEYDOWN : { - SDL_KeyboardEvent *kev=&ev->key; - TCOD_key_t tmpkey; - switch(kev->keysym.sym) { - case SDLK_LALT : ret->lalt=1; break; - case SDLK_RALT : ret->ralt=1; break; - case SDLK_LCTRL : ret->lctrl=1; break; - case SDLK_RCTRL : ret->rctrl=1; break; - case SDLK_LSHIFT : ret->shift=1; break; - case SDLK_RSHIFT : ret->shift=1; break; - case SDLK_LGUI : ret->lmeta=1; break; - case SDLK_RGUI : ret->rmeta=1; break; - default : break; - } - TCOD_sys_convert_event(ev,&tmpkey); - key_status[tmpkey.vk]=true; - if ( flags & TCOD_KEY_PRESSED ) { - ret->vk=tmpkey.vk; - ret->c=tmpkey.c; - ret->pressed=1; - } - } - break; - } - return *ret; -} - -bool TCOD_sys_is_key_pressed(TCOD_keycode_t key) { - return key_status[key]; -} - -#ifdef TCOD_TOUCH_INPUT -static TCOD_touch_t tcod_touch={0}; - -static int TCOD_sys_get_touch_finger_index(SDL_FingerID fingerId) { - int i; - for (i = 0; i < tcod_touch.nfingers; i++) - if (tcod_touch.finger_ids[i] == fingerId) - return i; - if (i == tcod_touch.nfingers && i+1 <= MAX_TOUCH_FINGERS) { - tcod_touch.nfingers += 1; - tcod_touch.finger_ids[i] = fingerId; - return i; - } - return -1; -} -#endif - -void TCOD_sys_unproject_screen_coords(int sx, int sy, int *ssx, int *ssy) { - if (scale_data.dst_display_width != 0 ) { - *ssx = (scale_data.src_x0 + ((sx - scale_data.dst_offset_x) * scale_data.src_copy_width) / scale_data.dst_display_width); - *ssy = (scale_data.src_y0 + ((sy - scale_data.dst_offset_y) * scale_data.src_copy_width) / scale_data.dst_display_width); - } else { - *ssx=sx - TCOD_ctx.fullscreen_offsetx; - *ssy=sy - TCOD_ctx.fullscreen_offsety; - } -} - -void TCOD_sys_convert_console_to_screen_coords(int cx, int cy, int *sx, int *sy) { - *sx = scale_data.dst_offset_x + ((cx * TCOD_ctx.font_width - scale_data.src_x0) * scale_data.dst_display_width) / scale_data.src_copy_width; - *sy = scale_data.dst_offset_y + ((cy * TCOD_ctx.font_height - scale_data.src_y0) * scale_data.dst_display_height) / scale_data.src_copy_height; -} - -void TCOD_sys_convert_screen_to_console_coords(int sx, int sy, int *cx, int *cy) { - int ssx, ssy; - TCOD_sys_unproject_screen_coords(sx, sy, &ssx, &ssy); - *cx = ssx / TCOD_ctx.font_width; - *cy = ssy / TCOD_ctx.font_height; -} - -static TCOD_mouse_t tcod_mouse={0,0,0,0,0,0,0,0,false,false,false,false,false,false,false,false}; -static TCOD_event_t TCOD_sys_handle_event(SDL_Event *ev,TCOD_event_t eventMask, TCOD_key_t *key, TCOD_mouse_t *mouse) { - TCOD_event_t retMask=0; - key->text[0] = '\0'; - /* printf("TCOD_sys_handle_event type=%04x\n", ev->type); */ - switch(ev->type) { - case SDL_KEYDOWN : { - TCOD_key_t tmpKey=TCOD_sys_SDLtoTCOD(ev,TCOD_KEY_PRESSED); - if ( (TCOD_EVENT_KEY_PRESS & eventMask) != 0) { - retMask|=TCOD_EVENT_KEY_PRESS; - if ( key ) *key = tmpKey; - return retMask; - } - } - break; - case SDL_KEYUP : { - TCOD_key_t tmpKey=TCOD_sys_SDLtoTCOD(ev,TCOD_KEY_RELEASED); - if ( (TCOD_EVENT_KEY_RELEASE & eventMask) != 0) { - retMask|=TCOD_EVENT_KEY_RELEASE; - if ( key ) *key = tmpKey; - return retMask; - } - } - break; - case SDL_TEXTINPUT: { - SDL_TextInputEvent *iev=&ev->text; - *key = TCOD_ctx.key_state; - key->vk = TCODK_TEXT; - key->c = 0; - key->pressed = 1; - strncpy(key->text, iev->text, TCOD_KEY_TEXT_SIZE); - return retMask | TCOD_EVENT_KEY_PRESS; - } - break; -#ifdef TCOD_TOUCH_INPUT - /* - * Need to distinguish between: - * - Tap: Can be optionally delegated to a mouse press. - * - Touch and drag: Should affect scaling screen position. - * - */ - case SDL_FINGERDOWN : - case SDL_FINGERUP : - case SDL_FINGERMOTION : - { - int idx, mouse_touch_valid; - float xf, yf, screen_x, screen_y; - uint32_t ticks_taken = 0; - - /* Reset the global variable. */ - if (tcod_touch.nfingerspressed == 0) { - tcod_touch.nupdates = 0; - tcod_touch.nfingers = 0; - tcod_touch.ticks0 = SDL_GetTicks(); - } else - ticks_taken = SDL_GetTicks() - tcod_touch.ticks0; - - idx = TCOD_sys_get_touch_finger_index(ev->tfinger.fingerId); - if (idx == -1) { - TCOD_LOG(("ERROR: failed to allocate extra finger")); - break; - } - - /* Count the number of events contributing to an ongoing tracked touch (zeroed above in finger press). */ - tcod_touch.finger_id = ev->tfinger.fingerId; - tcod_touch.nupdates += 1; - - /* We only emulate mouse events when the first finger is the only one pressed. */ - if (SDL_FINGERDOWN == ev->type) { - tcod_touch.nfingerspressed += 1; - tcod_touch.fingerspressed[idx] = 1; - mouse_touch_valid = mouse_touch && tcod_touch.nfingerspressed == 1 && tcod_touch.fingerspressed[0]; - } else if (SDL_FINGERUP == ev->type) { - mouse_touch_valid = mouse_touch && tcod_touch.nfingerspressed == 1 && tcod_touch.fingerspressed[0]; - tcod_touch.nfingerspressed -= 1; - tcod_touch.fingerspressed[idx] = 0; - } else - mouse_touch_valid = mouse_touch && tcod_touch.nfingerspressed == 1 && tcod_touch.fingerspressed[0]; - - /* Coordinates are raw full screen positions. */ - screen_x = ev->tfinger.x * scale_data.surface_width; - screen_y = ev->tfinger.y * scale_data.surface_height; - xf = (float)(screen_x - scale_data.dst_offset_x) / scale_data.dst_display_width; - yf = (float)(screen_y - scale_data.dst_offset_y) / scale_data.dst_display_height; - tcod_touch.coords[idx][0] = scale_data.src_x0 + scale_data.src_copy_width * xf; - tcod_touch.coords[idx][1] = scale_data.src_y0 + scale_data.src_copy_height * yf; - tcod_touch.coords_delta[idx][0] = ev->tfinger.dx * scale_data.src_proportionate_width; - tcod_touch.coords_delta[idx][1] = ev->tfinger.dy * scale_data.src_proportionate_height; - - /* Console coordinates need to be mapped back from screen coordinates through scaling. */ - tcod_touch.consolecoords[idx][0] = tcod_touch.coords[idx][0] / TCOD_ctx.font_width; - tcod_touch.consolecoords[idx][1] = tcod_touch.coords[idx][1] / TCOD_ctx.font_height; - tcod_touch.consolecoords_delta[idx][0] = tcod_touch.coords_delta[idx][0] / TCOD_ctx.font_width; - tcod_touch.consolecoords_delta[idx][1] = tcod_touch.coords_delta[idx][1] / TCOD_ctx.font_height; - - if (SDL_FINGERDOWN == ev->type) { - // printf("SDL_FINGERDOWN [%d] ticks=%d", tcod_touch.nupdates, ticks_taken); - if ((TCOD_EVENT_FINGER_PRESS & eventMask) != 0) - retMask |= TCOD_EVENT_FINGER_PRESS; - - if (mouse_touch_valid && (TCOD_EVENT_MOUSE_PRESS & eventMask) != 0) { - mouse->lbutton=mousebl=true; - retMask |= TCOD_EVENT_MOUSE_PRESS; - } - } else if (SDL_FINGERUP == ev->type) { - // printf("SDL_FINGERUP [%d] ticks=%d", tcod_touch.nupdates, ticks_taken); - if ((TCOD_EVENT_FINGER_RELEASE & eventMask) != 0) - retMask |= TCOD_EVENT_FINGER_RELEASE; - - if (mouse_touch_valid && (TCOD_EVENT_MOUSE_RELEASE & eventMask) != 0) { - if (mousebl) - mouse->lbutton_pressed = mouse_force_bl=true; - mouse->lbutton = mousebl=false; - retMask |= TCOD_EVENT_MOUSE_RELEASE; - } - } else if (SDL_FINGERMOTION == ev->type) { - float scale_adjust = 1.0f, xc_shift = 0.0f, yc_shift = 0.0f; - - // printf("SDL_FINGERMOTION [%d] ticks=%d", tcod_touch.nupdates, ticks_taken); - if ((TCOD_EVENT_FINGER_MOVE & eventMask) != 0) - retMask |= TCOD_EVENT_FINGER_MOVE; - - if (mouse_touch_valid && (TCOD_EVENT_MOUSE_MOVE & eventMask) != 0) - retMask |= TCOD_EVENT_MOUSE_MOVE; - - if (tcod_touch.nfingerspressed == 1) { - /* One finger drag AKA drag to move. - * Ignore the first few move events that happen unhelpfully immediately after finger down. */ - if (tcod_touch.fingerspressed[0] && (tcod_touch.coords_delta[0][0] || tcod_touch.coords_delta[0][1]) && ticks_taken > 10) { - xc_shift = (float)tcod_touch.coords_delta[idx][0] / scale_data.surface_width; - yc_shift = (float)tcod_touch.coords_delta[idx][1] / scale_data.surface_height; - } - } else if (tcod_touch.nfingerspressed == 2) { - /* Two finger pinch AKA pinch to zoom - * Both fingers should stay exactly where they are on the full surface - * in order to manipulate the drag and zoom effect. */ - if (tcod_touch.fingerspressed[0] && tcod_touch.fingerspressed[1]) { - /* - * New algorithm - */ - int f0x0 = tcod_touch.coords[0][0]-tcod_touch.coords_delta[0][0], f0y0 = tcod_touch.coords[0][1]-tcod_touch.coords_delta[0][1]; - int f1x0 = tcod_touch.coords[1][0]-tcod_touch.coords_delta[1][0], f1y0 = tcod_touch.coords[1][1]-tcod_touch.coords_delta[1][1]; - int f0x1 = tcod_touch.coords[0][0], f0y1 = tcod_touch.coords[0][1]; - int f1x1 = tcod_touch.coords[1][0], f1y1 = tcod_touch.coords[1][1]; - float p0x = (f1x0 + f0x0)/2.0f, p0y = (f1y0 + f0y0)/2.0f; - float p1x = (f1x1 + f0x1)/2.0f, p1y = (f1y1 + f0y1)/2.0f; - float len_previous = sqrtf((float)(pow(f0x0-f1x0,2) + pow(f0y0-f1y0,2))); - float len_current = sqrt((float)(pow(f0x1-f1x1, 2) + pow(f0y1-f1y1,2))); - scale_adjust = len_current/len_previous; - xc_shift = ((p1x - p0x) / scale_data.surface_width); - yc_shift = ((p1y - p0y) / scale_data.surface_height); - } - } - - /* Bound the translations within the console area. */ - if (fabs(xc_shift) > 1e-3f) { - sdl->scale_xc -= xc_shift; /* Actual display shift is the inverted finger movement. */ - if (sdl->scale_xc + 1e-3f < 0.0f) - sdl->scale_xc = 0.0f; - if (sdl->scale_xc - 1e-3f > 1.0f) - sdl->scale_xc = 1.0f; - } - if (fabs(yc_shift) > 1e-3f) { - sdl->scale_yc -= yc_shift; /* Actual display shift is the inverted finger movement. */ - if (sdl->scale_yc + 1e-3f < 0.0f) - sdl->scale_yc = 0.0f; - if (sdl->scale_yc - 1e-3f > 1.0f) - sdl->scale_yc = 1.0f; - } - if (fabs(scale_adjust - 1.0f) > 1e-3f) - TCOD_sys_set_scale_factor(scale_factor * scale_adjust); - } - - /* We need to distinguish between handleable touch events, and short distinct mouse events. */ - if (ticks_taken > 400 || tcod_touch.nfingers > 1) { - // printf("DEF NOT MOUSE CODE[%d]", tcod_touch.nupdates); - mouse->cx = 0; - mouse->cy = 0; - mouse->dcx = 0; - mouse->dcy = 0; - } else if (mouse_touch_valid && (retMask & (TCOD_EVENT_MOUSE_PRESS|TCOD_EVENT_MOUSE_RELEASE|TCOD_EVENT_MOUSE_MOVE)) != 0) { - mouse->x = tcod_touch.coords[idx][0]; - mouse->y = tcod_touch.coords[idx][1]; - mouse->dx += tcod_touch.coords_delta[idx][0]; - mouse->dy += tcod_touch.coords_delta[idx][1]; - mouse->cx = tcod_touch.consolecoords[idx][0]; - mouse->cy = tcod_touch.consolecoords[idx][1]; - mouse->dcx = tcod_touch.consolecoords_delta[idx][0]; - mouse->dcy = tcod_touch.consolecoords_delta[idx][1]; - /* printf("CX,CY: %d,%d", mouse->cx,mouse->cy); */ - } - - break; - } -#endif - case SDL_MOUSEMOTION : - if ( (TCOD_EVENT_MOUSE_MOVE & eventMask) != 0) { - SDL_MouseMotionEvent *mev=&ev->motion; - TCOD_sys_unproject_screen_coords(mev->x, mev->y, &mouse->x, &mouse->y); - if (scale_data.surface_width != 0) { - mouse->dx += (mev->xrel * scale_data.src_proportionate_width) / scale_data.surface_width; - mouse->dy += (mev->yrel * scale_data.src_proportionate_height) / scale_data.surface_height; - } - mouse->cx = mouse->x / TCOD_ctx.font_width; - mouse->cy = mouse->y / TCOD_ctx.font_height; - mouse->dcx = mouse->dx / TCOD_ctx.font_width; - mouse->dcy = mouse->dy / TCOD_ctx.font_height; - - return retMask | TCOD_EVENT_MOUSE_MOVE; - } - break; - case SDL_MOUSEWHEEL : - if (ev->wheel.y < 0) - mouse->wheel_down=true; - else - mouse->wheel_up=true; - return retMask | TCOD_EVENT_MOUSE_PRESS; - break; - case SDL_MOUSEBUTTONDOWN : - if ( (TCOD_EVENT_MOUSE_PRESS & eventMask) != 0) { - SDL_MouseButtonEvent *mev=&ev->button; - retMask|=TCOD_EVENT_MOUSE_PRESS; - switch (mev->button) { - case SDL_BUTTON_LEFT : mouse->lbutton=mousebl=true; break; - case SDL_BUTTON_MIDDLE : mouse->mbutton=mousebm=true; break; - case SDL_BUTTON_RIGHT : mouse->rbutton=mousebr=true; break; - } - /* update mouse position */ - if ( (TCOD_EVENT_MOUSE_MOVE & eventMask) == 0) { - mouse->x=mev->x; - mouse->y=mev->y; - mouse->cx = (mouse->x - TCOD_ctx.fullscreen_offsetx) / TCOD_ctx.font_width; - mouse->cy = (mouse->y - TCOD_ctx.fullscreen_offsety) / TCOD_ctx.font_height; - } - return retMask; - } - break; - case SDL_MOUSEBUTTONUP : - if ( (TCOD_EVENT_MOUSE_RELEASE & eventMask) != 0) { - SDL_MouseButtonEvent *mev=&ev->button; - retMask|=TCOD_EVENT_MOUSE_RELEASE; - switch (mev->button) { - case SDL_BUTTON_LEFT : if (mousebl) mouse->lbutton_pressed = mouse_force_bl=true; mouse->lbutton = mousebl=false; break; - case SDL_BUTTON_MIDDLE : if (mousebm) mouse->mbutton_pressed = mouse_force_bm=true; mouse->mbutton = mousebm=false; break; - case SDL_BUTTON_RIGHT : if (mousebr) mouse->rbutton_pressed = mouse_force_br=true; mouse->rbutton = mousebr=false; break; - } - /* update mouse position */ - if ( (TCOD_EVENT_MOUSE_MOVE & eventMask) == 0) { - mouse->x=mev->x; - mouse->y=mev->y; - mouse->cx = (mouse->x - TCOD_ctx.fullscreen_offsetx) / TCOD_ctx.font_width; - mouse->cy = (mouse->y - TCOD_ctx.fullscreen_offsety) / TCOD_ctx.font_height; - } - return retMask; - } - break; - case SDL_QUIT : - TCOD_ctx.is_window_closed=true; - break; - case SDL_WINDOWEVENT : - /* At this point, there are some corner cases that need dealing with. So log this. */ - /* printf("SDL2 WINDOWEVENT: 0x%04x\n", ev->window.event); */ - switch (ev->window.event) { -#ifdef TCOD_ANDROID - case SDL_WINDOWEVENT_SIZE_CHANGED: - { - /* printf("SDL2 WINDOWEVENT (SDL_WINDOWEVENT_SIZE_CHANGED): 0x%04x w=%d h=%d\n", ev->window.event, ev->window.data1, ev->window.data2); */ - /* If the app is started while the device is locked, the screen will be in portrait mode. We need to rescale when it changes. */ - if (scale_data.surface_width != ev->window.data1 || scale_data.surface_height != ev->window.data1) - scale_data.force_recalc = 1; - break; - } -#endif - case SDL_WINDOWEVENT_ENTER: /**< Window has gained mouse focus */ - TCOD_ctx.app_has_mouse_focus=true; break; - case SDL_WINDOWEVENT_LEAVE: /**< Window has lost mouse focus */ - TCOD_ctx.app_has_mouse_focus=false; break; - case SDL_WINDOWEVENT_FOCUS_GAINED: - TCOD_ctx.app_is_active=true; break; - case SDL_WINDOWEVENT_FOCUS_LOST: - TCOD_ctx.app_is_active=false; break; - case SDL_WINDOWEVENT_EXPOSED: /**< Window has been returned to and needs a refresh. */ - TCOD_sys_render(NULL, TCOD_ctx.root); - break; -#ifdef NDEBUG_HMM - default: - TCOD_LOG(("SDL2 WINDOWEVENT (unknown): 0x%04x\n", ev->window.event)); - break; -#endif - } - break; - default : break; - } - return retMask; -} - -TCOD_event_t TCOD_sys_wait_for_event(int eventMask, TCOD_key_t *key, TCOD_mouse_t *mouse, bool flush) { - SDL_Event ev; - TCOD_event_t retMask=0; - if ( eventMask == 0 ) return 0; - if ( flush ) { - while ( SDL_PollEvent(&ev) ) { - TCOD_sys_SDLtoTCOD(&ev,0); - } - } - tcod_mouse.lbutton_pressed =false; - tcod_mouse.rbutton_pressed =false; - tcod_mouse.mbutton_pressed =false; - tcod_mouse.wheel_up=false; - tcod_mouse.wheel_down=false; - tcod_mouse.dx=0; - tcod_mouse.dy=0; - if ( key ) { - key->vk=TCODK_NONE; - key->c=0; - } - do { - SDL_WaitEvent(&ev); - retMask=TCOD_sys_handle_event(&ev,eventMask,key,&tcod_mouse); - } while ( ev.type != SDL_QUIT && (retMask & eventMask) == 0 ); - if (mouse) { *mouse=tcod_mouse; } - return retMask; -} - -TCOD_event_t TCOD_sys_check_for_event(int eventMask, TCOD_key_t *key, TCOD_mouse_t *mouse) { - SDL_Event ev; - TCOD_event_t retMask=0; - if ( eventMask == 0 ) return 0; - tcod_mouse.lbutton_pressed =false; - tcod_mouse.rbutton_pressed =false; - tcod_mouse.mbutton_pressed =false; - tcod_mouse.wheel_up=false; - tcod_mouse.wheel_down=false; - tcod_mouse.dx=0; - tcod_mouse.dy=0; - if ( key ) { - key->vk=TCODK_NONE; - key->c=0; - } - while ( SDL_PollEvent(&ev) ) { - retMask=TCOD_sys_handle_event(&ev,eventMask,key,&tcod_mouse); - if ((retMask & TCOD_EVENT_KEY) != 0) - /* only one key event per frame */ - break; - } - if (mouse) { *mouse=tcod_mouse; } - return retMask; -} - -TCOD_mouse_t TCOD_mouse_get_status(void) { - return tcod_mouse; -} - - -/* classic keyboard functions (based on generic events) */ -/** - * Return immediately with a recently pressed key. - * - * \param flags A TCOD_event_t bit-field, for example: `TCOD_EVENT_KEY_PRESS` - * \return A TCOD_key_t struct with a recently pressed key. - * If no event exists then the `vk` attribute will be `TCODK_NONE` - */ -TCOD_key_t TCOD_sys_check_for_keypress(int flags) { - static TCOD_key_t noret={TCODK_NONE,0}; - - TCOD_key_t key; - TCOD_event_t ev = TCOD_sys_check_for_event(flags & TCOD_EVENT_KEY, &key, NULL); - - if ((ev & TCOD_EVENT_KEY) == 0) return noret; - - return key; -} -/** - * Wait for a key press event, then return it. - * - * \param flush If 1 then the event queue will be cleared before waiting for - * the next event. This should always be 0. - * \return A TCOD_key_t struct with the most recent key data. - */ -TCOD_key_t TCOD_sys_wait_for_keypress(bool flush) { - static TCOD_key_t noret={TCODK_NONE,0}; - - TCOD_key_t key; - TCOD_event_t ev = TCOD_sys_wait_for_event(TCOD_EVENT_KEY_PRESS, &key, NULL, flush); - - if ((ev & TCOD_EVENT_KEY_PRESS) == 0) return noret; - - return key; -} - - -void TCOD_sys_sleep_milli(uint32_t milliseconds) { - SDL_Delay(milliseconds); -} - -void *TCOD_sys_load_image(const char *filename) { - image_support_t *img=image_type; - while ( img->extension != NULL && !img->check_type(filename) ) img++; - if ( img->extension == NULL || img->read == NULL ) return NULL; /* unknown format */ - return img->read(filename); -} - -void TCOD_sys_get_image_size(const void *image, int *w, int *h) { - SDL_Surface *surf=(SDL_Surface *)image; - *w = surf->w; - *h = surf->h; -} - -TCOD_color_t TCOD_sys_get_image_pixel(const void *image,int x, int y) { - TCOD_color_t ret; - SDL_Surface *surf=(SDL_Surface *)image; - uint8_t bpp; - uint8_t*bits; - if ( x < 0 || y < 0 || x >= surf->w || y >= surf->h ) return TCOD_black; - bpp = surf->format->BytesPerPixel; - bits = ((uint8_t*)surf->pixels)+y*surf->pitch+x*bpp; - switch (bpp) { - case 1 : - { - if (surf->format->palette) { - SDL_Color col = surf->format->palette->colors[(*bits)]; - ret.r=col.r; - ret.g=col.g; - ret.b=col.b; - } else return TCOD_black; - } - break; - default : - ret.r = *((bits)+surf->format->Rshift/8); - ret.g = *((bits)+surf->format->Gshift/8); - ret.b = *((bits)+surf->format->Bshift/8); - break; - } - - return ret; -} - -int TCOD_sys_get_image_alpha(const void *image,int x, int y) { - SDL_Surface *surf=(SDL_Surface *)image; - uint8_t bpp; - uint8_t*bits; - if ( x < 0 || y < 0 || x >= surf->w || y >= surf->h ) return 255; - bpp = surf->format->BytesPerPixel; - if ( bpp != 4 ) return 255; - bits = ((uint8_t*)surf->pixels)+y*surf->pitch+x*bpp; - return *((bits)+surf->format->Ashift/8); -} - -uint32_t TCOD_sys_elapsed_milli(void) { - return (uint32_t)SDL_GetTicks(); -} - -float TCOD_sys_elapsed_seconds(void) { - static float div=1.0f/1000.0f; - return SDL_GetTicks()*div; -} - -void TCOD_sys_force_fullscreen_resolution(int width, int height) { - TCOD_ctx.fullscreen_width=width; - TCOD_ctx.fullscreen_height=height; -} - -void * TCOD_sys_create_bitmap(int width, int height, TCOD_color_t *buf) { - int x,y; - SDL_PixelFormat fmt; - SDL_Surface *bitmap; - memset(&fmt,0,sizeof(SDL_PixelFormat)); - if ( charmap != NULL ) { - fmt = *charmap->format; - } else { - fmt.BitsPerPixel=24; - fmt.Amask=0; - if ( SDL_BYTEORDER == SDL_LIL_ENDIAN ) { - fmt.Rmask=0x0000FF; - fmt.Gmask=0x00FF00; - fmt.Bmask=0xFF0000; - } else { - fmt.Rmask=0xFF0000; - fmt.Gmask=0x00FF00; - fmt.Bmask=0x0000FF; - } - } - bitmap=SDL_CreateRGBSurface(SDL_SWSURFACE,width,height,fmt.BitsPerPixel,fmt.Rmask,fmt.Gmask,fmt.Bmask,fmt.Amask); - for (x=0; x < width; x++) { - for (y=0; y < height; y++) { - SDL_Rect rect; - uint32_t col=SDL_MapRGB(&fmt,buf[x+y*width].r,buf[x+y*width].g,buf[x+y*width].b); - rect.x=x; - rect.y=y; - rect.w=1; - rect.h=1; - SDL_FillRect(bitmap,&rect,col); - } - } - return (void *)bitmap; -} - -void TCOD_sys_delete_bitmap(void *bitmap) { - SDL_FreeSurface((SDL_Surface *)bitmap); -} - -void TCOD_sys_set_fps(int val) { - if( val == 0 ) min_frame_length=0; - else min_frame_length=1000/val; -} - -void TCOD_sys_save_fps(void) { - min_frame_length_backup=min_frame_length; -} - -void TCOD_sys_restore_fps(void) { - min_frame_length=min_frame_length_backup; -} - -int TCOD_sys_get_fps(void) { - return fps; -} - -float TCOD_sys_get_last_frame_length(void) { - return last_frame_length; -} - -void TCOD_sys_get_char_size(int *w, int *h) { - *w = TCOD_ctx.font_width; - *h = TCOD_ctx.font_height; -} - -void TCOD_sys_get_current_resolution(int *w, int *h) { - /* be sure that SDL is initialized */ - TCOD_sys_startup(); - sdl->get_current_resolution(w,h); -} - -/* image stuff */ -bool TCOD_sys_check_magic_number(const char *filename, size_t size, uint8_t*data) { - uint8_t tmp[128]; - size_t i; - SDL_RWops *rwops = SDL_RWFromFile(filename, "rb"); - if (! rwops) return false; - if ( (i = rwops->read(rwops,tmp,size,1)) != 1 ) { - rwops->close(rwops); - return false; - } - rwops->close(rwops); - for (i=0; i< size; i++) if (tmp[i]!=data[i]) return false; - return true; -} - -void *TCOD_sys_get_SDL_window(void) { - return (void *)window; -} - -void *TCOD_sys_get_SDL_renderer(void) { - return (void *)renderer; -} - -/* mouse stuff */ -void TCOD_mouse_show_cursor(bool visible) { - SDL_ShowCursor(visible ? 1 : 0); -} - -bool TCOD_mouse_is_cursor_visible(void) { - return SDL_ShowCursor(-1) ? true : false; -} - -void TCOD_mouse_move(int x, int y) { - sdl->set_mouse_position(x,y); -} - -void TCOD_mouse_includes_touch(bool enable) { -#ifdef TCOD_TOUCH_INPUT - mouse_touch = enable; -#endif -} - -/*clipboard stuff */ -bool TCOD_sys_clipboard_set(const char *value) { - if (!has_startup) { return false; } - return sdl->set_clipboard_text(value); -} - -char *TCOD_sys_clipboard_get() { - if (!has_startup) { return ""; } - return sdl->get_clipboard_text(); -} - -bool TCOD_sys_read_file(const char *filename, unsigned char **buf, size_t *size) { - return sdl->file_read(filename,buf,size); -} - -bool TCOD_sys_file_exists(const char * filename, ...) { - char f[1024]; - va_list ap; - va_start(ap,filename); - vsprintf(f,filename,ap); - va_end(ap); - return sdl->file_exists(f); -} - -bool TCOD_sys_write_file(const char *filename, unsigned char *buf, uint32_t size) { - return sdl->file_write(filename,buf,size); -} - -/* Mark a rectangle of tiles dirty. */ -void TCOD_sys_set_dirty(int dx, int dy, int dw, int dh) { - int x, y; - TCOD_console_data_t *dat = sdl->get_root_console_cache(); - if (!dat) return; - TCOD_IFNOT(dx < dat->w && dy < dat->h && dx + dw >= 0 && dy + dh >= 0) return; - TCOD_IFNOT(dx >= 0) { - dw += dx; - dx = 0; - } - TCOD_IFNOT(dy >= 0) { - dh += dy; - dy = 0; - } - TCOD_IFNOT(dx + dw <= dat->w) dw = dat->w - dx; - TCOD_IFNOT(dy + dh <= dat->h) dh = dat->h - dy; - - for (x = dx; x < dx + dw; ++x) { - for (y = dy; y < dy + dh; ++y) { - dat->ch_array[dat->w * y + x] = -1; - } - } -} - -/* Mark a character dirty by invalidating all occurrences of it in the software - renderer cache. Each character tile will be refreshed when the old buffer - is compared to the current buffer next render. - It's recommended that this method stays non-public. */ -void TCOD_sys_set_dirty_character_code(int ch) { - int i; - TCOD_console_data_t *dat = sdl->get_root_console_cache(); - if (!dat) return; - for (i = 0; i < dat->w * dat->h; ++i) { - if (dat->ch_array[i] == ch) { - dat->ch_array[i] = -1; - } - } -} -/** - * Return the current tile index for a given character code. - */ -int TCOD_get_tileid_for_charcode_(int charcode) { - if (charcode >= 0 && charcode < TCOD_ctx.max_font_chars) { - return TCOD_ctx.ascii_to_tcod[charcode]; - } - return 0; -} -#endif /* TCOD_BARE */ +/* +* libtcod +* Copyright (c) 2008-2018 Jice & Mingos & rmtew +* All rights reserved. +* +* Redistribution and use in source and binary forms, with or without +* modification, are permitted provided that the following conditions are met: +* * Redistributions of source code must retain the above copyright +* notice, this list of conditions and the following disclaimer. +* * Redistributions in binary form must reproduce the above copyright +* notice, this list of conditions and the following disclaimer in the +* documentation and/or other materials provided with the distribution. +* * The name of Jice or Mingos may not be used to endorse or promote +* products derived from this software without specific prior written +* permission. +* +* THIS SOFTWARE IS PROVIDED BY JICE, MINGOS AND RMTEW ``AS IS'' AND ANY +* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED +* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE +* DISCLAIMED. IN NO EVENT SHALL JICE, MINGOS OR RMTEW BE LIABLE FOR ANY +* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES +* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; +* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND +* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS +* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +*/ +#ifndef TCOD_BARE +#include "mouse.h" +#include "sys.h" + +#include +#include +#include +#include + +#include +#include "console.h" +#include "libtcod_int.h" +#include "parser.h" +#include "engine/globals.h" + +static TCOD_SDL_driver_t *sdl=NULL; + + +/* library initialization function */ +#ifdef TCOD_WINDOWS +#define NOMINMAX +#include +BOOL APIENTRY DllMain( HINSTANCE hModule, DWORD reason, LPVOID reserved) { + switch (reason ) { + case DLL_PROCESS_ATTACH : sdl = SDL_implementation_factory(); break; + default : break; + } + return TRUE; +} +#else + void __attribute__ ((constructor)) DllMain(void) { + sdl = SDL_implementation_factory(); + } +#endif + +#if defined(__ANDROID__) +#define TCOD_TOUCH_INPUT +#define MAX_TOUCH_FINGERS 5 + +typedef struct { + int nupdates; /* how many updates have happened since the first finger was pressed. */ + uint32_t ticks0; /* current number of ticks at start of touch event sequence. */ + SDL_FingerID finger_id; /* the last finger which was pressed. */ + int coords[MAX_TOUCH_FINGERS][2]; /* absolute position of each finger. */ + int coords_delta[MAX_TOUCH_FINGERS][2]; /* absolute position of each finger. */ + int consolecoords[MAX_TOUCH_FINGERS][2]; /* cell coordinates in the root console for each finger. */ + int consolecoords_delta[MAX_TOUCH_FINGERS][2]; /* cell coordinates in the root console for each finger. */ + int nfingers; /* number of unique fingers employed at any time during this. */ + int nfingerspressed; /* number of those fingers currently still pressed. */ + SDL_FingerID finger_ids[MAX_TOUCH_FINGERS]; + char fingerspressed[MAX_TOUCH_FINGERS]; +} TCOD_touch_t; +#endif + +/* to enable bitmap locking. Is there any use ?? makes the OSX port renderer to fail */ +/*#define USE_SDL_LOCKS */ + +/* image support stuff */ +bool TCOD_sys_check_bmp(const char *filename); +SDL_Surface *TCOD_sys_read_bmp(const char *filename); +void TCOD_sys_write_bmp(const SDL_Surface *surf, const char *filename); +bool TCOD_sys_check_png(const char *filename); +SDL_Surface *TCOD_sys_read_png(const char *filename); +void TCOD_sys_write_png(const SDL_Surface *surf, const char *filename); + +typedef struct { + char *extension; + bool (*check_type)(const char *filename); + SDL_Surface *(*read)(const char *filename); + void (*write)(const SDL_Surface *surf, const char *filename); +} image_support_t; + +static image_support_t image_type[] = { + { "BMP", TCOD_sys_check_bmp, TCOD_sys_read_bmp, TCOD_sys_write_bmp }, + { "PNG", TCOD_sys_check_png, TCOD_sys_read_png, TCOD_sys_write_png }, + { NULL, NULL, NULL, NULL }, +}; + +scale_data_t scale_data={0}; +SDL_Window* window=NULL; +SDL_Renderer* renderer=NULL; +float scale_factor=1.0f; +SDL_Surface* charmap=NULL; +char *last_clipboard_text = NULL; +static bool has_startup=false; +#define MAX_SCALE_FACTOR 5.0f + +/* font transparent color */ +static TCOD_color_t fontKeyCol={0,0,0}; + +static uint32_t sdl_key=0, rgb_mask=0, nrgb_mask=0; + +/* mouse stuff */ +static bool mousebl=false; +static bool mousebm=false; +static bool mousebr=false; +static bool mouse_force_bl=false; +static bool mouse_force_bm=false; +static bool mouse_force_br=false; +#ifdef TCOD_TOUCH_INPUT +static bool mouse_touch=true; +#endif + +/* minimum length for a frame (when fps are limited) */ +static int min_frame_length=0; +static int min_frame_length_backup=0; +/* number of frames in the last second */ +static int fps=0; +/* current number of frames */ +static int cur_fps=0; +/* length of the last rendering loop */ +static float last_frame_length=0.0f; + +static TCOD_color_t *charcols=NULL; +static bool *first_draw=NULL; +static bool key_status[TCODK_CHAR+1]; +int oldFade=-1; + +/* convert SDL vk to a char (depends on the keyboard layout) */ +typedef struct { + SDL_Keycode sdl_key; + int tcod_key; +} vk_to_c_entry; +#define NUM_VK_TO_C_ENTRIES 10 +static vk_to_c_entry vk_to_c[NUM_VK_TO_C_ENTRIES]; + +/* convert ASCII code to TCOD layout position */ +static int init_ascii_to_tcod[256] = { + 0, 0, 0, 0, 0, 0, 0, 0, 0, 76, 77, 0, 0, 0, 0, 0, /* ASCII 0 to 15 */ + 71, 70, 72, 0, 0, 0, 0, 0, 64, 65, 67, 66, 0, 73, 68, 69, /* ASCII 16 to 31 */ + 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, /* ASCII 32 to 47 */ + 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, /* ASCII 48 to 63 */ + 32, 96, 97, 98, 99,100,101,102,103,104,105,106,107,108,109,110, /* ASCII 64 to 79 */ +111,112,113,114,115,116,117,118,119,120,121, 33, 34, 35, 36, 37, /* ASCII 80 to 95 */ + 38,128,129,130,131,132,133,134,135,136,137,138,139,140,141,142, /* ASCII 96 to 111 */ +143,144,145,146,147,148,149,150,151,152,153, 39, 40, 41, 42, 0, /* ASCII 112 to 127 */ + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* ASCII 128 to 143 */ + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* ASCII 144 to 159 */ + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* ASCII 160 to 175 */ + 43, 44, 45, 46, 49, 0, 0, 0, 0, 81, 78, 87, 88, 0, 0, 55, /* ASCII 176 to 191 */ + 53, 50, 52, 51, 47, 48, 0, 0, 85, 86, 82, 84, 83, 79, 80, 0, /* ASCII 192 to 207 */ + 0, 0, 0, 0, 0, 0, 0, 0, 0, 56, 54, 0, 0, 0, 0, 0, /* ASCII 208 to 223 */ + 74, 75, 57, 58, 59, 60, 61, 62, 63, 0, 0, 0, 0, 0, 0, 0, /* ASCII 224 to 239 */ + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* ASCII 240 to 255 */ +}; + +static void alloc_ascii_tables(void) { + if ( TCOD_ctx.ascii_to_tcod ) free(TCOD_ctx.ascii_to_tcod); + if ( charcols ) { + free(charcols); + free(first_draw); + } + + TCOD_ctx.ascii_to_tcod = (int *)calloc(sizeof(int),TCOD_ctx.max_font_chars); + charcols = (TCOD_color_t *)calloc(sizeof(TCOD_color_t),TCOD_ctx.max_font_chars); + first_draw =(bool *)calloc(sizeof(bool),TCOD_ctx.max_font_chars); + memcpy(TCOD_ctx.ascii_to_tcod,init_ascii_to_tcod,sizeof(int)*256); +} +/** Reallocate the TCOD_ctx.ascii_to_tcod array, usually to make it bigger. + */ +static int realloc_ascii_tables(int new_size) { + int *new_table = static_cast(realloc(TCOD_ctx.ascii_to_tcod, + sizeof(int) * new_size)); + int i; + if (!new_table) { + return -1; /* failed to realloc table (old table pointer is still good) */ + } + /* any new array indexes are undefined and need to be filled with zeros */ + for (i = TCOD_ctx.max_font_chars; i < new_size; ++i) { + new_table[i] = 0; + } + TCOD_ctx.ascii_to_tcod = new_table; + TCOD_ctx.max_font_chars = new_size; + return 0; +} + +static void check_ascii_to_tcod(void) { + if ( TCOD_ctx.fontNbCharHoriz * TCOD_ctx.fontNbCharVertic != TCOD_ctx.max_font_chars ) { + TCOD_ctx.max_font_chars=TCOD_ctx.fontNbCharHoriz * TCOD_ctx.fontNbCharVertic; + alloc_ascii_tables(); + } +} + +void TCOD_sys_register_SDL_renderer(SDL_renderer_t renderer) { + TCOD_ctx.sdl_cbk=renderer; +} +/** See TCOD_console_map_ascii_code_to_font */ +void TCOD_sys_map_ascii_to_font(int asciiCode, int fontCharX, int fontCharY) { + if (asciiCode <= 0) { return; } /* can't reassign 0 or negatives */ + // Assign to new-style Tileset. + auto tileset = tcod::engine::get_tileset(); + auto tilesheet = tcod::engine::get_tilesheet(); + if (tileset && tilesheet) { + try { + tileset->set_tile(asciiCode, tilesheet->get_tile(fontCharX, fontCharY)); + } catch (const std::runtime_error&) { // Ignore errors and continue. + } catch (const std::logic_error&) { + } + } + // Assign to legacy character table. + if (asciiCode >= TCOD_ctx.max_font_chars) { + /* reduce total allocations by resizing in increments of 256 */ + if (realloc_ascii_tables((asciiCode & 0xff) + 1)) { + return; /* Failed to realloc table (old table pointer is still good) */ + } + } + TCOD_ctx.ascii_to_tcod[asciiCode] = + fontCharX + fontCharY * TCOD_ctx.fontNbCharHoriz; +} + +void TCOD_sys_load_font(void) { + int i; + bool hasTransparent=false; + int x,y; + + if ( charmap ) SDL_FreeSurface(charmap); + charmap=static_cast(TCOD_sys_load_image(TCOD_ctx.font_file)); + if (charmap == NULL ) TCOD_fatal("SDL : cannot load %s",TCOD_ctx.font_file); + if ( (float)(charmap->w / TCOD_ctx.fontNbCharHoriz) != charmap->w / TCOD_ctx.fontNbCharHoriz + || (float)(charmap->h / TCOD_ctx.fontNbCharVertic) != charmap->h / TCOD_ctx.fontNbCharVertic ) TCOD_fatal(" %s size is not a multiple of font layout (%dx%d)\n", + TCOD_ctx.font_file,TCOD_ctx.fontNbCharHoriz,TCOD_ctx.fontNbCharVertic); + TCOD_ctx.font_width=charmap->w/TCOD_ctx.fontNbCharHoriz; + TCOD_ctx.font_height=charmap->h/TCOD_ctx.fontNbCharVertic; + /* allocated bool array for colored flags */ + if ( TCOD_ctx.colored ) free(TCOD_ctx.colored); + TCOD_ctx.colored=(bool *)calloc(sizeof(bool), TCOD_ctx.fontNbCharHoriz*TCOD_ctx.fontNbCharVertic); + check_ascii_to_tcod(); + /* figure out what kind of font we have */ + /* check if the alpha layer is actually used */ + if ( charmap->format->BytesPerPixel == 4 ) { + TCOD_LOG(("32bits font... checking for alpha layer... ")); + for (x=0; !hasTransparent && x < charmap->w; x ++ ) { + for (y=0;!hasTransparent && y < charmap->h; y++ ) { + uint8_t*pixel=(uint8_t*)(charmap->pixels) + y * charmap->pitch + x * charmap->format->BytesPerPixel; + uint8_t alpha=*((pixel)+charmap->format->Ashift/8); + if ( alpha < 255 ) { + hasTransparent=true; + } + } + } + TCOD_LOG((hasTransparent ? "present\n" : "not present\n")); + } else if ( charmap->format->BytesPerPixel != 3 ) { + /* convert to 24 bits */ + SDL_Surface *temp; + TCOD_LOG(("font bpp < 24. converting to 24bits\n")); + temp=(SDL_Surface *)TCOD_sys_get_surface(charmap->w,charmap->h,false); + SDL_BlitSurface(charmap,NULL,temp,NULL); + SDL_FreeSurface(charmap); + charmap=temp; + } else { + TCOD_LOG(("24 bits font.\n")); + } + if (! hasTransparent ) { + /* alpha layer not used */ + int keyx,keyy; + uint8_t*pixel; + /* the key color is found on the character corresponding to space ' ' */ + if ( TCOD_ctx.font_tcod_layout ) { + keyx = TCOD_ctx.font_width/2; + keyy = TCOD_ctx.font_height/2; + } else if (TCOD_ctx.font_in_row) { + keyx = ((int)(' ') % TCOD_ctx.fontNbCharHoriz ) * TCOD_ctx.font_width + TCOD_ctx.font_width/2; + keyy = ((int)(' ') / TCOD_ctx.fontNbCharHoriz ) * TCOD_ctx.font_height + TCOD_ctx.font_height/2; + } else { + keyx = ((int)(' ') / TCOD_ctx.fontNbCharVertic ) * TCOD_ctx.font_width + TCOD_ctx.font_width/2; + keyy = ((int)(' ') % TCOD_ctx.fontNbCharVertic ) * TCOD_ctx.font_height + TCOD_ctx.font_height/2; + } + pixel=(uint8_t*)(charmap->pixels) + keyy * charmap->pitch + keyx * charmap->format->BytesPerPixel; + fontKeyCol.r=*((pixel)+charmap->format->Rshift/8); + fontKeyCol.g=*((pixel)+charmap->format->Gshift/8); + fontKeyCol.b=*((pixel)+charmap->format->Bshift/8); + TCOD_LOG(("key color : %d %d %d\n",fontKeyCol.r,fontKeyCol.g,fontKeyCol.b)); + if ( ! TCOD_ctx.font_greyscale && charmap->format->BytesPerPixel == 4 ) { + /* 32 bits font but alpha layer not used. convert to 24 bits (faster) */ + SDL_Surface *temp; + TCOD_LOG(("32bits font with no alpha => converting to faster 24 bits\n")); + temp=(SDL_Surface *)TCOD_sys_get_surface(charmap->w,charmap->h,false); + SDL_BlitSurface(charmap,NULL,temp,NULL); + SDL_FreeSurface(charmap); + charmap=temp; + } + } + /* detect colored tiles */ + for (i=0; i < TCOD_ctx.fontNbCharHoriz*TCOD_ctx.fontNbCharVertic; i++ ) { + int px,py,cx,cy; + bool end=false; + cx=(i%TCOD_ctx.fontNbCharHoriz); + cy=(i/TCOD_ctx.fontNbCharHoriz); + for( px=0; !end && px < TCOD_ctx.font_width; px++ ) { + for (py=0; !end && py < TCOD_ctx.font_height; py++ ) { + uint8_t*pixel=(uint8_t*)(charmap->pixels) + (cy*TCOD_ctx.font_height+py) * charmap->pitch + + (cx*TCOD_ctx.font_width+px) * charmap->format->BytesPerPixel; + uint8_t r=*((pixel)+charmap->format->Rshift/8); + uint8_t g=*((pixel)+charmap->format->Gshift/8); + uint8_t b=*((pixel)+charmap->format->Bshift/8); + if ( charmap->format->BytesPerPixel == 3 ) { + /* ignore key color */ + if ( r == fontKeyCol.r && g == fontKeyCol.g && b == fontKeyCol.b ) continue; + } + /* colored tile if a pixel is not desaturated */ + if ( r != g || g !=b || b != r ) { + TCOD_ctx.colored[i]=true; + TCOD_LOG(("character for ascii code %d is colored\n",i)); + end=true; + } + } + } + } + /* convert 24/32 bits greyscale to 32bits font with alpha layer */ + if ( ! hasTransparent && TCOD_ctx.font_greyscale ) { + bool invert=( fontKeyCol.r > 128 ); /* black on white font ? */ + /* convert the surface to 32 bits if needed */ + if ( charmap->format->BytesPerPixel != 4 ) { + SDL_Surface *temp; + TCOD_LOG(("24bits greyscale font. converting to 32bits\n")); + temp=(SDL_Surface *)TCOD_sys_get_surface(charmap->w,charmap->h,true); + SDL_BlitSurface(charmap,NULL,temp,NULL); + SDL_FreeSurface(charmap); + charmap=temp; + } + for (i=0; i < TCOD_ctx.fontNbCharHoriz*TCOD_ctx.fontNbCharVertic; i++ ) { + int cx,cy; + cx=(i%TCOD_ctx.fontNbCharHoriz); + cy=(i/TCOD_ctx.fontNbCharHoriz); + /* fill the surface with white (except colored tiles), use alpha layer for characters */ + for (x=cx*TCOD_ctx.font_width; x < (cx+1)*TCOD_ctx.font_width; x ++ ) { + for (y=cy*TCOD_ctx.font_height;y < (cy+1)*TCOD_ctx.font_height; y++ ) { + if ( ! TCOD_ctx.colored[i]) { + uint8_t*pixel=(uint8_t*)(charmap->pixels) + y * charmap->pitch + x * charmap->format->BytesPerPixel; + uint8_t r=*((pixel)+charmap->format->Rshift/8); + *((pixel)+charmap->format->Ashift/8) = (invert ? 255-r : r); + *((pixel)+charmap->format->Rshift/8)=255; + *((pixel)+charmap->format->Gshift/8)=255; + *((pixel)+charmap->format->Bshift/8)=255; + } else { + uint8_t*pixel=(uint8_t*)(charmap->pixels) + y * charmap->pitch + x * charmap->format->BytesPerPixel; + uint8_t r=*((pixel)+charmap->format->Rshift/8); + uint8_t g=*((pixel)+charmap->format->Gshift/8); + uint8_t b=*((pixel)+charmap->format->Bshift/8); + if ( r == fontKeyCol.r && g == fontKeyCol.g && b == fontKeyCol.b ) { + *((pixel)+charmap->format->Ashift/8) = 0; + } else { + *((pixel)+charmap->format->Ashift/8) = 255; + } + } + } + } + } + } + sdl_key=SDL_MapRGB(charmap->format,fontKeyCol.r,fontKeyCol.g,fontKeyCol.b); + rgb_mask=charmap->format->Rmask|charmap->format->Gmask|charmap->format->Bmask; + nrgb_mask = ~ rgb_mask; + sdl_key &= rgb_mask; /* remove the alpha part */ + if ( charmap->format->BytesPerPixel == 3 ) SDL_SetColorKey(charmap,SDL_TRUE|SDL_RLEACCEL,sdl_key); + for (i=0; i < TCOD_ctx.fontNbCharHoriz*TCOD_ctx.fontNbCharVertic; i++ ) { + charcols[i]=fontKeyCol; + first_draw[i]=true; + } + check_ascii_to_tcod(); + if (!TCOD_ctx.font_tcod_layout) { + /* apply standard ascii mapping */ + if ( TCOD_ctx.font_in_row ) { + /* for font in row */ + for (i=0; i < TCOD_ctx.max_font_chars; i++ ) TCOD_ctx.ascii_to_tcod[i]=i; + } else { + /* for font in column */ + for (i=0; i < TCOD_ctx.max_font_chars; i++ ) { + int fy = i % TCOD_ctx.fontNbCharVertic; + int fx = i / TCOD_ctx.fontNbCharVertic; + TCOD_ctx.ascii_to_tcod[i]=fx + fy * TCOD_ctx.fontNbCharHoriz; + } + } + } +} + +void TCOD_sys_set_custom_font(const char *fontFile,int nb_ch, int nb_cv, int flags) { + check_ascii_to_tcod(); +} + +void find_resolution(void) { + TCOD_ctx.actual_fullscreen_width=TCOD_ctx.fullscreen_width>TCOD_ctx.root->w*TCOD_ctx.font_width?TCOD_ctx.fullscreen_width:TCOD_ctx.root->w*TCOD_ctx.font_width; + TCOD_ctx.actual_fullscreen_height=TCOD_ctx.fullscreen_height>TCOD_ctx.root->h*TCOD_ctx.font_height?TCOD_ctx.fullscreen_height:TCOD_ctx.root->h*TCOD_ctx.font_height; + sdl->get_closest_mode(&TCOD_ctx.actual_fullscreen_width,&TCOD_ctx.actual_fullscreen_height); +} + +void *TCOD_sys_create_bitmap_for_console(TCOD_console_t console) { + int w,h; + w = TCOD_console_get_width(console) * TCOD_ctx.font_width; + h = TCOD_console_get_height(console) * TCOD_ctx.font_height; + return TCOD_sys_get_surface(w,h,false); +} + +static void TCOD_sys_render(void *vbitmap, struct TCOD_Console* console) { + if (!tcod::engine::get_display()) { + sdl->render(sdl, vbitmap, console); + } +} + +void TCOD_sys_console_to_bitmap(void *vbitmap, + struct TCOD_Console* console, struct TCOD_Console* cache) { + static SDL_Surface *charmap_backup=NULL; + SDL_Surface *bitmap = (SDL_Surface *)vbitmap; + int x,y; + uint32_t sdl_back=0, sdl_fore=0; + TCOD_color_t fading_color = TCOD_console_get_fading_color(); + int fade = (int)TCOD_console_get_fade(); + /* can only track changes on the root console */ + bool track_changes = (cache && oldFade == fade); + uint8_t bpp = charmap->format->BytesPerPixel; + int *c = console->ch_array; + int *oc; + TCOD_color_t *ofg, *obg, *nfg, *nbg; + int hdelta; + if ( bpp == 4 ) { + hdelta=(charmap->pitch - TCOD_ctx.font_width*bpp)/4; + } else { + hdelta=(charmap->pitch - TCOD_ctx.font_width*bpp); + } + nfg = console->fg_array; + nbg = console->bg_array; + if (track_changes) { + oc = cache->ch_array; + ofg = cache->fg_array; + obg = cache->bg_array; + } + if ( charmap_backup == NULL ) { + charmap_backup=(SDL_Surface *)TCOD_sys_get_surface(charmap->w,charmap->h,true); + SDL_BlitSurface(charmap,NULL,charmap_backup,NULL); + } +#ifdef USE_SDL_LOCKS + if ( SDL_MUSTLOCK( bitmap ) && SDL_LockSurface( bitmap ) < 0 ) return; +#endif + for (y = 0; y < console->h; y++) { + for (x = 0; x < console->w; x++) { + SDL_Rect srcRect,dstRect; + bool changed=true; + if ( track_changes ) { + changed=false; + if ( + nbg->r != obg->r || nbg->g != obg->g || nbg->b != obg->b || + nfg->r != ofg->r || nfg->g != ofg->g || nfg->b != ofg->b || + *c != *oc) { + changed=true; + } + } + if ( changed ) { + TCOD_color_t b=*nbg; + dstRect.x=x*TCOD_ctx.font_width; + dstRect.y=y*TCOD_ctx.font_height; + dstRect.w=TCOD_ctx.font_width; + dstRect.h=TCOD_ctx.font_height; + /* draw background */ + if ( fade != 255 ) { + b.r = ((int)b.r) * fade / 255 + ((int)fading_color.r) * (255-fade)/255; + b.g = ((int)b.g) * fade / 255 + ((int)fading_color.g) * (255-fade)/255; + b.b = ((int)b.b) * fade / 255 + ((int)fading_color.b) * (255-fade)/255; + } + sdl_back=SDL_MapRGB(bitmap->format,b.r,b.g,b.b); + SDL_FillRect(bitmap,&dstRect,sdl_back); + if ( *c != ' ' ) { + /* draw foreground */ + int ascii = TCOD_get_tileid_for_charcode_(*c); + TCOD_color_t *curtext = &charcols[ascii]; + bool first = first_draw[ascii]; + TCOD_color_t f=*nfg; + + if ( fade != 255 ) { + f.r = ((int)f.r) * fade / 255 + ((int)fading_color.r) * (255-fade)/255; + f.g = ((int)f.g) * fade / 255 + ((int)fading_color.g) * (255-fade)/255; + f.b = ((int)f.b) * fade / 255 + ((int)fading_color.b) * (255-fade)/255; + } + /* only draw character if foreground color != background color */ + if ( f.r != b.r || f.g != b.g || f.b != b.b ) { + if ( charmap->format->Amask == 0 + && f.r == fontKeyCol.r && f.g == fontKeyCol.g && f.b == fontKeyCol.b ) { + /* cannot draw with the key color... */ + if ( f.r < 255 ) f.r++; else f.r--; + } + srcRect.x = (ascii%TCOD_ctx.fontNbCharHoriz)*TCOD_ctx.font_width; + srcRect.y = (ascii/TCOD_ctx.fontNbCharHoriz)*TCOD_ctx.font_height; + srcRect.w=TCOD_ctx.font_width; + srcRect.h=TCOD_ctx.font_height; + + if ( charmap && (first || curtext->r != f.r || curtext->g != f.g || curtext->b!=f.b) ) { + /* change the character color in the font */ + first_draw[ascii]=false; + sdl_fore=SDL_MapRGB(charmap->format,f.r,f.g,f.b) & rgb_mask; + *curtext=f; +#ifdef USE_SDL_LOCKS + if ( SDL_MUSTLOCK(charmap) ) { + if ( SDL_LockSurface(charmap) < 0 ) return; + } +#endif + if ( bpp == 4 ) { + /* 32 bits font : fill the whole character with foreground color */ + uint32_t *pix = (uint32_t *)(((uint8_t*)charmap->pixels)+srcRect.x*bpp + srcRect.y*charmap->pitch); + int h=TCOD_ctx.font_height; + if ( ! TCOD_ctx.colored[ascii] ) { + while ( h-- ) { + int w=TCOD_ctx.font_width; + while ( w-- ) { + (*pix) &= nrgb_mask; + (*pix) |= sdl_fore; + pix++; + } + pix += hdelta; + } + } else { + /* colored character : multiply color with foreground color */ + uint32_t *pixorig = (uint32_t *)(((uint8_t*)charmap_backup->pixels)+srcRect.x*bpp + srcRect.y*charmap_backup->pitch); + int hdelta_backup=(charmap_backup->pitch - TCOD_ctx.font_width*4)/4; + while (h> 0) { + int w=TCOD_ctx.font_width; + while ( w > 0 ) { + int r=(int)(*((uint8_t*)(pixorig)+charmap_backup->format->Rshift/8)); + int g=(int)(*((uint8_t*)(pixorig)+charmap_backup->format->Gshift/8)); + int b=(int)(*((uint8_t*)(pixorig)+charmap_backup->format->Bshift/8)); + (*pix) &= nrgb_mask; /* erase the color */ + r = r * f.r / 255; + g = g * f.g / 255; + b = b * f.b / 255; + /* set the new color */ + (*pix) |= (r<format->Rshift)|(g<format->Gshift)|(b<format->Bshift); + w--; + pix++; + pixorig++; + } + h--; + pix += hdelta; + pixorig += hdelta_backup; + } + } + } else { + /* 24 bits font : fill only non key color pixels */ + uint32_t *pix = (uint32_t *)(((uint8_t*)charmap->pixels)+srcRect.x*bpp + srcRect.y*charmap->pitch); + int h=TCOD_ctx.font_height; + if ( ! TCOD_ctx.colored[ascii] ) { + while ( h-- ) { + int w=TCOD_ctx.font_width; + while ( w-- ) { + if (((*pix) & rgb_mask) != sdl_key ) { + (*pix) &= nrgb_mask; + (*pix) |= sdl_fore; + } + pix = (uint32_t *) (((uint8_t*)pix)+3); + } + pix = (uint32_t *) (((uint8_t*)pix)+hdelta); + } + } else { + /* colored character : multiply color with foreground color */ + uint32_t *pixorig = (uint32_t *)(((uint8_t*)charmap_backup->pixels)+srcRect.x*4 + srcRect.y*charmap_backup->pitch); + /* charmap_backup is always 32 bits */ + int hdelta_backup=(charmap_backup->pitch - TCOD_ctx.font_width*4)/4; + while (h> 0) { + int w=TCOD_ctx.font_width; + while ( w > 0 ) { + if (((*pixorig) & rgb_mask) != sdl_key ) { + int r=(int)(*((uint8_t*)(pixorig)+charmap_backup->format->Rshift/8)); + int g=(int)(*((uint8_t*)(pixorig)+charmap_backup->format->Gshift/8)); + int b=(int)(*((uint8_t*)(pixorig)+charmap_backup->format->Bshift/8)); + (*pix) &= nrgb_mask; /* erase the color */ + r = r * f.r / 255; + g = g * f.g / 255; + b = b * f.b / 255; + /* set the new color */ + (*pix) |= (r<format->Rshift)|(g<format->Gshift)|(b<format->Bshift); + } + w--; + pix = (uint32_t *) (((uint8_t*)pix)+3); + pixorig ++; + } + h--; + pix = (uint32_t *) (((uint8_t*)pix)+hdelta); + pixorig += hdelta_backup; + } + } + } +#ifdef USE_SDL_LOCKS + if ( SDL_MUSTLOCK(charmap) ) { + SDL_UnlockSurface(charmap); + } +#endif + } + SDL_BlitSurface(charmap,&srcRect,bitmap,&dstRect); + } + } + } + c++; + nfg++; + nbg++; + if (track_changes) { + oc++; + ofg++; + obg++; + } + } + } +#ifdef USE_SDL_LOCKS + if ( SDL_MUSTLOCK( bitmap ) ) SDL_UnlockSurface( bitmap ); +#endif + if (cache) { + /* update previous values cache */ + memcpy(cache->ch_array, console->ch_array, + sizeof(console->ch_array[0]) * console->w * console->h); + memcpy(cache->fg_array, console->fg_array, + sizeof(console->fg_array[0]) * console->w * console->h); + memcpy(cache->bg_array, console->bg_array, + sizeof(console->bg_array[0]) * console->w * console->h); + } +} + +void *TCOD_sys_get_surface(int width, int height, bool alpha) { + return sdl->create_surface(width,height,alpha); +} + +void TCOD_sys_update_char(int asciiCode, int fontx, int fonty, TCOD_image_t img, int x, int y) { + int px,py; + int iw,ih; + static TCOD_color_t pink={255,0,255}; + TCOD_sys_map_ascii_to_font(asciiCode,fontx,fonty); + TCOD_image_get_size(img,&iw,&ih); + for (px=0; px < TCOD_ctx.font_width; px ++ ) { + for (py=0;py < TCOD_ctx.font_height; py++ ) { + TCOD_color_t col=TCOD_white; + uint8_t*pixel; + uint8_t bpp; + if ( (unsigned)(x+px) < (unsigned)iw && (unsigned)(y+py) < (unsigned)ih ) { + col=TCOD_image_get_pixel(img,x+px,y+py); + } + pixel=(uint8_t*)(charmap->pixels) + (fonty*TCOD_ctx.font_height+py) * charmap->pitch + (fontx*TCOD_ctx.font_width+px) * charmap->format->BytesPerPixel; + bpp = charmap->format->BytesPerPixel; + if (bpp == 4 ) { + *((pixel)+charmap->format->Ashift/8) = col.r; + *((pixel)+charmap->format->Rshift/8)=255; + *((pixel)+charmap->format->Gshift/8)=255; + *((pixel)+charmap->format->Bshift/8)=255; + } else { + *((pixel)+charmap->format->Rshift/8)=col.r; + *((pixel)+charmap->format->Gshift/8)=col.g; + *((pixel)+charmap->format->Bshift/8)=col.b; + } + } + } + charcols[asciiCode]=pink; + TCOD_sys_set_dirty_character_code(asciiCode); +} +/** + * Older startup function, mostly called from TCOD_sys_init. + */ +void TCOD_sys_startup(void) { + if (has_startup) return; +#ifndef NDEBUG + SDL_LogSetAllPriority(SDL_LOG_PRIORITY_VERBOSE); +#endif + TCOD_IFNOT(SDL_Init(SDL_INIT_VIDEO) >= 0 ) return; + memset(&TCOD_ctx.key_state,0,sizeof(TCOD_key_t)); + TCOD_ctx.max_font_chars=256; + alloc_ascii_tables(); +#ifndef NO_OPENGL + TCOD_opengl_init_attributes(); +#endif + + has_startup=true; +} +/** + * All shutdown routines call this function. + * + * Mostly used internally. TCOD_quit should be called to shutdown the library. + */ +void TCOD_sys_shutdown(void) +{ + if (TCOD_ctx.root) { + TCOD_console_data_free(TCOD_ctx.root); + free(TCOD_ctx.root); + TCOD_ctx.root = NULL; + } + if (tcod::engine::get_display()){ + tcod::engine::set_display(nullptr); + return; + } + if (has_startup) { + sdl->destroy_window(); + sdl->shutdown(); + memset(&scale_data, 0, sizeof(scale_data_t)); + has_startup = false; + } + SDL_Quit(); +} + +static void TCOD_sys_load_player_config(void) { + const char *renderer; + const char *font; + int fullscreenWidth,fullscreenHeight; + + /* define file structure */ + TCOD_parser_t parser=TCOD_parser_new(); + TCOD_parser_struct_t libtcod = TCOD_parser_new_struct(parser, "libtcod"); + TCOD_struct_add_property(libtcod, "renderer", TCOD_TYPE_STRING, false); + TCOD_struct_add_property(libtcod, "font", TCOD_TYPE_STRING, false); + TCOD_struct_add_property(libtcod, "fontInRow", TCOD_TYPE_BOOL, false); + TCOD_struct_add_property(libtcod, "fontGreyscale", TCOD_TYPE_BOOL, false); + TCOD_struct_add_property(libtcod, "fontTcodLayout", TCOD_TYPE_BOOL, false); + TCOD_struct_add_property(libtcod, "fontNbCharHoriz", TCOD_TYPE_INT, false); + TCOD_struct_add_property(libtcod, "fontNbCharVertic", TCOD_TYPE_INT, false); + TCOD_struct_add_property(libtcod, "fullscreen", TCOD_TYPE_BOOL, false); + TCOD_struct_add_property(libtcod, "fullscreenWidth", TCOD_TYPE_INT, false); + TCOD_struct_add_property(libtcod, "fullscreenHeight", TCOD_TYPE_INT, false); + TCOD_struct_add_property(libtcod, "fullscreenScaling", TCOD_TYPE_BOOL, false); + + /* parse file */ + TCOD_parser_run(parser,"./libtcod.cfg",NULL); + + /* set user preferences */ + renderer=TCOD_parser_get_string_property(parser, "libtcod.renderer"); + if ( renderer != NULL ) { + /* custom renderer */ + if ( TCOD_strcasecmp(renderer,"GLSL") == 0 ) TCOD_ctx.renderer=TCOD_RENDERER_GLSL; + else if ( TCOD_strcasecmp(renderer,"OPENGL") == 0 ) TCOD_ctx.renderer=TCOD_RENDERER_OPENGL; + else if ( TCOD_strcasecmp(renderer,"SDL") == 0 ) TCOD_ctx.renderer=TCOD_RENDERER_SDL; + else printf ("Warning : unknown renderer '%s' in libtcod.cfg\n", renderer); + } + font=TCOD_parser_get_string_property(parser, "libtcod.font"); + if ( font != NULL ) { + /* custom font */ + if ( TCOD_sys_file_exists(font)) { + int fontNbCharHoriz,fontNbCharVertic; + strcpy(TCOD_ctx.font_file,font); + TCOD_ctx.font_in_row=TCOD_parser_get_bool_property(parser,"libtcod.fontInRow"); + TCOD_ctx.font_greyscale=TCOD_parser_get_bool_property(parser,"libtcod.fontGreyscale"); + TCOD_ctx.font_tcod_layout=TCOD_parser_get_bool_property(parser,"libtcod.fontTcodLayout"); + fontNbCharHoriz=TCOD_parser_get_int_property(parser,"libtcod.fontNbCharHoriz"); + fontNbCharVertic=TCOD_parser_get_int_property(parser,"libtcod.fontNbCharVertic"); + if ( fontNbCharHoriz > 0 ) TCOD_ctx.fontNbCharHoriz=fontNbCharHoriz; + if ( fontNbCharVertic > 0 ) TCOD_ctx.fontNbCharVertic=fontNbCharVertic; + if ( charmap ) { + SDL_FreeSurface(charmap); + charmap=NULL; + } + } else { + printf ("Warning : font file '%s' does not exist\n",font); + } + } + /* custom fullscreen resolution */ + TCOD_ctx.fullscreen=TCOD_parser_get_bool_property(parser,"libtcod.fullscreen"); + fullscreenWidth=TCOD_parser_get_int_property(parser,"libtcod.fullscreenWidth"); + fullscreenHeight=TCOD_parser_get_int_property(parser,"libtcod.fullscreenHeight"); + if ( fullscreenWidth > 0 ) TCOD_ctx.fullscreen_width=fullscreenWidth; + if ( fullscreenHeight > 0 ) TCOD_ctx.fullscreen_height=fullscreenHeight; +} + + +TCOD_renderer_t TCOD_sys_get_renderer(void) { + return TCOD_ctx.renderer; +} + +void TCOD_sys_set_renderer(TCOD_renderer_t renderer) { + if ( renderer == TCOD_ctx.renderer ) return; + TCOD_console_init_root(TCOD_ctx.root->w, TCOD_ctx.root->h, + TCOD_ctx.window_title, TCOD_ctx.fullscreen, renderer); +} + +void TCOD_sys_init_screen_offset(void) { + TCOD_ctx.fullscreen_offsetx=(TCOD_ctx.actual_fullscreen_width-TCOD_ctx.root->w*TCOD_ctx.font_width)/2; + TCOD_ctx.fullscreen_offsety=(TCOD_ctx.actual_fullscreen_height-TCOD_ctx.root->h*TCOD_ctx.font_height)/2; +} + +bool TCOD_sys_init(struct TCOD_Console *console, bool fullscreen) { + static TCOD_renderer_t last_renderer=TCOD_RENDERER_SDL; + static char last_font[512]=""; + TCOD_sys_startup(); + /* check if there is a user (player) config file */ + if ( TCOD_sys_file_exists("./libtcod.cfg")) { + /* yes, read it */ + TCOD_sys_load_player_config(); + if (TCOD_ctx.fullscreen) fullscreen=true; + } + if (last_renderer != TCOD_ctx.renderer || ! charmap || strcmp(last_font,TCOD_ctx.font_file) != 0) { + /* reload the font when switching renderer to restore original character colors */ + TCOD_sys_load_font(); + } + sdl->create_window(console->w, console->h, fullscreen); + memset(key_status,0,sizeof(bool)*(TCODK_CHAR+1)); + + return true; +} + +static char *TCOD_strcasestr (const char *haystack, const char *needle) { + const char *p, *startn = 0, *np = 0; + + for (p = haystack; *p; p++) { + if (np) { + if (toupper(*p) == toupper(*np)) { + if (!*++np) + return (char *)startn; + } else + np = 0; + } else if (toupper(*p) == toupper(*needle)) { + np = needle + 1; + startn = p; + } + } + + return 0; +} + +void TCOD_sys_save_bitmap(void *bitmap, const char *filename) { + image_support_t *img=image_type; + while ( img->extension != NULL && TCOD_strcasestr(filename,img->extension) == NULL ) img++; + if ( img->extension == NULL || img->write == NULL ) img=image_type; /* default to bmp */ + img->write((SDL_Surface *)bitmap,filename); +} + +void TCOD_sys_save_screenshot(const char *filename) { + char buf[128]; + int idx = 0; + while (!filename) { + /* generate filename */ + FILE *access_file = NULL; + sprintf(buf, "./screenshot%03d.png", idx); + access_file = fopen(buf, "rb"); + if (!access_file) { + filename = buf; + } else { + idx++; + fclose(access_file); + } + } + sdl->save_screenshot(filename); +} + +void TCOD_sys_set_fullscreen(bool fullscreen) { + TCOD_ctx.fullscreen=fullscreen; + sdl->set_fullscreen(fullscreen); +} + +void TCOD_sys_set_scale_factor(float value) { + float old_scale_factor = scale_factor; + scale_factor = value; + if (scale_factor + 1e-3 < scale_data.min_scale_factor) + scale_factor = scale_data.min_scale_factor; + else if (scale_factor - 1e-3 > MAX_SCALE_FACTOR) + scale_factor = MAX_SCALE_FACTOR; + /*printf("scale_factor: %0.3f -> %0.3f (wanted: %0.3f)", old_scale_factor, scale_factor, value);*/ +} + +void TCOD_sys_set_window_title(const char *title) { + strcpy(TCOD_ctx.window_title,title); + sdl->set_window_title(title); +} +/** + * Keep track of time and wait if the frame-rate is faster than the set FPS. + */ +static void sync_time(void) { + static uint32_t old_time = 0; + static uint32_t new_time = 0; + static uint32_t elapsed = 0; + int32_t frame_time; + int32_t time_to_wait; + + old_time = new_time; + new_time = TCOD_sys_elapsed_milli(); + /* If TCOD has been terminated and restarted. */ + if (old_time > new_time) + old_time = elapsed = 0; + if ( new_time / 1000 != elapsed ) { + /* update fps every second */ + fps = cur_fps; + cur_fps = 0; + elapsed = new_time / 1000; + } + /* if too fast, wait */ + frame_time = (new_time - old_time); + last_frame_length = frame_time * 0.001f; + cur_fps++; + time_to_wait = min_frame_length - frame_time; + if (old_time > 0 && time_to_wait > 0) { + TCOD_sys_sleep_milli(time_to_wait); + new_time = TCOD_sys_elapsed_milli(); + frame_time=(new_time - old_time); + } + last_frame_length = frame_time * 0.001f; +} +/** + * Flush the screen, if `render` is true then the root console will be + * presented (this is mostly ignored.) + */ +void TCOD_sys_flush(bool render) { + if (!TCOD_ctx.root) { return; } + std::shared_ptr display = tcod::engine::get_display(); + if (display) { + display->present(TCOD_ctx.root); + } else { + if (render) { TCOD_sys_render(NULL, TCOD_ctx.root); } + } + sync_time(); +} + +static char TCOD_sys_get_vk(SDL_Keycode sdl_key) { + int i; + for (i = 0; i < NUM_VK_TO_C_ENTRIES; i++) { + if (vk_to_c[i].sdl_key == sdl_key) { + vk_to_c[i].sdl_key = 0; + return vk_to_c[i].tcod_key; + } + } + return 0; +} + +static void TCOD_sys_set_vk(SDL_Keycode sdl_key, char tcod_key) { + int i; + for (i = 0; i < NUM_VK_TO_C_ENTRIES; i++) { + if (vk_to_c[i].sdl_key == 0) { + vk_to_c[i].sdl_key = sdl_key; + vk_to_c[i].tcod_key = tcod_key; + break; + } + } +} + +static void TCOD_sys_convert_event(const SDL_Event *ev, TCOD_key_t *ret) { + const SDL_KeyboardEvent *kev=&ev->key; + /* SDL2 does not map keycodes and modifiers to characters, this is on the developer. + Presumably in order to avoid problems with different keyboard layouts, they + are expected to write their own key mapping editing code for the user. */ + if (SDLK_SCANCODE_MASK == (kev->keysym.sym & SDLK_SCANCODE_MASK)) + ret->c = 0; + else + ret->c = kev->keysym.sym; + if ( ( kev->keysym.mod & (KMOD_LCTRL|KMOD_RCTRL) ) != 0 ) { + /* when pressing CTRL-A, we don't get unicode for 'a', but unicode for CTRL-A = 1. Fix it */ + if ( kev->keysym.sym >= SDLK_a && kev->keysym.sym <= SDLK_z ) { + ret->c = 'a'+(kev->keysym.sym - SDLK_a); + } + } + if ( ev->type == SDL_KEYDOWN ) TCOD_sys_set_vk(kev->keysym.sym, ret->c); + else if (ev->type == SDL_KEYUP ) ret->c = TCOD_sys_get_vk(kev->keysym.sym); + switch(kev->keysym.sym) { + case SDLK_ESCAPE : ret->vk=TCODK_ESCAPE;break; + case SDLK_SPACE : ret->vk=TCODK_SPACE; break; + case SDLK_BACKSPACE : ret->vk=TCODK_BACKSPACE;break; + case SDLK_TAB : ret->vk=TCODK_TAB;break; + case SDLK_RETURN : ret->vk=TCODK_ENTER;break; + case SDLK_PAUSE : ret->vk=TCODK_PAUSE;break; + case SDLK_PAGEUP : ret->vk=TCODK_PAGEUP;break; + case SDLK_PAGEDOWN : ret->vk=TCODK_PAGEDOWN;break; + case SDLK_HOME : ret->vk=TCODK_HOME;break; + case SDLK_END : ret->vk=TCODK_END;break; + case SDLK_DELETE : ret->vk=TCODK_DELETE;break; + case SDLK_INSERT : ret->vk=TCODK_INSERT; break; + case SDLK_LALT : case SDLK_RALT : ret->vk=TCODK_ALT;break; + case SDLK_LCTRL : case SDLK_RCTRL : ret->vk=TCODK_CONTROL;break; + case SDLK_LSHIFT : case SDLK_RSHIFT : ret->vk=TCODK_SHIFT;break; + case SDLK_PRINTSCREEN : ret->vk=TCODK_PRINTSCREEN;break; + case SDLK_LEFT : ret->vk=TCODK_LEFT;break; + case SDLK_UP : ret->vk=TCODK_UP;break; + case SDLK_RIGHT : ret->vk=TCODK_RIGHT;break; + case SDLK_DOWN : ret->vk=TCODK_DOWN;break; + case SDLK_F1 : ret->vk=TCODK_F1;break; + case SDLK_F2 : ret->vk=TCODK_F2;break; + case SDLK_F3 : ret->vk=TCODK_F3;break; + case SDLK_F4 : ret->vk=TCODK_F4;break; + case SDLK_F5 : ret->vk=TCODK_F5;break; + case SDLK_F6 : ret->vk=TCODK_F6;break; + case SDLK_F7 : ret->vk=TCODK_F7;break; + case SDLK_F8 : ret->vk=TCODK_F8;break; + case SDLK_F9 : ret->vk=TCODK_F9;break; + case SDLK_F10 : ret->vk=TCODK_F10;break; + case SDLK_F11 : ret->vk=TCODK_F11;break; + case SDLK_F12 : ret->vk=TCODK_F12;break; + case SDLK_0 : ret->vk=TCODK_0;break; + case SDLK_1 : ret->vk=TCODK_1;break; + case SDLK_2 : ret->vk=TCODK_2;break; + case SDLK_3 : ret->vk=TCODK_3;break; + case SDLK_4 : ret->vk=TCODK_4;break; + case SDLK_5 : ret->vk=TCODK_5;break; + case SDLK_6 : ret->vk=TCODK_6;break; + case SDLK_7 : ret->vk=TCODK_7;break; + case SDLK_8 : ret->vk=TCODK_8;break; + case SDLK_9 : ret->vk=TCODK_9;break; + case SDLK_RGUI : ret->vk=TCODK_RWIN;break; + case SDLK_LGUI : ret->vk=TCODK_LWIN;break; + case SDLK_NUMLOCKCLEAR : ret->vk=TCODK_NUMLOCK;break; + case SDLK_KP_0 : ret->vk=TCODK_KP0;break; + case SDLK_KP_1 : ret->vk=TCODK_KP1;break; + case SDLK_KP_2 : ret->vk=TCODK_KP2;break; + case SDLK_KP_3 : ret->vk=TCODK_KP3;break; + case SDLK_KP_4 : ret->vk=TCODK_KP4;break; + case SDLK_KP_5 : ret->vk=TCODK_KP5;break; + case SDLK_KP_6 : ret->vk=TCODK_KP6;break; + case SDLK_KP_7 : ret->vk=TCODK_KP7;break; + case SDLK_KP_8 : ret->vk=TCODK_KP8;break; + case SDLK_KP_9 : ret->vk=TCODK_KP9;break; + case SDLK_KP_DIVIDE : ret->vk=TCODK_KPDIV;break; + case SDLK_KP_MULTIPLY : ret->vk=TCODK_KPMUL;break; + case SDLK_KP_PLUS : ret->vk=TCODK_KPADD;break; + case SDLK_KP_MINUS : ret->vk=TCODK_KPSUB;break; + case SDLK_KP_ENTER : ret->vk=TCODK_KPENTER;break; + case SDLK_KP_PERIOD : ret->vk=TCODK_KPDEC;break; + default : ret->vk=TCODK_CHAR; break; + } + +} +/** + * Parse an SDL key-up or key-down event and return the global key state. + */ +static TCOD_key_t TCOD_sys_SDLtoTCOD(const SDL_Event *ev, int flags) { + TCOD_key_t *ret = &TCOD_ctx.key_state; + ret->vk = TCODK_NONE; + ret->c = 0; + ret->pressed = 0; + switch (ev->type) { + case SDL_KEYUP: { + TCOD_key_t tmpkey; + switch(ev->key.keysym.sym) { + case SDLK_LALT: ret->lalt = 0; break; + case SDLK_RALT: ret->ralt = 0; break; + case SDLK_LCTRL: ret->lctrl = 0; break; + case SDLK_RCTRL: ret->rctrl = 0; break; + case SDLK_LSHIFT: ret->shift = 0; break; + case SDLK_RSHIFT: ret->shift = 0; break; + case SDLK_LGUI: ret->lmeta = 0; break; + case SDLK_RGUI: ret->rmeta = 0; break; + default: break; + } + TCOD_sys_convert_event(ev, &tmpkey); + key_status[tmpkey.vk] = false; + if (flags & TCOD_KEY_RELEASED) { + ret->vk = tmpkey.vk; + ret->c = tmpkey.c; + ret->pressed = 0; + } + break; + } + case SDL_KEYDOWN: { + TCOD_key_t tmpkey; + switch(ev->key.keysym.sym) { + case SDLK_LALT: ret->lalt = 1; break; + case SDLK_RALT: ret->ralt = 1; break; + case SDLK_LCTRL: ret->lctrl = 1; break; + case SDLK_RCTRL: ret->rctrl = 1; break; + case SDLK_LSHIFT: ret->shift = 1; break; + case SDLK_RSHIFT: ret->shift = 1; break; + case SDLK_LGUI: ret->lmeta = 1; break; + case SDLK_RGUI: ret->rmeta = 1; break; + default : break; + } + TCOD_sys_convert_event(ev, &tmpkey); + key_status[tmpkey.vk] = true; + if (flags & TCOD_KEY_PRESSED) { + ret->vk = tmpkey.vk; + ret->c = tmpkey.c; + ret->pressed = 1; + } + break; + } + } + return *ret; +} + +bool TCOD_sys_is_key_pressed(TCOD_keycode_t key) { + return key_status[key]; +} + +#ifdef TCOD_TOUCH_INPUT +static TCOD_touch_t tcod_touch={0}; + +static int TCOD_sys_get_touch_finger_index(SDL_FingerID fingerId) { + int i; + for (i = 0; i < tcod_touch.nfingers; i++) + if (tcod_touch.finger_ids[i] == fingerId) + return i; + if (i == tcod_touch.nfingers && i+1 <= MAX_TOUCH_FINGERS) { + tcod_touch.nfingers += 1; + tcod_touch.finger_ids[i] = fingerId; + return i; + } + return -1; +} +#endif + +void TCOD_sys_unproject_screen_coords(int sx, int sy, int *ssx, int *ssy) { + if (scale_data.dst_display_width != 0 ) { + *ssx = (scale_data.src_x0 + ((sx - scale_data.dst_offset_x) * scale_data.src_copy_width) / scale_data.dst_display_width); + *ssy = (scale_data.src_y0 + ((sy - scale_data.dst_offset_y) * scale_data.src_copy_width) / scale_data.dst_display_width); + } else { + *ssx=sx - TCOD_ctx.fullscreen_offsetx; + *ssy=sy - TCOD_ctx.fullscreen_offsety; + } +} + +void TCOD_sys_convert_console_to_screen_coords(int cx, int cy, int *sx, int *sy) { + *sx = scale_data.dst_offset_x + ((cx * TCOD_ctx.font_width - scale_data.src_x0) * scale_data.dst_display_width) / scale_data.src_copy_width; + *sy = scale_data.dst_offset_y + ((cy * TCOD_ctx.font_height - scale_data.src_y0) * scale_data.dst_display_height) / scale_data.src_copy_height; +} + +void TCOD_sys_convert_screen_to_console_coords(int sx, int sy, int *cx, int *cy) { + int ssx, ssy; + TCOD_sys_unproject_screen_coords(sx, sy, &ssx, &ssy); + *cx = ssx / TCOD_ctx.font_width; + *cy = ssy / TCOD_ctx.font_height; +} +/** The global libtcod mouse state. */ +static TCOD_mouse_t tcod_mouse={0,0,0,0,0,0,0,0,false,false,false,false,false,false,false,false}; +/** + * Parse an SDL_Event into `mouse` and return the relevant TCOD_event_t. + * + * Returns 0 if the event wasn't mouse related. + */ +static TCOD_event_t TCOD_sys_handle_mouse_event(const SDL_Event *ev, + TCOD_mouse_t *mouse) { + if (!ev || !mouse) { return TCOD_EVENT_NONE; } + switch(ev->type) { + case SDL_MOUSEMOTION: + TCOD_sys_unproject_screen_coords(ev->motion.x, ev->motion.y, + &mouse->x, &mouse->y); + if (scale_data.surface_width != 0) { + mouse->dx = (ev->motion.xrel * scale_data.src_proportionate_width + / scale_data.surface_width); + mouse->dy = (ev->motion.yrel * scale_data.src_proportionate_height + / scale_data.surface_height); + } + mouse->cx = mouse->x / TCOD_ctx.font_width; + mouse->cy = mouse->y / TCOD_ctx.font_height; + mouse->dcx = mouse->dx / TCOD_ctx.font_width; + mouse->dcy = mouse->dy / TCOD_ctx.font_height; + + return TCOD_EVENT_MOUSE_MOVE; + case SDL_MOUSEWHEEL: + if (ev->wheel.y < 0) { + mouse->wheel_down = true; + } else { + mouse->wheel_up = true; + } + return TCOD_EVENT_MOUSE_PRESS; + case SDL_MOUSEBUTTONDOWN: + switch (ev->button.button) { + case SDL_BUTTON_LEFT: mouse->lbutton = mousebl = true; break; + case SDL_BUTTON_MIDDLE: mouse->mbutton = mousebm = true; break; + case SDL_BUTTON_RIGHT: mouse->rbutton = mousebr = true; break; + default: break; + } + return TCOD_EVENT_MOUSE_PRESS; + case SDL_MOUSEBUTTONUP: + switch (ev->button.button) { + case SDL_BUTTON_LEFT: + if (mousebl) { mouse->lbutton_pressed = mouse_force_bl = true; } + mouse->lbutton = mousebl = false; + break; + case SDL_BUTTON_MIDDLE: + if (mousebm) { mouse->mbutton_pressed = mouse_force_bm = true; } + mouse->mbutton = mousebm = false; + break; + case SDL_BUTTON_RIGHT: + if (mousebr) { mouse->rbutton_pressed = mouse_force_br = true; } + mouse->rbutton = mousebr = false; + break; + } + return TCOD_EVENT_MOUSE_RELEASE; + default: + return TCOD_EVENT_NONE; + } +} +/** + * Parse an SDL_Event into `key` and return the relevant TCOD_event_t. + * + * Returns 0 if the event wasn't keyboard related. + */ +static TCOD_event_t TCOD_sys_handle_key_event(const SDL_Event *ev, + TCOD_key_t *key) { + if (!ev || !key) { return TCOD_EVENT_NONE; } + switch(ev->type) { + case SDL_KEYDOWN: + *key = TCOD_sys_SDLtoTCOD(ev, TCOD_KEY_PRESSED); + return TCOD_EVENT_KEY_PRESS; + case SDL_KEYUP: + *key = TCOD_sys_SDLtoTCOD(ev, TCOD_KEY_RELEASED); + return TCOD_EVENT_KEY_RELEASE; + case SDL_TEXTINPUT: { + *key = TCOD_ctx.key_state; + key->vk = TCODK_TEXT; + key->c = 0; + key->pressed = 1; + strncpy(key->text, ev->text.text, TCOD_KEY_TEXT_SIZE); + return TCOD_EVENT_KEY_PRESS; + } + break; + default: + return TCOD_EVENT_NONE; + } +} +static TCOD_event_t TCOD_sys_handle_event(SDL_Event *ev,TCOD_event_t eventMask, TCOD_key_t *key, TCOD_mouse_t *mouse) { + TCOD_event_t retMask = TCOD_EVENT_NONE; + /* printf("TCOD_sys_handle_event type=%04x\n", ev->type); */ + retMask = static_cast( + retMask | TCOD_sys_handle_mouse_event(ev, mouse) & eventMask); + retMask = static_cast( + retMask | TCOD_sys_handle_key_event(ev, key) & eventMask); + switch(ev->type) { +#ifdef TCOD_TOUCH_INPUT + /* + * Need to distinguish between: + * - Tap: Can be optionally delegated to a mouse press. + * - Touch and drag: Should affect scaling screen position. + * + */ + case SDL_FINGERDOWN : + case SDL_FINGERUP : + case SDL_FINGERMOTION : + { + int idx, mouse_touch_valid; + float xf, yf, screen_x, screen_y; + uint32_t ticks_taken = 0; + + /* Reset the global variable. */ + if (tcod_touch.nfingerspressed == 0) { + tcod_touch.nupdates = 0; + tcod_touch.nfingers = 0; + tcod_touch.ticks0 = SDL_GetTicks(); + } else + ticks_taken = SDL_GetTicks() - tcod_touch.ticks0; + + idx = TCOD_sys_get_touch_finger_index(ev->tfinger.fingerId); + if (idx == -1) { + TCOD_LOG(("ERROR: failed to allocate extra finger")); + break; + } + + /* Count the number of events contributing to an ongoing tracked touch (zeroed above in finger press). */ + tcod_touch.finger_id = ev->tfinger.fingerId; + tcod_touch.nupdates += 1; + + /* We only emulate mouse events when the first finger is the only one pressed. */ + if (SDL_FINGERDOWN == ev->type) { + tcod_touch.nfingerspressed += 1; + tcod_touch.fingerspressed[idx] = 1; + mouse_touch_valid = mouse_touch && tcod_touch.nfingerspressed == 1 && tcod_touch.fingerspressed[0]; + } else if (SDL_FINGERUP == ev->type) { + mouse_touch_valid = mouse_touch && tcod_touch.nfingerspressed == 1 && tcod_touch.fingerspressed[0]; + tcod_touch.nfingerspressed -= 1; + tcod_touch.fingerspressed[idx] = 0; + } else + mouse_touch_valid = mouse_touch && tcod_touch.nfingerspressed == 1 && tcod_touch.fingerspressed[0]; + + /* Coordinates are raw full screen positions. */ + screen_x = ev->tfinger.x * scale_data.surface_width; + screen_y = ev->tfinger.y * scale_data.surface_height; + xf = (float)(screen_x - scale_data.dst_offset_x) / scale_data.dst_display_width; + yf = (float)(screen_y - scale_data.dst_offset_y) / scale_data.dst_display_height; + tcod_touch.coords[idx][0] = scale_data.src_x0 + scale_data.src_copy_width * xf; + tcod_touch.coords[idx][1] = scale_data.src_y0 + scale_data.src_copy_height * yf; + tcod_touch.coords_delta[idx][0] = ev->tfinger.dx * scale_data.src_proportionate_width; + tcod_touch.coords_delta[idx][1] = ev->tfinger.dy * scale_data.src_proportionate_height; + + /* Console coordinates need to be mapped back from screen coordinates through scaling. */ + tcod_touch.consolecoords[idx][0] = tcod_touch.coords[idx][0] / TCOD_ctx.font_width; + tcod_touch.consolecoords[idx][1] = tcod_touch.coords[idx][1] / TCOD_ctx.font_height; + tcod_touch.consolecoords_delta[idx][0] = tcod_touch.coords_delta[idx][0] / TCOD_ctx.font_width; + tcod_touch.consolecoords_delta[idx][1] = tcod_touch.coords_delta[idx][1] / TCOD_ctx.font_height; + + if (SDL_FINGERDOWN == ev->type) { + // printf("SDL_FINGERDOWN [%d] ticks=%d", tcod_touch.nupdates, ticks_taken); + if ((TCOD_EVENT_FINGER_PRESS & eventMask) != 0) + retMask |= TCOD_EVENT_FINGER_PRESS; + + if (mouse_touch_valid && (TCOD_EVENT_MOUSE_PRESS & eventMask) != 0) { + mouse->lbutton=mousebl=true; + retMask |= TCOD_EVENT_MOUSE_PRESS; + } + } else if (SDL_FINGERUP == ev->type) { + // printf("SDL_FINGERUP [%d] ticks=%d", tcod_touch.nupdates, ticks_taken); + if ((TCOD_EVENT_FINGER_RELEASE & eventMask) != 0) + retMask |= TCOD_EVENT_FINGER_RELEASE; + + if (mouse_touch_valid && (TCOD_EVENT_MOUSE_RELEASE & eventMask) != 0) { + if (mousebl) + mouse->lbutton_pressed = mouse_force_bl=true; + mouse->lbutton = mousebl=false; + retMask |= TCOD_EVENT_MOUSE_RELEASE; + } + } else if (SDL_FINGERMOTION == ev->type) { + float scale_adjust = 1.0f, xc_shift = 0.0f, yc_shift = 0.0f; + + // printf("SDL_FINGERMOTION [%d] ticks=%d", tcod_touch.nupdates, ticks_taken); + if ((TCOD_EVENT_FINGER_MOVE & eventMask) != 0) + retMask |= TCOD_EVENT_FINGER_MOVE; + + if (mouse_touch_valid && (TCOD_EVENT_MOUSE_MOVE & eventMask) != 0) + retMask |= TCOD_EVENT_MOUSE_MOVE; + + if (tcod_touch.nfingerspressed == 1) { + /* One finger drag AKA drag to move. + * Ignore the first few move events that happen unhelpfully immediately after finger down. */ + if (tcod_touch.fingerspressed[0] && (tcod_touch.coords_delta[0][0] || tcod_touch.coords_delta[0][1]) && ticks_taken > 10) { + xc_shift = (float)tcod_touch.coords_delta[idx][0] / scale_data.surface_width; + yc_shift = (float)tcod_touch.coords_delta[idx][1] / scale_data.surface_height; + } + } else if (tcod_touch.nfingerspressed == 2) { + /* Two finger pinch AKA pinch to zoom + * Both fingers should stay exactly where they are on the full surface + * in order to manipulate the drag and zoom effect. */ + if (tcod_touch.fingerspressed[0] && tcod_touch.fingerspressed[1]) { + /* + * New algorithm + */ + int f0x0 = tcod_touch.coords[0][0]-tcod_touch.coords_delta[0][0], f0y0 = tcod_touch.coords[0][1]-tcod_touch.coords_delta[0][1]; + int f1x0 = tcod_touch.coords[1][0]-tcod_touch.coords_delta[1][0], f1y0 = tcod_touch.coords[1][1]-tcod_touch.coords_delta[1][1]; + int f0x1 = tcod_touch.coords[0][0], f0y1 = tcod_touch.coords[0][1]; + int f1x1 = tcod_touch.coords[1][0], f1y1 = tcod_touch.coords[1][1]; + float p0x = (f1x0 + f0x0)/2.0f, p0y = (f1y0 + f0y0)/2.0f; + float p1x = (f1x1 + f0x1)/2.0f, p1y = (f1y1 + f0y1)/2.0f; + float len_previous = sqrtf((float)(pow(f0x0-f1x0,2) + pow(f0y0-f1y0,2))); + float len_current = sqrt((float)(pow(f0x1-f1x1, 2) + pow(f0y1-f1y1,2))); + scale_adjust = len_current/len_previous; + xc_shift = ((p1x - p0x) / scale_data.surface_width); + yc_shift = ((p1y - p0y) / scale_data.surface_height); + } + } + + /* Bound the translations within the console area. */ + if (fabs(xc_shift) > 1e-3f) { + sdl->scale_xc -= xc_shift; /* Actual display shift is the inverted finger movement. */ + if (sdl->scale_xc + 1e-3f < 0.0f) + sdl->scale_xc = 0.0f; + if (sdl->scale_xc - 1e-3f > 1.0f) + sdl->scale_xc = 1.0f; + } + if (fabs(yc_shift) > 1e-3f) { + sdl->scale_yc -= yc_shift; /* Actual display shift is the inverted finger movement. */ + if (sdl->scale_yc + 1e-3f < 0.0f) + sdl->scale_yc = 0.0f; + if (sdl->scale_yc - 1e-3f > 1.0f) + sdl->scale_yc = 1.0f; + } + if (fabs(scale_adjust - 1.0f) > 1e-3f) + TCOD_sys_set_scale_factor(scale_factor * scale_adjust); + } + + /* We need to distinguish between handleable touch events, and short distinct mouse events. */ + if (ticks_taken > 400 || tcod_touch.nfingers > 1) { + // printf("DEF NOT MOUSE CODE[%d]", tcod_touch.nupdates); + mouse->cx = 0; + mouse->cy = 0; + mouse->dcx = 0; + mouse->dcy = 0; + } else if (mouse_touch_valid && (retMask & (TCOD_EVENT_MOUSE_PRESS|TCOD_EVENT_MOUSE_RELEASE|TCOD_EVENT_MOUSE_MOVE)) != 0) { + mouse->x = tcod_touch.coords[idx][0]; + mouse->y = tcod_touch.coords[idx][1]; + mouse->dx += tcod_touch.coords_delta[idx][0]; + mouse->dy += tcod_touch.coords_delta[idx][1]; + mouse->cx = tcod_touch.consolecoords[idx][0]; + mouse->cy = tcod_touch.consolecoords[idx][1]; + mouse->dcx = tcod_touch.consolecoords_delta[idx][0]; + mouse->dcy = tcod_touch.consolecoords_delta[idx][1]; + /* printf("CX,CY: %d,%d", mouse->cx,mouse->cy); */ + } + + break; + } +#endif + case SDL_QUIT : + TCOD_ctx.is_window_closed=true; + break; + case SDL_WINDOWEVENT : + /* At this point, there are some corner cases that need dealing with. So log this. */ + /* printf("SDL2 WINDOWEVENT: 0x%04x\n", ev->window.event); */ + switch (ev->window.event) { +#ifdef TCOD_ANDROID + case SDL_WINDOWEVENT_SIZE_CHANGED: + { + /* printf("SDL2 WINDOWEVENT (SDL_WINDOWEVENT_SIZE_CHANGED): 0x%04x w=%d h=%d\n", ev->window.event, ev->window.data1, ev->window.data2); */ + /* If the app is started while the device is locked, the screen will be in portrait mode. We need to rescale when it changes. */ + if (scale_data.surface_width != ev->window.data1 || scale_data.surface_height != ev->window.data1) + scale_data.force_recalc = 1; + break; + } +#endif + case SDL_WINDOWEVENT_ENTER: /**< Window has gained mouse focus */ + TCOD_ctx.app_has_mouse_focus=true; break; + case SDL_WINDOWEVENT_LEAVE: /**< Window has lost mouse focus */ + TCOD_ctx.app_has_mouse_focus=false; break; + case SDL_WINDOWEVENT_FOCUS_GAINED: + TCOD_ctx.app_is_active=true; break; + case SDL_WINDOWEVENT_FOCUS_LOST: + TCOD_ctx.app_is_active=false; break; + case SDL_WINDOWEVENT_EXPOSED: /**< Window has been returned to and needs a refresh. */ + TCOD_sys_render(NULL, TCOD_ctx.root); + break; +#ifdef NDEBUG_HMM + default: + TCOD_LOG(("SDL2 WINDOWEVENT (unknown): 0x%04x\n", ev->window.event)); + break; +#endif + } + break; + default : break; + } + return retMask; +} +/** + * Internal function containing code shared by TCOD_sys_wait_for_event + * and TCOD_sys_check_for_event + */ +static TCOD_event_t TCOD_sys_check_for_event_( + SDL_Event *ev, int eventMask, TCOD_key_t *key, TCOD_mouse_t *mouse) { + TCOD_event_t retMask = TCOD_EVENT_NONE; + if (eventMask == 0) { return TCOD_EVENT_NONE; } + tcod_mouse.lbutton_pressed = 0; + tcod_mouse.rbutton_pressed = 0; + tcod_mouse.mbutton_pressed = 0; + tcod_mouse.wheel_up = 0; + tcod_mouse.wheel_down = 0; + tcod_mouse.dx = 0; + tcod_mouse.dy = 0; + if (key) { + key->vk = TCODK_NONE; + key->c = 0; + key->text[0] = '\0'; + } + while (SDL_PollEvent(ev)) { + retMask = TCOD_sys_handle_event(ev, static_cast(eventMask), + key, &tcod_mouse); + if (retMask & TCOD_EVENT_KEY) { + break; /* only one key event per frame */ + } + } + if (mouse) { *mouse = tcod_mouse; } + if (key && !(eventMask & retMask & TCOD_EVENT_KEY)) { + key->vk = TCODK_NONE; + key->c = 0; + key->text[0] = '\0'; + } + return retMask; +} +/** + * Wait for a specific type of event. + * + * \param eventMask A bit-mask of TCOD_event_t flags. + * \param key Optional pointer to a TCOD_key_t struct. + * \param mouse Optional pointer to a TCOD_mouse_t struct. + * \param flush This should always be false. + * \return A TCOD_event_t flag showing which event was actually processed. + * + * This function also returns when the SDL window is being closed. + */ +TCOD_event_t TCOD_sys_wait_for_event(int eventMask, TCOD_key_t *key, + TCOD_mouse_t *mouse, bool flush) { + SDL_Event ev; + TCOD_event_t retMask = TCOD_EVENT_NONE; + if (eventMask == 0) { return TCOD_EVENT_NONE; } + if (flush) { + while (SDL_PollEvent(&ev)) { + TCOD_sys_check_for_event_(&ev, 0, NULL, NULL); + } + } + do { + SDL_WaitEvent(NULL); + retMask = TCOD_sys_check_for_event_(&ev, eventMask, key, mouse); + } while (ev.type != SDL_QUIT && (retMask & eventMask) == 0); + return retMask; +} +/** + * Check for a specific type of event. + * + * \param eventMask A bit-mask of TCOD_event_t flags. + * \param key Optional pointer to a TCOD_key_t struct. + * \param mouse Optional pointer to a TCOD_mouse_t struct. + * \param flush This should always be false. + * \return A TCOD_event_t flag showing which event was actually processed. + */ +TCOD_event_t TCOD_sys_check_for_event( + int eventMask, TCOD_key_t *key, TCOD_mouse_t *mouse) { + SDL_Event ev; + return TCOD_sys_check_for_event_(&ev, eventMask, key, mouse); +} +/** + * Return a copy of the current mouse state. + */ +TCOD_mouse_t TCOD_mouse_get_status(void) { + return tcod_mouse; +} + +/* classic keyboard functions (based on generic events) */ +/** + * Return immediately with a recently pressed key. + * + * \param flags A TCOD_event_t bit-field, for example: `TCOD_EVENT_KEY_PRESS` + * \return A TCOD_key_t struct with a recently pressed key. + * If no event exists then the `vk` attribute will be `TCODK_NONE` + */ +TCOD_key_t TCOD_sys_check_for_keypress(int flags) { + static TCOD_key_t noret={TCODK_NONE,0}; + + TCOD_key_t key; + TCOD_event_t ev = TCOD_sys_check_for_event(flags & TCOD_EVENT_KEY, &key, NULL); + + if ((ev & TCOD_EVENT_KEY) == 0) return noret; + + return key; +} +/** + * Wait for a key press event, then return it. + * + * \param flush If 1 then the event queue will be cleared before waiting for + * the next event. This should always be 0. + * \return A TCOD_key_t struct with the most recent key data. + */ +TCOD_key_t TCOD_sys_wait_for_keypress(bool flush) { + static TCOD_key_t noret={TCODK_NONE,0}; + + TCOD_key_t key; + TCOD_event_t ev = TCOD_sys_wait_for_event(TCOD_EVENT_KEY_PRESS, &key, NULL, flush); + + if ((ev & TCOD_EVENT_KEY_PRESS) == 0) return noret; + + return key; +} + + +void TCOD_sys_sleep_milli(uint32_t milliseconds) { + SDL_Delay(milliseconds); +} + +void *TCOD_sys_load_image(const char *filename) { + image_support_t *img=image_type; + while ( img->extension != NULL && !img->check_type(filename) ) img++; + if ( img->extension == NULL || img->read == NULL ) return NULL; /* unknown format */ + return img->read(filename); +} + +void TCOD_sys_get_image_size(const void *image, int *w, int *h) { + SDL_Surface *surf=(SDL_Surface *)image; + *w = surf->w; + *h = surf->h; +} + +TCOD_color_t TCOD_sys_get_image_pixel(const void *image,int x, int y) { + TCOD_color_t ret; + SDL_Surface *surf=(SDL_Surface *)image; + uint8_t bpp; + uint8_t*bits; + if ( x < 0 || y < 0 || x >= surf->w || y >= surf->h ) return TCOD_black; + bpp = surf->format->BytesPerPixel; + bits = ((uint8_t*)surf->pixels)+y*surf->pitch+x*bpp; + switch (bpp) { + case 1 : + { + if (surf->format->palette) { + SDL_Color col = surf->format->palette->colors[(*bits)]; + ret.r=col.r; + ret.g=col.g; + ret.b=col.b; + } else return TCOD_black; + } + break; + default : + ret.r = *((bits)+surf->format->Rshift/8); + ret.g = *((bits)+surf->format->Gshift/8); + ret.b = *((bits)+surf->format->Bshift/8); + break; + } + + return ret; +} + +int TCOD_sys_get_image_alpha(const void *image,int x, int y) { + SDL_Surface *surf=(SDL_Surface *)image; + uint8_t bpp; + uint8_t*bits; + if ( x < 0 || y < 0 || x >= surf->w || y >= surf->h ) return 255; + bpp = surf->format->BytesPerPixel; + if ( bpp != 4 ) return 255; + bits = ((uint8_t*)surf->pixels)+y*surf->pitch+x*bpp; + return *((bits)+surf->format->Ashift/8); +} + +uint32_t TCOD_sys_elapsed_milli(void) { + return (uint32_t)SDL_GetTicks(); +} + +float TCOD_sys_elapsed_seconds(void) { + static float div=1.0f/1000.0f; + return SDL_GetTicks()*div; +} + +void TCOD_sys_force_fullscreen_resolution(int width, int height) { + TCOD_ctx.fullscreen_width=width; + TCOD_ctx.fullscreen_height=height; +} + +void * TCOD_sys_create_bitmap(int width, int height, TCOD_color_t *buf) { + int x,y; + SDL_PixelFormat fmt; + SDL_Surface *bitmap; + memset(&fmt,0,sizeof(SDL_PixelFormat)); + if ( charmap != NULL ) { + fmt = *charmap->format; + } else { + fmt.BitsPerPixel=24; + fmt.Amask=0; + if ( SDL_BYTEORDER == SDL_LIL_ENDIAN ) { + fmt.Rmask=0x0000FF; + fmt.Gmask=0x00FF00; + fmt.Bmask=0xFF0000; + } else { + fmt.Rmask=0xFF0000; + fmt.Gmask=0x00FF00; + fmt.Bmask=0x0000FF; + } + } + bitmap=SDL_CreateRGBSurface(SDL_SWSURFACE,width,height,fmt.BitsPerPixel,fmt.Rmask,fmt.Gmask,fmt.Bmask,fmt.Amask); + for (x=0; x < width; x++) { + for (y=0; y < height; y++) { + SDL_Rect rect; + uint32_t col=SDL_MapRGB(&fmt,buf[x+y*width].r,buf[x+y*width].g,buf[x+y*width].b); + rect.x=x; + rect.y=y; + rect.w=1; + rect.h=1; + SDL_FillRect(bitmap,&rect,col); + } + } + return (void *)bitmap; +} + +void TCOD_sys_delete_bitmap(void *bitmap) { + SDL_FreeSurface((SDL_Surface *)bitmap); +} + +void TCOD_sys_set_fps(int val) { + if( val == 0 ) min_frame_length=0; + else min_frame_length=1000/val; +} + +void TCOD_sys_save_fps(void) { + min_frame_length_backup=min_frame_length; +} + +void TCOD_sys_restore_fps(void) { + min_frame_length=min_frame_length_backup; +} + +int TCOD_sys_get_fps(void) { + return fps; +} + +float TCOD_sys_get_last_frame_length(void) { + return last_frame_length; +} + +void TCOD_sys_get_char_size(int *w, int *h) { + *w = TCOD_ctx.font_width; + *h = TCOD_ctx.font_height; +} + +void TCOD_sys_get_current_resolution(int *w, int *h) { + /* be sure that SDL is initialized */ + TCOD_sys_startup(); + sdl->get_current_resolution(w,h); +} + +/* image stuff */ +bool TCOD_sys_check_magic_number(const char *filename, size_t size, uint8_t*data) { + uint8_t tmp[128]; + size_t i; + SDL_RWops *rwops = SDL_RWFromFile(filename, "rb"); + if (! rwops) return false; + if ( (i = rwops->read(rwops,tmp,size,1)) != 1 ) { + rwops->close(rwops); + return false; + } + rwops->close(rwops); + for (i=0; i< size; i++) if (tmp[i]!=data[i]) return false; + return true; +} + +void *TCOD_sys_get_SDL_window(void) { + return (void *)window; +} + +void *TCOD_sys_get_SDL_renderer(void) { + return (void *)renderer; +} + +/* mouse stuff */ +void TCOD_mouse_show_cursor(bool visible) { + SDL_ShowCursor(visible ? 1 : 0); +} + +bool TCOD_mouse_is_cursor_visible(void) { + return SDL_ShowCursor(-1) ? true : false; +} + +void TCOD_mouse_move(int x, int y) { + sdl->set_mouse_position(x,y); +} + +void TCOD_mouse_includes_touch(bool enable) { +#ifdef TCOD_TOUCH_INPUT + mouse_touch = enable; +#endif +} + +/*clipboard stuff */ +bool TCOD_sys_clipboard_set(const char *value) { + if (!has_startup) { return false; } + return sdl->set_clipboard_text(value); +} + +char *TCOD_sys_clipboard_get() { + if (!has_startup) { return ""; } + return sdl->get_clipboard_text(); +} + +bool TCOD_sys_read_file(const char *filename, unsigned char **buf, size_t *size) { + return sdl->file_read(filename,buf,size); +} + +bool TCOD_sys_file_exists(const char * filename, ...) { + char f[1024]; + va_list ap; + va_start(ap,filename); + vsprintf(f,filename,ap); + va_end(ap); + return sdl->file_exists(f); +} + +bool TCOD_sys_write_file(const char *filename, unsigned char *buf, uint32_t size) { + return sdl->file_write(filename,buf,size); +} + +/* Mark a rectangle of tiles dirty. */ +void TCOD_sys_set_dirty(int dx, int dy, int dw, int dh) { + int x, y; + struct TCOD_Console *dat = sdl->get_root_console_cache(); + if (!dat) return; + TCOD_IFNOT(dx < dat->w && dy < dat->h && dx + dw >= 0 && dy + dh >= 0) return; + TCOD_IFNOT(dx >= 0) { + dw += dx; + dx = 0; + } + TCOD_IFNOT(dy >= 0) { + dh += dy; + dy = 0; + } + TCOD_IFNOT(dx + dw <= dat->w) dw = dat->w - dx; + TCOD_IFNOT(dy + dh <= dat->h) dh = dat->h - dy; + + for (x = dx; x < dx + dw; ++x) { + for (y = dy; y < dy + dh; ++y) { + dat->ch_array[dat->w * y + x] = -1; + } + } +} + +/* Mark a character dirty by invalidating all occurrences of it in the software + renderer cache. Each character tile will be refreshed when the old buffer + is compared to the current buffer next render. + It's recommended that this method stays non-public. */ +void TCOD_sys_set_dirty_character_code(int ch) { + int i; + struct TCOD_Console *dat = sdl->get_root_console_cache(); + if (!dat) return; + for (i = 0; i < dat->w * dat->h; ++i) { + if (dat->ch_array[i] == ch) { + dat->ch_array[i] = -1; + } + } +} +/** + * Return the current tile index for a given character code. + */ +int TCOD_get_tileid_for_charcode_(int charcode) { + if (charcode >= 0 && charcode < TCOD_ctx.max_font_chars) { + return TCOD_ctx.ascii_to_tcod[charcode]; + } + return 0; +} +#endif /* TCOD_BARE */ diff --git a/tcod_sys/libtcod/src/sys_sdl_img_bmp.c b/tcod_sys/libtcod/src/libtcod/sys_sdl_img_bmp.cpp similarity index 95% rename from tcod_sys/libtcod/src/sys_sdl_img_bmp.c rename to tcod_sys/libtcod/src/libtcod/sys_sdl_img_bmp.cpp index 8256d1bb3..7ac830900 100644 --- a/tcod_sys/libtcod/src/sys_sdl_img_bmp.c +++ b/tcod_sys/libtcod/src/libtcod/sys_sdl_img_bmp.cpp @@ -1,70 +1,67 @@ -/* -* libtcod -* Copyright (c) 2008-2018 Jice & Mingos & rmtew -* All rights reserved. -* -* Redistribution and use in source and binary forms, with or without -* modification, are permitted provided that the following conditions are met: -* * Redistributions of source code must retain the above copyright -* notice, this list of conditions and the following disclaimer. -* * Redistributions in binary form must reproduce the above copyright -* notice, this list of conditions and the following disclaimer in the -* documentation and/or other materials provided with the distribution. -* * The name of Jice or Mingos may not be used to endorse or promote -* products derived from this software without specific prior written -* permission. -* -* THIS SOFTWARE IS PROVIDED BY JICE, MINGOS AND RMTEW ``AS IS'' AND ANY -* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED -* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE -* DISCLAIMED. IN NO EVENT SHALL JICE, MINGOS OR RMTEW BE LIABLE FOR ANY -* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES -* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; -* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND -* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS -* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. -*/ -#ifndef TCOD_BARE - -#include - -#include - -#include - -bool TCOD_sys_check_bmp(const char *filename) { - static uint8_t magic_number[]={0x42, 0x4d}; - return TCOD_sys_check_magic_number(filename,sizeof(magic_number),magic_number); -} - -SDL_Surface *TCOD_sys_read_bmp(const char *filename) { - SDL_Surface *ret=SDL_LoadBMP(filename); - if( !ret ) TCOD_fatal("SDL : %s",SDL_GetError()); - /* convert low color images to 24 bits */ - if ( ret->format->BytesPerPixel != 3 ) { - uint32_t rmask,gmask,bmask; - SDL_Surface * tmp; - if ( SDL_BYTEORDER == SDL_LIL_ENDIAN ) { - rmask=0xFF0000; - gmask=0x00FF00; - bmask=0x0000FF; - } else { - rmask=0x0000FF; - gmask=0x00FF00; - bmask=0xFF0000; - } - tmp=SDL_CreateRGBSurface(SDL_SWSURFACE,ret->w,ret->h,24, rmask, gmask, bmask, 0); - SDL_BlitSurface(ret,NULL,tmp,NULL); - SDL_FreeSurface(ret); - ret=tmp; - } - - return ret; -} - -void TCOD_sys_write_bmp(const SDL_Surface *surf, const char *filename) { - SDL_SaveBMP((SDL_Surface *)surf,filename); -} - -#endif /* TCOD_BARE */ +/* +* libtcod +* Copyright (c) 2008-2018 Jice & Mingos & rmtew +* All rights reserved. +* +* Redistribution and use in source and binary forms, with or without +* modification, are permitted provided that the following conditions are met: +* * Redistributions of source code must retain the above copyright +* notice, this list of conditions and the following disclaimer. +* * Redistributions in binary form must reproduce the above copyright +* notice, this list of conditions and the following disclaimer in the +* documentation and/or other materials provided with the distribution. +* * The name of Jice or Mingos may not be used to endorse or promote +* products derived from this software without specific prior written +* permission. +* +* THIS SOFTWARE IS PROVIDED BY JICE, MINGOS AND RMTEW ``AS IS'' AND ANY +* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED +* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE +* DISCLAIMED. IN NO EVENT SHALL JICE, MINGOS OR RMTEW BE LIABLE FOR ANY +* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES +* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; +* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND +* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS +* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +*/ +#ifndef TCOD_BARE +#include "sys.h" + +#include + +#include "libtcod_int.h" +bool TCOD_sys_check_bmp(const char *filename) { + static uint8_t magic_number[]={0x42, 0x4d}; + return TCOD_sys_check_magic_number(filename,sizeof(magic_number),magic_number); +} + +SDL_Surface *TCOD_sys_read_bmp(const char *filename) { + SDL_Surface *ret=SDL_LoadBMP(filename); + if( !ret ) TCOD_fatal("SDL : %s",SDL_GetError()); + /* convert low color images to 24 bits */ + if ( ret->format->BytesPerPixel != 3 ) { + uint32_t rmask,gmask,bmask; + SDL_Surface * tmp; + if ( SDL_BYTEORDER == SDL_LIL_ENDIAN ) { + rmask=0xFF0000; + gmask=0x00FF00; + bmask=0x0000FF; + } else { + rmask=0x0000FF; + gmask=0x00FF00; + bmask=0xFF0000; + } + tmp=SDL_CreateRGBSurface(SDL_SWSURFACE,ret->w,ret->h,24, rmask, gmask, bmask, 0); + SDL_BlitSurface(ret,NULL,tmp,NULL); + SDL_FreeSurface(ret); + ret=tmp; + } + + return ret; +} + +void TCOD_sys_write_bmp(const SDL_Surface *surf, const char *filename) { + SDL_SaveBMP((SDL_Surface *)surf,filename); +} +#endif /* TCOD_BARE */ diff --git a/tcod_sys/libtcod/src/sys_sdl_img_png.c b/tcod_sys/libtcod/src/libtcod/sys_sdl_img_png.cpp similarity index 94% rename from tcod_sys/libtcod/src/sys_sdl_img_png.c rename to tcod_sys/libtcod/src/libtcod/sys_sdl_img_png.cpp index 51a4a6886..f212b830e 100644 --- a/tcod_sys/libtcod/src/sys_sdl_img_png.c +++ b/tcod_sys/libtcod/src/libtcod/sys_sdl_img_png.cpp @@ -1,123 +1,120 @@ -/* -* libtcod -* Copyright (c) 2008-2018 Jice & Mingos & rmtew -* All rights reserved. -* -* Redistribution and use in source and binary forms, with or without -* modification, are permitted provided that the following conditions are met: -* * Redistributions of source code must retain the above copyright -* notice, this list of conditions and the following disclaimer. -* * Redistributions in binary form must reproduce the above copyright -* notice, this list of conditions and the following disclaimer in the -* documentation and/or other materials provided with the distribution. -* * The name of Jice or Mingos may not be used to endorse or promote -* products derived from this software without specific prior written -* permission. -* -* THIS SOFTWARE IS PROVIDED BY JICE, MINGOS AND RMTEW ``AS IS'' AND ANY -* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED -* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE -* DISCLAIMED. IN NO EVENT SHALL JICE, MINGOS OR RMTEW BE LIABLE FOR ANY -* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES -* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; -* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND -* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS -* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. -*/ -#ifndef TCOD_BARE - -#include - -#if !defined (__HAIKU__) && !defined (__ANDROID__) -#include -#include -#endif -#include - -#include "png/lodepng.h" - -#include - -bool TCOD_sys_check_png(const char *filename) { - static uint8_t magic_number[]={137, 80, 78, 71, 13, 10, 26, 10}; - return TCOD_sys_check_magic_number(filename,sizeof(magic_number),magic_number); -} - -SDL_Surface *TCOD_sys_read_png(const char *filename) { - unsigned error; - unsigned char* image; - unsigned width, height, y, bpp; - unsigned char* png; - size_t pngsize; - LodePNGState state; - SDL_Surface *bitmap; - unsigned char *source; - unsigned int rowsize; - - lodepng_state_init(&state); - /*optionally customize the state*/ - if (!TCOD_sys_read_file(filename,&png,&pngsize)) return NULL; - - lodepng_inspect(&width,&height,&state, png, pngsize); - bpp=lodepng_get_bpp(&state.info_png.color); - - if ( bpp == 24 ) { - /* don't convert to 32 bits because libtcod's 24bits renderer is faster */ - state.info_raw.colortype=LCT_RGB; - } else if ( bpp != 24 && bpp != 32 ) { - /* paletted png. convert to 24 bits */ - state.info_raw.colortype=LCT_RGB; - state.info_raw.bitdepth=8; - bpp=24; - } - error = lodepng_decode(&image, &width, &height, &state, png, pngsize); - free(png); - if(error) { - printf("error %u: %s\n", error, lodepng_error_text(error)); - lodepng_state_cleanup(&state); - return NULL; - } - - /* create the SDL surface */ - bitmap=TCOD_sys_get_surface(width,height,bpp==32); - source=image; - rowsize=width*bpp/8; - for (y=0; y< height; y++ ) { - uint8_t*row_pointer=(uint8_t*)(bitmap->pixels) + y * bitmap->pitch; - memcpy(row_pointer,source,rowsize); - source+=rowsize; - } - - lodepng_state_cleanup(&state); - free(image); - return bitmap; -} - -void TCOD_sys_write_png(const SDL_Surface *surf, const char *filename) { - unsigned char *image, *dest=(unsigned char *)malloc(surf->h*surf->w*3*sizeof(char)); - int x,y; - unsigned char *buf; - size_t size; - int error; - /* SDL uses 32bits format without alpha layer for screen. convert it to 24 bits */ - image=dest; - for (y=0; y< surf->h; y++ ) { - for (x=0; x < surf->w; x++ ) { - uint8_t*pixel=(uint8_t*)(surf->pixels) + y * surf->pitch + x * surf->format->BytesPerPixel; - *dest++=*((pixel)+surf->format->Rshift/8); - *dest++=*((pixel)+surf->format->Gshift/8); - *dest++=*((pixel)+surf->format->Bshift/8); - } - } - error=lodepng_encode_memory(&buf,&size,image,surf->w,surf->h,LCT_RGB,8); - free(image); - if ( ! error ) { - TCOD_sys_write_file(filename,buf,(uint32_t)size); - free(buf); - } else { - printf("error %u: %s\n", error, lodepng_error_text(error)); - } -} - -#endif /* TCOD_BARE */ +/* +* libtcod +* Copyright (c) 2008-2018 Jice & Mingos & rmtew +* All rights reserved. +* +* Redistribution and use in source and binary forms, with or without +* modification, are permitted provided that the following conditions are met: +* * Redistributions of source code must retain the above copyright +* notice, this list of conditions and the following disclaimer. +* * Redistributions in binary form must reproduce the above copyright +* notice, this list of conditions and the following disclaimer in the +* documentation and/or other materials provided with the distribution. +* * The name of Jice or Mingos may not be used to endorse or promote +* products derived from this software without specific prior written +* permission. +* +* THIS SOFTWARE IS PROVIDED BY JICE, MINGOS AND RMTEW ``AS IS'' AND ANY +* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED +* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE +* DISCLAIMED. IN NO EVENT SHALL JICE, MINGOS OR RMTEW BE LIABLE FOR ANY +* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES +* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; +* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND +* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS +* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +*/ +#ifndef TCOD_BARE +#include "sys.h" + +#if !defined (__HAIKU__) && !defined (__ANDROID__) +#include +#include +#endif +#include + +#include "../vendor/lodepng.h" + +#include "libtcod_int.h" +bool TCOD_sys_check_png(const char *filename) { + static uint8_t magic_number[]={137, 80, 78, 71, 13, 10, 26, 10}; + return TCOD_sys_check_magic_number(filename,sizeof(magic_number),magic_number); +} + +SDL_Surface *TCOD_sys_read_png(const char *filename) { + unsigned error; + unsigned char* image; + unsigned width, height, y, bpp; + unsigned char* png; + size_t pngsize; + LodePNGState state; + SDL_Surface *bitmap; + unsigned char *source; + unsigned int rowsize; + + lodepng_state_init(&state); + /*optionally customize the state*/ + if (!TCOD_sys_read_file(filename,&png,&pngsize)) return NULL; + + lodepng_inspect(&width,&height,&state, png, pngsize); + bpp=lodepng_get_bpp(&state.info_png.color); + + if ( bpp == 24 ) { + /* don't convert to 32 bits because libtcod's 24bits renderer is faster */ + state.info_raw.colortype=LCT_RGB; + } else if ( bpp != 24 && bpp != 32 ) { + /* paletted png. convert to 24 bits */ + state.info_raw.colortype=LCT_RGB; + state.info_raw.bitdepth=8; + bpp=24; + } + error = lodepng_decode(&image, &width, &height, &state, png, pngsize); + free(png); + if(error) { + printf("error %u: %s\n", error, lodepng_error_text(error)); + lodepng_state_cleanup(&state); + return NULL; + } + + /* create the SDL surface */ + bitmap=(SDL_Surface*)TCOD_sys_get_surface(width,height,bpp==32); + source=image; + rowsize=width*bpp/8; + for (y=0; y< height; y++ ) { + uint8_t*row_pointer=(uint8_t*)(bitmap->pixels) + y * bitmap->pitch; + memcpy(row_pointer,source,rowsize); + source+=rowsize; + } + + lodepng_state_cleanup(&state); + free(image); + return bitmap; +} + +void TCOD_sys_write_png(const SDL_Surface *surf, const char *filename) { + unsigned char *image, *dest=(unsigned char *)malloc(surf->h*surf->w*3*sizeof(char)); + int x,y; + unsigned char *buf; + size_t size; + int error; + /* SDL uses 32bits format without alpha layer for screen. convert it to 24 bits */ + image=dest; + for (y=0; y< surf->h; y++ ) { + for (x=0; x < surf->w; x++ ) { + uint8_t*pixel=(uint8_t*)(surf->pixels) + y * surf->pitch + x * surf->format->BytesPerPixel; + *dest++=*((pixel)+surf->format->Rshift/8); + *dest++=*((pixel)+surf->format->Gshift/8); + *dest++=*((pixel)+surf->format->Bshift/8); + } + } + error=lodepng_encode_memory(&buf,&size,image,surf->w,surf->h,LCT_RGB,8); + free(image); + if ( ! error ) { + TCOD_sys_write_file(filename,buf,(uint32_t)size); + free(buf); + } else { + printf("error %u: %s\n", error, lodepng_error_text(error)); + } +} +#endif /* TCOD_BARE */ diff --git a/tcod_sys/libtcod/src/libtcod/tileset/observer.cpp b/tcod_sys/libtcod/src/libtcod/tileset/observer.cpp new file mode 100644 index 000000000..ddb29ee4e --- /dev/null +++ b/tcod_sys/libtcod/src/libtcod/tileset/observer.cpp @@ -0,0 +1,6 @@ + +#include "observer.h" +namespace tcod { +namespace tileset { +} // namespace tileset +} // namespace tcod diff --git a/tcod_sys/libtcod/src/libtcod/tileset/observer.h b/tcod_sys/libtcod/src/libtcod/tileset/observer.h new file mode 100644 index 000000000..135e5f27b --- /dev/null +++ b/tcod_sys/libtcod/src/libtcod/tileset/observer.h @@ -0,0 +1,89 @@ + +#ifndef LIBTCOD_TILESET_OBSERVER_H_ +#define LIBTCOD_TILESET_OBSERVER_H_ +#include "../portability.h" + +#ifdef __cplusplus +#include +#include +#include +#include +#endif + +#include "tile.h" +#include "tileset.h" +#ifdef __cplusplus +namespace tcod { +namespace tileset { +class Tileset; +class TilesetObserver; +typedef std::vector> IdTileRefPairVector_; +class TilesetObserver { + public: + TilesetObserver() = default; + + TilesetObserver(std::shared_ptr subject) + { + if (!subject) { + throw std::invalid_argument("tileset cannot be nullptr."); + } + observe(subject); + } + + TilesetObserver(TilesetObserver&& rhs) + : TilesetObserver(rhs.tileset_) + {} + TilesetObserver& operator=(TilesetObserver&& rhs) + { + if (this != &rhs) { + observe(rhs.tileset_); + } + return *this; + } + TilesetObserver(const TilesetObserver& rhs) + : TilesetObserver(rhs.tileset_) + {} + TilesetObserver& operator=(const TilesetObserver& rhs) + { + if (this != &rhs) { + observe(rhs.tileset_); + } + return *this; + } + virtual ~TilesetObserver() { + unobserve(); + } + /** + * Called on Tileset state changes. + * + * `changes` is a vector of index,Tile pairs. + * + * The Tileset may have been resized. + */ + virtual void on_tileset_changed( + const std::vector> &changes) + {} + std::shared_ptr& get_tileset() + { + return tileset_; + } + protected: + std::shared_ptr tileset_; + private: + void observe(std::shared_ptr subject) + { + unobserve(); + tileset_ = subject; + subject->observers_.emplace_back(this); + } + void unobserve() { + if (!tileset_) { return; } + auto& observers = tileset_->observers_; + observers.erase(std::find(observers.begin(), observers.end(), this)); + tileset_ = nullptr; + } +}; +} // namespace tileset +} // namespace tcod +#endif /* __cplusplus */ +#endif /* LIBTCOD_TILESET_OBSERVER_H_ */ diff --git a/tcod_sys/libtcod/src/libtcod/tileset/tile.cpp b/tcod_sys/libtcod/src/libtcod/tileset/tile.cpp new file mode 100644 index 000000000..8bba22974 --- /dev/null +++ b/tcod_sys/libtcod/src/libtcod/tileset/tile.cpp @@ -0,0 +1,2 @@ + +#include "tile.h" diff --git a/tcod_sys/libtcod/src/libtcod/tileset/tile.h b/tcod_sys/libtcod/src/libtcod/tileset/tile.h new file mode 100644 index 000000000..4705bb3e7 --- /dev/null +++ b/tcod_sys/libtcod/src/libtcod/tileset/tile.h @@ -0,0 +1,39 @@ + +#ifndef LIBTCOD_TILESET_TILE_H_ +#define LIBTCOD_TILESET_TILE_H_ +#include +#ifdef __cplusplus +#include +#include +#endif + +#include "../portability.h" +#include "../color/canvas.h" +#ifdef __cplusplus +namespace tcod { +namespace tileset { +using image::Image; + +class Tile { + public: + Tile(); + explicit Tile(int codepoint, const Image &image) + : codepoint(codepoint), image_(image) + {} + explicit Tile(int codepoint, int width, int height) + : Tile(codepoint, Image(width, height)) + {} + + int width(void) const { return image_.width(); } + int height(void) const { return image_.height(); } + Image get_image() const { + return image_; + } + const int codepoint; + private: + Image image_; +}; +} // namespace tileset +} // namespace tcod +#endif // __cplusplus +#endif // LIBTCOD_TILESET_TILE_H_ diff --git a/tcod_sys/libtcod/src/libtcod/tileset/tileset.cpp b/tcod_sys/libtcod/src/libtcod/tileset/tileset.cpp new file mode 100644 index 000000000..8be361132 --- /dev/null +++ b/tcod_sys/libtcod/src/libtcod/tileset/tileset.cpp @@ -0,0 +1,22 @@ + +#include "tileset.h" + +#include +#include + +#include "observer.h" +#include "tilesheet.h" +#include "../libtcod_int.h" + +namespace tcod { +namespace tileset { +extern "C" { +Tileset* TCOD_tileset_new(int tile_width, int tile_height) { + return new Tileset(tile_width, tile_height); +} +void TCOD_tileset_delete(Tileset* tileset) { + if (tileset) { delete tileset; } +} +} // extern "C" +} // namespace tileset +} // namespace tcod diff --git a/tcod_sys/libtcod/src/libtcod/tileset/tileset.h b/tcod_sys/libtcod/src/libtcod/tileset/tileset.h new file mode 100644 index 000000000..1e672741e --- /dev/null +++ b/tcod_sys/libtcod/src/libtcod/tileset/tileset.h @@ -0,0 +1,125 @@ + +#ifndef LIBTCOD_TILESET_TILESET_H_ +#define LIBTCOD_TILESET_TILESET_H_ +#ifdef __cplusplus +#include +#include +#include +#include +#endif + +#include "../portability.h" +#include "tile.h" +#ifdef __cplusplus +namespace tcod { +namespace tileset { +/** + * This is a tile-set resource. + */ +class Tileset { + public: + friend class TilesetObserver; + explicit Tileset(int tile_width, int tile_height): + tile_width_(std::max(0, tile_width)), + tile_height_(std::max(0, tile_height)), + /* The tile at zero is always blank. */ + tiles_{Tile(0, tile_width_, tile_height_)} + {} + + Tileset(Tileset&&) = default; + Tileset& operator=(Tileset&&) = default; + Tileset(const Tileset&) = default; + Tileset& operator=(const Tileset&) = default; + + ~Tileset() = default; + /** + * Assign `codepoint` to a new `tile` for this Tileset. + * + * `codepoint` is a Unicode character. + */ + int set_tile(int codepoint, const Image &image) + { + return set_tile(Tile(codepoint, image)); + } + int set_tile(const Tile& tile) + { + if (VerifyTile(tile) < 0) { return -1; } + if (tile.codepoint >= static_cast(character_map_.size())) { + character_map_.resize(tile.codepoint + 1, -1); + } + character_map_[tile.codepoint] = tiles_.size(); + tiles_.push_back(tile); + return 0; + } + /** Return the width of each tile in this Tileset */ + int get_tile_width() const { return tile_width_; } + /** Return the height of each tile in this Tileset */ + int get_tile_height() const { return tile_height_; } + /** + * Return a reference to this objects tile vector. + */ + const std::vector& get_tiles() const { + return tiles_; + } + const std::vector& get_character_map() const + { + return character_map_; + } + private: + /** + * Return the tile ID for a specific code-point. + * + * If the code-point is not assigned to a tile then this will return -1. + */ + int GetTileIndexForCharacter(int codepoint) const { + if (0 <= codepoint && + codepoint < static_cast(character_map_.size())) { + return character_map_[codepoint]; + } + return -1; + } + /** + * Return 0 if this tile will fit in this tile-set. + * + * Return -1 if it can't. + */ + int VerifyTile(const Tile &tile) const { + if (tile.width() == tile_width_ && tile.height() == tile_height_) { + return 0; + } + return -1; + } + /** Width and height of each tile in pixels. */ + int tile_width_; + int tile_height_; + /** An array of tiles. */ + std::vector tiles_; + int tiles_last_known_capacity; + /** Mapping of Unicode code-points to the tiles of this tile-set. */ + std::vector character_map_; + std::vector observers_; +}; +#endif /* __cplusplus */ +#ifdef __cplusplus +/** + * C API alias to the tcod::Tileset class. + */ +typedef Tileset TCOD_Tileset; +extern "C" { +#else +typedef struct TCOD_Tileset TCOD_Tileset; +#endif +/** + * Create a new tile-set with the given tile size. + */ +TCOD_Tileset *TCOD_tileset_new(int tile_width, int tile_height); +/** + * Delete a tile-set. + */ +void TCOD_tileset_delete(TCOD_Tileset *tileset); +#ifdef __cplusplus +} // extern "C" +} // namespace tileset +} // namespace tcod +#endif +#endif /* LIBTCOD_TILESET_TILESET_H_ */ diff --git a/tcod_sys/libtcod/src/libtcod/tileset/tilesheet.cpp b/tcod_sys/libtcod/src/libtcod/tileset/tilesheet.cpp new file mode 100644 index 000000000..ad904aed7 --- /dev/null +++ b/tcod_sys/libtcod/src/libtcod/tileset/tilesheet.cpp @@ -0,0 +1,27 @@ + +#include "tilesheet.h" + +#include "../../vendor/lodepng.h" +#include "../color/canvas.h" +namespace tcod { +namespace tileset { +Tilesheet LoadTilesheet(const std::string& filename, + const TilesheetLayout& layout) { + unsigned img_width, img_height; + std::vector img_data; + if (lodepng::decode(img_data, img_width, img_height, filename)) { + return Tilesheet(); + } + Image canvas(img_width, img_height); + std::vector::iterator img_iter = img_data.begin(); + for (int y = 0; y < canvas.height(); ++y) { + for (int x = 0; y < canvas.width(); ++x) { + canvas.at(x, y) = ColorRGBA{img_iter[0], img_iter[1], + img_iter[2], img_iter[3]}; + img_iter += 4; + } + } + return Tilesheet(canvas, layout); +} +} // namespace tileset +} // namespace tcod diff --git a/tcod_sys/libtcod/src/libtcod/tileset/tilesheet.h b/tcod_sys/libtcod/src/libtcod/tileset/tilesheet.h new file mode 100644 index 000000000..ae348dd24 --- /dev/null +++ b/tcod_sys/libtcod/src/libtcod/tileset/tilesheet.h @@ -0,0 +1,135 @@ + +#ifndef LIBTCOD_TILESET_TILESHEET_H_ +#define LIBTCOD_TILESET_TILESHEET_H_ +#ifdef __cplusplus +#include +#include +#endif // __cplusplus + +#include "../color/canvas.h" +#include "tile.h" +#ifdef __cplusplus +namespace tcod { +namespace tileset { +using image::Image; +/** + * The layout of tiles on a tile-sheet. + */ +struct TilesheetLayout { + int tile_width; + int tile_height; + int columns; + int rows; +}; +class Tilesheet { + public: + Tilesheet() = default; + explicit Tilesheet(const Image& canvas, const TilesheetLayout& layout) + : canvas_(canvas), layout_(layout) { + fill_layout(); + } + explicit Tilesheet(const Image& canvas, const std::pair& layout) + : Tilesheet(canvas, {0, 0, layout.first, layout.second}) + {} + Tilesheet(Tilesheet&&) = default; + Tilesheet& operator=(Tilesheet&&) = default; + Tilesheet(const Tilesheet&) = default; + Tilesheet& operator=(const Tilesheet&) = default; + /** + * Return the Tile at `x` and `y`. + */ + Image get_tile(int x, int y) const { + if (!(0 <= x && x < layout_.columns && 0 <= y && y < layout_.rows)) { + throw std::out_of_range("Tile not in Tilesheet layout."); + } + return new_tile(x * layout_.tile_width, y * layout_.tile_height, + layout_.tile_width, layout_.tile_height); + } + /** + * Return the Tile at `n`. + */ + Image get_tile(int n) const { + return get_tile(n % layout_.columns, n / layout_.columns); + } + int get_tile_width() const { + return layout_.tile_width; + } + int get_tile_height() const { + return layout_.tile_height; + } + int get_columns() const { + return layout_.columns; + } + int get_rows() const { + return layout_.rows; + } + int count() const { + return get_columns() * get_rows(); + } + private: + /** + * Automatically fill values which are 0 in layout_. + */ + void fill_layout() { + // Find undefined columns/rows from tile size and canvas_ size. + if (layout_.columns == 0 && layout_.tile_width > 0) { + layout_.columns = canvas_.width() / layout_.tile_width; + } + if (layout_.rows == 0 && layout_.tile_height > 0) { + layout_.rows = canvas_.height() / layout_.tile_height; + } + // Find undefined tile width/height from columns/rows and canvas_ size. + if (layout_.tile_width == 0 && layout_.columns > 0) { + layout_.tile_width = canvas_.width() / layout_.columns; + } + if (layout_.tile_height == 0 && layout_.rows > 0) { + layout_.tile_height = canvas_.height() / layout_.rows; + } + if (!layout_.columns || !layout_.rows) { + throw std::logic_error("Tilesheet layout is non-valid."); + } + } + /** + * Return a new Tile from the given region on the Tilesheet. + */ + Image new_tile(int x, int y, int width, int height) const { + Image tile{width, height}; + for (int pixel_y = 0; pixel_y < height; ++pixel_y) { + for (int pixel_x = 0; pixel_x < width; ++pixel_x) { + tile.at(pixel_x, pixel_y) = canvas_.at(x + pixel_x, + y + pixel_y); + } + } + bool is_colored = false; + for (const ColorRGBA& pixel : tile) { + if (pixel.r != pixel.g || pixel.r != pixel.b) { + is_colored = true; + break; + } + } + bool has_alpha = false; + for (ColorRGBA& pixel : tile) { + if (pixel.a != 0xff) { + has_alpha = true; + break; + } + } + if (!is_colored && !has_alpha) { + for (ColorRGBA& pixel : tile) { + pixel.a = pixel.r; + pixel.r = pixel.g = pixel.b = 0xff; + } + } + return tile; + } + Image canvas_; + TilesheetLayout layout_; +}; +/** + * Load a Tilesheet from an image file. + */ +Tilesheet LoadTilesheet(const std::string &filename); +} // namespace tileset +} // namespace tcod +#endif // __cplusplus +#endif /* LIBTCOD_TILESET_TILESHEET_H_ */ diff --git a/tcod_sys/libtcod/include/tree.h b/tcod_sys/libtcod/src/libtcod/tree.h similarity index 98% rename from tcod_sys/libtcod/include/tree.h rename to tcod_sys/libtcod/src/libtcod/tree.h index 5d3fafd10..d4d66f656 100644 --- a/tcod_sys/libtcod/include/tree.h +++ b/tcod_sys/libtcod/src/libtcod/tree.h @@ -28,7 +28,7 @@ #ifndef _TCOD_TREE_H #define _TCOD_TREE_H -#include "libtcod_portability.h" +#include "portability.h" #ifdef __cplusplus extern "C" { diff --git a/tcod_sys/libtcod/include/tree.hpp b/tcod_sys/libtcod/src/libtcod/tree.hpp similarity index 100% rename from tcod_sys/libtcod/include/tree.hpp rename to tcod_sys/libtcod/src/libtcod/tree.hpp diff --git a/tcod_sys/libtcod/src/tree_c.c b/tcod_sys/libtcod/src/libtcod/tree_c.c similarity index 96% rename from tcod_sys/libtcod/src/tree_c.c rename to tcod_sys/libtcod/src/libtcod/tree_c.c index c8bf96e59..485ee8a45 100644 --- a/tcod_sys/libtcod/src/tree_c.c +++ b/tcod_sys/libtcod/src/libtcod/tree_c.c @@ -1,45 +1,45 @@ -/* -* libtcod -* Copyright (c) 2008-2018 Jice & Mingos & rmtew -* All rights reserved. -* -* Redistribution and use in source and binary forms, with or without -* modification, are permitted provided that the following conditions are met: -* * Redistributions of source code must retain the above copyright -* notice, this list of conditions and the following disclaimer. -* * Redistributions in binary form must reproduce the above copyright -* notice, this list of conditions and the following disclaimer in the -* documentation and/or other materials provided with the distribution. -* * The name of Jice or Mingos may not be used to endorse or promote -* products derived from this software without specific prior written -* permission. -* -* THIS SOFTWARE IS PROVIDED BY JICE, MINGOS AND RMTEW ``AS IS'' AND ANY -* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED -* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE -* DISCLAIMED. IN NO EVENT SHALL JICE, MINGOS OR RMTEW BE LIABLE FOR ANY -* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES -* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; -* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND -* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS -* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. -*/ -#include - -#include - -TCOD_tree_t *TCOD_tree_new(void) { - return (TCOD_tree_t *)calloc(1,sizeof(TCOD_tree_t)); -} - -void TCOD_tree_add_son(TCOD_tree_t *node, TCOD_tree_t *son) { - TCOD_tree_t *lastson = node->sons; - son->father=node; - while ( lastson && lastson->next ) lastson=lastson->next; - if ( lastson ) { - lastson->next=son; - } else { - node->sons=son; - } -} +/* +* libtcod +* Copyright (c) 2008-2018 Jice & Mingos & rmtew +* All rights reserved. +* +* Redistribution and use in source and binary forms, with or without +* modification, are permitted provided that the following conditions are met: +* * Redistributions of source code must retain the above copyright +* notice, this list of conditions and the following disclaimer. +* * Redistributions in binary form must reproduce the above copyright +* notice, this list of conditions and the following disclaimer in the +* documentation and/or other materials provided with the distribution. +* * The name of Jice or Mingos may not be used to endorse or promote +* products derived from this software without specific prior written +* permission. +* +* THIS SOFTWARE IS PROVIDED BY JICE, MINGOS AND RMTEW ``AS IS'' AND ANY +* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED +* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE +* DISCLAIMED. IN NO EVENT SHALL JICE, MINGOS OR RMTEW BE LIABLE FOR ANY +* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES +* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; +* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND +* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS +* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +*/ +#include "tree.h" + +#include + +TCOD_tree_t *TCOD_tree_new(void) { + return (TCOD_tree_t *)calloc(1,sizeof(TCOD_tree_t)); +} + +void TCOD_tree_add_son(TCOD_tree_t *node, TCOD_tree_t *son) { + TCOD_tree_t *lastson = node->sons; + son->father=node; + while ( lastson && lastson->next ) lastson=lastson->next; + if ( lastson ) { + lastson->next=son; + } else { + node->sons=son; + } +} diff --git a/tcod_sys/libtcod/src/txtfield.cpp b/tcod_sys/libtcod/src/libtcod/txtfield.cpp similarity index 96% rename from tcod_sys/libtcod/src/txtfield.cpp rename to tcod_sys/libtcod/src/libtcod/txtfield.cpp index a2966b86e..dd5776c54 100644 --- a/tcod_sys/libtcod/src/txtfield.cpp +++ b/tcod_sys/libtcod/src/libtcod/txtfield.cpp @@ -1,74 +1,74 @@ -/* -* libtcod -* Copyright (c) 2008-2018 Jice & Mingos & rmtew -* All rights reserved. -* -* Redistribution and use in source and binary forms, with or without -* modification, are permitted provided that the following conditions are met: -* * Redistributions of source code must retain the above copyright -* notice, this list of conditions and the following disclaimer. -* * Redistributions in binary form must reproduce the above copyright -* notice, this list of conditions and the following disclaimer in the -* documentation and/or other materials provided with the distribution. -* * The name of Jice or Mingos may not be used to endorse or promote -* products derived from this software without specific prior written -* permission. -* -* THIS SOFTWARE IS PROVIDED BY JICE, MINGOS AND RMTEW ``AS IS'' AND ANY -* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED -* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE -* DISCLAIMED. IN NO EVENT SHALL JICE, MINGOS OR RMTEW BE LIABLE FOR ANY -* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES -* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; -* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND -* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS -* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. -*/ -#include - -#ifdef TCOD_CONSOLE_SUPPORT - -TCODText::TCODText(int x, int y, int w, int h, int max_chars){ - data=TCOD_text_init(x,y,w,h,max_chars); -} - -TCODText::TCODText(int w, int h, int max_chars){ - data=TCOD_text_init2(w,h,max_chars); -} - -TCODText::~TCODText(){ - TCOD_text_delete(data); -} - -void TCODText::setPos(int x, int y) { - TCOD_text_set_pos(data,x,y); -} - -void TCODText::setProperties(int cursor_char, int blink_interval, const char * prompt, int tab_size){ - TCOD_text_set_properties(data,cursor_char,blink_interval,prompt,tab_size); -} - -void TCODText::setColors(TCODColor fore, TCODColor back, float back_transparency){ - TCOD_color_t foreground = {fore.r,fore.g,fore.b}; - TCOD_color_t background = {back.r,back.g,back.b}; - TCOD_text_set_colors(data,foreground,background,back_transparency); -} - -bool TCODText::update(TCOD_key_t key){ - return TCOD_text_update(data,key) != 0; -} - -void TCODText::render(TCODConsole * con){ - TCOD_text_render(data,con->data); -} - -const char *TCODText::getText(){ - return TCOD_text_get(data); -} - -void TCODText::reset(){ - TCOD_text_reset(data); -} - -#endif /* TCOD_CONSOLE_SUPPORT */ +/* +* libtcod +* Copyright (c) 2008-2018 Jice & Mingos & rmtew +* All rights reserved. +* +* Redistribution and use in source and binary forms, with or without +* modification, are permitted provided that the following conditions are met: +* * Redistributions of source code must retain the above copyright +* notice, this list of conditions and the following disclaimer. +* * Redistributions in binary form must reproduce the above copyright +* notice, this list of conditions and the following disclaimer in the +* documentation and/or other materials provided with the distribution. +* * The name of Jice or Mingos may not be used to endorse or promote +* products derived from this software without specific prior written +* permission. +* +* THIS SOFTWARE IS PROVIDED BY JICE, MINGOS AND RMTEW ``AS IS'' AND ANY +* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED +* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE +* DISCLAIMED. IN NO EVENT SHALL JICE, MINGOS OR RMTEW BE LIABLE FOR ANY +* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES +* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; +* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND +* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS +* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +*/ +#include "txtfield.hpp" + +#ifdef TCOD_CONSOLE_SUPPORT + +TCODText::TCODText(int x, int y, int w, int h, int max_chars){ + data=TCOD_text_init(x,y,w,h,max_chars); +} + +TCODText::TCODText(int w, int h, int max_chars){ + data=TCOD_text_init2(w,h,max_chars); +} + +TCODText::~TCODText(){ + TCOD_text_delete(data); +} + +void TCODText::setPos(int x, int y) { + TCOD_text_set_pos(data,x,y); +} + +void TCODText::setProperties(int cursor_char, int blink_interval, const char * prompt, int tab_size){ + TCOD_text_set_properties(data,cursor_char,blink_interval,prompt,tab_size); +} + +void TCODText::setColors(TCODColor fore, TCODColor back, float back_transparency){ + TCOD_color_t foreground = {fore.r,fore.g,fore.b}; + TCOD_color_t background = {back.r,back.g,back.b}; + TCOD_text_set_colors(data,foreground,background,back_transparency); +} + +bool TCODText::update(TCOD_key_t key){ + return TCOD_text_update(data,key) != 0; +} + +void TCODText::render(TCODConsole * con){ + TCOD_text_render(data,con->data); +} + +const char *TCODText::getText(){ + return TCOD_text_get(data); +} + +void TCODText::reset(){ + TCOD_text_reset(data); +} + +#endif /* TCOD_CONSOLE_SUPPORT */ diff --git a/tcod_sys/libtcod/include/txtfield.h b/tcod_sys/libtcod/src/libtcod/txtfield.h similarity index 95% rename from tcod_sys/libtcod/include/txtfield.h rename to tcod_sys/libtcod/src/libtcod/txtfield.h index 48739722a..327b1495d 100644 --- a/tcod_sys/libtcod/include/txtfield.h +++ b/tcod_sys/libtcod/src/libtcod/txtfield.h @@ -1,59 +1,60 @@ -/* -* libtcod -* Copyright (c) 2008-2018 Jice & Mingos & rmtew -* All rights reserved. -* -* Redistribution and use in source and binary forms, with or without -* modification, are permitted provided that the following conditions are met: -* * Redistributions of source code must retain the above copyright -* notice, this list of conditions and the following disclaimer. -* * Redistributions in binary form must reproduce the above copyright -* notice, this list of conditions and the following disclaimer in the -* documentation and/or other materials provided with the distribution. -* * The name of Jice or Mingos may not be used to endorse or promote -* products derived from this software without specific prior written -* permission. -* -* THIS SOFTWARE IS PROVIDED BY JICE, MINGOS AND RMTEW ``AS IS'' AND ANY -* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED -* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE -* DISCLAIMED. IN NO EVENT SHALL JICE, MINGOS OR RMTEW BE LIABLE FOR ANY -* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES -* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; -* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND -* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS -* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. -*/ -#ifndef _TCOD_TEXT_H_ -#define _TCOD_TEXT_H_ - -#include "libtcod_portability.h" - -#ifdef TCOD_CONSOLE_SUPPORT - -#include "color.h" -#include "console_types.h" - -#ifdef __cplusplus -extern "C" { -#endif -typedef void * TCOD_text_t; - -TCODLIB_API TCOD_text_t TCOD_text_init(int x, int y, int w, int h, int max_chars); -TCODLIB_API TCOD_text_t TCOD_text_init2(int w, int h, int max_chars); -TCODLIB_API void TCOD_text_set_pos(TCOD_text_t txt, int x, int y); -TCODLIB_API void TCOD_text_set_properties(TCOD_text_t txt, int cursor_char, int blink_interval, const char * prompt, int tab_size); -TCODLIB_API void TCOD_text_set_colors(TCOD_text_t txt, TCOD_color_t fore, TCOD_color_t back, float back_transparency); -TCODLIB_API bool TCOD_text_update(TCOD_text_t txt, TCOD_key_t key); -TCODLIB_API void TCOD_text_render(TCOD_text_t txt, TCOD_console_t con); -TCODLIB_API const char * TCOD_text_get(TCOD_text_t txt); -TCODLIB_API void TCOD_text_reset(TCOD_text_t txt); -TCODLIB_API void TCOD_text_delete(TCOD_text_t txt); -#ifdef __cplusplus -} -#endif - -#endif /* TCOD_CONSOLE_SUPPORT */ - -#endif /* _TCOD_TEXT_H_ */ +/* +* libtcod +* Copyright (c) 2008-2018 Jice & Mingos & rmtew +* All rights reserved. +* +* Redistribution and use in source and binary forms, with or without +* modification, are permitted provided that the following conditions are met: +* * Redistributions of source code must retain the above copyright +* notice, this list of conditions and the following disclaimer. +* * Redistributions in binary form must reproduce the above copyright +* notice, this list of conditions and the following disclaimer in the +* documentation and/or other materials provided with the distribution. +* * The name of Jice or Mingos may not be used to endorse or promote +* products derived from this software without specific prior written +* permission. +* +* THIS SOFTWARE IS PROVIDED BY JICE, MINGOS AND RMTEW ``AS IS'' AND ANY +* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED +* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE +* DISCLAIMED. IN NO EVENT SHALL JICE, MINGOS OR RMTEW BE LIABLE FOR ANY +* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES +* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; +* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND +* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS +* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +*/ +#ifndef _TCOD_TEXT_H_ +#define _TCOD_TEXT_H_ + +#include "portability.h" + +#ifdef TCOD_CONSOLE_SUPPORT + +#include "color.h" +#include "console_types.h" + +#ifdef __cplusplus +extern "C" { +#endif +struct TCOD_Text; +typedef struct TCOD_Text *TCOD_text_t; + +TCODLIB_API TCOD_text_t TCOD_text_init(int x, int y, int w, int h, int max_chars); +TCODLIB_API TCOD_text_t TCOD_text_init2(int w, int h, int max_chars); +TCODLIB_API void TCOD_text_set_pos(TCOD_text_t txt, int x, int y); +TCODLIB_API void TCOD_text_set_properties(TCOD_text_t txt, int cursor_char, int blink_interval, const char * prompt, int tab_size); +TCODLIB_API void TCOD_text_set_colors(TCOD_text_t txt, TCOD_color_t fore, TCOD_color_t back, float back_transparency); +TCODLIB_API bool TCOD_text_update(TCOD_text_t txt, TCOD_key_t key); +TCODLIB_API void TCOD_text_render(TCOD_text_t txt, TCOD_console_t con); +TCODLIB_API const char * TCOD_text_get(TCOD_text_t txt); +TCODLIB_API void TCOD_text_reset(TCOD_text_t txt); +TCODLIB_API void TCOD_text_delete(TCOD_text_t txt); +#ifdef __cplusplus +} +#endif + +#endif /* TCOD_CONSOLE_SUPPORT */ + +#endif /* _TCOD_TEXT_H_ */ diff --git a/tcod_sys/libtcod/include/txtfield.hpp b/tcod_sys/libtcod/src/libtcod/txtfield.hpp similarity index 97% rename from tcod_sys/libtcod/include/txtfield.hpp rename to tcod_sys/libtcod/src/libtcod/txtfield.hpp index 807140c4c..5f18f5576 100644 --- a/tcod_sys/libtcod/include/txtfield.hpp +++ b/tcod_sys/libtcod/src/libtcod/txtfield.hpp @@ -1,55 +1,55 @@ -/* -* libtcod -* Copyright (c) 2008-2018 Jice & Mingos & rmtew -* All rights reserved. -* -* Redistribution and use in source and binary forms, with or without -* modification, are permitted provided that the following conditions are met: -* * Redistributions of source code must retain the above copyright -* notice, this list of conditions and the following disclaimer. -* * Redistributions in binary form must reproduce the above copyright -* notice, this list of conditions and the following disclaimer in the -* documentation and/or other materials provided with the distribution. -* * The name of Jice or Mingos may not be used to endorse or promote -* products derived from this software without specific prior written -* permission. -* -* THIS SOFTWARE IS PROVIDED BY JICE, MINGOS AND RMTEW ``AS IS'' AND ANY -* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED -* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE -* DISCLAIMED. IN NO EVENT SHALL JICE, MINGOS OR RMTEW BE LIABLE FOR ANY -* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES -* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; -* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND -* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS -* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. -*/ -#ifndef _TCOD_TEXT_HPP_ -#define _TCOD_TEXT_HPP_ - -#include "color.hpp" -#include "console.hpp" -#include "txtfield.h" - -#ifdef TCOD_CONSOLE_SUPPORT - -class TCODLIB_API TCODText { -public : - TCODText(int x, int y, int w, int h, int max_chars); - TCODText(int w, int h, int max_chars); - ~TCODText(); - void setProperties(int cursor_char, int blink_interval, const char * prompt, int tab_size); - void setColors(TCODColor fore, TCODColor back, float back_transparency); - void setPos(int x, int y); - bool update(TCOD_key_t key); - void render(TCODConsole * con); - const char *getText(); - void reset(); -protected : - TCOD_text_t data; -}; - -#endif /* TCOD_CONSOLE_SUPPORT */ - -#endif +/* +* libtcod +* Copyright (c) 2008-2018 Jice & Mingos & rmtew +* All rights reserved. +* +* Redistribution and use in source and binary forms, with or without +* modification, are permitted provided that the following conditions are met: +* * Redistributions of source code must retain the above copyright +* notice, this list of conditions and the following disclaimer. +* * Redistributions in binary form must reproduce the above copyright +* notice, this list of conditions and the following disclaimer in the +* documentation and/or other materials provided with the distribution. +* * The name of Jice or Mingos may not be used to endorse or promote +* products derived from this software without specific prior written +* permission. +* +* THIS SOFTWARE IS PROVIDED BY JICE, MINGOS AND RMTEW ``AS IS'' AND ANY +* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED +* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE +* DISCLAIMED. IN NO EVENT SHALL JICE, MINGOS OR RMTEW BE LIABLE FOR ANY +* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES +* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; +* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND +* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS +* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +*/ +#ifndef _TCOD_TEXT_HPP_ +#define _TCOD_TEXT_HPP_ + +#include "color.hpp" +#include "console.hpp" +#include "txtfield.h" + +#ifdef TCOD_CONSOLE_SUPPORT + +class TCODLIB_API TCODText { +public : + TCODText(int x, int y, int w, int h, int max_chars); + TCODText(int w, int h, int max_chars); + ~TCODText(); + void setProperties(int cursor_char, int blink_interval, const char * prompt, int tab_size); + void setColors(TCODColor fore, TCODColor back, float back_transparency); + void setPos(int x, int y); + bool update(TCOD_key_t key); + void render(TCODConsole * con); + const char *getText(); + void reset(); +protected : + TCOD_text_t data; +}; + +#endif /* TCOD_CONSOLE_SUPPORT */ + +#endif diff --git a/tcod_sys/libtcod/src/txtfield_c.c b/tcod_sys/libtcod/src/libtcod/txtfield_c.c similarity index 96% rename from tcod_sys/libtcod/src/txtfield_c.c rename to tcod_sys/libtcod/src/libtcod/txtfield_c.c index 3af7708f0..3057c9885 100644 --- a/tcod_sys/libtcod/src/txtfield_c.c +++ b/tcod_sys/libtcod/src/libtcod/txtfield_c.c @@ -1,689 +1,689 @@ -/* -* libtcod -* Copyright (c) 2008-2018 Jice & Mingos & rmtew -* All rights reserved. -* -* Redistribution and use in source and binary forms, with or without -* modification, are permitted provided that the following conditions are met: -* * Redistributions of source code must retain the above copyright -* notice, this list of conditions and the following disclaimer. -* * Redistributions in binary form must reproduce the above copyright -* notice, this list of conditions and the following disclaimer in the -* documentation and/or other materials provided with the distribution. -* * The name of Jice or Mingos may not be used to endorse or promote -* products derived from this software without specific prior written -* permission. -* -* THIS SOFTWARE IS PROVIDED BY JICE, MINGOS AND RMTEW ``AS IS'' AND ANY -* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED -* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE -* DISCLAIMED. IN NO EVENT SHALL JICE, MINGOS OR RMTEW BE LIABLE FOR ANY -* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES -* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; -* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND -* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS -* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. -*/ -#include - -#ifdef TCOD_CONSOLE_SUPPORT - -#include -#include - -#include -#include -#include - -#define MAX_INT 0x7FFFFFFF - -typedef struct { - int x, y; /* coordinates on parent console */ - int w, h; /* textfield display size */ - int max; /* maximum nb of characters */ - int interval; /* cursor blinking interval */ - int halfinterval; /* half of the above */ - int ascii_cursor; /* cursor char. 0 if none */ - int cursor_pos, sel_start,sel_end; /* cursor position in text, selection range */ - int tab_size; /* tab size, if 0, no tab */ - char * prompt; /* prompt to be displayed before the string */ - int textx,texty; /* coordinate of start of text (after prompt) */ - TCOD_console_t con; /* offscreen console that will contain the textfield */ - bool input_continue; /* controls whether ENTER has been pressed */ - int len; /* allocated size of the text */ - int curlen; /* current length of the text */ - TCOD_color_t back; /* background colour */ - TCOD_color_t fore; /* foreground colour */ - float transparency; /* background transparency */ - bool multiline; /* multiline support ? */ - char * text; /* the text itself */ -} text_t; - -/* ctor */ -TCOD_text_t TCOD_text_init (int x, int y, int w, int h, int max_chars) { - text_t * data = (text_t*)calloc(sizeof(text_t),1); - TCOD_IFNOT(w> 0 && h > 0) return data; - data->x = x; - data->y = y; - data->w = w; - data->h = h; - data->multiline = (h > 1); - data->max = (max_chars > 0 ? max_chars + 1 : MAX_INT); - data->interval = 800; - data->halfinterval = 400; - data->ascii_cursor = 0; - data->prompt = NULL; - data->textx = data->texty = 0; - data->con = TCOD_console_new(w,h); - data->sel_start = MAX_INT; - data->sel_end = -1; - /* - if (! data->multiline ) { - data->max = MIN(w - data->textx,data->max); - } else { - data->max = MIN(w*(h-data->texty) - data->textx,data->max); - } - */ - if (max_chars && max_chars > 0) data->max = max_chars; - else data->max = data->w * data->h; - data->input_continue = true; - data->len = MIN(64,data->max); - data->text = (char*)calloc(data->len,sizeof(char)); - data->back.r = data->back.g = data->back.b = 0; - data->fore.r = data->fore.g = data->fore.b = 255; - data->transparency = 1.0f; - return (TCOD_text_t)data; -} - -TCOD_text_t TCOD_text_init2(int w, int h, int max_chars) { - text_t * data = (text_t*)calloc(sizeof(text_t),1); - TCOD_IFNOT(w> 0 && h > 0) return data; - data->x = 0; - data->y = 0; - data->w = w; - data->h = h; - data->multiline = (h > 1); - data->max = (max_chars > 0 ? max_chars + 1 : MAX_INT); - data->interval = 800; - data->halfinterval = 400; - data->ascii_cursor = 0; - data->prompt = NULL; - data->textx = data->texty = 0; - data->con = TCOD_console_new(w,h); - data->sel_start = MAX_INT; - data->sel_end = -1; - /* - if (! data->multiline ) { - data->max = MIN(w - data->textx,data->max); - } else { - data->max = MIN(w*(h-data->texty) - data->textx,data->max); - } - */ - if (max_chars && max_chars > 0) data->max = max_chars; - else data->max = data->w * data->h; - data->input_continue = true; - data->len = MIN(64,data->max); - data->text = (char*)calloc(data->len,sizeof(char)); - data->back.r = data->back.g = data->back.b = 0; - data->fore.r = data->fore.g = data->fore.b = 255; - data->transparency = 1.0f; - return (TCOD_text_t)data; -} - -void TCOD_text_set_pos(TCOD_text_t txt, int x, int y) { - text_t * data = (text_t*)txt; - data->x=x; - data->y=y; -} - -/* set cursor and prompt */ -void TCOD_text_set_properties (TCOD_text_t txt, int cursor_char, int blink_interval, const char * prompt, int tab_size) { - text_t * data = (text_t*)txt; - TCOD_IFNOT(data && data->con ) return; - data->interval = blink_interval; - data->halfinterval = (blink_interval > 0 ? blink_interval / 2 : 0); - data->ascii_cursor = cursor_char; - if (data->prompt) free(data->prompt); - data->prompt = prompt ? TCOD_strdup(prompt) : NULL; - data->textx = data->texty = 0; - data->tab_size=tab_size; - if ( prompt ) { - const char *ptr=prompt; - while (*ptr) { - data->textx++; - if ( *ptr == '\n' || data->textx == data->w) { - data->textx=0;data->texty++; - } - ptr++; - } - } -} - -/* set colours */ -void TCOD_text_set_colors (TCOD_text_t txt, TCOD_color_t fore, TCOD_color_t back, float back_transparency) { - text_t * data = (text_t*)txt; - TCOD_IFNOT(data && data->con ) return; - data->back = back; - data->fore = fore; - data->transparency = back_transparency; -} - -/* increase the buffer size. internal function */ -static void allocate(text_t *data) { - char *tmp; - data->len *= 2; - tmp = (char*)calloc(data->len,sizeof(char)); - memcpy(tmp,data->text,data->len/2); - free(data->text); - data->text = tmp; -} - -/* insert a character at cursor position. internal function */ -static void insertChar(text_t *data, char c) { - char *ptr, *end; - if (data->cursor_pos + 1 == data->max) { - /* max size reached. replace the last char. don't increase text size */ - *(data->text + data->cursor_pos -1) = c; - return; - } - if (data->curlen + 1 == data->len ) allocate(data); - ptr=data->text + data->cursor_pos; - end=data->text + data->curlen; - do { - *(end+1) = *end; - end--; - } while ( end >= ptr ); - *ptr = c; - data->curlen++; - data->cursor_pos++; -} - -/* delete character at cursor position */ -static void deleteChar(text_t *data) { - char *ptr; - if ( data->cursor_pos == 0 ) return; - ptr=data->text + data->cursor_pos-1; - do { - *ptr = *(ptr+1); - ptr++; - } while (*ptr); - if ( data->cursor_pos > 0 ) { - data->cursor_pos--; - data->curlen--; - } -} - -/* convert current cursor_pos into console coordinates. internal function */ -static void get_cursor_coords(text_t *data, int *cx, int *cy) { - char *ptr; - if (data->multiline) { - int curcount=data->cursor_pos; - ptr=data->text; - *cx = data->textx; - *cy = data->texty; - while (curcount > 0 && *ptr) { - if ( *ptr == '\n') { - *cx=0; - (*cy)++; - } else { - (*cx)++; - if ( *cx == data->w ) { - *cx=0; - (*cy)++; - } - } - ptr++; - curcount--; - } - } else { - *cx = data->textx + data->cursor_pos; - *cy = data->texty; - } -} - -/* check if the text does not overflow the textfield */ -/* -not working... -static bool check_last_pos(text_t *data) { - int count = strlen(data->text); - int cx=data->textx; - int cy=data->texty; - char *ptr=data->text; - while ( count > 0 ) { - if ( *ptr == '\n') { - cx=0; - cy++; - } else { - cx++; - if ( cx == data->w ) { - cx=0; - cy++; - } - } - ptr++; - count--; - } - return ( cy < data->h ); -} -*/ - -/* set cursor_pos from coordinates. internal function */ -static void set_cursor_pos(text_t *data, int cx, int cy, bool clamp) { - if ( data->multiline ) { - int curx=data->textx,cury=data->texty; - char *ptr=data->text; - int newpos=0; - if ( clamp ) { - cy=MAX(data->texty,cy); - if ( cy == data->texty) cx = MAX(data->textx,cx); - } - /* find the right line */ - while ( *ptr && cury < cy && cury < data->h ) { - if (*ptr == '\n' || curx == data->w-1) { - curx=0;cury++; - } else curx++; - ptr++; - newpos++; - } - if ( cury >= data->h ) return; - if ( cury == cy ) { - /* check if cx can be reached */ - while ( *ptr && curx < cx && *ptr != '\n') { - ptr++; - curx++; - newpos++; - } - } - data->cursor_pos = newpos; - } else { - int newpos = cx - data->textx + (cy - data->texty)*data->w; - if ( clamp ) newpos = CLAMP(0,data->curlen,newpos); - if ( newpos >= 0 && newpos <= data->curlen ) data->cursor_pos = newpos; - } -} - - -/* decreases the selection range start */ -static void selectStart(text_t *data, int oldpos, TCOD_key_t key) { - if ( data->multiline && data->cursor_pos != oldpos ) { - if ( key.shift ) { - if ( data->sel_start > data->cursor_pos ) data->sel_start = data->cursor_pos; - else data->sel_end = data->cursor_pos; - } else { - data->sel_start=MAX_INT; - data->sel_end=-1; - } - } -} - -/* increases the selection range end */ -static void selectEnd(text_t *data, int oldpos, TCOD_key_t key) { - if ( data->multiline && data->cursor_pos != oldpos ) { - if ( key.shift ) { - if ( data->sel_end < data->cursor_pos ) data->sel_end = data->cursor_pos; - else data->sel_start = data->cursor_pos; - } else { - data->sel_start=MAX_INT; - data->sel_end=-1; - } - } -} - -enum { TYPE_SYMBOL, TYPE_ALPHANUM, TYPE_SPACE }; -static const char txt_symbols[]="&~\"#'{([-|`_\\^@)]=+}*/!:;.,?<>"; - -/* check whether a character is a space */ -/* this is needed because cctype isspace() returns rubbish for many diacritics */ -static bool is_space (int ch) { - bool ret; - switch (ch) { - case ' ': case '\n': case '\r': case '\t': ret = true; break; - default: ret = false; break; - } - return ret; -} - -static void typecheck (int * type, int ch) { - if (strchr(txt_symbols,ch)) *type = TYPE_SYMBOL; - else if (is_space(ch)) *type = TYPE_SPACE; - else *type = TYPE_ALPHANUM; -} - -/* go one word left */ -static void previous_word(text_t *data) { - /* current character type */ - if ( data->cursor_pos > 0 ) { - /* detect current char type (alphanum/space or symbol) */ - char *ptr=data->text + data->cursor_pos - 1; - int curtype, prevtype; - typecheck(&curtype,*ptr); - /* go back until char type changes from alphanumeric to something else */ - do { - data->cursor_pos--; - ptr--; - prevtype = curtype; - typecheck(&curtype,*ptr); - } while ( data->cursor_pos > 0 && !(curtype != TYPE_ALPHANUM && prevtype == TYPE_ALPHANUM)); - } -} - -/* go one word right */ -static void next_word(text_t *data) { - /* current character type */ - if ( data->text[data->cursor_pos] ) { - /* detect current char type (alphanum/space or symbol) */ - char *ptr=data->text + data->cursor_pos; - int curtype, prevtype; - typecheck(&curtype,*ptr); - /* go forth until char type changes from non alphanumeric to alphanumeric */ - do { - data->cursor_pos++; - ptr++; - prevtype = curtype; - typecheck(&curtype,*ptr); - } while ( *ptr && !(curtype == TYPE_ALPHANUM && prevtype != TYPE_ALPHANUM)); - } -} - -/* erase the selected text */ -static void deleteSelection(text_t *data) { - int count = data->sel_end-data->sel_start; - data->cursor_pos = data->sel_start+1; - while ( count > 0 ) { - deleteChar(data); - count--; - data->cursor_pos++; - } - data->cursor_pos--; - data->sel_start=MAX_INT; - data->sel_end=-1; -} - -/* copy selected text to clipboard */ -static void copy(text_t *data) { - if ( data->sel_end - data->sel_start > 0 ) { - char *clipbuf = (char*)calloc(data->sel_end - data->sel_start+1,1); - char *ptr=clipbuf; - int i; - for (i=data->sel_start; i != data->sel_end; i++) { - *ptr++ = data->text[i]; - } - TCOD_sys_clipboard_set(clipbuf); - free(clipbuf); - } -} - -/* cut selected text to clipboard */ -static void cut(text_t *data) { - if ( data->sel_end - data->sel_start > 0 ) { - char *clipbuf = (char*)calloc(data->sel_end - data->sel_start+1,1); - char *ptr=clipbuf; - int i; - for (i=data->sel_start; i != data->sel_end; i++) { - *ptr++ = data->text[i]; - } - TCOD_sys_clipboard_set(clipbuf); - free(clipbuf); - deleteSelection(data); - } -} - -/* paste from clipboard */ -static void paste(text_t *data) { - char *clipbuf=TCOD_sys_clipboard_get(); - if ( clipbuf ) { - if ( data->sel_start != MAX_INT ) { - deleteSelection(data); - } - while (*clipbuf) { - insertChar(data,*clipbuf++); - } - } -} - -/* update returns false if enter has been pressed, true otherwise */ -bool TCOD_text_update (TCOD_text_t txt, TCOD_key_t key) { - int cx,cy,oldpos; - text_t * data = (text_t*)txt; - TCOD_IFNOT(data && data->con ) return false; - oldpos = data->cursor_pos; - /* for real-time keyboard : only on key release */ - if ( key.pressed ) { - /* process keyboard input */ - switch (key.vk) { - case TCODK_BACKSPACE: /* get rid of the last character */ - if ( data->sel_start != MAX_INT ) { - deleteSelection(data); - } else { - deleteChar(data); - } - break; - case TCODK_DELETE: - if ( key.shift ) { - /* SHIFT-DELETE : cut to clipboard */ - cut(data); - } else { - if ( data->sel_start != MAX_INT ) { - deleteSelection(data); - } else if ( data->text[data->cursor_pos] ) { - data->cursor_pos++; - deleteChar(data); - } - } - break; - /* shift + arrow / home / end = selection */ - /* ctrl + arrow = word skipping. ctrl + shift + arrow = word selection */ - case TCODK_LEFT: - if ( data->multiline && key.shift && data->sel_end == -1) { - data->sel_end = data->cursor_pos; - } - if ( data->cursor_pos > 0 ) { - if ( key.lctrl || key.rctrl ) { - previous_word(data); - } else data->cursor_pos--; - selectStart(data,oldpos,key); - } - break; - case TCODK_RIGHT: - if ( data->multiline && key.shift && data->sel_start == MAX_INT ) { - data->sel_start = data->cursor_pos; - } - if ( data->text[data->cursor_pos] ) { - if ( key.lctrl || key.rctrl ) { - next_word(data); - } else data->cursor_pos++; - selectEnd(data,oldpos,key); - } - break; - case TCODK_UP : - get_cursor_coords(data,&cx,&cy); - if ( data->multiline && key.shift && data->sel_end == -1) { - data->sel_end = data->cursor_pos; - } - set_cursor_pos(data,cx,cy-1,false); - selectStart(data,oldpos,key); - break; - case TCODK_DOWN : - get_cursor_coords(data,&cx,&cy); - if ( data->multiline && key.shift && data->sel_start == MAX_INT ) { - data->sel_start = data->cursor_pos; - } - set_cursor_pos(data,cx,cy+1,false); - selectEnd(data,oldpos,key); - break; - case TCODK_HOME: - get_cursor_coords(data,&cx,&cy); - if ( data->multiline && key.shift && data->sel_end == -1) { - data->sel_end = data->cursor_pos; - } - if ( key.lctrl || key.rctrl ) { - set_cursor_pos(data,0,0,true); - } else { - set_cursor_pos(data,0,cy,true); - } - selectStart(data,oldpos,key); - break; - case TCODK_END: - get_cursor_coords(data,&cx,&cy); - if ( data->multiline && key.shift && data->sel_start == MAX_INT ) { - data->sel_start = data->cursor_pos; - } - if ( key.lctrl || key.rctrl ) { - set_cursor_pos(data,data->w,data->h,true); - } else { - set_cursor_pos(data,data->w-1,cy,true); - } - selectEnd(data,oldpos,key); - break; - case TCODK_ENTER: /* validate input */ - case TCODK_KPENTER: - if ( data->sel_start != MAX_INT ) { - deleteSelection(data); - } - if ( data->multiline ) { - get_cursor_coords(data,&cx,&cy); - if ( cy < data->h-1 ) insertChar(data,'\n'); - } else { - data->input_continue = false; - } - break; - case TCODK_TAB : - if (data->tab_size ) { - int count=data->tab_size; - if ( data->sel_start != MAX_INT ) { - deleteSelection(data); - } - while ( count > 0 ) { - insertChar(data,' '); - count--; - } - } - break; - default: { /* append a new character */ - if ( (key.c == 'c' || key.c=='C' || key.vk == TCODK_INSERT) && (key.lctrl || key.rctrl) ) { - /* CTRL-C or CTRL-INSERT : copy to clipboard */ - copy(data); - } else if ( (key.c == 'x' || key.c=='X') && (key.lctrl || key.rctrl) ) { - /* CTRL-X : cut to clipboard */ - cut(data); - } else if ( ((key.c == 'v' || key.c=='V') && (key.lctrl || key.rctrl)) - || ( key.vk == TCODK_INSERT && key.shift ) - ) { - /* CTRL-V or SHIFT-INSERT : paste from clipboard */ - paste(data); - } else if (key.c > 31) { - if ( data->sel_start != MAX_INT ) { - deleteSelection(data); - } - insertChar(data,(char)(key.c)); - } - break; - } - } - } - return data->input_continue; -} - -/* renders the textfield */ -void TCOD_text_render (TCOD_text_t txt, TCOD_console_t con) { - text_t * data = (text_t*)txt; - uint32_t time; - bool cursor_on; - char back=0; - int curx,cury,cursorx,cursory, curpos; - char *ptr; - TCOD_IFNOT(data && data->con ) return; - time = TCOD_sys_elapsed_milli(); - cursor_on = (int)( time % data->interval ) > data->halfinterval; - TCOD_console_set_default_background(data->con, data->back); - TCOD_console_set_default_foreground(data->con, data->fore); - TCOD_console_clear(data->con); - - /* compute cursor position */ - get_cursor_coords(data,&cursorx,&cursory); - - if ( cursor_on && data->ascii_cursor) { - /* save the character under cursor position */ - back = data->text[data->cursor_pos]; - data->text[data->cursor_pos] = data->ascii_cursor; - } - /* render prompt */ - if (data->prompt) TCOD_console_print_rect_ex(data->con,0,0,data->w,data->h,TCOD_BKGND_SET,TCOD_LEFT,"%s",data->prompt); - /* render text */ - curx=data->textx; - cury=data->texty; - ptr=data->text; - curpos=0; - while (*ptr) { - if ( *ptr == '\n') { - if ( (curx == 0 || curpos == 0 ) && curpos >= data->sel_start && curpos < data->sel_end ) { - /* inverted colors for selected empty lines */ - TCOD_console_set_char_background(data->con, curx, cury, data->fore, TCOD_BKGND_SET); - TCOD_console_set_char_foreground(data->con, curx, cury, data->back); - } - curx=0; - cury++; - } else { - if ( curpos >= data->sel_start && curpos < data->sel_end ) { - /* inverted colors for selection */ - TCOD_console_set_char_background(data->con, curx, cury, data->fore, TCOD_BKGND_SET); - TCOD_console_set_char_foreground(data->con, curx, cury, data->back); - } - TCOD_console_set_char(data->con,curx,cury,*ptr); - curx++; - if ( curx == data->w ) { - curx=0; - cury++; - } - } - ptr++; - curpos++; - } - if ( cursor_on ) { - if ( data->ascii_cursor) { - /* restore the character under cursor */ - data->text[data->cursor_pos] = back; - } else { - /* invert colors at cursor position */ - TCOD_console_set_char_background(data->con,cursorx,cursory,data->fore,TCOD_BKGND_SET); - TCOD_console_set_char_foreground(data->con,cursorx,cursory,data->back); - } - } else if (! cursor_on && ! data->ascii_cursor && data->multiline ) { - /* normal colors for cursor ( might be inside selection ) */ - TCOD_console_set_char_background(data->con,cursorx,cursory,data->back,TCOD_BKGND_SET); - TCOD_console_set_char_foreground(data->con,cursorx,cursory,data->fore); - } - TCOD_console_blit(data->con,0,0,data->w,data->h,con,data->x,data->y,1.0f,data->transparency); -} - -/* returns the text currently stored in the textfield object */ -const char * TCOD_text_get (TCOD_text_t txt) { - text_t * data = (text_t*)txt; - TCOD_IFNOT(data && data->con ) return ""; - return data->text; -} - -/* resets the text initial state */ -void TCOD_text_reset (TCOD_text_t txt) { - text_t * data = (text_t*)txt; - TCOD_IFNOT(data && data->con ) return; - memset(data->text,'\0',data->len); - data->curlen = 0; - data->cursor_pos = 0; - data->sel_start = MAX_INT; - data->sel_end = -1; - data->input_continue = true; -} - -/* destructor */ -void TCOD_text_delete (TCOD_text_t txt) { - text_t * data = (text_t*)txt; - TCOD_IFNOT(data && data->con ) return; - if ( data->text ) free(data->text); - if ( data->prompt ) free(data->prompt); - TCOD_console_delete(data->con); - free(data); -} - -#endif /* TCOD_CONSOLE_SUPPORT */ +/* +* libtcod +* Copyright (c) 2008-2018 Jice & Mingos & rmtew +* All rights reserved. +* +* Redistribution and use in source and binary forms, with or without +* modification, are permitted provided that the following conditions are met: +* * Redistributions of source code must retain the above copyright +* notice, this list of conditions and the following disclaimer. +* * Redistributions in binary form must reproduce the above copyright +* notice, this list of conditions and the following disclaimer in the +* documentation and/or other materials provided with the distribution. +* * The name of Jice or Mingos may not be used to endorse or promote +* products derived from this software without specific prior written +* permission. +* +* THIS SOFTWARE IS PROVIDED BY JICE, MINGOS AND RMTEW ``AS IS'' AND ANY +* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED +* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE +* DISCLAIMED. IN NO EVENT SHALL JICE, MINGOS OR RMTEW BE LIABLE FOR ANY +* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES +* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; +* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND +* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS +* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +*/ +#include "txtfield.h" + +#ifdef TCOD_CONSOLE_SUPPORT + +#include +#include + +#include "console.h" +#include "libtcod_int.h" +#include "utility.h" + +#define MAX_INT 0x7FFFFFFF + +typedef struct TCOD_Text { + int x, y; /* coordinates on parent console */ + int w, h; /* textfield display size */ + int max; /* maximum nb of characters */ + int interval; /* cursor blinking interval */ + int halfinterval; /* half of the above */ + int ascii_cursor; /* cursor char. 0 if none */ + int cursor_pos, sel_start,sel_end; /* cursor position in text, selection range */ + int tab_size; /* tab size, if 0, no tab */ + char * prompt; /* prompt to be displayed before the string */ + int textx,texty; /* coordinate of start of text (after prompt) */ + TCOD_console_t con; /* offscreen console that will contain the textfield */ + bool input_continue; /* controls whether ENTER has been pressed */ + int len; /* allocated size of the text */ + int curlen; /* current length of the text */ + TCOD_color_t back; /* background colour */ + TCOD_color_t fore; /* foreground colour */ + float transparency; /* background transparency */ + bool multiline; /* multiline support ? */ + char * text; /* the text itself */ +} text_t; + +/* ctor */ +TCOD_text_t TCOD_text_init (int x, int y, int w, int h, int max_chars) { + text_t * data = (text_t*)calloc(sizeof(text_t),1); + TCOD_IFNOT(w> 0 && h > 0) return data; + data->x = x; + data->y = y; + data->w = w; + data->h = h; + data->multiline = (h > 1); + data->max = (max_chars > 0 ? max_chars + 1 : MAX_INT); + data->interval = 800; + data->halfinterval = 400; + data->ascii_cursor = 0; + data->prompt = NULL; + data->textx = data->texty = 0; + data->con = TCOD_console_new(w,h); + data->sel_start = MAX_INT; + data->sel_end = -1; + /* + if (! data->multiline ) { + data->max = MIN(w - data->textx,data->max); + } else { + data->max = MIN(w*(h-data->texty) - data->textx,data->max); + } + */ + if (max_chars && max_chars > 0) data->max = max_chars; + else data->max = data->w * data->h; + data->input_continue = true; + data->len = MIN(64,data->max); + data->text = (char*)calloc(data->len,sizeof(char)); + data->back.r = data->back.g = data->back.b = 0; + data->fore.r = data->fore.g = data->fore.b = 255; + data->transparency = 1.0f; + return (TCOD_text_t)data; +} + +TCOD_text_t TCOD_text_init2(int w, int h, int max_chars) { + text_t * data = (text_t*)calloc(sizeof(text_t),1); + TCOD_IFNOT(w> 0 && h > 0) return data; + data->x = 0; + data->y = 0; + data->w = w; + data->h = h; + data->multiline = (h > 1); + data->max = (max_chars > 0 ? max_chars + 1 : MAX_INT); + data->interval = 800; + data->halfinterval = 400; + data->ascii_cursor = 0; + data->prompt = NULL; + data->textx = data->texty = 0; + data->con = TCOD_console_new(w,h); + data->sel_start = MAX_INT; + data->sel_end = -1; + /* + if (! data->multiline ) { + data->max = MIN(w - data->textx,data->max); + } else { + data->max = MIN(w*(h-data->texty) - data->textx,data->max); + } + */ + if (max_chars && max_chars > 0) data->max = max_chars; + else data->max = data->w * data->h; + data->input_continue = true; + data->len = MIN(64,data->max); + data->text = (char*)calloc(data->len,sizeof(char)); + data->back.r = data->back.g = data->back.b = 0; + data->fore.r = data->fore.g = data->fore.b = 255; + data->transparency = 1.0f; + return (TCOD_text_t)data; +} + +void TCOD_text_set_pos(TCOD_text_t txt, int x, int y) { + text_t * data = (text_t*)txt; + data->x=x; + data->y=y; +} + +/* set cursor and prompt */ +void TCOD_text_set_properties (TCOD_text_t txt, int cursor_char, int blink_interval, const char * prompt, int tab_size) { + text_t * data = (text_t*)txt; + TCOD_IFNOT(data && data->con ) return; + data->interval = blink_interval; + data->halfinterval = (blink_interval > 0 ? blink_interval / 2 : 0); + data->ascii_cursor = cursor_char; + if (data->prompt) free(data->prompt); + data->prompt = prompt ? TCOD_strdup(prompt) : NULL; + data->textx = data->texty = 0; + data->tab_size=tab_size; + if ( prompt ) { + const char *ptr=prompt; + while (*ptr) { + data->textx++; + if ( *ptr == '\n' || data->textx == data->w) { + data->textx=0;data->texty++; + } + ptr++; + } + } +} + +/* set colours */ +void TCOD_text_set_colors (TCOD_text_t txt, TCOD_color_t fore, TCOD_color_t back, float back_transparency) { + text_t * data = (text_t*)txt; + TCOD_IFNOT(data && data->con ) return; + data->back = back; + data->fore = fore; + data->transparency = back_transparency; +} + +/* increase the buffer size. internal function */ +static void allocate(text_t *data) { + char *tmp; + data->len *= 2; + tmp = (char*)calloc(data->len,sizeof(char)); + memcpy(tmp,data->text,data->len/2); + free(data->text); + data->text = tmp; +} + +/* insert a character at cursor position. internal function */ +static void insertChar(text_t *data, char c) { + char *ptr, *end; + if (data->cursor_pos + 1 == data->max) { + /* max size reached. replace the last char. don't increase text size */ + *(data->text + data->cursor_pos -1) = c; + return; + } + if (data->curlen + 1 == data->len ) allocate(data); + ptr=data->text + data->cursor_pos; + end=data->text + data->curlen; + do { + *(end+1) = *end; + end--; + } while ( end >= ptr ); + *ptr = c; + data->curlen++; + data->cursor_pos++; +} + +/* delete character at cursor position */ +static void deleteChar(text_t *data) { + char *ptr; + if ( data->cursor_pos == 0 ) return; + ptr=data->text + data->cursor_pos-1; + do { + *ptr = *(ptr+1); + ptr++; + } while (*ptr); + if ( data->cursor_pos > 0 ) { + data->cursor_pos--; + data->curlen--; + } +} + +/* convert current cursor_pos into console coordinates. internal function */ +static void get_cursor_coords(text_t *data, int *cx, int *cy) { + char *ptr; + if (data->multiline) { + int curcount=data->cursor_pos; + ptr=data->text; + *cx = data->textx; + *cy = data->texty; + while (curcount > 0 && *ptr) { + if ( *ptr == '\n') { + *cx=0; + (*cy)++; + } else { + (*cx)++; + if ( *cx == data->w ) { + *cx=0; + (*cy)++; + } + } + ptr++; + curcount--; + } + } else { + *cx = data->textx + data->cursor_pos; + *cy = data->texty; + } +} + +/* check if the text does not overflow the textfield */ +/* +not working... +static bool check_last_pos(text_t *data) { + int count = strlen(data->text); + int cx=data->textx; + int cy=data->texty; + char *ptr=data->text; + while ( count > 0 ) { + if ( *ptr == '\n') { + cx=0; + cy++; + } else { + cx++; + if ( cx == data->w ) { + cx=0; + cy++; + } + } + ptr++; + count--; + } + return ( cy < data->h ); +} +*/ + +/* set cursor_pos from coordinates. internal function */ +static void set_cursor_pos(text_t *data, int cx, int cy, bool clamp) { + if ( data->multiline ) { + int curx=data->textx,cury=data->texty; + char *ptr=data->text; + int newpos=0; + if ( clamp ) { + cy=MAX(data->texty,cy); + if ( cy == data->texty) cx = MAX(data->textx,cx); + } + /* find the right line */ + while ( *ptr && cury < cy && cury < data->h ) { + if (*ptr == '\n' || curx == data->w-1) { + curx=0;cury++; + } else curx++; + ptr++; + newpos++; + } + if ( cury >= data->h ) return; + if ( cury == cy ) { + /* check if cx can be reached */ + while ( *ptr && curx < cx && *ptr != '\n') { + ptr++; + curx++; + newpos++; + } + } + data->cursor_pos = newpos; + } else { + int newpos = cx - data->textx + (cy - data->texty)*data->w; + if ( clamp ) newpos = CLAMP(0,data->curlen,newpos); + if ( newpos >= 0 && newpos <= data->curlen ) data->cursor_pos = newpos; + } +} + + +/* decreases the selection range start */ +static void selectStart(text_t *data, int oldpos, TCOD_key_t key) { + if ( data->multiline && data->cursor_pos != oldpos ) { + if ( key.shift ) { + if ( data->sel_start > data->cursor_pos ) data->sel_start = data->cursor_pos; + else data->sel_end = data->cursor_pos; + } else { + data->sel_start=MAX_INT; + data->sel_end=-1; + } + } +} + +/* increases the selection range end */ +static void selectEnd(text_t *data, int oldpos, TCOD_key_t key) { + if ( data->multiline && data->cursor_pos != oldpos ) { + if ( key.shift ) { + if ( data->sel_end < data->cursor_pos ) data->sel_end = data->cursor_pos; + else data->sel_start = data->cursor_pos; + } else { + data->sel_start=MAX_INT; + data->sel_end=-1; + } + } +} + +enum { TYPE_SYMBOL, TYPE_ALPHANUM, TYPE_SPACE }; +static const char txt_symbols[]="&~\"#'{([-|`_\\^@)]=+}*/!:;.,?<>"; + +/* check whether a character is a space */ +/* this is needed because cctype isspace() returns rubbish for many diacritics */ +static bool is_space (int ch) { + bool ret; + switch (ch) { + case ' ': case '\n': case '\r': case '\t': ret = true; break; + default: ret = false; break; + } + return ret; +} + +static void typecheck (int * type, int ch) { + if (strchr(txt_symbols,ch)) *type = TYPE_SYMBOL; + else if (is_space(ch)) *type = TYPE_SPACE; + else *type = TYPE_ALPHANUM; +} + +/* go one word left */ +static void previous_word(text_t *data) { + /* current character type */ + if ( data->cursor_pos > 0 ) { + /* detect current char type (alphanum/space or symbol) */ + char *ptr=data->text + data->cursor_pos - 1; + int curtype, prevtype; + typecheck(&curtype,*ptr); + /* go back until char type changes from alphanumeric to something else */ + do { + data->cursor_pos--; + ptr--; + prevtype = curtype; + typecheck(&curtype,*ptr); + } while ( data->cursor_pos > 0 && !(curtype != TYPE_ALPHANUM && prevtype == TYPE_ALPHANUM)); + } +} + +/* go one word right */ +static void next_word(text_t *data) { + /* current character type */ + if ( data->text[data->cursor_pos] ) { + /* detect current char type (alphanum/space or symbol) */ + char *ptr=data->text + data->cursor_pos; + int curtype, prevtype; + typecheck(&curtype,*ptr); + /* go forth until char type changes from non alphanumeric to alphanumeric */ + do { + data->cursor_pos++; + ptr++; + prevtype = curtype; + typecheck(&curtype,*ptr); + } while ( *ptr && !(curtype == TYPE_ALPHANUM && prevtype != TYPE_ALPHANUM)); + } +} + +/* erase the selected text */ +static void deleteSelection(text_t *data) { + int count = data->sel_end-data->sel_start; + data->cursor_pos = data->sel_start+1; + while ( count > 0 ) { + deleteChar(data); + count--; + data->cursor_pos++; + } + data->cursor_pos--; + data->sel_start=MAX_INT; + data->sel_end=-1; +} + +/* copy selected text to clipboard */ +static void copy(text_t *data) { + if ( data->sel_end - data->sel_start > 0 ) { + char *clipbuf = (char*)calloc(data->sel_end - data->sel_start+1,1); + char *ptr=clipbuf; + int i; + for (i=data->sel_start; i != data->sel_end; i++) { + *ptr++ = data->text[i]; + } + TCOD_sys_clipboard_set(clipbuf); + free(clipbuf); + } +} + +/* cut selected text to clipboard */ +static void cut(text_t *data) { + if ( data->sel_end - data->sel_start > 0 ) { + char *clipbuf = (char*)calloc(data->sel_end - data->sel_start+1,1); + char *ptr=clipbuf; + int i; + for (i=data->sel_start; i != data->sel_end; i++) { + *ptr++ = data->text[i]; + } + TCOD_sys_clipboard_set(clipbuf); + free(clipbuf); + deleteSelection(data); + } +} + +/* paste from clipboard */ +static void paste(text_t *data) { + char *clipbuf=TCOD_sys_clipboard_get(); + if ( clipbuf ) { + if ( data->sel_start != MAX_INT ) { + deleteSelection(data); + } + while (*clipbuf) { + insertChar(data,*clipbuf++); + } + } +} + +/* update returns false if enter has been pressed, true otherwise */ +bool TCOD_text_update (TCOD_text_t txt, TCOD_key_t key) { + int cx,cy,oldpos; + text_t * data = (text_t*)txt; + TCOD_IFNOT(data && data->con ) return false; + oldpos = data->cursor_pos; + /* for real-time keyboard : only on key release */ + if ( key.pressed ) { + /* process keyboard input */ + switch (key.vk) { + case TCODK_BACKSPACE: /* get rid of the last character */ + if ( data->sel_start != MAX_INT ) { + deleteSelection(data); + } else { + deleteChar(data); + } + break; + case TCODK_DELETE: + if ( key.shift ) { + /* SHIFT-DELETE : cut to clipboard */ + cut(data); + } else { + if ( data->sel_start != MAX_INT ) { + deleteSelection(data); + } else if ( data->text[data->cursor_pos] ) { + data->cursor_pos++; + deleteChar(data); + } + } + break; + /* shift + arrow / home / end = selection */ + /* ctrl + arrow = word skipping. ctrl + shift + arrow = word selection */ + case TCODK_LEFT: + if ( data->multiline && key.shift && data->sel_end == -1) { + data->sel_end = data->cursor_pos; + } + if ( data->cursor_pos > 0 ) { + if ( key.lctrl || key.rctrl ) { + previous_word(data); + } else data->cursor_pos--; + selectStart(data,oldpos,key); + } + break; + case TCODK_RIGHT: + if ( data->multiline && key.shift && data->sel_start == MAX_INT ) { + data->sel_start = data->cursor_pos; + } + if ( data->text[data->cursor_pos] ) { + if ( key.lctrl || key.rctrl ) { + next_word(data); + } else data->cursor_pos++; + selectEnd(data,oldpos,key); + } + break; + case TCODK_UP : + get_cursor_coords(data,&cx,&cy); + if ( data->multiline && key.shift && data->sel_end == -1) { + data->sel_end = data->cursor_pos; + } + set_cursor_pos(data,cx,cy-1,false); + selectStart(data,oldpos,key); + break; + case TCODK_DOWN : + get_cursor_coords(data,&cx,&cy); + if ( data->multiline && key.shift && data->sel_start == MAX_INT ) { + data->sel_start = data->cursor_pos; + } + set_cursor_pos(data,cx,cy+1,false); + selectEnd(data,oldpos,key); + break; + case TCODK_HOME: + get_cursor_coords(data,&cx,&cy); + if ( data->multiline && key.shift && data->sel_end == -1) { + data->sel_end = data->cursor_pos; + } + if ( key.lctrl || key.rctrl ) { + set_cursor_pos(data,0,0,true); + } else { + set_cursor_pos(data,0,cy,true); + } + selectStart(data,oldpos,key); + break; + case TCODK_END: + get_cursor_coords(data,&cx,&cy); + if ( data->multiline && key.shift && data->sel_start == MAX_INT ) { + data->sel_start = data->cursor_pos; + } + if ( key.lctrl || key.rctrl ) { + set_cursor_pos(data,data->w,data->h,true); + } else { + set_cursor_pos(data,data->w-1,cy,true); + } + selectEnd(data,oldpos,key); + break; + case TCODK_ENTER: /* validate input */ + case TCODK_KPENTER: + if ( data->sel_start != MAX_INT ) { + deleteSelection(data); + } + if ( data->multiline ) { + get_cursor_coords(data,&cx,&cy); + if ( cy < data->h-1 ) insertChar(data,'\n'); + } else { + data->input_continue = false; + } + break; + case TCODK_TAB : + if (data->tab_size ) { + int count=data->tab_size; + if ( data->sel_start != MAX_INT ) { + deleteSelection(data); + } + while ( count > 0 ) { + insertChar(data,' '); + count--; + } + } + break; + default: { /* append a new character */ + if ( (key.c == 'c' || key.c=='C' || key.vk == TCODK_INSERT) && (key.lctrl || key.rctrl) ) { + /* CTRL-C or CTRL-INSERT : copy to clipboard */ + copy(data); + } else if ( (key.c == 'x' || key.c=='X') && (key.lctrl || key.rctrl) ) { + /* CTRL-X : cut to clipboard */ + cut(data); + } else if ( ((key.c == 'v' || key.c=='V') && (key.lctrl || key.rctrl)) + || ( key.vk == TCODK_INSERT && key.shift ) + ) { + /* CTRL-V or SHIFT-INSERT : paste from clipboard */ + paste(data); + } else if (key.c > 31) { + if ( data->sel_start != MAX_INT ) { + deleteSelection(data); + } + insertChar(data,(char)(key.c)); + } + break; + } + } + } + return data->input_continue; +} + +/* renders the textfield */ +void TCOD_text_render (TCOD_text_t txt, TCOD_console_t con) { + text_t * data = (text_t*)txt; + uint32_t time; + bool cursor_on; + char back=0; + int curx,cury,cursorx,cursory, curpos; + char *ptr; + TCOD_IFNOT(data && data->con ) return; + time = TCOD_sys_elapsed_milli(); + cursor_on = (int)( time % data->interval ) > data->halfinterval; + TCOD_console_set_default_background(data->con, data->back); + TCOD_console_set_default_foreground(data->con, data->fore); + TCOD_console_clear(data->con); + + /* compute cursor position */ + get_cursor_coords(data,&cursorx,&cursory); + + if ( cursor_on && data->ascii_cursor) { + /* save the character under cursor position */ + back = data->text[data->cursor_pos]; + data->text[data->cursor_pos] = data->ascii_cursor; + } + /* render prompt */ + if (data->prompt) TCOD_console_print_rect_ex(data->con,0,0,data->w,data->h,TCOD_BKGND_SET,TCOD_LEFT,"%s",data->prompt); + /* render text */ + curx=data->textx; + cury=data->texty; + ptr=data->text; + curpos=0; + while (*ptr) { + if ( *ptr == '\n') { + if ( (curx == 0 || curpos == 0 ) && curpos >= data->sel_start && curpos < data->sel_end ) { + /* inverted colors for selected empty lines */ + TCOD_console_set_char_background(data->con, curx, cury, data->fore, TCOD_BKGND_SET); + TCOD_console_set_char_foreground(data->con, curx, cury, data->back); + } + curx=0; + cury++; + } else { + if ( curpos >= data->sel_start && curpos < data->sel_end ) { + /* inverted colors for selection */ + TCOD_console_set_char_background(data->con, curx, cury, data->fore, TCOD_BKGND_SET); + TCOD_console_set_char_foreground(data->con, curx, cury, data->back); + } + TCOD_console_set_char(data->con,curx,cury,*ptr); + curx++; + if ( curx == data->w ) { + curx=0; + cury++; + } + } + ptr++; + curpos++; + } + if ( cursor_on ) { + if ( data->ascii_cursor) { + /* restore the character under cursor */ + data->text[data->cursor_pos] = back; + } else { + /* invert colors at cursor position */ + TCOD_console_set_char_background(data->con,cursorx,cursory,data->fore,TCOD_BKGND_SET); + TCOD_console_set_char_foreground(data->con,cursorx,cursory,data->back); + } + } else if (! cursor_on && ! data->ascii_cursor && data->multiline ) { + /* normal colors for cursor ( might be inside selection ) */ + TCOD_console_set_char_background(data->con,cursorx,cursory,data->back,TCOD_BKGND_SET); + TCOD_console_set_char_foreground(data->con,cursorx,cursory,data->fore); + } + TCOD_console_blit(data->con,0,0,data->w,data->h,con,data->x,data->y,1.0f,data->transparency); +} + +/* returns the text currently stored in the textfield object */ +const char * TCOD_text_get (TCOD_text_t txt) { + text_t * data = (text_t*)txt; + TCOD_IFNOT(data && data->con ) return ""; + return data->text; +} + +/* resets the text initial state */ +void TCOD_text_reset (TCOD_text_t txt) { + text_t * data = (text_t*)txt; + TCOD_IFNOT(data && data->con ) return; + memset(data->text,'\0',data->len); + data->curlen = 0; + data->cursor_pos = 0; + data->sel_start = MAX_INT; + data->sel_end = -1; + data->input_continue = true; +} + +/* destructor */ +void TCOD_text_delete (TCOD_text_t txt) { + text_t * data = (text_t*)txt; + TCOD_IFNOT(data && data->con ) return; + if ( data->text ) free(data->text); + if ( data->prompt ) free(data->prompt); + TCOD_console_delete(data->con); + free(data); +} + +#endif /* TCOD_CONSOLE_SUPPORT */ diff --git a/tcod_sys/libtcod/include/libtcod_utility.h b/tcod_sys/libtcod/src/libtcod/utility.h similarity index 100% rename from tcod_sys/libtcod/include/libtcod_utility.h rename to tcod_sys/libtcod/src/libtcod/utility.h diff --git a/tcod_sys/libtcod/src/libtcod/utility/vector2.h b/tcod_sys/libtcod/src/libtcod/utility/vector2.h new file mode 100644 index 000000000..200827b0d --- /dev/null +++ b/tcod_sys/libtcod/src/libtcod/utility/vector2.h @@ -0,0 +1,86 @@ + +#ifndef LIBTCOD_UTILITY_VECTOR2_H_ +#define LIBTCOD_UTILITY_VECTOR2_H_ +#ifdef __cplusplus +#include +#include +#include +#endif // __cplusplus + +#ifdef __cplusplus +namespace tcod { +template +/** + * A 2-dimensional vector array. + */ +class Vector2 { + public: + using value_type = T; + Vector2() = default; + explicit Vector2(int width, int height) + : width_(std::max(0, width)), + height_(std::max(0, height)), + vector_(width_ * height_) {} + Vector2(Vector2&&) = default; + Vector2& operator=(Vector2&&) = default; + Vector2(const Vector2&) = default; + Vector2& operator=(const Vector2&) = default; + /** Return the width of this 2d vector. */ + int width(void) const noexcept { return width_; } + /** Return the height of this 2d vector. */ + int height(void) const noexcept { return height_; } + /** + * Return a reference for the pixel at `x`,`y`. + * + * Throws std::out_of_range if `x` or `y` are out of bounds. + */ + T& at(int x, int y) { + range_check(x, y); + return vector_.at(y * width_ + x); + } + /** + * Return a constant reference for the pixel at `x`,`y`. + * + * Throws std::out_of_range if `x` or `y` are out of bounds. + */ + const T& at(int x, int y) const { + range_check(x, y); + return vector_.at(y * width_ + x); + } + T* data() noexcept + { + return vector_.data(); + } + typename std::vector::iterator begin() + { + return vector_.begin(); + } + typename std::vector::iterator end() + { + return vector_.end(); + } + private: + /** + * Return true if x and y are in the bounds of this canvas. + */ + bool in_bounds(int x, int y) const noexcept { + return 0 <= x && x < width_ && 0 <= y && y < height_; + } + /** + * Immediately throws std::out_of_range if `x` or `y` are out of bounds. + */ + void range_check(int x, int y) const { + if (!in_bounds(x, y)) { + throw std::out_of_range("Out of bounds lookup on Vector2."); + } + } + /** The width of this canvas. */ + int width_ = 0; + /** The height of this canvas. */ + int height_ = 0; + /** A 1d vector mapped to a 2d array of pixels. */ + std::vector vector_; +}; +} // namespace tcod +#endif // __cplusplus +#endif // LIBTCOD_UTILITY_VECTOR2_H_ diff --git a/tcod_sys/libtcod/include/libtcod_version.h b/tcod_sys/libtcod/src/libtcod/version.h similarity index 82% rename from tcod_sys/libtcod/include/libtcod_version.h rename to tcod_sys/libtcod/src/libtcod/version.h index 336b832ae..3c8eecaa2 100644 --- a/tcod_sys/libtcod/include/libtcod_version.h +++ b/tcod_sys/libtcod/src/libtcod/version.h @@ -28,9 +28,16 @@ #ifndef LIBTCOD_VERSION_H #define LIBTCOD_VERSION_H -#define TCOD_HEXVERSION 0x010700 -#define TCOD_STRVERSION "1.7.0" -#define TCOD_TECHVERSION 0x01070000 +#define TCOD_MAJOR_VERSION 1 +#define TCOD_MINOR_VERSION 8 +#define TCOD_PATCHLEVEL 0 + +#define TCOD_STRVERSION "1.8.0" + +#define TCOD_HEXVERSION (0x010000 * TCOD_MAJOR_VERSION \ + + 0x0100 * TCOD_MINOR_VERSION \ + + 0x01 * TCOD_PATCHLEVEL) +#define TCOD_TECHVERSION (TCOD_HEXVERSION * 0x100) #define TCOD_STRVERSIONNAME "libtcod " TCOD_STRVERSION diff --git a/tcod_sys/libtcod/src/wrappers.c b/tcod_sys/libtcod/src/libtcod/wrappers.c similarity index 92% rename from tcod_sys/libtcod/src/wrappers.c rename to tcod_sys/libtcod/src/libtcod/wrappers.c index c9ce37b78..51122f044 100644 --- a/tcod_sys/libtcod/src/wrappers.c +++ b/tcod_sys/libtcod/src/libtcod/wrappers.c @@ -1,377 +1,377 @@ -/* -* libtcod -* Copyright (c) 2008-2018 Jice & Mingos & rmtew -* All rights reserved. -* -* Redistribution and use in source and binary forms, with or without -* modification, are permitted provided that the following conditions are met: -* * Redistributions of source code must retain the above copyright -* notice, this list of conditions and the following disclaimer. -* * Redistributions in binary form must reproduce the above copyright -* notice, this list of conditions and the following disclaimer in the -* documentation and/or other materials provided with the distribution. -* * The name of Jice or Mingos may not be used to endorse or promote -* products derived from this software without specific prior written -* permission. -* -* THIS SOFTWARE IS PROVIDED BY JICE, MINGOS AND RMTEW ``AS IS'' AND ANY -* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED -* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE -* DISCLAIMED. IN NO EVENT SHALL JICE, MINGOS OR RMTEW BE LIABLE FOR ANY -* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES -* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; -* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND -* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS -* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. -*/ -#include - -#include -#include - -#include -#include -#include - -#define RED_MASK 0x0000FF -#define GREEN_MASK 0x00FF00 -#define BLUE_MASK 0xFF0000 - -TCOD_color_t int_to_color (colornum_t col) { - TCOD_color_t ret; - ret.r = col & RED_MASK; - ret.g = (col & GREEN_MASK) >> 8; - ret.b = (col & BLUE_MASK) >> 16; - return ret; -} - -#define color_to_int(col) (int)(((int)((col).b) << 16) | ((col).g << 8) | (col).r) - -bool TCOD_color_equals_wrapper (colornum_t c1, colornum_t c2) { - return TCOD_color_equals (int_to_color(c1), int_to_color(c2)); -} - -colornum_t TCOD_color_add_wrapper (colornum_t c1, colornum_t c2) { - return color_to_int(TCOD_color_add (int_to_color(c1), - int_to_color(c2))); -} - -colornum_t TCOD_color_subtract_wrapper (colornum_t c1, colornum_t c2) { - return color_to_int(TCOD_color_subtract (int_to_color(c1), - int_to_color(c2))); -} - -colornum_t TCOD_color_multiply_wrapper (colornum_t c1, colornum_t c2) -{ - return color_to_int(TCOD_color_multiply (int_to_color(c1), int_to_color(c2))); -} - -colornum_t TCOD_color_multiply_scalar_wrapper (colornum_t c1, float value) -{ - return color_to_int(TCOD_color_multiply_scalar (int_to_color(c1), - value)); -} - -colornum_t TCOD_color_lerp_wrapper(colornum_t c1, colornum_t c2, float coef) -{ - return color_to_int(TCOD_color_lerp (int_to_color(c1),int_to_color(c2), - coef)); -} - -void TCOD_color_get_HSV_wrapper(colornum_t c,float * h, - float * s, float * v) -{ - TCOD_color_get_HSV (int_to_color(c), h, s, v); -} - -float TCOD_color_get_hue_wrapper (colornum_t c) { - return TCOD_color_get_hue(int_to_color(c)); -} - -float TCOD_color_get_saturation_wrapper (colornum_t c) { - return TCOD_color_get_saturation(int_to_color(c)); -} - -float TCOD_color_get_value_wrapper (colornum_t c) { - return TCOD_color_get_value(int_to_color(c)); -} - -#ifdef TCOD_CONSOLE_SUPPORT - -colornum_t TCOD_console_get_default_background_wrapper(TCOD_console_t con) -{ - return color_to_int(TCOD_console_get_default_background (con)); -} - - -colornum_t TCOD_console_get_default_foreground_wrapper(TCOD_console_t con) -{ - return color_to_int(TCOD_console_get_default_foreground (con)); -} - - -void TCOD_console_set_default_background_wrapper(TCOD_console_t con, - colornum_t col) -{ - TCOD_console_set_default_background (con, - int_to_color(col)); -} - -void TCOD_console_set_default_foreground_wrapper(TCOD_console_t con, - colornum_t col) -{ - TCOD_console_set_default_foreground (con, - int_to_color(col)); -} - -colornum_t TCOD_console_get_char_foreground_wrapper(TCOD_console_t con, - int x, int y) -{ - return color_to_int(TCOD_console_get_char_foreground (con, x, y)); -} - -colornum_t TCOD_console_get_char_background_wrapper(TCOD_console_t con, - int x, int y) -{ - return color_to_int(TCOD_console_get_char_background (con, x, y)); -} - -void TCOD_console_set_char_background_wrapper(TCOD_console_t con,int x, int y, - colornum_t col, - TCOD_bkgnd_flag_t flag) -{ - TCOD_console_set_char_background (con, x, y, int_to_color(col), flag); -} - - -void TCOD_console_set_char_foreground_wrapper(TCOD_console_t con,int x, int y, - colornum_t col) -{ - TCOD_console_set_char_foreground (con, x, y, int_to_color(col)); -} - -void TCOD_console_put_char_ex_wrapper(TCOD_console_t con, int x, int y, - int c, colornum_t fore, colornum_t back) -{ - TCOD_console_put_char_ex (con, x, y, c, int_to_color(fore), - int_to_color(back)); -} - -void TCOD_console_set_fade_wrapper(uint8_t val, colornum_t fade) -{ - TCOD_console_set_fade (val, int_to_color(fade)); -} - -void TCOD_console_fill_background(TCOD_console_t con, int *r, int *g, int *b) { - TCOD_console_data_t *dat = con ? (TCOD_console_data_t *)con : TCOD_ctx.root; - int i; - TCOD_color_t *curcolor = TCOD_image_get_colors(dat->bg_colors); - for (i = 0; i < dat->w*dat->h; i++) { - curcolor->r = *r; - curcolor->g = *g; - curcolor->b = *b; - curcolor++; - r++; - g++; - b++; - } -} - -void TCOD_console_fill_foreground(TCOD_console_t con, int *r, int *g, int *b) { - TCOD_console_data_t *dat = con ? (TCOD_console_data_t *)con : TCOD_ctx.root; - int i; - TCOD_color_t *curcolor = TCOD_image_get_colors(dat->fg_colors); - for (i = 0; i < dat->w*dat->h; i++) { - curcolor->r = *r; - curcolor->g = *g; - curcolor->b = *b; - curcolor++; - r++; - g++; - b++; - } -} - -void TCOD_console_fill_char(TCOD_console_t con, int *arr) { - TCOD_console_data_t *dat = con ? (TCOD_console_data_t *)con : TCOD_ctx.root; - int i; - for (i = 0; i < dat->w*dat->h; i++) { - dat->ch_array[i] = arr[i]; - } -} - -colornum_t -TCOD_console_get_fading_color_wrapper () -{ - return color_to_int(TCOD_console_get_fading_color()); -} - -void TCOD_console_set_color_control_wrapper(TCOD_colctrl_t con, - colornum_t fore, - colornum_t back) -{ - TCOD_console_set_color_control (con, - int_to_color(fore), - int_to_color(back)); -} - -#endif /* TCOD_CONSOLE_SUPPORT */ - -#ifdef TCOD_IMAGE_SUPPORT -void TCOD_image_clear_wrapper(TCOD_image_t image, - colornum_t color) -{ - TCOD_image_clear (image, - int_to_color(color)); -} - -colornum_t TCOD_image_get_pixel_wrapper(TCOD_image_t image, - int x, int y) -{ - return color_to_int(TCOD_image_get_pixel (image, x, y)); -} - -colornum_t TCOD_image_get_mipmap_pixel_wrapper(TCOD_image_t image, - float x0,float y0, float x1, float y1) -{ - return color_to_int(TCOD_image_get_mipmap_pixel (image, - x0, y0, x1, y1)); -} - -void TCOD_image_put_pixel_wrapper(TCOD_image_t image,int x, int y, - colornum_t col) -{ - TCOD_image_put_pixel (image, x, y, - int_to_color( col)); -} - -void TCOD_image_set_key_color_wrapper(TCOD_image_t image, - colornum_t key_color) -{ - TCOD_image_set_key_color (image, - int_to_color(key_color)); -} -#endif /* TCOD_IMAGE_SUPPORT */ - -#ifdef TCOD_CONSOLE_SUPPORT - -bool TCOD_console_check_for_keypress_wrapper (TCOD_key_t *holder, int flags) -{ - *holder = TCOD_console_check_for_keypress(flags); - return (holder->vk != TCODK_NONE); -} - - -void TCOD_console_wait_for_keypress_wrapper (TCOD_key_t *holder, bool flush) -{ - *holder = TCOD_console_wait_for_keypress(flush); -} - -void TCOD_mouse_get_status_wrapper(TCOD_mouse_t *mouse) { - *mouse=TCOD_mouse_get_status(); -} - -/* Routines to draw hlines, vlines and frames using the double-lined - * characters. */ - -void TCOD_console_double_hline(TCOD_console_t con,int x,int y, int l, TCOD_bkgnd_flag_t flag) { - int i; - for (i=x; i< x+l; i++) TCOD_console_put_char(con,i,y,TCOD_CHAR_DHLINE,flag); -} - -void TCOD_console_double_vline(TCOD_console_t con,int x,int y, int l, TCOD_bkgnd_flag_t flag) { - int i; - for (i=y; i< y+l; i++) TCOD_console_put_char(con,x,i,TCOD_CHAR_DVLINE,flag); -} - - -void TCOD_console_print_double_frame(TCOD_console_t con,int x,int y,int w,int h, bool empty, TCOD_bkgnd_flag_t flag, const char *fmt, ...) { - TCOD_console_data_t *dat = con ? (TCOD_console_data_t *)con : TCOD_ctx.root; - TCOD_console_put_char(con,x,y,TCOD_CHAR_DNW,flag); - TCOD_console_put_char(con,x+w-1,y,TCOD_CHAR_DNE,flag); - TCOD_console_put_char(con,x,y+h-1,TCOD_CHAR_DSW,flag); - TCOD_console_put_char(con,x+w-1,y+h-1,TCOD_CHAR_DSE,flag); - TCOD_console_double_hline(con,x+1,y,w-2, flag); - TCOD_console_double_hline(con,x+1,y+h-1,w-2, flag); - TCOD_console_double_vline(con,x,y+1,h-2, flag); - TCOD_console_double_vline(con,x+w-1,y+1,h-2, flag); - if ( h > 2 ) { - TCOD_console_vline(con,x,y+1,h-2,flag); - TCOD_console_vline(con,x+w-1,y+1,h-2,flag); - if ( empty ) { - TCOD_console_rect(con,x+1,y+1,w-2,h-2,true,flag); - } - } - if (fmt) { - va_list ap; - int xs; - TCOD_color_t tmp; - char *title; - va_start(ap,fmt); - title = TCOD_console_vsprint(fmt,ap); - va_end(ap); - title[w-3]=0; /* truncate if needed */ - xs = x + (w-(int)strlen(title)-2)/2; - tmp=dat->back; /* swap colors */ - dat->back=dat->fore; - dat->fore=tmp; - TCOD_console_print_ex(con,xs,y,TCOD_BKGND_SET,TCOD_LEFT," %s ",title); - tmp=dat->back; /* swap colors */ - dat->back=dat->fore; - dat->fore=tmp; - } -} - - -char *TCOD_console_print_return_string(TCOD_console_t con,int x,int y, int rw, - int rh, TCOD_bkgnd_flag_t flag, - TCOD_alignment_t align, char *msg, bool can_split, bool count_only) { - TCOD_console_print_internal(con,x,y,rw,rh,flag,align,msg,can_split,count_only); - return msg; -} - -#endif /* TCOD_CONSOLE_SUPPORT */ - -colornum_t TCOD_parser_get_color_property_wrapper(TCOD_parser_t parser, const char *name) { - return color_to_int(TCOD_parser_get_color_property(parser,name)); -} - -int TCOD_namegen_get_nb_sets_wrapper(void) { - TCOD_list_t l=TCOD_namegen_get_sets(); - int nb = TCOD_list_size(l); - TCOD_list_delete(l); - return nb; -} - -void TCOD_namegen_get_sets_wrapper(char **sets) { - TCOD_list_t l=TCOD_namegen_get_sets(); - char **it; - int i=0; - for (it=(char**)TCOD_list_begin(l); it != (char **)TCOD_list_end(l); it++) { - sets[i++]=*it; - } -} - -#ifndef TCOD_BARE -int TCOD_sys_get_current_resolution_x() -{ - int x, y; - TCOD_sys_get_current_resolution(&x, &y); - return x; -} - -int TCOD_sys_get_current_resolution_y() -{ - int x, y; - TCOD_sys_get_current_resolution(&x, &y); - return y; -} -#endif - -#ifdef TCOD_CONSOLE_SUPPORT -void TCOD_console_set_key_color_wrapper (TCOD_console_t con, colornum_t c) -{ - TCOD_console_set_key_color(con, int_to_color(c)); -} -#endif +/* +* libtcod +* Copyright (c) 2008-2018 Jice & Mingos & rmtew +* All rights reserved. +* +* Redistribution and use in source and binary forms, with or without +* modification, are permitted provided that the following conditions are met: +* * Redistributions of source code must retain the above copyright +* notice, this list of conditions and the following disclaimer. +* * Redistributions in binary form must reproduce the above copyright +* notice, this list of conditions and the following disclaimer in the +* documentation and/or other materials provided with the distribution. +* * The name of Jice or Mingos may not be used to endorse or promote +* products derived from this software without specific prior written +* permission. +* +* THIS SOFTWARE IS PROVIDED BY JICE, MINGOS AND RMTEW ``AS IS'' AND ANY +* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED +* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE +* DISCLAIMED. IN NO EVENT SHALL JICE, MINGOS OR RMTEW BE LIABLE FOR ANY +* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES +* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; +* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND +* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS +* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +*/ +#include "wrappers.h" + +#include +#include + +#include "console.h" +#include "libtcod_int.h" +#include "namegen.h" + +#define RED_MASK 0x0000FF +#define GREEN_MASK 0x00FF00 +#define BLUE_MASK 0xFF0000 + +TCOD_color_t int_to_color (colornum_t col) { + TCOD_color_t ret; + ret.r = col & RED_MASK; + ret.g = (col & GREEN_MASK) >> 8; + ret.b = (col & BLUE_MASK) >> 16; + return ret; +} + +#define color_to_int(col) (int)(((int)((col).b) << 16) | ((col).g << 8) | (col).r) + +bool TCOD_color_equals_wrapper (colornum_t c1, colornum_t c2) { + return TCOD_color_equals (int_to_color(c1), int_to_color(c2)); +} + +colornum_t TCOD_color_add_wrapper (colornum_t c1, colornum_t c2) { + return color_to_int(TCOD_color_add (int_to_color(c1), + int_to_color(c2))); +} + +colornum_t TCOD_color_subtract_wrapper (colornum_t c1, colornum_t c2) { + return color_to_int(TCOD_color_subtract (int_to_color(c1), + int_to_color(c2))); +} + +colornum_t TCOD_color_multiply_wrapper (colornum_t c1, colornum_t c2) +{ + return color_to_int(TCOD_color_multiply (int_to_color(c1), int_to_color(c2))); +} + +colornum_t TCOD_color_multiply_scalar_wrapper (colornum_t c1, float value) +{ + return color_to_int(TCOD_color_multiply_scalar (int_to_color(c1), + value)); +} + +colornum_t TCOD_color_lerp_wrapper(colornum_t c1, colornum_t c2, float coef) +{ + return color_to_int(TCOD_color_lerp (int_to_color(c1),int_to_color(c2), + coef)); +} + +void TCOD_color_get_HSV_wrapper(colornum_t c,float * h, + float * s, float * v) +{ + TCOD_color_get_HSV (int_to_color(c), h, s, v); +} + +float TCOD_color_get_hue_wrapper (colornum_t c) { + return TCOD_color_get_hue(int_to_color(c)); +} + +float TCOD_color_get_saturation_wrapper (colornum_t c) { + return TCOD_color_get_saturation(int_to_color(c)); +} + +float TCOD_color_get_value_wrapper (colornum_t c) { + return TCOD_color_get_value(int_to_color(c)); +} + +#ifdef TCOD_CONSOLE_SUPPORT + +colornum_t TCOD_console_get_default_background_wrapper(TCOD_console_t con) +{ + return color_to_int(TCOD_console_get_default_background (con)); +} + + +colornum_t TCOD_console_get_default_foreground_wrapper(TCOD_console_t con) +{ + return color_to_int(TCOD_console_get_default_foreground (con)); +} + + +void TCOD_console_set_default_background_wrapper(TCOD_console_t con, + colornum_t col) +{ + TCOD_console_set_default_background (con, + int_to_color(col)); +} + +void TCOD_console_set_default_foreground_wrapper(TCOD_console_t con, + colornum_t col) +{ + TCOD_console_set_default_foreground (con, + int_to_color(col)); +} + +colornum_t TCOD_console_get_char_foreground_wrapper(TCOD_console_t con, + int x, int y) +{ + return color_to_int(TCOD_console_get_char_foreground (con, x, y)); +} + +colornum_t TCOD_console_get_char_background_wrapper(TCOD_console_t con, + int x, int y) +{ + return color_to_int(TCOD_console_get_char_background (con, x, y)); +} + +void TCOD_console_set_char_background_wrapper(TCOD_console_t con,int x, int y, + colornum_t col, + TCOD_bkgnd_flag_t flag) +{ + TCOD_console_set_char_background (con, x, y, int_to_color(col), flag); +} + + +void TCOD_console_set_char_foreground_wrapper(TCOD_console_t con,int x, int y, + colornum_t col) +{ + TCOD_console_set_char_foreground (con, x, y, int_to_color(col)); +} + +void TCOD_console_put_char_ex_wrapper(TCOD_console_t con, int x, int y, + int c, colornum_t fore, colornum_t back) +{ + TCOD_console_put_char_ex (con, x, y, c, int_to_color(fore), + int_to_color(back)); +} + +void TCOD_console_set_fade_wrapper(uint8_t val, colornum_t fade) +{ + TCOD_console_set_fade (val, int_to_color(fade)); +} + +void TCOD_console_fill_background(TCOD_console_t con, int *r, int *g, int *b) { + struct TCOD_Console *dat = con ? (struct TCOD_Console *)con : TCOD_ctx.root; + int i; + TCOD_color_t *curcolor = dat->bg_array; + for (i = 0; i < dat->w*dat->h; i++) { + curcolor->r = *r; + curcolor->g = *g; + curcolor->b = *b; + curcolor++; + r++; + g++; + b++; + } +} + +void TCOD_console_fill_foreground(TCOD_console_t con, int *r, int *g, int *b) { + struct TCOD_Console *dat = con ? (struct TCOD_Console *)con : TCOD_ctx.root; + int i; + TCOD_color_t *curcolor = dat->fg_array; + for (i = 0; i < dat->w*dat->h; i++) { + curcolor->r = *r; + curcolor->g = *g; + curcolor->b = *b; + curcolor++; + r++; + g++; + b++; + } +} + +void TCOD_console_fill_char(TCOD_console_t con, int *arr) { + struct TCOD_Console *dat = con ? (struct TCOD_Console *)con : TCOD_ctx.root; + int i; + for (i = 0; i < dat->w*dat->h; i++) { + dat->ch_array[i] = arr[i]; + } +} + +colornum_t +TCOD_console_get_fading_color_wrapper () +{ + return color_to_int(TCOD_console_get_fading_color()); +} + +void TCOD_console_set_color_control_wrapper(TCOD_colctrl_t con, + colornum_t fore, + colornum_t back) +{ + TCOD_console_set_color_control (con, + int_to_color(fore), + int_to_color(back)); +} + +#endif /* TCOD_CONSOLE_SUPPORT */ + +#ifdef TCOD_IMAGE_SUPPORT +void TCOD_image_clear_wrapper(TCOD_image_t image, + colornum_t color) +{ + TCOD_image_clear (image, + int_to_color(color)); +} + +colornum_t TCOD_image_get_pixel_wrapper(TCOD_image_t image, + int x, int y) +{ + return color_to_int(TCOD_image_get_pixel (image, x, y)); +} + +colornum_t TCOD_image_get_mipmap_pixel_wrapper(TCOD_image_t image, + float x0,float y0, float x1, float y1) +{ + return color_to_int(TCOD_image_get_mipmap_pixel (image, + x0, y0, x1, y1)); +} + +void TCOD_image_put_pixel_wrapper(TCOD_image_t image,int x, int y, + colornum_t col) +{ + TCOD_image_put_pixel (image, x, y, + int_to_color( col)); +} + +void TCOD_image_set_key_color_wrapper(TCOD_image_t image, + colornum_t key_color) +{ + TCOD_image_set_key_color (image, + int_to_color(key_color)); +} +#endif /* TCOD_IMAGE_SUPPORT */ + +#ifdef TCOD_CONSOLE_SUPPORT + +bool TCOD_console_check_for_keypress_wrapper (TCOD_key_t *holder, int flags) +{ + *holder = TCOD_console_check_for_keypress(flags); + return (holder->vk != TCODK_NONE); +} + + +void TCOD_console_wait_for_keypress_wrapper (TCOD_key_t *holder, bool flush) +{ + *holder = TCOD_console_wait_for_keypress(flush); +} + +void TCOD_mouse_get_status_wrapper(TCOD_mouse_t *mouse) { + *mouse=TCOD_mouse_get_status(); +} + +/* Routines to draw hlines, vlines and frames using the double-lined + * characters. */ + +void TCOD_console_double_hline(TCOD_console_t con,int x,int y, int l, TCOD_bkgnd_flag_t flag) { + int i; + for (i=x; i< x+l; i++) TCOD_console_put_char(con,i,y,TCOD_CHAR_DHLINE,flag); +} + +void TCOD_console_double_vline(TCOD_console_t con,int x,int y, int l, TCOD_bkgnd_flag_t flag) { + int i; + for (i=y; i< y+l; i++) TCOD_console_put_char(con,x,i,TCOD_CHAR_DVLINE,flag); +} + + +void TCOD_console_print_double_frame(TCOD_console_t con,int x,int y,int w,int h, bool empty, TCOD_bkgnd_flag_t flag, const char *fmt, ...) { + struct TCOD_Console *dat = con ? (struct TCOD_Console *)con : TCOD_ctx.root; + TCOD_console_put_char(con,x,y,TCOD_CHAR_DNW,flag); + TCOD_console_put_char(con,x+w-1,y,TCOD_CHAR_DNE,flag); + TCOD_console_put_char(con,x,y+h-1,TCOD_CHAR_DSW,flag); + TCOD_console_put_char(con,x+w-1,y+h-1,TCOD_CHAR_DSE,flag); + TCOD_console_double_hline(con,x+1,y,w-2, flag); + TCOD_console_double_hline(con,x+1,y+h-1,w-2, flag); + TCOD_console_double_vline(con,x,y+1,h-2, flag); + TCOD_console_double_vline(con,x+w-1,y+1,h-2, flag); + if ( h > 2 ) { + TCOD_console_vline(con,x,y+1,h-2,flag); + TCOD_console_vline(con,x+w-1,y+1,h-2,flag); + if ( empty ) { + TCOD_console_rect(con,x+1,y+1,w-2,h-2,true,flag); + } + } + if (fmt) { + va_list ap; + int xs; + TCOD_color_t tmp; + char *title; + va_start(ap,fmt); + title = TCOD_console_vsprint(fmt,ap); + va_end(ap); + title[w-3]=0; /* truncate if needed */ + xs = x + (w-(int)strlen(title)-2)/2; + tmp=dat->back; /* swap colors */ + dat->back=dat->fore; + dat->fore=tmp; + TCOD_console_print_ex(con,xs,y,TCOD_BKGND_SET,TCOD_LEFT," %s ",title); + tmp=dat->back; /* swap colors */ + dat->back=dat->fore; + dat->fore=tmp; + } +} + + +char *TCOD_console_print_return_string(TCOD_console_t con,int x,int y, int rw, + int rh, TCOD_bkgnd_flag_t flag, + TCOD_alignment_t align, char *msg, bool can_split, bool count_only) { + TCOD_console_print_internal(con,x,y,rw,rh,flag,align,msg,can_split,count_only); + return msg; +} + +#endif /* TCOD_CONSOLE_SUPPORT */ + +colornum_t TCOD_parser_get_color_property_wrapper(TCOD_parser_t parser, const char *name) { + return color_to_int(TCOD_parser_get_color_property(parser,name)); +} + +int TCOD_namegen_get_nb_sets_wrapper(void) { + TCOD_list_t l=TCOD_namegen_get_sets(); + int nb = TCOD_list_size(l); + TCOD_list_delete(l); + return nb; +} + +void TCOD_namegen_get_sets_wrapper(char **sets) { + TCOD_list_t l=TCOD_namegen_get_sets(); + char **it; + int i=0; + for (it=(char**)TCOD_list_begin(l); it != (char **)TCOD_list_end(l); it++) { + sets[i++]=*it; + } +} + +#ifndef TCOD_BARE +int TCOD_sys_get_current_resolution_x() +{ + int x, y; + TCOD_sys_get_current_resolution(&x, &y); + return x; +} + +int TCOD_sys_get_current_resolution_y() +{ + int x, y; + TCOD_sys_get_current_resolution(&x, &y); + return y; +} +#endif + +#ifdef TCOD_CONSOLE_SUPPORT +void TCOD_console_set_key_color_wrapper (TCOD_console_t con, colornum_t c) +{ + TCOD_console_set_key_color(con, int_to_color(c)); +} +#endif diff --git a/tcod_sys/libtcod/include/wrappers.h b/tcod_sys/libtcod/src/libtcod/wrappers.h similarity index 99% rename from tcod_sys/libtcod/include/wrappers.h rename to tcod_sys/libtcod/src/libtcod/wrappers.h index ed0f6bf0c..8a9112831 100644 --- a/tcod_sys/libtcod/include/wrappers.h +++ b/tcod_sys/libtcod/src/libtcod/wrappers.h @@ -28,7 +28,7 @@ #ifndef WRAPPERS_H #define WRAPPERS_H -#include "libtcod_portability.h" +#include "portability.h" #include "console_types.h" #include "image.h" #include "mouse.h" diff --git a/tcod_sys/libtcod/src/zip.cpp b/tcod_sys/libtcod/src/libtcod/zip.cpp similarity index 95% rename from tcod_sys/libtcod/src/zip.cpp rename to tcod_sys/libtcod/src/libtcod/zip.cpp index cfb5b8661..3d8ee70a3 100644 --- a/tcod_sys/libtcod/src/zip.cpp +++ b/tcod_sys/libtcod/src/libtcod/zip.cpp @@ -1,132 +1,132 @@ -/* -* libtcod -* Copyright (c) 2008-2018 Jice & Mingos & rmtew -* All rights reserved. -* -* Redistribution and use in source and binary forms, with or without -* modification, are permitted provided that the following conditions are met: -* * Redistributions of source code must retain the above copyright -* notice, this list of conditions and the following disclaimer. -* * Redistributions in binary form must reproduce the above copyright -* notice, this list of conditions and the following disclaimer in the -* documentation and/or other materials provided with the distribution. -* * The name of Jice or Mingos may not be used to endorse or promote -* products derived from this software without specific prior written -* permission. -* -* THIS SOFTWARE IS PROVIDED BY JICE, MINGOS AND RMTEW ``AS IS'' AND ANY -* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED -* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE -* DISCLAIMED. IN NO EVENT SHALL JICE, MINGOS OR RMTEW BE LIABLE FOR ANY -* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES -* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; -* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND -* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS -* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. -*/ -#include - -TCODZip::TCODZip() { - data=TCOD_zip_new(); -} - -TCODZip::~TCODZip() { - TCOD_zip_delete(data); -} - -void TCODZip::putChar(char val) { - TCOD_zip_put_char(data,val); -} - -void TCODZip::putInt(int val) { - TCOD_zip_put_int(data,val); -} - -void TCODZip::putFloat(float val) { - TCOD_zip_put_float(data,val); -} - -void TCODZip::putString(const char *val) { - TCOD_zip_put_string(data,val); -} - -void TCODZip::putData(int nbBytes, const void *pdata) { - TCOD_zip_put_data(data,nbBytes,pdata); -} - -void TCODZip::putColor(const TCODColor *val) { - TCOD_color_t col; - col.r=val->r; - col.g=val->g; - col.b=val->b; - TCOD_zip_put_color(data,col); -} - -#ifdef TCOD_IMAGE_SUPPORT -void TCODZip::putImage(const TCODImage *val) { - TCOD_zip_put_image(data,val->data); -} -#endif - -#ifdef TCOD_CONSOLE_SUPPORT -void TCODZip::putConsole(const TCODConsole *val) { - TCOD_zip_put_console(data,val->data); -} -#endif - -int TCODZip::saveToFile(const char *filename) { - return TCOD_zip_save_to_file(data,filename); -} - -int TCODZip::loadFromFile(const char *filename) { - return TCOD_zip_load_from_file(data,filename); -} - -char TCODZip::getChar() { - return TCOD_zip_get_char(data); -} - -int TCODZip::getInt() { - return TCOD_zip_get_int(data); -} - -float TCODZip::getFloat() { - return TCOD_zip_get_float(data); -} - -const char *TCODZip::getString() { - return TCOD_zip_get_string(data); -} - -int TCODZip::getData(int nbBytes, void *pdata) { - return TCOD_zip_get_data(data,nbBytes,pdata); -} - -TCODColor TCODZip::getColor() { - return TCODColor(TCOD_zip_get_color(data)); -} - -#ifdef TCOD_IMAGE_SUPPORT -TCODImage *TCODZip::getImage() { - return new TCODImage(TCOD_zip_get_image(data)); -} -#endif - -#ifdef TCOD_CONSOLE_SUPPORT -TCODConsole *TCODZip::getConsole() { - return new TCODConsole(TCOD_zip_get_console(data)); -} -#endif - -uint32_t TCODZip::getCurrentBytes() const { - return TCOD_zip_get_current_bytes(data); -} - -uint32_t TCODZip::getRemainingBytes() const { - return TCOD_zip_get_remaining_bytes(data); -} - -void TCODZip::skipBytes(uint32_t nbBytes) { - TCOD_zip_skip_bytes(data,nbBytes); -} +/* +* libtcod +* Copyright (c) 2008-2018 Jice & Mingos & rmtew +* All rights reserved. +* +* Redistribution and use in source and binary forms, with or without +* modification, are permitted provided that the following conditions are met: +* * Redistributions of source code must retain the above copyright +* notice, this list of conditions and the following disclaimer. +* * Redistributions in binary form must reproduce the above copyright +* notice, this list of conditions and the following disclaimer in the +* documentation and/or other materials provided with the distribution. +* * The name of Jice or Mingos may not be used to endorse or promote +* products derived from this software without specific prior written +* permission. +* +* THIS SOFTWARE IS PROVIDED BY JICE, MINGOS AND RMTEW ``AS IS'' AND ANY +* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED +* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE +* DISCLAIMED. IN NO EVENT SHALL JICE, MINGOS OR RMTEW BE LIABLE FOR ANY +* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES +* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; +* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND +* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS +* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +*/ +#include "zip.hpp" + +TCODZip::TCODZip() { + data=TCOD_zip_new(); +} + +TCODZip::~TCODZip() { + TCOD_zip_delete(data); +} + +void TCODZip::putChar(char val) { + TCOD_zip_put_char(data,val); +} + +void TCODZip::putInt(int val) { + TCOD_zip_put_int(data,val); +} + +void TCODZip::putFloat(float val) { + TCOD_zip_put_float(data,val); +} + +void TCODZip::putString(const char *val) { + TCOD_zip_put_string(data,val); +} + +void TCODZip::putData(int nbBytes, const void *pdata) { + TCOD_zip_put_data(data,nbBytes,pdata); +} + +void TCODZip::putColor(const TCODColor *val) { + TCOD_color_t col; + col.r=val->r; + col.g=val->g; + col.b=val->b; + TCOD_zip_put_color(data,col); +} + +#ifdef TCOD_IMAGE_SUPPORT +void TCODZip::putImage(const TCODImage *val) { + TCOD_zip_put_image(data,val->data); +} +#endif + +#ifdef TCOD_CONSOLE_SUPPORT +void TCODZip::putConsole(const TCODConsole *val) { + TCOD_zip_put_console(data,val->data); +} +#endif + +int TCODZip::saveToFile(const char *filename) { + return TCOD_zip_save_to_file(data,filename); +} + +int TCODZip::loadFromFile(const char *filename) { + return TCOD_zip_load_from_file(data,filename); +} + +char TCODZip::getChar() { + return TCOD_zip_get_char(data); +} + +int TCODZip::getInt() { + return TCOD_zip_get_int(data); +} + +float TCODZip::getFloat() { + return TCOD_zip_get_float(data); +} + +const char *TCODZip::getString() { + return TCOD_zip_get_string(data); +} + +int TCODZip::getData(int nbBytes, void *pdata) { + return TCOD_zip_get_data(data,nbBytes,pdata); +} + +TCODColor TCODZip::getColor() { + return TCODColor(TCOD_zip_get_color(data)); +} + +#ifdef TCOD_IMAGE_SUPPORT +TCODImage *TCODZip::getImage() { + return new TCODImage(TCOD_zip_get_image(data)); +} +#endif + +#ifdef TCOD_CONSOLE_SUPPORT +TCODConsole *TCODZip::getConsole() { + return new TCODConsole(TCOD_zip_get_console(data)); +} +#endif + +uint32_t TCODZip::getCurrentBytes() const { + return TCOD_zip_get_current_bytes(data); +} + +uint32_t TCODZip::getRemainingBytes() const { + return TCOD_zip_get_remaining_bytes(data); +} + +void TCODZip::skipBytes(uint32_t nbBytes) { + TCOD_zip_skip_bytes(data,nbBytes); +} diff --git a/tcod_sys/libtcod/include/zip.h b/tcod_sys/libtcod/src/libtcod/zip.h similarity index 97% rename from tcod_sys/libtcod/include/zip.h rename to tcod_sys/libtcod/src/libtcod/zip.h index 5d0b449fb..e8760847a 100644 --- a/tcod_sys/libtcod/include/zip.h +++ b/tcod_sys/libtcod/src/libtcod/zip.h @@ -28,7 +28,7 @@ #ifndef _TCOD_ZIP_H #define _TCOD_ZIP_H -#include "libtcod_portability.h" +#include "portability.h" #include "color.h" #include "console_types.h" #include "image.h" @@ -36,7 +36,8 @@ #ifdef __cplusplus extern "C" { #endif -typedef void *TCOD_zip_t; +struct TCOD_Zip; +typedef struct TCOD_Zip *TCOD_zip_t; TCODLIB_API TCOD_zip_t TCOD_zip_new(void); TCODLIB_API void TCOD_zip_delete(TCOD_zip_t zip); diff --git a/tcod_sys/libtcod/include/zip.hpp b/tcod_sys/libtcod/src/libtcod/zip.hpp similarity index 100% rename from tcod_sys/libtcod/include/zip.hpp rename to tcod_sys/libtcod/src/libtcod/zip.hpp diff --git a/tcod_sys/libtcod/src/zip_c.c b/tcod_sys/libtcod/src/libtcod/zip_c.c similarity index 95% rename from tcod_sys/libtcod/src/zip_c.c rename to tcod_sys/libtcod/src/libtcod/zip_c.c index 583865fbf..90324a8b1 100644 --- a/tcod_sys/libtcod/src/zip_c.c +++ b/tcod_sys/libtcod/src/libtcod/zip_c.c @@ -1,390 +1,390 @@ -/* -* libtcod -* Copyright (c) 2008-2018 Jice & Mingos & rmtew -* All rights reserved. -* -* Redistribution and use in source and binary forms, with or without -* modification, are permitted provided that the following conditions are met: -* * Redistributions of source code must retain the above copyright -* notice, this list of conditions and the following disclaimer. -* * Redistributions in binary form must reproduce the above copyright -* notice, this list of conditions and the following disclaimer in the -* documentation and/or other materials provided with the distribution. -* * The name of Jice or Mingos may not be used to endorse or promote -* products derived from this software without specific prior written -* permission. -* -* THIS SOFTWARE IS PROVIDED BY JICE, MINGOS AND RMTEW ``AS IS'' AND ANY -* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED -* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE -* DISCLAIMED. IN NO EVENT SHALL JICE, MINGOS OR RMTEW BE LIABLE FOR ANY -* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES -* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; -* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND -* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS -* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. -*/ -#include - -#include -#include -#include - -#include -#include -#include - -typedef struct { - TCOD_list_t buffer; /* list */ - uintptr_t ibuffer; /* byte buffer. bytes are send into buffer 4 by 4 (32 bits OS) or 8 by 8(64 bits OS) */ - int isize; /* number of bytes in ibuffer */ - int bsize; /* number of bytes in buffer */ - int offset; /* current reading position */ -} zip_data_t; - -TCOD_zip_t TCOD_zip_new(void) { - zip_data_t *ret=(zip_data_t *)calloc(sizeof(zip_data_t),1); - return (TCOD_zip_t)ret; -} - -void TCOD_zip_delete(TCOD_zip_t pzip) { - zip_data_t *zip=(zip_data_t *)pzip; - if ( zip->buffer != NULL ) TCOD_list_delete(zip->buffer); - free(zip); -} - - -/* output interface */ -void TCOD_zip_put_char(TCOD_zip_t pzip, char val) { - zip_data_t *zip=(zip_data_t *)pzip; - uintptr_t iv=(uintptr_t)(uint8_t)val; - /* store one byte in ibuffer */ - switch (zip->isize) { - case 0 : zip->ibuffer|=iv; break; - case 1 : zip->ibuffer|=(iv<<8); break; - case 2 : zip->ibuffer|=(iv<<16); break; - case 3 : zip->ibuffer|=(iv<<24); break; -#ifdef TCOD_64BITS - /* for 64 bits OS */ - case 4 : zip->ibuffer|=(iv<<32); break; - case 5 : zip->ibuffer|=(iv<<40); break; - case 6 : zip->ibuffer|=(iv<<48); break; - case 7 : zip->ibuffer|=(iv<<56); break; -#endif - } - zip->isize++; - zip->bsize++; - if (zip->isize == sizeof(uintptr_t) ) { - /* ibuffer full. send it to buffer */ - if (!zip->buffer) zip->buffer=TCOD_list_new(); - TCOD_list_push(zip->buffer,(void *)zip->ibuffer); - zip->isize = 0; - zip->ibuffer = 0; - } -} - -void TCOD_zip_put_int(TCOD_zip_t pzip, int val) { -#ifndef TCOD_64BITS - zip_data_t *zip=(zip_data_t *)pzip; - if ( zip->isize == 0 ) { - /* the buffer is padded. read 4 bytes */ - if (!zip->buffer) zip->buffer=TCOD_list_new(); - TCOD_list_push(zip->buffer,(void *)val); - zip->bsize += sizeof(uintptr_t); - } else { -#endif - /* the buffer is not padded. read 4x1 byte */ - TCOD_zip_put_char(pzip,(char)(val&0xFF)); - TCOD_zip_put_char(pzip,(char)((val&0xFF00)>>8)); - TCOD_zip_put_char(pzip,(char)((val&0xFF0000)>>16)); - TCOD_zip_put_char(pzip,(char)((val&0xFF000000)>>24)); -#ifndef TCOD_64BITS - } -#endif -} - -void TCOD_zip_put_float(TCOD_zip_t pzip, float val) { - TCOD_zip_put_int(pzip,* (int *)(&val) ); -} - -void TCOD_zip_put_string(TCOD_zip_t pzip, const char *val) { - if (val == NULL) TCOD_zip_put_int(pzip,-1); - else { - size_t l=strlen(val),i; - TCOD_zip_put_int(pzip,(int)l); - for (i=0; i <= l; i++) TCOD_zip_put_char(pzip,val[i]); - } -} - -void TCOD_zip_put_data(TCOD_zip_t pzip, int nbBytes, const void *data) { - if (data == NULL) TCOD_zip_put_int(pzip,-1); - else { - char *val=(char *)data; - int i; - TCOD_zip_put_int(pzip,nbBytes); - for (i=0; i< nbBytes; i++) TCOD_zip_put_char(pzip,val[i]); - } -} - -void TCOD_zip_put_color(TCOD_zip_t zip, const TCOD_color_t val) { - TCOD_zip_put_char(zip,val.r); - TCOD_zip_put_char(zip,val.g); - TCOD_zip_put_char(zip,val.b); -} - -#ifdef TCOD_IMAGE_SUPPORT -void TCOD_zip_put_image(TCOD_zip_t zip, const TCOD_image_t val) { - int w,h,x,y; - TCOD_image_get_size(val, &w,&h); - TCOD_zip_put_int(zip,w); - TCOD_zip_put_int(zip,h); - for (y=0; y < h; y++) { - for (x=0; x < w; x++ ) { - TCOD_zip_put_color(zip,TCOD_image_get_pixel(val,x,y)); - } - } -} -#endif - -#ifdef TCOD_CONSOLE_SUPPORT -void TCOD_zip_put_console(TCOD_zip_t zip, const TCOD_console_t val) { - int w,h,x,y; - w=TCOD_console_get_width(val); - h=TCOD_console_get_height(val); - TCOD_zip_put_int(zip,w); - TCOD_zip_put_int(zip,h); - for (y=0; y < h; y++) { - for (x=0; x < w; x++ ) { - TCOD_zip_put_char(zip,TCOD_console_get_char(val,x,y)); - TCOD_zip_put_color(zip,TCOD_console_get_char_foreground(val,x,y)); - TCOD_zip_put_color(zip,TCOD_console_get_char_background(val,x,y)); - } - } -} -#endif - -int TCOD_zip_save_to_file(TCOD_zip_t pzip, const char *filename) { - zip_data_t *zip=(zip_data_t *)pzip; - gzFile f=gzopen(filename,"wb"); - int l=zip->bsize, ret; - void *buf; - if (!f) return 0; - gzwrite(f,&l,sizeof(int)); - if (l==0) { - gzclose(f); - return 0; - } - if ( zip->isize > 0 ) { - /* send remaining bytes from ibuffer to buffer */ - if (!zip->buffer) zip->buffer=TCOD_list_new(); - TCOD_list_push(zip->buffer,(void *)zip->ibuffer); - zip->isize = 0; - zip->ibuffer = 0; - } - buf=(void *)TCOD_list_begin(zip->buffer); - ret=gzwrite(f,buf,l); - if (ret != l) { - gzclose(f); - return 0; - } - ret=gzclose(f); - if (ret != Z_OK) - return 0; - return l; -} - - -/* input interface */ -int TCOD_zip_load_from_file(TCOD_zip_t pzip, const char *filename) { - zip_data_t *zip=(zip_data_t *)pzip; - gzFile f=gzopen(filename,"rb"); - int l,lread; - void *buf; - int wordsize=sizeof(uintptr_t); - if (!f) return 0; - gzread(f,&l,sizeof(int)); - if (l==0) { - gzclose(f); - return 0; - } - if ( zip->buffer) { - TCOD_list_delete(zip->buffer); - memset(zip,0,sizeof(zip_data_t)); - } - zip->buffer=TCOD_list_allocate((l+wordsize-1)/wordsize); - TCOD_list_set_size(zip->buffer,(l+wordsize-1)/wordsize); - buf=(void *)TCOD_list_begin(zip->buffer); - lread=gzread(f,buf,l); - gzclose(f); - return lread == 0 ? l : lread; -} - -char TCOD_zip_get_char(TCOD_zip_t pzip) { - zip_data_t *zip=(zip_data_t *)pzip; - char c=0; - if ( zip->isize == 0 ) { - /* ibuffer is empty. get 4 or 8 new bytes from buffer */ - zip->ibuffer=(uintptr_t)TCOD_list_get(zip->buffer,zip->offset); - zip->offset++; - zip->isize=sizeof(uintptr_t); - } - /* read one byte from ibuffer */ -#ifdef TCOD_64BITS - switch(zip->isize) { - case 8: c= zip->ibuffer&0xFFL; break; - case 7: c= (zip->ibuffer>>8) & 0xFFL; break; - case 6: c= (zip->ibuffer>>16) & 0xFFL; break; - case 5: c= (zip->ibuffer>>24) & 0xFFL; break; - case 4: c= (zip->ibuffer>>32) & 0xFFL; break; - case 3: c= (zip->ibuffer>>40) & 0xFFL; break; - case 2: c= (zip->ibuffer>>48) & 0xFFL; break; - case 1: c= (zip->ibuffer>>56) & 0xFFL; break; - } -#else - switch(zip->isize) { - case 4: c= (char)(zip->ibuffer&0xFF); break; - case 3: c= (char)((zip->ibuffer&0xFF00)>>8); break; - case 2: c= (char)((zip->ibuffer&0xFF0000)>>16); break; - case 1: c= (char)((zip->ibuffer&0xFF000000)>>24); break; - } -#endif - zip->isize--; - return c; -} - -int TCOD_zip_get_int(TCOD_zip_t pzip) { -#ifndef TCOD_64BITS - zip_data_t *zip=(zip_data_t *)pzip; - if ( zip->isize == 0 ) { - /* buffer is padded. read 4 bytes */ - int i=(int)TCOD_list_get(zip->buffer,zip->offset); - zip->offset++; - return i; - } else { -#endif - /* buffer is not padded. read 4x 1 byte */ - uint32_t i1=(uint32_t)(uint8_t)TCOD_zip_get_char(pzip); - uint32_t i2=(uint32_t)(uint8_t)TCOD_zip_get_char(pzip); - uint32_t i3=(uint32_t)(uint8_t)TCOD_zip_get_char(pzip); - uint32_t i4=(uint32_t)(uint8_t)TCOD_zip_get_char(pzip); - - return i1 | (i2<<8) | (i3<<16) | (i4<<24); -#ifndef TCOD_64BITS - } -#endif -} - -float TCOD_zip_get_float(TCOD_zip_t pzip) { - int i=TCOD_zip_get_int(pzip); - return *(float *)(&i); -} - -TCOD_color_t TCOD_zip_get_color(TCOD_zip_t pzip) { - TCOD_color_t col; - col.r=TCOD_zip_get_char(pzip); - col.g=TCOD_zip_get_char(pzip); - col.b=TCOD_zip_get_char(pzip); - return col; -} - -const char *TCOD_zip_get_string(TCOD_zip_t pzip) { - zip_data_t *zip=(zip_data_t *)pzip; - int l=TCOD_zip_get_int(pzip); - const char *ret=(const char *)TCOD_list_begin(zip->buffer); - int boffset; /* offset in bytes */ - if ( l == -1 ) return NULL; - boffset=zip->offset*sizeof(uintptr_t)-zip->isize; /* current offset */ - ret += boffset; /* the string address in buffer */ - boffset += l+1; /* new offset */ - /* update ibuffer */ - zip->offset = (boffset+sizeof(uintptr_t)-1)/sizeof(uintptr_t); - zip->isize = boffset%sizeof(uintptr_t); - if ( zip->isize != 0 ) { - zip->isize=sizeof(uintptr_t)-zip->isize; - zip->ibuffer=(uintptr_t)TCOD_list_get(zip->buffer,zip->offset-1); - } - return ret; -} - -int TCOD_zip_get_data(TCOD_zip_t pzip, int nbBytes, void *data) { - zip_data_t *zip=(zip_data_t *)pzip; - int l=TCOD_zip_get_int(pzip),i; - const char *in=(const char *)TCOD_list_begin(zip->buffer); - char *out=(char *)data; - int boffset; /* offset in bytes */ - if ( l == -1 ) return 0; - boffset=zip->offset*sizeof(uintptr_t)-zip->isize; /* current offset */ - in += boffset; /* the data address in buffer */ - /* copy it to data */ - for (i=0; i < MIN(l,nbBytes); i++ ) { - *(out++)=*(in++); - boffset++; - } - /* update ibuffer */ - zip->offset = (boffset+sizeof(uintptr_t)-1)/sizeof(uintptr_t); - zip->isize = boffset%sizeof(uintptr_t); - if ( zip->isize != 0 ) { - zip->isize=sizeof(uintptr_t)-zip->isize; - zip->ibuffer=(uintptr_t)TCOD_list_get(zip->buffer,zip->offset-1); - } - return l; -} - -#ifdef TCOD_IMAGE_SUPPORT -TCOD_image_t TCOD_zip_get_image(TCOD_zip_t pzip) { - TCOD_image_t ret; - int w,h,x,y; - w=TCOD_zip_get_int(pzip); - h=TCOD_zip_get_int(pzip); - ret=TCOD_image_new(w,h); - for (y=0; y < h; y++) { - for (x=0; x < w; x++ ) { - TCOD_image_put_pixel(ret, x,y,TCOD_zip_get_color(pzip)); - } - } - return ret; -} -#endif - -#ifdef TCOD_CONSOLE_SUPPORT -TCOD_console_t TCOD_zip_get_console(TCOD_zip_t pzip) { - TCOD_console_t ret; - int w,h,x,y; - w=TCOD_zip_get_int(pzip); - h=TCOD_zip_get_int(pzip); - ret=TCOD_console_new(w,h); - for (y=0; y < h; y++) { - for (x=0; x < w; x++ ) { - TCOD_console_set_char(ret, x,y,TCOD_zip_get_char(pzip)); - TCOD_console_set_char_foreground(ret, x,y,TCOD_zip_get_color(pzip)); - TCOD_console_set_char_background(ret, x,y,TCOD_zip_get_color(pzip), TCOD_BKGND_SET); - } - } - return ret; -} -#endif - -uint32_t TCOD_zip_get_current_bytes(TCOD_zip_t pzip) { - zip_data_t *zip=(zip_data_t *)pzip; - if (!zip->buffer) zip->buffer=TCOD_list_new(); - return TCOD_list_size(zip->buffer)*sizeof(uintptr_t)+zip->isize; -} - -uint32_t TCOD_zip_get_remaining_bytes(TCOD_zip_t pzip) { - zip_data_t *zip=(zip_data_t *)pzip; - if (!zip->buffer) zip->buffer=TCOD_list_new(); - return (TCOD_list_size(zip->buffer) - zip->offset) * sizeof(uintptr_t) + zip->isize; -} - -void TCOD_zip_skip_bytes(TCOD_zip_t pzip, uint32_t nbBytes) { - zip_data_t *zip=(zip_data_t *)pzip; - uint32_t boffset=zip->offset*sizeof(uintptr_t)-zip->isize+ nbBytes; /* new offset */ - TCOD_IFNOT(boffset <= TCOD_list_size(zip->buffer)*sizeof(uintptr_t)) return; - zip->offset = (boffset+sizeof(uintptr_t)-1)/sizeof(uintptr_t); - zip->isize = boffset%sizeof(uintptr_t); - if ( zip->isize != 0 ) { - zip->isize=sizeof(uintptr_t)-zip->isize; - zip->ibuffer=(uintptr_t)TCOD_list_get(zip->buffer,zip->offset-1); - } -} +/* +* libtcod +* Copyright (c) 2008-2018 Jice & Mingos & rmtew +* All rights reserved. +* +* Redistribution and use in source and binary forms, with or without +* modification, are permitted provided that the following conditions are met: +* * Redistributions of source code must retain the above copyright +* notice, this list of conditions and the following disclaimer. +* * Redistributions in binary form must reproduce the above copyright +* notice, this list of conditions and the following disclaimer in the +* documentation and/or other materials provided with the distribution. +* * The name of Jice or Mingos may not be used to endorse or promote +* products derived from this software without specific prior written +* permission. +* +* THIS SOFTWARE IS PROVIDED BY JICE, MINGOS AND RMTEW ``AS IS'' AND ANY +* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED +* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE +* DISCLAIMED. IN NO EVENT SHALL JICE, MINGOS OR RMTEW BE LIABLE FOR ANY +* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES +* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; +* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND +* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS +* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +*/ +#include "zip.h" + +#include +#include +#include + +#include "console.h" +#include "libtcod_int.h" +#include "utility.h" + +typedef struct TCOD_Zip { + TCOD_list_t buffer; /* list */ + uintptr_t ibuffer; /* byte buffer. bytes are send into buffer 4 by 4 (32 bits OS) or 8 by 8(64 bits OS) */ + int isize; /* number of bytes in ibuffer */ + int bsize; /* number of bytes in buffer */ + int offset; /* current reading position */ +} zip_data_t; + +TCOD_zip_t TCOD_zip_new(void) { + zip_data_t *ret=(zip_data_t *)calloc(sizeof(zip_data_t),1); + return (TCOD_zip_t)ret; +} + +void TCOD_zip_delete(TCOD_zip_t pzip) { + zip_data_t *zip=(zip_data_t *)pzip; + if ( zip->buffer != NULL ) TCOD_list_delete(zip->buffer); + free(zip); +} + + +/* output interface */ +void TCOD_zip_put_char(TCOD_zip_t pzip, char val) { + zip_data_t *zip=(zip_data_t *)pzip; + uintptr_t iv=(uintptr_t)(uint8_t)val; + /* store one byte in ibuffer */ + switch (zip->isize) { + case 0 : zip->ibuffer|=iv; break; + case 1 : zip->ibuffer|=(iv<<8); break; + case 2 : zip->ibuffer|=(iv<<16); break; + case 3 : zip->ibuffer|=(iv<<24); break; +#ifdef TCOD_64BITS + /* for 64 bits OS */ + case 4 : zip->ibuffer|=(iv<<32); break; + case 5 : zip->ibuffer|=(iv<<40); break; + case 6 : zip->ibuffer|=(iv<<48); break; + case 7 : zip->ibuffer|=(iv<<56); break; +#endif + } + zip->isize++; + zip->bsize++; + if (zip->isize == sizeof(uintptr_t) ) { + /* ibuffer full. send it to buffer */ + if (!zip->buffer) zip->buffer=TCOD_list_new(); + TCOD_list_push(zip->buffer,(void *)zip->ibuffer); + zip->isize = 0; + zip->ibuffer = 0; + } +} + +void TCOD_zip_put_int(TCOD_zip_t pzip, int val) { +#ifndef TCOD_64BITS + zip_data_t *zip=(zip_data_t *)pzip; + if ( zip->isize == 0 ) { + /* the buffer is padded. read 4 bytes */ + if (!zip->buffer) zip->buffer=TCOD_list_new(); + TCOD_list_push(zip->buffer,(void *)val); + zip->bsize += sizeof(uintptr_t); + } else { +#endif + /* the buffer is not padded. read 4x1 byte */ + TCOD_zip_put_char(pzip,(char)(val&0xFF)); + TCOD_zip_put_char(pzip,(char)((val&0xFF00)>>8)); + TCOD_zip_put_char(pzip,(char)((val&0xFF0000)>>16)); + TCOD_zip_put_char(pzip,(char)((val&0xFF000000)>>24)); +#ifndef TCOD_64BITS + } +#endif +} + +void TCOD_zip_put_float(TCOD_zip_t pzip, float val) { + TCOD_zip_put_int(pzip,* (int *)(&val) ); +} + +void TCOD_zip_put_string(TCOD_zip_t pzip, const char *val) { + if (val == NULL) TCOD_zip_put_int(pzip,-1); + else { + size_t l=strlen(val),i; + TCOD_zip_put_int(pzip,(int)l); + for (i=0; i <= l; i++) TCOD_zip_put_char(pzip,val[i]); + } +} + +void TCOD_zip_put_data(TCOD_zip_t pzip, int nbBytes, const void *data) { + if (data == NULL) TCOD_zip_put_int(pzip,-1); + else { + char *val=(char *)data; + int i; + TCOD_zip_put_int(pzip,nbBytes); + for (i=0; i< nbBytes; i++) TCOD_zip_put_char(pzip,val[i]); + } +} + +void TCOD_zip_put_color(TCOD_zip_t zip, const TCOD_color_t val) { + TCOD_zip_put_char(zip,val.r); + TCOD_zip_put_char(zip,val.g); + TCOD_zip_put_char(zip,val.b); +} + +#ifdef TCOD_IMAGE_SUPPORT +void TCOD_zip_put_image(TCOD_zip_t zip, const TCOD_image_t val) { + int w,h,x,y; + TCOD_image_get_size(val, &w,&h); + TCOD_zip_put_int(zip,w); + TCOD_zip_put_int(zip,h); + for (y=0; y < h; y++) { + for (x=0; x < w; x++ ) { + TCOD_zip_put_color(zip,TCOD_image_get_pixel(val,x,y)); + } + } +} +#endif + +#ifdef TCOD_CONSOLE_SUPPORT +void TCOD_zip_put_console(TCOD_zip_t zip, const TCOD_console_t val) { + int w,h,x,y; + w=TCOD_console_get_width(val); + h=TCOD_console_get_height(val); + TCOD_zip_put_int(zip,w); + TCOD_zip_put_int(zip,h); + for (y=0; y < h; y++) { + for (x=0; x < w; x++ ) { + TCOD_zip_put_char(zip,TCOD_console_get_char(val,x,y)); + TCOD_zip_put_color(zip,TCOD_console_get_char_foreground(val,x,y)); + TCOD_zip_put_color(zip,TCOD_console_get_char_background(val,x,y)); + } + } +} +#endif + +int TCOD_zip_save_to_file(TCOD_zip_t pzip, const char *filename) { + zip_data_t *zip=(zip_data_t *)pzip; + gzFile f=gzopen(filename,"wb"); + int l=zip->bsize, ret; + void *buf; + if (!f) return 0; + gzwrite(f,&l,sizeof(int)); + if (l==0) { + gzclose(f); + return 0; + } + if ( zip->isize > 0 ) { + /* send remaining bytes from ibuffer to buffer */ + if (!zip->buffer) zip->buffer=TCOD_list_new(); + TCOD_list_push(zip->buffer,(void *)zip->ibuffer); + zip->isize = 0; + zip->ibuffer = 0; + } + buf=(void *)TCOD_list_begin(zip->buffer); + ret=gzwrite(f,buf,l); + if (ret != l) { + gzclose(f); + return 0; + } + ret=gzclose(f); + if (ret != Z_OK) + return 0; + return l; +} + + +/* input interface */ +int TCOD_zip_load_from_file(TCOD_zip_t pzip, const char *filename) { + zip_data_t *zip=(zip_data_t *)pzip; + gzFile f=gzopen(filename,"rb"); + int l,lread; + void *buf; + int wordsize=sizeof(uintptr_t); + if (!f) return 0; + gzread(f,&l,sizeof(int)); + if (l==0) { + gzclose(f); + return 0; + } + if ( zip->buffer) { + TCOD_list_delete(zip->buffer); + memset(zip,0,sizeof(zip_data_t)); + } + zip->buffer=TCOD_list_allocate((l+wordsize-1)/wordsize); + TCOD_list_set_size(zip->buffer,(l+wordsize-1)/wordsize); + buf=(void *)TCOD_list_begin(zip->buffer); + lread=gzread(f,buf,l); + gzclose(f); + return lread == 0 ? l : lread; +} + +char TCOD_zip_get_char(TCOD_zip_t pzip) { + zip_data_t *zip=(zip_data_t *)pzip; + char c=0; + if ( zip->isize == 0 ) { + /* ibuffer is empty. get 4 or 8 new bytes from buffer */ + zip->ibuffer=(uintptr_t)TCOD_list_get(zip->buffer,zip->offset); + zip->offset++; + zip->isize=sizeof(uintptr_t); + } + /* read one byte from ibuffer */ +#ifdef TCOD_64BITS + switch(zip->isize) { + case 8: c= zip->ibuffer&0xFFL; break; + case 7: c= (zip->ibuffer>>8) & 0xFFL; break; + case 6: c= (zip->ibuffer>>16) & 0xFFL; break; + case 5: c= (zip->ibuffer>>24) & 0xFFL; break; + case 4: c= (zip->ibuffer>>32) & 0xFFL; break; + case 3: c= (zip->ibuffer>>40) & 0xFFL; break; + case 2: c= (zip->ibuffer>>48) & 0xFFL; break; + case 1: c= (zip->ibuffer>>56) & 0xFFL; break; + } +#else + switch(zip->isize) { + case 4: c= (char)(zip->ibuffer&0xFF); break; + case 3: c= (char)((zip->ibuffer&0xFF00)>>8); break; + case 2: c= (char)((zip->ibuffer&0xFF0000)>>16); break; + case 1: c= (char)((zip->ibuffer&0xFF000000)>>24); break; + } +#endif + zip->isize--; + return c; +} + +int TCOD_zip_get_int(TCOD_zip_t pzip) { +#ifndef TCOD_64BITS + zip_data_t *zip=(zip_data_t *)pzip; + if ( zip->isize == 0 ) { + /* buffer is padded. read 4 bytes */ + int i=(int)TCOD_list_get(zip->buffer,zip->offset); + zip->offset++; + return i; + } else { +#endif + /* buffer is not padded. read 4x 1 byte */ + uint32_t i1=(uint32_t)(uint8_t)TCOD_zip_get_char(pzip); + uint32_t i2=(uint32_t)(uint8_t)TCOD_zip_get_char(pzip); + uint32_t i3=(uint32_t)(uint8_t)TCOD_zip_get_char(pzip); + uint32_t i4=(uint32_t)(uint8_t)TCOD_zip_get_char(pzip); + + return i1 | (i2<<8) | (i3<<16) | (i4<<24); +#ifndef TCOD_64BITS + } +#endif +} + +float TCOD_zip_get_float(TCOD_zip_t pzip) { + int i=TCOD_zip_get_int(pzip); + return *(float *)(&i); +} + +TCOD_color_t TCOD_zip_get_color(TCOD_zip_t pzip) { + TCOD_color_t col; + col.r=TCOD_zip_get_char(pzip); + col.g=TCOD_zip_get_char(pzip); + col.b=TCOD_zip_get_char(pzip); + return col; +} + +const char *TCOD_zip_get_string(TCOD_zip_t pzip) { + zip_data_t *zip=(zip_data_t *)pzip; + int l=TCOD_zip_get_int(pzip); + const char *ret=(const char *)TCOD_list_begin(zip->buffer); + int boffset; /* offset in bytes */ + if ( l == -1 ) return NULL; + boffset=zip->offset*sizeof(uintptr_t)-zip->isize; /* current offset */ + ret += boffset; /* the string address in buffer */ + boffset += l+1; /* new offset */ + /* update ibuffer */ + zip->offset = (boffset+sizeof(uintptr_t)-1)/sizeof(uintptr_t); + zip->isize = boffset%sizeof(uintptr_t); + if ( zip->isize != 0 ) { + zip->isize=sizeof(uintptr_t)-zip->isize; + zip->ibuffer=(uintptr_t)TCOD_list_get(zip->buffer,zip->offset-1); + } + return ret; +} + +int TCOD_zip_get_data(TCOD_zip_t pzip, int nbBytes, void *data) { + zip_data_t *zip=(zip_data_t *)pzip; + int l=TCOD_zip_get_int(pzip),i; + const char *in=(const char *)TCOD_list_begin(zip->buffer); + char *out=(char *)data; + int boffset; /* offset in bytes */ + if ( l == -1 ) return 0; + boffset=zip->offset*sizeof(uintptr_t)-zip->isize; /* current offset */ + in += boffset; /* the data address in buffer */ + /* copy it to data */ + for (i=0; i < MIN(l,nbBytes); i++ ) { + *(out++)=*(in++); + boffset++; + } + /* update ibuffer */ + zip->offset = (boffset+sizeof(uintptr_t)-1)/sizeof(uintptr_t); + zip->isize = boffset%sizeof(uintptr_t); + if ( zip->isize != 0 ) { + zip->isize=sizeof(uintptr_t)-zip->isize; + zip->ibuffer=(uintptr_t)TCOD_list_get(zip->buffer,zip->offset-1); + } + return l; +} + +#ifdef TCOD_IMAGE_SUPPORT +TCOD_image_t TCOD_zip_get_image(TCOD_zip_t pzip) { + TCOD_image_t ret; + int w,h,x,y; + w=TCOD_zip_get_int(pzip); + h=TCOD_zip_get_int(pzip); + ret=TCOD_image_new(w,h); + for (y=0; y < h; y++) { + for (x=0; x < w; x++ ) { + TCOD_image_put_pixel(ret, x,y,TCOD_zip_get_color(pzip)); + } + } + return ret; +} +#endif + +#ifdef TCOD_CONSOLE_SUPPORT +TCOD_console_t TCOD_zip_get_console(TCOD_zip_t pzip) { + TCOD_console_t ret; + int w,h,x,y; + w=TCOD_zip_get_int(pzip); + h=TCOD_zip_get_int(pzip); + ret=TCOD_console_new(w,h); + for (y=0; y < h; y++) { + for (x=0; x < w; x++ ) { + TCOD_console_set_char(ret, x,y,TCOD_zip_get_char(pzip)); + TCOD_console_set_char_foreground(ret, x,y,TCOD_zip_get_color(pzip)); + TCOD_console_set_char_background(ret, x,y,TCOD_zip_get_color(pzip), TCOD_BKGND_SET); + } + } + return ret; +} +#endif + +uint32_t TCOD_zip_get_current_bytes(TCOD_zip_t pzip) { + zip_data_t *zip=(zip_data_t *)pzip; + if (!zip->buffer) zip->buffer=TCOD_list_new(); + return TCOD_list_size(zip->buffer)*sizeof(uintptr_t)+zip->isize; +} + +uint32_t TCOD_zip_get_remaining_bytes(TCOD_zip_t pzip) { + zip_data_t *zip=(zip_data_t *)pzip; + if (!zip->buffer) zip->buffer=TCOD_list_new(); + return (TCOD_list_size(zip->buffer) - zip->offset) * sizeof(uintptr_t) + zip->isize; +} + +void TCOD_zip_skip_bytes(TCOD_zip_t pzip, uint32_t nbBytes) { + zip_data_t *zip=(zip_data_t *)pzip; + uint32_t boffset=zip->offset*sizeof(uintptr_t)-zip->isize+ nbBytes; /* new offset */ + TCOD_IFNOT(boffset <= TCOD_list_size(zip->buffer)*sizeof(uintptr_t)) return; + zip->offset = (boffset+sizeof(uintptr_t)-1)/sizeof(uintptr_t); + zip->isize = boffset%sizeof(uintptr_t); + if ( zip->isize != 0 ) { + zip->isize=sizeof(uintptr_t)-zip->isize; + zip->ibuffer=(uintptr_t)TCOD_list_get(zip->buffer,zip->offset-1); + } +} diff --git a/tcod_sys/libtcod/src/list_c.c b/tcod_sys/libtcod/src/list_c.c deleted file mode 100644 index 04fd3d6f8..000000000 --- a/tcod_sys/libtcod/src/list_c.c +++ /dev/null @@ -1,201 +0,0 @@ -/* -* libtcod -* Copyright (c) 2008-2018 Jice & Mingos & rmtew -* All rights reserved. -* -* Redistribution and use in source and binary forms, with or without -* modification, are permitted provided that the following conditions are met: -* * Redistributions of source code must retain the above copyright -* notice, this list of conditions and the following disclaimer. -* * Redistributions in binary form must reproduce the above copyright -* notice, this list of conditions and the following disclaimer in the -* documentation and/or other materials provided with the distribution. -* * The name of Jice or Mingos may not be used to endorse or promote -* products derived from this software without specific prior written -* permission. -* -* THIS SOFTWARE IS PROVIDED BY JICE, MINGOS AND RMTEW ``AS IS'' AND ANY -* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED -* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE -* DISCLAIMED. IN NO EVENT SHALL JICE, MINGOS OR RMTEW BE LIABLE FOR ANY -* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES -* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; -* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND -* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS -* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. -*/ -#include - -#include /* calloc */ -#include /* NULL/memcpy */ - -#include - -#define LIST(l) ((TCOD_list_int_t *)l) - -typedef struct { - void **array; - int fillSize; - int allocSize; -} TCOD_list_int_t; - -static void TCOD_list_allocate_int(TCOD_list_t l) { - void **newArray; - int newSize = LIST(l)->allocSize * 2; - if ( newSize == 0 ) newSize = 16; - newArray = (void **)calloc(sizeof(void *),newSize ); - if ( LIST(l)->array ) { - if ( LIST(l)->fillSize > 0 ) memcpy(newArray, LIST(l)->array, sizeof(void *)*LIST(l)->fillSize); - free(LIST(l)->array); - } - LIST(l)->array=newArray; - LIST(l)->allocSize=newSize; -} - -void TCOD_list_set_size(TCOD_list_t l, int size) { - LIST(l)->fillSize=MIN(size,LIST(l)->allocSize); -} - -TCOD_list_t TCOD_list_new(void) { - return (TCOD_list_t)calloc(1,sizeof(TCOD_list_int_t)); -} - -TCOD_list_t TCOD_list_allocate(int nb_elements) { - TCOD_list_t l=TCOD_list_new(); - LIST(l)->array = (void **)calloc(sizeof(void *),nb_elements); - LIST(l)->allocSize = nb_elements; - return l; -} - -TCOD_list_t TCOD_list_duplicate(TCOD_list_t l) { - int i=0; - void **t; - TCOD_list_int_t *ret=(TCOD_list_int_t *)TCOD_list_new(); - while ( ret->allocSize < LIST(l)->allocSize ) TCOD_list_allocate_int((TCOD_list_t)ret); - ret->fillSize=LIST(l)->fillSize; - for (t=TCOD_list_begin(l); t != TCOD_list_end(l); t++) { - ret->array[i++]=*t; - } - return (TCOD_list_t)ret; -} - -void TCOD_list_delete(TCOD_list_t l) { - if ( l ) { - if ( LIST(l)->array ) free(LIST(l)->array); - free(l); - } -} - -void TCOD_list_push(TCOD_list_t l, const void * elt) { - if ( LIST(l)->fillSize+1 >= LIST(l)->allocSize ) TCOD_list_allocate_int(l); - LIST(l)->array[LIST(l)->fillSize++] = (void *)elt; -} -void * TCOD_list_pop(TCOD_list_t l) { - if ( LIST(l)->fillSize == 0 ) return NULL; - return LIST(l)->array[--(LIST(l)->fillSize)]; -} -void * TCOD_list_peek(TCOD_list_t l) { - if ( LIST(l)->fillSize == 0 ) return NULL; - return LIST(l)->array[LIST(l)->fillSize-1]; -} -void TCOD_list_add_all(TCOD_list_t l, TCOD_list_t l2) { - void **curElt; - for ( curElt = TCOD_list_begin(l2); curElt != TCOD_list_end(l2); curElt ++) { - TCOD_list_push(l,*curElt); - } -} -void * TCOD_list_get(TCOD_list_t l,int idx) { - return LIST(l)->array[idx]; -} -void TCOD_list_set(TCOD_list_t l,const void *elt, int idx) { - if ( idx < 0 ) return; - while ( LIST(l)->allocSize < idx+1 ) TCOD_list_allocate_int(l); - LIST(l)->array[idx]=(void *)elt; - if ( idx+1 > LIST(l)->fillSize ) LIST(l)->fillSize = idx+1; -} -void ** TCOD_list_begin(TCOD_list_t l) { - if ( LIST(l)->fillSize == 0 ) return (void **)NULL; - return &LIST(l)->array[0]; -} -void ** TCOD_list_end(TCOD_list_t l) { - if ( LIST(l)->fillSize == 0 ) return (void **)NULL; - return &LIST(l)->array[LIST(l)->fillSize]; -} -void TCOD_list_reverse(TCOD_list_t l) { - void **head=TCOD_list_begin(l); - void **tail=TCOD_list_end(l) - 1; - while ( head < tail ) { - void *tmp=*head; - *head=*tail; - *tail=tmp; - head++; - tail--; - } -} -void **TCOD_list_remove_iterator(TCOD_list_t l, void **elt) { - void **curElt; - for ( curElt = elt; curElt < TCOD_list_end(l)-1; curElt ++) { - *curElt = *(curElt+1); - } - LIST(l)->fillSize--; - if ( LIST(l)->fillSize == 0 ) return ((void **)NULL)-1; - else return elt-1; -} -void TCOD_list_remove(TCOD_list_t l, const void * elt) { - void **curElt; - for ( curElt = TCOD_list_begin(l); curElt != TCOD_list_end(l); curElt ++) { - if ( *curElt == elt ) { - TCOD_list_remove_iterator(l,curElt); - return; - } - } -} -void **TCOD_list_remove_iterator_fast(TCOD_list_t l, void **elt) { - *elt = LIST(l)->array[LIST(l)->fillSize-1]; - LIST(l)->fillSize--; - if ( LIST(l)->fillSize == 0 ) return ((void **)NULL)-1; - else return elt-1; -} -void TCOD_list_remove_fast(TCOD_list_t l, const void * elt) { - void **curElt; - for ( curElt = TCOD_list_begin(l); curElt != TCOD_list_end(l); curElt ++) { - if ( *curElt == elt ) { - TCOD_list_remove_iterator_fast(l,curElt); - return; - } - } -} -bool TCOD_list_contains(TCOD_list_t l,const void * elt) { - void **curElt; - for ( curElt = TCOD_list_begin(l); curElt != TCOD_list_end(l); curElt ++) { - if ( *curElt == elt ) return true; - } - return false; -} -void TCOD_list_clear(TCOD_list_t l) { - LIST(l)->fillSize=0; -} -void TCOD_list_clear_and_delete(TCOD_list_t l) { - void **curElt; - for ( curElt = TCOD_list_begin(l); curElt != TCOD_list_end(l); curElt ++ ) { - free(*curElt); - } - LIST(l)->fillSize=0; -} -int TCOD_list_size(TCOD_list_t l) { - return LIST(l)->fillSize; -} -void **TCOD_list_insert_before(TCOD_list_t l,const void *elt,int before) { - int idx; - if ( LIST(l)->fillSize+1 >= LIST(l)->allocSize ) TCOD_list_allocate_int(l); - for (idx=LIST(l)->fillSize; idx > before; idx--) { - LIST(l)->array[idx]=LIST(l)->array[idx-1]; - } - LIST(l)->array[before]=(void *)elt; - LIST(l)->fillSize++; - return &LIST(l)->array[before]; -} -bool TCOD_list_is_empty(TCOD_list_t l) { - return ( LIST(l)->fillSize == 0 ); -} diff --git a/tcod_sys/libtcod/src/sys_sdl2_c.c b/tcod_sys/libtcod/src/sys_sdl2_c.c deleted file mode 100644 index 228f43970..000000000 --- a/tcod_sys/libtcod/src/sys_sdl2_c.c +++ /dev/null @@ -1,529 +0,0 @@ -/* -* libtcod -* Copyright (c) 2008-2018 Jice & Mingos & rmtew -* All rights reserved. -* -* Redistribution and use in source and binary forms, with or without -* modification, are permitted provided that the following conditions are met: -* * Redistributions of source code must retain the above copyright -* notice, this list of conditions and the following disclaimer. -* * Redistributions in binary form must reproduce the above copyright -* notice, this list of conditions and the following disclaimer in the -* documentation and/or other materials provided with the distribution. -* * The name of Jice or Mingos may not be used to endorse or promote -* products derived from this software without specific prior written -* permission. -* -* THIS SOFTWARE IS PROVIDED BY JICE, MINGOS AND RMTEW ``AS IS'' AND ANY -* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED -* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE -* DISCLAIMED. IN NO EVENT SHALL JICE, MINGOS OR RMTEW BE LIABLE FOR ANY -* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES -* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; -* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND -* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS -* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. -*/ -#ifndef TCOD_BARE - -#include - -#include -#include - -#include - -#include -#include -#include - -static SDL_Surface* scale_screen=NULL; -static bool clear_screen=false; -static TCOD_console_data_t *root_console_cache; /* cache for previous values */ - -/* This just forces a complete redraw, bypassing the usual rendering of changes. */ -void TCOD_sys_set_clear_screen(void) { - clear_screen=true; -} - -static void get_closest_mode(int *w, int *h) { - SDL_DisplayMode wantedmode, closestmode; - wantedmode.w = *w; - wantedmode.h = *h; - wantedmode.format = 0; /* don't care for rest. */ - wantedmode.refresh_rate = 0; - wantedmode.driverdata = 0; - if (SDL_GetClosestDisplayMode(window?SDL_GetWindowDisplayIndex(window):0, &wantedmode, &closestmode) == &closestmode) { - *w=closestmode.w; - *h=closestmode.h; - } -} - -/* - * Separate out the actual rendering, so that render to texture can be done. - */ -static void actual_rendering(void) { - SDL_Rect srcRect, dstRect; - SDL_Texture *texture; - - if (scale_data.min_scale_factor - 1e-3f > scale_factor) { - /* Prepare for the unscaled and centered copy of the entire console. */ - srcRect.x=0; srcRect.y=0; srcRect.w=scale_screen->w; srcRect.h=scale_screen->h; - if (TCOD_ctx.fullscreen) { - dstRect.x=TCOD_ctx.fullscreen_offsetx; dstRect.y=TCOD_ctx.fullscreen_offsety; - } else { - dstRect.x=0; dstRect.y=0; - } - dstRect.w=scale_screen->w; dstRect.h=scale_screen->h; - } else { - /* Prepare for the scaled copy of the displayed console area. */ - srcRect.x=scale_data.src_x0; srcRect.y=scale_data.src_y0; srcRect.w=scale_data.src_copy_width; srcRect.h=scale_data.src_copy_height; - dstRect.x=scale_data.dst_offset_x; dstRect.y=scale_data.dst_offset_y; - dstRect.w=scale_data.dst_display_width; dstRect.h=scale_data.dst_display_height; - } - if ( TCOD_ctx.sdl_cbk ) { - TCOD_ctx.sdl_cbk((void *)scale_screen); - } - texture = SDL_CreateTextureFromSurface(renderer, scale_screen); - SDL_RenderCopy(renderer, texture, &srcRect, &dstRect); - SDL_DestroyTexture(texture); -} - -/* Return an up-to-date cache for the root console, create or resize the cache - if needed */ -static TCOD_console_data_t *ensure_cache(TCOD_console_data_t* root) { - if (!root_console_cache || - root_console_cache->w != root->w || - root_console_cache->h != root->h) { - if (root_console_cache) { TCOD_console_delete(root_console_cache); } - root_console_cache = TCOD_console_new(root->w, root->h); - } - return root_console_cache; -} - -/* In order to avoid rendering race conditions and the ensuing segmentation - * faults, this should only be called when it would normally be and not - * specifically to force screen refreshes. To this end, and to avoid - * threading complications it takes care of special cases internally. */ -static void render(TCOD_SDL_driver_t *sdl, void *vbitmap, TCOD_console_data_t *console) { - if ( TCOD_ctx.renderer == TCOD_RENDERER_SDL ) { - int console_width_p = console->w * TCOD_ctx.font_width; - int console_height_p = console->h * TCOD_ctx.font_height; - - /* Make a bitmap of exact rendering size and correct format. */ - if (scale_screen == NULL) { - int bpp; - uint32_t rmask, gmask, bmask, amask; - if (SDL_PixelFormatEnumToMasks(SDL_GetWindowPixelFormat(window), &bpp, &rmask, &gmask, &bmask, &amask) == SDL_FALSE) { - TCOD_fatal("SDL : failed to create scaling surface : indeterminate window pixel format"); - return; - } - scale_screen=SDL_CreateRGBSurface(SDL_SWSURFACE,console_width_p,console_height_p,bpp,rmask,gmask,bmask,amask); - if (scale_screen == NULL) { - TCOD_fatal("SDL : failed to create scaling surface"); - return; - } - } else if (clear_screen) { - clear_screen=false; - SDL_FillRect(scale_screen,0,0); - /* Implicitly do complete console redraw, not just tracked changes. */ - TCOD_console_set_dirty(0, 0, console->w, console->h); - } - - TCOD_sys_console_to_bitmap(scale_screen, console, ensure_cache(console)); - - /* Scale the rendered bitmap to the screen, preserving aspect ratio, and blit it. - * This data is also used for console coordinate resolution.. */ - if (scale_data.last_scale_factor != scale_factor || scale_data.last_scale_xc != sdl->scale_xc || scale_data.last_scale_yc != sdl->scale_yc || - scale_data.last_fullscreen != TCOD_ctx.fullscreen || scale_data.force_recalc) { - /* Preserve old value of input variables, to enable recalculation if they change. */ - scale_data.last_scale_factor = scale_factor; - scale_data.last_scale_xc = sdl->scale_xc; - scale_data.last_scale_yc = sdl->scale_yc; - scale_data.last_fullscreen = TCOD_ctx.fullscreen; - scale_data.force_recalc = 0; - - if (scale_data.last_fullscreen) { - scale_data.surface_width = TCOD_ctx.actual_fullscreen_width; - scale_data.surface_height = TCOD_ctx.actual_fullscreen_height; - } else { - scale_data.surface_width = console_width_p; - scale_data.surface_height = console_height_p; - } - scale_data.min_scale_factor = MAX((float)console_width_p/scale_data.surface_width, (float)console_height_p/scale_data.surface_height); - if (scale_data.min_scale_factor > 1.0f) - scale_data.min_scale_factor = 1.0f; - /*printf("min_scale_factor %0.3f = MAX(%d/%d, %d/%d)", scale_data.min_scale_factor, console_width_p, scale_data.surface_width, console_height_p, scale_data.surface_height);*/ - - scale_data.dst_height_width_ratio = (float)scale_data.surface_height/scale_data.surface_width; - scale_data.src_proportionate_width = (int)(console_width_p / scale_factor); - scale_data.src_proportionate_height = (int)((console_width_p * scale_data.dst_height_width_ratio) / scale_factor); - - /* Work out how much of the console to copy. */ - scale_data.src_x0 = (int)((sdl->scale_xc * console_width_p) - (0.5f * scale_data.src_proportionate_width)); - if (scale_data.src_x0 + scale_data.src_proportionate_width > console_width_p) - scale_data.src_x0 = console_width_p - scale_data.src_proportionate_width; - if (scale_data.src_x0 < 0) - scale_data.src_x0 = 0; - scale_data.src_copy_width = scale_data.src_proportionate_width; - if (scale_data.src_x0 + scale_data.src_copy_width > console_width_p) - scale_data.src_copy_width = console_width_p - scale_data.src_x0; - - scale_data.src_y0 = (int)((sdl->scale_yc * console_height_p) - (0.5f * scale_data.src_proportionate_height)); - if (scale_data.src_y0 + scale_data.src_proportionate_height > console_height_p) - scale_data.src_y0 = console_height_p - scale_data.src_proportionate_height; - if (scale_data.src_y0 < 0) - scale_data.src_y0 = 0; - scale_data.src_copy_height = scale_data.src_proportionate_height; - if (scale_data.src_y0 + scale_data.src_copy_height > console_height_p) - scale_data.src_copy_height = console_height_p - scale_data.src_y0; - - scale_data.dst_display_width = (scale_data.src_copy_width * scale_data.surface_width) / scale_data.src_proportionate_width; - scale_data.dst_display_height = (scale_data.src_copy_height * scale_data.surface_height) / scale_data.src_proportionate_height; - scale_data.dst_offset_x = (scale_data.surface_width - scale_data.dst_display_width)/2; - scale_data.dst_offset_y = (scale_data.surface_height - scale_data.dst_display_height)/2; - } - - SDL_RenderClear(renderer); - actual_rendering(); - SDL_RenderPresent(renderer); - } -#ifndef NO_OPENGL - else { - TCOD_opengl_render(oldFade, NULL, console, ensure_cache(console)); - TCOD_opengl_swap(); - } -#endif - oldFade=(int)TCOD_console_get_fade(); -} - -/* Return the current root console cache if it exists, or NULL. */ -static TCOD_console_data_t *get_root_console_cache(void){ - return root_console_cache; -} - -static SDL_Surface *create_surface(int width, int height, bool with_alpha) { - uint32_t rmask,gmask,bmask,amask; - SDL_Surface *bitmap; - int flags=SDL_SWSURFACE; - - if ( with_alpha ) { - if ( SDL_BYTEORDER == SDL_LIL_ENDIAN ) { - rmask=0x000000FF; - gmask=0x0000FF00; - bmask=0x00FF0000; - amask=0xFF000000; - } else { - rmask=0xFF000000; - gmask=0x00FF0000; - bmask=0x0000FF00; - amask=0x000000FF; - } - } else { - if ( SDL_BYTEORDER == SDL_LIL_ENDIAN ) { - rmask=0x0000FF; - gmask=0x00FF00; - bmask=0xFF0000; - } else { - rmask=0xFF0000; - gmask=0x00FF00; - bmask=0x0000FF; - } - amask=0; - } - bitmap=SDL_CreateRGBSurface(flags,width,height, - with_alpha ? 32:24, - rmask,gmask,bmask,amask); - if ( with_alpha ) { - SDL_SetSurfaceAlphaMod(bitmap, 255); - } - return (void *)bitmap; -} - -static void create_window(int w, int h, bool fullscreen) { - uint32_t winflags = SDL_WINDOW_SHOWN | SDL_WINDOW_OPENGL; -#if defined(TCOD_ANDROID) - /* Android should always be fullscreen. */ - TCOD_ctx.fullscreen = fullscreen = true; -#endif - if ( fullscreen ) { - find_resolution(); -#ifndef NO_OPENGL - if (TCOD_ctx.renderer != TCOD_RENDERER_SDL ) { - TCOD_opengl_init_attributes(); - winflags |= SDL_WINDOW_FULLSCREEN | SDL_WINDOW_BORDERLESS | SDL_WINDOW_OPENGL; -# if defined(TCOD_ANDROID) && defined(FUTURE_SUPPORT) - winflags |= SDL_WINDOW_RESIZABLE; -# endif - window = SDL_CreateWindow(TCOD_ctx.window_title,SDL_WINDOWPOS_CENTERED,SDL_WINDOWPOS_CENTERED,TCOD_ctx.actual_fullscreen_width,TCOD_ctx.actual_fullscreen_height,winflags); - if ( window && TCOD_opengl_init_state(w, h, charmap) && TCOD_opengl_init_shaders() ) { - TCOD_LOG(("Using %s renderer...\n",TCOD_ctx.renderer == TCOD_RENDERER_GLSL ? "GLSL" : "OPENGL")); - } else { - TCOD_LOG(("Fallback to SDL renderer...\n")); - TCOD_ctx.renderer = TCOD_RENDERER_SDL; - } - } -#endif - if (TCOD_ctx.renderer == TCOD_RENDERER_SDL ) { - winflags |= SDL_WINDOW_FULLSCREEN | SDL_WINDOW_BORDERLESS; -# if defined(TCOD_ANDROID) && defined(FUTURE_SUPPORT) - winflags |= SDL_WINDOW_RESIZABLE; -# endif - window = SDL_CreateWindow(TCOD_ctx.window_title,SDL_WINDOWPOS_CENTERED, SDL_WINDOWPOS_CENTERED, TCOD_ctx.actual_fullscreen_width,TCOD_ctx.actual_fullscreen_height,winflags); - if ( window == NULL ) TCOD_fatal("SDL : cannot set fullscreen video mode: %s", SDL_GetError()); - } - SDL_ShowCursor(0); - SDL_GetWindowSize(window,&TCOD_ctx.actual_fullscreen_width,&TCOD_ctx.actual_fullscreen_height); - TCOD_sys_init_screen_offset(); - } else { -#ifndef NO_OPENGL - if (TCOD_ctx.renderer != TCOD_RENDERER_SDL ) { - TCOD_opengl_init_attributes(); - winflags |= SDL_WINDOW_OPENGL; - window = SDL_CreateWindow(TCOD_ctx.window_title,SDL_WINDOWPOS_CENTERED,SDL_WINDOWPOS_CENTERED,w*TCOD_ctx.font_width,h*TCOD_ctx.font_height,winflags); - if ( window && TCOD_opengl_init_state(w, h, charmap) && TCOD_opengl_init_shaders() ) { - TCOD_LOG(("Using %s renderer...\n",TCOD_ctx.renderer == TCOD_RENDERER_GLSL ? "GLSL" : "OPENGL")); - } else { - TCOD_LOG(("Fallback to SDL renderer...\n")); - TCOD_ctx.renderer = TCOD_RENDERER_SDL; - } - } -#endif - if (TCOD_ctx.renderer == TCOD_RENDERER_SDL ) { - window = SDL_CreateWindow(TCOD_ctx.window_title,SDL_WINDOWPOS_CENTERED,SDL_WINDOWPOS_CENTERED,w*TCOD_ctx.font_width,h*TCOD_ctx.font_height,winflags); - SDL_PumpEvents(); - SDL_SetWindowSize(window,w*TCOD_ctx.font_width,h*TCOD_ctx.font_height); - TCOD_LOG(("Using SDL renderer...\n")); - } - if ( window == NULL ) TCOD_fatal("Cannot create SDL window: %s", SDL_GetError()); - } - if (TCOD_ctx.renderer == TCOD_RENDERER_SDL ) { - renderer = SDL_CreateRenderer(window, -1, SDL_RENDERER_ACCELERATED); - if ( renderer == NULL ) TCOD_fatal("Cannot create SDL renderer: %s", SDL_GetError()); - SDL_SetRenderDrawColor(renderer, 0, 0, 0, SDL_ALPHA_OPAQUE); - } -} - -static void destroy_window(void) { -#ifndef NO_OPENGL - if (TCOD_ctx.renderer == TCOD_RENDERER_OPENGL || TCOD_ctx.renderer == TCOD_RENDERER_GLSL) { - TCOD_opengl_uninit_state(); - } -#endif - if (scale_screen) { - SDL_FreeSurface(scale_screen); - scale_screen = NULL; - } - if (renderer) { - SDL_DestroyRenderer(renderer); - renderer = NULL; - } - if (window) { - SDL_DestroyWindow(window); - window = NULL; - } -} - -static void set_fullscreen(bool fullscreen) { - bool mouseOn=SDL_ShowCursor(-1); - if ( fullscreen ) { - find_resolution(); - SDL_SetWindowFullscreen(window, fullscreen); - SDL_ShowCursor(mouseOn ? 1:0); - SDL_GetWindowSize(window,&TCOD_ctx.actual_fullscreen_width,&TCOD_ctx.actual_fullscreen_height); - TCOD_sys_init_screen_offset(); - } else { - SDL_SetWindowFullscreen(window, fullscreen); - SDL_ShowCursor(mouseOn ? 1:0); - TCOD_ctx.fullscreen_offsetx=0; - TCOD_ctx.fullscreen_offsety=0; - } - TCOD_ctx.fullscreen=fullscreen; - oldFade=-1; /* to redraw the whole screen */ -} - -static void set_window_title(const char *title) { - SDL_SetWindowTitle(window, title); -} - -static void save_screenshot(const char *filename) { - if ( TCOD_ctx.renderer == TCOD_RENDERER_SDL ) { - /* This would be a lot easier if image saving could do textures. */ - SDL_Rect rect; - uint32_t format; - SDL_Texture *texture; - SDL_RenderGetViewport(renderer, &rect); - format = SDL_GetWindowPixelFormat(window); - texture = SDL_CreateTexture(renderer, format, SDL_TEXTUREACCESS_TARGET, rect.w, rect.h); - if (0 != texture) { - if (SDL_SetRenderTarget(renderer, texture)) { - void *pixels; - int pitch, access; - - actual_rendering(); - SDL_SetRenderTarget(renderer, NULL); - - rect.x = rect.y = rect.w = rect.h = 0; - if (-1 != SDL_QueryTexture(texture, &format, &access, &rect.w, &rect.h) && - -1 != SDL_LockTexture(texture, NULL, &pixels, &pitch)) { - int depth; - uint32_t rmask, gmask, bmask, amask; - if (SDL_TRUE == SDL_PixelFormatEnumToMasks(format, &depth, &rmask, &gmask, &bmask, &amask)) { - SDL_Surface *surface = SDL_CreateRGBSurfaceFrom(pixels, rect.w, rect.h, depth, pitch, rmask, gmask, bmask, amask); - TCOD_sys_save_bitmap((void *)surface,filename); - SDL_FreeSurface(surface); - } else - TCOD_LOG(("TCOD_sys_save_screenshot - failed call to SDL_PixelFormatEnumToMasks")); - - SDL_UnlockTexture(texture); - } else - TCOD_LOG(("TCOD_sys_save_screenshot - failed call to SDL_QueryTexture or SDL_LockTexture")); - } else - TCOD_LOG(("TCOD_sys_save_screenshot - failed call to SDL_SetRenderTarget")); - SDL_DestroyTexture(texture); - } else - TCOD_LOG(("TCOD_sys_save_screenshot - failed call to SDL_CreateTexture")); -#ifndef NO_OPENGL - } else { - SDL_Surface *screenshot=(SDL_Surface *)TCOD_opengl_get_screen(); - TCOD_sys_save_bitmap((void *)screenshot,filename); - SDL_FreeSurface(screenshot); -#endif - } -} -/* get desktop resolution */ -static void get_current_resolution(int *w, int *h) { - int displayidx; - SDL_Rect rect = { 0, 0, 0, 0 }; - if (window) { - TCOD_IFNOT(window) return; - displayidx = SDL_GetWindowDisplayIndex(window); - TCOD_IFNOT(displayidx >= 0) return; - } else { - /* No window if no console, but user can want to know res before opening one. */ - TCOD_IFNOT(SDL_GetNumVideoDisplays() > 0) return; - displayidx = 0; - } - TCOD_IFNOT(SDL_GetDisplayBounds(displayidx, &rect) == 0) return; - *w=rect.w; - *h=rect.h; -} - -static void set_mouse_position(int x, int y) { - SDL_WarpMouseInWindow(window, (uint16_t)x,(uint16_t)y); -} - -static char *get_clipboard_text(void) { -#ifdef TCOD_LINUX - /* - X11 clipboard is inaccessible without an open window. - https://bugzilla.libsdl.org/show_bug.cgi?id=3222 - */ - if (!window) - return ""; -#endif - - /* - We hold onto the last clipboard text pointer SDL gave us. - For C API callers it can be considered a borrowed reference. - For Python ctypes API callers, the contents are copied into the Python string that is constructed from it. - */ - if (last_clipboard_text) { - SDL_free(last_clipboard_text); - last_clipboard_text = NULL; - } - last_clipboard_text = SDL_GetClipboardText(); - return last_clipboard_text; -} - -static bool set_clipboard_text(const char *text) { -#ifdef TCOD_LINUX - /* - X11 clipboard is inaccessible without an open window. - https://bugzilla.libsdl.org/show_bug.cgi?id=3222 - */ - if (!window) - return false; -#endif - - return SDL_SetClipboardText(text) == 0; -} - -/* android compatible file access functions */ -static bool file_read(const char *filename, unsigned char **buf, size_t *size) { - int64_t filesize; - /* get file size */ - SDL_RWops *rwops= SDL_RWFromFile(filename,"rb"); - if (!rwops) return false; - SDL_RWseek(rwops,0,RW_SEEK_END); - filesize=SDL_RWtell(rwops); - SDL_RWseek(rwops,0,RW_SEEK_SET); - /* allocate buffer */ - *buf = (unsigned char *)malloc(sizeof(unsigned char)*filesize); - /* read from file */ - if (SDL_RWread(rwops,*buf,sizeof(unsigned char),filesize) != filesize) { - SDL_RWclose(rwops); - free(*buf); - return false; - } - SDL_RWclose(rwops); - *size=filesize; - return true; -} - -static bool file_exists(const char * filename) { - SDL_RWops *rwops; - rwops = SDL_RWFromFile(filename,"rb"); - if (rwops) { - SDL_RWclose(rwops); - return true; - } - return false; -} - -static bool file_write(const char *filename, unsigned char *buf, uint32_t size) { - SDL_RWops *rwops= SDL_RWFromFile(filename,"wb"); - if (!rwops) return false; - SDL_RWwrite(rwops,buf,sizeof(unsigned char),size); - SDL_RWclose(rwops); - return true; -} - -static void shutdown_(void) { - if (last_clipboard_text) { - SDL_free(last_clipboard_text); - last_clipboard_text = NULL; - } - if (root_console_cache) { - TCOD_console_delete(root_console_cache); - root_console_cache = NULL; - } -} - -TCOD_SDL_driver_t *SDL_implementation_factory(void) { - TCOD_SDL_driver_t *ret=(TCOD_SDL_driver_t *)calloc(1,sizeof(TCOD_SDL_driver_t)); - ret->scale_xc = 0.5f; - ret->scale_yc = 0.5f; - - ret->get_closest_mode = get_closest_mode; - ret->render = render; - ret->create_surface = create_surface; - ret->create_window = create_window; - ret->destroy_window = destroy_window; - ret->set_fullscreen = set_fullscreen; - ret->set_window_title = set_window_title; - ret->save_screenshot = save_screenshot; - ret->get_current_resolution = get_current_resolution; - ret->set_mouse_position = set_mouse_position; - ret->get_clipboard_text = get_clipboard_text; - ret->set_clipboard_text = set_clipboard_text; - ret->file_read = file_read; - ret->file_exists = file_exists; - ret->file_write = file_write; - ret->shutdown = shutdown_; - ret->get_root_console_cache = get_root_console_cache; - return ret; -} - -#endif /* TCOD_BARE */ diff --git a/tcod_sys/libtcod/src/png/lodepng.c b/tcod_sys/libtcod/src/vendor/lodepng.cpp similarity index 96% rename from tcod_sys/libtcod/src/png/lodepng.c rename to tcod_sys/libtcod/src/vendor/lodepng.cpp index 8c78758ff..6568bba8c 100644 --- a/tcod_sys/libtcod/src/png/lodepng.c +++ b/tcod_sys/libtcod/src/vendor/lodepng.cpp @@ -1,7 +1,7 @@ /* -LodePNG version 20160501 +LodePNG version 20180611 -Copyright (c) 2005-2016 Lode Vandevenne +Copyright (c) 2005-2018 Lode Vandevenne This software is provided 'as-is', without any express or implied warranty. In no event will the authors be held liable for any damages @@ -39,7 +39,7 @@ Rename this file to lodepng.cpp to use it for C++, or to lodepng.c to use it for #pragma warning( disable : 4996 ) /*VS does not like fopen, but fopen_s is not standard C so unusable here*/ #endif /*_MSC_VER */ -const char* LODEPNG_VERSION_STRING = "20160501"; +const char* LODEPNG_VERSION_STRING = "20180611"; /* This source file is built up in the following large parts. The code sections @@ -62,11 +62,17 @@ from here.*/ #ifdef LODEPNG_COMPILE_ALLOCATORS static void* lodepng_malloc(size_t size) { +#ifdef LODEPNG_MAX_ALLOC + if(size > LODEPNG_MAX_ALLOC) return 0; +#endif return malloc(size); } static void* lodepng_realloc(void* ptr, size_t new_size) { +#ifdef LODEPNG_MAX_ALLOC + if(new_size > LODEPNG_MAX_ALLOC) return 0; +#endif return realloc(ptr, new_size); } @@ -86,6 +92,8 @@ void lodepng_free(void* ptr); /* ////////////////////////////////////////////////////////////////////////// */ /* ////////////////////////////////////////////////////////////////////////// */ +#define LODEPNG_MAX(a, b) (((a) > (b)) ? (a) : (b)) + /* Often in case of an error a value is assigned to a variable and then it breaks out of a loop (to go to the cleanup phase of a function). This macro does that. @@ -795,7 +803,7 @@ unsigned lodepng_huffman_code_lengths(unsigned* lengths, const unsigned* frequen BPMNode* leaves; /*the symbols, only those with > 0 frequency*/ if(numcodes == 0) return 80; /*error: a tree of 0 symbols is not supposed to be made*/ - if((1u << maxbitlen) < numcodes) return 80; /*error: represent all symbols*/ + if((1u << maxbitlen) < (unsigned)numcodes) return 80; /*error: represent all symbols*/ leaves = (BPMNode*)lodepng_malloc(numcodes * sizeof(*leaves)); if(!leaves) return 83; /*alloc fail*/ @@ -1171,7 +1179,7 @@ static unsigned inflateHuffmanBlock(ucvector* out, const unsigned char* in, size code_d = huffmanDecodeSymbol(in, bp, &tree_d, inbitlength); if(code_d > 29) { - if(code_ll == (unsigned)(-1)) /*huffmanDecodeSymbol returns (unsigned)(-1) in case of error*/ + if(code_d == (unsigned)(-1)) /*huffmanDecodeSymbol returns (unsigned)(-1) in case of error*/ { /*return error code 10 or 11 depending on the situation that happened in huffmanDecodeSymbol (10=no endcode, 11=wrong jump outside of tree)*/ @@ -1455,11 +1463,11 @@ static void updateHashChain(Hash* hash, size_t wpos, unsigned hashval, unsigned { hash->val[wpos] = (int)hashval; if(hash->head[hashval] != -1) hash->chain[wpos] = hash->head[hashval]; - hash->head[hashval] = wpos; + hash->head[hashval] = (int)wpos; hash->zeros[wpos] = numzeros; if(hash->headz[numzeros] != -1) hash->chainz[wpos] = hash->headz[numzeros]; - hash->headz[numzeros] = wpos; + hash->headz[numzeros] = (int)wpos; } /* @@ -1531,7 +1539,7 @@ static unsigned encodeLZ77(uivector* out, Hash* hash, for(;;) { if(chainlength++ >= maxchainlength) break; - current_offset = hashpos <= wpos ? wpos - hashpos : wpos - hashpos + windowsize; + current_offset = (unsigned)(hashpos <= wpos ? wpos - hashpos : wpos - hashpos + windowsize); if(current_offset < prev_offset) break; /*stop when went completely around the circular buffer*/ prev_offset = current_offset; @@ -2090,13 +2098,13 @@ static unsigned deflate(unsigned char** out, size_t* outsize, static unsigned update_adler32(unsigned adler, const unsigned char* data, unsigned len) { - unsigned s1 = adler & 0xffff; - unsigned s2 = (adler >> 16) & 0xffff; + unsigned s1 = adler & 0xffff; + unsigned s2 = (adler >> 16) & 0xffff; while(len > 0) { - /*at least 5550 sums can be done before the sums overflow, saving a lot of module divisions*/ - unsigned amount = len > 5550 ? 5550 : len; + /*at least 5552 sums can be done before the sums overflow, saving a lot of module divisions*/ + unsigned amount = len > 5552 ? 5552 : len; len -= amount; while(amount > 0) { @@ -2621,15 +2629,10 @@ static int lodepng_color_mode_equal(const LodePNGColorMode* a, const LodePNGColo if(a->key_g != b->key_g) return 0; if(a->key_b != b->key_b) return 0; } - /*if one of the palette sizes is 0, then we consider it to be the same as the - other: it means that e.g. the palette was not given by the user and should be - considered the same as the palette inside the PNG.*/ - if(1/*a->palettesize != 0 && b->palettesize != 0*/) { - if(a->palettesize != b->palettesize) return 0; - for(i = 0; i != a->palettesize * 4; ++i) - { - if(a->palette[i] != b->palette[i]) return 0; - } + if(a->palettesize != b->palettesize) return 0; + for(i = 0; i != a->palettesize * 4; ++i) + { + if(a->palette[i] != b->palette[i]) return 0; } return 1; } @@ -2705,32 +2708,75 @@ unsigned lodepng_can_have_alpha(const LodePNGColorMode* info) || lodepng_has_palette_alpha(info); } -size_t lodepng_get_raw_size(unsigned w, unsigned h, const LodePNGColorMode* color) +size_t lodepng_get_raw_size_lct(unsigned w, unsigned h, LodePNGColorType colortype, unsigned bitdepth) { - /*will not overflow for any color type if roughly w * h < 268435455*/ - size_t bpp = lodepng_get_bpp(color); - size_t n = w * h; + size_t bpp = lodepng_get_bpp_lct(colortype, bitdepth); + size_t n = (size_t)w * (size_t)h; return ((n / 8) * bpp) + ((n & 7) * bpp + 7) / 8; } -size_t lodepng_get_raw_size_lct(unsigned w, unsigned h, LodePNGColorType colortype, unsigned bitdepth) +size_t lodepng_get_raw_size(unsigned w, unsigned h, const LodePNGColorMode* color) { - /*will not overflow for any color type if roughly w * h < 268435455*/ - size_t bpp = lodepng_get_bpp_lct(colortype, bitdepth); - size_t n = w * h; - return ((n / 8) * bpp) + ((n & 7) * bpp + 7) / 8; + return lodepng_get_raw_size_lct(w, h, color->colortype, color->bitdepth); } #ifdef LODEPNG_COMPILE_PNG #ifdef LODEPNG_COMPILE_DECODER -/*in an idat chunk, each scanline is a multiple of 8 bits, unlike the lodepng output buffer*/ + +/*in an idat chunk, each scanline is a multiple of 8 bits, unlike the lodepng output buffer, +and in addition has one extra byte per line: the filter byte. So this gives a larger +result than lodepng_get_raw_size. */ static size_t lodepng_get_raw_size_idat(unsigned w, unsigned h, const LodePNGColorMode* color) { - /*will not overflow for any color type if roughly w * h < 268435455*/ size_t bpp = lodepng_get_bpp(color); - size_t line = ((w / 8) * bpp) + ((w & 7) * bpp + 7) / 8; - return h * line; + /* + 1 for the filter byte, and possibly plus padding bits per line */ + size_t line = ((size_t)(w / 8) * bpp) + 1 + ((w & 7) * bpp + 7) / 8; + return (size_t)h * line; +} + +/* Safely check if multiplying two integers will overflow (no undefined +behavior, compiler removing the code, etc...) and output result. */ +static int lodepng_mulofl(size_t a, size_t b, size_t* result) +{ + *result = a * b; /* Unsigned multiplication is well defined and safe in C90 */ + return (a != 0 && *result / a != b); +} + +/* Safely check if adding two integers will overflow (no undefined +behavior, compiler removing the code, etc...) and output result. */ +static int lodepng_addofl(size_t a, size_t b, size_t* result) +{ + *result = a + b; /* Unsigned addition is well defined and safe in C90 */ + return *result < a; +} + +/*Safely checks whether size_t overflow can be caused due to amount of pixels. +This check is overcautious rather than precise. If this check indicates no overflow, +you can safely compute in a size_t (but not an unsigned): +-(size_t)w * (size_t)h * 8 +-amount of bytes in IDAT (including filter, padding and Adam7 bytes) +-amount of bytes in raw color model +Returns 1 if overflow possible, 0 if not. +*/ +static int lodepng_pixel_overflow(unsigned w, unsigned h, + const LodePNGColorMode* pngcolor, const LodePNGColorMode* rawcolor) +{ + size_t bpp = LODEPNG_MAX(lodepng_get_bpp(pngcolor), lodepng_get_bpp(rawcolor)); + size_t numpixels, total; + size_t line; /* bytes per line in worst case */ + + if(lodepng_mulofl((size_t)w, (size_t)h, &numpixels)) return 1; + if(lodepng_mulofl(numpixels, 8, &total)) return 1; /* bit pointer with 8-bit color, or 8 bytes per channel color */ + + /* Bytes per scanline with the expression "(w / 8) * bpp) + ((w & 7) * bpp + 7) / 8" */ + if(lodepng_mulofl((size_t)(w / 8), bpp, &line)) return 1; + if(lodepng_addofl(line, ((w & 7) * bpp + 7) / 8, &line)) return 1; + + if(lodepng_addofl(line, 5, &line)) return 1; /* 5 bytes overhead per line: 1 filterbyte, 4 for Adam7 worst case */ + if(lodepng_mulofl(line, h, &total)) return 1; /* Total bytes in worst case */ + + return 0; /* no overflow */ } #endif /*LODEPNG_COMPILE_DECODER*/ #endif /*LODEPNG_COMPILE_PNG*/ @@ -3462,7 +3508,8 @@ unsigned lodepng_convert(unsigned char* out, const unsigned char* in, { size_t i; ColorTree tree; - size_t numpixels = w * h; + size_t numpixels = (size_t)w * (size_t)h; + unsigned error = 0; if(lodepng_color_mode_equal(mode_out, mode_in)) { @@ -3475,7 +3522,7 @@ unsigned lodepng_convert(unsigned char* out, const unsigned char* in, { size_t palettesize = mode_out->palettesize; const unsigned char* palette = mode_out->palette; - size_t palsize = 1u << mode_out->bitdepth; + size_t palsize = (size_t)1u << mode_out->bitdepth; /*if the user specified output palette but did not give the values, assume they want the values of the input color type (assuming that one is palette). Note that we never create a new palette ourselves.*/ @@ -3483,13 +3530,22 @@ unsigned lodepng_convert(unsigned char* out, const unsigned char* in, { palettesize = mode_in->palettesize; palette = mode_in->palette; + /*if the input was also palette with same bitdepth, then the color types are also + equal, so copy literally. This to preserve the exact indices that were in the PNG + even in case there are duplicate colors in the palette.*/ + if (mode_in->colortype == LCT_PALETTE && mode_in->bitdepth == mode_out->bitdepth) + { + size_t numbytes = lodepng_get_raw_size(w, h, mode_in); + for(i = 0; i != numbytes; ++i) out[i] = in[i]; + return 0; + } } if(palettesize < palsize) palsize = palettesize; color_tree_init(&tree); for(i = 0; i != palsize; ++i) { const unsigned char* p = &palette[i * 4]; - color_tree_add(&tree, p[0], p[1], p[2], p[3], i); + color_tree_add(&tree, p[0], p[1], p[2], p[3], (unsigned)i); } } @@ -3516,7 +3572,8 @@ unsigned lodepng_convert(unsigned char* out, const unsigned char* in, for(i = 0; i != numpixels; ++i) { getPixelColorRGBA8(&r, &g, &b, &a, in, i, mode_in); - CERROR_TRY_RETURN(rgba8ToPixel(out, i, mode_out, &tree, r, g, b, a)); + error = rgba8ToPixel(out, i, mode_out, &tree, r, g, b, a); + if (error) break; } } @@ -3525,7 +3582,7 @@ unsigned lodepng_convert(unsigned char* out, const unsigned char* in, color_tree_cleanup(&tree); } - return 0; /*no error*/ + return error; } #ifdef LODEPNG_COMPILE_ENCODER @@ -3534,8 +3591,8 @@ void lodepng_color_profile_init(LodePNGColorProfile* profile) { profile->colored = 0; profile->key = 0; - profile->alpha = 0; profile->key_r = profile->key_g = profile->key_b = 0; + profile->alpha = 0; profile->numcolors = 0; profile->bits = 1; } @@ -3571,7 +3628,7 @@ unsigned lodepng_get_color_profile(LodePNGColorProfile* profile, unsigned error = 0; size_t i; ColorTree tree; - size_t numpixels = w * h; + size_t numpixels = (size_t)w * (size_t)h; unsigned colored_done = lodepng_is_greyscale_type(mode) ? 1 : 0; unsigned alpha_done = lodepng_can_have_alpha(mode) ? 0 : 1; @@ -3622,8 +3679,8 @@ unsigned lodepng_get_color_profile(LodePNGColorProfile* profile, if(a != 65535 && (a != 0 || (profile->key && !matchkey))) { profile->alpha = 1; + profile->key = 0; alpha_done = 1; - if(profile->bits < 8) profile->bits = 8; /*PNG has no alphachannel modes with less than 8-bit per channel*/ } else if(a == 0 && !profile->alpha && !profile->key) { @@ -3636,6 +3693,7 @@ unsigned lodepng_get_color_profile(LodePNGColorProfile* profile, { /* Color key cannot be used if an opaque pixel also has that RGB color. */ profile->alpha = 1; + profile->key = 0; alpha_done = 1; } } @@ -3651,6 +3709,7 @@ unsigned lodepng_get_color_profile(LodePNGColorProfile* profile, { /* Color key cannot be used if an opaque pixel also has that RGB color. */ profile->alpha = 1; + profile->key = 0; alpha_done = 1; } } @@ -3684,6 +3743,7 @@ unsigned lodepng_get_color_profile(LodePNGColorProfile* profile, if(a != 255 && (a != 0 || (profile->key && !matchkey))) { profile->alpha = 1; + profile->key = 0; alpha_done = 1; if(profile->bits < 8) profile->bits = 8; /*PNG has no alphachannel modes with less than 8-bit per channel*/ } @@ -3698,6 +3758,7 @@ unsigned lodepng_get_color_profile(LodePNGColorProfile* profile, { /* Color key cannot be used if an opaque pixel also has that RGB color. */ profile->alpha = 1; + profile->key = 0; alpha_done = 1; if(profile->bits < 8) profile->bits = 8; /*PNG has no alphachannel modes with less than 8-bit per channel*/ } @@ -3734,7 +3795,9 @@ unsigned lodepng_get_color_profile(LodePNGColorProfile* profile, { /* Color key cannot be used if an opaque pixel also has that RGB color. */ profile->alpha = 1; + profile->key = 0; alpha_done = 1; + if(profile->bits < 8) profile->bits = 8; /*PNG has no alphachannel modes with less than 8-bit per channel*/ } } } @@ -3760,24 +3823,26 @@ unsigned lodepng_auto_choose_color(LodePNGColorMode* mode_out, { LodePNGColorProfile prof; unsigned error = 0; - unsigned i, n, palettebits, grey_ok, palette_ok; + unsigned palettebits, palette_ok; + size_t i, n; + size_t numpixels = (size_t)w * (size_t)h; lodepng_color_profile_init(&prof); error = lodepng_get_color_profile(&prof, image, w, h, mode_in); if(error) return error; mode_out->key_defined = 0; - if(prof.key && w * h <= 16) + if(prof.key && numpixels <= 16) { prof.alpha = 1; /*too few pixels to justify tRNS chunk overhead*/ + prof.key = 0; if(prof.bits < 8) prof.bits = 8; /*PNG has no alphachannel modes with less than 8-bit per channel*/ } - grey_ok = !prof.colored && !prof.alpha; /*grey without alpha, with potentially low bits*/ n = prof.numcolors; palettebits = n <= 2 ? 1 : (n <= 4 ? 2 : (n <= 16 ? 4 : 8)); - palette_ok = n <= 256 && (n * 2 < w * h) && prof.bits <= 8; - if(w * h < n * 2) palette_ok = 0; /*don't add palette overhead if image has only a few pixels*/ - if(grey_ok && prof.bits <= palettebits) palette_ok = 0; /*grey is less overhead*/ + palette_ok = n <= 256 && prof.bits <= 8; + if(numpixels < n * 2) palette_ok = 0; /*don't add palette overhead if image has only a few pixels*/ + if(!prof.colored && prof.bits <= palettebits) palette_ok = 0; /*grey is less overhead*/ if(palette_ok) { @@ -3806,7 +3871,7 @@ unsigned lodepng_auto_choose_color(LodePNGColorMode* mode_out, mode_out->colortype = prof.alpha ? (prof.colored ? LCT_RGBA : LCT_GREY_ALPHA) : (prof.colored ? LCT_RGB : LCT_GREY); - if(prof.key && !prof.alpha) + if(prof.key) { unsigned mask = (1u << mode_out->bitdepth) - 1u; /*profile always uses 16-bit, mask converts it*/ mode_out->key_r = prof.key_r & mask; @@ -4323,7 +4388,7 @@ static unsigned readChunk_tEXt(LodePNGInfo* info, const unsigned char* data, siz string2_begin = length + 1; /*skip keyword null terminator*/ - length = chunkLength < string2_begin ? 0 : chunkLength - string2_begin; + length = (unsigned)(chunkLength < string2_begin ? 0 : chunkLength - string2_begin); str = (char*)lodepng_malloc(length + 1); if(!str) CERROR_BREAK(error, 83); /*alloc fail*/ @@ -4371,7 +4436,7 @@ static unsigned readChunk_zTXt(LodePNGInfo* info, const LodePNGDecompressSetting string2_begin = length + 2; if(string2_begin > chunkLength) CERROR_BREAK(error, 75); /*no null termination, corrupt?*/ - length = chunkLength - string2_begin; + length = (unsigned)chunkLength - string2_begin; /*will fail if zlib error, e.g. if length is too small*/ error = zlib_decompress(&decoded.data, &decoded.size, (unsigned char*)(&data[string2_begin]), @@ -4451,7 +4516,7 @@ static unsigned readChunk_iTXt(LodePNGInfo* info, const LodePNGDecompressSetting /*read the actual text*/ begin += length + 1; - length = chunkLength < begin ? 0 : chunkLength - begin; + length = (unsigned)chunkLength < begin ? 0 : (unsigned)chunkLength - begin; if(compressed) { @@ -4523,7 +4588,6 @@ static void decodeGeneric(unsigned char** out, unsigned* w, unsigned* h, ucvector idat; /*the data from idat chunks*/ ucvector scanlines; size_t predict; - size_t numpixels; size_t outsize = 0; /*for unknown chunk order*/ @@ -4538,13 +4602,10 @@ static void decodeGeneric(unsigned char** out, unsigned* w, unsigned* h, state->error = lodepng_inspect(w, h, state, in, insize); /*reads header and resets other parameters in state->info_png*/ if(state->error) return; - numpixels = *w * *h; - - /*multiplication overflow*/ - if(*h != 0 && numpixels / *h != *w) CERROR_RETURN(state->error, 92); - /*multiplication overflow possible further below. Allows up to 2^31-1 pixel - bytes with 16-bit RGBA, the rest is room for filter bytes.*/ - if(numpixels > 268435455) CERROR_RETURN(state->error, 92); + if(lodepng_pixel_overflow(*w, *h, &state->info_png.color, &state->info_raw)) + { + CERROR_RETURN(state->error, 92); /*overflow possible due to amount of pixels*/ + } ucvector_init(&idat); chunk = &in[33]; /*first byte of the first chunk after the header*/ @@ -4557,12 +4618,20 @@ static void decodeGeneric(unsigned char** out, unsigned* w, unsigned* h, const unsigned char* data; /*the data in the chunk*/ /*error: size of the in buffer too small to contain next chunk*/ - if((size_t)((chunk - in) + 12) > insize || chunk < in) CERROR_BREAK(state->error, 30); + if((size_t)((chunk - in) + 12) > insize || chunk < in) + { + if(state->decoder.ignore_end) break; /*other errors may still happen though*/ + CERROR_BREAK(state->error, 30); + } /*length of the data of the chunk, excluding the length bytes, chunk type and CRC bytes*/ chunkLength = lodepng_chunk_length(chunk); /*error: chunk length larger than the max PNG chunk size*/ - if(chunkLength > 2147483647) CERROR_BREAK(state->error, 63); + if(chunkLength > 2147483647) + { + if(state->decoder.ignore_end) break; /*other errors may still happen though*/ + CERROR_BREAK(state->error, 63); + } if((size_t)((chunk - in) + chunkLength + 12) > insize || (chunk + chunkLength + 12) < in) { @@ -4575,7 +4644,9 @@ static void decodeGeneric(unsigned char** out, unsigned* w, unsigned* h, if(lodepng_chunk_type_equals(chunk, "IDAT")) { size_t oldsize = idat.size; - if(!ucvector_resize(&idat, oldsize + chunkLength)) CERROR_BREAK(state->error, 83 /*alloc fail*/); + size_t newsize; + if(lodepng_addofl(oldsize, chunkLength, &newsize)) CERROR_BREAK(state->error, 95); + if(!ucvector_resize(&idat, newsize)) CERROR_BREAK(state->error, 83 /*alloc fail*/); for(i = 0; i != chunkLength; ++i) idat.data[oldsize + i] = data[i]; #ifdef LODEPNG_COMPILE_ANCILLARY_CHUNKS critical_pos = 3; @@ -4649,7 +4720,10 @@ static void decodeGeneric(unsigned char** out, unsigned* w, unsigned* h, else /*it's not an implemented chunk type, so ignore it: skip over the data*/ { /*error: unknown critical chunk (5th bit of first byte of chunk type is 0)*/ - if(!lodepng_chunk_ancillary(chunk)) CERROR_BREAK(state->error, 69); + if(!state->decoder.ignore_critical && !lodepng_chunk_ancillary(chunk)) + { + CERROR_BREAK(state->error, 69); + } unknown = 1; #ifdef LODEPNG_COMPILE_ANCILLARY_CHUNKS @@ -4675,21 +4749,20 @@ static void decodeGeneric(unsigned char** out, unsigned* w, unsigned* h, If the decompressed size does not match the prediction, the image must be corrupt.*/ if(state->info_png.interlace_method == 0) { - /*The extra *h is added because this are the filter bytes every scanline starts with*/ - predict = lodepng_get_raw_size_idat(*w, *h, &state->info_png.color) + *h; + predict = lodepng_get_raw_size_idat(*w, *h, &state->info_png.color); } else { /*Adam-7 interlaced: predicted size is the sum of the 7 sub-images sizes*/ const LodePNGColorMode* color = &state->info_png.color; predict = 0; - predict += lodepng_get_raw_size_idat((*w + 7) >> 3, (*h + 7) >> 3, color) + ((*h + 7) >> 3); - if(*w > 4) predict += lodepng_get_raw_size_idat((*w + 3) >> 3, (*h + 7) >> 3, color) + ((*h + 7) >> 3); - predict += lodepng_get_raw_size_idat((*w + 3) >> 2, (*h + 3) >> 3, color) + ((*h + 3) >> 3); - if(*w > 2) predict += lodepng_get_raw_size_idat((*w + 1) >> 2, (*h + 3) >> 2, color) + ((*h + 3) >> 2); - predict += lodepng_get_raw_size_idat((*w + 1) >> 1, (*h + 1) >> 2, color) + ((*h + 1) >> 2); - if(*w > 1) predict += lodepng_get_raw_size_idat((*w + 0) >> 1, (*h + 1) >> 1, color) + ((*h + 1) >> 1); - predict += lodepng_get_raw_size_idat((*w + 0), (*h + 0) >> 1, color) + ((*h + 0) >> 1); + predict += lodepng_get_raw_size_idat((*w + 7) >> 3, (*h + 7) >> 3, color); + if(*w > 4) predict += lodepng_get_raw_size_idat((*w + 3) >> 3, (*h + 7) >> 3, color); + predict += lodepng_get_raw_size_idat((*w + 3) >> 2, (*h + 3) >> 3, color); + if(*w > 2) predict += lodepng_get_raw_size_idat((*w + 1) >> 2, (*h + 3) >> 2, color); + predict += lodepng_get_raw_size_idat((*w + 1) >> 1, (*h + 1) >> 2, color); + if(*w > 1) predict += lodepng_get_raw_size_idat((*w + 0) >> 1, (*h + 1) >> 1, color); + predict += lodepng_get_raw_size_idat((*w + 0), (*h + 0) >> 1, color); } if(!state->error && !ucvector_reserve(&scanlines, predict)) state->error = 83; /*alloc fail*/ if(!state->error) @@ -4814,6 +4887,8 @@ void lodepng_decoder_settings_init(LodePNGDecoderSettings* settings) settings->remember_unknown_chunks = 0; #endif /*LODEPNG_COMPILE_ANCILLARY_CHUNKS*/ settings->ignore_crc = 0; + settings->ignore_critical = 0; + settings->ignore_end = 0; lodepng_decompress_settings_init(&settings->zlibsettings); } @@ -5394,7 +5469,7 @@ static unsigned filter(unsigned char* out, const unsigned char* in, unsigned w, { for(type = 0; type != 5; ++type) { - unsigned testsize = linebytes; + unsigned testsize = (unsigned)linebytes; /*if(testsize > 8) testsize /= 8;*/ /*it already works good enough by testing a part of the row*/ filterScanline(attempt[type], &in[y * linebytes], prevline, linebytes, bytewidth, type); @@ -5645,22 +5720,12 @@ unsigned lodepng_encode(unsigned char** out, size_t* outsize, *outsize = 0; state->error = 0; - lodepng_info_init(&info); - lodepng_info_copy(&info, &state->info_png); - - if((info.color.colortype == LCT_PALETTE || state->encoder.force_palette) - && (info.color.palettesize == 0 || info.color.palettesize > 256)) + /*check input values validity*/ + if((state->info_png.color.colortype == LCT_PALETTE || state->encoder.force_palette) + && (state->info_png.color.palettesize == 0 || state->info_png.color.palettesize > 256)) { - state->error = 68; /*invalid palette size, it is only allowed to be 1-256*/ - return state->error; + CERROR_RETURN_ERROR(state->error, 68); /*invalid palette size, it is only allowed to be 1-256*/ } - - if(state->encoder.auto_convert) - { - state->error = lodepng_auto_choose_color(&info.color, image, w, h, &state->info_raw); - } - if(state->error) return state->error; - if(state->encoder.zlibsettings.btype > 2) { CERROR_RETURN_ERROR(state->error, 61); /*error: unexisting btype*/ @@ -5669,28 +5734,38 @@ unsigned lodepng_encode(unsigned char** out, size_t* outsize, { CERROR_RETURN_ERROR(state->error, 71); /*error: unexisting interlace mode*/ } - - state->error = checkColorValidity(info.color.colortype, info.color.bitdepth); + state->error = checkColorValidity(state->info_png.color.colortype, state->info_png.color.bitdepth); if(state->error) return state->error; /*error: unexisting color type given*/ state->error = checkColorValidity(state->info_raw.colortype, state->info_raw.bitdepth); if(state->error) return state->error; /*error: unexisting color type given*/ - if(!lodepng_color_mode_equal(&state->info_raw, &info.color)) + /* color convert and compute scanline filter types */ + lodepng_info_init(&info); + lodepng_info_copy(&info, &state->info_png); + if(state->encoder.auto_convert) { - unsigned char* converted; - size_t size = (w * h * (size_t)lodepng_get_bpp(&info.color) + 7) / 8; - - converted = (unsigned char*)lodepng_malloc(size); - if(!converted && size) state->error = 83; /*alloc fail*/ - if(!state->error) + state->error = lodepng_auto_choose_color(&info.color, image, w, h, &state->info_raw); + } + if (!state->error) + { + if(!lodepng_color_mode_equal(&state->info_raw, &info.color)) { - state->error = lodepng_convert(converted, image, &info.color, &state->info_raw, w, h); + unsigned char* converted; + size_t size = ((size_t)w * (size_t)h * (size_t)lodepng_get_bpp(&info.color) + 7) / 8; + + converted = (unsigned char*)lodepng_malloc(size); + if(!converted && size) state->error = 83; /*alloc fail*/ + if(!state->error) + { + state->error = lodepng_convert(converted, image, &info.color, &state->info_raw, w, h); + } + if(!state->error) preProcessScanlines(&data, &datasize, converted, w, h, &info, &state->encoder); + lodepng_free(converted); } - if(!state->error) preProcessScanlines(&data, &datasize, converted, w, h, &info, &state->encoder); - lodepng_free(converted); + else preProcessScanlines(&data, &datasize, image, w, h, &info, &state->encoder); } - else preProcessScanlines(&data, &datasize, image, w, h, &info, &state->encoder); + /* output all PNG chunks */ ucvector_init(&outv); while(!state->error) /*while only executed once, to break on error*/ { @@ -5989,9 +6064,10 @@ const char* lodepng_error_text(unsigned code) /*the windowsize in the LodePNGCompressSettings. Requiring POT(==> & instead of %) makes encoding 12% faster.*/ case 90: return "windowsize must be a power of two"; case 91: return "invalid decompressed idat size"; - case 92: return "too many pixels, not supported"; + case 92: return "integer overflow due to too many pixels"; case 93: return "zero width or height is invalid"; case 94: return "header chunk must have a size of 13 bytes"; + case 95: return "integer overflow with combined idat chunk size"; } return "unknown error code"; } diff --git a/tcod_sys/libtcod/src/png/lodepng.h b/tcod_sys/libtcod/src/vendor/lodepng.h similarity index 98% rename from tcod_sys/libtcod/src/png/lodepng.h rename to tcod_sys/libtcod/src/vendor/lodepng.h index fcf9f714b..6c56c1dfd 100644 --- a/tcod_sys/libtcod/src/png/lodepng.h +++ b/tcod_sys/libtcod/src/vendor/lodepng.h @@ -1,7 +1,7 @@ /* -LodePNG version 20160501 +LodePNG version 20180611 -Copyright (c) 2005-2016 Lode Vandevenne +Copyright (c) 2005-2018 Lode Vandevenne This software is provided 'as-is', without any express or implied warranty. In no event will the authors be held liable for any damages @@ -255,6 +255,7 @@ const char* lodepng_error_text(unsigned code); typedef struct LodePNGDecompressSettings LodePNGDecompressSettings; struct LodePNGDecompressSettings { + /* Check LodePNGDecoderSettings for more ignorable errors */ unsigned ignore_adler32; /*if 1, continue and don't give an error message if the Adler32 checksum is corrupted*/ /*use custom zlib decoder instead of built in one (default: null)*/ @@ -409,7 +410,7 @@ typedef struct LodePNGInfo /*header (IHDR), palette (PLTE) and transparency (tRNS) chunks*/ unsigned compression_method;/*compression method of the original file. Always 0.*/ unsigned filter_method; /*filter method of the original file*/ - unsigned interlace_method; /*interlace method of the original file*/ + unsigned interlace_method; /*interlace method of the original file: 0=none, 1=Adam7*/ LodePNGColorMode color; /*color type and bits, palette and transparency of the PNG file*/ #ifdef LODEPNG_COMPILE_ANCILLARY_CHUNKS @@ -520,7 +521,10 @@ typedef struct LodePNGDecoderSettings { LodePNGDecompressSettings zlibsettings; /*in here is the setting to ignore Adler32 checksums*/ + /* Check LodePNGDecompressSettings for more ignorable errors */ unsigned ignore_crc; /*ignore CRC checksums*/ + unsigned ignore_critical; /*ignore unknown critical chunks*/ + unsigned ignore_end; /*ignore issues at end of file if possible (missing IEND chunk, too large chunk, ...)*/ unsigned color_convert; /*whether to convert the PNG to the color type you want. Default: yes*/ @@ -559,11 +563,11 @@ Used internally by default if "auto_convert" is enabled. Public because it's use typedef struct LodePNGColorProfile { unsigned colored; /*not greyscale*/ - unsigned key; /*if true, image is not opaque. Only if true and alpha is false, color key is possible.*/ - unsigned short key_r; /*these values are always in 16-bit bitdepth in the profile*/ + unsigned key; /*image is not opaque and color key is possible instead of full alpha*/ + unsigned short key_r; /*key values, always as 16-bit, in 8-bit case the byte is duplicated, e.g. 65535 means 255*/ unsigned short key_g; unsigned short key_b; - unsigned alpha; /*alpha channel or alpha palette required*/ + unsigned alpha; /*image is not opaque and alpha channel or alpha palette required*/ unsigned numcolors; /*amount of colors, up to 257. Not valid if bits == 16.*/ unsigned char palette[1024]; /*Remembers up to the first 256 RGBA colors, in no particular order*/ unsigned bits; /*bits per channel (not for palette). 1,2 or 4 for greyscale only. 16 if 16-bit per channel required.*/ @@ -1567,6 +1571,8 @@ For decoding: state.decoder.zlibsettings.ignore_adler32: ignore ADLER32 checksums state.decoder.zlibsettings.custom_...: use custom inflate function state.decoder.ignore_crc: ignore CRC checksums +state.decoder.ignore_critical: ignore unknown critical chunks +state.decoder.ignore_end: ignore missing IEND chunk. May fail if this corruption causes other errors state.decoder.color_convert: convert internal PNG color to chosen one state.decoder.read_text_chunks: whether to read in text metadata chunks state.decoder.remember_unknown_chunks: whether to read in unknown chunks @@ -1608,6 +1614,10 @@ yyyymmdd. Some changes aren't backwards compatible. Those are indicated with a (!) symbol. +*) 11 jun 2018: less restrictive check for pixel size integer overflow +*) 14 jan 2018: allow optionally ignoring a few more recoverable errors +*) 17 sep 2017: fix memory leak for some encoder input error cases +*) 27 nov 2016: grey+alpha auto color model detection bugfix *) 18 apr 2016: Changed qsort to custom stable sort (for platforms w/o qsort). *) 09 apr 2016: Fixed colorkey usage detection, and better file loading (within the limits of pure C90). @@ -1756,5 +1766,5 @@ Domain: gmail dot com. Account: lode dot vandevenne. -Copyright (c) 2005-2016 Lode Vandevenne +Copyright (c) 2005-2018 Lode Vandevenne */ From 7086c531842414ad096af27fc331959779bf1342 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Zolt=C3=A1n=20Nagy?= Date: Thu, 6 Jun 2019 23:15:00 +0100 Subject: [PATCH 04/15] Upgraded libtcod to 1.12.3 --- tcod_sys/build.rs | 64 +- tcod_sys/libtcod/LIBTCOD-CREDITS.txt | 4 + tcod_sys/libtcod/README.md | 61 +- tcod_sys/libtcod/src/libtcod/bresenham.cpp | 58 +- tcod_sys/libtcod/src/libtcod/bresenham.h | 58 +- tcod_sys/libtcod/src/libtcod/bresenham.hpp | 58 +- tcod_sys/libtcod/src/libtcod/bresenham_c.c | 58 +- tcod_sys/libtcod/src/libtcod/bsp.cpp | 62 +- tcod_sys/libtcod/src/libtcod/bsp.h | 58 +- tcod_sys/libtcod/src/libtcod/bsp.hpp | 64 +- tcod_sys/libtcod/src/libtcod/bsp_c.c | 82 +- tcod_sys/libtcod/src/libtcod/color.cpp | 81 +- tcod_sys/libtcod/src/libtcod/color.h | 67 +- tcod_sys/libtcod/src/libtcod/color.hpp | 183 +- tcod_sys/libtcod/src/libtcod/color/canvas.cpp | 61 +- tcod_sys/libtcod/src/libtcod/color/canvas.h | 33 +- tcod_sys/libtcod/src/libtcod/color/color.h | 98 +- tcod_sys/libtcod/src/libtcod/color_c.c | 58 +- tcod_sys/libtcod/src/libtcod/console.cpp | 162 +- tcod_sys/libtcod/src/libtcod/console.h | 170 +- tcod_sys/libtcod/src/libtcod/console.hpp | 112 +- .../libtcod/src/libtcod/console/console.h | 427 ++ .../src/libtcod/console/console_clobbered.cpp | 431 ++ .../libtcod/src/libtcod/console/drawing.cpp | 118 + .../libtcod/src/libtcod/console/drawing.h | 117 + .../libtcod/src/libtcod/console/printing.cpp | 1399 +++++ .../libtcod/src/libtcod/console/printing.h | 153 + .../rexpaint.cpp} | 117 +- .../libtcod/src/libtcod/console/rexpaint.h | 46 + tcod_sys/libtcod/src/libtcod/console_c.cpp | 1134 +--- .../libtcod/src/libtcod/console_printing.c | 1086 ---- .../libtcod/src/libtcod/console_rexpaint.h | 50 - tcod_sys/libtcod/src/libtcod/console_types.h | 130 +- tcod_sys/libtcod/src/libtcod/deprecated.cpp | 38 + .../libtcod/src/libtcod/engine/backend.cpp | 32 +- tcod_sys/libtcod/src/libtcod/engine/backend.h | 40 +- .../libtcod/src/libtcod/engine/display.cpp | 237 +- tcod_sys/libtcod/src/libtcod/engine/display.h | 240 +- tcod_sys/libtcod/src/libtcod/engine/error.cpp | 69 + tcod_sys/libtcod/src/libtcod/engine/error.h | 73 + .../libtcod/src/libtcod/engine/globals.cpp | 45 +- tcod_sys/libtcod/src/libtcod/engine/globals.h | 71 +- tcod_sys/libtcod/src/libtcod/fov.cpp | 58 +- tcod_sys/libtcod/src/libtcod/fov.h | 58 +- tcod_sys/libtcod/src/libtcod/fov.hpp | 58 +- tcod_sys/libtcod/src/libtcod/fov_c.c | 62 +- .../src/libtcod/fov_circular_raycasting.c | 58 +- .../src/libtcod/fov_diamond_raycasting.c | 58 +- .../libtcod/src/libtcod/fov_permissive2.c | 58 +- .../src/libtcod/fov_recursive_shadowcasting.c | 58 +- .../libtcod/src/libtcod/fov_restrictive.c | 58 +- tcod_sys/libtcod/src/libtcod/fov_types.h | 58 +- tcod_sys/libtcod/src/libtcod/gui/button.cpp | 179 +- tcod_sys/libtcod/src/libtcod/gui/button.hpp | 58 +- .../libtcod/src/libtcod/gui/container.cpp | 58 +- .../libtcod/src/libtcod/gui/container.hpp | 58 +- tcod_sys/libtcod/src/libtcod/gui/flatlist.cpp | 58 +- tcod_sys/libtcod/src/libtcod/gui/flatlist.hpp | 58 +- tcod_sys/libtcod/src/libtcod/gui/gui.hpp | 58 +- .../src/libtcod/gui/gui_portability.hpp | 68 +- tcod_sys/libtcod/src/libtcod/gui/hbox.cpp | 58 +- tcod_sys/libtcod/src/libtcod/gui/hbox.hpp | 58 +- tcod_sys/libtcod/src/libtcod/gui/image.cpp | 58 +- tcod_sys/libtcod/src/libtcod/gui/image.hpp | 58 +- tcod_sys/libtcod/src/libtcod/gui/label.cpp | 84 +- tcod_sys/libtcod/src/libtcod/gui/label.hpp | 58 +- .../libtcod/src/libtcod/gui/radiobutton.cpp | 58 +- .../libtcod/src/libtcod/gui/radiobutton.hpp | 58 +- tcod_sys/libtcod/src/libtcod/gui/slider.cpp | 120 +- tcod_sys/libtcod/src/libtcod/gui/slider.hpp | 58 +- .../libtcod/src/libtcod/gui/statusbar.cpp | 60 +- .../libtcod/src/libtcod/gui/statusbar.hpp | 58 +- tcod_sys/libtcod/src/libtcod/gui/textbox.cpp | 74 +- tcod_sys/libtcod/src/libtcod/gui/textbox.hpp | 58 +- .../libtcod/src/libtcod/gui/togglebutton.cpp | 58 +- .../libtcod/src/libtcod/gui/togglebutton.hpp | 58 +- tcod_sys/libtcod/src/libtcod/gui/toolbar.cpp | 81 +- tcod_sys/libtcod/src/libtcod/gui/toolbar.hpp | 58 +- tcod_sys/libtcod/src/libtcod/gui/vbox.cpp | 58 +- tcod_sys/libtcod/src/libtcod/gui/vbox.hpp | 58 +- tcod_sys/libtcod/src/libtcod/gui/widget.cpp | 128 +- tcod_sys/libtcod/src/libtcod/gui/widget.hpp | 60 +- tcod_sys/libtcod/src/libtcod/heightmap.cpp | 66 +- tcod_sys/libtcod/src/libtcod/heightmap.h | 59 +- tcod_sys/libtcod/src/libtcod/heightmap.hpp | 60 +- tcod_sys/libtcod/src/libtcod/heightmap_c.c | 62 +- tcod_sys/libtcod/src/libtcod/image.cpp | 58 +- tcod_sys/libtcod/src/libtcod/image.h | 133 +- tcod_sys/libtcod/src/libtcod/image.hpp | 58 +- tcod_sys/libtcod/src/libtcod/image_c.c | 868 --- tcod_sys/libtcod/src/libtcod/image_c.cpp | 909 +++ tcod_sys/libtcod/src/libtcod/lex.cpp | 133 +- tcod_sys/libtcod/src/libtcod/lex.h | 58 +- tcod_sys/libtcod/src/libtcod/lex.hpp | 161 +- tcod_sys/libtcod/src/libtcod/lex_c.c | 101 +- tcod_sys/libtcod/src/libtcod/libtcod.h | 70 +- tcod_sys/libtcod/src/libtcod/libtcod.hpp | 58 +- tcod_sys/libtcod/src/libtcod/libtcod_int.h | 239 +- tcod_sys/libtcod/src/libtcod/list.h | 58 +- tcod_sys/libtcod/src/libtcod/list.hpp | 90 +- tcod_sys/libtcod/src/libtcod/list_c.c | 58 +- tcod_sys/libtcod/src/libtcod/mersenne.cpp | 61 +- tcod_sys/libtcod/src/libtcod/mersenne.h | 58 +- tcod_sys/libtcod/src/libtcod/mersenne.hpp | 60 +- tcod_sys/libtcod/src/libtcod/mersenne_c.c | 58 +- tcod_sys/libtcod/src/libtcod/mersenne_types.h | 58 +- tcod_sys/libtcod/src/libtcod/mouse.cpp | 58 +- tcod_sys/libtcod/src/libtcod/mouse.h | 58 +- tcod_sys/libtcod/src/libtcod/mouse.hpp | 58 +- tcod_sys/libtcod/src/libtcod/mouse_types.h | 58 +- tcod_sys/libtcod/src/libtcod/namegen.cpp | 58 +- tcod_sys/libtcod/src/libtcod/namegen.h | 58 +- tcod_sys/libtcod/src/libtcod/namegen.hpp | 58 +- tcod_sys/libtcod/src/libtcod/namegen_c.c | 58 +- tcod_sys/libtcod/src/libtcod/noise.cpp | 58 +- tcod_sys/libtcod/src/libtcod/noise.h | 58 +- tcod_sys/libtcod/src/libtcod/noise.hpp | 58 +- tcod_sys/libtcod/src/libtcod/noise_c.c | 58 +- tcod_sys/libtcod/src/libtcod/noise_defaults.h | 58 +- tcod_sys/libtcod/src/libtcod/parser.cpp | 74 +- tcod_sys/libtcod/src/libtcod/parser.h | 60 +- tcod_sys/libtcod/src/libtcod/parser.hpp | 58 +- tcod_sys/libtcod/src/libtcod/parser_c.c | 60 +- tcod_sys/libtcod/src/libtcod/path.cpp | 85 +- tcod_sys/libtcod/src/libtcod/path.h | 58 +- tcod_sys/libtcod/src/libtcod/path.hpp | 58 +- tcod_sys/libtcod/src/libtcod/path_c.c | 58 +- .../libtcod/src/libtcod/pathfinding/astar.cpp | 32 + .../libtcod/src/libtcod/pathfinding/astar.h | 40 + .../src/libtcod/pathfinding/dijkstra.cpp | 32 + .../src/libtcod/pathfinding/dijkstra.h | 124 + .../src/libtcod/pathfinding/generic.cpp | 32 + .../libtcod/src/libtcod/pathfinding/generic.h | 179 + tcod_sys/libtcod/src/libtcod/portability.h | 94 +- .../src/libtcod/sdl2/console_2tris.glslf | 46 + .../src/libtcod/sdl2/console_2tris.glslv | 18 + .../src/libtcod/sdl2/console_grid.glslf | 16 + .../src/libtcod/sdl2/console_grid.glslv | 22 + tcod_sys/libtcod/src/libtcod/sdl2/event.cpp | 65 + tcod_sys/libtcod/src/libtcod/sdl2/event.h | 90 + .../libtcod/src/libtcod/sdl2/gl2_display.cpp | 91 + .../libtcod/src/libtcod/sdl2/gl2_display.h | 59 + tcod_sys/libtcod/src/libtcod/sdl2/gl2_ext_.h | 68 + .../libtcod/src/libtcod/sdl2/gl2_raii.cpp | 230 + tcod_sys/libtcod/src/libtcod/sdl2/gl2_raii.h | 195 + .../libtcod/src/libtcod/sdl2/gl2_renderer.cpp | 424 ++ .../libtcod/src/libtcod/sdl2/gl2_renderer.h | 71 + .../libtcod/src/libtcod/sdl2/gl_alias.cpp | 281 + tcod_sys/libtcod/src/libtcod/sdl2/gl_alias.h | 71 + .../src/libtcod/sdl2/legacy_backend.cpp | 32 +- .../libtcod/src/libtcod/sdl2/legacy_backend.h | 32 +- .../libtcod/src/libtcod/sdl2/sdl2_alias.cpp | 298 +- .../libtcod/src/libtcod/sdl2/sdl2_alias.h | 59 +- .../libtcod/src/libtcod/sdl2/sdl2_display.cpp | 123 +- .../libtcod/src/libtcod/sdl2/sdl2_display.h | 83 +- .../src/libtcod/sdl2/sdl2_renderer.cpp | 240 +- .../libtcod/src/libtcod/sdl2/sdl2_renderer.h | 63 +- tcod_sys/libtcod/src/libtcod/sys.cpp | 64 +- tcod_sys/libtcod/src/libtcod/sys.h | 65 +- tcod_sys/libtcod/src/libtcod/sys.hpp | 86 +- tcod_sys/libtcod/src/libtcod/sys_c.cpp | 222 +- tcod_sys/libtcod/src/libtcod/sys_opengl_c.cpp | 1149 ++-- tcod_sys/libtcod/src/libtcod/sys_sdl2_c.cpp | 170 +- tcod_sys/libtcod/src/libtcod/sys_sdl_c.cpp | 1191 ++-- .../libtcod/src/libtcod/sys_sdl_img_bmp.cpp | 62 +- .../libtcod/src/libtcod/sys_sdl_img_png.cpp | 72 +- .../libtcod/src/libtcod/tileset/fallback.cpp | 83 + .../libtcod/src/libtcod/tileset/fallback.h | 53 + .../libtcod/src/libtcod/tileset/observer.cpp | 32 +- .../libtcod/src/libtcod/tileset/observer.h | 41 +- tcod_sys/libtcod/src/libtcod/tileset/tile.cpp | 32 +- tcod_sys/libtcod/src/libtcod/tileset/tile.h | 48 +- .../libtcod/src/libtcod/tileset/tileset.cpp | 79 +- .../libtcod/src/libtcod/tileset/tileset.h | 112 +- .../libtcod/src/libtcod/tileset/tilesheet.cpp | 213 +- .../libtcod/src/libtcod/tileset/tilesheet.h | 148 +- .../libtcod/src/libtcod/tileset/truetype.cpp | 265 + .../libtcod/src/libtcod/tileset/truetype.h | 67 + tcod_sys/libtcod/src/libtcod/tree.h | 58 +- tcod_sys/libtcod/src/libtcod/tree.hpp | 58 +- tcod_sys/libtcod/src/libtcod/tree_c.c | 58 +- tcod_sys/libtcod/src/libtcod/txtfield.cpp | 58 +- tcod_sys/libtcod/src/libtcod/txtfield.h | 58 +- tcod_sys/libtcod/src/libtcod/txtfield.hpp | 58 +- tcod_sys/libtcod/src/libtcod/txtfield_c.c | 58 +- tcod_sys/libtcod/src/libtcod/utility.h | 58 +- tcod_sys/libtcod/src/libtcod/utility/matrix.h | 230 + .../libtcod/src/libtcod/utility/vector2.h | 153 +- tcod_sys/libtcod/src/libtcod/version.h | 64 +- .../src/libtcod/{wrappers.c => wrappers.cpp} | 140 +- tcod_sys/libtcod/src/libtcod/wrappers.h | 58 +- tcod_sys/libtcod/src/libtcod/zip.cpp | 58 +- tcod_sys/libtcod/src/libtcod/zip.h | 58 +- tcod_sys/libtcod/src/libtcod/zip.hpp | 58 +- tcod_sys/libtcod/src/libtcod/zip_c.c | 58 +- tcod_sys/libtcod/src/vendor/glad.c | 1321 +++++ tcod_sys/libtcod/src/vendor/glad.h | 2656 +++++++++ tcod_sys/libtcod/src/vendor/khrplatform.h | 282 + tcod_sys/libtcod/src/vendor/stb.c | 4 + tcod_sys/libtcod/src/vendor/stb_truetype.h | 4894 +++++++++++++++++ 200 files changed, 24509 insertions(+), 8673 deletions(-) create mode 100644 tcod_sys/libtcod/src/libtcod/console/console.h create mode 100644 tcod_sys/libtcod/src/libtcod/console/console_clobbered.cpp create mode 100644 tcod_sys/libtcod/src/libtcod/console/drawing.cpp create mode 100644 tcod_sys/libtcod/src/libtcod/console/drawing.h create mode 100644 tcod_sys/libtcod/src/libtcod/console/printing.cpp create mode 100644 tcod_sys/libtcod/src/libtcod/console/printing.h rename tcod_sys/libtcod/src/libtcod/{console_rexpaint.c => console/rexpaint.cpp} (76%) create mode 100644 tcod_sys/libtcod/src/libtcod/console/rexpaint.h delete mode 100644 tcod_sys/libtcod/src/libtcod/console_printing.c delete mode 100644 tcod_sys/libtcod/src/libtcod/console_rexpaint.h create mode 100644 tcod_sys/libtcod/src/libtcod/deprecated.cpp create mode 100644 tcod_sys/libtcod/src/libtcod/engine/error.cpp create mode 100644 tcod_sys/libtcod/src/libtcod/engine/error.h delete mode 100644 tcod_sys/libtcod/src/libtcod/image_c.c create mode 100644 tcod_sys/libtcod/src/libtcod/image_c.cpp create mode 100644 tcod_sys/libtcod/src/libtcod/pathfinding/astar.cpp create mode 100644 tcod_sys/libtcod/src/libtcod/pathfinding/astar.h create mode 100644 tcod_sys/libtcod/src/libtcod/pathfinding/dijkstra.cpp create mode 100644 tcod_sys/libtcod/src/libtcod/pathfinding/dijkstra.h create mode 100644 tcod_sys/libtcod/src/libtcod/pathfinding/generic.cpp create mode 100644 tcod_sys/libtcod/src/libtcod/pathfinding/generic.h create mode 100644 tcod_sys/libtcod/src/libtcod/sdl2/console_2tris.glslf create mode 100644 tcod_sys/libtcod/src/libtcod/sdl2/console_2tris.glslv create mode 100644 tcod_sys/libtcod/src/libtcod/sdl2/console_grid.glslf create mode 100644 tcod_sys/libtcod/src/libtcod/sdl2/console_grid.glslv create mode 100644 tcod_sys/libtcod/src/libtcod/sdl2/event.cpp create mode 100644 tcod_sys/libtcod/src/libtcod/sdl2/event.h create mode 100644 tcod_sys/libtcod/src/libtcod/sdl2/gl2_display.cpp create mode 100644 tcod_sys/libtcod/src/libtcod/sdl2/gl2_display.h create mode 100644 tcod_sys/libtcod/src/libtcod/sdl2/gl2_ext_.h create mode 100644 tcod_sys/libtcod/src/libtcod/sdl2/gl2_raii.cpp create mode 100644 tcod_sys/libtcod/src/libtcod/sdl2/gl2_raii.h create mode 100644 tcod_sys/libtcod/src/libtcod/sdl2/gl2_renderer.cpp create mode 100644 tcod_sys/libtcod/src/libtcod/sdl2/gl2_renderer.h create mode 100644 tcod_sys/libtcod/src/libtcod/sdl2/gl_alias.cpp create mode 100644 tcod_sys/libtcod/src/libtcod/sdl2/gl_alias.h create mode 100644 tcod_sys/libtcod/src/libtcod/tileset/fallback.cpp create mode 100644 tcod_sys/libtcod/src/libtcod/tileset/fallback.h create mode 100644 tcod_sys/libtcod/src/libtcod/tileset/truetype.cpp create mode 100644 tcod_sys/libtcod/src/libtcod/tileset/truetype.h create mode 100644 tcod_sys/libtcod/src/libtcod/utility/matrix.h rename tcod_sys/libtcod/src/libtcod/{wrappers.c => wrappers.cpp} (73%) create mode 100644 tcod_sys/libtcod/src/vendor/glad.c create mode 100644 tcod_sys/libtcod/src/vendor/glad.h create mode 100644 tcod_sys/libtcod/src/vendor/khrplatform.h create mode 100644 tcod_sys/libtcod/src/vendor/stb_truetype.h diff --git a/tcod_sys/build.rs b/tcod_sys/build.rs index 99b1bd633..faca6332e 100644 --- a/tcod_sys/build.rs +++ b/tcod_sys/build.rs @@ -15,10 +15,23 @@ fn build_libz(libz_sources: &[&str]) { config.compile("libz.a"); } +fn add_includes(config: &mut cc::Build) { + config.include(Path::new("libtcod").join("src").join("vendor")); + config.include(Path::new("libtcod").join("src").join("vendor").join("utf8proc")); + config.include(Path::new("libtcod").join("src").join("vendor").join("zlib")); + config.include(Path::new("libtcod").join("src").join("libtcod").join("color")); + config.include(Path::new("libtcod").join("src").join("libtcod").join("console")); + config.include(Path::new("libtcod").join("src").join("libtcod").join("engine")); + config.include(Path::new("libtcod").join("src").join("libtcod").join("gui")); + config.include(Path::new("libtcod").join("src").join("libtcod").join("sdl2")); + config.include(Path::new("libtcod").join("src").join("libtcod").join("pathfinding")); + config.include(Path::new("libtcod").join("src").join("libtcod").join("tileset")); + config.include(Path::new("libtcod").join("src").join("libtcod").join("utility")); + config.include(Path::new("libtcod").join("src").join("libtcod")); +} + fn build_libtcod_objects(mut config: cc::Build, sources: &[&str]) { - config.include("libtcod/src/libtcod"); - config.include("libtcod/src/vendor/utf8proc"); - config.include("libtcod/src/vendor/zlib"); + add_includes(&mut config); for c_file in sources { config.file(c_file); } @@ -146,6 +159,7 @@ fn main() { ]; let vendor_sources = &[ + "libtcod/src/vendor/glad.c", "libtcod/src/vendor/stb.c", "libtcod/src/vendor/lodepng.cpp", "libtcod/src/vendor/utf8proc/utf8proc.c", @@ -157,8 +171,7 @@ fn main() { "libtcod/src/libtcod/color_c.c", "libtcod/src/libtcod/console.cpp", "libtcod/src/libtcod/console_c.cpp", - "libtcod/src/libtcod/console_printing.c", - "libtcod/src/libtcod/console_rexpaint.c", + "libtcod/src/libtcod/deprecated.cpp", "libtcod/src/libtcod/fov_c.c", "libtcod/src/libtcod/fov_circular_raycasting.c", "libtcod/src/libtcod/fov_diamond_raycasting.c", @@ -167,7 +180,7 @@ fn main() { "libtcod/src/libtcod/fov_restrictive.c", "libtcod/src/libtcod/heightmap_c.c", "libtcod/src/libtcod/image.cpp", - "libtcod/src/libtcod/image_c.c", + "libtcod/src/libtcod/image_c.cpp", "libtcod/src/libtcod/lex_c.c", "libtcod/src/libtcod/list_c.c", "libtcod/src/libtcod/mersenne_c.c", @@ -183,13 +196,23 @@ fn main() { "libtcod/src/libtcod/sys_sdl_img_png.cpp", "libtcod/src/libtcod/tree_c.c", "libtcod/src/libtcod/txtfield_c.c", - "libtcod/src/libtcod/wrappers.c", + "libtcod/src/libtcod/wrappers.cpp", "libtcod/src/libtcod/zip_c.c", // color "libtcod/src/libtcod/color/canvas.cpp", + // console + // Note that console/console.cpp here was renamed because MSVC can't deal with source + // files with the same name in different dirs (output is the same .obj file for each). + // I failed to make this go away with /Fo. + // See https://stackoverflow.com/questions/3729515/visual-studio-2010-2008-cant-handle-source-files-with-identical-names-in-diff/ + "libtcod/src/libtcod/console/console_clobbered.cpp", + "libtcod/src/libtcod/console/drawing.cpp", + "libtcod/src/libtcod/console/printing.cpp", + "libtcod/src/libtcod/console/rexpaint.cpp", // engine "libtcod/src/libtcod/engine/backend.cpp", "libtcod/src/libtcod/engine/display.cpp", + "libtcod/src/libtcod/engine/error.cpp", "libtcod/src/libtcod/engine/globals.cpp", // gui // "libtcod/src/libtcod/gui/button.cpp", @@ -206,16 +229,27 @@ fn main() { // "libtcod/src/libtcod/gui/toolbar.cpp", // "libtcod/src/libtcod/gui/vbox.cpp", // "libtcod/src/libtcod/gui/widget.cpp", + // pathfinding + "libtcod/src/libtcod/pathfinding/astar.cpp", + "libtcod/src/libtcod/pathfinding/dijkstra.cpp", + "libtcod/src/libtcod/pathfinding/generic.cpp", // sdl2 + "libtcod/src/libtcod/sdl2/event.cpp", + "libtcod/src/libtcod/sdl2/gl2_display.cpp", + "libtcod/src/libtcod/sdl2/gl2_raii.cpp", + "libtcod/src/libtcod/sdl2/gl2_renderer.cpp", + "libtcod/src/libtcod/sdl2/gl_alias.cpp", "libtcod/src/libtcod/sdl2/legacy_backend.cpp", "libtcod/src/libtcod/sdl2/sdl2_alias.cpp", "libtcod/src/libtcod/sdl2/sdl2_display.cpp", "libtcod/src/libtcod/sdl2/sdl2_renderer.cpp", // tileset + "libtcod/src/libtcod/tileset/fallback.cpp", "libtcod/src/libtcod/tileset/observer.cpp", "libtcod/src/libtcod/tileset/tile.cpp", "libtcod/src/libtcod/tileset/tileset.cpp", "libtcod/src/libtcod/tileset/tilesheet.cpp", + "libtcod/src/libtcod/tileset/truetype.cpp", ]; if target.contains("linux") { @@ -289,10 +323,7 @@ fn main() { config.flag("-shared"); fs::create_dir(dst.join("lib")).unwrap(); config.flag(&format!("-Wl,--out-implib,{}", dst.join("lib/libtcod.a").display())); - config.include(Path::new("libtcod").join("src").join("vendor")); - config.include(Path::new("libtcod").join("src").join("vendor").join("utf8proc")); - config.include(Path::new("libtcod").join("src").join("vendor").join("zlib")); - config.include(Path::new("libtcod").join("src").join("libtcod")); + add_includes(&mut config); for c_file in libz_sources.iter().chain(libtcod_sources.iter()).chain(vendor_sources) { let path = c_file.split('/').fold(PathBuf::new(), |path, segment| path.join(segment)); config.flag(src.join(path).to_str().unwrap()); @@ -330,16 +361,7 @@ fn main() { config.flag("/EHsc"); config.flag(&format!("/Fo:{}\\", dst.to_str().unwrap())); config.include(sdl_include_dir.to_str().unwrap()); - config.include(Path::new("libtcod").join("src").join("vendor")); - config.include(Path::new("libtcod").join("src").join("vendor").join("utf8proc")); - config.include(Path::new("libtcod").join("src").join("vendor").join("zlib")); - config.include(Path::new("libtcod").join("src").join("libtcod")); - config.include(Path::new("libtcod").join("src").join("libtcod").join("color")); - config.include(Path::new("libtcod").join("src").join("libtcod").join("engine")); - config.include(Path::new("libtcod").join("src").join("libtcod").join("gui")); - config.include(Path::new("libtcod").join("src").join("libtcod").join("sdl2")); - config.include(Path::new("libtcod").join("src").join("libtcod").join("tileset")); - config.include(Path::new("libtcod").join("src").join("libtcod").join("utility")); + add_includes(&mut config); for c_file in libz_sources.iter().chain(vendor_sources).chain(libtcod_sources.iter()) { // Make sure the path is in the Windows format. This // shouldn't matter but it's distracting when debugging diff --git a/tcod_sys/libtcod/LIBTCOD-CREDITS.txt b/tcod_sys/libtcod/LIBTCOD-CREDITS.txt index 70a8d6bc0..19ebf004f 100644 --- a/tcod_sys/libtcod/LIBTCOD-CREDITS.txt +++ b/tcod_sys/libtcod/LIBTCOD-CREDITS.txt @@ -9,9 +9,13 @@ Products : - stb_sprintf, originally by Jeff Roberts / RAD Game Tools, 2015/10/20 http://github.com/nothings/stb (modified to compile for C89) +- stb_truetype, authored from 2009-2016 by Sean Barrett / RAD Game Tools + http://github.com/nothings/stb - utf8proc https://github.com/JuliaStrings/utf8proc (modified to be statically linkable, and to compile for C89) +- glad + https://github.com/Dav1dde/glad Many thanks to everyone who provided feedback and patches, and especially : - Dominik 'Mingos' Marczuk for the restrictive shadowcasting fov, djikstra diff --git a/tcod_sys/libtcod/README.md b/tcod_sys/libtcod/README.md index 06c4b7d3e..14abf722e 100644 --- a/tcod_sys/libtcod/README.md +++ b/tcod_sys/libtcod/README.md @@ -17,51 +17,50 @@ utilities frequently used in roguelikes. Status: [![Build status](https://ci.appveyor.com/api/projects/status/pemepxo2221f8heo/branch/master?svg=true)](https://ci.appveyor.com/project/HexDecimal/libtcod-6e1jk/branch/master) [![Build Status](https://travis-ci.org/libtcod/libtcod.svg?branch=master)](https://travis-ci.org/libtcod/libtcod) +[![Documentation Status](https://readthedocs.org/projects/libtcod/badge/?version=latest)](https://libtcod.readthedocs.io/en/latest/?badge=latest) # What can it do? # -If you want to get a quick overview of the features that libtcod provides, check out the [Features](https://bitbucket.org/libtcod/libtcod/wiki/Features) page. +If you want to get a quick overview of the features that libtcod provides, +check out the [Features](https://bitbucket.org/libtcod/libtcod/wiki/Features) +page. -If you want to get a quick overview of games which have used libtcod, check out the [Projects](http://roguecentral.org/doryen/projects-2/) page. - -libtcod is also well known for it's [easy to follow tutorial](http://www.roguebasin.com/index.php?title=Complete_Roguelike_Tutorial,_using_python%2Blibtcod), which many people have used to get started developing a roguelike. Follow the relevant links the tutorial gives, and it will point you to the right locations. +If you want to get a quick overview of games which have used libtcod, check out +the [Projects](http://roguecentral.org/doryen/projects-2/) page. # How do I get set up? # ## Using one of our downloads ## +If you are programming in C or C++ then Windows and MacOS binaries are available from the [GitHub Releases page](https://github.com/libtcod/libtcod/releases). -If you are programming in C or C++, various sample projects are included within +Various C/C++ sample projects are included within the repository which can be used as examples of various features. -For those who wish to program in Python which is the only scripting language -support that has been contributed so far, the basics are described in -[part 1](http://www.roguebasin.com/index.php?title=Complete_Roguelike_Tutorial,_using_python%2Blibtcod,_part_1#Setting_it_up) -of the tutorial. -It's currently recommended to install libtcodpy via -[python-tdl](https://github.com/HexDecimal/python-tdl) rather than using the -libtcodpy package included in this repository. - -**Warning:** If you download these builds, run `samples.exe` as your very first -action. -If you are unable to and get an error about `vcruntime140.dll` being missing, -you need to install the two -[Visual Studio 2015 runtimes](https://www.microsoft.com/en-us/download/details.aspx?id=53587). -Make sure you install the 32-bit runtime. -And make sure you also install the 64-bit runtime. -Then run `samples.exe` again, and it should now work. -Whether you plan to develop in C, C++, Python or some other language, this is -required. +Keep in mind that as a C++14 library, you will need to distribute the +appropriate runtime with your program such as the +[Visual Studio 2015 runtimes](https://www.microsoft.com/en-us/download/details.aspx?id=53587) +or else the program will fail to run. This is required even when using Python. + +For those who wish to program in Python you can install python-tcod using +[this installation guide](https://python-tcod.readthedocs.io/en/latest/installation.html). +Once installed you can follow +[the Python 3 tutorial](http://rogueliketutorials.com/libtcod/1) +or you can find Python example scripts on the +[python-tcod repository](https://github.com/libtcod/python-tcod). + +A alternative version of the Python library (libtcodpy) exists in the binary +downloads, but you should avoid using this version as it is not as well +maintained. ## Compiling from source ## -You can clone with Mercurial via the -[BitBucket repository](https://bitbucket.org/libtcod/libtcod), or with Git via -the [GitHub repository](https://github.com/libtcod/libtcod). +You can clone with Git via the +[GitHub repository](https://github.com/libtcod/libtcod). You can then checkout a specific tag or get the in-development version from -the default or master branches. +the master branch. All compilation methods, currently including Visual Studio (Windows), SCons (Windows, Linux, MacOS) and Autotools (Linux, MacOS), are located within @@ -93,12 +92,14 @@ The latest documentation is [here](https://libtcod.readthedocs.io/en/latest). Currently it's very incomplete, so most people will want to read the [1.5.1 documentation](http://roguecentral.org/doryen/data/libtcod/doc/1.5.1/index2.html?c=true&cpp=true&cs=false&py=true&lua=false) instead. +Python users should use the +[python-tcod documentation](http://python-tcod.readthedocs.io). libtcod comes with a sample application, implementations of which are provided in each of -C ([samples_c.c](https://bitbucket.org/libtcod/libtcod/src/tip/samples/samples_c.c?at=default)), -C++ ([samples_cpp.cpp](https://bitbucket.org/libtcod/libtcod/src/tip/samples/samples_cpp.cpp?at=default)), -and Python ([samples_py.py](https://bitbucket.org/libtcod/libtcod/src/tip/python/samples_py.py?at=default)). +C ([samples_c.c](https://github.com/libtcod/libtcod/blob/master/samples/samples_c.c)), +C++ ([samples_cpp.cpp](https://github.com/libtcod/libtcod/blob/master/samples/samples_cpp.cpp)), +and Python ([samples_py.py](https://github.com/libtcod/python-tcod/blob/master/examples/samples_tcod.py)). This provides a decent overview of the basic features, in an interactive fashion. Each should be identical for the most part, so if you are using Windows, diff --git a/tcod_sys/libtcod/src/libtcod/bresenham.cpp b/tcod_sys/libtcod/src/libtcod/bresenham.cpp index 358220a70..406fc1e68 100644 --- a/tcod_sys/libtcod/src/libtcod/bresenham.cpp +++ b/tcod_sys/libtcod/src/libtcod/bresenham.cpp @@ -1,30 +1,34 @@ -/* -* libtcod -* Copyright (c) 2008-2018 Jice & Mingos & rmtew -* All rights reserved. -* -* Redistribution and use in source and binary forms, with or without -* modification, are permitted provided that the following conditions are met: -* * Redistributions of source code must retain the above copyright -* notice, this list of conditions and the following disclaimer. -* * Redistributions in binary form must reproduce the above copyright -* notice, this list of conditions and the following disclaimer in the -* documentation and/or other materials provided with the distribution. -* * The name of Jice or Mingos may not be used to endorse or promote -* products derived from this software without specific prior written -* permission. -* -* THIS SOFTWARE IS PROVIDED BY JICE, MINGOS AND RMTEW ``AS IS'' AND ANY -* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED -* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE -* DISCLAIMED. IN NO EVENT SHALL JICE, MINGOS OR RMTEW BE LIABLE FOR ANY -* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES -* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; -* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND -* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS -* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. -*/ +/* BSD 3-Clause License + * + * Copyright © 2008-2019, Jice and the libtcod contributors. + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions are met: + * + * 1. Redistributions of source code must retain the above copyright notice, + * this list of conditions and the following disclaimer. + * + * 2. Redistributions in binary form must reproduce the above copyright notice, + * this list of conditions and the following disclaimer in the documentation + * and/or other materials provided with the distribution. + * + * 3. Neither the name of the copyright holder nor the names of its + * contributors may be used to endorse or promote products derived from + * this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE + * POSSIBILITY OF SUCH DAMAGE. + */ #include "bresenham.hpp" // ********** bresenham line drawing ********** diff --git a/tcod_sys/libtcod/src/libtcod/bresenham.h b/tcod_sys/libtcod/src/libtcod/bresenham.h index 7b8e9b313..9796feeab 100644 --- a/tcod_sys/libtcod/src/libtcod/bresenham.h +++ b/tcod_sys/libtcod/src/libtcod/bresenham.h @@ -1,30 +1,34 @@ -/* -* libtcod -* Copyright (c) 2008-2018 Jice & Mingos & rmtew -* All rights reserved. -* -* Redistribution and use in source and binary forms, with or without -* modification, are permitted provided that the following conditions are met: -* * Redistributions of source code must retain the above copyright -* notice, this list of conditions and the following disclaimer. -* * Redistributions in binary form must reproduce the above copyright -* notice, this list of conditions and the following disclaimer in the -* documentation and/or other materials provided with the distribution. -* * The name of Jice or Mingos may not be used to endorse or promote -* products derived from this software without specific prior written -* permission. -* -* THIS SOFTWARE IS PROVIDED BY JICE, MINGOS AND RMTEW ``AS IS'' AND ANY -* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED -* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE -* DISCLAIMED. IN NO EVENT SHALL JICE, MINGOS OR RMTEW BE LIABLE FOR ANY -* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES -* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; -* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND -* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS -* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. -*/ +/* BSD 3-Clause License + * + * Copyright © 2008-2019, Jice and the libtcod contributors. + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions are met: + * + * 1. Redistributions of source code must retain the above copyright notice, + * this list of conditions and the following disclaimer. + * + * 2. Redistributions in binary form must reproduce the above copyright notice, + * this list of conditions and the following disclaimer in the documentation + * and/or other materials provided with the distribution. + * + * 3. Neither the name of the copyright holder nor the names of its + * contributors may be used to endorse or promote products derived from + * this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE + * POSSIBILITY OF SUCH DAMAGE. + */ #ifndef _TCOD_BRESENHAM_H #define _TCOD_BRESENHAM_H diff --git a/tcod_sys/libtcod/src/libtcod/bresenham.hpp b/tcod_sys/libtcod/src/libtcod/bresenham.hpp index 7c27a8e43..389d5c222 100644 --- a/tcod_sys/libtcod/src/libtcod/bresenham.hpp +++ b/tcod_sys/libtcod/src/libtcod/bresenham.hpp @@ -1,30 +1,34 @@ -/* -* libtcod -* Copyright (c) 2008-2018 Jice & Mingos & rmtew -* All rights reserved. -* -* Redistribution and use in source and binary forms, with or without -* modification, are permitted provided that the following conditions are met: -* * Redistributions of source code must retain the above copyright -* notice, this list of conditions and the following disclaimer. -* * Redistributions in binary form must reproduce the above copyright -* notice, this list of conditions and the following disclaimer in the -* documentation and/or other materials provided with the distribution. -* * The name of Jice or Mingos may not be used to endorse or promote -* products derived from this software without specific prior written -* permission. -* -* THIS SOFTWARE IS PROVIDED BY JICE, MINGOS AND RMTEW ``AS IS'' AND ANY -* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED -* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE -* DISCLAIMED. IN NO EVENT SHALL JICE, MINGOS OR RMTEW BE LIABLE FOR ANY -* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES -* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; -* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND -* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS -* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. -*/ +/* BSD 3-Clause License + * + * Copyright © 2008-2019, Jice and the libtcod contributors. + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions are met: + * + * 1. Redistributions of source code must retain the above copyright notice, + * this list of conditions and the following disclaimer. + * + * 2. Redistributions in binary form must reproduce the above copyright notice, + * this list of conditions and the following disclaimer in the documentation + * and/or other materials provided with the distribution. + * + * 3. Neither the name of the copyright holder nor the names of its + * contributors may be used to endorse or promote products derived from + * this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE + * POSSIBILITY OF SUCH DAMAGE. + */ #ifndef _TCOD_BRESENHAM_HPP #define _TCOD_BRESENHAM_HPP diff --git a/tcod_sys/libtcod/src/libtcod/bresenham_c.c b/tcod_sys/libtcod/src/libtcod/bresenham_c.c index 41a66a4d3..8daab957f 100644 --- a/tcod_sys/libtcod/src/libtcod/bresenham_c.c +++ b/tcod_sys/libtcod/src/libtcod/bresenham_c.c @@ -1,30 +1,34 @@ -/* -* libtcod -* Copyright (c) 2008-2018 Jice & Mingos & rmtew -* All rights reserved. -* -* Redistribution and use in source and binary forms, with or without -* modification, are permitted provided that the following conditions are met: -* * Redistributions of source code must retain the above copyright -* notice, this list of conditions and the following disclaimer. -* * Redistributions in binary form must reproduce the above copyright -* notice, this list of conditions and the following disclaimer in the -* documentation and/or other materials provided with the distribution. -* * The name of Jice or Mingos may not be used to endorse or promote -* products derived from this software without specific prior written -* permission. -* -* THIS SOFTWARE IS PROVIDED BY JICE, MINGOS AND RMTEW ``AS IS'' AND ANY -* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED -* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE -* DISCLAIMED. IN NO EVENT SHALL JICE, MINGOS OR RMTEW BE LIABLE FOR ANY -* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES -* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; -* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND -* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS -* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. -*/ +/* BSD 3-Clause License + * + * Copyright © 2008-2019, Jice and the libtcod contributors. + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions are met: + * + * 1. Redistributions of source code must retain the above copyright notice, + * this list of conditions and the following disclaimer. + * + * 2. Redistributions in binary form must reproduce the above copyright notice, + * this list of conditions and the following disclaimer in the documentation + * and/or other materials provided with the distribution. + * + * 3. Neither the name of the copyright holder nor the names of its + * contributors may be used to endorse or promote products derived from + * this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE + * POSSIBILITY OF SUCH DAMAGE. + */ #include "bresenham.h" /** * \file bresenham_c.c diff --git a/tcod_sys/libtcod/src/libtcod/bsp.cpp b/tcod_sys/libtcod/src/libtcod/bsp.cpp index 6c17d4d17..e97b732c8 100644 --- a/tcod_sys/libtcod/src/libtcod/bsp.cpp +++ b/tcod_sys/libtcod/src/libtcod/bsp.cpp @@ -1,30 +1,34 @@ -/* -* libtcod -* Copyright (c) 2008-2018 Jice & Mingos & rmtew -* All rights reserved. -* -* Redistribution and use in source and binary forms, with or without -* modification, are permitted provided that the following conditions are met: -* * Redistributions of source code must retain the above copyright -* notice, this list of conditions and the following disclaimer. -* * Redistributions in binary form must reproduce the above copyright -* notice, this list of conditions and the following disclaimer in the -* documentation and/or other materials provided with the distribution. -* * The name of Jice or Mingos may not be used to endorse or promote -* products derived from this software without specific prior written -* permission. -* -* THIS SOFTWARE IS PROVIDED BY JICE, MINGOS AND RMTEW ``AS IS'' AND ANY -* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED -* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE -* DISCLAIMED. IN NO EVENT SHALL JICE, MINGOS OR RMTEW BE LIABLE FOR ANY -* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES -* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; -* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND -* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS -* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. -*/ +/* BSD 3-Clause License + * + * Copyright © 2008-2019, Jice and the libtcod contributors. + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions are met: + * + * 1. Redistributions of source code must retain the above copyright notice, + * this list of conditions and the following disclaimer. + * + * 2. Redistributions in binary form must reproduce the above copyright notice, + * this list of conditions and the following disclaimer in the documentation + * and/or other materials provided with the distribution. + * + * 3. Neither the name of the copyright holder nor the names of its + * contributors may be used to endorse or promote products derived from + * this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE + * POSSIBILITY OF SUCH DAMAGE. + */ #include "bsp.hpp" TCODBsp::TCODBsp(TCODBsp *father, bool left) { @@ -99,9 +103,9 @@ bool TCODBsp::traverseInvertedLevelOrder(ITCODBspCallback *listener, void *userD } void TCODBsp::removeSons() { - TCODBsp *node=(TCODBsp *)sons; + TCODBsp *node = static_cast(sons); while ( node ) { - TCODBsp *nextNode=(TCODBsp *)node->next; + TCODBsp *nextNode = static_cast(node->next); node->removeSons(); delete node; node=nextNode; diff --git a/tcod_sys/libtcod/src/libtcod/bsp.h b/tcod_sys/libtcod/src/libtcod/bsp.h index 782caef6b..1e5156144 100644 --- a/tcod_sys/libtcod/src/libtcod/bsp.h +++ b/tcod_sys/libtcod/src/libtcod/bsp.h @@ -1,30 +1,34 @@ -/* -* libtcod -* Copyright (c) 2008-2018 Jice & Mingos & rmtew -* All rights reserved. -* -* Redistribution and use in source and binary forms, with or without -* modification, are permitted provided that the following conditions are met: -* * Redistributions of source code must retain the above copyright -* notice, this list of conditions and the following disclaimer. -* * Redistributions in binary form must reproduce the above copyright -* notice, this list of conditions and the following disclaimer in the -* documentation and/or other materials provided with the distribution. -* * The name of Jice or Mingos may not be used to endorse or promote -* products derived from this software without specific prior written -* permission. -* -* THIS SOFTWARE IS PROVIDED BY JICE, MINGOS AND RMTEW ``AS IS'' AND ANY -* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED -* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE -* DISCLAIMED. IN NO EVENT SHALL JICE, MINGOS OR RMTEW BE LIABLE FOR ANY -* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES -* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; -* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND -* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS -* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. -*/ +/* BSD 3-Clause License + * + * Copyright © 2008-2019, Jice and the libtcod contributors. + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions are met: + * + * 1. Redistributions of source code must retain the above copyright notice, + * this list of conditions and the following disclaimer. + * + * 2. Redistributions in binary form must reproduce the above copyright notice, + * this list of conditions and the following disclaimer in the documentation + * and/or other materials provided with the distribution. + * + * 3. Neither the name of the copyright holder nor the names of its + * contributors may be used to endorse or promote products derived from + * this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE + * POSSIBILITY OF SUCH DAMAGE. + */ #ifndef _TCOD_BSP_H #define _TCOD_BSP_H diff --git a/tcod_sys/libtcod/src/libtcod/bsp.hpp b/tcod_sys/libtcod/src/libtcod/bsp.hpp index 06cae8913..6ebc3fec2 100644 --- a/tcod_sys/libtcod/src/libtcod/bsp.hpp +++ b/tcod_sys/libtcod/src/libtcod/bsp.hpp @@ -1,30 +1,34 @@ -/* -* libtcod -* Copyright (c) 2008-2018 Jice & Mingos & rmtew -* All rights reserved. -* -* Redistribution and use in source and binary forms, with or without -* modification, are permitted provided that the following conditions are met: -* * Redistributions of source code must retain the above copyright -* notice, this list of conditions and the following disclaimer. -* * Redistributions in binary form must reproduce the above copyright -* notice, this list of conditions and the following disclaimer in the -* documentation and/or other materials provided with the distribution. -* * The name of Jice or Mingos may not be used to endorse or promote -* products derived from this software without specific prior written -* permission. -* -* THIS SOFTWARE IS PROVIDED BY JICE, MINGOS AND RMTEW ``AS IS'' AND ANY -* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED -* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE -* DISCLAIMED. IN NO EVENT SHALL JICE, MINGOS OR RMTEW BE LIABLE FOR ANY -* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES -* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; -* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND -* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS -* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. -*/ +/* BSD 3-Clause License + * + * Copyright © 2008-2019, Jice and the libtcod contributors. + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions are met: + * + * 1. Redistributions of source code must retain the above copyright notice, + * this list of conditions and the following disclaimer. + * + * 2. Redistributions in binary form must reproduce the above copyright notice, + * this list of conditions and the following disclaimer in the documentation + * and/or other materials provided with the distribution. + * + * 3. Neither the name of the copyright holder nor the names of its + * contributors may be used to endorse or promote products derived from + * this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE + * POSSIBILITY OF SUCH DAMAGE. + */ #ifndef _TCOD_BSP_HPP #define _TCOD_BSP_HPP @@ -278,13 +282,13 @@ You can use it if you changed the nodes size and position while using the BSP tr @Param node In the C version, the node reference. */ TCODBsp *getLeft() const { - return (TCODBsp *)sons; + return static_cast(sons); } TCODBsp *getRight() const { - return sons ? (TCODBsp *)(sons->next) : NULL; + return sons ? static_cast(sons->next) : NULL; } TCODBsp *getFather() const { - return (TCODBsp *)father; + return static_cast(father); } /** diff --git a/tcod_sys/libtcod/src/libtcod/bsp_c.c b/tcod_sys/libtcod/src/libtcod/bsp_c.c index cec227fbd..abacd3df5 100644 --- a/tcod_sys/libtcod/src/libtcod/bsp_c.c +++ b/tcod_sys/libtcod/src/libtcod/bsp_c.c @@ -1,30 +1,34 @@ -/* -* libtcod -* Copyright (c) 2008-2018 Jice & Mingos & rmtew -* All rights reserved. -* -* Redistribution and use in source and binary forms, with or without -* modification, are permitted provided that the following conditions are met: -* * Redistributions of source code must retain the above copyright -* notice, this list of conditions and the following disclaimer. -* * Redistributions in binary form must reproduce the above copyright -* notice, this list of conditions and the following disclaimer in the -* documentation and/or other materials provided with the distribution. -* * The name of Jice or Mingos may not be used to endorse or promote -* products derived from this software without specific prior written -* permission. -* -* THIS SOFTWARE IS PROVIDED BY JICE, MINGOS AND RMTEW ``AS IS'' AND ANY -* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED -* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE -* DISCLAIMED. IN NO EVENT SHALL JICE, MINGOS OR RMTEW BE LIABLE FOR ANY -* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES -* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; -* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND -* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS -* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. -*/ +/* BSD 3-Clause License + * + * Copyright © 2008-2019, Jice and the libtcod contributors. + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions are met: + * + * 1. Redistributions of source code must retain the above copyright notice, + * this list of conditions and the following disclaimer. + * + * 2. Redistributions in binary form must reproduce the above copyright notice, + * this list of conditions and the following disclaimer in the documentation + * and/or other materials provided with the distribution. + * + * 3. Neither the name of the copyright holder nor the names of its + * contributors may be used to endorse or promote products derived from + * this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE + * POSSIBILITY OF SUCH DAMAGE. + */ #include "bsp.h" #include @@ -108,11 +112,11 @@ bool TCOD_bsp_traverse_level_order(TCOD_bsp_t *node, TCOD_bsp_callback_t listene TCOD_list_t stack=TCOD_list_new(); TCOD_list_push(stack,node); while ( ! TCOD_list_is_empty(stack) ) { - TCOD_bsp_t *node=(TCOD_bsp_t *)TCOD_list_get(stack,0); - TCOD_list_remove(stack,node); - if ( TCOD_bsp_left(node) ) TCOD_list_push(stack,TCOD_bsp_left(node)); - if ( TCOD_bsp_right(node) ) TCOD_list_push(stack,TCOD_bsp_right(node)); - if (!listener(node,userData)) { + TCOD_bsp_t *node_=(TCOD_bsp_t *)TCOD_list_get(stack,0); + TCOD_list_remove(stack,node_); + if ( TCOD_bsp_left(node_) ) TCOD_list_push(stack,TCOD_bsp_left(node_)); + if ( TCOD_bsp_right(node_) ) TCOD_list_push(stack,TCOD_bsp_right(node_)); + if (!listener(node_,userData)) { TCOD_list_delete(stack); return false; } @@ -126,15 +130,15 @@ bool TCOD_bsp_traverse_inverted_level_order(TCOD_bsp_t *node, TCOD_bsp_callback_ TCOD_list_t stack2=TCOD_list_new(); TCOD_list_push(stack1,node); while ( ! TCOD_list_is_empty(stack1) ) { - TCOD_bsp_t *node=(TCOD_bsp_t *)TCOD_list_get(stack1,0); - TCOD_list_push(stack2,node); - TCOD_list_remove(stack1,node); - if ( TCOD_bsp_left(node) ) TCOD_list_push(stack1,TCOD_bsp_left(node)); - if ( TCOD_bsp_right(node) ) TCOD_list_push(stack1,TCOD_bsp_right(node)); + TCOD_bsp_t *node_ = (TCOD_bsp_t *)TCOD_list_get(stack1,0); + TCOD_list_push(stack2,node_); + TCOD_list_remove(stack1,node_); + if (TCOD_bsp_left(node_)) TCOD_list_push(stack1,TCOD_bsp_left(node_)); + if (TCOD_bsp_right(node_)) TCOD_list_push(stack1,TCOD_bsp_right(node_)); } while ( ! TCOD_list_is_empty(stack2) ) { - TCOD_bsp_t *node=(TCOD_bsp_t *)TCOD_list_pop(stack2); - if (!listener(node,userData)) { + TCOD_bsp_t *node_ = (TCOD_bsp_t *)TCOD_list_pop(stack2); + if (!listener(node_, userData)) { TCOD_list_delete(stack1); TCOD_list_delete(stack2); return false; diff --git a/tcod_sys/libtcod/src/libtcod/color.cpp b/tcod_sys/libtcod/src/libtcod/color.cpp index 7928377dc..14ea79338 100644 --- a/tcod_sys/libtcod/src/libtcod/color.cpp +++ b/tcod_sys/libtcod/src/libtcod/color.cpp @@ -1,30 +1,34 @@ -/* -* libtcod -* Copyright (c) 2008-2018 Jice & Mingos & rmtew -* All rights reserved. -* -* Redistribution and use in source and binary forms, with or without -* modification, are permitted provided that the following conditions are met: -* * Redistributions of source code must retain the above copyright -* notice, this list of conditions and the following disclaimer. -* * Redistributions in binary form must reproduce the above copyright -* notice, this list of conditions and the following disclaimer in the -* documentation and/or other materials provided with the distribution. -* * The name of Jice or Mingos may not be used to endorse or promote -* products derived from this software without specific prior written -* permission. -* -* THIS SOFTWARE IS PROVIDED BY JICE, MINGOS AND RMTEW ``AS IS'' AND ANY -* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED -* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE -* DISCLAIMED. IN NO EVENT SHALL JICE, MINGOS OR RMTEW BE LIABLE FOR ANY -* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES -* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; -* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND -* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS -* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. -*/ +/* BSD 3-Clause License + * + * Copyright © 2008-2019, Jice and the libtcod contributors. + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions are met: + * + * 1. Redistributions of source code must retain the above copyright notice, + * this list of conditions and the following disclaimer. + * + * 2. Redistributions in binary form must reproduce the above copyright notice, + * this list of conditions and the following disclaimer in the documentation + * and/or other materials provided with the distribution. + * + * 3. Neither the name of the copyright holder nor the names of its + * contributors may be used to endorse or promote products derived from + * this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE + * POSSIBILITY OF SUCH DAMAGE. + */ #include "color.hpp" #include "libtcod_int.h" @@ -337,13 +341,18 @@ TCODColor operator *(float value, const TCODColor &c) { return c*value; } -void TCODColor::genMap(TCODColor *map, int nbKey, TCODColor const *keyColor, int const *keyIndex) { - for (int segment=0; segment < nbKey-1; segment++) { - int idxStart=keyIndex[segment]; - int idxEnd=keyIndex[segment+1]; - int idx; - for ( idx=idxStart;idx <= idxEnd; idx++) { - map[idx]=TCODColor::lerp(keyColor[segment],keyColor[segment+1],(float)(idx-idxStart)/(idxEnd-idxStart)); - } - } +void TCODColor::genMap(TCODColor *map, int nbKey, TCODColor const *keyColor, + int const *keyIndex) +{ + for (int segment = 0; segment < nbKey - 1; ++segment) { + int idxStart = keyIndex[segment]; + int idxEnd = keyIndex[segment + 1]; + for (int idx = idxStart; idx <= idxEnd; ++idx) { + map[idx] = TCODColor::lerp( + keyColor[segment], + keyColor[segment + 1], + static_cast(idx - idxStart) / (idxEnd - idxStart) + ); + } + } } diff --git a/tcod_sys/libtcod/src/libtcod/color.h b/tcod_sys/libtcod/src/libtcod/color.h index 67e52bfcd..27817f187 100644 --- a/tcod_sys/libtcod/src/libtcod/color.h +++ b/tcod_sys/libtcod/src/libtcod/color.h @@ -1,46 +1,43 @@ -/* -* libtcod -* Copyright (c) 2008-2018 Jice & Mingos & rmtew -* All rights reserved. -* -* Redistribution and use in source and binary forms, with or without -* modification, are permitted provided that the following conditions are met: -* * Redistributions of source code must retain the above copyright -* notice, this list of conditions and the following disclaimer. -* * Redistributions in binary form must reproduce the above copyright -* notice, this list of conditions and the following disclaimer in the -* documentation and/or other materials provided with the distribution. -* * The name of Jice or Mingos may not be used to endorse or promote -* products derived from this software without specific prior written -* permission. -* -* THIS SOFTWARE IS PROVIDED BY JICE, MINGOS AND RMTEW ``AS IS'' AND ANY -* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED -* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE -* DISCLAIMED. IN NO EVENT SHALL JICE, MINGOS OR RMTEW BE LIABLE FOR ANY -* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES -* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; -* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND -* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS -* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. -*/ +/* BSD 3-Clause License + * + * Copyright © 2008-2019, Jice and the libtcod contributors. + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions are met: + * + * 1. Redistributions of source code must retain the above copyright notice, + * this list of conditions and the following disclaimer. + * + * 2. Redistributions in binary form must reproduce the above copyright notice, + * this list of conditions and the following disclaimer in the documentation + * and/or other materials provided with the distribution. + * + * 3. Neither the name of the copyright holder nor the names of its + * contributors may be used to endorse or promote products derived from + * this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE + * POSSIBILITY OF SUCH DAMAGE. + */ #ifndef _TCOD_COLOR_H #define _TCOD_COLOR_H #include "portability.h" +#include "color/color.h" #ifdef __cplusplus extern "C" { #endif - -/** - * \brief An RGB color struct. - */ -typedef struct { - uint8_t r,g,b; -} TCOD_color_t; - /* constructors */ TCODLIB_API TCOD_color_t TCOD_color_RGB(uint8_t r, uint8_t g, uint8_t b); TCODLIB_API TCOD_color_t TCOD_color_HSV(float hue, float saturation, diff --git a/tcod_sys/libtcod/src/libtcod/color.hpp b/tcod_sys/libtcod/src/libtcod/color.hpp index d88881763..202a37a90 100644 --- a/tcod_sys/libtcod/src/libtcod/color.hpp +++ b/tcod_sys/libtcod/src/libtcod/color.hpp @@ -1,33 +1,39 @@ -/* -* libtcod -* Copyright (c) 2008-2018 Jice & Mingos & rmtew -* All rights reserved. -* -* Redistribution and use in source and binary forms, with or without -* modification, are permitted provided that the following conditions are met: -* * Redistributions of source code must retain the above copyright -* notice, this list of conditions and the following disclaimer. -* * Redistributions in binary form must reproduce the above copyright -* notice, this list of conditions and the following disclaimer in the -* documentation and/or other materials provided with the distribution. -* * The name of Jice or Mingos may not be used to endorse or promote -* products derived from this software without specific prior written -* permission. -* -* THIS SOFTWARE IS PROVIDED BY JICE, MINGOS AND RMTEW ``AS IS'' AND ANY -* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED -* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE -* DISCLAIMED. IN NO EVENT SHALL JICE, MINGOS OR RMTEW BE LIABLE FOR ANY -* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES -* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; -* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND -* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS -* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. -*/ +/* BSD 3-Clause License + * + * Copyright © 2008-2019, Jice and the libtcod contributors. + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions are met: + * + * 1. Redistributions of source code must retain the above copyright notice, + * this list of conditions and the following disclaimer. + * + * 2. Redistributions in binary form must reproduce the above copyright notice, + * this list of conditions and the following disclaimer in the documentation + * and/or other materials provided with the distribution. + * + * 3. Neither the name of the copyright holder nor the names of its + * contributors may be used to endorse or promote products derived from + * this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE + * POSSIBILITY OF SUCH DAMAGE. + */ #ifndef _TCOD_COLOR_HPP #define _TCOD_COLOR_HPP +#include + #include "color.h" #include "utility.h" // color constants uses to generate @ColorTable @@ -146,8 +152,12 @@ public : TCODColor myColor = new TCODColor(321.0f,0.7f,1.0f); //HSV @LuaEx myColor = tcod.Color(24,24,255) */ - TCODColor(uint8_t r, uint8_t g, uint8_t b): r(r), g(g), b(b) {} - TCODColor(int r, int g, int b): r(r), g(g), b(b) {} + TCODColor(uint8_t r_, uint8_t g_, uint8_t b_) + : r(r_), g(g_), b(b_) + {} + TCODColor(int r_, int g_, int b_) + : r(r_), g(g_), b(b_) + {} TCODColor(const TCOD_color_t &col): r(col.r), g(col.g), b(col.b) {} TCODColor(float h, float s, float v); @@ -169,12 +179,14 @@ public : @LuaEx if myColor == tcod.color.yellow then ... end */ - bool operator == (const TCODColor & c) const { - return (c.r == r && c.g == g && c.b == b); - } - bool operator != (const TCODColor & c) const { - return (c.r != r || c.g != g || c.b != b); - } + bool operator == (const TCODColor& c) const + { + return (c.r == r && c.g == g && c.b == b); + } + bool operator != (const TCODColor& c) const + { + return !(*this == c); + } /** @PageName color @@ -191,13 +203,10 @@ public : @C#Ex TCODColor myDarkishRed = TCODColor.darkGrey.Multiply(TCODColor.lightRed); @LuaEx myDarkishRed = tcod.color.darkGrey * tcod.color.lightRed */ - TCODColor operator * (const TCODColor & a) const { - TCODColor ret; - ret.r=(uint8_t)(((int)r)*a.r/255); - ret.g=(uint8_t)(((int)g)*a.g/255); - ret.b=(uint8_t)(((int)b)*a.b/255); - return ret; - } + TCODColor operator*(const TCODColor& rhs) const + { + return TCODColor(*this, rhs, [](int c1, int c2){ return c1 * c2 / 255; }); + } /** @PageName color @@ -215,20 +224,10 @@ public : @C#Ex TCODColor myDarkishRed = TCODColor.lightRed.Multiply(0.5f); @LuaEx myDarkishRed = tcod.color.lightRed * 0.5 */ - TCODColor operator *(float value) const { - TCOD_color_t ret; - int r,g,b; - r = (int)(this->r * value); - g = (int)(this->g * value); - b = (int)(this->b * value); - r = CLAMP(0,255,r); - g = CLAMP(0,255,g); - b = CLAMP(0,255,b); - ret.r=(uint8_t)r; - ret.g=(uint8_t)g; - ret.b=(uint8_t)b; - return ret; - } + TCODColor operator*(float value) const + { + return TCODColor(*this, [=](int c){ return static_cast(c * value); }); + } /** @PageName color @@ -244,19 +243,10 @@ public : @C#Ex TCODColor myLightishRed = TCODColor.red.Plus(TCODColor.darkGrey) @LuaEx myLightishRed = tcod.color.red + tcod.color.darkGrey */ - TCODColor operator + (const TCODColor & a) const { - TCODColor ret; - int r=(int)(this->r)+a.r; - int g=(int)(this->g)+a.g; - int b=(int)(this->b)+a.b; - r = MIN(255,r); - g = MIN(255,g); - b = MIN(255,b); - ret.r=(uint8_t)r; - ret.g=(uint8_t)g; - ret.b=(uint8_t)b; - return ret; - } + TCODColor operator+(const TCODColor & rhs) const + { + return TCODColor(*this, rhs, [](int c1, int c2){ return c1 + c2; }); + } /** @PageName color @@ -272,19 +262,10 @@ public : @C#Ex TCODColor myRedish = TCODColor.red.Minus(TCODColor.darkGrey) @LuaEx myRedish = tcod.color.red - tcod.color.darkGrey */ - TCODColor operator - (const TCODColor & a) const { - TCODColor ret; - int r=(int)(this->r)-a.r; - int g=(int)(this->g)-a.g; - int b=(int)(this->b)-a.b; - r = MAX(0,r); - g = MAX(0,g); - b = MAX(0,b); - ret.r=(uint8_t)r; - ret.g=(uint8_t)g; - ret.b=(uint8_t)b; - return ret; - } + TCODColor operator-(const TCODColor& rhs) const + { + return TCODColor(*this, rhs, [](int c1, int c2){ return c1 - c2; }); + } /** @PageName color @@ -305,13 +286,10 @@ coef should be between 0.0 and 1.0 but you can as well use other values @C#Ex TCODColor myColor = TCODColor.Interpolate( TCODColor.darkGrey, TCODColor.lightRed, coef ); @LuaEx myColor = tcod.color.Interpolate( tcod.color.darkGrey, tcod.color.lightRed, coef ) */ - static TCODColor lerp(const TCODColor &a, const TCODColor &b, float coef) { - TCODColor ret; - ret.r=(uint8_t)(a.r+(b.r-a.r)*coef); - ret.g=(uint8_t)(a.g+(b.g-a.g)*coef); - ret.b=(uint8_t)(a.b+(b.b-a.b)*coef); - return ret; - } + static TCODColor lerp(const TCODColor &c1, const TCODColor &c2, float coef) + { + return TCODColor(c1, c2, [=](int c, int d){ return c + (d - c) * coef; }); + } /** @PageName color @@ -685,6 +663,33 @@ coef should be between 0.0 and 1.0 but you can as well use other values // miscellaneous static const TCODColor celadon; static const TCODColor peach; + private: + /** + * Return a color transformed by a lambda. + */ + template + TCODColor(const TCODColor& color, const F& lambda) + : r(clamp_(lambda(color.r))), + g(clamp_(lambda(color.g))), + b(clamp_(lambda(color.b))) + {} + /** + * Return a color from two colors combined using a lambda. + */ + template + TCODColor(const TCODColor& color1, const TCODColor& color2, const F& lambda) + : r(clamp_(lambda(color1.r, color2.r))), + g(clamp_(lambda(color1.g, color2.g))), + b(clamp_(lambda(color1.b, color2.b))) + {} + /** + * Return a color value clamped between 0 to 255. + */ + template + static constexpr uint8_t clamp_(const T& value) noexcept + { + return static_cast(std::max(0, std::min(value, 255))); + } }; TCODLIB_API TCODColor operator *(float value, const TCODColor &c); diff --git a/tcod_sys/libtcod/src/libtcod/color/canvas.cpp b/tcod_sys/libtcod/src/libtcod/color/canvas.cpp index 3116dd578..191836f8d 100644 --- a/tcod_sys/libtcod/src/libtcod/color/canvas.cpp +++ b/tcod_sys/libtcod/src/libtcod/color/canvas.cpp @@ -1,29 +1,82 @@ - +/* BSD 3-Clause License + * + * Copyright © 2008-2019, Jice and the libtcod contributors. + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions are met: + * + * 1. Redistributions of source code must retain the above copyright notice, + * this list of conditions and the following disclaimer. + * + * 2. Redistributions in binary form must reproduce the above copyright notice, + * this list of conditions and the following disclaimer in the documentation + * and/or other materials provided with the distribution. + * + * 3. Neither the name of the copyright holder nor the names of its + * contributors may be used to endorse or promote products derived from + * this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE + * POSSIBILITY OF SUCH DAMAGE. + */ #include "canvas.h" #include +#include +#include + #include "../../vendor/lodepng.h" namespace tcod { namespace image { +/** + * Return true if the file at `path` exists. + */ +static bool file_exists(const std::string& path) +{ + struct stat buffer; + return stat(path.c_str(), &buffer) == 0; +} Image load(const std::string& filename) { + if (!file_exists(filename)) { + throw std::runtime_error("File does not exist: " + filename); + } unsigned img_width, img_height; std::vector img_data; - if (lodepng::decode(img_data, img_width, img_height, filename)) { - throw std::runtime_error("File not found: " + filename); + if (auto err=lodepng::decode(img_data, img_width, img_height, filename)) { + throw std::runtime_error(lodepng_error_text(err)); } Image image(img_width, img_height); std::vector::iterator img_iter = img_data.begin(); for (int y = 0; y < image.height(); ++y) { for (int x = 0; x < image.width(); ++x) { - image.at(x, y) = ColorRGBA{ + image.atf(x, y) = ColorRGBA{ img_iter[0], img_iter[1], img_iter[2], img_iter[3]}; img_iter += 4; } } return image; } +void save(const Image& image, const std::string& filename) +{ + const unsigned char* buffer = + reinterpret_cast(image.data()); + if (auto err=lodepng::encode(filename, buffer, + image.width(), image.height())) { + throw std::runtime_error(lodepng_error_text(err)); + } +} } // namespace image } // namespace tcod diff --git a/tcod_sys/libtcod/src/libtcod/color/canvas.h b/tcod_sys/libtcod/src/libtcod/color/canvas.h index e7f41a13c..205742811 100644 --- a/tcod_sys/libtcod/src/libtcod/color/canvas.h +++ b/tcod_sys/libtcod/src/libtcod/color/canvas.h @@ -1,4 +1,34 @@ - +/* BSD 3-Clause License + * + * Copyright © 2008-2019, Jice and the libtcod contributors. + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions are met: + * + * 1. Redistributions of source code must retain the above copyright notice, + * this list of conditions and the following disclaimer. + * + * 2. Redistributions in binary form must reproduce the above copyright notice, + * this list of conditions and the following disclaimer in the documentation + * and/or other materials provided with the distribution. + * + * 3. Neither the name of the copyright holder nor the names of its + * contributors may be used to endorse or promote products derived from + * this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE + * POSSIBILITY OF SUCH DAMAGE. + */ #ifndef LIBTCOD_COLOR_CANVAS_H_ #define LIBTCOD_COLOR_CANVAS_H_ #ifdef __cplusplus @@ -15,6 +45,7 @@ namespace image { */ typedef Vector2 Image; Image load(const std::string& filename); +void save(const Image& image, const std::string& filename); } // namespace image } // namespace tcod #endif /* __cplusplus */ diff --git a/tcod_sys/libtcod/src/libtcod/color/color.h b/tcod_sys/libtcod/src/libtcod/color/color.h index 7c5392646..8a9fa3e12 100644 --- a/tcod_sys/libtcod/src/libtcod/color/color.h +++ b/tcod_sys/libtcod/src/libtcod/color/color.h @@ -1,12 +1,102 @@ - +/* BSD 3-Clause License + * + * Copyright © 2008-2019, Jice and the libtcod contributors. + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions are met: + * + * 1. Redistributions of source code must retain the above copyright notice, + * this list of conditions and the following disclaimer. + * + * 2. Redistributions in binary form must reproduce the above copyright notice, + * this list of conditions and the following disclaimer in the documentation + * and/or other materials provided with the distribution. + * + * 3. Neither the name of the copyright holder nor the names of its + * contributors may be used to endorse or promote products derived from + * this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE + * POSSIBILITY OF SUCH DAMAGE. + */ #ifndef LIBTCOD_COLOR_COLOR_H_ #define LIBTCOD_COLOR_COLOR_H_ #include +/** + * A three channel color struct. + */ +struct TCOD_ColorRGB { #ifdef __cplusplus -namespace tcod { -struct ColorRGBA { - uint8_t r, g, b, a; + bool operator==(const TCOD_ColorRGB& rhs) const noexcept + { + return r == rhs.r && g == rhs.g && b == rhs.b; + } + bool operator!=(const TCOD_ColorRGB& rhs) const noexcept + { + return !(*this == rhs); + } +#endif // __cplusplus + uint8_t r; + uint8_t g; + uint8_t b; +}; +typedef struct TCOD_ColorRGB TCOD_color_t; +/** + * A four channel color struct. + */ +struct TCOD_ColorRGBA { +#ifdef __cplusplus + bool operator==(const TCOD_ColorRGBA& rhs) const noexcept + { + return r == rhs.r && g == rhs.g && b == rhs.b && a == rhs.a; + } + bool operator!=(const TCOD_ColorRGBA& rhs) const noexcept + { + return !(*this == rhs); + } +#endif // __cplusplus + uint8_t r; + uint8_t g; + uint8_t b; + uint8_t a; }; +#ifdef __cplusplus +namespace tcod { + struct ColorRGB: TCOD_ColorRGB { + ColorRGB() = default; + ColorRGB(uint8_t red, uint8_t green, uint8_t blue) + : TCOD_ColorRGB{red, green, blue} + {} + ColorRGB(const struct TCOD_ColorRGB& rhs) + : TCOD_ColorRGB{rhs} + {} + explicit ColorRGB(const struct TCOD_ColorRGBA& rhs) + : TCOD_ColorRGB{rhs.r, rhs.g, rhs.b} + {} + }; + struct ColorRGBA: TCOD_ColorRGBA { + ColorRGBA() = default; + ColorRGBA(uint8_t red, uint8_t green, uint8_t blue, uint8_t alpha=0xff) + : TCOD_ColorRGBA{red, green, blue, alpha} + {} + explicit ColorRGBA(const struct TCOD_ColorRGB& color, + uint8_t alpha=0xff) + : TCOD_ColorRGBA{color.r, color.g, color.b, alpha} + {} + ColorRGBA(const struct TCOD_ColorRGBA& rhs) + : TCOD_ColorRGBA{rhs} + {} + }; } // namespace tcod #endif /* __cplusplus */ #endif /* LIBTCOD_COLOR_COLOR_H_ */ diff --git a/tcod_sys/libtcod/src/libtcod/color_c.c b/tcod_sys/libtcod/src/libtcod/color_c.c index 319d14f38..444fd691d 100644 --- a/tcod_sys/libtcod/src/libtcod/color_c.c +++ b/tcod_sys/libtcod/src/libtcod/color_c.c @@ -1,30 +1,34 @@ -/* -* libtcod -* Copyright (c) 2008-2018 Jice & Mingos & rmtew -* All rights reserved. -* -* Redistribution and use in source and binary forms, with or without -* modification, are permitted provided that the following conditions are met: -* * Redistributions of source code must retain the above copyright -* notice, this list of conditions and the following disclaimer. -* * Redistributions in binary form must reproduce the above copyright -* notice, this list of conditions and the following disclaimer in the -* documentation and/or other materials provided with the distribution. -* * The name of Jice or Mingos may not be used to endorse or promote -* products derived from this software without specific prior written -* permission. -* -* THIS SOFTWARE IS PROVIDED BY JICE, MINGOS AND RMTEW ``AS IS'' AND ANY -* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED -* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE -* DISCLAIMED. IN NO EVENT SHALL JICE, MINGOS OR RMTEW BE LIABLE FOR ANY -* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES -* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; -* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND -* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS -* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. -*/ +/* BSD 3-Clause License + * + * Copyright © 2008-2019, Jice and the libtcod contributors. + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions are met: + * + * 1. Redistributions of source code must retain the above copyright notice, + * this list of conditions and the following disclaimer. + * + * 2. Redistributions in binary form must reproduce the above copyright notice, + * this list of conditions and the following disclaimer in the documentation + * and/or other materials provided with the distribution. + * + * 3. Neither the name of the copyright holder nor the names of its + * contributors may be used to endorse or promote products derived from + * this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE + * POSSIBILITY OF SUCH DAMAGE. + */ #include "color.h" #include diff --git a/tcod_sys/libtcod/src/libtcod/console.cpp b/tcod_sys/libtcod/src/libtcod/console.cpp index d1ccb639f..d98414fa3 100644 --- a/tcod_sys/libtcod/src/libtcod/console.cpp +++ b/tcod_sys/libtcod/src/libtcod/console.cpp @@ -1,30 +1,34 @@ -/* -* libtcod -* Copyright (c) 2008-2018 Jice & Mingos & rmtew -* All rights reserved. -* -* Redistribution and use in source and binary forms, with or without -* modification, are permitted provided that the following conditions are met: -* * Redistributions of source code must retain the above copyright -* notice, this list of conditions and the following disclaimer. -* * Redistributions in binary form must reproduce the above copyright -* notice, this list of conditions and the following disclaimer in the -* documentation and/or other materials provided with the distribution. -* * The name of Jice or Mingos may not be used to endorse or promote -* products derived from this software without specific prior written -* permission. -* -* THIS SOFTWARE IS PROVIDED BY JICE, MINGOS AND RMTEW ``AS IS'' AND ANY -* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED -* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE -* DISCLAIMED. IN NO EVENT SHALL JICE, MINGOS OR RMTEW BE LIABLE FOR ANY -* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES -* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; -* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND -* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS -* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. -*/ +/* BSD 3-Clause License + * + * Copyright © 2008-2019, Jice and the libtcod contributors. + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions are met: + * + * 1. Redistributions of source code must retain the above copyright notice, + * this list of conditions and the following disclaimer. + * + * 2. Redistributions in binary form must reproduce the above copyright notice, + * this list of conditions and the following disclaimer in the documentation + * and/or other materials provided with the distribution. + * + * 3. Neither the name of the copyright holder nor the names of its + * contributors may be used to endorse or promote products derived from + * this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE + * POSSIBILITY OF SUCH DAMAGE. + */ #include "console.hpp" #include @@ -33,6 +37,7 @@ #include "libtcod_int.h" #include "image.hpp" +#include "engine/display.h" #ifdef TCOD_CONSOLE_SUPPORT @@ -142,7 +147,7 @@ void TCODConsole::setWindowTitle(const char *title) { void TCODConsole::initRoot(int w, int h, const char *title, bool fullscreen, TCOD_renderer_t renderer) { - TCOD_console_init_root(w, h, title, fullscreen, renderer); + tcod::console::init_root(w, h, title ? title : "", fullscreen, renderer); } void TCODConsole::setFullscreen(bool fullscreen) { @@ -270,9 +275,8 @@ void TCODConsole::print(int x, int y, const std::string &str) { } void TCODConsole::print(int x, int y, const std::string &str, TCOD_alignment_t alignment, TCOD_bkgnd_flag_t flag) { - TCOD_console_print_internal_utf8_( - data, x, y, 0, 0, flag, alignment, - reinterpret_cast(str.c_str()), false, false); + tcod::console::print(data, x, y, str, + &data->fore, &data->back, flag, alignment); } void TCODConsole::printf(int x, int y, const char *fmt, ...) { va_list ap; @@ -322,14 +326,16 @@ void TCODConsole::printLine(int x, int y, TCOD_bkgnd_flag_t flag, TCOD_print_loc } */ -int TCODConsole::printRect(int x, int y, int w, int h, const char *fmt, ...) { - va_list ap; - struct TCOD_Console *dat=(struct TCOD_Console *)data; - TCOD_IFNOT ( dat != NULL ) return 0; - va_start(ap,fmt); - int ret = TCOD_console_print_internal(data,x,y,w,h,dat->bkgnd_flag,dat->alignment,TCOD_console_vsprint(fmt,ap),true,false); - va_end(ap); - return ret; +int TCODConsole::printRect(int x, int y, int w, int h, const char *fmt, ...) +{ + va_list ap; + TCOD_IFNOT (data != NULL) { return 0; } + va_start(ap,fmt); + int ret = TCOD_console_print_internal( + data, x, y, w, h, data->bkgnd_flag, data->alignment, + TCOD_console_vsprint(fmt, ap), true, false); + va_end(ap); + return ret; } int TCODConsole::printRectEx(int x, int y, int w, int h, TCOD_bkgnd_flag_t flag, @@ -374,13 +380,15 @@ void TCODConsole::mapStringToFont(const wchar_t *s, int fontCharX, int fontCharY TCOD_console_map_string_to_font_utf(s, fontCharX, fontCharY); } -void TCODConsole::print(int x, int y, const wchar_t *fmt, ...) { - va_list ap; - struct TCOD_Console *dat=(struct TCOD_Console *)data; - TCOD_IFNOT ( dat != NULL ) return; - va_start(ap,fmt); - TCOD_console_print_internal_utf(data,x,y,0,0,dat->bkgnd_flag,dat->alignment,TCOD_console_vsprint_utf(fmt,ap),false,false); - va_end(ap); +void TCODConsole::print(int x, int y, const wchar_t *fmt, ...) +{ + va_list ap; + TCOD_IFNOT (data != NULL) { return; } + va_start(ap, fmt); + TCOD_console_print_internal_utf( + data, x, y, 0, 0, data->bkgnd_flag, data->alignment, + TCOD_console_vsprint_utf(fmt, ap), false, false); + va_end(ap); } void TCODConsole::printEx(int x, int y, TCOD_bkgnd_flag_t flag, TCOD_alignment_t alignment, const wchar_t *fmt, ...) { @@ -390,15 +398,16 @@ void TCODConsole::printEx(int x, int y, TCOD_bkgnd_flag_t flag, TCOD_alignment_t va_end(ap); } -int TCODConsole::printRect(int x, int y, int w, int h, const wchar_t *fmt, ...) { - va_list ap; - struct TCOD_Console *dat=(struct TCOD_Console *)data; - TCOD_IFNOT ( dat != NULL ) return 0; - va_start(ap,fmt); - int ret = TCOD_console_print_internal_utf(data,x,y,w,h,dat->bkgnd_flag,dat->alignment, - TCOD_console_vsprint_utf(fmt,ap),true,false); - va_end(ap); - return ret; +int TCODConsole::printRect(int x, int y, int w, int h, const wchar_t *fmt, ...) +{ + va_list ap; + TCOD_IFNOT (data != NULL) { return 0; } + va_start(ap,fmt); + int ret = TCOD_console_print_internal_utf( + data, x, y, w, h, data->bkgnd_flag, data->alignment, + TCOD_console_vsprint_utf(fmt, ap), true, false); + va_end(ap); + return ret; } int TCODConsole::printRectEx(int x, int y, int w, int h, TCOD_bkgnd_flag_t flag, @@ -423,30 +432,31 @@ int TCODConsole::getHeightRect(int x, int y, int w, int h, const wchar_t *fmt, . // ctrl = TCOD_COLCTRL_1...TCOD_COLCTRL_5 or TCOD_COLCTRL_STOP #define NB_BUFFERS 10 -const char *TCODConsole::getColorControlString( TCOD_colctrl_t ctrl ) { - static char buf[NB_BUFFERS][2]; - static int buf_nb=0; - const char *ret; - buf[buf_nb][0]=ctrl; - buf[buf_nb][1]=0; - ret = (const char *)(&buf[buf_nb][0]); - buf_nb = (buf_nb+1) % NB_BUFFERS; - return ret; +const char *TCODConsole::getColorControlString(TCOD_colctrl_t ctrl) +{ + static char buf[NB_BUFFERS][2]; + static int buf_nb = 0; + buf[buf_nb][0] = ctrl; + buf[buf_nb][1] = 0; + const char* ret = buf[buf_nb]; + buf_nb = (buf_nb + 1) % NB_BUFFERS; + return ret; } // ctrl = TCOD_COLCTRL_FORE_RGB or TCOD_COLCTRL_BACK_RGB -const char *TCODConsole::getRGBColorControlString( TCOD_colctrl_t ctrl, const TCODColor & col ) { - static char buf[NB_BUFFERS][5]; - static int buf_nb=0; - const char *ret; - buf[buf_nb][0]=ctrl; - buf[buf_nb][1]=col.r; - buf[buf_nb][2]=col.g; - buf[buf_nb][3]=col.b; - buf[buf_nb][4]=0; - ret = (const char *)(&buf[buf_nb][0]); - buf_nb = (buf_nb+1) % NB_BUFFERS; - return ret; +const char *TCODConsole::getRGBColorControlString(TCOD_colctrl_t ctrl, + const TCODColor& col) +{ + static char buf[NB_BUFFERS][5]; + static int buf_nb = 0; + buf[buf_nb][0] = ctrl; + buf[buf_nb][1] = col.r; + buf[buf_nb][2] = col.g; + buf[buf_nb][3] = col.b; + buf[buf_nb][4] = 0; + const char* ret = buf[buf_nb]; + buf_nb = (buf_nb + 1) % NB_BUFFERS; + return ret; } #endif diff --git a/tcod_sys/libtcod/src/libtcod/console.h b/tcod_sys/libtcod/src/libtcod/console.h index 05bfc69a4..e01059da4 100644 --- a/tcod_sys/libtcod/src/libtcod/console.h +++ b/tcod_sys/libtcod/src/libtcod/console.h @@ -1,30 +1,34 @@ -/* -* libtcod -* Copyright (c) 2008-2018 Jice & Mingos & rmtew -* All rights reserved. -* -* Redistribution and use in source and binary forms, with or without -* modification, are permitted provided that the following conditions are met: -* * Redistributions of source code must retain the above copyright -* notice, this list of conditions and the following disclaimer. -* * Redistributions in binary form must reproduce the above copyright -* notice, this list of conditions and the following disclaimer in the -* documentation and/or other materials provided with the distribution. -* * The name of Jice or Mingos may not be used to endorse or promote -* products derived from this software without specific prior written -* permission. -* -* THIS SOFTWARE IS PROVIDED BY JICE, MINGOS AND RMTEW ``AS IS'' AND ANY -* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED -* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE -* DISCLAIMED. IN NO EVENT SHALL JICE, MINGOS OR RMTEW BE LIABLE FOR ANY -* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES -* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; -* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND -* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS -* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. -*/ +/* BSD 3-Clause License + * + * Copyright © 2008-2019, Jice and the libtcod contributors. + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions are met: + * + * 1. Redistributions of source code must retain the above copyright notice, + * this list of conditions and the following disclaimer. + * + * 2. Redistributions in binary form must reproduce the above copyright notice, + * this list of conditions and the following disclaimer in the documentation + * and/or other materials provided with the distribution. + * + * 3. Neither the name of the copyright holder nor the names of its + * contributors may be used to endorse or promote products derived from + * this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE + * POSSIBILITY OF SUCH DAMAGE. + */ #ifndef _TCOD_CONSOLE_H #define _TCOD_CONSOLE_H @@ -32,6 +36,10 @@ #ifdef TCOD_CONSOLE_SUPPORT +#include "console/console.h" +#include "console/drawing.h" +#include "console/printing.h" +#include "console/rexpaint.h" #include "color.h" #include "console_types.h" #include "image.h" @@ -44,74 +52,19 @@ extern "C" { #define TCOD_BKGND_ALPHA(alpha) ((TCOD_bkgnd_flag_t)(TCOD_BKGND_ALPH|(((uint8_t)(alpha*255))<<8))) #define TCOD_BKGND_ADDALPHA(alpha) ((TCOD_bkgnd_flag_t)(TCOD_BKGND_ADDA|(((uint8_t)(alpha*255))<<8))) -TCODLIB_API void TCOD_console_init_root(int w, int h, const char * title, bool fullscreen, TCOD_renderer_t renderer); -TCODLIB_API void TCOD_quit(void); -TCODLIB_API void TCOD_console_set_window_title(const char *title); -TCODLIB_API void TCOD_console_set_fullscreen(bool fullscreen); -TCODLIB_API bool TCOD_console_is_fullscreen(void); -TCODLIB_API bool TCOD_console_is_window_closed(void); -TCODLIB_API bool TCOD_console_has_mouse_focus(void); -TCODLIB_API bool TCOD_console_is_active(void); - -TCODLIB_API void TCOD_console_set_custom_font(const char *fontFile, int flags,int nb_char_horiz, int nb_char_vertic); +TCODLIB_API int TCOD_console_set_custom_font( + const char *fontFile, + int flags, + int nb_char_horiz, + int nb_char_vertic); TCODLIB_API void TCOD_console_map_ascii_code_to_font(int asciiCode, int fontCharX, int fontCharY); TCODLIB_API void TCOD_console_map_ascii_codes_to_font(int asciiCode, int nbCodes, int fontCharX, int fontCharY); TCODLIB_API void TCOD_console_map_string_to_font(const char *s, int fontCharX, int fontCharY); - -TCODLIB_API void TCOD_console_set_dirty(int x, int y, int w, int h); -TCODLIB_API void TCOD_console_set_default_background(TCOD_console_t con,TCOD_color_t col); -TCODLIB_API void TCOD_console_set_default_foreground(TCOD_console_t con,TCOD_color_t col); -TCODLIB_API void TCOD_console_clear(TCOD_console_t con); -TCODLIB_API void TCOD_console_set_char_background(TCOD_console_t con,int x, int y, TCOD_color_t col, TCOD_bkgnd_flag_t flag); -TCODLIB_API void TCOD_console_set_char_foreground(TCOD_console_t con,int x, int y, TCOD_color_t col); -TCODLIB_API void TCOD_console_set_char(TCOD_console_t con,int x, int y, int c); -TCODLIB_API void TCOD_console_put_char(TCOD_console_t con,int x, int y, int c, TCOD_bkgnd_flag_t flag); -TCODLIB_API void TCOD_console_put_char_ex(TCOD_console_t con,int x, int y, int c, TCOD_color_t fore, TCOD_color_t back); - -TCODLIB_API void TCOD_console_set_background_flag(TCOD_console_t con,TCOD_bkgnd_flag_t flag); -TCODLIB_API TCOD_bkgnd_flag_t TCOD_console_get_background_flag(TCOD_console_t con); -TCODLIB_API void TCOD_console_set_alignment(TCOD_console_t con,TCOD_alignment_t alignment); -TCODLIB_API TCOD_alignment_t TCOD_console_get_alignment(TCOD_console_t con); - -TCOD_DEPRECATED("Use TCOD_console_printf instead.") -TCODLIB_API void TCOD_console_print(TCOD_console_t con,int x, int y, const char *fmt, ...); -TCOD_DEPRECATED("Use TCOD_console_printf_ex instead.") -TCODLIB_API void TCOD_console_print_ex(TCOD_console_t con,int x, int y, TCOD_bkgnd_flag_t flag, TCOD_alignment_t alignment, const char *fmt, ...); -TCOD_DEPRECATED("Use TCOD_console_printf_rect instead.") -TCODLIB_API int TCOD_console_print_rect(TCOD_console_t con,int x, int y, int w, int h, const char *fmt, ...); -TCOD_DEPRECATED("Use TCOD_console_printf_rect_ex instead.") -TCODLIB_API int TCOD_console_print_rect_ex(TCOD_console_t con,int x, int y, int w, int h, TCOD_bkgnd_flag_t flag, TCOD_alignment_t alignment, const char *fmt, ...); -TCODLIB_API int TCOD_console_get_height_rect(TCOD_console_t con,int x, int y, int w, int h, const char *fmt, ...); - -TCODLIB_API void TCOD_console_rect(TCOD_console_t con,int x, int y, int w, int h, bool clear, TCOD_bkgnd_flag_t flag); -TCODLIB_API void TCOD_console_hline(TCOD_console_t con,int x,int y, int l, TCOD_bkgnd_flag_t flag); -TCODLIB_API void TCOD_console_vline(TCOD_console_t con,int x,int y, int l, TCOD_bkgnd_flag_t flag); -TCODLIB_API void TCOD_console_print_frame(TCOD_console_t con,int x,int y,int w,int h, bool empty, TCOD_bkgnd_flag_t flag, const char *fmt, ...); - #ifndef NO_UNICODE -/* unicode support */ TCODLIB_API void TCOD_console_map_string_to_font_utf(const wchar_t *s, int fontCharX, int fontCharY); -TCOD_DEPRECATED("Use TCOD_console_printf instead.") -TCODLIB_API void TCOD_console_print_utf(TCOD_console_t con,int x, int y, const wchar_t *fmt, ...); -TCOD_DEPRECATED("Use TCOD_console_printf_ex instead.") -TCODLIB_API void TCOD_console_print_ex_utf(TCOD_console_t con,int x, int y, TCOD_bkgnd_flag_t flag, TCOD_alignment_t alignment, const wchar_t *fmt, ...); -TCOD_DEPRECATED("Use TCOD_console_printf_rect instead.") -TCODLIB_API int TCOD_console_print_rect_utf(TCOD_console_t con,int x, int y, int w, int h, const wchar_t *fmt, ...); -TCOD_DEPRECATED("Use TCOD_console_printf_rect_ex instead.") -TCODLIB_API int TCOD_console_print_rect_ex_utf(TCOD_console_t con,int x, int y, int w, int h, TCOD_bkgnd_flag_t flag, TCOD_alignment_t alignment, const wchar_t *fmt, ...); -TCODLIB_API int TCOD_console_get_height_rect_utf(TCOD_console_t con,int x, int y, int w, int h, const wchar_t *fmt, ...); #endif - -TCODLIB_API TCOD_color_t TCOD_console_get_default_background(TCOD_console_t con); -TCODLIB_API TCOD_color_t TCOD_console_get_default_foreground(TCOD_console_t con); -TCODLIB_API TCOD_color_t TCOD_console_get_char_background(TCOD_console_t con,int x, int y); -TCODLIB_API TCOD_color_t TCOD_console_get_char_foreground(TCOD_console_t con,int x, int y); -TCODLIB_API int TCOD_console_get_char(TCOD_console_t con,int x, int y); - -TCODLIB_API void TCOD_console_set_fade(uint8_t val, TCOD_color_t fade); -TCODLIB_API uint8_t TCOD_console_get_fade(void); -TCODLIB_API TCOD_color_t TCOD_console_get_fading_color(void); +TCODLIB_API void TCOD_console_set_dirty(int x, int y, int w, int h); TCODLIB_API void TCOD_console_flush(void); @@ -128,46 +81,15 @@ TCODLIB_API bool TCOD_console_load_apf(TCOD_console_t con, const char *filename) TCODLIB_API bool TCOD_console_save_asc(TCOD_console_t con, const char *filename); TCODLIB_API bool TCOD_console_save_apf(TCOD_console_t con, const char *filename); -TCODLIB_API TCOD_console_t TCOD_console_new(int w, int h); -TCODLIB_API int TCOD_console_get_width(TCOD_console_t con); -TCODLIB_API int TCOD_console_get_height(TCOD_console_t con); -TCODLIB_API void TCOD_console_set_key_color(TCOD_console_t con,TCOD_color_t col); -TCODLIB_API void TCOD_console_blit(TCOD_console_t src,int xSrc, int ySrc, int wSrc, int hSrc, TCOD_console_t dst, int xDst, int yDst, float foreground_alpha, float background_alpha); -TCODLIB_API void TCOD_console_blit_key_color( - TCOD_console_t src,int xSrc, int ySrc, int wSrc, int hSrc, - TCOD_console_t dst, int xDst, int yDst, - float foreground_alpha, float background_alpha, TCOD_color_t *key_color); -TCODLIB_API void TCOD_console_delete(TCOD_console_t console); - TCODLIB_API void TCOD_console_credits(void); TCODLIB_API void TCOD_console_credits_reset(void); TCODLIB_API bool TCOD_console_credits_render(int x, int y, bool alpha); -/* UTF-8 functions */ -TCODLIB_API void TCOD_console_printf(TCOD_console_t con, int x, int y, - const char *fmt, ...); -TCODLIB_API void TCOD_console_printf_ex( - TCOD_console_t con, int x, int y, TCOD_bkgnd_flag_t flag, - TCOD_alignment_t alignment, const char *fmt, ...); -TCODLIB_API int TCOD_console_printf_rect( - TCOD_console_t con, int x, int y, int w, int h, const char *fmt, ...); -TCODLIB_API int TCOD_console_printf_rect_ex( - TCOD_console_t con,int x, int y, int w, int h, - TCOD_bkgnd_flag_t flag, TCOD_alignment_t alignment, const char *fmt, ...); -TCODLIB_API -void TCOD_console_printf_frame(struct TCOD_Console *con, - int x, int y, int w, int h, int empty, - TCOD_bkgnd_flag_t flag, const char *fmt, ...); -TCODLIB_API -int TCOD_console_get_height_rect_fmt(struct TCOD_Console *con, - int x, int y, int w, int h, - const char *fmt, ...); - -/* Private internal functions. */ -int TCOD_console_print_internal_utf8_( - TCOD_console_t con, int x, int y, int max_width, int max_height, - TCOD_bkgnd_flag_t flag, TCOD_alignment_t align, - const unsigned char *string, int can_split, int count_only); +TCOD_DEPRECATED("This function is a stub and will do nothing.") +TCODLIB_API void TCOD_console_set_keyboard_repeat(int initial_delay, + int interval); +TCOD_DEPRECATED("This function is a stub and will do nothing.") +TCODLIB_API void TCOD_console_disable_keyboard_repeat(); #ifdef __cplusplus } #endif diff --git a/tcod_sys/libtcod/src/libtcod/console.hpp b/tcod_sys/libtcod/src/libtcod/console.hpp index 065bf4200..73ffc53da 100644 --- a/tcod_sys/libtcod/src/libtcod/console.hpp +++ b/tcod_sys/libtcod/src/libtcod/console.hpp @@ -1,37 +1,44 @@ -/* -* libtcod -* Copyright (c) 2008-2018 Jice & Mingos & rmtew -* All rights reserved. -* -* Redistribution and use in source and binary forms, with or without -* modification, are permitted provided that the following conditions are met: -* * Redistributions of source code must retain the above copyright -* notice, this list of conditions and the following disclaimer. -* * Redistributions in binary form must reproduce the above copyright -* notice, this list of conditions and the following disclaimer in the -* documentation and/or other materials provided with the distribution. -* * The name of Jice or Mingos may not be used to endorse or promote -* products derived from this software without specific prior written -* permission. -* -* THIS SOFTWARE IS PROVIDED BY JICE, MINGOS AND RMTEW ``AS IS'' AND ANY -* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED -* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE -* DISCLAIMED. IN NO EVENT SHALL JICE, MINGOS OR RMTEW BE LIABLE FOR ANY -* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES -* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; -* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND -* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS -* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. -*/ +/* BSD 3-Clause License + * + * Copyright © 2008-2019, Jice and the libtcod contributors. + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions are met: + * + * 1. Redistributions of source code must retain the above copyright notice, + * this list of conditions and the following disclaimer. + * + * 2. Redistributions in binary form must reproduce the above copyright notice, + * this list of conditions and the following disclaimer in the documentation + * and/or other materials provided with the distribution. + * + * 3. Neither the name of the copyright holder nor the names of its + * contributors may be used to endorse or promote products derived from + * this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE + * POSSIBILITY OF SUCH DAMAGE. + */ #ifndef _TCOD_CONSOLE_HPP #define _TCOD_CONSOLE_HPP #include #include "console.h" -#include "console_rexpaint.h" +#include "console/drawing.h" +#include "console/printing.h" +#include "console/rexpaint.h" +#include "engine/display.h" #ifdef TCOD_CONSOLE_SUPPORT @@ -680,11 +687,11 @@ public : TCOD_alignment_t getAlignment() const; /** * Print an EASCII formatted string to the console. - * /rst + * \rst * .. deprecated:: 1.8 * EASCII is being phased out. Use TCODConsole::printf or one of the * UTF-8 overloads. - * /endrst + * \endrst */ TCOD_DEPRECATED("Use TCODConsole::printf or the std::string overload for" " this function.") @@ -694,17 +701,17 @@ public : * * This method will use this consoles default alignment, blend mode, and * colors. - * /rst + * \rst * .. versionadded:: 1.8 - * /endrst + * \endrst */ void print(int x, int y, const std::string &str); /** * Print a UTF-8 string to the console with specific alignment and blend * mode. - * /rst + * \rst * .. versionadded:: 1.8 - * /endrst + * \endrst */ void print(int x, int y, const std::string &str, TCOD_alignment_t alignment, TCOD_bkgnd_flag_t flag); @@ -713,27 +720,29 @@ public : * * This method will use this consoles default alignment, blend mode, and * colors. - * /rst + * \rst * .. versionadded:: 1.8 - * /endrst + * \endrst */ + TCODLIB_FORMAT(4, 5) void printf(int x, int y, const char *fmt, ...); /** * Format and print a UTF-8 string to the console with specific alignment * and blend mode. - * /rst + * \rst * .. versionadded:: 1.8 - * /endrst + * \endrst */ + TCODLIB_FORMAT(6, 7) void printf(int x, int y, TCOD_bkgnd_flag_t flag, TCOD_alignment_t alignment, const char *fmt, ...); /** * Print an EASCII formatted string to the console. - * /rst + * \rst * .. deprecated:: 1.8 * Use `TCODConsole::print` or `TCODConsole::printf`. * These functions have overloads for specifying flag and alignment. - * /endrst + * \endrst */ TCOD_DEPRECATED("Use TCODConsole::print or TCODConsole::printf instead of" " this function.") @@ -761,7 +770,8 @@ public : y <= y+h < console height @Param fmt printf-like format string, eventually followed by parameters. You can use control codes to change the colors inside the string, except in C#. */ - int printRect(int x, int y, int w, int h, const char *fmt, ...); + TCODLIB_FORMAT(6, 7) + int printRect(int x, int y, int w, int h, const char *fmt, ...); /** @PageName console_print @@ -787,7 +797,9 @@ public : @Param alignment defines how the strings are printed on screen. @Param fmt printf-like format string, eventually followed by parameters. You can use control codes to change the colors inside the string, except in C#. */ - int printRectEx(int x, int y, int w, int h, TCOD_bkgnd_flag_t flag, TCOD_alignment_t alignment, const char *fmt, ...); + TCODLIB_FORMAT(8, 9) + int printRectEx(int x, int y, int w, int h, TCOD_bkgnd_flag_t flag, + TCOD_alignment_t alignment, const char *fmt, ...); /** @PageName console_print @@ -806,7 +818,8 @@ public : y <= y+h < console height @Param fmt printf-like format string, eventually followed by parameters. You can use control codes to change the colors inside the string, except in C#. */ - int getHeightRect(int x, int y, int w, int h, const char *fmt, ...); + TCODLIB_FORMAT(6, 7) + int getHeightRect(int x, int y, int w, int h, const char *fmt, ...); /** @PageName console_print @@ -1770,6 +1783,11 @@ public : ... use off1 off1=nil -- release the reference */ + TCOD_DEPRECATED("This function is a stub and will do nothing.") + static void setKeyboardRepeat(int initialDelay,int interval); + TCOD_DEPRECATED("This function is a stub and will do nothing.") + static void disableKeyboardRepeat(); + virtual ~TCODConsole(); void setDirty(int x, int y, int w, int h); @@ -1786,11 +1804,11 @@ protected : friend class TCODImage; friend class TCODZip; friend class TCODText; - friend TCODLIB_API void TCOD_console_init_root( - int w, int h, const char* title, - bool fullscreen, TCOD_renderer_t renderer); + friend TCODLIB_API void tcod::console::init_root( + int w, int h, const std::string& title, + bool fullscreen, TCOD_renderer_t renderer, bool vsync); TCODConsole(); - TCOD_console_t data; + TCOD_Console* data; }; #endif /* TCOD_CONSOLE_SUPPORT */ diff --git a/tcod_sys/libtcod/src/libtcod/console/console.h b/tcod_sys/libtcod/src/libtcod/console/console.h new file mode 100644 index 000000000..43fdff373 --- /dev/null +++ b/tcod_sys/libtcod/src/libtcod/console/console.h @@ -0,0 +1,427 @@ +/* BSD 3-Clause License + * + * Copyright © 2008-2019, Jice and the libtcod contributors. + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions are met: + * + * 1. Redistributions of source code must retain the above copyright notice, + * this list of conditions and the following disclaimer. + * + * 2. Redistributions in binary form must reproduce the above copyright notice, + * this list of conditions and the following disclaimer in the documentation + * and/or other materials provided with the distribution. + * + * 3. Neither the name of the copyright holder nor the names of its + * contributors may be used to endorse or promote products derived from + * this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE + * POSSIBILITY OF SUCH DAMAGE. + */ +#ifndef TCOD_CONSOLE_CONSOLE_H_ +#define TCOD_CONSOLE_CONSOLE_H_ + +#ifdef __cplusplus +#include +#include +#include +#endif // __cplusplus + +#include "../portability.h" +#include "../color/color.h" +#include "../utility/matrix.h" +/** + * \enum TCOD_bkgnd_flag_t + * + * Background color blend modes. + */ +typedef enum { + TCOD_BKGND_NONE, + TCOD_BKGND_SET, + TCOD_BKGND_MULTIPLY, + TCOD_BKGND_LIGHTEN, + TCOD_BKGND_DARKEN, + TCOD_BKGND_SCREEN, + TCOD_BKGND_COLOR_DODGE, + TCOD_BKGND_COLOR_BURN, + TCOD_BKGND_ADD, + TCOD_BKGND_ADDA, + TCOD_BKGND_BURN, + TCOD_BKGND_OVERLAY, + TCOD_BKGND_ALPH, + TCOD_BKGND_DEFAULT +} TCOD_bkgnd_flag_t; +/** + * \enum TCOD_alignment_t + * + * Print justification options. + */ +typedef enum { + TCOD_LEFT, + TCOD_RIGHT, + TCOD_CENTER +} TCOD_alignment_t; +/** + * A console tile. + */ +struct TCOD_ConsoleTile { +#ifdef __cplusplus + bool operator==(const TCOD_ConsoleTile& rhs) const noexcept + { + return ch == rhs.ch && fg == rhs.fg && bg == rhs.bg; + } + bool operator!=(const TCOD_ConsoleTile& rhs) const noexcept + { + return !(*this == rhs); + } +#endif // __cplusplus + /** + * The Unicode codepoint for this tile. + */ + int ch; + /** + * The tile glyph color, rendered on top of the background. + */ + struct TCOD_ColorRGBA fg; + /** + * The tile background color, rendered behind the glyph. + */ + struct TCOD_ColorRGBA bg; +}; +/** + * The libtcod console struct. + * + * All attributes should be considered private. + * + * All C++ methods should be considered provisional, and are subject to + * change. + */ +struct TCOD_Console { +#ifdef __cplusplus + struct TCOD_ConsoleTile* begin() noexcept + { + return tiles; + } + const struct TCOD_ConsoleTile* begin() const noexcept + { + return tiles; + } + struct TCOD_ConsoleTile* end() noexcept + { + return tiles + w * h; + } + const struct TCOD_ConsoleTile* end() const noexcept + { + return tiles + w * h; + } + auto operator[](const std::array& yx) noexcept + -> struct TCOD_ConsoleTile& + { + return tiles[w * yx[0] + yx[1]]; + } + auto operator[](const std::array& yx) const noexcept + -> const struct TCOD_ConsoleTile& + { + return tiles[w * yx[0] + yx[1]]; + } + struct TCOD_ConsoleTile& at(int y, int x) + { + range_check_(y, x); + return (*this)[{y, x}]; + } + const struct TCOD_ConsoleTile& at(int y, int x) const + { + range_check_(y, x); + return (*this)[{y, x}]; + } + int size() const + { + return w * h; + } + void range_check_(int y, int x) const + { + if (!in_bounds(y, x)) { + throw std::out_of_range( + std::string("Out of bounds lookup {x=") + + std::to_string(x) + + ", y=" + + std::to_string(y) + + "} on console of shape {" + + std::to_string(w) + + ", " + + std::to_string(h) + + "}."); + } + } + bool in_bounds(int y, int x) const noexcept + { + return 0 <= x && x < w && 0 <= y && y < h; + } +#endif // __cplusplus + /** Console width and height (in characters, not pixels.) */ + int w,h; + /** A contiguous array of console tiles. */ + struct TCOD_ConsoleTile* tiles; + /** Default background operator for print & print_rect functions. */ + TCOD_bkgnd_flag_t bkgnd_flag; + /** Default alignment for print & print_rect functions. */ + TCOD_alignment_t alignment; + /** Foreground (text) and background colors. */ + TCOD_color_t fore, back; + /** True if a key color is being used. */ + bool has_key_color; + /** The current key color for this console. */ + TCOD_color_t key_color; +}; +typedef struct TCOD_Console TCOD_Console; +typedef struct TCOD_Console *TCOD_console_t; +/** + * Return a new console with a specific number of columns and rows. + * + * \param w Number of columns. + * \param h Number of columns. + * \return A pointer to the new console, or NULL on error. + */ +TCODLIB_CAPI TCOD_Console* TCOD_console_new(int w, int h); +/** + * Return the width of a console. + */ +TCODLIB_CAPI int TCOD_console_get_width(const TCOD_Console* con); +/** + * Return the height of a console. + */ +TCODLIB_CAPI int TCOD_console_get_height(const TCOD_Console* con); +TCODLIB_CAPI void TCOD_console_set_key_color( + TCOD_Console* con, TCOD_color_t col); +/** + * Blit from one console to another. + * + * \param srcCon Pointer to the source console. + * \param xSrc The left region of the source console to blit from. + * \param ySrc The top region of the source console to blit from. + * \param wSrc The width of the region to blit from. + * If 0 then it will fill to the maximum width. + * \param hSrc The height of the region to blit from. + * If 0 then it will fill to the maximum height. + * \param dstCon Pointer to the destination console. + * \param xDst The left corner to blit onto the destination console. + * \param yDst The top corner to blit onto the destination console. + * \param foreground_alpha Foreground blending alpha. + * \param background_alpha Background blending alpha. + * + * If the source console has a key color, this function will use it. + */ +TCODLIB_CAPI void TCOD_console_blit( + const TCOD_Console* src, + int xSrc, + int ySrc, + int wSrc, + int hSrc, + TCOD_Console* dst, + int xDst, + int yDst, + float foreground_alpha, + float background_alpha); +TCODLIB_CAPI void TCOD_console_blit_key_color( + const TCOD_Console* src, + int xSrc, + int ySrc, + int wSrc, + int hSrc, + TCOD_Console* dst, + int xDst, + int yDst, + float foreground_alpha, + float background_alpha, + const TCOD_color_t *key_color); +/** + * Delete a console. + * + * \param con A console pointer. + * + * If the console being deleted is the root console, then the display will be + * uninitialized. + */ +TCODLIB_CAPI void TCOD_console_delete(TCOD_Console* console); + +TCODLIB_CAPI void TCOD_console_set_default_background( + TCOD_Console* con, TCOD_color_t col); +TCODLIB_CAPI void TCOD_console_set_default_foreground( + TCOD_Console* con, TCOD_color_t col); +/** + * Clear a console to its default colors and the space character code. + */ +TCODLIB_CAPI void TCOD_console_clear(TCOD_Console* con); +/** + * Blend a background color onto a console tile. + * + * \param con A console pointer. + * \param x The X coordinate, the left-most position being 0. + * \param y The Y coordinate, the top-most position being 0. + * \param col The background color to blend. + * \param flag The blend mode to use. + */ +TCODLIB_CAPI void TCOD_console_set_char_background( + TCOD_Console* con, + int x, + int y, + TCOD_color_t col, + TCOD_bkgnd_flag_t flag); +/** + * Change the foreground color of a console tile. + * + * \param con A console pointer. + * \param x The X coordinate, the left-most position being 0. + * \param y The Y coordinate, the top-most position being 0. + * \param col The foreground color to set. + */ +TCODLIB_CAPI void TCOD_console_set_char_foreground( + TCOD_Console* con, int x, int y, TCOD_color_t col); +/** + * Change a character on a console tile, without changing its colors. + * + * \param con A console pointer. + * \param x The X coordinate, the left-most position being 0. + * \param y The Y coordinate, the top-most position being 0. + * \param c The character code to set. + */ +TCODLIB_CAPI void TCOD_console_set_char( + TCOD_Console* con, int x, int y, int c); +/** + * Draw a character on a console using the default colors. + * + * \param con A console pointer. + * \param x The X coordinate, the left-most position being 0. + * \param y The Y coordinate, the top-most position being 0. + * \param c The character code to place. + * \param flag A TCOD_bkgnd_flag_t flag. + */ +TCODLIB_CAPI void TCOD_console_put_char( + TCOD_Console* con, int x, int y, int c, TCOD_bkgnd_flag_t flag); +/** + * Draw a character on the console with the given colors. + * + * \param con A console pointer. + * \param x The X coordinate, the left-most position being 0. + * \param y The Y coordinate, the top-most position being 0. + * \param c The character code to place. + * \param fore The foreground color. + * \param back The background color. This color will not be blended. + */ +TCODLIB_CAPI void TCOD_console_put_char_ex( + TCOD_Console* con, + int x, + int y, + int c, + TCOD_color_t fore, TCOD_color_t back); +/** + * Set a consoles default background flag. + * + * \param con A console pointer. + * \param flag One of `TCOD_bkgnd_flag_t`. + */ +TCODLIB_CAPI void TCOD_console_set_background_flag( + TCOD_Console* con, + TCOD_bkgnd_flag_t flag); +/** + * Return a consoles default background flag. + */ +TCODLIB_CAPI TCOD_bkgnd_flag_t TCOD_console_get_background_flag( + TCOD_Console* con); +/** + * Set a consoles default alignment. + * + * \param con A console pointer. + * \param alignment One of TCOD_alignment_t + */ +TCODLIB_CAPI void TCOD_console_set_alignment( + TCOD_Console* con, + TCOD_alignment_t alignment); +/** + * Return a consoles default alignment. + */ +TCODLIB_CAPI TCOD_alignment_t TCOD_console_get_alignment(TCOD_Console* con); + +TCODLIB_CAPI TCOD_color_t TCOD_console_get_default_background( + TCOD_Console* con); +TCODLIB_CAPI TCOD_color_t TCOD_console_get_default_foreground( + TCOD_Console* con); +/** + * Return the background color of a console at x,y + * + * \param con A console pointer. + * \param x The X coordinate, the left-most position being 0. + * \param y The Y coordinate, the top-most position being 0. + * \return A TCOD_color_t struct with a copy of the background color. + */ +TCODLIB_CAPI TCOD_color_t TCOD_console_get_char_background( + const TCOD_Console* con, int x, int y); +/** + * Return the foreground color of a console at x,y + * + * \param con A console pointer. + * \param x The X coordinate, the left-most position being 0. + * \param y The Y coordinate, the top-most position being 0. + * \return A TCOD_color_t struct with a copy of the foreground color. + */ +TCODLIB_CAPI TCOD_color_t TCOD_console_get_char_foreground( + const TCOD_Console* con, int x, int y); +/** + * Return a character code of a console at x,y + * + * \param con A console pointer. + * \param x The X coordinate, the left-most position being 0. + * \param y The Y coordinate, the top-most position being 0. + * \return The character code. + */ +TCODLIB_CAPI int TCOD_console_get_char(const TCOD_Console* con, int x, int y); +/** + * Fade the color of the display. + * + * \param val Where at 255 colors are normal and at 0 colors are completely + * faded. + * \param fadecol Color to fade towards. + */ +TCODLIB_CAPI void TCOD_console_set_fade(uint8_t val, TCOD_color_t fade); +/** + * Return the fade value. + * + * \return At 255 colors are normal and at 0 colors are completely faded. + */ +TCODLIB_CAPI uint8_t TCOD_console_get_fade(void); +/** + * Return the fade color. + * + * \return The current fading color. + */ +TCODLIB_CAPI TCOD_color_t TCOD_console_get_fading_color(void); +TCODLIB_CAPI void TCOD_console_resize_( + TCOD_Console* console, int width, int height); +#ifdef __cplusplus +namespace tcod { +namespace console { + typedef struct TCOD_ConsoleTile Tile; + typedef MatrixView ConsoleView; + inline ConsoleView as_view_(struct TCOD_Console& console) + { + return {console.tiles, {console.h, console.w}}; + } + inline const ConsoleView as_view_(const struct TCOD_Console& console) + { + return {console.tiles, {console.h, console.w}}; + } +} // namespace console +} // namespace tcod +#endif // __cplusplus +#endif // TCOD_CONSOLE_CONSOLE_H_ diff --git a/tcod_sys/libtcod/src/libtcod/console/console_clobbered.cpp b/tcod_sys/libtcod/src/libtcod/console/console_clobbered.cpp new file mode 100644 index 000000000..106c2d2c7 --- /dev/null +++ b/tcod_sys/libtcod/src/libtcod/console/console_clobbered.cpp @@ -0,0 +1,431 @@ +/* BSD 3-Clause License + * + * Copyright © 2008-2019, Jice and the libtcod contributors. + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions are met: + * + * 1. Redistributions of source code must retain the above copyright notice, + * this list of conditions and the following disclaimer. + * + * 2. Redistributions in binary form must reproduce the above copyright notice, + * this list of conditions and the following disclaimer in the documentation + * and/or other materials provided with the distribution. + * + * 3. Neither the name of the copyright holder nor the names of its + * contributors may be used to endorse or promote products derived from + * this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE + * POSSIBILITY OF SUCH DAMAGE. + */ +#include "console.h" +#include "../libtcod_int.h" +TCOD_Console* TCOD_console_new(int w, int h) +{ + TCOD_IFNOT(w > 0 && h > 0 ) { return NULL; } + struct TCOD_Console *con = new TCOD_Console{}; + if (!con) { return NULL; } + con->w = w; + con->h = h; + TCOD_console_init(con); + if (TCOD_ctx.root) { + con->alignment = TCOD_ctx.root->alignment; + con->bkgnd_flag = TCOD_ctx.root->bkgnd_flag; + } + return con; +} +static void TCOD_console_data_alloc(struct TCOD_Console& console) +{ + int size = console.w * console.h; + if (!console.tiles) { console.tiles = new struct TCOD_ConsoleTile[size](); } +} +static void TCOD_console_data_free(struct TCOD_Console *con) +{ + if (!con) { return; } + delete[] con->tiles; + con->tiles = nullptr; +} +bool TCOD_console_init(TCOD_Console* con) +{ + con = TCOD_console_validate_(con); + TCOD_IFNOT(con) { return false; } + con->fore = TCOD_white; + con->back = TCOD_black; + + TCOD_console_data_alloc(*con); + + con->bkgnd_flag = TCOD_BKGND_NONE; + con->alignment = TCOD_LEFT; + TCOD_console_clear(con); + return true; +} +bool TCOD_console_init(TCOD_Console* con, const std::string& title, + bool fullscreen) +{ + if (!TCOD_console_init(con)) { return false; } + if (!TCOD_sys_init(con, fullscreen) ) { return false; } + TCOD_sys_set_window_title(title.c_str()); + return true; +} +void TCOD_console_delete(TCOD_Console* con) +{ + TCOD_Console* console = (con ? con : TCOD_ctx.root); + if (!console) { return; } + TCOD_console_data_free(console); + delete console; + if (console == TCOD_ctx.root) { + TCOD_ctx.root = nullptr; + } + if (con == nullptr) { + TCOD_sys_shutdown(); + } +} +void TCOD_console_resize_(TCOD_Console* console, int width, int height) +{ + console = TCOD_console_validate_(console); + if (!console) { return; } + if (console->w == width && console->h == height) { return; } + TCOD_console_data_free(console); + console->w = width; + console->h = height; + TCOD_console_data_alloc(*console); +} +int TCOD_console_get_width(const TCOD_Console* con) +{ + con = TCOD_console_validate_(con); + return (con ? con->w : 0); +} +int TCOD_console_get_height(const TCOD_Console* con) +{ + con = TCOD_console_validate_(con); + return (con ? con->h : 0); +} +void TCOD_console_set_background_flag(TCOD_Console* con, + TCOD_bkgnd_flag_t flag) +{ + con = TCOD_console_validate_(con); + if (con) { con->bkgnd_flag = flag; } +} +TCOD_bkgnd_flag_t TCOD_console_get_background_flag(TCOD_Console* con) +{ + con = TCOD_console_validate_(con); + return (con ? con->bkgnd_flag : TCOD_BKGND_NONE); +} +void TCOD_console_set_alignment(TCOD_Console* con, TCOD_alignment_t alignment) +{ + con = TCOD_console_validate_(con); + if (con) { con->alignment = alignment; } +} +TCOD_alignment_t TCOD_console_get_alignment(TCOD_console_t con) +{ + con = TCOD_console_validate_(con); + return (con ? con->alignment : TCOD_LEFT); +} +/** + * A modified lerp operation which can accept RGBA types. + */ +static auto TCOD_console_blit_lerp_( + const struct TCOD_ColorRGBA color1, + const struct TCOD_ColorRGBA color2, + float interp) +-> struct TCOD_ColorRGBA +{ + return tcod::ColorRGBA{ + TCOD_color_lerp(tcod::ColorRGB(color1), tcod::ColorRGB(color2), interp), + color1.a, + }; +} +/** + * Return the tile for a blit operation between src and dst. + */ +static auto TCOD_console_blit_cell_( + const struct TCOD_ConsoleTile& src, + const struct TCOD_ConsoleTile& dst, + float fg_alpha, + float bg_alpha, + const TCOD_ColorRGB* key_color) +-> struct TCOD_ConsoleTile +{ + if (key_color && tcod::ColorRGB(src.bg) == *key_color) { + return dst; // Source pixel is transparent. + } + if (fg_alpha >= 1.0f && bg_alpha >= 1.0f) { + return src; // No alpha. Perform a plain copy. + } + int ch = dst.ch; + tcod::ColorRGBA bg(dst.bg); + tcod::ColorRGBA fg(dst.fg); + bg = TCOD_console_blit_lerp_(bg, src.bg, bg_alpha); + if (src.ch == ' ') { + // Source is space, so keep the current glyph. + fg = TCOD_console_blit_lerp_(fg, src.bg, bg_alpha); + } else if (ch == ' ') { + // Destination is space, so use the glyph from source. + ch = src.ch; + fg = TCOD_console_blit_lerp_(bg, src.fg, fg_alpha); + } else if (ch == src.ch) { + fg = TCOD_console_blit_lerp_(fg, src.fg, fg_alpha); + } else { + /* Pick the glyph based on foreground_alpha. */ + if (fg_alpha < 0.5f) { + fg = TCOD_console_blit_lerp_(fg, bg, fg_alpha * 2); + } else { + ch = src.ch; + fg = TCOD_console_blit_lerp_(bg, src.fg, (fg_alpha - 0.5f) * 2); + } + } + return {ch, fg, bg}; +} +void TCOD_console_blit_key_color( + const TCOD_Console* src, + int xSrc, + int ySrc, + int wSrc, + int hSrc, + TCOD_Console* dst, + int xDst, + int yDst, + float foreground_alpha, + float background_alpha, + const TCOD_color_t* key_color) +{ + src = TCOD_console_validate_(src); + dst = TCOD_console_validate_(dst); + if (!src || !dst) { return; } + if (wSrc == 0) { wSrc = src->w; } + if (hSrc == 0) { hSrc = src->h; } + TCOD_IFNOT(wSrc > 0 && hSrc > 0) { return; } + TCOD_IFNOT(xDst + wSrc >= 0 && yDst + hSrc >= 0 + && xDst < dst->w && yDst < dst->h) { return; } + for (int cx = xSrc; cx < xSrc + wSrc; ++cx) { + for (int cy = ySrc; cy < ySrc + hSrc; ++cy) { + /* Check if we're outside the dest console. */ + int dx = cx - xSrc + xDst; + int dy = cy - ySrc + yDst; + if (!src->in_bounds(cy, cx)) { continue; } + if (!dst->in_bounds(dy, dx)) { continue; } + dst->at(dy, dx) = TCOD_console_blit_cell_( + src->at(cy, cx), + dst->at(dy, dx), + foreground_alpha, + background_alpha, + key_color); + } + } +} +void TCOD_console_blit( + const TCOD_Console* src, + int xSrc, + int ySrc, + int wSrc, + int hSrc, + TCOD_Console* dst, + int xDst, + int yDst, + float foreground_alpha, + float background_alpha) +{ + src = TCOD_console_validate_(src); + if (!src) { return; } + TCOD_console_blit_key_color( + src, xSrc, ySrc, wSrc, hSrc, dst, xDst, yDst, + foreground_alpha, background_alpha, + (src->has_key_color ? &src->key_color : NULL)); +} +void TCOD_console_put_char(TCOD_Console* con, int x, int y, int c, + TCOD_bkgnd_flag_t flag) +{ + con = TCOD_console_validate_(con); + if (!TCOD_console_is_index_valid_(con, x, y)) { return; } + con->tiles[y * con->w + x].ch = c; + TCOD_console_set_char_foreground(con, x, y, con->fore); + TCOD_console_set_char_background(con, x, y, con->back, flag); +} +void TCOD_console_put_char_ex(TCOD_console_t con, int x, int y, int c, + TCOD_color_t fore, TCOD_color_t back) +{ + con = TCOD_console_validate_(con); + if (!TCOD_console_is_index_valid_(con, x, y)) { return; } + con->tiles[y * con->w + x].ch = c; + TCOD_console_set_char_foreground(con, x, y, fore); + TCOD_console_set_char_background(con, x, y, back, TCOD_BKGND_SET); +} +void TCOD_console_clear(TCOD_console_t con) +{ + con = TCOD_console_validate_(con); + TCOD_IFNOT(con) { return; } + for (auto& tile : *con) { + tile = {' ', tcod::ColorRGBA(con->fore), tcod::ColorRGBA(con->back)}; + } + /* clear the sdl renderer cache */ + TCOD_sys_set_dirty(0, 0, con->w, con->h); +} +TCOD_color_t TCOD_console_get_char_background(const TCOD_Console* con, + int x, int y) +{ + con = TCOD_console_validate_(con); + if (!TCOD_console_is_index_valid_(con, x, y)) { return TCOD_black; } + return tcod::ColorRGB(con->tiles[y * con->w + x].bg); +} +void TCOD_console_set_char_foreground(TCOD_Console* con, + int x, int y, TCOD_color_t col) +{ + con = TCOD_console_validate_(con); + if (!TCOD_console_is_index_valid_(con, x, y)) { return; } + con->tiles[y * con->w + x].fg = tcod::ColorRGBA(col); +} +TCOD_color_t TCOD_console_get_char_foreground(const TCOD_Console* con, + int x, int y) +{ + con = TCOD_console_validate_(con); + if (!TCOD_console_is_index_valid_(con, x, y)) { return TCOD_white; } + return tcod::ColorRGB(con->tiles[y * con->w + x].fg); +} +int TCOD_console_get_char(const TCOD_Console* con, int x, int y) +{ + con = TCOD_console_validate_(con); + if (!TCOD_console_is_index_valid_(con, x, y)) { return 0; } + return con->tiles[y * con->w + x].ch; +} +/** + * Clamp colors channels that are outside of uint8_t's range. + */ +static constexpr uint8_t clamp_color_(uint8_t c) noexcept { return c; } +static constexpr uint8_t clamp_color_(int c) noexcept +{ + return static_cast(std::max(0, std::min(c, 255))); +} +/** + * Mix two colors using a lambda. + */ +template +static constexpr TCOD_ColorRGBA blend_color_( + const TCOD_ColorRGBA& bg, const TCOD_color_t& fg, const F& lambda) +{ + return { + clamp_color_(lambda(bg.r, fg.r)), + clamp_color_(lambda(bg.g, fg.g)), + clamp_color_(lambda(bg.b, fg.b)), + bg.a, + }; +} +void TCOD_console_set_char_background( + TCOD_Console* con, int x, int y, TCOD_color_t col, TCOD_bkgnd_flag_t flag) +{ + con = TCOD_console_validate_(con); + if (!TCOD_console_is_index_valid_(con, x, y)) { return; } + TCOD_ColorRGBA& bg = con->tiles[y * con->w + x].bg; + if (flag == TCOD_BKGND_DEFAULT) { flag = con->bkgnd_flag; } + int alpha = flag >> 8; + switch (flag & 0xff) { + case TCOD_BKGND_SET: + bg = tcod::ColorRGBA(col, bg.a); + break; + case TCOD_BKGND_MULTIPLY: + bg = tcod::ColorRGBA(TCOD_color_multiply(tcod::ColorRGB(bg), col), bg.a); + break; + case TCOD_BKGND_LIGHTEN: + bg = blend_color_(bg, col, + [](uint8_t a, uint8_t b){ return std::max(a, b); }); + break; + case TCOD_BKGND_DARKEN: + bg = blend_color_(bg, col, + [](uint8_t a, uint8_t b){ return std::min(a, b); }); + break; + case TCOD_BKGND_SCREEN: + // newbk = white - (white - oldbk) * (white - curbk) + bg = blend_color_(bg, col, + [](int a, int b){ return 255 - (255 - a) * (255 - b) / 255; }); + break; + case TCOD_BKGND_COLOR_DODGE: + // newbk = curbk / (white - oldbk) + bg = blend_color_(bg, col, + [](int a, int b){ return (a == 255 ? 255 : 255 * b / (255 - a)); }); + break; + case TCOD_BKGND_COLOR_BURN: + // newbk = white - (white - oldbk) / curbk + bg = blend_color_(bg, col, + [](int a, int b){ + return (b == 0 ? 0 : 255 - (255 * (255 - a)) / b); }); + break; + case TCOD_BKGND_ADD: + // newbk = oldbk + curbk + bg = blend_color_(bg, col, [](int a, int b){ return a + b; }); + break; + case TCOD_BKGND_ADDA: + // newbk = oldbk + alpha * curbk + bg = blend_color_(bg, col, + [=](int a, int b){ return a + alpha * b / 255; }); + break; + case TCOD_BKGND_BURN: + // newbk = oldbk + curbk - white + bg = blend_color_(bg, col, [](int a, int b){ return a + b - 255; }); + break; + case TCOD_BKGND_OVERLAY: + // newbk = curbk.x <= 0.5 ? 2*curbk*oldbk + // : white - 2*(white-curbk)*(white-oldbk) + bg = blend_color_(bg, col, [](int a, int b){ + return (b <= 128 ? 2 * b * a / 255 + : 255 - 2 * (255 - b) * (255 - a) / 255); }); + break; + case TCOD_BKGND_ALPH: + // newbk = (1.0f-alpha)*oldbk + alpha*(curbk-oldbk) + bg = tcod::ColorRGBA(TCOD_color_lerp(tcod::ColorRGB(bg), col, alpha / 255.0f), bg.a); + break; + default: break; + } +} +void TCOD_console_set_char(TCOD_console_t con, int x, int y, int c) +{ + con = TCOD_console_validate_(con); + if (!TCOD_console_is_index_valid_(con, x, y)) { return; } + con->tiles[y * con->w + x].ch = c; +} +void TCOD_console_set_default_foreground(TCOD_Console* con, TCOD_color_t col) +{ + con = TCOD_console_validate_(con); + TCOD_IFNOT(con) { return; } + con->fore = col; +} +void TCOD_console_set_default_background(TCOD_Console* con,TCOD_color_t col) +{ + con = TCOD_console_validate_(con); + TCOD_IFNOT(con) { return; } + con->back = col; +} +TCOD_color_t TCOD_console_get_default_foreground(TCOD_Console* con) +{ + con = TCOD_console_validate_(con); + TCOD_IFNOT(con) { return TCOD_white; } + return con->fore; +} +TCOD_color_t TCOD_console_get_default_background(TCOD_Console* con) +{ + con = TCOD_console_validate_(con); + TCOD_IFNOT(con) { return TCOD_black; } + return con->back; +} +void TCOD_console_set_fade(uint8_t val, TCOD_color_t fadecol) +{ + TCOD_ctx.fade = val; + TCOD_ctx.fading_color = fadecol; +} +uint8_t TCOD_console_get_fade(void) +{ + return TCOD_ctx.fade; +} +TCOD_color_t TCOD_console_get_fading_color(void) +{ + return TCOD_ctx.fading_color; +} diff --git a/tcod_sys/libtcod/src/libtcod/console/drawing.cpp b/tcod_sys/libtcod/src/libtcod/console/drawing.cpp new file mode 100644 index 000000000..6972f487f --- /dev/null +++ b/tcod_sys/libtcod/src/libtcod/console/drawing.cpp @@ -0,0 +1,118 @@ +/* BSD 3-Clause License + * + * Copyright © 2008-2019, Jice and the libtcod contributors. + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions are met: + * + * 1. Redistributions of source code must retain the above copyright notice, + * this list of conditions and the following disclaimer. + * + * 2. Redistributions in binary form must reproduce the above copyright notice, + * this list of conditions and the following disclaimer in the documentation + * and/or other materials provided with the distribution. + * + * 3. Neither the name of the copyright holder nor the names of its + * contributors may be used to endorse or promote products derived from + * this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE + * POSSIBILITY OF SUCH DAMAGE. + */ +#include "drawing.h" + +#include "../libtcod_int.h" +#include "../console.h" +namespace tcod { +namespace console { +/** + * Clamp the given values to fit within a console. + */ +static void clamp_rect_(int cx, int cy, int cw, int ch, + int& x, int& y, int& w, int& h) +{ + if (x + w > cw) { w = cw - x; } + if (y + h > ch) { h = ch - y; } + if (x < cx) { + w -= cx - x; + x = cx; + } + if (y < cy) { + h -= cy - y; + y = cy; + } +} +void put( + TCOD_Console* console, + int x, + int y, + int ch, + const TCOD_color_t* fg, + const TCOD_color_t* bg, + TCOD_bkgnd_flag_t flag) +{ + console = TCOD_console_validate_(console); + if (!console) { return; } + if (!TCOD_console_is_index_valid_(console, x, y)) { return; } + int console_index = y * console->w + x; + if (ch > 0) { console->tiles[console_index].ch = ch; } + if (fg) { TCOD_console_set_char_foreground(console, x, y, *fg); } + if (bg) { TCOD_console_set_char_background(console, x, y, *bg, flag); } +} +void draw_rect( + TCOD_Console* console, + int x, + int y, + int width, + int height, + int ch, + const TCOD_color_t* fg, + const TCOD_color_t* bg, + TCOD_bkgnd_flag_t flag) +{ + console = TCOD_console_validate_(console); + if (!console) { return; } + clamp_rect_(0, 0, console->w, console->h, x, y, width, height); + TCOD_ASSERT(x + width <= console->w && y + height <= console->h); + for (int console_y = y; console_y < y + height; ++console_y) { + for (int console_x = x; console_x < x + width; ++console_x) { + put(console, console_x, console_y, ch, fg, bg, flag); + } + } +} +} // namespace console +} // namespace tcod +void TCOD_console_rect(TCOD_Console* console, int x, int y, int rw, int rh, + bool clear, TCOD_bkgnd_flag_t flag) +{ + console = TCOD_console_validate_(console); + if (!console) { return; } + tcod::console::draw_rect(console, x, y, rw, rh, + clear ? 0x20 : 0, nullptr, &console->back, flag); +} +void TCOD_console_hline(TCOD_Console* console,int x, int y, int l, + TCOD_bkgnd_flag_t flag) +{ + console = TCOD_console_validate_(console); + if (!console) { return; } + tcod::console::draw_rect(console, x, y, l, 1, + 0x2500, &console->fore, &console->back, flag); // ─ +} +void TCOD_console_vline(TCOD_Console* console,int x, int y, int l, + TCOD_bkgnd_flag_t flag) +{ + console = TCOD_console_validate_(console); + if (!console) { return; } + tcod::console::draw_rect(console, x, y, 1, l, + 0x2502, &console->fore, &console->back, flag); // │ +} diff --git a/tcod_sys/libtcod/src/libtcod/console/drawing.h b/tcod_sys/libtcod/src/libtcod/console/drawing.h new file mode 100644 index 000000000..d26f42687 --- /dev/null +++ b/tcod_sys/libtcod/src/libtcod/console/drawing.h @@ -0,0 +1,117 @@ +/* BSD 3-Clause License + * + * Copyright © 2008-2019, Jice and the libtcod contributors. + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions are met: + * + * 1. Redistributions of source code must retain the above copyright notice, + * this list of conditions and the following disclaimer. + * + * 2. Redistributions in binary form must reproduce the above copyright notice, + * this list of conditions and the following disclaimer in the documentation + * and/or other materials provided with the distribution. + * + * 3. Neither the name of the copyright holder nor the names of its + * contributors may be used to endorse or promote products derived from + * this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE + * POSSIBILITY OF SUCH DAMAGE. + */ +#ifndef TCOD_CONSOLE_DRAWING_H_ +#define TCOD_CONSOLE_DRAWING_H_ +#include "../console_types.h" +#include "../portability.h" +/** + * Draw a rectangle onto a console. + * + * \param con A console pointer. + * \param x The starting region, the left-most position being 0. + * \param y The starting region, the top-most position being 0. + * \param rw The width of the rectangle. + * \param rh The height of the rectangle. + * \param clear If true the drawing region will be filled with spaces. + * \param flag The blending flag to use. + */ +TCODLIB_CAPI void TCOD_console_rect( + TCOD_Console* con, int x, int y, int w, int h, bool clear, + TCOD_bkgnd_flag_t flag); +/** + * Draw a horizontal line using the default colors. + * + * \param con A console pointer. + * \param x The starting X coordinate, the left-most position being 0. + * \param y The starting Y coordinate, the top-most position being 0. + * \param l The width of the line. + * \param flag The blending flag. + * + * This function makes assumptions about the fonts character encoding. + * It will fail if the font encoding is not `cp437`. + */ +TCODLIB_CAPI void TCOD_console_hline( + TCOD_Console* con, int x, int y, int l, TCOD_bkgnd_flag_t flag); +/** + * Draw a vertical line using the default colors. + * + * \param con A console pointer. + * \param x The starting X coordinate, the left-most position being 0. + * \param y The starting Y coordinate, the top-most position being 0. + * \param l The height of the line. + * \param flag The blending flag. + * + * This function makes assumptions about the fonts character encoding. + * It will fail if the font encoding is not `cp437`. + */ +TCODLIB_CAPI void TCOD_console_vline( + TCOD_Console* con, int x, int y, int l, TCOD_bkgnd_flag_t flag); +#ifdef __cplusplus +namespace tcod { +namespace console { +// All functions here are provisional unless given an added version. +/** + * Place a single tile on a `console` at `x`,`y`. + * + * If `ch` is 0 then the character code will not be updated. + * + * If `fg`,`bg` is nullptr then their respective colors will not be updated. + */ +TCODLIB_API void put( + TCOD_Console* console, + int x, + int y, + int ch, + const TCOD_color_t* fg = &TCOD_white, + const TCOD_color_t* bg = &TCOD_black, + TCOD_bkgnd_flag_t flag = TCOD_BKGND_SET); +/** + * Draw a rectangle on a `console` with a shape of `x`,`y`,`width`,`height`. + * + * If `ch` is 0 then the character code will not be updated. + * + * If `fg`,`bg` is nullptr then their respective colors will not be updated. + */ +TCODLIB_API void draw_rect( + TCOD_Console* console, + int x, + int y, + int width, + int height, + int ch, + const TCOD_color_t* fg = &TCOD_white, + const TCOD_color_t* bg = &TCOD_black, + TCOD_bkgnd_flag_t flag = TCOD_BKGND_SET); +} // namespace console +} // namespace tcod +#endif // __cplusplus +#endif // TCOD_CONSOLE_DRAWING_H_ diff --git a/tcod_sys/libtcod/src/libtcod/console/printing.cpp b/tcod_sys/libtcod/src/libtcod/console/printing.cpp new file mode 100644 index 000000000..accfec81d --- /dev/null +++ b/tcod_sys/libtcod/src/libtcod/console/printing.cpp @@ -0,0 +1,1399 @@ +/* BSD 3-Clause License + * + * Copyright © 2008-2019, Jice and the libtcod contributors. + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions are met: + * + * 1. Redistributions of source code must retain the above copyright notice, + * this list of conditions and the following disclaimer. + * + * 2. Redistributions in binary form must reproduce the above copyright notice, + * this list of conditions and the following disclaimer in the documentation + * and/or other materials provided with the distribution. + * + * 3. Neither the name of the copyright holder nor the names of its + * contributors may be used to endorse or promote products derived from + * this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE + * POSSIBILITY OF SUCH DAMAGE. + */ +#include "printing.h" + +#include +#ifndef NO_UNICODE +#include +#include +#endif +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#include "drawing.h" +#include "../console.h" +#include "../libtcod_int.h" +#include "../utility.h" +#include "../../vendor/utf8proc/utf8proc.h" +static TCOD_color_t color_control_fore[TCOD_COLCTRL_NUMBER] = { + {255, 255, 255}, {255, 255, 255}, {255, 255, 255}, {255, 255, 255}, + {255, 255, 255}}; +static TCOD_color_t color_control_back[TCOD_COLCTRL_NUMBER]; +/** + * Assign a foreground and background color to a color control index. + * + * \param con Index to change, e.g. `TCOD_COLCTRL_1` + * \param fore Foreground color to assign to this index. + * \param back Background color to assign to this index. + */ +void TCOD_console_set_color_control( + TCOD_colctrl_t con, TCOD_color_t fore, TCOD_color_t back) +{ + TCOD_IFNOT(con >= TCOD_COLCTRL_1 && con <= TCOD_COLCTRL_NUMBER) return; + color_control_fore[con - 1] = fore; + color_control_back[con - 1] = back; +} +char *TCOD_console_vsprint(const char *fmt, va_list ap) +{ + #define NB_BUFFERS 10 + #define INITIAL_SIZE 512 + /* several static buffers in case the function is used more than once in a single function call */ + static char *msg[NB_BUFFERS] = {NULL}; + static int buflen[NB_BUFFERS] = {0}; + static int curbuf = 0; + char *ret; + bool ok = false; + if (!msg[0]) { + int i; + for (i = 0; i < NB_BUFFERS; i++) { + buflen[i] = INITIAL_SIZE; + msg[i] = static_cast(calloc(sizeof(char), INITIAL_SIZE)); + } + } + do { + /* warning ! depending on the compiler, vsnprintf return -1 or + the expected string length if the buffer is not big enough */ + va_list ap_clone; + va_copy(ap_clone, ap); + int len = std::vsnprintf(msg[curbuf], buflen[curbuf], fmt, ap_clone); + va_end(ap_clone); + ok=true; + if (len < 0 || len >= buflen[curbuf]) { + /* buffer too small. */ + if (len > 0) { + while (buflen[curbuf] < len + 1) { buflen[curbuf] *= 2; } + } else { + buflen[curbuf] *= 2; + } + free(msg[curbuf]); + msg[curbuf] = static_cast(calloc(sizeof(char), buflen[curbuf])); + ok = false; + } + } while (!ok); + ret = msg[curbuf]; + curbuf = (curbuf + 1) % NB_BUFFERS; + return ret; +} +/** + * Print a titled, framed region on a console, using default colors and + * alignment. + * + * \param con A console pointer. + * \param x The starting X coordinate, the left-most position being 0. + * \param y The starting Y coordinate, the top-most position being 0. + * \param w The width of the frame. + * \param h The height of the frame. + * \param empty If true the characters inside of the frame will be cleared + * with spaces. + * \param flag The blending flag. + * \param fmt A format string as if passed to printf. + * \param ... Variadic arguments as if passed to printf. + * + * This function makes assumptions about the fonts character encoding. + * It will fail if the font encoding is not `cp437`. + */ +void TCOD_console_print_frame( + TCOD_Console* con,int x, int y, int w, int h, + bool empty, TCOD_bkgnd_flag_t flag, const char* fmt, ...) +{ + con = TCOD_console_validate_(con); + if (!con) { return; } + TCOD_console_put_char(con, x, y, TCOD_CHAR_NW, flag); + TCOD_console_put_char(con, x + w - 1, y, TCOD_CHAR_NE, flag); + TCOD_console_put_char(con, x, y + h - 1 , TCOD_CHAR_SW, flag); + TCOD_console_put_char(con, x + w - 1, y + h - 1, TCOD_CHAR_SE, flag); + TCOD_console_hline(con, x + 1, y, w - 2, flag); + TCOD_console_hline(con, x + 1, y + h - 1, w - 2, flag); + if (h > 2) { + TCOD_console_vline(con, x,y + 1, h - 2, flag); + TCOD_console_vline(con, x + w - 1, y + 1, h - 2, flag); + if (empty) { + TCOD_console_rect(con, x + 1, y + 1, w - 2, h - 2, true, flag); + } + } + if (fmt) { + va_list ap; + int xs; + char *title; + va_start(ap, fmt); + title = TCOD_console_vsprint(fmt, ap); + va_end(ap); + title[w - 3] = 0; /* truncate if needed */ + xs = x + (w - static_cast(strlen(title)) - 2) / 2; + std::swap(con->fore, con->back); + TCOD_console_print_ex(con, xs, y, TCOD_BKGND_SET, TCOD_LEFT, + " %s ", title); + std::swap(con->fore, con->back); + } +} +/** + * Print a string on a console, using default colors and alignment. + * + * \param con A console pointer. + * \param x The starting X coordinate, the left-most position being 0. + * \param y The starting Y coordinate, the top-most position being 0. + * \param fmt A format string as if passed to printf. + * \param ... Variadic arguments as if passed to printf. + */ +void TCOD_console_print(TCOD_Console* con, int x, int y, const char* fmt, ...) +{ + va_list ap; + con = TCOD_console_validate_(con); + if (!con) { return; } + va_start(ap, fmt); + TCOD_console_print_internal(con, x, y, 0, 0, con->bkgnd_flag, + con->alignment, TCOD_console_vsprint(fmt, ap), false, false); + va_end(ap); +} +/** + * Print a string on a console, using default colors. + * + * \param con A console pointer. + * \param x The starting X coordinate, the left-most position being 0. + * \param y The starting Y coordinate, the top-most position being 0. + * \param flag The blending flag. + * \param alignment The font alignment to use. + * \param fmt A format string as if passed to printf. + * \param ... Variadic arguments as if passed to printf. + */ +void TCOD_console_print_ex(TCOD_Console* con,int x, int y, + TCOD_bkgnd_flag_t flag, TCOD_alignment_t alignment, const char *fmt, ...) +{ + va_list ap; + va_start(ap, fmt); + TCOD_console_print_internal(con, x, y, 0, 0, flag, alignment, + TCOD_console_vsprint(fmt, ap), false, false); + va_end(ap); +} +/** + * Print a string on a console constrained to a rectangle, using default + * colors and alignment. + * + * \param con A console pointer. + * \param x The starting X coordinate, the left-most position being 0. + * \param y The starting Y coordinate, the top-most position being 0. + * \param w The width of the region. + * If 0 then the maximum width will be used. + * \param h The height of the region. + * If 0 then the maximum height will be used. + * \param fmt A format string as if passed to printf. + * \param ... Variadic arguments as if passed to printf. + * \return The number of lines actually printed. + */ +int TCOD_console_print_rect(TCOD_Console* con, int x, int y, int w, int h, + const char *fmt, ...) +{ + int ret; + va_list ap; + con = TCOD_console_validate_(con); + if (!con) { return 0; } + va_start(ap, fmt); + ret = TCOD_console_print_internal(con, x, y, w, h, con->bkgnd_flag, + con->alignment, TCOD_console_vsprint(fmt, ap), true, false); + va_end(ap); + return ret; +} +/** + * Print a string on a console constrained to a rectangle, using default + * colors. + * + * \param con A console pointer. + * \param x The starting X coordinate, the left-most position being 0. + * \param y The starting Y coordinate, the top-most position being 0. + * \param w The width of the region. + * If 0 then the maximum width will be used. + * \param h The height of the region. + * If 0 then the maximum height will be used. + * \param flag The blending flag. + * \param alignment The font alignment to use. + * \param fmt A format string as if passed to printf. + * \param ... Variadic arguments as if passed to printf. + * \return The number of lines actually printed. + */ +int TCOD_console_print_rect_ex(TCOD_Console* con, int x, int y, int w, int h, + TCOD_bkgnd_flag_t flag, TCOD_alignment_t alignment, const char *fmt, ...) +{ + int ret; + va_list ap; + va_start(ap, fmt); + ret = TCOD_console_print_internal(con, x, y, w, h, flag, alignment, + TCOD_console_vsprint(fmt, ap), true, false); + va_end(ap); + return ret; +} +/** + * Return the number of lines that would be printed by the + * + * \param con A console pointer. + * \param x The starting X coordinate, the left-most position being 0. + * \param y The starting Y coordinate, the top-most position being 0. + * \param w The width of the region. + * If 0 then the maximum width will be used. + * \param h The height of the region. + * If 0 then the maximum height will be used. + * \param fmt A format string as if passed to printf. + * \param ... Variadic arguments as if passed to printf. + * \return The number of lines that would have been printed. + */ +int TCOD_console_get_height_rect(TCOD_Console* con, + int x, int y, int w, int h, const char *fmt, ...) +{ + int ret; + va_list ap; + va_start(ap, fmt); + ret = TCOD_console_print_internal(con, x, y, w, h, TCOD_BKGND_NONE, + TCOD_LEFT, TCOD_console_vsprint(fmt, ap), true, true); + va_end(ap); + return ret; +} +/* non public methods */ +int TCOD_console_stringLength(const unsigned char *s) +{ + int l = 0; + while (*s) { + if (*s == TCOD_COLCTRL_FORE_RGB || *s == TCOD_COLCTRL_BACK_RGB) { + s += 3; + } else if (*s > TCOD_COLCTRL_STOP) { + l++; + } + s++; + } + return l; +} +unsigned char * TCOD_console_forward(unsigned char *s,int l) +{ + while (*s && l > 0) { + if (*s == TCOD_COLCTRL_FORE_RGB || *s == TCOD_COLCTRL_BACK_RGB) { + s += 3; + } else if (*s > TCOD_COLCTRL_STOP) { + l--; + } + s++; + } + return s; +} +unsigned char *TCOD_console_strchr(unsigned char *s, unsigned char c) +{ + while (*s && *s != c) { + if (*s == TCOD_COLCTRL_FORE_RGB || *s == TCOD_COLCTRL_BACK_RGB) { + s += 3; + } + s++; + } + return (*s ? s : NULL); +} + +int TCOD_console_print_internal( + TCOD_Console* con, int x,int y, int rw, int rh, TCOD_bkgnd_flag_t flag, + TCOD_alignment_t align, char *msg, bool can_split, bool count_only) +{ + unsigned char *c = reinterpret_cast(msg); + int cx = 0; + int cy = y; + int minx, maxx, miny, maxy; + TCOD_color_t oldFore; + TCOD_color_t oldBack; + con = TCOD_console_validate_(con); + if (!con) { return 0; } + TCOD_IFNOT(TCOD_console_is_index_valid_(con, x, y)) { return 0; } + TCOD_IFNOT(msg != NULL) { return 0; } + if (rh == 0) { rh = con->h - y; } + if (rw == 0) { + switch(align) { + case TCOD_LEFT: rw = con->w - x; break; + case TCOD_RIGHT: rw = x + 1; break; + case TCOD_CENTER: default: rw = con->w; break; + } + } + oldFore = con->fore; + oldBack = con->back; + miny = y; + maxy = con->h - 1; + if (rh > 0) { maxy = std::min(maxy, y + rh - 1); } + switch (align) { + case TCOD_LEFT: + minx = std::max(0,x); + maxx = std::min(con->w - 1, x + rw - 1); + break; + case TCOD_RIGHT: + minx = std::max(0, x - rw + 1); + maxx = std::min(con->w - 1, x); + break; + case TCOD_CENTER: default: + minx = std::max(0, x - rw / 2); + maxx = std::min(con->w - 1, x + rw / 2); + break; + } + + do { + /* get \n delimited sub-message */ + unsigned char *end = TCOD_console_strchr(c, '\n'); + char bak = 0; + int cl; + unsigned char *split = NULL; + if (end) { *end=0; } + cl = TCOD_console_stringLength(c); + /* find starting x */ + switch (align) { + case TCOD_LEFT : cx = x; break; + case TCOD_RIGHT : cx = x - cl + 1; break; + case TCOD_CENTER : cx = x - cl / 2; break; + } + /* check if the string is completely out of the minx,miny,maxx,maxy frame */ + if (cy >= miny && cy <= maxy && cx <= maxx && cx + cl -1 >= minx) { + if (can_split && cy <= maxy) { + /* if partially out of screen, try to split the sub-message */ + if (cx < minx) { + split = TCOD_console_forward(c, (align == TCOD_CENTER + ? cl - 2 * (minx - cx) + : cl - (minx - cx))); + } else if (align == TCOD_CENTER) { + if (cx + cl / 2 > maxx + 1) { + split = TCOD_console_forward(c, maxx + 1 - cx); + } + } else { + if (cx + cl > maxx + 1) { + split = TCOD_console_forward(c, maxx + 1 - cx); + } + } + } + if (split) { + unsigned char *oldsplit = split; + while (!isspace(*split) && split > c) { split--; } + if (end) { *end = '\n'; } + if (!isspace(*split)) { + split = oldsplit; + } + end = split; + bak = *split; + *split = 0; + cl = TCOD_console_stringLength(c); + switch (align) { + case TCOD_LEFT : cx = x; break; + case TCOD_RIGHT : cx = x - cl + 1; break; + case TCOD_CENTER : cx = x - cl / 2; break; + } + } + if (cx < minx) { + /* truncate left part */ + c += minx-cx; + cl -= minx-cx; + cx = minx; + } + if (cx + cl > maxx + 1) { + /* truncate right part */ + split = TCOD_console_forward(c, maxx + 1 - cx); + *split = 0; + } + /* render the sub-message */ + if (cy >= 0 && cy < con->h) { + while (*c) { + if (*c >= TCOD_COLCTRL_1 && *c <= TCOD_COLCTRL_NUMBER) { + con->fore = color_control_fore[*c - 1]; + con->back = color_control_back[*c - 1]; + } else if (*c == TCOD_COLCTRL_FORE_RGB) { + c++; + con->fore.r = *c++; + con->fore.g = *c++; + con->fore.b = *c; + } else if (*c == TCOD_COLCTRL_BACK_RGB) { + c++; + con->back.r = *c++; + con->back.g = *c++; + con->back.b = *c; + } else if (*c == TCOD_COLCTRL_STOP) { + con->fore = oldFore; + con->back = oldBack; + } else { + if (!count_only) { + TCOD_console_put_char(con, cx, cy, *c, flag); + } + cx++; + } + c++; + } + } + } + if (end) { + /* next line */ + if (split && ! isspace(bak)) { + *end = bak; + c = end; + } else { + c = end + 1; + } + cy++; + } else { + c = NULL; + } + } while (c && cy < con->h && (rh == 0 || cy < y + rh)); + return cy - y + 1; +} +#ifndef NO_UNICODE +wchar_t *TCOD_console_strchr_utf(wchar_t *s, char c) +{ + while (*s && *s != c) { + if (*s == TCOD_COLCTRL_FORE_RGB || *s == TCOD_COLCTRL_BACK_RGB) { + s += 3; + } + s++; + } + return (*s ? s : NULL); +} +void TCOD_console_map_string_to_font_utf(const wchar_t *s, + int fontCharX, int fontCharY) +{ + TCOD_IFNOT(s != NULL) return; + while (*s) { + TCOD_sys_map_ascii_to_font(*s, fontCharX, fontCharY); + fontCharX++; + if (fontCharX == TCOD_ctx.fontNbCharHoriz) { + fontCharX = 0; + fontCharY++; + } + s++; + } +} +wchar_t *TCOD_console_vsprint_utf(const wchar_t *fmt, va_list ap) +{ + #define NB_BUFFERS 10 + #define INITIAL_SIZE 512 + /* several static buffers in case the function is used more than once in a single function call */ + static wchar_t *msg[NB_BUFFERS] = {NULL}; + static int buflen[NB_BUFFERS] = {0}; + static int curbuf = 0; + wchar_t *ret; + bool ok = false; + if (!msg[0]) { + int i; + for (i = 0; i < NB_BUFFERS; i++) { + buflen[i] = INITIAL_SIZE; + msg[i] = static_cast(calloc(sizeof(wchar_t), INITIAL_SIZE)); + } + } + do { + /* warning ! depending on the compiler, vsnprintf return -1 or + the expected string length if the buffer is not big enough */ + int len = vswprintf(msg[curbuf], buflen[curbuf], fmt, ap); + ok = true; + if (len < 0 || len >= buflen[curbuf]) { + /* buffer too small. */ + if (len > 0) { + while (buflen[curbuf] < len + 1) { buflen[curbuf] *= 2; } + } else { + buflen[curbuf] *= 2; + } + free(msg[curbuf]); + msg[curbuf] = static_cast( + calloc(sizeof(wchar_t), buflen[curbuf])); + ok = false; + } + } while (!ok); + ret = msg[curbuf]; + curbuf = (curbuf + 1) % NB_BUFFERS; + return ret; +} +int TCOD_console_stringLength_utf(const wchar_t *s) +{ + int l = 0; + while (*s) { + if (*s == TCOD_COLCTRL_FORE_RGB || *s == TCOD_COLCTRL_BACK_RGB) { + s += 3; + } else if (*s > TCOD_COLCTRL_STOP) { + l++; + } + s++; + } + return l; +} +wchar_t * TCOD_console_forward_utf(wchar_t *s,int l) +{ + while (*s && l > 0) { + if (*s == TCOD_COLCTRL_FORE_RGB || *s == TCOD_COLCTRL_BACK_RGB) { + s+=3; + } else if (*s > TCOD_COLCTRL_STOP) { + l--; + } + s++; + } + return s; +} +int TCOD_console_print_internal_utf( + TCOD_Console* con,int x,int y, int rw, int rh, TCOD_bkgnd_flag_t flag, + TCOD_alignment_t align, wchar_t *msg, bool can_split, bool count_only) +{ + wchar_t *c = msg; + int cx = 0; + int cy = y; + int minx, maxx, miny, maxy; + TCOD_color_t oldFore; + TCOD_color_t oldBack; + con = TCOD_console_validate_(con); + if (!con) { return 0; } + if (!TCOD_console_is_index_valid_(con, x, y)) { return 0; } + TCOD_IFNOT(msg != NULL) { return 0; } + if (rh == 0) { rh = con->h - y; } + if (rw == 0) { + switch(align) { + case TCOD_LEFT: rw = con->w - x; break; + case TCOD_RIGHT: rw = x + 1; break; + case TCOD_CENTER: default: rw = con->w; break; + } + } + oldFore = con->fore; + oldBack = con->back; + miny = y; + maxy = con->h - 1; + if (rh > 0) maxy = std::min(maxy, y + rh - 1); + switch (align) { + case TCOD_LEFT: + minx = std::max(0,x); + maxx = std::min(con->w-1,x+rw-1); + break; + case TCOD_RIGHT: + minx = std::max(0, x - rw + 1); + maxx = std::min(con->w - 1, x); + break; + case TCOD_CENTER: default: + minx = std::max(0, x - rw / 2); + maxx = std::min(con->w - 1, x + rw / 2); + break; + } + + do { + /* get \n delimited sub-message */ + wchar_t *end = TCOD_console_strchr_utf(c, '\n'); + wchar_t bak = 0; + int cl; + wchar_t *split = NULL; + if (end) { *end = 0; } + cl = TCOD_console_stringLength_utf(c); + /* find starting x */ + switch (align) { + case TCOD_LEFT: cx = x; break; + case TCOD_RIGHT: cx = x - cl + 1; break; + case TCOD_CENTER: cx = x - cl / 2; break; + } + /* check if the string is completely out of the minx,miny,maxx,maxy frame */ + if (cy >= miny && cy <= maxy && cx <= maxx && cx + cl - 1 >= minx) { + if (can_split && cy < maxy) { + /* if partially out of screen, try to split the sub-message */ + if (cx < minx) { + split = TCOD_console_forward_utf(c, (align == TCOD_CENTER + ? cl - 2 * (minx - cx) + : cl - (minx - cx))); + } else if (align == TCOD_CENTER) { + if (cx + cl / 2 > maxx + 1) { + split = TCOD_console_forward_utf(c, maxx + 1 - cx); + } + } else { + if (cx + cl > maxx + 1) { + split = TCOD_console_forward_utf(c, maxx + 1 - cx); + } + } + } + if (split) { + wchar_t *oldsplit = split; + while (!iswspace(*split) && split > c) { split--; } + if (end) { *end='\n'; } + if (!iswspace(*split)) { + split = oldsplit; + } + end = split; + bak = *split; + *split = 0; + cl = TCOD_console_stringLength_utf(c); + switch (align) { + case TCOD_LEFT: cx = x; break; + case TCOD_RIGHT: cx = x - cl + 1; break; + case TCOD_CENTER: cx = x - cl / 2; break; + } + } + if (cx < minx) { + /* truncate left part */ + c += minx - cx; + cl -= minx - cx; + cx = minx; + } + if (cx + cl > maxx + 1) { + /* truncate right part */ + split = TCOD_console_forward_utf(c, maxx + 1 - cx); + *split = 0; + } + /* render the sub-message */ + if (cy >= 0 && cy < con->h) + while (*c) { + if (*c >= TCOD_COLCTRL_1 && *c <= TCOD_COLCTRL_NUMBER) { + con->fore = color_control_fore[static_cast(*c) - 1]; + con->back = color_control_back[static_cast(*c) - 1]; + } else if (*c == TCOD_COLCTRL_FORE_RGB) { + c++; + con->fore.r = static_cast(*c++); + con->fore.g = static_cast(*c++); + con->fore.b = static_cast(*c); + } else if (*c == TCOD_COLCTRL_BACK_RGB) { + c++; + con->back.r = static_cast(*c++); + con->back.g = static_cast(*c++); + con->back.b = static_cast(*c); + } else if (*c == TCOD_COLCTRL_STOP) { + con->fore = oldFore; + con->back = oldBack; + } else { + if (!count_only) { + TCOD_console_put_char(con, cx, cy, static_cast(*c), flag); + } + cx++; + } + c++; + } + } + if (end) { + /* next line */ + if (split && !iswspace(bak)) { + *end = bak; + c = end; + } else { + c = end + 1; + } + cy++; + } else { + c = NULL; + } + } while (c && cy < con->h && (rh == 0 || cy < y + rh)); + return cy - y + 1; +} +/** + * \rst + * .. deprecated:: 1.8 + * Use :any:`TCOD_console_printf` instead. + * \endrst + */ +void TCOD_console_print_utf(TCOD_Console* con, int x, int y, + const wchar_t *fmt, ...) +{ + va_list ap; + con = TCOD_console_validate_(con); + if (!con) { return; } + va_start(ap, fmt); + TCOD_console_print_internal_utf(con, x, y, 0, 0, con->bkgnd_flag, + con->alignment, TCOD_console_vsprint_utf(fmt, ap), false, false); + va_end(ap); +} +/** + * \rst + * .. deprecated:: 1.8 + * Use :any:`TCOD_console_printf_ex` instead. + * \endrst + */ +void TCOD_console_print_ex_utf( + TCOD_Console* con, int x, int y, TCOD_bkgnd_flag_t flag, + TCOD_alignment_t alignment, const wchar_t *fmt, ...) +{ + va_list ap; + va_start(ap, fmt); + TCOD_console_print_internal_utf( + con, x, y, 0, 0, flag, alignment, TCOD_console_vsprint_utf(fmt, ap), + false, false); + va_end(ap); +} + +int TCOD_console_print_rect_utf(TCOD_Console* con, int x, int y, int w, int h, + const wchar_t *fmt, ...) +{ + con = TCOD_console_validate_(con); + if (!con) { return 0; } + va_list ap; + va_start(ap, fmt); + int ret = TCOD_console_print_internal_utf( + con, x, y, w, h, con->bkgnd_flag, con->alignment, + TCOD_console_vsprint_utf(fmt, ap), true, false); + va_end(ap); + return ret; +} +/** + * \rst + * .. deprecated:: 1.8 + * Use :any:`TCOD_console_printf_rect_ex` instead. + * \endrst + */ +int TCOD_console_print_rect_ex_utf( + TCOD_Console* con,int x, int y, int w, int h, TCOD_bkgnd_flag_t flag, + TCOD_alignment_t alignment, const wchar_t *fmt, ...) +{ + va_list ap; + va_start(ap, fmt); + int ret = TCOD_console_print_internal_utf( + con, x, y, w, h, flag, alignment, + TCOD_console_vsprint_utf(fmt, ap), true, false); + va_end(ap); + return ret; +} +/** + * \rst + * .. deprecated:: 1.8 + * \endrst + */ +int TCOD_console_get_height_rect_utf( + TCOD_Console* con,int x, int y, int w, int h, const wchar_t *fmt, ...) +{ + va_list ap; + va_start(ap, fmt); + int ret = TCOD_console_print_internal_utf( + con, x, y, w, h, TCOD_BKGND_NONE, TCOD_LEFT, + TCOD_console_vsprint_utf(fmt, ap), true, true); + va_end(ap); + return ret; +} + +#endif /* NO_UNICODE */ +namespace tcod { +namespace console { +static auto vsprint_(const char *fmt, va_list ap) -> std::string +{ + if (!fmt) { return ""; } + va_list ap_clone; + va_copy(ap_clone, ap); + std::string result(std::vsnprintf(nullptr, 0, fmt, ap_clone), 0); + va_end(ap_clone); + std::vsnprintf(&result[0], result.size() + 1, fmt, ap); + return result; +} +class UnicodeIterator: public std::iterator { + public: + UnicodeIterator() + : p_(nullptr), end_(nullptr) + {} + UnicodeIterator(const utf8proc_uint8_t* start, const utf8proc_uint8_t* end) + : p_(start), end_(end) + { + parse_unicode(); + } + UnicodeIterator(const char* start, const char* end) + : UnicodeIterator(reinterpret_cast(start), + reinterpret_cast(end)) + {} + UnicodeIterator(const std::string& str) + : UnicodeIterator(str.empty() ? nullptr : &str.front(), + str.empty() ? nullptr : &str.back() + 1) + {} + UnicodeIterator& operator++() + { + if (p_ >= end_) { + throw std::out_of_range("Moved past the end of the string."); + } + p_ += code_size_; + parse_unicode(); + return *this; + } + UnicodeIterator operator++(int) + { + UnicodeIterator tmp(*this); + operator++(); + return tmp; + } + bool operator==(const UnicodeIterator& rhs) const noexcept + { + return p_ == rhs.p_; + } + bool operator!=(const UnicodeIterator& rhs) const noexcept + { + return p_ != rhs.p_; + } + bool operator<(const UnicodeIterator& rhs) const noexcept + { + return p_ < rhs.p_; + } + int operator*() const + { + if (p_ == end_) { + throw std::out_of_range("Dereferenced past the end of the iterator."); + } + return codepoint_; + } + auto get_property() const noexcept -> const utf8proc_property_t* + { + return utf8proc_get_property(codepoint_); + } + bool empty() const noexcept + { + return p_ == end_; + } + auto end() const -> const UnicodeIterator + { + return UnicodeIterator(end_, end_); + } + /* + * Check if the specified character is any line-break character + */ + bool is_newline() const noexcept + { + switch (get_property()->category) { + case UTF8PROC_CATEGORY_ZL: /* Separator, line */ + case UTF8PROC_CATEGORY_ZP: /* Separator, paragraph */ + return true; + case UTF8PROC_CATEGORY_CC: /* Other, control */ + switch(get_property()->boundclass) { + case UTF8PROC_BOUNDCLASS_CR: // carriage return - \r + case UTF8PROC_BOUNDCLASS_LF: // line feed - \n + return true; + default: break; + } + break; + default: break; + } + return false; + } + private: + void parse_unicode() + { + if (p_ == end_) { + codepoint_ = 0; + code_size_ = 1; + return; + } + code_size_ = utf8proc_iterate(p_, end_ - p_, &codepoint_); + if (code_size_ < 0) { + throw std::logic_error(utf8proc_errmsg(code_size_)); + } + } + const utf8proc_uint8_t* p_; + const utf8proc_uint8_t* end_; + utf8proc_int32_t codepoint_; + utf8proc_ssize_t code_size_; +}; +class FormattedUnicodeIterator: public UnicodeIterator { + public: + FormattedUnicodeIterator() + : UnicodeIterator(), default_fg_(nullptr), default_bg_(nullptr), + fg_(nullptr), bg_(nullptr) + {} + FormattedUnicodeIterator(const std::string& str, + const TCOD_color_t* fg, const TCOD_color_t* bg) + : UnicodeIterator(str), default_fg_(fg), default_bg_(bg), fg_(fg), bg_(bg) + { + parse_special_codes(); + } + FormattedUnicodeIterator(const UnicodeIterator& mit, + const TCOD_color_t* fg, const TCOD_color_t* bg) + : UnicodeIterator(mit), default_fg_(fg), default_bg_(bg), fg_(fg), bg_(bg) + { + parse_special_codes(); + } + FormattedUnicodeIterator(const FormattedUnicodeIterator& rhs) + : UnicodeIterator(rhs), + default_fg_(rhs.default_fg_), default_bg_(rhs.default_bg_), + fg_(rhs.fg_), bg_(rhs.bg_) + { + // Avoid pointing to the temporary colors of other iterators. + if (fg_ == &rhs.temp_fg_) { temp_fg_ = rhs.temp_fg_; fg_ = &temp_fg_; } + if (bg_ == &rhs.temp_bg_) { temp_bg_ = rhs.temp_bg_; bg_ = &temp_bg_; } + } + FormattedUnicodeIterator& operator++() + { + UnicodeIterator::operator++(); + parse_special_codes(); + return *this; + } + auto get_fg() const noexcept -> const TCOD_color_t* + { + return fg_; + } + auto get_bg() const noexcept -> const TCOD_color_t* + { + return bg_; + } + private: + auto parse_rgb() -> TCOD_color_t { + TCOD_color_t color; + UnicodeIterator::operator++(); + color.r = **this; + UnicodeIterator::operator++(); + color.g = **this; + UnicodeIterator::operator++(); + color.b = **this; + return color; + } + void parse_special_codes() + { + if (*this == (*this).end()) { return; } + if (TCOD_COLCTRL_1 <= **this && **this <= TCOD_COLCTRL_NUMBER) { + // Read colors from the color control array. + int color_index = (**this) - TCOD_COLCTRL_1; + fg_ = &color_control_fore[color_index]; + bg_ = &color_control_back[color_index]; + ++(*this); + return; + } else if (**this == TCOD_COLCTRL_STOP) { + // Return colors to their original color. + fg_ = default_fg_; + bg_ = default_bg_; + ++(*this); + return; + } else if (**this == TCOD_COLCTRL_FORE_RGB) { + temp_fg_ = parse_rgb(); + fg_ = &temp_fg_; + ++(*this); + return; + } else if (**this == TCOD_COLCTRL_BACK_RGB) { + temp_bg_ = parse_rgb(); + bg_ = &temp_bg_; + ++(*this); + return; + } + } + // Original colors + const TCOD_color_t* default_fg_; + const TCOD_color_t* default_bg_; + // Current active colors. + const TCOD_color_t* fg_; + const TCOD_color_t* bg_; + // Colors generated from RGB codes. + TCOD_color_t temp_fg_; + TCOD_color_t temp_bg_; +}; +/** + * Get the next line-break or null terminator, or break the string before + * `max_width`. + * + * Returns {break_point, line_width, status} + */ +static std::tuple next_split_( + FormattedUnicodeIterator it, + const UnicodeIterator& end, + int max_width, + int can_split) +{ + // The break point and width of the line. + UnicodeIterator break_point(end); + int break_width = 0; + // The current line width. + int char_width = 0; + bool separating = false; // True if the last iteration was breakable. + while (it != end) { + if (can_split && char_width > 0) { + switch (it.get_property()->category) { + default: + if (char_width + it.get_property()->charwidth > max_width) { + // The next character would go over the max width, so return now. + if (break_point != end) { + // Use latest line break if one exists. + return {break_point, break_width, 1}; + } else { + // Force a line break here. + return {it, char_width, 1}; + } + } + separating = false; + break; + case UTF8PROC_CATEGORY_PD: // Punctuation, dash + if (char_width + it.get_property()->charwidth > max_width) { + return {it, char_width, 1}; + } else { + break_point = it; + ++break_point; + break_width = char_width + it.get_property()->charwidth; + separating = true; + } + break; + case UTF8PROC_CATEGORY_ZS: // Separator, space + if (!separating) { + break_point = it; + break_width = char_width; + separating = true; + } + break; + } + } + if (it.is_newline()) { + // Always break on newlines. + return {it, char_width, 0}; + } + char_width += it.get_property()->charwidth; + ++it; + } + // Return end of iteration. + return {it, char_width, 0}; +} +static int print_internal_( + TCOD_Console& con, + int x, + int y, + int width, + int height, + const std::string& string, + const TCOD_color_t* fg, + const TCOD_color_t* bg, + TCOD_bkgnd_flag_t flag, + TCOD_alignment_t align, + int can_split, + int count_only) +{ + FormattedUnicodeIterator it(string, fg, bg); + UnicodeIterator end = it.end(); + if (!can_split && align == TCOD_RIGHT) { + // In general `can_split = false` is deprecated. + x -= con.w - 1; + width = con.w; + } + // Expand the width/height of 0 to the edge of the console. + if (!width) { width = con.w - x; } + if (!height) { height = con.h - y; } + // Print bounding box. + int left = x; + int right = x + width; + int top = y; + int bottom = y + height; + width = right - left; + height = bottom - top; + if (can_split && (width <= 0 || height <= 0)) { + return 0; // The bounding box is invalid. + } + while (it != end && top < bottom && top < con.h) { + // Check for newlines. + if(it.is_newline()) { + if(it.get_property()->category == UTF8PROC_CATEGORY_ZP) { + top += 2; + } else { + top += 1; + } + ++it; + continue; + } + // Get the next line of characters. + UnicodeIterator line_break; + int line_width; + int split_status; + std::tie(line_break, line_width, split_status) = + next_split_(it, end, width, can_split); + // Set cursor_x from alignment. + int cursor_x = 0; + switch (align) { + default: + case TCOD_LEFT: + cursor_x = left; + break; + case TCOD_RIGHT: + cursor_x = right - line_width; + break; + case TCOD_CENTER: + if (can_split) { + cursor_x = left + (width - line_width) / 2; + } else { + cursor_x = left - (line_width / 2); // Deprecated. + } + break; + } + for (; it < line_break; cursor_x += it.get_property()->charwidth, ++it) { + if(count_only) { continue; } + if (can_split && (left > cursor_x || cursor_x >= right)) { continue; } + if (!can_split && (0 > cursor_x || cursor_x >= con.w)) { continue; } + // Actually render this line of characters. + put(&con, cursor_x, top, *it, it.get_fg(), it.get_bg(), flag); + } + // Ignore any extra spaces. + while (it != end) { + // Separator, space + if (it.get_property()->category != UTF8PROC_CATEGORY_ZS) { break; } + ++it; + } + // If there was an automatic split earlier then the top is moved down. + if (split_status == 1) { top += 1; } + } + return std::min(top, bottom) - y + 1; +} +/** + * Normalize rectangle values using old libtcod rules where alignment can move + * the rectangle position. + */ +static void normalize_old_rect_( + TCOD_Console& console, + TCOD_alignment_t alignment, + int& x, + int& y, + int& width, + int& height) +{ + // Set default width/height if either is zero. + if (width == 0) { width = console.w; } + if (height == 0) { height = console.h - y; } + switch(alignment) { + default: + case TCOD_LEFT: + break; + case TCOD_RIGHT: + x -= width; + break; + case TCOD_CENTER: + x -= width / 2; + break; + } + return; +} +void print( + TCOD_Console* con, + int x, + int y, + const std::string& str, + const TCOD_color_t* fg, + const TCOD_color_t* bg, + TCOD_bkgnd_flag_t flag, + TCOD_alignment_t alignment) +{ + con = TCOD_console_validate_(con); + if (!con) { return; } + print_internal_(*con, x, y, con->w, con->h, str, fg, bg, flag, alignment, + false, false); +} +int print_rect( + struct TCOD_Console *con, + int x, + int y, + int width, + int height, + const std::string& str, + const TCOD_color_t* fg, + const TCOD_color_t* bg, + TCOD_bkgnd_flag_t flag, + TCOD_alignment_t alignment) +{ + con = TCOD_console_validate_(con); + if (!con) { return 0; } + return print_internal_(*con, x, y, width, height, str, fg, bg, + flag, alignment, true, false); +} +int get_height_rect( + std::array console_size, + int x, + int y, + int width, + int height, + const std::string& str) +{ + struct TCOD_Console console{}; + console.w = console_size[0]; + console.h = console_size[1]; + return print_internal_(console, x, y, width, height, str, nullptr, nullptr, + TCOD_BKGND_NONE, TCOD_LEFT, true, true); +} +int get_height_rect( + int width, + const std::string& str) +{ + auto MAX_INT = std::numeric_limits::max(); + return get_height_rect({width, MAX_INT}, 0, 0, width, MAX_INT, str); +} +int get_height_rect( + struct TCOD_Console *con, + int x, + int y, + int width, + int height, + const std::string& str) +{ + con = TCOD_console_validate_(con); + if (!con) { return 0; } + return get_height_rect({con->w, con->h}, x, y, width, height, str); +} +void print_frame( + struct TCOD_Console *con, + int x, + int y, + int width, + int height, + const std::string& title, + const TCOD_color_t* fg, + const TCOD_color_t* bg, + TCOD_bkgnd_flag_t flag, + bool empty) +{ + const int left = x; + const int right = x + width - 1; + const int top = y; + const int bottom = y + height - 1; + con = TCOD_console_validate_(con); + if (!con) { return; } + put(con, left, top, 0x250C, fg, bg, flag); // ┌ + put(con, right, top, 0x2510, fg, bg, flag); // ┠+ put(con, left, bottom, 0x2514, fg, bg, flag); // └ + put(con, right, bottom, 0x2518, fg, bg, flag); // ┘ + draw_rect(con, x + 1, y, width - 2, 1, + 0x2500, &con->fore, &con->back, flag); // ─ + draw_rect(con, x + 1, y + height - 1, width - 2, 1, + 0x2500, &con->fore, &con->back, flag); + draw_rect(con, x, y + 1, 1, height - 2, + 0x2502, &con->fore, &con->back, flag); // │ + draw_rect(con, x + width - 1, y + 1, 1, height - 2, + 0x2502, &con->fore, &con->back, flag); + if (empty) { + draw_rect(con, x + 1, y + 1, width -2, height - 2, + 0x20, &con->fore, &con->back, flag); + } + if (!title.empty()) { + print_rect(con, x, y, width, 1, + " " + title + " ", bg, fg, TCOD_BKGND_SET, TCOD_CENTER); + } +} +} // namespace console +} // namespace tcod +/** + * Format and print a UTF-8 string to a console. + * \rst + * .. versionadded:: 1.8 + * \endrst + */ +void TCOD_console_printf_ex( + TCOD_Console* con, + int x, + int y, + TCOD_bkgnd_flag_t flag, + TCOD_alignment_t alignment, + const char *fmt, ...) +{ + con = TCOD_console_validate_(con); + if (!con) { return; } + va_list ap; + va_start(ap, fmt); + tcod::console::print(con, x, y, tcod::console::vsprint_(fmt, ap), + &con->fore, &con->back, flag, alignment); + va_end(ap); +} +/** + * Format and print a UTF-8 string to a console. + * \rst + * .. versionadded:: 1.8 + * \endrst + */ +void TCOD_console_printf(TCOD_Console* con, int x, int y, const char *fmt, ...) +{ + con = TCOD_console_validate_(con); + if (!con) { return; } + va_list ap; + va_start(ap, fmt); + tcod::console::print( + con, x, y, tcod::console::vsprint_(fmt, ap), + &con->fore, &con->back, con->bkgnd_flag, con->alignment); + va_end(ap); +} +/** + * Format and print a UTF-8 string to a console. + * \rst + * .. versionadded:: 1.8 + * \endrst + */ +int TCOD_console_printf_rect_ex( + struct TCOD_Console* con, + int x, int y, int w, int h, + TCOD_bkgnd_flag_t flag, TCOD_alignment_t alignment, const char *fmt, ...) +{ + con = TCOD_console_validate_(con); + if (!con) { return 0; } + tcod::console::normalize_old_rect_(*con, alignment, x, y, w, h); + va_list ap; + va_start(ap, fmt); + int ret = tcod::console::print_rect( + con, x, y, w, h, tcod::console::vsprint_(fmt, ap), + &con->fore, &con->back, flag, alignment); + va_end(ap); + return ret; +} +/** + * Format and print a UTF-8 string to a console. + * \rst + * .. versionadded:: 1.8 + * \endrst + */ +int TCOD_console_printf_rect( + struct TCOD_Console* con, int x, int y, int w, int h, const char *fmt, ...) +{ + con = TCOD_console_validate_(con); + if (!con) { return 0; } + tcod::console::normalize_old_rect_(*con, con->alignment, x, y, w, h); + va_list ap; + va_start(ap, fmt); + int ret = tcod::console::print_rect( + con, x, y, w, h, tcod::console::vsprint_(fmt, ap), + &con->fore, &con->back, con->bkgnd_flag, con->alignment); + va_end(ap); + return ret; +} +/** + * Return the number of lines that would be printed by this formatted string. + * \rst + * .. versionadded:: 1.8 + * \endrst + */ +int TCOD_console_get_height_rect_fmt( + struct TCOD_Console* con, int x, int y, int w, int h, const char *fmt, ...) +{ + con = TCOD_console_validate_(con); + if (!con) { return 0; } + tcod::console::normalize_old_rect_(*con, TCOD_LEFT, x, y, w, h); + va_list ap; + va_start(ap, fmt); + int ret = tcod::console::get_height_rect(con, x, y, w, h, + tcod::console::vsprint_(fmt, ap)); + va_end(ap); + return ret; +} +/** + * Print a framed and optionally titled region to a console, using default + * colors and alignment. + * + * This function uses Unicode box-drawing characters and a UTF-8 formatted + * string. + * \rst + * .. versionadded:: 1.8 + * \endrst + */ +void TCOD_console_printf_frame(struct TCOD_Console *con, + int x, int y, int width, int height, int empty, + TCOD_bkgnd_flag_t flag, const char *fmt, ...) +{ + con = TCOD_console_validate_(con); + if (!con) { return; } + va_list ap; + va_start(ap, fmt); + tcod::console::print_frame( + con, x, y, width, height, tcod::console::vsprint_(fmt, ap), + &con->fore, &con->back, flag, empty); + va_end(ap); +} diff --git a/tcod_sys/libtcod/src/libtcod/console/printing.h b/tcod_sys/libtcod/src/libtcod/console/printing.h new file mode 100644 index 000000000..46e325872 --- /dev/null +++ b/tcod_sys/libtcod/src/libtcod/console/printing.h @@ -0,0 +1,153 @@ +/* BSD 3-Clause License + * + * Copyright © 2008-2019, Jice and the libtcod contributors. + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions are met: + * + * 1. Redistributions of source code must retain the above copyright notice, + * this list of conditions and the following disclaimer. + * + * 2. Redistributions in binary form must reproduce the above copyright notice, + * this list of conditions and the following disclaimer in the documentation + * and/or other materials provided with the distribution. + * + * 3. Neither the name of the copyright holder nor the names of its + * contributors may be used to endorse or promote products derived from + * this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE + * POSSIBILITY OF SUCH DAMAGE. + */ +#ifndef TCOD_CONSOLE_PRINTING_H_ +#define TCOD_CONSOLE_PRINTING_H_ + +#ifdef __cplusplus +#include +#include +#include +#endif +#include "../portability.h" +#include "../console_types.h" + +#ifdef __cplusplus +extern "C" { +#endif +TCOD_DEPRECATED("Use TCOD_console_printf instead.") +TCODLIB_API void TCOD_console_print(TCOD_Console* con,int x, int y, const char *fmt, ...); +TCOD_DEPRECATED("Use TCOD_console_printf_ex instead.") +TCODLIB_API void TCOD_console_print_ex(TCOD_Console* con,int x, int y, TCOD_bkgnd_flag_t flag, TCOD_alignment_t alignment, const char *fmt, ...); +TCOD_DEPRECATED("Use TCOD_console_printf_rect instead.") +TCODLIB_API int TCOD_console_print_rect(TCOD_Console* con,int x, int y, int w, int h, const char *fmt, ...); +TCOD_DEPRECATED("Use TCOD_console_printf_rect_ex instead.") +TCODLIB_API int TCOD_console_print_rect_ex(TCOD_Console* con,int x, int y, int w, int h, TCOD_bkgnd_flag_t flag, TCOD_alignment_t alignment, const char *fmt, ...); +TCOD_DEPRECATED("Use TCOD_console_printf_frame instead.") +TCODLIB_API void TCOD_console_print_frame(TCOD_console_t con,int x,int y,int w,int h, bool empty, TCOD_bkgnd_flag_t flag, const char *fmt, ...); +TCOD_DEPRECATED("Use TCOD_console_get_height_rect_fmt instead.") +TCODLIB_API int TCOD_console_get_height_rect(TCOD_Console* con,int x, int y, int w, int h, const char *fmt, ...); + +#ifndef NO_UNICODE +TCOD_DEPRECATED("Use TCOD_console_printf instead.") +TCODLIB_API void TCOD_console_print_utf(TCOD_Console* con,int x, int y, const wchar_t *fmt, ...); +TCOD_DEPRECATED("Use TCOD_console_printf_ex instead.") +TCODLIB_API void TCOD_console_print_ex_utf(TCOD_Console* con,int x, int y, TCOD_bkgnd_flag_t flag, TCOD_alignment_t alignment, const wchar_t *fmt, ...); +TCOD_DEPRECATED("Use TCOD_console_printf_rect instead.") +TCODLIB_API int TCOD_console_print_rect_utf(TCOD_Console* con,int x, int y, int w, int h, const wchar_t *fmt, ...); +TCOD_DEPRECATED("Use TCOD_console_printf_rect_ex instead.") +TCODLIB_API int TCOD_console_print_rect_ex_utf(TCOD_Console* con,int x, int y, int w, int h, TCOD_bkgnd_flag_t flag, TCOD_alignment_t alignment, const wchar_t *fmt, ...); +TCOD_DEPRECATED("Use TCOD_console_get_height_rect_fmt instead.") +TCODLIB_API int TCOD_console_get_height_rect_utf(TCOD_Console* con,int x, int y, int w, int h, const wchar_t *fmt, ...); +#endif + +/* UTF-8 functions */ +TCODLIB_API TCODLIB_FORMAT(4, 5) void TCOD_console_printf( + TCOD_Console* con, int x, int y, const char *fmt, ...); +TCODLIB_API TCODLIB_FORMAT(6, 7) void TCOD_console_printf_ex( + TCOD_Console* con, int x, int y, TCOD_bkgnd_flag_t flag, + TCOD_alignment_t alignment, const char *fmt, ...); +TCODLIB_API TCODLIB_FORMAT(6, 7) int TCOD_console_printf_rect( + TCOD_Console* con, int x, int y, int w, int h, const char *fmt, ...); +TCODLIB_API TCODLIB_FORMAT(8, 9) int TCOD_console_printf_rect_ex( + TCOD_Console* con,int x, int y, int w, int h, + TCOD_bkgnd_flag_t flag, TCOD_alignment_t alignment, const char *fmt, ...); +TCODLIB_API TCODLIB_FORMAT(8, 9) +void TCOD_console_printf_frame(struct TCOD_Console *con, + int x, int y, int w, int h, int empty, + TCOD_bkgnd_flag_t flag, const char *fmt, ...); +TCODLIB_API TCODLIB_FORMAT(6, 7) +int TCOD_console_get_height_rect_fmt(struct TCOD_Console *con, + int x, int y, int w, int h, + const char *fmt, ...); +#ifdef __cplusplus +} +#endif +#ifdef __cplusplus +namespace tcod { +namespace console { +// All functions here are provisional unless given an added version. +TCODLIB_API void print( + TCOD_Console* con, + int x, + int y, + const std::string& str, + const TCOD_color_t* fg, + const TCOD_color_t* bg, + TCOD_bkgnd_flag_t flag, + TCOD_alignment_t alignment); +TCODLIB_API int print_rect( + struct TCOD_Console *con, + int x, + int y, + int width, + int height, + const std::string& str, + const TCOD_color_t* fg, + const TCOD_color_t* bg, + TCOD_bkgnd_flag_t flag, + TCOD_alignment_t alignment); +/** + * Return the total number lines that a function with similar arguments would + * print. + */ +TCODLIB_API int get_height_rect( + std::array console_size, + int x, + int y, + int width, + int height, + const std::string& str); +TCODLIB_API int get_height_rect( + int width, + const std::string& str); +TCODLIB_API int get_height_rect( + struct TCOD_Console *con, + int x, + int y, + int width, + int height, + const std::string& str); +TCODLIB_API void print_frame( + struct TCOD_Console *con, + int x, + int y, + int width, + int height, + const std::string& title, + const TCOD_color_t* fg, + const TCOD_color_t* bg, + TCOD_bkgnd_flag_t flag, + bool empty); +} // namespace console +} // namespace tcod +#endif // __cplusplus +#endif /* TCOD_CONSOLE_PRINTING_H_ */ diff --git a/tcod_sys/libtcod/src/libtcod/console_rexpaint.c b/tcod_sys/libtcod/src/libtcod/console/rexpaint.cpp similarity index 76% rename from tcod_sys/libtcod/src/libtcod/console_rexpaint.c rename to tcod_sys/libtcod/src/libtcod/console/rexpaint.cpp index 497979a93..1cf8bdccd 100644 --- a/tcod_sys/libtcod/src/libtcod/console_rexpaint.c +++ b/tcod_sys/libtcod/src/libtcod/console/rexpaint.cpp @@ -1,59 +1,64 @@ -/* -* libtcod -* Copyright (c) 2008-2018 Jice & Mingos & rmtew -* All rights reserved. -* -* Redistribution and use in source and binary forms, with or without -* modification, are permitted provided that the following conditions are met: -* * Redistributions of source code must retain the above copyright -* notice, this list of conditions and the following disclaimer. -* * Redistributions in binary form must reproduce the above copyright -* notice, this list of conditions and the following disclaimer in the -* documentation and/or other materials provided with the distribution. -* * The name of Jice or Mingos may not be used to endorse or promote -* products derived from this software without specific prior written -* permission. -* -* THIS SOFTWARE IS PROVIDED BY JICE, MINGOS AND RMTEW ``AS IS'' AND ANY -* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED -* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE -* DISCLAIMED. IN NO EVENT SHALL JICE, MINGOS OR RMTEW BE LIABLE FOR ANY -* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES -* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; -* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND -* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS -* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. -*/ -#include "console_rexpaint.h" +/* BSD 3-Clause License + * + * Copyright © 2008-2019, Jice and the libtcod contributors. + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions are met: + * + * 1. Redistributions of source code must retain the above copyright notice, + * this list of conditions and the following disclaimer. + * + * 2. Redistributions in binary form must reproduce the above copyright notice, + * this list of conditions and the following disclaimer in the documentation + * and/or other materials provided with the distribution. + * + * 3. Neither the name of the copyright holder nor the names of its + * contributors may be used to endorse or promote products derived from + * this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE + * POSSIBILITY OF SUCH DAMAGE. + */ +#include "rexpaint.h" #ifdef TCOD_CONSOLE_SUPPORT -#include +#include #include -#include "console.h" -#include "libtcod_int.h" /* Needed only for TCOD_fatal */ -#include "console_types.h" -#include "color.h" +#include "../console.h" +#include "../libtcod_int.h" /* Needed only for TCOD_fatal */ +#include "../console_types.h" +#include "../color.h" /* Convert a little-endian number to native memory order. */ -static uint32_t decode_little_endian(uint32_t data) { - int i; - uint32_t result=0; - for(i=0; i<(int)sizeof(result);++i){ - result += (unsigned int)((unsigned char*)&data)[i] << (CHAR_BIT * i); +static uint32_t decode_little_endian(uint32_t data) +{ + uint32_t result = 0; + const uint8_t* p = reinterpret_cast(&data); + for(int i = 0; i < static_cast(sizeof(result)); ++i) { + result += p[i] << (std::numeric_limits::digits * i); } return result; } /* Byte swaps a number into little-endian order to be saved to disk. */ static uint32_t encode_little_endian(uint32_t number) { - int i; - uint32_t result=0; - for(i=0; i<(int)sizeof(result);++i){ - ((unsigned char*)&result)[i] = number & UCHAR_MAX; - number >>= CHAR_BIT; + uint32_t result = 0; + uint8_t* p = reinterpret_cast(&result); + for(int i = 0; i < static_cast(sizeof(result)); ++i) { + p[i] = number & std::numeric_limits::max(); + number >>= std::numeric_limits::digits; } return result; } @@ -73,13 +78,16 @@ struct RexPaintTile { }; /* Read data from a gz file, returns 0 on success, or -1 on any error. */ static int load_gz_confirm(gzFile gz_file, void *data, size_t length) { - if (gzread(gz_file, data, (int)length) != length) { return -1; } + int length_ = static_cast(length); + if (gzread(gz_file, data, length_) != length_) { return -1; } return 0; } /* Loads a little-endian 32 bit signed int into memory. */ static int load_int32(gzFile gz_file, int32_t *out) { if (load_gz_confirm(gz_file, out, sizeof(out[0]))) { return -1; } - *out = (int32_t)decode_little_endian((uint32_t)(out[0])); + *out = static_cast( + decode_little_endian(static_cast(out[0])) + ); return 0; } static int load_header(gzFile gz_file, struct RexPaintHeader *xp_header) { @@ -99,7 +107,7 @@ static int load_tile(gzFile gz_file, struct RexPaintTile *tile) { /* Read a layer of REXPaint tiles onto a console. If transparent is true, then follow REXPaint's rules for transparency. */ static int load_tiles( - gzFile gz_file, TCOD_console_t console, int transparent) { + gzFile gz_file, TCOD_Console* console, int transparent) { int x, y; const int width = TCOD_console_get_width(console); const int height = TCOD_console_get_height(console); @@ -149,7 +157,8 @@ static TCOD_list_t load_consoleList(gzFile gz_file) { if (!console) { /* There was an issue then delete everything so far and return NULL */ while (!TCOD_list_is_empty(console_list)) { - TCOD_console_delete(TCOD_list_pop(console_list)); + TCOD_console_delete( + static_cast(TCOD_list_pop(console_list))); } TCOD_list_delete(console_list); return NULL; @@ -165,9 +174,10 @@ static TCOD_console_t combine_console_list(TCOD_list_t console_list) { if (!console_list) { return NULL; } /* Reverse the list so that elements will be dequeued. */ TCOD_list_reverse(console_list); - main_console = TCOD_list_pop(console_list); + main_console = static_cast(TCOD_list_pop(console_list)); while (!TCOD_list_is_empty(console_list)) { - TCOD_console_t console = TCOD_list_pop(console_list); + TCOD_console_t console = + static_cast(TCOD_list_pop(console_list)); /* Set key color to {255, 0, 255} before blit. */ TCOD_console_set_key_color(console, TCOD_fuchsia); /* This blit may fail if the consoles do not match shapes. */ @@ -238,7 +248,7 @@ bool TCOD_console_load_xp(TCOD_console_t con, const char *filename) { } /* Saves a 32-bit signed int encoded as little-endian to gz_file. */ static int write_int32(gzFile gz_file, int32_t number) { - uint32_t encoded = encode_little_endian((uint32_t)number); + uint32_t encoded = encode_little_endian(static_cast(number)); if (!gzwrite(gz_file, &encoded, sizeof(encoded))) { return -1; } @@ -260,7 +270,7 @@ static int write_tile(gzFile gz_file, struct RexPaintTile *tile) { } return 0; } -static int write_console(gzFile gz_file, TCOD_console_t console) { +static int write_console(gzFile gz_file, const TCOD_Console* console) { int x, y; struct RexPaintLayerChunk xp_layer; xp_layer.width = TCOD_console_get_width(console); @@ -295,7 +305,7 @@ static int write_console(gzFile gz_file, TCOD_console_t console) { * The REXPaint format can support a 1:1 copy of a libtcod console. */ bool TCOD_console_save_xp( - TCOD_console_t con, const char *filename, int compress_level) { + const TCOD_Console* con, const char *filename, int compress_level) { struct RexPaintHeader xp_header; gzFile gz_file = gzopen(filename, "wb"); if (!gz_file) { return false; /* could not open file */ } @@ -338,7 +348,8 @@ bool TCOD_console_list_save_xp( return false; /* error writing metadata */ } for (i = 0; i < xp_header.layer_count; ++i){ - if (write_console(gz_file, TCOD_list_get(console_list, i))) { + if (write_console( + gz_file, static_cast(TCOD_list_get(console_list, i)))) { gzclose(gz_file); return false; /* error writing out console data */ } diff --git a/tcod_sys/libtcod/src/libtcod/console/rexpaint.h b/tcod_sys/libtcod/src/libtcod/console/rexpaint.h new file mode 100644 index 000000000..cda87b904 --- /dev/null +++ b/tcod_sys/libtcod/src/libtcod/console/rexpaint.h @@ -0,0 +1,46 @@ +/* BSD 3-Clause License + * + * Copyright © 2008-2019, Jice and the libtcod contributors. + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions are met: + * + * 1. Redistributions of source code must retain the above copyright notice, + * this list of conditions and the following disclaimer. + * + * 2. Redistributions in binary form must reproduce the above copyright notice, + * this list of conditions and the following disclaimer in the documentation + * and/or other materials provided with the distribution. + * + * 3. Neither the name of the copyright holder nor the names of its + * contributors may be used to endorse or promote products derived from + * this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE + * POSSIBILITY OF SUCH DAMAGE. + */ +#ifndef TCOD_CONSOLE_REXPAINT_H_ +#define TCOD_CONSOLE_REXPAINT_H_ + +#include "../portability.h" +#include "../console_types.h" +#include "../list.h" +TCODLIB_CAPI TCOD_console_t TCOD_console_from_xp(const char *filename); +TCODLIB_CAPI bool TCOD_console_load_xp(TCOD_Console* con, + const char *filename); +TCODLIB_CAPI bool TCOD_console_save_xp( + const TCOD_Console* con, const char *filename, int compress_level); +TCODLIB_CAPI TCOD_list_t TCOD_console_list_from_xp(const char *filename); +TCODLIB_CAPI bool TCOD_console_list_save_xp( + TCOD_list_t console_list, const char *filename, int compress_level); +#endif /* TCOD_CONSOLE_REXPAINT_H_ */ diff --git a/tcod_sys/libtcod/src/libtcod/console_c.cpp b/tcod_sys/libtcod/src/libtcod/console_c.cpp index f4dd84d5e..a7b12515b 100644 --- a/tcod_sys/libtcod/src/libtcod/console_c.cpp +++ b/tcod_sys/libtcod/src/libtcod/console_c.cpp @@ -1,30 +1,34 @@ -/* -* libtcod -* Copyright (c) 2008-2018 Jice & Mingos & rmtew -* All rights reserved. -* -* Redistribution and use in source and binary forms, with or without -* modification, are permitted provided that the following conditions are met: -* * Redistributions of source code must retain the above copyright -* notice, this list of conditions and the following disclaimer. -* * Redistributions in binary form must reproduce the above copyright -* notice, this list of conditions and the following disclaimer in the -* documentation and/or other materials provided with the distribution. -* * The name of Jice or Mingos may not be used to endorse or promote -* products derived from this software without specific prior written -* permission. -* -* THIS SOFTWARE IS PROVIDED BY JICE, MINGOS AND RMTEW ``AS IS'' AND ANY -* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED -* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE -* DISCLAIMED. IN NO EVENT SHALL JICE, MINGOS OR RMTEW BE LIABLE FOR ANY -* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES -* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; -* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND -* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS -* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. -*/ +/* BSD 3-Clause License + * + * Copyright © 2008-2019, Jice and the libtcod contributors. + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions are met: + * + * 1. Redistributions of source code must retain the above copyright notice, + * this list of conditions and the following disclaimer. + * + * 2. Redistributions in binary form must reproduce the above copyright notice, + * this list of conditions and the following disclaimer in the documentation + * and/or other materials provided with the distribution. + * + * 3. Neither the name of the copyright holder nor the names of its + * contributors may be used to endorse or promote products derived from + * this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE + * POSSIBILITY OF SUCH DAMAGE. + */ #include "console.h" #include @@ -32,18 +36,18 @@ #include #include #include -#include +#include #include #include "console.hpp" -#include "console_rexpaint.h" #include "noise.h" #include "mersenne.h" #include "libtcod_int.h" #include "utility.h" #include "version.h" +#include "console/drawing.h" +#include "engine/error.h" #include "engine/globals.h" -#include "sdl2/sdl2_display.h" #include "tileset/tileset.h" #include "tileset/tilesheet.h" @@ -60,8 +64,9 @@ TCOD_internal_context_t TCOD_ctx={ 16,16, /* font type and layout */ false,false,false, - /* character size in font */ - 8,8, + 0, + /* character size in font */ + 0, 0, "terminal.png","", NULL,NULL,NULL,0,false,0,0,0,0,0,0, #ifndef TCOD_BARE @@ -80,63 +85,6 @@ TCOD_internal_context_t TCOD_ctx={ /* application active ? */ true, }; - -/** - * Codec for TCOD_FONT_LAYOUT_TCOD. - * - * Converts from EASCII code-point -> raw tile position. - */ -static constexpr std::array tcod_codec_{ - 0, 0, 0, 0, 0, 0, 0, 0, 0, 76, 77, 0, 0, 0, 0, 0, /* 0 to 15 */ - 71, 70, 72, 0, 0, 0, 0, 0, 64, 65, 67, 66, 0, 73, 68, 69, /* 16 to 31 */ - 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, /* 32 to 47 */ - 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, /* 48 to 63 */ - 32, 96, 97, 98, 99,100,101,102,103,104,105,106,107,108,109,110, /* 64 to 79 */ -111,112,113,114,115,116,117,118,119,120,121, 33, 34, 35, 36, 37, /* 80 to 95 */ - 38,128,129,130,131,132,133,134,135,136,137,138,139,140,141,142, /* 96 to 111 */ -143,144,145,146,147,148,149,150,151,152,153, 39, 40, 41, 42, 0, /* 112 to 127 */ - 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* 128 to 143 */ - 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* 144 to 159 */ - 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* 160 to 175 */ - 43, 44, 45, 46, 49, 0, 0, 0, 0, 81, 78, 87, 88, 0, 0, 55, /* 176 to 191 */ - 53, 50, 52, 51, 47, 48, 0, 0, 85, 86, 82, 84, 83, 79, 80, 0, /* 192 to 207 */ - 0, 0, 0, 0, 0, 0, 0, 0, 0, 56, 54, 0, 0, 0, 0, 0, /* 208 to 223 */ - 74, 75, 57, 58, 59, 60, 61, 62, 63, 0, 0, 0, 0, 0, 0, 0, /* 224 to 239 */ - 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* 240 to 255 */ -}; -/** - * Return a new console with a specific number of columns and rows. - * - * \param w Number of columns. - * \param h Number of columns. - * \return A pointer to the new console, or NULL on error. - */ -TCOD_console_t TCOD_console_new(int w, int h) { - TCOD_IFNOT(w > 0 && h > 0 ) { - return NULL; - } else { - struct TCOD_Console *con=(struct TCOD_Console *)calloc(sizeof(struct TCOD_Console),1); - if (!con) { return NULL; } - con->w=w; - con->h=h; - TCOD_console_init(con,NULL,false); /* NOTE: CHECK THIS FOR ERORS */ - if(TCOD_ctx.root) { - con->alignment=TCOD_ctx.root->alignment; - con->bkgnd_flag=TCOD_ctx.root->bkgnd_flag; - } - return (TCOD_console_t)con; - } -} -/** - * Return immediately with a recently pressed key. - * - * \param flags A TCOD_event_t bit-field, for example: `TCOD_EVENT_KEY_PRESS` - * \return A TCOD_key_t struct with a recently pressed key. - * If no event exists then the `vk` attribute will be `TCODK_NONE` - */ -TCOD_key_t TCOD_console_check_for_keypress(int flags) { - return TCOD_sys_check_for_keypress(flags); -} /** * Wait for a key press event, then return it. * @@ -150,703 +98,27 @@ TCOD_key_t TCOD_console_wait_for_keypress(bool flush) { return TCOD_sys_wait_for_keypress(flush); } /** - * Return true if the window is closing. - */ -bool TCOD_console_is_window_closed(void) { - return TCOD_ctx.is_window_closed; -} -/** - * Return true if the window has mouse focus. - */ -bool TCOD_console_has_mouse_focus(void) { - return TCOD_ctx.app_has_mouse_focus; -} -#ifndef TCOD_BARE -/** - * Return true if the window has keyboard focus. - * - * \verbatim embed:rst:leading-asterisk - * .. versionchanged: 1.7 - * This function was previously broken. It now keeps track of keyboard - * focus. - * \endverbatim - */ -bool TCOD_console_is_active(void) { - return TCOD_ctx.app_is_active; -} -#endif -/** - * Change the title string of the active window. - * - * \param title A utf8 string. - */ -void TCOD_console_set_window_title(const char *title) { - TCOD_sys_set_window_title(title); -} -/** - * Set the display to be full-screen or windowed. - * - * \param fullscreen If true the display will go full-screen. - */ -void TCOD_console_set_fullscreen(bool fullscreen) { - TCOD_IFNOT(TCOD_ctx.root != NULL) return; - TCOD_sys_set_fullscreen(fullscreen); - TCOD_ctx.fullscreen=fullscreen; -} -/** - * Return true if the display is full-screen. - */ -bool TCOD_console_is_fullscreen(void) { - return TCOD_ctx.fullscreen; -} -/** - * Set a consoles default background flag. - * - * \param con A console pointer. - * \param flag One of `TCOD_bkgnd_flag_t`. - */ -void TCOD_console_set_background_flag(TCOD_console_t con,TCOD_bkgnd_flag_t flag) { - struct TCOD_Console *dat=con ? (struct TCOD_Console *)con : TCOD_ctx.root; - TCOD_IFNOT ( dat != NULL ) return; - dat->bkgnd_flag=flag; -} -/** - * Return a consoles default background flag. - */ -TCOD_bkgnd_flag_t TCOD_console_get_background_flag(TCOD_console_t con) { - struct TCOD_Console *dat=con ? (struct TCOD_Console *)con : TCOD_ctx.root; - TCOD_IFNOT ( dat != NULL ) return TCOD_BKGND_NONE; - return dat->bkgnd_flag; -} -/** - * Set a consoles default alignment. - * - * \param con A console pointer. - * \param alignment One of TCOD_alignment_t - */ -void TCOD_console_set_alignment(TCOD_console_t con,TCOD_alignment_t alignment) { - struct TCOD_Console *dat=con ? (struct TCOD_Console *)con : TCOD_ctx.root; - TCOD_IFNOT ( dat != NULL ) return; - dat->alignment=alignment; -} -/** - * Return a consoles default alignment. - */ -TCOD_alignment_t TCOD_console_get_alignment(TCOD_console_t con) { - struct TCOD_Console *dat=con ? (struct TCOD_Console *)con : TCOD_ctx.root; - TCOD_IFNOT ( dat != NULL ) return TCOD_LEFT; - return dat->alignment; -} - -void TCOD_console_data_free(struct TCOD_Console *dat) -{ - if (!dat) { return; } - free(dat->ch_array); - free(dat->fg_array); - free(dat->bg_array); - dat->ch_array = NULL; - dat->fg_array = NULL; - dat->bg_array = NULL; -} -/** - * Delete a console. - * - * \param con A console pointer. + * Return immediately with a recently pressed key. * - * If the console being deleted is the root console, then the display will be - * uninitialized. - */ -void TCOD_console_delete(TCOD_console_t con) -{ - if (con) { - TCOD_console_data_free(con); - free(con); - } else { - TCOD_sys_shutdown(); - con=TCOD_ctx.root; - TCOD_ctx.root=NULL; - } -} -/** - * Shutdown libtcod. This must be called before your program exits. - * /rst - * .. versionadded:: 1.8 - * /endrst + * \param flags A TCOD_event_t bit-field, for example: `TCOD_EVENT_KEY_PRESS` + * \return A TCOD_key_t struct with a recently pressed key. + * If no event exists then the `vk` attribute will be `TCODK_NONE` */ -void TCOD_quit(void) -{ - TCOD_console_delete(NULL); -} - -void TCOD_console_blit_key_color( - TCOD_console_t srcCon, int xSrc, int ySrc, int wSrc, int hSrc, - TCOD_console_t dstCon, int xDst, int yDst, - float foreground_alpha, float background_alpha, TCOD_color_t *key_color) { - struct TCOD_Console *src = srcCon ? (struct TCOD_Console *)srcCon : TCOD_ctx.root; - struct TCOD_Console *dst = dstCon ? (struct TCOD_Console *)dstCon : TCOD_ctx.root; - TCOD_color_t *srcFgColors, *srcBgColors, *dstFgColors, *dstBgColors; - int cx, cy; - if (wSrc == 0) wSrc = src->w; - if (hSrc == 0) hSrc = src->h; - TCOD_IFNOT(wSrc > 0 && hSrc > 0) return; - TCOD_IFNOT(xDst + wSrc >= 0 && yDst + hSrc >= 0 && xDst < dst->w && yDst < dst->h) return; - srcFgColors = src->fg_array; - srcBgColors = src->bg_array; - dstFgColors = dst->fg_array; - dstBgColors = dst->bg_array; - for (cx = xSrc; cx < xSrc + wSrc; cx++) { - for (cy = ySrc; cy < ySrc + hSrc; cy++) { - /* check if we're outside the dest console */ - int dx = cx - xSrc + xDst; - int dy = cy - ySrc + yDst; - int dst_idx = dy * dst->w + dx; - int src_idx = cy * src->w + cx; - int srcChar, dstChar; - TCOD_color_t srcFgColor, srcBgColor, dstFgColor, dstBgColor; - if ((unsigned)cx >= (unsigned)src->w || (unsigned)cy >= (unsigned)src->h) continue; - if ((unsigned)dx >= (unsigned)dst->w || (unsigned)dy >= (unsigned)dst->h) continue; - srcChar = src->ch_array[src_idx]; - srcFgColor = srcFgColors[src_idx]; - srcBgColor = srcBgColors[src_idx]; - /* check if source pixel is transparent */ - if (key_color && - srcBgColor.r == key_color->r && - srcBgColor.g == key_color->g && - srcBgColor.b == key_color->b) { continue; } - - if (foreground_alpha == 1.0f && background_alpha == 1.0f) { - dstChar = srcChar; - dstFgColor = srcFgColor; - dstBgColor = srcBgColor; - } - else { - dstChar = dst->ch_array[dst_idx]; - dstFgColor = dstFgColors[dst_idx]; - dstBgColor = dstBgColors[dst_idx]; - - dstBgColor = TCOD_color_lerp(dstBgColor, srcBgColor, background_alpha); - if (srcChar == ' ') { - dstFgColor = TCOD_color_lerp(dstFgColor, srcBgColor, background_alpha); - } - else if (dstChar == ' ') { - dstChar = srcChar; - dstFgColor = TCOD_color_lerp(dstBgColor, srcFgColor, foreground_alpha); - } - else if (dstChar == srcChar) { - dstFgColor = TCOD_color_lerp(dstFgColor, srcFgColor, foreground_alpha); - } - else { - if (foreground_alpha < 0.5f) { - dstFgColor = TCOD_color_lerp(dstFgColor, dstBgColor, - foreground_alpha * 2); - } - else { - dstChar = srcChar; - dstFgColor = TCOD_color_lerp(dstBgColor, srcFgColor, - (foreground_alpha - 0.5f) * 2); - } - } - } - dstFgColors[dst_idx] = dstFgColor; - dstBgColors[dst_idx] = dstBgColor; - dst->ch_array[dst_idx] = dstChar; - } - } +TCOD_key_t TCOD_console_check_for_keypress(int flags) { + return TCOD_sys_check_for_keypress(flags); } -/** - * Blit from one console to another. - * - * \param srcCon Pointer to the source console. - * \param xSrc The left region of the source console to blit from. - * \param ySrc The top region of the source console to blit from. - * \param wSrc The width of the region to blit from. - * If 0 then it will fill to the maximum width. - * \param hSrc The height of the region to blit from. - * If 0 then it will fill to the maximum height. - * \param dstCon Pointer to the destination console. - * \param xDst The left corner to blit onto the destination console. - * \param yDst The top corner to blit onto the destination console. - * \param foreground_alpha Foreground blending alpha. - * \param background_alpha Background blending alpha. - * - * If the source console has a key color, this function will use it. - */ -void TCOD_console_blit( - TCOD_console_t srcCon, int xSrc, int ySrc, int wSrc, int hSrc, - TCOD_console_t dstCon, int xDst, int yDst, - float foreground_alpha, float background_alpha) { - struct TCOD_Console *src = srcCon ? (struct TCOD_Console *)srcCon : TCOD_ctx.root; - TCOD_console_blit_key_color( - srcCon, xSrc, ySrc, wSrc, hSrc, dstCon, xDst, yDst, - foreground_alpha, background_alpha, - (src->has_key_color ? &src->key_color : NULL) - ); - } /** * Render and present the root console to the active display. */ void TCOD_console_flush(void) { TCOD_sys_flush(true); } -/** - * Fade the color of the display. - * - * \param val Where at 255 colors are normal and at 0 colors are completely - * faded. - * \param fadecol Color to fade towards. - */ -void TCOD_console_set_fade(uint8_t val, TCOD_color_t fadecol) { - TCOD_ctx.fade=val; - TCOD_ctx.fading_color=fadecol; -} -/** - * Return the fade value. - * - * \return At 255 colors are normal and at 0 colors are completely faded. - */ -uint8_t TCOD_console_get_fade(void) { - return TCOD_ctx.fade; -} -/** - * Return the fade color. - * - * \return The current fading color. - */ -TCOD_color_t TCOD_console_get_fading_color(void) { - return TCOD_ctx.fading_color; -} -/** - * Draw a character on a console using the default colors. - * - * \param con A console pointer. - * \param x The X coordinate, the left-most position being 0. - * \param y The Y coordinate, the top-most position being 0. - * \param c The character code to place. - * \param flag A TCOD_bkgnd_flag_t flag. - */ -void TCOD_console_put_char(TCOD_console_t con, int x, int y, int c, TCOD_bkgnd_flag_t flag) { - int offset; - struct TCOD_Console *dat = con ? (struct TCOD_Console *)con : TCOD_ctx.root; - TCOD_IFNOT(dat != NULL && (unsigned)(x) < (unsigned)dat->w && (unsigned)(y) < (unsigned)dat->h) return; - offset = y * dat->w + x; - dat->ch_array[offset] = c; - TCOD_console_set_char_foreground(dat, x, y, dat->fore); - TCOD_console_set_char_background(con, x, y, dat->back, (TCOD_bkgnd_flag_t)flag); -} -/** - * Draw a character on the console with the given colors. - * - * \param con A console pointer. - * \param x The X coordinate, the left-most position being 0. - * \param y The Y coordinate, the top-most position being 0. - * \param c The character code to place. - * \param fore The foreground color. - * \param back The background color. This color will not be blended. - */ -void TCOD_console_put_char_ex(TCOD_console_t con, int x, int y, int c, TCOD_color_t fore, TCOD_color_t back) { - int offset; - struct TCOD_Console *dat = con ? (struct TCOD_Console *)con : TCOD_ctx.root; - TCOD_IFNOT(dat != NULL && (unsigned)(x) < (unsigned)dat->w && (unsigned)(y) < (unsigned)dat->h) return; - offset = y * dat->w + x; - dat->ch_array[offset] = c; - TCOD_console_set_char_foreground(dat, x, y, fore); - TCOD_console_set_char_background(dat, x, y, back, TCOD_BKGND_SET); -} /** * Manually mark a region of a console as dirty. */ void TCOD_console_set_dirty(int dx, int dy, int dw, int dh) { TCOD_sys_set_dirty(dx, dy, dw, dh); } -/** - * Clear a console to its default colors and the space character code. - */ -void TCOD_console_clear(TCOD_console_t con) { - int i; - struct TCOD_Console *dat = con ? (struct TCOD_Console *)con : TCOD_ctx.root; - TCOD_IFNOT(dat != NULL) return; - for (i = 0; i < dat->w * dat->h; i++) { - dat->ch_array[i] = ' '; - dat->fg_array[i] = dat->fore; - dat->bg_array[i] = dat->back; - } - /* clear the sdl renderer cache */ - TCOD_sys_set_dirty(0, 0, dat->w, dat->h); -} -/** - * Return the background color of a console at x,y - * - * \param con A console pointer. - * \param x The X coordinate, the left-most position being 0. - * \param y The Y coordinate, the top-most position being 0. - * \return A TCOD_color_t struct with a copy of the background color. - */ -TCOD_color_t TCOD_console_get_char_background(TCOD_console_t con, int x, int y) { - struct TCOD_Console *dat = con ? (struct TCOD_Console *)con : TCOD_ctx.root; - TCOD_IFNOT(dat != NULL - && (unsigned)(x) < (unsigned)dat->w && (unsigned)(y) < (unsigned)dat->h) - return TCOD_black; - return dat->bg_array[y * dat->w + x]; -} -/** - * Change the foreground color of a console tile. - * - * \param con A console pointer. - * \param x The X coordinate, the left-most position being 0. - * \param y The Y coordinate, the top-most position being 0. - * \param col The foreground color to set. - */ -void TCOD_console_set_char_foreground(TCOD_console_t con, int x, int y, TCOD_color_t col) { - struct TCOD_Console *dat = con ? (struct TCOD_Console *)con : TCOD_ctx.root; - if ((unsigned)(x) >= (unsigned)dat->w || (unsigned)(y) >= (unsigned)dat->h) return; - TCOD_IFNOT(dat != NULL - && (unsigned)(x) < (unsigned)dat->w && (unsigned)(y) < (unsigned)dat->h) - return; - dat->fg_array[y * dat->w + x] = col; -} -/** - * Return the foreground color of a console at x,y - * - * \param con A console pointer. - * \param x The X coordinate, the left-most position being 0. - * \param y The Y coordinate, the top-most position being 0. - * \return A TCOD_color_t struct with a copy of the foreground color. - */ -TCOD_color_t TCOD_console_get_char_foreground(TCOD_console_t con, int x, int y) { - struct TCOD_Console *dat = con ? (struct TCOD_Console *)con : TCOD_ctx.root; - TCOD_IFNOT(dat != NULL - && (unsigned)(x) < (unsigned)dat->w && (unsigned)(y) < (unsigned)dat->h) - return TCOD_white; - return dat->fg_array[y * dat->w + x]; -} -/** - * Return a character code of a console at x,y - * - * \param con A console pointer. - * \param x The X coordinate, the left-most position being 0. - * \param y The Y coordinate, the top-most position being 0. - * \return The character code. - */ -int TCOD_console_get_char(TCOD_console_t con, int x, int y) { - struct TCOD_Console *dat = con ? (struct TCOD_Console *)con : TCOD_ctx.root; - TCOD_IFNOT(dat != NULL - && (unsigned)(x) < (unsigned)dat->w && (unsigned)(y) < (unsigned)dat->h) - return 0; - return dat->ch_array[y * dat->w + x]; -} -/** - * Blend a background color onto a console tile. - * - * \param con A console pointer. - * \param x The X coordinate, the left-most position being 0. - * \param y The Y coordinate, the top-most position being 0. - * \param col The background color to blend. - * \param flag The blend mode to use. - */ -void TCOD_console_set_char_background(TCOD_console_t con, int x, int y, TCOD_color_t col, TCOD_bkgnd_flag_t flag) { - TCOD_color_t *back; - int newr, newg, newb; - int alpha; - struct TCOD_Console *dat = con ? (struct TCOD_Console *)con : TCOD_ctx.root; - TCOD_IFNOT(dat != NULL - && (unsigned)(x) < (unsigned)dat->w && (unsigned)(y) < (unsigned)dat->h) - return; - back = &(dat->bg_array[y*dat->w + x]); - if (flag == TCOD_BKGND_DEFAULT) flag = dat->bkgnd_flag; - switch (flag & 0xff) { - case TCOD_BKGND_SET: *back = col; break; - case TCOD_BKGND_MULTIPLY: *back = TCOD_color_multiply(*back, col); break; - case TCOD_BKGND_LIGHTEN: - back->r = MAX(back->r, col.r); - back->g = MAX(back->g, col.g); - back->b = MAX(back->b, col.b); - break; - case TCOD_BKGND_DARKEN: - back->r = MIN(back->r, col.r); - back->g = MIN(back->g, col.g); - back->b = MIN(back->b, col.b); - break; - case TCOD_BKGND_SCREEN: - /* newbk = white - (white - oldbk) * (white - curbk) */ - back->r = (uint8_t)(255 - (int)(255 - back->r)*(255 - col.r) / 255); - back->g = (uint8_t)(255 - (int)(255 - back->g)*(255 - col.g) / 255); - back->b = (uint8_t)(255 - (int)(255 - back->b)*(255 - col.b) / 255); - break; - case TCOD_BKGND_COLOR_DODGE: - /* newbk = curbk / (white - oldbk) */ - if (back->r != 255) newr = (int)(255 * col.r) / (255 - back->r); - else newr = 255; - if (back->g != 255) newg = (int)(255 * col.g) / (255 - back->g); - else newg = 255; - if (back->b != 255) newb = (int)(255 * col.b) / (255 - back->b); - else newb = 255; - back->r = (uint8_t)CLAMP(0, 255, newr); - back->g = (uint8_t)CLAMP(0, 255, newg); - back->b = (uint8_t)CLAMP(0, 255, newb); - break; - case TCOD_BKGND_COLOR_BURN: - /* newbk = white - (white - oldbk) / curbk */ - if (col.r > 0) newr = 255 - (int)(255 * (255 - back->r)) / col.r; - else newr = 0; - if (col.g > 0) newg = 255 - (int)(255 * (255 - back->g)) / col.g; - else newg = 0; - if (col.b > 0) newb = 255 - (int)(255 * (255 - back->b)) / col.b; - else newb = 0; - back->r = (uint8_t)CLAMP(0, 255, newr); - back->g = (uint8_t)CLAMP(0, 255, newg); - back->b = (uint8_t)CLAMP(0, 255, newb); - break; - case TCOD_BKGND_ADD: - /* newbk = oldbk + curbk */ - newr = (int)(back->r) + col.r; - newg = (int)(back->g) + col.g; - newb = (int)(back->b) + col.b; - back->r = (uint8_t)CLAMP(0, 255, newr); - back->g = (uint8_t)CLAMP(0, 255, newg); - back->b = (uint8_t)CLAMP(0, 255, newb); - break; - case TCOD_BKGND_ADDA: - alpha = (flag >> 8); - /* newbk = oldbk + alpha * curbk */ - newr = (int)(back->r) + alpha * col.r / 255; - newg = (int)(back->g) + alpha * col.g / 255; - newb = (int)(back->b) + alpha * col.b / 255; - back->r = (uint8_t)CLAMP(0, 255, newr); - back->g = (uint8_t)CLAMP(0, 255, newg); - back->b = (uint8_t)CLAMP(0, 255, newb); - break; - case TCOD_BKGND_BURN: - /* newbk = oldbk + curbk - white */ - newr = (int)(back->r) + col.r - 255; - newg = (int)(back->g) + col.g - 255; - newb = (int)(back->b) + col.b - 255; - back->r = (uint8_t)CLAMP(0, 255, newr); - back->g = (uint8_t)CLAMP(0, 255, newg); - back->b = (uint8_t)CLAMP(0, 255, newb); - break; - case TCOD_BKGND_OVERLAY: - /* newbk = curbk.x <= 0.5 ? 2*curbk*oldbk : white - 2*(white-curbk)*(white-oldbk) */ - newr = col.r <= 128 ? 2 * (int)(col.r) * back->r / 255 : 255 - 2 * (int)(255 - col.r)*(255 - back->r) / 255; - newg = col.g <= 128 ? 2 * (int)(col.g) * back->g / 255 : 255 - 2 * (int)(255 - col.g)*(255 - back->g) / 255; - newb = col.b <= 128 ? 2 * (int)(col.b) * back->b / 255 : 255 - 2 * (int)(255 - col.b)*(255 - back->b) / 255; - back->r = (uint8_t)CLAMP(0, 255, newr); - back->g = (uint8_t)CLAMP(0, 255, newg); - back->b = (uint8_t)CLAMP(0, 255, newb); - break; - case TCOD_BKGND_ALPH: - /* newbk = (1.0f-alpha)*oldbk + alpha*(curbk-oldbk) */ - alpha = (flag >> 8); - *back = TCOD_color_lerp(*back, col, (float)(alpha / 255.0f)); - break; - default: break; - } -} -/** - * Change a character on a console tile, without changing its colors. - * - * \param con A console pointer. - * \param x The X coordinate, the left-most position being 0. - * \param y The Y coordinate, the top-most position being 0. - * \param c The character code to set. - */ -void TCOD_console_set_char(TCOD_console_t con, int x, int y, int c) { - struct TCOD_Console *dat = con ? (struct TCOD_Console *)con : TCOD_ctx.root; - if ((unsigned)(x) >= (unsigned)dat->w || (unsigned)(y) >= (unsigned)dat->h) return; - dat->ch_array[y * dat->w + x] = c; -} - -static void TCOD_console_clamp(int cx, int cy, int cw, int ch, int *x, int *y, int *w, int *h) { - if (*x + *w > cw) *w = cw - *x; - if (*y + *h > ch) *h = ch - *y; - if (*x < cx) { - *w -= cx - *x; - *x = cx; - } - if (*y < cy) { - *h -= cy - *y; - *y = cy; - } -} -/** - * Draw a rectangle onto a console. - * - * \param con A console pointer. - * \param x The starting region, the left-most position being 0. - * \param y The starting region, the top-most position being 0. - * \param rw The width of the rectangle. - * \param rh The height of the rectangle. - * \param clear If true the drawing region will be filled with spaces. - * \param flag The blending flag to use. - */ -void TCOD_console_rect(TCOD_console_t con, int x, int y, int rw, int rh, bool clear, TCOD_bkgnd_flag_t flag) { - int cx, cy; - struct TCOD_Console *dat = con ? (struct TCOD_Console *)con : TCOD_ctx.root; - TCOD_IFNOT(dat != NULL) return; - TCOD_ASSERT((unsigned)(x) < (unsigned)dat->w && (unsigned)(y) < (unsigned)dat->h); - TCOD_ASSERT(x + rw <= dat->w && y + rh <= dat->h); - - TCOD_console_clamp(0, 0, dat->w, dat->h, &x, &y, &rw, &rh); - TCOD_IFNOT(rw > 0 && rh > 0) return; - for (cx = x; cx < x + rw; cx++) { - for (cy = y; cyback, flag); - if (clear) { - dat->ch_array[cx + cy*dat->w] = ' '; - } - } - } -} -/** - * Draw a horizontal line using the default colors. - * - * \param con A console pointer. - * \param x The starting X coordinate, the left-most position being 0. - * \param y The starting Y coordinate, the top-most position being 0. - * \param l The width of the line. - * \param flag The blending flag. - * - * This function makes assumptions about the fonts character encoding. - * It will fail if the font encoding is not `cp437`. - */ -void TCOD_console_hline(TCOD_console_t con,int x,int y, int l, TCOD_bkgnd_flag_t flag) { - int i; - for (i=x; i< x+l; i++) TCOD_console_put_char(con,i,y,TCOD_CHAR_HLINE,flag); -} -/** - * Draw a vertical line using the default colors. - * - * \param con A console pointer. - * \param x The starting X coordinate, the left-most position being 0. - * \param y The starting Y coordinate, the top-most position being 0. - * \param l The height of the line. - * \param flag The blending flag. - * - * This function makes assumptions about the fonts character encoding. - * It will fail if the font encoding is not `cp437`. - */ -void TCOD_console_vline(TCOD_console_t con,int x,int y, int l, TCOD_bkgnd_flag_t flag) { - int i; - for (i=y; i< y+l; i++) TCOD_console_put_char(con,x,i,TCOD_CHAR_VLINE,flag); -} -/** - * \brief Initialize the libtcod graphical engine. - * - * \param w The width in tiles. - * \param h The height in tiles. - * \param title The title for the window. - * \param fullscreen Fullscreen option. - * \param renderer Which renderer to use when rendering the console. - * - * You may want to call TCOD_console_set_custom_font BEFORE calling this - * function. By default this function loads libtcod's `terminal.png` image - * from the working directory. - * - * Afterwards TCOD_quit must be called before the program exits. - */ -void TCOD_console_init_root(int w, int h, const char* title, bool fullscreen, - TCOD_renderer_t renderer) -{ - TCOD_IF(w > 0 && h > 0) { - TCOD_console_delete(NULL); - TCODConsole::root->data = TCOD_ctx.root = TCOD_console_new(w, h); -#ifndef TCOD_BARE - TCOD_ctx.renderer=renderer; -#endif - strncpy(TCOD_ctx.window_title, title, sizeof(TCOD_ctx.window_title) - 1); - TCOD_ctx.fullscreen = fullscreen; - switch (renderer) { - case TCOD_RENDERER_SDL2: { - auto tileset = tcod::engine::get_tileset(); - if (!tileset) { throw; } - auto display = std::make_shared( - tileset, - std::make_pair(tileset->get_tile_width() * w, - tileset->get_tile_height() * h), - (SDL_WINDOW_RESIZABLE | - (fullscreen ? SDL_WINDOW_FULLSCREEN_DESKTOP : 0)), - std::string(title)); - tcod::engine::set_display(display); - break; - } - default: - TCOD_console_init(TCOD_ctx.root, TCOD_ctx.window_title, - TCOD_ctx.fullscreen); - break; - } - } -} - -static void TCOD_console_data_alloc(struct TCOD_Console *dat) { - if (!dat->ch_array) { - dat->ch_array = static_cast( - calloc(sizeof(int), dat->w * dat->h)); - } - if (!dat->fg_array) { - dat->fg_array = static_cast( - calloc(sizeof(TCOD_color_t), dat->w * dat->h)); - } - if (!dat->bg_array) { - dat->bg_array = static_cast( - calloc(sizeof(TCOD_color_t), dat->w * dat->h)); - } -} - -bool TCOD_console_init(TCOD_console_t con,const char *title, bool fullscreen) { - int i; - struct TCOD_Console *dat=con ? (struct TCOD_Console *)con : TCOD_ctx.root; - TCOD_IFNOT(dat != NULL) return false; - dat->fore=TCOD_white; - dat->back=TCOD_black; - - TCOD_console_data_alloc(dat); - - dat->bkgnd_flag=TCOD_BKGND_NONE; - dat->alignment=TCOD_LEFT; - for (i=0; i< dat->w*dat->h; i++) { - dat->ch_array[i] = ' '; - } - if ( title ) { - if (! TCOD_sys_init(dat, fullscreen) ) return false; - TCOD_sys_set_window_title(title); - } - return true; -} - -void TCOD_console_set_default_foreground(TCOD_console_t con,TCOD_color_t col) { - struct TCOD_Console *dat=con ? (struct TCOD_Console *)con : TCOD_ctx.root; - TCOD_IFNOT(dat != NULL) return; - dat->fore=col; -} - -void TCOD_console_set_default_background(TCOD_console_t con,TCOD_color_t col) { - struct TCOD_Console *dat=con ? (struct TCOD_Console *)con : TCOD_ctx.root; - TCOD_IFNOT(dat != NULL) return; - dat->back=col; -} - -TCOD_color_t TCOD_console_get_default_foreground(TCOD_console_t con) { - struct TCOD_Console *dat=con ? (struct TCOD_Console *)con : TCOD_ctx.root; - TCOD_IFNOT(dat != NULL) return TCOD_white; - return dat->fore; -} - -TCOD_color_t TCOD_console_get_default_background(TCOD_console_t con) { - struct TCOD_Console *dat=con ? (struct TCOD_Console *)con : TCOD_ctx.root; - TCOD_IFNOT(dat != NULL) return TCOD_black; - return dat->back; -} - -int TCOD_console_get_width(TCOD_console_t con) { - struct TCOD_Console *dat=con ? (struct TCOD_Console *)con : TCOD_ctx.root; - TCOD_IFNOT(dat != NULL) return 0; - return dat->w; -} - -int TCOD_console_get_height(TCOD_console_t con) { - struct TCOD_Console *dat=con ? (struct TCOD_Console *)con : TCOD_ctx.root; - TCOD_IFNOT(dat != NULL) return 0; - return dat->h; -} /** * \brief Set a font image to be loaded during initialization. * @@ -857,9 +129,19 @@ int TCOD_console_get_height(TCOD_console_t con) { * \param nb_char_vertic The number of rows in the font image. * * `fontFile` will be case-sensitive depending on the platform. + * + * Returns 0 on success, or -1 on an error, you can check the error with + * TCOD_sys_get_error() + * \rst + * .. versionchanged:: 1.12 + * Now returns -1 on error instead of crashing. + * \endrst */ -void TCOD_console_set_custom_font(const char *fontFile, int flags, - int nb_char_horiz, int nb_char_vertic) +int TCOD_console_set_custom_font( + const char *fontFile, + int flags, + int nb_char_horiz, + int nb_char_vertic) { strcpy(TCOD_ctx.font_file, fontFile); /* if layout not defined, assume ASCII_INCOL */ @@ -868,18 +150,19 @@ void TCOD_console_set_custom_font(const char *fontFile, int flags, flags |= TCOD_FONT_LAYOUT_ASCII_INCOL; } TCOD_ctx.font_in_row = ((flags & TCOD_FONT_LAYOUT_ASCII_INROW) != 0); - TCOD_ctx.font_greyscale = ((flags & TCOD_FONT_TYPE_GREYSCALE) != 0 ); - TCOD_ctx.font_tcod_layout = ((flags & TCOD_FONT_LAYOUT_TCOD) != 0 ); - if (nb_char_horiz > 0) { + TCOD_ctx.font_greyscale = ((flags & TCOD_FONT_TYPE_GREYSCALE) != 0); + TCOD_ctx.font_tcod_layout = ((flags & TCOD_FONT_LAYOUT_TCOD) != 0); + TCOD_ctx.font_flags = flags; + if (nb_char_horiz > 0 && nb_char_vertic > 0) { TCOD_ctx.fontNbCharHoriz = nb_char_horiz; TCOD_ctx.fontNbCharVertic = nb_char_vertic; } else { - if ( ( flags & TCOD_FONT_LAYOUT_ASCII_INROW ) || ( flags & TCOD_FONT_LAYOUT_ASCII_INCOL ) ) { - TCOD_ctx.fontNbCharHoriz = nb_char_horiz = 16; - TCOD_ctx.fontNbCharVertic = nb_char_vertic = 16; - } else { + if (flags & TCOD_FONT_LAYOUT_TCOD) { TCOD_ctx.fontNbCharHoriz = nb_char_horiz = 32; TCOD_ctx.fontNbCharVertic = nb_char_vertic = 8; + } else { + TCOD_ctx.fontNbCharHoriz = nb_char_horiz = 16; + TCOD_ctx.fontNbCharVertic = nb_char_vertic = 16; } } if (TCOD_ctx.font_tcod_layout) { TCOD_ctx.font_in_row = true; } @@ -898,28 +181,11 @@ void TCOD_console_set_custom_font(const char *fontFile, int flags, auto tileset = std::make_shared(tilesheet->get_tile_width(), tilesheet->get_tile_height()); tcod::engine::set_tileset(tileset); - if (flags & TCOD_FONT_LAYOUT_TCOD) { - for (int i = 0; i < static_cast(tcod_codec_.size()); ++i) { - tileset->set_tile(i, tilesheet->get_tile(tcod_codec_.at(i))); - } - } else if (flags & TCOD_FONT_LAYOUT_ASCII_INROW) { - for (int i = 0; i < tilesheet->count(); ++i) { - tileset->set_tile(i, tilesheet->get_tile(i)); - } - } else if (flags & TCOD_FONT_LAYOUT_ASCII_INCOL) { - for (int x = 0; x < tilesheet->get_columns(); ++x) { - for (int y = 0; y < tilesheet->get_rows(); ++y) { - int i = x * tilesheet->get_rows() + y; - tileset->set_tile(i, tilesheet->get_tile(x, y)); - } - } - } - } catch (const std::runtime_error&) { - // Ignore any runtime error, will likely catch a missing file error. - return; - } catch (const std::logic_error&) { - return; // Ignore logic errors from constructing objects. + } catch (const std::exception& e) { + return tcod::set_error(e); } + TCOD_sys_decode_font_(); + return 0; } /** * \brief Remap a character code to a tile. @@ -930,10 +196,12 @@ void TCOD_console_set_custom_font(const char *fontFile, int flags, * * X,Y parameters are the coordinate of the tile, not pixel-coordinates. */ -void TCOD_console_map_ascii_code_to_font(int asciiCode, int fontCharX, int fontCharY) { - /* cannot change mapping before initRoot is called */ - TCOD_IFNOT(TCOD_ctx.root != NULL) return; - TCOD_sys_map_ascii_to_font(asciiCode, fontCharX, fontCharY); +void TCOD_console_map_ascii_code_to_font(int asciiCode, + int fontCharX, int fontCharY) +{ + /* cannot change mapping before initRoot is called */ + TCOD_IFNOT(TCOD_ctx.root) { return; } + TCOD_sys_map_ascii_to_font(asciiCode, fontCharX, fontCharY); } /** * \brief Remap a series of character codes to a row of tiles. @@ -946,19 +214,22 @@ void TCOD_console_map_ascii_code_to_font(int asciiCode, int fontCharX, int fontC * This function always assigns tiles in row-major order, even if the * TCOD_FONT_LAYOUT_ASCII_INCOL flag was set. */ -void TCOD_console_map_ascii_codes_to_font(int asciiCode, int nbCodes, int fontCharX, int fontCharY) { - int c; - /* cannot change mapping before initRoot is called */ - TCOD_IFNOT(TCOD_ctx.root != NULL) return; - TCOD_IFNOT(asciiCode >= 0 && asciiCode+nbCodes <= TCOD_ctx.max_font_chars) return; - for (c=asciiCode; c < asciiCode+nbCodes; c++ ) { - TCOD_sys_map_ascii_to_font(c, fontCharX, fontCharY); - fontCharX++; - if ( fontCharX == TCOD_ctx.fontNbCharHoriz ) { - fontCharX=0; - fontCharY++; - } - } +void TCOD_console_map_ascii_codes_to_font(int asciiCode, int nbCodes, + int fontCharX, int fontCharY) +{ + /* cannot change mapping before initRoot is called */ + TCOD_IFNOT(TCOD_ctx.root) { return; } + TCOD_IFNOT(asciiCode >= 0 && asciiCode+nbCodes <= TCOD_ctx.max_font_chars) { + return; + } + for (int c = asciiCode; c < asciiCode + nbCodes; ++c) { + TCOD_sys_map_ascii_to_font(c, fontCharX, fontCharY); + ++fontCharX; + if (fontCharX == TCOD_ctx.fontNbCharHoriz) { + fontCharX = 0; + ++fontCharY; + } + } } /** * \brief Remap a string of character codes to a row of tiles. @@ -970,29 +241,31 @@ void TCOD_console_map_ascii_codes_to_font(int asciiCode, int nbCodes, int fontCh * This function always assigns tiles in row-major order, even if the * TCOD_FONT_LAYOUT_ASCII_INCOL flag was set. */ -void TCOD_console_map_string_to_font(const char *s, int fontCharX, int fontCharY) { - TCOD_IFNOT(s != NULL) return; - /* cannot change mapping before initRoot is called */ - TCOD_IFNOT(TCOD_ctx.root != NULL) return; - while (*s) { - TCOD_console_map_ascii_code_to_font(*s, fontCharX, fontCharY); - fontCharX++; - if ( fontCharX == TCOD_ctx.fontNbCharHoriz ) { - fontCharX=0; - fontCharY++; - } - s++; - } +void TCOD_console_map_string_to_font(const char *s, + int fontCharX, int fontCharY) +{ + TCOD_IFNOT(s) { return; } + /* cannot change mapping before initRoot is called */ + TCOD_IFNOT(TCOD_ctx.root) { return; } + while (*s) { + TCOD_console_map_ascii_code_to_font(*s, fontCharX, fontCharY); + ++fontCharX; + if (fontCharX == TCOD_ctx.fontNbCharHoriz) { + fontCharX = 0; + ++fontCharY; + } + ++s; + } } bool TCOD_console_is_key_pressed(TCOD_keycode_t key) { return TCOD_sys_is_key_pressed(key); } -void TCOD_console_set_key_color(TCOD_console_t con,TCOD_color_t col) { - struct TCOD_Console *dat=con ? (struct TCOD_Console *)con : TCOD_ctx.root; - if (!dat) { return; } - dat->has_key_color = 1; - dat->key_color = col; +void TCOD_console_set_key_color(TCOD_Console* con,TCOD_color_t col) { + con = TCOD_console_validate_(con); + if (!con) { return; } + con->has_key_color = 1; + con->key_color = col; } void TCOD_console_credits(void) { @@ -1072,7 +345,7 @@ bool TCOD_console_credits_render(int x, int y, bool alpha) { TCOD_color_gen_map(colmap_light,4,colkeys_light,colpos); sprintf(poweredby,"Powered by\n%s",version_string); noise=TCOD_noise_new(1,TCOD_NOISE_DEFAULT_HURST,TCOD_NOISE_DEFAULT_LACUNARITY,NULL); - len=(int)strlen(poweredby); + len=static_cast(strlen(poweredby)); len1=11; /* sizeof "Powered by\n" */ left=MAX(x-4,0); top=MAX(y-4,0); @@ -1113,18 +386,18 @@ bool TCOD_console_credits_render(int x, int y, bool alpha) { img = TCOD_image_new(width*2,height*2); } fbackup=TCOD_console_get_default_foreground(NULL); - if ( xstr < (float)len1 ) { + if ( xstr < len1 ) { sparklex=x+xstr; - sparkley=(float)y; + sparkley=y; } else { sparklex=x-len1+xstr; - sparkley=(float)y+1; + sparkley=y+1; } noisex=xstr*6; sparklerad=3.0f+2*TCOD_noise_get(noise,&noisex); if ( xstr >= len-1 ) sparklerad -= (xstr-len+1)*4.0f; else if ( xstr < 0.0f ) sparklerad += xstr*4.0f; - else if ( poweredby[ (int)(xstr+0.5f) ] == ' ' || poweredby[ (int)(xstr+0.5f) ] == '\n' ) sparklerad/=2; + else if ( poweredby[ static_cast(xstr+0.5f) ] == ' ' || poweredby[ static_cast(xstr+0.5f) ] == '\n' ) sparklerad/=2; sparklerad2=sparklerad*sparklerad*4; /* draw the light */ @@ -1133,7 +406,7 @@ bool TCOD_console_credits_render(int x, int y, bool alpha) { float dist=((xc-2*sparklex)*(xc-2*sparklex)+(yc-2*sparkley)*(yc-2*sparkley)); TCOD_color_t pixcol; if ( sparklerad >= 0.0f && dist < sparklerad2 ) { - int colidx=63-(int)(63*(sparklerad2-dist)/sparklerad2) + TCOD_random_get_int(NULL,-10,10); + int colidx=63-static_cast(63*(sparklerad2-dist)/sparklerad2) + TCOD_random_get_int(NULL,-10,10); colidx=CLAMP(0,63,colidx); pixcol=colmap_light[colidx]; } else { @@ -1169,9 +442,9 @@ bool TCOD_console_credits_render(int x, int y, bool alpha) { bk = TCOD_console_get_char_foreground(NULL,xc/2,yc/2); } } - pixcol.r = MIN(255,(int)(bk.r)+pixcol.r); - pixcol.g = MIN(255,(int)(bk.g)+pixcol.g); - pixcol.b = MIN(255,(int)(bk.b)+pixcol.b); + pixcol.r = std::min(255, bk.r + pixcol.r); + pixcol.g = std::min(255, bk.g + pixcol.g); + pixcol.b = std::min(255, bk.b + pixcol.b); } TCOD_image_put_pixel(img,xi,yi,pixcol); } @@ -1180,13 +453,13 @@ bool TCOD_console_credits_render(int x, int y, bool alpha) { /* draw and update the particules */ j=nbpart;i=firstpart; while (j > 0) { - int colidx=(int)(64*(1.0f-pheat[i])); + int colidx = static_cast(64 * (1.0f - pheat[i])); TCOD_color_t col; - colidx=MIN(63,colidx); + colidx=std::min(63, colidx); col=colmap[colidx]; - if ( (int)py[i]< (bottom-top+1)*2 ) { - int ipx = (int)px[i]; - int ipy = (int)py[i]; + if (py[i] < (bottom - top + 1) * 2) { + int ipx = static_cast(px[i]); + int ipy = static_cast(py[i]); float fpx = px[i]-ipx; float fpy = py[i]-ipy; TCOD_color_t col2=TCOD_image_get_pixel(img,ipx,ipy); @@ -1232,7 +505,7 @@ bool TCOD_console_credits_render(int x, int y, bool alpha) { /* draw the text */ for (i=0; i < len ;i++) { if ( char_heat[i] >= 0.0f && poweredby[i]!='\n') { - int colidx=(int)(64*char_heat[i]); + int colidx = static_cast(64 * char_heat[i]); TCOD_color_t col; colidx=MIN(63,colidx); col=colmap[colidx]; @@ -1240,12 +513,12 @@ bool TCOD_console_credits_render(int x, int y, bool alpha) { float coef=(xstr-len)/len; if ( alpha ) { TCOD_color_t fore=TCOD_console_get_char_background(NULL,char_x[i],char_y[i]); - int r=(int)(coef*fore.r + (1.0f-coef)*col.r); - int g=(int)(coef*fore.g + (1.0f-coef)*col.g); - int b=(int)(coef*fore.b + (1.0f-coef)*col.b); - col.r = CLAMP(0,255,r); - col.g = CLAMP(0,255,g); - col.b = CLAMP(0,255,b); + int r = static_cast(coef * fore.r + (1.0f - coef) * col.r); + int g = static_cast(coef * fore.g + (1.0f - coef) * col.g); + int b = static_cast(coef * fore.b + (1.0f - coef) * col.b); + col.r = std::max(0, std::min(r, 255)); + col.g = std::max(0, std::min(g, 255)); + col.b = std::max(0, std::min(b, 255)); TCOD_console_set_char_foreground(NULL,char_x[i],char_y[i],col); } else { col=TCOD_color_lerp(col,TCOD_black,coef); @@ -1257,7 +530,7 @@ bool TCOD_console_credits_render(int x, int y, bool alpha) { } /* update letters heat */ xstr += elapsed * 4; - for (i=0; i < (int)(xstr+0.5f); i++) { + for (i = 0; i < static_cast(xstr+0.5f); ++i) { char_heat[i]=(xstr-i)/(len/2); } /* restore fg color */ @@ -1267,35 +540,33 @@ bool TCOD_console_credits_render(int x, int y, bool alpha) { return true; } -static void TCOD_console_read_asc(TCOD_console_t con,FILE *f,int width, int height, float version) { - int x,y; - struct TCOD_Console *dat=con ? (struct TCOD_Console *)con : TCOD_ctx.root; - TCOD_IFNOT(dat != NULL) return; - while(fgetc(f) != '#'); - for(x = 0; x < width; x++) { - for(y = 0; y < height; y++) { - TCOD_color_t fore,back; - int c = fgetc(f); - fore.r = fgetc(f); - fore.g = fgetc(f); - fore.b = fgetc(f); - back.r = fgetc(f); - back.g = fgetc(f); - back.b = fgetc(f); - /* skip solid/walkable info */ - if ( version >= 0.3f ) { - fgetc(f); - fgetc(f); - } - TCOD_console_put_char_ex(con,x,y,c,fore,back); - } +static void TCOD_console_read_asc(TCOD_console_t con, FILE *f, + int width, int height, float version) +{ + con = TCOD_console_validate_(con); + TCOD_IFNOT(con) { return; } + while(fgetc(f) != '#'); + for(int x = 0; x < width; ++x) { + for(int y = 0; y < height; ++y) { + TCOD_color_t fore, back; + int c = fgetc(f); + fore.r = fgetc(f); + fore.g = fgetc(f); + fore.b = fgetc(f); + back.r = fgetc(f); + back.g = fgetc(f); + back.b = fgetc(f); + /* skip solid/walkable info */ + if (version >= 0.3f) { + fgetc(f); + fgetc(f); + } + TCOD_console_put_char_ex(con, x, y, c, fore, back); + } } fclose(f); } -static void TCOD_console_read_apf(TCOD_console_t con,FILE *f,int width, int height, float version) { -} - static int string_ends_with(const char *str, const char *suffix) { size_t str_len = strlen(str); size_t suffix_len = strlen(suffix); @@ -1334,8 +605,6 @@ TCOD_console_t TCOD_console_from_file(const char *filename) { con=TCOD_console_new(width,height); if (string_ends_with(filename, ".asc")) { TCOD_console_read_asc(con,f,width,height,version); - } else { - TCOD_console_read_apf(con,f,width,height,version); } return con; } @@ -1344,7 +613,7 @@ bool TCOD_console_load_asc(TCOD_console_t pcon, const char *filename) { float version; int width,height; FILE *f; - struct TCOD_Console *con=pcon ? (struct TCOD_Console *)pcon : TCOD_ctx.root; + struct TCOD_Console *con = TCOD_console_validate_(pcon); TCOD_IFNOT(con != NULL) return false; TCOD_IFNOT( filename != NULL ) { return false; @@ -1365,13 +634,7 @@ bool TCOD_console_load_asc(TCOD_console_t pcon, const char *filename) { fclose(f); return false; } - if ( con->w != width || con->h != height ) { - /* resize console */ - TCOD_console_data_free(con); - con->w = width; - con->h = height; - TCOD_console_data_alloc(con); - } + TCOD_console_resize_(con, width, height); TCOD_console_read_asc(con,f,width,height,version); return true; } @@ -1380,7 +643,7 @@ bool TCOD_console_save_asc(TCOD_console_t pcon, const char *filename) { static float version = 0.3f; FILE *f; int x,y; - struct TCOD_Console *con=pcon ? (struct TCOD_Console *)pcon : TCOD_ctx.root; + struct TCOD_Console *con = TCOD_console_validate_(pcon); TCOD_IFNOT(con != NULL) return false; TCOD_IFNOT( filename != NULL ) { return false; @@ -1388,7 +651,7 @@ bool TCOD_console_save_asc(TCOD_console_t pcon, const char *filename) { TCOD_IFNOT(con->w > 0 && con->h > 0) return false; f=fopen(filename,"wb"); TCOD_IFNOT( f != NULL ) return false; - fprintf(f, "ASCII-Paint v%g\n", version); + fprintf(f, "ASCII-Paint v%g\n", static_cast(version)); fprintf(f, "%i %i\n", con->w, con->h); fputc('#', f); for(x = 0; x < con->w; x++) { @@ -1417,34 +680,37 @@ static bool isBigEndian; void detectBigEndianness(void) { if (!hasDetectedBigEndianness){ uint32_t Value32; - uint8_t *VPtr = (uint8_t *)&Value32; + uint8_t *VPtr = reinterpret_cast(&Value32); VPtr[0] = VPtr[1] = VPtr[2] = 0; VPtr[3] = 1; if(Value32 == 1) isBigEndian = true; else isBigEndian = false; hasDetectedBigEndianness = true; } } - -uint16_t bswap16(uint16_t s){ - uint8_t* ps = (uint8_t*)&s; +#ifndef bswap16 +static uint16_t bswap16(uint16_t s) +{ + uint8_t* ps = reinterpret_cast(&s); uint16_t res; - uint8_t* pres = (uint8_t*)&res; + uint8_t* pres = reinterpret_cast(&res); pres[0] = ps[1]; pres[1] = ps[0]; return res; } - -uint32_t bswap32(uint32_t s){ - uint8_t *ps=(uint8_t *)(&s); +#endif +#ifndef bswap32 +static uint32_t bswap32(uint32_t s) +{ + uint8_t *ps = reinterpret_cast(&s); uint32_t res; - uint8_t *pres=(uint8_t *)&res; + uint8_t *pres = reinterpret_cast(&res); pres[0]=ps[3]; pres[1]=ps[2]; pres[2]=ps[1]; pres[3]=ps[0]; return res; } - +#endif uint16_t l16(uint16_t s){ if (isBigEndian) return bswap16(s); else return s; } @@ -1465,7 +731,7 @@ void fix32(uint32_t* u){ /************ RIFF helpers */ uint32_t fourCC(const char* c){ - return (*(uint32_t*)c); + return (*reinterpret_cast(c)); } /* checks if u equals str */ @@ -1474,7 +740,7 @@ bool fourCCequals(uint32_t u, const char* str){ } void fromFourCC(uint32_t u, char*s){ - const char* c = (const char*)(&u); + const char* c = reinterpret_cast(&u); s[0]=c[0]; s[1]=c[1]; s[2]=c[2]; @@ -1503,15 +769,15 @@ void putData(void* what, int length, FILE* fp){ } bool get8(uint8_t* u, FILE* fp){ - return 1==fread((void*)u, sizeof(uint8_t),1,fp); + return 1==fread(u, sizeof(uint8_t),1,fp); } bool get16(uint16_t* u, FILE* fp){ - return 1==fread((void*)u, sizeof(uint16_t),1,fp); + return 1==fread(u, sizeof(uint16_t),1,fp); } bool get32(uint32_t* u, FILE* fp){ - return 1==fread((void*)u, sizeof(uint32_t),1,fp); + return 1==fread(u, sizeof(uint32_t),1,fp); } bool getData(void* u, size_t sz, FILE* fp){ @@ -1589,7 +855,7 @@ void fixLayerv2(LayerV2* l){ /*********** ApfFile */ bool TCOD_console_save_apf(TCOD_console_t pcon, const char *filename) { - struct TCOD_Console *con=pcon ? (struct TCOD_Console *)pcon : TCOD_ctx.root; + struct TCOD_Console *con = TCOD_console_validate_(pcon); FILE* fp ; TCOD_IFNOT(con != NULL) return false; detectBigEndianness(); @@ -1625,7 +891,7 @@ bool TCOD_console_save_apf(TCOD_console_t pcon, const char *filename) { putFourCC("sett",fp); put32(l32(settingsSz),fp); put32(l32(1),fp); - putData((void*)&settingsData,sizeof settingsData,fp); + putData(&settingsData,sizeof settingsData,fp); if (settingsSz&1){ put8(0,fp); riffSize++; @@ -1641,7 +907,7 @@ bool TCOD_console_save_apf(TCOD_console_t pcon, const char *filename) { putFourCC("imgd",fp); put32(l32(imgDetailsSize),fp); put32(l32(1),fp); - putData((void*)&imgData,sizeof imgData,fp); + putData(&imgData,sizeof imgData,fp); if (imgDetailsSize&1){ put8(0,fp); riffSize++; @@ -1724,7 +990,7 @@ bool TCOD_console_load_apf(TCOD_console_t pcon, const char *filename) { uint32_t layr = fourCC("layr"); FILE* fp ; Data data; - struct TCOD_Console *con=pcon ? (struct TCOD_Console *)pcon : TCOD_ctx.root; + struct TCOD_Console *con = TCOD_console_validate_(pcon); TCOD_IFNOT(con != NULL) return false; detectBigEndianness(); @@ -1784,7 +1050,7 @@ bool TCOD_console_load_apf(TCOD_console_t pcon, const char *filename) { fix32(&ver); if (ver!=1) ERR_NEWER("settings"); /* ver must be 1 */ - if (! getData((void*)&settingsData,sizeof settingsData,fp)) ERR("Can't read settings."); + if (! getData(&settingsData,sizeof settingsData,fp)) ERR("Can't read settings."); data.settings = settingsData; fixSettings(&data.settings); @@ -1802,7 +1068,7 @@ bool TCOD_console_load_apf(TCOD_console_t pcon, const char *filename) { fix32(&ver); if (ver!=1) ERR_NEWER("image details"); /* ver must be 1 */ - if (! getData((void*)&dets, sizeof dets, fp)) ERR("Can't read image details."); + if (! getData(&dets, sizeof dets, fp)) ERR("Can't read image details."); data.details = dets; fixImage(&data.details); @@ -1811,14 +1077,8 @@ bool TCOD_console_load_apf(TCOD_console_t pcon, const char *filename) { fclose(fp); return false; } - if (con->w != static_cast(data.details.width) || con->h != static_cast(data.details.height)) { - /* resize console */ - TCOD_console_data_free(con); - con->w = data.details.width; - con->h = data.details.height; - TCOD_console_data_alloc(con); - } - + TCOD_console_resize_( + con, data.details.width, data.details.height); } else if (seg==layr){ uint32_t sz; @@ -1832,20 +1092,20 @@ bool TCOD_console_load_apf(TCOD_console_t pcon, const char *filename) { if (ver>2) ERR_NEWER("layer spec"); if (ver==1){ - if (! getData((void*)&data.layer.headerv1, sizeof( LayerV1 ), fp)) ERR("Can't read layer header."); + if (! getData(static_cast(&data.layer.headerv1), sizeof( LayerV1 ), fp)) ERR("Can't read layer header."); fixLayerv1(&data.layer.headerv1); /* Read in the data chunk*/ - data.layer.data = (uint8_t*)malloc(sizeof(uint8_t)*data.layer.headerv1.dataSize); - getData((void*) data.layer.data, data.layer.headerv1.dataSize, fp); + data.layer.data = static_cast(malloc(sizeof(uint8_t)*data.layer.headerv1.dataSize)); + getData(static_cast(data.layer.data), data.layer.headerv1.dataSize, fp); } else if (ver==2){ - if (! getData((void*)&data.layer.headerv2, sizeof( LayerV2 ), fp)) ERR("Can't read layer header."); + if (! getData(static_cast(&data.layer.headerv2), sizeof( LayerV2 ), fp)) ERR("Can't read layer header."); fixLayerv2(&data.layer.headerv2); /* Read in the data chunk */ - data.layer.data = (uint8_t*)malloc(sizeof(uint8_t)*data.layer.headerv2.dataSize); - getData((void*) data.layer.data, data.layer.headerv2.dataSize, fp); + data.layer.data = static_cast(malloc(sizeof(uint8_t)*data.layer.headerv2.dataSize)); + getData(static_cast(data.layer.data), data.layer.headerv2.dataSize, fp); } } @@ -1874,13 +1134,13 @@ bool TCOD_console_load_apf(TCOD_console_t pcon, const char *filename) { for(x = 0; x < con->w; x++) { for(y = 0; y < con->h; y++) { TCOD_color_t fore,back; - int c = (unsigned char)(imgData[index++]); - fore.r = (uint8_t)(imgData[index++]); - fore.g = (uint8_t)(imgData[index++]); - fore.b = (uint8_t)(imgData[index++]); - back.r = (uint8_t)(imgData[index++]); - back.g = (uint8_t)(imgData[index++]); - back.b = (uint8_t)(imgData[index++]); + int c = imgData[index++]; + fore.r = imgData[index++]; + fore.g = imgData[index++]; + fore.b = imgData[index++]; + back.r = imgData[index++]; + back.g = imgData[index++]; + back.b = imgData[index++]; TCOD_console_put_char_ex(con,x,y,c,fore,back); } } diff --git a/tcod_sys/libtcod/src/libtcod/console_printing.c b/tcod_sys/libtcod/src/libtcod/console_printing.c deleted file mode 100644 index 6be861dfe..000000000 --- a/tcod_sys/libtcod/src/libtcod/console_printing.c +++ /dev/null @@ -1,1086 +0,0 @@ -/* -* libtcod -* Copyright (c) 2008-2018 Jice & Mingos & rmtew -* All rights reserved. -* -* Redistribution and use in source and binary forms, with or without -* modification, are permitted provided that the following conditions are met: -* * Redistributions of source code must retain the above copyright -* notice, this list of conditions and the following disclaimer. -* * Redistributions in binary form must reproduce the above copyright -* notice, this list of conditions and the following disclaimer in the -* documentation and/or other materials provided with the distribution. -* * The name of Jice or Mingos may not be used to endorse or promote -* products derived from this software without specific prior written -* permission. -* -* THIS SOFTWARE IS PROVIDED BY JICE, MINGOS AND RMTEW ``AS IS'' AND ANY -* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED -* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE -* DISCLAIMED. IN NO EVENT SHALL JICE, MINGOS OR RMTEW BE LIABLE FOR ANY -* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES -* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; -* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND -* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS -* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. -*/ -#include "console.h" - -#include -#include -#include -#include -#include -#ifndef NO_UNICODE -#include -#include -#endif - -#include "../vendor/stb_sprintf.h" -#include "../vendor/utf8proc/utf8proc.h" -#include "libtcod_int.h" -#include "utility.h" -static TCOD_color_t color_control_fore[TCOD_COLCTRL_NUMBER] = { - {255, 255, 255}, {255, 255, 255}, {255, 255, 255}, {255, 255, 255}, - {255, 255, 255}}; -static TCOD_color_t color_control_back[TCOD_COLCTRL_NUMBER]; -/** - * Assign a foreground and background color to a color control index. - * - * \param con Index to change, e.g. `TCOD_COLCTRL_1` - * \param fore Foreground color to assign to this index. - * \param back Background color to assign to this index. - */ -void TCOD_console_set_color_control(TCOD_colctrl_t con, TCOD_color_t fore, TCOD_color_t back) { - TCOD_IFNOT(con >= TCOD_COLCTRL_1 && con <= TCOD_COLCTRL_NUMBER ) return; - color_control_fore[con-1]=fore; - color_control_back[con-1]=back; -} -char *TCOD_console_vsprint(const char *fmt, va_list ap) { - #define NB_BUFFERS 10 - #define INITIAL_SIZE 512 - /* several static buffers in case the function is used more than once in a single function call */ - static char *msg[NB_BUFFERS]={NULL}; - static int buflen[NB_BUFFERS]={0}; - static int curbuf=0; - char *ret; - bool ok=false; - if (!msg[0]) { - int i; - for (i=0; i < NB_BUFFERS; i++) { - buflen[i]=INITIAL_SIZE; - msg[i]=(char *)calloc(sizeof(char),INITIAL_SIZE); - } - } - do { - /* warning ! depending on the compiler, vsnprintf return -1 or - the expected string length if the buffer is not big enough */ - int len = stbsp_vsnprintf(msg[curbuf],buflen[curbuf],fmt,ap); - ok=true; - if (len < 0 || len >= buflen[curbuf]) { - /* buffer too small. */ - if ( len > 0 ) { - while ( buflen[curbuf] < len+1 ) buflen[curbuf]*=2; - } else { - buflen[curbuf]*=2; - } - free( msg[curbuf] ); - msg[curbuf]=(char *)calloc(sizeof(char),buflen[curbuf]); - ok=false; - } - } while (! ok); - ret=msg[curbuf]; - curbuf = (curbuf+1)%NB_BUFFERS; - return ret; -} -/** - * Print a titled, framed region on a console, using default colors and - * alignment. - * - * \param con A console pointer. - * \param x The starting X coordinate, the left-most position being 0. - * \param y The starting Y coordinate, the top-most position being 0. - * \param w The width of the frame. - * \param h The height of the frame. - * \param empty If true the characters inside of the frame will be cleared - * with spaces. - * \param flag The blending flag. - * \param fmt A format string as if passed to printf. - * \param ... Variadic arguments as if passed to printf. - * - * This function makes assumptions about the fonts character encoding. - * It will fail if the font encoding is not `cp437`. - */ -void TCOD_console_print_frame(TCOD_console_t con,int x,int y,int w,int h, bool empty, TCOD_bkgnd_flag_t flag, const char *fmt, ...) { - struct TCOD_Console *dat=con ? (struct TCOD_Console *)con : TCOD_ctx.root; - TCOD_console_put_char(con,x,y,TCOD_CHAR_NW,flag); - TCOD_console_put_char(con,x+w-1,y,TCOD_CHAR_NE,flag); - TCOD_console_put_char(con,x,y+h-1,TCOD_CHAR_SW,flag); - TCOD_console_put_char(con,x+w-1,y+h-1,TCOD_CHAR_SE,flag); - TCOD_console_hline(con,x+1,y,w-2,flag); - TCOD_console_hline(con,x+1,y+h-1,w-2,flag); - if ( h > 2 ) { - TCOD_console_vline(con,x,y+1,h-2,flag); - TCOD_console_vline(con,x+w-1,y+1,h-2,flag); - if ( empty ) { - TCOD_console_rect(con,x+1,y+1,w-2,h-2,true,flag); - } - } - if (fmt) { - va_list ap; - int xs; - TCOD_color_t tmp; - char *title; - va_start(ap,fmt); - title = TCOD_console_vsprint(fmt,ap); - va_end(ap); - title[w-3]=0; /* truncate if needed */ - xs = x + (w-(int)strlen(title)-2)/2; - tmp=dat->back; /* swap colors */ - dat->back=dat->fore; - dat->fore=tmp; - TCOD_console_print_ex(con,xs,y,TCOD_BKGND_SET,TCOD_LEFT," %s ",title); - tmp=dat->back; /* swap colors */ - dat->back=dat->fore; - dat->fore=tmp; - } -} -/** - * Print a string on a console, using default colors and alignment. - * - * \param con A console pointer. - * \param x The starting X coordinate, the left-most position being 0. - * \param y The starting Y coordinate, the top-most position being 0. - * \param fmt A format string as if passed to printf. - * \param ... Variadic arguments as if passed to printf. - */ -void TCOD_console_print(TCOD_console_t con,int x, int y, const char *fmt, ...) { - va_list ap; - struct TCOD_Console *dat=con ? (struct TCOD_Console *)con : TCOD_ctx.root; - TCOD_IFNOT ( dat != NULL ) return; - va_start(ap,fmt); - TCOD_console_print_internal(con,x,y,0,0,dat->bkgnd_flag, - dat->alignment,TCOD_console_vsprint(fmt,ap), false, false); - va_end(ap); -} -/** - * Print a string on a console, using default colors. - * - * \param con A console pointer. - * \param x The starting X coordinate, the left-most position being 0. - * \param y The starting Y coordinate, the top-most position being 0. - * \param flag The blending flag. - * \param alignment The font alignment to use. - * \param fmt A format string as if passed to printf. - * \param ... Variadic arguments as if passed to printf. - */ -void TCOD_console_print_ex(TCOD_console_t con,int x, int y, - TCOD_bkgnd_flag_t flag, TCOD_alignment_t alignment, const char *fmt, ...) { - va_list ap; - struct TCOD_Console *dat=con ? (struct TCOD_Console *)con : TCOD_ctx.root; - TCOD_IFNOT ( dat != NULL ) return; - va_start(ap,fmt); - TCOD_console_print_internal(con,x,y,0,0,flag,alignment, - TCOD_console_vsprint(fmt,ap), false, false); - va_end(ap); -} -/** - * Print a string on a console constrained to a rectangle, using default - * colors and alignment. - * - * \param con A console pointer. - * \param x The starting X coordinate, the left-most position being 0. - * \param y The starting Y coordinate, the top-most position being 0. - * \param w The width of the region. - * If 0 then the maximum width will be used. - * \param h The height of the region. - * If 0 then the maximum height will be used. - * \param fmt A format string as if passed to printf. - * \param ... Variadic arguments as if passed to printf. - * \return The number of lines actually printed. - */ -int TCOD_console_print_rect(TCOD_console_t con,int x, int y, int w, int h, const char *fmt, ...) { - int ret; - va_list ap; - struct TCOD_Console *dat=con ? (struct TCOD_Console *)con : TCOD_ctx.root; - TCOD_IFNOT ( dat != NULL ) return 0; - va_start(ap,fmt); - ret = TCOD_console_print_internal(con,x,y,w,h,dat->bkgnd_flag,dat->alignment, - TCOD_console_vsprint(fmt,ap), true, false); - va_end(ap); - return ret; -} -/** - * Print a string on a console constrained to a rectangle, using default - * colors. - * - * \param con A console pointer. - * \param x The starting X coordinate, the left-most position being 0. - * \param y The starting Y coordinate, the top-most position being 0. - * \param w The width of the region. - * If 0 then the maximum width will be used. - * \param h The height of the region. - * If 0 then the maximum height will be used. - * \param flag The blending flag. - * \param alignment The font alignment to use. - * \param fmt A format string as if passed to printf. - * \param ... Variadic arguments as if passed to printf. - * \return The number of lines actually printed. - */ -int TCOD_console_print_rect_ex(TCOD_console_t con,int x, int y, int w, int h, - TCOD_bkgnd_flag_t flag, TCOD_alignment_t alignment,const char *fmt, ...) { - int ret; - va_list ap; - va_start(ap,fmt); - ret = TCOD_console_print_internal(con,x,y,w,h,flag,alignment,TCOD_console_vsprint(fmt,ap), true, false); - va_end(ap); - return ret; -} -/** - * Return the number of lines that would be printed by the - * - * \param con A console pointer. - * \param x The starting X coordinate, the left-most position being 0. - * \param y The starting Y coordinate, the top-most position being 0. - * \param w The width of the region. - * If 0 then the maximum width will be used. - * \param h The height of the region. - * If 0 then the maximum height will be used. - * \param fmt A format string as if passed to printf. - * \param ... Variadic arguments as if passed to printf. - * \return The number of lines that would have been printed. - */ -int TCOD_console_get_height_rect(TCOD_console_t con,int x, int y, int w, int h, const char *fmt, ...) { - int ret; - va_list ap; - va_start(ap,fmt); - ret = TCOD_console_print_internal(con,x,y,w,h,TCOD_BKGND_NONE,TCOD_LEFT,TCOD_console_vsprint(fmt,ap), true, true); - va_end(ap); - return ret; -} - -/* non public methods */ -int TCOD_console_stringLength(const unsigned char *s) { - int l=0; - while (*s) { - if ( *s == (int)TCOD_COLCTRL_FORE_RGB || *s == (int)TCOD_COLCTRL_BACK_RGB ) s+=3; - else if ( (unsigned)(*s) > (unsigned)TCOD_COLCTRL_STOP ) l++; - s++; - } - return l; -} - -unsigned char * TCOD_console_forward(unsigned char *s,int l) { - while ( *s && l > 0 ) { - if ( *s == (int)TCOD_COLCTRL_FORE_RGB || *s == (int)TCOD_COLCTRL_BACK_RGB ) s+=3; - else if ( *s > (int)TCOD_COLCTRL_STOP ) l--; - s++; - } - return s; -} - -unsigned char *TCOD_console_strchr(unsigned char *s, unsigned char c) { - while ( *s && *s != c ) { - if ( *s == (int)TCOD_COLCTRL_FORE_RGB || *s == (int)TCOD_COLCTRL_BACK_RGB ) s+=3; - s++; - } - return (*s ? s : NULL); -} - -int TCOD_console_print_internal(TCOD_console_t con,int x,int y, int rw, int rh, TCOD_bkgnd_flag_t flag, - TCOD_alignment_t align, char *msg, bool can_split, bool count_only) { - unsigned char *c=(unsigned char *)msg; - int cx=0,cy=y; - int minx,maxx,miny,maxy; - TCOD_color_t oldFore; - TCOD_color_t oldBack; - struct TCOD_Console *dat=con ? (struct TCOD_Console *)con : TCOD_ctx.root; - TCOD_IFNOT ( dat != NULL - && (unsigned)(x) < (unsigned)dat->w && (unsigned)(y) < (unsigned)dat->h ) - return 0; - TCOD_IFNOT(msg != NULL) return 0; - if ( rh == 0 ) rh = dat->h-y; - if ( rw == 0 ) switch(align) { - case TCOD_LEFT : rw = dat->w-x; break; - case TCOD_RIGHT : rw=x+1; break; - case TCOD_CENTER : default : rw=dat->w; break; - } - oldFore=dat->fore; - oldBack=dat->back; - miny=y; - maxy=dat->h-1; - if (rh > 0) maxy=MIN(maxy,y+rh-1); - switch (align) { - case TCOD_LEFT : minx=MAX(0,x); maxx=MIN(dat->w-1,x+rw-1); break; - case TCOD_RIGHT : minx=MAX(0,x-rw+1); maxx=MIN(dat->w-1,x); break; - case TCOD_CENTER : default : minx=MAX(0,x-rw/2); maxx=MIN(dat->w-1,x+rw/2); break; - } - - do { - /* get \n delimited sub-message */ - unsigned char *end=TCOD_console_strchr(c,'\n'); - char bak=0; - int cl; - unsigned char *split=NULL; - if ( end ) *end=0; - cl= TCOD_console_stringLength(c); - /* find starting x */ - switch (align) { - case TCOD_LEFT : cx=x; break; - case TCOD_RIGHT : cx=x-cl+1; break; - case TCOD_CENTER : cx= x-cl/2;break; - } - /* check if the string is completely out of the minx,miny,maxx,maxy frame */ - if ( cy >= miny && cy <= maxy && cx <= maxx && cx+cl -1 >= minx ) { - if ( can_split && cy <= maxy ) { - /* if partially out of screen, try to split the sub-message */ - if ( cx < minx ) split = TCOD_console_forward(c, align == TCOD_CENTER ? cl-2*(minx-cx) : cl-(minx-cx)); - else if ( align == TCOD_CENTER ) { - if ( cx + cl/2 > maxx+1 ) split = TCOD_console_forward(c, maxx+1 - cx); - } else { - if ( cx + cl > maxx+1 ) split = TCOD_console_forward(c, maxx+1 - cx); - } - } - if ( split ) { - unsigned char *oldsplit=split; - while ( ! isspace(*split) && split > c ) split --; - if (end) *end='\n'; - if (!isspace(*split) ) { - split=oldsplit; - } - end=split; - bak=*split; - *split=0; - cl=TCOD_console_stringLength(c); - switch (align) { - case TCOD_LEFT : cx=x; break; - case TCOD_RIGHT : cx=x-cl+1; break; - case TCOD_CENTER : cx= x-cl/2;break; - } - } - if ( cx < minx ) { - /* truncate left part */ - c += minx-cx; - cl -= minx-cx; - cx=minx; - } - if ( cx + cl > maxx+1 ) { - /* truncate right part */ - split = TCOD_console_forward(c, maxx+1 - cx); - *split=0; - } - /* render the sub-message */ - if ( cy >= 0 && cy < dat->h ) - while (*c) { - if ( *c >= TCOD_COLCTRL_1 && *c <= TCOD_COLCTRL_NUMBER ) { - dat->fore=color_control_fore[(int)(*c)-1]; - dat->back=color_control_back[(int)(*c)-1]; - } else if ( *c == TCOD_COLCTRL_FORE_RGB ) { - c++; - dat->fore.r=*c++; - dat->fore.g=*c++; - dat->fore.b=*c; - } else if ( *c == TCOD_COLCTRL_BACK_RGB ) { - c++; - dat->back.r=*c++; - dat->back.g=*c++; - dat->back.b=*c; - } else if ( *c == TCOD_COLCTRL_STOP ) { - dat->fore=oldFore; - dat->back=oldBack; - } else { - if (! count_only) TCOD_console_put_char(con,cx,cy,(int)(*c),flag); - cx++; - } - c++; - } - } - if ( end ) { - /* next line */ - if ( split && ! isspace(bak) ) { - *end=bak; - c=end; - } else { - c=end+1; - } - cy++; - } else c=NULL; - } while ( c && cy < dat->h && (rh == 0 || cy < y+rh) ); - return cy-y+1; -} - -#ifndef NO_UNICODE - -wchar_t *TCOD_console_strchr_utf(wchar_t *s, char c) { - while ( *s && *s != c ) { - if ( *s == (int)TCOD_COLCTRL_FORE_RGB || *s == (int)TCOD_COLCTRL_BACK_RGB ) s+=3; - s++; - } - return (*s ? s : NULL); -} - -void TCOD_console_map_string_to_font_utf(const wchar_t *s, int fontCharX, int fontCharY) { - TCOD_IFNOT(s != NULL) return; - while (*s) { - TCOD_sys_map_ascii_to_font(*s, fontCharX, fontCharY); - fontCharX++; - if ( fontCharX == TCOD_ctx.fontNbCharHoriz ) { - fontCharX=0; - fontCharY++; - } - s++; - } -} - -wchar_t *TCOD_console_vsprint_utf(const wchar_t *fmt, va_list ap) { - #define NB_BUFFERS 10 - #define INITIAL_SIZE 512 - /* several static buffers in case the function is used more than once in a single function call */ - static wchar_t *msg[NB_BUFFERS]={NULL}; - static int buflen[NB_BUFFERS]={0}; - static int curbuf=0; - wchar_t *ret; - bool ok=false; - if (!msg[0]) { - int i; - for (i=0; i < NB_BUFFERS; i++) { - buflen[i]=INITIAL_SIZE; - msg[i]=(wchar_t *)calloc(sizeof(wchar_t),INITIAL_SIZE); - } - } - do { - /* warning ! depending on the compiler, vsnprintf return -1 or - the expected string length if the buffer is not big enough */ - int len = vswprintf(msg[curbuf],buflen[curbuf],fmt,ap); - ok=true; - if (len < 0 || len >= buflen[curbuf]) { - /* buffer too small. */ - if ( len > 0 ) { - while ( buflen[curbuf] < len+1 ) buflen[curbuf]*=2; - } else { - buflen[curbuf]*=2; - } - free( msg[curbuf] ); - msg[curbuf]=(wchar_t *)calloc(sizeof(wchar_t),buflen[curbuf]); - ok=false; - } - } while (! ok); - ret=msg[curbuf]; - curbuf = (curbuf+1)%NB_BUFFERS; - return ret; -} - - -int TCOD_console_stringLength_utf(const wchar_t *s) { - int l=0; - while (*s) { - if ( *s == (int)TCOD_COLCTRL_FORE_RGB || *s == (int)TCOD_COLCTRL_BACK_RGB ) s+=3; - else if ( *s > (int)TCOD_COLCTRL_STOP ) l++; - s++; - } - return l; -} - -wchar_t * TCOD_console_forward_utf(wchar_t *s,int l) { - while ( *s && l > 0 ) { - if ( *s == (int)TCOD_COLCTRL_FORE_RGB || *s == (int)TCOD_COLCTRL_BACK_RGB ) s+=3; - else if ( *s > (int)TCOD_COLCTRL_STOP ) l--; - s++; - } - return s; -} - -int TCOD_console_print_internal_utf(TCOD_console_t con,int x,int y, int rw, int rh, TCOD_bkgnd_flag_t flag, - TCOD_alignment_t align, wchar_t *msg, bool can_split, bool count_only) { - wchar_t *c=msg; - int cx=0,cy=y; - int minx,maxx,miny,maxy; - TCOD_color_t oldFore; - TCOD_color_t oldBack; - struct TCOD_Console *dat=con ? (struct TCOD_Console *)con : TCOD_ctx.root; - TCOD_IFNOT ( dat != NULL - && (unsigned)(x) < (unsigned)dat->w && (unsigned)(y) < (unsigned)dat->h ) - return 0; - TCOD_IFNOT(msg != NULL) return 0; - if ( rh == 0 ) rh = dat->h-y; - if ( rw == 0 ) switch(align) { - case TCOD_LEFT : rw = dat->w-x; break; - case TCOD_RIGHT : rw=x+1; break; - case TCOD_CENTER : default : rw=dat->w; break; - } - oldFore=dat->fore; - oldBack=dat->back; - miny=y; - maxy=dat->h-1; - if (rh > 0) maxy=MIN(maxy,y+rh-1); - switch (align) { - case TCOD_LEFT : minx=MAX(0,x); maxx=MIN(dat->w-1,x+rw-1); break; - case TCOD_RIGHT : minx=MAX(0,x-rw+1); maxx=MIN(dat->w-1,x); break; - case TCOD_CENTER : default : minx=MAX(0,x-rw/2); maxx=MIN(dat->w-1,x+rw/2); break; - } - - do { - /* get \n delimited sub-message */ - wchar_t *end=TCOD_console_strchr_utf(c,'\n'); - wchar_t bak=0; - int cl; - wchar_t *split=NULL; - if ( end ) *end=0; - cl= TCOD_console_stringLength_utf(c); - /* find starting x */ - switch (align) { - case TCOD_LEFT : cx=x; break; - case TCOD_RIGHT : cx=x-cl+1; break; - case TCOD_CENTER : cx= x-cl/2;break; - } - /* check if the string is completely out of the minx,miny,maxx,maxy frame */ - if ( cy >= miny && cy <= maxy && cx <= maxx && cx+cl -1 >= minx ) { - if ( can_split && cy < maxy ) { - /* if partially out of screen, try to split the sub-message */ - if ( cx < minx ) split = TCOD_console_forward_utf(c, align == TCOD_CENTER ? cl-2*(minx-cx) : cl-(minx-cx)); - else if ( align==TCOD_CENTER ) { - if ( cx + cl/2 > maxx+1 ) split = TCOD_console_forward_utf(c, maxx+1 - cx); - } else { - if ( cx + cl > maxx+1 ) split = TCOD_console_forward_utf(c, maxx+1 - cx); - } - } - if ( split ) { - wchar_t *oldsplit=split; - while ( ! iswspace(*split) && split > c ) split --; - if (end) *end='\n'; - if (!iswspace(*split) ) { - split=oldsplit; - } - end=split; - bak=*split; - *split=0; - cl=TCOD_console_stringLength_utf(c); - switch (align) { - case TCOD_LEFT : cx=x; break; - case TCOD_RIGHT : cx=x-cl+1; break; - case TCOD_CENTER : cx= x-cl/2;break; - } - } - if ( cx < minx ) { - /* truncate left part */ - c += minx-cx; - cl -= minx-cx; - cx=minx; - } - if ( cx + cl > maxx+1 ) { - /* truncate right part */ - split = TCOD_console_forward_utf(c, maxx+1 - cx); - *split=0; - } - /* render the sub-message */ - if ( cy >= 0 && cy < dat->h ) - while (*c) { - if ( *c >= TCOD_COLCTRL_1 && *c <= TCOD_COLCTRL_NUMBER ) { - dat->fore=color_control_fore[(int)(*c)-1]; - dat->back=color_control_back[(int)(*c)-1]; - } else if ( *c == TCOD_COLCTRL_FORE_RGB ) { - c++; - dat->fore.r=(uint8_t)(*c++); - dat->fore.g=(uint8_t)(*c++); - dat->fore.b=(uint8_t)(*c); - } else if ( *c == TCOD_COLCTRL_BACK_RGB ) { - c++; - dat->back.r=(uint8_t)(*c++); - dat->back.g=(uint8_t)(*c++); - dat->back.b=(uint8_t)(*c); - } else if ( *c == TCOD_COLCTRL_STOP ) { - dat->fore=oldFore; - dat->back=oldBack; - } else { - if (! count_only) TCOD_console_put_char(con,cx,cy,(int)(*c),flag); - cx++; - } - c++; - } - } - if ( end ) { - /* next line */ - if ( split && ! iswspace(bak) ) { - *end=bak; - c=end; - } else { - c=end+1; - } - cy++; - } else c=NULL; - } while ( c && cy < dat->h && (rh == 0 || cy < y+rh) ); - return cy-y+1; -} -/** - * /rst - * .. deprecated:: 1.8 - * Use :any:`TCOD_console_printf` instead. - * /endrst - */ -void TCOD_console_print_utf(TCOD_console_t con,int x, int y, const wchar_t *fmt, ...) { - va_list ap; - struct TCOD_Console *dat=con ? (struct TCOD_Console *)con : TCOD_ctx.root; - TCOD_IFNOT ( dat != NULL ) return; - va_start(ap,fmt); - TCOD_console_print_internal_utf(con,x,y,0,0,dat->bkgnd_flag,dat->alignment, - TCOD_console_vsprint_utf(fmt,ap), false, false); - va_end(ap); -} -/** - * /rst - * .. deprecated:: 1.8 - * Use :any:`TCOD_console_printf_ex` instead. - * /endrst - */ -void TCOD_console_print_ex_utf(TCOD_console_t con,int x, int y, - TCOD_bkgnd_flag_t flag, TCOD_alignment_t alignment, const wchar_t *fmt, ...) { - va_list ap; - struct TCOD_Console *dat=con ? (struct TCOD_Console *)con : TCOD_ctx.root; - TCOD_IFNOT ( dat != NULL ) return; - va_start(ap,fmt); - TCOD_console_print_internal_utf(con,x,y,0,0,flag,alignment,TCOD_console_vsprint_utf(fmt,ap), false, false); - va_end(ap); -} - -int TCOD_console_print_rect_utf(TCOD_console_t con,int x, int y, int w, int h, - const wchar_t *fmt, ...) { - int ret; - va_list ap; - struct TCOD_Console *dat=con ? (struct TCOD_Console *)con : TCOD_ctx.root; - TCOD_IFNOT ( dat != NULL ) return 0; - va_start(ap,fmt); - ret = TCOD_console_print_internal_utf(con,x,y,w,h,dat->bkgnd_flag,dat->alignment, - TCOD_console_vsprint_utf(fmt,ap), true, false); - va_end(ap); - return ret; -} -/** - * /rst - * .. deprecated:: 1.8 - * Use :any:`TCOD_console_printf_rect_ex` instead. - * /endrst - */ -int TCOD_console_print_rect_ex_utf(TCOD_console_t con,int x, int y, int w, int h, - TCOD_bkgnd_flag_t flag, TCOD_alignment_t alignment, const wchar_t *fmt, ...) { - int ret; - va_list ap; - va_start(ap,fmt); - ret=TCOD_console_print_internal_utf(con,x,y,w,h,flag,alignment,TCOD_console_vsprint_utf(fmt,ap), true, false); - va_end(ap); - return ret; -} -/** - * /rst - * .. deprecated:: 1.8 - * /endrst - */ -int TCOD_console_get_height_rect_utf(TCOD_console_t con,int x, int y, int w, int h, const wchar_t *fmt, ...) { - int ret; - va_list ap; - va_start(ap,fmt); - ret = TCOD_console_print_internal_utf(con,x,y,w,h,TCOD_BKGND_NONE,TCOD_LEFT,TCOD_console_vsprint_utf(fmt,ap), true, true); - va_end(ap); - return ret; -} - -#endif /* NO_UNICODE */ -/** - * Outputs the bounding box used for printing. - * - * If `max_width` or `max_height` are zero, they will be set automatically. - */ -static int TCOD_get_print_bounds( - const struct TCOD_Console *con, TCOD_alignment_t align, int x, int y, - int *max_width, int *max_height, - int *left, int *right, int *top, int *bottom) { - if (!con) { return -1; } - /* Set default width/height if either is zero. */ - if (*max_height == 0) { *max_height = con->h - y; } - if (*max_width == 0 ) { - switch(align) { - default: case TCOD_LEFT: - *max_width = con->w - x; - break; - case TCOD_RIGHT: - *max_width = x + 1; - break; - case TCOD_CENTER: - *max_width = con->w; - break; - } - } - /* Return printing boundary. */ - *top = y; - *bottom = MIN(con->h - 1, y + *max_height - 1); - switch (align) { - case TCOD_LEFT: - *left = x; - *right = x + *max_width - 1; - break; - case TCOD_RIGHT: - *left = x - *max_width + 1; - *right = x; - break; - case TCOD_CENTER: default: - *left = x - *max_width / 2; - *right = x + *max_width / 2; - break; - } - *left = MAX(0, *left); - *right = MIN(*right, con->w - 1); - return 0; -} -/** - * Parse ALL color codes on a utf8 string, returns the total length of the - * string parsed. - * - * Any `TCOD_color_t` parameters can be NULL. - */ -static utf8proc_ssize_t TCOD_utf8_parse_color( - const unsigned char *str, TCOD_color_t *fg_color, TCOD_color_t *bg_color, - const TCOD_color_t *old_fg_color, const TCOD_color_t *old_bg_color) { - const unsigned char *start = str; - utf8proc_int32_t codepoint; - utf8proc_ssize_t code_size; - code_size = utf8proc_iterate(str, -1, &codepoint); - str += code_size; - if (TCOD_COLCTRL_1 <= codepoint && codepoint <= TCOD_COLCTRL_NUMBER) { - /* Read colors from the color control array. */ - int color_index = codepoint - TCOD_COLCTRL_1; - if (fg_color) { *fg_color = color_control_fore[color_index]; } - if (bg_color) { *bg_color = color_control_back[color_index]; } - return code_size + TCOD_utf8_parse_color(str, fg_color, bg_color, - old_fg_color, old_bg_color); - } else if (codepoint == TCOD_COLCTRL_STOP) { - /* Return colors to their original color. */ - if (fg_color && old_fg_color) { *fg_color = *old_fg_color; } - if (bg_color && old_bg_color) { *bg_color = *old_bg_color; } - return code_size + TCOD_utf8_parse_color(str, fg_color, bg_color, - old_fg_color, old_bg_color); - } else if (codepoint == TCOD_COLCTRL_FORE_RGB - || codepoint == TCOD_COLCTRL_BACK_RGB) { - /* Read the next 3 code-points as 8-bit RGB color values. */ - unsigned char *color_array = NULL; - int i; - if (codepoint == TCOD_COLCTRL_FORE_RGB && fg_color) { - color_array = (unsigned char *)fg_color; - } else if (codepoint == TCOD_COLCTRL_BACK_RGB && bg_color) { - color_array = (unsigned char *)bg_color; - } - for (i = 0; i < 3; ++i) { - code_size = utf8proc_iterate(str, -1, &codepoint); - if (code_size < 0) { break; } - if (color_array) { color_array[i] = (unsigned char)codepoint; } - str += code_size; - } - code_size = str - start; - return code_size + TCOD_utf8_parse_color(str, fg_color, bg_color, - old_fg_color, old_bg_color); - } else { - return 0; /* `str` is not on any color codes. */ - } -} -/** - * Check for and return the length of ALL control codes at `str`. - */ -static utf8proc_ssize_t TCOD_utf8_skip_control_codes( - const unsigned char *str) { - return TCOD_utf8_parse_color(str, NULL, NULL, NULL, NULL); -} - -/* - * Check if the specified character is any line-break character - */ -static bool TCOD_utf8_is_newline_character(const utf8proc_property_t *property) -{ - switch (property->category) { - case UTF8PROC_CATEGORY_ZL: /* Separator, line */ - case UTF8PROC_CATEGORY_ZP: /* Separator, paragraph */ - return true; - - case UTF8PROC_CATEGORY_CC: /* Other, control */ - switch(property->boundclass) - { - case UTF8PROC_BOUNDCLASS_CR: // carriage return - \r - case UTF8PROC_BOUNDCLASS_LF: // line feed - \n - return true; - - default: - break; - } - break; - - default: - break; - } - return false; -} - -/** - * Get the next line-break or null terminator, or break the string before - * `max_width`. - * - * Return 0 if a line-break or null terminator was found, or 1 if the line was - * automatically split. - */ -int TCOD_utf8_next_split( - const unsigned char *str, int max_width, int can_split, - const unsigned char **endpoint, utf8proc_ssize_t *total_width) { - const unsigned char *break_point = NULL; - *total_width = 0; - *endpoint = str; - while (*str != '\0') { - utf8proc_int32_t codepoint; - utf8proc_ssize_t code_size; - const utf8proc_property_t *property; - - str += TCOD_utf8_skip_control_codes(str); - code_size = utf8proc_iterate(str, -1, &codepoint); - property = utf8proc_get_property(codepoint); - if (code_size <= 0) { break; } - if (can_split && *total_width > 0 - && *total_width + (int)property->charwidth > max_width) { - *endpoint = str; - if (break_point) { *endpoint = break_point; } - return 1; - } - switch (property->category) { - case UTF8PROC_CATEGORY_PD: /* Punctuation, dash */ - case UTF8PROC_CATEGORY_ZS: /* Separator, space */ - break_point = str; - break; - default: - break; - } - - if(TCOD_utf8_is_newline_character(property)) { - *endpoint = str; - return 0; - } - - str += code_size; - *total_width += 1; - } - *endpoint = str; - return 0; -} -/** - * Internal UTF-8 printer. - */ -int TCOD_console_print_internal_utf8_( - TCOD_console_t con, int x, int y, int max_width, int max_height, - TCOD_bkgnd_flag_t flag, TCOD_alignment_t align, - const unsigned char *string, int can_split, int count_only) { - int left, right, top, bottom; /* Print bounding box. */ - TCOD_color_t old_fg, old_bg; - int cursor_x = 0; - con = con ? con : TCOD_ctx.root; - if (!con || !string) { return 0; } - old_fg = con->fore; - old_bg = con->back; - TCOD_get_print_bounds(con, align, x, y, &max_width, &max_height, - &left, &right, &top, &bottom); - while (*string != '\0' && top <= bottom) { - const unsigned char *line_break; - utf8proc_ssize_t line_width; - utf8proc_int32_t codepoint; - utf8proc_ssize_t code_size; - const utf8proc_property_t *property; - int split_status; - code_size = utf8proc_iterate(string, -1, &codepoint); - if (code_size < 0) { return -1; } - property = utf8proc_get_property(codepoint); - /* Check for newlines. */ - if(TCOD_utf8_is_newline_character(property)) - { - string += code_size; - if(property->category == UTF8PROC_CATEGORY_ZP) - { - top += 2; - } - else { - top += 1; - } - continue; - } - - /* Get the next line of characters. */ - split_status = TCOD_utf8_next_split(string, max_width, can_split, - &line_break, &line_width); - switch (align) { - default: - case TCOD_LEFT: - cursor_x = x; - break; - case TCOD_RIGHT: - cursor_x = x - line_width; - break; - case TCOD_CENTER: - cursor_x = x - line_width / 2; - break; - } - while (string < line_break) { - /* Actually render this line of characters. */ - string += TCOD_utf8_parse_color(string, &con->fore, &con->back, - &old_fg, &old_bg); - string += code_size = utf8proc_iterate(string, -1, &codepoint); - if (code_size < 0) { return -1; } - if (!count_only && left <= cursor_x && cursor_x <= right) { - TCOD_console_put_char(con, cursor_x, top, codepoint, flag); - } - cursor_x += 1; - } - /* Ignore any extra spaces. */ - while (string != '\0') { - code_size = utf8proc_iterate(string, -1, &codepoint); - if (code_size < 0) { return -1; } - property = utf8proc_get_property(codepoint); - if (property->category == UTF8PROC_CATEGORY_ZS) { /* Separator, space */ - string += code_size; - } else { - break; - } - } - /* If there was an automatic split earlier then the top is moved down. */ - if (split_status == 1) { - top += 1; - } - } - return MIN(top, bottom) - y + 1; -} -/** - * Format and print a UTF-8 string to a console. - * /rst - * .. versionadded:: 1.8 - * /endrst - */ -void TCOD_console_printf_ex(struct TCOD_Console *con, int x, int y, - TCOD_bkgnd_flag_t flag, TCOD_alignment_t alignment, - const char *fmt, ...) { - va_list ap; - va_start(ap, fmt); - TCOD_console_print_internal_utf8_( - con, x, y, 0, 0, flag, alignment, - (const unsigned char *)TCOD_console_vsprint(fmt, ap), false, false); - va_end(ap); -} -/** - * Format and print a UTF-8 string to a console. - * /rst - * .. versionadded:: 1.8 - * /endrst - */ -void TCOD_console_printf(struct TCOD_Console *con, int x, int y, - const char *fmt, ...) { - va_list ap; - con = con ? con : TCOD_ctx.root; - if (!con) { return; } - va_start(ap, fmt); - TCOD_console_print_internal_utf8_( - con, x, y, 0, 0, con->bkgnd_flag, con->alignment, - (const unsigned char *)TCOD_console_vsprint(fmt, ap), false, false); - va_end(ap); -} -/** - * Format and print a UTF-8 string to a console. - * /rst - * .. versionadded:: 1.8 - * /endrst - */ -int TCOD_console_printf_rect_ex(struct TCOD_Console *con, - int x, int y, int w, int h, - TCOD_bkgnd_flag_t flag, TCOD_alignment_t alignment,const char *fmt, ...) { - int ret; - va_list ap; - va_start(ap, fmt); - ret = TCOD_console_print_internal_utf8_( - con, x, y, w, h, flag, alignment, - (const unsigned char *)TCOD_console_vsprint(fmt, ap), true, false); - va_end(ap); - return ret; -} -/** - * Format and print a UTF-8 string to a console. - * /rst - * .. versionadded:: 1.8 - * /endrst - */ -int TCOD_console_printf_rect(struct TCOD_Console *con, - int x, int y, int w, int h, const char *fmt, ...) { - int ret; - va_list ap; - con = con ? con : TCOD_ctx.root; - if (!con) { return 0; } - va_start(ap, fmt); - ret = TCOD_console_print_internal_utf8_( - con, x, y, w, h, con->bkgnd_flag,con->alignment, - (const unsigned char *)TCOD_console_vsprint(fmt, ap), true, false); - va_end(ap); - return ret; -} -/** - * Return the number of lines that would be printed by this formatted string. - */ -int TCOD_console_get_height_rect_fmt(struct TCOD_Console *con, - int x, int y, int w, int h, - const char *fmt, ...) { - int ret; - va_list ap; - va_start(ap, fmt); - ret = TCOD_console_print_internal_utf8_( - con, x, y, w, h, TCOD_BKGND_NONE, TCOD_LEFT, - (const unsigned char *)TCOD_console_vsprint(fmt, ap), true, true); - va_end(ap); - return ret; -} -/** - * Print a framed and optionally titled region to a console, using default - * colors and alignment. - * - * This function uses Unicode box-drawing characters and a UTF-8 formatted - * string. - */ -void TCOD_console_printf_frame(struct TCOD_Console *con, - int x, int y, int w, int h, int empty, - TCOD_bkgnd_flag_t flag, const char *fmt, ...) { - const int left = x; - const int right = x + w - 1; - const int top = y; - const int bottom = y + h - 1; - int i; - con = con ? con : TCOD_ctx.root; - TCOD_console_put_char(con, left, top, 0x250C, flag); /* ┌ */ - TCOD_console_put_char(con, right, top, 0x2510, flag); /* ┠*/ - TCOD_console_put_char(con, left, bottom, 0x2514, flag); /* └ */ - TCOD_console_put_char(con, right, bottom, 0x2518, flag); /* ┘ */ - for (i = left + 1; i < right - 1; ++i) { - TCOD_console_put_char(con, i, top, 0x2500, flag); /* ─ */ - TCOD_console_put_char(con, i, bottom, 0x2500,flag); - } - for (i = top + 1; i < bottom - 1; ++i) { - TCOD_console_put_char(con, left, i, 0x2502, flag); /* │ */ - TCOD_console_put_char(con, right, i, 0x2502, flag); - } - if (empty) { - TCOD_console_rect(con, left + 1, top + 1, right - 1, bottom - 1, true, - flag); - } - if (fmt && con) { - va_list ap; - TCOD_color_t tmp; - /* swap colors */ - tmp = con->back; - con->back = con->fore; - con->fore = tmp; - /* print the title */ - va_start(ap,fmt); - TCOD_console_printf_rect_ex(con, x + w / 2, y, w, 1, - TCOD_BKGND_SET, TCOD_CENTER, " %s ", TCOD_console_vsprint(fmt, ap)); - va_end(ap); - /* swap colors */ - tmp = con->back; - con->back = con->fore; - con->fore = tmp; - } -} diff --git a/tcod_sys/libtcod/src/libtcod/console_rexpaint.h b/tcod_sys/libtcod/src/libtcod/console_rexpaint.h deleted file mode 100644 index 3b957f84e..000000000 --- a/tcod_sys/libtcod/src/libtcod/console_rexpaint.h +++ /dev/null @@ -1,50 +0,0 @@ -/* -* libtcod -* Copyright (c) 2008-2018 Jice & Mingos & rmtew -* All rights reserved. -* -* Redistribution and use in source and binary forms, with or without -* modification, are permitted provided that the following conditions are met: -* * Redistributions of source code must retain the above copyright -* notice, this list of conditions and the following disclaimer. -* * Redistributions in binary form must reproduce the above copyright -* notice, this list of conditions and the following disclaimer in the -* documentation and/or other materials provided with the distribution. -* * The name of Jice or Mingos may not be used to endorse or promote -* products derived from this software without specific prior written -* permission. -* -* THIS SOFTWARE IS PROVIDED BY JICE, MINGOS AND RMTEW ``AS IS'' AND ANY -* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED -* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE -* DISCLAIMED. IN NO EVENT SHALL JICE, MINGOS OR RMTEW BE LIABLE FOR ANY -* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES -* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; -* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND -* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS -* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. -*/ -#ifndef TCOD_CONSOLE_REXPAINT_H_ -#define TCOD_CONSOLE_REXPAINT_H_ - -#include "portability.h" -#include "console.h" - -#ifdef __cplusplus -extern "C" { -#endif - -TCODLIB_API TCOD_console_t TCOD_console_from_xp(const char *filename); -TCODLIB_API bool TCOD_console_load_xp(TCOD_console_t con, const char *filename); -TCODLIB_API bool TCOD_console_save_xp(TCOD_console_t con, - const char *filename, int compress_level); -TCODLIB_API TCOD_list_t TCOD_console_list_from_xp(const char *filename); -TCODLIB_API bool TCOD_console_list_save_xp( - TCOD_list_t console_list, const char *filename, int compress_level); - -#ifdef __cplusplus -} -#endif - -#endif /* TCOD_CONSOLE_REXPAINT_H_ */ diff --git a/tcod_sys/libtcod/src/libtcod/console_types.h b/tcod_sys/libtcod/src/libtcod/console_types.h index 4aa75ae83..85aa109b5 100644 --- a/tcod_sys/libtcod/src/libtcod/console_types.h +++ b/tcod_sys/libtcod/src/libtcod/console_types.h @@ -1,35 +1,40 @@ -/* -* libtcod -* Copyright (c) 2008-2018 Jice & Mingos & rmtew -* All rights reserved. -* -* Redistribution and use in source and binary forms, with or without -* modification, are permitted provided that the following conditions are met: -* * Redistributions of source code must retain the above copyright -* notice, this list of conditions and the following disclaimer. -* * Redistributions in binary form must reproduce the above copyright -* notice, this list of conditions and the following disclaimer in the -* documentation and/or other materials provided with the distribution. -* * The name of Jice or Mingos may not be used to endorse or promote -* products derived from this software without specific prior written -* permission. -* -* THIS SOFTWARE IS PROVIDED BY JICE, MINGOS AND RMTEW ``AS IS'' AND ANY -* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED -* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE -* DISCLAIMED. IN NO EVENT SHALL JICE, MINGOS OR RMTEW BE LIABLE FOR ANY -* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES -* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; -* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND -* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS -* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. -*/ +/* BSD 3-Clause License + * + * Copyright © 2008-2019, Jice and the libtcod contributors. + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions are met: + * + * 1. Redistributions of source code must retain the above copyright notice, + * this list of conditions and the following disclaimer. + * + * 2. Redistributions in binary form must reproduce the above copyright notice, + * this list of conditions and the following disclaimer in the documentation + * and/or other materials provided with the distribution. + * + * 3. Neither the name of the copyright holder nor the names of its + * contributors may be used to endorse or promote products derived from + * this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE + * POSSIBILITY OF SUCH DAMAGE. + */ #ifndef _TCOD_CONSOLE_TYPES_H #define _TCOD_CONSOLE_TYPES_H #include "portability.h" #include "color.h" +#include "console/console.h" typedef enum { TCODK_NONE, @@ -223,28 +228,10 @@ typedef enum { TCOD_COLCTRL_STOP } TCOD_colctrl_t; -typedef enum { - TCOD_BKGND_NONE, - TCOD_BKGND_SET, - TCOD_BKGND_MULTIPLY, - TCOD_BKGND_LIGHTEN, - TCOD_BKGND_DARKEN, - TCOD_BKGND_SCREEN, - TCOD_BKGND_COLOR_DODGE, - TCOD_BKGND_COLOR_BURN, - TCOD_BKGND_ADD, - TCOD_BKGND_ADDA, - TCOD_BKGND_BURN, - TCOD_BKGND_OVERLAY, - TCOD_BKGND_ALPH, - TCOD_BKGND_DEFAULT -} TCOD_bkgnd_flag_t; - typedef enum { TCOD_KEY_PRESSED=1, TCOD_KEY_RELEASED=2, } TCOD_key_status_t; - /** * These font flags can be OR'd together into a bit-field and passed to * TCOD_console_set_custom_font @@ -269,6 +256,13 @@ typedef enum { TCOD_FONT_TYPE_GRAYSCALE=4, /** A unique layout used by some of libtcod's fonts. */ TCOD_FONT_LAYOUT_TCOD=8, + /** + * Decode a code page 437 tileset into Unicode code-points. + * \rst + * .. versionadded:: 1.10 + * \endrst + */ + TCOD_FONT_LAYOUT_CP437=16, } TCOD_font_flags_t; /** * The available renderers. @@ -290,43 +284,21 @@ typedef enum { TCOD_RENDERER_SDL, /** * A new SDL2 renderer. Allows the window to be resized. - * /rst + * \rst * .. versionadded:: 1.8 - * /endrst + * \endrst */ TCOD_RENDERER_SDL2, + /** + * A new OpenGL 2.0 core renderer. Allows the window to be resized. + * \rst + * .. versionadded:: 1.9 + * + * .. versionchanged:: 1.11.0 + * This renderer now uses OpenGL 2.0 instead of 2.1. + * \endrst + */ + TCOD_RENDERER_OPENGL2, TCOD_NB_RENDERERS, } TCOD_renderer_t; - -/** - * \enum TCOD_alignment_t - * - * Print justification options. - */ -typedef enum { - TCOD_LEFT, - TCOD_RIGHT, - TCOD_CENTER -} TCOD_alignment_t; - -/** Private console struct. */ -typedef struct TCOD_Console { - /** Character code array. */ - int *ch_array; - /** Pointers to arrays of TCOD_color_t colors. */ - TCOD_color_t *fg_array, *bg_array; - /** Console width and height (in characters, not pixels.) */ - int w,h; - /** Default background operator for print & print_rect functions. */ - TCOD_bkgnd_flag_t bkgnd_flag; - /** Default alignment for print & print_rect functions. */ - TCOD_alignment_t alignment; - /** Foreground (text) and background colors. */ - TCOD_color_t fore, back; - /** True if a key color is being used. */ - bool has_key_color; - /** The current key color for this console. */ - TCOD_color_t key_color; -} TCOD_Console; -typedef TCOD_Console *TCOD_console_t; #endif /* _TCOD_CONSOLE_TYPES_H */ diff --git a/tcod_sys/libtcod/src/libtcod/deprecated.cpp b/tcod_sys/libtcod/src/libtcod/deprecated.cpp new file mode 100644 index 000000000..53bd8d9c9 --- /dev/null +++ b/tcod_sys/libtcod/src/libtcod/deprecated.cpp @@ -0,0 +1,38 @@ +/* BSD 3-Clause License + * + * Copyright © 2008-2019, Jice and the libtcod contributors. + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions are met: + * + * 1. Redistributions of source code must retain the above copyright notice, + * this list of conditions and the following disclaimer. + * + * 2. Redistributions in binary form must reproduce the above copyright notice, + * this list of conditions and the following disclaimer in the documentation + * and/or other materials provided with the distribution. + * + * 3. Neither the name of the copyright holder nor the names of its + * contributors may be used to endorse or promote products derived from + * this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE + * POSSIBILITY OF SUCH DAMAGE. + */ +#include "console.h" +#include "console.hpp" + +void TCOD_console_set_keyboard_repeat(int, int) {} +void TCOD_console_disable_keyboard_repeat() {} +void TCODConsole::setKeyboardRepeat(int, int) {} +void TCODConsole::disableKeyboardRepeat() {} diff --git a/tcod_sys/libtcod/src/libtcod/engine/backend.cpp b/tcod_sys/libtcod/src/libtcod/engine/backend.cpp index 33668d290..62579c5a9 100644 --- a/tcod_sys/libtcod/src/libtcod/engine/backend.cpp +++ b/tcod_sys/libtcod/src/libtcod/engine/backend.cpp @@ -1,2 +1,32 @@ - +/* BSD 3-Clause License + * + * Copyright © 2008-2019, Jice and the libtcod contributors. + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions are met: + * + * 1. Redistributions of source code must retain the above copyright notice, + * this list of conditions and the following disclaimer. + * + * 2. Redistributions in binary form must reproduce the above copyright notice, + * this list of conditions and the following disclaimer in the documentation + * and/or other materials provided with the distribution. + * + * 3. Neither the name of the copyright holder nor the names of its + * contributors may be used to endorse or promote products derived from + * this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE + * POSSIBILITY OF SUCH DAMAGE. + */ #include "backend.h" diff --git a/tcod_sys/libtcod/src/libtcod/engine/backend.h b/tcod_sys/libtcod/src/libtcod/engine/backend.h index dd26541a9..edb42393c 100644 --- a/tcod_sys/libtcod/src/libtcod/engine/backend.h +++ b/tcod_sys/libtcod/src/libtcod/engine/backend.h @@ -1,4 +1,34 @@ - +/* BSD 3-Clause License + * + * Copyright © 2008-2019, Jice and the libtcod contributors. + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions are met: + * + * 1. Redistributions of source code must retain the above copyright notice, + * this list of conditions and the following disclaimer. + * + * 2. Redistributions in binary form must reproduce the above copyright notice, + * this list of conditions and the following disclaimer in the documentation + * and/or other materials provided with the distribution. + * + * 3. Neither the name of the copyright holder nor the names of its + * contributors may be used to endorse or promote products derived from + * this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE + * POSSIBILITY OF SUCH DAMAGE. + */ #ifndef LIBTCOD_ENGINE_BACKEND_H_ #define LIBTCOD_ENGINE_BACKEND_H_ @@ -20,16 +50,12 @@ class Backend { * Legacy wait for event virtual function. */ virtual TCOD_event_t legacy_wait_for_event( - int eventMask, TCOD_key_t *key, TCOD_mouse_t *mouse, bool flush) { - return TCOD_EVENT_NONE; - } + int eventMask, TCOD_key_t *key, TCOD_mouse_t *mouse, bool flush) = 0; /** * Legacy check for event virtual function. */ virtual TCOD_event_t legacy_check_for_event( - int eventMask, TCOD_key_t *key, TCOD_mouse_t *mouse) { - return TCOD_EVENT_NONE; - } + int eventMask, TCOD_key_t *key, TCOD_mouse_t *mouse) = 0; }; } // namespace engine } // namespace tcod diff --git a/tcod_sys/libtcod/src/libtcod/engine/display.cpp b/tcod_sys/libtcod/src/libtcod/engine/display.cpp index c8d7bf73c..ea26cd89a 100644 --- a/tcod_sys/libtcod/src/libtcod/engine/display.cpp +++ b/tcod_sys/libtcod/src/libtcod/engine/display.cpp @@ -1,2 +1,237 @@ - +/* BSD 3-Clause License + * + * Copyright © 2008-2019, Jice and the libtcod contributors. + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions are met: + * + * 1. Redistributions of source code must retain the above copyright notice, + * this list of conditions and the following disclaimer. + * + * 2. Redistributions in binary form must reproduce the above copyright notice, + * this list of conditions and the following disclaimer in the documentation + * and/or other materials provided with the distribution. + * + * 3. Neither the name of the copyright holder nor the names of its + * contributors may be used to endorse or promote products derived from + * this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE + * POSSIBILITY OF SUCH DAMAGE. + */ #include "display.h" + +#include +#include +#include + +#include +#include "error.h" +#include "globals.h" +#include "../console.h" +#include "../console.hpp" +#include "../libtcod_int.h" +#include "../sdl2/sdl2_display.h" +#include "../sdl2/gl2_display.h" +#include "../tileset/fallback.h" +namespace tcod { +static auto ensure_tileset() -> std::shared_ptr +{ + using tcod::engine::get_tileset; + using tcod::engine::set_tileset; + using tcod::tileset::new_fallback_tileset; + if (!get_tileset()) { + try { + set_tileset(new_fallback_tileset()); + } + catch (const std::runtime_error& e) { + throw std::runtime_error( + std::string() + + "Couldn't load a fallback font for the SDL2/OPENGL2 renderer: " + + e.what()); + } + } + return get_tileset(); +} +/** + * Initialize the display using one of the new renderers. + */ +template +static void init_display(int w, int h, const std::string& title, + int fullscreen, Args... args) +{ + auto tileset = ensure_tileset(); + std::array display_size{tileset->get_tile_width() * w, + tileset->get_tile_height() * h}; + int display_flags = (SDL_WINDOW_RESIZABLE | + (fullscreen ? SDL_WINDOW_FULLSCREEN_DESKTOP : 0)); + tcod::engine::set_display( + std::make_shared(tileset, display_size, display_flags, title, args...)); +} +namespace console { +void init_root(int w, int h, const std::string& title, bool fullscreen, + TCOD_renderer_t renderer, bool vsync) +{ + if (w <= 0 || h <= 0) { + throw std::invalid_argument("Width and height must be greater than zero."); + } + TCOD_console_delete(NULL); + TCODConsole::root->data = TCOD_ctx.root = TCOD_console_new(w, h); +#ifndef TCOD_BARE + TCOD_ctx.renderer=renderer; +#endif + strncpy(TCOD_ctx.window_title, title.c_str(), + sizeof(TCOD_ctx.window_title) - 1); + TCOD_ctx.window_title[sizeof(TCOD_ctx.window_title) - 1] = '\0'; + TCOD_ctx.fullscreen = fullscreen; + switch (renderer) { + case TCOD_RENDERER_SDL2: { + using tcod::sdl2::SDL2Display; + int renderer_flags = SDL_RENDERER_PRESENTVSYNC * vsync; + init_display(w, h, title, fullscreen, renderer_flags); + break; + } + case TCOD_RENDERER_OPENGL2: + init_display(w, h, title, fullscreen, vsync); + break; + default: + if(!TCOD_console_init(TCOD_ctx.root, title, fullscreen)) { + throw std::runtime_error(TCOD_get_error()); + } + break; + } +} +void init_root(int w, int h, const std::string& title, bool fullscreen, + TCOD_renderer_t renderer) +{ + init_root(w, h, title, fullscreen, renderer, false); +} +} // namespace console +} // namespace tcod +int TCOD_console_init_root_( + int w, + int h, + const char* title, + bool fullscreen, + TCOD_renderer_t renderer, + bool vsync) +{ + using tcod::console::init_root; + try { + init_root(w, h, title ? title : "", fullscreen, renderer, vsync); + } catch (const std::exception& e) { + return tcod::set_error(e); + } + return 0; +} +int TCOD_console_init_root(int w, int h, const char* title, bool fullscreen, + TCOD_renderer_t renderer) +{ + return TCOD_console_init_root_(w, h, title, fullscreen, renderer, false); +} +void TCOD_quit(void) +{ + TCOD_console_delete(NULL); +} +void TCOD_console_set_window_title(const char *title) +{ + if (auto display = tcod::engine::get_display()) { + display->set_title(title); + } else { // Deprecated renderer. + TCOD_sys_set_window_title(title); + } +} +void TCOD_console_set_fullscreen(bool fullscreen) +{ + if (auto display = tcod::engine::get_display()) { + display->set_fullscreen(fullscreen); + } else { // Deprecated renderer. + TCOD_IFNOT(TCOD_ctx.root != NULL) { return; } + TCOD_sys_set_fullscreen(fullscreen); + TCOD_ctx.fullscreen = fullscreen; + } +} +bool TCOD_console_is_fullscreen(void) +{ + if (auto display = tcod::engine::get_display()) { + return display->get_fullscreen() == 1; + } else { // Deprecated renderer. + return TCOD_ctx.fullscreen; + } +} +bool TCOD_console_has_mouse_focus(void) +{ + if (auto display = tcod::engine::get_display()) { + if (auto window = display->get_sdl_window()) { + return (SDL_GetWindowFlags(window) & SDL_WINDOW_MOUSE_FOCUS) != 0; + } + } + return TCOD_ctx.app_has_mouse_focus; +} +bool TCOD_console_is_active(void) +{ + if (auto display = tcod::engine::get_display()) { + if (auto window = display->get_sdl_window()) { + return (SDL_GetWindowFlags(window) & SDL_WINDOW_INPUT_FOCUS) != 0; + } + } + return TCOD_ctx.app_is_active; +} +bool TCOD_console_is_window_closed(void) { + return TCOD_ctx.is_window_closed; +} +struct SDL_Window* TCOD_sys_get_sdl_window(void) +{ + if (auto display = tcod::engine::get_display()) { + return display->get_sdl_window(); + } + return TCOD_sys_get_sdl_window_(); +} +struct SDL_Renderer* TCOD_sys_get_sdl_renderer(void) +{ + if (auto display = tcod::engine::get_display()) { + return display->get_sdl_renderer(); + } + return TCOD_sys_get_sdl_renderer_(); +} +int TCOD_sys_accumulate_console(const TCOD_Console* console) +{ + return TCOD_sys_accumulate_console_(console, nullptr); +} +int TCOD_sys_accumulate_console_(const TCOD_Console* console, const struct SDL_Rect* viewport) +{ + console = tcod::console::validate_(console); + auto display = tcod::engine::get_display(); + if (!console || !display) { return -1; } + display->accumulate(console, viewport); + return 0; +} +int TCOD_sys_init_sdl2_renderer_( + int width, + int height, + const char* title, + int window_flags, + int renderer_flags) +{ + using tcod::sdl2::SDL2Display; + try { + auto tileset = tcod::ensure_tileset(); + std::array window_size{ width, height }; + auto display = std::make_shared( + tileset, window_size, window_flags, title, renderer_flags); + tcod::engine::set_display(display); + } catch (const std::exception& e) { + return tcod::set_error(e); + } + return 0; +} diff --git a/tcod_sys/libtcod/src/libtcod/engine/display.h b/tcod_sys/libtcod/src/libtcod/engine/display.h index 8b70f10eb..44e3205a4 100644 --- a/tcod_sys/libtcod/src/libtcod/engine/display.h +++ b/tcod_sys/libtcod/src/libtcod/engine/display.h @@ -1,43 +1,271 @@ - +/* BSD 3-Clause License + * + * Copyright © 2008-2019, Jice and the libtcod contributors. + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions are met: + * + * 1. Redistributions of source code must retain the above copyright notice, + * this list of conditions and the following disclaimer. + * + * 2. Redistributions in binary form must reproduce the above copyright notice, + * this list of conditions and the following disclaimer in the documentation + * and/or other materials provided with the distribution. + * + * 3. Neither the name of the copyright holder nor the names of its + * contributors may be used to endorse or promote products derived from + * this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE + * POSSIBILITY OF SUCH DAMAGE. + */ #ifndef LIBTCOD_ENGINE_DISPLAY_H_ #define LIBTCOD_ENGINE_DISPLAY_H_ #ifdef __cplusplus +#include #include #endif // __cplusplus +#include "../color/canvas.h" #include "../tileset/tileset.h" #include "../console_types.h" +struct SDL_Rect; +struct SDL_Window; +struct SDL_Renderer; #ifdef __cplusplus namespace tcod { namespace engine { +using tcod::image::Image; using tcod::tileset::Tileset; class Display { public: virtual ~Display() = default; virtual void set_tileset(std::shared_ptr tileset) = 0; - virtual void set_title(const std::string title) = 0; + virtual void set_title(const std::string& title) = 0; virtual std::string get_title() = 0; + /** + * Set the fullscreen status if the display supports it. + * + * If it is supported this can be used to switch between a window and + * borderless fullscreen window. + */ + virtual void set_fullscreen(bool fullscreen) = 0; + /** + * Return true if the display is in fullscreen mode. + * + * Returns a negative number if the display does not support fullscreen. + */ + virtual int get_fullscreen() = 0; + /** + * Render a console over this display. + */ + virtual void accumulate(const TCOD_Console*) = 0; + virtual void accumulate(const TCOD_Console*, const struct SDL_Rect* viewport) = 0; + /** + * Render a console and present the display. + */ virtual void present(const TCOD_Console*) = 0; + virtual auto pixel_to_tile(const std::array& xy) + -> std::array = 0; + + virtual auto read_pixels() const -> Image = 0; + /** + * Return the pointer to an SDL2 window, if this display uses SDL. + * + * Could return nullptr. + */ + virtual auto get_sdl_window() -> struct SDL_Window* = 0; + /** + * Return the pointer to an SDL2 renderer, if this display uses SDL's + * renderer. + * + * Could return nullptr. + */ + virtual auto get_sdl_renderer() -> struct SDL_Renderer* = 0; }; /** * Incomplete interface for subclasses which don't need an SDL2 window. */ class TerminalDisplay: public Display { public: - virtual void set_tileset(std::shared_ptr tileset) override + using Display::accumulate; + virtual void set_tileset(std::shared_ptr) override {} - virtual void set_title(const std::string title) override + virtual void set_title(const std::string&) override {} virtual std::string get_title() override { return {}; } + /** + * Terminals do not support fullscreen modes. + */ + virtual void set_fullscreen(bool) override + {} + /** + * Return a negative error code. + */ + virtual int get_fullscreen() override + { + return -1; + } + virtual auto pixel_to_tile(const std::array& xy) + -> std::array override + { + return xy; + } + virtual auto get_sdl_window() -> struct SDL_Window* override + { + return nullptr; + } + virtual auto get_sdl_renderer() -> struct SDL_Renderer* override + { + return nullptr; + } + virtual void accumulate(const TCOD_Console* console, const struct SDL_Rect*) override + { + accumulate(console); + } }; } // namespace sdl2 +namespace console { +TCODLIB_API void init_root(int w, int h, const std::string& title, + bool fullscreen, TCOD_renderer_t renderer); +TCODLIB_API void init_root( + int w, + int h, + const std::string& title, + bool fullscreen, + TCOD_renderer_t renderer, + bool vsync); +} // namespace console } // namespace tcod #endif // __cplusplus +/** + * \brief Initialize the libtcod graphical engine. + * + * \param w The width in tiles. + * \param h The height in tiles. + * \param title The title for the window. + * \param fullscreen Fullscreen option. + * \param renderer Which renderer to use when rendering the console. + * + * You may want to call TCOD_console_set_custom_font BEFORE calling this + * function. By default this function loads libtcod's `terminal.png` image + * from the working directory. + * + * Afterwards TCOD_quit must be called before the program exits. + * + * Returns 0 on success, or -1 on an error, you can check the error with + * TCOD_sys_get_error() + * \rst + * .. versionchanged:: 1.12 + * Now returns -1 on error instead of crashing. + * \endrst + */ +TCODLIB_CAPI int TCOD_console_init_root(int w, int h, const char* title, + bool fullscreen, + TCOD_renderer_t renderer); +TCODLIB_CAPI int TCOD_console_init_root_( + int w, + int h, + const char* title, + bool fullscreen, + TCOD_renderer_t renderer, + bool vsync); +/** + * Shutdown libtcod. This must be called before your program exits. + * \rst + * .. versionadded:: 1.8 + * \endrst + */ +TCODLIB_CAPI void TCOD_quit(void); +/** + * Change the title string of the active window. + * + * \param title A utf8 string. + */ +TCODLIB_CAPI void TCOD_console_set_window_title(const char *title); +/** + * Set the display to be full-screen or windowed. + * + * \param fullscreen If true the display will go full-screen. + */ +TCODLIB_CAPI void TCOD_console_set_fullscreen(bool fullscreen); +/** + * Return true if the display is full-screen. + */ +TCODLIB_CAPI bool TCOD_console_is_fullscreen(void); +/** + * Return true if the window has mouse focus. + */ +TCODLIB_CAPI bool TCOD_console_has_mouse_focus(void); +/** + * Return true if the window has keyboard focus. + * + * \verbatim embed:rst:leading-asterisk + * .. versionchanged: 1.7 + * This function was previously broken. It now keeps track of keyboard + * focus. + * \endverbatim + */ +TCODLIB_CAPI bool TCOD_console_is_active(void); +/** + * Return true if the window is closing. + */ +TCODLIB_CAPI bool TCOD_console_is_window_closed(void); +/** + * Return an SDL_Window pointer if one is in use, returns NULL otherwise. + * \rst + * .. versionadded:: 1.11 + * \endrst + */ +TCODLIB_CAPI struct SDL_Window* TCOD_sys_get_sdl_window(void); +/** + * Return an SDL_Renderer pointer if one is in use, returns NULL otherwise. + * \rst + * .. versionadded:: 1.11 + * \endrst + */ +TCODLIB_CAPI struct SDL_Renderer* TCOD_sys_get_sdl_renderer(void); +/** + * Render a console over the display. + * \rst + * `console` can be any size, the active render will try to scale it to fit + * the screen. + * + * The function will only work for the SDL2/OPENGL2 renderers. + * + * Unlike :any:`TCOD_console_flush` this will not present the display. + * You will need to do that manually, likely with the SDL API. + * + * Returns 0 on success, or a negative number on a failure such as the + * incorrect renderer being active. + * + * .. versionadded:: 1.11 + * + * .. seealso:: + * :any:`TCOD_sys_get_sdl_window` :any:`TCOD_sys_get_sdl_renderer` + * \endrst + */ +TCODLIB_CAPI int TCOD_sys_accumulate_console(const TCOD_Console* console); +TCODLIB_CAPI int TCOD_sys_accumulate_console_(const TCOD_Console* console, const struct SDL_Rect* viewport); +TCODLIB_CAPI int TCOD_sys_init_sdl2_renderer_( + int width, + int height, + const char* title, + int window_flags, + int renderer_flags); #endif // LIBTCOD_ENGINE_DISPLAY_H_ - - diff --git a/tcod_sys/libtcod/src/libtcod/engine/error.cpp b/tcod_sys/libtcod/src/libtcod/engine/error.cpp new file mode 100644 index 000000000..b3b2836da --- /dev/null +++ b/tcod_sys/libtcod/src/libtcod/engine/error.cpp @@ -0,0 +1,69 @@ +/* BSD 3-Clause License + * + * Copyright © 2008-2019, Jice and the libtcod contributors. + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions are met: + * + * 1. Redistributions of source code must retain the above copyright notice, + * this list of conditions and the following disclaimer. + * + * 2. Redistributions in binary form must reproduce the above copyright notice, + * this list of conditions and the following disclaimer in the documentation + * and/or other materials provided with the distribution. + * + * 3. Neither the name of the copyright holder nor the names of its + * contributors may be used to endorse or promote products derived from + * this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE + * POSSIBILITY OF SUCH DAMAGE. + */ +#include "error.h" + +#include +#include +#include + +namespace tcod { +static thread_local char error_msg_[256] = {}; +int set_errorf(const char* fmt, ...) +{ + va_list ap; + va_start(ap, fmt); + vsnprintf(error_msg_, sizeof(error_msg_) - 1, fmt, ap); + va_end(ap); + return -1; +} +int set_error(const char* msg) +{ + std::strncpy(error_msg_, msg, sizeof(error_msg_) - 1); + return -1; +} +int set_error(const std::string& msg) +{ + return set_error(msg.c_str()); +} +int set_error(const std::exception& e) +{ + return set_error(e.what()); +} +} // namespace tcod +const char* TCOD_get_error() +{ + return tcod::error_msg_; +} +int TCOD_set_error(const char* msg) +{ + return tcod::set_error(msg); +} diff --git a/tcod_sys/libtcod/src/libtcod/engine/error.h b/tcod_sys/libtcod/src/libtcod/engine/error.h new file mode 100644 index 000000000..c32c226f1 --- /dev/null +++ b/tcod_sys/libtcod/src/libtcod/engine/error.h @@ -0,0 +1,73 @@ +/* BSD 3-Clause License + * + * Copyright © 2008-2019, Jice and the libtcod contributors. + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions are met: + * + * 1. Redistributions of source code must retain the above copyright notice, + * this list of conditions and the following disclaimer. + * + * 2. Redistributions in binary form must reproduce the above copyright notice, + * this list of conditions and the following disclaimer in the documentation + * and/or other materials provided with the distribution. + * + * 3. Neither the name of the copyright holder nor the names of its + * contributors may be used to endorse or promote products derived from + * this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE + * POSSIBILITY OF SUCH DAMAGE. + */ +#ifndef LIBTCOD_ENGINE_ERROR_H_ +#define LIBTCOD_ENGINE_ERROR_H_ + +#ifdef __cplusplus +#include +#include +#endif // __cplusplus + +#include "../portability.h" + +#ifdef __cplusplus +namespace tcod { +/** + * Set an error message and return a relevant error code, usually -1. + * + * Used internally. + */ +TCODLIB_FORMAT(1, 2) +int set_errorf(const char* fmt, ...); +int set_error(const char* msg); +int set_error(const std::string& msg); +int set_error(const std::exception& e); +} // namespace tcod +#endif // __cplusplus +/** + * Return the last error message. If there is no error then the string will + * have a length of zero. + * + * The error state is thread specific. + * \rst + * .. versionadded:: 1.12 + * \endrst + */ +TCODLIB_CAPI const char* TCOD_get_error(); +/** + * Set an error message and return -1. + * \rst + * .. versionadded:: 1.12 + * \endrst + */ +TCODLIB_CAPI int TCOD_set_error(const char*); +#endif // LIBTCOD_ENGINE_ERROR_H_ diff --git a/tcod_sys/libtcod/src/libtcod/engine/globals.cpp b/tcod_sys/libtcod/src/libtcod/engine/globals.cpp index ea00c17c7..76c886103 100644 --- a/tcod_sys/libtcod/src/libtcod/engine/globals.cpp +++ b/tcod_sys/libtcod/src/libtcod/engine/globals.cpp @@ -1,4 +1,34 @@ - +/* BSD 3-Clause License + * + * Copyright © 2008-2019, Jice and the libtcod contributors. + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions are met: + * + * 1. Redistributions of source code must retain the above copyright notice, + * this list of conditions and the following disclaimer. + * + * 2. Redistributions in binary form must reproduce the above copyright notice, + * this list of conditions and the following disclaimer in the documentation + * and/or other materials provided with the distribution. + * + * 3. Neither the name of the copyright holder nor the names of its + * contributors may be used to endorse or promote products derived from + * this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE + * POSSIBILITY OF SUCH DAMAGE. + */ #include "globals.h" #include @@ -29,6 +59,9 @@ std::shared_ptr get_display() void set_tileset(std::shared_ptr tileset) { active_tileset = tileset; + if (tileset && active_display) { + active_display->set_tileset(tileset); + } } auto get_tileset() -> std::shared_ptr { @@ -42,5 +75,13 @@ auto get_tilesheet() -> std::shared_ptr { return active_tilesheet; } -} // namespace sdl2 +} // namespace engine } // namespace tcod +TCODLIB_CAPI TCOD_Tileset* TCOD_get_default_tileset(void) +{ + return new TCOD_Tileset(tcod::engine::get_tileset()); +} +TCODLIB_CAPI void TCOD_set_default_tileset(TCOD_Tileset* tileset) +{ + tcod::engine::set_tileset(tileset ? (*tileset) : nullptr); +} diff --git a/tcod_sys/libtcod/src/libtcod/engine/globals.h b/tcod_sys/libtcod/src/libtcod/engine/globals.h index 0f9b55f0e..dd3ce974a 100644 --- a/tcod_sys/libtcod/src/libtcod/engine/globals.h +++ b/tcod_sys/libtcod/src/libtcod/engine/globals.h @@ -1,4 +1,34 @@ - +/* BSD 3-Clause License + * + * Copyright © 2008-2019, Jice and the libtcod contributors. + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions are met: + * + * 1. Redistributions of source code must retain the above copyright notice, + * this list of conditions and the following disclaimer. + * + * 2. Redistributions in binary form must reproduce the above copyright notice, + * this list of conditions and the following disclaimer in the documentation + * and/or other materials provided with the distribution. + * + * 3. Neither the name of the copyright holder nor the names of its + * contributors may be used to endorse or promote products derived from + * this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE + * POSSIBILITY OF SUCH DAMAGE. + */ #ifndef LIBTCOD_ENGINE_GLOBALS_H_ #define LIBTCOD_ENGINE_GLOBALS_H_ @@ -6,6 +36,7 @@ #include #endif // __cplusplus +#include "../portability.h" #include "backend.h" #include "display.h" #include "../tileset/tileset.h" @@ -14,32 +45,52 @@ #ifdef __cplusplus namespace tcod { namespace engine { +// All functions here are provisional unless given an added version. using tileset::Tileset; using tileset::Tilesheet; /** * Replace the active backend with a new instance, can be nullptr. */ -void set_backend(std::shared_ptr backend); +TCODLIB_API void set_backend(std::shared_ptr backend); /** * Return a shared pointer to the active backend. Might be nullptr. */ -std::shared_ptr get_backend(); +TCODLIB_API std::shared_ptr get_backend(); /** * Replace the active display with a new instance, can be nullptr. */ -void set_display(std::shared_ptr display); +TCODLIB_API void set_display(std::shared_ptr display); /** * Return a shared pointer to the active display. Might be nullptr. */ -std::shared_ptr get_display(); - -void set_tileset(std::shared_ptr tileset); -auto get_tileset() -> std::shared_ptr; -void set_tilesheet(std::shared_ptr sheet); -auto get_tilesheet() -> std::shared_ptr; +TCODLIB_API std::shared_ptr get_display(); +/** + * Replace the active tileset with a new one, can be nullptr. + * + * If there is an active display then its tileset will be set to this one. + */ +TCODLIB_API void set_tileset(std::shared_ptr tileset); +/** + * Return the current active tileset. This might be nullptr. + */ +TCODLIB_API auto get_tileset() -> std::shared_ptr; +TCODLIB_API void set_tilesheet(std::shared_ptr sheet); +TCODLIB_API auto get_tilesheet() -> std::shared_ptr; } // namespace sdl2 } // namespace tcod #endif // __cplusplus +/** + * Return the default tileset, may be NULL. + * + * This function is provisional, the API may change in the future. + */ +TCODLIB_CAPI TCOD_Tileset* TCOD_get_default_tileset(void); +/** + * Set the default tileset and update the default display to use it. + * + * This function is provisional, the API may change in the future. + */ +TCODLIB_CAPI void TCOD_set_default_tileset(TCOD_Tileset* tileset); #endif // LIBTCOD_ENGINE_GLOBALS_H_ diff --git a/tcod_sys/libtcod/src/libtcod/fov.cpp b/tcod_sys/libtcod/src/libtcod/fov.cpp index 6a0c3fe47..9a2a79e69 100644 --- a/tcod_sys/libtcod/src/libtcod/fov.cpp +++ b/tcod_sys/libtcod/src/libtcod/fov.cpp @@ -1,30 +1,34 @@ -/* -* libtcod -* Copyright (c) 2008-2018 Jice & Mingos & rmtew -* All rights reserved. -* -* Redistribution and use in source and binary forms, with or without -* modification, are permitted provided that the following conditions are met: -* * Redistributions of source code must retain the above copyright -* notice, this list of conditions and the following disclaimer. -* * Redistributions in binary form must reproduce the above copyright -* notice, this list of conditions and the following disclaimer in the -* documentation and/or other materials provided with the distribution. -* * The name of Jice or Mingos may not be used to endorse or promote -* products derived from this software without specific prior written -* permission. -* -* THIS SOFTWARE IS PROVIDED BY JICE, MINGOS AND RMTEW ``AS IS'' AND ANY -* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED -* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE -* DISCLAIMED. IN NO EVENT SHALL JICE, MINGOS OR RMTEW BE LIABLE FOR ANY -* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES -* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; -* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND -* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS -* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. -*/ +/* BSD 3-Clause License + * + * Copyright © 2008-2019, Jice and the libtcod contributors. + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions are met: + * + * 1. Redistributions of source code must retain the above copyright notice, + * this list of conditions and the following disclaimer. + * + * 2. Redistributions in binary form must reproduce the above copyright notice, + * this list of conditions and the following disclaimer in the documentation + * and/or other materials provided with the distribution. + * + * 3. Neither the name of the copyright holder nor the names of its + * contributors may be used to endorse or promote products derived from + * this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE + * POSSIBILITY OF SUCH DAMAGE. + */ #include "fov.hpp" TCODMap::TCODMap(int width,int height) { diff --git a/tcod_sys/libtcod/src/libtcod/fov.h b/tcod_sys/libtcod/src/libtcod/fov.h index 39d013fd4..21f67c086 100644 --- a/tcod_sys/libtcod/src/libtcod/fov.h +++ b/tcod_sys/libtcod/src/libtcod/fov.h @@ -1,30 +1,34 @@ -/* -* libtcod -* Copyright (c) 2008-2018 Jice & Mingos & rmtew -* All rights reserved. -* -* Redistribution and use in source and binary forms, with or without -* modification, are permitted provided that the following conditions are met: -* * Redistributions of source code must retain the above copyright -* notice, this list of conditions and the following disclaimer. -* * Redistributions in binary form must reproduce the above copyright -* notice, this list of conditions and the following disclaimer in the -* documentation and/or other materials provided with the distribution. -* * The name of Jice or Mingos may not be used to endorse or promote -* products derived from this software without specific prior written -* permission. -* -* THIS SOFTWARE IS PROVIDED BY JICE, MINGOS AND RMTEW ``AS IS'' AND ANY -* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED -* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE -* DISCLAIMED. IN NO EVENT SHALL JICE, MINGOS OR RMTEW BE LIABLE FOR ANY -* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES -* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; -* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND -* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS -* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. -*/ +/* BSD 3-Clause License + * + * Copyright © 2008-2019, Jice and the libtcod contributors. + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions are met: + * + * 1. Redistributions of source code must retain the above copyright notice, + * this list of conditions and the following disclaimer. + * + * 2. Redistributions in binary form must reproduce the above copyright notice, + * this list of conditions and the following disclaimer in the documentation + * and/or other materials provided with the distribution. + * + * 3. Neither the name of the copyright holder nor the names of its + * contributors may be used to endorse or promote products derived from + * this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE + * POSSIBILITY OF SUCH DAMAGE. + */ #ifndef _TCOD_FOV_H #define _TCOD_FOV_H diff --git a/tcod_sys/libtcod/src/libtcod/fov.hpp b/tcod_sys/libtcod/src/libtcod/fov.hpp index b0d894289..a18d5c090 100644 --- a/tcod_sys/libtcod/src/libtcod/fov.hpp +++ b/tcod_sys/libtcod/src/libtcod/fov.hpp @@ -1,30 +1,34 @@ -/* -* libtcod -* Copyright (c) 2008-2018 Jice & Mingos & rmtew -* All rights reserved. -* -* Redistribution and use in source and binary forms, with or without -* modification, are permitted provided that the following conditions are met: -* * Redistributions of source code must retain the above copyright -* notice, this list of conditions and the following disclaimer. -* * Redistributions in binary form must reproduce the above copyright -* notice, this list of conditions and the following disclaimer in the -* documentation and/or other materials provided with the distribution. -* * The name of Jice or Mingos may not be used to endorse or promote -* products derived from this software without specific prior written -* permission. -* -* THIS SOFTWARE IS PROVIDED BY JICE, MINGOS AND RMTEW ``AS IS'' AND ANY -* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED -* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE -* DISCLAIMED. IN NO EVENT SHALL JICE, MINGOS OR RMTEW BE LIABLE FOR ANY -* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES -* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; -* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND -* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS -* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. -*/ +/* BSD 3-Clause License + * + * Copyright © 2008-2019, Jice and the libtcod contributors. + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions are met: + * + * 1. Redistributions of source code must retain the above copyright notice, + * this list of conditions and the following disclaimer. + * + * 2. Redistributions in binary form must reproduce the above copyright notice, + * this list of conditions and the following disclaimer in the documentation + * and/or other materials provided with the distribution. + * + * 3. Neither the name of the copyright holder nor the names of its + * contributors may be used to endorse or promote products derived from + * this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE + * POSSIBILITY OF SUCH DAMAGE. + */ #ifndef _TCOD_FOV_HPP #define _TCOD_FOV_HPP diff --git a/tcod_sys/libtcod/src/libtcod/fov_c.c b/tcod_sys/libtcod/src/libtcod/fov_c.c index dd0ead99e..8d6eb55e9 100644 --- a/tcod_sys/libtcod/src/libtcod/fov_c.c +++ b/tcod_sys/libtcod/src/libtcod/fov_c.c @@ -1,30 +1,34 @@ -/* -* libtcod -* Copyright (c) 2008-2018 Jice & Mingos & rmtew -* All rights reserved. -* -* Redistribution and use in source and binary forms, with or without -* modification, are permitted provided that the following conditions are met: -* * Redistributions of source code must retain the above copyright -* notice, this list of conditions and the following disclaimer. -* * Redistributions in binary form must reproduce the above copyright -* notice, this list of conditions and the following disclaimer in the -* documentation and/or other materials provided with the distribution. -* * The name of Jice or Mingos may not be used to endorse or promote -* products derived from this software without specific prior written -* permission. -* -* THIS SOFTWARE IS PROVIDED BY JICE, MINGOS AND RMTEW ``AS IS'' AND ANY -* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED -* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE -* DISCLAIMED. IN NO EVENT SHALL JICE, MINGOS OR RMTEW BE LIABLE FOR ANY -* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES -* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; -* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND -* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS -* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. -*/ +/* BSD 3-Clause License + * + * Copyright © 2008-2019, Jice and the libtcod contributors. + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions are met: + * + * 1. Redistributions of source code must retain the above copyright notice, + * this list of conditions and the following disclaimer. + * + * 2. Redistributions in binary form must reproduce the above copyright notice, + * this list of conditions and the following disclaimer in the documentation + * and/or other materials provided with the distribution. + * + * 3. Neither the name of the copyright holder nor the names of its + * contributors may be used to endorse or promote products derived from + * this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE + * POSSIBILITY OF SUCH DAMAGE. + */ #include "fov.h" #include @@ -105,7 +109,7 @@ void TCOD_map_delete(struct TCOD_Map *map) { /** * Calculate the field-of-view. * - * /rst + * \rst * `player_x` and `player_y` are the used as the field-of-view source. * * `max_radius` is the maximum distance for the field-of-view algorithm. @@ -117,7 +121,7 @@ void TCOD_map_delete(struct TCOD_Map *map) { * * After this call you may check if a cell is within the field-of-view by * calling :any:`TCOD_map_is_in_fov`. - * /endrst + * \endrst */ void TCOD_map_compute_fov(struct TCOD_Map *map, int player_x, int player_y, int max_radius, bool light_walls, diff --git a/tcod_sys/libtcod/src/libtcod/fov_circular_raycasting.c b/tcod_sys/libtcod/src/libtcod/fov_circular_raycasting.c index 4f25d6b1c..76090da98 100644 --- a/tcod_sys/libtcod/src/libtcod/fov_circular_raycasting.c +++ b/tcod_sys/libtcod/src/libtcod/fov_circular_raycasting.c @@ -1,30 +1,34 @@ -/* -* libtcod -* Copyright (c) 2008-2018 Jice & Mingos & rmtew -* All rights reserved. -* -* Redistribution and use in source and binary forms, with or without -* modification, are permitted provided that the following conditions are met: -* * Redistributions of source code must retain the above copyright -* notice, this list of conditions and the following disclaimer. -* * Redistributions in binary form must reproduce the above copyright -* notice, this list of conditions and the following disclaimer in the -* documentation and/or other materials provided with the distribution. -* * The name of Jice or Mingos may not be used to endorse or promote -* products derived from this software without specific prior written -* permission. -* -* THIS SOFTWARE IS PROVIDED BY JICE, MINGOS AND RMTEW ``AS IS'' AND ANY -* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED -* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE -* DISCLAIMED. IN NO EVENT SHALL JICE, MINGOS OR RMTEW BE LIABLE FOR ANY -* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES -* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; -* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND -* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS -* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. -*/ +/* BSD 3-Clause License + * + * Copyright © 2008-2019, Jice and the libtcod contributors. + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions are met: + * + * 1. Redistributions of source code must retain the above copyright notice, + * this list of conditions and the following disclaimer. + * + * 2. Redistributions in binary form must reproduce the above copyright notice, + * this list of conditions and the following disclaimer in the documentation + * and/or other materials provided with the distribution. + * + * 3. Neither the name of the copyright holder nor the names of its + * contributors may be used to endorse or promote products derived from + * this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE + * POSSIBILITY OF SUCH DAMAGE. + */ #include "fov.h" #include diff --git a/tcod_sys/libtcod/src/libtcod/fov_diamond_raycasting.c b/tcod_sys/libtcod/src/libtcod/fov_diamond_raycasting.c index bf280d2e6..b5251c801 100644 --- a/tcod_sys/libtcod/src/libtcod/fov_diamond_raycasting.c +++ b/tcod_sys/libtcod/src/libtcod/fov_diamond_raycasting.c @@ -1,30 +1,34 @@ -/* -* libtcod -* Copyright (c) 2008-2018 Jice & Mingos & rmtew -* All rights reserved. -* -* Redistribution and use in source and binary forms, with or without -* modification, are permitted provided that the following conditions are met: -* * Redistributions of source code must retain the above copyright -* notice, this list of conditions and the following disclaimer. -* * Redistributions in binary form must reproduce the above copyright -* notice, this list of conditions and the following disclaimer in the -* documentation and/or other materials provided with the distribution. -* * The name of Jice or Mingos may not be used to endorse or promote -* products derived from this software without specific prior written -* permission. -* -* THIS SOFTWARE IS PROVIDED BY JICE, MINGOS AND RMTEW ``AS IS'' AND ANY -* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED -* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE -* DISCLAIMED. IN NO EVENT SHALL JICE, MINGOS OR RMTEW BE LIABLE FOR ANY -* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES -* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; -* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND -* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS -* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. -*/ +/* BSD 3-Clause License + * + * Copyright © 2008-2019, Jice and the libtcod contributors. + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions are met: + * + * 1. Redistributions of source code must retain the above copyright notice, + * this list of conditions and the following disclaimer. + * + * 2. Redistributions in binary form must reproduce the above copyright notice, + * this list of conditions and the following disclaimer in the documentation + * and/or other materials provided with the distribution. + * + * 3. Neither the name of the copyright holder nor the names of its + * contributors may be used to endorse or promote products derived from + * this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE + * POSSIBILITY OF SUCH DAMAGE. + */ #include "fov.h" #include diff --git a/tcod_sys/libtcod/src/libtcod/fov_permissive2.c b/tcod_sys/libtcod/src/libtcod/fov_permissive2.c index 1551e6fb1..dd9f66008 100644 --- a/tcod_sys/libtcod/src/libtcod/fov_permissive2.c +++ b/tcod_sys/libtcod/src/libtcod/fov_permissive2.c @@ -1,30 +1,34 @@ -/* -* libtcod -* Copyright (c) 2008-2018 Jice & Mingos & rmtew -* All rights reserved. -* -* Redistribution and use in source and binary forms, with or without -* modification, are permitted provided that the following conditions are met: -* * Redistributions of source code must retain the above copyright -* notice, this list of conditions and the following disclaimer. -* * Redistributions in binary form must reproduce the above copyright -* notice, this list of conditions and the following disclaimer in the -* documentation and/or other materials provided with the distribution. -* * The name of Jice or Mingos may not be used to endorse or promote -* products derived from this software without specific prior written -* permission. -* -* THIS SOFTWARE IS PROVIDED BY JICE, MINGOS AND RMTEW ``AS IS'' AND ANY -* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED -* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE -* DISCLAIMED. IN NO EVENT SHALL JICE, MINGOS OR RMTEW BE LIABLE FOR ANY -* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES -* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; -* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND -* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS -* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. -*/ +/* BSD 3-Clause License + * + * Copyright © 2008-2019, Jice and the libtcod contributors. + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions are met: + * + * 1. Redistributions of source code must retain the above copyright notice, + * this list of conditions and the following disclaimer. + * + * 2. Redistributions in binary form must reproduce the above copyright notice, + * this list of conditions and the following disclaimer in the documentation + * and/or other materials provided with the distribution. + * + * 3. Neither the name of the copyright holder nor the names of its + * contributors may be used to endorse or promote products derived from + * this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE + * POSSIBILITY OF SUCH DAMAGE. + */ #include "fov.h" #include diff --git a/tcod_sys/libtcod/src/libtcod/fov_recursive_shadowcasting.c b/tcod_sys/libtcod/src/libtcod/fov_recursive_shadowcasting.c index 7d772ca0a..657a5ce2c 100644 --- a/tcod_sys/libtcod/src/libtcod/fov_recursive_shadowcasting.c +++ b/tcod_sys/libtcod/src/libtcod/fov_recursive_shadowcasting.c @@ -1,30 +1,34 @@ -/* -* libtcod -* Copyright (c) 2008-2018 Jice & Mingos & rmtew -* All rights reserved. -* -* Redistribution and use in source and binary forms, with or without -* modification, are permitted provided that the following conditions are met: -* * Redistributions of source code must retain the above copyright -* notice, this list of conditions and the following disclaimer. -* * Redistributions in binary form must reproduce the above copyright -* notice, this list of conditions and the following disclaimer in the -* documentation and/or other materials provided with the distribution. -* * The name of Jice or Mingos may not be used to endorse or promote -* products derived from this software without specific prior written -* permission. -* -* THIS SOFTWARE IS PROVIDED BY JICE, MINGOS AND RMTEW ``AS IS'' AND ANY -* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED -* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE -* DISCLAIMED. IN NO EVENT SHALL JICE, MINGOS OR RMTEW BE LIABLE FOR ANY -* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES -* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; -* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND -* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS -* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. -*/ +/* BSD 3-Clause License + * + * Copyright © 2008-2019, Jice and the libtcod contributors. + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions are met: + * + * 1. Redistributions of source code must retain the above copyright notice, + * this list of conditions and the following disclaimer. + * + * 2. Redistributions in binary form must reproduce the above copyright notice, + * this list of conditions and the following disclaimer in the documentation + * and/or other materials provided with the distribution. + * + * 3. Neither the name of the copyright holder nor the names of its + * contributors may be used to endorse or promote products derived from + * this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE + * POSSIBILITY OF SUCH DAMAGE. + */ #include "fov.h" #include diff --git a/tcod_sys/libtcod/src/libtcod/fov_restrictive.c b/tcod_sys/libtcod/src/libtcod/fov_restrictive.c index 5cf1b2540..211375158 100644 --- a/tcod_sys/libtcod/src/libtcod/fov_restrictive.c +++ b/tcod_sys/libtcod/src/libtcod/fov_restrictive.c @@ -1,30 +1,34 @@ -/* -* libtcod -* Copyright (c) 2008-2018 Jice & Mingos & rmtew -* All rights reserved. -* -* Redistribution and use in source and binary forms, with or without -* modification, are permitted provided that the following conditions are met: -* * Redistributions of source code must retain the above copyright -* notice, this list of conditions and the following disclaimer. -* * Redistributions in binary form must reproduce the above copyright -* notice, this list of conditions and the following disclaimer in the -* documentation and/or other materials provided with the distribution. -* * The name of Jice or Mingos may not be used to endorse or promote -* products derived from this software without specific prior written -* permission. -* -* THIS SOFTWARE IS PROVIDED BY JICE, MINGOS AND RMTEW ``AS IS'' AND ANY -* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED -* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE -* DISCLAIMED. IN NO EVENT SHALL JICE, MINGOS OR RMTEW BE LIABLE FOR ANY -* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES -* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; -* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND -* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS -* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. -*/ +/* BSD 3-Clause License + * + * Copyright © 2008-2019, Jice and the libtcod contributors. + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions are met: + * + * 1. Redistributions of source code must retain the above copyright notice, + * this list of conditions and the following disclaimer. + * + * 2. Redistributions in binary form must reproduce the above copyright notice, + * this list of conditions and the following disclaimer in the documentation + * and/or other materials provided with the distribution. + * + * 3. Neither the name of the copyright holder nor the names of its + * contributors may be used to endorse or promote products derived from + * this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE + * POSSIBILITY OF SUCH DAMAGE. + */ /* * Mingos' Restrictive Precise Angle Shadowcasting (MRPAS) v1.2 */ diff --git a/tcod_sys/libtcod/src/libtcod/fov_types.h b/tcod_sys/libtcod/src/libtcod/fov_types.h index fd25d8c2c..35fe36f7a 100644 --- a/tcod_sys/libtcod/src/libtcod/fov_types.h +++ b/tcod_sys/libtcod/src/libtcod/fov_types.h @@ -1,30 +1,34 @@ -/* -* libtcod -* Copyright (c) 2008-2018 Jice & Mingos & rmtew -* All rights reserved. -* -* Redistribution and use in source and binary forms, with or without -* modification, are permitted provided that the following conditions are met: -* * Redistributions of source code must retain the above copyright -* notice, this list of conditions and the following disclaimer. -* * Redistributions in binary form must reproduce the above copyright -* notice, this list of conditions and the following disclaimer in the -* documentation and/or other materials provided with the distribution. -* * The name of Jice or Mingos may not be used to endorse or promote -* products derived from this software without specific prior written -* permission. -* -* THIS SOFTWARE IS PROVIDED BY JICE, MINGOS AND RMTEW ``AS IS'' AND ANY -* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED -* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE -* DISCLAIMED. IN NO EVENT SHALL JICE, MINGOS OR RMTEW BE LIABLE FOR ANY -* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES -* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; -* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND -* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS -* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. -*/ +/* BSD 3-Clause License + * + * Copyright © 2008-2019, Jice and the libtcod contributors. + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions are met: + * + * 1. Redistributions of source code must retain the above copyright notice, + * this list of conditions and the following disclaimer. + * + * 2. Redistributions in binary form must reproduce the above copyright notice, + * this list of conditions and the following disclaimer in the documentation + * and/or other materials provided with the distribution. + * + * 3. Neither the name of the copyright holder nor the names of its + * contributors may be used to endorse or promote products derived from + * this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE + * POSSIBILITY OF SUCH DAMAGE. + */ #ifndef TCOD_FOV_TYPES_H_ #define TCOD_FOV_TYPES_H_ #include "portability.h" diff --git a/tcod_sys/libtcod/src/libtcod/gui/button.cpp b/tcod_sys/libtcod/src/libtcod/gui/button.cpp index f5c8fc1d7..933b981bd 100644 --- a/tcod_sys/libtcod/src/libtcod/gui/button.cpp +++ b/tcod_sys/libtcod/src/libtcod/gui/button.cpp @@ -1,101 +1,110 @@ -/* -* libtcod -* Copyright (c) 2008-2018 Jice & Mingos & rmtew -* All rights reserved. -* -* Redistribution and use in source and binary forms, with or without -* modification, are permitted provided that the following conditions are met: -* * Redistributions of source code must retain the above copyright -* notice, this list of conditions and the following disclaimer. -* * Redistributions in binary form must reproduce the above copyright -* notice, this list of conditions and the following disclaimer in the -* documentation and/or other materials provided with the distribution. -* * The name of Jice or Mingos may not be used to endorse or promote -* products derived from this software without specific prior written -* permission. -* -* THIS SOFTWARE IS PROVIDED BY JICE, MINGOS AND RMTEW ``AS IS'' AND ANY -* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED -* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE -* DISCLAIMED. IN NO EVENT SHALL JICE, MINGOS OR RMTEW BE LIABLE FOR ANY -* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES -* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; -* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND -* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS -* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. -*/ +/* BSD 3-Clause License + * + * Copyright © 2008-2019, Jice and the libtcod contributors. + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions are met: + * + * 1. Redistributions of source code must retain the above copyright notice, + * this list of conditions and the following disclaimer. + * + * 2. Redistributions in binary form must reproduce the above copyright notice, + * this list of conditions and the following disclaimer in the documentation + * and/or other materials provided with the distribution. + * + * 3. Neither the name of the copyright holder nor the names of its + * contributors may be used to endorse or promote products derived from + * this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE + * POSSIBILITY OF SUCH DAMAGE. + */ #include "button.hpp" #include +#include -Button::Button(const char *label,const char *tip,widget_callback_t cbk, void *userData) - : pressed(false),label(NULL) { - if ( label != NULL ) { - setLabel(label); - } - if ( tip != NULL ) setTip(tip); - this->x=0; - this->y=0; - this->userData=userData; - this->cbk=cbk; +Button::Button( + const char* label, + const char* tip, + widget_callback_t cbk, + void* userData) +: pressed(false), label(NULL) +{ + if (label) { setLabel(label); } + if (tip) { setTip(tip); } + this->x=0; + this->y=0; + this->userData=userData; + this->cbk=cbk; } - -Button::Button(int x,int y,int width, int height,const char *label,const char *tip,widget_callback_t cbk, void *userData) - : pressed(false), label(NULL) { - if ( label != NULL ) setLabel(label); - if ( tip != NULL ) setTip(tip); - w=width; - h=height; - this->x=x; - this->y=y; - this->userData=userData; - this->cbk=cbk; +Button::Button( + int x, + int y, + int width, + int height, + const char* label, + const char* tip, + widget_callback_t cbk, + void* userData) +: pressed(false), label(NULL) +{ + if (label) { setLabel(label); } + if (tip) { setTip(tip); } + w = width; + h = height; + this->x=x; + this->y=y; + this->userData=userData; + this->cbk=cbk; } - Button::~Button() { - if ( label ) free(label); + if (label) { free(label); } } - -void Button::setLabel(const char *newLabel) { - if ( label ) free(label); - label=TCOD_strdup(newLabel); +void Button::setLabel(const char* newLabel) { + if (label) { free(label); } + label = TCOD_strdup(newLabel); } - void Button::render() { - con->setDefaultBackground(mouseIn ? backFocus : back); - con->setDefaultForeground(mouseIn ? foreFocus : fore); - if ( w > 0 && h > 0 ) con->rect(x,y,w,h,true,TCOD_BKGND_SET); - if ( label ) { - if ( pressed && mouseIn ) { - con->printEx(x+w/2,y,TCOD_BKGND_NONE,TCOD_CENTER,"-%s-",label); - } else { - con->printEx(x+w/2,y,TCOD_BKGND_NONE,TCOD_CENTER,label); - } - } + con->setDefaultBackground(mouseIn ? backFocus : back); + con->setDefaultForeground(mouseIn ? foreFocus : fore); + if (w > 0 && h > 0) { con->rect(x, y, w, h, true, TCOD_BKGND_SET); } + if (label) { + if (pressed && mouseIn) { + con->printEx(x + w / 2, y, TCOD_BKGND_NONE, TCOD_CENTER, "-%s-", label); + } else { + con->printEx(x + w / 2, y, TCOD_BKGND_NONE, TCOD_CENTER, label); + } + } } - -void Button::computeSize() { - if ( label != NULL ) { - w=(int)(strlen(label)+2); - } else { - w=4; - } - h=1; +void Button::computeSize() +{ + w = label ? static_cast(strlen(label) + 2) : 4; + h = 1; } - -void Button::expand(int width, int height) { - if ( w < width ) w = width; +void Button::expand(int width, int) +{ + w = std::max(w, width); } - -void Button::onButtonPress() { - pressed=true; +void Button::onButtonPress() +{ + pressed = true; } - -void Button::onButtonRelease() { - pressed=false; +void Button::onButtonRelease() +{ + pressed = false; } - -void Button::onButtonClick() { - if ( cbk ) cbk(this,userData); +void Button::onButtonClick() +{ + if (cbk) { cbk(this, userData); } } diff --git a/tcod_sys/libtcod/src/libtcod/gui/button.hpp b/tcod_sys/libtcod/src/libtcod/gui/button.hpp index 599b647a8..047c8112b 100644 --- a/tcod_sys/libtcod/src/libtcod/gui/button.hpp +++ b/tcod_sys/libtcod/src/libtcod/gui/button.hpp @@ -1,30 +1,34 @@ -/* -* libtcod -* Copyright (c) 2008-2018 Jice & Mingos & rmtew -* All rights reserved. -* -* Redistribution and use in source and binary forms, with or without -* modification, are permitted provided that the following conditions are met: -* * Redistributions of source code must retain the above copyright -* notice, this list of conditions and the following disclaimer. -* * Redistributions in binary form must reproduce the above copyright -* notice, this list of conditions and the following disclaimer in the -* documentation and/or other materials provided with the distribution. -* * The name of Jice or Mingos may not be used to endorse or promote -* products derived from this software without specific prior written -* permission. -* -* THIS SOFTWARE IS PROVIDED BY JICE, MINGOS AND RMTEW ``AS IS'' AND ANY -* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED -* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE -* DISCLAIMED. IN NO EVENT SHALL JICE, MINGOS OR RMTEW BE LIABLE FOR ANY -* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES -* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; -* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND -* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS -* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. -*/ +/* BSD 3-Clause License + * + * Copyright © 2008-2019, Jice and the libtcod contributors. + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions are met: + * + * 1. Redistributions of source code must retain the above copyright notice, + * this list of conditions and the following disclaimer. + * + * 2. Redistributions in binary form must reproduce the above copyright notice, + * this list of conditions and the following disclaimer in the documentation + * and/or other materials provided with the distribution. + * + * 3. Neither the name of the copyright holder nor the names of its + * contributors may be used to endorse or promote products derived from + * this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE + * POSSIBILITY OF SUCH DAMAGE. + */ #ifndef TCOD_GUI_BUTTON_HPP #define TCOD_GUI_BUTTON_HPP #include "widget.hpp" diff --git a/tcod_sys/libtcod/src/libtcod/gui/container.cpp b/tcod_sys/libtcod/src/libtcod/gui/container.cpp index 4f6e14bfd..ce1feb32b 100644 --- a/tcod_sys/libtcod/src/libtcod/gui/container.cpp +++ b/tcod_sys/libtcod/src/libtcod/gui/container.cpp @@ -1,30 +1,34 @@ -/* -* libtcod -* Copyright (c) 2008-2018 Jice & Mingos & rmtew -* All rights reserved. -* -* Redistribution and use in source and binary forms, with or without -* modification, are permitted provided that the following conditions are met: -* * Redistributions of source code must retain the above copyright -* notice, this list of conditions and the following disclaimer. -* * Redistributions in binary form must reproduce the above copyright -* notice, this list of conditions and the following disclaimer in the -* documentation and/or other materials provided with the distribution. -* * The name of Jice or Mingos may not be used to endorse or promote -* products derived from this software without specific prior written -* permission. -* -* THIS SOFTWARE IS PROVIDED BY JICE, MINGOS AND RMTEW ``AS IS'' AND ANY -* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED -* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE -* DISCLAIMED. IN NO EVENT SHALL JICE, MINGOS OR RMTEW BE LIABLE FOR ANY -* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES -* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; -* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND -* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS -* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. -*/ +/* BSD 3-Clause License + * + * Copyright © 2008-2019, Jice and the libtcod contributors. + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions are met: + * + * 1. Redistributions of source code must retain the above copyright notice, + * this list of conditions and the following disclaimer. + * + * 2. Redistributions in binary form must reproduce the above copyright notice, + * this list of conditions and the following disclaimer in the documentation + * and/or other materials provided with the distribution. + * + * 3. Neither the name of the copyright holder nor the names of its + * contributors may be used to endorse or promote products derived from + * this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE + * POSSIBILITY OF SUCH DAMAGE. + */ #include "container.hpp" Container::~Container() { diff --git a/tcod_sys/libtcod/src/libtcod/gui/container.hpp b/tcod_sys/libtcod/src/libtcod/gui/container.hpp index 8ec09cd15..c5f671e59 100644 --- a/tcod_sys/libtcod/src/libtcod/gui/container.hpp +++ b/tcod_sys/libtcod/src/libtcod/gui/container.hpp @@ -1,30 +1,34 @@ -/* -* libtcod -* Copyright (c) 2008-2018 Jice & Mingos & rmtew -* All rights reserved. -* -* Redistribution and use in source and binary forms, with or without -* modification, are permitted provided that the following conditions are met: -* * Redistributions of source code must retain the above copyright -* notice, this list of conditions and the following disclaimer. -* * Redistributions in binary form must reproduce the above copyright -* notice, this list of conditions and the following disclaimer in the -* documentation and/or other materials provided with the distribution. -* * The name of Jice or Mingos may not be used to endorse or promote -* products derived from this software without specific prior written -* permission. -* -* THIS SOFTWARE IS PROVIDED BY JICE, MINGOS AND RMTEW ``AS IS'' AND ANY -* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED -* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE -* DISCLAIMED. IN NO EVENT SHALL JICE, MINGOS OR RMTEW BE LIABLE FOR ANY -* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES -* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; -* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND -* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS -* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. -*/ +/* BSD 3-Clause License + * + * Copyright © 2008-2019, Jice and the libtcod contributors. + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions are met: + * + * 1. Redistributions of source code must retain the above copyright notice, + * this list of conditions and the following disclaimer. + * + * 2. Redistributions in binary form must reproduce the above copyright notice, + * this list of conditions and the following disclaimer in the documentation + * and/or other materials provided with the distribution. + * + * 3. Neither the name of the copyright holder nor the names of its + * contributors may be used to endorse or promote products derived from + * this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE + * POSSIBILITY OF SUCH DAMAGE. + */ #ifndef TCOD_GUI_CONTAINER_HPP #define TCOD_GUI_CONTAINER_HPP #include "widget.hpp" diff --git a/tcod_sys/libtcod/src/libtcod/gui/flatlist.cpp b/tcod_sys/libtcod/src/libtcod/gui/flatlist.cpp index 5c3187d1b..d2504c1fb 100644 --- a/tcod_sys/libtcod/src/libtcod/gui/flatlist.cpp +++ b/tcod_sys/libtcod/src/libtcod/gui/flatlist.cpp @@ -1,30 +1,34 @@ -/* -* libtcod -* Copyright (c) 2008-2018 Jice & Mingos & rmtew -* All rights reserved. -* -* Redistribution and use in source and binary forms, with or without -* modification, are permitted provided that the following conditions are met: -* * Redistributions of source code must retain the above copyright -* notice, this list of conditions and the following disclaimer. -* * Redistributions in binary form must reproduce the above copyright -* notice, this list of conditions and the following disclaimer in the -* documentation and/or other materials provided with the distribution. -* * The name of Jice or Mingos may not be used to endorse or promote -* products derived from this software without specific prior written -* permission. -* -* THIS SOFTWARE IS PROVIDED BY JICE, MINGOS AND RMTEW ``AS IS'' AND ANY -* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED -* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE -* DISCLAIMED. IN NO EVENT SHALL JICE, MINGOS OR RMTEW BE LIABLE FOR ANY -* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES -* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; -* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND -* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS -* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. -*/ +/* BSD 3-Clause License + * + * Copyright © 2008-2019, Jice and the libtcod contributors. + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions are met: + * + * 1. Redistributions of source code must retain the above copyright notice, + * this list of conditions and the following disclaimer. + * + * 2. Redistributions in binary form must reproduce the above copyright notice, + * this list of conditions and the following disclaimer in the documentation + * and/or other materials provided with the distribution. + * + * 3. Neither the name of the copyright holder nor the names of its + * contributors may be used to endorse or promote products derived from + * this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE + * POSSIBILITY OF SUCH DAMAGE. + */ #include "flatlist.hpp" #include diff --git a/tcod_sys/libtcod/src/libtcod/gui/flatlist.hpp b/tcod_sys/libtcod/src/libtcod/gui/flatlist.hpp index 8d830de48..811b0d57f 100644 --- a/tcod_sys/libtcod/src/libtcod/gui/flatlist.hpp +++ b/tcod_sys/libtcod/src/libtcod/gui/flatlist.hpp @@ -1,30 +1,34 @@ -/* -* libtcod -* Copyright (c) 2008-2018 Jice & Mingos & rmtew -* All rights reserved. -* -* Redistribution and use in source and binary forms, with or without -* modification, are permitted provided that the following conditions are met: -* * Redistributions of source code must retain the above copyright -* notice, this list of conditions and the following disclaimer. -* * Redistributions in binary form must reproduce the above copyright -* notice, this list of conditions and the following disclaimer in the -* documentation and/or other materials provided with the distribution. -* * The name of Jice or Mingos may not be used to endorse or promote -* products derived from this software without specific prior written -* permission. -* -* THIS SOFTWARE IS PROVIDED BY JICE, MINGOS AND RMTEW ``AS IS'' AND ANY -* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED -* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE -* DISCLAIMED. IN NO EVENT SHALL JICE, MINGOS OR RMTEW BE LIABLE FOR ANY -* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES -* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; -* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND -* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS -* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. -*/ +/* BSD 3-Clause License + * + * Copyright © 2008-2019, Jice and the libtcod contributors. + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions are met: + * + * 1. Redistributions of source code must retain the above copyright notice, + * this list of conditions and the following disclaimer. + * + * 2. Redistributions in binary form must reproduce the above copyright notice, + * this list of conditions and the following disclaimer in the documentation + * and/or other materials provided with the distribution. + * + * 3. Neither the name of the copyright holder nor the names of its + * contributors may be used to endorse or promote products derived from + * this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE + * POSSIBILITY OF SUCH DAMAGE. + */ #ifndef TCOD_GUI_FLATLIST_HPP #define TCOD_GUI_FLATLIST_HPP #include "textbox.hpp" diff --git a/tcod_sys/libtcod/src/libtcod/gui/gui.hpp b/tcod_sys/libtcod/src/libtcod/gui/gui.hpp index 3a2b2a2cd..5950e8e8c 100644 --- a/tcod_sys/libtcod/src/libtcod/gui/gui.hpp +++ b/tcod_sys/libtcod/src/libtcod/gui/gui.hpp @@ -1,30 +1,34 @@ -/* -* libtcod -* Copyright (c) 2008-2018 Jice & Mingos & rmtew -* All rights reserved. -* -* Redistribution and use in source and binary forms, with or without -* modification, are permitted provided that the following conditions are met: -* * Redistributions of source code must retain the above copyright -* notice, this list of conditions and the following disclaimer. -* * Redistributions in binary form must reproduce the above copyright -* notice, this list of conditions and the following disclaimer in the -* documentation and/or other materials provided with the distribution. -* * The name of Jice or Mingos may not be used to endorse or promote -* products derived from this software without specific prior written -* permission. -* -* THIS SOFTWARE IS PROVIDED BY JICE, MINGOS AND RMTEW ``AS IS'' AND ANY -* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED -* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE -* DISCLAIMED. IN NO EVENT SHALL JICE, MINGOS OR RMTEW BE LIABLE FOR ANY -* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES -* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; -* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND -* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS -* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. -*/ +/* BSD 3-Clause License + * + * Copyright © 2008-2019, Jice and the libtcod contributors. + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions are met: + * + * 1. Redistributions of source code must retain the above copyright notice, + * this list of conditions and the following disclaimer. + * + * 2. Redistributions in binary form must reproduce the above copyright notice, + * this list of conditions and the following disclaimer in the documentation + * and/or other materials provided with the distribution. + * + * 3. Neither the name of the copyright holder nor the names of its + * contributors may be used to endorse or promote products derived from + * this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE + * POSSIBILITY OF SUCH DAMAGE. + */ #ifndef _GUI_HPP #define _GUI_HPP diff --git a/tcod_sys/libtcod/src/libtcod/gui/gui_portability.hpp b/tcod_sys/libtcod/src/libtcod/gui/gui_portability.hpp index 99418a836..307808ebf 100644 --- a/tcod_sys/libtcod/src/libtcod/gui/gui_portability.hpp +++ b/tcod_sys/libtcod/src/libtcod/gui/gui_portability.hpp @@ -1,30 +1,34 @@ -/* -* libtcod -* Copyright (c) 2008-2018 Jice & Mingos & rmtew -* All rights reserved. -* -* Redistribution and use in source and binary forms, with or without -* modification, are permitted provided that the following conditions are met: -* * Redistributions of source code must retain the above copyright -* notice, this list of conditions and the following disclaimer. -* * Redistributions in binary form must reproduce the above copyright -* notice, this list of conditions and the following disclaimer in the -* documentation and/or other materials provided with the distribution. -* * The name of Jice or Mingos may not be used to endorse or promote -* products derived from this software without specific prior written -* permission. -* -* THIS SOFTWARE IS PROVIDED BY JICE, MINGOS AND RMTEW ``AS IS'' AND ANY -* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED -* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE -* DISCLAIMED. IN NO EVENT SHALL JICE, MINGOS OR RMTEW BE LIABLE FOR ANY -* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES -* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; -* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND -* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS -* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. -*/ +/* BSD 3-Clause License + * + * Copyright © 2008-2019, Jice and the libtcod contributors. + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions are met: + * + * 1. Redistributions of source code must retain the above copyright notice, + * this list of conditions and the following disclaimer. + * + * 2. Redistributions in binary form must reproduce the above copyright notice, + * this list of conditions and the following disclaimer in the documentation + * and/or other materials provided with the distribution. + * + * 3. Neither the name of the copyright holder nor the names of its + * contributors may be used to endorse or promote products derived from + * this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE + * POSSIBILITY OF SUCH DAMAGE. + */ #ifndef TCOD_GUI_PORTABILITY_HPP #define TCOD_GUI_PORTABILITY_HPP @@ -36,14 +40,6 @@ #endif // DLL export -#ifdef TCOD_WINDOWS -#ifdef LIBTCOD_EXPORTS -#define TCODLIB_GUI_API __declspec(dllexport) -#else -#define TCODLIB_GUI_API __declspec(dllimport) -#endif -#else -#define TCODLIB_GUI_API -#endif +#define TCODLIB_GUI_API TCODLIB_API #endif /* TCOD_GUI_PORTABILITY_HPP */ diff --git a/tcod_sys/libtcod/src/libtcod/gui/hbox.cpp b/tcod_sys/libtcod/src/libtcod/gui/hbox.cpp index 50af338c5..5d151bd5d 100644 --- a/tcod_sys/libtcod/src/libtcod/gui/hbox.cpp +++ b/tcod_sys/libtcod/src/libtcod/gui/hbox.cpp @@ -1,30 +1,34 @@ -/* -* libtcod -* Copyright (c) 2008-2018 Jice & Mingos & rmtew -* All rights reserved. -* -* Redistribution and use in source and binary forms, with or without -* modification, are permitted provided that the following conditions are met: -* * Redistributions of source code must retain the above copyright -* notice, this list of conditions and the following disclaimer. -* * Redistributions in binary form must reproduce the above copyright -* notice, this list of conditions and the following disclaimer in the -* documentation and/or other materials provided with the distribution. -* * The name of Jice or Mingos may not be used to endorse or promote -* products derived from this software without specific prior written -* permission. -* -* THIS SOFTWARE IS PROVIDED BY JICE, MINGOS AND RMTEW ``AS IS'' AND ANY -* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED -* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE -* DISCLAIMED. IN NO EVENT SHALL JICE, MINGOS OR RMTEW BE LIABLE FOR ANY -* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES -* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; -* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND -* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS -* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. -*/ +/* BSD 3-Clause License + * + * Copyright © 2008-2019, Jice and the libtcod contributors. + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions are met: + * + * 1. Redistributions of source code must retain the above copyright notice, + * this list of conditions and the following disclaimer. + * + * 2. Redistributions in binary form must reproduce the above copyright notice, + * this list of conditions and the following disclaimer in the documentation + * and/or other materials provided with the distribution. + * + * 3. Neither the name of the copyright holder nor the names of its + * contributors may be used to endorse or promote products derived from + * this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE + * POSSIBILITY OF SUCH DAMAGE. + */ #include "hbox.hpp" HBox::HBox(int x, int y, int padding) : VBox(x,y,padding) { diff --git a/tcod_sys/libtcod/src/libtcod/gui/hbox.hpp b/tcod_sys/libtcod/src/libtcod/gui/hbox.hpp index 0d789b21a..e41dd5544 100644 --- a/tcod_sys/libtcod/src/libtcod/gui/hbox.hpp +++ b/tcod_sys/libtcod/src/libtcod/gui/hbox.hpp @@ -1,30 +1,34 @@ -/* -* libtcod -* Copyright (c) 2008-2018 Jice & Mingos & rmtew -* All rights reserved. -* -* Redistribution and use in source and binary forms, with or without -* modification, are permitted provided that the following conditions are met: -* * Redistributions of source code must retain the above copyright -* notice, this list of conditions and the following disclaimer. -* * Redistributions in binary form must reproduce the above copyright -* notice, this list of conditions and the following disclaimer in the -* documentation and/or other materials provided with the distribution. -* * The name of Jice or Mingos may not be used to endorse or promote -* products derived from this software without specific prior written -* permission. -* -* THIS SOFTWARE IS PROVIDED BY JICE, MINGOS AND RMTEW ``AS IS'' AND ANY -* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED -* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE -* DISCLAIMED. IN NO EVENT SHALL JICE, MINGOS OR RMTEW BE LIABLE FOR ANY -* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES -* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; -* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND -* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS -* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. -*/ +/* BSD 3-Clause License + * + * Copyright © 2008-2019, Jice and the libtcod contributors. + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions are met: + * + * 1. Redistributions of source code must retain the above copyright notice, + * this list of conditions and the following disclaimer. + * + * 2. Redistributions in binary form must reproduce the above copyright notice, + * this list of conditions and the following disclaimer in the documentation + * and/or other materials provided with the distribution. + * + * 3. Neither the name of the copyright holder nor the names of its + * contributors may be used to endorse or promote products derived from + * this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE + * POSSIBILITY OF SUCH DAMAGE. + */ #ifndef TCOD_GUI_HBOX_HPP #define TCOD_GUI_HBOX_HPP #include "vbox.hpp" diff --git a/tcod_sys/libtcod/src/libtcod/gui/image.cpp b/tcod_sys/libtcod/src/libtcod/gui/image.cpp index f0d86c2e1..9e53dc1e3 100644 --- a/tcod_sys/libtcod/src/libtcod/gui/image.cpp +++ b/tcod_sys/libtcod/src/libtcod/gui/image.cpp @@ -1,30 +1,34 @@ -/* -* libtcod -* Copyright (c) 2008-2018 Jice & Mingos & rmtew -* All rights reserved. -* -* Redistribution and use in source and binary forms, with or without -* modification, are permitted provided that the following conditions are met: -* * Redistributions of source code must retain the above copyright -* notice, this list of conditions and the following disclaimer. -* * Redistributions in binary form must reproduce the above copyright -* notice, this list of conditions and the following disclaimer in the -* documentation and/or other materials provided with the distribution. -* * The name of Jice or Mingos may not be used to endorse or promote -* products derived from this software without specific prior written -* permission. -* -* THIS SOFTWARE IS PROVIDED BY JICE, MINGOS AND RMTEW ``AS IS'' AND ANY -* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED -* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE -* DISCLAIMED. IN NO EVENT SHALL JICE, MINGOS OR RMTEW BE LIABLE FOR ANY -* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES -* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; -* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND -* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS -* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. -*/ +/* BSD 3-Clause License + * + * Copyright © 2008-2019, Jice and the libtcod contributors. + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions are met: + * + * 1. Redistributions of source code must retain the above copyright notice, + * this list of conditions and the following disclaimer. + * + * 2. Redistributions in binary form must reproduce the above copyright notice, + * this list of conditions and the following disclaimer in the documentation + * and/or other materials provided with the distribution. + * + * 3. Neither the name of the copyright holder nor the names of its + * contributors may be used to endorse or promote products derived from + * this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE + * POSSIBILITY OF SUCH DAMAGE. + */ #include "image.hpp" Image::Image(int x,int y,int w, int h, const char *tip) : Widget(x,y,w,h), back(TCODColor::black) { diff --git a/tcod_sys/libtcod/src/libtcod/gui/image.hpp b/tcod_sys/libtcod/src/libtcod/gui/image.hpp index 54fda46a0..15cebd793 100644 --- a/tcod_sys/libtcod/src/libtcod/gui/image.hpp +++ b/tcod_sys/libtcod/src/libtcod/gui/image.hpp @@ -1,30 +1,34 @@ -/* -* libtcod -* Copyright (c) 2008-2018 Jice & Mingos & rmtew -* All rights reserved. -* -* Redistribution and use in source and binary forms, with or without -* modification, are permitted provided that the following conditions are met: -* * Redistributions of source code must retain the above copyright -* notice, this list of conditions and the following disclaimer. -* * Redistributions in binary form must reproduce the above copyright -* notice, this list of conditions and the following disclaimer in the -* documentation and/or other materials provided with the distribution. -* * The name of Jice or Mingos may not be used to endorse or promote -* products derived from this software without specific prior written -* permission. -* -* THIS SOFTWARE IS PROVIDED BY JICE, MINGOS AND RMTEW ``AS IS'' AND ANY -* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED -* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE -* DISCLAIMED. IN NO EVENT SHALL JICE, MINGOS OR RMTEW BE LIABLE FOR ANY -* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES -* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; -* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND -* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS -* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. -*/ +/* BSD 3-Clause License + * + * Copyright © 2008-2019, Jice and the libtcod contributors. + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions are met: + * + * 1. Redistributions of source code must retain the above copyright notice, + * this list of conditions and the following disclaimer. + * + * 2. Redistributions in binary form must reproduce the above copyright notice, + * this list of conditions and the following disclaimer in the documentation + * and/or other materials provided with the distribution. + * + * 3. Neither the name of the copyright holder nor the names of its + * contributors may be used to endorse or promote products derived from + * this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE + * POSSIBILITY OF SUCH DAMAGE. + */ #ifndef TCOD_GUI_IMAGE_HPP #define TCOD_GUI_IMAGE_HPP #include "widget.hpp" diff --git a/tcod_sys/libtcod/src/libtcod/gui/label.cpp b/tcod_sys/libtcod/src/libtcod/gui/label.cpp index 03b74ca75..ed1ade59c 100644 --- a/tcod_sys/libtcod/src/libtcod/gui/label.cpp +++ b/tcod_sys/libtcod/src/libtcod/gui/label.cpp @@ -1,48 +1,52 @@ -/* -* libtcod -* Copyright (c) 2008-2018 Jice & Mingos & rmtew -* All rights reserved. -* -* Redistribution and use in source and binary forms, with or without -* modification, are permitted provided that the following conditions are met: -* * Redistributions of source code must retain the above copyright -* notice, this list of conditions and the following disclaimer. -* * Redistributions in binary form must reproduce the above copyright -* notice, this list of conditions and the following disclaimer in the -* documentation and/or other materials provided with the distribution. -* * The name of Jice or Mingos may not be used to endorse or promote -* products derived from this software without specific prior written -* permission. -* -* THIS SOFTWARE IS PROVIDED BY JICE, MINGOS AND RMTEW ``AS IS'' AND ANY -* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED -* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE -* DISCLAIMED. IN NO EVENT SHALL JICE, MINGOS OR RMTEW BE LIABLE FOR ANY -* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES -* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; -* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND -* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS -* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. -*/ +/* BSD 3-Clause License + * + * Copyright © 2008-2019, Jice and the libtcod contributors. + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions are met: + * + * 1. Redistributions of source code must retain the above copyright notice, + * this list of conditions and the following disclaimer. + * + * 2. Redistributions in binary form must reproduce the above copyright notice, + * this list of conditions and the following disclaimer in the documentation + * and/or other materials provided with the distribution. + * + * 3. Neither the name of the copyright holder nor the names of its + * contributors may be used to endorse or promote products derived from + * this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE + * POSSIBILITY OF SUCH DAMAGE. + */ #include "label.hpp" -Label::Label(int x, int y, const char *label, const char *tip) : Widget(x,y,0,1) { - this->label=label; - if ( tip ) setTip(tip); -} +#include +Label::Label(int x, int y, const char *label, const char *tip) +: Widget(x, y, 0, 1) +{ + this->label = label; + if (tip) { setTip(tip); } +} void Label::render() { - con->setDefaultBackground(back); - con->setDefaultForeground(fore); - con->printEx(x,y,TCOD_BKGND_NONE,TCOD_LEFT,label); + con->setDefaultBackground(back); + con->setDefaultForeground(fore); + con->printEx(x, y, TCOD_BKGND_NONE, TCOD_LEFT, label); } - void Label::computeSize() { - if ( label ) w=(int)strlen(label); - else w=0; + w = label ? static_cast(strlen(label)) : 0; } - -void Label::expand(int width, int height) { - if ( w < width ) w=width; +void Label::expand(int width, int) { + w = std::max(w, width); } diff --git a/tcod_sys/libtcod/src/libtcod/gui/label.hpp b/tcod_sys/libtcod/src/libtcod/gui/label.hpp index b556b9e7d..a5b61ce77 100644 --- a/tcod_sys/libtcod/src/libtcod/gui/label.hpp +++ b/tcod_sys/libtcod/src/libtcod/gui/label.hpp @@ -1,30 +1,34 @@ -/* -* libtcod -* Copyright (c) 2008-2018 Jice & Mingos & rmtew -* All rights reserved. -* -* Redistribution and use in source and binary forms, with or without -* modification, are permitted provided that the following conditions are met: -* * Redistributions of source code must retain the above copyright -* notice, this list of conditions and the following disclaimer. -* * Redistributions in binary form must reproduce the above copyright -* notice, this list of conditions and the following disclaimer in the -* documentation and/or other materials provided with the distribution. -* * The name of Jice or Mingos may not be used to endorse or promote -* products derived from this software without specific prior written -* permission. -* -* THIS SOFTWARE IS PROVIDED BY JICE, MINGOS AND RMTEW ``AS IS'' AND ANY -* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED -* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE -* DISCLAIMED. IN NO EVENT SHALL JICE, MINGOS OR RMTEW BE LIABLE FOR ANY -* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES -* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; -* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND -* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS -* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. -*/ +/* BSD 3-Clause License + * + * Copyright © 2008-2019, Jice and the libtcod contributors. + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions are met: + * + * 1. Redistributions of source code must retain the above copyright notice, + * this list of conditions and the following disclaimer. + * + * 2. Redistributions in binary form must reproduce the above copyright notice, + * this list of conditions and the following disclaimer in the documentation + * and/or other materials provided with the distribution. + * + * 3. Neither the name of the copyright holder nor the names of its + * contributors may be used to endorse or promote products derived from + * this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE + * POSSIBILITY OF SUCH DAMAGE. + */ #ifndef TCOD_GUI_LABEL_HPP #define TCOD_GUI_LABEL_HPP #include "widget.hpp" diff --git a/tcod_sys/libtcod/src/libtcod/gui/radiobutton.cpp b/tcod_sys/libtcod/src/libtcod/gui/radiobutton.cpp index d0cfa11ea..ee4df2d92 100644 --- a/tcod_sys/libtcod/src/libtcod/gui/radiobutton.cpp +++ b/tcod_sys/libtcod/src/libtcod/gui/radiobutton.cpp @@ -1,30 +1,34 @@ -/* -* libtcod -* Copyright (c) 2008-2018 Jice & Mingos & rmtew -* All rights reserved. -* -* Redistribution and use in source and binary forms, with or without -* modification, are permitted provided that the following conditions are met: -* * Redistributions of source code must retain the above copyright -* notice, this list of conditions and the following disclaimer. -* * Redistributions in binary form must reproduce the above copyright -* notice, this list of conditions and the following disclaimer in the -* documentation and/or other materials provided with the distribution. -* * The name of Jice or Mingos may not be used to endorse or promote -* products derived from this software without specific prior written -* permission. -* -* THIS SOFTWARE IS PROVIDED BY JICE, MINGOS AND RMTEW ``AS IS'' AND ANY -* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED -* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE -* DISCLAIMED. IN NO EVENT SHALL JICE, MINGOS OR RMTEW BE LIABLE FOR ANY -* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES -* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; -* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND -* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS -* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. -*/ +/* BSD 3-Clause License + * + * Copyright © 2008-2019, Jice and the libtcod contributors. + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions are met: + * + * 1. Redistributions of source code must retain the above copyright notice, + * this list of conditions and the following disclaimer. + * + * 2. Redistributions in binary form must reproduce the above copyright notice, + * this list of conditions and the following disclaimer in the documentation + * and/or other materials provided with the distribution. + * + * 3. Neither the name of the copyright holder nor the names of its + * contributors may be used to endorse or promote products derived from + * this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE + * POSSIBILITY OF SUCH DAMAGE. + */ #include "radiobutton.hpp" RadioButton *RadioButton::groupSelect[512]; diff --git a/tcod_sys/libtcod/src/libtcod/gui/radiobutton.hpp b/tcod_sys/libtcod/src/libtcod/gui/radiobutton.hpp index 838fbfa10..47b793bc8 100644 --- a/tcod_sys/libtcod/src/libtcod/gui/radiobutton.hpp +++ b/tcod_sys/libtcod/src/libtcod/gui/radiobutton.hpp @@ -1,30 +1,34 @@ -/* -* libtcod -* Copyright (c) 2008-2018 Jice & Mingos & rmtew -* All rights reserved. -* -* Redistribution and use in source and binary forms, with or without -* modification, are permitted provided that the following conditions are met: -* * Redistributions of source code must retain the above copyright -* notice, this list of conditions and the following disclaimer. -* * Redistributions in binary form must reproduce the above copyright -* notice, this list of conditions and the following disclaimer in the -* documentation and/or other materials provided with the distribution. -* * The name of Jice or Mingos may not be used to endorse or promote -* products derived from this software without specific prior written -* permission. -* -* THIS SOFTWARE IS PROVIDED BY JICE, MINGOS AND RMTEW ``AS IS'' AND ANY -* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED -* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE -* DISCLAIMED. IN NO EVENT SHALL JICE, MINGOS OR RMTEW BE LIABLE FOR ANY -* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES -* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; -* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND -* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS -* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. -*/ +/* BSD 3-Clause License + * + * Copyright © 2008-2019, Jice and the libtcod contributors. + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions are met: + * + * 1. Redistributions of source code must retain the above copyright notice, + * this list of conditions and the following disclaimer. + * + * 2. Redistributions in binary form must reproduce the above copyright notice, + * this list of conditions and the following disclaimer in the documentation + * and/or other materials provided with the distribution. + * + * 3. Neither the name of the copyright holder nor the names of its + * contributors may be used to endorse or promote products derived from + * this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE + * POSSIBILITY OF SUCH DAMAGE. + */ #ifndef TCOD_GUI_RADIOBUTTON_HPP #define TCOD_GUI_RADIOBUTTON_HPP #include "button.hpp" diff --git a/tcod_sys/libtcod/src/libtcod/gui/slider.cpp b/tcod_sys/libtcod/src/libtcod/gui/slider.cpp index a9d3b3b39..18de6a76d 100644 --- a/tcod_sys/libtcod/src/libtcod/gui/slider.cpp +++ b/tcod_sys/libtcod/src/libtcod/gui/slider.cpp @@ -1,30 +1,34 @@ -/* -* libtcod -* Copyright (c) 2008-2018 Jice & Mingos & rmtew -* All rights reserved. -* -* Redistribution and use in source and binary forms, with or without -* modification, are permitted provided that the following conditions are met: -* * Redistributions of source code must retain the above copyright -* notice, this list of conditions and the following disclaimer. -* * Redistributions in binary form must reproduce the above copyright -* notice, this list of conditions and the following disclaimer in the -* documentation and/or other materials provided with the distribution. -* * The name of Jice or Mingos may not be used to endorse or promote -* products derived from this software without specific prior written -* permission. -* -* THIS SOFTWARE IS PROVIDED BY JICE, MINGOS AND RMTEW ``AS IS'' AND ANY -* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED -* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE -* DISCLAIMED. IN NO EVENT SHALL JICE, MINGOS OR RMTEW BE LIABLE FOR ANY -* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES -* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; -* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND -* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS -* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. -*/ +/* BSD 3-Clause License + * + * Copyright © 2008-2019, Jice and the libtcod contributors. + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions are met: + * + * 1. Redistributions of source code must retain the above copyright notice, + * this list of conditions and the following disclaimer. + * + * 2. Redistributions in binary form must reproduce the above copyright notice, + * this list of conditions and the following disclaimer in the documentation + * and/or other materials provided with the distribution. + * + * 3. Neither the name of the copyright holder nor the names of its + * contributors may be used to endorse or promote products derived from + * this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE + * POSSIBILITY OF SUCH DAMAGE. + */ #include "slider.hpp" #include @@ -65,37 +69,41 @@ void Slider::render() { } void Slider::update(TCOD_key_t k) { - float oldValue=value; - TextBox::update(k); - textToValue(); - if ( mouse.cx >= x+w-2 && mouse.cx < x+w && mouse.cy == y ) onArrows=true; - else onArrows=false; - if ( drag ) { - if ( dragy == -1 ) { - dragx = mouse.x; - dragy = mouse.y; - } else { - float mdx = (float)((mouse.x-dragx)*sensitivity) / (con->getWidth()*8); - float mdy = (float)((mouse.y-dragy)*sensitivity) / (con->getHeight()*8); - float oldValue=value; - if ( fabs(mdy) > fabs(mdx) ) mdx=-mdy; - value = dragValue+(max-min)*mdx; - value=CLAMP(min,max,value); - if ( value != oldValue ) { - valueToText(); - textToValue(); - } - } - } - if ( value != oldValue && cbk ) { - cbk(this,value,data); - } + float old_value = value; + TextBox::update(k); + textToValue(); + if (mouse.cx >= x + w - 2 && mouse.cx < x + w && mouse.cy == y) { + onArrows = true; + } else { + onArrows = false; + } + if (drag) { + if (dragy == -1) { + dragx = mouse.x; + dragy = mouse.y; + } else { + float mdx = ((mouse.x - dragx) * sensitivity) / (con->getWidth() * 8); + float mdy = ((mouse.y - dragy) * sensitivity) / (con->getHeight() * 8); + float old_value2 = value; + if (fabs(mdy) > fabs(mdx)) { mdx = -mdy; } + value = dragValue + (max - min) * mdx; + value = std::max(min, std::min(value, max)); + if (value != old_value2) { + valueToText(); + textToValue(); + } + } + } + if (value != old_value && cbk) { + cbk(this, value, data); + } } -void Slider::valueToText() { - char tmp[128]; - sprintf(tmp, fmt ? fmt : "%.2f",value); - setText(tmp); +void Slider::valueToText() +{ + char tmp[128]; + sprintf(tmp, fmt ? fmt : "%.2f", static_cast(value)); + setText(tmp); } void Slider::textToValue() { diff --git a/tcod_sys/libtcod/src/libtcod/gui/slider.hpp b/tcod_sys/libtcod/src/libtcod/gui/slider.hpp index 7a49e2029..811a8a0b8 100644 --- a/tcod_sys/libtcod/src/libtcod/gui/slider.hpp +++ b/tcod_sys/libtcod/src/libtcod/gui/slider.hpp @@ -1,30 +1,34 @@ -/* -* libtcod -* Copyright (c) 2008-2018 Jice & Mingos & rmtew -* All rights reserved. -* -* Redistribution and use in source and binary forms, with or without -* modification, are permitted provided that the following conditions are met: -* * Redistributions of source code must retain the above copyright -* notice, this list of conditions and the following disclaimer. -* * Redistributions in binary form must reproduce the above copyright -* notice, this list of conditions and the following disclaimer in the -* documentation and/or other materials provided with the distribution. -* * The name of Jice or Mingos may not be used to endorse or promote -* products derived from this software without specific prior written -* permission. -* -* THIS SOFTWARE IS PROVIDED BY JICE, MINGOS AND RMTEW ``AS IS'' AND ANY -* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED -* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE -* DISCLAIMED. IN NO EVENT SHALL JICE, MINGOS OR RMTEW BE LIABLE FOR ANY -* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES -* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; -* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND -* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS -* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. -*/ +/* BSD 3-Clause License + * + * Copyright © 2008-2019, Jice and the libtcod contributors. + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions are met: + * + * 1. Redistributions of source code must retain the above copyright notice, + * this list of conditions and the following disclaimer. + * + * 2. Redistributions in binary form must reproduce the above copyright notice, + * this list of conditions and the following disclaimer in the documentation + * and/or other materials provided with the distribution. + * + * 3. Neither the name of the copyright holder nor the names of its + * contributors may be used to endorse or promote products derived from + * this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE + * POSSIBILITY OF SUCH DAMAGE. + */ #ifndef TCOD_GUI_SLIDER_HPP #define TCOD_GUI_SLIDER_HPP #include "textbox.hpp" diff --git a/tcod_sys/libtcod/src/libtcod/gui/statusbar.cpp b/tcod_sys/libtcod/src/libtcod/gui/statusbar.cpp index 7d1940f93..a4786cab3 100644 --- a/tcod_sys/libtcod/src/libtcod/gui/statusbar.cpp +++ b/tcod_sys/libtcod/src/libtcod/gui/statusbar.cpp @@ -1,30 +1,34 @@ -/* -* libtcod -* Copyright (c) 2008-2018 Jice & Mingos & rmtew -* All rights reserved. -* -* Redistribution and use in source and binary forms, with or without -* modification, are permitted provided that the following conditions are met: -* * Redistributions of source code must retain the above copyright -* notice, this list of conditions and the following disclaimer. -* * Redistributions in binary form must reproduce the above copyright -* notice, this list of conditions and the following disclaimer in the -* documentation and/or other materials provided with the distribution. -* * The name of Jice or Mingos may not be used to endorse or promote -* products derived from this software without specific prior written -* permission. -* -* THIS SOFTWARE IS PROVIDED BY JICE, MINGOS AND RMTEW ``AS IS'' AND ANY -* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED -* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE -* DISCLAIMED. IN NO EVENT SHALL JICE, MINGOS OR RMTEW BE LIABLE FOR ANY -* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES -* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; -* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND -* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS -* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. -*/ +/* BSD 3-Clause License + * + * Copyright © 2008-2019, Jice and the libtcod contributors. + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions are met: + * + * 1. Redistributions of source code must retain the above copyright notice, + * this list of conditions and the following disclaimer. + * + * 2. Redistributions in binary form must reproduce the above copyright notice, + * this list of conditions and the following disclaimer in the documentation + * and/or other materials provided with the distribution. + * + * 3. Neither the name of the copyright holder nor the names of its + * contributors may be used to endorse or promote products derived from + * this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE + * POSSIBILITY OF SUCH DAMAGE. + */ #include "statusbar.hpp" void StatusBar::render() { @@ -32,6 +36,6 @@ void StatusBar::render() { con->rect(x,y,w,h,true,TCOD_BKGND_SET); if ( focus && focus->tip ) { con->setDefaultForeground(fore); - con->printRectEx(x+1,y,w,h,TCOD_BKGND_NONE,TCOD_LEFT,focus->tip); + con->printRectEx(x+1,y,w,h,TCOD_BKGND_NONE,TCOD_LEFT,"%s",focus->tip); } } diff --git a/tcod_sys/libtcod/src/libtcod/gui/statusbar.hpp b/tcod_sys/libtcod/src/libtcod/gui/statusbar.hpp index b947a9ed0..b38b850b1 100644 --- a/tcod_sys/libtcod/src/libtcod/gui/statusbar.hpp +++ b/tcod_sys/libtcod/src/libtcod/gui/statusbar.hpp @@ -1,30 +1,34 @@ -/* -* libtcod -* Copyright (c) 2008-2018 Jice & Mingos & rmtew -* All rights reserved. -* -* Redistribution and use in source and binary forms, with or without -* modification, are permitted provided that the following conditions are met: -* * Redistributions of source code must retain the above copyright -* notice, this list of conditions and the following disclaimer. -* * Redistributions in binary form must reproduce the above copyright -* notice, this list of conditions and the following disclaimer in the -* documentation and/or other materials provided with the distribution. -* * The name of Jice or Mingos may not be used to endorse or promote -* products derived from this software without specific prior written -* permission. -* -* THIS SOFTWARE IS PROVIDED BY JICE, MINGOS AND RMTEW ``AS IS'' AND ANY -* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED -* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE -* DISCLAIMED. IN NO EVENT SHALL JICE, MINGOS OR RMTEW BE LIABLE FOR ANY -* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES -* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; -* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND -* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS -* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. -*/ +/* BSD 3-Clause License + * + * Copyright © 2008-2019, Jice and the libtcod contributors. + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions are met: + * + * 1. Redistributions of source code must retain the above copyright notice, + * this list of conditions and the following disclaimer. + * + * 2. Redistributions in binary form must reproduce the above copyright notice, + * this list of conditions and the following disclaimer in the documentation + * and/or other materials provided with the distribution. + * + * 3. Neither the name of the copyright holder nor the names of its + * contributors may be used to endorse or promote products derived from + * this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE + * POSSIBILITY OF SUCH DAMAGE. + */ #ifndef TCOD_GUI_STATUSBAR_HPP #define TCOD_GUI_STATUSBAR_HPP #include "widget.hpp" diff --git a/tcod_sys/libtcod/src/libtcod/gui/textbox.cpp b/tcod_sys/libtcod/src/libtcod/gui/textbox.cpp index d163d01b8..1821469e9 100644 --- a/tcod_sys/libtcod/src/libtcod/gui/textbox.cpp +++ b/tcod_sys/libtcod/src/libtcod/gui/textbox.cpp @@ -1,30 +1,34 @@ -/* -* libtcod -* Copyright (c) 2008-2018 Jice & Mingos & rmtew -* All rights reserved. -* -* Redistribution and use in source and binary forms, with or without -* modification, are permitted provided that the following conditions are met: -* * Redistributions of source code must retain the above copyright -* notice, this list of conditions and the following disclaimer. -* * Redistributions in binary form must reproduce the above copyright -* notice, this list of conditions and the following disclaimer in the -* documentation and/or other materials provided with the distribution. -* * The name of Jice or Mingos may not be used to endorse or promote -* products derived from this software without specific prior written -* permission. -* -* THIS SOFTWARE IS PROVIDED BY JICE, MINGOS AND RMTEW ``AS IS'' AND ANY -* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED -* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE -* DISCLAIMED. IN NO EVENT SHALL JICE, MINGOS OR RMTEW BE LIABLE FOR ANY -* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES -* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; -* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND -* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS -* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. -*/ +/* BSD 3-Clause License + * + * Copyright © 2008-2019, Jice and the libtcod contributors. + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions are met: + * + * 1. Redistributions of source code must retain the above copyright notice, + * this list of conditions and the following disclaimer. + * + * 2. Redistributions in binary form must reproduce the above copyright notice, + * this list of conditions and the following disclaimer in the documentation + * and/or other materials provided with the distribution. + * + * 3. Neither the name of the copyright holder nor the names of its + * contributors may be used to endorse or promote products derived from + * this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE + * POSSIBILITY OF SUCH DAMAGE. + */ #include "textbox.hpp" #include @@ -45,7 +49,7 @@ TextBox::TextBox(int x,int y,int w, int maxw, const char *label, const char *val if ( label ) this->label=TCOD_strdup(label); boxw=w; if (label ) { - boxx=(int)strlen(label)+1; + boxx=static_cast(strlen(label) + 1); this->w+= boxx; } } @@ -68,7 +72,7 @@ void TextBox::render() { con->setDefaultBackground(keyboardFocus == this ? foreFocus : fore); con->setDefaultForeground(keyboardFocus == this ? backFocus : back); con->rect(x+boxx,y,boxw,h,false,TCOD_BKGND_SET); - int len=(int)strlen(txt)-offset; + int len = static_cast(strlen(txt) - offset); if (len > boxw) len = boxw; if ( txt ) con->printEx(x+boxx,y,TCOD_BKGND_NONE,TCOD_LEFT,"%.*s",len,&txt[offset]); if (keyboardFocus == this && blink > 0.0f) { @@ -89,9 +93,9 @@ void TextBox::update(TCOD_key_t k) { if ( k.vk == TCODK_CHAR || (k.vk >= TCODK_0 && k.vk <= TCODK_9) || (k.vk >= TCODK_KP0 && k.vk <= TCODK_KP9) ) { - if ( ! insert || (int)strlen(txt) < maxw ) { - if ( insert && pos < (int)strlen(txt) ) { - for (int i=(int)strlen(txt); i >= pos; i-- ) { + if (!insert || static_cast(strlen(txt)) < maxw) { + if (insert && pos < static_cast(strlen(txt))) { + for (int i = static_cast(strlen(txt)); i >= pos; --i) { txt[i+1]=txt[i]; } } @@ -109,7 +113,7 @@ void TextBox::update(TCOD_key_t k) { blink=blinkingDelay; break; case TCODK_RIGHT : - if (pos < (int)strlen(txt)) pos++; + if (pos < static_cast(strlen(txt))) { pos++; } if ( pos >= w ) offset = pos-w+1; blink=blinkingDelay; break; @@ -129,7 +133,7 @@ void TextBox::update(TCOD_key_t k) { blink=blinkingDelay; break; case TCODK_DELETE : - if (pos < (int)strlen(txt)) { + if (pos < static_cast(strlen(txt))) { for (uint32_t i=pos; i <= strlen(txt); i++ ) { txt[i]=txt[i+1]; } @@ -144,7 +148,7 @@ void TextBox::update(TCOD_key_t k) { break; */ case TCODK_END : - pos = (int)strlen(txt); + pos = static_cast(strlen(txt)); if ( pos >= w ) offset = pos-w+1; blink=blinkingDelay; break; diff --git a/tcod_sys/libtcod/src/libtcod/gui/textbox.hpp b/tcod_sys/libtcod/src/libtcod/gui/textbox.hpp index ba1f770fc..b734e2b29 100644 --- a/tcod_sys/libtcod/src/libtcod/gui/textbox.hpp +++ b/tcod_sys/libtcod/src/libtcod/gui/textbox.hpp @@ -1,30 +1,34 @@ -/* -* libtcod -* Copyright (c) 2008-2018 Jice & Mingos & rmtew -* All rights reserved. -* -* Redistribution and use in source and binary forms, with or without -* modification, are permitted provided that the following conditions are met: -* * Redistributions of source code must retain the above copyright -* notice, this list of conditions and the following disclaimer. -* * Redistributions in binary form must reproduce the above copyright -* notice, this list of conditions and the following disclaimer in the -* documentation and/or other materials provided with the distribution. -* * The name of Jice or Mingos may not be used to endorse or promote -* products derived from this software without specific prior written -* permission. -* -* THIS SOFTWARE IS PROVIDED BY JICE, MINGOS AND RMTEW ``AS IS'' AND ANY -* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED -* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE -* DISCLAIMED. IN NO EVENT SHALL JICE, MINGOS OR RMTEW BE LIABLE FOR ANY -* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES -* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; -* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND -* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS -* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. -*/ +/* BSD 3-Clause License + * + * Copyright © 2008-2019, Jice and the libtcod contributors. + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions are met: + * + * 1. Redistributions of source code must retain the above copyright notice, + * this list of conditions and the following disclaimer. + * + * 2. Redistributions in binary form must reproduce the above copyright notice, + * this list of conditions and the following disclaimer in the documentation + * and/or other materials provided with the distribution. + * + * 3. Neither the name of the copyright holder nor the names of its + * contributors may be used to endorse or promote products derived from + * this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE + * POSSIBILITY OF SUCH DAMAGE. + */ #ifndef TCOD_GUI_TEXTBOX_HPP #define TCOD_GUI_TEXTBOX_HPP #include "widget.hpp" diff --git a/tcod_sys/libtcod/src/libtcod/gui/togglebutton.cpp b/tcod_sys/libtcod/src/libtcod/gui/togglebutton.cpp index b07f75164..f260bb597 100644 --- a/tcod_sys/libtcod/src/libtcod/gui/togglebutton.cpp +++ b/tcod_sys/libtcod/src/libtcod/gui/togglebutton.cpp @@ -1,30 +1,34 @@ -/* -* libtcod -* Copyright (c) 2008-2018 Jice & Mingos & rmtew -* All rights reserved. -* -* Redistribution and use in source and binary forms, with or without -* modification, are permitted provided that the following conditions are met: -* * Redistributions of source code must retain the above copyright -* notice, this list of conditions and the following disclaimer. -* * Redistributions in binary form must reproduce the above copyright -* notice, this list of conditions and the following disclaimer in the -* documentation and/or other materials provided with the distribution. -* * The name of Jice or Mingos may not be used to endorse or promote -* products derived from this software without specific prior written -* permission. -* -* THIS SOFTWARE IS PROVIDED BY JICE, MINGOS AND RMTEW ``AS IS'' AND ANY -* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED -* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE -* DISCLAIMED. IN NO EVENT SHALL JICE, MINGOS OR RMTEW BE LIABLE FOR ANY -* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES -* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; -* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND -* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS -* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. -*/ +/* BSD 3-Clause License + * + * Copyright © 2008-2019, Jice and the libtcod contributors. + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions are met: + * + * 1. Redistributions of source code must retain the above copyright notice, + * this list of conditions and the following disclaimer. + * + * 2. Redistributions in binary form must reproduce the above copyright notice, + * this list of conditions and the following disclaimer in the documentation + * and/or other materials provided with the distribution. + * + * 3. Neither the name of the copyright holder nor the names of its + * contributors may be used to endorse or promote products derived from + * this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE + * POSSIBILITY OF SUCH DAMAGE. + */ #include "togglebutton.hpp" #include diff --git a/tcod_sys/libtcod/src/libtcod/gui/togglebutton.hpp b/tcod_sys/libtcod/src/libtcod/gui/togglebutton.hpp index 9123066e0..6210ee0b2 100644 --- a/tcod_sys/libtcod/src/libtcod/gui/togglebutton.hpp +++ b/tcod_sys/libtcod/src/libtcod/gui/togglebutton.hpp @@ -1,30 +1,34 @@ -/* -* libtcod -* Copyright (c) 2008-2018 Jice & Mingos & rmtew -* All rights reserved. -* -* Redistribution and use in source and binary forms, with or without -* modification, are permitted provided that the following conditions are met: -* * Redistributions of source code must retain the above copyright -* notice, this list of conditions and the following disclaimer. -* * Redistributions in binary form must reproduce the above copyright -* notice, this list of conditions and the following disclaimer in the -* documentation and/or other materials provided with the distribution. -* * The name of Jice or Mingos may not be used to endorse or promote -* products derived from this software without specific prior written -* permission. -* -* THIS SOFTWARE IS PROVIDED BY JICE, MINGOS AND RMTEW ``AS IS'' AND ANY -* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED -* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE -* DISCLAIMED. IN NO EVENT SHALL JICE, MINGOS OR RMTEW BE LIABLE FOR ANY -* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES -* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; -* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND -* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS -* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. -*/ +/* BSD 3-Clause License + * + * Copyright © 2008-2019, Jice and the libtcod contributors. + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions are met: + * + * 1. Redistributions of source code must retain the above copyright notice, + * this list of conditions and the following disclaimer. + * + * 2. Redistributions in binary form must reproduce the above copyright notice, + * this list of conditions and the following disclaimer in the documentation + * and/or other materials provided with the distribution. + * + * 3. Neither the name of the copyright holder nor the names of its + * contributors may be used to endorse or promote products derived from + * this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE + * POSSIBILITY OF SUCH DAMAGE. + */ #ifndef TCOD_GUI_TOGGLEBUTTON_HPP #define TCOD_GUI_TOGGLEBUTTON_HPP #include "button.hpp" diff --git a/tcod_sys/libtcod/src/libtcod/gui/toolbar.cpp b/tcod_sys/libtcod/src/libtcod/gui/toolbar.cpp index c0a5eeceb..c192f2546 100644 --- a/tcod_sys/libtcod/src/libtcod/gui/toolbar.cpp +++ b/tcod_sys/libtcod/src/libtcod/gui/toolbar.cpp @@ -1,33 +1,38 @@ -/* -* libtcod -* Copyright (c) 2008-2018 Jice & Mingos & rmtew -* All rights reserved. -* -* Redistribution and use in source and binary forms, with or without -* modification, are permitted provided that the following conditions are met: -* * Redistributions of source code must retain the above copyright -* notice, this list of conditions and the following disclaimer. -* * Redistributions in binary form must reproduce the above copyright -* notice, this list of conditions and the following disclaimer in the -* documentation and/or other materials provided with the distribution. -* * The name of Jice or Mingos may not be used to endorse or promote -* products derived from this software without specific prior written -* permission. -* -* THIS SOFTWARE IS PROVIDED BY JICE, MINGOS AND RMTEW ``AS IS'' AND ANY -* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED -* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE -* DISCLAIMED. IN NO EVENT SHALL JICE, MINGOS OR RMTEW BE LIABLE FOR ANY -* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES -* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; -* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND -* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS -* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. -*/ +/* BSD 3-Clause License + * + * Copyright © 2008-2019, Jice and the libtcod contributors. + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions are met: + * + * 1. Redistributions of source code must retain the above copyright notice, + * this list of conditions and the following disclaimer. + * + * 2. Redistributions in binary form must reproduce the above copyright notice, + * this list of conditions and the following disclaimer in the documentation + * and/or other materials provided with the distribution. + * + * 3. Neither the name of the copyright holder nor the names of its + * contributors may be used to endorse or promote products derived from + * this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE + * POSSIBILITY OF SUCH DAMAGE. + */ #include "toolbar.hpp" #include +#include class Separator : public Widget { public : @@ -42,12 +47,14 @@ public : free(txt); } } - void computeSize() { - w = (txt ? (int)strlen(txt)+2 : 0 ); - } - void expand(int width, int height) { - if ( w < width ) w=width; - } + void computeSize() + { + w = txt ? static_cast(strlen(txt) + 2) : 0; + } + void expand(int width, int) + { + w = std::max(w, width); + } void render() { con->setDefaultBackground(back); con->setDefaultForeground(fore); @@ -65,7 +72,7 @@ ToolBar::ToolBar(int x, int y, const char *name, const char *tip) : Container(x,y,0,2),name(NULL),fixedWidth(0) { if ( name ) { this->name = TCOD_strdup(name); - w = (int)strlen(name)+4; + w = static_cast(strlen(name) + 4); } if ( tip ) setTip(tip); } @@ -74,7 +81,7 @@ ToolBar::ToolBar(int x, int y, int w, const char *name, const char *tip) : Container(x,y,w,2),name(NULL),fixedWidth(w) { if ( name ) { this->name = TCOD_strdup(name); - fixedWidth = w = MAX((int)strlen(name)+4,w); + fixedWidth = w = std::max(static_cast(strlen(name) + 4), w); } if ( tip ) setTip(tip); } @@ -87,7 +94,7 @@ void ToolBar::setName(const char *name) { if ( this->name ) free(this->name); if ( name ) { this->name = TCOD_strdup(name); - fixedWidth = MAX((int)strlen(name)+4,fixedWidth); + fixedWidth = std::max(static_cast(strlen(name) + 4), fixedWidth); } else { name=NULL; } @@ -102,7 +109,7 @@ void ToolBar::render() { void ToolBar::computeSize() { int cury=y+1; - w=name ? (int)strlen(name)+4 : 2; + w = name ? static_cast(strlen(name) + 4) : 2; for (Widget **wid=content.begin(); wid != content.end(); wid ++ ) { if ( (*wid)->isVisible() ) { (*wid)->x=x+1; diff --git a/tcod_sys/libtcod/src/libtcod/gui/toolbar.hpp b/tcod_sys/libtcod/src/libtcod/gui/toolbar.hpp index 988a6fc78..78d812ae7 100644 --- a/tcod_sys/libtcod/src/libtcod/gui/toolbar.hpp +++ b/tcod_sys/libtcod/src/libtcod/gui/toolbar.hpp @@ -1,30 +1,34 @@ -/* -* libtcod -* Copyright (c) 2008-2018 Jice & Mingos & rmtew -* All rights reserved. -* -* Redistribution and use in source and binary forms, with or without -* modification, are permitted provided that the following conditions are met: -* * Redistributions of source code must retain the above copyright -* notice, this list of conditions and the following disclaimer. -* * Redistributions in binary form must reproduce the above copyright -* notice, this list of conditions and the following disclaimer in the -* documentation and/or other materials provided with the distribution. -* * The name of Jice or Mingos may not be used to endorse or promote -* products derived from this software without specific prior written -* permission. -* -* THIS SOFTWARE IS PROVIDED BY JICE, MINGOS AND RMTEW ``AS IS'' AND ANY -* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED -* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE -* DISCLAIMED. IN NO EVENT SHALL JICE, MINGOS OR RMTEW BE LIABLE FOR ANY -* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES -* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; -* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND -* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS -* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. -*/ +/* BSD 3-Clause License + * + * Copyright © 2008-2019, Jice and the libtcod contributors. + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions are met: + * + * 1. Redistributions of source code must retain the above copyright notice, + * this list of conditions and the following disclaimer. + * + * 2. Redistributions in binary form must reproduce the above copyright notice, + * this list of conditions and the following disclaimer in the documentation + * and/or other materials provided with the distribution. + * + * 3. Neither the name of the copyright holder nor the names of its + * contributors may be used to endorse or promote products derived from + * this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE + * POSSIBILITY OF SUCH DAMAGE. + */ #ifndef TCOD_GUI_TOOLBAR_HPP #define TCOD_GUI_TOOLBAR_HPP #include "container.hpp" diff --git a/tcod_sys/libtcod/src/libtcod/gui/vbox.cpp b/tcod_sys/libtcod/src/libtcod/gui/vbox.cpp index 92a306cd5..5b4de7ed3 100644 --- a/tcod_sys/libtcod/src/libtcod/gui/vbox.cpp +++ b/tcod_sys/libtcod/src/libtcod/gui/vbox.cpp @@ -1,30 +1,34 @@ -/* -* libtcod -* Copyright (c) 2008-2018 Jice & Mingos & rmtew -* All rights reserved. -* -* Redistribution and use in source and binary forms, with or without -* modification, are permitted provided that the following conditions are met: -* * Redistributions of source code must retain the above copyright -* notice, this list of conditions and the following disclaimer. -* * Redistributions in binary form must reproduce the above copyright -* notice, this list of conditions and the following disclaimer in the -* documentation and/or other materials provided with the distribution. -* * The name of Jice or Mingos may not be used to endorse or promote -* products derived from this software without specific prior written -* permission. -* -* THIS SOFTWARE IS PROVIDED BY JICE, MINGOS AND RMTEW ``AS IS'' AND ANY -* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED -* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE -* DISCLAIMED. IN NO EVENT SHALL JICE, MINGOS OR RMTEW BE LIABLE FOR ANY -* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES -* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; -* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND -* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS -* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. -*/ +/* BSD 3-Clause License + * + * Copyright © 2008-2019, Jice and the libtcod contributors. + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions are met: + * + * 1. Redistributions of source code must retain the above copyright notice, + * this list of conditions and the following disclaimer. + * + * 2. Redistributions in binary form must reproduce the above copyright notice, + * this list of conditions and the following disclaimer in the documentation + * and/or other materials provided with the distribution. + * + * 3. Neither the name of the copyright holder nor the names of its + * contributors may be used to endorse or promote products derived from + * this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE + * POSSIBILITY OF SUCH DAMAGE. + */ #include "vbox.hpp" void VBox::computeSize() { diff --git a/tcod_sys/libtcod/src/libtcod/gui/vbox.hpp b/tcod_sys/libtcod/src/libtcod/gui/vbox.hpp index 6a0a1e933..80aa42641 100644 --- a/tcod_sys/libtcod/src/libtcod/gui/vbox.hpp +++ b/tcod_sys/libtcod/src/libtcod/gui/vbox.hpp @@ -1,30 +1,34 @@ -/* -* libtcod -* Copyright (c) 2008-2018 Jice & Mingos & rmtew -* All rights reserved. -* -* Redistribution and use in source and binary forms, with or without -* modification, are permitted provided that the following conditions are met: -* * Redistributions of source code must retain the above copyright -* notice, this list of conditions and the following disclaimer. -* * Redistributions in binary form must reproduce the above copyright -* notice, this list of conditions and the following disclaimer in the -* documentation and/or other materials provided with the distribution. -* * The name of Jice or Mingos may not be used to endorse or promote -* products derived from this software without specific prior written -* permission. -* -* THIS SOFTWARE IS PROVIDED BY JICE, MINGOS AND RMTEW ``AS IS'' AND ANY -* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED -* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE -* DISCLAIMED. IN NO EVENT SHALL JICE, MINGOS OR RMTEW BE LIABLE FOR ANY -* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES -* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; -* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND -* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS -* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. -*/ +/* BSD 3-Clause License + * + * Copyright © 2008-2019, Jice and the libtcod contributors. + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions are met: + * + * 1. Redistributions of source code must retain the above copyright notice, + * this list of conditions and the following disclaimer. + * + * 2. Redistributions in binary form must reproduce the above copyright notice, + * this list of conditions and the following disclaimer in the documentation + * and/or other materials provided with the distribution. + * + * 3. Neither the name of the copyright holder nor the names of its + * contributors may be used to endorse or promote products derived from + * this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE + * POSSIBILITY OF SUCH DAMAGE. + */ #ifndef TCOD_GUI_VBOX_HPP #define TCOD_GUI_VBOX_HPP #include "container.hpp" diff --git a/tcod_sys/libtcod/src/libtcod/gui/widget.cpp b/tcod_sys/libtcod/src/libtcod/gui/widget.cpp index 0a19b4e92..1ff36d42e 100644 --- a/tcod_sys/libtcod/src/libtcod/gui/widget.cpp +++ b/tcod_sys/libtcod/src/libtcod/gui/widget.cpp @@ -1,30 +1,34 @@ -/* -* libtcod -* Copyright (c) 2008-2018 Jice & Mingos & rmtew -* All rights reserved. -* -* Redistribution and use in source and binary forms, with or without -* modification, are permitted provided that the following conditions are met: -* * Redistributions of source code must retain the above copyright -* notice, this list of conditions and the following disclaimer. -* * Redistributions in binary form must reproduce the above copyright -* notice, this list of conditions and the following disclaimer in the -* documentation and/or other materials provided with the distribution. -* * The name of Jice or Mingos may not be used to endorse or promote -* products derived from this software without specific prior written -* permission. -* -* THIS SOFTWARE IS PROVIDED BY JICE, MINGOS AND RMTEW ``AS IS'' AND ANY -* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED -* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE -* DISCLAIMED. IN NO EVENT SHALL JICE, MINGOS OR RMTEW BE LIABLE FOR ANY -* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES -* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; -* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND -* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS -* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. -*/ +/* BSD 3-Clause License + * + * Copyright © 2008-2019, Jice and the libtcod contributors. + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions are met: + * + * 1. Redistributions of source code must retain the above copyright notice, + * this list of conditions and the following disclaimer. + * + * 2. Redistributions in binary form must reproduce the above copyright notice, + * this list of conditions and the following disclaimer in the documentation + * and/or other materials provided with the distribution. + * + * 3. Neither the name of the copyright holder nor the names of its + * contributors may be used to endorse or promote products derived from + * this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE + * POSSIBILITY OF SUCH DAMAGE. + */ #include "widget.hpp" #include @@ -74,42 +78,40 @@ void Widget::setConsole(TCODConsole *console) { con=console; } -void Widget::update(const TCOD_key_t k) { - bool curs=TCODMouse::isCursorVisible(); - if ( curs ) { - if ( mouse.cx >= x && mouse.cx < x+w && mouse.cy >= y && mouse.cy < y+h ) { - if ( ! mouseIn ) { - mouseIn = true; - onMouseIn(); - } - if ( focus != this ) { - focus=this; - } - } else { - if ( mouseIn ) { - mouseIn = false; - onMouseOut(); - } - mouseL=false; - if ( this == focus ) { - focus = NULL; - } - } - } - if ( mouseIn || (! curs && this == focus ) ) { - if ( mouse.lbutton && ! mouseL ) { - mouseL = true; - onButtonPress(); - } else if (! mouse.lbutton && mouseL ) { - onButtonRelease(); - keyboardFocus=NULL; - if ( mouseL ) onButtonClick(); - mouseL=false; - } else if ( mouse.lbutton_pressed ) { - keyboardFocus=NULL; - onButtonClick(); - } - } +void Widget::update(const TCOD_key_t) +{ + bool curs = TCODMouse::isCursorVisible(); + if (curs) { + if (mouse.cx >= x && mouse.cx < x + w + && mouse.cy >= y && mouse.cy < y + h) { + if (!mouseIn) { + mouseIn = true; + onMouseIn(); + } + focus = this; + } else { + if (mouseIn) { + mouseIn = false; + onMouseOut(); + } + mouseL = false; + if (this == focus) { focus = NULL; } + } + } + if (mouseIn || (!curs && this == focus)) { + if (mouse.lbutton && !mouseL) { + mouseL = true; + onButtonPress(); + } else if (!mouse.lbutton && mouseL) { + onButtonRelease(); + keyboardFocus = NULL; + if (mouseL) { onButtonClick(); } + mouseL = false; + } else if (mouse.lbutton_pressed) { + keyboardFocus = NULL; + onButtonClick(); + } + } } void Widget::updateWidgetsIntern(const TCOD_key_t k) { diff --git a/tcod_sys/libtcod/src/libtcod/gui/widget.hpp b/tcod_sys/libtcod/src/libtcod/gui/widget.hpp index 2afc02f1e..2a179caef 100644 --- a/tcod_sys/libtcod/src/libtcod/gui/widget.hpp +++ b/tcod_sys/libtcod/src/libtcod/gui/widget.hpp @@ -1,30 +1,34 @@ -/* -* libtcod -* Copyright (c) 2008-2018 Jice & Mingos & rmtew -* All rights reserved. -* -* Redistribution and use in source and binary forms, with or without -* modification, are permitted provided that the following conditions are met: -* * Redistributions of source code must retain the above copyright -* notice, this list of conditions and the following disclaimer. -* * Redistributions in binary form must reproduce the above copyright -* notice, this list of conditions and the following disclaimer in the -* documentation and/or other materials provided with the distribution. -* * The name of Jice or Mingos may not be used to endorse or promote -* products derived from this software without specific prior written -* permission. -* -* THIS SOFTWARE IS PROVIDED BY JICE, MINGOS AND RMTEW ``AS IS'' AND ANY -* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED -* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE -* DISCLAIMED. IN NO EVENT SHALL JICE, MINGOS OR RMTEW BE LIABLE FOR ANY -* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES -* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; -* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND -* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS -* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. -*/ +/* BSD 3-Clause License + * + * Copyright © 2008-2019, Jice and the libtcod contributors. + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions are met: + * + * 1. Redistributions of source code must retain the above copyright notice, + * this list of conditions and the following disclaimer. + * + * 2. Redistributions in binary form must reproduce the above copyright notice, + * this list of conditions and the following disclaimer in the documentation + * and/or other materials provided with the distribution. + * + * 3. Neither the name of the copyright holder nor the names of its + * contributors may be used to endorse or promote products derived from + * this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE + * POSSIBILITY OF SUCH DAMAGE. + */ #ifndef TCOD_GUI_WIDGET_HPP #define TCOD_GUI_WIDGET_HPP #include "gui_portability.hpp" @@ -57,7 +61,7 @@ public : static void renderWidgets(); static TCOD_mouse_t mouse; static TCODColor fore; - virtual void expand(int width, int height) {} + virtual void expand(int, int) {} // parameters: width, height protected : friend class StatusBar; friend class ToolBar; diff --git a/tcod_sys/libtcod/src/libtcod/heightmap.cpp b/tcod_sys/libtcod/src/libtcod/heightmap.cpp index 7afb75a6c..db1cce24c 100644 --- a/tcod_sys/libtcod/src/libtcod/heightmap.cpp +++ b/tcod_sys/libtcod/src/libtcod/heightmap.cpp @@ -1,39 +1,45 @@ -/* -* libtcod -* Copyright (c) 2008-2018 Jice & Mingos & rmtew -* All rights reserved. -* -* Redistribution and use in source and binary forms, with or without -* modification, are permitted provided that the following conditions are met: -* * Redistributions of source code must retain the above copyright -* notice, this list of conditions and the following disclaimer. -* * Redistributions in binary form must reproduce the above copyright -* notice, this list of conditions and the following disclaimer in the -* documentation and/or other materials provided with the distribution. -* * The name of Jice or Mingos may not be used to endorse or promote -* products derived from this software without specific prior written -* permission. -* -* THIS SOFTWARE IS PROVIDED BY JICE, MINGOS AND RMTEW ``AS IS'' AND ANY -* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED -* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE -* DISCLAIMED. IN NO EVENT SHALL JICE, MINGOS OR RMTEW BE LIABLE FOR ANY -* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES -* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; -* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND -* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS -* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. -*/ +/* BSD 3-Clause License + * + * Copyright © 2008-2019, Jice and the libtcod contributors. + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions are met: + * + * 1. Redistributions of source code must retain the above copyright notice, + * this list of conditions and the following disclaimer. + * + * 2. Redistributions in binary form must reproduce the above copyright notice, + * this list of conditions and the following disclaimer in the documentation + * and/or other materials provided with the distribution. + * + * 3. Neither the name of the copyright holder nor the names of its + * contributors may be used to endorse or promote products derived from + * this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE + * POSSIBILITY OF SUCH DAMAGE. + */ #include "heightmap.hpp" #include #include -TCODHeightMap::TCODHeightMap(int w, int h) : w(w),h(h) { - values = new float[w*h]; - memset(values,0,sizeof(float)*w*h); +TCODHeightMap::TCODHeightMap(int width, int height) +: w(width), h(height) +{ + values = new float[w * h]; + memset(values, 0, sizeof(float) * w * h); } TCODHeightMap::~TCODHeightMap() { delete [] values; diff --git a/tcod_sys/libtcod/src/libtcod/heightmap.h b/tcod_sys/libtcod/src/libtcod/heightmap.h index e65c211ec..669ddcae4 100644 --- a/tcod_sys/libtcod/src/libtcod/heightmap.h +++ b/tcod_sys/libtcod/src/libtcod/heightmap.h @@ -1,30 +1,34 @@ -/* -* libtcod -* Copyright (c) 2008-2018 Jice & Mingos & rmtew -* All rights reserved. -* -* Redistribution and use in source and binary forms, with or without -* modification, are permitted provided that the following conditions are met: -* * Redistributions of source code must retain the above copyright -* notice, this list of conditions and the following disclaimer. -* * Redistributions in binary form must reproduce the above copyright -* notice, this list of conditions and the following disclaimer in the -* documentation and/or other materials provided with the distribution. -* * The name of Jice or Mingos may not be used to endorse or promote -* products derived from this software without specific prior written -* permission. -* -* THIS SOFTWARE IS PROVIDED BY JICE, MINGOS AND RMTEW ``AS IS'' AND ANY -* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED -* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE -* DISCLAIMED. IN NO EVENT SHALL JICE, MINGOS OR RMTEW BE LIABLE FOR ANY -* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES -* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; -* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND -* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS -* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. -*/ +/* BSD 3-Clause License + * + * Copyright © 2008-2019, Jice and the libtcod contributors. + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions are met: + * + * 1. Redistributions of source code must retain the above copyright notice, + * this list of conditions and the following disclaimer. + * + * 2. Redistributions in binary form must reproduce the above copyright notice, + * this list of conditions and the following disclaimer in the documentation + * and/or other materials provided with the distribution. + * + * 3. Neither the name of the copyright holder nor the names of its + * contributors may be used to endorse or promote products derived from + * this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE + * POSSIBILITY OF SUCH DAMAGE. + */ #ifndef _TCOD_HEIGHTMAP_H #define _TCOD_HEIGHTMAP_H @@ -72,6 +76,7 @@ TCODLIB_API void TCOD_heightmap_add_voronoi(TCOD_heightmap_t *hm, int nbPoints, TCODLIB_API void TCOD_heightmap_mid_point_displacement(TCOD_heightmap_t *hm, TCOD_random_t rnd, float roughness); TCODLIB_API void TCOD_heightmap_add_fbm(TCOD_heightmap_t *hm, TCOD_noise_t noise,float mulx, float muly, float addx, float addy, float octaves, float delta, float scale); TCODLIB_API void TCOD_heightmap_scale_fbm(TCOD_heightmap_t *hm, TCOD_noise_t noise,float mulx, float muly, float addx, float addy, float octaves, float delta, float scale); +TCOD_DEPRECATED("This function is not implemented.") TCODLIB_API void TCOD_heightmap_islandify(TCOD_heightmap_t *hm, float seaLevel,TCOD_random_t rnd); #ifdef __cplusplus } diff --git a/tcod_sys/libtcod/src/libtcod/heightmap.hpp b/tcod_sys/libtcod/src/libtcod/heightmap.hpp index e7b0643d4..1843eb6c3 100644 --- a/tcod_sys/libtcod/src/libtcod/heightmap.hpp +++ b/tcod_sys/libtcod/src/libtcod/heightmap.hpp @@ -1,30 +1,34 @@ -/* -* libtcod -* Copyright (c) 2008-2018 Jice & Mingos & rmtew -* All rights reserved. -* -* Redistribution and use in source and binary forms, with or without -* modification, are permitted provided that the following conditions are met: -* * Redistributions of source code must retain the above copyright -* notice, this list of conditions and the following disclaimer. -* * Redistributions in binary form must reproduce the above copyright -* notice, this list of conditions and the following disclaimer in the -* documentation and/or other materials provided with the distribution. -* * The name of Jice or Mingos may not be used to endorse or promote -* products derived from this software without specific prior written -* permission. -* -* THIS SOFTWARE IS PROVIDED BY JICE, MINGOS AND RMTEW ``AS IS'' AND ANY -* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED -* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE -* DISCLAIMED. IN NO EVENT SHALL JICE, MINGOS OR RMTEW BE LIABLE FOR ANY -* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES -* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; -* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND -* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS -* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. -*/ +/* BSD 3-Clause License + * + * Copyright © 2008-2019, Jice and the libtcod contributors. + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions are met: + * + * 1. Redistributions of source code must retain the above copyright notice, + * this list of conditions and the following disclaimer. + * + * 2. Redistributions in binary form must reproduce the above copyright notice, + * this list of conditions and the following disclaimer in the documentation + * and/or other materials provided with the distribution. + * + * 3. Neither the name of the copyright holder nor the names of its + * contributors may be used to endorse or promote products derived from + * this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE + * POSSIBILITY OF SUCH DAMAGE. + */ #ifndef _TCOD_HEIGHTMAP_HPP #define _TCOD_HEIGHTMAP_HPP @@ -66,7 +70,7 @@ public : map=libtcod.heightmap_new(50,50) print map.w, map.h */ - TCODHeightMap(int w, int h); + TCODHeightMap(int width, int height); /** @PageName heightmap_init diff --git a/tcod_sys/libtcod/src/libtcod/heightmap_c.c b/tcod_sys/libtcod/src/libtcod/heightmap_c.c index bf7a7a6a5..90018b23e 100644 --- a/tcod_sys/libtcod/src/libtcod/heightmap_c.c +++ b/tcod_sys/libtcod/src/libtcod/heightmap_c.c @@ -1,30 +1,34 @@ -/* -* libtcod -* Copyright (c) 2008-2018 Jice & Mingos & rmtew -* All rights reserved. -* -* Redistribution and use in source and binary forms, with or without -* modification, are permitted provided that the following conditions are met: -* * Redistributions of source code must retain the above copyright -* notice, this list of conditions and the following disclaimer. -* * Redistributions in binary form must reproduce the above copyright -* notice, this list of conditions and the following disclaimer in the -* documentation and/or other materials provided with the distribution. -* * The name of Jice or Mingos may not be used to endorse or promote -* products derived from this software without specific prior written -* permission. -* -* THIS SOFTWARE IS PROVIDED BY JICE, MINGOS AND RMTEW ``AS IS'' AND ANY -* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED -* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE -* DISCLAIMED. IN NO EVENT SHALL JICE, MINGOS OR RMTEW BE LIABLE FOR ANY -* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES -* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; -* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND -* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS -* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. -*/ +/* BSD 3-Clause License + * + * Copyright © 2008-2019, Jice and the libtcod contributors. + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions are met: + * + * 1. Redistributions of source code must retain the above copyright notice, + * this list of conditions and the following disclaimer. + * + * 2. Redistributions in binary form must reproduce the above copyright notice, + * this list of conditions and the following disclaimer in the documentation + * and/or other materials provided with the distribution. + * + * 3. Neither the name of the copyright holder nor the names of its + * contributors may be used to endorse or promote products derived from + * this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE + * POSSIBILITY OF SUCH DAMAGE. + */ #include "heightmap.h" #include @@ -106,7 +110,7 @@ void TCOD_heightmap_add_hill(TCOD_heightmap_t *hm, float hx, float hy, float hra float xdist=( x - hx )*( x - hx ); for (y=miny; y < maxy; y++) { float z = hradius2 - xdist - (y - hy)*(y - hy); - if ( z > 0.0 ) GET_VALUE(hm,x,y) += z * coef; + if (z > 0) { GET_VALUE(hm, x, y) += z * coef; } } } } @@ -125,7 +129,7 @@ void TCOD_heightmap_dig_hill(TCOD_heightmap_t *hm, float hx, float hy, float hra float dist=xdist + (y - hy)*(y - hy); if ( dist < hradius2 ) { float z = (hradius2 - dist) * coef; - if ( hheight > 0.0 ) { + if (hheight > 0) { if ( GET_VALUE(hm,x,y) < z ) GET_VALUE(hm,x,y) = z; } else { if ( GET_VALUE(hm,x,y) > z ) GET_VALUE(hm,x,y) = z; diff --git a/tcod_sys/libtcod/src/libtcod/image.cpp b/tcod_sys/libtcod/src/libtcod/image.cpp index bc5827509..049008ba5 100644 --- a/tcod_sys/libtcod/src/libtcod/image.cpp +++ b/tcod_sys/libtcod/src/libtcod/image.cpp @@ -1,30 +1,34 @@ -/* -* libtcod -* Copyright (c) 2008-2018 Jice & Mingos & rmtew -* All rights reserved. -* -* Redistribution and use in source and binary forms, with or without -* modification, are permitted provided that the following conditions are met: -* * Redistributions of source code must retain the above copyright -* notice, this list of conditions and the following disclaimer. -* * Redistributions in binary form must reproduce the above copyright -* notice, this list of conditions and the following disclaimer in the -* documentation and/or other materials provided with the distribution. -* * The name of Jice or Mingos may not be used to endorse or promote -* products derived from this software without specific prior written -* permission. -* -* THIS SOFTWARE IS PROVIDED BY JICE, MINGOS AND RMTEW ``AS IS'' AND ANY -* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED -* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE -* DISCLAIMED. IN NO EVENT SHALL JICE, MINGOS OR RMTEW BE LIABLE FOR ANY -* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES -* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; -* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND -* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS -* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. -*/ +/* BSD 3-Clause License + * + * Copyright © 2008-2019, Jice and the libtcod contributors. + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions are met: + * + * 1. Redistributions of source code must retain the above copyright notice, + * this list of conditions and the following disclaimer. + * + * 2. Redistributions in binary form must reproduce the above copyright notice, + * this list of conditions and the following disclaimer in the documentation + * and/or other materials provided with the distribution. + * + * 3. Neither the name of the copyright holder nor the names of its + * contributors may be used to endorse or promote products derived from + * this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE + * POSSIBILITY OF SUCH DAMAGE. + */ #include "image.hpp" #ifdef TCOD_IMAGE_SUPPORT diff --git a/tcod_sys/libtcod/src/libtcod/image.h b/tcod_sys/libtcod/src/libtcod/image.h index 0d2212d04..1dfbaf4be 100644 --- a/tcod_sys/libtcod/src/libtcod/image.h +++ b/tcod_sys/libtcod/src/libtcod/image.h @@ -1,30 +1,34 @@ -/* -* libtcod -* Copyright (c) 2008-2018 Jice & Mingos & rmtew -* All rights reserved. -* -* Redistribution and use in source and binary forms, with or without -* modification, are permitted provided that the following conditions are met: -* * Redistributions of source code must retain the above copyright -* notice, this list of conditions and the following disclaimer. -* * Redistributions in binary form must reproduce the above copyright -* notice, this list of conditions and the following disclaimer in the -* documentation and/or other materials provided with the distribution. -* * The name of Jice or Mingos may not be used to endorse or promote -* products derived from this software without specific prior written -* permission. -* -* THIS SOFTWARE IS PROVIDED BY JICE, MINGOS AND RMTEW ``AS IS'' AND ANY -* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED -* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE -* DISCLAIMED. IN NO EVENT SHALL JICE, MINGOS OR RMTEW BE LIABLE FOR ANY -* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES -* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; -* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND -* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS -* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. -*/ +/* BSD 3-Clause License + * + * Copyright © 2008-2019, Jice and the libtcod contributors. + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions are met: + * + * 1. Redistributions of source code must retain the above copyright notice, + * this list of conditions and the following disclaimer. + * + * 2. Redistributions in binary form must reproduce the above copyright notice, + * this list of conditions and the following disclaimer in the documentation + * and/or other materials provided with the distribution. + * + * 3. Neither the name of the copyright holder nor the names of its + * contributors may be used to endorse or promote products derived from + * this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE + * POSSIBILITY OF SUCH DAMAGE. + */ #ifndef _TCOD_IMAGE_H #define _TCOD_IMAGE_H @@ -38,38 +42,61 @@ #ifdef __cplusplus extern "C" { #endif -struct TCOD_Image; -typedef struct TCOD_Image *TCOD_image_t; +struct TCOD_mipmap_{ + int width, height; + float fwidth, fheight; + TCOD_color_t* buf; + bool dirty; +}; -TCODLIB_API TCOD_image_t TCOD_image_new(int width, int height); +typedef struct TCOD_Image { + struct SDL_Surface* sys_img; + int nb_mipmaps; + struct TCOD_mipmap_* mipmaps; + TCOD_color_t key_color; + bool has_key_color; +} TCOD_Image; + +typedef TCOD_Image *TCOD_image_t; + +TCODLIB_API TCOD_Image* TCOD_image_new(int width, int height); #ifdef TCOD_CONSOLE_SUPPORT -TCODLIB_API TCOD_image_t TCOD_image_from_console(TCOD_console_t console); -TCODLIB_API void TCOD_image_refresh_console(TCOD_image_t image, TCOD_console_t console); +TCODLIB_API TCOD_Image* TCOD_image_from_console(TCOD_console_t console); +TCODLIB_API void TCOD_image_refresh_console(TCOD_Image* image, TCOD_console_t console); #endif -TCODLIB_API TCOD_image_t TCOD_image_load(const char *filename); -TCODLIB_API void TCOD_image_clear(TCOD_image_t image, TCOD_color_t color); -TCODLIB_API void TCOD_image_invert(TCOD_image_t image); -TCODLIB_API void TCOD_image_hflip(TCOD_image_t image); -TCODLIB_API void TCOD_image_rotate90(TCOD_image_t image, int numRotations); -TCODLIB_API void TCOD_image_vflip(TCOD_image_t image); -TCODLIB_API void TCOD_image_scale(TCOD_image_t image, int neww, int newh); -TCODLIB_API void TCOD_image_save(TCOD_image_t image, const char *filename); -TCODLIB_API void TCOD_image_get_size(TCOD_image_t image, int *w,int *h); -TCODLIB_API TCOD_color_t TCOD_image_get_pixel(TCOD_image_t image,int x, int y); -TCODLIB_API int TCOD_image_get_alpha(TCOD_image_t image,int x, int y); -TCODLIB_API TCOD_color_t TCOD_image_get_mipmap_pixel(TCOD_image_t image,float x0,float y0, float x1, float y1); -TCODLIB_API void TCOD_image_put_pixel(TCOD_image_t image,int x, int y,TCOD_color_t col); +TCODLIB_API TCOD_Image* TCOD_image_load(const char *filename); +TCODLIB_API void TCOD_image_clear(TCOD_Image* image, TCOD_color_t color); +TCODLIB_API void TCOD_image_invert(TCOD_Image* image); +TCODLIB_API void TCOD_image_hflip(TCOD_Image* image); +TCODLIB_API void TCOD_image_rotate90(TCOD_Image* image, int numRotations); +TCODLIB_API void TCOD_image_vflip(TCOD_Image* image); +TCODLIB_API void TCOD_image_scale(TCOD_Image* image, int neww, int newh); +TCODLIB_API void TCOD_image_save(const TCOD_Image* image, const char *filename); +TCODLIB_API void TCOD_image_get_size(const TCOD_Image* image, int *w,int *h); +TCODLIB_API TCOD_color_t TCOD_image_get_pixel(const TCOD_Image* image, + int x, int y); +TCODLIB_API int TCOD_image_get_alpha(const TCOD_Image* image, int x, int y); +TCODLIB_API TCOD_color_t TCOD_image_get_mipmap_pixel( + const TCOD_Image* image, float x0, float y0, float x1, float y1); +TCODLIB_API void TCOD_image_put_pixel( + TCOD_Image* image, int x, int y, TCOD_color_t col); #ifdef TCOD_CONSOLE_SUPPORT -TCODLIB_API void TCOD_image_blit(TCOD_image_t image, TCOD_console_t console, float x, float y, - TCOD_bkgnd_flag_t bkgnd_flag, float scalex, float scaley, float angle); -TCODLIB_API void TCOD_image_blit_rect(TCOD_image_t image, TCOD_console_t console, int x, int y, int w, int h, - TCOD_bkgnd_flag_t bkgnd_flag); -TCODLIB_API void TCOD_image_blit_2x(TCOD_image_t image, TCOD_console_t dest, int dx, int dy, int sx, int sy, int w, int h); +TCODLIB_API void TCOD_image_blit( + const TCOD_Image* image, TCOD_console_t console, float x, float y, + TCOD_bkgnd_flag_t bkgnd_flag, float scalex, float scaley, float angle); +TCODLIB_API void TCOD_image_blit_rect( + const TCOD_Image* image, TCOD_console_t console, + int x, int y, int w, int h, TCOD_bkgnd_flag_t bkgnd_flag); +TCODLIB_API void TCOD_image_blit_2x( + const TCOD_Image* image, TCOD_console_t dest, + int dx, int dy, int sx, int sy, int w, int h); #endif -TCODLIB_API void TCOD_image_delete(TCOD_image_t image); -TCODLIB_API void TCOD_image_set_key_color(TCOD_image_t image, TCOD_color_t key_color); -TCODLIB_API bool TCOD_image_is_pixel_transparent(TCOD_image_t image, int x, int y); +TCODLIB_API void TCOD_image_delete(TCOD_Image* image); +TCODLIB_API void TCOD_image_set_key_color(TCOD_Image* image, + TCOD_color_t key_color); +TCODLIB_API bool TCOD_image_is_pixel_transparent( + const TCOD_Image* image, int x, int y); #ifdef __cplusplus } diff --git a/tcod_sys/libtcod/src/libtcod/image.hpp b/tcod_sys/libtcod/src/libtcod/image.hpp index 3cd960b0f..04a81e8f4 100644 --- a/tcod_sys/libtcod/src/libtcod/image.hpp +++ b/tcod_sys/libtcod/src/libtcod/image.hpp @@ -1,30 +1,34 @@ -/* -* libtcod -* Copyright (c) 2008-2018 Jice & Mingos & rmtew -* All rights reserved. -* -* Redistribution and use in source and binary forms, with or without -* modification, are permitted provided that the following conditions are met: -* * Redistributions of source code must retain the above copyright -* notice, this list of conditions and the following disclaimer. -* * Redistributions in binary form must reproduce the above copyright -* notice, this list of conditions and the following disclaimer in the -* documentation and/or other materials provided with the distribution. -* * The name of Jice or Mingos may not be used to endorse or promote -* products derived from this software without specific prior written -* permission. -* -* THIS SOFTWARE IS PROVIDED BY JICE, MINGOS AND RMTEW ``AS IS'' AND ANY -* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED -* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE -* DISCLAIMED. IN NO EVENT SHALL JICE, MINGOS OR RMTEW BE LIABLE FOR ANY -* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES -* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; -* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND -* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS -* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. -*/ +/* BSD 3-Clause License + * + * Copyright © 2008-2019, Jice and the libtcod contributors. + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions are met: + * + * 1. Redistributions of source code must retain the above copyright notice, + * this list of conditions and the following disclaimer. + * + * 2. Redistributions in binary form must reproduce the above copyright notice, + * this list of conditions and the following disclaimer in the documentation + * and/or other materials provided with the distribution. + * + * 3. Neither the name of the copyright holder nor the names of its + * contributors may be used to endorse or promote products derived from + * this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE + * POSSIBILITY OF SUCH DAMAGE. + */ #ifndef _TCOD_IMAGE_HPP #define _TCOD_IMAGE_HPP diff --git a/tcod_sys/libtcod/src/libtcod/image_c.c b/tcod_sys/libtcod/src/libtcod/image_c.c deleted file mode 100644 index 4a8348b3a..000000000 --- a/tcod_sys/libtcod/src/libtcod/image_c.c +++ /dev/null @@ -1,868 +0,0 @@ -/* -* libtcod -* Copyright (c) 2008-2018 Jice & Mingos & rmtew -* All rights reserved. -* -* Redistribution and use in source and binary forms, with or without -* modification, are permitted provided that the following conditions are met: -* * Redistributions of source code must retain the above copyright -* notice, this list of conditions and the following disclaimer. -* * Redistributions in binary form must reproduce the above copyright -* notice, this list of conditions and the following disclaimer in the -* documentation and/or other materials provided with the distribution. -* * The name of Jice or Mingos may not be used to endorse or promote -* products derived from this software without specific prior written -* permission. -* -* THIS SOFTWARE IS PROVIDED BY JICE, MINGOS AND RMTEW ``AS IS'' AND ANY -* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED -* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE -* DISCLAIMED. IN NO EVENT SHALL JICE, MINGOS OR RMTEW BE LIABLE FOR ANY -* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES -* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; -* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND -* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS -* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. -*/ -#include "portability.h" -#ifdef TCOD_IMAGE_SUPPORT -#include "image.h" - -#include -#include -#include -#include - -#include "console.h" -#include "libtcod_int.h" -#include "utility.h" - -typedef struct { - int width,height; - float fwidth,fheight; - TCOD_color_t *buf; - bool dirty; -} mipmap_t; - -struct TCOD_Image { - void *sys_img; - int nb_mipmaps; - mipmap_t *mipmaps; - TCOD_color_t key_color; - bool has_key_color; -}; - -typedef struct TCOD_Image image_data_t; - -/* -Internal libtcod optimisation, direct colour manipulation in the images primary mipmap. -*/ -TCOD_color_t *TCOD_image_get_colors(TCOD_image_t *image) { - image_data_t *img = ((image_data_t *)image); - return img->mipmaps[0].buf; -} - -void TCOD_image_get_key_data(TCOD_image_t image, bool *has_key_color, TCOD_color_t *key_color) { - image_data_t *img = ((image_data_t *)image); - *has_key_color = img->has_key_color; - *key_color = img->key_color; -} - -void TCOD_image_invalidate_mipmaps(TCOD_image_t *image) { - int i; - image_data_t *img = ((image_data_t *)image); - for (i = 1; i < img->nb_mipmaps; i++) { - img->mipmaps[i].dirty = true; - } -} - -static int TCOD_image_get_mipmap_levels(int width, int height) { - int curw=width; - int curh=height; - int nb_mipmap=0; - while ( curw > 0 && curh > 0 ) { - nb_mipmap++; - curw >>= 1; - curh >>= 1; - } - return nb_mipmap; -} - -static void TCOD_image_generate_mip(image_data_t *img, int mip) { - mipmap_t *orig=&img->mipmaps[0]; - mipmap_t *cur =&img->mipmaps[mip]; - int x,y; - if (! cur->buf) { - cur->buf=(TCOD_color_t *)calloc(sizeof(TCOD_color_t),cur->width*cur->height); - } - cur->dirty=false; - for (x=0; x < cur->width; x++) { - for (y=0; y < cur->height; y++) { - int r=0,g=0,b=0, count=0; - int sx,sy; - TCOD_color_t *col; - for (sx=(x << mip); sx < ((x+1)<width; - count++; - r+=orig->buf[offset].r; - g+=orig->buf[offset].g; - b+=orig->buf[offset].b; - } - } - r /= count; - g /= count; - b /= count; - col = &cur->buf[x+y*cur->width]; - col->r=r; - col->g=g; - col->b=b; - } - } -} - -/* -Internal way of copying rendering fg/bg color frame data. -*/ -bool TCOD_image_mipmap_copy_internal(TCOD_image_t srcImage, TCOD_image_t dstImage) { - int i; - image_data_t *img_src = (image_data_t *)srcImage; - image_data_t *img_dst = (image_data_t *)dstImage; - if (!img_src->mipmaps || img_src->sys_img || !img_dst->mipmaps || img_dst->sys_img) /* Both internal images. */ - return false; - if (img_src->mipmaps[0].width != img_dst->mipmaps[0].width || img_src->mipmaps[0].height != img_dst->mipmaps[0].height) - return false; - /* Copy all mipmaps? */ - img_dst->mipmaps[0].dirty = img_src->mipmaps[0].dirty; - memcpy(img_dst->mipmaps[0].buf, img_src->mipmaps[0].buf, sizeof(TCOD_color_t)*(img_src->mipmaps[0].width)*(img_src->mipmaps[0].height)); - for (i = 1; i < img_src->nb_mipmaps; i++) - img_dst->mipmaps[i].dirty = true; - return true; -} - -static void TCOD_image_init_mipmaps(image_data_t *img) { - int w,h,i,x,y; - float fw,fh; - if (! img->sys_img ) return; - TCOD_sys_get_image_size(img->sys_img,&w,&h); - img->nb_mipmaps=TCOD_image_get_mipmap_levels(w,h); - img->mipmaps = (mipmap_t *)calloc(sizeof(mipmap_t),img->nb_mipmaps); - img->mipmaps[0].buf = (TCOD_color_t *)calloc(sizeof(TCOD_color_t),w*h); - for (x=0; x < w; x++) { - for (y=0;y < h; y++) { - img->mipmaps[0].buf[x+y*w]=TCOD_sys_get_image_pixel(img->sys_img,x,y); - } - } - fw=(float)w; - fh=(float)h; - for ( i=0; i < img->nb_mipmaps; i++) { - img->mipmaps[i].width=w; - img->mipmaps[i].height=h; - img->mipmaps[i].fwidth=fw; - img->mipmaps[i].fheight=fh; - img->mipmaps[i].dirty=true; - w >>= 1; - h >>= 1; - fw *= 0.5f; - fh *= 0.5f; - } - img->mipmaps[0].dirty=false; -} - -void TCOD_image_clear(TCOD_image_t image, TCOD_color_t color) { - int i; - image_data_t *img=(image_data_t *)image; - if ( !img->mipmaps && !img->sys_img) return; /* no image data */ - if ( ! img->mipmaps ) { - TCOD_image_init_mipmaps(img); - } - for (i=0; i< img->mipmaps[0].width*img->mipmaps[0].height; i++) { - img->mipmaps[0].buf[i] = color; - } - for ( i=1; i < img->nb_mipmaps; i++) { - img->mipmaps[i].dirty=true; - } -} - -TCOD_image_t TCOD_image_new(int width, int height) { - int i; - float fw,fh; - image_data_t *ret=(image_data_t *)calloc(sizeof(image_data_t),1); - ret->nb_mipmaps=TCOD_image_get_mipmap_levels(width,height); - ret->mipmaps = (mipmap_t *)calloc(sizeof(mipmap_t),ret->nb_mipmaps); - ret->mipmaps[0].buf = (TCOD_color_t *)calloc(sizeof(TCOD_color_t),width*height); - - for (i=0; i< width*height; i++) { - ret->mipmaps[0].buf[i] = TCOD_black; - } - fw=(float)width; - fh=(float)height; - for ( i=0; i < ret->nb_mipmaps; i++) { - ret->mipmaps[i].width=width; - ret->mipmaps[i].height=height; - ret->mipmaps[i].fwidth=fw; - ret->mipmaps[i].fheight=fh; - width >>= 1; - height >>= 1; - fw *= 0.5f; - fh *= 0.5f; - } - return (TCOD_image_t)ret; -} - -TCOD_image_t TCOD_image_load(const char *filename) { - image_data_t *ret=(image_data_t *)calloc(sizeof(image_data_t),1); - ret->sys_img=TCOD_sys_load_image(filename); - return (TCOD_image_t)ret; -} - -void TCOD_image_get_size(TCOD_image_t image, int *w,int *h) { - image_data_t *img=(image_data_t *)image; - if ( !img->mipmaps && !img->sys_img) return; /* no image data */ - if ( img->mipmaps ) { - *w = img->mipmaps[0].width; - *h = img->mipmaps[0].height; - } else { - TCOD_sys_get_image_size(img->sys_img,w,h); - } -} - -TCOD_color_t TCOD_image_get_pixel(TCOD_image_t image,int x, int y) { - image_data_t *img=(image_data_t *)image; - if ( !img->mipmaps && !img->sys_img) return TCOD_black; /* no image data */ - if ( img->mipmaps ) { - if ( x >= 0 && x < img->mipmaps[0].width - && y >= 0 && y < img->mipmaps[0].height ) { - return img->mipmaps[0].buf[x+y*img->mipmaps[0].width]; - } else { - return TCOD_black; - } - } else { - return TCOD_sys_get_image_pixel(img->sys_img,x,y); - } -} - -int TCOD_image_get_alpha(TCOD_image_t image,int x, int y) { - image_data_t *img=(image_data_t *)image; - if ( img->sys_img ) { - return TCOD_sys_get_image_alpha(img->sys_img,x,y); - } else return 255; -} - -TCOD_color_t TCOD_image_get_mipmap_pixel(TCOD_image_t image,float x0,float y0, float x1, float y1) { - int texel_xsize,texel_ysize, texel_size, texel_x,texel_y; - int cur_size=1; - int mip=0; - image_data_t *img=(image_data_t *)image; - if ( !img->mipmaps && !img->sys_img) return TCOD_black; /* no image data */ - if (!img->mipmaps) TCOD_image_init_mipmaps(img); - texel_xsize=(int)(x1-x0); - texel_ysize=(int)(y1-y0); - texel_size=texel_xsize < texel_ysize ? texel_ysize : texel_xsize; - while ( mip < img->nb_mipmaps-1 && cur_size < texel_size ) { - mip++; - cur_size <<= 1; - } - if ( mip > 0 ) mip --; - texel_x=(int)(x0*(img->mipmaps[mip].width)/img->mipmaps[0].fwidth); - texel_y=(int)(y0*(img->mipmaps[mip].height)/img->mipmaps[0].fheight); - - if (img->mipmaps[mip].buf == NULL || img->mipmaps[mip].dirty) { - TCOD_image_generate_mip(img,mip); - } - if ( texel_x < 0 || texel_y < 0 || texel_x >= img->mipmaps[mip].width || texel_y >= img->mipmaps[mip].height ) - return TCOD_black; - return img->mipmaps[mip].buf[texel_x+texel_y*img->mipmaps[mip].width]; -} - -void TCOD_image_put_pixel(TCOD_image_t image,int x, int y,TCOD_color_t col) { - image_data_t *img=(image_data_t *)image; - if ( !img->mipmaps && !img->sys_img) return; /* no image data */ - if ( ! img->mipmaps ) { - TCOD_image_init_mipmaps(img); - } - if ( x >= 0 && x < img->mipmaps[0].width - && y >= 0 && y < img->mipmaps[0].height ) { - int mip; - img->mipmaps[0].buf[x+y*img->mipmaps[0].width] = col; - for (mip=1; mip < img->nb_mipmaps; mip++) { - img->mipmaps[mip].dirty=true; - } - } -} - -void TCOD_image_delete_internal(TCOD_image_t image) { - image_data_t *img=(image_data_t *)image; - if ( img->mipmaps ) { - int i; - for ( i=0; i < img->nb_mipmaps; i++) { - if ( img->mipmaps[i].buf ) free(img->mipmaps[i].buf); - } - free(img->mipmaps); - } - if ( img->sys_img ) { -#ifndef TCOD_BARE - TCOD_sys_delete_bitmap(img->sys_img); -#endif - } -} - -void TCOD_image_delete(TCOD_image_t image) { - TCOD_image_delete_internal(image); - free(image); -} - -bool TCOD_image_is_pixel_transparent(TCOD_image_t image, int x, int y) { - image_data_t *img=(image_data_t *)image; - TCOD_color_t col=TCOD_image_get_pixel(image,x,y); - if ( img->has_key_color && img->key_color.r == col.r - && img->key_color.g == col.g && img->key_color.b == col.b ) { - return true; - } - if ( TCOD_image_get_alpha(image,x,y) == 0 ) return true; - return false; -} - -#ifdef TCOD_CONSOLE_SUPPORT - -void TCOD_image_blit(TCOD_image_t image, TCOD_console_t console, float x, float y, - TCOD_bkgnd_flag_t bkgnd_flag, float scalex, float scaley, float angle) { - int width,height; - float rx,ry; - image_data_t *img=(image_data_t *)image; - if ( scalex == 0.0f || scaley == 0.0f || bkgnd_flag == TCOD_BKGND_NONE ) return; - TCOD_image_get_size(image,&width,&height); - rx = x - width * 0.5f; - ry = y - height * 0.5f; - if ( scalex == 1.0f && scaley == 1.0f && angle == 0.0f && rx == ((int)rx) && ry == ((int)ry)) { - /* clip the image */ - int ix = (int)(x - width*0.5f); - int iy = (int)(y - height*0.5f); - int minx=MAX(ix,0); - int miny=MAX(iy,0); - int maxx=MIN(ix+width,TCOD_console_get_width(console)); - int maxy=MIN(iy+height,TCOD_console_get_height(console)); - int offx=0,offy=0; - int cx,cy; - if ( ix < 0 ) offx=-ix; - if ( iy < 0 ) offy=-iy; - for (cx=minx; cx < maxx; cx ++) { - for (cy=miny; cy < maxy; cy ++) { - TCOD_color_t col=TCOD_image_get_pixel(image,cx-minx+offx,cy-miny+offy); - if ( !img->has_key_color || img->key_color.r != col.r - || img->key_color.g != col.g || img->key_color.b != col.b ) { - TCOD_console_set_char_background(console,cx,cy,col,bkgnd_flag); - } - } - } - } else { - float iw=width/2*scalex; - float ih=height/2*scaley; - /* get the coordinates of the image corners in the console */ - float newx_x = (float)cos(angle); - float newx_y = -(float)sin(angle); - float newy_x = newx_y; - float newy_y = -newx_x; - float x0,y0,x1,y1,x2,y2,x3,y3; /* image corners coordinates */ - int rx,ry,rw,rh; /* rectangular area in the console */ - int cx,cy; - int minx,miny,maxx,maxy; - float invscalex,invscaley; - /* 0 = P - w/2 x' +h/2 y' */ - x0 = x-iw*newx_x+ih*newy_x; - y0 = y-iw*newx_y+ih*newy_y; - /* 1 = P + w/2 x' + h/2 y' */ - x1 = x+iw*newx_x+ih*newy_x; - y1 = y+iw*newx_y+ih*newy_y; - /* 2 = P + w/2 x' - h/2 y' */ - x2 = x+iw*newx_x-ih*newy_x; - y2 = y+iw*newx_y-ih*newy_y; - /* 3 = P - w/2 x' - h/2 y' */ - x3 = x-iw*newx_x-ih*newy_x; - y3 = y-iw*newx_y-ih*newy_y; - /* get the affected rectangular area in the console */ - rx=(int)(MIN(MIN(x0,x1),MIN(x2,x3))); - ry=(int)(MIN(MIN(y0,y1),MIN(y2,y3))); - rw=(int)(MAX(MAX(x0,x1),MAX(x2,x3))) - rx; - rh=(int)(MAX(MAX(y0,y1),MAX(y2,y3))) - ry; - /* clip it */ - minx=MAX(rx,0); - miny=MAX(ry,0); - maxx=MIN(rx+rw,TCOD_console_get_width(console)); - maxy=MIN(ry+rh,TCOD_console_get_height(console)); - invscalex=1.0f / scalex; - invscaley=1.0f / scaley; - for (cx=minx; cx < maxx; cx ++) { - for (cy=miny; cy < maxy; cy ++) { - float ix,iy; - TCOD_color_t col; - /* map the console pixel to the image world */ - ix = (iw+ (cx-x) * newx_x + (cy-y) *(-newy_x))*invscalex; - iy = (ih + (cx-x) * (newx_y) - (cy-y)*newy_y)*invscaley; - col = TCOD_image_get_pixel(image,(int)(ix),(int)(iy)); - if ( !img->has_key_color || img->key_color.r != col.r - || img->key_color.g != col.g || img->key_color.b != col.b ) { - if ( scalex < 1.0f || scaley < 1.0f ) { - col = TCOD_image_get_mipmap_pixel(image,ix,iy,ix+1.0f,iy+1.0f); - } - TCOD_console_set_char_background(console,cx,cy,col,bkgnd_flag); - } - } - } - } -} - -void TCOD_image_blit_rect(TCOD_image_t image, TCOD_console_t console, int x, int y, - int w, int h, TCOD_bkgnd_flag_t bkgnd_flag) { - int width,height; - float scalex,scaley; - TCOD_image_get_size(image,&width,&height); - if ( w == -1 ) w=width; - if ( h == -1 ) h=height; - if ( w <= 0 || h <= 0 || bkgnd_flag == TCOD_BKGND_NONE ) return; - scalex = (float)(w)/width; - scaley = (float)(h)/height; - TCOD_image_blit(image,console,x+w*0.5f,y+h*0.5f,bkgnd_flag,scalex,scaley,0.0f); -} - -TCOD_image_t TCOD_image_from_console(TCOD_console_t console) { - image_data_t *ret; - void *bitmap=TCOD_sys_create_bitmap_for_console(console); - ret=(image_data_t *)calloc(sizeof(image_data_t),1); - ret->sys_img=bitmap; - TCOD_image_refresh_console((TCOD_image_t)ret,console); - return (TCOD_image_t)ret; -} - -void TCOD_image_refresh_console(TCOD_image_t image, TCOD_console_t console) { - image_data_t *img=(image_data_t *)image; - console = (console?console:TCOD_ctx.root); - /* We're copying the state and clearing part of the copy, no need to delete/free. */ - TCOD_sys_console_to_bitmap( - img->sys_img, (struct TCOD_Console*)console, NULL); -} - -#endif /* TCOD_CONSOLE_SUPPORT */ - -void TCOD_image_save(TCOD_image_t image, const char *filename) { - image_data_t *img=(image_data_t *)image; - void *bitmap=NULL; - bool must_free=false; - if ( img->sys_img ) { - bitmap=img->sys_img; - } else if ( img->mipmaps ){ - bitmap=TCOD_sys_create_bitmap(img->mipmaps[0].width, img->mipmaps[0].height, img->mipmaps[0].buf); - must_free=true; - } - if (bitmap) { - TCOD_sys_save_bitmap(bitmap, filename); - if ( must_free ) { - TCOD_sys_delete_bitmap(bitmap); - } - } -} - -void TCOD_image_set_key_color(TCOD_image_t image, TCOD_color_t key_color) { - image_data_t *img=(image_data_t *)image; - img->has_key_color=true; - img->key_color=key_color; -} - -void TCOD_image_invert(TCOD_image_t image) { - int i,mip; - int width,height; - image_data_t *img=(image_data_t *)image; - if ( !img->mipmaps && !img->sys_img) return; /* no image data */ - if ( ! img->mipmaps ) { - TCOD_image_init_mipmaps(img); - } - TCOD_image_get_size(image,&width,&height); - for (i=0; i< width*height; i++) { - TCOD_color_t col=img->mipmaps[0].buf[i]; - col.r=255-col.r; - col.g=255-col.g; - col.b=255-col.b; - img->mipmaps[0].buf[i] = col; - } - for (mip=1; mip < img->nb_mipmaps; mip++) { - img->mipmaps[mip].dirty=true; - } -} - -void TCOD_image_hflip(TCOD_image_t image) { - int px,py; - int width,height; - TCOD_image_get_size(image,&width,&height); - for (py = 0; py < height; py++ ) { - for (px = 0; px < width/2; px++ ) { - TCOD_color_t col1=TCOD_image_get_pixel(image,px,py); - TCOD_color_t col2=TCOD_image_get_pixel(image,width-1-px,py); - TCOD_image_put_pixel(image,px,py,col2); - TCOD_image_put_pixel(image,width-1-px,py,col1); - } - } -} - -void TCOD_image_vflip(TCOD_image_t image) { - int px,py; - int width,height; - TCOD_image_get_size(image,&width,&height); - for (px = 0; px < width; px++ ) { - for (py = 0; py < height/2; py++ ) { - TCOD_color_t col1=TCOD_image_get_pixel(image,px,py); - TCOD_color_t col2=TCOD_image_get_pixel(image,px,height-1-py); - TCOD_image_put_pixel(image,px,py,col2); - TCOD_image_put_pixel(image,px,height-1-py,col1); - } - } -} - -void TCOD_image_rotate90(TCOD_image_t image, int numRotations) { - int px,py; - int width,height; - numRotations = numRotations % 4; - if (numRotations == 0 ) return; - if ( numRotations < 0 ) numRotations += 4; - TCOD_image_get_size(image,&width,&height); - if (numRotations == 1) { - /* rotate 90 degrees */ - TCOD_image_t newImg=TCOD_image_new(height,width); - image_data_t *img=(image_data_t *)image; - image_data_t *img2=(image_data_t *)newImg; - for (px = 0; px < width; px++ ) { - for (py = 0; py < height; py++ ) { - TCOD_color_t col1=TCOD_image_get_pixel(image,px,py); - TCOD_image_put_pixel(newImg,height-1-py,px,col1); - } - } - TCOD_image_delete_internal(image); - /* update img with the new image content */ - img->mipmaps = img2->mipmaps; - img->sys_img=NULL; - img->nb_mipmaps=img2->nb_mipmaps; - free(img2); - } else if ( numRotations == 2 ) { - /* rotate 180 degrees */ - int maxy=height/2 + ((height & 1) == 1? 1 : 0 ); - for (px = 0; px < width; px++ ) { - for (py = 0; py < maxy; py++ ) { - if ( py != height-1-py || px < width/2 ) { - TCOD_color_t col1=TCOD_image_get_pixel(image,px,py); - TCOD_color_t col2=TCOD_image_get_pixel(image,width-1-px,height-1-py); - TCOD_image_put_pixel(image,px,py,col2); - TCOD_image_put_pixel(image,width-1-px,height-1-py,col1); - } - } - } - } else if (numRotations == 3) { - /* rotate 270 degrees */ - TCOD_image_t newImg=TCOD_image_new(height,width); - image_data_t *img=(image_data_t *)image; - image_data_t *img2=(image_data_t *)newImg; - for (px = 0; px < width; px++ ) { - for (py = 0; py < height; py++ ) { - TCOD_color_t col1=TCOD_image_get_pixel(image,px,py); - TCOD_image_put_pixel(newImg,py,width-1-px,col1); - } - } - TCOD_image_delete_internal(image); - /* update img with the new image content */ - img->mipmaps = img2->mipmaps; - img->sys_img=NULL; - img->nb_mipmaps=img2->nb_mipmaps; - free(img2); - } -} - -void TCOD_image_scale(TCOD_image_t image, int neww, int newh) { - image_data_t *img=(image_data_t *)image; - int px,py; - int width,height; - image_data_t *newimg; - TCOD_image_get_size(image,&width,&height); - if ( neww==width && newh==height ) return; - if ( neww == 0 || newh == 0 ) return; - newimg=(image_data_t *)TCOD_image_new(neww,newh); - - if ( neww < width && newh < height ) { - /* scale down image, using supersampling */ - for (py = 0; py < newh; py++ ) { - float y0 = (float)(py) * height / newh; - float y0floor = (float)floor(y0); - float y0weight = 1.0f - (y0 - y0floor); - int iy0 = (int)y0floor; - - float y1 = (float)(py+1) * height / newh; - float y1floor = (float)floor(y1-0.00001); - float y1weight = (y1 - y1floor); - int iy1 = (int)y1floor; - - for (px = 0; px < neww; px++ ) { - TCOD_color_t col; - float x0 = (float)(px) * width / neww; - float x0floor = (float)floor(x0); - float x0weight = 1.0f - (x0 - x0floor); - int ix0 = (int)x0floor; - - float x1 = (float)(px+1) * width / neww; - float x1floor = (float)floor(x1- 0.00001); - float x1weight = (x1 - x1floor); - int ix1 = (int)x1floor; - - float r=0,g=0,b=0,sumweight=0.0f; - int srcx,srcy; - /* left & right fractional edges */ - for (srcy=(int)(y0+1); srcy < (int)y1; srcy++) { - TCOD_color_t col_left=TCOD_image_get_pixel(image,ix0,srcy); - TCOD_color_t col_right=TCOD_image_get_pixel(image,ix1,srcy); - r += col_left.r * x0weight + col_right.r * x1weight; - g += col_left.g * x0weight + col_right.g * x1weight; - b += col_left.b * x0weight + col_right.b * x1weight; - sumweight += x0weight+x1weight; - } - /* top & bottom fractional edges */ - for (srcx = (int)(x0+1); srcx < (int)x1; srcx++) { - TCOD_color_t col_top=TCOD_image_get_pixel(image,srcx,iy0); - TCOD_color_t col_bottom=TCOD_image_get_pixel(image,srcx,iy1); - r += col_top.r * y0weight + col_bottom.r * y1weight; - g += col_top.g * y0weight + col_bottom.g * y1weight; - b += col_top.b * y0weight + col_bottom.b * y1weight; - sumweight += y0weight+y1weight; - } - /* center */ - for (srcy=(int)(y0+1); srcy < (int)y1; srcy++) { - for (srcx = (int)(x0+1); srcx < (int)x1; srcx++) { - TCOD_color_t col=TCOD_image_get_pixel(image,srcx,srcy); - r += col.r; - g += col.g; - b += col.b; - sumweight += 1.0f; - } - } - /* corners */ - col=TCOD_image_get_pixel(image,ix0,iy0); - r += col.r * (x0weight * y0weight); - g += col.g * (x0weight * y0weight); - b += col.b * (x0weight * y0weight); - sumweight += x0weight * y0weight; - col=TCOD_image_get_pixel(image,ix0,iy1); - r += col.r * (x0weight * y1weight); - g += col.g * (x0weight * y1weight); - b += col.b * (x0weight * y1weight); - sumweight += x0weight * y1weight; - col=TCOD_image_get_pixel(image,ix1,iy1); - r += col.r * (x1weight * y1weight); - g += col.g * (x1weight * y1weight); - b += col.b * (x1weight * y1weight); - sumweight += x1weight * y1weight; - col=TCOD_image_get_pixel(image,ix1,iy0); - r += col.r * (x1weight * y0weight); - g += col.g * (x1weight * y0weight); - b += col.b * (x1weight * y0weight); - sumweight += x1weight * y0weight; - sumweight = 1.0f / sumweight; - r = r*sumweight + 0.5f; - g = g*sumweight + 0.5f; - b = b*sumweight + 0.5f; - col.r=(int)r; - col.g=(int)g; - col.b=(int)b; - TCOD_image_put_pixel(newimg,px,py,col); - } - } - } else { - /* scale up image, using nearest neightbor */ - for (py = 0; py < newh; py++ ) { - int srcy = py * height / newh; - for (px = 0; px < neww; px++ ) { - int srcx = px * width / neww; - TCOD_color_t col=TCOD_image_get_pixel(image,srcx,srcy); - TCOD_image_put_pixel(newimg,px,py,col); - } - } - } - - /* destroy old image */ - TCOD_image_delete_internal(image); - /* update img with the new image content */ - img->mipmaps = newimg->mipmaps; - img->sys_img=NULL; - img->nb_mipmaps=newimg->nb_mipmaps; - free(newimg); -} - - -/* distance between two colors */ -int rgbdist(const TCOD_color_t *c1,const TCOD_color_t *c2) { - int dr=(int)(c1->r)-c2->r; - int dg=(int)(c1->g)-c2->g; - int db=(int)(c1->b)-c2->b; - return dr*dr+dg*dg+db*db; -} - -void getPattern(TCOD_color_t desired[4], TCOD_color_t palette[2], int *nbCols, int *ascii) { - /* adapted from Jeff Lait's code posted on r.g.r.d */ - int flag=0; - /* - pixels have following flag values : - X 1 - 2 4 - flag indicates which pixels uses foreground color (palette[1]) - */ - static int flagToAscii[8] = { - 0, - TCOD_CHAR_SUBP_NE,TCOD_CHAR_SUBP_SW,-TCOD_CHAR_SUBP_DIAG,TCOD_CHAR_SUBP_SE, - TCOD_CHAR_SUBP_E,-TCOD_CHAR_SUBP_N,-TCOD_CHAR_SUBP_NW - }; - int weight[2] = { 0, 0 }; - int i; - - /* First colour trivial. */ - palette[0] = desired[0]; - - /* Ignore all duplicates... */ - for (i = 1; i < 4; i++) { - if (desired[i].r != palette[0].r || desired[i].g != palette[0].g || desired[i].b != palette[0].b) - break; - } - - /* All the same. */ - if (i == 4) { - *nbCols=1; - return; - } - weight[0] = i; - - /* Found a second colour... */ - palette[1] = desired[i]; - weight[1] = 1; - flag |= 1<<(i-1); - *nbCols = 2; - /* remaining colours */ - i++; - while (i< 4) { - if (desired[i].r == palette[0].r && desired[i].g == palette[0].g && desired[i].b == palette[0].b) { - weight[0]++; - } else if (desired[i].r == palette[1].r && desired[i].g == palette[1].g && desired[i].b == palette[1].b) { - flag |= 1<<(i-1); - weight[1]++; - } else { - /* Bah, too many colours, */ - /* merge the two nearest */ - int dist0i=rgbdist(&desired[i], &palette[0]); - int dist1i=rgbdist(&desired[i], &palette[1]); - int dist01=rgbdist(&palette[0],&palette[1]); - if ( dist0i < dist1i ) { - if ( dist0i <= dist01 ) { - /* merge 0 and i */ - palette[0]=TCOD_color_lerp(desired[i],palette[0],weight[0]/(1.0f+weight[0])); - weight[0]++; - } else { - /* merge 0 and 1 */ - palette[0]=TCOD_color_lerp(palette[0],palette[1],(float)(weight[1])/(weight[0]+weight[1])); - weight[0]++; - palette[1]=desired[i]; - flag=1<<(i-1); - } - } else { - if ( dist1i <= dist01 ) { - /* merge 1 and i */ - palette[1]=TCOD_color_lerp(desired[i],palette[1],weight[1]/(1.0f+weight[1])); - weight[1]++; - flag|=1<<(i-1); - } else { - /* merge 0 and 1 */ - palette[0]=TCOD_color_lerp(palette[0],palette[1],(float)(weight[1])/(weight[0]+weight[1])); - weight[0]++; - palette[1]=desired[i]; - flag=1<<(i-1); - } - } - } - i++; - } - *ascii=flagToAscii[flag]; -} - -#ifdef TCOD_CONSOLE_SUPPORT - -void TCOD_image_blit_2x(TCOD_image_t image, TCOD_console_t con, int dx, int dy, int sx, int sy, int w, int h) { - TCOD_color_t grid[4]; - TCOD_color_t cols[2]; - int nbCols; - int width,height,ascii,cx,cy; - struct TCOD_Console *dat = con ? (struct TCOD_Console *)(con) : TCOD_ctx.root; - image_data_t *img=(image_data_t *)image; - int maxx,maxy; - TCOD_IFNOT(image != NULL && dat != NULL) return; - - TCOD_image_get_size(image,&width,&height); - if ( w == -1 ) w=width; - if ( h == -1 ) h=height; - - /* check that the sx,sy/w,h rectangle is inside the image */ - TCOD_ASSERT(sx >= 0 && sy >= 0 && sx+w <= width && sy+h <= height); - TCOD_IFNOT(w > 0 && h > 0) return; - - sx=MAX(0,sx); - sy=MAX(0,sy); - w = MIN(w,width-sx); - h = MIN(h,height-sy); - - maxx=dx+w/2 <= dat->w ? w : (dat->w-dx)*2; - maxy=dy+h/2 <= dat->h ? h : (dat->h-dy)*2; - /* check that the image is not blitted outside the console */ - TCOD_IFNOT(dx+maxx/2 >= 0 && dy+maxy/2 >= 0 && dx < dat->w && dy < dat->h) return; - maxx+=sx; - maxy+=sy; - - for (cx=sx; cx < maxx; cx += 2) { - for (cy=sy; cy < maxy; cy += 2) { - /* get the 2x2 super pixel colors from the image */ - int conx=dx+(cx-sx)/2; - int cony=dy+(cy-sy)/2; - TCOD_color_t consoleBack=TCOD_console_get_char_background(con,conx,cony); - grid[0]=TCOD_image_get_pixel(image,cx,cy); - if ( img->has_key_color && grid[0].r == img->key_color.r && grid[0].g == img->key_color.g && grid[0].b == img->key_color.b) - grid[0]=consoleBack; - if ( cx < maxx-1 ) { - grid[1]=TCOD_image_get_pixel(image,cx+1,cy); - if ( img->has_key_color && grid[1].r == img->key_color.r && grid[1].g == img->key_color.g && grid[1].b == img->key_color.b) - grid[1]=consoleBack; - } else grid[1]=consoleBack; - if ( cy < maxy-1 ) { - grid[2]=TCOD_image_get_pixel(image,cx,cy+1); - if ( img->has_key_color && grid[2].r == img->key_color.r && grid[2].g == img->key_color.g && grid[2].b == img->key_color.b) - grid[2]=consoleBack; - } else grid[2]=consoleBack; - if ( cx < maxx-1 && cy < maxy-1 ) { - grid[3]=TCOD_image_get_pixel(image,cx+1,cy+1); - if ( img->has_key_color && grid[3].r == img->key_color.r && grid[3].g == img->key_color.g && grid[3].b == img->key_color.b) - grid[3]=consoleBack; - } else grid[3]=consoleBack; - /* analyse color, posterize, get pattern */ - getPattern(grid,cols,&nbCols,&ascii); - if ( nbCols == 1 ) { - /* single color */ - TCOD_console_set_char_background(con,conx,cony,cols[0],TCOD_BKGND_SET); - TCOD_console_set_char(con,conx,cony,' '); - } else { - if ( ascii >= 0 ) { - TCOD_console_set_char_background(con,conx,cony,cols[0],TCOD_BKGND_SET); - TCOD_console_set_char_foreground(con,conx,cony,cols[1]); - TCOD_console_set_char(con,conx,cony,ascii); - } else { - /* negative ascii code means we need to invert back/fore colors */ - TCOD_console_set_char_background(con,conx,cony,cols[1],TCOD_BKGND_SET); - TCOD_console_set_char_foreground(con,conx,cony,cols[0]); - TCOD_console_set_char(con,conx,cony,-ascii); - } - } - } - } -} - -#endif /* TCOD_CONSOLE_SUPPORT */ - -#endif /* TCOD_IMAGE_SUPPORT */ diff --git a/tcod_sys/libtcod/src/libtcod/image_c.cpp b/tcod_sys/libtcod/src/libtcod/image_c.cpp new file mode 100644 index 000000000..8c24678c2 --- /dev/null +++ b/tcod_sys/libtcod/src/libtcod/image_c.cpp @@ -0,0 +1,909 @@ +/* BSD 3-Clause License + * + * Copyright © 2008-2019, Jice and the libtcod contributors. + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions are met: + * + * 1. Redistributions of source code must retain the above copyright notice, + * this list of conditions and the following disclaimer. + * + * 2. Redistributions in binary form must reproduce the above copyright notice, + * this list of conditions and the following disclaimer in the documentation + * and/or other materials provided with the distribution. + * + * 3. Neither the name of the copyright holder nor the names of its + * contributors may be used to endorse or promote products derived from + * this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE + * POSSIBILITY OF SUCH DAMAGE. + */ +#include "portability.h" +#ifdef TCOD_IMAGE_SUPPORT +#include "image.h" + +#include +#include +#include +#include +#include + +#include "console.h" +#include "libtcod_int.h" +#include "utility.h" + +/* +Internal libtcod optimisation, direct colour manipulation in the images primary mipmap. +*/ +TCOD_color_t *TCOD_image_get_colors(TCOD_Image* image) { + return image->mipmaps[0].buf; +} + +void TCOD_image_get_key_data(const TCOD_Image* image, bool* has_key_color, + TCOD_color_t* key_color) +{ + *has_key_color = image->has_key_color; + *key_color = image->key_color; +} + +void TCOD_image_invalidate_mipmaps(TCOD_Image* image) { + for (int i = 1; i < image->nb_mipmaps; ++i) { + image->mipmaps[i].dirty = true; + } +} + +static int TCOD_image_get_mipmap_levels(int width, int height) +{ + int curw = width; + int curh = height; + int nb_mipmap = 0; + while (curw > 0 && curh > 0) { + ++nb_mipmap; + curw >>= 1; + curh >>= 1; + } + return nb_mipmap; +} + +static void TCOD_image_generate_mip(TCOD_Image* image, int mip) { + struct TCOD_mipmap_* orig = &image->mipmaps[0]; + struct TCOD_mipmap_* cur = &image->mipmaps[mip]; + if (!cur->buf) { + cur->buf = static_cast( + calloc(sizeof(TCOD_color_t), cur->width * cur->height) + ); + } + cur->dirty = false; + for (int x = 0; x < cur->width; ++x) { + for (int y = 0; y < cur->height; ++y) { + int r = 0; + int g = 0; + int b = 0; + int count=0; + for (int sx = x << mip; sx < (x + 1) << mip; ++sx) { + for (int sy = y << mip; sy < (y + 1) << mip; ++sy) { + int offset = sx + sy * orig->width; + ++count; + r += orig->buf[offset].r; + g += orig->buf[offset].g; + b += orig->buf[offset].b; + } + } + cur->buf[x + y * cur->width] = { + static_cast(r / count), + static_cast(g / count), + static_cast(b / count), + }; + } + } +} +/* +Internal way of copying rendering fg/bg color frame data. +*/ +bool TCOD_image_mipmap_copy_internal(const TCOD_Image* img_src, + TCOD_Image* img_dst) +{ + if (!img_src->mipmaps || img_src->sys_img || !img_dst->mipmaps + || img_dst->sys_img) { // Both internal images. + return false; + } + if (img_src->mipmaps[0].width != img_dst->mipmaps[0].width + || img_src->mipmaps[0].height != img_dst->mipmaps[0].height) { + return false; + } + // Copy all mipmaps? + img_dst->mipmaps[0].dirty = img_src->mipmaps[0].dirty; + memcpy( + img_dst->mipmaps[0].buf, + img_src->mipmaps[0].buf, + (sizeof(TCOD_color_t) + * (img_src->mipmaps[0].width) * (img_src->mipmaps[0].height)) + ); + for (int i = 1; i < img_src->nb_mipmaps; ++i) { + img_dst->mipmaps[i].dirty = true; + } + return true; +} + +static void TCOD_image_init_mipmaps(TCOD_Image* image) +{ + int w, h; + if (!image->sys_img) { return; } + TCOD_sys_get_image_size(image->sys_img, &w, &h); + image->nb_mipmaps = TCOD_image_get_mipmap_levels(w, h); + image->mipmaps = static_cast( + calloc(sizeof(struct TCOD_mipmap_), image->nb_mipmaps) + ); + image->mipmaps[0].buf = static_cast( + calloc(sizeof(TCOD_color_t), w * h) + ); + for (int x = 0; x < w; ++x) { + for (int y = 0; y < h; ++y) { + image->mipmaps[0].buf[x + y * w] = + TCOD_sys_get_image_pixel(image->sys_img, x, y); + } + } + float fw = w; + float fh = h; + for (int i = 0; i < image->nb_mipmaps; ++i) { + image->mipmaps[i].width = w; + image->mipmaps[i].height = h; + image->mipmaps[i].fwidth = fw; + image->mipmaps[i].fheight = fh; + image->mipmaps[i].dirty = true; + w >>= 1; + h >>= 1; + fw *= 0.5f; + fh *= 0.5f; + } + image->mipmaps[0].dirty = false; +} + +void TCOD_image_clear(TCOD_Image* image, TCOD_color_t color) +{ + if (!image->mipmaps && !image->sys_img) { return; } /* no image data */ + if (!image->mipmaps) { + TCOD_image_init_mipmaps(image); + } + for (int i = 0; i < image->mipmaps[0].width * image->mipmaps[0].height; ++i) { + image->mipmaps[0].buf[i] = color; + } + for (int i = 1; i < image->nb_mipmaps; ++i) { + image->mipmaps[i].dirty = true; + } +} + +TCOD_Image* TCOD_image_new(int width, int height) +{ + TCOD_Image* ret=static_cast(calloc(sizeof(TCOD_Image), 1)); + ret->nb_mipmaps = TCOD_image_get_mipmap_levels(width, height); + ret->mipmaps = static_cast( + calloc(sizeof(struct TCOD_mipmap_), ret->nb_mipmaps)); + ret->mipmaps[0].buf = static_cast( + calloc(sizeof(TCOD_color_t), width * height)); + + for (int i = 0; i < width * height; ++i) { + ret->mipmaps[0].buf[i] = TCOD_black; + } + float fw = width; + float fh = height; + for (int i = 0; i < ret->nb_mipmaps; ++i) { + ret->mipmaps[i].width = width; + ret->mipmaps[i].height = height; + ret->mipmaps[i].fwidth = fw; + ret->mipmaps[i].fheight = fh; + width >>= 1; + height >>= 1; + fw *= 0.5f; + fh *= 0.5f; + } + return ret; +} + +TCOD_Image* TCOD_image_load(const char *filename) { + TCOD_Image* ret = static_cast(calloc(sizeof(TCOD_Image), 1)); + ret->sys_img = TCOD_sys_load_image(filename); + return ret; +} + +void TCOD_image_get_size(const TCOD_Image* image, int *w,int *h) +{ + if (!image->mipmaps && !image->sys_img) { return; } // no image data + if (image->mipmaps) { + *w = image->mipmaps[0].width; + *h = image->mipmaps[0].height; + } else { + TCOD_sys_get_image_size(image->sys_img, w, h); + } +} + +TCOD_color_t TCOD_image_get_pixel(const TCOD_Image* image, int x, int y) +{ + if (!image->mipmaps && !image->sys_img) { + return TCOD_black; // no image data + } + if (image->mipmaps) { + if (x >= 0 && x < image->mipmaps[0].width + && y >= 0 && y < image->mipmaps[0].height) { + return image->mipmaps[0].buf[x + y * image->mipmaps[0].width]; + } else { + return TCOD_black; + } + } else { + return TCOD_sys_get_image_pixel(image->sys_img, x, y); + } +} + +int TCOD_image_get_alpha(const TCOD_Image* image,int x, int y) { + + if (image->sys_img) { + return TCOD_sys_get_image_alpha(image->sys_img, x, y); + } + return 255; +} + +TCOD_color_t TCOD_image_get_mipmap_pixel( + const TCOD_Image* image, float x0, float y0, float x1, float y1) { + int cur_size = 1; + int mip = 0; + if (!image->mipmaps && !image->sys_img) { + return TCOD_black; // no image data + } + if (!image->mipmaps) TCOD_image_init_mipmaps(const_cast(image)); + int texel_xsize = static_cast(x1 - x0); + int texel_ysize = static_cast(y1 - y0); + int texel_size = texel_xsize < texel_ysize ? texel_ysize : texel_xsize; + while (mip < image->nb_mipmaps - 1 && cur_size < texel_size) { + ++mip; + cur_size <<= 1; + } + if (mip > 0) { --mip; } + int texel_x = static_cast( + x0 * (image->mipmaps[mip].width) / image->mipmaps[0].fwidth + ); + int texel_y = static_cast( + y0 * (image->mipmaps[mip].height) / image->mipmaps[0].fheight + ); + if (image->mipmaps[mip].buf == NULL || image->mipmaps[mip].dirty) { + TCOD_image_generate_mip(const_cast(image), mip); + } + if (texel_x < 0 || texel_y < 0 + || texel_x >= image->mipmaps[mip].width + || texel_y >= image->mipmaps[mip].height) { + return TCOD_black; + } + return image->mipmaps[mip].buf[texel_x + + texel_y * image->mipmaps[mip].width]; +} + +void TCOD_image_put_pixel(TCOD_Image* image, int x, int y, TCOD_color_t col) { + if (!image->mipmaps && !image->sys_img) { return; } /* no image data */ + if (!image->mipmaps) { + TCOD_image_init_mipmaps(image); + } + if (x >= 0 && x < image->mipmaps[0].width + && y >= 0 && y < image->mipmaps[0].height) { + image->mipmaps[0].buf[x + y * image->mipmaps[0].width] = col; + for (int mip = 1; mip < image->nb_mipmaps; ++mip) { + image->mipmaps[mip].dirty = true; + } + } +} + +void TCOD_image_delete_internal(TCOD_Image* image) { + if (image->mipmaps) { + for (int i=0; i < image->nb_mipmaps; ++i) { + if (image->mipmaps[i].buf) { free(image->mipmaps[i].buf); } + } + free(image->mipmaps); + } + if (image->sys_img) { +#ifndef TCOD_BARE + TCOD_sys_delete_bitmap(image->sys_img); +#endif + } +} + +void TCOD_image_delete(TCOD_Image* image) { + TCOD_image_delete_internal(image); + free(image); +} + +bool TCOD_image_is_pixel_transparent(const TCOD_Image* image, int x, int y) { + TCOD_color_t col = TCOD_image_get_pixel(image, x, y); + if (image->has_key_color + && image->key_color.r == col.r + && image->key_color.g == col.g + && image->key_color.b == col.b) { + return true; + } + if (TCOD_image_get_alpha(image, x, y) == 0) { return true; } + return false; +} + +#ifdef TCOD_CONSOLE_SUPPORT + +void TCOD_image_blit( + const TCOD_Image* image, TCOD_console_t console, float x, float y, + TCOD_bkgnd_flag_t bkgnd_flag, float scalex, float scaley, float angle) +{ + if (scalex == 0.0f || scaley == 0.0f || bkgnd_flag == TCOD_BKGND_NONE) { + return; + } + int width, height; + TCOD_image_get_size(image, &width, &height); + float rx_ = x - width * 0.5f; + float ry_ = y - height * 0.5f; + if (scalex == 1.0f && scaley == 1.0f && angle == 0.0f + && rx_ == static_cast(rx_) && ry_ == static_cast(ry_)) { + /* clip the image */ + int ix = static_cast(x - width * 0.5f); + int iy = static_cast(y - height * 0.5f); + int minx = std::max(ix, 0); + int miny = std::max(iy, 0); + int maxx = std::min(ix + width, TCOD_console_get_width(console)); + int maxy = std::min(iy + height, TCOD_console_get_height(console)); + int offx = 0; + int offy = 0; + if (ix < 0) { offx = -ix; } + if (iy < 0) { offy = -iy; } + for (int cx = minx; cx < maxx; ++cx) { + for (int cy = miny; cy < maxy; ++cy) { + TCOD_color_t col = TCOD_image_get_pixel( + image, cx - minx + offx, cy - miny + offy); + if (!image->has_key_color + || image->key_color.r != col.r + || image->key_color.g != col.g + || image->key_color.b != col.b) { + TCOD_console_set_char_background(console, cx, cy, col, bkgnd_flag); + } + } + } + } else { + float iw = width / 2 * scalex; + float ih = height / 2 * scaley; + /* get the coordinates of the image corners in the console */ + float newx_x = std::cos(angle); + float newx_y = -std::sin(angle); + float newy_x = newx_y; + float newy_y = -newx_x; + // image corners coordinates + /* 0 = P - w/2 x' +h/2 y' */ + float x0 = x - iw * newx_x + ih * newy_x; + float y0 = y - iw * newx_y + ih * newy_y; + /* 1 = P + w/2 x' + h/2 y' */ + float x1 = x + iw * newx_x + ih * newy_x; + float y1 = y + iw * newx_y + ih * newy_y; + /* 2 = P + w/2 x' - h/2 y' */ + float x2 = x + iw * newx_x - ih * newy_x; + float y2 = y + iw * newx_y - ih * newy_y; + /* 3 = P - w/2 x' - h/2 y' */ + float x3 = x - iw * newx_x - ih * newy_x; + float y3 = y - iw * newx_y - ih * newy_y; + /* get the affected rectangular area in the console */ + int rx = std::min(std::min(x0, x1), std::min(x2, x3)); + int ry = std::min(std::min(y0, y1), std::min(y2, y3)); + int rw = std::max(std::max(x0, x1), std::max(x2, x3)) - rx; + int rh = std::max(std::max(y0, y1), std::max(y2, y3)) - ry; + /* clip it */ + int minx = std::max(rx, 0); + int miny = std::max(ry, 0); + int maxx = std::min(rx + rw, TCOD_console_get_width(console)); + int maxy = std::min(ry + rh, TCOD_console_get_height(console)); + float invscalex = 1.0f / scalex; + float invscaley = 1.0f / scaley; + for (int cx = minx; cx < maxx; ++cx) { + for (int cy = miny; cy < maxy; ++cy) { + /* map the console pixel to the image world */ + float ix = (iw + (cx - x) * newx_x + (cy - y) * (-newy_x)) * invscalex; + float iy = (ih + (cx - x) * newx_y - (cy - y) * newy_y) * invscaley; + TCOD_color_t col = TCOD_image_get_pixel(image, ix, iy); + if (!image->has_key_color + || image->key_color.r != col.r + || image->key_color.g != col.g + || image->key_color.b != col.b ) { + if (scalex < 1.0f || scaley < 1.0f) { + col = TCOD_image_get_mipmap_pixel(image, + ix, iy, ix + 1.0f, iy + 1.0f); + } + TCOD_console_set_char_background(console, cx, cy, col, bkgnd_flag); + } + } + } + } +} + +void TCOD_image_blit_rect( + const TCOD_Image* image, TCOD_console_t console, + int x, int y, int w, int h, TCOD_bkgnd_flag_t bkgnd_flag) +{ + int width, height; + TCOD_image_get_size(image, &width, &height); + if (w == -1) { w = width; } + if (h == -1) { h = height; } + if (w <= 0 || h <= 0 || bkgnd_flag == TCOD_BKGND_NONE) { return; } + float scalex = static_cast(w) / width; + float scaley = static_cast(h) / height; + TCOD_image_blit(image, console, x + w * 0.5f, y + h * 0.5f, bkgnd_flag, + scalex, scaley, 0.0f); +} + +TCOD_Image* TCOD_image_from_console(TCOD_Console* console) { + TCOD_Image* ret = static_cast(calloc(sizeof(TCOD_Image), 1)); + ret->sys_img = TCOD_sys_create_bitmap_for_console(console); + TCOD_image_refresh_console(ret, console); + return ret; +} + +void TCOD_image_refresh_console(TCOD_Image* image, TCOD_console_t console) { + /* We're copying the state and clearing part of the copy, no need to delete/free. */ + TCOD_sys_console_to_bitmap( + image->sys_img, TCOD_console_validate_(console), NULL); +} + +#endif /* TCOD_CONSOLE_SUPPORT */ + +void TCOD_image_save(const TCOD_Image* image, const char *filename) +{ + SDL_Surface* bitmap = nullptr; + bool must_free = false; + if (image->sys_img) { + bitmap = image->sys_img; + } else if (image->mipmaps){ + bitmap = TCOD_sys_create_bitmap( + image->mipmaps[0].width, + image->mipmaps[0].height, + image->mipmaps[0].buf + ); + must_free=true; + } + if (bitmap) { + TCOD_sys_save_bitmap(bitmap, filename); + if (must_free) { + TCOD_sys_delete_bitmap(bitmap); + } + } +} + +void TCOD_image_set_key_color(TCOD_Image* image, TCOD_color_t key_color) +{ + image->has_key_color = true; + image->key_color = key_color; +} + +void TCOD_image_invert(TCOD_Image* image) +{ + if (!image->mipmaps && !image->sys_img) { return; } /* no image data */ + if (!image->mipmaps) { + TCOD_image_init_mipmaps(image); + } + int width, height; + TCOD_image_get_size(image, &width, &height); + for (int i = 0; i < width * height; ++i) { + TCOD_color_t col = image->mipmaps[0].buf[i]; + col.r = 255 - col.r; + col.g = 255 - col.g; + col.b = 255 - col.b; + image->mipmaps[0].buf[i] = col; + } + for (int mip = 1; mip < image->nb_mipmaps; ++mip) { + image->mipmaps[mip].dirty = true; + } +} + +void TCOD_image_hflip(TCOD_Image* image) +{ + int width, height; + TCOD_image_get_size(image, &width, &height); + for (int py = 0; py < height; ++py) { + for (int px = 0; px < width / 2; ++px) { + TCOD_color_t col1 = TCOD_image_get_pixel(image, px, py); + TCOD_color_t col2 = TCOD_image_get_pixel(image, width - 1 - px, py); + TCOD_image_put_pixel(image, px, py, col2); + TCOD_image_put_pixel(image, width - 1 - px, py, col1); + } + } +} + +void TCOD_image_vflip(TCOD_Image* image) +{ + int width, height; + TCOD_image_get_size(image, &width, &height); + for (int px = 0; px < width; ++px) { + for (int py = 0; py < height / 2; ++py) { + TCOD_color_t col1 = TCOD_image_get_pixel(image, px, py); + TCOD_color_t col2 = TCOD_image_get_pixel(image, px, height - 1 - py); + TCOD_image_put_pixel(image, px, py, col2); + TCOD_image_put_pixel(image, px, height - 1 - py, col1); + } + } +} + +void TCOD_image_rotate90(TCOD_Image* image, int numRotations) +{ + numRotations = numRotations % 4; + if (numRotations == 0) { return; } + if (numRotations < 0) numRotations += 4; + int width, height; + TCOD_image_get_size(image, &width, &height); + if (numRotations == 1) { + /* rotate 90 degrees */ + TCOD_Image* img2 = TCOD_image_new(height, width); + for (int px = 0; px < width; ++px) { + for (int py = 0; py < height; ++py) { + TCOD_color_t col1 = TCOD_image_get_pixel(image, px, py); + TCOD_image_put_pixel(img2, height - 1 - py, px, col1); + } + } + TCOD_image_delete_internal(image); + /* update image with the new image content */ + image->mipmaps = img2->mipmaps; + image->sys_img = NULL; + image->nb_mipmaps = img2->nb_mipmaps; + free(img2); + } else if (numRotations == 2) { + /* rotate 180 degrees */ + int maxy = height / 2 + ((height & 1) == 1 ? 1 : 0 ); + for (int px = 0; px < width; ++px) { + for (int py = 0; py < maxy; ++py) { + if (py != height - 1 - py || px < width / 2) { + TCOD_color_t col1 = TCOD_image_get_pixel(image, px, py); + TCOD_color_t col2 = TCOD_image_get_pixel( + image, width - 1 - px, height - 1 - py); + TCOD_image_put_pixel(image, px, py, col2); + TCOD_image_put_pixel(image, width - 1 - px, height - 1 - py, col1); + } + } + } + } else if (numRotations == 3) { + /* rotate 270 degrees */ + TCOD_Image* newImg = TCOD_image_new(height, width); + for (int px = 0; px < width; ++px) { + for (int py = 0; py < height; ++py) { + TCOD_color_t col1 = TCOD_image_get_pixel(image, px, py); + TCOD_image_put_pixel(newImg, py, width - 1 - px, col1); + } + } + TCOD_image_delete_internal(image); + /* update image with the new image content */ + image->mipmaps = newImg->mipmaps; + image->sys_img = NULL; + image->nb_mipmaps = newImg->nb_mipmaps; + free(newImg); + } +} + +void TCOD_image_scale(TCOD_Image* image, int neww, int newh) +{ + int width, height; + TCOD_image_get_size(image, &width, &height); + if ( neww == width && newh == height ) { return; } + if ( neww == 0 || newh == 0 ) { return; } + TCOD_Image* newimg = TCOD_image_new(neww, newh); + + if (neww < width && newh < height) { + /* scale down image, using supersampling */ + for (int py = 0; py < newh; ++py) { + float y0 = static_cast(py) * height / newh; + float y0floor = std::floor(y0); + float y0weight = 1.0f - (y0 - y0floor); + int iy0 = static_cast(y0floor); + + float y1 = static_cast(py + 1) * height / newh; + float y1floor = std::floor(y1 - 0.00001f); + float y1weight = (y1 - y1floor); + int iy1 = static_cast(y1floor); + + for (int px = 0; px < neww; ++px) { + float x0 = static_cast(px) * width / neww; + float x0floor = std::floor(x0); + float x0weight = 1.0f - (x0 - x0floor); + int ix0 = static_cast(x0floor); + + float x1 = static_cast(px+1) * width / neww; + float x1floor = std::floor(x1 - 0.00001f); + float x1weight = (x1 - x1floor); + int ix1 = static_cast(x1floor); + + float r=0,g=0,b=0,sumweight=0.0f; + /* left & right fractional edges */ + for (int srcy = static_cast(y0 + 1); + srcy < static_cast(y1); + ++srcy) { + TCOD_color_t col_left = TCOD_image_get_pixel(image, ix0, srcy); + TCOD_color_t col_right = TCOD_image_get_pixel(image, ix1, srcy); + r += col_left.r * x0weight + col_right.r * x1weight; + g += col_left.g * x0weight + col_right.g * x1weight; + b += col_left.b * x0weight + col_right.b * x1weight; + sumweight += x0weight + x1weight; + } + /* top & bottom fractional edges */ + for (int srcx = static_cast(x0 + 1); + srcx < static_cast(x1); + ++srcx) { + TCOD_color_t col_top = TCOD_image_get_pixel(image, srcx, iy0); + TCOD_color_t col_bottom = TCOD_image_get_pixel(image, srcx, iy1); + r += col_top.r * y0weight + col_bottom.r * y1weight; + g += col_top.g * y0weight + col_bottom.g * y1weight; + b += col_top.b * y0weight + col_bottom.b * y1weight; + sumweight += y0weight + y1weight; + } + /* center */ + for (int srcy = static_cast(y0 + 1); + srcy < static_cast(y1); + ++srcy) { + for (int srcx = static_cast(x0 + 1); + srcx < static_cast(x1); + ++srcx) { + TCOD_color_t sample = TCOD_image_get_pixel(image, srcx, srcy); + r += sample.r; + g += sample.g; + b += sample.b; + sumweight += 1.0f; + } + } + /* corners */ + TCOD_color_t col = TCOD_image_get_pixel(image, ix0, iy0); + r += col.r * (x0weight * y0weight); + g += col.g * (x0weight * y0weight); + b += col.b * (x0weight * y0weight); + sumweight += x0weight * y0weight; + col = TCOD_image_get_pixel(image, ix0, iy1); + r += col.r * (x0weight * y1weight); + g += col.g * (x0weight * y1weight); + b += col.b * (x0weight * y1weight); + sumweight += x0weight * y1weight; + col = TCOD_image_get_pixel(image, ix1, iy1); + r += col.r * (x1weight * y1weight); + g += col.g * (x1weight * y1weight); + b += col.b * (x1weight * y1weight); + sumweight += x1weight * y1weight; + col = TCOD_image_get_pixel(image, ix1, iy0); + r += col.r * (x1weight * y0weight); + g += col.g * (x1weight * y0weight); + b += col.b * (x1weight * y0weight); + sumweight += x1weight * y0weight; + sumweight = 1.0f / sumweight; + r = r * sumweight + 0.5f; + g = g * sumweight + 0.5f; + b = b * sumweight + 0.5f; + col.r = r; + col.g = g; + col.b = b; + TCOD_image_put_pixel(newimg, px, py, col); + } + } + } else { + /* scale up image, using nearest neightbor */ + for (int py = 0; py < newh; ++py) { + int srcy = py * height / newh; + for (int px = 0; px < neww; ++px) { + int srcx = px * width / neww; + TCOD_image_put_pixel( + newimg, px, py, TCOD_image_get_pixel(image, srcx, srcy) + ); + } + } + } + /* destroy old image */ + TCOD_image_delete_internal(image); + /* update image with the new image content */ + image->mipmaps = newimg->mipmaps; + image->sys_img = NULL; + image->nb_mipmaps = newimg->nb_mipmaps; + free(newimg); +} + + +/* distance between two colors */ +int rgbdist(const TCOD_color_t *c1, const TCOD_color_t *c2) +{ + int dr = static_cast(c1->r) - c2->r; + int dg = static_cast(c1->g) - c2->g; + int db = static_cast(c1->b) - c2->b; + return dr * dr + dg * dg + db * db; +} + +void getPattern(const TCOD_color_t desired[4], TCOD_color_t palette[2], + int* nbCols, int* ascii) { + /* adapted from Jeff Lait's code posted on r.g.r.d */ + int flag = 0; + /* + pixels have following flag values : + X 1 + 2 4 + flag indicates which pixels uses foreground color (palette[1]) + */ + static int flagToAscii[8] = { + 0, + TCOD_CHAR_SUBP_NE, + TCOD_CHAR_SUBP_SW, + -TCOD_CHAR_SUBP_DIAG, + TCOD_CHAR_SUBP_SE, + TCOD_CHAR_SUBP_E, + -TCOD_CHAR_SUBP_N, + -TCOD_CHAR_SUBP_NW + }; + int weight[2] = { 0, 0 }; + int i; + + /* First colour trivial. */ + palette[0] = desired[0]; + + /* Ignore all duplicates... */ + for (i = 1; i < 4; i++) { + if (desired[i] != palette[0]) { break; } + } + + /* All the same. */ + if (i == 4) { + *nbCols = 1; + return; + } + weight[0] = i; + + /* Found a second colour... */ + palette[1] = desired[i]; + weight[1] = 1; + flag |= 1 << (i - 1); + *nbCols = 2; + /* remaining colours */ + ++i; + while (i < 4) { + if (desired[i] == palette[0]) { + ++weight[0]; + } else if (desired[i] == palette[1]) { + flag |= 1 << (i - 1); + ++weight[1]; + } else { + /* Bah, too many colours, */ + /* merge the two nearest */ + int dist0i = rgbdist(&desired[i], &palette[0]); + int dist1i = rgbdist(&desired[i], &palette[1]); + int dist01 = rgbdist(&palette[0], &palette[1]); + if (dist0i < dist1i) { + if (dist0i <= dist01) { + /* merge 0 and i */ + palette[0] = TCOD_color_lerp( + desired[i], palette[0], weight[0] / (1.0f + weight[0]) + ); + ++weight[0]; + } else { + /* merge 0 and 1 */ + palette[0] = TCOD_color_lerp( + palette[0], + palette[1], + static_cast(weight[1]) / (weight[0] + weight[1]) + ); + ++weight[0]; + palette[1] = desired[i]; + flag = 1 << (i - 1); + } + } else { + if (dist1i <= dist01) { + /* merge 1 and i */ + palette[1] = TCOD_color_lerp( + desired[i], palette[1], weight[1] / (1.0f + weight[1]) + ); + ++weight[1]; + flag |= 1 << (i - 1); + } else { + /* merge 0 and 1 */ + palette[0] = TCOD_color_lerp( + palette[0], + palette[1], + static_cast(weight[1]) / (weight[0] + weight[1]) + ); + ++weight[0]; + palette[1] = desired[i]; + flag = 1 << (i - 1); + } + } + } + ++i; + } + *ascii = flagToAscii[flag]; +} +#ifdef TCOD_CONSOLE_SUPPORT + +void TCOD_image_blit_2x(const TCOD_Image* image, TCOD_Console* con, + int dx, int dy, int sx, int sy, int w, int h) { + con = TCOD_console_validate_(con); + TCOD_IFNOT(image != NULL && con != NULL) { return; } + TCOD_color_t grid[4]; + TCOD_color_t cols[2]; + + int width, height; + TCOD_image_get_size(image, &width, &height); + if (w == -1) { w = width; } + if (h == -1) { h = height; } + + /* check that the sx,sy/w,h rectangle is inside the image */ + TCOD_ASSERT(sx >= 0 && sy >= 0 && sx+w <= width && sy+h <= height); + TCOD_IFNOT(w > 0 && h > 0) { return; } + + sx = std::max(0, sx); + sy = std::max(0, sy); + w = std::min(w, width - sx); + h = std::min(h, height - sy); + + int maxx = dx + w / 2 <= con->w ? w : (con->w - dx) * 2; + int maxy = dy + h / 2 <= con->h ? h : (con->h - dy) * 2; + /* check that the image is not blitted outside the console */ + TCOD_IFNOT(dx + maxx / 2 >= 0 && dy + maxy / 2 >= 0 + && dx < con->w && dy < con->h) { return; } + maxx += sx; + maxy += sy; + + for (int cx = sx; cx < maxx; cx += 2) { + for (int cy = sy; cy < maxy; cy += 2) { + /* get the 2x2 super pixel colors from the image */ + int conx = dx + (cx - sx) / 2; + int cony = dy + (cy - sy) / 2; + TCOD_color_t consoleBack = + TCOD_console_get_char_background(con, conx, cony); + grid[0] = TCOD_image_get_pixel(image, cx, cy); + if (image->has_key_color && grid[0] == image->key_color) { + grid[0] = consoleBack; + } + if (cx < maxx - 1) { + grid[1] = TCOD_image_get_pixel(image, cx + 1, cy); + if (image->has_key_color && grid[1] == image->key_color) { + grid[1] = consoleBack; + } + } else { + grid[1] = consoleBack; + } + if (cy < maxy-1) { + grid[2] = TCOD_image_get_pixel(image, cx, cy + 1); + if (image->has_key_color && grid[2] == image->key_color) { + grid[2] = consoleBack; + } + } else { + grid[2] = consoleBack; + } + if (cx < maxx-1 && cy < maxy-1) { + grid[3] = TCOD_image_get_pixel(image, cx + 1, cy + 1); + if (image->has_key_color && grid[3] == image->key_color) { + grid[3] = consoleBack; + } + } else { + grid[3] = consoleBack; + } + /* analyse color, posterize, get pattern */ + int nbCols; + int ascii; + getPattern(grid, cols, &nbCols, &ascii); + if (nbCols == 1) { + /* single color */ + TCOD_console_set_char_background( + con, conx, cony, cols[0], TCOD_BKGND_SET); + TCOD_console_set_char(con, conx, cony, ' '); + } else if (ascii >= 0) { + TCOD_console_set_char_background(con, conx, cony, cols[0], + TCOD_BKGND_SET); + TCOD_console_set_char_foreground(con, conx, cony, cols[1]); + TCOD_console_set_char(con, conx, cony, ascii); + } else { + /* negative ascii code means we need to invert back/fore colors */ + TCOD_console_set_char_background(con, conx, cony, cols[1], + TCOD_BKGND_SET); + TCOD_console_set_char_foreground(con, conx, cony, cols[0]); + TCOD_console_set_char(con, conx, cony, -ascii); + } + } + } +} +#endif /* TCOD_CONSOLE_SUPPORT */ +#endif /* TCOD_IMAGE_SUPPORT */ diff --git a/tcod_sys/libtcod/src/libtcod/lex.cpp b/tcod_sys/libtcod/src/libtcod/lex.cpp index 834719554..8f71e44cb 100644 --- a/tcod_sys/libtcod/src/libtcod/lex.cpp +++ b/tcod_sys/libtcod/src/libtcod/lex.cpp @@ -1,30 +1,34 @@ -/* -* libtcod -* Copyright (c) 2008-2018 Jice & Mingos & rmtew -* All rights reserved. -* -* Redistribution and use in source and binary forms, with or without -* modification, are permitted provided that the following conditions are met: -* * Redistributions of source code must retain the above copyright -* notice, this list of conditions and the following disclaimer. -* * Redistributions in binary form must reproduce the above copyright -* notice, this list of conditions and the following disclaimer in the -* documentation and/or other materials provided with the distribution. -* * The name of Jice or Mingos may not be used to endorse or promote -* products derived from this software without specific prior written -* permission. -* -* THIS SOFTWARE IS PROVIDED BY JICE, MINGOS AND RMTEW ``AS IS'' AND ANY -* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED -* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE -* DISCLAIMED. IN NO EVENT SHALL JICE, MINGOS OR RMTEW BE LIABLE FOR ANY -* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES -* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; -* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND -* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS -* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. -*/ +/* BSD 3-Clause License + * + * Copyright © 2008-2019, Jice and the libtcod contributors. + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions are met: + * + * 1. Redistributions of source code must retain the above copyright notice, + * this list of conditions and the following disclaimer. + * + * 2. Redistributions in binary form must reproduce the above copyright notice, + * this list of conditions and the following disclaimer in the documentation + * and/or other materials provided with the distribution. + * + * 3. Neither the name of the copyright holder nor the names of its + * contributors may be used to endorse or promote products derived from + * this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE + * POSSIBILITY OF SUCH DAMAGE. + */ #include "lex.hpp" #include @@ -35,72 +39,71 @@ #include "libtcod_int.h" -TCODLex::TCODLex( const char **_symbols, const char **_keywords, const char *simpleComment, - const char *commentStart, const char *commentStop, const char *javadocCommentStart, - const char *_stringDelim, int _flags) +TCODLex::TCODLex( + const char** _symbols, + const char** _keywords, + const char* simpleComment, + const char* commentStart, + const char* commentStop, + const char* javadocCommentStart, + const char* _stringDelim, + int _flags) { - data=(void *)TCOD_lex_new(_symbols,_keywords,simpleComment,commentStart,commentStop,javadocCommentStart,_stringDelim,_flags); - + data = TCOD_lex_new( + _symbols, + _keywords, + simpleComment, + commentStart, + commentStop, + javadocCommentStart, + _stringDelim, + _flags); } - TCODLex::TCODLex() { - data= (void *)TCOD_lex_new_intern(); + data = TCOD_lex_new_intern(); } - TCODLex::~TCODLex() { - TCOD_lex_delete((TCOD_lex_t *)data); + TCOD_lex_delete(data); } - -char *TCODLex::getLastJavadoc() +char* TCODLex::getLastJavadoc() { - return TCOD_lex_get_last_javadoc((TCOD_lex_t *)data); + return TCOD_lex_get_last_javadoc(data); } - - -void TCODLex::setDataBuffer(char *dat) +void TCODLex::setDataBuffer(char* dat) { - TCOD_lex_set_data_buffer((TCOD_lex_t *)data,dat); + TCOD_lex_set_data_buffer(data, dat); } - -bool TCODLex::setDataFile(const char *_filename) +bool TCODLex::setDataFile(const char* _filename) { - return TCOD_lex_set_data_file((TCOD_lex_t *)data,_filename) != 0; + return TCOD_lex_set_data_file(data, _filename) != 0; } - int TCODLex::parse() { - return TCOD_lex_parse((TCOD_lex_t *)data); + return TCOD_lex_parse(data); } - - int TCODLex::parseUntil(int tokenType) { - return TCOD_lex_parse_until_token_type((TCOD_lex_t *)data,tokenType); + return TCOD_lex_parse_until_token_type(data, tokenType); } - -int TCODLex::parseUntil(const char *tokenValue) +int TCODLex::parseUntil(const char* tokenValue) { - return TCOD_lex_parse_until_token_value((TCOD_lex_t *)data,tokenValue); + return TCOD_lex_parse_until_token_value(data, tokenValue); } - -void TCODLex::savepoint(TCODLex *savepoint) +void TCODLex::savepoint(TCODLex* savepoint) { - TCOD_lex_savepoint((TCOD_lex_t *)data,(TCOD_lex_t *)(savepoint->data)); + TCOD_lex_savepoint(data, savepoint->data); } - -void TCODLex::restore(TCODLex *savepoint) +void TCODLex::restore(TCODLex* savepoint) { - TCOD_lex_restore((TCOD_lex_t *)data,(TCOD_lex_t *)(savepoint->data)); + TCOD_lex_restore(data, savepoint->data); } - bool TCODLex::expect(int tokenType) { - return TCOD_lex_expect_token_type((TCOD_lex_t *)data,tokenType) != 0; + return TCOD_lex_expect_token_type(data, tokenType) != 0; } - -bool TCODLex::expect(int tokenType, const char *tokenValue) +bool TCODLex::expect(int tokenType, const char* tokenValue) { - return TCOD_lex_expect_token_value((TCOD_lex_t *)data,tokenType,tokenValue) != 0; + return TCOD_lex_expect_token_value(data, tokenType, tokenValue) != 0; } diff --git a/tcod_sys/libtcod/src/libtcod/lex.h b/tcod_sys/libtcod/src/libtcod/lex.h index 81c7aefb0..30a08b5c6 100644 --- a/tcod_sys/libtcod/src/libtcod/lex.h +++ b/tcod_sys/libtcod/src/libtcod/lex.h @@ -1,30 +1,34 @@ -/* -* libtcod -* Copyright (c) 2008-2018 Jice & Mingos & rmtew -* All rights reserved. -* -* Redistribution and use in source and binary forms, with or without -* modification, are permitted provided that the following conditions are met: -* * Redistributions of source code must retain the above copyright -* notice, this list of conditions and the following disclaimer. -* * Redistributions in binary form must reproduce the above copyright -* notice, this list of conditions and the following disclaimer in the -* documentation and/or other materials provided with the distribution. -* * The name of Jice or Mingos may not be used to endorse or promote -* products derived from this software without specific prior written -* permission. -* -* THIS SOFTWARE IS PROVIDED BY JICE, MINGOS AND RMTEW ``AS IS'' AND ANY -* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED -* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE -* DISCLAIMED. IN NO EVENT SHALL JICE, MINGOS OR RMTEW BE LIABLE FOR ANY -* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES -* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; -* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND -* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS -* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. -*/ +/* BSD 3-Clause License + * + * Copyright © 2008-2019, Jice and the libtcod contributors. + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions are met: + * + * 1. Redistributions of source code must retain the above copyright notice, + * this list of conditions and the following disclaimer. + * + * 2. Redistributions in binary form must reproduce the above copyright notice, + * this list of conditions and the following disclaimer in the documentation + * and/or other materials provided with the distribution. + * + * 3. Neither the name of the copyright holder nor the names of its + * contributors may be used to endorse or promote products derived from + * this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE + * POSSIBILITY OF SUCH DAMAGE. + */ /* * This is a libtcod internal module. * Use at your own risks... diff --git a/tcod_sys/libtcod/src/libtcod/lex.hpp b/tcod_sys/libtcod/src/libtcod/lex.hpp index 0db88e654..1d9056277 100644 --- a/tcod_sys/libtcod/src/libtcod/lex.hpp +++ b/tcod_sys/libtcod/src/libtcod/lex.hpp @@ -1,30 +1,34 @@ -/* -* libtcod -* Copyright (c) 2008-2018 Jice & Mingos & rmtew -* All rights reserved. -* -* Redistribution and use in source and binary forms, with or without -* modification, are permitted provided that the following conditions are met: -* * Redistributions of source code must retain the above copyright -* notice, this list of conditions and the following disclaimer. -* * Redistributions in binary form must reproduce the above copyright -* notice, this list of conditions and the following disclaimer in the -* documentation and/or other materials provided with the distribution. -* * The name of Jice or Mingos may not be used to endorse or promote -* products derived from this software without specific prior written -* permission. -* -* THIS SOFTWARE IS PROVIDED BY JICE, MINGOS AND RMTEW ``AS IS'' AND ANY -* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED -* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE -* DISCLAIMED. IN NO EVENT SHALL JICE, MINGOS OR RMTEW BE LIABLE FOR ANY -* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES -* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; -* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND -* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS -* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. -*/ +/* BSD 3-Clause License + * + * Copyright © 2008-2019, Jice and the libtcod contributors. + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions are met: + * + * 1. Redistributions of source code must retain the above copyright notice, + * this list of conditions and the following disclaimer. + * + * 2. Redistributions in binary form must reproduce the above copyright notice, + * this list of conditions and the following disclaimer in the documentation + * and/or other materials provided with the distribution. + * + * 3. Neither the name of the copyright holder nor the names of its + * contributors may be used to endorse or promote products derived from + * this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE + * POSSIBILITY OF SUCH DAMAGE. + */ /* * This is a libtcod internal module. * Use at your own risks... @@ -35,41 +39,80 @@ #include "lex.h" class TCODLIB_API TCODLex { -public : - TCODLex(); - TCODLex( const char **symbols, const char **keywords, const char *simpleComment="//", - const char *commentStart="/*", const char *commentStop="*/", const char *javadocCommentStart="/**", - const char *stringDelim="\"", int flags=TCOD_LEX_FLAG_NESTING_COMMENT); - ~TCODLex(); + public: + TCODLex(); + TCODLex( + const char** symbols, + const char** keywords, + const char* simpleComment="//", + const char* commentStart="/*", + const char* commentStop="*/", + const char* javadocCommentStart="/**", + const char* stringDelim="\"", + int flags=TCOD_LEX_FLAG_NESTING_COMMENT); + ~TCODLex(); - void setDataBuffer(char *dat); - bool setDataFile(const char *filename); + void setDataBuffer(char* dat); + bool setDataFile(const char* filename); - int parse(void); - int parseUntil(int tokenType); - int parseUntil(const char *tokenValue); + int parse(); + int parseUntil(int tokenType); + int parseUntil(const char* tokenValue); - bool expect(int tokenType); - bool expect(int tokenType,const char *tokenValue); + bool expect(int tokenType); + bool expect(int tokenType, const char* tokenValue); - void savepoint(TCODLex *savept); - void restore(TCODLex *savept); - char *getLastJavadoc(); + void savepoint(TCODLex* savept); + void restore(TCODLex* savept); + char* getLastJavadoc(); - int getFileLine() { return ((TCOD_lex_t *)data)->file_line; } - int getTokenType() { return ((TCOD_lex_t *)data)->token_type; } - int getTokenIntVal() { return ((TCOD_lex_t *)data)->token_int_val; } - int getTokenIdx() { return ((TCOD_lex_t *)data)->token_idx; } - float getTokenFloatVal() { return ((TCOD_lex_t *)data)->token_float_val; } - char *getToken() { return ((TCOD_lex_t *)data)->tok; } - char getStringLastDelimiter() { return ((TCOD_lex_t *)data)->lastStringDelim; } - char *getPos() { return ((TCOD_lex_t *)data)->pos; } - char *getBuf() { return ((TCOD_lex_t *)data)->buf; } - char *getFilename() { return ((TCOD_lex_t *)data)->filename; } - char *getLastJavadocComment() { return ((TCOD_lex_t *)data)->last_javadoc_comment; } - static const char *getTokenName(int tokenType) { return TCOD_lex_get_token_name(tokenType); } -protected : - void *data; + int getFileLine() + { + return data->file_line; + } + int getTokenType() + { + return data->token_type; + } + int getTokenIntVal() + { + return data->token_int_val; + } + int getTokenIdx() + { + return data->token_idx; + } + float getTokenFloatVal() + { + return data->token_float_val; + } + char* getToken() + { + return data->tok; + } + char getStringLastDelimiter() + { + return data->lastStringDelim; + } + char* getPos() + { return data->pos; } + char* getBuf() + { + return data->buf; + } + char* getFilename() + { + return data->filename; + } + char* getLastJavadocComment() + { + return data->last_javadoc_comment; + } + static const char* getTokenName(int tokenType) + { + return TCOD_lex_get_token_name(tokenType); + } + protected: + TCOD_lex_t* data; }; - -#endif +#endif // _TCOD_LEX_HPP diff --git a/tcod_sys/libtcod/src/libtcod/lex_c.c b/tcod_sys/libtcod/src/libtcod/lex_c.c index d8c8aa17b..754c0d1a4 100644 --- a/tcod_sys/libtcod/src/libtcod/lex_c.c +++ b/tcod_sys/libtcod/src/libtcod/lex_c.c @@ -1,30 +1,34 @@ -/* -* libtcod -* Copyright (c) 2008-2018 Jice & Mingos & rmtew -* All rights reserved. -* -* Redistribution and use in source and binary forms, with or without -* modification, are permitted provided that the following conditions are met: -* * Redistributions of source code must retain the above copyright -* notice, this list of conditions and the following disclaimer. -* * Redistributions in binary form must reproduce the above copyright -* notice, this list of conditions and the following disclaimer in the -* documentation and/or other materials provided with the distribution. -* * The name of Jice or Mingos may not be used to endorse or promote -* products derived from this software without specific prior written -* permission. -* -* THIS SOFTWARE IS PROVIDED BY JICE, MINGOS AND RMTEW ``AS IS'' AND ANY -* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED -* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE -* DISCLAIMED. IN NO EVENT SHALL JICE, MINGOS OR RMTEW BE LIABLE FOR ANY -* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES -* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; -* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND -* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS -* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. -*/ +/* BSD 3-Clause License + * + * Copyright © 2008-2019, Jice and the libtcod contributors. + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions are met: + * + * 1. Redistributions of source code must retain the above copyright notice, + * this list of conditions and the following disclaimer. + * + * 2. Redistributions in binary form must reproduce the above copyright notice, + * this list of conditions and the following disclaimer in the documentation + * and/or other materials provided with the distribution. + * + * 3. Neither the name of the copyright holder nor the names of its + * contributors may be used to endorse or promote products derived from + * this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE + * POSSIBILITY OF SUCH DAMAGE. + */ #include "lex.h" #include @@ -643,35 +647,34 @@ int TCOD_lex_parse(TCOD_lex_t *lex) } -int TCOD_lex_parse_until_token_type(TCOD_lex_t *lex,int tokenType) +int TCOD_lex_parse_until_token_type(TCOD_lex_t *lex, int tokenType) { - int token; + int token; + token = TCOD_lex_parse(lex); + if (token == TCOD_LEX_ERROR) { return token; } + while (token != TCOD_LEX_EOF) + { + if (token == tokenType) { return token; } token = TCOD_lex_parse(lex); - if ( token == TCOD_LEX_ERROR ) return token; - while ( token != TCOD_LEX_EOF ) - { - if ( token == tokenType ) - return token; - token = TCOD_lex_parse(lex); - if ( token == TCOD_LEX_ERROR ) return token; - } - return token; + if (token == TCOD_LEX_ERROR) { return token; } + } + return token; } int TCOD_lex_parse_until_token_value(TCOD_lex_t *lex, const char *tokenValue) { - int token; - token = TCOD_lex_parse(lex); - if ( token == TCOD_LEX_ERROR ) return token; - { - while ( token != TCOD_LEX_EOF ) - if ( strcmp( lex->tok, tokenValue ) == 0 - || ( ( lex->flags & TCOD_LEX_FLAG_NOCASE ) && TCOD_strcasecmp(lex->tok, tokenValue ) == 0 ) ) - return token; - token = TCOD_lex_parse(lex); - if ( token == TCOD_LEX_ERROR ) return token; + int token = TCOD_lex_parse(lex); + if (token == TCOD_LEX_ERROR) { return token; } + while (token != TCOD_LEX_EOF) { + if (strcmp(lex->tok, tokenValue) == 0 + || ((lex->flags & TCOD_LEX_FLAG_NOCASE) + && TCOD_strcasecmp(lex->tok, tokenValue) == 0)) { + return token; } - return token; + token = TCOD_lex_parse(lex); + if (token == TCOD_LEX_ERROR) { return token; } + } + return token; } void TCOD_lex_savepoint(TCOD_lex_t *lex,TCOD_lex_t *_savept) diff --git a/tcod_sys/libtcod/src/libtcod/libtcod.h b/tcod_sys/libtcod/src/libtcod/libtcod.h index 1be4bfa2d..7ac2ab09a 100644 --- a/tcod_sys/libtcod/src/libtcod/libtcod.h +++ b/tcod_sys/libtcod/src/libtcod/libtcod.h @@ -1,30 +1,34 @@ -/* -* libtcod -* Copyright (c) 2008-2018 Jice & Mingos & rmtew -* All rights reserved. -* -* Redistribution and use in source and binary forms, with or without -* modification, are permitted provided that the following conditions are met: -* * Redistributions of source code must retain the above copyright -* notice, this list of conditions and the following disclaimer. -* * Redistributions in binary form must reproduce the above copyright -* notice, this list of conditions and the following disclaimer in the -* documentation and/or other materials provided with the distribution. -* * The name of Jice or Mingos may not be used to endorse or promote -* products derived from this software without specific prior written -* permission. -* -* THIS SOFTWARE IS PROVIDED BY JICE, MINGOS AND RMTEW ``AS IS'' AND ANY -* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED -* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE -* DISCLAIMED. IN NO EVENT SHALL JICE, MINGOS OR RMTEW BE LIABLE FOR ANY -* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES -* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; -* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND -* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS -* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. -*/ +/* BSD 3-Clause License + * + * Copyright © 2008-2019, Jice and the libtcod contributors. + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions are met: + * + * 1. Redistributions of source code must retain the above copyright notice, + * this list of conditions and the following disclaimer. + * + * 2. Redistributions in binary form must reproduce the above copyright notice, + * this list of conditions and the following disclaimer in the documentation + * and/or other materials provided with the distribution. + * + * 3. Neither the name of the copyright holder nor the names of its + * contributors may be used to endorse or promote products derived from + * this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE + * POSSIBILITY OF SUCH DAMAGE. + */ #ifndef _LIBTCOD_H #define _LIBTCOD_H @@ -36,7 +40,6 @@ #include "bsp.h" #include "color.h" #include "console.h" -#include "console_rexpaint.h" #include "fov.h" #include "heightmap.h" #include "image.h" @@ -53,6 +56,17 @@ #include "txtfield.h" #include "zip.h" +#include "console/drawing.h" +#include "console/printing.h" +#include "console/rexpaint.h" + +#include "engine/backend.h" +#include "engine/display.h" +#include "engine/error.h" +#include "engine/globals.h" + +#include "sdl2/event.h" + #include "tileset/observer.h" #include "tileset/tileset.h" #include "tileset/tile.h" diff --git a/tcod_sys/libtcod/src/libtcod/libtcod.hpp b/tcod_sys/libtcod/src/libtcod/libtcod.hpp index cdc816599..304925682 100644 --- a/tcod_sys/libtcod/src/libtcod/libtcod.hpp +++ b/tcod_sys/libtcod/src/libtcod/libtcod.hpp @@ -1,28 +1,32 @@ -/* -* libtcod -* Copyright (c) 2008-2018 Jice & Mingos & rmtew -* All rights reserved. -* -* Redistribution and use in source and binary forms, with or without -* modification, are permitted provided that the following conditions are met: -* * Redistributions of source code must retain the above copyright -* notice, this list of conditions and the following disclaimer. -* * Redistributions in binary form must reproduce the above copyright -* notice, this list of conditions and the following disclaimer in the -* documentation and/or other materials provided with the distribution. -* * The name of Jice or Mingos may not be used to endorse or promote -* products derived from this software without specific prior written -* permission. -* -* THIS SOFTWARE IS PROVIDED BY JICE, MINGOS AND RMTEW ``AS IS'' AND ANY -* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED -* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE -* DISCLAIMED. IN NO EVENT SHALL JICE, MINGOS OR RMTEW BE LIABLE FOR ANY -* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES -* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; -* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND -* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS -* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. -*/ +/* BSD 3-Clause License + * + * Copyright © 2008-2019, Jice and the libtcod contributors. + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions are met: + * + * 1. Redistributions of source code must retain the above copyright notice, + * this list of conditions and the following disclaimer. + * + * 2. Redistributions in binary form must reproduce the above copyright notice, + * this list of conditions and the following disclaimer in the documentation + * and/or other materials provided with the distribution. + * + * 3. Neither the name of the copyright holder nor the names of its + * contributors may be used to endorse or promote products derived from + * this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE + * POSSIBILITY OF SUCH DAMAGE. + */ #include "libtcod.h" diff --git a/tcod_sys/libtcod/src/libtcod/libtcod_int.h b/tcod_sys/libtcod/src/libtcod/libtcod_int.h index 7a82b67f3..f98563769 100644 --- a/tcod_sys/libtcod/src/libtcod/libtcod_int.h +++ b/tcod_sys/libtcod/src/libtcod/libtcod_int.h @@ -1,37 +1,45 @@ -/* -* libtcod -* Copyright (c) 2008-2018 Jice & Mingos & rmtew -* All rights reserved. -* -* Redistribution and use in source and binary forms, with or without -* modification, are permitted provided that the following conditions are met: -* * Redistributions of source code must retain the above copyright -* notice, this list of conditions and the following disclaimer. -* * Redistributions in binary form must reproduce the above copyright -* notice, this list of conditions and the following disclaimer in the -* documentation and/or other materials provided with the distribution. -* * The name of Jice or Mingos may not be used to endorse or promote -* products derived from this software without specific prior written -* permission. -* -* THIS SOFTWARE IS PROVIDED BY JICE, MINGOS AND RMTEW ``AS IS'' AND ANY -* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED -* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE -* DISCLAIMED. IN NO EVENT SHALL JICE, MINGOS OR RMTEW BE LIABLE FOR ANY -* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES -* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; -* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND -* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS -* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. -*/ -#ifndef _TCODLIB_INT_H -#define _TCODLIB_INT_H +/* BSD 3-Clause License + * + * Copyright © 2008-2019, Jice and the libtcod contributors. + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions are met: + * + * 1. Redistributions of source code must retain the above copyright notice, + * this list of conditions and the following disclaimer. + * + * 2. Redistributions in binary form must reproduce the above copyright notice, + * this list of conditions and the following disclaimer in the documentation + * and/or other materials provided with the distribution. + * + * 3. Neither the name of the copyright holder nor the names of its + * contributors may be used to endorse or promote products derived from + * this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE + * POSSIBILITY OF SUCH DAMAGE. + */ +#ifndef TCODLIB_INT_H_ +#define TCODLIB_INT_H_ #include #include #if defined(__ANDROID__) #include #endif +#ifdef __cplusplus +#include +#include +#endif // __cplusplus #include "portability.h" #include "color.h" @@ -74,6 +82,7 @@ typedef struct { bool font_tcod_layout; bool font_in_row; bool font_greyscale; + int font_flags; /* character size in font */ int font_width; int font_height; @@ -155,20 +164,22 @@ extern TCOD_internal_context_t TCOD_ctx; #if !defined(TCOD_BARE) && !defined(NO_OPENGL) /* opengl utilities */ void TCOD_opengl_init_attributes(void); -bool TCOD_opengl_init_state(int conw, int conh, void *font_tex); +bool TCOD_opengl_init_state(int conw, int conh, struct SDL_Surface* font_tex); void TCOD_opengl_uninit_state(void); bool TCOD_opengl_init_shaders(void); bool TCOD_opengl_render(int oldFade, bool *ascii_updated, struct TCOD_Console *console, struct TCOD_Console *cache); void TCOD_opengl_swap(void); -void * TCOD_opengl_get_screen(void); +struct SDL_Surface* TCOD_opengl_get_screen(void); #endif #ifdef TCOD_IMAGE_SUPPORT /* image internal stuff */ -bool TCOD_image_mipmap_copy_internal(TCOD_image_t srcImage, TCOD_image_t dstImage); -TCOD_color_t *TCOD_image_get_colors(TCOD_image_t *image); -void TCOD_image_invalidate_mipmaps(TCOD_image_t *image); -void TCOD_image_get_key_data(TCOD_image_t image, bool *has_key_color, TCOD_color_t *key_color); +bool TCOD_image_mipmap_copy_internal(const TCOD_Image* srcImage, + TCOD_Image* dstImage); +TCOD_color_t *TCOD_image_get_colors(TCOD_Image* image); +void TCOD_image_invalidate_mipmaps(TCOD_Image* image); +void TCOD_image_get_key_data(const TCOD_Image* image, + bool *has_key_color, TCOD_color_t *key_color); #endif /* fov internal stuff */ @@ -179,38 +190,10 @@ void TCOD_map_compute_fov_permissive2(TCOD_map_t map, int player_x, int player_y void TCOD_map_compute_fov_restrictive_shadowcasting(TCOD_map_t map, int player_x, int player_y, int max_radius, bool light_walls); void TCOD_map_postproc(TCOD_map_t map,int x0,int y0, int x1, int y1, int dx, int dy); -#ifdef TCOD_CONSOLE_SUPPORT -/* TCODConsole non public methods*/ -bool TCOD_console_init(TCOD_console_t con,const char *title, bool fullscreen); -int TCOD_console_print_internal(TCOD_console_t con,int x,int y, int w, int h, TCOD_bkgnd_flag_t flag, TCOD_alignment_t align, char *msg, bool can_split, bool count_only); -int TCOD_console_stringLength(const unsigned char *s); -unsigned char * TCOD_console_forward(unsigned char *s,int l); -char *TCOD_console_vsprint(const char *fmt, va_list ap); -#endif - /* fatal errors */ void TCOD_fatal(const char *fmt, ...); void TCOD_fatal_nopar(const char *msg); -/* TCODSystem non public methods */ -#ifdef TCOD_CONSOLE_SUPPORT -void TCOD_console_data_free(struct TCOD_Console *dat); -bool TCOD_sys_init(struct TCOD_Console *console, bool fullscreen); -void TCOD_sys_set_custom_font(const char *font_name,int nb_ch, int nb_cv,int flags); -void TCOD_sys_map_ascii_to_font(int asciiCode, int fontCharX, int fontCharY); -void *TCOD_sys_create_bitmap_for_console(TCOD_console_t console); -void TCOD_sys_save_bitmap(void *bitmap, const char *filename); -void *TCOD_sys_create_bitmap(int width, int height, TCOD_color_t *buf); -void TCOD_sys_delete_bitmap(void *bitmap); -void TCOD_sys_console_to_bitmap(void *bitmap, struct TCOD_Console *console, - struct TCOD_Console *cache); -TCODLIB_API void *TCOD_sys_get_surface(int width, int height, bool alpha); -void TCOD_sys_save_fps(void); -void TCOD_sys_restore_fps(void); -void TCOD_sys_set_dirty(int dx, int dy, int dw, int dh); -void TCOD_sys_set_dirty_character_code(int ch); -int TCOD_get_tileid_for_charcode_(int charcode); - /* switch fullscreen mode */ void TCOD_sys_set_fullscreen(bool fullscreen); void TCOD_sys_set_clear_screen(void); @@ -222,8 +205,13 @@ TCOD_key_t TCOD_sys_check_for_keypress(int flags); TCOD_key_t TCOD_sys_wait_for_keypress(bool flush); bool TCOD_sys_is_key_pressed(TCOD_keycode_t key); void TCOD_sys_set_window_title(const char *title); -#endif +void TCOD_sys_pixel_to_tile(double* x, double* y); +int TCOD_console_print_internal( + TCOD_Console* con, int x,int y, int w, int h, TCOD_bkgnd_flag_t flag, + TCOD_alignment_t align, char* msg, bool can_split, bool count_only +); +char* TCOD_console_vsprint(const char* fmt, va_list ap); /* UTF-8 stuff */ #ifndef NO_UNICODE wchar_t *TCOD_console_vsprint_utf(const wchar_t *fmt, va_list ap); @@ -233,10 +221,11 @@ int TCOD_console_print_internal_utf(TCOD_console_t con,int x,int y, int rw, int #ifdef TCOD_IMAGE_SUPPORT /* image manipulation */ -TCODLIB_API void *TCOD_sys_load_image(const char *filename); -void TCOD_sys_get_image_size(const void *image, int *w,int *h); -TCOD_color_t TCOD_sys_get_image_pixel(const void *image,int x, int y); -int TCOD_sys_get_image_alpha(const void *image,int x, int y); +TCODLIB_API struct SDL_Surface* TCOD_sys_load_image(const char *filename); +void TCOD_sys_get_image_size(const struct SDL_Surface *image, int *w,int *h); +TCOD_color_t TCOD_sys_get_image_pixel(const struct SDL_Surface *image, + int x, int y); +int TCOD_sys_get_image_alpha(const struct SDL_Surface* image, int x, int y); bool TCOD_sys_check_magic_number(const char *filename, size_t size, uint8_t *data); #endif @@ -272,7 +261,7 @@ typedef struct TCOD_SDL_driver_t { /* change the mouse cursor position */ void (*set_mouse_position)(int x, int y); /* clipboard */ - char *(*get_clipboard_text)(void); + const char *(*get_clipboard_text)(void); bool (*set_clipboard_text)(const char *text); /* android compatible file access functions */ bool (*file_read)(const char *filename, unsigned char **buf, size_t *size); @@ -532,6 +521,114 @@ extern int oldFade; #define TCOD_PEACH 255,159,127 #ifdef __cplusplus -} -#endif +} // extern "C" #endif + +#ifdef __cplusplus +// TCODConsole non public methods +bool TCOD_console_init(TCOD_Console* con); +bool TCOD_console_init(TCOD_Console* con, const std::string& title, + bool fullscreen); +int TCOD_console_stringLength(const unsigned char* s); +unsigned char* TCOD_console_forward(unsigned char* s,int l); +// TCODSystem non public methods +bool TCOD_sys_init(struct TCOD_Console *console, bool fullscreen); +void TCOD_sys_set_custom_font(const char *font_name,int nb_ch, int nb_cv,int flags); +void TCOD_sys_map_ascii_to_font(int asciiCode, int fontCharX, int fontCharY); +void TCOD_sys_decode_font_(void); +struct SDL_Surface* TCOD_sys_create_bitmap_for_console(TCOD_Console* console); +void TCOD_sys_save_bitmap(struct SDL_Surface* bitmap, const char *filename); +struct SDL_Surface* TCOD_sys_create_bitmap(int width, int height, + TCOD_color_t *buf); +void TCOD_sys_delete_bitmap(struct SDL_Surface* bitmap); +void TCOD_sys_console_to_bitmap( + struct SDL_Surface* bitmap, + struct TCOD_Console *console, + struct TCOD_Console *cache); +TCODLIB_CAPI struct SDL_Surface* TCOD_sys_get_surface(int width, int height, + bool alpha); +void TCOD_sys_save_fps(void); +void TCOD_sys_restore_fps(void); +void TCOD_sys_set_dirty(int dx, int dy, int dw, int dh); +void TCOD_sys_set_dirty_character_code(int ch); +int TCOD_get_tileid_for_charcode_(int charcode); +namespace tcod { +namespace console { +/** + * Validate and return a console. + */ +inline TCOD_Console* validate_(TCOD_Console* console) +{ + console = (console ? console : TCOD_ctx.root); + TCOD_ASSERT(console); + return console; +} +/** + * Validate and return a constant console. + */ +inline const TCOD_Console* validate_(const TCOD_Console* console) +{ + console = (console ? console : TCOD_ctx.root); + TCOD_ASSERT(console); + return console; +} +/** + * Return a console reference from a valid console pointer. + */ +inline TCOD_Console& ensure_(TCOD_Console* console) +{ + console = validate_(console); + if (!console) { + throw std::logic_error("libtcod has not been initialized yet."); + } + return *console; +} +/** + * Return a console reference from a valid constant console pointer. + */ +inline const TCOD_Console& ensure_(const TCOD_Console* console) +{ + console = validate_(console); + if (!console) { + throw std::logic_error("libtcod has not been initialized yet."); + } + return *console; +} +} // namespace console +} // namespace tcod +/** + * Validate and return a console. + */ +inline TCOD_Console* TCOD_console_validate_(TCOD_Console* console) +{ + return tcod::console::validate_(console); +} +/** + * Validate and return a constant console. + */ +inline const TCOD_Console* TCOD_console_validate_(const TCOD_Console* console) +{ + return tcod::console::validate_(console); +} +/** + * Return true if the console is valid and the index is within it. + */ +inline bool TCOD_console_is_index_valid_(const TCOD_Console* console, + int x, int y) +{ + return console && 0 <= x && x < console->w && 0 <= y && y < console->h; +} +TCOD_event_t TCOD_sys_handle_mouse_event( + const union SDL_Event* ev, TCOD_mouse_t* mouse); +TCOD_event_t TCOD_sys_handle_key_event( + const union SDL_Event* ev, TCOD_key_t* key); +/** + * Private function, gets pointers of an old renderer. + */ +struct SDL_Window* TCOD_sys_get_sdl_window_(void); +/** + * Private function, gets pointers of an old renderer. + */ +struct SDL_Renderer* TCOD_sys_get_sdl_renderer_(void); +#endif // __cplusplus +#endif // TCODLIB_INT_H_ diff --git a/tcod_sys/libtcod/src/libtcod/list.h b/tcod_sys/libtcod/src/libtcod/list.h index 85c0892a2..623754e6f 100644 --- a/tcod_sys/libtcod/src/libtcod/list.h +++ b/tcod_sys/libtcod/src/libtcod/list.h @@ -1,30 +1,34 @@ -/* -* libtcod -* Copyright (c) 2008-2018 Jice & Mingos & rmtew -* All rights reserved. -* -* Redistribution and use in source and binary forms, with or without -* modification, are permitted provided that the following conditions are met: -* * Redistributions of source code must retain the above copyright -* notice, this list of conditions and the following disclaimer. -* * Redistributions in binary form must reproduce the above copyright -* notice, this list of conditions and the following disclaimer in the -* documentation and/or other materials provided with the distribution. -* * The name of Jice or Mingos may not be used to endorse or promote -* products derived from this software without specific prior written -* permission. -* -* THIS SOFTWARE IS PROVIDED BY JICE, MINGOS AND RMTEW ``AS IS'' AND ANY -* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED -* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE -* DISCLAIMED. IN NO EVENT SHALL JICE, MINGOS OR RMTEW BE LIABLE FOR ANY -* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES -* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; -* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND -* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS -* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. -*/ +/* BSD 3-Clause License + * + * Copyright © 2008-2019, Jice and the libtcod contributors. + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions are met: + * + * 1. Redistributions of source code must retain the above copyright notice, + * this list of conditions and the following disclaimer. + * + * 2. Redistributions in binary form must reproduce the above copyright notice, + * this list of conditions and the following disclaimer in the documentation + * and/or other materials provided with the distribution. + * + * 3. Neither the name of the copyright holder nor the names of its + * contributors may be used to endorse or promote products derived from + * this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE + * POSSIBILITY OF SUCH DAMAGE. + */ #ifndef _TCOD_LIST_H #define _TCOD_LIST_H diff --git a/tcod_sys/libtcod/src/libtcod/list.hpp b/tcod_sys/libtcod/src/libtcod/list.hpp index 57d07f854..38853beaa 100644 --- a/tcod_sys/libtcod/src/libtcod/list.hpp +++ b/tcod_sys/libtcod/src/libtcod/list.hpp @@ -1,30 +1,34 @@ -/* -* libtcod -* Copyright (c) 2008-2018 Jice & Mingos & rmtew -* All rights reserved. -* -* Redistribution and use in source and binary forms, with or without -* modification, are permitted provided that the following conditions are met: -* * Redistributions of source code must retain the above copyright -* notice, this list of conditions and the following disclaimer. -* * Redistributions in binary form must reproduce the above copyright -* notice, this list of conditions and the following disclaimer in the -* documentation and/or other materials provided with the distribution. -* * The name of Jice or Mingos may not be used to endorse or promote -* products derived from this software without specific prior written -* permission. -* -* THIS SOFTWARE IS PROVIDED BY JICE, MINGOS AND RMTEW ``AS IS'' AND ANY -* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED -* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE -* DISCLAIMED. IN NO EVENT SHALL JICE, MINGOS OR RMTEW BE LIABLE FOR ANY -* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES -* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; -* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND -* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS -* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. -*/ +/* BSD 3-Clause License + * + * Copyright © 2008-2019, Jice and the libtcod contributors. + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions are met: + * + * 1. Redistributions of source code must retain the above copyright notice, + * this list of conditions and the following disclaimer. + * + * 2. Redistributions in binary form must reproduce the above copyright notice, + * this list of conditions and the following disclaimer in the documentation + * and/or other materials provided with the distribution. + * + * 3. Neither the name of the copyright holder nor the names of its + * contributors may be used to endorse or promote products derived from + * this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE + * POSSIBILITY OF SUCH DAMAGE. + */ #ifndef _TCOD_LIST_HPP #define _TCOD_LIST_HPP @@ -85,13 +89,14 @@ public : TCOD_list_push(intList,(const void *)5); TCOD_list_t intList2 = TCOD_list_duplicate(intList); // intList2 contains two elements : 3 and 5 */ - TCODList(const TCOD_list_t l) { - array=NULL; - fillSize=allocSize=0; - for ( void **it=TCOD_list_begin(l); it != TCOD_list_end(l); it++ ) { - push(*((T *)(it))); - } - } + TCODList(const TCOD_list_t l) + { + array = NULL; + fillSize = allocSize = 0; + for (void** it = TCOD_list_begin(l); it != TCOD_list_end(l); ++it) { + push(*reinterpret_cast(it)); + } + } TCODList(const TCODList &l2) { array=NULL; fillSize=allocSize=0; @@ -244,12 +249,13 @@ public : bool has3 = TCOD_list_contains(intList,(const void *)3); // has3 == true bool has4 = TCOD_list_contains(intList,(const void *)4); // has4 == false */ - bool contains(const T elt) const { - for ( T* curElt = begin(); curElt != end(); curElt ++) { - if ( *curElt == elt ) return true; - } - return false; - } + bool contains(const T elt) const + { + for (T* curElt = begin(); curElt != end(); ++curElt) { + if (*curElt == elt) { return true; } + } + return false; + } /** @PageName list_list @@ -470,7 +476,7 @@ public : val = (int)TCOD_list_pop(intList); */ T pop() { - if ( fillSize == 0 ) return (T)0; + if ( fillSize == 0 ) return T{}; return array[--fillSize]; } @@ -495,7 +501,7 @@ public : val = (int)TCOD_list_peek(intList); */ T peek() const { - if ( fillSize == 0 ) return (T)0; + if ( fillSize == 0 ) return T{}; return array[fillSize-1]; } diff --git a/tcod_sys/libtcod/src/libtcod/list_c.c b/tcod_sys/libtcod/src/libtcod/list_c.c index 7a0a6a430..53066a4f9 100644 --- a/tcod_sys/libtcod/src/libtcod/list_c.c +++ b/tcod_sys/libtcod/src/libtcod/list_c.c @@ -1,30 +1,34 @@ -/* -* libtcod -* Copyright (c) 2008-2018 Jice & Mingos & rmtew -* All rights reserved. -* -* Redistribution and use in source and binary forms, with or without -* modification, are permitted provided that the following conditions are met: -* * Redistributions of source code must retain the above copyright -* notice, this list of conditions and the following disclaimer. -* * Redistributions in binary form must reproduce the above copyright -* notice, this list of conditions and the following disclaimer in the -* documentation and/or other materials provided with the distribution. -* * The name of Jice or Mingos may not be used to endorse or promote -* products derived from this software without specific prior written -* permission. -* -* THIS SOFTWARE IS PROVIDED BY JICE, MINGOS AND RMTEW ``AS IS'' AND ANY -* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED -* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE -* DISCLAIMED. IN NO EVENT SHALL JICE, MINGOS OR RMTEW BE LIABLE FOR ANY -* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES -* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; -* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND -* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS -* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. -*/ +/* BSD 3-Clause License + * + * Copyright © 2008-2019, Jice and the libtcod contributors. + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions are met: + * + * 1. Redistributions of source code must retain the above copyright notice, + * this list of conditions and the following disclaimer. + * + * 2. Redistributions in binary form must reproduce the above copyright notice, + * this list of conditions and the following disclaimer in the documentation + * and/or other materials provided with the distribution. + * + * 3. Neither the name of the copyright holder nor the names of its + * contributors may be used to endorse or promote products derived from + * this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE + * POSSIBILITY OF SUCH DAMAGE. + */ #include "list.h" #include /* calloc */ diff --git a/tcod_sys/libtcod/src/libtcod/mersenne.cpp b/tcod_sys/libtcod/src/libtcod/mersenne.cpp index ef1bb568d..e3b59318f 100644 --- a/tcod_sys/libtcod/src/libtcod/mersenne.cpp +++ b/tcod_sys/libtcod/src/libtcod/mersenne.cpp @@ -1,30 +1,34 @@ -/* -* libtcod -* Copyright (c) 2008-2018 Jice & Mingos & rmtew -* All rights reserved. -* -* Redistribution and use in source and binary forms, with or without -* modification, are permitted provided that the following conditions are met: -* * Redistributions of source code must retain the above copyright -* notice, this list of conditions and the following disclaimer. -* * Redistributions in binary form must reproduce the above copyright -* notice, this list of conditions and the following disclaimer in the -* documentation and/or other materials provided with the distribution. -* * The name of Jice or Mingos may not be used to endorse or promote -* products derived from this software without specific prior written -* permission. -* -* THIS SOFTWARE IS PROVIDED BY JICE, MINGOS AND RMTEW ``AS IS'' AND ANY -* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED -* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE -* DISCLAIMED. IN NO EVENT SHALL JICE, MINGOS OR RMTEW BE LIABLE FOR ANY -* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES -* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; -* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND -* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS -* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. -*/ +/* BSD 3-Clause License + * + * Copyright © 2008-2019, Jice and the libtcod contributors. + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions are met: + * + * 1. Redistributions of source code must retain the above copyright notice, + * this list of conditions and the following disclaimer. + * + * 2. Redistributions in binary form must reproduce the above copyright notice, + * this list of conditions and the following disclaimer in the documentation + * and/or other materials provided with the distribution. + * + * 3. Neither the name of the copyright holder nor the names of its + * contributors may be used to endorse or promote products derived from + * this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE + * POSSIBILITY OF SUCH DAMAGE. + */ #include "mersenne.hpp" #include @@ -53,7 +57,8 @@ TCODRandom::~TCODRandom() { } TCODRandom *TCODRandom::save() const { - TCODRandom *ret=new TCODRandom(((mersenne_data_t *)data)->algo,false); + TCODRandom *ret = + new TCODRandom(data->algo, false); ret->data=TCOD_random_save(data); return ret; } diff --git a/tcod_sys/libtcod/src/libtcod/mersenne.h b/tcod_sys/libtcod/src/libtcod/mersenne.h index 1deaa012f..906faaee5 100644 --- a/tcod_sys/libtcod/src/libtcod/mersenne.h +++ b/tcod_sys/libtcod/src/libtcod/mersenne.h @@ -1,30 +1,34 @@ -/* -* libtcod -* Copyright (c) 2008-2018 Jice & Mingos & rmtew -* All rights reserved. -* -* Redistribution and use in source and binary forms, with or without -* modification, are permitted provided that the following conditions are met: -* * Redistributions of source code must retain the above copyright -* notice, this list of conditions and the following disclaimer. -* * Redistributions in binary form must reproduce the above copyright -* notice, this list of conditions and the following disclaimer in the -* documentation and/or other materials provided with the distribution. -* * The name of Jice or Mingos may not be used to endorse or promote -* products derived from this software without specific prior written -* permission. -* -* THIS SOFTWARE IS PROVIDED BY JICE, MINGOS AND RMTEW ``AS IS'' AND ANY -* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED -* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE -* DISCLAIMED. IN NO EVENT SHALL JICE, MINGOS OR RMTEW BE LIABLE FOR ANY -* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES -* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; -* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND -* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS -* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. -*/ +/* BSD 3-Clause License + * + * Copyright © 2008-2019, Jice and the libtcod contributors. + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions are met: + * + * 1. Redistributions of source code must retain the above copyright notice, + * this list of conditions and the following disclaimer. + * + * 2. Redistributions in binary form must reproduce the above copyright notice, + * this list of conditions and the following disclaimer in the documentation + * and/or other materials provided with the distribution. + * + * 3. Neither the name of the copyright holder nor the names of its + * contributors may be used to endorse or promote products derived from + * this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE + * POSSIBILITY OF SUCH DAMAGE. + */ #ifndef _TCOD_RANDOM_H #define _TCOD_RANDOM_H diff --git a/tcod_sys/libtcod/src/libtcod/mersenne.hpp b/tcod_sys/libtcod/src/libtcod/mersenne.hpp index 3b09906c6..0fe1f3c17 100644 --- a/tcod_sys/libtcod/src/libtcod/mersenne.hpp +++ b/tcod_sys/libtcod/src/libtcod/mersenne.hpp @@ -1,30 +1,34 @@ -/* -* libtcod -* Copyright (c) 2008-2018 Jice & Mingos & rmtew -* All rights reserved. -* -* Redistribution and use in source and binary forms, with or without -* modification, are permitted provided that the following conditions are met: -* * Redistributions of source code must retain the above copyright -* notice, this list of conditions and the following disclaimer. -* * Redistributions in binary form must reproduce the above copyright -* notice, this list of conditions and the following disclaimer in the -* documentation and/or other materials provided with the distribution. -* * The name of Jice or Mingos may not be used to endorse or promote -* products derived from this software without specific prior written -* permission. -* -* THIS SOFTWARE IS PROVIDED BY JICE, MINGOS AND RMTEW ``AS IS'' AND ANY -* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED -* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE -* DISCLAIMED. IN NO EVENT SHALL JICE, MINGOS OR RMTEW BE LIABLE FOR ANY -* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES -* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; -* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND -* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS -* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. -*/ +/* BSD 3-Clause License + * + * Copyright © 2008-2019, Jice and the libtcod contributors. + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions are met: + * + * 1. Redistributions of source code must retain the above copyright notice, + * this list of conditions and the following disclaimer. + * + * 2. Redistributions in binary form must reproduce the above copyright notice, + * this list of conditions and the following disclaimer in the documentation + * and/or other materials provided with the distribution. + * + * 3. Neither the name of the copyright holder nor the names of its + * contributors may be used to endorse or promote products derived from + * this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE + * POSSIBILITY OF SUCH DAMAGE. + */ #ifndef _TCOD_RANDOM_HPP #define _TCOD_RANDOM_HPP @@ -393,7 +397,7 @@ In these cases, the selected mean will appear with the lowest frequency. friend class TCODLIB_API TCODHeightMap; friend class TCODLIB_API TCODNamegen; friend class TCODNameGenerator; // Used for SWIG interface, does NOT need TCODLIB_API - TCOD_random_t data; + struct TCOD_Random* data; }; #endif diff --git a/tcod_sys/libtcod/src/libtcod/mersenne_c.c b/tcod_sys/libtcod/src/libtcod/mersenne_c.c index b57ed1573..b5cb537d6 100644 --- a/tcod_sys/libtcod/src/libtcod/mersenne_c.c +++ b/tcod_sys/libtcod/src/libtcod/mersenne_c.c @@ -1,30 +1,34 @@ -/* -* libtcod -* Copyright (c) 2008-2018 Jice & Mingos & rmtew -* All rights reserved. -* -* Redistribution and use in source and binary forms, with or without -* modification, are permitted provided that the following conditions are met: -* * Redistributions of source code must retain the above copyright -* notice, this list of conditions and the following disclaimer. -* * Redistributions in binary form must reproduce the above copyright -* notice, this list of conditions and the following disclaimer in the -* documentation and/or other materials provided with the distribution. -* * The name of Jice or Mingos may not be used to endorse or promote -* products derived from this software without specific prior written -* permission. -* -* THIS SOFTWARE IS PROVIDED BY JICE, MINGOS AND RMTEW ``AS IS'' AND ANY -* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED -* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE -* DISCLAIMED. IN NO EVENT SHALL JICE, MINGOS OR RMTEW BE LIABLE FOR ANY -* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES -* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; -* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND -* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS -* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. -*/ +/* BSD 3-Clause License + * + * Copyright © 2008-2019, Jice and the libtcod contributors. + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions are met: + * + * 1. Redistributions of source code must retain the above copyright notice, + * this list of conditions and the following disclaimer. + * + * 2. Redistributions in binary form must reproduce the above copyright notice, + * this list of conditions and the following disclaimer in the documentation + * and/or other materials provided with the distribution. + * + * 3. Neither the name of the copyright holder nor the names of its + * contributors may be used to endorse or promote products derived from + * this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE + * POSSIBILITY OF SUCH DAMAGE. + */ #include "mersenne.h" #include diff --git a/tcod_sys/libtcod/src/libtcod/mersenne_types.h b/tcod_sys/libtcod/src/libtcod/mersenne_types.h index 66cb43690..e073fd34e 100644 --- a/tcod_sys/libtcod/src/libtcod/mersenne_types.h +++ b/tcod_sys/libtcod/src/libtcod/mersenne_types.h @@ -1,30 +1,34 @@ -/* -* libtcod -* Copyright (c) 2008-2018 Jice & Mingos & rmtew -* All rights reserved. -* -* Redistribution and use in source and binary forms, with or without -* modification, are permitted provided that the following conditions are met: -* * Redistributions of source code must retain the above copyright -* notice, this list of conditions and the following disclaimer. -* * Redistributions in binary form must reproduce the above copyright -* notice, this list of conditions and the following disclaimer in the -* documentation and/or other materials provided with the distribution. -* * The name of Jice or Mingos may not be used to endorse or promote -* products derived from this software without specific prior written -* permission. -* -* THIS SOFTWARE IS PROVIDED BY JICE, MINGOS AND RMTEW ``AS IS'' AND ANY -* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED -* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE -* DISCLAIMED. IN NO EVENT SHALL JICE, MINGOS OR RMTEW BE LIABLE FOR ANY -* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES -* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; -* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND -* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS -* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. -*/ +/* BSD 3-Clause License + * + * Copyright © 2008-2019, Jice and the libtcod contributors. + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions are met: + * + * 1. Redistributions of source code must retain the above copyright notice, + * this list of conditions and the following disclaimer. + * + * 2. Redistributions in binary form must reproduce the above copyright notice, + * this list of conditions and the following disclaimer in the documentation + * and/or other materials provided with the distribution. + * + * 3. Neither the name of the copyright holder nor the names of its + * contributors may be used to endorse or promote products derived from + * this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE + * POSSIBILITY OF SUCH DAMAGE. + */ #ifndef _TCOD_RANDOM_TYPES_H #define _TCOD_RANDOM_TYPES_H struct TCOD_Random; diff --git a/tcod_sys/libtcod/src/libtcod/mouse.cpp b/tcod_sys/libtcod/src/libtcod/mouse.cpp index af33c3c78..876077b09 100644 --- a/tcod_sys/libtcod/src/libtcod/mouse.cpp +++ b/tcod_sys/libtcod/src/libtcod/mouse.cpp @@ -1,30 +1,34 @@ -/* -* libtcod -* Copyright (c) 2008-2018 Jice & Mingos & rmtew -* All rights reserved. -* -* Redistribution and use in source and binary forms, with or without -* modification, are permitted provided that the following conditions are met: -* * Redistributions of source code must retain the above copyright -* notice, this list of conditions and the following disclaimer. -* * Redistributions in binary form must reproduce the above copyright -* notice, this list of conditions and the following disclaimer in the -* documentation and/or other materials provided with the distribution. -* * The name of Jice or Mingos may not be used to endorse or promote -* products derived from this software without specific prior written -* permission. -* -* THIS SOFTWARE IS PROVIDED BY JICE, MINGOS AND RMTEW ``AS IS'' AND ANY -* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED -* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE -* DISCLAIMED. IN NO EVENT SHALL JICE, MINGOS OR RMTEW BE LIABLE FOR ANY -* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES -* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; -* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND -* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS -* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. -*/ +/* BSD 3-Clause License + * + * Copyright © 2008-2019, Jice and the libtcod contributors. + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions are met: + * + * 1. Redistributions of source code must retain the above copyright notice, + * this list of conditions and the following disclaimer. + * + * 2. Redistributions in binary form must reproduce the above copyright notice, + * this list of conditions and the following disclaimer in the documentation + * and/or other materials provided with the distribution. + * + * 3. Neither the name of the copyright holder nor the names of its + * contributors may be used to endorse or promote products derived from + * this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE + * POSSIBILITY OF SUCH DAMAGE. + */ #include "mouse.hpp" #ifdef TCOD_CONSOLE_SUPPORT diff --git a/tcod_sys/libtcod/src/libtcod/mouse.h b/tcod_sys/libtcod/src/libtcod/mouse.h index 223080ae9..6fe8148e5 100644 --- a/tcod_sys/libtcod/src/libtcod/mouse.h +++ b/tcod_sys/libtcod/src/libtcod/mouse.h @@ -1,30 +1,34 @@ -/* -* libtcod -* Copyright (c) 2008-2018 Jice & Mingos & rmtew -* All rights reserved. -* -* Redistribution and use in source and binary forms, with or without -* modification, are permitted provided that the following conditions are met: -* * Redistributions of source code must retain the above copyright -* notice, this list of conditions and the following disclaimer. -* * Redistributions in binary form must reproduce the above copyright -* notice, this list of conditions and the following disclaimer in the -* documentation and/or other materials provided with the distribution. -* * The name of Jice or Mingos may not be used to endorse or promote -* products derived from this software without specific prior written -* permission. -* -* THIS SOFTWARE IS PROVIDED BY JICE, MINGOS AND RMTEW ``AS IS'' AND ANY -* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED -* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE -* DISCLAIMED. IN NO EVENT SHALL JICE, MINGOS OR RMTEW BE LIABLE FOR ANY -* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES -* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; -* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND -* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS -* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. -*/ +/* BSD 3-Clause License + * + * Copyright © 2008-2019, Jice and the libtcod contributors. + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions are met: + * + * 1. Redistributions of source code must retain the above copyright notice, + * this list of conditions and the following disclaimer. + * + * 2. Redistributions in binary form must reproduce the above copyright notice, + * this list of conditions and the following disclaimer in the documentation + * and/or other materials provided with the distribution. + * + * 3. Neither the name of the copyright holder nor the names of its + * contributors may be used to endorse or promote products derived from + * this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE + * POSSIBILITY OF SUCH DAMAGE. + */ #ifndef _TCOD_MOUSE_H #define _TCOD_MOUSE_H diff --git a/tcod_sys/libtcod/src/libtcod/mouse.hpp b/tcod_sys/libtcod/src/libtcod/mouse.hpp index ac40cfc61..757c7035b 100644 --- a/tcod_sys/libtcod/src/libtcod/mouse.hpp +++ b/tcod_sys/libtcod/src/libtcod/mouse.hpp @@ -1,30 +1,34 @@ -/* -* libtcod -* Copyright (c) 2008-2018 Jice & Mingos & rmtew -* All rights reserved. -* -* Redistribution and use in source and binary forms, with or without -* modification, are permitted provided that the following conditions are met: -* * Redistributions of source code must retain the above copyright -* notice, this list of conditions and the following disclaimer. -* * Redistributions in binary form must reproduce the above copyright -* notice, this list of conditions and the following disclaimer in the -* documentation and/or other materials provided with the distribution. -* * The name of Jice or Mingos may not be used to endorse or promote -* products derived from this software without specific prior written -* permission. -* -* THIS SOFTWARE IS PROVIDED BY JICE, MINGOS AND RMTEW ``AS IS'' AND ANY -* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED -* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE -* DISCLAIMED. IN NO EVENT SHALL JICE, MINGOS OR RMTEW BE LIABLE FOR ANY -* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES -* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; -* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND -* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS -* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. -*/ +/* BSD 3-Clause License + * + * Copyright © 2008-2019, Jice and the libtcod contributors. + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions are met: + * + * 1. Redistributions of source code must retain the above copyright notice, + * this list of conditions and the following disclaimer. + * + * 2. Redistributions in binary form must reproduce the above copyright notice, + * this list of conditions and the following disclaimer in the documentation + * and/or other materials provided with the distribution. + * + * 3. Neither the name of the copyright holder nor the names of its + * contributors may be used to endorse or promote products derived from + * this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE + * POSSIBILITY OF SUCH DAMAGE. + */ #ifndef _TCOD_MOUSE_HPP #define _TCOD_MOUSE_HPP diff --git a/tcod_sys/libtcod/src/libtcod/mouse_types.h b/tcod_sys/libtcod/src/libtcod/mouse_types.h index fa3a425b5..64f7199bf 100644 --- a/tcod_sys/libtcod/src/libtcod/mouse_types.h +++ b/tcod_sys/libtcod/src/libtcod/mouse_types.h @@ -1,30 +1,34 @@ -/* -* libtcod -* Copyright (c) 2008-2018 Jice & Mingos & rmtew -* All rights reserved. -* -* Redistribution and use in source and binary forms, with or without -* modification, are permitted provided that the following conditions are met: -* * Redistributions of source code must retain the above copyright -* notice, this list of conditions and the following disclaimer. -* * Redistributions in binary form must reproduce the above copyright -* notice, this list of conditions and the following disclaimer in the -* documentation and/or other materials provided with the distribution. -* * The name of Jice or Mingos may not be used to endorse or promote -* products derived from this software without specific prior written -* permission. -* -* THIS SOFTWARE IS PROVIDED BY JICE, MINGOS AND RMTEW ``AS IS'' AND ANY -* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED -* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE -* DISCLAIMED. IN NO EVENT SHALL JICE, MINGOS OR RMTEW BE LIABLE FOR ANY -* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES -* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; -* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND -* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS -* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. -*/ +/* BSD 3-Clause License + * + * Copyright © 2008-2019, Jice and the libtcod contributors. + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions are met: + * + * 1. Redistributions of source code must retain the above copyright notice, + * this list of conditions and the following disclaimer. + * + * 2. Redistributions in binary form must reproduce the above copyright notice, + * this list of conditions and the following disclaimer in the documentation + * and/or other materials provided with the distribution. + * + * 3. Neither the name of the copyright holder nor the names of its + * contributors may be used to endorse or promote products derived from + * this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE + * POSSIBILITY OF SUCH DAMAGE. + */ #ifndef _TCOD_MOUSE_TYPES_H #define _TCOD_MOUSE_TYPES_H diff --git a/tcod_sys/libtcod/src/libtcod/namegen.cpp b/tcod_sys/libtcod/src/libtcod/namegen.cpp index 4d405dfe4..0842e714b 100644 --- a/tcod_sys/libtcod/src/libtcod/namegen.cpp +++ b/tcod_sys/libtcod/src/libtcod/namegen.cpp @@ -1,30 +1,34 @@ -/* -* libtcod -* Copyright (c) 2008-2018 Jice & Mingos & rmtew -* All rights reserved. -* -* Redistribution and use in source and binary forms, with or without -* modification, are permitted provided that the following conditions are met: -* * Redistributions of source code must retain the above copyright -* notice, this list of conditions and the following disclaimer. -* * Redistributions in binary form must reproduce the above copyright -* notice, this list of conditions and the following disclaimer in the -* documentation and/or other materials provided with the distribution. -* * The name of Jice or Mingos may not be used to endorse or promote -* products derived from this software without specific prior written -* permission. -* -* THIS SOFTWARE IS PROVIDED BY JICE, MINGOS AND RMTEW ``AS IS'' AND ANY -* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED -* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE -* DISCLAIMED. IN NO EVENT SHALL JICE, MINGOS OR RMTEW BE LIABLE FOR ANY -* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES -* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; -* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND -* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS -* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. -*/ +/* BSD 3-Clause License + * + * Copyright © 2008-2019, Jice and the libtcod contributors. + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions are met: + * + * 1. Redistributions of source code must retain the above copyright notice, + * this list of conditions and the following disclaimer. + * + * 2. Redistributions in binary form must reproduce the above copyright notice, + * this list of conditions and the following disclaimer in the documentation + * and/or other materials provided with the distribution. + * + * 3. Neither the name of the copyright holder nor the names of its + * contributors may be used to endorse or promote products derived from + * this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE + * POSSIBILITY OF SUCH DAMAGE. + */ /* * Mingos' NameGen * This file was written by Dominik "Mingos" Marczuk. diff --git a/tcod_sys/libtcod/src/libtcod/namegen.h b/tcod_sys/libtcod/src/libtcod/namegen.h index 8b7463f75..cf3daf9cc 100644 --- a/tcod_sys/libtcod/src/libtcod/namegen.h +++ b/tcod_sys/libtcod/src/libtcod/namegen.h @@ -1,30 +1,34 @@ -/* -* libtcod -* Copyright (c) 2008-2018 Jice & Mingos & rmtew -* All rights reserved. -* -* Redistribution and use in source and binary forms, with or without -* modification, are permitted provided that the following conditions are met: -* * Redistributions of source code must retain the above copyright -* notice, this list of conditions and the following disclaimer. -* * Redistributions in binary form must reproduce the above copyright -* notice, this list of conditions and the following disclaimer in the -* documentation and/or other materials provided with the distribution. -* * The name of Jice or Mingos may not be used to endorse or promote -* products derived from this software without specific prior written -* permission. -* -* THIS SOFTWARE IS PROVIDED BY JICE, MINGOS AND RMTEW ``AS IS'' AND ANY -* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED -* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE -* DISCLAIMED. IN NO EVENT SHALL JICE, MINGOS OR RMTEW BE LIABLE FOR ANY -* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES -* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; -* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND -* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS -* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. -*/ +/* BSD 3-Clause License + * + * Copyright © 2008-2019, Jice and the libtcod contributors. + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions are met: + * + * 1. Redistributions of source code must retain the above copyright notice, + * this list of conditions and the following disclaimer. + * + * 2. Redistributions in binary form must reproduce the above copyright notice, + * this list of conditions and the following disclaimer in the documentation + * and/or other materials provided with the distribution. + * + * 3. Neither the name of the copyright holder nor the names of its + * contributors may be used to endorse or promote products derived from + * this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE + * POSSIBILITY OF SUCH DAMAGE. + */ /* * Mingos' NameGen * This file was written by Dominik "Mingos" Marczuk. diff --git a/tcod_sys/libtcod/src/libtcod/namegen.hpp b/tcod_sys/libtcod/src/libtcod/namegen.hpp index 36a253a1f..7ca953f1b 100644 --- a/tcod_sys/libtcod/src/libtcod/namegen.hpp +++ b/tcod_sys/libtcod/src/libtcod/namegen.hpp @@ -1,30 +1,34 @@ -/* -* libtcod -* Copyright (c) 2008-2018 Jice & Mingos & rmtew -* All rights reserved. -* -* Redistribution and use in source and binary forms, with or without -* modification, are permitted provided that the following conditions are met: -* * Redistributions of source code must retain the above copyright -* notice, this list of conditions and the following disclaimer. -* * Redistributions in binary form must reproduce the above copyright -* notice, this list of conditions and the following disclaimer in the -* documentation and/or other materials provided with the distribution. -* * The name of Jice or Mingos may not be used to endorse or promote -* products derived from this software without specific prior written -* permission. -* -* THIS SOFTWARE IS PROVIDED BY JICE, MINGOS AND RMTEW ``AS IS'' AND ANY -* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED -* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE -* DISCLAIMED. IN NO EVENT SHALL JICE, MINGOS OR RMTEW BE LIABLE FOR ANY -* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES -* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; -* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND -* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS -* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. -*/ +/* BSD 3-Clause License + * + * Copyright © 2008-2019, Jice and the libtcod contributors. + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions are met: + * + * 1. Redistributions of source code must retain the above copyright notice, + * this list of conditions and the following disclaimer. + * + * 2. Redistributions in binary form must reproduce the above copyright notice, + * this list of conditions and the following disclaimer in the documentation + * and/or other materials provided with the distribution. + * + * 3. Neither the name of the copyright holder nor the names of its + * contributors may be used to endorse or promote products derived from + * this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE + * POSSIBILITY OF SUCH DAMAGE. + */ /* * Mingos' NameGen * This file was written by Dominik "Mingos" Marczuk. diff --git a/tcod_sys/libtcod/src/libtcod/namegen_c.c b/tcod_sys/libtcod/src/libtcod/namegen_c.c index c2d890df4..0521e5fcb 100644 --- a/tcod_sys/libtcod/src/libtcod/namegen_c.c +++ b/tcod_sys/libtcod/src/libtcod/namegen_c.c @@ -1,30 +1,34 @@ -/* -* libtcod -* Copyright (c) 2008-2018 Jice & Mingos & rmtew -* All rights reserved. -* -* Redistribution and use in source and binary forms, with or without -* modification, are permitted provided that the following conditions are met: -* * Redistributions of source code must retain the above copyright -* notice, this list of conditions and the following disclaimer. -* * Redistributions in binary form must reproduce the above copyright -* notice, this list of conditions and the following disclaimer in the -* documentation and/or other materials provided with the distribution. -* * The name of Jice or Mingos may not be used to endorse or promote -* products derived from this software without specific prior written -* permission. -* -* THIS SOFTWARE IS PROVIDED BY JICE, MINGOS AND RMTEW ``AS IS'' AND ANY -* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED -* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE -* DISCLAIMED. IN NO EVENT SHALL JICE, MINGOS OR RMTEW BE LIABLE FOR ANY -* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES -* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; -* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND -* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS -* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. -*/ +/* BSD 3-Clause License + * + * Copyright © 2008-2019, Jice and the libtcod contributors. + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions are met: + * + * 1. Redistributions of source code must retain the above copyright notice, + * this list of conditions and the following disclaimer. + * + * 2. Redistributions in binary form must reproduce the above copyright notice, + * this list of conditions and the following disclaimer in the documentation + * and/or other materials provided with the distribution. + * + * 3. Neither the name of the copyright holder nor the names of its + * contributors may be used to endorse or promote products derived from + * this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE + * POSSIBILITY OF SUCH DAMAGE. + */ /* * Mingos' NameGen * This file was written by Dominik "Mingos" Marczuk. diff --git a/tcod_sys/libtcod/src/libtcod/noise.cpp b/tcod_sys/libtcod/src/libtcod/noise.cpp index cce723f70..05ab77c8b 100644 --- a/tcod_sys/libtcod/src/libtcod/noise.cpp +++ b/tcod_sys/libtcod/src/libtcod/noise.cpp @@ -1,30 +1,34 @@ -/* -* libtcod -* Copyright (c) 2008-2018 Jice & Mingos & rmtew -* All rights reserved. -* -* Redistribution and use in source and binary forms, with or without -* modification, are permitted provided that the following conditions are met: -* * Redistributions of source code must retain the above copyright -* notice, this list of conditions and the following disclaimer. -* * Redistributions in binary form must reproduce the above copyright -* notice, this list of conditions and the following disclaimer in the -* documentation and/or other materials provided with the distribution. -* * The name of Jice or Mingos may not be used to endorse or promote -* products derived from this software without specific prior written -* permission. -* -* THIS SOFTWARE IS PROVIDED BY JICE, MINGOS AND RMTEW ``AS IS'' AND ANY -* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED -* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE -* DISCLAIMED. IN NO EVENT SHALL JICE, MINGOS OR RMTEW BE LIABLE FOR ANY -* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES -* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; -* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND -* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS -* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. -*/ +/* BSD 3-Clause License + * + * Copyright © 2008-2019, Jice and the libtcod contributors. + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions are met: + * + * 1. Redistributions of source code must retain the above copyright notice, + * this list of conditions and the following disclaimer. + * + * 2. Redistributions in binary form must reproduce the above copyright notice, + * this list of conditions and the following disclaimer in the documentation + * and/or other materials provided with the distribution. + * + * 3. Neither the name of the copyright holder nor the names of its + * contributors may be used to endorse or promote products derived from + * this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE + * POSSIBILITY OF SUCH DAMAGE. + */ #include "noise.hpp" #include diff --git a/tcod_sys/libtcod/src/libtcod/noise.h b/tcod_sys/libtcod/src/libtcod/noise.h index d8afab8ba..bddfa5803 100644 --- a/tcod_sys/libtcod/src/libtcod/noise.h +++ b/tcod_sys/libtcod/src/libtcod/noise.h @@ -1,30 +1,34 @@ -/* -* libtcod -* Copyright (c) 2008-2018 Jice & Mingos & rmtew -* All rights reserved. -* -* Redistribution and use in source and binary forms, with or without -* modification, are permitted provided that the following conditions are met: -* * Redistributions of source code must retain the above copyright -* notice, this list of conditions and the following disclaimer. -* * Redistributions in binary form must reproduce the above copyright -* notice, this list of conditions and the following disclaimer in the -* documentation and/or other materials provided with the distribution. -* * The name of Jice or Mingos may not be used to endorse or promote -* products derived from this software without specific prior written -* permission. -* -* THIS SOFTWARE IS PROVIDED BY JICE, MINGOS AND RMTEW ``AS IS'' AND ANY -* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED -* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE -* DISCLAIMED. IN NO EVENT SHALL JICE, MINGOS OR RMTEW BE LIABLE FOR ANY -* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES -* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; -* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND -* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS -* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. -*/ +/* BSD 3-Clause License + * + * Copyright © 2008-2019, Jice and the libtcod contributors. + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions are met: + * + * 1. Redistributions of source code must retain the above copyright notice, + * this list of conditions and the following disclaimer. + * + * 2. Redistributions in binary form must reproduce the above copyright notice, + * this list of conditions and the following disclaimer in the documentation + * and/or other materials provided with the distribution. + * + * 3. Neither the name of the copyright holder nor the names of its + * contributors may be used to endorse or promote products derived from + * this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE + * POSSIBILITY OF SUCH DAMAGE. + */ #ifndef _TCOD_PERLIN_H #define _TCOD_PERLIN_H diff --git a/tcod_sys/libtcod/src/libtcod/noise.hpp b/tcod_sys/libtcod/src/libtcod/noise.hpp index 915b9cd4a..ca2eb958b 100644 --- a/tcod_sys/libtcod/src/libtcod/noise.hpp +++ b/tcod_sys/libtcod/src/libtcod/noise.hpp @@ -1,30 +1,34 @@ -/* -* libtcod -* Copyright (c) 2008-2018 Jice & Mingos & rmtew -* All rights reserved. -* -* Redistribution and use in source and binary forms, with or without -* modification, are permitted provided that the following conditions are met: -* * Redistributions of source code must retain the above copyright -* notice, this list of conditions and the following disclaimer. -* * Redistributions in binary form must reproduce the above copyright -* notice, this list of conditions and the following disclaimer in the -* documentation and/or other materials provided with the distribution. -* * The name of Jice or Mingos may not be used to endorse or promote -* products derived from this software without specific prior written -* permission. -* -* THIS SOFTWARE IS PROVIDED BY JICE, MINGOS AND RMTEW ``AS IS'' AND ANY -* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED -* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE -* DISCLAIMED. IN NO EVENT SHALL JICE, MINGOS OR RMTEW BE LIABLE FOR ANY -* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES -* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; -* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND -* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS -* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. -*/ +/* BSD 3-Clause License + * + * Copyright © 2008-2019, Jice and the libtcod contributors. + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions are met: + * + * 1. Redistributions of source code must retain the above copyright notice, + * this list of conditions and the following disclaimer. + * + * 2. Redistributions in binary form must reproduce the above copyright notice, + * this list of conditions and the following disclaimer in the documentation + * and/or other materials provided with the distribution. + * + * 3. Neither the name of the copyright holder nor the names of its + * contributors may be used to endorse or promote products derived from + * this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE + * POSSIBILITY OF SUCH DAMAGE. + */ #ifndef _TCOD_PERLIN_HPP #define _TCOD_PERLIN_HPP diff --git a/tcod_sys/libtcod/src/libtcod/noise_c.c b/tcod_sys/libtcod/src/libtcod/noise_c.c index 02c10d716..90b02823c 100644 --- a/tcod_sys/libtcod/src/libtcod/noise_c.c +++ b/tcod_sys/libtcod/src/libtcod/noise_c.c @@ -1,30 +1,34 @@ -/* -* libtcod -* Copyright (c) 2008-2018 Jice & Mingos & rmtew -* All rights reserved. -* -* Redistribution and use in source and binary forms, with or without -* modification, are permitted provided that the following conditions are met: -* * Redistributions of source code must retain the above copyright -* notice, this list of conditions and the following disclaimer. -* * Redistributions in binary form must reproduce the above copyright -* notice, this list of conditions and the following disclaimer in the -* documentation and/or other materials provided with the distribution. -* * The name of Jice or Mingos may not be used to endorse or promote -* products derived from this software without specific prior written -* permission. -* -* THIS SOFTWARE IS PROVIDED BY JICE, MINGOS AND RMTEW ``AS IS'' AND ANY -* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED -* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE -* DISCLAIMED. IN NO EVENT SHALL JICE, MINGOS OR RMTEW BE LIABLE FOR ANY -* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES -* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; -* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND -* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS -* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. -*/ +/* BSD 3-Clause License + * + * Copyright © 2008-2019, Jice and the libtcod contributors. + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions are met: + * + * 1. Redistributions of source code must retain the above copyright notice, + * this list of conditions and the following disclaimer. + * + * 2. Redistributions in binary form must reproduce the above copyright notice, + * this list of conditions and the following disclaimer in the documentation + * and/or other materials provided with the distribution. + * + * 3. Neither the name of the copyright holder nor the names of its + * contributors may be used to endorse or promote products derived from + * this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE + * POSSIBILITY OF SUCH DAMAGE. + */ #include "noise.h" #include diff --git a/tcod_sys/libtcod/src/libtcod/noise_defaults.h b/tcod_sys/libtcod/src/libtcod/noise_defaults.h index 14f9e0497..bce4adcc6 100644 --- a/tcod_sys/libtcod/src/libtcod/noise_defaults.h +++ b/tcod_sys/libtcod/src/libtcod/noise_defaults.h @@ -1,30 +1,34 @@ -/* -* libtcod -* Copyright (c) 2008-2018 Jice & Mingos & rmtew -* All rights reserved. -* -* Redistribution and use in source and binary forms, with or without -* modification, are permitted provided that the following conditions are met: -* * Redistributions of source code must retain the above copyright -* notice, this list of conditions and the following disclaimer. -* * Redistributions in binary form must reproduce the above copyright -* notice, this list of conditions and the following disclaimer in the -* documentation and/or other materials provided with the distribution. -* * The name of Jice or Mingos may not be used to endorse or promote -* products derived from this software without specific prior written -* permission. -* -* THIS SOFTWARE IS PROVIDED BY JICE, MINGOS AND RMTEW ``AS IS'' AND ANY -* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED -* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE -* DISCLAIMED. IN NO EVENT SHALL JICE, MINGOS OR RMTEW BE LIABLE FOR ANY -* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES -* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; -* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND -* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS -* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. -*/ +/* BSD 3-Clause License + * + * Copyright © 2008-2019, Jice and the libtcod contributors. + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions are met: + * + * 1. Redistributions of source code must retain the above copyright notice, + * this list of conditions and the following disclaimer. + * + * 2. Redistributions in binary form must reproduce the above copyright notice, + * this list of conditions and the following disclaimer in the documentation + * and/or other materials provided with the distribution. + * + * 3. Neither the name of the copyright holder nor the names of its + * contributors may be used to endorse or promote products derived from + * this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE + * POSSIBILITY OF SUCH DAMAGE. + */ #ifndef _TCOD_NOISE_DEFAULTS #define _TCOD_NOISE_DEFAULTS diff --git a/tcod_sys/libtcod/src/libtcod/parser.cpp b/tcod_sys/libtcod/src/libtcod/parser.cpp index f3ca217d4..1d73f37b6 100644 --- a/tcod_sys/libtcod/src/libtcod/parser.cpp +++ b/tcod_sys/libtcod/src/libtcod/parser.cpp @@ -1,30 +1,34 @@ -/* -* libtcod -* Copyright (c) 2008-2018 Jice & Mingos & rmtew -* All rights reserved. -* -* Redistribution and use in source and binary forms, with or without -* modification, are permitted provided that the following conditions are met: -* * Redistributions of source code must retain the above copyright -* notice, this list of conditions and the following disclaimer. -* * Redistributions in binary form must reproduce the above copyright -* notice, this list of conditions and the following disclaimer in the -* documentation and/or other materials provided with the distribution. -* * The name of Jice or Mingos may not be used to endorse or promote -* products derived from this software without specific prior written -* permission. -* -* THIS SOFTWARE IS PROVIDED BY JICE, MINGOS AND RMTEW ``AS IS'' AND ANY -* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED -* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE -* DISCLAIMED. IN NO EVENT SHALL JICE, MINGOS OR RMTEW BE LIABLE FOR ANY -* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES -* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; -* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND -* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS -* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. -*/ +/* BSD 3-Clause License + * + * Copyright © 2008-2019, Jice and the libtcod contributors. + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions are met: + * + * 1. Redistributions of source code must retain the above copyright notice, + * this list of conditions and the following disclaimer. + * + * 2. Redistributions in binary form must reproduce the above copyright notice, + * this list of conditions and the following disclaimer in the documentation + * and/or other materials provided with the distribution. + * + * 3. Neither the name of the copyright holder nor the names of its + * contributors may be used to endorse or promote products derived from + * this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE + * POSSIBILITY OF SUCH DAMAGE. + */ #include "parser.hpp" #include @@ -72,7 +76,7 @@ TCOD_value_type_t TCODParserStruct::getPropertyType(const char *propname) const TCODParserStruct *TCODParser::newStructure(const char *name) { TCODParserStruct *ent = new TCODParserStruct(); - ent->data = TCOD_parser_new_struct(data,(char *)name); + ent->data = TCOD_parser_new_struct(data, name); defs.push(ent); return ent; } @@ -126,11 +130,15 @@ TCODParser::~TCODParser() { TCOD_parser_delete(data); } -void TCODParser::run(const char *filename, ITCODParserListener *_listener) { - listener=_listener; - parser=this; - if ( listener ) TCOD_parser_run(data,(char *)filename,&c_to_cpp_listener); - else TCOD_parser_run(data,(char *)filename, NULL); +void TCODParser::run(const char *filename, ITCODParserListener *_listener) +{ + listener = _listener; + parser = this; + if (listener) { + TCOD_parser_run(data, filename, &c_to_cpp_listener); + } else { + TCOD_parser_run(data, filename, NULL); + } } TCOD_value_type_t TCODParser::newCustomType(TCOD_parser_custom_t custom_type_parser) { diff --git a/tcod_sys/libtcod/src/libtcod/parser.h b/tcod_sys/libtcod/src/libtcod/parser.h index 67b62ec90..e0b96a844 100644 --- a/tcod_sys/libtcod/src/libtcod/parser.h +++ b/tcod_sys/libtcod/src/libtcod/parser.h @@ -1,30 +1,34 @@ -/* -* libtcod -* Copyright (c) 2008-2018 Jice & Mingos & rmtew -* All rights reserved. -* -* Redistribution and use in source and binary forms, with or without -* modification, are permitted provided that the following conditions are met: -* * Redistributions of source code must retain the above copyright -* notice, this list of conditions and the following disclaimer. -* * Redistributions in binary form must reproduce the above copyright -* notice, this list of conditions and the following disclaimer in the -* documentation and/or other materials provided with the distribution. -* * The name of Jice or Mingos may not be used to endorse or promote -* products derived from this software without specific prior written -* permission. -* -* THIS SOFTWARE IS PROVIDED BY JICE, MINGOS AND RMTEW ``AS IS'' AND ANY -* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED -* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE -* DISCLAIMED. IN NO EVENT SHALL JICE, MINGOS OR RMTEW BE LIABLE FOR ANY -* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES -* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; -* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND -* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS -* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. -*/ +/* BSD 3-Clause License + * + * Copyright © 2008-2019, Jice and the libtcod contributors. + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions are met: + * + * 1. Redistributions of source code must retain the above copyright notice, + * this list of conditions and the following disclaimer. + * + * 2. Redistributions in binary form must reproduce the above copyright notice, + * this list of conditions and the following disclaimer in the documentation + * and/or other materials provided with the distribution. + * + * 3. Neither the name of the copyright holder nor the names of its + * contributors may be used to endorse or promote products derived from + * this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE + * POSSIBILITY OF SUCH DAMAGE. + */ #ifndef _TCOD_PARSER_H #define _TCOD_PARSER_H @@ -126,7 +130,7 @@ struct TCOD_Parser; typedef struct TCOD_Parser *TCOD_parser_t; TCODLIB_API TCOD_parser_t TCOD_parser_new(void); -TCODLIB_API TCOD_parser_struct_t TCOD_parser_new_struct(TCOD_parser_t parser, char *name); +TCODLIB_API TCOD_parser_struct_t TCOD_parser_new_struct(TCOD_parser_t parser, const char *name); TCODLIB_API TCOD_value_type_t TCOD_parser_new_custom_type(TCOD_parser_t parser,TCOD_parser_custom_t custom_type_parser); TCODLIB_API void TCOD_parser_run(TCOD_parser_t parser, const char *filename, TCOD_parser_listener_t *listener); TCODLIB_API void TCOD_parser_delete(TCOD_parser_t parser); diff --git a/tcod_sys/libtcod/src/libtcod/parser.hpp b/tcod_sys/libtcod/src/libtcod/parser.hpp index a77ae79d3..fdcf58c5e 100644 --- a/tcod_sys/libtcod/src/libtcod/parser.hpp +++ b/tcod_sys/libtcod/src/libtcod/parser.hpp @@ -1,30 +1,34 @@ -/* -* libtcod -* Copyright (c) 2008-2018 Jice & Mingos & rmtew -* All rights reserved. -* -* Redistribution and use in source and binary forms, with or without -* modification, are permitted provided that the following conditions are met: -* * Redistributions of source code must retain the above copyright -* notice, this list of conditions and the following disclaimer. -* * Redistributions in binary form must reproduce the above copyright -* notice, this list of conditions and the following disclaimer in the -* documentation and/or other materials provided with the distribution. -* * The name of Jice or Mingos may not be used to endorse or promote -* products derived from this software without specific prior written -* permission. -* -* THIS SOFTWARE IS PROVIDED BY JICE, MINGOS AND RMTEW ``AS IS'' AND ANY -* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED -* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE -* DISCLAIMED. IN NO EVENT SHALL JICE, MINGOS OR RMTEW BE LIABLE FOR ANY -* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES -* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; -* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND -* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS -* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. -*/ +/* BSD 3-Clause License + * + * Copyright © 2008-2019, Jice and the libtcod contributors. + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions are met: + * + * 1. Redistributions of source code must retain the above copyright notice, + * this list of conditions and the following disclaimer. + * + * 2. Redistributions in binary form must reproduce the above copyright notice, + * this list of conditions and the following disclaimer in the documentation + * and/or other materials provided with the distribution. + * + * 3. Neither the name of the copyright holder nor the names of its + * contributors may be used to endorse or promote products derived from + * this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE + * POSSIBILITY OF SUCH DAMAGE. + */ #ifndef _TCOD_PARSER_HPP #define _TCOD_PARSER_HPP diff --git a/tcod_sys/libtcod/src/libtcod/parser_c.c b/tcod_sys/libtcod/src/libtcod/parser_c.c index 44023a983..15ec33ea2 100644 --- a/tcod_sys/libtcod/src/libtcod/parser_c.c +++ b/tcod_sys/libtcod/src/libtcod/parser_c.c @@ -1,30 +1,34 @@ -/* -* libtcod -* Copyright (c) 2008-2018 Jice & Mingos & rmtew -* All rights reserved. -* -* Redistribution and use in source and binary forms, with or without -* modification, are permitted provided that the following conditions are met: -* * Redistributions of source code must retain the above copyright -* notice, this list of conditions and the following disclaimer. -* * Redistributions in binary form must reproduce the above copyright -* notice, this list of conditions and the following disclaimer in the -* documentation and/or other materials provided with the distribution. -* * The name of Jice or Mingos may not be used to endorse or promote -* products derived from this software without specific prior written -* permission. -* -* THIS SOFTWARE IS PROVIDED BY JICE, MINGOS AND RMTEW ``AS IS'' AND ANY -* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED -* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE -* DISCLAIMED. IN NO EVENT SHALL JICE, MINGOS OR RMTEW BE LIABLE FOR ANY -* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES -* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; -* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND -* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS -* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. -*/ +/* BSD 3-Clause License + * + * Copyright © 2008-2019, Jice and the libtcod contributors. + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions are met: + * + * 1. Redistributions of source code must retain the above copyright notice, + * this list of conditions and the following disclaimer. + * + * 2. Redistributions in binary form must reproduce the above copyright notice, + * this list of conditions and the following disclaimer in the documentation + * and/or other materials provided with the distribution. + * + * 3. Neither the name of the copyright holder nor the names of its + * contributors may be used to endorse or promote products derived from + * this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE + * POSSIBILITY OF SUCH DAMAGE. + */ #include "parser.h" #include @@ -635,7 +639,7 @@ TCOD_value_type_t TCOD_parser_new_custom_type(TCOD_parser_t parser, TCOD_parser_ return type; } -TCOD_parser_struct_t TCOD_parser_new_struct(TCOD_parser_t parser, char *name) { +TCOD_parser_struct_t TCOD_parser_new_struct(TCOD_parser_t parser, const char *name) { TCOD_struct_int_t *ent = (TCOD_struct_int_t*)calloc(1,sizeof(TCOD_struct_int_t)); ent->name=TCOD_strdup(name); ent->flags=TCOD_list_new(); diff --git a/tcod_sys/libtcod/src/libtcod/path.cpp b/tcod_sys/libtcod/src/libtcod/path.cpp index 0fa1b2a88..8cc9cd88e 100644 --- a/tcod_sys/libtcod/src/libtcod/path.cpp +++ b/tcod_sys/libtcod/src/libtcod/path.cpp @@ -1,30 +1,34 @@ -/* -* libtcod -* Copyright (c) 2008-2018 Jice & Mingos & rmtew -* All rights reserved. -* -* Redistribution and use in source and binary forms, with or without -* modification, are permitted provided that the following conditions are met: -* * Redistributions of source code must retain the above copyright -* notice, this list of conditions and the following disclaimer. -* * Redistributions in binary form must reproduce the above copyright -* notice, this list of conditions and the following disclaimer in the -* documentation and/or other materials provided with the distribution. -* * The name of Jice or Mingos may not be used to endorse or promote -* products derived from this software without specific prior written -* permission. -* -* THIS SOFTWARE IS PROVIDED BY JICE, MINGOS AND RMTEW ``AS IS'' AND ANY -* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED -* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE -* DISCLAIMED. IN NO EVENT SHALL JICE, MINGOS OR RMTEW BE LIABLE FOR ANY -* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES -* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; -* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND -* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS -* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. -*/ +/* BSD 3-Clause License + * + * Copyright © 2008-2019, Jice and the libtcod contributors. + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions are met: + * + * 1. Redistributions of source code must retain the above copyright notice, + * this list of conditions and the following disclaimer. + * + * 2. Redistributions in binary form must reproduce the above copyright notice, + * this list of conditions and the following disclaimer in the documentation + * and/or other materials provided with the distribution. + * + * 3. Neither the name of the copyright holder nor the names of its + * contributors may be used to endorse or promote products derived from + * this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE + * POSSIBILITY OF SUCH DAMAGE. + */ #include "path.hpp" @@ -37,14 +41,19 @@ TCODPath::~TCODPath() { } float TCOD_path_func(int xFrom, int yFrom, int xTo,int yTo, void *data) { - TCODPath::WrapperData *cppData=(TCODPath::WrapperData *)data; + TCODPath::WrapperData *cppData = static_cast(data); return cppData->listener->getWalkCost(xFrom,yFrom,xTo,yTo,cppData->userData); } -TCODPath::TCODPath(int width, int height, const ITCODPathCallback *listener, void *userData, float diagonalCost) { - cppData.listener=listener; - cppData.userData=userData; - data = TCOD_path_new_using_function(width, height, TCOD_path_func, (void *)&cppData, diagonalCost); +TCODPath::TCODPath( + int width, int height, + const ITCODPathCallback *listener, void *userData, float diagonalCost) +{ + cppData.listener = listener; + cppData.userData = userData; + data = TCOD_path_new_using_function( + width, height, + TCOD_path_func, static_cast(&cppData), diagonalCost); } @@ -91,10 +100,14 @@ TCODDijkstra::TCODDijkstra (TCODMap *map, float diagonalCost) { } //another ctor -TCODDijkstra::TCODDijkstra (int width, int height, const ITCODPathCallback *listener, void *userData, float diagonalCost) { - cppData.listener=listener; - cppData.userData=userData; - data = TCOD_dijkstra_new_using_function(width, height, TCOD_path_func, (void *)&cppData,diagonalCost); +TCODDijkstra::TCODDijkstra ( + int width, int height, + const ITCODPathCallback *listener, void *userData, float diagonalCost) +{ + cppData.listener = listener; + cppData.userData = userData; + data = TCOD_dijkstra_new_using_function( + width, height, TCOD_path_func, static_cast(&cppData), diagonalCost); } //dtor diff --git a/tcod_sys/libtcod/src/libtcod/path.h b/tcod_sys/libtcod/src/libtcod/path.h index 7d7efd131..38b3f826a 100644 --- a/tcod_sys/libtcod/src/libtcod/path.h +++ b/tcod_sys/libtcod/src/libtcod/path.h @@ -1,30 +1,34 @@ -/* -* libtcod -* Copyright (c) 2008-2018 Jice & Mingos & rmtew -* All rights reserved. -* -* Redistribution and use in source and binary forms, with or without -* modification, are permitted provided that the following conditions are met: -* * Redistributions of source code must retain the above copyright -* notice, this list of conditions and the following disclaimer. -* * Redistributions in binary form must reproduce the above copyright -* notice, this list of conditions and the following disclaimer in the -* documentation and/or other materials provided with the distribution. -* * The name of Jice or Mingos may not be used to endorse or promote -* products derived from this software without specific prior written -* permission. -* -* THIS SOFTWARE IS PROVIDED BY JICE, MINGOS AND RMTEW ``AS IS'' AND ANY -* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED -* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE -* DISCLAIMED. IN NO EVENT SHALL JICE, MINGOS OR RMTEW BE LIABLE FOR ANY -* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES -* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; -* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND -* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS -* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. -*/ +/* BSD 3-Clause License + * + * Copyright © 2008-2019, Jice and the libtcod contributors. + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions are met: + * + * 1. Redistributions of source code must retain the above copyright notice, + * this list of conditions and the following disclaimer. + * + * 2. Redistributions in binary form must reproduce the above copyright notice, + * this list of conditions and the following disclaimer in the documentation + * and/or other materials provided with the distribution. + * + * 3. Neither the name of the copyright holder nor the names of its + * contributors may be used to endorse or promote products derived from + * this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE + * POSSIBILITY OF SUCH DAMAGE. + */ #ifndef _TCOD_PATH_H #define _TCOD_PATH_H diff --git a/tcod_sys/libtcod/src/libtcod/path.hpp b/tcod_sys/libtcod/src/libtcod/path.hpp index 830607fd1..e0f3f09f8 100644 --- a/tcod_sys/libtcod/src/libtcod/path.hpp +++ b/tcod_sys/libtcod/src/libtcod/path.hpp @@ -1,30 +1,34 @@ -/* -* libtcod -* Copyright (c) 2008-2018 Jice & Mingos & rmtew -* All rights reserved. -* -* Redistribution and use in source and binary forms, with or without -* modification, are permitted provided that the following conditions are met: -* * Redistributions of source code must retain the above copyright -* notice, this list of conditions and the following disclaimer. -* * Redistributions in binary form must reproduce the above copyright -* notice, this list of conditions and the following disclaimer in the -* documentation and/or other materials provided with the distribution. -* * The name of Jice or Mingos may not be used to endorse or promote -* products derived from this software without specific prior written -* permission. -* -* THIS SOFTWARE IS PROVIDED BY JICE, MINGOS AND RMTEW ``AS IS'' AND ANY -* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED -* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE -* DISCLAIMED. IN NO EVENT SHALL JICE, MINGOS OR RMTEW BE LIABLE FOR ANY -* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES -* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; -* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND -* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS -* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. -*/ +/* BSD 3-Clause License + * + * Copyright © 2008-2019, Jice and the libtcod contributors. + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions are met: + * + * 1. Redistributions of source code must retain the above copyright notice, + * this list of conditions and the following disclaimer. + * + * 2. Redistributions in binary form must reproduce the above copyright notice, + * this list of conditions and the following disclaimer in the documentation + * and/or other materials provided with the distribution. + * + * 3. Neither the name of the copyright holder nor the names of its + * contributors may be used to endorse or promote products derived from + * this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE + * POSSIBILITY OF SUCH DAMAGE. + */ #ifndef _TCOD_PATH_HPP #define _TCOD_PATH_HPP diff --git a/tcod_sys/libtcod/src/libtcod/path_c.c b/tcod_sys/libtcod/src/libtcod/path_c.c index 254dbb6c8..bf868ebf5 100644 --- a/tcod_sys/libtcod/src/libtcod/path_c.c +++ b/tcod_sys/libtcod/src/libtcod/path_c.c @@ -1,30 +1,34 @@ -/* -* libtcod -* Copyright (c) 2008-2018 Jice & Mingos & rmtew -* All rights reserved. -* -* Redistribution and use in source and binary forms, with or without -* modification, are permitted provided that the following conditions are met: -* * Redistributions of source code must retain the above copyright -* notice, this list of conditions and the following disclaimer. -* * Redistributions in binary form must reproduce the above copyright -* notice, this list of conditions and the following disclaimer in the -* documentation and/or other materials provided with the distribution. -* * The name of Jice or Mingos may not be used to endorse or promote -* products derived from this software without specific prior written -* permission. -* -* THIS SOFTWARE IS PROVIDED BY JICE, MINGOS AND RMTEW ``AS IS'' AND ANY -* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED -* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE -* DISCLAIMED. IN NO EVENT SHALL JICE, MINGOS OR RMTEW BE LIABLE FOR ANY -* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES -* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; -* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND -* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS -* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. -*/ +/* BSD 3-Clause License + * + * Copyright © 2008-2019, Jice and the libtcod contributors. + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions are met: + * + * 1. Redistributions of source code must retain the above copyright notice, + * this list of conditions and the following disclaimer. + * + * 2. Redistributions in binary form must reproduce the above copyright notice, + * this list of conditions and the following disclaimer in the documentation + * and/or other materials provided with the distribution. + * + * 3. Neither the name of the copyright holder nor the names of its + * contributors may be used to endorse or promote products derived from + * this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE + * POSSIBILITY OF SUCH DAMAGE. + */ #include "path.h" #include diff --git a/tcod_sys/libtcod/src/libtcod/pathfinding/astar.cpp b/tcod_sys/libtcod/src/libtcod/pathfinding/astar.cpp new file mode 100644 index 000000000..7dee4df45 --- /dev/null +++ b/tcod_sys/libtcod/src/libtcod/pathfinding/astar.cpp @@ -0,0 +1,32 @@ +/* BSD 3-Clause License + * + * Copyright © 2008-2019, Jice and the libtcod contributors. + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions are met: + * + * 1. Redistributions of source code must retain the above copyright notice, + * this list of conditions and the following disclaimer. + * + * 2. Redistributions in binary form must reproduce the above copyright notice, + * this list of conditions and the following disclaimer in the documentation + * and/or other materials provided with the distribution. + * + * 3. Neither the name of the copyright holder nor the names of its + * contributors may be used to endorse or promote products derived from + * this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE + * POSSIBILITY OF SUCH DAMAGE. + */ +#include "astar.h" diff --git a/tcod_sys/libtcod/src/libtcod/pathfinding/astar.h b/tcod_sys/libtcod/src/libtcod/pathfinding/astar.h new file mode 100644 index 000000000..3fe4b59e6 --- /dev/null +++ b/tcod_sys/libtcod/src/libtcod/pathfinding/astar.h @@ -0,0 +1,40 @@ +/* BSD 3-Clause License + * + * Copyright © 2008-2019, Jice and the libtcod contributors. + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions are met: + * + * 1. Redistributions of source code must retain the above copyright notice, + * this list of conditions and the following disclaimer. + * + * 2. Redistributions in binary form must reproduce the above copyright notice, + * this list of conditions and the following disclaimer in the documentation + * and/or other materials provided with the distribution. + * + * 3. Neither the name of the copyright holder nor the names of its + * contributors may be used to endorse or promote products derived from + * this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE + * POSSIBILITY OF SUCH DAMAGE. + */ +#ifndef LIBTCOD_PATHFINDING_ASTAR_H_ +#define LIBTCOD_PATHFINDING_ASTAR_H_ +#ifdef __cplusplus +namespace tcod { +namespace pathfinding { +} // namespace pathfinding +} // namespace tcod +#endif // __cplusplus +#endif // LIBTCOD_PATHFINDING_ASTAR_H_ diff --git a/tcod_sys/libtcod/src/libtcod/pathfinding/dijkstra.cpp b/tcod_sys/libtcod/src/libtcod/pathfinding/dijkstra.cpp new file mode 100644 index 000000000..73a7f76e6 --- /dev/null +++ b/tcod_sys/libtcod/src/libtcod/pathfinding/dijkstra.cpp @@ -0,0 +1,32 @@ +/* BSD 3-Clause License + * + * Copyright © 2008-2019, Jice and the libtcod contributors. + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions are met: + * + * 1. Redistributions of source code must retain the above copyright notice, + * this list of conditions and the following disclaimer. + * + * 2. Redistributions in binary form must reproduce the above copyright notice, + * this list of conditions and the following disclaimer in the documentation + * and/or other materials provided with the distribution. + * + * 3. Neither the name of the copyright holder nor the names of its + * contributors may be used to endorse or promote products derived from + * this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE + * POSSIBILITY OF SUCH DAMAGE. + */ +#include "dijkstra.h" diff --git a/tcod_sys/libtcod/src/libtcod/pathfinding/dijkstra.h b/tcod_sys/libtcod/src/libtcod/pathfinding/dijkstra.h new file mode 100644 index 000000000..117ee3926 --- /dev/null +++ b/tcod_sys/libtcod/src/libtcod/pathfinding/dijkstra.h @@ -0,0 +1,124 @@ +/* BSD 3-Clause License + * + * Copyright © 2008-2019, Jice and the libtcod contributors. + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions are met: + * + * 1. Redistributions of source code must retain the above copyright notice, + * this list of conditions and the following disclaimer. + * + * 2. Redistributions in binary form must reproduce the above copyright notice, + * this list of conditions and the following disclaimer in the documentation + * and/or other materials provided with the distribution. + * + * 3. Neither the name of the copyright holder nor the names of its + * contributors may be used to endorse or promote products derived from + * this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE + * POSSIBILITY OF SUCH DAMAGE. + */ +#ifndef LIBTCOD_PATHFINDING_DIJKSTRA_H_ +#define LIBTCOD_PATHFINDING_DIJKSTRA_H_ +#ifdef __cplusplus +#include +#include +#include +#include +#include +#include +#include +#include +#endif // __cplusplus +#include "generic.h" +#include "../utility/vector2.h" + +#ifdef __cplusplus +namespace tcod { +namespace pathfinding { +/** + * Create an unsorted heap from a distance map. + */ +template +auto dijkstra_make_heap(const GridType& dist_grid) +{ + const typename GridType::value_type MAX_DIST = + std::numeric_limits::max(); + using node_type = std::tuple>; + std::vector heap = {}; + for (IndexSize y = 0; y < dist_grid.height(); ++y) { + for (IndexSize x = 0; x < dist_grid.width(); ++x) { + if (dist_grid.atf(x, y) == MAX_DIST) { continue; } + heap.emplace_back(node_type(dist_grid.atf(x, y), {x, y})); + } + } + return heap; +} +/** + * Private hard-coded edge positions. + * + * {x, y, is_diagonal} + */ +static constexpr std::array, 8> EDGES_{{ + {-1, -1, 1}, {0, -1, 0}, {1, -1, 1}, + {-1, 0, 0}, {1, 0, 0}, + {-1, 1, 1}, {0, 1, 0}, {1, 1, 1}, +}}; +/** + * Recompute a Dijkstra distance map. + */ +template +void dijkstra_compute(DistGrid& dist_grid, const CostGrid& cost_grid, + CostType cardinal=2, CostType diagonal=3, + PathGrid* path_grid=nullptr) +{ + using dist_type = typename DistGrid::value_type; + using index_type = std::array; + + auto distance_at = [&](index_type index) -> dist_type& { + return dist_grid.atf(index); + }; + auto get_edges = [&](index_type index, auto new_edge) { + for (const auto& edge : EDGES_) { + std::array other_pos{ + index.at(0) + std::get<0>(edge), + index.at(1) + std::get<1>(edge), + }; + if (other_pos.at(0) < 0 || other_pos.at(0) >= dist_grid.width() || + other_pos.at(1) < 0 || other_pos.at(1) >= dist_grid.height()) { + continue; + } + auto cost = cost_grid.atf(other_pos); + cost *= std::get<2>(edge) ? diagonal : cardinal; + if (cost <= 0) { continue; } + new_edge(other_pos, cost); + } + }; + auto is_goal = [](auto, auto) { return 0; }; + auto heuristic = [](auto dist, auto){ return dist; }; + auto mark_path = [&](auto index, auto next) { + if(path_grid) { path_grid->atf(index) = next; } + }; + + Pathfinder pathfinder; + pathfinder.set_heap(dijkstra_make_heap(dist_grid)); + pathfinder.compute(distance_at, get_edges, is_goal, heuristic, mark_path); +} +} // namespace pathfinding +} // namespace tcod +#endif // __cplusplus +#endif // LIBTCOD_PATHFINDING_DIJKSTRA_H_ diff --git a/tcod_sys/libtcod/src/libtcod/pathfinding/generic.cpp b/tcod_sys/libtcod/src/libtcod/pathfinding/generic.cpp new file mode 100644 index 000000000..d9792d19b --- /dev/null +++ b/tcod_sys/libtcod/src/libtcod/pathfinding/generic.cpp @@ -0,0 +1,32 @@ +/* BSD 3-Clause License + * + * Copyright © 2008-2019, Jice and the libtcod contributors. + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions are met: + * + * 1. Redistributions of source code must retain the above copyright notice, + * this list of conditions and the following disclaimer. + * + * 2. Redistributions in binary form must reproduce the above copyright notice, + * this list of conditions and the following disclaimer in the documentation + * and/or other materials provided with the distribution. + * + * 3. Neither the name of the copyright holder nor the names of its + * contributors may be used to endorse or promote products derived from + * this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE + * POSSIBILITY OF SUCH DAMAGE. + */ +#include "generic.h" diff --git a/tcod_sys/libtcod/src/libtcod/pathfinding/generic.h b/tcod_sys/libtcod/src/libtcod/pathfinding/generic.h new file mode 100644 index 000000000..c256b851b --- /dev/null +++ b/tcod_sys/libtcod/src/libtcod/pathfinding/generic.h @@ -0,0 +1,179 @@ +/* BSD 3-Clause License + * + * Copyright © 2008-2019, Jice and the libtcod contributors. + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions are met: + * + * 1. Redistributions of source code must retain the above copyright notice, + * this list of conditions and the following disclaimer. + * + * 2. Redistributions in binary form must reproduce the above copyright notice, + * this list of conditions and the following disclaimer in the documentation + * and/or other materials provided with the distribution. + * + * 3. Neither the name of the copyright holder nor the names of its + * contributors may be used to endorse or promote products derived from + * this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE + * POSSIBILITY OF SUCH DAMAGE. + */ +#ifndef LIBTCOD_PATHFINDING_GENERIC_H_ +#define LIBTCOD_PATHFINDING_GENERIC_H_ +#ifdef __cplusplus +#include +#include +#include +#include +#include +#include +#include +#include +#endif // __cplusplus +#include "../utility/vector2.h" + +#ifdef __cplusplus +namespace tcod { +namespace pathfinding { +template +class Pathfinder +{ + public: + using heap_node = std::tuple; + using heap_type = std::vector; + Pathfinder() = default; + /** + * Continue the computation until is_goal is met or the heap runs empty. + * + * distance_at(IndexType index) -> DistType& + * Return a reference to the distance value at index. This function will + * read and write to these values. + * + * get_edges(IndexType index, auto new_edge) + * Get the edges for index. Edges are added using the new_edge callback: + * new_edge(IndexType destination, DistType cost) + * + * is_goal(DistType dist, IndexType index) -> bool + * When this returns True or when all paths are exhausted the computation + * will end. + * + * heuristic(DistType dist, IndexType index) -> DistType + * Determine the order of when nodes will be checked. The lowest values + * are checked before higher values. + * + * mark_path(IndexType current, IndexType next) + * Provides the best path from the current index so far. + */ + template + void compute( + DistanceAt& distance_at, + GetEdges& get_edges, + IsGoal& is_goal, + Heuristic& heuristic, + MarkPath& mark_path) + { + while (heap_.size()) { + const heap_node current_node = heap_.front(); + if (is_goal(std::get<0>(current_node), std::get<1>(current_node))) { + return; + } + std::pop_heap(heap_.begin(), heap_.end(), heap_compare); + heap_.pop_back(); + const DistType& current_dist = std::get<0>(current_node); + const IndexType& current_pos = std::get<1>(current_node); + if (current_dist > distance_at(current_pos)) { continue; } + auto edge_lambda = [&](IndexType dest, DistType cost) { + add_edge(current_pos, dest, cost, distance_at, heuristic, mark_path); + }; + get_edges(current_pos, edge_lambda); + } + } + /** + * Configure the heap. + */ + void set_heap(heap_type&& heap) noexcept + { + heap_ = std::move(heap); + std::make_heap(heap_.begin(), heap_.end(), heap_compare); + } + private: + /** + * Compute an edge, adding the results to the distance map and heap. + */ + template + void add_edge(IndexType origin, IndexType dest, DistType cost, + DistanceAt& distance_at, Heuristic& heuristic, + MarkPath& mark_path) + { + if (cost <= 0) { return; } + DistType distance = distance_at(origin) + cost; + if (distance >= distance_at(dest)) { return; } + distance_at(dest) = distance; + mark_path(dest, origin); + heap_.emplace_back(heuristic(distance, dest), dest); + std::push_heap(heap_.begin(), heap_.end(), heap_compare); + } + /** + * Compare values in the heap. + */ + static bool heap_compare(const heap_node& a, const heap_node& b) noexcept + { + return std::get<0>(a) < std::get<0>(b); + } + /** + * A priority queue of which nodes to check next. + */ + heap_type heap_ = {}; +}; +/** + * Clear a distance map by setting all values to maximum. + */ +template +void distance_clear(DistGrid& dist_grid) noexcept +{ + for (auto& i : dist_grid) { + i = std::numeric_limits::max(); + } +} +/** + * Clear a path map, setting all paths to themselves. + */ +template +void path_clear(Vector2& path_grid) noexcept +{ + for (ptrdiff_t y = 0; y < path_grid.height(); ++y) { + for (ptrdiff_t x = 0; x < path_grid.width(); ++x) { + path_grid.atf(x, y) = {x, y}; + } + } +} +template +auto get_path(const Vector2& path_grid, + const IndexType& start) -> std::vector +{ + std::vector path; + IndexType current = start; + IndexType next = path_grid.atf(current); + while (current != next) { + path.emplace_back(next); + current = next; + next = path_grid.atf(current); + } + return path; +} +} // namespace pathfinding +} // namespace tcod +#endif // __cplusplus +#endif // LIBTCOD_PATHFINDING_GENERIC_H_ diff --git a/tcod_sys/libtcod/src/libtcod/portability.h b/tcod_sys/libtcod/src/libtcod/portability.h index 3da5110b7..e48b41b39 100644 --- a/tcod_sys/libtcod/src/libtcod/portability.h +++ b/tcod_sys/libtcod/src/libtcod/portability.h @@ -1,30 +1,34 @@ -/* -* libtcod -* Copyright (c) 2008-2018 Jice & Mingos & rmtew -* All rights reserved. -* -* Redistribution and use in source and binary forms, with or without -* modification, are permitted provided that the following conditions are met: -* * Redistributions of source code must retain the above copyright -* notice, this list of conditions and the following disclaimer. -* * Redistributions in binary form must reproduce the above copyright -* notice, this list of conditions and the following disclaimer in the -* documentation and/or other materials provided with the distribution. -* * The name of Jice or Mingos may not be used to endorse or promote -* products derived from this software without specific prior written -* permission. -* -* THIS SOFTWARE IS PROVIDED BY JICE, MINGOS AND RMTEW ``AS IS'' AND ANY -* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED -* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE -* DISCLAIMED. IN NO EVENT SHALL JICE, MINGOS OR RMTEW BE LIABLE FOR ANY -* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES -* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; -* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND -* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS -* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. -*/ +/* BSD 3-Clause License + * + * Copyright © 2008-2019, Jice and the libtcod contributors. + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions are met: + * + * 1. Redistributions of source code must retain the above copyright notice, + * this list of conditions and the following disclaimer. + * + * 2. Redistributions in binary form must reproduce the above copyright notice, + * this list of conditions and the following disclaimer in the documentation + * and/or other materials provided with the distribution. + * + * 3. Neither the name of the copyright holder nor the names of its + * contributors may be used to endorse or promote products derived from + * this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE + * POSSIBILITY OF SUCH DAMAGE. + */ #ifndef LIBTCOD_PORTABILITY_H #define LIBTCOD_PORTABILITY_H /* uncomment to disable unicode support */ @@ -109,18 +113,38 @@ #endif /* DLL export */ +#if defined _WIN32 || defined __CYGWIN__ || defined __MINGW32__ #ifndef TCODLIB_API -#ifdef TCOD_WINDOWS #ifdef LIBTCOD_EXPORTS +#ifdef __GNUC__ +#define TCODLIB_API __attribute__((dllexport)) +#else #define TCODLIB_API __declspec(dllexport) +#endif // __GNUC__ +#else +#ifdef __GNUC__ +#define TCODLIB_API __attribute__((dllimport)) #else #define TCODLIB_API __declspec(dllimport) -#endif +#endif // __GNUC__ +#endif // LIBTCOD_EXPORTS +#endif // TCODLIB_API +#else +#if __GNUC__ >= 4 +#define TCODLIB_API __attribute__((visibility("default"))) #else #define TCODLIB_API -#endif +#endif // __GNUC__ >= 4 #endif +#ifndef TCODLIB_CAPI +#ifdef __cplusplus +#define TCODLIB_CAPI extern "C" TCODLIB_API +#else +#define TCODLIB_CAPI TCODLIB_API +#endif // __cplusplus +#endif // TCODLIB_CAPI + /* For now this encapsulates mouse, keyboard, and consoles themselves. */ #undef TCOD_CONSOLE_SUPPORT #undef TCOD_IMAGE_SUPPORT @@ -153,7 +177,7 @@ TCODLIB_API int TCOD_strncasecmp(const char *s1, const char *s2, size_t n); #endif /* _WIN32 */ /* cross platform deprecation */ -#if defined(__cplusplus) && __cplusplus >= 201402L +#if defined(__cplusplus) && __cplusplus >= 201402L && !defined(__clang__) #define TCOD_DEPRECATED(msg) [[deprecated(msg)]] #define TCOD_DEPRECATED_NOMESSAGE [[deprecated]] #elif defined(_MSC_VER) @@ -167,6 +191,14 @@ TCODLIB_API int TCOD_strncasecmp(const char *s1, const char *s2, size_t n); #define TCOD_DEPRECATED_NOMESSAGE #endif +/* Tells GCC the these functions are like printf. */ +#ifdef __GNUC__ +#define TCODLIB_FORMAT(str_index, first_arg) \ + __attribute__((format(printf, str_index, first_arg))) +#else +#define TCODLIB_FORMAT(str_index, first_arg) +#endif + #ifdef __cplusplus } #endif diff --git a/tcod_sys/libtcod/src/libtcod/sdl2/console_2tris.glslf b/tcod_sys/libtcod/src/libtcod/sdl2/console_2tris.glslf new file mode 100644 index 000000000..ed7dd49a9 --- /dev/null +++ b/tcod_sys/libtcod/src/libtcod/sdl2/console_2tris.glslf @@ -0,0 +1,46 @@ +SHADER_STRINGIFY( +uniform vec2 v_tiles_shape; // Tileset columns/rows. +uniform vec2 v_tiles_size; // Tileset texture size. +uniform sampler2D t_tileset; + +uniform vec2 v_console_shape; // The true size of the textures. +uniform sampler2D t_console_tile; // Packed tileset coordinates. +uniform sampler2D t_console_fg; +uniform sampler2D t_console_bg; + +varying vec2 v_coord; // Console coordinates. + +void main(void) +{ + vec2 tile_size = v_tiles_size / v_tiles_shape; + // The sample coordinate for per-tile console variables. + vec2 console_pos = floor(v_coord); + console_pos += vec2(0.5, 0.5); // Offset to the center (for sampling.) + console_pos /= v_console_shape; // Scale to fit in t_console_X textures. + + // Coordinates within a tile. + vec2 tile_interp = fract(v_coord); + + vec4 tile_encoded = vec4(texture2D(t_console_tile, console_pos)); + + // Unpack tileset index. + vec2 tile_address = vec2( + tile_encoded.x * float(0xff) + tile_encoded.y * float(0xff00), + tile_encoded.z * float(0xff) + tile_encoded.w * float(0xff00) + ); + + // Clamp the edges of tile_interp to prevent alias bleeding. + tile_interp = clamp(tile_interp, 0.5 / tile_size, 1.0 - 0.5 / tile_size); + + // Apply tile_interp and scale. + tile_address = (tile_address + tile_interp) / v_tiles_shape; + + vec4 tile_color = texture2D(t_tileset, tile_address); + + vec4 bg = texture2D(t_console_bg, console_pos); + vec4 fg = texture2D(t_console_fg, console_pos); + fg.rgb *= tile_color.rgb; + + gl_FragColor = mix(bg, fg, tile_color.a); +} +) diff --git a/tcod_sys/libtcod/src/libtcod/sdl2/console_2tris.glslv b/tcod_sys/libtcod/src/libtcod/sdl2/console_2tris.glslv new file mode 100644 index 000000000..35067db16 --- /dev/null +++ b/tcod_sys/libtcod/src/libtcod/sdl2/console_2tris.glslv @@ -0,0 +1,18 @@ +SHADER_STRINGIFY( +uniform mat4 mvp_matrix; // Model-view-projection matrix + +attribute vec2 a_vertex; // Simple vertex quad. + +uniform vec2 v_console_shape; // The true size of the textures. +uniform vec2 v_console_size; // The relative size of the console textures. + +varying vec2 v_coord; // Simple quad coordinate. + +void main(void) +{ + gl_Position = mvp_matrix * vec4(a_vertex, 0.0, 1.0); + v_coord = vec2(a_vertex.x, 1.0 - a_vertex.y); // Flip Y + // Expand to console coordinates. + v_coord *= v_console_shape * v_console_size; +} +) diff --git a/tcod_sys/libtcod/src/libtcod/sdl2/console_grid.glslf b/tcod_sys/libtcod/src/libtcod/sdl2/console_grid.glslf new file mode 100644 index 000000000..a8c8d5821 --- /dev/null +++ b/tcod_sys/libtcod/src/libtcod/sdl2/console_grid.glslf @@ -0,0 +1,16 @@ +SHADER_STRINGIFY( +uniform sampler2D t_tileset; + +varying vec2 v_tile; +varying vec4 v_fg; +varying vec4 v_bg; + +void main(void) +{ + vec4 tile_color = texture2D(t_tileset, v_tile); + vec4 fg = v_fg; + fg.rgb *= tile_color.rgb; + + gl_FragColor = mix(v_bg, fg, tile_color.a); +} +) diff --git a/tcod_sys/libtcod/src/libtcod/sdl2/console_grid.glslv b/tcod_sys/libtcod/src/libtcod/sdl2/console_grid.glslv new file mode 100644 index 000000000..d46c1451d --- /dev/null +++ b/tcod_sys/libtcod/src/libtcod/sdl2/console_grid.glslv @@ -0,0 +1,22 @@ +SHADER_STRINGIFY( +uniform mat4 mvp_matrix; // Model-view-projection matrix +uniform mat3 tileset_matrix; + +attribute vec2 a_vertex; // Vertex quad array. + +attribute vec2 a_tile; // Tile coordinates. +attribute vec4 a_fg; // Text foreground color. +attribute vec4 a_bg; // Background color. + +varying vec2 v_tile; // Simple quad coordinate. +varying vec4 v_fg; +varying vec4 v_bg; + +void main(void) +{ + gl_Position = mvp_matrix * vec4(a_vertex, 0, 1); + v_tile = (tileset_matrix * vec3(a_tile, 1)).xy; + v_fg = a_fg; + v_bg = a_bg; +} +) diff --git a/tcod_sys/libtcod/src/libtcod/sdl2/event.cpp b/tcod_sys/libtcod/src/libtcod/sdl2/event.cpp new file mode 100644 index 000000000..375854228 --- /dev/null +++ b/tcod_sys/libtcod/src/libtcod/sdl2/event.cpp @@ -0,0 +1,65 @@ +/* BSD 3-Clause License + * + * Copyright © 2008-2019, Jice and the libtcod contributors. + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions are met: + * + * 1. Redistributions of source code must retain the above copyright notice, + * this list of conditions and the following disclaimer. + * + * 2. Redistributions in binary form must reproduce the above copyright notice, + * this list of conditions and the following disclaimer in the documentation + * and/or other materials provided with the distribution. + * + * 3. Neither the name of the copyright holder nor the names of its + * contributors may be used to endorse or promote products derived from + * this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE + * POSSIBILITY OF SUCH DAMAGE. + */ +#include "event.h" + +#include + +#include "../libtcod_int.h" +#include "../engine/globals.h" + +#include +namespace tcod { +namespace sdl2 { +TCOD_event_t process_event(const union SDL_Event& ev, + TCOD_key_t& key) noexcept +{ + return TCOD_sys_handle_key_event(&ev, &key); +} +TCOD_event_t process_event(const union SDL_Event& ev, + TCOD_mouse_t& mouse) noexcept +{ + return TCOD_sys_handle_mouse_event(&ev, &mouse); +} +} // namespace sdl2 +} // namespace tcod +TCOD_event_t TCOD_sys_process_key_event( + const union SDL_Event* in, TCOD_key_t* out) +{ + if (!in || !out) { return TCOD_EVENT_NONE; } + return tcod::sdl2::process_event(*in, *out); +} +TCOD_event_t TCOD_sys_process_mouse_event( + const union SDL_Event* in, TCOD_mouse_t* out) +{ + if (!in || !out) { return TCOD_EVENT_NONE; } + return tcod::sdl2::process_event(*in, *out); +} diff --git a/tcod_sys/libtcod/src/libtcod/sdl2/event.h b/tcod_sys/libtcod/src/libtcod/sdl2/event.h new file mode 100644 index 000000000..9bc99256e --- /dev/null +++ b/tcod_sys/libtcod/src/libtcod/sdl2/event.h @@ -0,0 +1,90 @@ +/* BSD 3-Clause License + * + * Copyright © 2008-2019, Jice and the libtcod contributors. + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions are met: + * + * 1. Redistributions of source code must retain the above copyright notice, + * this list of conditions and the following disclaimer. + * + * 2. Redistributions in binary form must reproduce the above copyright notice, + * this list of conditions and the following disclaimer in the documentation + * and/or other materials provided with the distribution. + * + * 3. Neither the name of the copyright holder nor the names of its + * contributors may be used to endorse or promote products derived from + * this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE + * POSSIBILITY OF SUCH DAMAGE. + */ +#ifndef LIBTCOD_SDL2_EVENT_H_ +#define LIBTCOD_SDL2_EVENT_H_ + +#include "../console_types.h" +#include "../mouse.h" +#include "../sys.h" + +union SDL_Event; +#ifdef __cplusplus +namespace tcod { +namespace sdl2 { +/** + * Parse an SDL_Event into a key event and return the relevant TCOD_event_t. + * + * Returns TCOD_EVENT_NONE if the event wasn't keyboard related. + * \rst + * .. versionadded:: 1.11 + * \endrst + */ +TCODLIB_API +TCOD_event_t process_event(const union SDL_Event& in, + TCOD_key_t& out) noexcept; +/** + * Parse an SDL_Event into a mouse event and return the relevant TCOD_event_t. + * + * Returns TCOD_EVENT_NONE if the event wasn't mouse related. + * \rst + * .. versionadded:: 1.11 + * \endrst + */ +TCODLIB_API +TCOD_event_t process_event(const union SDL_Event& in, + TCOD_mouse_t& out) noexcept; +} // namespace sdl2 +} // namespace tcod +#endif // __cplusplus +/** + * Parse an SDL_Event into a key event and return the relevant TCOD_event_t. + * + * Returns TCOD_EVENT_NONE if the event wasn't keyboard related. + * \rst + * .. versionadded:: 1.11 + * \endrst + */ +TCODLIB_CAPI +TCOD_event_t TCOD_sys_process_key_event(const union SDL_Event* in, + TCOD_key_t* out); +/** + * Parse an SDL_Event into a mouse event and return the relevant TCOD_event_t. + * + * Returns TCOD_EVENT_NONE if the event wasn't mouse related. + * \rst + * .. versionadded:: 1.11 + * \endrst + */ +TCODLIB_CAPI +TCOD_event_t TCOD_sys_process_mouse_event(const union SDL_Event* in, + TCOD_mouse_t* out); +#endif // LIBTCOD_SDL2_EVENT_H_ diff --git a/tcod_sys/libtcod/src/libtcod/sdl2/gl2_display.cpp b/tcod_sys/libtcod/src/libtcod/sdl2/gl2_display.cpp new file mode 100644 index 000000000..f6c3153b8 --- /dev/null +++ b/tcod_sys/libtcod/src/libtcod/sdl2/gl2_display.cpp @@ -0,0 +1,91 @@ +/* BSD 3-Clause License + * + * Copyright © 2008-2019, Jice and the libtcod contributors. + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions are met: + * + * 1. Redistributions of source code must retain the above copyright notice, + * this list of conditions and the following disclaimer. + * + * 2. Redistributions in binary form must reproduce the above copyright notice, + * this list of conditions and the following disclaimer in the documentation + * and/or other materials provided with the distribution. + * + * 3. Neither the name of the copyright holder nor the names of its + * contributors may be used to endorse or promote products derived from + * this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE + * POSSIBILITY OF SUCH DAMAGE. + */ +#include "gl2_display.h" + +#include "gl2_ext_.h" +#include + +namespace tcod { +namespace sdl2 { +static std::shared_ptr new_gl_context(OpenGL2Display& self, bool vsync) +{ + std::shared_ptr new_context( + SDL_GL_CreateContext(self.get_sdl_window()), + [](SDL_GLContext context){ SDL_GL_DeleteContext(context); }); + if (!new_context) { throw std::runtime_error(SDL_GetError()); } + if(!gladLoadGLLoader(SDL_GL_GetProcAddress)) { + throw std::runtime_error("Failed to invoke the GLAD loader."); + } + SDL_GL_SetSwapInterval(vsync); + return new_context; +} +OpenGL2Display::OpenGL2Display(std::shared_ptr tileset, + std::array window_size, int window_flags, + const std::string& title, bool vsync) +: WindowedDisplay(window_size, window_flags | SDL_WINDOW_OPENGL, title), + glcontext_(new_gl_context(*this, vsync)), + tcod_renderer_(tileset) +{} +void OpenGL2Display::set_tileset(std::shared_ptr tileset) +{ + if (!tileset) { + throw std::invalid_argument("tileset must not be nullptr."); + } + tcod_renderer_ = OpenGL2Renderer(tileset); +} +void OpenGL2Display::accumulate(const TCOD_Console* console) +{ + return accumulate(console, nullptr); +} +void OpenGL2Display::accumulate(const TCOD_Console* console, const struct SDL_Rect* viewport) +{ + if (!viewport) { + int window_size[2]; + SDL_GL_GetDrawableSize(get_sdl_window(), &window_size[0], &window_size[1]); + SDL_Rect default_viewport{ 0, 0, window_size[0], window_size[1] }; + return accumulate(console, &default_viewport); + } + glViewport(viewport->x, viewport->y, viewport->w, viewport->h); + tcod_renderer_.render(console); + update_pixel_to_tile_scale(console); +} +void OpenGL2Display::present(const TCOD_Console* console) +{ + accumulate(console); + SDL_GL_SwapWindow(get_sdl_window()); +} +auto OpenGL2Display::read_pixels() const -> Image +{ + return tcod_renderer_.read_pixels(); +} +} // namespace sdl2 +} // namespace tcod diff --git a/tcod_sys/libtcod/src/libtcod/sdl2/gl2_display.h b/tcod_sys/libtcod/src/libtcod/sdl2/gl2_display.h new file mode 100644 index 000000000..d5de84f21 --- /dev/null +++ b/tcod_sys/libtcod/src/libtcod/sdl2/gl2_display.h @@ -0,0 +1,59 @@ +/* BSD 3-Clause License + * + * Copyright © 2008-2019, Jice and the libtcod contributors. + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions are met: + * + * 1. Redistributions of source code must retain the above copyright notice, + * this list of conditions and the following disclaimer. + * + * 2. Redistributions in binary form must reproduce the above copyright notice, + * this list of conditions and the following disclaimer in the documentation + * and/or other materials provided with the distribution. + * + * 3. Neither the name of the copyright holder nor the names of its + * contributors may be used to endorse or promote products derived from + * this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE + * POSSIBILITY OF SUCH DAMAGE. + */ +#ifndef LIBTCOD_SDL2_GL2_DISPLAY_H_ +#define LIBTCOD_SDL2_GL2_DISPLAY_H_ + +#include "gl2_renderer.h" +#include "sdl2_display.h" + +namespace tcod { +namespace sdl2 { +class OpenGL2Display: public WindowedDisplay { + public: + explicit OpenGL2Display( + std::shared_ptr tileset, + std::array window_size, + int window_flags, + const std::string& title, + bool vsync); + virtual void set_tileset(std::shared_ptr tileset) override; + virtual void accumulate(const TCOD_Console*) override; + virtual void accumulate(const TCOD_Console*, const struct SDL_Rect*) override; + virtual void present(const TCOD_Console*) override; + virtual auto read_pixels() const -> Image override; + private: + std::shared_ptr glcontext_; + OpenGL2Renderer tcod_renderer_; +}; +} // namespace sdl2 +} // namespace tcod +#endif //LIBTCOD_SDL2_GL2_DISPLAY_H_ diff --git a/tcod_sys/libtcod/src/libtcod/sdl2/gl2_ext_.h b/tcod_sys/libtcod/src/libtcod/sdl2/gl2_ext_.h new file mode 100644 index 000000000..29c43c0a3 --- /dev/null +++ b/tcod_sys/libtcod/src/libtcod/sdl2/gl2_ext_.h @@ -0,0 +1,68 @@ +/* BSD 3-Clause License + * + * Copyright © 2008-2019, Jice and the libtcod contributors. + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions are met: + * + * 1. Redistributions of source code must retain the above copyright notice, + * this list of conditions and the following disclaimer. + * + * 2. Redistributions in binary form must reproduce the above copyright notice, + * this list of conditions and the following disclaimer in the documentation + * and/or other materials provided with the distribution. + * + * 3. Neither the name of the copyright holder nor the names of its + * contributors may be used to endorse or promote products derived from + * this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE + * POSSIBILITY OF SUCH DAMAGE. + */ +#ifndef LIBTCOD_SDL2_GL2_EXT_H_ +#define LIBTCOD_SDL2_GL2_EXT_H_ +#include + +#include "../../vendor/glad.h" +namespace tcod { +namespace sdl2 { +class opengl_error : public std::runtime_error { + public: + explicit opengl_error(const std::string& what_arg) + : runtime_error(what_arg) + {}; +}; +inline void gl_check() { +#ifndef NDEBUG + switch(glGetError()) { + case GL_NO_ERROR: + return; + case GL_INVALID_ENUM: + throw opengl_error("GL_INVALID_ENUM"); + case GL_INVALID_VALUE: + throw opengl_error("GL_INVALID_VALUE"); + case GL_INVALID_OPERATION: + throw opengl_error("GL_INVALID_OPERATION"); + //case GL_INVALID_FRAMEBUFFER_OPERATION: + // throw opengl_error("GL_INVALID_FRAMEBUFFER_OPERATION"); + case GL_OUT_OF_MEMORY: + throw opengl_error("GL_OUT_OF_MEMORY"); + default: + throw opengl_error("Unknown OpenGL error."); + } +#endif // NDEBUG +} +inline void gl_debug() { gl_check(); } +} // namespace sdl2 +} // namespace tcod +#endif // LIBTCOD_SDL2_GL2_EXT_H_ diff --git a/tcod_sys/libtcod/src/libtcod/sdl2/gl2_raii.cpp b/tcod_sys/libtcod/src/libtcod/sdl2/gl2_raii.cpp new file mode 100644 index 000000000..9074d9283 --- /dev/null +++ b/tcod_sys/libtcod/src/libtcod/sdl2/gl2_raii.cpp @@ -0,0 +1,230 @@ +/* BSD 3-Clause License + * + * Copyright © 2008-2019, Jice and the libtcod contributors. + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions are met: + * + * 1. Redistributions of source code must retain the above copyright notice, + * this list of conditions and the following disclaimer. + * + * 2. Redistributions in binary form must reproduce the above copyright notice, + * this list of conditions and the following disclaimer in the documentation + * and/or other materials provided with the distribution. + * + * 3. Neither the name of the copyright holder nor the names of its + * contributors may be used to endorse or promote products derived from + * this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE + * POSSIBILITY OF SUCH DAMAGE. + */ +#include "gl2_raii.h" + +#include +#include +#include +#include + +#include "gl2_ext_.h" + +namespace tcod { +namespace sdl2 { +#ifdef GL_ES_VERSION_2_0 // OpenGL ES 2.0 +static const char* GLSL_VERSION_DIRECTIVE = "#version 100\n"; +#else // OpenGL 2.0 +static const char* GLSL_VERSION_DIRECTIVE = "#version 110\n"; +#endif +GLShader::GLShader(int shader_type, const std::string& source) +: shader_{glCreateShader(shader_type)} +{ + gl_check(); + if (!shader_) { + throw std::runtime_error("Error creating OpenGL shader."); + } + std::array sources{ + GLSL_VERSION_DIRECTIVE, + source.c_str(), + }; + glShaderSource( + shader_, + static_cast(sources.size()), + sources.data(), + nullptr); + gl_check(); + glCompileShader(shader_); gl_check(); +#ifndef NDEBUG + verify_shader(); +#endif +} +GLShader::~GLShader() noexcept +{ + if (shader_) { glDeleteShader(shader_); gl_check(); } +} +std::string GLShader::get_log() const +{ + std::vector info_log(get_variable(GL_INFO_LOG_LENGTH)); + if (info_log.size() == 0) { return ""; } + glGetShaderInfoLog( + shader_, + static_cast(info_log.size()), + nullptr, + info_log.data()); + gl_check(); + return std::string(info_log.data()); +} +int GLShader::get_variable(int name) const +{ + int variable; + glGetShaderiv(shader_, name, &variable); gl_check(); + return variable; +} +void GLShader::verify_shader() +{ + if (get_variable(GL_COMPILE_STATUS)) { return; } + throw std::runtime_error(std::string("Shader failed to compile:\n") + + get_log()); +} +GLProgram::GLProgram() +: program_{glCreateProgram()} +{ + gl_check(); + if (!program_) { + throw std::runtime_error("Error creating OpenGL program."); + } +} +GLProgram::GLProgram(const std::string& vshader, const std::string& fshader) +: GLProgram() +{ + attach(GLShader(GL_VERTEX_SHADER, vshader)); + attach(GLShader(GL_FRAGMENT_SHADER, fshader)); + link(); +} +GLProgram::~GLProgram() noexcept +{ + if (program_) { glDeleteProgram(program_); gl_check(); } +} +void GLProgram::attach(const GLShader& shader) +{ + glAttachShader(program_, shader.get()); gl_check(); +} +std::string GLProgram::get_log() const +{ + std::vector info_log(get_variable(GL_INFO_LOG_LENGTH)); + if (info_log.size() == 0) { return ""; } + glGetProgramInfoLog( + program_, + static_cast(info_log.size()), + nullptr, + info_log.data()); + gl_check(); + return std::string(info_log.data()); +} +void GLProgram::link() +{ + glLinkProgram(program_); gl_check(); + if (!get_variable(GL_LINK_STATUS)) { + throw std::runtime_error( + std::string("Shader program failed to link:\n") + get_log()); + } +} +void GLProgram::validate() +{ + glValidateProgram(program_); gl_check(); + if (!get_variable(GL_VALIDATE_STATUS)) { + throw std::runtime_error( + std::string("Shader program failed to validate:\n") + get_log()); + } +} +void GLProgram::use() const +{ + glUseProgram(program_); gl_check(); +} +int GLProgram::get_attribute(const std::string& name) const +{ + int attribute = glGetAttribLocation(program_, name.c_str()); + gl_check(); + return attribute; +} +int GLProgram::get_variable(int name) const +{ + int variable; + glGetProgramiv(program_, name, &variable); gl_check(); + return variable; +} +int GLProgram::get_uniform(const std::string& name) const +{ + int id = glGetUniformLocation(program_, name.c_str()); + gl_check(); + if (id == -1) { + throw std::runtime_error("Could not find uniform: " + name); + } + return id; +} + +GLBuffer::GLBuffer() +: buffer_{0} +{ + glGenBuffers(1, &buffer_); gl_check(); + if (!buffer_) { + throw std::runtime_error("Error creating OpenGL program."); + } +} +GLBuffer::~GLBuffer() noexcept +{ + if (buffer_) { glDeleteBuffers(1, &buffer_); gl_check(); } +} +void GLBuffer::allocate(int target, size_t size, const void* data, int usage) +{ + target_ = target; + bind(); + glBufferData(target_, size, data, usage); gl_check(); +} +void GLBuffer::update(size_t size, const void* data) +{ + bind(); + glBufferSubData(target_, 0, size, data); gl_check(); +} +void GLBuffer::bind() +{ + glBindBuffer(target_, buffer_); gl_check(); +} +GLTexture::GLTexture() +{ + glGenTextures(1, &texture_); +} +GLTexture::~GLTexture() noexcept +{ + if (texture_) { glDeleteTextures(1, &texture_); } +} +void GLTexture::bind() +{ + glBindTexture(GL_TEXTURE_2D, texture_); gl_check(); +} +// Framebuffers +/* +GLFramebuffer::GLFramebuffer() +{ + glGenFramebuffers(1, &framebuffer_); +} +GLFramebuffer::~GLFramebuffer() noexcept +{ + if (framebuffer_) { glDeleteFramebuffers(1, &framebuffer_); } +} +void GLFramebuffer::bind() +{ + glBindFramebuffer(GL_FRAMEBUFFER, framebuffer_); gl_check(); +} +*/ +} // namespace sdl2 +} // namespace tcod diff --git a/tcod_sys/libtcod/src/libtcod/sdl2/gl2_raii.h b/tcod_sys/libtcod/src/libtcod/sdl2/gl2_raii.h new file mode 100644 index 000000000..f14ca560f --- /dev/null +++ b/tcod_sys/libtcod/src/libtcod/sdl2/gl2_raii.h @@ -0,0 +1,195 @@ +/* BSD 3-Clause License + * + * Copyright © 2008-2019, Jice and the libtcod contributors. + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions are met: + * + * 1. Redistributions of source code must retain the above copyright notice, + * this list of conditions and the following disclaimer. + * + * 2. Redistributions in binary form must reproduce the above copyright notice, + * this list of conditions and the following disclaimer in the documentation + * and/or other materials provided with the distribution. + * + * 3. Neither the name of the copyright holder nor the names of its + * contributors may be used to endorse or promote products derived from + * this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE + * POSSIBILITY OF SUCH DAMAGE. + */ +#ifndef LIBTCOD_SDL2_GL2_RAII_H_ +#define LIBTCOD_SDL2_GL2_RAII_H_ + +#include +#include +#include +#include + +namespace tcod { +namespace sdl2 { +class GLShader { + public: + GLShader() = delete; + explicit GLShader(int shader_type, const std::string& source); + GLShader(const GLShader&) = delete; + GLShader& operator=(const GLShader&) = delete; + GLShader(GLShader&& rhs) noexcept + : shader_(rhs.shader_) + { + rhs.shader_ = 0; + } + GLShader& operator=(GLShader&& rhs) noexcept + { + std::swap(shader_, rhs.shader_); + return *this; + } + ~GLShader() noexcept; + uint32_t get() const noexcept + { + return shader_; + } + std::string get_log() const; + int get_variable(int name) const; + private: + void verify_shader(); + uint32_t shader_{0}; +}; +class GLProgram { + public: + GLProgram(); + GLProgram(const std::string& vshader, const std::string& fshader); + GLProgram(const GLProgram&) = delete; + GLProgram& operator=(const GLProgram&) = delete; + GLProgram(GLProgram&& rhs) noexcept + : program_(rhs.program_) + { + rhs.program_ = 0; + } + GLProgram& operator=(GLProgram&& rhs) noexcept + { + std::swap(program_, rhs.program_); + return *this; + } + ~GLProgram() noexcept; + uint32_t get() const noexcept + { + return program_; + } + void attach(const GLShader& shader); + std::string get_log() const; + void link(); + void validate(); + void use() const; + int get_attribute(const std::string& name) const; + int get_variable(int name) const; + int get_uniform(const std::string& name) const; + private: + uint32_t program_{0}; +}; +class GLBuffer { + public: + GLBuffer(); + template + GLBuffer(int target, const T& data, int usage) + : GLBuffer() + { + allocate(target, data, usage); + } + GLBuffer(const GLBuffer&) = delete; + GLBuffer& operator=(const GLBuffer&) = delete; + GLBuffer(GLBuffer&& rhs) noexcept + : buffer_(rhs.buffer_) + { + rhs.buffer_ = 0; + } + GLBuffer& operator=(GLBuffer&& rhs) noexcept + { + std::swap(buffer_, rhs.buffer_); + std::swap(target_, rhs.target_); + return *this; + } + ~GLBuffer() noexcept; + uint32_t get() const noexcept + { + return buffer_; + } + void allocate(int target, size_t size, const void* data, int usage); + template + void allocate(int target, const T& data, int usage) + { + allocate(target, sizeof(data[0]) * data.size(), data.data(), usage); + } + void update(size_t size, const void* data); + template + void update(const T& data) + { + update(sizeof(data[0]) * data.size(), data.data()); + } + void bind(); + private: + uint32_t buffer_{0}; + int target_{-1}; +}; +class GLTexture { + public: + GLTexture(); + GLTexture(const GLTexture&) = delete; + GLTexture& operator=(const GLTexture&) = delete; + GLTexture(GLTexture&& rhs) noexcept + : texture_(rhs.texture_) + { + rhs.texture_ = 0; + } + GLTexture& operator=(GLTexture&& rhs) noexcept + { + std::swap(texture_, rhs.texture_); + return *this; + } + ~GLTexture() noexcept; + uint32_t get() const noexcept + { + return texture_; + } + void bind(); + private: + uint32_t texture_{0}; +}; +class GLFramebuffer { + public: + GLFramebuffer(); + GLFramebuffer(const GLFramebuffer&) = delete; + GLFramebuffer& operator=(const GLFramebuffer&) = delete; + GLFramebuffer(GLFramebuffer&& rhs) noexcept + : framebuffer_(rhs.framebuffer_) + { + rhs.framebuffer_ = 0; + } + GLFramebuffer& operator=(GLFramebuffer&& rhs) noexcept + { + std::swap(framebuffer_, rhs.framebuffer_); + return *this; + } + ~GLFramebuffer() noexcept; + uint32_t get() const noexcept + { + return framebuffer_; + } + void bind(); + private: + uint32_t framebuffer_{0}; +}; +} // namespace sdl2 +} // namespace tcod +#endif // LIBTCOD_SDL2_GL2_RAII_H_ diff --git a/tcod_sys/libtcod/src/libtcod/sdl2/gl2_renderer.cpp b/tcod_sys/libtcod/src/libtcod/sdl2/gl2_renderer.cpp new file mode 100644 index 000000000..1625f2a67 --- /dev/null +++ b/tcod_sys/libtcod/src/libtcod/sdl2/gl2_renderer.cpp @@ -0,0 +1,424 @@ +/* BSD 3-Clause License + * + * Copyright © 2008-2019, Jice and the libtcod contributors. + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions are met: + * + * 1. Redistributions of source code must retain the above copyright notice, + * this list of conditions and the following disclaimer. + * + * 2. Redistributions in binary form must reproduce the above copyright notice, + * this list of conditions and the following disclaimer in the documentation + * and/or other materials provided with the distribution. + * + * 3. Neither the name of the copyright holder nor the names of its + * contributors may be used to endorse or promote products derived from + * this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE + * POSSIBILITY OF SUCH DAMAGE. + */ +#include "gl2_renderer.h" + +#include +#include +#include + +#include "gl2_ext_.h" +#include "../utility/matrix.h" +#include "../console.h" +#include "../libtcod_int.h" + +#define SHADER_STRINGIFY(...) #__VA_ARGS__ + +namespace tcod { +namespace sdl2 { +/** + * Return a number rounded up to a power of 2. + */ +int round_to_pow2(int i) +{ + if (i <= 0) { i = 1; } + i |= i >> 1; + i |= i >> 2; + i |= i >> 4; + i |= i >> 8; + return ++i; +} + +class TwoTranglesRenderer { + public: + explicit TwoTranglesRenderer(OpenGLTilesetAlias alias) + : alias_(alias), + program_( +#include "console_2tris.glslv" + , +#include "console_2tris.glslf" + ), + vertex_buffer_( + GL_ARRAY_BUFFER, + std::array{0, 0, 0, 1, 1, 0, 1, 1}, + GL_STATIC_DRAW + ) + { + program_.use(); gl_check(); + + vertex_buffer_.bind(); + const int a_vertex = program_.get_attribute("a_vertex"); + glVertexAttribPointer(a_vertex, 2, GL_BYTE, GL_FALSE, 0, 0); gl_check(); + glEnableVertexAttribArray(a_vertex); gl_check(); + + const std::array matrix{ + 2, 0, 0, 0, + 0, 2, 0, 0, + 0, 0, 1, 0, + -1, -1, 0, 1, + }; + glUniformMatrix4fv(program_.get_uniform("mvp_matrix"), + 1, GL_FALSE, matrix.data()); gl_check(); + + bg_tex_.bind(); + glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST); + glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST); + fg_tex_.bind(); + glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST); + glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST); + ch_tex_.bind(); + glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST); + glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST); + } + /** + * Upload color data to the currently bound texture. + */ + template + void upload_colors(const TCOD_Console& console, const F& color_at) + { + std::vector tile_colors; + tile_colors.reserve(console.size()); + for (int y = 0; y < console.h; ++y) { + for (int x = 0; x < console.w; ++x) { + tile_colors.emplace_back(color_at(y, x)); + } + } + glTexSubImage2D( + GL_TEXTURE_2D, 0, 0, 0, console.w, console.h, GL_RGBA, + GL_UNSIGNED_BYTE, tile_colors.data()); + } + /** + * Upload glyph positions to the currently bound texture. + */ + void upload_characters(const TCOD_Console& console) + { + std::vector tile_indexes; + tile_indexes.reserve(console.size() * 4); + for (int i = 0; i < console.size(); ++i) { + auto tile = alias_.get_tile_position(console.tiles[i].ch); + tile_indexes.emplace_back(tile.at(0) & 0xff); + tile_indexes.emplace_back(tile.at(0) >> 8); + tile_indexes.emplace_back(tile.at(1) & 0xff); + tile_indexes.emplace_back(tile.at(1) >> 8); + } + glTexSubImage2D( + GL_TEXTURE_2D, 0, 0, 0, console.w, console.h, GL_RGBA, + GL_UNSIGNED_BYTE, tile_indexes.data()); + } + void render(const TCOD_Console& console) + { + glDisable(GL_BLEND); + glDisable(GL_CULL_FACE); + glDisable(GL_DEPTH_TEST); + glDisable(GL_POLYGON_OFFSET_FILL); + glDisable(GL_SAMPLE_ALPHA_TO_COVERAGE); + glDisable(GL_SAMPLE_COVERAGE); + glDisable(GL_SCISSOR_TEST); + glDisable(GL_STENCIL_TEST); + //glClear(GL_COLOR_BUFFER_BIT); gl_check(); + program_.use(); gl_check(); + + glUniform2fv(program_.get_uniform("v_tiles_shape"), 1, + alias_.get_alias_shape().data()); + glUniform2fv(program_.get_uniform("v_tiles_size"), 1, + alias_.get_alias_size().data()); + + if (console.h > cached_size_[0] || console.w > cached_size_[1]) { + cached_size_ = {console.h, console.w}; + int tex_width = round_to_pow2(console.w); + int tex_height = round_to_pow2(console.h); + + glUniform2f(program_.get_uniform("v_console_shape"), + tex_width, tex_height); + glUniform2f(program_.get_uniform("v_console_size"), + static_cast(console.w) / tex_width, + static_cast(console.h) / tex_height); + bg_tex_.bind(); + glTexImage2D( + GL_TEXTURE_2D, 0, GL_RGBA, tex_width, tex_height, 0, GL_RGBA, + GL_UNSIGNED_BYTE, nullptr); + fg_tex_.bind(); + glTexImage2D( + GL_TEXTURE_2D, 0, GL_RGBA, tex_width, tex_height, 0, GL_RGBA, + GL_UNSIGNED_BYTE, nullptr); + ch_tex_.bind(); + glTexImage2D( + GL_TEXTURE_2D, 0, GL_RGBA, tex_width, tex_height, 0, GL_RGBA, + GL_UNSIGNED_BYTE, nullptr); + } + + glPixelStorei(GL_PACK_ALIGNMENT, 4); + + glActiveTexture(GL_TEXTURE0 + 0); + glBindTexture(GL_TEXTURE_2D, alias_.get_alias_texture(console)); + glUniform1i(program_.get_uniform("t_tileset"), 0); + + glActiveTexture(GL_TEXTURE0 + 1); + bg_tex_.bind(); + glUniform1i(program_.get_uniform("t_console_bg"), 1); + upload_colors(console, [&](int y, int x){ return console.at(y, x).bg; }); + + glActiveTexture(GL_TEXTURE0 + 2); + fg_tex_.bind(); + glUniform1i(program_.get_uniform("t_console_fg"), 2); + upload_colors(console, [&](int y, int x){ return console.at(y, x).fg; }); + + glActiveTexture(GL_TEXTURE0 + 3); + ch_tex_.bind(); + glUniform1i(program_.get_uniform("t_console_tile"), 3); + upload_characters(console); + + glDrawArrays(GL_TRIANGLE_STRIP, 0, 4); + glFlush(); + gl_check(); + } + private: + OpenGLTilesetAlias alias_; + GLProgram program_; + GLBuffer vertex_buffer_; + GLTexture ch_tex_; + GLTexture fg_tex_; + GLTexture bg_tex_; + std::array cached_size_{-1, -1}; +}; +class GridRenderer { + public: + GridRenderer(OpenGLTilesetAlias alias) + : alias_(alias), + program_( +#include "console_grid.glslv" + , +#include "console_grid.glslf" + ) + { + program_.use(); gl_check(); + const std::array matrix{ + 2, 0, 0, 0, + 0, 2, 0, 0, + 0, 0, 1, 0, + -1, -1, 0, 1, + }; + glUniformMatrix4fv(program_.get_uniform("mvp_matrix"), + 1, GL_FALSE, matrix.data()); gl_check(); + } + void setup_static(const TCOD_Console& console) + { + std::vector vertices; + std::vector elements; + vertices.reserve(console.w * console.h * 4 * 2); + elements.reserve(console.w * console.h * 6); + auto add_vertex = [&](float x, float y) { + vertices.emplace_back(x / console.w); + vertices.emplace_back(1.0f - y / console.h); + }; + for (float y = 0; y < console.h; ++y) { + for (float x = 0; x < console.w; ++x) { + for (int i : {0, 1, 2, 2, 1, 3}) { + elements.emplace_back((y * console.w + x) * 4 + i); + } + add_vertex(x, y); + add_vertex(x, y + 1); + add_vertex(x + 1, y); + add_vertex(x + 1, y + 1); + } + } + vertex_buffer_ = GLBuffer(GL_ARRAY_BUFFER, vertices, GL_STATIC_DRAW); + vertex_buffer_.bind(); + const int a_vertex = program_.get_attribute("a_vertex"); + glEnableVertexAttribArray(a_vertex); gl_check(); + glVertexAttribPointer(a_vertex, 2, GL_FLOAT, GL_FALSE, 0, 0); gl_check(); + element_buffer_ = GLBuffer(GL_ELEMENT_ARRAY_BUFFER, elements, + GL_STATIC_DRAW); + } + void setup_attributes(const TCOD_Console& console) + { + attribute_buffer_ = GLBuffer( + GL_ARRAY_BUFFER, + std::vector(console.w * console.h * 4), + GL_STREAM_DRAW); gl_check(); + attribute_buffer_.bind(); + const int a_tile = program_.get_attribute("a_tile"); + glEnableVertexAttribArray(a_tile); gl_check(); + glVertexAttribPointer( + a_tile, + 2, + GL_UNSIGNED_SHORT, + GL_FALSE, + sizeof(TileAttribute), + reinterpret_cast(offsetof(TileAttribute, tile))); gl_check(); + + const int a_fg = program_.get_attribute("a_fg"); + glEnableVertexAttribArray(a_fg); gl_check(); + glVertexAttribPointer( + a_fg, + 4, + GL_UNSIGNED_BYTE, + GL_TRUE, + sizeof(TileAttribute), + reinterpret_cast(offsetof(TileAttribute, fg))); gl_check(); + + const int a_bg = program_.get_attribute("a_bg"); + glEnableVertexAttribArray(a_bg); gl_check(); + glVertexAttribPointer( + a_bg, + 4, + GL_UNSIGNED_BYTE, + GL_TRUE, + sizeof(TileAttribute), + reinterpret_cast(offsetof(TileAttribute, bg))); gl_check(); + } + void update_attributes(const TCOD_Console& console) + { + // Setup tileset texture. + glActiveTexture(GL_TEXTURE0); + // get_alias_texture must be called before get_tile_position. + glBindTexture(GL_TEXTURE_2D, alias_.get_alias_texture(console)); + glUniform1i(program_.get_uniform("t_tileset"), 0); + + const std::array tileset_matrix{alias_.get_alias_matrix()}; + glUniformMatrix3fv(program_.get_uniform("tileset_matrix"), + 1, GL_FALSE, tileset_matrix.data()); gl_check(); + + // Upload console attributes. + std::vector attributes; + attributes.reserve(console.w * console.h * 4); + for (int y = 0; y < console.h; ++y) { + for (int x = 0; x < console.w; ++x) { + int i = y * console.w + x; + TilePos tile_pos(alias_.get_tile_position(console.tiles[i].ch)); + const TCOD_ColorRGBA& fg = console.tiles[i].fg; + const TCOD_ColorRGBA& bg = console.tiles[i].bg; + attributes.emplace_back(TilePos(tile_pos.x, tile_pos.y), fg, bg); + attributes.emplace_back(TilePos(tile_pos.x, tile_pos.y + 1), fg, bg); + attributes.emplace_back(TilePos(tile_pos.x + 1, tile_pos.y), fg, bg); + attributes.emplace_back(TilePos(tile_pos.x + 1, tile_pos.y + 1), fg, bg); + } + } + attribute_buffer_.update(attributes); + } + void setup(const TCOD_Console& console) + { + if (cached_size_[0] == console.w && cached_size_[0] == console.h) { + return; + } + cached_size_ = {console.w, console.h}; + setup_static(console); + setup_attributes(console); + } + void render(const TCOD_Console& console) + { + program_.use(); + setup(console); + update_attributes(console); + + glDisable(GL_BLEND); + glDisable(GL_CULL_FACE); + glDisable(GL_DEPTH_TEST); + glDisable(GL_POLYGON_OFFSET_FILL); + glDisable(GL_SAMPLE_ALPHA_TO_COVERAGE); + glDisable(GL_SAMPLE_COVERAGE); + glDisable(GL_SCISSOR_TEST); + glDisable(GL_STENCIL_TEST); + + element_buffer_.bind(); + glDrawElements( + GL_TRIANGLES, + cached_size_[0] * cached_size_[1] * 6, + GL_UNSIGNED_SHORT, + 0); gl_check(); + glFlush(); gl_check(); + } + private: + struct TilePos { + TilePos() = default; + TilePos(uint16_t x_, uint16_t y_) + : x(x_), y(y_) + {} + TilePos(const std::array& pos) + : TilePos(pos[0], pos[1]) + {} + uint16_t x, y; + }; + struct TileAttribute { + TileAttribute() = default; + TileAttribute( + const TilePos& tile_, const TCOD_ColorRGBA& fg_, const TCOD_ColorRGBA& bg_) + : tile(tile_), fg(fg_), bg(bg_) + {} + TilePos tile; + TCOD_ColorRGBA fg; + TCOD_ColorRGBA bg; + }; + OpenGLTilesetAlias alias_; + GLProgram program_; + GLBuffer vertex_buffer_; + GLBuffer element_buffer_; + GLBuffer attribute_buffer_; + std::array cached_size_{-1, -1}; +}; +typedef TwoTranglesRenderer ActiveOpenGL2Renderer; +class OpenGL2Renderer::impl : public ActiveOpenGL2Renderer { + public: + explicit impl(OpenGLTilesetAlias alias) + : ActiveOpenGL2Renderer(alias) + {} + auto read_pixels() const -> Image + { + int rect[4]; + glGetIntegerv(GL_VIEWPORT, rect); gl_check(); + Image image(rect[2], rect[3]); + glReadPixels(0, 0, image.width(), image.height(), + GL_RGBA, GL_UNSIGNED_BYTE, image.data()); gl_check(); + for (int y = 0; y < image.height() / 2; ++y) { + for (int x = 0; x < image.width(); ++x) { + std::swap(image.atf(x, y), image.atf(x, image.height() - 1 - y)); + } + } + return image; + } +}; + +OpenGL2Renderer::OpenGL2Renderer(OpenGLTilesetAlias alias) +: impl_(std::make_unique(alias)) +{} +OpenGL2Renderer::OpenGL2Renderer(OpenGL2Renderer&&) noexcept = default; +OpenGL2Renderer& OpenGL2Renderer::operator=(OpenGL2Renderer&&) noexcept = default; +OpenGL2Renderer::~OpenGL2Renderer() noexcept = default; +void OpenGL2Renderer::render(const TCOD_Console* console) +{ + impl_->render(tcod::console::ensure_(console)); +} +auto OpenGL2Renderer::read_pixels() const -> Image +{ + return impl_->read_pixels(); +} +} // namespace sdl2 +} // namespace tcod diff --git a/tcod_sys/libtcod/src/libtcod/sdl2/gl2_renderer.h b/tcod_sys/libtcod/src/libtcod/sdl2/gl2_renderer.h new file mode 100644 index 000000000..0db560da7 --- /dev/null +++ b/tcod_sys/libtcod/src/libtcod/sdl2/gl2_renderer.h @@ -0,0 +1,71 @@ +/* BSD 3-Clause License + * + * Copyright © 2008-2019, Jice and the libtcod contributors. + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions are met: + * + * 1. Redistributions of source code must retain the above copyright notice, + * this list of conditions and the following disclaimer. + * + * 2. Redistributions in binary form must reproduce the above copyright notice, + * this list of conditions and the following disclaimer in the documentation + * and/or other materials provided with the distribution. + * + * 3. Neither the name of the copyright holder nor the names of its + * contributors may be used to endorse or promote products derived from + * this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE + * POSSIBILITY OF SUCH DAMAGE. + */ +#ifndef LIBTCOD_SDL2_GL2_RENDERER_H_ +#define LIBTCOD_SDL2_GL2_RENDERER_H_ +#ifdef __cplusplus +#endif /* __cplusplus */ +#include + +#include "gl_alias.h" +#include "gl2_raii.h" +#include "../color/color.h" +#include "../console_types.h" +#include "../tileset/observer.h" +#include "../tileset/tileset.h" +#include "../utility/vector2.h" +#ifdef __cplusplus +namespace tcod { +namespace sdl2 { +using tcod::image::Image; +using tcod::tileset::Tileset; +class OpenGL2Renderer { + public: + explicit OpenGL2Renderer(OpenGLTilesetAlias alias); + explicit OpenGL2Renderer(std::shared_ptr tileset) + : OpenGL2Renderer(OpenGLTilesetAlias(tileset)) + {} + OpenGL2Renderer(const OpenGL2Renderer&) = delete; + OpenGL2Renderer& operator=(const OpenGL2Renderer&) = delete; + OpenGL2Renderer(OpenGL2Renderer&&) noexcept; + OpenGL2Renderer& operator=(OpenGL2Renderer&&) noexcept; + ~OpenGL2Renderer() noexcept; + + void render(const TCOD_Console* console); + auto read_pixels() const -> Image; + private: + class impl; + std::unique_ptr impl_; +}; +} // namespace sdl2 +} // namespace tcod +#endif // __cplusplus +#endif // LIBTCOD_SDL2_GL2_RENDERER_H_ diff --git a/tcod_sys/libtcod/src/libtcod/sdl2/gl_alias.cpp b/tcod_sys/libtcod/src/libtcod/sdl2/gl_alias.cpp new file mode 100644 index 000000000..96974e9d2 --- /dev/null +++ b/tcod_sys/libtcod/src/libtcod/sdl2/gl_alias.cpp @@ -0,0 +1,281 @@ +/* BSD 3-Clause License + * + * Copyright © 2008-2019, Jice and the libtcod contributors. + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions are met: + * + * 1. Redistributions of source code must retain the above copyright notice, + * this list of conditions and the following disclaimer. + * + * 2. Redistributions in binary form must reproduce the above copyright notice, + * this list of conditions and the following disclaimer in the documentation + * and/or other materials provided with the distribution. + * + * 3. Neither the name of the copyright holder nor the names of its + * contributors may be used to endorse or promote products derived from + * this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE + * POSSIBILITY OF SUCH DAMAGE. + */ +#include "gl_alias.h" + +#include +#include +#include + +#include "gl2_ext_.h" +#include +namespace tcod { +namespace sdl2 { +using image::Image; +template +class AliasPool { + public: + AliasPool() + : mutex_(), alias_pool_() + {}; + std::shared_ptr get(const Key& key, const Init& init) + { + std::unique_lock lock(mutex_); + alias_pool_.size(); + std::shared_ptr alias = alias_pool_[key].lock(); + if (!alias) { + alias_pool_[key] = alias = std::make_shared(init); + } + return alias; + } + private: + std::mutex mutex_; + std::map> alias_pool_; +}; +class OpenGLTilesetAlias::impl : public TilesetObserver { + using pool_type = AliasPool< + impl, const Tileset*, const std::shared_ptr&>; + public: + impl(const std::shared_ptr& tileset) + : TilesetObserver(tileset) + { + glGenTextures(1, &gltexture_); gl_check(); + clear_alias(); + } + auto prepare_alias(const TCOD_Console& console) -> uint32_t + { + for (int i = 0; i < console.w * console.h; ++i) { + int codepoint = console.tiles[i].ch; + if (codepoint >= static_cast(local_map_.size()) + || local_map_.at(codepoint) < 0) { + if (ensure_tile(codepoint) == -1) { + // The texture alias was replaced by a bigger one. + i = -1; // Need to start over from the beginning. + continue; + } + } + } + return gltexture_; + } + auto get_tile_position(int codepoint) const -> std::array + { + int index = local_map_.at(codepoint); + return {index % columns(), index / columns()}; + } + auto get_alias_shape() const -> std::array + { + return { + static_cast(texture_size_) / tile_width(), + static_cast(texture_size_) / tile_height(), + }; + } + auto get_alias_size() const -> std::array + { + return { + static_cast(columns() * tile_width()), + static_cast(rows() * tile_height()), + }; + } + auto get_alias_matrix() const -> std::array + { + float x = 1.0f / columns(); + x *= static_cast(columns() * tile_width()) / texture_size_; + float y = 1.0f / rows(); + y *= static_cast(rows() * tile_height()) / texture_size_; + return { + x, 0, 0, + 0, y, 0, + 0, 0, 0, + }; + } + static pool_type pool_; + protected: + virtual void on_tileset_changed( + const std::vector> &changes) override + { + for (const auto& changed : changes) { + // If this glyph is already in this alias then free it. + int codepoint = changed.second.codepoint; + if (codepoint < static_cast(local_map_.size()) + && local_map_.at(codepoint) >= 0) { + unallocated_.emplace_back(local_map_.at(codepoint)); + local_map_.at(codepoint) = -1; + } + } + } + private: + /** + * Return the rectangle for the tile `index` on the texture. + * + * Does not perform any extra checks. + */ + auto get_alias_rect(int index) const noexcept -> SDL_Rect + { + return SDL_Rect{ + (index % columns()) * tile_width(), + (index / columns()) * tile_height(), + tile_width(), + tile_height(), + }; + } + /** + * Make sure a codepoint exists on this alias. + * + * Returns 0 on success, or returns -1 if the texture was reset and + * everything needs to be regenerated. + */ + auto ensure_tile(int codepoint) -> int + { + if (codepoint >= static_cast(local_map_.size())) { + local_map_.resize(codepoint + 1, -1); + } + if (next_alias_index_ == capacity()) { + // Replace the current texture with a larger one. + texture_size_ *= 2; + clear_alias(); + return -1; // Tell prepare_alias to start over. + } + // Allocate an area of the texture alias for this codepoint. + SDL_Rect alias_rect; + if (unallocated_.size()) { + alias_rect = get_alias_rect(unallocated_.back()); + unallocated_.pop_back(); + } else { + alias_rect = get_alias_rect(next_alias_index_); + local_map_.at(codepoint) = next_alias_index_++; + } + // Find and draw the tile glyph into the alias. + const auto& charmap = tileset_->get_character_map(); + Image tile; + if (codepoint >= static_cast(charmap.size()) + || charmap.at(codepoint) < 0) { + // Glyph not in this tileset, leave blank. + tile = Image(alias_rect.w, alias_rect.h, {0, 0, 0, 0}); + } else{ + tile = tileset_->get_tiles().at(charmap.at(codepoint)).get_image(); + } + glBindTexture(GL_TEXTURE_2D, gltexture_); gl_check(); + glTexSubImage2D( + GL_TEXTURE_2D, + 0, + alias_rect.x, + alias_rect.y, + alias_rect.w, + alias_rect.h, + GL_RGBA, + GL_UNSIGNED_BYTE, + tile.data()); + return 0; // Tile is ready. + } + /** + * Replace the texture alias with an undefined texture. + * + * This function depends on the value of `texture_size_` before calling. + */ + void clear_alias() + { + for (auto& it : local_map_) { it = -1; } + unallocated_.clear(); + next_alias_index_ = 0; + glBindTexture(GL_TEXTURE_2D, gltexture_); gl_check(); + glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR); + gl_check(); + glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, texture_size_, texture_size_, 0, + GL_RGBA, GL_UNSIGNED_BYTE, nullptr); gl_check(); + glBindTexture(GL_TEXTURE_2D, 0); gl_check(); + } + /** + * Return the tile width of the assigned tileset. + */ + int tile_width() const noexcept { return tileset_->get_tile_width(); } + /** + * Return the tile height of the assigned tileset. + */ + int tile_height() const noexcept { return tileset_->get_tile_height(); } + /** + * Return the maximum columns supported by the current texture alias. + */ + int columns() const noexcept { return texture_size_ / tile_width(); } + /** + * Return the maximum rows supported by the current texture alias. + */ + int rows() const noexcept { return texture_size_ / tile_height(); } + /** + * Return the total number of tiles supported by the current texture alias. + */ + int capacity() const noexcept { return columns() * rows(); } + int texture_size_ = 256; + GLuint gltexture_ = 0; + /** + * The next index on the alias. Check `capacity` before using. + */ + int next_alias_index_ = 0; + /** + * Mapping of `Unicode -> texture_index`. + */ + std::vector local_map_; + /** + * Alias indexes that have been temporarily freed by changed tiles. + */ + std::vector unallocated_; +}; +typename OpenGLTilesetAlias::impl::pool_type OpenGLTilesetAlias::impl::pool_; + +OpenGLTilesetAlias::OpenGLTilesetAlias(std::shared_ptr tileset) +: impl_(OpenGLTilesetAlias::impl::pool_.get(tileset.get(), tileset)) +{} +const std::shared_ptr OpenGLTilesetAlias::get_tileset() const +{ + return impl_->get_tileset(); +} +uint32_t OpenGLTilesetAlias::get_alias_texture(const TCOD_Console& console) +{ + return impl_->prepare_alias(console); +} +auto OpenGLTilesetAlias::get_alias_shape() const -> std::array +{ + return impl_->get_alias_shape(); +} +auto OpenGLTilesetAlias::get_alias_size() const -> std::array +{ + return impl_->get_alias_size(); +} +auto OpenGLTilesetAlias::get_tile_position(int codepoint) const +-> std::array +{ + return impl_->get_tile_position(codepoint); +} +auto OpenGLTilesetAlias::get_alias_matrix() const -> std::array +{ + return impl_->get_alias_matrix(); +} +} // namespace sdl2 +} // namespace tcod diff --git a/tcod_sys/libtcod/src/libtcod/sdl2/gl_alias.h b/tcod_sys/libtcod/src/libtcod/sdl2/gl_alias.h new file mode 100644 index 000000000..4e77a7bb8 --- /dev/null +++ b/tcod_sys/libtcod/src/libtcod/sdl2/gl_alias.h @@ -0,0 +1,71 @@ +/* BSD 3-Clause License + * + * Copyright © 2008-2019, Jice and the libtcod contributors. + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions are met: + * + * 1. Redistributions of source code must retain the above copyright notice, + * this list of conditions and the following disclaimer. + * + * 2. Redistributions in binary form must reproduce the above copyright notice, + * this list of conditions and the following disclaimer in the documentation + * and/or other materials provided with the distribution. + * + * 3. Neither the name of the copyright holder nor the names of its + * contributors may be used to endorse or promote products derived from + * this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE + * POSSIBILITY OF SUCH DAMAGE. + */ +#ifndef LIBTCOD_SDL2_GL_ALIAS_H_ +#define LIBTCOD_SDL2_GL_ALIAS_H_ +#include +#include +#include + +#include "../console.h" +#include "../tileset/observer.h" +#ifdef __cplusplus +struct SDL_Renderer; +struct SDL_Texture; +struct SDL_Rect; + +namespace tcod { +namespace sdl2 { +using tileset::Tile; +using tileset::Tileset; +using tileset::TilesetObserver; + +class OpenGLTilesetAlias { + public: + OpenGLTilesetAlias() = default; + explicit OpenGLTilesetAlias(std::shared_ptr tileset); + ~OpenGLTilesetAlias() = default; + + const std::shared_ptr get_tileset() const; + + auto get_alias_texture(const TCOD_Console& console) -> uint32_t; + auto get_alias_shape() const -> std::array; + auto get_alias_size() const -> std::array; + auto get_alias_matrix() const -> std::array; + auto get_tile_position(int codepoint) const -> std::array; + private: + class impl; + std::shared_ptr impl_; +}; +} // namespace sdl2 +} // namespace tcod +#endif // __cplusplus +#endif // LIBTCOD_SDL2_GL_ALIAS_H_ diff --git a/tcod_sys/libtcod/src/libtcod/sdl2/legacy_backend.cpp b/tcod_sys/libtcod/src/libtcod/sdl2/legacy_backend.cpp index edac786e4..1a94ce977 100644 --- a/tcod_sys/libtcod/src/libtcod/sdl2/legacy_backend.cpp +++ b/tcod_sys/libtcod/src/libtcod/sdl2/legacy_backend.cpp @@ -1,2 +1,32 @@ - +/* BSD 3-Clause License + * + * Copyright © 2008-2019, Jice and the libtcod contributors. + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions are met: + * + * 1. Redistributions of source code must retain the above copyright notice, + * this list of conditions and the following disclaimer. + * + * 2. Redistributions in binary form must reproduce the above copyright notice, + * this list of conditions and the following disclaimer in the documentation + * and/or other materials provided with the distribution. + * + * 3. Neither the name of the copyright holder nor the names of its + * contributors may be used to endorse or promote products derived from + * this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE + * POSSIBILITY OF SUCH DAMAGE. + */ #include "legacy_backend.h" diff --git a/tcod_sys/libtcod/src/libtcod/sdl2/legacy_backend.h b/tcod_sys/libtcod/src/libtcod/sdl2/legacy_backend.h index d09eaf669..cd4fccd47 100644 --- a/tcod_sys/libtcod/src/libtcod/sdl2/legacy_backend.h +++ b/tcod_sys/libtcod/src/libtcod/sdl2/legacy_backend.h @@ -1,4 +1,34 @@ - +/* BSD 3-Clause License + * + * Copyright © 2008-2019, Jice and the libtcod contributors. + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions are met: + * + * 1. Redistributions of source code must retain the above copyright notice, + * this list of conditions and the following disclaimer. + * + * 2. Redistributions in binary form must reproduce the above copyright notice, + * this list of conditions and the following disclaimer in the documentation + * and/or other materials provided with the distribution. + * + * 3. Neither the name of the copyright holder nor the names of its + * contributors may be used to endorse or promote products derived from + * this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE + * POSSIBILITY OF SUCH DAMAGE. + */ #ifndef LIBTCOD_SDL2_LEGACY_BACKEND_H_ #define LIBTCOD_SDL2_LEGACY_BACKEND_H_ diff --git a/tcod_sys/libtcod/src/libtcod/sdl2/sdl2_alias.cpp b/tcod_sys/libtcod/src/libtcod/sdl2/sdl2_alias.cpp index 00bd82832..ad943cdc3 100644 --- a/tcod_sys/libtcod/src/libtcod/sdl2/sdl2_alias.cpp +++ b/tcod_sys/libtcod/src/libtcod/sdl2/sdl2_alias.cpp @@ -1,4 +1,34 @@ - +/* BSD 3-Clause License + * + * Copyright © 2008-2019, Jice and the libtcod contributors. + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions are met: + * + * 1. Redistributions of source code must retain the above copyright notice, + * this list of conditions and the following disclaimer. + * + * 2. Redistributions in binary form must reproduce the above copyright notice, + * this list of conditions and the following disclaimer in the documentation + * and/or other materials provided with the distribution. + * + * 3. Neither the name of the copyright holder nor the names of its + * contributors may be used to endorse or promote products derived from + * this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE + * POSSIBILITY OF SUCH DAMAGE. + */ #include "sdl2_alias.h" #include @@ -19,114 +49,248 @@ struct sdl_deleter void operator()(SDL_Texture *p) const { SDL_DestroyTexture(p); } }; -std::map, - std::weak_ptr> sdl2_alias_pool = {}; +template +class SharedObjectPool { + public: + auto get_instance(const Key& key, const Init& init) -> std::shared_ptr + { + std::unique_lock lock(mutex_); + std::shared_ptr pointer = pool_[key].lock(); + if (!pointer) { + pool_[key] = pointer = std::make_shared(init); + } + return pointer; + } + auto get_instance(const Key& key) -> std::shared_ptr + { + return get_instance(key, key); + } + private: + std::mutex mutex_; + std::map> pool_; +}; -class SDL2InternalTilesetAlias_: public TilesetObserver { +class SDL2TilesetAlias::impl : public TilesetObserver { public: - using key_type = std::tuple; - SDL2InternalTilesetAlias_(struct SDL_Renderer* renderer, - std::shared_ptr tileset) - : TilesetObserver(tileset), renderer_(renderer), texture_(nullptr) + impl() = delete; + impl(const std::shared_ptr& tileset, struct SDL_Renderer* renderer) + : TilesetObserver(tileset), renderer_(renderer) { SDL_AddEventWatch(on_sdl_event, this); if (!renderer_) { throw std::invalid_argument("renderer cannot be nullptr."); } - sync_alias(); + clear_alias(); } - ~SDL2InternalTilesetAlias_() { + impl(const std::tuple, struct SDL_Renderer*>& init) + : impl(std::get<0>(init), std::get<1>(init)) + {} + impl(const impl&) = delete; + impl& operator=(const impl&) = delete; + impl(impl&&) = delete; + impl& operator=(impl&&) = delete; + ~impl() noexcept { SDL_DelEventWatch(on_sdl_event, this); } - SDL_Texture* get_texture_alias() + /** + * Prepare and return a SDL_Texture after it contains all glyphs needed by + * `console`. + */ + auto prepare_alias(const TCOD_Console& console) -> SDL_Texture* { + for (int i = 0; i < console.w * console.h; ++i) { + int codepoint = console.tiles[i].ch; + if (codepoint >= static_cast(local_map_.size()) + || local_map_.at(codepoint) < 0) { + if (ensure_tile(codepoint) == -1) { + // The texture alias was replaced by a bigger one. + i = -1; // Need to start over from the beginning. + continue; + } + } + } return texture_.get(); } - struct SDL_Renderer* renderer_; - struct std::unique_ptr texture_; + /** + * Perform a fast rectangle lookup of a codepoint. + * + * Called after preparations finished by the `prepare_alias` method. + */ + auto get_char_rect(int codepoint) const -> SDL_Rect + { + return get_alias_rect(local_map_.at(codepoint)); + } protected: + /** + * Keep the texture alias in a valid state during tileset changes. + */ virtual void on_tileset_changed( const std::vector> &changes) override { - sync_alias(); + for (const auto& changed : changes) { + // If this glyph is already in this alias then update it. + // Otherwise just ignore it. + int codepoint = changed.second.codepoint; + if (codepoint < static_cast(local_map_.size()) + && local_map_.at(codepoint) >= 0) { + SDL_Rect rect(get_char_rect(codepoint)); + Image tile(changed.second.get_image()); + SDL_UpdateTexture( + texture_.get(), + &rect, + tile.data(), + static_cast(sizeof(tile.data()[0]) * tile.width())); + } + } } private: - void clear_alias() + /** + * Return the rectangle for the tile `index` on the texture. + * + * Does not perform any extra checks. + */ + auto get_alias_rect(int index) const noexcept -> SDL_Rect { - texture_ = nullptr; + return SDL_Rect{ + (index % columns()) * tile_width(), + (index / columns()) * tile_height(), + tile_width(), + tile_height(), + }; } - void sync_alias() + /** + * Make sure a codepoint exists on this alias. + * + * Returns 0 on success, or returns -1 if the texture was reset and + * everything needs to be regenerated. + */ + auto ensure_tile(int codepoint) -> int { - clear_alias(); - const std::vector& tiles = tileset_->get_tiles(); - int tile_width = tileset_->get_tile_width(); - int tile_height = tileset_->get_tile_height(); - int width = tile_width * tiles.size(); - int height = tile_height; + if (codepoint >= static_cast(local_map_.size())) { + local_map_.resize(codepoint + 1, -1); + } + if (next_alias_index_ == capacity()) { + // Replace the current texture with a larger one. + texture_size_ *= 2; + clear_alias(); + return -1; // Tell prepare_alias to start over. + } + // Allocate an area of the texture alias for this codepoint. + SDL_Rect alias_rect(get_alias_rect(next_alias_index_)); + local_map_.at(codepoint) = next_alias_index_++; + // Find and draw the tile glyph into the alias. + const auto& charmap = tileset_->get_character_map(); + if (codepoint >= static_cast(charmap.size()) + || charmap.at(codepoint) < 0) { + return 0; // Glyph not in this tileset, leave blank. + } + Image tile(tileset_->get_tiles().at(charmap.at(codepoint)).get_image()); + SDL_UpdateTexture(texture_.get(), &alias_rect, tile.data(), + static_cast(sizeof(tile.data()[0]) * tile.width())); + return 0; // Tile is ready. + } + /** + * Replace the texture alias with a blank texture. + * + * This function depends on the value of `texture_size_` before calling. + */ + void clear_alias() + { + for (auto& it : local_map_) { it = -1; } + next_alias_index_ = 0; texture_ = std::unique_ptr( - SDL_CreateTexture(renderer_, SDL_PIXELFORMAT_RGBA32, - SDL_TEXTUREACCESS_STATIC, width, height), + SDL_CreateTexture( + renderer_, + SDL_PIXELFORMAT_RGBA32, + SDL_TEXTUREACCESS_STATIC, + texture_size_, + texture_size_), sdl_deleter()); - Image alias(width, height); - for (size_t i = 0; i < tiles.size(); ++i) { - Image tile = tiles.at(i).get_image(); - for (int y = 0; y < tile_height; ++y) { - for (int x = 0; x < tile_width; ++x) { - alias.at(x + tile_width * i, y) = tile.at(x, y); - } - } + if (!texture_) { + throw std::runtime_error( + std::string("SDL_CreateTexture failed: ") + SDL_GetError()); } - SDL_UpdateTexture(texture_.get(), nullptr, alias.data(), - sizeof(alias.at(0,0)) * alias.width()); } + /** + * React to events which my invalidate the texture. + */ static int on_sdl_event(void* userdata, SDL_Event* event) { - auto this_ = static_cast(userdata); + auto this_ = static_cast(userdata); switch (event->type) { case SDL_RENDER_DEVICE_RESET: // Lost all textures. - this_->sync_alias(); + this_->clear_alias(); break; } return 0; } + /** + * Return the tile width of the assigned tileset. + */ + int tile_width() const noexcept { return tileset_->get_tile_width(); } + /** + * Return the tile height of the assigned tileset. + */ + int tile_height() const noexcept { return tileset_->get_tile_height(); } + /** + * Return the maximum columns supported by the current texture alias. + */ + int columns() const noexcept { return texture_size_ / tile_width(); } + /** + * Return the maximum rows supported by the current texture alias. + */ + int rows() const noexcept { return texture_size_ / tile_height(); } + /** + * Return the total number of tiles supported by the current texture alias. + */ + int capacity() const noexcept { return columns() * rows(); } + /** + * The assigned SDL2 renderer. + */ + struct SDL_Renderer* renderer_; + /** + * The texture alias. + */ + std::unique_ptr texture_ = nullptr; + /** + * The current texture width and height. The starting value is defined here. + */ + int texture_size_ = 256; + /** + * The next index on the alias. Check `capacity` before using. + */ + int next_alias_index_ = 0; + /** + * Mapping of `Unicode -> texture_index`. + */ + std::vector local_map_; +}; + +class SDL2AliasPool +: public SharedObjectPool< + SDL2TilesetAlias::impl, + std::tuple, + std::tuple, struct SDL_Renderer*>> { }; +static SDL2AliasPool sdl2_alias_pool; SDL2TilesetAlias::SDL2TilesetAlias(struct SDL_Renderer* renderer, - std::shared_ptr tileset) + const std::shared_ptr& tileset) +: impl_(sdl2_alias_pool.get_instance({tileset.get(), renderer}, + {tileset, renderer})) +{} +const std::shared_ptr SDL2TilesetAlias::get_tileset() const { - static std::mutex mutex; - std::unique_lock lock(mutex); - SDL2InternalTilesetAlias_::key_type key = - std::make_tuple(tileset.get(), renderer); - alias_ = sdl2_alias_pool[key].lock(); - if (!alias_) { - sdl2_alias_pool[key] = alias_ = - std::make_shared(renderer, tileset); - } + return impl_->get_tileset(); } - -std::shared_ptr& SDL2TilesetAlias::get_tileset() +auto SDL2TilesetAlias::prepare_alias(const TCOD_Console& console) +-> SDL_Texture* { - return alias_->get_tileset(); + return impl_->prepare_alias(console); } - -SDL_Texture* SDL2TilesetAlias::get_texture_alias() +auto SDL2TilesetAlias::get_char_rect(int codepoint) const -> SDL_Rect { - return alias_->texture_.get(); -} -SDL_Rect SDL2TilesetAlias::get_char_rect(int codepoint) { - auto& charmap = alias_->get_tileset()->get_character_map(); - int tile_index = 0; - if (static_cast(codepoint) < charmap.size()) { - tile_index = charmap.at(codepoint); - } - return SDL_Rect{ - alias_->get_tileset()->get_tile_width() * tile_index, - 0, - alias_->get_tileset()->get_tile_width(), - alias_->get_tileset()->get_tile_height(), - }; + return impl_->get_char_rect(codepoint); } - } // namespace sdl2 } // namespace tcod diff --git a/tcod_sys/libtcod/src/libtcod/sdl2/sdl2_alias.h b/tcod_sys/libtcod/src/libtcod/sdl2/sdl2_alias.h index acfc9c6e1..cfd649940 100644 --- a/tcod_sys/libtcod/src/libtcod/sdl2/sdl2_alias.h +++ b/tcod_sys/libtcod/src/libtcod/sdl2/sdl2_alias.h @@ -1,8 +1,39 @@ - +/* BSD 3-Clause License + * + * Copyright © 2008-2019, Jice and the libtcod contributors. + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions are met: + * + * 1. Redistributions of source code must retain the above copyright notice, + * this list of conditions and the following disclaimer. + * + * 2. Redistributions in binary form must reproduce the above copyright notice, + * this list of conditions and the following disclaimer in the documentation + * and/or other materials provided with the distribution. + * + * 3. Neither the name of the copyright holder nor the names of its + * contributors may be used to endorse or promote products derived from + * this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE + * POSSIBILITY OF SUCH DAMAGE. + */ #ifndef LIBTCOD_SDL2_SDL2_ALIAS_H_ #define LIBTCOD_SDL2_SDL2_ALIAS_H_ #include +#include "../console.h" #include "../tileset/observer.h" #ifdef __cplusplus struct SDL_Renderer; @@ -15,19 +46,31 @@ using tileset::Tile; using tileset::Tileset; using tileset::TilesetObserver; class SDL2InternalTilesetAlias_; - +/** + * A texture alias manager for SDL2 renderers. + */ class SDL2TilesetAlias { public: SDL2TilesetAlias() = default; SDL2TilesetAlias(struct SDL_Renderer* renderer, - std::shared_ptr tileset); - - std::shared_ptr& get_tileset(); + const std::shared_ptr& tileset); - SDL_Texture* get_texture_alias(); - SDL_Rect get_char_rect(int codepoint); + const std::shared_ptr get_tileset() const; + /** + * Return a texture alias containing all the glyphs required by `console`. + * + * The returned pointer is owned by this object, and will expire on the next + * call to `prepare_alias`; + */ + auto prepare_alias(const TCOD_Console& console) -> struct SDL_Texture*; + /** + * Return the rectangle where a codepoint exists on the texture alias. + */ + auto get_char_rect(int codepoint) const -> SDL_Rect; private: - std::shared_ptr alias_; + friend class SDL2AliasPool; + class impl; + std::shared_ptr impl_; }; } // namespace sdl2 } // namespace tcod diff --git a/tcod_sys/libtcod/src/libtcod/sdl2/sdl2_display.cpp b/tcod_sys/libtcod/src/libtcod/sdl2/sdl2_display.cpp index cfbc19f71..dbebf22e3 100644 --- a/tcod_sys/libtcod/src/libtcod/sdl2/sdl2_display.cpp +++ b/tcod_sys/libtcod/src/libtcod/sdl2/sdl2_display.cpp @@ -1,4 +1,34 @@ - +/* BSD 3-Clause License + * + * Copyright © 2008-2019, Jice and the libtcod contributors. + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions are met: + * + * 1. Redistributions of source code must retain the above copyright notice, + * this list of conditions and the following disclaimer. + * + * 2. Redistributions in binary form must reproduce the above copyright notice, + * this list of conditions and the following disclaimer in the documentation + * and/or other materials provided with the distribution. + * + * 3. Neither the name of the copyright holder nor the names of its + * contributors may be used to endorse or promote products derived from + * this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE + * POSSIBILITY OF SUCH DAMAGE. + */ #include "sdl2_display.h" #include @@ -11,25 +41,45 @@ namespace tcod { namespace sdl2 { -WindowedDisplay::WindowedDisplay(std::pair window_size, - int window_flags, const std::string& title) +/** + * Initialize a return a new SDL2 window. + * + * If the SDL_WINDOW_OPENGL flag is set then it will create an OpenGL 2.0 + * context. + */ +static auto init_sdl2_window( + const std::array& window_size, + int window_flags, + const std::string& title) +-> std::shared_ptr { - int width = window_size.first; - int height = window_size.second; + int width = window_size.at(0); + int height = window_size.at(1); if (width < 0 || height < 0) { throw std::invalid_argument("width and height must be non-negative."); } if (SDL_Init(SDL_INIT_VIDEO | SDL_INIT_EVENTS | SDL_INIT_TIMER)) { throw std::runtime_error(SDL_GetError()); } - window_ = std::shared_ptr( + SDL_GL_SetAttribute(SDL_GL_CONTEXT_PROFILE_MASK, SDL_GL_CONTEXT_PROFILE_CORE); + SDL_GL_SetAttribute(SDL_GL_CONTEXT_MAJOR_VERSION, 2); + SDL_GL_SetAttribute(SDL_GL_CONTEXT_MINOR_VERSION, 0); + auto window = std::shared_ptr( SDL_CreateWindow( title.c_str(), SDL_WINDOWPOS_UNDEFINED, SDL_WINDOWPOS_UNDEFINED, width, height, window_flags), - [](SDL_Window* window){ SDL_DestroyWindow(window); }); - if (!window_) { throw std::runtime_error(SDL_GetError()); } + [](SDL_Window* window_ptr){ SDL_DestroyWindow(window_ptr); }); + if (!window) { throw std::runtime_error(SDL_GetError()); } + return window; } -void WindowedDisplay::set_title(const std::string title) +WindowedDisplay::WindowedDisplay(std::shared_ptr window) +: window_(window) +{} +WindowedDisplay::WindowedDisplay(const std::array& window_size, + int window_flags, const std::string& title) +: WindowedDisplay(init_sdl2_window(window_size, window_flags, title)) +{} +void WindowedDisplay::set_title(const std::string& title) { if (!window_) { throw std::logic_error("Unresolved class invariant."); } SDL_SetWindowTitle(window_.get(), title.c_str()); @@ -39,15 +89,43 @@ std::string WindowedDisplay::get_title() if (!window_) { throw std::logic_error("Unresolved class invariant."); } return std::string(SDL_GetWindowTitle(window_.get())); } +void WindowedDisplay::set_fullscreen(bool fullscreen) +{ + if (fullscreen) { + SDL_SetWindowFullscreen(window_.get(), SDL_WINDOW_FULLSCREEN_DESKTOP); + } else { + SDL_SetWindowFullscreen(window_.get(), 0); + } +} +int WindowedDisplay::get_fullscreen() +{ + return ((SDL_GetWindowFlags(window_.get()) + & (SDL_WINDOW_FULLSCREEN | SDL_WINDOW_FULLSCREEN_DESKTOP)) != 0); +} +void WindowedDisplay::update_pixel_to_tile_scale(const TCOD_Console* console) +{ + int width, height; + SDL_GetWindowSize(window_.get(), &width, &height); + pixel_to_tile_scale = { + static_cast(TCOD_console_get_width(console)) + / static_cast(width), + static_cast(TCOD_console_get_height(console)) + / static_cast(height), + }; +} -SDL2Display::SDL2Display(std::shared_ptr tileset, - std::pair window_size, int window_flags, - const std::string& title) +SDL2Display::SDL2Display( + std::shared_ptr tileset, + const std::array& window_size, + int window_flags, + const std::string& title, + int renderer_flags) : WindowedDisplay(window_size, window_flags, title) { // Configure SDL2 renderer. + renderer_flags |= SDL_RENDERER_TARGETTEXTURE; renderer_ = std::shared_ptr( - SDL_CreateRenderer(get_window(), -1, SDL_RENDERER_TARGETTEXTURE), + SDL_CreateRenderer(get_sdl_window(), -1, renderer_flags), [](SDL_Renderer* renderer){ SDL_DestroyRenderer(renderer); }); if (!renderer_) { throw std::runtime_error(SDL_GetError()); } // Configure libtcod renderer. @@ -61,13 +139,26 @@ void SDL2Display::set_tileset(std::shared_ptr tileset) } tcod_renderer_ = SDL2Renderer(renderer_.get(), tileset); } -void SDL2Display::present(const TCOD_Console* console) +void SDL2Display::accumulate(const TCOD_Console* console) +{ + accumulate(console, nullptr); +} +void SDL2Display::accumulate(const TCOD_Console* console, const struct SDL_Rect* viewport) { if (!renderer_) { throw std::logic_error("Unresolved class invariant."); } SDL_Texture* backbuffer = tcod_renderer_.render(console); - SDL_RenderClear(renderer_.get()); - SDL_RenderCopy(renderer_.get(), backbuffer, nullptr, nullptr); + SDL_RenderCopy(renderer_.get(), backbuffer, nullptr, viewport); + update_pixel_to_tile_scale(console); +} +void SDL2Display::present(const TCOD_Console* console) +{ + if (!renderer_) { throw std::logic_error("Unresolved class invariant."); } + accumulate(console); SDL_RenderPresent(renderer_.get()); } +auto SDL2Display::read_pixels() const -> Image +{ + return tcod_renderer_.read_pixels(); +} } // namespace sdl2 } // namespace tcod diff --git a/tcod_sys/libtcod/src/libtcod/sdl2/sdl2_display.h b/tcod_sys/libtcod/src/libtcod/sdl2/sdl2_display.h index a50c4740d..12a7e255a 100644 --- a/tcod_sys/libtcod/src/libtcod/sdl2/sdl2_display.h +++ b/tcod_sys/libtcod/src/libtcod/sdl2/sdl2_display.h @@ -1,11 +1,41 @@ - +/* BSD 3-Clause License + * + * Copyright © 2008-2019, Jice and the libtcod contributors. + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions are met: + * + * 1. Redistributions of source code must retain the above copyright notice, + * this list of conditions and the following disclaimer. + * + * 2. Redistributions in binary form must reproduce the above copyright notice, + * this list of conditions and the following disclaimer in the documentation + * and/or other materials provided with the distribution. + * + * 3. Neither the name of the copyright holder nor the names of its + * contributors may be used to endorse or promote products derived from + * this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE + * POSSIBILITY OF SUCH DAMAGE. + */ #ifndef LIBTCOD_SDL2_SDL2_DISPLAY_H_ #define LIBTCOD_SDL2_SDL2_DISPLAY_H_ #ifdef __cplusplus +#include #include #include -#include #endif // __cplusplus #include "sdl2_renderer.h" @@ -16,18 +46,49 @@ struct SDL_Renderer; #ifdef __cplusplus namespace tcod { namespace sdl2 { +using tcod::image::Image; /** * Incomplete interface for subclasses expecting an SDL2 window. */ class WindowedDisplay: public engine::Display { public: - WindowedDisplay(std::pair window_size, int window_flags, + explicit WindowedDisplay(std::shared_ptr window); + WindowedDisplay(const std::array& window_size, int window_flags, const std::string& title); - virtual void set_title(const std::string title) override; + virtual void set_title(const std::string& title) override; virtual std::string get_title() override; - SDL_Window* get_window() { return window_.get(); } + virtual void set_fullscreen(bool fullscreen) override; + virtual int get_fullscreen() override; + /** + * Return the tile coordinate of the last console given to present. + */ + virtual auto pixel_to_tile(const std::array& xy) + -> std::array override + { + return { + std::get<0>(xy) * std::get<0>(pixel_to_tile_scale), + std::get<1>(xy) * std::get<1>(pixel_to_tile_scale), + }; + } + virtual auto get_sdl_window() -> struct SDL_Window* override + { + return window_.get(); + } + virtual auto get_sdl_renderer() -> struct SDL_Renderer* override + { + return nullptr; + } + protected: + /** + * Update the scale using a console/tileset and the current window size. + */ + void update_pixel_to_tile_scale(const TCOD_Console* console); private: std::shared_ptr window_; + /** + * Scale used to convert from pixel coordinate to tile coordinate. + */ + std::array pixel_to_tile_scale = {1.0, 1.0}; }; /** * Display interface using a basic SDL2 renderer. @@ -36,11 +97,19 @@ class SDL2Display: public WindowedDisplay { public: SDL2Display( std::shared_ptr tileset, - std::pair window_size, + const std::array& window_size, int window_flags, - const std::string& title); + const std::string& title, + int renderer_flags); virtual void set_tileset(std::shared_ptr tileset) override; + virtual void accumulate(const TCOD_Console*) override; + virtual void accumulate(const TCOD_Console*, const struct SDL_Rect*) override; virtual void present(const TCOD_Console*) override; + virtual auto read_pixels() const -> Image override; + virtual auto get_sdl_renderer() -> struct SDL_Renderer* override + { + return renderer_.get(); + } private: std::shared_ptr renderer_; SDL2Renderer tcod_renderer_; diff --git a/tcod_sys/libtcod/src/libtcod/sdl2/sdl2_renderer.cpp b/tcod_sys/libtcod/src/libtcod/sdl2/sdl2_renderer.cpp index 16d1e2743..ba5c06d56 100644 --- a/tcod_sys/libtcod/src/libtcod/sdl2/sdl2_renderer.cpp +++ b/tcod_sys/libtcod/src/libtcod/sdl2/sdl2_renderer.cpp @@ -1,80 +1,200 @@ - +/* BSD 3-Clause License + * + * Copyright © 2008-2019, Jice and the libtcod contributors. + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions are met: + * + * 1. Redistributions of source code must retain the above copyright notice, + * this list of conditions and the following disclaimer. + * + * 2. Redistributions in binary form must reproduce the above copyright notice, + * this list of conditions and the following disclaimer in the documentation + * and/or other materials provided with the distribution. + * + * 3. Neither the name of the copyright holder nor the names of its + * contributors may be used to endorse or promote products derived from + * this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE + * POSSIBILITY OF SUCH DAMAGE. + */ #include "sdl2_renderer.h" #include +#include "../utility/matrix.h" + #include namespace tcod { namespace sdl2 { using tileset::Tileset; -SDL2Renderer::~SDL2Renderer() -{ - if (texture_ && !SDL_WasInit(SDL_INIT_VIDEO)) { - SDL_DestroyTexture(texture_); +class SDL2Renderer::impl: public TilesetObserver { + public: + impl(struct SDL_Renderer* renderer, SDL2TilesetAlias alias) + : TilesetObserver(alias.get_tileset()), alias_{alias}, renderer_{renderer} + { + SDL_AddEventWatch(on_sdl_event, this); } -} - -struct SDL_Texture* SDL2Renderer::render(const TCOD_Console* console) -{ - if (!console) { throw; } - if (console->w != cache_.width() || console->h != cache_.height()) { - if (texture_) { + ~impl() + { + if (texture_ && !SDL_WasInit(SDL_INIT_VIDEO)) { SDL_DestroyTexture(texture_); - texture_ = nullptr; } + SDL_DelEventWatch(on_sdl_event, this); } - if (!texture_) { - cache_ = cache_type(console->w, console->h); - const uint32_t format = 0; - texture_ = SDL_CreateTexture(renderer_, format, SDL_TEXTUREACCESS_TARGET, - tileset_->get_tile_width() * console->w, - tileset_->get_tile_height() * console->h); - if(!texture_) { throw std::runtime_error(SDL_GetError()); } + /** + * Selectively reset the cache so that only changed tiles are redrawn. + */ + void on_tileset_changed( + const std::vector> &changes) override + { + for (const auto& changed : changes) { + int codepoint = changed.second.codepoint; + for (auto& it : cache_) { + if (it.ch == codepoint) { + it.ch = -1; + } + } + } } - SDL_SetRenderTarget(renderer_, texture_); - SDL_Texture* alias_texture = alias_.get_texture_alias(); - SDL_SetRenderDrawBlendMode(renderer_, SDL_BLENDMODE_NONE); - SDL_SetTextureBlendMode(alias_texture, SDL_BLENDMODE_BLEND); - SDL_SetTextureAlphaMod(alias_texture, 0xff); - for (int y = 0; y < console->h; ++y) { - for (int x = 0; x < console->w; ++x) { - const int i = console->w * y + x; // console index - const int ch = console->ch_array[i]; - const TCOD_color_t fg = console->fg_array[i]; - const TCOD_color_t bg = console->bg_array[i]; - int& cache_ch = std::get<0>(cache_.at(x, y)); - ColorRGBA& cache_fg = std::get<1>(cache_.at(x, y)); - ColorRGBA& cache_bg = std::get<2>(cache_.at(x, y)); - if (cache_ch == ch && - cache_fg.r == fg.r && cache_fg.g == fg.g && cache_fg.b == fg.b && - cache_bg.r == bg.r && cache_bg.g == bg.g && cache_bg.b == bg.b) { - continue; // This tile was already rendered on a previous frame. + auto render(const TCOD_Console& console) -> struct SDL_Texture* + { + if (cache_.get_shape() + != cache_type::shape_type{{console.h, console.w}}) { + if (texture_) { + SDL_DestroyTexture(texture_); + texture_ = nullptr; } - cache_ch = ch; - cache_fg.r = fg.r; - cache_fg.b = fg.b; - cache_fg.g = fg.g; - cache_bg.r = bg.r; - cache_bg.b = bg.b; - cache_bg.g = bg.g; - const SDL_Rect dest_rect{ - x * tileset_->get_tile_width(), - y * tileset_->get_tile_height(), - tileset_->get_tile_width(), - tileset_->get_tile_height(), - }; - SDL_SetRenderDrawColor(renderer_, bg.r, bg.g, bg.b, 0xff); - SDL_RenderFillRect(renderer_, &dest_rect); - if (fg.r != bg.r || fg.g != bg.g || fg.b != bg.b) { - SDL_SetTextureColorMod(alias_texture, fg.r, fg.g, fg.b); - const SDL_Rect alias_rect = alias_.get_char_rect(ch); - SDL_RenderCopy(renderer_, alias_texture, - &alias_rect, &dest_rect); + } + if (!texture_) { + cache_ = cache_type({console.h, console.w}); + const uint32_t format = 0; + texture_ = SDL_CreateTexture( + renderer_, format, SDL_TEXTUREACCESS_TARGET, + tileset_->get_tile_width() * console.w, + tileset_->get_tile_height() * console.h); + SDL_SetTextureBlendMode(texture_, SDL_BLENDMODE_BLEND); + if(!texture_) { throw std::runtime_error(SDL_GetError()); } + } + SDL_SetRenderTarget(renderer_, texture_); + SDL_Texture* alias_texture = alias_.prepare_alias(console); + SDL_SetRenderDrawBlendMode(renderer_, SDL_BLENDMODE_NONE); + SDL_SetTextureBlendMode(alias_texture, SDL_BLENDMODE_BLEND); + SDL_SetTextureAlphaMod(alias_texture, 0xff); + for (int y = 0; y < console.h; ++y) { + for (int x = 0; x < console.w; ++x) { + auto tile = console.at(y, x); + if (tile.ch == 0x20 || tile.fg.a == 0) { + // Tile is the space character or has no alpha. + tile.ch = 0; // Skip drawing this glyph. + } + if (tcod::ColorRGB(tile.fg) == tcod::ColorRGB(tile.bg) + && tile.bg.a == 0xff) { + // Foreground color is the same as the background. + tile.ch = 0; // Skip drawing this glyph. + } + if (tile.ch == 0) { + // There is no foreground glyph, so ignore the color. + tile.fg = {0, 0, 0, 0}; + } + auto& cache = cache_.at({y, x}); + if (tile == cache) { + continue; // This tile was already rendered from the last frame. + } + cache = tile; + const SDL_Rect dest_rect{ + x * tileset_->get_tile_width(), + y * tileset_->get_tile_height(), + tileset_->get_tile_width(), + tileset_->get_tile_height(), + }; + // Fill the background of the tile with a solid color. + SDL_SetRenderDrawColor( + renderer_, tile.bg.r, tile.bg.g, tile.bg.b, tile.bg.a); + SDL_RenderFillRect(renderer_, &dest_rect); + if (tile.ch == 0) { + continue; // No foreground glyph. + } + // Blend the foreground glyph on top of the background. + SDL_SetTextureColorMod(alias_texture, tile.fg.r, tile.fg.g, tile.fg.b); + SDL_SetTextureAlphaMod(alias_texture, tile.fg.a); + const SDL_Rect alias_rect = alias_.get_char_rect(tile.ch); + SDL_RenderCopy(renderer_, alias_texture, &alias_rect, &dest_rect); } } + SDL_SetRenderTarget(renderer_, nullptr); + return texture_; } - SDL_SetRenderTarget(renderer_, nullptr); - return texture_; + auto read_pixels() const -> Image + { + SDL_SetRenderTarget(renderer_, texture_); + int width, height; + SDL_QueryTexture(texture_, nullptr, nullptr, &width, &height); + Image pixels(width, height); + SDL_RenderReadPixels( + renderer_, + nullptr, + SDL_PIXELFORMAT_RGBA32, + static_cast(pixels.data()), + width * 4); + SDL_SetRenderTarget(renderer_, nullptr); + return pixels; + } + private: + using cache_type = Matrix; + static int on_sdl_event(void* userdata, SDL_Event* event) + { + auto this_ = static_cast(userdata); + switch (event->type) { + case SDL_RENDER_TARGETS_RESET: // Lost target textures. + // Reset cache so that cells are updated. + for (auto& cell : this_->cache_) { + cell = {-1, {0, 0, 0, 0}, {0, 0, 0, 0}}; + } + break; + } + return 0; + } + SDL2TilesetAlias alias_; + cache_type cache_; + struct SDL_Renderer* renderer_; + struct SDL_Texture* texture_ = nullptr; +}; + +SDL2Renderer::SDL2Renderer() +{} +SDL2Renderer::SDL2Renderer(struct SDL_Renderer* renderer, SDL2TilesetAlias alias) +: impl_(std::make_unique(renderer, alias)) +{} + +SDL2Renderer::SDL2Renderer(struct SDL_Renderer* renderer, + std::shared_ptr tileset) +: impl_(std::make_unique(renderer, SDL2TilesetAlias(renderer, tileset))) +{} + +SDL2Renderer::SDL2Renderer(SDL2Renderer&&) noexcept = default; +SDL2Renderer& SDL2Renderer::operator=(SDL2Renderer&&) noexcept = default; +SDL2Renderer::~SDL2Renderer() = default; + +struct SDL_Texture* SDL2Renderer::render(const TCOD_Console* console) +{ + if (!console) { throw; } + return impl_->render(*console); +} +auto SDL2Renderer::read_pixels() const -> Image +{ + return impl_->read_pixels(); } } // namespace sdl2 } // namespace tcod diff --git a/tcod_sys/libtcod/src/libtcod/sdl2/sdl2_renderer.h b/tcod_sys/libtcod/src/libtcod/sdl2/sdl2_renderer.h index cf82bbed0..5e65983bb 100644 --- a/tcod_sys/libtcod/src/libtcod/sdl2/sdl2_renderer.h +++ b/tcod_sys/libtcod/src/libtcod/sdl2/sdl2_renderer.h @@ -1,4 +1,34 @@ - +/* BSD 3-Clause License + * + * Copyright © 2008-2019, Jice and the libtcod contributors. + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions are met: + * + * 1. Redistributions of source code must retain the above copyright notice, + * this list of conditions and the following disclaimer. + * + * 2. Redistributions in binary form must reproduce the above copyright notice, + * this list of conditions and the following disclaimer in the documentation + * and/or other materials provided with the distribution. + * + * 3. Neither the name of the copyright holder nor the names of its + * contributors may be used to endorse or promote products derived from + * this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE + * POSSIBILITY OF SUCH DAMAGE. + */ #ifndef LIBTCOD_SDL2_SDL2_RENDERER_H_ #define LIBTCOD_SDL2_SDL2_RENDERER_H_ #ifdef __cplusplus @@ -16,29 +46,28 @@ struct SDL_Renderer; struct SDL_Texture; namespace tcod { namespace sdl2 { +using tcod::image::Image; using tcod::tileset::Tileset; -class SDL2Renderer: public TilesetObserver { +class SDL2Renderer { public: - SDL2Renderer() - {} - SDL2Renderer(struct SDL_Renderer* renderer, SDL2TilesetAlias alias) - : TilesetObserver(alias.get_tileset()), alias_{alias}, renderer_{renderer} - {} - + SDL2Renderer(); + SDL2Renderer(struct SDL_Renderer* renderer, SDL2TilesetAlias alias); SDL2Renderer(struct SDL_Renderer* renderer, - std::shared_ptr tileset) - : SDL2Renderer(renderer, SDL2TilesetAlias(renderer, tileset)) - {} + std::shared_ptr tileset); + + SDL2Renderer(const SDL2Renderer&) = delete; + SDL2Renderer& operator=(const SDL2Renderer&) = delete; + SDL2Renderer(SDL2Renderer&&) noexcept; + SDL2Renderer& operator=(SDL2Renderer&&) noexcept; ~SDL2Renderer(); - struct SDL_Texture* render(const TCOD_Console* console); + auto render(const TCOD_Console* console) -> struct SDL_Texture*; + auto read_pixels() const -> Image; + private: - using cache_type = Vector2>; - SDL2TilesetAlias alias_; - cache_type cache_; - struct SDL_Renderer* renderer_; - struct SDL_Texture* texture_ = nullptr; + class impl; + std::unique_ptr impl_; }; } // namespace sdl2 } // namespace tcod diff --git a/tcod_sys/libtcod/src/libtcod/sys.cpp b/tcod_sys/libtcod/src/libtcod/sys.cpp index d231ce19e..6354ac5b2 100644 --- a/tcod_sys/libtcod/src/libtcod/sys.cpp +++ b/tcod_sys/libtcod/src/libtcod/sys.cpp @@ -1,30 +1,34 @@ -/* -* libtcod -* Copyright (c) 2008-2018 Jice & Mingos & rmtew -* All rights reserved. -* -* Redistribution and use in source and binary forms, with or without -* modification, are permitted provided that the following conditions are met: -* * Redistributions of source code must retain the above copyright -* notice, this list of conditions and the following disclaimer. -* * Redistributions in binary form must reproduce the above copyright -* notice, this list of conditions and the following disclaimer in the -* documentation and/or other materials provided with the distribution. -* * The name of Jice or Mingos may not be used to endorse or promote -* products derived from this software without specific prior written -* permission. -* -* THIS SOFTWARE IS PROVIDED BY JICE, MINGOS AND RMTEW ``AS IS'' AND ANY -* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED -* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE -* DISCLAIMED. IN NO EVENT SHALL JICE, MINGOS OR RMTEW BE LIABLE FOR ANY -* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES -* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; -* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND -* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS -* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. -*/ +/* BSD 3-Clause License + * + * Copyright © 2008-2019, Jice and the libtcod contributors. + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions are met: + * + * 1. Redistributions of source code must retain the above copyright notice, + * this list of conditions and the following disclaimer. + * + * 2. Redistributions in binary form must reproduce the above copyright notice, + * this list of conditions and the following disclaimer in the documentation + * and/or other materials provided with the distribution. + * + * 3. Neither the name of the copyright holder nor the names of its + * contributors may be used to endorse or promote products derived from + * this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE + * POSSIBILITY OF SUCH DAMAGE. + */ #include "sys.hpp" #include @@ -153,7 +157,7 @@ bool TCODSystem::setClipboard(const char *value) { } char *TCODSystem::getClipboard() { - return TCOD_sys_clipboard_get(); + return TCOD_sys_clipboard_get(); } #endif @@ -231,8 +235,8 @@ void TCODSystem::deleteCondition( TCOD_cond_t cond) { // custom post-renderer static ITCODSDLRenderer *post_renderer=NULL; -extern "C" void TCOD_CRenderer(void *sdl_surface) { - if ( post_renderer ) post_renderer->render(sdl_surface); +extern "C" void TCOD_CRenderer(struct SDL_Surface* sdl_surface) { + if (post_renderer) { post_renderer->render(sdl_surface); } } void TCODSystem::registerSDLRenderer(ITCODSDLRenderer *renderer) { ::post_renderer = renderer; diff --git a/tcod_sys/libtcod/src/libtcod/sys.h b/tcod_sys/libtcod/src/libtcod/sys.h index 17073d07e..ea9d5cf8f 100644 --- a/tcod_sys/libtcod/src/libtcod/sys.h +++ b/tcod_sys/libtcod/src/libtcod/sys.h @@ -1,30 +1,34 @@ -/* -* libtcod -* Copyright (c) 2008-2018 Jice & Mingos & rmtew -* All rights reserved. -* -* Redistribution and use in source and binary forms, with or without -* modification, are permitted provided that the following conditions are met: -* * Redistributions of source code must retain the above copyright -* notice, this list of conditions and the following disclaimer. -* * Redistributions in binary form must reproduce the above copyright -* notice, this list of conditions and the following disclaimer in the -* documentation and/or other materials provided with the distribution. -* * The name of Jice or Mingos may not be used to endorse or promote -* products derived from this software without specific prior written -* permission. -* -* THIS SOFTWARE IS PROVIDED BY JICE, MINGOS AND RMTEW ``AS IS'' AND ANY -* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED -* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE -* DISCLAIMED. IN NO EVENT SHALL JICE, MINGOS OR RMTEW BE LIABLE FOR ANY -* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES -* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; -* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND -* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS -* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. -*/ +/* BSD 3-Clause License + * + * Copyright © 2008-2019, Jice and the libtcod contributors. + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions are met: + * + * 1. Redistributions of source code must retain the above copyright notice, + * this list of conditions and the following disclaimer. + * + * 2. Redistributions in binary form must reproduce the above copyright notice, + * this list of conditions and the following disclaimer in the documentation + * and/or other materials provided with the distribution. + * + * 3. Neither the name of the copyright holder nor the names of its + * contributors may be used to endorse or promote products derived from + * this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE + * POSSIBILITY OF SUCH DAMAGE. + */ #ifndef _TCOD_SYS_H #define _TCOD_SYS_H @@ -63,8 +67,8 @@ TCODLIB_API void TCOD_sys_update_char(int asciiCode, int fontx, int fonty, TCOD_ #endif #ifndef TCOD_BARE -TCODLIB_API void *TCOD_sys_get_SDL_window(void); -TCODLIB_API void *TCOD_sys_get_SDL_renderer(void); +TCODLIB_API struct SDL_Window* TCOD_sys_get_SDL_window(void); +TCODLIB_API struct SDL_Renderer* TCOD_sys_get_SDL_renderer(void); #endif #ifndef TCOD_BARE @@ -168,7 +172,8 @@ TCOD_DEPRECATED_NOMESSAGE TCODLIB_API void TCOD_close_library(TCOD_library_t); /* SDL renderer callback */ #ifndef TCOD_BARE -typedef void (*SDL_renderer_t) (void *sdl_renderer); +typedef void (*SDL_renderer_t) (struct SDL_Surface* sdl_renderer); +TCOD_DEPRECATED_NOMESSAGE TCODLIB_API void TCOD_sys_register_SDL_renderer(SDL_renderer_t renderer); #endif #ifdef __cplusplus diff --git a/tcod_sys/libtcod/src/libtcod/sys.hpp b/tcod_sys/libtcod/src/libtcod/sys.hpp index 0363c585e..119931c88 100644 --- a/tcod_sys/libtcod/src/libtcod/sys.hpp +++ b/tcod_sys/libtcod/src/libtcod/sys.hpp @@ -1,30 +1,34 @@ -/* -* libtcod -* Copyright (c) 2008-2018 Jice & Mingos & rmtew -* All rights reserved. -* -* Redistribution and use in source and binary forms, with or without -* modification, are permitted provided that the following conditions are met: -* * Redistributions of source code must retain the above copyright -* notice, this list of conditions and the following disclaimer. -* * Redistributions in binary form must reproduce the above copyright -* notice, this list of conditions and the following disclaimer in the -* documentation and/or other materials provided with the distribution. -* * The name of Jice or Mingos may not be used to endorse or promote -* products derived from this software without specific prior written -* permission. -* -* THIS SOFTWARE IS PROVIDED BY JICE, MINGOS AND RMTEW ``AS IS'' AND ANY -* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED -* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE -* DISCLAIMED. IN NO EVENT SHALL JICE, MINGOS OR RMTEW BE LIABLE FOR ANY -* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES -* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; -* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND -* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS -* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. -*/ +/* BSD 3-Clause License + * + * Copyright © 2008-2019, Jice and the libtcod contributors. + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions are met: + * + * 1. Redistributions of source code must retain the above copyright notice, + * this list of conditions and the following disclaimer. + * + * 2. Redistributions in binary form must reproduce the above copyright notice, + * this list of conditions and the following disclaimer in the documentation + * and/or other materials provided with the distribution. + * + * 3. Neither the name of the copyright holder nor the names of its + * contributors may be used to endorse or promote products derived from + * this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE + * POSSIBILITY OF SUCH DAMAGE. + */ #ifndef _TCOD_SYS_HPP #define _TCOD_SYS_HPP @@ -250,6 +254,7 @@ public : @C bool TCOD_sys_create_directory(const char *path) @Param path Directory path. The immediate father directory (/..) must exist and be writable. */ + TCOD_DEPRECATED_NOMESSAGE static bool createDirectory(const char *path); /** @@ -259,6 +264,7 @@ public : @C bool TCOD_sys_delete_directory(const char *path) @Param path directory path. This directory must exist, be writable and empty */ + TCOD_DEPRECATED_NOMESSAGE static bool deleteDirectory(const char *path); /** @@ -268,6 +274,7 @@ public : @C bool TCOD_sys_delete_file(const char *path) @Param path File path. This file must exist and be writable. */ + TCOD_DEPRECATED_NOMESSAGE static bool deleteFile(const char *path); /** @@ -277,6 +284,7 @@ public : @C bool TCOD_sys_is_directory(const char *path) @Param path a path to check */ + TCOD_DEPRECATED_NOMESSAGE static bool isDirectory(const char *path); /** @@ -289,6 +297,7 @@ public : @Param path a directory @Param pattern If NULL or empty, returns all directory entries. Else returns only entries matching the pattern. The pattern is NOT a regular expression. It can only handle one '*' wildcard. Examples : *.png, saveGame*, font*.png */ + TCOD_DEPRECATED_NOMESSAGE static TCOD_list_t getDirectoryContent(const char *path, const char *pattern); /** @@ -308,6 +317,7 @@ public : fprintf(stderr,"no such file!"); } */ + TCOD_DEPRECATED_NOMESSAGE static bool fileExists(const char * filename, ...); /** @PageName system_filesystem @@ -332,6 +342,7 @@ public : free(buf); } */ + TCOD_DEPRECATED_NOMESSAGE static bool readFile(const char *filename, unsigned char **buf, size_t *size); /** @PageName system_filesystem @@ -347,6 +358,7 @@ public : @CEx TCOD_sys_write_file("myfile.dat",buf,size)); */ + TCOD_DEPRECATED_NOMESSAGE static bool writeFile(const char *filename, unsigned char *buf, uint32_t size); /** @PageName system_sdlcbk @@ -390,6 +402,7 @@ public : ... draw something on sdl_surface using pygame libtcod.sys_register_SDL_renderer(my_renderer) */ + TCOD_DEPRECATED_NOMESSAGE static void registerSDLRenderer(ITCODSDLRenderer *renderer); /** @@ -522,6 +535,7 @@ public : @Py sys_clipboard_set(value) @Param value UTF-8 text to copy into the clipboard */ + TCOD_DEPRECATED_NOMESSAGE static bool setClipboard(const char *value); /** @@ -532,29 +546,47 @@ public : @C char *TCOD_sys_clipboard_get() @Py sys_clipboard_get() # Returns UTF-8 string */ + TCOD_DEPRECATED_NOMESSAGE static char *getClipboard(); #endif // thread stuff + TCOD_DEPRECATED_NOMESSAGE static int getNumCores(); + TCOD_DEPRECATED_NOMESSAGE static TCOD_thread_t newThread(int (*func)(void *), void *data); + TCOD_DEPRECATED_NOMESSAGE static void deleteThread(TCOD_thread_t th); + TCOD_DEPRECATED_NOMESSAGE static void waitThread(TCOD_thread_t th); // mutex + TCOD_DEPRECATED_NOMESSAGE static TCOD_mutex_t newMutex(); + TCOD_DEPRECATED_NOMESSAGE static void mutexIn(TCOD_mutex_t mut); + TCOD_DEPRECATED_NOMESSAGE static void mutexOut(TCOD_mutex_t mut); + TCOD_DEPRECATED_NOMESSAGE static void deleteMutex(TCOD_mutex_t mut); // semaphore + TCOD_DEPRECATED_NOMESSAGE static TCOD_semaphore_t newSemaphore(int initVal); + TCOD_DEPRECATED_NOMESSAGE static void lockSemaphore(TCOD_semaphore_t sem); + TCOD_DEPRECATED_NOMESSAGE static void unlockSemaphore(TCOD_semaphore_t sem); + TCOD_DEPRECATED_NOMESSAGE static void deleteSemaphore( TCOD_semaphore_t sem); // condition + TCOD_DEPRECATED_NOMESSAGE static TCOD_cond_t newCondition(); + TCOD_DEPRECATED_NOMESSAGE static void signalCondition(TCOD_cond_t sem); + TCOD_DEPRECATED_NOMESSAGE static void broadcastCondition(TCOD_cond_t sem); + TCOD_DEPRECATED_NOMESSAGE static void waitCondition(TCOD_cond_t sem, TCOD_mutex_t mut); + TCOD_DEPRECATED_NOMESSAGE static void deleteCondition( TCOD_cond_t sem); }; diff --git a/tcod_sys/libtcod/src/libtcod/sys_c.cpp b/tcod_sys/libtcod/src/libtcod/sys_c.cpp index 6dd8733db..dfa76dc67 100644 --- a/tcod_sys/libtcod/src/libtcod/sys_c.cpp +++ b/tcod_sys/libtcod/src/libtcod/sys_c.cpp @@ -1,47 +1,48 @@ -/* -* libtcod -* Copyright (c) 2008-2018 Jice & Mingos & rmtew -* All rights reserved. -* -* Redistribution and use in source and binary forms, with or without -* modification, are permitted provided that the following conditions are met: -* * Redistributions of source code must retain the above copyright -* notice, this list of conditions and the following disclaimer. -* * Redistributions in binary form must reproduce the above copyright -* notice, this list of conditions and the following disclaimer in the -* documentation and/or other materials provided with the distribution. -* * The name of Jice or Mingos may not be used to endorse or promote -* products derived from this software without specific prior written -* permission. -* -* THIS SOFTWARE IS PROVIDED BY JICE, MINGOS AND RMTEW ``AS IS'' AND ANY -* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED -* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE -* DISCLAIMED. IN NO EVENT SHALL JICE, MINGOS OR RMTEW BE LIABLE FOR ANY -* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES -* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; -* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND -* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS -* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. -*/ +/* BSD 3-Clause License + * + * Copyright © 2008-2019, Jice and the libtcod contributors. + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions are met: + * + * 1. Redistributions of source code must retain the above copyright notice, + * this list of conditions and the following disclaimer. + * + * 2. Redistributions in binary form must reproduce the above copyright notice, + * this list of conditions and the following disclaimer in the documentation + * and/or other materials provided with the distribution. + * + * 3. Neither the name of the copyright holder nor the names of its + * contributors may be used to endorse or promote products derived from + * this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE + * POSSIBILITY OF SUCH DAMAGE. + */ #include "sys.h" #include #include #include #include -#include +#include #include +#include -#if defined (__APPLE__) && defined (__MACH__) -/* Is this necessary now the custom clipboard stuff is gone? */ -#include -#endif #include "libtcod_int.h" #include "version.h" #ifdef TCOD_WINDOWS -#define NOMINMAX +#define NOMINMAX 1 #include #else #include @@ -146,7 +147,7 @@ static DWORD CountSetBits(ULONG_PTR bitMask) { DWORD LSHIFT = sizeof(ULONG_PTR)*8 - 1; DWORD bitSetCount = 0; - ULONG_PTR bitTest = (ULONG_PTR)1 << LSHIFT; + ULONG_PTR bitTest = static_cast(1) << LSHIFT; DWORD i; for (i = 0; i <= LSHIFT; ++i) @@ -210,9 +211,9 @@ int TCOD_sys_get_num_cores(void) { DWORD logicalProcessorCount = 0; DWORD byteOffset = 0; - glpi = (LPFN_GLPI) GetProcAddress( - GetModuleHandle(TEXT("kernel32")), - "GetLogicalProcessorInformation"); + glpi = reinterpret_cast( + GetProcAddress(GetModuleHandle(TEXT("kernel32")), + "GetLogicalProcessorInformation")); if (! glpi) { return 1; } @@ -226,8 +227,8 @@ int TCOD_sys_get_num_cores(void) { if (buffer) free(buffer); - buffer = (PSYSTEM_LOGICAL_PROCESSOR_INFORMATION)malloc( - returnLength); + buffer = static_cast( + malloc(returnLength)); if (NULL == buffer) { return 1; @@ -265,32 +266,34 @@ int TCOD_sys_get_num_cores(void) { TCOD_thread_t TCOD_thread_new(int (*func)(void *), void *data) { #ifdef TCOD_WINDOWS - HANDLE ret = CreateThread(NULL,0,(DWORD (WINAPI *)( LPVOID ))func,data,0,NULL); - return (TCOD_thread_t)ret; + HANDLE ret = CreateThread( + NULL, 0, reinterpret_cast(func), data, 0, NULL); + return ret; #else pthread_t id; int iret; pthread_attr_t attr; pthread_attr_init(&attr); pthread_attr_setdetachstate(&attr,PTHREAD_CREATE_DETACHED); - iret =pthread_create(&id,&attr,(void *(*)(void *))func,data); + iret =pthread_create( + &id, &attr, reinterpret_cast(func), data); if ( iret != 0 ) id=0; - return (TCOD_thread_t)id; + return reinterpret_cast(id); #endif } void TCOD_thread_delete(TCOD_thread_t th) { #ifdef TCOD_WINDOWS - CloseHandle((HANDLE)th); + CloseHandle(th); #endif } void TCOD_thread_wait(TCOD_thread_t th) { #ifdef TCOD_WINDOWS - WaitForSingleObject((HANDLE)th,INFINITE); + WaitForSingleObject(th, INFINITE); #else - pthread_t id=(pthread_t)th; + pthread_t id = reinterpret_cast(th); pthread_join(id,NULL); #endif } @@ -298,42 +301,44 @@ void TCOD_thread_wait(TCOD_thread_t th) { TCOD_mutex_t TCOD_mutex_new() { #ifdef TCOD_WINDOWS - CRITICAL_SECTION *cs = (CRITICAL_SECTION *)calloc(sizeof(CRITICAL_SECTION),1); + CRITICAL_SECTION *cs = + static_cast(calloc(sizeof(CRITICAL_SECTION), 1)); InitializeCriticalSection(cs); - return (TCOD_mutex_t)cs; + return static_cast(cs); #else static pthread_mutex_t tmp=PTHREAD_MUTEX_INITIALIZER; - pthread_mutex_t *mut = (pthread_mutex_t *)calloc(sizeof(pthread_mutex_t),1); + pthread_mutex_t *mut = + static_cast(calloc(sizeof(pthread_mutex_t), 1)); *mut = tmp; - return (TCOD_mutex_t)mut; + return static_cast(mut); #endif } void TCOD_mutex_in(TCOD_mutex_t mut) { #ifdef TCOD_WINDOWS - EnterCriticalSection((CRITICAL_SECTION *)mut); + EnterCriticalSection(static_cast(mut)); #else - pthread_mutex_lock((pthread_mutex_t *)mut); + pthread_mutex_lock(static_cast(mut)); #endif } void TCOD_mutex_out(TCOD_mutex_t mut) { #ifdef TCOD_WINDOWS - LeaveCriticalSection((CRITICAL_SECTION *)mut); + LeaveCriticalSection(static_cast(mut)); #else - pthread_mutex_unlock((pthread_mutex_t *)mut); + pthread_mutex_unlock(static_cast(mut)); #endif } void TCOD_mutex_delete(TCOD_mutex_t mut) { #ifdef TCOD_WINDOWS - DeleteCriticalSection((CRITICAL_SECTION *)mut); + DeleteCriticalSection(static_cast(mut)); free(mut); #else - pthread_mutex_destroy((pthread_mutex_t *)mut); + pthread_mutex_destroy(static_cast(mut)); free(mut); #endif } @@ -342,40 +347,40 @@ TCOD_semaphore_t TCOD_semaphore_new(int initVal) { #ifdef TCOD_WINDOWS HANDLE ret = CreateSemaphore(NULL,initVal,255,NULL); - return (TCOD_semaphore_t)ret; + return ret; #else - sem_t *ret = (sem_t *)calloc(sizeof(sem_t),1); - if ( ret ) sem_init(ret,0,initVal); - return (TCOD_semaphore_t) ret; + sem_t *ret = static_cast(calloc(sizeof(sem_t), 1)); + if ( ret ) sem_init(ret, 0, initVal); + return static_cast(ret); #endif } void TCOD_semaphore_lock(TCOD_semaphore_t sem) { #ifdef TCOD_WINDOWS - WaitForSingleObject((HANDLE)sem,INFINITE); + WaitForSingleObject(sem, INFINITE); #else - if ( sem ) sem_wait((sem_t *)sem); + if ( sem ) sem_wait(static_cast(sem)); #endif } void TCOD_semaphore_unlock(TCOD_semaphore_t sem) { #ifdef TCOD_WINDOWS - ReleaseSemaphore((HANDLE)sem,1,NULL); + ReleaseSemaphore(sem, 1, NULL); #else - if ( sem ) sem_post((sem_t *)sem); + if ( sem ) sem_post(static_cast(sem)); #endif } void TCOD_semaphore_delete( TCOD_semaphore_t sem) { #ifdef TCOD_WINDOWS - CloseHandle((HANDLE)sem); + CloseHandle(sem); #else if ( sem ) { - sem_destroy((sem_t *)sem); + sem_destroy(static_cast(sem)); free (sem); } #endif @@ -394,21 +399,22 @@ typedef struct { TCOD_cond_t TCOD_condition_new(void) { #ifdef TCOD_WINDOWS - cond_t *ret = (cond_t *)calloc(sizeof(cond_t),1); + cond_t *ret = static_cast(calloc(sizeof(cond_t), 1)); ret->mutex = TCOD_mutex_new(); ret->waiting = TCOD_semaphore_new(0); ret->waitDone = TCOD_semaphore_new(0); - return (TCOD_cond_t)ret; + return ret; #else - pthread_cond_t *ret = (pthread_cond_t *)calloc(sizeof(pthread_cond_t),1); + pthread_cond_t *ret = + static_cast(calloc(sizeof(pthread_cond_t), 1)); if ( ret ) pthread_cond_init(ret,NULL); - return (TCOD_cond_t) ret; + return static_cast(ret); #endif } void TCOD_condition_signal(TCOD_cond_t pcond) { #ifdef TCOD_WINDOWS - cond_t *cond=(cond_t *)pcond; + cond_t* cond = static_cast(pcond); if ( cond ) { TCOD_mutex_in(cond->mutex); if ( cond->nbWaiting > cond->nbSignals ) { @@ -422,14 +428,14 @@ void TCOD_condition_signal(TCOD_cond_t pcond) { } #else if ( pcond ) { - pthread_cond_signal((pthread_cond_t *)pcond); + pthread_cond_signal(static_cast(pcond)); } #endif } void TCOD_condition_broadcast(TCOD_cond_t pcond) { #ifdef TCOD_WINDOWS - cond_t *cond=(cond_t *)pcond; + cond_t *cond = static_cast(pcond); if ( cond ) { TCOD_mutex_in(cond->mutex); if ( cond->nbWaiting > cond->nbSignals ) { @@ -449,14 +455,14 @@ void TCOD_condition_broadcast(TCOD_cond_t pcond) { } #else if ( pcond ) { - pthread_cond_broadcast((pthread_cond_t *)pcond); + pthread_cond_broadcast(static_cast(pcond)); } #endif } void TCOD_condition_wait(TCOD_cond_t pcond, TCOD_mutex_t mut) { #ifdef TCOD_WINDOWS - cond_t *cond=(cond_t *)pcond; + cond_t *cond = static_cast(pcond); if ( cond ) { TCOD_mutex_in(cond->mutex); cond->nbWaiting++; @@ -473,14 +479,15 @@ void TCOD_condition_wait(TCOD_cond_t pcond, TCOD_mutex_t mut) { } #else if ( pcond && mut ) { - pthread_cond_wait((pthread_cond_t *)pcond, (pthread_mutex_t *)mut); + pthread_cond_wait(static_cast(pcond), + static_cast(mut)); } #endif } void TCOD_condition_delete( TCOD_cond_t pcond) { #ifdef TCOD_WINDOWS - cond_t *cond=(cond_t *)pcond; + cond_t* cond = static_cast(pcond); if ( cond ) { TCOD_mutex_delete(cond->mutex); TCOD_semaphore_delete(cond->waiting); @@ -489,7 +496,7 @@ void TCOD_condition_delete( TCOD_cond_t pcond) { } #else if ( pcond ) { - pthread_cond_destroy((pthread_cond_t *)pcond); + pthread_cond_destroy(static_cast(pcond)); free (pcond); } #endif @@ -517,42 +524,49 @@ bool TCOD_sys_write_file(const char *filename, unsigned char *buf, uint32_t size return false; } #endif /* TCOD_BARE */ - -void TCOD_fatal(const char *fmt, ...) { - va_list ap; - TCOD_sys_shutdown(); - printf("%s\n", TCOD_STRVERSIONNAME); - va_start(ap, fmt); - vprintf(fmt, ap); - va_end(ap); - printf("\n"); - exit(1); -} - -void TCOD_fatal_nopar(const char *msg) { - TCOD_sys_shutdown(); - printf("%s\n%s\n", TCOD_STRVERSIONNAME, msg); - exit(1); +/** + * Print formatted text as an error and then forcefully terminate the program. + */ +void TCOD_fatal(const char *fmt, ...) +{ + va_list ap; + TCOD_sys_shutdown(); + fprintf(stderr, "%s FATAL ERROR:\n", TCOD_STRVERSIONNAME); + va_start(ap, fmt); + vfprintf(stderr, fmt, ap); + va_end(ap); + fprintf(stderr, "\n"); + std::terminate(); +} +void TCOD_fatal_nopar(const char *msg) +{ + TCOD_fatal("%s", msg); } /* dynamic library support */ #ifdef TCOD_WINDOWS -TCOD_library_t TCOD_load_library(const char *path) { - return (TCOD_library_t)LoadLibrary(path); +TCOD_library_t TCOD_load_library(const char *path) +{ + return static_cast(LoadLibrary(path)); } -void * TCOD_get_function_address(TCOD_library_t library, const char *function_name) { - return (void *)GetProcAddress((HMODULE)library,function_name); +void* TCOD_get_function_address( + TCOD_library_t library, const char *function_name) +{ + return reinterpret_cast(GetProcAddress(static_cast(library), + function_name)); } -void TCOD_close_library(TCOD_library_t library) { - FreeLibrary((HMODULE)library); +void TCOD_close_library(TCOD_library_t library) +{ + FreeLibrary(static_cast(library)); } #else -TCOD_library_t TCOD_load_library(const char *path) { - void *l=dlopen(path,RTLD_LAZY); - return (TCOD_library_t)l; +TCOD_library_t TCOD_load_library(const char *path) +{ + void *l = dlopen(path, RTLD_LAZY); + return l; } void * TCOD_get_function_address(TCOD_library_t library, const char *function_name) { - return dlsym(library,(char *)function_name); + return dlsym(library, function_name); } void TCOD_close_library(TCOD_library_t library) { dlclose(library); diff --git a/tcod_sys/libtcod/src/libtcod/sys_opengl_c.cpp b/tcod_sys/libtcod/src/libtcod/sys_opengl_c.cpp index 33dcd687d..9a91c7821 100644 --- a/tcod_sys/libtcod/src/libtcod/sys_opengl_c.cpp +++ b/tcod_sys/libtcod/src/libtcod/sys_opengl_c.cpp @@ -1,30 +1,34 @@ -/* -* libtcod -* Copyright (c) 2008-2018 Jice & Mingos & rmtew -* All rights reserved. -* -* Redistribution and use in source and binary forms, with or without -* modification, are permitted provided that the following conditions are met: -* * Redistributions of source code must retain the above copyright -* notice, this list of conditions and the following disclaimer. -* * Redistributions in binary form must reproduce the above copyright -* notice, this list of conditions and the following disclaimer in the -* documentation and/or other materials provided with the distribution. -* * The name of Jice or Mingos may not be used to endorse or promote -* products derived from this software without specific prior written -* permission. -* -* THIS SOFTWARE IS PROVIDED BY JICE, MINGOS AND RMTEW ``AS IS'' AND ANY -* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED -* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE -* DISCLAIMED. IN NO EVENT SHALL JICE, MINGOS OR RMTEW BE LIABLE FOR ANY -* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES -* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; -* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND -* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS -* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. -*/ +/* BSD 3-Clause License + * + * Copyright © 2008-2019, Jice and the libtcod contributors. + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions are met: + * + * 1. Redistributions of source code must retain the above copyright notice, + * this list of conditions and the following disclaimer. + * + * 2. Redistributions in binary form must reproduce the above copyright notice, + * this list of conditions and the following disclaimer in the documentation + * and/or other materials provided with the distribution. + * + * 3. Neither the name of the copyright holder nor the names of its + * contributors may be used to endorse or promote products derived from + * this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE + * POSSIBILITY OF SUCH DAMAGE. + */ /* * This renderer is mostly copied and pasted from Antagonist's SkyFire GLSL roguelike engine */ @@ -34,28 +38,19 @@ #include "libtcod_int.h" #include "console.h" -#ifndef NO_OPENGL #include +#include #include -#include - -#define CHECKGL( GLcall ) \ - GLcall; \ - if(!_CheckGL_Error( #GLcall, __FILE__, __LINE__)) \ - return false; +#include "sdl2/gl2_ext_.h" -#ifdef NDEBUG -#define DBGCHECKGL(GLcall) GLcall -#else -#define DBGCHECKGL CHECKGL -#endif +#define CHECKGL(GLcall) GLcall; tcod::sdl2::gl_check() +#define DBGCHECKGL(GLcall) GLcall; tcod::sdl2::gl_debug() -typedef enum -{ - Character, - ForeCol, - BackCol, - ConsoleDataEnumSize +typedef enum { + Character, + ForeCol, + BackCol, + ConsoleDataEnumSize } ConsoleDataEnum; /* JBR04152012 - Made Character a 4 byte value here to support extended characters like other renderers. Seems like it should be possible to make it a two byte value using GL_UNSIGNED_SHORT_5_6_5_REV in updateTex, @@ -102,7 +97,7 @@ static const char *TCOD_con_pixel_shader = " pixPos = vec2(pixPos.x*fontcoef.x,pixPos.y*fontcoef.y); " /* Correct pixel offset for font tex location */ " vec2 address = vec2(conPos.x*termcoef.x,conPos.y*termcoef.y); " -" address=address+vec2(0.001, 0.001); " +" address=address+vec2(0.001, 0.001); " " vec4 charvec = texture2D(term,address);" " float inchar = (charvec.r * 256.0) + (charvec.g * 256.0 * 256.0);" /* character */ " vec4 tcharfcol = texture2D(termfcol, address); " /* front color */ @@ -114,38 +109,37 @@ static const char *TCOD_con_pixel_shader = " gl_FragColor=gl_FragColor.a*tcharfcol+(1.0-gl_FragColor.a)*tcharbcol; " /* Coloring stage */ "} " ; - -bool _CheckGL_Error(const char* GLcall, const char* file, const int line) -{ - GLenum errCode; - if((errCode = glGetError())!=GL_NO_ERROR) - { - printf("OPENGL ERROR #%i: in file %s on line %i\n",errCode,file, line); - printf("OPENGL Call: %s\n",GLcall); - return false; - } - return true; -} - -/* called before creating window */ +/** + * Called before creating a window with the older libtcod renderers. + */ void TCOD_opengl_init_attributes(void) { - static bool first=true; - if ( first ) { - SDL_GL_SetAttribute(SDL_GL_DOUBLEBUFFER, 1); - SDL_GL_SetAttribute(SDL_GL_RED_SIZE, 8); - SDL_GL_SetAttribute(SDL_GL_BLUE_SIZE, 8); - SDL_GL_SetAttribute(SDL_GL_GREEN_SIZE,8); - SDL_GL_SetAttribute(SDL_GL_BUFFER_SIZE, 32 ); - /* ATI driver bug : enabling this might result in red screen */ - /* SDL_GL_SetAttribute(SDL_GL_ACCELERATED_VISUAL, 1); */ - first=false; - } + switch (TCOD_ctx.renderer) { + case TCOD_RENDERER_GLSL: + SDL_GL_SetAttribute(SDL_GL_CONTEXT_PROFILE_MASK, + SDL_GL_CONTEXT_PROFILE_COMPATIBILITY); + SDL_GL_SetAttribute(SDL_GL_CONTEXT_MAJOR_VERSION, 2); + SDL_GL_SetAttribute(SDL_GL_CONTEXT_MINOR_VERSION, 0); + + break; + case TCOD_RENDERER_OPENGL: + SDL_GL_SetAttribute(SDL_GL_CONTEXT_PROFILE_MASK, + SDL_GL_CONTEXT_PROFILE_COMPATIBILITY); + SDL_GL_SetAttribute(SDL_GL_CONTEXT_MAJOR_VERSION, 1); + SDL_GL_SetAttribute(SDL_GL_CONTEXT_MINOR_VERSION, 0); + break; + default: break; + } + SDL_GL_SetAttribute(SDL_GL_DOUBLEBUFFER, 1); + SDL_GL_SetAttribute(SDL_GL_RED_SIZE, 8); + SDL_GL_SetAttribute(SDL_GL_BLUE_SIZE, 8); + SDL_GL_SetAttribute(SDL_GL_GREEN_SIZE, 8); + SDL_GL_SetAttribute(SDL_GL_BUFFER_SIZE, 32); } /* console size (power of 2 and cells) */ static int POTconwidth, POTconheight, conwidth, conheight; /* programs and shaders handles */ -static GLhandleARB conProgram, conVertShader, conFragShader; +static GLuint conProgram, conVertShader, conFragShader; /* font texture handle */ static GLuint font_tex; /* font power of 2 size and pixels */ @@ -155,534 +149,517 @@ static GLuint Tex[ConsoleDataEnumSize]; static unsigned char *data[ConsoleDataEnumSize]; static bool dirty[ConsoleDataEnumSize]; -/* extension function pointers */ -static PFNGLCREATESHADEROBJECTARBPROC glCreateShaderObjectARB=0; -static PFNGLGETOBJECTPARAMETERIVARBPROC glGetObjectParameterivARB=0; -static PFNGLSHADERSOURCEARBPROC glShaderSourceARB=0; -static PFNGLCOMPILESHADERARBPROC glCompileShaderARB=0; -static PFNGLGETINFOLOGARBPROC glGetInfoLogARB=0; -static PFNGLCREATEPROGRAMOBJECTARBPROC glCreateProgramObjectARB=0; -static PFNGLATTACHOBJECTARBPROC glAttachObjectARB=0; -static PFNGLLINKPROGRAMARBPROC glLinkProgramARB=0; -static PFNGLUSEPROGRAMOBJECTARBPROC glUseProgramObjectARB=0; -static PFNGLUNIFORM2FARBPROC glUniform2fARB=0; -static PFNGLGETUNIFORMLOCATIONARBPROC glGetUniformLocationARB=0; -static PFNGLUNIFORM1FARBPROC glUniform1fARB=0; -static PFNGLUNIFORM1IARBPROC glUniform1iARB=0; -static PFNGLACTIVETEXTUREPROC glActiveTextureF=0; - static SDL_GLContext glcontext; -void TCOD_opengl_uninit_state() { - SDL_GL_DeleteContext(glcontext); +void TCOD_opengl_uninit_state() +{ + SDL_GL_DeleteContext(glcontext); } - -/* call after creating window */ -bool TCOD_opengl_init_state(int conw, int conh, void *font) { - SDL_Surface *font_surf=(SDL_Surface *)font; - SDL_PixelFormat *my_format=SDL_AllocFormat(SDL_GetWindowPixelFormat(window)); - - /* convert font for opengl */ - uint32_t rmask, gmask, bmask, amask; - SDL_Surface *temp; - SDL_Surface *temp_alpha; - - glcontext = SDL_GL_CreateContext(window); - - /* check opengl extensions */ - if ( TCOD_ctx.renderer == TCOD_RENDERER_GLSL ) { - bool hasShader = false; - const char *glexts=(const char *)glGetString(GL_EXTENSIONS); - if (glexts ) { - hasShader = (strstr(glexts,"GL_ARB_shader_objects") != NULL); - } - if (! hasShader ) { - TCOD_LOG(("Missing GL_ARB_shader_objects extension. Falling back to fixed pipeline...\n")); - TCOD_ctx.renderer = TCOD_RENDERER_OPENGL; - } - } - - /* set extensions functions pointers */ - glCreateShaderObjectARB=(PFNGLCREATESHADEROBJECTARBPROC)SDL_GL_GetProcAddress("glCreateShaderObjectARB"); - glGetObjectParameterivARB=(PFNGLGETOBJECTPARAMETERIVARBPROC)SDL_GL_GetProcAddress("glGetObjectParameterivARB"); - glShaderSourceARB=(PFNGLSHADERSOURCEARBPROC)SDL_GL_GetProcAddress("glShaderSourceARB"); - glCompileShaderARB=(PFNGLCOMPILESHADERARBPROC)SDL_GL_GetProcAddress("glCompileShaderARB"); - glGetInfoLogARB=(PFNGLGETINFOLOGARBPROC)SDL_GL_GetProcAddress("glGetInfoLogARB"); - glCreateProgramObjectARB=(PFNGLCREATEPROGRAMOBJECTARBPROC)SDL_GL_GetProcAddress("glCreateProgramObjectARB"); - glAttachObjectARB=(PFNGLATTACHOBJECTARBPROC)SDL_GL_GetProcAddress("glAttachObjectARB"); - glLinkProgramARB=(PFNGLLINKPROGRAMARBPROC)SDL_GL_GetProcAddress("glLinkProgramARB"); - glUseProgramObjectARB=(PFNGLUSEPROGRAMOBJECTARBPROC)SDL_GL_GetProcAddress("glUseProgramObjectARB"); - glUniform2fARB=(PFNGLUNIFORM2FARBPROC)SDL_GL_GetProcAddress("glUniform2fARB"); - glGetUniformLocationARB=(PFNGLGETUNIFORMLOCATIONARBPROC)SDL_GL_GetProcAddress("glGetUniformLocationARB"); - glUniform1fARB=(PFNGLUNIFORM1FARBPROC)SDL_GL_GetProcAddress("glUniform1fARB"); - glUniform1iARB=(PFNGLUNIFORM1IARBPROC)SDL_GL_GetProcAddress("glUniform1iARB"); - glActiveTextureF=(PFNGLACTIVETEXTUREPROC)SDL_GL_GetProcAddress("glActiveTexture"); - - /* set opengl state */ - glEnable(GL_TEXTURE_2D); - glClearColor(1.0f, 1.0f, 0.0f, 0.0f); - glPixelStorei(GL_UNPACK_ALIGNMENT, 1); - glClear( GL_COLOR_BUFFER_BIT ); - glMatrixMode( GL_PROJECTION ); - glLoadIdentity(); - if ( TCOD_ctx.renderer == TCOD_RENDERER_GLSL ) { - glOrtho(0, conw, 0, conh, -1.0f, 1.0f); - glDisable (GL_BLEND); - } else { - glOrtho(0, conw, conh, 0.0f, -1.0f, 1.0f); - glEnable (GL_BLEND); - glBlendFunc (GL_ONE, GL_ONE_MINUS_SRC_ALPHA); - } - - glMatrixMode( GL_MODELVIEW ); - glLoadIdentity(); -/*#ifdef TCOD_WINDOWS */ - if ( ! TCOD_ctx.fullscreen ) { - /* turn vsync off in windowed mode */ - typedef bool (APIENTRY *PFNWGLSWAPINTERVALFARPROC)(int); - PFNWGLSWAPINTERVALFARPROC wglSwapIntervalEXT = 0; - - wglSwapIntervalEXT = (PFNWGLSWAPINTERVALFARPROC)SDL_GL_GetProcAddress("wglSwapIntervalEXT"); - - if (wglSwapIntervalEXT) wglSwapIntervalEXT(0); - } -/*#endif */ - - /* compute pot size */ - conwidth=conw; - conheight=conh; - POTconwidth=POTconheight=1; - while ( POTconwidth < conw ) POTconwidth *= 2; - while ( POTconheight < conh ) POTconheight *= 2; - - - #if SDL_BYTEORDER == SDL_BIG_ENDIAN - rmask = 0xff000000; - gmask = 0x00ff0000; - bmask = 0x0000ff00; - amask = 0x000000ff; - #else - rmask = 0x000000ff; - gmask = 0x0000ff00; - bmask = 0x00ff0000; - amask = 0xff000000; - #endif - - fontwidth=font_surf->w; - fontheight=font_surf->h; - POTfontwidth=POTfontheight=1; - while ( POTfontwidth < fontwidth ) POTfontwidth *= 2; - while ( POTfontheight < fontheight ) POTfontheight *= 2; - - SDL_SetColorKey(font_surf, 1, SDL_MapRGB(font_surf->format, 0, 0, 0)); - my_format->Amask = amask; - temp_alpha = SDL_ConvertSurface(font_surf, my_format, 0); - SDL_FreeFormat(my_format); - - temp = SDL_CreateRGBSurface(SDL_SWSURFACE, POTfontwidth, POTfontheight, 32, bmask, gmask, rmask, amask); /*BGRA */ - - SDL_BlitSurface(temp_alpha, NULL, temp, NULL); - SDL_FreeSurface(temp_alpha); - - CHECKGL(glGenTextures(1, &font_tex)); - CHECKGL(glBindTexture(GL_TEXTURE_2D, font_tex)); - SDL_LockSurface(temp); - - glTexParameteri( GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST ); - glTexParameteri( GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST ); - - CHECKGL(glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, temp->w, temp->h, 0, GL_BGRA, GL_UNSIGNED_BYTE, temp->pixels)); - SDL_UnlockSurface(temp); - SDL_FreeSurface(temp); - return true; +/** + * Called after creating an OpenGL window. + */ +bool TCOD_opengl_init_state(int conw, int conh, SDL_Surface* font) +{ + SDL_PixelFormat *my_format = + SDL_AllocFormat(SDL_GetWindowPixelFormat(window)); + + glcontext = SDL_GL_CreateContext(window); + + if(!gladLoadGLLoader(SDL_GL_GetProcAddress)) { + throw std::runtime_error("Failed to invoke the GLAD loader."); + } + // check OpenGL extensions + if (TCOD_ctx.renderer == TCOD_RENDERER_GLSL) { + if (!GLAD_GL_VERSION_2_0) { + TCOD_LOG(("Falling back to fixed pipeline...\n")); + TCOD_ctx.renderer = TCOD_RENDERER_OPENGL; + } + } + // set OpenGL state + glEnable(GL_TEXTURE_2D); + glClearColor(1.0f, 1.0f, 0.0f, 0.0f); + glPixelStorei(GL_UNPACK_ALIGNMENT, 1); + glClear(GL_COLOR_BUFFER_BIT); + glMatrixMode(GL_PROJECTION); + glLoadIdentity(); + if (TCOD_ctx.renderer == TCOD_RENDERER_GLSL) { + glOrtho(0, conw, 0, conh, -1.0, 1.0); + glDisable(GL_BLEND); + } else { + glOrtho(0, conw, conh, 0.0, -1.0, 1.0); + glEnable(GL_BLEND); + glBlendFunc(GL_ONE, GL_ONE_MINUS_SRC_ALPHA); + } + + glMatrixMode(GL_MODELVIEW); + glLoadIdentity(); + + if (!TCOD_ctx.fullscreen) { + SDL_GL_SetSwapInterval(0); // turn vsync off in windowed mode + } + // compute pot size + conwidth = conw; + conheight = conh; + POTconwidth = POTconheight = 1; + while (POTconwidth < conw) { POTconwidth *= 2; } + while (POTconheight < conh) { POTconheight *= 2; } + // convert font for OpenGL + uint32_t rmask, gmask, bmask, amask; + SDL_Surface *temp; + SDL_Surface *temp_alpha; + + #if SDL_BYTEORDER == SDL_BIG_ENDIAN + rmask = 0xff000000; + gmask = 0x00ff0000; + bmask = 0x0000ff00; + amask = 0x000000ff; + #else + rmask = 0x000000ff; + gmask = 0x0000ff00; + bmask = 0x00ff0000; + amask = 0xff000000; + #endif + + fontwidth = font->w; + fontheight = font->h; + POTfontwidth = POTfontheight=1; + while (POTfontwidth < fontwidth) { POTfontwidth *= 2; } + while (POTfontheight < fontheight) { POTfontheight *= 2; } + + SDL_SetColorKey(font, 1, SDL_MapRGB(font->format, 0, 0, 0)); + my_format->Amask = amask; + temp_alpha = SDL_ConvertSurface(font, my_format, 0); + SDL_FreeFormat(my_format); + + temp = SDL_CreateRGBSurface(SDL_SWSURFACE, POTfontwidth, POTfontheight, 32, + bmask, gmask, rmask, amask); // BGRA + + SDL_BlitSurface(temp_alpha, NULL, temp, NULL); + SDL_FreeSurface(temp_alpha); + + CHECKGL(glGenTextures(1, &font_tex)); + CHECKGL(glBindTexture(GL_TEXTURE_2D, font_tex)); + SDL_LockSurface(temp); + + glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST); + glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST); + + CHECKGL(glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, temp->w, temp->h, 0, GL_BGRA, + GL_UNSIGNED_BYTE, temp->pixels)); + SDL_UnlockSurface(temp); + SDL_FreeSurface(temp); + return true; } - -static GLhandleARB loadShader(const char *txt, GLuint type) { - int success; - int infologLength = 0; - int charsWritten = 0; - char *infoLog; - GLhandleARB v = glCreateShaderObjectARB(type); - glShaderSourceARB(v, 1, &txt, 0); - glCompileShaderARB(v); - - glGetObjectParameterivARB(v, GL_COMPILE_STATUS, &success); - if(success!=GL_TRUE) - { - /* something went wrong */ - glGetObjectParameterivARB(v, GL_INFO_LOG_LENGTH,&infologLength); - if(infologLength>0) - { - infoLog = (char *)malloc(infologLength); - glGetInfoLogARB(v, infologLength, &charsWritten, infoLog); - printf("GLSL ERROR : %s\n",infoLog); - free(infoLog); - } - return 0; - } - - return v; +/** + * Return a `type` shader from the `txt` source. + * + * Returns 0 non error. + */ +static GLuint loadShader(const char* txt, GLuint type) +{ + GLuint v = glCreateShader(type); + glShaderSource(v, 1, &txt, 0); + glCompileShader(v); + int success; + glGetShaderiv(v, GL_COMPILE_STATUS, &success); + if(success != GL_TRUE) { + // something went wrong + int infologLength = 0; + glGetShaderiv(v, GL_INFO_LOG_LENGTH, &infologLength); + if(infologLength > 0) { + int charsWritten = 0; + char* infoLog = static_cast(malloc(infologLength)); + glGetProgramInfoLog(v, infologLength, &charsWritten, infoLog); + printf("GLSL ERROR : %s\n", infoLog); + free(infoLog); + } + return 0; + } + return v; } - -static bool loadProgram(const char *vertShaderCode, const char *fragShaderCode, - GLhandleARB *vertShader, GLhandleARB *fragShader, GLhandleARB *prog) { - /* Create and load Program and Shaders */ - int success; - *prog = DBGCHECKGL(glCreateProgramObjectARB()); - - *vertShader = loadShader(vertShaderCode, GL_VERTEX_SHADER); - if ( *vertShader == 0 ) return false; - glAttachObjectARB(*prog, *vertShader); - - *fragShader = loadShader(fragShaderCode, GL_FRAGMENT_SHADER); - if ( *fragShader == 0 ) return false; - glAttachObjectARB(*prog, *fragShader); - - glLinkProgramARB(*prog); - - glGetObjectParameterivARB(*prog, GL_LINK_STATUS, &success); - if(success!=GL_TRUE) - { - /* something went wrong */ - int infologLength = 0; - int charsWritten = 0; - char *infoLog; - glGetObjectParameterivARB(*prog, GL_INFO_LOG_LENGTH,&infologLength); - if (infologLength > 0) - { - infoLog = (char *)malloc(infologLength); - glGetInfoLogARB(*prog, infologLength, &charsWritten, infoLog); - printf("OPENGL ERROR: Program link Error"); - printf("%s\n",infoLog); - free(infoLog); - } - return false; - } - return true; +/** + * Compile a program from sources and output the shaders and program, returns + * true if successful. + * + * `vertShaderCode` and `fragShaderCode` point to the source code for the + * shaders. + * + * Shaders will be output to `vertShader` and `fragShader`. + * + * Program will be output to `prog`. + */ +static bool loadProgram(const char* vertShaderCode, const char* fragShaderCode, + GLuint* vertShader, GLuint* fragShader, GLuint* prog) +{ + // Create and load Program and Shaders + *prog = DBGCHECKGL(glCreateProgram()); + + *vertShader = loadShader(vertShaderCode, GL_VERTEX_SHADER); + if (*vertShader == 0) { return false; } + glAttachShader(*prog, *vertShader); + + *fragShader = loadShader(fragShaderCode, GL_FRAGMENT_SHADER); + if (*fragShader == 0) { return false; } + glAttachShader(*prog, *fragShader); + + glLinkProgram(*prog); + + int success; + glGetProgramiv(*prog, GL_LINK_STATUS, &success); + if(success != GL_TRUE) { + /* something went wrong */ + int infologLength = 0; + int charsWritten = 0; + glGetProgramiv(*prog, GL_INFO_LOG_LENGTH, &infologLength); + if (infologLength > 0) { + char* infoLog = static_cast(malloc(infologLength)); + glGetProgramInfoLog(*prog, infologLength, &charsWritten, infoLog); + printf("OPENGL ERROR: Program link Error"); + printf("%s\n", infoLog); + free(infoLog); + } + return false; + } + return true; } - -bool TCOD_opengl_init_shaders(void) { - int i; - TCOD_color_t *fCol; - if ( TCOD_ctx.renderer == TCOD_RENDERER_GLSL ) { - if (! loadProgram(TCOD_con_vertex_shader, TCOD_con_pixel_shader, &conVertShader, &conFragShader, &conProgram ) ) return false; - } - /* Host side data init */ - for(i = 0; i< ConsoleDataEnumSize; i++) - { - data[i] = (unsigned char *)calloc(conwidth*conheight,ConsoleDataAlignment[i]); - dirty[i]=true; - } - /* Initialize ForeCol to 255, 255, 255, 255 */ - fCol = (TCOD_color_t *)data[ForeCol]; - for( i = 0; i < conwidth*conheight; i++) - { - fCol[i].r=255; - fCol[i].g=255; - fCol[i].b=255; - } - - /* Generate Textures */ - glGenTextures(3, Tex); - - /* Character Texture */ - CHECKGL(glBindTexture(GL_TEXTURE_2D, Tex[Character])); - - CHECKGL(glTexParameteri( GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST )); - CHECKGL(glTexParameteri( GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST )); - - CHECKGL(glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, POTconwidth, POTconheight, 0, GL_LUMINANCE, GL_UNSIGNED_BYTE, 0)); - - - /* ForeCol Texture */ - CHECKGL(glBindTexture(GL_TEXTURE_2D, Tex[ForeCol])); - - CHECKGL(glTexParameteri( GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST )); - CHECKGL(glTexParameteri( GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST )); - - CHECKGL(glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, POTconwidth, POTconheight, 0, GL_RGB, GL_UNSIGNED_BYTE, 0)); - - /* BackCol Texture */ - CHECKGL(glBindTexture(GL_TEXTURE_2D, Tex[BackCol])); - - CHECKGL(glTexParameteri( GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST )); - CHECKGL(glTexParameteri( GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST )); - - CHECKGL(glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, POTconwidth, POTconheight, 0, GL_RGB, GL_UNSIGNED_BYTE, 0)); - - CHECKGL(glBindTexture(GL_TEXTURE_2D, 0)); - - return true; +/** + * Load built-in shaders, returns true if successful. + */ +bool TCOD_opengl_init_shaders(void) +{ + if (TCOD_ctx.renderer == TCOD_RENDERER_GLSL) { + if (!loadProgram(TCOD_con_vertex_shader, TCOD_con_pixel_shader, + &conVertShader, &conFragShader, &conProgram)) { + return false; + } + } + // Host side data init + for(int i = 0; i < ConsoleDataEnumSize; ++i) + { + data[i] = static_cast( + calloc(conwidth * conheight, ConsoleDataAlignment[i]) + ); + dirty[i] = true; + } + // Initialize ForeCol to 255, 255, 255, 255 + TCOD_color_t* fCol = reinterpret_cast(data[ForeCol]); + for(int i = 0; i < conwidth * conheight; ++i) + { + fCol[i].r=255; + fCol[i].g=255; + fCol[i].b=255; + } + // Generate Textures + glGenTextures(3, Tex); + + // Character Texture + CHECKGL(glBindTexture(GL_TEXTURE_2D, Tex[Character])); + + CHECKGL(glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST)); + CHECKGL(glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST)); + + CHECKGL(glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, POTconwidth, POTconheight, 0, + GL_LUMINANCE, GL_UNSIGNED_BYTE, 0)); + + // ForeCol Texture + CHECKGL(glBindTexture(GL_TEXTURE_2D, Tex[ForeCol])); + + CHECKGL(glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST)); + CHECKGL(glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST)); + + CHECKGL(glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, POTconwidth, POTconheight, 0, + GL_RGB, GL_UNSIGNED_BYTE, 0)); + + // BackCol Texture + CHECKGL(glBindTexture(GL_TEXTURE_2D, Tex[BackCol])); + + CHECKGL(glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST)); + CHECKGL(glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST)); + + CHECKGL(glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, POTconwidth, POTconheight, 0, + GL_RGB, GL_UNSIGNED_BYTE, 0)); + + CHECKGL(glBindTexture(GL_TEXTURE_2D, 0)); + + return true; } -static bool updateTex(ConsoleDataEnum dataType) { - GLenum Type=0; - DBGCHECKGL(glBindTexture(GL_TEXTURE_2D, Tex[dataType])); - - switch(ConsoleDataAlignment[dataType]) - { - case 1: - Type = GL_RED; - break; - /*case 2: - Type = GL_RG; - break; */ - case 3: - Type = GL_RGB; - break; - case 4: - Type = GL_RGBA; - break; - } - /*glPixelStorei(GL_UNPACK_ALIGNMENT, 1); */ - DBGCHECKGL(glTexSubImage2D(GL_TEXTURE_2D, 0, 0, 0, conwidth, conheight, Type, GL_UNSIGNED_BYTE, data[dataType])); - - DBGCHECKGL(glBindTexture(GL_TEXTURE_2D,0)); - return true; +static bool updateTex(ConsoleDataEnum dataType) +{ + GLenum Type = 0; + DBGCHECKGL(glBindTexture(GL_TEXTURE_2D, Tex[dataType])); + + switch(ConsoleDataAlignment[dataType]) { + case 1: + Type = GL_RED; + break; + /*case 2: + Type = GL_RG; + break; */ + case 3: + Type = GL_RGB; + break; + case 4: + Type = GL_RGBA; + break; + } + /*glPixelStorei(GL_UNPACK_ALIGNMENT, 1); */ + DBGCHECKGL(glTexSubImage2D(GL_TEXTURE_2D, 0, 0, 0, conwidth, conheight, + Type, GL_UNSIGNED_BYTE, data[dataType])); + + DBGCHECKGL(glBindTexture(GL_TEXTURE_2D, 0)); + return true; } -static void updateChar(ConsoleDataEnum dataType, int BufferPos, unsigned char *c, int length, int offset) { - int i; - dirty[dataType] = true; /* Set dirty so Texture gets updated next frame */ - - for(i = 0; i(&c), + ConsoleDataAlignment[Character], 0); + updateChar(ForeCol, loc, &fore.r, ConsoleDataAlignment[ForeCol], 0); + } + updateChar(BackCol, loc, &back.r, ConsoleDataAlignment[BackCol], 0); } -bool TCOD_opengl_render( int oldFade, bool *ascii_updated, struct TCOD_Console *console, struct TCOD_Console *cache) { - int x,y,i; - int fade = (int)TCOD_console_get_fade(); - bool track_changes = (cache && oldFade == fade); - TCOD_color_t *ofg, *obg, *nfg, *nbg; - int *c = console->ch_array; - int *oc; - nfg = console->fg_array; - nbg = console->bg_array; - if (track_changes) { - oc = cache->ch_array; - ofg = cache->fg_array; - obg = cache->bg_array; - } - /* update opengl data */ - /* TODO use function pointers so that libtcod's putchar directly updates opengl data */ - for (y=0;yr != obg->r || nbg->g != obg->g || nbg->b != obg->b || - nfg->r != ofg->r || nfg->g != ofg->g || nfg->b != ofg->b || - *c != *oc) { - changed=true; - } - } - if ( changed ) { - TCOD_opengl_putchar_ex(x, y, TCOD_get_tileid_for_charcode_(*c), *nfg, *nbg); - } - c++; - nfg++; - nbg++; - if (track_changes) { - oc++; - ofg++; - obg++; - } - } - } - - /* check if any of the textures have changed since they were last uploaded */ - for( i = 0; i< ConsoleDataEnumSize; i++) - { - if(dirty[i]) - { - updateTex((ConsoleDataEnum)i); - dirty[i] = false; - } - } - if ( TCOD_ctx.renderer == TCOD_RENDERER_OPENGL ) { - /* fixed pipeline for video cards without pixel shader support */ - /* draw the background as a single quad */ - float texw=(float)conwidth/POTconwidth; - float texh=(float)conheight/POTconheight; - float fonw=(float)fontwidth/(TCOD_ctx.fontNbCharHoriz*POTfontwidth); - float fonh=(float)fontheight/(TCOD_ctx.fontNbCharVertic*POTfontheight); - DBGCHECKGL(glBindTexture(GL_TEXTURE_2D, Tex[BackCol])); - DBGCHECKGL(glBegin(GL_QUADS); - glColor3f(1.0,1.0,1.0); - glTexCoord2f( 0.0, 0.0 ); - glVertex2i( 0, 0); - glTexCoord2f( 0.0, texh); - glVertex2i( 0, conheight ); - glTexCoord2f( texw, texh ); - glVertex2i( conwidth, conheight); - glTexCoord2f( texw, 0.0 ); - glVertex2i( conwidth, 0 ); - glEnd()); - /* draw the characters (one quad per cell) */ - DBGCHECKGL(glBindTexture(GL_TEXTURE_2D, font_tex)); - - c = console->ch_array; - nfg = console->fg_array; - nbg = console->bg_array; - for (y=0;yValidate()); */ - - DBGCHECKGL(glBegin(GL_QUADS); - glTexCoord2f(0.0f, 1.0f); - glVertex3f(-1.0f,-1.0f,0.0f); - glTexCoord2f(1.0f, 1.0f); - glVertex3f(1.0f,-1.0f,0.0f); - glTexCoord2f(1.0f, 0.0f); - glVertex3f(1.0f,1.0f, 0.0f); - glTexCoord2f(0.0f, 0.0f); - glVertex3f(-1.0f,1.0f,0.0f); - glEnd()); - - DBGCHECKGL(glBindTexture(GL_TEXTURE_2D, 0)); - - DBGCHECKGL(glUseProgramObjectARB(0)); - } - /* fading overlay */ - if ( fade != 255 ) { - int x=0,y=0; - if ( TCOD_ctx.fullscreen ) { - x=TCOD_ctx.fullscreen_offsetx/TCOD_ctx.font_width; - y=TCOD_ctx.fullscreen_offsety/TCOD_ctx.font_height; - } - glBegin( GL_QUADS ); - glColor4f(TCOD_ctx.fading_color.r/255.0f,TCOD_ctx.fading_color.g/255.0f,TCOD_ctx.fading_color.b/255.0f,1.0f-fade/255.0f); - glVertex2i( x, y); - glVertex2i( x, y+conheight ); - glVertex2i( x+conwidth, y+conheight ); - glVertex2i( x+conwidth, y); - glEnd(); - } - return true; +bool TCOD_opengl_render( + int oldFade, + bool*, // ascii_updated + TCOD_Console* console, + TCOD_Console* cache) +{ + int fade = TCOD_console_get_fade(); + bool track_changes = (cache && oldFade == fade); + // update OpenGL data + for (int y = 0; y < conheight; ++y) { + for (int x = 0; x < conwidth; ++x) { + int i = y * conwidth + x; + if (track_changes && console->tiles[i] == cache->tiles[i]) { + continue; + } + TCOD_opengl_putchar_ex( + x, y, + TCOD_get_tileid_for_charcode_(console->tiles[i].ch), + tcod::ColorRGB(console->tiles[i].fg), + tcod::ColorRGB(console->tiles[i].bg) + ); + } + } + /* check if any of the textures have changed since they were last uploaded */ + for(int i = 0; i < ConsoleDataEnumSize; ++i) + { + if (dirty[i]) { + updateTex(static_cast(i)); + dirty[i] = false; + } + } + if (TCOD_ctx.renderer == TCOD_RENDERER_OPENGL) { + /* fixed pipeline for video cards without pixel shader support */ + /* draw the background as a single quad */ + float texw = static_cast(conwidth) / POTconwidth; + float texh = static_cast(conheight) / POTconheight; + float fonw = static_cast(fontwidth) / (TCOD_ctx.fontNbCharHoriz + * POTfontwidth); + float fonh = static_cast(fontheight) / (TCOD_ctx.fontNbCharVertic + * POTfontheight); + DBGCHECKGL(glBindTexture(GL_TEXTURE_2D, Tex[BackCol])); + DBGCHECKGL( + glBegin(GL_QUADS); + glColor3f(1.0, 1.0, 1.0); + glTexCoord2f(0.0, 0.0); + glVertex2i(0, 0); + glTexCoord2f(0.0, texh); + glVertex2i(0, conheight); + glTexCoord2f(texw, texh); + glVertex2i(conwidth, conheight); + glTexCoord2f(texw, 0.0); + glVertex2i(conwidth, 0); + glEnd() + ); + // draw the characters (one quad per cell) + DBGCHECKGL(glBindTexture(GL_TEXTURE_2D, font_tex)); + + for (int y = 0; y < conheight; ++y) { + for (int x = 0; x < conwidth; ++x) { + int i = y * conwidth + x; + if (console->tiles[i].ch == ' ') { continue; } + const TCOD_ColorRGB f = tcod::ColorRGB(console->tiles[i].fg); + const TCOD_ColorRGB b = tcod::ColorRGB(console->tiles[i].bg); + // only draw character if foreground color != background color + if (f == b) { continue; } + int destx = x;/* *TCOD_font_width; */ + int desty = y;/* *TCOD_font_height; */ + if (TCOD_ctx.fullscreen) { + destx += TCOD_ctx.fullscreen_offsetx / TCOD_ctx.font_width; + desty += TCOD_ctx.fullscreen_offsety / TCOD_ctx.font_height; + } + // draw foreground + int ascii = TCOD_ctx.ascii_to_tcod[console->tiles[i].ch]; + int srcx = ascii % TCOD_ctx.fontNbCharHoriz; + int srcy = ascii / TCOD_ctx.fontNbCharHoriz; + glBegin(GL_QUADS); + glColor3f(f.r / 255.0f, f.g / 255.0f, f.b / 255.0f); + glTexCoord2f(srcx * fonw, srcy * fonh); + glVertex2i(destx, desty); + glTexCoord2f(srcx * fonw, (srcy + 1) * fonh); + glVertex2i(destx, desty + 1); + glTexCoord2f((srcx + 1) * fonw, (srcy + 1) * fonh); + glVertex2i(destx + 1, desty + 1); + glTexCoord2f((srcx + 1) * fonw, srcy * fonh); + glVertex2i(destx+1, desty); + glEnd(); + } + } + DBGCHECKGL(glBindTexture(GL_TEXTURE_2D, 0)); + } else { + // actual rendering + DBGCHECKGL(glUseProgram(conProgram)); + // Technically all these glUniform calls can be moved to SFConsole() when + // the shader is loaded. + // None of these change. + // The Textures still need to bind to the same # Activetexture throughout + // though. + DBGCHECKGL( + glUniform2f( + glGetUniformLocation(conProgram,"termsize"), + conwidth, + conheight + ) + ); + DBGCHECKGL( + glUniform2f( + glGetUniformLocation(conProgram,"termcoef"), + 1.0f / POTconwidth, + 1.0f / POTconheight + ) + ); + DBGCHECKGL( + glUniform1f( + glGetUniformLocation(conProgram,"fontw"), + static_cast(TCOD_ctx.fontNbCharHoriz) + ) + ); + DBGCHECKGL( + glUniform2f( + glGetUniformLocation(conProgram,"fontcoef"), + static_cast(fontwidth) / (POTfontwidth + * TCOD_ctx.fontNbCharHoriz), + static_cast(fontheight) / (POTfontheight + * TCOD_ctx.fontNbCharVertic) + ) + ); + + DBGCHECKGL(glActiveTexture(GL_TEXTURE0)); + DBGCHECKGL(glBindTexture(GL_TEXTURE_2D, font_tex)); + DBGCHECKGL(glUniform1i(glGetUniformLocation(conProgram,"font"), 0)); + + DBGCHECKGL(glActiveTexture(GL_TEXTURE1)); + DBGCHECKGL(glBindTexture(GL_TEXTURE_2D, Tex[Character])); + DBGCHECKGL(glUniform1i(glGetUniformLocation(conProgram, "term"), 1)); + + DBGCHECKGL(glActiveTexture(GL_TEXTURE2)); + DBGCHECKGL(glBindTexture(GL_TEXTURE_2D, Tex[ForeCol])); + DBGCHECKGL(glUniform1i(glGetUniformLocation(conProgram, "termfcol"), 2)); + + DBGCHECKGL(glActiveTexture(GL_TEXTURE3)); + DBGCHECKGL(glBindTexture(GL_TEXTURE_2D, Tex[BackCol])); + DBGCHECKGL(glUniform1i(glGetUniformLocation(conProgram, "termbcol"), 3)); + + /*DBGCHECKGL(shader->Validate()); */ + + DBGCHECKGL( + glBegin(GL_QUADS); + glTexCoord2f(0.0f, 1.0f); + glVertex3f(-1.0f, -1.0f, 0.0f); + glTexCoord2f(1.0f, 1.0f); + glVertex3f(1.0f, -1.0f, 0.0f); + glTexCoord2f(1.0f, 0.0f); + glVertex3f(1.0f, 1.0f, 0.0f); + glTexCoord2f(0.0f, 0.0f); + glVertex3f(-1.0f, 1.0f, 0.0f); + glEnd() + ); + DBGCHECKGL(glBindTexture(GL_TEXTURE_2D, 0)); + DBGCHECKGL(glUseProgram(0)); + } + /* fading overlay */ + if (fade != 255) { + int x = 0; + int y = 0; + if (TCOD_ctx.fullscreen) { + x = TCOD_ctx.fullscreen_offsetx / TCOD_ctx.font_width; + y = TCOD_ctx.fullscreen_offsety / TCOD_ctx.font_height; + } + glBegin(GL_QUADS); + glColor4f( + TCOD_ctx.fading_color.r / 255.0f, + TCOD_ctx.fading_color.g / 255.0f, + TCOD_ctx.fading_color.b / 255.0f, + 1.0f - fade / 255.0f + ); + glVertex2i(x, y); + glVertex2i(x, y + conheight); + glVertex2i(x + conwidth, y + conheight); + glVertex2i(x + conwidth, y); + glEnd(); + } + return true; } - -void TCOD_opengl_swap(void) { - SDL_GL_SwapWindow(window); +void TCOD_opengl_swap(void) +{ + SDL_GL_SwapWindow(window); } - -void * TCOD_opengl_get_screen(void) { - SDL_Surface *surf; - int pixw,pixh,offx=0,offy=0,x,y; - uint32_t mask,nmask; - - /* allocate a pixel buffer */ - pixw=TCOD_ctx.root->w * TCOD_ctx.font_width; - pixh=TCOD_ctx.root->h * TCOD_ctx.font_height; - surf=(SDL_Surface*)TCOD_sys_get_surface(pixw,pixh,false); - if ( TCOD_ctx.fullscreen ) { - offx=TCOD_ctx.fullscreen_offsetx; - offy=TCOD_ctx.fullscreen_offsety; - } - - /* get pixel data from opengl */ - glPushClientAttrib( GL_CLIENT_PIXEL_STORE_BIT ); - glPixelStorei(GL_PACK_ROW_LENGTH, 0); - glPixelStorei(GL_PACK_ALIGNMENT, 1); - glReadPixels(offx,offy,pixw,pixh, GL_RGB, GL_UNSIGNED_BYTE, surf->pixels); - glPopClientAttrib(); - - /* vertical flip (opengl has lower-left origin, SDL upper left) */ - mask=surf->format->Rmask|surf->format->Gmask|surf->format->Bmask; - nmask=~mask; - for (x=0; x < surf->w; x++) { - for (y=0; y < surf->h/2; y++) { - int offsrc=x*3+y*surf->pitch; - int offdst=x*3+(surf->h-1-y)*surf->pitch; - uint32_t *pixsrc = (uint32_t *)(((uint8_t*)surf->pixels)+offsrc); - uint32_t *pixdst = (uint32_t *)(((uint8_t*)surf->pixels)+offdst); - uint32_t tmp = *pixsrc; - *pixsrc = ((*pixsrc) & nmask) | ((*pixdst) & mask); - *pixdst = ((*pixdst) & nmask) | (tmp & mask); - } - } - - return (void *)surf; +/** + * Return an SDL_Surface screenshot of the OpenGL surface. + */ +SDL_Surface* TCOD_opengl_get_screen(void) +{ + int offx = 0; + int offy = 0; + /* allocate a pixel buffer */ + int pixw = TCOD_ctx.root->w * TCOD_ctx.font_width; + int pixh = TCOD_ctx.root->h * TCOD_ctx.font_height; + SDL_Surface* surf = TCOD_sys_get_surface(pixw, pixh, false); + if (TCOD_ctx.fullscreen) { + offx = TCOD_ctx.fullscreen_offsetx; + offy = TCOD_ctx.fullscreen_offsety; + } + /* get pixel data from opengl */ + glPushClientAttrib(GL_CLIENT_PIXEL_STORE_BIT); + glPixelStorei(GL_PACK_ROW_LENGTH, 0); + glPixelStorei(GL_PACK_ALIGNMENT, 1); + glReadPixels(offx, offy, pixw, pixh, GL_RGB, GL_UNSIGNED_BYTE, surf->pixels); + glPopClientAttrib(); + /* vertical flip (opengl has lower-left origin, SDL upper left) */ + uint32_t mask = (surf->format->Rmask | surf->format->Gmask + | surf->format->Bmask); + uint32_t nmask = ~mask; + for (int x = 0; x < surf->w; ++x) { + for (int y = 0; y < surf->h / 2; ++y) { + int offsrc = x * 3 + y * surf->pitch; + int offdst = x * 3 + (surf->h - 1 - y) * surf->pitch; + uint32_t *pixsrc = reinterpret_cast( + (static_cast(surf->pixels)) + offsrc + ); + uint32_t *pixdst = reinterpret_cast( + (static_cast(surf->pixels)) + offdst + ); + uint32_t tmp = *pixsrc; + *pixsrc = ((*pixsrc) & nmask) | ((*pixdst) & mask); + *pixdst = ((*pixdst) & nmask) | (tmp & mask); + } + } + return surf; } - -#endif /* NO_OPENGL */ - -#endif /* TCOD_BARE */ +#endif // TCOD_BARE diff --git a/tcod_sys/libtcod/src/libtcod/sys_sdl2_c.cpp b/tcod_sys/libtcod/src/libtcod/sys_sdl2_c.cpp index 8bb6324e6..9eb793838 100644 --- a/tcod_sys/libtcod/src/libtcod/sys_sdl2_c.cpp +++ b/tcod_sys/libtcod/src/libtcod/sys_sdl2_c.cpp @@ -1,30 +1,34 @@ -/* -* libtcod -* Copyright (c) 2008-2018 Jice & Mingos & rmtew -* All rights reserved. -* -* Redistribution and use in source and binary forms, with or without -* modification, are permitted provided that the following conditions are met: -* * Redistributions of source code must retain the above copyright -* notice, this list of conditions and the following disclaimer. -* * Redistributions in binary form must reproduce the above copyright -* notice, this list of conditions and the following disclaimer in the -* documentation and/or other materials provided with the distribution. -* * The name of Jice or Mingos may not be used to endorse or promote -* products derived from this software without specific prior written -* permission. -* -* THIS SOFTWARE IS PROVIDED BY JICE, MINGOS AND RMTEW ``AS IS'' AND ANY -* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED -* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE -* DISCLAIMED. IN NO EVENT SHALL JICE, MINGOS OR RMTEW BE LIABLE FOR ANY -* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES -* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; -* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND -* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS -* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. -*/ +/* BSD 3-Clause License + * + * Copyright © 2008-2019, Jice and the libtcod contributors. + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions are met: + * + * 1. Redistributions of source code must retain the above copyright notice, + * this list of conditions and the following disclaimer. + * + * 2. Redistributions in binary form must reproduce the above copyright notice, + * this list of conditions and the following disclaimer in the documentation + * and/or other materials provided with the distribution. + * + * 3. Neither the name of the copyright holder nor the names of its + * contributors may be used to endorse or promote products derived from + * this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE + * POSSIBILITY OF SUCH DAMAGE. + */ #ifndef TCOD_BARE #include @@ -566,6 +570,7 @@ TCOD_SDL_driver_t *SDL_implementation_factory(void) { #include "console.h" #include "libtcod_int.h" #include "utility.h" +#include "color/canvas.h" static SDL_Surface* scale_screen=NULL; static bool clear_screen=false; @@ -612,7 +617,7 @@ static void actual_rendering(void) { dstRect.w=scale_data.dst_display_width; dstRect.h=scale_data.dst_display_height; } if ( TCOD_ctx.sdl_cbk ) { - TCOD_ctx.sdl_cbk((void *)scale_screen); + TCOD_ctx.sdl_cbk(scale_screen); } texture = SDL_CreateTextureFromSurface(renderer, scale_screen); SDL_RenderCopy(renderer, texture, &srcRect, &dstRect); @@ -635,7 +640,11 @@ static struct TCOD_Console *ensure_cache(struct TCOD_Console* root) { * faults, this should only be called when it would normally be and not * specifically to force screen refreshes. To this end, and to avoid * threading complications it takes care of special cases internally. */ -static void render(TCOD_SDL_driver_t *sdl, void *vbitmap, struct TCOD_Console *console) { +static void render( + TCOD_SDL_driver_t *sdl, + void*, // vbitmap + struct TCOD_Console *console) +{ if ( TCOD_ctx.renderer == TCOD_RENDERER_SDL ) { int console_width_p = console->w * TCOD_ctx.font_width; int console_height_p = console->h * TCOD_ctx.font_height; @@ -680,17 +689,26 @@ static void render(TCOD_SDL_driver_t *sdl, void *vbitmap, struct TCOD_Console *c scale_data.surface_width = console_width_p; scale_data.surface_height = console_height_p; } - scale_data.min_scale_factor = MAX((float)console_width_p/scale_data.surface_width, (float)console_height_p/scale_data.surface_height); + scale_data.min_scale_factor = std::max( + static_cast(console_width_p) / scale_data.surface_width, + static_cast(console_height_p) / scale_data.surface_height); if (scale_data.min_scale_factor > 1.0f) scale_data.min_scale_factor = 1.0f; /*printf("min_scale_factor %0.3f = MAX(%d/%d, %d/%d)", scale_data.min_scale_factor, console_width_p, scale_data.surface_width, console_height_p, scale_data.surface_height);*/ - scale_data.dst_height_width_ratio = (float)scale_data.surface_height/scale_data.surface_width; - scale_data.src_proportionate_width = (int)(console_width_p / scale_factor); - scale_data.src_proportionate_height = (int)((console_width_p * scale_data.dst_height_width_ratio) / scale_factor); + scale_data.dst_height_width_ratio = + static_cast(scale_data.surface_height) + / scale_data.surface_width; + scale_data.src_proportionate_width = + static_cast(console_width_p / scale_factor); + scale_data.src_proportionate_height = static_cast( + (console_width_p * scale_data.dst_height_width_ratio) + / scale_factor); /* Work out how much of the console to copy. */ - scale_data.src_x0 = (int)((sdl->scale_xc * console_width_p) - (0.5f * scale_data.src_proportionate_width)); + scale_data.src_x0 = static_cast( + (sdl->scale_xc * console_width_p) + - (0.5f * scale_data.src_proportionate_width)); if (scale_data.src_x0 + scale_data.src_proportionate_width > console_width_p) scale_data.src_x0 = console_width_p - scale_data.src_proportionate_width; if (scale_data.src_x0 < 0) @@ -699,7 +717,9 @@ static void render(TCOD_SDL_driver_t *sdl, void *vbitmap, struct TCOD_Console *c if (scale_data.src_x0 + scale_data.src_copy_width > console_width_p) scale_data.src_copy_width = console_width_p - scale_data.src_x0; - scale_data.src_y0 = (int)((sdl->scale_yc * console_height_p) - (0.5f * scale_data.src_proportionate_height)); + scale_data.src_y0 = static_cast( + (sdl->scale_yc * console_height_p) + - (0.5f * scale_data.src_proportionate_height)); if (scale_data.src_y0 + scale_data.src_proportionate_height > console_height_p) scale_data.src_y0 = console_height_p - scale_data.src_proportionate_height; if (scale_data.src_y0 < 0) @@ -724,7 +744,7 @@ static void render(TCOD_SDL_driver_t *sdl, void *vbitmap, struct TCOD_Console *c TCOD_opengl_swap(); } #endif - oldFade=(int)TCOD_console_get_fade(); + oldFade = TCOD_console_get_fade(); } /* Return the current root console cache if it exists, or NULL. */ @@ -878,50 +898,30 @@ static void set_window_title(const char *title) { SDL_SetWindowTitle(window, title); } -static void save_screenshot(const char *filename) { - if ( TCOD_ctx.renderer == TCOD_RENDERER_SDL ) { - /* This would be a lot easier if image saving could do textures. */ - SDL_Rect rect; - uint32_t format; - SDL_Texture *texture; - SDL_RenderGetViewport(renderer, &rect); - format = SDL_GetWindowPixelFormat(window); - texture = SDL_CreateTexture(renderer, format, SDL_TEXTUREACCESS_TARGET, rect.w, rect.h); - if (0 != texture) { - if (SDL_SetRenderTarget(renderer, texture)) { - void *pixels; - int pitch, access; - - actual_rendering(); - SDL_SetRenderTarget(renderer, NULL); - - rect.x = rect.y = rect.w = rect.h = 0; - if (-1 != SDL_QueryTexture(texture, &format, &access, &rect.w, &rect.h) && - -1 != SDL_LockTexture(texture, NULL, &pixels, &pitch)) { - int depth; - uint32_t rmask, gmask, bmask, amask; - if (SDL_TRUE == SDL_PixelFormatEnumToMasks(format, &depth, &rmask, &gmask, &bmask, &amask)) { - SDL_Surface *surface = SDL_CreateRGBSurfaceFrom(pixels, rect.w, rect.h, depth, pitch, rmask, gmask, bmask, amask); - TCOD_sys_save_bitmap((void *)surface,filename); - SDL_FreeSurface(surface); - } else - TCOD_LOG(("TCOD_sys_save_screenshot - failed call to SDL_PixelFormatEnumToMasks")); - - SDL_UnlockTexture(texture); - } else - TCOD_LOG(("TCOD_sys_save_screenshot - failed call to SDL_QueryTexture or SDL_LockTexture")); - } else - TCOD_LOG(("TCOD_sys_save_screenshot - failed call to SDL_SetRenderTarget")); - SDL_DestroyTexture(texture); - } else - TCOD_LOG(("TCOD_sys_save_screenshot - failed call to SDL_CreateTexture")); +static void save_screenshot(const char* filename) +{ + switch (TCOD_ctx.renderer) { + case TCOD_RENDERER_SDL: { + int width, height; + SDL_GetRendererOutputSize(renderer, &width, &height); + tcod::image::Image pixels(width, height); + SDL_RenderReadPixels( + renderer, + nullptr, + SDL_PIXELFORMAT_RGBA32, + static_cast(pixels.data()), + width * 4); + tcod::image::save(pixels, filename); + break; + } #ifndef NO_OPENGL - } else { - SDL_Surface *screenshot=(SDL_Surface *)TCOD_opengl_get_screen(); - TCOD_sys_save_bitmap((void *)screenshot,filename); - SDL_FreeSurface(screenshot); + case TCOD_RENDERER_OPENGL: + SDL_Surface* screenshot = TCOD_opengl_get_screen(); + TCOD_sys_save_bitmap(screenshot, filename); + SDL_FreeSurface(screenshot); + break; #endif - } + } } /* get desktop resolution */ static void get_current_resolution(int *w, int *h) { @@ -942,10 +942,11 @@ static void get_current_resolution(int *w, int *h) { } static void set_mouse_position(int x, int y) { - SDL_WarpMouseInWindow(window, (uint16_t)x,(uint16_t)y); + SDL_WarpMouseInWindow( + window, static_cast(x), static_cast(y)); } -static char *get_clipboard_text(void) { +static const char *get_clipboard_text(void) { #ifdef TCOD_LINUX /* X11 clipboard is inaccessible without an open window. @@ -983,7 +984,7 @@ static bool set_clipboard_text(const char *text) { /* android compatible file access functions */ static bool file_read(const char *filename, unsigned char **buf, size_t *size) { - int64_t filesize; + size_t filesize; /* get file size */ SDL_RWops *rwops= SDL_RWFromFile(filename,"rb"); if (!rwops) return false; @@ -991,9 +992,9 @@ static bool file_read(const char *filename, unsigned char **buf, size_t *size) { filesize=SDL_RWtell(rwops); SDL_RWseek(rwops,0,RW_SEEK_SET); /* allocate buffer */ - *buf = (unsigned char *)malloc(sizeof(unsigned char)*filesize); + *buf = static_cast(malloc(sizeof(unsigned char) * filesize)); /* read from file */ - if (SDL_RWread(rwops,*buf,sizeof(unsigned char),filesize) != filesize) { + if (SDL_RWread(rwops, *buf, sizeof(unsigned char), filesize) != filesize) { SDL_RWclose(rwops); free(*buf); return false; @@ -1033,7 +1034,8 @@ static void shutdown_(void) { } TCOD_SDL_driver_t *SDL_implementation_factory(void) { - TCOD_SDL_driver_t *ret=(TCOD_SDL_driver_t *)calloc(1,sizeof(TCOD_SDL_driver_t)); + TCOD_SDL_driver_t *ret = + static_cast(calloc(1, sizeof(TCOD_SDL_driver_t))); ret->scale_xc = 0.5f; ret->scale_yc = 0.5f; diff --git a/tcod_sys/libtcod/src/libtcod/sys_sdl_c.cpp b/tcod_sys/libtcod/src/libtcod/sys_sdl_c.cpp index d4614d676..82f9e0ed6 100644 --- a/tcod_sys/libtcod/src/libtcod/sys_sdl_c.cpp +++ b/tcod_sys/libtcod/src/libtcod/sys_sdl_c.cpp @@ -1,34 +1,39 @@ -/* -* libtcod -* Copyright (c) 2008-2018 Jice & Mingos & rmtew -* All rights reserved. -* -* Redistribution and use in source and binary forms, with or without -* modification, are permitted provided that the following conditions are met: -* * Redistributions of source code must retain the above copyright -* notice, this list of conditions and the following disclaimer. -* * Redistributions in binary form must reproduce the above copyright -* notice, this list of conditions and the following disclaimer in the -* documentation and/or other materials provided with the distribution. -* * The name of Jice or Mingos may not be used to endorse or promote -* products derived from this software without specific prior written -* permission. -* -* THIS SOFTWARE IS PROVIDED BY JICE, MINGOS AND RMTEW ``AS IS'' AND ANY -* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED -* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE -* DISCLAIMED. IN NO EVENT SHALL JICE, MINGOS OR RMTEW BE LIABLE FOR ANY -* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES -* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; -* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND -* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS -* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. -*/ +/* BSD 3-Clause License + * + * Copyright © 2008-2019, Jice and the libtcod contributors. + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions are met: + * + * 1. Redistributions of source code must retain the above copyright notice, + * this list of conditions and the following disclaimer. + * + * 2. Redistributions in binary form must reproduce the above copyright notice, + * this list of conditions and the following disclaimer in the documentation + * and/or other materials provided with the distribution. + * + * 3. Neither the name of the copyright holder nor the names of its + * contributors may be used to endorse or promote products derived from + * this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE + * POSSIBILITY OF SUCH DAMAGE. + */ #ifndef TCOD_BARE #include "mouse.h" #include "sys.h" +#include #include #include #include @@ -38,6 +43,8 @@ #include "console.h" #include "libtcod_int.h" #include "parser.h" +#include "color/canvas.h" +#include "engine/error.h" #include "engine/globals.h" static TCOD_SDL_driver_t *sdl=NULL; @@ -45,10 +52,10 @@ static TCOD_SDL_driver_t *sdl=NULL; /* library initialization function */ #ifdef TCOD_WINDOWS -#define NOMINMAX +#define NOMINMAX 1 #include -BOOL APIENTRY DllMain( HINSTANCE hModule, DWORD reason, LPVOID reserved) { - switch (reason ) { +BOOL APIENTRY DllMain(HINSTANCE, DWORD reason, LPVOID) { + switch (reason) { case DLL_PROCESS_ATTACH : sdl = SDL_implementation_factory(); break; default : break; } @@ -85,31 +92,31 @@ typedef struct { /* image support stuff */ bool TCOD_sys_check_bmp(const char *filename); SDL_Surface *TCOD_sys_read_bmp(const char *filename); -void TCOD_sys_write_bmp(const SDL_Surface *surf, const char *filename); +void TCOD_sys_write_bmp(SDL_Surface *surf, const char *filename); bool TCOD_sys_check_png(const char *filename); SDL_Surface *TCOD_sys_read_png(const char *filename); -void TCOD_sys_write_png(const SDL_Surface *surf, const char *filename); +void TCOD_sys_write_png(SDL_Surface *surf, const char *filename); typedef struct { - char *extension; + const char *extension; bool (*check_type)(const char *filename); SDL_Surface *(*read)(const char *filename); - void (*write)(const SDL_Surface *surf, const char *filename); + void (*write)(SDL_Surface *surf, const char *filename); } image_support_t; -static image_support_t image_type[] = { +static constexpr image_support_t image_type[] = { { "BMP", TCOD_sys_check_bmp, TCOD_sys_read_bmp, TCOD_sys_write_bmp }, { "PNG", TCOD_sys_check_png, TCOD_sys_read_png, TCOD_sys_write_png }, { NULL, NULL, NULL, NULL }, }; -scale_data_t scale_data={0}; -SDL_Window* window=NULL; -SDL_Renderer* renderer=NULL; -float scale_factor=1.0f; -SDL_Surface* charmap=NULL; -char *last_clipboard_text = NULL; -static bool has_startup=false; +scale_data_t scale_data = {}; +SDL_Window* window = nullptr; +SDL_Renderer* renderer = nullptr; +float scale_factor = 1.0f; +SDL_Surface* charmap = nullptr; +char *last_clipboard_text = nullptr; +static bool has_startup = false; #define MAX_SCALE_FACTOR 5.0f /* font transparent color */ @@ -150,27 +157,63 @@ typedef struct { } vk_to_c_entry; #define NUM_VK_TO_C_ENTRIES 10 static vk_to_c_entry vk_to_c[NUM_VK_TO_C_ENTRIES]; - -/* convert ASCII code to TCOD layout position */ -static int init_ascii_to_tcod[256] = { - 0, 0, 0, 0, 0, 0, 0, 0, 0, 76, 77, 0, 0, 0, 0, 0, /* ASCII 0 to 15 */ - 71, 70, 72, 0, 0, 0, 0, 0, 64, 65, 67, 66, 0, 73, 68, 69, /* ASCII 16 to 31 */ - 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, /* ASCII 32 to 47 */ - 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, /* ASCII 48 to 63 */ - 32, 96, 97, 98, 99,100,101,102,103,104,105,106,107,108,109,110, /* ASCII 64 to 79 */ -111,112,113,114,115,116,117,118,119,120,121, 33, 34, 35, 36, 37, /* ASCII 80 to 95 */ - 38,128,129,130,131,132,133,134,135,136,137,138,139,140,141,142, /* ASCII 96 to 111 */ -143,144,145,146,147,148,149,150,151,152,153, 39, 40, 41, 42, 0, /* ASCII 112 to 127 */ - 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* ASCII 128 to 143 */ - 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* ASCII 144 to 159 */ - 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* ASCII 160 to 175 */ - 43, 44, 45, 46, 49, 0, 0, 0, 0, 81, 78, 87, 88, 0, 0, 55, /* ASCII 176 to 191 */ - 53, 50, 52, 51, 47, 48, 0, 0, 85, 86, 82, 84, 83, 79, 80, 0, /* ASCII 192 to 207 */ - 0, 0, 0, 0, 0, 0, 0, 0, 0, 56, 54, 0, 0, 0, 0, 0, /* ASCII 208 to 223 */ - 74, 75, 57, 58, 59, 60, 61, 62, 63, 0, 0, 0, 0, 0, 0, 0, /* ASCII 224 to 239 */ - 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* ASCII 240 to 255 */ +/** + * Codec for TCOD_FONT_LAYOUT_TCOD. + * + * Converts from EASCII code-point -> raw tile position. + */ +constexpr std::array tcod_codec_{ + 0, 0, 0, 0, 0, 0, 0, 0, 0, 76, 77, 0, 0, 0, 0, 0, /* 0 to 15 */ + 71, 70, 72, 0, 0, 0, 0, 0, 64, 65, 67, 66, 0, 73, 68, 69, /* 16 to 31 */ + 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, /* 32 to 47 */ + 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, /* 48 to 63 */ + 32, 96, 97, 98, 99,100,101,102,103,104,105,106,107,108,109,110, /* 64 to 79 */ +111,112,113,114,115,116,117,118,119,120,121, 33, 34, 35, 36, 37, /* 80 to 95 */ + 38,128,129,130,131,132,133,134,135,136,137,138,139,140,141,142, /* 96 to 111 */ +143,144,145,146,147,148,149,150,151,152,153, 39, 40, 41, 42, 0, /* 112 to 127 */ + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* 128 to 143 */ + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* 144 to 159 */ + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* 160 to 175 */ + 43, 44, 45, 46, 49, 0, 0, 0, 0, 81, 78, 87, 88, 0, 0, 55, /* 176 to 191 */ + 53, 50, 52, 51, 47, 48, 0, 0, 85, 86, 82, 84, 83, 79, 80, 0, /* 192 to 207 */ + 0, 0, 0, 0, 0, 0, 0, 0, 0, 56, 54, 0, 0, 0, 0, 0, /* 208 to 223 */ + 74, 75, 57, 58, 59, 60, 61, 62, 63, 0, 0, 0, 0, 0, 0, 0, /* 224 to 239 */ + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* 240 to 255 */ +}; +constexpr std::array cp437_codec_{ +0x0000, 0x263A, 0x263B, 0x2665, 0x2666, 0x2663, 0x2660, 0x2022, +0x25D8, 0x25CB, 0x25D9, 0x2642, 0x2640, 0x266A, 0x266B, 0x263C, +0x25BA, 0x25C4, 0x2195, 0x203C, 0x00B6, 0x00A7, 0x25AC, 0x21A8, +0x2191, 0x2193, 0x2192, 0x2190, 0x221F, 0x2194, 0x25B2, 0x25BC, +0x0020, 0x0021, 0x0022, 0x0023, 0x0024, 0x0025, 0x0026, 0x0027, +0x0028, 0x0029, 0x002A, 0x002B, 0x002C, 0x002D, 0x002E, 0x002F, +0x0030, 0x0031, 0x0032, 0x0033, 0x0034, 0x0035, 0x0036, 0x0037, +0x0038, 0x0039, 0x003A, 0x003B, 0x003C, 0x003D, 0x003E, 0x003F, +0x0040, 0x0041, 0x0042, 0x0043, 0x0044, 0x0045, 0x0046, 0x0047, +0x0048, 0x0049, 0x004A, 0x004B, 0x004C, 0x004D, 0x004E, 0x004F, +0x0050, 0x0051, 0x0052, 0x0053, 0x0054, 0x0055, 0x0056, 0x0057, +0x0058, 0x0059, 0x005A, 0x005B, 0x005C, 0x005D, 0x005E, 0x005F, +0x0060, 0x0061, 0x0062, 0x0063, 0x0064, 0x0065, 0x0066, 0x0067, +0x0068, 0x0069, 0x006A, 0x006B, 0x006C, 0x006D, 0x006E, 0x006F, +0x0070, 0x0071, 0x0072, 0x0073, 0x0074, 0x0075, 0x0076, 0x0077, +0x0078, 0x0079, 0x007A, 0x007B, 0x007C, 0x007D, 0x007E, 0x007F, +0x00C7, 0x00FC, 0x00E9, 0x00E2, 0x00E4, 0x00E0, 0x00E5, 0x00E7, +0x00EA, 0x00EB, 0x00E8, 0x00EF, 0x00EE, 0x00EC, 0x00C4, 0x00C5, +0x00C9, 0x00E6, 0x00C6, 0x00F4, 0x00F6, 0x00F2, 0x00FB, 0x00F9, +0x00FF, 0x00D6, 0x00DC, 0x00A2, 0x00A3, 0x00A5, 0x20A7, 0x0192, +0x00E1, 0x00ED, 0x00F3, 0x00FA, 0x00F1, 0x00D1, 0x00AA, 0x00BA, +0x00BF, 0x2310, 0x00AC, 0x00BD, 0x00BC, 0x00A1, 0x00AB, 0x00BB, +0x2591, 0x2592, 0x2593, 0x2502, 0x2524, 0x2561, 0x2562, 0x2556, +0x2555, 0x2563, 0x2551, 0x2557, 0x255D, 0x255C, 0x255B, 0x2510, +0x2514, 0x2534, 0x252C, 0x251C, 0x2500, 0x253C, 0x255E, 0x255F, +0x255A, 0x2554, 0x2569, 0x2566, 0x2560, 0x2550, 0x256C, 0x2567, +0x2568, 0x2564, 0x2565, 0x2559, 0x2558, 0x2552, 0x2553, 0x256B, +0x256A, 0x2518, 0x250C, 0x2588, 0x2584, 0x258C, 0x2590, 0x2580, +0x03B1, 0x00DF, 0x0393, 0x03C0, 0x03A3, 0x03C3, 0x00B5, 0x03C4, +0x03A6, 0x0398, 0x03A9, 0x03B4, 0x221E, 0x03C6, 0x03B5, 0x2229, +0x2261, 0x00B1, 0x2265, 0x2264, 0x2320, 0x2321, 0x00F7, 0x2248, +0x00B0, 0x2219, 0x00B7, 0x221A, 0x207F, 0x00B2, 0x25A0, 0x00A0, }; - static void alloc_ascii_tables(void) { if ( TCOD_ctx.ascii_to_tcod ) free(TCOD_ctx.ascii_to_tcod); if ( charcols ) { @@ -178,10 +221,12 @@ static void alloc_ascii_tables(void) { free(first_draw); } - TCOD_ctx.ascii_to_tcod = (int *)calloc(sizeof(int),TCOD_ctx.max_font_chars); - charcols = (TCOD_color_t *)calloc(sizeof(TCOD_color_t),TCOD_ctx.max_font_chars); - first_draw =(bool *)calloc(sizeof(bool),TCOD_ctx.max_font_chars); - memcpy(TCOD_ctx.ascii_to_tcod,init_ascii_to_tcod,sizeof(int)*256); + TCOD_ctx.ascii_to_tcod = + static_cast(calloc(sizeof(int),TCOD_ctx.max_font_chars)); + charcols = static_cast(calloc(sizeof(TCOD_color_t), + TCOD_ctx.max_font_chars)); + first_draw = + static_cast(calloc(sizeof(bool), TCOD_ctx.max_font_chars)); } /** Reallocate the TCOD_ctx.ascii_to_tcod array, usually to make it bigger. */ @@ -219,7 +264,8 @@ void TCOD_sys_map_ascii_to_font(int asciiCode, int fontCharX, int fontCharY) { auto tilesheet = tcod::engine::get_tilesheet(); if (tileset && tilesheet) { try { - tileset->set_tile(asciiCode, tilesheet->get_tile(fontCharX, fontCharY)); + int tile_id = fontCharX + fontCharY * tilesheet->get_columns(); + tileset->set_tile(asciiCode, tilesheet->get_tile(tile_id)); } catch (const std::runtime_error&) { // Ignore errors and continue. } catch (const std::logic_error&) { } @@ -227,30 +273,50 @@ void TCOD_sys_map_ascii_to_font(int asciiCode, int fontCharX, int fontCharY) { // Assign to legacy character table. if (asciiCode >= TCOD_ctx.max_font_chars) { /* reduce total allocations by resizing in increments of 256 */ - if (realloc_ascii_tables((asciiCode & 0xff) + 1)) { + if (realloc_ascii_tables((asciiCode | 0xff) + 1)) { return; /* Failed to realloc table (old table pointer is still good) */ } } TCOD_ctx.ascii_to_tcod[asciiCode] = fontCharX + fontCharY * TCOD_ctx.fontNbCharHoriz; } +/** + * Set a code-point to point to an already existing code-point. + */ +static void TCOD_sys_map_clone_(int new_codepoint, int old_codepoint) { + if (old_codepoint < 0) { return; } + if (old_codepoint >= TCOD_ctx.max_font_chars) { return; } + TCOD_sys_map_ascii_to_font( + new_codepoint, TCOD_ctx.ascii_to_tcod[old_codepoint], 0); +} -void TCOD_sys_load_font(void) { +static int TCOD_sys_load_font(void) { int i; bool hasTransparent=false; int x,y; - if ( charmap ) SDL_FreeSurface(charmap); - charmap=static_cast(TCOD_sys_load_image(TCOD_ctx.font_file)); - if (charmap == NULL ) TCOD_fatal("SDL : cannot load %s",TCOD_ctx.font_file); - if ( (float)(charmap->w / TCOD_ctx.fontNbCharHoriz) != charmap->w / TCOD_ctx.fontNbCharHoriz - || (float)(charmap->h / TCOD_ctx.fontNbCharVertic) != charmap->h / TCOD_ctx.fontNbCharVertic ) TCOD_fatal(" %s size is not a multiple of font layout (%dx%d)\n", - TCOD_ctx.font_file,TCOD_ctx.fontNbCharHoriz,TCOD_ctx.fontNbCharVertic); + if (charmap) { SDL_FreeSurface(charmap); } + charmap = TCOD_sys_load_image(TCOD_ctx.font_file); + if (charmap == NULL) { + return tcod::set_errorf("SDL : cannot load %s", TCOD_ctx.font_file); + } + if ((static_cast(charmap->w / TCOD_ctx.fontNbCharHoriz) + != charmap->w / TCOD_ctx.fontNbCharHoriz) + || (static_cast(charmap->h / TCOD_ctx.fontNbCharVertic) + != charmap->h / TCOD_ctx.fontNbCharVertic)) { + return tcod::set_errorf( + " %s size is not a multiple of font layout (%dx%d)\n", + TCOD_ctx.font_file, + TCOD_ctx.fontNbCharHoriz, + TCOD_ctx.fontNbCharVertic); + } TCOD_ctx.font_width=charmap->w/TCOD_ctx.fontNbCharHoriz; TCOD_ctx.font_height=charmap->h/TCOD_ctx.fontNbCharVertic; /* allocated bool array for colored flags */ if ( TCOD_ctx.colored ) free(TCOD_ctx.colored); - TCOD_ctx.colored=(bool *)calloc(sizeof(bool), TCOD_ctx.fontNbCharHoriz*TCOD_ctx.fontNbCharVertic); + TCOD_ctx.colored = static_cast( + calloc(sizeof(bool), + TCOD_ctx.fontNbCharHoriz * TCOD_ctx.fontNbCharVertic)); check_ascii_to_tcod(); /* figure out what kind of font we have */ /* check if the alpha layer is actually used */ @@ -258,7 +324,8 @@ void TCOD_sys_load_font(void) { TCOD_LOG(("32bits font... checking for alpha layer... ")); for (x=0; !hasTransparent && x < charmap->w; x ++ ) { for (y=0;!hasTransparent && y < charmap->h; y++ ) { - uint8_t*pixel=(uint8_t*)(charmap->pixels) + y * charmap->pitch + x * charmap->format->BytesPerPixel; + uint8_t* pixel = static_cast(charmap->pixels) + + y * charmap->pitch + x * charmap->format->BytesPerPixel; uint8_t alpha=*((pixel)+charmap->format->Ashift/8); if ( alpha < 255 ) { hasTransparent=true; @@ -270,7 +337,7 @@ void TCOD_sys_load_font(void) { /* convert to 24 bits */ SDL_Surface *temp; TCOD_LOG(("font bpp < 24. converting to 24bits\n")); - temp=(SDL_Surface *)TCOD_sys_get_surface(charmap->w,charmap->h,false); + temp = TCOD_sys_get_surface(charmap->w, charmap->h, false); SDL_BlitSurface(charmap,NULL,temp,NULL); SDL_FreeSurface(charmap); charmap=temp; @@ -286,13 +353,18 @@ void TCOD_sys_load_font(void) { keyx = TCOD_ctx.font_width/2; keyy = TCOD_ctx.font_height/2; } else if (TCOD_ctx.font_in_row) { - keyx = ((int)(' ') % TCOD_ctx.fontNbCharHoriz ) * TCOD_ctx.font_width + TCOD_ctx.font_width/2; - keyy = ((int)(' ') / TCOD_ctx.fontNbCharHoriz ) * TCOD_ctx.font_height + TCOD_ctx.font_height/2; + keyx = (static_cast(' ') % TCOD_ctx.fontNbCharHoriz) + * TCOD_ctx.font_width + TCOD_ctx.font_width / 2; + keyy = (static_cast(' ') / TCOD_ctx.fontNbCharHoriz) + * TCOD_ctx.font_height + TCOD_ctx.font_height / 2; } else { - keyx = ((int)(' ') / TCOD_ctx.fontNbCharVertic ) * TCOD_ctx.font_width + TCOD_ctx.font_width/2; - keyy = ((int)(' ') % TCOD_ctx.fontNbCharVertic ) * TCOD_ctx.font_height + TCOD_ctx.font_height/2; + keyx = (static_cast(' ') / TCOD_ctx.fontNbCharVertic) + * TCOD_ctx.font_width + TCOD_ctx.font_width / 2; + keyy = (static_cast(' ') % TCOD_ctx.fontNbCharVertic) + * TCOD_ctx.font_height + TCOD_ctx.font_height / 2; } - pixel=(uint8_t*)(charmap->pixels) + keyy * charmap->pitch + keyx * charmap->format->BytesPerPixel; + pixel = static_cast(charmap->pixels) + + keyy * charmap->pitch + keyx * charmap->format->BytesPerPixel; fontKeyCol.r=*((pixel)+charmap->format->Rshift/8); fontKeyCol.g=*((pixel)+charmap->format->Gshift/8); fontKeyCol.b=*((pixel)+charmap->format->Bshift/8); @@ -301,7 +373,7 @@ void TCOD_sys_load_font(void) { /* 32 bits font but alpha layer not used. convert to 24 bits (faster) */ SDL_Surface *temp; TCOD_LOG(("32bits font with no alpha => converting to faster 24 bits\n")); - temp=(SDL_Surface *)TCOD_sys_get_surface(charmap->w,charmap->h,false); + temp = TCOD_sys_get_surface(charmap->w, charmap->h, false); SDL_BlitSurface(charmap,NULL,temp,NULL); SDL_FreeSurface(charmap); charmap=temp; @@ -315,8 +387,10 @@ void TCOD_sys_load_font(void) { cy=(i/TCOD_ctx.fontNbCharHoriz); for( px=0; !end && px < TCOD_ctx.font_width; px++ ) { for (py=0; !end && py < TCOD_ctx.font_height; py++ ) { - uint8_t*pixel=(uint8_t*)(charmap->pixels) + (cy*TCOD_ctx.font_height+py) * charmap->pitch - + (cx*TCOD_ctx.font_width+px) * charmap->format->BytesPerPixel; + uint8_t*pixel=static_cast(charmap->pixels) + + (cy * TCOD_ctx.font_height + py) * charmap->pitch + + (cx * TCOD_ctx.font_width + px) + * charmap->format->BytesPerPixel; uint8_t r=*((pixel)+charmap->format->Rshift/8); uint8_t g=*((pixel)+charmap->format->Gshift/8); uint8_t b=*((pixel)+charmap->format->Bshift/8); @@ -340,7 +414,7 @@ void TCOD_sys_load_font(void) { if ( charmap->format->BytesPerPixel != 4 ) { SDL_Surface *temp; TCOD_LOG(("24bits greyscale font. converting to 32bits\n")); - temp=(SDL_Surface *)TCOD_sys_get_surface(charmap->w,charmap->h,true); + temp = TCOD_sys_get_surface(charmap->w, charmap->h, true); SDL_BlitSurface(charmap,NULL,temp,NULL); SDL_FreeSurface(charmap); charmap=temp; @@ -353,14 +427,16 @@ void TCOD_sys_load_font(void) { for (x=cx*TCOD_ctx.font_width; x < (cx+1)*TCOD_ctx.font_width; x ++ ) { for (y=cy*TCOD_ctx.font_height;y < (cy+1)*TCOD_ctx.font_height; y++ ) { if ( ! TCOD_ctx.colored[i]) { - uint8_t*pixel=(uint8_t*)(charmap->pixels) + y * charmap->pitch + x * charmap->format->BytesPerPixel; + uint8_t* pixel = static_cast(charmap->pixels) + + y * charmap->pitch + x * charmap->format->BytesPerPixel; uint8_t r=*((pixel)+charmap->format->Rshift/8); *((pixel)+charmap->format->Ashift/8) = (invert ? 255-r : r); *((pixel)+charmap->format->Rshift/8)=255; *((pixel)+charmap->format->Gshift/8)=255; *((pixel)+charmap->format->Bshift/8)=255; } else { - uint8_t*pixel=(uint8_t*)(charmap->pixels) + y * charmap->pitch + x * charmap->format->BytesPerPixel; + uint8_t* pixel = static_cast(charmap->pixels) + + y * charmap->pitch + x * charmap->format->BytesPerPixel; uint8_t r=*((pixel)+charmap->format->Rshift/8); uint8_t g=*((pixel)+charmap->format->Gshift/8); uint8_t b=*((pixel)+charmap->format->Bshift/8); @@ -384,23 +460,57 @@ void TCOD_sys_load_font(void) { first_draw[i]=true; } check_ascii_to_tcod(); - if (!TCOD_ctx.font_tcod_layout) { - /* apply standard ascii mapping */ - if ( TCOD_ctx.font_in_row ) { - /* for font in row */ - for (i=0; i < TCOD_ctx.max_font_chars; i++ ) TCOD_ctx.ascii_to_tcod[i]=i; - } else { - /* for font in column */ - for (i=0; i < TCOD_ctx.max_font_chars; i++ ) { - int fy = i % TCOD_ctx.fontNbCharVertic; - int fx = i / TCOD_ctx.fontNbCharVertic; - TCOD_ctx.ascii_to_tcod[i]=fx + fy * TCOD_ctx.fontNbCharHoriz; - } - } - } + TCOD_sys_decode_font_(); + return 0; } - -void TCOD_sys_set_custom_font(const char *fontFile,int nb_ch, int nb_cv, int flags) { +/** + * Decode the font layout depending on the current flags. + */ +void TCOD_sys_decode_font_(void) +{ + if (TCOD_ctx.font_flags & TCOD_FONT_LAYOUT_CP437) { + for (int i = 0; i < static_cast(cp437_codec_.size()); ++i) { + TCOD_sys_map_ascii_to_font(cp437_codec_.at(i), i, 0); + } + } else if (TCOD_ctx.font_tcod_layout) { + for (int i = 0; i < static_cast(tcod_codec_.size()); ++i) { + TCOD_sys_map_ascii_to_font(i, tcod_codec_.at(i), 0); + } + TCOD_sys_map_clone_(0x2500, TCOD_CHAR_HLINE); + TCOD_sys_map_clone_(0x2502, TCOD_CHAR_VLINE); + TCOD_sys_map_clone_(0x250C, TCOD_CHAR_NW); + TCOD_sys_map_clone_(0x2510, TCOD_CHAR_NE); + TCOD_sys_map_clone_(0x2514, TCOD_CHAR_SW); + TCOD_sys_map_clone_(0x2518, TCOD_CHAR_SE); + } else { + if (TCOD_ctx.font_in_row) { + /* for font in row */ + for (int i = 0; i < TCOD_ctx.max_font_chars; ++i) { + TCOD_sys_map_ascii_to_font(i, i, 0); + } + } else { + /* for font in column */ + for (int i = 0; i < TCOD_ctx.max_font_chars; ++i) { + int fy = i % TCOD_ctx.fontNbCharVertic; + int fx = i / TCOD_ctx.fontNbCharVertic; + TCOD_sys_map_ascii_to_font(i, fx, fy); + } + } + TCOD_sys_map_clone_(0x2500, 0xC4); + TCOD_sys_map_clone_(0x2502, 0xB3); + TCOD_sys_map_clone_(0x250C, 0xDA); + TCOD_sys_map_clone_(0x2510, 0xBF); + TCOD_sys_map_clone_(0x2514, 0xC0); + TCOD_sys_map_clone_(0x2518, 0xD9); + } +} +/** + * This function used to handle more stuff, now it only initializes the + * legacy font system. + * + * See TCOD_console_set_custom_font. + */ +void TCOD_sys_set_custom_font(const char*, int, int, int) { check_ascii_to_tcod(); } @@ -410,11 +520,10 @@ void find_resolution(void) { sdl->get_closest_mode(&TCOD_ctx.actual_fullscreen_width,&TCOD_ctx.actual_fullscreen_height); } -void *TCOD_sys_create_bitmap_for_console(TCOD_console_t console) { - int w,h; - w = TCOD_console_get_width(console) * TCOD_ctx.font_width; - h = TCOD_console_get_height(console) * TCOD_ctx.font_height; - return TCOD_sys_get_surface(w,h,false); +SDL_Surface* TCOD_sys_create_bitmap_for_console(TCOD_Console* console) { + int w = TCOD_console_get_width(console) * TCOD_ctx.font_width; + int h = TCOD_console_get_height(console) * TCOD_ctx.font_height; + return TCOD_sys_get_surface(w, h, false); } static void TCOD_sys_render(void *vbitmap, struct TCOD_Console* console) { @@ -423,253 +532,252 @@ static void TCOD_sys_render(void *vbitmap, struct TCOD_Console* console) { } } -void TCOD_sys_console_to_bitmap(void *vbitmap, - struct TCOD_Console* console, struct TCOD_Console* cache) { - static SDL_Surface *charmap_backup=NULL; - SDL_Surface *bitmap = (SDL_Surface *)vbitmap; - int x,y; - uint32_t sdl_back=0, sdl_fore=0; - TCOD_color_t fading_color = TCOD_console_get_fading_color(); - int fade = (int)TCOD_console_get_fade(); - /* can only track changes on the root console */ - bool track_changes = (cache && oldFade == fade); - uint8_t bpp = charmap->format->BytesPerPixel; - int *c = console->ch_array; - int *oc; - TCOD_color_t *ofg, *obg, *nfg, *nbg; - int hdelta; - if ( bpp == 4 ) { - hdelta=(charmap->pitch - TCOD_ctx.font_width*bpp)/4; - } else { - hdelta=(charmap->pitch - TCOD_ctx.font_width*bpp); - } - nfg = console->fg_array; - nbg = console->bg_array; - if (track_changes) { - oc = cache->ch_array; - ofg = cache->fg_array; - obg = cache->bg_array; - } - if ( charmap_backup == NULL ) { - charmap_backup=(SDL_Surface *)TCOD_sys_get_surface(charmap->w,charmap->h,true); - SDL_BlitSurface(charmap,NULL,charmap_backup,NULL); - } -#ifdef USE_SDL_LOCKS - if ( SDL_MUSTLOCK( bitmap ) && SDL_LockSurface( bitmap ) < 0 ) return; -#endif - for (y = 0; y < console->h; y++) { - for (x = 0; x < console->w; x++) { - SDL_Rect srcRect,dstRect; - bool changed=true; - if ( track_changes ) { - changed=false; - if ( - nbg->r != obg->r || nbg->g != obg->g || nbg->b != obg->b || - nfg->r != ofg->r || nfg->g != ofg->g || nfg->b != ofg->b || - *c != *oc) { - changed=true; - } - } - if ( changed ) { - TCOD_color_t b=*nbg; - dstRect.x=x*TCOD_ctx.font_width; - dstRect.y=y*TCOD_ctx.font_height; - dstRect.w=TCOD_ctx.font_width; - dstRect.h=TCOD_ctx.font_height; - /* draw background */ - if ( fade != 255 ) { - b.r = ((int)b.r) * fade / 255 + ((int)fading_color.r) * (255-fade)/255; - b.g = ((int)b.g) * fade / 255 + ((int)fading_color.g) * (255-fade)/255; - b.b = ((int)b.b) * fade / 255 + ((int)fading_color.b) * (255-fade)/255; - } - sdl_back=SDL_MapRGB(bitmap->format,b.r,b.g,b.b); - SDL_FillRect(bitmap,&dstRect,sdl_back); - if ( *c != ' ' ) { - /* draw foreground */ - int ascii = TCOD_get_tileid_for_charcode_(*c); - TCOD_color_t *curtext = &charcols[ascii]; - bool first = first_draw[ascii]; - TCOD_color_t f=*nfg; - - if ( fade != 255 ) { - f.r = ((int)f.r) * fade / 255 + ((int)fading_color.r) * (255-fade)/255; - f.g = ((int)f.g) * fade / 255 + ((int)fading_color.g) * (255-fade)/255; - f.b = ((int)f.b) * fade / 255 + ((int)fading_color.b) * (255-fade)/255; - } - /* only draw character if foreground color != background color */ - if ( f.r != b.r || f.g != b.g || f.b != b.b ) { - if ( charmap->format->Amask == 0 - && f.r == fontKeyCol.r && f.g == fontKeyCol.g && f.b == fontKeyCol.b ) { - /* cannot draw with the key color... */ - if ( f.r < 255 ) f.r++; else f.r--; - } - srcRect.x = (ascii%TCOD_ctx.fontNbCharHoriz)*TCOD_ctx.font_width; - srcRect.y = (ascii/TCOD_ctx.fontNbCharHoriz)*TCOD_ctx.font_height; - srcRect.w=TCOD_ctx.font_width; - srcRect.h=TCOD_ctx.font_height; - - if ( charmap && (first || curtext->r != f.r || curtext->g != f.g || curtext->b!=f.b) ) { - /* change the character color in the font */ - first_draw[ascii]=false; - sdl_fore=SDL_MapRGB(charmap->format,f.r,f.g,f.b) & rgb_mask; - *curtext=f; -#ifdef USE_SDL_LOCKS - if ( SDL_MUSTLOCK(charmap) ) { - if ( SDL_LockSurface(charmap) < 0 ) return; - } -#endif - if ( bpp == 4 ) { - /* 32 bits font : fill the whole character with foreground color */ - uint32_t *pix = (uint32_t *)(((uint8_t*)charmap->pixels)+srcRect.x*bpp + srcRect.y*charmap->pitch); - int h=TCOD_ctx.font_height; - if ( ! TCOD_ctx.colored[ascii] ) { - while ( h-- ) { - int w=TCOD_ctx.font_width; - while ( w-- ) { - (*pix) &= nrgb_mask; - (*pix) |= sdl_fore; - pix++; - } - pix += hdelta; - } - } else { - /* colored character : multiply color with foreground color */ - uint32_t *pixorig = (uint32_t *)(((uint8_t*)charmap_backup->pixels)+srcRect.x*bpp + srcRect.y*charmap_backup->pitch); - int hdelta_backup=(charmap_backup->pitch - TCOD_ctx.font_width*4)/4; - while (h> 0) { - int w=TCOD_ctx.font_width; - while ( w > 0 ) { - int r=(int)(*((uint8_t*)(pixorig)+charmap_backup->format->Rshift/8)); - int g=(int)(*((uint8_t*)(pixorig)+charmap_backup->format->Gshift/8)); - int b=(int)(*((uint8_t*)(pixorig)+charmap_backup->format->Bshift/8)); - (*pix) &= nrgb_mask; /* erase the color */ - r = r * f.r / 255; - g = g * f.g / 255; - b = b * f.b / 255; - /* set the new color */ - (*pix) |= (r<format->Rshift)|(g<format->Gshift)|(b<format->Bshift); - w--; - pix++; - pixorig++; - } - h--; - pix += hdelta; - pixorig += hdelta_backup; - } - } - } else { - /* 24 bits font : fill only non key color pixels */ - uint32_t *pix = (uint32_t *)(((uint8_t*)charmap->pixels)+srcRect.x*bpp + srcRect.y*charmap->pitch); - int h=TCOD_ctx.font_height; - if ( ! TCOD_ctx.colored[ascii] ) { - while ( h-- ) { - int w=TCOD_ctx.font_width; - while ( w-- ) { - if (((*pix) & rgb_mask) != sdl_key ) { - (*pix) &= nrgb_mask; - (*pix) |= sdl_fore; - } - pix = (uint32_t *) (((uint8_t*)pix)+3); - } - pix = (uint32_t *) (((uint8_t*)pix)+hdelta); - } - } else { - /* colored character : multiply color with foreground color */ - uint32_t *pixorig = (uint32_t *)(((uint8_t*)charmap_backup->pixels)+srcRect.x*4 + srcRect.y*charmap_backup->pitch); - /* charmap_backup is always 32 bits */ - int hdelta_backup=(charmap_backup->pitch - TCOD_ctx.font_width*4)/4; - while (h> 0) { - int w=TCOD_ctx.font_width; - while ( w > 0 ) { - if (((*pixorig) & rgb_mask) != sdl_key ) { - int r=(int)(*((uint8_t*)(pixorig)+charmap_backup->format->Rshift/8)); - int g=(int)(*((uint8_t*)(pixorig)+charmap_backup->format->Gshift/8)); - int b=(int)(*((uint8_t*)(pixorig)+charmap_backup->format->Bshift/8)); - (*pix) &= nrgb_mask; /* erase the color */ - r = r * f.r / 255; - g = g * f.g / 255; - b = b * f.b / 255; - /* set the new color */ - (*pix) |= (r<format->Rshift)|(g<format->Gshift)|(b<format->Bshift); - } - w--; - pix = (uint32_t *) (((uint8_t*)pix)+3); - pixorig ++; - } - h--; - pix = (uint32_t *) (((uint8_t*)pix)+hdelta); - pixorig += hdelta_backup; - } - } - } -#ifdef USE_SDL_LOCKS - if ( SDL_MUSTLOCK(charmap) ) { - SDL_UnlockSurface(charmap); - } -#endif - } - SDL_BlitSurface(charmap,&srcRect,bitmap,&dstRect); - } - } - } - c++; - nfg++; - nbg++; - if (track_changes) { - oc++; - ofg++; - obg++; - } - } - } +static TCOD_color_t blend_fade_color_( + const TCOD_color_t& color, + const TCOD_color_t& fade_color, + uint8_t fade_value) +{ + if (fade_value != 255) { return color; } + return { + static_cast( + static_cast(color.r) * fade_value / 255 + + static_cast(fade_color.r) * (255 - fade_value) / 255), + static_cast( + static_cast(color.g) * fade_value / 255 + + static_cast(fade_color.g) * (255 - fade_value) / 255), + static_cast( + static_cast(color.b) * fade_value / 255 + + static_cast(fade_color.b) * (255 - fade_value) / 255), + }; +} + +void TCOD_sys_console_to_bitmap( + SDL_Surface* vbitmap, + struct TCOD_Console* console, + struct TCOD_Console* cache) +{ + static SDL_Surface* charmap_backup = NULL; + SDL_Surface *bitmap = vbitmap; + uint32_t sdl_back = 0; + uint32_t sdl_fore = 0; + TCOD_color_t fading_color = TCOD_console_get_fading_color(); + int fade = TCOD_console_get_fade(); + /* can only track changes on the root console */ + bool track_changes = (cache && oldFade == fade); + uint8_t bpp = charmap->format->BytesPerPixel; + int hdelta; + if (bpp == 4) { + hdelta = (charmap->pitch - TCOD_ctx.font_width * bpp) / 4; + } else { + hdelta = (charmap->pitch - TCOD_ctx.font_width * bpp); + } + if (charmap_backup == NULL) { + charmap_backup = TCOD_sys_get_surface(charmap->w, charmap->h, true); + SDL_BlitSurface(charmap, NULL, charmap_backup, NULL); + } + for (int y = 0; y < console->h; ++y) { + for (int x = 0; x < console->w; ++x) { + using tcod::console::Tile; + int console_i = y * console->w + x; + const Tile& current = console->tiles[console_i]; + const int& c = current.ch; + const TCOD_ColorRGBA& nfg = current.fg; + const TCOD_ColorRGBA& nbg = current.bg; + SDL_Rect srcRect, dstRect; + if (track_changes) { + Tile& old = cache->tiles[console_i]; + if (current == old) { + continue; + } + old = current; + } + TCOD_ColorRGB b = tcod::ColorRGB(nbg); + dstRect.x = x * TCOD_ctx.font_width; + dstRect.y = y * TCOD_ctx.font_height; + dstRect.w = TCOD_ctx.font_width; + dstRect.h = TCOD_ctx.font_height; + /* draw background */ + b = blend_fade_color_(b, fading_color, fade); + sdl_back = SDL_MapRGB(bitmap->format, b.r, b.g, b.b); + SDL_FillRect(bitmap, &dstRect, sdl_back); + if (c != ' ') { + /* draw foreground */ + int ascii = TCOD_get_tileid_for_charcode_(c); + TCOD_ColorRGB *curtext = &charcols[ascii]; + bool first = first_draw[ascii]; + TCOD_ColorRGB f = tcod::ColorRGB(nfg); + f = blend_fade_color_(f, fading_color, fade); + /* only draw character if foreground color != background color */ + if (f != b) { + if (charmap->format->Amask == 0 && f == fontKeyCol) { + /* cannot draw with the key color... */ + if (f.r < 255) { f.r++; } else { f.r--; } + } + srcRect.x = (ascii % TCOD_ctx.fontNbCharHoriz) + * TCOD_ctx.font_width; + srcRect.y = (ascii / TCOD_ctx.fontNbCharHoriz) + * TCOD_ctx.font_height; + srcRect.w = TCOD_ctx.font_width; + srcRect.h = TCOD_ctx.font_height; + + if (charmap && (first || *curtext != f)) { + /* change the character color in the font */ + first_draw[ascii] = false; + sdl_fore = SDL_MapRGB(charmap->format, f.r, f.g, f.b) & rgb_mask; + *curtext = f; + if (bpp == 4) { + /* 32 bits font : fill the whole character with foreground color */ + uint32_t *pix = reinterpret_cast( + reinterpret_cast(charmap->pixels) + srcRect.x * bpp + + srcRect.y * charmap->pitch); + int h = TCOD_ctx.font_height; + if (!TCOD_ctx.colored[ascii]) { + while (h--) { + int w = TCOD_ctx.font_width; + while (w--) { + (*pix) &= nrgb_mask; + (*pix) |= sdl_fore; + ++pix; + } + pix += hdelta; + } + } else { + /* colored character : multiply color with foreground color */ + uint32_t *pixorig = reinterpret_cast( + reinterpret_cast(charmap_backup->pixels) + + srcRect.x * bpp + srcRect.y * charmap_backup->pitch); + int hdelta_backup = (charmap_backup->pitch + - TCOD_ctx.font_width * 4) / 4; + while (h > 0) { + int w = TCOD_ctx.font_width; + while (w > 0) { + int r_ = reinterpret_cast(pixorig)[ + charmap_backup->format->Rshift / 8]; + int g_ = reinterpret_cast(pixorig)[ + charmap_backup->format->Gshift / 8]; + int b_ = reinterpret_cast(pixorig)[ + charmap_backup->format->Bshift / 8]; + (*pix) &= nrgb_mask; /* erase the color */ + r_ = r_ * f.r / 255; + g_ = g_ * f.g / 255; + b_ = b_ * f.b / 255; + /* set the new color */ + (*pix) |= (r_ << charmap->format->Rshift) + | (g_ <format->Gshift) + | (b_ <format->Bshift); + w--; + pix++; + pixorig++; + } + h--; + pix += hdelta; + pixorig += hdelta_backup; + } + } + } else { + /* 24 bits font : fill only non key color pixels */ + uint32_t *pix = reinterpret_cast( + reinterpret_cast(charmap->pixels) + + srcRect.x*bpp + srcRect.y * charmap->pitch); + int h = TCOD_ctx.font_height; + if (!TCOD_ctx.colored[ascii]) { + while (h--) { + int w = TCOD_ctx.font_width; + while (w--) { + if (((*pix) & rgb_mask) != sdl_key ) { + (*pix) &= nrgb_mask; + (*pix) |= sdl_fore; + } + pix = reinterpret_cast( + reinterpret_cast(pix) + 3); + } + pix = reinterpret_cast( + reinterpret_cast(pix) + hdelta); + } + } else { + /* colored character : multiply color with foreground color */ + uint32_t *pixorig = reinterpret_cast( + reinterpret_cast(charmap_backup->pixels) + + srcRect.x * 4 + srcRect.y * charmap_backup->pitch); + /* charmap_backup is always 32 bits */ + int hdelta_backup = (charmap_backup->pitch + - TCOD_ctx.font_width * 4) / 4; + while (h > 0) { + int w = TCOD_ctx.font_width; + while (w > 0) { + if (((*pixorig) & rgb_mask) != sdl_key) { + int r_ = reinterpret_cast(pixorig)[ + charmap_backup->format->Rshift / 8]; + int g_ = reinterpret_cast(pixorig)[ + charmap_backup->format->Gshift / 8]; + int b_ = reinterpret_cast(pixorig)[ + charmap_backup->format->Bshift / 8]; + (*pix) &= nrgb_mask; /* erase the color */ + r_ = r_ * f.r / 255; + g_ = g_ * f.g / 255; + b_ = b_ * f.b / 255; + /* set the new color */ + (*pix) |= (r_ << charmap->format->Rshift) + | (g_ << charmap->format->Gshift) + | (b_ << charmap->format->Bshift); + } + w--; + pix = reinterpret_cast( + reinterpret_cast(pix) + 3); + pixorig++; + } + h--; + pix = reinterpret_cast( + reinterpret_cast(pix) + hdelta); + pixorig += hdelta_backup; + } + } + } + } + SDL_BlitSurface(charmap, &srcRect, bitmap, &dstRect); + } + } + } + } #ifdef USE_SDL_LOCKS - if ( SDL_MUSTLOCK( bitmap ) ) SDL_UnlockSurface( bitmap ); + if (SDL_MUSTLOCK(bitmap)) { SDL_UnlockSurface(bitmap); } #endif - if (cache) { - /* update previous values cache */ - memcpy(cache->ch_array, console->ch_array, - sizeof(console->ch_array[0]) * console->w * console->h); - memcpy(cache->fg_array, console->fg_array, - sizeof(console->fg_array[0]) * console->w * console->h); - memcpy(cache->bg_array, console->bg_array, - sizeof(console->bg_array[0]) * console->w * console->h); - } } -void *TCOD_sys_get_surface(int width, int height, bool alpha) { +SDL_Surface *TCOD_sys_get_surface(int width, int height, bool alpha) { return sdl->create_surface(width,height,alpha); } -void TCOD_sys_update_char(int asciiCode, int fontx, int fonty, TCOD_image_t img, int x, int y) { - int px,py; - int iw,ih; - static TCOD_color_t pink={255,0,255}; - TCOD_sys_map_ascii_to_font(asciiCode,fontx,fonty); - TCOD_image_get_size(img,&iw,&ih); - for (px=0; px < TCOD_ctx.font_width; px ++ ) { - for (py=0;py < TCOD_ctx.font_height; py++ ) { - TCOD_color_t col=TCOD_white; - uint8_t*pixel; - uint8_t bpp; - if ( (unsigned)(x+px) < (unsigned)iw && (unsigned)(y+py) < (unsigned)ih ) { - col=TCOD_image_get_pixel(img,x+px,y+py); - } - pixel=(uint8_t*)(charmap->pixels) + (fonty*TCOD_ctx.font_height+py) * charmap->pitch + (fontx*TCOD_ctx.font_width+px) * charmap->format->BytesPerPixel; - bpp = charmap->format->BytesPerPixel; - if (bpp == 4 ) { - *((pixel)+charmap->format->Ashift/8) = col.r; - *((pixel)+charmap->format->Rshift/8)=255; - *((pixel)+charmap->format->Gshift/8)=255; - *((pixel)+charmap->format->Bshift/8)=255; - } else { - *((pixel)+charmap->format->Rshift/8)=col.r; - *((pixel)+charmap->format->Gshift/8)=col.g; - *((pixel)+charmap->format->Bshift/8)=col.b; - } - } - } - charcols[asciiCode]=pink; - TCOD_sys_set_dirty_character_code(asciiCode); +void TCOD_sys_update_char(int asciiCode, int fontx, int fonty, + TCOD_Image* img, int x, int y) +{ + static const TCOD_color_t pink = {255, 0, 255}; + TCOD_sys_map_ascii_to_font(asciiCode, fontx, fonty); + int iw, ih; + TCOD_image_get_size(img, &iw, &ih); + for (int px = 0; px < TCOD_ctx.font_width; ++px) { + for (int py = 0; py < TCOD_ctx.font_height; ++py) { + TCOD_color_t col = TCOD_image_get_pixel(img, x + px, y + py); + uint8_t* pixel = static_cast(charmap->pixels) + + (fonty * TCOD_ctx.font_height + py) + * charmap->pitch + + (fontx * TCOD_ctx.font_width + px) + * charmap->format->BytesPerPixel; + uint8_t bpp = charmap->format->BytesPerPixel; + if (bpp == 4) { + *(pixel + charmap->format->Ashift / 8) = col.r; + *(pixel + charmap->format->Rshift / 8) = 255; + *(pixel + charmap->format->Gshift / 8) = 255; + *(pixel + charmap->format->Bshift / 8) = 255; + } else { + *(pixel + charmap->format->Rshift / 8) = col.r; + *(pixel + charmap->format->Gshift / 8) = col.g; + *(pixel + charmap->format->Bshift / 8) = col.b; + } + } + } + charcols[asciiCode] = pink; + TCOD_sys_set_dirty_character_code(asciiCode); } /** * Older startup function, mostly called from TCOD_sys_init. @@ -696,11 +804,7 @@ void TCOD_sys_startup(void) { */ void TCOD_sys_shutdown(void) { - if (TCOD_ctx.root) { - TCOD_console_data_free(TCOD_ctx.root); - free(TCOD_ctx.root); - TCOD_ctx.root = NULL; - } + TCOD_console_delete(TCOD_ctx.root); if (tcod::engine::get_display()){ tcod::engine::set_display(nullptr); return; @@ -783,7 +887,8 @@ TCOD_renderer_t TCOD_sys_get_renderer(void) { void TCOD_sys_set_renderer(TCOD_renderer_t renderer) { if ( renderer == TCOD_ctx.renderer ) return; TCOD_console_init_root(TCOD_ctx.root->w, TCOD_ctx.root->h, - TCOD_ctx.window_title, TCOD_ctx.fullscreen, renderer); + TCOD_ctx.window_title, TCOD_console_is_fullscreen(), + renderer); } void TCOD_sys_init_screen_offset(void) { @@ -803,38 +908,42 @@ bool TCOD_sys_init(struct TCOD_Console *console, bool fullscreen) { } if (last_renderer != TCOD_ctx.renderer || ! charmap || strcmp(last_font,TCOD_ctx.font_file) != 0) { /* reload the font when switching renderer to restore original character colors */ - TCOD_sys_load_font(); + if (TCOD_sys_load_font() < 0) { return false; } } sdl->create_window(console->w, console->h, fullscreen); memset(key_status,0,sizeof(bool)*(TCODK_CHAR+1)); return true; } - -static char *TCOD_strcasestr (const char *haystack, const char *needle) { - const char *p, *startn = 0, *np = 0; - - for (p = haystack; *p; p++) { - if (np) { - if (toupper(*p) == toupper(*np)) { - if (!*++np) - return (char *)startn; - } else - np = 0; - } else if (toupper(*p) == toupper(*needle)) { - np = needle + 1; - startn = p; - } - } - - return 0; +TCOD_DEPRECATED_NOMESSAGE +static char* TCOD_strcasestr(const char *haystack, const char *needle) +{ + const char *startn = NULL, *np = NULL; + for (const char* p = haystack; *p; p++) { + if (np) { + if (toupper(*p) == toupper(*np)) { + if (!*++np) { return const_cast(startn); } + } else { + np = 0; + } + } else if (toupper(*p) == toupper(*needle)) { + np = needle + 1; + startn = p; + } + } + return 0; } -void TCOD_sys_save_bitmap(void *bitmap, const char *filename) { - image_support_t *img=image_type; - while ( img->extension != NULL && TCOD_strcasestr(filename,img->extension) == NULL ) img++; - if ( img->extension == NULL || img->write == NULL ) img=image_type; /* default to bmp */ - img->write((SDL_Surface *)bitmap,filename); +void TCOD_sys_save_bitmap(SDL_Surface* bitmap, const char *filename) { + const image_support_t *img = image_type; + while (img->extension != NULL + && TCOD_strcasestr(filename,img->extension) == NULL ) { + ++img; + } + if (img->extension == NULL || img->write == NULL) { + img = image_type; // default to bmp + } + img->write(bitmap, filename); } void TCOD_sys_save_screenshot(const char *filename) { @@ -852,7 +961,12 @@ void TCOD_sys_save_screenshot(const char *filename) { fclose(access_file); } } - sdl->save_screenshot(filename); + auto display = tcod::engine::get_display(); + if (display) { + tcod::image::save(display->read_pixels(), filename); + } else { + sdl->save_screenshot(filename); + } } void TCOD_sys_set_fullscreen(bool fullscreen) { @@ -860,19 +974,20 @@ void TCOD_sys_set_fullscreen(bool fullscreen) { sdl->set_fullscreen(fullscreen); } -void TCOD_sys_set_scale_factor(float value) { - float old_scale_factor = scale_factor; - scale_factor = value; - if (scale_factor + 1e-3 < scale_data.min_scale_factor) - scale_factor = scale_data.min_scale_factor; - else if (scale_factor - 1e-3 > MAX_SCALE_FACTOR) - scale_factor = MAX_SCALE_FACTOR; - /*printf("scale_factor: %0.3f -> %0.3f (wanted: %0.3f)", old_scale_factor, scale_factor, value);*/ +void TCOD_sys_set_scale_factor(float value) +{ + scale_factor = value; + if (scale_factor + 1e-3f < scale_data.min_scale_factor) { + scale_factor = scale_data.min_scale_factor; + } else if (scale_factor - 1e-3f > MAX_SCALE_FACTOR) { + scale_factor = MAX_SCALE_FACTOR; + } } void TCOD_sys_set_window_title(const char *title) { - strcpy(TCOD_ctx.window_title,title); - sdl->set_window_title(title); + strncpy(TCOD_ctx.window_title, title, sizeof(TCOD_ctx.window_title) - 1); + TCOD_ctx.window_title[sizeof(TCOD_ctx.window_title) - 1] = '\0'; + sdl->set_window_title(title); } /** * Keep track of time and wait if the frame-rate is faster than the set FPS. @@ -1128,36 +1243,88 @@ void TCOD_sys_convert_screen_to_console_coords(int sx, int sy, int *cx, int *cy) } /** The global libtcod mouse state. */ static TCOD_mouse_t tcod_mouse={0,0,0,0,0,0,0,0,false,false,false,false,false,false,false,false}; +/** + * Convert a pixel coordinate to a tile coordinate using global state. + */ +void TCOD_sys_pixel_to_tile(double* x, double* y) +{ + if (!x || !y) { return; } + auto display = tcod::engine::get_display(); + if (display) { + std::array xy = display->pixel_to_tile({*x, *y}); + *x = std::get<0>(xy); + *y = std::get<1>(xy); + } else { + *x = (*x - TCOD_ctx.fullscreen_offsetx) / TCOD_ctx.font_width; + *y = (*y - TCOD_ctx.fullscreen_offsety) / TCOD_ctx.font_height; + } +} +/** + * Parse the coordinates and motion of an SDL event into a libtcod mouse + * struct. + */ +static void sdl_parse_mouse_(const SDL_Event& ev, TCOD_mouse_t& mouse) +{ + switch(ev.type) { + case SDL_MOUSEMOTION: + mouse.x = ev.motion.x; + mouse.y = ev.motion.y; + mouse.dx = ev.motion.xrel; + mouse.dy = ev.motion.yrel; + break; + case SDL_MOUSEWHEEL: + // Leave x,y attributes as is to preserve the original libtcod behaviour. + mouse.wheel_up = ev.wheel.y > 0; + mouse.wheel_down = ev.wheel.y < 0; + mouse.dx = mouse.dy = 0; + break; + case SDL_MOUSEBUTTONDOWN: + case SDL_MOUSEBUTTONUP: + mouse.x = ev.button.x; + mouse.y = ev.button.y; + mouse.dx = mouse.dy = 0; + break; + default: return; + } + auto display = tcod::engine::get_display(); + if (display) { + auto to_tile = [&](double x, double y) -> std::array { + std::array result(display->pixel_to_tile({x, y})); + return {static_cast(result.at(0)), static_cast(result.at(1))}; + }; + std::array cell_xy(to_tile(mouse.x, mouse.y)); + std::array prev_cell_xy( + to_tile(mouse.x - mouse.dx, mouse.y - mouse.dy) + ); + mouse.cx = cell_xy.at(0); + mouse.cy = cell_xy.at(1); + mouse.dcx = cell_xy.at(0) - prev_cell_xy.at(0); + mouse.dcy = cell_xy.at(1) - prev_cell_xy.at(1); + } else { + mouse.x -= TCOD_ctx.fullscreen_offsetx; + mouse.y -= TCOD_ctx.fullscreen_offsety; + mouse.cx = mouse.x / TCOD_ctx.font_width; + mouse.cy = mouse.y / TCOD_ctx.font_height; + int prev_cx = (mouse.x - mouse.dx) / TCOD_ctx.font_width; + int prev_cy = (mouse.y - mouse.dy) / TCOD_ctx.font_height; + mouse.dcx = mouse.cx - prev_cx; + mouse.dcy = mouse.cy - prev_cy; + } +} /** * Parse an SDL_Event into `mouse` and return the relevant TCOD_event_t. * * Returns 0 if the event wasn't mouse related. */ -static TCOD_event_t TCOD_sys_handle_mouse_event(const SDL_Event *ev, - TCOD_mouse_t *mouse) { +TCOD_event_t TCOD_sys_handle_mouse_event( + const SDL_Event* ev, TCOD_mouse_t* mouse) +{ if (!ev || !mouse) { return TCOD_EVENT_NONE; } + sdl_parse_mouse_(*ev, *mouse); switch(ev->type) { case SDL_MOUSEMOTION: - TCOD_sys_unproject_screen_coords(ev->motion.x, ev->motion.y, - &mouse->x, &mouse->y); - if (scale_data.surface_width != 0) { - mouse->dx = (ev->motion.xrel * scale_data.src_proportionate_width - / scale_data.surface_width); - mouse->dy = (ev->motion.yrel * scale_data.src_proportionate_height - / scale_data.surface_height); - } - mouse->cx = mouse->x / TCOD_ctx.font_width; - mouse->cy = mouse->y / TCOD_ctx.font_height; - mouse->dcx = mouse->dx / TCOD_ctx.font_width; - mouse->dcy = mouse->dy / TCOD_ctx.font_height; - return TCOD_EVENT_MOUSE_MOVE; case SDL_MOUSEWHEEL: - if (ev->wheel.y < 0) { - mouse->wheel_down = true; - } else { - mouse->wheel_up = true; - } return TCOD_EVENT_MOUSE_PRESS; case SDL_MOUSEBUTTONDOWN: switch (ev->button.button) { @@ -1192,8 +1359,8 @@ static TCOD_event_t TCOD_sys_handle_mouse_event(const SDL_Event *ev, * * Returns 0 if the event wasn't keyboard related. */ -static TCOD_event_t TCOD_sys_handle_key_event(const SDL_Event *ev, - TCOD_key_t *key) { +TCOD_event_t TCOD_sys_handle_key_event(const SDL_Event* ev, TCOD_key_t* key) +{ if (!ev || !key) { return TCOD_EVENT_NONE; } switch(ev->type) { case SDL_KEYDOWN: @@ -1215,13 +1382,14 @@ static TCOD_event_t TCOD_sys_handle_key_event(const SDL_Event *ev, return TCOD_EVENT_NONE; } } -static TCOD_event_t TCOD_sys_handle_event(SDL_Event *ev,TCOD_event_t eventMask, TCOD_key_t *key, TCOD_mouse_t *mouse) { - TCOD_event_t retMask = TCOD_EVENT_NONE; +static TCOD_event_t TCOD_sys_handle_event( + SDL_Event *ev, TCOD_event_t eventMask, + TCOD_key_t *key, TCOD_mouse_t *mouse) +{ + int retMask = TCOD_EVENT_NONE; /* printf("TCOD_sys_handle_event type=%04x\n", ev->type); */ - retMask = static_cast( - retMask | TCOD_sys_handle_mouse_event(ev, mouse) & eventMask); - retMask = static_cast( - retMask | TCOD_sys_handle_key_event(ev, key) & eventMask); + retMask |= TCOD_sys_handle_mouse_event(ev, mouse) & eventMask; + retMask |= TCOD_sys_handle_key_event(ev, key) & eventMask; switch(ev->type) { #ifdef TCOD_TOUCH_INPUT /* @@ -1421,7 +1589,7 @@ static TCOD_event_t TCOD_sys_handle_event(SDL_Event *ev,TCOD_event_t eventMask, break; default : break; } - return retMask; + return static_cast(retMask); } /** * Internal function containing code shared by TCOD_sys_wait_for_event @@ -1515,14 +1683,11 @@ TCOD_mouse_t TCOD_mouse_get_status(void) { * If no event exists then the `vk` attribute will be `TCODK_NONE` */ TCOD_key_t TCOD_sys_check_for_keypress(int flags) { - static TCOD_key_t noret={TCODK_NONE,0}; - - TCOD_key_t key; - TCOD_event_t ev = TCOD_sys_check_for_event(flags & TCOD_EVENT_KEY, &key, NULL); - - if ((ev & TCOD_EVENT_KEY) == 0) return noret; - - return key; + TCOD_key_t key; + TCOD_event_t ev = TCOD_sys_check_for_event(flags & TCOD_EVENT_KEY, + &key, nullptr); + if ((ev & TCOD_EVENT_KEY) == 0) { return {}; } + return key; } /** * Wait for a key press event, then return it. @@ -1532,81 +1697,70 @@ TCOD_key_t TCOD_sys_check_for_keypress(int flags) { * \return A TCOD_key_t struct with the most recent key data. */ TCOD_key_t TCOD_sys_wait_for_keypress(bool flush) { - static TCOD_key_t noret={TCODK_NONE,0}; - - TCOD_key_t key; - TCOD_event_t ev = TCOD_sys_wait_for_event(TCOD_EVENT_KEY_PRESS, &key, NULL, flush); - - if ((ev & TCOD_EVENT_KEY_PRESS) == 0) return noret; - - return key; + TCOD_key_t key; + TCOD_event_t ev = TCOD_sys_wait_for_event(TCOD_EVENT_KEY_PRESS, + &key, nullptr, flush); + if ((ev & TCOD_EVENT_KEY_PRESS) == 0) { return {}; } + return key; } - void TCOD_sys_sleep_milli(uint32_t milliseconds) { SDL_Delay(milliseconds); } -void *TCOD_sys_load_image(const char *filename) { - image_support_t *img=image_type; - while ( img->extension != NULL && !img->check_type(filename) ) img++; - if ( img->extension == NULL || img->read == NULL ) return NULL; /* unknown format */ - return img->read(filename); -} - -void TCOD_sys_get_image_size(const void *image, int *w, int *h) { - SDL_Surface *surf=(SDL_Surface *)image; - *w = surf->w; - *h = surf->h; +SDL_Surface* TCOD_sys_load_image(const char *filename) { + const image_support_t* img = image_type; + while (img->extension != NULL && !img->check_type(filename)) { img++; } + if (img->extension == NULL || img->read == NULL) { return NULL; } /* unknown format */ + return img->read(filename); } -TCOD_color_t TCOD_sys_get_image_pixel(const void *image,int x, int y) { - TCOD_color_t ret; - SDL_Surface *surf=(SDL_Surface *)image; - uint8_t bpp; - uint8_t*bits; - if ( x < 0 || y < 0 || x >= surf->w || y >= surf->h ) return TCOD_black; - bpp = surf->format->BytesPerPixel; - bits = ((uint8_t*)surf->pixels)+y*surf->pitch+x*bpp; - switch (bpp) { - case 1 : - { - if (surf->format->palette) { - SDL_Color col = surf->format->palette->colors[(*bits)]; - ret.r=col.r; - ret.g=col.g; - ret.b=col.b; - } else return TCOD_black; - } - break; - default : - ret.r = *((bits)+surf->format->Rshift/8); - ret.g = *((bits)+surf->format->Gshift/8); - ret.b = *((bits)+surf->format->Bshift/8); - break; - } - - return ret; +void TCOD_sys_get_image_size(const SDL_Surface* image, int *w, int *h) +{ + *w = image->w; + *h = image->h; } - -int TCOD_sys_get_image_alpha(const void *image,int x, int y) { - SDL_Surface *surf=(SDL_Surface *)image; - uint8_t bpp; - uint8_t*bits; - if ( x < 0 || y < 0 || x >= surf->w || y >= surf->h ) return 255; - bpp = surf->format->BytesPerPixel; - if ( bpp != 4 ) return 255; - bits = ((uint8_t*)surf->pixels)+y*surf->pitch+x*bpp; - return *((bits)+surf->format->Ashift/8); +TCOD_color_t TCOD_sys_get_image_pixel(const SDL_Surface* image, int x, int y) +{ + if (x < 0 || y < 0 || x >= image->w || y >= image->h) { return TCOD_black; } + uint8_t bpp = image->format->BytesPerPixel; + uint8_t* bits = static_cast(image->pixels); + bits += y * image->pitch + x * bpp; + switch (bpp) { + case 1: + if (image->format->palette) { + SDL_Color col = image->format->palette->colors[(*bits)]; + return {col.r, col.g, col.b}; + } else { + return TCOD_black; + } + break; + default: + return { + *((bits)+image->format->Rshift/8), + *((bits)+image->format->Gshift/8), + *((bits)+image->format->Bshift/8), + }; + } } -uint32_t TCOD_sys_elapsed_milli(void) { - return (uint32_t)SDL_GetTicks(); +int TCOD_sys_get_image_alpha(const SDL_Surface *surf, int x, int y) +{ + if (x < 0 || y < 0 || x >= surf->w || y >= surf->h) { return 255; } + uint8_t bpp = surf->format->BytesPerPixel; + if (bpp != 4) { return 255; } + uint8_t* bits = static_cast(surf->pixels); + bits += y * surf->pitch + x * bpp; + return bits[surf->format->Ashift / 8]; +} +uint32_t TCOD_sys_elapsed_milli(void) +{ + return SDL_GetTicks(); } - -float TCOD_sys_elapsed_seconds(void) { - static float div=1.0f/1000.0f; - return SDL_GetTicks()*div; +float TCOD_sys_elapsed_seconds(void) +{ + static float div=1.0f / 1000.0f; + return SDL_GetTicks() * div; } void TCOD_sys_force_fullscreen_resolution(int width, int height) { @@ -1614,7 +1768,8 @@ void TCOD_sys_force_fullscreen_resolution(int width, int height) { TCOD_ctx.fullscreen_height=height; } -void * TCOD_sys_create_bitmap(int width, int height, TCOD_color_t *buf) { +SDL_Surface* TCOD_sys_create_bitmap(int width, int height, TCOD_color_t *buf) +{ int x,y; SDL_PixelFormat fmt; SDL_Surface *bitmap; @@ -1646,11 +1801,11 @@ void * TCOD_sys_create_bitmap(int width, int height, TCOD_color_t *buf) { SDL_FillRect(bitmap,&rect,col); } } - return (void *)bitmap; + return bitmap; } -void TCOD_sys_delete_bitmap(void *bitmap) { - SDL_FreeSurface((SDL_Surface *)bitmap); +void TCOD_sys_delete_bitmap(SDL_Surface* bitmap) { + SDL_FreeSurface(bitmap); } void TCOD_sys_set_fps(int val) { @@ -1675,8 +1830,14 @@ float TCOD_sys_get_last_frame_length(void) { } void TCOD_sys_get_char_size(int *w, int *h) { - *w = TCOD_ctx.font_width; - *h = TCOD_ctx.font_height; + auto tileset = tcod::engine::get_tileset(); + if (tileset) { + *w = tileset->get_tile_width(); + *h = tileset->get_tile_height(); + } else { + *w = TCOD_ctx.font_width; + *h = TCOD_ctx.font_height; + } } void TCOD_sys_get_current_resolution(int *w, int *h) { @@ -1700,12 +1861,14 @@ bool TCOD_sys_check_magic_number(const char *filename, size_t size, uint8_t*data return true; } -void *TCOD_sys_get_SDL_window(void) { - return (void *)window; +SDL_Window* TCOD_sys_get_SDL_window(void) +{ + return window; } -void *TCOD_sys_get_SDL_renderer(void) { - return (void *)renderer; +SDL_Renderer* TCOD_sys_get_SDL_renderer(void) +{ + return renderer; } /* mouse stuff */ @@ -1721,11 +1884,15 @@ void TCOD_mouse_move(int x, int y) { sdl->set_mouse_position(x,y); } -void TCOD_mouse_includes_touch(bool enable) { #ifdef TCOD_TOUCH_INPUT +void TCOD_mouse_includes_touch(bool enable) +{ mouse_touch = enable; -#endif } +#else +void TCOD_mouse_includes_touch(bool) +{} +#endif /*clipboard stuff */ bool TCOD_sys_clipboard_set(const char *value) { @@ -1734,8 +1901,8 @@ bool TCOD_sys_clipboard_set(const char *value) { } char *TCOD_sys_clipboard_get() { - if (!has_startup) { return ""; } - return sdl->get_clipboard_text(); + if (!has_startup) { return const_cast(""); } + return const_cast(sdl->get_clipboard_text()); } bool TCOD_sys_read_file(const char *filename, unsigned char **buf, size_t *size) { @@ -1774,7 +1941,7 @@ void TCOD_sys_set_dirty(int dx, int dy, int dw, int dh) { for (x = dx; x < dx + dw; ++x) { for (y = dy; y < dy + dh; ++y) { - dat->ch_array[dat->w * y + x] = -1; + dat->tiles[dat->w * y + x].ch = -1; } } } @@ -1788,8 +1955,8 @@ void TCOD_sys_set_dirty_character_code(int ch) { struct TCOD_Console *dat = sdl->get_root_console_cache(); if (!dat) return; for (i = 0; i < dat->w * dat->h; ++i) { - if (dat->ch_array[i] == ch) { - dat->ch_array[i] = -1; + if (dat->tiles[i].ch == ch) { + dat->tiles[i].ch = -1; } } } @@ -1802,4 +1969,12 @@ int TCOD_get_tileid_for_charcode_(int charcode) { } return 0; } +struct SDL_Window* TCOD_sys_get_sdl_window_(void) +{ + return window; +} +struct SDL_Renderer* TCOD_sys_get_sdl_renderer_(void) +{ + return renderer; +} #endif /* TCOD_BARE */ diff --git a/tcod_sys/libtcod/src/libtcod/sys_sdl_img_bmp.cpp b/tcod_sys/libtcod/src/libtcod/sys_sdl_img_bmp.cpp index 7ac830900..d413d3346 100644 --- a/tcod_sys/libtcod/src/libtcod/sys_sdl_img_bmp.cpp +++ b/tcod_sys/libtcod/src/libtcod/sys_sdl_img_bmp.cpp @@ -1,30 +1,34 @@ -/* -* libtcod -* Copyright (c) 2008-2018 Jice & Mingos & rmtew -* All rights reserved. -* -* Redistribution and use in source and binary forms, with or without -* modification, are permitted provided that the following conditions are met: -* * Redistributions of source code must retain the above copyright -* notice, this list of conditions and the following disclaimer. -* * Redistributions in binary form must reproduce the above copyright -* notice, this list of conditions and the following disclaimer in the -* documentation and/or other materials provided with the distribution. -* * The name of Jice or Mingos may not be used to endorse or promote -* products derived from this software without specific prior written -* permission. -* -* THIS SOFTWARE IS PROVIDED BY JICE, MINGOS AND RMTEW ``AS IS'' AND ANY -* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED -* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE -* DISCLAIMED. IN NO EVENT SHALL JICE, MINGOS OR RMTEW BE LIABLE FOR ANY -* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES -* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; -* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND -* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS -* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. -*/ +/* BSD 3-Clause License + * + * Copyright © 2008-2019, Jice and the libtcod contributors. + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions are met: + * + * 1. Redistributions of source code must retain the above copyright notice, + * this list of conditions and the following disclaimer. + * + * 2. Redistributions in binary form must reproduce the above copyright notice, + * this list of conditions and the following disclaimer in the documentation + * and/or other materials provided with the distribution. + * + * 3. Neither the name of the copyright holder nor the names of its + * contributors may be used to endorse or promote products derived from + * this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE + * POSSIBILITY OF SUCH DAMAGE. + */ #ifndef TCOD_BARE #include "sys.h" @@ -61,7 +65,7 @@ SDL_Surface *TCOD_sys_read_bmp(const char *filename) { return ret; } -void TCOD_sys_write_bmp(const SDL_Surface *surf, const char *filename) { - SDL_SaveBMP((SDL_Surface *)surf,filename); +void TCOD_sys_write_bmp(SDL_Surface *surf, const char *filename) { + SDL_SaveBMP(surf, filename); } #endif /* TCOD_BARE */ diff --git a/tcod_sys/libtcod/src/libtcod/sys_sdl_img_png.cpp b/tcod_sys/libtcod/src/libtcod/sys_sdl_img_png.cpp index f212b830e..a65012275 100644 --- a/tcod_sys/libtcod/src/libtcod/sys_sdl_img_png.cpp +++ b/tcod_sys/libtcod/src/libtcod/sys_sdl_img_png.cpp @@ -1,30 +1,34 @@ -/* -* libtcod -* Copyright (c) 2008-2018 Jice & Mingos & rmtew -* All rights reserved. -* -* Redistribution and use in source and binary forms, with or without -* modification, are permitted provided that the following conditions are met: -* * Redistributions of source code must retain the above copyright -* notice, this list of conditions and the following disclaimer. -* * Redistributions in binary form must reproduce the above copyright -* notice, this list of conditions and the following disclaimer in the -* documentation and/or other materials provided with the distribution. -* * The name of Jice or Mingos may not be used to endorse or promote -* products derived from this software without specific prior written -* permission. -* -* THIS SOFTWARE IS PROVIDED BY JICE, MINGOS AND RMTEW ``AS IS'' AND ANY -* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED -* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE -* DISCLAIMED. IN NO EVENT SHALL JICE, MINGOS OR RMTEW BE LIABLE FOR ANY -* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES -* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; -* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND -* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS -* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. -*/ +/* BSD 3-Clause License + * + * Copyright © 2008-2019, Jice and the libtcod contributors. + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions are met: + * + * 1. Redistributions of source code must retain the above copyright notice, + * this list of conditions and the following disclaimer. + * + * 2. Redistributions in binary form must reproduce the above copyright notice, + * this list of conditions and the following disclaimer in the documentation + * and/or other materials provided with the distribution. + * + * 3. Neither the name of the copyright holder nor the names of its + * contributors may be used to endorse or promote products derived from + * this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE + * POSSIBILITY OF SUCH DAMAGE. + */ #ifndef TCOD_BARE #include "sys.h" @@ -78,11 +82,12 @@ SDL_Surface *TCOD_sys_read_png(const char *filename) { } /* create the SDL surface */ - bitmap=(SDL_Surface*)TCOD_sys_get_surface(width,height,bpp==32); + bitmap = TCOD_sys_get_surface(width, height, bpp==32); source=image; rowsize=width*bpp/8; for (y=0; y< height; y++ ) { - uint8_t*row_pointer=(uint8_t*)(bitmap->pixels) + y * bitmap->pitch; + uint8_t* row_pointer = static_cast(bitmap->pixels) + + y * bitmap->pitch; memcpy(row_pointer,source,rowsize); source+=rowsize; } @@ -92,8 +97,8 @@ SDL_Surface *TCOD_sys_read_png(const char *filename) { return bitmap; } -void TCOD_sys_write_png(const SDL_Surface *surf, const char *filename) { - unsigned char *image, *dest=(unsigned char *)malloc(surf->h*surf->w*3*sizeof(char)); +void TCOD_sys_write_png(SDL_Surface *surf, const char *filename) { + unsigned char *image, *dest=static_cast(malloc(surf->h * surf->w * 3 * sizeof(char))); int x,y; unsigned char *buf; size_t size; @@ -102,7 +107,8 @@ void TCOD_sys_write_png(const SDL_Surface *surf, const char *filename) { image=dest; for (y=0; y< surf->h; y++ ) { for (x=0; x < surf->w; x++ ) { - uint8_t*pixel=(uint8_t*)(surf->pixels) + y * surf->pitch + x * surf->format->BytesPerPixel; + uint8_t* pixel = static_cast(surf->pixels) + + y * surf->pitch + x * surf->format->BytesPerPixel; *dest++=*((pixel)+surf->format->Rshift/8); *dest++=*((pixel)+surf->format->Gshift/8); *dest++=*((pixel)+surf->format->Bshift/8); @@ -111,7 +117,7 @@ void TCOD_sys_write_png(const SDL_Surface *surf, const char *filename) { error=lodepng_encode_memory(&buf,&size,image,surf->w,surf->h,LCT_RGB,8); free(image); if ( ! error ) { - TCOD_sys_write_file(filename,buf,(uint32_t)size); + TCOD_sys_write_file(filename, buf, static_cast(size)); free(buf); } else { printf("error %u: %s\n", error, lodepng_error_text(error)); diff --git a/tcod_sys/libtcod/src/libtcod/tileset/fallback.cpp b/tcod_sys/libtcod/src/libtcod/tileset/fallback.cpp new file mode 100644 index 000000000..2401480b7 --- /dev/null +++ b/tcod_sys/libtcod/src/libtcod/tileset/fallback.cpp @@ -0,0 +1,83 @@ +/* BSD 3-Clause License + * + * Copyright © 2008-2019, Jice and the libtcod contributors. + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions are met: + * + * 1. Redistributions of source code must retain the above copyright notice, + * this list of conditions and the following disclaimer. + * + * 2. Redistributions in binary form must reproduce the above copyright notice, + * this list of conditions and the following disclaimer in the documentation + * and/or other materials provided with the distribution. + * + * 3. Neither the name of the copyright holder nor the names of its + * contributors may be used to endorse or promote products derived from + * this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE + * POSSIBILITY OF SUCH DAMAGE. + */ +#include "fallback.h" + +#include +#include +#include +#include +#include +#include +#include + +#include "truetype.h" +namespace tcod { +namespace tileset { +#ifdef __unix__ +/** + * Run and return the output from the given command. + * + * https://stackoverflow.com/questions/478898/how-do-i-execute-a-command-and-get-output-of-command-within-c-using-posix + */ +std::string exec_(const char* cmd) { + std::array buffer; + std::string result; + std::unique_ptr pipe(popen(cmd, "r"), pclose); + if (!pipe) { + throw std::runtime_error("popen() failed!"); + } + while (fgets(buffer.data(), buffer.size(), pipe.get()) != nullptr) { + result += buffer.data(); + } + return result; +} +#endif +auto new_fallback_tileset(const std::array& tile_size) +-> std::unique_ptr +{ +#if defined(_WIN32) // Windows. + std::string font_path(std::getenv("SystemRoot")); + font_path += "\\Fonts\\LUCON.TTF"; + return load_truetype(font_path, tile_size); +#elif defined(__APPLE__) // MacOS. + return load_truetype("/System/Library/Fonts/SFCompactDisplay-Regular.otf", + tile_size); +#elif defined(__unix__) // Linux + return load_truetype( + exec_("fc-match --format=%{file} monospace"), tile_size + ); +#else + throw std::runtime_error("Fallback font not supported for this OS."); +#endif +} +} // namespace tileset +} // namespace tcod diff --git a/tcod_sys/libtcod/src/libtcod/tileset/fallback.h b/tcod_sys/libtcod/src/libtcod/tileset/fallback.h new file mode 100644 index 000000000..105db011d --- /dev/null +++ b/tcod_sys/libtcod/src/libtcod/tileset/fallback.h @@ -0,0 +1,53 @@ +/* BSD 3-Clause License + * + * Copyright © 2008-2019, Jice and the libtcod contributors. + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions are met: + * + * 1. Redistributions of source code must retain the above copyright notice, + * this list of conditions and the following disclaimer. + * + * 2. Redistributions in binary form must reproduce the above copyright notice, + * this list of conditions and the following disclaimer in the documentation + * and/or other materials provided with the distribution. + * + * 3. Neither the name of the copyright holder nor the names of its + * contributors may be used to endorse or promote products derived from + * this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE + * POSSIBILITY OF SUCH DAMAGE. + */ +#ifndef LIBTCOD_TILESET_FALLBACK_H_ +#define LIBTCOD_TILESET_FALLBACK_H_ +#ifdef __cplusplus +#include +#include +#endif // __cplusplus +#include "tileset.h" +#ifdef __cplusplus +namespace tcod { +namespace tileset { +/** + * Try to return a fall-back Tileset, may return nullptr or throw an error. + * + * Used when one is needed, but was not provided by the user. + */ +TCODLIB_API +auto new_fallback_tileset(const std::array& tile_size = {0, 12}) +-> std::unique_ptr; +} // namespace tileset +} // namespace tcod +#endif // __cplusplus +#endif // LIBTCOD_TILESET_FALLBACK_H_ diff --git a/tcod_sys/libtcod/src/libtcod/tileset/observer.cpp b/tcod_sys/libtcod/src/libtcod/tileset/observer.cpp index ddb29ee4e..6b8617418 100644 --- a/tcod_sys/libtcod/src/libtcod/tileset/observer.cpp +++ b/tcod_sys/libtcod/src/libtcod/tileset/observer.cpp @@ -1,4 +1,34 @@ - +/* BSD 3-Clause License + * + * Copyright © 2008-2019, Jice and the libtcod contributors. + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions are met: + * + * 1. Redistributions of source code must retain the above copyright notice, + * this list of conditions and the following disclaimer. + * + * 2. Redistributions in binary form must reproduce the above copyright notice, + * this list of conditions and the following disclaimer in the documentation + * and/or other materials provided with the distribution. + * + * 3. Neither the name of the copyright holder nor the names of its + * contributors may be used to endorse or promote products derived from + * this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE + * POSSIBILITY OF SUCH DAMAGE. + */ #include "observer.h" namespace tcod { namespace tileset { diff --git a/tcod_sys/libtcod/src/libtcod/tileset/observer.h b/tcod_sys/libtcod/src/libtcod/tileset/observer.h index 135e5f27b..a0b6279ea 100644 --- a/tcod_sys/libtcod/src/libtcod/tileset/observer.h +++ b/tcod_sys/libtcod/src/libtcod/tileset/observer.h @@ -1,4 +1,34 @@ - +/* BSD 3-Clause License + * + * Copyright © 2008-2019, Jice and the libtcod contributors. + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions are met: + * + * 1. Redistributions of source code must retain the above copyright notice, + * this list of conditions and the following disclaimer. + * + * 2. Redistributions in binary form must reproduce the above copyright notice, + * this list of conditions and the following disclaimer in the documentation + * and/or other materials provided with the distribution. + * + * 3. Neither the name of the copyright holder nor the names of its + * contributors may be used to endorse or promote products derived from + * this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE + * POSSIBILITY OF SUCH DAMAGE. + */ #ifndef LIBTCOD_TILESET_OBSERVER_H_ #define LIBTCOD_TILESET_OBSERVER_H_ #include "../portability.h" @@ -22,7 +52,7 @@ class TilesetObserver { public: TilesetObserver() = default; - TilesetObserver(std::shared_ptr subject) + TilesetObserver(const std::shared_ptr& subject) { if (!subject) { throw std::invalid_argument("tileset cannot be nullptr."); @@ -61,16 +91,15 @@ class TilesetObserver { * The Tileset may have been resized. */ virtual void on_tileset_changed( - const std::vector> &changes) - {} - std::shared_ptr& get_tileset() + const std::vector> &changes) = 0; + std::shared_ptr get_tileset() { return tileset_; } protected: std::shared_ptr tileset_; private: - void observe(std::shared_ptr subject) + void observe(const std::shared_ptr& subject) { unobserve(); tileset_ = subject; diff --git a/tcod_sys/libtcod/src/libtcod/tileset/tile.cpp b/tcod_sys/libtcod/src/libtcod/tileset/tile.cpp index 8bba22974..e28c62066 100644 --- a/tcod_sys/libtcod/src/libtcod/tileset/tile.cpp +++ b/tcod_sys/libtcod/src/libtcod/tileset/tile.cpp @@ -1,2 +1,32 @@ - +/* BSD 3-Clause License + * + * Copyright © 2008-2019, Jice and the libtcod contributors. + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions are met: + * + * 1. Redistributions of source code must retain the above copyright notice, + * this list of conditions and the following disclaimer. + * + * 2. Redistributions in binary form must reproduce the above copyright notice, + * this list of conditions and the following disclaimer in the documentation + * and/or other materials provided with the distribution. + * + * 3. Neither the name of the copyright holder nor the names of its + * contributors may be used to endorse or promote products derived from + * this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE + * POSSIBILITY OF SUCH DAMAGE. + */ #include "tile.h" diff --git a/tcod_sys/libtcod/src/libtcod/tileset/tile.h b/tcod_sys/libtcod/src/libtcod/tileset/tile.h index 4705bb3e7..5d266fc4a 100644 --- a/tcod_sys/libtcod/src/libtcod/tileset/tile.h +++ b/tcod_sys/libtcod/src/libtcod/tileset/tile.h @@ -1,4 +1,34 @@ - +/* BSD 3-Clause License + * + * Copyright © 2008-2019, Jice and the libtcod contributors. + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions are met: + * + * 1. Redistributions of source code must retain the above copyright notice, + * this list of conditions and the following disclaimer. + * + * 2. Redistributions in binary form must reproduce the above copyright notice, + * this list of conditions and the following disclaimer in the documentation + * and/or other materials provided with the distribution. + * + * 3. Neither the name of the copyright holder nor the names of its + * contributors may be used to endorse or promote products derived from + * this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE + * POSSIBILITY OF SUCH DAMAGE. + */ #ifndef LIBTCOD_TILESET_TILE_H_ #define LIBTCOD_TILESET_TILE_H_ #include @@ -17,18 +47,22 @@ using image::Image; class Tile { public: Tile(); - explicit Tile(int codepoint, const Image &image) - : codepoint(codepoint), image_(image) + explicit Tile(int codepoint_, const Image &image) + : codepoint(codepoint_), image_(image) {} - explicit Tile(int codepoint, int width, int height) - : Tile(codepoint, Image(width, height)) + explicit Tile(int codepoint_, int width, int height) + : Tile(codepoint_, Image(width, height)) {} - int width(void) const { return image_.width(); } - int height(void) const { return image_.height(); } + int width(void) const { return static_cast(image_.width()); } + int height(void) const { return static_cast(image_.height()); } Image get_image() const { return image_; } + bool operator==(const Tile& rhs) const noexcept + { + return image_ == rhs.image_; + } const int codepoint; private: Image image_; diff --git a/tcod_sys/libtcod/src/libtcod/tileset/tileset.cpp b/tcod_sys/libtcod/src/libtcod/tileset/tileset.cpp index 8be361132..5b10064cf 100644 --- a/tcod_sys/libtcod/src/libtcod/tileset/tileset.cpp +++ b/tcod_sys/libtcod/src/libtcod/tileset/tileset.cpp @@ -1,6 +1,37 @@ - +/* BSD 3-Clause License + * + * Copyright © 2008-2019, Jice and the libtcod contributors. + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions are met: + * + * 1. Redistributions of source code must retain the above copyright notice, + * this list of conditions and the following disclaimer. + * + * 2. Redistributions in binary form must reproduce the above copyright notice, + * this list of conditions and the following disclaimer in the documentation + * and/or other materials provided with the distribution. + * + * 3. Neither the name of the copyright holder nor the names of its + * contributors may be used to endorse or promote products derived from + * this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE + * POSSIBILITY OF SUCH DAMAGE. + */ #include "tileset.h" +#include #include #include @@ -11,12 +42,52 @@ namespace tcod { namespace tileset { extern "C" { -Tileset* TCOD_tileset_new(int tile_width, int tile_height) { - return new Tileset(tile_width, tile_height); +TCOD_Tileset* TCOD_tileset_new(int tile_width, int tile_height) +{ + auto tileset = std::make_shared(tile_width, tile_height); + return new TCOD_Tileset(tileset); } -void TCOD_tileset_delete(Tileset* tileset) { +void TCOD_tileset_delete(TCOD_Tileset* tileset) +{ if (tileset) { delete tileset; } } +int TCOD_tileset_get_tile_width_(const TCOD_Tileset* tileset) +{ + if (!tileset || !(*tileset)) { return 0; } + return (*tileset)->get_tile_width(); +} +int TCOD_tileset_get_tile_height_(const TCOD_Tileset* tileset) +{ + if (!tileset || !(*tileset)) { return 0; } + return (*tileset)->get_tile_height(); +} +int TCOD_tileset_get_tile_( + const TCOD_Tileset* tileset, + int codepoint, + struct TCOD_ColorRGBA* buffer) +{ + if (!tileset || !(*tileset)) { return -1; } + if (!(*tileset)->has_tile_(codepoint)) { + return -1; // No tile for the given codepoint in this tileset. + } + if (!buffer) { + return 0; // buffer is NULL, just return an OK status. + } + auto tile = (*tileset)->get_tile_(codepoint); + std::copy(tile.begin(), tile.end(), buffer); + return 0; // Tile exists and was copied to buffer. +} +int TCOD_tileset_set_tile_( + TCOD_Tileset* tileset, + int codepoint, + const struct TCOD_ColorRGBA* buffer) +{ + if (!tileset || !(*tileset)) { return -1; } + Image tile((*tileset)->get_tile_width(), (*tileset)->get_tile_height()); + std::copy(buffer, buffer + (tile.width() * tile.height()), tile.begin()); + (*tileset)->set_tile(codepoint, tile); + return 0; // Tile uploaded successfully. +} } // extern "C" } // namespace tileset } // namespace tcod diff --git a/tcod_sys/libtcod/src/libtcod/tileset/tileset.h b/tcod_sys/libtcod/src/libtcod/tileset/tileset.h index 1e672741e..1ad2756d8 100644 --- a/tcod_sys/libtcod/src/libtcod/tileset/tileset.h +++ b/tcod_sys/libtcod/src/libtcod/tileset/tileset.h @@ -1,4 +1,34 @@ - +/* BSD 3-Clause License + * + * Copyright © 2008-2019, Jice and the libtcod contributors. + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions are met: + * + * 1. Redistributions of source code must retain the above copyright notice, + * this list of conditions and the following disclaimer. + * + * 2. Redistributions in binary form must reproduce the above copyright notice, + * this list of conditions and the following disclaimer in the documentation + * and/or other materials provided with the distribution. + * + * 3. Neither the name of the copyright holder nor the names of its + * contributors may be used to endorse or promote products derived from + * this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE + * POSSIBILITY OF SUCH DAMAGE. + */ #ifndef LIBTCOD_TILESET_TILESET_H_ #define LIBTCOD_TILESET_TILESET_H_ #ifdef __cplusplus @@ -47,8 +77,14 @@ class Tileset { if (tile.codepoint >= static_cast(character_map_.size())) { character_map_.resize(tile.codepoint + 1, -1); } - character_map_[tile.codepoint] = tiles_.size(); - tiles_.push_back(tile); + auto it = std::find(tiles_.begin(), tiles_.end(), tile); + if (it == tiles_.end()) { + character_map_[tile.codepoint] = static_cast(tiles_.size()); + tiles_.push_back(tile); + } else { + character_map_[tile.codepoint] = static_cast( + std::distance(tiles_.begin(), it)); + } return 0; } /** Return the width of each tile in this Tileset */ @@ -65,6 +101,16 @@ class Tileset { { return character_map_; } + Image get_tile_(int codepoint) const { + if(!has_tile_(codepoint)) { + return Image(tile_width_, tile_height_); + } + return tiles_.at(character_map_.at(codepoint)).get_image(); + } + bool has_tile_(int codepoint) const { + return (codepoint < static_cast(character_map_.size()) + && character_map_.at(codepoint) >= 0); + } private: /** * Return the tile ID for a specific code-point. @@ -99,27 +145,67 @@ class Tileset { std::vector character_map_; std::vector observers_; }; -#endif /* __cplusplus */ +} // namespace tileset +} // namespace tcod +#endif // __cplusplus #ifdef __cplusplus /** * C API alias to the tcod::Tileset class. */ -typedef Tileset TCOD_Tileset; -extern "C" { +typedef std::shared_ptr TCOD_Tileset; #else typedef struct TCOD_Tileset TCOD_Tileset; #endif /** * Create a new tile-set with the given tile size. */ -TCOD_Tileset *TCOD_tileset_new(int tile_width, int tile_height); +TCODLIB_CAPI TCOD_Tileset* TCOD_tileset_new(int tile_width, int tile_height); /** * Delete a tile-set. */ -void TCOD_tileset_delete(TCOD_Tileset *tileset); -#ifdef __cplusplus -} // extern "C" -} // namespace tileset -} // namespace tcod -#endif +TCODLIB_CAPI void TCOD_tileset_delete(TCOD_Tileset* tileset); +/** + * Return the pixel width of tiles in this tileset. + * + * The tileset functions are provisional, the API may change in the future. + */ +TCODLIB_CAPI int TCOD_tileset_get_tile_width_(const TCOD_Tileset* tileset); +/** + * Return the pixel height of tiles in this tileset. + * + * The tileset functions are provisional, the API may change in the future. + */ +TCODLIB_CAPI int TCOD_tileset_get_tile_height_(const TCOD_Tileset* tileset); +/** + * Fetch a tile, outputting its data to a pixel buffer. + * + * `codepoint` is the index for the tile. Unicode is recommend. + * + * `buffer` is a pointer to a contiguous row-major array of pixels. The tile + * data will be outputted here. This pointer can be NULL if you only want to + * know if the tileset has a specific tile. + * + * Returns 0 if the tile exists. Returns a negative value on an error or if + * the tileset does not have a tile for this codepoint. + * + * The tileset functions are provisional, the API may change in the future. + */ +TCODLIB_CAPI int TCOD_tileset_get_tile_( + const TCOD_Tileset* tileset, + int codepoint, + struct TCOD_ColorRGBA* buffer); +/** + * Upload a tile from a pixel buffer into this tileset. + * + * `codepoint` is the index for the tile. Unicode is recommend. + * + * `buffer` is a pointer to a contiguous row-major array of pixels. + * This can not be NULL. + * + * The tileset functions are provisional, the API may change in the future. + */ +TCODLIB_CAPI int TCOD_tileset_set_tile_( + TCOD_Tileset* tileset, + int codepoint, + const struct TCOD_ColorRGBA* buffer); #endif /* LIBTCOD_TILESET_TILESET_H_ */ diff --git a/tcod_sys/libtcod/src/libtcod/tileset/tilesheet.cpp b/tcod_sys/libtcod/src/libtcod/tileset/tilesheet.cpp index ad904aed7..fc9dbdd4f 100644 --- a/tcod_sys/libtcod/src/libtcod/tileset/tilesheet.cpp +++ b/tcod_sys/libtcod/src/libtcod/tileset/tilesheet.cpp @@ -1,10 +1,216 @@ - +/* BSD 3-Clause License + * + * Copyright © 2008-2019, Jice and the libtcod contributors. + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions are met: + * + * 1. Redistributions of source code must retain the above copyright notice, + * this list of conditions and the following disclaimer. + * + * 2. Redistributions in binary form must reproduce the above copyright notice, + * this list of conditions and the following disclaimer in the documentation + * and/or other materials provided with the distribution. + * + * 3. Neither the name of the copyright holder nor the names of its + * contributors may be used to endorse or promote products derived from + * this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE + * POSSIBILITY OF SUCH DAMAGE. + */ #include "tilesheet.h" #include "../../vendor/lodepng.h" #include "../color/canvas.h" namespace tcod { namespace tileset { +class Tilesheet::impl { + public: + impl() = default; + explicit impl(const Image& canvas, const TilesheetLayout& layout) + : canvas_(canvas), layout_(layout) { + fill_layout(); + color_key_ = guess_color_key(); + } + impl(impl&&) = default; + impl& operator=(impl&&) = default; + impl(const impl&) = default; + impl& operator=(const impl&) = default; + /** + * Return the Tile at `x` and `y`. + */ + Image get_tile(int x, int y) const { + if (!(0 <= x && x < layout_.columns && 0 <= y && y < layout_.rows)) { + throw std::out_of_range("Tile not in Tilesheet layout."); + } + return new_tile(x * layout_.tile_width, y * layout_.tile_height, + layout_.tile_width, layout_.tile_height); + } + /** + * Return the Tile at `n`. + */ + Image get_tile(int n) const { + return get_tile(n % layout_.columns, n / layout_.columns); + } + int get_tile_width() const noexcept { + return layout_.tile_width; + } + int get_tile_height() const noexcept { + return layout_.tile_height; + } + int get_columns() const noexcept { + return layout_.columns; + } + int get_rows() const noexcept { + return layout_.rows; + } + int count() const noexcept { + return get_columns() * get_rows(); + } + private: + /** + * Automatically fill values which are 0 in layout_. + */ + void fill_layout() { + // Find undefined columns/rows from tile size and canvas_ size. + if (layout_.columns == 0 && layout_.tile_width > 0) { + layout_.columns = static_cast(canvas_.width() / layout_.tile_width); + } + if (layout_.rows == 0 && layout_.tile_height > 0) { + layout_.rows = static_cast(canvas_.height() / layout_.tile_height); + } + // Find undefined tile width/height from columns/rows and canvas_ size. + if (layout_.tile_width == 0 && layout_.columns > 0) { + layout_.tile_width = static_cast(canvas_.width() / layout_.columns); + } + if (layout_.tile_height == 0 && layout_.rows > 0) { + layout_.tile_height = static_cast(canvas_.height() / layout_.rows); + } + if (!layout_.columns || !layout_.rows) { + throw std::logic_error("Tilesheet layout is non-valid."); + } + } + /** + * Attempt to figure out a tile-sheets color key automatically. + */ + ColorRGBA guess_color_key() + { + Image tile(get_tile(0)); // Check the NULL tile. + const ColorRGBA color_key(tile.atf(0, 0)); + if (color_key.a != 255) { + return {0, 0, 0, 0}; + } + // Tile must be a solid color. + for (const ColorRGBA& pixel : tile) { + if (pixel != color_key) { + return {0, 0, 0, 0}; + } + } + return color_key; + } + /** + * Return a new Tile from the given region on the Tilesheet. + */ + Image new_tile(int x, int y, int width, int height) const { + Image tile{width, height}; + for (int pixel_y = 0; pixel_y < height; ++pixel_y) { + for (int pixel_x = 0; pixel_x < width; ++pixel_x) { + tile.atf(pixel_x, pixel_y) = canvas_.atf(x + pixel_x, y + pixel_y); + } + } + bool is_colored = false; + for (const ColorRGBA& pixel : tile) { + if (pixel.r != pixel.g || pixel.r != pixel.b) { + is_colored = true; + break; + } + } + bool has_alpha = false; + for (ColorRGBA& pixel : tile) { + if (pixel.a != 0xff) { + has_alpha = true; + break; + } + } + // Convert a grey-scale tiles to white-with-alpha. + if (!is_colored && !has_alpha) { + for (ColorRGBA& pixel : tile) { + pixel.a = pixel.r; + pixel.r = pixel.g = pixel.b = 0xff; + } + } + // Set key-color pixels to zero. + for (ColorRGBA& pixel : tile) { + if (pixel == color_key_) { + pixel.r = pixel.g = pixel.b = pixel.a = 0; + } + } + return tile; + } + Image canvas_; + TilesheetLayout layout_; + ColorRGBA color_key_; +}; + +Tilesheet::Tilesheet() = default; +Tilesheet::Tilesheet(const Image& canvas, const TilesheetLayout& layout) +: impl_(std::make_unique(canvas, layout)) +{} +Tilesheet::Tilesheet(const Image& canvas, const std::pair& layout) +: Tilesheet(canvas, {0, 0, layout.first, layout.second}) +{} + +Tilesheet::Tilesheet(Tilesheet&&) noexcept = default; +Tilesheet& Tilesheet::operator=(Tilesheet&&) noexcept = default; +Tilesheet::Tilesheet(const Tilesheet& rhs) +: impl_(std::make_unique(*rhs.impl_)) +{} +Tilesheet& Tilesheet::operator=(const Tilesheet& rhs) +{ + impl_ = std::make_unique(*rhs.impl_); + return *this; +} +Tilesheet::~Tilesheet() noexcept = default; + +Image Tilesheet::get_tile(int x, int y) const +{ + return impl_->get_tile(x, y); +} +Image Tilesheet::get_tile(int n) const +{ + return impl_->get_tile(n); +} +int Tilesheet::get_tile_width() const noexcept +{ + return impl_->get_tile_width(); +} +int Tilesheet::get_tile_height() const noexcept +{ + return impl_->get_tile_height(); +} +int Tilesheet::get_columns() const noexcept +{ + return impl_->get_columns(); +} +int Tilesheet::get_rows() const noexcept +{ + return impl_->get_rows(); +} +int Tilesheet::count() const noexcept +{ + return impl_->count(); +} Tilesheet LoadTilesheet(const std::string& filename, const TilesheetLayout& layout) { unsigned img_width, img_height; @@ -16,8 +222,9 @@ Tilesheet LoadTilesheet(const std::string& filename, std::vector::iterator img_iter = img_data.begin(); for (int y = 0; y < canvas.height(); ++y) { for (int x = 0; y < canvas.width(); ++x) { - canvas.at(x, y) = ColorRGBA{img_iter[0], img_iter[1], - img_iter[2], img_iter[3]}; + canvas.atf(x, y) = ColorRGBA{ + img_iter[0], img_iter[1], img_iter[2], img_iter[3] + }; img_iter += 4; } } diff --git a/tcod_sys/libtcod/src/libtcod/tileset/tilesheet.h b/tcod_sys/libtcod/src/libtcod/tileset/tilesheet.h index ae348dd24..0d7561245 100644 --- a/tcod_sys/libtcod/src/libtcod/tileset/tilesheet.h +++ b/tcod_sys/libtcod/src/libtcod/tileset/tilesheet.h @@ -1,7 +1,38 @@ - +/* BSD 3-Clause License + * + * Copyright © 2008-2019, Jice and the libtcod contributors. + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions are met: + * + * 1. Redistributions of source code must retain the above copyright notice, + * this list of conditions and the following disclaimer. + * + * 2. Redistributions in binary form must reproduce the above copyright notice, + * this list of conditions and the following disclaimer in the documentation + * and/or other materials provided with the distribution. + * + * 3. Neither the name of the copyright holder nor the names of its + * contributors may be used to endorse or promote products derived from + * this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE + * POSSIBILITY OF SUCH DAMAGE. + */ #ifndef LIBTCOD_TILESET_TILESHEET_H_ #define LIBTCOD_TILESET_TILESHEET_H_ #ifdef __cplusplus +#include #include #include #endif // __cplusplus @@ -23,107 +54,30 @@ struct TilesheetLayout { }; class Tilesheet { public: - Tilesheet() = default; - explicit Tilesheet(const Image& canvas, const TilesheetLayout& layout) - : canvas_(canvas), layout_(layout) { - fill_layout(); - } - explicit Tilesheet(const Image& canvas, const std::pair& layout) - : Tilesheet(canvas, {0, 0, layout.first, layout.second}) - {} - Tilesheet(Tilesheet&&) = default; - Tilesheet& operator=(Tilesheet&&) = default; - Tilesheet(const Tilesheet&) = default; - Tilesheet& operator=(const Tilesheet&) = default; + Tilesheet(); + explicit Tilesheet(const Image& canvas, const TilesheetLayout& layout); + explicit Tilesheet(const Image& canvas, const std::pair& layout); + Tilesheet(Tilesheet&&) noexcept; + Tilesheet& operator=(Tilesheet&&) noexcept; + Tilesheet(const Tilesheet&); + Tilesheet& operator=(const Tilesheet&); + ~Tilesheet() noexcept; /** - * Return the Tile at `x` and `y`. + * Return the tile at `x` and `y`. */ - Image get_tile(int x, int y) const { - if (!(0 <= x && x < layout_.columns && 0 <= y && y < layout_.rows)) { - throw std::out_of_range("Tile not in Tilesheet layout."); - } - return new_tile(x * layout_.tile_width, y * layout_.tile_height, - layout_.tile_width, layout_.tile_height); - } + Image get_tile(int x, int y) const; /** - * Return the Tile at `n`. + * Return the tile at `n`. */ - Image get_tile(int n) const { - return get_tile(n % layout_.columns, n / layout_.columns); - } - int get_tile_width() const { - return layout_.tile_width; - } - int get_tile_height() const { - return layout_.tile_height; - } - int get_columns() const { - return layout_.columns; - } - int get_rows() const { - return layout_.rows; - } - int count() const { - return get_columns() * get_rows(); - } + Image get_tile(int n) const; + int get_tile_width() const noexcept; + int get_tile_height() const noexcept; + int get_columns() const noexcept; + int get_rows() const noexcept; + int count() const noexcept; private: - /** - * Automatically fill values which are 0 in layout_. - */ - void fill_layout() { - // Find undefined columns/rows from tile size and canvas_ size. - if (layout_.columns == 0 && layout_.tile_width > 0) { - layout_.columns = canvas_.width() / layout_.tile_width; - } - if (layout_.rows == 0 && layout_.tile_height > 0) { - layout_.rows = canvas_.height() / layout_.tile_height; - } - // Find undefined tile width/height from columns/rows and canvas_ size. - if (layout_.tile_width == 0 && layout_.columns > 0) { - layout_.tile_width = canvas_.width() / layout_.columns; - } - if (layout_.tile_height == 0 && layout_.rows > 0) { - layout_.tile_height = canvas_.height() / layout_.rows; - } - if (!layout_.columns || !layout_.rows) { - throw std::logic_error("Tilesheet layout is non-valid."); - } - } - /** - * Return a new Tile from the given region on the Tilesheet. - */ - Image new_tile(int x, int y, int width, int height) const { - Image tile{width, height}; - for (int pixel_y = 0; pixel_y < height; ++pixel_y) { - for (int pixel_x = 0; pixel_x < width; ++pixel_x) { - tile.at(pixel_x, pixel_y) = canvas_.at(x + pixel_x, - y + pixel_y); - } - } - bool is_colored = false; - for (const ColorRGBA& pixel : tile) { - if (pixel.r != pixel.g || pixel.r != pixel.b) { - is_colored = true; - break; - } - } - bool has_alpha = false; - for (ColorRGBA& pixel : tile) { - if (pixel.a != 0xff) { - has_alpha = true; - break; - } - } - if (!is_colored && !has_alpha) { - for (ColorRGBA& pixel : tile) { - pixel.a = pixel.r; - pixel.r = pixel.g = pixel.b = 0xff; - } - } - return tile; - } - Image canvas_; - TilesheetLayout layout_; + class impl; + std::unique_ptr impl_; }; /** * Load a Tilesheet from an image file. diff --git a/tcod_sys/libtcod/src/libtcod/tileset/truetype.cpp b/tcod_sys/libtcod/src/libtcod/tileset/truetype.cpp new file mode 100644 index 000000000..86e770ac3 --- /dev/null +++ b/tcod_sys/libtcod/src/libtcod/tileset/truetype.cpp @@ -0,0 +1,265 @@ +/* BSD 3-Clause License + * + * Copyright © 2008-2019, Jice and the libtcod contributors. + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions are met: + * + * 1. Redistributions of source code must retain the above copyright notice, + * this list of conditions and the following disclaimer. + * + * 2. Redistributions in binary form must reproduce the above copyright notice, + * this list of conditions and the following disclaimer in the documentation + * and/or other materials provided with the distribution. + * + * 3. Neither the name of the copyright holder nor the names of its + * contributors may be used to endorse or promote products derived from + * this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE + * POSSIBILITY OF SUCH DAMAGE. + */ +#include +#include +#include +#include +#include +#include +#include + +#include "truetype.h" +#include "../engine/error.h" +#include "../engine/globals.h" +#include "../../vendor/stb_truetype.h" +// You can look here for a reference on glyph metrics: +// https://www.freetype.org/freetype2/docs/glyphs/glyphs-3.html +namespace tcod { +namespace tileset { +/** + * Return an entire file as a single data buffer. + */ +static auto load_data_file(const std::string& path) +-> std::basic_string +{ + std::ifstream file(path, std::ios::in | std::ios::binary); + if (!file.is_open()) { + throw std::runtime_error(std::string("File not found: ") + path); + } + return std::basic_string( + std::istreambuf_iterator(file), + std::istreambuf_iterator() + ); +} +/** + * Return the stbtt_fontinfo for the given `font_data`. + */ +static auto init_font_info(const std::basic_string& font_data) +-> stbtt_fontinfo +{ + stbtt_fontinfo font_info; + stbtt_InitFont(&font_info, font_data.data(), 0); + return font_info; +} +/** + * Converts TrueType fonts into tiles. + */ +class TTFontLoader { + public: + TTFontLoader(const std::string& path, int tile_width, int tile_height) + : font_data_(load_data_file(path)), + font_info_(init_font_info(font_data_)), + width_(tile_width), + height_(tile_height), + scale_(stbtt_ScaleForPixelHeight(&font_info_, height_)) + { + if (width_ <= 0) { + tile_width = width_ = guess_font_width(); + } + BBox font_bbox = get_font_bbox(); + float font_width = font_bbox.width() * scale_; + if (font_width > tile_width) { + // Shrink the font to fit its tile width. + scale_ *= static_cast(tile_width) / font_width; + } + } + auto generate_tileset() const -> std::unique_ptr + { + auto tileset = std::make_unique(width_, height_); + for (int codepoint = 1; codepoint <= 0x1ffff; ++codepoint) { + int glyph = stbtt_FindGlyphIndex(&font_info_, codepoint); + if (!glyph) { continue; } + tileset->set_tile(codepoint, render_glyph(glyph)); + } + return tileset; + } + private: + struct BBox { + int width() const noexcept + { + return xMax - xMin; + } + int height() const noexcept + { + return yMax - yMin; + } + int xMin; + int yMin; + int xMax; + int yMax; + }; + template + struct Point { + T x; + T y; + }; + /** + * Return the Image for a specific glyph. + */ + auto render_glyph(int glyph) const -> Image + { + Point shift(get_glyph_shift(glyph)); + Image image(width_, height_, {0xff, 0xff, 0xff, 0x00}); + Vector2 alpha(width_, height_); + stbtt_MakeGlyphBitmapSubpixel( + &font_info_, + alpha.data(), + width_, + height_, + static_cast(sizeof(alpha.data()[0]) * alpha.width()), + scale_, + scale_, + shift.x, + shift.y, + glyph); + for (int img_y = 0; img_y < image.height(); ++img_y) { + for (int img_x = 0; img_x < image.width(); ++img_x) { + int alpha_y = img_y - static_cast(shift.y); + int alpha_x = img_x - static_cast(shift.x); + if (alpha_y < 0 || alpha.height() <= alpha_y) { continue; } + if (alpha_x < 0 || alpha.width() <= alpha_x) { continue; } + image.atf(img_x, img_y).a = alpha.atf(alpha_x, alpha_y); + } + } + return image; + } + /** + * Return the bounding box for this glyph. + */ + auto get_glyph_bbox(int glyph, float scale=1.0f) const -> BBox + { + BBox bbox; + stbtt_GetGlyphBitmapBox(&font_info_, glyph, scale, scale, + &bbox.xMin, &bbox.yMin, &bbox.xMax, &bbox.yMax); + return bbox; + } + /** + * Return the bounding box for all possible glyphs. + */ + auto get_font_bbox() const -> BBox + { + BBox bbox; + stbtt_GetFontBoundingBox( + &font_info_, &bbox.xMin, &bbox.yMin, &bbox.xMax, &bbox.yMax); + return bbox; + } + /** + * Try to return a decent guess for this fonts width. + */ + int guess_font_width() const + { + BBox font_bbox = get_font_bbox(); + return static_cast(static_cast(font_bbox.width()) * scale_); + } + /** + * Return the shift needed to align this glyph with the current tile size. + */ + auto get_glyph_shift(int glyph) const -> Point + { + int ascent; + int descent; + int line_gap; + stbtt_GetFontVMetrics(&font_info_, &ascent, &descent, &line_gap); + BBox font_bbox = get_font_bbox(); + BBox bbox = get_glyph_bbox(glyph); + return { + (width_ - bbox.width() * scale_) * alignment_.at(0), + (bbox.yMin + ascent) * scale_ + + static_cast((height_ - (ascent - descent) * scale_) + * alignment_.at(1)), + }; + } + /** + * A data buffer referenced by `font_info_`. + */ + std::basic_string font_data_; + /** + * stb_truetype font info struct. + */ + stbtt_fontinfo font_info_; + /** + * Tile width. + */ + int width_; + /** + * Tile height. + */ + int height_; + /** + * Font scale needed to fit the current height. + */ + float scale_; + /** + * Font glyph alignment inside of a tile. + */ + std::array alignment_{0.5f, 0.5f}; +}; +auto load_truetype( + const std::string& path, + const std::array& tile_size) +-> std::unique_ptr +{ + return TTFontLoader(path, tile_size[0], tile_size[1]).generate_tileset(); +} +} // namespace tileset +} // namespace tcod +TCODLIB_CAPI TCOD_Tileset* TCOD_load_truetype_font_( + const char* path, + int tile_width, + int tile_height) +{ + using tcod::tileset::load_truetype; + using tcod::tileset::Tileset; + if (!path) { return nullptr; } + try { + auto tileset = load_truetype(path, {tile_width, tile_height}); + return new TCOD_Tileset(std::move(tileset)); + } catch (const std::exception& e) { + tcod::set_error(e); + return nullptr; + } +} +int TCOD_tileset_load_truetype_( + const char* path, + int tile_width, + int tile_height) +{ + TCOD_Tileset* tileset = TCOD_load_truetype_font_(path, + tile_width, tile_height); + if (!tileset) { return -1; } + try { + tcod::engine::set_tileset(*tileset); + } catch (const std::exception& e) { + return tcod::set_error(e); + } + return 0; +} diff --git a/tcod_sys/libtcod/src/libtcod/tileset/truetype.h b/tcod_sys/libtcod/src/libtcod/tileset/truetype.h new file mode 100644 index 000000000..febabedd4 --- /dev/null +++ b/tcod_sys/libtcod/src/libtcod/tileset/truetype.h @@ -0,0 +1,67 @@ +/* BSD 3-Clause License + * + * Copyright © 2008-2019, Jice and the libtcod contributors. + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions are met: + * + * 1. Redistributions of source code must retain the above copyright notice, + * this list of conditions and the following disclaimer. + * + * 2. Redistributions in binary form must reproduce the above copyright notice, + * this list of conditions and the following disclaimer in the documentation + * and/or other materials provided with the distribution. + * + * 3. Neither the name of the copyright holder nor the names of its + * contributors may be used to endorse or promote products derived from + * this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE + * POSSIBILITY OF SUCH DAMAGE. + */ +#ifndef LIBTCOD_TILESET_TRUETYPE_H_ +#define LIBTCOD_TILESET_TRUETYPE_H_ +#ifdef __cplusplus +#include +#include +#endif // __cplusplus +#include "tileset.h" + +#ifdef __cplusplus +namespace tcod { +namespace tileset { +/** + * Return a Tileset from a `.ttf` or `.otf` font file. + */ +auto load_truetype( + const std::string& path, + const std::array& tile_size) +-> std::unique_ptr; +} // namespace tileset +} // namespace tcod +#endif // __cplusplus +/** + * Return a tileset from a TrueType font file. + */ +TCODLIB_CAPI TCOD_Tileset* TCOD_load_truetype_font_( + const char* path, + int tile_width, + int tile_height); +/** + * Set the global tileset from a TrueType font file. + */ +TCODLIB_CAPI int TCOD_tileset_load_truetype_( + const char* path, + int tile_width, + int tile_height); +#endif // LIBTCOD_TILESET_TRUETYPE_H_ diff --git a/tcod_sys/libtcod/src/libtcod/tree.h b/tcod_sys/libtcod/src/libtcod/tree.h index d4d66f656..c219033dc 100644 --- a/tcod_sys/libtcod/src/libtcod/tree.h +++ b/tcod_sys/libtcod/src/libtcod/tree.h @@ -1,30 +1,34 @@ -/* -* libtcod -* Copyright (c) 2008-2018 Jice & Mingos & rmtew -* All rights reserved. -* -* Redistribution and use in source and binary forms, with or without -* modification, are permitted provided that the following conditions are met: -* * Redistributions of source code must retain the above copyright -* notice, this list of conditions and the following disclaimer. -* * Redistributions in binary form must reproduce the above copyright -* notice, this list of conditions and the following disclaimer in the -* documentation and/or other materials provided with the distribution. -* * The name of Jice or Mingos may not be used to endorse or promote -* products derived from this software without specific prior written -* permission. -* -* THIS SOFTWARE IS PROVIDED BY JICE, MINGOS AND RMTEW ``AS IS'' AND ANY -* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED -* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE -* DISCLAIMED. IN NO EVENT SHALL JICE, MINGOS OR RMTEW BE LIABLE FOR ANY -* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES -* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; -* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND -* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS -* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. -*/ +/* BSD 3-Clause License + * + * Copyright © 2008-2019, Jice and the libtcod contributors. + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions are met: + * + * 1. Redistributions of source code must retain the above copyright notice, + * this list of conditions and the following disclaimer. + * + * 2. Redistributions in binary form must reproduce the above copyright notice, + * this list of conditions and the following disclaimer in the documentation + * and/or other materials provided with the distribution. + * + * 3. Neither the name of the copyright holder nor the names of its + * contributors may be used to endorse or promote products derived from + * this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE + * POSSIBILITY OF SUCH DAMAGE. + */ #ifndef _TCOD_TREE_H #define _TCOD_TREE_H diff --git a/tcod_sys/libtcod/src/libtcod/tree.hpp b/tcod_sys/libtcod/src/libtcod/tree.hpp index 54b46abdb..d0d7c2630 100644 --- a/tcod_sys/libtcod/src/libtcod/tree.hpp +++ b/tcod_sys/libtcod/src/libtcod/tree.hpp @@ -1,30 +1,34 @@ -/* -* libtcod -* Copyright (c) 2008-2018 Jice & Mingos & rmtew -* All rights reserved. -* -* Redistribution and use in source and binary forms, with or without -* modification, are permitted provided that the following conditions are met: -* * Redistributions of source code must retain the above copyright -* notice, this list of conditions and the following disclaimer. -* * Redistributions in binary form must reproduce the above copyright -* notice, this list of conditions and the following disclaimer in the -* documentation and/or other materials provided with the distribution. -* * The name of Jice or Mingos may not be used to endorse or promote -* products derived from this software without specific prior written -* permission. -* -* THIS SOFTWARE IS PROVIDED BY JICE, MINGOS AND RMTEW ``AS IS'' AND ANY -* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED -* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE -* DISCLAIMED. IN NO EVENT SHALL JICE, MINGOS OR RMTEW BE LIABLE FOR ANY -* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES -* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; -* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND -* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS -* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. -*/ +/* BSD 3-Clause License + * + * Copyright © 2008-2019, Jice and the libtcod contributors. + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions are met: + * + * 1. Redistributions of source code must retain the above copyright notice, + * this list of conditions and the following disclaimer. + * + * 2. Redistributions in binary form must reproduce the above copyright notice, + * this list of conditions and the following disclaimer in the documentation + * and/or other materials provided with the distribution. + * + * 3. Neither the name of the copyright holder nor the names of its + * contributors may be used to endorse or promote products derived from + * this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE + * POSSIBILITY OF SUCH DAMAGE. + */ #ifndef _TCOD_TREE_HPP #define _TCOD_TREE_HPP diff --git a/tcod_sys/libtcod/src/libtcod/tree_c.c b/tcod_sys/libtcod/src/libtcod/tree_c.c index 485ee8a45..f8c60df86 100644 --- a/tcod_sys/libtcod/src/libtcod/tree_c.c +++ b/tcod_sys/libtcod/src/libtcod/tree_c.c @@ -1,30 +1,34 @@ -/* -* libtcod -* Copyright (c) 2008-2018 Jice & Mingos & rmtew -* All rights reserved. -* -* Redistribution and use in source and binary forms, with or without -* modification, are permitted provided that the following conditions are met: -* * Redistributions of source code must retain the above copyright -* notice, this list of conditions and the following disclaimer. -* * Redistributions in binary form must reproduce the above copyright -* notice, this list of conditions and the following disclaimer in the -* documentation and/or other materials provided with the distribution. -* * The name of Jice or Mingos may not be used to endorse or promote -* products derived from this software without specific prior written -* permission. -* -* THIS SOFTWARE IS PROVIDED BY JICE, MINGOS AND RMTEW ``AS IS'' AND ANY -* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED -* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE -* DISCLAIMED. IN NO EVENT SHALL JICE, MINGOS OR RMTEW BE LIABLE FOR ANY -* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES -* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; -* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND -* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS -* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. -*/ +/* BSD 3-Clause License + * + * Copyright © 2008-2019, Jice and the libtcod contributors. + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions are met: + * + * 1. Redistributions of source code must retain the above copyright notice, + * this list of conditions and the following disclaimer. + * + * 2. Redistributions in binary form must reproduce the above copyright notice, + * this list of conditions and the following disclaimer in the documentation + * and/or other materials provided with the distribution. + * + * 3. Neither the name of the copyright holder nor the names of its + * contributors may be used to endorse or promote products derived from + * this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE + * POSSIBILITY OF SUCH DAMAGE. + */ #include "tree.h" #include diff --git a/tcod_sys/libtcod/src/libtcod/txtfield.cpp b/tcod_sys/libtcod/src/libtcod/txtfield.cpp index dd5776c54..9c1a9fb50 100644 --- a/tcod_sys/libtcod/src/libtcod/txtfield.cpp +++ b/tcod_sys/libtcod/src/libtcod/txtfield.cpp @@ -1,30 +1,34 @@ -/* -* libtcod -* Copyright (c) 2008-2018 Jice & Mingos & rmtew -* All rights reserved. -* -* Redistribution and use in source and binary forms, with or without -* modification, are permitted provided that the following conditions are met: -* * Redistributions of source code must retain the above copyright -* notice, this list of conditions and the following disclaimer. -* * Redistributions in binary form must reproduce the above copyright -* notice, this list of conditions and the following disclaimer in the -* documentation and/or other materials provided with the distribution. -* * The name of Jice or Mingos may not be used to endorse or promote -* products derived from this software without specific prior written -* permission. -* -* THIS SOFTWARE IS PROVIDED BY JICE, MINGOS AND RMTEW ``AS IS'' AND ANY -* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED -* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE -* DISCLAIMED. IN NO EVENT SHALL JICE, MINGOS OR RMTEW BE LIABLE FOR ANY -* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES -* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; -* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND -* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS -* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. -*/ +/* BSD 3-Clause License + * + * Copyright © 2008-2019, Jice and the libtcod contributors. + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions are met: + * + * 1. Redistributions of source code must retain the above copyright notice, + * this list of conditions and the following disclaimer. + * + * 2. Redistributions in binary form must reproduce the above copyright notice, + * this list of conditions and the following disclaimer in the documentation + * and/or other materials provided with the distribution. + * + * 3. Neither the name of the copyright holder nor the names of its + * contributors may be used to endorse or promote products derived from + * this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE + * POSSIBILITY OF SUCH DAMAGE. + */ #include "txtfield.hpp" #ifdef TCOD_CONSOLE_SUPPORT diff --git a/tcod_sys/libtcod/src/libtcod/txtfield.h b/tcod_sys/libtcod/src/libtcod/txtfield.h index 327b1495d..c6273986d 100644 --- a/tcod_sys/libtcod/src/libtcod/txtfield.h +++ b/tcod_sys/libtcod/src/libtcod/txtfield.h @@ -1,30 +1,34 @@ -/* -* libtcod -* Copyright (c) 2008-2018 Jice & Mingos & rmtew -* All rights reserved. -* -* Redistribution and use in source and binary forms, with or without -* modification, are permitted provided that the following conditions are met: -* * Redistributions of source code must retain the above copyright -* notice, this list of conditions and the following disclaimer. -* * Redistributions in binary form must reproduce the above copyright -* notice, this list of conditions and the following disclaimer in the -* documentation and/or other materials provided with the distribution. -* * The name of Jice or Mingos may not be used to endorse or promote -* products derived from this software without specific prior written -* permission. -* -* THIS SOFTWARE IS PROVIDED BY JICE, MINGOS AND RMTEW ``AS IS'' AND ANY -* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED -* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE -* DISCLAIMED. IN NO EVENT SHALL JICE, MINGOS OR RMTEW BE LIABLE FOR ANY -* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES -* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; -* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND -* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS -* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. -*/ +/* BSD 3-Clause License + * + * Copyright © 2008-2019, Jice and the libtcod contributors. + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions are met: + * + * 1. Redistributions of source code must retain the above copyright notice, + * this list of conditions and the following disclaimer. + * + * 2. Redistributions in binary form must reproduce the above copyright notice, + * this list of conditions and the following disclaimer in the documentation + * and/or other materials provided with the distribution. + * + * 3. Neither the name of the copyright holder nor the names of its + * contributors may be used to endorse or promote products derived from + * this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE + * POSSIBILITY OF SUCH DAMAGE. + */ #ifndef _TCOD_TEXT_H_ #define _TCOD_TEXT_H_ diff --git a/tcod_sys/libtcod/src/libtcod/txtfield.hpp b/tcod_sys/libtcod/src/libtcod/txtfield.hpp index 5f18f5576..515432972 100644 --- a/tcod_sys/libtcod/src/libtcod/txtfield.hpp +++ b/tcod_sys/libtcod/src/libtcod/txtfield.hpp @@ -1,30 +1,34 @@ -/* -* libtcod -* Copyright (c) 2008-2018 Jice & Mingos & rmtew -* All rights reserved. -* -* Redistribution and use in source and binary forms, with or without -* modification, are permitted provided that the following conditions are met: -* * Redistributions of source code must retain the above copyright -* notice, this list of conditions and the following disclaimer. -* * Redistributions in binary form must reproduce the above copyright -* notice, this list of conditions and the following disclaimer in the -* documentation and/or other materials provided with the distribution. -* * The name of Jice or Mingos may not be used to endorse or promote -* products derived from this software without specific prior written -* permission. -* -* THIS SOFTWARE IS PROVIDED BY JICE, MINGOS AND RMTEW ``AS IS'' AND ANY -* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED -* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE -* DISCLAIMED. IN NO EVENT SHALL JICE, MINGOS OR RMTEW BE LIABLE FOR ANY -* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES -* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; -* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND -* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS -* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. -*/ +/* BSD 3-Clause License + * + * Copyright © 2008-2019, Jice and the libtcod contributors. + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions are met: + * + * 1. Redistributions of source code must retain the above copyright notice, + * this list of conditions and the following disclaimer. + * + * 2. Redistributions in binary form must reproduce the above copyright notice, + * this list of conditions and the following disclaimer in the documentation + * and/or other materials provided with the distribution. + * + * 3. Neither the name of the copyright holder nor the names of its + * contributors may be used to endorse or promote products derived from + * this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE + * POSSIBILITY OF SUCH DAMAGE. + */ #ifndef _TCOD_TEXT_HPP_ #define _TCOD_TEXT_HPP_ diff --git a/tcod_sys/libtcod/src/libtcod/txtfield_c.c b/tcod_sys/libtcod/src/libtcod/txtfield_c.c index 3057c9885..e2a04206a 100644 --- a/tcod_sys/libtcod/src/libtcod/txtfield_c.c +++ b/tcod_sys/libtcod/src/libtcod/txtfield_c.c @@ -1,30 +1,34 @@ -/* -* libtcod -* Copyright (c) 2008-2018 Jice & Mingos & rmtew -* All rights reserved. -* -* Redistribution and use in source and binary forms, with or without -* modification, are permitted provided that the following conditions are met: -* * Redistributions of source code must retain the above copyright -* notice, this list of conditions and the following disclaimer. -* * Redistributions in binary form must reproduce the above copyright -* notice, this list of conditions and the following disclaimer in the -* documentation and/or other materials provided with the distribution. -* * The name of Jice or Mingos may not be used to endorse or promote -* products derived from this software without specific prior written -* permission. -* -* THIS SOFTWARE IS PROVIDED BY JICE, MINGOS AND RMTEW ``AS IS'' AND ANY -* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED -* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE -* DISCLAIMED. IN NO EVENT SHALL JICE, MINGOS OR RMTEW BE LIABLE FOR ANY -* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES -* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; -* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND -* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS -* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. -*/ +/* BSD 3-Clause License + * + * Copyright © 2008-2019, Jice and the libtcod contributors. + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions are met: + * + * 1. Redistributions of source code must retain the above copyright notice, + * this list of conditions and the following disclaimer. + * + * 2. Redistributions in binary form must reproduce the above copyright notice, + * this list of conditions and the following disclaimer in the documentation + * and/or other materials provided with the distribution. + * + * 3. Neither the name of the copyright holder nor the names of its + * contributors may be used to endorse or promote products derived from + * this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE + * POSSIBILITY OF SUCH DAMAGE. + */ #include "txtfield.h" #ifdef TCOD_CONSOLE_SUPPORT diff --git a/tcod_sys/libtcod/src/libtcod/utility.h b/tcod_sys/libtcod/src/libtcod/utility.h index 6dab8746f..e4a3b546f 100644 --- a/tcod_sys/libtcod/src/libtcod/utility.h +++ b/tcod_sys/libtcod/src/libtcod/utility.h @@ -1,30 +1,34 @@ -/* -* libtcod -* Copyright (c) 2008-2018 Jice & Mingos & rmtew -* All rights reserved. -* -* Redistribution and use in source and binary forms, with or without -* modification, are permitted provided that the following conditions are met: -* * Redistributions of source code must retain the above copyright -* notice, this list of conditions and the following disclaimer. -* * Redistributions in binary form must reproduce the above copyright -* notice, this list of conditions and the following disclaimer in the -* documentation and/or other materials provided with the distribution. -* * The name of Jice or Mingos may not be used to endorse or promote -* products derived from this software without specific prior written -* permission. -* -* THIS SOFTWARE IS PROVIDED BY JICE, MINGOS AND RMTEW ``AS IS'' AND ANY -* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED -* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE -* DISCLAIMED. IN NO EVENT SHALL JICE, MINGOS OR RMTEW BE LIABLE FOR ANY -* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES -* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; -* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND -* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS -* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. -*/ +/* BSD 3-Clause License + * + * Copyright © 2008-2019, Jice and the libtcod contributors. + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions are met: + * + * 1. Redistributions of source code must retain the above copyright notice, + * this list of conditions and the following disclaimer. + * + * 2. Redistributions in binary form must reproduce the above copyright notice, + * this list of conditions and the following disclaimer in the documentation + * and/or other materials provided with the distribution. + * + * 3. Neither the name of the copyright holder nor the names of its + * contributors may be used to endorse or promote products derived from + * this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE + * POSSIBILITY OF SUCH DAMAGE. + */ #ifndef LIBTCOD_UTILITY_H #define LIBTCOD_UTILITY_H /****************************************** diff --git a/tcod_sys/libtcod/src/libtcod/utility/matrix.h b/tcod_sys/libtcod/src/libtcod/utility/matrix.h new file mode 100644 index 000000000..f0a17cf69 --- /dev/null +++ b/tcod_sys/libtcod/src/libtcod/utility/matrix.h @@ -0,0 +1,230 @@ +/* BSD 3-Clause License + * + * Copyright © 2008-2019, Jice and the libtcod contributors. + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions are met: + * + * 1. Redistributions of source code must retain the above copyright notice, + * this list of conditions and the following disclaimer. + * + * 2. Redistributions in binary form must reproduce the above copyright notice, + * this list of conditions and the following disclaimer in the documentation + * and/or other materials provided with the distribution. + * + * 3. Neither the name of the copyright holder nor the names of its + * contributors may be used to endorse or promote products derived from + * this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE + * POSSIBILITY OF SUCH DAMAGE. + */ +#ifndef LIBTCOD_UTILITY_MATRIX_H_ +#define LIBTCOD_UTILITY_MATRIX_H_ +#ifdef __cplusplus +#include +#include +#include +#include +#include +#include +#include +#include +#include +#endif // __cplusplus +#ifdef __cplusplus +namespace tcod { +template +class MatrixView { + public: + using value_type = T; + using size_type = ptrdiff_t; + using shape_type = std::array; + using strides_type = std::array; + MatrixView() = default; + MatrixView(T* ptr, const shape_type& shape, const strides_type& strides) + : data_{reinterpret_cast(ptr)}, shape_{shape}, strides_{strides} + {} + MatrixView(T* ptr, const shape_type& shape) + : MatrixView(ptr, shape, get_contiguous_strides(shape)) + {} + T& operator[](shape_type index) noexcept + { + return *get_data_at(index); + } + const T& operator[](shape_type index) const noexcept + { + return *get_data_at(index); + } + T& at(shape_type index) + { + range_check(index); + return (*this)[index]; + } + const T& at(shape_type index) const + { + range_check(index); + return (*this)[index]; + } + shape_type get_shape() const + { + return shape_; + } + private: + T* get_data_at(shape_type index) + { + auto ptr = data_; + for (size_t i = 0; i < shape_.size(); ++i) { + ptr += index.at(i) * strides_.at(i); + } + return reinterpret_cast(ptr); + } + MatrixView get_submatrix(size_type n) + { + return { + data_ + n * strides_.at(0), + pop_array(shape_), + pop_array(strides_) + }; + } + bool in_bounds(size_type n) const noexcept + { + return 0 <= n && n < shape_.at(0); + } + bool in_bounds(shape_type index) const noexcept + { + for (size_t i = 0; i < shape_.size(); ++i) { + if (index.at(i) < 0 || index.at(i) >= shape_.at(i)) { + return false; + } + } + return true; + } + void range_check(size_type n) const + { + if (in_bounds(n)) { return; } + throw std::out_of_range( + std::string("Out of bounds lookup {") + + std::to_string(n) + + "} on matrix of shape " + + array_as_string(shape_) + + "."); + } + void range_check(shape_type index) const + { + if (in_bounds(index)) { return; } + throw std::out_of_range( + std::string("Out of bounds lookup ") + + array_as_string(index) + + " on matrix of shape " + + array_as_string(shape_) + + "."); + } + template + static std::string array_as_string(const ArrayType& arr) + { + std::string result{"{ "}; + for (const auto& it : arr) { + result += std::to_string(it); + if (it != arr.back()) { result += ", "; } + } + result += " }"; + return result; + } + auto pop_array(const std::array& array) const noexcept + -> std::array + { + std::array new_array; + std::copy(array[1], array.end(), new_array.begin()); + return new_array; + } + static strides_type get_contiguous_strides(shape_type shape) + { + strides_type strides; + size_type stride = static_cast(sizeof(T)); + for (size_type i = strides.size() - 1; i >= 0; --i) { + strides.at(i) = stride; + stride *= shape.at(i); + } + return strides; + } + char* data_{nullptr}; + shape_type shape_; + strides_type strides_; +}; +template +class Matrix { + public: + using view_type = MatrixView; + using value_type = typename view_type::value_type; + using size_type = typename view_type::size_type; + using shape_type = typename view_type::shape_type; + using strides_type = typename view_type::strides_type; + Matrix() = default; + Matrix(const shape_type& shape) + : data_(get_size_from_shape(shape)), view_(data_.data(), shape) + {} + Matrix(const shape_type& shape, const value_type& fill) + : data_(get_size_from_shape(shape), fill), view_(data_.data(), shape) + {} + auto begin() noexcept + { + return data_.begin(); + } + auto begin() const noexcept + { + return data_.cbegin(); + } + auto end() noexcept + { + return data_.end(); + } + auto end() const noexcept + { + return data_.cend(); + } + value_type& operator[](shape_type index) noexcept + { + return view_[index]; + } + const value_type& operator[](shape_type index) const noexcept + { + return view_[index]; + } + value_type& at(shape_type index) + { + return view_.at(index); + } + const value_type& at(shape_type index) const + { + return view_.at(index); + } + shape_type get_shape() const + { + return view_.get_shape(); + } + private: + static size_t get_size_from_shape(const shape_type& shape) noexcept + { + size_t size = 1; + for (size_t i = 0; i < shape.size(); ++i) { + size *= shape.at(i); + } + return size; + } + std::vector data_; + view_type view_; +}; +} // namespace tcod +#endif // __cplusplus +#endif // LIBTCOD_UTILITY_MATRIX_H_ diff --git a/tcod_sys/libtcod/src/libtcod/utility/vector2.h b/tcod_sys/libtcod/src/libtcod/utility/vector2.h index 200827b0d..8529594d7 100644 --- a/tcod_sys/libtcod/src/libtcod/utility/vector2.h +++ b/tcod_sys/libtcod/src/libtcod/utility/vector2.h @@ -1,9 +1,44 @@ - +/* BSD 3-Clause License + * + * Copyright © 2008-2019, Jice and the libtcod contributors. + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions are met: + * + * 1. Redistributions of source code must retain the above copyright notice, + * this list of conditions and the following disclaimer. + * + * 2. Redistributions in binary form must reproduce the above copyright notice, + * this list of conditions and the following disclaimer in the documentation + * and/or other materials provided with the distribution. + * + * 3. Neither the name of the copyright holder nor the names of its + * contributors may be used to endorse or promote products derived from + * this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE + * POSSIBILITY OF SUCH DAMAGE. + */ #ifndef LIBTCOD_UTILITY_VECTOR2_H_ #define LIBTCOD_UTILITY_VECTOR2_H_ #ifdef __cplusplus #include +#include +#include +#include +#include #include +#include #include #endif // __cplusplus @@ -16,71 +51,157 @@ template class Vector2 { public: using value_type = T; + using size_type = ptrdiff_t; + using iterator = typename std::vector::iterator; + using const_iterator = typename std::vector::const_iterator; Vector2() = default; - explicit Vector2(int width, int height) - : width_(std::max(0, width)), - height_(std::max(0, height)), + explicit Vector2(size_type width, size_type height, const T& fill) + : width_(std::max(0, width)), + height_(std::max(0, height)), + vector_(width_ * height_, fill) + {} + explicit Vector2(size_type width, size_type height) + : width_(std::max(0, width)), + height_(std::max(0, height)), vector_(width_ * height_) {} + explicit Vector2( + const std::initializer_list>& array) + : Vector2( + std::max(array, + [](auto a, auto b){ return a.size() < b.size(); }).size(), + array.size() + ) + { + auto iter_out = vector_.begin(); + for (const auto row : array) { + std::copy(row.begin(), row.end(), iter_out); + iter_out += width_; + } + } Vector2(Vector2&&) = default; Vector2& operator=(Vector2&&) = default; Vector2(const Vector2&) = default; Vector2& operator=(const Vector2&) = default; /** Return the width of this 2d vector. */ - int width(void) const noexcept { return width_; } + size_type width(void) const noexcept { return width_; } /** Return the height of this 2d vector. */ - int height(void) const noexcept { return height_; } + size_type height(void) const noexcept { return height_; } /** * Return a reference for the pixel at `x`,`y`. * * Throws std::out_of_range if `x` or `y` are out of bounds. */ - T& at(int x, int y) { + T& atf(size_type x, size_type y) { range_check(x, y); return vector_.at(y * width_ + x); } + /** + * Return a reference for the value at `index`. + */ + T& atf(const std::tuple& index) + { + return atf(std::get<0>(index), std::get<1>(index)); + } + T& atf(const std::array& index) + { + return atf(index.at(0), index.at(1)); + } /** * Return a constant reference for the pixel at `x`,`y`. * * Throws std::out_of_range if `x` or `y` are out of bounds. */ - const T& at(int x, int y) const { + const T& atf(size_type x, size_type y) const + { range_check(x, y); return vector_.at(y * width_ + x); } + const T& atf(const std::array& index) const + { + return atf(index.at(0), index.at(1)); + } + /** + * Return a constant reference for the value at `index`. + */ + const T& atf(const std::tuple& index) const + { + return atf(std::get<0>(index), std::get<1>(index)); + } T* data() noexcept { return vector_.data(); } - typename std::vector::iterator begin() + const T* data() const noexcept + { + return vector_.data(); + } + iterator begin() noexcept + { + return vector_.begin(); + } + iterator end() noexcept + { + return vector_.end(); + } + const_iterator begin() const noexcept { return vector_.begin(); } - typename std::vector::iterator end() + const_iterator end() const noexcept { return vector_.end(); } + bool operator==(const Vector2& rhs) const noexcept + { + return width_ == rhs.width_ && vector_ == rhs.vector_; + } private: /** * Return true if x and y are in the bounds of this canvas. */ - bool in_bounds(int x, int y) const noexcept { + bool in_boundsf(size_type x, size_type y) const noexcept { return 0 <= x && x < width_ && 0 <= y && y < height_; } /** * Immediately throws std::out_of_range if `x` or `y` are out of bounds. */ - void range_check(int x, int y) const { - if (!in_bounds(x, y)) { - throw std::out_of_range("Out of bounds lookup on Vector2."); + void range_check(size_type x, size_type y) const { + if (!in_boundsf(x, y)) { + throw std::out_of_range( + std::string("Out of bounds lookup {") + + std::to_string(x) + + ", " + + std::to_string(y) + + "} on Vector2 of size {" + + std::to_string(width_) + + ", " + + std::to_string(height_) + + "}."); } } /** The width of this canvas. */ - int width_ = 0; + size_type width_ = 0; /** The height of this canvas. */ - int height_ = 0; + size_type height_ = 0; /** A 1d vector mapped to a 2d array of pixels. */ std::vector vector_; }; +template +std::ostream& operator<< (std::ostream &out, const Vector2& data) +{ + out << '{'; + for (int y = 0; y < data.height(); ++y) { + out << '{'; + for (int x = 0; x < data.width(); ++x) { + out << data.atf(x, y); + if (x != data.width() - 1) { out << ',' << ' '; } + } + out << '}'; + if (y != data.height() - 1) { out << ',' << ' '; } + } + out << '}'; + return out; +} } // namespace tcod #endif // __cplusplus #endif // LIBTCOD_UTILITY_VECTOR2_H_ diff --git a/tcod_sys/libtcod/src/libtcod/version.h b/tcod_sys/libtcod/src/libtcod/version.h index 3c8eecaa2..631cda21f 100644 --- a/tcod_sys/libtcod/src/libtcod/version.h +++ b/tcod_sys/libtcod/src/libtcod/version.h @@ -1,38 +1,42 @@ -/* -* libtcod -* Copyright (c) 2008-2018 Jice & Mingos & rmtew -* All rights reserved. -* -* Redistribution and use in source and binary forms, with or without -* modification, are permitted provided that the following conditions are met: -* * Redistributions of source code must retain the above copyright -* notice, this list of conditions and the following disclaimer. -* * Redistributions in binary form must reproduce the above copyright -* notice, this list of conditions and the following disclaimer in the -* documentation and/or other materials provided with the distribution. -* * The name of Jice or Mingos may not be used to endorse or promote -* products derived from this software without specific prior written -* permission. -* -* THIS SOFTWARE IS PROVIDED BY JICE, MINGOS AND RMTEW ``AS IS'' AND ANY -* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED -* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE -* DISCLAIMED. IN NO EVENT SHALL JICE, MINGOS OR RMTEW BE LIABLE FOR ANY -* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES -* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; -* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND -* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS -* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. -*/ +/* BSD 3-Clause License + * + * Copyright © 2008-2019, Jice and the libtcod contributors. + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions are met: + * + * 1. Redistributions of source code must retain the above copyright notice, + * this list of conditions and the following disclaimer. + * + * 2. Redistributions in binary form must reproduce the above copyright notice, + * this list of conditions and the following disclaimer in the documentation + * and/or other materials provided with the distribution. + * + * 3. Neither the name of the copyright holder nor the names of its + * contributors may be used to endorse or promote products derived from + * this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE + * POSSIBILITY OF SUCH DAMAGE. + */ #ifndef LIBTCOD_VERSION_H #define LIBTCOD_VERSION_H #define TCOD_MAJOR_VERSION 1 -#define TCOD_MINOR_VERSION 8 -#define TCOD_PATCHLEVEL 0 +#define TCOD_MINOR_VERSION 12 +#define TCOD_PATCHLEVEL 3 -#define TCOD_STRVERSION "1.8.0" +#define TCOD_STRVERSION "1.12.3" #define TCOD_HEXVERSION (0x010000 * TCOD_MAJOR_VERSION \ + 0x0100 * TCOD_MINOR_VERSION \ diff --git a/tcod_sys/libtcod/src/libtcod/wrappers.c b/tcod_sys/libtcod/src/libtcod/wrappers.cpp similarity index 73% rename from tcod_sys/libtcod/src/libtcod/wrappers.c rename to tcod_sys/libtcod/src/libtcod/wrappers.cpp index 51122f044..37b393210 100644 --- a/tcod_sys/libtcod/src/libtcod/wrappers.c +++ b/tcod_sys/libtcod/src/libtcod/wrappers.cpp @@ -1,30 +1,34 @@ -/* -* libtcod -* Copyright (c) 2008-2018 Jice & Mingos & rmtew -* All rights reserved. -* -* Redistribution and use in source and binary forms, with or without -* modification, are permitted provided that the following conditions are met: -* * Redistributions of source code must retain the above copyright -* notice, this list of conditions and the following disclaimer. -* * Redistributions in binary form must reproduce the above copyright -* notice, this list of conditions and the following disclaimer in the -* documentation and/or other materials provided with the distribution. -* * The name of Jice or Mingos may not be used to endorse or promote -* products derived from this software without specific prior written -* permission. -* -* THIS SOFTWARE IS PROVIDED BY JICE, MINGOS AND RMTEW ``AS IS'' AND ANY -* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED -* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE -* DISCLAIMED. IN NO EVENT SHALL JICE, MINGOS OR RMTEW BE LIABLE FOR ANY -* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES -* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; -* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND -* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS -* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. -*/ +/* BSD 3-Clause License + * + * Copyright © 2008-2019, Jice and the libtcod contributors. + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions are met: + * + * 1. Redistributions of source code must retain the above copyright notice, + * this list of conditions and the following disclaimer. + * + * 2. Redistributions in binary form must reproduce the above copyright notice, + * this list of conditions and the following disclaimer in the documentation + * and/or other materials provided with the distribution. + * + * 3. Neither the name of the copyright holder nor the names of its + * contributors may be used to endorse or promote products derived from + * this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE + * POSSIBILITY OF SUCH DAMAGE. + */ #include "wrappers.h" #include @@ -46,7 +50,10 @@ TCOD_color_t int_to_color (colornum_t col) { return ret; } -#define color_to_int(col) (int)(((int)((col).b) << 16) | ((col).g << 8) | (col).r) +static constexpr colornum_t color_to_int(const TCOD_ColorRGB& color) +{ + return (color.b << 16) | (color.g << 8) | color.r; +} bool TCOD_color_equals_wrapper (colornum_t c1, colornum_t c2) { return TCOD_color_equals (int_to_color(c1), int_to_color(c2)); @@ -163,42 +170,29 @@ void TCOD_console_set_fade_wrapper(uint8_t val, colornum_t fade) TCOD_console_set_fade (val, int_to_color(fade)); } -void TCOD_console_fill_background(TCOD_console_t con, int *r, int *g, int *b) { - struct TCOD_Console *dat = con ? (struct TCOD_Console *)con : TCOD_ctx.root; - int i; - TCOD_color_t *curcolor = dat->bg_array; - for (i = 0; i < dat->w*dat->h; i++) { - curcolor->r = *r; - curcolor->g = *g; - curcolor->b = *b; - curcolor++; - r++; - g++; - b++; - } +void TCOD_console_fill_background(TCOD_Console* con, int *r, int *g, int *b) +{ + con = tcod::console::validate_(con); + if (!con) { return; } + for (int i = 0; i < con->w * con->h; ++i) { + con->tiles[i].bg = tcod::ColorRGBA(r[i], g[i], b[i]); + } } - -void TCOD_console_fill_foreground(TCOD_console_t con, int *r, int *g, int *b) { - struct TCOD_Console *dat = con ? (struct TCOD_Console *)con : TCOD_ctx.root; - int i; - TCOD_color_t *curcolor = dat->fg_array; - for (i = 0; i < dat->w*dat->h; i++) { - curcolor->r = *r; - curcolor->g = *g; - curcolor->b = *b; - curcolor++; - r++; - g++; - b++; - } +void TCOD_console_fill_foreground(TCOD_Console* con, int *r, int *g, int *b) +{ + con = tcod::console::validate_(con); + if (!con) { return; } + for (int i = 0; i < con->w * con->h; ++i) { + con->tiles[i].fg = tcod::ColorRGBA(r[i], g[i], b[i]); + } } - -void TCOD_console_fill_char(TCOD_console_t con, int *arr) { - struct TCOD_Console *dat = con ? (struct TCOD_Console *)con : TCOD_ctx.root; - int i; - for (i = 0; i < dat->w*dat->h; i++) { - dat->ch_array[i] = arr[i]; - } +void TCOD_console_fill_char(TCOD_Console* con, int *arr) +{ + con = tcod::console::validate_(con); + if (!con) { return; } + for (int i = 0; i < con->w * con->h; ++i) { + con->tiles[i].ch = arr[i]; + } } colornum_t @@ -285,9 +279,19 @@ void TCOD_console_double_vline(TCOD_console_t con,int x,int y, int l, TCOD_bkgnd for (i=y; i< y+l; i++) TCOD_console_put_char(con,x,i,TCOD_CHAR_DVLINE,flag); } - -void TCOD_console_print_double_frame(TCOD_console_t con,int x,int y,int w,int h, bool empty, TCOD_bkgnd_flag_t flag, const char *fmt, ...) { - struct TCOD_Console *dat = con ? (struct TCOD_Console *)con : TCOD_ctx.root; +void TCOD_console_print_double_frame( + TCOD_Console* con, + int x, + int y, + int w, + int h, + bool empty, + TCOD_bkgnd_flag_t flag, + const char *fmt, + ...) +{ + struct TCOD_Console *dat = tcod::console::validate_(con); + if (!dat) { return; } TCOD_console_put_char(con,x,y,TCOD_CHAR_DNW,flag); TCOD_console_put_char(con,x+w-1,y,TCOD_CHAR_DNE,flag); TCOD_console_put_char(con,x,y+h-1,TCOD_CHAR_DSW,flag); @@ -312,7 +316,7 @@ void TCOD_console_print_double_frame(TCOD_console_t con,int x,int y,int w,int h, title = TCOD_console_vsprint(fmt,ap); va_end(ap); title[w-3]=0; /* truncate if needed */ - xs = x + (w-(int)strlen(title)-2)/2; + xs = x + (w - static_cast(strlen(title)) - 2) / 2; tmp=dat->back; /* swap colors */ dat->back=dat->fore; dat->fore=tmp; @@ -348,7 +352,9 @@ void TCOD_namegen_get_sets_wrapper(char **sets) { TCOD_list_t l=TCOD_namegen_get_sets(); char **it; int i=0; - for (it=(char**)TCOD_list_begin(l); it != (char **)TCOD_list_end(l); it++) { + for (it = reinterpret_cast(TCOD_list_begin(l)); + it != reinterpret_cast(TCOD_list_end(l)); + ++it) { sets[i++]=*it; } } diff --git a/tcod_sys/libtcod/src/libtcod/wrappers.h b/tcod_sys/libtcod/src/libtcod/wrappers.h index 8a9112831..bcace136f 100644 --- a/tcod_sys/libtcod/src/libtcod/wrappers.h +++ b/tcod_sys/libtcod/src/libtcod/wrappers.h @@ -1,30 +1,34 @@ -/* -* libtcod -* Copyright (c) 2008-2018 Jice & Mingos & rmtew -* All rights reserved. -* -* Redistribution and use in source and binary forms, with or without -* modification, are permitted provided that the following conditions are met: -* * Redistributions of source code must retain the above copyright -* notice, this list of conditions and the following disclaimer. -* * Redistributions in binary form must reproduce the above copyright -* notice, this list of conditions and the following disclaimer in the -* documentation and/or other materials provided with the distribution. -* * The name of Jice or Mingos may not be used to endorse or promote -* products derived from this software without specific prior written -* permission. -* -* THIS SOFTWARE IS PROVIDED BY JICE, MINGOS AND RMTEW ``AS IS'' AND ANY -* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED -* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE -* DISCLAIMED. IN NO EVENT SHALL JICE, MINGOS OR RMTEW BE LIABLE FOR ANY -* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES -* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; -* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND -* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS -* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. -*/ +/* BSD 3-Clause License + * + * Copyright © 2008-2019, Jice and the libtcod contributors. + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions are met: + * + * 1. Redistributions of source code must retain the above copyright notice, + * this list of conditions and the following disclaimer. + * + * 2. Redistributions in binary form must reproduce the above copyright notice, + * this list of conditions and the following disclaimer in the documentation + * and/or other materials provided with the distribution. + * + * 3. Neither the name of the copyright holder nor the names of its + * contributors may be used to endorse or promote products derived from + * this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE + * POSSIBILITY OF SUCH DAMAGE. + */ #ifndef WRAPPERS_H #define WRAPPERS_H diff --git a/tcod_sys/libtcod/src/libtcod/zip.cpp b/tcod_sys/libtcod/src/libtcod/zip.cpp index 3d8ee70a3..ea3d24dc0 100644 --- a/tcod_sys/libtcod/src/libtcod/zip.cpp +++ b/tcod_sys/libtcod/src/libtcod/zip.cpp @@ -1,30 +1,34 @@ -/* -* libtcod -* Copyright (c) 2008-2018 Jice & Mingos & rmtew -* All rights reserved. -* -* Redistribution and use in source and binary forms, with or without -* modification, are permitted provided that the following conditions are met: -* * Redistributions of source code must retain the above copyright -* notice, this list of conditions and the following disclaimer. -* * Redistributions in binary form must reproduce the above copyright -* notice, this list of conditions and the following disclaimer in the -* documentation and/or other materials provided with the distribution. -* * The name of Jice or Mingos may not be used to endorse or promote -* products derived from this software without specific prior written -* permission. -* -* THIS SOFTWARE IS PROVIDED BY JICE, MINGOS AND RMTEW ``AS IS'' AND ANY -* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED -* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE -* DISCLAIMED. IN NO EVENT SHALL JICE, MINGOS OR RMTEW BE LIABLE FOR ANY -* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES -* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; -* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND -* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS -* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. -*/ +/* BSD 3-Clause License + * + * Copyright © 2008-2019, Jice and the libtcod contributors. + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions are met: + * + * 1. Redistributions of source code must retain the above copyright notice, + * this list of conditions and the following disclaimer. + * + * 2. Redistributions in binary form must reproduce the above copyright notice, + * this list of conditions and the following disclaimer in the documentation + * and/or other materials provided with the distribution. + * + * 3. Neither the name of the copyright holder nor the names of its + * contributors may be used to endorse or promote products derived from + * this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE + * POSSIBILITY OF SUCH DAMAGE. + */ #include "zip.hpp" TCODZip::TCODZip() { diff --git a/tcod_sys/libtcod/src/libtcod/zip.h b/tcod_sys/libtcod/src/libtcod/zip.h index e8760847a..0bf16ae7d 100644 --- a/tcod_sys/libtcod/src/libtcod/zip.h +++ b/tcod_sys/libtcod/src/libtcod/zip.h @@ -1,30 +1,34 @@ -/* -* libtcod -* Copyright (c) 2008-2018 Jice & Mingos & rmtew -* All rights reserved. -* -* Redistribution and use in source and binary forms, with or without -* modification, are permitted provided that the following conditions are met: -* * Redistributions of source code must retain the above copyright -* notice, this list of conditions and the following disclaimer. -* * Redistributions in binary form must reproduce the above copyright -* notice, this list of conditions and the following disclaimer in the -* documentation and/or other materials provided with the distribution. -* * The name of Jice or Mingos may not be used to endorse or promote -* products derived from this software without specific prior written -* permission. -* -* THIS SOFTWARE IS PROVIDED BY JICE, MINGOS AND RMTEW ``AS IS'' AND ANY -* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED -* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE -* DISCLAIMED. IN NO EVENT SHALL JICE, MINGOS OR RMTEW BE LIABLE FOR ANY -* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES -* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; -* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND -* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS -* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. -*/ +/* BSD 3-Clause License + * + * Copyright © 2008-2019, Jice and the libtcod contributors. + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions are met: + * + * 1. Redistributions of source code must retain the above copyright notice, + * this list of conditions and the following disclaimer. + * + * 2. Redistributions in binary form must reproduce the above copyright notice, + * this list of conditions and the following disclaimer in the documentation + * and/or other materials provided with the distribution. + * + * 3. Neither the name of the copyright holder nor the names of its + * contributors may be used to endorse or promote products derived from + * this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE + * POSSIBILITY OF SUCH DAMAGE. + */ #ifndef _TCOD_ZIP_H #define _TCOD_ZIP_H diff --git a/tcod_sys/libtcod/src/libtcod/zip.hpp b/tcod_sys/libtcod/src/libtcod/zip.hpp index 6e0680ede..64db8a560 100644 --- a/tcod_sys/libtcod/src/libtcod/zip.hpp +++ b/tcod_sys/libtcod/src/libtcod/zip.hpp @@ -1,30 +1,34 @@ -/* -* libtcod -* Copyright (c) 2008-2018 Jice & Mingos & rmtew -* All rights reserved. -* -* Redistribution and use in source and binary forms, with or without -* modification, are permitted provided that the following conditions are met: -* * Redistributions of source code must retain the above copyright -* notice, this list of conditions and the following disclaimer. -* * Redistributions in binary form must reproduce the above copyright -* notice, this list of conditions and the following disclaimer in the -* documentation and/or other materials provided with the distribution. -* * The name of Jice or Mingos may not be used to endorse or promote -* products derived from this software without specific prior written -* permission. -* -* THIS SOFTWARE IS PROVIDED BY JICE, MINGOS AND RMTEW ``AS IS'' AND ANY -* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED -* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE -* DISCLAIMED. IN NO EVENT SHALL JICE, MINGOS OR RMTEW BE LIABLE FOR ANY -* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES -* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; -* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND -* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS -* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. -*/ +/* BSD 3-Clause License + * + * Copyright © 2008-2019, Jice and the libtcod contributors. + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions are met: + * + * 1. Redistributions of source code must retain the above copyright notice, + * this list of conditions and the following disclaimer. + * + * 2. Redistributions in binary form must reproduce the above copyright notice, + * this list of conditions and the following disclaimer in the documentation + * and/or other materials provided with the distribution. + * + * 3. Neither the name of the copyright holder nor the names of its + * contributors may be used to endorse or promote products derived from + * this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE + * POSSIBILITY OF SUCH DAMAGE. + */ #ifndef _TCOD_ZIP_HPP #define _TCOD_ZIP_HPP diff --git a/tcod_sys/libtcod/src/libtcod/zip_c.c b/tcod_sys/libtcod/src/libtcod/zip_c.c index 90324a8b1..c714c2f0b 100644 --- a/tcod_sys/libtcod/src/libtcod/zip_c.c +++ b/tcod_sys/libtcod/src/libtcod/zip_c.c @@ -1,30 +1,34 @@ -/* -* libtcod -* Copyright (c) 2008-2018 Jice & Mingos & rmtew -* All rights reserved. -* -* Redistribution and use in source and binary forms, with or without -* modification, are permitted provided that the following conditions are met: -* * Redistributions of source code must retain the above copyright -* notice, this list of conditions and the following disclaimer. -* * Redistributions in binary form must reproduce the above copyright -* notice, this list of conditions and the following disclaimer in the -* documentation and/or other materials provided with the distribution. -* * The name of Jice or Mingos may not be used to endorse or promote -* products derived from this software without specific prior written -* permission. -* -* THIS SOFTWARE IS PROVIDED BY JICE, MINGOS AND RMTEW ``AS IS'' AND ANY -* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED -* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE -* DISCLAIMED. IN NO EVENT SHALL JICE, MINGOS OR RMTEW BE LIABLE FOR ANY -* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES -* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; -* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND -* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS -* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. -*/ +/* BSD 3-Clause License + * + * Copyright © 2008-2019, Jice and the libtcod contributors. + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions are met: + * + * 1. Redistributions of source code must retain the above copyright notice, + * this list of conditions and the following disclaimer. + * + * 2. Redistributions in binary form must reproduce the above copyright notice, + * this list of conditions and the following disclaimer in the documentation + * and/or other materials provided with the distribution. + * + * 3. Neither the name of the copyright holder nor the names of its + * contributors may be used to endorse or promote products derived from + * this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE + * POSSIBILITY OF SUCH DAMAGE. + */ #include "zip.h" #include diff --git a/tcod_sys/libtcod/src/vendor/glad.c b/tcod_sys/libtcod/src/vendor/glad.c new file mode 100644 index 000000000..f3c603d1d --- /dev/null +++ b/tcod_sys/libtcod/src/vendor/glad.c @@ -0,0 +1,1321 @@ +/* + + OpenGL loader generated by glad 0.1.28 on Mon Nov 19 11:18:35 2018. + + Language/Generator: C/C++ + Specification: gl + APIs: gl=2.0 + Profile: compatibility + Extensions: + + Loader: False + Local files: True + Omit khrplatform: False + Reproducible: False + + Commandline: + --profile="compatibility" --api="gl=2.0" --generator="c" --spec="gl" --no-loader --local-files --extensions="" + Online: + https://glad.dav1d.de/#profile=compatibility&language=c&specification=gl&api=gl%3D2.0 +*/ + +#include +#include +#include +#include "glad.h" + +struct gladGLversionStruct GLVersion = { 0, 0 }; + +#if defined(GL_ES_VERSION_3_0) || defined(GL_VERSION_3_0) +#define _GLAD_IS_SOME_NEW_VERSION 1 +#endif + +static int max_loaded_major; +static int max_loaded_minor; + +static const char *exts = NULL; +static int num_exts_i = 0; +static char **exts_i = NULL; + +static int get_exts(void) { +#ifdef _GLAD_IS_SOME_NEW_VERSION + if(max_loaded_major < 3) { +#endif + exts = (const char *)glGetString(GL_EXTENSIONS); +#ifdef _GLAD_IS_SOME_NEW_VERSION + } else { + unsigned int index; + + num_exts_i = 0; + glGetIntegerv(GL_NUM_EXTENSIONS, &num_exts_i); + if (num_exts_i > 0) { + char **tmp_exts_i = (char **)realloc((void *)exts_i, (size_t)num_exts_i * (sizeof *exts_i)); + if (tmp_exts_i == NULL) { + return 0; + } + exts_i = tmp_exts_i; + } + + if (exts_i == NULL) { + return 0; + } + + for(index = 0; index < (unsigned)num_exts_i; index++) { + const char *gl_str_tmp = (const char*)glGetStringi(GL_EXTENSIONS, index); + size_t len = strlen(gl_str_tmp); + + char *local_str = (char*)malloc((len+1) * sizeof(char)); + if(local_str != NULL) { + memcpy(local_str, gl_str_tmp, (len+1) * sizeof(char)); + } + exts_i[index] = local_str; + } + } +#endif + return 1; +} + +static void free_exts(void) { + if (exts_i != NULL) { + int index; + for(index = 0; index < num_exts_i; index++) { + free((char *)exts_i[index]); + } + free((void *)exts_i); + exts_i = NULL; + } +} + +static int has_ext(const char *ext) { +#ifdef _GLAD_IS_SOME_NEW_VERSION + if(max_loaded_major < 3) { +#endif + const char *extensions; + const char *loc; + const char *terminator; + extensions = exts; + if(extensions == NULL || ext == NULL) { + return 0; + } + + while(1) { + loc = strstr(extensions, ext); + if(loc == NULL) { + return 0; + } + + terminator = loc + strlen(ext); + if((loc == extensions || *(loc - 1) == ' ') && + (*terminator == ' ' || *terminator == '\0')) { + return 1; + } + extensions = terminator; + } +#ifdef _GLAD_IS_SOME_NEW_VERSION + } else { + int index; + if(exts_i == NULL) return 0; + for(index = 0; index < num_exts_i; index++) { + const char *e = exts_i[index]; + + if(exts_i[index] != NULL && strcmp(e, ext) == 0) { + return 1; + } + } + } +#endif + + return 0; +} +int GLAD_GL_VERSION_1_0 = 0; +int GLAD_GL_VERSION_1_1 = 0; +int GLAD_GL_VERSION_1_2 = 0; +int GLAD_GL_VERSION_1_3 = 0; +int GLAD_GL_VERSION_1_4 = 0; +int GLAD_GL_VERSION_1_5 = 0; +int GLAD_GL_VERSION_2_0 = 0; +PFNGLACCUMPROC glad_glAccum = NULL; +PFNGLACTIVETEXTUREPROC glad_glActiveTexture = NULL; +PFNGLALPHAFUNCPROC glad_glAlphaFunc = NULL; +PFNGLARETEXTURESRESIDENTPROC glad_glAreTexturesResident = NULL; +PFNGLARRAYELEMENTPROC glad_glArrayElement = NULL; +PFNGLATTACHSHADERPROC glad_glAttachShader = NULL; +PFNGLBEGINPROC glad_glBegin = NULL; +PFNGLBEGINQUERYPROC glad_glBeginQuery = NULL; +PFNGLBINDATTRIBLOCATIONPROC glad_glBindAttribLocation = NULL; +PFNGLBINDBUFFERPROC glad_glBindBuffer = NULL; +PFNGLBINDTEXTUREPROC glad_glBindTexture = NULL; +PFNGLBITMAPPROC glad_glBitmap = NULL; +PFNGLBLENDCOLORPROC glad_glBlendColor = NULL; +PFNGLBLENDEQUATIONPROC glad_glBlendEquation = NULL; +PFNGLBLENDEQUATIONSEPARATEPROC glad_glBlendEquationSeparate = NULL; +PFNGLBLENDFUNCPROC glad_glBlendFunc = NULL; +PFNGLBLENDFUNCSEPARATEPROC glad_glBlendFuncSeparate = NULL; +PFNGLBUFFERDATAPROC glad_glBufferData = NULL; +PFNGLBUFFERSUBDATAPROC glad_glBufferSubData = NULL; +PFNGLCALLLISTPROC glad_glCallList = NULL; +PFNGLCALLLISTSPROC glad_glCallLists = NULL; +PFNGLCLEARPROC glad_glClear = NULL; +PFNGLCLEARACCUMPROC glad_glClearAccum = NULL; +PFNGLCLEARCOLORPROC glad_glClearColor = NULL; +PFNGLCLEARDEPTHPROC glad_glClearDepth = NULL; +PFNGLCLEARINDEXPROC glad_glClearIndex = NULL; +PFNGLCLEARSTENCILPROC glad_glClearStencil = NULL; +PFNGLCLIENTACTIVETEXTUREPROC glad_glClientActiveTexture = NULL; +PFNGLCLIPPLANEPROC glad_glClipPlane = NULL; +PFNGLCOLOR3BPROC glad_glColor3b = NULL; +PFNGLCOLOR3BVPROC glad_glColor3bv = NULL; +PFNGLCOLOR3DPROC glad_glColor3d = NULL; +PFNGLCOLOR3DVPROC glad_glColor3dv = NULL; +PFNGLCOLOR3FPROC glad_glColor3f = NULL; +PFNGLCOLOR3FVPROC glad_glColor3fv = NULL; +PFNGLCOLOR3IPROC glad_glColor3i = NULL; +PFNGLCOLOR3IVPROC glad_glColor3iv = NULL; +PFNGLCOLOR3SPROC glad_glColor3s = NULL; +PFNGLCOLOR3SVPROC glad_glColor3sv = NULL; +PFNGLCOLOR3UBPROC glad_glColor3ub = NULL; +PFNGLCOLOR3UBVPROC glad_glColor3ubv = NULL; +PFNGLCOLOR3UIPROC glad_glColor3ui = NULL; +PFNGLCOLOR3UIVPROC glad_glColor3uiv = NULL; +PFNGLCOLOR3USPROC glad_glColor3us = NULL; +PFNGLCOLOR3USVPROC glad_glColor3usv = NULL; +PFNGLCOLOR4BPROC glad_glColor4b = NULL; +PFNGLCOLOR4BVPROC glad_glColor4bv = NULL; +PFNGLCOLOR4DPROC glad_glColor4d = NULL; +PFNGLCOLOR4DVPROC glad_glColor4dv = NULL; +PFNGLCOLOR4FPROC glad_glColor4f = NULL; +PFNGLCOLOR4FVPROC glad_glColor4fv = NULL; +PFNGLCOLOR4IPROC glad_glColor4i = NULL; +PFNGLCOLOR4IVPROC glad_glColor4iv = NULL; +PFNGLCOLOR4SPROC glad_glColor4s = NULL; +PFNGLCOLOR4SVPROC glad_glColor4sv = NULL; +PFNGLCOLOR4UBPROC glad_glColor4ub = NULL; +PFNGLCOLOR4UBVPROC glad_glColor4ubv = NULL; +PFNGLCOLOR4UIPROC glad_glColor4ui = NULL; +PFNGLCOLOR4UIVPROC glad_glColor4uiv = NULL; +PFNGLCOLOR4USPROC glad_glColor4us = NULL; +PFNGLCOLOR4USVPROC glad_glColor4usv = NULL; +PFNGLCOLORMASKPROC glad_glColorMask = NULL; +PFNGLCOLORMATERIALPROC glad_glColorMaterial = NULL; +PFNGLCOLORPOINTERPROC glad_glColorPointer = NULL; +PFNGLCOMPILESHADERPROC glad_glCompileShader = NULL; +PFNGLCOMPRESSEDTEXIMAGE1DPROC glad_glCompressedTexImage1D = NULL; +PFNGLCOMPRESSEDTEXIMAGE2DPROC glad_glCompressedTexImage2D = NULL; +PFNGLCOMPRESSEDTEXIMAGE3DPROC glad_glCompressedTexImage3D = NULL; +PFNGLCOMPRESSEDTEXSUBIMAGE1DPROC glad_glCompressedTexSubImage1D = NULL; +PFNGLCOMPRESSEDTEXSUBIMAGE2DPROC glad_glCompressedTexSubImage2D = NULL; +PFNGLCOMPRESSEDTEXSUBIMAGE3DPROC glad_glCompressedTexSubImage3D = NULL; +PFNGLCOPYPIXELSPROC glad_glCopyPixels = NULL; +PFNGLCOPYTEXIMAGE1DPROC glad_glCopyTexImage1D = NULL; +PFNGLCOPYTEXIMAGE2DPROC glad_glCopyTexImage2D = NULL; +PFNGLCOPYTEXSUBIMAGE1DPROC glad_glCopyTexSubImage1D = NULL; +PFNGLCOPYTEXSUBIMAGE2DPROC glad_glCopyTexSubImage2D = NULL; +PFNGLCOPYTEXSUBIMAGE3DPROC glad_glCopyTexSubImage3D = NULL; +PFNGLCREATEPROGRAMPROC glad_glCreateProgram = NULL; +PFNGLCREATESHADERPROC glad_glCreateShader = NULL; +PFNGLCULLFACEPROC glad_glCullFace = NULL; +PFNGLDELETEBUFFERSPROC glad_glDeleteBuffers = NULL; +PFNGLDELETELISTSPROC glad_glDeleteLists = NULL; +PFNGLDELETEPROGRAMPROC glad_glDeleteProgram = NULL; +PFNGLDELETEQUERIESPROC glad_glDeleteQueries = NULL; +PFNGLDELETESHADERPROC glad_glDeleteShader = NULL; +PFNGLDELETETEXTURESPROC glad_glDeleteTextures = NULL; +PFNGLDEPTHFUNCPROC glad_glDepthFunc = NULL; +PFNGLDEPTHMASKPROC glad_glDepthMask = NULL; +PFNGLDEPTHRANGEPROC glad_glDepthRange = NULL; +PFNGLDETACHSHADERPROC glad_glDetachShader = NULL; +PFNGLDISABLEPROC glad_glDisable = NULL; +PFNGLDISABLECLIENTSTATEPROC glad_glDisableClientState = NULL; +PFNGLDISABLEVERTEXATTRIBARRAYPROC glad_glDisableVertexAttribArray = NULL; +PFNGLDRAWARRAYSPROC glad_glDrawArrays = NULL; +PFNGLDRAWBUFFERPROC glad_glDrawBuffer = NULL; +PFNGLDRAWBUFFERSPROC glad_glDrawBuffers = NULL; +PFNGLDRAWELEMENTSPROC glad_glDrawElements = NULL; +PFNGLDRAWPIXELSPROC glad_glDrawPixels = NULL; +PFNGLDRAWRANGEELEMENTSPROC glad_glDrawRangeElements = NULL; +PFNGLEDGEFLAGPROC glad_glEdgeFlag = NULL; +PFNGLEDGEFLAGPOINTERPROC glad_glEdgeFlagPointer = NULL; +PFNGLEDGEFLAGVPROC glad_glEdgeFlagv = NULL; +PFNGLENABLEPROC glad_glEnable = NULL; +PFNGLENABLECLIENTSTATEPROC glad_glEnableClientState = NULL; +PFNGLENABLEVERTEXATTRIBARRAYPROC glad_glEnableVertexAttribArray = NULL; +PFNGLENDPROC glad_glEnd = NULL; +PFNGLENDLISTPROC glad_glEndList = NULL; +PFNGLENDQUERYPROC glad_glEndQuery = NULL; +PFNGLEVALCOORD1DPROC glad_glEvalCoord1d = NULL; +PFNGLEVALCOORD1DVPROC glad_glEvalCoord1dv = NULL; +PFNGLEVALCOORD1FPROC glad_glEvalCoord1f = NULL; +PFNGLEVALCOORD1FVPROC glad_glEvalCoord1fv = NULL; +PFNGLEVALCOORD2DPROC glad_glEvalCoord2d = NULL; +PFNGLEVALCOORD2DVPROC glad_glEvalCoord2dv = NULL; +PFNGLEVALCOORD2FPROC glad_glEvalCoord2f = NULL; +PFNGLEVALCOORD2FVPROC glad_glEvalCoord2fv = NULL; +PFNGLEVALMESH1PROC glad_glEvalMesh1 = NULL; +PFNGLEVALMESH2PROC glad_glEvalMesh2 = NULL; +PFNGLEVALPOINT1PROC glad_glEvalPoint1 = NULL; +PFNGLEVALPOINT2PROC glad_glEvalPoint2 = NULL; +PFNGLFEEDBACKBUFFERPROC glad_glFeedbackBuffer = NULL; +PFNGLFINISHPROC glad_glFinish = NULL; +PFNGLFLUSHPROC glad_glFlush = NULL; +PFNGLFOGCOORDPOINTERPROC glad_glFogCoordPointer = NULL; +PFNGLFOGCOORDDPROC glad_glFogCoordd = NULL; +PFNGLFOGCOORDDVPROC glad_glFogCoorddv = NULL; +PFNGLFOGCOORDFPROC glad_glFogCoordf = NULL; +PFNGLFOGCOORDFVPROC glad_glFogCoordfv = NULL; +PFNGLFOGFPROC glad_glFogf = NULL; +PFNGLFOGFVPROC glad_glFogfv = NULL; +PFNGLFOGIPROC glad_glFogi = NULL; +PFNGLFOGIVPROC glad_glFogiv = NULL; +PFNGLFRONTFACEPROC glad_glFrontFace = NULL; +PFNGLFRUSTUMPROC glad_glFrustum = NULL; +PFNGLGENBUFFERSPROC glad_glGenBuffers = NULL; +PFNGLGENLISTSPROC glad_glGenLists = NULL; +PFNGLGENQUERIESPROC glad_glGenQueries = NULL; +PFNGLGENTEXTURESPROC glad_glGenTextures = NULL; +PFNGLGETACTIVEATTRIBPROC glad_glGetActiveAttrib = NULL; +PFNGLGETACTIVEUNIFORMPROC glad_glGetActiveUniform = NULL; +PFNGLGETATTACHEDSHADERSPROC glad_glGetAttachedShaders = NULL; +PFNGLGETATTRIBLOCATIONPROC glad_glGetAttribLocation = NULL; +PFNGLGETBOOLEANVPROC glad_glGetBooleanv = NULL; +PFNGLGETBUFFERPARAMETERIVPROC glad_glGetBufferParameteriv = NULL; +PFNGLGETBUFFERPOINTERVPROC glad_glGetBufferPointerv = NULL; +PFNGLGETBUFFERSUBDATAPROC glad_glGetBufferSubData = NULL; +PFNGLGETCLIPPLANEPROC glad_glGetClipPlane = NULL; +PFNGLGETCOMPRESSEDTEXIMAGEPROC glad_glGetCompressedTexImage = NULL; +PFNGLGETDOUBLEVPROC glad_glGetDoublev = NULL; +PFNGLGETERRORPROC glad_glGetError = NULL; +PFNGLGETFLOATVPROC glad_glGetFloatv = NULL; +PFNGLGETINTEGERVPROC glad_glGetIntegerv = NULL; +PFNGLGETLIGHTFVPROC glad_glGetLightfv = NULL; +PFNGLGETLIGHTIVPROC glad_glGetLightiv = NULL; +PFNGLGETMAPDVPROC glad_glGetMapdv = NULL; +PFNGLGETMAPFVPROC glad_glGetMapfv = NULL; +PFNGLGETMAPIVPROC glad_glGetMapiv = NULL; +PFNGLGETMATERIALFVPROC glad_glGetMaterialfv = NULL; +PFNGLGETMATERIALIVPROC glad_glGetMaterialiv = NULL; +PFNGLGETPIXELMAPFVPROC glad_glGetPixelMapfv = NULL; +PFNGLGETPIXELMAPUIVPROC glad_glGetPixelMapuiv = NULL; +PFNGLGETPIXELMAPUSVPROC glad_glGetPixelMapusv = NULL; +PFNGLGETPOINTERVPROC glad_glGetPointerv = NULL; +PFNGLGETPOLYGONSTIPPLEPROC glad_glGetPolygonStipple = NULL; +PFNGLGETPROGRAMINFOLOGPROC glad_glGetProgramInfoLog = NULL; +PFNGLGETPROGRAMIVPROC glad_glGetProgramiv = NULL; +PFNGLGETQUERYOBJECTIVPROC glad_glGetQueryObjectiv = NULL; +PFNGLGETQUERYOBJECTUIVPROC glad_glGetQueryObjectuiv = NULL; +PFNGLGETQUERYIVPROC glad_glGetQueryiv = NULL; +PFNGLGETSHADERINFOLOGPROC glad_glGetShaderInfoLog = NULL; +PFNGLGETSHADERSOURCEPROC glad_glGetShaderSource = NULL; +PFNGLGETSHADERIVPROC glad_glGetShaderiv = NULL; +PFNGLGETSTRINGPROC glad_glGetString = NULL; +PFNGLGETTEXENVFVPROC glad_glGetTexEnvfv = NULL; +PFNGLGETTEXENVIVPROC glad_glGetTexEnviv = NULL; +PFNGLGETTEXGENDVPROC glad_glGetTexGendv = NULL; +PFNGLGETTEXGENFVPROC glad_glGetTexGenfv = NULL; +PFNGLGETTEXGENIVPROC glad_glGetTexGeniv = NULL; +PFNGLGETTEXIMAGEPROC glad_glGetTexImage = NULL; +PFNGLGETTEXLEVELPARAMETERFVPROC glad_glGetTexLevelParameterfv = NULL; +PFNGLGETTEXLEVELPARAMETERIVPROC glad_glGetTexLevelParameteriv = NULL; +PFNGLGETTEXPARAMETERFVPROC glad_glGetTexParameterfv = NULL; +PFNGLGETTEXPARAMETERIVPROC glad_glGetTexParameteriv = NULL; +PFNGLGETUNIFORMLOCATIONPROC glad_glGetUniformLocation = NULL; +PFNGLGETUNIFORMFVPROC glad_glGetUniformfv = NULL; +PFNGLGETUNIFORMIVPROC glad_glGetUniformiv = NULL; +PFNGLGETVERTEXATTRIBPOINTERVPROC glad_glGetVertexAttribPointerv = NULL; +PFNGLGETVERTEXATTRIBDVPROC glad_glGetVertexAttribdv = NULL; +PFNGLGETVERTEXATTRIBFVPROC glad_glGetVertexAttribfv = NULL; +PFNGLGETVERTEXATTRIBIVPROC glad_glGetVertexAttribiv = NULL; +PFNGLHINTPROC glad_glHint = NULL; +PFNGLINDEXMASKPROC glad_glIndexMask = NULL; +PFNGLINDEXPOINTERPROC glad_glIndexPointer = NULL; +PFNGLINDEXDPROC glad_glIndexd = NULL; +PFNGLINDEXDVPROC glad_glIndexdv = NULL; +PFNGLINDEXFPROC glad_glIndexf = NULL; +PFNGLINDEXFVPROC glad_glIndexfv = NULL; +PFNGLINDEXIPROC glad_glIndexi = NULL; +PFNGLINDEXIVPROC glad_glIndexiv = NULL; +PFNGLINDEXSPROC glad_glIndexs = NULL; +PFNGLINDEXSVPROC glad_glIndexsv = NULL; +PFNGLINDEXUBPROC glad_glIndexub = NULL; +PFNGLINDEXUBVPROC glad_glIndexubv = NULL; +PFNGLINITNAMESPROC glad_glInitNames = NULL; +PFNGLINTERLEAVEDARRAYSPROC glad_glInterleavedArrays = NULL; +PFNGLISBUFFERPROC glad_glIsBuffer = NULL; +PFNGLISENABLEDPROC glad_glIsEnabled = NULL; +PFNGLISLISTPROC glad_glIsList = NULL; +PFNGLISPROGRAMPROC glad_glIsProgram = NULL; +PFNGLISQUERYPROC glad_glIsQuery = NULL; +PFNGLISSHADERPROC glad_glIsShader = NULL; +PFNGLISTEXTUREPROC glad_glIsTexture = NULL; +PFNGLLIGHTMODELFPROC glad_glLightModelf = NULL; +PFNGLLIGHTMODELFVPROC glad_glLightModelfv = NULL; +PFNGLLIGHTMODELIPROC glad_glLightModeli = NULL; +PFNGLLIGHTMODELIVPROC glad_glLightModeliv = NULL; +PFNGLLIGHTFPROC glad_glLightf = NULL; +PFNGLLIGHTFVPROC glad_glLightfv = NULL; +PFNGLLIGHTIPROC glad_glLighti = NULL; +PFNGLLIGHTIVPROC glad_glLightiv = NULL; +PFNGLLINESTIPPLEPROC glad_glLineStipple = NULL; +PFNGLLINEWIDTHPROC glad_glLineWidth = NULL; +PFNGLLINKPROGRAMPROC glad_glLinkProgram = NULL; +PFNGLLISTBASEPROC glad_glListBase = NULL; +PFNGLLOADIDENTITYPROC glad_glLoadIdentity = NULL; +PFNGLLOADMATRIXDPROC glad_glLoadMatrixd = NULL; +PFNGLLOADMATRIXFPROC glad_glLoadMatrixf = NULL; +PFNGLLOADNAMEPROC glad_glLoadName = NULL; +PFNGLLOADTRANSPOSEMATRIXDPROC glad_glLoadTransposeMatrixd = NULL; +PFNGLLOADTRANSPOSEMATRIXFPROC glad_glLoadTransposeMatrixf = NULL; +PFNGLLOGICOPPROC glad_glLogicOp = NULL; +PFNGLMAP1DPROC glad_glMap1d = NULL; +PFNGLMAP1FPROC glad_glMap1f = NULL; +PFNGLMAP2DPROC glad_glMap2d = NULL; +PFNGLMAP2FPROC glad_glMap2f = NULL; +PFNGLMAPBUFFERPROC glad_glMapBuffer = NULL; +PFNGLMAPGRID1DPROC glad_glMapGrid1d = NULL; +PFNGLMAPGRID1FPROC glad_glMapGrid1f = NULL; +PFNGLMAPGRID2DPROC glad_glMapGrid2d = NULL; +PFNGLMAPGRID2FPROC glad_glMapGrid2f = NULL; +PFNGLMATERIALFPROC glad_glMaterialf = NULL; +PFNGLMATERIALFVPROC glad_glMaterialfv = NULL; +PFNGLMATERIALIPROC glad_glMateriali = NULL; +PFNGLMATERIALIVPROC glad_glMaterialiv = NULL; +PFNGLMATRIXMODEPROC glad_glMatrixMode = NULL; +PFNGLMULTMATRIXDPROC glad_glMultMatrixd = NULL; +PFNGLMULTMATRIXFPROC glad_glMultMatrixf = NULL; +PFNGLMULTTRANSPOSEMATRIXDPROC glad_glMultTransposeMatrixd = NULL; +PFNGLMULTTRANSPOSEMATRIXFPROC glad_glMultTransposeMatrixf = NULL; +PFNGLMULTIDRAWARRAYSPROC glad_glMultiDrawArrays = NULL; +PFNGLMULTIDRAWELEMENTSPROC glad_glMultiDrawElements = NULL; +PFNGLMULTITEXCOORD1DPROC glad_glMultiTexCoord1d = NULL; +PFNGLMULTITEXCOORD1DVPROC glad_glMultiTexCoord1dv = NULL; +PFNGLMULTITEXCOORD1FPROC glad_glMultiTexCoord1f = NULL; +PFNGLMULTITEXCOORD1FVPROC glad_glMultiTexCoord1fv = NULL; +PFNGLMULTITEXCOORD1IPROC glad_glMultiTexCoord1i = NULL; +PFNGLMULTITEXCOORD1IVPROC glad_glMultiTexCoord1iv = NULL; +PFNGLMULTITEXCOORD1SPROC glad_glMultiTexCoord1s = NULL; +PFNGLMULTITEXCOORD1SVPROC glad_glMultiTexCoord1sv = NULL; +PFNGLMULTITEXCOORD2DPROC glad_glMultiTexCoord2d = NULL; +PFNGLMULTITEXCOORD2DVPROC glad_glMultiTexCoord2dv = NULL; +PFNGLMULTITEXCOORD2FPROC glad_glMultiTexCoord2f = NULL; +PFNGLMULTITEXCOORD2FVPROC glad_glMultiTexCoord2fv = NULL; +PFNGLMULTITEXCOORD2IPROC glad_glMultiTexCoord2i = NULL; +PFNGLMULTITEXCOORD2IVPROC glad_glMultiTexCoord2iv = NULL; +PFNGLMULTITEXCOORD2SPROC glad_glMultiTexCoord2s = NULL; +PFNGLMULTITEXCOORD2SVPROC glad_glMultiTexCoord2sv = NULL; +PFNGLMULTITEXCOORD3DPROC glad_glMultiTexCoord3d = NULL; +PFNGLMULTITEXCOORD3DVPROC glad_glMultiTexCoord3dv = NULL; +PFNGLMULTITEXCOORD3FPROC glad_glMultiTexCoord3f = NULL; +PFNGLMULTITEXCOORD3FVPROC glad_glMultiTexCoord3fv = NULL; +PFNGLMULTITEXCOORD3IPROC glad_glMultiTexCoord3i = NULL; +PFNGLMULTITEXCOORD3IVPROC glad_glMultiTexCoord3iv = NULL; +PFNGLMULTITEXCOORD3SPROC glad_glMultiTexCoord3s = NULL; +PFNGLMULTITEXCOORD3SVPROC glad_glMultiTexCoord3sv = NULL; +PFNGLMULTITEXCOORD4DPROC glad_glMultiTexCoord4d = NULL; +PFNGLMULTITEXCOORD4DVPROC glad_glMultiTexCoord4dv = NULL; +PFNGLMULTITEXCOORD4FPROC glad_glMultiTexCoord4f = NULL; +PFNGLMULTITEXCOORD4FVPROC glad_glMultiTexCoord4fv = NULL; +PFNGLMULTITEXCOORD4IPROC glad_glMultiTexCoord4i = NULL; +PFNGLMULTITEXCOORD4IVPROC glad_glMultiTexCoord4iv = NULL; +PFNGLMULTITEXCOORD4SPROC glad_glMultiTexCoord4s = NULL; +PFNGLMULTITEXCOORD4SVPROC glad_glMultiTexCoord4sv = NULL; +PFNGLNEWLISTPROC glad_glNewList = NULL; +PFNGLNORMAL3BPROC glad_glNormal3b = NULL; +PFNGLNORMAL3BVPROC glad_glNormal3bv = NULL; +PFNGLNORMAL3DPROC glad_glNormal3d = NULL; +PFNGLNORMAL3DVPROC glad_glNormal3dv = NULL; +PFNGLNORMAL3FPROC glad_glNormal3f = NULL; +PFNGLNORMAL3FVPROC glad_glNormal3fv = NULL; +PFNGLNORMAL3IPROC glad_glNormal3i = NULL; +PFNGLNORMAL3IVPROC glad_glNormal3iv = NULL; +PFNGLNORMAL3SPROC glad_glNormal3s = NULL; +PFNGLNORMAL3SVPROC glad_glNormal3sv = NULL; +PFNGLNORMALPOINTERPROC glad_glNormalPointer = NULL; +PFNGLORTHOPROC glad_glOrtho = NULL; +PFNGLPASSTHROUGHPROC glad_glPassThrough = NULL; +PFNGLPIXELMAPFVPROC glad_glPixelMapfv = NULL; +PFNGLPIXELMAPUIVPROC glad_glPixelMapuiv = NULL; +PFNGLPIXELMAPUSVPROC glad_glPixelMapusv = NULL; +PFNGLPIXELSTOREFPROC glad_glPixelStoref = NULL; +PFNGLPIXELSTOREIPROC glad_glPixelStorei = NULL; +PFNGLPIXELTRANSFERFPROC glad_glPixelTransferf = NULL; +PFNGLPIXELTRANSFERIPROC glad_glPixelTransferi = NULL; +PFNGLPIXELZOOMPROC glad_glPixelZoom = NULL; +PFNGLPOINTPARAMETERFPROC glad_glPointParameterf = NULL; +PFNGLPOINTPARAMETERFVPROC glad_glPointParameterfv = NULL; +PFNGLPOINTPARAMETERIPROC glad_glPointParameteri = NULL; +PFNGLPOINTPARAMETERIVPROC glad_glPointParameteriv = NULL; +PFNGLPOINTSIZEPROC glad_glPointSize = NULL; +PFNGLPOLYGONMODEPROC glad_glPolygonMode = NULL; +PFNGLPOLYGONOFFSETPROC glad_glPolygonOffset = NULL; +PFNGLPOLYGONSTIPPLEPROC glad_glPolygonStipple = NULL; +PFNGLPOPATTRIBPROC glad_glPopAttrib = NULL; +PFNGLPOPCLIENTATTRIBPROC glad_glPopClientAttrib = NULL; +PFNGLPOPMATRIXPROC glad_glPopMatrix = NULL; +PFNGLPOPNAMEPROC glad_glPopName = NULL; +PFNGLPRIORITIZETEXTURESPROC glad_glPrioritizeTextures = NULL; +PFNGLPUSHATTRIBPROC glad_glPushAttrib = NULL; +PFNGLPUSHCLIENTATTRIBPROC glad_glPushClientAttrib = NULL; +PFNGLPUSHMATRIXPROC glad_glPushMatrix = NULL; +PFNGLPUSHNAMEPROC glad_glPushName = NULL; +PFNGLRASTERPOS2DPROC glad_glRasterPos2d = NULL; +PFNGLRASTERPOS2DVPROC glad_glRasterPos2dv = NULL; +PFNGLRASTERPOS2FPROC glad_glRasterPos2f = NULL; +PFNGLRASTERPOS2FVPROC glad_glRasterPos2fv = NULL; +PFNGLRASTERPOS2IPROC glad_glRasterPos2i = NULL; +PFNGLRASTERPOS2IVPROC glad_glRasterPos2iv = NULL; +PFNGLRASTERPOS2SPROC glad_glRasterPos2s = NULL; +PFNGLRASTERPOS2SVPROC glad_glRasterPos2sv = NULL; +PFNGLRASTERPOS3DPROC glad_glRasterPos3d = NULL; +PFNGLRASTERPOS3DVPROC glad_glRasterPos3dv = NULL; +PFNGLRASTERPOS3FPROC glad_glRasterPos3f = NULL; +PFNGLRASTERPOS3FVPROC glad_glRasterPos3fv = NULL; +PFNGLRASTERPOS3IPROC glad_glRasterPos3i = NULL; +PFNGLRASTERPOS3IVPROC glad_glRasterPos3iv = NULL; +PFNGLRASTERPOS3SPROC glad_glRasterPos3s = NULL; +PFNGLRASTERPOS3SVPROC glad_glRasterPos3sv = NULL; +PFNGLRASTERPOS4DPROC glad_glRasterPos4d = NULL; +PFNGLRASTERPOS4DVPROC glad_glRasterPos4dv = NULL; +PFNGLRASTERPOS4FPROC glad_glRasterPos4f = NULL; +PFNGLRASTERPOS4FVPROC glad_glRasterPos4fv = NULL; +PFNGLRASTERPOS4IPROC glad_glRasterPos4i = NULL; +PFNGLRASTERPOS4IVPROC glad_glRasterPos4iv = NULL; +PFNGLRASTERPOS4SPROC glad_glRasterPos4s = NULL; +PFNGLRASTERPOS4SVPROC glad_glRasterPos4sv = NULL; +PFNGLREADBUFFERPROC glad_glReadBuffer = NULL; +PFNGLREADPIXELSPROC glad_glReadPixels = NULL; +PFNGLRECTDPROC glad_glRectd = NULL; +PFNGLRECTDVPROC glad_glRectdv = NULL; +PFNGLRECTFPROC glad_glRectf = NULL; +PFNGLRECTFVPROC glad_glRectfv = NULL; +PFNGLRECTIPROC glad_glRecti = NULL; +PFNGLRECTIVPROC glad_glRectiv = NULL; +PFNGLRECTSPROC glad_glRects = NULL; +PFNGLRECTSVPROC glad_glRectsv = NULL; +PFNGLRENDERMODEPROC glad_glRenderMode = NULL; +PFNGLROTATEDPROC glad_glRotated = NULL; +PFNGLROTATEFPROC glad_glRotatef = NULL; +PFNGLSAMPLECOVERAGEPROC glad_glSampleCoverage = NULL; +PFNGLSCALEDPROC glad_glScaled = NULL; +PFNGLSCALEFPROC glad_glScalef = NULL; +PFNGLSCISSORPROC glad_glScissor = NULL; +PFNGLSECONDARYCOLOR3BPROC glad_glSecondaryColor3b = NULL; +PFNGLSECONDARYCOLOR3BVPROC glad_glSecondaryColor3bv = NULL; +PFNGLSECONDARYCOLOR3DPROC glad_glSecondaryColor3d = NULL; +PFNGLSECONDARYCOLOR3DVPROC glad_glSecondaryColor3dv = NULL; +PFNGLSECONDARYCOLOR3FPROC glad_glSecondaryColor3f = NULL; +PFNGLSECONDARYCOLOR3FVPROC glad_glSecondaryColor3fv = NULL; +PFNGLSECONDARYCOLOR3IPROC glad_glSecondaryColor3i = NULL; +PFNGLSECONDARYCOLOR3IVPROC glad_glSecondaryColor3iv = NULL; +PFNGLSECONDARYCOLOR3SPROC glad_glSecondaryColor3s = NULL; +PFNGLSECONDARYCOLOR3SVPROC glad_glSecondaryColor3sv = NULL; +PFNGLSECONDARYCOLOR3UBPROC glad_glSecondaryColor3ub = NULL; +PFNGLSECONDARYCOLOR3UBVPROC glad_glSecondaryColor3ubv = NULL; +PFNGLSECONDARYCOLOR3UIPROC glad_glSecondaryColor3ui = NULL; +PFNGLSECONDARYCOLOR3UIVPROC glad_glSecondaryColor3uiv = NULL; +PFNGLSECONDARYCOLOR3USPROC glad_glSecondaryColor3us = NULL; +PFNGLSECONDARYCOLOR3USVPROC glad_glSecondaryColor3usv = NULL; +PFNGLSECONDARYCOLORPOINTERPROC glad_glSecondaryColorPointer = NULL; +PFNGLSELECTBUFFERPROC glad_glSelectBuffer = NULL; +PFNGLSHADEMODELPROC glad_glShadeModel = NULL; +PFNGLSHADERSOURCEPROC glad_glShaderSource = NULL; +PFNGLSTENCILFUNCPROC glad_glStencilFunc = NULL; +PFNGLSTENCILFUNCSEPARATEPROC glad_glStencilFuncSeparate = NULL; +PFNGLSTENCILMASKPROC glad_glStencilMask = NULL; +PFNGLSTENCILMASKSEPARATEPROC glad_glStencilMaskSeparate = NULL; +PFNGLSTENCILOPPROC glad_glStencilOp = NULL; +PFNGLSTENCILOPSEPARATEPROC glad_glStencilOpSeparate = NULL; +PFNGLTEXCOORD1DPROC glad_glTexCoord1d = NULL; +PFNGLTEXCOORD1DVPROC glad_glTexCoord1dv = NULL; +PFNGLTEXCOORD1FPROC glad_glTexCoord1f = NULL; +PFNGLTEXCOORD1FVPROC glad_glTexCoord1fv = NULL; +PFNGLTEXCOORD1IPROC glad_glTexCoord1i = NULL; +PFNGLTEXCOORD1IVPROC glad_glTexCoord1iv = NULL; +PFNGLTEXCOORD1SPROC glad_glTexCoord1s = NULL; +PFNGLTEXCOORD1SVPROC glad_glTexCoord1sv = NULL; +PFNGLTEXCOORD2DPROC glad_glTexCoord2d = NULL; +PFNGLTEXCOORD2DVPROC glad_glTexCoord2dv = NULL; +PFNGLTEXCOORD2FPROC glad_glTexCoord2f = NULL; +PFNGLTEXCOORD2FVPROC glad_glTexCoord2fv = NULL; +PFNGLTEXCOORD2IPROC glad_glTexCoord2i = NULL; +PFNGLTEXCOORD2IVPROC glad_glTexCoord2iv = NULL; +PFNGLTEXCOORD2SPROC glad_glTexCoord2s = NULL; +PFNGLTEXCOORD2SVPROC glad_glTexCoord2sv = NULL; +PFNGLTEXCOORD3DPROC glad_glTexCoord3d = NULL; +PFNGLTEXCOORD3DVPROC glad_glTexCoord3dv = NULL; +PFNGLTEXCOORD3FPROC glad_glTexCoord3f = NULL; +PFNGLTEXCOORD3FVPROC glad_glTexCoord3fv = NULL; +PFNGLTEXCOORD3IPROC glad_glTexCoord3i = NULL; +PFNGLTEXCOORD3IVPROC glad_glTexCoord3iv = NULL; +PFNGLTEXCOORD3SPROC glad_glTexCoord3s = NULL; +PFNGLTEXCOORD3SVPROC glad_glTexCoord3sv = NULL; +PFNGLTEXCOORD4DPROC glad_glTexCoord4d = NULL; +PFNGLTEXCOORD4DVPROC glad_glTexCoord4dv = NULL; +PFNGLTEXCOORD4FPROC glad_glTexCoord4f = NULL; +PFNGLTEXCOORD4FVPROC glad_glTexCoord4fv = NULL; +PFNGLTEXCOORD4IPROC glad_glTexCoord4i = NULL; +PFNGLTEXCOORD4IVPROC glad_glTexCoord4iv = NULL; +PFNGLTEXCOORD4SPROC glad_glTexCoord4s = NULL; +PFNGLTEXCOORD4SVPROC glad_glTexCoord4sv = NULL; +PFNGLTEXCOORDPOINTERPROC glad_glTexCoordPointer = NULL; +PFNGLTEXENVFPROC glad_glTexEnvf = NULL; +PFNGLTEXENVFVPROC glad_glTexEnvfv = NULL; +PFNGLTEXENVIPROC glad_glTexEnvi = NULL; +PFNGLTEXENVIVPROC glad_glTexEnviv = NULL; +PFNGLTEXGENDPROC glad_glTexGend = NULL; +PFNGLTEXGENDVPROC glad_glTexGendv = NULL; +PFNGLTEXGENFPROC glad_glTexGenf = NULL; +PFNGLTEXGENFVPROC glad_glTexGenfv = NULL; +PFNGLTEXGENIPROC glad_glTexGeni = NULL; +PFNGLTEXGENIVPROC glad_glTexGeniv = NULL; +PFNGLTEXIMAGE1DPROC glad_glTexImage1D = NULL; +PFNGLTEXIMAGE2DPROC glad_glTexImage2D = NULL; +PFNGLTEXIMAGE3DPROC glad_glTexImage3D = NULL; +PFNGLTEXPARAMETERFPROC glad_glTexParameterf = NULL; +PFNGLTEXPARAMETERFVPROC glad_glTexParameterfv = NULL; +PFNGLTEXPARAMETERIPROC glad_glTexParameteri = NULL; +PFNGLTEXPARAMETERIVPROC glad_glTexParameteriv = NULL; +PFNGLTEXSUBIMAGE1DPROC glad_glTexSubImage1D = NULL; +PFNGLTEXSUBIMAGE2DPROC glad_glTexSubImage2D = NULL; +PFNGLTEXSUBIMAGE3DPROC glad_glTexSubImage3D = NULL; +PFNGLTRANSLATEDPROC glad_glTranslated = NULL; +PFNGLTRANSLATEFPROC glad_glTranslatef = NULL; +PFNGLUNIFORM1FPROC glad_glUniform1f = NULL; +PFNGLUNIFORM1FVPROC glad_glUniform1fv = NULL; +PFNGLUNIFORM1IPROC glad_glUniform1i = NULL; +PFNGLUNIFORM1IVPROC glad_glUniform1iv = NULL; +PFNGLUNIFORM2FPROC glad_glUniform2f = NULL; +PFNGLUNIFORM2FVPROC glad_glUniform2fv = NULL; +PFNGLUNIFORM2IPROC glad_glUniform2i = NULL; +PFNGLUNIFORM2IVPROC glad_glUniform2iv = NULL; +PFNGLUNIFORM3FPROC glad_glUniform3f = NULL; +PFNGLUNIFORM3FVPROC glad_glUniform3fv = NULL; +PFNGLUNIFORM3IPROC glad_glUniform3i = NULL; +PFNGLUNIFORM3IVPROC glad_glUniform3iv = NULL; +PFNGLUNIFORM4FPROC glad_glUniform4f = NULL; +PFNGLUNIFORM4FVPROC glad_glUniform4fv = NULL; +PFNGLUNIFORM4IPROC glad_glUniform4i = NULL; +PFNGLUNIFORM4IVPROC glad_glUniform4iv = NULL; +PFNGLUNIFORMMATRIX2FVPROC glad_glUniformMatrix2fv = NULL; +PFNGLUNIFORMMATRIX3FVPROC glad_glUniformMatrix3fv = NULL; +PFNGLUNIFORMMATRIX4FVPROC glad_glUniformMatrix4fv = NULL; +PFNGLUNMAPBUFFERPROC glad_glUnmapBuffer = NULL; +PFNGLUSEPROGRAMPROC glad_glUseProgram = NULL; +PFNGLVALIDATEPROGRAMPROC glad_glValidateProgram = NULL; +PFNGLVERTEX2DPROC glad_glVertex2d = NULL; +PFNGLVERTEX2DVPROC glad_glVertex2dv = NULL; +PFNGLVERTEX2FPROC glad_glVertex2f = NULL; +PFNGLVERTEX2FVPROC glad_glVertex2fv = NULL; +PFNGLVERTEX2IPROC glad_glVertex2i = NULL; +PFNGLVERTEX2IVPROC glad_glVertex2iv = NULL; +PFNGLVERTEX2SPROC glad_glVertex2s = NULL; +PFNGLVERTEX2SVPROC glad_glVertex2sv = NULL; +PFNGLVERTEX3DPROC glad_glVertex3d = NULL; +PFNGLVERTEX3DVPROC glad_glVertex3dv = NULL; +PFNGLVERTEX3FPROC glad_glVertex3f = NULL; +PFNGLVERTEX3FVPROC glad_glVertex3fv = NULL; +PFNGLVERTEX3IPROC glad_glVertex3i = NULL; +PFNGLVERTEX3IVPROC glad_glVertex3iv = NULL; +PFNGLVERTEX3SPROC glad_glVertex3s = NULL; +PFNGLVERTEX3SVPROC glad_glVertex3sv = NULL; +PFNGLVERTEX4DPROC glad_glVertex4d = NULL; +PFNGLVERTEX4DVPROC glad_glVertex4dv = NULL; +PFNGLVERTEX4FPROC glad_glVertex4f = NULL; +PFNGLVERTEX4FVPROC glad_glVertex4fv = NULL; +PFNGLVERTEX4IPROC glad_glVertex4i = NULL; +PFNGLVERTEX4IVPROC glad_glVertex4iv = NULL; +PFNGLVERTEX4SPROC glad_glVertex4s = NULL; +PFNGLVERTEX4SVPROC glad_glVertex4sv = NULL; +PFNGLVERTEXATTRIB1DPROC glad_glVertexAttrib1d = NULL; +PFNGLVERTEXATTRIB1DVPROC glad_glVertexAttrib1dv = NULL; +PFNGLVERTEXATTRIB1FPROC glad_glVertexAttrib1f = NULL; +PFNGLVERTEXATTRIB1FVPROC glad_glVertexAttrib1fv = NULL; +PFNGLVERTEXATTRIB1SPROC glad_glVertexAttrib1s = NULL; +PFNGLVERTEXATTRIB1SVPROC glad_glVertexAttrib1sv = NULL; +PFNGLVERTEXATTRIB2DPROC glad_glVertexAttrib2d = NULL; +PFNGLVERTEXATTRIB2DVPROC glad_glVertexAttrib2dv = NULL; +PFNGLVERTEXATTRIB2FPROC glad_glVertexAttrib2f = NULL; +PFNGLVERTEXATTRIB2FVPROC glad_glVertexAttrib2fv = NULL; +PFNGLVERTEXATTRIB2SPROC glad_glVertexAttrib2s = NULL; +PFNGLVERTEXATTRIB2SVPROC glad_glVertexAttrib2sv = NULL; +PFNGLVERTEXATTRIB3DPROC glad_glVertexAttrib3d = NULL; +PFNGLVERTEXATTRIB3DVPROC glad_glVertexAttrib3dv = NULL; +PFNGLVERTEXATTRIB3FPROC glad_glVertexAttrib3f = NULL; +PFNGLVERTEXATTRIB3FVPROC glad_glVertexAttrib3fv = NULL; +PFNGLVERTEXATTRIB3SPROC glad_glVertexAttrib3s = NULL; +PFNGLVERTEXATTRIB3SVPROC glad_glVertexAttrib3sv = NULL; +PFNGLVERTEXATTRIB4NBVPROC glad_glVertexAttrib4Nbv = NULL; +PFNGLVERTEXATTRIB4NIVPROC glad_glVertexAttrib4Niv = NULL; +PFNGLVERTEXATTRIB4NSVPROC glad_glVertexAttrib4Nsv = NULL; +PFNGLVERTEXATTRIB4NUBPROC glad_glVertexAttrib4Nub = NULL; +PFNGLVERTEXATTRIB4NUBVPROC glad_glVertexAttrib4Nubv = NULL; +PFNGLVERTEXATTRIB4NUIVPROC glad_glVertexAttrib4Nuiv = NULL; +PFNGLVERTEXATTRIB4NUSVPROC glad_glVertexAttrib4Nusv = NULL; +PFNGLVERTEXATTRIB4BVPROC glad_glVertexAttrib4bv = NULL; +PFNGLVERTEXATTRIB4DPROC glad_glVertexAttrib4d = NULL; +PFNGLVERTEXATTRIB4DVPROC glad_glVertexAttrib4dv = NULL; +PFNGLVERTEXATTRIB4FPROC glad_glVertexAttrib4f = NULL; +PFNGLVERTEXATTRIB4FVPROC glad_glVertexAttrib4fv = NULL; +PFNGLVERTEXATTRIB4IVPROC glad_glVertexAttrib4iv = NULL; +PFNGLVERTEXATTRIB4SPROC glad_glVertexAttrib4s = NULL; +PFNGLVERTEXATTRIB4SVPROC glad_glVertexAttrib4sv = NULL; +PFNGLVERTEXATTRIB4UBVPROC glad_glVertexAttrib4ubv = NULL; +PFNGLVERTEXATTRIB4UIVPROC glad_glVertexAttrib4uiv = NULL; +PFNGLVERTEXATTRIB4USVPROC glad_glVertexAttrib4usv = NULL; +PFNGLVERTEXATTRIBPOINTERPROC glad_glVertexAttribPointer = NULL; +PFNGLVERTEXPOINTERPROC glad_glVertexPointer = NULL; +PFNGLVIEWPORTPROC glad_glViewport = NULL; +PFNGLWINDOWPOS2DPROC glad_glWindowPos2d = NULL; +PFNGLWINDOWPOS2DVPROC glad_glWindowPos2dv = NULL; +PFNGLWINDOWPOS2FPROC glad_glWindowPos2f = NULL; +PFNGLWINDOWPOS2FVPROC glad_glWindowPos2fv = NULL; +PFNGLWINDOWPOS2IPROC glad_glWindowPos2i = NULL; +PFNGLWINDOWPOS2IVPROC glad_glWindowPos2iv = NULL; +PFNGLWINDOWPOS2SPROC glad_glWindowPos2s = NULL; +PFNGLWINDOWPOS2SVPROC glad_glWindowPos2sv = NULL; +PFNGLWINDOWPOS3DPROC glad_glWindowPos3d = NULL; +PFNGLWINDOWPOS3DVPROC glad_glWindowPos3dv = NULL; +PFNGLWINDOWPOS3FPROC glad_glWindowPos3f = NULL; +PFNGLWINDOWPOS3FVPROC glad_glWindowPos3fv = NULL; +PFNGLWINDOWPOS3IPROC glad_glWindowPos3i = NULL; +PFNGLWINDOWPOS3IVPROC glad_glWindowPos3iv = NULL; +PFNGLWINDOWPOS3SPROC glad_glWindowPos3s = NULL; +PFNGLWINDOWPOS3SVPROC glad_glWindowPos3sv = NULL; +static void load_GL_VERSION_1_0(GLADloadproc load) { + if(!GLAD_GL_VERSION_1_0) return; + glad_glCullFace = (PFNGLCULLFACEPROC)load("glCullFace"); + glad_glFrontFace = (PFNGLFRONTFACEPROC)load("glFrontFace"); + glad_glHint = (PFNGLHINTPROC)load("glHint"); + glad_glLineWidth = (PFNGLLINEWIDTHPROC)load("glLineWidth"); + glad_glPointSize = (PFNGLPOINTSIZEPROC)load("glPointSize"); + glad_glPolygonMode = (PFNGLPOLYGONMODEPROC)load("glPolygonMode"); + glad_glScissor = (PFNGLSCISSORPROC)load("glScissor"); + glad_glTexParameterf = (PFNGLTEXPARAMETERFPROC)load("glTexParameterf"); + glad_glTexParameterfv = (PFNGLTEXPARAMETERFVPROC)load("glTexParameterfv"); + glad_glTexParameteri = (PFNGLTEXPARAMETERIPROC)load("glTexParameteri"); + glad_glTexParameteriv = (PFNGLTEXPARAMETERIVPROC)load("glTexParameteriv"); + glad_glTexImage1D = (PFNGLTEXIMAGE1DPROC)load("glTexImage1D"); + glad_glTexImage2D = (PFNGLTEXIMAGE2DPROC)load("glTexImage2D"); + glad_glDrawBuffer = (PFNGLDRAWBUFFERPROC)load("glDrawBuffer"); + glad_glClear = (PFNGLCLEARPROC)load("glClear"); + glad_glClearColor = (PFNGLCLEARCOLORPROC)load("glClearColor"); + glad_glClearStencil = (PFNGLCLEARSTENCILPROC)load("glClearStencil"); + glad_glClearDepth = (PFNGLCLEARDEPTHPROC)load("glClearDepth"); + glad_glStencilMask = (PFNGLSTENCILMASKPROC)load("glStencilMask"); + glad_glColorMask = (PFNGLCOLORMASKPROC)load("glColorMask"); + glad_glDepthMask = (PFNGLDEPTHMASKPROC)load("glDepthMask"); + glad_glDisable = (PFNGLDISABLEPROC)load("glDisable"); + glad_glEnable = (PFNGLENABLEPROC)load("glEnable"); + glad_glFinish = (PFNGLFINISHPROC)load("glFinish"); + glad_glFlush = (PFNGLFLUSHPROC)load("glFlush"); + glad_glBlendFunc = (PFNGLBLENDFUNCPROC)load("glBlendFunc"); + glad_glLogicOp = (PFNGLLOGICOPPROC)load("glLogicOp"); + glad_glStencilFunc = (PFNGLSTENCILFUNCPROC)load("glStencilFunc"); + glad_glStencilOp = (PFNGLSTENCILOPPROC)load("glStencilOp"); + glad_glDepthFunc = (PFNGLDEPTHFUNCPROC)load("glDepthFunc"); + glad_glPixelStoref = (PFNGLPIXELSTOREFPROC)load("glPixelStoref"); + glad_glPixelStorei = (PFNGLPIXELSTOREIPROC)load("glPixelStorei"); + glad_glReadBuffer = (PFNGLREADBUFFERPROC)load("glReadBuffer"); + glad_glReadPixels = (PFNGLREADPIXELSPROC)load("glReadPixels"); + glad_glGetBooleanv = (PFNGLGETBOOLEANVPROC)load("glGetBooleanv"); + glad_glGetDoublev = (PFNGLGETDOUBLEVPROC)load("glGetDoublev"); + glad_glGetError = (PFNGLGETERRORPROC)load("glGetError"); + glad_glGetFloatv = (PFNGLGETFLOATVPROC)load("glGetFloatv"); + glad_glGetIntegerv = (PFNGLGETINTEGERVPROC)load("glGetIntegerv"); + glad_glGetString = (PFNGLGETSTRINGPROC)load("glGetString"); + glad_glGetTexImage = (PFNGLGETTEXIMAGEPROC)load("glGetTexImage"); + glad_glGetTexParameterfv = (PFNGLGETTEXPARAMETERFVPROC)load("glGetTexParameterfv"); + glad_glGetTexParameteriv = (PFNGLGETTEXPARAMETERIVPROC)load("glGetTexParameteriv"); + glad_glGetTexLevelParameterfv = (PFNGLGETTEXLEVELPARAMETERFVPROC)load("glGetTexLevelParameterfv"); + glad_glGetTexLevelParameteriv = (PFNGLGETTEXLEVELPARAMETERIVPROC)load("glGetTexLevelParameteriv"); + glad_glIsEnabled = (PFNGLISENABLEDPROC)load("glIsEnabled"); + glad_glDepthRange = (PFNGLDEPTHRANGEPROC)load("glDepthRange"); + glad_glViewport = (PFNGLVIEWPORTPROC)load("glViewport"); + glad_glNewList = (PFNGLNEWLISTPROC)load("glNewList"); + glad_glEndList = (PFNGLENDLISTPROC)load("glEndList"); + glad_glCallList = (PFNGLCALLLISTPROC)load("glCallList"); + glad_glCallLists = (PFNGLCALLLISTSPROC)load("glCallLists"); + glad_glDeleteLists = (PFNGLDELETELISTSPROC)load("glDeleteLists"); + glad_glGenLists = (PFNGLGENLISTSPROC)load("glGenLists"); + glad_glListBase = (PFNGLLISTBASEPROC)load("glListBase"); + glad_glBegin = (PFNGLBEGINPROC)load("glBegin"); + glad_glBitmap = (PFNGLBITMAPPROC)load("glBitmap"); + glad_glColor3b = (PFNGLCOLOR3BPROC)load("glColor3b"); + glad_glColor3bv = (PFNGLCOLOR3BVPROC)load("glColor3bv"); + glad_glColor3d = (PFNGLCOLOR3DPROC)load("glColor3d"); + glad_glColor3dv = (PFNGLCOLOR3DVPROC)load("glColor3dv"); + glad_glColor3f = (PFNGLCOLOR3FPROC)load("glColor3f"); + glad_glColor3fv = (PFNGLCOLOR3FVPROC)load("glColor3fv"); + glad_glColor3i = (PFNGLCOLOR3IPROC)load("glColor3i"); + glad_glColor3iv = (PFNGLCOLOR3IVPROC)load("glColor3iv"); + glad_glColor3s = (PFNGLCOLOR3SPROC)load("glColor3s"); + glad_glColor3sv = (PFNGLCOLOR3SVPROC)load("glColor3sv"); + glad_glColor3ub = (PFNGLCOLOR3UBPROC)load("glColor3ub"); + glad_glColor3ubv = (PFNGLCOLOR3UBVPROC)load("glColor3ubv"); + glad_glColor3ui = (PFNGLCOLOR3UIPROC)load("glColor3ui"); + glad_glColor3uiv = (PFNGLCOLOR3UIVPROC)load("glColor3uiv"); + glad_glColor3us = (PFNGLCOLOR3USPROC)load("glColor3us"); + glad_glColor3usv = (PFNGLCOLOR3USVPROC)load("glColor3usv"); + glad_glColor4b = (PFNGLCOLOR4BPROC)load("glColor4b"); + glad_glColor4bv = (PFNGLCOLOR4BVPROC)load("glColor4bv"); + glad_glColor4d = (PFNGLCOLOR4DPROC)load("glColor4d"); + glad_glColor4dv = (PFNGLCOLOR4DVPROC)load("glColor4dv"); + glad_glColor4f = (PFNGLCOLOR4FPROC)load("glColor4f"); + glad_glColor4fv = (PFNGLCOLOR4FVPROC)load("glColor4fv"); + glad_glColor4i = (PFNGLCOLOR4IPROC)load("glColor4i"); + glad_glColor4iv = (PFNGLCOLOR4IVPROC)load("glColor4iv"); + glad_glColor4s = (PFNGLCOLOR4SPROC)load("glColor4s"); + glad_glColor4sv = (PFNGLCOLOR4SVPROC)load("glColor4sv"); + glad_glColor4ub = (PFNGLCOLOR4UBPROC)load("glColor4ub"); + glad_glColor4ubv = (PFNGLCOLOR4UBVPROC)load("glColor4ubv"); + glad_glColor4ui = (PFNGLCOLOR4UIPROC)load("glColor4ui"); + glad_glColor4uiv = (PFNGLCOLOR4UIVPROC)load("glColor4uiv"); + glad_glColor4us = (PFNGLCOLOR4USPROC)load("glColor4us"); + glad_glColor4usv = (PFNGLCOLOR4USVPROC)load("glColor4usv"); + glad_glEdgeFlag = (PFNGLEDGEFLAGPROC)load("glEdgeFlag"); + glad_glEdgeFlagv = (PFNGLEDGEFLAGVPROC)load("glEdgeFlagv"); + glad_glEnd = (PFNGLENDPROC)load("glEnd"); + glad_glIndexd = (PFNGLINDEXDPROC)load("glIndexd"); + glad_glIndexdv = (PFNGLINDEXDVPROC)load("glIndexdv"); + glad_glIndexf = (PFNGLINDEXFPROC)load("glIndexf"); + glad_glIndexfv = (PFNGLINDEXFVPROC)load("glIndexfv"); + glad_glIndexi = (PFNGLINDEXIPROC)load("glIndexi"); + glad_glIndexiv = (PFNGLINDEXIVPROC)load("glIndexiv"); + glad_glIndexs = (PFNGLINDEXSPROC)load("glIndexs"); + glad_glIndexsv = (PFNGLINDEXSVPROC)load("glIndexsv"); + glad_glNormal3b = (PFNGLNORMAL3BPROC)load("glNormal3b"); + glad_glNormal3bv = (PFNGLNORMAL3BVPROC)load("glNormal3bv"); + glad_glNormal3d = (PFNGLNORMAL3DPROC)load("glNormal3d"); + glad_glNormal3dv = (PFNGLNORMAL3DVPROC)load("glNormal3dv"); + glad_glNormal3f = (PFNGLNORMAL3FPROC)load("glNormal3f"); + glad_glNormal3fv = (PFNGLNORMAL3FVPROC)load("glNormal3fv"); + glad_glNormal3i = (PFNGLNORMAL3IPROC)load("glNormal3i"); + glad_glNormal3iv = (PFNGLNORMAL3IVPROC)load("glNormal3iv"); + glad_glNormal3s = (PFNGLNORMAL3SPROC)load("glNormal3s"); + glad_glNormal3sv = (PFNGLNORMAL3SVPROC)load("glNormal3sv"); + glad_glRasterPos2d = (PFNGLRASTERPOS2DPROC)load("glRasterPos2d"); + glad_glRasterPos2dv = (PFNGLRASTERPOS2DVPROC)load("glRasterPos2dv"); + glad_glRasterPos2f = (PFNGLRASTERPOS2FPROC)load("glRasterPos2f"); + glad_glRasterPos2fv = (PFNGLRASTERPOS2FVPROC)load("glRasterPos2fv"); + glad_glRasterPos2i = (PFNGLRASTERPOS2IPROC)load("glRasterPos2i"); + glad_glRasterPos2iv = (PFNGLRASTERPOS2IVPROC)load("glRasterPos2iv"); + glad_glRasterPos2s = (PFNGLRASTERPOS2SPROC)load("glRasterPos2s"); + glad_glRasterPos2sv = (PFNGLRASTERPOS2SVPROC)load("glRasterPos2sv"); + glad_glRasterPos3d = (PFNGLRASTERPOS3DPROC)load("glRasterPos3d"); + glad_glRasterPos3dv = (PFNGLRASTERPOS3DVPROC)load("glRasterPos3dv"); + glad_glRasterPos3f = (PFNGLRASTERPOS3FPROC)load("glRasterPos3f"); + glad_glRasterPos3fv = (PFNGLRASTERPOS3FVPROC)load("glRasterPos3fv"); + glad_glRasterPos3i = (PFNGLRASTERPOS3IPROC)load("glRasterPos3i"); + glad_glRasterPos3iv = (PFNGLRASTERPOS3IVPROC)load("glRasterPos3iv"); + glad_glRasterPos3s = (PFNGLRASTERPOS3SPROC)load("glRasterPos3s"); + glad_glRasterPos3sv = (PFNGLRASTERPOS3SVPROC)load("glRasterPos3sv"); + glad_glRasterPos4d = (PFNGLRASTERPOS4DPROC)load("glRasterPos4d"); + glad_glRasterPos4dv = (PFNGLRASTERPOS4DVPROC)load("glRasterPos4dv"); + glad_glRasterPos4f = (PFNGLRASTERPOS4FPROC)load("glRasterPos4f"); + glad_glRasterPos4fv = (PFNGLRASTERPOS4FVPROC)load("glRasterPos4fv"); + glad_glRasterPos4i = (PFNGLRASTERPOS4IPROC)load("glRasterPos4i"); + glad_glRasterPos4iv = (PFNGLRASTERPOS4IVPROC)load("glRasterPos4iv"); + glad_glRasterPos4s = (PFNGLRASTERPOS4SPROC)load("glRasterPos4s"); + glad_glRasterPos4sv = (PFNGLRASTERPOS4SVPROC)load("glRasterPos4sv"); + glad_glRectd = (PFNGLRECTDPROC)load("glRectd"); + glad_glRectdv = (PFNGLRECTDVPROC)load("glRectdv"); + glad_glRectf = (PFNGLRECTFPROC)load("glRectf"); + glad_glRectfv = (PFNGLRECTFVPROC)load("glRectfv"); + glad_glRecti = (PFNGLRECTIPROC)load("glRecti"); + glad_glRectiv = (PFNGLRECTIVPROC)load("glRectiv"); + glad_glRects = (PFNGLRECTSPROC)load("glRects"); + glad_glRectsv = (PFNGLRECTSVPROC)load("glRectsv"); + glad_glTexCoord1d = (PFNGLTEXCOORD1DPROC)load("glTexCoord1d"); + glad_glTexCoord1dv = (PFNGLTEXCOORD1DVPROC)load("glTexCoord1dv"); + glad_glTexCoord1f = (PFNGLTEXCOORD1FPROC)load("glTexCoord1f"); + glad_glTexCoord1fv = (PFNGLTEXCOORD1FVPROC)load("glTexCoord1fv"); + glad_glTexCoord1i = (PFNGLTEXCOORD1IPROC)load("glTexCoord1i"); + glad_glTexCoord1iv = (PFNGLTEXCOORD1IVPROC)load("glTexCoord1iv"); + glad_glTexCoord1s = (PFNGLTEXCOORD1SPROC)load("glTexCoord1s"); + glad_glTexCoord1sv = (PFNGLTEXCOORD1SVPROC)load("glTexCoord1sv"); + glad_glTexCoord2d = (PFNGLTEXCOORD2DPROC)load("glTexCoord2d"); + glad_glTexCoord2dv = (PFNGLTEXCOORD2DVPROC)load("glTexCoord2dv"); + glad_glTexCoord2f = (PFNGLTEXCOORD2FPROC)load("glTexCoord2f"); + glad_glTexCoord2fv = (PFNGLTEXCOORD2FVPROC)load("glTexCoord2fv"); + glad_glTexCoord2i = (PFNGLTEXCOORD2IPROC)load("glTexCoord2i"); + glad_glTexCoord2iv = (PFNGLTEXCOORD2IVPROC)load("glTexCoord2iv"); + glad_glTexCoord2s = (PFNGLTEXCOORD2SPROC)load("glTexCoord2s"); + glad_glTexCoord2sv = (PFNGLTEXCOORD2SVPROC)load("glTexCoord2sv"); + glad_glTexCoord3d = (PFNGLTEXCOORD3DPROC)load("glTexCoord3d"); + glad_glTexCoord3dv = (PFNGLTEXCOORD3DVPROC)load("glTexCoord3dv"); + glad_glTexCoord3f = (PFNGLTEXCOORD3FPROC)load("glTexCoord3f"); + glad_glTexCoord3fv = (PFNGLTEXCOORD3FVPROC)load("glTexCoord3fv"); + glad_glTexCoord3i = (PFNGLTEXCOORD3IPROC)load("glTexCoord3i"); + glad_glTexCoord3iv = (PFNGLTEXCOORD3IVPROC)load("glTexCoord3iv"); + glad_glTexCoord3s = (PFNGLTEXCOORD3SPROC)load("glTexCoord3s"); + glad_glTexCoord3sv = (PFNGLTEXCOORD3SVPROC)load("glTexCoord3sv"); + glad_glTexCoord4d = (PFNGLTEXCOORD4DPROC)load("glTexCoord4d"); + glad_glTexCoord4dv = (PFNGLTEXCOORD4DVPROC)load("glTexCoord4dv"); + glad_glTexCoord4f = (PFNGLTEXCOORD4FPROC)load("glTexCoord4f"); + glad_glTexCoord4fv = (PFNGLTEXCOORD4FVPROC)load("glTexCoord4fv"); + glad_glTexCoord4i = (PFNGLTEXCOORD4IPROC)load("glTexCoord4i"); + glad_glTexCoord4iv = (PFNGLTEXCOORD4IVPROC)load("glTexCoord4iv"); + glad_glTexCoord4s = (PFNGLTEXCOORD4SPROC)load("glTexCoord4s"); + glad_glTexCoord4sv = (PFNGLTEXCOORD4SVPROC)load("glTexCoord4sv"); + glad_glVertex2d = (PFNGLVERTEX2DPROC)load("glVertex2d"); + glad_glVertex2dv = (PFNGLVERTEX2DVPROC)load("glVertex2dv"); + glad_glVertex2f = (PFNGLVERTEX2FPROC)load("glVertex2f"); + glad_glVertex2fv = (PFNGLVERTEX2FVPROC)load("glVertex2fv"); + glad_glVertex2i = (PFNGLVERTEX2IPROC)load("glVertex2i"); + glad_glVertex2iv = (PFNGLVERTEX2IVPROC)load("glVertex2iv"); + glad_glVertex2s = (PFNGLVERTEX2SPROC)load("glVertex2s"); + glad_glVertex2sv = (PFNGLVERTEX2SVPROC)load("glVertex2sv"); + glad_glVertex3d = (PFNGLVERTEX3DPROC)load("glVertex3d"); + glad_glVertex3dv = (PFNGLVERTEX3DVPROC)load("glVertex3dv"); + glad_glVertex3f = (PFNGLVERTEX3FPROC)load("glVertex3f"); + glad_glVertex3fv = (PFNGLVERTEX3FVPROC)load("glVertex3fv"); + glad_glVertex3i = (PFNGLVERTEX3IPROC)load("glVertex3i"); + glad_glVertex3iv = (PFNGLVERTEX3IVPROC)load("glVertex3iv"); + glad_glVertex3s = (PFNGLVERTEX3SPROC)load("glVertex3s"); + glad_glVertex3sv = (PFNGLVERTEX3SVPROC)load("glVertex3sv"); + glad_glVertex4d = (PFNGLVERTEX4DPROC)load("glVertex4d"); + glad_glVertex4dv = (PFNGLVERTEX4DVPROC)load("glVertex4dv"); + glad_glVertex4f = (PFNGLVERTEX4FPROC)load("glVertex4f"); + glad_glVertex4fv = (PFNGLVERTEX4FVPROC)load("glVertex4fv"); + glad_glVertex4i = (PFNGLVERTEX4IPROC)load("glVertex4i"); + glad_glVertex4iv = (PFNGLVERTEX4IVPROC)load("glVertex4iv"); + glad_glVertex4s = (PFNGLVERTEX4SPROC)load("glVertex4s"); + glad_glVertex4sv = (PFNGLVERTEX4SVPROC)load("glVertex4sv"); + glad_glClipPlane = (PFNGLCLIPPLANEPROC)load("glClipPlane"); + glad_glColorMaterial = (PFNGLCOLORMATERIALPROC)load("glColorMaterial"); + glad_glFogf = (PFNGLFOGFPROC)load("glFogf"); + glad_glFogfv = (PFNGLFOGFVPROC)load("glFogfv"); + glad_glFogi = (PFNGLFOGIPROC)load("glFogi"); + glad_glFogiv = (PFNGLFOGIVPROC)load("glFogiv"); + glad_glLightf = (PFNGLLIGHTFPROC)load("glLightf"); + glad_glLightfv = (PFNGLLIGHTFVPROC)load("glLightfv"); + glad_glLighti = (PFNGLLIGHTIPROC)load("glLighti"); + glad_glLightiv = (PFNGLLIGHTIVPROC)load("glLightiv"); + glad_glLightModelf = (PFNGLLIGHTMODELFPROC)load("glLightModelf"); + glad_glLightModelfv = (PFNGLLIGHTMODELFVPROC)load("glLightModelfv"); + glad_glLightModeli = (PFNGLLIGHTMODELIPROC)load("glLightModeli"); + glad_glLightModeliv = (PFNGLLIGHTMODELIVPROC)load("glLightModeliv"); + glad_glLineStipple = (PFNGLLINESTIPPLEPROC)load("glLineStipple"); + glad_glMaterialf = (PFNGLMATERIALFPROC)load("glMaterialf"); + glad_glMaterialfv = (PFNGLMATERIALFVPROC)load("glMaterialfv"); + glad_glMateriali = (PFNGLMATERIALIPROC)load("glMateriali"); + glad_glMaterialiv = (PFNGLMATERIALIVPROC)load("glMaterialiv"); + glad_glPolygonStipple = (PFNGLPOLYGONSTIPPLEPROC)load("glPolygonStipple"); + glad_glShadeModel = (PFNGLSHADEMODELPROC)load("glShadeModel"); + glad_glTexEnvf = (PFNGLTEXENVFPROC)load("glTexEnvf"); + glad_glTexEnvfv = (PFNGLTEXENVFVPROC)load("glTexEnvfv"); + glad_glTexEnvi = (PFNGLTEXENVIPROC)load("glTexEnvi"); + glad_glTexEnviv = (PFNGLTEXENVIVPROC)load("glTexEnviv"); + glad_glTexGend = (PFNGLTEXGENDPROC)load("glTexGend"); + glad_glTexGendv = (PFNGLTEXGENDVPROC)load("glTexGendv"); + glad_glTexGenf = (PFNGLTEXGENFPROC)load("glTexGenf"); + glad_glTexGenfv = (PFNGLTEXGENFVPROC)load("glTexGenfv"); + glad_glTexGeni = (PFNGLTEXGENIPROC)load("glTexGeni"); + glad_glTexGeniv = (PFNGLTEXGENIVPROC)load("glTexGeniv"); + glad_glFeedbackBuffer = (PFNGLFEEDBACKBUFFERPROC)load("glFeedbackBuffer"); + glad_glSelectBuffer = (PFNGLSELECTBUFFERPROC)load("glSelectBuffer"); + glad_glRenderMode = (PFNGLRENDERMODEPROC)load("glRenderMode"); + glad_glInitNames = (PFNGLINITNAMESPROC)load("glInitNames"); + glad_glLoadName = (PFNGLLOADNAMEPROC)load("glLoadName"); + glad_glPassThrough = (PFNGLPASSTHROUGHPROC)load("glPassThrough"); + glad_glPopName = (PFNGLPOPNAMEPROC)load("glPopName"); + glad_glPushName = (PFNGLPUSHNAMEPROC)load("glPushName"); + glad_glClearAccum = (PFNGLCLEARACCUMPROC)load("glClearAccum"); + glad_glClearIndex = (PFNGLCLEARINDEXPROC)load("glClearIndex"); + glad_glIndexMask = (PFNGLINDEXMASKPROC)load("glIndexMask"); + glad_glAccum = (PFNGLACCUMPROC)load("glAccum"); + glad_glPopAttrib = (PFNGLPOPATTRIBPROC)load("glPopAttrib"); + glad_glPushAttrib = (PFNGLPUSHATTRIBPROC)load("glPushAttrib"); + glad_glMap1d = (PFNGLMAP1DPROC)load("glMap1d"); + glad_glMap1f = (PFNGLMAP1FPROC)load("glMap1f"); + glad_glMap2d = (PFNGLMAP2DPROC)load("glMap2d"); + glad_glMap2f = (PFNGLMAP2FPROC)load("glMap2f"); + glad_glMapGrid1d = (PFNGLMAPGRID1DPROC)load("glMapGrid1d"); + glad_glMapGrid1f = (PFNGLMAPGRID1FPROC)load("glMapGrid1f"); + glad_glMapGrid2d = (PFNGLMAPGRID2DPROC)load("glMapGrid2d"); + glad_glMapGrid2f = (PFNGLMAPGRID2FPROC)load("glMapGrid2f"); + glad_glEvalCoord1d = (PFNGLEVALCOORD1DPROC)load("glEvalCoord1d"); + glad_glEvalCoord1dv = (PFNGLEVALCOORD1DVPROC)load("glEvalCoord1dv"); + glad_glEvalCoord1f = (PFNGLEVALCOORD1FPROC)load("glEvalCoord1f"); + glad_glEvalCoord1fv = (PFNGLEVALCOORD1FVPROC)load("glEvalCoord1fv"); + glad_glEvalCoord2d = (PFNGLEVALCOORD2DPROC)load("glEvalCoord2d"); + glad_glEvalCoord2dv = (PFNGLEVALCOORD2DVPROC)load("glEvalCoord2dv"); + glad_glEvalCoord2f = (PFNGLEVALCOORD2FPROC)load("glEvalCoord2f"); + glad_glEvalCoord2fv = (PFNGLEVALCOORD2FVPROC)load("glEvalCoord2fv"); + glad_glEvalMesh1 = (PFNGLEVALMESH1PROC)load("glEvalMesh1"); + glad_glEvalPoint1 = (PFNGLEVALPOINT1PROC)load("glEvalPoint1"); + glad_glEvalMesh2 = (PFNGLEVALMESH2PROC)load("glEvalMesh2"); + glad_glEvalPoint2 = (PFNGLEVALPOINT2PROC)load("glEvalPoint2"); + glad_glAlphaFunc = (PFNGLALPHAFUNCPROC)load("glAlphaFunc"); + glad_glPixelZoom = (PFNGLPIXELZOOMPROC)load("glPixelZoom"); + glad_glPixelTransferf = (PFNGLPIXELTRANSFERFPROC)load("glPixelTransferf"); + glad_glPixelTransferi = (PFNGLPIXELTRANSFERIPROC)load("glPixelTransferi"); + glad_glPixelMapfv = (PFNGLPIXELMAPFVPROC)load("glPixelMapfv"); + glad_glPixelMapuiv = (PFNGLPIXELMAPUIVPROC)load("glPixelMapuiv"); + glad_glPixelMapusv = (PFNGLPIXELMAPUSVPROC)load("glPixelMapusv"); + glad_glCopyPixels = (PFNGLCOPYPIXELSPROC)load("glCopyPixels"); + glad_glDrawPixels = (PFNGLDRAWPIXELSPROC)load("glDrawPixels"); + glad_glGetClipPlane = (PFNGLGETCLIPPLANEPROC)load("glGetClipPlane"); + glad_glGetLightfv = (PFNGLGETLIGHTFVPROC)load("glGetLightfv"); + glad_glGetLightiv = (PFNGLGETLIGHTIVPROC)load("glGetLightiv"); + glad_glGetMapdv = (PFNGLGETMAPDVPROC)load("glGetMapdv"); + glad_glGetMapfv = (PFNGLGETMAPFVPROC)load("glGetMapfv"); + glad_glGetMapiv = (PFNGLGETMAPIVPROC)load("glGetMapiv"); + glad_glGetMaterialfv = (PFNGLGETMATERIALFVPROC)load("glGetMaterialfv"); + glad_glGetMaterialiv = (PFNGLGETMATERIALIVPROC)load("glGetMaterialiv"); + glad_glGetPixelMapfv = (PFNGLGETPIXELMAPFVPROC)load("glGetPixelMapfv"); + glad_glGetPixelMapuiv = (PFNGLGETPIXELMAPUIVPROC)load("glGetPixelMapuiv"); + glad_glGetPixelMapusv = (PFNGLGETPIXELMAPUSVPROC)load("glGetPixelMapusv"); + glad_glGetPolygonStipple = (PFNGLGETPOLYGONSTIPPLEPROC)load("glGetPolygonStipple"); + glad_glGetTexEnvfv = (PFNGLGETTEXENVFVPROC)load("glGetTexEnvfv"); + glad_glGetTexEnviv = (PFNGLGETTEXENVIVPROC)load("glGetTexEnviv"); + glad_glGetTexGendv = (PFNGLGETTEXGENDVPROC)load("glGetTexGendv"); + glad_glGetTexGenfv = (PFNGLGETTEXGENFVPROC)load("glGetTexGenfv"); + glad_glGetTexGeniv = (PFNGLGETTEXGENIVPROC)load("glGetTexGeniv"); + glad_glIsList = (PFNGLISLISTPROC)load("glIsList"); + glad_glFrustum = (PFNGLFRUSTUMPROC)load("glFrustum"); + glad_glLoadIdentity = (PFNGLLOADIDENTITYPROC)load("glLoadIdentity"); + glad_glLoadMatrixf = (PFNGLLOADMATRIXFPROC)load("glLoadMatrixf"); + glad_glLoadMatrixd = (PFNGLLOADMATRIXDPROC)load("glLoadMatrixd"); + glad_glMatrixMode = (PFNGLMATRIXMODEPROC)load("glMatrixMode"); + glad_glMultMatrixf = (PFNGLMULTMATRIXFPROC)load("glMultMatrixf"); + glad_glMultMatrixd = (PFNGLMULTMATRIXDPROC)load("glMultMatrixd"); + glad_glOrtho = (PFNGLORTHOPROC)load("glOrtho"); + glad_glPopMatrix = (PFNGLPOPMATRIXPROC)load("glPopMatrix"); + glad_glPushMatrix = (PFNGLPUSHMATRIXPROC)load("glPushMatrix"); + glad_glRotated = (PFNGLROTATEDPROC)load("glRotated"); + glad_glRotatef = (PFNGLROTATEFPROC)load("glRotatef"); + glad_glScaled = (PFNGLSCALEDPROC)load("glScaled"); + glad_glScalef = (PFNGLSCALEFPROC)load("glScalef"); + glad_glTranslated = (PFNGLTRANSLATEDPROC)load("glTranslated"); + glad_glTranslatef = (PFNGLTRANSLATEFPROC)load("glTranslatef"); +} +static void load_GL_VERSION_1_1(GLADloadproc load) { + if(!GLAD_GL_VERSION_1_1) return; + glad_glDrawArrays = (PFNGLDRAWARRAYSPROC)load("glDrawArrays"); + glad_glDrawElements = (PFNGLDRAWELEMENTSPROC)load("glDrawElements"); + glad_glGetPointerv = (PFNGLGETPOINTERVPROC)load("glGetPointerv"); + glad_glPolygonOffset = (PFNGLPOLYGONOFFSETPROC)load("glPolygonOffset"); + glad_glCopyTexImage1D = (PFNGLCOPYTEXIMAGE1DPROC)load("glCopyTexImage1D"); + glad_glCopyTexImage2D = (PFNGLCOPYTEXIMAGE2DPROC)load("glCopyTexImage2D"); + glad_glCopyTexSubImage1D = (PFNGLCOPYTEXSUBIMAGE1DPROC)load("glCopyTexSubImage1D"); + glad_glCopyTexSubImage2D = (PFNGLCOPYTEXSUBIMAGE2DPROC)load("glCopyTexSubImage2D"); + glad_glTexSubImage1D = (PFNGLTEXSUBIMAGE1DPROC)load("glTexSubImage1D"); + glad_glTexSubImage2D = (PFNGLTEXSUBIMAGE2DPROC)load("glTexSubImage2D"); + glad_glBindTexture = (PFNGLBINDTEXTUREPROC)load("glBindTexture"); + glad_glDeleteTextures = (PFNGLDELETETEXTURESPROC)load("glDeleteTextures"); + glad_glGenTextures = (PFNGLGENTEXTURESPROC)load("glGenTextures"); + glad_glIsTexture = (PFNGLISTEXTUREPROC)load("glIsTexture"); + glad_glArrayElement = (PFNGLARRAYELEMENTPROC)load("glArrayElement"); + glad_glColorPointer = (PFNGLCOLORPOINTERPROC)load("glColorPointer"); + glad_glDisableClientState = (PFNGLDISABLECLIENTSTATEPROC)load("glDisableClientState"); + glad_glEdgeFlagPointer = (PFNGLEDGEFLAGPOINTERPROC)load("glEdgeFlagPointer"); + glad_glEnableClientState = (PFNGLENABLECLIENTSTATEPROC)load("glEnableClientState"); + glad_glIndexPointer = (PFNGLINDEXPOINTERPROC)load("glIndexPointer"); + glad_glInterleavedArrays = (PFNGLINTERLEAVEDARRAYSPROC)load("glInterleavedArrays"); + glad_glNormalPointer = (PFNGLNORMALPOINTERPROC)load("glNormalPointer"); + glad_glTexCoordPointer = (PFNGLTEXCOORDPOINTERPROC)load("glTexCoordPointer"); + glad_glVertexPointer = (PFNGLVERTEXPOINTERPROC)load("glVertexPointer"); + glad_glAreTexturesResident = (PFNGLARETEXTURESRESIDENTPROC)load("glAreTexturesResident"); + glad_glPrioritizeTextures = (PFNGLPRIORITIZETEXTURESPROC)load("glPrioritizeTextures"); + glad_glIndexub = (PFNGLINDEXUBPROC)load("glIndexub"); + glad_glIndexubv = (PFNGLINDEXUBVPROC)load("glIndexubv"); + glad_glPopClientAttrib = (PFNGLPOPCLIENTATTRIBPROC)load("glPopClientAttrib"); + glad_glPushClientAttrib = (PFNGLPUSHCLIENTATTRIBPROC)load("glPushClientAttrib"); +} +static void load_GL_VERSION_1_2(GLADloadproc load) { + if(!GLAD_GL_VERSION_1_2) return; + glad_glDrawRangeElements = (PFNGLDRAWRANGEELEMENTSPROC)load("glDrawRangeElements"); + glad_glTexImage3D = (PFNGLTEXIMAGE3DPROC)load("glTexImage3D"); + glad_glTexSubImage3D = (PFNGLTEXSUBIMAGE3DPROC)load("glTexSubImage3D"); + glad_glCopyTexSubImage3D = (PFNGLCOPYTEXSUBIMAGE3DPROC)load("glCopyTexSubImage3D"); +} +static void load_GL_VERSION_1_3(GLADloadproc load) { + if(!GLAD_GL_VERSION_1_3) return; + glad_glActiveTexture = (PFNGLACTIVETEXTUREPROC)load("glActiveTexture"); + glad_glSampleCoverage = (PFNGLSAMPLECOVERAGEPROC)load("glSampleCoverage"); + glad_glCompressedTexImage3D = (PFNGLCOMPRESSEDTEXIMAGE3DPROC)load("glCompressedTexImage3D"); + glad_glCompressedTexImage2D = (PFNGLCOMPRESSEDTEXIMAGE2DPROC)load("glCompressedTexImage2D"); + glad_glCompressedTexImage1D = (PFNGLCOMPRESSEDTEXIMAGE1DPROC)load("glCompressedTexImage1D"); + glad_glCompressedTexSubImage3D = (PFNGLCOMPRESSEDTEXSUBIMAGE3DPROC)load("glCompressedTexSubImage3D"); + glad_glCompressedTexSubImage2D = (PFNGLCOMPRESSEDTEXSUBIMAGE2DPROC)load("glCompressedTexSubImage2D"); + glad_glCompressedTexSubImage1D = (PFNGLCOMPRESSEDTEXSUBIMAGE1DPROC)load("glCompressedTexSubImage1D"); + glad_glGetCompressedTexImage = (PFNGLGETCOMPRESSEDTEXIMAGEPROC)load("glGetCompressedTexImage"); + glad_glClientActiveTexture = (PFNGLCLIENTACTIVETEXTUREPROC)load("glClientActiveTexture"); + glad_glMultiTexCoord1d = (PFNGLMULTITEXCOORD1DPROC)load("glMultiTexCoord1d"); + glad_glMultiTexCoord1dv = (PFNGLMULTITEXCOORD1DVPROC)load("glMultiTexCoord1dv"); + glad_glMultiTexCoord1f = (PFNGLMULTITEXCOORD1FPROC)load("glMultiTexCoord1f"); + glad_glMultiTexCoord1fv = (PFNGLMULTITEXCOORD1FVPROC)load("glMultiTexCoord1fv"); + glad_glMultiTexCoord1i = (PFNGLMULTITEXCOORD1IPROC)load("glMultiTexCoord1i"); + glad_glMultiTexCoord1iv = (PFNGLMULTITEXCOORD1IVPROC)load("glMultiTexCoord1iv"); + glad_glMultiTexCoord1s = (PFNGLMULTITEXCOORD1SPROC)load("glMultiTexCoord1s"); + glad_glMultiTexCoord1sv = (PFNGLMULTITEXCOORD1SVPROC)load("glMultiTexCoord1sv"); + glad_glMultiTexCoord2d = (PFNGLMULTITEXCOORD2DPROC)load("glMultiTexCoord2d"); + glad_glMultiTexCoord2dv = (PFNGLMULTITEXCOORD2DVPROC)load("glMultiTexCoord2dv"); + glad_glMultiTexCoord2f = (PFNGLMULTITEXCOORD2FPROC)load("glMultiTexCoord2f"); + glad_glMultiTexCoord2fv = (PFNGLMULTITEXCOORD2FVPROC)load("glMultiTexCoord2fv"); + glad_glMultiTexCoord2i = (PFNGLMULTITEXCOORD2IPROC)load("glMultiTexCoord2i"); + glad_glMultiTexCoord2iv = (PFNGLMULTITEXCOORD2IVPROC)load("glMultiTexCoord2iv"); + glad_glMultiTexCoord2s = (PFNGLMULTITEXCOORD2SPROC)load("glMultiTexCoord2s"); + glad_glMultiTexCoord2sv = (PFNGLMULTITEXCOORD2SVPROC)load("glMultiTexCoord2sv"); + glad_glMultiTexCoord3d = (PFNGLMULTITEXCOORD3DPROC)load("glMultiTexCoord3d"); + glad_glMultiTexCoord3dv = (PFNGLMULTITEXCOORD3DVPROC)load("glMultiTexCoord3dv"); + glad_glMultiTexCoord3f = (PFNGLMULTITEXCOORD3FPROC)load("glMultiTexCoord3f"); + glad_glMultiTexCoord3fv = (PFNGLMULTITEXCOORD3FVPROC)load("glMultiTexCoord3fv"); + glad_glMultiTexCoord3i = (PFNGLMULTITEXCOORD3IPROC)load("glMultiTexCoord3i"); + glad_glMultiTexCoord3iv = (PFNGLMULTITEXCOORD3IVPROC)load("glMultiTexCoord3iv"); + glad_glMultiTexCoord3s = (PFNGLMULTITEXCOORD3SPROC)load("glMultiTexCoord3s"); + glad_glMultiTexCoord3sv = (PFNGLMULTITEXCOORD3SVPROC)load("glMultiTexCoord3sv"); + glad_glMultiTexCoord4d = (PFNGLMULTITEXCOORD4DPROC)load("glMultiTexCoord4d"); + glad_glMultiTexCoord4dv = (PFNGLMULTITEXCOORD4DVPROC)load("glMultiTexCoord4dv"); + glad_glMultiTexCoord4f = (PFNGLMULTITEXCOORD4FPROC)load("glMultiTexCoord4f"); + glad_glMultiTexCoord4fv = (PFNGLMULTITEXCOORD4FVPROC)load("glMultiTexCoord4fv"); + glad_glMultiTexCoord4i = (PFNGLMULTITEXCOORD4IPROC)load("glMultiTexCoord4i"); + glad_glMultiTexCoord4iv = (PFNGLMULTITEXCOORD4IVPROC)load("glMultiTexCoord4iv"); + glad_glMultiTexCoord4s = (PFNGLMULTITEXCOORD4SPROC)load("glMultiTexCoord4s"); + glad_glMultiTexCoord4sv = (PFNGLMULTITEXCOORD4SVPROC)load("glMultiTexCoord4sv"); + glad_glLoadTransposeMatrixf = (PFNGLLOADTRANSPOSEMATRIXFPROC)load("glLoadTransposeMatrixf"); + glad_glLoadTransposeMatrixd = (PFNGLLOADTRANSPOSEMATRIXDPROC)load("glLoadTransposeMatrixd"); + glad_glMultTransposeMatrixf = (PFNGLMULTTRANSPOSEMATRIXFPROC)load("glMultTransposeMatrixf"); + glad_glMultTransposeMatrixd = (PFNGLMULTTRANSPOSEMATRIXDPROC)load("glMultTransposeMatrixd"); +} +static void load_GL_VERSION_1_4(GLADloadproc load) { + if(!GLAD_GL_VERSION_1_4) return; + glad_glBlendFuncSeparate = (PFNGLBLENDFUNCSEPARATEPROC)load("glBlendFuncSeparate"); + glad_glMultiDrawArrays = (PFNGLMULTIDRAWARRAYSPROC)load("glMultiDrawArrays"); + glad_glMultiDrawElements = (PFNGLMULTIDRAWELEMENTSPROC)load("glMultiDrawElements"); + glad_glPointParameterf = (PFNGLPOINTPARAMETERFPROC)load("glPointParameterf"); + glad_glPointParameterfv = (PFNGLPOINTPARAMETERFVPROC)load("glPointParameterfv"); + glad_glPointParameteri = (PFNGLPOINTPARAMETERIPROC)load("glPointParameteri"); + glad_glPointParameteriv = (PFNGLPOINTPARAMETERIVPROC)load("glPointParameteriv"); + glad_glFogCoordf = (PFNGLFOGCOORDFPROC)load("glFogCoordf"); + glad_glFogCoordfv = (PFNGLFOGCOORDFVPROC)load("glFogCoordfv"); + glad_glFogCoordd = (PFNGLFOGCOORDDPROC)load("glFogCoordd"); + glad_glFogCoorddv = (PFNGLFOGCOORDDVPROC)load("glFogCoorddv"); + glad_glFogCoordPointer = (PFNGLFOGCOORDPOINTERPROC)load("glFogCoordPointer"); + glad_glSecondaryColor3b = (PFNGLSECONDARYCOLOR3BPROC)load("glSecondaryColor3b"); + glad_glSecondaryColor3bv = (PFNGLSECONDARYCOLOR3BVPROC)load("glSecondaryColor3bv"); + glad_glSecondaryColor3d = (PFNGLSECONDARYCOLOR3DPROC)load("glSecondaryColor3d"); + glad_glSecondaryColor3dv = (PFNGLSECONDARYCOLOR3DVPROC)load("glSecondaryColor3dv"); + glad_glSecondaryColor3f = (PFNGLSECONDARYCOLOR3FPROC)load("glSecondaryColor3f"); + glad_glSecondaryColor3fv = (PFNGLSECONDARYCOLOR3FVPROC)load("glSecondaryColor3fv"); + glad_glSecondaryColor3i = (PFNGLSECONDARYCOLOR3IPROC)load("glSecondaryColor3i"); + glad_glSecondaryColor3iv = (PFNGLSECONDARYCOLOR3IVPROC)load("glSecondaryColor3iv"); + glad_glSecondaryColor3s = (PFNGLSECONDARYCOLOR3SPROC)load("glSecondaryColor3s"); + glad_glSecondaryColor3sv = (PFNGLSECONDARYCOLOR3SVPROC)load("glSecondaryColor3sv"); + glad_glSecondaryColor3ub = (PFNGLSECONDARYCOLOR3UBPROC)load("glSecondaryColor3ub"); + glad_glSecondaryColor3ubv = (PFNGLSECONDARYCOLOR3UBVPROC)load("glSecondaryColor3ubv"); + glad_glSecondaryColor3ui = (PFNGLSECONDARYCOLOR3UIPROC)load("glSecondaryColor3ui"); + glad_glSecondaryColor3uiv = (PFNGLSECONDARYCOLOR3UIVPROC)load("glSecondaryColor3uiv"); + glad_glSecondaryColor3us = (PFNGLSECONDARYCOLOR3USPROC)load("glSecondaryColor3us"); + glad_glSecondaryColor3usv = (PFNGLSECONDARYCOLOR3USVPROC)load("glSecondaryColor3usv"); + glad_glSecondaryColorPointer = (PFNGLSECONDARYCOLORPOINTERPROC)load("glSecondaryColorPointer"); + glad_glWindowPos2d = (PFNGLWINDOWPOS2DPROC)load("glWindowPos2d"); + glad_glWindowPos2dv = (PFNGLWINDOWPOS2DVPROC)load("glWindowPos2dv"); + glad_glWindowPos2f = (PFNGLWINDOWPOS2FPROC)load("glWindowPos2f"); + glad_glWindowPos2fv = (PFNGLWINDOWPOS2FVPROC)load("glWindowPos2fv"); + glad_glWindowPos2i = (PFNGLWINDOWPOS2IPROC)load("glWindowPos2i"); + glad_glWindowPos2iv = (PFNGLWINDOWPOS2IVPROC)load("glWindowPos2iv"); + glad_glWindowPos2s = (PFNGLWINDOWPOS2SPROC)load("glWindowPos2s"); + glad_glWindowPos2sv = (PFNGLWINDOWPOS2SVPROC)load("glWindowPos2sv"); + glad_glWindowPos3d = (PFNGLWINDOWPOS3DPROC)load("glWindowPos3d"); + glad_glWindowPos3dv = (PFNGLWINDOWPOS3DVPROC)load("glWindowPos3dv"); + glad_glWindowPos3f = (PFNGLWINDOWPOS3FPROC)load("glWindowPos3f"); + glad_glWindowPos3fv = (PFNGLWINDOWPOS3FVPROC)load("glWindowPos3fv"); + glad_glWindowPos3i = (PFNGLWINDOWPOS3IPROC)load("glWindowPos3i"); + glad_glWindowPos3iv = (PFNGLWINDOWPOS3IVPROC)load("glWindowPos3iv"); + glad_glWindowPos3s = (PFNGLWINDOWPOS3SPROC)load("glWindowPos3s"); + glad_glWindowPos3sv = (PFNGLWINDOWPOS3SVPROC)load("glWindowPos3sv"); + glad_glBlendColor = (PFNGLBLENDCOLORPROC)load("glBlendColor"); + glad_glBlendEquation = (PFNGLBLENDEQUATIONPROC)load("glBlendEquation"); +} +static void load_GL_VERSION_1_5(GLADloadproc load) { + if(!GLAD_GL_VERSION_1_5) return; + glad_glGenQueries = (PFNGLGENQUERIESPROC)load("glGenQueries"); + glad_glDeleteQueries = (PFNGLDELETEQUERIESPROC)load("glDeleteQueries"); + glad_glIsQuery = (PFNGLISQUERYPROC)load("glIsQuery"); + glad_glBeginQuery = (PFNGLBEGINQUERYPROC)load("glBeginQuery"); + glad_glEndQuery = (PFNGLENDQUERYPROC)load("glEndQuery"); + glad_glGetQueryiv = (PFNGLGETQUERYIVPROC)load("glGetQueryiv"); + glad_glGetQueryObjectiv = (PFNGLGETQUERYOBJECTIVPROC)load("glGetQueryObjectiv"); + glad_glGetQueryObjectuiv = (PFNGLGETQUERYOBJECTUIVPROC)load("glGetQueryObjectuiv"); + glad_glBindBuffer = (PFNGLBINDBUFFERPROC)load("glBindBuffer"); + glad_glDeleteBuffers = (PFNGLDELETEBUFFERSPROC)load("glDeleteBuffers"); + glad_glGenBuffers = (PFNGLGENBUFFERSPROC)load("glGenBuffers"); + glad_glIsBuffer = (PFNGLISBUFFERPROC)load("glIsBuffer"); + glad_glBufferData = (PFNGLBUFFERDATAPROC)load("glBufferData"); + glad_glBufferSubData = (PFNGLBUFFERSUBDATAPROC)load("glBufferSubData"); + glad_glGetBufferSubData = (PFNGLGETBUFFERSUBDATAPROC)load("glGetBufferSubData"); + glad_glMapBuffer = (PFNGLMAPBUFFERPROC)load("glMapBuffer"); + glad_glUnmapBuffer = (PFNGLUNMAPBUFFERPROC)load("glUnmapBuffer"); + glad_glGetBufferParameteriv = (PFNGLGETBUFFERPARAMETERIVPROC)load("glGetBufferParameteriv"); + glad_glGetBufferPointerv = (PFNGLGETBUFFERPOINTERVPROC)load("glGetBufferPointerv"); +} +static void load_GL_VERSION_2_0(GLADloadproc load) { + if(!GLAD_GL_VERSION_2_0) return; + glad_glBlendEquationSeparate = (PFNGLBLENDEQUATIONSEPARATEPROC)load("glBlendEquationSeparate"); + glad_glDrawBuffers = (PFNGLDRAWBUFFERSPROC)load("glDrawBuffers"); + glad_glStencilOpSeparate = (PFNGLSTENCILOPSEPARATEPROC)load("glStencilOpSeparate"); + glad_glStencilFuncSeparate = (PFNGLSTENCILFUNCSEPARATEPROC)load("glStencilFuncSeparate"); + glad_glStencilMaskSeparate = (PFNGLSTENCILMASKSEPARATEPROC)load("glStencilMaskSeparate"); + glad_glAttachShader = (PFNGLATTACHSHADERPROC)load("glAttachShader"); + glad_glBindAttribLocation = (PFNGLBINDATTRIBLOCATIONPROC)load("glBindAttribLocation"); + glad_glCompileShader = (PFNGLCOMPILESHADERPROC)load("glCompileShader"); + glad_glCreateProgram = (PFNGLCREATEPROGRAMPROC)load("glCreateProgram"); + glad_glCreateShader = (PFNGLCREATESHADERPROC)load("glCreateShader"); + glad_glDeleteProgram = (PFNGLDELETEPROGRAMPROC)load("glDeleteProgram"); + glad_glDeleteShader = (PFNGLDELETESHADERPROC)load("glDeleteShader"); + glad_glDetachShader = (PFNGLDETACHSHADERPROC)load("glDetachShader"); + glad_glDisableVertexAttribArray = (PFNGLDISABLEVERTEXATTRIBARRAYPROC)load("glDisableVertexAttribArray"); + glad_glEnableVertexAttribArray = (PFNGLENABLEVERTEXATTRIBARRAYPROC)load("glEnableVertexAttribArray"); + glad_glGetActiveAttrib = (PFNGLGETACTIVEATTRIBPROC)load("glGetActiveAttrib"); + glad_glGetActiveUniform = (PFNGLGETACTIVEUNIFORMPROC)load("glGetActiveUniform"); + glad_glGetAttachedShaders = (PFNGLGETATTACHEDSHADERSPROC)load("glGetAttachedShaders"); + glad_glGetAttribLocation = (PFNGLGETATTRIBLOCATIONPROC)load("glGetAttribLocation"); + glad_glGetProgramiv = (PFNGLGETPROGRAMIVPROC)load("glGetProgramiv"); + glad_glGetProgramInfoLog = (PFNGLGETPROGRAMINFOLOGPROC)load("glGetProgramInfoLog"); + glad_glGetShaderiv = (PFNGLGETSHADERIVPROC)load("glGetShaderiv"); + glad_glGetShaderInfoLog = (PFNGLGETSHADERINFOLOGPROC)load("glGetShaderInfoLog"); + glad_glGetShaderSource = (PFNGLGETSHADERSOURCEPROC)load("glGetShaderSource"); + glad_glGetUniformLocation = (PFNGLGETUNIFORMLOCATIONPROC)load("glGetUniformLocation"); + glad_glGetUniformfv = (PFNGLGETUNIFORMFVPROC)load("glGetUniformfv"); + glad_glGetUniformiv = (PFNGLGETUNIFORMIVPROC)load("glGetUniformiv"); + glad_glGetVertexAttribdv = (PFNGLGETVERTEXATTRIBDVPROC)load("glGetVertexAttribdv"); + glad_glGetVertexAttribfv = (PFNGLGETVERTEXATTRIBFVPROC)load("glGetVertexAttribfv"); + glad_glGetVertexAttribiv = (PFNGLGETVERTEXATTRIBIVPROC)load("glGetVertexAttribiv"); + glad_glGetVertexAttribPointerv = (PFNGLGETVERTEXATTRIBPOINTERVPROC)load("glGetVertexAttribPointerv"); + glad_glIsProgram = (PFNGLISPROGRAMPROC)load("glIsProgram"); + glad_glIsShader = (PFNGLISSHADERPROC)load("glIsShader"); + glad_glLinkProgram = (PFNGLLINKPROGRAMPROC)load("glLinkProgram"); + glad_glShaderSource = (PFNGLSHADERSOURCEPROC)load("glShaderSource"); + glad_glUseProgram = (PFNGLUSEPROGRAMPROC)load("glUseProgram"); + glad_glUniform1f = (PFNGLUNIFORM1FPROC)load("glUniform1f"); + glad_glUniform2f = (PFNGLUNIFORM2FPROC)load("glUniform2f"); + glad_glUniform3f = (PFNGLUNIFORM3FPROC)load("glUniform3f"); + glad_glUniform4f = (PFNGLUNIFORM4FPROC)load("glUniform4f"); + glad_glUniform1i = (PFNGLUNIFORM1IPROC)load("glUniform1i"); + glad_glUniform2i = (PFNGLUNIFORM2IPROC)load("glUniform2i"); + glad_glUniform3i = (PFNGLUNIFORM3IPROC)load("glUniform3i"); + glad_glUniform4i = (PFNGLUNIFORM4IPROC)load("glUniform4i"); + glad_glUniform1fv = (PFNGLUNIFORM1FVPROC)load("glUniform1fv"); + glad_glUniform2fv = (PFNGLUNIFORM2FVPROC)load("glUniform2fv"); + glad_glUniform3fv = (PFNGLUNIFORM3FVPROC)load("glUniform3fv"); + glad_glUniform4fv = (PFNGLUNIFORM4FVPROC)load("glUniform4fv"); + glad_glUniform1iv = (PFNGLUNIFORM1IVPROC)load("glUniform1iv"); + glad_glUniform2iv = (PFNGLUNIFORM2IVPROC)load("glUniform2iv"); + glad_glUniform3iv = (PFNGLUNIFORM3IVPROC)load("glUniform3iv"); + glad_glUniform4iv = (PFNGLUNIFORM4IVPROC)load("glUniform4iv"); + glad_glUniformMatrix2fv = (PFNGLUNIFORMMATRIX2FVPROC)load("glUniformMatrix2fv"); + glad_glUniformMatrix3fv = (PFNGLUNIFORMMATRIX3FVPROC)load("glUniformMatrix3fv"); + glad_glUniformMatrix4fv = (PFNGLUNIFORMMATRIX4FVPROC)load("glUniformMatrix4fv"); + glad_glValidateProgram = (PFNGLVALIDATEPROGRAMPROC)load("glValidateProgram"); + glad_glVertexAttrib1d = (PFNGLVERTEXATTRIB1DPROC)load("glVertexAttrib1d"); + glad_glVertexAttrib1dv = (PFNGLVERTEXATTRIB1DVPROC)load("glVertexAttrib1dv"); + glad_glVertexAttrib1f = (PFNGLVERTEXATTRIB1FPROC)load("glVertexAttrib1f"); + glad_glVertexAttrib1fv = (PFNGLVERTEXATTRIB1FVPROC)load("glVertexAttrib1fv"); + glad_glVertexAttrib1s = (PFNGLVERTEXATTRIB1SPROC)load("glVertexAttrib1s"); + glad_glVertexAttrib1sv = (PFNGLVERTEXATTRIB1SVPROC)load("glVertexAttrib1sv"); + glad_glVertexAttrib2d = (PFNGLVERTEXATTRIB2DPROC)load("glVertexAttrib2d"); + glad_glVertexAttrib2dv = (PFNGLVERTEXATTRIB2DVPROC)load("glVertexAttrib2dv"); + glad_glVertexAttrib2f = (PFNGLVERTEXATTRIB2FPROC)load("glVertexAttrib2f"); + glad_glVertexAttrib2fv = (PFNGLVERTEXATTRIB2FVPROC)load("glVertexAttrib2fv"); + glad_glVertexAttrib2s = (PFNGLVERTEXATTRIB2SPROC)load("glVertexAttrib2s"); + glad_glVertexAttrib2sv = (PFNGLVERTEXATTRIB2SVPROC)load("glVertexAttrib2sv"); + glad_glVertexAttrib3d = (PFNGLVERTEXATTRIB3DPROC)load("glVertexAttrib3d"); + glad_glVertexAttrib3dv = (PFNGLVERTEXATTRIB3DVPROC)load("glVertexAttrib3dv"); + glad_glVertexAttrib3f = (PFNGLVERTEXATTRIB3FPROC)load("glVertexAttrib3f"); + glad_glVertexAttrib3fv = (PFNGLVERTEXATTRIB3FVPROC)load("glVertexAttrib3fv"); + glad_glVertexAttrib3s = (PFNGLVERTEXATTRIB3SPROC)load("glVertexAttrib3s"); + glad_glVertexAttrib3sv = (PFNGLVERTEXATTRIB3SVPROC)load("glVertexAttrib3sv"); + glad_glVertexAttrib4Nbv = (PFNGLVERTEXATTRIB4NBVPROC)load("glVertexAttrib4Nbv"); + glad_glVertexAttrib4Niv = (PFNGLVERTEXATTRIB4NIVPROC)load("glVertexAttrib4Niv"); + glad_glVertexAttrib4Nsv = (PFNGLVERTEXATTRIB4NSVPROC)load("glVertexAttrib4Nsv"); + glad_glVertexAttrib4Nub = (PFNGLVERTEXATTRIB4NUBPROC)load("glVertexAttrib4Nub"); + glad_glVertexAttrib4Nubv = (PFNGLVERTEXATTRIB4NUBVPROC)load("glVertexAttrib4Nubv"); + glad_glVertexAttrib4Nuiv = (PFNGLVERTEXATTRIB4NUIVPROC)load("glVertexAttrib4Nuiv"); + glad_glVertexAttrib4Nusv = (PFNGLVERTEXATTRIB4NUSVPROC)load("glVertexAttrib4Nusv"); + glad_glVertexAttrib4bv = (PFNGLVERTEXATTRIB4BVPROC)load("glVertexAttrib4bv"); + glad_glVertexAttrib4d = (PFNGLVERTEXATTRIB4DPROC)load("glVertexAttrib4d"); + glad_glVertexAttrib4dv = (PFNGLVERTEXATTRIB4DVPROC)load("glVertexAttrib4dv"); + glad_glVertexAttrib4f = (PFNGLVERTEXATTRIB4FPROC)load("glVertexAttrib4f"); + glad_glVertexAttrib4fv = (PFNGLVERTEXATTRIB4FVPROC)load("glVertexAttrib4fv"); + glad_glVertexAttrib4iv = (PFNGLVERTEXATTRIB4IVPROC)load("glVertexAttrib4iv"); + glad_glVertexAttrib4s = (PFNGLVERTEXATTRIB4SPROC)load("glVertexAttrib4s"); + glad_glVertexAttrib4sv = (PFNGLVERTEXATTRIB4SVPROC)load("glVertexAttrib4sv"); + glad_glVertexAttrib4ubv = (PFNGLVERTEXATTRIB4UBVPROC)load("glVertexAttrib4ubv"); + glad_glVertexAttrib4uiv = (PFNGLVERTEXATTRIB4UIVPROC)load("glVertexAttrib4uiv"); + glad_glVertexAttrib4usv = (PFNGLVERTEXATTRIB4USVPROC)load("glVertexAttrib4usv"); + glad_glVertexAttribPointer = (PFNGLVERTEXATTRIBPOINTERPROC)load("glVertexAttribPointer"); +} +static int find_extensionsGL(void) { + if (!get_exts()) return 0; + (void)&has_ext; + free_exts(); + return 1; +} + +static void find_coreGL(void) { + + /* Thank you @elmindreda + * https://github.com/elmindreda/greg/blob/master/templates/greg.c.in#L176 + * https://github.com/glfw/glfw/blob/master/src/context.c#L36 + */ + int i, major, minor; + + const char* version; + const char* prefixes[] = { + "OpenGL ES-CM ", + "OpenGL ES-CL ", + "OpenGL ES ", + NULL + }; + + version = (const char*) glGetString(GL_VERSION); + if (!version) return; + + for (i = 0; prefixes[i]; i++) { + const size_t length = strlen(prefixes[i]); + if (strncmp(version, prefixes[i], length) == 0) { + version += length; + break; + } + } + +/* PR #18 */ +#ifdef _MSC_VER + sscanf_s(version, "%d.%d", &major, &minor); +#else + sscanf(version, "%d.%d", &major, &minor); +#endif + + GLVersion.major = major; GLVersion.minor = minor; + max_loaded_major = major; max_loaded_minor = minor; + GLAD_GL_VERSION_1_0 = (major == 1 && minor >= 0) || major > 1; + GLAD_GL_VERSION_1_1 = (major == 1 && minor >= 1) || major > 1; + GLAD_GL_VERSION_1_2 = (major == 1 && minor >= 2) || major > 1; + GLAD_GL_VERSION_1_3 = (major == 1 && minor >= 3) || major > 1; + GLAD_GL_VERSION_1_4 = (major == 1 && minor >= 4) || major > 1; + GLAD_GL_VERSION_1_5 = (major == 1 && minor >= 5) || major > 1; + GLAD_GL_VERSION_2_0 = (major == 2 && minor >= 0) || major > 2; + if (GLVersion.major > 2 || (GLVersion.major >= 2 && GLVersion.minor >= 0)) { + max_loaded_major = 2; + max_loaded_minor = 0; + } +} + +int gladLoadGLLoader(GLADloadproc load) { + GLVersion.major = 0; GLVersion.minor = 0; + glGetString = (PFNGLGETSTRINGPROC)load("glGetString"); + if(glGetString == NULL) return 0; + if(glGetString(GL_VERSION) == NULL) return 0; + find_coreGL(); + load_GL_VERSION_1_0(load); + load_GL_VERSION_1_1(load); + load_GL_VERSION_1_2(load); + load_GL_VERSION_1_3(load); + load_GL_VERSION_1_4(load); + load_GL_VERSION_1_5(load); + load_GL_VERSION_2_0(load); + + if (!find_extensionsGL()) return 0; + return GLVersion.major != 0 || GLVersion.minor != 0; +} + diff --git a/tcod_sys/libtcod/src/vendor/glad.h b/tcod_sys/libtcod/src/vendor/glad.h new file mode 100644 index 000000000..19f7a4306 --- /dev/null +++ b/tcod_sys/libtcod/src/vendor/glad.h @@ -0,0 +1,2656 @@ +/* + + OpenGL loader generated by glad 0.1.28 on Mon Nov 19 11:18:35 2018. + + Language/Generator: C/C++ + Specification: gl + APIs: gl=2.0 + Profile: compatibility + Extensions: + + Loader: False + Local files: True + Omit khrplatform: False + Reproducible: False + + Commandline: + --profile="compatibility" --api="gl=2.0" --generator="c" --spec="gl" --no-loader --local-files --extensions="" + Online: + https://glad.dav1d.de/#profile=compatibility&language=c&specification=gl&api=gl%3D2.0 +*/ + + +#ifndef __glad_h_ +#define __glad_h_ + +#ifdef __gl_h_ +#error OpenGL header already included, remove this include, glad already provides it +#endif +#define __gl_h_ + +#if defined(_WIN32) && !defined(APIENTRY) && !defined(__CYGWIN__) && !defined(__SCITECH_SNAP__) +#ifndef WIN32_LEAN_AND_MEAN +#define WIN32_LEAN_AND_MEAN 1 +#endif +#ifndef NOMINMAX +#define NOMINMAX 1 +#endif +#include +#endif + +#ifndef APIENTRY +#define APIENTRY +#endif +#ifndef APIENTRYP +#define APIENTRYP APIENTRY * +#endif + +#ifndef GLAPIENTRY +#define GLAPIENTRY APIENTRY +#endif + +#ifdef __cplusplus +extern "C" { +#endif + +struct gladGLversionStruct { + int major; + int minor; +}; + +typedef void* (* GLADloadproc)(const char *name); + +#ifndef GLAPI +# if defined(GLAD_GLAPI_EXPORT) +# if defined(_WIN32) || defined(__CYGWIN__) +# if defined(GLAD_GLAPI_EXPORT_BUILD) +# if defined(__GNUC__) +# define GLAPI __attribute__ ((dllexport)) extern +# else +# define GLAPI __declspec(dllexport) extern +# endif +# else +# if defined(__GNUC__) +# define GLAPI __attribute__ ((dllimport)) extern +# else +# define GLAPI __declspec(dllimport) extern +# endif +# endif +# elif defined(__GNUC__) && defined(GLAD_GLAPI_EXPORT_BUILD) +# define GLAPI __attribute__ ((visibility ("default"))) extern +# else +# define GLAPI extern +# endif +# else +# define GLAPI extern +# endif +#endif + +GLAPI struct gladGLversionStruct GLVersion; +GLAPI int gladLoadGLLoader(GLADloadproc); + +#include "khrplatform.h" +typedef unsigned int GLenum; +typedef unsigned char GLboolean; +typedef unsigned int GLbitfield; +typedef void GLvoid; +typedef khronos_int8_t GLbyte; +typedef khronos_uint8_t GLubyte; +typedef khronos_int16_t GLshort; +typedef khronos_uint16_t GLushort; +typedef int GLint; +typedef unsigned int GLuint; +typedef khronos_int32_t GLclampx; +typedef int GLsizei; +typedef khronos_float_t GLfloat; +typedef khronos_float_t GLclampf; +typedef double GLdouble; +typedef double GLclampd; +typedef void *GLeglClientBufferEXT; +typedef void *GLeglImageOES; +typedef char GLchar; +typedef char GLcharARB; +#ifdef __APPLE__ +typedef void *GLhandleARB; +#else +typedef unsigned int GLhandleARB; +#endif +typedef khronos_uint16_t GLhalf; +typedef khronos_uint16_t GLhalfARB; +typedef khronos_int32_t GLfixed; +typedef khronos_intptr_t GLintptr; +typedef khronos_intptr_t GLintptrARB; +typedef khronos_ssize_t GLsizeiptr; +typedef khronos_ssize_t GLsizeiptrARB; +typedef khronos_int64_t GLint64; +typedef khronos_int64_t GLint64EXT; +typedef khronos_uint64_t GLuint64; +typedef khronos_uint64_t GLuint64EXT; +typedef struct __GLsync *GLsync; +struct _cl_context; +struct _cl_event; +typedef void (APIENTRY *GLDEBUGPROC)(GLenum source,GLenum type,GLuint id,GLenum severity,GLsizei length,const GLchar *message,const void *userParam); +typedef void (APIENTRY *GLDEBUGPROCARB)(GLenum source,GLenum type,GLuint id,GLenum severity,GLsizei length,const GLchar *message,const void *userParam); +typedef void (APIENTRY *GLDEBUGPROCKHR)(GLenum source,GLenum type,GLuint id,GLenum severity,GLsizei length,const GLchar *message,const void *userParam); +typedef void (APIENTRY *GLDEBUGPROCAMD)(GLuint id,GLenum category,GLenum severity,GLsizei length,const GLchar *message,void *userParam); +typedef unsigned short GLhalfNV; +typedef GLintptr GLvdpauSurfaceNV; +typedef void (APIENTRY *GLVULKANPROCNV)(void); +#define GL_DEPTH_BUFFER_BIT 0x00000100 +#define GL_STENCIL_BUFFER_BIT 0x00000400 +#define GL_COLOR_BUFFER_BIT 0x00004000 +#define GL_FALSE 0 +#define GL_TRUE 1 +#define GL_POINTS 0x0000 +#define GL_LINES 0x0001 +#define GL_LINE_LOOP 0x0002 +#define GL_LINE_STRIP 0x0003 +#define GL_TRIANGLES 0x0004 +#define GL_TRIANGLE_STRIP 0x0005 +#define GL_TRIANGLE_FAN 0x0006 +#define GL_QUADS 0x0007 +#define GL_NEVER 0x0200 +#define GL_LESS 0x0201 +#define GL_EQUAL 0x0202 +#define GL_LEQUAL 0x0203 +#define GL_GREATER 0x0204 +#define GL_NOTEQUAL 0x0205 +#define GL_GEQUAL 0x0206 +#define GL_ALWAYS 0x0207 +#define GL_ZERO 0 +#define GL_ONE 1 +#define GL_SRC_COLOR 0x0300 +#define GL_ONE_MINUS_SRC_COLOR 0x0301 +#define GL_SRC_ALPHA 0x0302 +#define GL_ONE_MINUS_SRC_ALPHA 0x0303 +#define GL_DST_ALPHA 0x0304 +#define GL_ONE_MINUS_DST_ALPHA 0x0305 +#define GL_DST_COLOR 0x0306 +#define GL_ONE_MINUS_DST_COLOR 0x0307 +#define GL_SRC_ALPHA_SATURATE 0x0308 +#define GL_NONE 0 +#define GL_FRONT_LEFT 0x0400 +#define GL_FRONT_RIGHT 0x0401 +#define GL_BACK_LEFT 0x0402 +#define GL_BACK_RIGHT 0x0403 +#define GL_FRONT 0x0404 +#define GL_BACK 0x0405 +#define GL_LEFT 0x0406 +#define GL_RIGHT 0x0407 +#define GL_FRONT_AND_BACK 0x0408 +#define GL_NO_ERROR 0 +#define GL_INVALID_ENUM 0x0500 +#define GL_INVALID_VALUE 0x0501 +#define GL_INVALID_OPERATION 0x0502 +#define GL_OUT_OF_MEMORY 0x0505 +#define GL_CW 0x0900 +#define GL_CCW 0x0901 +#define GL_POINT_SIZE 0x0B11 +#define GL_POINT_SIZE_RANGE 0x0B12 +#define GL_POINT_SIZE_GRANULARITY 0x0B13 +#define GL_LINE_SMOOTH 0x0B20 +#define GL_LINE_WIDTH 0x0B21 +#define GL_LINE_WIDTH_RANGE 0x0B22 +#define GL_LINE_WIDTH_GRANULARITY 0x0B23 +#define GL_POLYGON_MODE 0x0B40 +#define GL_POLYGON_SMOOTH 0x0B41 +#define GL_CULL_FACE 0x0B44 +#define GL_CULL_FACE_MODE 0x0B45 +#define GL_FRONT_FACE 0x0B46 +#define GL_DEPTH_RANGE 0x0B70 +#define GL_DEPTH_TEST 0x0B71 +#define GL_DEPTH_WRITEMASK 0x0B72 +#define GL_DEPTH_CLEAR_VALUE 0x0B73 +#define GL_DEPTH_FUNC 0x0B74 +#define GL_STENCIL_TEST 0x0B90 +#define GL_STENCIL_CLEAR_VALUE 0x0B91 +#define GL_STENCIL_FUNC 0x0B92 +#define GL_STENCIL_VALUE_MASK 0x0B93 +#define GL_STENCIL_FAIL 0x0B94 +#define GL_STENCIL_PASS_DEPTH_FAIL 0x0B95 +#define GL_STENCIL_PASS_DEPTH_PASS 0x0B96 +#define GL_STENCIL_REF 0x0B97 +#define GL_STENCIL_WRITEMASK 0x0B98 +#define GL_VIEWPORT 0x0BA2 +#define GL_DITHER 0x0BD0 +#define GL_BLEND_DST 0x0BE0 +#define GL_BLEND_SRC 0x0BE1 +#define GL_BLEND 0x0BE2 +#define GL_LOGIC_OP_MODE 0x0BF0 +#define GL_DRAW_BUFFER 0x0C01 +#define GL_READ_BUFFER 0x0C02 +#define GL_SCISSOR_BOX 0x0C10 +#define GL_SCISSOR_TEST 0x0C11 +#define GL_COLOR_CLEAR_VALUE 0x0C22 +#define GL_COLOR_WRITEMASK 0x0C23 +#define GL_DOUBLEBUFFER 0x0C32 +#define GL_STEREO 0x0C33 +#define GL_LINE_SMOOTH_HINT 0x0C52 +#define GL_POLYGON_SMOOTH_HINT 0x0C53 +#define GL_UNPACK_SWAP_BYTES 0x0CF0 +#define GL_UNPACK_LSB_FIRST 0x0CF1 +#define GL_UNPACK_ROW_LENGTH 0x0CF2 +#define GL_UNPACK_SKIP_ROWS 0x0CF3 +#define GL_UNPACK_SKIP_PIXELS 0x0CF4 +#define GL_UNPACK_ALIGNMENT 0x0CF5 +#define GL_PACK_SWAP_BYTES 0x0D00 +#define GL_PACK_LSB_FIRST 0x0D01 +#define GL_PACK_ROW_LENGTH 0x0D02 +#define GL_PACK_SKIP_ROWS 0x0D03 +#define GL_PACK_SKIP_PIXELS 0x0D04 +#define GL_PACK_ALIGNMENT 0x0D05 +#define GL_MAX_TEXTURE_SIZE 0x0D33 +#define GL_MAX_VIEWPORT_DIMS 0x0D3A +#define GL_SUBPIXEL_BITS 0x0D50 +#define GL_TEXTURE_1D 0x0DE0 +#define GL_TEXTURE_2D 0x0DE1 +#define GL_TEXTURE_WIDTH 0x1000 +#define GL_TEXTURE_HEIGHT 0x1001 +#define GL_TEXTURE_BORDER_COLOR 0x1004 +#define GL_DONT_CARE 0x1100 +#define GL_FASTEST 0x1101 +#define GL_NICEST 0x1102 +#define GL_BYTE 0x1400 +#define GL_UNSIGNED_BYTE 0x1401 +#define GL_SHORT 0x1402 +#define GL_UNSIGNED_SHORT 0x1403 +#define GL_INT 0x1404 +#define GL_UNSIGNED_INT 0x1405 +#define GL_FLOAT 0x1406 +#define GL_STACK_OVERFLOW 0x0503 +#define GL_STACK_UNDERFLOW 0x0504 +#define GL_CLEAR 0x1500 +#define GL_AND 0x1501 +#define GL_AND_REVERSE 0x1502 +#define GL_COPY 0x1503 +#define GL_AND_INVERTED 0x1504 +#define GL_NOOP 0x1505 +#define GL_XOR 0x1506 +#define GL_OR 0x1507 +#define GL_NOR 0x1508 +#define GL_EQUIV 0x1509 +#define GL_INVERT 0x150A +#define GL_OR_REVERSE 0x150B +#define GL_COPY_INVERTED 0x150C +#define GL_OR_INVERTED 0x150D +#define GL_NAND 0x150E +#define GL_SET 0x150F +#define GL_TEXTURE 0x1702 +#define GL_COLOR 0x1800 +#define GL_DEPTH 0x1801 +#define GL_STENCIL 0x1802 +#define GL_STENCIL_INDEX 0x1901 +#define GL_DEPTH_COMPONENT 0x1902 +#define GL_RED 0x1903 +#define GL_GREEN 0x1904 +#define GL_BLUE 0x1905 +#define GL_ALPHA 0x1906 +#define GL_RGB 0x1907 +#define GL_RGBA 0x1908 +#define GL_POINT 0x1B00 +#define GL_LINE 0x1B01 +#define GL_FILL 0x1B02 +#define GL_KEEP 0x1E00 +#define GL_REPLACE 0x1E01 +#define GL_INCR 0x1E02 +#define GL_DECR 0x1E03 +#define GL_VENDOR 0x1F00 +#define GL_RENDERER 0x1F01 +#define GL_VERSION 0x1F02 +#define GL_EXTENSIONS 0x1F03 +#define GL_NEAREST 0x2600 +#define GL_LINEAR 0x2601 +#define GL_NEAREST_MIPMAP_NEAREST 0x2700 +#define GL_LINEAR_MIPMAP_NEAREST 0x2701 +#define GL_NEAREST_MIPMAP_LINEAR 0x2702 +#define GL_LINEAR_MIPMAP_LINEAR 0x2703 +#define GL_TEXTURE_MAG_FILTER 0x2800 +#define GL_TEXTURE_MIN_FILTER 0x2801 +#define GL_TEXTURE_WRAP_S 0x2802 +#define GL_TEXTURE_WRAP_T 0x2803 +#define GL_REPEAT 0x2901 +#define GL_CURRENT_BIT 0x00000001 +#define GL_POINT_BIT 0x00000002 +#define GL_LINE_BIT 0x00000004 +#define GL_POLYGON_BIT 0x00000008 +#define GL_POLYGON_STIPPLE_BIT 0x00000010 +#define GL_PIXEL_MODE_BIT 0x00000020 +#define GL_LIGHTING_BIT 0x00000040 +#define GL_FOG_BIT 0x00000080 +#define GL_ACCUM_BUFFER_BIT 0x00000200 +#define GL_VIEWPORT_BIT 0x00000800 +#define GL_TRANSFORM_BIT 0x00001000 +#define GL_ENABLE_BIT 0x00002000 +#define GL_HINT_BIT 0x00008000 +#define GL_EVAL_BIT 0x00010000 +#define GL_LIST_BIT 0x00020000 +#define GL_TEXTURE_BIT 0x00040000 +#define GL_SCISSOR_BIT 0x00080000 +#define GL_ALL_ATTRIB_BITS 0xFFFFFFFF +#define GL_QUAD_STRIP 0x0008 +#define GL_POLYGON 0x0009 +#define GL_ACCUM 0x0100 +#define GL_LOAD 0x0101 +#define GL_RETURN 0x0102 +#define GL_MULT 0x0103 +#define GL_ADD 0x0104 +#define GL_AUX0 0x0409 +#define GL_AUX1 0x040A +#define GL_AUX2 0x040B +#define GL_AUX3 0x040C +#define GL_2D 0x0600 +#define GL_3D 0x0601 +#define GL_3D_COLOR 0x0602 +#define GL_3D_COLOR_TEXTURE 0x0603 +#define GL_4D_COLOR_TEXTURE 0x0604 +#define GL_PASS_THROUGH_TOKEN 0x0700 +#define GL_POINT_TOKEN 0x0701 +#define GL_LINE_TOKEN 0x0702 +#define GL_POLYGON_TOKEN 0x0703 +#define GL_BITMAP_TOKEN 0x0704 +#define GL_DRAW_PIXEL_TOKEN 0x0705 +#define GL_COPY_PIXEL_TOKEN 0x0706 +#define GL_LINE_RESET_TOKEN 0x0707 +#define GL_EXP 0x0800 +#define GL_EXP2 0x0801 +#define GL_COEFF 0x0A00 +#define GL_ORDER 0x0A01 +#define GL_DOMAIN 0x0A02 +#define GL_PIXEL_MAP_I_TO_I 0x0C70 +#define GL_PIXEL_MAP_S_TO_S 0x0C71 +#define GL_PIXEL_MAP_I_TO_R 0x0C72 +#define GL_PIXEL_MAP_I_TO_G 0x0C73 +#define GL_PIXEL_MAP_I_TO_B 0x0C74 +#define GL_PIXEL_MAP_I_TO_A 0x0C75 +#define GL_PIXEL_MAP_R_TO_R 0x0C76 +#define GL_PIXEL_MAP_G_TO_G 0x0C77 +#define GL_PIXEL_MAP_B_TO_B 0x0C78 +#define GL_PIXEL_MAP_A_TO_A 0x0C79 +#define GL_CURRENT_COLOR 0x0B00 +#define GL_CURRENT_INDEX 0x0B01 +#define GL_CURRENT_NORMAL 0x0B02 +#define GL_CURRENT_TEXTURE_COORDS 0x0B03 +#define GL_CURRENT_RASTER_COLOR 0x0B04 +#define GL_CURRENT_RASTER_INDEX 0x0B05 +#define GL_CURRENT_RASTER_TEXTURE_COORDS 0x0B06 +#define GL_CURRENT_RASTER_POSITION 0x0B07 +#define GL_CURRENT_RASTER_POSITION_VALID 0x0B08 +#define GL_CURRENT_RASTER_DISTANCE 0x0B09 +#define GL_POINT_SMOOTH 0x0B10 +#define GL_LINE_STIPPLE 0x0B24 +#define GL_LINE_STIPPLE_PATTERN 0x0B25 +#define GL_LINE_STIPPLE_REPEAT 0x0B26 +#define GL_LIST_MODE 0x0B30 +#define GL_MAX_LIST_NESTING 0x0B31 +#define GL_LIST_BASE 0x0B32 +#define GL_LIST_INDEX 0x0B33 +#define GL_POLYGON_STIPPLE 0x0B42 +#define GL_EDGE_FLAG 0x0B43 +#define GL_LIGHTING 0x0B50 +#define GL_LIGHT_MODEL_LOCAL_VIEWER 0x0B51 +#define GL_LIGHT_MODEL_TWO_SIDE 0x0B52 +#define GL_LIGHT_MODEL_AMBIENT 0x0B53 +#define GL_SHADE_MODEL 0x0B54 +#define GL_COLOR_MATERIAL_FACE 0x0B55 +#define GL_COLOR_MATERIAL_PARAMETER 0x0B56 +#define GL_COLOR_MATERIAL 0x0B57 +#define GL_FOG 0x0B60 +#define GL_FOG_INDEX 0x0B61 +#define GL_FOG_DENSITY 0x0B62 +#define GL_FOG_START 0x0B63 +#define GL_FOG_END 0x0B64 +#define GL_FOG_MODE 0x0B65 +#define GL_FOG_COLOR 0x0B66 +#define GL_ACCUM_CLEAR_VALUE 0x0B80 +#define GL_MATRIX_MODE 0x0BA0 +#define GL_NORMALIZE 0x0BA1 +#define GL_MODELVIEW_STACK_DEPTH 0x0BA3 +#define GL_PROJECTION_STACK_DEPTH 0x0BA4 +#define GL_TEXTURE_STACK_DEPTH 0x0BA5 +#define GL_MODELVIEW_MATRIX 0x0BA6 +#define GL_PROJECTION_MATRIX 0x0BA7 +#define GL_TEXTURE_MATRIX 0x0BA8 +#define GL_ATTRIB_STACK_DEPTH 0x0BB0 +#define GL_ALPHA_TEST 0x0BC0 +#define GL_ALPHA_TEST_FUNC 0x0BC1 +#define GL_ALPHA_TEST_REF 0x0BC2 +#define GL_LOGIC_OP 0x0BF1 +#define GL_AUX_BUFFERS 0x0C00 +#define GL_INDEX_CLEAR_VALUE 0x0C20 +#define GL_INDEX_WRITEMASK 0x0C21 +#define GL_INDEX_MODE 0x0C30 +#define GL_RGBA_MODE 0x0C31 +#define GL_RENDER_MODE 0x0C40 +#define GL_PERSPECTIVE_CORRECTION_HINT 0x0C50 +#define GL_POINT_SMOOTH_HINT 0x0C51 +#define GL_FOG_HINT 0x0C54 +#define GL_TEXTURE_GEN_S 0x0C60 +#define GL_TEXTURE_GEN_T 0x0C61 +#define GL_TEXTURE_GEN_R 0x0C62 +#define GL_TEXTURE_GEN_Q 0x0C63 +#define GL_PIXEL_MAP_I_TO_I_SIZE 0x0CB0 +#define GL_PIXEL_MAP_S_TO_S_SIZE 0x0CB1 +#define GL_PIXEL_MAP_I_TO_R_SIZE 0x0CB2 +#define GL_PIXEL_MAP_I_TO_G_SIZE 0x0CB3 +#define GL_PIXEL_MAP_I_TO_B_SIZE 0x0CB4 +#define GL_PIXEL_MAP_I_TO_A_SIZE 0x0CB5 +#define GL_PIXEL_MAP_R_TO_R_SIZE 0x0CB6 +#define GL_PIXEL_MAP_G_TO_G_SIZE 0x0CB7 +#define GL_PIXEL_MAP_B_TO_B_SIZE 0x0CB8 +#define GL_PIXEL_MAP_A_TO_A_SIZE 0x0CB9 +#define GL_MAP_COLOR 0x0D10 +#define GL_MAP_STENCIL 0x0D11 +#define GL_INDEX_SHIFT 0x0D12 +#define GL_INDEX_OFFSET 0x0D13 +#define GL_RED_SCALE 0x0D14 +#define GL_RED_BIAS 0x0D15 +#define GL_ZOOM_X 0x0D16 +#define GL_ZOOM_Y 0x0D17 +#define GL_GREEN_SCALE 0x0D18 +#define GL_GREEN_BIAS 0x0D19 +#define GL_BLUE_SCALE 0x0D1A +#define GL_BLUE_BIAS 0x0D1B +#define GL_ALPHA_SCALE 0x0D1C +#define GL_ALPHA_BIAS 0x0D1D +#define GL_DEPTH_SCALE 0x0D1E +#define GL_DEPTH_BIAS 0x0D1F +#define GL_MAX_EVAL_ORDER 0x0D30 +#define GL_MAX_LIGHTS 0x0D31 +#define GL_MAX_CLIP_PLANES 0x0D32 +#define GL_MAX_PIXEL_MAP_TABLE 0x0D34 +#define GL_MAX_ATTRIB_STACK_DEPTH 0x0D35 +#define GL_MAX_MODELVIEW_STACK_DEPTH 0x0D36 +#define GL_MAX_NAME_STACK_DEPTH 0x0D37 +#define GL_MAX_PROJECTION_STACK_DEPTH 0x0D38 +#define GL_MAX_TEXTURE_STACK_DEPTH 0x0D39 +#define GL_INDEX_BITS 0x0D51 +#define GL_RED_BITS 0x0D52 +#define GL_GREEN_BITS 0x0D53 +#define GL_BLUE_BITS 0x0D54 +#define GL_ALPHA_BITS 0x0D55 +#define GL_DEPTH_BITS 0x0D56 +#define GL_STENCIL_BITS 0x0D57 +#define GL_ACCUM_RED_BITS 0x0D58 +#define GL_ACCUM_GREEN_BITS 0x0D59 +#define GL_ACCUM_BLUE_BITS 0x0D5A +#define GL_ACCUM_ALPHA_BITS 0x0D5B +#define GL_NAME_STACK_DEPTH 0x0D70 +#define GL_AUTO_NORMAL 0x0D80 +#define GL_MAP1_COLOR_4 0x0D90 +#define GL_MAP1_INDEX 0x0D91 +#define GL_MAP1_NORMAL 0x0D92 +#define GL_MAP1_TEXTURE_COORD_1 0x0D93 +#define GL_MAP1_TEXTURE_COORD_2 0x0D94 +#define GL_MAP1_TEXTURE_COORD_3 0x0D95 +#define GL_MAP1_TEXTURE_COORD_4 0x0D96 +#define GL_MAP1_VERTEX_3 0x0D97 +#define GL_MAP1_VERTEX_4 0x0D98 +#define GL_MAP2_COLOR_4 0x0DB0 +#define GL_MAP2_INDEX 0x0DB1 +#define GL_MAP2_NORMAL 0x0DB2 +#define GL_MAP2_TEXTURE_COORD_1 0x0DB3 +#define GL_MAP2_TEXTURE_COORD_2 0x0DB4 +#define GL_MAP2_TEXTURE_COORD_3 0x0DB5 +#define GL_MAP2_TEXTURE_COORD_4 0x0DB6 +#define GL_MAP2_VERTEX_3 0x0DB7 +#define GL_MAP2_VERTEX_4 0x0DB8 +#define GL_MAP1_GRID_DOMAIN 0x0DD0 +#define GL_MAP1_GRID_SEGMENTS 0x0DD1 +#define GL_MAP2_GRID_DOMAIN 0x0DD2 +#define GL_MAP2_GRID_SEGMENTS 0x0DD3 +#define GL_TEXTURE_COMPONENTS 0x1003 +#define GL_TEXTURE_BORDER 0x1005 +#define GL_AMBIENT 0x1200 +#define GL_DIFFUSE 0x1201 +#define GL_SPECULAR 0x1202 +#define GL_POSITION 0x1203 +#define GL_SPOT_DIRECTION 0x1204 +#define GL_SPOT_EXPONENT 0x1205 +#define GL_SPOT_CUTOFF 0x1206 +#define GL_CONSTANT_ATTENUATION 0x1207 +#define GL_LINEAR_ATTENUATION 0x1208 +#define GL_QUADRATIC_ATTENUATION 0x1209 +#define GL_COMPILE 0x1300 +#define GL_COMPILE_AND_EXECUTE 0x1301 +#define GL_2_BYTES 0x1407 +#define GL_3_BYTES 0x1408 +#define GL_4_BYTES 0x1409 +#define GL_EMISSION 0x1600 +#define GL_SHININESS 0x1601 +#define GL_AMBIENT_AND_DIFFUSE 0x1602 +#define GL_COLOR_INDEXES 0x1603 +#define GL_MODELVIEW 0x1700 +#define GL_PROJECTION 0x1701 +#define GL_COLOR_INDEX 0x1900 +#define GL_LUMINANCE 0x1909 +#define GL_LUMINANCE_ALPHA 0x190A +#define GL_BITMAP 0x1A00 +#define GL_RENDER 0x1C00 +#define GL_FEEDBACK 0x1C01 +#define GL_SELECT 0x1C02 +#define GL_FLAT 0x1D00 +#define GL_SMOOTH 0x1D01 +#define GL_S 0x2000 +#define GL_T 0x2001 +#define GL_R 0x2002 +#define GL_Q 0x2003 +#define GL_MODULATE 0x2100 +#define GL_DECAL 0x2101 +#define GL_TEXTURE_ENV_MODE 0x2200 +#define GL_TEXTURE_ENV_COLOR 0x2201 +#define GL_TEXTURE_ENV 0x2300 +#define GL_EYE_LINEAR 0x2400 +#define GL_OBJECT_LINEAR 0x2401 +#define GL_SPHERE_MAP 0x2402 +#define GL_TEXTURE_GEN_MODE 0x2500 +#define GL_OBJECT_PLANE 0x2501 +#define GL_EYE_PLANE 0x2502 +#define GL_CLAMP 0x2900 +#define GL_CLIP_PLANE0 0x3000 +#define GL_CLIP_PLANE1 0x3001 +#define GL_CLIP_PLANE2 0x3002 +#define GL_CLIP_PLANE3 0x3003 +#define GL_CLIP_PLANE4 0x3004 +#define GL_CLIP_PLANE5 0x3005 +#define GL_LIGHT0 0x4000 +#define GL_LIGHT1 0x4001 +#define GL_LIGHT2 0x4002 +#define GL_LIGHT3 0x4003 +#define GL_LIGHT4 0x4004 +#define GL_LIGHT5 0x4005 +#define GL_LIGHT6 0x4006 +#define GL_LIGHT7 0x4007 +#define GL_COLOR_LOGIC_OP 0x0BF2 +#define GL_POLYGON_OFFSET_UNITS 0x2A00 +#define GL_POLYGON_OFFSET_POINT 0x2A01 +#define GL_POLYGON_OFFSET_LINE 0x2A02 +#define GL_POLYGON_OFFSET_FILL 0x8037 +#define GL_POLYGON_OFFSET_FACTOR 0x8038 +#define GL_TEXTURE_BINDING_1D 0x8068 +#define GL_TEXTURE_BINDING_2D 0x8069 +#define GL_TEXTURE_INTERNAL_FORMAT 0x1003 +#define GL_TEXTURE_RED_SIZE 0x805C +#define GL_TEXTURE_GREEN_SIZE 0x805D +#define GL_TEXTURE_BLUE_SIZE 0x805E +#define GL_TEXTURE_ALPHA_SIZE 0x805F +#define GL_DOUBLE 0x140A +#define GL_PROXY_TEXTURE_1D 0x8063 +#define GL_PROXY_TEXTURE_2D 0x8064 +#define GL_R3_G3_B2 0x2A10 +#define GL_RGB4 0x804F +#define GL_RGB5 0x8050 +#define GL_RGB8 0x8051 +#define GL_RGB10 0x8052 +#define GL_RGB12 0x8053 +#define GL_RGB16 0x8054 +#define GL_RGBA2 0x8055 +#define GL_RGBA4 0x8056 +#define GL_RGB5_A1 0x8057 +#define GL_RGBA8 0x8058 +#define GL_RGB10_A2 0x8059 +#define GL_RGBA12 0x805A +#define GL_RGBA16 0x805B +#define GL_CLIENT_PIXEL_STORE_BIT 0x00000001 +#define GL_CLIENT_VERTEX_ARRAY_BIT 0x00000002 +#define GL_CLIENT_ALL_ATTRIB_BITS 0xFFFFFFFF +#define GL_VERTEX_ARRAY_POINTER 0x808E +#define GL_NORMAL_ARRAY_POINTER 0x808F +#define GL_COLOR_ARRAY_POINTER 0x8090 +#define GL_INDEX_ARRAY_POINTER 0x8091 +#define GL_TEXTURE_COORD_ARRAY_POINTER 0x8092 +#define GL_EDGE_FLAG_ARRAY_POINTER 0x8093 +#define GL_FEEDBACK_BUFFER_POINTER 0x0DF0 +#define GL_SELECTION_BUFFER_POINTER 0x0DF3 +#define GL_CLIENT_ATTRIB_STACK_DEPTH 0x0BB1 +#define GL_INDEX_LOGIC_OP 0x0BF1 +#define GL_MAX_CLIENT_ATTRIB_STACK_DEPTH 0x0D3B +#define GL_FEEDBACK_BUFFER_SIZE 0x0DF1 +#define GL_FEEDBACK_BUFFER_TYPE 0x0DF2 +#define GL_SELECTION_BUFFER_SIZE 0x0DF4 +#define GL_VERTEX_ARRAY 0x8074 +#define GL_NORMAL_ARRAY 0x8075 +#define GL_COLOR_ARRAY 0x8076 +#define GL_INDEX_ARRAY 0x8077 +#define GL_TEXTURE_COORD_ARRAY 0x8078 +#define GL_EDGE_FLAG_ARRAY 0x8079 +#define GL_VERTEX_ARRAY_SIZE 0x807A +#define GL_VERTEX_ARRAY_TYPE 0x807B +#define GL_VERTEX_ARRAY_STRIDE 0x807C +#define GL_NORMAL_ARRAY_TYPE 0x807E +#define GL_NORMAL_ARRAY_STRIDE 0x807F +#define GL_COLOR_ARRAY_SIZE 0x8081 +#define GL_COLOR_ARRAY_TYPE 0x8082 +#define GL_COLOR_ARRAY_STRIDE 0x8083 +#define GL_INDEX_ARRAY_TYPE 0x8085 +#define GL_INDEX_ARRAY_STRIDE 0x8086 +#define GL_TEXTURE_COORD_ARRAY_SIZE 0x8088 +#define GL_TEXTURE_COORD_ARRAY_TYPE 0x8089 +#define GL_TEXTURE_COORD_ARRAY_STRIDE 0x808A +#define GL_EDGE_FLAG_ARRAY_STRIDE 0x808C +#define GL_TEXTURE_LUMINANCE_SIZE 0x8060 +#define GL_TEXTURE_INTENSITY_SIZE 0x8061 +#define GL_TEXTURE_PRIORITY 0x8066 +#define GL_TEXTURE_RESIDENT 0x8067 +#define GL_ALPHA4 0x803B +#define GL_ALPHA8 0x803C +#define GL_ALPHA12 0x803D +#define GL_ALPHA16 0x803E +#define GL_LUMINANCE4 0x803F +#define GL_LUMINANCE8 0x8040 +#define GL_LUMINANCE12 0x8041 +#define GL_LUMINANCE16 0x8042 +#define GL_LUMINANCE4_ALPHA4 0x8043 +#define GL_LUMINANCE6_ALPHA2 0x8044 +#define GL_LUMINANCE8_ALPHA8 0x8045 +#define GL_LUMINANCE12_ALPHA4 0x8046 +#define GL_LUMINANCE12_ALPHA12 0x8047 +#define GL_LUMINANCE16_ALPHA16 0x8048 +#define GL_INTENSITY 0x8049 +#define GL_INTENSITY4 0x804A +#define GL_INTENSITY8 0x804B +#define GL_INTENSITY12 0x804C +#define GL_INTENSITY16 0x804D +#define GL_V2F 0x2A20 +#define GL_V3F 0x2A21 +#define GL_C4UB_V2F 0x2A22 +#define GL_C4UB_V3F 0x2A23 +#define GL_C3F_V3F 0x2A24 +#define GL_N3F_V3F 0x2A25 +#define GL_C4F_N3F_V3F 0x2A26 +#define GL_T2F_V3F 0x2A27 +#define GL_T4F_V4F 0x2A28 +#define GL_T2F_C4UB_V3F 0x2A29 +#define GL_T2F_C3F_V3F 0x2A2A +#define GL_T2F_N3F_V3F 0x2A2B +#define GL_T2F_C4F_N3F_V3F 0x2A2C +#define GL_T4F_C4F_N3F_V4F 0x2A2D +#define GL_UNSIGNED_BYTE_3_3_2 0x8032 +#define GL_UNSIGNED_SHORT_4_4_4_4 0x8033 +#define GL_UNSIGNED_SHORT_5_5_5_1 0x8034 +#define GL_UNSIGNED_INT_8_8_8_8 0x8035 +#define GL_UNSIGNED_INT_10_10_10_2 0x8036 +#define GL_TEXTURE_BINDING_3D 0x806A +#define GL_PACK_SKIP_IMAGES 0x806B +#define GL_PACK_IMAGE_HEIGHT 0x806C +#define GL_UNPACK_SKIP_IMAGES 0x806D +#define GL_UNPACK_IMAGE_HEIGHT 0x806E +#define GL_TEXTURE_3D 0x806F +#define GL_PROXY_TEXTURE_3D 0x8070 +#define GL_TEXTURE_DEPTH 0x8071 +#define GL_TEXTURE_WRAP_R 0x8072 +#define GL_MAX_3D_TEXTURE_SIZE 0x8073 +#define GL_UNSIGNED_BYTE_2_3_3_REV 0x8362 +#define GL_UNSIGNED_SHORT_5_6_5 0x8363 +#define GL_UNSIGNED_SHORT_5_6_5_REV 0x8364 +#define GL_UNSIGNED_SHORT_4_4_4_4_REV 0x8365 +#define GL_UNSIGNED_SHORT_1_5_5_5_REV 0x8366 +#define GL_UNSIGNED_INT_8_8_8_8_REV 0x8367 +#define GL_UNSIGNED_INT_2_10_10_10_REV 0x8368 +#define GL_BGR 0x80E0 +#define GL_BGRA 0x80E1 +#define GL_MAX_ELEMENTS_VERTICES 0x80E8 +#define GL_MAX_ELEMENTS_INDICES 0x80E9 +#define GL_CLAMP_TO_EDGE 0x812F +#define GL_TEXTURE_MIN_LOD 0x813A +#define GL_TEXTURE_MAX_LOD 0x813B +#define GL_TEXTURE_BASE_LEVEL 0x813C +#define GL_TEXTURE_MAX_LEVEL 0x813D +#define GL_SMOOTH_POINT_SIZE_RANGE 0x0B12 +#define GL_SMOOTH_POINT_SIZE_GRANULARITY 0x0B13 +#define GL_SMOOTH_LINE_WIDTH_RANGE 0x0B22 +#define GL_SMOOTH_LINE_WIDTH_GRANULARITY 0x0B23 +#define GL_ALIASED_LINE_WIDTH_RANGE 0x846E +#define GL_RESCALE_NORMAL 0x803A +#define GL_LIGHT_MODEL_COLOR_CONTROL 0x81F8 +#define GL_SINGLE_COLOR 0x81F9 +#define GL_SEPARATE_SPECULAR_COLOR 0x81FA +#define GL_ALIASED_POINT_SIZE_RANGE 0x846D +#define GL_TEXTURE0 0x84C0 +#define GL_TEXTURE1 0x84C1 +#define GL_TEXTURE2 0x84C2 +#define GL_TEXTURE3 0x84C3 +#define GL_TEXTURE4 0x84C4 +#define GL_TEXTURE5 0x84C5 +#define GL_TEXTURE6 0x84C6 +#define GL_TEXTURE7 0x84C7 +#define GL_TEXTURE8 0x84C8 +#define GL_TEXTURE9 0x84C9 +#define GL_TEXTURE10 0x84CA +#define GL_TEXTURE11 0x84CB +#define GL_TEXTURE12 0x84CC +#define GL_TEXTURE13 0x84CD +#define GL_TEXTURE14 0x84CE +#define GL_TEXTURE15 0x84CF +#define GL_TEXTURE16 0x84D0 +#define GL_TEXTURE17 0x84D1 +#define GL_TEXTURE18 0x84D2 +#define GL_TEXTURE19 0x84D3 +#define GL_TEXTURE20 0x84D4 +#define GL_TEXTURE21 0x84D5 +#define GL_TEXTURE22 0x84D6 +#define GL_TEXTURE23 0x84D7 +#define GL_TEXTURE24 0x84D8 +#define GL_TEXTURE25 0x84D9 +#define GL_TEXTURE26 0x84DA +#define GL_TEXTURE27 0x84DB +#define GL_TEXTURE28 0x84DC +#define GL_TEXTURE29 0x84DD +#define GL_TEXTURE30 0x84DE +#define GL_TEXTURE31 0x84DF +#define GL_ACTIVE_TEXTURE 0x84E0 +#define GL_MULTISAMPLE 0x809D +#define GL_SAMPLE_ALPHA_TO_COVERAGE 0x809E +#define GL_SAMPLE_ALPHA_TO_ONE 0x809F +#define GL_SAMPLE_COVERAGE 0x80A0 +#define GL_SAMPLE_BUFFERS 0x80A8 +#define GL_SAMPLES 0x80A9 +#define GL_SAMPLE_COVERAGE_VALUE 0x80AA +#define GL_SAMPLE_COVERAGE_INVERT 0x80AB +#define GL_TEXTURE_CUBE_MAP 0x8513 +#define GL_TEXTURE_BINDING_CUBE_MAP 0x8514 +#define GL_TEXTURE_CUBE_MAP_POSITIVE_X 0x8515 +#define GL_TEXTURE_CUBE_MAP_NEGATIVE_X 0x8516 +#define GL_TEXTURE_CUBE_MAP_POSITIVE_Y 0x8517 +#define GL_TEXTURE_CUBE_MAP_NEGATIVE_Y 0x8518 +#define GL_TEXTURE_CUBE_MAP_POSITIVE_Z 0x8519 +#define GL_TEXTURE_CUBE_MAP_NEGATIVE_Z 0x851A +#define GL_PROXY_TEXTURE_CUBE_MAP 0x851B +#define GL_MAX_CUBE_MAP_TEXTURE_SIZE 0x851C +#define GL_COMPRESSED_RGB 0x84ED +#define GL_COMPRESSED_RGBA 0x84EE +#define GL_TEXTURE_COMPRESSION_HINT 0x84EF +#define GL_TEXTURE_COMPRESSED_IMAGE_SIZE 0x86A0 +#define GL_TEXTURE_COMPRESSED 0x86A1 +#define GL_NUM_COMPRESSED_TEXTURE_FORMATS 0x86A2 +#define GL_COMPRESSED_TEXTURE_FORMATS 0x86A3 +#define GL_CLAMP_TO_BORDER 0x812D +#define GL_CLIENT_ACTIVE_TEXTURE 0x84E1 +#define GL_MAX_TEXTURE_UNITS 0x84E2 +#define GL_TRANSPOSE_MODELVIEW_MATRIX 0x84E3 +#define GL_TRANSPOSE_PROJECTION_MATRIX 0x84E4 +#define GL_TRANSPOSE_TEXTURE_MATRIX 0x84E5 +#define GL_TRANSPOSE_COLOR_MATRIX 0x84E6 +#define GL_MULTISAMPLE_BIT 0x20000000 +#define GL_NORMAL_MAP 0x8511 +#define GL_REFLECTION_MAP 0x8512 +#define GL_COMPRESSED_ALPHA 0x84E9 +#define GL_COMPRESSED_LUMINANCE 0x84EA +#define GL_COMPRESSED_LUMINANCE_ALPHA 0x84EB +#define GL_COMPRESSED_INTENSITY 0x84EC +#define GL_COMBINE 0x8570 +#define GL_COMBINE_RGB 0x8571 +#define GL_COMBINE_ALPHA 0x8572 +#define GL_SOURCE0_RGB 0x8580 +#define GL_SOURCE1_RGB 0x8581 +#define GL_SOURCE2_RGB 0x8582 +#define GL_SOURCE0_ALPHA 0x8588 +#define GL_SOURCE1_ALPHA 0x8589 +#define GL_SOURCE2_ALPHA 0x858A +#define GL_OPERAND0_RGB 0x8590 +#define GL_OPERAND1_RGB 0x8591 +#define GL_OPERAND2_RGB 0x8592 +#define GL_OPERAND0_ALPHA 0x8598 +#define GL_OPERAND1_ALPHA 0x8599 +#define GL_OPERAND2_ALPHA 0x859A +#define GL_RGB_SCALE 0x8573 +#define GL_ADD_SIGNED 0x8574 +#define GL_INTERPOLATE 0x8575 +#define GL_SUBTRACT 0x84E7 +#define GL_CONSTANT 0x8576 +#define GL_PRIMARY_COLOR 0x8577 +#define GL_PREVIOUS 0x8578 +#define GL_DOT3_RGB 0x86AE +#define GL_DOT3_RGBA 0x86AF +#define GL_BLEND_DST_RGB 0x80C8 +#define GL_BLEND_SRC_RGB 0x80C9 +#define GL_BLEND_DST_ALPHA 0x80CA +#define GL_BLEND_SRC_ALPHA 0x80CB +#define GL_POINT_FADE_THRESHOLD_SIZE 0x8128 +#define GL_DEPTH_COMPONENT16 0x81A5 +#define GL_DEPTH_COMPONENT24 0x81A6 +#define GL_DEPTH_COMPONENT32 0x81A7 +#define GL_MIRRORED_REPEAT 0x8370 +#define GL_MAX_TEXTURE_LOD_BIAS 0x84FD +#define GL_TEXTURE_LOD_BIAS 0x8501 +#define GL_INCR_WRAP 0x8507 +#define GL_DECR_WRAP 0x8508 +#define GL_TEXTURE_DEPTH_SIZE 0x884A +#define GL_TEXTURE_COMPARE_MODE 0x884C +#define GL_TEXTURE_COMPARE_FUNC 0x884D +#define GL_POINT_SIZE_MIN 0x8126 +#define GL_POINT_SIZE_MAX 0x8127 +#define GL_POINT_DISTANCE_ATTENUATION 0x8129 +#define GL_GENERATE_MIPMAP 0x8191 +#define GL_GENERATE_MIPMAP_HINT 0x8192 +#define GL_FOG_COORDINATE_SOURCE 0x8450 +#define GL_FOG_COORDINATE 0x8451 +#define GL_FRAGMENT_DEPTH 0x8452 +#define GL_CURRENT_FOG_COORDINATE 0x8453 +#define GL_FOG_COORDINATE_ARRAY_TYPE 0x8454 +#define GL_FOG_COORDINATE_ARRAY_STRIDE 0x8455 +#define GL_FOG_COORDINATE_ARRAY_POINTER 0x8456 +#define GL_FOG_COORDINATE_ARRAY 0x8457 +#define GL_COLOR_SUM 0x8458 +#define GL_CURRENT_SECONDARY_COLOR 0x8459 +#define GL_SECONDARY_COLOR_ARRAY_SIZE 0x845A +#define GL_SECONDARY_COLOR_ARRAY_TYPE 0x845B +#define GL_SECONDARY_COLOR_ARRAY_STRIDE 0x845C +#define GL_SECONDARY_COLOR_ARRAY_POINTER 0x845D +#define GL_SECONDARY_COLOR_ARRAY 0x845E +#define GL_TEXTURE_FILTER_CONTROL 0x8500 +#define GL_DEPTH_TEXTURE_MODE 0x884B +#define GL_COMPARE_R_TO_TEXTURE 0x884E +#define GL_BLEND_COLOR 0x8005 +#define GL_BLEND_EQUATION 0x8009 +#define GL_CONSTANT_COLOR 0x8001 +#define GL_ONE_MINUS_CONSTANT_COLOR 0x8002 +#define GL_CONSTANT_ALPHA 0x8003 +#define GL_ONE_MINUS_CONSTANT_ALPHA 0x8004 +#define GL_FUNC_ADD 0x8006 +#define GL_FUNC_REVERSE_SUBTRACT 0x800B +#define GL_FUNC_SUBTRACT 0x800A +#define GL_MIN 0x8007 +#define GL_MAX 0x8008 +#define GL_BUFFER_SIZE 0x8764 +#define GL_BUFFER_USAGE 0x8765 +#define GL_QUERY_COUNTER_BITS 0x8864 +#define GL_CURRENT_QUERY 0x8865 +#define GL_QUERY_RESULT 0x8866 +#define GL_QUERY_RESULT_AVAILABLE 0x8867 +#define GL_ARRAY_BUFFER 0x8892 +#define GL_ELEMENT_ARRAY_BUFFER 0x8893 +#define GL_ARRAY_BUFFER_BINDING 0x8894 +#define GL_ELEMENT_ARRAY_BUFFER_BINDING 0x8895 +#define GL_VERTEX_ATTRIB_ARRAY_BUFFER_BINDING 0x889F +#define GL_READ_ONLY 0x88B8 +#define GL_WRITE_ONLY 0x88B9 +#define GL_READ_WRITE 0x88BA +#define GL_BUFFER_ACCESS 0x88BB +#define GL_BUFFER_MAPPED 0x88BC +#define GL_BUFFER_MAP_POINTER 0x88BD +#define GL_STREAM_DRAW 0x88E0 +#define GL_STREAM_READ 0x88E1 +#define GL_STREAM_COPY 0x88E2 +#define GL_STATIC_DRAW 0x88E4 +#define GL_STATIC_READ 0x88E5 +#define GL_STATIC_COPY 0x88E6 +#define GL_DYNAMIC_DRAW 0x88E8 +#define GL_DYNAMIC_READ 0x88E9 +#define GL_DYNAMIC_COPY 0x88EA +#define GL_SAMPLES_PASSED 0x8914 +#define GL_SRC1_ALPHA 0x8589 +#define GL_VERTEX_ARRAY_BUFFER_BINDING 0x8896 +#define GL_NORMAL_ARRAY_BUFFER_BINDING 0x8897 +#define GL_COLOR_ARRAY_BUFFER_BINDING 0x8898 +#define GL_INDEX_ARRAY_BUFFER_BINDING 0x8899 +#define GL_TEXTURE_COORD_ARRAY_BUFFER_BINDING 0x889A +#define GL_EDGE_FLAG_ARRAY_BUFFER_BINDING 0x889B +#define GL_SECONDARY_COLOR_ARRAY_BUFFER_BINDING 0x889C +#define GL_FOG_COORDINATE_ARRAY_BUFFER_BINDING 0x889D +#define GL_WEIGHT_ARRAY_BUFFER_BINDING 0x889E +#define GL_FOG_COORD_SRC 0x8450 +#define GL_FOG_COORD 0x8451 +#define GL_CURRENT_FOG_COORD 0x8453 +#define GL_FOG_COORD_ARRAY_TYPE 0x8454 +#define GL_FOG_COORD_ARRAY_STRIDE 0x8455 +#define GL_FOG_COORD_ARRAY_POINTER 0x8456 +#define GL_FOG_COORD_ARRAY 0x8457 +#define GL_FOG_COORD_ARRAY_BUFFER_BINDING 0x889D +#define GL_SRC0_RGB 0x8580 +#define GL_SRC1_RGB 0x8581 +#define GL_SRC2_RGB 0x8582 +#define GL_SRC0_ALPHA 0x8588 +#define GL_SRC2_ALPHA 0x858A +#define GL_BLEND_EQUATION_RGB 0x8009 +#define GL_VERTEX_ATTRIB_ARRAY_ENABLED 0x8622 +#define GL_VERTEX_ATTRIB_ARRAY_SIZE 0x8623 +#define GL_VERTEX_ATTRIB_ARRAY_STRIDE 0x8624 +#define GL_VERTEX_ATTRIB_ARRAY_TYPE 0x8625 +#define GL_CURRENT_VERTEX_ATTRIB 0x8626 +#define GL_VERTEX_PROGRAM_POINT_SIZE 0x8642 +#define GL_VERTEX_ATTRIB_ARRAY_POINTER 0x8645 +#define GL_STENCIL_BACK_FUNC 0x8800 +#define GL_STENCIL_BACK_FAIL 0x8801 +#define GL_STENCIL_BACK_PASS_DEPTH_FAIL 0x8802 +#define GL_STENCIL_BACK_PASS_DEPTH_PASS 0x8803 +#define GL_MAX_DRAW_BUFFERS 0x8824 +#define GL_DRAW_BUFFER0 0x8825 +#define GL_DRAW_BUFFER1 0x8826 +#define GL_DRAW_BUFFER2 0x8827 +#define GL_DRAW_BUFFER3 0x8828 +#define GL_DRAW_BUFFER4 0x8829 +#define GL_DRAW_BUFFER5 0x882A +#define GL_DRAW_BUFFER6 0x882B +#define GL_DRAW_BUFFER7 0x882C +#define GL_DRAW_BUFFER8 0x882D +#define GL_DRAW_BUFFER9 0x882E +#define GL_DRAW_BUFFER10 0x882F +#define GL_DRAW_BUFFER11 0x8830 +#define GL_DRAW_BUFFER12 0x8831 +#define GL_DRAW_BUFFER13 0x8832 +#define GL_DRAW_BUFFER14 0x8833 +#define GL_DRAW_BUFFER15 0x8834 +#define GL_BLEND_EQUATION_ALPHA 0x883D +#define GL_MAX_VERTEX_ATTRIBS 0x8869 +#define GL_VERTEX_ATTRIB_ARRAY_NORMALIZED 0x886A +#define GL_MAX_TEXTURE_IMAGE_UNITS 0x8872 +#define GL_FRAGMENT_SHADER 0x8B30 +#define GL_VERTEX_SHADER 0x8B31 +#define GL_MAX_FRAGMENT_UNIFORM_COMPONENTS 0x8B49 +#define GL_MAX_VERTEX_UNIFORM_COMPONENTS 0x8B4A +#define GL_MAX_VARYING_FLOATS 0x8B4B +#define GL_MAX_VERTEX_TEXTURE_IMAGE_UNITS 0x8B4C +#define GL_MAX_COMBINED_TEXTURE_IMAGE_UNITS 0x8B4D +#define GL_SHADER_TYPE 0x8B4F +#define GL_FLOAT_VEC2 0x8B50 +#define GL_FLOAT_VEC3 0x8B51 +#define GL_FLOAT_VEC4 0x8B52 +#define GL_INT_VEC2 0x8B53 +#define GL_INT_VEC3 0x8B54 +#define GL_INT_VEC4 0x8B55 +#define GL_BOOL 0x8B56 +#define GL_BOOL_VEC2 0x8B57 +#define GL_BOOL_VEC3 0x8B58 +#define GL_BOOL_VEC4 0x8B59 +#define GL_FLOAT_MAT2 0x8B5A +#define GL_FLOAT_MAT3 0x8B5B +#define GL_FLOAT_MAT4 0x8B5C +#define GL_SAMPLER_1D 0x8B5D +#define GL_SAMPLER_2D 0x8B5E +#define GL_SAMPLER_3D 0x8B5F +#define GL_SAMPLER_CUBE 0x8B60 +#define GL_SAMPLER_1D_SHADOW 0x8B61 +#define GL_SAMPLER_2D_SHADOW 0x8B62 +#define GL_DELETE_STATUS 0x8B80 +#define GL_COMPILE_STATUS 0x8B81 +#define GL_LINK_STATUS 0x8B82 +#define GL_VALIDATE_STATUS 0x8B83 +#define GL_INFO_LOG_LENGTH 0x8B84 +#define GL_ATTACHED_SHADERS 0x8B85 +#define GL_ACTIVE_UNIFORMS 0x8B86 +#define GL_ACTIVE_UNIFORM_MAX_LENGTH 0x8B87 +#define GL_SHADER_SOURCE_LENGTH 0x8B88 +#define GL_ACTIVE_ATTRIBUTES 0x8B89 +#define GL_ACTIVE_ATTRIBUTE_MAX_LENGTH 0x8B8A +#define GL_FRAGMENT_SHADER_DERIVATIVE_HINT 0x8B8B +#define GL_SHADING_LANGUAGE_VERSION 0x8B8C +#define GL_CURRENT_PROGRAM 0x8B8D +#define GL_POINT_SPRITE_COORD_ORIGIN 0x8CA0 +#define GL_LOWER_LEFT 0x8CA1 +#define GL_UPPER_LEFT 0x8CA2 +#define GL_STENCIL_BACK_REF 0x8CA3 +#define GL_STENCIL_BACK_VALUE_MASK 0x8CA4 +#define GL_STENCIL_BACK_WRITEMASK 0x8CA5 +#define GL_VERTEX_PROGRAM_TWO_SIDE 0x8643 +#define GL_POINT_SPRITE 0x8861 +#define GL_COORD_REPLACE 0x8862 +#define GL_MAX_TEXTURE_COORDS 0x8871 +#ifndef GL_VERSION_1_0 +#define GL_VERSION_1_0 1 +GLAPI int GLAD_GL_VERSION_1_0; +typedef void (APIENTRYP PFNGLCULLFACEPROC)(GLenum mode); +GLAPI PFNGLCULLFACEPROC glad_glCullFace; +#define glCullFace glad_glCullFace +typedef void (APIENTRYP PFNGLFRONTFACEPROC)(GLenum mode); +GLAPI PFNGLFRONTFACEPROC glad_glFrontFace; +#define glFrontFace glad_glFrontFace +typedef void (APIENTRYP PFNGLHINTPROC)(GLenum target, GLenum mode); +GLAPI PFNGLHINTPROC glad_glHint; +#define glHint glad_glHint +typedef void (APIENTRYP PFNGLLINEWIDTHPROC)(GLfloat width); +GLAPI PFNGLLINEWIDTHPROC glad_glLineWidth; +#define glLineWidth glad_glLineWidth +typedef void (APIENTRYP PFNGLPOINTSIZEPROC)(GLfloat size); +GLAPI PFNGLPOINTSIZEPROC glad_glPointSize; +#define glPointSize glad_glPointSize +typedef void (APIENTRYP PFNGLPOLYGONMODEPROC)(GLenum face, GLenum mode); +GLAPI PFNGLPOLYGONMODEPROC glad_glPolygonMode; +#define glPolygonMode glad_glPolygonMode +typedef void (APIENTRYP PFNGLSCISSORPROC)(GLint x, GLint y, GLsizei width, GLsizei height); +GLAPI PFNGLSCISSORPROC glad_glScissor; +#define glScissor glad_glScissor +typedef void (APIENTRYP PFNGLTEXPARAMETERFPROC)(GLenum target, GLenum pname, GLfloat param); +GLAPI PFNGLTEXPARAMETERFPROC glad_glTexParameterf; +#define glTexParameterf glad_glTexParameterf +typedef void (APIENTRYP PFNGLTEXPARAMETERFVPROC)(GLenum target, GLenum pname, const GLfloat *params); +GLAPI PFNGLTEXPARAMETERFVPROC glad_glTexParameterfv; +#define glTexParameterfv glad_glTexParameterfv +typedef void (APIENTRYP PFNGLTEXPARAMETERIPROC)(GLenum target, GLenum pname, GLint param); +GLAPI PFNGLTEXPARAMETERIPROC glad_glTexParameteri; +#define glTexParameteri glad_glTexParameteri +typedef void (APIENTRYP PFNGLTEXPARAMETERIVPROC)(GLenum target, GLenum pname, const GLint *params); +GLAPI PFNGLTEXPARAMETERIVPROC glad_glTexParameteriv; +#define glTexParameteriv glad_glTexParameteriv +typedef void (APIENTRYP PFNGLTEXIMAGE1DPROC)(GLenum target, GLint level, GLint internalformat, GLsizei width, GLint border, GLenum format, GLenum type, const void *pixels); +GLAPI PFNGLTEXIMAGE1DPROC glad_glTexImage1D; +#define glTexImage1D glad_glTexImage1D +typedef void (APIENTRYP PFNGLTEXIMAGE2DPROC)(GLenum target, GLint level, GLint internalformat, GLsizei width, GLsizei height, GLint border, GLenum format, GLenum type, const void *pixels); +GLAPI PFNGLTEXIMAGE2DPROC glad_glTexImage2D; +#define glTexImage2D glad_glTexImage2D +typedef void (APIENTRYP PFNGLDRAWBUFFERPROC)(GLenum buf); +GLAPI PFNGLDRAWBUFFERPROC glad_glDrawBuffer; +#define glDrawBuffer glad_glDrawBuffer +typedef void (APIENTRYP PFNGLCLEARPROC)(GLbitfield mask); +GLAPI PFNGLCLEARPROC glad_glClear; +#define glClear glad_glClear +typedef void (APIENTRYP PFNGLCLEARCOLORPROC)(GLfloat red, GLfloat green, GLfloat blue, GLfloat alpha); +GLAPI PFNGLCLEARCOLORPROC glad_glClearColor; +#define glClearColor glad_glClearColor +typedef void (APIENTRYP PFNGLCLEARSTENCILPROC)(GLint s); +GLAPI PFNGLCLEARSTENCILPROC glad_glClearStencil; +#define glClearStencil glad_glClearStencil +typedef void (APIENTRYP PFNGLCLEARDEPTHPROC)(GLdouble depth); +GLAPI PFNGLCLEARDEPTHPROC glad_glClearDepth; +#define glClearDepth glad_glClearDepth +typedef void (APIENTRYP PFNGLSTENCILMASKPROC)(GLuint mask); +GLAPI PFNGLSTENCILMASKPROC glad_glStencilMask; +#define glStencilMask glad_glStencilMask +typedef void (APIENTRYP PFNGLCOLORMASKPROC)(GLboolean red, GLboolean green, GLboolean blue, GLboolean alpha); +GLAPI PFNGLCOLORMASKPROC glad_glColorMask; +#define glColorMask glad_glColorMask +typedef void (APIENTRYP PFNGLDEPTHMASKPROC)(GLboolean flag); +GLAPI PFNGLDEPTHMASKPROC glad_glDepthMask; +#define glDepthMask glad_glDepthMask +typedef void (APIENTRYP PFNGLDISABLEPROC)(GLenum cap); +GLAPI PFNGLDISABLEPROC glad_glDisable; +#define glDisable glad_glDisable +typedef void (APIENTRYP PFNGLENABLEPROC)(GLenum cap); +GLAPI PFNGLENABLEPROC glad_glEnable; +#define glEnable glad_glEnable +typedef void (APIENTRYP PFNGLFINISHPROC)(void); +GLAPI PFNGLFINISHPROC glad_glFinish; +#define glFinish glad_glFinish +typedef void (APIENTRYP PFNGLFLUSHPROC)(void); +GLAPI PFNGLFLUSHPROC glad_glFlush; +#define glFlush glad_glFlush +typedef void (APIENTRYP PFNGLBLENDFUNCPROC)(GLenum sfactor, GLenum dfactor); +GLAPI PFNGLBLENDFUNCPROC glad_glBlendFunc; +#define glBlendFunc glad_glBlendFunc +typedef void (APIENTRYP PFNGLLOGICOPPROC)(GLenum opcode); +GLAPI PFNGLLOGICOPPROC glad_glLogicOp; +#define glLogicOp glad_glLogicOp +typedef void (APIENTRYP PFNGLSTENCILFUNCPROC)(GLenum func, GLint ref, GLuint mask); +GLAPI PFNGLSTENCILFUNCPROC glad_glStencilFunc; +#define glStencilFunc glad_glStencilFunc +typedef void (APIENTRYP PFNGLSTENCILOPPROC)(GLenum fail, GLenum zfail, GLenum zpass); +GLAPI PFNGLSTENCILOPPROC glad_glStencilOp; +#define glStencilOp glad_glStencilOp +typedef void (APIENTRYP PFNGLDEPTHFUNCPROC)(GLenum func); +GLAPI PFNGLDEPTHFUNCPROC glad_glDepthFunc; +#define glDepthFunc glad_glDepthFunc +typedef void (APIENTRYP PFNGLPIXELSTOREFPROC)(GLenum pname, GLfloat param); +GLAPI PFNGLPIXELSTOREFPROC glad_glPixelStoref; +#define glPixelStoref glad_glPixelStoref +typedef void (APIENTRYP PFNGLPIXELSTOREIPROC)(GLenum pname, GLint param); +GLAPI PFNGLPIXELSTOREIPROC glad_glPixelStorei; +#define glPixelStorei glad_glPixelStorei +typedef void (APIENTRYP PFNGLREADBUFFERPROC)(GLenum src); +GLAPI PFNGLREADBUFFERPROC glad_glReadBuffer; +#define glReadBuffer glad_glReadBuffer +typedef void (APIENTRYP PFNGLREADPIXELSPROC)(GLint x, GLint y, GLsizei width, GLsizei height, GLenum format, GLenum type, void *pixels); +GLAPI PFNGLREADPIXELSPROC glad_glReadPixels; +#define glReadPixels glad_glReadPixels +typedef void (APIENTRYP PFNGLGETBOOLEANVPROC)(GLenum pname, GLboolean *data); +GLAPI PFNGLGETBOOLEANVPROC glad_glGetBooleanv; +#define glGetBooleanv glad_glGetBooleanv +typedef void (APIENTRYP PFNGLGETDOUBLEVPROC)(GLenum pname, GLdouble *data); +GLAPI PFNGLGETDOUBLEVPROC glad_glGetDoublev; +#define glGetDoublev glad_glGetDoublev +typedef GLenum (APIENTRYP PFNGLGETERRORPROC)(void); +GLAPI PFNGLGETERRORPROC glad_glGetError; +#define glGetError glad_glGetError +typedef void (APIENTRYP PFNGLGETFLOATVPROC)(GLenum pname, GLfloat *data); +GLAPI PFNGLGETFLOATVPROC glad_glGetFloatv; +#define glGetFloatv glad_glGetFloatv +typedef void (APIENTRYP PFNGLGETINTEGERVPROC)(GLenum pname, GLint *data); +GLAPI PFNGLGETINTEGERVPROC glad_glGetIntegerv; +#define glGetIntegerv glad_glGetIntegerv +typedef const GLubyte * (APIENTRYP PFNGLGETSTRINGPROC)(GLenum name); +GLAPI PFNGLGETSTRINGPROC glad_glGetString; +#define glGetString glad_glGetString +typedef void (APIENTRYP PFNGLGETTEXIMAGEPROC)(GLenum target, GLint level, GLenum format, GLenum type, void *pixels); +GLAPI PFNGLGETTEXIMAGEPROC glad_glGetTexImage; +#define glGetTexImage glad_glGetTexImage +typedef void (APIENTRYP PFNGLGETTEXPARAMETERFVPROC)(GLenum target, GLenum pname, GLfloat *params); +GLAPI PFNGLGETTEXPARAMETERFVPROC glad_glGetTexParameterfv; +#define glGetTexParameterfv glad_glGetTexParameterfv +typedef void (APIENTRYP PFNGLGETTEXPARAMETERIVPROC)(GLenum target, GLenum pname, GLint *params); +GLAPI PFNGLGETTEXPARAMETERIVPROC glad_glGetTexParameteriv; +#define glGetTexParameteriv glad_glGetTexParameteriv +typedef void (APIENTRYP PFNGLGETTEXLEVELPARAMETERFVPROC)(GLenum target, GLint level, GLenum pname, GLfloat *params); +GLAPI PFNGLGETTEXLEVELPARAMETERFVPROC glad_glGetTexLevelParameterfv; +#define glGetTexLevelParameterfv glad_glGetTexLevelParameterfv +typedef void (APIENTRYP PFNGLGETTEXLEVELPARAMETERIVPROC)(GLenum target, GLint level, GLenum pname, GLint *params); +GLAPI PFNGLGETTEXLEVELPARAMETERIVPROC glad_glGetTexLevelParameteriv; +#define glGetTexLevelParameteriv glad_glGetTexLevelParameteriv +typedef GLboolean (APIENTRYP PFNGLISENABLEDPROC)(GLenum cap); +GLAPI PFNGLISENABLEDPROC glad_glIsEnabled; +#define glIsEnabled glad_glIsEnabled +typedef void (APIENTRYP PFNGLDEPTHRANGEPROC)(GLdouble n, GLdouble f); +GLAPI PFNGLDEPTHRANGEPROC glad_glDepthRange; +#define glDepthRange glad_glDepthRange +typedef void (APIENTRYP PFNGLVIEWPORTPROC)(GLint x, GLint y, GLsizei width, GLsizei height); +GLAPI PFNGLVIEWPORTPROC glad_glViewport; +#define glViewport glad_glViewport +typedef void (APIENTRYP PFNGLNEWLISTPROC)(GLuint list, GLenum mode); +GLAPI PFNGLNEWLISTPROC glad_glNewList; +#define glNewList glad_glNewList +typedef void (APIENTRYP PFNGLENDLISTPROC)(void); +GLAPI PFNGLENDLISTPROC glad_glEndList; +#define glEndList glad_glEndList +typedef void (APIENTRYP PFNGLCALLLISTPROC)(GLuint list); +GLAPI PFNGLCALLLISTPROC glad_glCallList; +#define glCallList glad_glCallList +typedef void (APIENTRYP PFNGLCALLLISTSPROC)(GLsizei n, GLenum type, const void *lists); +GLAPI PFNGLCALLLISTSPROC glad_glCallLists; +#define glCallLists glad_glCallLists +typedef void (APIENTRYP PFNGLDELETELISTSPROC)(GLuint list, GLsizei range); +GLAPI PFNGLDELETELISTSPROC glad_glDeleteLists; +#define glDeleteLists glad_glDeleteLists +typedef GLuint (APIENTRYP PFNGLGENLISTSPROC)(GLsizei range); +GLAPI PFNGLGENLISTSPROC glad_glGenLists; +#define glGenLists glad_glGenLists +typedef void (APIENTRYP PFNGLLISTBASEPROC)(GLuint base); +GLAPI PFNGLLISTBASEPROC glad_glListBase; +#define glListBase glad_glListBase +typedef void (APIENTRYP PFNGLBEGINPROC)(GLenum mode); +GLAPI PFNGLBEGINPROC glad_glBegin; +#define glBegin glad_glBegin +typedef void (APIENTRYP PFNGLBITMAPPROC)(GLsizei width, GLsizei height, GLfloat xorig, GLfloat yorig, GLfloat xmove, GLfloat ymove, const GLubyte *bitmap); +GLAPI PFNGLBITMAPPROC glad_glBitmap; +#define glBitmap glad_glBitmap +typedef void (APIENTRYP PFNGLCOLOR3BPROC)(GLbyte red, GLbyte green, GLbyte blue); +GLAPI PFNGLCOLOR3BPROC glad_glColor3b; +#define glColor3b glad_glColor3b +typedef void (APIENTRYP PFNGLCOLOR3BVPROC)(const GLbyte *v); +GLAPI PFNGLCOLOR3BVPROC glad_glColor3bv; +#define glColor3bv glad_glColor3bv +typedef void (APIENTRYP PFNGLCOLOR3DPROC)(GLdouble red, GLdouble green, GLdouble blue); +GLAPI PFNGLCOLOR3DPROC glad_glColor3d; +#define glColor3d glad_glColor3d +typedef void (APIENTRYP PFNGLCOLOR3DVPROC)(const GLdouble *v); +GLAPI PFNGLCOLOR3DVPROC glad_glColor3dv; +#define glColor3dv glad_glColor3dv +typedef void (APIENTRYP PFNGLCOLOR3FPROC)(GLfloat red, GLfloat green, GLfloat blue); +GLAPI PFNGLCOLOR3FPROC glad_glColor3f; +#define glColor3f glad_glColor3f +typedef void (APIENTRYP PFNGLCOLOR3FVPROC)(const GLfloat *v); +GLAPI PFNGLCOLOR3FVPROC glad_glColor3fv; +#define glColor3fv glad_glColor3fv +typedef void (APIENTRYP PFNGLCOLOR3IPROC)(GLint red, GLint green, GLint blue); +GLAPI PFNGLCOLOR3IPROC glad_glColor3i; +#define glColor3i glad_glColor3i +typedef void (APIENTRYP PFNGLCOLOR3IVPROC)(const GLint *v); +GLAPI PFNGLCOLOR3IVPROC glad_glColor3iv; +#define glColor3iv glad_glColor3iv +typedef void (APIENTRYP PFNGLCOLOR3SPROC)(GLshort red, GLshort green, GLshort blue); +GLAPI PFNGLCOLOR3SPROC glad_glColor3s; +#define glColor3s glad_glColor3s +typedef void (APIENTRYP PFNGLCOLOR3SVPROC)(const GLshort *v); +GLAPI PFNGLCOLOR3SVPROC glad_glColor3sv; +#define glColor3sv glad_glColor3sv +typedef void (APIENTRYP PFNGLCOLOR3UBPROC)(GLubyte red, GLubyte green, GLubyte blue); +GLAPI PFNGLCOLOR3UBPROC glad_glColor3ub; +#define glColor3ub glad_glColor3ub +typedef void (APIENTRYP PFNGLCOLOR3UBVPROC)(const GLubyte *v); +GLAPI PFNGLCOLOR3UBVPROC glad_glColor3ubv; +#define glColor3ubv glad_glColor3ubv +typedef void (APIENTRYP PFNGLCOLOR3UIPROC)(GLuint red, GLuint green, GLuint blue); +GLAPI PFNGLCOLOR3UIPROC glad_glColor3ui; +#define glColor3ui glad_glColor3ui +typedef void (APIENTRYP PFNGLCOLOR3UIVPROC)(const GLuint *v); +GLAPI PFNGLCOLOR3UIVPROC glad_glColor3uiv; +#define glColor3uiv glad_glColor3uiv +typedef void (APIENTRYP PFNGLCOLOR3USPROC)(GLushort red, GLushort green, GLushort blue); +GLAPI PFNGLCOLOR3USPROC glad_glColor3us; +#define glColor3us glad_glColor3us +typedef void (APIENTRYP PFNGLCOLOR3USVPROC)(const GLushort *v); +GLAPI PFNGLCOLOR3USVPROC glad_glColor3usv; +#define glColor3usv glad_glColor3usv +typedef void (APIENTRYP PFNGLCOLOR4BPROC)(GLbyte red, GLbyte green, GLbyte blue, GLbyte alpha); +GLAPI PFNGLCOLOR4BPROC glad_glColor4b; +#define glColor4b glad_glColor4b +typedef void (APIENTRYP PFNGLCOLOR4BVPROC)(const GLbyte *v); +GLAPI PFNGLCOLOR4BVPROC glad_glColor4bv; +#define glColor4bv glad_glColor4bv +typedef void (APIENTRYP PFNGLCOLOR4DPROC)(GLdouble red, GLdouble green, GLdouble blue, GLdouble alpha); +GLAPI PFNGLCOLOR4DPROC glad_glColor4d; +#define glColor4d glad_glColor4d +typedef void (APIENTRYP PFNGLCOLOR4DVPROC)(const GLdouble *v); +GLAPI PFNGLCOLOR4DVPROC glad_glColor4dv; +#define glColor4dv glad_glColor4dv +typedef void (APIENTRYP PFNGLCOLOR4FPROC)(GLfloat red, GLfloat green, GLfloat blue, GLfloat alpha); +GLAPI PFNGLCOLOR4FPROC glad_glColor4f; +#define glColor4f glad_glColor4f +typedef void (APIENTRYP PFNGLCOLOR4FVPROC)(const GLfloat *v); +GLAPI PFNGLCOLOR4FVPROC glad_glColor4fv; +#define glColor4fv glad_glColor4fv +typedef void (APIENTRYP PFNGLCOLOR4IPROC)(GLint red, GLint green, GLint blue, GLint alpha); +GLAPI PFNGLCOLOR4IPROC glad_glColor4i; +#define glColor4i glad_glColor4i +typedef void (APIENTRYP PFNGLCOLOR4IVPROC)(const GLint *v); +GLAPI PFNGLCOLOR4IVPROC glad_glColor4iv; +#define glColor4iv glad_glColor4iv +typedef void (APIENTRYP PFNGLCOLOR4SPROC)(GLshort red, GLshort green, GLshort blue, GLshort alpha); +GLAPI PFNGLCOLOR4SPROC glad_glColor4s; +#define glColor4s glad_glColor4s +typedef void (APIENTRYP PFNGLCOLOR4SVPROC)(const GLshort *v); +GLAPI PFNGLCOLOR4SVPROC glad_glColor4sv; +#define glColor4sv glad_glColor4sv +typedef void (APIENTRYP PFNGLCOLOR4UBPROC)(GLubyte red, GLubyte green, GLubyte blue, GLubyte alpha); +GLAPI PFNGLCOLOR4UBPROC glad_glColor4ub; +#define glColor4ub glad_glColor4ub +typedef void (APIENTRYP PFNGLCOLOR4UBVPROC)(const GLubyte *v); +GLAPI PFNGLCOLOR4UBVPROC glad_glColor4ubv; +#define glColor4ubv glad_glColor4ubv +typedef void (APIENTRYP PFNGLCOLOR4UIPROC)(GLuint red, GLuint green, GLuint blue, GLuint alpha); +GLAPI PFNGLCOLOR4UIPROC glad_glColor4ui; +#define glColor4ui glad_glColor4ui +typedef void (APIENTRYP PFNGLCOLOR4UIVPROC)(const GLuint *v); +GLAPI PFNGLCOLOR4UIVPROC glad_glColor4uiv; +#define glColor4uiv glad_glColor4uiv +typedef void (APIENTRYP PFNGLCOLOR4USPROC)(GLushort red, GLushort green, GLushort blue, GLushort alpha); +GLAPI PFNGLCOLOR4USPROC glad_glColor4us; +#define glColor4us glad_glColor4us +typedef void (APIENTRYP PFNGLCOLOR4USVPROC)(const GLushort *v); +GLAPI PFNGLCOLOR4USVPROC glad_glColor4usv; +#define glColor4usv glad_glColor4usv +typedef void (APIENTRYP PFNGLEDGEFLAGPROC)(GLboolean flag); +GLAPI PFNGLEDGEFLAGPROC glad_glEdgeFlag; +#define glEdgeFlag glad_glEdgeFlag +typedef void (APIENTRYP PFNGLEDGEFLAGVPROC)(const GLboolean *flag); +GLAPI PFNGLEDGEFLAGVPROC glad_glEdgeFlagv; +#define glEdgeFlagv glad_glEdgeFlagv +typedef void (APIENTRYP PFNGLENDPROC)(void); +GLAPI PFNGLENDPROC glad_glEnd; +#define glEnd glad_glEnd +typedef void (APIENTRYP PFNGLINDEXDPROC)(GLdouble c); +GLAPI PFNGLINDEXDPROC glad_glIndexd; +#define glIndexd glad_glIndexd +typedef void (APIENTRYP PFNGLINDEXDVPROC)(const GLdouble *c); +GLAPI PFNGLINDEXDVPROC glad_glIndexdv; +#define glIndexdv glad_glIndexdv +typedef void (APIENTRYP PFNGLINDEXFPROC)(GLfloat c); +GLAPI PFNGLINDEXFPROC glad_glIndexf; +#define glIndexf glad_glIndexf +typedef void (APIENTRYP PFNGLINDEXFVPROC)(const GLfloat *c); +GLAPI PFNGLINDEXFVPROC glad_glIndexfv; +#define glIndexfv glad_glIndexfv +typedef void (APIENTRYP PFNGLINDEXIPROC)(GLint c); +GLAPI PFNGLINDEXIPROC glad_glIndexi; +#define glIndexi glad_glIndexi +typedef void (APIENTRYP PFNGLINDEXIVPROC)(const GLint *c); +GLAPI PFNGLINDEXIVPROC glad_glIndexiv; +#define glIndexiv glad_glIndexiv +typedef void (APIENTRYP PFNGLINDEXSPROC)(GLshort c); +GLAPI PFNGLINDEXSPROC glad_glIndexs; +#define glIndexs glad_glIndexs +typedef void (APIENTRYP PFNGLINDEXSVPROC)(const GLshort *c); +GLAPI PFNGLINDEXSVPROC glad_glIndexsv; +#define glIndexsv glad_glIndexsv +typedef void (APIENTRYP PFNGLNORMAL3BPROC)(GLbyte nx, GLbyte ny, GLbyte nz); +GLAPI PFNGLNORMAL3BPROC glad_glNormal3b; +#define glNormal3b glad_glNormal3b +typedef void (APIENTRYP PFNGLNORMAL3BVPROC)(const GLbyte *v); +GLAPI PFNGLNORMAL3BVPROC glad_glNormal3bv; +#define glNormal3bv glad_glNormal3bv +typedef void (APIENTRYP PFNGLNORMAL3DPROC)(GLdouble nx, GLdouble ny, GLdouble nz); +GLAPI PFNGLNORMAL3DPROC glad_glNormal3d; +#define glNormal3d glad_glNormal3d +typedef void (APIENTRYP PFNGLNORMAL3DVPROC)(const GLdouble *v); +GLAPI PFNGLNORMAL3DVPROC glad_glNormal3dv; +#define glNormal3dv glad_glNormal3dv +typedef void (APIENTRYP PFNGLNORMAL3FPROC)(GLfloat nx, GLfloat ny, GLfloat nz); +GLAPI PFNGLNORMAL3FPROC glad_glNormal3f; +#define glNormal3f glad_glNormal3f +typedef void (APIENTRYP PFNGLNORMAL3FVPROC)(const GLfloat *v); +GLAPI PFNGLNORMAL3FVPROC glad_glNormal3fv; +#define glNormal3fv glad_glNormal3fv +typedef void (APIENTRYP PFNGLNORMAL3IPROC)(GLint nx, GLint ny, GLint nz); +GLAPI PFNGLNORMAL3IPROC glad_glNormal3i; +#define glNormal3i glad_glNormal3i +typedef void (APIENTRYP PFNGLNORMAL3IVPROC)(const GLint *v); +GLAPI PFNGLNORMAL3IVPROC glad_glNormal3iv; +#define glNormal3iv glad_glNormal3iv +typedef void (APIENTRYP PFNGLNORMAL3SPROC)(GLshort nx, GLshort ny, GLshort nz); +GLAPI PFNGLNORMAL3SPROC glad_glNormal3s; +#define glNormal3s glad_glNormal3s +typedef void (APIENTRYP PFNGLNORMAL3SVPROC)(const GLshort *v); +GLAPI PFNGLNORMAL3SVPROC glad_glNormal3sv; +#define glNormal3sv glad_glNormal3sv +typedef void (APIENTRYP PFNGLRASTERPOS2DPROC)(GLdouble x, GLdouble y); +GLAPI PFNGLRASTERPOS2DPROC glad_glRasterPos2d; +#define glRasterPos2d glad_glRasterPos2d +typedef void (APIENTRYP PFNGLRASTERPOS2DVPROC)(const GLdouble *v); +GLAPI PFNGLRASTERPOS2DVPROC glad_glRasterPos2dv; +#define glRasterPos2dv glad_glRasterPos2dv +typedef void (APIENTRYP PFNGLRASTERPOS2FPROC)(GLfloat x, GLfloat y); +GLAPI PFNGLRASTERPOS2FPROC glad_glRasterPos2f; +#define glRasterPos2f glad_glRasterPos2f +typedef void (APIENTRYP PFNGLRASTERPOS2FVPROC)(const GLfloat *v); +GLAPI PFNGLRASTERPOS2FVPROC glad_glRasterPos2fv; +#define glRasterPos2fv glad_glRasterPos2fv +typedef void (APIENTRYP PFNGLRASTERPOS2IPROC)(GLint x, GLint y); +GLAPI PFNGLRASTERPOS2IPROC glad_glRasterPos2i; +#define glRasterPos2i glad_glRasterPos2i +typedef void (APIENTRYP PFNGLRASTERPOS2IVPROC)(const GLint *v); +GLAPI PFNGLRASTERPOS2IVPROC glad_glRasterPos2iv; +#define glRasterPos2iv glad_glRasterPos2iv +typedef void (APIENTRYP PFNGLRASTERPOS2SPROC)(GLshort x, GLshort y); +GLAPI PFNGLRASTERPOS2SPROC glad_glRasterPos2s; +#define glRasterPos2s glad_glRasterPos2s +typedef void (APIENTRYP PFNGLRASTERPOS2SVPROC)(const GLshort *v); +GLAPI PFNGLRASTERPOS2SVPROC glad_glRasterPos2sv; +#define glRasterPos2sv glad_glRasterPos2sv +typedef void (APIENTRYP PFNGLRASTERPOS3DPROC)(GLdouble x, GLdouble y, GLdouble z); +GLAPI PFNGLRASTERPOS3DPROC glad_glRasterPos3d; +#define glRasterPos3d glad_glRasterPos3d +typedef void (APIENTRYP PFNGLRASTERPOS3DVPROC)(const GLdouble *v); +GLAPI PFNGLRASTERPOS3DVPROC glad_glRasterPos3dv; +#define glRasterPos3dv glad_glRasterPos3dv +typedef void (APIENTRYP PFNGLRASTERPOS3FPROC)(GLfloat x, GLfloat y, GLfloat z); +GLAPI PFNGLRASTERPOS3FPROC glad_glRasterPos3f; +#define glRasterPos3f glad_glRasterPos3f +typedef void (APIENTRYP PFNGLRASTERPOS3FVPROC)(const GLfloat *v); +GLAPI PFNGLRASTERPOS3FVPROC glad_glRasterPos3fv; +#define glRasterPos3fv glad_glRasterPos3fv +typedef void (APIENTRYP PFNGLRASTERPOS3IPROC)(GLint x, GLint y, GLint z); +GLAPI PFNGLRASTERPOS3IPROC glad_glRasterPos3i; +#define glRasterPos3i glad_glRasterPos3i +typedef void (APIENTRYP PFNGLRASTERPOS3IVPROC)(const GLint *v); +GLAPI PFNGLRASTERPOS3IVPROC glad_glRasterPos3iv; +#define glRasterPos3iv glad_glRasterPos3iv +typedef void (APIENTRYP PFNGLRASTERPOS3SPROC)(GLshort x, GLshort y, GLshort z); +GLAPI PFNGLRASTERPOS3SPROC glad_glRasterPos3s; +#define glRasterPos3s glad_glRasterPos3s +typedef void (APIENTRYP PFNGLRASTERPOS3SVPROC)(const GLshort *v); +GLAPI PFNGLRASTERPOS3SVPROC glad_glRasterPos3sv; +#define glRasterPos3sv glad_glRasterPos3sv +typedef void (APIENTRYP PFNGLRASTERPOS4DPROC)(GLdouble x, GLdouble y, GLdouble z, GLdouble w); +GLAPI PFNGLRASTERPOS4DPROC glad_glRasterPos4d; +#define glRasterPos4d glad_glRasterPos4d +typedef void (APIENTRYP PFNGLRASTERPOS4DVPROC)(const GLdouble *v); +GLAPI PFNGLRASTERPOS4DVPROC glad_glRasterPos4dv; +#define glRasterPos4dv glad_glRasterPos4dv +typedef void (APIENTRYP PFNGLRASTERPOS4FPROC)(GLfloat x, GLfloat y, GLfloat z, GLfloat w); +GLAPI PFNGLRASTERPOS4FPROC glad_glRasterPos4f; +#define glRasterPos4f glad_glRasterPos4f +typedef void (APIENTRYP PFNGLRASTERPOS4FVPROC)(const GLfloat *v); +GLAPI PFNGLRASTERPOS4FVPROC glad_glRasterPos4fv; +#define glRasterPos4fv glad_glRasterPos4fv +typedef void (APIENTRYP PFNGLRASTERPOS4IPROC)(GLint x, GLint y, GLint z, GLint w); +GLAPI PFNGLRASTERPOS4IPROC glad_glRasterPos4i; +#define glRasterPos4i glad_glRasterPos4i +typedef void (APIENTRYP PFNGLRASTERPOS4IVPROC)(const GLint *v); +GLAPI PFNGLRASTERPOS4IVPROC glad_glRasterPos4iv; +#define glRasterPos4iv glad_glRasterPos4iv +typedef void (APIENTRYP PFNGLRASTERPOS4SPROC)(GLshort x, GLshort y, GLshort z, GLshort w); +GLAPI PFNGLRASTERPOS4SPROC glad_glRasterPos4s; +#define glRasterPos4s glad_glRasterPos4s +typedef void (APIENTRYP PFNGLRASTERPOS4SVPROC)(const GLshort *v); +GLAPI PFNGLRASTERPOS4SVPROC glad_glRasterPos4sv; +#define glRasterPos4sv glad_glRasterPos4sv +typedef void (APIENTRYP PFNGLRECTDPROC)(GLdouble x1, GLdouble y1, GLdouble x2, GLdouble y2); +GLAPI PFNGLRECTDPROC glad_glRectd; +#define glRectd glad_glRectd +typedef void (APIENTRYP PFNGLRECTDVPROC)(const GLdouble *v1, const GLdouble *v2); +GLAPI PFNGLRECTDVPROC glad_glRectdv; +#define glRectdv glad_glRectdv +typedef void (APIENTRYP PFNGLRECTFPROC)(GLfloat x1, GLfloat y1, GLfloat x2, GLfloat y2); +GLAPI PFNGLRECTFPROC glad_glRectf; +#define glRectf glad_glRectf +typedef void (APIENTRYP PFNGLRECTFVPROC)(const GLfloat *v1, const GLfloat *v2); +GLAPI PFNGLRECTFVPROC glad_glRectfv; +#define glRectfv glad_glRectfv +typedef void (APIENTRYP PFNGLRECTIPROC)(GLint x1, GLint y1, GLint x2, GLint y2); +GLAPI PFNGLRECTIPROC glad_glRecti; +#define glRecti glad_glRecti +typedef void (APIENTRYP PFNGLRECTIVPROC)(const GLint *v1, const GLint *v2); +GLAPI PFNGLRECTIVPROC glad_glRectiv; +#define glRectiv glad_glRectiv +typedef void (APIENTRYP PFNGLRECTSPROC)(GLshort x1, GLshort y1, GLshort x2, GLshort y2); +GLAPI PFNGLRECTSPROC glad_glRects; +#define glRects glad_glRects +typedef void (APIENTRYP PFNGLRECTSVPROC)(const GLshort *v1, const GLshort *v2); +GLAPI PFNGLRECTSVPROC glad_glRectsv; +#define glRectsv glad_glRectsv +typedef void (APIENTRYP PFNGLTEXCOORD1DPROC)(GLdouble s); +GLAPI PFNGLTEXCOORD1DPROC glad_glTexCoord1d; +#define glTexCoord1d glad_glTexCoord1d +typedef void (APIENTRYP PFNGLTEXCOORD1DVPROC)(const GLdouble *v); +GLAPI PFNGLTEXCOORD1DVPROC glad_glTexCoord1dv; +#define glTexCoord1dv glad_glTexCoord1dv +typedef void (APIENTRYP PFNGLTEXCOORD1FPROC)(GLfloat s); +GLAPI PFNGLTEXCOORD1FPROC glad_glTexCoord1f; +#define glTexCoord1f glad_glTexCoord1f +typedef void (APIENTRYP PFNGLTEXCOORD1FVPROC)(const GLfloat *v); +GLAPI PFNGLTEXCOORD1FVPROC glad_glTexCoord1fv; +#define glTexCoord1fv glad_glTexCoord1fv +typedef void (APIENTRYP PFNGLTEXCOORD1IPROC)(GLint s); +GLAPI PFNGLTEXCOORD1IPROC glad_glTexCoord1i; +#define glTexCoord1i glad_glTexCoord1i +typedef void (APIENTRYP PFNGLTEXCOORD1IVPROC)(const GLint *v); +GLAPI PFNGLTEXCOORD1IVPROC glad_glTexCoord1iv; +#define glTexCoord1iv glad_glTexCoord1iv +typedef void (APIENTRYP PFNGLTEXCOORD1SPROC)(GLshort s); +GLAPI PFNGLTEXCOORD1SPROC glad_glTexCoord1s; +#define glTexCoord1s glad_glTexCoord1s +typedef void (APIENTRYP PFNGLTEXCOORD1SVPROC)(const GLshort *v); +GLAPI PFNGLTEXCOORD1SVPROC glad_glTexCoord1sv; +#define glTexCoord1sv glad_glTexCoord1sv +typedef void (APIENTRYP PFNGLTEXCOORD2DPROC)(GLdouble s, GLdouble t); +GLAPI PFNGLTEXCOORD2DPROC glad_glTexCoord2d; +#define glTexCoord2d glad_glTexCoord2d +typedef void (APIENTRYP PFNGLTEXCOORD2DVPROC)(const GLdouble *v); +GLAPI PFNGLTEXCOORD2DVPROC glad_glTexCoord2dv; +#define glTexCoord2dv glad_glTexCoord2dv +typedef void (APIENTRYP PFNGLTEXCOORD2FPROC)(GLfloat s, GLfloat t); +GLAPI PFNGLTEXCOORD2FPROC glad_glTexCoord2f; +#define glTexCoord2f glad_glTexCoord2f +typedef void (APIENTRYP PFNGLTEXCOORD2FVPROC)(const GLfloat *v); +GLAPI PFNGLTEXCOORD2FVPROC glad_glTexCoord2fv; +#define glTexCoord2fv glad_glTexCoord2fv +typedef void (APIENTRYP PFNGLTEXCOORD2IPROC)(GLint s, GLint t); +GLAPI PFNGLTEXCOORD2IPROC glad_glTexCoord2i; +#define glTexCoord2i glad_glTexCoord2i +typedef void (APIENTRYP PFNGLTEXCOORD2IVPROC)(const GLint *v); +GLAPI PFNGLTEXCOORD2IVPROC glad_glTexCoord2iv; +#define glTexCoord2iv glad_glTexCoord2iv +typedef void (APIENTRYP PFNGLTEXCOORD2SPROC)(GLshort s, GLshort t); +GLAPI PFNGLTEXCOORD2SPROC glad_glTexCoord2s; +#define glTexCoord2s glad_glTexCoord2s +typedef void (APIENTRYP PFNGLTEXCOORD2SVPROC)(const GLshort *v); +GLAPI PFNGLTEXCOORD2SVPROC glad_glTexCoord2sv; +#define glTexCoord2sv glad_glTexCoord2sv +typedef void (APIENTRYP PFNGLTEXCOORD3DPROC)(GLdouble s, GLdouble t, GLdouble r); +GLAPI PFNGLTEXCOORD3DPROC glad_glTexCoord3d; +#define glTexCoord3d glad_glTexCoord3d +typedef void (APIENTRYP PFNGLTEXCOORD3DVPROC)(const GLdouble *v); +GLAPI PFNGLTEXCOORD3DVPROC glad_glTexCoord3dv; +#define glTexCoord3dv glad_glTexCoord3dv +typedef void (APIENTRYP PFNGLTEXCOORD3FPROC)(GLfloat s, GLfloat t, GLfloat r); +GLAPI PFNGLTEXCOORD3FPROC glad_glTexCoord3f; +#define glTexCoord3f glad_glTexCoord3f +typedef void (APIENTRYP PFNGLTEXCOORD3FVPROC)(const GLfloat *v); +GLAPI PFNGLTEXCOORD3FVPROC glad_glTexCoord3fv; +#define glTexCoord3fv glad_glTexCoord3fv +typedef void (APIENTRYP PFNGLTEXCOORD3IPROC)(GLint s, GLint t, GLint r); +GLAPI PFNGLTEXCOORD3IPROC glad_glTexCoord3i; +#define glTexCoord3i glad_glTexCoord3i +typedef void (APIENTRYP PFNGLTEXCOORD3IVPROC)(const GLint *v); +GLAPI PFNGLTEXCOORD3IVPROC glad_glTexCoord3iv; +#define glTexCoord3iv glad_glTexCoord3iv +typedef void (APIENTRYP PFNGLTEXCOORD3SPROC)(GLshort s, GLshort t, GLshort r); +GLAPI PFNGLTEXCOORD3SPROC glad_glTexCoord3s; +#define glTexCoord3s glad_glTexCoord3s +typedef void (APIENTRYP PFNGLTEXCOORD3SVPROC)(const GLshort *v); +GLAPI PFNGLTEXCOORD3SVPROC glad_glTexCoord3sv; +#define glTexCoord3sv glad_glTexCoord3sv +typedef void (APIENTRYP PFNGLTEXCOORD4DPROC)(GLdouble s, GLdouble t, GLdouble r, GLdouble q); +GLAPI PFNGLTEXCOORD4DPROC glad_glTexCoord4d; +#define glTexCoord4d glad_glTexCoord4d +typedef void (APIENTRYP PFNGLTEXCOORD4DVPROC)(const GLdouble *v); +GLAPI PFNGLTEXCOORD4DVPROC glad_glTexCoord4dv; +#define glTexCoord4dv glad_glTexCoord4dv +typedef void (APIENTRYP PFNGLTEXCOORD4FPROC)(GLfloat s, GLfloat t, GLfloat r, GLfloat q); +GLAPI PFNGLTEXCOORD4FPROC glad_glTexCoord4f; +#define glTexCoord4f glad_glTexCoord4f +typedef void (APIENTRYP PFNGLTEXCOORD4FVPROC)(const GLfloat *v); +GLAPI PFNGLTEXCOORD4FVPROC glad_glTexCoord4fv; +#define glTexCoord4fv glad_glTexCoord4fv +typedef void (APIENTRYP PFNGLTEXCOORD4IPROC)(GLint s, GLint t, GLint r, GLint q); +GLAPI PFNGLTEXCOORD4IPROC glad_glTexCoord4i; +#define glTexCoord4i glad_glTexCoord4i +typedef void (APIENTRYP PFNGLTEXCOORD4IVPROC)(const GLint *v); +GLAPI PFNGLTEXCOORD4IVPROC glad_glTexCoord4iv; +#define glTexCoord4iv glad_glTexCoord4iv +typedef void (APIENTRYP PFNGLTEXCOORD4SPROC)(GLshort s, GLshort t, GLshort r, GLshort q); +GLAPI PFNGLTEXCOORD4SPROC glad_glTexCoord4s; +#define glTexCoord4s glad_glTexCoord4s +typedef void (APIENTRYP PFNGLTEXCOORD4SVPROC)(const GLshort *v); +GLAPI PFNGLTEXCOORD4SVPROC glad_glTexCoord4sv; +#define glTexCoord4sv glad_glTexCoord4sv +typedef void (APIENTRYP PFNGLVERTEX2DPROC)(GLdouble x, GLdouble y); +GLAPI PFNGLVERTEX2DPROC glad_glVertex2d; +#define glVertex2d glad_glVertex2d +typedef void (APIENTRYP PFNGLVERTEX2DVPROC)(const GLdouble *v); +GLAPI PFNGLVERTEX2DVPROC glad_glVertex2dv; +#define glVertex2dv glad_glVertex2dv +typedef void (APIENTRYP PFNGLVERTEX2FPROC)(GLfloat x, GLfloat y); +GLAPI PFNGLVERTEX2FPROC glad_glVertex2f; +#define glVertex2f glad_glVertex2f +typedef void (APIENTRYP PFNGLVERTEX2FVPROC)(const GLfloat *v); +GLAPI PFNGLVERTEX2FVPROC glad_glVertex2fv; +#define glVertex2fv glad_glVertex2fv +typedef void (APIENTRYP PFNGLVERTEX2IPROC)(GLint x, GLint y); +GLAPI PFNGLVERTEX2IPROC glad_glVertex2i; +#define glVertex2i glad_glVertex2i +typedef void (APIENTRYP PFNGLVERTEX2IVPROC)(const GLint *v); +GLAPI PFNGLVERTEX2IVPROC glad_glVertex2iv; +#define glVertex2iv glad_glVertex2iv +typedef void (APIENTRYP PFNGLVERTEX2SPROC)(GLshort x, GLshort y); +GLAPI PFNGLVERTEX2SPROC glad_glVertex2s; +#define glVertex2s glad_glVertex2s +typedef void (APIENTRYP PFNGLVERTEX2SVPROC)(const GLshort *v); +GLAPI PFNGLVERTEX2SVPROC glad_glVertex2sv; +#define glVertex2sv glad_glVertex2sv +typedef void (APIENTRYP PFNGLVERTEX3DPROC)(GLdouble x, GLdouble y, GLdouble z); +GLAPI PFNGLVERTEX3DPROC glad_glVertex3d; +#define glVertex3d glad_glVertex3d +typedef void (APIENTRYP PFNGLVERTEX3DVPROC)(const GLdouble *v); +GLAPI PFNGLVERTEX3DVPROC glad_glVertex3dv; +#define glVertex3dv glad_glVertex3dv +typedef void (APIENTRYP PFNGLVERTEX3FPROC)(GLfloat x, GLfloat y, GLfloat z); +GLAPI PFNGLVERTEX3FPROC glad_glVertex3f; +#define glVertex3f glad_glVertex3f +typedef void (APIENTRYP PFNGLVERTEX3FVPROC)(const GLfloat *v); +GLAPI PFNGLVERTEX3FVPROC glad_glVertex3fv; +#define glVertex3fv glad_glVertex3fv +typedef void (APIENTRYP PFNGLVERTEX3IPROC)(GLint x, GLint y, GLint z); +GLAPI PFNGLVERTEX3IPROC glad_glVertex3i; +#define glVertex3i glad_glVertex3i +typedef void (APIENTRYP PFNGLVERTEX3IVPROC)(const GLint *v); +GLAPI PFNGLVERTEX3IVPROC glad_glVertex3iv; +#define glVertex3iv glad_glVertex3iv +typedef void (APIENTRYP PFNGLVERTEX3SPROC)(GLshort x, GLshort y, GLshort z); +GLAPI PFNGLVERTEX3SPROC glad_glVertex3s; +#define glVertex3s glad_glVertex3s +typedef void (APIENTRYP PFNGLVERTEX3SVPROC)(const GLshort *v); +GLAPI PFNGLVERTEX3SVPROC glad_glVertex3sv; +#define glVertex3sv glad_glVertex3sv +typedef void (APIENTRYP PFNGLVERTEX4DPROC)(GLdouble x, GLdouble y, GLdouble z, GLdouble w); +GLAPI PFNGLVERTEX4DPROC glad_glVertex4d; +#define glVertex4d glad_glVertex4d +typedef void (APIENTRYP PFNGLVERTEX4DVPROC)(const GLdouble *v); +GLAPI PFNGLVERTEX4DVPROC glad_glVertex4dv; +#define glVertex4dv glad_glVertex4dv +typedef void (APIENTRYP PFNGLVERTEX4FPROC)(GLfloat x, GLfloat y, GLfloat z, GLfloat w); +GLAPI PFNGLVERTEX4FPROC glad_glVertex4f; +#define glVertex4f glad_glVertex4f +typedef void (APIENTRYP PFNGLVERTEX4FVPROC)(const GLfloat *v); +GLAPI PFNGLVERTEX4FVPROC glad_glVertex4fv; +#define glVertex4fv glad_glVertex4fv +typedef void (APIENTRYP PFNGLVERTEX4IPROC)(GLint x, GLint y, GLint z, GLint w); +GLAPI PFNGLVERTEX4IPROC glad_glVertex4i; +#define glVertex4i glad_glVertex4i +typedef void (APIENTRYP PFNGLVERTEX4IVPROC)(const GLint *v); +GLAPI PFNGLVERTEX4IVPROC glad_glVertex4iv; +#define glVertex4iv glad_glVertex4iv +typedef void (APIENTRYP PFNGLVERTEX4SPROC)(GLshort x, GLshort y, GLshort z, GLshort w); +GLAPI PFNGLVERTEX4SPROC glad_glVertex4s; +#define glVertex4s glad_glVertex4s +typedef void (APIENTRYP PFNGLVERTEX4SVPROC)(const GLshort *v); +GLAPI PFNGLVERTEX4SVPROC glad_glVertex4sv; +#define glVertex4sv glad_glVertex4sv +typedef void (APIENTRYP PFNGLCLIPPLANEPROC)(GLenum plane, const GLdouble *equation); +GLAPI PFNGLCLIPPLANEPROC glad_glClipPlane; +#define glClipPlane glad_glClipPlane +typedef void (APIENTRYP PFNGLCOLORMATERIALPROC)(GLenum face, GLenum mode); +GLAPI PFNGLCOLORMATERIALPROC glad_glColorMaterial; +#define glColorMaterial glad_glColorMaterial +typedef void (APIENTRYP PFNGLFOGFPROC)(GLenum pname, GLfloat param); +GLAPI PFNGLFOGFPROC glad_glFogf; +#define glFogf glad_glFogf +typedef void (APIENTRYP PFNGLFOGFVPROC)(GLenum pname, const GLfloat *params); +GLAPI PFNGLFOGFVPROC glad_glFogfv; +#define glFogfv glad_glFogfv +typedef void (APIENTRYP PFNGLFOGIPROC)(GLenum pname, GLint param); +GLAPI PFNGLFOGIPROC glad_glFogi; +#define glFogi glad_glFogi +typedef void (APIENTRYP PFNGLFOGIVPROC)(GLenum pname, const GLint *params); +GLAPI PFNGLFOGIVPROC glad_glFogiv; +#define glFogiv glad_glFogiv +typedef void (APIENTRYP PFNGLLIGHTFPROC)(GLenum light, GLenum pname, GLfloat param); +GLAPI PFNGLLIGHTFPROC glad_glLightf; +#define glLightf glad_glLightf +typedef void (APIENTRYP PFNGLLIGHTFVPROC)(GLenum light, GLenum pname, const GLfloat *params); +GLAPI PFNGLLIGHTFVPROC glad_glLightfv; +#define glLightfv glad_glLightfv +typedef void (APIENTRYP PFNGLLIGHTIPROC)(GLenum light, GLenum pname, GLint param); +GLAPI PFNGLLIGHTIPROC glad_glLighti; +#define glLighti glad_glLighti +typedef void (APIENTRYP PFNGLLIGHTIVPROC)(GLenum light, GLenum pname, const GLint *params); +GLAPI PFNGLLIGHTIVPROC glad_glLightiv; +#define glLightiv glad_glLightiv +typedef void (APIENTRYP PFNGLLIGHTMODELFPROC)(GLenum pname, GLfloat param); +GLAPI PFNGLLIGHTMODELFPROC glad_glLightModelf; +#define glLightModelf glad_glLightModelf +typedef void (APIENTRYP PFNGLLIGHTMODELFVPROC)(GLenum pname, const GLfloat *params); +GLAPI PFNGLLIGHTMODELFVPROC glad_glLightModelfv; +#define glLightModelfv glad_glLightModelfv +typedef void (APIENTRYP PFNGLLIGHTMODELIPROC)(GLenum pname, GLint param); +GLAPI PFNGLLIGHTMODELIPROC glad_glLightModeli; +#define glLightModeli glad_glLightModeli +typedef void (APIENTRYP PFNGLLIGHTMODELIVPROC)(GLenum pname, const GLint *params); +GLAPI PFNGLLIGHTMODELIVPROC glad_glLightModeliv; +#define glLightModeliv glad_glLightModeliv +typedef void (APIENTRYP PFNGLLINESTIPPLEPROC)(GLint factor, GLushort pattern); +GLAPI PFNGLLINESTIPPLEPROC glad_glLineStipple; +#define glLineStipple glad_glLineStipple +typedef void (APIENTRYP PFNGLMATERIALFPROC)(GLenum face, GLenum pname, GLfloat param); +GLAPI PFNGLMATERIALFPROC glad_glMaterialf; +#define glMaterialf glad_glMaterialf +typedef void (APIENTRYP PFNGLMATERIALFVPROC)(GLenum face, GLenum pname, const GLfloat *params); +GLAPI PFNGLMATERIALFVPROC glad_glMaterialfv; +#define glMaterialfv glad_glMaterialfv +typedef void (APIENTRYP PFNGLMATERIALIPROC)(GLenum face, GLenum pname, GLint param); +GLAPI PFNGLMATERIALIPROC glad_glMateriali; +#define glMateriali glad_glMateriali +typedef void (APIENTRYP PFNGLMATERIALIVPROC)(GLenum face, GLenum pname, const GLint *params); +GLAPI PFNGLMATERIALIVPROC glad_glMaterialiv; +#define glMaterialiv glad_glMaterialiv +typedef void (APIENTRYP PFNGLPOLYGONSTIPPLEPROC)(const GLubyte *mask); +GLAPI PFNGLPOLYGONSTIPPLEPROC glad_glPolygonStipple; +#define glPolygonStipple glad_glPolygonStipple +typedef void (APIENTRYP PFNGLSHADEMODELPROC)(GLenum mode); +GLAPI PFNGLSHADEMODELPROC glad_glShadeModel; +#define glShadeModel glad_glShadeModel +typedef void (APIENTRYP PFNGLTEXENVFPROC)(GLenum target, GLenum pname, GLfloat param); +GLAPI PFNGLTEXENVFPROC glad_glTexEnvf; +#define glTexEnvf glad_glTexEnvf +typedef void (APIENTRYP PFNGLTEXENVFVPROC)(GLenum target, GLenum pname, const GLfloat *params); +GLAPI PFNGLTEXENVFVPROC glad_glTexEnvfv; +#define glTexEnvfv glad_glTexEnvfv +typedef void (APIENTRYP PFNGLTEXENVIPROC)(GLenum target, GLenum pname, GLint param); +GLAPI PFNGLTEXENVIPROC glad_glTexEnvi; +#define glTexEnvi glad_glTexEnvi +typedef void (APIENTRYP PFNGLTEXENVIVPROC)(GLenum target, GLenum pname, const GLint *params); +GLAPI PFNGLTEXENVIVPROC glad_glTexEnviv; +#define glTexEnviv glad_glTexEnviv +typedef void (APIENTRYP PFNGLTEXGENDPROC)(GLenum coord, GLenum pname, GLdouble param); +GLAPI PFNGLTEXGENDPROC glad_glTexGend; +#define glTexGend glad_glTexGend +typedef void (APIENTRYP PFNGLTEXGENDVPROC)(GLenum coord, GLenum pname, const GLdouble *params); +GLAPI PFNGLTEXGENDVPROC glad_glTexGendv; +#define glTexGendv glad_glTexGendv +typedef void (APIENTRYP PFNGLTEXGENFPROC)(GLenum coord, GLenum pname, GLfloat param); +GLAPI PFNGLTEXGENFPROC glad_glTexGenf; +#define glTexGenf glad_glTexGenf +typedef void (APIENTRYP PFNGLTEXGENFVPROC)(GLenum coord, GLenum pname, const GLfloat *params); +GLAPI PFNGLTEXGENFVPROC glad_glTexGenfv; +#define glTexGenfv glad_glTexGenfv +typedef void (APIENTRYP PFNGLTEXGENIPROC)(GLenum coord, GLenum pname, GLint param); +GLAPI PFNGLTEXGENIPROC glad_glTexGeni; +#define glTexGeni glad_glTexGeni +typedef void (APIENTRYP PFNGLTEXGENIVPROC)(GLenum coord, GLenum pname, const GLint *params); +GLAPI PFNGLTEXGENIVPROC glad_glTexGeniv; +#define glTexGeniv glad_glTexGeniv +typedef void (APIENTRYP PFNGLFEEDBACKBUFFERPROC)(GLsizei size, GLenum type, GLfloat *buffer); +GLAPI PFNGLFEEDBACKBUFFERPROC glad_glFeedbackBuffer; +#define glFeedbackBuffer glad_glFeedbackBuffer +typedef void (APIENTRYP PFNGLSELECTBUFFERPROC)(GLsizei size, GLuint *buffer); +GLAPI PFNGLSELECTBUFFERPROC glad_glSelectBuffer; +#define glSelectBuffer glad_glSelectBuffer +typedef GLint (APIENTRYP PFNGLRENDERMODEPROC)(GLenum mode); +GLAPI PFNGLRENDERMODEPROC glad_glRenderMode; +#define glRenderMode glad_glRenderMode +typedef void (APIENTRYP PFNGLINITNAMESPROC)(void); +GLAPI PFNGLINITNAMESPROC glad_glInitNames; +#define glInitNames glad_glInitNames +typedef void (APIENTRYP PFNGLLOADNAMEPROC)(GLuint name); +GLAPI PFNGLLOADNAMEPROC glad_glLoadName; +#define glLoadName glad_glLoadName +typedef void (APIENTRYP PFNGLPASSTHROUGHPROC)(GLfloat token); +GLAPI PFNGLPASSTHROUGHPROC glad_glPassThrough; +#define glPassThrough glad_glPassThrough +typedef void (APIENTRYP PFNGLPOPNAMEPROC)(void); +GLAPI PFNGLPOPNAMEPROC glad_glPopName; +#define glPopName glad_glPopName +typedef void (APIENTRYP PFNGLPUSHNAMEPROC)(GLuint name); +GLAPI PFNGLPUSHNAMEPROC glad_glPushName; +#define glPushName glad_glPushName +typedef void (APIENTRYP PFNGLCLEARACCUMPROC)(GLfloat red, GLfloat green, GLfloat blue, GLfloat alpha); +GLAPI PFNGLCLEARACCUMPROC glad_glClearAccum; +#define glClearAccum glad_glClearAccum +typedef void (APIENTRYP PFNGLCLEARINDEXPROC)(GLfloat c); +GLAPI PFNGLCLEARINDEXPROC glad_glClearIndex; +#define glClearIndex glad_glClearIndex +typedef void (APIENTRYP PFNGLINDEXMASKPROC)(GLuint mask); +GLAPI PFNGLINDEXMASKPROC glad_glIndexMask; +#define glIndexMask glad_glIndexMask +typedef void (APIENTRYP PFNGLACCUMPROC)(GLenum op, GLfloat value); +GLAPI PFNGLACCUMPROC glad_glAccum; +#define glAccum glad_glAccum +typedef void (APIENTRYP PFNGLPOPATTRIBPROC)(void); +GLAPI PFNGLPOPATTRIBPROC glad_glPopAttrib; +#define glPopAttrib glad_glPopAttrib +typedef void (APIENTRYP PFNGLPUSHATTRIBPROC)(GLbitfield mask); +GLAPI PFNGLPUSHATTRIBPROC glad_glPushAttrib; +#define glPushAttrib glad_glPushAttrib +typedef void (APIENTRYP PFNGLMAP1DPROC)(GLenum target, GLdouble u1, GLdouble u2, GLint stride, GLint order, const GLdouble *points); +GLAPI PFNGLMAP1DPROC glad_glMap1d; +#define glMap1d glad_glMap1d +typedef void (APIENTRYP PFNGLMAP1FPROC)(GLenum target, GLfloat u1, GLfloat u2, GLint stride, GLint order, const GLfloat *points); +GLAPI PFNGLMAP1FPROC glad_glMap1f; +#define glMap1f glad_glMap1f +typedef void (APIENTRYP PFNGLMAP2DPROC)(GLenum target, GLdouble u1, GLdouble u2, GLint ustride, GLint uorder, GLdouble v1, GLdouble v2, GLint vstride, GLint vorder, const GLdouble *points); +GLAPI PFNGLMAP2DPROC glad_glMap2d; +#define glMap2d glad_glMap2d +typedef void (APIENTRYP PFNGLMAP2FPROC)(GLenum target, GLfloat u1, GLfloat u2, GLint ustride, GLint uorder, GLfloat v1, GLfloat v2, GLint vstride, GLint vorder, const GLfloat *points); +GLAPI PFNGLMAP2FPROC glad_glMap2f; +#define glMap2f glad_glMap2f +typedef void (APIENTRYP PFNGLMAPGRID1DPROC)(GLint un, GLdouble u1, GLdouble u2); +GLAPI PFNGLMAPGRID1DPROC glad_glMapGrid1d; +#define glMapGrid1d glad_glMapGrid1d +typedef void (APIENTRYP PFNGLMAPGRID1FPROC)(GLint un, GLfloat u1, GLfloat u2); +GLAPI PFNGLMAPGRID1FPROC glad_glMapGrid1f; +#define glMapGrid1f glad_glMapGrid1f +typedef void (APIENTRYP PFNGLMAPGRID2DPROC)(GLint un, GLdouble u1, GLdouble u2, GLint vn, GLdouble v1, GLdouble v2); +GLAPI PFNGLMAPGRID2DPROC glad_glMapGrid2d; +#define glMapGrid2d glad_glMapGrid2d +typedef void (APIENTRYP PFNGLMAPGRID2FPROC)(GLint un, GLfloat u1, GLfloat u2, GLint vn, GLfloat v1, GLfloat v2); +GLAPI PFNGLMAPGRID2FPROC glad_glMapGrid2f; +#define glMapGrid2f glad_glMapGrid2f +typedef void (APIENTRYP PFNGLEVALCOORD1DPROC)(GLdouble u); +GLAPI PFNGLEVALCOORD1DPROC glad_glEvalCoord1d; +#define glEvalCoord1d glad_glEvalCoord1d +typedef void (APIENTRYP PFNGLEVALCOORD1DVPROC)(const GLdouble *u); +GLAPI PFNGLEVALCOORD1DVPROC glad_glEvalCoord1dv; +#define glEvalCoord1dv glad_glEvalCoord1dv +typedef void (APIENTRYP PFNGLEVALCOORD1FPROC)(GLfloat u); +GLAPI PFNGLEVALCOORD1FPROC glad_glEvalCoord1f; +#define glEvalCoord1f glad_glEvalCoord1f +typedef void (APIENTRYP PFNGLEVALCOORD1FVPROC)(const GLfloat *u); +GLAPI PFNGLEVALCOORD1FVPROC glad_glEvalCoord1fv; +#define glEvalCoord1fv glad_glEvalCoord1fv +typedef void (APIENTRYP PFNGLEVALCOORD2DPROC)(GLdouble u, GLdouble v); +GLAPI PFNGLEVALCOORD2DPROC glad_glEvalCoord2d; +#define glEvalCoord2d glad_glEvalCoord2d +typedef void (APIENTRYP PFNGLEVALCOORD2DVPROC)(const GLdouble *u); +GLAPI PFNGLEVALCOORD2DVPROC glad_glEvalCoord2dv; +#define glEvalCoord2dv glad_glEvalCoord2dv +typedef void (APIENTRYP PFNGLEVALCOORD2FPROC)(GLfloat u, GLfloat v); +GLAPI PFNGLEVALCOORD2FPROC glad_glEvalCoord2f; +#define glEvalCoord2f glad_glEvalCoord2f +typedef void (APIENTRYP PFNGLEVALCOORD2FVPROC)(const GLfloat *u); +GLAPI PFNGLEVALCOORD2FVPROC glad_glEvalCoord2fv; +#define glEvalCoord2fv glad_glEvalCoord2fv +typedef void (APIENTRYP PFNGLEVALMESH1PROC)(GLenum mode, GLint i1, GLint i2); +GLAPI PFNGLEVALMESH1PROC glad_glEvalMesh1; +#define glEvalMesh1 glad_glEvalMesh1 +typedef void (APIENTRYP PFNGLEVALPOINT1PROC)(GLint i); +GLAPI PFNGLEVALPOINT1PROC glad_glEvalPoint1; +#define glEvalPoint1 glad_glEvalPoint1 +typedef void (APIENTRYP PFNGLEVALMESH2PROC)(GLenum mode, GLint i1, GLint i2, GLint j1, GLint j2); +GLAPI PFNGLEVALMESH2PROC glad_glEvalMesh2; +#define glEvalMesh2 glad_glEvalMesh2 +typedef void (APIENTRYP PFNGLEVALPOINT2PROC)(GLint i, GLint j); +GLAPI PFNGLEVALPOINT2PROC glad_glEvalPoint2; +#define glEvalPoint2 glad_glEvalPoint2 +typedef void (APIENTRYP PFNGLALPHAFUNCPROC)(GLenum func, GLfloat ref); +GLAPI PFNGLALPHAFUNCPROC glad_glAlphaFunc; +#define glAlphaFunc glad_glAlphaFunc +typedef void (APIENTRYP PFNGLPIXELZOOMPROC)(GLfloat xfactor, GLfloat yfactor); +GLAPI PFNGLPIXELZOOMPROC glad_glPixelZoom; +#define glPixelZoom glad_glPixelZoom +typedef void (APIENTRYP PFNGLPIXELTRANSFERFPROC)(GLenum pname, GLfloat param); +GLAPI PFNGLPIXELTRANSFERFPROC glad_glPixelTransferf; +#define glPixelTransferf glad_glPixelTransferf +typedef void (APIENTRYP PFNGLPIXELTRANSFERIPROC)(GLenum pname, GLint param); +GLAPI PFNGLPIXELTRANSFERIPROC glad_glPixelTransferi; +#define glPixelTransferi glad_glPixelTransferi +typedef void (APIENTRYP PFNGLPIXELMAPFVPROC)(GLenum map, GLsizei mapsize, const GLfloat *values); +GLAPI PFNGLPIXELMAPFVPROC glad_glPixelMapfv; +#define glPixelMapfv glad_glPixelMapfv +typedef void (APIENTRYP PFNGLPIXELMAPUIVPROC)(GLenum map, GLsizei mapsize, const GLuint *values); +GLAPI PFNGLPIXELMAPUIVPROC glad_glPixelMapuiv; +#define glPixelMapuiv glad_glPixelMapuiv +typedef void (APIENTRYP PFNGLPIXELMAPUSVPROC)(GLenum map, GLsizei mapsize, const GLushort *values); +GLAPI PFNGLPIXELMAPUSVPROC glad_glPixelMapusv; +#define glPixelMapusv glad_glPixelMapusv +typedef void (APIENTRYP PFNGLCOPYPIXELSPROC)(GLint x, GLint y, GLsizei width, GLsizei height, GLenum type); +GLAPI PFNGLCOPYPIXELSPROC glad_glCopyPixels; +#define glCopyPixels glad_glCopyPixels +typedef void (APIENTRYP PFNGLDRAWPIXELSPROC)(GLsizei width, GLsizei height, GLenum format, GLenum type, const void *pixels); +GLAPI PFNGLDRAWPIXELSPROC glad_glDrawPixels; +#define glDrawPixels glad_glDrawPixels +typedef void (APIENTRYP PFNGLGETCLIPPLANEPROC)(GLenum plane, GLdouble *equation); +GLAPI PFNGLGETCLIPPLANEPROC glad_glGetClipPlane; +#define glGetClipPlane glad_glGetClipPlane +typedef void (APIENTRYP PFNGLGETLIGHTFVPROC)(GLenum light, GLenum pname, GLfloat *params); +GLAPI PFNGLGETLIGHTFVPROC glad_glGetLightfv; +#define glGetLightfv glad_glGetLightfv +typedef void (APIENTRYP PFNGLGETLIGHTIVPROC)(GLenum light, GLenum pname, GLint *params); +GLAPI PFNGLGETLIGHTIVPROC glad_glGetLightiv; +#define glGetLightiv glad_glGetLightiv +typedef void (APIENTRYP PFNGLGETMAPDVPROC)(GLenum target, GLenum query, GLdouble *v); +GLAPI PFNGLGETMAPDVPROC glad_glGetMapdv; +#define glGetMapdv glad_glGetMapdv +typedef void (APIENTRYP PFNGLGETMAPFVPROC)(GLenum target, GLenum query, GLfloat *v); +GLAPI PFNGLGETMAPFVPROC glad_glGetMapfv; +#define glGetMapfv glad_glGetMapfv +typedef void (APIENTRYP PFNGLGETMAPIVPROC)(GLenum target, GLenum query, GLint *v); +GLAPI PFNGLGETMAPIVPROC glad_glGetMapiv; +#define glGetMapiv glad_glGetMapiv +typedef void (APIENTRYP PFNGLGETMATERIALFVPROC)(GLenum face, GLenum pname, GLfloat *params); +GLAPI PFNGLGETMATERIALFVPROC glad_glGetMaterialfv; +#define glGetMaterialfv glad_glGetMaterialfv +typedef void (APIENTRYP PFNGLGETMATERIALIVPROC)(GLenum face, GLenum pname, GLint *params); +GLAPI PFNGLGETMATERIALIVPROC glad_glGetMaterialiv; +#define glGetMaterialiv glad_glGetMaterialiv +typedef void (APIENTRYP PFNGLGETPIXELMAPFVPROC)(GLenum map, GLfloat *values); +GLAPI PFNGLGETPIXELMAPFVPROC glad_glGetPixelMapfv; +#define glGetPixelMapfv glad_glGetPixelMapfv +typedef void (APIENTRYP PFNGLGETPIXELMAPUIVPROC)(GLenum map, GLuint *values); +GLAPI PFNGLGETPIXELMAPUIVPROC glad_glGetPixelMapuiv; +#define glGetPixelMapuiv glad_glGetPixelMapuiv +typedef void (APIENTRYP PFNGLGETPIXELMAPUSVPROC)(GLenum map, GLushort *values); +GLAPI PFNGLGETPIXELMAPUSVPROC glad_glGetPixelMapusv; +#define glGetPixelMapusv glad_glGetPixelMapusv +typedef void (APIENTRYP PFNGLGETPOLYGONSTIPPLEPROC)(GLubyte *mask); +GLAPI PFNGLGETPOLYGONSTIPPLEPROC glad_glGetPolygonStipple; +#define glGetPolygonStipple glad_glGetPolygonStipple +typedef void (APIENTRYP PFNGLGETTEXENVFVPROC)(GLenum target, GLenum pname, GLfloat *params); +GLAPI PFNGLGETTEXENVFVPROC glad_glGetTexEnvfv; +#define glGetTexEnvfv glad_glGetTexEnvfv +typedef void (APIENTRYP PFNGLGETTEXENVIVPROC)(GLenum target, GLenum pname, GLint *params); +GLAPI PFNGLGETTEXENVIVPROC glad_glGetTexEnviv; +#define glGetTexEnviv glad_glGetTexEnviv +typedef void (APIENTRYP PFNGLGETTEXGENDVPROC)(GLenum coord, GLenum pname, GLdouble *params); +GLAPI PFNGLGETTEXGENDVPROC glad_glGetTexGendv; +#define glGetTexGendv glad_glGetTexGendv +typedef void (APIENTRYP PFNGLGETTEXGENFVPROC)(GLenum coord, GLenum pname, GLfloat *params); +GLAPI PFNGLGETTEXGENFVPROC glad_glGetTexGenfv; +#define glGetTexGenfv glad_glGetTexGenfv +typedef void (APIENTRYP PFNGLGETTEXGENIVPROC)(GLenum coord, GLenum pname, GLint *params); +GLAPI PFNGLGETTEXGENIVPROC glad_glGetTexGeniv; +#define glGetTexGeniv glad_glGetTexGeniv +typedef GLboolean (APIENTRYP PFNGLISLISTPROC)(GLuint list); +GLAPI PFNGLISLISTPROC glad_glIsList; +#define glIsList glad_glIsList +typedef void (APIENTRYP PFNGLFRUSTUMPROC)(GLdouble left, GLdouble right, GLdouble bottom, GLdouble top, GLdouble zNear, GLdouble zFar); +GLAPI PFNGLFRUSTUMPROC glad_glFrustum; +#define glFrustum glad_glFrustum +typedef void (APIENTRYP PFNGLLOADIDENTITYPROC)(void); +GLAPI PFNGLLOADIDENTITYPROC glad_glLoadIdentity; +#define glLoadIdentity glad_glLoadIdentity +typedef void (APIENTRYP PFNGLLOADMATRIXFPROC)(const GLfloat *m); +GLAPI PFNGLLOADMATRIXFPROC glad_glLoadMatrixf; +#define glLoadMatrixf glad_glLoadMatrixf +typedef void (APIENTRYP PFNGLLOADMATRIXDPROC)(const GLdouble *m); +GLAPI PFNGLLOADMATRIXDPROC glad_glLoadMatrixd; +#define glLoadMatrixd glad_glLoadMatrixd +typedef void (APIENTRYP PFNGLMATRIXMODEPROC)(GLenum mode); +GLAPI PFNGLMATRIXMODEPROC glad_glMatrixMode; +#define glMatrixMode glad_glMatrixMode +typedef void (APIENTRYP PFNGLMULTMATRIXFPROC)(const GLfloat *m); +GLAPI PFNGLMULTMATRIXFPROC glad_glMultMatrixf; +#define glMultMatrixf glad_glMultMatrixf +typedef void (APIENTRYP PFNGLMULTMATRIXDPROC)(const GLdouble *m); +GLAPI PFNGLMULTMATRIXDPROC glad_glMultMatrixd; +#define glMultMatrixd glad_glMultMatrixd +typedef void (APIENTRYP PFNGLORTHOPROC)(GLdouble left, GLdouble right, GLdouble bottom, GLdouble top, GLdouble zNear, GLdouble zFar); +GLAPI PFNGLORTHOPROC glad_glOrtho; +#define glOrtho glad_glOrtho +typedef void (APIENTRYP PFNGLPOPMATRIXPROC)(void); +GLAPI PFNGLPOPMATRIXPROC glad_glPopMatrix; +#define glPopMatrix glad_glPopMatrix +typedef void (APIENTRYP PFNGLPUSHMATRIXPROC)(void); +GLAPI PFNGLPUSHMATRIXPROC glad_glPushMatrix; +#define glPushMatrix glad_glPushMatrix +typedef void (APIENTRYP PFNGLROTATEDPROC)(GLdouble angle, GLdouble x, GLdouble y, GLdouble z); +GLAPI PFNGLROTATEDPROC glad_glRotated; +#define glRotated glad_glRotated +typedef void (APIENTRYP PFNGLROTATEFPROC)(GLfloat angle, GLfloat x, GLfloat y, GLfloat z); +GLAPI PFNGLROTATEFPROC glad_glRotatef; +#define glRotatef glad_glRotatef +typedef void (APIENTRYP PFNGLSCALEDPROC)(GLdouble x, GLdouble y, GLdouble z); +GLAPI PFNGLSCALEDPROC glad_glScaled; +#define glScaled glad_glScaled +typedef void (APIENTRYP PFNGLSCALEFPROC)(GLfloat x, GLfloat y, GLfloat z); +GLAPI PFNGLSCALEFPROC glad_glScalef; +#define glScalef glad_glScalef +typedef void (APIENTRYP PFNGLTRANSLATEDPROC)(GLdouble x, GLdouble y, GLdouble z); +GLAPI PFNGLTRANSLATEDPROC glad_glTranslated; +#define glTranslated glad_glTranslated +typedef void (APIENTRYP PFNGLTRANSLATEFPROC)(GLfloat x, GLfloat y, GLfloat z); +GLAPI PFNGLTRANSLATEFPROC glad_glTranslatef; +#define glTranslatef glad_glTranslatef +#endif +#ifndef GL_VERSION_1_1 +#define GL_VERSION_1_1 1 +GLAPI int GLAD_GL_VERSION_1_1; +typedef void (APIENTRYP PFNGLDRAWARRAYSPROC)(GLenum mode, GLint first, GLsizei count); +GLAPI PFNGLDRAWARRAYSPROC glad_glDrawArrays; +#define glDrawArrays glad_glDrawArrays +typedef void (APIENTRYP PFNGLDRAWELEMENTSPROC)(GLenum mode, GLsizei count, GLenum type, const void *indices); +GLAPI PFNGLDRAWELEMENTSPROC glad_glDrawElements; +#define glDrawElements glad_glDrawElements +typedef void (APIENTRYP PFNGLGETPOINTERVPROC)(GLenum pname, void **params); +GLAPI PFNGLGETPOINTERVPROC glad_glGetPointerv; +#define glGetPointerv glad_glGetPointerv +typedef void (APIENTRYP PFNGLPOLYGONOFFSETPROC)(GLfloat factor, GLfloat units); +GLAPI PFNGLPOLYGONOFFSETPROC glad_glPolygonOffset; +#define glPolygonOffset glad_glPolygonOffset +typedef void (APIENTRYP PFNGLCOPYTEXIMAGE1DPROC)(GLenum target, GLint level, GLenum internalformat, GLint x, GLint y, GLsizei width, GLint border); +GLAPI PFNGLCOPYTEXIMAGE1DPROC glad_glCopyTexImage1D; +#define glCopyTexImage1D glad_glCopyTexImage1D +typedef void (APIENTRYP PFNGLCOPYTEXIMAGE2DPROC)(GLenum target, GLint level, GLenum internalformat, GLint x, GLint y, GLsizei width, GLsizei height, GLint border); +GLAPI PFNGLCOPYTEXIMAGE2DPROC glad_glCopyTexImage2D; +#define glCopyTexImage2D glad_glCopyTexImage2D +typedef void (APIENTRYP PFNGLCOPYTEXSUBIMAGE1DPROC)(GLenum target, GLint level, GLint xoffset, GLint x, GLint y, GLsizei width); +GLAPI PFNGLCOPYTEXSUBIMAGE1DPROC glad_glCopyTexSubImage1D; +#define glCopyTexSubImage1D glad_glCopyTexSubImage1D +typedef void (APIENTRYP PFNGLCOPYTEXSUBIMAGE2DPROC)(GLenum target, GLint level, GLint xoffset, GLint yoffset, GLint x, GLint y, GLsizei width, GLsizei height); +GLAPI PFNGLCOPYTEXSUBIMAGE2DPROC glad_glCopyTexSubImage2D; +#define glCopyTexSubImage2D glad_glCopyTexSubImage2D +typedef void (APIENTRYP PFNGLTEXSUBIMAGE1DPROC)(GLenum target, GLint level, GLint xoffset, GLsizei width, GLenum format, GLenum type, const void *pixels); +GLAPI PFNGLTEXSUBIMAGE1DPROC glad_glTexSubImage1D; +#define glTexSubImage1D glad_glTexSubImage1D +typedef void (APIENTRYP PFNGLTEXSUBIMAGE2DPROC)(GLenum target, GLint level, GLint xoffset, GLint yoffset, GLsizei width, GLsizei height, GLenum format, GLenum type, const void *pixels); +GLAPI PFNGLTEXSUBIMAGE2DPROC glad_glTexSubImage2D; +#define glTexSubImage2D glad_glTexSubImage2D +typedef void (APIENTRYP PFNGLBINDTEXTUREPROC)(GLenum target, GLuint texture); +GLAPI PFNGLBINDTEXTUREPROC glad_glBindTexture; +#define glBindTexture glad_glBindTexture +typedef void (APIENTRYP PFNGLDELETETEXTURESPROC)(GLsizei n, const GLuint *textures); +GLAPI PFNGLDELETETEXTURESPROC glad_glDeleteTextures; +#define glDeleteTextures glad_glDeleteTextures +typedef void (APIENTRYP PFNGLGENTEXTURESPROC)(GLsizei n, GLuint *textures); +GLAPI PFNGLGENTEXTURESPROC glad_glGenTextures; +#define glGenTextures glad_glGenTextures +typedef GLboolean (APIENTRYP PFNGLISTEXTUREPROC)(GLuint texture); +GLAPI PFNGLISTEXTUREPROC glad_glIsTexture; +#define glIsTexture glad_glIsTexture +typedef void (APIENTRYP PFNGLARRAYELEMENTPROC)(GLint i); +GLAPI PFNGLARRAYELEMENTPROC glad_glArrayElement; +#define glArrayElement glad_glArrayElement +typedef void (APIENTRYP PFNGLCOLORPOINTERPROC)(GLint size, GLenum type, GLsizei stride, const void *pointer); +GLAPI PFNGLCOLORPOINTERPROC glad_glColorPointer; +#define glColorPointer glad_glColorPointer +typedef void (APIENTRYP PFNGLDISABLECLIENTSTATEPROC)(GLenum array); +GLAPI PFNGLDISABLECLIENTSTATEPROC glad_glDisableClientState; +#define glDisableClientState glad_glDisableClientState +typedef void (APIENTRYP PFNGLEDGEFLAGPOINTERPROC)(GLsizei stride, const void *pointer); +GLAPI PFNGLEDGEFLAGPOINTERPROC glad_glEdgeFlagPointer; +#define glEdgeFlagPointer glad_glEdgeFlagPointer +typedef void (APIENTRYP PFNGLENABLECLIENTSTATEPROC)(GLenum array); +GLAPI PFNGLENABLECLIENTSTATEPROC glad_glEnableClientState; +#define glEnableClientState glad_glEnableClientState +typedef void (APIENTRYP PFNGLINDEXPOINTERPROC)(GLenum type, GLsizei stride, const void *pointer); +GLAPI PFNGLINDEXPOINTERPROC glad_glIndexPointer; +#define glIndexPointer glad_glIndexPointer +typedef void (APIENTRYP PFNGLINTERLEAVEDARRAYSPROC)(GLenum format, GLsizei stride, const void *pointer); +GLAPI PFNGLINTERLEAVEDARRAYSPROC glad_glInterleavedArrays; +#define glInterleavedArrays glad_glInterleavedArrays +typedef void (APIENTRYP PFNGLNORMALPOINTERPROC)(GLenum type, GLsizei stride, const void *pointer); +GLAPI PFNGLNORMALPOINTERPROC glad_glNormalPointer; +#define glNormalPointer glad_glNormalPointer +typedef void (APIENTRYP PFNGLTEXCOORDPOINTERPROC)(GLint size, GLenum type, GLsizei stride, const void *pointer); +GLAPI PFNGLTEXCOORDPOINTERPROC glad_glTexCoordPointer; +#define glTexCoordPointer glad_glTexCoordPointer +typedef void (APIENTRYP PFNGLVERTEXPOINTERPROC)(GLint size, GLenum type, GLsizei stride, const void *pointer); +GLAPI PFNGLVERTEXPOINTERPROC glad_glVertexPointer; +#define glVertexPointer glad_glVertexPointer +typedef GLboolean (APIENTRYP PFNGLARETEXTURESRESIDENTPROC)(GLsizei n, const GLuint *textures, GLboolean *residences); +GLAPI PFNGLARETEXTURESRESIDENTPROC glad_glAreTexturesResident; +#define glAreTexturesResident glad_glAreTexturesResident +typedef void (APIENTRYP PFNGLPRIORITIZETEXTURESPROC)(GLsizei n, const GLuint *textures, const GLfloat *priorities); +GLAPI PFNGLPRIORITIZETEXTURESPROC glad_glPrioritizeTextures; +#define glPrioritizeTextures glad_glPrioritizeTextures +typedef void (APIENTRYP PFNGLINDEXUBPROC)(GLubyte c); +GLAPI PFNGLINDEXUBPROC glad_glIndexub; +#define glIndexub glad_glIndexub +typedef void (APIENTRYP PFNGLINDEXUBVPROC)(const GLubyte *c); +GLAPI PFNGLINDEXUBVPROC glad_glIndexubv; +#define glIndexubv glad_glIndexubv +typedef void (APIENTRYP PFNGLPOPCLIENTATTRIBPROC)(void); +GLAPI PFNGLPOPCLIENTATTRIBPROC glad_glPopClientAttrib; +#define glPopClientAttrib glad_glPopClientAttrib +typedef void (APIENTRYP PFNGLPUSHCLIENTATTRIBPROC)(GLbitfield mask); +GLAPI PFNGLPUSHCLIENTATTRIBPROC glad_glPushClientAttrib; +#define glPushClientAttrib glad_glPushClientAttrib +#endif +#ifndef GL_VERSION_1_2 +#define GL_VERSION_1_2 1 +GLAPI int GLAD_GL_VERSION_1_2; +typedef void (APIENTRYP PFNGLDRAWRANGEELEMENTSPROC)(GLenum mode, GLuint start, GLuint end, GLsizei count, GLenum type, const void *indices); +GLAPI PFNGLDRAWRANGEELEMENTSPROC glad_glDrawRangeElements; +#define glDrawRangeElements glad_glDrawRangeElements +typedef void (APIENTRYP PFNGLTEXIMAGE3DPROC)(GLenum target, GLint level, GLint internalformat, GLsizei width, GLsizei height, GLsizei depth, GLint border, GLenum format, GLenum type, const void *pixels); +GLAPI PFNGLTEXIMAGE3DPROC glad_glTexImage3D; +#define glTexImage3D glad_glTexImage3D +typedef void (APIENTRYP PFNGLTEXSUBIMAGE3DPROC)(GLenum target, GLint level, GLint xoffset, GLint yoffset, GLint zoffset, GLsizei width, GLsizei height, GLsizei depth, GLenum format, GLenum type, const void *pixels); +GLAPI PFNGLTEXSUBIMAGE3DPROC glad_glTexSubImage3D; +#define glTexSubImage3D glad_glTexSubImage3D +typedef void (APIENTRYP PFNGLCOPYTEXSUBIMAGE3DPROC)(GLenum target, GLint level, GLint xoffset, GLint yoffset, GLint zoffset, GLint x, GLint y, GLsizei width, GLsizei height); +GLAPI PFNGLCOPYTEXSUBIMAGE3DPROC glad_glCopyTexSubImage3D; +#define glCopyTexSubImage3D glad_glCopyTexSubImage3D +#endif +#ifndef GL_VERSION_1_3 +#define GL_VERSION_1_3 1 +GLAPI int GLAD_GL_VERSION_1_3; +typedef void (APIENTRYP PFNGLACTIVETEXTUREPROC)(GLenum texture); +GLAPI PFNGLACTIVETEXTUREPROC glad_glActiveTexture; +#define glActiveTexture glad_glActiveTexture +typedef void (APIENTRYP PFNGLSAMPLECOVERAGEPROC)(GLfloat value, GLboolean invert); +GLAPI PFNGLSAMPLECOVERAGEPROC glad_glSampleCoverage; +#define glSampleCoverage glad_glSampleCoverage +typedef void (APIENTRYP PFNGLCOMPRESSEDTEXIMAGE3DPROC)(GLenum target, GLint level, GLenum internalformat, GLsizei width, GLsizei height, GLsizei depth, GLint border, GLsizei imageSize, const void *data); +GLAPI PFNGLCOMPRESSEDTEXIMAGE3DPROC glad_glCompressedTexImage3D; +#define glCompressedTexImage3D glad_glCompressedTexImage3D +typedef void (APIENTRYP PFNGLCOMPRESSEDTEXIMAGE2DPROC)(GLenum target, GLint level, GLenum internalformat, GLsizei width, GLsizei height, GLint border, GLsizei imageSize, const void *data); +GLAPI PFNGLCOMPRESSEDTEXIMAGE2DPROC glad_glCompressedTexImage2D; +#define glCompressedTexImage2D glad_glCompressedTexImage2D +typedef void (APIENTRYP PFNGLCOMPRESSEDTEXIMAGE1DPROC)(GLenum target, GLint level, GLenum internalformat, GLsizei width, GLint border, GLsizei imageSize, const void *data); +GLAPI PFNGLCOMPRESSEDTEXIMAGE1DPROC glad_glCompressedTexImage1D; +#define glCompressedTexImage1D glad_glCompressedTexImage1D +typedef void (APIENTRYP PFNGLCOMPRESSEDTEXSUBIMAGE3DPROC)(GLenum target, GLint level, GLint xoffset, GLint yoffset, GLint zoffset, GLsizei width, GLsizei height, GLsizei depth, GLenum format, GLsizei imageSize, const void *data); +GLAPI PFNGLCOMPRESSEDTEXSUBIMAGE3DPROC glad_glCompressedTexSubImage3D; +#define glCompressedTexSubImage3D glad_glCompressedTexSubImage3D +typedef void (APIENTRYP PFNGLCOMPRESSEDTEXSUBIMAGE2DPROC)(GLenum target, GLint level, GLint xoffset, GLint yoffset, GLsizei width, GLsizei height, GLenum format, GLsizei imageSize, const void *data); +GLAPI PFNGLCOMPRESSEDTEXSUBIMAGE2DPROC glad_glCompressedTexSubImage2D; +#define glCompressedTexSubImage2D glad_glCompressedTexSubImage2D +typedef void (APIENTRYP PFNGLCOMPRESSEDTEXSUBIMAGE1DPROC)(GLenum target, GLint level, GLint xoffset, GLsizei width, GLenum format, GLsizei imageSize, const void *data); +GLAPI PFNGLCOMPRESSEDTEXSUBIMAGE1DPROC glad_glCompressedTexSubImage1D; +#define glCompressedTexSubImage1D glad_glCompressedTexSubImage1D +typedef void (APIENTRYP PFNGLGETCOMPRESSEDTEXIMAGEPROC)(GLenum target, GLint level, void *img); +GLAPI PFNGLGETCOMPRESSEDTEXIMAGEPROC glad_glGetCompressedTexImage; +#define glGetCompressedTexImage glad_glGetCompressedTexImage +typedef void (APIENTRYP PFNGLCLIENTACTIVETEXTUREPROC)(GLenum texture); +GLAPI PFNGLCLIENTACTIVETEXTUREPROC glad_glClientActiveTexture; +#define glClientActiveTexture glad_glClientActiveTexture +typedef void (APIENTRYP PFNGLMULTITEXCOORD1DPROC)(GLenum target, GLdouble s); +GLAPI PFNGLMULTITEXCOORD1DPROC glad_glMultiTexCoord1d; +#define glMultiTexCoord1d glad_glMultiTexCoord1d +typedef void (APIENTRYP PFNGLMULTITEXCOORD1DVPROC)(GLenum target, const GLdouble *v); +GLAPI PFNGLMULTITEXCOORD1DVPROC glad_glMultiTexCoord1dv; +#define glMultiTexCoord1dv glad_glMultiTexCoord1dv +typedef void (APIENTRYP PFNGLMULTITEXCOORD1FPROC)(GLenum target, GLfloat s); +GLAPI PFNGLMULTITEXCOORD1FPROC glad_glMultiTexCoord1f; +#define glMultiTexCoord1f glad_glMultiTexCoord1f +typedef void (APIENTRYP PFNGLMULTITEXCOORD1FVPROC)(GLenum target, const GLfloat *v); +GLAPI PFNGLMULTITEXCOORD1FVPROC glad_glMultiTexCoord1fv; +#define glMultiTexCoord1fv glad_glMultiTexCoord1fv +typedef void (APIENTRYP PFNGLMULTITEXCOORD1IPROC)(GLenum target, GLint s); +GLAPI PFNGLMULTITEXCOORD1IPROC glad_glMultiTexCoord1i; +#define glMultiTexCoord1i glad_glMultiTexCoord1i +typedef void (APIENTRYP PFNGLMULTITEXCOORD1IVPROC)(GLenum target, const GLint *v); +GLAPI PFNGLMULTITEXCOORD1IVPROC glad_glMultiTexCoord1iv; +#define glMultiTexCoord1iv glad_glMultiTexCoord1iv +typedef void (APIENTRYP PFNGLMULTITEXCOORD1SPROC)(GLenum target, GLshort s); +GLAPI PFNGLMULTITEXCOORD1SPROC glad_glMultiTexCoord1s; +#define glMultiTexCoord1s glad_glMultiTexCoord1s +typedef void (APIENTRYP PFNGLMULTITEXCOORD1SVPROC)(GLenum target, const GLshort *v); +GLAPI PFNGLMULTITEXCOORD1SVPROC glad_glMultiTexCoord1sv; +#define glMultiTexCoord1sv glad_glMultiTexCoord1sv +typedef void (APIENTRYP PFNGLMULTITEXCOORD2DPROC)(GLenum target, GLdouble s, GLdouble t); +GLAPI PFNGLMULTITEXCOORD2DPROC glad_glMultiTexCoord2d; +#define glMultiTexCoord2d glad_glMultiTexCoord2d +typedef void (APIENTRYP PFNGLMULTITEXCOORD2DVPROC)(GLenum target, const GLdouble *v); +GLAPI PFNGLMULTITEXCOORD2DVPROC glad_glMultiTexCoord2dv; +#define glMultiTexCoord2dv glad_glMultiTexCoord2dv +typedef void (APIENTRYP PFNGLMULTITEXCOORD2FPROC)(GLenum target, GLfloat s, GLfloat t); +GLAPI PFNGLMULTITEXCOORD2FPROC glad_glMultiTexCoord2f; +#define glMultiTexCoord2f glad_glMultiTexCoord2f +typedef void (APIENTRYP PFNGLMULTITEXCOORD2FVPROC)(GLenum target, const GLfloat *v); +GLAPI PFNGLMULTITEXCOORD2FVPROC glad_glMultiTexCoord2fv; +#define glMultiTexCoord2fv glad_glMultiTexCoord2fv +typedef void (APIENTRYP PFNGLMULTITEXCOORD2IPROC)(GLenum target, GLint s, GLint t); +GLAPI PFNGLMULTITEXCOORD2IPROC glad_glMultiTexCoord2i; +#define glMultiTexCoord2i glad_glMultiTexCoord2i +typedef void (APIENTRYP PFNGLMULTITEXCOORD2IVPROC)(GLenum target, const GLint *v); +GLAPI PFNGLMULTITEXCOORD2IVPROC glad_glMultiTexCoord2iv; +#define glMultiTexCoord2iv glad_glMultiTexCoord2iv +typedef void (APIENTRYP PFNGLMULTITEXCOORD2SPROC)(GLenum target, GLshort s, GLshort t); +GLAPI PFNGLMULTITEXCOORD2SPROC glad_glMultiTexCoord2s; +#define glMultiTexCoord2s glad_glMultiTexCoord2s +typedef void (APIENTRYP PFNGLMULTITEXCOORD2SVPROC)(GLenum target, const GLshort *v); +GLAPI PFNGLMULTITEXCOORD2SVPROC glad_glMultiTexCoord2sv; +#define glMultiTexCoord2sv glad_glMultiTexCoord2sv +typedef void (APIENTRYP PFNGLMULTITEXCOORD3DPROC)(GLenum target, GLdouble s, GLdouble t, GLdouble r); +GLAPI PFNGLMULTITEXCOORD3DPROC glad_glMultiTexCoord3d; +#define glMultiTexCoord3d glad_glMultiTexCoord3d +typedef void (APIENTRYP PFNGLMULTITEXCOORD3DVPROC)(GLenum target, const GLdouble *v); +GLAPI PFNGLMULTITEXCOORD3DVPROC glad_glMultiTexCoord3dv; +#define glMultiTexCoord3dv glad_glMultiTexCoord3dv +typedef void (APIENTRYP PFNGLMULTITEXCOORD3FPROC)(GLenum target, GLfloat s, GLfloat t, GLfloat r); +GLAPI PFNGLMULTITEXCOORD3FPROC glad_glMultiTexCoord3f; +#define glMultiTexCoord3f glad_glMultiTexCoord3f +typedef void (APIENTRYP PFNGLMULTITEXCOORD3FVPROC)(GLenum target, const GLfloat *v); +GLAPI PFNGLMULTITEXCOORD3FVPROC glad_glMultiTexCoord3fv; +#define glMultiTexCoord3fv glad_glMultiTexCoord3fv +typedef void (APIENTRYP PFNGLMULTITEXCOORD3IPROC)(GLenum target, GLint s, GLint t, GLint r); +GLAPI PFNGLMULTITEXCOORD3IPROC glad_glMultiTexCoord3i; +#define glMultiTexCoord3i glad_glMultiTexCoord3i +typedef void (APIENTRYP PFNGLMULTITEXCOORD3IVPROC)(GLenum target, const GLint *v); +GLAPI PFNGLMULTITEXCOORD3IVPROC glad_glMultiTexCoord3iv; +#define glMultiTexCoord3iv glad_glMultiTexCoord3iv +typedef void (APIENTRYP PFNGLMULTITEXCOORD3SPROC)(GLenum target, GLshort s, GLshort t, GLshort r); +GLAPI PFNGLMULTITEXCOORD3SPROC glad_glMultiTexCoord3s; +#define glMultiTexCoord3s glad_glMultiTexCoord3s +typedef void (APIENTRYP PFNGLMULTITEXCOORD3SVPROC)(GLenum target, const GLshort *v); +GLAPI PFNGLMULTITEXCOORD3SVPROC glad_glMultiTexCoord3sv; +#define glMultiTexCoord3sv glad_glMultiTexCoord3sv +typedef void (APIENTRYP PFNGLMULTITEXCOORD4DPROC)(GLenum target, GLdouble s, GLdouble t, GLdouble r, GLdouble q); +GLAPI PFNGLMULTITEXCOORD4DPROC glad_glMultiTexCoord4d; +#define glMultiTexCoord4d glad_glMultiTexCoord4d +typedef void (APIENTRYP PFNGLMULTITEXCOORD4DVPROC)(GLenum target, const GLdouble *v); +GLAPI PFNGLMULTITEXCOORD4DVPROC glad_glMultiTexCoord4dv; +#define glMultiTexCoord4dv glad_glMultiTexCoord4dv +typedef void (APIENTRYP PFNGLMULTITEXCOORD4FPROC)(GLenum target, GLfloat s, GLfloat t, GLfloat r, GLfloat q); +GLAPI PFNGLMULTITEXCOORD4FPROC glad_glMultiTexCoord4f; +#define glMultiTexCoord4f glad_glMultiTexCoord4f +typedef void (APIENTRYP PFNGLMULTITEXCOORD4FVPROC)(GLenum target, const GLfloat *v); +GLAPI PFNGLMULTITEXCOORD4FVPROC glad_glMultiTexCoord4fv; +#define glMultiTexCoord4fv glad_glMultiTexCoord4fv +typedef void (APIENTRYP PFNGLMULTITEXCOORD4IPROC)(GLenum target, GLint s, GLint t, GLint r, GLint q); +GLAPI PFNGLMULTITEXCOORD4IPROC glad_glMultiTexCoord4i; +#define glMultiTexCoord4i glad_glMultiTexCoord4i +typedef void (APIENTRYP PFNGLMULTITEXCOORD4IVPROC)(GLenum target, const GLint *v); +GLAPI PFNGLMULTITEXCOORD4IVPROC glad_glMultiTexCoord4iv; +#define glMultiTexCoord4iv glad_glMultiTexCoord4iv +typedef void (APIENTRYP PFNGLMULTITEXCOORD4SPROC)(GLenum target, GLshort s, GLshort t, GLshort r, GLshort q); +GLAPI PFNGLMULTITEXCOORD4SPROC glad_glMultiTexCoord4s; +#define glMultiTexCoord4s glad_glMultiTexCoord4s +typedef void (APIENTRYP PFNGLMULTITEXCOORD4SVPROC)(GLenum target, const GLshort *v); +GLAPI PFNGLMULTITEXCOORD4SVPROC glad_glMultiTexCoord4sv; +#define glMultiTexCoord4sv glad_glMultiTexCoord4sv +typedef void (APIENTRYP PFNGLLOADTRANSPOSEMATRIXFPROC)(const GLfloat *m); +GLAPI PFNGLLOADTRANSPOSEMATRIXFPROC glad_glLoadTransposeMatrixf; +#define glLoadTransposeMatrixf glad_glLoadTransposeMatrixf +typedef void (APIENTRYP PFNGLLOADTRANSPOSEMATRIXDPROC)(const GLdouble *m); +GLAPI PFNGLLOADTRANSPOSEMATRIXDPROC glad_glLoadTransposeMatrixd; +#define glLoadTransposeMatrixd glad_glLoadTransposeMatrixd +typedef void (APIENTRYP PFNGLMULTTRANSPOSEMATRIXFPROC)(const GLfloat *m); +GLAPI PFNGLMULTTRANSPOSEMATRIXFPROC glad_glMultTransposeMatrixf; +#define glMultTransposeMatrixf glad_glMultTransposeMatrixf +typedef void (APIENTRYP PFNGLMULTTRANSPOSEMATRIXDPROC)(const GLdouble *m); +GLAPI PFNGLMULTTRANSPOSEMATRIXDPROC glad_glMultTransposeMatrixd; +#define glMultTransposeMatrixd glad_glMultTransposeMatrixd +#endif +#ifndef GL_VERSION_1_4 +#define GL_VERSION_1_4 1 +GLAPI int GLAD_GL_VERSION_1_4; +typedef void (APIENTRYP PFNGLBLENDFUNCSEPARATEPROC)(GLenum sfactorRGB, GLenum dfactorRGB, GLenum sfactorAlpha, GLenum dfactorAlpha); +GLAPI PFNGLBLENDFUNCSEPARATEPROC glad_glBlendFuncSeparate; +#define glBlendFuncSeparate glad_glBlendFuncSeparate +typedef void (APIENTRYP PFNGLMULTIDRAWARRAYSPROC)(GLenum mode, const GLint *first, const GLsizei *count, GLsizei drawcount); +GLAPI PFNGLMULTIDRAWARRAYSPROC glad_glMultiDrawArrays; +#define glMultiDrawArrays glad_glMultiDrawArrays +typedef void (APIENTRYP PFNGLMULTIDRAWELEMENTSPROC)(GLenum mode, const GLsizei *count, GLenum type, const void *const*indices, GLsizei drawcount); +GLAPI PFNGLMULTIDRAWELEMENTSPROC glad_glMultiDrawElements; +#define glMultiDrawElements glad_glMultiDrawElements +typedef void (APIENTRYP PFNGLPOINTPARAMETERFPROC)(GLenum pname, GLfloat param); +GLAPI PFNGLPOINTPARAMETERFPROC glad_glPointParameterf; +#define glPointParameterf glad_glPointParameterf +typedef void (APIENTRYP PFNGLPOINTPARAMETERFVPROC)(GLenum pname, const GLfloat *params); +GLAPI PFNGLPOINTPARAMETERFVPROC glad_glPointParameterfv; +#define glPointParameterfv glad_glPointParameterfv +typedef void (APIENTRYP PFNGLPOINTPARAMETERIPROC)(GLenum pname, GLint param); +GLAPI PFNGLPOINTPARAMETERIPROC glad_glPointParameteri; +#define glPointParameteri glad_glPointParameteri +typedef void (APIENTRYP PFNGLPOINTPARAMETERIVPROC)(GLenum pname, const GLint *params); +GLAPI PFNGLPOINTPARAMETERIVPROC glad_glPointParameteriv; +#define glPointParameteriv glad_glPointParameteriv +typedef void (APIENTRYP PFNGLFOGCOORDFPROC)(GLfloat coord); +GLAPI PFNGLFOGCOORDFPROC glad_glFogCoordf; +#define glFogCoordf glad_glFogCoordf +typedef void (APIENTRYP PFNGLFOGCOORDFVPROC)(const GLfloat *coord); +GLAPI PFNGLFOGCOORDFVPROC glad_glFogCoordfv; +#define glFogCoordfv glad_glFogCoordfv +typedef void (APIENTRYP PFNGLFOGCOORDDPROC)(GLdouble coord); +GLAPI PFNGLFOGCOORDDPROC glad_glFogCoordd; +#define glFogCoordd glad_glFogCoordd +typedef void (APIENTRYP PFNGLFOGCOORDDVPROC)(const GLdouble *coord); +GLAPI PFNGLFOGCOORDDVPROC glad_glFogCoorddv; +#define glFogCoorddv glad_glFogCoorddv +typedef void (APIENTRYP PFNGLFOGCOORDPOINTERPROC)(GLenum type, GLsizei stride, const void *pointer); +GLAPI PFNGLFOGCOORDPOINTERPROC glad_glFogCoordPointer; +#define glFogCoordPointer glad_glFogCoordPointer +typedef void (APIENTRYP PFNGLSECONDARYCOLOR3BPROC)(GLbyte red, GLbyte green, GLbyte blue); +GLAPI PFNGLSECONDARYCOLOR3BPROC glad_glSecondaryColor3b; +#define glSecondaryColor3b glad_glSecondaryColor3b +typedef void (APIENTRYP PFNGLSECONDARYCOLOR3BVPROC)(const GLbyte *v); +GLAPI PFNGLSECONDARYCOLOR3BVPROC glad_glSecondaryColor3bv; +#define glSecondaryColor3bv glad_glSecondaryColor3bv +typedef void (APIENTRYP PFNGLSECONDARYCOLOR3DPROC)(GLdouble red, GLdouble green, GLdouble blue); +GLAPI PFNGLSECONDARYCOLOR3DPROC glad_glSecondaryColor3d; +#define glSecondaryColor3d glad_glSecondaryColor3d +typedef void (APIENTRYP PFNGLSECONDARYCOLOR3DVPROC)(const GLdouble *v); +GLAPI PFNGLSECONDARYCOLOR3DVPROC glad_glSecondaryColor3dv; +#define glSecondaryColor3dv glad_glSecondaryColor3dv +typedef void (APIENTRYP PFNGLSECONDARYCOLOR3FPROC)(GLfloat red, GLfloat green, GLfloat blue); +GLAPI PFNGLSECONDARYCOLOR3FPROC glad_glSecondaryColor3f; +#define glSecondaryColor3f glad_glSecondaryColor3f +typedef void (APIENTRYP PFNGLSECONDARYCOLOR3FVPROC)(const GLfloat *v); +GLAPI PFNGLSECONDARYCOLOR3FVPROC glad_glSecondaryColor3fv; +#define glSecondaryColor3fv glad_glSecondaryColor3fv +typedef void (APIENTRYP PFNGLSECONDARYCOLOR3IPROC)(GLint red, GLint green, GLint blue); +GLAPI PFNGLSECONDARYCOLOR3IPROC glad_glSecondaryColor3i; +#define glSecondaryColor3i glad_glSecondaryColor3i +typedef void (APIENTRYP PFNGLSECONDARYCOLOR3IVPROC)(const GLint *v); +GLAPI PFNGLSECONDARYCOLOR3IVPROC glad_glSecondaryColor3iv; +#define glSecondaryColor3iv glad_glSecondaryColor3iv +typedef void (APIENTRYP PFNGLSECONDARYCOLOR3SPROC)(GLshort red, GLshort green, GLshort blue); +GLAPI PFNGLSECONDARYCOLOR3SPROC glad_glSecondaryColor3s; +#define glSecondaryColor3s glad_glSecondaryColor3s +typedef void (APIENTRYP PFNGLSECONDARYCOLOR3SVPROC)(const GLshort *v); +GLAPI PFNGLSECONDARYCOLOR3SVPROC glad_glSecondaryColor3sv; +#define glSecondaryColor3sv glad_glSecondaryColor3sv +typedef void (APIENTRYP PFNGLSECONDARYCOLOR3UBPROC)(GLubyte red, GLubyte green, GLubyte blue); +GLAPI PFNGLSECONDARYCOLOR3UBPROC glad_glSecondaryColor3ub; +#define glSecondaryColor3ub glad_glSecondaryColor3ub +typedef void (APIENTRYP PFNGLSECONDARYCOLOR3UBVPROC)(const GLubyte *v); +GLAPI PFNGLSECONDARYCOLOR3UBVPROC glad_glSecondaryColor3ubv; +#define glSecondaryColor3ubv glad_glSecondaryColor3ubv +typedef void (APIENTRYP PFNGLSECONDARYCOLOR3UIPROC)(GLuint red, GLuint green, GLuint blue); +GLAPI PFNGLSECONDARYCOLOR3UIPROC glad_glSecondaryColor3ui; +#define glSecondaryColor3ui glad_glSecondaryColor3ui +typedef void (APIENTRYP PFNGLSECONDARYCOLOR3UIVPROC)(const GLuint *v); +GLAPI PFNGLSECONDARYCOLOR3UIVPROC glad_glSecondaryColor3uiv; +#define glSecondaryColor3uiv glad_glSecondaryColor3uiv +typedef void (APIENTRYP PFNGLSECONDARYCOLOR3USPROC)(GLushort red, GLushort green, GLushort blue); +GLAPI PFNGLSECONDARYCOLOR3USPROC glad_glSecondaryColor3us; +#define glSecondaryColor3us glad_glSecondaryColor3us +typedef void (APIENTRYP PFNGLSECONDARYCOLOR3USVPROC)(const GLushort *v); +GLAPI PFNGLSECONDARYCOLOR3USVPROC glad_glSecondaryColor3usv; +#define glSecondaryColor3usv glad_glSecondaryColor3usv +typedef void (APIENTRYP PFNGLSECONDARYCOLORPOINTERPROC)(GLint size, GLenum type, GLsizei stride, const void *pointer); +GLAPI PFNGLSECONDARYCOLORPOINTERPROC glad_glSecondaryColorPointer; +#define glSecondaryColorPointer glad_glSecondaryColorPointer +typedef void (APIENTRYP PFNGLWINDOWPOS2DPROC)(GLdouble x, GLdouble y); +GLAPI PFNGLWINDOWPOS2DPROC glad_glWindowPos2d; +#define glWindowPos2d glad_glWindowPos2d +typedef void (APIENTRYP PFNGLWINDOWPOS2DVPROC)(const GLdouble *v); +GLAPI PFNGLWINDOWPOS2DVPROC glad_glWindowPos2dv; +#define glWindowPos2dv glad_glWindowPos2dv +typedef void (APIENTRYP PFNGLWINDOWPOS2FPROC)(GLfloat x, GLfloat y); +GLAPI PFNGLWINDOWPOS2FPROC glad_glWindowPos2f; +#define glWindowPos2f glad_glWindowPos2f +typedef void (APIENTRYP PFNGLWINDOWPOS2FVPROC)(const GLfloat *v); +GLAPI PFNGLWINDOWPOS2FVPROC glad_glWindowPos2fv; +#define glWindowPos2fv glad_glWindowPos2fv +typedef void (APIENTRYP PFNGLWINDOWPOS2IPROC)(GLint x, GLint y); +GLAPI PFNGLWINDOWPOS2IPROC glad_glWindowPos2i; +#define glWindowPos2i glad_glWindowPos2i +typedef void (APIENTRYP PFNGLWINDOWPOS2IVPROC)(const GLint *v); +GLAPI PFNGLWINDOWPOS2IVPROC glad_glWindowPos2iv; +#define glWindowPos2iv glad_glWindowPos2iv +typedef void (APIENTRYP PFNGLWINDOWPOS2SPROC)(GLshort x, GLshort y); +GLAPI PFNGLWINDOWPOS2SPROC glad_glWindowPos2s; +#define glWindowPos2s glad_glWindowPos2s +typedef void (APIENTRYP PFNGLWINDOWPOS2SVPROC)(const GLshort *v); +GLAPI PFNGLWINDOWPOS2SVPROC glad_glWindowPos2sv; +#define glWindowPos2sv glad_glWindowPos2sv +typedef void (APIENTRYP PFNGLWINDOWPOS3DPROC)(GLdouble x, GLdouble y, GLdouble z); +GLAPI PFNGLWINDOWPOS3DPROC glad_glWindowPos3d; +#define glWindowPos3d glad_glWindowPos3d +typedef void (APIENTRYP PFNGLWINDOWPOS3DVPROC)(const GLdouble *v); +GLAPI PFNGLWINDOWPOS3DVPROC glad_glWindowPos3dv; +#define glWindowPos3dv glad_glWindowPos3dv +typedef void (APIENTRYP PFNGLWINDOWPOS3FPROC)(GLfloat x, GLfloat y, GLfloat z); +GLAPI PFNGLWINDOWPOS3FPROC glad_glWindowPos3f; +#define glWindowPos3f glad_glWindowPos3f +typedef void (APIENTRYP PFNGLWINDOWPOS3FVPROC)(const GLfloat *v); +GLAPI PFNGLWINDOWPOS3FVPROC glad_glWindowPos3fv; +#define glWindowPos3fv glad_glWindowPos3fv +typedef void (APIENTRYP PFNGLWINDOWPOS3IPROC)(GLint x, GLint y, GLint z); +GLAPI PFNGLWINDOWPOS3IPROC glad_glWindowPos3i; +#define glWindowPos3i glad_glWindowPos3i +typedef void (APIENTRYP PFNGLWINDOWPOS3IVPROC)(const GLint *v); +GLAPI PFNGLWINDOWPOS3IVPROC glad_glWindowPos3iv; +#define glWindowPos3iv glad_glWindowPos3iv +typedef void (APIENTRYP PFNGLWINDOWPOS3SPROC)(GLshort x, GLshort y, GLshort z); +GLAPI PFNGLWINDOWPOS3SPROC glad_glWindowPos3s; +#define glWindowPos3s glad_glWindowPos3s +typedef void (APIENTRYP PFNGLWINDOWPOS3SVPROC)(const GLshort *v); +GLAPI PFNGLWINDOWPOS3SVPROC glad_glWindowPos3sv; +#define glWindowPos3sv glad_glWindowPos3sv +typedef void (APIENTRYP PFNGLBLENDCOLORPROC)(GLfloat red, GLfloat green, GLfloat blue, GLfloat alpha); +GLAPI PFNGLBLENDCOLORPROC glad_glBlendColor; +#define glBlendColor glad_glBlendColor +typedef void (APIENTRYP PFNGLBLENDEQUATIONPROC)(GLenum mode); +GLAPI PFNGLBLENDEQUATIONPROC glad_glBlendEquation; +#define glBlendEquation glad_glBlendEquation +#endif +#ifndef GL_VERSION_1_5 +#define GL_VERSION_1_5 1 +GLAPI int GLAD_GL_VERSION_1_5; +typedef void (APIENTRYP PFNGLGENQUERIESPROC)(GLsizei n, GLuint *ids); +GLAPI PFNGLGENQUERIESPROC glad_glGenQueries; +#define glGenQueries glad_glGenQueries +typedef void (APIENTRYP PFNGLDELETEQUERIESPROC)(GLsizei n, const GLuint *ids); +GLAPI PFNGLDELETEQUERIESPROC glad_glDeleteQueries; +#define glDeleteQueries glad_glDeleteQueries +typedef GLboolean (APIENTRYP PFNGLISQUERYPROC)(GLuint id); +GLAPI PFNGLISQUERYPROC glad_glIsQuery; +#define glIsQuery glad_glIsQuery +typedef void (APIENTRYP PFNGLBEGINQUERYPROC)(GLenum target, GLuint id); +GLAPI PFNGLBEGINQUERYPROC glad_glBeginQuery; +#define glBeginQuery glad_glBeginQuery +typedef void (APIENTRYP PFNGLENDQUERYPROC)(GLenum target); +GLAPI PFNGLENDQUERYPROC glad_glEndQuery; +#define glEndQuery glad_glEndQuery +typedef void (APIENTRYP PFNGLGETQUERYIVPROC)(GLenum target, GLenum pname, GLint *params); +GLAPI PFNGLGETQUERYIVPROC glad_glGetQueryiv; +#define glGetQueryiv glad_glGetQueryiv +typedef void (APIENTRYP PFNGLGETQUERYOBJECTIVPROC)(GLuint id, GLenum pname, GLint *params); +GLAPI PFNGLGETQUERYOBJECTIVPROC glad_glGetQueryObjectiv; +#define glGetQueryObjectiv glad_glGetQueryObjectiv +typedef void (APIENTRYP PFNGLGETQUERYOBJECTUIVPROC)(GLuint id, GLenum pname, GLuint *params); +GLAPI PFNGLGETQUERYOBJECTUIVPROC glad_glGetQueryObjectuiv; +#define glGetQueryObjectuiv glad_glGetQueryObjectuiv +typedef void (APIENTRYP PFNGLBINDBUFFERPROC)(GLenum target, GLuint buffer); +GLAPI PFNGLBINDBUFFERPROC glad_glBindBuffer; +#define glBindBuffer glad_glBindBuffer +typedef void (APIENTRYP PFNGLDELETEBUFFERSPROC)(GLsizei n, const GLuint *buffers); +GLAPI PFNGLDELETEBUFFERSPROC glad_glDeleteBuffers; +#define glDeleteBuffers glad_glDeleteBuffers +typedef void (APIENTRYP PFNGLGENBUFFERSPROC)(GLsizei n, GLuint *buffers); +GLAPI PFNGLGENBUFFERSPROC glad_glGenBuffers; +#define glGenBuffers glad_glGenBuffers +typedef GLboolean (APIENTRYP PFNGLISBUFFERPROC)(GLuint buffer); +GLAPI PFNGLISBUFFERPROC glad_glIsBuffer; +#define glIsBuffer glad_glIsBuffer +typedef void (APIENTRYP PFNGLBUFFERDATAPROC)(GLenum target, GLsizeiptr size, const void *data, GLenum usage); +GLAPI PFNGLBUFFERDATAPROC glad_glBufferData; +#define glBufferData glad_glBufferData +typedef void (APIENTRYP PFNGLBUFFERSUBDATAPROC)(GLenum target, GLintptr offset, GLsizeiptr size, const void *data); +GLAPI PFNGLBUFFERSUBDATAPROC glad_glBufferSubData; +#define glBufferSubData glad_glBufferSubData +typedef void (APIENTRYP PFNGLGETBUFFERSUBDATAPROC)(GLenum target, GLintptr offset, GLsizeiptr size, void *data); +GLAPI PFNGLGETBUFFERSUBDATAPROC glad_glGetBufferSubData; +#define glGetBufferSubData glad_glGetBufferSubData +typedef void * (APIENTRYP PFNGLMAPBUFFERPROC)(GLenum target, GLenum access); +GLAPI PFNGLMAPBUFFERPROC glad_glMapBuffer; +#define glMapBuffer glad_glMapBuffer +typedef GLboolean (APIENTRYP PFNGLUNMAPBUFFERPROC)(GLenum target); +GLAPI PFNGLUNMAPBUFFERPROC glad_glUnmapBuffer; +#define glUnmapBuffer glad_glUnmapBuffer +typedef void (APIENTRYP PFNGLGETBUFFERPARAMETERIVPROC)(GLenum target, GLenum pname, GLint *params); +GLAPI PFNGLGETBUFFERPARAMETERIVPROC glad_glGetBufferParameteriv; +#define glGetBufferParameteriv glad_glGetBufferParameteriv +typedef void (APIENTRYP PFNGLGETBUFFERPOINTERVPROC)(GLenum target, GLenum pname, void **params); +GLAPI PFNGLGETBUFFERPOINTERVPROC glad_glGetBufferPointerv; +#define glGetBufferPointerv glad_glGetBufferPointerv +#endif +#ifndef GL_VERSION_2_0 +#define GL_VERSION_2_0 1 +GLAPI int GLAD_GL_VERSION_2_0; +typedef void (APIENTRYP PFNGLBLENDEQUATIONSEPARATEPROC)(GLenum modeRGB, GLenum modeAlpha); +GLAPI PFNGLBLENDEQUATIONSEPARATEPROC glad_glBlendEquationSeparate; +#define glBlendEquationSeparate glad_glBlendEquationSeparate +typedef void (APIENTRYP PFNGLDRAWBUFFERSPROC)(GLsizei n, const GLenum *bufs); +GLAPI PFNGLDRAWBUFFERSPROC glad_glDrawBuffers; +#define glDrawBuffers glad_glDrawBuffers +typedef void (APIENTRYP PFNGLSTENCILOPSEPARATEPROC)(GLenum face, GLenum sfail, GLenum dpfail, GLenum dppass); +GLAPI PFNGLSTENCILOPSEPARATEPROC glad_glStencilOpSeparate; +#define glStencilOpSeparate glad_glStencilOpSeparate +typedef void (APIENTRYP PFNGLSTENCILFUNCSEPARATEPROC)(GLenum face, GLenum func, GLint ref, GLuint mask); +GLAPI PFNGLSTENCILFUNCSEPARATEPROC glad_glStencilFuncSeparate; +#define glStencilFuncSeparate glad_glStencilFuncSeparate +typedef void (APIENTRYP PFNGLSTENCILMASKSEPARATEPROC)(GLenum face, GLuint mask); +GLAPI PFNGLSTENCILMASKSEPARATEPROC glad_glStencilMaskSeparate; +#define glStencilMaskSeparate glad_glStencilMaskSeparate +typedef void (APIENTRYP PFNGLATTACHSHADERPROC)(GLuint program, GLuint shader); +GLAPI PFNGLATTACHSHADERPROC glad_glAttachShader; +#define glAttachShader glad_glAttachShader +typedef void (APIENTRYP PFNGLBINDATTRIBLOCATIONPROC)(GLuint program, GLuint index, const GLchar *name); +GLAPI PFNGLBINDATTRIBLOCATIONPROC glad_glBindAttribLocation; +#define glBindAttribLocation glad_glBindAttribLocation +typedef void (APIENTRYP PFNGLCOMPILESHADERPROC)(GLuint shader); +GLAPI PFNGLCOMPILESHADERPROC glad_glCompileShader; +#define glCompileShader glad_glCompileShader +typedef GLuint (APIENTRYP PFNGLCREATEPROGRAMPROC)(void); +GLAPI PFNGLCREATEPROGRAMPROC glad_glCreateProgram; +#define glCreateProgram glad_glCreateProgram +typedef GLuint (APIENTRYP PFNGLCREATESHADERPROC)(GLenum type); +GLAPI PFNGLCREATESHADERPROC glad_glCreateShader; +#define glCreateShader glad_glCreateShader +typedef void (APIENTRYP PFNGLDELETEPROGRAMPROC)(GLuint program); +GLAPI PFNGLDELETEPROGRAMPROC glad_glDeleteProgram; +#define glDeleteProgram glad_glDeleteProgram +typedef void (APIENTRYP PFNGLDELETESHADERPROC)(GLuint shader); +GLAPI PFNGLDELETESHADERPROC glad_glDeleteShader; +#define glDeleteShader glad_glDeleteShader +typedef void (APIENTRYP PFNGLDETACHSHADERPROC)(GLuint program, GLuint shader); +GLAPI PFNGLDETACHSHADERPROC glad_glDetachShader; +#define glDetachShader glad_glDetachShader +typedef void (APIENTRYP PFNGLDISABLEVERTEXATTRIBARRAYPROC)(GLuint index); +GLAPI PFNGLDISABLEVERTEXATTRIBARRAYPROC glad_glDisableVertexAttribArray; +#define glDisableVertexAttribArray glad_glDisableVertexAttribArray +typedef void (APIENTRYP PFNGLENABLEVERTEXATTRIBARRAYPROC)(GLuint index); +GLAPI PFNGLENABLEVERTEXATTRIBARRAYPROC glad_glEnableVertexAttribArray; +#define glEnableVertexAttribArray glad_glEnableVertexAttribArray +typedef void (APIENTRYP PFNGLGETACTIVEATTRIBPROC)(GLuint program, GLuint index, GLsizei bufSize, GLsizei *length, GLint *size, GLenum *type, GLchar *name); +GLAPI PFNGLGETACTIVEATTRIBPROC glad_glGetActiveAttrib; +#define glGetActiveAttrib glad_glGetActiveAttrib +typedef void (APIENTRYP PFNGLGETACTIVEUNIFORMPROC)(GLuint program, GLuint index, GLsizei bufSize, GLsizei *length, GLint *size, GLenum *type, GLchar *name); +GLAPI PFNGLGETACTIVEUNIFORMPROC glad_glGetActiveUniform; +#define glGetActiveUniform glad_glGetActiveUniform +typedef void (APIENTRYP PFNGLGETATTACHEDSHADERSPROC)(GLuint program, GLsizei maxCount, GLsizei *count, GLuint *shaders); +GLAPI PFNGLGETATTACHEDSHADERSPROC glad_glGetAttachedShaders; +#define glGetAttachedShaders glad_glGetAttachedShaders +typedef GLint (APIENTRYP PFNGLGETATTRIBLOCATIONPROC)(GLuint program, const GLchar *name); +GLAPI PFNGLGETATTRIBLOCATIONPROC glad_glGetAttribLocation; +#define glGetAttribLocation glad_glGetAttribLocation +typedef void (APIENTRYP PFNGLGETPROGRAMIVPROC)(GLuint program, GLenum pname, GLint *params); +GLAPI PFNGLGETPROGRAMIVPROC glad_glGetProgramiv; +#define glGetProgramiv glad_glGetProgramiv +typedef void (APIENTRYP PFNGLGETPROGRAMINFOLOGPROC)(GLuint program, GLsizei bufSize, GLsizei *length, GLchar *infoLog); +GLAPI PFNGLGETPROGRAMINFOLOGPROC glad_glGetProgramInfoLog; +#define glGetProgramInfoLog glad_glGetProgramInfoLog +typedef void (APIENTRYP PFNGLGETSHADERIVPROC)(GLuint shader, GLenum pname, GLint *params); +GLAPI PFNGLGETSHADERIVPROC glad_glGetShaderiv; +#define glGetShaderiv glad_glGetShaderiv +typedef void (APIENTRYP PFNGLGETSHADERINFOLOGPROC)(GLuint shader, GLsizei bufSize, GLsizei *length, GLchar *infoLog); +GLAPI PFNGLGETSHADERINFOLOGPROC glad_glGetShaderInfoLog; +#define glGetShaderInfoLog glad_glGetShaderInfoLog +typedef void (APIENTRYP PFNGLGETSHADERSOURCEPROC)(GLuint shader, GLsizei bufSize, GLsizei *length, GLchar *source); +GLAPI PFNGLGETSHADERSOURCEPROC glad_glGetShaderSource; +#define glGetShaderSource glad_glGetShaderSource +typedef GLint (APIENTRYP PFNGLGETUNIFORMLOCATIONPROC)(GLuint program, const GLchar *name); +GLAPI PFNGLGETUNIFORMLOCATIONPROC glad_glGetUniformLocation; +#define glGetUniformLocation glad_glGetUniformLocation +typedef void (APIENTRYP PFNGLGETUNIFORMFVPROC)(GLuint program, GLint location, GLfloat *params); +GLAPI PFNGLGETUNIFORMFVPROC glad_glGetUniformfv; +#define glGetUniformfv glad_glGetUniformfv +typedef void (APIENTRYP PFNGLGETUNIFORMIVPROC)(GLuint program, GLint location, GLint *params); +GLAPI PFNGLGETUNIFORMIVPROC glad_glGetUniformiv; +#define glGetUniformiv glad_glGetUniformiv +typedef void (APIENTRYP PFNGLGETVERTEXATTRIBDVPROC)(GLuint index, GLenum pname, GLdouble *params); +GLAPI PFNGLGETVERTEXATTRIBDVPROC glad_glGetVertexAttribdv; +#define glGetVertexAttribdv glad_glGetVertexAttribdv +typedef void (APIENTRYP PFNGLGETVERTEXATTRIBFVPROC)(GLuint index, GLenum pname, GLfloat *params); +GLAPI PFNGLGETVERTEXATTRIBFVPROC glad_glGetVertexAttribfv; +#define glGetVertexAttribfv glad_glGetVertexAttribfv +typedef void (APIENTRYP PFNGLGETVERTEXATTRIBIVPROC)(GLuint index, GLenum pname, GLint *params); +GLAPI PFNGLGETVERTEXATTRIBIVPROC glad_glGetVertexAttribiv; +#define glGetVertexAttribiv glad_glGetVertexAttribiv +typedef void (APIENTRYP PFNGLGETVERTEXATTRIBPOINTERVPROC)(GLuint index, GLenum pname, void **pointer); +GLAPI PFNGLGETVERTEXATTRIBPOINTERVPROC glad_glGetVertexAttribPointerv; +#define glGetVertexAttribPointerv glad_glGetVertexAttribPointerv +typedef GLboolean (APIENTRYP PFNGLISPROGRAMPROC)(GLuint program); +GLAPI PFNGLISPROGRAMPROC glad_glIsProgram; +#define glIsProgram glad_glIsProgram +typedef GLboolean (APIENTRYP PFNGLISSHADERPROC)(GLuint shader); +GLAPI PFNGLISSHADERPROC glad_glIsShader; +#define glIsShader glad_glIsShader +typedef void (APIENTRYP PFNGLLINKPROGRAMPROC)(GLuint program); +GLAPI PFNGLLINKPROGRAMPROC glad_glLinkProgram; +#define glLinkProgram glad_glLinkProgram +typedef void (APIENTRYP PFNGLSHADERSOURCEPROC)(GLuint shader, GLsizei count, const GLchar *const*string, const GLint *length); +GLAPI PFNGLSHADERSOURCEPROC glad_glShaderSource; +#define glShaderSource glad_glShaderSource +typedef void (APIENTRYP PFNGLUSEPROGRAMPROC)(GLuint program); +GLAPI PFNGLUSEPROGRAMPROC glad_glUseProgram; +#define glUseProgram glad_glUseProgram +typedef void (APIENTRYP PFNGLUNIFORM1FPROC)(GLint location, GLfloat v0); +GLAPI PFNGLUNIFORM1FPROC glad_glUniform1f; +#define glUniform1f glad_glUniform1f +typedef void (APIENTRYP PFNGLUNIFORM2FPROC)(GLint location, GLfloat v0, GLfloat v1); +GLAPI PFNGLUNIFORM2FPROC glad_glUniform2f; +#define glUniform2f glad_glUniform2f +typedef void (APIENTRYP PFNGLUNIFORM3FPROC)(GLint location, GLfloat v0, GLfloat v1, GLfloat v2); +GLAPI PFNGLUNIFORM3FPROC glad_glUniform3f; +#define glUniform3f glad_glUniform3f +typedef void (APIENTRYP PFNGLUNIFORM4FPROC)(GLint location, GLfloat v0, GLfloat v1, GLfloat v2, GLfloat v3); +GLAPI PFNGLUNIFORM4FPROC glad_glUniform4f; +#define glUniform4f glad_glUniform4f +typedef void (APIENTRYP PFNGLUNIFORM1IPROC)(GLint location, GLint v0); +GLAPI PFNGLUNIFORM1IPROC glad_glUniform1i; +#define glUniform1i glad_glUniform1i +typedef void (APIENTRYP PFNGLUNIFORM2IPROC)(GLint location, GLint v0, GLint v1); +GLAPI PFNGLUNIFORM2IPROC glad_glUniform2i; +#define glUniform2i glad_glUniform2i +typedef void (APIENTRYP PFNGLUNIFORM3IPROC)(GLint location, GLint v0, GLint v1, GLint v2); +GLAPI PFNGLUNIFORM3IPROC glad_glUniform3i; +#define glUniform3i glad_glUniform3i +typedef void (APIENTRYP PFNGLUNIFORM4IPROC)(GLint location, GLint v0, GLint v1, GLint v2, GLint v3); +GLAPI PFNGLUNIFORM4IPROC glad_glUniform4i; +#define glUniform4i glad_glUniform4i +typedef void (APIENTRYP PFNGLUNIFORM1FVPROC)(GLint location, GLsizei count, const GLfloat *value); +GLAPI PFNGLUNIFORM1FVPROC glad_glUniform1fv; +#define glUniform1fv glad_glUniform1fv +typedef void (APIENTRYP PFNGLUNIFORM2FVPROC)(GLint location, GLsizei count, const GLfloat *value); +GLAPI PFNGLUNIFORM2FVPROC glad_glUniform2fv; +#define glUniform2fv glad_glUniform2fv +typedef void (APIENTRYP PFNGLUNIFORM3FVPROC)(GLint location, GLsizei count, const GLfloat *value); +GLAPI PFNGLUNIFORM3FVPROC glad_glUniform3fv; +#define glUniform3fv glad_glUniform3fv +typedef void (APIENTRYP PFNGLUNIFORM4FVPROC)(GLint location, GLsizei count, const GLfloat *value); +GLAPI PFNGLUNIFORM4FVPROC glad_glUniform4fv; +#define glUniform4fv glad_glUniform4fv +typedef void (APIENTRYP PFNGLUNIFORM1IVPROC)(GLint location, GLsizei count, const GLint *value); +GLAPI PFNGLUNIFORM1IVPROC glad_glUniform1iv; +#define glUniform1iv glad_glUniform1iv +typedef void (APIENTRYP PFNGLUNIFORM2IVPROC)(GLint location, GLsizei count, const GLint *value); +GLAPI PFNGLUNIFORM2IVPROC glad_glUniform2iv; +#define glUniform2iv glad_glUniform2iv +typedef void (APIENTRYP PFNGLUNIFORM3IVPROC)(GLint location, GLsizei count, const GLint *value); +GLAPI PFNGLUNIFORM3IVPROC glad_glUniform3iv; +#define glUniform3iv glad_glUniform3iv +typedef void (APIENTRYP PFNGLUNIFORM4IVPROC)(GLint location, GLsizei count, const GLint *value); +GLAPI PFNGLUNIFORM4IVPROC glad_glUniform4iv; +#define glUniform4iv glad_glUniform4iv +typedef void (APIENTRYP PFNGLUNIFORMMATRIX2FVPROC)(GLint location, GLsizei count, GLboolean transpose, const GLfloat *value); +GLAPI PFNGLUNIFORMMATRIX2FVPROC glad_glUniformMatrix2fv; +#define glUniformMatrix2fv glad_glUniformMatrix2fv +typedef void (APIENTRYP PFNGLUNIFORMMATRIX3FVPROC)(GLint location, GLsizei count, GLboolean transpose, const GLfloat *value); +GLAPI PFNGLUNIFORMMATRIX3FVPROC glad_glUniformMatrix3fv; +#define glUniformMatrix3fv glad_glUniformMatrix3fv +typedef void (APIENTRYP PFNGLUNIFORMMATRIX4FVPROC)(GLint location, GLsizei count, GLboolean transpose, const GLfloat *value); +GLAPI PFNGLUNIFORMMATRIX4FVPROC glad_glUniformMatrix4fv; +#define glUniformMatrix4fv glad_glUniformMatrix4fv +typedef void (APIENTRYP PFNGLVALIDATEPROGRAMPROC)(GLuint program); +GLAPI PFNGLVALIDATEPROGRAMPROC glad_glValidateProgram; +#define glValidateProgram glad_glValidateProgram +typedef void (APIENTRYP PFNGLVERTEXATTRIB1DPROC)(GLuint index, GLdouble x); +GLAPI PFNGLVERTEXATTRIB1DPROC glad_glVertexAttrib1d; +#define glVertexAttrib1d glad_glVertexAttrib1d +typedef void (APIENTRYP PFNGLVERTEXATTRIB1DVPROC)(GLuint index, const GLdouble *v); +GLAPI PFNGLVERTEXATTRIB1DVPROC glad_glVertexAttrib1dv; +#define glVertexAttrib1dv glad_glVertexAttrib1dv +typedef void (APIENTRYP PFNGLVERTEXATTRIB1FPROC)(GLuint index, GLfloat x); +GLAPI PFNGLVERTEXATTRIB1FPROC glad_glVertexAttrib1f; +#define glVertexAttrib1f glad_glVertexAttrib1f +typedef void (APIENTRYP PFNGLVERTEXATTRIB1FVPROC)(GLuint index, const GLfloat *v); +GLAPI PFNGLVERTEXATTRIB1FVPROC glad_glVertexAttrib1fv; +#define glVertexAttrib1fv glad_glVertexAttrib1fv +typedef void (APIENTRYP PFNGLVERTEXATTRIB1SPROC)(GLuint index, GLshort x); +GLAPI PFNGLVERTEXATTRIB1SPROC glad_glVertexAttrib1s; +#define glVertexAttrib1s glad_glVertexAttrib1s +typedef void (APIENTRYP PFNGLVERTEXATTRIB1SVPROC)(GLuint index, const GLshort *v); +GLAPI PFNGLVERTEXATTRIB1SVPROC glad_glVertexAttrib1sv; +#define glVertexAttrib1sv glad_glVertexAttrib1sv +typedef void (APIENTRYP PFNGLVERTEXATTRIB2DPROC)(GLuint index, GLdouble x, GLdouble y); +GLAPI PFNGLVERTEXATTRIB2DPROC glad_glVertexAttrib2d; +#define glVertexAttrib2d glad_glVertexAttrib2d +typedef void (APIENTRYP PFNGLVERTEXATTRIB2DVPROC)(GLuint index, const GLdouble *v); +GLAPI PFNGLVERTEXATTRIB2DVPROC glad_glVertexAttrib2dv; +#define glVertexAttrib2dv glad_glVertexAttrib2dv +typedef void (APIENTRYP PFNGLVERTEXATTRIB2FPROC)(GLuint index, GLfloat x, GLfloat y); +GLAPI PFNGLVERTEXATTRIB2FPROC glad_glVertexAttrib2f; +#define glVertexAttrib2f glad_glVertexAttrib2f +typedef void (APIENTRYP PFNGLVERTEXATTRIB2FVPROC)(GLuint index, const GLfloat *v); +GLAPI PFNGLVERTEXATTRIB2FVPROC glad_glVertexAttrib2fv; +#define glVertexAttrib2fv glad_glVertexAttrib2fv +typedef void (APIENTRYP PFNGLVERTEXATTRIB2SPROC)(GLuint index, GLshort x, GLshort y); +GLAPI PFNGLVERTEXATTRIB2SPROC glad_glVertexAttrib2s; +#define glVertexAttrib2s glad_glVertexAttrib2s +typedef void (APIENTRYP PFNGLVERTEXATTRIB2SVPROC)(GLuint index, const GLshort *v); +GLAPI PFNGLVERTEXATTRIB2SVPROC glad_glVertexAttrib2sv; +#define glVertexAttrib2sv glad_glVertexAttrib2sv +typedef void (APIENTRYP PFNGLVERTEXATTRIB3DPROC)(GLuint index, GLdouble x, GLdouble y, GLdouble z); +GLAPI PFNGLVERTEXATTRIB3DPROC glad_glVertexAttrib3d; +#define glVertexAttrib3d glad_glVertexAttrib3d +typedef void (APIENTRYP PFNGLVERTEXATTRIB3DVPROC)(GLuint index, const GLdouble *v); +GLAPI PFNGLVERTEXATTRIB3DVPROC glad_glVertexAttrib3dv; +#define glVertexAttrib3dv glad_glVertexAttrib3dv +typedef void (APIENTRYP PFNGLVERTEXATTRIB3FPROC)(GLuint index, GLfloat x, GLfloat y, GLfloat z); +GLAPI PFNGLVERTEXATTRIB3FPROC glad_glVertexAttrib3f; +#define glVertexAttrib3f glad_glVertexAttrib3f +typedef void (APIENTRYP PFNGLVERTEXATTRIB3FVPROC)(GLuint index, const GLfloat *v); +GLAPI PFNGLVERTEXATTRIB3FVPROC glad_glVertexAttrib3fv; +#define glVertexAttrib3fv glad_glVertexAttrib3fv +typedef void (APIENTRYP PFNGLVERTEXATTRIB3SPROC)(GLuint index, GLshort x, GLshort y, GLshort z); +GLAPI PFNGLVERTEXATTRIB3SPROC glad_glVertexAttrib3s; +#define glVertexAttrib3s glad_glVertexAttrib3s +typedef void (APIENTRYP PFNGLVERTEXATTRIB3SVPROC)(GLuint index, const GLshort *v); +GLAPI PFNGLVERTEXATTRIB3SVPROC glad_glVertexAttrib3sv; +#define glVertexAttrib3sv glad_glVertexAttrib3sv +typedef void (APIENTRYP PFNGLVERTEXATTRIB4NBVPROC)(GLuint index, const GLbyte *v); +GLAPI PFNGLVERTEXATTRIB4NBVPROC glad_glVertexAttrib4Nbv; +#define glVertexAttrib4Nbv glad_glVertexAttrib4Nbv +typedef void (APIENTRYP PFNGLVERTEXATTRIB4NIVPROC)(GLuint index, const GLint *v); +GLAPI PFNGLVERTEXATTRIB4NIVPROC glad_glVertexAttrib4Niv; +#define glVertexAttrib4Niv glad_glVertexAttrib4Niv +typedef void (APIENTRYP PFNGLVERTEXATTRIB4NSVPROC)(GLuint index, const GLshort *v); +GLAPI PFNGLVERTEXATTRIB4NSVPROC glad_glVertexAttrib4Nsv; +#define glVertexAttrib4Nsv glad_glVertexAttrib4Nsv +typedef void (APIENTRYP PFNGLVERTEXATTRIB4NUBPROC)(GLuint index, GLubyte x, GLubyte y, GLubyte z, GLubyte w); +GLAPI PFNGLVERTEXATTRIB4NUBPROC glad_glVertexAttrib4Nub; +#define glVertexAttrib4Nub glad_glVertexAttrib4Nub +typedef void (APIENTRYP PFNGLVERTEXATTRIB4NUBVPROC)(GLuint index, const GLubyte *v); +GLAPI PFNGLVERTEXATTRIB4NUBVPROC glad_glVertexAttrib4Nubv; +#define glVertexAttrib4Nubv glad_glVertexAttrib4Nubv +typedef void (APIENTRYP PFNGLVERTEXATTRIB4NUIVPROC)(GLuint index, const GLuint *v); +GLAPI PFNGLVERTEXATTRIB4NUIVPROC glad_glVertexAttrib4Nuiv; +#define glVertexAttrib4Nuiv glad_glVertexAttrib4Nuiv +typedef void (APIENTRYP PFNGLVERTEXATTRIB4NUSVPROC)(GLuint index, const GLushort *v); +GLAPI PFNGLVERTEXATTRIB4NUSVPROC glad_glVertexAttrib4Nusv; +#define glVertexAttrib4Nusv glad_glVertexAttrib4Nusv +typedef void (APIENTRYP PFNGLVERTEXATTRIB4BVPROC)(GLuint index, const GLbyte *v); +GLAPI PFNGLVERTEXATTRIB4BVPROC glad_glVertexAttrib4bv; +#define glVertexAttrib4bv glad_glVertexAttrib4bv +typedef void (APIENTRYP PFNGLVERTEXATTRIB4DPROC)(GLuint index, GLdouble x, GLdouble y, GLdouble z, GLdouble w); +GLAPI PFNGLVERTEXATTRIB4DPROC glad_glVertexAttrib4d; +#define glVertexAttrib4d glad_glVertexAttrib4d +typedef void (APIENTRYP PFNGLVERTEXATTRIB4DVPROC)(GLuint index, const GLdouble *v); +GLAPI PFNGLVERTEXATTRIB4DVPROC glad_glVertexAttrib4dv; +#define glVertexAttrib4dv glad_glVertexAttrib4dv +typedef void (APIENTRYP PFNGLVERTEXATTRIB4FPROC)(GLuint index, GLfloat x, GLfloat y, GLfloat z, GLfloat w); +GLAPI PFNGLVERTEXATTRIB4FPROC glad_glVertexAttrib4f; +#define glVertexAttrib4f glad_glVertexAttrib4f +typedef void (APIENTRYP PFNGLVERTEXATTRIB4FVPROC)(GLuint index, const GLfloat *v); +GLAPI PFNGLVERTEXATTRIB4FVPROC glad_glVertexAttrib4fv; +#define glVertexAttrib4fv glad_glVertexAttrib4fv +typedef void (APIENTRYP PFNGLVERTEXATTRIB4IVPROC)(GLuint index, const GLint *v); +GLAPI PFNGLVERTEXATTRIB4IVPROC glad_glVertexAttrib4iv; +#define glVertexAttrib4iv glad_glVertexAttrib4iv +typedef void (APIENTRYP PFNGLVERTEXATTRIB4SPROC)(GLuint index, GLshort x, GLshort y, GLshort z, GLshort w); +GLAPI PFNGLVERTEXATTRIB4SPROC glad_glVertexAttrib4s; +#define glVertexAttrib4s glad_glVertexAttrib4s +typedef void (APIENTRYP PFNGLVERTEXATTRIB4SVPROC)(GLuint index, const GLshort *v); +GLAPI PFNGLVERTEXATTRIB4SVPROC glad_glVertexAttrib4sv; +#define glVertexAttrib4sv glad_glVertexAttrib4sv +typedef void (APIENTRYP PFNGLVERTEXATTRIB4UBVPROC)(GLuint index, const GLubyte *v); +GLAPI PFNGLVERTEXATTRIB4UBVPROC glad_glVertexAttrib4ubv; +#define glVertexAttrib4ubv glad_glVertexAttrib4ubv +typedef void (APIENTRYP PFNGLVERTEXATTRIB4UIVPROC)(GLuint index, const GLuint *v); +GLAPI PFNGLVERTEXATTRIB4UIVPROC glad_glVertexAttrib4uiv; +#define glVertexAttrib4uiv glad_glVertexAttrib4uiv +typedef void (APIENTRYP PFNGLVERTEXATTRIB4USVPROC)(GLuint index, const GLushort *v); +GLAPI PFNGLVERTEXATTRIB4USVPROC glad_glVertexAttrib4usv; +#define glVertexAttrib4usv glad_glVertexAttrib4usv +typedef void (APIENTRYP PFNGLVERTEXATTRIBPOINTERPROC)(GLuint index, GLint size, GLenum type, GLboolean normalized, GLsizei stride, const void *pointer); +GLAPI PFNGLVERTEXATTRIBPOINTERPROC glad_glVertexAttribPointer; +#define glVertexAttribPointer glad_glVertexAttribPointer +#endif + +#ifdef __cplusplus +} +#endif + +#endif diff --git a/tcod_sys/libtcod/src/vendor/khrplatform.h b/tcod_sys/libtcod/src/vendor/khrplatform.h new file mode 100644 index 000000000..975bbffed --- /dev/null +++ b/tcod_sys/libtcod/src/vendor/khrplatform.h @@ -0,0 +1,282 @@ +#ifndef __khrplatform_h_ +#define __khrplatform_h_ + +/* +** Copyright (c) 2008-2018 The Khronos Group Inc. +** +** Permission is hereby granted, free of charge, to any person obtaining a +** copy of this software and/or associated documentation files (the +** "Materials"), to deal in the Materials without restriction, including +** without limitation the rights to use, copy, modify, merge, publish, +** distribute, sublicense, and/or sell copies of the Materials, and to +** permit persons to whom the Materials are furnished to do so, subject to +** the following conditions: +** +** The above copyright notice and this permission notice shall be included +** in all copies or substantial portions of the Materials. +** +** THE MATERIALS ARE PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, +** EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +** MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. +** IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY +** CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, +** TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE +** MATERIALS OR THE USE OR OTHER DEALINGS IN THE MATERIALS. +*/ + +/* Khronos platform-specific types and definitions. + * + * The master copy of khrplatform.h is maintained in the Khronos EGL + * Registry repository at https://github.com/KhronosGroup/EGL-Registry + * The last semantic modification to khrplatform.h was at commit ID: + * 67a3e0864c2d75ea5287b9f3d2eb74a745936692 + * + * Adopters may modify this file to suit their platform. Adopters are + * encouraged to submit platform specific modifications to the Khronos + * group so that they can be included in future versions of this file. + * Please submit changes by filing pull requests or issues on + * the EGL Registry repository linked above. + * + * + * See the Implementer's Guidelines for information about where this file + * should be located on your system and for more details of its use: + * http://www.khronos.org/registry/implementers_guide.pdf + * + * This file should be included as + * #include + * by Khronos client API header files that use its types and defines. + * + * The types in khrplatform.h should only be used to define API-specific types. + * + * Types defined in khrplatform.h: + * khronos_int8_t signed 8 bit + * khronos_uint8_t unsigned 8 bit + * khronos_int16_t signed 16 bit + * khronos_uint16_t unsigned 16 bit + * khronos_int32_t signed 32 bit + * khronos_uint32_t unsigned 32 bit + * khronos_int64_t signed 64 bit + * khronos_uint64_t unsigned 64 bit + * khronos_intptr_t signed same number of bits as a pointer + * khronos_uintptr_t unsigned same number of bits as a pointer + * khronos_ssize_t signed size + * khronos_usize_t unsigned size + * khronos_float_t signed 32 bit floating point + * khronos_time_ns_t unsigned 64 bit time in nanoseconds + * khronos_utime_nanoseconds_t unsigned time interval or absolute time in + * nanoseconds + * khronos_stime_nanoseconds_t signed time interval in nanoseconds + * khronos_boolean_enum_t enumerated boolean type. This should + * only be used as a base type when a client API's boolean type is + * an enum. Client APIs which use an integer or other type for + * booleans cannot use this as the base type for their boolean. + * + * Tokens defined in khrplatform.h: + * + * KHRONOS_FALSE, KHRONOS_TRUE Enumerated boolean false/true values. + * + * KHRONOS_SUPPORT_INT64 is 1 if 64 bit integers are supported; otherwise 0. + * KHRONOS_SUPPORT_FLOAT is 1 if floats are supported; otherwise 0. + * + * Calling convention macros defined in this file: + * KHRONOS_APICALL + * KHRONOS_APIENTRY + * KHRONOS_APIATTRIBUTES + * + * These may be used in function prototypes as: + * + * KHRONOS_APICALL void KHRONOS_APIENTRY funcname( + * int arg1, + * int arg2) KHRONOS_APIATTRIBUTES; + */ + +/*------------------------------------------------------------------------- + * Definition of KHRONOS_APICALL + *------------------------------------------------------------------------- + * This precedes the return type of the function in the function prototype. + */ +#if defined(_WIN32) && !defined(__SCITECH_SNAP__) +# define KHRONOS_APICALL __declspec(dllimport) +#elif defined (__SYMBIAN32__) +# define KHRONOS_APICALL IMPORT_C +#elif defined(__ANDROID__) +# define KHRONOS_APICALL __attribute__((visibility("default"))) +#else +# define KHRONOS_APICALL +#endif + +/*------------------------------------------------------------------------- + * Definition of KHRONOS_APIENTRY + *------------------------------------------------------------------------- + * This follows the return type of the function and precedes the function + * name in the function prototype. + */ +#if defined(_WIN32) && !defined(_WIN32_WCE) && !defined(__SCITECH_SNAP__) + /* Win32 but not WinCE */ +# define KHRONOS_APIENTRY __stdcall +#else +# define KHRONOS_APIENTRY +#endif + +/*------------------------------------------------------------------------- + * Definition of KHRONOS_APIATTRIBUTES + *------------------------------------------------------------------------- + * This follows the closing parenthesis of the function prototype arguments. + */ +#if defined (__ARMCC_2__) +#define KHRONOS_APIATTRIBUTES __softfp +#else +#define KHRONOS_APIATTRIBUTES +#endif + +/*------------------------------------------------------------------------- + * basic type definitions + *-----------------------------------------------------------------------*/ +#if (defined(__STDC_VERSION__) && __STDC_VERSION__ >= 199901L) || defined(__GNUC__) || defined(__SCO__) || defined(__USLC__) + + +/* + * Using + */ +#include +typedef int32_t khronos_int32_t; +typedef uint32_t khronos_uint32_t; +typedef int64_t khronos_int64_t; +typedef uint64_t khronos_uint64_t; +#define KHRONOS_SUPPORT_INT64 1 +#define KHRONOS_SUPPORT_FLOAT 1 + +#elif defined(__VMS ) || defined(__sgi) + +/* + * Using + */ +#include +typedef int32_t khronos_int32_t; +typedef uint32_t khronos_uint32_t; +typedef int64_t khronos_int64_t; +typedef uint64_t khronos_uint64_t; +#define KHRONOS_SUPPORT_INT64 1 +#define KHRONOS_SUPPORT_FLOAT 1 + +#elif defined(_WIN32) && !defined(__SCITECH_SNAP__) + +/* + * Win32 + */ +typedef __int32 khronos_int32_t; +typedef unsigned __int32 khronos_uint32_t; +typedef __int64 khronos_int64_t; +typedef unsigned __int64 khronos_uint64_t; +#define KHRONOS_SUPPORT_INT64 1 +#define KHRONOS_SUPPORT_FLOAT 1 + +#elif defined(__sun__) || defined(__digital__) + +/* + * Sun or Digital + */ +typedef int khronos_int32_t; +typedef unsigned int khronos_uint32_t; +#if defined(__arch64__) || defined(_LP64) +typedef long int khronos_int64_t; +typedef unsigned long int khronos_uint64_t; +#else +typedef long long int khronos_int64_t; +typedef unsigned long long int khronos_uint64_t; +#endif /* __arch64__ */ +#define KHRONOS_SUPPORT_INT64 1 +#define KHRONOS_SUPPORT_FLOAT 1 + +#elif 0 + +/* + * Hypothetical platform with no float or int64 support + */ +typedef int khronos_int32_t; +typedef unsigned int khronos_uint32_t; +#define KHRONOS_SUPPORT_INT64 0 +#define KHRONOS_SUPPORT_FLOAT 0 + +#else + +/* + * Generic fallback + */ +#include +typedef int32_t khronos_int32_t; +typedef uint32_t khronos_uint32_t; +typedef int64_t khronos_int64_t; +typedef uint64_t khronos_uint64_t; +#define KHRONOS_SUPPORT_INT64 1 +#define KHRONOS_SUPPORT_FLOAT 1 + +#endif + + +/* + * Types that are (so far) the same on all platforms + */ +typedef signed char khronos_int8_t; +typedef unsigned char khronos_uint8_t; +typedef signed short int khronos_int16_t; +typedef unsigned short int khronos_uint16_t; + +/* + * Types that differ between LLP64 and LP64 architectures - in LLP64, + * pointers are 64 bits, but 'long' is still 32 bits. Win64 appears + * to be the only LLP64 architecture in current use. + */ +#ifdef _WIN64 +typedef signed long long int khronos_intptr_t; +typedef unsigned long long int khronos_uintptr_t; +typedef signed long long int khronos_ssize_t; +typedef unsigned long long int khronos_usize_t; +#else +typedef signed long int khronos_intptr_t; +typedef unsigned long int khronos_uintptr_t; +typedef signed long int khronos_ssize_t; +typedef unsigned long int khronos_usize_t; +#endif + +#if KHRONOS_SUPPORT_FLOAT +/* + * Float type + */ +typedef float khronos_float_t; +#endif + +#if KHRONOS_SUPPORT_INT64 +/* Time types + * + * These types can be used to represent a time interval in nanoseconds or + * an absolute Unadjusted System Time. Unadjusted System Time is the number + * of nanoseconds since some arbitrary system event (e.g. since the last + * time the system booted). The Unadjusted System Time is an unsigned + * 64 bit value that wraps back to 0 every 584 years. Time intervals + * may be either signed or unsigned. + */ +typedef khronos_uint64_t khronos_utime_nanoseconds_t; +typedef khronos_int64_t khronos_stime_nanoseconds_t; +#endif + +/* + * Dummy value used to pad enum types to 32 bits. + */ +#ifndef KHRONOS_MAX_ENUM +#define KHRONOS_MAX_ENUM 0x7FFFFFFF +#endif + +/* + * Enumerated boolean type + * + * Values other than zero should be considered to be true. Therefore + * comparisons should not be made against KHRONOS_TRUE. + */ +typedef enum { + KHRONOS_FALSE = 0, + KHRONOS_TRUE = 1, + KHRONOS_BOOLEAN_ENUM_FORCE_SIZE = KHRONOS_MAX_ENUM +} khronos_boolean_enum_t; + +#endif /* __khrplatform_h_ */ diff --git a/tcod_sys/libtcod/src/vendor/stb.c b/tcod_sys/libtcod/src/vendor/stb.c index 2d869d998..a99a88d52 100644 --- a/tcod_sys/libtcod/src/vendor/stb.c +++ b/tcod_sys/libtcod/src/vendor/stb.c @@ -2,3 +2,7 @@ #define STB_SPRINTF_IMPLEMENTATION #include "stb_sprintf.h" #undef STB_SPRINTF_IMPLEMENTATION + +#define STB_TRUETYPE_IMPLEMENTATION +#include "stb_truetype.h" +#undef STB_TRUETYPE_IMPLEMENTATION diff --git a/tcod_sys/libtcod/src/vendor/stb_truetype.h b/tcod_sys/libtcod/src/vendor/stb_truetype.h new file mode 100644 index 000000000..0af88ac86 --- /dev/null +++ b/tcod_sys/libtcod/src/vendor/stb_truetype.h @@ -0,0 +1,4894 @@ +// stb_truetype.h - v1.20 - public domain +// authored from 2009-2016 by Sean Barrett / RAD Game Tools +// +// This library processes TrueType files: +// parse files +// extract glyph metrics +// extract glyph shapes +// render glyphs to one-channel bitmaps with antialiasing (box filter) +// render glyphs to one-channel SDF bitmaps (signed-distance field/function) +// +// Todo: +// non-MS cmaps +// crashproof on bad data +// hinting? (no longer patented) +// cleartype-style AA? +// optimize: use simple memory allocator for intermediates +// optimize: build edge-list directly from curves +// optimize: rasterize directly from curves? +// +// ADDITIONAL CONTRIBUTORS +// +// Mikko Mononen: compound shape support, more cmap formats +// Tor Andersson: kerning, subpixel rendering +// Dougall Johnson: OpenType / Type 2 font handling +// Daniel Ribeiro Maciel: basic GPOS-based kerning +// +// Misc other: +// Ryan Gordon +// Simon Glass +// github:IntellectualKitty +// Imanol Celaya +// Daniel Ribeiro Maciel +// +// Bug/warning reports/fixes: +// "Zer" on mollyrocket Fabian "ryg" Giesen +// Cass Everitt Martins Mozeiko +// stoiko (Haemimont Games) Cap Petschulat +// Brian Hook Omar Cornut +// Walter van Niftrik github:aloucks +// David Gow Peter LaValle +// David Given Sergey Popov +// Ivan-Assen Ivanov Giumo X. Clanjor +// Anthony Pesch Higor Euripedes +// Johan Duparc Thomas Fields +// Hou Qiming Derek Vinyard +// Rob Loach Cort Stratton +// Kenney Phillis Jr. github:oyvindjam +// Brian Costabile github:vassvik +// +// VERSION HISTORY +// +// 1.20 (2019-02-07) PackFontRange skips missing codepoints; GetScaleFontVMetrics() +// 1.19 (2018-02-11) GPOS kerning, STBTT_fmod +// 1.18 (2018-01-29) add missing function +// 1.17 (2017-07-23) make more arguments const; doc fix +// 1.16 (2017-07-12) SDF support +// 1.15 (2017-03-03) make more arguments const +// 1.14 (2017-01-16) num-fonts-in-TTC function +// 1.13 (2017-01-02) support OpenType fonts, certain Apple fonts +// 1.12 (2016-10-25) suppress warnings about casting away const with -Wcast-qual +// 1.11 (2016-04-02) fix unused-variable warning +// 1.10 (2016-04-02) user-defined fabs(); rare memory leak; remove duplicate typedef +// 1.09 (2016-01-16) warning fix; avoid crash on outofmem; use allocation userdata properly +// 1.08 (2015-09-13) document stbtt_Rasterize(); fixes for vertical & horizontal edges +// 1.07 (2015-08-01) allow PackFontRanges to accept arrays of sparse codepoints; +// variant PackFontRanges to pack and render in separate phases; +// fix stbtt_GetFontOFfsetForIndex (never worked for non-0 input?); +// fixed an assert() bug in the new rasterizer +// replace assert() with STBTT_assert() in new rasterizer +// +// Full history can be found at the end of this file. +// +// LICENSE +// +// See end of file for license information. +// +// USAGE +// +// Include this file in whatever places need to refer to it. In ONE C/C++ +// file, write: +// #define STB_TRUETYPE_IMPLEMENTATION +// before the #include of this file. This expands out the actual +// implementation into that C/C++ file. +// +// To make the implementation private to the file that generates the implementation, +// #define STBTT_STATIC +// +// Simple 3D API (don't ship this, but it's fine for tools and quick start) +// stbtt_BakeFontBitmap() -- bake a font to a bitmap for use as texture +// stbtt_GetBakedQuad() -- compute quad to draw for a given char +// +// Improved 3D API (more shippable): +// #include "stb_rect_pack.h" -- optional, but you really want it +// stbtt_PackBegin() +// stbtt_PackSetOversampling() -- for improved quality on small fonts +// stbtt_PackFontRanges() -- pack and renders +// stbtt_PackEnd() +// stbtt_GetPackedQuad() +// +// "Load" a font file from a memory buffer (you have to keep the buffer loaded) +// stbtt_InitFont() +// stbtt_GetFontOffsetForIndex() -- indexing for TTC font collections +// stbtt_GetNumberOfFonts() -- number of fonts for TTC font collections +// +// Render a unicode codepoint to a bitmap +// stbtt_GetCodepointBitmap() -- allocates and returns a bitmap +// stbtt_MakeCodepointBitmap() -- renders into bitmap you provide +// stbtt_GetCodepointBitmapBox() -- how big the bitmap must be +// +// Character advance/positioning +// stbtt_GetCodepointHMetrics() +// stbtt_GetFontVMetrics() +// stbtt_GetFontVMetricsOS2() +// stbtt_GetCodepointKernAdvance() +// +// Starting with version 1.06, the rasterizer was replaced with a new, +// faster and generally-more-precise rasterizer. The new rasterizer more +// accurately measures pixel coverage for anti-aliasing, except in the case +// where multiple shapes overlap, in which case it overestimates the AA pixel +// coverage. Thus, anti-aliasing of intersecting shapes may look wrong. If +// this turns out to be a problem, you can re-enable the old rasterizer with +// #define STBTT_RASTERIZER_VERSION 1 +// which will incur about a 15% speed hit. +// +// ADDITIONAL DOCUMENTATION +// +// Immediately after this block comment are a series of sample programs. +// +// After the sample programs is the "header file" section. This section +// includes documentation for each API function. +// +// Some important concepts to understand to use this library: +// +// Codepoint +// Characters are defined by unicode codepoints, e.g. 65 is +// uppercase A, 231 is lowercase c with a cedilla, 0x7e30 is +// the hiragana for "ma". +// +// Glyph +// A visual character shape (every codepoint is rendered as +// some glyph) +// +// Glyph index +// A font-specific integer ID representing a glyph +// +// Baseline +// Glyph shapes are defined relative to a baseline, which is the +// bottom of uppercase characters. Characters extend both above +// and below the baseline. +// +// Current Point +// As you draw text to the screen, you keep track of a "current point" +// which is the origin of each character. The current point's vertical +// position is the baseline. Even "baked fonts" use this model. +// +// Vertical Font Metrics +// The vertical qualities of the font, used to vertically position +// and space the characters. See docs for stbtt_GetFontVMetrics. +// +// Font Size in Pixels or Points +// The preferred interface for specifying font sizes in stb_truetype +// is to specify how tall the font's vertical extent should be in pixels. +// If that sounds good enough, skip the next paragraph. +// +// Most font APIs instead use "points", which are a common typographic +// measurement for describing font size, defined as 72 points per inch. +// stb_truetype provides a point API for compatibility. However, true +// "per inch" conventions don't make much sense on computer displays +// since different monitors have different number of pixels per +// inch. For example, Windows traditionally uses a convention that +// there are 96 pixels per inch, thus making 'inch' measurements have +// nothing to do with inches, and thus effectively defining a point to +// be 1.333 pixels. Additionally, the TrueType font data provides +// an explicit scale factor to scale a given font's glyphs to points, +// but the author has observed that this scale factor is often wrong +// for non-commercial fonts, thus making fonts scaled in points +// according to the TrueType spec incoherently sized in practice. +// +// DETAILED USAGE: +// +// Scale: +// Select how high you want the font to be, in points or pixels. +// Call ScaleForPixelHeight or ScaleForMappingEmToPixels to compute +// a scale factor SF that will be used by all other functions. +// +// Baseline: +// You need to select a y-coordinate that is the baseline of where +// your text will appear. Call GetFontBoundingBox to get the baseline-relative +// bounding box for all characters. SF*-y0 will be the distance in pixels +// that the worst-case character could extend above the baseline, so if +// you want the top edge of characters to appear at the top of the +// screen where y=0, then you would set the baseline to SF*-y0. +// +// Current point: +// Set the current point where the first character will appear. The +// first character could extend left of the current point; this is font +// dependent. You can either choose a current point that is the leftmost +// point and hope, or add some padding, or check the bounding box or +// left-side-bearing of the first character to be displayed and set +// the current point based on that. +// +// Displaying a character: +// Compute the bounding box of the character. It will contain signed values +// relative to . I.e. if it returns x0,y0,x1,y1, +// then the character should be displayed in the rectangle from +// to = 32 && *text < 128) { + stbtt_aligned_quad q; + stbtt_GetBakedQuad(cdata, 512,512, *text-32, &x,&y,&q,1);//1=opengl & d3d10+,0=d3d9 + glTexCoord2f(q.s0,q.t1); glVertex2f(q.x0,q.y0); + glTexCoord2f(q.s1,q.t1); glVertex2f(q.x1,q.y0); + glTexCoord2f(q.s1,q.t0); glVertex2f(q.x1,q.y1); + glTexCoord2f(q.s0,q.t0); glVertex2f(q.x0,q.y1); + } + ++text; + } + glEnd(); +} +#endif +// +// +////////////////////////////////////////////////////////////////////////////// +// +// Complete program (this compiles): get a single bitmap, print as ASCII art +// +#if 0 +#include +#define STB_TRUETYPE_IMPLEMENTATION // force following include to generate implementation +#include "stb_truetype.h" + +char ttf_buffer[1<<25]; + +int main(int argc, char **argv) +{ + stbtt_fontinfo font; + unsigned char *bitmap; + int w,h,i,j,c = (argc > 1 ? atoi(argv[1]) : 'a'), s = (argc > 2 ? atoi(argv[2]) : 20); + + fread(ttf_buffer, 1, 1<<25, fopen(argc > 3 ? argv[3] : "c:/windows/fonts/arialbd.ttf", "rb")); + + stbtt_InitFont(&font, ttf_buffer, stbtt_GetFontOffsetForIndex(ttf_buffer,0)); + bitmap = stbtt_GetCodepointBitmap(&font, 0,stbtt_ScaleForPixelHeight(&font, s), c, &w, &h, 0,0); + + for (j=0; j < h; ++j) { + for (i=0; i < w; ++i) + putchar(" .:ioVM@"[bitmap[j*w+i]>>5]); + putchar('\n'); + } + return 0; +} +#endif +// +// Output: +// +// .ii. +// @@@@@@. +// V@Mio@@o +// :i. V@V +// :oM@@M +// :@@@MM@M +// @@o o@M +// :@@. M@M +// @@@o@@@@ +// :M@@V:@@. +// +////////////////////////////////////////////////////////////////////////////// +// +// Complete program: print "Hello World!" banner, with bugs +// +#if 0 +char buffer[24<<20]; +unsigned char screen[20][79]; + +int main(int arg, char **argv) +{ + stbtt_fontinfo font; + int i,j,ascent,baseline,ch=0; + float scale, xpos=2; // leave a little padding in case the character extends left + char *text = "Heljo World!"; // intentionally misspelled to show 'lj' brokenness + + fread(buffer, 1, 1000000, fopen("c:/windows/fonts/arialbd.ttf", "rb")); + stbtt_InitFont(&font, buffer, 0); + + scale = stbtt_ScaleForPixelHeight(&font, 15); + stbtt_GetFontVMetrics(&font, &ascent,0,0); + baseline = (int) (ascent*scale); + + while (text[ch]) { + int advance,lsb,x0,y0,x1,y1; + float x_shift = xpos - (float) floor(xpos); + stbtt_GetCodepointHMetrics(&font, text[ch], &advance, &lsb); + stbtt_GetCodepointBitmapBoxSubpixel(&font, text[ch], scale,scale,x_shift,0, &x0,&y0,&x1,&y1); + stbtt_MakeCodepointBitmapSubpixel(&font, &screen[baseline + y0][(int) xpos + x0], x1-x0,y1-y0, 79, scale,scale,x_shift,0, text[ch]); + // note that this stomps the old data, so where character boxes overlap (e.g. 'lj') it's wrong + // because this API is really for baking character bitmaps into textures. if you want to render + // a sequence of characters, you really need to render each bitmap to a temp buffer, then + // "alpha blend" that into the working buffer + xpos += (advance * scale); + if (text[ch+1]) + xpos += scale*stbtt_GetCodepointKernAdvance(&font, text[ch],text[ch+1]); + ++ch; + } + + for (j=0; j < 20; ++j) { + for (i=0; i < 78; ++i) + putchar(" .:ioVM@"[screen[j][i]>>5]); + putchar('\n'); + } + + return 0; +} +#endif + + +////////////////////////////////////////////////////////////////////////////// +////////////////////////////////////////////////////////////////////////////// +//// +//// INTEGRATION WITH YOUR CODEBASE +//// +//// The following sections allow you to supply alternate definitions +//// of C library functions used by stb_truetype, e.g. if you don't +//// link with the C runtime library. + +#ifdef STB_TRUETYPE_IMPLEMENTATION + // #define your own (u)stbtt_int8/16/32 before including to override this + #ifndef stbtt_uint8 + typedef unsigned char stbtt_uint8; + typedef signed char stbtt_int8; + typedef unsigned short stbtt_uint16; + typedef signed short stbtt_int16; + typedef unsigned int stbtt_uint32; + typedef signed int stbtt_int32; + #endif + + typedef char stbtt__check_size32[sizeof(stbtt_int32)==4 ? 1 : -1]; + typedef char stbtt__check_size16[sizeof(stbtt_int16)==2 ? 1 : -1]; + + // e.g. #define your own STBTT_ifloor/STBTT_iceil() to avoid math.h + #ifndef STBTT_ifloor + #include + #define STBTT_ifloor(x) ((int) floor(x)) + #define STBTT_iceil(x) ((int) ceil(x)) + #endif + + #ifndef STBTT_sqrt + #include + #define STBTT_sqrt(x) sqrt(x) + #define STBTT_pow(x,y) pow(x,y) + #endif + + #ifndef STBTT_fmod + #include + #define STBTT_fmod(x,y) fmod(x,y) + #endif + + #ifndef STBTT_cos + #include + #define STBTT_cos(x) cos(x) + #define STBTT_acos(x) acos(x) + #endif + + #ifndef STBTT_fabs + #include + #define STBTT_fabs(x) fabs(x) + #endif + + // #define your own functions "STBTT_malloc" / "STBTT_free" to avoid malloc.h + #ifndef STBTT_malloc + #include + #define STBTT_malloc(x,u) ((void)(u),malloc(x)) + #define STBTT_free(x,u) ((void)(u),free(x)) + #endif + + #ifndef STBTT_assert + #include + #define STBTT_assert(x) assert(x) + #endif + + #ifndef STBTT_strlen + #include + #define STBTT_strlen(x) strlen(x) + #endif + + #ifndef STBTT_memcpy + #include + #define STBTT_memcpy memcpy + #define STBTT_memset memset + #endif +#endif + +/////////////////////////////////////////////////////////////////////////////// +/////////////////////////////////////////////////////////////////////////////// +//// +//// INTERFACE +//// +//// + +#ifndef __STB_INCLUDE_STB_TRUETYPE_H__ +#define __STB_INCLUDE_STB_TRUETYPE_H__ + +#ifdef STBTT_STATIC +#define STBTT_DEF static +#else +#define STBTT_DEF extern +#endif + +#ifdef __cplusplus +extern "C" { +#endif + +// private structure +typedef struct +{ + unsigned char *data; + int cursor; + int size; +} stbtt__buf; + +////////////////////////////////////////////////////////////////////////////// +// +// TEXTURE BAKING API +// +// If you use this API, you only have to call two functions ever. +// + +typedef struct +{ + unsigned short x0,y0,x1,y1; // coordinates of bbox in bitmap + float xoff,yoff,xadvance; +} stbtt_bakedchar; + +STBTT_DEF int stbtt_BakeFontBitmap(const unsigned char *data, int offset, // font location (use offset=0 for plain .ttf) + float pixel_height, // height of font in pixels + unsigned char *pixels, int pw, int ph, // bitmap to be filled in + int first_char, int num_chars, // characters to bake + stbtt_bakedchar *chardata); // you allocate this, it's num_chars long +// if return is positive, the first unused row of the bitmap +// if return is negative, returns the negative of the number of characters that fit +// if return is 0, no characters fit and no rows were used +// This uses a very crappy packing. + +typedef struct +{ + float x0,y0,s0,t0; // top-left + float x1,y1,s1,t1; // bottom-right +} stbtt_aligned_quad; + +STBTT_DEF void stbtt_GetBakedQuad(const stbtt_bakedchar *chardata, int pw, int ph, // same data as above + int char_index, // character to display + float *xpos, float *ypos, // pointers to current position in screen pixel space + stbtt_aligned_quad *q, // output: quad to draw + int opengl_fillrule); // true if opengl fill rule; false if DX9 or earlier +// Call GetBakedQuad with char_index = 'character - first_char', and it +// creates the quad you need to draw and advances the current position. +// +// The coordinate system used assumes y increases downwards. +// +// Characters will extend both above and below the current position; +// see discussion of "BASELINE" above. +// +// It's inefficient; you might want to c&p it and optimize it. + +STBTT_DEF void stbtt_GetScaledFontVMetrics(const unsigned char *fontdata, int index, float size, float *ascent, float *descent, float *lineGap); +// Query the font vertical metrics without having to create a font first. + + +////////////////////////////////////////////////////////////////////////////// +// +// NEW TEXTURE BAKING API +// +// This provides options for packing multiple fonts into one atlas, not +// perfectly but better than nothing. + +typedef struct +{ + unsigned short x0,y0,x1,y1; // coordinates of bbox in bitmap + float xoff,yoff,xadvance; + float xoff2,yoff2; +} stbtt_packedchar; + +typedef struct stbtt_pack_context stbtt_pack_context; +typedef struct stbtt_fontinfo stbtt_fontinfo; +#ifndef STB_RECT_PACK_VERSION +typedef struct stbrp_rect stbrp_rect; +#endif + +STBTT_DEF int stbtt_PackBegin(stbtt_pack_context *spc, unsigned char *pixels, int width, int height, int stride_in_bytes, int padding, void *alloc_context); +// Initializes a packing context stored in the passed-in stbtt_pack_context. +// Future calls using this context will pack characters into the bitmap passed +// in here: a 1-channel bitmap that is width * height. stride_in_bytes is +// the distance from one row to the next (or 0 to mean they are packed tightly +// together). "padding" is the amount of padding to leave between each +// character (normally you want '1' for bitmaps you'll use as textures with +// bilinear filtering). +// +// Returns 0 on failure, 1 on success. + +STBTT_DEF void stbtt_PackEnd (stbtt_pack_context *spc); +// Cleans up the packing context and frees all memory. + +#define STBTT_POINT_SIZE(x) (-(x)) + +STBTT_DEF int stbtt_PackFontRange(stbtt_pack_context *spc, const unsigned char *fontdata, int font_index, float font_size, + int first_unicode_char_in_range, int num_chars_in_range, stbtt_packedchar *chardata_for_range); +// Creates character bitmaps from the font_index'th font found in fontdata (use +// font_index=0 if you don't know what that is). It creates num_chars_in_range +// bitmaps for characters with unicode values starting at first_unicode_char_in_range +// and increasing. Data for how to render them is stored in chardata_for_range; +// pass these to stbtt_GetPackedQuad to get back renderable quads. +// +// font_size is the full height of the character from ascender to descender, +// as computed by stbtt_ScaleForPixelHeight. To use a point size as computed +// by stbtt_ScaleForMappingEmToPixels, wrap the point size in STBTT_POINT_SIZE() +// and pass that result as 'font_size': +// ..., 20 , ... // font max minus min y is 20 pixels tall +// ..., STBTT_POINT_SIZE(20), ... // 'M' is 20 pixels tall + +typedef struct +{ + float font_size; + int first_unicode_codepoint_in_range; // if non-zero, then the chars are continuous, and this is the first codepoint + int *array_of_unicode_codepoints; // if non-zero, then this is an array of unicode codepoints + int num_chars; + stbtt_packedchar *chardata_for_range; // output + unsigned char h_oversample, v_oversample; // don't set these, they're used internally +} stbtt_pack_range; + +STBTT_DEF int stbtt_PackFontRanges(stbtt_pack_context *spc, const unsigned char *fontdata, int font_index, stbtt_pack_range *ranges, int num_ranges); +// Creates character bitmaps from multiple ranges of characters stored in +// ranges. This will usually create a better-packed bitmap than multiple +// calls to stbtt_PackFontRange. Note that you can call this multiple +// times within a single PackBegin/PackEnd. + +STBTT_DEF void stbtt_PackSetOversampling(stbtt_pack_context *spc, unsigned int h_oversample, unsigned int v_oversample); +// Oversampling a font increases the quality by allowing higher-quality subpixel +// positioning, and is especially valuable at smaller text sizes. +// +// This function sets the amount of oversampling for all following calls to +// stbtt_PackFontRange(s) or stbtt_PackFontRangesGatherRects for a given +// pack context. The default (no oversampling) is achieved by h_oversample=1 +// and v_oversample=1. The total number of pixels required is +// h_oversample*v_oversample larger than the default; for example, 2x2 +// oversampling requires 4x the storage of 1x1. For best results, render +// oversampled textures with bilinear filtering. Look at the readme in +// stb/tests/oversample for information about oversampled fonts +// +// To use with PackFontRangesGather etc., you must set it before calls +// call to PackFontRangesGatherRects. + +STBTT_DEF void stbtt_PackSetSkipMissingCodepoints(stbtt_pack_context *spc, int skip); +// If skip != 0, this tells stb_truetype to skip any codepoints for which +// there is no corresponding glyph. If skip=0, which is the default, then +// codepoints without a glyph recived the font's "missing character" glyph, +// typically an empty box by convention. + +STBTT_DEF void stbtt_GetPackedQuad(const stbtt_packedchar *chardata, int pw, int ph, // same data as above + int char_index, // character to display + float *xpos, float *ypos, // pointers to current position in screen pixel space + stbtt_aligned_quad *q, // output: quad to draw + int align_to_integer); + +STBTT_DEF int stbtt_PackFontRangesGatherRects(stbtt_pack_context *spc, const stbtt_fontinfo *info, stbtt_pack_range *ranges, int num_ranges, stbrp_rect *rects); +STBTT_DEF void stbtt_PackFontRangesPackRects(stbtt_pack_context *spc, stbrp_rect *rects, int num_rects); +STBTT_DEF int stbtt_PackFontRangesRenderIntoRects(stbtt_pack_context *spc, const stbtt_fontinfo *info, stbtt_pack_range *ranges, int num_ranges, stbrp_rect *rects); +// Calling these functions in sequence is roughly equivalent to calling +// stbtt_PackFontRanges(). If you more control over the packing of multiple +// fonts, or if you want to pack custom data into a font texture, take a look +// at the source to of stbtt_PackFontRanges() and create a custom version +// using these functions, e.g. call GatherRects multiple times, +// building up a single array of rects, then call PackRects once, +// then call RenderIntoRects repeatedly. This may result in a +// better packing than calling PackFontRanges multiple times +// (or it may not). + +// this is an opaque structure that you shouldn't mess with which holds +// all the context needed from PackBegin to PackEnd. +struct stbtt_pack_context { + void *user_allocator_context; + void *pack_info; + int width; + int height; + int stride_in_bytes; + int padding; + int skip_missing; + unsigned int h_oversample, v_oversample; + unsigned char *pixels; + void *nodes; +}; + +////////////////////////////////////////////////////////////////////////////// +// +// FONT LOADING +// +// + +STBTT_DEF int stbtt_GetNumberOfFonts(const unsigned char *data); +// This function will determine the number of fonts in a font file. TrueType +// collection (.ttc) files may contain multiple fonts, while TrueType font +// (.ttf) files only contain one font. The number of fonts can be used for +// indexing with the previous function where the index is between zero and one +// less than the total fonts. If an error occurs, -1 is returned. + +STBTT_DEF int stbtt_GetFontOffsetForIndex(const unsigned char *data, int index); +// Each .ttf/.ttc file may have more than one font. Each font has a sequential +// index number starting from 0. Call this function to get the font offset for +// a given index; it returns -1 if the index is out of range. A regular .ttf +// file will only define one font and it always be at offset 0, so it will +// return '0' for index 0, and -1 for all other indices. + +// The following structure is defined publicly so you can declare one on +// the stack or as a global or etc, but you should treat it as opaque. +struct stbtt_fontinfo +{ + void * userdata; + unsigned char * data; // pointer to .ttf file + int fontstart; // offset of start of font + + int numGlyphs; // number of glyphs, needed for range checking + + int loca,head,glyf,hhea,hmtx,kern,gpos; // table locations as offset from start of .ttf + int index_map; // a cmap mapping for our chosen character encoding + int indexToLocFormat; // format needed to map from glyph index to glyph + + stbtt__buf cff; // cff font data + stbtt__buf charstrings; // the charstring index + stbtt__buf gsubrs; // global charstring subroutines index + stbtt__buf subrs; // private charstring subroutines index + stbtt__buf fontdicts; // array of font dicts + stbtt__buf fdselect; // map from glyph to fontdict +}; + +STBTT_DEF int stbtt_InitFont(stbtt_fontinfo *info, const unsigned char *data, int offset); +// Given an offset into the file that defines a font, this function builds +// the necessary cached info for the rest of the system. You must allocate +// the stbtt_fontinfo yourself, and stbtt_InitFont will fill it out. You don't +// need to do anything special to free it, because the contents are pure +// value data with no additional data structures. Returns 0 on failure. + + +////////////////////////////////////////////////////////////////////////////// +// +// CHARACTER TO GLYPH-INDEX CONVERSIOn + +STBTT_DEF int stbtt_FindGlyphIndex(const stbtt_fontinfo *info, int unicode_codepoint); +// If you're going to perform multiple operations on the same character +// and you want a speed-up, call this function with the character you're +// going to process, then use glyph-based functions instead of the +// codepoint-based functions. +// Returns 0 if the character codepoint is not defined in the font. + + +////////////////////////////////////////////////////////////////////////////// +// +// CHARACTER PROPERTIES +// + +STBTT_DEF float stbtt_ScaleForPixelHeight(const stbtt_fontinfo *info, float pixels); +// computes a scale factor to produce a font whose "height" is 'pixels' tall. +// Height is measured as the distance from the highest ascender to the lowest +// descender; in other words, it's equivalent to calling stbtt_GetFontVMetrics +// and computing: +// scale = pixels / (ascent - descent) +// so if you prefer to measure height by the ascent only, use a similar calculation. + +STBTT_DEF float stbtt_ScaleForMappingEmToPixels(const stbtt_fontinfo *info, float pixels); +// computes a scale factor to produce a font whose EM size is mapped to +// 'pixels' tall. This is probably what traditional APIs compute, but +// I'm not positive. + +STBTT_DEF void stbtt_GetFontVMetrics(const stbtt_fontinfo *info, int *ascent, int *descent, int *lineGap); +// ascent is the coordinate above the baseline the font extends; descent +// is the coordinate below the baseline the font extends (i.e. it is typically negative) +// lineGap is the spacing between one row's descent and the next row's ascent... +// so you should advance the vertical position by "*ascent - *descent + *lineGap" +// these are expressed in unscaled coordinates, so you must multiply by +// the scale factor for a given size + +STBTT_DEF int stbtt_GetFontVMetricsOS2(const stbtt_fontinfo *info, int *typoAscent, int *typoDescent, int *typoLineGap); +// analogous to GetFontVMetrics, but returns the "typographic" values from the OS/2 +// table (specific to MS/Windows TTF files). +// +// Returns 1 on success (table present), 0 on failure. + +STBTT_DEF void stbtt_GetFontBoundingBox(const stbtt_fontinfo *info, int *x0, int *y0, int *x1, int *y1); +// the bounding box around all possible characters + +STBTT_DEF void stbtt_GetCodepointHMetrics(const stbtt_fontinfo *info, int codepoint, int *advanceWidth, int *leftSideBearing); +// leftSideBearing is the offset from the current horizontal position to the left edge of the character +// advanceWidth is the offset from the current horizontal position to the next horizontal position +// these are expressed in unscaled coordinates + +STBTT_DEF int stbtt_GetCodepointKernAdvance(const stbtt_fontinfo *info, int ch1, int ch2); +// an additional amount to add to the 'advance' value between ch1 and ch2 + +STBTT_DEF int stbtt_GetCodepointBox(const stbtt_fontinfo *info, int codepoint, int *x0, int *y0, int *x1, int *y1); +// Gets the bounding box of the visible part of the glyph, in unscaled coordinates + +STBTT_DEF void stbtt_GetGlyphHMetrics(const stbtt_fontinfo *info, int glyph_index, int *advanceWidth, int *leftSideBearing); +STBTT_DEF int stbtt_GetGlyphKernAdvance(const stbtt_fontinfo *info, int glyph1, int glyph2); +STBTT_DEF int stbtt_GetGlyphBox(const stbtt_fontinfo *info, int glyph_index, int *x0, int *y0, int *x1, int *y1); +// as above, but takes one or more glyph indices for greater efficiency + + +////////////////////////////////////////////////////////////////////////////// +// +// GLYPH SHAPES (you probably don't need these, but they have to go before +// the bitmaps for C declaration-order reasons) +// + +#ifndef STBTT_vmove // you can predefine these to use different values (but why?) + enum { + STBTT_vmove=1, + STBTT_vline, + STBTT_vcurve, + STBTT_vcubic + }; +#endif + +#ifndef stbtt_vertex // you can predefine this to use different values + // (we share this with other code at RAD) + #define stbtt_vertex_type short // can't use stbtt_int16 because that's not visible in the header file + typedef struct + { + stbtt_vertex_type x,y,cx,cy,cx1,cy1; + unsigned char type,padding; + } stbtt_vertex; +#endif + +STBTT_DEF int stbtt_IsGlyphEmpty(const stbtt_fontinfo *info, int glyph_index); +// returns non-zero if nothing is drawn for this glyph + +STBTT_DEF int stbtt_GetCodepointShape(const stbtt_fontinfo *info, int unicode_codepoint, stbtt_vertex **vertices); +STBTT_DEF int stbtt_GetGlyphShape(const stbtt_fontinfo *info, int glyph_index, stbtt_vertex **vertices); +// returns # of vertices and fills *vertices with the pointer to them +// these are expressed in "unscaled" coordinates +// +// The shape is a series of contours. Each one starts with +// a STBTT_moveto, then consists of a series of mixed +// STBTT_lineto and STBTT_curveto segments. A lineto +// draws a line from previous endpoint to its x,y; a curveto +// draws a quadratic bezier from previous endpoint to +// its x,y, using cx,cy as the bezier control point. + +STBTT_DEF void stbtt_FreeShape(const stbtt_fontinfo *info, stbtt_vertex *vertices); +// frees the data allocated above + +////////////////////////////////////////////////////////////////////////////// +// +// BITMAP RENDERING +// + +STBTT_DEF void stbtt_FreeBitmap(unsigned char *bitmap, void *userdata); +// frees the bitmap allocated below + +STBTT_DEF unsigned char *stbtt_GetCodepointBitmap(const stbtt_fontinfo *info, float scale_x, float scale_y, int codepoint, int *width, int *height, int *xoff, int *yoff); +// allocates a large-enough single-channel 8bpp bitmap and renders the +// specified character/glyph at the specified scale into it, with +// antialiasing. 0 is no coverage (transparent), 255 is fully covered (opaque). +// *width & *height are filled out with the width & height of the bitmap, +// which is stored left-to-right, top-to-bottom. +// +// xoff/yoff are the offset it pixel space from the glyph origin to the top-left of the bitmap + +STBTT_DEF unsigned char *stbtt_GetCodepointBitmapSubpixel(const stbtt_fontinfo *info, float scale_x, float scale_y, float shift_x, float shift_y, int codepoint, int *width, int *height, int *xoff, int *yoff); +// the same as stbtt_GetCodepoitnBitmap, but you can specify a subpixel +// shift for the character + +STBTT_DEF void stbtt_MakeCodepointBitmap(const stbtt_fontinfo *info, unsigned char *output, int out_w, int out_h, int out_stride, float scale_x, float scale_y, int codepoint); +// the same as stbtt_GetCodepointBitmap, but you pass in storage for the bitmap +// in the form of 'output', with row spacing of 'out_stride' bytes. the bitmap +// is clipped to out_w/out_h bytes. Call stbtt_GetCodepointBitmapBox to get the +// width and height and positioning info for it first. + +STBTT_DEF void stbtt_MakeCodepointBitmapSubpixel(const stbtt_fontinfo *info, unsigned char *output, int out_w, int out_h, int out_stride, float scale_x, float scale_y, float shift_x, float shift_y, int codepoint); +// same as stbtt_MakeCodepointBitmap, but you can specify a subpixel +// shift for the character + +STBTT_DEF void stbtt_MakeCodepointBitmapSubpixelPrefilter(const stbtt_fontinfo *info, unsigned char *output, int out_w, int out_h, int out_stride, float scale_x, float scale_y, float shift_x, float shift_y, int oversample_x, int oversample_y, float *sub_x, float *sub_y, int codepoint); +// same as stbtt_MakeCodepointBitmapSubpixel, but prefiltering +// is performed (see stbtt_PackSetOversampling) + +STBTT_DEF void stbtt_GetCodepointBitmapBox(const stbtt_fontinfo *font, int codepoint, float scale_x, float scale_y, int *ix0, int *iy0, int *ix1, int *iy1); +// get the bbox of the bitmap centered around the glyph origin; so the +// bitmap width is ix1-ix0, height is iy1-iy0, and location to place +// the bitmap top left is (leftSideBearing*scale,iy0). +// (Note that the bitmap uses y-increases-down, but the shape uses +// y-increases-up, so CodepointBitmapBox and CodepointBox are inverted.) + +STBTT_DEF void stbtt_GetCodepointBitmapBoxSubpixel(const stbtt_fontinfo *font, int codepoint, float scale_x, float scale_y, float shift_x, float shift_y, int *ix0, int *iy0, int *ix1, int *iy1); +// same as stbtt_GetCodepointBitmapBox, but you can specify a subpixel +// shift for the character + +// the following functions are equivalent to the above functions, but operate +// on glyph indices instead of Unicode codepoints (for efficiency) +STBTT_DEF unsigned char *stbtt_GetGlyphBitmap(const stbtt_fontinfo *info, float scale_x, float scale_y, int glyph, int *width, int *height, int *xoff, int *yoff); +STBTT_DEF unsigned char *stbtt_GetGlyphBitmapSubpixel(const stbtt_fontinfo *info, float scale_x, float scale_y, float shift_x, float shift_y, int glyph, int *width, int *height, int *xoff, int *yoff); +STBTT_DEF void stbtt_MakeGlyphBitmap(const stbtt_fontinfo *info, unsigned char *output, int out_w, int out_h, int out_stride, float scale_x, float scale_y, int glyph); +STBTT_DEF void stbtt_MakeGlyphBitmapSubpixel(const stbtt_fontinfo *info, unsigned char *output, int out_w, int out_h, int out_stride, float scale_x, float scale_y, float shift_x, float shift_y, int glyph); +STBTT_DEF void stbtt_MakeGlyphBitmapSubpixelPrefilter(const stbtt_fontinfo *info, unsigned char *output, int out_w, int out_h, int out_stride, float scale_x, float scale_y, float shift_x, float shift_y, int oversample_x, int oversample_y, float *sub_x, float *sub_y, int glyph); +STBTT_DEF void stbtt_GetGlyphBitmapBox(const stbtt_fontinfo *font, int glyph, float scale_x, float scale_y, int *ix0, int *iy0, int *ix1, int *iy1); +STBTT_DEF void stbtt_GetGlyphBitmapBoxSubpixel(const stbtt_fontinfo *font, int glyph, float scale_x, float scale_y,float shift_x, float shift_y, int *ix0, int *iy0, int *ix1, int *iy1); + + +// @TODO: don't expose this structure +typedef struct +{ + int w,h,stride; + unsigned char *pixels; +} stbtt__bitmap; + +// rasterize a shape with quadratic beziers into a bitmap +STBTT_DEF void stbtt_Rasterize(stbtt__bitmap *result, // 1-channel bitmap to draw into + float flatness_in_pixels, // allowable error of curve in pixels + stbtt_vertex *vertices, // array of vertices defining shape + int num_verts, // number of vertices in above array + float scale_x, float scale_y, // scale applied to input vertices + float shift_x, float shift_y, // translation applied to input vertices + int x_off, int y_off, // another translation applied to input + int invert, // if non-zero, vertically flip shape + void *userdata); // context for to STBTT_MALLOC + +////////////////////////////////////////////////////////////////////////////// +// +// Signed Distance Function (or Field) rendering + +STBTT_DEF void stbtt_FreeSDF(unsigned char *bitmap, void *userdata); +// frees the SDF bitmap allocated below + +STBTT_DEF unsigned char * stbtt_GetGlyphSDF(const stbtt_fontinfo *info, float scale, int glyph, int padding, unsigned char onedge_value, float pixel_dist_scale, int *width, int *height, int *xoff, int *yoff); +STBTT_DEF unsigned char * stbtt_GetCodepointSDF(const stbtt_fontinfo *info, float scale, int codepoint, int padding, unsigned char onedge_value, float pixel_dist_scale, int *width, int *height, int *xoff, int *yoff); +// These functions compute a discretized SDF field for a single character, suitable for storing +// in a single-channel texture, sampling with bilinear filtering, and testing against +// larger than some threshold to produce scalable fonts. +// info -- the font +// scale -- controls the size of the resulting SDF bitmap, same as it would be creating a regular bitmap +// glyph/codepoint -- the character to generate the SDF for +// padding -- extra "pixels" around the character which are filled with the distance to the character (not 0), +// which allows effects like bit outlines +// onedge_value -- value 0-255 to test the SDF against to reconstruct the character (i.e. the isocontour of the character) +// pixel_dist_scale -- what value the SDF should increase by when moving one SDF "pixel" away from the edge (on the 0..255 scale) +// if positive, > onedge_value is inside; if negative, < onedge_value is inside +// width,height -- output height & width of the SDF bitmap (including padding) +// xoff,yoff -- output origin of the character +// return value -- a 2D array of bytes 0..255, width*height in size +// +// pixel_dist_scale & onedge_value are a scale & bias that allows you to make +// optimal use of the limited 0..255 for your application, trading off precision +// and special effects. SDF values outside the range 0..255 are clamped to 0..255. +// +// Example: +// scale = stbtt_ScaleForPixelHeight(22) +// padding = 5 +// onedge_value = 180 +// pixel_dist_scale = 180/5.0 = 36.0 +// +// This will create an SDF bitmap in which the character is about 22 pixels +// high but the whole bitmap is about 22+5+5=32 pixels high. To produce a filled +// shape, sample the SDF at each pixel and fill the pixel if the SDF value +// is greater than or equal to 180/255. (You'll actually want to antialias, +// which is beyond the scope of this example.) Additionally, you can compute +// offset outlines (e.g. to stroke the character border inside & outside, +// or only outside). For example, to fill outside the character up to 3 SDF +// pixels, you would compare against (180-36.0*3)/255 = 72/255. The above +// choice of variables maps a range from 5 pixels outside the shape to +// 2 pixels inside the shape to 0..255; this is intended primarily for apply +// outside effects only (the interior range is needed to allow proper +// antialiasing of the font at *smaller* sizes) +// +// The function computes the SDF analytically at each SDF pixel, not by e.g. +// building a higher-res bitmap and approximating it. In theory the quality +// should be as high as possible for an SDF of this size & representation, but +// unclear if this is true in practice (perhaps building a higher-res bitmap +// and computing from that can allow drop-out prevention). +// +// The algorithm has not been optimized at all, so expect it to be slow +// if computing lots of characters or very large sizes. + + + +////////////////////////////////////////////////////////////////////////////// +// +// Finding the right font... +// +// You should really just solve this offline, keep your own tables +// of what font is what, and don't try to get it out of the .ttf file. +// That's because getting it out of the .ttf file is really hard, because +// the names in the file can appear in many possible encodings, in many +// possible languages, and e.g. if you need a case-insensitive comparison, +// the details of that depend on the encoding & language in a complex way +// (actually underspecified in truetype, but also gigantic). +// +// But you can use the provided functions in two possible ways: +// stbtt_FindMatchingFont() will use *case-sensitive* comparisons on +// unicode-encoded names to try to find the font you want; +// you can run this before calling stbtt_InitFont() +// +// stbtt_GetFontNameString() lets you get any of the various strings +// from the file yourself and do your own comparisons on them. +// You have to have called stbtt_InitFont() first. + + +STBTT_DEF int stbtt_FindMatchingFont(const unsigned char *fontdata, const char *name, int flags); +// returns the offset (not index) of the font that matches, or -1 if none +// if you use STBTT_MACSTYLE_DONTCARE, use a font name like "Arial Bold". +// if you use any other flag, use a font name like "Arial"; this checks +// the 'macStyle' header field; i don't know if fonts set this consistently +#define STBTT_MACSTYLE_DONTCARE 0 +#define STBTT_MACSTYLE_BOLD 1 +#define STBTT_MACSTYLE_ITALIC 2 +#define STBTT_MACSTYLE_UNDERSCORE 4 +#define STBTT_MACSTYLE_NONE 8 // <= not same as 0, this makes us check the bitfield is 0 + +STBTT_DEF int stbtt_CompareUTF8toUTF16_bigendian(const char *s1, int len1, const char *s2, int len2); +// returns 1/0 whether the first string interpreted as utf8 is identical to +// the second string interpreted as big-endian utf16... useful for strings from next func + +STBTT_DEF const char *stbtt_GetFontNameString(const stbtt_fontinfo *font, int *length, int platformID, int encodingID, int languageID, int nameID); +// returns the string (which may be big-endian double byte, e.g. for unicode) +// and puts the length in bytes in *length. +// +// some of the values for the IDs are below; for more see the truetype spec: +// http://developer.apple.com/textfonts/TTRefMan/RM06/Chap6name.html +// http://www.microsoft.com/typography/otspec/name.htm + +enum { // platformID + STBTT_PLATFORM_ID_UNICODE =0, + STBTT_PLATFORM_ID_MAC =1, + STBTT_PLATFORM_ID_ISO =2, + STBTT_PLATFORM_ID_MICROSOFT =3 +}; + +enum { // encodingID for STBTT_PLATFORM_ID_UNICODE + STBTT_UNICODE_EID_UNICODE_1_0 =0, + STBTT_UNICODE_EID_UNICODE_1_1 =1, + STBTT_UNICODE_EID_ISO_10646 =2, + STBTT_UNICODE_EID_UNICODE_2_0_BMP=3, + STBTT_UNICODE_EID_UNICODE_2_0_FULL=4 +}; + +enum { // encodingID for STBTT_PLATFORM_ID_MICROSOFT + STBTT_MS_EID_SYMBOL =0, + STBTT_MS_EID_UNICODE_BMP =1, + STBTT_MS_EID_SHIFTJIS =2, + STBTT_MS_EID_UNICODE_FULL =10 +}; + +enum { // encodingID for STBTT_PLATFORM_ID_MAC; same as Script Manager codes + STBTT_MAC_EID_ROMAN =0, STBTT_MAC_EID_ARABIC =4, + STBTT_MAC_EID_JAPANESE =1, STBTT_MAC_EID_HEBREW =5, + STBTT_MAC_EID_CHINESE_TRAD =2, STBTT_MAC_EID_GREEK =6, + STBTT_MAC_EID_KOREAN =3, STBTT_MAC_EID_RUSSIAN =7 +}; + +enum { // languageID for STBTT_PLATFORM_ID_MICROSOFT; same as LCID... + // problematic because there are e.g. 16 english LCIDs and 16 arabic LCIDs + STBTT_MS_LANG_ENGLISH =0x0409, STBTT_MS_LANG_ITALIAN =0x0410, + STBTT_MS_LANG_CHINESE =0x0804, STBTT_MS_LANG_JAPANESE =0x0411, + STBTT_MS_LANG_DUTCH =0x0413, STBTT_MS_LANG_KOREAN =0x0412, + STBTT_MS_LANG_FRENCH =0x040c, STBTT_MS_LANG_RUSSIAN =0x0419, + STBTT_MS_LANG_GERMAN =0x0407, STBTT_MS_LANG_SPANISH =0x0409, + STBTT_MS_LANG_HEBREW =0x040d, STBTT_MS_LANG_SWEDISH =0x041D +}; + +enum { // languageID for STBTT_PLATFORM_ID_MAC + STBTT_MAC_LANG_ENGLISH =0 , STBTT_MAC_LANG_JAPANESE =11, + STBTT_MAC_LANG_ARABIC =12, STBTT_MAC_LANG_KOREAN =23, + STBTT_MAC_LANG_DUTCH =4 , STBTT_MAC_LANG_RUSSIAN =32, + STBTT_MAC_LANG_FRENCH =1 , STBTT_MAC_LANG_SPANISH =6 , + STBTT_MAC_LANG_GERMAN =2 , STBTT_MAC_LANG_SWEDISH =5 , + STBTT_MAC_LANG_HEBREW =10, STBTT_MAC_LANG_CHINESE_SIMPLIFIED =33, + STBTT_MAC_LANG_ITALIAN =3 , STBTT_MAC_LANG_CHINESE_TRAD =19 +}; + +#ifdef __cplusplus +} +#endif + +#endif // __STB_INCLUDE_STB_TRUETYPE_H__ + +/////////////////////////////////////////////////////////////////////////////// +/////////////////////////////////////////////////////////////////////////////// +//// +//// IMPLEMENTATION +//// +//// + +#ifdef STB_TRUETYPE_IMPLEMENTATION + +#ifndef STBTT_MAX_OVERSAMPLE +#define STBTT_MAX_OVERSAMPLE 8 +#endif + +#if STBTT_MAX_OVERSAMPLE > 255 +#error "STBTT_MAX_OVERSAMPLE cannot be > 255" +#endif + +typedef int stbtt__test_oversample_pow2[(STBTT_MAX_OVERSAMPLE & (STBTT_MAX_OVERSAMPLE-1)) == 0 ? 1 : -1]; + +#ifndef STBTT_RASTERIZER_VERSION +#define STBTT_RASTERIZER_VERSION 2 +#endif + +#ifdef _MSC_VER +#define STBTT__NOTUSED(v) (void)(v) +#else +#define STBTT__NOTUSED(v) (void)sizeof(v) +#endif + +////////////////////////////////////////////////////////////////////////// +// +// stbtt__buf helpers to parse data from file +// + +static stbtt_uint8 stbtt__buf_get8(stbtt__buf *b) +{ + if (b->cursor >= b->size) + return 0; + return b->data[b->cursor++]; +} + +static stbtt_uint8 stbtt__buf_peek8(stbtt__buf *b) +{ + if (b->cursor >= b->size) + return 0; + return b->data[b->cursor]; +} + +static void stbtt__buf_seek(stbtt__buf *b, int o) +{ + STBTT_assert(!(o > b->size || o < 0)); + b->cursor = (o > b->size || o < 0) ? b->size : o; +} + +static void stbtt__buf_skip(stbtt__buf *b, int o) +{ + stbtt__buf_seek(b, b->cursor + o); +} + +static stbtt_uint32 stbtt__buf_get(stbtt__buf *b, int n) +{ + stbtt_uint32 v = 0; + int i; + STBTT_assert(n >= 1 && n <= 4); + for (i = 0; i < n; i++) + v = (v << 8) | stbtt__buf_get8(b); + return v; +} + +static stbtt__buf stbtt__new_buf(const void *p, size_t size) +{ + stbtt__buf r; + STBTT_assert(size < 0x40000000); + r.data = (stbtt_uint8*) p; + r.size = (int) size; + r.cursor = 0; + return r; +} + +#define stbtt__buf_get16(b) stbtt__buf_get((b), 2) +#define stbtt__buf_get32(b) stbtt__buf_get((b), 4) + +static stbtt__buf stbtt__buf_range(const stbtt__buf *b, int o, int s) +{ + stbtt__buf r = stbtt__new_buf(NULL, 0); + if (o < 0 || s < 0 || o > b->size || s > b->size - o) return r; + r.data = b->data + o; + r.size = s; + return r; +} + +static stbtt__buf stbtt__cff_get_index(stbtt__buf *b) +{ + int count, start, offsize; + start = b->cursor; + count = stbtt__buf_get16(b); + if (count) { + offsize = stbtt__buf_get8(b); + STBTT_assert(offsize >= 1 && offsize <= 4); + stbtt__buf_skip(b, offsize * count); + stbtt__buf_skip(b, stbtt__buf_get(b, offsize) - 1); + } + return stbtt__buf_range(b, start, b->cursor - start); +} + +static stbtt_uint32 stbtt__cff_int(stbtt__buf *b) +{ + int b0 = stbtt__buf_get8(b); + if (b0 >= 32 && b0 <= 246) return b0 - 139; + else if (b0 >= 247 && b0 <= 250) return (b0 - 247)*256 + stbtt__buf_get8(b) + 108; + else if (b0 >= 251 && b0 <= 254) return -(b0 - 251)*256 - stbtt__buf_get8(b) - 108; + else if (b0 == 28) return stbtt__buf_get16(b); + else if (b0 == 29) return stbtt__buf_get32(b); + STBTT_assert(0); + return 0; +} + +static void stbtt__cff_skip_operand(stbtt__buf *b) { + int v, b0 = stbtt__buf_peek8(b); + STBTT_assert(b0 >= 28); + if (b0 == 30) { + stbtt__buf_skip(b, 1); + while (b->cursor < b->size) { + v = stbtt__buf_get8(b); + if ((v & 0xF) == 0xF || (v >> 4) == 0xF) + break; + } + } else { + stbtt__cff_int(b); + } +} + +static stbtt__buf stbtt__dict_get(stbtt__buf *b, int key) +{ + stbtt__buf_seek(b, 0); + while (b->cursor < b->size) { + int start = b->cursor, end, op; + while (stbtt__buf_peek8(b) >= 28) + stbtt__cff_skip_operand(b); + end = b->cursor; + op = stbtt__buf_get8(b); + if (op == 12) op = stbtt__buf_get8(b) | 0x100; + if (op == key) return stbtt__buf_range(b, start, end-start); + } + return stbtt__buf_range(b, 0, 0); +} + +static void stbtt__dict_get_ints(stbtt__buf *b, int key, int outcount, stbtt_uint32 *out) +{ + int i; + stbtt__buf operands = stbtt__dict_get(b, key); + for (i = 0; i < outcount && operands.cursor < operands.size; i++) + out[i] = stbtt__cff_int(&operands); +} + +static int stbtt__cff_index_count(stbtt__buf *b) +{ + stbtt__buf_seek(b, 0); + return stbtt__buf_get16(b); +} + +static stbtt__buf stbtt__cff_index_get(stbtt__buf b, int i) +{ + int count, offsize, start, end; + stbtt__buf_seek(&b, 0); + count = stbtt__buf_get16(&b); + offsize = stbtt__buf_get8(&b); + STBTT_assert(i >= 0 && i < count); + STBTT_assert(offsize >= 1 && offsize <= 4); + stbtt__buf_skip(&b, i*offsize); + start = stbtt__buf_get(&b, offsize); + end = stbtt__buf_get(&b, offsize); + return stbtt__buf_range(&b, 2+(count+1)*offsize+start, end - start); +} + +////////////////////////////////////////////////////////////////////////// +// +// accessors to parse data from file +// + +// on platforms that don't allow misaligned reads, if we want to allow +// truetype fonts that aren't padded to alignment, define ALLOW_UNALIGNED_TRUETYPE + +#define ttBYTE(p) (* (stbtt_uint8 *) (p)) +#define ttCHAR(p) (* (stbtt_int8 *) (p)) +#define ttFixed(p) ttLONG(p) + +static stbtt_uint16 ttUSHORT(stbtt_uint8 *p) { return p[0]*256 + p[1]; } +static stbtt_int16 ttSHORT(stbtt_uint8 *p) { return p[0]*256 + p[1]; } +static stbtt_uint32 ttULONG(stbtt_uint8 *p) { return (p[0]<<24) + (p[1]<<16) + (p[2]<<8) + p[3]; } +static stbtt_int32 ttLONG(stbtt_uint8 *p) { return (p[0]<<24) + (p[1]<<16) + (p[2]<<8) + p[3]; } + +#define stbtt_tag4(p,c0,c1,c2,c3) ((p)[0] == (c0) && (p)[1] == (c1) && (p)[2] == (c2) && (p)[3] == (c3)) +#define stbtt_tag(p,str) stbtt_tag4(p,str[0],str[1],str[2],str[3]) + +static int stbtt__isfont(stbtt_uint8 *font) +{ + // check the version number + if (stbtt_tag4(font, '1',0,0,0)) return 1; // TrueType 1 + if (stbtt_tag(font, "typ1")) return 1; // TrueType with type 1 font -- we don't support this! + if (stbtt_tag(font, "OTTO")) return 1; // OpenType with CFF + if (stbtt_tag4(font, 0,1,0,0)) return 1; // OpenType 1.0 + if (stbtt_tag(font, "true")) return 1; // Apple specification for TrueType fonts + return 0; +} + +// @OPTIMIZE: binary search +static stbtt_uint32 stbtt__find_table(stbtt_uint8 *data, stbtt_uint32 fontstart, const char *tag) +{ + stbtt_int32 num_tables = ttUSHORT(data+fontstart+4); + stbtt_uint32 tabledir = fontstart + 12; + stbtt_int32 i; + for (i=0; i < num_tables; ++i) { + stbtt_uint32 loc = tabledir + 16*i; + if (stbtt_tag(data+loc+0, tag)) + return ttULONG(data+loc+8); + } + return 0; +} + +static int stbtt_GetFontOffsetForIndex_internal(unsigned char *font_collection, int index) +{ + // if it's just a font, there's only one valid index + if (stbtt__isfont(font_collection)) + return index == 0 ? 0 : -1; + + // check if it's a TTC + if (stbtt_tag(font_collection, "ttcf")) { + // version 1? + if (ttULONG(font_collection+4) == 0x00010000 || ttULONG(font_collection+4) == 0x00020000) { + stbtt_int32 n = ttLONG(font_collection+8); + if (index >= n) + return -1; + return ttULONG(font_collection+12+index*4); + } + } + return -1; +} + +static int stbtt_GetNumberOfFonts_internal(unsigned char *font_collection) +{ + // if it's just a font, there's only one valid font + if (stbtt__isfont(font_collection)) + return 1; + + // check if it's a TTC + if (stbtt_tag(font_collection, "ttcf")) { + // version 1? + if (ttULONG(font_collection+4) == 0x00010000 || ttULONG(font_collection+4) == 0x00020000) { + return ttLONG(font_collection+8); + } + } + return 0; +} + +static stbtt__buf stbtt__get_subrs(stbtt__buf cff, stbtt__buf fontdict) +{ + stbtt_uint32 subrsoff = 0, private_loc[2] = { 0, 0 }; + stbtt__buf pdict; + stbtt__dict_get_ints(&fontdict, 18, 2, private_loc); + if (!private_loc[1] || !private_loc[0]) return stbtt__new_buf(NULL, 0); + pdict = stbtt__buf_range(&cff, private_loc[1], private_loc[0]); + stbtt__dict_get_ints(&pdict, 19, 1, &subrsoff); + if (!subrsoff) return stbtt__new_buf(NULL, 0); + stbtt__buf_seek(&cff, private_loc[1]+subrsoff); + return stbtt__cff_get_index(&cff); +} + +static int stbtt_InitFont_internal(stbtt_fontinfo *info, unsigned char *data, int fontstart) +{ + stbtt_uint32 cmap, t; + stbtt_int32 i,numTables; + + info->data = data; + info->fontstart = fontstart; + info->cff = stbtt__new_buf(NULL, 0); + + cmap = stbtt__find_table(data, fontstart, "cmap"); // required + info->loca = stbtt__find_table(data, fontstart, "loca"); // required + info->head = stbtt__find_table(data, fontstart, "head"); // required + info->glyf = stbtt__find_table(data, fontstart, "glyf"); // required + info->hhea = stbtt__find_table(data, fontstart, "hhea"); // required + info->hmtx = stbtt__find_table(data, fontstart, "hmtx"); // required + info->kern = stbtt__find_table(data, fontstart, "kern"); // not required + info->gpos = stbtt__find_table(data, fontstart, "GPOS"); // not required + + if (!cmap || !info->head || !info->hhea || !info->hmtx) + return 0; + if (info->glyf) { + // required for truetype + if (!info->loca) return 0; + } else { + // initialization for CFF / Type2 fonts (OTF) + stbtt__buf b, topdict, topdictidx; + stbtt_uint32 cstype = 2, charstrings = 0, fdarrayoff = 0, fdselectoff = 0; + stbtt_uint32 cff; + + cff = stbtt__find_table(data, fontstart, "CFF "); + if (!cff) return 0; + + info->fontdicts = stbtt__new_buf(NULL, 0); + info->fdselect = stbtt__new_buf(NULL, 0); + + // @TODO this should use size from table (not 512MB) + info->cff = stbtt__new_buf(data+cff, 512*1024*1024); + b = info->cff; + + // read the header + stbtt__buf_skip(&b, 2); + stbtt__buf_seek(&b, stbtt__buf_get8(&b)); // hdrsize + + // @TODO the name INDEX could list multiple fonts, + // but we just use the first one. + stbtt__cff_get_index(&b); // name INDEX + topdictidx = stbtt__cff_get_index(&b); + topdict = stbtt__cff_index_get(topdictidx, 0); + stbtt__cff_get_index(&b); // string INDEX + info->gsubrs = stbtt__cff_get_index(&b); + + stbtt__dict_get_ints(&topdict, 17, 1, &charstrings); + stbtt__dict_get_ints(&topdict, 0x100 | 6, 1, &cstype); + stbtt__dict_get_ints(&topdict, 0x100 | 36, 1, &fdarrayoff); + stbtt__dict_get_ints(&topdict, 0x100 | 37, 1, &fdselectoff); + info->subrs = stbtt__get_subrs(b, topdict); + + // we only support Type 2 charstrings + if (cstype != 2) return 0; + if (charstrings == 0) return 0; + + if (fdarrayoff) { + // looks like a CID font + if (!fdselectoff) return 0; + stbtt__buf_seek(&b, fdarrayoff); + info->fontdicts = stbtt__cff_get_index(&b); + info->fdselect = stbtt__buf_range(&b, fdselectoff, b.size-fdselectoff); + } + + stbtt__buf_seek(&b, charstrings); + info->charstrings = stbtt__cff_get_index(&b); + } + + t = stbtt__find_table(data, fontstart, "maxp"); + if (t) + info->numGlyphs = ttUSHORT(data+t+4); + else + info->numGlyphs = 0xffff; + + // find a cmap encoding table we understand *now* to avoid searching + // later. (todo: could make this installable) + // the same regardless of glyph. + numTables = ttUSHORT(data + cmap + 2); + info->index_map = 0; + for (i=0; i < numTables; ++i) { + stbtt_uint32 encoding_record = cmap + 4 + 8 * i; + // find an encoding we understand: + switch(ttUSHORT(data+encoding_record)) { + case STBTT_PLATFORM_ID_MICROSOFT: + switch (ttUSHORT(data+encoding_record+2)) { + case STBTT_MS_EID_UNICODE_BMP: + case STBTT_MS_EID_UNICODE_FULL: + // MS/Unicode + info->index_map = cmap + ttULONG(data+encoding_record+4); + break; + } + break; + case STBTT_PLATFORM_ID_UNICODE: + // Mac/iOS has these + // all the encodingIDs are unicode, so we don't bother to check it + info->index_map = cmap + ttULONG(data+encoding_record+4); + break; + } + } + if (info->index_map == 0) + return 0; + + info->indexToLocFormat = ttUSHORT(data+info->head + 50); + return 1; +} + +STBTT_DEF int stbtt_FindGlyphIndex(const stbtt_fontinfo *info, int unicode_codepoint) +{ + stbtt_uint8 *data = info->data; + stbtt_uint32 index_map = info->index_map; + + stbtt_uint16 format = ttUSHORT(data + index_map + 0); + if (format == 0) { // apple byte encoding + stbtt_int32 bytes = ttUSHORT(data + index_map + 2); + if (unicode_codepoint < bytes-6) + return ttBYTE(data + index_map + 6 + unicode_codepoint); + return 0; + } else if (format == 6) { + stbtt_uint32 first = ttUSHORT(data + index_map + 6); + stbtt_uint32 count = ttUSHORT(data + index_map + 8); + if ((stbtt_uint32) unicode_codepoint >= first && (stbtt_uint32) unicode_codepoint < first+count) + return ttUSHORT(data + index_map + 10 + (unicode_codepoint - first)*2); + return 0; + } else if (format == 2) { + STBTT_assert(0); // @TODO: high-byte mapping for japanese/chinese/korean + return 0; + } else if (format == 4) { // standard mapping for windows fonts: binary search collection of ranges + stbtt_uint16 segcount = ttUSHORT(data+index_map+6) >> 1; + stbtt_uint16 searchRange = ttUSHORT(data+index_map+8) >> 1; + stbtt_uint16 entrySelector = ttUSHORT(data+index_map+10); + stbtt_uint16 rangeShift = ttUSHORT(data+index_map+12) >> 1; + + // do a binary search of the segments + stbtt_uint32 endCount = index_map + 14; + stbtt_uint32 search = endCount; + + if (unicode_codepoint > 0xffff) + return 0; + + // they lie from endCount .. endCount + segCount + // but searchRange is the nearest power of two, so... + if (unicode_codepoint >= ttUSHORT(data + search + rangeShift*2)) + search += rangeShift*2; + + // now decrement to bias correctly to find smallest + search -= 2; + while (entrySelector) { + stbtt_uint16 end; + searchRange >>= 1; + end = ttUSHORT(data + search + searchRange*2); + if (unicode_codepoint > end) + search += searchRange*2; + --entrySelector; + } + search += 2; + + { + stbtt_uint16 offset, start; + stbtt_uint16 item = (stbtt_uint16) ((search - endCount) >> 1); + + STBTT_assert(unicode_codepoint <= ttUSHORT(data + endCount + 2*item)); + start = ttUSHORT(data + index_map + 14 + segcount*2 + 2 + 2*item); + if (unicode_codepoint < start) + return 0; + + offset = ttUSHORT(data + index_map + 14 + segcount*6 + 2 + 2*item); + if (offset == 0) + return (stbtt_uint16) (unicode_codepoint + ttSHORT(data + index_map + 14 + segcount*4 + 2 + 2*item)); + + return ttUSHORT(data + offset + (unicode_codepoint-start)*2 + index_map + 14 + segcount*6 + 2 + 2*item); + } + } else if (format == 12 || format == 13) { + stbtt_uint32 ngroups = ttULONG(data+index_map+12); + stbtt_int32 low,high; + low = 0; high = (stbtt_int32)ngroups; + // Binary search the right group. + while (low < high) { + stbtt_int32 mid = low + ((high-low) >> 1); // rounds down, so low <= mid < high + stbtt_uint32 start_char = ttULONG(data+index_map+16+mid*12); + stbtt_uint32 end_char = ttULONG(data+index_map+16+mid*12+4); + if ((stbtt_uint32) unicode_codepoint < start_char) + high = mid; + else if ((stbtt_uint32) unicode_codepoint > end_char) + low = mid+1; + else { + stbtt_uint32 start_glyph = ttULONG(data+index_map+16+mid*12+8); + if (format == 12) + return start_glyph + unicode_codepoint-start_char; + else // format == 13 + return start_glyph; + } + } + return 0; // not found + } + // @TODO + STBTT_assert(0); + return 0; +} + +STBTT_DEF int stbtt_GetCodepointShape(const stbtt_fontinfo *info, int unicode_codepoint, stbtt_vertex **vertices) +{ + return stbtt_GetGlyphShape(info, stbtt_FindGlyphIndex(info, unicode_codepoint), vertices); +} + +static void stbtt_setvertex(stbtt_vertex *v, stbtt_uint8 type, stbtt_int32 x, stbtt_int32 y, stbtt_int32 cx, stbtt_int32 cy) +{ + v->type = type; + v->x = (stbtt_int16) x; + v->y = (stbtt_int16) y; + v->cx = (stbtt_int16) cx; + v->cy = (stbtt_int16) cy; +} + +static int stbtt__GetGlyfOffset(const stbtt_fontinfo *info, int glyph_index) +{ + int g1,g2; + + STBTT_assert(!info->cff.size); + + if (glyph_index >= info->numGlyphs) return -1; // glyph index out of range + if (info->indexToLocFormat >= 2) return -1; // unknown index->glyph map format + + if (info->indexToLocFormat == 0) { + g1 = info->glyf + ttUSHORT(info->data + info->loca + glyph_index * 2) * 2; + g2 = info->glyf + ttUSHORT(info->data + info->loca + glyph_index * 2 + 2) * 2; + } else { + g1 = info->glyf + ttULONG (info->data + info->loca + glyph_index * 4); + g2 = info->glyf + ttULONG (info->data + info->loca + glyph_index * 4 + 4); + } + + return g1==g2 ? -1 : g1; // if length is 0, return -1 +} + +static int stbtt__GetGlyphInfoT2(const stbtt_fontinfo *info, int glyph_index, int *x0, int *y0, int *x1, int *y1); + +STBTT_DEF int stbtt_GetGlyphBox(const stbtt_fontinfo *info, int glyph_index, int *x0, int *y0, int *x1, int *y1) +{ + if (info->cff.size) { + stbtt__GetGlyphInfoT2(info, glyph_index, x0, y0, x1, y1); + } else { + int g = stbtt__GetGlyfOffset(info, glyph_index); + if (g < 0) return 0; + + if (x0) *x0 = ttSHORT(info->data + g + 2); + if (y0) *y0 = ttSHORT(info->data + g + 4); + if (x1) *x1 = ttSHORT(info->data + g + 6); + if (y1) *y1 = ttSHORT(info->data + g + 8); + } + return 1; +} + +STBTT_DEF int stbtt_GetCodepointBox(const stbtt_fontinfo *info, int codepoint, int *x0, int *y0, int *x1, int *y1) +{ + return stbtt_GetGlyphBox(info, stbtt_FindGlyphIndex(info,codepoint), x0,y0,x1,y1); +} + +STBTT_DEF int stbtt_IsGlyphEmpty(const stbtt_fontinfo *info, int glyph_index) +{ + stbtt_int16 numberOfContours; + int g; + if (info->cff.size) + return stbtt__GetGlyphInfoT2(info, glyph_index, NULL, NULL, NULL, NULL) == 0; + g = stbtt__GetGlyfOffset(info, glyph_index); + if (g < 0) return 1; + numberOfContours = ttSHORT(info->data + g); + return numberOfContours == 0; +} + +static int stbtt__close_shape(stbtt_vertex *vertices, int num_vertices, int was_off, int start_off, + stbtt_int32 sx, stbtt_int32 sy, stbtt_int32 scx, stbtt_int32 scy, stbtt_int32 cx, stbtt_int32 cy) +{ + if (start_off) { + if (was_off) + stbtt_setvertex(&vertices[num_vertices++], STBTT_vcurve, (cx+scx)>>1, (cy+scy)>>1, cx,cy); + stbtt_setvertex(&vertices[num_vertices++], STBTT_vcurve, sx,sy,scx,scy); + } else { + if (was_off) + stbtt_setvertex(&vertices[num_vertices++], STBTT_vcurve,sx,sy,cx,cy); + else + stbtt_setvertex(&vertices[num_vertices++], STBTT_vline,sx,sy,0,0); + } + return num_vertices; +} + +static int stbtt__GetGlyphShapeTT(const stbtt_fontinfo *info, int glyph_index, stbtt_vertex **pvertices) +{ + stbtt_int16 numberOfContours; + stbtt_uint8 *endPtsOfContours; + stbtt_uint8 *data = info->data; + stbtt_vertex *vertices=0; + int num_vertices=0; + int g = stbtt__GetGlyfOffset(info, glyph_index); + + *pvertices = NULL; + + if (g < 0) return 0; + + numberOfContours = ttSHORT(data + g); + + if (numberOfContours > 0) { + stbtt_uint8 flags=0,flagcount; + stbtt_int32 ins, i,j=0,m,n, next_move, was_off=0, off, start_off=0; + stbtt_int32 x,y,cx,cy,sx,sy, scx,scy; + stbtt_uint8 *points; + endPtsOfContours = (data + g + 10); + ins = ttUSHORT(data + g + 10 + numberOfContours * 2); + points = data + g + 10 + numberOfContours * 2 + 2 + ins; + + n = 1+ttUSHORT(endPtsOfContours + numberOfContours*2-2); + + m = n + 2*numberOfContours; // a loose bound on how many vertices we might need + vertices = (stbtt_vertex *) STBTT_malloc(m * sizeof(vertices[0]), info->userdata); + if (vertices == 0) + return 0; + + next_move = 0; + flagcount=0; + + // in first pass, we load uninterpreted data into the allocated array + // above, shifted to the end of the array so we won't overwrite it when + // we create our final data starting from the front + + off = m - n; // starting offset for uninterpreted data, regardless of how m ends up being calculated + + // first load flags + + for (i=0; i < n; ++i) { + if (flagcount == 0) { + flags = *points++; + if (flags & 8) + flagcount = *points++; + } else + --flagcount; + vertices[off+i].type = flags; + } + + // now load x coordinates + x=0; + for (i=0; i < n; ++i) { + flags = vertices[off+i].type; + if (flags & 2) { + stbtt_int16 dx = *points++; + x += (flags & 16) ? dx : -dx; // ??? + } else { + if (!(flags & 16)) { + x = x + (stbtt_int16) (points[0]*256 + points[1]); + points += 2; + } + } + vertices[off+i].x = (stbtt_int16) x; + } + + // now load y coordinates + y=0; + for (i=0; i < n; ++i) { + flags = vertices[off+i].type; + if (flags & 4) { + stbtt_int16 dy = *points++; + y += (flags & 32) ? dy : -dy; // ??? + } else { + if (!(flags & 32)) { + y = y + (stbtt_int16) (points[0]*256 + points[1]); + points += 2; + } + } + vertices[off+i].y = (stbtt_int16) y; + } + + // now convert them to our format + num_vertices=0; + sx = sy = cx = cy = scx = scy = 0; + for (i=0; i < n; ++i) { + flags = vertices[off+i].type; + x = (stbtt_int16) vertices[off+i].x; + y = (stbtt_int16) vertices[off+i].y; + + if (next_move == i) { + if (i != 0) + num_vertices = stbtt__close_shape(vertices, num_vertices, was_off, start_off, sx,sy,scx,scy,cx,cy); + + // now start the new one + start_off = !(flags & 1); + if (start_off) { + // if we start off with an off-curve point, then when we need to find a point on the curve + // where we can start, and we need to save some state for when we wraparound. + scx = x; + scy = y; + if (!(vertices[off+i+1].type & 1)) { + // next point is also a curve point, so interpolate an on-point curve + sx = (x + (stbtt_int32) vertices[off+i+1].x) >> 1; + sy = (y + (stbtt_int32) vertices[off+i+1].y) >> 1; + } else { + // otherwise just use the next point as our start point + sx = (stbtt_int32) vertices[off+i+1].x; + sy = (stbtt_int32) vertices[off+i+1].y; + ++i; // we're using point i+1 as the starting point, so skip it + } + } else { + sx = x; + sy = y; + } + stbtt_setvertex(&vertices[num_vertices++], STBTT_vmove,sx,sy,0,0); + was_off = 0; + next_move = 1 + ttUSHORT(endPtsOfContours+j*2); + ++j; + } else { + if (!(flags & 1)) { // if it's a curve + if (was_off) // two off-curve control points in a row means interpolate an on-curve midpoint + stbtt_setvertex(&vertices[num_vertices++], STBTT_vcurve, (cx+x)>>1, (cy+y)>>1, cx, cy); + cx = x; + cy = y; + was_off = 1; + } else { + if (was_off) + stbtt_setvertex(&vertices[num_vertices++], STBTT_vcurve, x,y, cx, cy); + else + stbtt_setvertex(&vertices[num_vertices++], STBTT_vline, x,y,0,0); + was_off = 0; + } + } + } + num_vertices = stbtt__close_shape(vertices, num_vertices, was_off, start_off, sx,sy,scx,scy,cx,cy); + } else if (numberOfContours == -1) { + // Compound shapes. + int more = 1; + stbtt_uint8 *comp = data + g + 10; + num_vertices = 0; + vertices = 0; + while (more) { + stbtt_uint16 flags, gidx; + int comp_num_verts = 0, i; + stbtt_vertex *comp_verts = 0, *tmp = 0; + float mtx[6] = {1,0,0,1,0,0}, m, n; + + flags = ttSHORT(comp); comp+=2; + gidx = ttSHORT(comp); comp+=2; + + if (flags & 2) { // XY values + if (flags & 1) { // shorts + mtx[4] = ttSHORT(comp); comp+=2; + mtx[5] = ttSHORT(comp); comp+=2; + } else { + mtx[4] = ttCHAR(comp); comp+=1; + mtx[5] = ttCHAR(comp); comp+=1; + } + } + else { + // @TODO handle matching point + STBTT_assert(0); + } + if (flags & (1<<3)) { // WE_HAVE_A_SCALE + mtx[0] = mtx[3] = ttSHORT(comp)/16384.0f; comp+=2; + mtx[1] = mtx[2] = 0; + } else if (flags & (1<<6)) { // WE_HAVE_AN_X_AND_YSCALE + mtx[0] = ttSHORT(comp)/16384.0f; comp+=2; + mtx[1] = mtx[2] = 0; + mtx[3] = ttSHORT(comp)/16384.0f; comp+=2; + } else if (flags & (1<<7)) { // WE_HAVE_A_TWO_BY_TWO + mtx[0] = ttSHORT(comp)/16384.0f; comp+=2; + mtx[1] = ttSHORT(comp)/16384.0f; comp+=2; + mtx[2] = ttSHORT(comp)/16384.0f; comp+=2; + mtx[3] = ttSHORT(comp)/16384.0f; comp+=2; + } + + // Find transformation scales. + m = (float) STBTT_sqrt(mtx[0]*mtx[0] + mtx[1]*mtx[1]); + n = (float) STBTT_sqrt(mtx[2]*mtx[2] + mtx[3]*mtx[3]); + + // Get indexed glyph. + comp_num_verts = stbtt_GetGlyphShape(info, gidx, &comp_verts); + if (comp_num_verts > 0) { + // Transform vertices. + for (i = 0; i < comp_num_verts; ++i) { + stbtt_vertex* v = &comp_verts[i]; + stbtt_vertex_type x,y; + x=v->x; y=v->y; + v->x = (stbtt_vertex_type)(m * (mtx[0]*x + mtx[2]*y + mtx[4])); + v->y = (stbtt_vertex_type)(n * (mtx[1]*x + mtx[3]*y + mtx[5])); + x=v->cx; y=v->cy; + v->cx = (stbtt_vertex_type)(m * (mtx[0]*x + mtx[2]*y + mtx[4])); + v->cy = (stbtt_vertex_type)(n * (mtx[1]*x + mtx[3]*y + mtx[5])); + } + // Append vertices. + tmp = (stbtt_vertex*)STBTT_malloc((num_vertices+comp_num_verts)*sizeof(stbtt_vertex), info->userdata); + if (!tmp) { + if (vertices) STBTT_free(vertices, info->userdata); + if (comp_verts) STBTT_free(comp_verts, info->userdata); + return 0; + } + if (num_vertices > 0) STBTT_memcpy(tmp, vertices, num_vertices*sizeof(stbtt_vertex)); + STBTT_memcpy(tmp+num_vertices, comp_verts, comp_num_verts*sizeof(stbtt_vertex)); + if (vertices) STBTT_free(vertices, info->userdata); + vertices = tmp; + STBTT_free(comp_verts, info->userdata); + num_vertices += comp_num_verts; + } + // More components ? + more = flags & (1<<5); + } + } else if (numberOfContours < 0) { + // @TODO other compound variations? + STBTT_assert(0); + } else { + // numberOfCounters == 0, do nothing + } + + *pvertices = vertices; + return num_vertices; +} + +typedef struct +{ + int bounds; + int started; + float first_x, first_y; + float x, y; + stbtt_int32 min_x, max_x, min_y, max_y; + + stbtt_vertex *pvertices; + int num_vertices; +} stbtt__csctx; + +#define STBTT__CSCTX_INIT(bounds) {bounds,0, 0,0, 0,0, 0,0,0,0, NULL, 0} + +static void stbtt__track_vertex(stbtt__csctx *c, stbtt_int32 x, stbtt_int32 y) +{ + if (x > c->max_x || !c->started) c->max_x = x; + if (y > c->max_y || !c->started) c->max_y = y; + if (x < c->min_x || !c->started) c->min_x = x; + if (y < c->min_y || !c->started) c->min_y = y; + c->started = 1; +} + +static void stbtt__csctx_v(stbtt__csctx *c, stbtt_uint8 type, stbtt_int32 x, stbtt_int32 y, stbtt_int32 cx, stbtt_int32 cy, stbtt_int32 cx1, stbtt_int32 cy1) +{ + if (c->bounds) { + stbtt__track_vertex(c, x, y); + if (type == STBTT_vcubic) { + stbtt__track_vertex(c, cx, cy); + stbtt__track_vertex(c, cx1, cy1); + } + } else { + stbtt_setvertex(&c->pvertices[c->num_vertices], type, x, y, cx, cy); + c->pvertices[c->num_vertices].cx1 = (stbtt_int16) cx1; + c->pvertices[c->num_vertices].cy1 = (stbtt_int16) cy1; + } + c->num_vertices++; +} + +static void stbtt__csctx_close_shape(stbtt__csctx *ctx) +{ + if (ctx->first_x != ctx->x || ctx->first_y != ctx->y) + stbtt__csctx_v(ctx, STBTT_vline, (int)ctx->first_x, (int)ctx->first_y, 0, 0, 0, 0); +} + +static void stbtt__csctx_rmove_to(stbtt__csctx *ctx, float dx, float dy) +{ + stbtt__csctx_close_shape(ctx); + ctx->first_x = ctx->x = ctx->x + dx; + ctx->first_y = ctx->y = ctx->y + dy; + stbtt__csctx_v(ctx, STBTT_vmove, (int)ctx->x, (int)ctx->y, 0, 0, 0, 0); +} + +static void stbtt__csctx_rline_to(stbtt__csctx *ctx, float dx, float dy) +{ + ctx->x += dx; + ctx->y += dy; + stbtt__csctx_v(ctx, STBTT_vline, (int)ctx->x, (int)ctx->y, 0, 0, 0, 0); +} + +static void stbtt__csctx_rccurve_to(stbtt__csctx *ctx, float dx1, float dy1, float dx2, float dy2, float dx3, float dy3) +{ + float cx1 = ctx->x + dx1; + float cy1 = ctx->y + dy1; + float cx2 = cx1 + dx2; + float cy2 = cy1 + dy2; + ctx->x = cx2 + dx3; + ctx->y = cy2 + dy3; + stbtt__csctx_v(ctx, STBTT_vcubic, (int)ctx->x, (int)ctx->y, (int)cx1, (int)cy1, (int)cx2, (int)cy2); +} + +static stbtt__buf stbtt__get_subr(stbtt__buf idx, int n) +{ + int count = stbtt__cff_index_count(&idx); + int bias = 107; + if (count >= 33900) + bias = 32768; + else if (count >= 1240) + bias = 1131; + n += bias; + if (n < 0 || n >= count) + return stbtt__new_buf(NULL, 0); + return stbtt__cff_index_get(idx, n); +} + +static stbtt__buf stbtt__cid_get_glyph_subrs(const stbtt_fontinfo *info, int glyph_index) +{ + stbtt__buf fdselect = info->fdselect; + int nranges, start, end, v, fmt, fdselector = -1, i; + + stbtt__buf_seek(&fdselect, 0); + fmt = stbtt__buf_get8(&fdselect); + if (fmt == 0) { + // untested + stbtt__buf_skip(&fdselect, glyph_index); + fdselector = stbtt__buf_get8(&fdselect); + } else if (fmt == 3) { + nranges = stbtt__buf_get16(&fdselect); + start = stbtt__buf_get16(&fdselect); + for (i = 0; i < nranges; i++) { + v = stbtt__buf_get8(&fdselect); + end = stbtt__buf_get16(&fdselect); + if (glyph_index >= start && glyph_index < end) { + fdselector = v; + break; + } + start = end; + } + } + if (fdselector == -1) stbtt__new_buf(NULL, 0); + return stbtt__get_subrs(info->cff, stbtt__cff_index_get(info->fontdicts, fdselector)); +} + +static int stbtt__run_charstring(const stbtt_fontinfo *info, int glyph_index, stbtt__csctx *c) +{ + int in_header = 1, maskbits = 0, subr_stack_height = 0, sp = 0, v, i, b0; + int has_subrs = 0, clear_stack; + float s[48]; + stbtt__buf subr_stack[10], subrs = info->subrs, b; + float f; + +#define STBTT__CSERR(s) (0) + + // this currently ignores the initial width value, which isn't needed if we have hmtx + b = stbtt__cff_index_get(info->charstrings, glyph_index); + while (b.cursor < b.size) { + i = 0; + clear_stack = 1; + b0 = stbtt__buf_get8(&b); + switch (b0) { + // @TODO implement hinting + case 0x13: // hintmask + case 0x14: // cntrmask + if (in_header) + maskbits += (sp / 2); // implicit "vstem" + in_header = 0; + stbtt__buf_skip(&b, (maskbits + 7) / 8); + break; + + case 0x01: // hstem + case 0x03: // vstem + case 0x12: // hstemhm + case 0x17: // vstemhm + maskbits += (sp / 2); + break; + + case 0x15: // rmoveto + in_header = 0; + if (sp < 2) return STBTT__CSERR("rmoveto stack"); + stbtt__csctx_rmove_to(c, s[sp-2], s[sp-1]); + break; + case 0x04: // vmoveto + in_header = 0; + if (sp < 1) return STBTT__CSERR("vmoveto stack"); + stbtt__csctx_rmove_to(c, 0, s[sp-1]); + break; + case 0x16: // hmoveto + in_header = 0; + if (sp < 1) return STBTT__CSERR("hmoveto stack"); + stbtt__csctx_rmove_to(c, s[sp-1], 0); + break; + + case 0x05: // rlineto + if (sp < 2) return STBTT__CSERR("rlineto stack"); + for (; i + 1 < sp; i += 2) + stbtt__csctx_rline_to(c, s[i], s[i+1]); + break; + + // hlineto/vlineto and vhcurveto/hvcurveto alternate horizontal and vertical + // starting from a different place. + + case 0x07: // vlineto + if (sp < 1) return STBTT__CSERR("vlineto stack"); + goto vlineto; + case 0x06: // hlineto + if (sp < 1) return STBTT__CSERR("hlineto stack"); + for (;;) { + if (i >= sp) break; + stbtt__csctx_rline_to(c, s[i], 0); + i++; + vlineto: + if (i >= sp) break; + stbtt__csctx_rline_to(c, 0, s[i]); + i++; + } + break; + + case 0x1F: // hvcurveto + if (sp < 4) return STBTT__CSERR("hvcurveto stack"); + goto hvcurveto; + case 0x1E: // vhcurveto + if (sp < 4) return STBTT__CSERR("vhcurveto stack"); + for (;;) { + if (i + 3 >= sp) break; + stbtt__csctx_rccurve_to(c, 0, s[i], s[i+1], s[i+2], s[i+3], (sp - i == 5) ? s[i + 4] : 0.0f); + i += 4; + hvcurveto: + if (i + 3 >= sp) break; + stbtt__csctx_rccurve_to(c, s[i], 0, s[i+1], s[i+2], (sp - i == 5) ? s[i+4] : 0.0f, s[i+3]); + i += 4; + } + break; + + case 0x08: // rrcurveto + if (sp < 6) return STBTT__CSERR("rcurveline stack"); + for (; i + 5 < sp; i += 6) + stbtt__csctx_rccurve_to(c, s[i], s[i+1], s[i+2], s[i+3], s[i+4], s[i+5]); + break; + + case 0x18: // rcurveline + if (sp < 8) return STBTT__CSERR("rcurveline stack"); + for (; i + 5 < sp - 2; i += 6) + stbtt__csctx_rccurve_to(c, s[i], s[i+1], s[i+2], s[i+3], s[i+4], s[i+5]); + if (i + 1 >= sp) return STBTT__CSERR("rcurveline stack"); + stbtt__csctx_rline_to(c, s[i], s[i+1]); + break; + + case 0x19: // rlinecurve + if (sp < 8) return STBTT__CSERR("rlinecurve stack"); + for (; i + 1 < sp - 6; i += 2) + stbtt__csctx_rline_to(c, s[i], s[i+1]); + if (i + 5 >= sp) return STBTT__CSERR("rlinecurve stack"); + stbtt__csctx_rccurve_to(c, s[i], s[i+1], s[i+2], s[i+3], s[i+4], s[i+5]); + break; + + case 0x1A: // vvcurveto + case 0x1B: // hhcurveto + if (sp < 4) return STBTT__CSERR("(vv|hh)curveto stack"); + f = 0.0; + if (sp & 1) { f = s[i]; i++; } + for (; i + 3 < sp; i += 4) { + if (b0 == 0x1B) + stbtt__csctx_rccurve_to(c, s[i], f, s[i+1], s[i+2], s[i+3], 0.0); + else + stbtt__csctx_rccurve_to(c, f, s[i], s[i+1], s[i+2], 0.0, s[i+3]); + f = 0.0; + } + break; + + case 0x0A: // callsubr + if (!has_subrs) { + if (info->fdselect.size) + subrs = stbtt__cid_get_glyph_subrs(info, glyph_index); + has_subrs = 1; + } + // fallthrough + case 0x1D: // callgsubr + if (sp < 1) return STBTT__CSERR("call(g|)subr stack"); + v = (int) s[--sp]; + if (subr_stack_height >= 10) return STBTT__CSERR("recursion limit"); + subr_stack[subr_stack_height++] = b; + b = stbtt__get_subr(b0 == 0x0A ? subrs : info->gsubrs, v); + if (b.size == 0) return STBTT__CSERR("subr not found"); + b.cursor = 0; + clear_stack = 0; + break; + + case 0x0B: // return + if (subr_stack_height <= 0) return STBTT__CSERR("return outside subr"); + b = subr_stack[--subr_stack_height]; + clear_stack = 0; + break; + + case 0x0E: // endchar + stbtt__csctx_close_shape(c); + return 1; + + case 0x0C: { // two-byte escape + float dx1, dx2, dx3, dx4, dx5, dx6, dy1, dy2, dy3, dy4, dy5, dy6; + float dx, dy; + int b1 = stbtt__buf_get8(&b); + switch (b1) { + // @TODO These "flex" implementations ignore the flex-depth and resolution, + // and always draw beziers. + case 0x22: // hflex + if (sp < 7) return STBTT__CSERR("hflex stack"); + dx1 = s[0]; + dx2 = s[1]; + dy2 = s[2]; + dx3 = s[3]; + dx4 = s[4]; + dx5 = s[5]; + dx6 = s[6]; + stbtt__csctx_rccurve_to(c, dx1, 0, dx2, dy2, dx3, 0); + stbtt__csctx_rccurve_to(c, dx4, 0, dx5, -dy2, dx6, 0); + break; + + case 0x23: // flex + if (sp < 13) return STBTT__CSERR("flex stack"); + dx1 = s[0]; + dy1 = s[1]; + dx2 = s[2]; + dy2 = s[3]; + dx3 = s[4]; + dy3 = s[5]; + dx4 = s[6]; + dy4 = s[7]; + dx5 = s[8]; + dy5 = s[9]; + dx6 = s[10]; + dy6 = s[11]; + //fd is s[12] + stbtt__csctx_rccurve_to(c, dx1, dy1, dx2, dy2, dx3, dy3); + stbtt__csctx_rccurve_to(c, dx4, dy4, dx5, dy5, dx6, dy6); + break; + + case 0x24: // hflex1 + if (sp < 9) return STBTT__CSERR("hflex1 stack"); + dx1 = s[0]; + dy1 = s[1]; + dx2 = s[2]; + dy2 = s[3]; + dx3 = s[4]; + dx4 = s[5]; + dx5 = s[6]; + dy5 = s[7]; + dx6 = s[8]; + stbtt__csctx_rccurve_to(c, dx1, dy1, dx2, dy2, dx3, 0); + stbtt__csctx_rccurve_to(c, dx4, 0, dx5, dy5, dx6, -(dy1+dy2+dy5)); + break; + + case 0x25: // flex1 + if (sp < 11) return STBTT__CSERR("flex1 stack"); + dx1 = s[0]; + dy1 = s[1]; + dx2 = s[2]; + dy2 = s[3]; + dx3 = s[4]; + dy3 = s[5]; + dx4 = s[6]; + dy4 = s[7]; + dx5 = s[8]; + dy5 = s[9]; + dx6 = dy6 = s[10]; + dx = dx1+dx2+dx3+dx4+dx5; + dy = dy1+dy2+dy3+dy4+dy5; + if (STBTT_fabs(dx) > STBTT_fabs(dy)) + dy6 = -dy; + else + dx6 = -dx; + stbtt__csctx_rccurve_to(c, dx1, dy1, dx2, dy2, dx3, dy3); + stbtt__csctx_rccurve_to(c, dx4, dy4, dx5, dy5, dx6, dy6); + break; + + default: + return STBTT__CSERR("unimplemented"); + } + } break; + + default: + if (b0 != 255 && b0 != 28 && (b0 < 32 || b0 > 254)) + return STBTT__CSERR("reserved operator"); + + // push immediate + if (b0 == 255) { + f = (float)(stbtt_int32)stbtt__buf_get32(&b) / 0x10000; + } else { + stbtt__buf_skip(&b, -1); + f = (float)(stbtt_int16)stbtt__cff_int(&b); + } + if (sp >= 48) return STBTT__CSERR("push stack overflow"); + s[sp++] = f; + clear_stack = 0; + break; + } + if (clear_stack) sp = 0; + } + return STBTT__CSERR("no endchar"); + +#undef STBTT__CSERR +} + +static int stbtt__GetGlyphShapeT2(const stbtt_fontinfo *info, int glyph_index, stbtt_vertex **pvertices) +{ + // runs the charstring twice, once to count and once to output (to avoid realloc) + stbtt__csctx count_ctx = STBTT__CSCTX_INIT(1); + stbtt__csctx output_ctx = STBTT__CSCTX_INIT(0); + if (stbtt__run_charstring(info, glyph_index, &count_ctx)) { + *pvertices = (stbtt_vertex*)STBTT_malloc(count_ctx.num_vertices*sizeof(stbtt_vertex), info->userdata); + output_ctx.pvertices = *pvertices; + if (stbtt__run_charstring(info, glyph_index, &output_ctx)) { + STBTT_assert(output_ctx.num_vertices == count_ctx.num_vertices); + return output_ctx.num_vertices; + } + } + *pvertices = NULL; + return 0; +} + +static int stbtt__GetGlyphInfoT2(const stbtt_fontinfo *info, int glyph_index, int *x0, int *y0, int *x1, int *y1) +{ + stbtt__csctx c = STBTT__CSCTX_INIT(1); + int r = stbtt__run_charstring(info, glyph_index, &c); + if (x0) *x0 = r ? c.min_x : 0; + if (y0) *y0 = r ? c.min_y : 0; + if (x1) *x1 = r ? c.max_x : 0; + if (y1) *y1 = r ? c.max_y : 0; + return r ? c.num_vertices : 0; +} + +STBTT_DEF int stbtt_GetGlyphShape(const stbtt_fontinfo *info, int glyph_index, stbtt_vertex **pvertices) +{ + if (!info->cff.size) + return stbtt__GetGlyphShapeTT(info, glyph_index, pvertices); + else + return stbtt__GetGlyphShapeT2(info, glyph_index, pvertices); +} + +STBTT_DEF void stbtt_GetGlyphHMetrics(const stbtt_fontinfo *info, int glyph_index, int *advanceWidth, int *leftSideBearing) +{ + stbtt_uint16 numOfLongHorMetrics = ttUSHORT(info->data+info->hhea + 34); + if (glyph_index < numOfLongHorMetrics) { + if (advanceWidth) *advanceWidth = ttSHORT(info->data + info->hmtx + 4*glyph_index); + if (leftSideBearing) *leftSideBearing = ttSHORT(info->data + info->hmtx + 4*glyph_index + 2); + } else { + if (advanceWidth) *advanceWidth = ttSHORT(info->data + info->hmtx + 4*(numOfLongHorMetrics-1)); + if (leftSideBearing) *leftSideBearing = ttSHORT(info->data + info->hmtx + 4*numOfLongHorMetrics + 2*(glyph_index - numOfLongHorMetrics)); + } +} + +static int stbtt__GetGlyphKernInfoAdvance(const stbtt_fontinfo *info, int glyph1, int glyph2) +{ + stbtt_uint8 *data = info->data + info->kern; + stbtt_uint32 needle, straw; + int l, r, m; + + // we only look at the first table. it must be 'horizontal' and format 0. + if (!info->kern) + return 0; + if (ttUSHORT(data+2) < 1) // number of tables, need at least 1 + return 0; + if (ttUSHORT(data+8) != 1) // horizontal flag must be set in format + return 0; + + l = 0; + r = ttUSHORT(data+10) - 1; + needle = glyph1 << 16 | glyph2; + while (l <= r) { + m = (l + r) >> 1; + straw = ttULONG(data+18+(m*6)); // note: unaligned read + if (needle < straw) + r = m - 1; + else if (needle > straw) + l = m + 1; + else + return ttSHORT(data+22+(m*6)); + } + return 0; +} + +static stbtt_int32 stbtt__GetCoverageIndex(stbtt_uint8 *coverageTable, int glyph) +{ + stbtt_uint16 coverageFormat = ttUSHORT(coverageTable); + switch(coverageFormat) { + case 1: { + stbtt_uint16 glyphCount = ttUSHORT(coverageTable + 2); + + // Binary search. + stbtt_int32 l=0, r=glyphCount-1, m; + int straw, needle=glyph; + while (l <= r) { + stbtt_uint8 *glyphArray = coverageTable + 4; + stbtt_uint16 glyphID; + m = (l + r) >> 1; + glyphID = ttUSHORT(glyphArray + 2 * m); + straw = glyphID; + if (needle < straw) + r = m - 1; + else if (needle > straw) + l = m + 1; + else { + return m; + } + } + } break; + + case 2: { + stbtt_uint16 rangeCount = ttUSHORT(coverageTable + 2); + stbtt_uint8 *rangeArray = coverageTable + 4; + + // Binary search. + stbtt_int32 l=0, r=rangeCount-1, m; + int strawStart, strawEnd, needle=glyph; + while (l <= r) { + stbtt_uint8 *rangeRecord; + m = (l + r) >> 1; + rangeRecord = rangeArray + 6 * m; + strawStart = ttUSHORT(rangeRecord); + strawEnd = ttUSHORT(rangeRecord + 2); + if (needle < strawStart) + r = m - 1; + else if (needle > strawEnd) + l = m + 1; + else { + stbtt_uint16 startCoverageIndex = ttUSHORT(rangeRecord + 4); + return startCoverageIndex + glyph - strawStart; + } + } + } break; + + default: { + // There are no other cases. + STBTT_assert(0); + } break; + } + + return -1; +} + +static stbtt_int32 stbtt__GetGlyphClass(stbtt_uint8 *classDefTable, int glyph) +{ + stbtt_uint16 classDefFormat = ttUSHORT(classDefTable); + switch(classDefFormat) + { + case 1: { + stbtt_uint16 startGlyphID = ttUSHORT(classDefTable + 2); + stbtt_uint16 glyphCount = ttUSHORT(classDefTable + 4); + stbtt_uint8 *classDef1ValueArray = classDefTable + 6; + + if (glyph >= startGlyphID && glyph < startGlyphID + glyphCount) + return (stbtt_int32)ttUSHORT(classDef1ValueArray + 2 * (glyph - startGlyphID)); + + classDefTable = classDef1ValueArray + 2 * glyphCount; + } break; + + case 2: { + stbtt_uint16 classRangeCount = ttUSHORT(classDefTable + 2); + stbtt_uint8 *classRangeRecords = classDefTable + 4; + + // Binary search. + stbtt_int32 l=0, r=classRangeCount-1, m; + int strawStart, strawEnd, needle=glyph; + while (l <= r) { + stbtt_uint8 *classRangeRecord; + m = (l + r) >> 1; + classRangeRecord = classRangeRecords + 6 * m; + strawStart = ttUSHORT(classRangeRecord); + strawEnd = ttUSHORT(classRangeRecord + 2); + if (needle < strawStart) + r = m - 1; + else if (needle > strawEnd) + l = m + 1; + else + return (stbtt_int32)ttUSHORT(classRangeRecord + 4); + } + + classDefTable = classRangeRecords + 6 * classRangeCount; + } break; + + default: { + // There are no other cases. + STBTT_assert(0); + } break; + } + + return -1; +} + +// Define to STBTT_assert(x) if you want to break on unimplemented formats. +#define STBTT_GPOS_TODO_assert(x) + +static stbtt_int32 stbtt__GetGlyphGPOSInfoAdvance(const stbtt_fontinfo *info, int glyph1, int glyph2) +{ + stbtt_uint16 lookupListOffset; + stbtt_uint8 *lookupList; + stbtt_uint16 lookupCount; + stbtt_uint8 *data; + stbtt_int32 i; + + if (!info->gpos) return 0; + + data = info->data + info->gpos; + + if (ttUSHORT(data+0) != 1) return 0; // Major version 1 + if (ttUSHORT(data+2) != 0) return 0; // Minor version 0 + + lookupListOffset = ttUSHORT(data+8); + lookupList = data + lookupListOffset; + lookupCount = ttUSHORT(lookupList); + + for (i=0; i> 1; + pairValue = pairValueArray + (2 + valueRecordPairSizeInBytes) * m; + secondGlyph = ttUSHORT(pairValue); + straw = secondGlyph; + if (needle < straw) + r = m - 1; + else if (needle > straw) + l = m + 1; + else { + stbtt_int16 xAdvance = ttSHORT(pairValue + 2); + return xAdvance; + } + } + } break; + + case 2: { + stbtt_uint16 valueFormat1 = ttUSHORT(table + 4); + stbtt_uint16 valueFormat2 = ttUSHORT(table + 6); + + stbtt_uint16 classDef1Offset = ttUSHORT(table + 8); + stbtt_uint16 classDef2Offset = ttUSHORT(table + 10); + int glyph1class = stbtt__GetGlyphClass(table + classDef1Offset, glyph1); + int glyph2class = stbtt__GetGlyphClass(table + classDef2Offset, glyph2); + + stbtt_uint16 class1Count = ttUSHORT(table + 12); + stbtt_uint16 class2Count = ttUSHORT(table + 14); + STBTT_assert(glyph1class < class1Count); + STBTT_assert(glyph2class < class2Count); + + // TODO: Support more formats. + STBTT_GPOS_TODO_assert(valueFormat1 == 4); + if (valueFormat1 != 4) return 0; + STBTT_GPOS_TODO_assert(valueFormat2 == 0); + if (valueFormat2 != 0) return 0; + + if (glyph1class >= 0 && glyph1class < class1Count && glyph2class >= 0 && glyph2class < class2Count) { + stbtt_uint8 *class1Records = table + 16; + stbtt_uint8 *class2Records = class1Records + 2 * (glyph1class * class2Count); + stbtt_int16 xAdvance = ttSHORT(class2Records + 2 * glyph2class); + return xAdvance; + } + } break; + + default: { + // There are no other cases. + STBTT_assert(0); + break; + }; + } + } + break; + }; + + default: + // TODO: Implement other stuff. + break; + } + } + + return 0; +} + +STBTT_DEF int stbtt_GetGlyphKernAdvance(const stbtt_fontinfo *info, int g1, int g2) +{ + int xAdvance = 0; + + if (info->gpos) + xAdvance += stbtt__GetGlyphGPOSInfoAdvance(info, g1, g2); + + if (info->kern) + xAdvance += stbtt__GetGlyphKernInfoAdvance(info, g1, g2); + + return xAdvance; +} + +STBTT_DEF int stbtt_GetCodepointKernAdvance(const stbtt_fontinfo *info, int ch1, int ch2) +{ + if (!info->kern && !info->gpos) // if no kerning table, don't waste time looking up both codepoint->glyphs + return 0; + return stbtt_GetGlyphKernAdvance(info, stbtt_FindGlyphIndex(info,ch1), stbtt_FindGlyphIndex(info,ch2)); +} + +STBTT_DEF void stbtt_GetCodepointHMetrics(const stbtt_fontinfo *info, int codepoint, int *advanceWidth, int *leftSideBearing) +{ + stbtt_GetGlyphHMetrics(info, stbtt_FindGlyphIndex(info,codepoint), advanceWidth, leftSideBearing); +} + +STBTT_DEF void stbtt_GetFontVMetrics(const stbtt_fontinfo *info, int *ascent, int *descent, int *lineGap) +{ + if (ascent ) *ascent = ttSHORT(info->data+info->hhea + 4); + if (descent) *descent = ttSHORT(info->data+info->hhea + 6); + if (lineGap) *lineGap = ttSHORT(info->data+info->hhea + 8); +} + +STBTT_DEF int stbtt_GetFontVMetricsOS2(const stbtt_fontinfo *info, int *typoAscent, int *typoDescent, int *typoLineGap) +{ + int tab = stbtt__find_table(info->data, info->fontstart, "OS/2"); + if (!tab) + return 0; + if (typoAscent ) *typoAscent = ttSHORT(info->data+tab + 68); + if (typoDescent) *typoDescent = ttSHORT(info->data+tab + 70); + if (typoLineGap) *typoLineGap = ttSHORT(info->data+tab + 72); + return 1; +} + +STBTT_DEF void stbtt_GetFontBoundingBox(const stbtt_fontinfo *info, int *x0, int *y0, int *x1, int *y1) +{ + *x0 = ttSHORT(info->data + info->head + 36); + *y0 = ttSHORT(info->data + info->head + 38); + *x1 = ttSHORT(info->data + info->head + 40); + *y1 = ttSHORT(info->data + info->head + 42); +} + +STBTT_DEF float stbtt_ScaleForPixelHeight(const stbtt_fontinfo *info, float height) +{ + int fheight = ttSHORT(info->data + info->hhea + 4) - ttSHORT(info->data + info->hhea + 6); + return (float) height / fheight; +} + +STBTT_DEF float stbtt_ScaleForMappingEmToPixels(const stbtt_fontinfo *info, float pixels) +{ + int unitsPerEm = ttUSHORT(info->data + info->head + 18); + return pixels / unitsPerEm; +} + +STBTT_DEF void stbtt_FreeShape(const stbtt_fontinfo *info, stbtt_vertex *v) +{ + STBTT_free(v, info->userdata); +} + +////////////////////////////////////////////////////////////////////////////// +// +// antialiasing software rasterizer +// + +STBTT_DEF void stbtt_GetGlyphBitmapBoxSubpixel(const stbtt_fontinfo *font, int glyph, float scale_x, float scale_y,float shift_x, float shift_y, int *ix0, int *iy0, int *ix1, int *iy1) +{ + int x0=0,y0=0,x1,y1; // =0 suppresses compiler warning + if (!stbtt_GetGlyphBox(font, glyph, &x0,&y0,&x1,&y1)) { + // e.g. space character + if (ix0) *ix0 = 0; + if (iy0) *iy0 = 0; + if (ix1) *ix1 = 0; + if (iy1) *iy1 = 0; + } else { + // move to integral bboxes (treating pixels as little squares, what pixels get touched)? + if (ix0) *ix0 = STBTT_ifloor( x0 * scale_x + shift_x); + if (iy0) *iy0 = STBTT_ifloor(-y1 * scale_y + shift_y); + if (ix1) *ix1 = STBTT_iceil ( x1 * scale_x + shift_x); + if (iy1) *iy1 = STBTT_iceil (-y0 * scale_y + shift_y); + } +} + +STBTT_DEF void stbtt_GetGlyphBitmapBox(const stbtt_fontinfo *font, int glyph, float scale_x, float scale_y, int *ix0, int *iy0, int *ix1, int *iy1) +{ + stbtt_GetGlyphBitmapBoxSubpixel(font, glyph, scale_x, scale_y,0.0f,0.0f, ix0, iy0, ix1, iy1); +} + +STBTT_DEF void stbtt_GetCodepointBitmapBoxSubpixel(const stbtt_fontinfo *font, int codepoint, float scale_x, float scale_y, float shift_x, float shift_y, int *ix0, int *iy0, int *ix1, int *iy1) +{ + stbtt_GetGlyphBitmapBoxSubpixel(font, stbtt_FindGlyphIndex(font,codepoint), scale_x, scale_y,shift_x,shift_y, ix0,iy0,ix1,iy1); +} + +STBTT_DEF void stbtt_GetCodepointBitmapBox(const stbtt_fontinfo *font, int codepoint, float scale_x, float scale_y, int *ix0, int *iy0, int *ix1, int *iy1) +{ + stbtt_GetCodepointBitmapBoxSubpixel(font, codepoint, scale_x, scale_y,0.0f,0.0f, ix0,iy0,ix1,iy1); +} + +////////////////////////////////////////////////////////////////////////////// +// +// Rasterizer + +typedef struct stbtt__hheap_chunk +{ + struct stbtt__hheap_chunk *next; +} stbtt__hheap_chunk; + +typedef struct stbtt__hheap +{ + struct stbtt__hheap_chunk *head; + void *first_free; + int num_remaining_in_head_chunk; +} stbtt__hheap; + +static void *stbtt__hheap_alloc(stbtt__hheap *hh, size_t size, void *userdata) +{ + if (hh->first_free) { + void *p = hh->first_free; + hh->first_free = * (void **) p; + return p; + } else { + if (hh->num_remaining_in_head_chunk == 0) { + int count = (size < 32 ? 2000 : size < 128 ? 800 : 100); + stbtt__hheap_chunk *c = (stbtt__hheap_chunk *) STBTT_malloc(sizeof(stbtt__hheap_chunk) + size * count, userdata); + if (c == NULL) + return NULL; + c->next = hh->head; + hh->head = c; + hh->num_remaining_in_head_chunk = count; + } + --hh->num_remaining_in_head_chunk; + return (char *) (hh->head) + sizeof(stbtt__hheap_chunk) + size * hh->num_remaining_in_head_chunk; + } +} + +static void stbtt__hheap_free(stbtt__hheap *hh, void *p) +{ + *(void **) p = hh->first_free; + hh->first_free = p; +} + +static void stbtt__hheap_cleanup(stbtt__hheap *hh, void *userdata) +{ + stbtt__hheap_chunk *c = hh->head; + while (c) { + stbtt__hheap_chunk *n = c->next; + STBTT_free(c, userdata); + c = n; + } +} + +typedef struct stbtt__edge { + float x0,y0, x1,y1; + int invert; +} stbtt__edge; + + +typedef struct stbtt__active_edge +{ + struct stbtt__active_edge *next; + #if STBTT_RASTERIZER_VERSION==1 + int x,dx; + float ey; + int direction; + #elif STBTT_RASTERIZER_VERSION==2 + float fx,fdx,fdy; + float direction; + float sy; + float ey; + #else + #error "Unrecognized value of STBTT_RASTERIZER_VERSION" + #endif +} stbtt__active_edge; + +#if STBTT_RASTERIZER_VERSION == 1 +#define STBTT_FIXSHIFT 10 +#define STBTT_FIX (1 << STBTT_FIXSHIFT) +#define STBTT_FIXMASK (STBTT_FIX-1) + +static stbtt__active_edge *stbtt__new_active(stbtt__hheap *hh, stbtt__edge *e, int off_x, float start_point, void *userdata) +{ + stbtt__active_edge *z = (stbtt__active_edge *) stbtt__hheap_alloc(hh, sizeof(*z), userdata); + float dxdy = (e->x1 - e->x0) / (e->y1 - e->y0); + STBTT_assert(z != NULL); + if (!z) return z; + + // round dx down to avoid overshooting + if (dxdy < 0) + z->dx = -STBTT_ifloor(STBTT_FIX * -dxdy); + else + z->dx = STBTT_ifloor(STBTT_FIX * dxdy); + + z->x = STBTT_ifloor(STBTT_FIX * e->x0 + z->dx * (start_point - e->y0)); // use z->dx so when we offset later it's by the same amount + z->x -= off_x * STBTT_FIX; + + z->ey = e->y1; + z->next = 0; + z->direction = e->invert ? 1 : -1; + return z; +} +#elif STBTT_RASTERIZER_VERSION == 2 +static stbtt__active_edge *stbtt__new_active(stbtt__hheap *hh, stbtt__edge *e, int off_x, float start_point, void *userdata) +{ + stbtt__active_edge *z = (stbtt__active_edge *) stbtt__hheap_alloc(hh, sizeof(*z), userdata); + float dxdy = (e->x1 - e->x0) / (e->y1 - e->y0); + STBTT_assert(z != NULL); + //STBTT_assert(e->y0 <= start_point); + if (!z) return z; + z->fdx = dxdy; + z->fdy = dxdy != 0.0f ? (1.0f/dxdy) : 0.0f; + z->fx = e->x0 + dxdy * (start_point - e->y0); + z->fx -= off_x; + z->direction = e->invert ? 1.0f : -1.0f; + z->sy = e->y0; + z->ey = e->y1; + z->next = 0; + return z; +} +#else +#error "Unrecognized value of STBTT_RASTERIZER_VERSION" +#endif + +#if STBTT_RASTERIZER_VERSION == 1 +// note: this routine clips fills that extend off the edges... ideally this +// wouldn't happen, but it could happen if the truetype glyph bounding boxes +// are wrong, or if the user supplies a too-small bitmap +static void stbtt__fill_active_edges(unsigned char *scanline, int len, stbtt__active_edge *e, int max_weight) +{ + // non-zero winding fill + int x0=0, w=0; + + while (e) { + if (w == 0) { + // if we're currently at zero, we need to record the edge start point + x0 = e->x; w += e->direction; + } else { + int x1 = e->x; w += e->direction; + // if we went to zero, we need to draw + if (w == 0) { + int i = x0 >> STBTT_FIXSHIFT; + int j = x1 >> STBTT_FIXSHIFT; + + if (i < len && j >= 0) { + if (i == j) { + // x0,x1 are the same pixel, so compute combined coverage + scanline[i] = scanline[i] + (stbtt_uint8) ((x1 - x0) * max_weight >> STBTT_FIXSHIFT); + } else { + if (i >= 0) // add antialiasing for x0 + scanline[i] = scanline[i] + (stbtt_uint8) (((STBTT_FIX - (x0 & STBTT_FIXMASK)) * max_weight) >> STBTT_FIXSHIFT); + else + i = -1; // clip + + if (j < len) // add antialiasing for x1 + scanline[j] = scanline[j] + (stbtt_uint8) (((x1 & STBTT_FIXMASK) * max_weight) >> STBTT_FIXSHIFT); + else + j = len; // clip + + for (++i; i < j; ++i) // fill pixels between x0 and x1 + scanline[i] = scanline[i] + (stbtt_uint8) max_weight; + } + } + } + } + + e = e->next; + } +} + +static void stbtt__rasterize_sorted_edges(stbtt__bitmap *result, stbtt__edge *e, int n, int vsubsample, int off_x, int off_y, void *userdata) +{ + stbtt__hheap hh = { 0, 0, 0 }; + stbtt__active_edge *active = NULL; + int y,j=0; + int max_weight = (255 / vsubsample); // weight per vertical scanline + int s; // vertical subsample index + unsigned char scanline_data[512], *scanline; + + if (result->w > 512) + scanline = (unsigned char *) STBTT_malloc(result->w, userdata); + else + scanline = scanline_data; + + y = off_y * vsubsample; + e[n].y0 = (off_y + result->h) * (float) vsubsample + 1; + + while (j < result->h) { + STBTT_memset(scanline, 0, result->w); + for (s=0; s < vsubsample; ++s) { + // find center of pixel for this scanline + float scan_y = y + 0.5f; + stbtt__active_edge **step = &active; + + // update all active edges; + // remove all active edges that terminate before the center of this scanline + while (*step) { + stbtt__active_edge * z = *step; + if (z->ey <= scan_y) { + *step = z->next; // delete from list + STBTT_assert(z->direction); + z->direction = 0; + stbtt__hheap_free(&hh, z); + } else { + z->x += z->dx; // advance to position for current scanline + step = &((*step)->next); // advance through list + } + } + + // resort the list if needed + for(;;) { + int changed=0; + step = &active; + while (*step && (*step)->next) { + if ((*step)->x > (*step)->next->x) { + stbtt__active_edge *t = *step; + stbtt__active_edge *q = t->next; + + t->next = q->next; + q->next = t; + *step = q; + changed = 1; + } + step = &(*step)->next; + } + if (!changed) break; + } + + // insert all edges that start before the center of this scanline -- omit ones that also end on this scanline + while (e->y0 <= scan_y) { + if (e->y1 > scan_y) { + stbtt__active_edge *z = stbtt__new_active(&hh, e, off_x, scan_y, userdata); + if (z != NULL) { + // find insertion point + if (active == NULL) + active = z; + else if (z->x < active->x) { + // insert at front + z->next = active; + active = z; + } else { + // find thing to insert AFTER + stbtt__active_edge *p = active; + while (p->next && p->next->x < z->x) + p = p->next; + // at this point, p->next->x is NOT < z->x + z->next = p->next; + p->next = z; + } + } + } + ++e; + } + + // now process all active edges in XOR fashion + if (active) + stbtt__fill_active_edges(scanline, result->w, active, max_weight); + + ++y; + } + STBTT_memcpy(result->pixels + j * result->stride, scanline, result->w); + ++j; + } + + stbtt__hheap_cleanup(&hh, userdata); + + if (scanline != scanline_data) + STBTT_free(scanline, userdata); +} + +#elif STBTT_RASTERIZER_VERSION == 2 + +// the edge passed in here does not cross the vertical line at x or the vertical line at x+1 +// (i.e. it has already been clipped to those) +static void stbtt__handle_clipped_edge(float *scanline, int x, stbtt__active_edge *e, float x0, float y0, float x1, float y1) +{ + if (y0 == y1) return; + STBTT_assert(y0 < y1); + STBTT_assert(e->sy <= e->ey); + if (y0 > e->ey) return; + if (y1 < e->sy) return; + if (y0 < e->sy) { + x0 += (x1-x0) * (e->sy - y0) / (y1-y0); + y0 = e->sy; + } + if (y1 > e->ey) { + x1 += (x1-x0) * (e->ey - y1) / (y1-y0); + y1 = e->ey; + } + + if (x0 == x) + STBTT_assert(x1 <= x+1); + else if (x0 == x+1) + STBTT_assert(x1 >= x); + else if (x0 <= x) + STBTT_assert(x1 <= x); + else if (x0 >= x+1) + STBTT_assert(x1 >= x+1); + else + STBTT_assert(x1 >= x && x1 <= x+1); + + if (x0 <= x && x1 <= x) + scanline[x] += e->direction * (y1-y0); + else if (x0 >= x+1 && x1 >= x+1) + ; + else { + STBTT_assert(x0 >= x && x0 <= x+1 && x1 >= x && x1 <= x+1); + scanline[x] += e->direction * (y1-y0) * (1-((x0-x)+(x1-x))/2); // coverage = 1 - average x position + } +} + +static void stbtt__fill_active_edges_new(float *scanline, float *scanline_fill, int len, stbtt__active_edge *e, float y_top) +{ + float y_bottom = y_top+1; + + while (e) { + // brute force every pixel + + // compute intersection points with top & bottom + STBTT_assert(e->ey >= y_top); + + if (e->fdx == 0) { + float x0 = e->fx; + if (x0 < len) { + if (x0 >= 0) { + stbtt__handle_clipped_edge(scanline,(int) x0,e, x0,y_top, x0,y_bottom); + stbtt__handle_clipped_edge(scanline_fill-1,(int) x0+1,e, x0,y_top, x0,y_bottom); + } else { + stbtt__handle_clipped_edge(scanline_fill-1,0,e, x0,y_top, x0,y_bottom); + } + } + } else { + float x0 = e->fx; + float dx = e->fdx; + float xb = x0 + dx; + float x_top, x_bottom; + float sy0,sy1; + float dy = e->fdy; + STBTT_assert(e->sy <= y_bottom && e->ey >= y_top); + + // compute endpoints of line segment clipped to this scanline (if the + // line segment starts on this scanline. x0 is the intersection of the + // line with y_top, but that may be off the line segment. + if (e->sy > y_top) { + x_top = x0 + dx * (e->sy - y_top); + sy0 = e->sy; + } else { + x_top = x0; + sy0 = y_top; + } + if (e->ey < y_bottom) { + x_bottom = x0 + dx * (e->ey - y_top); + sy1 = e->ey; + } else { + x_bottom = xb; + sy1 = y_bottom; + } + + if (x_top >= 0 && x_bottom >= 0 && x_top < len && x_bottom < len) { + // from here on, we don't have to range check x values + + if ((int) x_top == (int) x_bottom) { + float height; + // simple case, only spans one pixel + int x = (int) x_top; + height = sy1 - sy0; + STBTT_assert(x >= 0 && x < len); + scanline[x] += e->direction * (1-((x_top - x) + (x_bottom-x))/2) * height; + scanline_fill[x] += e->direction * height; // everything right of this pixel is filled + } else { + int x,x1,x2; + float y_crossing, step, sign, area; + // covers 2+ pixels + if (x_top > x_bottom) { + // flip scanline vertically; signed area is the same + float t; + sy0 = y_bottom - (sy0 - y_top); + sy1 = y_bottom - (sy1 - y_top); + t = sy0, sy0 = sy1, sy1 = t; + t = x_bottom, x_bottom = x_top, x_top = t; + dx = -dx; + dy = -dy; + t = x0, x0 = xb, xb = t; + } + + x1 = (int) x_top; + x2 = (int) x_bottom; + // compute intersection with y axis at x1+1 + y_crossing = (x1+1 - x0) * dy + y_top; + + sign = e->direction; + // area of the rectangle covered from y0..y_crossing + area = sign * (y_crossing-sy0); + // area of the triangle (x_top,y0), (x+1,y0), (x+1,y_crossing) + scanline[x1] += area * (1-((x_top - x1)+(x1+1-x1))/2); + + step = sign * dy; + for (x = x1+1; x < x2; ++x) { + scanline[x] += area + step/2; + area += step; + } + y_crossing += dy * (x2 - (x1+1)); + + STBTT_assert(STBTT_fabs(area) <= 1.01f); + + scanline[x2] += area + sign * (1-((x2-x2)+(x_bottom-x2))/2) * (sy1-y_crossing); + + scanline_fill[x2] += sign * (sy1-sy0); + } + } else { + // if edge goes outside of box we're drawing, we require + // clipping logic. since this does not match the intended use + // of this library, we use a different, very slow brute + // force implementation + int x; + for (x=0; x < len; ++x) { + // cases: + // + // there can be up to two intersections with the pixel. any intersection + // with left or right edges can be handled by splitting into two (or three) + // regions. intersections with top & bottom do not necessitate case-wise logic. + // + // the old way of doing this found the intersections with the left & right edges, + // then used some simple logic to produce up to three segments in sorted order + // from top-to-bottom. however, this had a problem: if an x edge was epsilon + // across the x border, then the corresponding y position might not be distinct + // from the other y segment, and it might ignored as an empty segment. to avoid + // that, we need to explicitly produce segments based on x positions. + + // rename variables to clearly-defined pairs + float y0 = y_top; + float x1 = (float) (x); + float x2 = (float) (x+1); + float x3 = xb; + float y3 = y_bottom; + + // x = e->x + e->dx * (y-y_top) + // (y-y_top) = (x - e->x) / e->dx + // y = (x - e->x) / e->dx + y_top + float y1 = (x - x0) / dx + y_top; + float y2 = (x+1 - x0) / dx + y_top; + + if (x0 < x1 && x3 > x2) { // three segments descending down-right + stbtt__handle_clipped_edge(scanline,x,e, x0,y0, x1,y1); + stbtt__handle_clipped_edge(scanline,x,e, x1,y1, x2,y2); + stbtt__handle_clipped_edge(scanline,x,e, x2,y2, x3,y3); + } else if (x3 < x1 && x0 > x2) { // three segments descending down-left + stbtt__handle_clipped_edge(scanline,x,e, x0,y0, x2,y2); + stbtt__handle_clipped_edge(scanline,x,e, x2,y2, x1,y1); + stbtt__handle_clipped_edge(scanline,x,e, x1,y1, x3,y3); + } else if (x0 < x1 && x3 > x1) { // two segments across x, down-right + stbtt__handle_clipped_edge(scanline,x,e, x0,y0, x1,y1); + stbtt__handle_clipped_edge(scanline,x,e, x1,y1, x3,y3); + } else if (x3 < x1 && x0 > x1) { // two segments across x, down-left + stbtt__handle_clipped_edge(scanline,x,e, x0,y0, x1,y1); + stbtt__handle_clipped_edge(scanline,x,e, x1,y1, x3,y3); + } else if (x0 < x2 && x3 > x2) { // two segments across x+1, down-right + stbtt__handle_clipped_edge(scanline,x,e, x0,y0, x2,y2); + stbtt__handle_clipped_edge(scanline,x,e, x2,y2, x3,y3); + } else if (x3 < x2 && x0 > x2) { // two segments across x+1, down-left + stbtt__handle_clipped_edge(scanline,x,e, x0,y0, x2,y2); + stbtt__handle_clipped_edge(scanline,x,e, x2,y2, x3,y3); + } else { // one segment + stbtt__handle_clipped_edge(scanline,x,e, x0,y0, x3,y3); + } + } + } + } + e = e->next; + } +} + +// directly AA rasterize edges w/o supersampling +static void stbtt__rasterize_sorted_edges(stbtt__bitmap *result, stbtt__edge *e, int n, int vsubsample, int off_x, int off_y, void *userdata) +{ + stbtt__hheap hh = { 0, 0, 0 }; + stbtt__active_edge *active = NULL; + int y,j=0, i; + float scanline_data[129], *scanline, *scanline2; + + STBTT__NOTUSED(vsubsample); + + if (result->w > 64) + scanline = (float *) STBTT_malloc((result->w*2+1) * sizeof(float), userdata); + else + scanline = scanline_data; + + scanline2 = scanline + result->w; + + y = off_y; + e[n].y0 = (float) (off_y + result->h) + 1; + + while (j < result->h) { + // find center of pixel for this scanline + float scan_y_top = y + 0.0f; + float scan_y_bottom = y + 1.0f; + stbtt__active_edge **step = &active; + + STBTT_memset(scanline , 0, result->w*sizeof(scanline[0])); + STBTT_memset(scanline2, 0, (result->w+1)*sizeof(scanline[0])); + + // update all active edges; + // remove all active edges that terminate before the top of this scanline + while (*step) { + stbtt__active_edge * z = *step; + if (z->ey <= scan_y_top) { + *step = z->next; // delete from list + STBTT_assert(z->direction); + z->direction = 0; + stbtt__hheap_free(&hh, z); + } else { + step = &((*step)->next); // advance through list + } + } + + // insert all edges that start before the bottom of this scanline + while (e->y0 <= scan_y_bottom) { + if (e->y0 != e->y1) { + stbtt__active_edge *z = stbtt__new_active(&hh, e, off_x, scan_y_top, userdata); + if (z != NULL) { + if (j == 0 && off_y != 0) { + if (z->ey < scan_y_top) { + // this can happen due to subpixel positioning and some kind of fp rounding error i think + z->ey = scan_y_top; + } + } + STBTT_assert(z->ey >= scan_y_top); // if we get really unlucky a tiny bit of an edge can be out of bounds + // insert at front + z->next = active; + active = z; + } + } + ++e; + } + + // now process all active edges + if (active) + stbtt__fill_active_edges_new(scanline, scanline2+1, result->w, active, scan_y_top); + + { + float sum = 0; + for (i=0; i < result->w; ++i) { + float k; + int m; + sum += scanline2[i]; + k = scanline[i] + sum; + k = (float) STBTT_fabs(k)*255 + 0.5f; + m = (int) k; + if (m > 255) m = 255; + result->pixels[j*result->stride + i] = (unsigned char) m; + } + } + // advance all the edges + step = &active; + while (*step) { + stbtt__active_edge *z = *step; + z->fx += z->fdx; // advance to position for current scanline + step = &((*step)->next); // advance through list + } + + ++y; + ++j; + } + + stbtt__hheap_cleanup(&hh, userdata); + + if (scanline != scanline_data) + STBTT_free(scanline, userdata); +} +#else +#error "Unrecognized value of STBTT_RASTERIZER_VERSION" +#endif + +#define STBTT__COMPARE(a,b) ((a)->y0 < (b)->y0) + +static void stbtt__sort_edges_ins_sort(stbtt__edge *p, int n) +{ + int i,j; + for (i=1; i < n; ++i) { + stbtt__edge t = p[i], *a = &t; + j = i; + while (j > 0) { + stbtt__edge *b = &p[j-1]; + int c = STBTT__COMPARE(a,b); + if (!c) break; + p[j] = p[j-1]; + --j; + } + if (i != j) + p[j] = t; + } +} + +static void stbtt__sort_edges_quicksort(stbtt__edge *p, int n) +{ + /* threshold for transitioning to insertion sort */ + while (n > 12) { + stbtt__edge t; + int c01,c12,c,m,i,j; + + /* compute median of three */ + m = n >> 1; + c01 = STBTT__COMPARE(&p[0],&p[m]); + c12 = STBTT__COMPARE(&p[m],&p[n-1]); + /* if 0 >= mid >= end, or 0 < mid < end, then use mid */ + if (c01 != c12) { + /* otherwise, we'll need to swap something else to middle */ + int z; + c = STBTT__COMPARE(&p[0],&p[n-1]); + /* 0>mid && midn => n; 0 0 */ + /* 0n: 0>n => 0; 0 n */ + z = (c == c12) ? 0 : n-1; + t = p[z]; + p[z] = p[m]; + p[m] = t; + } + /* now p[m] is the median-of-three */ + /* swap it to the beginning so it won't move around */ + t = p[0]; + p[0] = p[m]; + p[m] = t; + + /* partition loop */ + i=1; + j=n-1; + for(;;) { + /* handling of equality is crucial here */ + /* for sentinels & efficiency with duplicates */ + for (;;++i) { + if (!STBTT__COMPARE(&p[i], &p[0])) break; + } + for (;;--j) { + if (!STBTT__COMPARE(&p[0], &p[j])) break; + } + /* make sure we haven't crossed */ + if (i >= j) break; + t = p[i]; + p[i] = p[j]; + p[j] = t; + + ++i; + --j; + } + /* recurse on smaller side, iterate on larger */ + if (j < (n-i)) { + stbtt__sort_edges_quicksort(p,j); + p = p+i; + n = n-i; + } else { + stbtt__sort_edges_quicksort(p+i, n-i); + n = j; + } + } +} + +static void stbtt__sort_edges(stbtt__edge *p, int n) +{ + stbtt__sort_edges_quicksort(p, n); + stbtt__sort_edges_ins_sort(p, n); +} + +typedef struct +{ + float x,y; +} stbtt__point; + +static void stbtt__rasterize(stbtt__bitmap *result, stbtt__point *pts, int *wcount, int windings, float scale_x, float scale_y, float shift_x, float shift_y, int off_x, int off_y, int invert, void *userdata) +{ + float y_scale_inv = invert ? -scale_y : scale_y; + stbtt__edge *e; + int n,i,j,k,m; +#if STBTT_RASTERIZER_VERSION == 1 + int vsubsample = result->h < 8 ? 15 : 5; +#elif STBTT_RASTERIZER_VERSION == 2 + int vsubsample = 1; +#else + #error "Unrecognized value of STBTT_RASTERIZER_VERSION" +#endif + // vsubsample should divide 255 evenly; otherwise we won't reach full opacity + + // now we have to blow out the windings into explicit edge lists + n = 0; + for (i=0; i < windings; ++i) + n += wcount[i]; + + e = (stbtt__edge *) STBTT_malloc(sizeof(*e) * (n+1), userdata); // add an extra one as a sentinel + if (e == 0) return; + n = 0; + + m=0; + for (i=0; i < windings; ++i) { + stbtt__point *p = pts + m; + m += wcount[i]; + j = wcount[i]-1; + for (k=0; k < wcount[i]; j=k++) { + int a=k,b=j; + // skip the edge if horizontal + if (p[j].y == p[k].y) + continue; + // add edge from j to k to the list + e[n].invert = 0; + if (invert ? p[j].y > p[k].y : p[j].y < p[k].y) { + e[n].invert = 1; + a=j,b=k; + } + e[n].x0 = p[a].x * scale_x + shift_x; + e[n].y0 = (p[a].y * y_scale_inv + shift_y) * vsubsample; + e[n].x1 = p[b].x * scale_x + shift_x; + e[n].y1 = (p[b].y * y_scale_inv + shift_y) * vsubsample; + ++n; + } + } + + // now sort the edges by their highest point (should snap to integer, and then by x) + //STBTT_sort(e, n, sizeof(e[0]), stbtt__edge_compare); + stbtt__sort_edges(e, n); + + // now, traverse the scanlines and find the intersections on each scanline, use xor winding rule + stbtt__rasterize_sorted_edges(result, e, n, vsubsample, off_x, off_y, userdata); + + STBTT_free(e, userdata); +} + +static void stbtt__add_point(stbtt__point *points, int n, float x, float y) +{ + if (!points) return; // during first pass, it's unallocated + points[n].x = x; + points[n].y = y; +} + +// tessellate until threshold p is happy... @TODO warped to compensate for non-linear stretching +static int stbtt__tesselate_curve(stbtt__point *points, int *num_points, float x0, float y0, float x1, float y1, float x2, float y2, float objspace_flatness_squared, int n) +{ + // midpoint + float mx = (x0 + 2*x1 + x2)/4; + float my = (y0 + 2*y1 + y2)/4; + // versus directly drawn line + float dx = (x0+x2)/2 - mx; + float dy = (y0+y2)/2 - my; + if (n > 16) // 65536 segments on one curve better be enough! + return 1; + if (dx*dx+dy*dy > objspace_flatness_squared) { // half-pixel error allowed... need to be smaller if AA + stbtt__tesselate_curve(points, num_points, x0,y0, (x0+x1)/2.0f,(y0+y1)/2.0f, mx,my, objspace_flatness_squared,n+1); + stbtt__tesselate_curve(points, num_points, mx,my, (x1+x2)/2.0f,(y1+y2)/2.0f, x2,y2, objspace_flatness_squared,n+1); + } else { + stbtt__add_point(points, *num_points,x2,y2); + *num_points = *num_points+1; + } + return 1; +} + +static void stbtt__tesselate_cubic(stbtt__point *points, int *num_points, float x0, float y0, float x1, float y1, float x2, float y2, float x3, float y3, float objspace_flatness_squared, int n) +{ + // @TODO this "flatness" calculation is just made-up nonsense that seems to work well enough + float dx0 = x1-x0; + float dy0 = y1-y0; + float dx1 = x2-x1; + float dy1 = y2-y1; + float dx2 = x3-x2; + float dy2 = y3-y2; + float dx = x3-x0; + float dy = y3-y0; + float longlen = (float) (STBTT_sqrt(dx0*dx0+dy0*dy0)+STBTT_sqrt(dx1*dx1+dy1*dy1)+STBTT_sqrt(dx2*dx2+dy2*dy2)); + float shortlen = (float) STBTT_sqrt(dx*dx+dy*dy); + float flatness_squared = longlen*longlen-shortlen*shortlen; + + if (n > 16) // 65536 segments on one curve better be enough! + return; + + if (flatness_squared > objspace_flatness_squared) { + float x01 = (x0+x1)/2; + float y01 = (y0+y1)/2; + float x12 = (x1+x2)/2; + float y12 = (y1+y2)/2; + float x23 = (x2+x3)/2; + float y23 = (y2+y3)/2; + + float xa = (x01+x12)/2; + float ya = (y01+y12)/2; + float xb = (x12+x23)/2; + float yb = (y12+y23)/2; + + float mx = (xa+xb)/2; + float my = (ya+yb)/2; + + stbtt__tesselate_cubic(points, num_points, x0,y0, x01,y01, xa,ya, mx,my, objspace_flatness_squared,n+1); + stbtt__tesselate_cubic(points, num_points, mx,my, xb,yb, x23,y23, x3,y3, objspace_flatness_squared,n+1); + } else { + stbtt__add_point(points, *num_points,x3,y3); + *num_points = *num_points+1; + } +} + +// returns number of contours +static stbtt__point *stbtt_FlattenCurves(stbtt_vertex *vertices, int num_verts, float objspace_flatness, int **contour_lengths, int *num_contours, void *userdata) +{ + stbtt__point *points=0; + int num_points=0; + + float objspace_flatness_squared = objspace_flatness * objspace_flatness; + int i,n=0,start=0, pass; + + // count how many "moves" there are to get the contour count + for (i=0; i < num_verts; ++i) + if (vertices[i].type == STBTT_vmove) + ++n; + + *num_contours = n; + if (n == 0) return 0; + + *contour_lengths = (int *) STBTT_malloc(sizeof(**contour_lengths) * n, userdata); + + if (*contour_lengths == 0) { + *num_contours = 0; + return 0; + } + + // make two passes through the points so we don't need to realloc + for (pass=0; pass < 2; ++pass) { + float x=0,y=0; + if (pass == 1) { + points = (stbtt__point *) STBTT_malloc(num_points * sizeof(points[0]), userdata); + if (points == NULL) goto error; + } + num_points = 0; + n= -1; + for (i=0; i < num_verts; ++i) { + switch (vertices[i].type) { + case STBTT_vmove: + // start the next contour + if (n >= 0) + (*contour_lengths)[n] = num_points - start; + ++n; + start = num_points; + + x = vertices[i].x, y = vertices[i].y; + stbtt__add_point(points, num_points++, x,y); + break; + case STBTT_vline: + x = vertices[i].x, y = vertices[i].y; + stbtt__add_point(points, num_points++, x, y); + break; + case STBTT_vcurve: + stbtt__tesselate_curve(points, &num_points, x,y, + vertices[i].cx, vertices[i].cy, + vertices[i].x, vertices[i].y, + objspace_flatness_squared, 0); + x = vertices[i].x, y = vertices[i].y; + break; + case STBTT_vcubic: + stbtt__tesselate_cubic(points, &num_points, x,y, + vertices[i].cx, vertices[i].cy, + vertices[i].cx1, vertices[i].cy1, + vertices[i].x, vertices[i].y, + objspace_flatness_squared, 0); + x = vertices[i].x, y = vertices[i].y; + break; + } + } + (*contour_lengths)[n] = num_points - start; + } + + return points; +error: + STBTT_free(points, userdata); + STBTT_free(*contour_lengths, userdata); + *contour_lengths = 0; + *num_contours = 0; + return NULL; +} + +STBTT_DEF void stbtt_Rasterize(stbtt__bitmap *result, float flatness_in_pixels, stbtt_vertex *vertices, int num_verts, float scale_x, float scale_y, float shift_x, float shift_y, int x_off, int y_off, int invert, void *userdata) +{ + float scale = scale_x > scale_y ? scale_y : scale_x; + int winding_count = 0; + int *winding_lengths = NULL; + stbtt__point *windings = stbtt_FlattenCurves(vertices, num_verts, flatness_in_pixels / scale, &winding_lengths, &winding_count, userdata); + if (windings) { + stbtt__rasterize(result, windings, winding_lengths, winding_count, scale_x, scale_y, shift_x, shift_y, x_off, y_off, invert, userdata); + STBTT_free(winding_lengths, userdata); + STBTT_free(windings, userdata); + } +} + +STBTT_DEF void stbtt_FreeBitmap(unsigned char *bitmap, void *userdata) +{ + STBTT_free(bitmap, userdata); +} + +STBTT_DEF unsigned char *stbtt_GetGlyphBitmapSubpixel(const stbtt_fontinfo *info, float scale_x, float scale_y, float shift_x, float shift_y, int glyph, int *width, int *height, int *xoff, int *yoff) +{ + int ix0,iy0,ix1,iy1; + stbtt__bitmap gbm; + stbtt_vertex *vertices; + int num_verts = stbtt_GetGlyphShape(info, glyph, &vertices); + + if (scale_x == 0) scale_x = scale_y; + if (scale_y == 0) { + if (scale_x == 0) { + STBTT_free(vertices, info->userdata); + return NULL; + } + scale_y = scale_x; + } + + stbtt_GetGlyphBitmapBoxSubpixel(info, glyph, scale_x, scale_y, shift_x, shift_y, &ix0,&iy0,&ix1,&iy1); + + // now we get the size + gbm.w = (ix1 - ix0); + gbm.h = (iy1 - iy0); + gbm.pixels = NULL; // in case we error + + if (width ) *width = gbm.w; + if (height) *height = gbm.h; + if (xoff ) *xoff = ix0; + if (yoff ) *yoff = iy0; + + if (gbm.w && gbm.h) { + gbm.pixels = (unsigned char *) STBTT_malloc(gbm.w * gbm.h, info->userdata); + if (gbm.pixels) { + gbm.stride = gbm.w; + + stbtt_Rasterize(&gbm, 0.35f, vertices, num_verts, scale_x, scale_y, shift_x, shift_y, ix0, iy0, 1, info->userdata); + } + } + STBTT_free(vertices, info->userdata); + return gbm.pixels; +} + +STBTT_DEF unsigned char *stbtt_GetGlyphBitmap(const stbtt_fontinfo *info, float scale_x, float scale_y, int glyph, int *width, int *height, int *xoff, int *yoff) +{ + return stbtt_GetGlyphBitmapSubpixel(info, scale_x, scale_y, 0.0f, 0.0f, glyph, width, height, xoff, yoff); +} + +STBTT_DEF void stbtt_MakeGlyphBitmapSubpixel(const stbtt_fontinfo *info, unsigned char *output, int out_w, int out_h, int out_stride, float scale_x, float scale_y, float shift_x, float shift_y, int glyph) +{ + int ix0,iy0; + stbtt_vertex *vertices; + int num_verts = stbtt_GetGlyphShape(info, glyph, &vertices); + stbtt__bitmap gbm; + + stbtt_GetGlyphBitmapBoxSubpixel(info, glyph, scale_x, scale_y, shift_x, shift_y, &ix0,&iy0,0,0); + gbm.pixels = output; + gbm.w = out_w; + gbm.h = out_h; + gbm.stride = out_stride; + + if (gbm.w && gbm.h) + stbtt_Rasterize(&gbm, 0.35f, vertices, num_verts, scale_x, scale_y, shift_x, shift_y, ix0,iy0, 1, info->userdata); + + STBTT_free(vertices, info->userdata); +} + +STBTT_DEF void stbtt_MakeGlyphBitmap(const stbtt_fontinfo *info, unsigned char *output, int out_w, int out_h, int out_stride, float scale_x, float scale_y, int glyph) +{ + stbtt_MakeGlyphBitmapSubpixel(info, output, out_w, out_h, out_stride, scale_x, scale_y, 0.0f,0.0f, glyph); +} + +STBTT_DEF unsigned char *stbtt_GetCodepointBitmapSubpixel(const stbtt_fontinfo *info, float scale_x, float scale_y, float shift_x, float shift_y, int codepoint, int *width, int *height, int *xoff, int *yoff) +{ + return stbtt_GetGlyphBitmapSubpixel(info, scale_x, scale_y,shift_x,shift_y, stbtt_FindGlyphIndex(info,codepoint), width,height,xoff,yoff); +} + +STBTT_DEF void stbtt_MakeCodepointBitmapSubpixelPrefilter(const stbtt_fontinfo *info, unsigned char *output, int out_w, int out_h, int out_stride, float scale_x, float scale_y, float shift_x, float shift_y, int oversample_x, int oversample_y, float *sub_x, float *sub_y, int codepoint) +{ + stbtt_MakeGlyphBitmapSubpixelPrefilter(info, output, out_w, out_h, out_stride, scale_x, scale_y, shift_x, shift_y, oversample_x, oversample_y, sub_x, sub_y, stbtt_FindGlyphIndex(info,codepoint)); +} + +STBTT_DEF void stbtt_MakeCodepointBitmapSubpixel(const stbtt_fontinfo *info, unsigned char *output, int out_w, int out_h, int out_stride, float scale_x, float scale_y, float shift_x, float shift_y, int codepoint) +{ + stbtt_MakeGlyphBitmapSubpixel(info, output, out_w, out_h, out_stride, scale_x, scale_y, shift_x, shift_y, stbtt_FindGlyphIndex(info,codepoint)); +} + +STBTT_DEF unsigned char *stbtt_GetCodepointBitmap(const stbtt_fontinfo *info, float scale_x, float scale_y, int codepoint, int *width, int *height, int *xoff, int *yoff) +{ + return stbtt_GetCodepointBitmapSubpixel(info, scale_x, scale_y, 0.0f,0.0f, codepoint, width,height,xoff,yoff); +} + +STBTT_DEF void stbtt_MakeCodepointBitmap(const stbtt_fontinfo *info, unsigned char *output, int out_w, int out_h, int out_stride, float scale_x, float scale_y, int codepoint) +{ + stbtt_MakeCodepointBitmapSubpixel(info, output, out_w, out_h, out_stride, scale_x, scale_y, 0.0f,0.0f, codepoint); +} + +////////////////////////////////////////////////////////////////////////////// +// +// bitmap baking +// +// This is SUPER-CRAPPY packing to keep source code small + +static int stbtt_BakeFontBitmap_internal(unsigned char *data, int offset, // font location (use offset=0 for plain .ttf) + float pixel_height, // height of font in pixels + unsigned char *pixels, int pw, int ph, // bitmap to be filled in + int first_char, int num_chars, // characters to bake + stbtt_bakedchar *chardata) +{ + float scale; + int x,y,bottom_y, i; + stbtt_fontinfo f; + f.userdata = NULL; + if (!stbtt_InitFont(&f, data, offset)) + return -1; + STBTT_memset(pixels, 0, pw*ph); // background of 0 around pixels + x=y=1; + bottom_y = 1; + + scale = stbtt_ScaleForPixelHeight(&f, pixel_height); + + for (i=0; i < num_chars; ++i) { + int advance, lsb, x0,y0,x1,y1,gw,gh; + int g = stbtt_FindGlyphIndex(&f, first_char + i); + stbtt_GetGlyphHMetrics(&f, g, &advance, &lsb); + stbtt_GetGlyphBitmapBox(&f, g, scale,scale, &x0,&y0,&x1,&y1); + gw = x1-x0; + gh = y1-y0; + if (x + gw + 1 >= pw) + y = bottom_y, x = 1; // advance to next row + if (y + gh + 1 >= ph) // check if it fits vertically AFTER potentially moving to next row + return -i; + STBTT_assert(x+gw < pw); + STBTT_assert(y+gh < ph); + stbtt_MakeGlyphBitmap(&f, pixels+x+y*pw, gw,gh,pw, scale,scale, g); + chardata[i].x0 = (stbtt_int16) x; + chardata[i].y0 = (stbtt_int16) y; + chardata[i].x1 = (stbtt_int16) (x + gw); + chardata[i].y1 = (stbtt_int16) (y + gh); + chardata[i].xadvance = scale * advance; + chardata[i].xoff = (float) x0; + chardata[i].yoff = (float) y0; + x = x + gw + 1; + if (y+gh+1 > bottom_y) + bottom_y = y+gh+1; + } + return bottom_y; +} + +STBTT_DEF void stbtt_GetBakedQuad(const stbtt_bakedchar *chardata, int pw, int ph, int char_index, float *xpos, float *ypos, stbtt_aligned_quad *q, int opengl_fillrule) +{ + float d3d_bias = opengl_fillrule ? 0 : -0.5f; + float ipw = 1.0f / pw, iph = 1.0f / ph; + const stbtt_bakedchar *b = chardata + char_index; + int round_x = STBTT_ifloor((*xpos + b->xoff) + 0.5f); + int round_y = STBTT_ifloor((*ypos + b->yoff) + 0.5f); + + q->x0 = round_x + d3d_bias; + q->y0 = round_y + d3d_bias; + q->x1 = round_x + b->x1 - b->x0 + d3d_bias; + q->y1 = round_y + b->y1 - b->y0 + d3d_bias; + + q->s0 = b->x0 * ipw; + q->t0 = b->y0 * iph; + q->s1 = b->x1 * ipw; + q->t1 = b->y1 * iph; + + *xpos += b->xadvance; +} + +////////////////////////////////////////////////////////////////////////////// +// +// rectangle packing replacement routines if you don't have stb_rect_pack.h +// + +#ifndef STB_RECT_PACK_VERSION + +typedef int stbrp_coord; + +//////////////////////////////////////////////////////////////////////////////////// +// // +// // +// COMPILER WARNING ?!?!? // +// // +// // +// if you get a compile warning due to these symbols being defined more than // +// once, move #include "stb_rect_pack.h" before #include "stb_truetype.h" // +// // +//////////////////////////////////////////////////////////////////////////////////// + +typedef struct +{ + int width,height; + int x,y,bottom_y; +} stbrp_context; + +typedef struct +{ + unsigned char x; +} stbrp_node; + +struct stbrp_rect +{ + stbrp_coord x,y; + int id,w,h,was_packed; +}; + +static void stbrp_init_target(stbrp_context *con, int pw, int ph, stbrp_node *nodes, int num_nodes) +{ + con->width = pw; + con->height = ph; + con->x = 0; + con->y = 0; + con->bottom_y = 0; + STBTT__NOTUSED(nodes); + STBTT__NOTUSED(num_nodes); +} + +static void stbrp_pack_rects(stbrp_context *con, stbrp_rect *rects, int num_rects) +{ + int i; + for (i=0; i < num_rects; ++i) { + if (con->x + rects[i].w > con->width) { + con->x = 0; + con->y = con->bottom_y; + } + if (con->y + rects[i].h > con->height) + break; + rects[i].x = con->x; + rects[i].y = con->y; + rects[i].was_packed = 1; + con->x += rects[i].w; + if (con->y + rects[i].h > con->bottom_y) + con->bottom_y = con->y + rects[i].h; + } + for ( ; i < num_rects; ++i) + rects[i].was_packed = 0; +} +#endif + +////////////////////////////////////////////////////////////////////////////// +// +// bitmap baking +// +// This is SUPER-AWESOME (tm Ryan Gordon) packing using stb_rect_pack.h. If +// stb_rect_pack.h isn't available, it uses the BakeFontBitmap strategy. + +STBTT_DEF int stbtt_PackBegin(stbtt_pack_context *spc, unsigned char *pixels, int pw, int ph, int stride_in_bytes, int padding, void *alloc_context) +{ + stbrp_context *context = (stbrp_context *) STBTT_malloc(sizeof(*context) ,alloc_context); + int num_nodes = pw - padding; + stbrp_node *nodes = (stbrp_node *) STBTT_malloc(sizeof(*nodes ) * num_nodes,alloc_context); + + if (context == NULL || nodes == NULL) { + if (context != NULL) STBTT_free(context, alloc_context); + if (nodes != NULL) STBTT_free(nodes , alloc_context); + return 0; + } + + spc->user_allocator_context = alloc_context; + spc->width = pw; + spc->height = ph; + spc->pixels = pixels; + spc->pack_info = context; + spc->nodes = nodes; + spc->padding = padding; + spc->stride_in_bytes = stride_in_bytes != 0 ? stride_in_bytes : pw; + spc->h_oversample = 1; + spc->v_oversample = 1; + spc->skip_missing = 0; + + stbrp_init_target(context, pw-padding, ph-padding, nodes, num_nodes); + + if (pixels) + STBTT_memset(pixels, 0, pw*ph); // background of 0 around pixels + + return 1; +} + +STBTT_DEF void stbtt_PackEnd (stbtt_pack_context *spc) +{ + STBTT_free(spc->nodes , spc->user_allocator_context); + STBTT_free(spc->pack_info, spc->user_allocator_context); +} + +STBTT_DEF void stbtt_PackSetOversampling(stbtt_pack_context *spc, unsigned int h_oversample, unsigned int v_oversample) +{ + STBTT_assert(h_oversample <= STBTT_MAX_OVERSAMPLE); + STBTT_assert(v_oversample <= STBTT_MAX_OVERSAMPLE); + if (h_oversample <= STBTT_MAX_OVERSAMPLE) + spc->h_oversample = h_oversample; + if (v_oversample <= STBTT_MAX_OVERSAMPLE) + spc->v_oversample = v_oversample; +} + +STBTT_DEF void stbtt_PackSetSkipMissingCodepoints(stbtt_pack_context *spc, int skip) +{ + spc->skip_missing = skip; +} + +#define STBTT__OVER_MASK (STBTT_MAX_OVERSAMPLE-1) + +static void stbtt__h_prefilter(unsigned char *pixels, int w, int h, int stride_in_bytes, unsigned int kernel_width) +{ + unsigned char buffer[STBTT_MAX_OVERSAMPLE]; + int safe_w = w - kernel_width; + int j; + STBTT_memset(buffer, 0, STBTT_MAX_OVERSAMPLE); // suppress bogus warning from VS2013 -analyze + for (j=0; j < h; ++j) { + int i; + unsigned int total; + STBTT_memset(buffer, 0, kernel_width); + + total = 0; + + // make kernel_width a constant in common cases so compiler can optimize out the divide + switch (kernel_width) { + case 2: + for (i=0; i <= safe_w; ++i) { + total += pixels[i] - buffer[i & STBTT__OVER_MASK]; + buffer[(i+kernel_width) & STBTT__OVER_MASK] = pixels[i]; + pixels[i] = (unsigned char) (total / 2); + } + break; + case 3: + for (i=0; i <= safe_w; ++i) { + total += pixels[i] - buffer[i & STBTT__OVER_MASK]; + buffer[(i+kernel_width) & STBTT__OVER_MASK] = pixels[i]; + pixels[i] = (unsigned char) (total / 3); + } + break; + case 4: + for (i=0; i <= safe_w; ++i) { + total += pixels[i] - buffer[i & STBTT__OVER_MASK]; + buffer[(i+kernel_width) & STBTT__OVER_MASK] = pixels[i]; + pixels[i] = (unsigned char) (total / 4); + } + break; + case 5: + for (i=0; i <= safe_w; ++i) { + total += pixels[i] - buffer[i & STBTT__OVER_MASK]; + buffer[(i+kernel_width) & STBTT__OVER_MASK] = pixels[i]; + pixels[i] = (unsigned char) (total / 5); + } + break; + default: + for (i=0; i <= safe_w; ++i) { + total += pixels[i] - buffer[i & STBTT__OVER_MASK]; + buffer[(i+kernel_width) & STBTT__OVER_MASK] = pixels[i]; + pixels[i] = (unsigned char) (total / kernel_width); + } + break; + } + + for (; i < w; ++i) { + STBTT_assert(pixels[i] == 0); + total -= buffer[i & STBTT__OVER_MASK]; + pixels[i] = (unsigned char) (total / kernel_width); + } + + pixels += stride_in_bytes; + } +} + +static void stbtt__v_prefilter(unsigned char *pixels, int w, int h, int stride_in_bytes, unsigned int kernel_width) +{ + unsigned char buffer[STBTT_MAX_OVERSAMPLE]; + int safe_h = h - kernel_width; + int j; + STBTT_memset(buffer, 0, STBTT_MAX_OVERSAMPLE); // suppress bogus warning from VS2013 -analyze + for (j=0; j < w; ++j) { + int i; + unsigned int total; + STBTT_memset(buffer, 0, kernel_width); + + total = 0; + + // make kernel_width a constant in common cases so compiler can optimize out the divide + switch (kernel_width) { + case 2: + for (i=0; i <= safe_h; ++i) { + total += pixels[i*stride_in_bytes] - buffer[i & STBTT__OVER_MASK]; + buffer[(i+kernel_width) & STBTT__OVER_MASK] = pixels[i*stride_in_bytes]; + pixels[i*stride_in_bytes] = (unsigned char) (total / 2); + } + break; + case 3: + for (i=0; i <= safe_h; ++i) { + total += pixels[i*stride_in_bytes] - buffer[i & STBTT__OVER_MASK]; + buffer[(i+kernel_width) & STBTT__OVER_MASK] = pixels[i*stride_in_bytes]; + pixels[i*stride_in_bytes] = (unsigned char) (total / 3); + } + break; + case 4: + for (i=0; i <= safe_h; ++i) { + total += pixels[i*stride_in_bytes] - buffer[i & STBTT__OVER_MASK]; + buffer[(i+kernel_width) & STBTT__OVER_MASK] = pixels[i*stride_in_bytes]; + pixels[i*stride_in_bytes] = (unsigned char) (total / 4); + } + break; + case 5: + for (i=0; i <= safe_h; ++i) { + total += pixels[i*stride_in_bytes] - buffer[i & STBTT__OVER_MASK]; + buffer[(i+kernel_width) & STBTT__OVER_MASK] = pixels[i*stride_in_bytes]; + pixels[i*stride_in_bytes] = (unsigned char) (total / 5); + } + break; + default: + for (i=0; i <= safe_h; ++i) { + total += pixels[i*stride_in_bytes] - buffer[i & STBTT__OVER_MASK]; + buffer[(i+kernel_width) & STBTT__OVER_MASK] = pixels[i*stride_in_bytes]; + pixels[i*stride_in_bytes] = (unsigned char) (total / kernel_width); + } + break; + } + + for (; i < h; ++i) { + STBTT_assert(pixels[i*stride_in_bytes] == 0); + total -= buffer[i & STBTT__OVER_MASK]; + pixels[i*stride_in_bytes] = (unsigned char) (total / kernel_width); + } + + pixels += 1; + } +} + +static float stbtt__oversample_shift(int oversample) +{ + if (!oversample) + return 0.0f; + + // The prefilter is a box filter of width "oversample", + // which shifts phase by (oversample - 1)/2 pixels in + // oversampled space. We want to shift in the opposite + // direction to counter this. + return (float)-(oversample - 1) / (2.0f * (float)oversample); +} + +// rects array must be big enough to accommodate all characters in the given ranges +STBTT_DEF int stbtt_PackFontRangesGatherRects(stbtt_pack_context *spc, const stbtt_fontinfo *info, stbtt_pack_range *ranges, int num_ranges, stbrp_rect *rects) +{ + int i,j,k; + + k=0; + for (i=0; i < num_ranges; ++i) { + float fh = ranges[i].font_size; + float scale = fh > 0 ? stbtt_ScaleForPixelHeight(info, fh) : stbtt_ScaleForMappingEmToPixels(info, -fh); + ranges[i].h_oversample = (unsigned char) spc->h_oversample; + ranges[i].v_oversample = (unsigned char) spc->v_oversample; + for (j=0; j < ranges[i].num_chars; ++j) { + int x0,y0,x1,y1; + int codepoint = ranges[i].array_of_unicode_codepoints == NULL ? ranges[i].first_unicode_codepoint_in_range + j : ranges[i].array_of_unicode_codepoints[j]; + int glyph = stbtt_FindGlyphIndex(info, codepoint); + if (glyph == 0 && spc->skip_missing) { + rects[k].w = rects[k].h = 0; + } else { + stbtt_GetGlyphBitmapBoxSubpixel(info,glyph, + scale * spc->h_oversample, + scale * spc->v_oversample, + 0,0, + &x0,&y0,&x1,&y1); + rects[k].w = (stbrp_coord) (x1-x0 + spc->padding + spc->h_oversample-1); + rects[k].h = (stbrp_coord) (y1-y0 + spc->padding + spc->v_oversample-1); + } + ++k; + } + } + + return k; +} + +STBTT_DEF void stbtt_MakeGlyphBitmapSubpixelPrefilter(const stbtt_fontinfo *info, unsigned char *output, int out_w, int out_h, int out_stride, float scale_x, float scale_y, float shift_x, float shift_y, int prefilter_x, int prefilter_y, float *sub_x, float *sub_y, int glyph) +{ + stbtt_MakeGlyphBitmapSubpixel(info, + output, + out_w - (prefilter_x - 1), + out_h - (prefilter_y - 1), + out_stride, + scale_x, + scale_y, + shift_x, + shift_y, + glyph); + + if (prefilter_x > 1) + stbtt__h_prefilter(output, out_w, out_h, out_stride, prefilter_x); + + if (prefilter_y > 1) + stbtt__v_prefilter(output, out_w, out_h, out_stride, prefilter_y); + + *sub_x = stbtt__oversample_shift(prefilter_x); + *sub_y = stbtt__oversample_shift(prefilter_y); +} + +// rects array must be big enough to accommodate all characters in the given ranges +STBTT_DEF int stbtt_PackFontRangesRenderIntoRects(stbtt_pack_context *spc, const stbtt_fontinfo *info, stbtt_pack_range *ranges, int num_ranges, stbrp_rect *rects) +{ + int i,j,k, return_value = 1; + + // save current values + int old_h_over = spc->h_oversample; + int old_v_over = spc->v_oversample; + + k = 0; + for (i=0; i < num_ranges; ++i) { + float fh = ranges[i].font_size; + float scale = fh > 0 ? stbtt_ScaleForPixelHeight(info, fh) : stbtt_ScaleForMappingEmToPixels(info, -fh); + float recip_h,recip_v,sub_x,sub_y; + spc->h_oversample = ranges[i].h_oversample; + spc->v_oversample = ranges[i].v_oversample; + recip_h = 1.0f / spc->h_oversample; + recip_v = 1.0f / spc->v_oversample; + sub_x = stbtt__oversample_shift(spc->h_oversample); + sub_y = stbtt__oversample_shift(spc->v_oversample); + for (j=0; j < ranges[i].num_chars; ++j) { + stbrp_rect *r = &rects[k]; + if (r->was_packed && r->w != 0 && r->h != 0) { + stbtt_packedchar *bc = &ranges[i].chardata_for_range[j]; + int advance, lsb, x0,y0,x1,y1; + int codepoint = ranges[i].array_of_unicode_codepoints == NULL ? ranges[i].first_unicode_codepoint_in_range + j : ranges[i].array_of_unicode_codepoints[j]; + int glyph = stbtt_FindGlyphIndex(info, codepoint); + stbrp_coord pad = (stbrp_coord) spc->padding; + + // pad on left and top + r->x += pad; + r->y += pad; + r->w -= pad; + r->h -= pad; + stbtt_GetGlyphHMetrics(info, glyph, &advance, &lsb); + stbtt_GetGlyphBitmapBox(info, glyph, + scale * spc->h_oversample, + scale * spc->v_oversample, + &x0,&y0,&x1,&y1); + stbtt_MakeGlyphBitmapSubpixel(info, + spc->pixels + r->x + r->y*spc->stride_in_bytes, + r->w - spc->h_oversample+1, + r->h - spc->v_oversample+1, + spc->stride_in_bytes, + scale * spc->h_oversample, + scale * spc->v_oversample, + 0,0, + glyph); + + if (spc->h_oversample > 1) + stbtt__h_prefilter(spc->pixels + r->x + r->y*spc->stride_in_bytes, + r->w, r->h, spc->stride_in_bytes, + spc->h_oversample); + + if (spc->v_oversample > 1) + stbtt__v_prefilter(spc->pixels + r->x + r->y*spc->stride_in_bytes, + r->w, r->h, spc->stride_in_bytes, + spc->v_oversample); + + bc->x0 = (stbtt_int16) r->x; + bc->y0 = (stbtt_int16) r->y; + bc->x1 = (stbtt_int16) (r->x + r->w); + bc->y1 = (stbtt_int16) (r->y + r->h); + bc->xadvance = scale * advance; + bc->xoff = (float) x0 * recip_h + sub_x; + bc->yoff = (float) y0 * recip_v + sub_y; + bc->xoff2 = (x0 + r->w) * recip_h + sub_x; + bc->yoff2 = (y0 + r->h) * recip_v + sub_y; + } else { + return_value = 0; // if any fail, report failure + } + + ++k; + } + } + + // restore original values + spc->h_oversample = old_h_over; + spc->v_oversample = old_v_over; + + return return_value; +} + +STBTT_DEF void stbtt_PackFontRangesPackRects(stbtt_pack_context *spc, stbrp_rect *rects, int num_rects) +{ + stbrp_pack_rects((stbrp_context *) spc->pack_info, rects, num_rects); +} + +STBTT_DEF int stbtt_PackFontRanges(stbtt_pack_context *spc, const unsigned char *fontdata, int font_index, stbtt_pack_range *ranges, int num_ranges) +{ + stbtt_fontinfo info; + int i,j,n, return_value = 1; + //stbrp_context *context = (stbrp_context *) spc->pack_info; + stbrp_rect *rects; + + // flag all characters as NOT packed + for (i=0; i < num_ranges; ++i) + for (j=0; j < ranges[i].num_chars; ++j) + ranges[i].chardata_for_range[j].x0 = + ranges[i].chardata_for_range[j].y0 = + ranges[i].chardata_for_range[j].x1 = + ranges[i].chardata_for_range[j].y1 = 0; + + n = 0; + for (i=0; i < num_ranges; ++i) + n += ranges[i].num_chars; + + rects = (stbrp_rect *) STBTT_malloc(sizeof(*rects) * n, spc->user_allocator_context); + if (rects == NULL) + return 0; + + info.userdata = spc->user_allocator_context; + stbtt_InitFont(&info, fontdata, stbtt_GetFontOffsetForIndex(fontdata,font_index)); + + n = stbtt_PackFontRangesGatherRects(spc, &info, ranges, num_ranges, rects); + + stbtt_PackFontRangesPackRects(spc, rects, n); + + return_value = stbtt_PackFontRangesRenderIntoRects(spc, &info, ranges, num_ranges, rects); + + STBTT_free(rects, spc->user_allocator_context); + return return_value; +} + +STBTT_DEF int stbtt_PackFontRange(stbtt_pack_context *spc, const unsigned char *fontdata, int font_index, float font_size, + int first_unicode_codepoint_in_range, int num_chars_in_range, stbtt_packedchar *chardata_for_range) +{ + stbtt_pack_range range; + range.first_unicode_codepoint_in_range = first_unicode_codepoint_in_range; + range.array_of_unicode_codepoints = NULL; + range.num_chars = num_chars_in_range; + range.chardata_for_range = chardata_for_range; + range.font_size = font_size; + return stbtt_PackFontRanges(spc, fontdata, font_index, &range, 1); +} + +STBTT_DEF void stbtt_GetScaledFontVMetrics(const unsigned char *fontdata, int index, float size, float *ascent, float *descent, float *lineGap) +{ + int i_ascent, i_descent, i_lineGap; + float scale; + stbtt_fontinfo info; + stbtt_InitFont(&info, fontdata, stbtt_GetFontOffsetForIndex(fontdata, index)); + scale = size > 0 ? stbtt_ScaleForPixelHeight(&info, size) : stbtt_ScaleForMappingEmToPixels(&info, -size); + stbtt_GetFontVMetrics(&info, &i_ascent, &i_descent, &i_lineGap); + *ascent = (float) i_ascent * scale; + *descent = (float) i_descent * scale; + *lineGap = (float) i_lineGap * scale; +} + +STBTT_DEF void stbtt_GetPackedQuad(const stbtt_packedchar *chardata, int pw, int ph, int char_index, float *xpos, float *ypos, stbtt_aligned_quad *q, int align_to_integer) +{ + float ipw = 1.0f / pw, iph = 1.0f / ph; + const stbtt_packedchar *b = chardata + char_index; + + if (align_to_integer) { + float x = (float) STBTT_ifloor((*xpos + b->xoff) + 0.5f); + float y = (float) STBTT_ifloor((*ypos + b->yoff) + 0.5f); + q->x0 = x; + q->y0 = y; + q->x1 = x + b->xoff2 - b->xoff; + q->y1 = y + b->yoff2 - b->yoff; + } else { + q->x0 = *xpos + b->xoff; + q->y0 = *ypos + b->yoff; + q->x1 = *xpos + b->xoff2; + q->y1 = *ypos + b->yoff2; + } + + q->s0 = b->x0 * ipw; + q->t0 = b->y0 * iph; + q->s1 = b->x1 * ipw; + q->t1 = b->y1 * iph; + + *xpos += b->xadvance; +} + +////////////////////////////////////////////////////////////////////////////// +// +// sdf computation +// + +#define STBTT_min(a,b) ((a) < (b) ? (a) : (b)) +#define STBTT_max(a,b) ((a) < (b) ? (b) : (a)) + +static int stbtt__ray_intersect_bezier(float orig[2], float ray[2], float q0[2], float q1[2], float q2[2], float hits[2][2]) +{ + float q0perp = q0[1]*ray[0] - q0[0]*ray[1]; + float q1perp = q1[1]*ray[0] - q1[0]*ray[1]; + float q2perp = q2[1]*ray[0] - q2[0]*ray[1]; + float roperp = orig[1]*ray[0] - orig[0]*ray[1]; + + float a = q0perp - 2*q1perp + q2perp; + float b = q1perp - q0perp; + float c = q0perp - roperp; + + float s0 = 0., s1 = 0.; + int num_s = 0; + + if (a != 0.0) { + float discr = b*b - a*c; + if (discr > 0.0) { + float rcpna = -1 / a; + float d = (float) STBTT_sqrt(discr); + s0 = (b+d) * rcpna; + s1 = (b-d) * rcpna; + if (s0 >= 0.0 && s0 <= 1.0) + num_s = 1; + if (d > 0.0 && s1 >= 0.0 && s1 <= 1.0) { + if (num_s == 0) s0 = s1; + ++num_s; + } + } + } else { + // 2*b*s + c = 0 + // s = -c / (2*b) + s0 = c / (-2 * b); + if (s0 >= 0.0 && s0 <= 1.0) + num_s = 1; + } + + if (num_s == 0) + return 0; + else { + float rcp_len2 = 1 / (ray[0]*ray[0] + ray[1]*ray[1]); + float rayn_x = ray[0] * rcp_len2, rayn_y = ray[1] * rcp_len2; + + float q0d = q0[0]*rayn_x + q0[1]*rayn_y; + float q1d = q1[0]*rayn_x + q1[1]*rayn_y; + float q2d = q2[0]*rayn_x + q2[1]*rayn_y; + float rod = orig[0]*rayn_x + orig[1]*rayn_y; + + float q10d = q1d - q0d; + float q20d = q2d - q0d; + float q0rd = q0d - rod; + + hits[0][0] = q0rd + s0*(2.0f - 2.0f*s0)*q10d + s0*s0*q20d; + hits[0][1] = a*s0+b; + + if (num_s > 1) { + hits[1][0] = q0rd + s1*(2.0f - 2.0f*s1)*q10d + s1*s1*q20d; + hits[1][1] = a*s1+b; + return 2; + } else { + return 1; + } + } +} + +static int equal(float *a, float *b) +{ + return (a[0] == b[0] && a[1] == b[1]); +} + +static int stbtt__compute_crossings_x(float x, float y, int nverts, stbtt_vertex *verts) +{ + int i; + float orig[2], ray[2] = { 1, 0 }; + float y_frac; + int winding = 0; + + orig[0] = x; + orig[1] = y; + + // make sure y never passes through a vertex of the shape + y_frac = (float) STBTT_fmod(y, 1.0f); + if (y_frac < 0.01f) + y += 0.01f; + else if (y_frac > 0.99f) + y -= 0.01f; + orig[1] = y; + + // test a ray from (-infinity,y) to (x,y) + for (i=0; i < nverts; ++i) { + if (verts[i].type == STBTT_vline) { + int x0 = (int) verts[i-1].x, y0 = (int) verts[i-1].y; + int x1 = (int) verts[i ].x, y1 = (int) verts[i ].y; + if (y > STBTT_min(y0,y1) && y < STBTT_max(y0,y1) && x > STBTT_min(x0,x1)) { + float x_inter = (y - y0) / (y1 - y0) * (x1-x0) + x0; + if (x_inter < x) + winding += (y0 < y1) ? 1 : -1; + } + } + if (verts[i].type == STBTT_vcurve) { + int x0 = (int) verts[i-1].x , y0 = (int) verts[i-1].y ; + int x1 = (int) verts[i ].cx, y1 = (int) verts[i ].cy; + int x2 = (int) verts[i ].x , y2 = (int) verts[i ].y ; + int ax = STBTT_min(x0,STBTT_min(x1,x2)), ay = STBTT_min(y0,STBTT_min(y1,y2)); + int by = STBTT_max(y0,STBTT_max(y1,y2)); + if (y > ay && y < by && x > ax) { + float q0[2],q1[2],q2[2]; + float hits[2][2]; + q0[0] = (float)x0; + q0[1] = (float)y0; + q1[0] = (float)x1; + q1[1] = (float)y1; + q2[0] = (float)x2; + q2[1] = (float)y2; + if (equal(q0,q1) || equal(q1,q2)) { + x0 = (int)verts[i-1].x; + y0 = (int)verts[i-1].y; + x1 = (int)verts[i ].x; + y1 = (int)verts[i ].y; + if (y > STBTT_min(y0,y1) && y < STBTT_max(y0,y1) && x > STBTT_min(x0,x1)) { + float x_inter = (y - y0) / (y1 - y0) * (x1-x0) + x0; + if (x_inter < x) + winding += (y0 < y1) ? 1 : -1; + } + } else { + int num_hits = stbtt__ray_intersect_bezier(orig, ray, q0, q1, q2, hits); + if (num_hits >= 1) + if (hits[0][0] < 0) + winding += (hits[0][1] < 0 ? -1 : 1); + if (num_hits >= 2) + if (hits[1][0] < 0) + winding += (hits[1][1] < 0 ? -1 : 1); + } + } + } + } + return winding; +} + +static float stbtt__cuberoot( float x ) +{ + if (x<0) + return -(float) STBTT_pow(-x,1.0f/3.0f); + else + return (float) STBTT_pow( x,1.0f/3.0f); +} + +// x^3 + c*x^2 + b*x + a = 0 +static int stbtt__solve_cubic(float a, float b, float c, float* r) +{ + float s = -a / 3; + float p = b - a*a / 3; + float q = a * (2*a*a - 9*b) / 27 + c; + float p3 = p*p*p; + float d = q*q + 4*p3 / 27; + if (d >= 0) { + float z = (float) STBTT_sqrt(d); + float u = (-q + z) / 2; + float v = (-q - z) / 2; + u = stbtt__cuberoot(u); + v = stbtt__cuberoot(v); + r[0] = s + u + v; + return 1; + } else { + float u = (float) STBTT_sqrt(-p/3); + float v = (float) STBTT_acos(-STBTT_sqrt(-27/p3) * q / 2) / 3; // p3 must be negative, since d is negative + float m = (float) STBTT_cos(v); + float n = (float) STBTT_cos(v-3.141592/2)*1.732050808f; + r[0] = s + u * 2 * m; + r[1] = s - u * (m + n); + r[2] = s - u * (m - n); + + //STBTT_assert( STBTT_fabs(((r[0]+a)*r[0]+b)*r[0]+c) < 0.05f); // these asserts may not be safe at all scales, though they're in bezier t parameter units so maybe? + //STBTT_assert( STBTT_fabs(((r[1]+a)*r[1]+b)*r[1]+c) < 0.05f); + //STBTT_assert( STBTT_fabs(((r[2]+a)*r[2]+b)*r[2]+c) < 0.05f); + return 3; + } +} + +STBTT_DEF unsigned char * stbtt_GetGlyphSDF(const stbtt_fontinfo *info, float scale, int glyph, int padding, unsigned char onedge_value, float pixel_dist_scale, int *width, int *height, int *xoff, int *yoff) +{ + float scale_x = scale, scale_y = scale; + int ix0,iy0,ix1,iy1; + int w,h; + unsigned char *data; + + // if one scale is 0, use same scale for both + if (scale_x == 0) scale_x = scale_y; + if (scale_y == 0) { + if (scale_x == 0) return NULL; // if both scales are 0, return NULL + scale_y = scale_x; + } + + stbtt_GetGlyphBitmapBoxSubpixel(info, glyph, scale, scale, 0.0f,0.0f, &ix0,&iy0,&ix1,&iy1); + + // if empty, return NULL + if (ix0 == ix1 || iy0 == iy1) + return NULL; + + ix0 -= padding; + iy0 -= padding; + ix1 += padding; + iy1 += padding; + + w = (ix1 - ix0); + h = (iy1 - iy0); + + if (width ) *width = w; + if (height) *height = h; + if (xoff ) *xoff = ix0; + if (yoff ) *yoff = iy0; + + // invert for y-downwards bitmaps + scale_y = -scale_y; + + { + int x,y,i,j; + float *precompute; + stbtt_vertex *verts; + int num_verts = stbtt_GetGlyphShape(info, glyph, &verts); + data = (unsigned char *) STBTT_malloc(w * h, info->userdata); + precompute = (float *) STBTT_malloc(num_verts * sizeof(float), info->userdata); + + for (i=0,j=num_verts-1; i < num_verts; j=i++) { + if (verts[i].type == STBTT_vline) { + float x0 = verts[i].x*scale_x, y0 = verts[i].y*scale_y; + float x1 = verts[j].x*scale_x, y1 = verts[j].y*scale_y; + float dist = (float) STBTT_sqrt((x1-x0)*(x1-x0) + (y1-y0)*(y1-y0)); + precompute[i] = (dist == 0) ? 0.0f : 1.0f / dist; + } else if (verts[i].type == STBTT_vcurve) { + float x2 = verts[j].x *scale_x, y2 = verts[j].y *scale_y; + float x1 = verts[i].cx*scale_x, y1 = verts[i].cy*scale_y; + float x0 = verts[i].x *scale_x, y0 = verts[i].y *scale_y; + float bx = x0 - 2*x1 + x2, by = y0 - 2*y1 + y2; + float len2 = bx*bx + by*by; + if (len2 != 0.0f) + precompute[i] = 1.0f / (bx*bx + by*by); + else + precompute[i] = 0.0f; + } else + precompute[i] = 0.0f; + } + + for (y=iy0; y < iy1; ++y) { + for (x=ix0; x < ix1; ++x) { + float val; + float min_dist = 999999.0f; + float sx = (float) x + 0.5f; + float sy = (float) y + 0.5f; + float x_gspace = (sx / scale_x); + float y_gspace = (sy / scale_y); + + int winding = stbtt__compute_crossings_x(x_gspace, y_gspace, num_verts, verts); // @OPTIMIZE: this could just be a rasterization, but needs to be line vs. non-tesselated curves so a new path + + for (i=0; i < num_verts; ++i) { + float x0 = verts[i].x*scale_x, y0 = verts[i].y*scale_y; + + // check against every point here rather than inside line/curve primitives -- @TODO: wrong if multiple 'moves' in a row produce a garbage point, and given culling, probably more efficient to do within line/curve + float dist2 = (x0-sx)*(x0-sx) + (y0-sy)*(y0-sy); + if (dist2 < min_dist*min_dist) + min_dist = (float) STBTT_sqrt(dist2); + + if (verts[i].type == STBTT_vline) { + float x1 = verts[i-1].x*scale_x, y1 = verts[i-1].y*scale_y; + + // coarse culling against bbox + //if (sx > STBTT_min(x0,x1)-min_dist && sx < STBTT_max(x0,x1)+min_dist && + // sy > STBTT_min(y0,y1)-min_dist && sy < STBTT_max(y0,y1)+min_dist) + float dist = (float) STBTT_fabs((x1-x0)*(y0-sy) - (y1-y0)*(x0-sx)) * precompute[i]; + STBTT_assert(i != 0); + if (dist < min_dist) { + // check position along line + // x' = x0 + t*(x1-x0), y' = y0 + t*(y1-y0) + // minimize (x'-sx)*(x'-sx)+(y'-sy)*(y'-sy) + float dx = x1-x0, dy = y1-y0; + float px = x0-sx, py = y0-sy; + // minimize (px+t*dx)^2 + (py+t*dy)^2 = px*px + 2*px*dx*t + t^2*dx*dx + py*py + 2*py*dy*t + t^2*dy*dy + // derivative: 2*px*dx + 2*py*dy + (2*dx*dx+2*dy*dy)*t, set to 0 and solve + float t = -(px*dx + py*dy) / (dx*dx + dy*dy); + if (t >= 0.0f && t <= 1.0f) + min_dist = dist; + } + } else if (verts[i].type == STBTT_vcurve) { + float x2 = verts[i-1].x *scale_x, y2 = verts[i-1].y *scale_y; + float x1 = verts[i ].cx*scale_x, y1 = verts[i ].cy*scale_y; + float box_x0 = STBTT_min(STBTT_min(x0,x1),x2); + float box_y0 = STBTT_min(STBTT_min(y0,y1),y2); + float box_x1 = STBTT_max(STBTT_max(x0,x1),x2); + float box_y1 = STBTT_max(STBTT_max(y0,y1),y2); + // coarse culling against bbox to avoid computing cubic unnecessarily + if (sx > box_x0-min_dist && sx < box_x1+min_dist && sy > box_y0-min_dist && sy < box_y1+min_dist) { + int num=0; + float ax = x1-x0, ay = y1-y0; + float bx = x0 - 2*x1 + x2, by = y0 - 2*y1 + y2; + float mx = x0 - sx, my = y0 - sy; + float res[3],px,py,t,it; + float a_inv = precompute[i]; + if (a_inv == 0.0) { // if a_inv is 0, it's 2nd degree so use quadratic formula + float a = 3*(ax*bx + ay*by); + float b = 2*(ax*ax + ay*ay) + (mx*bx+my*by); + float c = mx*ax+my*ay; + if (a == 0.0) { // if a is 0, it's linear + if (b != 0.0) { + res[num++] = -c/b; + } + } else { + float discriminant = b*b - 4*a*c; + if (discriminant < 0) + num = 0; + else { + float root = (float) STBTT_sqrt(discriminant); + res[0] = (-b - root)/(2*a); + res[1] = (-b + root)/(2*a); + num = 2; // don't bother distinguishing 1-solution case, as code below will still work + } + } + } else { + float b = 3*(ax*bx + ay*by) * a_inv; // could precompute this as it doesn't depend on sample point + float c = (2*(ax*ax + ay*ay) + (mx*bx+my*by)) * a_inv; + float d = (mx*ax+my*ay) * a_inv; + num = stbtt__solve_cubic(b, c, d, res); + } + if (num >= 1 && res[0] >= 0.0f && res[0] <= 1.0f) { + t = res[0], it = 1.0f - t; + px = it*it*x0 + 2*t*it*x1 + t*t*x2; + py = it*it*y0 + 2*t*it*y1 + t*t*y2; + dist2 = (px-sx)*(px-sx) + (py-sy)*(py-sy); + if (dist2 < min_dist * min_dist) + min_dist = (float) STBTT_sqrt(dist2); + } + if (num >= 2 && res[1] >= 0.0f && res[1] <= 1.0f) { + t = res[1], it = 1.0f - t; + px = it*it*x0 + 2*t*it*x1 + t*t*x2; + py = it*it*y0 + 2*t*it*y1 + t*t*y2; + dist2 = (px-sx)*(px-sx) + (py-sy)*(py-sy); + if (dist2 < min_dist * min_dist) + min_dist = (float) STBTT_sqrt(dist2); + } + if (num >= 3 && res[2] >= 0.0f && res[2] <= 1.0f) { + t = res[2], it = 1.0f - t; + px = it*it*x0 + 2*t*it*x1 + t*t*x2; + py = it*it*y0 + 2*t*it*y1 + t*t*y2; + dist2 = (px-sx)*(px-sx) + (py-sy)*(py-sy); + if (dist2 < min_dist * min_dist) + min_dist = (float) STBTT_sqrt(dist2); + } + } + } + } + if (winding == 0) + min_dist = -min_dist; // if outside the shape, value is negative + val = onedge_value + pixel_dist_scale * min_dist; + if (val < 0) + val = 0; + else if (val > 255) + val = 255; + data[(y-iy0)*w+(x-ix0)] = (unsigned char) val; + } + } + STBTT_free(precompute, info->userdata); + STBTT_free(verts, info->userdata); + } + return data; +} + +STBTT_DEF unsigned char * stbtt_GetCodepointSDF(const stbtt_fontinfo *info, float scale, int codepoint, int padding, unsigned char onedge_value, float pixel_dist_scale, int *width, int *height, int *xoff, int *yoff) +{ + return stbtt_GetGlyphSDF(info, scale, stbtt_FindGlyphIndex(info, codepoint), padding, onedge_value, pixel_dist_scale, width, height, xoff, yoff); +} + +STBTT_DEF void stbtt_FreeSDF(unsigned char *bitmap, void *userdata) +{ + STBTT_free(bitmap, userdata); +} + +////////////////////////////////////////////////////////////////////////////// +// +// font name matching -- recommended not to use this +// + +// check if a utf8 string contains a prefix which is the utf16 string; if so return length of matching utf8 string +static stbtt_int32 stbtt__CompareUTF8toUTF16_bigendian_prefix(stbtt_uint8 *s1, stbtt_int32 len1, stbtt_uint8 *s2, stbtt_int32 len2) +{ + stbtt_int32 i=0; + + // convert utf16 to utf8 and compare the results while converting + while (len2) { + stbtt_uint16 ch = s2[0]*256 + s2[1]; + if (ch < 0x80) { + if (i >= len1) return -1; + if (s1[i++] != ch) return -1; + } else if (ch < 0x800) { + if (i+1 >= len1) return -1; + if (s1[i++] != 0xc0 + (ch >> 6)) return -1; + if (s1[i++] != 0x80 + (ch & 0x3f)) return -1; + } else if (ch >= 0xd800 && ch < 0xdc00) { + stbtt_uint32 c; + stbtt_uint16 ch2 = s2[2]*256 + s2[3]; + if (i+3 >= len1) return -1; + c = ((ch - 0xd800) << 10) + (ch2 - 0xdc00) + 0x10000; + if (s1[i++] != 0xf0 + (c >> 18)) return -1; + if (s1[i++] != 0x80 + ((c >> 12) & 0x3f)) return -1; + if (s1[i++] != 0x80 + ((c >> 6) & 0x3f)) return -1; + if (s1[i++] != 0x80 + ((c ) & 0x3f)) return -1; + s2 += 2; // plus another 2 below + len2 -= 2; + } else if (ch >= 0xdc00 && ch < 0xe000) { + return -1; + } else { + if (i+2 >= len1) return -1; + if (s1[i++] != 0xe0 + (ch >> 12)) return -1; + if (s1[i++] != 0x80 + ((ch >> 6) & 0x3f)) return -1; + if (s1[i++] != 0x80 + ((ch ) & 0x3f)) return -1; + } + s2 += 2; + len2 -= 2; + } + return i; +} + +static int stbtt_CompareUTF8toUTF16_bigendian_internal(char *s1, int len1, char *s2, int len2) +{ + return len1 == stbtt__CompareUTF8toUTF16_bigendian_prefix((stbtt_uint8*) s1, len1, (stbtt_uint8*) s2, len2); +} + +// returns results in whatever encoding you request... but note that 2-byte encodings +// will be BIG-ENDIAN... use stbtt_CompareUTF8toUTF16_bigendian() to compare +STBTT_DEF const char *stbtt_GetFontNameString(const stbtt_fontinfo *font, int *length, int platformID, int encodingID, int languageID, int nameID) +{ + stbtt_int32 i,count,stringOffset; + stbtt_uint8 *fc = font->data; + stbtt_uint32 offset = font->fontstart; + stbtt_uint32 nm = stbtt__find_table(fc, offset, "name"); + if (!nm) return NULL; + + count = ttUSHORT(fc+nm+2); + stringOffset = nm + ttUSHORT(fc+nm+4); + for (i=0; i < count; ++i) { + stbtt_uint32 loc = nm + 6 + 12 * i; + if (platformID == ttUSHORT(fc+loc+0) && encodingID == ttUSHORT(fc+loc+2) + && languageID == ttUSHORT(fc+loc+4) && nameID == ttUSHORT(fc+loc+6)) { + *length = ttUSHORT(fc+loc+8); + return (const char *) (fc+stringOffset+ttUSHORT(fc+loc+10)); + } + } + return NULL; +} + +static int stbtt__matchpair(stbtt_uint8 *fc, stbtt_uint32 nm, stbtt_uint8 *name, stbtt_int32 nlen, stbtt_int32 target_id, stbtt_int32 next_id) +{ + stbtt_int32 i; + stbtt_int32 count = ttUSHORT(fc+nm+2); + stbtt_int32 stringOffset = nm + ttUSHORT(fc+nm+4); + + for (i=0; i < count; ++i) { + stbtt_uint32 loc = nm + 6 + 12 * i; + stbtt_int32 id = ttUSHORT(fc+loc+6); + if (id == target_id) { + // find the encoding + stbtt_int32 platform = ttUSHORT(fc+loc+0), encoding = ttUSHORT(fc+loc+2), language = ttUSHORT(fc+loc+4); + + // is this a Unicode encoding? + if (platform == 0 || (platform == 3 && encoding == 1) || (platform == 3 && encoding == 10)) { + stbtt_int32 slen = ttUSHORT(fc+loc+8); + stbtt_int32 off = ttUSHORT(fc+loc+10); + + // check if there's a prefix match + stbtt_int32 matchlen = stbtt__CompareUTF8toUTF16_bigendian_prefix(name, nlen, fc+stringOffset+off,slen); + if (matchlen >= 0) { + // check for target_id+1 immediately following, with same encoding & language + if (i+1 < count && ttUSHORT(fc+loc+12+6) == next_id && ttUSHORT(fc+loc+12) == platform && ttUSHORT(fc+loc+12+2) == encoding && ttUSHORT(fc+loc+12+4) == language) { + slen = ttUSHORT(fc+loc+12+8); + off = ttUSHORT(fc+loc+12+10); + if (slen == 0) { + if (matchlen == nlen) + return 1; + } else if (matchlen < nlen && name[matchlen] == ' ') { + ++matchlen; + if (stbtt_CompareUTF8toUTF16_bigendian_internal((char*) (name+matchlen), nlen-matchlen, (char*)(fc+stringOffset+off),slen)) + return 1; + } + } else { + // if nothing immediately following + if (matchlen == nlen) + return 1; + } + } + } + + // @TODO handle other encodings + } + } + return 0; +} + +static int stbtt__matches(stbtt_uint8 *fc, stbtt_uint32 offset, stbtt_uint8 *name, stbtt_int32 flags) +{ + stbtt_int32 nlen = (stbtt_int32) STBTT_strlen((char *) name); + stbtt_uint32 nm,hd; + if (!stbtt__isfont(fc+offset)) return 0; + + // check italics/bold/underline flags in macStyle... + if (flags) { + hd = stbtt__find_table(fc, offset, "head"); + if ((ttUSHORT(fc+hd+44) & 7) != (flags & 7)) return 0; + } + + nm = stbtt__find_table(fc, offset, "name"); + if (!nm) return 0; + + if (flags) { + // if we checked the macStyle flags, then just check the family and ignore the subfamily + if (stbtt__matchpair(fc, nm, name, nlen, 16, -1)) return 1; + if (stbtt__matchpair(fc, nm, name, nlen, 1, -1)) return 1; + if (stbtt__matchpair(fc, nm, name, nlen, 3, -1)) return 1; + } else { + if (stbtt__matchpair(fc, nm, name, nlen, 16, 17)) return 1; + if (stbtt__matchpair(fc, nm, name, nlen, 1, 2)) return 1; + if (stbtt__matchpair(fc, nm, name, nlen, 3, -1)) return 1; + } + + return 0; +} + +static int stbtt_FindMatchingFont_internal(unsigned char *font_collection, char *name_utf8, stbtt_int32 flags) +{ + stbtt_int32 i; + for (i=0;;++i) { + stbtt_int32 off = stbtt_GetFontOffsetForIndex(font_collection, i); + if (off < 0) return off; + if (stbtt__matches((stbtt_uint8 *) font_collection, off, (stbtt_uint8*) name_utf8, flags)) + return off; + } +} + +#if defined(__GNUC__) || defined(__clang__) +#pragma GCC diagnostic push +#pragma GCC diagnostic ignored "-Wcast-qual" +#endif + +STBTT_DEF int stbtt_BakeFontBitmap(const unsigned char *data, int offset, + float pixel_height, unsigned char *pixels, int pw, int ph, + int first_char, int num_chars, stbtt_bakedchar *chardata) +{ + return stbtt_BakeFontBitmap_internal((unsigned char *) data, offset, pixel_height, pixels, pw, ph, first_char, num_chars, chardata); +} + +STBTT_DEF int stbtt_GetFontOffsetForIndex(const unsigned char *data, int index) +{ + return stbtt_GetFontOffsetForIndex_internal((unsigned char *) data, index); +} + +STBTT_DEF int stbtt_GetNumberOfFonts(const unsigned char *data) +{ + return stbtt_GetNumberOfFonts_internal((unsigned char *) data); +} + +STBTT_DEF int stbtt_InitFont(stbtt_fontinfo *info, const unsigned char *data, int offset) +{ + return stbtt_InitFont_internal(info, (unsigned char *) data, offset); +} + +STBTT_DEF int stbtt_FindMatchingFont(const unsigned char *fontdata, const char *name, int flags) +{ + return stbtt_FindMatchingFont_internal((unsigned char *) fontdata, (char *) name, flags); +} + +STBTT_DEF int stbtt_CompareUTF8toUTF16_bigendian(const char *s1, int len1, const char *s2, int len2) +{ + return stbtt_CompareUTF8toUTF16_bigendian_internal((char *) s1, len1, (char *) s2, len2); +} + +#if defined(__GNUC__) || defined(__clang__) +#pragma GCC diagnostic pop +#endif + +#endif // STB_TRUETYPE_IMPLEMENTATION + + +// FULL VERSION HISTORY +// +// 1.19 (2018-02-11) OpenType GPOS kerning (horizontal only), STBTT_fmod +// 1.18 (2018-01-29) add missing function +// 1.17 (2017-07-23) make more arguments const; doc fix +// 1.16 (2017-07-12) SDF support +// 1.15 (2017-03-03) make more arguments const +// 1.14 (2017-01-16) num-fonts-in-TTC function +// 1.13 (2017-01-02) support OpenType fonts, certain Apple fonts +// 1.12 (2016-10-25) suppress warnings about casting away const with -Wcast-qual +// 1.11 (2016-04-02) fix unused-variable warning +// 1.10 (2016-04-02) allow user-defined fabs() replacement +// fix memory leak if fontsize=0.0 +// fix warning from duplicate typedef +// 1.09 (2016-01-16) warning fix; avoid crash on outofmem; use alloc userdata for PackFontRanges +// 1.08 (2015-09-13) document stbtt_Rasterize(); fixes for vertical & horizontal edges +// 1.07 (2015-08-01) allow PackFontRanges to accept arrays of sparse codepoints; +// allow PackFontRanges to pack and render in separate phases; +// fix stbtt_GetFontOFfsetForIndex (never worked for non-0 input?); +// fixed an assert() bug in the new rasterizer +// replace assert() with STBTT_assert() in new rasterizer +// 1.06 (2015-07-14) performance improvements (~35% faster on x86 and x64 on test machine) +// also more precise AA rasterizer, except if shapes overlap +// remove need for STBTT_sort +// 1.05 (2015-04-15) fix misplaced definitions for STBTT_STATIC +// 1.04 (2015-04-15) typo in example +// 1.03 (2015-04-12) STBTT_STATIC, fix memory leak in new packing, various fixes +// 1.02 (2014-12-10) fix various warnings & compile issues w/ stb_rect_pack, C++ +// 1.01 (2014-12-08) fix subpixel position when oversampling to exactly match +// non-oversampled; STBTT_POINT_SIZE for packed case only +// 1.00 (2014-12-06) add new PackBegin etc. API, w/ support for oversampling +// 0.99 (2014-09-18) fix multiple bugs with subpixel rendering (ryg) +// 0.9 (2014-08-07) support certain mac/iOS fonts without an MS platformID +// 0.8b (2014-07-07) fix a warning +// 0.8 (2014-05-25) fix a few more warnings +// 0.7 (2013-09-25) bugfix: subpixel glyph bug fixed in 0.5 had come back +// 0.6c (2012-07-24) improve documentation +// 0.6b (2012-07-20) fix a few more warnings +// 0.6 (2012-07-17) fix warnings; added stbtt_ScaleForMappingEmToPixels, +// stbtt_GetFontBoundingBox, stbtt_IsGlyphEmpty +// 0.5 (2011-12-09) bugfixes: +// subpixel glyph renderer computed wrong bounding box +// first vertex of shape can be off-curve (FreeSans) +// 0.4b (2011-12-03) fixed an error in the font baking example +// 0.4 (2011-12-01) kerning, subpixel rendering (tor) +// bugfixes for: +// codepoint-to-glyph conversion using table fmt=12 +// codepoint-to-glyph conversion using table fmt=4 +// stbtt_GetBakedQuad with non-square texture (Zer) +// updated Hello World! sample to use kerning and subpixel +// fixed some warnings +// 0.3 (2009-06-24) cmap fmt=12, compound shapes (MM) +// userdata, malloc-from-userdata, non-zero fill (stb) +// 0.2 (2009-03-11) Fix unsigned/signed char warnings +// 0.1 (2009-03-09) First public release +// + +/* +------------------------------------------------------------------------------ +This software is available under 2 licenses -- choose whichever you prefer. +------------------------------------------------------------------------------ +ALTERNATIVE A - MIT License +Copyright (c) 2017 Sean Barrett +Permission is hereby granted, free of charge, to any person obtaining a copy of +this software and associated documentation files (the "Software"), to deal in +the Software without restriction, including without limitation the rights to +use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies +of the Software, and to permit persons to whom the Software is furnished to do +so, subject to the following conditions: +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. +------------------------------------------------------------------------------ +ALTERNATIVE B - Public Domain (www.unlicense.org) +This is free and unencumbered software released into the public domain. +Anyone is free to copy, modify, publish, use, compile, sell, or distribute this +software, either in source code form or as a compiled binary, for any purpose, +commercial or non-commercial, and by any means. +In jurisdictions that recognize copyright laws, the author or authors of this +software dedicate any and all copyright interest in the software to the public +domain. We make this dedication for the benefit of the public at large and to +the detriment of our heirs and successors. We intend this dedication to be an +overt act of relinquishment in perpetuity of all present and future rights to +this software under copyright law. +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN +ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION +WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. +------------------------------------------------------------------------------ +*/ From 26891e14ef474f3dc1e13974962a62b732d1c9e8 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Zolt=C3=A1n=20Nagy?= Date: Mon, 24 Jun 2019 22:36:33 +0100 Subject: [PATCH 05/15] Use c++14 mode to compile tcod_sys --- tcod_sys/build.rs | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/tcod_sys/build.rs b/tcod_sys/build.rs index faca6332e..4dfba8051 100644 --- a/tcod_sys/build.rs +++ b/tcod_sys/build.rs @@ -76,7 +76,7 @@ fn build_linux_static(_dst: &Path, libtcod_sources: &[& 'static str]) { config.define("NO_OPENGL", None); config.define("NDEBUG", None); config.flag("-fno-strict-aliasing"); - config.flag("-ansi"); + config.flag("-std=c++14"); build_libtcod_objects(config, libtcod_sources); } @@ -94,7 +94,7 @@ fn build_linux_dynamic(dst: &Path, libtcod_sources: &[& 'static str]) { config.define("NO_OPENGL", None); config.define("NDEBUG", None); config.flag("-fno-strict-aliasing"); - config.flag("-ansi"); + config.flag("-std=c++14"); build_libtcod_objects(config, libtcod_sources); } @@ -273,7 +273,7 @@ fn main() { config.define("NO_OPENGL", None); config.define("NDEBUG", None); config.flag("-fno-strict-aliasing"); - config.flag("-ansi"); + config.flag("-std=c++14"); build_libtcod_objects(config, libtcod_sources); } @@ -313,7 +313,7 @@ fn main() { // Build the DLL let mut config = cc::Build::new(); config.flag("-fno-strict-aliasing"); - config.flag("-ansi"); + config.flag("-std=c++14"); config.define("TCOD_SDL2", None); config.define("NO_OPENGL", None); config.define("NDEBUG", None); From 6c484b7524b8afd63fff90c69d7cfbb7c8bb1956 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Zolt=C3=A1n=20Nagy?= Date: Mon, 24 Jun 2019 22:39:35 +0100 Subject: [PATCH 06/15] Update top-level Cargo.toml with tcod_sys version --- Cargo.toml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Cargo.toml b/Cargo.toml index eeecd5295..2773b5e54 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -43,7 +43,7 @@ serialization = ["serde", "serde_derive"] [dependencies.tcod-sys] path = "tcod_sys" -version = "5.0.0" +version = "5.3.0" [dev-dependencies] rand = "0.3" From be4b64dd3632df0072c40e08e8df60d7a32a2da7 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Zolt=C3=A1n=20Nagy?= Date: Mon, 24 Jun 2019 23:02:48 +0100 Subject: [PATCH 07/15] Fix conflict resolution in tcod_sys/libtcod/src/libtcod/sys_sdl2_c.cpp --- tcod_sys/libtcod/src/libtcod/sys_sdl2_c.cpp | 530 -------------------- 1 file changed, 530 deletions(-) diff --git a/tcod_sys/libtcod/src/libtcod/sys_sdl2_c.cpp b/tcod_sys/libtcod/src/libtcod/sys_sdl2_c.cpp index 9eb793838..9dca2d2fe 100644 --- a/tcod_sys/libtcod/src/libtcod/sys_sdl2_c.cpp +++ b/tcod_sys/libtcod/src/libtcod/sys_sdl2_c.cpp @@ -30,536 +30,6 @@ * POSSIBILITY OF SUCH DAMAGE. */ #ifndef TCOD_BARE - -#include - -#include -#include - -#include - -#include -#include -#include - -static SDL_Surface* scale_screen=NULL; -static bool clear_screen=false; -static TCOD_console_data_t *root_console_cache; /* cache for previous values */ - -/* This just forces a complete redraw, bypassing the usual rendering of changes. */ -void TCOD_sys_set_clear_screen(void) { - clear_screen=true; -} - -static void get_closest_mode(int *w, int *h) { - SDL_DisplayMode wantedmode, closestmode; - wantedmode.w = *w; - wantedmode.h = *h; - wantedmode.format = 0; /* don't care for rest. */ - wantedmode.refresh_rate = 0; - wantedmode.driverdata = 0; - if (SDL_GetClosestDisplayMode(window?SDL_GetWindowDisplayIndex(window):0, &wantedmode, &closestmode) == &closestmode) { - *w=closestmode.w; - *h=closestmode.h; - } -} - -/* - * Separate out the actual rendering, so that render to texture can be done. - */ -static void actual_rendering(void) { - SDL_Rect srcRect, dstRect; - SDL_Texture *texture; - - if (scale_data.min_scale_factor - 1e-3f > scale_factor) { - /* Prepare for the unscaled and centered copy of the entire console. */ - srcRect.x=0; srcRect.y=0; srcRect.w=scale_screen->w; srcRect.h=scale_screen->h; - if (TCOD_ctx.fullscreen) { - dstRect.x=TCOD_ctx.fullscreen_offsetx; dstRect.y=TCOD_ctx.fullscreen_offsety; - } else { - dstRect.x=0; dstRect.y=0; - } - dstRect.w=scale_screen->w; dstRect.h=scale_screen->h; - } else { - /* Prepare for the scaled copy of the displayed console area. */ - srcRect.x=scale_data.src_x0; srcRect.y=scale_data.src_y0; srcRect.w=scale_data.src_copy_width; srcRect.h=scale_data.src_copy_height; - dstRect.x=scale_data.dst_offset_x; dstRect.y=scale_data.dst_offset_y; - dstRect.w=scale_data.dst_display_width; dstRect.h=scale_data.dst_display_height; - } - if ( TCOD_ctx.sdl_cbk ) { - TCOD_ctx.sdl_cbk((void *)scale_screen); - } - texture = SDL_CreateTextureFromSurface(renderer, scale_screen); - SDL_RenderCopy(renderer, texture, &srcRect, &dstRect); - SDL_DestroyTexture(texture); -} - -/* Return an up-to-date cache for the root console, create or resize the cache - if needed */ -static TCOD_console_data_t *ensure_cache(TCOD_console_data_t* root) { - if (!root_console_cache || - root_console_cache->w != root->w || - root_console_cache->h != root->h) { - if (root_console_cache) { TCOD_console_delete(root_console_cache); } - root_console_cache = TCOD_console_new(root->w, root->h); - } - return root_console_cache; -} - -/* In order to avoid rendering race conditions and the ensuing segmentation - * faults, this should only be called when it would normally be and not - * specifically to force screen refreshes. To this end, and to avoid - * threading complications it takes care of special cases internally. */ -static void render(TCOD_SDL_driver_t *sdl, void *vbitmap, TCOD_console_data_t *console) { - if ( TCOD_ctx.renderer == TCOD_RENDERER_SDL ) { - int console_width_p = console->w * TCOD_ctx.font_width; - int console_height_p = console->h * TCOD_ctx.font_height; - - /* Make a bitmap of exact rendering size and correct format. */ - if (scale_screen == NULL) { - int bpp; - uint32_t rmask, gmask, bmask, amask; - if (SDL_PixelFormatEnumToMasks(SDL_GetWindowPixelFormat(window), &bpp, &rmask, &gmask, &bmask, &amask) == SDL_FALSE) { - TCOD_fatal("SDL : failed to create scaling surface : indeterminate window pixel format"); - return; - } - scale_screen=SDL_CreateRGBSurface(SDL_SWSURFACE,console_width_p,console_height_p,bpp,rmask,gmask,bmask,amask); - if (scale_screen == NULL) { - TCOD_fatal("SDL : failed to create scaling surface"); - return; - } - } else if (clear_screen) { - clear_screen=false; - SDL_FillRect(scale_screen,0,0); - /* Implicitly do complete console redraw, not just tracked changes. */ - TCOD_console_set_dirty(0, 0, console->w, console->h); - } - - TCOD_sys_console_to_bitmap(scale_screen, console, ensure_cache(console)); - - /* Scale the rendered bitmap to the screen, preserving aspect ratio, and blit it. - * This data is also used for console coordinate resolution.. */ - if (scale_data.last_scale_factor != scale_factor || scale_data.last_scale_xc != sdl->scale_xc || scale_data.last_scale_yc != sdl->scale_yc || - scale_data.last_fullscreen != TCOD_ctx.fullscreen || scale_data.force_recalc) { - /* Preserve old value of input variables, to enable recalculation if they change. */ - scale_data.last_scale_factor = scale_factor; - scale_data.last_scale_xc = sdl->scale_xc; - scale_data.last_scale_yc = sdl->scale_yc; - scale_data.last_fullscreen = TCOD_ctx.fullscreen; - scale_data.force_recalc = 0; - - if (scale_data.last_fullscreen) { - scale_data.surface_width = TCOD_ctx.actual_fullscreen_width; - scale_data.surface_height = TCOD_ctx.actual_fullscreen_height; - } else { - scale_data.surface_width = console_width_p; - scale_data.surface_height = console_height_p; - } - scale_data.min_scale_factor = MAX((float)console_width_p/scale_data.surface_width, (float)console_height_p/scale_data.surface_height); - if (scale_data.min_scale_factor > 1.0f) - scale_data.min_scale_factor = 1.0f; - /*printf("min_scale_factor %0.3f = MAX(%d/%d, %d/%d)", scale_data.min_scale_factor, console_width_p, scale_data.surface_width, console_height_p, scale_data.surface_height);*/ - - scale_data.dst_height_width_ratio = (float)scale_data.surface_height/scale_data.surface_width; - scale_data.src_proportionate_width = (int)(console_width_p / scale_factor); - scale_data.src_proportionate_height = (int)((console_width_p * scale_data.dst_height_width_ratio) / scale_factor); - - /* Work out how much of the console to copy. */ - scale_data.src_x0 = (int)((sdl->scale_xc * console_width_p) - (0.5f * scale_data.src_proportionate_width)); - if (scale_data.src_x0 + scale_data.src_proportionate_width > console_width_p) - scale_data.src_x0 = console_width_p - scale_data.src_proportionate_width; - if (scale_data.src_x0 < 0) - scale_data.src_x0 = 0; - scale_data.src_copy_width = scale_data.src_proportionate_width; - if (scale_data.src_x0 + scale_data.src_copy_width > console_width_p) - scale_data.src_copy_width = console_width_p - scale_data.src_x0; - - scale_data.src_y0 = (int)((sdl->scale_yc * console_height_p) - (0.5f * scale_data.src_proportionate_height)); - if (scale_data.src_y0 + scale_data.src_proportionate_height > console_height_p) - scale_data.src_y0 = console_height_p - scale_data.src_proportionate_height; - if (scale_data.src_y0 < 0) - scale_data.src_y0 = 0; - scale_data.src_copy_height = scale_data.src_proportionate_height; - if (scale_data.src_y0 + scale_data.src_copy_height > console_height_p) - scale_data.src_copy_height = console_height_p - scale_data.src_y0; - - scale_data.dst_display_width = (scale_data.src_copy_width * scale_data.surface_width) / scale_data.src_proportionate_width; - scale_data.dst_display_height = (scale_data.src_copy_height * scale_data.surface_height) / scale_data.src_proportionate_height; - scale_data.dst_offset_x = (scale_data.surface_width - scale_data.dst_display_width)/2; - scale_data.dst_offset_y = (scale_data.surface_height - scale_data.dst_display_height)/2; - } - - SDL_RenderClear(renderer); - actual_rendering(); - SDL_RenderPresent(renderer); - } -#ifndef NO_OPENGL - else { - TCOD_opengl_render(oldFade, NULL, console, ensure_cache(console)); - TCOD_opengl_swap(); - } -#endif - oldFade=(int)TCOD_console_get_fade(); -} - -/* Return the current root console cache if it exists, or NULL. */ -static TCOD_console_data_t *get_root_console_cache(void){ - return root_console_cache; -} - -static SDL_Surface *create_surface(int width, int height, bool with_alpha) { - uint32_t rmask,gmask,bmask,amask; - SDL_Surface *bitmap; - int flags=SDL_SWSURFACE; - - if ( with_alpha ) { - if ( SDL_BYTEORDER == SDL_LIL_ENDIAN ) { - rmask=0x000000FF; - gmask=0x0000FF00; - bmask=0x00FF0000; - amask=0xFF000000; - } else { - rmask=0xFF000000; - gmask=0x00FF0000; - bmask=0x0000FF00; - amask=0x000000FF; - } - } else { - if ( SDL_BYTEORDER == SDL_LIL_ENDIAN ) { - rmask=0x0000FF; - gmask=0x00FF00; - bmask=0xFF0000; - } else { - rmask=0xFF0000; - gmask=0x00FF00; - bmask=0x0000FF; - } - amask=0; - } - bitmap=SDL_CreateRGBSurface(flags,width,height, - with_alpha ? 32:24, - rmask,gmask,bmask,amask); - if ( with_alpha ) { - SDL_SetSurfaceAlphaMod(bitmap, 255); - } - return (void *)bitmap; -} - -static void create_window(int w, int h, bool fullscreen) { - uint32_t winflags = SDL_WINDOW_SHOWN | SDL_WINDOW_OPENGL; -#if defined(TCOD_ANDROID) - /* Android should always be fullscreen. */ - TCOD_ctx.fullscreen = fullscreen = true; -#endif - if ( fullscreen ) { - find_resolution(); -#ifndef NO_OPENGL - if (TCOD_ctx.renderer != TCOD_RENDERER_SDL ) { - TCOD_opengl_init_attributes(); - winflags |= SDL_WINDOW_FULLSCREEN | SDL_WINDOW_BORDERLESS | SDL_WINDOW_OPENGL; -# if defined(TCOD_ANDROID) && defined(FUTURE_SUPPORT) - winflags |= SDL_WINDOW_RESIZABLE; -# endif - window = SDL_CreateWindow(TCOD_ctx.window_title,SDL_WINDOWPOS_CENTERED,SDL_WINDOWPOS_CENTERED,TCOD_ctx.actual_fullscreen_width,TCOD_ctx.actual_fullscreen_height,winflags); - if ( window && TCOD_opengl_init_state(w, h, charmap) && TCOD_opengl_init_shaders() ) { - TCOD_LOG(("Using %s renderer...\n",TCOD_ctx.renderer == TCOD_RENDERER_GLSL ? "GLSL" : "OPENGL")); - } else { - TCOD_LOG(("Fallback to SDL renderer...\n")); - TCOD_ctx.renderer = TCOD_RENDERER_SDL; - } - } -#endif - if (TCOD_ctx.renderer == TCOD_RENDERER_SDL ) { - winflags |= SDL_WINDOW_FULLSCREEN | SDL_WINDOW_BORDERLESS; -# if defined(TCOD_ANDROID) && defined(FUTURE_SUPPORT) - winflags |= SDL_WINDOW_RESIZABLE; -# endif - window = SDL_CreateWindow(TCOD_ctx.window_title,SDL_WINDOWPOS_CENTERED, SDL_WINDOWPOS_CENTERED, TCOD_ctx.actual_fullscreen_width,TCOD_ctx.actual_fullscreen_height,winflags); - if ( window == NULL ) TCOD_fatal("SDL : cannot set fullscreen video mode: %s", SDL_GetError()); - } - SDL_ShowCursor(0); - SDL_GetWindowSize(window,&TCOD_ctx.actual_fullscreen_width,&TCOD_ctx.actual_fullscreen_height); - TCOD_sys_init_screen_offset(); - } else { -#ifndef NO_OPENGL - if (TCOD_ctx.renderer != TCOD_RENDERER_SDL ) { - TCOD_opengl_init_attributes(); - winflags |= SDL_WINDOW_OPENGL; - window = SDL_CreateWindow(TCOD_ctx.window_title,SDL_WINDOWPOS_CENTERED,SDL_WINDOWPOS_CENTERED,w*TCOD_ctx.font_width,h*TCOD_ctx.font_height,winflags); - if ( window && TCOD_opengl_init_state(w, h, charmap) && TCOD_opengl_init_shaders() ) { - TCOD_LOG(("Using %s renderer...\n",TCOD_ctx.renderer == TCOD_RENDERER_GLSL ? "GLSL" : "OPENGL")); - } else { - TCOD_LOG(("Fallback to SDL renderer...\n")); - TCOD_ctx.renderer = TCOD_RENDERER_SDL; - } - } -#endif - if (TCOD_ctx.renderer == TCOD_RENDERER_SDL ) { - window = SDL_CreateWindow(TCOD_ctx.window_title,SDL_WINDOWPOS_CENTERED,SDL_WINDOWPOS_CENTERED,w*TCOD_ctx.font_width,h*TCOD_ctx.font_height,winflags); - SDL_PumpEvents(); - SDL_SetWindowSize(window,w*TCOD_ctx.font_width,h*TCOD_ctx.font_height); - TCOD_LOG(("Using SDL renderer...\n")); - } - if ( window == NULL ) TCOD_fatal("Cannot create SDL window: %s", SDL_GetError()); - } - if (TCOD_ctx.renderer == TCOD_RENDERER_SDL ) { - renderer = SDL_CreateRenderer(window, -1, SDL_RENDERER_ACCELERATED); - if ( renderer == NULL ) TCOD_fatal("Cannot create SDL renderer: %s", SDL_GetError()); - SDL_SetRenderDrawColor(renderer, 0, 0, 0, SDL_ALPHA_OPAQUE); - } -} - -static void destroy_window(void) { -#ifndef NO_OPENGL - if (TCOD_ctx.renderer == TCOD_RENDERER_OPENGL || TCOD_ctx.renderer == TCOD_RENDERER_GLSL) { - TCOD_opengl_uninit_state(); - } -#endif - if (scale_screen) { - SDL_FreeSurface(scale_screen); - scale_screen = NULL; - } - if (renderer) { - SDL_DestroyRenderer(renderer); - renderer = NULL; - } - if (window) { - SDL_DestroyWindow(window); - window = NULL; - } -} - -static void set_fullscreen(bool fullscreen) { - bool mouseOn=SDL_ShowCursor(-1); - if ( fullscreen ) { - find_resolution(); - SDL_SetWindowFullscreen(window, fullscreen); - SDL_ShowCursor(mouseOn ? 1:0); - SDL_GetWindowSize(window,&TCOD_ctx.actual_fullscreen_width,&TCOD_ctx.actual_fullscreen_height); - TCOD_sys_init_screen_offset(); - } else { - SDL_SetWindowFullscreen(window, fullscreen); - SDL_ShowCursor(mouseOn ? 1:0); - TCOD_ctx.fullscreen_offsetx=0; - TCOD_ctx.fullscreen_offsety=0; - } - TCOD_ctx.fullscreen=fullscreen; - oldFade=-1; /* to redraw the whole screen */ -} - -static void set_window_title(const char *title) { - SDL_SetWindowTitle(window, title); -} - -static void save_screenshot(const char *filename) { - if ( TCOD_ctx.renderer == TCOD_RENDERER_SDL ) { - /* This would be a lot easier if image saving could do textures. */ - SDL_Rect rect; - uint32_t format; - SDL_Texture *texture; - SDL_RenderGetViewport(renderer, &rect); - format = SDL_GetWindowPixelFormat(window); - texture = SDL_CreateTexture(renderer, format, SDL_TEXTUREACCESS_TARGET, rect.w, rect.h); - if (0 != texture) { - if (SDL_SetRenderTarget(renderer, texture)) { - void *pixels; - int pitch, access; - - actual_rendering(); - SDL_SetRenderTarget(renderer, NULL); - - rect.x = rect.y = rect.w = rect.h = 0; - if (-1 != SDL_QueryTexture(texture, &format, &access, &rect.w, &rect.h) && - -1 != SDL_LockTexture(texture, NULL, &pixels, &pitch)) { - int depth; - uint32_t rmask, gmask, bmask, amask; - if (SDL_TRUE == SDL_PixelFormatEnumToMasks(format, &depth, &rmask, &gmask, &bmask, &amask)) { - SDL_Surface *surface = SDL_CreateRGBSurfaceFrom(pixels, rect.w, rect.h, depth, pitch, rmask, gmask, bmask, amask); - TCOD_sys_save_bitmap((void *)surface,filename); - SDL_FreeSurface(surface); - } else - TCOD_LOG(("TCOD_sys_save_screenshot - failed call to SDL_PixelFormatEnumToMasks")); - - SDL_UnlockTexture(texture); - } else - TCOD_LOG(("TCOD_sys_save_screenshot - failed call to SDL_QueryTexture or SDL_LockTexture")); - } else - TCOD_LOG(("TCOD_sys_save_screenshot - failed call to SDL_SetRenderTarget")); - SDL_DestroyTexture(texture); - } else - TCOD_LOG(("TCOD_sys_save_screenshot - failed call to SDL_CreateTexture")); -#ifndef NO_OPENGL - } else { - SDL_Surface *screenshot=(SDL_Surface *)TCOD_opengl_get_screen(); - TCOD_sys_save_bitmap((void *)screenshot,filename); - SDL_FreeSurface(screenshot); -#endif - } -} -/* get desktop resolution */ -static void get_current_resolution(int *w, int *h) { - int displayidx; - SDL_Rect rect = { 0, 0, 0, 0 }; - if (window) { - TCOD_IFNOT(window) return; - displayidx = SDL_GetWindowDisplayIndex(window); - TCOD_IFNOT(displayidx >= 0) return; - } else { - /* No window if no console, but user can want to know res before opening one. */ - TCOD_IFNOT(SDL_GetNumVideoDisplays() > 0) return; - displayidx = 0; - } - TCOD_IFNOT(SDL_GetDisplayBounds(displayidx, &rect) == 0) return; - *w=rect.w; - *h=rect.h; -} - -static void set_mouse_position(int x, int y) { - SDL_WarpMouseInWindow(window, (uint16_t)x,(uint16_t)y); -} - -static char *get_clipboard_text(void) { -#ifdef TCOD_LINUX - /* - X11 clipboard is inaccessible without an open window. - https://bugzilla.libsdl.org/show_bug.cgi?id=3222 - */ - if (!window) - return ""; -#endif - - /* - We hold onto the last clipboard text pointer SDL gave us. - For C API callers it can be considered a borrowed reference. - For Python ctypes API callers, the contents are copied into the Python string that is constructed from it. - */ - if (last_clipboard_text) { - SDL_free(last_clipboard_text); - last_clipboard_text = NULL; - } - last_clipboard_text = SDL_GetClipboardText(); - return last_clipboard_text; -} - -static bool set_clipboard_text(const char *text) { -#ifdef TCOD_LINUX - /* - X11 clipboard is inaccessible without an open window. - https://bugzilla.libsdl.org/show_bug.cgi?id=3222 - */ - if (!window) - return false; -#endif - - return SDL_SetClipboardText(text) == 0; -} - -/* android compatible file access functions */ -static bool file_read(const char *filename, unsigned char **buf, size_t *size) { - int64_t filesize; - /* get file size */ - SDL_RWops *rwops= SDL_RWFromFile(filename,"rb"); - if (!rwops) return false; - SDL_RWseek(rwops,0,RW_SEEK_END); - filesize=SDL_RWtell(rwops); - SDL_RWseek(rwops,0,RW_SEEK_SET); - /* allocate buffer */ - *buf = (unsigned char *)malloc(sizeof(unsigned char)*filesize); - /* read from file */ - if (SDL_RWread(rwops,*buf,sizeof(unsigned char),filesize) != filesize) { - SDL_RWclose(rwops); - free(*buf); - return false; - } - SDL_RWclose(rwops); - *size=filesize; - return true; -} - -static bool file_exists(const char * filename) { - SDL_RWops *rwops; - rwops = SDL_RWFromFile(filename,"rb"); - if (rwops) { - SDL_RWclose(rwops); - return true; - } - return false; -} - -static bool file_write(const char *filename, unsigned char *buf, uint32_t size) { - SDL_RWops *rwops= SDL_RWFromFile(filename,"wb"); - if (!rwops) return false; - SDL_RWwrite(rwops,buf,sizeof(unsigned char),size); - SDL_RWclose(rwops); - return true; -} - -static void shutdown_(void) { - if (last_clipboard_text) { - SDL_free(last_clipboard_text); - last_clipboard_text = NULL; - } - if (root_console_cache) { - TCOD_console_delete(root_console_cache); - root_console_cache = NULL; - } -} - -TCOD_SDL_driver_t *SDL_implementation_factory(void) { - TCOD_SDL_driver_t *ret=(TCOD_SDL_driver_t *)calloc(1,sizeof(TCOD_SDL_driver_t)); - ret->scale_xc = 0.5f; - ret->scale_yc = 0.5f; - - ret->get_closest_mode = get_closest_mode; - ret->render = render; - ret->create_surface = create_surface; - ret->create_window = create_window; - ret->destroy_window = destroy_window; - ret->set_fullscreen = set_fullscreen; - ret->set_window_title = set_window_title; - ret->save_screenshot = save_screenshot; - ret->get_current_resolution = get_current_resolution; - ret->set_mouse_position = set_mouse_position; - ret->get_clipboard_text = get_clipboard_text; - ret->set_clipboard_text = set_clipboard_text; - ret->file_read = file_read; - ret->file_exists = file_exists; - ret->file_write = file_write; - ret->shutdown = shutdown_; - ret->get_root_console_cache = get_root_console_cache; - return ret; -} - -#endif /* TCOD_BARE */ -======= -/* -* libtcod -* Copyright (c) 2008-2018 Jice & Mingos & rmtew -* All rights reserved. -* -* Redistribution and use in source and binary forms, with or without -* modification, are permitted provided that the following conditions are met: -* * Redistributions of source code must retain the above copyright -* notice, this list of conditions and the following disclaimer. -* * Redistributions in binary form must reproduce the above copyright -* notice, this list of conditions and the following disclaimer in the -* documentation and/or other materials provided with the distribution. -* * The name of Jice or Mingos may not be used to endorse or promote -* products derived from this software without specific prior written -* permission. -* -* THIS SOFTWARE IS PROVIDED BY JICE, MINGOS AND RMTEW ``AS IS'' AND ANY -* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED -* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE -* DISCLAIMED. IN NO EVENT SHALL JICE, MINGOS OR RMTEW BE LIABLE FOR ANY -* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES -* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; -* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND -* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS -* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. -*/ -#ifndef TCOD_BARE #include "sys.h" #include From aabf787308ee15060cdf4b5d6ee0a02bd2eb8719 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Zolt=C3=A1n=20Nagy?= Date: Tue, 25 Jun 2019 20:49:57 +0100 Subject: [PATCH 08/15] Try to fix Travis Linux build: use g++-8 --- .travis.yml | 8 +++++++- 1 file changed, 7 insertions(+), 1 deletion(-) diff --git a/.travis.yml b/.travis.yml index b7cadae83..fb0836145 100644 --- a/.travis.yml +++ b/.travis.yml @@ -11,12 +11,18 @@ matrix: rust: nightly - os: osx rust: nightly +addons: + apt: + sources: + - ubuntu-toolchain-r-test + packages: + - g++-8 before_install: - '[ "$TRAVIS_OS_NAME" = linux ] && sudo apt-get update -qq || brew update' install: - '[ "$TRAVIS_OS_NAME" = linux ] && sudo apt-get install -y libsdl2-dev libegl1-mesa-dev libgles2-mesa-dev || brew install sdl2' script: -- cargo build --verbose +- CC=g++-8 cargo build --verbose - cargo test --verbose - cargo test --features "rustc-serialize serde" --verbose - cargo test --release From 4663305d4a4b096c0b68909b54db9be444a85687 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Zolt=C3=A1n=20Nagy?= Date: Tue, 25 Jun 2019 20:58:55 +0100 Subject: [PATCH 09/15] ... maybe this is how computers work? --- .travis.yml | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/.travis.yml b/.travis.yml index fb0836145..98fb55f82 100644 --- a/.travis.yml +++ b/.travis.yml @@ -22,7 +22,7 @@ before_install: install: - '[ "$TRAVIS_OS_NAME" = linux ] && sudo apt-get install -y libsdl2-dev libegl1-mesa-dev libgles2-mesa-dev || brew install sdl2' script: -- CC=g++-8 cargo build --verbose +- cargo build --verbose - cargo test --verbose - cargo test --features "rustc-serialize serde" --verbose - cargo test --release @@ -51,3 +51,5 @@ after_success: ! '[ $TRAVIS_BRANCH = master ] && env: global: - secure: h21kqC5s6iVs4p5n9KFZ5ZTWtPF8nGVFpaPP6t/1Sg+xMaHMDyr/sBYI1gsNGTXrVsiP2Zs6cRTBEbX12PVL6MXFgKpdhKG1+lBCMk6HxU8/W2UHCh6Y38+W4Ybyv5fuoWqkUOX3yODNkRZWrqNhdm8lCdE2uGczkIKPi7hDYMM= + - CC=gcc-8 + - CXX=g++-8 From 40e3c40c7042356264b23df32ef380226560a615 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Zolt=C3=A1n=20Nagy?= Date: Tue, 25 Jun 2019 21:27:15 +0100 Subject: [PATCH 10/15] Let's get us an up-to-date libsdl2-dev --- .travis.yml | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/.travis.yml b/.travis.yml index 98fb55f82..c1e690d38 100644 --- a/.travis.yml +++ b/.travis.yml @@ -17,10 +17,11 @@ addons: - ubuntu-toolchain-r-test packages: - g++-8 + - libsdl2-dev before_install: - '[ "$TRAVIS_OS_NAME" = linux ] && sudo apt-get update -qq || brew update' install: -- '[ "$TRAVIS_OS_NAME" = linux ] && sudo apt-get install -y libsdl2-dev libegl1-mesa-dev libgles2-mesa-dev || brew install sdl2' +- '[ "$TRAVIS_OS_NAME" = linux ] && sudo apt-get install -y libegl1-mesa-dev libgles2-mesa-dev || brew install sdl2' script: - cargo build --verbose - cargo test --verbose From 925121e585c5dd981427c06dff1db4999952cffd Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Zolt=C3=A1n=20Nagy?= Date: Tue, 25 Jun 2019 21:43:08 +0100 Subject: [PATCH 11/15] For realz though, let's get us an up-to-date SDL --- .travis.yml | 11 +++++++++-- 1 file changed, 9 insertions(+), 2 deletions(-) diff --git a/.travis.yml b/.travis.yml index c1e690d38..43e8b5860 100644 --- a/.travis.yml +++ b/.travis.yml @@ -18,10 +18,17 @@ addons: packages: - g++-8 - libsdl2-dev + - libegl1-mesa-dev + - libgles2-mesa-dev before_install: -- '[ "$TRAVIS_OS_NAME" = linux ] && sudo apt-get update -qq || brew update' +- '[ "$TRAVIS_OS_NAME" != linux ] && brew update' install: -- '[ "$TRAVIS_OS_NAME" = linux ] && sudo apt-get install -y libegl1-mesa-dev libgles2-mesa-dev || brew install sdl2' +- '[ "$TRAVIS_OS_NAME" != linux ] && brew install sdl2' + # Upgrade SDL. Copy-paste from https://github.com/libtcod/libtcod/blob/master/.ci/travis_before_install.sh @ ce85b9f0245ece439e509fc38667aa59c440d391 +- '[ "$TRAVIS_OS_NAME" = linux ] && wget -O - https://www.libsdl.org/release/SDL2-2.0.8.tar.gz | tar xz' +- '[ "$TRAVIS_OS_NAME" = linux ] && (cd SDL2-* && ./configure --prefix=$HOME/.local && make -j 3 install)' +- '[ "$TRAVIS_OS_NAME" = linxu ] && PATH=~/.local/bin:$PATH' + script: - cargo build --verbose - cargo test --verbose From c93411c0692f66c807994394c42304c36cb67d72 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Zolt=C3=A1n=20Nagy?= Date: Tue, 25 Jun 2019 21:47:57 +0100 Subject: [PATCH 12/15] Computers \o/ --- .travis.yml | 10 +++++----- 1 file changed, 5 insertions(+), 5 deletions(-) diff --git a/.travis.yml b/.travis.yml index 43e8b5860..2168b6ebe 100644 --- a/.travis.yml +++ b/.travis.yml @@ -21,13 +21,13 @@ addons: - libegl1-mesa-dev - libgles2-mesa-dev before_install: -- '[ "$TRAVIS_OS_NAME" != linux ] && brew update' +- 'if [[ "$TRAVIS_OS_NAME" != linux ]]; then brew update; fi' install: -- '[ "$TRAVIS_OS_NAME" != linux ] && brew install sdl2' +- 'if [[ "$TRAVIS_OS_NAME" != linux ]]; then brew install sdl2; fi' # Upgrade SDL. Copy-paste from https://github.com/libtcod/libtcod/blob/master/.ci/travis_before_install.sh @ ce85b9f0245ece439e509fc38667aa59c440d391 -- '[ "$TRAVIS_OS_NAME" = linux ] && wget -O - https://www.libsdl.org/release/SDL2-2.0.8.tar.gz | tar xz' -- '[ "$TRAVIS_OS_NAME" = linux ] && (cd SDL2-* && ./configure --prefix=$HOME/.local && make -j 3 install)' -- '[ "$TRAVIS_OS_NAME" = linxu ] && PATH=~/.local/bin:$PATH' +- 'if [[ "$TRAVIS_OS_NAME" == linux ]]; then wget -O - https://www.libsdl.org/release/SDL2-2.0.8.tar.gz | tar xz; fi' +- 'if [[ "$TRAVIS_OS_NAME" == linux ]]; then (cd SDL2-* && ./configure --prefix=$HOME/.local && make -j 3 install); fi' +- 'if [[ "$TRAVIS_OS_NAME" == linxu ]]; then PATH=~/.local/bin:$PATH; fi' script: - cargo build --verbose From 0383078bb4535a2e6bd39ec0d1174f2c6dbd11e4 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Zolt=C3=A1n=20Nagy?= Date: Tue, 25 Jun 2019 22:06:24 +0100 Subject: [PATCH 13/15] Let's use that awesome new up-to-date SDL --- .travis.yml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/.travis.yml b/.travis.yml index 2168b6ebe..2c0ccb974 100644 --- a/.travis.yml +++ b/.travis.yml @@ -27,7 +27,7 @@ install: # Upgrade SDL. Copy-paste from https://github.com/libtcod/libtcod/blob/master/.ci/travis_before_install.sh @ ce85b9f0245ece439e509fc38667aa59c440d391 - 'if [[ "$TRAVIS_OS_NAME" == linux ]]; then wget -O - https://www.libsdl.org/release/SDL2-2.0.8.tar.gz | tar xz; fi' - 'if [[ "$TRAVIS_OS_NAME" == linux ]]; then (cd SDL2-* && ./configure --prefix=$HOME/.local && make -j 3 install); fi' -- 'if [[ "$TRAVIS_OS_NAME" == linxu ]]; then PATH=~/.local/bin:$PATH; fi' +- 'if [[ "$TRAVIS_OS_NAME" == linxu ]]; then PATH=~/.local/bin:$PATH; PKG_CONFIG_PATH="$PKG_CONFIG_PATH:$HOME/.local/lib/pkgconfig"; fi' script: - cargo build --verbose From 554016c04baca9db36a898c2029ae98498f257f9 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Zolt=C3=A1n=20Nagy?= Date: Tue, 25 Jun 2019 22:12:44 +0100 Subject: [PATCH 14/15] TYOP! --- .travis.yml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/.travis.yml b/.travis.yml index 2c0ccb974..5755609a5 100644 --- a/.travis.yml +++ b/.travis.yml @@ -27,7 +27,7 @@ install: # Upgrade SDL. Copy-paste from https://github.com/libtcod/libtcod/blob/master/.ci/travis_before_install.sh @ ce85b9f0245ece439e509fc38667aa59c440d391 - 'if [[ "$TRAVIS_OS_NAME" == linux ]]; then wget -O - https://www.libsdl.org/release/SDL2-2.0.8.tar.gz | tar xz; fi' - 'if [[ "$TRAVIS_OS_NAME" == linux ]]; then (cd SDL2-* && ./configure --prefix=$HOME/.local && make -j 3 install); fi' -- 'if [[ "$TRAVIS_OS_NAME" == linxu ]]; then PATH=~/.local/bin:$PATH; PKG_CONFIG_PATH="$PKG_CONFIG_PATH:$HOME/.local/lib/pkgconfig"; fi' +- 'if [[ "$TRAVIS_OS_NAME" == linux ]]; then PATH=~/.local/bin:$PATH; PKG_CONFIG_PATH="$PKG_CONFIG_PATH:$HOME/.local/lib/pkgconfig"; fi' script: - cargo build --verbose From 58e4330afc1e8ab23392c71685d43ee74635fdea Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Zolt=C3=A1n=20Nagy?= Date: Tue, 25 Jun 2019 22:19:46 +0100 Subject: [PATCH 15/15] This might fix SDL path lookup? Also add debug statement. --- .travis.yml | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/.travis.yml b/.travis.yml index 5755609a5..10a7db370 100644 --- a/.travis.yml +++ b/.travis.yml @@ -27,7 +27,9 @@ install: # Upgrade SDL. Copy-paste from https://github.com/libtcod/libtcod/blob/master/.ci/travis_before_install.sh @ ce85b9f0245ece439e509fc38667aa59c440d391 - 'if [[ "$TRAVIS_OS_NAME" == linux ]]; then wget -O - https://www.libsdl.org/release/SDL2-2.0.8.tar.gz | tar xz; fi' - 'if [[ "$TRAVIS_OS_NAME" == linux ]]; then (cd SDL2-* && ./configure --prefix=$HOME/.local && make -j 3 install); fi' -- 'if [[ "$TRAVIS_OS_NAME" == linux ]]; then PATH=~/.local/bin:$PATH; PKG_CONFIG_PATH="$PKG_CONFIG_PATH:$HOME/.local/lib/pkgconfig"; fi' +- 'if [[ "$TRAVIS_OS_NAME" == linux ]]; then PATH=~/.local/bin:$PATH; export PKG_CONFIG_PATH="$PKG_CONFIG_PATH:$HOME/.local/lib/pkgconfig"; fi' + # Debugging, feel free to remove this +- 'if [[ "$TRAVIS_OS_NAME" == linux ]]; then pkg-config sdl2 --cflags; fi' script: - cargo build --verbose