From 005971a8e386a2403d735df8c4f1d9a5167c621f Mon Sep 17 00:00:00 2001 From: Peter Li Date: Tue, 29 Sep 2026 02:42:04 -0700 Subject: [PATCH] added p2 support package --- README.md | 1 + engine/build.zig | 22 + engine/p2/.gitignore | 2 + engine/p2/LICENSE | 21 + engine/p2/Readme.md | 3 + engine/p2/build.zig | 47 + engine/p2/build.zig.zon | 11 + engine/p2/debugging/lldb_std_formatters.py | 1279 +++++ engine/p2/src/algorithm/pointer-hash.zig | 1 + engine/p2/src/p2.zig | 433 ++ .../p2/src/queue-benchmark-cas-baseline.zig | 117 + engine/p2/src/queue-benchmark.zig | 203 + engine/p2/src/structures/bump-arena.zig | 161 + engine/p2/src/structures/concurrent-queue.zig | 280 ++ .../p2/src/structures/counting-allocator.zig | 71 + engine/p2/src/structures/index-pool.zig | 431 ++ engine/p2/src/structures/int-mapper.zig | 14 + engine/p2/src/structures/interface.zig | 136 + engine/p2/src/structures/math.zig | 688 +++ engine/p2/src/structures/names.zig | 306 ++ engine/p2/src/structures/paged-vector.zig | 323 ++ engine/p2/src/structures/perf-tests.zig | 190 + engine/p2/src/structures/pscopes.zig | 165 + engine/p2/src/structures/ref-pool.zig | 658 +++ engine/p2/src/structures/ref-string-map.zig | 170 + engine/p2/src/structures/ring-queue.zig | 259 + engine/p2/src/structures/samplegun.json | 33 + engine/p2/src/structures/spans.zig | 293 ++ engine/p2/src/structures/sparse-set.zig | 885 ++++ .../src/structures/spmc-submission-queue.zig | 681 +++ .../p2/src/structures/static-structures.zig | 70 + engine/p2/src/structures/stats.zig | 6 + engine/p2/src/structures/string-pool.zig | 832 ++++ .../p2/src/structures/structured-logging.zig | 164 + engine/p2/src/structures/utils.zig | 226 + engine/p2/src/structures/zmath.zig | 4182 +++++++++++++++++ engine/p2/src/utils/shell.zig | 117 + engine/p2/src/utils/xxd.zig | 102 + engine/p2/tools/vscode-env/README.md | 59 + .../p2/tools/vscode-env/extensions/.gitkeep | 1 + engine/p2/tools/vscode-env/install.bat | 137 + engine/p2/tools/vscode-env/install.sh | 145 + .../tools/vscode-env/settings/settings.json | 7 + engine/src/core/core.zig | 2 +- engine/tools/interface-parser.zig | 8 + 45 files changed, 13941 insertions(+), 1 deletion(-) create mode 100644 README.md create mode 100644 engine/p2/.gitignore create mode 100644 engine/p2/LICENSE create mode 100644 engine/p2/Readme.md create mode 100644 engine/p2/build.zig create mode 100644 engine/p2/build.zig.zon create mode 100644 engine/p2/debugging/lldb_std_formatters.py create mode 100644 engine/p2/src/algorithm/pointer-hash.zig create mode 100644 engine/p2/src/p2.zig create mode 100644 engine/p2/src/queue-benchmark-cas-baseline.zig create mode 100644 engine/p2/src/queue-benchmark.zig create mode 100644 engine/p2/src/structures/bump-arena.zig create mode 100644 engine/p2/src/structures/concurrent-queue.zig create mode 100644 engine/p2/src/structures/counting-allocator.zig create mode 100644 engine/p2/src/structures/index-pool.zig create mode 100644 engine/p2/src/structures/int-mapper.zig create mode 100644 engine/p2/src/structures/interface.zig create mode 100644 engine/p2/src/structures/math.zig create mode 100644 engine/p2/src/structures/names.zig create mode 100644 engine/p2/src/structures/paged-vector.zig create mode 100644 engine/p2/src/structures/perf-tests.zig create mode 100644 engine/p2/src/structures/pscopes.zig create mode 100644 engine/p2/src/structures/ref-pool.zig create mode 100644 engine/p2/src/structures/ref-string-map.zig create mode 100644 engine/p2/src/structures/ring-queue.zig create mode 100644 engine/p2/src/structures/samplegun.json create mode 100644 engine/p2/src/structures/spans.zig create mode 100644 engine/p2/src/structures/sparse-set.zig create mode 100644 engine/p2/src/structures/spmc-submission-queue.zig create mode 100644 engine/p2/src/structures/static-structures.zig create mode 100644 engine/p2/src/structures/stats.zig create mode 100644 engine/p2/src/structures/string-pool.zig create mode 100644 engine/p2/src/structures/structured-logging.zig create mode 100644 engine/p2/src/structures/utils.zig create mode 100644 engine/p2/src/structures/zmath.zig create mode 100644 engine/p2/src/utils/shell.zig create mode 100644 engine/p2/src/utils/xxd.zig create mode 100644 engine/p2/tools/vscode-env/README.md create mode 100644 engine/p2/tools/vscode-env/extensions/.gitkeep create mode 100644 engine/p2/tools/vscode-env/install.bat create mode 100755 engine/p2/tools/vscode-env/install.sh create mode 100644 engine/p2/tools/vscode-env/settings/settings.json diff --git a/README.md b/README.md new file mode 100644 index 0000000..1b2d454 --- /dev/null +++ b/README.md @@ -0,0 +1 @@ +# Ribtech diff --git a/engine/build.zig b/engine/build.zig index e69de29..21fc4d4 100644 --- a/engine/build.zig +++ b/engine/build.zig @@ -0,0 +1,22 @@ +const std = @import("std"); + +pub fn build(b: *std.Build) void { + const optimize = b.standardOptimizeOption(.{}); + const target = b.standardTargetOptions(.{}); + + const parser = b.addExecutable(.{ + .root_module = b.createModule(.{ + .optimize = optimize, + .target = target, + .root_source_file = b.path("tools/interface-parser.zig"), + }), + .name = "parser", + }); + + const parse_interface_core = b.addRunArtifact(parser); + parse_interface_core.addArgs(&.{ "--input", b.path("src/core/core.zig").getPath(b) }); + + const generate_headers_step = b.step("generate-interface", "generates interface information from all core apis"); + + generate_headers_step.dependOn(&parse_interface_core.step); +} diff --git a/engine/p2/.gitignore b/engine/p2/.gitignore new file mode 100644 index 0000000..4a0641e --- /dev/null +++ b/engine/p2/.gitignore @@ -0,0 +1,2 @@ +zig-cache/ +zig-out/ \ No newline at end of file diff --git a/engine/p2/LICENSE b/engine/p2/LICENSE new file mode 100644 index 0000000..0b12b03 --- /dev/null +++ b/engine/p2/LICENSE @@ -0,0 +1,21 @@ +MIT License + +Copyright (c) 2022 Peter Li + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. diff --git a/engine/p2/Readme.md b/engine/p2/Readme.md new file mode 100644 index 0000000..b852ba8 --- /dev/null +++ b/engine/p2/Readme.md @@ -0,0 +1,3 @@ +# P2 - Peterino's stdlib + +Contains a bunch of stuff i think is missing from the zig stdlib that is needed for gamedev diff --git a/engine/p2/build.zig b/engine/p2/build.zig new file mode 100644 index 0000000..69a6dab --- /dev/null +++ b/engine/p2/build.zig @@ -0,0 +1,47 @@ +const std = @import("std"); +const bh = @import("bh"); + +pub fn build(b: *std.Build) void { + const opts = bh.declareOptions(b); + + const mod = b.addModule("p2", .{ + .target = opts.target, + .optimize = opts.optimize, + .root_source_file = b.path("src/p2.zig"), + }); + + const filter_option = b.option([]const []const u8, "test-filter", "Skip test that do not match this filter"); + const test_filters = filter_option orelse &.{}; + const test_step = b.step("test", "test p2"); + const tests = b.addTest(.{ + .root_module = b.createModule(.{ + .target = opts.target, + .optimize = opts.optimize, + .root_source_file = b.path("src/p2.zig"), + }), + .use_llvm = b.option(bool, "llvm", "compiles the tests with llvm "), + .filters = test_filters, + }); + + tests.root_module.addImport("p2", mod); + const installArtifact = b.addInstallArtifact(tests, .{}); + const runArtifact = b.addRunArtifact(tests); + test_step.dependOn(&installArtifact.step); + test_step.dependOn(&runArtifact.step); + if (b.args) |args| { + runArtifact.addArgs(args); + } + b.installArtifact(tests); + + const benchmark = b.addExecutable(.{ + .name = "queue-benchmark", + .root_module = b.createModule(.{ + .target = opts.target, + .optimize = opts.optimize, + .root_source_file = b.path("src/queue-benchmark.zig"), + }), + }); + const runBenchmark = b.addRunArtifact(benchmark); + if (b.args) |args| runBenchmark.addArgs(args); + b.step("bench-queues", "Compare one-producer/many-consumer queue throughput").dependOn(&runBenchmark.step); +} diff --git a/engine/p2/build.zig.zon b/engine/p2/build.zig.zon new file mode 100644 index 0000000..0b25598 --- /dev/null +++ b/engine/p2/build.zig.zon @@ -0,0 +1,11 @@ +.{ + .name = .p2, + .version = "0.0.0", + .dependencies = .{ + .bh = .{ .path = "../bh" }, + }, + .paths = .{ + "", + }, + .fingerprint = 0xa6313a892725ee21, +} diff --git a/engine/p2/debugging/lldb_std_formatters.py b/engine/p2/debugging/lldb_std_formatters.py new file mode 100644 index 0000000..a9ef293 --- /dev/null +++ b/engine/p2/debugging/lldb_std_formatters.py @@ -0,0 +1,1279 @@ +"""LLDB formatters for common Zig standard library data structures. + +Import from LLDB with: + + command script import /path/to/debugging/lldb_std_formatters.py + +The formatters are deliberately field-shape based. Zig's stdlib types are +heavily comptime-generated, so exact type names vary by compiler version, +element type, and package path. These helpers prefer safe summaries and +expandable children over evaluating Zig code inside the debuggee. +""" + +from __future__ import annotations + +import lldb +import re +import struct + + +MAX_STRING_BYTES = 4096 +MAX_CREATE_CHILD_OFFSET = 0xFFFFFFFF +MAX_TRUSTED_SYNTHETIC_CHILDREN = 100000 + + +def __lldb_init_module(debugger: lldb.SBDebugger, _dict) -> None: + debugger.HandleCommand( + "type summary add -x '^\\[\\].*' " + "-F lldb_std_formatters.slice_summary" + ) + debugger.HandleCommand( + "type synthetic add -x '^\\[\\].*' " + "-l lldb_std_formatters.SliceSyntheticProvider" + ) + + debugger.HandleCommand( + "type summary add -x '^\\[\\*\\].*' " + "-F lldb_std_formatters.many_pointer_summary" + ) + + debugger.HandleCommand( + "type summary add -x '(^|.*\\.)ArrayList(Unmanaged)?(Aligned)?(\\(|$|<)' " + "-F lldb_std_formatters.array_list_summary" + ) + debugger.HandleCommand( + "type synthetic add -x '(^|.*\\.)ArrayList(Unmanaged)?(Aligned)?(\\(|$|<)' " + "-l lldb_std_formatters.ArrayListSyntheticProvider" + ) + + debugger.HandleCommand( + "type summary add -x '(^|.*\\.)(StringHashMap|StringArrayHashMap|" + "AutoHashMap|AutoArrayHashMap|HashMap|ArrayHashMap)(Unmanaged)?(\\(|$|<)' " + "-F lldb_std_formatters.hash_map_summary" + ) + debugger.HandleCommand( + "type synthetic add -x '(^|.*\\.)(StringHashMap|StringArrayHashMap|" + "AutoHashMap|AutoArrayHashMap|HashMap|ArrayHashMap)(Unmanaged)?(\\(|$|<)' " + "-l lldb_std_formatters.HashMapSyntheticProvider" + ) + + debugger.HandleCommand( + "type summary add -x '(^|.*\\.)(StringHashMap|StringArrayHashMap)" + "(Unmanaged)?(\\(|$|<)' " + "-F lldb_std_formatters.string_hash_map_summary" + ) + + debugger.HandleCommand( + "type summary add -x '^structures\\.document\\.Record$' " + "-F lldb_std_formatters.record_summary" + ) + debugger.HandleCommand( + "type synthetic add -x '^structures\\.document\\.Record$' " + "-l lldb_std_formatters.RecordSyntheticProvider" + ) + + debugger.HandleCommand( + "type summary add -x '^structures\\.document\\.List$' " + "-F lldb_std_formatters.record_list_summary" + ) + debugger.HandleCommand( + "type synthetic add -x '^structures\\.document\\.List$' " + "-l lldb_std_formatters.RecordListSyntheticProvider" + ) + + debugger.HandleCommand( + "type summary add -x '^structures\\.document\\.Dict$' " + "-F lldb_std_formatters.record_dict_summary" + ) + debugger.HandleCommand( + "type synthetic add -x '^structures\\.document\\.Dict$' " + "-l lldb_std_formatters.RecordDictSyntheticProvider" + ) + + +def slice_summary(valobj: lldb.SBValue, _dict) -> str: + length = _slice_len(valobj) + if length is None: + return "" + + text = _read_u8_string_from_slice(valobj, length) + if text is not None: + return f'len={length} "{text}"' + + if _suspicious_child_count(length): + return f"len={length}, children suppressed" + return f"len={length}" + + +def many_pointer_summary(valobj: lldb.SBValue, _dict) -> str: + address = _address(valobj) + if address is None: + return "" + return f"ptr=0x{address:x}" + + +def array_list_summary(valobj: lldb.SBValue, _dict) -> str: + items = _array_list_items(valobj) + length = _slice_len(items) if items is not None else None + capacity = _uint_child(valobj, "capacity") + + if length is None: + return "" + length_text = f"len={length}" + if _suspicious_child_count(length): + length_text = f"len={length}, children suppressed" + if capacity is None: + return length_text + return f"{length_text}, capacity={capacity}" + + +def hash_map_summary(valobj: lldb.SBValue, _dict) -> str: + count = _hash_map_count(valobj) + capacity = _hash_map_capacity(valobj) + + if count is None and capacity is None: + return "" + if capacity is None: + return f"count={count}" + if count is None: + return f"capacity={capacity}" + return f"count={count}, capacity={capacity}" + + +def string_hash_map_summary(valobj: lldb.SBValue, _dict) -> str: + summary = hash_map_summary(valobj, _dict) + return f"StringHashMap {summary}" + + +def record_summary(valobj: lldb.SBValue, _dict) -> str: + try: + document = _child(valobj, "document") + record_id = _uint_child(valobj, "id") + if document is None or record_id is None: + return "" + + slot = _record_slot(valobj) + if slot is None: + slots_len = _document_slots_len(document) + if slots_len is None: + return f"id={record_id}, slot=" + return f"id={record_id}, slot=, slots.len={slots_len}" + + tag = _zig_union_tag_name(slot) + if tag is None: + return f"id={record_id}, slot={slot.GetTypeName()}" + return f"id={record_id}, tag={tag}" + except Exception as exc: + record_id = _uint_child(valobj, "id") + if record_id is None: + return f"" + return f"id={record_id}, slot=" + + +def record_list_summary(valobj: lldb.SBValue, _dict) -> str: + try: + record = _child(valobj, "record") + if record is None: + return "" + + record_id = _uint_child(record, "id") + active_list = _record_active_list(record) + items = _array_list_items(active_list) if active_list is not None else None + length = _slice_len(items) + if record_id is None: + return "" + if length is None: + return f"id={record_id}, list=" + return f"id={record_id}, len={length}" + except Exception as exc: + return f"" + + +def record_dict_summary(valobj: lldb.SBValue, _dict) -> str: + try: + record = _child(valobj, "record") + if record is None: + return "" + + record_id = _uint_child(record, "id") + active_dict = _record_active_dict(record) + if record_id is None: + return "" + if active_dict is None: + return f"id={record_id}, dict=" + + summary = hash_map_summary(active_dict, _dict) + return f"id={record_id}, {summary}" + except Exception as exc: + return f"" + + +class SliceSyntheticProvider: + def __init__(self, valobj: lldb.SBValue, _dict): + self.valobj = valobj + self.ptr = None + self.length = 0 + self.elem_type = None + self.elem_size = 0 + self.has_string_child = False + self.update() + + def update(self) -> None: + self.ptr = _child(self.valobj, "ptr") + self.length = _slice_len(self.valobj) or 0 + self.elem_type = _pointer_pointee_type(self.ptr) + self.elem_size = _byte_size(self.elem_type) + self.has_string_child = _is_u8_type(self.elem_type) + + def num_children(self) -> int: + string_count = 1 if self.has_string_child else 0 + if _suspicious_child_count(self.length): + return string_count + return string_count + self.length + + def get_child_index(self, name: str) -> int: + if self.has_string_child and name == "string": + return 0 + + match = re.match(r"^\[(\d+)\]$", name) + if match is None: + return -1 + index = int(match.group(1)) + return index + (1 if self.has_string_child else 0) + + def get_child_at_index(self, index: int) -> lldb.SBValue: + if index < 0 or index >= self.num_children(): + return lldb.SBValue() + + if self.has_string_child: + if index == 0: + return _slice_string_child(self.valobj, "string", self.length) + index -= 1 + + if index >= self.length: + return lldb.SBValue() + return _pointer_child_at(self.ptr, self.elem_type, self.elem_size, index) + + def has_children(self) -> bool: + return self.num_children() > 0 + + +class ArrayListSyntheticProvider: + def __init__(self, valobj: lldb.SBValue, _dict): + self.valobj = valobj + self.slice_provider = None + self.update() + + def update(self) -> None: + items = _array_list_items(self.valobj) + self.slice_provider = ( + SliceSyntheticProvider(items, {}) if items is not None else None + ) + + def num_children(self) -> int: + if self.slice_provider is None: + return 0 + return self.slice_provider.num_children() + + def get_child_index(self, name: str) -> int: + if self.slice_provider is None: + return -1 + return self.slice_provider.get_child_index(name) + + def get_child_at_index(self, index: int) -> lldb.SBValue: + if self.slice_provider is None: + return lldb.SBValue() + return self.slice_provider.get_child_at_index(index) + + def has_children(self) -> bool: + return self.num_children() > 0 + + +class HashMapSyntheticProvider: + """Best-effort expansion for std hash maps. + + Zig's HashMap internals differ between releases and between managed and + unmanaged variants. This provider exposes the raw control fields and, for + Zig 0.16 HashMapUnmanaged layout, scans metadata to show only live slots. + """ + + def __init__(self, valobj: lldb.SBValue, _dict): + self.valobj = valobj + self.children = [] + self.entries = None + self.keys = None + self.values = None + self.capacity = 0 + self.header_data = None + self.key_type = None + self.value_type = None + self.live_slots = [] + self.update() + + def update(self) -> None: + self.children = [] + self.entries = _hash_map_entries(self.valobj) + self.keys = _hash_map_keys(self.valobj) + self.values = _hash_map_values(self.valobj) + self.capacity = _hash_map_capacity(self.valobj) or 0 + self.header_data = None + self.key_type = None + self.value_type = None + self.live_slots = [] + + raw_map = _hash_map_unmanaged(self.valobj) + if raw_map is not None: + for name in ("metadata", "size", "available", "pointer_stability"): + child = _child(raw_map, name) + if child is not None: + self.children.append((name, child)) + + header = _hash_map_header(raw_map) + for name, child in header: + self.children.append((name, child)) + + self.header_data = _hash_map_header_data(raw_map) + self.key_type, self.value_type = _hash_map_key_value_types(raw_map) + self.live_slots = _hash_map_live_slots(raw_map, self.header_data) + + def num_children(self) -> int: + fixed_count = len(self.children) + if self._has_live_slot_children(): + count = len(self.live_slots) * 2 + return fixed_count if _suspicious_child_count(count) else fixed_count + count + + if self.entries is None: + if self.keys is not None and self.values is not None: + count = self.capacity * 2 + return fixed_count if _suspicious_child_count(count) else fixed_count + count + if self.keys is not None or self.values is not None: + return fixed_count if _suspicious_child_count(self.capacity) else fixed_count + self.capacity + return fixed_count + count = _slice_len(self.entries) or 0 + return fixed_count if _suspicious_child_count(count) else fixed_count + count + + def get_child_index(self, name: str) -> int: + for i, (child_name, _child_value) in enumerate(self.children): + if child_name == name: + return i + + match = re.match(r"^slot\[(\d+)\]\.(key|value)$", name) + if match is not None: + slot = int(match.group(1)) + try: + live_index = self.live_slots.index(slot) + except ValueError: + return -1 + return len(self.children) + live_index * 2 + (0 if match.group(2) == "key" else 1) + + match = re.match(r"^\[(\d+)\]$", name) + if match is None: + return -1 + return len(self.children) + int(match.group(1)) + + def get_child_at_index(self, index: int) -> lldb.SBValue: + if index < 0 or index >= self.num_children(): + return lldb.SBValue() + + fixed_count = len(self.children) + if index < fixed_count: + _name, child = self.children[index] + return child + + entry_index = index - fixed_count + if self._has_live_slot_children(): + live_index = entry_index // 2 + if live_index < 0 or live_index >= len(self.live_slots): + return lldb.SBValue() + + slot = self.live_slots[live_index] + if entry_index % 2 == 0: + return _hash_map_slot_child( + self.valobj, + self.header_data, + self.key_type, + slot, + f"slot[{slot}].key", + "keys_addr", + ) + return _hash_map_slot_child( + self.valobj, + self.header_data, + self.value_type, + slot, + f"slot[{slot}].value", + "values_addr", + ) + + if self.entries is None: + if self.keys is not None and self.values is not None: + slot = entry_index // 2 + storage = self.keys if entry_index % 2 == 0 else self.values + name = f"[{slot}].key" if entry_index % 2 == 0 else f"[{slot}].value" + child = _pointer_storage_child(storage, name, slot) + return child if child is not None else lldb.SBValue() + if self.keys is not None or self.values is not None: + storage = self.keys if self.keys is not None else self.values + child = _pointer_storage_child(storage, f"[{entry_index}]", entry_index) + return child if child is not None else lldb.SBValue() + return lldb.SBValue() + provider = SliceSyntheticProvider(self.entries, {}) + return provider.get_child_at_index(entry_index) + + def has_children(self) -> bool: + return self.num_children() > 0 + + def _has_live_slot_children(self) -> bool: + return ( + self.header_data is not None + and self.key_type is not None + and self.value_type is not None + and len(self.live_slots) > 0 + ) + + +class RecordSyntheticProvider: + def __init__(self, valobj: lldb.SBValue, _dict): + self.valobj = valobj + self.children = [] + self.update() + + def update(self) -> None: + self.children = [] + try: + record_id = _child(self.valobj, "id") + if record_id is not None: + self.children.append(("id", record_id)) + + document = _child(self.valobj, "document") + if document is not None: + self.children.append(("document", document)) + + slot_ptr = _record_slot_ptr(self.valobj) + if slot_ptr is not None: + self.children.append(("slot_ptr", slot_ptr)) + + slot = _deref(slot_ptr) + if slot is not None: + self.children.append(("slot", slot)) + except Exception: + self.children = [] + + def num_children(self) -> int: + return len(self.children) + + def get_child_index(self, name: str) -> int: + for i, (child_name, _child_value) in enumerate(self.children): + if child_name == name: + return i + return -1 + + def get_child_at_index(self, index: int) -> lldb.SBValue: + if index < 0 or index >= len(self.children): + return lldb.SBValue() + _name, child = self.children[index] + return child + + def has_children(self) -> bool: + return len(self.children) > 0 + + +class RecordListSyntheticProvider: + def __init__(self, valobj: lldb.SBValue, _dict): + self.valobj = valobj + self.children = [] + self.items_provider = None + self.fixed_count = 0 + self.update() + + def update(self) -> None: + self.children = [] + self.items_provider = None + self.fixed_count = 0 + + try: + record = _child(self.valobj, "record") + if record is not None: + self.children.append(("record", record)) + + slot_ptr = _record_slot_ptr(record) if record is not None else None + if slot_ptr is not None: + self.children.append(("slot_ptr", slot_ptr)) + + slot = _deref(slot_ptr) + if slot is not None: + self.children.append(("slot", slot)) + + active_list = _record_active_list(record) if record is not None else None + if active_list is not None: + self.children.append(("active_list", active_list)) + items = _array_list_items(active_list) + if items is not None: + self.children.append(("items", items)) + self.items_provider = SliceSyntheticProvider(items, {}) + + self.fixed_count = len(self.children) + except Exception: + self.children = [] + self.items_provider = None + self.fixed_count = 0 + + def num_children(self) -> int: + item_count = self.items_provider.num_children() if self.items_provider else 0 + return self.fixed_count + item_count + + def get_child_index(self, name: str) -> int: + for i, (child_name, _child_value) in enumerate(self.children): + if child_name == name: + return i + + match = re.match(r"^\[(\d+)\]$", name) + if match is None: + return -1 + return self.fixed_count + int(match.group(1)) + + def get_child_at_index(self, index: int) -> lldb.SBValue: + if index < 0: + return lldb.SBValue() + if index < self.fixed_count: + _name, child = self.children[index] + return child + if self.items_provider is None: + return lldb.SBValue() + + item_index = index - self.fixed_count + return self.items_provider.get_child_at_index(item_index) + + def has_children(self) -> bool: + return self.num_children() > 0 + + +class RecordDictSyntheticProvider: + def __init__(self, valobj: lldb.SBValue, _dict): + self.valobj = valobj + self.children = [] + self.dict_provider = None + self.fixed_count = 0 + self.update() + + def update(self) -> None: + self.children = [] + self.dict_provider = None + self.fixed_count = 0 + + try: + record = _child(self.valobj, "record") + if record is not None: + self.children.append(("record", record)) + + slot_ptr = _record_slot_ptr(record) if record is not None else None + if slot_ptr is not None: + self.children.append(("slot_ptr", slot_ptr)) + + slot = _deref(slot_ptr) + if slot is not None: + self.children.append(("slot", slot)) + + active_dict = _record_active_dict(record) if record is not None else None + if active_dict is not None: + self.children.append(("active_dict", active_dict)) + self.dict_provider = HashMapSyntheticProvider(active_dict, {}) + if record is not None and record.GetType().IsValid(): + self.dict_provider.value_type = record.GetType() + + self.fixed_count = len(self.children) + except Exception: + self.children = [] + self.dict_provider = None + self.fixed_count = 0 + + def num_children(self) -> int: + dict_count = self.dict_provider.num_children() if self.dict_provider else 0 + return self.fixed_count + dict_count + + def get_child_index(self, name: str) -> int: + for i, (child_name, _child_value) in enumerate(self.children): + if child_name == name: + return i + + match = re.match(r"^\[(\d+)\]$", name) + if match is None: + return -1 + return self.fixed_count + int(match.group(1)) + + def get_child_at_index(self, index: int) -> lldb.SBValue: + if index < 0: + return lldb.SBValue() + if index < self.fixed_count: + _name, child = self.children[index] + return child + if self.dict_provider is None: + return lldb.SBValue() + + dict_index = index - self.fixed_count + return self.dict_provider.get_child_at_index(dict_index) + + def has_children(self) -> bool: + return self.num_children() > 0 + + +def _child(valobj: lldb.SBValue | None, name: str) -> lldb.SBValue | None: + if valobj is None or not valobj.IsValid(): + return None + raw = _raw_value(valobj) + child = raw.GetChildMemberWithName(name) + if child.IsValid(): + return child + return None + + +def _raw_value(valobj: lldb.SBValue) -> lldb.SBValue: + raw = valobj.GetNonSyntheticValue() + if raw.IsValid(): + return raw + return valobj + + +def _first_child(valobj: lldb.SBValue | None, names: tuple[str, ...]) -> lldb.SBValue | None: + for name in names: + child = _child(valobj, name) + if child is not None: + return child + return None + + +def _uint(value: lldb.SBValue | None) -> int | None: + if value is None or not value.IsValid(): + return None + result = value.GetValueAsUnsigned(0) + if result != 0 or (value.GetValue() in ("0", "0x0")): + return result + try: + return int(value.GetValue(), 0) + except (TypeError, ValueError): + return None + + +def _uint_child(valobj: lldb.SBValue | None, name: str) -> int | None: + return _uint(_child(valobj, name)) + + +def _address(value: lldb.SBValue | None) -> int | None: + if value is None or not value.IsValid(): + return None + address = value.GetValueAsUnsigned() + if address: + return address + load_address = value.GetLoadAddress() + if load_address != lldb.LLDB_INVALID_ADDRESS: + return load_address + return None + + +def _deref(value: lldb.SBValue | None) -> lldb.SBValue | None: + if value is None or not value.IsValid(): + return None + child = value.Dereference() + if child.IsValid(): + return child + return None + + +def _slice_len(valobj: lldb.SBValue | None) -> int | None: + return _uint_child(valobj, "len") + + +def _pointer_pointee_type(ptr: lldb.SBValue | None) -> lldb.SBType | None: + if ptr is None or not ptr.IsValid(): + return None + pointee = ptr.GetType().GetPointeeType() + if pointee.IsValid(): + return pointee + return None + + +def _byte_size(value_type: lldb.SBType | None) -> int: + if value_type is None or not value_type.IsValid(): + return 0 + return value_type.GetByteSize() + + +def _is_u8_type(value_type: lldb.SBType | None) -> bool: + if value_type is None or not value_type.IsValid(): + return False + return (value_type.GetName() or "") in ("u8", "const u8") + + +def _slice_string_child( + valobj: lldb.SBValue, + name: str, + length: int, +) -> lldb.SBValue: + target = valobj.GetTarget() + if not target.IsValid(): + return lldb.SBValue() + + char_type = target.GetBasicType(lldb.eBasicTypeChar) + if not char_type.IsValid(): + char_type = target.GetBasicType(lldb.eBasicTypeSignedChar) + if not char_type.IsValid(): + char_type = target.GetBasicType(lldb.eBasicTypeUnsignedChar) + if not char_type.IsValid(): + return lldb.SBValue() + + string_len = min(length, MAX_STRING_BYTES) + array_type = char_type.GetArrayType(max(string_len, 1)) + if not array_type.IsValid(): + return lldb.SBValue() + + ptr = _child(valobj, "ptr") + address = _address(ptr) + if address is None: + return lldb.SBValue() + return valobj.CreateValueFromAddress(name, address, array_type) + + +def _string_value(parent: lldb.SBValue, name: str, text: str) -> lldb.SBValue: + escaped = ( + text.replace("\\", "\\\\") + .replace("\n", "\\n") + .replace("\r", "\\r") + .replace("\t", "\\t") + .replace('"', '\\"') + ) + return parent.CreateValueFromExpression(name, f'"{escaped}"') + + +def _pointer_child_at( + ptr: lldb.SBValue | None, + elem_type: lldb.SBType | None, + elem_size: int, + index: int, + name: str | None = None, +) -> lldb.SBValue: + if ptr is None or elem_type is None or elem_size == 0: + return lldb.SBValue() + address = _address(ptr) + if address is None: + return lldb.SBValue() + offset = index * elem_size + if offset > MAX_CREATE_CHILD_OFFSET: + return lldb.SBValue() + try: + child_name = name if name is not None else f"[{index}]" + return ptr.CreateValueFromAddress(child_name, address + offset, elem_type) + except OverflowError: + return lldb.SBValue() + + +def _array_list_items(valobj: lldb.SBValue) -> lldb.SBValue | None: + items = _child(valobj, "items") + if items is not None: + return items + + unmanaged = _first_child(valobj, ("unmanaged", "list", "inner")) + if unmanaged is not None: + return _child(unmanaged, "items") + + return None + + +def _suspicious_child_count(count: int) -> bool: + return count > MAX_TRUSTED_SYNTHETIC_CHILDREN + + +def _record_slot(record: lldb.SBValue) -> lldb.SBValue | None: + return _deref(_record_slot_ptr(record)) + + +def _record_active_list(record: lldb.SBValue) -> lldb.SBValue | None: + slot = _record_slot(record) + if slot is None: + return None + return _union_payload(slot, ("list",)) + + +def _record_active_dict(record: lldb.SBValue) -> lldb.SBValue | None: + slot = _record_slot(record) + if slot is None: + return None + return _union_payload(slot, ("dict",)) + + +def _record_slot_ptr(record: lldb.SBValue) -> lldb.SBValue | None: + document_ptr = _child(record, "document") + record_id = _uint_child(record, "id") + if document_ptr is None or record_id is None: + return None + + document = _deref(document_ptr) + if document is None: + return None + + slots = _child(document, "slots") + if slots is None: + return None + + items = _array_list_items(slots) + slots_len = _slice_len(items) + if items is None or slots_len is None or record_id >= slots_len: + return None + + slot_ptr = _slice_child_at(items, record_id, "slot_ptr") + if slot_ptr.IsValid(): + return slot_ptr + return None + + +def _slice_child_at( + slice_value: lldb.SBValue, + index: int, + name: str | None = None, +) -> lldb.SBValue: + length = _slice_len(slice_value) + if length is None or index < 0 or index >= length: + return lldb.SBValue() + + ptr = _child(slice_value, "ptr") + elem_type = _pointer_pointee_type(ptr) + elem_size = _byte_size(elem_type) + return _pointer_child_at(ptr, elem_type, elem_size, index, name) + + +def _document_slots_len(document_ptr: lldb.SBValue) -> int | None: + document = _deref(document_ptr) + if document is None: + return None + slots = _child(document, "slots") + if slots is None: + return None + items = _array_list_items(slots) + return _slice_len(items) + + +def _zig_union_tag(value: lldb.SBValue) -> str | None: + tag = _zig_union_tag_child(value) + if tag is not None: + return tag.GetValue() or tag.GetSummary() + return None + + +def _zig_union_tag_child(value: lldb.SBValue) -> lldb.SBValue | None: + for name in ("tag", "__tag", "_tag"): + tag = _child(value, name) + if tag is not None: + return tag + + for i in range(value.GetNumChildren()): + child = value.GetChildAtIndex(i) + name = child.GetName() or "" + if "tag" in name.lower(): + return child + + return None + + +def _zig_union_tag_name(value: lldb.SBValue) -> str | None: + raw = _zig_union_tag(value) + if raw is None: + return None + + raw = raw.strip() + if raw.startswith('"') and raw.endswith('"'): + raw = raw[1:-1] + if raw.startswith("."): + raw = raw[1:] + + match = re.search(r"([A-Za-z_][A-Za-z0-9_]*)$", raw) + if match is None: + return raw or None + return match.group(1) + + +def _union_payload(value: lldb.SBValue, names: tuple[str, ...]) -> lldb.SBValue | None: + payload = _first_child(value, names) + if payload is not None: + return payload + + for i in range(value.GetNumChildren()): + child = value.GetChildAtIndex(i) + name = child.GetName() or "" + if name in names: + return child + + lowered = name.lower() + for wanted in names: + wanted_lower = wanted.lower() + if wanted_lower == lowered or wanted_lower in lowered: + return child + + return None + + +def _hash_map_count(valobj: lldb.SBValue) -> int | None: + direct = _first_uint_child( + valobj, + ( + "count", + "size", + "len", + "entries_len", + ), + ) + if direct is not None: + return direct + + unmanaged = _hash_map_unmanaged(valobj) + if unmanaged is not None and unmanaged.GetID() != valobj.GetID(): + return _hash_map_count(unmanaged) + + metadata = _first_child(valobj, ("metadata", "header")) + if metadata is not None: + return _first_uint_child(metadata, ("count", "size", "len")) + + return None + + +def _hash_map_capacity(valobj: lldb.SBValue) -> int | None: + direct = _first_uint_child( + valobj, + ( + "capacity", + "available", + "entries_cap", + ), + ) + if direct is not None: + return direct + + unmanaged = _hash_map_unmanaged(valobj) + if unmanaged is not None and unmanaged.GetID() != valobj.GetID(): + return _hash_map_capacity(unmanaged) + + entries = _hash_map_entries(valobj) + if entries is not None: + return _slice_len(entries) + + header_capacity = _hash_map_header_capacity(valobj) + if header_capacity is not None: + return header_capacity + + return None + + +def _hash_map_header_capacity(valobj: lldb.SBValue) -> int | None: + header = _hash_map_header_data(valobj) + if header is None: + return None + return header["capacity"] + + +def _hash_map_header(valobj: lldb.SBValue) -> list[tuple[str, lldb.SBValue]]: + header = _hash_map_header_data(valobj) + if header is None: + return [] + + children: list[tuple[str, lldb.SBValue]] = [] + children.append(("header_addr", _usize_value(valobj, "header_addr", header["header_addr"]))) + children.append(("header.values", _usize_value(valobj, "header.values", header["values_addr"]))) + children.append(("header.keys", _usize_value(valobj, "header.keys", header["keys_addr"]))) + children.append(("header.capacity", _usize_value(valobj, "header.capacity", header["capacity"]))) + return children + + +def _hash_map_header_data(valobj: lldb.SBValue) -> dict[str, int] | None: + metadata = _child(valobj, "metadata") + metadata_addr = _address(metadata) + if metadata_addr is None: + return None + + process = valobj.GetProcess() + if not process.IsValid(): + return None + + address_size = process.GetAddressByteSize() + header_fields_size = address_size * 2 + 4 + header_size = _align_forward(header_fields_size, address_size) + header_addr = metadata_addr - header_size + + err = lldb.SBError() + raw = process.ReadMemory(header_addr, header_size, err) + if not err.Success() or len(raw) != header_size: + return None + + endian_prefix = _endian_prefix(process) + if address_size == 8: + values_addr = struct.unpack_from(endian_prefix + "Q", raw, 0)[0] + keys_addr = struct.unpack_from(endian_prefix + "Q", raw, 8)[0] + capacity = struct.unpack_from(endian_prefix + "I", raw, 16)[0] + elif address_size == 4: + values_addr = struct.unpack_from(endian_prefix + "I", raw, 0)[0] + keys_addr = struct.unpack_from(endian_prefix + "I", raw, 4)[0] + capacity = struct.unpack_from(endian_prefix + "I", raw, 8)[0] + else: + return None + + return { + "header_addr": header_addr, + "values_addr": values_addr, + "keys_addr": keys_addr, + "capacity": capacity, + } + + +def _hash_map_live_slots( + valobj: lldb.SBValue, + header: dict[str, int] | None, +) -> list[int]: + if header is None: + return [] + + capacity = header["capacity"] + if capacity == 0 or _suspicious_child_count(capacity): + return [] + + metadata = _child(valobj, "metadata") + metadata_addr = _address(metadata) + if metadata_addr is None: + return [] + + process = valobj.GetProcess() + if not process.IsValid(): + return [] + + err = lldb.SBError() + raw = process.ReadMemory(metadata_addr, capacity, err) + if not err.Success() or len(raw) != capacity: + return [] + + byte_order = process.GetByteOrder() + used_mask = 0x01 if byte_order == lldb.eByteOrderBig else 0x80 + return [index for index, metadata_byte in enumerate(raw) if metadata_byte & used_mask] + + +def _hash_map_key_value_types( + valobj: lldb.SBValue, +) -> tuple[lldb.SBType | None, lldb.SBType | None]: + type_name = valobj.GetTypeName() or valobj.GetType().GetName() or "" + args = _type_arguments(type_name, "HashMapUnmanaged") + if len(args) < 2: + args = _type_arguments(type_name, "HashMap") + if len(args) < 2: + return (None, None) + + target = valobj.GetTarget() + if not target.IsValid(): + return (None, None) + + key_type = _find_type(target, args[0]) + value_type = _find_type(target, args[1]) + if key_type is None or value_type is None: + return (None, None) + return (key_type, value_type) + + +def _type_arguments(type_name: str, callee: str) -> list[str]: + start = type_name.find(callee + "(") + if start < 0: + return [] + + start += len(callee) + 1 + depth = 0 + end = start + while end < len(type_name): + char = type_name[end] + if char in "([{": + depth += 1 + elif char in ")]}": + if depth == 0: + break + depth -= 1 + end += 1 + + if end >= len(type_name): + return [] + return _split_top_level_args(type_name[start:end]) + + +def _split_top_level_args(args: str) -> list[str]: + result: list[str] = [] + start = 0 + depth = 0 + for index, char in enumerate(args): + if char in "([{": + depth += 1 + elif char in ")]}": + depth -= 1 + elif char == "," and depth == 0: + result.append(args[start:index].strip()) + start = index + 1 + result.append(args[start:].strip()) + return [arg for arg in result if arg] + + +def _find_type(target: lldb.SBTarget, type_name: str) -> lldb.SBType | None: + candidates = [type_name] + if type_name.startswith("const "): + candidates.append(type_name[len("const ") :]) + + for candidate in candidates: + found = target.FindFirstType(candidate) + if found.IsValid(): + return found + + return None + + +def _hash_map_slot_child( + parent: lldb.SBValue, + header: dict[str, int] | None, + child_type: lldb.SBType | None, + slot: int, + name: str, + address_field: str, +) -> lldb.SBValue: + if header is None or child_type is None or not child_type.IsValid(): + return lldb.SBValue() + + elem_size = child_type.GetByteSize() + if elem_size == 0: + return lldb.SBValue() + + address = header[address_field] + slot * elem_size + return parent.CreateValueFromAddress(name, address, child_type) + + +def _usize_value(parent: lldb.SBValue, name: str, value: int) -> lldb.SBValue: + return parent.CreateValueFromExpression(name, str(value)) + + +def _endian_prefix(process: lldb.SBProcess) -> str: + byte_order = process.GetByteOrder() + if byte_order == lldb.eByteOrderBig: + return ">" + return "<" + + +def _align_forward(value: int, alignment: int) -> int: + return (value + alignment - 1) & ~(alignment - 1) + + +def _first_uint_child(valobj: lldb.SBValue, names: tuple[str, ...]) -> int | None: + for name in names: + result = _uint_child(valobj, name) + if result is not None: + return result + return None + + +def _hash_map_unmanaged(valobj: lldb.SBValue) -> lldb.SBValue | None: + return _first_child( + valobj, + ( + "unmanaged", + "map", + "hm", + "hash_map", + ), + ) or valobj + + +def _hash_map_entries(valobj: lldb.SBValue) -> lldb.SBValue | None: + direct = _first_child( + valobj, + ( + "entries", + "keys", + "values", + ), + ) + if direct is not None and _slice_len(direct) is not None: + return direct + + unmanaged = _hash_map_unmanaged(valobj) + if unmanaged is not None and unmanaged.GetID() != valobj.GetID(): + return _hash_map_entries(unmanaged) + + return None + + +def _hash_map_keys(valobj: lldb.SBValue) -> lldb.SBValue | None: + return _hash_map_pointer_storage(valobj, ("keys", "key_ptr", "keyPtr")) + + +def _hash_map_values(valobj: lldb.SBValue) -> lldb.SBValue | None: + return _hash_map_pointer_storage(valobj, ("values", "value_ptr", "valuePtr")) + + +def _hash_map_pointer_storage( + valobj: lldb.SBValue, + names: tuple[str, ...], +) -> lldb.SBValue | None: + direct = _first_child(valobj, names) + if direct is not None: + return direct + + unmanaged = _hash_map_unmanaged(valobj) + if unmanaged is not None and unmanaged.GetID() != valobj.GetID(): + return _hash_map_pointer_storage(unmanaged, names) + + return None + + +def _pointer_storage_child( + storage: lldb.SBValue | None, + name: str, + index: int, +) -> lldb.SBValue | None: + if storage is None: + return None + + if _slice_len(storage) is not None: + provider = SliceSyntheticProvider(storage, {}) + child = _slice_child_at(storage, index, name) + return child if child.IsValid() else None + + elem_type = _pointer_pointee_type(storage) + elem_size = _byte_size(elem_type) + child = _pointer_child_at(storage, elem_type, elem_size, index, name) + return child if child.IsValid() else None + + +def _read_u8_string_from_slice(valobj: lldb.SBValue, length: int) -> str | None: + if length == 0: + return "" + + ptr = _child(valobj, "ptr") + elem_type = _pointer_pointee_type(ptr) + if elem_type is None: + return None + + elem_name = elem_type.GetName() or "" + if elem_name not in ("u8", "const u8"): + return None + + address = _address(ptr) + if address is None: + return None + + process = valobj.GetProcess() + if not process.IsValid(): + return None + + read_len = min(length, MAX_STRING_BYTES) + err = lldb.SBError() + data = process.ReadMemory(address, read_len, err) + if not err.Success(): + return None + + decoded = data.decode("utf-8", errors="replace") + escaped = ( + decoded.replace("\\", "\\\\") + .replace("\n", "\\n") + .replace("\r", "\\r") + .replace("\t", "\\t") + .replace('"', '\\"') + ) + if read_len < length: + escaped += "..." + return escaped diff --git a/engine/p2/src/algorithm/pointer-hash.zig b/engine/p2/src/algorithm/pointer-hash.zig new file mode 100644 index 0000000..95a0b68 --- /dev/null +++ b/engine/p2/src/algorithm/pointer-hash.zig @@ -0,0 +1 @@ +const std = @import("std"); diff --git a/engine/p2/src/p2.zig b/engine/p2/src/p2.zig new file mode 100644 index 0000000..d667d4b --- /dev/null +++ b/engine/p2/src/p2.zig @@ -0,0 +1,433 @@ +// ---- ---- +const std = @import("std"); + +pub const stats = @import("structures/stats.zig"); +pub const PoolStatistics = stats.PoolStatistics; + +const utils = @import("structures/utils.zig"); +pub const getFileExtension = utils.getFileExtension; +pub const getBasePath = utils.getBasePath; +pub const getFolder = utils.getFolder; +pub const getDir = utils.getFolder; +pub const splitSliceWork = utils.splitSliceWork; + +pub const BumpArena = @import("structures/bump-arena.zig").BumpArena; + +pub const pscopes = @import("structures/pscopes.zig"); + +pub const dupeString = utils.dupeString; +pub const xxd = @import("utils/xxd.zig"); + +pub const stringStrip = utils.stringStrip; +pub const xxdWrite = xxd.xxdWrite; + +pub const loadFileAlloc = utils.loadFileAlloc; +const ArrayList = std.ArrayList; +const ArrayListUnmanaged = std.ArrayListUnmanaged; +pub const interface = @import("structures/interface.zig"); +pub const MakeInterface = interface.MakeInterface; +pub const Reference = interface.Reference; +pub const refFromPtr = interface.refFromPtr; + +pub const assertf = utils.assertf; +pub const asserts = utils.asserts; +pub const assert = utils.assert; + +pub const createFileWithPath = utils.createFileWithPath; +pub const makePathAny = utils.makePathAny; + +pub const static_structures = @import("structures/static-structures.zig"); +pub const StaticVector = static_structures.StaticVector; + +pub const math = @import("structures/math.zig"); +pub const zm = math.zm; + +pub const ring_queue = @import("structures/ring-queue.zig"); + +pub const RingQueueU = ring_queue.RingQueueU; +pub const RingQueue = ring_queue.RingQueue; + +pub const sparse_set = @import("structures/sparse-set.zig"); + +pub const SparseSet = sparse_set.SparseSet; +pub const SparseMap = sparse_set.SparseMap; +pub const SparseMultiSet = sparse_set.SparseMultiSet; +pub const SparseSetAdvanced = sparse_set.SparseSetAdvanced; +pub const SparseMultiSetAdvanced = sparse_set.SparseMultiSetAdvanced; +pub const SetHandle = sparse_set.SetHandle; +pub const EcsContainerInterface = sparse_set.EcsContainerInterface; + +// pub const stack_structures = @import("structures/stack-structures.zig"); + +pub const index_pool = @import("structures/index-pool.zig"); +pub const IndexPoolHandle = index_pool.TypedHandle; +pub const IndexPool = index_pool.IndexPool; + +pub const ref_pool = @import("structures/ref-pool.zig"); +pub const RefPoolOptions = ref_pool.RefPoolOptions; +pub const RefPool = ref_pool.RefPool; +pub const RefPoolAdvanced = ref_pool.RefPoolAdvanced; + +pub const concurrent_queue = @import("structures/concurrent-queue.zig"); + +pub const ConcurrentQueueU = concurrent_queue.ConcurrentQueueU; +pub const ConcurrentQueueUnmanagedAdvanced = concurrent_queue.ConcurrentQueueUnmanagedAdvanced; + +pub const string_pool = @import("structures/string-pool.zig"); +pub const RefBuffer = string_pool.RefBuffer; +pub const RefString = string_pool.RefString; +pub const ref_string_map = @import("structures/ref-string-map.zig"); +pub const RefStringMap = ref_string_map.RefStringMap; + +pub const paged_vector = @import("structures/paged-vector.zig"); +pub const PagedVector = paged_vector.PagedVector; + +pub const names = @import("structures/names.zig"); + +pub const NameInvalid = names.NameInvalid; +pub const ComptimeName = names.ComptimeName; +pub const Name = names.Name; +pub const StaticName = names.StaticName; +pub const MakeName = names.MakeName; +pub const DefineName = names.DefineName; +pub const createNameRegistry = names.createNameRegistry; +pub const destroyNameRegistry = names.destroyNameRegistry; +pub const setNameRegistry = names.setNameRegistry; +pub const NameRegistry = names.NameRegistry; + +pub const spans = @import("structures/spans.zig"); +pub const MergedSpans = spans.MergedSpans; +pub const Span = spans.Span; + +pub const shell = @import("utils/shell.zig"); + +pub fn sharedLibNameAlloc(allocator: std.mem.Allocator, s: []const u8) ![]u8 { + const os_tag = @import("builtin").os.tag; + + var suffix: []const u8 = "dll"; + var prefix: []const u8 = ""; + if (os_tag == .linux) { + prefix = "lib"; + suffix = "so"; + } else if (os_tag == .macos) { + suffix = "dylib"; + prefix = "lib"; + } + + const path = try std.fmt.allocPrint(allocator, "{s}{s}.{s}", .{ prefix, s, suffix }); + + return path; +} + +comptime { + std.testing.refAllDecls(utils); + std.testing.refAllDecls(static_structures); + std.testing.refAllDecls(ring_queue); + std.testing.refAllDecls(sparse_set); + // std.testing.refAllDecls(stack_structures); + std.testing.refAllDecls(index_pool); + std.testing.refAllDecls(concurrent_queue); + std.testing.refAllDecls(@import("structures/spmc-submission-queue.zig")); + std.testing.refAllDecls(string_pool); + std.testing.refAllDecls(ref_string_map); + std.testing.refAllDecls(spans); +} + +// ---- aliases ---- +pub const ObjectHandle = SetHandle; + +pub inline fn u32_to_slice(array: *u32) []u8 { + var slice: []u8 = undefined; + slice.ptr = @ptrCast(array); + slice.len = 4; + return slice; +} + +pub inline fn u64_to_slice(array: *u64) []u8 { + var slice: []u8 = undefined; + slice.ptr = @ptrCast(array); + slice.len = 8; + return slice; +} + +pub inline fn arrayTo_u32(array: anytype) u32 { + return @as(*const u32, @ptrCast(@alignCast(&array))).*; +} + +pub inline fn arrayTo_u64(array: anytype) u64 { + return @as(*const u64, @ptrCast(@alignCast(&array))).*; +} + +// ---- tests ---- +test "multi-sparse-basic" { + const allocator = std.testing.allocator; + const TestStructField = struct { + x: u32, + }; + + const TestStruct = struct { + field1: usize, + structField: TestStructField, + }; + + var testSet = SparseMultiSet(TestStruct).init(allocator); + defer testSet.deinit(); + const sparseHandle = try testSet.createObject(.{ .field1 = 1, .structField = .{ .x = 12 } }); + const sparseHandle1 = try testSet.createObject(.{ .field1 = 2, .structField = .{ .x = 34 } }); + const sparseHandle2 = try testSet.createObject(.{ .field1 = 3, .structField = .{ .x = 56 } }); + std.debug.print("handle: {any}\n", .{testSet.get(sparseHandle, .field1).?.*}); + std.debug.print("handle1: {any}\n", .{testSet.get(sparseHandle1, .field1).?.*}); + std.debug.print("handle2: {any}\n", .{testSet.get(sparseHandle2, .field1).?.*}); + _ = testSet.destroyObject(sparseHandle); + std.debug.print("handle1: {any}\n", .{testSet.get(sparseHandle1, .field1).?.*}); + std.debug.print("handle2: {any}\n", .{testSet.get(sparseHandle2, .field1).?.*}); +} + +// As RibTech is primarily a playground for me to learn and practice programming, +// There will be some implementations of basic data structures. For fun ofc +pub fn AppendToArrayListUnique(list: anytype, value: anytype) !void { + for (list.items) |v| { + if (v == value) + return; + } + + try list.append(value); +} + +fn printSetHandle(s: SetHandle) void { + std.debug.print("{any}\n", .{s}); +} + +test "sparse-set" { + std.debug.print("\n", .{}); + const Payload = struct { + name: []const u8, + v: u32, + }; + + const PayloadSet = SparseSet(Payload); + const expect = std.testing.expect; + + var set = PayloadSet.init(std.testing.allocator); + defer set.deinit(); + + var set2 = PayloadSet.init(std.testing.allocator); + defer set2.deinit(); + + const setHandle = (try set.createAndGet(.{ .name = "object1", .v = 0 })).handle; + printSetHandle(setHandle); + const setHandle1 = (try set.createObject(.{ .name = "object2", .v = 1 })); + printSetHandle(setHandle1); + const setHandle2 = (try set.createObject(.{ .name = "object3", .v = 2 })); + printSetHandle(setHandle2); + const setHandle3 = (try set.createObject(.{ .name = "object4", .v = 3 })); + printSetHandle(setHandle3); + + const set2Handle1 = (try set2.createWithHandle(setHandle3, set.get(setHandle2).?.*)).handle; + std.debug.print("set2 handle: \n", .{}); + printSetHandle(set2Handle1); + + for (set.dense.items) |entry| { + std.debug.print("{any}: {s}\n", .{ entry.value, entry.value.name }); + } + + std.debug.print("\ndestroying handle\n", .{}); + set.destroyObject(setHandle); + for (set.dense.items) |entry| { + std.debug.print("{any}: {s}\n", .{ entry.value, entry.value.name }); + } + try expect(set.get(setHandle) == null); + try expect(set.get(setHandle1).?.v == 1); + try expect(set.get(setHandle2).?.v == 2); + try expect(set.get(setHandle3).?.v == 3); + + std.debug.print("\ndestroying handle\n", .{}); + set.destroyObject(setHandle1); + for (set.dense.items) |entry| { + std.debug.print("{any}: {s}\n", .{ entry.value, entry.value.name }); + } + try expect(set.get(setHandle) == null); + try expect(set.get(setHandle1) == null); + try expect(set.get(setHandle2).?.v == 2); + try expect(set.get(setHandle3).?.v == 3); + + std.debug.print("\ndestroying handle\n", .{}); + set.destroyObject(setHandle2); + for (set.dense.items) |entry| { + std.debug.print("{any}: {s}\n", .{ entry.value, entry.value.name }); + } + + try expect(set.get(setHandle) == null); + try expect(set.get(setHandle1) == null); + try expect(set.get(setHandle3).?.v == 3); + try expect(set.get(setHandle2) == null); + + std.debug.print("\ndestroying handle\n", .{}); + set.destroyObject(setHandle3); + for (set.dense.items) |entry| { + std.debug.print("{any}: {s}\n", .{ entry.value, entry.value.name }); + } + + try expect(set.get(setHandle) == null); + try expect(set.get(setHandle1) == null); + try expect(set.get(setHandle2) == null); + try expect(set.get(setHandle3) == null); + + try expect(set.dense.items.len == 0); +} + +test "ringBuffer" { + std.debug.print("\nbuffer test: filling a ring buffer\n", .{}); + + const allocator = std.testing.allocator; + var b = try RingQueueU(u32).init(allocator, 4); + defer b.deinit(allocator); + + const expect = std.testing.expect; + + try b.push(1); + std.debug.print("head={d} tail={d}\n", .{ b.head, b.tail }); + try b.push(2); + std.debug.print("head={d} tail={d}\n", .{ b.head, b.tail }); + try b.push(3); + std.debug.print("head={d} tail={d}\n", .{ b.head, b.tail }); + try expect(b.count() == 3); + + std.debug.print("popping: {d}\n", .{b.pop().?}); + std.debug.print("head={d} tail={d}\n", .{ b.head, b.tail }); + try expect(b.count() == 2); + std.debug.print("popping: {d}\n", .{b.pop().?}); + try expect(b.count() == 1); + std.debug.print("head={d} tail={d}\n", .{ b.head, b.tail }); + std.debug.print("popping: {d}\n", .{b.pop().?}); + try expect(b.count() == 0); + try expect(b.pop() == null); + std.debug.print("head={d} tail={d}\n", .{ b.head, b.tail }); + try std.testing.expect(b.head == b.tail); + try std.testing.expect(b.isEmpty()); + + try b.push(11); + std.debug.print("head={d} tail={d} count={d} len={d}\n", .{ b.head, b.tail, b.count(), b.buffer.len }); + try expect(b.count() == 1); + try b.push(12); + std.debug.print("head={d} tail={d} count={d} len={d}\n", .{ b.head, b.tail, b.count(), b.buffer.len }); + try expect(b.count() == 2); + try b.push(13); + std.debug.print("head={d} tail={d} count={d} len={d}\n", .{ b.head, b.tail, b.count(), b.buffer.len }); + try expect(b.count() == 3); + try b.push(14); + std.debug.print("head={d} tail={d} count={d} len={d}\n", .{ b.head, b.tail, b.count(), b.buffer.len }); + + try expect(b.head == 3); + try expect(b.count() == 4); + try expect(b.tail == ((b.head + 4) % b.buffer.len)); + + try expect(b.at(0).? == b.peek().?); + + const newSize = b.buffer.len * 4; + try b.resize(allocator, newSize); // grow that shit, expect the new size to be size + 1 + try expect(b.capacity() == newSize); + try expect(b.buffer.len == newSize + 1); + + var errorHit: bool = false; + b.resize(allocator, 2) catch |e| { + errorHit = true; + try expect(e == error.AllocSizeTooSmall); + std.debug.print("{any}\n", .{e}); + }; + + try expect(errorHit); + try expect(b.peekBack().?.* == 14); + try expect(b.atBack(1).?.* == 14); + try expect(b.atBack(2).?.* == 13); + try expect(b.atBack(3).?.* == 12); + try expect(b.atBack(4).?.* == 11); + + try b.pushFront(44); + + try expect(b.count() == 5); + try expect(b.peek().?.* == 44); +} + +test "managed ring queue uses stored io mutex" { + const allocator = std.testing.allocator; + const expect = std.testing.expect; + + var queue = try RingQueue(u32).init(allocator, std.testing.io, 2); + defer queue.deinit(); + queue.allowRegrow(); + + try queue.pushLocked(1); + try queue.pushLocked(2); + try queue.pushLocked(3); + try expect(queue.count() == 3); + try expect(queue.popFromLocked().? == 1); + + queue.lock(); + defer queue.unlock(); + try expect(queue.popFromUnlocked().? == 2); + try expect(queue.popFromUnlocked().? == 3); + try expect(queue.popFromUnlocked() == null); +} + +test "spin child process echo" { + const io = std.testing.io; + { + std.debug.print("spin child process\n", .{}); + const process = try shell.ShellProcess.init(std.testing.allocator, io, &.{ "echo", "lmao 2 nova" }); + defer process.deinit(); + std.debug.print("child process created: {any}\n", .{process.argv}); + } + + { + std.debug.print("spin child process 2\n", .{}); + const process = try shell.ShellProcess.initCmd(std.testing.allocator, io, "echo lmao2nova -target='lmao 3 nova'"); + defer process.deinit(); + std.debug.print("{any}\n", .{process.argv}); + } +} + +test "ring queue regrow remains opt-in" { + const allocator = std.testing.allocator; + const expect = std.testing.expect; + const expectError = std.testing.expectError; + + var fixed = try RingQueueU(u32).init(allocator, 1); + defer fixed.deinit(allocator); + + try fixed.push(1); + try expectError(error.QueueIsFull, fixed.push(2)); + try expect(fixed.capacity() == 1); + + var regrow = try RingQueueU(u32).init(allocator, 1); + defer regrow.deinit(allocator); + regrow.allowRegrow(); + + try regrow.push(10); + try regrow.push(20); + try expect(regrow.capacity() >= 2); + try expect(regrow.count() == 2); + try expect(regrow.pop().? == 10); + try expect(regrow.pop().? == 20); + try expect(regrow.pop() == null); +} + +test "ring queue regrow supports pushFront ordering" { + const allocator = std.testing.allocator; + const expect = std.testing.expect; + + var queue = try RingQueueU(u32).init(allocator, 2); + defer queue.deinit(allocator); + queue.allowRegrow(); + + try queue.push(2); + try queue.push(3); + try queue.pushFront(1); + + try expect(queue.capacity() >= 3); + try expect(queue.count() == 3); + try expect(queue.pop().? == 1); + try expect(queue.pop().? == 2); + try expect(queue.pop().? == 3); + try expect(queue.isEmpty()); +} diff --git a/engine/p2/src/queue-benchmark-cas-baseline.zig b/engine/p2/src/queue-benchmark-cas-baseline.zig new file mode 100644 index 0000000..592d8cf --- /dev/null +++ b/engine/p2/src/queue-benchmark-cas-baseline.zig @@ -0,0 +1,117 @@ +//! Frozen pre-fetchSub implementation for queue-benchmark.zig only. +//! Do not use as a production queue or update alongside the live implementation. +const std = @import("std"); + +pub const PackedState = packed struct(u32) { + remaining_items: u24 = 0, // Unclaimed entries. + active_readers: u8 = 0, // Consumers copying descriptors. +}; + +/// Single-producer, multiple-consumer batch mailbox. +/// +/// Keep the mailbox at a stable address once shared. +/// Values are copied +/// +/// usage: +/// +/// producer: +/// queue.push(.{.x = 4}); +/// +/// consumers: +/// while(alive) { +/// if(queue.tryTake())|value| +/// { +/// self.dowork(value); +/// } +/// else +/// { +/// chillout(); +/// } +/// } +/// +pub fn CommitQueue(comptime T: type) type { + return struct { + allocator: std.mem.Allocator, + state: std.atomic.Value(PackedState) = .init(.{}), + + active: std.ArrayList(T) = .empty, + back: std.ArrayList(T) = .empty, + + pub fn init(allocator: std.mem.Allocator) @This() { + return .{ .allocator = allocator }; + } + + pub fn deinit(self: *@This()) void { + while (!self.canSubmit()) std.atomic.spinLoopHint(); + + self.active.deinit(self.allocator); + self.back.deinit(self.allocator); + } + + /// Producer only. Grows the private backbuffer as needed. + pub fn push(self: *@This(), item: T) !void { + if (self.back.items.len == std.math.maxInt(u24)) return error.BatchFull; + try self.back.append(self.allocator, item); + } + + /// Consumers. Null means the batch is empty or all 255 reader pins are in use. + pub fn tryTake(self: *@This()) ?T { + var s = self.state.load(.monotonic); + + while (true) { + if (s.remaining_items == 0 or s.active_readers == std.math.maxInt(u8)) + return null; + + // Claim one entry and pin its batch atomically. + var desired = s; + desired.remaining_items -= 1; + desired.active_readers += 1; + + if (self.state.cmpxchgWeak(s, desired, .acquire, .monotonic)) |observed| { + s = observed; + continue; + } + + // Read metadata only after successfully pinning. + const index = self.active.items.len - @as(usize, s.remaining_items); + const item = self.active.items[index]; + + self.releaseReader(); + return item; + } + } + + /// Historical release loop, intentionally frozen for A/B measurement. + fn releaseReader(self: *@This()) void { + var s = self.state.load(.monotonic); + var bailOut: u32 = 100000000; + while (bailOut > 0) : (bailOut -= 1) { + var desired = s; + desired.active_readers -= 1; + if (self.state.cmpxchgWeak(s, desired, .release, .monotonic)) |observed| { + s = observed; + continue; + } + return; + } + } + + pub fn canSubmit(self: *const @This()) bool { + const state = self.state.load(.acquire); + return state.remaining_items == 0 and state.active_readers == 0; + } + + /// Must only be called Producer only. + /// publishes the backbuffer to all consumers, + pub fn submit(self: *@This()) void { + while (!self.canSubmit()) { + std.atomic.spinLoopHint(); + } + + std.mem.swap(@TypeOf(self.active), &self.active, &self.back); + + self.back.clearRetainingCapacity(); + self.state.store(.{ .remaining_items = @intCast(self.active.items.len) }, .release); + } + }; +} diff --git a/engine/p2/src/queue-benchmark.zig b/engine/p2/src/queue-benchmark.zig new file mode 100644 index 0000000..967b5e2 --- /dev/null +++ b/engine/p2/src/queue-benchmark.zig @@ -0,0 +1,203 @@ +//! One producer, N consumers. Run through `zig build bench-queues` in lib/p2. +const std = @import("std"); +const CommitQueue = @import("structures/spmc-submission-queue.zig").CommitQueue; +const ConcurrentQueue = @import("structures/concurrent-queue.zig").ConcurrentQueueU; +const CasCommitQueue = @import("queue-benchmark-cas-baseline.zig").CommitQueue; +const Kind = enum { commit, concurrent, commit_cas }; + +fn Bench(comptime kind: Kind, comptime wordCount: usize, comptime work: usize) type { + return struct { + const Item = struct { words: [wordCount]u64 }; + const Queue = switch (kind) { + .commit => CommitQueue(Item, .{ .ChunkSize = 256 }), + .commit_cas => CasCommitQueue(Item), + .concurrent => ConcurrentQueue(Item), + }; + const Worker = struct { + queue: *Queue, + gate: *std.Io.Event, + ready: *std.atomic.Value(usize), + producerDone: *std.atomic.Value(bool), + io: std.Io, + count: u64 align(64) = 0, + sum: u64 = 0, + xor: u64 = 0, + digest: u64 = 0, + bad: bool = false, + + fn run(self: *@This()) void { + _ = self.ready.fetchAdd(1, .release); + self.gate.waitUncancelable(self.io); + var output: [256]Item = undefined; + var draining = false; + while (true) { + const items: []const Item = if (kind == .commit) + self.queue.maybeTake(&output) + else blk: { + const item = if (kind == .commit_cas) self.queue.tryTake() else self.queue.pop(); + if (item) |value| { + output[0] = value; + break :blk output[0..1]; + } + break :blk &.{}; + }; + for (items) |item| { + const id = item.words[0]; + self.count += 1; + self.sum +%= id; + self.xor ^= id; + for (item.words[1..], 1..) |value, lane| { + if (value != id ^ @as(u64, @intCast(lane))) self.bad = true; + } + var result = id; + for (0..work) |_| result = (result ^ (result >> 13)) *% 0x9e3779b97f4a7c15; + self.digest +%= result; + } + if (items.len == 0) { + if (draining) return; + // After acquiring completion, recheck the queue before + // exiting: the first empty observation may predate publication. + draining = self.producerDone.load(.acquire); + std.atomic.spinLoopHint(); + } + } + } + }; + + fn makeItem(id: u64) Item { + var item: Item = undefined; + for (&item.words, 0..) |*value, lane| value.* = id ^ @as(u64, @intCast(lane)); + return item; + } + + fn flush(queue: *Queue) void { + if (kind != .concurrent) queue.submit(); + } + + fn measure(gpa: std.mem.Allocator, io: std.Io, consumers: usize, batch: usize, milliseconds: i64) !f64 { + const capacity = @max(batch, consumers); + var queue = if (kind != .concurrent) Queue.init(gpa) else try Queue.initCapacity(gpa, capacity * 2); + defer if (kind != .concurrent) queue.deinit() else queue.deinit(gpa); + if (kind != .concurrent) { + try queue.active.ensureTotalCapacity(gpa, capacity); + try queue.back.ensureTotalCapacity(gpa, capacity); + } + var gate: std.Io.Event = .unset; + var ready: std.atomic.Value(usize) = .init(0); + var producerDone: std.atomic.Value(bool) = .init(false); + var workers: [8]Worker = undefined; + var threads: [8]std.Thread = undefined; + var spawned: usize = 0; + // Even a partial spawn must release and shut down existing workers. + errdefer { + gate.set(io); + flush(&queue); + producerDone.store(true, .release); + for (threads[0..spawned]) |thread| thread.join(); + } + for (0..consumers) |i| { + workers[i] = .{ .queue = &queue, .gate = &gate, .ready = &ready, .producerDone = &producerDone, .io = io }; + threads[i] = try std.Thread.spawn(.{}, Worker.run, .{&workers[i]}); + spawned += 1; + } + while (ready.load(.acquire) != consumers) std.atomic.spinLoopHint(); + const begin = std.Io.Timestamp.now(io, .awake); + gate.set(io); + var produced: u64 = 0; + var expectedSum: u64 = 0; + var expectedXor: u64 = 0; + var batches: usize = 0; + while (true) { + for (0..batch) |_| { + try queue.push(makeItem(produced)); + expectedSum +%= produced; + expectedXor ^= produced; + produced += 1; + } + flush(&queue); + batches += 1; + // Amortize clock overhead for small batches; check every large batch + // so a 65K batch does not force millions of extra items per sample. + const clockInterval: usize = if (batch >= 10000) 1 else 64; + if (batches % clockInterval == 0 and begin.durationTo(std.Io.Timestamp.now(io, .awake)).toMilliseconds() >= milliseconds) break; + } + producerDone.store(true, .release); + for (threads[0..consumers]) |thread| thread.join(); + spawned = 0; + const elapsed = begin.durationTo(std.Io.Timestamp.now(io, .awake)).toNanoseconds(); + var count: u64 = 0; + var sum: u64 = 0; + var xor: u64 = 0; + for (workers[0..consumers]) |*worker| { + if (worker.bad) return error.CorruptPayload; + count += worker.count; + sum +%= worker.sum; + xor ^= worker.xor; + std.mem.doNotOptimizeAway(worker.digest); + } + if (count != produced or sum != expectedSum or xor != expectedXor) return error.IncorrectDelivery; + return @as(f64, @floatFromInt(count)) * 1000.0 / @as(f64, @floatFromInt(elapsed)); + } + }; +} + +fn scenario(comptime words: usize, comptime work: usize, init: std.process.Init, consumers: usize, batch: usize, sampleMs: i64, compareCas: bool) !void { + if (compareCas) return scenarioAgainst(words, work, .commit_cas, init, consumers, batch, sampleMs); + return scenarioAgainst(words, work, .concurrent, init, consumers, batch, sampleMs); +} + +fn scenarioAgainst(comptime words: usize, comptime work: usize, comptime other: Kind, init: std.process.Init, consumers: usize, batch: usize, sampleMs: i64) !void { + const S = Bench(.commit, words, work); + const C = Bench(other, words, work); + _ = try S.measure(init.gpa, init.io, consumers, batch, 100); + _ = try C.measure(init.gpa, init.io, consumers, batch, 100); + for (0..3) |sample| { + var s: f64 = undefined; + var c: f64 = undefined; + if (sample % 2 == 0) { + s = try S.measure(init.gpa, init.io, consumers, batch, sampleMs); + c = try C.measure(init.gpa, init.io, consumers, batch, sampleMs); + } else { + c = try C.measure(init.gpa, init.io, consumers, batch, sampleMs); + s = try S.measure(init.gpa, init.io, consumers, batch, sampleMs); + } + std.debug.print("{d},{d},{d},{d},{d},commit,{d:.6}\n", .{ consumers, batch, words * 8, work, sample, s }); + std.debug.print("{d},{d},{d},{d},{d},{s},{d:.6}\n", .{ consumers, batch, words * 8, work, sample, @tagName(other), c }); + } +} + +pub fn main(init: std.process.Init) !void { + var sampleMs: i64 = 400; + var minConsumers: usize = 1; + var largeBatches = false; + var compareCas = false; + const args = try init.minimal.args.toSlice(init.arena.allocator()); + for (args[1..]) |arg| { + if (std.mem.startsWith(u8, arg, "--sample-ms=")) { + sampleMs = try std.fmt.parseInt(i64, arg["--sample-ms=".len..], 10); + if (sampleMs < 1) return error.InvalidSampleDuration; + } else if (std.mem.startsWith(u8, arg, "--min-consumers=")) { + minConsumers = try std.fmt.parseInt(usize, arg["--min-consumers=".len..], 10); + if (minConsumers < 1 or minConsumers > 8) return error.InvalidConsumerCount; + } else if (std.mem.eql(u8, arg, "--large-batches")) { + largeBatches = true; + } else if (std.mem.eql(u8, arg, "--compare-cas")) { + compareCas = true; + } else return error.UnknownArgument; + } + std.debug.print("consumers,batch,payload_bytes,work_iterations,sample,queue,million_items_per_second\n", .{}); + for ([_]usize{ 1, 2, 4, 8 }) |consumers| { + if (consumers < minConsumers) continue; + if (largeBatches) { + for ([_]usize{ 10000, 65536 }) |batch| { + try scenario(2, 0, init, consumers, batch, sampleMs, compareCas); + try scenario(32, 0, init, consumers, batch, sampleMs, compareCas); + try scenario(2, 256, init, consumers, batch, sampleMs, compareCas); + } + } else { + for ([_]usize{ 1, 64, 1024 }) |batch| try scenario(2, 0, init, consumers, batch, sampleMs, compareCas); + try scenario(32, 0, init, consumers, 256, sampleMs, compareCas); + try scenario(2, 256, init, consumers, 256, sampleMs, compareCas); + } + } +} diff --git a/engine/p2/src/structures/bump-arena.zig b/engine/p2/src/structures/bump-arena.zig new file mode 100644 index 0000000..d4268ef --- /dev/null +++ b/engine/p2/src/structures/bump-arena.zig @@ -0,0 +1,161 @@ +const std = @import("std"); +const stats = @import("stats.zig"); +const paged_vector = @import("paged-vector.zig"); +const PagedVectorAdvanced = paged_vector.PagedVectorAdvanced; + +// mutex based, fast bump-only allocator +pub const BumpArena = struct { + const PageSize = 8192 * 2; + const SmallAllocPages = paged_vector.PagedVectorAdvanced([PageSize]u8, 1); + + smallBumpOffset: usize = 0, + pageIndex: usize = 0, + + allocatedBytes: usize = 0, + allocCount: usize = 0, + + backing: std.mem.Allocator, + io_context: std.Io, + small: SmallAllocPages, + large: std.heap.ArenaAllocator, + mutex: std.Io.Mutex, + + pub var vtable: std.mem.Allocator.VTable = .{ + .alloc = alloc, + .free = free, + .resize = resize, + .remap = std.mem.Allocator.noRemap, + }; + + pub fn usage(self: *@This()) usize { + return self.allocatedBytes; + } + + pub fn getStatistics(self: *@This()) stats.PoolStatistics { + return .{ + .statName = "BumpArena", + .instanceCount = self.allocCount, + .memoryReserved = self.small.pages.items.len * PageSize + + self.small.pages.capacity * @sizeOf(usize) + + self.large.queryCapacity(), + .memoryUsed = self.allocatedBytes, + }; + } + + pub fn init(backing: std.mem.Allocator, io_context: std.Io) !@This() { + return .{ + .backing = backing, + .io_context = io_context, + .small = try SmallAllocPages.init(backing), + .large = std.heap.ArenaAllocator.init(backing), + .mutex = .init, + }; + } + + pub fn io(self: *const @This()) std.Io { + return self.io_context; + } + + pub fn deinit(self: *@This()) void { + self.mutex.lockUncancelable(self.io()); + defer self.mutex.unlock(self.io()); + self.small.deinit(self.backing); + self.large.deinit(); + } + + fn respectAlignment(offset: usize, alignment: std.mem.Alignment) usize { + if (offset == 0) { + return 0; + } + const a: usize = @intCast(@as(usize, @intCast(1)) << @as(u6, @truncate(@intFromEnum(alignment)))); + return ((offset / a) + 1) * @as(usize, @intCast(a)); + } + + pub fn alloc(ctx: *anyopaque, len: usize, ptr_align: std.mem.Alignment, ret_addr: usize) ?[*]u8 { + const self: *@This() = @ptrCast(@alignCast(ctx)); + + self.mutex.lockUncancelable(self.io()); + defer self.mutex.unlock(self.io()); + + self.allocatedBytes += len; + self.allocCount += 1; + + if (len > 4096) { + return self.largeAllocator().vtable.alloc(self.largeAllocator().ptr, len, ptr_align, ret_addr); + } else { + const currentPageFree = PageSize - self.smallBumpOffset; + if (len < currentPageFree) { + const alignedOffset = respectAlignment(self.smallBumpOffset, ptr_align); + const rv = self.small.getMutable(self.pageIndex)[alignedOffset .. alignedOffset + len]; + // std.debug.print("original offset {d} respected offset {d} alignment {d} address: {x}\n", .{ self.smallBumpOffset, alignedOffset, ptr_align, @intFromPtr(rv.ptr) }); + self.smallBumpOffset = alignedOffset + len; + return rv.ptr; + } else { + // new allocation exceeds the remaining size of this page + self.pageIndex += 1; + self.smallBumpOffset = len; + self.small.append(self.backing, undefined) catch return null; + return self.small.getMutable(self.pageIndex)[0..len].ptr; + } + } + + unreachable; + } + + inline fn largeAllocator(self: *@This()) std.mem.Allocator { + return self.large.allocator(); + } + + pub fn free(ctx: *anyopaque, buf: []u8, buf_align: std.mem.Alignment, ret_addr: usize) void { + // it's a bump allocator, it does nothing on free. + _ = ctx; + _ = buf; + _ = buf_align; + _ = ret_addr; + } + + // do not support resize in place. + pub fn resize(ctx: *anyopaque, buf: []u8, buf_align: std.mem.Alignment, new_len: usize, ret_addr: usize) bool { + _ = ctx; + _ = buf; + _ = buf_align; + _ = new_len; + _ = ret_addr; + + return false; + } + + pub fn allocator(self: *@This()) std.mem.Allocator { + return .{ .ptr = self, .vtable = &vtable }; + } + + pub fn reset(self: *@This()) void { + self.mutex.lockUncancelable(self.io()); + defer self.mutex.unlock(self.io()); + + _ = self.large.reset(.free_all); + self.small.reset(self.backing); + self.smallBumpOffset = 0; + self.pageIndex = 0; + self.allocatedBytes = 0; + self.allocCount = 0; + } +}; + +test "bump-it-uppp" { + var arena = try BumpArena.init(std.testing.allocator, std.testing.io); + defer arena.deinit(); +} + +test "reset clears usage" { + var arena = try BumpArena.init(std.testing.allocator, std.testing.io); + defer arena.deinit(); + + const allocator = arena.allocator(); + const mem = allocator.alloc(u8, 128) catch unreachable; + defer _ = mem; + + try std.testing.expect(arena.usage() >= 128); + arena.reset(); + try std.testing.expectEqual(@as(usize, 0), arena.usage()); +} diff --git a/engine/p2/src/structures/concurrent-queue.zig b/engine/p2/src/structures/concurrent-queue.zig new file mode 100644 index 0000000..208c52a --- /dev/null +++ b/engine/p2/src/structures/concurrent-queue.zig @@ -0,0 +1,280 @@ +const std = @import("std"); +const utils = @import("utils.zig"); + +const ArrayList = std.ArrayList; +const ArrayListUnmanaged = std.ArrayListUnmanaged; + +const asserts = utils.asserts; + +const Atomic = std.atomic.Value; + +pub const ConcurrentQueueError = error{ + CorruptedState, + QueueIsEmpty, + QueueIsFull, +}; + +pub fn ConcurrentQueueU(comptime T: type) type { + return ConcurrentQueueUnmanagedAdvanced(T, .{}); +} + +pub fn ConcurrentQueueAssert(comptime T: type) type { + return ConcurrentQueueUnmanagedAdvanced(T, .{ .allowAsserts = true }); +} + +// lock-free concurrent queue, fixed capacity, +// will never resize. +// +// new version based on +// https://github.com/rigtorp/MPMCQueue + +pub const ConcurrentStatus = packed struct(usize) { + alive: bool = false, + generation: u63 = 0, +}; + +pub fn ConcurrentQueueUnmanagedAdvanced(comptime T: type, comptime opts: struct { + allowAsserts: bool = false, + debug: bool = false, +}) type { + return struct { + data: []align(64) T align(64), + status: []align(64) Atomic(ConcurrentStatus) align(64), // 1 = valid, 0 = invalid, + pushId: Atomic(usize) align(64), + popId: Atomic(usize) align(64), + + // tail points to next free slot + // head points to the next one to pop + pub fn initCapacity(allocator: std.mem.Allocator, cap: usize) !@This() { + const new = @This(){ + .data = try allocator.alignedAlloc(T, .@"64", cap), + .status = try allocator.alignedAlloc(Atomic(ConcurrentStatus), .@"64", cap), + .pushId = Atomic(usize).init(0), + .popId = Atomic(usize).init(0), + }; + + for (new.status) |*s| { + s.* = Atomic(ConcurrentStatus).init(std.mem.zeroes(ConcurrentStatus)); + } + + return new; + } + + pub fn push(self: *@This(), value: T) !void { + const pushId = self.pushId.fetchAdd(1, .acq_rel); + + const slot = @mod(pushId, self.data.len); + + const newStatus = ConcurrentStatus{ + .generation = @intCast(@divTrunc(pushId, self.data.len)), + .alive = true, + }; + + if (opts.debug) std.log.warn("pushing {d}", .{pushId}); + while (true) { + const status = self.status[slot].load(.acquire); + if (status.generation == newStatus.generation and status.alive == false) { + break; + } + std.atomic.spinLoopHint(); + } + + if (opts.debug) std.log.warn("pushed {d}", .{pushId}); + self.data[slot] = value; + self.status[slot].store(newStatus, .release); + } + + // pop the value from the queue, moves the head forward + pub fn pop(self: *@This()) ?T { // things are empty + const popId = blk: while (true) { + const popId = self.popId.load(.acquire); + const pushId = self.pushId.load(.acquire); + if (popId >= pushId) return null; + + if (self.popId.cmpxchgWeak(popId, popId + 1, .acq_rel, .acquire) == null) { + break :blk popId; + } + std.atomic.spinLoopHint(); + }; + + const slot = @mod(popId, self.data.len); + const expectedStatus = ConcurrentStatus{ + .generation = @intCast(@divTrunc(popId, self.data.len)), + .alive = true, + }; + + if (opts.debug) std.log.warn("popping {d}", .{popId}); + while (true) { + const status = self.status[slot].load(.acquire); + if (status.generation == expectedStatus.generation and status.alive) { + break; + } + std.atomic.spinLoopHint(); + } + if (opts.debug) std.log.warn("popped {d}", .{popId}); + + const value = self.data[slot]; + self.status[slot].store(.{ .alive = false, .generation = expectedStatus.generation +% 1 }, .release); + return value; + } + + pub fn count(self: @This()) usize { + const head = self.pushId.load(.acquire); + const tail = self.popId.load(.acquire); + + if (opts.debug) + std.log.warn("count {d}", .{head - tail}); + if (opts.allowAsserts) { + asserts(tail <= head, "tail > head in concurrent queue, this shouldnt ever happen", .{}, "concurrent queue assert"); + } + + return head - tail; + } + + pub fn capacity(self: @This()) usize { + return self.data.len; + } + + pub fn deinit(self: *@This(), allocator: std.mem.Allocator) void { + allocator.free(self.data); + allocator.free(self.status); + } + }; +} + +test "concurrent queue basic correctness test" { + const Info = struct { + x: u32 = 0, + }; + + const allocator = std.testing.allocator; + + var y = try ConcurrentQueueUnmanagedAdvanced(Info, .{ .allowAsserts = true, .debug = true }).initCapacity(allocator, 420); + defer y.deinit(allocator); + + try y.push(.{}); + try y.push(.{ .x = 1 }); + try y.push(.{ .x = 2 }); + try y.push(.{ .x = 1 }); + + try utils.assertf(y.count() == 4, "expected there to be {d} elements in queue, we saw {d}", .{ 4, y.count() }); + _ = y.pop(); + _ = y.pop(); + _ = y.pop(); + _ = y.pop(); + + try utils.assertf(y.count() == 0, "expected there to be {d} elements in queue, we saw {d}", .{ 0, y.count() }); + + var x = try ConcurrentQueueU(Info).initCapacity(allocator, 12); + defer x.deinit(allocator); + + try x.push(.{ .x = 0 }); + try x.push(.{ .x = 1 }); + try x.push(.{ .x = 2 }); + try x.push(.{ .x = 3 }); + + try x.push(.{ .x = 4 }); + try x.push(.{ .x = 5 }); + try x.push(.{ .x = 6 }); + try x.push(.{ .x = 7 }); + + try x.push(.{ .x = 8 }); + try x.push(.{ .x = 9 }); + try x.push(.{ .x = 10 }); + + // const maybeError = x.push(.{ .x = 11 }); + + // try utils.assertf(maybeError == ConcurrentQueueError.QueueIsFull, "Expected queue to have an error", .{}); +} + +test "concurrent queue multiple producer single consumer" { + // 1. create multiple threads + const threadCount = 24; + + const Payload = struct { + x: i64 = 0, + arb: [4096]u8 = undefined, + }; + + const QueueType = ConcurrentQueueUnmanagedAdvanced(Payload, .{ .debug = false, .allowAsserts = true }); + + const Wrap = struct { + pub fn threadFunc(queueRef: *QueueType, id: i64, exitSignal: *Atomic(bool), pushedCountResults: *Atomic(i64)) void { + var pushedCount: i64 = 0; + while (!exitSignal.load(.monotonic)) { + queueRef.push(.{ + .x = id + pushedCount, + }) catch unreachable; + pushedCount += 1; + } + + _ = pushedCountResults.fetchAdd(pushedCount, .seq_cst); + } + }; + + var threads: [threadCount]std.Thread = undefined; + + var testQueue = try QueueType.initCapacity(std.testing.allocator, 4096 * 4); + defer testQueue.deinit(std.testing.allocator); + + var exitSignalAtomic = Atomic(bool).init(false); + var pushedCountResults = Atomic(i64).init(0); + + for (0..threadCount) |i| { + threads[i] = try std.Thread.spawn(.{}, Wrap.threadFunc, .{ &testQueue, @as(i64, @intCast(i * 10000)), &exitSignalAtomic, &pushedCountResults }); + } + + // 5 second message pump test + var oldTime: f64 = test_getTime(std.testing.io); + + // 10 second test, 5 seconds of input, 5 seconds of drain + const startTime: f64 = 2.2; + var timeLeft: f64 = startTime; + + var poppedCount: i64 = 0; + + var signaled: bool = false; + + while (timeLeft > 0 or testQueue.count() > 0) { + const newTime = test_getTime(std.testing.io); + const deltaTime = newTime - oldTime; + + if (timeLeft - deltaTime < 0.0 and !signaled) { + signaled = true; + exitSignalAtomic.store(true, .seq_cst); + } + + timeLeft -= deltaTime; + oldTime = newTime; + if (testQueue.pop()) |x| { + _ = x; + poppedCount += 1; + } + std.atomic.spinLoopHint(); + } + + for (0..threadCount) |i| { + threads[i].join(); + } + + std.debug.print("popped {d} entries in {d} seconds payloadSize: {d} dataRate: {d:.3} MiB/s time/event {d:.3} us \n", .{ + poppedCount, + startTime, + @sizeOf(Payload), + @as(f64, @floatFromInt(@as(usize, @intCast(poppedCount)) * @sizeOf(Payload))) / startTime / 1024 / 1024, + startTime / @as(f64, @floatFromInt(@as(usize, @intCast(poppedCount)))) * 1000 * 1000, + }); + + try utils.assertf( + poppedCount == pushedCountResults.load(.seq_cst), + "mismatched, we popped {d} records while the workers pushed {d}", + .{ + poppedCount, + pushedCountResults.load(.seq_cst), + }, + ); +} + +fn test_getTime(io: std.Io) f64 { + return @as(f64, @floatFromInt(std.Io.Clock.awake.now(io).toMilliseconds())) / 1000; +} diff --git a/engine/p2/src/structures/counting-allocator.zig b/engine/p2/src/structures/counting-allocator.zig new file mode 100644 index 0000000..df8d84d --- /dev/null +++ b/engine/p2/src/structures/counting-allocator.zig @@ -0,0 +1,71 @@ +pub const std = @import("std"); + +pub const CountingAllocatorContext = struct { + wrappedAllocator: std.mem.Allocator = undefined, + alloc_count: usize = 0, + free_count: usize = 0, + alloc_bytes: usize = 0, + free_bytes: usize = 0, + memory_usage: usize = 0, + + const vtable: std.mem.Allocator.VTable = .{ + .alloc = alloc, + .resize = resize, + .remap = remap, + .free = free, + }; + + pub fn allocator(self: *@This(), wrappedAllocator: std.mem.Allocator) std.mem.Allocator { + self.wrappedAllocator = wrappedAllocator; + return .{ + .ptr = self, + .vtable = &vtable, + }; + } + + fn alloc(ctx: *anyopaque, len: usize, alignment: std.mem.Alignment, ret_addr: usize) ?[*]u8 { + const self: *@This() = @ptrCast(@alignCast(ctx)); + const ptr = self.wrappedAllocator.rawAlloc(len, alignment, ret_addr) orelse return null; + self.alloc_count += 1; + self.alloc_bytes += len; + self.memory_usage += len; + return ptr; + } + + fn resize(ctx: *anyopaque, memory: []u8, alignment: std.mem.Alignment, new_len: usize, ret_addr: usize) bool { + const self: *@This() = @ptrCast(@alignCast(ctx)); + if (!self.wrappedAllocator.rawResize(memory, alignment, new_len, ret_addr)) { + return false; + } + + self.recordResize(memory.len, new_len); + return true; + } + + fn remap(ctx: *anyopaque, memory: []u8, alignment: std.mem.Alignment, new_len: usize, ret_addr: usize) ?[*]u8 { + const self: *@This() = @ptrCast(@alignCast(ctx)); + const ptr = self.wrappedAllocator.rawRemap(memory, alignment, new_len, ret_addr) orelse return null; + self.recordResize(memory.len, new_len); + return ptr; + } + + fn free(ctx: *anyopaque, memory: []u8, alignment: std.mem.Alignment, ret_addr: usize) void { + const self: *@This() = @ptrCast(@alignCast(ctx)); + self.free_count += 1; + self.free_bytes += memory.len; + self.memory_usage -= @min(self.memory_usage, memory.len); + self.wrappedAllocator.rawFree(memory, alignment, ret_addr); + } + + fn recordResize(self: *@This(), old_len: usize, new_len: usize) void { + if (new_len > old_len) { + const delta = new_len - old_len; + self.alloc_bytes += delta; + self.memory_usage += delta; + } else if (old_len > new_len) { + const delta = old_len - new_len; + self.free_bytes += delta; + self.memory_usage -= @min(self.memory_usage, delta); + } + } +}; diff --git a/engine/p2/src/structures/index-pool.zig b/engine/p2/src/structures/index-pool.zig new file mode 100644 index 0000000..03edc13 --- /dev/null +++ b/engine/p2/src/structures/index-pool.zig @@ -0,0 +1,431 @@ +const std = @import("std"); +const stats = @import("stats.zig"); + +/// A compact weak handle for an IndexPool element type. +/// +/// The zero value is always invalid. `T` gives handles compile-time element +/// type safety. Handles do not encode runtime pool identity: the owner must not +/// use a handle with a different IndexPool instance of the same element type. +pub fn TypedHandle(comptime T: type) type { + return packed struct(u32) { + index: u18 = 0, + generation: u14 = 0, + + pub const _static = T; + + pub const invalid: @This() = .{}; + + pub fn eql(self: @This(), other: @This()) bool { + return self.index == other.index and + self.generation == other.generation; + } + + /// True when the handle is not the zero value. Handles minted by + /// IndexPool always carry a non-zero generation (fresh slots start at + /// 1 and reused slots keep their bumped generation), so the zero + /// value can never address a live element. + pub fn isValid(self: @This()) bool { + return @as(u32, @bitCast(self)) != 0; + } + + /// The raw encoding, suitable as a hash-map key. + pub fn hash(self: @This()) u32 { + return @bitCast(self); + } + + /// Implements the std.Io.Writer format interface so a handle can be + /// printed with `{f}` in format strings. + pub fn format(self: @This(), writer: *std.Io.Writer) std.Io.Writer.Error!void { + try writer.print("Handle({d},{d})", .{ self.index, self.generation }); + } + }; +} + +/// A dense value pool with weak, generation-checked handles. +/// +/// Values are stored densely and removed with swap-remove. Handles address a +/// separate slot table, so moving a dense value does not change its handle. +/// Pointers and slices returned by this type are invalidated by `new`, +/// `destroy`, `releaseAllFreeSlots`, or `deinit`. +/// +/// The pool owns its backing allocations but does not call cleanup methods on +/// `T`. `destroy` returns the removed value so its caller can release any +/// resources owned by that value. +/// +/// Handles belong to one pool instance. `releaseAllFreeSlots` is a full epoch +/// boundary: callers must discard every handle, including stale handles, +/// before calling it because the released generation history cannot be kept. +/// +/// This type is not thread-safe. +pub fn IndexPool(comptime T: type) type { + return struct { + const Self = @This(); + + pub const SlotIndex = u18; + pub const Generation = u14; + + const Slot = struct { + denseIndex: ?SlotIndex, + generation: Generation, + }; + + allocator: std.mem.Allocator, + dense: std.ArrayList(T) = .empty, + denseSlots: std.ArrayList(SlotIndex) = .empty, + slots: std.ArrayList(Slot) = .empty, + freeSlots: std.ArrayList(SlotIndex) = .empty, + + pub const Handle = TypedHandle(T); + pub const maxSlotCount: usize = @as(usize, std.math.maxInt(SlotIndex)) + 1; + + pub const CapacityError = std.mem.Allocator.Error || error{PoolFull}; + + pub fn init(allocator: std.mem.Allocator) Self { + return .{ + .allocator = allocator, + }; + } + + /// Initializes a pool with capacity for `capacity` live or free slots. + /// The free list is reserved alongside the other storage, ensuring + /// that `destroy` never allocates. + pub fn initCapacity(allocator: std.mem.Allocator, capacity: usize) CapacityError!Self { + var self = init(allocator); + errdefer self.deinit(); + try self.ensureTotalCapacity(capacity); + return self; + } + + /// Reserves all dense, slot, and free-list storage. + pub fn ensureTotalCapacity(self: *Self, capacity: usize) CapacityError!void { + if (capacity > maxSlotCount) return error.PoolFull; + + try self.dense.ensureTotalCapacity(self.allocator, capacity); + try self.denseSlots.ensureTotalCapacity(self.allocator, capacity); + try self.slots.ensureTotalCapacity(self.allocator, capacity); + try self.freeSlots.ensureTotalCapacity(self.allocator, capacity); + } + + /// Returns a handle for a physical slot index when that slot is live. + pub fn indexToHandle(self: *const Self, index: usize) ?Handle { + if (index >= self.slots.items.len) return null; + + const slot = self.slots.items[index]; + if (slot.denseIndex == null) return null; + + return .{ + .index = @intCast(index), + .generation = slot.generation, + }; + } + + /// Returns the handle associated with a dense iteration index. + pub fn handleAtDenseIndex(self: *const Self, denseIndex: usize) ?Handle { + if (denseIndex >= self.denseSlots.items.len) return null; + return self.indexToHandle(self.denseSlots.items[denseIndex]); + } + + /// Number of live values. + pub fn count(self: *const Self) usize { + return self.dense.items.len; + } + + /// Number of allocated handle slots, including free and retired slots. + pub fn slotCount(self: *const Self) usize { + return self.slots.items.len; + } + + /// Number of slots available for immediate allocation-free reuse. + pub fn freeCount(self: *const Self) usize { + return self.freeSlots.items.len; + } + + pub fn getStatistics(self: *const Self) stats.PoolStatistics { + return .{ + .statName = "IndexPool", + .instanceCount = self.count(), + .memoryReserved = self.dense.capacity * @sizeOf(T) + + self.denseSlots.capacity * @sizeOf(SlotIndex) + + self.slots.capacity * @sizeOf(Slot) + + self.freeSlots.capacity * @sizeOf(SlotIndex), + .memoryUsed = self.dense.items.len * @sizeOf(T) + + self.denseSlots.items.len * @sizeOf(SlotIndex) + + self.slots.items.len * @sizeOf(Slot) + + self.freeSlots.items.len * @sizeOf(SlotIndex), + }; + } + + /// Dense read-only iteration. Invalidated by any mutating pool method. + pub fn items(self: *const Self) []const T { + return self.dense.items; + } + + /// Dense mutable iteration. Invalidated by any other mutating pool method. + pub fn itemsMut(self: *Self) []T { + return self.dense.items; + } + + pub fn new(self: *Self, initVal: T) CapacityError!Handle { + if (self.freeSlots.items.len != 0) { + const slotIndex = self.freeSlots.pop().?; + const denseIndex: SlotIndex = @intCast(self.dense.items.len); + const slot = &self.slots.items[slotIndex]; + + std.debug.assert(slot.denseIndex == null); + std.debug.assert(slot.generation != 0); + std.debug.assert(self.dense.items.len < self.dense.capacity); + std.debug.assert(self.denseSlots.items.len < self.denseSlots.capacity); + + self.dense.appendAssumeCapacity(initVal); + self.denseSlots.appendAssumeCapacity(slotIndex); + slot.denseIndex = denseIndex; + + return .{ + .index = slotIndex, + .generation = slot.generation, + }; + } + + if (self.slots.items.len == maxSlotCount) return error.PoolFull; + + const newSlotCount = self.slots.items.len + 1; + try self.ensureTotalCapacity(newSlotCount); + + const slotIndex: SlotIndex = @intCast(self.slots.items.len); + const denseIndex: SlotIndex = @intCast(self.dense.items.len); + const initialGeneration: Generation = 1; + + self.dense.appendAssumeCapacity(initVal); + self.denseSlots.appendAssumeCapacity(slotIndex); + self.slots.appendAssumeCapacity(.{ + .denseIndex = denseIndex, + .generation = initialGeneration, + }); + + return .{ + .index = slotIndex, + .generation = initialGeneration, + }; + } + + pub fn isValid(self: *const Self, handle: Handle) bool { + if (handle.generation == 0) return false; + if (handle.index >= self.slots.items.len) return false; + + const slot = self.slots.items[handle.index]; + return slot.denseIndex != null and slot.generation == handle.generation; + } + + pub fn get(self: *Self, handle: Handle) ?*T { + if (!self.isValid(handle)) return null; + const denseIndex = self.slots.items[handle.index].denseIndex.?; + return &self.dense.items[denseIndex]; + } + + pub fn getRead(self: *const Self, handle: Handle) ?*const T { + if (!self.isValid(handle)) return null; + const denseIndex = self.slots.items[handle.index].denseIndex.?; + return &self.dense.items[denseIndex]; + } + + /// Removes a live value and returns it to the caller. + /// + /// Invalid, stale, and duplicate handles return null without changing + /// the pool. Removal is allocation-free because free-list capacity is + /// reserved whenever slot capacity grows. + pub fn destroy(self: *Self, handle: Handle) ?T { + if (!self.isValid(handle)) return null; + + const slot = &self.slots.items[handle.index]; + const denseIndex = slot.denseIndex.?; + const removedValue = self.dense.swapRemove(denseIndex); + const removedSlot = self.denseSlots.swapRemove(denseIndex); + std.debug.assert(removedSlot == handle.index); + + if (denseIndex < self.dense.items.len) { + const movedSlot = self.denseSlots.items[denseIndex]; + self.slots.items[movedSlot].denseIndex = denseIndex; + } + + slot.denseIndex = null; + if (slot.generation == std.math.maxInt(Generation)) { + // Retire this slot permanently rather than wrapping and making + // an old handle valid again. + } else { + slot.generation += 1; + std.debug.assert(self.freeSlots.items.len < self.freeSlots.capacity); + self.freeSlots.appendAssumeCapacity(handle.index); + } + + return removedValue; + } + + /// Fully releases pool storage when there are no live values. + /// + /// This is a full epoch boundary. Every handle associated with this + /// pool must be discarded before calling it; rebuilding the pool can + /// reuse the same index and generation values. Returns false when + /// values are still live or there is no allocation to release. + pub fn releaseAllFreeSlots(self: *Self) bool { + if (self.dense.items.len != 0) return false; + + const hadStorage = self.dense.capacity != 0 or + self.denseSlots.capacity != 0 or + self.slots.capacity != 0 or + self.freeSlots.capacity != 0; + if (!hadStorage) return false; + + self.dense.clearAndFree(self.allocator); + self.denseSlots.clearAndFree(self.allocator); + self.slots.clearAndFree(self.allocator); + self.freeSlots.clearAndFree(self.allocator); + return true; + } + + pub fn deinit(self: *Self) void { + self.dense.deinit(self.allocator); + self.denseSlots.deinit(self.allocator); + self.slots.deinit(self.allocator); + self.freeSlots.deinit(self.allocator); + self.* = undefined; + } + }; +} + +const TestValue = struct { + id: u32, +}; +const TestPool = IndexPool(TestValue); + +test "index pool handles are typed and zero-invalid" { + try std.testing.expect(TypedHandle(u32) != TypedHandle(u64)); + try std.testing.expectEqual(@as(usize, 4), @sizeOf(TestPool.Handle)); + try std.testing.expectEqual(@as(usize, 1) << 18, TestPool.maxSlotCount); + + var pool = TestPool.init(std.testing.allocator); + defer pool.deinit(); + + try std.testing.expect(!pool.isValid(.{})); + + const handle = try pool.new(.{ .id = 42 }); + try std.testing.expect(handle.generation != 0); + try std.testing.expect(pool.isValid(handle)); + try std.testing.expectEqual(@as(u32, 42), pool.get(handle).?.id); +} + +test "index pool rejects stale and duplicate destruction" { + var first = TestPool.init(std.testing.allocator); + defer first.deinit(); + + const original = try first.new(.{ .id = 1 }); + const removed = first.destroy(original).?; + try std.testing.expectEqual(@as(u32, 1), removed.id); + try std.testing.expect(!first.isValid(original)); + try std.testing.expect(first.destroy(original) == null); + + const replacement = try first.new(.{ .id = 2 }); + try std.testing.expectEqual(original.index, replacement.index); + try std.testing.expect(original.generation != replacement.generation); + try std.testing.expect(first.destroy(original) == null); + try std.testing.expectEqual(@as(u32, 2), first.get(replacement).?.id); +} + +test "index pool keeps values dense while handles remain stable" { + var pool = TestPool.init(std.testing.allocator); + defer pool.deinit(); + + const first = try pool.new(.{ .id = 1 }); + const middle = try pool.new(.{ .id = 2 }); + const last = try pool.new(.{ .id = 3 }); + + _ = pool.destroy(middle).?; + + try std.testing.expectEqual(@as(usize, 2), pool.count()); + try std.testing.expectEqualSlices(TestValue, &.{ .{ .id = 1 }, .{ .id = 3 } }, pool.items()); + try std.testing.expectEqual(@as(u32, 1), pool.get(first).?.id); + try std.testing.expectEqual(@as(u32, 3), pool.get(last).?.id); + try std.testing.expect(pool.indexToHandle(middle.index) == null); + try std.testing.expect(pool.indexToHandle(last.index).?.eql(last)); + try std.testing.expect(pool.handleAtDenseIndex(1).?.eql(last)); +} + +test "index pool retires slots instead of wrapping generations" { + var pool = TestPool.init(std.testing.allocator); + defer pool.deinit(); + + var handle = try pool.new(.{ .id = 1 }); + var expectedGeneration: u32 = 1; + while (expectedGeneration < std.math.maxInt(TestPool.Generation)) : (expectedGeneration += 1) { + _ = pool.destroy(handle).?; + handle = try pool.new(.{ .id = 1 }); + try std.testing.expectEqual(@as(TestPool.Generation, @intCast(expectedGeneration + 1)), handle.generation); + try std.testing.expectEqual(@as(TestPool.SlotIndex, 0), handle.index); + } + + const retiredHandle = handle; + _ = pool.destroy(retiredHandle).?; + try std.testing.expectEqual(@as(usize, 0), pool.freeCount()); + + const next = try pool.new(.{ .id = 2 }); + try std.testing.expectEqual(@as(TestPool.SlotIndex, 1), next.index); + try std.testing.expect(!pool.isValid(retiredHandle)); +} + +test "index pool reserves its free list and can release an empty pool" { + var allocatorState = std.testing.FailingAllocator.init(std.testing.allocator, .{}); + var pool = try TestPool.initCapacity(allocatorState.allocator(), 8); + defer pool.deinit(); + + try std.testing.expect(pool.dense.capacity >= 8); + try std.testing.expect(pool.denseSlots.capacity >= 8); + try std.testing.expect(pool.slots.capacity >= 8); + try std.testing.expect(pool.freeSlots.capacity >= 8); + + const allocationsAfterReserve = allocatorState.allocations; + var handles: [8]TestPool.Handle = undefined; + for (&handles, 0..) |*handle, i| { + handle.* = try pool.new(.{ .id = @intCast(i) }); + } + try std.testing.expect(!pool.releaseAllFreeSlots()); + + for (handles) |handle| { + _ = pool.destroy(handle).?; + } + + try std.testing.expectEqual(allocationsAfterReserve, allocatorState.allocations); + try std.testing.expectEqual(@as(usize, 0), pool.count()); + try std.testing.expectEqual(pool.slotCount(), pool.freeCount()); + + try std.testing.expect(pool.releaseAllFreeSlots()); + try std.testing.expectEqual(@as(usize, 0), pool.dense.capacity); + try std.testing.expectEqual(@as(usize, 0), pool.denseSlots.capacity); + try std.testing.expectEqual(@as(usize, 0), pool.slots.capacity); + try std.testing.expectEqual(@as(usize, 0), pool.freeSlots.capacity); + const rebuilt = try pool.new(.{ .id = 99 }); + try std.testing.expectEqual(@as(TestPool.SlotIndex, 0), rebuilt.index); + try std.testing.expectEqual(@as(TestPool.Generation, 1), rebuilt.generation); +} + +test "index pool reports growth allocation failures" { + for (0..4) |failIndex| { + var failingState = std.testing.FailingAllocator.init(std.testing.allocator, .{ + .fail_index = failIndex, + }); + var pool = TestPool.init(failingState.allocator()); + defer pool.deinit(); + + try std.testing.expectError(error.OutOfMemory, pool.new(.{ .id = 1 })); + try std.testing.expectEqual(@as(usize, 0), pool.count()); + try std.testing.expectEqual(@as(usize, 0), pool.slotCount()); + try std.testing.expectEqual(@as(usize, 0), pool.freeCount()); + } +} + +test "index pool rejects capacity beyond its handle index range" { + var pool = TestPool.init(std.testing.allocator); + defer pool.deinit(); + + try std.testing.expectError(error.PoolFull, pool.ensureTotalCapacity(TestPool.maxSlotCount + 1)); + try std.testing.expectEqual(@as(usize, 0), pool.count()); + try std.testing.expectEqual(@as(usize, 0), pool.slotCount()); +} diff --git a/engine/p2/src/structures/int-mapper.zig b/engine/p2/src/structures/int-mapper.zig new file mode 100644 index 0000000..fe489ee --- /dev/null +++ b/engine/p2/src/structures/int-mapper.zig @@ -0,0 +1,14 @@ +const std = @import("std"); + +// TODO: +// +// This one is not quite finished yet. +// +// The idea for this one is to efficently map one +// arbitrary set of integers to another set of integers. +pub fn IntMapperUnmanaged(comptime IntType: type) type { + return struct { + capacity: usize, + smallMap: []IntType, + }; +} diff --git a/engine/p2/src/structures/interface.zig b/engine/p2/src/structures/interface.zig new file mode 100644 index 0000000..bd0005e --- /dev/null +++ b/engine/p2/src/structures/interface.zig @@ -0,0 +1,136 @@ +pub fn MakeInterface(comptime vtable_declname: []const u8, comptime VTableType: type) type { + return struct { + pub const VTableDeclName = vtable_declname; + pub const VTable = VTableType; + + pub fn Implement(comptime T: type) VTableType { + return VTableType.Implement(T); + } + }; +} + +pub fn Reference(comptime Interface: type) type { + return struct { + ptr: *anyopaque, + vtable: Interface.VTable, + }; +} + +pub inline fn refFromPtr(comptime Interface: type, ptr: anytype) Reference(Interface) { + return .{ + .ptr = @ptrCast(ptr), + .vtable = @field(@TypeOf(ptr.*), Interface.VTableDeclName), + }; +} + +test "simple" { + const std = @import("std"); + + const TestOtherInterface = MakeInterface("TestOtherInterfaceVTable", struct { + testOtherfn: *const fn (*anyopaque, f64, f64) f64, + + pub fn Implement(comptime T: type) @This() { + const Wrap = struct { + pub fn testOtherfn(p: *anyopaque, a: f64, b: f64) f64 { + const ptr: *T = @ptrCast(@alignCast(p)); + return ptr.testOtherfn(a, b); + } + }; + + inline for (@typeInfo(Wrap).@"struct".decls) |d| { + if (!@hasDecl(T, d.name)) { + @compileError(@typeName(T) ++ " is missing implementation of func " ++ d.name); + } + } + + return .{ + .testOtherfn = Wrap.testOtherfn, + }; + } + }); + + const TestInterface = MakeInterface("TestInterfaceVTable", struct { + testfn1: *const fn (*anyopaque, f64, f64) f64, + testfn2: *const fn (*anyopaque, []const u8) void, + + pub fn Implement(comptime T: type) @This() { + const Wrap = struct { + pub fn testfn1(p: *anyopaque, a: f64, b: f64) f64 { + const ptr: *T = @ptrCast(@alignCast(p)); + return ptr.testfn1(a, b); + } + pub fn testfn2(p: *anyopaque, msg: []const u8) void { + const ptr: *T = @ptrCast(@alignCast(p)); + ptr.testfn2(msg); + } + }; + + inline for (@typeInfo(Wrap).@"struct".decls) |d| { + if (!@hasDecl(T, d.name)) { + @compileError(@typeName(T) ++ " is missing implementation of func " ++ d.name); + } + } + + return .{ + .testfn1 = Wrap.testfn1, + .testfn2 = Wrap.testfn2, + }; + } + }); + + const Test1 = struct { + name: []const u8, + + pub const TestInterfaceVTable = TestInterface.Implement(@This()); + pub const TestOtherInterfaceVTable = TestOtherInterface.Implement(@This()); + + // gathered into TestInterfaceVTable + pub fn testfn1(self: *@This(), a: f64, b: f64) f64 { + std.debug.print("{s}: a + b == {d}\n", .{ self.name, a + b }); + return a + b; + } + + // gathered into TestInterfaceVTable + pub fn testfn2(self: *@This(), msg: []const u8) void { + std.debug.print("{s}: msg: {s}\n", .{ self.name, msg }); + } + + // gathered into TestOtherInterfaceVTable + pub fn testOtherfn(self: *@This(), a: f64, b: f64) f64 { + _ = self; + std.debug.print(">: a - b == {d}\n", .{a - b}); + return a - b; + } + }; + + const Test2 = struct { + name: []const u8, + + pub const TestInterfaceVTable = TestInterface.VTable.Implement(@This()); + + pub fn testfn1(self: *@This(), a: f64, b: f64) f64 { + std.debug.print("2>{s}: a * b == {d}\n", .{ self.name, a * b }); + return a * b; + } + + pub fn testfn2(self: *@This(), msg: []const u8) void { + std.debug.print("2>{s}: msg: {s}\n", .{ self.name, msg }); + } + }; + + var t1 = Test1{ .name = "test1" }; + var t2 = Test2{ .name = "test2" }; + + const refs = [_]Reference(TestInterface){ + refFromPtr(TestInterface, &t1), + refFromPtr(TestInterface, &t2), + }; + std.debug.print("\n", .{}); + + for (refs) |r| { + _ = r.vtable.testfn1(r.ptr, 12.0, 24.0); + } + + const ref = refFromPtr(TestOtherInterface, &t1); + _ = ref.vtable.testOtherfn(ref.ptr, 12.0, 42.0); +} diff --git a/engine/p2/src/structures/math.zig b/engine/p2/src/structures/math.zig new file mode 100644 index 0000000..4491b09 --- /dev/null +++ b/engine/p2/src/structures/math.zig @@ -0,0 +1,688 @@ +const std = @import("std"); +pub const zm = @import("zmath.zig"); +const math = std.math; + +// vector versions. +pub const f32x4 = @Vector(4, f32); // __m128_int +pub const f32x8 = @Vector(8, f32); // __m256_int +pub const f32x16 = @Vector(16, f32); // __m512_int + +pub const f32x4_zero = std.mem.zeroes(@Vector(4, f32)); +pub const f32x8_zero = std.mem.zeroes(@Vector(8, f32)); +pub const f32x16_zero = std.mem.zeroes(@Vector(16, f32)); + +pub const Rayf = RayType(Vectorf); + +pub const PlaneBasisf = struct { + u_axis: Vectorf, + v_axis: Vectorf, +}; + +// creates a translation matrix 4x4 +pub const identity = zm.identity; + +pub fn matToScalef(mat: anytype) Vectorf { + const x = Vectorf.new(mat[0][0], mat[0][1], mat[0][2]).length(); + const y = Vectorf.new(mat[1][0], mat[1][1], mat[1][2]).length(); + const z = Vectorf.new(mat[2][0], mat[2][1], mat[2][2]).length(); + + return Vectorf.new(x, y, z); +} + +/// Builds a stable orthonormal basis for the plane described by `normal`. +pub fn planeBasisFromNormal(normal: Vectorf) PlaneBasisf { + const n = if (normal.length() > 0.0001) normal.normalize() else Vectorf.Forward; + const reference = if (@abs(n.dot(Vectorf.Up)) < 0.94) Vectorf.Up else Vectorf.Right; + var u_axis = reference.cross(n); + if (u_axis.length() <= 0.0001) u_axis = Vectorf.Right; + u_axis = u_axis.normalize(); + var v_axis = n.cross(u_axis); + if (v_axis.length() <= 0.0001) v_axis = Vectorf.Up; + v_axis = v_axis.normalize(); + return .{ + .u_axis = u_axis, + .v_axis = v_axis, + }; +} + +/// Returns the component of `vector` perpendicular to a normalized axis. +pub fn vectorRejectNormalized(vector: Vectorf, axis_normalized: Vectorf) Vectorf { + return vector.sub(axis_normalized.fmul(vector.dot(axis_normalized))); +} + +pub fn RayType(comptime T: type) type { + return struct { + start: T, + dir: T, + }; +} + +pub fn clamp(x: anytype, min: anytype, max: anytype) @TypeOf(x) { + if (x < min) + return min; + if (x > max) + return max; + return x; +} + +pub fn matFromEulerAngles(x: f32, y: f32, z: f32) Mat { + return zm.matFromRollPitchYaw(y, z, x); +} + +pub fn Radians(comptime T: type) type { + return struct { + value: T, + + pub fn fromDegrees(f: anytype) @This() { + return .{ .value = f }; + } + }; +} + +pub fn radians(f: anytype) @TypeOf(f) { + return f * math.pi / 180.0; +} + +pub fn fabs(x: anytype) @TypeOf(x) { + if (x < 0) + return -x; + return x; +} + +pub fn Vector2Type(comptime T: type, comptime typeName: []const u8) type { + return extern struct { + x: T = 0, + y: T = 0, + + pub const VectorTypeName = typeName; + + pub const ones = @This(){ .x = 1, .y = 1 }; + pub const zeroes = @This(){ .x = 0, .y = 0 }; + + pub const Ones = @This(){ .x = 1, .y = 1 }; + pub const Zeroes = @This(){ .x = 0, .y = 0 }; + + pub inline fn new(x: T, y: T) @This() { + return .{ + .x = x, + .y = y, + }; + } + + pub inline fn add(self: @This(), other: @This()) @This() { + return .{ + .x = self.x + other.x, + .y = self.y + other.y, + }; + } + + pub inline fn sub(self: @This(), other: @This()) @This() { + return .{ + .x = self.x - other.x, + .y = self.y - other.y, + }; + } + + pub inline fn vmul(self: @This(), other: @This()) @This() { + return .{ + .x = self.x * other.x, + .y = self.y * other.y, + }; + } + + pub inline fn divFloor(self: @This(), other: T) @This() { + return .{ + .x = @divFloor(self.x, other), + .y = @divFloor(self.y, other), + }; + } + + pub inline fn fmul(self: @This(), other: T) @This() { + return .{ + .x = self.x * other, + .y = self.y * other, + }; + } + + pub inline fn dot(self: @This(), other: @This()) T { + return self.x * other.x + self.y * other.y; + } + + pub inline fn equals(self: @This(), other: @This()) bool { + return self.x == other.x and self.y == other.y; + } + + pub inline fn length(self: @This()) T { + return std.math.sqrt(self.x * self.x + self.y * self.y); + } + + pub inline fn swizzleYX(self: @This()) @This() { + return .{ .x = self.y, .y = self.x }; + } + + pub inline fn normalize(self: @This()) @This() { + if (fabs(self.x) <= 0.0001 and fabs(self.y) <= 0.0001) { + return .{ .x = 0, .y = 0 }; + } + const len = std.math.sqrt(self.x * self.x + self.y * self.y); + + if (len < 0.00001) + return .{ .x = 0, .y = 0 }; + + return .{ + .x = self.x / len, + .y = self.y / len, + }; + } + + pub inline fn negate(self: @This()) @This() { + return .{ .x = -self.x, .y = self.y }; + } + + pub inline fn cross(self: @This(), other: @This()) T { + return self.x * other.y - self.y * other.x; + } + + pub inline fn removeComponent(self: @This(), other: @This()) @This() { + return self.sub(other.fmul(self.dot(other))); + } + + pub inline fn from(o: anytype) @This() { + const OType: std.builtin.Type = @typeInfo(@TypeOf(o.x)); + switch (@typeInfo(T)) { + .int => { + switch (OType) { + .int => { + // convert integer into integer + return .{ + .x = @intCast(o.x), + .y = @intCast(o.y), + }; + }, + .float => { + // convert float into float + return .{ + .x = @intFromFloat(o.x), + .y = @intFromFloat(o.y), + }; + }, + else => { + @compileError("Invalid vector type conversion"); + }, + } + }, + .float => { + switch (OType) { + .int => { + // convert integer into float + return .{ + .x = @floatFromInt(o.x), + .y = @floatFromInt(o.y), + }; + }, + .float => { + // convert float + return .{ + .x = @floatCast(o.x), + .y = @floatCast(o.y), + }; + }, + else => { + // convert float into float + @compileError("Invalid vector type conversion"); + }, + } + }, + else => { + @compileError("Invalid vector type conversion"); + }, + } + @compileError("Invalid vector conversion"); + } + }; +} + +pub fn Vector3Type(comptime T: type, comptime typeName: []const u8) type { + return extern struct { + x: T = 0, + y: T = 0, + z: T = 0, + + pub const VectorTypeName = typeName; + + pub const ones = @This(){ .x = 1.0, .y = 1.0, .z = 1.0 }; + pub const zeroes = @This(){ .x = 0, .y = 0, .z = 0.0 }; + + pub const Ones = @This(){ .x = 1, .y = 1, .z = 1 }; + pub const Zeroes = @This(){ .x = 0, .y = 0, .z = 0 }; + + pub const Up = @This(){ .y = 1 }; + pub const Right = @This(){ .x = 1 }; + pub const Forward = @This(){ .z = 1 }; + + pub inline fn new(x: T, y: T, z: T) @This() { + return .{ + .x = x, + .y = y, + .z = z, + }; + } + + pub inline fn fromInt(t: anytype) @This() { + return .{ .x = t, .y = t, .z = t }; + } + + pub inline fn splat(t: anytype) @This() { + return .{ .x = t, .y = t, .z = t }; + } + + // easing functions + pub inline fn drainToZero(self: @This(), o: anytype) @This() { + return self.drain(o, Zeroes); + } + + pub inline fn drain(self: @This(), o: anytype, target: anytype) @This() { + return .{ + .x = drainElement(self.x, o.x, target.x), + .y = drainElement(self.y, o.y, target.y), + .z = drainElement(self.z, o.z, target.z), + }; + } + + inline fn drainElement(a: anytype, v: anytype, t: anytype) @TypeOf(a) { + if (a > t) { + return @max(t, a - v); + } else { + return @min(t, a + v); + } + } + + // array functions. + pub inline fn toArr3(self: @This()) [3]T { + return .{ self.x, self.y, self.z }; + } + + pub inline fn fromArr3(v: [3]f32) @This() { + return .{ .x = v[0], .y = v[1], .z = v[2] }; + } + + pub inline fn toZm(self: @This()) zm.Vec { + return .{ self.x, self.y, self.z, 1.0 }; + } + + pub inline fn fromZm(vec: zm.Vec) @This() { + return @This().new(vec[0], vec[1], vec[2]); + } + + pub inline fn add(self: @This(), other: @This()) @This() { + return .{ + .x = self.x + other.x, + .y = self.y + other.y, + .z = self.z + other.z, + }; + } + + pub inline fn sub(self: @This(), other: @This()) @This() { + return .{ + .x = self.x - other.x, + .y = self.y - other.y, + .z = self.z - other.z, + }; + } + + pub inline fn vmul(self: @This(), other: @This()) @This() { + return .{ + .x = self.x * other.x, + .y = self.y * other.y, + .z = self.z * other.z, + }; + } + + pub inline fn fmul(self: @This(), other: T) @This() { + return .{ + .x = self.x * other, + .y = self.y * other, + .z = self.z * other, + }; + } + + pub inline fn dot(self: @This(), other: @This()) T { + return self.x * other.x + self.y * other.y + self.z * other.z; + } + + pub inline fn equals(self: @This(), other: @This()) bool { + return self.x == other.x and self.y == self.y and self.z == self.z; + } + + pub inline fn eql(self: @This(), other: @This()) bool { + return self.x == other.x and self.y == self.y and self.z == self.z; + } + + pub inline fn length(self: @This()) T { + return std.math.sqrt(self.x * self.x + self.z * self.z + self.y * self.y); + } + + pub inline fn swizzleYZX(self: @This()) @This() { + return .{ .x = self.y, .y = self.z, .z = self.x }; + } + + pub inline fn swizzleYXZ(self: @This()) @This() { + return .{ .x = self.y, .y = self.x, .z = self.z }; + } + + pub inline fn swizzleZXY(self: @This()) @This() { + return .{ .x = self.z, .y = self.x, .z = self.y }; + } + + pub inline fn swizzleZYX(self: @This()) @This() { + return .{ .x = self.z, .y = self.y, .z = self.x }; + } + + pub inline fn swizzleXZY(self: @This()) @This() { + return .{ .x = self.x, .y = self.z, .z = self.y }; + } + + pub inline fn lengthXZ(self: @This()) T { + return std.math.sqrt(self.x * self.x + self.z * self.z); + } + + pub inline fn normalize(self: @This()) @This() { + if (fabs(self.x) <= 0.0001 and fabs(self.y) <= 0.0001 and fabs(self.z) <= 0.0001) { + return .{ .x = 0, .y = 0, .z = 0 }; + } + const len = std.math.sqrt(self.x * self.x + self.y * self.y + self.z * self.z); + + if (len < 0.00001) + return .{ .x = 0, .y = 0, .z = 0 }; + + return .{ + .x = self.x / len, + .y = self.y / len, + .z = self.z / len, + }; + } + + pub inline fn fromArray(o: anytype) @This() { + return .{ + .x = o[0], + .y = o[1], + .z = o[2], + }; + } + + pub inline fn clampAllAbs(self: @This(), abs: anytype) @This() { + return .{ + .x = std.math.clamp(self.x, -abs, abs), + .y = std.math.clamp(self.y, -abs, abs), + .z = std.math.clamp(self.z, -abs, abs), + }; + } + + pub inline fn cross(self: @This(), other: @This()) @This() { + return .{ + .x = self.y * other.z - self.z * other.y, + .y = self.z * other.x - self.x * other.z, + .z = self.x * other.y - self.y * other.x, + }; + } + + pub fn lerp(self: @This(), other: @This(), alpha: anytype) @This() { + return .{ + .x = std.math.lerp(self.x, other.x, alpha), + .y = std.math.lerp(self.y, other.y, alpha), + .z = std.math.lerp(self.z, other.z, alpha), + }; + } + + pub inline fn clampAll(self: @This(), lower: anytype, upper: anytype) @This() { + return .{ + .x = std.math.clamp(self.x, -lower, upper), + .y = std.math.clamp(self.y, -lower, upper), + .z = std.math.clamp(self.z, -lower, upper), + }; + } + + pub inline fn from(o: anytype) @This() { + const OType = @typeInfo(@TypeOf(o.x)); + switch (@typeInfo(T)) { + .int => { + switch (OType) { + .int => { + // convert integer into integer + return .{ + .x = @intCast(o.x), + .y = @intCast(o.y), + .z = @intCast(o.z), + }; + }, + .float => { + // convert float into float + return .{ + .x = @intFromFloat(o.x), + .y = @intFromFloat(o.y), + .z = @intFromFloat(o.z), + }; + }, + else => { + @compileError("Invalid vector type conversion"); + }, + } + }, + .float => { + switch (OType) { + .int, .comptime_int => { + // convert integer into float + return .{ + .x = @floatFromInt(o.x), + .y = @floatFromInt(o.y), + .z = @floatFromInt(o.z), + }; + }, + .float, .comptime_float => { + // convert float + return .{ + .x = @floatCast(o.x), + .y = @floatCast(o.y), + .z = @floatCast(o.z), + }; + }, + else => { + // convert float into float + @compileError("Invalid vector type conversion"); + }, + } + }, + else => { + @compileError("Invalid vector type conversion"); + }, + } + @compileError("Invalid vector conversion"); + } + }; +} + +pub fn Vector4Type(comptime T: type) type { + return extern struct { + x: T = 0, + y: T = 0, + z: T = 0, + w: T = 0, + + pub const Ones = @This(){ .x = 1, .y = 1, .z = 1 }; + pub const Zeroes = @This(){ .x = 0, .y = 0, .z = 0 }; + + pub const ones = @This(){ .x = 1, .y = 1, .z = 1 }; + pub const zero = @This(){ .x = 0, .y = 0, .z = 0 }; + + pub inline fn from(o: anytype) @This() { + return .{ .x = o.x, .y = o.y, .z = o.z, .w = o.w }; + } + + pub inline fn new(x: T, y: T, z: T, w: T) @This() { + return .{ + .x = x, + .y = y, + .z = z, + .w = w, + }; + } + + pub inline fn add(self: @This(), other: @This()) @This() { + return .{ + .x = self.x + other.x, + .y = self.y + other.y, + .z = self.z + other.z, + .w = self.w + other.w, + }; + } + + pub inline fn sub(self: @This(), other: @This()) @This() { + return .{ + .x = self.x - other.x, + .y = self.y - other.y, + .z = self.z - other.z, + .w = self.w - other.w, + }; + } + + pub inline fn normalize(self: @This()) @This() { + const len = std.math.sqrt(self.x * self.x + self.y * self.y + self.z * self.z + self.w * self.w); + + return .{ + .x = self.x / len, + .y = self.y / len, + .z = self.z / len, + .w = self.w / len, + }; + } + }; +} +pub const Vector4 = Vector4Type(f64); +pub const Vector4f = Vector4Type(f32); + +pub const Vector = Vector3Type(f64, "Vector"); +pub const Vectorf = Vector3Type(f32, "Vectorf"); +pub const Vector2f = Vector2Type(f32, "Vector2f"); +pub const Vector2 = Vector2Type(f64, "Vector2"); + +pub const Vector2i = Vector2Type(i32, "Vector2i"); +pub const Vector2c = Vector2Type(c_int, "Vector2c"); +pub const Vector2u = Vector2Type(u32, "Vector2u"); +pub const Vector2l = Vector2Type(i64, "Vector2l"); + +pub const EulerAngles = Vectorf; +pub const Quat = zm.Quat; +pub const Mat = zm.Mat; +pub const Transform = zm.Mat; + +pub fn matGetPosition(m: Mat) Vectorf { + const vec: Vectorf = .{}; + return Vectorf.fromZm(zm.mul(vec.toZm(), m)); +} + +pub fn matToRotation(m: Mat) Rotation { + const r: Rotation = .{ .quat = zm.matToQuat(m) }; + return r; +} + +pub const Rotation = struct { + quat: Quat = zm.qidentity(), + + pub fn init() @This() { + return .{}; + } + + pub fn isIdentity(self: @This()) bool { + return self.quat[0] == 0.0 and self.quat[1] == 0.0 and + self.quat[2] == 0.0 and self.quat[3] == 1.0; + } + + pub fn add(self: @This(), other: @This()) Rotation { + const m1 = zm.quatToMat(self.quat); + const m2 = zm.quatToMat(other.quat); + + const r = zm.mul(m1, m2); + return .{ .quat = zm.matToQuat(r) }; + } + + pub fn eulerX(o: f32) @This() { + return .{ + .quat = zm.matToQuat(zm.rotationX((o))), + }; + } + + pub fn eulerY(o: f32) @This() { + return .{ + .quat = zm.matToQuat(zm.rotationY((o))), + }; + } + + pub fn eulerZ(o: f32) @This() { + return .{ + .quat = zm.matToQuat(zm.rotationZ((o))), + }; + } + + pub fn up(self: @This()) Vectorf { + return self.rotateVector(Vectorf.Up); + } + + pub fn forward(self: @This()) Vectorf { + return self.rotateVector(Vectorf.Forward); + } + + pub fn right(self: @This()) Vectorf { + return self.rotateVector(Vectorf.Right); + } + + pub fn rotateVector(self: @This(), other: Vectorf) Vectorf { + return Vectorf.fromZm( + zm.mul( + other.toZm(), + zm.quatToMat(self.quat), + ), + ); + } +}; + +pub fn lerp(a: f32, b: f32, t: f32) f32 { + return a + t * (b - a); +} + +pub fn simdVec4ToVec(vec: zm.Vec) Vector4f { + return .{ + .x = vec[0], + .y = vec[1], + .z = vec[2], + .w = vec[3], + }; +} + +pub fn easeLinear(c: f32, t: f32, dt: f64, rate: f32) f32 { + const d = rate * @as(f32, @floatCast(dt)); + + if (c > t) { + return @max(c - d, t); + } else if (c < t) { + return @min(c + d, t); + } else { + return t; + } +} + +pub fn rollingAverage(average: *f64, newValue: f64, sampleCount: f64) void { + average.* = average.* - (average.* / sampleCount) + newValue / sampleCount; +} + +pub fn finite(value: f32) bool { + return !math.isNan(value) and !math.isInf(value); +} + +pub fn validVector(value: Vectorf) bool { + return finite(value.x) and finite(value.y) and finite(value.z); +} + +pub fn validRotation(value: Rotation) bool { + inline for (0..4) |index| if (!finite(value.quat[index])) return false; + return true; +} diff --git a/engine/p2/src/structures/names.zig b/engine/p2/src/structures/names.zig new file mode 100644 index 0000000..5164fca --- /dev/null +++ b/engine/p2/src/structures/names.zig @@ -0,0 +1,306 @@ +const std = @import("std"); +const stats = @import("stats.zig"); +const paged_vector = @import("paged-vector.zig"); +const builtin = @import("builtin"); + +const PagedVectorAdvanced = paged_vector.PagedVectorAdvanced; + +pub const NameRegistryStatus = enum { + Ok, + OutOfMemory, +}; + +pub const NameInvalid: Name = .{ .index = 0 }; + +const NameInvalidComptimeString = "Invalid"; + +// trying out a names scheme similar in vein to unreal engine's FNames +pub const NameRegistry = struct { + allocator: std.mem.Allocator, + io_context: std.Io, + map: std.StringHashMapUnmanaged(u32), // todo.. this can be replaced with a specialized hashmap + pagedVector: PagedVectorAdvanced([]const u8, 1024), + stringArena: std.heap.ArenaAllocator, + mutex: std.Io.Mutex = .init, + + // with this system errors should be nonexistent + // as a result I downgrade all errors into this error status field. + // I think the enhanced ergonomics of being able to use names ubiquitously is worth losing the + // immediate handling of the trace. + // + // usage of names should be null checked anyway. + errorStatus: NameRegistryStatus = .Ok, + + pub fn init(allocator: std.mem.Allocator, io_context: std.Io) !@This() { + var self = @This(){ + .allocator = allocator, + .io_context = io_context, + .stringArena = std.heap.ArenaAllocator.init(allocator), + .map = .empty, + .pagedVector = try PagedVectorAdvanced([]const u8, 1024).init(allocator), + }; + + _ = self.InstallNameInner(NameInvalidComptimeString, false); + return self; + } + + pub fn io(self: *const @This()) std.Io { + return self.io_context; + } + + pub fn count(self: @This()) u32 { + return @intCast(self.pagedVector.len()); + } + + pub fn getStatistics(self: *@This()) stats.PoolStatistics { + // per-entry cost of the string->index hashmap (key + value + metadata byte) + const mapEntryBytes = @sizeOf([]const u8) + @sizeOf(u32) + 1; + + var stringBytes: usize = 0; + for (0..self.pagedVector.len()) |i| { + stringBytes += self.pagedVector.get(i).len; + } + + const vectorStats = self.pagedVector.getStatistics(); + return .{ + .statName = "NameRegistry", + .instanceCount = self.count(), + .memoryReserved = vectorStats.memoryReserved + + self.stringArena.queryCapacity() + + self.map.capacity() * mapEntryBytes, + .memoryUsed = vectorStats.memoryUsed + + stringBytes + + self.map.count() * mapEntryBytes, + }; + } + + pub fn name(self: *@This(), nameString: []const u8) Name { + const index = self.InstallNameInner(nameString, true); + + return .{ + .index = index, + .string = self.pagedVector.get(index).*, + }; + } + + fn InstallNameInner(self: *@This(), nameString: []const u8, shouldCopy: bool) u32 { + self.mutex.lockUncancelable(self.io()); + defer self.mutex.unlock(self.io()); + + var newString = nameString; + // check if the string exists if it does just return it as a name. + if (self.map.get(newString)) |index| { + return index; + } + + if (shouldCopy) { + var allocator = self.stringArena.allocator(); + newString = allocator.dupe(u8, nameString) catch { + self.errorStatus = .OutOfMemory; + @panic("Out of memory during name operation"); + }; + } + + // add to registry + const newIndex = @as(u32, @intCast(self.pagedVector.len())); + self.pagedVector.append(self.allocator, newString) catch { + self.errorStatus = .OutOfMemory; + @panic("Out of memory during name operation"); + }; + + self.map.put(self.allocator, newString, newIndex) catch { + self.errorStatus = .OutOfMemory; + @panic("Out of memory during name operation"); + }; + + return newIndex; + } + + pub fn deinit(self: *@This()) void { + self.mutex.lockUncancelable(self.io()); + defer self.mutex.unlock(self.io()); + self.map.deinit(self.allocator); + self.pagedVector.deinit(self.allocator); + self.stringArena.deinit(); + } +}; + +pub var gRegistry: *NameRegistry = undefined; +var registryCreated: bool = false; +var registryOwned: bool = false; + +pub var gStringArena: std.heap.ArenaAllocator = undefined; +var testArenaActive: bool = false; + +pub fn createNameRegistry(allocator: std.mem.Allocator, io_context: std.Io) !*NameRegistry { + if (!registryCreated) { + gRegistry = try allocator.create(NameRegistry); + gRegistry.* = try NameRegistry.init(allocator, io_context); + registryCreated = true; + registryOwned = true; + } + return gRegistry; +} + +pub fn setNameRegistry(registry: *NameRegistry) void { + gRegistry = registry; + registryCreated = true; + registryOwned = false; +} + +pub fn isReady() bool { + return registryCreated; +} + +pub fn getRegistry() *NameRegistry { + // specifically in the case of unittests we can silently just initialize a temporary registry + if (builtin.is_test) { + if (!registryCreated) { + gStringArena = std.heap.ArenaAllocator.init(std.heap.page_allocator); + testArenaActive = true; + // leaking here is fine? might piss off valgrind + _ = createNameRegistry(gStringArena.allocator(), std.testing.io) catch unreachable; + } + } + + return gRegistry; +} + +pub fn destroyNameRegistry() void { + if (!registryCreated) return; + if (registryOwned) { + var allocator = gRegistry.allocator; + gRegistry.deinit(); + allocator.destroy(gRegistry); + } + if (testArenaActive) { + gStringArena.deinit(); + testArenaActive = false; + } + registryCreated = false; + registryOwned = false; +} + +// use this one when you want to be able to chain multiple declarations, +// otherwise DefineName is a bit nicer +pub fn ComptimeName(comptime s: []const u8) type { + return struct { + pub const string = s; + pub var name: Name = DefineName(string); + pub const copy: Name = DefineName(string); + }; +} + +pub fn DefineName(comptime string: []const u8) Name { + return Name.MakeComptime(string); +} + +pub fn MakeName(string: []const u8) Name { + return Name.Make(string); +} + +pub const Name = struct { + index: ?u32 = 0, // do not directly access + string: []const u8 = "Invalid", // do not directly access + + pub fn MakeComptime(string: []const u8) @This() { + return .{ .index = null, .string = string }; + } + + pub fn Make(string: []const u8) @This() { + return getRegistry().name(string); + } + + pub fn fromUtf8(string: []const u8) @This() { + return getRegistry().name(string); + } + + pub fn handle(self: *@This()) u32 { + if (self.index == null) { + const index = getRegistry().InstallNameInner(self.string, false); + self.index = index; + } + + return self.index.?; + } + + pub fn utf8(self: *@This()) []const u8 { + // so nasty... and const-violating. but the ergonomics is so good... + if (self.index == null) { + // screw it.. i'll pay the cost of duplicating even comptime strings + const index = getRegistry().InstallNameInner(self.string, true); + self.index = index; + } + + return getRegistry().pagedVector.get(self.index.?).*; + } + + pub fn eql(self: *@This(), other: *@This()) bool { + if (self.index == null) { + const index = getRegistry().InstallNameInner(self.string, false); + const mutableThis = self; + mutableThis.*.index = index; + } + + if (other.index == null) { + const index = getRegistry().InstallNameInner(self.string, false); + const mutableThis = self; + mutableThis.*.index = index; + } + + return self.index == other.index; + } +}; + +pub fn StaticName(comptime N: []const u8) type { + return struct { + pub const str = N; + pub var staticName: Name = .{ .string = str, .index = null }; + + pub fn ToName() Name { + .{ .string = N, .index = null }; + } + + pub fn get() Name { + return staticName; + } + + pub fn handle() u32 { + return staticName.handle(); + } + + pub fn utf() []const u8 { + return staticName.utf8(); + } + }; +} + +test "zname initialization and lookup" { + _ = try createNameRegistry(std.testing.allocator, std.testing.io); + defer destroyNameRegistry(); + + const testComptimeName = "This is a name test"; + const testComptimeName2 = "This is another name test"; + + var r = getRegistry(); + var name = MakeName(testComptimeName); + var name2 = r.name(testComptimeName); + var name4 = r.name(testComptimeName2); + + const fmtString = try std.fmt.allocPrint(std.testing.allocator, "morty I did horrible things to your {s}.", .{"locally elected representative"}); + defer std.testing.allocator.free(fmtString); + + var name3 = r.name(fmtString); + + try std.testing.expectEqualSlices(u8, testComptimeName, name.utf8()); + try std.testing.expectEqualSlices(u8, testComptimeName, name2.utf8()); + try std.testing.expect(name2.eql(&name)); + try std.testing.expect(!name3.eql(&name)); + + var uninitializedName: Name = .{}; + var invalidName = r.name("Invalid"); + try std.testing.expect(uninitializedName.eql(&invalidName)); + try std.testing.expect(!name4.eql(&name3)); + + try std.testing.expectEqualSlices(u8, name3.utf8(), fmtString); +} diff --git a/engine/p2/src/structures/paged-vector.zig b/engine/p2/src/structures/paged-vector.zig new file mode 100644 index 0000000..4b5abca --- /dev/null +++ b/engine/p2/src/structures/paged-vector.zig @@ -0,0 +1,323 @@ +const std = @import("std"); +const stats = @import("stats.zig"); + +// it's like an normal vector/ arraylist except it never invalidates old pointers. +// and never causes re-allocations. (excepting in the control block, which is just a vector of things) +// +// It is implemented with a control block which which contains a list of pages. +// these pages contain the actual memory of the vector. +// +// it has a growth factor, which can be configured. +// +// use cases: +// +// - this is highly performant for cases where +// - YOU WANT generally fast insertion time +// - YOU WANT fast random access time +// - YOU WANT cache-coherent and efficient linear iteration +// - YOU WANT to retain pointers across operations +// - YOU WANT to avoid reallocations (eg. if the data set is remarkably big) +// - YOU KNOW that you have linear growth factors and exponential growth is overkill. +// +// great for: +// - event logging. +// - output buffering. +// - recording timelines. + +pub fn PagedVectorAdvanced(comptime T: type, comptime growth: usize) type { + return struct { + const Page = struct { + data: [growth]T align(8) = undefined, + len: u32 = 0, + }; + + pages: std.ArrayListUnmanaged(*Page) = .empty, + currentPageId: usize = 0, + head: *T, + + pub fn init(allocator: std.mem.Allocator) !@This() { + var rv = @This(){ + .head = undefined, + }; + + const page = try allocator.create(Page); + page.* = .{}; + try rv.pages.append(allocator, page); + rv.head = &rv.pages.items[0].data[0]; + return rv; + } + + pub fn capacity(self: @This()) usize { + return self.pages.items.len * growth; + } + + pub fn len(self: @This()) usize { + return (self.currentPageId) * growth + self.currentPage().len; + } + + pub fn getStatistics(self: *const @This()) stats.PoolStatistics { + return .{ + .statName = "PagedVector", + .instanceCount = self.len(), + .memoryReserved = self.pages.items.len * @sizeOf(Page) + + self.pages.capacity * @sizeOf(*Page), + .memoryUsed = self.len() * @sizeOf(T), + }; + } + + pub fn deinit(self: *@This(), allocator: std.mem.Allocator) void { + for (self.pages.items) |page| { + allocator.destroy(page); + } + + self.pages.deinit(allocator); + } + + fn maybeExpand(self: *@This(), allocator: std.mem.Allocator) !void { + if (self.currentPageId == self.pages.items.len - 1) { + const page = try allocator.create(Page); + page.* = .{}; + try self.pages.append(allocator, page); + self.currentPageId = self.pages.items.len - 1; + } else { + self.currentPageId += 1; + } + } + + // frees all pages. and resets back to default state + pub fn reset(self: *@This(), allocator: std.mem.Allocator) void { + if (self.pages.items.len > 1) { + for (self.pages.items[1..]) |page| { + allocator.destroy(page); + } + self.pages.items.len = 1; + } + self.pages.items[0].len = 0; + self.currentPageId = 0; + self.head = &self.pages.items[0].data[0]; + } + + pub fn append(self: *@This(), allocator: std.mem.Allocator, value: T) !void { + var page = self.currentPage(); + page.len += 1; + if (page.len >= growth) { + try self.maybeExpand(allocator); + var appendedPage = self.pages.items[self.pages.items.len - 1]; + self.head = &appendedPage.data[appendedPage.len]; + } else { + self.head = &page.data[page.len - 1]; + } + self.head.* = value; + } + + pub fn appendSlice(self: *@This(), allocator: std.mem.Allocator, slice: []const T) !void { + for (slice) |value| { + try self.append(allocator, value); + } + } + + pub fn getMutable(self: *@This(), index: usize) *T { + const pageIndex = std.math.divFloor(usize, index, growth) catch unreachable; + return &self.pages.items[pageIndex].data[index % growth]; + } + + pub fn get(self: @This(), index: usize) *const T { + const pageIndex = std.math.divFloor(usize, index, growth) catch unreachable; + return &self.pages.items[pageIndex].data[index % growth]; + } + + // swaps the element at the index with the element currently pointed to by head + // then pops back the head, shrinking length by 1 + // + // Efficient removal of an element at an index but does not preserve order. + pub fn swapRemove(self: *@This(), index: usize) void { + const ptr = self.getMutable(index); + ptr.* = self.head.*; + _ = try self.pop(); + } + + fn currentPage(self: @This()) *Page { + return self.pages.items[self.currentPageId]; + } + + // // retrieves a value, shrinking length by 1 + pub fn pop(self: *@This()) !T { + const rv = self.head.*; + var page = self.currentPage(); + page.len -= 1; + if (page.len < 1) { + page.len = 0; + self.currentPageId -= 1; + } + + self.head = &self.currentPage().data[self.currentPage().len - 1]; + return rv; + } + }; +} + +pub fn PagedVectorUnmanaged(comptime T: type) type { + return PagedVectorAdvanced(T, 1024); +} + +pub fn PagedVector(comptime T: type) type { + return struct { + const VectorType = PagedVectorAdvanced(T, 1024); + + vector: VectorType, + allocator: std.mem.Allocator, + + pub fn init(allocator: std.mem.Allocator) !@This() { + return .{ + .vector = try VectorType.init(allocator), + .allocator = allocator, + }; + } + + pub fn deinit(self: *@This()) void { + self.vector.deinit(self.allocator); + } + + pub fn appendSlice(self: *@This(), slice: []const T) !void { + try self.vector.appendSlice(self.allocator, slice); + } + + pub fn append(self: *@This(), value: T) !void { + try self.vector.append(self.allocator, value); + } + + pub fn appendAndGet(self: *@This(), value: T) !*T { + const index = self.len(); + try self.append(value); + return self.getMutable(index); + } + + pub fn get(self: *const @This(), index: usize) *const T { + return self.vector.get(index); + } + + pub fn getMutable(self: *@This(), index: usize) *T { + return self.vector.getMutable(index); + } + + pub fn len(self: @This()) usize { + return self.vector.len(); + } + + pub fn capacity(self: @This()) usize { + return self.vector.capacity(); + } + + pub fn getStatistics(self: *const @This()) stats.PoolStatistics { + return self.vector.getStatistics(); + } + + pub fn swapRemove(self: *@This(), index: usize) void { + self.vector.swapRemove(index); + } + + pub fn reset(self: *@This()) void { + self.vector.reset(self.allocator); + } + + // // retrieves a value, shrinking length by 1 + pub fn pop(self: *@This()) !T { + return try self.vector.pop(); + } + }; +} + +test "simple loading multiple pages." { + const TestStruct = struct { + lmao: usize, + }; + + const allocator = std.testing.allocator; + var vector = try PagedVectorAdvanced(TestStruct, 1024).init(std.testing.allocator); + defer vector.deinit(allocator); + + for (0..128) |j| { + try vector.append(allocator, .{ .lmao = j }); + } + + const ptr = vector.get(0); + const mutable = vector.getMutable(127); + + for (0..4096) |i| { + try vector.append(allocator, .{ .lmao = i }); + } + + // testing that pointers are not invalidated + std.debug.assert(ptr == vector.get(0)); + std.debug.assert(mutable == vector.getMutable(127)); + + std.debug.assert(vector.getMutable(4092) == vector.getMutable(4092)); + + // 4096 + 128 = 4224 = 4 pages + 128 extra entries + std.debug.assert(vector.pages.items.len == 5); + std.debug.assert(vector.capacity() == 1024 * 5); + std.debug.assert(vector.len() == 128 + 1024 * 4); + + // 4092 - 3072 = offset of 1020 in the third page. + const ptr4092 = vector.getMutable(4092); + std.debug.assert(vector.getMutable(4092) == &vector.pages.items[3].data[1020]); + + // lets try adding 1024 elements and see if pointers are still preserved. + for (0..1024) |_| { + try vector.append(allocator, .{ .lmao = 0 }); + } + + std.debug.assert(vector.getMutable(4092) == ptr4092); + std.debug.assert(vector.get(0).lmao == 0); + std.debug.assert(vector.get(1).lmao == 1); + std.debug.assert(vector.get(2).lmao == 2); + + // testing the pop() function + std.debug.assert(vector.len() == 128 + 1024 * 5); + _ = try vector.pop(); + _ = try vector.pop(); + _ = try vector.pop(); + + // testing the swapRemove Functionality + std.debug.assert(vector.len() == 128 + 1024 * 5 - 3); + vector.swapRemove(1); + std.debug.assert(vector.len() == 128 + 1024 * 5 - 4); + + for (0..1024) |_| { + vector.swapRemove(0); + } + std.debug.assert(vector.len() == 128 + 1024 * 5 - 4 - 1024); +} + +test "managed version" { + const allocator = std.testing.allocator; + + var vec = try PagedVector(struct { lmao: u64 }).init(allocator); + defer vec.deinit(); + + for (0..8192) |i| { + try vec.append(.{ .lmao = i }); + } + + std.debug.assert(vec.vector.pages.items.len == 9); +} + +test "reset releases extra pages and clears length" { + const allocator = std.testing.allocator; + + var vec = try PagedVectorAdvanced(u32, 4).init(allocator); + defer vec.deinit(allocator); + + for (0..10) |i| { + try vec.append(allocator, @intCast(i)); + } + + try std.testing.expect(vec.pages.items.len > 1); + vec.reset(allocator); + + try std.testing.expectEqual(@as(usize, 1), vec.pages.items.len); + try std.testing.expectEqual(@as(usize, 0), vec.len()); + + try vec.append(allocator, 42); + try std.testing.expectEqual(@as(u32, 42), vec.get(0).*); +} diff --git a/engine/p2/src/structures/perf-tests.zig b/engine/p2/src/structures/perf-tests.zig new file mode 100644 index 0000000..1d69d27 --- /dev/null +++ b/engine/p2/src/structures/perf-tests.zig @@ -0,0 +1,190 @@ +const std = @import("std"); +const sparse_set = @import("sparse-set.zig"); + +fn println(comptime fmt: []const u8, args: anytype) void { + std.debug.print(fmt ++ "\n", args); +} + +const LookupPerfContext = struct { + testName: []const u8 = "lookup perf 1 Billion Accesses", + dsName: std.ArrayList([]const u8), // name of data structures + testSizes: std.ArrayList(usize), + testTimes: std.ArrayList(std.ArrayList(f64)), // + + pub fn init(allocator: std.mem.Allocator) @This() { + _ = allocator; + return .{ + .dsName = .empty, + .testSizes = .empty, + .testTimes = .empty, + }; + } + + pub fn printResults(self: @This()) void { + // prints out results in a csv format + println("Test Results: {s}", .{self.testName}); + std.debug.print("number of elements,", .{}); + + for (self.dsName.items) |name| { + std.debug.print("{s},", .{name}); + } + + std.debug.print("\n", .{}); + std.debug.assert(self.testSizes.items.len == self.testTimes.items.len); + + var i: usize = 0; + while (i < self.testSizes.items.len) : (i += 1) { + std.debug.print("{d},", .{self.testSizes.items[i]}); + const times = self.testTimes.items[i]; + + for (times.items) |entry| { + std.debug.print("{d},", .{entry}); + } + + std.debug.print("\n", .{}); + } + } +}; + +fn nowNs(io: std.Io) i96 { + return std.Io.Timestamp.now(io, .awake).toNanoseconds(); +} + +fn elapsedSeconds(start_ns: i96, end_ns: i96) f64 { + return @as(f64, @floatFromInt(end_ns - start_ns)) / @as(f64, @floatFromInt(std.time.ns_per_s)); +} + +pub fn LookupPerfTest(io: std.Io, allocator: std.mem.Allocator, perfContext: *LookupPerfContext, comptime TestSize: comptime_int, comptime AccessCount: comptime_int) !void { + var testTimes: std.ArrayList(f64) = .empty; + try testTimes.appendSlice(allocator, &.{ + 0.0, + 0.0, + 0.0, + 0.0, + }); + + const TestPayload = struct { + touchCount: u32 = 0, + name: []const u8 = "payload", + }; + + // Doing a test of 1 million accesses to random sparse set handles to one thousand hashmap lookups + const TestMap = std.AutoHashMap(u32, TestPayload); + const TestSet = sparse_set.SparseMultiSet(struct { + obj: TestPayload = .{}, + }); + + println(" === preparing test with {d} entries === ", .{TestSize}); + var testMap = TestMap.init(allocator); + defer testMap.deinit(); + var i: usize = 0; + while (i < TestSize) : (i += 1) { + try testMap.put(@as(u32, @intCast(i)), .{}); + } + i = 0; + + var hashMapTime: f64 = 0; + + { + const startTime = nowNs(io); + // random access for 1M. + while (i < AccessCount) : (i += 1) { + const id = @as(u32, @intCast(i % TestSize)); + testMap.getEntry(id).?.value_ptr.*.touchCount += 1; + } + const endTime = nowNs(io); + println("hashMap: {d} accesses executed in {d}s", .{ AccessCount, elapsedSeconds(startTime, endTime) }); + hashMapTime = elapsedSeconds(startTime, endTime); // index 0 + testTimes.items[0] = hashMapTime; + } + + var hashmap_linear_time: f64 = 0; + { + i = 0; + const startTime = nowNs(io); + // random access for 1M. + while (i < AccessCount) : (i += 1) { + var iter = testMap.iterator(); + while (iter.next()) |entry| { + entry.value_ptr.*.touchCount += 1; + i += 1; + } + } + const endTime = nowNs(io); + println("hashMap_linear: {d} accesses executed in {d}s", .{ AccessCount, elapsedSeconds(startTime, endTime) }); + hashmap_linear_time = elapsedSeconds(startTime, endTime); + testTimes.items[2] = hashmap_linear_time; + } + + // --- testing sparse sets + var testSet = TestSet.init(allocator); + defer testSet.deinit(); + var handlesList: std.ArrayList(sparse_set.SetHandle) = .empty; + + i = 0; + while (i < TestSize) : (i += 1) { + const newHandle = try testSet.createObject(.{}); + try handlesList.append(allocator, newHandle); + } + + var sparseSetTime: f64 = 0; + i = 0; + { + const startTime = nowNs(io); + while (i < AccessCount) : (i += 1) { + testSet.get(handlesList.items[i % TestSize], .obj).?.*.touchCount += 1; + } + const endTime = nowNs(io); + println("sparseSet: {d} accesses executed in {d}s", .{ AccessCount, elapsedSeconds(startTime, endTime) }); + sparseSetTime = elapsedSeconds(startTime, endTime); + testTimes.items[1] = sparseSetTime; + } + + // linear access + var sparseset_linear_time: f64 = 0; + i = 0; + { + const startTime = nowNs(io); + var denseArray = testSet.denseItems(.obj); + while (i < AccessCount) : (i += 1) { + denseArray[i % TestSize].touchCount += 1; + } + const endTime = nowNs(io); + sparseset_linear_time = elapsedSeconds(startTime, endTime); + println("sparseSet_linear: {d} accesses executed in {d}s", .{ AccessCount, elapsedSeconds(startTime, endTime) }); + testTimes.items[3] = sparseset_linear_time; + } + + println("random read: sparseSet is {d} times faster than hashmap", .{hashMapTime / sparseSetTime}); + println("sequential read: sparseSet is {d} times faster than hashmap", .{hashmap_linear_time / sparseset_linear_time}); + + try perfContext.testTimes.append(allocator, testTimes); + try perfContext.testSizes.append(allocator, TestSize); +} + +const K = 1000; +const M = 1000 * K; +const G = 1000 * M; + +pub fn count(comptime n: anytype) [n]u0 { + return comptime [1]u0{0} ** n; +} + +test "Perf test sparse vs hashmap" { + // this test does NOT care about freeing memory, just gonna let the arena hit it. + var arena = std.heap.ArenaAllocator.init(std.heap.smp_allocator); + defer arena.deinit(); + const arenaAlloc = arena.allocator(); + + var context = LookupPerfContext.init(arenaAlloc); + try context.dsName.append(arenaAlloc, "hashmap random"); + try context.dsName.append(arenaAlloc, "sparseSet random"); + try context.dsName.append(arenaAlloc, "hashmap linear"); + try context.dsName.append(arenaAlloc, "sparseset linear"); + + inline for (comptime count(100 - 1), 0..) |_, i| { + try LookupPerfTest(std.testing.io, arenaAlloc, &context, (i + 1) * (100 * K) / 100, 100 * M); + } + + context.printResults(); +} diff --git a/engine/p2/src/structures/pscopes.zig b/engine/p2/src/structures/pscopes.zig new file mode 100644 index 0000000..d5a15e6 --- /dev/null +++ b/engine/p2/src/structures/pscopes.zig @@ -0,0 +1,165 @@ +// pscopes +// +// a tiny scope based profiling library +// as well as contains info for arbitrary timestamping and timestamp resolution + +const timestampTicks = if (builtin.target.cpu.arch == .x86_64) rdtsc else aarch64_ticks; + +// rdtsc actually gets read +pub inline fn rdtsc() u64 { + var hi: u32 = 0; + var lo: u32 = 0; + + asm ( + \\rdtsc + : [lo] "={eax}" (lo), + [hi] "={edx}" (hi), + ); + return (@as(u64, hi) << 32) | @as(u64, lo); +} + +fn aarch64_ticks() u64 { + return asm volatile ("mrs %[ret], CNTVCT_EL0" + : [ret] "=r" (-> u64), + ); +} + +fn aarch64_freq() u64 { + return asm volatile ("mrs %[ret], CNTFRQ_EL0" + : [ret] "=r" (-> u64), + ); +} + +fn countTo1Million() u32 { + var i: u32 = 0; + while (i < 1000 * 1000) : (i += 1) {} + return i; +} + +fn countTo1Billion() u32 { + var i: u32 = 0; + while (i < 1000 * 1000 * 1000) : (i += 1) {} + return i; +} + +pub const TimingScope = struct { + // value in tsc ticks + startTsc: u64, + endTsc: ?u64 = null, + + context: *ScopesContext, + + pub inline fn init(c: *ScopesContext) @This() { + return .{ + .startTsc = timestampTicks(), + .context = c, + }; + } + + pub fn duration(self: *@This()) ?f64 { + if (self.endTsc) |endTsc| { + if (self.context.ticksPerMs) |ticksPerMs| { + const x = @as(f64, @floatFromInt(endTsc - self.startTsc)) / ticksPerMs / 1000; + return x; + } + } + + return null; + } + + pub inline fn end(self: *@This()) void { + self.endTsc = timestampTicks(); + } +}; + +pub const ScopesContext = struct { + allocator: std.mem.Allocator, + io_context: std.Io, + ticksPerMs: ?f64 = null, + + pub fn io(self: *const @This()) std.Io { + return self.io_context; + } + + // creates a very simple scope, the only thing it does is store the timestamp, and move on + pub fn stampScope(self: *@This()) TimingScope { + return .{ + .startTsc = timestampTicks(), + .endTsc = null, + .context = self, + }; + } + + // calibrates the ticks per second divider. + // spins for 1 ms then compares against the monotonic timer + // should be called once every second, this is kinda perscriptive, + // calling it more frequently will increase accuracy + pub fn calibrate(self: *@This()) void { + if (builtin.target.cpu.arch == .x86_64) { + const startTime = std.Io.Timestamp.now(self.io(), .awake); + const startStamp = rdtsc(); + while (startTime.durationTo(std.Io.Timestamp.now(self.io(), .awake)).toNanoseconds() < std.time.ns_per_ms) {} + const endStamp = rdtsc(); + + self.ticksPerMs = @floatFromInt((endStamp - startStamp)); + } else if (builtin.target.cpu.arch == .aarch64) { + self.ticksPerMs = @as(f64, @floatFromInt(aarch64_freq())) / 1000; + } else { + // not ticking + // unreachable; + } + } + + pub fn create(allocator: std.mem.Allocator, io_context: std.Io) !*@This() { + const self = try allocator.create(@This()); + self.* = .{ + .allocator = allocator, + .io_context = io_context, + }; + return self; + } + + pub fn destroy(self: *@This()) void { + self.allocator.destroy(self); + } +}; + +test "calibrate scoes" { + const allocator = std.testing.allocator; + + const scopes = try ScopesContext.create(allocator, std.testing.io); + defer scopes.destroy(); + + scopes.calibrate(); + std.debug.print("calibration ticksPerMs = {d}\n", .{scopes.ticksPerMs.?}); + + scopes.calibrate(); + std.debug.print("calibration ticksPerMs = {d}\n", .{scopes.ticksPerMs.?}); + + scopes.calibrate(); + std.debug.print("calibration ticksPerMs = {d}\n", .{scopes.ticksPerMs.?}); + + { + var scope = scopes.stampScope(); + _ = countTo1Billion(); + scope.end(); + + std.debug.print("time elapsed: {d}\n ", .{scope.duration().?}); + } + + { + var z = scopes.stampScope(); + defer z.end(); + _ = countTo1Million(); + } + + { + var z = scopes.stampScope(); + defer z.end(); + _ = countTo1Million(); + } +} + +const std = @import("std"); +const builtin = @import("builtin"); +const pscopes_zig_src = @embedFile("pscopes.zig"); diff --git a/engine/p2/src/structures/ref-pool.zig b/engine/p2/src/structures/ref-pool.zig new file mode 100644 index 0000000..ffc67ae --- /dev/null +++ b/engine/p2/src/structures/ref-pool.zig @@ -0,0 +1,658 @@ +const std = @import("std"); +const stats = @import("stats.zig"); +const index_pool = @import("index-pool.zig"); + +pub const RefPoolOptions = struct { + deferredDestruction: bool = false, +}; + +/// A dense value pool with strong, reference-counted handles. +/// +/// This default form destroys values immediately after their final `drop`. +/// Use `RefPoolAdvanced` to opt into deferred destruction. +pub fn RefPool(comptime T: type) type { + return RefPoolAdvanced(T, .{}); +} + +// Deffered destruction version of refpool +// owning system MUST tick the trim() function, +// provides lifetime destruction hooks for each entry. +pub fn RefPoolDeferred(comptime T: type) type { + return RefPoolAdvanced(T, .{}); +} + +/// A dense value pool with strong, reference-counted handles. +/// +/// RefPool is backed by an IndexPool and shares its storage model and handle +/// layout, but handles own the value they address: `new` creates a value with +/// one reference, `pin` adds a reference, and `drop` releases one. +/// +/// A final `drop` makes the handle logically dead immediately. With immediate +/// destruction it also removes the value at once. With deferred destruction +/// it queues the value for a later `trim`; the zero-pin entry remains in the +/// backing pool and its slot cannot be reused until then. +/// +/// Handles are generational like IndexPool handles. Copying a handle without +/// calling `pin` is a contract violation. An optional `onDestroy` callback can +/// release resources owned by `T`; without one, removed values are discarded. +/// The callback receives a temporary pointer that is valid only for that call. +/// +/// The backing `pool` remains exposed for dense iteration and low-level slot +/// bookkeeping. In deferred mode its dense storage includes queued zero-pin +/// entries; callers must not treat those entries as live. Do not call `new` or +/// `destroy` on the backing pool directly. +/// +/// Pointers and slices returned by this type are invalidated by `new`, an +/// immediate destroying `drop`, `trim`, `releaseAllFreeSlots`, or `deinit`. +/// A final deferred `drop` logically invalidates pointers to that value even +/// though physical removal waits for `trim`. +/// +/// Releasing every reference during normal operation is the caller's +/// responsibility. `deinit` defensively destroys pending and still-pinned +/// entries. Handles belong to one pool instance. `releaseAllFreeSlots` is a +/// full epoch boundary: callers must discard every handle, including stale +/// handles, before calling it because released generation history is lost. +/// +/// This type is not thread-safe. +pub fn RefPoolAdvanced(comptime T: type, comptime options: RefPoolOptions) type { + return struct { + const Self = @This(); + + pub const PinCount = u32; + + /// Dense storage element. The pin count travels with the value under + /// IndexPool's swap-remove; handle stability comes from the slot + /// table underneath. A zero pin count marks deferred destruction. + pub const Entry = struct { + value: T, + pins: PinCount, + }; + + pub const Pool = index_pool.IndexPool(Entry); + pub const Handle = index_pool.TypedHandle(T); + pub const OnDestroyFn = *const fn (context: ?*anyopaque, value: *T) void; + + const InnerHandle = Pool.Handle; + const OnDestroyBinding = struct { + context: ?*anyopaque, + callback: OnDestroyFn, + }; + const PendingDestroyList = if (options.deferredDestruction) + std.ArrayList(Handle) + else + struct { + const empty: @This() = .{}; + }; + + pub const maxSlotCount: usize = Pool.maxSlotCount; + pub const CapacityError = Pool.CapacityError; + + allocator: std.mem.Allocator, + + /// The backing pool. Direct mutation bypasses RefPool's ownership + /// invariants and is unsupported. + pool: Pool, + + pendingDestroy: PendingDestroyList = .empty, + onDestroy: ?OnDestroyBinding = null, + callbackDepth: usize = 0, + trimming: bool = false, + deinitializing: bool = false, + + pub fn init(allocator: std.mem.Allocator) Self { + return .{ + .allocator = allocator, + .pool = Pool.init(allocator), + }; + } + + /// Initializes a pool with capacity for `capacity` live, free, or + /// pending slots. A final `drop` and `trim` remain allocation-free. + pub fn initCapacity(allocator: std.mem.Allocator, capacity: usize) CapacityError!Self { + var self = init(allocator); + errdefer self.deinit(); + try self.ensureTotalCapacity(capacity); + return self; + } + + /// Reserves dense, slot, free-list, and deferred-destruction storage. + pub fn ensureTotalCapacity(self: *Self, capacity: usize) CapacityError!void { + if (capacity > maxSlotCount) return error.PoolFull; + if (comptime options.deferredDestruction) { + try self.pendingDestroy.ensureTotalCapacity(self.allocator, capacity); + } + try self.pool.ensureTotalCapacity(capacity); + } + + fn toInner(handle: Handle) InnerHandle { + return @bitCast(handle); + } + + /// Number of logically live values. Deferred zero-pin entries are not + /// included even though they remain in backing storage until `trim`. + pub fn count(self: *const Self) usize { + return self.pool.count() - self.pendingDestroyCount(); + } + + /// Number of values awaiting physical removal and `onDestroy`. + pub fn pendingDestroyCount(self: *const Self) usize { + if (comptime options.deferredDestruction) { + return self.pendingDestroy.items.len; + } + return 0; + } + + /// Number of allocated handle slots, including free, pending, and + /// retired slots. + pub fn slotCount(self: *const Self) usize { + return self.pool.slotCount(); + } + + /// Number of slots available for immediate allocation-free reuse. + /// Deferred entries do not become free until `trim` removes them. + pub fn freeCount(self: *const Self) usize { + return self.pool.freeCount(); + } + + pub fn getStatistics(self: *const Self) stats.PoolStatistics { + var poolStats = self.pool.getStatistics(); + poolStats.statName = "RefPool"; + poolStats.instanceCount = self.count(); + if (comptime options.deferredDestruction) { + poolStats.memoryReserved += self.pendingDestroy.capacity * @sizeOf(Handle); + poolStats.memoryUsed += self.pendingDestroy.items.len * @sizeOf(Handle); + } + return poolStats; + } + + /// Installs or replaces the pool-wide destruction callback. The + /// context and function must remain valid through every later destroy + /// operation, including `deinit`, unless explicitly unregistered. + pub fn registerOnDestroy(self: *Self, context: ?*anyopaque, callback: OnDestroyFn) void { + std.debug.assert(self.callbackDepth == 0); + std.debug.assert(!self.trimming); + std.debug.assert(!self.deinitializing); + self.onDestroy = .{ + .context = context, + .callback = callback, + }; + } + + /// Clears the callback. Values destroyed afterward are discarded. + pub fn unregisterOnDestroy(self: *Self) void { + std.debug.assert(self.callbackDepth == 0); + std.debug.assert(!self.trimming); + std.debug.assert(!self.deinitializing); + self.onDestroy = null; + } + + /// Creates a value with one reference and returns its owning handle. + pub fn new(self: *Self, initVal: T) CapacityError!Handle { + std.debug.assert(self.callbackDepth == 0); + std.debug.assert(!self.deinitializing); + + // A free slot already has matching dense and pending capacity. + // Growing the slot table must reserve every backing structure + // before IndexPool's allocation-free append path is entered. + if (self.pool.freeCount() == 0) { + if (self.pool.slotCount() == maxSlotCount) return error.PoolFull; + try self.ensureTotalCapacity(self.pool.slotCount() + 1); + } + + const inner = try self.pool.new(.{ + .value = initVal, + .pins = 1, + }); + return @bitCast(inner); + } + + pub fn isValid(self: *const Self, handle: Handle) bool { + const entry = self.pool.getRead(toInner(handle)) orelse return false; + return entry.pins != 0; + } + + /// Adds a reference to a live value. Pending, invalid, and stale + /// handles return false without changing the pool. + pub fn pin(self: *Self, handle: Handle) bool { + std.debug.assert(self.callbackDepth == 0); + std.debug.assert(!self.deinitializing); + + const entry = self.pool.get(toInner(handle)) orelse return false; + if (entry.pins == 0) return false; + std.debug.assert(entry.pins < std.math.maxInt(PinCount)); + entry.pins += 1; + return true; + } + + /// Releases one reference. Returns false for invalid, stale, already + /// pending, and duplicate handles. A final drop either destroys the + /// value immediately or queues it for `trim`, depending on the + /// compile-time configuration. This operation never allocates. + pub fn drop(self: *Self, handle: Handle) bool { + const inner = toInner(handle); + const entry = self.pool.get(inner) orelse return false; + if (entry.pins == 0) return false; + + entry.pins -= 1; + if (entry.pins != 0) return true; + + if (comptime options.deferredDestruction) { + std.debug.assert(self.pendingDestroy.items.len < self.pendingDestroy.capacity); + self.pendingDestroy.appendAssumeCapacity(handle); + } else { + var removed = self.pool.destroy(inner).?; + self.invokeOnDestroy(&removed.value); + } + return true; + } + + /// Current reference count of a live value, null for pending, + /// invalid, or stale handles. + pub fn pinCount(self: *const Self, handle: Handle) ?PinCount { + const entry = self.pool.getRead(toInner(handle)) orelse return null; + if (entry.pins == 0) return null; + return entry.pins; + } + + pub fn get(self: *Self, handle: Handle) ?*T { + const entry = self.pool.get(toInner(handle)) orelse return null; + if (entry.pins == 0) return null; + return &entry.value; + } + + pub fn getRead(self: *const Self, handle: Handle) ?*const T { + const entry = self.pool.getRead(toInner(handle)) orelse return null; + if (entry.pins == 0) return null; + return &entry.value; + } + + /// Physically removes every pending value and invokes the currently + /// registered callback. Drops performed by callbacks are included in + /// the same drain. Returns the number of values removed. + pub fn trim(self: *Self) usize { + if (comptime !options.deferredDestruction) return 0; + + std.debug.assert(self.callbackDepth == 0); + std.debug.assert(!self.trimming); + std.debug.assert(!self.deinitializing); + self.trimming = true; + defer self.trimming = false; + return self.drainPending(); + } + + /// Fully releases pool storage when there are no live or pending + /// values. This is a full epoch boundary; every associated handle must + /// be discarded first. + pub fn releaseAllFreeSlots(self: *Self) bool { + if (self.pool.count() != 0 or self.pendingDestroyCount() != 0) return false; + + const releasedPoolStorage = self.pool.releaseAllFreeSlots(); + if (comptime options.deferredDestruction) { + const releasedPendingStorage = self.pendingDestroy.capacity != 0; + if (releasedPendingStorage) { + self.pendingDestroy.clearAndFree(self.allocator); + } + return releasedPoolStorage or releasedPendingStorage; + } + return releasedPoolStorage; + } + + /// Destroys pending and still-pinned entries, then releases storage. + pub fn deinit(self: *Self) void { + std.debug.assert(self.callbackDepth == 0); + std.debug.assert(!self.trimming); + std.debug.assert(!self.deinitializing); + self.deinitializing = true; + + _ = self.drainPending(); + while (self.pool.count() != 0) { + // A callback may have dropped other values. Drain those first + // so their queued handles never become stale inside the list. + if (self.pendingDestroyCount() != 0) { + _ = self.drainPending(); + continue; + } + + const denseIndex = self.pool.count() - 1; + const handle = self.pool.handleAtDenseIndex(denseIndex).?; + var removed = self.pool.destroy(handle).?; + self.invokeOnDestroy(&removed.value); + } + + if (comptime options.deferredDestruction) { + std.debug.assert(self.pendingDestroy.items.len == 0); + self.pendingDestroy.deinit(self.allocator); + } + self.pool.deinit(); + self.* = undefined; + } + + fn drainPending(self: *Self) usize { + if (comptime !options.deferredDestruction) return 0; + + var destroyed: usize = 0; + while (self.pendingDestroy.pop()) |handle| { + const inner = toInner(handle); + const entry = self.pool.get(inner) orelse continue; + std.debug.assert(entry.pins == 0); + var removed = self.pool.destroy(inner).?; + self.invokeOnDestroy(&removed.value); + destroyed += 1; + } + return destroyed; + } + + fn invokeOnDestroy(self: *Self, value: *T) void { + const binding = self.onDestroy orelse return; + std.debug.assert(self.callbackDepth < std.math.maxInt(usize)); + self.callbackDepth += 1; + defer self.callbackDepth -= 1; + binding.callback(binding.context, value); + } + }; +} + +const TestValue = struct { + id: u32, +}; +const TestPool = RefPool(TestValue); +const DeferredTestPool = RefPoolAdvanced(TestValue, .{ .deferredDestruction = true }); + +const DestroyContext = struct { + ids: [16]u32 = undefined, + count: usize = 0, + + fn onDestroy(rawContext: ?*anyopaque, value: *TestValue) void { + const self: *@This() = @ptrCast(@alignCast(rawContext.?)); + self.ids[self.count] = value.id; + self.count += 1; + } +}; + +test "ref pool handles are typed and zero-invalid" { + try std.testing.expect(RefPool(u32).Handle != RefPool(u64).Handle); + try std.testing.expectEqual(@as(usize, 4), @sizeOf(TestPool.Handle)); + try std.testing.expectEqual(@as(usize, 1) << 18, TestPool.maxSlotCount); + + var pool = TestPool.init(std.testing.allocator); + defer pool.deinit(); + + try std.testing.expect(!pool.isValid(.{})); + try std.testing.expect(!pool.pin(.{})); + try std.testing.expect(!pool.drop(.{})); + + const handle = try pool.new(.{ .id = 42 }); + try std.testing.expect(handle.generation != 0); + try std.testing.expect(pool.isValid(handle)); + try std.testing.expectEqual(@as(u32, 42), pool.get(handle).?.id); + try std.testing.expectEqual(@as(TestPool.PinCount, 1), pool.pinCount(handle).?); +} + +test "ref pool invokes onDestroy on an immediate final drop" { + var pool = TestPool.init(std.testing.allocator); + defer pool.deinit(); + + var context: DestroyContext = .{}; + pool.registerOnDestroy(&context, DestroyContext.onDestroy); + + const handle = try pool.new(.{ .id = 1 }); + try std.testing.expect(pool.pin(handle)); + try std.testing.expect(pool.pin(handle)); + try std.testing.expectEqual(@as(TestPool.PinCount, 3), pool.pinCount(handle).?); + + try std.testing.expect(pool.drop(handle)); + try std.testing.expect(pool.isValid(handle)); + try std.testing.expect(pool.drop(handle)); + try std.testing.expectEqual(@as(TestPool.PinCount, 1), pool.pinCount(handle).?); + try std.testing.expectEqual(@as(usize, 0), context.count); + + try std.testing.expect(pool.drop(handle)); + try std.testing.expectEqual(@as(usize, 1), context.count); + try std.testing.expectEqual(@as(u32, 1), context.ids[0]); + try std.testing.expect(!pool.isValid(handle)); + try std.testing.expect(pool.pinCount(handle) == null); + try std.testing.expectEqual(@as(usize, 0), pool.count()); + try std.testing.expectEqual(@as(usize, 0), pool.trim()); +} + +test "ref pool unregisters onDestroy and rejects stale drops" { + var pool = TestPool.init(std.testing.allocator); + defer pool.deinit(); + + var context: DestroyContext = .{}; + pool.registerOnDestroy(&context, DestroyContext.onDestroy); + pool.unregisterOnDestroy(); + + const original = try pool.new(.{ .id = 1 }); + try std.testing.expect(pool.drop(original)); + try std.testing.expectEqual(@as(usize, 0), context.count); + + try std.testing.expect(!pool.isValid(original)); + try std.testing.expect(!pool.pin(original)); + try std.testing.expect(!pool.drop(original)); + try std.testing.expect(pool.get(original) == null); + + const replacement = try pool.new(.{ .id = 2 }); + try std.testing.expectEqual(original.index, replacement.index); + try std.testing.expect(original.generation != replacement.generation); + try std.testing.expect(!pool.drop(original)); + try std.testing.expectEqual(@as(u32, 2), pool.get(replacement).?.id); +} + +test "ref pool keeps immediate survivors dense" { + var pool = TestPool.init(std.testing.allocator); + defer pool.deinit(); + + const first = try pool.new(.{ .id = 1 }); + const middle = try pool.new(.{ .id = 2 }); + const last = try pool.new(.{ .id = 3 }); + try std.testing.expect(pool.pin(last)); + + try std.testing.expect(pool.drop(middle)); + + try std.testing.expectEqual(@as(usize, 2), pool.count()); + try std.testing.expectEqual(@as(u32, 1), pool.get(first).?.id); + try std.testing.expectEqual(@as(u32, 3), pool.get(last).?.id); + try std.testing.expectEqual(@as(TestPool.PinCount, 2), pool.pinCount(last).?); + + const entries = pool.pool.items(); + try std.testing.expectEqual(@as(usize, 2), entries.len); + try std.testing.expectEqual(@as(u32, 1), entries[0].value.id); + try std.testing.expectEqual(@as(u32, 3), entries[1].value.id); + try std.testing.expectEqual(@as(TestPool.PinCount, 2), entries[1].pins); +} + +test "deferred final drop invalidates logically until trim" { + var pool = try DeferredTestPool.initCapacity(std.testing.allocator, 2); + defer pool.deinit(); + + var context: DestroyContext = .{}; + pool.registerOnDestroy(&context, DestroyContext.onDestroy); + + const original = try pool.new(.{ .id = 1 }); + try std.testing.expect(pool.drop(original)); + + try std.testing.expectEqual(@as(usize, 0), pool.count()); + try std.testing.expectEqual(@as(usize, 1), pool.pendingDestroyCount()); + try std.testing.expectEqual(@as(usize, 1), pool.pool.count()); + try std.testing.expectEqual(@as(usize, 0), pool.freeCount()); + try std.testing.expectEqual(@as(usize, 0), context.count); + try std.testing.expect(!pool.isValid(original)); + try std.testing.expect(!pool.pin(original)); + try std.testing.expect(!pool.drop(original)); + try std.testing.expect(pool.get(original) == null); + try std.testing.expect(pool.getRead(original) == null); + try std.testing.expect(pool.pinCount(original) == null); + try std.testing.expect(!pool.releaseAllFreeSlots()); + + const other = try pool.new(.{ .id = 2 }); + try std.testing.expect(original.index != other.index); + try std.testing.expectEqual(@as(usize, 1), pool.count()); + try std.testing.expectEqual(@as(usize, 2), pool.pool.items().len); + + try std.testing.expectEqual(@as(usize, 1), pool.trim()); + try std.testing.expectEqual(@as(usize, 0), pool.pendingDestroyCount()); + try std.testing.expectEqual(@as(usize, 1), pool.count()); + try std.testing.expectEqual(@as(usize, 1), pool.freeCount()); + try std.testing.expectEqual(@as(usize, 1), context.count); + try std.testing.expectEqual(@as(u32, 1), context.ids[0]); + + const replacement = try pool.new(.{ .id = 3 }); + try std.testing.expectEqual(original.index, replacement.index); + try std.testing.expect(original.generation != replacement.generation); +} + +const CascadeValue = struct { + id: u32, + childBits: ?u32 = null, +}; +const CascadePool = RefPoolAdvanced(CascadeValue, .{ .deferredDestruction = true }); +const CascadeContext = struct { + pool: *CascadePool, + ids: [4]u32 = undefined, + count: usize = 0, + + fn onDestroy(rawContext: ?*anyopaque, value: *CascadeValue) void { + const self: *@This() = @ptrCast(@alignCast(rawContext.?)); + self.ids[self.count] = value.id; + self.count += 1; + if (value.childBits) |bits| { + const child: CascadePool.Handle = @bitCast(bits); + std.debug.assert(self.pool.drop(child)); + } + } +}; + +test "deferred trim drains callback-triggered drops" { + var pool = try CascadePool.initCapacity(std.testing.allocator, 2); + defer pool.deinit(); + + var context: CascadeContext = .{ .pool = &pool }; + pool.registerOnDestroy(&context, CascadeContext.onDestroy); + + const child = try pool.new(.{ .id = 1 }); + const parent = try pool.new(.{ + .id = 2, + .childBits = @bitCast(child), + }); + + try std.testing.expect(pool.drop(parent)); + try std.testing.expectEqual(@as(usize, 1), pool.pendingDestroyCount()); + try std.testing.expectEqual(@as(usize, 2), pool.trim()); + try std.testing.expectEqual(@as(usize, 0), pool.count()); + try std.testing.expectEqual(@as(usize, 0), pool.pendingDestroyCount()); + try std.testing.expectEqual(@as(usize, 2), context.count); + try std.testing.expectEqual(@as(u32, 2), context.ids[0]); + try std.testing.expectEqual(@as(u32, 1), context.ids[1]); +} + +test "ref pool deinit destroys pending and still-pinned values" { + var pool = try DeferredTestPool.initCapacity(std.testing.allocator, 2); + var context: DestroyContext = .{}; + pool.registerOnDestroy(&context, DestroyContext.onDestroy); + + const pending = try pool.new(.{ .id = 1 }); + const pinned = try pool.new(.{ .id = 2 }); + try std.testing.expect(pool.pin(pinned)); + try std.testing.expect(pool.drop(pending)); + + pool.deinit(); + try std.testing.expectEqual(@as(usize, 2), context.count); + try std.testing.expectEqual(@as(u32, 1), context.ids[0]); + try std.testing.expectEqual(@as(u32, 2), context.ids[1]); +} + +test "ref pool reserves storage so immediate pin and drop never allocate" { + var allocatorState = std.testing.FailingAllocator.init(std.testing.allocator, .{}); + var pool = try TestPool.initCapacity(allocatorState.allocator(), 8); + defer pool.deinit(); + + const allocationsAfterReserve = allocatorState.allocations; + var handles: [8]TestPool.Handle = undefined; + for (&handles, 0..) |*handle, i| { + handle.* = try pool.new(.{ .id = @intCast(i) }); + try std.testing.expect(pool.pin(handle.*)); + } + try std.testing.expect(!pool.releaseAllFreeSlots()); + + for (handles) |handle| { + try std.testing.expect(pool.drop(handle)); + try std.testing.expect(pool.drop(handle)); + } + + try std.testing.expectEqual(allocationsAfterReserve, allocatorState.allocations); + try std.testing.expectEqual(@as(usize, 0), pool.count()); + try std.testing.expectEqual(pool.slotCount(), pool.freeCount()); + + try std.testing.expect(pool.releaseAllFreeSlots()); + const rebuilt = try pool.new(.{ .id = 99 }); + try std.testing.expectEqual(@as(TestPool.Pool.SlotIndex, 0), rebuilt.index); + try std.testing.expectEqual(@as(TestPool.Pool.Generation, 1), rebuilt.generation); +} + +test "ref pool reserves deferred drop and trim storage" { + var allocatorState = std.testing.FailingAllocator.init(std.testing.allocator, .{}); + var pool = try DeferredTestPool.initCapacity(allocatorState.allocator(), 8); + defer pool.deinit(); + + const allocationsAfterReserve = allocatorState.allocations; + var handles: [8]DeferredTestPool.Handle = undefined; + for (&handles, 0..) |*handle, i| { + handle.* = try pool.new(.{ .id = @intCast(i) }); + try std.testing.expect(pool.pin(handle.*)); + } + + for (handles) |handle| { + try std.testing.expect(pool.drop(handle)); + try std.testing.expect(pool.drop(handle)); + } + try std.testing.expectEqual(@as(usize, 0), pool.count()); + try std.testing.expectEqual(@as(usize, 8), pool.pendingDestroyCount()); + try std.testing.expectEqual(@as(usize, 0), pool.freeCount()); + + try std.testing.expectEqual(@as(usize, 8), pool.trim()); + try std.testing.expectEqual(allocationsAfterReserve, allocatorState.allocations); + try std.testing.expectEqual(pool.slotCount(), pool.freeCount()); + try std.testing.expect(pool.releaseAllFreeSlots()); +} + +test "ref pool reports immediate growth allocation failures" { + for (0..4) |failIndex| { + var failingState = std.testing.FailingAllocator.init(std.testing.allocator, .{ + .fail_index = failIndex, + }); + var pool = TestPool.init(failingState.allocator()); + defer pool.deinit(); + + try std.testing.expectError(error.OutOfMemory, pool.new(.{ .id = 1 })); + try std.testing.expectEqual(@as(usize, 0), pool.count()); + try std.testing.expectEqual(@as(usize, 0), pool.slotCount()); + try std.testing.expectEqual(@as(usize, 0), pool.freeCount()); + } +} + +test "ref pool reports deferred growth allocation failures" { + for (0..5) |failIndex| { + var failingState = std.testing.FailingAllocator.init(std.testing.allocator, .{ + .fail_index = failIndex, + }); + var pool = DeferredTestPool.init(failingState.allocator()); + defer pool.deinit(); + + try std.testing.expectError(error.OutOfMemory, pool.new(.{ .id = 1 })); + try std.testing.expectEqual(@as(usize, 0), pool.count()); + try std.testing.expectEqual(@as(usize, 0), pool.pendingDestroyCount()); + try std.testing.expectEqual(@as(usize, 0), pool.slotCount()); + try std.testing.expectEqual(@as(usize, 0), pool.freeCount()); + } +} + +test "ref pool rejects capacity beyond its handle index range" { + var pool = DeferredTestPool.init(std.testing.allocator); + defer pool.deinit(); + + try std.testing.expectError(error.PoolFull, pool.ensureTotalCapacity(DeferredTestPool.maxSlotCount + 1)); + try std.testing.expectEqual(@as(usize, 0), pool.count()); + try std.testing.expectEqual(@as(usize, 0), pool.pendingDestroyCount()); + try std.testing.expectEqual(@as(usize, 0), pool.slotCount()); +} diff --git a/engine/p2/src/structures/ref-string-map.zig b/engine/p2/src/structures/ref-string-map.zig new file mode 100644 index 0000000..f47923f --- /dev/null +++ b/engine/p2/src/structures/ref-string-map.zig @@ -0,0 +1,170 @@ +const std = @import("std"); +const string_pool = @import("string-pool.zig"); + +pub const RefString = string_pool.RefString; + +pub fn RefStringMap(comptime T: type) type { + return struct { + const Self = @This(); + const Map = std.StringHashMap(*Slot); + + pub const Slot = struct { + payload: T, + stringRef: RefString, + }; + + pub const AddError = std.mem.Allocator.Error || error{ + KeyAlreadyExists, + }; + + allocator: std.mem.Allocator, + map: Map, + + pub fn init(allocator: std.mem.Allocator) Self { + return .{ + .allocator = allocator, + .map = Map.init(allocator), + }; + } + + pub fn deinit(self: *Self) void { + self.clearRetainingCapacity(); + self.map.deinit(); + } + + pub fn deinitWithPayloadDeinit(self: *Self, comptime deinitPayload: fn (*T) void) void { + self.clearRetainingCapacityWithPayloadDeinit(deinitPayload); + self.map.deinit(); + } + + pub fn count(self: *const Self) usize { + return self.map.count(); + } + + pub fn contains(self: *const Self, key: RefString) bool { + return self.containsString(key.getUtf8()); + } + + pub fn containsString(self: *const Self, key: []const u8) bool { + return self.map.contains(key); + } + + pub fn get(self: *const Self, key: RefString) ?*T { + return self.getString(key.getUtf8()); + } + + pub fn getString(self: *const Self, key: []const u8) ?*T { + const slot = self.map.get(key) orelse return null; + return &slot.payload; + } + + pub fn getSlot(self: *const Self, key: RefString) ?*Slot { + return self.getSlotString(key.getUtf8()); + } + + pub fn getSlotString(self: *const Self, key: []const u8) ?*Slot { + return self.map.get(key); + } + + pub fn add(self: *Self, key: RefString, payload: T) AddError!*T { + if (self.contains(key)) return error.KeyAlreadyExists; + + const slot = try self.allocator.create(Slot); + errdefer self.allocator.destroy(slot); + + slot.* = .{ + .payload = payload, + .stringRef = key.pin(), + }; + errdefer slot.stringRef.drop(); + + try self.map.putNoClobber(slot.stringRef.getUtf8(), slot); + return &slot.payload; + } + + pub const putNoClobber = add; + + pub fn remove(self: *Self, key: RefString) ?T { + return self.removeString(key.getUtf8()); + } + + pub fn removeString(self: *Self, key: []const u8) ?T { + const removed = self.map.fetchRemove(key) orelse return null; + const slot = removed.value; + const payload = slot.payload; + slot.stringRef.drop(); + self.allocator.destroy(slot); + return payload; + } + + pub fn clearRetainingCapacity(self: *Self) void { + var iter = self.map.valueIterator(); + while (iter.next()) |slot_ptr| { + const slot = slot_ptr.*; + slot.stringRef.drop(); + self.allocator.destroy(slot); + } + self.map.clearRetainingCapacity(); + } + + pub fn clearRetainingCapacityWithPayloadDeinit(self: *Self, comptime deinitPayload: fn (*T) void) void { + var iter = self.map.valueIterator(); + while (iter.next()) |slot_ptr| { + const slot = slot_ptr.*; + deinitPayload(&slot.payload); + slot.stringRef.drop(); + self.allocator.destroy(slot); + } + self.map.clearRetainingCapacity(); + } + + pub const ValueIterator = struct { + inner: Map.ValueIterator, + + pub fn next(self: *@This()) ?*T { + const slot_ptr = self.inner.next() orelse return null; + return &slot_ptr.*.payload; + } + }; + + pub fn valueIterator(self: *const Self) ValueIterator { + return .{ .inner = self.map.valueIterator() }; + } + + pub const SlotIterator = struct { + inner: Map.ValueIterator, + + pub fn next(self: *@This()) ?*Slot { + const slot_ptr = self.inner.next() orelse return null; + return slot_ptr.*; + } + }; + + pub fn slotIterator(self: *const Self) SlotIterator { + return .{ .inner = self.map.valueIterator() }; + } + }; +} + +test "RefStringMap pins keys and removes payloads" { + try string_pool.setup(std.testing.allocator, std.testing.io); + defer string_pool.shutdown(); + + var map = RefStringMap(u32).init(std.testing.allocator); + defer map.deinit(); + + const key = try RefString.new("alpha"); + const value = try map.add(key, 42); + key.drop(); + + try std.testing.expectEqual(@as(u32, 42), value.*); + try std.testing.expectEqual(@as(usize, 1), map.count()); + try std.testing.expect(map.containsString("alpha")); + try std.testing.expectEqual(@as(u32, 42), map.getString("alpha").?.*); + + const lookup = try RefString.new("alpha"); + defer lookup.drop(); + const removed = map.remove(lookup).?; + try std.testing.expectEqual(@as(u32, 42), removed); + try std.testing.expectEqual(@as(usize, 0), map.count()); +} diff --git a/engine/p2/src/structures/ring-queue.zig b/engine/p2/src/structures/ring-queue.zig new file mode 100644 index 0000000..50dc1a8 --- /dev/null +++ b/engine/p2/src/structures/ring-queue.zig @@ -0,0 +1,259 @@ +const std = @import("std"); +const stats = @import("stats.zig"); + +pub const RingQueueError = error{ + QueueIsFull, + QueueIsEmpty, + AllocSizeTooSmall, + OutOfMemory, +}; + +// managed version of the ringqueue, includes a mutex +pub fn RingQueue(comptime T: type) type { + return struct { + const _InnerType = RingQueueU(T); + + queue: _InnerType, + allocator: std.mem.Allocator, + io_context: std.Io, + mutex: std.Io.Mutex = .init, + + pub fn init(allocator: std.mem.Allocator, io_context: std.Io, size: usize) !@This() { + const newSelf = @This(){ + .queue = try _InnerType.init(allocator, size), + .allocator = allocator, + .io_context = io_context, + .mutex = .init, + }; + + return newSelf; + } + + pub fn io(self: *const @This()) std.Io { + return self.io_context; + } + + pub fn pushLocked(self: *@This(), newValue: T) RingQueueError!void { + self.mutex.lockUncancelable(self.io()); + defer self.mutex.unlock(self.io()); + try self.queue.push(newValue); + } + + // only call this if you have locked already + pub fn popFromUnlocked(self: *@This()) ?T { + return self.queue.pop(); + } + + pub fn lock(self: *@This()) void { + self.mutex.lockUncancelable(self.io()); + } + + pub fn unlock(self: *@This()) void { + self.mutex.unlock(self.io()); + } + + pub fn popFromLocked(self: *@This()) ?T { + self.mutex.lockUncancelable(self.io()); + defer self.mutex.unlock(self.io()); + const val = self.queue.pop(); + return val; + } + + pub fn allowRegrow(self: *@This()) void { + self.queue.allowRegrow(); + } + + pub fn count(self: @This()) usize { + return self.queue.count(); + } + + pub fn getStatistics(self: *const @This()) stats.PoolStatistics { + return self.queue.getStatistics(); + } + + pub fn deinit(self: *@This()) void { + self.queue.deinit(self.allocator); + } + }; +} + +// tail points to next free +// head points to next one to read +// unmanaged ring queue +pub fn RingQueueU(comptime T: type) type { + return struct { + allocator: std.mem.Allocator = undefined, + buffer: []T = undefined, + head: usize = 0, // resets upon resizes + tail: usize = 0, // resets upon resizes + regrow_allowed: bool = false, + + pub fn init(allocator: std.mem.Allocator, size: usize) !@This() { + const self = @This(){ + .allocator = allocator, + .buffer = try allocator.alloc(T, size + 1), + }; + + return self; + } + + pub fn allowRegrow(self: *@This()) void { + self.regrow_allowed = true; + } + + fn growCapacity(self: *@This()) !void { + const current_capacity = self.capacity(); + const new_capacity = if (current_capacity == 0) 1 else current_capacity * 2; + try self.resize(self.allocator, new_capacity); + } + + pub fn push(self: *@This(), value: T) RingQueueError!void { + var next = (self.tail + 1) % self.buffer.len; + + if (next == self.head) { + if (!self.regrow_allowed) { + return error.QueueIsFull; + } + try self.growCapacity(); + next = (self.tail + 1) % self.buffer.len; + } + self.buffer[self.tail] = value; + self.tail = next; + } + + pub fn pushFront(self: *@This(), value: T) !void { + var iHead = @as(isize, @intCast(self.head)) - 1; + + if (iHead < 0) { + iHead = @as(isize, @intCast(self.buffer.len)) + iHead; + } + + if (iHead == @as(isize, @intCast(self.tail))) { + if (!self.regrow_allowed) { + return error.QueueIsFull; + } + try self.growCapacity(); + iHead = @as(isize, @intCast(self.buffer.len)) - 1; + } + + self.head = @as(usize, @intCast(iHead)); + self.buffer[self.head] = value; + } + + pub fn count(self: @This()) usize { + if (self.head == self.tail) + return 0; + + if (self.head < self.tail) + return self.tail - self.head; + + // head > tail means we looped around. + return (self.buffer.len - self.head) + self.tail; + } + + pub fn pop(self: *@This()) ?T { + if (self.head == self.tail) + return null; + + const r = self.buffer[self.head]; + self.head = ((self.head + 1) % self.buffer.len); + + return r; + } + + pub fn peek(self: *@This()) ?*T { + return self.at(0); + } + + pub fn peekBack(self: @This()) ?*T { + return self.atBack(1); + } + + // reference an element at an offset from the back of the queue + // similar to python's negative number syntax. + // gets you an element at an offset from the tail. + // given the way the tail works, this will return null on zero + pub fn atBack(self: @This(), offset: usize) ?*T { + const c = self.count(); + + if (offset > c or offset == 0) { + return null; + } + + var x: isize = @as(isize, @intCast(self.tail)) - @as(isize, @intCast(offset)); + + if (x < 0) { + x = @as(isize, @intCast(self.buffer.len)) + x; + } + + return &self.buffer[@as(usize, @intCast(x))]; + } + + pub fn at(self: *@This(), offset: usize) ?*T { + const c = self.count(); + + if (c == 0) { + return null; + } + + if (offset >= c) { + return null; + } + + const index = (self.head + offset) % self.buffer.len; + + return &self.buffer[index]; + } + + // returns the number of elements this buffer can hold. + // you should rarely ever need to use this. + pub fn capacity(self: *@This()) usize { + return self.buffer.len - 1; + } + + pub fn getStatistics(self: *const @This()) stats.PoolStatistics { + return .{ + .statName = "RingQueue", + .instanceCount = self.count(), + .memoryReserved = self.buffer.len * @sizeOf(T), + .memoryUsed = self.count() * @sizeOf(T), + }; + } + + pub fn resize(self: *@This(), allocator: std.mem.Allocator, size: usize) !void { + const c = self.count(); + + // new size needs to be greater than current size by 1, tail always points to an empty + if (c >= size) { + return error.AllocSizeTooSmall; + } + + var buffer: []T = try allocator.alloc(T, size + 1); + var index: usize = 0; + + while (self.pop()) |v| { + buffer[index] = v; + index += 1; + } + + allocator.free(self.buffer); + + self.buffer = buffer; + self.head = 0; + self.tail = index; + } + + pub fn isEmpty(self: @This()) bool { + return self.head == self.tail; + } + + pub fn empty(self: *@This()) void { + self.head = 0; + self.tail = 0; + } + + pub fn deinit(self: *@This(), allocator: std.mem.Allocator) void { + allocator.free(self.buffer); + } + }; +} diff --git a/engine/p2/src/structures/samplegun.json b/engine/p2/src/structures/samplegun.json new file mode 100644 index 0000000..59422d8 --- /dev/null +++ b/engine/p2/src/structures/samplegun.json @@ -0,0 +1,33 @@ +{ + "attributes" : { + "target_uri": "mesh:/exopunk/guns/samplegun", + "magazine_uri": "mesh:/exopunk/guns/samplegun_magazine" + }, + "materials" : [ + { + "material_name" : "gun body", + "master" : "opaque", + "albedo" : "texture:/exopunk/guns/samplegun_albedo", + "triple" : "texture:/exopunk/guns/samplegun_triple" + }, + { + "material_name" : "scope", + "master" : "transparent", + "albedo" : "texture:/exopunk/guns/samplegun_scope" + } + ], + "sockets" : [ + { + "name": "socket_muzzle", + "pos": [1, 2, 3] + }, + { + "name": "socket_magazine", + "pos": [1, 2, 3] + }, + { + "name": "socket_sights", + "pos": [1, 2, 3] + } + ] +} diff --git a/engine/p2/src/structures/spans.zig b/engine/p2/src/structures/spans.zig new file mode 100644 index 0000000..db51a0b --- /dev/null +++ b/engine/p2/src/structures/spans.zig @@ -0,0 +1,293 @@ +const std = @import("std"); +const PagedVector = @import("paged-vector.zig").PagedVector; + +pub const Span = struct { + start: u32, + size: u32, + + pub fn end(self: @This()) u32 { + return self.start + self.size; + } +}; + +pub const SpanHandle = struct { + _index: i32 = 0, +}; + +pub const AllocatedSpan = struct { + handle: SpanHandle, + span: Span, +}; + +pub const MergedSpan = struct { + start: u32, + end: u32, // points to one-past-the-end, invalid to deref + index: u32, + next: ?*MergedSpan = null, +}; + +pub const MergedSpans = struct { + list: ?*MergedSpan, + free_list: ?*MergedSpan, + capacity: u32, + available: u32, + spans: PagedVector(MergedSpan), + + pub fn init(allocator: std.mem.Allocator, capacity: u32) !@This() { + return .{ + .list = null, + .free_list = null, + .spans = try PagedVector(MergedSpan).init(allocator), + .capacity = capacity, + .available = capacity, + }; + } + + pub fn allocate(self: *@This(), size: u32) !Span { + + // 1. find the first gap that matches the size + // 2. create a span from that gap and call addSpan on it. + var newSpan: ?Span = null; + var predecessor: ?*MergedSpan = null; + + if (self.list) |list| { + if (list.start >= size) { + newSpan = .{ .start = 0, .size = size }; + } else { + var iter: ?*MergedSpan = list; + + while (iter) |p| : (iter = p.next) { + const gapStart = p.end; + var gapSize = self.capacity - gapStart; + if (p.next) |_next| { + const next: *MergedSpan = _next; + gapSize = next.start - p.end; + } + + if (gapSize >= size) { + predecessor = p; + newSpan = .{ .start = gapStart, .size = size }; + break; + } + } + } + } else { + // handle special case where we are empty and nothing is used. + if (size <= self.capacity) { + newSpan = .{ .start = 0, .size = size }; + } + } + + if (newSpan) |n| { + try self.addSpan(n, predecessor); + return n; + } + + return error.OutOfMemory; + } + + pub fn addSpan(self: *@This(), span: Span, predecessor: ?*MergedSpan) !void { + + // update stats + self.available -= span.size; + + // if the predecessor is null, this is the first span that we have, just set it and move on. + if (predecessor) |p| { + // if we're touching the end of one span, grow that one. + if (p.end == span.start) { + p.end += span.size; + + if (p.next) |next| { + if (next.start == span.start + span.size) { + // delete the next one and update predecessor's end to the next one + p.end = next.end; + p.next = next.next; + + self.removeMergedSpan(next); + } + } + } else if (p.next) |next| { + // if we're touching the start of one span, grow that one + if (next.start == span.start + span.size) { + next.start = span.start; + } + } else { + // if neither, then, create a new + const newSpan = try self.createMergedSpan(.{ + .start = span.start, + .end = span.start + span.size, + .next = p.next, + .index = 0, + }); + p.next = newSpan; + } + } else if (self.list) |list| { + if (span.end() == list.start) { + list.start = span.start; + } else { + self.list = try self.createMergedSpan(.{ + .start = span.start, + .end = span.end(), + .next = list, + .index = 0, + }); + } + } else { + self.list = try self.createMergedSpan(.{ + .start = span.start, + .end = span.end(), + .next = null, + .index = 0, + }); + } + } + + fn createMergedSpan(self: *@This(), value: MergedSpan) !*MergedSpan { + if (self.free_list) |node| { + self.free_list = node.next; + node.* = value; + return node; + } + + const index = self.spans.len(); + const node = try self.spans.appendAndGet(value); + node.index = @intCast(index); + return node; + } + + fn removeMergedSpan(self: *@This(), remove: *MergedSpan) void { + remove.* = .{ + .start = 0, + .end = 0, + .index = remove.index, + .next = self.free_list, + }; + self.free_list = remove; + } + + pub fn debugSpanCount(self: @This()) u32 { + var i: u32 = 0; + var iter = self.list; + + while (iter) |p| : (iter = p.next) { + i += 1; + } + + return i; + } + + pub fn removeSpan(self: *@This(), span: Span) void { + if (span.size == 0) return; + + const remove_start = span.start; + const remove_end = span.end(); + var released: u32 = 0; + var predecessor: ?*MergedSpan = null; + var iter = self.list; + + while (iter) |node| { + const next = node.next; + if (remove_end <= node.start) break; + if (remove_start >= node.end) { + predecessor = node; + iter = next; + continue; + } + + const overlap_start = @max(remove_start, node.start); + const overlap_end = @min(remove_end, node.end); + if (overlap_end > overlap_start) { + released += overlap_end - overlap_start; + } + + if (remove_start <= node.start and remove_end >= node.end) { + if (predecessor) |prev| { + prev.next = next; + } else { + self.list = next; + } + self.removeMergedSpan(node); + iter = next; + continue; + } + + if (remove_start <= node.start) { + node.start = remove_end; + break; + } + + if (remove_end >= node.end) { + node.end = remove_start; + predecessor = node; + iter = next; + continue; + } + + const tail = self.createMergedSpan(.{ + .start = remove_end, + .end = node.end, + .next = node.next, + .index = 0, + }) catch unreachable; + node.end = remove_start; + node.next = tail; + break; + } + + self.available += released; + } + + pub fn deinit(self: *@This()) void { + self.spans.deinit(); + } +}; + +test "span allocation" { + const allocator = std.testing.allocator; + var spans = try MergedSpans.init(allocator, 4096); + defer spans.deinit(); + + const newSpan: Span = try spans.allocate(16); + try std.testing.expectEqual(0, newSpan.start); + try std.testing.expectEqual(16, newSpan.size); + + const newSpan2: Span = try spans.allocate(16); + try std.testing.expectEqual(16, newSpan2.start); + try std.testing.expectEqual(16, newSpan2.start); + + const newSpan3: Span = try spans.allocate(16); + try std.testing.expectEqual(32, newSpan3.start); + try std.testing.expectEqual(16, newSpan3.size); + + try std.testing.expectEqual(spans.debugSpanCount(), 1); + + const newSpan4: Span = try spans.allocate(16); + try std.testing.expectEqual(48, newSpan4.start); + try std.testing.expectEqual(16, newSpan4.size); + + spans.removeSpan(.{ .start = 12, .size = 4 }); + try std.testing.expectEqual(2, spans.debugSpanCount()); + + const newSpan5: Span = try spans.allocate(4); + try std.testing.expectEqual(12, newSpan5.start); + try std.testing.expectEqual(4, newSpan5.size); + try std.testing.expectEqual(1, spans.debugSpanCount()); + + spans.removeSpan(.{ .start = 12, .size = 1 }); + spans.removeSpan(.{ .start = 14, .size = 1 }); + try std.testing.expectEqual(3, spans.debugSpanCount()); + + _ = try spans.allocate(1); + _ = try spans.allocate(1); + + try std.testing.expectEqual(1, spans.debugSpanCount()); + + const available_before_full_remove = spans.available; + spans.removeSpan(newSpan); + try std.testing.expectEqual(1, spans.debugSpanCount()); + try std.testing.expectEqual(available_before_full_remove + newSpan.size, spans.available); + + const reused_full_remove = try spans.allocate(newSpan.size); + try std.testing.expectEqual(newSpan.start, reused_full_remove.start); + try std.testing.expectEqual(newSpan.size, reused_full_remove.size); +} diff --git a/engine/p2/src/structures/sparse-set.zig b/engine/p2/src/structures/sparse-set.zig new file mode 100644 index 0000000..e724a76 --- /dev/null +++ b/engine/p2/src/structures/sparse-set.zig @@ -0,0 +1,885 @@ +const std = @import("std"); +const stats = @import("stats.zig"); + +const ArrayList = std.ArrayList; +const ArrayListUnmanaged = std.ArrayListUnmanaged; + +// can be index by an 18 bit value, and 262144 of anything ought to be enough... right? +pub const DefaultSparseSize = 262144 / 2; + +pub fn SparseSet(comptime T: type) type { + return SparseSetAdvanced(T, DefaultSparseSize); +} + +pub const IndexType = u24; +pub const GenerationType = u7; + +pub const SetHandle = packed struct(u32) { + index: IndexType = 0, + generation: GenerationType = 0, + alive: bool = false, + + pub fn hash(self: @This()) u32 { + return @as(u32, @bitCast(self)); + } + + pub fn eql(self: @This(), other: @This()) bool { + return self.hash() == other.hash(); + } +}; + +pub fn SparseMultiSet(comptime T: type) type { + return SparseMultiSetAdvanced(T, DefaultSparseSize); +} + +pub const ContainerListener = struct { + ptr: *anyopaque, + onHandleRemoved: *const fn (*anyopaque, u32, SetHandle) void, + onHandleAdded: *const fn (*anyopaque, u32, SetHandle) void, +}; + +// works by converting a datastructure into an AOS type. +pub fn SparseMultiSetAdvanced(comptime T: type, comptime SparseSize: u32) type { + return struct { + pub const SetType = std.MultiArrayList(T); + + pub const InnerType = T; + + allocator: std.mem.Allocator, + denseIndices: ArrayListUnmanaged(SetHandle), + dense: SetType, + sparse: []SetHandle, + containerID: u32 = 0, + containerListener: ?ContainerListener = null, + opCount: u32 = 0, + + pub const Field = SetType.Field; + pub const Slice = SetType.Slice; + + pub const IsMultiset = true; + + pub const StableReferences = false; + + pub fn init(allocator: std.mem.Allocator) @This() { + var self = @This(){ + .allocator = allocator, + .denseIndices = .empty, + .dense = .empty, + .sparse = allocator.alloc(SetHandle, SparseSize) catch unreachable, + }; + + for (self.sparse, 0..) |_, i| { + self.sparse[i] = .{ .generation = 0, .index = 0x0, .alive = false }; + } + + return self; + } + + pub fn create(allocator: std.mem.Allocator) !*@This() { + const self = try allocator.create(@This()); + self.* = init(allocator); + + return self; + } + + pub fn destroy(self: *@This()) void { + const allocator = self.allocator; + self.deinit(); + allocator.destroy(self); + } + + pub fn denseItems(self: *@This(), comptime field: Field) []FieldType(field) { + return self.dense.items(field); + } + + pub fn deinit(self: *@This()) void { + self.dense.deinit(self.allocator); + self.denseIndices.deinit(self.allocator); + self.allocator.free(self.sparse); + } + + pub fn getStatistics(self: *const @This()) stats.PoolStatistics { + return .{ + .statName = "SparseMultiSet", + .instanceCount = self.dense.len, + .memoryReserved = self.dense.capacity * @sizeOf(T) + + self.denseIndices.capacity * @sizeOf(SetHandle) + + self.sparse.len * @sizeOf(SetHandle), + .memoryUsed = self.dense.len * @sizeOf(T) + + self.denseIndices.items.len * @sizeOf(SetHandle) + + self.sparse.len * @sizeOf(SetHandle), + }; + } + + pub fn readDense(self: @This(), offset: usize, comptime field: Field) *const FieldType(field) { + return &self.dense.items(field)[offset]; + } + + pub fn getDense(self: *@This(), offset: usize, comptime field: Field) *FieldType(field) { + return &self.dense.items(field)[offset]; + } + + // ----- sparse set features ----- + + pub fn handleFromSparseIndex(self: @This(), sparseIndex: IndexType) SetHandle { + var handle: SetHandle = self.sparse[@as(usize, @intCast(sparseIndex))]; + handle.index = sparseIndex; + return handle; + } + + pub fn sparseToDense(self: @This(), handle: SetHandle) ?usize { + const denseHandle = self.sparse[@as(usize, @intCast(handle.index))]; + + // todo: need to update generation + if (denseHandle.generation != handle.generation) // tombstone value + { + // Generation mismatch, this handle is totally dead. + return null; + } + + if (denseHandle.alive == false) { + return null; + } + + const denseIndex = @as(usize, @intCast(denseHandle.index)); + + if (denseIndex >= self.denseIndices.items.len) { + return null; + } + + return denseIndex; + } + + pub fn FieldType(comptime field: Field) type { + return std.meta.fieldInfo(T, field).type; + } + + pub fn get(self: *@This(), handle: SetHandle, comptime field: Field) ?*FieldType(field) { + const denseIndex = self.sparseToDense(handle) orelse return null; + return &self.dense.items(field)[denseIndex]; + } + + // the idea behind a sparse array is that the sethandle is + // highly stable. + // if this container is registered as part of an ECS, this is unsafe to call directly + pub fn createObject(self: *@This(), initValue: T) !SetHandle { + var newSparseIndex = newRandomIndex(); + + var denseHandle = self.sparse[@as(usize, @intCast(newSparseIndex))]; + + while (denseHandle.alive == true) { + newSparseIndex = newRandomIndex(); + denseHandle = self.sparse[@as(usize, @intCast(newSparseIndex))]; + } + const generation = (denseHandle.generation + 1) % (std.math.maxInt(GenerationType)); + + return self.createObjectInternal(initValue, newSparseIndex, generation); + } + + pub fn createObjectInternal(self: *@This(), initValue: T, newSparseIndex: IndexType, generation: GenerationType) !SetHandle { + const newDenseIndex = self.denseIndices.items.len; + self.sparse[@as(usize, @intCast(newSparseIndex))] = SetHandle{ + .alive = true, + .generation = @as(GenerationType, @intCast(generation)), + .index = @as(IndexType, @intCast(newDenseIndex)), + }; + + const setHandle = SetHandle{ + .alive = true, + .generation = generation, + .index = newSparseIndex, + }; + + try self.denseIndices.append(self.allocator, setHandle); + try self.dense.append(self.allocator, initValue); + std.debug.assert(self.sparse[newSparseIndex].index < self.dense.len); + self.opCount +%= 1; + + if (self.containerListener) |l| { + l.onHandleAdded(l.ptr, @intCast(self.containerID), setHandle); + } + + return setHandle; + } + + pub fn denseToSparse(self: @This(), dense: u32) SetHandle { + return self.denseIndices.items[dense]; + } + + pub fn createWithHandle(self: *@This(), handle: SetHandle, initValue: T) !SetHandle { + const currentDenseHandle = self.sparse[handle.index]; + if (currentDenseHandle.alive) { + return error.ObjectAlreadyExists; + } + + return self.createObjectInternal(initValue, handle.index, handle.generation); + } + + pub fn destroyObject(self: *@This(), handle: SetHandle) bool { + // to destroy an object + // get handle and get the dense position, swap and remove. + // Then insert the tombstone value into the sparse handle + + // if this fails it means the object is already destroyed + const denseIndex = self.sparseToDense(handle) orelse return false; + + // get the indec of the last object in the dense set + const tailDenseIndex = self.dense.len - 1; + + // get the sparse index of the last object + const sparseIndexToSwap = self.denseIndices.items[tailDenseIndex]; + + // redirect the sparse index to the new position of the swapped object. + self.sparse[@as(usize, @intCast(sparseIndexToSwap.index))].index = @as(IndexType, @intCast(denseIndex)); + + // perform the swap and remove, mark the tombstone as well. + _ = self.dense.swapRemove(denseIndex); + _ = self.denseIndices.swapRemove(denseIndex); + self.sparse[@as(usize, @intCast(handle.index))].alive = false; + self.opCount +%= 1; + + if (self.containerListener) |l| { + l.onHandleRemoved(l.ptr, self.containerID, handle); + } + + return true; + } + + var prng = std.Random.DefaultPrng.init(0x1234); + var rand = prng.random(); + + pub fn newRandomIndex() IndexType { + if (SparseSize == std.math.maxInt(IndexType)) { + return rand.int(IndexType); + } + + return rand.int(IndexType) % @as(IndexType, @intCast(SparseSize)); + } + + // ecs interface + + pub const EcsContainerInterfaceVTable = EcsContainerInterface.Implement(@This()); + + pub fn handleExists(self: @This(), handle: SetHandle) bool { + return self.sparseToDense(handle) != null; + } + + pub fn getContainerID(self: @This()) u32 { + return self.containerID; + } + + pub fn onRegister(self: *@This(), id: u32, listener: ContainerListener) void { + self.containerID = id; + self.containerListener = listener; + } + + pub fn evictFromRegistry(self: *@This()) void { + self.containerListener = null; + } + + pub fn getStateCount(self: @This()) u32 { + return self.opCount; + } + + // replaces get. + // really nasty trick here. I'm relying on absolutely fucked aliasing + // for sparse-multiset + // which is not a type which can be represented in lua directly. + // rather the resulting component type should be a THIN component + // which only contains the handle. + // + // Zig MAY break this in the future. in which case I'll have to + // treat the sparse sets in this handle as C ABI with a fixed bit layout + pub fn getHandleRef(self: @This(), handle: SetHandle) *SetHandle { + if (self.handleExists(handle)) { + // std.debug.print("get: {p}\n", .{@as(*anyopaque, @ptrCast(&self.sparse[handle.index]))}); + return &self.sparse[handle.index]; + } + @panic("uh oh "); + } + + pub fn createWithHandleECS(self: *@This(), handle: SetHandle) *SetHandle { + _ = self.createWithHandle(handle, .{}) catch @panic("unable to create with handle"); + + return self.getHandleRef(handle); + } + + pub const ContainerTypeName = "SparseMultiSet"; + }; +} + +// A quick little sparse set implementation, this feeds the core of the +// ECS. A sparse set provides Constant time random access to a range of objects through stable handles +// While providing dense memory locality for iterating. +// +// should probably never use this one outside of the base-set for checking entity existence. +pub fn SparseSetAdvanced(comptime T: type, comptime SparseSize: u32) type { + return struct { + const DenseEntry = struct { + value: T, + sparseIndex: SetHandle, + }; + + allocator: std.mem.Allocator, + dense: ArrayListUnmanaged(DenseEntry), + sparse: []SetHandle, + + containerID: u32 = 0, + containerListener: ?ContainerListener = null, + opCount: u32 = 0, + + pub const StableReferences = false; + pub const InnerType = T; + + pub fn getStateCount(self: @This()) u32 { + return self.opCount; + } + + pub fn handleFromSparseIndex(self: @This(), sparseIndex: IndexType) SetHandle { + var handle: SetHandle = self.sparse[@as(usize, @intCast(sparseIndex))]; + handle.index = sparseIndex; + return handle; + } + + pub fn create(allocator: std.mem.Allocator) !*@This() { + const self = try allocator.create(@This()); + self.* = init(allocator); + return self; + } + + pub fn destroy(self: *@This()) void { + self.deinit(); + self.allocator.destroy(self); + } + + pub fn init(allocator: std.mem.Allocator) @This() { + var self = @This(){ + .allocator = allocator, + .dense = .empty, + .sparse = allocator.alloc(SetHandle, SparseSize) catch unreachable, + }; + + for (self.sparse, 0..) |_, i| { + self.sparse[i] = .{ .generation = 0, .index = 0x0, .alive = false }; + } + + return self; + } + + pub fn readDense(self: @This(), offset: usize) *const T { + return &self.dense.items[offset].value; + } + + pub fn getDense(self: *@This(), offset: usize) *T { + return &self.dense.items[offset].value; + } + + pub fn count(self: @This()) usize { + return self.dense.items.len; + } + + pub fn ensureUnusedCapacity(self: *@This(), additionalCount: usize) !void { + try self.dense.ensureUnusedCapacity(self.allocator, additionalCount); + } + + pub fn sparseToDense(self: @This(), handle: SetHandle) ?usize { + const denseHandle = self.sparse[@as(usize, @intCast(handle.index))]; + + // todo: need to update generation + if (denseHandle.generation != handle.generation) // tombstone value + { + // Generation mismatch, this handle is totally dead. + return null; + } + + if (denseHandle.alive == false) { + return null; + } + + const denseIndex = @as(usize, @intCast(denseHandle.index)); + + if (denseIndex >= self.dense.items.len) { + return null; + } + + return denseIndex; + } + + pub fn get(self: @This(), handle: SetHandle) ?*T { + const denseIndex = self.sparseToDense(handle) orelse return null; + return &self.dense.items[denseIndex].value; + } + + pub fn destroyObject(self: *@This(), handle: SetHandle) void { + // to destroy an object + // get handle and get the dense position, swap and remove. + // Then insert the tombstone value into the sparse handle + + if (@hasDecl(T, "deinitECS")) { + self.get(handle).?.deinitECS(handle); + } + + const denseIndex = self.sparseToDense(handle) orelse return; + const tailDenseIndex = self.dense.items.len - 1; + const sparseIndexToSwap = self.dense.items[tailDenseIndex].sparseIndex; + self.opCount +%= 1; + + self.sparse[@as(usize, @intCast(sparseIndexToSwap.index))].index = @as(IndexType, @intCast(denseIndex)); + + _ = self.dense.swapRemove(denseIndex); + self.sparse[@as(usize, @intCast(handle.index))].alive = false; + + if (self.containerListener) |l| { + l.onHandleRemoved(l.ptr, self.containerID, handle); + } + } + + var prng = std.Random.DefaultPrng.init(0x1234); + var rand = prng.random(); + + fn newRandomIndex() IndexType { + if (SparseSize == std.math.maxInt(IndexType)) { + return rand.int(IndexType); + } + + return rand.int(IndexType) % @as(IndexType, @intCast(SparseSize)); + } + + // the idea behind a sparse array is that the sethandle is + // highly stable. + pub fn createObject(self: *@This(), initValue: T) !SetHandle { + var newSparseIndex = newRandomIndex(); + self.opCount +%= 1; + + var denseHandle = self.sparse[@as(usize, @intCast(newSparseIndex))]; + + while (denseHandle.alive == true) { + newSparseIndex = newRandomIndex(); + denseHandle = self.sparse[@as(usize, @intCast(newSparseIndex))]; + } + + const generation = (denseHandle.generation + 1) % (std.math.maxInt(GenerationType)); + const newDenseIndex = self.dense.items.len; + + const sparseToDenseHandle = SetHandle{ + .alive = true, + .generation = @as(GenerationType, @intCast(generation)), + .index = @as(IndexType, @intCast(newDenseIndex)), + }; + + const denseToSparseHandle = SetHandle{ + .alive = true, + .generation = @as(GenerationType, @intCast(generation)), + .index = @as(IndexType, @intCast(newSparseIndex)), + }; + + try self.dense.append(self.allocator, .{ + .value = initValue, + .sparseIndex = denseToSparseHandle, + }); + + self.sparse[@as(usize, @intCast(newSparseIndex))] = sparseToDenseHandle; + + const setHandle = SetHandle{ + .alive = true, + .generation = generation, + .index = newSparseIndex, + }; + + return setHandle; + } + + pub const ConstructResult = struct { + ptr: *T, + handle: SetHandle, + }; + + // Will fail if the handle already exists. + pub fn createWithHandle(self: *@This(), handle: SetHandle, initValue: T) !ConstructResult { + if (handle.index >= DefaultSparseSize) { + std.debug.print("this should never happen handle index is huge: {x} {d}\n", .{ handle.index, handle.index }); + @panic("impossible handle"); + } + var currentDenseHandle = self.sparse[handle.index]; + if (currentDenseHandle.alive) { + return error.ObjectAlreadyExists; + } + currentDenseHandle.generation = handle.generation; + currentDenseHandle.alive = true; + + return try self.createAndGetInternal(currentDenseHandle, handle.index, initValue, false); + } + + pub fn createWithHandleECS(self: *@This(), handle: SetHandle) *T { + const rv = (self.createWithHandle(handle, .{}) catch @panic("unable to create")).ptr; + + if (@hasDecl(T, "initECS")) { + rv.initECS(handle); + } + return rv; + } + + fn createAndGetInternal(self: *@This(), denseHandle: SetHandle, sparseIndex: IndexType, initValue: T, comptime bumpGeneration: bool) !ConstructResult { + const newDenseIndex = self.dense.items.len; + try self.dense.append(self.allocator, .{ + .value = initValue, + .sparseIndex = .{ + .index = sparseIndex, + .generation = denseHandle.generation, + .alive = true, + }, + }); + + var generation = denseHandle.generation; + + if (bumpGeneration) { + generation = (generation + 1) % (std.math.maxInt(GenerationType)); + } + + self.sparse[@as(usize, @intCast(sparseIndex))] = SetHandle{ + .alive = true, + .generation = @as(GenerationType, @intCast(generation)), + .index = @as(IndexType, @intCast(newDenseIndex)), + }; + + const setHandle = SetHandle{ + .alive = true, + .generation = generation, + .index = sparseIndex, + }; + + const rv = ConstructResult{ + .ptr = &self.dense.items[@as(usize, @intCast(newDenseIndex))].value, + .handle = setHandle, + }; + + if (self.containerListener) |l| { + l.onHandleAdded(l.ptr, self.containerID, setHandle); + } + + return rv; + } + + pub fn createAndGet(self: *@This(), initValue: T) !ConstructResult { + var newSparseIndex = newRandomIndex(); + + var denseHandle = self.sparse[@as(usize, @intCast(newSparseIndex))]; + + while (denseHandle.alive == true) { + newSparseIndex = newRandomIndex(); + denseHandle = self.sparse[@as(usize, @intCast(newSparseIndex))]; + } + + return try self.createAndGetInternal(denseHandle, newSparseIndex, initValue, true); + } + + pub fn deinit(self: *@This()) void { + self.allocator.free(self.sparse); + self.dense.deinit(self.allocator); + } + + pub fn getStatistics(self: *const @This()) stats.PoolStatistics { + return .{ + .statName = "SparseSet", + .instanceCount = self.dense.items.len, + .memoryReserved = self.dense.capacity * @sizeOf(DenseEntry) + + self.sparse.len * @sizeOf(SetHandle), + .memoryUsed = self.dense.items.len * @sizeOf(DenseEntry) + + self.sparse.len * @sizeOf(SetHandle), + }; + } + + pub const EcsContainerInterfaceVTable = EcsContainerInterface.Implement(@This()); + + pub fn handleExists(self: @This(), handle: SetHandle) bool { + return self.sparseToDense(handle) != null; + } + + pub fn getContainerID(self: @This()) u32 { + return self.containerID; + } + + pub fn onRegister(self: *@This(), id: u32, listener: ContainerListener) void { + self.containerID = id; + self.containerListener = listener; + } + + // might never need to call this one... + pub fn evictFromRegistry(self: *@This()) void { + self.containerListener = null; + } + + pub const ContainerTypeName = "SparseSet"; + }; +} + +// slowish look-up, fast-ish iteration time, +// very little memory overhead, stable pointers +// good all-around choice if you have a small +// number of these objects around, and the object itself is quite big. +pub fn SparseMap(comptime T: type) type { + return struct { + backingAllocator: std.mem.Allocator, + arena: std.heap.ArenaAllocator, + + map: std.AutoHashMapUnmanaged(SetHandle, *T) = .empty, + listEntriesByHandle: std.AutoHashMapUnmanaged(SetHandle, u32) = .empty, + list: std.ArrayListUnmanaged(*T) = .empty, + handles: std.ArrayListUnmanaged(SetHandle) = .empty, + containerID: u32 = 0, + containerListener: ?ContainerListener = null, + opCount: u32 = 0, + + pub const InnerType = T; + pub const StableReferences = true; + + pub fn create(backingAllocator: std.mem.Allocator) !*@This() { + const self = try backingAllocator.create(@This()); + + self.* = .{ + .arena = std.heap.ArenaAllocator.init(backingAllocator), + .backingAllocator = backingAllocator, + }; + + return self; + } + + pub fn indexToHandle(self: @This(), index: usize) SetHandle { + return self.handles.items[index]; + } + + pub fn destroyObject(self: *@This(), handle: SetHandle) void { + std.debug.assert(self.map.contains(handle)); + + if (@hasDecl(T, "deinitECS")) { + self.map.get(handle).?.deinitECS(handle); + } + + const alloc = self.allocator(); + const index = self.listEntriesByHandle.get(handle).?; + + alloc.destroy(self.map.get(handle).?); + + _ = self.map.remove(handle); + _ = self.listEntriesByHandle.remove(handle); + _ = self.list.swapRemove(index); // oops. + const swappedHandle = self.handles.getLastOrNull(); + _ = self.handles.swapRemove(index); + + if (swappedHandle) |swapped| + self.listEntriesByHandle.put(alloc, swapped, index) catch unreachable; + + self.opCount +%= 1; + + if (self.containerListener) |l| { + l.onHandleRemoved(l.ptr, self.containerID, handle); + } + } + + pub fn createWithHandle(self: *@This(), handle: SetHandle, initValue: T) !*T { + std.debug.assert(!self.map.contains(handle)); + const alloc = self.allocator(); + + const new = try alloc.create(T); + new.* = initValue; + + try self.map.put(alloc, handle, new); + try self.list.append(alloc, new); + try self.handles.append(alloc, handle); + try self.listEntriesByHandle.put(alloc, handle, @intCast(self.list.items.len - 1)); + + if (self.containerListener) |l| { + l.onHandleAdded(l.ptr, self.containerID, handle); + } + + self.opCount +%= 1; + + return new; + } + + pub fn createWithHandleECS(self: *@This(), handle: SetHandle) *T { + const rv = self.createWithHandle(handle, .{}) catch @panic("Unable to create"); + + if (@hasDecl(T, "initECS")) { + rv.initECS(handle); + } + return rv; + } + + pub fn allocator(self: *@This()) std.mem.Allocator { + return self.arena.allocator(); + } + + pub fn getStatistics(self: *@This()) stats.PoolStatistics { + // per-entry cost of each hashmap (key + value + metadata byte) + const mapEntryBytes = @sizeOf(SetHandle) + @sizeOf(*T) + 1; + const indexEntryBytes = @sizeOf(SetHandle) + @sizeOf(u32) + 1; + return .{ + .statName = "SparseMap", + .instanceCount = self.list.items.len, + // values themselves are allocated out of the arena + .memoryReserved = self.arena.queryCapacity() + + self.map.capacity() * mapEntryBytes + + self.listEntriesByHandle.capacity() * indexEntryBytes + + self.list.capacity * @sizeOf(*T) + + self.handles.capacity * @sizeOf(SetHandle), + .memoryUsed = self.map.count() * mapEntryBytes + + self.listEntriesByHandle.count() * indexEntryBytes + + self.list.items.len * @sizeOf(*T) + + self.handles.items.len * @sizeOf(SetHandle), + }; + } + + pub fn destroy(self: *@This()) void { + self.arena.deinit(); + self.backingAllocator.destroy(self); + } + + // == interface below == + + pub const EcsContainerInterfaceVTable = EcsContainerInterface.Implement(@This()); + + pub fn get(self: @This(), handle: SetHandle) ?*anyopaque { + return self.map.get(handle); + } + + pub fn handleExists(self: @This(), handle: SetHandle) bool { + return self.map.contains(handle); + } + + pub fn getContainerID(self: @This()) u32 { + return self.containerID; + } + + pub fn onRegister(self: *@This(), id: u32, listener: ContainerListener) void { + self.containerID = id; + self.containerListener = listener; + } + + // might never need to call this one... + pub fn evictFromRegistry(self: *@This()) void { + self.containerListener = null; + } + + pub fn getStateCount(self: @This()) u32 { + return self.opCount; + } + + pub const ContainerTypeName = "SparseMap"; + }; +} + +// this is quickly becoming the ecs containers file +// todo.. move EcsContainerInterface into somewhere else. +const interface = @import("interface.zig"); + +pub const EcsContainerInterface = interface.MakeInterface("EcsContainerInterfaceVTable", struct { + containerTypeName: []const u8, + componentName: []const u8, + handleExists: *const fn (*const anyopaque, SetHandle) bool, + get: *const fn (*const anyopaque, SetHandle) ?*anyopaque, + createWithHandle: *const fn (*anyopaque, SetHandle) *anyopaque, + destroyObject: *const fn (*anyopaque, SetHandle) void, + getContainerID: *const fn (*const anyopaque) u32, + onRegister: *const fn (*anyopaque, u32, ContainerListener) void, + evictFromRegistry: *const fn (*anyopaque) void, + getStateCount: *const fn (*anyopaque) u32, // returns an internal number representing the state of the container + + pub const Reference = struct { + vtable: *const @This(), + ptr: *anyopaque, + }; + + pub fn Implement(comptime TargetType: type) @This() { + const Wrap = struct { + pub fn handleExists(p: *const anyopaque, handle: SetHandle) bool { + var ptr = @as(*const TargetType, @ptrCast(@alignCast(p))); + return ptr.handleExists(handle); + } + + // gets a function. assuming it exists + pub fn get(p: *const anyopaque, handle: SetHandle) ?*anyopaque { + // std.debug.print("get {p}\n", .{p}); + var ptr = @as(*const TargetType, @ptrCast(@alignCast(p))); + if (@hasDecl(TargetType, "getHandleRef")) { + return ptr.getHandleRef(handle); + } + return @ptrCast(ptr.get(handle)); + } + + pub fn destroyObject(p: *anyopaque, handle: SetHandle) void { + // std.debug.print("creat with handle {p}\n", .{p}); + var ptr = @as(*TargetType, @ptrCast(@alignCast(p))); + ptr.destroyObject(handle); + } + + pub fn createWithHandle(p: *anyopaque, handle: SetHandle) *anyopaque { + // std.debug.print("creat with handle {p}\n", .{p}); + var ptr = @as(*TargetType, @ptrCast(@alignCast(p))); + return ptr.createWithHandleECS(handle); + } + + pub fn getStateCount(p: *const anyopaque) u32 { + // std.debug.print("getstatecount {p}\n", .{p}); + var ptr = @as(*const TargetType, @ptrCast(@alignCast(p))); + return ptr.getStateCount(); + } + + pub fn getContainerID(p: *const anyopaque) u32 { + var ptr = @as(*const TargetType, @ptrCast(@alignCast(p))); + return ptr.getContainerID(); + } + + pub fn onRegister(p: *anyopaque, id: u32, listener: ContainerListener) void { + var ptr = @as(*TargetType, @ptrCast(@alignCast(p))); + return ptr.onRegister(id, listener); + } + + pub fn evictFromRegistry(p: *anyopaque) void { + var ptr = @as(*TargetType, @ptrCast(@alignCast(p))); + return ptr.evictFromRegistry(); + } + }; + + return .{ + .containerTypeName = TargetType.ContainerTypeName, + .componentName = @typeName(TargetType.InnerType), + .handleExists = Wrap.handleExists, + .get = Wrap.get, + .createWithHandle = Wrap.createWithHandle, + .destroyObject = Wrap.destroyObject, + .getContainerID = Wrap.getContainerID, + .onRegister = Wrap.onRegister, + .evictFromRegistry = Wrap.evictFromRegistry, + .getStateCount = Wrap.getStateCount, + }; + } +}); + +test "sparse-multiset-recycle-handles" { + const testHandle: SetHandle = .{ + .index = 420, + .alive = true, + .generation = 12, + }; + + const testHandle2: SetHandle = .{ + .index = 421, + .alive = true, + .generation = 12, + }; + + const TestStruct = struct { + wutang: u32 = 0, + lmao: u32 = 0, + }; + + var testSet = SparseMultiSet(TestStruct).init(std.testing.allocator); + defer testSet.deinit(); + + _ = testSet.createWithHandleECS(testHandle); + _ = testSet.createWithHandleECS(testHandle2); + + std.debug.assert(testSet.get(testHandle, .wutang) != null); + std.debug.assert(testSet.get(testHandle2, .wutang) != null); +} diff --git a/engine/p2/src/structures/spmc-submission-queue.zig b/engine/p2/src/structures/spmc-submission-queue.zig new file mode 100644 index 0000000..1de5a1c --- /dev/null +++ b/engine/p2/src/structures/spmc-submission-queue.zig @@ -0,0 +1,681 @@ +const std = @import("std"); + +pub const PackedState = packed struct(u32) { + remaining_items: u24 = 0, // Unclaimed entries. + active_readers: u8 = 0, // Consumers copying descriptors. +}; + +pub const Config = struct { + ChunkSize: usize = 256, +}; + +/// Single-producer, multiple-consumer batch mailbox. Keep its address stable. +/// The producer pushes values then calls submit(). Each consumer supplies its +/// own [ChunkSize]T buffer to maybeTake() and processes the returned slice. +/// Empty slices mean no chunk is claimable. The final chunk may be shorter. +pub fn CommitQueue(comptime T: type, comptime config: Config) type { + if (config.ChunkSize == 0 or config.ChunkSize > std.math.maxInt(u24)) + @compileError("ChunkSize must be between 1 and 16777215"); + return struct { + pub const Item = T; + pub const ChunkSize = config.ChunkSize; + + allocator: std.mem.Allocator, + state: std.atomic.Value(u32) = .init(0), + + active: std.ArrayList(T) = .empty, + back: std.ArrayList(T) = .empty, + + pub fn init(allocator: std.mem.Allocator) @This() { + return .{ .allocator = allocator }; + } + + pub fn deinit(self: *@This()) void { + while (!self.canSubmit()) std.atomic.spinLoopHint(); + + self.active.deinit(self.allocator); + self.back.deinit(self.allocator); + } + + /// Producer only. Grows the private backbuffer as needed. + pub fn push(self: *@This(), item: T) !void { + if (self.back.items.len == std.math.maxInt(u24)) return error.BatchFull; + try self.back.append(self.allocator, item); + } + + /// Copy up to ChunkSize values into consumer-owned storage. The returned + /// slice lives until that storage is overwritten, even across submit(). + /// Empty/saturated batches return a static empty slice without touching output. + pub fn maybeTake(self: *@This(), output: *[ChunkSize]T) []const T { + var s: PackedState = @bitCast(self.state.load(.monotonic)); + + while (true) { + if (s.remaining_items == 0 or s.active_readers == std.math.maxInt(u8)) + return &.{}; + + // Claim a contiguous chunk and pin its batch atomically. + var desired = s; + const count: u24 = @intCast(@min(@as(usize, s.remaining_items), ChunkSize)); + desired.remaining_items -= count; + desired.active_readers += 1; + + if (self.state.cmpxchgWeak(@bitCast(s), @bitCast(desired), .acquire, .monotonic)) |observed| { + s = @bitCast(observed); + continue; + } + + // Read metadata only after successfully pinning. + const index = self.active.items.len - @as(usize, s.remaining_items); + @memcpy(output[0..count], self.active.items[index..][0..count]); + + self.releaseReader(); + return output[0..count]; + } + } + + /// Release a pin after copying the submission. + fn releaseReader(self: *@This()) void { + // Every caller owns a pin. Subtracting one high-byte unit cannot + // alter the low 24 bits, even while other consumers claim entries. + const previous = self.state.fetchSub(@as(u32, 1) << 24, .release); + std.debug.assert(@as(PackedState, @bitCast(previous)).active_readers != 0); + } + + pub fn canSubmit(self: *const @This()) bool { + return self.state.load(.acquire) == 0; + } + + /// Must only be called Producer only. + /// publishes the backbuffer to all consumers, + pub fn submit(self: *@This()) void { + while (!self.canSubmit()) { + std.atomic.spinLoopHint(); + } + + std.mem.swap(@TypeOf(self.active), &self.active, &self.back); + + self.back.clearRetainingCapacity(); + self.state.store(@bitCast(PackedState{ .remaining_items = @intCast(self.active.items.len) }), .release); + } + }; +} + +// Drain before deinit on assertion/OOM paths: deinit deliberately waits for +// outstanding submissions and would otherwise hide the original test failure. +fn drainTestQueue(queue: anytype) void { + var output: [@TypeOf(queue.*).ChunkSize]@TypeOf(queue.*).Item = undefined; + while (queue.maybeTake(&output).len != 0) {} +} + +test "spmc publication is explicit and batches remain isolated during growth" { + var queue = CommitQueue(usize, .{ .ChunkSize = 1 }).init(std.testing.allocator); + defer queue.deinit(); + defer drainTestQueue(&queue); + + try std.testing.expect(queue.canSubmit()); + try std.testing.expectEqual(null, takeTestOne(&queue)); + for (0..8) |_| { + queue.submit(); + try std.testing.expect(queue.canSubmit()); + try std.testing.expectEqual(null, takeTestOne(&queue)); + } + for (0..17) |i| try queue.push(i); + try std.testing.expectEqual(null, takeTestOne(&queue)); + queue.submit(); + try std.testing.expect(!queue.canSubmit()); + // Force several backbuffer reallocations while the old front is live. + for (0..4097) |i| try queue.push(10000 + i); + for (0..17) |i| try std.testing.expectEqual(i, takeTestOne(&queue).?); + try std.testing.expect(queue.canSubmit()); + try std.testing.expectEqual(null, takeTestOne(&queue)); + queue.submit(); + for (0..4097) |i| try std.testing.expectEqual(10000 + i, takeTestOne(&queue).?); + try std.testing.expectEqual(null, takeTestOne(&queue)); +} + +test "spmc repeated swaps preserve FIFO values without replaying stale capacity" { + const Item = struct { id: usize, bytes: [257]u8 }; + var queue = CommitQueue(Item, .{ .ChunkSize = 1 }).init(std.testing.allocator); + defer queue.deinit(); + defer drainTestQueue(&queue); + const sizes = [_]usize{ 513, 0, 1, 0, 33, 2, 1025, 3 }; + var next: usize = 0; + for (0..64) |round| { + const count = sizes[round % sizes.len]; + for (0..count) |i| { + var item: Item = .{ .id = next + i, .bytes = @splat(@truncate(next + i)) }; + try queue.push(item); + item.bytes = @splat(0); // push owns a value copy. + } + try std.testing.expectEqual(null, takeTestOne(&queue)); + queue.submit(); + for (0..count) |i| { + const item = takeTestOne(&queue).?; + try std.testing.expectEqual(next + i, item.id); + for (item.bytes) |byte| try std.testing.expectEqual(@as(u8, @truncate(next + i)), byte); + } + next += count; + try std.testing.expectEqual(null, takeTestOne(&queue)); + try std.testing.expect(queue.canSubmit()); + } +} + +test "spmc flush requires both zero entries and zero reader pins" { + var queue = CommitQueue(u32, .{ .ChunkSize = 1 }).init(std.testing.allocator); + defer queue.deinit(); + defer storeTestState(&queue, .{}, .monotonic); + // Synthetic states cover the interval after the last claim but before its + // copy finishes, which cannot be scheduled reliably through maybeTake alone. + for ([_]PackedState{ + .{ .remaining_items = 1 }, + .{ .active_readers = 1 }, + .{ .remaining_items = 7, .active_readers = 3 }, + .{ .active_readers = std.math.maxInt(u8) }, + }) |state| { + storeTestState(&queue, state, .monotonic); + try std.testing.expect(!queue.canSubmit()); + } + storeTestState(&queue, .{ .active_readers = 1 }, .monotonic); + try std.testing.expectEqual(null, takeTestOne(&queue)); + queue.releaseReader(); + try std.testing.expect(queue.canSubmit()); +} + +test "spmc saturated readers leave entries untouched and resume after release" { + var queue = CommitQueue(u32, .{ .ChunkSize = 1 }).init(std.testing.allocator); + defer queue.deinit(); + defer storeTestState(&queue, .{}, .monotonic); + try queue.push(42); + queue.submit(); + storeTestState(&queue, .{ .remaining_items = 1, .active_readers = 255 }, .monotonic); + try std.testing.expectEqual(null, takeTestOne(&queue)); + try std.testing.expectEqual(@as(u24, 1), loadTestState(&queue).remaining_items); + try std.testing.expectEqual(@as(u8, 255), loadTestState(&queue).active_readers); + queue.releaseReader(); + // Claiming uses the last available pin, then returns it after the copy. + try std.testing.expectEqual(@as(u32, 42), takeTestOne(&queue).?); + try std.testing.expectEqual(@as(u24, 0), loadTestState(&queue).remaining_items); + try std.testing.expectEqual(@as(u8, 254), loadTestState(&queue).active_readers); + try std.testing.expectEqual(null, takeTestOne(&queue)); + try std.testing.expect(!queue.canSubmit()); +} + +test "spmc packed counters occupy exactly 32 bits without overlap" { + try std.testing.expectEqual(@as(usize, 4), @sizeOf(PackedState)); + try std.testing.expectEqual(@as(usize, 32), @bitSizeOf(PackedState)); + try std.testing.expectEqual(@as(usize, 4), @sizeOf(std.atomic.Value(u32))); + const entries: PackedState = .{ .remaining_items = std.math.maxInt(u24) }; + const readers: PackedState = .{ .active_readers = std.math.maxInt(u8) }; + try std.testing.expectEqual(@as(u32, 0x00ffffff), @as(u32, @bitCast(entries))); + try std.testing.expectEqual(@as(u32, 0xff000000), @as(u32, @bitCast(readers))); +} + +test "spmc maximum batch publishes without truncation and rejects overflow" { + var queue = CommitQueue(void, .{ .ChunkSize = 1 }).init(std.testing.allocator); + defer queue.deinit(); + defer storeTestState(&queue, .{}, .monotonic); + const limit = std.math.maxInt(u24); + // Zero-sized values exercise the actual length boundary without a huge allocation. + try queue.back.resize(std.testing.allocator, limit - 1); + try queue.push({}); + try std.testing.expectError(error.BatchFull, queue.push({})); + try std.testing.expectEqual(@as(usize, limit), queue.back.items.len); + queue.submit(); + try std.testing.expectEqual(limit, loadTestState(&queue).remaining_items); + try std.testing.expect(takeTestOne(&queue) != null); + try std.testing.expectEqual(@as(u24, limit - 1), loadTestState(&queue).remaining_items); + try std.testing.expectEqual(@as(u8, 0), loadTestState(&queue).active_readers); + // Discard remaining synthetic work, then prove a rejected push did not poison reuse. + storeTestState(&queue, .{}, .monotonic); + try queue.push({}); + queue.submit(); + try std.testing.expect(takeTestOne(&queue) != null); + try std.testing.expectEqual(null, takeTestOne(&queue)); +} + +test "spmc failed backbuffer growth preserves both batches and permits retry" { + var failing = std.testing.FailingAllocator.init(std.testing.allocator, .{}); + var queue = CommitQueue(usize, .{ .ChunkSize = 1 }).init(failing.allocator()); + defer queue.deinit(); + defer drainTestQueue(&queue); + try queue.push(99); + queue.submit(); + try queue.push(0); + const capacity = queue.back.capacity; + for (1..capacity) |i| try queue.push(i); + failing.fail_index = failing.alloc_index; + try std.testing.expectError(error.OutOfMemory, queue.push(capacity)); + try std.testing.expectEqual(capacity, queue.back.items.len); + try std.testing.expectEqual(@as(usize, 99), takeTestOne(&queue).?); + failing.fail_index = std.math.maxInt(usize); + try queue.push(capacity); + queue.submit(); + for (0..capacity + 1) |i| try std.testing.expectEqual(i, takeTestOne(&queue).?); +} + +fn allocationFailureScenario(allocator: std.mem.Allocator) !void { + var queue = CommitQueue(usize, .{ .ChunkSize = 1 }).init(allocator); + defer queue.deinit(); + defer drainTestQueue(&queue); + for (0..4) |round| { + for (0..129) |i| try queue.push(round * 129 + i); + drainTestQueue(&queue); + queue.submit(); + } +} + +test "spmc allocation failures release front and pending backbuffer storage" { + try std.testing.checkAllAllocationFailures(std.testing.allocator, allocationFailureScenario, .{}); +} + +const ContentionTest = struct { + const rounds = 256; + const sizes = [_]usize{ 0, 1, 255, 256, 257, 512, 10000, 7 }; + const total = 32 * (1 + 255 + 256 + 257 + 512 + 10000 + 7); + const Item = struct { id: usize, words: [64]u64 }; + const Queue = CommitQueue(Item, .{}); + + queue: *Queue, + start: *std.Io.Event, + stop: *std.atomic.Value(bool), + seen: [total]u64 = @splat(0), + wrapIds: bool = false, + lastId: ?usize = null, + corrupt: bool = false, + + fn word(id: usize, lane: usize) u64 { + return (@as(u64, @intCast(id)) *% 0x9e3779b97f4a7c15) ^ (@as(u64, @intCast(lane)) *% 0xd6e8feb86659fd93); + } + + fn consume(self: *@This()) void { + var output: [Queue.ChunkSize]Item = undefined; + self.start.waitUncancelable(std.testing.io); + while (!self.stop.load(.acquire)) { + const items = self.queue.maybeTake(&output); + for (items) |item| { + if (!self.wrapIds and item.id >= total) { + self.corrupt = true; + continue; + } + if (self.lastId) |last| { + if (item.id <= last) self.corrupt = true; + } + self.lastId = item.id; + self.seen[item.id % total] +|= 1; + for (item.words, 0..) |value, lane| { + if (value != word(item.id, lane)) self.corrupt = true; + } + if (item.id % 17 == 0) std.Thread.yield() catch {}; + } + if (items.len == 0) std.Thread.yield() catch {}; + } + } + + fn awaitDrained(queue: *Queue) !void { + const begin = std.Io.Timestamp.now(std.testing.io, .awake); + while (!queue.canSubmit()) { + if (begin.durationTo(std.Io.Timestamp.now(std.testing.io, .awake)).toMilliseconds() > 10000) + return error.QueueDrainTimeout; + std.Thread.yield() catch {}; + } + } +}; + +test "spmc eight consumers deliver every large descriptor exactly once across 256 batches" { + const C = ContentionTest; + var queue = C.Queue.init(std.testing.allocator); + defer queue.deinit(); + defer drainTestQueue(&queue); + var start: std.Io.Event = .unset; + var stop: std.atomic.Value(bool) = .init(false); + const workers = try std.testing.allocator.alloc(C, 8); + defer std.testing.allocator.free(workers); + var threads: [8]std.Thread = undefined; + var spawned: usize = 0; + { + // Also releases/joins a partially spawned set on allocation or spawn failure. + defer { + stop.store(true, .release); + start.set(std.testing.io); + for (threads[0..spawned]) |thread| thread.join(); + } + for (workers, 0..) |*worker, i| { + worker.* = .{ .queue = &queue, .start = &start, .stop = &stop }; + threads[i] = try std.Thread.spawn(.{}, C.consume, .{worker}); + spawned += 1; + } + start.set(std.testing.io); + var next: usize = 0; + for (0..C.rounds) |round| { + // Build the next batch while consumers can still copy the previous one. + for (0..C.sizes[round % C.sizes.len]) |_| { + var item: C.Item = .{ .id = next, .words = undefined }; + for (&item.words, 0..) |*value, lane| value.* = C.word(next, lane); + try queue.push(item); + next += 1; + } + try C.awaitDrained(&queue); + queue.submit(); + } + try C.awaitDrained(&queue); + try std.testing.expectEqual(C.total, next); + } + // Per-worker observations avoid adding synchronization to descriptor copying. + for (workers) |*worker| try std.testing.expect(!worker.corrupt); + for (0..C.total) |id| { + var copies: u64 = 0; + for (workers) |*worker| copies += worker.seen[id]; + try std.testing.expectEqual(@as(u64, 1), copies); + } + var emptyOutput: [C.Queue.ChunkSize]C.Item = undefined; + try std.testing.expectEqual(@as(usize, 0), queue.maybeTake(&emptyOutput).len); + try std.testing.expect(queue.canSubmit()); +} + +test "spmc zero sized values still consume exactly one claim each" { + var queue = CommitQueue(void, .{ .ChunkSize = 1 }).init(std.testing.allocator); + defer queue.deinit(); + defer drainTestQueue(&queue); + for ([_]usize{ 0, 1, 127, 0, 3 }) |count| { + for (0..count) |_| try queue.push({}); + try std.testing.expectEqual(null, takeTestOne(&queue)); + queue.submit(); + for (0..count) |_| try std.testing.expect(takeTestOne(&queue) != null); + try std.testing.expectEqual(null, takeTestOne(&queue)); + try std.testing.expect(queue.canSubmit()); + } +} + +test "spmc warmed buffers reuse capacity with all further allocations disabled" { + var failing = std.testing.FailingAllocator.init(std.testing.allocator, .{}); + var queue = CommitQueue(usize, .{ .ChunkSize = 1 }).init(failing.allocator()); + defer queue.deinit(); + defer drainTestQueue(&queue); + // Both buffers must grow once before steady-state swaps need no allocation. + for (0..2) |_| { + for (0..129) |i| try queue.push(i); + queue.submit(); + drainTestQueue(&queue); + } + const allocations = failing.alloc_index; + failing.fail_index = allocations; + for (0..64) |round| { + const count: usize = if (round % 3 == 0) 0 else 129; + for (0..count) |i| try queue.push(round * 129 + i); + queue.submit(); + for (0..count) |i| try std.testing.expectEqual(round * 129 + i, takeTestOne(&queue).?); + try std.testing.expectEqual(null, takeTestOne(&queue)); + } + try std.testing.expectEqual(allocations, failing.alloc_index); +} + +fn testBlockedSubmit(comptime pinned: bool) !void { + const Producer = struct { + queue: *CommitQueue(u32, .{ .ChunkSize = 1 }), + entered: std.Io.Event = .unset, + finished: std.Io.Event = .unset, + + fn run(self: *@This()) void { + self.entered.set(std.testing.io); + self.queue.submit(); + self.finished.set(std.testing.io); + } + }; + var queue = CommitQueue(u32, .{ .ChunkSize = 1 }).init(std.testing.allocator); + defer queue.deinit(); + defer drainTestQueue(&queue); + try queue.push(11); + queue.submit(); + try queue.push(22); + if (pinned) { + // Model the final consumer having claimed, but not yet copied, item 11. + storeTestState(&queue, .{ .active_readers = 1 }, .monotonic); + } + var producer: Producer = .{ .queue = &queue }; + const thread = std.Thread.spawn(.{}, Producer.run, .{&producer}) catch |err| { + storeTestState(&queue, .{}, .monotonic); + return err; + }; + defer { + // On a failed assertion unblock submit before joining. No consumer is + // running here, and both buffers are freed only after the producer exits. + storeTestState(&queue, .{}, .release); + thread.join(); + } + try producer.entered.waitTimeout(std.testing.io, .{ .duration = .{ + .raw = .fromSeconds(10), + .clock = .awake, + } }); + // This observation window supplements the deterministic state tests above; + // the scheduler cannot guarantee that the producer ran inside the window. + try std.testing.expectError(error.Timeout, producer.finished.waitTimeout(std.testing.io, .{ .duration = .{ + .raw = .fromMilliseconds(20), + .clock = .awake, + } })); + if (pinned) { + try std.testing.expectEqual(@as(u32, 11), queue.active.items[0]); + queue.releaseReader(); + } else { + try std.testing.expectEqual(@as(u32, 11), takeTestOne(&queue).?); + } + try producer.finished.waitTimeout(std.testing.io, .{ .duration = .{ + .raw = .fromSeconds(10), + .clock = .awake, + } }); + try std.testing.expectEqual(@as(u32, 22), takeTestOne(&queue).?); + try std.testing.expectEqual(null, takeTestOne(&queue)); + try std.testing.expect(queue.canSubmit()); +} + +test "spmc submit waits for the previous batch to be claimed" { + try testBlockedSubmit(false); +} + +test "spmc submit waits for the last descriptor copy to release its pin" { + try testBlockedSubmit(true); +} + +test "spmc stress 30 seconds of continuous publication with eight consumers" { + const C = ContentionTest; + var queue = C.Queue.init(std.testing.allocator); + defer queue.deinit(); + defer drainTestQueue(&queue); + var start: std.Io.Event = .unset; + var stop: std.atomic.Value(bool) = .init(false); + const workers = try std.testing.allocator.alloc(C, 8); + defer std.testing.allocator.free(workers); + var threads: [8]std.Thread = undefined; + var spawned: usize = 0; + var next: usize = 0; + var batches: usize = 0; + { + defer { + stop.store(true, .release); + start.set(std.testing.io); + for (threads[0..spawned]) |thread| thread.join(); + } + for (workers, 0..) |*worker, i| { + worker.* = .{ .queue = &queue, .start = &start, .stop = &stop, .wrapIds = true }; + threads[i] = try std.Thread.spawn(.{}, C.consume, .{worker}); + spawned += 1; + } + var random = std.Random.DefaultPrng.init(0x5a17_c0de); + const begin = std.Io.Timestamp.now(std.testing.io, .awake); + start.set(std.testing.io); + while (begin.durationTo(std.Io.Timestamp.now(std.testing.io, .awake)).toMilliseconds() < 30000) { + // Include empty publications and singleton races, plus batches large + // enough to keep all consumers busy and force backbuffer growth. + const count = random.random().uintAtMost(usize, 10000); + for (0..count) |_| { + var item: C.Item = .{ .id = next, .words = undefined }; + for (&item.words, 0..) |*value, lane| value.* = C.word(next, lane); + try queue.push(item); + next += 1; + } + try C.awaitDrained(&queue); + queue.submit(); + batches += 1; + } + try C.awaitDrained(&queue); + } + try std.testing.expect(batches > 1); + try std.testing.expect(next > 0); + for (workers) |*worker| try std.testing.expect(!worker.corrupt); + // A bounded histogram checks delivery counts over an unbounded ID stream. + // Strictly increasing IDs per consumer additionally detect local replay; + // the short stress test above tracks every individual descriptor exactly. + var received: u64 = 0; + for (0..C.total) |slot| { + var copies: u64 = 0; + for (workers) |*worker| copies += worker.seen[slot]; + const expected = next / C.total + @intFromBool(slot < next % C.total); + try std.testing.expectEqual(@as(u64, @intCast(expected)), copies); + received += copies; + } + try std.testing.expectEqual(@as(u64, @intCast(next)), received); + var emptyOutput: [C.Queue.ChunkSize]C.Item = undefined; + try std.testing.expectEqual(@as(usize, 0), queue.maybeTake(&emptyOutput).len); + try std.testing.expect(queue.canSubmit()); + std.debug.print("\nspmc 30s stress: {d} batches, {d} descriptors, 8 consumers\n", .{ batches, received }); +} + +fn storeTestState(queue: anytype, state: PackedState, comptime order: std.builtin.AtomicOrder) void { + queue.state.store(@bitCast(state), order); +} + +fn loadTestState(queue: anytype) PackedState { + return @bitCast(queue.state.load(.monotonic)); +} + +test "spmc reader subtraction preserves every entry boundary for all pin counts" { + var queue = CommitQueue(void, .{ .ChunkSize = 1 }).init(std.testing.allocator); + defer queue.deinit(); + defer storeTestState(&queue, .{}, .monotonic); + for ([_]u24{ 0, 1, 0xffff, std.math.maxInt(u24) }) |remaining| { + for (1..256) |readers| { + storeTestState(&queue, .{ .remaining_items = remaining, .active_readers = @intCast(readers) }, .monotonic); + queue.releaseReader(); + const observed = loadTestState(&queue); + try std.testing.expectEqual(remaining, observed.remaining_items); + try std.testing.expectEqual(@as(u8, @intCast(readers - 1)), observed.active_readers); + try std.testing.expectEqual(remaining == 0 and readers == 1, queue.canSubmit()); + } + } +} + +test "spmc simultaneous reader releases lose no decrements or unclaimed entries" { + const Worker = struct { + fn run(queue: *CommitQueue(void, .{ .ChunkSize = 1 }), gate: *std.Io.Event) void { + gate.waitUncancelable(std.testing.io); + for (0..31) |_| queue.releaseReader(); + } + }; + var queue = CommitQueue(void, .{ .ChunkSize = 1 }).init(std.testing.allocator); + defer queue.deinit(); + defer storeTestState(&queue, .{}, .monotonic); + storeTestState(&queue, .{ .remaining_items = std.math.maxInt(u24), .active_readers = 248 }, .monotonic); + var gate: std.Io.Event = .unset; + var threads: [8]std.Thread = undefined; + var spawned: usize = 0; + { + defer { + gate.set(std.testing.io); + for (threads[0..spawned]) |thread| thread.join(); + } + for (&threads) |*thread| { + thread.* = try std.Thread.spawn(.{}, Worker.run, .{ &queue, &gate }); + spawned += 1; + } + } + const observed = loadTestState(&queue); + try std.testing.expectEqual(@as(u24, std.math.maxInt(u24)), observed.remaining_items); + try std.testing.expectEqual(@as(u8, 0), observed.active_readers); + try std.testing.expect(!queue.canSubmit()); +} + +// Retain the original one-item behavioral tests using the chunk-size-one configuration. +fn takeTestOne(queue: anytype) ?@TypeOf(queue.*).Item { + const Q = @TypeOf(queue.*); + if (Q.ChunkSize != 1) @compileError("single-item test requires ChunkSize = 1"); + var output: [1]Q.Item = undefined; + const items = queue.maybeTake(&output); + return if (items.len == 0) null else items[0]; +} + +test "spmc 256 item chunks preserve FIFO tails output bounds and copy lifetime" { + const Q = CommitQueue(usize, .{}); + var queue = Q.init(std.testing.allocator); + defer queue.deinit(); + defer drainTestQueue(&queue); + var output: [Q.ChunkSize]usize = @splat(std.math.maxInt(usize)); + const empty = queue.maybeTake(&output); + try std.testing.expectEqual(@as(usize, 0), empty.len); + try std.testing.expect(empty.ptr != output[0..].ptr); + for (output) |value| try std.testing.expectEqual(std.math.maxInt(usize), value); + for ([_]usize{ 1, 255, 256, 257, 512, 519, 10000 }) |count| { + for (0..count) |i| try queue.push(i); + try std.testing.expectEqual(@as(usize, 0), queue.maybeTake(&output).len); + queue.submit(); + var offset: usize = 0; + while (offset < count) { + @memset(&output, std.math.maxInt(usize)); + const items = queue.maybeTake(&output); + const expected = @min(Q.ChunkSize, count - offset); + try std.testing.expectEqual(expected, items.len); + try std.testing.expect(items.ptr == output[0..].ptr); + for (items, 0..) |item, i| try std.testing.expectEqual(offset + i, item); + for (output[expected..]) |value| try std.testing.expectEqual(std.math.maxInt(usize), value); + offset += expected; + try std.testing.expectEqual(@as(u24, @intCast(count - offset)), loadTestState(&queue).remaining_items); + try std.testing.expectEqual(@as(u8, 0), loadTestState(&queue).active_readers); + } + // Recycle both queue buffers without touching the consumer's copy. + const lastFirst = output[0]; + queue.submit(); + try queue.push(999999); + queue.submit(); + try std.testing.expectEqual(lastFirst, output[0]); + drainTestQueue(&queue); + } +} + +test "spmc chunk saturation rejects atomically then claims a full chunk with one pin" { + const Q = CommitQueue(u32, .{}); + var queue = Q.init(std.testing.allocator); + defer queue.deinit(); + defer storeTestState(&queue, .{}, .monotonic); + for (0..257) |i| try queue.push(@intCast(i)); + queue.submit(); + var output: [Q.ChunkSize]u32 = @splat(77); + storeTestState(&queue, .{ .remaining_items = 257, .active_readers = 255 }, .monotonic); + try std.testing.expectEqual(@as(usize, 0), queue.maybeTake(&output).len); + try std.testing.expectEqual(@as(u24, 257), loadTestState(&queue).remaining_items); + for (output) |value| try std.testing.expectEqual(@as(u32, 77), value); + queue.releaseReader(); + const items = queue.maybeTake(&output); + try std.testing.expectEqual(@as(usize, 256), items.len); + for (items, 0..) |value, i| try std.testing.expectEqual(@as(u32, @intCast(i)), value); + try std.testing.expectEqual(@as(u24, 1), loadTestState(&queue).remaining_items); + try std.testing.expectEqual(@as(u8, 254), loadTestState(&queue).active_readers); + const tail = queue.maybeTake(&output); + try std.testing.expectEqual(@as(usize, 1), tail.len); + try std.testing.expectEqual(@as(u32, 256), tail[0]); + try std.testing.expectEqual(@as(u8, 254), loadTestState(&queue).active_readers); +} + +test "spmc configurable chunk sizes support zero sized values and short final chunks" { + inline for (.{ 1, 3, 256, 1024 }) |size| { + const Q = CommitQueue(void, .{ .ChunkSize = size }); + var queue = Q.init(std.testing.allocator); + defer queue.deinit(); + defer drainTestQueue(&queue); + var output: [Q.ChunkSize]void = undefined; + for (0..size * 2 + 1) |_| try queue.push({}); + queue.submit(); + try std.testing.expectEqual(@as(usize, size), queue.maybeTake(&output).len); + try std.testing.expectEqual(@as(usize, size), queue.maybeTake(&output).len); + try std.testing.expectEqual(@as(usize, 1), queue.maybeTake(&output).len); + try std.testing.expectEqual(@as(usize, 0), queue.maybeTake(&output).len); + try std.testing.expect(queue.canSubmit()); + } +} diff --git a/engine/p2/src/structures/static-structures.zig b/engine/p2/src/structures/static-structures.zig new file mode 100644 index 0000000..61cc9c4 --- /dev/null +++ b/engine/p2/src/structures/static-structures.zig @@ -0,0 +1,70 @@ +const std = @import("std"); + +fn makeSlice(comptime T: type, ptr: *T, len: usize) []T { + var slice: []T = undefined; + slice.len = len; + slice.ptr = ptr; + return slice; +} + +// A completely static arraylist, returns out of capacity when it's full. +// does NOT do any kind of allocator backing. +pub fn StaticVector(comptime T: type, comptime size: usize) type { + return struct { + fn makeEmptySlice() []T { + var slice: []T = undefined; + slice.len = 0; + slice.ptr = undefined; + return slice; + } + + _data: [size]T = undefined, + items: []T = makeEmptySlice(), + + pub fn append(self: *@This(), value: T) !void { + if (self.items.len >= size) + return error.OutOfCapacity; + + self._data[self.items.len] = value; + self.items.ptr = @ptrCast(&self._data[0]); + self.items.len += 1; + } + + pub fn pop(self: *@This()) ?T { + if (self.len == 0) { + return null; + } + + self.items.len -= 1; + return self._data[self.len]; + } + }; +} + +test "static vector" { + var al = StaticVector(struct { x: u32 = 0 }, 42){}; + + for (0..42) |i| { + try al.append(.{ .x = @intCast(i) }); + } + + std.debug.assert(al.items[0].x == 0); + std.debug.assert(al.items[1].x == 1); +} // + +// TODO: +// +// this is a fixed size vector which +// exists on the stack until it exceeds the static capacity. +// in which case it gets bumped to the heap with an allocator. +pub fn SmallVectorUnmanaged(comptime T: type, comptime size: usize) type { + return struct { + data: [size]T = undefined, + ptr: *T = undefined, + len: usize = 0, + + pub fn append(self: *@This()) !void { + _ = self; + } + }; +} diff --git a/engine/p2/src/structures/stats.zig b/engine/p2/src/structures/stats.zig new file mode 100644 index 0000000..4744cd8 --- /dev/null +++ b/engine/p2/src/structures/stats.zig @@ -0,0 +1,6 @@ +pub const PoolStatistics = struct { + statName: []const u8, + instanceCount: usize, + memoryReserved: usize, + memoryUsed: usize, +}; diff --git a/engine/p2/src/structures/string-pool.zig b/engine/p2/src/structures/string-pool.zig new file mode 100644 index 0000000..ff17fcc --- /dev/null +++ b/engine/p2/src/structures/string-pool.zig @@ -0,0 +1,832 @@ +const std = @import("std"); +const stats = @import("stats.zig"); + +// main purpose of this string-pool is to provide an RC-able interface for +// interfacing with GC'ed systems such as lua +// +// Design: strings are immutable after creation. All "mutation" operations +// (append, trim, fmt, etc.) allocate a new string and drop the old handle. +// A generation counter per slot detects use-after-free of stale handles. + +pub var gStringContext: *StringContext = undefined; + +pub const RefString = struct { + index: u24, + bucketId: u8, + generation: u8 = 0, + + pub fn getUtf8(self: @This()) []u8 { + return gStringContext.getUtf8(self); + } + + pub const utf8 = getUtf8; + + // creates a new string from []const u8 + pub fn new(str: []const u8) !@This() { + return try gStringContext.newFromUtf8(str); + } + + // deep copy of a string + pub fn clone(self: @This()) !@This() { + return try gStringContext.newFromUtf8(self.getUtf8()); + } + + // increases the reference count for this string by one and makes a copy of the handle + pub fn pin(self: @This()) @This() { + gStringContext.rcAdd(self); + return self; + } + + pub fn drop(self: @This()) void { + gStringContext.strDestroy(self); + } + + pub fn len(self: @This()) usize { + return gStringContext.handleLen(self); + } + + pub fn concat(self: @This(), other: @This()) !@This() { + return try RefString.concatSlices(self.getUtf8(), other.getUtf8()); + } + + pub fn concatSlice(self: @This(), other: []const u8) !@This() { + return try RefString.concatSlices(self.getUtf8(), other); + } + + pub fn concatSlices(left: []const u8, right: []const u8) !@This() { + return try gStringContext.newFromUtf8Concat(left, right); + } + + pub fn append(self: @This(), other: []const u8) !@This() { + const result = try self.concatSlice(other); + self.drop(); + return result; + } + + pub const add = append; + + pub fn trim(self: @This()) !@This() { + const str = self.getUtf8(); + const trimmed = std.mem.trim(u8, str, " \t\n\r"); + if (trimmed.len == str.len) { + return self.pin(); + } + return try RefString.new(trimmed); + } + + pub fn substring(self: @This(), start: usize, end: usize) !@This() { + const str = self.getUtf8(); + const s = @min(start, str.len); + const e = @min(end, str.len); + return try RefString.new(str[s..e]); + } + + pub fn substringSlice(self: @This(), start: usize, end: usize) []const u8 { + const str = self.getUtf8(); + const s = @min(start, str.len); + const e = @min(end, str.len); + return str[s..e]; + } + + pub const SplitResult = struct { + items: []RefString, + + pub fn deinit(self: @This()) void { + for (self.items) |s| s.drop(); + gStringContext.getAllocator().free(self.items); + } + }; + + pub fn split(self: @This(), delimiter: []const u8) !SplitResult { + const str = self.getUtf8(); + const allocator = gStringContext.getAllocator(); + + // count segments + var count: usize = 0; + var countIter = std.mem.splitSequence(u8, str, delimiter); + while (countIter.next()) |_| count += 1; + + const items = try allocator.alloc(RefString, count); + errdefer allocator.free(items); + + var iter = std.mem.splitSequence(u8, str, delimiter); + var i: usize = 0; + while (iter.next()) |segment| { + items[i] = try RefString.new(segment); + i += 1; + } + + return .{ .items = items }; + } + + pub fn splitSlice(self: @This(), delimiter: []const u8) std.mem.SplitIterator(u8, .sequence) { + return std.mem.splitSequence(u8, self.getUtf8(), delimiter); + } + + pub fn fmt(comptime format: []const u8, args: anytype) !@This() { + var buf: [4096]u8 = undefined; + var w: std.Io.Writer = .fixed(&buf); + try w.print(format, args); + const result = w.buffered(); + return try RefString.new(result); + } + + pub fn eql(self: @This(), other: @This()) bool { + if (self.bucketId == other.bucketId and self.index == other.index and self.generation == other.generation) return true; + return std.mem.eql(u8, self.getUtf8(), other.getUtf8()); + } + + pub fn eqlSlice(self: @This(), other: []const u8) bool { + return std.mem.eql(u8, self.getUtf8(), other); + } +}; + +pub const RefBuffer = RefString; + +const StringAllocation = struct { + ptr: *align(4) anyopaque, + + pub const HeaderLen = 6; + + // offsets: + // 0x0 -> 0x4 : length (u32) + // 0x4 : reference count (u8, atomic) + // 0x5 : generation (u8, atomic) + // 0x6 -> : string content + + pub fn len(self: @This()) usize { + const read = @as(*u32, @ptrCast(@alignCast(self.ptr))).*; + return @intCast(read); + } + + pub fn setLen(self: @This(), length: usize) void { + @as(*u32, @ptrCast(@alignCast(self.ptr))).* = @intCast(length); + } + + pub fn initRc(self: @This()) void { + const x: [*]std.atomic.Value(u8) = @ptrCast(self.ptr); + x[4] = std.atomic.Value(u8).init(1); + } + + pub fn rcAdd(self: @This()) void { + const x: [*]std.atomic.Value(u8) = @ptrCast(self.ptr); + _ = x[4].fetchAdd(1, .monotonic); + } + + // returns true if the reference count hits 0 + pub fn rcSub(self: @This()) bool { + const x: [*]std.atomic.Value(u8) = @ptrCast(self.ptr); + if (x[4].fetchSub(1, .release) == 1) { + return true; + } + return false; + } + + pub fn rc(self: @This()) u8 { + const x: [*]std.atomic.Value(u8) = @ptrCast(self.ptr); + return x[4].load(.monotonic); + } + + pub fn generation(self: @This()) u8 { + const x: [*]std.atomic.Value(u8) = @ptrCast(self.ptr); + return x[5].load(.monotonic); + } + + pub fn initGeneration(self: @This(), gen: u8) void { + const x: [*]std.atomic.Value(u8) = @ptrCast(self.ptr); + x[5] = std.atomic.Value(u8).init(gen); + } + + pub fn bumpGeneration(self: @This()) void { + const x: [*]std.atomic.Value(u8) = @ptrCast(self.ptr); + _ = x[5].fetchAdd(1, .monotonic); + } + + pub fn bytes(self: @This()) []u8 { + return @as([*]u8, @ptrCast(self.ptr))[HeaderLen .. HeaderLen + self.len()]; + } + + pub fn deallocBytes(self: @This()) []align(4) u8 { + var rv: []align(4) u8 = undefined; + rv.ptr = @ptrCast(self.ptr); + rv.len = self.len() + StringAllocation.HeaderLen; + return rv; + } + + pub fn fromPtr(ptr: *anyopaque) @This() { + return .{ .ptr = @ptrCast(@alignCast(ptr)) }; + } +}; + +const Page = struct { + bytes: []align(8) u8, +}; + +const Bucket = struct { + id: u32, + allocSize: u32, + io_context: std.Io, + + pageSize: u32, + slotsPerPage: u32, + next: u32 = 0, + pages: std.ArrayListUnmanaged(Page) = .empty, + freeSlots: std.ArrayListUnmanaged(u32) = .empty, + + lock: std.Io.Mutex = .init, + + pub const BucketAllocation = struct { + bytes: []u8, + index: u24, + }; + + pub fn init(id: u32, allocSize: u32, pageSize: u32, io_context: std.Io) @This() { + return .{ + .id = id, + .allocSize = allocSize, + .io_context = io_context, + .pageSize = pageSize, + .slotsPerPage = pageSize / allocSize, + }; + } + + pub fn io(self: *const @This()) std.Io { + return self.io_context; + } + + // index to page + inline fn i2p(self: @This(), index: u32) u32 { + return @divFloor(index, self.slotsPerPage); + } + + // index based off of a page + inline fn ibp(self: @This(), index: u32) u32 { + return index % self.slotsPerPage; + } + + fn getBytesFromIndex(self: @This(), index: u32) []u8 { + return self.indexToSlot(self.i2p(index), self.ibp(index)); + } + + fn addPage(self: *@This(), allocator: std.mem.Allocator) !void { + const page: Page = .{ + .bytes = try allocator.alignedAlloc(u8, .@"8", self.pageSize), + }; + try self.pages.append(allocator, page); + } + + fn indexToSlot(self: @This(), pageIndex: u32, pageBase: u32) []u8 { + const left = pageBase * self.allocSize; + const right = left + self.allocSize; + const slice = self.pages.items[pageIndex].bytes[left..right]; + return slice; + } + + pub fn destroySlot(self: *@This(), allocator: std.mem.Allocator, index: u32) void { + self.lock.lockUncancelable(self.io()); + defer self.lock.unlock(self.io()); + // bump generation so stale handles are detected on reuse + const alloc = StringAllocation.fromPtr(self.getBytesFromIndex(index).ptr); + alloc.bumpGeneration(); + self.freeSlots.append(allocator, index) catch unreachable; + } + + pub fn assignOrRecycleSlot(self: *@This(), allocator: std.mem.Allocator) !BucketAllocation { + self.lock.lockUncancelable(self.io()); + defer self.lock.unlock(self.io()); + if (self.freeSlots.items.len < 1) { + const pageIndex = self.i2p(self.next); + + if (pageIndex >= self.pages.items.len) { + try self.addPage(allocator); + } + + const rv: BucketAllocation = .{ + .bytes = self.indexToSlot(pageIndex, self.ibp(self.next)), + .index = @intCast(self.next), + }; + + self.next += 1; + + return rv; + } else { + const index = self.freeSlots.pop().?; + + const rv: BucketAllocation = .{ + .bytes = self.indexToSlot(self.i2p(index), self.ibp(index)), + .index = @intCast(index), + }; + + return rv; + } + } +}; + +pub const StringContext = struct { + backingAllocator: std.mem.Allocator, + io_context: std.Io, + arena: std.heap.ArenaAllocator, + buckets: std.ArrayListUnmanaged(Bucket) = .empty, + live_count: std.atomic.Value(usize) = std.atomic.Value(usize).init(0), + warning_fired: std.atomic.Value(bool) = std.atomic.Value(bool).init(false), + + /// When the number of live pooled strings reaches this count, a warning is + /// logged once and `on_allocation_count_warning` is invoked (first hit only). + /// Lives on the context so it persists across hot reloads. + allocation_count_warning_threshold: usize = 1 << 20, + + /// Invoked once, the first time the live allocation count reaches + /// `allocation_count_warning_threshold`. Engine code installs a handler that + /// dumps all live strings to disk. + on_allocation_count_warning: ?*const fn () void = null, + + pub fn create(backingAllocator: std.mem.Allocator, io_context: std.Io) !*@This() { + const self = try backingAllocator.create(@This()); + + self.* = .{ + .backingAllocator = backingAllocator, + .io_context = io_context, + .arena = std.heap.ArenaAllocator.init(backingAllocator), + }; + + // default bucket setup + // zig fmt: off + try self.buckets.appendSlice(backingAllocator, &.{ + Bucket.init( 0x0, 16, 4096 * 1, io_context), + Bucket.init( 0x1, 32, 4096 * 1, io_context), + Bucket.init( 0x2, 64, 4096 * 1, io_context), + Bucket.init( 0x3, 128, 4096 * 1, io_context), + Bucket.init( 0x4, 512, 4096 * 16, io_context), + Bucket.init( 0x5, 4096, 4096 * 16, io_context), + }); + // zig fmt: on + + return self; + } + + pub fn io(self: *const @This()) std.Io { + return self.io_context; + } + + pub fn getAllocator(self: *@This()) std.mem.Allocator { + return self.arena.allocator(); + } + + pub fn newFromUtf8(self: *@This(), str: []const u8) !RefString { + const results = try self.strNew(str.len); + std.mem.copyForwards(u8, results.bytes, str); + return results.handle; + } + + pub fn newFromUtf8Concat(self: *@This(), left: []const u8, right: []const u8) !RefString { + const left_len = left.len; + const new_len = left_len + right.len; + const results = try self.strNew(new_len); + std.mem.copyForwards(u8, results.bytes[0..left_len], left); + std.mem.copyForwards(u8, results.bytes[left_len..new_len], right); + return results.handle; + } + + pub fn strNew(self: *@This(), length: usize) !struct { + handle: RefString, + bytes: []u8, + } { + const bucket = self.getBucketByLen(@intCast(length)); + const allocation = try bucket.assignOrRecycleSlot(self.getAllocator()); + + const strAllocation = StringAllocation.fromPtr(allocation.bytes.ptr); + strAllocation.initRc(); + strAllocation.setLen(length); + + const live = self.live_count.fetchAdd(1, .monotonic) + 1; + if (live >= self.allocation_count_warning_threshold and + !self.warning_fired.swap(true, .acq_rel)) + { + std.log.warn("string-pool: live allocation count reached {d} (threshold {d})", .{ + live, self.allocation_count_warning_threshold, + }); + if (self.on_allocation_count_warning) |callback| callback(); + } + + // read current generation (may have been bumped by prior free+recycle) + const gen = strAllocation.generation(); + + return .{ + .handle = .{ + .bucketId = @intCast(bucket.id), + .index = allocation.index, + .generation = gen, + }, + .bytes = strAllocation.bytes(), + }; + } + + inline fn getBucketByLen(self: *@This(), stringLength: u32) *Bucket { + const actualLength = stringLength + StringAllocation.HeaderLen; + + for (self.buckets.items) |*bucket| { + if (bucket.allocSize >= actualLength) { + return bucket; + } + } + + @panic("Unable to find a bucket to allocate string of length."); + } + + inline fn getBucketFromHandle(self: @This(), handle: RefString) *Bucket { + return &self.buckets.items[@intCast(handle.bucketId)]; + } + + pub fn getUtf8(self: @This(), handle: RefString) []u8 { + const alloc = self.handleToAllocation(handle); + self.checkGeneration(handle, alloc); + return alloc.bytes(); + } + + pub fn handleLen(self: @This(), handle: RefString) usize { + const alloc = self.handleToAllocation(handle); + self.checkGeneration(handle, alloc); + return alloc.len(); + } + + pub fn rcAdd(self: *@This(), handle: RefString) void { + const allocation = self.handleToAllocation(handle); + self.checkGeneration(handle, allocation); + allocation.rcAdd(); + } + + pub fn handleToAllocation(self: @This(), handle: RefString) StringAllocation { + const bucket = self.getBucketFromHandle(handle); + return StringAllocation.fromPtr(bucket.getBytesFromIndex(handle.index).ptr); + } + + fn checkGeneration(self: @This(), handle: RefString, alloc: StringAllocation) void { + _ = self; + const slotGen = alloc.generation(); + if (slotGen != handle.generation) { + @panic("use-after-free: stale String handle"); + } + } + + pub fn strDestroy(self: *@This(), handle: RefString) void { + const allocation = self.handleToAllocation(handle); + self.checkGeneration(handle, allocation); + if (allocation.rcSub()) { + _ = self.live_count.fetchSub(1, .monotonic); + const bucket = self.getBucketFromHandle(handle); + bucket.destroySlot(self.getAllocator(), @intCast(handle.index)); + } + } + + /// Dumps every live string in the pool, one per line. + /// Diagnostic aid for tracking down leaks / unexpected growth. + /// Not synchronized against concurrent alloc/free; call from a quiescent + /// context or accept a racy snapshot. + pub fn dumpStrings(self: *@This(), writer: *std.Io.Writer) !void { + const allocator = self.backingAllocator; + try writer.print("string-pool dump: live_count={d}\n", .{self.live_count.load(.monotonic)}); + + var total: usize = 0; + for (self.buckets.items) |*bucket| { + var free_set: std.AutoHashMapUnmanaged(u32, void) = .empty; + defer free_set.deinit(allocator); + try free_set.ensureUnusedCapacity(allocator, @intCast(bucket.freeSlots.items.len)); + for (bucket.freeSlots.items) |index| free_set.putAssumeCapacity(index, {}); + + var index: u32 = 0; + while (index < bucket.next) : (index += 1) { + if (free_set.contains(index)) continue; + const alloc = StringAllocation.fromPtr(bucket.getBytesFromIndex(index).ptr); + try writer.print("bucket={d} index={d} gen={d} rc={d} len={d} \"{s}\"\n", .{ + bucket.id, + index, + alloc.generation(), + alloc.rc(), + alloc.len(), + alloc.bytes(), + }); + total += 1; + } + } + try writer.print("total_live={d}\n", .{total}); + } + + pub fn getStatistics(self: *@This()) stats.PoolStatistics { + var reserved: usize = 0; + var used: usize = 0; + for (self.buckets.items) |*bucket| { + reserved += bucket.pages.items.len * @as(usize, bucket.pageSize); + reserved += bucket.pages.capacity * @sizeOf(usize); + reserved += bucket.freeSlots.capacity * @sizeOf(u32); + used += (bucket.next - bucket.freeSlots.items.len) * @as(usize, bucket.allocSize); + } + return .{ + .statName = "StringContext", + .instanceCount = self.live_count.load(.monotonic), + .memoryReserved = reserved, + .memoryUsed = used, + }; + } + + pub fn destroy(self: *@This()) void { + self.arena.deinit(); + self.buckets.deinit(self.backingAllocator); + self.backingAllocator.destroy(self); + } +}; + +pub fn setup(allocator: std.mem.Allocator, io_context: std.Io) !void { + gStringContext = try StringContext.create(allocator, io_context); +} + +pub fn shutdown() void { + gStringContext.destroy(); +} + +/// Dumps all live strings in the global pool to `writer`. +pub fn dumpStrings(writer: *std.Io.Writer) !void { + try gStringContext.dumpStrings(writer); +} + +test "string context" { + try setup(std.testing.allocator, std.testing.io); + defer shutdown(); + + const ctx = gStringContext; + const testSizes: []const u32 = &.{ 14, 15, 16, 12, 32, 10, 1, 2, 3, 4, 440, 450, 3200 }; + for (testSizes) |testSize| { + const results = try ctx.strNew(testSize); + std.debug.print("test {d} = {d}, {d}\n", .{ testSize, results.handle.bucketId, results.handle.index }); + } + + const L = struct { + pub fn wrap(x: RefString) void { + std.debug.print("{d},{d}\n", .{ x.bucketId, x.index }); + } + }; + + const s = try RefString.new("lmao2nova"); + L.wrap(s); + + const x = s.utf8(); + std.debug.print("{x}\n", .{x.len}); + + // doing 1Billion accesses + { + const now = std.Io.Clock.awake.now(ctx.io()).nanoseconds; + for (0..1_000_000_000) |i| { + _ = i; + _ = s.utf8(); + } + const end = std.Io.Clock.awake.now(ctx.io()).nanoseconds; + const duration = end - now; + std.debug.print("time spent {d}ms\n", .{@as(f64, @floatFromInt(duration)) / 1000_000}); + } + + { + const now = std.Io.Clock.awake.now(ctx.io()).nanoseconds; + // 1 million string creations/destructions + for (0..1_000_000) |i| { + _ = i; + const y = try RefString.new("wutang forever\n"); + defer y.drop(); + } + const end = std.Io.Clock.awake.now(ctx.io()).nanoseconds; + const duration = end - now; + std.debug.print("time spent {d}ms\n", .{@as(f64, @floatFromInt(duration)) / 1000_000}); + } + + // allocate 1 million strings + const s2 = s.pin(); + defer s2.drop(); +} + +test "len" { + try setup(std.testing.allocator, std.testing.io); + defer shutdown(); + + const s = try RefString.new("hello"); + defer s.drop(); + try std.testing.expectEqual(@as(usize, 5), s.len()); +} + +test "append" { + try setup(std.testing.allocator, std.testing.io); + defer shutdown(); + + const s = try RefString.new("hello"); + // append drops the old handle, returns new + const s2 = try s.append(" world"); + defer s2.drop(); + try std.testing.expectEqualStrings("hello world", s2.getUtf8()); +} + +test "concat keeps operands alive" { + try setup(std.testing.allocator, std.testing.io); + defer shutdown(); + + const left = try RefString.new("hello"); + defer left.drop(); + const right = try RefString.new(" world"); + defer right.drop(); + + const joined = try left.concat(right); + defer joined.drop(); + + try std.testing.expectEqualStrings("hello world", joined.getUtf8()); + try std.testing.expectEqualStrings("hello", left.getUtf8()); + try std.testing.expectEqualStrings(" world", right.getUtf8()); +} + +test "concatSlice" { + try setup(std.testing.allocator, std.testing.io); + defer shutdown(); + + const left = try RefString.new("rib"); + defer left.drop(); + + const joined = try left.concatSlice("tech"); + defer joined.drop(); + + try std.testing.expectEqualStrings("ribtech", joined.getUtf8()); + try std.testing.expectEqualStrings("rib", left.getUtf8()); +} + +test "trim with whitespace" { + try setup(std.testing.allocator, std.testing.io); + defer shutdown(); + + const s = try RefString.new(" hello "); + defer s.drop(); + const trimmed = try s.trim(); + defer trimmed.drop(); + try std.testing.expectEqualStrings("hello", trimmed.getUtf8()); +} + +test "trim without whitespace" { + try setup(std.testing.allocator, std.testing.io); + defer shutdown(); + + const s = try RefString.new("abc"); + defer s.drop(); + const trimmed = try s.trim(); + defer trimmed.drop(); + try std.testing.expectEqualStrings("abc", trimmed.getUtf8()); + // pinned copy — same handle + try std.testing.expectEqual(s.index, trimmed.index); + try std.testing.expectEqual(s.bucketId, trimmed.bucketId); +} + +test "substring" { + try setup(std.testing.allocator, std.testing.io); + defer shutdown(); + + const s = try RefString.new("hello world"); + defer s.drop(); + + const sub = try s.substring(6, 11); + defer sub.drop(); + try std.testing.expectEqualStrings("world", sub.getUtf8()); + + // clamping + const sub2 = try s.substring(6, 999); + defer sub2.drop(); + try std.testing.expectEqualStrings("world", sub2.getUtf8()); + + // substringSlice + try std.testing.expectEqualStrings("world", s.substringSlice(6, 11)); +} + +test "split" { + try setup(std.testing.allocator, std.testing.io); + defer shutdown(); + + const s = try RefString.new("a::b::c"); + defer s.drop(); + + const result = try s.split("::"); + defer result.deinit(); + + try std.testing.expectEqual(@as(usize, 3), result.items.len); + try std.testing.expectEqualStrings("a", result.items[0].getUtf8()); + try std.testing.expectEqualStrings("b", result.items[1].getUtf8()); + try std.testing.expectEqualStrings("c", result.items[2].getUtf8()); +} + +test "fmt" { + try setup(std.testing.allocator, std.testing.io); + defer shutdown(); + + const s = try RefString.fmt("hello {s} {d}", .{ "world", 42 }); + defer s.drop(); + try std.testing.expectEqualStrings("hello world 42", s.getUtf8()); +} + +test "eql and eqlSlice" { + try setup(std.testing.allocator, std.testing.io); + defer shutdown(); + + const s1 = try RefString.new("hello"); + defer s1.drop(); + const s2 = try RefString.new("hello"); + defer s2.drop(); + const s3 = try RefString.new("world"); + defer s3.drop(); + + try std.testing.expect(s1.eql(s2)); + try std.testing.expect(!s1.eql(s3)); + + // pinned handle — fast path + const s4 = s1.pin(); + defer s4.drop(); + try std.testing.expect(s1.eql(s4)); + + try std.testing.expect(s1.eqlSlice("hello")); + try std.testing.expect(!s1.eqlSlice("world")); +} + +test "multithread create and destroy" { + try setup(std.testing.allocator, std.testing.io); + defer shutdown(); + + const ThreadCtx = struct { + threadId: usize, + iterations: usize, + }; + + const Worker = struct { + fn run(ctx: ThreadCtx) void { + var i: usize = 0; + while (i < ctx.iterations) : (i += 1) { + var s = RefString.fmt("t{d}-i{d}", .{ ctx.threadId, i }) catch unreachable; + if (@mod(i, 5) == 0) { + const s2 = s.append("-x") catch unreachable; + s = s2; + } + if (@mod(i, 7) == 0) { + const p = s.pin(); + p.drop(); + } + s.drop(); + } + } + }; + + const threadCount: usize = 8; + const iterationsPerThread: usize = 3000; + var threads: [threadCount]std.Thread = undefined; + + for (0..threadCount) |tid| { + threads[tid] = try std.Thread.spawn(.{}, Worker.run, .{ThreadCtx{ + .threadId = tid, + .iterations = iterationsPerThread, + }}); + } + + for (threads) |t| t.join(); + + const s = try RefString.new("post-thread-sanity"); + defer s.drop(); + try std.testing.expectEqualStrings("post-thread-sanity", s.getUtf8()); +} + +test "multithread shared pin and drop" { + try setup(std.testing.allocator, std.testing.io); + defer shutdown(); + + const base = try RefString.new("shared-handle"); + defer base.drop(); + + const ThreadCtx = struct { + handle: RefString, + iterations: usize, + }; + + const Worker = struct { + fn run(ctx: ThreadCtx) void { + var i: usize = 0; + while (i < ctx.iterations) : (i += 1) { + const p = ctx.handle.pin(); + if (@mod(i, 16) == 0) { + _ = p.len(); + } + p.drop(); + } + } + }; + + const threadCount: usize = 12; + const iterationsPerThread: usize = 6000; + var threads: [threadCount]std.Thread = undefined; + + for (0..threadCount) |tid| { + threads[tid] = try std.Thread.spawn(.{}, Worker.run, .{ThreadCtx{ + .handle = base, + .iterations = iterationsPerThread, + }}); + } + + for (threads) |t| t.join(); + + try std.testing.expectEqualStrings("shared-handle", base.getUtf8()); +} diff --git a/engine/p2/src/structures/structured-logging.zig b/engine/p2/src/structures/structured-logging.zig new file mode 100644 index 0000000..a33258d --- /dev/null +++ b/engine/p2/src/structures/structured-logging.zig @@ -0,0 +1,164 @@ +// experiment with a specialized logging infrastructure. +// structured logging. +// +// It can log to an ultra tiny in-memory buffer directly, +// or it can log to a second writer thread. +// but the way it all works is it goes through this logger + +const BumpArena = @import("bump-arena.zig"); + +pub const Verbosity = enum(u8) { + verbose, + log, + warn, + err, +}; + +var gLoggerContext: LoggerContext = undefined; + +pub const LoggerContext = struct { + stdout_buffer: [8192 * 8]u8 = undefined, + stdout_file_writer: std.Io.File.Writer = undefined, + stdout_writer: *std.Io.Writer = undefined, + + arena: std.heap.ArenaAllocator = undefined, + backing: std.mem.Allocator = undefined, + + logMap: std.HashMapUnmanaged(LogRef, u32, LogRef.Context, 80) = .empty, + logMapById: std.ArrayList(LogRef) = .empty, + + loggerStates: std.AutoHashMapUnmanaged(*LoggerState, u32) = .empty, + loggerStatesById: std.ArrayList(*LoggerState) = .empty, + + pub fn insertLoggerStateOrGetId(self: *@This(), state: *LoggerState) u32 { + if (state.id > -1) { + return @intCast(state.id); + } + + if (self.loggerStates.get(state)) |id| { + return id; + } + const allocator = self.arena.allocator(); + + const rv: u32 = @intCast(self.loggerStatesById.items.len); + self.loggerStates.put(allocator, state, rv) catch @panic("unbounded arena oom"); + self.loggerStatesById.append(allocator, state) catch @panic("unbounded arena saw oom"); + return rv; + } + + pub fn insertLogRefOrGetId(self: *@This(), ref: LogRef, idref: *i32) u32 { + if (idref.* > -1) { + return @intCast(idref.*); + } + + if (self.logMap.get(ref)) |key| { + idref.* = @intCast(key); + return key; + } + + const allocator = self.arena.allocator(); + const rv: u32 = @intCast(self.logMapById.items.len); + self.logMapById.append(allocator, ref) catch @panic("unbounded arena saw oom"); + self.logMap.put(allocator, ref, rv) catch @panic("unbounded arena saw oom"); + idref.* = @intCast(rv); + + return rv; + } + + pub fn init(self: *@This(), io: std.Io, allocator: std.mem.Allocator) void { + self.stdout_file_writer = .init(.stdout(), io, &self.stdout_buffer); + self.stdout_writer = &self.stdout_file_writer.interface; + + self.backing = allocator; + self.arena = std.heap.ArenaAllocator.init(self.backing); + } + + pub fn deinit(self: *@This()) void { + self.arena.deinit(); + } +}; + +pub fn initialize(io: std.Io, allocator: std.mem.Allocator) void { + gLoggerContext.init(io, allocator); +} + +pub fn deinit() void { + gLoggerContext.deinit(); +} +pub fn flush() void { + gLoggerContext.stdout_writer.flush() catch {}; +} + +pub const LogRef = struct { + line: u32, + file: []const u8, + fmt: []const u8, + + pub const Context = struct { + pub fn hash(_: @This(), key: LogRef) u64 { + var hasher = std.hash.Wyhash.init(0); + hasher.update(key.file); + hasher.update(std.mem.asBytes(&key.line)); + hasher.update(std.mem.asBytes(&key.fmt)); + return hasher.final(); + } + + pub fn eql(_: @This(), a: LogRef, b: LogRef) bool { + return a.line == b.line and std.mem.eql(u8, a.file, b.file); + } + }; + + pub fn fromSrcFmt(comptime s: std.builtin.SourceLocation, comptime fmt: []const u8) @This() { + return .{ + .line = s.line, + .file = @ptrCast(s.file), + .fmt = fmt, + }; + } +}; + +pub const LoggerState = struct { name: []const u8, verbosity: Verbosity, id: i32 = -1 }; + +pub fn DeclareLogger(comptime LoggerName: []const u8, defaultVerbosity: Verbosity) type { + return struct { + pub var loggerState: LoggerState = .{ + .name = LoggerName, + .verbosity = defaultVerbosity, + }; + + const debug = true; + + pub fn addLog(comptime s: std.builtin.SourceLocation, v: Verbosity, comptime fmt: []const u8, args: anytype) void { + const FmtState = struct { + pub const FMT = fmt; + pub var index: i32 = -1; + }; + + // create a hash of the s: builtin sourcelocation + const sourceId = gLoggerContext.insertLogRefOrGetId(LogRef.fromSrcFmt(s, fmt), &FmtState.index); + const loggerId = gLoggerContext.insertLoggerStateOrGetId(&loggerState); + + if (@intFromEnum(loggerState.verbosity) > @intFromEnum(v)) { + return; + } + + if (debug) { + gLoggerContext.stdout_writer.print("[{d}] [{d}] ", .{ loggerId, sourceId }) catch @panic("io error"); + gLoggerContext.stdout_writer.print(fmt ++ "\n", args) catch @panic("io error"); + } + } + }; +} + +const std = @import("std"); +const builtin = @import("builtin"); + +test "init logger" { + initialize(std.testing.io, std.testing.allocator); + defer deinit(); + + const TestLogger = DeclareLogger("Testing", .log); + TestLogger.addLog(@src(), .log, "testing", .{}); + + flush(); +} diff --git a/engine/p2/src/structures/utils.zig b/engine/p2/src/structures/utils.zig new file mode 100644 index 0000000..eb1d71f --- /dev/null +++ b/engine/p2/src/structures/utils.zig @@ -0,0 +1,226 @@ +const std = @import("std"); + +pub fn createFileWithPath(io: std.Io, filePath: []const u8) !std.Io.File { + var splitEndIterator = std.mem.splitBackwardsAny(u8, filePath, "\\/"); + + if (splitEndIterator.next()) |first| { + const newSlice = filePath[0 .. filePath.len - first.len]; + std.debug.print("ensuring Dir is created {s}\n", .{newSlice}); + try std.Io.Dir.cwd().createDirPath(io, newSlice); + } + + return std.Io.Dir.cwd().createFile(io, filePath, .{ .read = true, .truncate = true }); +} + +pub fn makePathAny(io: std.Io, path: []const u8) !void { + if (!std.Io.Dir.path.isAbsolute(path)) { + return std.Io.Dir.cwd().createDirPath(io, path); + } + + std.Io.Dir.accessAbsolute(io, path, .{}) catch |err| switch (err) { + error.FileNotFound => {}, + else => return err, + }; + + const parent = std.Io.Dir.path.dirname(path) orelse return; + if (parent.len > 0 and !std.mem.eql(u8, parent, path)) { + try makePathAny(io, parent); + } + + std.Io.Dir.createDirAbsolute(io, path, .default_dir) catch |err| switch (err) { + error.PathAlreadyExists => {}, + else => return err, + }; +} + +pub fn loadFileAlloc(io: std.Io, filename: []const u8, comptime alignment: std.mem.Alignment, allocator: std.mem.Allocator) ![]u8 { + const cwd = std.Io.Dir.cwd(); + const filesize = (try cwd.statFile(io, filename, .{})).size + 1; // add null byte + const buffer: []u8 = try allocator.alignedAlloc(u8, alignment, filesize); + errdefer allocator.free(buffer); + var file = try cwd.openFile(io, filename, .{}); + defer file.close(io); + var read_buffer: [4096]u8 = undefined; + var reader = file.reader(io, &read_buffer); + try reader.interface.readSliceAll(buffer[0 .. buffer.len - 1]); + buffer[buffer.len - 1] = 0; + return buffer; +} + +pub fn grapvizDotToPng(allocator: std.mem.Allocator, io: std.Io, vizFile: []const u8, pngFile: []const u8) !void { + const sourceFile = try std.fmt.allocPrint(allocator, "Saved/{s}", .{vizFile}); + defer allocator.free(sourceFile); + + const imageFile = try std.fmt.allocPrint(allocator, "Saved/{s}", .{pngFile}); + defer allocator.free(imageFile); + + var child = try std.process.spawn(io, .{ + .argv = &.{ "dot", "-Tpng", sourceFile, "-o", imageFile }, + }); + _ = try child.wait(io); +} + +pub fn dupeString(allocator: std.mem.Allocator, string: []const u8) ![]u8 { + const dupe = try allocator.alloc(u8, string.len); + + std.mem.copyForwards(u8, dupe, string); + + return dupe; +} + +pub const FileLog = struct { + buffer: std.Io.Writer.Allocating, + allocator: std.mem.Allocator, + fileName: []u8, + + pub fn init(allocator: std.mem.Allocator, fileName: []const u8) !@This() { + return .{ + .buffer = std.Io.Writer.Allocating.init(allocator), + .allocator = allocator, + .fileName = try dupeString(allocator, fileName), + }; + } + + pub fn write(self: *@This(), comptime fmt: []const u8, args: anytype) !void { + try self.buffer.writer.print(fmt, args); + } + + pub fn writeOut(self: @This(), io: std.Io) !void { + const cwd = std.Io.Dir.cwd(); + const ofile = try std.fmt.allocPrint(self.allocator, "Saved/{s}", .{self.fileName}); + defer self.allocator.free(ofile); + try cwd.createDirPath(io, "Saved"); + try cwd.writeFile(io, .{ .sub_path = ofile, .data = self.buffer.written() }); + } + + pub fn deinit(self: *@This()) void { + self.allocator.free(self.fileName); + self.buffer.deinit(); + } +}; + +pub fn assertf(eval: anytype, comptime fmt: []const u8, args: anytype) !void { + if (!eval) { + std.debug.print("\n\n[Error]: " ++ fmt ++ "\n\n", args); + return error.AssertFailure; + } +} + +pub fn asserts(eval: anytype, comptime fmt: []const u8, args: anytype, comptime tag: []const u8) void { + if (!eval) { + std.debug.print("[Error]: " ++ fmt, args); + std.debug.print("> " ++ tag, .{}); + @panic("assertion failed"); + } +} + +pub fn assert(eval: anytype) !void { + if (!eval) { + return error.AssertFailure; + } +} + +// gets the basename of the file/path +pub fn getBasePath(path: []const u8) []const u8 { + if (path.len == 0) { + return ""; + } + + if (path[path.len - 1] == '/' or path[path.len - 1] == '\\') { + return getBasePath(path[0 .. path.len - 1]); + } + + var i: i32 = @intCast(path.len - 1); + + while (i >= 0) : (i -= 1) { + const c = path[@intCast(i)]; + + if (c == '/' or c == '\\') { + return path[@intCast(i + 1)..]; + } + } + + return path; +} + +// gets the folder name of the dir/path +pub fn getFolder(path: []const u8) []const u8 { + if (path.len == 0) { + unreachable; + } + + if (path[path.len - 1] == '/' or path[path.len - 1] == '\\') { + return getBasePath(path[0 .. path.len - 1]); + } + + var i: i32 = @intCast(path.len - 1); + + while (i >= 0) : (i -= 1) { + const c = path[@intCast(i)]; + + if (c == '/' or c == '\\') { + return path[0..@intCast(i)]; + } + } + + return path; +} + +pub fn getFileExtension(path: []const u8) []const u8 { + for (path, 0..) |c, i| { + if (c == '.') { + return path[i..]; + } + } + return path; +} + +// removes whitespace from start and end +pub fn stringStrip(p: []const u8) []const u8 { + var s: usize = 0; + while (s < p.len) : (s += 1) { + if (!std.ascii.isWhitespace(p[s])) { + break; + } + } + var e: usize = p.len; + while (e > 0) : (e -= 1) { + if (!std.ascii.isWhitespace(p[e - 1])) { + break; + } + } + + if (s >= e) return p[0..0]; + return p[s..e]; +} + +pub fn splitSliceWork(comptime T: type, slice: []T, id: u32, count: u32) struct { slice: []T, startIndex: usize } { + const stride = @divFloor(slice.len, count); + const rem = @rem(slice.len, count); + + // let s = stride if index < remainder + // let r = stride if index >= remainder + // + // formula: + // x < R; start = s * x; stride = s + // x >=R; start = R * s + (x - R) * r; stride = r + // + // combining... + // + const s = stride + 1; + const r = stride; + + if (id < rem) { + const start = s * id; + return .{ .slice = slice[start .. start + s], .startIndex = start }; + } else { + const start = s * rem + (id - rem) * r; + return .{ .slice = slice[start .. start + r], .startIndex = start }; + } +} + +test "stringStrip handles empty and whitespace-only input" { + try std.testing.expectEqualStrings("", stringStrip("")); + try std.testing.expectEqualStrings("", stringStrip(" \t\r\n")); + try std.testing.expectEqualStrings("abc", stringStrip(" \t abc \n")); +} diff --git a/engine/p2/src/structures/zmath.zig b/engine/p2/src/structures/zmath.zig new file mode 100644 index 0000000..4e00fdc --- /dev/null +++ b/engine/p2/src/structures/zmath.zig @@ -0,0 +1,4182 @@ +pub const version = @import("std").SemanticVersion{ .major = 0, .minor = 9, .patch = 4 }; +// ============================================================================== +// +// SIMD math library for game developers +// https://github.com/michal-z/zig-gamedev/tree/main/libs/zmath +// +// Should work on all OSes supported by Zig. Works on x86_64 and ARM. +// Provides ~140 optimized routines and ~70 extensive tests. +// Can be used with any graphics API. +// +// zmath uses row-major matrices, row vectors (each row vector is stored in a SIMD register). +// Handedness is determined by which function version is used (Rh vs. Lh), +// otherwise the function works with either left-handed or right-handed view coordinates. +// +// const va = f32x4(1.0, 2.0, 3.0, 1.0); +// const vb = f32x4(-1.0, 1.0, -1.0, 1.0); +// const v0 = va + vb - f32x4(0.0, 1.0, 0.0, 1.0) * f32x4s(3.0); +// const v1 = cross3(va, vb) + f32x4(1.0, 1.0, 1.0, 1.0); +// const v2 = va + dot3(va, vb) / v1; // dotN() returns scalar replicated on all vector components +// +// const m = rotationX(math.pi * 0.25); +// const v = f32x4(...); +// const v0 = mul(v, m); // 'v' treated as a row vector +// const v1 = mul(m, v); // 'v' treated as a column vector +// const f = m[row][column]; +// +// const b = va < vb; +// if (all(b, 0)) { ... } // '0' means check all vector components; if all are 'true' +// if (all(b, 3)) { ... } // '3' means check first three vector components; if all first three are 'true' +// if (any(b, 0)) { ... } // '0' means check all vector components; if any is 'true' +// if (any(b, 3)) { ... } // '3' means check first three vector components; if any from first three is 'true' +// +// var v4 = load(mem[0..], F32x4, 0); +// var v8 = load(mem[100..], F32x8, 0); +// var v16 = load(mem[200..], F32x16, 0); +// +// var camera_position = [3]f32{ 1.0, 2.0, 3.0 }; +// var cam_pos = loadArr3(camera_position); +// ... +// storeArr3(&camera_position, cam_pos); +// +// v4 = sin(v4); // SIMDx4 +// v8 = cos(v8); // .x86_64 -> 2 x SIMDx4, .x86_64+avx+fma -> SIMDx8 +// v16 = atan(v16); // .x86_64 -> 4 x SIMDx4, .x86_64+avx+fma -> 2 x SIMDx8, .x86_64+avx512f -> SIMDx16 +// +// store(mem[0..], v4, 0); +// store(mem[100..], v8, 0); +// store(mem[200..], v16, 0); +// +// ------------------------------------------------------------------------------ +// 1. Initialization functions +// ------------------------------------------------------------------------------ +// +// f32x4(e0: f32, e1: f32, e2: f32, e3: f32) F32x4 +// f32x8(e0: f32, e1: f32, e2: f32, e3: f32, e4: f32, e5: f32, e6: f32, e7: f32) F32x8 +// f32x16(e0: f32, e1: f32, e2: f32, e3: f32, e4: f32, e5: f32, e6: f32, e7: f32, +// e8: f32, e9: f32, ea: f32, eb: f32, ec: f32, ed: f32, ee: f32, ef: f32) F32x16 +// +// f32x4s(e0: f32) F32x4 +// f32x8s(e0: f32) F32x8 +// f32x16s(e0: f32) F32x16 +// +// boolx4(e0: bool, e1: bool, e2: bool, e3: bool) Boolx4 +// boolx8(e0: bool, e1: bool, e2: bool, e3: bool, e4: bool, e5: bool, e6: bool, e7: bool) Boolx8 +// boolx16(e0: bool, e1: bool, e2: bool, e3: bool, e4: bool, e5: bool, e6: bool, e7: bool, +// e8: bool, e9: bool, ea: bool, eb: bool, ec: bool, ed: bool, ee: bool, ef: bool) Boolx16 +// +// load(mem: []const f32, comptime T: type, comptime len: u32) T +// store(mem: []f32, v: anytype, comptime len: u32) void +// +// loadArr2(arr: [2]f32) F32x4 +// loadArr2zw(arr: [2]f32, z: f32, w: f32) F32x4 +// loadArr3(arr: [3]f32) F32x4 +// loadArr3w(arr: [3]f32, w: f32) F32x4 +// loadArr4(arr: [4]f32) F32x4 +// +// storeArr2(arr: *[2]f32, v: F32x4) void +// storeArr3(arr: *[3]f32, v: F32x4) void +// storeArr4(arr: *[4]f32, v: F32x4) void +// +// arr3Ptr(ptr: anytype) *const [3]f32 +// arrNPtr(ptr: anytype) [*]const f32 +// +// splat(comptime T: type, value: f32) T +// splatInt(comptime T: type, value: u32) T +// +// ------------------------------------------------------------------------------ +// 2. Functions that work on all vector components (F32xN = F32x4 or F32x8 or F32x16) +// ------------------------------------------------------------------------------ +// +// all(vb: anytype, comptime len: u32) bool +// any(vb: anytype, comptime len: u32) bool +// +// isNearEqual(v0: F32xN, v1: F32xN, epsilon: F32xN) BoolxN +// isNan(v: F32xN) BoolxN +// isInf(v: F32xN) BoolxN +// isInBounds(v: F32xN, bounds: F32xN) BoolxN +// +// andInt(v0: F32xN, v1: F32xN) F32xN +// andNotInt(v0: F32xN, v1: F32xN) F32xN +// orInt(v0: F32xN, v1: F32xN) F32xN +// norInt(v0: F32xN, v1: F32xN) F32xN +// xorInt(v0: F32xN, v1: F32xN) F32xN +// +// minFast(v0: F32xN, v1: F32xN) F32xN +// maxFast(v0: F32xN, v1: F32xN) F32xN +// min(v0: F32xN, v1: F32xN) F32xN +// max(v0: F32xN, v1: F32xN) F32xN +// round(v: F32xN) F32xN +// floor(v: F32xN) F32xN +// trunc(v: F32xN) F32xN +// ceil(v: F32xN) F32xN +// clamp(v0: F32xN, v1: F32xN) F32xN +// clampFast(v0: F32xN, v1: F32xN) F32xN +// saturate(v: F32xN) F32xN +// saturateFast(v: F32xN) F32xN +// lerp(v0: F32xN, v1: F32xN, t: f32) F32xN +// lerpV(v0: F32xN, v1: F32xN, t: F32xN) F32xN +// sqrt(v: F32xN) F32xN +// abs(v: F32xN) F32xN +// mod(v0: F32xN, v1: F32xN) F32xN +// modAngle(v: F32xN) F32xN +// mulAdd(v0: F32xN, v1: F32xN, v2: F32xN) F32xN +// select(mask: BoolxN, v0: F32xN, v1: F32xN) +// sin(v: F32xN) F32xN +// cos(v: F32xN) F32xN +// sincos(v: F32xN) [2]F32xN +// asin(v: F32xN) F32xN +// acos(v: F32xN) F32xN +// atan(v: F32xN) F32xN +// atan2(vy: F32xN, vx: F32xN) F32xN +// cmulSoa(re0: F32xN, im0: F32xN, re1: F32xN, im1: F32xN) [2]F32xN +// +// ------------------------------------------------------------------------------ +// 3. 2D, 3D, 4D vector functions +// ------------------------------------------------------------------------------ +// +// swizzle(v: Vec, c, c, c, c) Vec (comptime c = .x | .y | .z | .w) +// dot2(v0: Vec, v1: Vec) F32x4 +// dot3(v0: Vec, v1: Vec) F32x4 +// dot4(v0: Vec, v1: Vec) F32x4 +// cross3(v0: Vec, v1: Vec) Vec +// lengthSq2(v: Vec) F32x4 +// lengthSq3(v: Vec) F32x4 +// lengthSq4(v: Vec) F32x4 +// length2(v: Vec) F32x4 +// length3(v: Vec) F32x4 +// length4(v: Vec) F32x4 +// normalize2(v: Vec) Vec +// normalize3(v: Vec) Vec +// normalize4(v: Vec) Vec +// +// vecToArr2(v: Vec) [2]f32 +// vecToArr3(v: Vec) [3]f32 +// vecToArr4(v: Vec) [4]f32 +// +// ------------------------------------------------------------------------------ +// 4. Matrix functions +// ------------------------------------------------------------------------------ +// +// identity() Mat +// mul(m0: Mat, m1: Mat) Mat +// mul(s: f32, m: Mat) Mat +// mul(m: Mat, s: f32) Mat +// mul(v: Vec, m: Mat) Vec +// mul(m: Mat, v: Vec) Vec +// transpose(m: Mat) Mat +// rotationX(angle: f32) Mat +// rotationY(angle: f32) Mat +// rotationZ(angle: f32) Mat +// translation(x: f32, y: f32, z: f32) Mat +// translationV(v: Vec) Mat +// scaling(x: f32, y: f32, z: f32) Mat +// scalingV(v: Vec) Mat +// lookToLh(eyepos: Vec, eyedir: Vec, updir: Vec) Mat +// lookAtLh(eyepos: Vec, focuspos: Vec, updir: Vec) Mat +// lookToRh(eyepos: Vec, eyedir: Vec, updir: Vec) Mat +// lookAtRh(eyepos: Vec, focuspos: Vec, updir: Vec) Mat +// perspectiveFovLh(fovy: f32, aspect: f32, near: f32, far: f32) Mat +// perspectiveFovRh(fovy: f32, aspect: f32, near: f32, far: f32) Mat +// perspectiveFovRhGl(fovy: f32, aspect: f32, near: f32, far: f32) Mat +// orthographicLh(w: f32, h: f32, near: f32, far: f32) Mat +// orthographicRh(w: f32, h: f32, near: f32, far: f32) Mat +// orthographicOffCenterLh(left: f32, right: f32, top: f32, bottom: f32, near: f32, far: f32) Mat +// orthographicOffCenterRh(left: f32, right: f32, top: f32, bottom: f32, near: f32, far: f32) Mat +// determinant(m: Mat) F32x4 +// inverse(m: Mat) Mat +// inverseDet(m: Mat, det: ?*F32x4) Mat +// matToQuat(m: Mat) Quat +// matFromAxisAngle(axis: Vec, angle: f32) Mat +// matFromNormAxisAngle(axis: Vec, angle: f32) Mat +// matFromQuat(quat: Quat) Mat +// matFromRollPitchYaw(pitch: f32, yaw: f32, roll: f32) Mat +// matFromRollPitchYawV(angles: Vec) Mat +// +// loadMat(mem: []const f32) Mat +// loadMat43(mem: []const f32) Mat +// loadMat34(mem: []const f32) Mat +// storeMat(mem: []f32, m: Mat) void +// storeMat43(mem: []f32, m: Mat) void +// storeMat34(mem: []f32, m: Mat) void +// +// matToArr(m: Mat) [16]f32 +// matToArr43(m: Mat) [12]f32 +// matToArr34(m: Mat) [12]f32 +// +// ------------------------------------------------------------------------------ +// 5. Quaternion functions +// ------------------------------------------------------------------------------ +// +// qmul(q0: Quat, q1: Quat) Quat +// qidentity() Quat +// conjugate(quat: Quat) Quat +// inverse(q: Quat) Quat +// slerp(q0: Quat, q1: Quat, t: f32) Quat +// slerpV(q0: Quat, q1: Quat, t: F32x4) Quat +// quatToMat(quat: Quat) Mat +// quatToAxisAngle(quat: Quat, axis: *Vec, angle: *f32) void +// quatFromMat(m: Mat) Quat +// quatFromAxisAngle(axis: Vec, angle: f32) Quat +// quatFromNormAxisAngle(axis: Vec, angle: f32) Quat +// quatFromRollPitchYaw(pitch: f32, yaw: f32, roll: f32) Quat +// quatFromRollPitchYawV(angles: Vec) Quat +// +// ------------------------------------------------------------------------------ +// 6. Color functions +// ------------------------------------------------------------------------------ +// +// adjustSaturation(color: F32x4, saturation: f32) F32x4 +// adjustContrast(color: F32x4, contrast: f32) F32x4 +// rgbToHsl(rgb: F32x4) F32x4 +// hslToRgb(hsl: F32x4) F32x4 +// rgbToHsv(rgb: F32x4) F32x4 +// hsvToRgb(hsv: F32x4) F32x4 +// rgbToSrgb(rgb: F32x4) F32x4 +// srgbToRgb(srgb: F32x4) F32x4 +// +// ------------------------------------------------------------------------------ +// X. Misc functions +// ------------------------------------------------------------------------------ +// +// linePointDistance(linept0: Vec, linept1: Vec, pt: Vec) F32x4 +// sin(v: f32) f32 +// cos(v: f32) f32 +// sincos(v: f32) [2]f32 +// asin(v: f32) f32 +// acos(v: f32) f32 +// +// fftInitUnityTable(unitytable: []F32x4) void +// fft(re: []F32x4, im: []F32x4, unitytable: []const F32x4) void +// ifft(re: []F32x4, im: []const F32x4, unitytable: []const F32x4) void +// +// ============================================================================== + +// Fundamental types +pub const F32x4 = @Vector(4, f32); +pub const F32x8 = @Vector(8, f32); +pub const F32x16 = @Vector(16, f32); +pub const Boolx4 = @Vector(4, bool); +pub const Boolx8 = @Vector(8, bool); +pub const Boolx16 = @Vector(16, bool); + +// "Higher-level" aliases +pub const Vec = F32x4; +pub const Mat = [4]F32x4; +pub const Quat = F32x4; + +const builtin = @import("builtin"); +const std = @import("std"); +const math = std.math; +const assert = std.debug.assert; +const expect = std.testing.expect; + +const cpu_arch = builtin.cpu.arch; +const has_avx = if (cpu_arch == .x86_64) std.Target.x86.featureSetHas(builtin.cpu.features, .avx) else false; +const has_avx512f = if (cpu_arch == .x86_64) std.Target.x86.featureSetHas(builtin.cpu.features, .avx512f) else false; +const has_fma = if (cpu_arch == .x86_64) std.Target.x86.featureSetHas(builtin.cpu.features, .fma) else false; +// ------------------------------------------------------------------------------ +// +// 1. Initialization functions +// +// ------------------------------------------------------------------------------ +pub inline fn f32x4(e0: f32, e1: f32, e2: f32, e3: f32) F32x4 { + return .{ e0, e1, e2, e3 }; +} +pub inline fn f32x8(e0: f32, e1: f32, e2: f32, e3: f32, e4: f32, e5: f32, e6: f32, e7: f32) F32x8 { + return .{ e0, e1, e2, e3, e4, e5, e6, e7 }; +} +// zig fmt: off +pub inline fn f32x16( + e0: f32, e1: f32, e2: f32, e3: f32, e4: f32, e5: f32, e6: f32, e7: f32, + e8: f32, e9: f32, ea: f32, eb: f32, ec: f32, ed: f32, ee: f32, ef: f32) F32x16 { + return .{ e0, e1, e2, e3, e4, e5, e6, e7, e8, e9, ea, eb, ec, ed, ee, ef }; +} +// zig fmt: on + +pub inline fn f32x4s(e0: f32) F32x4 { + return splat(F32x4, e0); +} +pub inline fn f32x8s(e0: f32) F32x8 { + return splat(F32x8, e0); +} +pub inline fn f32x16s(e0: f32) F32x16 { + return splat(F32x16, e0); +} + +pub inline fn boolx4(e0: bool, e1: bool, e2: bool, e3: bool) Boolx4 { + return .{ e0, e1, e2, e3 }; +} +pub inline fn boolx8(e0: bool, e1: bool, e2: bool, e3: bool, e4: bool, e5: bool, e6: bool, e7: bool) Boolx8 { + return .{ e0, e1, e2, e3, e4, e5, e6, e7 }; +} +// zig fmt: off +pub inline fn boolx16( + e0: bool, e1: bool, e2: bool, e3: bool, e4: bool, e5: bool, e6: bool, e7: bool, + e8: bool, e9: bool, ea: bool, eb: bool, ec: bool, ed: bool, ee: bool, ef: bool) Boolx16 { + return .{ e0, e1, e2, e3, e4, e5, e6, e7, e8, e9, ea, eb, ec, ed, ee, ef }; +} +// zig fmt: on + +pub inline fn veclen(comptime T: type) comptime_int { + return @typeInfo(T).vector.len; +} + +pub inline fn splat(comptime T: type, value: f32) T { + return @splat(value); +} +pub inline fn splatInt(comptime T: type, value: u32) T { + return @splat(@as(f32, @bitCast(value))); +} + +pub fn load(mem: []const f32, comptime T: type, comptime len: u32) T { + var v = splat(T, 0.0); + const loop_len = if (len == 0) veclen(T) else len; + comptime var i: u32 = 0; + inline while (i < loop_len) : (i += 1) { + v[i] = mem[i]; + } + return v; +} +test "zmath.load" { + const a = [7]f32{ 1.0, 2.0, 3.0, 4.0, 5.0, 6.0, 7.0 }; + var ptr = &a; + var i: u32 = 0; + const v0 = load(a[i..], F32x4, 2); + try expect(approxEqAbs(v0, F32x4{ 1.0, 2.0, 0.0, 0.0 }, 0.0)); + i += 2; + const v1 = load(a[i .. i + 2], F32x4, 2); + try expect(approxEqAbs(v1, F32x4{ 3.0, 4.0, 0.0, 0.0 }, 0.0)); + const v2 = load(a[5..7], F32x4, 2); + try expect(approxEqAbs(v2, F32x4{ 6.0, 7.0, 0.0, 0.0 }, 0.0)); + const v3 = load(ptr[1..], F32x4, 2); + try expect(approxEqAbs(v3, F32x4{ 2.0, 3.0, 0.0, 0.0 }, 0.0)); + i += 1; + const v4 = load(ptr[i .. i + 2], F32x4, 2); + try expect(approxEqAbs(v4, F32x4{ 4.0, 5.0, 0.0, 0.0 }, 0.0)); +} + +pub fn store(mem: []f32, v: anytype, comptime len: u32) void { + const T = @TypeOf(v); + const loop_len = if (len == 0) veclen(T) else len; + comptime var i: u32 = 0; + inline while (i < loop_len) : (i += 1) { + mem[i] = v[i]; + } +} +test "zmath.store" { + var a = [7]f32{ 1.0, 2.0, 3.0, 4.0, 5.0, 6.0, 7.0 }; + const v = load(a[1..], F32x4, 3); + store(a[2..], v, 4); + try expect(a[0] == 1.0); + try expect(a[1] == 2.0); + try expect(a[2] == 2.0); + try expect(a[3] == 3.0); + try expect(a[4] == 4.0); + try expect(a[5] == 0.0); +} + +pub inline fn loadArr2(arr: [2]f32) F32x4 { + return f32x4(arr[0], arr[1], 0.0, 0.0); +} +pub inline fn loadArr2zw(arr: [2]f32, z: f32, w: f32) F32x4 { + return f32x4(arr[0], arr[1], z, w); +} +pub inline fn loadArr3(arr: [3]f32) F32x4 { + return f32x4(arr[0], arr[1], arr[2], 0.0); +} +pub inline fn loadArr3w(arr: [3]f32, w: f32) F32x4 { + return f32x4(arr[0], arr[1], arr[2], w); +} +pub inline fn loadArr4(arr: [4]f32) F32x4 { + return f32x4(arr[0], arr[1], arr[2], arr[3]); +} + +pub inline fn storeArr2(arr: *[2]f32, v: F32x4) void { + arr.* = .{ v[0], v[1] }; +} +pub inline fn storeArr3(arr: *[3]f32, v: F32x4) void { + arr.* = .{ v[0], v[1], v[2] }; +} +pub inline fn storeArr4(arr: *[4]f32, v: F32x4) void { + arr.* = .{ v[0], v[1], v[2], v[3] }; +} + +pub inline fn arr3Ptr(ptr: anytype) *const [3]f32 { + comptime assert(@typeInfo(@TypeOf(ptr)) == .Pointer); + const T = std.meta.Child(@TypeOf(ptr)); + comptime assert(T == F32x4); + return @as(*const [3]f32, @ptrCast(ptr)); +} + +pub inline fn arrNPtr(ptr: anytype) [*]const f32 { + comptime assert(@typeInfo(@TypeOf(ptr)) == .pointer); + const T = std.meta.Child(@TypeOf(ptr)); + comptime assert(T == Mat or T == F32x4 or T == F32x8 or T == F32x16); + return @as([*]const f32, @ptrCast(ptr)); +} +test "zmath.arrNPtr" { + { + const mat = identity(); + const f32ptr = arrNPtr(&mat); + try expect(f32ptr[0] == 1.0); + try expect(f32ptr[5] == 1.0); + try expect(f32ptr[10] == 1.0); + try expect(f32ptr[15] == 1.0); + } + { + const v8 = f32x8s(1.0); + const f32ptr = arrNPtr(&v8); + try expect(f32ptr[1] == 1.0); + try expect(f32ptr[7] == 1.0); + } +} + +test "zmath.loadArr" { + { + const camera_position = [3]f32{ 1.0, 2.0, 3.0 }; + const simd_reg = loadArr3(camera_position); + try expect(approxEqAbs(simd_reg, f32x4(1.0, 2.0, 3.0, 0.0), 0.0)); + } + { + const camera_position = [3]f32{ 1.0, 2.0, 3.0 }; + const simd_reg = loadArr3w(camera_position, 1.0); + try expect(approxEqAbs(simd_reg, f32x4(1.0, 2.0, 3.0, 1.0), 0.0)); + } +} + +pub inline fn vecToArr2(v: Vec) [2]f32 { + return .{ v[0], v[1] }; +} +pub inline fn vecToArr3(v: Vec) [3]f32 { + return .{ v[0], v[1], v[2] }; +} +pub inline fn vecToArr4(v: Vec) [4]f32 { + return .{ v[0], v[1], v[2], v[3] }; +} +// ------------------------------------------------------------------------------ +// +// 2. Functions that work on all vector components (F32xN = F32x4 or F32x8 or F32x16) +// +// ------------------------------------------------------------------------------ +pub fn all(vb: anytype, comptime len: u32) bool { + const T = @TypeOf(vb); + if (len > veclen(T)) { + @compileError("zmath.all(): 'len' is greater than vector len of type " ++ @typeName(T)); + } + const loop_len = if (len == 0) veclen(T) else len; + const ab: [veclen(T)]bool = vb; + comptime var i: u32 = 0; + var result = true; + inline while (i < loop_len) : (i += 1) { + result = result and ab[i]; + } + return result; +} +test "zmath.all" { + try expect(all(boolx8(true, true, true, true, true, false, true, false), 5) == true); + try expect(all(boolx8(true, true, true, true, true, false, true, false), 6) == false); + try expect(all(boolx8(true, true, true, true, false, false, false, false), 4) == true); + try expect(all(boolx4(true, true, true, false), 3) == true); + try expect(all(boolx4(true, true, true, false), 1) == true); + try expect(all(boolx4(true, false, false, false), 1) == true); + try expect(all(boolx4(false, true, false, false), 1) == false); + try expect(all(boolx8(true, true, true, true, true, false, true, false), 0) == false); + try expect(all(boolx4(false, true, false, false), 0) == false); + try expect(all(boolx4(true, true, true, true), 0) == true); +} + +pub fn any(vb: anytype, comptime len: u32) bool { + const T = @TypeOf(vb); + if (len > veclen(T)) { + @compileError("zmath.any(): 'len' is greater than vector len of type " ++ @typeName(T)); + } + const loop_len = if (len == 0) veclen(T) else len; + const ab: [veclen(T)]bool = vb; + comptime var i: u32 = 0; + var result = false; + inline while (i < loop_len) : (i += 1) { + result = result or ab[i]; + } + return result; +} +test "zmath.any" { + try expect(any(boolx8(true, true, true, true, true, false, true, false), 0) == true); + try expect(any(boolx8(false, false, false, true, true, false, true, false), 3) == false); + try expect(any(boolx8(false, false, false, false, false, true, false, false), 4) == false); +} + +pub inline fn isNearEqual( + v0: anytype, + v1: anytype, + epsilon: anytype, +) @Vector(veclen(@TypeOf(v0)), bool) { + const T = @TypeOf(v0, v1, epsilon); + const delta = v0 - v1; + const temp = maxFast(delta, splat(T, 0.0) - delta); + return temp <= epsilon; +} +test "zmath.isNearEqual" { + if (builtin.target.os.tag == .macos and builtin.zig_backend != .stage1) return error.SkipZigTest; + { + const v0 = f32x4(1.0, 2.0, -3.0, 4.001); + const v1 = f32x4(1.0, 2.1, 3.0, 4.0); + const b = isNearEqual(v0, v1, splat(F32x4, 0.01)); + try expect(@reduce(.And, b == boolx4(true, false, false, true))); + } + { + const v0 = f32x8(1.0, 2.0, -3.0, 4.001, 1.001, 2.3, -0.0, 0.0); + const v1 = f32x8(1.0, 2.1, 3.0, 4.0, -1.001, 2.1, 0.0, 0.0); + const b = isNearEqual(v0, v1, splat(F32x8, 0.01)); + try expect(@reduce(.And, b == boolx8(true, false, false, true, false, false, true, true))); + } + try expect(all(isNearEqual( + splat(F32x4, math.inf(f32)), + splat(F32x4, math.inf(f32)), + splat(F32x4, 0.0001), + ), 0) == false); + try expect(all(isNearEqual( + splat(F32x4, -math.inf(f32)), + splat(F32x4, math.inf(f32)), + splat(F32x4, 0.0001), + ), 0) == false); + try expect(all(isNearEqual( + splat(F32x4, -math.inf(f32)), + splat(F32x4, -math.inf(f32)), + splat(F32x4, 0.0001), + ), 0) == false); + try expect(all(isNearEqual( + splat(F32x4, -math.nan(f32)), + splat(F32x4, math.inf(f32)), + splat(F32x4, 0.0001), + ), 0) == false); +} + +pub inline fn isNan( + v: anytype, +) @Vector(veclen(@TypeOf(v)), bool) { + return v != v; +} +test "zmath.isNan" { + { + const v0 = f32x4(math.inf(f32), math.nan(f32), math.nan(f32), 7.0); + const b = isNan(v0); + try expect(@reduce(.And, b == boolx4(false, true, true, false))); + } + { + const v0 = f32x8(0, math.nan(f32), 0, 0, math.inf(f32), math.nan(f32), math.nan(f32), 7.0); + const b = isNan(v0); + try expect(@reduce(.And, b == boolx8(false, true, false, false, false, true, true, false))); + } +} + +pub inline fn isInf( + v: anytype, +) @Vector(veclen(@TypeOf(v)), bool) { + const T = @TypeOf(v); + return abs(v) == splat(T, math.inf(f32)); +} +test "zmath.isInf" { + { + const v0 = f32x4(math.inf(f32), math.nan(f32), math.nan(f32), 7.0); + const b = isInf(v0); + try expect(@reduce(.And, b == boolx4(true, false, false, false))); + } + { + const v0 = f32x8(0, math.inf(f32), 0, 0, math.inf(f32), math.nan(f32), math.nan(f32), 7.0); + const b = isInf(v0); + try expect(@reduce(.And, b == boolx8(false, true, false, false, true, false, false, false))); + } +} + +pub inline fn isInBounds( + v: anytype, + bounds: anytype, +) @Vector(veclen(@TypeOf(v)), bool) { + const T = @TypeOf(v, bounds); + const Tu = @Vector(veclen(T), u1); + const Tr = @Vector(veclen(T), bool); + + // 2 x cmpleps, xorps, load, andps + const b0 = v <= bounds; + const b1 = (bounds * splat(T, -1.0)) <= v; + const b0u = @as(Tu, @bitCast(b0)); + const b1u = @as(Tu, @bitCast(b1)); + return @as(Tr, @bitCast(b0u & b1u)); +} +test "zmath.isInBounds" { + { + const v0 = f32x4(0.5, -2.0, -1.0, 1.9); + const v1 = f32x4(-1.6, -2.001, -1.0, 1.9); + const bounds = f32x4(1.0, 2.0, 1.0, 2.0); + const b0 = isInBounds(v0, bounds); + const b1 = isInBounds(v1, bounds); + try expect(@reduce(.And, b0 == boolx4(true, true, true, true))); + try expect(@reduce(.And, b1 == boolx4(false, false, true, true))); + } + { + const v0 = f32x8(2.0, 1.0, 2.0, 1.0, 0.5, -2.0, -1.0, 1.9); + const bounds = f32x8(1.0, 1.0, 1.0, math.inf(f32), 1.0, math.nan(f32), 1.0, 2.0); + const b0 = isInBounds(v0, bounds); + try expect(@reduce(.And, b0 == boolx8(false, true, false, true, true, false, true, true))); + } +} + +pub inline fn andInt(v0: anytype, v1: anytype) @TypeOf(v0, v1) { + const T = @TypeOf(v0, v1); + const Tu = @Vector(veclen(T), u32); + const v0u = @as(Tu, @bitCast(v0)); + const v1u = @as(Tu, @bitCast(v1)); + return @as(T, @bitCast(v0u & v1u)); // andps +} +test "zmath.andInt" { + { + const v0 = f32x4(0, @as(f32, @bitCast(~@as(u32, 0))), 0, @as(f32, @bitCast(~@as(u32, 0)))); + const v1 = f32x4(1.0, 2.0, 3.0, math.inf(f32)); + const v = andInt(v0, v1); + try expect(v[3] == math.inf(f32)); + try expect(approxEqAbs(v, f32x4(0.0, 2.0, 0.0, math.inf(f32)), 0.0)); + } + { + const v0 = f32x8(0, 0, 0, 0, 0, @as(f32, @bitCast(~@as(u32, 0))), 0, @as(f32, @bitCast(~@as(u32, 0)))); + const v1 = f32x8(0, 0, 0, 0, 1.0, 2.0, 3.0, math.inf(f32)); + const v = andInt(v0, v1); + try expect(v[7] == math.inf(f32)); + try expect(approxEqAbs(v, f32x8(0, 0, 0, 0, 0.0, 2.0, 0.0, math.inf(f32)), 0.0)); + } +} + +pub inline fn andNotInt(v0: anytype, v1: anytype) @TypeOf(v0, v1) { + const T = @TypeOf(v0, v1); + const Tu = @Vector(veclen(T), u32); + const v0u = @as(Tu, @bitCast(v0)); + const v1u = @as(Tu, @bitCast(v1)); + return @as(T, @bitCast(~v0u & v1u)); // andnps +} +test "zmath.andNotInt" { + { + const v0 = f32x4(1.0, 2.0, 3.0, 4.0); + const v1 = f32x4(0, @as(f32, @bitCast(~@as(u32, 0))), 0, @as(f32, @bitCast(~@as(u32, 0)))); + const v = andNotInt(v1, v0); + try expect(approxEqAbs(v, f32x4(1.0, 0.0, 3.0, 0.0), 0.0)); + } + { + const v0 = f32x8(0, 0, 0, 0, 1.0, 2.0, 3.0, 4.0); + const v1 = f32x8(0, 0, 0, 0, 0, @as(f32, @bitCast(~@as(u32, 0))), 0, @as(f32, @bitCast(~@as(u32, 0)))); + const v = andNotInt(v1, v0); + try expect(approxEqAbs(v, f32x8(0, 0, 0, 0, 1.0, 0.0, 3.0, 0.0), 0.0)); + } +} + +pub inline fn orInt(v0: anytype, v1: anytype) @TypeOf(v0, v1) { + const T = @TypeOf(v0, v1); + const Tu = @Vector(veclen(T), u32); + const v0u = @as(Tu, @bitCast(v0)); + const v1u = @as(Tu, @bitCast(v1)); + return @as(T, @bitCast(v0u | v1u)); // orps +} +test "zmath.orInt" { + { + const v0 = f32x4(0, @as(f32, @bitCast(~@as(u32, 0))), 0, 0); + const v1 = f32x4(1.0, 2.0, 3.0, 4.0); + const v = orInt(v0, v1); + try expect(v[0] == 1.0); + try expect(@as(u32, @bitCast(v[1])) == ~@as(u32, 0)); + try expect(v[2] == 3.0); + try expect(v[3] == 4.0); + } + { + const v0 = f32x8(0, 0, 0, 0, 0, @as(f32, @bitCast(~@as(u32, 0))), 0, 0); + const v1 = f32x8(0, 0, 0, 0, 1.0, 2.0, 3.0, 4.0); + const v = orInt(v0, v1); + try expect(v[4] == 1.0); + try expect(@as(u32, @bitCast(v[5])) == ~@as(u32, 0)); + try expect(v[6] == 3.0); + try expect(v[7] == 4.0); + } +} + +pub inline fn norInt(v0: anytype, v1: anytype) @TypeOf(v0, v1) { + const T = @TypeOf(v0, v1); + const Tu = @Vector(veclen(T), u32); + const v0u = @as(Tu, @bitCast(v0)); + const v1u = @as(Tu, @bitCast(v1)); + return @as(T, @bitCast(~(v0u | v1u))); // por, pcmpeqd, pxor +} + +pub inline fn xorInt(v0: anytype, v1: anytype) @TypeOf(v0, v1) { + const T = @TypeOf(v0, v1); + const Tu = @Vector(veclen(T), u32); + const v0u = @as(Tu, @bitCast(v0)); + const v1u = @as(Tu, @bitCast(v1)); + return @as(T, @bitCast(v0u ^ v1u)); // xorps +} +test "zmath.xorInt" { + { + const v0 = f32x4(1.0, @as(f32, @bitCast(~@as(u32, 0))), 0, 0); + const v1 = f32x4(1.0, 0, 0, 0); + const v = xorInt(v0, v1); + try expect(v[0] == 0.0); + try expect(@as(u32, @bitCast(v[1])) == ~@as(u32, 0)); + try expect(v[2] == 0.0); + try expect(v[3] == 0.0); + } + { + const v0 = f32x8(0, 0, 0, 0, 1.0, @as(f32, @bitCast(~@as(u32, 0))), 0, 0); + const v1 = f32x8(0, 0, 0, 0, 1.0, 0, 0, 0); + const v = xorInt(v0, v1); + try expect(v[4] == 0.0); + try expect(@as(u32, @bitCast(v[5])) == ~@as(u32, 0)); + try expect(v[6] == 0.0); + try expect(v[7] == 0.0); + } +} + +pub inline fn minFast(v0: anytype, v1: anytype) @TypeOf(v0, v1) { + return select(v0 < v1, v0, v1); // minps +} +test "zmath.minFast" { + { + const v0 = f32x4(1.0, 3.0, 2.0, 7.0); + const v1 = f32x4(2.0, 1.0, 4.0, math.inf(f32)); + const v = minFast(v0, v1); + try expect(approxEqAbs(v, f32x4(1.0, 1.0, 2.0, 7.0), 0.0)); + } + { + const v0 = f32x4(1.0, math.nan(f32), 5.0, math.nan(f32)); + const v1 = f32x4(2.0, 1.0, 4.0, math.inf(f32)); + const v = minFast(v0, v1); + try expect(v[0] == 1.0); + try expect(v[1] == 1.0); + try expect(!math.isNan(v[1])); + try expect(v[2] == 4.0); + try expect(v[3] == math.inf(f32)); + try expect(!math.isNan(v[3])); + } +} + +pub inline fn maxFast(v0: anytype, v1: anytype) @TypeOf(v0, v1) { + return select(v0 > v1, v0, v1); // maxps +} +test "zmath.maxFast" { + { + const v0 = f32x4(1.0, 3.0, 2.0, 7.0); + const v1 = f32x4(2.0, 1.0, 4.0, math.inf(f32)); + const v = maxFast(v0, v1); + try expect(approxEqAbs(v, f32x4(2.0, 3.0, 4.0, math.inf(f32)), 0.0)); + } + { + const v0 = f32x4(1.0, math.nan(f32), 5.0, math.nan(f32)); + const v1 = f32x4(2.0, 1.0, 4.0, math.inf(f32)); + const v = maxFast(v0, v1); + try expect(v[0] == 2.0); + try expect(v[1] == 1.0); + try expect(v[2] == 5.0); + try expect(v[3] == math.inf(f32)); + try expect(!math.isNan(v[3])); + } +} + +pub inline fn min(v0: anytype, v1: anytype) @TypeOf(v0, v1) { + // This will handle inf & nan + return @min(v0, v1); // minps, cmpunordps, andps, andnps, orps +} +test "zmath.min" { + { + const v0 = f32x4(1.0, 3.0, 2.0, 7.0); + const v1 = f32x4(2.0, 1.0, 4.0, math.inf(f32)); + const v = min(v0, v1); + try expect(approxEqAbs(v, f32x4(1.0, 1.0, 2.0, 7.0), 0.0)); + } + { + const v0 = f32x8(0, 0, -2.0, 0, 1.0, 3.0, 2.0, 7.0); + const v1 = f32x8(0, 1.0, 0, 0, 2.0, 1.0, 4.0, math.inf(f32)); + const v = min(v0, v1); + try expect(approxEqAbs(v, f32x8(0.0, 0.0, -2.0, 0.0, 1.0, 1.0, 2.0, 7.0), 0.0)); + } + { + const v0 = f32x4(1.0, math.nan(f32), 5.0, math.nan(f32)); + const v1 = f32x4(2.0, 1.0, 4.0, math.inf(f32)); + const v = min(v0, v1); + try expect(v[0] == 1.0); + try expect(v[1] == 1.0); + try expect(!math.isNan(v[1])); + try expect(v[2] == 4.0); + try expect(v[3] == math.inf(f32)); + try expect(!math.isNan(v[3])); + } + { + const v0 = f32x4(-math.inf(f32), math.inf(f32), math.inf(f32), math.nan(f32)); + const v1 = f32x4(math.nan(f32), -math.inf(f32), math.nan(f32), math.nan(f32)); + const v = min(v0, v1); + try expect(v[0] == -math.inf(f32)); + try expect(v[1] == -math.inf(f32)); + try expect(v[2] == math.inf(f32)); + try expect(!math.isNan(v[2])); + try expect(math.isNan(v[3])); + try expect(!math.isInf(v[3])); + } +} + +pub inline fn max(v0: anytype, v1: anytype) @TypeOf(v0, v1) { + // This will handle inf & nan + return @max(v0, v1); // maxps, cmpunordps, andps, andnps, orps +} +test "zmath.max" { + { + const v0 = f32x4(1.0, 3.0, 2.0, 7.0); + const v1 = f32x4(2.0, 1.0, 4.0, math.inf(f32)); + const v = max(v0, v1); + try expect(approxEqAbs(v, f32x4(2.0, 3.0, 4.0, math.inf(f32)), 0.0)); + } + { + const v0 = f32x8(0, 0, -2.0, 0, 1.0, 3.0, 2.0, 7.0); + const v1 = f32x8(0, 1.0, 0, 0, 2.0, 1.0, 4.0, math.inf(f32)); + const v = max(v0, v1); + try expect(approxEqAbs(v, f32x8(0.0, 1.0, 0.0, 0.0, 2.0, 3.0, 4.0, math.inf(f32)), 0.0)); + } + { + const v0 = f32x4(1.0, math.nan(f32), 5.0, math.nan(f32)); + const v1 = f32x4(2.0, 1.0, 4.0, math.inf(f32)); + const v = max(v0, v1); + try expect(v[0] == 2.0); + try expect(v[1] == 1.0); + try expect(v[2] == 5.0); + try expect(v[3] == math.inf(f32)); + try expect(!math.isNan(v[3])); + } + { + const v0 = f32x4(-math.inf(f32), math.inf(f32), math.inf(f32), math.nan(f32)); + const v1 = f32x4(math.nan(f32), -math.inf(f32), math.nan(f32), math.nan(f32)); + const v = max(v0, v1); + try expect(v[0] == -math.inf(f32)); + try expect(v[1] == math.inf(f32)); + try expect(v[2] == math.inf(f32)); + try expect(!math.isNan(v[2])); + try expect(math.isNan(v[3])); + try expect(!math.isInf(v[3])); + } +} + +pub fn round(v: anytype) @TypeOf(v) { + const T = @TypeOf(v); + const sign = andInt(v, splatNegativeZero(T)); + const magic = orInt(splatNoFraction(T), sign); + var r1 = v + magic; + r1 = r1 - magic; + const r2 = abs(v); + const mask = r2 <= splatNoFraction(T); + return select(mask, r1, v); +} +test "zmath.round" { + { + try expect(all(round(splat(F32x4, math.inf(f32))) == splat(F32x4, math.inf(f32)), 0)); + try expect(all(round(splat(F32x4, -math.inf(f32))) == splat(F32x4, -math.inf(f32)), 0)); + try expect(all(isNan(round(splat(F32x4, math.nan(f32)))), 0)); + try expect(all(isNan(round(splat(F32x4, -math.nan(f32)))), 0)); + try expect(all(isNan(round(splat(F32x4, math.nan(f32)))), 0)); + try expect(all(isNan(round(splat(F32x4, -math.nan(f32)))), 0)); + } + { + const v = round(f32x16(1.1, -1.1, -1.5, 1.5, 2.1, 2.8, 2.9, 4.1, 5.8, 6.1, 7.9, 8.9, 10.1, 11.2, 12.7, 13.1)); + try expect(approxEqAbs( + v, + f32x16(1.0, -1.0, -2.0, 2.0, 2.0, 3.0, 3.0, 4.0, 6.0, 6.0, 8.0, 9.0, 10.0, 11.0, 13.0, 13.0), + 0.0, + )); + } + var v = round(f32x4(1.1, -1.1, -1.5, 1.5)); + try expect(approxEqAbs(v, f32x4(1.0, -1.0, -2.0, 2.0), 0.0)); + + const v1 = f32x4(-10_000_000.1, -math.inf(f32), 10_000_001.5, math.inf(f32)); + v = round(v1); + try expect(v[3] == math.inf(f32)); + try expect(approxEqAbs(v, f32x4(-10_000_000.1, -math.inf(f32), 10_000_001.5, math.inf(f32)), 0.0)); + + const v2 = f32x4(-math.nan(f32), math.nan(f32), math.nan(f32), -math.inf(f32)); + v = round(v2); + try expect(math.isNan(v2[0])); + try expect(math.isNan(v2[1])); + try expect(math.isNan(v2[2])); + try expect(v2[3] == -math.inf(f32)); + + const v3 = f32x4(1001.5, -201.499, -10000.99, -101.5); + v = round(v3); + try expect(approxEqAbs(v, f32x4(1002.0, -201.0, -10001.0, -102.0), 0.0)); + + const v4 = f32x4(-1_388_609.9, 1_388_609.5, 1_388_109.01, 2_388_609.5); + v = round(v4); + try expect(approxEqAbs(v, f32x4(-1_388_610.0, 1_388_610.0, 1_388_109.0, 2_388_610.0), 0.0)); + + var f: f32 = -100.0; + var i: u32 = 0; + while (i < 100) : (i += 1) { + const vr = round(splat(F32x4, f)); + const fr = @round(splat(F32x4, f)); + const vr8 = round(splat(F32x8, f)); + const fr8 = @round(splat(F32x8, f)); + const vr16 = round(splat(F32x16, f)); + const fr16 = @round(splat(F32x16, f)); + try expect(approxEqAbs(vr, fr, 0.0)); + try expect(approxEqAbs(vr8, fr8, 0.0)); + try expect(approxEqAbs(vr16, fr16, 0.0)); + f += 0.12345 * @as(f32, @floatFromInt(i)); + } +} + +pub fn trunc(v: anytype) @TypeOf(v) { + return @trunc(v); +} +test "zmath.trunc" { + { + try expect(all(trunc(splat(F32x4, math.inf(f32))) == splat(F32x4, math.inf(f32)), 0)); + try expect(all(trunc(splat(F32x4, -math.inf(f32))) == splat(F32x4, -math.inf(f32)), 0)); + try expect(all(isNan(trunc(splat(F32x4, math.nan(f32)))), 0)); + try expect(all(isNan(trunc(splat(F32x4, -math.nan(f32)))), 0)); + try expect(all(isNan(trunc(splat(F32x4, math.nan(f32)))), 0)); + try expect(all(isNan(trunc(splat(F32x4, -math.nan(f32)))), 0)); + } + { + const v = trunc(f32x16(1.1, -1.1, -1.5, 1.5, 2.1, 2.8, 2.9, 4.1, 5.8, 6.1, 7.9, 8.9, 10.1, 11.2, 12.7, 13.1)); + try expect(approxEqAbs( + v, + f32x16(1.0, -1.0, -1.0, 1.0, 2.0, 2.0, 2.0, 4.0, 5.0, 6.0, 7.0, 8.0, 10.0, 11.0, 12.0, 13.0), + 0.0, + )); + } + var v = trunc(f32x4(1.1, -1.1, -1.5, 1.5)); + try expect(approxEqAbs(v, f32x4(1.0, -1.0, -1.0, 1.0), 0.0)); + + v = trunc(f32x4(-10_000_002.1, -math.inf(f32), 10_000_001.5, math.inf(f32))); + try expect(approxEqAbs(v, f32x4(-10_000_002.1, -math.inf(f32), 10_000_001.5, math.inf(f32)), 0.0)); + + v = trunc(f32x4(-math.nan(f32), math.nan(f32), math.nan(f32), -math.inf(f32))); + try expect(math.isNan(v[0])); + try expect(math.isNan(v[1])); + try expect(math.isNan(v[2])); + try expect(v[3] == -math.inf(f32)); + + v = trunc(f32x4(1000.5001, -201.499, -10000.99, 100.750001)); + try expect(approxEqAbs(v, f32x4(1000.0, -201.0, -10000.0, 100.0), 0.0)); + + v = trunc(f32x4(-7_388_609.5, 7_388_609.1, 8_388_109.5, -8_388_509.5)); + try expect(approxEqAbs(v, f32x4(-7_388_609.0, 7_388_609.0, 8_388_109.0, -8_388_509.0), 0.0)); + + var f: f32 = -100.0; + var i: u32 = 0; + while (i < 100) : (i += 1) { + const vr = trunc(splat(F32x4, f)); + const fr = @trunc(splat(F32x4, f)); + const vr8 = trunc(splat(F32x8, f)); + const fr8 = @trunc(splat(F32x8, f)); + const vr16 = trunc(splat(F32x16, f)); + const fr16 = @trunc(splat(F32x16, f)); + try expect(approxEqAbs(vr, fr, 0.0)); + try expect(approxEqAbs(vr8, fr8, 0.0)); + try expect(approxEqAbs(vr16, fr16, 0.0)); + f += 0.12345 * @as(f32, @floatFromInt(i)); + } +} + +pub fn floor(v: anytype) @TypeOf(v) { + return @floor(v); +} +test "zmath.floor" { + { + try expect(all(floor(splat(F32x4, math.inf(f32))) == splat(F32x4, math.inf(f32)), 0)); + try expect(all(floor(splat(F32x4, -math.inf(f32))) == splat(F32x4, -math.inf(f32)), 0)); + try expect(all(isNan(floor(splat(F32x4, math.nan(f32)))), 0)); + try expect(all(isNan(floor(splat(F32x4, -math.nan(f32)))), 0)); + try expect(all(isNan(floor(splat(F32x4, math.nan(f32)))), 0)); + try expect(all(isNan(floor(splat(F32x4, -math.nan(f32)))), 0)); + } + { + const v = floor(f32x16(1.1, -1.1, -1.5, 1.5, 2.1, 2.8, 2.9, 4.1, 5.8, 6.1, 7.9, 8.9, 10.1, 11.2, 12.7, 13.1)); + try expect(approxEqAbs( + v, + f32x16(1.0, -2.0, -2.0, 1.0, 2.0, 2.0, 2.0, 4.0, 5.0, 6.0, 7.0, 8.0, 10.0, 11.0, 12.0, 13.0), + 0.0, + )); + } + var v = floor(f32x4(1.5, -1.5, -1.7, -2.1)); + try expect(approxEqAbs(v, f32x4(1.0, -2.0, -2.0, -3.0), 0.0)); + + v = floor(f32x4(-10_000_002.1, -math.inf(f32), 10_000_001.5, math.inf(f32))); + try expect(approxEqAbs(v, f32x4(-10_000_002.1, -math.inf(f32), 10_000_001.5, math.inf(f32)), 0.0)); + + v = floor(f32x4(-math.nan(f32), math.nan(f32), math.nan(f32), -math.inf(f32))); + try expect(math.isNan(v[0])); + try expect(math.isNan(v[1])); + try expect(math.isNan(v[2])); + try expect(v[3] == -math.inf(f32)); + + v = floor(f32x4(1000.5001, -201.499, -10000.99, 100.75001)); + try expect(approxEqAbs(v, f32x4(1000.0, -202.0, -10001.0, 100.0), 0.0)); + + v = floor(f32x4(-7_388_609.5, 7_388_609.1, 8_388_109.5, -8_388_509.5)); + try expect(approxEqAbs(v, f32x4(-7_388_610.0, 7_388_609.0, 8_388_109.0, -8_388_510.0), 0.0)); + + var f: f32 = -100.0; + var i: u32 = 0; + while (i < 100) : (i += 1) { + const vr = floor(splat(F32x4, f)); + const fr = @floor(splat(F32x4, f)); + const vr8 = floor(splat(F32x8, f)); + const fr8 = @floor(splat(F32x8, f)); + const vr16 = floor(splat(F32x16, f)); + const fr16 = @floor(splat(F32x16, f)); + try expect(approxEqAbs(vr, fr, 0.0)); + try expect(approxEqAbs(vr8, fr8, 0.0)); + try expect(approxEqAbs(vr16, fr16, 0.0)); + f += 0.12345 * @as(f32, @floatFromInt(i)); + } +} + +pub fn ceil(v: anytype) @TypeOf(v) { + return @ceil(v); +} +test "zmath.ceil" { + { + try expect(all(ceil(splat(F32x4, math.inf(f32))) == splat(F32x4, math.inf(f32)), 0)); + try expect(all(ceil(splat(F32x4, -math.inf(f32))) == splat(F32x4, -math.inf(f32)), 0)); + try expect(all(isNan(ceil(splat(F32x4, math.nan(f32)))), 0)); + try expect(all(isNan(ceil(splat(F32x4, -math.nan(f32)))), 0)); + try expect(all(isNan(ceil(splat(F32x4, math.nan(f32)))), 0)); + try expect(all(isNan(ceil(splat(F32x4, -math.nan(f32)))), 0)); + } + { + const v = ceil(f32x16(1.1, -1.1, -1.5, 1.5, 2.1, 2.8, 2.9, 4.1, 5.8, 6.1, 7.9, 8.9, 10.1, 11.2, 12.7, 13.1)); + try expect(approxEqAbs( + v, + f32x16(2.0, -1.0, -1.0, 2.0, 3.0, 3.0, 3.0, 5.0, 6.0, 7.0, 8.0, 9.0, 11.0, 12.0, 13.0, 14.0), + 0.0, + )); + } + var v = ceil(f32x4(1.5, -1.5, -1.7, -2.1)); + try expect(approxEqAbs(v, f32x4(2.0, -1.0, -1.0, -2.0), 0.0)); + + v = ceil(f32x4(-10_000_002.1, -math.inf(f32), 10_000_001.5, math.inf(f32))); + try expect(approxEqAbs(v, f32x4(-10_000_002.1, -math.inf(f32), 10_000_001.5, math.inf(f32)), 0.0)); + + v = ceil(f32x4(-math.nan(f32), math.nan(f32), math.nan(f32), -math.inf(f32))); + try expect(math.isNan(v[0])); + try expect(math.isNan(v[1])); + try expect(math.isNan(v[2])); + try expect(v[3] == -math.inf(f32)); + + v = ceil(f32x4(1000.5001, -201.499, -10000.99, 100.75001)); + try expect(approxEqAbs(v, f32x4(1001.0, -201.0, -10000.0, 101.0), 0.0)); + + v = ceil(f32x4(-1_388_609.5, 1_388_609.1, 1_388_109.9, -1_388_509.9)); + try expect(approxEqAbs(v, f32x4(-1_388_609.0, 1_388_610.0, 1_388_110.0, -1_388_509.0), 0.0)); + + var f: f32 = -100.0; + var i: u32 = 0; + while (i < 100) : (i += 1) { + const vr = ceil(splat(F32x4, f)); + const fr = @ceil(splat(F32x4, f)); + const vr8 = ceil(splat(F32x8, f)); + const fr8 = @ceil(splat(F32x8, f)); + const vr16 = ceil(splat(F32x16, f)); + const fr16 = @ceil(splat(F32x16, f)); + try expect(approxEqAbs(vr, fr, 0.0)); + try expect(approxEqAbs(vr8, fr8, 0.0)); + try expect(approxEqAbs(vr16, fr16, 0.0)); + f += 0.12345 * @as(f32, @floatFromInt(i)); + } +} + +pub inline fn clamp(v: anytype, vmin: anytype, vmax: anytype) @TypeOf(v, vmin, vmax) { + var result = max(vmin, v); + result = min(vmax, result); + return result; +} +test "zmath.clamp" { + { + const v0 = f32x4(-1.0, 0.2, 1.1, -0.3); + const v = clamp(v0, splat(F32x4, -0.5), splat(F32x4, 0.5)); + try expect(approxEqAbs(v, f32x4(-0.5, 0.2, 0.5, -0.3), 0.0001)); + } + { + const v0 = f32x8(-2.0, 0.25, -0.25, 100.0, -1.0, 0.2, 1.1, -0.3); + const v = clamp(v0, splat(F32x8, -0.5), splat(F32x8, 0.5)); + try expect(approxEqAbs(v, f32x8(-0.5, 0.25, -0.25, 0.5, -0.5, 0.2, 0.5, -0.3), 0.0001)); + } + { + const v0 = f32x4(-math.inf(f32), math.inf(f32), math.nan(f32), math.nan(f32)); + const v = clamp(v0, f32x4(-100.0, 0.0, -100.0, 0.0), f32x4(0.0, 100.0, 0.0, 100.0)); + try expect(approxEqAbs(v, f32x4(-100.0, 100.0, -100.0, 0.0), 0.0001)); + } + { + const v0 = f32x4(math.inf(f32), math.inf(f32), -math.nan(f32), -math.nan(f32)); + const v = clamp(v0, splat(F32x4, -1.0), splat(F32x4, 1.0)); + try expect(approxEqAbs(v, f32x4(1.0, 1.0, -1.0, -1.0), 0.0001)); + } +} + +pub inline fn clampFast(v: anytype, vmin: anytype, vmax: anytype) @TypeOf(v, vmin, vmax) { + var result = maxFast(vmin, v); + result = minFast(vmax, result); + return result; +} +test "zmath.clampFast" { + { + const v0 = f32x4(-1.0, 0.2, 1.1, -0.3); + const v = clampFast(v0, splat(F32x4, -0.5), splat(F32x4, 0.5)); + try expect(approxEqAbs(v, f32x4(-0.5, 0.2, 0.5, -0.3), 0.0001)); + } +} + +pub inline fn saturate(v: anytype) @TypeOf(v) { + const T = @TypeOf(v); + var result = max(v, splat(T, 0.0)); + result = min(result, splat(T, 1.0)); + return result; +} +test "zmath.saturate" { + { + const v0 = f32x4(-1.0, 0.2, 1.1, -0.3); + const v = saturate(v0); + try expect(approxEqAbs(v, f32x4(0.0, 0.2, 1.0, 0.0), 0.0001)); + } + { + const v0 = f32x8(0.0, 0.0, 2.0, -2.0, -1.0, 0.2, 1.1, -0.3); + const v = saturate(v0); + try expect(approxEqAbs(v, f32x8(0.0, 0.0, 1.0, 0.0, 0.0, 0.2, 1.0, 0.0), 0.0001)); + } + { + const v0 = f32x4(-math.inf(f32), math.inf(f32), math.nan(f32), math.nan(f32)); + const v = saturate(v0); + try expect(approxEqAbs(v, f32x4(0.0, 1.0, 0.0, 0.0), 0.0001)); + } + { + const v0 = f32x4(math.inf(f32), math.inf(f32), -math.nan(f32), -math.nan(f32)); + const v = saturate(v0); + try expect(approxEqAbs(v, f32x4(1.0, 1.0, 0.0, 0.0), 0.0001)); + } +} + +pub inline fn saturateFast(v: anytype) @TypeOf(v) { + const T = @TypeOf(v); + var result = maxFast(v, splat(T, 0.0)); + result = minFast(result, splat(T, 1.0)); + return result; +} +test "zmath.saturateFast" { + { + const v0 = f32x4(-1.0, 0.2, 1.1, -0.3); + const v = saturateFast(v0); + try expect(approxEqAbs(v, f32x4(0.0, 0.2, 1.0, 0.0), 0.0001)); + } + { + const v0 = f32x8(0.0, 0.0, 2.0, -2.0, -1.0, 0.2, 1.1, -0.3); + const v = saturateFast(v0); + try expect(approxEqAbs(v, f32x8(0.0, 0.0, 1.0, 0.0, 0.0, 0.2, 1.0, 0.0), 0.0001)); + } + { + const v0 = f32x4(-math.inf(f32), math.inf(f32), math.nan(f32), math.nan(f32)); + const v = saturateFast(v0); + try expect(approxEqAbs(v, f32x4(0.0, 1.0, 0.0, 0.0), 0.0001)); + } + { + const v0 = f32x4(math.inf(f32), math.inf(f32), -math.nan(f32), -math.nan(f32)); + const v = saturateFast(v0); + try expect(approxEqAbs(v, f32x4(1.0, 1.0, 0.0, 0.0), 0.0001)); + } +} + +pub inline fn sqrt(v: anytype) @TypeOf(v) { + return @sqrt(v); // sqrtps +} + +pub inline fn abs(v: anytype) @TypeOf(v) { + return @abs(v); // load, andps +} + +pub inline fn select(mask: anytype, v0: anytype, v1: anytype) @TypeOf(v0, v1) { + return @select(f32, mask, v0, v1); +} + +pub inline fn lerp(v0: anytype, v1: anytype, t: f32) @TypeOf(v0, v1) { + const T = @TypeOf(v0, v1); + return v0 + (v1 - v0) * splat(T, t); // subps, shufps, addps, mulps +} + +pub inline fn lerpV(v0: anytype, v1: anytype, t: anytype) @TypeOf(v0, v1, t) { + return v0 + (v1 - v0) * t; // subps, addps, mulps +} + +pub const F32x4Component = enum { x, y, z, w }; + +pub inline fn swizzle( + v: F32x4, + comptime x: F32x4Component, + comptime y: F32x4Component, + comptime z: F32x4Component, + comptime w: F32x4Component, +) F32x4 { + return @shuffle(f32, v, undefined, [4]i32{ @intFromEnum(x), @intFromEnum(y), @intFromEnum(z), @intFromEnum(w) }); +} + +pub inline fn mod(v0: anytype, v1: anytype) @TypeOf(v0, v1) { + // vdivps, vroundps, vmulps, vsubps + return v0 - v1 * trunc(v0 / v1); +} +test "zmath.mod" { + if (builtin.target.os.tag == .macos and builtin.zig_backend != .stage1) return error.SkipZigTest; + try expect(approxEqAbs(mod(splat(F32x4, 3.1), splat(F32x4, 1.7)), splat(F32x4, 1.4), 0.0005)); + try expect(approxEqAbs(mod(splat(F32x4, -3.0), splat(F32x4, 2.0)), splat(F32x4, -1.0), 0.0005)); + try expect(approxEqAbs(mod(splat(F32x4, -3.0), splat(F32x4, -2.0)), splat(F32x4, -1.0), 0.0005)); + try expect(approxEqAbs(mod(splat(F32x4, 3.0), splat(F32x4, -2.0)), splat(F32x4, 1.0), 0.0005)); + try expect(all(isNan(mod(splat(F32x4, math.inf(f32)), splat(F32x4, 1.0))), 0)); + try expect(all(isNan(mod(splat(F32x4, -math.inf(f32)), splat(F32x4, 123.456))), 0)); + try expect(all(isNan(mod(splat(F32x4, math.nan(f32)), splat(F32x4, 123.456))), 0)); + try expect(all(isNan(mod(splat(F32x4, math.nan(f32)), splat(F32x4, 123.456))), 0)); + try expect(all(isNan(mod(splat(F32x4, -math.nan(f32)), splat(F32x4, 123.456))), 0)); + try expect(all(isNan(mod(splat(F32x4, 123.456), splat(F32x4, math.inf(f32)))), 0)); + try expect(all(isNan(mod(splat(F32x4, 123.456), splat(F32x4, -math.inf(f32)))), 0)); + try expect(all(isNan(mod(splat(F32x4, math.inf(f32)), splat(F32x4, math.inf(f32)))), 0)); + try expect(all(isNan(mod(splat(F32x4, 123.456), splat(F32x4, math.nan(f32)))), 0)); + try expect(all(isNan(mod(splat(F32x4, math.inf(f32)), splat(F32x4, math.nan(f32)))), 0)); +} + +pub fn modAngle(v: anytype) @TypeOf(v) { + const T = @TypeOf(v); + return switch (T) { + f32 => modAngle32(v), + F32x4, F32x8, F32x16 => modAngle32xN(v), + else => @compileError("zmath.modAngle() not implemented for " ++ @typeName(T)), + }; +} + +pub inline fn modAngle32xN(v: anytype) @TypeOf(v) { + const T = @TypeOf(v); + return v - splat(T, math.tau) * round(v * splat(T, 1.0 / math.tau)); // 2 x vmulps, 2 x load, vroundps, vaddps +} +test "zmath.modAngle" { + try expect(approxEqAbs(modAngle(splat(F32x4, math.tau)), splat(F32x4, 0.0), 0.0005)); + try expect(approxEqAbs(modAngle(splat(F32x4, 0.0)), splat(F32x4, 0.0), 0.0005)); + try expect(approxEqAbs(modAngle(splat(F32x4, math.pi)), splat(F32x4, math.pi), 0.0005)); + try expect(approxEqAbs(modAngle(splat(F32x4, 11 * math.pi)), splat(F32x4, math.pi), 0.0005)); + try expect(approxEqAbs(modAngle(splat(F32x4, 3.5 * math.pi)), splat(F32x4, -0.5 * math.pi), 0.0005)); + try expect(approxEqAbs(modAngle(splat(F32x4, 2.5 * math.pi)), splat(F32x4, 0.5 * math.pi), 0.0005)); +} + +pub inline fn mulAdd(v0: anytype, v1: anytype, v2: anytype) @TypeOf(v0, v1, v2) { + const T = @TypeOf(v0, v1, v2); + if (cpu_arch == .x86_64 and has_avx and has_fma) { + return @mulAdd(T, v0, v1, v2); + } else { + // NOTE(mziulek): On .x86_64 without HW fma instructions @mulAdd maps to really slow code! + return v0 * v1 + v2; + } +} + +fn sin32xN(v: anytype) @TypeOf(v) { + // 11-degree minimax approximation + const T = @TypeOf(v); + + var x = modAngle(v); + const sign = andInt(x, splatNegativeZero(T)); + const c = orInt(sign, splat(T, math.pi)); + const absx = andNotInt(sign, x); + const rflx = c - x; + const comp = absx <= splat(T, 0.5 * math.pi); + x = select(comp, x, rflx); + const x2 = x * x; + + var result = mulAdd(splat(T, -2.3889859e-08), x2, splat(T, 2.7525562e-06)); + result = mulAdd(result, x2, splat(T, -0.00019840874)); + result = mulAdd(result, x2, splat(T, 0.0083333310)); + result = mulAdd(result, x2, splat(T, -0.16666667)); + result = mulAdd(result, x2, splat(T, 1.0)); + return x * result; +} +test "zmath.sin" { + const epsilon = 0.0001; + + try expect(approxEqAbs(sin(splat(F32x4, 0.5 * math.pi)), splat(F32x4, 1.0), epsilon)); + try expect(approxEqAbs(sin(splat(F32x4, 0.0)), splat(F32x4, 0.0), epsilon)); + try expect(approxEqAbs(sin(splat(F32x4, -0.0)), splat(F32x4, -0.0), epsilon)); + try expect(approxEqAbs(sin(splat(F32x4, 89.123)), splat(F32x4, 0.916166), epsilon)); + try expect(approxEqAbs(sin(splat(F32x8, 89.123)), splat(F32x8, 0.916166), epsilon)); + try expect(approxEqAbs(sin(splat(F32x16, 89.123)), splat(F32x16, 0.916166), epsilon)); + try expect(all(isNan(sin(splat(F32x4, math.inf(f32)))), 0) == true); + try expect(all(isNan(sin(splat(F32x4, -math.inf(f32)))), 0) == true); + try expect(all(isNan(sin(splat(F32x4, math.nan(f32)))), 0) == true); + try expect(all(isNan(sin(splat(F32x4, math.nan(f32)))), 0) == true); + + var f: f32 = -100.0; + var i: u32 = 0; + while (i < 100) : (i += 1) { + const vr = sin(splat(F32x4, f)); + const fr = @sin(splat(F32x4, f)); + const vr8 = sin(splat(F32x8, f)); + const fr8 = @sin(splat(F32x8, f)); + const vr16 = sin(splat(F32x16, f)); + const fr16 = @sin(splat(F32x16, f)); + try expect(approxEqAbs(vr, fr, epsilon)); + try expect(approxEqAbs(vr8, fr8, epsilon)); + try expect(approxEqAbs(vr16, fr16, epsilon)); + f += 0.12345 * @as(f32, @floatFromInt(i)); + } +} + +fn cos32xN(v: anytype) @TypeOf(v) { + // 10-degree minimax approximation + const T = @TypeOf(v); + + var x = modAngle(v); + var sign = andInt(x, splatNegativeZero(T)); + const c = orInt(sign, splat(T, math.pi)); + const absx = andNotInt(sign, x); + const rflx = c - x; + const comp = absx <= splat(T, 0.5 * math.pi); + x = select(comp, x, rflx); + sign = select(comp, splat(T, 1.0), splat(T, -1.0)); + const x2 = x * x; + + var result = mulAdd(splat(T, -2.6051615e-07), x2, splat(T, 2.4760495e-05)); + result = mulAdd(result, x2, splat(T, -0.0013888378)); + result = mulAdd(result, x2, splat(T, 0.041666638)); + result = mulAdd(result, x2, splat(T, -0.5)); + result = mulAdd(result, x2, splat(T, 1.0)); + return sign * result; +} +test "zmath.cos" { + const epsilon = 0.0001; + + try expect(approxEqAbs(cos(splat(F32x4, 0.5 * math.pi)), splat(F32x4, 0.0), epsilon)); + try expect(approxEqAbs(cos(splat(F32x4, 0.0)), splat(F32x4, 1.0), epsilon)); + try expect(approxEqAbs(cos(splat(F32x4, -0.0)), splat(F32x4, 1.0), epsilon)); + try expect(all(isNan(cos(splat(F32x4, math.inf(f32)))), 0) == true); + try expect(all(isNan(cos(splat(F32x4, -math.inf(f32)))), 0) == true); + try expect(all(isNan(cos(splat(F32x4, math.nan(f32)))), 0) == true); + try expect(all(isNan(cos(splat(F32x4, math.nan(f32)))), 0) == true); + + var f: f32 = -100.0; + var i: u32 = 0; + while (i < 100) : (i += 1) { + const vr = cos(splat(F32x4, f)); + const fr = @cos(splat(F32x4, f)); + const vr8 = cos(splat(F32x8, f)); + const fr8 = @cos(splat(F32x8, f)); + const vr16 = cos(splat(F32x16, f)); + const fr16 = @cos(splat(F32x16, f)); + try expect(approxEqAbs(vr, fr, epsilon)); + try expect(approxEqAbs(vr8, fr8, epsilon)); + try expect(approxEqAbs(vr16, fr16, epsilon)); + f += 0.12345 * @as(f32, @floatFromInt(i)); + } +} + +pub fn sin(v: anytype) @TypeOf(v) { + const T = @TypeOf(v); + return switch (T) { + f32 => sin32(v), + F32x4, F32x8, F32x16 => sin32xN(v), + else => @compileError("zmath.sin() not implemented for " ++ @typeName(T)), + }; +} + +pub fn cos(v: anytype) @TypeOf(v) { + const T = @TypeOf(v); + return switch (T) { + f32 => cos32(v), + F32x4, F32x8, F32x16 => cos32xN(v), + else => @compileError("zmath.cos() not implemented for " ++ @typeName(T)), + }; +} + +pub fn sincos(v: anytype) [2]@TypeOf(v) { + const T = @TypeOf(v); + return switch (T) { + f32 => sincos32(v), + F32x4, F32x8, F32x16 => sincos32xN(v), + else => @compileError("zmath.sincos() not implemented for " ++ @typeName(T)), + }; +} + +pub fn asin(v: anytype) @TypeOf(v) { + const T = @TypeOf(v); + return switch (T) { + f32 => asin32(v), + F32x4, F32x8, F32x16 => asin32xN(v), + else => @compileError("zmath.asin() not implemented for " ++ @typeName(T)), + }; +} + +pub fn acos(v: anytype) @TypeOf(v) { + const T = @TypeOf(v); + return switch (T) { + f32 => acos32(v), + F32x4, F32x8, F32x16 => acos32xN(v), + else => @compileError("zmath.acos() not implemented for " ++ @typeName(T)), + }; +} + +fn sincos32xN(v: anytype) [2]@TypeOf(v) { + const T = @TypeOf(v); + + var x = modAngle(v); + var sign = andInt(x, splatNegativeZero(T)); + const c = orInt(sign, splat(T, math.pi)); + const absx = andNotInt(sign, x); + const rflx = c - x; + const comp = absx <= splat(T, 0.5 * math.pi); + x = select(comp, x, rflx); + sign = select(comp, splat(T, 1.0), splat(T, -1.0)); + const x2 = x * x; + + var sresult = mulAdd(splat(T, -2.3889859e-08), x2, splat(T, 2.7525562e-06)); + sresult = mulAdd(sresult, x2, splat(T, -0.00019840874)); + sresult = mulAdd(sresult, x2, splat(T, 0.0083333310)); + sresult = mulAdd(sresult, x2, splat(T, -0.16666667)); + sresult = x * mulAdd(sresult, x2, splat(T, 1.0)); + + var cresult = mulAdd(splat(T, -2.6051615e-07), x2, splat(T, 2.4760495e-05)); + cresult = mulAdd(cresult, x2, splat(T, -0.0013888378)); + cresult = mulAdd(cresult, x2, splat(T, 0.041666638)); + cresult = mulAdd(cresult, x2, splat(T, -0.5)); + cresult = sign * mulAdd(cresult, x2, splat(T, 1.0)); + + return .{ sresult, cresult }; +} +test "zmath.sincos32xN" { + const epsilon = 0.0001; + + var f: f32 = -100.0; + var i: u32 = 0; + while (i < 100) : (i += 1) { + const sc = sincos(splat(F32x4, f)); + const sc8 = sincos(splat(F32x8, f)); + const sc16 = sincos(splat(F32x16, f)); + const s4 = @sin(splat(F32x4, f)); + const s8 = @sin(splat(F32x8, f)); + const s16 = @sin(splat(F32x16, f)); + const c4 = @cos(splat(F32x4, f)); + const c8 = @cos(splat(F32x8, f)); + const c16 = @cos(splat(F32x16, f)); + try expect(approxEqAbs(sc[0], s4, epsilon)); + try expect(approxEqAbs(sc8[0], s8, epsilon)); + try expect(approxEqAbs(sc16[0], s16, epsilon)); + try expect(approxEqAbs(sc[1], c4, epsilon)); + try expect(approxEqAbs(sc8[1], c8, epsilon)); + try expect(approxEqAbs(sc16[1], c16, epsilon)); + f += 0.12345 * @as(f32, @floatFromInt(i)); + } +} + +fn asin32xN(v: anytype) @TypeOf(v) { + // 7-degree minimax approximation + const T = @TypeOf(v); + + const x = abs(v); + const root = sqrt(maxFast(splat(T, 0.0), splat(T, 1.0) - x)); + + var t0 = mulAdd(splat(T, -0.0012624911), x, splat(T, 0.0066700901)); + t0 = mulAdd(t0, x, splat(T, -0.0170881256)); + t0 = mulAdd(t0, x, splat(T, 0.0308918810)); + t0 = mulAdd(t0, x, splat(T, -0.0501743046)); + t0 = mulAdd(t0, x, splat(T, 0.0889789874)); + t0 = mulAdd(t0, x, splat(T, -0.2145988016)); + t0 = root * mulAdd(t0, x, splat(T, 1.5707963050)); + + const t1 = splat(T, math.pi) - t0; + return splat(T, 0.5 * math.pi) - select(v >= splat(T, 0.0), t0, t1); +} + +fn acos32xN(v: anytype) @TypeOf(v) { + // 7-degree minimax approximation + const T = @TypeOf(v); + + const x = abs(v); + const root = sqrt(maxFast(splat(T, 0.0), splat(T, 1.0) - x)); + + var t0 = mulAdd(splat(T, -0.0012624911), x, splat(T, 0.0066700901)); + t0 = mulAdd(t0, x, splat(T, -0.0170881256)); + t0 = mulAdd(t0, x, splat(T, 0.0308918810)); + t0 = mulAdd(t0, x, splat(T, -0.0501743046)); + t0 = mulAdd(t0, x, splat(T, 0.0889789874)); + t0 = mulAdd(t0, x, splat(T, -0.2145988016)); + t0 = root * mulAdd(t0, x, splat(T, 1.5707963050)); + + const t1 = splat(T, math.pi) - t0; + return select(v >= splat(T, 0.0), t0, t1); +} + +pub fn atan(v: anytype) @TypeOf(v) { + // 17-degree minimax approximation + const T = @TypeOf(v); + + const vabs = abs(v); + const vinv = splat(T, 1.0) / v; + var sign = select(v > splat(T, 1.0), splat(T, 1.0), splat(T, -1.0)); + const comp = vabs <= splat(T, 1.0); + sign = select(comp, splat(T, 0.0), sign); + const x = select(comp, v, vinv); + const x2 = x * x; + + var result = mulAdd(splat(T, 0.0028662257), x2, splat(T, -0.0161657367)); + result = mulAdd(result, x2, splat(T, 0.0429096138)); + result = mulAdd(result, x2, splat(T, -0.0752896400)); + result = mulAdd(result, x2, splat(T, 0.1065626393)); + result = mulAdd(result, x2, splat(T, -0.1420889944)); + result = mulAdd(result, x2, splat(T, 0.1999355085)); + result = mulAdd(result, x2, splat(T, -0.3333314528)); + result = x * mulAdd(result, x2, splat(T, 1.0)); + + const result1 = sign * splat(T, 0.5 * math.pi) - result; + return select(sign == splat(T, 0.0), result, result1); +} +test "zmath.atan" { + const epsilon = 0.0001; + { + const v = f32x4(0.25, 0.5, 1.0, 1.25); + const e = f32x4(math.atan(v[0]), math.atan(v[1]), math.atan(v[2]), math.atan(v[3])); + try expect(approxEqAbs(e, atan(v), epsilon)); + } + { + const v = f32x8(-0.25, 0.5, -1.0, 1.25, 100.0, -200.0, 300.0, 400.0); + // zig fmt: off + const e = f32x8( + math.atan(v[0]), math.atan(v[1]), math.atan(v[2]), math.atan(v[3]), + math.atan(v[4]), math.atan(v[5]), math.atan(v[6]), math.atan(v[7]), + ); + // zig fmt: on + try expect(approxEqAbs(e, atan(v), epsilon)); + } + { + // zig fmt: off + const v = f32x16( + -0.25, 0.5, -1.0, 0.0, 0.1, -0.2, 30.0, 400.0, + -0.25, 0.5, -1.0, -0.0, -0.05, -0.125, 0.0625, 4000.0 + ); + const e = f32x16( + math.atan(v[0]), math.atan(v[1]), math.atan(v[2]), math.atan(v[3]), + math.atan(v[4]), math.atan(v[5]), math.atan(v[6]), math.atan(v[7]), + math.atan(v[8]), math.atan(v[9]), math.atan(v[10]), math.atan(v[11]), + math.atan(v[12]), math.atan(v[13]), math.atan(v[14]), math.atan(v[15]), + ); + // zig fmt: on + try expect(approxEqAbs(e, atan(v), epsilon)); + } + { + try expect(approxEqAbs(atan(splat(F32x4, math.inf(f32))), splat(F32x4, 0.5 * math.pi), epsilon)); + try expect(approxEqAbs(atan(splat(F32x4, -math.inf(f32))), splat(F32x4, -0.5 * math.pi), epsilon)); + try expect(all(isNan(atan(splat(F32x4, math.nan(f32)))), 0) == true); + try expect(all(isNan(atan(splat(F32x4, -math.nan(f32)))), 0) == true); + } +} + +pub fn atan2(vy: anytype, vx: anytype) @TypeOf(vx, vy) { + const T = @TypeOf(vx, vy); + const Tu = @Vector(veclen(T), u32); + + const vx_is_positive = + (@as(Tu, @bitCast(vx)) & @as(Tu, @splat(@as(u32, 0x8000_0000)))) == @as(Tu, @splat(@as(u32, 0))); + + const vy_sign = andInt(vy, splatNegativeZero(T)); + const c0_25pi = orInt(vy_sign, splat(T, 0.25 * math.pi)); + const c0_50pi = orInt(vy_sign, splat(T, 0.50 * math.pi)); + const c0_75pi = orInt(vy_sign, splat(T, 0.75 * math.pi)); + const c1_00pi = orInt(vy_sign, splat(T, 1.00 * math.pi)); + + var r1 = select(vx_is_positive, vy_sign, c1_00pi); + var r2 = select(vx == splat(T, 0.0), c0_50pi, splatInt(T, 0xffff_ffff)); + const r3 = select(vy == splat(T, 0.0), r1, r2); + const r4 = select(vx_is_positive, c0_25pi, c0_75pi); + const r5 = select(isInf(vx), r4, c0_50pi); + const result = select(isInf(vy), r5, r3); + const result_valid = @as(Tu, @bitCast(result)) == @as(Tu, @splat(@as(u32, 0xffff_ffff))); + + const v = vy / vx; + const r0 = atan(v); + + r1 = select(vx_is_positive, splatNegativeZero(T), c1_00pi); + r2 = r0 + r1; + + return select(result_valid, r2, result); +} +test "zmath.atan2" { + // From DirectXMath XMVectorATan2(): + // + // Return the inverse tangent of Y / X in the range of -Pi to Pi with the following exceptions: + + // Y == 0 and X is Negative -> Pi with the sign of Y + // y == 0 and x is positive -> 0 with the sign of y + // Y != 0 and X == 0 -> Pi / 2 with the sign of Y + // Y != 0 and X is Negative -> atan(y/x) + (PI with the sign of Y) + // X == -Infinity and Finite Y -> Pi with the sign of Y + // X == +Infinity and Finite Y -> 0 with the sign of Y + // Y == Infinity and X is Finite -> Pi / 2 with the sign of Y + // Y == Infinity and X == -Infinity -> 3Pi / 4 with the sign of Y + // Y == Infinity and X == +Infinity -> Pi / 4 with the sign of Y + + const epsilon = 0.0001; + try expect(approxEqAbs(atan2(splat(F32x4, 0.0), splat(F32x4, -1.0)), splat(F32x4, math.pi), epsilon)); + try expect(approxEqAbs(atan2(splat(F32x4, -0.0), splat(F32x4, -1.0)), splat(F32x4, -math.pi), epsilon)); + try expect(approxEqAbs(atan2(splat(F32x4, 1.0), splat(F32x4, 0.0)), splat(F32x4, 0.5 * math.pi), epsilon)); + try expect(approxEqAbs(atan2(splat(F32x4, -1.0), splat(F32x4, 0.0)), splat(F32x4, -0.5 * math.pi), epsilon)); + try expect(approxEqAbs( + atan2(splat(F32x4, 1.0), splat(F32x4, -1.0)), + splat(F32x4, math.atan(@as(f32, -1.0)) + math.pi), + epsilon, + )); + try expect(approxEqAbs( + atan2(splat(F32x4, -10.0), splat(F32x4, -2.0)), + splat(F32x4, math.atan(@as(f32, 5.0)) - math.pi), + epsilon, + )); + try expect(approxEqAbs(atan2(splat(F32x4, 1.0), splat(F32x4, -math.inf(f32))), splat(F32x4, math.pi), epsilon)); + try expect(approxEqAbs(atan2(splat(F32x4, -1.0), splat(F32x4, -math.inf(f32))), splat(F32x4, -math.pi), epsilon)); + try expect(approxEqAbs(atan2(splat(F32x4, 1.0), splat(F32x4, math.inf(f32))), splat(F32x4, 0.0), epsilon)); + try expect(approxEqAbs(atan2(splat(F32x4, -1.0), splat(F32x4, math.inf(f32))), splat(F32x4, -0.0), epsilon)); + try expect(approxEqAbs( + atan2(splat(F32x4, math.inf(f32)), splat(F32x4, 2.0)), + splat(F32x4, 0.5 * math.pi), + epsilon, + )); + try expect(approxEqAbs( + atan2(splat(F32x4, -math.inf(f32)), splat(F32x4, 2.0)), + splat(F32x4, -0.5 * math.pi), + epsilon, + )); + try expect(approxEqAbs( + atan2(splat(F32x4, math.inf(f32)), splat(F32x4, -math.inf(f32))), + splat(F32x4, 0.75 * math.pi), + epsilon, + )); + try expect(approxEqAbs( + atan2(splat(F32x4, -math.inf(f32)), splat(F32x4, -math.inf(f32))), + splat(F32x4, -0.75 * math.pi), + epsilon, + )); + try expect(approxEqAbs( + atan2(splat(F32x4, math.inf(f32)), splat(F32x4, math.inf(f32))), + splat(F32x4, 0.25 * math.pi), + epsilon, + )); + try expect(approxEqAbs( + atan2(splat(F32x4, -math.inf(f32)), splat(F32x4, math.inf(f32))), + splat(F32x4, -0.25 * math.pi), + epsilon, + )); + try expect(approxEqAbs( + atan2( + f32x8(0.0, -math.inf(f32), -0.0, 2.0, math.inf(f32), math.inf(f32), 1.0, -math.inf(f32)), + f32x8(-2.0, math.inf(f32), 1.0, 0.0, 10.0, -math.inf(f32), 1.0, -math.inf(f32)), + ), + f32x8( + math.pi, + -0.25 * math.pi, + -0.0, + 0.5 * math.pi, + 0.5 * math.pi, + 0.75 * math.pi, + math.atan(@as(f32, 1.0)), + -0.75 * math.pi, + ), + epsilon, + )); + try expect(approxEqAbs(atan2(splat(F32x4, 0.0), splat(F32x4, 0.0)), splat(F32x4, 0.0), epsilon)); + try expect(approxEqAbs(atan2(splat(F32x4, -0.0), splat(F32x4, 0.0)), splat(F32x4, 0.0), epsilon)); + try expect(all(isNan(atan2(splat(F32x4, 1.0), splat(F32x4, math.nan(f32)))), 0) == true); + try expect(all(isNan(atan2(splat(F32x4, -1.0), splat(F32x4, math.nan(f32)))), 0) == true); + try expect(all(isNan(atan2(splat(F32x4, math.nan(f32)), splat(F32x4, -1.0))), 0) == true); + try expect(all(isNan(atan2(splat(F32x4, -math.nan(f32)), splat(F32x4, 1.0))), 0) == true); +} +// ------------------------------------------------------------------------------ +// +// 3. 2D, 3D, 4D vector functions +// +// ------------------------------------------------------------------------------ +pub inline fn dot2(v0: Vec, v1: Vec) F32x4 { + var xmm0 = v0 * v1; // | x0*x1 | y0*y1 | -- | -- | + const xmm1 = swizzle(xmm0, .y, .x, .x, .x); // | y0*y1 | -- | -- | -- | + xmm0 = f32x4(xmm0[0] + xmm1[0], xmm0[1], xmm0[2], xmm0[3]); // | x0*x1 + y0*y1 | -- | -- | -- | + return swizzle(xmm0, .x, .x, .x, .x); +} +test "zmath.dot2" { + const v0 = f32x4(-1.0, 2.0, 300.0, -2.0); + const v1 = f32x4(4.0, 5.0, 600.0, 2.0); + const v = dot2(v0, v1); + try expect(approxEqAbs(v, splat(F32x4, 6.0), 0.0001)); +} + +pub inline fn dot3(v0: Vec, v1: Vec) F32x4 { + const dot = v0 * v1; + return f32x4s(dot[0] + dot[1] + dot[2]); +} +test "zmath.dot3" { + const v0 = f32x4(-1.0, 2.0, 3.0, 1.0); + const v1 = f32x4(4.0, 5.0, 6.0, 1.0); + const v = dot3(v0, v1); + try expect(approxEqAbs(v, splat(F32x4, 24.0), 0.0001)); +} + +pub inline fn dot4(v0: Vec, v1: Vec) F32x4 { + var xmm0 = v0 * v1; // | x0*x1 | y0*y1 | z0*z1 | w0*w1 | + var xmm1 = swizzle(xmm0, .y, .x, .w, .x); // | y0*y1 | -- | w0*w1 | -- | + xmm1 = xmm0 + xmm1; // | x0*x1 + y0*y1 | -- | z0*z1 + w0*w1 | -- | + xmm0 = swizzle(xmm1, .z, .x, .x, .x); // | z0*z1 + w0*w1 | -- | -- | -- | + xmm0 = f32x4(xmm0[0] + xmm1[0], xmm0[1], xmm0[2], xmm0[2]); // addss + return swizzle(xmm0, .x, .x, .x, .x); +} +test "zmath.dot4" { + const v0 = f32x4(-1.0, 2.0, 3.0, -2.0); + const v1 = f32x4(4.0, 5.0, 6.0, 2.0); + const v = dot4(v0, v1); + try expect(approxEqAbs(v, splat(F32x4, 20.0), 0.0001)); +} + +pub inline fn cross3(v0: Vec, v1: Vec) Vec { + var xmm0 = swizzle(v0, .y, .z, .x, .w); + var xmm1 = swizzle(v1, .z, .x, .y, .w); + var result = xmm0 * xmm1; + xmm0 = swizzle(xmm0, .y, .z, .x, .w); + xmm1 = swizzle(xmm1, .z, .x, .y, .w); + result = result - xmm0 * xmm1; + return andInt(result, f32x4_mask3); +} +test "zmath.cross3" { + { + const v0 = f32x4(1.0, 0.0, 0.0, 1.0); + const v1 = f32x4(0.0, 1.0, 0.0, 1.0); + const v = cross3(v0, v1); + try expect(approxEqAbs(v, f32x4(0.0, 0.0, 1.0, 0.0), 0.0001)); + } + { + const v0 = f32x4(1.0, 0.0, 0.0, 1.0); + const v1 = f32x4(0.0, -1.0, 0.0, 1.0); + const v = cross3(v0, v1); + try expect(approxEqAbs(v, f32x4(0.0, 0.0, -1.0, 0.0), 0.0001)); + } + { + const v0 = f32x4(-3.0, 0, -2.0, 1.0); + const v1 = f32x4(5.0, -1.0, 2.0, 1.0); + const v = cross3(v0, v1); + try expect(approxEqAbs(v, f32x4(-2.0, -4.0, 3.0, 0.0), 0.0001)); + } +} + +pub inline fn lengthSq2(v: Vec) F32x4 { + return dot2(v, v); +} +pub inline fn lengthSq3(v: Vec) F32x4 { + return dot3(v, v); +} +pub inline fn lengthSq4(v: Vec) F32x4 { + return dot4(v, v); +} + +pub inline fn length2(v: Vec) F32x4 { + return sqrt(dot2(v, v)); +} +pub inline fn length3(v: Vec) F32x4 { + return sqrt(dot3(v, v)); +} +pub inline fn length4(v: Vec) F32x4 { + return sqrt(dot4(v, v)); +} +test "zmath.length3" { + if (builtin.target.os.tag == .macos and builtin.zig_backend != .stage1) return error.SkipZigTest; + { + const v = length3(f32x4(1.0, -2.0, 3.0, 1000.0)); + try expect(approxEqAbs(v, splat(F32x4, math.sqrt(14.0)), 0.001)); + } + { + const v = length3(f32x4(1.0, math.nan(f32), math.nan(f32), 1000.0)); + try expect(all(isNan(v), 0)); + } + { + const v = length3(f32x4(1.0, math.inf(f32), 3.0, 1000.0)); + try expect(all(isInf(v), 0)); + } + { + const v = length3(f32x4(3.0, 2.0, 1.0, math.nan(f32))); + try expect(approxEqAbs(v, splat(F32x4, math.sqrt(14.0)), 0.001)); + } +} + +pub inline fn normalize2(v: Vec) Vec { + return v * splat(F32x4, 1.0) / sqrt(dot2(v, v)); +} +pub inline fn normalize3(v: Vec) Vec { + return v * splat(F32x4, 1.0) / sqrt(dot3(v, v)); +} +pub inline fn normalize4(v: Vec) Vec { + return v * splat(F32x4, 1.0) / sqrt(dot4(v, v)); +} +test "zmath.normalize3" { + { + const v0 = f32x4(1.0, -2.0, 3.0, 1000.0); + const v = normalize3(v0); + try expect(approxEqAbs(v, v0 * splat(F32x4, 1.0 / math.sqrt(14.0)), 0.0005)); + } + { + try expect(any(isNan(normalize3(f32x4(1.0, math.inf(f32), 1.0, 1.0))), 0)); + try expect(any(isNan(normalize3(f32x4(-math.inf(f32), math.inf(f32), 0.0, 0.0))), 0)); + try expect(any(isNan(normalize3(f32x4(-math.nan(f32), math.nan(f32), 0.0, 0.0))), 0)); + try expect(any(isNan(normalize3(f32x4(0, 0, 0, 0))), 0)); + } +} +test "zmath.normalize4" { + { + const v0 = f32x4(1.0, -2.0, 3.0, 10.0); + const v = normalize4(v0); + try expect(approxEqAbs(v, v0 * splat(F32x4, 1.0 / math.sqrt(114.0)), 0.0005)); + } + { + try expect(any(isNan(normalize4(f32x4(1.0, math.inf(f32), 1.0, 1.0))), 0)); + try expect(any(isNan(normalize4(f32x4(-math.inf(f32), math.inf(f32), 0.0, 0.0))), 0)); + try expect(any(isNan(normalize4(f32x4(-math.nan(f32), math.nan(f32), 0.0, 0.0))), 0)); + try expect(any(isNan(normalize4(f32x4(0, 0, 0, 0))), 0)); + } +} + +fn vecMulMat(v: Vec, m: Mat) Vec { + const vx = @shuffle(f32, v, undefined, [4]i32{ 0, 0, 0, 0 }); + const vy = @shuffle(f32, v, undefined, [4]i32{ 1, 1, 1, 1 }); + const vz = @shuffle(f32, v, undefined, [4]i32{ 2, 2, 2, 2 }); + const vw = @shuffle(f32, v, undefined, [4]i32{ 3, 3, 3, 3 }); + return vx * m[0] + vy * m[1] + vz * m[2] + vw * m[3]; +} +fn matMulVec(m: Mat, v: Vec) Vec { + return .{ dot4(m[0], v)[0], dot4(m[1], v)[0], dot4(m[2], v)[0], dot4(m[3], v)[0] }; +} +test "zmath.vecMulMat" { + const m = Mat{ + f32x4(1.0, 0.0, 0.0, 0.0), + f32x4(0.0, 1.0, 0.0, 0.0), + f32x4(0.0, 0.0, 1.0, 0.0), + f32x4(2.0, 3.0, 4.0, 1.0), + }; + const vm = mul(f32x4(1.0, 2.0, 3.0, 1.0), m); + const mv = mul(m, f32x4(1.0, 2.0, 3.0, 1.0)); + const v = mul(transpose(m), f32x4(1.0, 2.0, 3.0, 1.0)); + try expect(approxEqAbs(vm, f32x4(3.0, 5.0, 7.0, 1.0), 0.0001)); + try expect(approxEqAbs(mv, f32x4(1.0, 2.0, 3.0, 21.0), 0.0001)); + try expect(approxEqAbs(v, f32x4(3.0, 5.0, 7.0, 1.0), 0.0001)); +} +// ------------------------------------------------------------------------------ +// +// 4. Matrix functions +// +// ------------------------------------------------------------------------------ +pub fn identity() Mat { + const static = struct { + const identity = Mat{ + f32x4(1.0, 0.0, 0.0, 0.0), + f32x4(0.0, 1.0, 0.0, 0.0), + f32x4(0.0, 0.0, 1.0, 0.0), + f32x4(0.0, 0.0, 0.0, 1.0), + }; + }; + return static.identity; +} + +fn mulRetType(comptime Ta: type, comptime Tb: type) type { + if (Ta == Mat and Tb == Mat) { + return Mat; + } else if ((Ta == f32 and Tb == Mat) or (Ta == Mat and Tb == f32)) { + return Mat; + } else if ((Ta == Vec and Tb == Mat) or (Ta == Mat and Tb == Vec)) { + return Vec; + } + @compileError("zmath.mul() not implemented for types: " ++ @typeName(Ta) ++ @typeName(Tb)); +} + +pub fn mul(a: anytype, b: anytype) mulRetType(@TypeOf(a), @TypeOf(b)) { + const Ta = @TypeOf(a); + const Tb = @TypeOf(b); + if (Ta == Mat and Tb == Mat) { + return mulMat(a, b); + } else if (Ta == f32 and Tb == Mat) { + const va = splat(F32x4, a); + return Mat{ va * b[0], va * b[1], va * b[2], va * b[3] }; + } else if (Ta == Mat and Tb == f32) { + const vb = splat(F32x4, b); + return Mat{ a[0] * vb, a[1] * vb, a[2] * vb, a[3] * vb }; + } else if (Ta == Vec and Tb == Mat) { + return vecMulMat(a, b); + } else if (Ta == Mat and Tb == Vec) { + return matMulVec(a, b); + } else { + @compileError("zmath.mul() not implemented for types: " ++ @typeName(Ta) ++ ", " ++ @typeName(Tb)); + } +} +test "zmath.mul" { + { + const m = Mat{ + f32x4(0.1, 0.2, 0.3, 0.4), + f32x4(0.5, 0.6, 0.7, 0.8), + f32x4(0.9, 1.0, 1.1, 1.2), + f32x4(1.3, 1.4, 1.5, 1.6), + }; + const ms = mul(@as(f32, 2.0), m); + try expect(approxEqAbs(ms[0], f32x4(0.2, 0.4, 0.6, 0.8), 0.0001)); + try expect(approxEqAbs(ms[1], f32x4(1.0, 1.2, 1.4, 1.6), 0.0001)); + try expect(approxEqAbs(ms[2], f32x4(1.8, 2.0, 2.2, 2.4), 0.0001)); + try expect(approxEqAbs(ms[3], f32x4(2.6, 2.8, 3.0, 3.2), 0.0001)); + } +} + +fn mulMat(m0: Mat, m1: Mat) Mat { + var result: Mat = undefined; + comptime var row: u32 = 0; + inline while (row < 4) : (row += 1) { + const vx = swizzle(m0[row], .x, .x, .x, .x); + const vy = swizzle(m0[row], .y, .y, .y, .y); + const vz = swizzle(m0[row], .z, .z, .z, .z); + const vw = swizzle(m0[row], .w, .w, .w, .w); + result[row] = mulAdd(vx, m1[0], vz * m1[2]) + mulAdd(vy, m1[1], vw * m1[3]); + } + return result; +} +test "zmath.matrix.mul" { + const a = Mat{ + f32x4(0.1, 0.2, 0.3, 0.4), + f32x4(0.5, 0.6, 0.7, 0.8), + f32x4(0.9, 1.0, 1.1, 1.2), + f32x4(1.3, 1.4, 1.5, 1.6), + }; + const b = Mat{ + f32x4(1.7, 1.8, 1.9, 2.0), + f32x4(2.1, 2.2, 2.3, 2.4), + f32x4(2.5, 2.6, 2.7, 2.8), + f32x4(2.9, 3.0, 3.1, 3.2), + }; + const c = mul(a, b); + try expect(approxEqAbs(c[0], f32x4(2.5, 2.6, 2.7, 2.8), 0.0001)); + try expect(approxEqAbs(c[1], f32x4(6.18, 6.44, 6.7, 6.96), 0.0001)); + try expect(approxEqAbs(c[2], f32x4(9.86, 10.28, 10.7, 11.12), 0.0001)); + try expect(approxEqAbs(c[3], f32x4(13.54, 14.12, 14.7, 15.28), 0.0001)); +} + +pub fn transpose(m: Mat) Mat { + const temp1 = @shuffle(f32, m[0], m[1], [4]i32{ 0, 1, ~@as(i32, 0), ~@as(i32, 1) }); + const temp3 = @shuffle(f32, m[0], m[1], [4]i32{ 2, 3, ~@as(i32, 2), ~@as(i32, 3) }); + const temp2 = @shuffle(f32, m[2], m[3], [4]i32{ 0, 1, ~@as(i32, 0), ~@as(i32, 1) }); + const temp4 = @shuffle(f32, m[2], m[3], [4]i32{ 2, 3, ~@as(i32, 2), ~@as(i32, 3) }); + return .{ + @shuffle(f32, temp1, temp2, [4]i32{ 0, 2, ~@as(i32, 0), ~@as(i32, 2) }), + @shuffle(f32, temp1, temp2, [4]i32{ 1, 3, ~@as(i32, 1), ~@as(i32, 3) }), + @shuffle(f32, temp3, temp4, [4]i32{ 0, 2, ~@as(i32, 0), ~@as(i32, 2) }), + @shuffle(f32, temp3, temp4, [4]i32{ 1, 3, ~@as(i32, 1), ~@as(i32, 3) }), + }; +} +test "zmath.matrix.transpose" { + const m = Mat{ + f32x4(1.0, 2.0, 3.0, 4.0), + f32x4(5.0, 6.0, 7.0, 8.0), + f32x4(9.0, 10.0, 11.0, 12.0), + f32x4(13.0, 14.0, 15.0, 16.0), + }; + const mt = transpose(m); + try expect(approxEqAbs(mt[0], f32x4(1.0, 5.0, 9.0, 13.0), 0.0001)); + try expect(approxEqAbs(mt[1], f32x4(2.0, 6.0, 10.0, 14.0), 0.0001)); + try expect(approxEqAbs(mt[2], f32x4(3.0, 7.0, 11.0, 15.0), 0.0001)); + try expect(approxEqAbs(mt[3], f32x4(4.0, 8.0, 12.0, 16.0), 0.0001)); +} + +pub fn rotationX(angle: f32) Mat { + const sc = sincos(angle); + return .{ + f32x4(1.0, 0.0, 0.0, 0.0), + f32x4(0.0, sc[1], sc[0], 0.0), + f32x4(0.0, -sc[0], sc[1], 0.0), + f32x4(0.0, 0.0, 0.0, 1.0), + }; +} + +pub fn rotationY(angle: f32) Mat { + const sc = sincos(angle); + return .{ + f32x4(sc[1], 0.0, -sc[0], 0.0), + f32x4(0.0, 1.0, 0.0, 0.0), + f32x4(sc[0], 0.0, sc[1], 0.0), + f32x4(0.0, 0.0, 0.0, 1.0), + }; +} + +pub fn rotationZ(angle: f32) Mat { + const sc = sincos(angle); + return .{ + f32x4(sc[1], sc[0], 0.0, 0.0), + f32x4(-sc[0], sc[1], 0.0, 0.0), + f32x4(0.0, 0.0, 1.0, 0.0), + f32x4(0.0, 0.0, 0.0, 1.0), + }; +} + +pub fn translation(x: f32, y: f32, z: f32) Mat { + return .{ + f32x4(1.0, 0.0, 0.0, 0.0), + f32x4(0.0, 1.0, 0.0, 0.0), + f32x4(0.0, 0.0, 1.0, 0.0), + f32x4(x, y, z, 1.0), + }; +} +pub fn translationV(v: Vec) Mat { + return translation(v[0], v[1], v[2]); +} + +pub fn scaling(x: f32, y: f32, z: f32) Mat { + return .{ + f32x4(x, 0.0, 0.0, 0.0), + f32x4(0.0, y, 0.0, 0.0), + f32x4(0.0, 0.0, z, 0.0), + f32x4(0.0, 0.0, 0.0, 1.0), + }; +} +pub fn scalingV(v: Vec) Mat { + return scaling(v[0], v[1], v[2]); +} + +pub fn lookToLh(eyepos: Vec, eyedir: Vec, updir: Vec) Mat { + const az = normalize3(eyedir); + const ax = normalize3(cross3(updir, az)); + const ay = normalize3(cross3(az, ax)); + return transpose(.{ + f32x4(ax[0], ax[1], ax[2], -dot3(ax, eyepos)[0]), + f32x4(ay[0], ay[1], ay[2], -dot3(ay, eyepos)[0]), + f32x4(az[0], az[1], az[2], -dot3(az, eyepos)[0]), + f32x4(0.0, 0.0, 0.0, 1.0), + }); +} +pub fn lookToRh(eyepos: Vec, eyedir: Vec, updir: Vec) Mat { + return lookToLh(eyepos, -eyedir, updir); +} +pub fn lookAtLh(eyepos: Vec, focuspos: Vec, updir: Vec) Mat { + return lookToLh(eyepos, focuspos - eyepos, updir); +} +pub fn lookAtRh(eyepos: Vec, focuspos: Vec, updir: Vec) Mat { + return lookToLh(eyepos, eyepos - focuspos, updir); +} +test "zmath.matrix.lookToLh" { + const m = lookToLh(f32x4(0.0, 0.0, -3.0, 1.0), f32x4(0.0, 0.0, 1.0, 0.0), f32x4(0.0, 1.0, 0.0, 0.0)); + try expect(approxEqAbs(m[0], f32x4(1.0, 0.0, 0.0, 0.0), 0.001)); + try expect(approxEqAbs(m[1], f32x4(0.0, 1.0, 0.0, 0.0), 0.001)); + try expect(approxEqAbs(m[2], f32x4(0.0, 0.0, 1.0, 0.0), 0.001)); + try expect(approxEqAbs(m[3], f32x4(0.0, 0.0, 3.0, 1.0), 0.001)); +} + +pub fn perspectiveFovLh(fovy: f32, aspect: f32, near: f32, far: f32) Mat { + const scfov = sincos(0.5 * fovy); + + assert(near > 0.0 and far > 0.0 and far > near); + assert(!math.approxEqAbs(f32, scfov[0], 0.0, 0.001)); + assert(!math.approxEqAbs(f32, far, near, 0.001)); + assert(!math.approxEqAbs(f32, aspect, 0.0, 0.01)); + + const h = scfov[1] / scfov[0]; + const w = h / aspect; + const r = far / (far - near); + return .{ + f32x4(w, 0.0, 0.0, 0.0), + f32x4(0.0, h, 0.0, 0.0), + f32x4(0.0, 0.0, r, 1.0), + f32x4(0.0, 0.0, -r * near, 0.0), + }; +} +pub fn perspectiveFovRh(fovy: f32, aspect: f32, near: f32, far: f32) Mat { + const scfov = sincos(0.5 * fovy); + + assert(near > 0.0 and far > 0.0 and far > near); + assert(!math.approxEqAbs(f32, scfov[0], 0.0, 0.001)); + assert(!math.approxEqAbs(f32, far, near, 0.001)); + assert(!math.approxEqAbs(f32, aspect, 0.0, 0.01)); + + const h = scfov[1] / scfov[0]; + const w = h / aspect; + const r = far / (near - far); + return .{ + f32x4(w, 0.0, 0.0, 0.0), + f32x4(0.0, h, 0.0, 0.0), + f32x4(0.0, 0.0, r, -1.0), + f32x4(0.0, 0.0, r * near, 0.0), + }; +} + +// Produces Z values in [-1.0, 1.0] range (OpenGL defaults) +pub fn perspectiveFovRhGl(fovy: f32, aspect: f32, near: f32, far: f32) Mat { + const scfov = sincos(0.5 * fovy); + + assert(near > 0.0 and far > 0.0 and far > near); + assert(!math.approxEqAbs(f32, scfov[0], 0.0, 0.001)); + assert(!math.approxEqAbs(f32, far, near, 0.001)); + assert(!math.approxEqAbs(f32, aspect, 0.0, 0.01)); + + const h = scfov[1] / scfov[0]; + const w = h / aspect; + const r = near - far; + return .{ + f32x4(w, 0.0, 0.0, 0.0), + f32x4(0.0, h, 0.0, 0.0), + f32x4(0.0, 0.0, (near + far) / r, -1.0), + f32x4(0.0, 0.0, 2.0 * near * far / r, 0.0), + }; +} + +pub fn orthographicLh(w: f32, h: f32, near: f32, far: f32) Mat { + assert(!math.approxEqAbs(f32, w, 0.0, 0.001)); + assert(!math.approxEqAbs(f32, h, 0.0, 0.001)); + assert(!math.approxEqAbs(f32, far, near, 0.001)); + + const r = 1 / (far - near); + return .{ + f32x4(2 / w, 0.0, 0.0, 0.0), + f32x4(0.0, 2 / h, 0.0, 0.0), + f32x4(0.0, 0.0, r, 0.0), + f32x4(0.0, 0.0, -r * near, 1.0), + }; +} + +pub fn orthographicRh(w: f32, h: f32, near: f32, far: f32) Mat { + assert(!math.approxEqAbs(f32, w, 0.0, 0.001)); + assert(!math.approxEqAbs(f32, h, 0.0, 0.001)); + assert(!math.approxEqAbs(f32, far, near, 0.001)); + + const r = 1 / (near - far); + return .{ + f32x4(2 / w, 0.0, 0.0, 0.0), + f32x4(0.0, 2 / h, 0.0, 0.0), + f32x4(0.0, 0.0, r, 0.0), + f32x4(0.0, 0.0, r * near, 1.0), + }; +} + +pub fn orthographicOffCenterLh(left: f32, right: f32, top: f32, bottom: f32, near: f32, far: f32) Mat { + assert(!math.approxEqAbs(f32, far, near, 0.001)); + + const r = 1.0 / (far - near); + + return .{ + f32x4(2 / (right - left), 0.0, 0.0, -(right + left) / (right - left)), + f32x4(0.0, 2 / (top - bottom), 0.0, -(top + bottom) / (top - bottom)), + f32x4(0.0, 0.0, r, -r * near), + f32x4(0.0, 0.0, 0.0, 1.0), + }; +} + +pub fn orthographicOffCenterRh(left: f32, right: f32, top: f32, bottom: f32, near: f32, far: f32) Mat { + assert(!math.approxEqAbs(f32, far, near, 0.001)); + + const r = 1.0 / (near - far); + + return .{ + f32x4(2 / (right - left), 0.0, 0.0, -(right + left) / (right - left)), + f32x4(0.0, 2 / (top - bottom), 0.0, -(top + bottom) / (top - bottom)), + f32x4(0.0, 0.0, r, r * near), + f32x4(0.0, 0.0, 0.0, 1.0), + }; +} + +pub fn determinant(m: Mat) F32x4 { + var v0 = swizzle(m[2], .y, .x, .x, .x); + var v1 = swizzle(m[3], .z, .z, .y, .y); + var v2 = swizzle(m[2], .y, .x, .x, .x); + var v3 = swizzle(m[3], .w, .w, .w, .z); + var v4 = swizzle(m[2], .z, .z, .y, .y); + var v5 = swizzle(m[3], .w, .w, .w, .z); + + var p0 = v0 * v1; + var p1 = v2 * v3; + var p2 = v4 * v5; + + v0 = swizzle(m[2], .z, .z, .y, .y); + v1 = swizzle(m[3], .y, .x, .x, .x); + v2 = swizzle(m[2], .w, .w, .w, .z); + v3 = swizzle(m[3], .y, .x, .x, .x); + v4 = swizzle(m[2], .w, .w, .w, .z); + v5 = swizzle(m[3], .z, .z, .y, .y); + + p0 = mulAdd(-v0, v1, p0); + p1 = mulAdd(-v2, v3, p1); + p2 = mulAdd(-v4, v5, p2); + + v0 = swizzle(m[1], .w, .w, .w, .z); + v1 = swizzle(m[1], .z, .z, .y, .y); + v2 = swizzle(m[1], .y, .x, .x, .x); + + const s = m[0] * f32x4(1.0, -1.0, 1.0, -1.0); + var r = v0 * p0; + r = mulAdd(-v1, p1, r); + r = mulAdd(v2, p2, r); + return dot4(s, r); +} +test "zmath.matrix.determinant" { + const m = Mat{ + f32x4(10.0, -9.0, -12.0, 1.0), + f32x4(7.0, -12.0, 11.0, 1.0), + f32x4(-10.0, 10.0, 3.0, 1.0), + f32x4(1.0, 2.0, 3.0, 4.0), + }; + try expect(approxEqAbs(determinant(m), splat(F32x4, 2939.0), 0.0001)); +} + +pub fn inverse(a: anytype) @TypeOf(a) { + const T = @TypeOf(a); + return switch (T) { + Mat => inverseMat(a), + Quat => inverseQuat(a), + else => @compileError("zmath.inverse() not implemented for " ++ @typeName(T)), + }; +} + +fn inverseMat(m: Mat) Mat { + return inverseDet(m, null); +} + +pub fn inverseDet(m: Mat, out_det: ?*F32x4) Mat { + const mt = transpose(m); + var v0: [4]F32x4 = undefined; + var v1: [4]F32x4 = undefined; + + v0[0] = swizzle(mt[2], .x, .x, .y, .y); + v1[0] = swizzle(mt[3], .z, .w, .z, .w); + v0[1] = swizzle(mt[0], .x, .x, .y, .y); + v1[1] = swizzle(mt[1], .z, .w, .z, .w); + v0[2] = @shuffle(f32, mt[2], mt[0], [4]i32{ 0, 2, ~@as(i32, 0), ~@as(i32, 2) }); + v1[2] = @shuffle(f32, mt[3], mt[1], [4]i32{ 1, 3, ~@as(i32, 1), ~@as(i32, 3) }); + + var d0 = v0[0] * v1[0]; + var d1 = v0[1] * v1[1]; + var d2 = v0[2] * v1[2]; + + v0[0] = swizzle(mt[2], .z, .w, .z, .w); + v1[0] = swizzle(mt[3], .x, .x, .y, .y); + v0[1] = swizzle(mt[0], .z, .w, .z, .w); + v1[1] = swizzle(mt[1], .x, .x, .y, .y); + v0[2] = @shuffle(f32, mt[2], mt[0], [4]i32{ 1, 3, ~@as(i32, 1), ~@as(i32, 3) }); + v1[2] = @shuffle(f32, mt[3], mt[1], [4]i32{ 0, 2, ~@as(i32, 0), ~@as(i32, 2) }); + + d0 = mulAdd(-v0[0], v1[0], d0); + d1 = mulAdd(-v0[1], v1[1], d1); + d2 = mulAdd(-v0[2], v1[2], d2); + + v0[0] = swizzle(mt[1], .y, .z, .x, .y); + v1[0] = @shuffle(f32, d0, d2, [4]i32{ ~@as(i32, 1), 1, 3, 0 }); + v0[1] = swizzle(mt[0], .z, .x, .y, .x); + v1[1] = @shuffle(f32, d0, d2, [4]i32{ 3, ~@as(i32, 1), 1, 2 }); + v0[2] = swizzle(mt[3], .y, .z, .x, .y); + v1[2] = @shuffle(f32, d1, d2, [4]i32{ ~@as(i32, 3), 1, 3, 0 }); + v0[3] = swizzle(mt[2], .z, .x, .y, .x); + v1[3] = @shuffle(f32, d1, d2, [4]i32{ 3, ~@as(i32, 3), 1, 2 }); + + var c0 = v0[0] * v1[0]; + var c2 = v0[1] * v1[1]; + var c4 = v0[2] * v1[2]; + var c6 = v0[3] * v1[3]; + + v0[0] = swizzle(mt[1], .z, .w, .y, .z); + v1[0] = @shuffle(f32, d0, d2, [4]i32{ 3, 0, 1, ~@as(i32, 0) }); + v0[1] = swizzle(mt[0], .w, .z, .w, .y); + v1[1] = @shuffle(f32, d0, d2, [4]i32{ 2, 1, ~@as(i32, 0), 0 }); + v0[2] = swizzle(mt[3], .z, .w, .y, .z); + v1[2] = @shuffle(f32, d1, d2, [4]i32{ 3, 0, 1, ~@as(i32, 2) }); + v0[3] = swizzle(mt[2], .w, .z, .w, .y); + v1[3] = @shuffle(f32, d1, d2, [4]i32{ 2, 1, ~@as(i32, 2), 0 }); + + c0 = mulAdd(-v0[0], v1[0], c0); + c2 = mulAdd(-v0[1], v1[1], c2); + c4 = mulAdd(-v0[2], v1[2], c4); + c6 = mulAdd(-v0[3], v1[3], c6); + + v0[0] = swizzle(mt[1], .w, .x, .w, .x); + v1[0] = @shuffle(f32, d0, d2, [4]i32{ 2, ~@as(i32, 1), ~@as(i32, 0), 2 }); + v0[1] = swizzle(mt[0], .y, .w, .x, .z); + v1[1] = @shuffle(f32, d0, d2, [4]i32{ ~@as(i32, 1), 0, 3, ~@as(i32, 0) }); + v0[2] = swizzle(mt[3], .w, .x, .w, .x); + v1[2] = @shuffle(f32, d1, d2, [4]i32{ 2, ~@as(i32, 3), ~@as(i32, 2), 2 }); + v0[3] = swizzle(mt[2], .y, .w, .x, .z); + v1[3] = @shuffle(f32, d1, d2, [4]i32{ ~@as(i32, 3), 0, 3, ~@as(i32, 2) }); + + const c1 = mulAdd(-v0[0], v1[0], c0); + const c3 = mulAdd(v0[1], v1[1], c2); + const c5 = mulAdd(-v0[2], v1[2], c4); + const c7 = mulAdd(v0[3], v1[3], c6); + + c0 = mulAdd(v0[0], v1[0], c0); + c2 = mulAdd(-v0[1], v1[1], c2); + c4 = mulAdd(v0[2], v1[2], c4); + c6 = mulAdd(-v0[3], v1[3], c6); + + var mr = Mat{ + f32x4(c0[0], c1[1], c0[2], c1[3]), + f32x4(c2[0], c3[1], c2[2], c3[3]), + f32x4(c4[0], c5[1], c4[2], c5[3]), + f32x4(c6[0], c7[1], c6[2], c7[3]), + }; + + const det = dot4(mr[0], mt[0]); + if (out_det != null) { + out_det.?.* = det; + } + + if (math.approxEqAbs(f32, det[0], 0.0, 0.0001)) { + return .{ + f32x4(0.0, 0.0, 0.0, 0.0), + f32x4(0.0, 0.0, 0.0, 0.0), + f32x4(0.0, 0.0, 0.0, 0.0), + f32x4(0.0, 0.0, 0.0, 0.0), + }; + } + + const scale = splat(F32x4, 1.0) / det; + mr[0] *= scale; + mr[1] *= scale; + mr[2] *= scale; + mr[3] *= scale; + return mr; +} +test "zmath.matrix.inverse" { + const m = Mat{ + f32x4(10.0, -9.0, -12.0, 1.0), + f32x4(7.0, -12.0, 11.0, 1.0), + f32x4(-10.0, 10.0, 3.0, 1.0), + f32x4(1.0, 2.0, 3.0, 4.0), + }; + var det: F32x4 = undefined; + const mi = inverseDet(m, &det); + try expect(approxEqAbs(det, splat(F32x4, 2939.0), 0.0001)); + + try expect(approxEqAbs(mi[0], f32x4(-0.170806, -0.13576, -0.349439, 0.164001), 0.0001)); + try expect(approxEqAbs(mi[1], f32x4(-0.163661, -0.14801, -0.253147, 0.141204), 0.0001)); + try expect(approxEqAbs(mi[2], f32x4(-0.0871045, 0.00646478, -0.0785982, 0.0398095), 0.0001)); + try expect(approxEqAbs(mi[3], f32x4(0.18986, 0.103096, 0.272882, 0.10854), 0.0001)); +} + +pub fn matFromNormAxisAngle(axis: Vec, angle: f32) Mat { + const sincos_angle = sincos(angle); + + const c2 = splat(F32x4, 1.0 - sincos_angle[1]); + const c1 = splat(F32x4, sincos_angle[1]); + const c0 = splat(F32x4, sincos_angle[0]); + + const n0 = swizzle(axis, .y, .z, .x, .w); + const n1 = swizzle(axis, .z, .x, .y, .w); + + var v0 = c2 * n0 * n1; + const r0 = c2 * axis * axis + c1; + const r1 = c0 * axis + v0; + var r2 = v0 - c0 * axis; + + v0 = andInt(r0, f32x4_mask3); + + var v1 = @shuffle(f32, r1, r2, [4]i32{ 0, 2, ~@as(i32, 1), ~@as(i32, 2) }); + v1 = swizzle(v1, .y, .z, .w, .x); + + var v2 = @shuffle(f32, r1, r2, [4]i32{ 1, 1, ~@as(i32, 0), ~@as(i32, 0) }); + v2 = swizzle(v2, .x, .z, .x, .z); + + r2 = @shuffle(f32, v0, v1, [4]i32{ 0, 3, ~@as(i32, 0), ~@as(i32, 1) }); + r2 = swizzle(r2, .x, .z, .w, .y); + + var m: Mat = undefined; + m[0] = r2; + + r2 = @shuffle(f32, v0, v1, [4]i32{ 1, 3, ~@as(i32, 2), ~@as(i32, 3) }); + r2 = swizzle(r2, .z, .x, .w, .y); + m[1] = r2; + + v2 = @shuffle(f32, v2, v0, [4]i32{ 0, 1, ~@as(i32, 2), ~@as(i32, 3) }); + m[2] = v2; + m[3] = f32x4(0.0, 0.0, 0.0, 1.0); + return m; +} +pub fn matFromAxisAngle(axis: Vec, angle: f32) Mat { + assert(!all(axis == splat(F32x4, 0.0), 3)); + assert(!all(isInf(axis), 3)); + const normal = normalize3(axis); + return matFromNormAxisAngle(normal, angle); +} +test "zmath.matrix.matFromAxisAngle" { + { + const m0 = matFromAxisAngle(f32x4(1.0, 0.0, 0.0, 0.0), math.pi * 0.25); + const m1 = rotationX(math.pi * 0.25); + try expect(approxEqAbs(m0[0], m1[0], 0.001)); + try expect(approxEqAbs(m0[1], m1[1], 0.001)); + try expect(approxEqAbs(m0[2], m1[2], 0.001)); + try expect(approxEqAbs(m0[3], m1[3], 0.001)); + } + { + const m0 = matFromAxisAngle(f32x4(0.0, 1.0, 0.0, 0.0), math.pi * 0.125); + const m1 = rotationY(math.pi * 0.125); + try expect(approxEqAbs(m0[0], m1[0], 0.001)); + try expect(approxEqAbs(m0[1], m1[1], 0.001)); + try expect(approxEqAbs(m0[2], m1[2], 0.001)); + try expect(approxEqAbs(m0[3], m1[3], 0.001)); + } + { + const m0 = matFromAxisAngle(f32x4(0.0, 0.0, 1.0, 0.0), math.pi * 0.333); + const m1 = rotationZ(math.pi * 0.333); + try expect(approxEqAbs(m0[0], m1[0], 0.001)); + try expect(approxEqAbs(m0[1], m1[1], 0.001)); + try expect(approxEqAbs(m0[2], m1[2], 0.001)); + try expect(approxEqAbs(m0[3], m1[3], 0.001)); + } +} + +pub fn matFromQuat(quat: Quat) Mat { + const q0 = quat + quat; + var q1 = quat * q0; + + var v0 = swizzle(q1, .y, .x, .x, .w); + v0 = andInt(v0, f32x4_mask3); + + var v1 = swizzle(q1, .z, .z, .y, .w); + v1 = andInt(v1, f32x4_mask3); + + const r0 = (f32x4(1.0, 1.0, 1.0, 0.0) - v0) - v1; + + v0 = swizzle(quat, .x, .x, .y, .w); + v1 = swizzle(q0, .z, .y, .z, .w); + v0 = v0 * v1; + + v1 = swizzle(quat, .w, .w, .w, .w); + const v2 = swizzle(q0, .y, .z, .x, .w); + v1 = v1 * v2; + + const r1 = v0 + v1; + const r2 = v0 - v1; + + v0 = @shuffle(f32, r1, r2, [4]i32{ 1, 2, ~@as(i32, 0), ~@as(i32, 1) }); + v0 = swizzle(v0, .x, .z, .w, .y); + v1 = @shuffle(f32, r1, r2, [4]i32{ 0, 0, ~@as(i32, 2), ~@as(i32, 2) }); + v1 = swizzle(v1, .x, .z, .x, .z); + + q1 = @shuffle(f32, r0, v0, [4]i32{ 0, 3, ~@as(i32, 0), ~@as(i32, 1) }); + q1 = swizzle(q1, .x, .z, .w, .y); + + var m: Mat = undefined; + m[0] = q1; + + q1 = @shuffle(f32, r0, v0, [4]i32{ 1, 3, ~@as(i32, 2), ~@as(i32, 3) }); + q1 = swizzle(q1, .z, .x, .w, .y); + m[1] = q1; + + q1 = @shuffle(f32, v1, r0, [4]i32{ 0, 1, ~@as(i32, 2), ~@as(i32, 3) }); + m[2] = q1; + m[3] = f32x4(0.0, 0.0, 0.0, 1.0); + return m; +} +test "zmath.matrix.matFromQuat" { + { + const m = matFromQuat(f32x4(0.0, 0.0, 0.0, 1.0)); + try expect(approxEqAbs(m[0], f32x4(1.0, 0.0, 0.0, 0.0), 0.0001)); + try expect(approxEqAbs(m[1], f32x4(0.0, 1.0, 0.0, 0.0), 0.0001)); + try expect(approxEqAbs(m[2], f32x4(0.0, 0.0, 1.0, 0.0), 0.0001)); + try expect(approxEqAbs(m[3], f32x4(0.0, 0.0, 0.0, 1.0), 0.0001)); + } +} + +pub fn matFromRollPitchYaw(pitch: f32, yaw: f32, roll: f32) Mat { + return matFromRollPitchYawV(f32x4(pitch, yaw, roll, 0.0)); +} +pub fn matFromRollPitchYawV(angles: Vec) Mat { + return matFromQuat(quatFromRollPitchYawV(angles)); +} + +pub fn matToQuat(m: Mat) Quat { + return quatFromMat(m); +} + +pub inline fn loadMat(mem: []const f32) Mat { + return .{ + load(mem[0..4], F32x4, 0), + load(mem[4..8], F32x4, 0), + load(mem[8..12], F32x4, 0), + load(mem[12..16], F32x4, 0), + }; +} +test "zmath.loadMat" { + const a = [18]f32{ + 1.0, 2.0, 3.0, 4.0, + 5.0, 6.0, 7.0, 8.0, + 9.0, 10.0, 11.0, 12.0, + 13.0, 14.0, 15.0, 16.0, + 17.0, 18.0, + }; + const m = loadMat(a[1..]); + try expect(approxEqAbs(m[0], f32x4(2.0, 3.0, 4.0, 5.0), 0.0)); + try expect(approxEqAbs(m[1], f32x4(6.0, 7.0, 8.0, 9.0), 0.0)); + try expect(approxEqAbs(m[2], f32x4(10.0, 11.0, 12.0, 13.0), 0.0)); + try expect(approxEqAbs(m[3], f32x4(14.0, 15.0, 16.0, 17.0), 0.0)); +} + +pub inline fn storeMat(mem: []f32, m: Mat) void { + store(mem[0..4], m[0], 0); + store(mem[4..8], m[1], 0); + store(mem[8..12], m[2], 0); + store(mem[12..16], m[3], 0); +} + +pub inline fn loadMat43(mem: []const f32) Mat { + return .{ + f32x4(mem[0], mem[1], mem[2], 0.0), + f32x4(mem[3], mem[4], mem[5], 0.0), + f32x4(mem[6], mem[7], mem[8], 0.0), + f32x4(mem[9], mem[10], mem[11], 1.0), + }; +} + +pub inline fn storeMat43(mem: []f32, m: Mat) void { + store(mem[0..3], m[0], 3); + store(mem[3..6], m[1], 3); + store(mem[6..9], m[2], 3); + store(mem[9..12], m[3], 3); +} + +pub inline fn loadMat34(mem: []const f32) Mat { + return .{ + load(mem[0..4], F32x4, 0), + load(mem[4..8], F32x4, 0), + load(mem[8..12], F32x4, 0), + f32x4(0.0, 0.0, 0.0, 1.0), + }; +} + +pub inline fn storeMat34(mem: []f32, m: Mat) void { + store(mem[0..4], m[0], 0); + store(mem[4..8], m[1], 0); + store(mem[8..12], m[2], 0); +} + +pub inline fn matToArr(m: Mat) [16]f32 { + var array: [16]f32 = undefined; + storeMat(array[0..], m); + return array; +} + +pub inline fn matToArr43(m: Mat) [12]f32 { + var array: [12]f32 = undefined; + storeMat43(array[0..], m); + return array; +} + +pub inline fn matToArr34(m: Mat) [12]f32 { + var array: [12]f32 = undefined; + storeMat34(array[0..], m); + return array; +} +// ------------------------------------------------------------------------------ +// +// 5. Quaternion functions +// +// ------------------------------------------------------------------------------ +pub fn qmul(q0: Quat, q1: Quat) Quat { + var result = swizzle(q1, .w, .w, .w, .w); + var q1x = swizzle(q1, .x, .x, .x, .x); + var q1y = swizzle(q1, .y, .y, .y, .y); + var q1z = swizzle(q1, .z, .z, .z, .z); + result = result * q0; + var q0_shuf = swizzle(q0, .w, .z, .y, .x); + q1x = q1x * q0_shuf; + q0_shuf = swizzle(q0_shuf, .y, .x, .w, .z); + result = mulAdd(q1x, f32x4(1.0, -1.0, 1.0, -1.0), result); + q1y = q1y * q0_shuf; + q0_shuf = swizzle(q0_shuf, .w, .z, .y, .x); + q1y = q1y * f32x4(1.0, 1.0, -1.0, -1.0); + q1z = q1z * q0_shuf; + q1y = mulAdd(q1z, f32x4(-1.0, 1.0, 1.0, -1.0), q1y); + return result + q1y; +} +test "zmath.quaternion.mul" { + { + const q0 = f32x4(2.0, 3.0, 4.0, 1.0); + const q1 = f32x4(3.0, 2.0, 1.0, 4.0); + try expect(approxEqAbs(qmul(q0, q1), f32x4(16.0, 4.0, 22.0, -12.0), 0.0001)); + } +} + +pub fn quatToMat(quat: Quat) Mat { + return matFromQuat(quat); +} + +pub fn quatToAxisAngle(quat: Quat, axis: *Vec, angle: *f32) void { + axis.* = quat; + angle.* = 2.0 * acos(quat[3]); +} +test "zmath.quaternion.quatToAxisAngle" { + { + const q0 = quatFromNormAxisAngle(f32x4(1.0, 0.0, 0.0, 0.0), 0.25 * math.pi); + var axis: Vec = f32x4(4.0, 3.0, 2.0, 1.0); + var angle: f32 = 10.0; + quatToAxisAngle(q0, &axis, &angle); + try expect(math.approxEqAbs(f32, axis[0], @sin(@as(f32, 0.25) * math.pi * 0.5), 0.0001)); + try expect(axis[1] == 0.0); + try expect(axis[2] == 0.0); + try expect(math.approxEqAbs(f32, angle, 0.25 * math.pi, 0.0001)); + } +} + +pub fn quatFromMat(m: Mat) Quat { + const r0 = m[0]; + const r1 = m[1]; + const r2 = m[2]; + const r00 = swizzle(r0, .x, .x, .x, .x); + const r11 = swizzle(r1, .y, .y, .y, .y); + const r22 = swizzle(r2, .z, .z, .z, .z); + + const x2gey2 = (r11 - r00) <= splat(F32x4, 0.0); + const z2gew2 = (r11 + r00) <= splat(F32x4, 0.0); + const x2py2gez2pw2 = r22 <= splat(F32x4, 0.0); + + var t0 = mulAdd(r00, f32x4(1.0, -1.0, -1.0, 1.0), splat(F32x4, 1.0)); + var t1 = r11 * f32x4(-1.0, 1.0, -1.0, 1.0); + var t2 = mulAdd(r22, f32x4(-1.0, -1.0, 1.0, 1.0), t0); + const x2y2z2w2 = t1 + t2; + + t0 = @shuffle(f32, r0, r1, [4]i32{ 1, 2, ~@as(i32, 2), ~@as(i32, 1) }); + t1 = @shuffle(f32, r1, r2, [4]i32{ 0, 0, ~@as(i32, 0), ~@as(i32, 1) }); + t1 = swizzle(t1, .x, .z, .w, .y); + const xyxzyz = t0 + t1; + + t0 = @shuffle(f32, r2, r1, [4]i32{ 1, 0, ~@as(i32, 0), ~@as(i32, 0) }); + t1 = @shuffle(f32, r1, r0, [4]i32{ 2, 2, ~@as(i32, 2), ~@as(i32, 1) }); + t1 = swizzle(t1, .x, .z, .w, .y); + const xwywzw = (t0 - t1) * f32x4(-1.0, 1.0, -1.0, 1.0); + + t0 = @shuffle(f32, x2y2z2w2, xyxzyz, [4]i32{ 0, 1, ~@as(i32, 0), ~@as(i32, 0) }); + t1 = @shuffle(f32, x2y2z2w2, xwywzw, [4]i32{ 2, 3, ~@as(i32, 2), ~@as(i32, 0) }); + t2 = @shuffle(f32, xyxzyz, xwywzw, [4]i32{ 1, 2, ~@as(i32, 0), ~@as(i32, 1) }); + + const tensor0 = @shuffle(f32, t0, t2, [4]i32{ 0, 2, ~@as(i32, 0), ~@as(i32, 2) }); + const tensor1 = @shuffle(f32, t0, t2, [4]i32{ 2, 1, ~@as(i32, 1), ~@as(i32, 3) }); + const tensor2 = @shuffle(f32, t2, t1, [4]i32{ 0, 1, ~@as(i32, 0), ~@as(i32, 2) }); + const tensor3 = @shuffle(f32, t2, t1, [4]i32{ 2, 3, ~@as(i32, 2), ~@as(i32, 1) }); + + t0 = select(x2gey2, tensor0, tensor1); + t1 = select(z2gew2, tensor2, tensor3); + t2 = select(x2py2gez2pw2, t0, t1); + + return t2 / length4(t2); +} +test "zmath.quatFromMat" { + { + const q0 = quatFromAxisAngle(f32x4(1.0, 0.0, 0.0, 0.0), 0.25 * math.pi); + const q1 = quatFromMat(rotationX(0.25 * math.pi)); + try expect(approxEqAbs(q0, q1, 0.0001)); + } + { + const q0 = quatFromAxisAngle(f32x4(1.0, 2.0, 0.5, 0.0), 0.25 * math.pi); + const q1 = quatFromMat(matFromAxisAngle(f32x4(1.0, 2.0, 0.5, 0.0), 0.25 * math.pi)); + try expect(approxEqAbs(q0, q1, 0.0001)); + } + { + const q0 = quatFromRollPitchYaw(0.1 * math.pi, -0.2 * math.pi, 0.3 * math.pi); + const q1 = quatFromMat(matFromRollPitchYaw(0.1 * math.pi, -0.2 * math.pi, 0.3 * math.pi)); + try expect(approxEqAbs(q0, q1, 0.0001)); + } +} + +pub fn quatFromNormAxisAngle(axis: Vec, angle: f32) Quat { + const n = f32x4(axis[0], axis[1], axis[2], 1.0); + const sc = sincos(0.5 * angle); + return n * f32x4(sc[0], sc[0], sc[0], sc[1]); +} +pub fn quatFromAxisAngle(axis: Vec, angle: f32) Quat { + assert(!all(axis == splat(F32x4, 0.0), 3)); + assert(!all(isInf(axis), 3)); + const normal = normalize3(axis); + return quatFromNormAxisAngle(normal, angle); +} +test "zmath.quaternion.quatFromNormAxisAngle" { + { + const q0 = quatFromAxisAngle(f32x4(1.0, 0.0, 0.0, 0.0), 0.25 * math.pi); + const q1 = quatFromAxisAngle(f32x4(0.0, 1.0, 0.0, 0.0), 0.125 * math.pi); + const m0 = rotationX(0.25 * math.pi); + const m1 = rotationY(0.125 * math.pi); + const mr0 = quatToMat(qmul(q0, q1)); + const mr1 = mul(m0, m1); + try expect(approxEqAbs(mr0[0], mr1[0], 0.0001)); + try expect(approxEqAbs(mr0[1], mr1[1], 0.0001)); + try expect(approxEqAbs(mr0[2], mr1[2], 0.0001)); + try expect(approxEqAbs(mr0[3], mr1[3], 0.0001)); + } + { + const m0 = quatToMat(quatFromAxisAngle(f32x4(1.0, 2.0, 0.5, 0.0), 0.25 * math.pi)); + const m1 = matFromAxisAngle(f32x4(1.0, 2.0, 0.5, 0.0), 0.25 * math.pi); + try expect(approxEqAbs(m0[0], m1[0], 0.0001)); + try expect(approxEqAbs(m0[1], m1[1], 0.0001)); + try expect(approxEqAbs(m0[2], m1[2], 0.0001)); + try expect(approxEqAbs(m0[3], m1[3], 0.0001)); + } +} + +pub inline fn qidentity() Quat { + return f32x4(@as(f32, 0.0), @as(f32, 0.0), @as(f32, 0.0), @as(f32, 1.0)); +} + +pub inline fn conjugate(quat: Quat) Quat { + return quat * f32x4(-1.0, -1.0, -1.0, 1.0); +} + +fn inverseQuat(quat: Quat) Quat { + const l = lengthSq4(quat); + const conj = conjugate(quat); + return select(l <= splat(F32x4, math.floatEps(f32)), splat(F32x4, 0.0), conj / l); +} +test "zmath.quaternion.inverseQuat" { + try expect(approxEqAbs( + inverse(f32x4(2.0, 3.0, 4.0, 1.0)), + f32x4(-1.0 / 15.0, -1.0 / 10.0, -2.0 / 15.0, 1.0 / 30.0), + 0.0001, + )); + try expect(approxEqAbs(inverse(qidentity()), qidentity(), 0.0001)); +} + +pub fn slerp(q0: Quat, q1: Quat, t: f32) Quat { + return slerpV(q0, q1, splat(F32x4, t)); +} +pub fn slerpV(q0: Quat, q1: Quat, t: F32x4) Quat { + var cos_omega = dot4(q0, q1); + const sign = select(cos_omega < splat(F32x4, 0.0), splat(F32x4, -1.0), splat(F32x4, 1.0)); + + cos_omega = cos_omega * sign; + const sin_omega = sqrt(splat(F32x4, 1.0) - cos_omega * cos_omega); + + const omega = atan2(sin_omega, cos_omega); + + var v01 = t; + v01 = xorInt(andInt(v01, f32x4_mask2), f32x4_sign_mask1); + v01 = f32x4(1.0, 0.0, 0.0, 0.0) + v01; + + var s0 = sin(v01 * omega) / sin_omega; + s0 = select(cos_omega < splat(F32x4, 1.0 - 0.00001), s0, v01); + + const s1 = swizzle(s0, .y, .y, .y, .y); + s0 = swizzle(s0, .x, .x, .x, .x); + + return q0 * s0 + sign * q1 * s1; +} +test "zmath.quaternion.slerp" { + const from = f32x4(0.0, 0.0, 0.0, 1.0); + const to = f32x4(0.5, 0.5, -0.5, 0.5); + const result = slerp(from, to, 0.5); + try expect(approxEqAbs(result, f32x4(0.28867513, 0.28867513, -0.28867513, 0.86602540), 0.0001)); +} + +pub fn quatFromRollPitchYaw(pitch: f32, yaw: f32, roll: f32) Quat { + return quatFromRollPitchYawV(f32x4(pitch, yaw, roll, 0.0)); +} +pub fn quatFromRollPitchYawV(angles: Vec) Quat { // | pitch | yaw | roll | 0 | + const sc = sincos(splat(Vec, 0.5) * angles); + const p0 = @shuffle(f32, sc[1], sc[0], [4]i32{ ~@as(i32, 0), 0, 0, 0 }); + const p1 = @shuffle(f32, sc[0], sc[1], [4]i32{ ~@as(i32, 0), 0, 0, 0 }); + const y0 = @shuffle(f32, sc[1], sc[0], [4]i32{ 1, ~@as(i32, 1), 1, 1 }); + const y1 = @shuffle(f32, sc[0], sc[1], [4]i32{ 1, ~@as(i32, 1), 1, 1 }); + const r0 = @shuffle(f32, sc[1], sc[0], [4]i32{ 2, 2, ~@as(i32, 2), 2 }); + const r1 = @shuffle(f32, sc[0], sc[1], [4]i32{ 2, 2, ~@as(i32, 2), 2 }); + const q1 = p1 * f32x4(1.0, -1.0, -1.0, 1.0) * y1; + const q0 = p0 * y0 * r0; + return mulAdd(q1, r1, q0); +} +test "zmath.quaternion.quatFromRollPitchYawV" { + { + const m0 = quatToMat(quatFromRollPitchYawV(f32x4(0.25 * math.pi, 0.0, 0.0, 0.0))); + const m1 = rotationX(0.25 * math.pi); + try expect(approxEqAbs(m0[0], m1[0], 0.0001)); + try expect(approxEqAbs(m0[1], m1[1], 0.0001)); + try expect(approxEqAbs(m0[2], m1[2], 0.0001)); + try expect(approxEqAbs(m0[3], m1[3], 0.0001)); + } + { + const m0 = quatToMat(quatFromRollPitchYaw(0.1 * math.pi, 0.2 * math.pi, 0.3 * math.pi)); + const m1 = mul( + rotationZ(0.3 * math.pi), + mul(rotationX(0.1 * math.pi), rotationY(0.2 * math.pi)), + ); + try expect(approxEqAbs(m0[0], m1[0], 0.0001)); + try expect(approxEqAbs(m0[1], m1[1], 0.0001)); + try expect(approxEqAbs(m0[2], m1[2], 0.0001)); + try expect(approxEqAbs(m0[3], m1[3], 0.0001)); + } +} +// ------------------------------------------------------------------------------ +// +// 6. Color functions +// +// ------------------------------------------------------------------------------ +pub fn adjustSaturation(color: F32x4, saturation: f32) F32x4 { + const luminance = dot3(f32x4(0.2125, 0.7154, 0.0721, 0.0), color); + var result = mulAdd(color - luminance, f32x4s(saturation), luminance); + result[3] = color[3]; + return result; +} + +pub fn adjustContrast(color: F32x4, contrast: f32) F32x4 { + var result = mulAdd(color - f32x4s(0.5), f32x4s(contrast), f32x4s(0.5)); + result[3] = color[3]; + return result; +} + +pub fn rgbToHsl(rgb: F32x4) F32x4 { + const r = swizzle(rgb, .x, .x, .x, .x); + const g = swizzle(rgb, .y, .y, .y, .y); + const b = swizzle(rgb, .z, .z, .z, .z); + + const minv = min(r, min(g, b)); + const maxv = max(r, max(g, b)); + + const l = (minv + maxv) * f32x4s(0.5); + const d = maxv - minv; + const la = select(boolx4(true, true, true, false), l, rgb); + + if (all(d < f32x4s(math.floatEps(f32)), 3)) { + return select(boolx4(true, true, false, false), f32x4s(0.0), la); + } else { + var s: F32x4 = undefined; + var h: F32x4 = undefined; + + const d2 = minv + maxv; + + if (all(l > f32x4s(0.5), 3)) { + s = d / (f32x4s(2.0) - d2); + } else { + s = d / d2; + } + + if (all(r == maxv, 3)) { + h = (g - b) / d; + } else if (all(g == maxv, 3)) { + h = f32x4s(2.0) + (b - r) / d; + } else { + h = f32x4s(4.0) + (r - g) / d; + } + + h /= f32x4s(6.0); + + if (all(h < f32x4s(0.0), 3)) { + h += f32x4s(1.0); + } + + const lha = select(boolx4(true, true, false, false), h, la); + return select(boolx4(true, false, true, true), lha, s); + } +} +test "zmath.color.rgbToHsl" { + try expect(approxEqAbs(rgbToHsl(f32x4(0.2, 0.4, 0.8, 1.0)), f32x4(0.6111, 0.6, 0.5, 1.0), 0.0001)); + try expect(approxEqAbs(rgbToHsl(f32x4(1.0, 0.0, 0.0, 0.5)), f32x4(0.0, 1.0, 0.5, 0.5), 0.0001)); + try expect(approxEqAbs(rgbToHsl(f32x4(0.0, 1.0, 0.0, 0.25)), f32x4(0.3333, 1.0, 0.5, 0.25), 0.0001)); + try expect(approxEqAbs(rgbToHsl(f32x4(0.0, 0.0, 1.0, 1.0)), f32x4(0.6666, 1.0, 0.5, 1.0), 0.0001)); + try expect(approxEqAbs(rgbToHsl(f32x4(0.0, 0.0, 0.0, 1.0)), f32x4(0.0, 0.0, 0.0, 1.0), 0.0001)); + try expect(approxEqAbs(rgbToHsl(f32x4(1.0, 1.0, 1.0, 1.0)), f32x4(0.0, 0.0, 1.0, 1.0), 0.0001)); +} + +fn hueToClr(p: F32x4, q: F32x4, h: F32x4) F32x4 { + var t = h; + + if (all(t < f32x4s(0.0), 3)) + t += f32x4s(1.0); + + if (all(t > f32x4s(1.0), 3)) + t -= f32x4s(1.0); + + if (all(t < f32x4s(1.0 / 6.0), 3)) + return mulAdd(q - p, f32x4s(6.0) * t, p); + + if (all(t < f32x4s(0.5), 3)) + return q; + + if (all(t < f32x4s(2.0 / 3.0), 3)) + return mulAdd(q - p, f32x4s(6.0) * (f32x4s(2.0 / 3.0) - t), p); + + return p; +} + +pub fn hslToRgb(hsl: F32x4) F32x4 { + const s = swizzle(hsl, .y, .y, .y, .y); + const l = swizzle(hsl, .z, .z, .z, .z); + + if (all(isNearEqual(s, f32x4s(0.0), f32x4s(math.floatEps(f32))), 3)) { + return select(boolx4(true, true, true, false), l, hsl); + } else { + const h = swizzle(hsl, .x, .x, .x, .x); + var q: F32x4 = undefined; + if (all(l < f32x4s(0.5), 3)) { + q = l * (f32x4s(1.0) + s); + } else { + q = (l + s) - (l * s); + } + + const p = f32x4s(2.0) * l - q; + + const r = hueToClr(p, q, h + f32x4s(1.0 / 3.0)); + const g = hueToClr(p, q, h); + const b = hueToClr(p, q, h - f32x4s(1.0 / 3.0)); + + const rg = select(boolx4(true, false, false, false), r, g); + const ba = select(boolx4(true, true, true, false), b, hsl); + return select(boolx4(true, true, false, false), rg, ba); + } +} +test "zmath.color.hslToRgb" { + try expect(approxEqAbs(f32x4(0.2, 0.4, 0.8, 1.0), hslToRgb(f32x4(0.6111, 0.6, 0.5, 1.0)), 0.0001)); + try expect(approxEqAbs(f32x4(1.0, 0.0, 0.0, 0.5), hslToRgb(f32x4(0.0, 1.0, 0.5, 0.5)), 0.0001)); + try expect(approxEqAbs(f32x4(0.0, 1.0, 0.0, 0.25), hslToRgb(f32x4(0.3333, 1.0, 0.5, 0.25)), 0.0005)); + try expect(approxEqAbs(f32x4(0.0, 0.0, 1.0, 1.0), hslToRgb(f32x4(0.6666, 1.0, 0.5, 1.0)), 0.0005)); + try expect(approxEqAbs(f32x4(0.0, 0.0, 0.0, 1.0), hslToRgb(f32x4(0.0, 0.0, 0.0, 1.0)), 0.0001)); + try expect(approxEqAbs(f32x4(1.0, 1.0, 1.0, 1.0), hslToRgb(f32x4(0.0, 0.0, 1.0, 1.0)), 0.0001)); + try expect(approxEqAbs(hslToRgb(rgbToHsl(f32x4(1.0, 1.0, 1.0, 1.0))), f32x4(1.0, 1.0, 1.0, 1.0), 0.0005)); + try expect(approxEqAbs( + hslToRgb(rgbToHsl(f32x4(0.82198, 0.1839, 0.632, 1.0))), + f32x4(0.82198, 0.1839, 0.632, 1.0), + 0.0005, + )); + try expect(approxEqAbs( + rgbToHsl(hslToRgb(f32x4(0.82198, 0.1839, 0.632, 1.0))), + f32x4(0.82198, 0.1839, 0.632, 1.0), + 0.0005, + )); + try expect(approxEqAbs( + rgbToHsl(hslToRgb(f32x4(0.1839, 0.82198, 0.632, 1.0))), + f32x4(0.1839, 0.82198, 0.632, 1.0), + 0.0005, + )); + try expect(approxEqAbs( + hslToRgb(rgbToHsl(f32x4(0.1839, 0.632, 0.82198, 1.0))), + f32x4(0.1839, 0.632, 0.82198, 1.0), + 0.0005, + )); +} + +pub fn rgbToHsv(rgb: F32x4) F32x4 { + const r = swizzle(rgb, .x, .x, .x, .x); + const g = swizzle(rgb, .y, .y, .y, .y); + const b = swizzle(rgb, .z, .z, .z, .z); + + const minv = min(r, min(g, b)); + const v = max(r, max(g, b)); + const d = v - minv; + const s = if (all(isNearEqual(v, f32x4s(0.0), f32x4s(math.floatEps(f32))), 3)) f32x4s(0.0) else d / v; + + if (all(d < f32x4s(math.floatEps(f32)), 3)) { + const hv = select(boolx4(true, false, false, false), f32x4s(0.0), v); + const hva = select(boolx4(true, true, true, false), hv, rgb); + return select(boolx4(true, false, true, true), hva, s); + } else { + var h: F32x4 = undefined; + if (all(r == v, 3)) { + h = (g - b) / d; + if (all(g < b, 3)) + h += f32x4s(6.0); + } else if (all(g == v, 3)) { + h = f32x4s(2.0) + (b - r) / d; + } else { + h = f32x4s(4.0) + (r - g) / d; + } + + h /= f32x4s(6.0); + const hv = select(boolx4(true, false, false, false), h, v); + const hva = select(boolx4(true, true, true, false), hv, rgb); + return select(boolx4(true, false, true, true), hva, s); + } +} +test "zmath.color.rgbToHsv" { + try expect(approxEqAbs(rgbToHsv(f32x4(0.2, 0.4, 0.8, 1.0)), f32x4(0.6111, 0.75, 0.8, 1.0), 0.0001)); + try expect(approxEqAbs(rgbToHsv(f32x4(0.4, 0.2, 0.8, 1.0)), f32x4(0.7222, 0.75, 0.8, 1.0), 0.0001)); + try expect(approxEqAbs(rgbToHsv(f32x4(0.4, 0.8, 0.2, 1.0)), f32x4(0.2777, 0.75, 0.8, 1.0), 0.0001)); + try expect(approxEqAbs(rgbToHsv(f32x4(1.0, 0.0, 0.0, 0.5)), f32x4(0.0, 1.0, 1.0, 0.5), 0.0001)); + try expect(approxEqAbs(rgbToHsv(f32x4(0.0, 1.0, 0.0, 0.25)), f32x4(0.3333, 1.0, 1.0, 0.25), 0.0001)); + try expect(approxEqAbs(rgbToHsv(f32x4(0.0, 0.0, 1.0, 1.0)), f32x4(0.6666, 1.0, 1.0, 1.0), 0.0001)); + try expect(approxEqAbs(rgbToHsv(f32x4(0.0, 0.0, 0.0, 1.0)), f32x4(0.0, 0.0, 0.0, 1.0), 0.0001)); + try expect(approxEqAbs(rgbToHsv(f32x4(1.0, 1.0, 1.0, 1.0)), f32x4(0.0, 0.0, 1.0, 1.0), 0.0001)); +} + +pub fn hsvToRgb(hsv: F32x4) F32x4 { + const h = swizzle(hsv, .x, .x, .x, .x); + const s = swizzle(hsv, .y, .y, .y, .y); + const v = swizzle(hsv, .z, .z, .z, .z); + + const h6 = h * f32x4s(6.0); + const i = floor(h6); + const f = h6 - i; + + const p = v * (f32x4s(1.0) - s); + const q = v * (f32x4s(1.0) - f * s); + const t = v * (f32x4s(1.0) - (f32x4s(1.0) - f) * s); + + const ii = @as(i32, @intFromFloat(mod(i, f32x4s(6.0))[0])); + const rgb = switch (ii) { + 0 => blk: { + const vt = select(boolx4(true, false, false, false), v, t); + break :blk select(boolx4(true, true, false, false), vt, p); + }, + 1 => blk: { + const qv = select(boolx4(true, false, false, false), q, v); + break :blk select(boolx4(true, true, false, false), qv, p); + }, + 2 => blk: { + const pv = select(boolx4(true, false, false, false), p, v); + break :blk select(boolx4(true, true, false, false), pv, t); + }, + 3 => blk: { + const pq = select(boolx4(true, false, false, false), p, q); + break :blk select(boolx4(true, true, false, false), pq, v); + }, + 4 => blk: { + const tp = select(boolx4(true, false, false, false), t, p); + break :blk select(boolx4(true, true, false, false), tp, v); + }, + 5 => blk: { + const vp = select(boolx4(true, false, false, false), v, p); + break :blk select(boolx4(true, true, false, false), vp, q); + }, + else => unreachable, + }; + return select(boolx4(true, true, true, false), rgb, hsv); +} +test "zmath.color.hsvToRgb" { + const epsilon = 0.0005; + try expect(approxEqAbs(f32x4(0.2, 0.4, 0.8, 1.0), hsvToRgb(f32x4(0.6111, 0.75, 0.8, 1.0)), epsilon)); + try expect(approxEqAbs(f32x4(0.4, 0.2, 0.8, 1.0), hsvToRgb(f32x4(0.7222, 0.75, 0.8, 1.0)), epsilon)); + try expect(approxEqAbs(f32x4(0.4, 0.8, 0.2, 1.0), hsvToRgb(f32x4(0.2777, 0.75, 0.8, 1.0)), epsilon)); + try expect(approxEqAbs(f32x4(1.0, 0.0, 0.0, 0.5), hsvToRgb(f32x4(0.0, 1.0, 1.0, 0.5)), epsilon)); + try expect(approxEqAbs(f32x4(0.0, 1.0, 0.0, 0.25), hsvToRgb(f32x4(0.3333, 1.0, 1.0, 0.25)), epsilon)); + try expect(approxEqAbs(f32x4(0.0, 0.0, 1.0, 1.0), hsvToRgb(f32x4(0.6666, 1.0, 1.0, 1.0)), epsilon)); + try expect(approxEqAbs(f32x4(0.0, 0.0, 0.0, 1.0), hsvToRgb(f32x4(0.0, 0.0, 0.0, 1.0)), epsilon)); + try expect(approxEqAbs(f32x4(1.0, 1.0, 1.0, 1.0), hsvToRgb(f32x4(0.0, 0.0, 1.0, 1.0)), epsilon)); + try expect(approxEqAbs( + hsvToRgb(rgbToHsv(f32x4(0.1839, 0.632, 0.82198, 1.0))), + f32x4(0.1839, 0.632, 0.82198, 1.0), + epsilon, + )); + try expect(approxEqAbs( + hsvToRgb(rgbToHsv(f32x4(0.82198, 0.1839, 0.632, 1.0))), + f32x4(0.82198, 0.1839, 0.632, 1.0), + epsilon, + )); + try expect(approxEqAbs( + rgbToHsv(hsvToRgb(f32x4(0.82198, 0.1839, 0.632, 1.0))), + f32x4(0.82198, 0.1839, 0.632, 1.0), + epsilon, + )); + try expect(approxEqAbs( + rgbToHsv(hsvToRgb(f32x4(0.1839, 0.82198, 0.632, 1.0))), + f32x4(0.1839, 0.82198, 0.632, 1.0), + epsilon, + )); +} + +pub fn rgbToSrgb(rgb: F32x4) F32x4 { + const static = struct { + const cutoff = f32x4(0.0031308, 0.0031308, 0.0031308, 1.0); + const linear = f32x4(12.92, 12.92, 12.92, 1.0); + const scale = f32x4(1.055, 1.055, 1.055, 1.0); + const bias = f32x4(0.055, 0.055, 0.055, 1.0); + const rgamma = 1.0 / 2.4; + }; + var v = saturate(rgb); + const v0 = v * static.linear; + const v1 = static.scale * f32x4( + math.pow(f32, v[0], static.rgamma), + math.pow(f32, v[1], static.rgamma), + math.pow(f32, v[2], static.rgamma), + v[3], + ) - static.bias; + v = select(v < static.cutoff, v0, v1); + return select(boolx4(true, true, true, false), v, rgb); +} +test "zmath.color.rgbToSrgb" { + const epsilon = 0.001; + try expect(approxEqAbs(rgbToSrgb(f32x4(0.2, 0.4, 0.8, 1.0)), f32x4(0.484, 0.665, 0.906, 1.0), epsilon)); +} + +pub fn srgbToRgb(srgb: F32x4) F32x4 { + const static = struct { + const cutoff = f32x4(0.04045, 0.04045, 0.04045, 1.0); + const rlinear = f32x4(1.0 / 12.92, 1.0 / 12.92, 1.0 / 12.92, 1.0); + const scale = f32x4(1.0 / 1.055, 1.0 / 1.055, 1.0 / 1.055, 1.0); + const bias = f32x4(0.055, 0.055, 0.055, 1.0); + const gamma = 2.4; + }; + var v = saturate(srgb); + const v0 = v * static.rlinear; + var v1 = static.scale * (v + static.bias); + v1 = f32x4( + math.pow(f32, v1[0], static.gamma), + math.pow(f32, v1[1], static.gamma), + math.pow(f32, v1[2], static.gamma), + v1[3], + ); + v = select(v > static.cutoff, v1, v0); + return select(boolx4(true, true, true, false), v, srgb); +} +test "zmath.color.srgbToRgb" { + const epsilon = 0.0007; + try expect(approxEqAbs(f32x4(0.2, 0.4, 0.8, 1.0), srgbToRgb(f32x4(0.484, 0.665, 0.906, 1.0)), epsilon)); + try expect(approxEqAbs( + rgbToSrgb(srgbToRgb(f32x4(0.1839, 0.82198, 0.632, 1.0))), + f32x4(0.1839, 0.82198, 0.632, 1.0), + epsilon, + )); +} +// ------------------------------------------------------------------------------ +// +// X. Misc functions +// +// ------------------------------------------------------------------------------ +pub fn linePointDistance(linept0: Vec, linept1: Vec, pt: Vec) F32x4 { + const ptvec = pt - linept0; + const linevec = linept1 - linept0; + const scale = dot3(ptvec, linevec) / lengthSq3(linevec); + return length3(ptvec - linevec * scale); +} +test "zmath.linePointDistance" { + { + const linept0 = f32x4(-1.0, -2.0, -3.0, 1.0); + const linept1 = f32x4(1.0, 2.0, 3.0, 1.0); + const pt = f32x4(1.0, 1.0, 1.0, 1.0); + const v = linePointDistance(linept0, linept1, pt); + try expect(approxEqAbs(v, splat(F32x4, 0.654), 0.001)); + } +} + +fn sin32(v: f32) f32 { + var y = v - math.tau * @round(v * 1.0 / math.tau); + + if (y > 0.5 * math.pi) { + y = math.pi - y; + } else if (y < -math.pi * 0.5) { + y = -math.pi - y; + } + const y2 = y * y; + + // 11-degree minimax approximation + var sinv = mulAdd(@as(f32, -2.3889859e-08), y2, 2.7525562e-06); + sinv = mulAdd(sinv, y2, -0.00019840874); + sinv = mulAdd(sinv, y2, 0.0083333310); + sinv = mulAdd(sinv, y2, -0.16666667); + return y * mulAdd(sinv, y2, 1.0); +} +fn cos32(v: f32) f32 { + var y = v - math.tau * @round(v * 1.0 / math.tau); + + const sign = blk: { + if (y > 0.5 * math.pi) { + y = math.pi - y; + break :blk @as(f32, -1.0); + } else if (y < -math.pi * 0.5) { + y = -math.pi - y; + break :blk @as(f32, -1.0); + } else { + break :blk @as(f32, 1.0); + } + }; + const y2 = y * y; + + // 10-degree minimax approximation + var cosv = mulAdd(@as(f32, -2.6051615e-07), y2, 2.4760495e-05); + cosv = mulAdd(cosv, y2, -0.0013888378); + cosv = mulAdd(cosv, y2, 0.041666638); + cosv = mulAdd(cosv, y2, -0.5); + return sign * mulAdd(cosv, y2, 1.0); +} +fn sincos32(v: f32) [2]f32 { + var y = v - math.tau * @round(v * 1.0 / math.tau); + + const sign = blk: { + if (y > 0.5 * math.pi) { + y = math.pi - y; + break :blk @as(f32, -1.0); + } else if (y < -math.pi * 0.5) { + y = -math.pi - y; + break :blk @as(f32, -1.0); + } else { + break :blk @as(f32, 1.0); + } + }; + const y2 = y * y; + + // 11-degree minimax approximation + var sinv = mulAdd(@as(f32, -2.3889859e-08), y2, 2.7525562e-06); + sinv = mulAdd(sinv, y2, -0.00019840874); + sinv = mulAdd(sinv, y2, 0.0083333310); + sinv = mulAdd(sinv, y2, -0.16666667); + sinv = y * mulAdd(sinv, y2, 1.0); + + // 10-degree minimax approximation + var cosv = mulAdd(@as(f32, -2.6051615e-07), y2, 2.4760495e-05); + cosv = mulAdd(cosv, y2, -0.0013888378); + cosv = mulAdd(cosv, y2, 0.041666638); + cosv = mulAdd(cosv, y2, -0.5); + cosv = sign * mulAdd(cosv, y2, 1.0); + + return .{ sinv, cosv }; +} +test "zmath.sincos32" { + const epsilon = 0.0001; + + try expect(math.isNan(sincos32(math.inf(f32))[0])); + try expect(math.isNan(sincos32(math.inf(f32))[1])); + try expect(math.isNan(sincos32(-math.inf(f32))[0])); + try expect(math.isNan(sincos32(-math.inf(f32))[1])); + try expect(math.isNan(sincos32(math.nan(f32))[0])); + try expect(math.isNan(sincos32(-math.nan(f32))[1])); + + try expect(math.isNan(sin32(math.inf(f32)))); + try expect(math.isNan(cos32(math.inf(f32)))); + try expect(math.isNan(sin32(-math.inf(f32)))); + try expect(math.isNan(cos32(-math.inf(f32)))); + try expect(math.isNan(sin32(math.nan(f32)))); + try expect(math.isNan(cos32(-math.nan(f32)))); + + var f: f32 = -100.0; + var i: u32 = 0; + while (i < 100) : (i += 1) { + const sc = sincos32(f); + const s0 = sin32(f); + const c0 = cos32(f); + const s = @sin(f); + const c = @cos(f); + try expect(math.approxEqAbs(f32, sc[0], s, epsilon)); + try expect(math.approxEqAbs(f32, sc[1], c, epsilon)); + try expect(math.approxEqAbs(f32, s0, s, epsilon)); + try expect(math.approxEqAbs(f32, c0, c, epsilon)); + f += 0.12345 * @as(f32, @floatFromInt(i)); + } +} + +fn asin32(v: f32) f32 { + const x = @abs(v); + var omx = 1.0 - x; + if (omx < 0.0) { + omx = 0.0; + } + const root = @sqrt(omx); + + // 7-degree minimax approximation + var result = mulAdd(@as(f32, -0.0012624911), x, 0.0066700901); + result = mulAdd(result, x, -0.0170881256); + result = mulAdd(result, x, 0.0308918810); + result = mulAdd(result, x, -0.0501743046); + result = mulAdd(result, x, 0.0889789874); + result = mulAdd(result, x, -0.2145988016); + result = root * mulAdd(result, x, 1.5707963050); + + return if (v >= 0.0) 0.5 * math.pi - result else result - 0.5 * math.pi; +} +test "zmath.asin32" { + const epsilon = 0.0001; + + try expect(math.approxEqAbs(f32, asin(@as(f32, -1.1)), -0.5 * math.pi, epsilon)); + try expect(math.approxEqAbs(f32, asin(@as(f32, 1.1)), 0.5 * math.pi, epsilon)); + try expect(math.approxEqAbs(f32, asin(@as(f32, -1000.1)), -0.5 * math.pi, epsilon)); + try expect(math.approxEqAbs(f32, asin(@as(f32, 100000.1)), 0.5 * math.pi, epsilon)); + try expect(math.isNan(asin(math.inf(f32)))); + try expect(math.isNan(asin(-math.inf(f32)))); + try expect(math.isNan(asin(math.nan(f32)))); + try expect(math.isNan(asin(-math.nan(f32)))); + + try expect(approxEqAbs(asin(splat(F32x8, -100.0)), splat(F32x8, -0.5 * math.pi), epsilon)); + try expect(approxEqAbs(asin(splat(F32x16, 100.0)), splat(F32x16, 0.5 * math.pi), epsilon)); + try expect(all(isNan(asin(splat(F32x4, math.inf(f32)))), 0) == true); + try expect(all(isNan(asin(splat(F32x4, -math.inf(f32)))), 0) == true); + try expect(all(isNan(asin(splat(F32x4, math.nan(f32)))), 0) == true); + try expect(all(isNan(asin(splat(F32x4, math.nan(f32)))), 0) == true); + + var f: f32 = -1.0; + var i: u32 = 0; + while (i < 8) : (i += 1) { + const r0 = asin32(f); + const r1 = math.asin(f); + const r4 = asin(splat(F32x4, f)); + const r8 = asin(splat(F32x8, f)); + const r16 = asin(splat(F32x16, f)); + try expect(math.approxEqAbs(f32, r0, r1, epsilon)); + try expect(approxEqAbs(r4, splat(F32x4, r1), epsilon)); + try expect(approxEqAbs(r8, splat(F32x8, r1), epsilon)); + try expect(approxEqAbs(r16, splat(F32x16, r1), epsilon)); + f += 0.09 * @as(f32, @floatFromInt(i)); + } +} + +fn acos32(v: f32) f32 { + const x = @abs(v); + var omx = 1.0 - x; + if (omx < 0.0) { + omx = 0.0; + } + const root = @sqrt(omx); + + // 7-degree minimax approximation + var result = mulAdd(@as(f32, -0.0012624911), x, 0.0066700901); + result = mulAdd(result, x, -0.0170881256); + result = mulAdd(result, x, 0.0308918810); + result = mulAdd(result, x, -0.0501743046); + result = mulAdd(result, x, 0.0889789874); + result = mulAdd(result, x, -0.2145988016); + result = root * mulAdd(result, x, 1.5707963050); + + return if (v >= 0.0) result else math.pi - result; +} +test "zmath.acos32" { + const epsilon = 0.1; + + try expect(math.approxEqAbs(f32, acos(@as(f32, -1.1)), math.pi, epsilon)); + try expect(math.approxEqAbs(f32, acos(@as(f32, -10000.1)), math.pi, epsilon)); + try expect(math.approxEqAbs(f32, acos(@as(f32, 1.1)), 0.0, epsilon)); + try expect(math.approxEqAbs(f32, acos(@as(f32, 1000.1)), 0.0, epsilon)); + try expect(math.isNan(acos(math.inf(f32)))); + try expect(math.isNan(acos(-math.inf(f32)))); + try expect(math.isNan(acos(math.nan(f32)))); + try expect(math.isNan(acos(-math.nan(f32)))); + + try expect(approxEqAbs(acos(splat(F32x8, -100.0)), splat(F32x8, math.pi), epsilon)); + try expect(approxEqAbs(acos(splat(F32x16, 100.0)), splat(F32x16, 0.0), epsilon)); + try expect(all(isNan(acos(splat(F32x4, math.inf(f32)))), 0) == true); + try expect(all(isNan(acos(splat(F32x4, -math.inf(f32)))), 0) == true); + try expect(all(isNan(acos(splat(F32x4, math.nan(f32)))), 0) == true); + try expect(all(isNan(acos(splat(F32x4, math.nan(f32)))), 0) == true); + + var f: f32 = -1.0; + var i: u32 = 0; + while (i < 8) : (i += 1) { + const r0 = acos32(f); + const r1 = math.acos(f); + const r4 = acos(splat(F32x4, f)); + const r8 = acos(splat(F32x8, f)); + const r16 = acos(splat(F32x16, f)); + try expect(math.approxEqAbs(f32, r0, r1, epsilon)); + try expect(approxEqAbs(r4, splat(F32x4, r1), epsilon)); + try expect(approxEqAbs(r8, splat(F32x8, r1), epsilon)); + try expect(approxEqAbs(r16, splat(F32x16, r1), epsilon)); + f += 0.09 * @as(f32, @floatFromInt(i)); + } +} + +pub fn modAngle32(in_angle: f32) f32 { + const angle = in_angle + math.pi; + var temp: f32 = @abs(angle); + temp = temp - (2.0 * math.pi * @as(f32, @floatFromInt(@as(i32, @intFromFloat(temp / math.pi))))); + temp = temp - math.pi; + if (angle < 0.0) { + temp = -temp; + } + return temp; +} + +pub fn cmulSoa(re0: anytype, im0: anytype, re1: anytype, im1: anytype) [2]@TypeOf(re0, im0, re1, im1) { + const re0_re1 = re0 * re1; + const re0_im1 = re0 * im1; + return .{ + mulAdd(-im0, im1, re0_re1), // re + mulAdd(re1, im0, re0_im1), // im + }; +} +// ------------------------------------------------------------------------------ +// +// FFT (implementation based on xdsp.h from DirectXMath) +// +// ------------------------------------------------------------------------------ +fn fftButterflyDit4_1(re0: *F32x4, im0: *F32x4) void { + const re0l = swizzle(re0.*, .x, .x, .y, .y); + const re0h = swizzle(re0.*, .z, .z, .w, .w); + + const im0l = swizzle(im0.*, .x, .x, .y, .y); + const im0h = swizzle(im0.*, .z, .z, .w, .w); + + const re_temp = mulAdd(re0h, f32x4(1.0, -1.0, 1.0, -1.0), re0l); + const im_temp = mulAdd(im0h, f32x4(1.0, -1.0, 1.0, -1.0), im0l); + + const re_shuf0 = @shuffle(f32, re_temp, im_temp, [4]i32{ 2, 3, ~@as(i32, 2), ~@as(i32, 3) }); + const re_shuf = swizzle(re_shuf0, .x, .w, .x, .w); + const im_shuf = swizzle(re_shuf0, .z, .y, .z, .y); + + const re_templ = swizzle(re_temp, .x, .y, .x, .y); + const im_templ = swizzle(im_temp, .x, .y, .x, .y); + + re0.* = mulAdd(re_shuf, f32x4(1.0, 1.0, -1.0, -1.0), re_templ); + im0.* = mulAdd(im_shuf, f32x4(1.0, -1.0, -1.0, 1.0), im_templ); +} + +fn fftButterflyDit4_4( + re0: *F32x4, + re1: *F32x4, + re2: *F32x4, + re3: *F32x4, + im0: *F32x4, + im1: *F32x4, + im2: *F32x4, + im3: *F32x4, + unity_table_re: []const F32x4, + unity_table_im: []const F32x4, + stride: u32, + last: bool, +) void { + const re_temp0 = re0.* + re2.*; + const im_temp0 = im0.* + im2.*; + + const re_temp2 = re1.* + re3.*; + const im_temp2 = im1.* + im3.*; + + const re_temp1 = re0.* - re2.*; + const im_temp1 = im0.* - im2.*; + + const re_temp3 = re1.* - re3.*; + const im_temp3 = im1.* - im3.*; + + var re_temp4 = re_temp0 + re_temp2; + var im_temp4 = im_temp0 + im_temp2; + + var re_temp5 = re_temp1 + im_temp3; + var im_temp5 = im_temp1 - re_temp3; + + var re_temp6 = re_temp0 - re_temp2; + var im_temp6 = im_temp0 - im_temp2; + + var re_temp7 = re_temp1 - im_temp3; + var im_temp7 = im_temp1 + re_temp3; + + { + const re_im = cmulSoa(re_temp5, im_temp5, unity_table_re[stride], unity_table_im[stride]); + re_temp5 = re_im[0]; + im_temp5 = re_im[1]; + } + { + const re_im = cmulSoa(re_temp6, im_temp6, unity_table_re[stride * 2], unity_table_im[stride * 2]); + re_temp6 = re_im[0]; + im_temp6 = re_im[1]; + } + { + const re_im = cmulSoa(re_temp7, im_temp7, unity_table_re[stride * 3], unity_table_im[stride * 3]); + re_temp7 = re_im[0]; + im_temp7 = re_im[1]; + } + + if (last) { + fftButterflyDit4_1(&re_temp4, &im_temp4); + fftButterflyDit4_1(&re_temp5, &im_temp5); + fftButterflyDit4_1(&re_temp6, &im_temp6); + fftButterflyDit4_1(&re_temp7, &im_temp7); + } + + re0.* = re_temp4; + im0.* = im_temp4; + + re1.* = re_temp5; + im1.* = im_temp5; + + re2.* = re_temp6; + im2.* = im_temp6; + + re3.* = re_temp7; + im3.* = im_temp7; +} + +fn fft4(re: []F32x4, im: []F32x4, count: u32) void { + assert(std.math.isPowerOfTwo(count)); + assert(re.len >= count); + assert(im.len >= count); + + var index: u32 = 0; + while (index < count) : (index += 1) { + fftButterflyDit4_1(&re[index], &im[index]); + } +} +test "zmath.fft4" { + const epsilon = 0.0001; + var re = [_]F32x4{f32x4(1.0, 2.0, 3.0, 4.0)}; + var im = [_]F32x4{f32x4s(0.0)}; + fft4(re[0..], im[0..], 1); + + var re_uns: [1]F32x4 = undefined; + var im_uns: [1]F32x4 = undefined; + fftUnswizzle(re[0..], re_uns[0..]); + fftUnswizzle(im[0..], im_uns[0..]); + + try expect(approxEqAbs(re_uns[0], f32x4(10.0, -2.0, -2.0, -2.0), epsilon)); + try expect(approxEqAbs(im_uns[0], f32x4(0.0, 2.0, 0.0, -2.0), epsilon)); +} + +fn fft8(re: []F32x4, im: []F32x4, count: u32) void { + assert(std.math.isPowerOfTwo(count)); + assert(re.len >= 2 * count); + assert(im.len >= 2 * count); + + var index: u32 = 0; + while (index < count) : (index += 1) { + var pre = re[index * 2 ..]; + var pim = im[index * 2 ..]; + + var odds_re = @shuffle(f32, pre[0], pre[1], [4]i32{ 1, 3, ~@as(i32, 1), ~@as(i32, 3) }); + var evens_re = @shuffle(f32, pre[0], pre[1], [4]i32{ 0, 2, ~@as(i32, 0), ~@as(i32, 2) }); + var odds_im = @shuffle(f32, pim[0], pim[1], [4]i32{ 1, 3, ~@as(i32, 1), ~@as(i32, 3) }); + var evens_im = @shuffle(f32, pim[0], pim[1], [4]i32{ 0, 2, ~@as(i32, 0), ~@as(i32, 2) }); + fftButterflyDit4_1(&odds_re, &odds_im); + fftButterflyDit4_1(&evens_re, &evens_im); + + { + const re_im = cmulSoa( + odds_re, + odds_im, + f32x4(1.0, 0.70710677, 0.0, -0.70710677), + f32x4(0.0, -0.70710677, -1.0, -0.70710677), + ); + pre[0] = evens_re + re_im[0]; + pim[0] = evens_im + re_im[1]; + } + { + const re_im = cmulSoa( + odds_re, + odds_im, + f32x4(-1.0, -0.70710677, 0.0, 0.70710677), + f32x4(0.0, 0.70710677, 1.0, 0.70710677), + ); + pre[1] = evens_re + re_im[0]; + pim[1] = evens_im + re_im[1]; + } + } +} +test "zmath.fft8" { + const epsilon = 0.0001; + var re = [_]F32x4{ f32x4(1.0, 2.0, 3.0, 4.0), f32x4(5.0, 6.0, 7.0, 8.0) }; + var im = [_]F32x4{ f32x4s(0.0), f32x4s(0.0) }; + fft8(re[0..], im[0..], 1); + + var re_uns: [2]F32x4 = undefined; + var im_uns: [2]F32x4 = undefined; + fftUnswizzle(re[0..], re_uns[0..]); + fftUnswizzle(im[0..], im_uns[0..]); + + try expect(approxEqAbs(re_uns[0], f32x4(36.0, -4.0, -4.0, -4.0), epsilon)); + try expect(approxEqAbs(re_uns[1], f32x4(-4.0, -4.0, -4.0, -4.0), epsilon)); + try expect(approxEqAbs(im_uns[0], f32x4(0.0, 9.656854, 4.0, 1.656854), epsilon)); + try expect(approxEqAbs(im_uns[1], f32x4(0.0, -1.656854, -4.0, -9.656854), epsilon)); +} + +fn fft16(re: []F32x4, im: []F32x4, count: u32) void { + assert(std.math.isPowerOfTwo(count)); + assert(re.len >= 4 * count); + assert(im.len >= 4 * count); + + const static = struct { + const unity_table_re = [4]F32x4{ + f32x4(1.0, 1.0, 1.0, 1.0), + f32x4(1.0, 0.92387950, 0.70710677, 0.38268343), + f32x4(1.0, 0.70710677, -4.3711388e-008, -0.70710677), + f32x4(1.0, 0.38268343, -0.70710677, -0.92387950), + }; + const unity_table_im = [4]F32x4{ + f32x4(-0.0, -0.0, -0.0, -0.0), + f32x4(-0.0, -0.38268343, -0.70710677, -0.92387950), + f32x4(-0.0, -0.70710677, -1.0, -0.70710677), + f32x4(-0.0, -0.92387950, -0.70710677, 0.38268343), + }; + }; + + var index: u32 = 0; + while (index < count) : (index += 1) { + fftButterflyDit4_4( + &re[index * 4], + &re[index * 4 + 1], + &re[index * 4 + 2], + &re[index * 4 + 3], + &im[index * 4], + &im[index * 4 + 1], + &im[index * 4 + 2], + &im[index * 4 + 3], + static.unity_table_re[0..], + static.unity_table_im[0..], + 1, + true, + ); + } +} +test "zmath.fft16" { + const epsilon = 0.0001; + var re = [_]F32x4{ + f32x4(1.0, 2.0, 3.0, 4.0), + f32x4(5.0, 6.0, 7.0, 8.0), + f32x4(9.0, 10.0, 11.0, 12.0), + f32x4(13.0, 14.0, 15.0, 16.0), + }; + var im = [_]F32x4{ f32x4s(0.0), f32x4s(0.0), f32x4s(0.0), f32x4s(0.0) }; + fft16(re[0..], im[0..], 1); + + var re_uns: [4]F32x4 = undefined; + var im_uns: [4]F32x4 = undefined; + fftUnswizzle(re[0..], re_uns[0..]); + fftUnswizzle(im[0..], im_uns[0..]); + + try expect(approxEqAbs(re_uns[0], f32x4(136.0, -8.0, -8.0, -8.0), epsilon)); + try expect(approxEqAbs(re_uns[1], f32x4(-8.0, -8.0, -8.0, -8.0), epsilon)); + try expect(approxEqAbs(re_uns[2], f32x4(-8.0, -8.0, -8.0, -8.0), epsilon)); + try expect(approxEqAbs(re_uns[3], f32x4(-8.0, -8.0, -8.0, -8.0), epsilon)); + try expect(approxEqAbs(im_uns[0], f32x4(0.0, 40.218716, 19.313708, 11.972846), epsilon)); + try expect(approxEqAbs(im_uns[1], f32x4(8.0, 5.345429, 3.313708, 1.591299), epsilon)); + try expect(approxEqAbs(im_uns[2], f32x4(0.0, -1.591299, -3.313708, -5.345429), epsilon)); + try expect(approxEqAbs(im_uns[3], f32x4(-8.0, -11.972846, -19.313708, -40.218716), epsilon)); +} + +fn fftN(re: []F32x4, im: []F32x4, unity_table: []const F32x4, length: u32, count: u32) void { + assert(length > 16); + assert(std.math.isPowerOfTwo(length)); + assert(std.math.isPowerOfTwo(count)); + assert(re.len >= length * count / 4); + assert(re.len == im.len); + + const total = count * length; + const total_vectors = total / 4; + const stage_vectors = length / 4; + const stage_vectors_mask = stage_vectors - 1; + const stride = length / 16; + const stride_mask = stride - 1; + const stride_inv_mask = ~stride_mask; + + var unity_table_re = unity_table; + var unity_table_im = unity_table[length / 4 ..]; + + var index: u32 = 0; + while (index < total_vectors / 4) : (index += 1) { + const n = (index & stride_inv_mask) * 4 + (index & stride_mask); + fftButterflyDit4_4( + &re[n], + &re[n + stride], + &re[n + stride * 2], + &re[n + stride * 3], + &im[n], + &im[n + stride], + &im[n + stride * 2], + &im[n + stride * 3], + unity_table_re[(n & stage_vectors_mask)..], + unity_table_im[(n & stage_vectors_mask)..], + stride, + false, + ); + } + + if (length > 16 * 4) { + fftN(re, im, unity_table[(length / 2)..], length / 4, count * 4); + } else if (length == 16 * 4) { + fft16(re, im, count * 4); + } else if (length == 8 * 4) { + fft8(re, im, count * 4); + } else if (length == 4 * 4) { + fft4(re, im, count * 4); + } +} + +fn f32x4Lane(v: F32x4, lane: usize) f32 { + return switch (lane) { + 0 => v[0], + 1 => v[1], + 2 => v[2], + 3 => v[3], + else => unreachable, + }; +} + +test "zmath.fftN" { + var unity_table: [128]F32x4 = undefined; + const epsilon = 0.0001; + + // 32 samples + { + var re = [_]F32x4{ + f32x4(1.0, 2.0, 3.0, 4.0), f32x4(5.0, 6.0, 7.0, 8.0), + f32x4(9.0, 10.0, 11.0, 12.0), f32x4(13.0, 14.0, 15.0, 16.0), + f32x4(17.0, 18.0, 19.0, 20.0), f32x4(21.0, 22.0, 23.0, 24.0), + f32x4(25.0, 26.0, 27.0, 28.0), f32x4(29.0, 30.0, 31.0, 32.0), + }; + var im = [_]F32x4{ + f32x4s(0.0), f32x4s(0.0), f32x4s(0.0), f32x4s(0.0), + f32x4s(0.0), f32x4s(0.0), f32x4s(0.0), f32x4s(0.0), + }; + + fftInitUnityTable(unity_table[0..32]); + fft(re[0..], im[0..], unity_table[0..32]); + + try expect(approxEqAbs(re[0], f32x4(528.0, -16.0, -16.0, -16.0), epsilon)); + try expect(approxEqAbs(re[1], f32x4(-16.0, -16.0, -16.0, -16.0), epsilon)); + try expect(approxEqAbs(re[2], f32x4(-16.0, -16.0, -16.0, -16.0), epsilon)); + try expect(approxEqAbs(re[3], f32x4(-16.0, -16.0, -16.0, -16.0), epsilon)); + try expect(approxEqAbs(re[4], f32x4(-16.0, -16.0, -16.0, -16.0), epsilon)); + try expect(approxEqAbs(re[5], f32x4(-16.0, -16.0, -16.0, -16.0), epsilon)); + try expect(approxEqAbs(re[6], f32x4(-16.0, -16.0, -16.0, -16.0), epsilon)); + try expect(approxEqAbs(re[7], f32x4(-16.0, -16.0, -16.0, -16.0), epsilon)); + try expect(approxEqAbs(im[0], f32x4(0.0, 162.450726, 80.437432, 52.744931), epsilon)); + try expect(approxEqAbs(im[1], f32x4(38.627417, 29.933895, 23.945692, 19.496056), epsilon)); + try expect(approxEqAbs(im[2], f32x4(16.0, 13.130861, 10.690858, 8.552178), epsilon)); + try expect(approxEqAbs(im[3], f32x4(6.627417, 4.853547, 3.182598, 1.575862), epsilon)); + try expect(approxEqAbs(im[4], f32x4(0.0, -1.575862, -3.182598, -4.853547), epsilon)); + try expect(approxEqAbs(im[5], f32x4(-6.627417, -8.552178, -10.690858, -13.130861), epsilon)); + try expect(approxEqAbs(im[6], f32x4(-16.0, -19.496056, -23.945692, -29.933895), epsilon)); + try expect(approxEqAbs(im[7], f32x4(-38.627417, -52.744931, -80.437432, -162.450726), epsilon)); + } + + // 64 samples + { + var re = [_]F32x4{ + f32x4(1.0, 2.0, 3.0, 4.0), f32x4(5.0, 6.0, 7.0, 8.0), + f32x4(9.0, 10.0, 11.0, 12.0), f32x4(13.0, 14.0, 15.0, 16.0), + f32x4(17.0, 18.0, 19.0, 20.0), f32x4(21.0, 22.0, 23.0, 24.0), + f32x4(25.0, 26.0, 27.0, 28.0), f32x4(29.0, 30.0, 31.0, 32.0), + f32x4(1.0, 2.0, 3.0, 4.0), f32x4(5.0, 6.0, 7.0, 8.0), + f32x4(9.0, 10.0, 11.0, 12.0), f32x4(13.0, 14.0, 15.0, 16.0), + f32x4(17.0, 18.0, 19.0, 20.0), f32x4(21.0, 22.0, 23.0, 24.0), + f32x4(25.0, 26.0, 27.0, 28.0), f32x4(29.0, 30.0, 31.0, 32.0), + }; + var im = [_]F32x4{ + f32x4s(0.0), f32x4s(0.0), f32x4s(0.0), f32x4s(0.0), + f32x4s(0.0), f32x4s(0.0), f32x4s(0.0), f32x4s(0.0), + f32x4s(0.0), f32x4s(0.0), f32x4s(0.0), f32x4s(0.0), + f32x4s(0.0), f32x4s(0.0), f32x4s(0.0), f32x4s(0.0), + }; + + fftInitUnityTable(unity_table[0..64]); + fft(re[0..], im[0..], unity_table[0..64]); + + try expect(approxEqAbs(re[0], f32x4(1056.0, 0.0, -32.0, 0.0), epsilon)); + var i: u32 = 1; + while (i < 16) : (i += 1) { + try expect(approxEqAbs(re[i], f32x4(-32.0, 0.0, -32.0, 0.0), epsilon)); + } + + const expected = [_]f32{ + 0.0, 0.0, 324.901452, 0.000000, 160.874864, 0.0, 105.489863, 0.000000, + 77.254834, 0.0, 59.867789, 0.0, 47.891384, 0.0, 38.992113, 0.0, + 32.000000, 0.000000, 26.261721, 0.000000, 21.381716, 0.000000, 17.104356, 0.000000, + 13.254834, 0.000000, 9.707094, 0.000000, 6.365196, 0.000000, 3.151725, 0.000000, + 0.000000, 0.000000, -3.151725, 0.000000, -6.365196, 0.000000, -9.707094, 0.000000, + -13.254834, 0.000000, -17.104356, 0.000000, -21.381716, 0.000000, -26.261721, 0.000000, + -32.000000, 0.000000, -38.992113, 0.000000, -47.891384, 0.000000, -59.867789, 0.000000, + -77.254834, 0.000000, -105.489863, 0.000000, -160.874864, 0.000000, -324.901452, 0.000000, + }; + for (expected, 0..) |e, ie| { + try expect(std.math.approxEqAbs(f32, e, f32x4Lane(im[(ie / 4)], ie % 4), epsilon)); + } + } + + // 128 samples + { + var re = [_]F32x4{ + f32x4(1.0, 2.0, 3.0, 4.0), f32x4(5.0, 6.0, 7.0, 8.0), + f32x4(9.0, 10.0, 11.0, 12.0), f32x4(13.0, 14.0, 15.0, 16.0), + f32x4(17.0, 18.0, 19.0, 20.0), f32x4(21.0, 22.0, 23.0, 24.0), + f32x4(25.0, 26.0, 27.0, 28.0), f32x4(29.0, 30.0, 31.0, 32.0), + f32x4(1.0, 2.0, 3.0, 4.0), f32x4(5.0, 6.0, 7.0, 8.0), + f32x4(9.0, 10.0, 11.0, 12.0), f32x4(13.0, 14.0, 15.0, 16.0), + f32x4(17.0, 18.0, 19.0, 20.0), f32x4(21.0, 22.0, 23.0, 24.0), + f32x4(25.0, 26.0, 27.0, 28.0), f32x4(29.0, 30.0, 31.0, 32.0), + f32x4(1.0, 2.0, 3.0, 4.0), f32x4(5.0, 6.0, 7.0, 8.0), + f32x4(9.0, 10.0, 11.0, 12.0), f32x4(13.0, 14.0, 15.0, 16.0), + f32x4(17.0, 18.0, 19.0, 20.0), f32x4(21.0, 22.0, 23.0, 24.0), + f32x4(25.0, 26.0, 27.0, 28.0), f32x4(29.0, 30.0, 31.0, 32.0), + f32x4(1.0, 2.0, 3.0, 4.0), f32x4(5.0, 6.0, 7.0, 8.0), + f32x4(9.0, 10.0, 11.0, 12.0), f32x4(13.0, 14.0, 15.0, 16.0), + f32x4(17.0, 18.0, 19.0, 20.0), f32x4(21.0, 22.0, 23.0, 24.0), + f32x4(25.0, 26.0, 27.0, 28.0), f32x4(29.0, 30.0, 31.0, 32.0), + }; + var im = [_]F32x4{ + f32x4s(0.0), f32x4s(0.0), f32x4s(0.0), f32x4s(0.0), + f32x4s(0.0), f32x4s(0.0), f32x4s(0.0), f32x4s(0.0), + f32x4s(0.0), f32x4s(0.0), f32x4s(0.0), f32x4s(0.0), + f32x4s(0.0), f32x4s(0.0), f32x4s(0.0), f32x4s(0.0), + f32x4s(0.0), f32x4s(0.0), f32x4s(0.0), f32x4s(0.0), + f32x4s(0.0), f32x4s(0.0), f32x4s(0.0), f32x4s(0.0), + f32x4s(0.0), f32x4s(0.0), f32x4s(0.0), f32x4s(0.0), + f32x4s(0.0), f32x4s(0.0), f32x4s(0.0), f32x4s(0.0), + }; + + fftInitUnityTable(unity_table[0..128]); + fft(re[0..], im[0..], unity_table[0..128]); + + try expect(approxEqAbs(re[0], f32x4(2112.0, 0.0, 0.0, 0.0), epsilon)); + var i: u32 = 1; + while (i < 32) : (i += 1) { + try expect(approxEqAbs(re[i], f32x4(-64.0, 0.0, 0.0, 0.0), epsilon)); + } + + const expected = [_]f32{ + 0.000000, 0.000000, 0.000000, 0.000000, 649.802905, 0.000000, 0.000000, 0.000000, + 321.749727, 0.000000, 0.000000, 0.000000, 210.979725, 0.000000, 0.000000, 0.000000, + 154.509668, 0.000000, 0.000000, 0.000000, 119.735578, 0.000000, 0.000000, 0.000000, + 95.782769, 0.000000, 0.000000, 0.000000, 77.984226, 0.000000, 0.000000, 0.000000, + 64.000000, 0.000000, 0.000000, 0.000000, 52.523443, 0.000000, 0.000000, 0.000000, + 42.763433, 0.000000, 0.000000, 0.000000, 34.208713, 0.000000, 0.000000, 0.000000, + 26.509668, 0.000000, 0.000000, 0.000000, 19.414188, 0.000000, 0.000000, 0.000000, + 12.730392, 0.000000, 0.000000, 0.000000, 6.303450, 0.000000, 0.000000, 0.000000, + 0.000000, 0.000000, 0.000000, 0.000000, -6.303450, 0.000000, 0.000000, 0.000000, + -12.730392, 0.000000, 0.000000, 0.000000, -19.414188, 0.000000, 0.000000, 0.000000, + -26.509668, 0.000000, 0.000000, 0.000000, -34.208713, 0.000000, 0.000000, 0.000000, + -42.763433, 0.000000, 0.000000, 0.000000, -52.523443, 0.000000, 0.000000, 0.000000, + -64.000000, 0.000000, 0.000000, 0.000000, -77.984226, 0.000000, 0.000000, 0.000000, + -95.782769, 0.000000, 0.000000, 0.000000, -119.735578, 0.000000, 0.000000, 0.000000, + -154.509668, 0.000000, 0.000000, 0.000000, -210.979725, 0.000000, 0.000000, 0.000000, + -321.749727, 0.000000, 0.000000, 0.000000, -649.802905, 0.000000, 0.000000, 0.000000, + }; + for (expected, 0..) |e, ie| { + try expect(std.math.approxEqAbs(f32, e, f32x4Lane(im[(ie / 4)], ie % 4), epsilon)); + } + } +} + +fn fftUnswizzle(input: []const F32x4, output: []F32x4) void { + assert(std.math.isPowerOfTwo(input.len)); + assert(input.len == output.len); + assert(input.ptr != output.ptr); + + const log2_length = std.math.log2_int(usize, input.len * 4); + assert(log2_length >= 2); + + const length = input.len; + + const f32_output = @as([*]f32, @ptrCast(output.ptr))[0 .. output.len * 4]; + + const static = struct { + const swizzle_table = [256]u8{ + 0x00, 0x40, 0x80, 0xC0, 0x10, 0x50, 0x90, 0xD0, 0x20, 0x60, 0xA0, 0xE0, 0x30, 0x70, 0xB0, 0xF0, + 0x04, 0x44, 0x84, 0xC4, 0x14, 0x54, 0x94, 0xD4, 0x24, 0x64, 0xA4, 0xE4, 0x34, 0x74, 0xB4, 0xF4, + 0x08, 0x48, 0x88, 0xC8, 0x18, 0x58, 0x98, 0xD8, 0x28, 0x68, 0xA8, 0xE8, 0x38, 0x78, 0xB8, 0xF8, + 0x0C, 0x4C, 0x8C, 0xCC, 0x1C, 0x5C, 0x9C, 0xDC, 0x2C, 0x6C, 0xAC, 0xEC, 0x3C, 0x7C, 0xBC, 0xFC, + 0x01, 0x41, 0x81, 0xC1, 0x11, 0x51, 0x91, 0xD1, 0x21, 0x61, 0xA1, 0xE1, 0x31, 0x71, 0xB1, 0xF1, + 0x05, 0x45, 0x85, 0xC5, 0x15, 0x55, 0x95, 0xD5, 0x25, 0x65, 0xA5, 0xE5, 0x35, 0x75, 0xB5, 0xF5, + 0x09, 0x49, 0x89, 0xC9, 0x19, 0x59, 0x99, 0xD9, 0x29, 0x69, 0xA9, 0xE9, 0x39, 0x79, 0xB9, 0xF9, + 0x0D, 0x4D, 0x8D, 0xCD, 0x1D, 0x5D, 0x9D, 0xDD, 0x2D, 0x6D, 0xAD, 0xED, 0x3D, 0x7D, 0xBD, 0xFD, + 0x02, 0x42, 0x82, 0xC2, 0x12, 0x52, 0x92, 0xD2, 0x22, 0x62, 0xA2, 0xE2, 0x32, 0x72, 0xB2, 0xF2, + 0x06, 0x46, 0x86, 0xC6, 0x16, 0x56, 0x96, 0xD6, 0x26, 0x66, 0xA6, 0xE6, 0x36, 0x76, 0xB6, 0xF6, + 0x0A, 0x4A, 0x8A, 0xCA, 0x1A, 0x5A, 0x9A, 0xDA, 0x2A, 0x6A, 0xAA, 0xEA, 0x3A, 0x7A, 0xBA, 0xFA, + 0x0E, 0x4E, 0x8E, 0xCE, 0x1E, 0x5E, 0x9E, 0xDE, 0x2E, 0x6E, 0xAE, 0xEE, 0x3E, 0x7E, 0xBE, 0xFE, + 0x03, 0x43, 0x83, 0xC3, 0x13, 0x53, 0x93, 0xD3, 0x23, 0x63, 0xA3, 0xE3, 0x33, 0x73, 0xB3, 0xF3, + 0x07, 0x47, 0x87, 0xC7, 0x17, 0x57, 0x97, 0xD7, 0x27, 0x67, 0xA7, 0xE7, 0x37, 0x77, 0xB7, 0xF7, + 0x0B, 0x4B, 0x8B, 0xCB, 0x1B, 0x5B, 0x9B, 0xDB, 0x2B, 0x6B, 0xAB, 0xEB, 0x3B, 0x7B, 0xBB, 0xFB, + 0x0F, 0x4F, 0x8F, 0xCF, 0x1F, 0x5F, 0x9F, 0xDF, 0x2F, 0x6F, 0xAF, 0xEF, 0x3F, 0x7F, 0xBF, 0xFF, + }; + }; + + if ((log2_length & 1) == 0) { + const rev32 = @as(u6, @intCast(32 - log2_length)); + var index: usize = 0; + while (index < length) : (index += 1) { + const n = index * 4; + const addr = + (@as(usize, @intCast(static.swizzle_table[n & 0xff])) << 24) | + (@as(usize, @intCast(static.swizzle_table[(n >> 8) & 0xff])) << 16) | + (@as(usize, @intCast(static.swizzle_table[(n >> 16) & 0xff])) << 8) | + @as(usize, @intCast(static.swizzle_table[(n >> 24) & 0xff])); + f32_output[addr >> rev32] = input[index][0]; + f32_output[(0x40000000 | addr) >> rev32] = input[index][1]; + f32_output[(0x80000000 | addr) >> rev32] = input[index][2]; + f32_output[(0xC0000000 | addr) >> rev32] = input[index][3]; + } + } else { + const rev7 = @as(usize, 1) << @as(u6, @intCast(log2_length - 3)); + const rev32 = @as(u6, @intCast(32 - (log2_length - 3))); + var index: usize = 0; + while (index < length) : (index += 1) { + const n = index / 2; + var addr = + (((@as(usize, @intCast(static.swizzle_table[n & 0xff])) << 24) | + (@as(usize, @intCast(static.swizzle_table[(n >> 8) & 0xff])) << 16) | + (@as(usize, @intCast(static.swizzle_table[(n >> 16) & 0xff])) << 8) | + (@as(usize, @intCast(static.swizzle_table[(n >> 24) & 0xff])))) >> rev32) | + ((index & 1) * rev7 * 4); + f32_output[addr] = input[index][0]; + addr += rev7; + f32_output[addr] = input[index][1]; + addr += rev7; + f32_output[addr] = input[index][2]; + addr += rev7; + f32_output[addr] = input[index][3]; + } + } +} + +pub fn fftInitUnityTable(out_unity_table: []F32x4) void { + assert(std.math.isPowerOfTwo(out_unity_table.len)); + assert(out_unity_table.len >= 32 and out_unity_table.len <= 512); + + var unity_table = out_unity_table; + + const v0123 = f32x4(0.0, 1.0, 2.0, 3.0); + var length = out_unity_table.len / 4; + var vlstep = f32x4s(0.5 * math.pi / @as(f32, @floatFromInt(length))); + + while (true) { + length /= 4; + var vjp = v0123; + + var j: u32 = 0; + while (j < length) : (j += 1) { + unity_table[j] = f32x4s(1.0); + unity_table[j + length * 4] = f32x4s(0.0); + + var vls = vjp * vlstep; + var sin_cos = sincos(vls); + unity_table[j + length] = sin_cos[1]; + unity_table[j + length * 5] = sin_cos[0] * f32x4s(-1.0); + + var vijp = vjp + vjp; + vls = vijp * vlstep; + sin_cos = sincos(vls); + unity_table[j + length * 2] = sin_cos[1]; + unity_table[j + length * 6] = sin_cos[0] * f32x4s(-1.0); + + vijp = vijp + vjp; + vls = vijp * vlstep; + sin_cos = sincos(vls); + unity_table[j + length * 3] = sin_cos[1]; + unity_table[j + length * 7] = sin_cos[0] * f32x4s(-1.0); + + vjp += f32x4s(4.0); + } + vlstep *= f32x4s(4.0); + unity_table = unity_table[8 * length ..]; + + if (length <= 4) + break; + } +} + +pub fn fft(re: []F32x4, im: []F32x4, unity_table: []const F32x4) void { + const length = @as(u32, @intCast(re.len * 4)); + assert(std.math.isPowerOfTwo(length)); + assert(length >= 4 and length <= 512); + assert(re.len == im.len); + + var re_temp_storage: [128]F32x4 = undefined; + var im_temp_storage: [128]F32x4 = undefined; + const re_temp = re_temp_storage[0..re.len]; + const im_temp = im_temp_storage[0..im.len]; + + std.mem.copyForwards(F32x4, re_temp, re); + std.mem.copyForwards(F32x4, im_temp, im); + + if (length > 16) { + assert(unity_table.len == length); + fftN(re_temp, im_temp, unity_table, length, 1); + } else if (length == 16) { + fft16(re_temp, im_temp, 1); + } else if (length == 8) { + fft8(re_temp, im_temp, 1); + } else if (length == 4) { + fft4(re_temp, im_temp, 1); + } + + fftUnswizzle(re_temp, re); + fftUnswizzle(im_temp, im); +} + +pub fn ifft(re: []F32x4, im: []const F32x4, unity_table: []const F32x4) void { + const length = @as(u32, @intCast(re.len * 4)); + assert(std.math.isPowerOfTwo(length)); + assert(length >= 4 and length <= 512); + assert(re.len == im.len); + + var re_temp_storage: [128]F32x4 = undefined; + var im_temp_storage: [128]F32x4 = undefined; + var re_temp = re_temp_storage[0..re.len]; + var im_temp = im_temp_storage[0..im.len]; + + const rnp = f32x4s(1.0 / @as(f32, @floatFromInt(length))); + const rnm = f32x4s(-1.0 / @as(f32, @floatFromInt(length))); + + for (re, 0..) |_, i| { + re_temp[i] = re[i] * rnp; + im_temp[i] = im[i] * rnm; + } + + if (length > 16) { + assert(unity_table.len == length); + fftN(re_temp, im_temp, unity_table, length, 1); + } else if (length == 16) { + fft16(re_temp, im_temp, 1); + } else if (length == 8) { + fft8(re_temp, im_temp, 1); + } else if (length == 4) { + fft4(re_temp, im_temp, 1); + } + + fftUnswizzle(re_temp, re); +} +test "zmath.ifft" { + var unity_table: [512]F32x4 = undefined; + const epsilon = 0.0001; + + // 64 samples + { + var re = [_]F32x4{ + f32x4(1.0, 2.0, 3.0, 4.0), f32x4(5.0, 6.0, 7.0, 8.0), + f32x4(9.0, 10.0, 11.0, 12.0), f32x4(13.0, 14.0, 15.0, 16.0), + f32x4(17.0, 18.0, 19.0, 20.0), f32x4(21.0, 22.0, 23.0, 24.0), + f32x4(25.0, 26.0, 27.0, 28.0), f32x4(29.0, 30.0, 31.0, 32.0), + f32x4(1.0, 2.0, 3.0, 4.0), f32x4(5.0, 6.0, 7.0, 8.0), + f32x4(9.0, 10.0, 11.0, 12.0), f32x4(13.0, 14.0, 15.0, 16.0), + f32x4(17.0, 18.0, 19.0, 20.0), f32x4(21.0, 22.0, 23.0, 24.0), + f32x4(25.0, 26.0, 27.0, 28.0), f32x4(29.0, 30.0, 31.0, 32.0), + }; + var im = [_]F32x4{ + f32x4s(0.0), f32x4s(0.0), f32x4s(0.0), f32x4s(0.0), + f32x4s(0.0), f32x4s(0.0), f32x4s(0.0), f32x4s(0.0), + f32x4s(0.0), f32x4s(0.0), f32x4s(0.0), f32x4s(0.0), + f32x4s(0.0), f32x4s(0.0), f32x4s(0.0), f32x4s(0.0), + }; + + fftInitUnityTable(unity_table[0..64]); + fft(re[0..], im[0..], unity_table[0..64]); + + try expect(approxEqAbs(re[0], f32x4(1056.0, 0.0, -32.0, 0.0), epsilon)); + var i: u32 = 1; + while (i < 16) : (i += 1) { + try expect(approxEqAbs(re[i], f32x4(-32.0, 0.0, -32.0, 0.0), epsilon)); + } + + ifft(re[0..], im[0..], unity_table[0..64]); + + try expect(approxEqAbs(re[0], f32x4(1.0, 2.0, 3.0, 4.0), epsilon)); + try expect(approxEqAbs(re[1], f32x4(5.0, 6.0, 7.0, 8.0), epsilon)); + try expect(approxEqAbs(re[2], f32x4(9.0, 10.0, 11.0, 12.0), epsilon)); + try expect(approxEqAbs(re[3], f32x4(13.0, 14.0, 15.0, 16.0), epsilon)); + try expect(approxEqAbs(re[4], f32x4(17.0, 18.0, 19.0, 20.0), epsilon)); + try expect(approxEqAbs(re[5], f32x4(21.0, 22.0, 23.0, 24.0), epsilon)); + try expect(approxEqAbs(re[6], f32x4(25.0, 26.0, 27.0, 28.0), epsilon)); + try expect(approxEqAbs(re[7], f32x4(29.0, 30.0, 31.0, 32.0), epsilon)); + } + + // 512 samples + { + var re: [128]F32x4 = undefined; + var im = [_]F32x4{f32x4s(0.0)} ** 128; + + for (&re, 0..) |*v, i| { + const f = @as(f32, @floatFromInt(i * 4)); + v.* = f32x4(f + 1.0, f + 2.0, f + 3.0, f + 4.0); + } + + fftInitUnityTable(unity_table[0..512]); + fft(re[0..], im[0..], unity_table[0..512]); + + for (re, 0..) |v, i| { + const f = @as(f32, @floatFromInt(i * 4)); + try expect(!approxEqAbs(v, f32x4(f + 1.0, f + 2.0, f + 3.0, f + 4.0), epsilon)); + } + + ifft(re[0..], im[0..], unity_table[0..512]); + + for (re, 0..) |v, i| { + const f = @as(f32, @floatFromInt(i * 4)); + try expect(approxEqAbs(v, f32x4(f + 1.0, f + 2.0, f + 3.0, f + 4.0), epsilon)); + } + } +} +// ------------------------------------------------------------------------------ +// +// Private functions and constants +// +// ------------------------------------------------------------------------------ +const f32x4_sign_mask1: F32x4 = F32x4{ @as(f32, @bitCast(@as(u32, 0x8000_0000))), 0, 0, 0 }; +const f32x4_mask2: F32x4 = F32x4{ + @as(f32, @bitCast(@as(u32, 0xffff_ffff))), + @as(f32, @bitCast(@as(u32, 0xffff_ffff))), + 0, + 0, +}; +const f32x4_mask3: F32x4 = F32x4{ + @as(f32, @bitCast(@as(u32, 0xffff_ffff))), + @as(f32, @bitCast(@as(u32, 0xffff_ffff))), + @as(f32, @bitCast(@as(u32, 0xffff_ffff))), + 0, +}; + +inline fn splatNegativeZero(comptime T: type) T { + return @splat(@as(f32, @bitCast(@as(u32, 0x8000_0000)))); +} +inline fn splatNoFraction(comptime T: type) T { + return @splat(@as(f32, 8_388_608.0)); +} +inline fn splatAbsMask(comptime T: type) T { + return @splat(@as(f32, @bitCast(@as(u32, 0x7fff_ffff)))); +} + +fn floatToIntAndBack(v: anytype) @TypeOf(v) { + // This routine won't handle nan, inf and numbers greater than 8_388_608.0 (will generate undefined values). + @setRuntimeSafety(false); + + const T = @TypeOf(v); + const len = veclen(T); + + var vi32: [len]i32 = undefined; + comptime var i: u32 = 0; + // vcvttps2dq + inline while (i < len) : (i += 1) { + vi32[i] = @as(i32, @intFromFloat(v[i])); + } + + var vf32: [len]f32 = undefined; + i = 0; + // vcvtdq2ps + inline while (i < len) : (i += 1) { + vf32[i] = @as(f32, @floatFromInt(vi32[i])); + } + + return vf32; +} +test "zmath.floatToIntAndBack" { + { + const v = floatToIntAndBack(f32x4(1.1, 2.9, 3.0, -4.5)); + try expect(approxEqAbs(v, f32x4(1.0, 2.0, 3.0, -4.0), 0.0)); + } + { + const v = floatToIntAndBack(f32x8(1.1, 2.9, 3.0, -4.5, 2.5, -2.5, 1.1, -100.2)); + try expect(approxEqAbs(v, f32x8(1.0, 2.0, 3.0, -4.0, 2.0, -2.0, 1.0, -100.0), 0.0)); + } + { + const v = floatToIntAndBack(f32x4(math.inf(f32), 2.9, math.nan(f32), math.nan(f32))); + try expect(v[1] == 2.0); + } +} + +pub fn approxEqAbs(v0: anytype, v1: anytype, eps: f32) bool { + const T = @TypeOf(v0, v1); + comptime var i: comptime_int = 0; + inline while (i < veclen(T)) : (i += 1) { + if (!math.approxEqAbs(f32, v0[i], v1[i], eps)) { + return false; + } + } + return true; +} + +// ------------------------------------------------------------------------------ +// This software is available under 2 licenses -- choose whichever you prefer. +// ------------------------------------------------------------------------------ +// ALTERNATIVE A - MIT License +// Copyright (c) 2022 Michal Ziulek +// Permission is hereby granted, free of charge, to any person obtaining a copy of +// this software and associated documentation files (the "Software"), to deal in +// the Software without restriction, including without limitation the rights to +// use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies +// of the Software, and to permit persons to whom the Software is furnished to do +// so, subject to the following conditions: +// The above copyright notice and this permission notice shall be included in all +// copies or substantial portions of the Software. +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +// SOFTWARE. +// ------------------------------------------------------------------------------ +// ALTERNATIVE B - Public Domain (www.unlicense.org) +// This is free and unencumbered software released into the public domain. +// Anyone is free to copy, modify, publish, use, compile, sell, or distribute this +// software, either in source code form or as a compiled binary, for any purpose, +// commercial or non-commercial, and by any means. +// In jurisdictions that recognize copyright laws, the author or authors of this +// software dedicate any and all copyright interest in the software to the public +// domain. We make this dedication for the benefit of the public at large and to +// the detriment of our heirs and successors. We intend this dedication to be an +// overt act of relinquishment in perpetuity of all present and future rights to +// this software under copyright law. +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +// AUTHORS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN +// ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION +// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. +// ------------------------------------------------------------------------------ diff --git a/engine/p2/src/utils/shell.zig b/engine/p2/src/utils/shell.zig new file mode 100644 index 0000000..1c7637b --- /dev/null +++ b/engine/p2/src/utils/shell.zig @@ -0,0 +1,117 @@ +const std = @import("std"); +const p2 = @import("../p2.zig"); + +pub const ShellProcess = struct { + backingAllocator: std.mem.Allocator, + + argv: []const []const u8 = undefined, + ownedArgs: ?[][]u8 = null, + stringArena: p2.BumpArena = undefined, + + // initialize the shellprocess from a windows cmd string + pub fn initCmd(alloc: std.mem.Allocator, io: std.Io, cmd: []const u8) !*@This() { + const self = try alloc.create(@This()); + self.* = .{ + .backingAllocator = alloc, + .stringArena = try p2.BumpArena.init(alloc, io), + }; + + try self.splitArgsFromCmd(cmd); + + return self; + } + + pub fn init(alloc: std.mem.Allocator, io: std.Io, argv: []const []const u8) !*@This() { + const self = try alloc.create(@This()); + self.* = .{ + .backingAllocator = alloc, + .stringArena = try p2.BumpArena.init(alloc, io), + }; + + try self.setArgsOwned(argv); + + return self; + } + + pub fn allocator(self: *@This()) std.mem.Allocator { + return self.stringArena.allocator(); + } + + pub fn splitArgsFromCmd(self: *@This(), cmd: []const u8) !void { + var currentCmd = std.ArrayList(u8).empty; + var ownedArgs = std.ArrayList([]u8).empty; + var terminalStack = std.ArrayList(u8).empty; + defer terminalStack.deinit(self.backingAllocator); + + for (cmd) |c| { + if (terminalStack.items.len == 0) { + if (c == ' ') { + try ownedArgs.append(self.allocator(), try currentCmd.toOwnedSlice(self.allocator())); + } else if (c == '\'' or c == '\"') { + try terminalStack.append(self.backingAllocator, c); + try currentCmd.append(self.allocator(), c); + } else { + try currentCmd.append(self.allocator(), c); + } + } else { + if (terminalStack.items[terminalStack.items.len - 1] == c) { + try currentCmd.append(self.allocator(), terminalStack.pop().?); + } else { + try currentCmd.append(self.allocator(), c); + } + } + } + + try ownedArgs.append(self.allocator(), try currentCmd.toOwnedSlice(self.allocator())); + + self.ownedArgs = try ownedArgs.toOwnedSlice(self.allocator()); + self.argv = @ptrCast(self.ownedArgs.?); + } + + pub fn setArgsOwned(self: *@This(), args: []const []const u8) !void { + self.ownedArgs = try self.allocator().alloc([]u8, args.len); + + for (args, 0..) |s, i| { + self.ownedArgs.?[i] = try self.allocator().dupe(u8, s); + } + + self.argv = @ptrCast(self.ownedArgs.?); + } + + pub fn deinit(self: *@This()) void { + self.stringArena.deinit(); + self.backingAllocator.destroy(self); + } +}; + +// TODO this is really bad +pub fn runCmd(allocator: std.mem.Allocator, io: std.Io, cmd: []const []const u8, cwd: []const u8) ![]u8 { + const result = try std.process.run(allocator, io, .{ + .argv = cmd, + .cwd = .{ .path = p2.getFolder(cwd) }, + .stdout_limit = .limited(150 * 1024 * 1024), + .stderr_limit = .limited(150 * 1024 * 1024), + }); + + defer allocator.free(result.stderr); + + switch (result.term) { + .exited => |code| { + if (code == 0) { + std.debug.print("runCmd stdout: {s}\n", .{result.stdout}); + return result.stdout; + } else { + defer allocator.free(result.stdout); + std.debug.print("runCmd stdout: {s}\n", .{result.stdout}); + std.debug.print("stderr: {s}\n", .{result.stderr}); + return error.NonZeroExitCode; + } + }, + else => { + allocator.free(result.stdout); + return error.Terminated; + }, + } + + return result.stdout; +} diff --git a/engine/p2/src/utils/xxd.zig b/engine/p2/src/utils/xxd.zig new file mode 100644 index 0000000..4f24f61 --- /dev/null +++ b/engine/p2/src/utils/xxd.zig @@ -0,0 +1,102 @@ +const std = @import("std"); + +const Endian = enum { + big, + little, +}; + +pub const XxdOptions = struct { + wordSize: u32 = 8, // in bits + endian: Endian = .little, + wordsPerGroup: u32 = 2, // in number of words + groupsPerLine: u32 = 8, // number of bytes per word + groupSplit: u32 = 4, // insert a double space every x number of + showAddress: bool = true, +}; + +pub fn xxdWrite( + writer: anytype, + bytes: []const u8, + options: XxdOptions, +) !void { + var wordBuffer: [16]u8 = undefined; + var wordOffset: usize = 0; + + const bytesPerWord = options.wordSize / 8; + + var wordInGroup: usize = 0; + var groupInLine: usize = 0; + + for (bytes, 0..) |byte, index| { + if (wordInGroup == options.wordsPerGroup) { + if ((groupInLine + 1) % options.groupSplit == 0 and wordInGroup == options.wordsPerGroup) { + try writer.writeByte(' '); + } + + try writer.writeByte(' '); + + wordInGroup = 0; + groupInLine += 1; + + if (groupInLine == options.groupsPerLine) { + try writer.writeByte('\n'); + groupInLine = 0; + } + } + + if (options.showAddress) { + if (wordInGroup == 0 and wordOffset == 0 and groupInLine == 0) { + try writer.print("{x:6.0}: ", .{index}); + } + } + + wordBuffer[wordOffset] = byte; + wordOffset += 1; + if (wordOffset == bytesPerWord) { + // write out the word into the reader according to endian + var wordOffsetIndex: usize = 0; + while (wordOffsetIndex < bytesPerWord) : (wordOffsetIndex += 1) { + const wordByte = if (options.endian == .little) + wordBuffer[wordOffsetIndex] + else + wordBuffer[bytesPerWord - 1 - wordOffsetIndex]; + + try writeByteAsHex(wordByte, writer); + } + wordOffset = 0; + } + + wordInGroup += 1; + } + + _ = try writer.write(".\n"); +} + +inline fn writeByteAsHex(byte: u8, writer: anytype) !void { + const hex = byteAsHex(byte); + try writer.writeByte(hex[1]); + try writer.writeByte(hex[0]); +} + +inline fn byteAsHex(byte: u8) [2]u8 { + var rv: [2]u8 = undefined; + rv[1] = nibbleAsHex(byte >> 4); + rv[0] = nibbleAsHex(byte & 0xF); + + return rv; +} + +fn nibbleAsHex(nib: u8) u8 { + if (nib < 10) + return '0' + nib; + return 'A' - 10 + nib; +} + +test "testing all" { + std.debug.print("\n", .{}); + const writer = std.io.getStdOut().writer(); + try writeByteAsHex(0x2f, writer); + std.debug.print("\n\n", .{}); + try xxdWrite(writer, &[_]u8{ 0xab, 0xf2, 0x21, 0x22, 0x43, 0x44, 0x12, 0x33, 0x12, 0x42, 0x22, 0xab, 0xf2, 0x21, 0x22, 0x43, 0x44, 0x12, 0x33, 0x12, 0x42, 0x22, 0xab, 0xf2, 0x21, 0x22, 0x43, 0x44, 0x12, 0x33, 0x12, 0x42, 0x22, 0xab, 0xf2, 0x21, 0x22, 0x43, 0x44, 0x12, 0x33, 0x12, 0x42, 0x22 }, .{}); + std.debug.print("\n", .{}); +} diff --git a/engine/p2/tools/vscode-env/README.md b/engine/p2/tools/vscode-env/README.md new file mode 100644 index 0000000..17ace13 --- /dev/null +++ b/engine/p2/tools/vscode-env/README.md @@ -0,0 +1,59 @@ +# P2 VS Code Environment + +This directory holds the repo-local definition for a pinned/custom VS Code setup. +It is meant to live under `lib/p2`, while installing generated launcher files at +the workspace root. + +## Layout + +- `extensions/`: put vendored `.vsix` files here. +- `settings/settings.json`: settings copied into the isolated VS Code user data. +- `install.sh`: installs the environment into the workspace root. + +## Install + +From `lib/p2`: + +```sh +./tools/vscode-env/install.sh +``` + +By default this creates: + +- `/.vscode-p2/` +- `/.bin/p2-code` +- `/.bin/p2-code.bat` +- `/p2.code-workspace` + +Run the environment with: + +```sh +/.bin/p2-code +``` + +The wrapper uses an isolated `--user-data-dir` and `--extensions-dir`, so custom +extensions do not affect your normal VS Code profile. + +On Windows, run: + +```bat +\.bin\p2-code.bat +``` + +## Vendored Extensions + +Drop custom or forked extensions into `extensions/` as `.vsix` files, then rerun +`install.sh`. The installer will install every `.vsix` it finds into the isolated +extension directory. + +For example: + +```sh +cp ~/dev/vscode-zig/ziglang.vscode-zig-0.6.18-custom.vsix tools/vscode-env/extensions/ +./tools/vscode-env/install.sh +``` + +Custom language extensions can live next to the tool they support, such as +`tools/riblang/vscode/`, and publish a packaged `.vsix` into this directory. +That keeps the source near the language implementation while keeping the editor +environment installer simple and pinned. diff --git a/engine/p2/tools/vscode-env/extensions/.gitkeep b/engine/p2/tools/vscode-env/extensions/.gitkeep new file mode 100644 index 0000000..8b13789 --- /dev/null +++ b/engine/p2/tools/vscode-env/extensions/.gitkeep @@ -0,0 +1 @@ + diff --git a/engine/p2/tools/vscode-env/install.bat b/engine/p2/tools/vscode-env/install.bat new file mode 100644 index 0000000..d94ac19 --- /dev/null +++ b/engine/p2/tools/vscode-env/install.bat @@ -0,0 +1,137 @@ +@echo off +setlocal EnableExtensions EnableDelayedExpansion + +set "SCRIPT_DIR=%~dp0" +if "%SCRIPT_DIR:~-1%"=="\" set "SCRIPT_DIR=%SCRIPT_DIR:~0,-1%" +for %%I in ("%SCRIPT_DIR%\..\..") do set "P2_DIR=%%~fI" + +set "WORKSPACE_ROOT=" +set "CODE_BIN=code" + +:parse_args +if "%~1"=="" goto after_args +if /I "%~1"=="--workspace-root" ( + if "%~2"=="" ( + echo missing value for --workspace-root 1>&2 + exit /b 2 + ) + set "WORKSPACE_ROOT=%~2" + shift + shift + goto parse_args +) +if /I "%~1"=="--code-bin" ( + if "%~2"=="" ( + echo missing value for --code-bin 1>&2 + exit /b 2 + ) + set "CODE_BIN=%~2" + shift + shift + goto parse_args +) +if /I "%~1"=="-h" goto usage +if /I "%~1"=="--help" goto usage + +echo unknown argument: %~1 1>&2 +goto usage_error + +:after_args +if "%WORKSPACE_ROOT%"=="" ( + for /f "usebackq delims=" %%I in (`git -C "%P2_DIR%" rev-parse --show-toplevel 2^>nul`) do set "WORKSPACE_ROOT=%%I" +) +if "%WORKSPACE_ROOT%"=="" set "WORKSPACE_ROOT=%P2_DIR%" +for %%I in ("%WORKSPACE_ROOT%") do set "WORKSPACE_ROOT=%%~fI" + +set "ENV_DIR=%WORKSPACE_ROOT%\.vscode-p2" +set "BIN_DIR=%WORKSPACE_ROOT%\.bin" +set "USER_DATA_DIR=%ENV_DIR%\user-data" +set "EXTENSIONS_DIR=%ENV_DIR%\extensions" +set "WORKSPACE_FILE=%WORKSPACE_ROOT%\p2.code-workspace" + +mkdir "%BIN_DIR%" 2>nul +mkdir "%USER_DATA_DIR%\User" 2>nul +mkdir "%EXTENSIONS_DIR%" 2>nul +copy /Y "%SCRIPT_DIR%\settings\settings.json" "%USER_DATA_DIR%\User\settings.json" >nul + +( + echo @echo off + echo setlocal + echo. + echo if "%%CODE_BIN%%"=="" ^( + echo set "CODE_BIN=%CODE_BIN%" + echo ^) + echo. + echo set "WORKSPACE_ROOT=%WORKSPACE_ROOT%" + echo set "ENV_DIR=%%WORKSPACE_ROOT%%\.vscode-p2" + echo. + echo "%%CODE_BIN%%" ^^ + echo --user-data-dir "%%ENV_DIR%%\user-data" ^^ + echo --extensions-dir "%%ENV_DIR%%\extensions" ^^ + echo "%%WORKSPACE_ROOT%%\p2.code-workspace" ^^ + echo %%* +) > "%BIN_DIR%\p2-code.bat" + +set "P2_REL=%P2_DIR%" +set "P2_REL=!P2_REL:%WORKSPACE_ROOT%=!" +if "!P2_REL:~0,1!"=="\" set "P2_REL=!P2_REL:~1!" +set "P2_REL=!P2_REL:\=/!" + +( + echo { + echo "folders": [ + echo { + echo "name": "snow", + echo "path": "." + echo }, + echo { + echo "name": "p2", + echo "path": "!P2_REL!" + echo } + echo ], + echo "settings": { + echo "editor.foldingStrategy": "auto" + echo } + echo } +) > "%WORKSPACE_FILE%" + +where "%CODE_BIN%" >nul 2>nul +if errorlevel 1 ( + echo VS Code binary not found: %CODE_BIN% 1>&2 + echo Skipping .vsix installation. Re-run with --code-bin PATH when available. 1>&2 +) else ( + set "FOUND_VSIX=0" + for %%F in ("%SCRIPT_DIR%\extensions\*.vsix") do ( + if exist "%%~fF" ( + set "FOUND_VSIX=1" + "%CODE_BIN%" --extensions-dir "%EXTENSIONS_DIR%" --install-extension "%%~fF" + ) + ) + if "!FOUND_VSIX!"=="0" echo No vendored .vsix files found in %SCRIPT_DIR%\extensions +) + +echo Installed P2 VS Code environment: +echo windows: %BIN_DIR%\p2-code.bat +echo workspace: %WORKSPACE_FILE% +echo user data: %USER_DATA_DIR% +echo extensions:%EXTENSIONS_DIR% +echo. +echo Run: +echo %BIN_DIR%\p2-code.bat +exit /b 0 + +:usage +echo Usage: install.bat [--workspace-root PATH] [--code-bin CODE] +echo. +echo Installs the P2 VS Code environment at the workspace root. +echo. +echo Options: +echo --workspace-root PATH Override the detected Git root. +echo --code-bin CODE VS Code binary to use for installing .vsix files. +echo -h, --help Show this help. +exit /b 0 + +:usage_error +call :usage +exit /b 2 + diff --git a/engine/p2/tools/vscode-env/install.sh b/engine/p2/tools/vscode-env/install.sh new file mode 100755 index 0000000..a69c8aa --- /dev/null +++ b/engine/p2/tools/vscode-env/install.sh @@ -0,0 +1,145 @@ +#!/usr/bin/env sh +set -eu + +usage() { + cat <<'EOF' +Usage: install.sh [--workspace-root PATH] [--code-bin CODE] + +Installs the P2 VS Code environment at the workspace root. + +Options: + --workspace-root PATH Override the detected Git root. + --code-bin CODE VS Code binary to use for installing .vsix files. + -h, --help Show this help. +EOF +} + +script_dir=$(CDPATH= cd -- "$(dirname -- "$0")" && pwd) +p2_dir=$(CDPATH= cd -- "$script_dir/../.." && pwd) +workspace_root= +code_bin=${CODE_BIN:-code} + +while [ "$#" -gt 0 ]; do + case "$1" in + --workspace-root) + [ "$#" -ge 2 ] || { + echo "missing value for --workspace-root" >&2 + exit 2 + } + workspace_root=$2 + shift 2 + ;; + --code-bin) + [ "$#" -ge 2 ] || { + echo "missing value for --code-bin" >&2 + exit 2 + } + code_bin=$2 + shift 2 + ;; + -h|--help) + usage + exit 0 + ;; + *) + echo "unknown argument: $1" >&2 + usage >&2 + exit 2 + ;; + esac +done + +if [ -z "$workspace_root" ]; then + workspace_root=$(git -C "$p2_dir" rev-parse --show-toplevel 2>/dev/null || printf '%s\n' "$p2_dir") +fi + +workspace_root=$(CDPATH= cd -- "$workspace_root" && pwd) +env_dir="$workspace_root/.vscode-p2" +bin_dir="$workspace_root/.bin" +user_data_dir="$env_dir/user-data" +extensions_dir="$env_dir/extensions" +workspace_file="$workspace_root/p2.code-workspace" + +mkdir -p "$bin_dir" "$user_data_dir/User" "$extensions_dir" +cp "$script_dir/settings/settings.json" "$user_data_dir/User/settings.json" + +cat > "$bin_dir/p2-code" < "$bin_dir/p2-code.bat" < "$workspace_file" </dev/null 2>&1; then + found_vsix=false + for vsix in "$script_dir"/extensions/*.vsix; do + [ -e "$vsix" ] || continue + found_vsix=true + "$code_bin" --extensions-dir "$extensions_dir" --install-extension "$vsix" + done + if [ "$found_vsix" = false ]; then + echo "No vendored .vsix files found in $script_dir/extensions" + fi +else + echo "VS Code binary not found: $code_bin" >&2 + echo "Skipping .vsix installation. Re-run with --code-bin PATH when available." >&2 +fi + +cat <