libstb 0.3.0__cp39-cp39-win32.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
libstb/__init__.py ADDED
@@ -0,0 +1,62 @@
1
+ """libstb: Python bindings for the stb single-header libraries.
2
+
3
+ No system dependencies: `pip install libstb` is all you need.
4
+
5
+ img = libstb.Image.open("photo.png") # object API
6
+ img.write("photo.jpg") # format from the extension
7
+ img.write_jpg("photo.jpg", quality=80) # or pick the format and its settings
8
+ small = img.resize(320, 240)
9
+ libstb.Font.open("font.ttf").render("Hi", 32).bitmap.write("hi.png")
10
+ pixels = libstb.load("photo.png") # or: just the ndarray
11
+ """
12
+
13
+ import os as _os
14
+
15
+ try:
16
+ # Version is derived from include/stb.h at build time - never
17
+ # hardcoded here, so it cannot drift from the real release.
18
+ from importlib.metadata import version as _pkg_version
19
+
20
+ __version__ = _pkg_version("libstb")
21
+ except Exception: # pragma: no cover
22
+ __version__ = "0.0.0+unknown"
23
+
24
+ from .image import DEFAULT_MAX_BYTES, Image, ImageInfo
25
+ from .font import Atlas, AtlasGlyph, Font, FontMetrics, Glyph, RenderedText, TextSize
26
+ from .libstb_py import DecodeError, EncodeError, Error, LimitError, Resizer
27
+
28
+ _pkg_dir = _os.path.dirname(__file__)
29
+
30
+
31
+ def info(source):
32
+ """Shortcut for ImageInfo.read(source)."""
33
+ return ImageInfo.read(source)
34
+
35
+
36
+ def load(source, **kwargs):
37
+ """Shortcut for Image.open(source, **kwargs).array (a uint8 ndarray)."""
38
+ return Image.open(source, **kwargs).array
39
+
40
+
41
+ def get_include_dir():
42
+ """Directory containing stb.h and stb/*.hpp."""
43
+ return _os.path.join(_pkg_dir, "include")
44
+
45
+
46
+ def get_lib_dir():
47
+ """Directory containing the static C++ library (libstb_core)."""
48
+ return _os.path.join(_pkg_dir, "lib")
49
+
50
+
51
+ def get_cmake_dir():
52
+ """Directory containing libstbConfig.cmake, for find_package(libstb CONFIG)."""
53
+ return _os.path.join(_pkg_dir, "cmake")
54
+
55
+
56
+ __all__ = [
57
+ "Image", "ImageInfo", "DEFAULT_MAX_BYTES", "info", "load",
58
+ "Resizer",
59
+ "Font", "FontMetrics", "Glyph", "TextSize", "RenderedText", "Atlas", "AtlasGlyph",
60
+ "Error", "DecodeError", "EncodeError", "LimitError",
61
+ "get_include_dir", "get_lib_dir", "get_cmake_dir",
62
+ ]
@@ -0,0 +1,29 @@
1
+
2
+ ####### Expanded from @PACKAGE_INIT@ by configure_package_config_file() #######
3
+ ####### Any changes to this file will be overwritten by the next CMake run ####
4
+ ####### The input file was libstbConfig.cmake.in ########
5
+
6
+ get_filename_component(PACKAGE_PREFIX_DIR "${CMAKE_CURRENT_LIST_DIR}/../../" ABSOLUTE)
7
+
8
+ macro(set_and_check _var _file)
9
+ set(${_var} "${_file}")
10
+ if(NOT EXISTS "${_file}")
11
+ message(FATAL_ERROR "File or directory ${_file} referenced by variable ${_var} does not exist !")
12
+ endif()
13
+ endmacro()
14
+
15
+ macro(check_required_components _NAME)
16
+ foreach(comp ${${_NAME}_FIND_COMPONENTS})
17
+ if(NOT ${_NAME}_${comp}_FOUND)
18
+ if(${_NAME}_FIND_REQUIRED_${comp})
19
+ set(${_NAME}_FOUND FALSE)
20
+ endif()
21
+ endif()
22
+ endforeach()
23
+ endmacro()
24
+
25
+ ####################################################################################
26
+
27
+ include("${CMAKE_CURRENT_LIST_DIR}/libstbTargets.cmake")
28
+
29
+ check_required_components(libstb)
@@ -0,0 +1,65 @@
1
+ # This is a basic version file for the Config-mode of find_package().
2
+ # It is used by write_basic_package_version_file() as input file for configure_file()
3
+ # to create a version-file which can be installed along a config.cmake file.
4
+ #
5
+ # The created file sets PACKAGE_VERSION_EXACT if the current version string and
6
+ # the requested version string are exactly the same and it sets
7
+ # PACKAGE_VERSION_COMPATIBLE if the current version is >= requested version,
8
+ # but only if the requested major version is the same as the current one.
9
+ # The variable CVF_VERSION must be set before calling configure_file().
10
+
11
+
12
+ set(PACKAGE_VERSION "0.3.0")
13
+
14
+ if(PACKAGE_VERSION VERSION_LESS PACKAGE_FIND_VERSION)
15
+ set(PACKAGE_VERSION_COMPATIBLE FALSE)
16
+ else()
17
+
18
+ if("0.3.0" MATCHES "^([0-9]+)\\.")
19
+ set(CVF_VERSION_MAJOR "${CMAKE_MATCH_1}")
20
+ if(NOT CVF_VERSION_MAJOR VERSION_EQUAL 0)
21
+ string(REGEX REPLACE "^0+" "" CVF_VERSION_MAJOR "${CVF_VERSION_MAJOR}")
22
+ endif()
23
+ else()
24
+ set(CVF_VERSION_MAJOR "0.3.0")
25
+ endif()
26
+
27
+ if(PACKAGE_FIND_VERSION_RANGE)
28
+ # both endpoints of the range must have the expected major version
29
+ math (EXPR CVF_VERSION_MAJOR_NEXT "${CVF_VERSION_MAJOR} + 1")
30
+ if (NOT PACKAGE_FIND_VERSION_MIN_MAJOR STREQUAL CVF_VERSION_MAJOR
31
+ OR ((PACKAGE_FIND_VERSION_RANGE_MAX STREQUAL "INCLUDE" AND NOT PACKAGE_FIND_VERSION_MAX_MAJOR STREQUAL CVF_VERSION_MAJOR)
32
+ OR (PACKAGE_FIND_VERSION_RANGE_MAX STREQUAL "EXCLUDE" AND NOT PACKAGE_FIND_VERSION_MAX VERSION_LESS_EQUAL CVF_VERSION_MAJOR_NEXT)))
33
+ set(PACKAGE_VERSION_COMPATIBLE FALSE)
34
+ elseif(PACKAGE_FIND_VERSION_MIN_MAJOR STREQUAL CVF_VERSION_MAJOR
35
+ AND ((PACKAGE_FIND_VERSION_RANGE_MAX STREQUAL "INCLUDE" AND PACKAGE_VERSION VERSION_LESS_EQUAL PACKAGE_FIND_VERSION_MAX)
36
+ OR (PACKAGE_FIND_VERSION_RANGE_MAX STREQUAL "EXCLUDE" AND PACKAGE_VERSION VERSION_LESS PACKAGE_FIND_VERSION_MAX)))
37
+ set(PACKAGE_VERSION_COMPATIBLE TRUE)
38
+ else()
39
+ set(PACKAGE_VERSION_COMPATIBLE FALSE)
40
+ endif()
41
+ else()
42
+ if(PACKAGE_FIND_VERSION_MAJOR STREQUAL CVF_VERSION_MAJOR)
43
+ set(PACKAGE_VERSION_COMPATIBLE TRUE)
44
+ else()
45
+ set(PACKAGE_VERSION_COMPATIBLE FALSE)
46
+ endif()
47
+
48
+ if(PACKAGE_FIND_VERSION STREQUAL PACKAGE_VERSION)
49
+ set(PACKAGE_VERSION_EXACT TRUE)
50
+ endif()
51
+ endif()
52
+ endif()
53
+
54
+
55
+ # if the installed or the using project don't have CMAKE_SIZEOF_VOID_P set, ignore it:
56
+ if("${CMAKE_SIZEOF_VOID_P}" STREQUAL "" OR "4" STREQUAL "")
57
+ return()
58
+ endif()
59
+
60
+ # check that the installed version has the same 32/64bit-ness as the one which is currently searching:
61
+ if(NOT CMAKE_SIZEOF_VOID_P STREQUAL "4")
62
+ math(EXPR installedBits "4 * 8")
63
+ set(PACKAGE_VERSION "${PACKAGE_VERSION} (${installedBits}bit)")
64
+ set(PACKAGE_VERSION_UNSUITABLE TRUE)
65
+ endif()
@@ -0,0 +1,19 @@
1
+ #----------------------------------------------------------------
2
+ # Generated CMake target import file for configuration "Release".
3
+ #----------------------------------------------------------------
4
+
5
+ # Commands may need to know the format version.
6
+ set(CMAKE_IMPORT_FILE_VERSION 1)
7
+
8
+ # Import target "libstb::core" for configuration "Release"
9
+ set_property(TARGET libstb::core APPEND PROPERTY IMPORTED_CONFIGURATIONS RELEASE)
10
+ set_target_properties(libstb::core PROPERTIES
11
+ IMPORTED_LINK_INTERFACE_LANGUAGES_RELEASE "CXX"
12
+ IMPORTED_LOCATION_RELEASE "${_IMPORT_PREFIX}/libstb/lib/stb_core.lib"
13
+ )
14
+
15
+ list(APPEND _cmake_import_check_targets libstb::core )
16
+ list(APPEND _cmake_import_check_files_for_libstb::core "${_IMPORT_PREFIX}/libstb/lib/stb_core.lib" )
17
+
18
+ # Commands beyond this point should not need to know the version.
19
+ set(CMAKE_IMPORT_FILE_VERSION)
@@ -0,0 +1,105 @@
1
+ # Generated by CMake
2
+
3
+ if("${CMAKE_MAJOR_VERSION}.${CMAKE_MINOR_VERSION}" LESS 2.8)
4
+ message(FATAL_ERROR "CMake >= 2.8.3 required")
5
+ endif()
6
+ if(CMAKE_VERSION VERSION_LESS "2.8.3")
7
+ message(FATAL_ERROR "CMake >= 2.8.3 required")
8
+ endif()
9
+ cmake_policy(PUSH)
10
+ cmake_policy(VERSION 2.8.3...4.2)
11
+ #----------------------------------------------------------------
12
+ # Generated CMake target import file.
13
+ #----------------------------------------------------------------
14
+
15
+ # Commands may need to know the format version.
16
+ set(CMAKE_IMPORT_FILE_VERSION 1)
17
+
18
+ # Protect against multiple inclusion, which would fail when already imported targets are added once more.
19
+ set(_cmake_targets_defined "")
20
+ set(_cmake_targets_not_defined "")
21
+ set(_cmake_expected_targets "")
22
+ foreach(_cmake_expected_target IN ITEMS libstb::core)
23
+ list(APPEND _cmake_expected_targets "${_cmake_expected_target}")
24
+ if(TARGET "${_cmake_expected_target}")
25
+ list(APPEND _cmake_targets_defined "${_cmake_expected_target}")
26
+ else()
27
+ list(APPEND _cmake_targets_not_defined "${_cmake_expected_target}")
28
+ endif()
29
+ endforeach()
30
+ unset(_cmake_expected_target)
31
+ if(_cmake_targets_defined STREQUAL _cmake_expected_targets)
32
+ unset(_cmake_targets_defined)
33
+ unset(_cmake_targets_not_defined)
34
+ unset(_cmake_expected_targets)
35
+ unset(CMAKE_IMPORT_FILE_VERSION)
36
+ cmake_policy(POP)
37
+ return()
38
+ endif()
39
+ if(NOT _cmake_targets_defined STREQUAL "")
40
+ string(REPLACE ";" ", " _cmake_targets_defined_text "${_cmake_targets_defined}")
41
+ string(REPLACE ";" ", " _cmake_targets_not_defined_text "${_cmake_targets_not_defined}")
42
+ message(FATAL_ERROR "Some (but not all) targets in this export set were already defined.\nTargets Defined: ${_cmake_targets_defined_text}\nTargets not yet defined: ${_cmake_targets_not_defined_text}\n")
43
+ endif()
44
+ unset(_cmake_targets_defined)
45
+ unset(_cmake_targets_not_defined)
46
+ unset(_cmake_expected_targets)
47
+
48
+
49
+ # Compute the installation prefix relative to this file.
50
+ get_filename_component(_IMPORT_PREFIX "${CMAKE_CURRENT_LIST_FILE}" PATH)
51
+ get_filename_component(_IMPORT_PREFIX "${_IMPORT_PREFIX}" PATH)
52
+ get_filename_component(_IMPORT_PREFIX "${_IMPORT_PREFIX}" PATH)
53
+ if(_IMPORT_PREFIX STREQUAL "/")
54
+ set(_IMPORT_PREFIX "")
55
+ endif()
56
+
57
+ # Create imported target libstb::core
58
+ add_library(libstb::core STATIC IMPORTED)
59
+
60
+ set_target_properties(libstb::core PROPERTIES
61
+ INTERFACE_INCLUDE_DIRECTORIES "${_IMPORT_PREFIX}/libstb/include"
62
+ )
63
+
64
+ # Load information for each installed configuration.
65
+ file(GLOB _cmake_config_files "${CMAKE_CURRENT_LIST_DIR}/libstbTargets-*.cmake")
66
+ foreach(_cmake_config_file IN LISTS _cmake_config_files)
67
+ include("${_cmake_config_file}")
68
+ endforeach()
69
+ unset(_cmake_config_file)
70
+ unset(_cmake_config_files)
71
+
72
+ # Cleanup temporary variables.
73
+ set(_IMPORT_PREFIX)
74
+
75
+ # Loop over all imported files and verify that they actually exist
76
+ foreach(_cmake_target IN LISTS _cmake_import_check_targets)
77
+ if(CMAKE_VERSION VERSION_LESS "3.28"
78
+ OR NOT DEFINED _cmake_import_check_xcframework_for_${_cmake_target}
79
+ OR NOT IS_DIRECTORY "${_cmake_import_check_xcframework_for_${_cmake_target}}")
80
+ foreach(_cmake_file IN LISTS "_cmake_import_check_files_for_${_cmake_target}")
81
+ if(NOT EXISTS "${_cmake_file}")
82
+ message(FATAL_ERROR "The imported target \"${_cmake_target}\" references the file
83
+ \"${_cmake_file}\"
84
+ but this file does not exist. Possible reasons include:
85
+ * The file was deleted, renamed, or moved to another location.
86
+ * An install or uninstall procedure did not complete successfully.
87
+ * The installation package was faulty and contained
88
+ \"${CMAKE_CURRENT_LIST_FILE}\"
89
+ but not all the files it references.
90
+ ")
91
+ endif()
92
+ endforeach()
93
+ endif()
94
+ unset(_cmake_file)
95
+ unset("_cmake_import_check_files_for_${_cmake_target}")
96
+ endforeach()
97
+ unset(_cmake_target)
98
+ unset(_cmake_import_check_targets)
99
+
100
+ # This file does not depend on other imported targets which have
101
+ # been exported from the same project but in a separate export set.
102
+
103
+ # Commands beyond this point should not need to know the version.
104
+ set(CMAKE_IMPORT_FILE_VERSION)
105
+ cmake_policy(POP)
libstb/font.py ADDED
@@ -0,0 +1,144 @@
1
+ """Fonts (stb_truetype): object API on top of the native module.
2
+
3
+ SECURITY: stb_truetype does no bounds checking; its author says not to use it
4
+ on untrusted font files. Only load fonts you trust.
5
+ """
6
+
7
+ from __future__ import annotations
8
+
9
+ from typing import Dict, NamedTuple, Optional
10
+
11
+
12
+ from . import libstb_py as _native
13
+ from .image import Image, Source, _read
14
+
15
+
16
+ class FontMetrics(NamedTuple):
17
+ """Vertical metrics in pixels (descent is negative)."""
18
+
19
+ ascent: float
20
+ descent: float
21
+ line_gap: float
22
+
23
+ @property
24
+ def line_height(self) -> float:
25
+ return self.ascent - self.descent + self.line_gap
26
+
27
+
28
+ class Glyph(NamedTuple):
29
+ """One rasterised character. `bitmap` is a 1-channel coverage Image, or
30
+ None for blank glyphs such as space. x_offset / y_offset place the bitmap
31
+ relative to the pen at the baseline (y_offset is negative above it)."""
32
+
33
+ bitmap: Optional[Image]
34
+ x_offset: int
35
+ y_offset: int
36
+ advance: float
37
+
38
+
39
+ class TextSize(NamedTuple):
40
+ width: float
41
+ height: float
42
+ lines: int
43
+
44
+
45
+ class RenderedText(NamedTuple):
46
+ """`bitmap` covers the layout box plus any overhanging ink;
47
+ (origin_x, origin_y) is where the layout box's top-left sits in it."""
48
+
49
+ bitmap: Image
50
+ origin_x: int
51
+ origin_y: int
52
+
53
+
54
+ class AtlasGlyph(NamedTuple):
55
+ char: str
56
+ x0: int
57
+ y0: int
58
+ x1: int
59
+ y1: int # pixel rectangle in the atlas
60
+ xoff: float
61
+ yoff: float # top-left of the quad, relative to the pen at the baseline
62
+ xoff2: float
63
+ yoff2: float # bottom-right of the quad
64
+ advance: float
65
+
66
+
67
+ class Atlas:
68
+ """A packed glyph sheet: `image` (1 channel) and a per-character lookup."""
69
+
70
+ __slots__ = ("image", "glyphs")
71
+
72
+ def __init__(self, image: Image, glyphs: Dict[str, AtlasGlyph]):
73
+ self.image = image
74
+ self.glyphs = glyphs
75
+
76
+ def __getitem__(self, char: str) -> AtlasGlyph:
77
+ return self.glyphs[char]
78
+
79
+ def __contains__(self, char: str) -> bool:
80
+ return char in self.glyphs
81
+
82
+ def __len__(self) -> int:
83
+ return len(self.glyphs)
84
+
85
+ def __repr__(self) -> str:
86
+ return f"Atlas({self.image.width}x{self.image.height}, {len(self)} glyphs)"
87
+
88
+
89
+ class Font:
90
+ """A TrueType/OpenType font (immutable; safe to share between threads).
91
+
92
+ >>> font = Font.open("DejaVuSans.ttf")
93
+ >>> font.render("Hello", 32).bitmap.write("hello.png")
94
+ """
95
+
96
+ __slots__ = ("_f",)
97
+
98
+ def __init__(self, native: _native.Font):
99
+ self._f = native
100
+
101
+ @classmethod
102
+ def open(cls, source: Source, *, index: int = 0) -> "Font":
103
+ """Load from a path or from bytes. `index` selects a face in a .ttc.
104
+
105
+ Raises ValueError (bad index), DecodeError (not a font), OSError.
106
+ """
107
+ return cls(_native.Font.from_bytes(_read(source), index))
108
+
109
+ def metrics(self, pixel_height: float) -> FontMetrics:
110
+ return FontMetrics(*self._f.metrics(pixel_height))
111
+
112
+ def has_glyph(self, char: str) -> bool:
113
+ return self._f.has_glyph(char)
114
+
115
+ def advance(self, char: str, pixel_height: float) -> float:
116
+ return self._f.advance(char, pixel_height)
117
+
118
+ def kerning(self, left: str, right: str, pixel_height: float) -> float:
119
+ """Kerning between two characters in pixels (usually <= 0)."""
120
+ return self._f.kerning(left, right, pixel_height)
121
+
122
+ def render_glyph(self, char: str, pixel_height: float) -> Glyph:
123
+ bitmap, xo, yo, adv = self._f.render_glyph(char, pixel_height)
124
+ return Glyph(bitmap, xo, yo, adv)
125
+
126
+ def measure(self, text: str, pixel_height: float) -> TextSize:
127
+ return TextSize(*self._f.measure(text, pixel_height))
128
+
129
+ def render(self, text: str, pixel_height: float, *, max_bytes: int = 1 << 28) -> RenderedText:
130
+ """Render (multi-line) text into one 1-channel coverage Image.
131
+
132
+ Raises ValueError (empty text, bad pixel_height), LimitError.
133
+ """
134
+ bitmap, ox, oy = self._f.render(text, pixel_height, max_bytes)
135
+ return RenderedText(bitmap, ox, oy)
136
+
137
+ def make_atlas(self, chars: str, pixel_height: float, width: int, height: int,
138
+ *, padding: int = 1) -> Atlas:
139
+ """Pack the characters of `chars` into one width x height sheet.
140
+
141
+ Raises LimitError if they do not all fit.
142
+ """
143
+ bitmap, entries = self._f.make_atlas(chars, pixel_height, width, height, padding)
144
+ return Atlas(bitmap, {e[0]: AtlasGlyph(*e) for e in entries})
libstb/image.py ADDED
@@ -0,0 +1,42 @@
1
+ """Image (native: it is stb::image) and the header-only ImageInfo."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import os
6
+ from typing import NamedTuple, Union
7
+
8
+ from . import libstb_py as _native
9
+ from .libstb_py import DEFAULT_MAX_BYTES, Image
10
+
11
+ # Path, or the encoded image itself.
12
+ Source = Union[str, "os.PathLike[str]", bytes, bytearray, memoryview]
13
+
14
+
15
+ def _read(source: Source) -> bytes:
16
+ """bytes-like -> the data itself; str / os.PathLike -> file contents.
17
+
18
+ ponytail: used by ImageInfo and Font, which decode from memory. (Image
19
+ opens paths natively; a missing file is a FileNotFoundError either way.)
20
+ """
21
+ if isinstance(source, bytes):
22
+ return source
23
+ if isinstance(source, (bytearray, memoryview)):
24
+ return bytes(source)
25
+ with open(source, "rb") as f:
26
+ return f.read()
27
+
28
+
29
+ class ImageInfo(NamedTuple):
30
+ """Header-only facts about an image file."""
31
+
32
+ width: int
33
+ height: int
34
+ channels: int
35
+
36
+ @classmethod
37
+ def read(cls, source: Source) -> "ImageInfo":
38
+ """Read just the header (no pixel decoding)."""
39
+ return cls(*_native.info_bytes(_read(source)))
40
+
41
+
42
+ __all__ = ["DEFAULT_MAX_BYTES", "Image", "ImageInfo", "Source"]
@@ -0,0 +1,52 @@
1
+ #pragma once
2
+
3
+ #include <stdexcept>
4
+ #include <string>
5
+
6
+ namespace stb {
7
+
8
+ // Everything libstb can fail at *at runtime* derives from stb::error, so
9
+ // `catch (const stb::error&)` handles all of it:
10
+ //
11
+ // error (std::runtime_error)
12
+ // |- decode_error input is corrupt, truncated, empty or an unsupported format
13
+ // |- encode_error encoding failed to produce output
14
+ // |- limit_error a size limit was hit (max_bytes, 2 GiB stb ceiling)
15
+ // `- io_error a file could not be opened, read or written
16
+ //
17
+ // Programmer errors (null pointer, channels outside 1..4, unknown file
18
+ // extension, quality outside 1..100 ...) are NOT stb::error: they throw
19
+ // std::invalid_argument, following the std convention that logic errors and
20
+ // runtime errors are different families.
21
+ class error : public std::runtime_error {
22
+ public:
23
+ using std::runtime_error::runtime_error;
24
+ };
25
+
26
+ class decode_error : public error {
27
+ public:
28
+ using error::error;
29
+ };
30
+
31
+ class encode_error : public error {
32
+ public:
33
+ using error::error;
34
+ };
35
+
36
+ class limit_error : public error {
37
+ public:
38
+ using error::error;
39
+ };
40
+
41
+ class io_error : public error {
42
+ public:
43
+ explicit io_error(const std::string& what, int code = 0) : error(what), code_(code) {}
44
+ // errno at the failure, 0 if unknown. Lets a binding raise the matching
45
+ // error (Python: FileNotFoundError, PermissionError, ...).
46
+ int code() const noexcept { return code_; }
47
+
48
+ private:
49
+ int code_ = 0;
50
+ };
51
+
52
+ } // namespace stb
@@ -0,0 +1,131 @@
1
+ #pragma once
2
+
3
+ // stb_truetype / stb_rect_pack live in src/core/font.cpp only; `font` hides
4
+ // them behind a pimpl, so no stbtt_* type appears in this header.
5
+ //
6
+ // !!! SECURITY: stb_truetype does no bounds checking of its own. Its author
7
+ // !!! states: "NO SECURITY GUARANTEE -- DO NOT USE THIS ON UNTRUSTED FONT
8
+ // !!! FILES". Only load fonts you trust (your own, or vetted system fonts).
9
+
10
+ #include <cstddef>
11
+ #include <cstdint>
12
+ #include <filesystem>
13
+ #include <memory>
14
+ #include <string_view>
15
+ #include <unordered_map>
16
+ #include <vector>
17
+
18
+ #include "stb/error.hpp"
19
+ #include "stb/image.hpp"
20
+
21
+ namespace stb {
22
+
23
+ // Vertical metrics in pixels at a given pixel height.
24
+ struct font_metrics {
25
+ float ascent = 0; // above the baseline (positive)
26
+ float descent = 0; // below the baseline (negative)
27
+ float line_gap = 0;
28
+ float line_height() const noexcept { return ascent - descent + line_gap; }
29
+ };
30
+
31
+ // One rasterised character: an 8-bit coverage mask (1 channel; empty for
32
+ // blank glyphs such as space) plus where it sits relative to the pen.
33
+ struct glyph {
34
+ image bitmap;
35
+ int x_offset = 0; // pen -> left edge of the bitmap
36
+ int y_offset = 0; // baseline -> top edge (negative = above the baseline)
37
+ float advance = 0; // how far the pen moves afterwards
38
+ };
39
+
40
+ struct text_size {
41
+ float width = 0;
42
+ float height = 0;
43
+ int lines = 1;
44
+ };
45
+
46
+ // A rendered line of text. The bitmap covers the layout box (0,0)-(width,
47
+ // height) plus any ink overhanging it; (origin_x, origin_y) is the pixel of
48
+ // the bitmap where the layout box's top-left corner sits.
49
+ struct text_bitmap {
50
+ image bitmap;
51
+ int origin_x = 0;
52
+ int origin_y = 0;
53
+ };
54
+
55
+ // Where one character lives in a glyph atlas, plus the quad offsets a
56
+ // renderer needs (relative to the pen at the baseline).
57
+ struct atlas_glyph {
58
+ char32_t codepoint = 0;
59
+ int x0 = 0, y0 = 0, x1 = 0, y1 = 0; // pixel rectangle in the atlas
60
+ float xoff = 0, yoff = 0; // top-left of the quad
61
+ float xoff2 = 0, yoff2 = 0; // bottom-right of the quad
62
+ float advance = 0;
63
+ };
64
+
65
+ // A packed glyph sheet: one 1-channel image plus the lookup table.
66
+ class atlas {
67
+ public:
68
+ atlas(image bitmap, std::vector<atlas_glyph> glyphs);
69
+
70
+ const image& bitmap() const noexcept { return bitmap_; }
71
+ const std::vector<atlas_glyph>& glyphs() const noexcept { return glyphs_; }
72
+ // nullptr if the codepoint is not in the atlas.
73
+ const atlas_glyph* find(char32_t codepoint) const noexcept;
74
+
75
+ private:
76
+ image bitmap_;
77
+ std::vector<atlas_glyph> glyphs_;
78
+ std::unordered_map<char32_t, std::size_t> index_;
79
+ };
80
+
81
+ // A TrueType/OpenType font. Cheap to copy (copies share one immutable
82
+ // parsed font) and safe to use from many threads at once.
83
+ //
84
+ // Text arguments are UTF-8; '\n' starts a new line. Characters the font has
85
+ // no glyph for render as its ".notdef" glyph (check with has_glyph()).
86
+ class font {
87
+ public:
88
+ static constexpr float max_pixel_height = 2048.0f;
89
+
90
+ // Takes ownership of the file contents. `index` selects a face inside a
91
+ // .ttc collection. Throws invalid_argument (index < 0), decode_error.
92
+ static font from_memory(std::vector<std::uint8_t> data, int index = 0);
93
+ // Also throws io_error / limit_error.
94
+ static font open(const std::filesystem::path& path, int index = 0);
95
+
96
+ // pixel_height is the em-height in pixels, in (0, max_pixel_height];
97
+ // anything else throws invalid_argument.
98
+ font_metrics metrics(float pixel_height) const;
99
+ bool has_glyph(char32_t codepoint) const;
100
+ float advance(char32_t codepoint, float pixel_height) const;
101
+ // Kerning (kern table or GPOS pair adjustment) in pixels, usually <= 0.
102
+ float kerning(char32_t left, char32_t right, float pixel_height) const;
103
+
104
+ glyph render_glyph(char32_t codepoint, float pixel_height) const;
105
+
106
+ // Throws invalid_argument on malformed UTF-8.
107
+ text_size measure(std::string_view utf8, float pixel_height) const;
108
+ // Single 1-channel coverage image of the whole text. Throws
109
+ // invalid_argument (malformed UTF-8, or empty text), limit_error
110
+ // (result would exceed max_bytes).
111
+ text_bitmap render(std::string_view utf8, float pixel_height,
112
+ std::size_t max_bytes = std::size_t(1) << 28) const;
113
+
114
+ // Packs the given characters (duplicates ignored) into one width x height
115
+ // sheet with `padding` pixels between glyphs. Throws limit_error if they
116
+ // do not all fit.
117
+ atlas make_atlas(std::u32string_view codepoints, float pixel_height, int width, int height,
118
+ int padding = 1) const;
119
+
120
+ // Opaque pimpl (holds the font file bytes and the stbtt_fontinfo). Public
121
+ // only so that helpers in font.cpp can name it; it is incomplete here, so
122
+ // nothing outside libstb_core can look inside.
123
+ struct impl;
124
+
125
+ private:
126
+ explicit font(std::shared_ptr<const impl> p) noexcept : impl_(std::move(p)) {}
127
+
128
+ std::shared_ptr<const impl> impl_;
129
+ };
130
+
131
+ } // namespace stb