Compare commits

..

10 Commits

24 changed files with 2341 additions and 213 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

@ -0,0 +1,21 @@
Sokoban (pack)
by Kenney Vleugels (Kenney.nl)
------------------------------
License (Creative Commons Zero, CC0)
http://creativecommons.org/publicdomain/zero/1.0/
You may use these assets in personal and commercial projects.
Credit (Kenney or www.kenney.nl) would be nice but is not mandatory.
------------------------------
Donate: http://support.kenney.nl
Request: http://request.kenney.nl
Follow on Twitter for updates:
@KenneyNL

BIN
assets/sokoban/Preview.png Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 171 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 153 KiB

BIN
assets/sokoban/Sample.png Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 106 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 93 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 200 KiB

View File

@ -5,10 +5,19 @@ pub fn build(b: *std.Build) !void {
const target = b.standardTargetOptions(.{});
const optimize = b.standardOptimizeOption(.{});
const assets_dir = "assets";
const asset_files = [_][]const u8{
"sokoban/sokoban_tilesheet.png",
"roboto-font/Roboto-Regular.ttf"
};
const asset_dir_realpath = try b.build_root.join(b.graph.arena, &.{ assets_dir });
const is_wasm = target.result.cpu.arch.isWasm();
const is_debug = (optimize == .Debug);
const has_imgui = b.option(bool, "imgui", "ImGui integration") orelse is_debug;
const assets_from_filesystem = b.option(bool, "assets-filesystem", "Allow reading assets from filesystem") orelse is_debug;
var has_tracy = false;
if (!is_wasm) {
@ -23,8 +32,11 @@ pub fn build(b: *std.Build) !void {
const build_options = b.addOptions();
build_options.addOption(bool, "has_imgui", has_imgui);
build_options.addOption(?[]const u8, "assets_dir", if (assets_from_filesystem) asset_dir_realpath else null);
exe_mod.addOptions("build_options", build_options);
exe_mod.addImport("embedded_assets", try createEmbeddedAssets(b, assets_dir, &asset_files));
const math_mod = b.createModule(.{
.root_source_file = b.path("src/math.zig")
});
@ -40,16 +52,21 @@ pub fn build(b: *std.Build) !void {
exe_mod.addImport("sokol", mod_sokol);
const dep_shdc = dep_sokol.builder.dependency("shdc", .{});
var slang = sokol.shdc.Slang{};
if (is_wasm) {
slang.wgsl = true;
} else {
slang.glsl410 = true;
slang.hlsl4 = true;
slang.metal_macos = true;
slang.glsl300es = true;
}
const mod_shader = try sokol.shdc.createModule(b, "shader", mod_sokol, .{
.shdc_dep = dep_shdc,
.input = "src/shader.glsl",
.output = "src/shader.zig",
.slang = .{
.glsl410 = true,
.hlsl4 = true,
.metal_macos = true,
.glsl300es = true,
},
.slang = slang
});
mod_shader.addImport("math", math_mod);
exe_mod.addImport("shader", mod_shader);
@ -69,6 +86,8 @@ pub fn build(b: *std.Build) !void {
const dep_stb = b.dependency("stb", .{});
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,
@ -128,6 +147,43 @@ pub fn build(b: *std.Build) !void {
run_step.dependOn(run_cmd_step);
}
fn createEmbeddedAssets(
b: *std.Build,
assets_dir: []const u8,
asset_files: []const []const u8
) !*std.Build.Module {
const write_files = b.addWriteFiles();
var embedded_assets: std.ArrayList(u8) = .empty;
defer embedded_assets.deinit(b.allocator);
try embedded_assets.appendSlice(b.allocator, "pub const files = .{\n");
const mod_embedded_assets = b.createModule(.{});
for (asset_files) |asset_file| {
mod_embedded_assets.addAnonymousImport(asset_file, .{
.root_source_file = b.path(b.pathJoin(&.{ assets_dir, asset_file }))
});
try embedded_assets.appendSlice(b.allocator, " .{ ");
try embedded_assets.appendSlice(b.allocator, ".name = \"");
try embedded_assets.appendSlice(b.allocator, asset_file);
try embedded_assets.appendSlice(b.allocator, "\"");
try embedded_assets.appendSlice(b.allocator, ", ");
try embedded_assets.appendSlice(b.allocator, ".contents = @embedFile(\"");
try embedded_assets.appendSlice(b.allocator, asset_file);
try embedded_assets.appendSlice(b.allocator, "\")");
try embedded_assets.appendSlice(b.allocator, " },\n");
}
try embedded_assets.appendSlice(b.allocator, "};\n");
mod_embedded_assets.root_source_file = write_files.add("embedded_assets.zig", embedded_assets.items);
return mod_embedded_assets;
}
const BuildNativeOptions = struct {
name: []const u8,
root_module: *std.Build.Module,

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,38 +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_image = b.addModule("stb_vorbis", .{
.target = target,
.optimize = optimize,
.root_source_file = b.path("src/stb_vorbis.zig"),
.link_libc = true,
});
mod_stb_image.addIncludePath(stb_dependency.path("."));
mod_stb_image.addCSourceFile(.{
.file = b.path("src/stb_vorbis_impl.c"),
.flags = &.{}
});
}
mod.addIncludePath(stb_dependency.path("."));
mod.addCSourceFile(.{
.file = impl_file,
.flags = &.{}
});
}

View File

@ -0,0 +1,36 @@
const std = @import("std");
const c = @cImport({
@cInclude("stb_rect_pack.h");
});
const STBRectPack = @This();
ctx: c.stbrp_context,
pub fn init(self: *STBRectPack, width: u32, height: u32, nodes: []Node) void {
c.stbrp_init_target(&self.ctx, @intCast(width), @intCast(height), nodes.ptr, @intCast(nodes.len));
}
pub fn setupAllowOutOfMem(self: *STBRectPack, enabled: bool) void {
c.stbrp_setup_heuristic(&self.ctx, if (enabled) 1 else 0);
}
pub fn setupHeuristic(self: *STBRectPack, heuristic: Heuristic) void {
c.stbrp_setup_heuristic(&self.ctx, heuristic);
}
pub fn packRects(self: *STBRectPack, rects: []Rect) bool {
return c.stbrp_pack_rects(&self.ctx, rects.ptr, @intCast(rects.len)) == 1;
}
pub const Heuristic = enum(i32) {
Skyline_BL_sortHeight = c.STBRP_HEURISTIC_Skyline_BL_sortHeight,
Skyline_BF_sortHeight = c.STBRP_HEURISTIC_Skyline_BF_sortHeight,
_,
pub const default = Heuristic.Skyline_BL_sortHeight;
};
pub const Node = c.stbrp_node;
pub const Rect = c.stbrp_rect;

View File

@ -0,0 +1,2 @@
#define STB_RECT_PACK_IMPLEMENTATION
#include "stb_rect_pack.h"

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: u32) i32 {
return c.stbtt_GetGlyphKernAdvance(&self.info, @intCast(prev_glyph), @intCast(next_glyph));
}
};

View File

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

View File

@ -6,10 +6,12 @@ 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;
const ImGUI = Platform.ImGUI;
const Rect = Platform.Rect;
const App = @This();
@ -17,25 +19,58 @@ bg: Platform.Color,
show_first_window: bool,
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();
const spritesheet = Gfx.ImageData{
.width = image.width,
.height = image.height,
.pixels = .{ .rgba8 = image.rgba8_pixels }
};
const tile_size = Vec2.init(64, 64);
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(.{});
Gfx.setSprite(wall_sprite, .{
.image = spritesheet,
.rect = Rect.init(1, 0, 1, 1).multiply(tile_size)
});
self.* = App{
.bg = .black,
.player_pos = .init(100, 100),
.show_first_window = true,
.check = false,
.sprite_sprite = player_sprite,
.wall_sprite = wall_sprite,
.roboto_font = robot_font
};
const cwd = std.Io.Dir.cwd();
const sokoban_spritesheet = try cwd.readFileAlloc(
plt.io,
"assets/sokoban/Spritesheet/sokoban_spritesheet.png",
plt.gpa,
.unlimited
);
defer plt.gpa.free(sokoban_spritesheet);
var image = try STBImage.load(sokoban_spritesheet);
defer image.deinit();
return null;
}
@ -62,8 +97,13 @@ pub fn frame(self: *App, plt: Platform.Frame) !void {
self.player_pos = self.player_pos.add(dir.multiplyScalar(50 * dt));
Gfx.setClearColor(self.bg);
Gfx.drawRectangle(self.player_pos, .init(100, 100), .rgb(200, 0, 0));
Gfx.drawRectangle(self.player_pos.add(.init(0, 200)), .init(100, 100), .rgb(200, 200, 0));
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",

View File

@ -10,6 +10,7 @@ a: f32,
pub const black = rgb(0, 0, 0);
pub const white = rgb(255, 255, 255);
pub const purple = rgb(255, 0, 255);
pub fn rgba(r: u8, g: u8, b: u8, a: f32) Color {
assert(0 <= a and a <= 1);

File diff suppressed because it is too large Load Diff

View File

@ -18,6 +18,7 @@ const ig = @import("cimgui");
const ImGUI = @This();
const State = struct {
enabled: bool,
frame: ?Allocator
};
@ -40,6 +41,7 @@ pub fn init(logger: simgui.Logger) void {
}
self.* = State{
.enabled = true,
.frame = null
};
}
@ -57,10 +59,15 @@ pub fn event(e: sapp.Event) bool {
return false;
}
const self = &g_state;
if (!self.enabled) {
return false;
}
return simgui.handleEvent(e);
}
pub fn beginFrame(frame: Allocator) void {
pub fn beginFrame(enabled: bool, frame: Allocator) void {
if (!build_options.has_imgui) {
return;
}
@ -68,6 +75,11 @@ pub fn beginFrame(frame: Allocator) void {
const self = &g_state;
self.frame = frame;
self.enabled = enabled;
if (!self.enabled) {
return;
}
simgui.newFrame(.{
.width = sapp.width(),
@ -105,6 +117,10 @@ pub fn endFrame() void {
if (!build_options.has_imgui) {
return;
}
const self = &g_state;
if (!self.enabled) {
return;
}
// TODO:
// if (ig.igBegin("Game", null, ig.ImGuiWindowFlags_None)) {
@ -140,6 +156,10 @@ pub fn beginWindow(opts: WindowOptions) bool {
if (!build_options.has_imgui) {
return false;
}
const self = &g_state;
if (!self.enabled) {
return false;
}
if (opts.open != null and opts.open.?.* == false) {
return false;
@ -180,6 +200,10 @@ pub fn endWindow() void {
if (!build_options.has_imgui) {
return;
}
const self = &g_state;
if (!self.enabled) {
return;
}
ig.igEnd();
}
@ -196,6 +220,10 @@ pub fn text(comptime fmt: []const u8, args: anytype) void {
if (!build_options.has_imgui) {
return;
}
const self = &g_state;
if (!self.enabled) {
return;
}
ig.igTextUnformatted(formatString(fmt, args));
}
@ -204,6 +232,10 @@ pub fn button(label: []const u8) bool {
if (!build_options.has_imgui) {
return false;
}
const self = &g_state;
if (!self.enabled) {
return false;
}
return ig.igButton(formatString("{s}", .{label}));
}
@ -219,6 +251,10 @@ pub fn slider(opts: SliderOptions) bool {
if (!build_options.has_imgui) {
return false;
}
const self = &g_state;
if (!self.enabled) {
return false;
}
return ig.igSliderFloat(
formatString("{s}", .{opts.label}),
@ -232,6 +268,10 @@ pub fn checkbox(label: []const u8, value: *bool) bool {
if (!build_options.has_imgui) {
return false;
}
const self = &g_state;
if (!self.enabled) {
return false;
}
return ig.igCheckbox(
formatString("{s}", .{label}),
@ -243,6 +283,10 @@ pub fn separator() void {
if (!build_options.has_imgui) {
return;
}
const self = &g_state;
if (!self.enabled) {
return;
}
ig.igSeparator();
}
@ -257,6 +301,10 @@ pub fn colorEdit(opts: ColorEditOptions) bool {
if (!build_options.has_imgui) {
return false;
}
const self = &g_state;
if (!self.enabled) {
return false;
}
const label = formatString("{s}", .{opts.label});
var color: [4]f32 = .{

View File

@ -12,10 +12,11 @@ const sg = sokol.gfx;
const sglue = sokol.glue;
const sgl = sokol.gl;
const Math = @import("math");
const Vec2 = Math.Vec2;
const Vec4 = Math.Vec4;
const Mat4 = Math.Mat4;
pub const Math = @import("math");
pub const Vec2 = Math.Vec2;
pub const Vec4 = Math.Vec4;
pub const Mat4 = Math.Mat4;
pub const Rect = Math.Rect;
const tracy = @import("tracy");
@ -24,7 +25,9 @@ const shd = @import("shader");
pub const ImGUI = @import("./imgui.zig");
pub const Gfx = @import("./graphics.zig");
const Input = @import("./input.zig");
pub const Input = @import("./input.zig");
const EmbeddedAssets = @import("embedded_assets");
fn PlatformType(App: type) type {
return struct {
@ -39,6 +42,7 @@ fn PlatformType(App: type) type {
started_at: Io.Timestamp,
last_frame_at: Io.Timestamp,
assets: Assets,
input: Input,
events_buffer: [256]Input.Event,
events_overflow: bool,
@ -57,7 +61,7 @@ fn PlatformType(App: type) type {
self.last_frame_at = self.started_at;
self.input = Input.init(window_size);
Gfx.init(.{
try Gfx.init(self.gpa, .{
.func = sokolLogCallback
});
ImGUI.init(.{
@ -67,7 +71,8 @@ fn PlatformType(App: type) type {
if (@hasDecl(App, "init")) {
const plt = Init{
.gpa = self.gpa,
.io = self.io
.io = self.io,
.assets = &self.assets
};
if (try self.app.init(plt)) |exit_code| {
std.process.exit(exit_code);
@ -103,9 +108,7 @@ fn PlatformType(App: type) type {
{
Gfx.beginFrame();
if (self.show_imgui) {
ImGUI.beginFrame(self.frame_arena.allocator());
}
ImGUI.beginFrame(self.show_imgui, self.frame_arena.allocator());
if (@hasDecl(App, "frame")) {
const plt = Frame{
@ -115,15 +118,16 @@ fn PlatformType(App: type) type {
.io = self.io,
.input = &self.input,
.input_events = self.events.items,
.frame = self.frame_arena.allocator()
.frame = self.frame_arena.allocator(),
.assets = &self.assets
};
try self.app.frame(plt);
}
Gfx.flush();
if (self.show_imgui) {
ImGUI.endFrame();
}
Gfx.flush(.{});
Gfx.showDebug();
ImGUI.endFrame();
Gfx.endFrame();
}
@ -284,18 +288,38 @@ fn PlatformType(App: type) type {
}
}
const input = &self.input;
switch (e.type) {
.MOUSE_DOWN => {
if (input.mouse_position == null) {
self.pushEvent(.{
.mouse_enter = .init(e.mouse_x, e.mouse_y)
});
}
self.pushEvent(.{
.mouse_pressed = Input.MouseButton.fromSokol(e.mouse_button) orelse return false,
});
},
.MOUSE_UP => {
if (input.mouse_position == null) {
self.pushEvent(.{
.mouse_enter = .init(e.mouse_x, e.mouse_y)
});
}
self.pushEvent(.{
.mouse_released = Input.MouseButton.fromSokol(e.mouse_button) orelse return false,
});
},
.MOUSE_MOVE => {
if (input.mouse_position == null) {
self.pushEvent(.{
.mouse_enter = .init(e.mouse_x, e.mouse_y)
});
}
self.pushEvent(.{
.mouse_move = .init(e.mouse_x, e.mouse_y)
});
@ -378,6 +402,7 @@ fn PlatformType(App: type) type {
self.app.deinit(plt);
}
self.frame_arena.deinit();
self.assets.deinit();
ImGUI.deinit();
Gfx.deinit();
@ -393,9 +418,84 @@ pub const RunOptions = struct {
height: i32 = 600,
};
pub const Assets = struct {
arena: std.heap.ArenaAllocator,
gpa: Allocator,
io: Io,
dir: ?Io.Dir,
files: std.array_hash_map.String(File),
fn init(gpa: Allocator, io: Io, dir: ?Io.Dir) Assets {
return Assets{
.gpa = gpa,
.io = io,
.arena = .init(gpa),
.dir = dir,
.files = .empty
};
}
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.readFileAllocOptions(
self.io,
filename,
arena,
.unlimited,
.of(u8),
0
);
const filename_owned = try arena.dupe(u8, filename);
try self.files.put(self.gpa, filename_owned, File{
.contents = contents
});
return contents;
}
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 which isn't defined in assets: '{s}'", .{filename});
return contents;
} else {
log.err("Attempt to read file '{s}', which doesn't exist", .{filename});
return "";
}
} else |err| {
log.err("Failed to read file from filesystem: {}", .{err});
return "";
}
}
}
fn insertStaticFile(self: *Assets, filename: []const u8, contents: [:0]const u8) !void {
try self.files.put(self.gpa, filename, File{
.contents = contents
});
}
fn deinit(self: *Assets) void {
self.arena.deinit();
self.files.deinit(self.gpa);
}
const File = struct {
contents: [:0]const u8
};
};
pub const Init = struct {
gpa: Allocator,
io: Io,
assets: *Assets
};
pub const Deinit = struct {
@ -410,6 +510,7 @@ pub const Frame = struct {
frame: Allocator,
gpa: Allocator,
io: Io,
assets: *Assets,
input: *Input,
input_events: []Input.Event,
@ -429,12 +530,22 @@ pub const Frame = struct {
pub fn run(App: type, opts: RunOptions) void {
const arena = opts.init.arena.allocator();
const gpa = opts.init.gpa;
const io = opts.init.io;
var assets_dir: ?Io.Dir = null;
if (build_options.assets_dir) |assets_dir_path| {
const cwd = Io.Dir.cwd();
assets_dir = cwd.openDir(io, assets_dir_path, .{}) catch |e| blk: {
log.err("Failed to open assets directory: {}", .{e});
break :blk null;
};
}
const PlatformApp = PlatformType(App);
const plt = arena.create(PlatformApp) catch @panic("OOM");
plt.* = PlatformApp{
.gpa = gpa,
.io = opts.init.io,
.io = io,
.cli_args = opts.init.minimal.args.toSlice(arena) catch @panic("OOM"),
.app = undefined,
.input = undefined,
@ -446,9 +557,14 @@ pub fn run(App: type, opts: RunOptions) void {
.last_key_press_is_repeat = false,
.last_key_pressed = null,
.frame_arena = .init(gpa),
.show_imgui = builtin.mode == .Debug
.show_imgui = builtin.mode == .Debug,
.assets = .init(gpa, io, assets_dir)
};
inline for (EmbeddedAssets.files) |file| {
plt.assets.insertStaticFile(file.name, file.contents) catch @panic("OOM");
}
var icon: sapp.IconDesc = .{};
icon.sokol_default = true;
// TODO: Don't hard code icon path, allow changing through options

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

@ -13,7 +13,7 @@ const Allocator = std.mem.Allocator;
///
/// For more details about this data structure checkout this podcast episode from Wookash:
/// * https://www.youtube.com/watch?v=ShSGHb65f3M
pub fn SlotMapType(Index: type, Generation: type) type {
pub fn SlotMapType(Index: type, Generation: type, Value: type) type {
assert(@typeInfo(Generation) == .int);
assert(@typeInfo(Index) == .int);
@ -28,6 +28,7 @@ pub fn SlotMapType(Index: type, Generation: type) type {
//
// So in the end idk if it's worth it.
pub const Slot = struct {
value: Value,
generation: Generation,
next_hole: ?Index,
used: bool
@ -50,7 +51,7 @@ pub fn SlotMapType(Index: type, Generation: type) type {
index: Index,
pub fn format(self: Id, writer: *std.Io.Writer) std.Io.Writer.Error!void {
try writer.print("Id{{ {}, {} }}", .{ self.index, self.generation });
try writer.print("Id({s}){{ {}, {} }}", .{ @typeName(Value), self.index, self.generation });
}
};
@ -77,7 +78,7 @@ pub fn SlotMapType(Index: type, Generation: type) type {
};
pub fn clearRetainingCapacity(self: *Self) void {
const slots = self.slots;
var slots = self.slots;
slots.clearRetainingCapacity();
self.* = .init(slots);
@ -109,6 +110,7 @@ pub fn SlotMapType(Index: type, Generation: type) type {
const index: Index = @intCast(self.slots.items.len);
self.slots.items.len += 1;
self.slots.items[index] = Slot{
.value = undefined,
.generation = 0,
.next_hole = null,
.used = false
@ -171,6 +173,18 @@ pub fn SlotMapType(Index: type, Generation: type) type {
return slot.used and slot.generation == id.generation;
}
pub fn get(self: *Self, id: Id) ?*Value {
if (self.exists(id)) {
return &self.slots.items[id.index].value;
}
return null;
}
pub fn getAssumeExists(self: *Self, id: Id) *Value {
assert(self.exists(id));
return self.get(id).?;
}
pub fn removeAssumeExists(self: *Self, id: Id) void {
assert(self.exists(id));
@ -209,7 +223,7 @@ pub fn SlotMapType(Index: type, Generation: type) type {
};
}
const TestMap = SlotMapType(u24, u8);
const TestMap = SlotMapType(u24, u8, void);
// TODO: Add more rigorous test for check if generation usage is nicely distributed.