{gfx,examples}: simplify text rendering API a bit

Signed-off-by: Stephen Gutekanst <stephen@hexops.com>
This commit is contained in:
Stephen Gutekanst 2024-05-13 22:38:40 +02:00
parent 393320aa68
commit 122a1ea9a7
5 changed files with 153 additions and 117 deletions

View file

@ -17,11 +17,14 @@ const Mat4x4 = math.Mat4x4;
var gpa = std.heap.GeneralPurposeAllocator(.{}){}; var gpa = std.heap.GeneralPurposeAllocator(.{}){};
info_text: mach.EntityID,
info_text_style: mach.EntityID,
timer: mach.Timer, timer: mach.Timer,
gotta_go_fast: bool = false, gotta_go_fast: bool = false,
spawn_timer: mach.Timer, spawn_timer: mach.Timer,
fps_timer: mach.Timer, fps_timer: mach.Timer,
frame_count: usize, frame_count: usize,
frame_rate: usize,
num_sprites_spawned: usize, num_sprites_spawned: usize,
score: usize, score: usize,
rand: std.rand.DefaultPrng, rand: std.rand.DefaultPrng,
@ -59,6 +62,20 @@ fn deinit(
} }
fn init( fn init(
audio: *mach.Audio.Mod,
text_pipeline: *gfx.TextPipeline.Mod,
text: *gfx.Text.Mod,
sprite_pipeline: *gfx.SpritePipeline.Mod,
game: *Mod,
) !void {
audio.schedule(.init);
text.schedule(.init);
text_pipeline.schedule(.init);
sprite_pipeline.schedule(.init);
game.schedule(.after_init);
}
fn afterInit(
entities: *mach.Entities.Mod, entities: *mach.Entities.Mod,
core: *mach.Core.Mod, core: *mach.Core.Mod,
audio: *mach.Audio.Mod, audio: *mach.Audio.Mod,
@ -68,9 +85,9 @@ fn init(
sprite_pipeline: *gfx.SpritePipeline.Mod, sprite_pipeline: *gfx.SpritePipeline.Mod,
game: *Mod, game: *Mod,
) !void { ) !void {
audio.schedule(.init); // Configure the audio module to run our audio_state_change system when entities audio finishes
text_pipeline.schedule(.init); // playing
sprite_pipeline.schedule(.init); audio.state().on_state_change = game.system(.audio_state_change);
// Create a sprite rendering pipeline // Create a sprite rendering pipeline
const allocator = gpa.allocator(); const allocator = gpa.allocator();
@ -79,13 +96,9 @@ fn init(
sprite_pipeline.schedule(.update); sprite_pipeline.schedule(.update);
// TODO: a better way to initialize entities with default values // TODO: a better way to initialize entities with default values
// TODO(text): most of these style options are not respected yet. // TODO(text): ability to specify other style options (custom font name, font color, italic/bold, etc.)
const style1 = try entities.new(); const style1 = try entities.new();
try text_style.set(style1, .font_name, "Roboto Medium"); // TODO
try text_style.set(style1, .font_size, 48 * gfx.px_per_pt); // 48pt try text_style.set(style1, .font_size, 48 * gfx.px_per_pt); // 48pt
try text_style.set(style1, .font_weight, gfx.font_weight_normal);
try text_style.set(style1, .italic, false);
try text_style.set(style1, .color, vec4(0.6, 1.0, 0.6, 1.0));
// Create a text rendering pipeline // Create a text rendering pipeline
const text_rendering_pipeline = try entities.new(); const text_rendering_pipeline = try entities.new();
@ -96,32 +109,34 @@ fn init(
const text1 = try entities.new(); const text1 = try entities.new();
try text.set(text1, .pipeline, text_rendering_pipeline); try text.set(text1, .pipeline, text_rendering_pipeline);
try text.set(text1, .transform, Mat4x4.translate(vec3(0, 0, 0))); try text.set(text1, .transform, Mat4x4.translate(vec3(0, 0, 0)));
try gfx.Text.allocPrintText(text, text1, style1,
// TODO: better storage mechanism for this
// TODO: this is a leak
const styles = try allocator.alloc(mach.EntityID, 1);
styles[0] = style1;
try text.set(text1, .text, &.{
\\ Mach is probably working if you: \\ Mach is probably working if you:
\\ * See this text \\ * See this text
\\ * See sprites to the left \\ * See sprites to the left
\\ * Hear sound effects \\ * Hear sounds when sprites die
\\ * Hold space and things go faster \\ * Hold space and things go faster
}); , .{});
try text.set(text1, .style, styles);
try text.set(text1, .dirty, true);
text.schedule(.update); text.schedule(.update);
const window_height: f32 = @floatFromInt(core.get(core.state().main_window, .height).?);
const info_text = try entities.new();
try text.set(info_text, .pipeline, text_rendering_pipeline);
try text.set(info_text, .transform, Mat4x4.translate(vec3(0, (window_height / 2.0) - 50.0, 0)));
try gfx.Text.allocPrintText(text, info_text, style1, "[info]", .{});
// Load sfx // Load sfx
const sfx_fbs = std.io.fixedBufferStream(assets.sfx.scifi_gun); const sfx_fbs = std.io.fixedBufferStream(assets.sfx.scifi_gun);
const sfx_sound_stream = std.io.StreamSource{ .const_buffer = sfx_fbs }; const sfx_sound_stream = std.io.StreamSource{ .const_buffer = sfx_fbs };
const sfx = try mach.Audio.Opus.decodeStream(gpa.allocator(), sfx_sound_stream); const sfx = try mach.Audio.Opus.decodeStream(gpa.allocator(), sfx_sound_stream);
game.init(.{ game.init(.{
.info_text = info_text,
.info_text_style = style1,
.timer = try mach.Timer.start(), .timer = try mach.Timer.start(),
.spawn_timer = try mach.Timer.start(), .spawn_timer = try mach.Timer.start(),
.fps_timer = try mach.Timer.start(), .fps_timer = try mach.Timer.start(),
.frame_count = 0, .frame_count = 0,
.frame_rate = 0,
.num_sprites_spawned = 0, .num_sprites_spawned = 0,
.score = 0, .score = 0,
.rand = std.rand.DefaultPrng.init(1337), .rand = std.rand.DefaultPrng.init(1337),
@ -133,12 +148,6 @@ fn init(
core.schedule(.start); core.schedule(.start);
} }
fn afterInit(audio: *mach.Audio.Mod, game: *Mod) void {
// Configure the audio module to run our audio_state_change system when entities audio finishes
// playing
audio.state().on_state_change = game.system(.audio_state_change);
}
fn audioStateChange(entities: *mach.Entities.Mod) !void { fn audioStateChange(entities: *mach.Entities.Mod) !void {
// Find audio entities that are no longer playing // Find audio entities that are no longer playing
var q = try entities.query(.{ var q = try entities.query(.{
@ -160,6 +169,7 @@ fn tick(
core: *mach.Core.Mod, core: *mach.Core.Mod,
sprite: *gfx.Sprite.Mod, sprite: *gfx.Sprite.Mod,
sprite_pipeline: *gfx.SpritePipeline.Mod, sprite_pipeline: *gfx.SpritePipeline.Mod,
text: *gfx.Text.Mod,
text_pipeline: *gfx.TextPipeline.Mod, text_pipeline: *gfx.TextPipeline.Mod,
game: *Mod, game: *Mod,
audio: *mach.Audio.Mod, audio: *mach.Audio.Mod,
@ -188,9 +198,25 @@ fn tick(
} }
game.state().gotta_go_fast = gotta_go_fast; game.state().gotta_go_fast = gotta_go_fast;
// Every second, update the frame rate
if (game.state().fps_timer.read() >= 1.0) {
game.state().frame_rate = game.state().frame_count;
game.state().fps_timer.reset();
game.state().frame_count = 0;
}
try gfx.Text.allocPrintText(
text,
game.state().info_text,
game.state().info_text_style,
"[ FPS: {d} ]\n[ Sprites spawned: {d} ]",
.{ game.state().frame_rate, game.state().num_sprites_spawned },
);
text.schedule(.update);
// var player_transform = sprite.get(game.state().player, .transform).?; // var player_transform = sprite.get(game.state().player, .transform).?;
// var player_pos = player_transform.translation(); // var player_pos = player_transform.translation();
const framebuffer_width: f32 = @floatFromInt(core.get(core.state().main_window, .framebuffer_width).?); const window_width: f32 = @floatFromInt(core.get(core.state().main_window, .width).?);
const entities_per_second: f32 = @floatFromInt( const entities_per_second: f32 = @floatFromInt(
game.state().rand.random().intRangeAtMost(usize, 0, if (gotta_go_fast) 50 else 10), game.state().rand.random().intRangeAtMost(usize, 0, if (gotta_go_fast) 50 else 10),
@ -199,7 +225,7 @@ fn tick(
// Spawn new entities // Spawn new entities
_ = game.state().spawn_timer.lap(); _ = game.state().spawn_timer.lap();
var new_pos = vec3(-(framebuffer_width / 2), 0, 0); var new_pos = vec3(-(window_width / 2), 0, 0);
new_pos.v[1] += game.state().rand.random().floatNorm(f32) * 50; new_pos.v[1] += game.state().rand.random().floatNorm(f32) * 50;
const new_entity = try entities.new(); const new_entity = try entities.new();
@ -222,7 +248,7 @@ fn tick(
for (v.ids, v.transforms) |id, *entity_transform| { for (v.ids, v.transforms) |id, *entity_transform| {
const location = entity_transform.*.translation(); const location = entity_transform.*.translation();
const speed: f32 = if (gotta_go_fast) 2000 else 100; const speed: f32 = if (gotta_go_fast) 2000 else 100;
const progression = std.math.clamp((location.v[0] + (framebuffer_width / 2.0)) / framebuffer_width, 0, 1); const progression = std.math.clamp((location.v[0] + (window_width / 2.0)) / window_width, 0, 1);
const scale = mach.math.lerp(2, 0, progression); const scale = mach.math.lerp(2, 0, progression);
if (progression >= 0.6) { if (progression >= 0.6) {
try entities.remove(id); try entities.remove(id);
@ -298,18 +324,6 @@ fn endFrame(game: *Mod, core: *mach.Core.Mod) !void {
// Present the frame // Present the frame
core.schedule(.present_frame); core.schedule(.present_frame);
// Every second, update the window title with the FPS
if (game.state().fps_timer.read() >= 1.0) {
try mach.Core.printTitle(
core,
core.state().main_window,
"sprite [ FPS: {d} ] [ Sprites spawned: {d} ]",
.{ game.state().frame_count, game.state().num_sprites_spawned },
);
core.schedule(.update);
game.state().fps_timer.reset();
game.state().frame_count = 0;
}
game.state().frame_count += 1; game.state().frame_count += 1;
} }

View file

@ -15,8 +15,6 @@ const Vec3 = math.Vec3;
const Mat3x3 = math.Mat3x3; const Mat3x3 = math.Mat3x3;
const Mat4x4 = math.Mat4x4; const Mat4x4 = math.Mat4x4;
var gpa = std.heap.GeneralPurposeAllocator(.{}){};
timer: mach.Timer, timer: mach.Timer,
player: mach.EntityID, player: mach.EntityID,
direction: Vec2 = vec2(0, 0), direction: Vec2 = vec2(0, 0),
@ -27,7 +25,6 @@ frame_count: usize,
rand: std.rand.DefaultPrng, rand: std.rand.DefaultPrng,
time: f32, time: f32,
style1: mach.EntityID, style1: mach.EntityID,
allocator: std.mem.Allocator,
pipeline: mach.EntityID, pipeline: mach.EntityID,
frame_encoder: *gpu.CommandEncoder = undefined, frame_encoder: *gpu.CommandEncoder = undefined,
frame_render_pass: *gpu.RenderPassEncoder = undefined, frame_render_pass: *gpu.RenderPassEncoder = undefined,
@ -40,6 +37,7 @@ pub const Mod = mach.Mod(@This());
pub const systems = .{ pub const systems = .{
.init = .{ .handler = init }, .init = .{ .handler = init },
.deinit = .{ .handler = deinit }, .deinit = .{ .handler = deinit },
.after_init = .{ .handler = afterInit },
.tick = .{ .handler = tick }, .tick = .{ .handler = tick },
.end_frame = .{ .handler = endFrame }, .end_frame = .{ .handler = endFrame },
}; };
@ -47,12 +45,12 @@ pub const systems = .{
const upscale = 1.0; const upscale = 1.0;
const text1: []const []const u8 = &.{ const text1: []const []const u8 = &.{
"Text but with spaces 😊\nand\n", "Text but with spaces\n",
"italics\nand\n", "and\n",
"bold\nand\n", "newlines\n",
}; };
const text2: []const []const u8 = &.{"$!?😊"}; const text2: []const []const u8 = &.{"$!?"};
fn deinit( fn deinit(
core: *mach.Core.Mod, core: *mach.Core.Mod,
@ -63,6 +61,16 @@ fn deinit(
} }
fn init( fn init(
text: *gfx.Text.Mod,
text_pipeline: *gfx.TextPipeline.Mod,
game: *Mod,
) !void {
text.schedule(.init);
text_pipeline.schedule(.init);
game.schedule(.after_init);
}
fn afterInit(
entities: *mach.Entities.Mod, entities: *mach.Entities.Mod,
core: *mach.Core.Mod, core: *mach.Core.Mod,
text: *gfx.Text.Mod, text: *gfx.Text.Mod,
@ -70,30 +78,10 @@ fn init(
text_style: *gfx.TextStyle.Mod, text_style: *gfx.TextStyle.Mod,
game: *Mod, game: *Mod,
) !void { ) !void {
text_pipeline.schedule(.init);
// TODO: a better way to initialize entities with default values // TODO: a better way to initialize entities with default values
// TODO(text): most of these style options are not respected yet. // TODO(text): ability to specify other style options (custom font name, font color, italic/bold, etc.)
const style1 = try entities.new(); const style1 = try entities.new();
try text_style.set(style1, .font_name, "Roboto Medium"); // TODO
try text_style.set(style1, .font_size, 48 * gfx.px_per_pt); // 48pt try text_style.set(style1, .font_size, 48 * gfx.px_per_pt); // 48pt
try text_style.set(style1, .font_weight, gfx.font_weight_normal);
try text_style.set(style1, .italic, false);
try text_style.set(style1, .color, vec4(0.6, 1.0, 0.6, 1.0));
const style2 = try entities.new();
try text_style.set(style2, .font_name, "Roboto Medium"); // TODO
try text_style.set(style2, .font_size, 48 * gfx.px_per_pt); // 48pt
try text_style.set(style2, .font_weight, gfx.font_weight_normal);
try text_style.set(style2, .italic, true);
try text_style.set(style2, .color, vec4(0.6, 1.0, 0.6, 1.0));
const style3 = try entities.new();
try text_style.set(style3, .font_name, "Roboto Medium"); // TODO
try text_style.set(style3, .font_size, 48 * gfx.px_per_pt); // 48pt
try text_style.set(style3, .font_weight, gfx.font_weight_bold);
try text_style.set(style3, .italic, false);
try text_style.set(style3, .color, vec4(0.6, 1.0, 0.6, 1.0));
// Create a text rendering pipeline // Create a text rendering pipeline
const pipeline = try entities.new(); const pipeline = try entities.new();
@ -103,18 +91,13 @@ fn init(
// Create some text // Create some text
const player = try entities.new(); const player = try entities.new();
try text.set(player, .pipeline, pipeline); try text.set(player, .pipeline, pipeline);
try text.set(player, .transform, Mat4x4.scaleScalar(upscale).mul(&Mat4x4.translate(vec3(0, 0, 0)))); try text.set(player, .transform, Mat4x4.translate(vec3(0, 0, 0)));
try gfx.Text.allocPrintText(text, player, style1,
// TODO: better storage mechanism for this \\ Text with spaces
// TODO: this is a leak \\ and newlines
const allocator = gpa.allocator(); \\ but nothing fancy yet
const styles = try allocator.alloc(mach.EntityID, 3); , .{});
styles[0] = style1; text.schedule(.update);
styles[1] = style2;
styles[2] = style3;
try text.set(player, .text, text1);
try text.set(player, .style, styles);
try text.set(player, .dirty, true);
game.init(.{ game.init(.{
.timer = try mach.Timer.start(), .timer = try mach.Timer.start(),
@ -125,7 +108,6 @@ fn init(
.rand = std.rand.DefaultPrng.init(1337), .rand = std.rand.DefaultPrng.init(1337),
.time = 0, .time = 0,
.style1 = style1, .style1 = style1,
.allocator = allocator,
.pipeline = pipeline, .pipeline = pipeline,
}); });
@ -183,17 +165,11 @@ fn tick(
new_pos.v[0] += game.state().rand.random().floatNorm(f32) * 50; new_pos.v[0] += game.state().rand.random().floatNorm(f32) * 50;
new_pos.v[1] += game.state().rand.random().floatNorm(f32) * 50; new_pos.v[1] += game.state().rand.random().floatNorm(f32) * 50;
// Create some text
const new_entity = try entities.new(); const new_entity = try entities.new();
try text.set(new_entity, .pipeline, game.state().pipeline); try text.set(new_entity, .pipeline, game.state().pipeline);
try text.set(new_entity, .transform, Mat4x4.scaleScalar(upscale).mul(&Mat4x4.translate(new_pos))); try text.set(new_entity, .transform, Mat4x4.scaleScalar(upscale).mul(&Mat4x4.translate(new_pos)));
try gfx.Text.allocPrintText(text, new_entity, game.state().style1, "?!$", .{});
// TODO: better storage mechanism for this
// TODO: this is a leak
const styles = try game.state().allocator.alloc(mach.EntityID, 1);
styles[0] = game.state().style1;
try text.set(new_entity, .text, text2);
try text.set(new_entity, .style, styles);
try text.set(new_entity, .dirty, true);
} }
} }

View file

@ -88,7 +88,6 @@ pub fn printTitle(
args: anytype, args: anytype,
) !void { ) !void {
// Free any previous window title slice // Free any previous window title slice
// TODO: reuse allocations
if (core.get(window_id, .title)) |slice| core.state().allocator.free(slice); if (core.get(window_id, .title)) |slice| core.state().allocator.free(slice);
// Allocate and assign a new window title slice. // Allocate and assign a new window title slice.

View file

@ -12,6 +12,8 @@ const vec4 = math.vec4;
const Mat3x3 = math.Mat3x3; const Mat3x3 = math.Mat3x3;
const Mat4x4 = math.Mat4x4; const Mat4x4 = math.Mat4x4;
var gpa = std.heap.GeneralPurposeAllocator(.{}){};
pub const name = .mach_gfx_text; pub const name = .mach_gfx_text;
pub const Mod = mach.Mod(@This()); pub const Mod = mach.Mod(@This());
@ -51,6 +53,8 @@ pub const components = .{
}; };
pub const systems = .{ pub const systems = .{
.init = .{ .handler = init },
.deinit = .{ .handler = deinit },
.update = .{ .handler = update }, .update = .{ .handler = update },
}; };
@ -58,6 +62,52 @@ const BuiltText = struct {
glyphs: std.ArrayListUnmanaged(gfx.TextPipeline.Glyph), glyphs: std.ArrayListUnmanaged(gfx.TextPipeline.Glyph),
}; };
allocator: std.mem.Allocator,
pub fn init(text: *Mod) void {
text.init(.{ .allocator = gpa.allocator() });
}
pub fn deinit(text: *Mod) void {
_ = text;
// TODO: help with cleaning up allocPrintText, which is currently a little difficult to track
// since it is a per-entity allocation
}
/// Helper to set text components on an entity simply/easily via heap allocating strings
///
/// ```
/// try mach.Text.allocPrintText(text, my_text_entity, my_style_entity, "Hello, {s}!", .{"Mach"});
/// ```
pub fn allocPrintText(
text: *Mod,
id: mach.EntityID,
style: mach.EntityID,
comptime fmt: []const u8,
args: anytype,
) !void {
freeText(text, id);
const str = try std.fmt.allocPrint(text.state().allocator, fmt, args);
const styles = try text.state().allocator.alloc(mach.EntityID, 1);
styles[0] = style;
const strings = try text.state().allocator.alloc([]const u8, 1);
strings[0] = str;
try text.set(id, .style, styles);
try text.set(id, .text, strings);
try text.set(id, .dirty, true);
}
/// Free's an entity's .text and .style slices that were previously allocated via e.g. allocPrintText
pub fn freeText(text: *Mod, id: mach.EntityID) void {
if (text.get(id, .text)) |slice| {
text.state().allocator.free(slice[0]);
text.state().allocator.free(slice);
}
if (text.get(id, .style)) |slice| text.state().allocator.free(slice);
}
fn update( fn update(
entities: *mach.Entities.Mod, entities: *mach.Entities.Mod,
text: *Mod, text: *Mod,
@ -149,8 +199,8 @@ fn updatePipeline(
// Load the font // Load the font
// TODO(text): allow specifying a custom font // TODO(text): allow specifying a custom font
// TODO(text): keep fonts around for reuse later // TODO(text): keep fonts around for reuse later
const font_name = text_style.get(style, .font_name).?; // const font_name = text_style.get(style, .font_name).?;
_ = font_name; // TODO: actually use font name // _ = font_name; // TODO: actually use font name
const font_bytes = @import("font-assets").fira_sans_regular_ttf; const font_bytes = @import("font-assets").fira_sans_regular_ttf;
var font = if (font_once) |f| f else blk: { var font = if (font_once) |f| f else blk: {
font_once = try gfx.Font.initBytes(font_bytes); font_once = try gfx.Font.initBytes(font_bytes);
@ -160,12 +210,9 @@ fn updatePipeline(
const font_size = text_style.get(style, .font_size).?; const font_size = text_style.get(style, .font_size).?;
// TODO(text): respect these style parameters // TODO(text): respect these style parameters
const font_weight = text_style.get(style, .font_weight).?; // const font_weight = text_style.get(style, .font_weight).?;
const italic = text_style.get(style, .italic).?; // const italic = text_style.get(style, .italic).?;
const color = text_style.get(style, .color).?; // const color = text_style.get(style, .color).?;
_ = font_weight;
_ = italic;
_ = color;
// Create a text shaper // Create a text shaper
var run = try gfx.TextRun.init(); var run = try gfx.TextRun.init();

View file

@ -5,11 +5,11 @@ pub const name = .mach_gfx_text_style;
pub const Mod = mach.Mod(@This()); pub const Mod = mach.Mod(@This());
pub const components = .{ pub const components = .{
// TODO: ship a default font // // TODO: ship a default font
.font_name = .{ .type = []const u8, .description = // .font_name = .{ .type = []const u8, .description =
\\ Desired font to render text with. // \\ Desired font to render text with.
\\ TODO(text): this is not currently implemented // \\ TODO(text): this is not currently implemented
}, // },
// e.g. 12 * mach.gfx.px_per_pt // 12pt // e.g. 12 * mach.gfx.px_per_pt // 12pt
.font_size = .{ .type = f32, .description = .font_size = .{ .type = f32, .description =
@ -17,23 +17,23 @@ pub const components = .{
\\ TODO(text): this is not currently implemented \\ TODO(text): this is not currently implemented
}, },
// e.g. mach.gfx.font_weight_normal // // e.g. mach.gfx.font_weight_normal
.font_weight = .{ .type = u16, .description = // .font_weight = .{ .type = u16, .description =
\\ Font weight // \\ Font weight
\\ TODO(text): this is not currently implemented // \\ TODO(text): this is not currently implemented
}, // },
// e.g. false // // e.g. false
.italic = .{ .type = bool, .description = // .italic = .{ .type = bool, .description =
\\ Italic text // \\ Italic text
\\ TODO(text): this is not currently implemented // \\ TODO(text): this is not currently implemented
}, // },
// e.g. vec4(0, 0, 0, 1.0) // // e.g. vec4(0, 0, 0, 1.0)
.color = .{ .type = math.Vec4, .description = // .color = .{ .type = math.Vec4, .description =
\\ Fill color // \\ Fill color
\\ TODO(text): this is not currently implemented // \\ TODO(text): this is not currently implemented
}, // },
// TODO(text): allow user to specify projection matrix (3d-space flat text etc.) // TODO(text): allow user to specify projection matrix (3d-space flat text etc.)
}; };