Skip to content

Commit

Permalink
feat: (WIP) serialization
Browse files Browse the repository at this point in the history
  • Loading branch information
kiedtl committed Oct 8, 2023
1 parent 691f021 commit ceaea86
Show file tree
Hide file tree
Showing 12 changed files with 238 additions and 146 deletions.
31 changes: 14 additions & 17 deletions src/alert.zig
Original file line number Diff line number Diff line change
Expand Up @@ -102,21 +102,18 @@ pub const ThreatResponse = struct {
pub const AList = std.ArrayList(@This());
};

pub var threats: std.AutoHashMap(Threat, ThreatData) = undefined;
pub var responses: ThreatResponse.AList = undefined;

pub fn init() void {
threats = @TypeOf(threats).init(state.GPA.allocator());
responses = @TypeOf(responses).init(state.GPA.allocator());
state.threats = @TypeOf(state.threats).init(state.GPA.allocator());
state.responses = @TypeOf(state.responses).init(state.GPA.allocator());
}

pub fn deinit() void {
threats.clearAndFree();
responses.deinit();
state.threats.clearAndFree();
state.responses.deinit();
}

pub fn getThreat(threat: Threat) *ThreatData {
return (threats.getOrPutValue(threat, .{}) catch err.wat()).value_ptr;
return (state.threats.getOrPutValue(threat, .{}) catch err.wat()).value_ptr;
}

pub fn reportThreat(by: ?*Mob, threat: Threat, threattype: ThreatIncrease) void {
Expand All @@ -142,7 +139,7 @@ pub fn reportThreat(by: ?*Mob, threat: Threat, threattype: ThreatIncrease) void
getThreat(.Unknown).is_active = true;
}

// Don't report threats if the guy is dead
// Don't report state.threats if the guy is dead
if (threat == .Specific and
threat.Specific.is_dead and threat.Specific.corpse_info.is_noticed)
{
Expand Down Expand Up @@ -174,24 +171,24 @@ pub fn dismissThreat(by: ?*Mob, threat: Threat) void {
// Also there would need to be checks in place for when threats are
// dismissed redundantly
//
//threats.put(threat, getThreat(.General).level - getThreat(threat).level);
//state.threats.put(threat, getThreat(.General).level - getThreat(threat).level);

assert(threat != .General);
assert(by == null or by.?.faction == .Necromancer);

_ = by;
_ = threats.remove(threat);
_ = state.threats.remove(threat);
}

pub fn queueThreatResponse(response: ThreatResponseType) void {
responses.append(.{ .type = response }) catch err.wat();
state.responses.append(.{ .type = response }) catch err.wat();
}

pub fn tickThreats(level: usize) void {
// Unsure if modifying container while iterator() is active is safe to do
var dismiss_threats = StackBuffer(Threat, 64).init(null);

var iter = threats.iterator();
var iter = state.threats.iterator();
while (iter.next()) |entry| {
if (entry.key_ptr.* == .General)
continue;
Expand Down Expand Up @@ -225,8 +222,8 @@ pub fn tickThreats(level: usize) void {
for (dismiss_threats.constSlice()) |threat|
dismissThreat(null, threat);

if (responses.items.len > 0) {
const response = responses.pop();
if (state.responses.items.len > 0) {
const response = state.responses.pop();
switch (response.type) {
.ReinforceAgainstEnemy => |r| {
const mob_template = switch (r.reinforcement) {
Expand Down Expand Up @@ -259,7 +256,7 @@ pub fn tickThreats(level: usize) void {
} else |_| {
// No space near stairs. Add the response back, wait until next
// time, hopefully the traffic dissipates.
responses.append(response) catch err.wat();
state.responses.append(response) catch err.wat();
}
},
.ReinforceRoom => |r| {
Expand Down Expand Up @@ -292,7 +289,7 @@ pub fn tickThreats(level: usize) void {
if (mobs.placeMobNearStairs(mob_template, level, opts)) |_| {} else |_| {
// No space near stairs. Add the response back, wait until next
// time, hopefully the traffic dissipates.
responses.append(response) catch err.wat();
state.responses.append(response) catch err.wat();
}
}
},
Expand Down
5 changes: 5 additions & 0 deletions src/buffer.zig
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@ const mem = std.mem;
const assert = std.debug.assert;

const rng = @import("rng.zig");
const serializer = @import("serializer.zig");

pub const StringBuf64 = StackBuffer(u8, 64);

Expand Down Expand Up @@ -137,6 +138,10 @@ pub fn StackBuffer(comptime T: type, comptime capacity: usize) type {
pub fn jsonStringify(val: @This(), opts: std.json.StringifyOptions, stream: anytype) !void {
try std.json.stringify(val.constSlice(), opts, stream);
}

pub fn serialize(val: @This(), out: anytype) !void {
try serializer.serialize([]const T, val.constSlice(), out);
}
};
}

Expand Down
2 changes: 1 addition & 1 deletion src/combat.zig
Original file line number Diff line number Diff line change
Expand Up @@ -371,7 +371,7 @@ pub fn disruptIndividualUndead(mob: *Mob) void {
}

test {
rng.seed = 2384928349;
state.seed = 2384928349;
rng.init();

var i: usize = 10;
Expand Down
5 changes: 2 additions & 3 deletions src/err.zig
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,6 @@ const std = @import("std");

const ui = @import("ui.zig");
const state = @import("state.zig");
const rng = @import("rng.zig");
const sentry = @import("sentry.zig");

pub fn ensure(expr: bool, comptime err_message: []const u8, args: anytype) !void {
Expand All @@ -20,7 +19,7 @@ pub fn bug(comptime fmt: []const u8, args: anytype) noreturn {
@setCold(true);

ui.deinit() catch {};
std.log.err("Fatal bug encountered. (Seed: {})", .{rng.seed});
std.log.err("Fatal bug encountered. (Seed: {})", .{state.seed});
std.log.err("BUG: " ++ fmt, args);

if (!state.sentry_disabled) {
Expand All @@ -35,7 +34,7 @@ pub fn bug(comptime fmt: []const u8, args: anytype) noreturn {
std.fmt.allocPrint(alloc, fmt, args) catch unreachable,
&[_]sentry.SentryEvent.TagSet.Tag{.{
.name = "seed",
.value = std.fmt.allocPrint(alloc, "{}", .{rng.seed}) catch unreachable,
.value = std.fmt.allocPrint(alloc, "{}", .{state.seed}) catch unreachable,
}},
@errorReturnTrace(),
@returnAddress(),
Expand Down
20 changes: 8 additions & 12 deletions src/events.zig
Original file line number Diff line number Diff line change
Expand Up @@ -81,23 +81,19 @@ pub const EVENTS = [_]struct { p: usize, v: *const Event }{
.{ .p = 75, .v = &EV_SHIELD_DISALLOW },
};

pub var completed_events: Event.AList = undefined;

pub fn init() void {
completed_events = @TypeOf(completed_events).init(state.GPA.allocator());
// Nothing
}

pub fn deinit() void {
completed_events.deinit();
// Nothing
}

pub fn eventUsedCount(id: []const u8) usize {
var i: usize = 0;
for (completed_events.items) |completed| {
if (mem.eql(u8, id, completed.id))
i += 1;
}
return i;
const ind = for (EVENTS) |ev, i| {
if (mem.eql(u8, ev.v.id, id)) break i;
} else err.wat();
return state.completed_events[ind];
}

pub fn eventCanBeUsed(event: *const Event) bool {
Expand All @@ -115,12 +111,12 @@ pub fn eventCanBeUsed(event: *const Event) bool {
// XXX: Need to add checks for restrictions etc when that's added
//
pub fn executeGlobalEvents() void {
for (&EVENTS) |event| {
for (&EVENTS) |event, i| {
if (rng.percent(event.p) and eventCanBeUsed(event.v)) {
var new_event = event.v.*;
for (new_event.effect) |effect|
effect.apply() catch unreachable;
completed_events.append(new_event) catch err.wat();
state.completed_events[i] += 1;
}
}
}
11 changes: 11 additions & 0 deletions src/list.zig
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,8 @@ const mem = std.mem;
const assert = std.debug.assert;
const testing = std.testing;

const serializer = @import("serializer.zig");

// Basic node that can be used for scalar data.
pub fn ScalarNode(comptime T: type) type {
return struct {
Expand Down Expand Up @@ -138,6 +140,15 @@ pub fn LinkedList(comptime T: type) type {
pub fn iteratorReverse(self: *const Self) Iterator {
return Iterator{ .current = self.tail, .reverse = true };
}

pub fn serialize(val: @This(), out: anytype) !void {
var iter = val.iterator();
var i: usize = 0;
while (iter.next()) |_| i += 1;
try serializer.serialize(usize, i, out);
iter = val.iterator();
while (iter.next()) |item| try serializer.serialize(T, item, out);
}
};
}

Expand Down
51 changes: 28 additions & 23 deletions src/main.zig
Original file line number Diff line number Diff line change
Expand Up @@ -13,29 +13,30 @@ const StackBuffer = @import("buffer.zig").StackBuffer;

const ai = @import("ai.zig");
const alert = @import("alert.zig");
const rng = @import("rng.zig");
const janet = @import("janet.zig");
const player = @import("player.zig");
const font = @import("font.zig");
const display = @import("display.zig");
const err = @import("err.zig");
const events = @import("events.zig");
const literature = @import("literature.zig");
const explosions = @import("explosions.zig");
const tasks = @import("tasks.zig");
const fire = @import("fire.zig");
const items = @import("items.zig");
const utils = @import("utils.zig");
const font = @import("font.zig");
const gas = @import("gas.zig");
const items = @import("items.zig");
const janet = @import("janet.zig");
const literature = @import("literature.zig");
const mapgen = @import("mapgen.zig");
const mobs = @import("mobs.zig");
const player = @import("player.zig");
const rng = @import("rng.zig");
const scores = @import("scores.zig");
const sentry = @import("sentry.zig");
const serializer = @import("serializer.zig");
const state = @import("state.zig");
const surfaces = @import("surfaces.zig");
const ui = @import("ui.zig");
const tasks = @import("tasks.zig");
const termbox = @import("termbox.zig");
const display = @import("display.zig");
const types = @import("types.zig");
const sentry = @import("sentry.zig");
const state = @import("state.zig");
const err = @import("err.zig");
const scores = @import("scores.zig");
const ui = @import("ui.zig");
const utils = @import("utils.zig");

const Direction = types.Direction;
const Coord = types.Coord;
Expand Down Expand Up @@ -84,7 +85,7 @@ pub fn panic(msg: []const u8, trace: ?*std.builtin.StackTrace) noreturn {
0 => {
__panic_stage = 1;
ui.deinit() catch {};
std.log.err("Fatal error encountered. (Seed: {})", .{rng.seed});
std.log.err("Fatal error encountered. (Seed: {})", .{state.seed});

if (!state.sentry_disabled) {
var membuf: [65535]u8 = undefined;
Expand All @@ -98,7 +99,7 @@ pub fn panic(msg: []const u8, trace: ?*std.builtin.StackTrace) noreturn {
msg,
&[_]sentry.SentryEvent.TagSet.Tag{.{
.name = "seed",
.value = std.fmt.allocPrint(alloc, "{}", .{rng.seed}) catch unreachable,
.value = std.fmt.allocPrint(alloc, "{}", .{state.seed}) catch unreachable,
}},
trace,
@returnAddress(),
Expand Down Expand Up @@ -160,7 +161,7 @@ fn initGameState() void {
state.dungeon.* = types.Dungeon{};

rng.init();
for (mapgen.floor_seeds) |*seed|
for (state.floor_seeds) |*seed|
seed.* = rng.int(u64);

for (state.default_patterns) |*r| r.pattern_checker.reset();
Expand Down Expand Up @@ -493,6 +494,10 @@ fn readInput() !bool {
// ui.hud_win.deinit();
// ui.hud_win.init();
// ui.map_win.drawTextLinef("This is a test.", .{}, .{});
var buf = std.ArrayList(u8).init(state.GPA.allocator());
defer buf.deinit();
serializer.serialize(Mob, state.player.*, buf.writer()) catch err.wat();
std.fs.cwd().writeFile("dump.dat", buf.items) catch err.wat();
},
.F8 => {
_ = janet.loadFile("scripts/particles.janet", state.GPA.allocator()) catch continue;
Expand Down Expand Up @@ -1158,7 +1163,7 @@ fn testerMain() void {
fn profilerMain() void {
// const LEVEL = 0;

std.log.info("[ Seed: {} ]", .{rng.seed});
std.log.info("[ Seed: {} ]", .{state.seed});

state.sentry_disabled = true;
assert(initGame(true, 0));
Expand Down Expand Up @@ -1230,8 +1235,8 @@ fn analyzerMain() void {

var i: usize = 0;
while (i < ITERS) : (i += 1) {
rng.seed = @intCast(u64, std.time.milliTimestamp());
std.log.info("*** \x1b[94;1m ITERATION \x1b[m {} (seed: {})", .{ i, rng.seed });
state.seed = @intCast(u64, std.time.milliTimestamp());
std.log.info("*** \x1b[94;1m ITERATION \x1b[m {} (seed: {})", .{ i, state.seed });
initGameState();

const S = state.PLAYER_STARTING_LEVEL;
Expand Down Expand Up @@ -1266,12 +1271,12 @@ pub fn actualMain() anyerror!void {

if (std.process.getEnvVarOwned(state.GPA.allocator(), "RL_SEED")) |seed_str| {
defer state.GPA.allocator().free(seed_str);
rng.seed = std.fmt.parseInt(u64, seed_str, 0) catch |e| b: {
state.seed = std.fmt.parseInt(u64, seed_str, 0) catch |e| b: {
std.log.err("Could not parse RL_SEED (reason: {}); using default.", .{e});
break :b 0;
};
} else |_| {
rng.seed = @intCast(u64, std.time.milliTimestamp());
state.seed = @intCast(u64, std.time.milliTimestamp());
}

if (std.process.getEnvVarOwned(state.GPA.allocator(), "RL_MODE")) |v| {
Expand Down Expand Up @@ -1388,7 +1393,7 @@ pub fn main() void {
"propagated error trace",
&[_]sentry.SentryEvent.TagSet.Tag{.{
.name = "seed",
.value = std.fmt.allocPrint(alloc, "{}", .{rng.seed}) catch unreachable,
.value = std.fmt.allocPrint(alloc, "{}", .{state.seed}) catch unreachable,
}},
error_trace,
null,
Expand Down
7 changes: 3 additions & 4 deletions src/mapgen.zig
Original file line number Diff line number Diff line change
Expand Up @@ -146,7 +146,6 @@ const Range = struct { from: Coord, to: Coord };
pub var s_fabs: PrefabArrayList = undefined;
pub var n_fabs: PrefabArrayList = undefined;
pub var fab_records: std.StringHashMap(Prefab.PlacementRecord) = undefined;
pub var floor_seeds: [LEVELS]u64 = undefined;

const gif = @import("build_options").tunneler_gif;
const giflib = if (gif) @cImport(@cInclude("gif_lib.h")) else null;
Expand Down Expand Up @@ -3399,7 +3398,7 @@ pub fn initLevelTest(prefab: []const u8, entry: bool) !void {
}

pub fn initLevel(level: usize) void {
rng.useTemp(floor_seeds[level]);
rng.useTemp(state.floor_seeds[level]);

var tries: usize = 0;
while (true) {
Expand Down Expand Up @@ -3481,8 +3480,8 @@ pub const LevelAnalysis = struct {
.prefabs = std.ArrayList(Pair).init(alloc),
.items = std.ArrayList(Pair2).init(alloc),
.mobs = std.ArrayList(Pair).init(alloc),
.seed = rng.seed,
.floor_seed = floor_seeds[z],
.seed = state.seed,
.floor_seed = state.floor_seeds[z],
};
}

Expand Down
7 changes: 4 additions & 3 deletions src/rng.zig
Original file line number Diff line number Diff line change
Expand Up @@ -9,11 +9,12 @@ const math = std.math;
var rng: rand.Isaac64 = undefined;
var rng2: rand.Isaac64 = undefined;
pub var using_temp = false;
pub var seed: u64 = undefined;
pub const seed = &@import("state.zig").seed;

//seed = 0xdefaced_cafe;

pub fn init() void {
rng = rand.Isaac64.init(seed);
rng = rand.Isaac64.init(seed.*);
}

pub fn useTemp(tseed: u64) void {
Expand Down Expand Up @@ -134,7 +135,7 @@ pub fn choose2(comptime T: type, arr: []const T, comptime weight_field: []const
test "range" {
const testing = std.testing;

seed = 2384928349;
seed.* = 2384928349;
init();

var i: usize = 0;
Expand Down
Loading

0 comments on commit ceaea86

Please sign in to comment.