add text rendering

This commit is contained in:
Rokas Puzonas 2026-07-12 18:44:18 +03:00
parent 7197b68637
commit e2b15895c2
14 changed files with 1345 additions and 182 deletions

View File

@ -0,0 +1,93 @@
Copyright 2011 The Roboto Project Authors (https://github.com/googlefonts/roboto-classic)
This Font Software is licensed under the SIL Open Font License, Version 1.1.
This license is copied below, and is also available with a FAQ at:
https://openfontlicense.org
-----------------------------------------------------------
SIL OPEN FONT LICENSE Version 1.1 - 26 February 2007
-----------------------------------------------------------
PREAMBLE
The goals of the Open Font License (OFL) are to stimulate worldwide
development of collaborative font projects, to support the font creation
efforts of academic and linguistic communities, and to provide a free and
open framework in which fonts may be shared and improved in partnership
with others.
The OFL allows the licensed fonts to be used, studied, modified and
redistributed freely as long as they are not sold by themselves. The
fonts, including any derivative works, can be bundled, embedded,
redistributed and/or sold with any software provided that any reserved
names are not used by derivative works. The fonts and derivatives,
however, cannot be released under any other type of license. The
requirement for fonts to remain under this license does not apply
to any document created using the fonts or their derivatives.
DEFINITIONS
"Font Software" refers to the set of files released by the Copyright
Holder(s) under this license and clearly marked as such. This may
include source files, build scripts and documentation.
"Reserved Font Name" refers to any names specified as such after the
copyright statement(s).
"Original Version" refers to the collection of Font Software components as
distributed by the Copyright Holder(s).
"Modified Version" refers to any derivative made by adding to, deleting,
or substituting -- in part or in whole -- any of the components of the
Original Version, by changing formats or by porting the Font Software to a
new environment.
"Author" refers to any designer, engineer, programmer, technical
writer or other person who contributed to the Font Software.
PERMISSION & CONDITIONS
Permission is hereby granted, free of charge, to any person obtaining
a copy of the Font Software, to use, study, copy, merge, embed, modify,
redistribute, and sell modified and unmodified copies of the Font
Software, subject to the following conditions:
1) Neither the Font Software nor any of its individual components,
in Original or Modified Versions, may be sold by itself.
2) Original or Modified Versions of the Font Software may be bundled,
redistributed and/or sold with any software, provided that each copy
contains the above copyright notice and this license. These can be
included either as stand-alone text files, human-readable headers or
in the appropriate machine-readable metadata fields within text or
binary files as long as those fields can be easily viewed by the user.
3) No Modified Version of the Font Software may use the Reserved Font
Name(s) unless explicit written permission is granted by the corresponding
Copyright Holder. This restriction only applies to the primary font name as
presented to the users.
4) The name(s) of the Copyright Holder(s) or the Author(s) of the Font
Software shall not be used to promote, endorse or advertise any
Modified Version, except to acknowledge the contribution(s) of the
Copyright Holder(s) and the Author(s) or with their explicit written
permission.
5) The Font Software, modified or unmodified, in part or in whole,
must be distributed entirely under this license, and must not be
distributed under any other license. The requirement for fonts to
remain under this license does not apply to any document created
using the Font Software.
TERMINATION
This license becomes null and void if any of the above conditions are
not met.
DISCLAIMER
THE FONT SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO ANY WARRANTIES OF
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT
OF COPYRIGHT, PATENT, TRADEMARK, OR OTHER RIGHT. IN NO EVENT SHALL THE
COPYRIGHT HOLDER BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
INCLUDING ANY GENERAL, SPECIAL, INDIRECT, INCIDENTAL, OR CONSEQUENTIAL
DAMAGES, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
FROM, OUT OF THE USE OR INABILITY TO USE THE FONT SOFTWARE OR FROM
OTHER DEALINGS IN THE FONT SOFTWARE.

Binary file not shown.

Binary file not shown.

Binary file not shown.

View File

@ -7,7 +7,8 @@ pub fn build(b: *std.Build) !void {
const assets_dir = "assets";
const asset_files = [_][]const u8{
"sokoban/sokoban_tilesheet.png"
"sokoban/sokoban_tilesheet.png",
"roboto-font/Roboto-Regular.ttf"
};
const asset_dir_realpath = try b.build_root.join(b.graph.arena, &.{ assets_dir });
@ -81,6 +82,7 @@ pub fn build(b: *std.Build) !void {
exe_mod.addImport("stb_image", dep_stb.module("stb_image"));
exe_mod.addImport("stb_vorbis", dep_stb.module("stb_vorbis"));
exe_mod.addImport("stb_rect_pack", dep_stb.module("stb_rect_pack"));
exe_mod.addImport("stb_truetype", dep_stb.module("stb_truetype"));
const dep_tracy = b.dependency("tracy", .{
.target = target,

View File

@ -17,6 +17,7 @@
.cimgui = .{
.url = "git+https://github.com/floooh/dcimgui.git#3c2b41a9333b1195e2c2f8ce6a2d3e50660a73bf",
.hash = "cimgui-0.1.0-44ClkR8dmgDqqnfloyLE1bUAtl4zSKTT1wxaHSEC0ikV",
.lazy = true
},
},
.paths = .{

View File

@ -1,53 +1,37 @@
const std = @import("std");
const Build = std.Build;
const LazyPath = Build.LazyPath;
pub fn build(b: *std.Build) void {
const target = b.standardTargetOptions(.{});
const optimize = b.standardOptimizeOption(.{});
buildSTBModule(b, target, optimize, "stb_image", b.path("src/stb_image.zig"), b.path("src/stb_image_impl.c"));
buildSTBModule(b, target, optimize, "stb_vorbis", b.path("src/stb_vorbis.zig"), b.path("src/stb_vorbis_impl.c"));
buildSTBModule(b, target, optimize, "stb_rect_pack", b.path("src/stb_rect_pack.zig"), b.path("src/stb_rect_pack_impl.c"));
buildSTBModule(b, target, optimize, "stb_truetype", b.path("src/stb_truetype.zig"), b.path("src/stb_truetype_impl.c"));
}
fn buildSTBModule(
b: *std.Build,
target: Build.ResolvedTarget,
optimize: std.builtin.OptimizeMode,
name: []const u8,
zig_file: LazyPath,
impl_file: LazyPath
) void {
const stb_dependency = b.dependency("stb", .{});
{
const mod_stb_image = b.addModule("stb_image", .{
.target = target,
.optimize = optimize,
.root_source_file = b.path("src/stb_image.zig"),
.link_libc = true,
});
const mod = b.addModule(name, .{
.target = target,
.optimize = optimize,
.root_source_file = zig_file,
.link_libc = true,
});
mod_stb_image.addIncludePath(stb_dependency.path("."));
mod_stb_image.addCSourceFile(.{
.file = b.path("src/stb_image_impl.c"),
.flags = &.{}
});
}
{
const mod_stb_vorbis = b.addModule("stb_vorbis", .{
.target = target,
.optimize = optimize,
.root_source_file = b.path("src/stb_vorbis.zig"),
.link_libc = true,
});
mod_stb_vorbis.addIncludePath(stb_dependency.path("."));
mod_stb_vorbis.addCSourceFile(.{
.file = b.path("src/stb_vorbis_impl.c"),
.flags = &.{}
});
}
{
const mod_stb_rect_pack = b.addModule("stb_rect_pack", .{
.target = target,
.optimize = optimize,
.root_source_file = b.path("src/stb_rect_pack.zig"),
.link_libc = true,
});
mod_stb_rect_pack.addIncludePath(stb_dependency.path("."));
mod_stb_rect_pack.addCSourceFile(.{
.file = b.path("src/stb_rect_pack_impl.c"),
.flags = &.{}
});
}
mod.addIncludePath(stb_dependency.path("."));
mod.addCSourceFile(.{
.file = impl_file,
.flags = &.{}
});
}

View File

@ -0,0 +1,116 @@
const std = @import("std");
const c = @cImport({
@cInclude("stb_truetype.h");
});
pub const Box = struct {
x0: i32,
y0: i32,
x1: i32,
y1: i32,
};
pub const HMetrics = struct {
advance_width: i32,
left_side_bearing: i32
};
pub const VMetrics = struct {
ascent: i32,
descent: i32,
line_gap: i32
};
pub const Font = struct {
info: c.stbtt_fontinfo,
pub fn getNumberOfFonts(data: [*c]const u8) !u32 {
const result = c.stbtt_GetNumberOfFonts(data);
if (result == -1) {
return error.stbtt_GetNumberOfFonts;
}
return @intCast(result);
}
pub fn getFontOffsetForIndex(data: [*c]const u8, index: u32) ?u32 {
const result = c.stbtt_GetFontOffsetForIndex(data, @intCast(index));
if (result == -1) {
return null;
}
return @intCast(result);
}
pub fn init(data: [*c]const u8, offset: u32) !Font {
var font: Font = .{
.info = undefined
};
if (c.stbtt_InitFont(&font.info, data, @intCast(offset)) == 0) {
return error.stbtt_InitFont;
}
return font;
}
pub fn findGlyphIndex(self: Font, codepoint: u21) ?u32 {
const result = c.stbtt_FindGlyphIndex(&self.info, codepoint);
if (result == 0) {
return null;
}
return @intCast(result);
}
pub fn scaleForPixelHeight(self: Font, pixel_height: f32) f32 {
return c.stbtt_ScaleForPixelHeight(&self.info, pixel_height);
}
pub fn getGlyphBitmapBox(self: Font, glyph: u32, scale_x: f32, scale_y: f32) Box {
var result: Box = undefined;
c.stbtt_GetGlyphBitmapBox(
&self.info,
@intCast(glyph),
scale_x, scale_y,
&result.x0, &result.y0,
&result.x1, &result.y1,
);
return result;
}
pub fn makeGlyphBitmap(
self: Font,
output: [*]u8,
out_w: u32,
out_h: u32,
out_stride: u32,
scale_x: f32,
scale_y: f32,
glyph: u32
) void {
c.stbtt_MakeGlyphBitmap(
&self.info,
output,
@intCast(out_w),
@intCast(out_h),
@intCast(out_stride),
scale_x,
scale_y,
@intCast(glyph)
);
}
pub fn getGlyphHMetrics(self: Font, glyph: u32) HMetrics {
var result: HMetrics = undefined;
c.stbtt_GetGlyphHMetrics(&self.info, @intCast(glyph), &result.advance_width, &result.left_side_bearing);
return result;
}
pub fn getFontVMetrics(self: Font) VMetrics {
var result: VMetrics = undefined;
c.stbtt_GetFontVMetrics(&self.info, &result.ascent, &result.descent, &result.line_gap);
return result;
}
pub fn getGlyphKernAdvance(self: Font, prev_glyph: u32, next_glyph: u21) i32 {
return c.stbtt_GetGlyphKernAdvance(&self.info, prev_glyph, next_glyph);
}
};

View File

@ -0,0 +1,4 @@
#define STB_TRUETYPE_IMPLEMENTATION
// TODO: #define STBTT_STATIC
#include "stb_truetype.h"

View File

@ -6,6 +6,7 @@ const Math = @import("math");
const Vec2 = Math.Vec2;
const STBImage = @import("stb_image");
const STBTrueType = @import("stb_truetype");
const Platform = @import("./platform.zig");
const Gfx = Platform.Gfx;
@ -20,10 +21,24 @@ check: bool,
player_pos: Vec2,
sprite_sprite: Gfx.Sprite.Id,
wall_sprite: Gfx.Sprite.Id,
roboto_font: Gfx.Font.Id,
pub fn init(self: *App, plt: Platform.Init) !?u8 {
const sokoban_spritesheet = plt.assets.readFile("sokoban/sokoban_tilesheet.png");
// const font = try STBTrueType.Font.init(robot_font, STBTrueType.Font.getFontOffsetForIndex(robot_font, 0).?);
// const glyph = font.findGlyphIndex('A').?;
// const scale = font.scaleForPixelHeight(16);
// const box = font.getGlyphBitmapBox(glyph, scale, scale);
// const width = box.x1 - box.x0;
// const height = box.y1 - box.y0;
// font.makeGlyphBitmap
// std.debug.print("{}\n", .{box});
const robot_font = Gfx.initFont();
Gfx.setFont(robot_font, plt.assets.readFile("roboto-font/Roboto-Regular.ttf"));
var image = try STBImage.load(sokoban_spritesheet);
defer image.deinit();
@ -35,13 +50,13 @@ pub fn init(self: *App, plt: Platform.Init) !?u8 {
const tile_size = Vec2.init(64, 64);
const player_sprite = Gfx.initSprite();
const player_sprite = Gfx.initSprite(.{});
Gfx.setSprite(player_sprite, .{
.image = spritesheet,
.rect = Rect.init(0, 4, 1, 1).multiply(tile_size)
});
const wall_sprite = Gfx.initSprite();
const wall_sprite = Gfx.initSprite(.{});
Gfx.setSprite(wall_sprite, .{
.image = spritesheet,
.rect = Rect.init(1, 0, 1, 1).multiply(tile_size)
@ -53,7 +68,8 @@ pub fn init(self: *App, plt: Platform.Init) !?u8 {
.show_first_window = true,
.check = false,
.sprite_sprite = player_sprite,
.wall_sprite = wall_sprite
.wall_sprite = wall_sprite,
.roboto_font = robot_font
};
return null;
@ -83,6 +99,11 @@ pub fn frame(self: *App, plt: Platform.Frame) !void {
Gfx.setClearColor(self.bg);
Gfx.drawSprite(self.sprite_sprite, self.player_pos, .init(100, 100), .white);
Gfx.drawSprite(self.wall_sprite, self.player_pos.add(.init(0, 200)), .init(100, 100), .white);
Gfx.drawText(self.roboto_font, .{
.pos = .init(300, 100),
.text = "Hello, World!",
.height = 32,
});
if (ImGUI.beginWindow(.{
.name = "Hello",

File diff suppressed because it is too large Load Diff

View File

@ -124,7 +124,9 @@ fn PlatformType(App: type) type {
try self.app.frame(plt);
}
Gfx.flush();
Gfx.flush(.{});
Gfx.showDebug();
ImGUI.endFrame();
Gfx.endFrame();
}
@ -434,15 +436,17 @@ pub const Assets = struct {
};
}
fn readFileFromAssetDir(self: *Assets, filename: []const u8) !?[]const u8 {
fn readFileFromAssetDir(self: *Assets, filename: []const u8) !?[:0]const u8 {
const dir = self.dir orelse return null;
const arena = self.arena.allocator();
const contents = try dir.readFileAlloc(
const contents = try dir.readFileAllocOptions(
self.io,
filename,
arena,
.unlimited
.unlimited,
.of(u8),
0
);
const filename_owned = try arena.dupe(u8, filename);
@ -453,13 +457,13 @@ pub const Assets = struct {
return contents;
}
pub fn readFile(self: *Assets, filename: []const u8) []const u8 {
pub fn readFile(self: *Assets, filename: []const u8) [:0]const u8 {
if (self.files.get(filename)) |file| {
return file.contents;
} else {
if (self.readFileFromAssetDir(filename)) |maybe_contents| {
if (maybe_contents) |contents| {
log.warn("Read file from which isn't defined in assets: '{s}'", .{filename});
log.warn("Read file which isn't defined in assets: '{s}'", .{filename});
return contents;
} else {
log.err("Attempt to read file '{s}', which doesn't exist", .{filename});
@ -472,7 +476,7 @@ pub const Assets = struct {
}
}
fn insertStaticFile(self: *Assets, filename: []const u8, contents: []const u8) !void {
fn insertStaticFile(self: *Assets, filename: []const u8, contents: [:0]const u8) !void {
try self.files.put(self.gpa, filename, File{
.contents = contents
});
@ -484,7 +488,7 @@ pub const Assets = struct {
}
const File = struct {
contents: []const u8
contents: [:0]const u8
};
};

View File

@ -29,8 +29,20 @@ in vec4 color;
in vec4 uv;
out vec4 frag_color;
layout(binding = 1) uniform fs_params {
// Textures modes:
// 0 - rgba8
// 1 - r8 - use red channel as opacity, used for fonts.
int texture_mode;
};
void main() {
frag_color = texture(sampler2D(tex, smp), uv.xy) * color;
vec4 tex_color = texture(sampler2D(tex, smp), uv.xy);
if (texture_mode == 0) {
frag_color = tex_color * color;
} else if (texture_mode == 1) {
frag_color = vec4(1, 1, 1, tex_color.r) * color;
}
}
@end

View File

@ -78,7 +78,7 @@ pub fn SlotMapType(Index: type, Generation: type, Value: type) type {
};
pub fn clearRetainingCapacity(self: *Self) void {
const slots = self.slots;
var slots = self.slots;
slots.clearRetainingCapacity();
self.* = .init(slots);