From 122a1ea9a7c07b497a550e2c93d7d5b19db6da07 Mon Sep 17 00:00:00 2001 From: Stephen Gutekanst Date: Mon, 13 May 2024 22:38:40 +0200 Subject: [PATCH] {gfx,examples}: simplify text rendering API a bit Signed-off-by: Stephen Gutekanst --- examples/hardware-check/App.zig | 92 +++++++++++++++++++-------------- examples/text/App.zig | 74 +++++++++----------------- src/Core.zig | 1 - src/gfx/Text.zig | 63 +++++++++++++++++++--- src/gfx/TextStyle.zig | 40 +++++++------- 5 files changed, 153 insertions(+), 117 deletions(-) diff --git a/examples/hardware-check/App.zig b/examples/hardware-check/App.zig index 975a88ed..fd983b72 100644 --- a/examples/hardware-check/App.zig +++ b/examples/hardware-check/App.zig @@ -17,11 +17,14 @@ const Mat4x4 = math.Mat4x4; var gpa = std.heap.GeneralPurposeAllocator(.{}){}; +info_text: mach.EntityID, +info_text_style: mach.EntityID, timer: mach.Timer, gotta_go_fast: bool = false, spawn_timer: mach.Timer, fps_timer: mach.Timer, frame_count: usize, +frame_rate: usize, num_sprites_spawned: usize, score: usize, rand: std.rand.DefaultPrng, @@ -59,6 +62,20 @@ fn deinit( } 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, core: *mach.Core.Mod, audio: *mach.Audio.Mod, @@ -68,9 +85,9 @@ fn init( sprite_pipeline: *gfx.SpritePipeline.Mod, game: *Mod, ) !void { - audio.schedule(.init); - text_pipeline.schedule(.init); - sprite_pipeline.schedule(.init); + // 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); // Create a sprite rendering pipeline const allocator = gpa.allocator(); @@ -79,13 +96,9 @@ fn init( sprite_pipeline.schedule(.update); // 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(); - 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_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 const text_rendering_pipeline = try entities.new(); @@ -96,32 +109,34 @@ fn init( const text1 = try entities.new(); try text.set(text1, .pipeline, text_rendering_pipeline); try text.set(text1, .transform, Mat4x4.translate(vec3(0, 0, 0))); - - // 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, &.{ + try gfx.Text.allocPrintText(text, text1, style1, \\ Mach is probably working if you: \\ * See this text \\ * See sprites to the left - \\ * Hear sound effects + \\ * Hear sounds when sprites die \\ * Hold space and things go faster - }); - try text.set(text1, .style, styles); - try text.set(text1, .dirty, true); + , .{}); 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 const sfx_fbs = std.io.fixedBufferStream(assets.sfx.scifi_gun); const sfx_sound_stream = std.io.StreamSource{ .const_buffer = sfx_fbs }; const sfx = try mach.Audio.Opus.decodeStream(gpa.allocator(), sfx_sound_stream); game.init(.{ + .info_text = info_text, + .info_text_style = style1, .timer = try mach.Timer.start(), .spawn_timer = try mach.Timer.start(), .fps_timer = try mach.Timer.start(), .frame_count = 0, + .frame_rate = 0, .num_sprites_spawned = 0, .score = 0, .rand = std.rand.DefaultPrng.init(1337), @@ -133,12 +148,6 @@ fn init( 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 { // Find audio entities that are no longer playing var q = try entities.query(.{ @@ -160,6 +169,7 @@ fn tick( core: *mach.Core.Mod, sprite: *gfx.Sprite.Mod, sprite_pipeline: *gfx.SpritePipeline.Mod, + text: *gfx.Text.Mod, text_pipeline: *gfx.TextPipeline.Mod, game: *Mod, audio: *mach.Audio.Mod, @@ -188,9 +198,25 @@ fn tick( } 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_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( game.state().rand.random().intRangeAtMost(usize, 0, if (gotta_go_fast) 50 else 10), @@ -199,7 +225,7 @@ fn tick( // Spawn new entities _ = 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; const new_entity = try entities.new(); @@ -222,7 +248,7 @@ fn tick( for (v.ids, v.transforms) |id, *entity_transform| { const location = entity_transform.*.translation(); 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); if (progression >= 0.6) { try entities.remove(id); @@ -298,18 +324,6 @@ fn endFrame(game: *Mod, core: *mach.Core.Mod) !void { // Present the 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; } diff --git a/examples/text/App.zig b/examples/text/App.zig index 6d33ecd5..1dcb5481 100644 --- a/examples/text/App.zig +++ b/examples/text/App.zig @@ -15,8 +15,6 @@ const Vec3 = math.Vec3; const Mat3x3 = math.Mat3x3; const Mat4x4 = math.Mat4x4; -var gpa = std.heap.GeneralPurposeAllocator(.{}){}; - timer: mach.Timer, player: mach.EntityID, direction: Vec2 = vec2(0, 0), @@ -27,7 +25,6 @@ frame_count: usize, rand: std.rand.DefaultPrng, time: f32, style1: mach.EntityID, -allocator: std.mem.Allocator, pipeline: mach.EntityID, frame_encoder: *gpu.CommandEncoder = undefined, frame_render_pass: *gpu.RenderPassEncoder = undefined, @@ -40,6 +37,7 @@ pub const Mod = mach.Mod(@This()); pub const systems = .{ .init = .{ .handler = init }, .deinit = .{ .handler = deinit }, + .after_init = .{ .handler = afterInit }, .tick = .{ .handler = tick }, .end_frame = .{ .handler = endFrame }, }; @@ -47,12 +45,12 @@ pub const systems = .{ const upscale = 1.0; const text1: []const []const u8 = &.{ - "Text but with spaces 😊\nand\n", - "italics\nand\n", - "bold\nand\n", + "Text but with spaces\n", + "and\n", + "newlines\n", }; -const text2: []const []const u8 = &.{"$!?😊"}; +const text2: []const []const u8 = &.{"$!?"}; fn deinit( core: *mach.Core.Mod, @@ -63,6 +61,16 @@ fn deinit( } 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, core: *mach.Core.Mod, text: *gfx.Text.Mod, @@ -70,30 +78,10 @@ fn init( text_style: *gfx.TextStyle.Mod, game: *Mod, ) !void { - text_pipeline.schedule(.init); - // 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(); - 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_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 const pipeline = try entities.new(); @@ -103,18 +91,13 @@ fn init( // Create some text const player = try entities.new(); try text.set(player, .pipeline, pipeline); - try text.set(player, .transform, Mat4x4.scaleScalar(upscale).mul(&Mat4x4.translate(vec3(0, 0, 0)))); - - // TODO: better storage mechanism for this - // TODO: this is a leak - const allocator = gpa.allocator(); - const styles = try allocator.alloc(mach.EntityID, 3); - styles[0] = style1; - styles[1] = style2; - styles[2] = style3; - try text.set(player, .text, text1); - try text.set(player, .style, styles); - try text.set(player, .dirty, true); + try text.set(player, .transform, Mat4x4.translate(vec3(0, 0, 0))); + try gfx.Text.allocPrintText(text, player, style1, + \\ Text with spaces + \\ and newlines + \\ but nothing fancy yet + , .{}); + text.schedule(.update); game.init(.{ .timer = try mach.Timer.start(), @@ -125,7 +108,6 @@ fn init( .rand = std.rand.DefaultPrng.init(1337), .time = 0, .style1 = style1, - .allocator = allocator, .pipeline = pipeline, }); @@ -183,17 +165,11 @@ fn tick( new_pos.v[0] += 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(); try text.set(new_entity, .pipeline, game.state().pipeline); try text.set(new_entity, .transform, Mat4x4.scaleScalar(upscale).mul(&Mat4x4.translate(new_pos))); - - // 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); + try gfx.Text.allocPrintText(text, new_entity, game.state().style1, "?!$", .{}); } } diff --git a/src/Core.zig b/src/Core.zig index a9d71bcb..b3be208c 100644 --- a/src/Core.zig +++ b/src/Core.zig @@ -88,7 +88,6 @@ pub fn printTitle( args: anytype, ) !void { // Free any previous window title slice - // TODO: reuse allocations if (core.get(window_id, .title)) |slice| core.state().allocator.free(slice); // Allocate and assign a new window title slice. diff --git a/src/gfx/Text.zig b/src/gfx/Text.zig index 3f41978d..ccbf77ec 100644 --- a/src/gfx/Text.zig +++ b/src/gfx/Text.zig @@ -12,6 +12,8 @@ const vec4 = math.vec4; const Mat3x3 = math.Mat3x3; const Mat4x4 = math.Mat4x4; +var gpa = std.heap.GeneralPurposeAllocator(.{}){}; + pub const name = .mach_gfx_text; pub const Mod = mach.Mod(@This()); @@ -51,6 +53,8 @@ pub const components = .{ }; pub const systems = .{ + .init = .{ .handler = init }, + .deinit = .{ .handler = deinit }, .update = .{ .handler = update }, }; @@ -58,6 +62,52 @@ const BuiltText = struct { 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( entities: *mach.Entities.Mod, text: *Mod, @@ -149,8 +199,8 @@ fn updatePipeline( // Load the font // TODO(text): allow specifying a custom font // TODO(text): keep fonts around for reuse later - const font_name = text_style.get(style, .font_name).?; - _ = font_name; // TODO: actually use font name + // const font_name = text_style.get(style, .font_name).?; + // _ = font_name; // TODO: actually use font name const font_bytes = @import("font-assets").fira_sans_regular_ttf; var font = if (font_once) |f| f else blk: { font_once = try gfx.Font.initBytes(font_bytes); @@ -160,12 +210,9 @@ fn updatePipeline( const font_size = text_style.get(style, .font_size).?; // TODO(text): respect these style parameters - const font_weight = text_style.get(style, .font_weight).?; - const italic = text_style.get(style, .italic).?; - const color = text_style.get(style, .color).?; - _ = font_weight; - _ = italic; - _ = color; + // const font_weight = text_style.get(style, .font_weight).?; + // const italic = text_style.get(style, .italic).?; + // const color = text_style.get(style, .color).?; // Create a text shaper var run = try gfx.TextRun.init(); diff --git a/src/gfx/TextStyle.zig b/src/gfx/TextStyle.zig index c12fa9b2..a73979a8 100644 --- a/src/gfx/TextStyle.zig +++ b/src/gfx/TextStyle.zig @@ -5,11 +5,11 @@ pub const name = .mach_gfx_text_style; pub const Mod = mach.Mod(@This()); pub const components = .{ - // TODO: ship a default font - .font_name = .{ .type = []const u8, .description = - \\ Desired font to render text with. - \\ TODO(text): this is not currently implemented - }, + // // TODO: ship a default font + // .font_name = .{ .type = []const u8, .description = + // \\ Desired font to render text with. + // \\ TODO(text): this is not currently implemented + // }, // e.g. 12 * mach.gfx.px_per_pt // 12pt .font_size = .{ .type = f32, .description = @@ -17,23 +17,23 @@ pub const components = .{ \\ TODO(text): this is not currently implemented }, - // e.g. mach.gfx.font_weight_normal - .font_weight = .{ .type = u16, .description = - \\ Font weight - \\ TODO(text): this is not currently implemented - }, + // // e.g. mach.gfx.font_weight_normal + // .font_weight = .{ .type = u16, .description = + // \\ Font weight + // \\ TODO(text): this is not currently implemented + // }, - // e.g. false - .italic = .{ .type = bool, .description = - \\ Italic text - \\ TODO(text): this is not currently implemented - }, + // // e.g. false + // .italic = .{ .type = bool, .description = + // \\ Italic text + // \\ TODO(text): this is not currently implemented + // }, - // e.g. vec4(0, 0, 0, 1.0) - .color = .{ .type = math.Vec4, .description = - \\ Fill color - \\ TODO(text): this is not currently implemented - }, + // // e.g. vec4(0, 0, 0, 1.0) + // .color = .{ .type = math.Vec4, .description = + // \\ Fill color + // \\ TODO(text): this is not currently implemented + // }, // TODO(text): allow user to specify projection matrix (3d-space flat text etc.) };