Unnamed: 0
int64 0
0
| repo_id
stringlengths 5
186
| file_path
stringlengths 15
223
| content
stringlengths 1
32.8M
⌀ |
---|---|---|---|
0 | repos/zig_vulkan/src/modules | repos/zig_vulkan/src/modules/voxel_rt/Benchmark.zig | /// This file contains logic to perform a simple benchmark report to test the renderer
const std = @import("std");
const za = @import("zalgebra");
const BrickState = @import("brick/State.zig");
const Camera = @import("Camera.zig");
const Context = @import("../render.zig").Context;
const Benchmark = @This();
brick_state: BrickState,
sun_enabled: bool,
camera: *Camera,
timer: f32,
path_point_fraction: f32,
path_orientation_fraction: f32,
report: Report,
/// You should probably use VoxelRT.createBenchmark ...
pub fn init(camera: *Camera, brick_state: BrickState, sun_enabled: bool) Benchmark {
const path_point_fraction = Configuration.benchmark_duration / @intToFloat(f32, Configuration.path_points.len);
const path_orientation_fraction = Configuration.benchmark_duration / @intToFloat(f32, Configuration.path_orientations.len);
// initialize camera state
camera.disableInput();
camera.d_camera.origin = Configuration.path_points[0].data;
// HACK: use yaw quat as orientation and ignore pitch
camera.yaw = Configuration.path_orientations[0];
camera.pitch = za.Quat.identity();
camera.propogatePitchChange();
return Benchmark{
.brick_state = brick_state,
.sun_enabled = sun_enabled,
.camera = camera,
.timer = 0,
.path_point_fraction = path_point_fraction,
.path_orientation_fraction = path_orientation_fraction,
.report = Report.init(brick_state),
};
}
/// Update benchmark and camera state, return true if benchmark has completed
pub fn update(self: *Benchmark, dt: f32) bool {
self.timer += dt;
const path_point_index = @floatToInt(usize, @divFloor(self.timer, self.path_point_fraction));
if (path_point_index < Configuration.path_points.len - 1) {
const path_point_lerp_pos = @rem(self.timer, self.path_point_fraction) / self.path_point_fraction;
const left = Configuration.path_points[path_point_index];
const right = Configuration.path_points[path_point_index + 1];
self.camera.d_camera.origin = left.lerp(right, path_point_lerp_pos).data;
}
const path_orientation_index = @floatToInt(usize, @divFloor(self.timer, self.path_orientation_fraction));
if (path_orientation_index < Configuration.path_orientations.len - 1) {
const path_orientation_lerp_pos = @rem(self.timer, self.path_orientation_fraction) / self.path_orientation_fraction;
const left = Configuration.path_orientations[path_orientation_index];
const right = Configuration.path_orientations[path_orientation_index + 1];
self.camera.yaw = left.lerp(right, path_orientation_lerp_pos);
self.camera.pitch = za.Quat.identity();
}
self.camera.propogatePitchChange();
self.report.min_delta_time = std.math.min(self.report.min_delta_time, dt);
self.report.max_delta_time = std.math.max(self.report.max_delta_time, dt);
self.report.delta_time_sum += dt;
self.report.delta_time_sum_samples += 1;
return self.timer >= Configuration.benchmark_duration;
}
pub fn printReport(self: Benchmark, device_name: []const u8) void {
self.report.print(device_name, self.camera.d_camera, self.sun_enabled);
}
pub const Report = struct {
const Vec3U = za.GenericVector(3, u32);
min_delta_time: f32,
max_delta_time: f32,
delta_time_sum: f32,
delta_time_sum_samples: u32,
brick_dim: Vec3U,
pub fn init(brick_state: BrickState) Report {
return Report{
.min_delta_time = std.math.f32_max,
.max_delta_time = 0,
.delta_time_sum = 0,
.delta_time_sum_samples = 0,
.brick_dim = Vec3U.new(
brick_state.device_state.voxel_dim_x,
brick_state.device_state.voxel_dim_y,
brick_state.device_state.voxel_dim_z,
),
};
}
pub fn average(self: Report) f32 {
return self.delta_time_sum / @intToFloat(f32, self.delta_time_sum_samples);
}
pub fn print(self: Report, device_name: []const u8, d_camera: Camera.Device, sun_enabled: bool) void {
const report_fmt = "{s: <25}: {d:>8.3}\n{s: <25}: {d:>8.3}\n{s: <25}: {d:>8.3}\n";
const sun_fmt = "{s: <25}: {any}\n";
const camera_fmt = "Camera state info:\n{s: <30}: (x = {d}, y = {d})\n{s: <30}: {d}\n{s: <30}: {d}\n";
std.log.info("\n{s:-^50}\n{s: <25}: {s}\n" ++ report_fmt ++ "{s: <25}: {any}\n" ++ sun_fmt ++ camera_fmt, .{
"BENCHMARK REPORT",
"GPU",
device_name,
"Min frame time",
self.min_delta_time * std.time.ms_per_s,
"Max frame time",
self.max_delta_time * std.time.ms_per_s,
"Avg frame time",
self.average() * std.time.ms_per_s,
"Brick state info",
self.brick_dim.data,
"Sun enabled",
sun_enabled,
" > image dimensions",
d_camera.image_width,
d_camera.image_height,
" > max bounce",
d_camera.max_bounce,
" > samples per pixel",
d_camera.samples_per_pixel,
});
}
};
// TODO: these are static for now, but should be configured through a file
// TODO: there should also be gui functionality to record paths and orientations
// in such a file ...
pub const Configuration = struct {
// total duration of benchmarks in seconds
pub const benchmark_duration: f32 = 60;
pub const path_points = [_]za.Vec3{
za.Vec3.new(0, 0, 0),
za.Vec3.new(2, 5, 0),
za.Vec3.new(3, 5, 5),
za.Vec3.new(5, 2, 1),
za.Vec3.new(10, 0, 10),
za.Vec3.new(20, -20, 20),
za.Vec3.new(10, -25, 15),
za.Vec3.new(10, -22, 20),
za.Vec3.new(10, -30, 25),
za.Vec3.new(5, -10, 10),
za.Vec3.new(0, 13, 0),
};
pub const path_orientations = [_]za.Quat{
za.Quat.identity(),
za.Quat.fromEulerAngles(za.Vec3.new(0, 45, 0)),
za.Quat.fromEulerAngles(za.Vec3.new(10, -20, 0)),
za.Quat.fromEulerAngles(za.Vec3.new(20, 180, 0)),
za.Quat.fromEulerAngles(za.Vec3.new(50, 90, 0)),
za.Quat.fromEulerAngles(za.Vec3.new(60, 0, 0)),
za.Quat.fromEulerAngles(za.Vec3.new(80, -10, 0)),
za.Quat.fromEulerAngles(za.Vec3.new(75, -40, 0)),
za.Quat.fromEulerAngles(za.Vec3.new(80, -10, 0)),
za.Quat.fromEulerAngles(za.Vec3.new(80, -90, 0)),
za.Quat.fromEulerAngles(za.Vec3.new(0, -145, 0)),
};
};
|
0 | repos/zig_vulkan/src/modules | repos/zig_vulkan/src/modules/voxel_rt/ImguiPipeline.zig | const std = @import("std");
const Allocator = std.mem.Allocator;
// based on sascha's imgui example
// this code does not use most of the codebase abstractions because a MVP is the goal and its
// easier to directly adapt the original code without out it :)
const zgui = @import("zgui");
const vk = @import("vulkan");
const za = @import("zalgebra");
const tracy = @import("ztracy");
const shaders = @import("shaders");
const render = @import("../render.zig");
const GpuBufferMemory = render.GpuBufferMemory;
const StagingRamp = render.StagingRamp;
const Context = render.Context;
const Texture = render.Texture;
/// application imgui vulkan render wrapper
/// this should not be used directly by user code and should only be used by internal code
const ImguiPipeline = @This();
pub const PushConstant = struct {
scale: [2]f32,
translate: [2]f32,
};
sampler: vk.Sampler,
vertex_index_buffer_offset: vk.DeviceSize,
vertex_size: vk.DeviceSize,
vertex_buffer_len: c_int,
index_buffer_len: c_int,
font_image: vk.Image,
font_view: vk.ImageView,
pipeline_cache: vk.PipelineCache,
pipeline_layout: vk.PipelineLayout,
pipeline: vk.Pipeline,
descriptor_pool: vk.DescriptorPool,
descriptor_set_layout: vk.DescriptorSetLayout,
descriptor_set: vk.DescriptorSet,
// shader modules stored for cleanup
shader_modules: [2]vk.ShaderModule,
pub fn init(
ctx: Context,
allocator: std.mem.Allocator,
render_pass: vk.RenderPass,
swapchain_image_count: usize,
staging_buffers: *StagingRamp,
vertex_index_buffer_offset: vk.DeviceSize,
image_memory_type: u32,
image_memory: vk.DeviceMemory,
image_memory_capacity: vk.DeviceSize,
image_memory_size: *vk.DeviceSize,
) !ImguiPipeline {
// initialize zgui
zgui.init(allocator);
errdefer zgui.deinit();
zgui.plot.init();
errdefer zgui.plot.deinit();
// Create font texture
var width: i32 = undefined;
var height: i32 = undefined;
const pixels = zgui.io.getFontsTextDataAsRgba32(&width, &height);
const font_image = blk: {
const image_info = vk.ImageCreateInfo{
.flags = .{},
.image_type = .@"2d",
.format = .r8g8b8a8_unorm,
.extent = .{
.width = @intCast(u32, width),
.height = @intCast(u32, height),
.depth = @intCast(u32, 1),
},
.mip_levels = 1,
.array_layers = 1,
.samples = .{
.@"1_bit" = true,
},
.tiling = .optimal,
.usage = .{
.sampled_bit = true,
.transfer_dst_bit = true,
},
.sharing_mode = .exclusive,
.queue_family_index_count = 0,
.p_queue_family_indices = undefined,
.initial_layout = .undefined,
};
break :blk try ctx.vkd.createImage(ctx.logical_device, &image_info, null);
};
errdefer ctx.vkd.destroyImage(ctx.logical_device, font_image, null);
const memory_requirements = ctx.vkd.getImageMemoryRequirements(ctx.logical_device, font_image);
const memory_type_index = try render.vk_utils.findMemoryTypeIndex(
ctx,
memory_requirements.memory_type_bits,
.{ .device_local_bit = true },
);
// In the event that any of the asserts below fail, we should allocate more memory
// we will not handle this for now, but a memory abstraction is needed sooner or later ...
std.debug.assert(image_memory_type == memory_type_index);
std.debug.assert(image_memory_size.* + memory_requirements.size < image_memory_capacity);
try ctx.vkd.bindImageMemory(ctx.logical_device, font_image, image_memory, image_memory_size.*);
image_memory_size.* += memory_requirements.size;
const font_view = blk: {
const view_info = vk.ImageViewCreateInfo{
.flags = .{},
.image = font_image,
.view_type = .@"2d",
.format = .r8g8b8a8_unorm,
.components = .{
.r = .identity,
.g = .identity,
.b = .identity,
.a = .identity,
},
.subresource_range = .{
.aspect_mask = .{ .color_bit = true },
.base_mip_level = 0,
.level_count = 1,
.base_array_layer = 0,
.layer_count = 1,
},
};
break :blk try ctx.vkd.createImageView(ctx.logical_device, &view_info, null);
};
errdefer ctx.vkd.destroyImageView(ctx.logical_device, font_view, null);
// upload texture data to gpu
try staging_buffers.transferToImage(
ctx,
.undefined,
.shader_read_only_optimal,
font_image,
@intCast(u32, width),
@intCast(u32, height),
u32,
pixels[0..@intCast(usize, width * height)],
);
const sampler = blk: {
const sampler_info = vk.SamplerCreateInfo{
.flags = .{},
.mag_filter = .linear,
.min_filter = .linear,
.mipmap_mode = .linear,
.address_mode_u = .clamp_to_edge,
.address_mode_v = .clamp_to_edge,
.address_mode_w = .clamp_to_edge,
.mip_lod_bias = 0,
.anisotropy_enable = vk.FALSE,
.max_anisotropy = 0,
.compare_enable = vk.FALSE,
.compare_op = .never,
.min_lod = 0,
.max_lod = 0,
.border_color = .float_opaque_white,
.unnormalized_coordinates = vk.FALSE,
};
break :blk try ctx.vkd.createSampler(ctx.logical_device, &sampler_info, null);
};
errdefer ctx.vkd.destroySampler(ctx.logical_device, sampler, null);
const descriptor_pool = blk: {
const pool_sizes = [_]vk.DescriptorPoolSize{.{
.type = .combined_image_sampler,
.descriptor_count = 1, // TODO: swap image size ?
}};
const descriptor_pool_info = vk.DescriptorPoolCreateInfo{
.flags = .{},
.max_sets = @intCast(u32, swapchain_image_count),
.pool_size_count = pool_sizes.len,
.p_pool_sizes = @ptrCast([*]const vk.DescriptorPoolSize, &pool_sizes),
};
break :blk try ctx.vkd.createDescriptorPool(ctx.logical_device, &descriptor_pool_info, null);
};
errdefer ctx.vkd.destroyDescriptorPool(ctx.logical_device, descriptor_pool, null);
const descriptor_set_layout = blk: {
const set_layout_bindings = [_]vk.DescriptorSetLayoutBinding{.{
.binding = 0,
.descriptor_type = .combined_image_sampler,
.descriptor_count = 1,
.stage_flags = .{
.fragment_bit = true,
},
.p_immutable_samplers = null,
}};
const set_layout_info = vk.DescriptorSetLayoutCreateInfo{
.flags = .{},
.binding_count = set_layout_bindings.len,
.p_bindings = @ptrCast([*]const vk.DescriptorSetLayoutBinding, &set_layout_bindings),
};
break :blk try ctx.vkd.createDescriptorSetLayout(ctx.logical_device, &set_layout_info, null);
};
errdefer ctx.vkd.destroyDescriptorSetLayout(ctx.logical_device, descriptor_set_layout, null);
const descriptor_set = blk: {
const alloc_info = vk.DescriptorSetAllocateInfo{
.descriptor_pool = descriptor_pool,
.descriptor_set_count = 1,
.p_set_layouts = @ptrCast([*]const vk.DescriptorSetLayout, &descriptor_set_layout),
};
var descriptor_set_tmp: vk.DescriptorSet = undefined;
try ctx.vkd.allocateDescriptorSets(
ctx.logical_device,
&alloc_info,
@ptrCast([*]vk.DescriptorSet, &descriptor_set_tmp),
);
break :blk descriptor_set_tmp;
};
{
const descriptor_info = vk.DescriptorImageInfo{
.sampler = sampler,
.image_view = font_view,
.image_layout = .shader_read_only_optimal,
};
const write_descriptor_sets = [_]vk.WriteDescriptorSet{.{
.dst_set = descriptor_set,
.dst_binding = 0,
.dst_array_element = 0,
.descriptor_count = 1,
.descriptor_type = .combined_image_sampler,
.p_image_info = @ptrCast([*]const vk.DescriptorImageInfo, &descriptor_info),
.p_buffer_info = undefined,
.p_texel_buffer_view = undefined,
}};
ctx.vkd.updateDescriptorSets(
ctx.logical_device,
write_descriptor_sets.len,
@ptrCast([*]const vk.WriteDescriptorSet, &write_descriptor_sets),
0,
undefined,
);
}
const pipeline_cache = blk: {
const pipeline_cache_info = vk.PipelineCacheCreateInfo{
.flags = .{},
.initial_data_size = 0,
.p_initial_data = undefined,
};
break :blk try ctx.vkd.createPipelineCache(ctx.logical_device, &pipeline_cache_info, null);
};
errdefer ctx.vkd.destroyPipelineCache(ctx.logical_device, pipeline_cache, null);
const pipeline_layout = blk: {
const push_constant_range = vk.PushConstantRange{
.stage_flags = .{ .vertex_bit = true },
.offset = 0,
.size = @sizeOf(PushConstant),
};
const pipeline_layout_info = vk.PipelineLayoutCreateInfo{
.flags = .{},
.set_layout_count = 1,
.p_set_layouts = @ptrCast([*]const vk.DescriptorSetLayout, &descriptor_set_layout),
.push_constant_range_count = 1,
.p_push_constant_ranges = @ptrCast([*]const vk.PushConstantRange, &push_constant_range),
};
break :blk try ctx.vkd.createPipelineLayout(ctx.logical_device, &pipeline_layout_info, null);
};
errdefer ctx.vkd.destroyPipelineLayout(ctx.logical_device, pipeline_layout, null);
const input_assembly_state = vk.PipelineInputAssemblyStateCreateInfo{
.flags = .{},
.topology = .triangle_list,
.primitive_restart_enable = vk.FALSE,
};
const rasterization_state = vk.PipelineRasterizationStateCreateInfo{
.flags = .{},
.depth_clamp_enable = vk.FALSE,
.rasterizer_discard_enable = vk.FALSE,
.polygon_mode = .fill,
.cull_mode = .{},
.front_face = .counter_clockwise,
.depth_bias_enable = 0,
.depth_bias_constant_factor = 0,
.depth_bias_clamp = 0,
.depth_bias_slope_factor = 0,
.line_width = 1,
};
const blend_mode = vk.PipelineColorBlendAttachmentState{
.blend_enable = vk.TRUE,
.src_color_blend_factor = .src_alpha,
.dst_color_blend_factor = .one_minus_src_alpha,
.color_blend_op = .add,
.src_alpha_blend_factor = .one_minus_src_alpha,
.dst_alpha_blend_factor = .zero,
.alpha_blend_op = .add,
.color_write_mask = .{
.r_bit = true,
.g_bit = true,
.b_bit = true,
.a_bit = true,
},
};
const color_blend_state = vk.PipelineColorBlendStateCreateInfo{
.flags = .{},
.logic_op_enable = vk.FALSE,
.logic_op = .clear,
.attachment_count = 1,
.p_attachments = @ptrCast([*]const vk.PipelineColorBlendAttachmentState, &blend_mode),
.blend_constants = [4]f32{ 0, 0, 0, 0 },
};
// TODO: deviation from guide. Validate that still valid!
const depth_stencil_state: ?*vk.PipelineDepthStencilStateCreateInfo = null;
const viewport_state = vk.PipelineViewportStateCreateInfo{
.flags = .{},
.viewport_count = 1,
.p_viewports = null, // viewport is created on draw
.scissor_count = 1,
.p_scissors = null, // scissor is created on draw
};
const multisample_state = vk.PipelineMultisampleStateCreateInfo{
.flags = .{},
.rasterization_samples = .{ .@"1_bit" = true },
.sample_shading_enable = vk.FALSE,
.min_sample_shading = 0,
.p_sample_mask = null,
.alpha_to_coverage_enable = vk.FALSE,
.alpha_to_one_enable = vk.FALSE,
};
const dynamic_state_enabled = [_]vk.DynamicState{
.viewport,
.scissor,
};
const dynamic_state = vk.PipelineDynamicStateCreateInfo{
.flags = .{},
.dynamic_state_count = dynamic_state_enabled.len,
.p_dynamic_states = &dynamic_state_enabled,
};
const vert = blk: {
const create_info = vk.ShaderModuleCreateInfo{
.flags = .{},
.p_code = @ptrCast([*]const u32, &shaders.ui_vert_spv),
.code_size = shaders.ui_vert_spv.len,
};
const module = try ctx.vkd.createShaderModule(ctx.logical_device, &create_info, null);
break :blk vk.PipelineShaderStageCreateInfo{
.flags = .{},
.stage = .{ .vertex_bit = true },
.module = module,
.p_name = "main",
.p_specialization_info = null,
};
};
errdefer ctx.vkd.destroyShaderModule(ctx.logical_device, vert.module, null);
const frag = blk: {
const create_info = vk.ShaderModuleCreateInfo{
.flags = .{},
.p_code = @ptrCast([*]const u32, &shaders.ui_frag_spv),
.code_size = shaders.ui_frag_spv.len,
};
const module = try ctx.vkd.createShaderModule(ctx.logical_device, &create_info, null);
break :blk vk.PipelineShaderStageCreateInfo{
.flags = .{},
.stage = .{ .fragment_bit = true },
.module = module,
.p_name = "main",
.p_specialization_info = null,
};
};
errdefer ctx.vkd.destroyShaderModule(ctx.logical_device, frag.module, null);
const shader_stages = [_]vk.PipelineShaderStageCreateInfo{ vert, frag };
const vertex_input_bindings = [_]vk.VertexInputBindingDescription{.{
.binding = 0,
.stride = @sizeOf(zgui.DrawVert),
.input_rate = .vertex,
}};
const vertex_input_attributes = [_]vk.VertexInputAttributeDescription{ .{
.location = 0,
.binding = 0,
.format = .r32g32_sfloat,
.offset = @offsetOf(zgui.DrawVert, "pos"),
}, .{
.location = 1,
.binding = 0,
.format = .r32g32_sfloat,
.offset = @offsetOf(zgui.DrawVert, "uv"),
}, .{
.location = 2,
.binding = 0,
.format = .r8g8b8a8_unorm,
.offset = @offsetOf(zgui.DrawVert, "color"),
} };
const vertex_input_state = vk.PipelineVertexInputStateCreateInfo{
.flags = .{},
.vertex_binding_description_count = vertex_input_bindings.len,
.p_vertex_binding_descriptions = &vertex_input_bindings,
.vertex_attribute_description_count = vertex_input_attributes.len,
.p_vertex_attribute_descriptions = &vertex_input_attributes,
};
const pipeline_create_info = vk.GraphicsPipelineCreateInfo{
.flags = .{},
.stage_count = shader_stages.len,
.p_stages = &shader_stages,
.p_vertex_input_state = &vertex_input_state,
.p_input_assembly_state = &input_assembly_state,
.p_tessellation_state = null,
.p_viewport_state = &viewport_state,
.p_rasterization_state = &rasterization_state,
.p_multisample_state = &multisample_state,
.p_depth_stencil_state = depth_stencil_state,
.p_color_blend_state = &color_blend_state,
.p_dynamic_state = &dynamic_state,
.layout = pipeline_layout,
.render_pass = render_pass,
.subpass = 0,
.base_pipeline_handle = vk.Pipeline.null_handle,
.base_pipeline_index = -1,
};
var pipeline: vk.Pipeline = undefined;
_ = try ctx.vkd.createGraphicsPipelines(
ctx.logical_device,
pipeline_cache,
1,
@ptrCast([*]const vk.GraphicsPipelineCreateInfo, &pipeline_create_info),
null,
@ptrCast([*]vk.Pipeline, &pipeline),
);
errdefer ctx.vkd.destroyPipeline(ctx.logical_device, pipeline, null);
return ImguiPipeline{
.sampler = sampler,
.vertex_index_buffer_offset = vertex_index_buffer_offset,
.vertex_size = 0,
.vertex_buffer_len = 0,
.index_buffer_len = 0,
.font_image = font_image,
.font_view = font_view,
.pipeline_cache = pipeline_cache,
.pipeline_layout = pipeline_layout,
.pipeline = pipeline,
.descriptor_pool = descriptor_pool,
.descriptor_set_layout = descriptor_set_layout,
.descriptor_set = descriptor_set,
.shader_modules = [2]vk.ShaderModule{ vert.module, frag.module },
};
}
pub fn deinit(self: ImguiPipeline, ctx: Context) void {
zgui.plot.deinit();
zgui.deinit();
ctx.vkd.destroyPipeline(ctx.logical_device, self.pipeline, null);
ctx.vkd.destroyPipelineLayout(ctx.logical_device, self.pipeline_layout, null);
ctx.vkd.destroyPipelineCache(ctx.logical_device, self.pipeline_cache, null);
ctx.vkd.destroyDescriptorPool(ctx.logical_device, self.descriptor_pool, null);
ctx.vkd.destroyDescriptorSetLayout(ctx.logical_device, self.descriptor_set_layout, null);
ctx.vkd.destroyShaderModule(ctx.logical_device, self.shader_modules[0], null);
ctx.vkd.destroyShaderModule(ctx.logical_device, self.shader_modules[1], null);
ctx.vkd.destroyImageView(ctx.logical_device, self.font_view, null);
ctx.vkd.destroySampler(ctx.logical_device, self.sampler, null);
ctx.vkd.destroyImage(ctx.logical_device, self.font_image, null);
}
/// record a command buffer that can draw current frame
pub fn recordCommandBuffer(
self: ImguiPipeline,
ctx: Context,
command_buffer: vk.CommandBuffer,
buffer_offset: vk.DeviceSize,
vertex_index_buffer: GpuBufferMemory,
) !void {
const record_zone = tracy.ZoneN(@src(), "imgui commands");
defer record_zone.End();
ctx.vkd.cmdBindDescriptorSets(
command_buffer,
.graphics,
self.pipeline_layout,
0,
1,
@ptrCast([*]const vk.DescriptorSet, &self.descriptor_set),
0,
undefined,
);
ctx.vkd.cmdBindPipeline(command_buffer, .graphics, self.pipeline);
const display_size = zgui.io.getDisplaySize();
const viewport = vk.Viewport{
.x = 0,
.y = 0,
.width = display_size[0],
.height = display_size[1],
.min_depth = 0,
.max_depth = 1,
};
ctx.vkd.cmdSetViewport(command_buffer, 0, 1, @ptrCast([*]const vk.Viewport, &viewport));
// UI scale and translate via push constants
const push_constant = PushConstant{
.scale = [2]f32{ 2 / display_size[0], 2 / display_size[1] },
.translate = [2]f32{ -1, -1 },
};
ctx.vkd.cmdPushConstants(command_buffer, self.pipeline_layout, .{ .vertex_bit = true }, 0, @sizeOf(PushConstant), &push_constant);
// Render commands
const im_draw_data = zgui.getDrawData();
var vertex_offset: c_uint = 0;
var index_offset: c_uint = 0;
if (im_draw_data.cmd_lists_count > 0) {
const vertex_offsets = [_]vk.DeviceSize{buffer_offset};
ctx.vkd.cmdBindVertexBuffers(
command_buffer,
0,
1,
@ptrCast([*]const vk.Buffer, &vertex_index_buffer.buffer),
&vertex_offsets,
);
ctx.vkd.cmdBindIndexBuffer(command_buffer, vertex_index_buffer.buffer, buffer_offset + self.vertex_size, .uint16);
for (im_draw_data.cmd_lists[0..@intCast(usize, im_draw_data.cmd_lists_count)]) |command_list| {
const command_buffer_length = command_list.getCmdBufferLength();
const command_buffer_data = command_list.getCmdBufferData();
for (command_buffer_data[0..@intCast(usize, command_buffer_length)]) |draw_command| {
const scissor_rect = vk.Rect2D{
.offset = .{
.x = std.math.max(@floatToInt(i32, draw_command.clip_rect[0]), 0),
.y = std.math.max(@floatToInt(i32, draw_command.clip_rect[1]), 0),
},
.extent = .{
.width = @floatToInt(u32, draw_command.clip_rect[2] - draw_command.clip_rect[0]),
.height = @floatToInt(u32, draw_command.clip_rect[3] - draw_command.clip_rect[1]),
},
};
ctx.vkd.cmdSetScissor(command_buffer, 0, 1, @ptrCast([*]const vk.Rect2D, &scissor_rect));
ctx.vkd.cmdDrawIndexed(
command_buffer,
draw_command.elem_count,
1,
@intCast(u32, index_offset),
@intCast(i32, vertex_offset),
0,
);
index_offset += draw_command.elem_count;
}
vertex_offset += @intCast(c_uint, command_list.getVertexBufferLength());
}
}
}
// TODO: do not make new buffers if buffer is larger than total count
pub fn updateBuffers(
self: *ImguiPipeline,
ctx: Context,
vertex_index_buffer: *GpuBufferMemory,
) !void {
const update_buffers_zone = tracy.ZoneN(@src(), "imgui: vertex & index update");
defer update_buffers_zone.End();
const draw_data = zgui.getDrawData();
if (draw_data.valid == false) {
return;
}
self.vertex_size = @intCast(vk.DeviceSize, draw_data.total_vtx_count * @sizeOf(zgui.DrawVert));
const index_size = @intCast(vk.DeviceSize, draw_data.total_idx_count * @sizeOf(zgui.DrawIdx));
self.vertex_buffer_len = draw_data.total_vtx_count;
self.index_buffer_len = draw_data.total_idx_count;
if (index_size == 0 or self.vertex_size == 0) return; // nothing to draw
std.debug.assert(self.vertex_size + index_size < vertex_index_buffer.size);
try vertex_index_buffer.map(ctx, self.vertex_index_buffer_offset, self.vertex_size + index_size);
defer vertex_index_buffer.unmap(ctx);
var vertex_dest = @ptrCast([*]zgui.DrawVert, @alignCast(@alignOf(zgui.DrawVert), vertex_index_buffer.mapped) orelse unreachable);
var vertex_offset: usize = 0;
// map index_dest to be the buffer memory + vertex byte offset
var index_dest = @ptrCast(
[*]zgui.DrawIdx,
@alignCast(
@alignOf(zgui.DrawIdx),
@intToPtr(?*anyopaque, @ptrToInt(vertex_index_buffer.mapped) + @intCast(usize, self.vertex_size)),
) orelse unreachable,
);
var index_offset: usize = 0;
for (draw_data.cmd_lists[0..@intCast(usize, draw_data.cmd_lists_count)]) |command_list| {
// transfer vertex data
{
const vertex_buffer_length = @intCast(usize, command_list.getVertexBufferLength());
const vertex_buffer_data = command_list.getVertexBufferData()[0..vertex_buffer_length];
std.mem.copy(
zgui.DrawVert,
vertex_dest[vertex_offset .. vertex_offset + vertex_buffer_data.len],
vertex_buffer_data,
);
vertex_offset += vertex_buffer_data.len;
}
// transfer index data
{
const index_buffer_length = @intCast(usize, command_list.getIndexBufferLength());
const index_buffer_data = command_list.getIndexBufferData()[0..index_buffer_length];
std.mem.copy(
zgui.DrawIdx,
index_dest[index_offset .. index_offset + index_buffer_data.len],
index_buffer_data,
);
index_offset += index_buffer_data.len;
}
}
// send changes to GPU
try vertex_index_buffer.flush(ctx, self.vertex_index_buffer_offset, self.vertex_size + index_size);
}
|
0 | repos/zig_vulkan/src/modules/voxel_rt | repos/zig_vulkan/src/modules/voxel_rt/vox/loader.zig | const std = @import("std");
const Allocator = std.mem.Allocator;
const types = @import("types.zig");
const Vox = types.Vox;
const Chunk = types.Chunk;
/// VOX loader implemented according to VOX specification: https://github.com/ephtracy/voxel-model/blob/master/MagicaVoxel-file-format-vox.txt
pub fn load(comptime strict: bool, allocator: Allocator, path: []const u8) !Vox {
const file = blk: {
const use_path = try buildPath(allocator, path);
defer allocator.free(use_path);
break :blk try std.fs.openFileAbsolute(use_path, .{});
};
defer file.close();
const file_buffer = blk: {
const size = (try file.stat()).size;
// + 1 to check if read is successfull
break :blk try allocator.alloc(u8, size + 1);
};
defer allocator.free(file_buffer);
const bytes_read = try file.readAll(file_buffer);
if (file_buffer.len <= bytes_read) {
return error.InsufficientBuffer;
}
return parseBuffer(strict, allocator, file_buffer);
}
pub const ParseError = error{
InvalidId,
ExpectedSizeHeader,
ExpectedXyziHeader,
ExpectedRgbaHeader,
UnexpectedVersion,
InvalidFileContent,
MultiplePackChunks,
};
pub fn parseBuffer(comptime strict: bool, allocator: Allocator, buffer: []const u8) !Vox {
if (strict == true) {
try validateHeader(buffer);
}
var vox = Vox.init(allocator);
errdefer vox.deinit();
// insert main node
try vox.generic_chunks.append(try chunkFrom(buffer[8..]));
try vox.nodes.append(.{
.type_id = .main,
.generic_index = 0,
.index = 0,
});
// id (4) + chunk size (4) + child size (4)
const chunk_stride = 4 * 3;
// skip main chunk
var pos: usize = 8 + chunk_stride;
// Parse pack_chunk if any
if (buffer[pos] == 'P') {
// parse generic chunk
try vox.generic_chunks.append(try chunkFrom(buffer[pos..]));
pos += chunk_stride;
// Parse pack
vox.pack_chunk = Chunk.Pack{
.num_models = parseI32(buffer[pos..]),
};
pos += 4;
} else {
vox.pack_chunk = Chunk.Pack{
.num_models = 1,
};
}
try vox.nodes.append(.{
.type_id = .pack,
.generic_index = 0,
.index = 0,
});
const num_models = @intCast(usize, vox.pack_chunk.num_models);
// allocate voxel data according to pack information
vox.size_chunks = try allocator.alloc(Chunk.Size, num_models);
vox.xyzi_chunks = try allocator.alloc([]Chunk.XyziElement, num_models);
// TODO: pos will cause out of bounds easily, make code more robust!
var model: usize = 0;
while (model < num_models) : (model += 1) {
// parse SIZE chunk
{
if (strict) {
if (!std.mem.eql(u8, buffer[pos .. pos + 4], "SIZE")) {
return ParseError.ExpectedSizeHeader;
}
}
// parse generic chunk
try vox.generic_chunks.append(try chunkFrom(buffer[pos..]));
pos += chunk_stride;
const size = Chunk.Size{
.size_x = parseI32(buffer[pos..]),
.size_y = parseI32(buffer[pos + 4 ..]),
.size_z = parseI32(buffer[pos + 8 ..]),
};
pos += 12;
vox.size_chunks[model] = size;
try vox.nodes.append(.{
.type_id = .size,
.generic_index = vox.generic_chunks.items.len,
.index = model,
});
}
// parse XYZI chunk
{
if (strict) {
if (!std.mem.eql(u8, buffer[pos .. pos + 4], "XYZI")) {
return ParseError.ExpectedXyziHeader;
}
}
// parse generic chunk
try vox.generic_chunks.append(try chunkFrom(buffer[pos..]));
pos += chunk_stride;
const voxel_count = parseI32(buffer[pos..]);
pos += 4;
const xyzis = try allocator.alloc(Chunk.XyziElement, @intCast(usize, voxel_count));
{
var i: usize = 0;
while (i < voxel_count) : (i += 1) {
xyzis[i].x = buffer[pos];
xyzis[i].y = buffer[pos + 1];
xyzis[i].z = buffer[pos + 2];
xyzis[i].color_index = buffer[pos + 3];
pos += 4;
}
}
vox.xyzi_chunks[model] = xyzis;
try vox.nodes.append(.{
.type_id = .xyzi,
.generic_index = vox.generic_chunks.items.len,
.index = model,
});
}
}
var rgba_set: bool = false;
while (pos < buffer.len) {
// Parse potential extensions and RGBA
switch (buffer[pos]) {
'R' => {
// check if it is probable that there is a RGBA chunk remaining
if (strict) {
if (!std.mem.eql(u8, buffer[pos .. pos + 4], "RGBA")) {
return ParseError.ExpectedRgbaHeader;
}
}
// parse generic chunk
try vox.generic_chunks.append(try chunkFrom(buffer[pos..]));
pos += chunk_stride;
vox.rgba_chunk[0] = Chunk.RgbaElement{
.r = 0,
.g = 0,
.b = 0,
.a = 1,
};
var i: usize = 1;
while (i < 255) : (i += 1) {
vox.rgba_chunk[i] = Chunk.RgbaElement{
.r = buffer[pos],
.g = buffer[pos + 1],
.b = buffer[pos + 2],
.a = buffer[pos + 3],
};
pos += 4;
}
rgba_set = true;
},
else => {
// skip bytes
pos += 4;
},
}
}
if (rgba_set == false) {
const default = @ptrCast(*const [256]Chunk.RgbaElement, &default_rgba);
std.mem.copy(Chunk.RgbaElement, vox.rgba_chunk[0..], default[0..]);
}
return vox;
}
inline fn parseI32(buffer: []const u8) i32 {
return @ptrCast(*const i32, @alignCast(4, &buffer[0])).*;
}
/// Parse a buffer into a chunk, buffer *has* to start with the first character in the id
inline fn chunkFrom(buffer: []const u8) std.fmt.ParseIntError!Chunk {
const size = parseI32(buffer[4..]);
const child_size = parseI32(buffer[8..]);
return Chunk{
.size = size,
.child_size = child_size,
};
}
inline fn validateHeader(buffer: []const u8) ParseError!void {
if (std.mem.eql(u8, buffer[0..4], "VOX ") == false) {
return error.InvalidId; // Vox format should start with "VOX "
}
const version = buffer[4];
if (version != 150) {
return error.UnexpectedVersion; // Expect version 150
}
if (std.mem.eql(u8, buffer[8..12], "MAIN") == false) {
return error.InvalidFileContent; // Missing main chunk in file
}
}
inline fn buildPath(allocator: Allocator, path: []const u8) ![]const u8 {
var buf: [std.fs.MAX_PATH_BYTES]u8 = undefined;
const exe_path = try std.fs.selfExeDirPath(buf[0..]);
const path_segments = [_][]const u8{ exe_path, path };
var zig_use_path = try std.fs.path.join(allocator, path_segments[0..]);
errdefer allocator.destroy(zig_use_path.ptr);
const sep = [_]u8{std.fs.path.sep};
_ = std.mem.replace(u8, zig_use_path, "\\", sep[0..], zig_use_path);
_ = std.mem.replace(u8, zig_use_path, "/", sep[0..], zig_use_path);
return zig_use_path;
}
const default_rgba = [256]u32{
0x00000000, 0xffffffff, 0xffccffff, 0xff99ffff, 0xff66ffff, 0xff33ffff, 0xff00ffff, 0xffffccff, 0xffccccff, 0xff99ccff, 0xff66ccff, 0xff33ccff, 0xff00ccff, 0xffff99ff, 0xffcc99ff, 0xff9999ff,
0xff6699ff, 0xff3399ff, 0xff0099ff, 0xffff66ff, 0xffcc66ff, 0xff9966ff, 0xff6666ff, 0xff3366ff, 0xff0066ff, 0xffff33ff, 0xffcc33ff, 0xff9933ff, 0xff6633ff, 0xff3333ff, 0xff0033ff, 0xffff00ff,
0xffcc00ff, 0xff9900ff, 0xff6600ff, 0xff3300ff, 0xff0000ff, 0xffffffcc, 0xffccffcc, 0xff99ffcc, 0xff66ffcc, 0xff33ffcc, 0xff00ffcc, 0xffffcccc, 0xffcccccc, 0xff99cccc, 0xff66cccc, 0xff33cccc,
0xff00cccc, 0xffff99cc, 0xffcc99cc, 0xff9999cc, 0xff6699cc, 0xff3399cc, 0xff0099cc, 0xffff66cc, 0xffcc66cc, 0xff9966cc, 0xff6666cc, 0xff3366cc, 0xff0066cc, 0xffff33cc, 0xffcc33cc, 0xff9933cc,
0xff6633cc, 0xff3333cc, 0xff0033cc, 0xffff00cc, 0xffcc00cc, 0xff9900cc, 0xff6600cc, 0xff3300cc, 0xff0000cc, 0xffffff99, 0xffccff99, 0xff99ff99, 0xff66ff99, 0xff33ff99, 0xff00ff99, 0xffffcc99,
0xffcccc99, 0xff99cc99, 0xff66cc99, 0xff33cc99, 0xff00cc99, 0xffff9999, 0xffcc9999, 0xff999999, 0xff669999, 0xff339999, 0xff009999, 0xffff6699, 0xffcc6699, 0xff996699, 0xff666699, 0xff336699,
0xff006699, 0xffff3399, 0xffcc3399, 0xff993399, 0xff663399, 0xff333399, 0xff003399, 0xffff0099, 0xffcc0099, 0xff990099, 0xff660099, 0xff330099, 0xff000099, 0xffffff66, 0xffccff66, 0xff99ff66,
0xff66ff66, 0xff33ff66, 0xff00ff66, 0xffffcc66, 0xffcccc66, 0xff99cc66, 0xff66cc66, 0xff33cc66, 0xff00cc66, 0xffff9966, 0xffcc9966, 0xff999966, 0xff669966, 0xff339966, 0xff009966, 0xffff6666,
0xffcc6666, 0xff996666, 0xff666666, 0xff336666, 0xff006666, 0xffff3366, 0xffcc3366, 0xff993366, 0xff663366, 0xff333366, 0xff003366, 0xffff0066, 0xffcc0066, 0xff990066, 0xff660066, 0xff330066,
0xff000066, 0xffffff33, 0xffccff33, 0xff99ff33, 0xff66ff33, 0xff33ff33, 0xff00ff33, 0xffffcc33, 0xffcccc33, 0xff99cc33, 0xff66cc33, 0xff33cc33, 0xff00cc33, 0xffff9933, 0xffcc9933, 0xff999933,
0xff669933, 0xff339933, 0xff009933, 0xffff6633, 0xffcc6633, 0xff996633, 0xff666633, 0xff336633, 0xff006633, 0xffff3333, 0xffcc3333, 0xff993333, 0xff663333, 0xff333333, 0xff003333, 0xffff0033,
0xffcc0033, 0xff990033, 0xff660033, 0xff330033, 0xff000033, 0xffffff00, 0xffccff00, 0xff99ff00, 0xff66ff00, 0xff33ff00, 0xff00ff00, 0xffffcc00, 0xffcccc00, 0xff99cc00, 0xff66cc00, 0xff33cc00,
0xff00cc00, 0xffff9900, 0xffcc9900, 0xff999900, 0xff669900, 0xff339900, 0xff009900, 0xffff6600, 0xffcc6600, 0xff996600, 0xff666600, 0xff336600, 0xff006600, 0xffff3300, 0xffcc3300, 0xff993300,
0xff663300, 0xff333300, 0xff003300, 0xffff0000, 0xffcc0000, 0xff990000, 0xff660000, 0xff330000, 0xff0000ee, 0xff0000dd, 0xff0000bb, 0xff0000aa, 0xff000088, 0xff000077, 0xff000055, 0xff000044,
0xff000022, 0xff000011, 0xff00ee00, 0xff00dd00, 0xff00bb00, 0xff00aa00, 0xff008800, 0xff007700, 0xff005500, 0xff004400, 0xff002200, 0xff001100, 0xffee0000, 0xffdd0000, 0xffbb0000, 0xffaa0000,
0xff880000, 0xff770000, 0xff550000, 0xff440000, 0xff220000, 0xff110000, 0xffeeeeee, 0xffdddddd, 0xffbbbbbb, 0xffaaaaaa, 0xff888888, 0xff777777, 0xff555555, 0xff444444, 0xff222222, 0xff111111,
};
test "validateHeader: valid header accepted" {
const valid_test_buffer: []const u8 = "VOX " ++ [_]u8{ 150, 0, 0, 0 } ++ "MAIN";
try validateHeader(valid_test_buffer);
}
test "validateHeader: invalid id detected" {
const invalid_test_buffer: []const u8 = "!VOX" ++ [_]u8{ 150, 0, 0, 0 } ++ "MAIN";
try std.testing.expectError(ParseError.InvalidId, validateHeader(invalid_test_buffer));
}
test "validateHeader: invalid version detected" {
const invalid_test_buffer: []const u8 = "VOX " ++ [_]u8{ 169, 0, 0, 0 } ++ "MAIN";
try std.testing.expectError(ParseError.UnexpectedVersion, validateHeader(invalid_test_buffer));
}
|
0 | repos/zig_vulkan/src/modules/voxel_rt | repos/zig_vulkan/src/modules/voxel_rt/vox/types.zig | const std = @import("std");
const Allocator = std.mem.Allocator;
const ArrayList = std.ArrayList;
/// A vox file
pub const Vox = struct {
allocator: Allocator,
version_number: i32,
nodes: ArrayList(ChunkNode),
generic_chunks: ArrayList(Chunk),
pack_chunk: Chunk.Pack,
size_chunks: []Chunk.Size,
xyzi_chunks: [][]Chunk.XyziElement,
rgba_chunk: [256]Chunk.RgbaElement,
pub fn init(allocator: Allocator) Vox {
return Vox{
.allocator = allocator,
// if you enable strict parsing in the load function, then this will be validated in validateHeader
.version_number = 150,
.nodes = ArrayList(ChunkNode).init(allocator),
.generic_chunks = ArrayList(Chunk).init(allocator),
.pack_chunk = undefined,
.size_chunks = undefined,
.xyzi_chunks = undefined,
.rgba_chunk = undefined,
};
}
pub fn deinit(self: Vox) void {
for (self.xyzi_chunks) |chunk| {
self.allocator.free(chunk);
}
self.allocator.free(self.size_chunks);
self.allocator.free(self.xyzi_chunks);
self.nodes.deinit();
self.generic_chunks.deinit();
}
};
pub const ChunkNode = struct {
type_id: Chunk.Type,
generic_index: usize,
index: usize,
};
/// Generic Chunk and all Chunk types
pub const Chunk = struct {
/// num bytes of chunk content
size: i32,
/// num bytes of children chunks
child_size: i32,
pub const Type = enum { main, pack, size, xyzi, rgba };
pub const Pack = struct {
/// num of SIZE and XYZI chunks
num_models: i32,
};
pub const Size = struct {
size_x: i32,
size_y: i32,
/// gravity direction in vox ...
size_z: i32,
};
pub const XyziElement = packed struct {
x: u8,
y: u8,
z: u8,
color_index: u8,
};
// * <NOTICE>
// * color [0-254] are mapped to palette index [1-255], e.g :
//
// for ( int i = 0; i <= 254; i++ ) {
// palette[i + 1] = ReadRGBA();
// }
pub const RgbaElement = packed struct {
r: u8,
g: u8,
b: u8,
a: u8,
};
// Extension chunks below
// pub const Material = struct {
// pub const Type = enum {
// diffuse,
// metal,
// glass,
// emit
// };
// @"type": Type,
// }
};
|
0 | repos/zig_vulkan/src/modules/voxel_rt | repos/zig_vulkan/src/modules/voxel_rt/vox/test.zig | test {
_ = @import("loader.zig");
}
|
0 | repos/zig_vulkan/src/modules/voxel_rt | repos/zig_vulkan/src/modules/voxel_rt/terrain/terrain.zig | const std = @import("std");
const Allocator = std.mem.Allocator;
const za = @import("zalgebra");
const stbi = @import("stbi");
const tracy = @import("ztracy");
const render = @import("../../render.zig");
const Context = render.Context;
const BrickGrid = @import("../brick/Grid.zig");
const gpu_types = @import("../gpu_types.zig");
const Perlin = @import("perlin.zig").PerlinNoiseGenerator(256);
const Material = enum(u8) {
water = 0,
grass,
dirt,
rock,
pub fn getMaterialIndex(self: Material, rnd: std.rand.Random) u8 {
switch (self) {
.water => return 0,
.grass => {
const roll = rnd.float(f32);
return 1 + @floatToInt(u8, @round(roll));
},
.dirt => {
const roll = rnd.float(f32);
return 3 + @floatToInt(u8, @round(roll));
},
.rock => {
const roll = rnd.float(f32);
return 5 + @floatToInt(u8, @round(roll));
},
}
}
};
/// populate a voxel grid with perlin noise terrain on CPU
pub fn generateCpu(comptime threads_count: usize, allocator: Allocator, seed: u64, scale: f32, ocean_level: usize, grid: *BrickGrid) !void { // TODO: return Terrain
const zone = tracy.ZoneNS(@src(), "generate terrain chunk", 1);
defer zone.End();
const perlin = blk: {
var p = try allocator.create(Perlin);
p.* = Perlin.init(seed);
break :blk p;
};
defer allocator.destroy(perlin);
const voxel_dim = [3]f32{
@intToFloat(f32, grid.state.device_state.dim_x * 8),
@intToFloat(f32, grid.state.device_state.dim_y * 8),
@intToFloat(f32, grid.state.device_state.dim_z * 8),
};
const point_mod = [3]f32{
(1 / voxel_dim[0]) * scale,
(1 / voxel_dim[1]) * scale,
(1 / voxel_dim[2]) * scale,
};
// create our gen function
const insert_job_gen_fn = struct {
pub fn insert(thread_id: usize, thread_name: [:0]const u8, perlin_: *const Perlin, voxel_dim_: [3]f32, point_mod_: [3]f32, ocean_level_v: usize, grid_: *BrickGrid) void {
tracy.SetThreadName(thread_name.ptr);
const gen_zone = tracy.ZoneN(@src(), "terrain gen");
defer gen_zone.End();
const thread_segment_size: f32 = if (threads_count == 0) voxel_dim_[0] else @ceil(voxel_dim_[0] / @intToFloat(f32, threads_count));
const terrain_max_height: f32 = voxel_dim_[1] * 0.5;
const inv_terrain_max_height = 1.0 / terrain_max_height;
var point: [3]f32 = undefined;
const thread_x_begin = thread_segment_size * @intToFloat(f32, thread_id);
const thread_x_end = std.math.min(thread_x_begin + thread_segment_size, voxel_dim_[0]);
var x: f32 = thread_x_begin;
while (x < thread_x_end) : (x += 1) {
const i_x = @floatToInt(usize, x);
var z: f32 = 0;
while (z < voxel_dim_[2]) : (z += 1) {
const i_z = @floatToInt(usize, z);
point[0] = x * point_mod_[0];
point[1] = 0;
point[2] = z * point_mod_[2];
const height = @floatToInt(usize, std.math.min(perlin_.smoothNoise(f32, point), 1) * terrain_max_height);
var i_y: usize = height / 2;
while (i_y < height) : (i_y += 1) {
const material_value = za.lerp(f32, 1, 3.4, @intToFloat(f32, i_y) * inv_terrain_max_height) + perlin_.rng.float(f32) * 0.5;
const material_index = @intToEnum(Material, @floatToInt(u8, @floor(material_value))).getMaterialIndex(perlin_.rng);
grid_.*.insert(i_x, i_y, i_z, material_index);
}
while (i_y < ocean_level_v) : (i_y += 1) {
grid_.*.insert(i_x, i_y, i_z, 0); // insert water
}
}
}
}
}.insert;
if (threads_count == 0) {
// run on main thread
@call(.{ .modifier = .always_inline }, insert_job_gen_fn, .{ 0, perlin, voxel_dim, point_mod, ocean_level, grid });
} else {
var threads: [threads_count]std.Thread = undefined;
comptime var i = 0;
inline while (i < threads_count) : (i += 1) {
const thread_name = comptime std.fmt.comptimePrint("terrain thread {d}", .{i});
threads[i] = try std.Thread.spawn(.{}, insert_job_gen_fn, .{ i, thread_name, perlin, voxel_dim, point_mod, ocean_level, grid });
}
i = 0;
inline while (i < threads_count) : (i += 1) {
threads[i].join();
}
}
}
/// color information expect by terrain to exist from 0.. in the albedo buffer
pub const color_data = [_]gpu_types.Albedo{
// water
.{ .color = za.Vec4.new(0.117, 0.45, 0.85, 1.0).data },
// grass 1
.{ .color = za.Vec4.new(0.0, 0.6, 0.0, 1.0).data },
// grass 2
.{ .color = za.Vec4.new(0.0, 0.5019, 0.0, 1.0).data },
// dirt 1
.{ .color = za.Vec4.new(0.3019, 0.149, 0, 1.0).data },
// dirt 2
.{ .color = za.Vec4.new(0.4, 0.2, 0, 1.0).data },
// rock 1
.{ .color = za.Vec4.new(0.275, 0.275, 0.275, 1.0).data },
// rock 2
.{ .color = za.Vec4.new(0.225, 0.225, 0.225, 1.0).data },
// iron
.{ .color = za.Vec4.new(0.6, 0.337, 0.282, 1.0).data },
};
/// material information expect by terrain to exist from 0.. in the material buffer
pub const material_data = [_]gpu_types.Material{
// water
.{ .type = .dielectric, .type_index = 0, .albedo_index = 0 },
// grass 1
.{ .type = .lambertian, .type_index = 0, .albedo_index = 1 },
// grass 2
.{ .type = .lambertian, .type_index = 0, .albedo_index = 2 },
// dirt 1
.{ .type = .lambertian, .type_index = 0, .albedo_index = 3 },
// dirt 2
.{ .type = .lambertian, .type_index = 0, .albedo_index = 4 },
// rock
.{ .type = .lambertian, .type_index = 0, .albedo_index = 5 },
// rock
.{ .type = .lambertian, .type_index = 0, .albedo_index = 6 },
// iron
.{ .type = .metal, .type_index = 0, .albedo_index = 4 },
};
|
0 | repos/zig_vulkan/src/modules/voxel_rt | repos/zig_vulkan/src/modules/voxel_rt/terrain/perlin.zig | // This code is directly taken from ray tracing the next week
// - https://raytracing.github.io/books/RayTracingTheNextWeek.html#perlinnoise
// The original source is c++ and changes have been made to accomodate Zig
const std = @import("std");
// TODO: point_count might have to be locked to exp of 2 i.e 2^8
pub fn PerlinNoiseGenerator(comptime point_count: u32) type {
// TODO: argument and input validation on PermInt & NoiseFloat
const PermInt: type = i32;
const NoiseFloat: type = f64;
return struct {
const Perlin = @This();
rand_float: [point_count]NoiseFloat,
perm_x: [point_count]PermInt,
perm_y: [point_count]PermInt,
perm_z: [point_count]PermInt,
rng: std.rand.Random,
pub fn init(seed: u64) Perlin {
var prng = std.rand.DefaultPrng.init(seed);
const rng = prng.random();
const generate_perm_fn = struct {
inline fn generate_perm(random: std.rand.Random) [point_count]PermInt {
var perm: [point_count]PermInt = undefined;
// TODO: replace for with while to avoid casting in loop
for (&perm, 0..) |*p, i| {
p.* = @intCast(PermInt, i);
}
{
var i: usize = point_count - 1;
while (i > 0) : (i -= 1) {
const target = random.intRangeLessThan(usize, 0, i);
const tmp = perm[i];
perm[i] = perm[target];
perm[target] = tmp;
}
}
return perm;
}
}.generate_perm;
var rand_float: [point_count]NoiseFloat = undefined;
for (&rand_float) |*float| {
float.* = rng.float(NoiseFloat);
}
const perm_x = generate_perm_fn(rng);
const perm_y = generate_perm_fn(rng);
const perm_z = generate_perm_fn(rng);
return Perlin{
.rand_float = rand_float,
.perm_x = perm_x,
.perm_y = perm_y,
.perm_z = perm_z,
.rng = rng,
};
}
pub fn noise(self: Perlin, comptime PointType: type, point: [3]PointType) NoiseFloat {
comptime {
const info = @typeInfo(PointType);
switch (info) {
.Float => {},
else => @compileError("PointType must be a float type"),
}
}
const and_value = point_count - 1;
const i = @floatToInt(usize, 4 * point[0]) & and_value;
const j = @floatToInt(usize, 4 * point[2]) & and_value;
const k = @floatToInt(usize, 4 * point[1]) & and_value;
return self.rand_float[@intCast(usize, self.perm_x[i] ^ self.perm_y[j] ^ self.perm_z[k])];
}
pub fn smoothNoise(self: Perlin, comptime PointType: type, point: [3]PointType) NoiseFloat {
comptime {
const info = @typeInfo(PointType);
switch (info) {
.Float => {},
else => @compileError("PointType must be a float type"),
}
}
var c: [2][2][2]NoiseFloat = undefined;
{
const and_value = point_count - 1;
const i = @floatToInt(usize, @floor(point[0]));
const j = @floatToInt(usize, @floor(point[1]));
const k = @floatToInt(usize, @floor(point[2]));
var di: usize = 0;
while (di < 2) : (di += 1) {
var dj: usize = 0;
while (dj < 2) : (dj += 1) {
var dk: usize = 0;
while (dk < 2) : (dk += 1) {
c[di][dj][dk] = self.rand_float[
@intCast(
usize,
self.perm_x[(i + di) & and_value] ^
self.perm_y[(j + dj) & and_value] ^
self.perm_z[(k + dk) & and_value],
)
];
}
}
}
}
const u = blk: {
const tmp = point[0] - @floor(point[0]);
break :blk tmp * tmp * (3 - 2 * tmp);
};
const v = blk: {
const tmp = point[1] - @floor(point[1]);
break :blk tmp * tmp * (3 - 2 * tmp);
};
const w = blk: {
const tmp = point[2] - @floor(point[2]);
break :blk tmp * tmp * (3 - 2 * tmp);
};
// perform trilinear filtering
var accum: NoiseFloat = 0;
{
var i: usize = 0;
while (i < 2) : (i += 1) {
const fi = @intToFloat(NoiseFloat, i);
var j: usize = 0;
while (j < 2) : (j += 1) {
const fj = @intToFloat(NoiseFloat, j);
var k: usize = 0;
while (k < 2) : (k += 1) {
const fk = @intToFloat(NoiseFloat, k);
accum += (fi * u + (1 - fi) * (1 - u)) *
(fj * v + (1 - fj) * (1 - v)) *
(fk * w + (1 - fk) * (1 - w)) * c[i][j][k];
}
}
}
}
return accum;
}
};
}
|
0 | repos/zig_vulkan/src/modules/voxel_rt | repos/zig_vulkan/src/modules/voxel_rt/brick/Grid.zig | // This file contains an implementaion of "Real-time Ray tracing and Editing of Large Voxel Scenes"
// source: https://dspace.library.uu.nl/handle/1874/315917
const std = @import("std");
const math = std.math;
const Allocator = std.mem.Allocator;
const ArrayList = std.ArrayList;
const State = @import("State.zig");
const AtomicCount = State.AtomicCount;
const Worker = @import("Worker.zig");
pub const Config = struct {
// Default value is all bricks
brick_alloc: ?usize = null,
base_t: f32 = 0.01,
min_point: [3]f32 = [_]f32{ 0.0, 0.0, 0.0 },
scale: f32 = 1.0,
material_indices_per_brick: usize = 256,
workers_count: usize = 4,
};
const BrickGrid = @This();
allocator: Allocator,
// grid state that is shared with the workers
state: *State,
worker_threads: []std.Thread,
workers: []Worker,
/// Initialize a BrickGrid that can be raytraced
/// @param:
/// - allocator: used to allocate bricks and the grid, also to clean up these in deinit
/// - dim_x: how many bricks *maps* (or chunks) in x dimension
/// - dim_y: how many bricks *maps* (or chunks) in y dimension
/// - dim_z: how many bricks *maps* (or chunks) in z dimension
/// - config: config options for the brickmap
pub fn init(allocator: Allocator, dim_x: u32, dim_y: u32, dim_z: u32, config: Config) !BrickGrid {
std.debug.assert(config.workers_count > 0);
std.debug.assert(dim_x * dim_y * dim_z > 0);
const brick_count = dim_x * dim_y * dim_z;
const higher_dim_x = @intToFloat(f64, dim_x) * 0.25;
const higher_dim_y = @intToFloat(f64, dim_y) * 0.25;
const higher_dim_z = @intToFloat(f64, dim_z) * 0.25;
const higher_order_grid = try allocator.alloc(u8, @floatToInt(usize, @ceil(higher_dim_x * higher_dim_y * higher_dim_z)));
errdefer allocator.free(higher_order_grid);
std.mem.set(u8, higher_order_grid, 0);
// each mask has 32 entries
const brick_statuses = try allocator.alloc(State.BrickStatusMask, (std.math.divCeil(u32, brick_count, 32) catch unreachable));
errdefer allocator.free(brick_statuses);
std.mem.set(State.BrickStatusMask, brick_statuses, .{ .bits = 0 });
const brick_indices = try allocator.alloc(State.BrickIndex, brick_count);
errdefer allocator.free(brick_indices);
std.mem.set(State.BrickIndex, brick_indices, 0);
const brick_alloc = config.brick_alloc orelse brick_count;
const bricks = try allocator.alloc(State.Brick, brick_alloc);
errdefer allocator.free(bricks);
std.mem.set(State.Brick, bricks, .{ .solid_mask = 0, .index_type = .voxel_start_index, .index = 0 });
const material_indices = try allocator.alloc(u8, bricks.len * math.min(512, config.material_indices_per_brick));
errdefer allocator.free(material_indices);
std.mem.set(u8, material_indices, 0);
const min_point_base_t = blk: {
const min_point = config.min_point;
const base_t = config.base_t;
var result: [4]f32 = undefined;
std.mem.copy(f32, &result, &min_point);
result[3] = base_t;
break :blk result;
};
const max_point_scale = blk: {
var result = [4]f32{
min_point_base_t[0] + @intToFloat(f32, dim_x) * config.scale,
min_point_base_t[1] + @intToFloat(f32, dim_y) * config.scale,
min_point_base_t[2] + @intToFloat(f32, dim_z) * config.scale,
config.scale,
};
break :blk result;
};
const state = try allocator.create(State);
errdefer allocator.destroy(state);
// initialize all delta structures
// these are used to track changes that should be pushed to GPU
var higher_order_grid_delta = try allocator.create(State.DeviceDataDelta);
errdefer allocator.destroy(higher_order_grid_delta);
higher_order_grid_delta.* = State.DeviceDataDelta.init();
var brick_statuses_deltas = try allocator.alloc(State.DeviceDataDelta, config.workers_count);
errdefer allocator.free(brick_statuses_deltas);
std.mem.set(State.DeviceDataDelta, brick_statuses_deltas, State.DeviceDataDelta.init());
var brick_indices_deltas = try allocator.alloc(State.DeviceDataDelta, config.workers_count);
errdefer allocator.free(brick_indices_deltas);
std.mem.set(State.DeviceDataDelta, brick_indices_deltas, State.DeviceDataDelta.init());
const bricks_delta = State.DeviceDataDelta.init();
var material_indices_deltas = try allocator.alloc(State.DeviceDataDelta, config.workers_count);
errdefer allocator.free(material_indices_deltas);
std.mem.set(State.DeviceDataDelta, material_indices_deltas, State.DeviceDataDelta.init());
const work_segment_size = try std.math.divCeil(u32, dim_x, @intCast(u32, config.workers_count));
state.* = .{
.higher_order_grid_delta = higher_order_grid_delta,
.material_indices_deltas = material_indices_deltas,
.higher_order_grid_mutex = .{},
.higher_order_grid = higher_order_grid,
.brick_statuses = brick_statuses,
.brick_indices = brick_indices,
.brick_statuses_deltas = brick_statuses_deltas,
.brick_indices_deltas = brick_indices_deltas,
.bricks_delta = bricks_delta,
.bricks = bricks,
.material_indices = material_indices,
.active_bricks = AtomicCount.init(0),
.work_segment_size = work_segment_size,
.device_state = State.Device{
.voxel_dim_x = dim_x * 8,
.voxel_dim_y = dim_y * 8,
.voxel_dim_z = dim_z * 8,
.dim_x = dim_x,
.dim_y = dim_y,
.dim_z = dim_z,
.higher_dim_x = @floatToInt(u32, higher_dim_x),
.higher_dim_y = @floatToInt(u32, higher_dim_y),
.higher_dim_z = @floatToInt(u32, higher_dim_z),
.min_point_base_t = min_point_base_t,
.max_point_scale = max_point_scale,
},
};
var workers = try allocator.alloc(Worker, config.workers_count);
errdefer allocator.free(workers);
var worker_threads = try allocator.alloc(std.Thread, config.workers_count);
errdefer allocator.free(worker_threads);
for (worker_threads, 0..) |*thread, i| {
workers[i] = try Worker.init(i, config.workers_count, state, allocator, 4096);
thread.* = try std.Thread.spawn(.{}, Worker.work, .{&workers[i]});
}
return BrickGrid{
.allocator = allocator,
.state = state,
.worker_threads = worker_threads,
.workers = workers,
};
}
/// Clean up host memory, does not account for device
pub fn deinit(self: BrickGrid) void {
// signal each worker to finish
for (self.workers) |*worker| {
// signal shutdown
worker.*.shutdown.store(true, .SeqCst);
// signal worker to wake up from idle state
worker.wake_event.signal();
}
// wait for each worker thread to finish
for (self.worker_threads) |thread| {
thread.join();
}
self.allocator.free(self.state.higher_order_grid);
self.allocator.free(self.state.brick_statuses);
self.allocator.free(self.state.brick_indices);
self.allocator.free(self.state.bricks);
self.allocator.free(self.state.material_indices);
self.allocator.destroy(self.state.higher_order_grid_delta);
self.allocator.free(self.state.brick_statuses_deltas);
self.allocator.free(self.state.brick_indices_deltas);
self.allocator.free(self.state.material_indices_deltas);
self.allocator.free(self.worker_threads);
self.allocator.free(self.workers);
self.allocator.destroy(self.state);
}
/// Force workers to sleep.
/// Can be useful if spurvious changes to the grid cause thread contention
pub fn sleepWorkers(self: *BrickGrid) void {
for (self.workers) |*worker| {
worker.*.sleep.store(true, .SeqCst);
}
}
/// Wake workers after forcing sleep.
pub fn wakeWorkers(self: *BrickGrid) void {
for (self.workers) |*worker| {
worker.*.sleep.store(false, .SeqCst);
worker.*.wake_event.signal();
}
}
/// Asynchrounsly (thread safe) insert a brick at coordinate x y z
/// this function will cause panics if you insert out of bounds
/// currently no way of checking if insert completes
pub fn insert(self: *BrickGrid, x: usize, y: usize, z: usize, material_index: u8) void {
// find a workers that should be assigned insert
const worker_index = blk: {
const grid_x = x / 8;
break :blk @min(grid_x / self.state.work_segment_size, self.workers.len - 1);
};
self.workers[worker_index].registerJob(Worker.Job{ .insert = .{
.x = x,
.y = y,
.z = z,
.material_index = material_index,
} });
}
|
0 | repos/zig_vulkan/src/modules/voxel_rt | repos/zig_vulkan/src/modules/voxel_rt/brick/Worker.zig | const std = @import("std");
const Allocator = std.mem.Allocator;
const Mutex = std.Thread.Mutex;
const Condition = std.Thread.Condition;
const tracy = @import("ztracy");
const State = @import("State.zig");
const BucketStorage = @import("BucketStorage.zig");
/// Parallel workers that does insert and remove work on the grid
/// each worker get one kernel thread
const Worker = @This();
/// a FIFO queue of jobs for a given worker
const JobQueue = std.fifo.LinearFifo(Job, .Dynamic);
const Signal = std.atomic.Atomic(bool);
pub const Insert = struct { x: usize, y: usize, z: usize, material_index: u8 };
pub const JobTag = enum {
insert,
// remove,
};
pub const Job = union(JobTag) {
insert: Insert,
// remove: struct {
// x: usize,
// y: usize,
// z: usize,
// },
};
allocator: Allocator,
id: usize,
grid: *State,
// used to assign material index to a given brick
bucket_storage: BucketStorage,
wake_mutex: Mutex,
wake_event: Condition,
job_mutex: Mutex,
job_queue: *JobQueue,
sleep: Signal,
shutdown: Signal,
pub fn init(id: usize, worker_count: usize, grid: *State, allocator: Allocator, initial_queue_capacity: usize) !Worker {
std.debug.assert(worker_count != 0);
var job_queue = try allocator.create(JobQueue);
job_queue.* = JobQueue.init(allocator);
errdefer job_queue.deinit();
try job_queue.ensureTotalCapacity(initial_queue_capacity);
// calculate bricks in this worker's bucket
const bucket_storage = blk: {
var brick_count = std.math.divFloor(usize, grid.bricks.len, worker_count) catch unreachable; // assert(worker_count != 0)
var material_count = std.math.divFloor(usize, grid.material_indices.len, worker_count) catch unreachable;
const start_index = @intCast(u32, material_count * id);
if (id == worker_count - 1) {
brick_count += std.math.rem(usize, grid.bricks.len, worker_count) catch unreachable;
material_count += std.math.rem(usize, grid.material_indices.len, worker_count) catch unreachable;
}
break :blk try BucketStorage.init(allocator, start_index, material_count, brick_count);
};
errdefer bucket_storage.deinit();
return Worker{
.allocator = allocator,
.id = id,
.grid = grid,
.bucket_storage = bucket_storage,
.wake_mutex = .{},
.wake_event = .{},
.job_mutex = .{},
.job_queue = job_queue,
.sleep = Signal.init(false),
.shutdown = Signal.init(false),
};
}
pub fn registerJob(self: *Worker, job: Job) void {
self.job_mutex.lock();
self.job_queue.writeItem(job) catch {}; // TODO: report error somehow?
self.job_mutex.unlock();
if (self.sleep.load(.SeqCst) == false) {
self.wake_event.signal();
}
}
pub fn work(self: *Worker) void {
// do not create a thread name if it will not be used
const c_thread_name: [:0]const u8 = blk: {
if (tracy.enabled) {
// create thread name
var thread_name_buffer: [32:0]u8 = undefined;
const thread_name = std.fmt.bufPrint(thread_name_buffer[0..], "worker {d}", .{self.id}) catch std.debug.panic("failed to print thread name", .{});
break :blk std.cstr.addNullByte(self.allocator, thread_name) catch std.debug.panic("failed to add '0' sentinel", .{});
} else {
break :blk "worker";
}
};
defer if (tracy.enabled) self.allocator.free(c_thread_name);
tracy.SetThreadName(c_thread_name);
const worker_zone = tracy.ZoneN(@src(), "grid work");
defer worker_zone.End();
life_loop: while (self.shutdown.load(.SeqCst) == false) {
self.job_mutex.lock();
if (self.sleep.load(.SeqCst) == false) {
var i: usize = 0;
work_loop: while (self.job_queue.*.readItem()) |job| {
self.job_mutex.unlock();
switch (job) {
.insert => |insert_job| {
self.performInsert(insert_job);
},
}
self.job_mutex.lock();
i += 1;
if (self.shutdown.load(.SeqCst)) break :life_loop;
if (self.sleep.load(.SeqCst)) break :work_loop;
}
}
defer self.job_mutex.unlock();
self.wake_event.wait(&self.job_mutex);
}
self.job_queue.deinit();
self.allocator.destroy(self.job_queue);
self.bucket_storage.deinit();
}
// perform a insert in the grid
fn performInsert(self: *Worker, insert_job: Insert) void {
const actual_y = self.grid.device_state.voxel_dim_y - 1 - insert_job.y;
const grid_index = gridAt(self.grid.*.device_state, insert_job.x, actual_y, insert_job.z);
const brick_status_index = grid_index / 32;
const brick_status_offset = @intCast(u5, (grid_index % 32));
const brick_status = self.grid.brick_statuses[brick_status_index].read(brick_status_offset);
const brick_index = blk: {
if (brick_status == .loaded) {
break :blk self.grid.brick_indices[grid_index];
}
// if entry is empty we need to populate the entry first
const higher_grid_index = higherGridAt(self.grid.*.device_state, insert_job.x, actual_y, insert_job.z);
self.grid.higher_order_grid_mutex.lock();
self.grid.*.higher_order_grid[higher_grid_index] += 1;
self.grid.higher_order_grid_mutex.unlock();
self.grid.higher_order_grid_delta.registerDelta(higher_grid_index);
// atomically fetch previous brick count and then add 1 to count
break :blk self.grid.*.active_bricks.fetchAdd(1, .Monotonic);
};
var brick = self.grid.bricks[brick_index];
// set the voxel to exist
const nth_bit = voxelAt(insert_job.x, actual_y, insert_job.z);
// set the color information for the given voxel
{
// shift material position voxels that are after this voxel
const voxels_in_brick = countBits(brick.solid_mask, 512);
// TODO: error
const bucket = self.bucket_storage.getBrickBucket(brick_index, voxels_in_brick, self.grid.*.material_indices) catch {
std.debug.panic("at {d} {d} {d} no more buckets", .{ insert_job.x, insert_job.y, insert_job.z });
};
// set the brick's material index
brick.index = @intCast(u31, bucket.start_index);
// move all color data
const bits_before = countBits(brick.solid_mask, nth_bit);
const new_voxel_material_index = bucket.start_index + bits_before;
const voxel_was_set: bool = (brick.solid_mask & @as(u512, 1) << nth_bit) != 0;
if (voxel_was_set == false) {
var i: u32 = voxels_in_brick;
while (i > bits_before) {
const base_index = bucket.start_index + i;
self.grid.*.material_indices[base_index] = self.grid.material_indices[base_index - 1];
i -= 1;
}
}
self.grid.*.material_indices[new_voxel_material_index] = insert_job.material_index;
// always register that the current voxel material has changed
const delta_from = new_voxel_material_index;
// we need to sync all of the voxel material data between current and last brick voxel since it has been shifted
const delta_to = if (voxel_was_set) new_voxel_material_index else new_voxel_material_index + (voxels_in_brick - bits_before);
self.grid.material_indices_deltas[self.id].registerDeltaRange(delta_from, delta_to);
// material indices is stored as 31bit on GPU and 8bit on CPU
// we divide by for to store the correct *GPU* index
brick.index /= 4;
}
// set voxel
brick.solid_mask |= @as(u512, 1) << nth_bit;
// store brick changes
self.grid.*.bricks[brick_index] = brick;
self.grid.bricks_delta.registerDelta(brick_index);
// set the brick as loaded
self.grid.brick_statuses[brick_status_index].write(.loaded, brick_status_offset);
self.grid.brick_statuses_deltas[self.id].registerDelta(brick_status_index);
// register brick index
self.grid.brick_indices[grid_index] = brick_index;
self.grid.brick_indices_deltas[self.id].registerDelta(grid_index);
}
// TODO: test
/// get brick index from global index coordinates
inline fn voxelAt(x: usize, y: usize, z: usize) u9 {
const brick_x: usize = @rem(x, 8);
const brick_y: usize = @rem(y, 8);
const brick_z: usize = @rem(z, 8);
return @intCast(u9, brick_x + 8 * (brick_z + 8 * brick_y));
}
/// get grid index from global index coordinates
inline fn gridAt(device_state: State.Device, x: usize, y: usize, z: usize) usize {
const grid_x: u32 = @intCast(u32, x / 8);
const grid_y: u32 = @intCast(u32, y / 8);
const grid_z: u32 = @intCast(u32, z / 8);
return @intCast(usize, grid_x + device_state.dim_x * (grid_z + device_state.dim_z * grid_y));
}
/// get higher grid index from global index coordinates
inline fn higherGridAt(device_state: State.Device, x: usize, y: usize, z: usize) usize {
const higher_grid_x: u32 = @intCast(u32, x / (8 * 4));
const higher_grid_y: u32 = @intCast(u32, y / (8 * 4));
const higher_grid_z: u32 = @intCast(u32, z / (8 * 4));
return @intCast(usize, higher_grid_x + device_state.higher_dim_x * (higher_grid_z + device_state.higher_dim_z * higher_grid_y));
}
/// count the set bits of a u512, up to range_to (exclusive)
inline fn countBits(bits: u512, range_to: u32) u32 {
var bit = bits;
var count: u512 = 0;
var i: u32 = 0;
while (i < range_to and bit != 0) : (i += 1) {
count += bit & 1;
bit = bit >> 1;
}
return @intCast(u32, count);
}
|
0 | repos/zig_vulkan/src/modules/voxel_rt | repos/zig_vulkan/src/modules/voxel_rt/brick/State.zig | const std = @import("std");
const Mutex = std.Thread.Mutex;
const BucketStorage = @import("./BucketStorage.zig");
pub const AtomicCount = std.atomic.Atomic(u32);
/// type used to record changes in host/device buffers in order to only send changed data to the gpu
pub const DeviceDataDelta = struct {
const DeltaState = enum {
invalid,
inactive,
active,
};
mutex: Mutex,
state: DeltaState,
from: usize,
to: usize,
pub fn init() DeviceDataDelta {
return DeviceDataDelta{
.mutex = .{},
.state = .inactive,
.from = 0,
.to = 0,
};
}
pub fn resetDelta(self: *DeviceDataDelta) void {
self.state = .inactive;
self.from = std.math.maxInt(usize);
self.to = std.math.minInt(usize);
}
pub fn registerDelta(self: *DeviceDataDelta, delta_index: usize) void {
self.mutex.lock();
defer self.mutex.unlock();
self.state = .active;
self.from = std.math.min(self.from, delta_index);
self.to = std.math.max(self.to, delta_index + 1);
}
/// register a delta range
pub fn registerDeltaRange(self: *DeviceDataDelta, from: usize, to: usize) void {
self.mutex.lock();
defer self.mutex.unlock();
self.state = .active;
self.from = std.math.min(self.from, from);
self.to = std.math.max(self.to, to + 1);
}
};
// uniform binding: 2
pub const Device = extern struct {
// how many voxels in each axis
voxel_dim_x: u32,
voxel_dim_y: u32,
voxel_dim_z: u32,
// how many bricks in each axis
dim_x: u32,
dim_y: u32,
dim_z: u32,
// how many higher order entries in each axis
higher_dim_x: u32,
higher_dim_y: u32,
higher_dim_z: u32,
padding1: u32 = 0,
padding2: u32 = 0,
padding3: u32 = 0,
// holds the min point, and the base t advance
// base t advance dictate the minimum stretch of distance a ray can go for each iteration
// at 0.1 it will move atleast 10% of a given voxel
min_point_base_t: [4]f32,
// holds the max_point, and the brick scale
max_point_scale: [4]f32,
};
// pub const Unloaded = packed struct {
// lod_color: u24,
// flags: u6,
// };
pub const BrickStatusMask = extern struct {
pub const Status = enum(u2) {
empty = 0,
loaded = 1,
};
bits: c_uint,
pub fn write(self: *BrickStatusMask, state: Status, at: u5) void {
// zero out bits
self.bits &= ~(@as(u32, 0b1) << at);
self.bits |= @intCast(u32, @enumToInt(state)) << at;
}
pub fn read(self: BrickStatusMask, at: u5) Status {
var bits = self.bits;
bits &= @as(u32, 0b1) << at;
bits = bits >> at;
return @intToEnum(Status, @intCast(u2, bits));
}
};
pub const BrickIndex = c_uint;
pub const Brick = packed struct {
const IndexType = enum(u1) {
voxel_start_index,
brick_lod_index,
};
/// maps to a voxel grid of 8x8x8
solid_mask: u512,
index: u31,
index_type: IndexType,
};
const State = @This();
higher_order_grid_mutex: Mutex,
higher_order_grid_delta: *DeviceDataDelta,
/// used to accelerate ray traversal over large empty distances
/// a entry is used to check if any brick in a 4x4x4 segment should be checked for hits or if nothing is set
higher_order_grid: []u8,
brick_statuses: []BrickStatusMask,
brick_statuses_deltas: []DeviceDataDelta,
brick_indices: []BrickIndex,
brick_indices_deltas: []DeviceDataDelta,
// we keep a single bricks delta structure since active_bricks is shared
bricks_delta: DeviceDataDelta,
bricks: []Brick,
material_indices_deltas: []DeviceDataDelta,
// assigned through a bucket
material_indices: []u8,
/// how many bricks are used in the grid, keep in mind that this is used in a multithread context
active_bricks: AtomicCount,
device_state: Device,
// used to determine which worker is scheduled a job
work_segment_size: usize,
|
0 | repos/zig_vulkan/src/modules/voxel_rt | repos/zig_vulkan/src/modules/voxel_rt/brick/BucketStorage.zig | const std = @import("std");
const ArrayList = std.ArrayList;
const Allocator = std.mem.Allocator;
const IndexMapContext = struct {
pub fn hash(self: IndexMapContext, key: usize) u64 {
_ = self;
return @intCast(u64, key);
}
pub fn eql(self: IndexMapContext, a: usize, b: usize) bool {
_ = self;
return a == b;
}
};
const IndexMap = std.HashMap(usize, Index, IndexMapContext, 80);
/// used by the brick grid to pack brick material data closer to eachother
pub const Bucket = struct {
pub const Entry = packed struct {
start_index: u32,
};
free: ArrayList(Entry),
occupied: ArrayList(?Entry),
/// check for any existing null elements to replace before doing a normal append
/// returns index of item
pub inline fn appendOccupied(self: *Bucket, item: Entry) !usize {
// replace first null element with item
for (self.occupied.items, 0..) |elem, i| {
if (elem == null) {
self.occupied.items[i] = item;
return i;
}
}
// append to list if no null item in list
try self.occupied.append(item);
return self.occupied.items.len - 1;
}
};
pub const BucketRequestError = error{
NoSuitableBucket,
};
const BucketStorage = @This();
const bucket_count = 4;
// max bucket is always the size of brick which is 2^9 = 512
const min_2_pow_size = 9 - (bucket_count - 1);
pub const Index = packed struct {
bucket_index: u6,
element_index: u26,
};
allocator: Allocator,
// used to find the active bucked for a given brick index
index: IndexMap,
buckets: [bucket_count]Bucket,
/// init a bucket storage.
/// caller must make sure to call deinit
pub fn init(allocator: Allocator, start_index: u32, material_indices_len: usize, brick_count: usize) !BucketStorage {
std.debug.assert(material_indices_len > 2048);
const segments_2048 = std.math.divFloor(usize, material_indices_len, 2048) catch unreachable;
var buckets: [bucket_count]Bucket = undefined;
var cursor: u32 = start_index;
{ // init first bucket
const inital_index = cursor;
buckets[0] = Bucket{
.free = try ArrayList(Bucket.Entry).initCapacity(allocator, 2 * segments_2048),
.occupied = try ArrayList(?Bucket.Entry).initCapacity(allocator, segments_2048),
};
const bucket_size = try std.math.powi(u32, 2, min_2_pow_size);
var j: usize = 0;
while (j < segments_2048) : (j += 1) {
buckets[0].free.appendAssumeCapacity(.{ .start_index = cursor });
buckets[0].free.appendAssumeCapacity(.{ .start_index = cursor + bucket_size });
cursor += 2048;
}
cursor = inital_index + bucket_size * 2;
}
{
comptime var i: usize = 1;
inline while (i < buckets.len - 1) : (i += 1) {
const inital_index = cursor;
buckets[i] = Bucket{
.free = try ArrayList(Bucket.Entry).initCapacity(allocator, segments_2048),
.occupied = try ArrayList(?Bucket.Entry).initCapacity(allocator, segments_2048 / 2),
};
const bucket_size = try std.math.powi(u32, 2, min_2_pow_size + i);
var j: usize = 0;
while (j < segments_2048) : (j += 1) {
buckets[i].free.appendAssumeCapacity(.{ .start_index = cursor });
cursor += 2048;
}
cursor = inital_index + bucket_size;
}
buckets[buckets.len - 1] = Bucket{
.free = try ArrayList(Bucket.Entry).initCapacity(allocator, segments_2048 * 3),
.occupied = try ArrayList(?Bucket.Entry).initCapacity(allocator, segments_2048),
};
const bucket_size = 512;
var j: usize = 0;
while (j < segments_2048) : (j += 1) {
buckets[buckets.len - 1].free.appendAssumeCapacity(.{ .start_index = cursor });
buckets[buckets.len - 1].free.appendAssumeCapacity(.{ .start_index = cursor + bucket_size });
buckets[buckets.len - 1].free.appendAssumeCapacity(.{ .start_index = cursor + bucket_size * 2 });
cursor += 2048;
}
}
var index = IndexMap.init(allocator);
errdefer index.deinit();
try index.ensureUnusedCapacity(@intCast(u32, brick_count));
return BucketStorage{
.allocator = allocator,
.index = index,
.buckets = buckets,
};
}
// return brick's bucket
// function handles assigning new buckets as needed and will transfer material indices to new slot in the event
// that a new bucket is required
// returns error if there is no more buckets of appropriate size
pub fn getBrickBucket(self: *BucketStorage, brick_index: usize, voxel_count: usize, material_indices: []u8) !Bucket.Entry {
// check if brick already have assigned a bucket
if (self.index.get(brick_index)) |index| {
const bucket_size = try std.math.powi(usize, 2, min_2_pow_size + index.bucket_index);
// if bucket size is sufficent, or if voxel was set before, no change required
if (bucket_size > voxel_count) {
return self.buckets[index.bucket_index].occupied.items[index.element_index].?;
}
// free previous bucket
const previous_bucket = self.buckets[index.bucket_index].occupied.items[index.element_index].?;
try self.buckets[index.bucket_index].free.append(previous_bucket);
self.buckets[index.bucket_index].occupied.items[index.element_index] = null;
// find a bucket with increased size that is free
var i: usize = index.bucket_index + 1;
while (i < self.buckets.len) : (i += 1) {
if (self.buckets[i].free.items.len > 0) {
// do bucket stuff to rel
const bucket = self.buckets[i].free.pop();
const oc_index = try self.buckets[i].appendOccupied(bucket);
try self.index.put(brick_index, Index{
.bucket_index = @intCast(u6, i),
.element_index = @intCast(u26, oc_index),
});
// copy material indices to new bucket
std.mem.copy(u8, material_indices[bucket.start_index..], material_indices[previous_bucket.start_index .. previous_bucket.start_index + bucket_size]);
return bucket;
}
}
} else {
// fetch the smallest free bucket
for (&self.buckets, 0..) |*bucket, i| {
if (bucket.free.items.len > 0) {
const take = bucket.free.pop();
const oc_index = try bucket.appendOccupied(take);
try self.index.put(brick_index, Index{
.bucket_index = @intCast(u6, i),
.element_index = @intCast(u26, oc_index),
});
return take;
}
}
}
return BucketRequestError.NoSuitableBucket; // no free bucket big enough to store brick color data
}
pub inline fn deinit(self: *BucketStorage) void {
self.index.deinit();
for (self.buckets) |bucket| {
bucket.free.deinit();
bucket.occupied.deinit();
}
}
|
0 | repos/zig_vulkan/src/modules | repos/zig_vulkan/src/modules/render/physical_device.zig | /// Abstractions around vulkan physical device
const std = @import("std");
const Allocator = std.mem.Allocator;
const ArrayList = std.ArrayList;
const vk = @import("vulkan");
const dispatch = @import("dispatch.zig");
const constants = @import("consts.zig");
const swapchain = @import("swapchain.zig");
const vk_utils = @import("vk_utils.zig");
const validation_layer = @import("validation_layer.zig");
const Context = @import("Context.zig");
pub const QueueFamilyIndices = struct {
compute: u32,
compute_queue_count: u32,
graphics: u32,
present: u32,
// TODO: use internal allocator that is suitable
/// Initialize a QueueFamilyIndices instance, internal allocation is handled by QueueFamilyIndices (no manuall cleanup)
pub fn init(allocator: Allocator, vki: dispatch.Instance, physical_device: vk.PhysicalDevice, surface: vk.SurfaceKHR) !QueueFamilyIndices {
var queue_family_count: u32 = 0;
vki.getPhysicalDeviceQueueFamilyProperties(physical_device, &queue_family_count, null);
var queue_families = try allocator.alloc(vk.QueueFamilyProperties, queue_family_count);
defer allocator.free(queue_families);
vki.getPhysicalDeviceQueueFamilyProperties(physical_device, &queue_family_count, queue_families.ptr);
queue_families.len = queue_family_count;
const compute_bit = vk.QueueFlags{
.compute_bit = true,
};
const graphics_bit = vk.QueueFlags{
.graphics_bit = true,
};
var compute_index: ?u32 = null;
var compute_queue_count: u32 = 0;
var graphics_index: ?u32 = null;
var present_index: ?u32 = null;
for (queue_families, 0..) |queue_family, i| {
const index = @intCast(u32, i);
if (compute_index == null and queue_family.queue_flags.contains(compute_bit)) {
compute_index = index;
compute_queue_count = queue_family.queue_count;
}
if (graphics_index == null and queue_family.queue_flags.contains(graphics_bit)) {
graphics_index = index;
}
if (present_index == null and (try vki.getPhysicalDeviceSurfaceSupportKHR(physical_device, index, surface)) == vk.TRUE) {
present_index = index;
}
}
if (compute_index == null) {
return error.ComputeIndexMissing;
}
if (graphics_index == null) {
return error.GraphicsIndexMissing;
}
if (present_index == null) {
return error.PresentIndexMissing;
}
return QueueFamilyIndices{
.compute = compute_index.?,
.compute_queue_count = compute_queue_count,
.graphics = graphics_index.?,
.present = present_index.?,
};
}
};
/// check if physical device supports given target extensions
// TODO: unify with getRequiredInstanceExtensions?
pub fn isDeviceExtensionsPresent(allocator: Allocator, vki: dispatch.Instance, device: vk.PhysicalDevice, target_extensions: []const [*:0]const u8) !bool {
// query extensions available
var supported_extensions_count: u32 = 0;
// TODO: handle "VkResult.incomplete"
_ = try vki.enumerateDeviceExtensionProperties(device, null, &supported_extensions_count, null);
var extensions = try ArrayList(vk.ExtensionProperties).initCapacity(allocator, supported_extensions_count);
defer extensions.deinit();
_ = try vki.enumerateDeviceExtensionProperties(device, null, &supported_extensions_count, extensions.items.ptr);
extensions.items.len = supported_extensions_count;
var matches: u32 = 0;
for (target_extensions) |target_extension| {
cmp: for (extensions.items) |existing| {
const existing_name = @ptrCast([*:0]const u8, &existing.extension_name);
if (std.cstr.cmp(target_extension, existing_name) == 0) {
matches += 1;
break :cmp;
}
}
}
return matches == target_extensions.len;
}
// TODO: use internal allocator that is suitable
/// select primary physical device in init
pub fn selectPrimary(allocator: Allocator, vki: dispatch.Instance, instance: vk.Instance, surface: vk.SurfaceKHR) !vk.PhysicalDevice {
var device_count: u32 = 0;
_ = try vki.enumeratePhysicalDevices(instance, &device_count, null); // TODO: handle incomplete
if (device_count < 0) {
std.debug.panic("no GPU suitable for vulkan identified");
}
var devices = try allocator.alloc(vk.PhysicalDevice, device_count);
defer allocator.free(devices);
_ = try vki.enumeratePhysicalDevices(instance, &device_count, devices.ptr); // TODO: handle incomplete
devices.len = device_count;
var device_score: i32 = -1;
var device_index: ?usize = null;
for (devices, 0..) |device, i| {
const new_score = try deviceHeuristic(allocator, vki, device, surface);
if (device_score < new_score) {
device_score = new_score;
device_index = i;
}
}
if (device_index == null) {
return error.NoSuitablePhysicalDevice;
}
const val = devices[device_index.?];
return val;
}
/// Any suiteable GPU should result in a positive value, an unsuitable GPU might return a negative value
fn deviceHeuristic(allocator: Allocator, vki: dispatch.Instance, device: vk.PhysicalDevice, surface: vk.SurfaceKHR) !i32 {
// TODO: rewrite function to have clearer distinction between required and bonus features
// possible solutions:
// - return error if missing feature and discard negative return value (use u32 instead)
// - 2 bitmaps
const property_score = blk: {
const device_properties = vki.getPhysicalDeviceProperties(device);
const discrete = @as(i32, @boolToInt(device_properties.device_type == vk.PhysicalDeviceType.discrete_gpu)) + 5;
break :blk discrete;
};
const feature_score = blk: {
const device_features = vki.getPhysicalDeviceFeatures(device);
const atomics = @intCast(i32, device_features.fragment_stores_and_atomics) * 5;
const anisotropy = @intCast(i32, device_features.sampler_anisotropy) * 5;
break :blk atomics + anisotropy;
};
const queue_fam_score: i32 = blk: {
_ = QueueFamilyIndices.init(allocator, vki, device, surface) catch break :blk -1000;
break :blk 10;
};
const extensions_score: i32 = blk: {
const extension_slice = constants.logical_device_extensions[0..];
const extensions_available = try isDeviceExtensionsPresent(allocator, vki, device, extension_slice);
if (!extensions_available) {
break :blk -1000;
}
break :blk 10;
};
const swapchain_score: i32 = blk: {
if (swapchain.SupportDetails.init(allocator, vki, device, surface)) |ok| {
defer ok.deinit(allocator);
break :blk 10;
} else |_| {
break :blk -1000;
}
};
return -30 + property_score + feature_score + queue_fam_score + extensions_score + swapchain_score;
}
pub fn createLogicalDevice(allocator: Allocator, ctx: Context) !vk.Device {
// merge indices if they are identical according to vulkan spec
var family_indices = [3]u32{ ctx.queue_indices.graphics, undefined, undefined };
var indices: usize = 1;
if (ctx.queue_indices.graphics != ctx.queue_indices.present) {
family_indices[indices] = ctx.queue_indices.present;
indices += 1;
}
if (ctx.queue_indices.compute != ctx.queue_indices.graphics and ctx.queue_indices.compute != ctx.queue_indices.present) {
family_indices[indices] = ctx.queue_indices.compute;
indices += 1;
}
var queue_create_infos = try allocator.alloc(vk.DeviceQueueCreateInfo, indices);
defer allocator.free(queue_create_infos);
const queue_priority = [_]f32{1.0};
for (family_indices[0..indices], 0..) |family_index, i| {
queue_create_infos[i] = .{
.flags = .{},
.queue_family_index = family_index,
.queue_count = if (family_index == ctx.queue_indices.compute) ctx.queue_indices.compute_queue_count else 1,
.p_queue_priorities = &queue_priority,
};
}
const device_features = vk.PhysicalDeviceFeatures{};
const validation_layer_info = try validation_layer.Info.init(allocator, ctx.vkb);
const create_info = vk.DeviceCreateInfo{
.flags = .{},
.queue_create_info_count = @intCast(u32, queue_create_infos.len),
.p_queue_create_infos = queue_create_infos.ptr,
.enabled_layer_count = validation_layer_info.enabled_layer_count,
.pp_enabled_layer_names = validation_layer_info.enabled_layer_names,
.enabled_extension_count = constants.logical_device_extensions.len,
.pp_enabled_extension_names = &constants.logical_device_extensions,
.p_enabled_features = @ptrCast(*const vk.PhysicalDeviceFeatures, &device_features),
};
return ctx.vki.createDevice(ctx.physical_device, &create_info, null);
}
|
0 | repos/zig_vulkan/src/modules | repos/zig_vulkan/src/modules/render/pipeline.zig | const std = @import("std");
const Allocator = std.mem.Allocator;
const vk = @import("vulkan");
const swapchain = @import("swapchain.zig");
const utils = @import("../utils.zig");
const Context = @import("Context.zig");
pub fn createFramebuffers(allocator: Allocator, ctx: Context, swapchain_data: *const swapchain.Data, render_pass: vk.RenderPass, prev_framebuffer: ?[]vk.Framebuffer) ![]vk.Framebuffer {
const image_views = swapchain_data.image_views;
var framebuffers = prev_framebuffer orelse try allocator.alloc(vk.Framebuffer, image_views.len);
for (image_views, 0..) |view, i| {
const attachments = [_]vk.ImageView{
view,
};
const framebuffer_info = vk.FramebufferCreateInfo{
.flags = .{},
.render_pass = render_pass,
.attachment_count = attachments.len,
.p_attachments = &attachments,
.width = swapchain_data.extent.width,
.height = swapchain_data.extent.height,
.layers = 1,
};
const framebuffer = try ctx.vkd.createFramebuffer(ctx.logical_device, &framebuffer_info, null);
framebuffers[i] = framebuffer;
}
return framebuffers;
}
pub fn loadShaderStage(
ctx: Context,
// TODO: validate and document anytype here
shader_code: anytype,
stage: vk.ShaderStageFlags,
specialization: ?*const vk.SpecializationInfo,
) !vk.PipelineShaderStageCreateInfo {
const create_info = vk.ShaderModuleCreateInfo{
.flags = .{},
.p_code = @ptrCast([*]const u32, &shader_code),
.code_size = shader_code.len,
};
const module = try ctx.vkd.createShaderModule(ctx.logical_device, &create_info, null);
return vk.PipelineShaderStageCreateInfo{
.flags = .{},
.stage = stage,
.module = module,
.p_name = "main",
.p_specialization_info = specialization,
};
}
/// create a command buffers with sizeof buffer_count, caller must deinit returned list
pub fn createCmdBuffers(allocator: Allocator, ctx: Context, command_pool: vk.CommandPool, buffer_count: usize, prev_buffer: ?[]vk.CommandBuffer) ![]vk.CommandBuffer {
var command_buffers = prev_buffer orelse try allocator.alloc(vk.CommandBuffer, buffer_count);
const alloc_info = vk.CommandBufferAllocateInfo{
.command_pool = command_pool,
.level = vk.CommandBufferLevel.primary,
.command_buffer_count = @intCast(u32, buffer_count),
};
try ctx.vkd.allocateCommandBuffers(ctx.logical_device, &alloc_info, command_buffers.ptr);
command_buffers.len = buffer_count;
return command_buffers;
}
/// create a command buffers with sizeof buffer_count, caller must destroy returned buffer with allocator
pub fn createCmdBuffer(ctx: Context, command_pool: vk.CommandPool) !vk.CommandBuffer {
const alloc_info = vk.CommandBufferAllocateInfo{
.command_pool = command_pool,
.level = vk.CommandBufferLevel.primary,
.command_buffer_count = @intCast(u32, 1),
};
var command_buffer: vk.CommandBuffer = undefined;
try ctx.vkd.allocateCommandBuffers(ctx.logical_device, &alloc_info, @ptrCast([*]vk.CommandBuffer, &command_buffer));
return command_buffer;
}
|
0 | repos/zig_vulkan/src/modules | repos/zig_vulkan/src/modules/render/swapchain.zig | const std = @import("std");
const Allocator = std.mem.Allocator;
const ArrayList = std.ArrayList;
const vk = @import("vulkan");
const glfw = @import("glfw");
const dispatch = @import("dispatch.zig");
const physical_device = @import("physical_device.zig");
const QueueFamilyIndices = physical_device.QueueFamilyIndices;
const Context = @import("Context.zig");
const Texture = @import("Texture.zig");
pub const ViewportScissor = struct {
viewport: [1]vk.Viewport,
scissor: [1]vk.Rect2D,
/// utility to create simple view state info
pub fn init(extent: vk.Extent2D) ViewportScissor {
// TODO: this can be broken down a bit since the code is pretty cluster fck
const width = extent.width;
const height = extent.height;
return .{
.viewport = [1]vk.Viewport{
.{ .x = 0, .y = 0, .width = @intToFloat(f32, width), .height = @intToFloat(f32, height), .min_depth = 0.0, .max_depth = 1.0 },
},
.scissor = [1]vk.Rect2D{
.{ .offset = .{
.x = 0,
.y = 0,
}, .extent = extent },
},
};
}
};
// TODO: rename
// TODO: mutex! : the data is shared between rendering implementation and pipeline
// pipeline will attempt to update the data in the event of rescale which might lead to RC
pub const Data = struct {
allocator: Allocator,
swapchain: vk.SwapchainKHR,
images: []vk.Image,
image_views: []vk.ImageView,
format: vk.Format,
extent: vk.Extent2D,
support_details: SupportDetails,
// create a swapchain data struct, caller must make sure to call deinit
pub fn init(allocator: Allocator, ctx: Context, command_pool: vk.CommandPool, old_swapchain: ?vk.SwapchainKHR) !Data {
const support_details = try SupportDetails.init(allocator, ctx.vki, ctx.physical_device, ctx.surface);
errdefer support_details.deinit(allocator);
const sc_create_info = blk1: {
const format = support_details.selectSwapChainFormat();
const present_mode = support_details.selectSwapchainPresentMode();
const extent = try support_details.constructSwapChainExtent(ctx.window_ptr.*);
const max_images = if (support_details.capabilities.max_image_count == 0) std.math.maxInt(u32) else support_details.capabilities.max_image_count;
const image_count = std.math.min(support_details.capabilities.min_image_count + 1, max_images);
const Config = struct {
sharing_mode: vk.SharingMode,
index_count: u32,
p_indices: [*]const u32,
};
const sharing_config = blk2: {
if (ctx.queue_indices.graphics != ctx.queue_indices.present) {
const indices_arr = [_]u32{ ctx.queue_indices.graphics, ctx.queue_indices.present };
break :blk2 Config{
.sharing_mode = .concurrent, // TODO: read up on ownership in this context
.index_count = indices_arr.len,
.p_indices = @ptrCast([*]const u32, &indices_arr[0..indices_arr.len]),
};
} else {
const indices_arr = [_]u32{ ctx.queue_indices.graphics, ctx.queue_indices.present };
break :blk2 Config{
.sharing_mode = .exclusive,
.index_count = 1,
.p_indices = @ptrCast([*]const u32, &indices_arr[0..1]),
};
}
};
break :blk1 vk.SwapchainCreateInfoKHR{
.flags = .{},
.surface = ctx.surface,
.min_image_count = image_count,
.image_format = format.format,
.image_color_space = format.color_space,
.image_extent = extent,
.image_array_layers = 1,
.image_usage = vk.ImageUsageFlags{ .color_attachment_bit = true },
.image_sharing_mode = sharing_config.sharing_mode,
.queue_family_index_count = sharing_config.index_count,
.p_queue_family_indices = sharing_config.p_indices,
.pre_transform = support_details.capabilities.current_transform,
.composite_alpha = vk.CompositeAlphaFlagsKHR{ .opaque_bit_khr = true },
.present_mode = present_mode,
.clipped = vk.TRUE,
.old_swapchain = old_swapchain orelse .null_handle,
};
};
const swapchain_khr = try ctx.vkd.createSwapchainKHR(ctx.logical_device, &sc_create_info, null);
const swapchain_images = blk: {
// TODO: handle incomplete
var image_count: u32 = 0;
_ = try ctx.vkd.getSwapchainImagesKHR(ctx.logical_device, swapchain_khr, &image_count, null);
var images = try allocator.alloc(vk.Image, image_count);
errdefer allocator.free(images);
// TODO: handle incomplete
_ = try ctx.vkd.getSwapchainImagesKHR(ctx.logical_device, swapchain_khr, &image_count, images.ptr);
break :blk images;
};
errdefer allocator.free(swapchain_images);
for (swapchain_images) |image| {
try Texture.transitionImageLayout(ctx, command_pool, image, .undefined, .present_src_khr);
}
const image_views = blk: {
var views = try allocator.alloc(vk.ImageView, swapchain_images.len);
errdefer allocator.free(views);
const components = vk.ComponentMapping{
.r = .identity,
.g = .identity,
.b = .identity,
.a = .identity,
};
const subresource_range = vk.ImageSubresourceRange{
.aspect_mask = .{ .color_bit = true },
.base_mip_level = 0,
.level_count = 1,
.base_array_layer = 0,
.layer_count = 1,
};
for (swapchain_images, 0..) |image, i| {
const create_info = vk.ImageViewCreateInfo{
.flags = .{},
.image = image,
.view_type = .@"2d",
.format = sc_create_info.image_format,
.components = components,
.subresource_range = subresource_range,
};
views[i] = try ctx.vkd.createImageView(ctx.logical_device, &create_info, null);
}
break :blk views;
};
errdefer allocator.free(image_views);
return Data{
.allocator = allocator,
.swapchain = swapchain_khr,
.images = swapchain_images,
.image_views = image_views,
.format = sc_create_info.image_format,
.extent = sc_create_info.image_extent,
.support_details = support_details,
};
}
pub fn deinit(self: Data, ctx: Context) void {
for (self.image_views) |view| {
ctx.vkd.destroyImageView(ctx.logical_device, view, null);
}
self.allocator.free(self.image_views);
self.allocator.free(self.images);
self.support_details.deinit(self.allocator);
ctx.vkd.destroySwapchainKHR(ctx.logical_device, self.swapchain, null);
}
};
pub const SupportDetails = struct {
const Self = @This();
capabilities: vk.SurfaceCapabilitiesKHR,
formats: []vk.SurfaceFormatKHR,
present_modes: []vk.PresentModeKHR,
/// caller has to make sure to also call deinit
pub fn init(allocator: Allocator, vki: dispatch.Instance, device: vk.PhysicalDevice, surface: vk.SurfaceKHR) !Self {
const capabilities = try vki.getPhysicalDeviceSurfaceCapabilitiesKHR(device, surface);
var format_count: u32 = 0;
// TODO: handle incomplete
_ = try vki.getPhysicalDeviceSurfaceFormatsKHR(device, surface, &format_count, null);
if (format_count <= 0) {
return error.NoSurfaceFormatsSupported;
}
const formats = blk: {
var formats = try allocator.alloc(vk.SurfaceFormatKHR, format_count);
_ = try vki.getPhysicalDeviceSurfaceFormatsKHR(device, surface, &format_count, formats.ptr);
formats.len = format_count;
break :blk formats;
};
errdefer allocator.free(formats);
var present_modes_count: u32 = 0;
_ = try vki.getPhysicalDeviceSurfacePresentModesKHR(device, surface, &present_modes_count, null);
if (present_modes_count <= 0) {
return error.NoPresentModesSupported;
}
const present_modes = blk: {
var present_modes = try allocator.alloc(vk.PresentModeKHR, present_modes_count);
_ = try vki.getPhysicalDeviceSurfacePresentModesKHR(device, surface, &present_modes_count, present_modes.ptr);
present_modes.len = present_modes_count;
break :blk present_modes;
};
errdefer allocator.free(present_modes);
return Self{
.capabilities = capabilities,
.formats = formats,
.present_modes = present_modes,
};
}
pub fn selectSwapChainFormat(self: Self) vk.SurfaceFormatKHR {
// TODO: in some cases this is a valid state?
// if so return error here instead ...
std.debug.assert(self.formats.len > 0);
for (self.formats) |format| {
if (format.format == .b8g8r8a8_unorm and format.color_space == .srgb_nonlinear_khr) {
return format;
}
}
return self.formats[0];
}
pub fn selectSwapchainPresentMode(self: Self) vk.PresentModeKHR {
for (self.present_modes) |present_mode| {
if (present_mode == .mailbox_khr) {
return present_mode;
}
}
return .fifo_khr;
}
pub fn constructSwapChainExtent(self: Self, window: glfw.Window) !vk.Extent2D {
if (self.capabilities.current_extent.width != std.math.maxInt(u32)) {
return self.capabilities.current_extent;
} else {
var window_size = blk: {
const size = window.getFramebufferSize();
break :blk vk.Extent2D{ .width = @intCast(u32, size.width), .height = @intCast(u32, size.height) };
};
const clamp = std.math.clamp;
const min = self.capabilities.min_image_extent;
const max = self.capabilities.max_image_extent;
return vk.Extent2D{
.width = clamp(window_size.width, min.width, max.width),
.height = clamp(window_size.height, min.height, max.height),
};
}
}
pub fn deinit(self: Self, allocator: Allocator) void {
allocator.free(self.formats);
allocator.free(self.present_modes);
}
};
|
0 | repos/zig_vulkan/src/modules | repos/zig_vulkan/src/modules/render/StagingRamp.zig | const std = @import("std");
const Allocator = std.mem.Allocator;
const vk = @import("vulkan");
const tracy = @import("ztracy");
const render = @import("../render.zig");
const Context = render.Context;
const GpuBufferMemory = render.GpuBufferMemory;
const Texture = render.Texture;
const memory = render.memory;
pub const buffer_size = 63 * memory.bytes_in_mb;
const DeferBufferTransfer = struct {
ctx: Context,
buffer: *GpuBufferMemory,
offset: vk.DeviceSize,
data: []const u8,
};
/// StagingRamp is a transfer abstraction used to transfer data from host
/// to device local memory (heap 0 memory)
const StagingRamp = @This();
last_buffer_used: usize,
staging_buffers: []StagingBuffer,
wait_all_fences: []vk.Fence,
deferred_buffer_transfers: std.ArrayList(DeferBufferTransfer),
pub fn init(ctx: Context, allocator: Allocator, buffer_count: usize) !StagingRamp {
const staging_buffers = try allocator.alloc(StagingBuffer, buffer_count);
errdefer allocator.free(staging_buffers);
var buffers_initialized: usize = 0;
for (staging_buffers, 0..) |*ramp, i| {
ramp.* = try StagingBuffer.init(ctx, allocator);
buffers_initialized = i + 1;
}
errdefer {
var i: usize = 0;
while (i < buffers_initialized) : (i += 1) {
staging_buffers[i].deinit(ctx);
}
}
const wait_all_fences = try allocator.alloc(vk.Fence, buffer_count);
errdefer allocator.free(wait_all_fences);
return StagingRamp{
.last_buffer_used = 0,
.staging_buffers = staging_buffers,
.wait_all_fences = wait_all_fences,
.deferred_buffer_transfers = std.ArrayList(DeferBufferTransfer).init(allocator),
};
}
pub fn flush(self: *StagingRamp, ctx: Context) !void {
for (self.staging_buffers) |*ramp| {
try ramp.flush(ctx);
}
for (self.deferred_buffer_transfers.items) |transfer| {
try self.transferToBuffer(transfer.ctx, transfer.buffer, transfer.offset, u8, transfer.data);
}
self.deferred_buffer_transfers.clearRetainingCapacity();
}
/// transfer to device image
pub fn transferToImage(
self: *StagingRamp,
ctx: Context,
src_layout: vk.ImageLayout,
dst_layout: vk.ImageLayout,
image: vk.Image,
width: u32,
height: u32,
comptime T: type,
data: []const T,
) !void {
const transfer_zone = tracy.ZoneN(@src(), "schedule images transfer");
defer transfer_zone.End();
// TODO: handle transfers greater than buffer size (split across ramps and frames!)
const index = self.getIdleRamp(ctx, data.len * @sizeOf(T)) catch |err| {
switch (err) {
error.StagingBuffersFull => {
std.debug.panic("TODO: handle image transfer defer", .{});
},
else => return err,
}
};
try self.staging_buffers[index].transferToImage(ctx, src_layout, dst_layout, image, width, height, T, data);
}
/// transfer to device storage buffer
pub fn transferToBuffer(self: *StagingRamp, ctx: Context, buffer: *GpuBufferMemory, offset: vk.DeviceSize, comptime T: type, data: []const T) !void {
const transfer_zone = tracy.ZoneN(@src(), "schedule buffers transfer");
defer transfer_zone.End();
const index = self.getIdleRamp(ctx, data.len * @sizeOf(T)) catch |err| {
switch (err) {
error.StagingBuffersFull => {
// TODO: RC: data might change between transfer call and final flush ...
try self.deferred_buffer_transfers.append(DeferBufferTransfer{
.ctx = ctx,
.buffer = buffer,
.offset = offset,
.data = std.mem.sliceAsBytes(data),
});
return;
},
else => return err,
}
};
try self.staging_buffers[index].transferToBuffer(ctx, buffer, offset, T, data);
}
// wait until all pending transfers are done
pub fn waitIdle(self: StagingRamp, ctx: Context) !void {
for (self.staging_buffers, 0..) |ramp, i| {
self.wait_all_fences[i] = ramp.fence;
}
_ = try ctx.vkd.waitForFences(
ctx.logical_device,
@intCast(u32, self.wait_all_fences.len),
self.wait_all_fences.ptr,
vk.TRUE,
std.math.maxInt(u64),
);
}
pub fn deinit(self: StagingRamp, ctx: Context, allocator: Allocator) void {
for (self.staging_buffers) |*ramp| {
ramp.deinit(ctx);
}
allocator.free(self.staging_buffers);
self.deferred_buffer_transfers.deinit();
allocator.free(self.wait_all_fences);
}
inline fn getIdleRamp(self: *StagingRamp, ctx: Context, size: vk.DeviceSize) !usize {
var full_ramps: usize = 0;
// get a idle buffer
var index: usize = blk: {
for (self.staging_buffers, 0..) |ramp, i| {
// if ramp is out of memory
if (ramp.buffer_cursor + size >= buffer_size) {
full_ramps += 1;
continue;
}
// if ramp is idle
if ((try ctx.vkd.getFenceStatus(ctx.logical_device, ramp.fence)) == .success) {
break :blk i;
}
}
break :blk (self.last_buffer_used + 1) % self.staging_buffers.len;
};
if (full_ramps >= self.staging_buffers.len) {
return error.StagingBuffersFull;
}
defer self.last_buffer_used = index;
// wait for previous transfer
_ = try ctx.vkd.waitForFences(
ctx.logical_device,
1,
@ptrCast([*]const vk.Fence, &self.staging_buffers[index].fence),
vk.TRUE,
std.math.maxInt(u64),
);
return index;
}
const RegionCount = 256;
const BufferCopies = struct {
len: u32,
regions: [RegionCount]vk.BufferCopy,
};
const BufferImageCopy = struct {
image: vk.Image,
src_layout: vk.ImageLayout,
dst_layout: vk.ImageLayout,
region: vk.BufferImageCopy,
};
// TODO: benchmark ArrayHashMap vs HashMap
// we do not need hash cache as the buffer and image type
// are u64 opaque types (so eql is cheap)
/// hash(self, K) u32
/// eql(self, K, K, usize) bool
const BufferCopyMapContext = struct {
pub fn hash(self: BufferCopyMapContext, key: vk.Buffer) u32 {
_ = self;
const v: u64 = @enumToInt(key);
const left_value = (v >> 32) / 4;
const right_value = ((v << 32) >> 32) / 2;
return @intCast(u32, left_value + right_value);
}
pub fn eql(self: BufferCopyMapContext, a: vk.Buffer, b: vk.Buffer, i: usize) bool {
_ = self;
_ = i;
return a == b;
}
};
const BufferCopyMap = std.ArrayHashMap(vk.Buffer, BufferCopies, BufferCopyMapContext, false);
const ImageCopyList = std.ArrayList(BufferImageCopy);
const fence_info = vk.FenceCreateInfo{
.flags = .{
.signaled_bit = true,
},
};
const StagingBuffer = struct {
command_pool: vk.CommandPool,
command_buffer: vk.CommandBuffer,
fence: vk.Fence,
buffer_cursor: vk.DeviceSize,
device_buffer_memory: GpuBufferMemory,
buffer_copy: BufferCopyMap,
image_copy: ImageCopyList,
fn init(ctx: Context, allocator: Allocator) !StagingBuffer {
const device_buffer_memory = try GpuBufferMemory.init(
ctx,
buffer_size,
.{ .transfer_src_bit = true },
.{ .host_visible_bit = true, .host_coherent_bit = true, .device_local_bit = true },
);
errdefer device_buffer_memory.deinit(ctx);
const pool_info = vk.CommandPoolCreateInfo{
.flags = .{ .transient_bit = true },
.queue_family_index = ctx.queue_indices.graphics,
};
const command_pool = try ctx.vkd.createCommandPool(ctx.logical_device, &pool_info, null);
errdefer ctx.vkd.destroyCommandPool(ctx.logical_device, command_pool, null);
const command_buffer = try render.pipeline.createCmdBuffer(ctx, command_pool);
errdefer ctx.vkd.freeCommandBuffers(
ctx.logical_device,
command_pool,
@intCast(u32, 1),
@ptrCast([*]const vk.CommandBuffer, &command_buffer),
);
const fence = try ctx.vkd.createFence(ctx.logical_device, &fence_info, null);
errdefer ctx.vkd.destroyFence(ctx.logical_device, fence, null);
return StagingBuffer{
.command_pool = command_pool,
.command_buffer = command_buffer,
.fence = fence,
.device_buffer_memory = device_buffer_memory,
.buffer_cursor = 0,
.buffer_copy = BufferCopyMap.init(allocator),
.image_copy = ImageCopyList.init(allocator),
};
}
fn transferToImage(
self: *StagingBuffer,
ctx: Context,
src_layout: vk.ImageLayout,
dst_layout: vk.ImageLayout,
image: vk.Image,
width: u32,
height: u32,
comptime T: type,
data: []const T,
) !void {
const data_size = data.len * @sizeOf(T);
try self.device_buffer_memory.map(ctx, self.buffer_cursor, data_size);
defer self.device_buffer_memory.unmap(ctx);
var dest_location = @ptrCast([*]T, @alignCast(@alignOf(T), self.device_buffer_memory.mapped) orelse unreachable);
std.mem.copy(T, dest_location[0..data.len], data);
const region = vk.BufferImageCopy{
.buffer_offset = self.buffer_cursor,
.buffer_row_length = 0,
.buffer_image_height = 0,
.image_subresource = vk.ImageSubresourceLayers{
.aspect_mask = .{
.color_bit = true,
},
.mip_level = 0,
.base_array_layer = 0,
.layer_count = 1,
},
.image_offset = .{
.x = 0,
.y = 0,
.z = 0,
},
.image_extent = .{
.width = width,
.height = height,
.depth = 1,
},
};
try self.image_copy.append(BufferImageCopy{
.image = image,
.src_layout = src_layout,
.dst_layout = dst_layout,
.region = region,
});
self.buffer_cursor += data_size;
}
fn transferToBuffer(self: *StagingBuffer, ctx: Context, dst: *GpuBufferMemory, offset: vk.DeviceSize, comptime T: type, data: []const T) !void {
const data_size = data.len * @sizeOf(T);
if (offset + data_size > dst.size) {
return error.DestOutOfDeviceMemory;
}
if (self.buffer_cursor + data_size > buffer_size) {
return error.StageOutOfDeviceMemory; // current buffer is out of memory
}
try self.device_buffer_memory.map(ctx, self.buffer_cursor, data_size);
defer self.device_buffer_memory.unmap(ctx);
// TODO: here we align as u8 and later we reinterpret data as a byte array.
// This is because we get runtime errors from using T and data directly.
// It *SEEMS* like alignment error is a zig bug, but might as well be an application bug.
// If the bug is an application bug, then we need to find a way to fix it instead of disabling safety ...
var dest_location = @ptrCast([*]u8, @alignCast(@alignOf(u8), self.device_buffer_memory.mapped) orelse unreachable);
{
// runtime safety is turned off for performance
const byte_data = std.mem.sliceAsBytes(data);
@setRuntimeSafety(false);
for (byte_data, 0..) |elem, i| {
dest_location[i] = elem;
}
}
const copy_region = vk.BufferCopy{
.src_offset = self.buffer_cursor,
.dst_offset = offset,
.size = data_size,
};
if (self.buffer_copy.getPtr(dst.buffer)) |regions| {
if (regions.len >= RegionCount) return error.OutOfRegions; // no more regions in this ramp for this frame
regions.*.regions[regions.len] = copy_region;
regions.*.len += 1;
} else {
var regions = [_]vk.BufferCopy{undefined} ** RegionCount;
regions[0] = copy_region;
try self.buffer_copy.put(
dst.buffer,
// create array of copy jobs, begin with current job and
// set remaining jobs as undefined
BufferCopies{ .len = 1, .regions = regions },
);
}
self.buffer_cursor += data_size;
}
fn flush(self: *StagingBuffer, ctx: Context) !void {
if (self.buffer_cursor == 0) return;
// wait for previous transfer
_ = try ctx.vkd.waitForFences(
ctx.logical_device,
1,
@ptrCast([*]const vk.Fence, &self.fence),
vk.TRUE,
std.math.maxInt(u64),
);
// lock ramp
try ctx.vkd.resetFences(ctx.logical_device, 1, @ptrCast([*]const vk.Fence, &self.fence));
try self.device_buffer_memory.map(ctx, 0, self.buffer_cursor);
try self.device_buffer_memory.flush(ctx, 0, self.buffer_cursor);
self.device_buffer_memory.unmap(ctx);
try ctx.vkd.resetCommandPool(ctx.logical_device, self.command_pool, .{});
const begin_info = vk.CommandBufferBeginInfo{
.flags = .{
.one_time_submit_bit = true,
},
.p_inheritance_info = null,
};
try ctx.vkd.beginCommandBuffer(self.command_buffer, &begin_info);
{ // copy buffer jobs
var iter = self.buffer_copy.iterator();
while (iter.next()) |some| {
ctx.vkd.cmdCopyBuffer(self.command_buffer, self.device_buffer_memory.buffer, some.key_ptr.*, some.value_ptr.len, &some.value_ptr.*.regions);
}
for (self.image_copy.items) |copy| {
{
const transfer_transition = Texture.getTransitionBits(copy.src_layout, .transfer_dst_optimal);
const transfer_barrier = vk.ImageMemoryBarrier{
.src_access_mask = transfer_transition.src_mask,
.dst_access_mask = transfer_transition.dst_mask,
.old_layout = copy.src_layout,
.new_layout = .transfer_dst_optimal,
.src_queue_family_index = vk.QUEUE_FAMILY_IGNORED,
.dst_queue_family_index = vk.QUEUE_FAMILY_IGNORED,
.image = copy.image,
.subresource_range = vk.ImageSubresourceRange{
.aspect_mask = .{
.color_bit = true,
},
.base_mip_level = 0,
.level_count = 1,
.base_array_layer = 0,
.layer_count = 1,
},
};
ctx.vkd.cmdPipelineBarrier(
self.command_buffer,
transfer_transition.src_stage,
transfer_transition.dst_stage,
vk.DependencyFlags{},
0,
undefined,
0,
undefined,
1,
@ptrCast([*]const vk.ImageMemoryBarrier, &transfer_barrier),
);
}
ctx.vkd.cmdCopyBufferToImage(
self.command_buffer,
self.device_buffer_memory.buffer,
copy.image,
.transfer_dst_optimal,
1,
@ptrCast([*]const vk.BufferImageCopy, ©.region),
);
{
const read_only_transition = Texture.getTransitionBits(.transfer_dst_optimal, copy.dst_layout);
const read_only_barrier = vk.ImageMemoryBarrier{
.src_access_mask = read_only_transition.src_mask,
.dst_access_mask = read_only_transition.dst_mask,
.old_layout = .transfer_dst_optimal,
.new_layout = copy.dst_layout,
.src_queue_family_index = vk.QUEUE_FAMILY_IGNORED,
.dst_queue_family_index = vk.QUEUE_FAMILY_IGNORED,
.image = copy.image,
.subresource_range = vk.ImageSubresourceRange{
.aspect_mask = .{
.color_bit = true,
},
.base_mip_level = 0,
.level_count = 1,
.base_array_layer = 0,
.layer_count = 1,
},
};
ctx.vkd.cmdPipelineBarrier(
self.command_buffer,
read_only_transition.src_stage,
read_only_transition.dst_stage,
vk.DependencyFlags{},
0,
undefined,
0,
undefined,
1,
@ptrCast([*]const vk.ImageMemoryBarrier, &read_only_barrier),
);
}
}
}
try ctx.vkd.endCommandBuffer(self.command_buffer);
{
@setRuntimeSafety(false);
var semo_null_ptr: [*c]const vk.Semaphore = null;
var wait_null_ptr: [*c]const vk.PipelineStageFlags = null;
// perform the compute ray tracing, draw to target texture
const submit_info = vk.SubmitInfo{
.wait_semaphore_count = 0,
.p_wait_semaphores = semo_null_ptr,
.p_wait_dst_stage_mask = wait_null_ptr,
.command_buffer_count = 1,
.p_command_buffers = @ptrCast([*]const vk.CommandBuffer, &self.command_buffer),
.signal_semaphore_count = 0,
.p_signal_semaphores = semo_null_ptr,
};
try ctx.vkd.queueSubmit(ctx.graphics_queue, 1, @ptrCast([*]const vk.SubmitInfo, &submit_info), self.fence);
}
self.buffer_copy.clearRetainingCapacity();
self.image_copy.clearRetainingCapacity();
self.buffer_cursor = 0;
}
fn deinit(self: *StagingBuffer, ctx: Context) void {
ctx.vkd.freeCommandBuffers(
ctx.logical_device,
self.command_pool,
@intCast(u32, 1),
@ptrCast([*]const vk.CommandBuffer, &self.command_buffer),
);
ctx.vkd.destroyCommandPool(ctx.logical_device, self.command_pool, null);
self.device_buffer_memory.deinit(ctx);
ctx.vkd.destroyFence(ctx.logical_device, self.fence, null);
self.buffer_copy.deinit();
self.image_copy.deinit();
}
};
|
0 | repos/zig_vulkan/src/modules | repos/zig_vulkan/src/modules/render/validation_layer.zig | /// Functions related to validation layers and debug messaging
const std = @import("std");
const Allocator = std.mem.Allocator;
const vk = @import("vulkan");
const constants = @import("consts.zig");
const dispatch = @import("dispatch.zig");
fn InfoType() type {
if (constants.enable_validation_layers) {
return struct {
const Self = @This();
enabled_layer_count: u8,
enabled_layer_names: [*]const [*:0]const u8,
pub fn init(allocator: Allocator, vkb: dispatch.Base) !Self {
const validation_layers = [_][*:0]const u8{"VK_LAYER_KHRONOS_validation"};
const is_valid = try isLayersPresent(allocator, vkb, validation_layers[0..validation_layers.len]);
if (!is_valid) {
std.debug.panic("debug build without validation layer support", .{});
}
return Self{
.enabled_layer_count = validation_layers.len,
.enabled_layer_names = @ptrCast([*]const [*:0]const u8, &validation_layers),
};
}
};
} else {
return struct {
const Self = @This();
enabled_layer_count: u8,
enabled_layer_names: [*]const [*:0]const u8,
pub fn init(allocator: Allocator, vkb: dispatch.Base) !Self {
_ = allocator;
_ = vkb;
return Self{
.enabled_layer_count = 0,
.enabled_layer_names = undefined,
};
}
};
}
}
pub const Info = InfoType();
/// check if validation layer exist
fn isLayersPresent(allocator: Allocator, vkb: dispatch.Base, target_layers: []const [*:0]const u8) !bool {
var layer_count: u32 = 0;
_ = try vkb.enumerateInstanceLayerProperties(&layer_count, null);
var available_layers = try std.ArrayList(vk.LayerProperties).initCapacity(allocator, layer_count);
defer available_layers.deinit();
// TODO: handle vk.INCOMPLETE (Array too small)
_ = try vkb.enumerateInstanceLayerProperties(&layer_count, available_layers.items.ptr);
available_layers.items.len = layer_count;
for (target_layers) |target_layer| {
// check if target layer exist in available_layers
inner: for (available_layers.items) |available_layer| {
const layer_name = available_layer.layer_name;
// if target_layer and available_layer is the same
if (std.cstr.cmp(target_layer, @ptrCast([*:0]const u8, &layer_name)) == 0) {
break :inner;
}
} else return false; // if our loop never break, then a requested layer is missing
}
return true;
}
pub fn messageCallback(
message_severity: vk.DebugUtilsMessageSeverityFlagsEXT,
message_types: vk.DebugUtilsMessageTypeFlagsEXT,
p_callback_data: ?*const vk.DebugUtilsMessengerCallbackDataEXT,
p_user_data: ?*anyopaque,
) callconv(vk.vulkan_call_conv) vk.Bool32 {
_ = p_user_data;
_ = message_types;
const error_mask = comptime blk: {
break :blk vk.DebugUtilsMessageSeverityFlagsEXT{
.warning_bit_ext = true,
.error_bit_ext = true,
};
};
const is_severe = (error_mask.toInt() & message_severity.toInt()) > 0;
const writer = if (is_severe) std.io.getStdErr().writer() else std.io.getStdOut().writer();
if (p_callback_data) |data| {
writer.print("validation layer: {s}\n", .{data.p_message}) catch {
std.debug.print("error from stdout print in message callback", .{});
};
}
return vk.FALSE;
}
|
0 | repos/zig_vulkan/src/modules | repos/zig_vulkan/src/modules/render/Context.zig | const std = @import("std");
const Allocator = std.mem.Allocator;
const ArrayList = std.ArrayList;
const vk = @import("vulkan");
const glfw = @import("glfw");
const consts = @import("consts.zig");
const dispatch = @import("dispatch.zig");
const physical_device = @import("physical_device.zig");
const QueueFamilyIndices = physical_device.QueueFamilyIndices;
const validation_layer = @import("validation_layer.zig");
const vk_utils = @import("vk_utils.zig");
// TODO: move command pool to context?
/// Utilized to supply vulkan methods and common vulkan state to other
/// renderer functions and structs
const Context = @This();
allocator: Allocator,
vkb: dispatch.Base,
vki: dispatch.Instance,
vkd: dispatch.Device,
instance: vk.Instance,
physical_device_limits: vk.PhysicalDeviceLimits,
physical_device: vk.PhysicalDevice,
logical_device: vk.Device,
compute_queue: vk.Queue,
graphics_queue: vk.Queue,
present_queue: vk.Queue,
surface: vk.SurfaceKHR,
queue_indices: QueueFamilyIndices,
// TODO: utilize comptime for this (emit from struct if we are in release mode)
messenger: ?vk.DebugUtilsMessengerEXT,
/// pointer to the window handle. Caution is adviced when using this pointer ...
window_ptr: *glfw.Window,
// Caller should make sure to call deinit
pub fn init(allocator: Allocator, application_name: []const u8, window: *glfw.Window) !Context {
const app_name = try std.cstr.addNullByte(allocator, application_name);
defer allocator.free(app_name);
const app_info = vk.ApplicationInfo{
.p_next = null,
.p_application_name = app_name,
.application_version = consts.application_version,
.p_engine_name = consts.engine_name,
.engine_version = consts.engine_version,
.api_version = vk.API_VERSION_1_2,
};
// TODO: move to global scope (currently crashes the zig compiler :') )
const common_extensions = [_][*:0]const u8{vk.extension_info.khr_surface.name};
const application_extensions = blk: {
if (consts.enable_validation_layers) {
const debug_extensions = [_][*:0]const u8{
vk.extension_info.ext_debug_utils.name,
} ++ common_extensions;
break :blk debug_extensions[0..];
}
break :blk common_extensions[0..];
};
const glfw_extensions_slice = glfw.getRequiredInstanceExtensions() orelse unreachable;
// Due to a zig bug we need arraylist to append instead of preallocate slice
// in release it fail and length turns out to be 1
var extensions = try ArrayList([*:0]const u8).initCapacity(allocator, glfw_extensions_slice.len + application_extensions.len);
defer extensions.deinit();
for (glfw_extensions_slice) |extension| {
try extensions.append(extension);
}
for (application_extensions) |extension| {
try extensions.append(extension);
}
// Partially init a context so that we can use "self" even in init
var self: Context = undefined;
self.allocator = allocator;
// load base dispatch wrapper
const vk_proc = @ptrCast(
*const fn (instance: vk.Instance, procname: [*:0]const u8) callconv(.C) vk.PfnVoidFunction,
&glfw.getInstanceProcAddress,
);
self.vkb = try dispatch.Base.load(vk_proc);
if (!(try vk_utils.isInstanceExtensionsPresent(allocator, self.vkb, extensions.items))) {
return error.InstanceExtensionNotPresent;
}
const validation_layer_info = try validation_layer.Info.init(allocator, self.vkb);
const debug_create_info: ?*const vk.DebugUtilsMessengerCreateInfoEXT = blk: {
if (consts.enable_validation_layers) {
break :blk &createDefaultDebugCreateInfo();
} else {
break :blk null;
}
};
const debug_features = [_]vk.ValidationFeatureEnableEXT{
.best_practices_ext, // .synchronization_validation_ext,
};
const features: ?*const vk.ValidationFeaturesEXT = blk: {
if (consts.enable_validation_layers) {
break :blk &vk.ValidationFeaturesEXT{
.p_next = @ptrCast(?*const anyopaque, debug_create_info),
.enabled_validation_feature_count = debug_features.len,
.p_enabled_validation_features = &debug_features,
.disabled_validation_feature_count = 0,
.p_disabled_validation_features = undefined,
};
}
break :blk null;
};
self.instance = blk: {
const instance_info = vk.InstanceCreateInfo{
.p_next = @ptrCast(?*const anyopaque, features),
.flags = .{},
.p_application_info = &app_info,
.enabled_layer_count = validation_layer_info.enabled_layer_count,
.pp_enabled_layer_names = validation_layer_info.enabled_layer_names,
.enabled_extension_count = @intCast(u32, extensions.items.len),
.pp_enabled_extension_names = @ptrCast([*]const [*:0]const u8, extensions.items.ptr),
};
break :blk try self.vkb.createInstance(&instance_info, null);
};
self.vki = try dispatch.Instance.load(self.instance, vk_proc);
errdefer self.vki.destroyInstance(self.instance, null);
const result = @intToEnum(vk.Result, glfw.createWindowSurface(self.instance, window.*, null, &self.surface));
if (result != .success) {
return error.FailedToCreateSurface;
}
errdefer self.vki.destroySurfaceKHR(self.instance, self.surface, null);
self.physical_device = try physical_device.selectPrimary(allocator, self.vki, self.instance, self.surface);
self.queue_indices = try QueueFamilyIndices.init(allocator, self.vki, self.physical_device, self.surface);
self.messenger = blk: {
if (!consts.enable_validation_layers) break :blk null;
break :blk self.vki.createDebugUtilsMessengerEXT(self.instance, debug_create_info.?, null) catch {
std.debug.panic("failed to create debug messenger", .{});
};
};
self.logical_device = try physical_device.createLogicalDevice(allocator, self);
self.vkd = try dispatch.Device.load(self.logical_device, self.vki.dispatch.vkGetDeviceProcAddr);
self.compute_queue = self.vkd.getDeviceQueue(self.logical_device, self.queue_indices.compute, 0);
self.graphics_queue = self.vkd.getDeviceQueue(self.logical_device, self.queue_indices.graphics, 0);
self.present_queue = self.vkd.getDeviceQueue(self.logical_device, self.queue_indices.present, 0);
self.physical_device_limits = self.getPhysicalDeviceProperties().limits;
// possibly a bit wasteful, but to get compile errors when forgetting to
// init a variable the partial context variables are moved to a new context which we return
return Context{
.allocator = self.allocator,
.vkb = self.vkb,
.vki = self.vki,
.vkd = self.vkd,
.instance = self.instance,
.physical_device = self.physical_device,
.logical_device = self.logical_device,
.compute_queue = self.compute_queue,
.graphics_queue = self.graphics_queue,
.present_queue = self.present_queue,
.physical_device_limits = self.physical_device_limits,
.surface = self.surface,
.queue_indices = self.queue_indices,
.messenger = self.messenger,
.window_ptr = window,
};
}
pub fn destroyShaderModule(self: Context, module: vk.ShaderModule) void {
self.vkd.destroyShaderModule(self.logical_device, module, null);
}
/// caller must destroy returned module
pub fn createPipelineLayout(self: Context, create_info: vk.PipelineLayoutCreateInfo) !vk.PipelineLayout {
return self.vkd.createPipelineLayout(self.logical_device, &create_info, null);
}
pub fn destroyPipelineLayout(self: Context, pipeline_layout: vk.PipelineLayout) void {
self.vkd.destroyPipelineLayout(self.logical_device, pipeline_layout, null);
}
/// caller must destroy pipeline from vulkan
pub inline fn createGraphicsPipeline(self: Context, create_info: vk.GraphicsPipelineCreateInfo) !vk.Pipeline {
const create_infos = [_]vk.GraphicsPipelineCreateInfo{
create_info,
};
var pipeline: vk.Pipeline = undefined;
const result = try self.vkd.createGraphicsPipelines(self.logical_device, .null_handle, create_infos.len, @ptrCast([*]const vk.GraphicsPipelineCreateInfo, &create_infos), null, @ptrCast([*]vk.Pipeline, &pipeline));
if (result != vk.Result.success) {
// TODO: not panic?
std.debug.panic("failed to initialize pipeline!", .{});
}
return pipeline;
}
/// caller must both destroy pipeline from the heap and in vulkan
pub fn createComputePipeline(self: Context, allocator: Allocator, create_info: vk.ComputePipelineCreateInfo) !*vk.Pipeline {
var pipeline = try allocator.create(vk.Pipeline);
errdefer allocator.destroy(pipeline);
const create_infos = [_]vk.ComputePipelineCreateInfo{
create_info,
};
const result = try self.vkd.createComputePipelines(self.logical_device, .null_handle, create_infos.len, @ptrCast([*]const vk.ComputePipelineCreateInfo, &create_infos), null, @ptrCast([*]vk.Pipeline, pipeline));
if (result != vk.Result.success) {
// TODO: not panic?
std.debug.panic("failed to initialize pipeline!", .{});
}
return pipeline;
}
/// destroy pipeline from vulkan *not* from the application memory
pub fn destroyPipeline(self: Context, pipeline: *vk.Pipeline) void {
self.vkd.destroyPipeline(self.logical_device, pipeline.*, null);
}
pub fn getPhysicalDeviceProperties(self: Context) vk.PhysicalDeviceProperties {
return self.vki.getPhysicalDeviceProperties(self.physical_device);
}
/// caller must destroy returned render pass
pub fn createRenderPass(self: Context, format: vk.Format) !vk.RenderPass {
const color_attachment = [_]vk.AttachmentDescription{
.{
.flags = .{},
.format = format,
.samples = .{
.@"1_bit" = true,
},
.load_op = .dont_care,
.store_op = .store,
.stencil_load_op = .dont_care,
.stencil_store_op = .dont_care,
.initial_layout = .present_src_khr,
.final_layout = .present_src_khr,
},
};
const color_attachment_refs = [_]vk.AttachmentReference{
.{
.attachment = 0,
.layout = .color_attachment_optimal,
},
};
const subpass = [_]vk.SubpassDescription{
.{
.flags = .{},
.pipeline_bind_point = .graphics,
.input_attachment_count = 0,
.p_input_attachments = undefined,
.color_attachment_count = color_attachment_refs.len,
.p_color_attachments = &color_attachment_refs,
.p_resolve_attachments = null,
.p_depth_stencil_attachment = null,
.preserve_attachment_count = 0,
.p_preserve_attachments = undefined,
},
};
const subpass_dependency = vk.SubpassDependency{
.src_subpass = vk.SUBPASS_EXTERNAL,
.dst_subpass = 0,
.src_stage_mask = .{
.color_attachment_output_bit = true,
},
.dst_stage_mask = .{
.color_attachment_output_bit = true,
},
.src_access_mask = .{},
.dst_access_mask = .{
.color_attachment_write_bit = true,
},
.dependency_flags = .{},
};
const render_pass_info = vk.RenderPassCreateInfo{
.flags = .{},
.attachment_count = color_attachment.len,
.p_attachments = &color_attachment,
.subpass_count = subpass.len,
.p_subpasses = &subpass,
.dependency_count = 1,
.p_dependencies = @ptrCast([*]const vk.SubpassDependency, &subpass_dependency),
};
return try self.vkd.createRenderPass(self.logical_device, &render_pass_info, null);
}
pub fn destroyRenderPass(self: Context, render_pass: vk.RenderPass) void {
self.vkd.destroyRenderPass(self.logical_device, render_pass, null);
}
pub fn deinit(self: Context) void {
self.vki.destroySurfaceKHR(self.instance, self.surface, null);
self.vkd.destroyDevice(self.logical_device, null);
if (consts.enable_validation_layers) {
self.vki.destroyDebugUtilsMessengerEXT(self.instance, self.messenger.?, null);
}
self.vki.destroyInstance(self.instance, null);
}
// TODO: can probably drop function and inline it in init
fn createDefaultDebugCreateInfo() vk.DebugUtilsMessengerCreateInfoEXT {
const message_severity = vk.DebugUtilsMessageSeverityFlagsEXT{
.verbose_bit_ext = false,
.info_bit_ext = false,
.warning_bit_ext = true,
.error_bit_ext = true,
};
const message_type = vk.DebugUtilsMessageTypeFlagsEXT{
.general_bit_ext = true,
.validation_bit_ext = true,
.performance_bit_ext = true,
};
return vk.DebugUtilsMessengerCreateInfoEXT{
.p_next = null,
.flags = .{},
.message_severity = message_severity,
.message_type = message_type,
.pfn_user_callback = &validation_layer.messageCallback,
.p_user_data = null,
};
}
|
0 | repos/zig_vulkan/src/modules | repos/zig_vulkan/src/modules/render/Texture.zig | const std = @import("std");
const vk = @import("vulkan");
const vk_utils = @import("vk_utils.zig");
const GpuBufferMemory = @import("GpuBufferMemory.zig");
const Context = @import("Context.zig");
const Allocator = std.mem.Allocator;
pub fn Config(comptime T: type) type {
return struct {
data: ?[]T,
width: u32,
height: u32,
usage: vk.ImageUsageFlags,
queue_family_indices: []const u32,
format: vk.Format,
};
}
const Texture = @This();
image_size: vk.DeviceSize,
image_extent: vk.Extent2D,
image: vk.Image,
image_view: vk.ImageView,
image_memory: vk.DeviceMemory,
format: vk.Format,
sampler: vk.Sampler,
layout: vk.ImageLayout,
// TODO: comptime send_to_device: bool to disable all useless transfer
pub fn init(ctx: Context, command_pool: vk.CommandPool, layout: vk.ImageLayout, comptime T: type, config: Config(T)) !Texture {
const image_extent = vk.Extent2D{
.width = config.width,
.height = config.height,
};
const image = blk: {
// TODO: make sure we use correct usage bits https://www.khronos.org/registry/vulkan/specs/1.2-extensions/man/html/VkImageUsageFlagBits.html
// TODO: VK_IMAGE_CREATE_SPARSE_BINDING_BIT
const image_info = vk.ImageCreateInfo{
.flags = .{},
.image_type = .@"2d",
.format = config.format,
.extent = vk.Extent3D{
.width = config.width,
.height = config.height,
.depth = 1,
},
.mip_levels = 1,
.array_layers = 1,
.samples = .{
.@"1_bit" = true,
},
.tiling = .optimal,
.usage = config.usage,
.sharing_mode = .exclusive, // TODO: concurrent if (queue_family_indices.len > 1)
.queue_family_index_count = @intCast(u32, config.queue_family_indices.len),
.p_queue_family_indices = config.queue_family_indices.ptr,
.initial_layout = .undefined,
};
break :blk try ctx.vkd.createImage(ctx.logical_device, &image_info, null);
};
const image_memory = blk: {
const memory_requirements = ctx.vkd.getImageMemoryRequirements(ctx.logical_device, image);
const alloc_info = vk.MemoryAllocateInfo{
.allocation_size = memory_requirements.size,
.memory_type_index = try vk_utils.findMemoryTypeIndex(ctx, memory_requirements.memory_type_bits, .{
.device_local_bit = true,
}),
};
break :blk try ctx.vkd.allocateMemory(ctx.logical_device, &alloc_info, null);
};
try ctx.vkd.bindImageMemory(ctx.logical_device, image, image_memory, 0);
// TODO: set size according to image format
const image_size: vk.DeviceSize = @intCast(vk.DeviceSize, config.width * config.height * @sizeOf(f32));
// transfer texture data to gpu
if (config.data) |data| {
var staging_buffer = try GpuBufferMemory.init(ctx, image_size, .{
.transfer_src_bit = true,
}, .{
.host_visible_bit = true,
.host_coherent_bit = true,
});
defer staging_buffer.deinit(ctx);
try staging_buffer.transferToDevice(ctx, T, 0, data);
try transitionImageLayout(ctx, command_pool, image, .undefined, .transfer_dst_optimal);
try copyBufferToImage(ctx, command_pool, image, staging_buffer.buffer, image_extent);
try transitionImageLayout(ctx, command_pool, image, .transfer_dst_optimal, layout);
} else {
try transitionImageLayout(ctx, command_pool, image, .undefined, layout);
}
const image_view = blk: {
// TODO: evaluate if this and swapchain should share logic (probably no)
const image_view_info = vk.ImageViewCreateInfo{
.flags = .{},
.image = image,
.view_type = .@"2d",
.format = config.format,
.components = .{
.r = .identity,
.g = .identity,
.b = .identity,
.a = .identity,
},
.subresource_range = .{
.aspect_mask = .{
.color_bit = true,
},
.base_mip_level = 0,
.level_count = 1,
.base_array_layer = 0,
.layer_count = 1,
},
};
break :blk try ctx.vkd.createImageView(ctx.logical_device, &image_view_info, null);
};
const sampler = blk: {
// const device_properties = ctx.vki.getPhysicalDeviceProperties(ctx.physical_device);
const sampler_info = vk.SamplerCreateInfo{
.flags = .{},
.mag_filter = .linear, // not sure what the application would need
.min_filter = .linear, // RT should use linear, pixel sim should be nearest
.mipmap_mode = .linear,
.address_mode_u = .repeat,
.address_mode_v = .repeat,
.address_mode_w = .repeat,
.mip_lod_bias = 0.0,
.anisotropy_enable = vk.FALSE, // TODO: test with, and without
.max_anisotropy = 1.0, // device_properties.limits.max_sampler_anisotropy,
.compare_enable = vk.FALSE,
.compare_op = .always,
.min_lod = 0.0,
.max_lod = 0.0,
.border_color = .int_opaque_black,
.unnormalized_coordinates = vk.FALSE, // TODO: might be good for pixel sim to use true
};
break :blk try ctx.vkd.createSampler(ctx.logical_device, &sampler_info, null);
};
return Texture{
.image_size = image_size,
.image_extent = image_extent,
.image = image,
.image_view = image_view,
.image_memory = image_memory,
.format = config.format,
.sampler = sampler,
.layout = layout,
};
}
pub fn deinit(self: Texture, ctx: Context) void {
ctx.vkd.destroySampler(ctx.logical_device, self.sampler, null);
ctx.vkd.destroyImageView(ctx.logical_device, self.image_view, null);
ctx.vkd.destroyImage(ctx.logical_device, self.image, null);
ctx.vkd.freeMemory(ctx.logical_device, self.image_memory, null);
}
pub fn copyToHost(self: Texture, command_pool: vk.CommandPool, ctx: Context, comptime T: type, buffer: []T) !void {
var staging_buffer = try GpuBufferMemory.init(ctx, self.image_size, .{
.transfer_dst_bit = true,
}, .{
.host_visible_bit = true,
.host_coherent_bit = true,
});
defer staging_buffer.deinit(ctx);
try transitionImageLayout(ctx, command_pool, self.image, self.layout, .transfer_src_optimal);
const command_buffer = try vk_utils.beginOneTimeCommandBuffer(ctx, command_pool);
{
const region = vk.BufferImageCopy{
.buffer_offset = 0,
.buffer_row_length = 0,
.buffer_image_height = 0,
.image_subresource = vk.ImageSubresourceLayers{
.aspect_mask = .{
.color_bit = true,
},
.mip_level = 0,
.base_array_layer = 0,
.layer_count = 1,
},
.image_offset = .{
.x = 0,
.y = 0,
.z = 0,
},
.image_extent = .{
.width = self.image_extent.width,
.height = self.image_extent.height,
.depth = 1,
},
};
ctx.vkd.cmdCopyImageToBuffer(command_buffer, self.image, .transfer_src_optimal, staging_buffer.buffer, 1, @ptrCast([*]const vk.BufferImageCopy, ®ion));
}
try vk_utils.endOneTimeCommandBuffer(ctx, command_pool, command_buffer);
try transitionImageLayout(ctx, command_pool, self.image, .transfer_src_optimal, self.layout);
try staging_buffer.transferFromDevice(ctx, T, buffer);
}
pub const TransitionBarrier = struct {
transition: TransitionBits,
barrier: vk.ImageMemoryBarrier,
};
pub inline fn getImageTransitionBarrier(image: vk.Image, comptime old_layout: vk.ImageLayout, comptime new_layout: vk.ImageLayout) TransitionBarrier {
const transition = getTransitionBits(old_layout, new_layout);
return TransitionBarrier{
.transition = transition,
.barrier = vk.ImageMemoryBarrier{
.src_access_mask = transition.src_mask,
.dst_access_mask = transition.dst_mask,
.old_layout = old_layout,
.new_layout = new_layout,
.src_queue_family_index = vk.QUEUE_FAMILY_IGNORED,
.dst_queue_family_index = vk.QUEUE_FAMILY_IGNORED,
.image = image,
.subresource_range = vk.ImageSubresourceRange{
.aspect_mask = .{
.color_bit = true,
},
.base_mip_level = 0,
.level_count = 1,
.base_array_layer = 0,
.layer_count = 1,
},
},
};
}
const TransitionBits = struct {
src_mask: vk.AccessFlags,
dst_mask: vk.AccessFlags,
src_stage: vk.PipelineStageFlags,
dst_stage: vk.PipelineStageFlags,
};
pub fn getTransitionBits(old_layout: vk.ImageLayout, new_layout: vk.ImageLayout) TransitionBits {
var transition_bits: TransitionBits = undefined;
switch (old_layout) {
.undefined => {
transition_bits.src_mask = .{};
transition_bits.src_stage = .{
.top_of_pipe_bit = true,
};
},
.general => {
transition_bits.src_mask = .{
.shader_read_bit = true,
.shader_write_bit = true,
};
transition_bits.src_stage = .{
.compute_shader_bit = true,
};
},
.shader_read_only_optimal => {
transition_bits.src_mask = .{
.shader_read_bit = true,
};
transition_bits.src_stage = .{
.fragment_shader_bit = true,
};
},
.transfer_dst_optimal => {
transition_bits.src_mask = .{
.transfer_write_bit = true,
};
transition_bits.src_stage = .{
.transfer_bit = true,
};
},
.transfer_src_optimal => {
transition_bits.src_mask = .{
.transfer_read_bit = true,
};
transition_bits.src_stage = .{
.transfer_bit = true,
};
},
else => {
// TODO return error
std.debug.panic("illegal old layout", .{});
},
}
switch (new_layout) {
.undefined => {
transition_bits.dst_mask = .{};
transition_bits.dst_stage = .{
.top_of_pipe_bit = true,
};
},
.present_src_khr => {
transition_bits.dst_mask = .{
.shader_read_bit = true,
};
transition_bits.dst_stage = .{
.fragment_shader_bit = true,
};
},
.general => {
transition_bits.dst_mask = .{
.shader_read_bit = true,
};
transition_bits.dst_stage = .{
.fragment_shader_bit = true,
};
},
.shader_read_only_optimal => {
transition_bits.dst_mask = .{
.shader_read_bit = true,
};
transition_bits.dst_stage = .{
.fragment_shader_bit = true,
};
},
.transfer_dst_optimal => {
transition_bits.dst_mask = .{
.transfer_write_bit = true,
};
transition_bits.dst_stage = .{
.transfer_bit = true,
};
},
.transfer_src_optimal => {
transition_bits.dst_mask = .{
.transfer_read_bit = true,
};
transition_bits.dst_stage = .{
.transfer_bit = true,
};
},
else => {
// TODO return error
std.debug.panic("illegal new layout", .{});
},
}
return transition_bits;
}
pub inline fn transitionImageLayout(ctx: Context, command_pool: vk.CommandPool, image: vk.Image, old_layout: vk.ImageLayout, new_layout: vk.ImageLayout) !void {
const commmand_buffer = try vk_utils.beginOneTimeCommandBuffer(ctx, command_pool);
const transition = getTransitionBits(old_layout, new_layout);
const barrier = vk.ImageMemoryBarrier{
.src_access_mask = transition.src_mask,
.dst_access_mask = transition.dst_mask,
.old_layout = old_layout,
.new_layout = new_layout,
.src_queue_family_index = vk.QUEUE_FAMILY_IGNORED,
.dst_queue_family_index = vk.QUEUE_FAMILY_IGNORED,
.image = image,
.subresource_range = vk.ImageSubresourceRange{
.aspect_mask = .{
.color_bit = true,
},
.base_mip_level = 0,
.level_count = 1,
.base_array_layer = 0,
.layer_count = 1,
},
};
ctx.vkd.cmdPipelineBarrier(commmand_buffer, transition.src_stage, transition.dst_stage, vk.DependencyFlags{}, 0, undefined, 0, undefined, 1, @ptrCast([*]const vk.ImageMemoryBarrier, &barrier));
try vk_utils.endOneTimeCommandBuffer(ctx, command_pool, commmand_buffer);
}
pub inline fn copyBufferToImage(ctx: Context, command_pool: vk.CommandPool, image: vk.Image, buffer: vk.Buffer, image_extent: vk.Extent2D) !void {
const command_buffer = try vk_utils.beginOneTimeCommandBuffer(ctx, command_pool);
{
const region = vk.BufferImageCopy{
.buffer_offset = 0,
.buffer_row_length = 0,
.buffer_image_height = 0,
.image_subresource = vk.ImageSubresourceLayers{
.aspect_mask = .{
.color_bit = true,
},
.mip_level = 0,
.base_array_layer = 0,
.layer_count = 1,
},
.image_offset = .{
.x = 0,
.y = 0,
.z = 0,
},
.image_extent = .{
.width = image_extent.width,
.height = image_extent.height,
.depth = 1,
},
};
ctx.vkd.cmdCopyBufferToImage(command_buffer, buffer, image, .transfer_dst_optimal, 1, @ptrCast([*]const vk.BufferImageCopy, ®ion));
}
try vk_utils.endOneTimeCommandBuffer(ctx, command_pool, command_buffer);
}
|
0 | repos/zig_vulkan/src/modules | repos/zig_vulkan/src/modules/render/consts.zig | /// This file contains compiletime constants that are relevant for the renderer API.
const std = @import("std");
const builtin = @import("builtin");
const vk = @import("vulkan");
// enable validation layer in debug
pub const enable_validation_layers = builtin.mode == .Debug;
pub const engine_name = "nop";
pub const engine_version = vk.makeApiVersion(0, 0, 1, 0);
pub const application_version = vk.makeApiVersion(0, 0, 1, 0);
const release_logical_device_extensions = [_][*:0]const u8{vk.extension_info.khr_swapchain.name};
const debug_logical_device_extensions = [_][*:0]const u8{vk.extension_info.khr_shader_non_semantic_info.name};
pub const logical_device_extensions = if (enable_validation_layers) release_logical_device_extensions ++ debug_logical_device_extensions else release_logical_device_extensions;
pub const max_frames_in_flight = 2;
|
0 | repos/zig_vulkan/src/modules | repos/zig_vulkan/src/modules/render/dispatch.zig | /// This file contains the vk Wrapper types used to call vulkan functions.
/// Wrapper is a vulkan-zig construct that generates compile time types that
/// links with vulkan functions depending on queried function requirements
/// see vk X_Command types for implementation details
const vk = @import("vulkan");
const consts = @import("consts.zig");
pub const Base = vk.BaseWrapper(.{
.enumerateInstanceLayerProperties = true,
.enumerateInstanceExtensionProperties = true,
.createInstance = true,
});
pub const Instance = vk.InstanceWrapper(.{
.createDebugUtilsMessengerEXT = consts.enable_validation_layers,
.createDevice = true,
.destroyDebugUtilsMessengerEXT = consts.enable_validation_layers,
.destroyInstance = true,
.destroySurfaceKHR = true,
.enumerateDeviceExtensionProperties = true,
.enumeratePhysicalDevices = true,
.getDeviceProcAddr = true,
.getPhysicalDeviceFeatures = true,
.getPhysicalDeviceMemoryProperties = true,
.getPhysicalDeviceProperties = true,
.getPhysicalDeviceQueueFamilyProperties = true,
.getPhysicalDeviceSurfaceCapabilitiesKHR = true,
.getPhysicalDeviceSurfaceFormatsKHR = true,
.getPhysicalDeviceSurfacePresentModesKHR = true,
.getPhysicalDeviceSurfaceSupportKHR = true,
});
pub const Device = vk.DeviceWrapper(.{
.acquireNextImageKHR = true,
.allocateCommandBuffers = true,
.allocateDescriptorSets = true,
.allocateMemory = true,
.beginCommandBuffer = true,
.bindBufferMemory = true,
.bindImageMemory = true,
.cmdBeginRenderPass = true,
.cmdBindDescriptorSets = true,
.cmdBindIndexBuffer = true,
.cmdBindPipeline = true,
.cmdBindVertexBuffers = true,
.cmdBlitImage = true,
.cmdCopyBuffer = true,
.cmdCopyBufferToImage = true,
.cmdCopyImageToBuffer = true,
.cmdDispatch = true,
.cmdDrawIndexed = true,
.cmdEndRenderPass = true,
.cmdPipelineBarrier = true,
.cmdPushConstants = true,
.cmdSetScissor = true,
.cmdSetViewport = true,
.createBuffer = true,
.createCommandPool = true,
.createComputePipelines = true,
.createDescriptorPool = true,
.createDescriptorSetLayout = true,
.createFence = true,
.createFramebuffer = true,
.createGraphicsPipelines = true,
.createImage = true,
.createImageView = true,
.createPipelineCache = true,
.createPipelineLayout = true,
.createRenderPass = true,
.createSampler = true,
.createSemaphore = true,
.createShaderModule = true,
.createSwapchainKHR = true,
.destroyBuffer = true,
.destroyCommandPool = true,
.destroyDescriptorPool = true,
.destroyDescriptorSetLayout = true,
.destroyDevice = true,
.destroyFence = true,
.destroyFramebuffer = true,
.destroyImage = true,
.destroyImageView = true,
.destroyPipeline = true,
.destroyPipelineCache = true,
.destroyPipelineLayout = true,
.destroyRenderPass = true,
.destroySampler = true,
.destroySemaphore = true,
.destroyShaderModule = true,
.destroySwapchainKHR = true,
.deviceWaitIdle = true,
.endCommandBuffer = true,
.flushMappedMemoryRanges = true,
.freeCommandBuffers = true,
.freeDescriptorSets = true,
.freeMemory = true,
.getBufferMemoryRequirements = true,
.getDeviceQueue = true,
.getFenceStatus = true,
.getImageMemoryRequirements = true,
.getSwapchainImagesKHR = true,
.mapMemory = true,
.queuePresentKHR = true,
.queueSubmit = true,
.queueWaitIdle = true,
.resetCommandPool = true,
.resetFences = true,
.unmapMemory = true,
.updateDescriptorSets = true,
.waitForFences = true,
});
pub const BeginCommandBufferError = Device.BeginCommandBufferError;
|
0 | repos/zig_vulkan/src/modules | repos/zig_vulkan/src/modules/render/memory.zig | const std = @import("std");
const vk = @import("vulkan");
const Context = @import("Context.zig");
pub const bytes_in_mb = 1048576;
pub inline fn nonCoherentAtomSize(ctx: Context, size: vk.DeviceSize) vk.DeviceSize {
const atom_size = ctx.physical_device_limits.non_coherent_atom_size;
return atom_size * (std.math.divCeil(vk.DeviceSize, size, atom_size) catch unreachable);
}
|
0 | repos/zig_vulkan/src/modules | repos/zig_vulkan/src/modules/render/GpuBufferMemory.zig | const std = @import("std");
const vk = @import("vulkan");
const vk_utils = @import("vk_utils.zig");
const Context = @import("Context.zig");
const tracy = @import("ztracy");
const memory_util = @import("memory.zig");
/// Vulkan buffer abstraction
const GpuBufferMemory = @This();
// TODO: might not make sense if different type, should be array
/// how many elements does the buffer contain
len: u32,
// TODO: rename capacity, and add an accumulating size variable
/// how many bytes *can* be stored in the buffer
size: vk.DeviceSize,
buffer: vk.Buffer,
memory: vk.DeviceMemory,
mapped: ?*anyopaque,
/// create a undefined buffer that can be utilized later
pub fn @"undefined"() GpuBufferMemory {
return GpuBufferMemory{
.len = 0,
.size = 0,
.buffer = .null_handle,
.memory = .null_handle,
.mapped = null,
};
}
/// user has to make sure to call deinit on buffer
pub fn init(ctx: Context, size: vk.DeviceSize, buf_usage_flags: vk.BufferUsageFlags, mem_prop_flags: vk.MemoryPropertyFlags) !GpuBufferMemory {
const buffer = blk: {
const buffer_info = vk.BufferCreateInfo{
.flags = .{},
.size = size,
.usage = buf_usage_flags,
.sharing_mode = .exclusive,
.queue_family_index_count = 0,
.p_queue_family_indices = undefined,
};
break :blk try ctx.vkd.createBuffer(ctx.logical_device, &buffer_info, null);
};
errdefer ctx.vkd.destroyBuffer(ctx.logical_device, buffer, null);
const memory = blk: {
const memory_requirements = ctx.vkd.getBufferMemoryRequirements(ctx.logical_device, buffer);
const memory_type_index = try vk_utils.findMemoryTypeIndex(ctx, memory_requirements.memory_type_bits, mem_prop_flags);
const allocate_info = vk.MemoryAllocateInfo{
.allocation_size = memory_requirements.size,
.memory_type_index = memory_type_index,
};
break :blk try ctx.vkd.allocateMemory(ctx.logical_device, &allocate_info, null);
};
errdefer ctx.vkd.freeMemory(ctx.logical_device, memory, null);
try ctx.vkd.bindBufferMemory(ctx.logical_device, buffer, memory, 0);
return GpuBufferMemory{
.len = 0,
.size = size,
.buffer = buffer,
.memory = memory,
.mapped = null,
};
}
pub const CopyConfig = struct {
src_offset: vk.DeviceSize = 0,
dst_offset: vk.DeviceSize = 0,
size: vk.DeviceSize = 0,
};
pub fn copy(self: GpuBufferMemory, ctx: Context, into: *GpuBufferMemory, command_pool: vk.CommandPool, config: CopyConfig) !void {
const copy_zone = tracy.ZoneN(@src(), "copy buffer");
defer copy_zone.End();
const command_buffer = try vk_utils.beginOneTimeCommandBuffer(ctx, command_pool);
var copy_region = vk.BufferCopy{
.src_offset = config.src_offset,
.dst_offset = config.dst_offset,
.size = config.size,
};
ctx.vkd.cmdCopyBuffer(command_buffer, self.buffer, into.buffer, 1, @ptrCast([*]vk.BufferCopy, ©_region));
try vk_utils.endOneTimeCommandBuffer(ctx, command_pool, command_buffer);
}
/// Same as copy but caller manage synchronization
pub fn manualCopy(self: GpuBufferMemory, ctx: Context, into: *GpuBufferMemory, command_buffer: vk.CommandBuffer, fence: vk.Fence, config: CopyConfig) !void {
var copy_region = vk.BufferCopy{
.src_offset = config.src_offset,
.dst_offset = config.dst_offset,
.size = config.size,
};
const begin_info = vk.CommandBufferBeginInfo{
.flags = .{
.one_time_submit_bit = true,
},
.p_inheritance_info = null,
};
try ctx.vkd.beginCommandBuffer(command_buffer, &begin_info);
ctx.vkd.cmdCopyBuffer(command_buffer, self.buffer, into.buffer, 1, @ptrCast([*]vk.BufferCopy, ©_region));
try ctx.vkd.endCommandBuffer(command_buffer);
{
@setRuntimeSafety(false);
var semo_null_ptr: [*c]const vk.Semaphore = null;
var wait_null_ptr: [*c]const vk.PipelineStageFlags = null;
// perform the compute ray tracing, draw to target texture
const submit_info = vk.SubmitInfo{
.wait_semaphore_count = 0,
.p_wait_semaphores = semo_null_ptr,
.p_wait_dst_stage_mask = wait_null_ptr,
.command_buffer_count = 1,
.p_command_buffers = @ptrCast([*]const vk.CommandBuffer, &command_buffer),
.signal_semaphore_count = 0,
.p_signal_semaphores = semo_null_ptr,
};
try ctx.vkd.queueSubmit(ctx.graphics_queue, 1, @ptrCast([*]const vk.SubmitInfo, &submit_info), fence);
}
}
/// Transfer data from host to device
pub fn transferToDevice(self: *GpuBufferMemory, ctx: Context, comptime T: type, offset: usize, data: []const T) !void {
const transfer_zone = tracy.ZoneN(@src(), @src().fn_name);
defer transfer_zone.End();
if (self.mapped != null) {
// TODO: implement a transfer for already mapped memory
return error.MemoryAlreadyMapped; // can't used transfer if memory is externally mapped
}
// transfer empty data slice is NOP
if (data.len <= 0) return;
const size = data.len * @sizeOf(T);
const map_size = memory_util.nonCoherentAtomSize(ctx, size);
if (map_size + offset > self.size) return error.OutOfDeviceMemory; // size greater than buffer
var gpu_mem = (try ctx.vkd.mapMemory(ctx.logical_device, self.memory, offset, map_size, .{})) orelse return error.FailedToMapGPUMem;
var typed_gpu_mem = @ptrCast([*]T, @alignCast(@alignOf(T), gpu_mem));
std.mem.copy(T, typed_gpu_mem[0..data.len], data);
ctx.vkd.unmapMemory(ctx.logical_device, self.memory);
self.len = @intCast(u32, data.len);
}
pub fn map(self: *GpuBufferMemory, ctx: Context, offset: vk.DeviceSize, size: vk.DeviceSize) !void {
const map_size = blk: {
if (size == vk.WHOLE_SIZE) {
break :blk vk.WHOLE_SIZE;
}
const atom_size = memory_util.nonCoherentAtomSize(ctx, size);
if (atom_size + offset > self.size) return error.InsufficientMemory; // size greater than buffer
break :blk atom_size;
};
self.mapped = (try ctx.vkd.mapMemory(ctx.logical_device, self.memory, offset, map_size, .{})) orelse return error.FailedToMapGPUMem;
}
pub fn unmap(self: *GpuBufferMemory, ctx: Context) void {
if (self.mapped != null) {
ctx.vkd.unmapMemory(ctx.logical_device, self.memory);
self.mapped = null;
}
}
pub fn flush(self: GpuBufferMemory, ctx: Context, offset: vk.DeviceSize, size: vk.DeviceSize) !void {
const atom_size = memory_util.nonCoherentAtomSize(ctx, size);
if (atom_size + offset > self.size) return error.InsufficientMemory; // size greater than buffer
const map_range = vk.MappedMemoryRange{
.memory = self.memory,
.offset = offset,
.size = atom_size,
};
try ctx.vkd.flushMappedMemoryRanges(
ctx.logical_device,
1,
@ptrCast([*]const vk.MappedMemoryRange, &map_range),
);
}
pub fn transferFromDevice(self: *GpuBufferMemory, ctx: Context, comptime T: type, data: []T) !void {
const transfer_zone = tracy.ZoneN(@src(), @src().fn_name);
defer transfer_zone.End();
if (self.mapped != null) {
// TODO: implement a transfer for already mapped memory
return error.MemoryAlreadyMapped; // can't used transfer if memory is externally mapped
}
const gpu_mem = (try ctx.vkd.mapMemory(ctx.logical_device, self.memory, 0, self.size, .{})) orelse return error.FailedToMapGPUMem;
const gpu_mem_start = @ptrToInt(gpu_mem);
var i: usize = 0;
var offset: usize = 0;
{
@setRuntimeSafety(false);
while (offset + @sizeOf(T) <= self.size and i < data.len) : (i += 1) {
offset = @sizeOf(T) * i;
data[i] = @intToPtr(*T, gpu_mem_start + offset).*;
}
}
ctx.vkd.unmapMemory(ctx.logical_device, self.memory);
}
/// Transfer data from host to device, allows you to send multiple chunks of data in the same buffer.
/// offsets are index offsets, not byte offsets
pub fn batchTransfer(self: *GpuBufferMemory, ctx: Context, comptime T: type, offsets: []usize, datas: [][]const T) !void {
const transfer_zone = tracy.ZoneN(@src(), @src().fn_name);
defer transfer_zone.End();
if (self.mapped != null) {
// TODO: implement a transfer for already mapped memory
return error.MemoryAlreadyMapped; // can't used transfer if memory is externally mapped
}
if (offsets.len == 0) return;
if (offsets.len != datas.len) {
return error.OffsetDataMismatch; // inconsistent offset and data size indicate a programatic error
}
// calculate how far in the memory location we are going
const size = datas[datas.len - 1].len * @sizeOf(T) + offsets[offsets.len - 1] * @sizeOf(T);
if (self.size < size) {
return error.InsufficentBufferSize; // size of buffer is less than data being transfered
}
const gpu_mem = (try ctx.vkd.mapMemory(ctx.logical_device, self.memory, 0, self.size, .{})) orelse return error.FailedToMapGPUMem;
const gpu_mem_start = @ptrToInt(gpu_mem);
{
@setRuntimeSafety(false);
for (offsets, 0..) |offset, i| {
const byte_offset = offset * @sizeOf(T);
for (datas[i], 0..) |element, j| {
const mem_location = gpu_mem_start + byte_offset + j * @sizeOf(T);
var ptr = @intToPtr(*T, mem_location);
ptr.* = element;
}
}
}
ctx.vkd.unmapMemory(ctx.logical_device, self.memory);
self.len = std.math.max(self.len, @intCast(u32, datas[datas.len - 1].len + offsets[offsets.len - 1]));
}
/// destroy buffer and free memory
pub fn deinit(self: GpuBufferMemory, ctx: Context) void {
if (self.mapped != null) {
ctx.vkd.unmapMemory(ctx.logical_device, self.memory);
}
if (self.buffer != .null_handle) {
ctx.vkd.destroyBuffer(ctx.logical_device, self.buffer, null);
}
if (self.memory != .null_handle) {
ctx.vkd.freeMemory(ctx.logical_device, self.memory, null);
}
}
|
0 | repos/zig_vulkan/src/modules | repos/zig_vulkan/src/modules/render/vk_utils.zig | /// vk_utils contains utility functions for the vulkan API to reduce boiler plate
// TODO: most of these functions are only called once in the codebase, move to where they are
// relevant, and those who are only called in one file should be in that file
const std = @import("std");
const Allocator = std.mem.Allocator;
const vk = @import("vulkan");
const dispatch = @import("dispatch.zig");
const Context = @import("Context.zig");
/// Check if extensions are available on host instance
pub fn isInstanceExtensionsPresent(allocator: Allocator, vkb: dispatch.Base, target_extensions: []const [*:0]const u8) !bool {
// query extensions available
var supported_extensions_count: u32 = 0;
// TODO: handle "VkResult.incomplete"
_ = try vkb.enumerateInstanceExtensionProperties(null, &supported_extensions_count, null);
var extensions = try std.ArrayList(vk.ExtensionProperties).initCapacity(allocator, supported_extensions_count);
defer extensions.deinit();
_ = try vkb.enumerateInstanceExtensionProperties(null, &supported_extensions_count, extensions.items.ptr);
extensions.items.len = supported_extensions_count;
var matches: u32 = 0;
for (target_extensions) |target_extension| {
cmp: for (extensions.items) |existing| {
const existing_name = @ptrCast([*:0]const u8, &existing.extension_name);
if (std.cstr.cmp(target_extension, existing_name) == 0) {
matches += 1;
break :cmp;
}
}
}
return matches == target_extensions.len;
}
pub inline fn findMemoryTypeIndex(ctx: Context, type_filter: u32, memory_flags: vk.MemoryPropertyFlags) !u32 {
const properties = ctx.vki.getPhysicalDeviceMemoryProperties(ctx.physical_device);
{
var i: u32 = 0;
while (i < properties.memory_type_count) : (i += 1) {
const correct_type: bool = (type_filter & (@as(u32, 1) << @intCast(u5, i))) != 0;
if (correct_type and (properties.memory_types[i].property_flags.toInt() & memory_flags.toInt()) == memory_flags.toInt()) {
return i;
}
}
}
return error.NotFound;
}
pub inline fn beginOneTimeCommandBuffer(ctx: Context, command_pool: vk.CommandPool) !vk.CommandBuffer {
const allocate_info = vk.CommandBufferAllocateInfo{
.command_pool = command_pool,
.level = .primary,
.command_buffer_count = 1,
};
var command_buffer: vk.CommandBuffer = undefined;
try ctx.vkd.allocateCommandBuffers(ctx.logical_device, &allocate_info, @ptrCast([*]vk.CommandBuffer, &command_buffer));
const begin_info = vk.CommandBufferBeginInfo{
.flags = .{
.one_time_submit_bit = true,
},
.p_inheritance_info = null,
};
try ctx.vkd.beginCommandBuffer(command_buffer, &begin_info);
return command_buffer;
}
// TODO: synchronization should be improved in this function (currently very sub optimal)!
pub inline fn endOneTimeCommandBuffer(ctx: Context, command_pool: vk.CommandPool, command_buffer: vk.CommandBuffer) !void {
try ctx.vkd.endCommandBuffer(command_buffer);
{
@setRuntimeSafety(false);
var semo_null_ptr: [*c]const vk.Semaphore = null;
var wait_null_ptr: [*c]const vk.PipelineStageFlags = null;
// perform the compute ray tracing, draw to target texture
const submit_info = vk.SubmitInfo{
.wait_semaphore_count = 0,
.p_wait_semaphores = semo_null_ptr,
.p_wait_dst_stage_mask = wait_null_ptr,
.command_buffer_count = 1,
.p_command_buffers = @ptrCast([*]const vk.CommandBuffer, &command_buffer),
.signal_semaphore_count = 0,
.p_signal_semaphores = semo_null_ptr,
};
try ctx.vkd.queueSubmit(ctx.graphics_queue, 1, @ptrCast([*]const vk.SubmitInfo, &submit_info), .null_handle);
}
try ctx.vkd.queueWaitIdle(ctx.graphics_queue);
ctx.vkd.freeCommandBuffers(ctx.logical_device, command_pool, 1, @ptrCast([*]const vk.CommandBuffer, &command_buffer));
}
|
0 | repos/zig_vulkan | repos/zig_vulkan/.vscode/launch.json | {
// Use IntelliSense to learn about possible attributes.
// Hover to view descriptions of existing attributes.
// For more information, visit: https://go.microsoft.com/fwlink/?linkid=830387
"version": "0.2.0",
"configurations": [
{
"name": "(Windows) Launch Debug",
"type": "cppvsdbg",
"request": "launch",
"program": "${workspaceFolder}/zig-out/bin/zig_vulkan.exe",
"args": [],
"stopAtEntry": false,
"cwd": "${fileDirname}",
"environment": [],
"preLaunchTask": "build"
},
{
"name": "(Windows) Launch Safe",
"type": "cppvsdbg",
"request": "launch",
"program": "${workspaceFolder}/zig-out/bin/zig_vulkan.exe",
"args": [],
"stopAtEntry": false,
"cwd": "${fileDirname}",
"environment": [],
"preLaunchTask": "safe"
},
{
"name": "(Windows) Launch Release",
"type": "lldb",
"request": "launch",
"program": "${workspaceFolder}/zig-out/bin/zig_vulkan",
"args": [],
"cwd": "${fileDirname}",
"preLaunchTask": "release"
},
{
"name": "(Linux) Launch Debug",
"type": "lldb",
"request": "launch",
"program": "${workspaceFolder}/zig-out/bin/zig_vulkan",
"args": [],
"cwd": "${fileDirname}",
"preLaunchTask": "build"
},
{
"name": "(Linux) Launch Safe",
"type": "lldb",
"request": "launch",
"program": "${workspaceFolder}/zig-out/bin/zig_vulkan",
"args": [],
"cwd": "${fileDirname}",
"preLaunchTask": "safe"
},
{
"name": "(Linux) Launch Release",
"type": "lldb",
"request": "launch",
"program": "${workspaceFolder}/zig-out/bin/zig_vulkan",
"args": [],
"cwd": "${fileDirname}",
"preLaunchTask": "release"
}
]
}
|
0 | repos/zig_vulkan | repos/zig_vulkan/.vscode/tasks.json | {
"version": "2.0.0",
"tasks": [
{
"label": "build",
"type": "shell",
"command": "zig build -Dshader-debug-info=true -Dtracy=true",
"group": "build",
"problemMatcher": [
"$gcc"
]
},
{
"label": "safe",
"type": "shell",
"command": "zig build -Drelease-safe=true -Dshader-debug-info=true -Dtracy=true",
"group": "build",
"problemMatcher": [
"$gcc"
]
},
{
"label": "release",
"type": "shell",
"command": "zig build -Drelease-safe=true -Dshader-debug-info=false -Dtracy=false",
"group": "build",
"problemMatcher": [
"$gcc"
]
}
]
}
|
0 | repos/zig_vulkan | repos/zig_vulkan/.vscode/settings.json | {
"cmake.configureOnOpen": false,
"debug.onTaskErrors": "abort",
"glsllint.glslangValidatorArgs": "--target-env vulkan1.2 -I${workspaceFolder}assets/shaders",
// run zig fmt when saving
"emeraldwalk.runonsave": {
"commands": [
{
"match": ".zig",
"isAsync": true,
"cmd": "zig fmt ${file}"
},
]
}
}
|
0 | repos/zig_vulkan | repos/zig_vulkan/.vscode/README.md | # VsCode configuration
Make sure to install Run on Save by emaraldwalk in order to get zig fmt on save
also recommmend zig by either Marc TieHuis or prime31 + zls for vscode |
0 | repos | repos/iotmonitor/DEVELOPING.md |
### Developing on the project
when-changed is a simple python command ligne that auto recompile the project, when files changes
when-changed *.zig zig build
when-changed leveldb.zig ../zig/zig test leveldb.zig -l leveldb -l c -l c++
### Possible Improvments
- Use a full parser
seems a target port for zig in antlr4, is a good idea
https://github.com/antlr/antlr4/blob/master/doc/creating-a-language-target.md
|
0 | repos | repos/iotmonitor/CHANGELOG.md |
## Version 0.2.5
- add nix support for distribution and compilation
- add http access to iot monitoring, see configuration options
- move to zig 0.9.0
## Version 0.2.2
#### 2021-06-12
- add clientid in config to permit multiple instances of iotmonitor
- fix 0.8 compilation
#### 2020-11-22
- move to zig release 0.7
#### 2020-10-16
- add mqtt reconnect logic, as mqtt sync client does not have the "reconnect" builtin capabilities yet.
## Version 0.2
#### 2020-09-13
- add process monitoring
- fix docker to use the zig master branch to compile
|
0 | repos | repos/iotmonitor/processlib.zig | // process lib, permit to launch loosely coupled processes
const std = @import("std");
const debug = std.debug;
const log = std.log;
const os = std.os;
const mem = std.mem;
const fs = std.fs;
const File = fs.File;
const Dir = fs.Dir;
const fmt = std.fmt;
pub const ProcessInformation = struct {
pid: i32 = 0,
// 8k for buffer ? is it enought ?
commandlinebuffer: [BUFFERSIZE]u8 = [_]u8{'\x00'} ** BUFFERSIZE,
commandlinebuffer_size: u16 = 0,
const Self = @This();
const BUFFERSIZE = 8292 * 2;
// iterator on the command line arguments
const Iterator = struct {
inner: *const Self,
currentIndex: u16 = 0,
const SelfIterator = @This();
pub fn next(self: *SelfIterator) ?[]const u8 {
if (self.currentIndex >= self.inner.commandlinebuffer_size) {
return null;
}
const start = self.currentIndex;
// seek for next 0 ending or end of commandline buffer_size
while (self.currentIndex < self.inner.commandlinebuffer_size and self.inner.commandlinebuffer[self.currentIndex] != '\x00') {
self.currentIndex = self.currentIndex + 1;
}
// move to next after returning the element slice
defer self.currentIndex = self.currentIndex + 1;
return self.inner.commandlinebuffer[start..self.currentIndex];
}
};
pub fn iterator(processInfo: *Self) Iterator {
return Iterator{ .inner = processInfo };
}
};
// get process information, for a specific PID
// return false if the process does not exists,
// return true and the processInfo is populated with the command line options
pub fn getProcessInformations(pid: i32, processInfo: *ProcessInformation) !bool {
var buffer = [_]u8{'\x00'} ** 8192;
const options = Dir.OpenDirOptions{
.access_sub_paths = true,
.iterate = true,
};
var procDir = try fs.cwd().openDir("/proc", options);
defer procDir.close();
const r = try fmt.bufPrint(&buffer, "{}", .{pid});
var subprocDir: Dir = procDir.openDir(r, options) catch {
log.warn("no dir associated to proc {}", .{pid});
return false;
};
defer subprocDir.close();
var commandLineFile: File = try subprocDir.openFile("cmdline", File.OpenFlags{});
defer commandLineFile.close();
const readSize = try commandLineFile.pread(processInfo.commandlinebuffer[0..], 0);
processInfo.commandlinebuffer_size = @intCast(u16, readSize);
processInfo.*.pid = pid;
return true;
}
// test if buffer contains only digits
fn isAllNumeric(buffer: []const u8) bool {
for (buffer) |c| {
if (c > '9' or c < '0') {
return false;
}
}
return true;
}
// Process browsing
//
const ProcessInformationCallback = fn (processInformation: *ProcessInformation) void;
// function that list processes and grab command line arguments
// a call back is taken from
pub fn listProcesses(callback: ProcessInformationCallback) !void {
const options = Dir.OpenDirOptions{
.access_sub_paths = true,
.iterate = true,
};
var procDir = try fs.cwd().openDir("/proc", options);
defer procDir.close();
var dirIterator = procDir.iterate();
while (try dirIterator.next()) |f| {
if (f.kind == File.Kind.File) {
continue;
}
if (!isAllNumeric(f.name)) {
continue;
}
const pid = try fmt.parseInt(i32, f.name, 10);
var pi = ProcessInformation{};
const successGetInformations = getProcessInformations(pid, &pi) catch {
// if file retrieve failed because of pid close, continue
continue;
};
if (successGetInformations and pi.commandlinebuffer_size > 0) {
callback(&pi);
// log.warn(" {}: {} \n", .{ pid, pi.commandlinebuffer[0..pi.commandlinebuffer_size] });
}
// try opening the commandline file
}
}
fn testCallback(processInformation: *ProcessInformation) void {
log.warn("processinformation : {}", .{processInformation});
// dump the commnand line buffer
var it = processInformation.iterator();
while (it.next()) |i| {
log.warn(" {}\n", .{i});
}
}
test "check existing process" {
try listProcesses(testCallback);
}
|
0 | repos | repos/iotmonitor/config.toml |
[mqtt]
serverAddress="tcp://localhost:1883"
baseTopic="mybaseTopic/monitoring"
user=""
password=""
[http]
[device_nodered]
watchTimeOut=2
watchTopics="home/agents/nodered/watchdog"
[agent_switchcontrol]
exec="sleep 100"
watchTopics="home/agents"
# watchTimeOut=
|
0 | repos | repos/iotmonitor/CODE_OF_CONDUCT.md | # Contributor Covenant Code of Conduct
## Our Pledge
In the interest of fostering an open and welcoming environment, we as
contributors and maintainers pledge to making participation in our project and
our community a harassment-free experience for everyone, regardless of age, body
size, disability, ethnicity, sex characteristics, gender identity and expression,
level of experience, education, socio-economic status, nationality, personal
appearance, race, religion, or sexual identity and orientation.
## Our Standards
Examples of behavior that contributes to creating a positive environment
include:
* Using welcoming and inclusive language
* Being respectful of differing viewpoints and experiences
* Gracefully accepting constructive criticism
* Focusing on what is best for the community
* Showing empathy towards other community members
Examples of unacceptable behavior by participants include:
* The use of sexualized language or imagery and unwelcome sexual attention or
advances
* Trolling, insulting/derogatory comments, and personal or political attacks
* Public or private harassment
* Publishing others' private information, such as a physical or electronic
address, without explicit permission
* Other conduct which could reasonably be considered inappropriate in a
professional setting
## Our Responsibilities
Project maintainers are responsible for clarifying the standards of acceptable
behavior and are expected to take appropriate and fair corrective action in
response to any instances of unacceptable behavior.
Project maintainers have the right and responsibility to remove, edit, or
reject comments, commits, code, wiki edits, issues, and other contributions
that are not aligned to this Code of Conduct, or to ban temporarily or
permanently any contributor for other behaviors that they deem inappropriate,
threatening, offensive, or harmful.
## Scope
This Code of Conduct applies both within project spaces and in public spaces
when an individual is representing the project or its community. Examples of
representing a project or community include using an official project e-mail
address, posting via an official social media account, or acting as an appointed
representative at an online or offline event. Representation of a project may be
further defined and clarified by project maintainers.
## Enforcement
Instances of abusive, harassing, or otherwise unacceptable behavior may be
reported by contacting the project team at [email protected]. All
complaints will be reviewed and investigated and will result in a response that
is deemed necessary and appropriate to the circumstances. The project team is
obligated to maintain confidentiality with regard to the reporter of an incident.
Further details of specific enforcement policies may be posted separately.
Project maintainers who do not follow or enforce the Code of Conduct in good
faith may face temporary or permanent repercussions as determined by other
members of the project's leadership.
## Attribution
This Code of Conduct is adapted from the [Contributor Covenant][homepage], version 1.4,
available at https://www.contributor-covenant.org/version/1/4/code-of-conduct.html
[homepage]: https://www.contributor-covenant.org
For answers to common questions about this code of conduct, see
https://www.contributor-covenant.org/faq
|
0 | repos | repos/iotmonitor/mqttlib.zig | const std = @import("std");
const mem = std.mem;
const debug = std.debug;
const log = std.log;
//const cmqtt = @import("mqtt_paho.zig");
const cmqtt = @cImport({
@cInclude("MQTTClient.h");
});
const c = @cImport({
@cInclude("stdio.h");
@cInclude("unistd.h");
@cInclude("string.h");
@cInclude("time.h");
//@cInclude("paho.mqtt.c/src/MQTTClient.h");
});
const CallBack = fn (topic: []u8, message: []u8) void;
const MAX_REGISTERED_TOPICS = 10;
const mqttlibError = error{FailToRegister};
// Connexion to mqtt
//
pub const MqttCnx = struct {
const Self = @This();
allocator: *mem.Allocator,
handle: cmqtt.MQTTClient = undefined,
callBack: CallBack = undefined,
latestDeliveryToken: *cmqtt.MQTTClient_deliveryToken = undefined,
connected: bool = undefined,
connect_option: *cmqtt.MQTTClient_connectOptions = undefined,
reconnect_registered_topics_length: u16 = 0,
reconnect_registered_topics: [10]?[]u8,
// this message is received in an other thread
fn _defaultCallback(topic: []u8, message: []u8) void {
_ = c.printf("%s -> %s\n", topic.ptr, message.ptr);
}
fn _connLost(ctx: ?*anyopaque, m: [*c]u8) callconv(.C) void {
_ = m;
const self_ctx = @intToPtr(*Self, @ptrToInt(ctx));
_ = c.printf("connection lost %d\n", self_ctx);
}
fn _msgArrived(ctx: ?*anyopaque, topic: [*c]u8, topic_length: c_int, message: [*c]cmqtt.MQTTClient_message) callconv(.C) c_int {
_ = topic_length;
const messagePtrAddress = @ptrToInt(&message);
var cmsg = @intToPtr([*c][*c]cmqtt.MQTTClient_message, messagePtrAddress);
defer cmqtt.MQTTClient_freeMessage(cmsg);
defer cmqtt.MQTTClient_free(topic);
// unsafe conversion
const self_ctx = @intToPtr(*Self, @ptrToInt(ctx));
// paho always return a 0 in topic_length, we must then compute it
// _ = c.printf("topic length is %d \n", topic_length);
const tlength: usize = c.strlen(topic);
// topic_length always 0 ... non sense
const mlength = @intCast(u32, message.*.payloadlen);
const am = @ptrToInt(message.*.payload);
const mptr = @intToPtr([*]u8, am);
// pass to zig in proper way with slices
self_ctx.callBack(topic[0..tlength], mptr[0..mlength]);
return 1; // properly handled
}
fn _delivered(ctx: ?*anyopaque, token: cmqtt.MQTTClient_deliveryToken) callconv(.C) void {
// _ = c.printf("%s", "received token");
// unsafe conversion
const self_ctx = @intToPtr(*Self, @ptrToInt(ctx));
self_ctx.*.latestDeliveryToken.* = token;
}
pub fn deinit(self: *Self) !void {
_ = self;
}
pub fn init(allocator: *mem.Allocator, serverAddress: []const u8, clientid: []const u8, username: []const u8, password: []const u8) !*Self {
var handle: cmqtt.MQTTClient = undefined;
// we need to make a safe string with zero ending
const zServerAddress = try allocator.alloc(u8, serverAddress.len + 1);
// defer allocator.free(zServerAddress);
mem.copy(u8, zServerAddress, serverAddress[0..]);
zServerAddress[serverAddress.len] = '\x00';
const zusername = try allocator.alloc(u8, username.len + 1);
// defer allocator.free(zusername);
mem.copy(u8, zusername, username[0..]);
zusername[username.len] = '\x00';
const zpassword = try allocator.alloc(u8, password.len + 1);
// defer allocator.free(zpassword);
mem.copy(u8, zpassword, password[0..]);
zpassword[password.len] = '\x00';
const zclientid = try allocator.alloc(u8, clientid.len + 1);
// defer allocator.free(zclientid);
mem.copy(u8, zclientid, clientid[0..]);
zclientid[clientid.len] = '\x00';
// convert to C the input parameters (ensuring the sentinel)
const MQTTCLIENT_PERSISTENCE_NONE = 1;
const result = cmqtt.MQTTClient_create(&handle, zServerAddress.ptr, zclientid.ptr, MQTTCLIENT_PERSISTENCE_NONE, null);
if (result > 0) return error.MQTTCreateError;
const HEADER = [_]u8{ 'M', 'Q', 'T', 'C' };
// we setup the struct here, because the initializer is a macro in C,
var conn_options = cmqtt.MQTTClient_connectOptions{
.struct_id = HEADER,
.struct_version = 0,
.keepAliveInterval = 60,
.cleansession = 1,
.reliable = 1,
.will = null,
.username = zusername.ptr,
.password = zpassword.ptr,
.connectTimeout = 30,
.retryInterval = 0,
.ssl = null,
.serverURIcount = 0,
.serverURIs = null,
.MQTTVersion = 0,
.returned = .{
.serverURI = null,
.MQTTVersion = 0,
.sessionPresent = 0,
},
.binarypwd = .{
.len = 0,
.data = null,
},
.maxInflightMessages = -1,
.cleanstart = 0, // only available on V5 +
.httpHeaders = null,
};
if (username.len == 0) {
conn_options.username = null;
conn_options.password = null;
}
var self_ptr = try allocator.create(Self);
// init members
self_ptr.handle = handle;
self_ptr.allocator = allocator;
self_ptr.callBack = _defaultCallback;
self_ptr.latestDeliveryToken = try allocator.create(cmqtt.MQTTClient_deliveryToken);
self_ptr.connected = false;
// remember the connect options
self_ptr.connect_option = try allocator.create(cmqtt.MQTTClient_connectOptions);
self_ptr.connect_option.* = conn_options;
self_ptr.reconnect_registered_topics = mem.zeroes([10]?[]u8);
self_ptr.reconnect_registered_topics_length = 0;
const retCallBacks = cmqtt.MQTTClient_setCallbacks(handle, self_ptr, _connLost, _msgArrived, _delivered);
if (retCallBacks != cmqtt.MQTTCLIENT_SUCCESS) {
return mqttlibError.FailToRegister;
}
try self_ptr.reconnect(true);
return self_ptr;
}
fn reconnect(self: *Self, first: bool) !void {
if (self.*.connected) {
// nothing to do
return;
}
if (!first) {
const result = cmqtt.MQTTClient_disconnect(self.handle, 100);
if (result != 0) {
_ = c.printf("disconnection failed MQTTClient_disconnect returned %d, continue\n", result);
}
}
const r = cmqtt.MQTTClient_connect(self.handle, self.connect_option);
_ = c.printf("connect to mqtt returned %d\n", r);
if (r != 0) return error.MQTTConnectError;
self.connected = true;
if (self.reconnect_registered_topics_length > 0) {
for (self.reconnect_registered_topics[0..self.reconnect_registered_topics_length]) |e| {
if (e) |nonNullPtr| {
_ = c.printf("re-registering %s \n", nonNullPtr.ptr);
self._register(nonNullPtr) catch {
_ = c.printf("cannot reregister \n");
};
}
}
}
}
// publish a message with default QOS 0
pub fn publish(self: *Self, topic: [*c]const u8, msg: []const u8) !void {
return publishWithQos(self, topic, msg, 0);
}
pub fn publishWithQos(self: *Self, topic: [*c]const u8, msg: []const u8, qos: u8) !void {
self._publishWithQos(topic, msg, qos) catch |e| {
_ = c.printf("fail to publish, try to reconnect \n");
log.warn("error : {}", .{e});
self.connected = false;
self.reconnect(false) catch |reconnecterr| {
_ = c.printf("failed to reconnect, will retry later \n");
log.warn("error: {}", .{reconnecterr});
};
};
}
// internal method, to permit to retry connect
fn _publishWithQos(self: *Self, topic: [*c]const u8, msg: []const u8, qos: u8) !void {
const messageLength: c_int = @intCast(c_int, msg.len);
if (msg.len == 0) {
return;
}
// beacause c declared the message as mutable (not const),
// convert it to const type
const constMessageContent: [*]u8 = @intToPtr([*]u8, @ptrToInt(msg.ptr));
const HEADER_MESSAGE = [_]u8{ 'M', 'Q', 'T', 'M' };
var mqttmessage = cmqtt.MQTTClient_message{
.struct_id = HEADER_MESSAGE,
.struct_version = 0, // no message properties
.payloadlen = messageLength,
.payload = constMessageContent,
.qos = qos,
.retained = 0,
.dup = 0,
.msgid = 0,
// below, these are MQTTV5 specific properties
.properties = cmqtt.MQTTProperties{
.count = 0,
.max_count = 0,
.length = 0,
.array = null,
},
};
var token = try self.allocator.create(cmqtt.MQTTClient_deliveryToken);
defer self.allocator.destroy(token);
const resultPublish = cmqtt.MQTTClient_publishMessage(self.handle, topic, &mqttmessage, token);
if (resultPublish != 0) {
std.log.warn("publish mqtt message returned {}\n", .{resultPublish});
return error.MQTTPublishError;
}
// wait for sent
if (qos > 0) {
const waitResult = cmqtt.MQTTClient_waitForCompletion(self.handle, token.*, @intCast(c_ulong, 2000));
if (waitResult != 0) return error.MQTTWaitTokenError;
while (self.latestDeliveryToken.* != token.*) {
// CPU breath, and yield
_ = c.usleep(1);
}
}
}
pub fn register(self: *Self, topic: []const u8) !void {
// remember the topic, to be able to re register at connection lost
//
if (self.*.reconnect_registered_topics_length >= self.reconnect_registered_topics.len) {
// not enought room remember registered topics
return error.TooMuchRegisteredTopics;
}
const ptr = try self.allocator.alloc(u8, topic.len + 1);
mem.copy(u8, ptr, topic[0..]);
ptr[topic.len] = '\x00';
self.reconnect_registered_topics[self.*.reconnect_registered_topics_length] = ptr;
self.reconnect_registered_topics_length = self.*.reconnect_registered_topics_length + 1;
try self._register(ptr);
}
fn _register(self: *Self, topic: []const u8) !void {
_ = c.printf("register to %s \n", topic.ptr);
const r = cmqtt.MQTTClient_subscribe(self.*.handle, topic.ptr, 0);
if (r != 0) return error.MQTTRegistrationError;
}
};
test "testconnect mqtt home" {
var arena = std.heap.ArenaAllocator.init(std.heap.c_allocator);
defer arena.deinit();
const allocator = &arena.allocator;
var serverAddress: []const u8 = "tcp://192.168.4.16:1883";
var clientid: []const u8 = "clientid";
var userName: []const u8 = "sys";
var password: []const u8 = "pwd";
// var handle: cmqtt.MQTTClient = null;
var cnx = try MqttCnx.init(allocator, serverAddress, clientid, userName, password);
const myStaticMessage: []const u8 = "Hello static message";
_ = try cnx.register("home/#");
_ = c.sleep(10);
var i: u32 = 0;
while (i < 10000) : (i += 1) {
try cnx.publish("myothertopic", myStaticMessage);
}
while (i < 10000) : (i += 1) {
try cnx.publishWithQos("myothertopic", myStaticMessage, 1);
}
_ = c.printf("ended");
}
pub fn main() !void {
var arena = std.heap.ArenaAllocator.init(std.heap.c_allocator);
defer arena.deinit();
const allocator = &arena.allocator;
var serverAddress: []const u8 = "tcp://192.168.4.16:1883";
var clientid: []const u8 = "clientid";
var userName: []const u8 = "sys";
var password: []const u8 = "pwd";
var cnx = try MqttCnx.init(allocator, serverAddress, clientid, userName, password);
_ = try cnx.register("home/#");
_ = c.sleep(20);
_ = c.printf("ended");
return;
}
|
0 | repos | repos/iotmonitor/topics.zig | const std = @import("std");
const mem = std.mem;
const assert = std.debug.assert;
// test if the evaluted topic belong to the reference Topic,
// return the sub path if it is
pub fn doesTopicBelongTo(evaluatedTopic: []const u8, referenceTopic: []const u8) !?[]const u8 {
if (evaluatedTopic.len < referenceTopic.len) return null;
const isWatched = mem.eql(u8, evaluatedTopic[0..referenceTopic.len], referenceTopic);
if (isWatched) {
const subTopic = evaluatedTopic[referenceTopic.len..];
return subTopic;
}
return null;
}
test "Test belong to" {
const topic1: []const u8 = "/home";
const topic2: []const u8 = "/home";
const a = try doesTopicBelongTo(topic1, topic2);
assert(a != null);
assert(a.?.len == 0);
}
test "sub path" {
const topic1: []const u8 = "/home";
const topic2: []const u8 = "/ho";
const a = try doesTopicBelongTo(topic1, topic2);
assert(a != null);
assert(a.?.len == 2);
assert(mem.eql(u8, a.?, "me"));
}
test "no match 1" {
const topic1: []const u8 = "/home";
const topic2: []const u8 = "/ho2";
const a = try doesTopicBelongTo(topic1, topic2);
assert(a == null);
}
test "no match 2" {
const topic1: []const u8 = "/home";
const topic2: []const u8 = "/home2";
const a = try doesTopicBelongTo(topic1, topic2);
assert(a == null);
}
|
0 | repos | repos/iotmonitor/leveldb.zig | // This library is a thick binding to leveldb C API
const std = @import("std");
const builtin = @import("builtin");
const trait = std.meta.trait;
const debug = std.debug;
const log = std.log;
const assert = debug.assert;
const Allocator = mem.Allocator;
const mem = std.mem;
const cleveldb = @cImport({
@cInclude("leveldb/c.h");
});
const c = @cImport({
@cInclude("stdio.h");
@cInclude("unistd.h");
});
///////////////////////////////////////////////////////////////////////
// Serialization / Deserialisation
// this define the generic API for either Simple Type and composite Type for serialization
fn SerDeserAPI(comptime T: type, comptime INType: type, comptime OUTType: type) type {
_ = T;
return struct {
const MarshallFn = fn (*const INType, *Allocator) []const u8;
const UnMarshallFn = fn ([]const u8, *Allocator) *align(1) OUTType;
marshall: MarshallFn,
unMarshall: UnMarshallFn,
};
}
pub fn ArrSerDeserType(comptime T: type) SerDeserAPI(T, []const T, []T) {
const MI = struct {
// default functions when the type is still serializable
fn noMarshallFn(t: *const []const T, allocator: *Allocator) []const u8 {
_ = allocator;
return t.*;
}
// unmarshall must make a copy,
// because leveldb has its own buffers
fn noUnMarshallFn(e: []const u8, allocator: *Allocator) *align(1) []T {
const ptrContainer = @ptrToInt(&e);
const elements = @intToPtr(*align(1) []T, ptrContainer);
const pNew = allocator.create([]T) catch unreachable;
pNew.* = elements.*;
return pNew;
}
};
const S = SerDeserAPI(T, []const T, []T);
return S{
.marshall = MI.noMarshallFn,
.unMarshall = MI.noUnMarshallFn,
};
}
// need sed deser for storing on disk
pub fn SerDeserType(comptime T: type) SerDeserAPI(T, T, T) {
comptime {
if (@typeInfo(T) == .Pointer) {
@panic("this ser deser type is only for simple types");
}
}
const MI = struct {
// default functions when the type is still serializable
fn noMarshallFn(t: *const T, allocator: *Allocator) []const u8 {
_ = allocator;
return mem.asBytes(t);
}
// unmarshall must make a copy,
// because leveldb has its own buffers
fn noUnMarshallFn(e: []const u8, allocator: *Allocator) *align(1) T {
_ = allocator;
const eptr = @ptrToInt(&e[0]);
return @intToPtr(*align(1) T, eptr);
}
};
const S = SerDeserAPI(T, T, T);
return S{
.marshall = MI.noMarshallFn,
.unMarshall = MI.noUnMarshallFn,
};
}
test "use of noMarshallFn" {
var allocator = std.heap.c_allocator;
const i: u32 = 12;
var r = SerDeserType(u32).marshall(&i, &allocator);
const ur = SerDeserType(u32).unMarshall(r, &allocator);
debug.assert(i == ur.*);
}
// create level db type for single element,
pub fn LevelDBHash(comptime K: type, comptime V: type) type {
return LevelDBHashWithSerialization(K, K, K, V, V, V, SerDeserType(K), SerDeserType(V));
}
// create a leveldb type for arrays of element, for instance
// []u8 (strings)
pub fn LevelDBHashArray(comptime K: type, comptime V: type) type {
return LevelDBHashWithSerialization(K, []const K, []K, V, []const V, []V, ArrSerDeserType(K), ArrSerDeserType(V));
}
// This function create a given type for using the leveldb, with serialization
// and deserialization
pub fn LevelDBHashWithSerialization(
// K is the key type,
comptime K: type,
// KIN is the associated type used in "put" primitive (when the element is passed in)
comptime KIN: type,
// KOUT is the associated type for out, see get primitive
comptime KOUT: type,
// V is the value base type
comptime V: type,
comptime VIN: type,
comptime VOUT: type,
// marshallkey function serialize the k to be stored in the database
comptime marshallKey: SerDeserAPI(K, KIN, KOUT),
comptime marshallValue: SerDeserAPI(V, VIN, VOUT),
) type {
return struct {
leveldbHandle: *cleveldb.leveldb_t = undefined,
writeOptions: *cleveldb.leveldb_writeoptions_t = undefined,
readOptions: *cleveldb.leveldb_readoptions_t = undefined,
allocator: *Allocator,
const Self = @This();
const KSerDeser = marshallKey;
const VSerDeser = marshallValue;
pub fn init(allocator: *Allocator) !*Self {
const self = try allocator.create(Self);
self.allocator = allocator;
self.writeOptions = cleveldb.leveldb_writeoptions_create().?;
self.readOptions = cleveldb.leveldb_readoptions_create().?;
return self;
}
pub fn deinit(self: *Self) void {
debug.print("deinit \n", .{});
// close already free the leveldb handle
// cleveldb.leveldb_free(self.leveldbHandle);
cleveldb.leveldb_free(self.writeOptions);
cleveldb.leveldb_free(self.readOptions);
}
pub fn open(self: *Self, filename: [*c]const u8) !void {
const options = cleveldb.leveldb_options_create();
defer cleveldb.leveldb_free(options);
// defining a small LRU cache,
// on level db, initialy initialized to 32Gb with 4096 bock size
// because, the key replace, will keep the values until compaction
// to full iteration can get all datas and put them into LRU cache
const cache = cleveldb.leveldb_cache_create_lru(4096);
const env = cleveldb.leveldb_create_default_env();
cleveldb.leveldb_options_set_cache(options, cache);
cleveldb.leveldb_options_set_create_if_missing(options, 1);
cleveldb.leveldb_options_set_max_open_files(options, 10);
cleveldb.leveldb_options_set_block_restart_interval(options, 4);
cleveldb.leveldb_options_set_write_buffer_size(options, 1000);
cleveldb.leveldb_options_set_env(options, env);
cleveldb.leveldb_options_set_info_log(options, null);
cleveldb.leveldb_options_set_block_size(options, 1024);
var err: [*c]u8 = null;
const result = cleveldb.leveldb_open(options, filename, &err);
if (err != null) {
_ = log.warn("{s}", .{"open failed"});
defer cleveldb.leveldb_free(err);
return error.OPEN_FAILED;
}
assert(result != null);
self.leveldbHandle = result.?;
}
pub fn close(self: *Self) void {
log.warn("close database \n", .{});
cleveldb.leveldb_close(self.leveldbHandle);
self.leveldbHandle = undefined;
}
pub fn put(self: *Self, key: KIN, value: VIN) !void {
var err: [*c]u8 = null;
// debug.print("k size {}\n", .{@sizeOf(K)});
// debug.print("array size {}\n", .{value.len});
// marshall value
const marshalledKey = KSerDeser.marshall(&key, self.allocator);
// defer self.allocator.free(marshalledKey);
const marshalledValue = VSerDeser.marshall(&value, self.allocator);
// defer self.allocator.free(marshalledValue);
cleveldb.leveldb_put(self.leveldbHandle, self.writeOptions, marshalledKey.ptr, marshalledKey.len, marshalledValue.ptr, marshalledValue.len, &err);
if (err != null) {
log.warn("{s}", .{"open failed"});
defer cleveldb.leveldb_free(err);
return error.KEY_WRITE_FAILED;
}
}
// retrieve the content of a key
pub fn get(self: *Self, key: KIN) !?*align(1) VOUT {
var read: ?[*]u8 = undefined;
var read_len: usize = 0;
var err: [*c]u8 = null;
const marshalledKey = KSerDeser.marshall(&key, self.allocator);
// defer self.allocator.free(marshalledKey);
read = cleveldb.leveldb_get(self.leveldbHandle, self.readOptions, marshalledKey.ptr, marshalledKey.len, &read_len, &err);
if (err != null) {
_ = c.printf("open failed");
defer cleveldb.leveldb_free(err);
return null;
}
if (read == null) {
debug.print("key not found \n", .{});
return null;
}
const torelease = @ptrCast(*anyopaque, read);
defer cleveldb.leveldb_free(torelease);
// _ = c.printf("returned : %s %d\n", read, read_len);
const structAddr = @ptrToInt(read);
var cmsg = @intToPtr([*]u8, structAddr);
const vTypePtr = VSerDeser.unMarshall(cmsg[0..read_len], self.allocator);
//return &cmsg[0..read_len];
return vTypePtr;
}
// iterator structure
const Iterator = struct {
const ItSelf = @This();
db: *Self = undefined,
innerIt: *cleveldb.leveldb_iterator_t = undefined,
allocator: *Allocator = undefined,
const ConstIter_t = *const cleveldb.leveldb_iterator_t;
fn init(allocator: *Allocator, db: *Self) !*Iterator {
const obj = try allocator.create(Iterator);
obj.allocator = allocator;
const result = cleveldb.leveldb_create_iterator(db.leveldbHandle, db.readOptions);
if (result) |innerhandle| {
obj.innerIt = innerhandle;
return obj;
}
return error.CannotCreateIterator;
}
pub fn first(self: *ItSelf) void {
cleveldb.leveldb_iter_seek_to_first(self.innerIt);
}
/// iterKey retrieve the value of the iterator
/// the memory on the value has been allocated and needs to be freed if not used
pub fn iterKey(self: *ItSelf) ?*align(1) KOUT {
var read_len: usize = 0;
const read: ?[*c]const u8 = cleveldb.leveldb_iter_key(self.innerIt, &read_len);
if (read) |existValue| {
const structAddr = @ptrToInt(existValue);
var cmsg = @intToPtr([*]const u8, structAddr);
const spanRead = mem.bytesAsSlice(u8, cmsg[0..read_len]);
const vTypePtr = KSerDeser.unMarshall(spanRead, self.allocator);
return vTypePtr;
}
return null;
}
/// iterValue retrieve the value of the iterator
/// the memory on the value has been allocated and needs to be freed if not used
pub fn iterValue(self: *ItSelf) ?*align(1) VOUT {
var read_len: usize = 0;
const read: ?[*c]const u8 = cleveldb.leveldb_iter_value(self.innerIt, &read_len);
if (read) |existValue| {
const structAddr = @ptrToInt(existValue);
var cmsg = @intToPtr([*]const u8, structAddr);
const spanRead = mem.bytesAsSlice(u8, cmsg[0..read_len]);
const vTypePtr = VSerDeser.unMarshall(spanRead, self.allocator);
return vTypePtr;
}
return null;
}
pub fn next(self: *ItSelf) void {
cleveldb.leveldb_iter_next(self.innerIt);
}
pub fn isValid(self: *ItSelf) bool {
const result = cleveldb.leveldb_iter_valid(self.innerIt);
return result > 0;
}
pub fn deinit(self: *ItSelf) void {
cleveldb.leveldb_iter_destroy(self.innerIt);
}
};
pub fn iterator(self: *Self) !*Iterator {
return Iterator.init(self.allocator, self);
}
};
}
test "test iterators" {
// already created database
var filename = "countingstorage\x00";
var allocator = std.heap.c_allocator;
const SS = LevelDBHash(u32, u32);
var l = try SS.init(&allocator);
defer l.deinit();
debug.print("opening databse", .{});
try l.open(filename);
defer l.close();
debug.print("create iterator", .{});
const iterator = try l.iterator();
defer iterator.deinit();
debug.print("call first", .{});
iterator.first();
var r: ?*align(1) u32 = null;
while (iterator.isValid()) {
debug.print("iterKey", .{});
r = iterator.iterKey();
var v = iterator.iterValue();
debug.print("key :{} value: {}\n", .{ r.?.*, v.?.* });
allocator.destroy(v.?);
iterator.next();
}
debug.print("now, close the iterator\n", .{});
}
test "test no specialization" {
var allocator = std.heap.c_allocator;
const SS = LevelDBHash(u32, u8);
_ = try SS.init(&allocator);
//var l = try SS.init(&allocator);
// assert(l != null);
}
test "test storing ints" {
var filename = "countingstorage\x00";
var allocator = std.heap.c_allocator;
const SS = LevelDBHash(u32, u32);
var l = try SS.init(&allocator);
defer l.deinit();
_ = try l.open(filename);
var i: u32 = 0;
while (i < 1000) {
try l.put(i, i + 10);
i += 1;
}
l.close();
}
test "test storing letters" {
var filename = "stringstoragetest\x00";
var allocator = std.heap.c_allocator;
const SS = LevelDBHashArray(u8, u8);
var l = try SS.init(&allocator);
defer l.deinit();
_ = try l.open(filename);
const MAX_ITERATIONS = 100_000;
var i: u64 = 0;
while (i < MAX_ITERATIONS) {
var keyBuffer = [_]u8{ 65, 65, 65, 65, 65, 65 };
var valueBuffer = [_]u8{ 65, 65, 65, 65, 65, 65 };
_ = c.sprintf(&keyBuffer[0], "%d", i % 1000);
_ = c.sprintf(&valueBuffer[0], "%d", (i + 1) % 1000);
// debug.print(" {} -> {} , key length {}\n", .{ keyBuffer, valueBuffer, keyBuffer.len });
try l.put(keyBuffer[0..], valueBuffer[0..]);
const opt = try l.get(keyBuffer[0..]);
allocator.destroy(opt.?);
i += 1;
// used for reduce pression in test
if (i % 100_000 == 0) {
_ = c.sleep(2);
}
}
var s = "1\x00AAAA";
const t = mem.span(s);
debug.print("test key length : {}\n", .{t[0..].len});
const lecturealea = try l.get(t[0..]);
debug.assert(lecturealea != null);
debug.print("retrieved : {}\n", .{lecturealea});
if (lecturealea) |value| {
allocator.destroy(value);
}
const it = try l.iterator();
defer allocator.destroy(it);
defer l.deinit();
it.first();
while (it.isValid()) {
const optK = it.iterKey();
const optV = it.iterValue();
if (optK) |k| {
defer allocator.destroy(k);
debug.print(" {any} value : {any}\n", .{ k.*, optV.?.* });
// debug.print(" key for string \"{}\" \n", .{k.*});
const ovbg = try l.get(k.*);
if (ovbg) |rv| {
debug.print(" {any} value : {any}\n", .{ k.*, rv.* });
}
}
if (optV) |v| {
defer allocator.destroy(v);
debug.print(" value for string \"{any}\" \n", .{v.*});
}
it.next();
}
it.deinit();
l.close();
}
// test "test marshalling" {
// debug.print("start marshall tests\n", .{});
// var allocator = std.heap.c_allocator;
// const StringMarshall = ArrSerDeserType(u8);
// const stringToMarshall = "hello\x00";
// debug.print("original string ptr \"{}\"\n", .{@ptrToInt(stringToMarshall)});
// const sspan = mem.span(stringToMarshall);
// debug.print("span type \"{}\"\n", .{@typeInfo(@TypeOf(sspan))});
// const marshalledC = StringMarshall.marshall(&sspan, &allocator);
// debug.print("marshalled \"{any}\", ptr {any} \n", .{ marshalledC, marshalledC.ptr });
// debug.print("pointer to first element {} \n", .{@ptrToInt(marshalledC.ptr)});
// debug.assert(&marshalledC[0] == &stringToMarshall[0]);
// }
// test "test reading" {
// var filename = "countingstorage\x00";
// var allocator = std.heap.c_allocator;
// const SS = LevelDBHash(u32, u32);
// var l = try SS.init(&allocator);
// defer l.deinit();
// _ = try l.open(filename);
// var i: u32 = 0;
// while (i < 1000) {
// const v = try l.get(i);
// debug.assert(v.?.* == i + 10);
// i += 1;
// }
// l.close();
// }
// test "test serialization types" {
// // var filename : [100]u8 = [_]u8{0} ** 100;
// var filename = "hellosimpletypes2\x00";
// var allocator = std.heap.c_allocator;
// const u32SerializationType = SerDeserType(u32);
// const u8ArrSerializationType = ArrSerDeserType(u8);
// const SS = LevelDBHashWithSerialization(u32, u32, u32, u8, []const u8, []u8, u32SerializationType, u8ArrSerializationType);
// var l = try SS.init(&allocator);
// _ = try l.open(filename);
// var h = @intCast(u32, 5);
// var w = [_]u8{ 'w', 'o', 'r', 'l', 'd', 0x00 };
// // debug.print("slice size : {}\n", .{w[0..].len});
// _ = try l.put(h, w[0..]);
// const t = try l.get(h);
// debug.print("returned value {}\n", .{t.?.*});
// if (t) |result| {
// debug.print("result is :{}\n", .{result.*});
// // debug.print("result type is :{}\n", .{@TypeOf(result.*)});
// }
// defer l.close();
// }
// RAW C API Tests
//test "creating file" {
// const options = cleveldb.leveldb_options_create();
// cleveldb.leveldb_options_set_create_if_missing(options, 1);
// var err: [*c]u8 = null;
// // const db = c.leveldb_open(options, "testdb", @intToPtr([*c][*c]u8,@ptrToInt(&err[0..])));
// const db = cleveldb.leveldb_open(options, "testdb", &err);
// if (err != null) {
// _ = c.printf("open failed");
// defer cleveldb.leveldb_free(err);
// return;
// }
// var woptions = cleveldb.leveldb_writeoptions_create();
// cleveldb.leveldb_put(db, woptions, "key", 3, "value", 6, &err);
//
// const roptions = cleveldb.leveldb_readoptions_create();
// var read: [*c]u8 = null;
// var read_len: usize = 0;
// read = cleveldb.leveldb_get(db, roptions, "key", 3, &read_len, &err);
// if (err != null) {
// _ = c.printf("open failed");
// defer cleveldb.leveldb_free(err);
// return;
// }
// _ = c.printf("returned : %s %d\n", read, read_len);
// cleveldb.leveldb_close(db);
//}
|
0 | repos | repos/iotmonitor/README.md |
## IOTMonitor project
IotMonitor is an effortless and lightweight mqtt monitoring for devices (things) and agents on Linux.
IotMonitor aims to solve the "always up" problem of large IOT devices and agents system. This project is successfully used every day for running smart home automation system.
Considering large and longlived running mqtt systems can hardly rely only on monolytics plateforms, the reality is always composite as some agents or functionalities increase with time. Diversity also occurs in running several programming languages implementation for agents.
This project offers a simple command line, as in *nix system, to monitor MQTT device or agents system. MQTT based communication devices (IOT) and agents are watched, and alerts are emitted if devices or agents are not responding any more. Declared software agents are restarted by iotmonitor when crashed.
In the behaviour, once the mqtt topics associated to a thing or agent is declared, IotMonitor records and restore given MQTT "states topics" as they go and recover. It helps reinstalling IOT things state, to avoid lots of administration tasks.
IotMonitor use a TOML config file. Each device has an independent configured communication message time out. When the device stop communication on this topic, the iotmonitor publish a specific monitoring failure topic for the lots device, with the latest contact timestamp. This topic is labelled :
home/monitoring/expire/[device_name]
This topic can then be displayed or alerted to inform that the device or agent is not working properly.
This project is based on C Paho MQTT client library, use leveldb as state database.
### Running the project on linux
#### Using Nix
Install Nix, [https://nixos.org/download.html](https://nixos.org/download.html)
then, using the following `shell.nix` file,
```
{ nixpkgs ? <nixpkgs>, iotstuff ? import (fetchTarball
"https://github.com/mqttiotstuff/nix-iotstuff-repo/archive/9b12720.tar.gz")
{ } }:
iotstuff.pkgs.mkShell rec { buildInputs = [ iotstuff.iotmonitor ]; }
```
run :
```
nix-shell shell.nix
```
or : (with the shell.nix in the folder)
```
nix-shell
```
#### Using Nix Flake
nix run git+https://github.com/mqttiotstuff/iotmonitor?submodules=1
build with flake :
git clone --recursive https://github.com/mqttiotstuff/iotmonitor
nix build "git+file://$(pwd)?submodules=1"
#### Using docker,
[see README in docker subfolder, for details and construct the image](docker/README.md)
launch the container from image :
```bash
docker run --rm -d -u $(id --user) -v `pwd`:/config iotmonitor
```
#### From scratch
for building the project, the following elements are needed :
- leveldb library (used for storing stated)
- C compiler (builds essentials)
- cmake
- zig : 0.9.1
then launch the following commands :
```bash
git clone --recursive https://github.com/frett27/iotmonitor
cd iotmonitor
cd paho.mqtt.c
cmake -DPAHO_BUILD_STATIC=true .
make
cd ..
mkdir bin
zig build -Dcpu=baseline -Dtarget=native-native-gnu
```
### Configuration File
The configuration is defined in the `config.toml` TOML file, (see an example in the root directory)
A global Mqtt broker configuration section is defined using a heading `[mqtt]`
the following parameters are found :
```toml
[mqtt]
serverAddress="tcp://localhost:1883"
baseTopic="home/monitoring"
user=""
password=""
```
An optional clientid can also be specified to change the mqtt clientid, a default "iotmonitor" is provided
#### Device declaration
In the configuration toml file, each device is declared in a section using a "device_" prefix
in the section : the following elements can be found :
```toml
[device_esp04]
watchTimeOut=60
helloTopic="home/esp04"
watchTopics="home/esp04/sensors/#"
stateTopics="home/esp04/actuators/#"
```
- `watchTimeOut` : watch dog for alive state, when the timeout is reached without and interactions on watchTopics, then iotmonitor trigger an expire message for the device
- `helloTopic` : the topic to observe to welcome the device. This topic trigger the state recovering for the device and agents. IotMonitor, resend the previous stored `stateTopics`, the content of the helloTopic is not used (every first mqtt topic can be used to restore state)
- `watchTopics` : the topic pattern to observe to know the device is alive
- `stateTopics` : list of topics for recording the states and reset them as they are welcomed
#### Agents declarations
Agents are declared using an "agent_" prefix in the section. Agents are devices with an associated command line (`exec` config key) that trigger the start of the software agent. IotMonitor checks periodically if the process is running, and relaunch it if needed.
```toml
[agent_ledboxdaemon]
exec="source ~/mqttagents/p3/bin/activate;cd ~/mqttagents/mqtt-agent-ledbox;python3 ledboxdaemon.py"
watchTopics="home/agents/ledbox/#"
```
IotMonitor running the processes identify the process using a specific bash command line containing an IOTMONITOR tag, which is recognized to detect if the process is running. Monitored processes are detached from the iotmonitor process, avoiding to relaunch the whole system in the case of restarting the `iotmonitor` process.
Agents may also have `helloTopic`, `stateTopics` and `watchTimeOut` as previously described.
#### State restoration for things and agents
At startup OR when the `helloTopic` is fired, iotmonitor fire the previousely recorded states on mqtt, this permit the device (things), to take it's previoulsy state, as if it has not been stopped.. All mqtt recorded states (`stateTopics`) are backuped by iotmonitor in a leveldb database.
For practical reasons, this permit to centralize the state, and restore them when an iot device has rebooted. If used this functionnality, reduce the need to implement a cold state storage for each agent or device. Starting or stopping iotmonitor, redefine the state for all elements.
#### Monitoring iotmonitor :-)
IotMonitor publish a counter on the `home/monitoring/up` topic every seconds. One can then monitor the iotmonitor externally.
The counter is resetted at each startup.
### Credits
- zig-toml : for zig toml parser
- paho eclipse mqtt c library
- levedb database
- routez : for http server integration
|
0 | repos | repos/iotmonitor/build.zig | const std = @import("std");
const mem = std.mem;
const fs = std.fs;
const Builder = std.build.Builder;
const ArrayList = std.ArrayList;
const builtin = @import("builtin");
const Target = std.Target;
const FileSource = std.build.FileSource;
pub fn build(b: *Builder) void {
const exe = b.addExecutable("iotmonitor", "iotmonitor.zig");
const target = b.standardTargetOptions(.{});
exe.setTarget(target);
exe.setBuildMode(b.standardReleaseOptions());
exe.addPackagePath("toml", "zig-toml/src/toml.zig");
exe.addPackagePath("clap", "zig-clap/clap.zig");
exe.addPackage(.{
.name = "routez",
.path = FileSource.relative("routez/src/routez.zig"),
.dependencies = &[_]std.build.Pkg{.{
.name = "zuri",
.path = FileSource.relative("routez/zuri/src/zuri.zig"),
}},
});
const Activate_Tracy = false;
if (Activate_Tracy) {
exe.addPackage(.{ .name = "tracy", .path = FileSource.relative("zig-tracy/src/lib.zig") });
exe.addIncludeDir("tracy/");
exe.addLibPath("tracy/library/unix");
exe.linkSystemLibrary("tracy-debug");
} else {
exe.addPackage(.{ .name = "tracy", .path = FileSource.relative("nozig-tracy/src/lib.zig") });
}
exe.setOutputDir("bin");
// exe.setTarget(.{ .cpu = builtin.Arch.arm });
// stripping symbols reduce the size of the exe
// exe.strip = true;
exe.linkLibC();
// static add the paho mqtt library
exe.addIncludeDir("paho.mqtt.c/src");
exe.addLibPath("paho.mqtt.c/build/output");
exe.addLibPath("paho.mqtt.c/src");
exe.addObjectFile("paho.mqtt.c/src/libpaho-mqtt3c.a");
// these libs are needed by leveldb backend
exe.linkSystemLibrary("leveldb");
b.default_step.dependOn(&exe.step);
}
|
0 | repos | repos/iotmonitor/flake.nix | {
description = "Flake for building Iotmonitor";
# inputs = [ zig git cmake leveldb pandoc ];
inputs = {
nixpkgs.url = "https://github.com/NixOS/nixpkgs/archive/22.05.tar.gz";
flake-utils.url = "github:numtide/flake-utils";
};
outputs = { self, nixpkgs, flake-utils }:
flake-utils.lib.eachDefaultSystem (system:
let pkgs = nixpkgs.legacyPackages.${system};
in {
packages.iotmonitor =
# Notice the reference to nixpkgs here.
pkgs.stdenv.mkDerivation {
name = "iotmonitor";
src = self;
buildInputs = [ pkgs.zig pkgs.git pkgs.cmake pkgs.leveldb pkgs.pandoc ];
configurePhase = ''
ls
zig version
'';
buildPhase = ''
make
zig build
'';
installPhase = ''
mkdir -p $out/bin
mv bin/iotmonitor $out/bin
'';
};
defaultPackage = self.packages.${system}.iotmonitor;
}
);
}
|
0 | repos | repos/iotmonitor/iotmonitor.zig | //
// IOT Monitor - monitor and recover state for iot device and software agents
//
// pfreydiere - 2019 - 2022
//
const std = @import("std");
const json = std.json;
const debug = std.debug;
const log = std.log;
const assert = debug.assert;
const mem = std.mem;
const os = std.os;
const io = std.io;
const version = @import("version.zig");
// used for sleep, and other, it may be removed
// to relax libC needs
const c = @cImport({
@cInclude("stdio.h");
@cInclude("unistd.h");
@cInclude("signal.h");
@cInclude("time.h");
@cInclude("string.h");
});
const leveldb = @import("leveldb.zig");
const mqtt = @import("mqttlib.zig");
const processlib = @import("processlib.zig");
const topics = @import("topics.zig");
const toml = @import("toml");
const clap = @import("clap");
// profiling, to check performance on functions
// this is mocked in the build.zig (activate this tracy library)
const tracy = @import("tracy");
const stdoutFile = std.io.getStdOut();
const out = std.fs.File.writer(stdoutFile);
const Verbose = false;
// This structure defines the process informations
// with live agent running, this permit to track the process and
// relaunch it if needed
//
const AdditionalProcessInformation = struct {
// pid is to track the process while running
pid: ?i32 = undefined,
// process identifier attributed by IOTMonitor, to track existing processes
// processIdentifier: []const u8 = "",
exec: []const u8 = "",
// last time the process is restarted
lastRestarted: c.time_t = 0,
// number of time, the process is restarted
restartedCount: u64 = 0,
};
const MonitoringInfo = struct {
// name of the device
name: []const u8 = "",
watchTopics: []const u8,
nextContact: c.time_t,
timeoutValue: u32 = 30,
stateTopics: ?[]const u8 = null,
helloTopic: ?[]const u8 = null,
helloTopicCount: u64 = 0,
allocator: mem.Allocator,
// in case of process informations,
// used to relaunch or not the process, permitting to
// take a process out of the monitoring, and then reintegrate it
enabled: bool = true,
associatedProcessInformation: ?*AdditionalProcessInformation = null,
fn init(allocator: mem.Allocator) !*MonitoringInfo {
const device = try allocator.create(MonitoringInfo);
device.allocator = allocator;
device.stateTopics = null;
device.helloTopic = null;
device.helloTopicCount = 0;
device.timeoutValue = 30;
device.associatedProcessInformation = null;
device.enabled = true;
return device;
}
fn deinit(self: *MonitoringInfo) void {
self.allocator.destroy(self);
}
fn updateNextContact(device: *MonitoringInfo) !void {
_ = c.time(&device.*.nextContact);
device.*.nextContact = device.*.nextContact + @intCast(c_long, device.*.timeoutValue);
}
fn hasExpired(device: *MonitoringInfo) !bool {
var currentTime: c.time_t = undefined;
_ = c.time(¤tTime);
const diff = c.difftime(currentTime, device.*.nextContact);
if (diff > 0) return true;
return false;
}
};
fn stripLastWildCard(watchValue: []const u8) ![]const u8 {
assert(watchValue.len > 0);
if (watchValue[watchValue.len - 1] == '#') {
return watchValue[0 .. watchValue.len - 2];
}
return watchValue;
}
test "test update time" {
var d = MonitoringInfo{
.timeoutValue = 1,
.watchTopics = "",
.nextContact = undefined,
.allocator = undefined,
.helloTopic = undefined,
.stateTopics = undefined,
.associatedProcessInformation = undefined,
};
try d.updateNextContact();
_ = c.sleep(3);
debug.assert(try d.hasExpired());
d.timeoutValue = 20;
try d.updateNextContact();
_ = c.sleep(3);
debug.assert(!try d.hasExpired());
}
pub fn secureZero(s: []u8) void {
var i: u32 = 0;
while (i < s.len) {
s[i] = '\x00';
i = i + 1;
}
}
// parse the device info,
// device must have a watch topics
fn parseDevice(allocator: mem.Allocator, name: []const u8, entry: *toml.Table) !*MonitoringInfo {
const device = try MonitoringInfo.init(allocator);
errdefer device.deinit();
const allocName = try allocator.alloc(u8, name.len + 1);
secureZero(allocName);
std.mem.copy(u8, allocName, name);
device.name = allocName;
if (entry.keys.get("exec")) |exec| {
const execValue = exec.String;
assert(execValue.len > 0);
const execCommand = try allocator.allocSentinel(u8, execValue.len, 0);
mem.copy(u8, execCommand, execValue);
const additionalStructure = try allocator.create(AdditionalProcessInformation);
additionalStructure.exec = execCommand;
additionalStructure.pid = null;
additionalStructure.lastRestarted = 0;
additionalStructure.restartedCount = 0;
device.associatedProcessInformation = additionalStructure;
}
if (entry.keys.get("watchTopics")) |watch| {
// there may have a wildcard at the end
// strip it to compare to the received topic
const watchValue = watch.String;
assert(watchValue.len > 0);
const strippedLastWildCard = try stripLastWildCard(watchValue);
const stopic = try allocator.alloc(u8, strippedLastWildCard.len);
mem.copy(u8, stopic, strippedLastWildCard);
device.watchTopics = stopic;
if (Verbose) {
_ = try out.print("add {s} to device {s} \n", .{ device.name, device.watchTopics });
}
} else {
return error.DEVICE_MUST_HAVE_A_WATCH_TOPIC;
}
if (entry.keys.get("stateTopics")) |statewatch| {
// there may have a wildcard at the end
// strip it to compare to the received topic
const watchValue = statewatch.String;
assert(watchValue.len > 0);
const strippedLastWildCard = try stripLastWildCard(watchValue);
const stopic = try allocator.alloc(u8, strippedLastWildCard.len);
mem.copy(u8, stopic, strippedLastWildCard);
device.stateTopics = stopic;
if (Verbose) {
_ = try out.print("add {s} to device {s} \n", .{ device.name, device.stateTopics });
}
}
if (entry.keys.get("helloTopic")) |hello| {
const helloValue = hello.String;
assert(helloValue.len > 0);
const stopic = try allocator.alloc(u8, helloValue.len);
mem.copy(u8, stopic, helloValue);
device.helloTopic = stopic;
if (Verbose) {
_ = try out.print("hello topic for device {s}\n", .{device.helloTopic});
}
}
if (entry.keys.get("watchTimeOut")) |timeout| {
const timeOutValue = timeout.Integer;
device.timeoutValue = @intCast(u32, timeOutValue);
if (Verbose) {
_ = try out.print("watch timeout for topic for device {s}\n", .{device.helloTopic});
}
}
try device.updateNextContact();
return device;
}
const Config = struct { clientId: []u8, mqttBroker: []u8, user: []u8, password: []u8, clientid: []u8, mqttIotmonitorBaseTopic: []u8 };
const HttpServerConfig = struct { activateHttp: bool = true, listenAddress: []u8, port: u16 = 8079 };
var MqttConfig: *Config = undefined;
var HttpConfig: *HttpServerConfig = undefined;
fn parseTomlConfig(allocator: mem.Allocator, _alldevices: *AllDevices, filename: []const u8) !void {
const t = tracy.trace(@src());
defer t.end();
// getting config parameters
var parser: toml.Parser = undefined;
defer parser.deinit();
var config = try toml.parseFile(allocator, filename, &parser); // no custom parser
defer config.deinit();
var it = config.keys.iterator();
while (it.next()) |e| {
// get table value
switch (e.value_ptr.*) {
toml.Value.Table => |table| {
if (table.name.len >= 7) {
const DEVICEPREFIX = "device_";
const AGENTPREFIX = "agent_";
const isDevice = mem.eql(u8, table.name.ptr[0..DEVICEPREFIX.len], DEVICEPREFIX);
const isAgent = mem.eql(u8, table.name.ptr[0..AGENTPREFIX.len], AGENTPREFIX);
if (isDevice or isAgent) {
if (Verbose) {
try out.print("device found :{s}\n", .{table.name});
}
var prefixlen = AGENTPREFIX.len;
if (isDevice) prefixlen = DEVICEPREFIX.len;
const dev = try parseDevice(allocator, table.name.ptr[prefixlen..table.name.len], table);
if (Verbose) {
try out.print("add {s} to device list, with watch {s} and state {s} \n", .{ dev.name, dev.watchTopics, dev.stateTopics });
}
_ = try _alldevices.put(dev.name, dev);
} else {
try out.print("bad prefix for section :{s} , only device_ or agent_ accepted, skipped \n", .{e.key_ptr});
}
}
},
toml.Value.None, toml.Value.String, toml.Value.Boolean, toml.Value.Integer, toml.Value.Float, toml.Value.Array, toml.Value.ManyTables => continue,
}
}
const conf = try allocator.create(Config);
if (config.keys.get("mqtt")) |mqttconfig| {
if (mqttconfig.Table.keys.get("serverAddress")) |configAdd| {
conf.mqttBroker = try allocator.alloc(u8, configAdd.String.len);
mem.copy(u8, conf.mqttBroker, configAdd.String);
} else {
return error.noKeyServerAddress;
}
if (mqttconfig.Table.keys.get("user")) |u| {
conf.user = try allocator.alloc(u8, u.String.len);
mem.copy(u8, conf.user, u.String);
} else {
return error.ConfigNoUser;
}
if (mqttconfig.Table.keys.get("password")) |p| {
conf.password = try allocator.alloc(u8, p.String.len);
mem.copy(u8, conf.password, p.String);
} else {
return error.ConfigNoPassword;
}
if (mqttconfig.Table.keys.get("clientid")) |cid| {
conf.clientid = try allocator.alloc(u8, cid.String.len);
mem.copy(u8, conf.clientid, cid.String);
try out.print("Using {s} as clientid \n", .{conf.clientid});
} else {
conf.clientid = try allocator.alloc(u8, "iotmonitor".len);
mem.copy(u8, conf.clientid, "iotmonitor");
}
const topicBase = if (mqttconfig.Table.keys.get("baseTopic")) |baseTopic| baseTopic.String else "home/monitoring";
conf.mqttIotmonitorBaseTopic = try allocator.alloc(u8, topicBase.len + 1);
conf.mqttIotmonitorBaseTopic[topicBase.len] = 0;
mem.copy(u8, conf.mqttIotmonitorBaseTopic, topicBase[0..topicBase.len]);
} else {
return error.ConfigNoMqttSection;
}
const httpconf = try allocator.create(HttpServerConfig);
if (config.keys.get("http")) |httpconfig| {
httpconf.*.activateHttp = true;
if (httpconfig.Table.keys.get("bind")) |baddr| {
httpconf.listenAddress = try allocator.alloc(u8, baddr.String.len);
mem.copy(u8, httpconf.listenAddress, baddr.String);
} else {
const localhostip = "127.0.0.1";
httpconf.listenAddress = try allocator.alloc(u8, localhostip.len);
mem.copy(u8, httpconf.listenAddress, localhostip);
}
if (httpconfig.Table.keys.get("port")) |port| {
httpconf.*.port = @intCast(u16, port.Integer);
} else {
httpconf.*.port = 8079;
}
}
HttpConfig = httpconf;
MqttConfig = conf;
}
// MQTT call back to handle the error handling and not
// send the error to C paho library
fn _external_callback(topic: []u8, message: []u8) void {
callback(topic, message) catch {
@panic("error in the callback");
};
}
// MQTT Callback implementation
fn callback(topic: []u8, message: []u8) !void {
const t = tracy.trace(@src());
defer t.end();
// MQTT callback
if (Verbose) {
try out.print("on topic {s}\n", .{topic});
try out.print(" message arrived {s}\n", .{message});
try out.writeAll(topic);
try out.writeAll("\n");
}
// look for all devices
var iterator = alldevices.iterator();
// device loop
while (iterator.next()) |e| {
const deviceInfo = e.value_ptr.*;
if (Verbose) {
if (deviceInfo.stateTopics) |stopic| {
try out.print("evaluate state topic {s} with incoming topic {s} \n", .{ stopic, topic });
}
}
const watchTopic = deviceInfo.watchTopics;
const storeTopic = deviceInfo.stateTopics;
const helloTopic = deviceInfo.helloTopic;
if (storeTopic) |store| {
if (try topics.doesTopicBelongTo(topic, store)) |_| {
// always store topic, even if the monitoring is not enabled
// store sub topic in leveldb
// trigger the refresh for timeout
if (Verbose) {
try out.print("sub topic to store value :{s}, in {s}\n", .{ message, topic });
try out.print("length {}\n", .{topic.len});
}
db.put(topic, message) catch |errStorage| {
log.warn("fail to store message {s} for topic {s}, on database with error {} \n", .{ message, topic, errStorage });
};
}
}
if (helloTopic) |hello| {
if (mem.eql(u8, topic, hello)) {
if (Verbose) {
try out.print("device started, put all state informations \n", .{});
}
// count the number of hello topic
//
//
deviceInfo.helloTopicCount += 1;
// iterate on db, on state topic
const itstorage = try db.iterator();
// itstorage is an allocated pointer
defer globalAllocator.destroy(itstorage);
defer itstorage.deinit();
itstorage.first();
while (itstorage.isValid()) {
var storedTopic = itstorage.iterKey();
if (storedTopic) |storedTopicValue| {
defer globalAllocator.destroy(storedTopicValue);
if (storedTopicValue.len >= topic.len) {
const slice = storedTopicValue.*;
if (mem.eql(u8, slice[0..topic.len], topic[0..])) {
if (deviceInfo.enabled) {
// send the state only if the monitoring is enabled
var stateTopic = itstorage.iterValue();
if (stateTopic) |stateTopicValue| {
if (Verbose) {
try out.print("sending state {s} to topic {s}\n", .{ stateTopic.?.*, slice });
}
defer globalAllocator.destroy(stateTopicValue);
const topicWithSentinel = try globalAllocator.allocSentinel(u8, storedTopicValue.*.len, 0);
defer globalAllocator.free(topicWithSentinel);
mem.copy(u8, topicWithSentinel[0..], storedTopicValue.*);
// resend state
cnx.publish(topicWithSentinel, stateTopicValue.*) catch |errorMqtt| {
log.warn("ERROR {} fail to publish initial state on topic {}", .{ errorMqtt, topicWithSentinel });
try out.print(".. state restoring done, listening mqtt topics\n", .{});
};
}
}
}
}
}
itstorage.next();
}
}
} // hello
if (try topics.doesTopicBelongTo(topic, watchTopic)) |_| {
// trigger the timeout for the iot element
try deviceInfo.updateNextContact();
}
}
if (Verbose) {
try out.print("end of callback \n", .{});
}
}
// global types
const AllDevices = std.StringHashMap(*MonitoringInfo);
const DiskHash = leveldb.LevelDBHashArray(u8, u8);
// global variables
var globalAllocator = std.heap.raw_c_allocator;
var alldevices: AllDevices = undefined;
var db: *DiskHash = undefined;
test "read whole database" {
db = try DiskHash.init(&globalAllocator);
const filename = "iotdb.leveldb";
_ = try db.open(filename);
defer db.close();
const iterator = try db.iterator();
defer globalAllocator.destroy(iterator);
defer iterator.deinit();
log.warn("Dump the iot database \n", .{});
iterator.first();
while (iterator.isValid()) {
const optReadKey = iterator.iterKey();
if (optReadKey) |k| {
defer globalAllocator.destroy(k);
const optReadValue = iterator.iterValue();
if (optReadValue) |v| {
log.warn(" key :{} value: {}\n", .{ k.*, v.* });
defer globalAllocator.destroy(v);
}
}
iterator.next();
}
}
// main connection for subscription
var cnx: *mqtt.MqttCnx = undefined;
var cpt: u32 = 0;
const MAGICPROCSSHEADER = "IOTMONITORMAGIC_";
const MAGIC_BUFFER_SIZE = 16 * 1024;
const LAUNCH_COMMAND_LINE_BUFFER_SIZE = 16 * 1024;
fn launchProcess(monitoringInfo: *MonitoringInfo) !void {
assert(monitoringInfo.associatedProcessInformation != null);
const associatedProcessInformation = monitoringInfo.*.associatedProcessInformation.?.*;
const pid = try os.fork();
if (pid == 0) {
// detach from parent, this permit the process to live independently from
// its parent
_ = c.setsid();
const bufferMagic = try globalAllocator.allocSentinel(u8, MAGIC_BUFFER_SIZE, 0);
defer globalAllocator.free(bufferMagic);
_ = c.sprintf(bufferMagic.ptr, "%s%s", MAGICPROCSSHEADER, monitoringInfo.name.ptr);
const commandLineBuffer = try globalAllocator.allocSentinel(u8, LAUNCH_COMMAND_LINE_BUFFER_SIZE, 0);
defer globalAllocator.free(commandLineBuffer);
const exec = associatedProcessInformation.exec;
_ = c.sprintf(commandLineBuffer.ptr, "echo %s;%s;echo END", bufferMagic.ptr, exec.ptr);
// launch here a bash to have a silent process identification
const argv = [_][]const u8{
"/bin/bash",
"-c",
commandLineBuffer[0..c.strlen(commandLineBuffer)],
};
var m = std.BufMap.init(globalAllocator);
// may add additional information about the process ...
try m.put("IOTMONITORMAGIC", bufferMagic[0..c.strlen(bufferMagic)]);
// execute the process
std.process.execve(globalAllocator, &argv, &m) catch {
unreachable;
};
// if succeeded the process is replaced
} else {
try out.print("process launched, pid : {}\n", .{pid});
monitoringInfo.*.associatedProcessInformation.?.pid = pid;
monitoringInfo.*.associatedProcessInformation.?.restartedCount += 1;
_ = c.time(&monitoringInfo.*.associatedProcessInformation.?.lastRestarted);
// launch mqtt restart information process in monitoring
try publishProcessStarted(monitoringInfo);
}
}
test "test_launch_process" {
globalAllocator = std.heap.c_allocator;
alldevices = AllDevices.init(globalAllocator);
var processInfo = AdditionalProcessInformation{
.exec = "sleep 20",
.pid = undefined,
};
var d = MonitoringInfo{
.timeoutValue = 1,
.name = "MYPROCESS",
.watchTopics = "",
.nextContact = undefined,
.allocator = undefined,
.helloTopic = undefined,
.stateTopics = undefined,
.associatedProcessInformation = &processInfo,
};
// try launchProcess(&d);
// const pid: i32 = d.associatedProcessInformation.?.*.pid.?;
// debug.warn("pid launched : {}\n", .{pid});
try alldevices.put(d.name, &d);
// var p: processlib.ProcessInformation = .{};
// const processFound = try processlib.getProcessInformations(pid, &p);
// assert(processFound);
try processlib.listProcesses(handleCheckAgent);
}
fn handleCheckAgent(processInformation: *processlib.ProcessInformation) void {
// iterate over the devices, to check which device belong to this process
// information
var it = alldevices.iterator();
while (it.next()) |deviceInfo| {
const device = deviceInfo.value_ptr.*;
// not on optional
if (device.associatedProcessInformation) |infos| {
// check if process has the magic Key in the process list
var itCmdLine = processInformation.iterator();
while (itCmdLine.next()) |a| {
if (Verbose) {
out.print("look in {s}\n", .{a}) catch unreachable;
}
const bufferMagic = globalAllocator.allocSentinel(u8, MAGIC_BUFFER_SIZE, 0) catch unreachable;
defer globalAllocator.free(bufferMagic);
_ = c.sprintf(bufferMagic.ptr, "%s%s", MAGICPROCSSHEADER, device.name.ptr);
const p = c.strstr(a.ptr, bufferMagic.ptr);
if (Verbose) {
out.print("found {*}\n", .{p}) catch unreachable;
}
if (p != null) {
// found in arguments, remember the pid
// of the process
infos.*.pid = processInformation.*.pid;
if (Verbose) {
out.print("process {} is monitored pid found\n", .{infos.pid}) catch unreachable;
}
break;
}
if (Verbose) {
out.writeAll("next ..\n") catch unreachable;
}
}
} else {
continue;
}
}
}
fn runAllMissings() !void {
// once all the process have been browsed,
// run all missing processes
var it = alldevices.iterator();
while (it.next()) |deviceinfo| {
const device = deviceinfo.value_ptr.*;
if (device.associatedProcessInformation) |processinfo| {
// this is a process monitored
if (device.enabled) {
if (processinfo.*.pid == null) {
out.print("running ...{s} \n", .{device.name}) catch unreachable;
// no pid associated to the info
//
launchProcess(device) catch {
@panic("fail to run process");
};
}
} else {
// monitoring not enabled on the process
}
}
}
}
fn checkProcessesAndRunMissing() !void {
const t = tracy.trace(@src());
defer t.end();
// RAZ pid infos
var it = alldevices.iterator();
while (it.next()) |deviceInfo| {
const device = deviceInfo.value_ptr.*;
if (device.associatedProcessInformation) |infos| {
infos.pid = null;
}
}
// list all process for wrapping
try processlib.listProcesses(handleCheckAgent);
try runAllMissings();
}
// this function publish a watchdog for the iotmonitor process
// this permit to check if the monitoring is up
fn publishWatchDog() !void {
const t = tracy.trace(@src());
defer t.end();
var topicBufferPayload = try globalAllocator.alloc(u8, 512);
defer globalAllocator.free(topicBufferPayload);
secureZero(topicBufferPayload);
_ = c.sprintf(topicBufferPayload.ptr, "%s/up", MqttConfig.mqttIotmonitorBaseTopic.ptr);
var bufferPayload = try globalAllocator.alloc(u8, 512);
defer globalAllocator.free(bufferPayload);
secureZero(bufferPayload);
cpt = (cpt + 1) % 1_000_000;
_ = c.sprintf(bufferPayload.ptr, "%d", cpt);
const payloadLength = c.strlen(bufferPayload.ptr);
cnx.publish(topicBufferPayload.ptr, bufferPayload[0..payloadLength]) catch {
log.warn("cannot publish watchdog message, will retryi \n", .{});
};
}
fn publishProcessStarted(mi: *MonitoringInfo) !void {
const t = tracy.trace(@src());
defer t.end();
var topicBufferPayload = try globalAllocator.alloc(u8, 512);
defer globalAllocator.free(topicBufferPayload);
secureZero(topicBufferPayload);
_ = c.sprintf(topicBufferPayload.ptr, "%s/startedprocess/%s", MqttConfig.mqttIotmonitorBaseTopic.ptr, mi.name.ptr);
var bufferPayload = try globalAllocator.alloc(u8, 512);
defer globalAllocator.free(bufferPayload);
secureZero(bufferPayload);
_ = c.sprintf(bufferPayload.ptr, "%d", mi.*.associatedProcessInformation.?.lastRestarted);
const payloadLength = c.strlen(bufferPayload.ptr);
cnx.publish(topicBufferPayload.ptr, bufferPayload[0..payloadLength]) catch {
log.warn("cannot publish watchdog message, will retryi \n", .{});
};
}
// this publish on the mqtt broker the process informations
//
fn publishDeviceMonitoringInfos(device: *MonitoringInfo) !void {
var topicBufferPayload = try globalAllocator.alloc(u8, 512);
defer globalAllocator.free(topicBufferPayload);
secureZero(topicBufferPayload);
_ = c.sprintf(topicBufferPayload.ptr, "%s/helloTopicCount/%s", MqttConfig.mqttIotmonitorBaseTopic.ptr, device.*.name.ptr);
var bufferPayload = try globalAllocator.alloc(u8, 512);
defer globalAllocator.free(bufferPayload);
secureZero(bufferPayload);
_ = c.sprintf(bufferPayload.ptr, "%u", device.helloTopicCount);
const payloadLen = c.strlen(bufferPayload.ptr);
cnx.publish(topicBufferPayload.ptr, bufferPayload[0..payloadLen]) catch {
log.warn("cannot publish timeout message for device {} , will retry \n", .{device.name});
};
}
// this function pulish a mqtt message for a device that is not publishing
// it mqtt messages
fn publishDeviceTimeOut(device: *MonitoringInfo) !void {
var topicBufferPayload = try globalAllocator.alloc(u8, 512);
defer globalAllocator.free(topicBufferPayload);
secureZero(topicBufferPayload);
_ = c.sprintf(topicBufferPayload.ptr, "%s/expired/%s", MqttConfig.mqttIotmonitorBaseTopic.ptr, device.*.name.ptr);
var bufferPayload = try globalAllocator.alloc(u8, 512);
defer globalAllocator.free(bufferPayload);
secureZero(bufferPayload);
_ = c.sprintf(bufferPayload.ptr, "%d", device.nextContact);
const payloadLen = c.strlen(bufferPayload.ptr);
cnx.publish(topicBufferPayload.ptr, bufferPayload[0..payloadLen]) catch {
log.warn("cannot publish timeout message for device {} , will retry \n", .{device.name});
};
}
const JSONStatus = struct {
name: []const u8,
enabled: bool = true,
expired: bool,
};
fn indexHandler(req: Request, res: Response) !void {
_ = req;
const t = tracy.trace(@src());
defer t.end();
var iterator = alldevices.iterator();
try res.setType("application/json");
try res.body.writeAll("[");
var hasone = false;
while (iterator.next()) |e| {
const deviceInfo = e.value_ptr.*;
if (hasone) {
try res.body.writeAll(",");
}
const j = JSONStatus{ .name = deviceInfo.name[0 .. deviceInfo.name.len - 1], .enabled = deviceInfo.enabled, .expired = try deviceInfo.hasExpired() };
// create a json response associated
try json.stringify(j, json.StringifyOptions{}, res.body);
hasone = true;
}
try res.body.writeAll("]");
// try res.write("IotMonitor version 0.2.2");
}
const Address = std.net.Address;
const routez = @import("routez");
const Request = routez.Request;
const Response = routez.Response;
const Server = routez.Server;
const Thread = std.Thread;
var server: Server = undefined;
var addr: Address = undefined;
// http server context
const ServerCtx = struct {};
pub fn startServer(context: ServerCtx) void {
_ = context;
server.listen(addr) catch {
@panic("cannot start listening http server");
};
}
// main procedure
pub fn main() !void {
const params = comptime [_]clap.Param(clap.Help){
clap.parseParam("-h, --help Display this help") catch unreachable,
clap.parseParam("-v, --version Display version") catch unreachable,
clap.parseParam("<TOML CONFIG FILE>...") catch unreachable,
};
var diag = clap.Diagnostic{};
var args = clap.parse(clap.Help, ¶ms, .{ .diagnostic = &diag }) catch |err| {
// Report useful error and exit
diag.report(io.getStdErr().writer(), err) catch {};
return err;
};
defer args.deinit();
if (args.flag("--help")) {
debug.print("\n", .{});
debug.print("start the iotmonitor deamon, usage :\n", .{});
debug.print(" iotmonitor [optional config.toml filepath]\n", .{});
debug.print("\n", .{});
return;
}
if (args.flag("--version")) {
debug.print("{s}", .{version.version});
return;
}
try out.writeAll("IotMonitor start, version ");
try out.writeAll(version.version);
try out.writeAll("\n");
// default
const defaultConfigFile = "config.toml";
var configurationFile = try globalAllocator.alloc(u8, defaultConfigFile.len);
mem.copy(u8, configurationFile, defaultConfigFile);
var arg_index: u32 = 0;
for (args.positionals()) |pos| {
debug.print("{s}\n", .{pos});
debug.print("{}\n", .{pos.len});
if (arg_index == 0) {
globalAllocator.free(configurationFile);
configurationFile = try globalAllocator.alloc(u8, pos.len);
mem.copy(u8, configurationFile, pos);
}
arg_index += 1;
}
try out.writeAll("Reading ");
try out.writeAll(configurationFile);
try out.writeAll(" file\n");
// Friendly error if the file does not exists
var openedtestfile = std.os.open(configurationFile, 0, 0) catch {
try out.writeAll("Cannot open file ");
try out.writeAll(configurationFile);
try out.writeAll("\n");
return;
};
std.os.close(openedtestfile);
alldevices = AllDevices.init(globalAllocator);
try parseTomlConfig(globalAllocator, &alldevices, configurationFile);
try out.writeAll("Opening database\n");
db = try DiskHash.init(&globalAllocator);
const filename = "iotdb.leveldb";
_ = try db.open(filename);
defer db.close();
// connecting to MQTT
var serverAddress: []const u8 = MqttConfig.mqttBroker;
var userName: []const u8 = MqttConfig.user;
var password: []const u8 = MqttConfig.password;
var clientid: []const u8 = MqttConfig.clientid;
try out.writeAll("Connecting to mqtt ..\n");
try out.print(" connecting to \"{s}\" with user \"{s}\" and clientid \"{s}\"\n", .{ serverAddress, userName, clientid });
cnx = try mqtt.MqttCnx.init(&globalAllocator, serverAddress, clientid, userName, password);
if (HttpConfig.activateHttp) {
try out.print("Start embedded http server on port {} \n", .{HttpConfig.*.port});
server = Server.init(
globalAllocator,
.{},
.{routez.all("/", indexHandler)},
);
addr = try Address.parseIp4(HttpConfig.*.listenAddress, HttpConfig.*.port);
const threadConfig: Thread.SpawnConfig = .{};
const threadHandle = try Thread.spawn(threadConfig, startServer, .{.{}});
_ = threadHandle;
try out.print("Http server thread launched\n", .{});
}
try out.print("Checking running monitored processes\n", .{});
try checkProcessesAndRunMissing();
try out.print("Restoring saved states topics ... \n", .{});
// read all elements in database, then redefine the state for all
const it = try db.iterator();
defer globalAllocator.destroy(it);
defer it.deinit();
it.first();
while (it.isValid()) {
const r = it.iterKey();
if (r) |subject| {
defer globalAllocator.destroy(subject);
const v = it.iterValue();
if (v) |value| {
defer globalAllocator.destroy(value);
try out.print("Sending initial stored state {s} to {s}\n", .{ value.*, subject.* });
const topicWithSentinel = try globalAllocator.allocSentinel(u8, subject.*.len, 0);
defer globalAllocator.free(topicWithSentinel);
mem.copy(u8, topicWithSentinel[0..], subject.*);
// if failed, stop the process
cnx.publish(topicWithSentinel, value.*) catch |e| {
log.warn("ERROR {} fail to publish initial state on topic {s}", .{ e, topicWithSentinel });
try out.print(".. State restoring done, listening mqtt topics\n", .{});
};
}
}
it.next();
}
try out.print(".. State restoring done, listening mqtt topics\n", .{});
cnx.callBack = _external_callback;
// register to all, it may be huge, and probably not scaling
_ = try cnx.register("#");
while (true) { // main loop
_ = c.sleep(1); // every 1 seconds
{
// if activated trace this function
const t = tracy.trace(@src());
defer t.end();
// check process that has falled down, and must be restarted
try checkProcessesAndRunMissing();
// watchdog
try publishWatchDog();
var iterator = alldevices.iterator();
while (iterator.next()) |e| {
// publish message
const deviceInfo = e.value_ptr.*;
if (deviceInfo.enabled) {
// if the device is enabled
const hasExpired = try deviceInfo.hasExpired();
if (hasExpired) {
try publishDeviceTimeOut(deviceInfo);
}
try publishDeviceMonitoringInfos(deviceInfo);
}
}
}
}
log.warn("ended", .{});
return;
}
|
0 | repos | repos/iotmonitor/flake.lock | {
"nodes": {
"flake-utils": {
"locked": {
"lastModified": 1642700792,
"narHash": "sha256-XqHrk7hFb+zBvRg6Ghl+AZDq03ov6OshJLiSWOoX5es=",
"owner": "numtide",
"repo": "flake-utils",
"rev": "846b2ae0fc4cc943637d3d1def4454213e203cba",
"type": "github"
},
"original": {
"owner": "numtide",
"repo": "flake-utils",
"type": "github"
}
},
"nixpkgs": {
"locked": {
"narHash": "sha256-M6bJShji9AIDZ7Kh7CPwPBPb/T7RiVev2PAcOi4fxDQ=",
"type": "tarball",
"url": "https://github.com/NixOS/nixpkgs/archive/22.05.tar.gz"
},
"original": {
"type": "tarball",
"url": "https://github.com/NixOS/nixpkgs/archive/22.05.tar.gz"
}
},
"root": {
"inputs": {
"flake-utils": "flake-utils",
"nixpkgs": "nixpkgs"
}
}
},
"root": "root",
"version": 7
}
|
0 | repos | repos/iotmonitor/version.zig | pub const version = "0.2.7";
|
0 | repos/iotmonitor | repos/iotmonitor/man/sections_to_cover.txt |
Name: The name of the command and a pithy one-liner that describes its function.
Synopsis: A terse description of the invocations someone can use to launch the program. These show the types of accepted command-line parameters.
Description: A description of the command or function.
Options: A list of command-line options, and what they do.
Examples: Some examples of common usage.
Exit Values: The possible return codes and their meanings.
Bugs: A list of known bugs and quirks. Sometimes, this is supplemented with (or replaced by) a link to the issue tracker for the project.
Author: The person or people who wrote the command.
Copyright: Your copyright message. These also usually include the type of license under which the program is released.
copy to /usr/share/man/man1
|
0 | repos/iotmonitor | repos/iotmonitor/man/iotmonitor.1.md | % IOTMONITOR(1) iotmonitor 0.2.3
% Patrice Freydiere
% December 2021
# NAME
iotmonitor - monitor and manage execution of mqtt iot processes
# SYNOPSIS
**iotmonitor** [*OPTIONS*]
# DESCRIPTION
**iotMonitor** is an effortless and lightweight mqtt monitoring for devices (things) and agents on Linux.
IotMonitor aims to solve the "always up" problem of large IOT devices and agents system. This project is successfully used every day for running smart home automation system.
Considering large and longlived running mqtt systems can hardly rely only on monolytics plateforms, the reality is always composite as some agents or functionnalities increase with time. Diversity also occurs in running several programming languages implementation for agents.
This project offers a simple command line, as in \*nix system, to monitor MQTT device or agents system. MQTT based communication devices (IOT) and agents are watched, and alerts are emitted if devices or agents are not responding any more. Declared software agents are restarted by iotmonitor when crashed.
# OPTIONS
**--help**
: Display a friendly help message
**-v**, **--version**
: Display the software version
# IOTMONITOR MESSAGE PUBLISHING
Once the mqtt topics associated to a thing or agent is declared, IotMonitor records and restore given MQTT "states topics" as they go and recover. It helps reinstalling IOT things state, to avoid lots of administration tasks.
## "EXPIRED" SUBTOPIC
IotMonitor use a TOML config file. Each device has an independent configured communication message time out. When the device stop communication on this topic, the iotmonitor publish a specific monitoring failure topic for the lots device, with the latest contact timestamp. This topic is labelled :
[BASE_IOTMONITOR_TOPIC]/expire/[device_name]
for example :
home/monitoring/expire/[device_name]
This topic can then be displayed or alerted to inform that the device or agent is not working properly.
## "UP" SUBTOPIC
When running, iotmonitor also published an *up* subtopic this topic is published every seconds and provide the startup seconds of the iotmonitor process. This topic can be also used to monitor the iotmonitor process.
## "HELLOTOPICCOUNT" SUBTOPIC
helloTopicCount count, for each device, the number of hello topic published by the device or agent. This counter inform the count of restart or reboot of each device or agent.
[BASE_IOTMONITOR_TOPIC]/helloTopicCount
# CONFIG FILE REFERENCE
The configuration is defined in the `config.toml` TOML file, (see an example in the root directory)
the global _Mqtt broker configuration section_ is defined using a heading `[mqtt]`
the following parameters are found :
```toml
[mqtt]
serverAddress="tcp://localhost:1883"
baseTopic="home/monitoring"
user=""
password=""
```
## GLOBAL SECTION
global section of the mqtt configuration file contains the following possible elements :
serverAddress
: mqtt broker address, this include tcp:// communication and the port as shown in the previous example
user
: mqtt broker authentication, left empty if no authentication is necessary. The password parameter is then used if the user parameter is filled.
password
: account associated password
baseTopic
: root of all iotmonitor publications. This defines the *BASE_IOTMONITOR_TOPIC*
clientid
: An optional clientid can also be specified to change the mqtt clientid, a default "iotmonitor" value is used when not specified
## DEVICE DECLARATION SECTION
Each monitored device is declared in a section using a "device_" prefix in this section : the following elements can be found :
```toml
[device_esp04]
watchTimeOut=60
helloTopic="home/esp04"
watchTopics="home/esp04/sensors/#"
stateTopics="home/esp04/actuators/#"
```
watchTimeOut
: watch dog for alive state, when the timeout is reached without and interactions on watchTopics, then iotmonitor trigger an expire message for the device
helloTopic
: the topic to observe to welcome the device. This topic trigger the state recovering for the device and agents. IotMonitor, resend the previous stored `stateTopics`
watchTopics
: the topic pattern to observe to know the device is alive
stateTopics
: list of topics for recording the states and reset them as they are welcomed
## AGENT DECLARATION SECTION
Agents are declared using an "agent_" prefix in the section. Agents are devices with an associated command line (`exec` config key) that trigger the start of the software agent. IotMonitor checks periodically if the process is running, and relaunch it if needed.
```toml
[agent_ledboxdaemon]
exec="source ~/mqttagents/p3/bin/activate;cd ~/mqttagents/mqtt-agent-ledbox;python3 ledboxdaemon.py"
watchTopics="home/agents/ledbox/#"
```
When IotMonitor run the processes, it identify the process by searching a specific command line parameter, containing an IOTMONITOR tag. When executing the agents processes, the processes are detached from the main iotmonitor process, avoiding to relaunch the whole system in the case of restarting the `iotmonitor` process.
Agents declaration inherit all DEVICE SECTION parameters, with an additional *exec* parameter.
Agents may also have `helloTopic`, `stateTopics` and `watchTimeOut` as previously described in DEVICE DECLARATION SECTION.
# STATE RECOVERY
At startup OR when the `helloTopic` is fired, iotmonitor fire the previousely recorded states on mqtt, this permit the device (things), to take it's previoulsy state, as if it has not been stopped.. All mqtt recorded states (`stateTopics`) are backuped by iotmonitor in a leveldb database.
For practical reasons, this permit to centralize the state, and restore them when an iot device has rebooted. If used this functionnality, reduce the need to implement a cold state storage for each agent or device. Starting or stopping iotmonitor, redefine the state for all elements.
|
0 | repos/iotmonitor | repos/iotmonitor/man/viewdoc.sh | #!/bin/bash
pandoc iotmonitor.1.md -s -t man | /usr/bin/man -l -
|
0 | repos/iotmonitor | repos/iotmonitor/snapcraft/README.md |
Building snap on command line
cd snap
snapcraft
cleaning the latest build :
snapcraft clean
Install on dev stage
sudo snap install iotmonitor_0.2+git_amd64.snap --devmode --dangerous
Upload the edge :
snapcraft upload --release=edge iotmonitor*.snap
promote the snap to beta or candidate
snapcraft release iotmonitor 5 beta
|
0 | repos/iotmonitor/snapcraft | repos/iotmonitor/snapcraft/snap/snapcraft.yaml | name: iotmonitor
base: core18
version: '0.2.6+git'
summary: Monitor MQTT IOT devices or agents to make them run
description: |
IotMonitor solve the "always up" problem of large IOT devices and agents system.
Considering large and longlived systems cannot rely only on some specific software,
using raw system's processes permit to compose a system with several processes or devices,
implemented with different langages and coming from multiple implementers or third party.
This project is simple command line, as in *nix system, to monitor MQTT device or
agents system. MQTT based communication devices (IOT) and agents are monitored,
and alerts are emitted if devices or agents are not responding.
Software agents are also restarted when crashed.
IotMonitor records and restore MQTT states topics as they go and recover.
It helps to maintain IOT things working, and avoid lots of administration tasks.
grade: devel
confinement: devmode
parts:
iotmonitor:
plugin: make
source-type: git
source: https://github.com/frett27/iotmonitor.git
source-branch: zig_0.9.1
build-snaps: [zig/latest/beta]
build-packages: [build-essential, make, cmake, libleveldb-dev]
stage-packages: [libleveldb-dev]
apps:
iotmonitor:
command: iotmonitor
|
0 | repos/iotmonitor | repos/iotmonitor/docker/config.toml |
[mqtt]
user="USER"
password="PASSWORD"
serverAddress="tcp://192.168.4.16:1883"
[device_nodered]
watchTimeOut=2
watchTopics="home/agents/nodered/watchdog"
[device_agent_wifi_measure]
watchTimeOut=30
watchTopics="home/esp10/sensors/#"
[device_esp10]
watchTimeOut=60
helloTopic="home/esp10"
watchTopics="home/esp10/sensors/#"
stateTopics="home/esp10/actuators/#"
[device_esp08]
watchTimeOut=60
helloTopic="home/esp08"
watchTopics="home/esp08/sensors/#"
stateTopics="home/esp08/actuators/relay1"
[device_esp04]
watchTimeOut=60
helloTopic="home/esp04"
watchTopics="home/esp04/sensors/#"
stateTopics="home/esp04/actuators/#"
[device_esp03]
watchTimeOut=60
helloTopic="home/esp03"
watchTopics="home/esp03/sensors/#"
stateTopics="home/esp03/actuators/#"
# METEO
[device_esp05]
watchTimeOut=1200
helloTopic="home/esp05"
watchTopics="home/esp03/sensors/#"
|
0 | repos/iotmonitor | repos/iotmonitor/docker/README.md | # Docker for iotmonitor
this docker create the iotmonitor image, for x64 platefoms
note that if you run the iotmonitor as a container, processes must be also hosted in the container.
# Building the image using the zig master
The VERSION variable mention the master version
Optional, The COMMIT variable may be specified for the ZIG commit to use (zig dev repository), if not set, official RELEASE zig version IS used
(check http://ziglang.org/downloads for the current value)
for officiel release zig version:
docker build --build-arg VERSION=0.9.1 -t iotmonitor .
docker build --build-arg COMMIT=45212e3b3 --build-arg VERSION=0.9.0-dev.103 -t iotmonitor .
# Running the container
The current folder must have the config.toml configuration file, and write access to the executing USER, to create the leveldb database associated to device states
docker run --rm -d -u $(id --user) -v `pwd`:/config iotmonitor
# RPI compilation (to be tested)
docker run -it -v $HOME/.dockerpi:/sdcard lukechilds/dockerpi
|
0 | repos/iotmonitor | repos/iotmonitor/docker/grabzigbinary.sh | #!/bin/bash
VERSION=$1
COMMIT=$2
if [ -z "${COMMIT}"]
then
echo "Using official build for zig"
BASEFILENAME=zig-linux-x86_64-$VERSION
DOWNLOADBASE=https://ziglang.org/download/$VERSION
else
echo "Using nightly build releases for zig"
BASEFILENAME=zig-linux-x86_64-$VERSION+$COMMIT
DOWNLOADBASE=https://ziglang.org/builds
fi
wget $DOWNLOADBASE/$BASEFILENAME.tar.xz
xz -d $BASEFILENAME.tar.xz
tar xvf $BASEFILENAME.tar
mv $BASEFILENAME zigbundle
|
0 | repos/iotmonitor | repos/iotmonitor/dev/shell.nix | let
nixpkgs = builtins.fetchTarball {
# nixpkgs-unstable (2021-10-28)
url = "https://github.com/NixOS/nixpkgs/archive/d9c13cf44ec1b6de95cb1ba83c296611d19a71ae.tar.gz";
# sha256 = "1rqp9nf45m03mfh4x972whw2gsaz5x44l3dy6p639ib565g24rmh";
};
in
{ pkgs ? import nixpkgs { } }:
pkgs.mkShell {
nativeBuildInputs = with pkgs; [
cmake
gdb
ninja
qemu
zig
leveldb
libsodium
] ++ (with llvmPackages_13; [
clang
clang-unwrapped
lld
llvm
]);
hardeningDisable = [ "all" ];
}
|
0 | repos/iotmonitor/nozig-tracy | repos/iotmonitor/nozig-tracy/src/lib.zig |
// This library mock the tracy calls
const std = @import("std");
pub const Ctx = struct {
pub fn end(self: Ctx) void {
// no op
_ = self;
}
};
pub fn trace(comptime src: std.builtin.SourceLocation) callconv(.Inline) Ctx {
_ = src;
return Ctx{
};
}
|
0 | repos/iotmonitor | repos/iotmonitor/doc/2020-08_RFC_01_adding_process_monitoring.md | # RFC adding process monitoring
August 2020
### Summary
IOTMonitor currently monitor MQTT devices or agents, by watching mqtt topics and associated states.
in case of non response, iotmonitor send a MQTT alert in a specific MQTT topic linked to monitoring.
### Process monitoring goal
This evolution it to also manage the external agents process management. Knowing if a process is healthy imply to know the functional behaviour and this is a hard trick to define externally (failure detection problem).
Nonetheless, if the process periodically published its health, or having and external process than monitor it's health. In Using periodic MQTT healthchecks, this is then possible to handle the (kill/exec) command on the process to make the system work.
This ability also simplify the managing of such system, this mean, when a process managing devices and providing MQTT watchdog health check, then an entry in IOTMonitor can be added to manage the process.
### Implementation Ideas
As IOTMonitor launch the process, it can setup a unique identifier that can be used to track the process. process can be wrapped into bash exec , (using the command lines) with additional parameters, and especially the IOTMonitor id, to track it down.
If the process does not respond periodically to mqtt topic, then the iot monitor can kill and restart the process, setting up a specific stdout log file and stderr log linked to the process. Process is detached from IOTMonitor session to be able to stop the IOTMonitor without to kill all process and stop all system's functionnalities.
In this manner, there are no complex IPC to setup or invasive
### Additional concerns
<u>MQTT authentication on the behave of the process</u> : this can be added in defining environment variable in the process launch. The command line can then take them to do the necessary transmission.
|
0 | repos/iotmonitor | repos/iotmonitor/doc/Using-Profiler-checking-performance.md |
# Using Tracy to check performances
## Ubuntu 20,
### Install tracy library dependencies
apt install libglfw3-dev libgtk-3-dev libcapstone-dev libtbb-dev
cd tracy
make -j -C profiler/build/unix debug release
make -j -C library/unix debug release
To launch iotmonitor with tracing,
be sure the library path contains the tracy library
export LD_LIBRARY_PATH=tracy/library/unix
launch iotmonitor, and Tracy,

|
0 | repos | repos/sqids-zig/README.md | # [Sqids Zig](https://sqids.org/zig)
[Sqids](https://sqids.org/zig) (*pronounced "squids"*) is a small library that lets you **generate unique IDs from numbers**. It's good for link shortening, fast & URL-safe ID generation and decoding back into numbers for quicker database lookups.
Features:
- **Encode multiple numbers** - generate short IDs from one or several non-negative numbers
- **Quick decoding** - easily decode IDs back into numbers
- **Unique IDs** - generate unique IDs by shuffling the alphabet once
- **ID padding** - provide minimum length to make IDs more uniform
- **URL safe** - auto-generated IDs do not contain common profanity
- **Randomized output** - Sequential input provides nonconsecutive IDs
- **Many implementations** - Support for [multiple programming languages](https://sqids.org/)
## 🧰 Use-cases
Good for:
- Generating IDs for public URLs (eg: link shortening)
- Generating IDs for internal systems (eg: event tracking)
- Decoding for quicker database lookups (eg: by primary keys)
Not good for:
- Sensitive data (this is not an encryption library)
- User IDs (can be decoded revealing user count)
## 🚀 Getting started
To add sqids-zig to your Zig application or library, follow these steps:
1. Fetch the package at the desired commit:
```terminal
zig fetch --save https://github.com/lvignoli/sqids-zig/archive/<commitID>.tar.gz
```
2. Declare the dependecy in the `build.zig.zon` file:
```zig
.dependencies = .{
.sqids = .{
.url = "https://github.com/lvignoli/sqids-zig/archive/<commitID>.tar.gz",
.hash = "<hash>",
},
}
```
3. Use it your `build.zig` and add it where needed:
```zig
const sqids_dep = b.dependency("sqids", .{});
const sqids_mod = sqids_dep.module("sqids");
[...]
exe.addModule("sqids", sqids_mod); // for an executable
lib.addModule("sqids", sqids_mod); // for a library
tests.addModule("sqids", sqids_mod); // for tests
```
4. Now you can import it in source sode with
```zig
const sqids = @import("sqids");
```
The import string is the one provided in the `addModule` call.
> [!TIP]
> Check [lvignoli/sqidify](https://github.com/lvignoli/sqidify) for a self-contained Zig executable example.
## 👩💻 Examples
Simple encode & decode:
```zig
const s = try sqids.Sqids.init(allocator, .{})
defer s.deinit();
const id = try s.encode(&.{1, 2, 3});
defer allocator.free(id); // Caller owns the memory.
const numbers = try s.decode(id);
defer allocator.free(numbers); // Caller owns the memory.
```
> **Note**
> 🚧 Because of the algorithm's design, **multiple IDs can decode back into the same sequence of numbers**. If it's important to your design that IDs are canonical, you have to manually re-encode decoded numbers and check that the generated ID matches.
The `sqids.Options` struct is used at initialization to customize the encoder.
Enforce a *minimum* length for IDs:
```zig
const s = try sqids.Sqids.init(allocator, .{.min_length = 10});
const id = try s.encode(&.{1, 2, 3}); // "86Rf07xd4z"
```
Randomize IDs by providing a custom alphabet:
```zig
const s = try sqids.Sqids.init(allocator, .{.alphabet = "FxnXM1kBN6cuhsAvjW3Co7l2RePyY8DwaU04Tzt9fHQrqSVKdpimLGIJOgb5ZE"});
const id = try s.encode(&.{1, 2, 3}); // "B4aajs"
```
Prevent specific words from appearing anywhere in the auto-generated IDs:
```zig
const s = try sqids.Sqids.init(allocator, .{.blocklist = &.{"86Rf07"}});
const id = try s.encode(&.{1, 2, 3}); // "se8ojk"
```
## 📝 License
[MIT](LICENSE)
|
0 | repos | repos/sqids-zig/build.zig.zon | .{
.name = "sqids",
.version = "0.0.0",
.dependencies = .{},
.paths = .{
"build.zig",
"build.zig.zon",
"src",
"README.md",
"LICENSE",
},
}
|
0 | repos | repos/sqids-zig/build.zig | const std = @import("std");
pub fn build(b: *std.Build) void {
const target = b.standardTargetOptions(.{});
const optimize = b.standardOptimizeOption(.{});
const sqids_module = b.addModule("sqids", .{ .root_source_file = b.path("src/main.zig") });
const tests = b.addTest(.{
.root_source_file = b.path("src/tests/tests.zig"),
.target = target,
.optimize = optimize,
});
tests.root_module.addImport("sqids", sqids_module);
const run_main_tests = b.addRunArtifact(tests);
const test_step = b.step("test", "Run library tests");
test_step.dependOn(&run_main_tests.step);
}
|
0 | repos/sqids-zig | repos/sqids-zig/src/blocklist.zig | pub const default_blocklist = .{
"0rgasm",
"1d10t",
"1d1ot",
"1di0t",
"1diot",
"1eccacu10",
"1eccacu1o",
"1eccacul0",
"1eccaculo",
"1mbec11e",
"1mbec1le",
"1mbeci1e",
"1mbecile",
"a11upat0",
"a11upato",
"a1lupat0",
"a1lupato",
"aand",
"ah01e",
"ah0le",
"aho1e",
"ahole",
"al1upat0",
"al1upato",
"allupat0",
"allupato",
"ana1",
"ana1e",
"anal",
"anale",
"anus",
"arrapat0",
"arrapato",
"arsch",
"arse",
"ass",
"b00b",
"b00be",
"b01ata",
"b0ceta",
"b0iata",
"b0ob",
"b0obe",
"b0sta",
"b1tch",
"b1te",
"b1tte",
"ba1atkar",
"balatkar",
"bastard0",
"bastardo",
"batt0na",
"battona",
"bitch",
"bite",
"bitte",
"bo0b",
"bo0be",
"bo1ata",
"boceta",
"boiata",
"boob",
"boobe",
"bosta",
"bran1age",
"bran1er",
"bran1ette",
"bran1eur",
"bran1euse",
"branlage",
"branler",
"branlette",
"branleur",
"branleuse",
"c0ck",
"c0g110ne",
"c0g11one",
"c0g1i0ne",
"c0g1ione",
"c0gl10ne",
"c0gl1one",
"c0gli0ne",
"c0glione",
"c0na",
"c0nnard",
"c0nnasse",
"c0nne",
"c0u111es",
"c0u11les",
"c0u1l1es",
"c0u1lles",
"c0ui11es",
"c0ui1les",
"c0uil1es",
"c0uilles",
"c11t",
"c11t0",
"c11to",
"c1it",
"c1it0",
"c1ito",
"cabr0n",
"cabra0",
"cabrao",
"cabron",
"caca",
"cacca",
"cacete",
"cagante",
"cagar",
"cagare",
"cagna",
"cara1h0",
"cara1ho",
"caracu10",
"caracu1o",
"caracul0",
"caraculo",
"caralh0",
"caralho",
"cazz0",
"cazz1mma",
"cazzata",
"cazzimma",
"cazzo",
"ch00t1a",
"ch00t1ya",
"ch00tia",
"ch00tiya",
"ch0d",
"ch0ot1a",
"ch0ot1ya",
"ch0otia",
"ch0otiya",
"ch1asse",
"ch1avata",
"ch1er",
"ch1ng0",
"ch1ngadaz0s",
"ch1ngadazos",
"ch1ngader1ta",
"ch1ngaderita",
"ch1ngar",
"ch1ngo",
"ch1ngues",
"ch1nk",
"chatte",
"chiasse",
"chiavata",
"chier",
"ching0",
"chingadaz0s",
"chingadazos",
"chingader1ta",
"chingaderita",
"chingar",
"chingo",
"chingues",
"chink",
"cho0t1a",
"cho0t1ya",
"cho0tia",
"cho0tiya",
"chod",
"choot1a",
"choot1ya",
"chootia",
"chootiya",
"cl1t",
"cl1t0",
"cl1to",
"clit",
"clit0",
"clito",
"cock",
"cog110ne",
"cog11one",
"cog1i0ne",
"cog1ione",
"cogl10ne",
"cogl1one",
"cogli0ne",
"coglione",
"cona",
"connard",
"connasse",
"conne",
"cou111es",
"cou11les",
"cou1l1es",
"cou1lles",
"coui11es",
"coui1les",
"couil1es",
"couilles",
"cracker",
"crap",
"cu10",
"cu1att0ne",
"cu1attone",
"cu1er0",
"cu1ero",
"cu1o",
"cul0",
"culatt0ne",
"culattone",
"culer0",
"culero",
"culo",
"cum",
"cunt",
"d11d0",
"d11do",
"d1ck",
"d1ld0",
"d1ldo",
"damn",
"de1ch",
"deich",
"depp",
"di1d0",
"di1do",
"dick",
"dild0",
"dildo",
"dyke",
"encu1e",
"encule",
"enema",
"enf01re",
"enf0ire",
"enfo1re",
"enfoire",
"estup1d0",
"estup1do",
"estupid0",
"estupido",
"etr0n",
"etron",
"f0da",
"f0der",
"f0ttere",
"f0tters1",
"f0ttersi",
"f0tze",
"f0utre",
"f1ca",
"f1cker",
"f1ga",
"fag",
"fica",
"ficker",
"figa",
"foda",
"foder",
"fottere",
"fotters1",
"fottersi",
"fotze",
"foutre",
"fr0c10",
"fr0c1o",
"fr0ci0",
"fr0cio",
"fr0sc10",
"fr0sc1o",
"fr0sci0",
"fr0scio",
"froc10",
"froc1o",
"froci0",
"frocio",
"frosc10",
"frosc1o",
"frosci0",
"froscio",
"fuck",
"g00",
"g0o",
"g0u1ne",
"g0uine",
"gandu",
"go0",
"goo",
"gou1ne",
"gouine",
"gr0gnasse",
"grognasse",
"haram1",
"harami",
"haramzade",
"hund1n",
"hundin",
"id10t",
"id1ot",
"idi0t",
"idiot",
"imbec11e",
"imbec1le",
"imbeci1e",
"imbecile",
"j1zz",
"jerk",
"jizz",
"k1ke",
"kam1ne",
"kamine",
"kike",
"leccacu10",
"leccacu1o",
"leccacul0",
"leccaculo",
"m1erda",
"m1gn0tta",
"m1gnotta",
"m1nch1a",
"m1nchia",
"m1st",
"mam0n",
"mamahuev0",
"mamahuevo",
"mamon",
"masturbat10n",
"masturbat1on",
"masturbate",
"masturbati0n",
"masturbation",
"merd0s0",
"merd0so",
"merda",
"merde",
"merdos0",
"merdoso",
"mierda",
"mign0tta",
"mignotta",
"minch1a",
"minchia",
"mist",
"musch1",
"muschi",
"n1gger",
"neger",
"negr0",
"negre",
"negro",
"nerch1a",
"nerchia",
"nigger",
"orgasm",
"p00p",
"p011a",
"p01la",
"p0l1a",
"p0lla",
"p0mp1n0",
"p0mp1no",
"p0mpin0",
"p0mpino",
"p0op",
"p0rca",
"p0rn",
"p0rra",
"p0uff1asse",
"p0uffiasse",
"p1p1",
"p1pi",
"p1r1a",
"p1rla",
"p1sc10",
"p1sc1o",
"p1sci0",
"p1scio",
"p1sser",
"pa11e",
"pa1le",
"pal1e",
"palle",
"pane1e1r0",
"pane1e1ro",
"pane1eir0",
"pane1eiro",
"panele1r0",
"panele1ro",
"paneleir0",
"paneleiro",
"patakha",
"pec0r1na",
"pec0rina",
"pecor1na",
"pecorina",
"pen1s",
"pendej0",
"pendejo",
"penis",
"pip1",
"pipi",
"pir1a",
"pirla",
"pisc10",
"pisc1o",
"pisci0",
"piscio",
"pisser",
"po0p",
"po11a",
"po1la",
"pol1a",
"polla",
"pomp1n0",
"pomp1no",
"pompin0",
"pompino",
"poop",
"porca",
"porn",
"porra",
"pouff1asse",
"pouffiasse",
"pr1ck",
"prick",
"pussy",
"put1za",
"puta",
"puta1n",
"putain",
"pute",
"putiza",
"puttana",
"queca",
"r0mp1ba11e",
"r0mp1ba1le",
"r0mp1bal1e",
"r0mp1balle",
"r0mpiba11e",
"r0mpiba1le",
"r0mpibal1e",
"r0mpiballe",
"rand1",
"randi",
"rape",
"recch10ne",
"recch1one",
"recchi0ne",
"recchione",
"retard",
"romp1ba11e",
"romp1ba1le",
"romp1bal1e",
"romp1balle",
"rompiba11e",
"rompiba1le",
"rompibal1e",
"rompiballe",
"ruff1an0",
"ruff1ano",
"ruffian0",
"ruffiano",
"s1ut",
"sa10pe",
"sa1aud",
"sa1ope",
"sacanagem",
"sal0pe",
"salaud",
"salope",
"saugnapf",
"sb0rr0ne",
"sb0rra",
"sb0rrone",
"sbattere",
"sbatters1",
"sbattersi",
"sborr0ne",
"sborra",
"sborrone",
"sc0pare",
"sc0pata",
"sch1ampe",
"sche1se",
"sche1sse",
"scheise",
"scheisse",
"schlampe",
"schwachs1nn1g",
"schwachs1nnig",
"schwachsinn1g",
"schwachsinnig",
"schwanz",
"scopare",
"scopata",
"sexy",
"sh1t",
"shit",
"slut",
"sp0mp1nare",
"sp0mpinare",
"spomp1nare",
"spompinare",
"str0nz0",
"str0nza",
"str0nzo",
"stronz0",
"stronza",
"stronzo",
"stup1d",
"stupid",
"succh1am1",
"succh1ami",
"succhiam1",
"succhiami",
"sucker",
"t0pa",
"tapette",
"test1c1e",
"test1cle",
"testic1e",
"testicle",
"tette",
"topa",
"tr01a",
"tr0ia",
"tr0mbare",
"tr1ng1er",
"tr1ngler",
"tring1er",
"tringler",
"tro1a",
"troia",
"trombare",
"turd",
"twat",
"vaffancu10",
"vaffancu1o",
"vaffancul0",
"vaffanculo",
"vag1na",
"vagina",
"verdammt",
"verga",
"w1chsen",
"wank",
"wichsen",
"x0ch0ta",
"x0chota",
"xana",
"xoch0ta",
"xochota",
"z0cc01a",
"z0cc0la",
"z0cco1a",
"z0ccola",
"z1z1",
"z1zi",
"ziz1",
"zizi",
"zocc01a",
"zocc0la",
"zocco1a",
"zoccola",
};
|
0 | repos/sqids-zig | repos/sqids-zig/src/main.zig | /// Module sqids-zig implements encoding and decoding of sqids identifiers. See sqids.org.
const std = @import("std");
const mem = std.mem;
const testing = std.testing;
const ArrayList = std.ArrayList;
pub const Error = error{
TooShortAlphabet,
NonASCIICharacter,
RepeatingAlphabetCharacter,
ReachedMaxAttempts,
};
const blocklist_module = @import("blocklist.zig");
pub const default_blocklist = blocklist_module.default_blocklist;
/// The default alphabet for sqids.
pub const default_alphabet = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
/// Options controls the configuration of the sqid encoder.
pub const Options = struct {
alphabet: []const u8 = default_alphabet,
blocklist: []const []const u8 = &default_blocklist,
min_length: u8 = 0,
};
/// Sqids encoder.
/// Must be initialized with init and free with deinit methods.
pub const Sqids = struct {
allocator: mem.Allocator,
alphabet: []const u8,
arena: std.heap.ArenaAllocator,
blocklist: []const []const u8,
min_length: u8,
pub fn init(allocator: mem.Allocator, opts: Options) !Sqids {
// Check alphabet.
// TODO(lvignoli): it would be better to "parse not validate", for both the alphabet and the blocklist.
if (opts.alphabet.len < 3) {
return Error.TooShortAlphabet;
}
for (opts.alphabet) |c| {
if (!std.ascii.isASCII(c)) {
return Error.NonASCIICharacter;
}
if (mem.count(u8, opts.alphabet, &.{c}) > 1) {
return Error.RepeatingAlphabetCharacter;
}
}
// Create blocklist from provided words.
// We use an arena to manage the memory of the blocklist
var arena = std.heap.ArenaAllocator.init(allocator);
const b = try blocklist_from_words(arena.allocator(), opts.alphabet, opts.blocklist);
return Sqids{
.allocator = allocator,
.alphabet = opts.alphabet,
.arena = arena,
.blocklist = b,
.min_length = opts.min_length,
};
}
pub fn deinit(self: Sqids) void {
self.arena.deinit();
}
/// encode encodes a list of numbers into a sqids ID. Caller owns the memory.
pub fn encode(self: Sqids, numbers: []const u64) ![]const u8 {
if (numbers.len == 0) {
return "";
}
const alphabet = try self.allocator.dupe(u8, self.alphabet);
defer self.allocator.free(alphabet);
shuffle(alphabet);
const increment = 0;
return try encodeNumbers(self.allocator, numbers, alphabet, increment, self.min_length, self.blocklist);
}
/// decode decodes an ID into numbers using alphabet. Caller owns the memory.
pub fn decode(self: Sqids, id: []const u8) ![]const u64 {
return try decodeID(self.allocator, id, self.alphabet);
}
};
/// blocklist_from_words constructs a sanitized blocklist from a list of words.
fn blocklist_from_words(allocator: mem.Allocator, alphabet: []const u8, words: []const []const u8) ![]const []const u8 {
// Clean up blocklist:
// 1. all blocklist words should be lowercase,
// 2. no words less than 3 chars,
// 3. if some words contain chars that are not in the alphabet, remove those.
const lowercase_alphabet = try std.ascii.allocLowerString(allocator, alphabet);
defer allocator.free(lowercase_alphabet);
var filtered_blocklist = ArrayList([]const u8).init(allocator);
for (words) |word| {
if (word.len < 3) {
continue;
}
const lowercased_word = try std.ascii.allocLowerString(allocator, word);
if (!validInAlphabet(lowercased_word, lowercase_alphabet)) {
allocator.free(lowercased_word);
continue;
}
try filtered_blocklist.append(lowercased_word);
}
return try filtered_blocklist.toOwnedSlice();
}
fn validInAlphabet(word: []const u8, alphabet: []const u8) bool {
for (word) |c| {
if (mem.indexOf(u8, alphabet, &.{c}) == null) {
return false;
}
}
return true;
}
/// encodeNumbers performs the actual encoding processing.
fn encodeNumbers(
allocator: mem.Allocator,
numbers: []const u64,
original_alphabet: []const u8,
increment: u64,
min_length: u64,
blocklist: []const []const u8,
) ![]u8 {
var alphabet = try allocator.dupe(u8, original_alphabet);
defer allocator.free(alphabet);
if (increment > alphabet.len) {
return Error.ReachedMaxAttempts;
}
// Get semi-random offset.
var offset: u64 = numbers.len;
for (numbers, 0..) |n, i| {
offset += i;
offset += alphabet[n % alphabet.len];
}
offset %= alphabet.len;
offset = (offset + increment) % alphabet.len;
// Prefix and alphabet.
mem.rotate(u8, alphabet, offset);
const prefix = alphabet[0];
mem.reverse(u8, alphabet);
// Build the ID.
var ret = ArrayList(u8).init(allocator);
defer ret.deinit();
try ret.append(prefix);
for (numbers, 0..) |n, i| {
const x = try toID(allocator, n, alphabet[1..]);
defer allocator.free(x);
try ret.appendSlice(x);
if (i < numbers.len - 1) {
try ret.append(alphabet[0]);
shuffle(alphabet);
}
}
// Handle min_length requirements.
if (min_length > ret.items.len) {
try ret.append(alphabet[0]);
while (min_length > ret.items.len) {
shuffle(alphabet);
const n = @min(min_length - ret.items.len, alphabet.len);
try ret.appendSlice(alphabet[0..n]);
}
}
var ID = try ret.toOwnedSlice();
// Handle blocklist.
const blocked = try isBlockedID(allocator, blocklist, ID);
if (blocked) {
allocator.free(ID); // Freeing the old ID string.
ID = try encodeNumbers(allocator, numbers, original_alphabet, increment + 1, min_length, blocklist);
}
return ID;
}
/// isBlockedID returns true if id collides with the blocklist.
fn isBlockedID(allocator: mem.Allocator, blocklist: []const []const u8, id: []const u8) !bool {
const lower_id = try std.ascii.allocLowerString(allocator, id);
defer allocator.free(lower_id);
for (blocklist) |word| {
if (word.len > lower_id.len) {
continue;
}
if (lower_id.len <= 3 or word.len <= 3) {
if (mem.eql(u8, id, word)) {
return true;
}
} else if (containsNumber(word)) {
if (mem.startsWith(u8, lower_id, word) or mem.endsWith(u8, lower_id, word)) {
return true;
}
} else if (mem.indexOf(u8, lower_id, word)) |_| {
return true;
}
}
return false;
}
fn containsNumber(s: []const u8) bool {
for (s) |c| {
if (std.ascii.isDigit(c)) {
return true;
}
}
return false;
}
/// decodeID decodes an ID into numbers using alphabet. Caller owns the memory.
fn decodeID(
allocator: mem.Allocator,
to_decode_id: []const u8,
decoding_alphabet: []const u8,
) ![]const u64 {
var id = to_decode_id[0..];
if (id.len == 0) {
return &.{};
}
const alphabet = try allocator.dupe(u8, decoding_alphabet);
defer allocator.free(alphabet);
shuffle(alphabet);
// If a character is not in the alphabet, return an empty array.
for (id) |c| {
if (mem.indexOfScalar(u8, alphabet, c) == null) {
return &.{};
}
}
const prefix = id[0];
id = id[1..];
const offset = mem.indexOfScalar(u8, alphabet, prefix).?;
// NOTE(l.vignoli): We can unwrap safely since all characters are in alphabet.
mem.rotate(u8, alphabet, offset);
mem.reverse(u8, alphabet);
var ret = ArrayList(u64).init(allocator);
defer ret.deinit();
while (id.len > 0) {
const separator = alphabet[0];
// We need the first part to the left of the separator to decode the number.
// If there is no separator, we take the whole string.
const i = mem.indexOfScalar(u8, id, separator) orelse id.len; // TODO: refactor.
const left = id[0..i];
const right = if (i == id.len) "" else id[i + 1 ..];
// If empty, we are done (the rest is junk characters).
if (left.len == 0) {
return try ret.toOwnedSlice();
}
try ret.append(toNumber(left, alphabet[1..]));
// If there is still numbers to decode from the ID, shuffle the alphabet.
if (right.len > 0) {
shuffle(alphabet);
}
// Keep the part to the right of the first separator for the next iteration.
id = right;
}
return try ret.toOwnedSlice();
}
/// toID generates a new ID string for number using alphabet.
fn toID(allocator: mem.Allocator, number: u64, alphabet: []const u8) ![]const u8 {
// NOTE(lvignoli): In the reference implementation, the letters are inserted at index 0.
// Here we append them for efficiency, so we reverse the ID at the end.
var result: u64 = number;
var id = std.ArrayList(u8).init(allocator);
while (true) {
try id.append(alphabet[result % alphabet.len]);
result = result / alphabet.len;
if (result == 0) break;
}
const value: []u8 = try id.toOwnedSlice();
mem.reverse(u8, value);
return value;
}
/// toNumber converts a string to an integer using the given alphabet.
fn toNumber(s: []const u8, alphabet: []const u8) u64 {
var num: u64 = 0;
for (s) |c| {
if (mem.indexOfScalar(u8, alphabet, c)) |i| {
num = num * alphabet.len + i;
}
}
return num;
}
/// shuffle shuffles inplace the given alphabet.
/// It is consistent: it produces / the same result given the input.
fn shuffle(alphabet: []u8) void {
const n = alphabet.len;
var i: usize = 0;
var j = alphabet.len - 1;
while (j > 0) {
const r = (i * j + alphabet[i] + alphabet[j]) % n;
mem.swap(u8, &alphabet[i], &alphabet[r]);
i += 1;
j -= 1;
}
}
//
// Encoding and decoding tests start from here.
//
test "encode" {
const allocator = testing.allocator;
const TestCase = struct {
numbers: []const u64,
alphabet: []const u8,
expected: []const u8,
};
const cases = [_]TestCase{
.{
.numbers = &[_]u64{ 1, 2, 3 },
.alphabet = "0123456789abcdef",
.expected = "489158",
},
.{
.numbers = &[_]u64{ 1, 2, 3 },
.alphabet = default_alphabet,
.expected = "86Rf07",
},
};
for (cases) |case| {
const sqids = try Sqids.init(allocator, .{ .alphabet = case.alphabet });
defer sqids.deinit();
const id = try sqids.encode(case.numbers);
defer allocator.free(id);
try testing.expectEqualStrings(case.expected, id);
}
}
test "non-empty blocklist" {
const allocator = testing.allocator;
const blocklist: []const []const u8 = &.{"ArUO"};
const sqids = try Sqids.init(allocator, .{ .blocklist = blocklist });
defer sqids.deinit();
const actual_numbers = try sqids.decode("ArUO");
defer allocator.free(actual_numbers);
try testing.expectEqualSlices(u64, &.{100000}, actual_numbers);
const got_id = try sqids.encode(&.{100000});
defer allocator.free(got_id);
try testing.expectEqualStrings("QyG4", got_id);
}
test "decode" {
const allocator = testing.allocator;
const sqids = try Sqids.init(allocator, .{ .alphabet = "0123456789abcdef" });
defer sqids.deinit();
const numbers = try sqids.decode("489158");
defer allocator.free(numbers);
try testing.expectEqualSlices(u64, &.{ 1, 2, 3 }, numbers);
}
|
0 | repos/sqids-zig/src | repos/sqids-zig/src/tests/utils.zig | const std = @import("std");
const mem = std.mem;
const testing = std.testing;
const sqids = @import("sqids");
const Squids = sqids.Sqids;
pub fn expectEncode(
allocator: mem.Allocator,
s: Squids,
numbers: []const u64,
id: []const u8,
) !void {
const got = try s.encode(numbers);
defer allocator.free(got);
try testing.expectEqualStrings(id, got);
}
pub fn expectDecode(
allocator: mem.Allocator,
s: Squids,
id: []const u8,
numbers: []const u64,
) !void {
const got = try s.decode(id);
defer allocator.free(got);
try testing.expectEqualSlices(u64, numbers, got);
}
pub fn expectEncodeDecode(
allocator: mem.Allocator,
s: Squids,
numbers: []const u64,
) !void {
const id = try s.encode(numbers);
defer allocator.free(id);
const obtained_numbers = try s.decode(id);
defer allocator.free(obtained_numbers);
try testing.expectEqualSlices(u64, numbers, obtained_numbers);
}
pub fn expectEncodeDecodeWithID(
allocator: mem.Allocator,
s: Squids,
numbers: []const u64,
id: []const u8,
) !void {
// Test encoding.
const obtained_id = try s.encode(numbers);
defer allocator.free(obtained_id);
try testing.expectEqualStrings(id, obtained_id);
// Test decoding back.
const obtained_numbers = try s.decode(obtained_id);
defer allocator.free(obtained_numbers);
try testing.expectEqualSlices(u64, numbers, obtained_numbers);
}
|
0 | repos/sqids-zig/src | repos/sqids-zig/src/tests/blocklist.zig | const std = @import("std");
const mem = std.mem;
const testing = std.testing;
const utils = @import("utils.zig");
const sqids = @import("sqids");
const Squids = sqids.Sqids;
const testing_allocator = testing.allocator;
test "if no custom blocklist param, use the default blocklist" {
const s = try Squids.init(testing_allocator, .{});
defer s.deinit();
try utils.expectDecode(testing_allocator, s, "aho1e", &.{4572721});
try utils.expectEncode(testing_allocator, s, &.{4572721}, "JExTR");
}
test "if an empty blocklist param passed, don't use any blocklist" {
const s = try Squids.init(testing_allocator, .{ .blocklist = &.{} });
defer s.deinit();
try utils.expectEncodeDecodeWithID(testing_allocator, s, &.{4572721}, "aho1e");
}
test "if a non-empty blocklist param passed, use only that" {
const s = try Squids.init(testing_allocator, .{ .blocklist = &.{"ArUO"} });
defer s.deinit();
try utils.expectEncodeDecodeWithID(testing_allocator, s, &.{4572721}, "aho1e");
try utils.expectDecode(testing_allocator, s, "ArUO", &.{100000});
try utils.expectEncode(testing_allocator, s, &.{100000}, "QyG4");
try utils.expectDecode(testing_allocator, s, "QyG4", &.{100000});
}
test "blocklist" {
const s = try Squids.init(testing_allocator, .{
.blocklist = &.{
"JSwXFaosAN", // normal result of 1st encoding, let's block that word on purpose
"OCjV9JK64o", // result of 2nd encoding
"rBHf", // result of 3rd encoding is `4rBHfOiqd3`, let's block a substring
"79SM", // result of 4th encoding is `dyhgw479SM`, let's block the postfix
"7tE6", // result of 4th encoding is `7tE6jdAHLe`, let's block the prefix
},
});
defer s.deinit();
try utils.expectEncodeDecodeWithID(testing_allocator, s, &.{ 1_000_000, 2_000_000 }, "1aYeB7bRUt");
}
test "decoding blocklist words should still work" {
const s = try Squids.init(testing_allocator, .{
.blocklist = &.{
"86Rf07",
"se8ojk",
"ARsz1p",
"Q8AI49",
"5sQRZO",
},
});
defer s.deinit();
try utils.expectDecode(testing_allocator, s, "86Rf07", &.{ 1, 2, 3 });
try utils.expectDecode(testing_allocator, s, "se8ojk", &.{ 1, 2, 3 });
try utils.expectDecode(testing_allocator, s, "ARsz1p", &.{ 1, 2, 3 });
try utils.expectDecode(testing_allocator, s, "Q8AI49", &.{ 1, 2, 3 });
try utils.expectDecode(testing_allocator, s, "5sQRZO", &.{ 1, 2, 3 });
}
test "match against a short blocklist word" {
const s = try Squids.init(testing_allocator, .{
.blocklist = &.{"pnd"},
});
defer s.deinit();
try utils.expectEncodeDecode(testing_allocator, s, &.{1000});
}
test "blocklist filtering in constructor" {
const s = try Squids.init(testing_allocator, .{
.alphabet = "ABCDEFGHIJKLMNOPQRSTUVWXYZ",
.blocklist = &.{"sxnzkl"},
});
defer s.deinit();
try utils.expectEncodeDecodeWithID(testing_allocator, s, &.{ 1, 2, 3 }, "IBSHOZ"); // without blocklist, would've been "SXNZKL"
}
test "max encoding attempts" {
// Setup encoder such that alphabet.len == min_length == blocklist.len
const s = try Squids.init(testing_allocator, .{
.alphabet = "abc",
.min_length = 3,
.blocklist = &.{ "cab", "abc", "bca" },
});
defer s.deinit();
const err = s.encode(&.{0}) catch |err| err;
try testing.expectError(sqids.Error.ReachedMaxAttempts, err);
}
|
0 | repos/sqids-zig/src | repos/sqids-zig/src/tests/alphabet.zig | const std = @import("std");
const mem = std.mem;
const testing = std.testing;
const utils = @import("utils.zig");
const sqids = @import("sqids");
const Squids = sqids.Sqids;
const testing_allocator = testing.allocator;
test "simple" {
const s = try Squids.init(testing_allocator, .{ .alphabet = "0123456789abcdef" });
defer s.deinit();
try utils.expectEncodeDecodeWithID(testing_allocator, s, &.{ 1, 2, 3 }, "489158");
}
test "short" {
const s = try Squids.init(testing_allocator, .{ .alphabet = "abc" });
defer s.deinit();
try utils.expectEncodeDecode(testing_allocator, s, &.{ 1, 2, 3 });
}
test "long" {
const alphabet =
\\abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789!@#$%^&*()-_+|{}[];:\'"/?.>,<`~
;
const s = try Squids.init(testing_allocator, .{ .alphabet = alphabet });
defer s.deinit();
try utils.expectEncodeDecode(testing_allocator, s, &.{ 1, 2, 3 });
}
test "multibyte alphabet" {
const err = Squids.init(testing_allocator, .{ .alphabet = "ë1092" }) catch |err| err;
try testing.expectError(sqids.Error.NonASCIICharacter, err);
}
test "repeating alphabet characters" {
const err = Squids.init(testing_allocator, .{ .alphabet = "aabcdefg" }) catch |err| err;
try testing.expectError(sqids.Error.RepeatingAlphabetCharacter, err);
}
test "too short of an alphabet" {
const err = Squids.init(testing_allocator, .{ .alphabet = "ab" }) catch |err| err;
try testing.expectError(sqids.Error.TooShortAlphabet, err);
}
|
0 | repos/sqids-zig/src | repos/sqids-zig/src/tests/tests.zig | //! Root test file.
comptime {
_ = @import("encoding_tests.zig");
_ = @import("minlength_tests.zig");
_ = @import("alphabet.zig");
_ = @import("blocklist.zig");
}
|
0 | repos/sqids-zig/src | repos/sqids-zig/src/tests/minlength_tests.zig | const std = @import("std");
const mem = std.mem;
const testing = std.testing;
const utils = @import("utils.zig");
const sqids = @import("sqids");
const Squids = sqids.Sqids;
const testing_allocator = testing.allocator;
test "min length: incremental min length" {
var map = std.AutoHashMap(u8, []const u8).init(testing_allocator);
defer map.deinit();
const numbers = [_]u64{ 1, 2, 3 };
// Simple.
try map.put(sqids.default_alphabet.len, "86Rf07xd4zBmiJXQG6otHEbew02c3PWsUOLZxADhCpKj7aVFv9I8RquYrNlSTM");
// Incremental.
try map.put(6, "86Rf07");
try map.put(7, "86Rf07x");
try map.put(8, "86Rf07xd");
try map.put(9, "86Rf07xd4");
try map.put(10, "86Rf07xd4z");
try map.put(11, "86Rf07xd4zB");
try map.put(12, "86Rf07xd4zBm");
try map.put(13, "86Rf07xd4zBmi");
try map.put(sqids.default_alphabet.len + 0, "86Rf07xd4zBmiJXQG6otHEbew02c3PWsUOLZxADhCpKj7aVFv9I8RquYrNlSTM");
try map.put(sqids.default_alphabet.len + 1, "86Rf07xd4zBmiJXQG6otHEbew02c3PWsUOLZxADhCpKj7aVFv9I8RquYrNlSTMy");
try map.put(sqids.default_alphabet.len + 2, "86Rf07xd4zBmiJXQG6otHEbew02c3PWsUOLZxADhCpKj7aVFv9I8RquYrNlSTMyf");
try map.put(sqids.default_alphabet.len + 3, "86Rf07xd4zBmiJXQG6otHEbew02c3PWsUOLZxADhCpKj7aVFv9I8RquYrNlSTMyf1");
var it = map.iterator();
while (it.next()) |e| {
const min_length = e.key_ptr.*;
const id = e.value_ptr.*;
const s = try Squids.init(testing_allocator, .{ .min_length = min_length });
defer s.deinit();
const got_id = try s.encode(&numbers);
defer testing_allocator.free(got_id);
try testing.expect(min_length == got_id.len);
try utils.expectEncodeDecodeWithID(testing_allocator, s, &numbers, id);
}
}
test "min length: incremental numbers" {
const s = try Squids.init(testing_allocator, .{ .min_length = sqids.default_alphabet.len });
defer s.deinit();
var ids = std.StringArrayHashMap([]const u64).init(testing_allocator);
defer ids.deinit();
try ids.put("SvIzsqYMyQwI3GWgJAe17URxX8V924Co0DaTZLtFjHriEn5bPhcSkfmvOslpBu", &.{ 0, 0 });
try ids.put("n3qafPOLKdfHpuNw3M61r95svbeJGk7aAEgYn4WlSjXURmF8IDqZBy0CT2VxQc", &.{ 0, 1 });
try ids.put("tryFJbWcFMiYPg8sASm51uIV93GXTnvRzyfLleh06CpodJD42B7OraKtkQNxUZ", &.{ 0, 2 });
try ids.put("eg6ql0A3XmvPoCzMlB6DraNGcWSIy5VR8iYup2Qk4tjZFKe1hbwfgHdUTsnLqE", &.{ 0, 3 });
try ids.put("rSCFlp0rB2inEljaRdxKt7FkIbODSf8wYgTsZM1HL9JzN35cyoqueUvVWCm4hX", &.{ 0, 4 });
try ids.put("sR8xjC8WQkOwo74PnglH1YFdTI0eaf56RGVSitzbjuZ3shNUXBrqLxEJyAmKv2", &.{ 0, 5 });
try ids.put("uY2MYFqCLpgx5XQcjdtZK286AwWV7IBGEfuS9yTmbJvkzoUPeYRHr4iDs3naN0", &.{ 0, 6 });
try ids.put("74dID7X28VLQhBlnGmjZrec5wTA1fqpWtK4YkaoEIM9SRNiC3gUJH0OFvsPDdy", &.{ 0, 7 });
try ids.put("30WXpesPhgKiEI5RHTY7xbB1GnytJvXOl2p0AcUjdF6waZDo9Qk8VLzMuWrqCS", &.{ 0, 8 });
try ids.put("moxr3HqLAK0GsTND6jowfZz3SUx7cQ8aC54Pl1RbIvFXmEJuBMYVeW9yrdOtin", &.{ 0, 9 });
var it = ids.iterator();
while (it.next()) |e| {
const id = e.key_ptr.*;
const numbers = e.value_ptr.*;
try utils.expectEncodeDecodeWithID(testing_allocator, s, numbers, id);
}
}
test "min length: various" {
const min_lengths = [_]u8{ 0, 1, 5, 10, sqids.default_alphabet.len };
const numbers = [_][]const u64{
&.{0},
&.{ 0, 0, 0, 0, 0 },
&.{ 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 },
&.{ 100, 200, 300 },
&.{ 1_000, 2_000, 3_000 },
&.{1_000_000},
&.{std.math.maxInt(u64)},
};
for (min_lengths) |min_length| {
const s = try Squids.init(testing_allocator, .{ .min_length = min_length });
defer s.deinit();
for (numbers) |ns| {
const id = try s.encode(ns);
defer testing_allocator.free(id);
try testing.expect(id.len >= min_length);
const got_numbers = try s.decode(id);
defer testing_allocator.free(got_numbers);
try testing.expectEqualSlices(u64, ns, got_numbers);
}
}
}
|
0 | repos/sqids-zig/src | repos/sqids-zig/src/tests/encoding_tests.zig | const std = @import("std");
const mem = std.mem;
const testing = std.testing;
const utils = @import("utils.zig");
const sqids = @import("sqids");
const Squids = sqids.Sqids;
const testing_allocator = testing.allocator;
test "default encoder: encode incremental numbers" {
const s = try Squids.init(testing_allocator, .{});
defer s.deinit();
var cases = std.StringHashMap([]const u64).init(testing_allocator);
defer cases.deinit();
// Simple.
try cases.put("86Rf07", &.{ 1, 2, 3 });
// Incremental numbers.
try cases.put("bM", &.{0});
try cases.put("Uk", &.{1});
try cases.put("gb", &.{2});
try cases.put("Ef", &.{3});
try cases.put("Vq", &.{4});
try cases.put("uw", &.{5});
try cases.put("OI", &.{6});
try cases.put("AX", &.{7});
try cases.put("p6", &.{8});
try cases.put("nJ", &.{9});
// Incremental numbers, same index zero.
try cases.put("SvIz", &.{ 0, 0 });
try cases.put("n3qa", &.{ 0, 1 });
try cases.put("tryF", &.{ 0, 2 });
try cases.put("eg6q", &.{ 0, 3 });
try cases.put("rSCF", &.{ 0, 4 });
try cases.put("sR8x", &.{ 0, 5 });
try cases.put("uY2M", &.{ 0, 6 });
try cases.put("74dI", &.{ 0, 7 });
try cases.put("30WX", &.{ 0, 8 });
try cases.put("moxr", &.{ 0, 9 });
// Incremental numbers, same index 1.
try cases.put("SvIz", &.{ 0, 0 });
try cases.put("nWqP", &.{ 1, 0 });
try cases.put("tSyw", &.{ 2, 0 });
try cases.put("eX68", &.{ 3, 0 });
try cases.put("rxCY", &.{ 4, 0 });
try cases.put("sV8a", &.{ 5, 0 });
try cases.put("uf2K", &.{ 6, 0 });
try cases.put("7Cdk", &.{ 7, 0 });
try cases.put("3aWP", &.{ 8, 0 });
try cases.put("m2xn", &.{ 9, 0 });
var it = cases.iterator();
while (it.next()) |e| {
const id = e.key_ptr.*;
const numbers = e.value_ptr.*;
try utils.expectEncodeDecodeWithID(testing_allocator, s, numbers, id);
}
}
test "default encoder: multi input" {
const s = try Squids.init(testing_allocator, .{});
defer s.deinit();
const numbers = [2][]const u64{
&.{ 0, 0, 0, 1, 2, 3, 100, 1_000, 100_000, 1_000_000, std.math.maxInt(u64) },
&.{ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, 62, 63, 64, 65, 66, 67, 68, 69, 70, 71, 72, 73, 74, 75, 76, 77, 78, 79, 80, 81, 82, 83, 84, 85, 86, 87, 88, 89, 90, 91, 92, 93, 94, 95, 96, 97, 98, 99 },
};
for (numbers) |n| {
const tmp_id = try s.encode(n);
defer testing_allocator.free(tmp_id);
const dec_output = try s.decode(tmp_id);
defer testing_allocator.free(dec_output);
try testing.expectEqualSlices(u64, n, dec_output);
}
}
test "default encoder: encoding no numbers" {
const s = try Squids.init(testing_allocator, .{});
defer s.deinit();
const output = try s.encode(&.{});
try testing.expectEqualStrings("", output);
testing_allocator.free(output);
}
test "default encoder: decoding empty string" {
const s = try Squids.init(testing_allocator, .{});
defer s.deinit();
const output = try s.decode("");
try testing.expectEqualSlices(u64, &.{}, output);
testing_allocator.free(output);
}
test "default encoder: decoding ID with invalid character" {
const s = try Squids.init(testing_allocator, .{});
defer s.deinit();
const output = try s.decode("*");
try testing.expectEqualSlices(u64, &.{}, output);
testing_allocator.free(output);
}
test "default encoder: encode out-of-range numbers" {
// Unnecessary: type system enforce u64 range.
}
|
0 | repos | repos/larry-pops-up/README.md | # Larry Pops Up!
[Larry Pops Up!](https://en.wikipedia.org/wiki/Leisure_Suit_Larry) is a modern re-creation of a small desktop widget/toy originally created in 1996 to promote Leisure Suit Larry 7: Love for Sail. Now available for MacOS, Windows and Linux desktops!
This desktop widget is comprised of *all* add-on packs that were ever released: 1 through 5.
Made with ♥️ - Please enjoy!
-Deckarep
#
# Further Details
Larry Pops Up! is more of just a fun desktop widget gag. The original version runs in the background as idle and waits for a period of inactivity. After some timeout, Larry pops on the screen in a very small 125x125 window and some random audio wav file plays where he says something funny; to you, the desktop user. Then the app simply disappears but goes back to an idle, invisible state awaiting for another timeout of inactivity. The user was able to drop in any additional WAV audio files into the widgets directory to allow any audio file sample to play. This new version does not yet do all of that and currently only plays a list of hardcoded audio samples that originally shipped with the game but also includes all add-on packs. For now, this version will also just run and play on some random interval that can be scheduled/configured by the user.
#
# Like this project? Tip Al!
If you enjoy this project or have ever enjoyed any of Al Lowe's work in the past, feel free to give him a tip (buy him a coffee) over at his original homepage. Al has stated that he does not earn royalties on his games and work at Sierra. Show him some gratitude if you can. [Click here to leave him a tip! to visit: allowe.com](https://allowe.com/more/tipjar.html)
#
Original version by: Don Munsil - [further details on Al Lowe's website](https://allowe.com/games/larry/even-more-larry/larry-links.html)

#

#

#

#

# Disclaimer
This is just a fan-made resurrection of an old simple desktop toy originally created by Sierra On-Line, [Al Lowe](https://allowe.com) and Don Munsil. Larry's voice by: [Jan Rabson](https://en.wikipedia.org/wiki/Jan_Rabson). The original version was a Windows-only desktop widget. |
0 | repos | repos/larry-pops-up/build.zig.zon | .{
// This is the default name used by packages depending on this one. For
// example, when a user runs `zig fetch --save <url>`, this field is used
// as the key in the `dependencies` table. Although the user can choose a
// different name, most users will stick with this provided value.
//
// It is redundant to include "zig" in this name because it is already
// within the Zig package namespace.
.name = "LarryPopsUp",
// This is a [Semantic Version](https://semver.org/).
// In a future version of Zig it will be used for package deduplication.
.version = "1.0.0",
// This field is optional.
// This is currently advisory only; Zig does not yet do anything
// with this value.
.minimum_zig_version = "0.13.0",
// This field is optional.
// Each dependency must either provide a `url` and `hash`, or a `path`.
// `zig build --fetch` can be used to fetch all dependencies of a package, recursively.
// Once all dependencies are fetched, `zig build` no longer requires
// internet connectivity.
.dependencies = .{
.@"raylib-zig" = .{
.url = "https://github.com/Not-Nik/raylib-zig/archive/devel.tar.gz",
.hash = "1220ff1a9e774784fe3f11ffe71bc0186f9e62eb0fe1727f676d038b62665a5c74c5", // put the actual hash here
},
// See `zig fetch --save <url>` for a command-line interface for adding dependencies.
//.example = .{
// // When updating this field to a new URL, be sure to delete the corresponding
// // `hash`, otherwise you are communicating that you expect to find the old hash at
// // the new URL.
// .url = "https://example.com/foo.tar.gz",
//
// // This is computed from the file contents of the directory of files that is
// // obtained after fetching `url` and applying the inclusion rules given by
// // `paths`.
// //
// // This field is the source of truth; packages do not come from a `url`; they
// // come from a `hash`. `url` is just one of many possible mirrors for how to
// // obtain a package matching this `hash`.
// //
// // Uses the [multihash](https://multiformats.io/multihash/) format.
// .hash = "...",
//
// // When this is provided, the package is found in a directory relative to the
// // build root. In this case the package's hash is irrelevant and therefore not
// // computed. This field and `url` are mutually exclusive.
// .path = "foo",
// // When this is set to `true`, a package is declared to be lazily
// // fetched. This makes the dependency only get fetched if it is
// // actually used.
// .lazy = false,
//},
},
// Specifies the set of files and directories that are included in this package.
// Only files and directories listed here are included in the `hash` that
// is computed for this package. Only files listed here will remain on disk
// when using the zig package manager. As a rule of thumb, one should list
// files required for compilation plus any license(s).
// Paths are relative to the build root. Use the empty string (`""`) to refer to
// the build root itself.
// A directory listed here means that all files within, recursively, are included.
.paths = .{
"build.zig",
"build.zig.zon",
"src",
// For example...
//"LICENSE",
"README.md",
},
}
|
0 | repos | repos/larry-pops-up/build.zig | const std = @import("std");
// Although this function looks imperative, note that its job is to
// declaratively construct a build graph that will be executed by an external
// runner.
pub fn build(b: *std.Build) void {
// Standard target options allows the person running `zig build` to choose
// what target to build for. Here we do not override the defaults, which
// means any target is allowed, and the default is native. Other options
// for restricting supported target set are available.
const target = b.standardTargetOptions(.{});
// Standard optimization options allow the person running `zig build` to select
// between Debug, ReleaseSafe, ReleaseFast, and ReleaseSmall. Here we do not
// set a preferred release mode, allowing the user to decide how to optimize.
const optimize = b.standardOptimizeOption(.{});
const exe = b.addExecutable(.{
.name = "LARPOPUP",
.root_source_file = b.path("src/main.zig"),
.target = target,
.optimize = optimize,
});
const raylib_dep = b.dependency("raylib-zig", .{
.target = target,
.optimize = optimize,
});
const raylib = raylib_dep.module("raylib"); // main raylib module
const raygui = raylib_dep.module("raygui"); // raygui module
const raylib_artifact = raylib_dep.artifact("raylib"); // raylib C library
exe.root_module.addImport("raylib", raylib);
exe.root_module.addImport("raygui", raygui);
// We don't need these defined here and it will break Windows builds anyway.
// The link is already taking care of via the Raylib build scripts from the .zon import.
// exe.linkFramework("CoreVideo");
// exe.linkFramework("IOKit");
// exe.linkFramework("Cocoa");
// exe.linkFramework("GLUT");
// exe.linkFramework("OpenGL");
exe.linkLibC();
exe.linkLibrary(raylib_artifact);
// This declares intent for the executable to be installed into the
// standard location when the user invokes the "install" step (the default
// step when running `zig build`).
b.installArtifact(exe);
// This *creates* a Run step in the build graph, to be executed when another
// step is evaluated that depends on it. The next line below will establish
// such a dependency.
const run_cmd = b.addRunArtifact(exe);
// By making the run step depend on the install step, it will be run from the
// installation directory rather than directly from within the cache directory.
// This is not necessary, however, if the application depends on other installed
// files, this ensures they will be present and in the expected location.
run_cmd.step.dependOn(b.getInstallStep());
// This allows the user to pass arguments to the application in the build
// command itself, like this: `zig build run -- arg1 arg2 etc`
if (b.args) |args| {
run_cmd.addArgs(args);
}
// This creates a build step. It will be visible in the `zig build --help` menu,
// and can be selected like this: `zig build run`
// This will evaluate the `run` step rather than the default, which is "install".
const run_step = b.step("run", "Run the app");
run_step.dependOn(&run_cmd.step);
const exe_unit_tests = b.addTest(.{
.root_source_file = b.path("src/main.zig"),
.target = target,
.optimize = optimize,
});
const run_exe_unit_tests = b.addRunArtifact(exe_unit_tests);
// Similar to creating the run step earlier, this exposes a `test` step to
// the `zig build --help` menu, providing a way for the user to request
// running the unit tests.
const test_step = b.step("test", "Run unit tests");
test_step.dependOn(&run_exe_unit_tests.step);
}
|
0 | repos/larry-pops-up | repos/larry-pops-up/src/main.zig | const std = @import("std");
const ogPack = @import("original_packs.zig");
const lsl6Pack = @import("lsl6_packs.zig");
const rl = @import("raylib");
const SCREEN_WIDTH = 125;
const SCREEN_HEIGHT = 125;
const FPS = 30; // FPS, barely does anything, no need to tax user's system.
const framesToPass = FPS >> 1; // Seconds to wait based on fps, so the user has a chance to see the image before it goes away.
var pngTexture: rl.Texture = undefined;
var selectedWav: rl.Sound = undefined;
var soundIsDone = false;
var killApp = false;
var scaleFactor: c_int = 1;
pub fn main() !void {
std.log.info("Larry Pops Up! - (@deckarep - 2024)\n", .{});
rl.initWindow(SCREEN_WIDTH, SCREEN_HEIGHT, "Larry Pops Up!");
rl.setWindowMaxSize(SCREEN_WIDTH, SCREEN_HEIGHT);
//rl.toggleBorderlessWindowed(); // - doesn't seem to work on macos.
rl.setWindowFocused();
defer rl.closeWindow();
rl.initAudioDevice();
defer rl.closeAudioDevice();
rl.setTargetFPS(FPS);
rl.setWindowPosition(0, 0);
const larryChosenResources = try choosePngAndWav();
std.debug.print(
"Larry Chosen Set: png: {d} wav: {d}\n",
.{ larryChosenResources.pngIdx, larryChosenResources.wavIdx },
);
const allPngs = ogPack.originalPngs ++ lsl6Pack.lsl6Pngs;
const selectedPng = allPngs[larryChosenResources.pngIdx];
const img = rl.loadImageFromMemory(".png", selectedPng);
if (larryChosenResources.pngIdx > 4) {
// Hack: the lsl6 are scaled up by 2.
scaleFactor = 2;
}
// Match the window size to the selected image file dimensions.
rl.setWindowSize(img.width * scaleFactor, img.height * scaleFactor);
pngTexture = rl.loadTextureFromImage(img);
defer rl.unloadTexture(pngTexture);
const selectedWavFile = ogPack.originalWavs[larryChosenResources.wavIdx];
const memWav = rl.loadWaveFromMemory(".wav", selectedWavFile);
selectedWav = rl.loadSoundFromWave(memWav);
defer rl.unloadSound(selectedWav);
while (!killApp and !rl.windowShouldClose()) {
try update();
try draw();
}
}
const selectedIndices = struct {
pngIdx: usize,
wavIdx: usize,
};
fn choosePngAndWav() !selectedIndices {
var prng = std.rand.DefaultPrng.init(blk: {
var seed: u64 = undefined;
try std.posix.getrandom(std.mem.asBytes(&seed));
break :blk seed;
});
const rand = prng.random();
const allPngCounts = ogPack.originalPngs.len - 1 + lsl6Pack.lsl6Pngs.len - 1;
const randPng = rand.intRangeAtMost(usize, 0, allPngCounts);
const randWav = rand.intRangeAtMost(usize, 0, ogPack.originalWavs.len - 1);
return selectedIndices{ .pngIdx = randPng, .wavIdx = randWav };
}
pub fn center_window(width: u32, height: u32) void {
const w = @as(c_int, @intCast(width));
const h = @as(c_int, @intCast(height));
const mon = rl.getCurrentMonitor();
const mon_width = rl.getMonitorWidth(mon);
const mon_height = rl.getMonitorHeight(mon);
rl.setWindowPosition(@divTrunc(mon_width, 2) - @divTrunc(w, 2), @divTrunc(mon_height, 2) - @divTrunc(h, 2));
}
var hangTime: i32 = 0;
var soundPlayCount: i32 = 0;
fn update() !void {
if (soundPlayCount == 0 and !rl.isSoundPlaying(selectedWav) and rl.isSoundReady(selectedWav)) {
rl.playSound(selectedWav);
soundPlayCount = 1;
}
if (!rl.isSoundPlaying(selectedWav)) {
soundIsDone = true;
hangTime += 1;
}
if (hangTime >= framesToPass) {
killApp = true;
}
}
fn draw() !void {
rl.beginDrawing();
defer rl.endDrawing();
rl.clearBackground(rl.Color.pink);
// Some assets might be scaled, so we use the more complicated from for teture drawing.
const tw: f32 = @floatFromInt(pngTexture.width);
const th: f32 = @floatFromInt(pngTexture.height);
const sf: f32 = @floatFromInt(scaleFactor);
const src = rl.Rectangle.init(0, 0, tw, th);
const dst = rl.Rectangle.init(0, 0, tw * sf, th * sf);
const org = rl.Vector2.init(0, 0);
rl.drawTexturePro(pngTexture, src, dst, org, 0, rl.Color.white);
}
|
0 | repos/larry-pops-up | repos/larry-pops-up/src/original_packs.zig | // These are the original Larry Pops Up! sound bites. They will be embedded in the binary.
// In the future, the end-user may provide .png or .wav files in a dedicated folder of their choosing
// for their own fun.
// originalPngs is a hardcoded, static table of all possible Larry images to show.
// perhaps more will be added...why the hell not?
pub const originalPngs = [_][]const u8{
@embedFile("embeded/LpopsUp1/POP1.png"),
@embedFile("embeded/LpopsUp2/POP2.png"),
@embedFile("embeded/LpopsUp3/POP3.png"),
@embedFile("embeded/LpopsUp4/POP4.png"),
@embedFile("embeded/LpopsUp5/POP5.png"),
};
// originalWavs is a hardcoded, static table of all possible sound bites to play.
// Yes, a big fucken static list, get over it...this is a desktop toy.
pub const originalWavs = [_][]const u8{
@embedFile("embeded/LpopsUp1/L001.WAV"),
@embedFile("embeded/LpopsUp1/L005.WAV"),
@embedFile("embeded/LpopsUp1/L007.WAV"),
@embedFile("embeded/LpopsUp1/L010.WAV"),
@embedFile("embeded/LpopsUp1/L015.WAV"),
@embedFile("embeded/LpopsUp1/L020.WAV"),
@embedFile("embeded/LpopsUp1/L021.WAV"),
@embedFile("embeded/LpopsUp1/L024.WAV"),
@embedFile("embeded/LpopsUp1/L036.WAV"),
@embedFile("embeded/LpopsUp1/L037.WAV"),
@embedFile("embeded/LpopsUp1/L044.WAV"),
@embedFile("embeded/LpopsUp1/L049.WAV"),
@embedFile("embeded/LpopsUp1/L051.WAV"),
@embedFile("embeded/LpopsUp1/L057.WAV"),
@embedFile("embeded/LpopsUp1/L070.WAV"),
@embedFile("embeded/LpopsUp1/L082.WAV"),
@embedFile("embeded/LpopsUp1/L086.WAV"),
@embedFile("embeded/LpopsUp1/L098.WAV"),
@embedFile("embeded/LpopsUp1/L099.WAV"),
@embedFile("embeded/LpopsUp1/L130.WAV"),
@embedFile("embeded/LpopsUp1/L137.WAV"),
@embedFile("embeded/LpopsUp2/L002.WAV"),
@embedFile("embeded/LpopsUp2/L006.WAV"),
@embedFile("embeded/LpopsUp2/L014.WAV"),
@embedFile("embeded/LpopsUp2/L018.WAV"),
@embedFile("embeded/LpopsUp2/L025.WAV"),
@embedFile("embeded/LpopsUp2/L040.WAV"),
@embedFile("embeded/LpopsUp2/L048.WAV"),
@embedFile("embeded/LpopsUp2/L056.WAV"),
@embedFile("embeded/LpopsUp2/L060.WAV"),
@embedFile("embeded/LpopsUp2/L062.WAV"),
@embedFile("embeded/LpopsUp2/L063.WAV"),
@embedFile("embeded/LpopsUp2/L077.WAV"),
@embedFile("embeded/LpopsUp2/L080.WAV"),
@embedFile("embeded/LpopsUp2/L084.WAV"),
@embedFile("embeded/LpopsUp2/L089.WAV"),
@embedFile("embeded/LpopsUp2/L095.WAV"),
@embedFile("embeded/LpopsUp2/L103.WAV"),
@embedFile("embeded/LpopsUp2/L109.WAV"),
@embedFile("embeded/LpopsUp2/L110.WAV"),
@embedFile("embeded/LpopsUp2/L111.WAV"),
@embedFile("embeded/LpopsUp2/L115.WAV"),
@embedFile("embeded/LpopsUp2/L131.WAV"),
@embedFile("embeded/LpopsUp3/L003.WAV"),
@embedFile("embeded/LpopsUp3/L009.WAV"),
@embedFile("embeded/LpopsUp3/L026.WAV"),
@embedFile("embeded/LpopsUp3/L033.WAV"),
@embedFile("embeded/LpopsUp3/L034.WAV"),
@embedFile("embeded/LpopsUp3/L035.WAV"),
@embedFile("embeded/LpopsUp3/L038.WAV"),
@embedFile("embeded/LpopsUp3/L041.WAV"),
@embedFile("embeded/LpopsUp3/L045.WAV"),
@embedFile("embeded/LpopsUp3/L050.WAV"),
@embedFile("embeded/LpopsUp3/L064.WAV"),
@embedFile("embeded/LpopsUp3/L065.WAV"),
@embedFile("embeded/LpopsUp3/L073.WAV"),
@embedFile("embeded/LpopsUp3/L079.WAV"),
@embedFile("embeded/LpopsUp3/L083.WAV"),
@embedFile("embeded/LpopsUp3/L091.WAV"),
@embedFile("embeded/LpopsUp3/L101.WAV"),
@embedFile("embeded/LpopsUp3/L106.WAV"),
@embedFile("embeded/LpopsUp3/L107.WAV"),
@embedFile("embeded/LpopsUp3/L112.WAV"),
@embedFile("embeded/LpopsUp3/L132.WAV"),
@embedFile("embeded/LpopsUp4/ANSWER.WAV"),
@embedFile("embeded/LpopsUp4/L004.WAV"),
@embedFile("embeded/LpopsUp4/L008.WAV"),
@embedFile("embeded/LpopsUp4/L028.WAV"),
@embedFile("embeded/LpopsUp4/L030.WAV"),
@embedFile("embeded/LpopsUp4/L039.WAV"),
@embedFile("embeded/LpopsUp4/L043.WAV"),
@embedFile("embeded/LpopsUp4/L053.WAV"),
@embedFile("embeded/LpopsUp4/L055.WAV"),
@embedFile("embeded/LpopsUp4/L066.WAV"),
@embedFile("embeded/LpopsUp4/L071.WAV"),
@embedFile("embeded/LpopsUp4/L081.WAV"),
@embedFile("embeded/LpopsUp4/L087.WAV"),
@embedFile("embeded/LpopsUp4/L090.WAV"),
@embedFile("embeded/LpopsUp4/L094.WAV"),
@embedFile("embeded/LpopsUp4/L105.WAV"),
@embedFile("embeded/LpopsUp4/L108.WAV"),
@embedFile("embeded/LpopsUp4/L119.WAV"),
@embedFile("embeded/LpopsUp4/L120.WAV"),
@embedFile("embeded/LpopsUp4/L122.WAV"),
@embedFile("embeded/LpopsUp4/L126.WAV"),
@embedFile("embeded/LpopsUp4/L133.WAV"),
@embedFile("embeded/LpopsUp4/L138.WAV"),
@embedFile("embeded/LpopsUp5/L012.WAV"),
@embedFile("embeded/LpopsUp5/L016.WAV"),
@embedFile("embeded/LpopsUp5/L023.WAV"),
@embedFile("embeded/LpopsUp5/L027.WAV"),
@embedFile("embeded/LpopsUp5/L032.WAV"),
@embedFile("embeded/LpopsUp5/L042.WAV"),
@embedFile("embeded/LpopsUp5/L058.WAV"),
@embedFile("embeded/LpopsUp5/L059.WAV"),
@embedFile("embeded/LpopsUp5/L068.WAV"),
@embedFile("embeded/LpopsUp5/L069.WAV"),
@embedFile("embeded/LpopsUp5/L072.WAV"),
@embedFile("embeded/LpopsUp5/L075.WAV"),
@embedFile("embeded/LpopsUp5/L085.WAV"),
@embedFile("embeded/LpopsUp5/L092.WAV"),
@embedFile("embeded/LpopsUp5/L096.WAV"),
@embedFile("embeded/LpopsUp5/L097.WAV"),
@embedFile("embeded/LpopsUp5/L104.WAV"),
@embedFile("embeded/LpopsUp5/L113.WAV"),
@embedFile("embeded/LpopsUp5/L116.WAV"),
@embedFile("embeded/LpopsUp5/L117.WAV"),
@embedFile("embeded/LpopsUp5/L134.WAV"),
};
|
0 | repos/larry-pops-up | repos/larry-pops-up/src/lsl6_packs.zig | pub const lsl6Pngs = [_][]const u8{
@embedFile("embeded/lsl6/larry_suit_blush.png"),
@embedFile("embeded/lsl6/larry_suit_smile.png"),
@embedFile("embeded/lsl6/larry_suit_think.png"),
@embedFile("embeded/lsl6/larry_suit_thumbsup.png"),
@embedFile("embeded/lsl6/larry_noshirt_thumbsup.png"),
@embedFile("embeded/lsl6/larry_noshirt_think.png"),
@embedFile("embeded/lsl6/larry_noshirt_smile.png"),
};
|
0 | repos | repos/brainfuck-zig/README.md | # Brainfuck-zig
Embeddable zig brainfuck interpreter.
## Usage
`usage: brainfuck [-e expression] [file path]`
## Embedding
```zig
const interpreter = @import("brainfuck-zig/src/main.zig").interpreter;
try interpret(program_string, reader, writer, error_writer);
```
|
0 | repos | repos/brainfuck-zig/build.zig | const std = @import("std");
// Although this function looks imperative, note that its job is to
// declaratively construct a build graph that will be executed by an external
// runner.
pub fn build(b: *std.Build) void {
// Standard target options allows the person running `zig build` to choose
// what target to build for. Here we do not override the defaults, which
// means any target is allowed, and the default is native. Other options
// for restricting supported target set are available.
const target = b.standardTargetOptions(.{});
// Standard optimization options allow the person running `zig build` to select
// between Debug, ReleaseSafe, ReleaseFast, and ReleaseSmall. Here we do not
// set a preferred release mode, allowing the user to decide how to optimize.
const optimize = b.standardOptimizeOption(.{});
const exe = b.addExecutable(.{
.name = "brainfuck",
.root_source_file = .{ .path = "src/main.zig" },
.target = target,
.optimize = optimize,
});
// This declares intent for the executable to be installed into the
// standard location when the user invokes the "install" step (the default
// step when running `zig build`).
b.installArtifact(exe);
// This *creates* a Run step in the build graph, to be executed when another
// step is evaluated that depends on it. The next line below will establish
// such a dependency.
const run_cmd = b.addRunArtifact(exe);
// By making the run step depend on the install step, it will be run from the
// installation directory rather than directly from within the cache directory.
// This is not necessary, however, if the application depends on other installed
// files, this ensures they will be present and in the expected location.
run_cmd.step.dependOn(b.getInstallStep());
// This allows the user to pass arguments to the application in the build
// command itself, like this: `zig build run -- arg1 arg2 etc`
if (b.args) |args| {
run_cmd.addArgs(args);
}
// This creates a build step. It will be visible in the `zig build --help` menu,
// and can be selected like this: `zig build run`
// This will evaluate the `run` step rather than the default, which is "install".
const run_step = b.step("run", "Run the app");
run_step.dependOn(&run_cmd.step);
// Creates a step for unit testing. This only builds the test executable
// but does not run it.
const exe_unit_tests = b.addTest(.{
.root_source_file = .{ .path = "src/main.zig" },
.target = target,
.optimize = optimize,
});
const run_exe_unit_tests = b.addRunArtifact(exe_unit_tests);
// Similar to creating the run step earlier, this exposes a `test` step to
// the `zig build --help` menu, providing a way for the user to request
// running the unit tests.
const test_step = b.step("test", "Run unit tests");
test_step.dependOn(&run_exe_unit_tests.step);
}
|
0 | repos/brainfuck-zig | repos/brainfuck-zig/src/main.zig | const std = @import("std");
const testing = std.testing;
const allocator = std.heap.page_allocator;
const memory_size = 30_000;
const max_file_size = 1024 * 1024 * 1024;
pub fn main() anyerror!void {
const args = try std.process.argsAlloc(allocator);
defer std.process.argsFree(allocator, args);
const stdin = std.io.getStdIn().reader();
const stdout = std.io.getStdOut().writer();
const stderr = std.io.getStdErr().writer();
if (args.len != 2 and !(args.len == 3 and std.mem.eql(u8, args[1], "-e"))) {
try stderr.print("usage: brainfuck [-e expression] [file path]\n", .{});
std.os.exit(1);
}
if (args.len == 3) {
const program = args[2];
interpret(program, stdin, stdout, stderr) catch std.os.exit(1);
} else if (args.len == 2) {
const file_path = args[1];
const program = std.fs.cwd().readFileAlloc(allocator, file_path, max_file_size) catch {
try stderr.print("File not found: {s}\n", .{file_path});
std.os.exit(1);
};
defer allocator.free(program);
interpret(program, stdin, stdout, stderr) catch std.os.exit(1);
}
}
pub fn interpret(program: []const u8, reader: anytype, writer: anytype, error_writer: anytype) anyerror!void {
var memory = [_]i32{0} ** memory_size;
var index: u32 = 0;
var program_counter: u32 = 0;
while (program_counter < program.len) {
const character = program[program_counter];
switch (character) {
'>' => {
if (index == memory_size - 1) {
try error_writer.print("Error: index out of upper bounds at char {d}\n", .{program_counter});
return error.IndexOutOfBounds;
}
index += 1;
},
'<' => {
if (index == 0) {
try error_writer.print("Error: index out of lower bounds at char {d}\n", .{program_counter});
return error.IndexOutOfBounds;
}
index -= 1;
},
'+' => {
memory[index] +%= 1;
},
'-' => {
memory[index] -%= 1;
},
'.' => {
const out_byte: u8 = @truncate(@as(u32, @bitCast(memory[index])));
try writer.writeByte(out_byte);
},
',' => {
memory[index] = reader.readByte() catch 0;
},
'[' => {
if (memory[index] == 0) {
const start = program_counter;
var depth: u32 = 1;
while (program_counter < program.len - 1) {
program_counter += 1;
const seek_char = program[program_counter];
if (seek_char == ']') {
depth -= 1;
}
if (depth == 0) {
break;
}
if (seek_char == '[') {
depth += 1;
}
}
if (program_counter == program.len - 1 and depth != 0) {
try error_writer.print("Error: missing closing braket to opening bracket at char {d}\n", .{start});
return error.MissingClosingBracket;
}
}
},
']' => {
if (memory[index] != 0) {
const start = program_counter;
var depth: u32 = 1;
while (program_counter > 0) {
program_counter -= 1;
const seek_char = program[program_counter];
if (seek_char == '[') {
depth -= 1;
}
if (depth == 0) {
break;
}
if (seek_char == ']') {
depth += 1;
}
}
if (program_counter == 0 and depth != 0) {
try error_writer.print("Error: missing opening bracket to closing bracket at char {d}\n", .{start});
return error.MissingOpeningBracket;
}
}
},
else => {},
}
program_counter += 1;
}
}
test "get cell bit width brainfuck" {
const program =
\\ // This generates 65536 to check for larger than 16bit cells
\\ [-]>[-]++[<++++++++>-]<[>++++++++<-]>[<++++++++>-]<[>++++++++<-]>[<+++++
\\ +++>-]<[[-]
\\ [-]>[-]+++++[<++++++++++>-]<+.-.
\\ [-]]
\\ // This section is cell doubling for 16bit cells
\\ >[-]>[-]<<[-]++++++++[>++++++++<-]>[<++++>-]<[->+>+<<]>[<++++++++>-]<[>+
\\ +++++++<-]>[<++++>-]>[<+>[-]]<<[>[-]<[-]]>[-<+>]<[[-]
\\ [-]>[-]+++++++[<+++++++>-]<.+++++.
\\ [-]]
\\ // This section is cell quadrupling for 8bit cells
\\ [-]>[-]++++++++[<++++++++>-]<[>++++<-]+>[<->[-]]<[[-]
\\ [-]>[-]+++++++[<++++++++>-]<.
\\ [-]]
\\ [-]>[-]++++[-<++++++++>]<.[->+++<]>++.+++++++.+++++++++++.[----<+>]<+++.
\\ +[->+++<]>.++.+++++++..+++++++.[-]++++++++++.[-]<
;
var output = std.ArrayList(u8).init(std.testing.allocator);
defer output.deinit();
const stdin = std.io.getStdIn().reader();
const stdout = output.writer();
const stderr = std.io.null_writer;
try interpret(program, stdin, stdout, stderr);
try std.testing.expectEqualStrings("32 bit cells\n", output.items);
}
test "write in cell outside of array bottom" {
const program = "<<<+";
const stdin = std.io.getStdIn().reader();
const stdout = std.io.null_writer;
const stderr = std.io.null_writer;
const output = interpret(program, stdin, stdout, stderr);
try testing.expectError(error.IndexOutOfBounds, output);
}
test "write in cell outside of array top" {
const program = ">" ** memory_size;
const stdin = std.io.getStdIn().reader();
const stdout = std.io.null_writer;
const stderr = std.io.null_writer;
const output = interpret(program, stdin, stdout, stderr);
try testing.expectError(error.IndexOutOfBounds, output);
}
test "write number over 255 to writer" {
const program = "+" ** 300 ++ ".";
const stdin = std.io.getStdIn().reader();
const stdout = std.io.null_writer;
const stderr = std.io.null_writer;
try interpret(program, stdin, stdout, stderr);
}
test "write negative number to writer" {
const program = "-" ** 200 ++ ".";
const stdin = std.io.getStdIn().reader();
const stdout = std.io.null_writer;
const stderr = std.io.null_writer;
try interpret(program, stdin, stdout, stderr);
}
test "loop without end" {
const program = "[><";
const stdin = std.io.getStdIn().reader();
const stdout = std.io.null_writer;
const stderr = std.io.null_writer;
const output = interpret(program, stdin, stdout, stderr);
try testing.expectError(error.MissingClosingBracket, output);
}
test "loop without beginning" {
const program = "+><]";
const stdin = std.io.getStdIn().reader();
const stdout = std.io.null_writer;
const stderr = std.io.null_writer;
const output = interpret(program, stdin, stdout, stderr);
try testing.expectError(error.MissingOpeningBracket, output);
}
|
0 | repos | repos/SortedMap/README.md | # SortedMap in ZIG
## Description
Sorted Map is a fast key-value table, an advance version of [skiplist ADT](https://en.wikipedia.org/wiki/Skip_list) as proposed by W.Pugh in 1989 for ordered mapping of keys to values.
## Features
* Takes any numeric key except the maximum possible value for the given type.
* Takes any literal key of type `[]const u8` and of any length, but lexicographically smaller than `"ÿ"` ASCII 255.
* Values are arbitrary values.
* Works in `.set` or `.list` mode. The latter allows duplicate keys.
* Has forward and backward iteration.
* Has `min`, `max`, `median` key query.
* Supports queries by key or index, similar to Python's list class, including reverse indexing.
* Basic operations like `get`, `remove` work on a range as well.
* Updating the values by giving the `start_idx` - `stop_idx` range is O(1) each update. Yes, the whole map can be updated in O(n).
* Updating the values by giving the `start_key` - `stop_key` range is O(1) each update.
## Performance
The benchmark is a set of standard stress routines to measure the throughput for the given task. The machine is an Apple M1 with 32GB RAM, optimization flag `ReleaseFast`.
There are five tests in total, all of which are run on the random data with intermediate shuffling during the test stages:
**READ HEAVY**\
[read 98, insert 1, remove 1, update 0 ]\
Models caching of data in places such as web servers and disk page caches.
**EXCHANGE**\
[read 10, insert 40, remove 40, update 10]\
Replicates a scenario where the map is used to exchange data.
**EXCHANGE HEAVY**\
[read 1, insert 98, remove 98, update 1]\
This test is an inverse of *RH* test. Hard for any map.
**RAPID GROW**\
[read 5, insert 80, remove 5, update 10]\
A scenario where the map is used to collect large amounts of data in a short burst.
**CLONE**\
Clone the Map. That is, rebuild the map anew yet from the sorted data.
### `u64`, arbitrary feed
```
SortedMap u64 BENCHMARK|
10_000_000 ops:each test|
|name |Tp Mops:sec| Rt :sec|
=====================================
|RH | 51.47| 0.194274|
arena size: 13804, cache len: 131
|EX | 23.25| 0.430069|
arena size: 13804, cache len: 121
|EXH | 20.20| 0.494928|
arena size: 13804, cache len: 135
|RG | 0.53| 18.996072|
arena size: 595966060, cache len: 5
|CLONE | 5.86| 1.279128|
```
### `[8]const u8`, arbitrary literal, arbitrary feed
```
SortedMap STR BENCHMARK|
10_000_000 ops:each test|
|name |Tp Mops:sec| Rt :sec|
=====================================
|RH | 25.49| 0.392336|
arena size: 13564, cache len: 133
|EX | 17.02| 0.587408|
arena size: 13564, cache len: 123
|EXH | 14.49| 0.690115|
arena size: 13564, cache len: 137
|RG | 0.37| 26.855707|
arena size: 894236804, cache len: 5
|CLONE | 3.12| 2.400613|
```
## How to run the benchmark
```
zig build bench
```
By default it runs 100_000 rounds each test on the `u64` type.
Give it a larger number to stress the map more.
```
zig build bench -- 1_000_000
```
Prepend with `-str` to test on the arbitrary `[8]u8` word.
```
zig build bench -- 1_000_000 -str
```
## How to use it
Copy `sorted_map.zig` and `cache.zig` into your project, or make a fork and work from there. Or you can import it as a dependency.
Declare in your file:
```zig
const SortedMap = @import("sorted_map.zig").SortedMap;
```
Initiate for numeric keys:
```zig
const map = SortedMap(u64, your_value_type, .list).init(your_allocator);
defer map.deinit();
```
Initiate for string literal keys:
```zig
const map = SortedMap([]const u8, your_value_type, .set).init(your_allocator);
defer map.deinit();
```
## zig version
```
0.12.0-dev.1830+779b8e259
```
|
0 | repos | repos/SortedMap/build.zig.zon | .{
.name = "SortedMap",
.version = "0.0.1",
.paths = .{"."},
.dependencies = .{},
}
|
0 | repos | repos/SortedMap/build.zig | const std = @import("std");
pub fn build(b: *std.Build) void {
const target = b.standardTargetOptions(.{});
_ = b.addModule(
"SortedMap",
.{ .source_file = .{ .path = "src/sorted_map.zig" } },
);
const lib = b.addStaticLibrary(.{
.name = "skiplist",
.root_source_file = .{ .path = "src/sorted_map.zig" },
.target = target,
.optimize = .ReleaseSafe,
});
b.installArtifact(lib);
// BENCH
const bench = b.addExecutable(.{
.name = "SortedMap_bench",
.root_source_file = .{ .path = "src/bench.zig" },
.target = target,
.optimize = .ReleaseFast,
});
const bench_run = b.addRunArtifact(bench);
if (b.args) |args| {
bench_run.addArgs(args);
}
const bench_step = b.step("bench", "Run benchmark");
bench_step.dependOn(&bench_run.step);
// TEST
const main_tests = b.addTest(.{
.root_source_file = .{ .path = "src/sorted_map.zig" },
.target = target,
.optimize = .ReleaseSafe,
});
const run_main_tests = b.addRunArtifact(main_tests);
const test_step = b.step("test", "Run library tests");
test_step.dependOn(&run_main_tests.step);
}
|
0 | repos/SortedMap | repos/SortedMap/src/cache.zig | const std = @import("std");
/// A wrapper around an allocator to hold the memory
/// of previously deleted items, but serving it when needed
/// instead of allocating new bytes.\
/// https://zig.news/xq/cool-zig-patterns-gotta-alloc-fast-23h (c)
pub fn Cache(comptime T: type) type {
return struct {
const List = std.DoublyLinkedList(T);
const Self = @This();
arena: std.heap.ArenaAllocator = undefined,
free: List = .{},
pub fn init(allocator: std.mem.Allocator) Self {
return .{ .arena = std.heap.ArenaAllocator.init(allocator) };
}
pub fn deinit(self: *Self) void {
self.arena.deinit();
}
pub fn new(self: *Self) !*T {
const obj = if (self.free.popFirst()) |item|
item
else
try self.arena.allocator().create(List.Node);
return &obj.data;
}
pub fn reuse(self: *Self, obj: *T) void {
const node = @fieldParentPtr(List.Node, "data", obj);
self.free.append(node);
}
pub fn destroy(self: *Self, obj: *T) void {
const node = @fieldParentPtr(List.Node, "data", obj);
self.arena.allocator().destroy(node);
}
pub fn clear(self: *Self) void {
while (self.free.len > 0) {
self.destroy(&self.free.pop().?.data);
}
}
};
}
|
0 | repos/SortedMap | repos/SortedMap/src/bench.zig | const std = @import("std");
const SortedMap = @import("sorted_map.zig").SortedMap;
const stdout = std.io.getStdOut().writer();
const assert = std.debug.assert;
const sEql = std.mem.eql;
pub fn benchSTR(N: usize) !void {
var gpa = std.heap.GeneralPurposeAllocator(.{}){};
defer if (gpa.deinit() == .leak) {
@panic("memory leak ...");
};
const allocatorG = gpa.allocator();
var arena = std.heap.ArenaAllocator.init(std.heap.page_allocator);
var allocatorA = arena.allocator();
defer arena.deinit();
var sL = try SortedMap([]const u8, []const u8, .set).init(allocatorG);
defer sL.deinit();
var keys = std.ArrayList([]const u8).init(allocatorA);
defer keys.deinit();
var prng = std.rand.DefaultPrng.init(@abs(std.time.timestamp()));
const random = prng.random();
const T = [8]u8;
for (0..N) |_| {
var key: *T = try allocatorA.create(T);
for (0..8) |idx| {
key[idx] = random.intRangeAtMost(u8, 33, 127);
}
try keys.append(key);
}
random.shuffle([]const u8, keys.items);
// Cosmetic function, number formatting
var buffer: [16]u8 = undefined;
const len = pretty(N, &buffer, allocatorA);
// Print benchmark header
try stdout.print("\n{s: >38}|", .{"SortedMap STR BENCHMARK"});
try stdout.print("\n{s: >24} ops:each test|\n", .{buffer[0..len]});
try stdout.print("\n|{s: <13}|{s: >11}|{s: >11}|\n", .{ "name", "Tp Mops:sec", "Rt :sec" });
try stdout.print(" {s:=>37}\n", .{""});
// ------------------ READ HEAVY -----------------//
// ---- read 98, insert 1, remove 1, update 0 --- //
// Initial input for the test because we start with read.
for (keys.items[0..98]) |key| {
try sL.put(key, key);
}
// Start the timer
var time: u128 = 0;
var aggregate: u128 = 0;
var timer = try std.time.Timer.start();
var start = timer.lap();
// Cycle of 100 operations each
for (0..N / 100) |i| {
// Read the slice of 98 keys
for (keys.items[i .. i + 98]) |key| {
// assert(sL.get(key) == key);
assert(sEql(u8, sL.get(key).?, key));
}
// Insert 1 new
try sL.put(keys.items[i + 98], keys.items[i + 98]);
// Remove 1
assert(sL.remove(keys.items[i]));
}
var end = timer.read();
time += end -| start;
aggregate += time;
// Print stats //
// Test' individual stats
try writeStamps("RH", N, time);
// Clear the sL
assert(sL.size == 98);
try sL.clearRetainingCapacity();
arenaCacheSizeQuery(&sL.cache);
// ------------------ EXCHANGE -------------------//
// -- read 10, insert 40, remove 40, update 10 -- //
// Re-shuffle the keys
random.shuffle([]const u8, keys.items);
// Initial input for the test, 10 keys, because we start with read
for (keys.items[0..10]) |key| {
try sL.put(key, key);
}
// Clear the time, re-start the timer
time = 0;
timer = try std.time.Timer.start();
start = timer.lap();
// Cycle of 100 operations each
var k: usize = 0; // helper coefficient to get the keys rotating
for (0..N / 100) |i| {
// Read 10
for (keys.items[i + k .. i + k + 10]) |key| {
// assert(sL.get(key) == key);
assert(sEql(u8, sL.get(key).?, key));
}
// Insert 40 new
for (keys.items[i + k + 10 .. i + k + 50]) |key| {
try sL.put(key, key);
}
// Remove 40
for (keys.items[i + k .. i + k + 40]) |key| {
assert(sL.remove(key));
}
// Update 10
for (keys.items[i + k + 40 .. i + k + 50]) |key| {
assert(sL.update(key, key));
}
k += 39;
}
end = timer.read();
time += end -| start;
aggregate += time;
// Print stats //
// Test' individual stats
try writeStamps("EX", N, time);
// Clear the sL
assert(sL.size == 10);
try sL.clearRetainingCapacity();
arenaCacheSizeQuery(&sL.cache);
// --------------- EXCHANGE HEAVY --------------//
// -- read 1, insert 98, remove 98, update 1 -- //
// Re-shuffle the keys
random.shuffle([]const u8, keys.items);
// Initial input for the test, 10 keys, because we start with read
for (keys.items[0..1]) |key| {
try sL.put(key, key);
}
// Clear the time, re-start the timer
time = 0;
timer = try std.time.Timer.start();
start = timer.lap();
// Cycle of 198 operations each
k = 0; // helper coefficient to get the keys rotating
for (0..N / 198) |i| {
// Read 1
for (keys.items[i + k .. i + k + 1]) |key| {
// assert(sL.get(key) == key);
assert(sEql(u8, sL.get(key).?, key));
}
// Insert 98 new
for (keys.items[i + k + 1 .. i + k + 99]) |key| {
try sL.put(key, key);
}
// Remove 98
for (keys.items[i + k .. i + k + 98]) |key| {
assert(sL.remove(key));
}
// Update 1
for (keys.items[i + k + 98 .. i + k + 99]) |key| {
assert(sL.update(key, key));
}
k += 97;
}
end = timer.read();
time += end -| start;
aggregate += time;
// Print stats //
// Test' individual stats
try writeStamps("EXH", N, time);
// Clear the sL
assert(sL.size == 1);
try sL.clearRetainingCapacity();
arenaCacheSizeQuery(&sL.cache);
// ---------------- RAPID GROW -----------------//
// -- read 5, insert 80, remove 5, update 10 -- //
// Re-shuffle the keys
random.shuffle([]const u8, keys.items);
// Initial input for the test, 5 keys, because we start with read
for (keys.items[0..5]) |key| {
try sL.put(key, key);
}
// Clear the time, re-start the timer
time = 0;
timer = try std.time.Timer.start();
start = timer.lap();
// Cycle of 100 operations each
k = 0; // helper coefficient to get the keys rotating
for (0..N / 100) |i| {
// Read 5
for (keys.items[i + k .. i + k + 5]) |key| {
// assert(sL.get(key) == key);
assert(sEql(u8, sL.get(key).?, key));
}
// Insert 80 new
for (keys.items[i + k + 5 .. i + k + 85]) |key| {
try sL.put(key, key);
}
// Remove 5
for (keys.items[i + k .. i + k + 5]) |key| {
assert(sL.remove(key));
}
// Update 10
for (keys.items[i + k + 5 .. i + k + 15]) |key| {
assert(sL.update(key, key));
}
k += 79;
}
end = timer.read();
time += end -| start;
aggregate += time;
// Print stats //
// Test' individual stats
try writeStamps("RG", N, time);
arenaCacheSizeQuery(&sL.cache);
// ---------------- CLONING -----------------//
// ------ obtain a clone of the graph ------ //
// Clear the time, re-start the timer
time = 0;
timer = try std.time.Timer.start();
start = timer.lap();
var clone = try sL.clone();
defer clone.deinit();
end = timer.read();
time += end -| start;
aggregate += time;
// Print stats //
// Test' individual stats
try writeStamps("CLONE", clone.size, time);
try stdout.print("\n", .{});
}
pub fn benchU64(N: usize) !void {
var gpa = std.heap.GeneralPurposeAllocator(.{}){};
defer if (gpa.deinit() == .leak) {
@panic("memory leak ...");
};
const allocatorG = gpa.allocator();
var arena = std.heap.ArenaAllocator.init(std.heap.page_allocator);
const allocatorA = arena.allocator();
defer arena.deinit();
var sL = try SortedMap(u64, u64, .set).init(allocatorG);
defer sL.deinit();
// try sL.ensureTotalCapacity(N);
// Get unique keys and shuffle them
var keys = std.ArrayList(u64).init(allocatorA);
defer keys.deinit();
var prng = std.rand.DefaultPrng.init(@abs(std.time.timestamp()));
const random = prng.random();
for (0..N) |key| {
try keys.append(key);
}
random.shuffle(u64, keys.items);
// Cosmetic function, number formatting
var buffer: [16]u8 = undefined;
const len = pretty(N, &buffer, allocatorA);
// Print benchmark header
try stdout.print("\n{s: >38}|", .{"SortedMap u64 BENCHMARK"});
try stdout.print("\n{s: >24} ops:each test|\n", .{buffer[0..len]});
try stdout.print("\n|{s: <13}|{s: >11}|{s: >11}|\n", .{ "name", "Tp Mops:sec", "Rt :sec" });
try stdout.print(" {s:=>37}\n", .{""});
// ------------------ READ HEAVY -----------------//
// ---- read 98, insert 1, remove 1, update 0 --- //
// Initial input for the test because we start with read.
for (keys.items[0..98]) |key| {
try sL.put(key, key);
}
// Start the timer
var time: u128 = 0;
var aggregate: u128 = 0;
var timer = try std.time.Timer.start();
var start = timer.lap();
// Cycle of 100 operations each
for (0..N / 100) |i| {
// Read the slice of 98 keys
for (keys.items[i .. i + 98]) |key| {
assert(sL.get(key) == key);
}
// Insert 1 new
try sL.put(keys.items[i + 98], keys.items[i + 98]);
// Remove 1
assert(sL.remove(keys.items[i]));
}
var end = timer.read();
time += end -| start;
aggregate += time;
// Print stats //
// Test' individual stats
try writeStamps("RH", N, time);
// Clear the sL
assert(sL.size == 98);
try sL.clearRetainingCapacity();
arenaCacheSizeQuery(&sL.cache);
// ------------------ EXCHANGE -------------------//
// -- read 10, insert 40, remove 40, update 10 -- //
// Re-shuffle the keys
random.shuffle(u64, keys.items);
// Initial input for the test, 10 keys, because we start with read
for (keys.items[0..10]) |key| {
try sL.put(key, key);
}
// Clear the time, re-start the timer
time = 0;
timer = try std.time.Timer.start();
start = timer.lap();
// Cycle of 100 operations each
var k: usize = 0; // helper coefficient to get the keys rotating
for (0..N / 100) |i| {
// Read 10
for (keys.items[i + k .. i + k + 10]) |key| {
assert(sL.get(key) == key);
}
// Insert 40 new
for (keys.items[i + k + 10 .. i + k + 50]) |key| {
try sL.put(key, key);
}
// Remove 40
for (keys.items[i + k .. i + k + 40]) |key| {
assert(sL.remove(key));
}
// Update 10
for (keys.items[i + k + 40 .. i + k + 50]) |key| {
assert(sL.update(key, key));
}
k += 39;
}
end = timer.read();
time += end -| start;
aggregate += time;
// Print stats //
// Test' individual stats
try writeStamps("EX", N, time);
// Clear the sL
assert(sL.size == 10);
try sL.clearRetainingCapacity();
arenaCacheSizeQuery(&sL.cache);
// --------------- EXCHANGE HEAVY --------------//
// -- read 1, insert 98, remove 98, update 1 -- //
// Re-shuffle the keys
random.shuffle(u64, keys.items);
// Initial input for the test, 1 key, because we start with read
for (keys.items[0..1]) |key| {
try sL.put(key, key);
}
// Clear the time, re-start the timer
time = 0;
timer = try std.time.Timer.start();
start = timer.lap();
// Cycle of 198 operations each
k = 0; // helper coefficient to get the keys rotating
for (0..N / 198) |i| {
// Read 1
for (keys.items[i + k .. i + k + 1]) |key| {
assert(sL.get(key) == key);
}
// Insert 98 new
for (keys.items[i + k + 1 .. i + k + 99]) |key| {
try sL.put(key, key);
}
// Remove 98
for (keys.items[i + k .. i + k + 98]) |key| {
assert(sL.remove(key));
}
// Update 1
for (keys.items[i + k + 98 .. i + k + 99]) |key| {
assert(sL.update(key, key));
}
k += 97;
}
end = timer.read();
time += end -| start;
aggregate += time;
// Print stats //
// Test' individual stats
try writeStamps("EXH", N, time);
// Clear the sL
assert(sL.size == 1);
try sL.clearRetainingCapacity();
arenaCacheSizeQuery(&sL.cache);
// ---------------- RAPID GROW -----------------//
// -- read 5, insert 80, remove 5, update 10 -- //
// Re-shuffle the keys
random.shuffle(u64, keys.items);
// Initial input for the test, 5 keys, because we start with read
for (keys.items[0..5]) |key| {
try sL.put(key, key);
}
// Clear the time, re-start the timer
time = 0;
timer = try std.time.Timer.start();
start = timer.lap();
// Cycle of 100 operations each
k = 0; // helper coefficient to get the keys rotating
for (0..N / 100) |i| {
// Read 5
for (keys.items[i + k .. i + k + 5]) |key| {
assert(sL.get(key) == key);
}
// Insert 80 new
for (keys.items[i + k + 5 .. i + k + 85]) |key| {
try sL.put(key, key);
}
// Remove 5
for (keys.items[i + k .. i + k + 5]) |key| {
assert(sL.remove(key));
}
// Update 10
for (keys.items[i + k + 5 .. i + k + 15]) |key| {
assert(sL.update(key, key));
}
k += 79;
}
end = timer.read();
time += end -| start;
aggregate += time;
// Print stats //
// Test' individual stats
try writeStamps("RG", N, time);
arenaCacheSizeQuery(&sL.cache);
// ---------------- CLONING -----------------//
// ------ obtain a clone of the graph ------ //
// Clear the time, re-start the timer
time = 0;
timer = try std.time.Timer.start();
start = timer.lap();
var clone = try sL.clone();
defer clone.deinit();
end = timer.read();
time += end -| start;
aggregate += time;
// Print stats //
// Test' individual stats
try writeStamps("CLONE", clone.size, time);
try stdout.print("\n", .{});
}
/// Print to the screen the size of the current memory being used by the arena allocator
/// along with the cache's len.
fn arenaCacheSizeQuery(cache: anytype) void {
std.debug.print("arena size: {}, cache len: {}\n\n", .{
cache.arena.queryCapacity(),
cache.free.len,
});
}
fn toSeconds(t: u128) f64 {
return @as(f64, @floatFromInt(t)) / 1_000_000_000;
}
fn throughput(N: usize, time: u128) f64 {
return @as(f64, @floatFromInt(N)) / toSeconds(time) / 1_000_000;
}
fn writeStamps(test_name: []const u8, N: usize, time: u128) !void {
const throughput_ = throughput(N, time);
const runtime = toSeconds(time);
try stdout.print("|{s: <13}|{d: >11.2}|{d: >11.6}|\n", .{ test_name, throughput_, runtime });
}
fn pretty(N: usize, buffer: []u8, alloc: std.mem.Allocator) usize {
var stack = std.ArrayList(u8).init(alloc);
defer stack.deinit();
var N_ = N;
var counter: u8 = 0;
while (N_ > 0) : (counter += 1) {
const rem: u8 = @intCast(N_ % 10);
if (counter == 3) {
stack.append(0x5F) catch unreachable;
counter = 0;
}
stack.append(rem + 48) catch unreachable;
N_ = @divFloor(N_, 10);
}
var j: usize = 0;
var k: usize = stack.items.len;
while (k > 0) : (j += 1) {
k -= 1;
buffer[j] = stack.items[k];
}
return stack.items.len;
}
const HELP =
\\skipList benchmark HELP menu
\\
\\command prompt example:
\\ zig build bench -- [option]
\\
\\info:
\\ options are optional
\\ default test runs on 1_000 of operations
\\ with unsigned integers as keys
\\
\\Options:
\\ [u64], unsigned integer,
\\ the number of operations you are interested benchmark is to run
\\
\\ [-str], string,
\\ benchmark string literals as keys
\\
\\ [-h], string,
\\ display this menu
\\
;
pub fn main() !void {
// get args
var buffer: [1024]u8 = undefined;
var fixed = std.heap.FixedBufferAllocator.init(buffer[0..]);
const args = try std.process.argsAlloc(fixed.allocator());
defer std.process.argsFree(fixed.allocator(), args);
// default number of operations
var N: usize = 100_000;
var string: bool = false;
var i: usize = 1;
if (args.len > 3) {
std.debug.print(HELP ++ "\n", .{});
return;
}
while (i < args.len) : (i += 1) {
var integer: bool = true;
for (args[i]) |char| {
if (char < 48 or char > 57 and char != 95) integer = false;
}
if (integer) {
// TODO give warning if N > 1B, y - n ?
N = try std.fmt.parseUnsigned(usize, args[i], 10);
// break;
} else if (std.mem.eql(u8, args[i], "-h")) {
std.debug.print(HELP ++ "\n", .{});
return;
} else if (std.mem.eql(u8, args[i], "-str")) {
string = true;
} else {
std.debug.print(HELP ++ "\n", .{});
return;
}
}
if (string) {
try benchSTR(N);
} else try benchU64(N);
}
|
0 | repos/SortedMap | repos/SortedMap/src/sorted_map.zig | // MIT (c) [email protected] 2023 //
const std = @import("std");
const Allocator = std.mem.Allocator;
const assert = std.debug.assert;
const eql = std.meta.eql;
const sEql = std.mem.eql;
const MapMode = enum { set, list };
/// A contiguous, growable map of key-value pairs in memory, sorted by key.
///
/// Keys can be numeric or literal. Values, any type.
/// When keys are string literals, it sorts lexicographically.
/// Slice and range operations are supported.
/// Works as either `.set` or `.list`; just pass the enum as the `mode` argument.
/// The `.list` mode allows duplicate keys.
///
/// IMPORTANT: Takes any numeric key except the maximum possible value for the given type.
/// Takes any literal key of type `[]const u8` and of any length,
/// but lexicographically smaller than `"ÿ"` ASCII 255.
///
pub fn SortedMap(comptime KEY: type, comptime VALUE: type, comptime mode: MapMode) type {
const keyIsString: bool = comptime if (KEY == []const u8) true else false;
return struct {
const MAXSIZE = if (keyIsString)
@as([]const u8, "ÿ")
else if (@typeInfo(KEY) == .Int)
std.math.maxInt(KEY)
else if (@typeInfo(KEY) == .Float)
std.math.inf(KEY)
else
@compileError("THE KEYS MUST BE NUMERIC OR LITERAL");
/// A field struct containing a key-value pair.
///
/// Format is this: { KEY, VALUE }\
/// Accessed VALUE must be tested for null.
pub const Item = struct { key: KEY, value: VALUE };
pub const Node = struct {
item: Item = undefined,
next: ?*Node = null,
parent: ?*Node = null,
width: usize = 0,
prev: ?*Node = null,
};
const SortedMapError = error{
EmptyList,
StartKeyIsGreaterThanEndKey,
StartIndexIsGreaterThanEndIndex,
MissingKey,
MissingStartKey,
MissingEndKey,
InvalidIndex,
InvalidStopIndex,
StepIndexIsZero,
};
const Self = @This();
const Stack = std.ArrayList(*Node);
const Cache = @import("cache.zig").Cache(Node);
/// Fixed probability of map growth up in "express lines."
const p: u3 = 7;
var mutex = std.Thread.Mutex{};
// Get random generator variables
var prng: std.rand.DefaultPrng = undefined;
var random: std.rand.Random = undefined;
trailer: *Node = undefined,
header: *Node = undefined,
size: usize = 0,
alloc: Allocator = undefined,
/// Coroutine control helper stack. No usage!
stack: Stack = undefined,
/// Stores all the nodes and manages their lifetime.
cache: Cache = undefined,
// NON-PUBLIC API, HELPER FUNCTIONS //
fn gTE(lhs: anytype, rhs: anytype) bool {
if (keyIsString) {
const answer = std.mem.order(u8, lhs, rhs);
return answer == .gt or answer == .eq;
}
return lhs >= rhs;
}
fn gT(lhs: anytype, rhs: anytype) bool {
return if (keyIsString) std.mem.order(u8, lhs, rhs) == .gt else lhs > rhs;
}
/// Equality test function for string literals and numerics
fn EQL(lhs: anytype, rhs: anytype) bool {
return if (keyIsString) sEql(u8, lhs, rhs) else eql(lhs, rhs);
}
/// Creates the node
fn makeNode(cache: *Cache, item: Item, next: ?*Node, parent: ?*Node, width: usize, prev: ?*Node) !*Node {
var node: *Node = try cache.new();
node.item = item;
node.next = next;
node.parent = parent;
node.prev = prev;
node.width = width;
return node;
}
fn makeHeadAndTail(self: *Self) !void {
self.trailer = try makeNode(
&self.cache,
Item{ .key = MAXSIZE, .value = undefined },
null,
null,
0,
self.header,
);
self.header = try makeNode(
&self.cache,
Item{ .key = MAXSIZE, .value = undefined },
self.trailer,
null,
0,
null,
);
}
fn insertNodeWithAllocation(self: *Self, item: Item, prev: ?*Node, parent: ?*Node, width: usize) !*Node {
prev.?.next.?.prev = try makeNode(&self.cache, item, prev.?.next, parent, width, prev);
prev.?.next = prev.?.next.?.prev.?;
return prev.?.next.?;
}
fn addNewLayer(self: *Self) !void {
self.header = try makeNode(
&self.cache,
Item{ .key = MAXSIZE, .value = undefined },
self.trailer,
self.header,
0,
null,
);
}
fn height(self: *Self) usize {
var node = self.header;
var height_: usize = 0;
while (node.parent != null) : (height_ += 1) {
node = node.parent.?;
}
return height_;
}
/// Used by removeSlice
fn getLevelStackPrev(self: *Self, key: KEY) !Stack {
self.stack.clearRetainingCapacity();
var node = self.header;
var foundKey: bool = false;
assert(node.parent != null);
while (node.parent != null) {
node = node.parent.?;
while (gT(key, node.next.?.item.key)) {
node = node.next.?;
}
if (EQL(key, node.next.?.item.key)) foundKey = true;
try self.stack.append(node);
}
if (!foundKey) {
self.stack.clearRetainingCapacity();
}
return self.stack;
}
/// Used by removeSlice
fn getLevelStackFirst(self: *Self, key: KEY) !Stack {
self.stack.clearRetainingCapacity();
var node = self.header;
var foundKey: bool = false;
assert(node.parent != null);
while (node.parent != null) {
node = node.parent.?;
while (EQL(key, node.item.key))
node = node.prev.?;
while (gTE(key, node.next.?.item.key)) {
node = node.next.?;
if (EQL(key, node.item.key)) {
foundKey = true;
break;
}
}
try self.stack.append(node);
}
if (!foundKey) {
self.stack.clearRetainingCapacity();
}
return self.stack;
}
/// Used by fetchRemove and put
fn getLevelStack(self: *Self, key: KEY) !Stack {
self.stack.clearRetainingCapacity();
var node = self.header;
assert(node.parent != null);
while (node.parent != null) {
node = node.parent.?;
while (gTE(key, node.next.?.item.key)) {
node = node.next.?;
}
try self.stack.append(node);
}
return self.stack;
}
/// Used by fetchRemoveByIndex
fn getLevelStackByIndex(self: *Self, index: u64) !Stack {
self.stack.clearRetainingCapacity();
var index_ = index;
var node = self.header;
index_ += 1;
while (node.parent != null) {
node = node.parent.?;
while (!eql(node.next.?.item.key, MAXSIZE) and index_ >= node.next.?.width) {
index_ -= node.next.?.width;
node = node.next.?;
}
try self.stack.append(node);
}
return self.stack;
}
fn width_(self: *Self, node: *Node, key: KEY) usize {
_ = self;
var node__: *Node = node;
var width: usize = 0;
while (node__.parent != null) {
node__ = node__.parent.?;
while (gTE(key, node__.next.?.item.key)) {
width += node__.next.?.width;
node__ = node__.next.?;
}
}
return width;
}
fn groundLeft(self: *Self) *Node {
var node = self.header;
while (node.parent != null)
node = node.parent.?;
return node.next.?;
}
fn groundRight(self: *Self) *Node {
var node = self.header;
while (node.parent != null) {
node = node.parent.?;
while (gT(MAXSIZE, node.next.?.item.key)) {
node = node.next.?;
}
}
return node;
}
fn removeLoop(self: *Self, key: KEY, stack: *Stack) void {
while (stack.items.len > 0) {
var node: *Node = stack.pop();
if (!keyIsString) {
if (eql(key, node.item.key)) {
if (node.next.?.parent != null) {
node.next.?.width += node.width - 1;
}
node.prev.?.next = node.next.?;
node.next.?.prev = node.prev.?;
self.cache.reuse(node); // reuse allocated memory
} else {
node.next.?.width -|= 1;
}
} else {
if (sEql(u8, key, node.item.key)) {
if (node.next.?.parent != null) {
node.next.?.width += node.width - 1;
}
node.prev.?.next = node.next.?;
node.next.?.prev = node.prev.?;
self.cache.reuse(node); // reuse allocated memory
} else {
node.next.?.width -|= 1;
}
}
}
}
//////////////////// PUBLIC API //////////////////////
/// Initiate the SortedMAP with the given allocator.
pub fn init(alloc: Allocator) !Self {
// Initiate random generator
prng = std.rand.DefaultPrng.init(blk: {
var seed: u64 = undefined;
try std.os.getrandom(std.mem.asBytes(&seed));
break :blk seed;
});
random = prng.random();
// Initiate Cache
var cache = Cache.init(alloc);
// Initiate header and trailer
var trailer: *Node = undefined;
var header: *Node = undefined;
trailer = try makeNode(
&cache,
Item{ .key = MAXSIZE, .value = undefined },
null,
null,
0,
header,
);
header = try makeNode(
&cache,
Item{ .key = MAXSIZE, .value = undefined },
trailer,
null,
0,
null,
);
header = try makeNode(
&cache,
Item{ .key = MAXSIZE, .value = undefined },
trailer,
header,
0,
null,
);
return .{
.stack = Stack.init(alloc),
.alloc = alloc,
.trailer = trailer,
.header = header,
.cache = cache,
};
}
/// De-initialize the map.
pub fn deinit(self: *Self) void {
mutex.lock();
defer mutex.unlock();
self.stack.deinit();
self.cache.deinit();
}
/// Clone the Skiplist, using the given allocator. The operation is O(n*log(n)).
///
/// However, due to that the original list is already sorted,
/// the cost of running this function is incomparably lower than
/// if building a clone on entirely assorted data. The larger the map, the more effective
/// this function is. Cloning a map with 1M entries is ~
/// 5 times faster than building it from the ground.
///
/// Requires `deinit()`.
pub fn cloneWithAllocator(self: *Self, alloc: Allocator) !Self {
var new: Self = try init(alloc);
var self_items = self.items();
while (self_items.next()) |item| {
try new.put(item.key, item.value);
}
return new;
}
/// Clone the Skiplist, using the same allocator. The operation is O(n*logn).
///
/// However, due to that the original list is already sorted,
/// the cost of running this function is incomparably lower than
/// if building a clone on entirely assorted data. The larger the map, the more effective
/// this function is. Cloning a map with 1M entries is ~
/// 5 times faster than building it from the ground.
///
/// Requires `deinit()`.
pub fn clone(self: *Self) !Self {
var new: Self = try init(self.alloc);
var self_items = self.items();
while (self_items.next()) |item| {
try new.put(item.key, item.value);
}
return new;
}
/// Clear the map of all items and clear the cache.
pub fn clearAndFree(self: *Self) !void {
mutex.lock();
defer mutex.unlock();
self.cache.clear();
_ = self.cache.arena.reset(.free_all);
// Re-Initiate the SortedMap's header and trailer
try self.makeHeadAndTail();
try self.addNewLayer();
self.size = 0;
}
/// Clear the map of all items but retain the cache.
/// Useful if your map contracts and expands on new data often.
pub fn clearRetainingCapacity(self: *Self) !void {
mutex.lock();
defer mutex.unlock();
// Reuse all the list
var node: *Node = self.header;
self.cache.reuse(node);
while (node.parent != null) {
node = node.parent.?;
var fringe = node;
while (!eql(fringe.next.?.item.key, MAXSIZE)) {
self.cache.reuse(fringe);
fringe = fringe.next.?;
}
}
// Re-Initiate the SortedMap's header and trailer
try self.makeHeadAndTail();
try self.addNewLayer();
self.size = 0;
}
/// Put a given key-value pair into the map. In the `.set` mode,
/// it will clobber the existing value of an item associated with the key.
pub fn put(self: *Self, key: KEY, value_: VALUE) !void {
mutex.lock();
defer mutex.unlock();
var stack = try self.getLevelStack(key);
if (!keyIsString) {
if (mode == .set and eql(stack.getLast().item.key, key)) {
assert(self.update(key, value_));
return;
}
} else {
if (mode == .set and sEql(u8, stack.getLast().item.key, key)) {
assert(self.update(key, value_));
return;
}
}
for (stack.items[0 .. stack.items.len - 1]) |node| {
if (!eql(node.next.?.item.key, MAXSIZE) and node.parent != null) {
node.next.?.width += 1;
}
}
var node: *Node = stack.pop();
var item: Item = undefined;
item = Item{ .key = key, .value = value_ };
var par: *Node = try self.insertNodeWithAllocation(item, node, null, 1);
while (random.intRangeAtMost(u3, 1, p) == 1) {
if (stack.items.len > 0) {
node = stack.pop();
par = try self.insertNodeWithAllocation(
item,
node,
par,
self.width_(node, key),
);
if (!eql(node.next.?.next.?.item.key, MAXSIZE)) {
node.next.?.next.?.width -|= node.next.?.width;
}
} else {
try self.addNewLayer();
par = try self.insertNodeWithAllocation(
item,
self.header.parent.?,
par,
self.width_(self.header.parent.?, key),
);
}
}
self.size += 1;
}
/// Query the map whether it contains an entry associated with the given key
pub fn contains(self: *Self, key: KEY) bool {
var node = self.header;
while (node.parent != null) {
node = node.parent.?;
while (gTE(key, node.next.?.item.key)) {
node = node.next.?;
}
}
return if (!keyIsString) eql(key, node.item.key) else sEql(u8, key, node.item.key);
}
/// Pop the MAP last item's value or null if the map is empty.
pub fn popOrNull(self: *Self) ?VALUE {
if (self.size == 0) return null;
if (self.fetchRemoveByIndex(@bitCast(self.size))) |real|
return real.value;
return null;
}
/// Pop the MAP last item's value or fail to assert that the map contains at least 1 item.
pub fn pop(self: *Self) VALUE {
assert(self.size > 0);
return self.fetchRemoveByIndex(@bitCast(self.size - 1)).?.value;
}
/// Pop the MAP first item's value or null if the map is empty.
pub fn popFirstOrNull(self: *Self) ?VALUE {
if (self.size == 0) return null;
if (self.fetchRemoveByIndex(@as(i64, 0))) |real|
return real.value;
return null;
}
/// Pop the MAP first item's value or fail to assert that the map contains at least 1 item.
pub fn popFirst(self: *Self) VALUE {
assert(self.size > 0);
return self.fetchRemoveByIndex(@as(i64, 0)).?.value;
}
/// Get the MAP last item's value or null if the map is empty.
pub fn getLastOrNull(self: *Self) ?VALUE {
if (self.size == 0) return null;
return self.groundRight().item.value;
}
/// Get the MAP last item's value or fail to assert that the map contains at least 1 item.
pub fn getLast(self: *Self) VALUE {
assert(self.size > 0);
return self.groundRight().item.value;
}
/// Get the MAP first item's value or null if the map is empty.
pub fn getFirstOrNull(self: *Self) ?VALUE {
if (self.size == 0) return null;
if (self.getItemByIndex(@as(i64, 0))) |real|
return real.value;
return null;
}
/// Get the MAP first item's value or fail to assert that the map contains at least 1 item.
pub fn getFirst(self: *Self) VALUE {
assert(self.size > 0);
return self.groundLeft().item.value;
}
///
/// Remove an entry associated with the given key from the map.
/// Returns false if the MAP does not contain such entry.
/// If duplicates keys are present it will remove starting from the utmost right key.
pub fn remove(self: *Self, key: KEY) bool {
if (self.size == 0) return false;
if (self.fetchRemove(key)) |item| {
_ = item;
return true;
}
return false;
}
/// Remove an entry associated with the given index from the map.
/// Returns false if the MAP does not contain such entry.
/// Takes negative indices akin to Python's list.
pub fn removeByIndex(self: *Self, index: i64) bool {
if (self.size == 0) return false;
if (self.fetchRemoveByIndex(index)) |item| {
_ = item;
return true;
}
return false;
}
/// Remove an entry associated with the given index from the map and return it to the caller.
/// Returns null if the MAP does not contain such entry.
/// Takes negative indices akin to Python's list.
pub fn fetchRemoveByIndex(self: *Self, index: i64) ?Item {
mutex.lock();
defer mutex.unlock();
if (@abs(index) >= self.size) return null;
const index_: u64 = if (index < 0) self.size -| @abs(index) else @abs(index);
var stack: Stack = self.getLevelStackByIndex(index_) catch unreachable;
const item: Item = stack.getLast().*.item;
const key = item.key;
self.removeLoop(key, &stack);
self.size -|= 1;
return item;
}
/// Remove an entry associated with the given keys from the map and return it to the caller.
/// Returns null if the MAP does not contain such entry.
pub fn fetchRemove(self: *Self, key: KEY) ?Item {
mutex.lock();
defer mutex.unlock();
var stack: Stack = self.getLevelStack(key) catch unreachable;
const item: Item = stack.getLast().*.item;
if (!keyIsString) {
if (!eql(item.key, key)) return null;
} else {
if (!sEql(u8, item.key, key)) return null;
}
self.removeLoop(key, &stack);
self.size -|= 1;
return item;
}
/// Remove slice of entries from `start_key` to (but not including) `stop_key`.
///
/// Returns an error if `start_key` > `stop_key` to indicate the issue.
/// Returns an error if one of the keys is missing.
pub fn removeSliceByKey(self: *Self, start_key: KEY, stop_key: KEY) !bool {
mutex.lock();
defer mutex.unlock();
if (self.size == 0) return false;
if (gT(start_key, stop_key)) return SortedMapError.StartKeyIsGreaterThanEndKey;
var s = try self.getLevelStackFirst(start_key);
if (s.items.len == 0) return SortedMapError.MissingStartKey;
s = try s.clone();
defer s.deinit();
var e = if (!EQL(start_key, stop_key)) try self.getLevelStackPrev(stop_key) else try self.getLevelStack(stop_key);
if (e.items.len == 0) return SortedMapError.MissingEndKey;
assert(s.items.len == e.items.len);
var to_delete: u64 = 0;
while (s.items.len > 0) {
var s_node: *Node = s.pop();
var e_node: *Node = e.pop();
var node: *Node = s_node;
if (s_node.prev != null and !EQL(s_node.item.key, MAXSIZE))
self.cache.reuse(s_node); // reuse allocated memory
var width: u64 = node.width;
while (!eql(node, e_node)) {
node = node.next.?;
width += node.width;
if (!EQL(node.item.key, MAXSIZE))
self.cache.reuse(node); // reuse allocated memory for each layer
}
if (node.parent == null) {
to_delete = width;
width = 0;
} else {
width = node.next.?.width + width -| to_delete;
node.next.?.width = width;
}
// this ternary expression is simple and trims redundant levels
if (s_node.prev != null) {
s_node.prev.?.next = e_node.next.?;
e_node.next.?.prev = s_node.prev.?;
} else {
s_node.next = e_node.next.?;
e_node.next.?.prev = s_node;
}
}
self.size -|= to_delete;
return true;
}
/// Remove slice of entries from `start` to (but not including) `stop` indices.
/// Indices can be negative. Behaves akin to Python's list() class.
///
/// Returns InvalidIndex error if the given indices are out of the map's span.
pub fn removeSliceByIndex(self: *Self, start: i64, stop: i64) !bool {
mutex.lock();
defer mutex.unlock();
if (start >= self.size) return false;
const start_: u64 = if (start < 0) self.size -| @abs(start) else @abs(start);
var stop_: u64 = if (stop < 0) self.size -| @abs(stop) else @abs(stop);
if (stop >= self.size)
stop_ = self.size;
stop_ -|= 1; // stop node is not deleted
if (start_ == stop_ or start_ > stop_) return SortedMapError.InvalidIndex;
var s = try self.getLevelStackByIndex(start_);
s = try s.clone();
defer s.deinit();
var e = try self.getLevelStackByIndex(stop_);
assert(s.items.len == e.items.len);
while (s.items.len > 0) {
var s_node: *Node = s.pop();
var e_node: *Node = e.pop();
var node: *Node = s_node;
if (s_node.prev != null and !EQL(s_node.item.key, MAXSIZE))
self.cache.reuse(s_node); // reuse allocated memory
var width: u64 = node.width;
while (!eql(node, e_node)) {
node = node.next.?;
width += node.width;
if (!EQL(node.item.key, MAXSIZE))
self.cache.reuse(node); // reuse allocated memory
}
if (node.parent == null)
width = 0;
if (node.parent != null) {
width = node.next.?.width + width -| (stop_ - start_) -| 1;
node.next.?.width = width;
}
// this ternary expression is simple and trims redundant levels
if (s_node.prev != null) {
s_node.prev.?.next = e_node.next.?;
e_node.next.?.prev = s_node.prev.?;
} else {
s_node.next = e_node.next.?;
e_node.next.?.prev = s_node;
}
}
self.size -|= (stop_ + 1) - start_;
return true;
}
/// Return `Iterator` struct to run the SortedMap backward
/// starting from the right most node. This function is a mere convenience to
/// `iterByKey()` which lets you specify the starting key, and then go
/// forward or backward as you need.
pub fn itemsReversed(self: *Self) Iterator {
const node: *Node = self.groundRight();
return Iterator{ .ctx = self, .gr = node, .rst = node };
}
/// Return `Iterator` struct to run the SortedMap forward
/// starting from the left most node. This function is a mere convenience to
/// `iterByKey()` which lets you specify the starting key, and then go
/// forward or backward as you need.
pub fn items(self: *Self) Iterator {
const node: *Node = self.groundLeft();
return Iterator{ .ctx = self, .gr = node, .rst = node };
}
/// Use `next` to iterate through the SortedMap forward.
/// Use `prev` to iterate through the SortedMap backward.
/// Use `reset` to reset the fringe back to the starting point.
pub const Iterator = struct {
ctx: *Self,
gr: *Node,
rst: *Node,
pub fn next(self: *Iterator) ?Item {
while (!eql(self.gr.item.key, MAXSIZE)) {
const node = self.gr;
self.gr = self.gr.next.?;
return node.item;
}
// TODO: technically it should be self.gr = self.gr.prev.?;
self.gr = self.ctx.groundRight();
return null;
}
pub fn prev(self: *Iterator) ?Item {
while (self.gr.prev != null) {
const node = self.gr;
self.gr = node.prev.?;
return node.item;
}
// one step fow so we can use next() right away
self.gr = self.gr.next.?;
return null;
}
pub fn reset(self: *Iterator) void {
self.gr = self.rst;
}
};
/// Return `Iterator` struct to run the SortedMap forward:`next()` or
/// backward:`prev()` depending on the start_key. Once exhausted,
/// you can run it in the opposite direction. If you want to start over, call `reset()`.
/// Reversing the iteration in the process, before it hits the either end of the map,
/// *has naturally a lag in one node.*
pub fn iterByKey(self: *Self, start_key: KEY) !Iterator {
if (self.getNodePtr(start_key)) |node| {
return Iterator{ .ctx = self, .gr = node, .rst = node };
}
return SortedMapError.MissingStartKey;
}
/// Return `Iterator` struct to run the SortedMap forward:`next()` or
/// backward:`prev()` depending on the `start_idx`. Once exhausted,
/// you can run it in the opposite direction. If you want to start over, call `reset()`.
/// Reversing the iteration in the process, before it hits the either end of the map,
/// *has naturally a lag in one node.*
pub fn iterByIndex(self: *Self, start_idx: i64) !Iterator {
if (self.getNodePtrByIndex(start_idx)) |node| {
return Iterator{ .ctx = self, .gr = node, .rst = node };
}
return SortedMapError.MissingStartKey;
}
/// Return the VALUE of an item associated with the min key,
/// or the VALUE of the very first item in the SortedMap.
///
/// asserts the map's size is > 0
pub fn min(self: *Self) VALUE {
assert(self.size > 0);
return self.groundLeft().item.value;
}
/// Return the VALUE of an item associated with the max key,
/// or the VALUE of the very last item in the SortedMap.
///
/// asserts the map's size is > 0
pub fn max(self: *Self) VALUE {
assert(self.size > 0);
return self.groundRight().item.value;
}
/// Return the VALUE of the median item of the SortedMap.
///
/// The median of the map is calculated as in the following example:\
/// 16 items have the median at index 8(9th item)\
/// 15 items have the median at index 7(8th item)
///
/// asserts the map's size is > 0.
pub fn median(self: *Self) VALUE {
assert(self.size > 0);
const median_ = @divFloor(self.size, 2);
return self.getByIndex(@as(i64, @bitCast(median_))).?;
}
/// Update the item associated with the given key with a new VALUE.
///
/// Returns false if such item wasn't found, but not an error.
pub fn update(self: *Self, key: KEY, new_value: VALUE) bool {
while (self.getNodePtr(key)) |node| {
node.item.value = new_value;
return true;
} else return false;
}
/// Get the VALUE of an item associated with the given key,\
/// or return null if no such item is present in the map.
pub fn get(self: *Self, key: KEY) ?VALUE {
while (self.getItem(key)) |item| {
return item.value;
} else return null;
}
/// Get the Item associated with the given key,\
/// or return null if no such item is present in the map.
pub fn getItem(self: *Self, key: KEY) ?Item {
while (self.getNodePtr(key)) |node| {
return node.item;
} else return null;
}
/// Get a pointer to the Node associated with the given key,\
/// or return null if no such item is present in the map.
pub fn getNodePtr(self: *Self, key: KEY) ?*Node {
var node = self.header;
while (node.parent != null) {
node = node.parent.?;
while (gTE(key, node.next.?.item.key)) {
node = node.next.?;
}
}
if (!keyIsString) {
if (eql(node.item.key, key)) {
return node;
} else return null;
} else {
if (sEql(u8, node.item.key, key)) {
return node;
} else return null;
}
}
/// Set the defined slice from the `start` to (but not including)
/// `stop` node belonging to the map to the given value.
/// Step equal to 1 means take every item in the slice.
///
/// Supports negative indices akin to Python's list() class.
pub fn setSliceByKey(self: *Self, start_key: KEY, stop_key: KEY, step: i64, value: VALUE) !void {
if (step == 0) return SortedMapError.StepIndexIsZero;
var gs = try self.getSliceByKey(start_key, stop_key, step);
gs.setter(value);
}
/// Get the `SliceIterator` of the defined slice from the `start` to
/// (but not including) `stop` node belonging to the map.
/// Step equal to 1 means take every item in the slice.
/// Use `next()` method to run the slice. Does not use allocation.
///
/// Supports negative indices akin to Python's list() class.
/// **TODO:** at the moment `SliceIterator` has no `reset()`. If you need to run the same slice
/// multiple times, call the function so, obtaining the slice is cheap.
pub fn getSliceByKey(self: *Self, start_key: KEY, stop_key: KEY, step: i64) !SliceIterator {
if (step == 0) return SortedMapError.StepIndexIsZero;
while (self.getNodePtr(start_key)) |start_k| {
while (self.getNodePtr(stop_key)) |stop_k| {
const sni = SliceNodeIterator{
.start = start_k,
.end = stop_k,
.step = step,
};
return SliceIterator{ .sni = sni };
}
return SortedMapError.MissingEndKey;
}
return SortedMapError.MissingStartKey;
}
/// Get a pointer to the Node associated with the given index,\
/// or return null if the given index is out of the map's size.
pub fn getNodePtrByIndex(self: *Self, index: i64) ?*Node {
if (@abs(index) >= self.size) return null;
var index_: u64 = if (index < 0) self.size - @abs(index) else @abs(index);
var node = self.header;
index_ += 1;
while (node.parent != null) {
node = node.parent.?;
while (!eql(node.next.?.item.key, MAXSIZE) and index_ >= node.next.?.width) {
index_ -= node.next.?.width;
node = node.next.?;
}
}
return node;
}
/// Set the defined slice from the `start` to (but not including)
/// `stop` indices belonging to the map to the given value.
/// Step equal to 1 means take every item in the slice.
///
/// Supports negative indices akin to Python's list() class.
pub fn setSliceByIndex(self: *Self, start: i64, stop: i64, step: i64, value_: VALUE) !void {
if (step == 0) return SortedMapError.StepIndexIsZero;
const size_: i64 = @bitCast(self.size);
const stop_: i64 = if (stop < 0) size_ + stop else stop;
if (start >= stop_) return SortedMapError.StartIndexIsGreaterThanEndIndex;
var gs = try self.getSliceByIndex(start, stop_, step);
gs.setter(value_);
}
/// Get the `SliceIterator` of the defined slice from the `start` to
/// (but not including) `stop` indices belonging to the map.
/// Step equal to 1 means take every item in the slice.
/// Use `next()` method to run the slice. Does not use allocation.
///
/// Supports negative indices akin to Python's list() class.
/// **TODO:** at the moment `SliceIterator` has no `reset()`. If you need to run the same slice
/// multiple times, call the function so, obtaining the slice is cheap.
pub fn getSliceByIndex(self: *Self, start: i64, stop: i64, step: i64) !SliceIterator {
if (stop < -@as(i64, @bitCast(self.size)) or stop > self.size)
return SortedMapError.InvalidStopIndex;
if (stop < 0)
if (start >= self.size - @abs(stop)) return SortedMapError.StartIndexIsGreaterThanEndIndex;
if (step == 0) return SortedMapError.StepIndexIsZero;
while (self.getNodePtrByIndex(start)) |node| {
const sni = SliceNodeIterator{
.start = node,
.stop = if (stop < 0) self.size - @abs(stop) else @abs(stop),
.step = step,
.fringe = if (start < 0) self.size - @abs(start) else @abs(start),
.step2 = if (step > 0) @as(i64, 0) else step,
};
return SliceIterator{ .sni = sni };
} else return SortedMapError.InvalidIndex;
}
/// Use `next` to run the slice from left to right
pub const SliceIterator = struct {
sni: SliceNodeIterator,
pub fn next(self: *SliceIterator) ?Item {
if (self.sni.stop != 0) {
while (self.sni.next()) |node| {
return node.item;
}
} else {
while (self.sni.next2()) |node| {
return node.item;
}
}
return null;
}
fn setter(self: *SliceIterator, value: VALUE) void {
if (self.sni.stop != 0) {
while (self.sni.next()) |node| {
node.item.value = value;
}
} else {
while (self.sni.next2()) |node| {
node.item.value = value;
}
}
return;
}
};
/// Use `next` to iterate over the node's pointers in the slice
pub const SliceNodeIterator = struct {
start: *Node,
end: *Node = undefined,
stop: u64 = 0,
step: i64,
fringe: u64 = 0,
step2: i64 = 0,
edge: i64 = 0,
pub fn next2(self: *SliceNodeIterator) ?*Node {
while (!eql(self.start, self.end)) {
if (@mod(self.edge, self.step) == 0) {
self.edge += 1;
const node = self.start;
self.start = node.next.?;
return node;
} else {
self.edge += 1;
self.start = self.start.next.?;
continue;
}
}
return null;
}
pub fn next(self: *SliceNodeIterator) ?*Node {
if (self.step > 0) {
while (self.fringe < self.stop) {
if (@mod(self.step2, self.step) == 0) {
self.fringe += 1;
self.step2 += 1;
const node = self.start;
self.start = node.next.?;
return node;
} else {
self.fringe += 1;
self.step2 += 1;
self.start = self.start.next.?;
continue;
}
}
} else {
while (self.fringe > self.stop) {
if (@mod(self.step2, self.step) == 0) {
self.fringe -|= 1;
self.step2 -= 1;
const node = self.start;
self.start = node.prev.?;
return node;
} else {
self.fringe -|= 1;
self.step2 -= 1;
self.start = self.start.prev.?;
continue;
}
}
}
return null;
}
};
/// Update the Item associated with the given index with a new VALUE.
///
/// Supports negative (reverse) indexing.
/// Returns false if such item wasn't found, but not an error.
pub fn updateByIndex(self: *Self, index: i64, new_value: VALUE) bool {
while (self.getNodePtrByIndex(index)) |node| {
node.item.value = new_value;
return true;
} else return false;
}
/// Get the VALUE of the Item associated with the given index,\
/// or return null if no such item is present in the map.
///
/// Supports negative (reverse) indexing.
pub fn getByIndex(self: *Self, index: i64) ?VALUE {
while (self.getItemByIndex(index)) |item| {
return item.value;
} else return null;
}
/// Get the Item associated with the given index,\
/// or return null if no such item is present in the map.
///
/// Supports negative (reverse) indexing.
pub fn getItemByIndex(self: *Self, index: i64) ?Item {
mutex.lock();
defer mutex.unlock();
while (self.getNodePtrByIndex(index)) |node| {
return node.item;
} else return null;
}
/// Return the index of the Item associated with the given key or
/// return `null` if no such Item present in the map.
///
/// In the case of duplicate keys, when the SortedMap works in the `.list` mode,
/// it will return the index of the rightmost Item.
pub fn getItemIndexByKey(self: *Self, key: KEY) ?i64 {
var node: *Node = self.header;
var width: usize = 0;
while (node.parent != null) {
node = node.parent.?;
while (gTE(key, node.next.?.item.key)) {
width += node.next.?.width;
node = node.next.?;
}
}
return if (EQL(key, node.item.key)) @bitCast(width -| 1) else null;
}
};
}
var allocatorT = std.testing.allocator;
const expect = std.testing.expect;
test "SortedMap: simple, iterator" {
var map = try SortedMap(u128, u128, .set).init(allocatorT);
defer map.deinit();
var keys = std.ArrayList(u128).init(allocatorT);
defer keys.deinit();
var prng = std.rand.DefaultPrng.init(0);
const random = prng.random();
var k: u128 = 0;
while (k < 32) : (k += 1) {
try keys.append(k);
}
random.shuffle(u128, keys.items);
for (keys.items) |v| {
try map.put(v, v);
try map.put(v, v + 2);
}
try expect(map.size == 32);
var counter: usize = 0;
var items = try map.iterByKey(map.getItemByIndex(0).?.key);
while (items.next()) |item| : (counter += 1) {
try expect(item.key == item.value - 2);
}
try expect(counter == 32);
items.reset();
counter = 0;
while (items.next()) |item| : (counter += 1) {
try expect(item.key == item.value - 2);
}
try expect(counter == 32);
try map.setSliceByIndex(0, 32, 1, 444);
try expect(map.size == 32);
// because the previous iteration has been exhausted, now iter can go backward
while (items.prev()) |item| {
try expect(item.value == 444);
}
// and now it can go forward again
while (items.next()) |item| {
try expect(item.value == 444);
}
try map.setSliceByIndex(0, 32 / 2, 1, 333);
try map.setSliceByIndex(32 / 2, 32, 1, 555);
// get new iter from the second half
items = try map.iterByIndex(@as(i64, 16));
while (items.next()) |item| {
try expect(item.value == 555);
}
// reset to the starting point
items.reset();
try expect(items.prev().?.value == 555); // this value is idx 16, so still 555!
// move backward, iterating over the first half of the map
while (items.prev()) |item| {
try expect(item.value == 333);
}
// PLEASE UNDERSTAND REVERSING THE ITERATOR IN THE PROCESS
items.reset(); // reset back to the starting key, 16
// Calling prev() or next() before the iteration hits the right or the left end of the map,
// know that the lag of one node occurs.
// Iterator gives you the current node and only then
// switches either to the prev node or to the next if such node exist!
try expect(items.prev().?.key == 16); // 16, the starting key
try expect(items.prev().?.key == 15); // 15 <-
try expect(items.prev().?.key == 14); // 14 <-
try expect(items.next().?.key == 13); // 13 <- lagging
try expect(items.next().?.key == 14); // 14 ->
try expect(items.next().?.key == 15); // 15 ->
try expect(items.prev().?.key == 16); // 16 -> lagging
try expect(items.prev().?.key == 15); // 15 <-
try expect(items.prev().?.key == 14); // 14 <-
// ...
// getSliceByKey and setSliceByKey
var slice = try map.getSliceByKey(1, 14, 3);
while (slice.next()) |item| {
try expect(item.value == 333);
}
try map.setSliceByKey(1, 14, 3, 888);
slice = try map.getSliceByKey(1, 14, 3); // get the new instance of the same slice
while (slice.next()) |item| {
try expect(item.value == 888);
}
}
test "SortedMap: basics" {
var map = try SortedMap(i64, i64, .list).init(allocatorT);
defer map.deinit();
var keys = std.ArrayList(i64).init(allocatorT);
defer keys.deinit();
var prng = std.rand.DefaultPrng.init(0);
const random = prng.random();
var k: i64 = 0;
while (k < 16) : (k += 1) {
try keys.append(k);
}
random.shuffle(i64, keys.items);
random.shuffle(i64, keys.items);
for (keys.items) |v| {
try map.put(v, v);
}
try expect(map.median() == 8);
const step: i64 = 1;
var slice = try map.getSliceByIndex(-12, 16, step);
var start: i64 = 16 - 12;
while (slice.next()) |item| : (start += 1)
try expect(start == item.key);
try expect(map.update(6, 66));
try expect(map.updateByIndex(-1, 1551));
try expect(map.size == k);
try expect(map.trailer.width == 0);
try expect(map.min() == 0);
try expect(map.getFirst() == 0);
try expect(map.getItem(11).?.value == map.get(11).?);
try expect(map.getItemByIndex(11).?.value == map.getByIndex(-5).?);
try expect(map.getItemByIndex(-11).?.value == map.getByIndex(5).?);
try expect(map.max() == 1551);
try expect(map.updateByIndex(-1, 15));
try expect(map.max() == k - 1);
try map.setSliceByIndex(0, 5, 1, 99);
var itemsR = map.itemsReversed();
start = 15;
while (itemsR.prev()) |item| : (start -= 1) {
if (start < 5)
try expect(item.value == @as(i64, 99));
}
try expect(map.remove(26) == false);
try expect(map.remove(6) == (map.size == k - 1));
try expect(map.remove(0) == (map.size == k - 2));
try expect(!map.contains(0));
try expect(map.remove(6) == false);
try expect(map.remove(1) == (map.size == k - 3));
try expect(!map.contains(1));
try expect(map.remove(12) == (map.size == k - 4));
try expect(!map.contains(12));
try expect(map.remove(3) == (map.size == k - 5));
try expect(map.remove(14) == (map.size == k - 6));
try expect(map.getItem(14) == null);
try map.put(6, 6);
try expect(map.contains(6));
try map.put(3, 3);
try expect(map.contains(3));
try map.put(14, 14);
try expect(map.contains(14));
try expect(map.removeByIndex(9) == true);
try expect(map.fetchRemove(9).?.key == 9);
try expect(map.getItemByIndex(9).?.key == map.fetchRemoveByIndex(9).?.key);
try expect(map.getItemByIndex(0).?.key == map.fetchRemoveByIndex(0).?.key);
try expect(map.getItemByIndex(0).?.key == map.fetchRemoveByIndex(0).?.key);
try expect(map.getItemByIndex(0).?.key == map.fetchRemoveByIndex(0).?.key);
try expect(map.getItemByIndex(0).?.key == map.fetchRemoveByIndex(0).?.key);
try expect(map.getItemByIndex(0).?.key == map.fetchRemoveByIndex(0).?.key);
for (keys.items) |v| {
try map.put(v + 50, v + 50);
}
for (keys.items) |v| {
try map.put(v, v);
}
var clone = try map.clone();
defer clone.deinit();
for (keys.items) |v| {
try clone.put(v, v);
}
var clone_size = clone.size;
try expect(true == try clone.removeSliceByIndex(2, 10));
try expect(clone.size == clone_size - 8);
for (keys.items) |v| {
try clone.put(v - 100 * 3, v);
}
clone_size = clone.size;
try expect(true == try clone.removeSliceByIndex(2, 20));
clone_size -|= 18;
try expect(clone.size == clone_size);
try expect(true == try clone.removeSliceByKey(8, 50));
try expect(true == try clone.removeSliceByIndex(-21, @bitCast(clone.size - 10)));
try expect(true == try clone.removeSliceByIndex(-21, -10));
clone_size = clone.size;
_ = clone.popOrNull();
_ = clone.pop();
_ = clone.pop();
_ = clone.popFirstOrNull();
_ = clone.popFirst();
_ = clone.popFirst();
_ = clone.popFirst();
_ = clone.popFirstOrNull();
_ = clone.popFirstOrNull();
_ = clone.popFirstOrNull();
try expect(clone.size == clone_size - 9);
try expect(clone.median() == @as(i64, 63));
try expect(clone.getFirst() == @as(i64, 63));
try expect(clone.getLast() == @as(i64, 63));
try expect(clone.size == 1);
for (keys.items) |v| {
try clone.put(v - 100 * 3, v - 100 * 3);
}
const query: i64 = -299;
try expect(clone.get(query) == clone.getByIndex(clone.getItemIndexByKey(query).?));
try expect(clone.getItemIndexByKey(query - 100) == null);
try expect(clone.getItemIndexByKey(query * -1) == null);
try expect(clone.getItemIndexByKey(query - 1) != null);
try expect(clone.getFirstOrNull().? == @as(i64, -300));
try expect(clone.getLastOrNull().? == @as(i64, 63));
try clone.put(std.math.maxInt(i64) - 1, std.math.maxInt(i64));
try expect(clone.max() == std.math.maxInt(i64));
}
test "SortedMap: floats" {
var map = try SortedMap(f128, f128, .set).init(allocatorT);
defer map.deinit();
var keys = std.ArrayList(f128).init(allocatorT);
defer keys.deinit();
var prng = std.rand.DefaultPrng.init(0);
const random = prng.random();
var k: f128 = 0;
while (k < 16) : (k += 1) {
try keys.append(k);
}
random.shuffle(f128, keys.items);
random.shuffle(f128, keys.items);
for (keys.items) |key| {
try map.put(key, key + 100);
}
try expect(map.getFirst() == map.min());
try expect(map.getLast() == map.max());
try expect(map.median() == @divFloor(k, 2) + 100);
// stop value > map length, rolls down to map length
try expect(true == try map.removeSliceByIndex(@as(i64, 8), @as(i64, 88)));
try expect(map.max() == @divFloor(k - 1, 2) + 100);
try expect(map.median() == @divFloor(k, 4) + 100);
try expect(true == map.remove(@as(f128, 7)));
try expect(true != map.remove(@as(f128, 7)));
try expect(true == map.remove(@as(f128, 6)));
try expect(true == map.remove(@as(f128, 0)));
try expect(true == map.remove(@as(f128, 5)));
try expect(true == map.remove(@as(f128, 1)));
try expect(true == map.remove(@as(f128, 3)));
try expect(true == map.remove(@as(f128, 4)));
try expect(map.size == 1);
try expect((map.median() == map.min()) == (@as(f128, 2 + 100) == map.max()));
try expect(map.removeByIndex(@as(i64, 0)));
try expect(!map.removeByIndex(@as(i64, 0)));
try expect(map.size == 0);
}
test "SortedMap: a string literal as a key" {
var map = try SortedMap([]const u8, u64, .set).init(allocatorT);
defer map.deinit();
const HeLlo = "HeLlo";
const HeLLo = "HeLLo";
const HeLLo2 = "HeLLo";
const hello = "hello";
const hello2 = "hello";
try map.put(HeLLo, 0);
try map.put(HeLlo, 1);
try map.put(hello, 2);
try map.put(hello2, 3);
try expect(map.getFirst() == 0);
try map.put(HeLLo2, 4);
try expect(map.getFirst() == 4);
try map.clearAndFree();
var message = "Zig is a general-purpose programming language and toolchain for maintaining robust, optimal and reusable software";
var old_idx: usize = 0;
var counter: u64 = 0;
for (message, 0..) |char, idx| {
if (char == 32) {
const key = if (message[idx -| 1] == 44) message[old_idx..idx -| 1] else message[old_idx..idx];
try map.put(key, counter);
old_idx = idx + 1;
counter += 1;
}
}
try map.put(message[old_idx..], counter + 1);
try expect(map.get("Zig") == 0);
try expect(map.getItemIndexByKey("Zig") == @as(i64, 0));
try expect(map.contains("Zig"));
try expect(map.removeByIndex(0));
try expect(!map.contains("Zig"));
try expect(sEql(u8, map.getItemByIndex(0).?.key, "a"));
try expect(map.get("a") == 2);
try expect(map.getItemIndexByKey("toolchain") == @as(i64, @bitCast(map.size - 1)));
try expect(try map.removeSliceByIndex(-7, 20)); // will trim the message from the right
try expect(map.size == 6);
try expect(map.max() == 5);
try expect(map.removeByIndex(@bitCast(map.size - 1)));
try expect(map.size == 5);
try expect(map.remove("is"));
try expect(map.size == 4);
try expect(try map.removeSliceByKey("and", "general-purpose"));
try expect(map.removeByIndex(@as(i64, 0)));
try expect(sEql(u8, map.getItemByIndex(0).?.key, "general-purpose"));
try expect(map.getByIndex(@as(i64, 0)) == 3);
try expect(map.size == 1);
}
test "SortedMap: split-remove" {
var map = try SortedMap(usize, usize, .set).init(allocatorT);
defer map.deinit();
for (0..16) |i| {
try map.put(i, i);
}
for (8..16) |i| {
try expect(map.getByIndex(8).? == i % 16);
try expect(map.removeByIndex(8));
}
try expect(map.size == 8);
for (4..8) |i| {
try expect(map.getByIndex(4).? == i % 8);
try expect(map.removeByIndex(4));
}
try expect(map.size == 4);
for (2..4) |i| {
try expect(map.getByIndex(2).? == i % 4);
try expect(map.removeByIndex(2));
}
try expect(map.size == 2);
for (1..2) |i| {
try expect(map.getByIndex(1).? == i % 2);
try expect(map.removeByIndex(1));
}
try expect(map.size == 1);
try expect(map.getByIndex(0) == 0);
try expect(map.removeByIndex(0));
try expect(!map.removeByIndex(0));
try expect(map.size == 0);
}
// The following two tests were adapted from here
// https://github.com/oven-sh/bun/blob/main/src/StaticHashMap.zig#L623
test "Sorted Map: test compare functions on [32]u8 keys" {
const prefix = [_]u8{'0'} ** 8 ++ [_]u8{'1'} ** 23;
const a = prefix ++ [_]u8{0};
const b = prefix ++ [_]u8{1};
try expect(SortedMap([]const u8, void, .set).EQL(&a, &a));
try expect(SortedMap([]const u8, void, .set).EQL(&b, &b));
try expect(SortedMap([]const u8, void, .set).gT(&b, &a));
try expect(!SortedMap([]const u8, void, .set).gT(&a, &b));
try expect(SortedMap([]const u8, void, .set).gT(&[_]u8{'o'} ++ [_]u8{'0'} ** 31, &[_]u8{'i'} ++ [_]u8{'0'} ** 31));
try expect(SortedMap([]const u8, void, .set).gT(&[_]u8{ 'h', 'o' } ++ [_]u8{'0'} ** 30, &[_]u8{ 'h', 'i' } ++ [_]u8{'0'} ** 30));
}
test "SortedMap: put, get, remove [32]u8 keys" {
var arena = std.heap.ArenaAllocator.init(std.heap.page_allocator);
var allocatorA = arena.allocator();
defer arena.deinit();
for (0..128) |seed| {
var keys = std.ArrayList([]const u8).init(allocatorA);
try keys.ensureTotalCapacity(512);
defer keys.deinit();
const T = [32]u8;
var prng = std.rand.DefaultPrng.init(seed);
const random = prng.random();
for (0..512) |_| {
var key: *T = try allocatorA.create(T);
for (0..32) |idx| {
key[idx] = random.intRangeAtMost(u8, 33, 127);
}
try keys.append(key);
}
random.shuffle([]const u8, keys.items);
var map = try SortedMap([]const u8, usize, .list).init(allocatorT);
defer map.deinit();
for (keys.items, 0..) |key, i| try map.put(key, i);
try expect(keys.items.len == map.size);
var itemsIT = map.items();
var key_ = itemsIT.next().?.key;
while (itemsIT.next()) |item| {
try expect(std.mem.order(u8, key_, item.key).compare(.lte));
key_ = item.key;
}
for (keys.items, 0..) |key, i| try expect(i == map.get(key).?);
for (keys.items) |key| try expect(map.remove(key));
}
}
|
0 | repos | repos/wired/build-assets.sh | #!/usr/bin/env bash
w4 png2src --template assets/assets-template --zig assets/tiles.png -o assets/tiles.zig
zig run map2src.zig -- assets/maps/map.zig assets/maps/map.json
|
0 | repos | repos/wired/map2src.zig | const std = @import("std");
const PropertyType = enum { bool, int };
const Property = struct {
name: []const u8 = &.{},
type: PropertyType = .bool,
value: union(PropertyType) { bool: bool, int: i64 },
};
const Point = struct {
x: f64 = 0,
y: f64 = 0,
};
const Object = struct {
height: f64 = 0,
id: u64 = 0,
gid: u64 = 0,
name: []const u8,
point: bool = false,
polyline: []Point = &.{},
properties: []Property = &.{},
rotation: f64 = 0,
type: enum { wire, source, door, spawn, focus, coin },
visible: bool = true,
width: f64 = 0,
x: f64 = 0,
y: f64 = 0,
};
const Layer = struct {
data: []u64 = &.{},
objects: []Object = &.{},
height: u64 = 0,
id: u64,
name: []const u8,
draworder: enum { topdown, none } = .none,
opacity: u64,
type: enum { tilelayer, objectgroup },
visible: bool,
width: u64 = 0,
x: i64,
y: i64,
};
const MapType = struct {
compressionlevel: i64 = -1,
editorsettings: struct { chunksize: struct { height: usize = 0, width: usize = 0 } = .{} } = .{},
height: u64 = 0,
infinite: bool = false,
layers: []Layer,
nextlayerid: u64 = 0,
nextobjectid: u64 = 0,
orientation: enum { orthogonal } = .orthogonal,
renderorder: enum { @"right-down" } = .@"right-down",
tiledversion: []const u8 = "",
tileheight: u64 = 0,
tilesets: []struct { firstgid: u64, source: []const u8 },
tilewidth: u64 = 0,
type: enum { map } = .map,
version: []const u8 = "",
width: u64 = 0,
};
const KB = 1024;
var heap: [256 * KB]u8 = undefined;
var fba = std.heap.FixedBufferAllocator.init(&heap);
var alloc = fba.allocator();
var verbose = true;
pub fn main() anyerror!void {
do() catch |e| switch (e) {
error.NoOutputName => showHelp("No output filename supplied"),
else => return e,
};
}
pub fn showHelp(msg: []const u8) void {
std.log.info("{s}\n map2src <output> input1...", .{msg});
}
pub fn do() !void {
var argsIter = std.process.args();
const cwd = std.fs.cwd();
const progName = (try argsIter.next(alloc)) orelse "";
defer alloc.free(progName);
if (verbose) std.log.info("{s}", .{progName});
const outputName = (try argsIter.next(alloc)) orelse return error.NoOutputName;
defer alloc.free(outputName);
var output = try cwd.createFile(outputName, .{});
defer output.close();
while (try argsIter.next(alloc)) |arg| {
defer alloc.free(arg);
if (verbose) std.log.info("{s}", .{arg});
var filebuffer: [64 * KB]u8 = undefined;
var filecontents = try cwd.readFile(arg, &filebuffer);
@setEvalBranchQuota(10000);
var tokenstream = std.json.TokenStream.init(filecontents);
const options = std.json.ParseOptions{ .allocator = fba.allocator() };
const map = try std.json.parse(MapType, &tokenstream, options);
defer std.json.parseFree(MapType, map, options);
var outlist = std.ArrayList(u8).init(alloc);
defer outlist.deinit();
try outlist.appendSlice("const std = @import(\"std\");\n");
try outlist.appendSlice("const Vec2 = std.meta.Vector(2,i32);\n");
try outlist.appendSlice("const AABB = struct {pos: Vec2, size: Vec2};\n");
try outlist.appendSlice("const Wire = struct { p1: Vec2, p2: Vec2, a1: bool, a2: bool, divisions: u8 };\n");
var outbuffer: [16 * KB]u8 = undefined;
for (map.layers) |layer| {
switch (layer.type) {
.tilelayer => {
var outcontent = try std.fmt.bufPrint(
&outbuffer,
"pub const {2s}_size: Vec2 = Vec2{{ {}, {} }};\npub const {s}: [{}]u8 = .{any};\n",
.{ layer.width, layer.height, layer.name, layer.data.len, layer.data },
);
_ = try outlist.appendSlice(outcontent);
},
.objectgroup => {
var wirelist = std.ArrayList(Object).init(alloc);
defer wirelist.deinit();
var doorlist = std.ArrayList(Object).init(alloc);
defer doorlist.deinit();
var coinlist = std.ArrayList(Object).init(alloc);
defer coinlist.deinit();
var sourcelist = std.ArrayList(Object).init(alloc);
defer sourcelist.deinit();
var focilist = std.ArrayList(Object).init(alloc);
defer focilist.deinit();
for (layer.objects) |obj| {
switch (obj.type) {
.wire => try wirelist.append(obj),
.door => try doorlist.append(obj),
.coin => try coinlist.append(obj),
.source => try sourcelist.append(obj),
.focus => try focilist.append(obj),
.spawn => try appendSpawn(&outlist, obj),
}
}
try appendWires(&outlist, wirelist);
try appendDoors(&outlist, doorlist);
try appendCoins(&outlist, coinlist);
try appendSources(&outlist, sourcelist);
try appendFoci(&outlist, focilist);
},
}
}
if (verbose) std.log.info("{s}", .{outlist.items});
_ = try output.writeAll(outlist.items);
}
}
pub fn length(vec: std.meta.Vector(2, i64)) i64 {
var squared = vec * vec;
return @as(i64, @intCast(std.math.sqrt(@as(u64, @intCast(@reduce(.Add, squared))))));
}
pub fn appendWires(outlist: *std.ArrayList(u8), wirelist: std.ArrayList(Object)) !void {
var outbuffer: [4 * KB]u8 = undefined;
var outcontent = try std.fmt.bufPrint(&outbuffer, "pub const wire: [{}]Wire = [_]Wire{{", .{wirelist.items.len});
try outlist.appendSlice(outcontent);
for (wirelist.items) |obj| {
var a1 = true;
var a2 = true;
var p1: std.meta.Vector(2, i64) = .{ 0, 0 };
var p2: std.meta.Vector(2, i64) = .{ 0, 0 };
var divisions: ?i64 = null;
for (obj.properties) |p| {
if (std.mem.eql(u8, p.name, "anchor1")) a1 = p.value.bool;
if (std.mem.eql(u8, p.name, "anchor2")) a2 = p.value.bool;
if (std.mem.eql(u8, p.name, "divisions")) divisions = p.value.int;
}
for (obj.polyline, 0..) |point, i| {
switch (i) {
0 => p1 = .{ @as(i64, @intFromFloat(obj.x + point.x)), @as(i64, @intFromFloat(obj.y + point.y)) },
1 => p2 = .{ @as(i64, @intFromFloat(obj.x + point.x)), @as(i64, @intFromFloat(obj.y + point.y)) },
else => return error.TooManyPoints,
}
}
divisions = divisions orelse std.math.max(2, @divTrunc(length(p2 - p1), 6));
var of = try std.fmt.bufPrint(
&outbuffer,
".{{ .a1 = {}, .a2 = {}, .divisions = {}, .p1 = Vec2{{ {}, {} }}, .p2 = Vec2{{ {}, {} }} }}, ",
.{ a1, a2, divisions, p1[0], p1[1], p2[0], p2[1] },
);
try outlist.appendSlice(of);
}
try outlist.appendSlice("};\n");
}
pub fn appendDoors(outlist: *std.ArrayList(u8), doorlist: std.ArrayList(Object)) !void {
var outbuffer: [4 * KB]u8 = undefined;
var outcontent = try std.fmt.bufPrint(&outbuffer, "pub const doors: [{}]Vec2 = [_]Vec2{{", .{doorlist.items.len});
try outlist.appendSlice(outcontent);
for (doorlist.items) |obj| {
var doorf = try std.fmt.bufPrint(&outbuffer, "Vec2{{ {}, {} }},", .{ @as(i32, @intFromFloat(@divTrunc(obj.x, 8))), @as(i32, @intFromFloat(@divTrunc(obj.y, 8))) });
try outlist.appendSlice(doorf);
}
try outlist.appendSlice("};\n");
}
pub fn appendSources(outlist: *std.ArrayList(u8), sourcelist: std.ArrayList(Object)) !void {
var outbuffer: [4 * KB]u8 = undefined;
var outcontent = try std.fmt.bufPrint(&outbuffer, "pub const sources: [{}]Vec2 = [_]Vec2{{", .{sourcelist.items.len});
try outlist.appendSlice(outcontent);
for (sourcelist.items) |obj| {
var sourcef = try std.fmt.bufPrint(&outbuffer, "Vec2{{ {}, {} }},", .{ @as(i32, @intFromFloat(@divTrunc(obj.x, 8))), @as(i32, @intFromFloat(@divTrunc(obj.y, 8))) });
try outlist.appendSlice(sourcef);
}
try outlist.appendSlice("};\n");
}
pub fn appendCoins(outlist: *std.ArrayList(u8), coinlist: std.ArrayList(Object)) !void {
var outbuffer: [4 * KB]u8 = undefined;
var outcontent = try std.fmt.bufPrint(&outbuffer, "pub const coins: [{}]Vec2 = [_]Vec2{{", .{coinlist.items.len});
try outlist.appendSlice(outcontent);
for (coinlist.items) |obj| {
var sourcef = try std.fmt.bufPrint(&outbuffer, "Vec2{{ {}, {} }},", .{ @as(i32, @intFromFloat(@divTrunc(obj.x, 8))), @as(i32, @intFromFloat(@divTrunc(obj.y - 8, 8))) });
try outlist.appendSlice(sourcef);
}
try outlist.appendSlice("};\n");
}
pub fn appendFoci(outlist: *std.ArrayList(u8), focilist: std.ArrayList(Object)) !void {
var outbuffer: [4 * KB]u8 = undefined;
var outcontent = try std.fmt.bufPrint(&outbuffer, "pub const focus: [{}]AABB = [_]AABB{{", .{focilist.items.len});
try outlist.appendSlice(outcontent);
for (focilist.items) |obj| {
var sourcef = try std.fmt.bufPrint(
&outbuffer,
"AABB{{ .pos = Vec2{{ {}, {} }}, .size = Vec2{{ {}, {} }} }}",
.{
@as(i32, @intFromFloat(@divTrunc(obj.x, 8))),
@as(i32, @intFromFloat(@divTrunc(obj.y, 8))),
@as(i32, @intFromFloat(@divTrunc(obj.width, 8))),
@as(i32, @intFromFloat(@divTrunc(obj.height, 8))),
},
);
try outlist.appendSlice(sourcef);
}
try outlist.appendSlice("};\n");
}
pub fn appendSpawn(outlist: *std.ArrayList(u8), spawn: Object) !void {
var outbuffer: [4 * KB]u8 = undefined;
var outcontent = try std.fmt.bufPrint(
&outbuffer,
"pub const spawn: Vec2 = Vec2{{ {}, {} }};\n",
.{
@as(i32, @intFromFloat(@divTrunc(spawn.x, 8))),
@as(i32, @intFromFloat(@divTrunc(spawn.y, 8))),
},
);
try outlist.appendSlice(outcontent);
}
|
0 | repos | repos/wired/wapm.toml | [package]
name = "desttinghim/wired"
version = "0.2.0"
description = "A puzzle platformer game with wire physics."
readme = "README.md"
repository = "https://github.com/desttinghim/wired"
license = "ISC"
[[module]]
name = "wired"
source = "wired.wasm"
abi = "wasm4"
interfaces = { wasm4 = "0.0.1" }
[[command]]
runner = "[email protected]"
name = "play"
module = "wired"
|
0 | repos | repos/wired/changelog.md | # Changelog
## Unreleased
|
0 | repos | repos/wired/README.md | # Wired
A puzzle platformer with wires.
## Controls
- Left/Right: Move left and right
- Up/Down: Look at items above and below
- X: Jump
- Z: Select
## Dependencies
- `zig` to compile the code
- `wasm-opt` to optimize the generated wasm file for release. It is a part of `binaryen`
- `wasm4` to run the generated cart
## Building
``` shellsession
git clone --recursive
zig build # makes a debug build
w4 run zig-out/lib/cart.wasm
zig build opt -Drelease-small # optimize cart size for release
```
|
0 | repos | repos/wired/build.zig | const std = @import("std");
const LDtkImport = @import("tools/LDtkImport.zig");
pub fn build(b: *std.build.Builder) !void {
const optimize = b.standardOptimizeOption(.{});
const assets = b.addModule("assets", .{
.source_file = .{ .path = "assets/assets.zig" },
});
const ldtk = LDtkImport.create(b, .{
.source_path = .{ .path = "assets/maps/wired.ldtk" },
.output_name = "mapldtk",
});
const data_step = b.addOptions();
data_step.addOptionFileSource("path", .{ .generated = &ldtk.world_data });
const world_data = data_step.createModule();
const lib = b.addSharedLibrary(.{
.name = "cart",
.root_source_file = .{ .path = "src/main.zig" },
.optimize = optimize,
.target = .{ .cpu_arch = .wasm32, .os_tag = .freestanding },
});
lib.step.dependOn(&data_step.step);
lib.addModule("world_data", world_data);
lib.addModule("assets", assets);
lib.import_memory = true;
lib.initial_memory = 65536;
lib.max_memory = 65536;
lib.stack_size = 24752;
// Workaround https://github.com/ziglang/zig/issues/2910, preventing
// functions from compiler_rt getting incorrectly marked as exported, which
// prevents them from being removed even if unused.
lib.export_symbol_names = &[_][]const u8{ "start", "update" };
b.installArtifact(lib);
const prefix = b.getInstallPath(.lib, "");
const opt = b.addSystemCommand(&[_][]const u8{
"wasm-opt",
"-Oz",
"--strip-debug",
"--strip-producers",
"--zero-filled-memory",
});
opt.addArtifactArg(lib);
const optout = try std.fs.path.join(b.allocator, &.{ prefix, "opt.wasm" });
defer b.allocator.free(optout);
opt.addArgs(&.{ "--output", optout });
const opt_step = b.step("opt", "Run wasm-opt on cart.wasm, producing opt.wasm");
opt_step.dependOn(&lib.step);
opt_step.dependOn(&opt.step);
}
|
0 | repos | repos/wired/flake.nix | {
description = "A very basic flake";
inputs = {
flake-utils.url = "github:numtide/flake-utils";
zig.url = "github:mitchellh/zig-overlay";
unstable.url = "nixpkgs/nixos-unstable";
};
outputs = { self, nixpkgs, zig, flake-utils, unstable }:
flake-utils.lib.eachDefaultSystem (system:
let
pkgs = nixpkgs.legacyPackages.${system};
upkgs = unstable.legacyPackages.${system};
in
{
# nix develop
devShells.default = pkgs.mkShell {
buildInputs = [
zig.packages.${system}.master
pkgs.butler
pkgs.binaryen
pkgs.tiled
pkgs.libresprite
upkgs.ldtk
];
};
});
}
|
0 | repos | repos/wired/push.sh | #!/usr/bin/env bash
butler push bundle/windows/ desttinghim/wired:windows --userversion $1
butler push bundle/linux/ desttinghim/wired:linux --userversion $1
butler push bundle/mac/ desttinghim/wired:mac --userversion $1
butler push bundle/html/ desttinghim/wired:html --userversion $1
butler push bundle/cart/ desttinghim/wired:cart --userversion $1
|
0 | repos | repos/wired/flake.lock | {
"nodes": {
"flake-utils": {
"locked": {
"lastModified": 1659877975,
"narHash": "sha256-zllb8aq3YO3h8B/U0/J1WBgAL8EX5yWf5pMj3G0NAmc=",
"owner": "numtide",
"repo": "flake-utils",
"rev": "c0e246b9b83f637f4681389ecabcb2681b4f3af0",
"type": "github"
},
"original": {
"owner": "numtide",
"repo": "flake-utils",
"type": "github"
}
},
"flake-utils_2": {
"locked": {
"lastModified": 1629481132,
"narHash": "sha256-JHgasjPR0/J1J3DRm4KxM4zTyAj4IOJY8vIl75v/kPI=",
"owner": "numtide",
"repo": "flake-utils",
"rev": "997f7efcb746a9c140ce1f13c72263189225f482",
"type": "github"
},
"original": {
"owner": "numtide",
"repo": "flake-utils",
"type": "github"
}
},
"nixpkgs": {
"locked": {
"lastModified": 1660137652,
"narHash": "sha256-L92gcG6Ya4bqjJmStl/HTENhc0PR9lmVgTmeVpk13Os=",
"owner": "NixOS",
"repo": "nixpkgs",
"rev": "a7f89ddd6313ef88fc9c6534ac2511ba9da85fdb",
"type": "github"
},
"original": {
"id": "nixpkgs",
"type": "indirect"
}
},
"nixpkgs_2": {
"locked": {
"lastModified": 1631288242,
"narHash": "sha256-sXm4KiKs7qSIf5oTAmrlsEvBW193sFj+tKYVirBaXz0=",
"owner": "NixOS",
"repo": "nixpkgs",
"rev": "0e24c87754430cb6ad2f8c8c8021b29834a8845e",
"type": "github"
},
"original": {
"owner": "NixOS",
"ref": "nixpkgs-unstable",
"repo": "nixpkgs",
"type": "github"
}
},
"root": {
"inputs": {
"flake-utils": "flake-utils",
"nixpkgs": "nixpkgs",
"unstable": "unstable",
"zig": "zig"
}
},
"unstable": {
"locked": {
"lastModified": 1660071133,
"narHash": "sha256-XX6T9wcvEZIVWY4TO5O1d2MgFyFrF2v4TpCFs7fjdn8=",
"owner": "NixOS",
"repo": "nixpkgs",
"rev": "36cc29d837e7232e3176e4651e8e117a6f231793",
"type": "github"
},
"original": {
"id": "nixpkgs",
"ref": "nixos-unstable",
"type": "indirect"
}
},
"zig": {
"inputs": {
"flake-utils": "flake-utils_2",
"nixpkgs": "nixpkgs_2"
},
"locked": {
"lastModified": 1661317012,
"narHash": "sha256-3Lm//qoKwWj9p/gdCaLSASB9kvBw1vfC9BBYUvhVbWU=",
"owner": "mitchellh",
"repo": "zig-overlay",
"rev": "252c13ba498106f37054ad2c4db8e261f569a81e",
"type": "github"
},
"original": {
"owner": "mitchellh",
"repo": "zig-overlay",
"type": "github"
}
}
},
"root": "root",
"version": 7
}
|
0 | repos | repos/wired/bundle.sh | #!/usr/bin/env bash
zig build opt -Drelease-small
mkdir -p bundle/html
mkdir -p bundle/linux
mkdir -p bundle/windows
mkdir -p bundle/mac
mkdir -p bundle/cart
npx wasm4 bundle --html bundle/html/index.html --linux bundle/linux/wired --windows bundle/windows/wired.exe --mac bundle/mac/wired zig-out/lib/opt.wasm
cp zig-out/lib/opt.wasm bundle/cart/cart.wasm
|
0 | repos/wired | repos/wired/assets/Wired.tsx | <?xml version="1.0" encoding="UTF-8"?>
<tileset version="1.5" tiledversion="1.7.2" name="Wired" tilewidth="16" tileheight="16" tilecount="64" columns="8">
<grid orientation="orthogonal" width="8" height="8"/>
<image source="tiles.png" width="128" height="128"/>
</tileset>
|
0 | repos/wired | repos/wired/assets/tiles.zig | // tiles
pub const tiles_width = 128;
pub const tiles_height = 64;
pub const tiles_flags = 1; // BLIT_2BPP
pub const tiles = [2048]u8{ 0x00, 0x00, 0x15, 0x54, 0x40, 0x01, 0x55, 0x55, 0x05, 0x50, 0x01, 0x40, 0x01, 0x40, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x01, 0x40, 0x00, 0x00, 0x00, 0x00, 0x59, 0x65, 0x40, 0x01, 0x50, 0x05, 0x1a, 0xa4, 0x06, 0x90, 0x01, 0x40, 0x41, 0x41, 0x01, 0x40, 0x01, 0x40, 0x01, 0x40, 0x01, 0x40, 0x01, 0x40, 0x01, 0x40, 0x41, 0x41, 0x01, 0x40, 0x00, 0x00, 0x59, 0x65, 0x40, 0x01, 0x44, 0x11, 0x69, 0x69, 0x19, 0xa4, 0x01, 0x40, 0x11, 0x44, 0x01, 0x40, 0x01, 0x40, 0x01, 0x40, 0x01, 0x40, 0x01, 0x40, 0x01, 0x40, 0x15, 0x54, 0x01, 0x40, 0x00, 0x00, 0x59, 0x65, 0x40, 0x01, 0x41, 0x41, 0x6a, 0x69, 0x19, 0xa4, 0x01, 0x40, 0x05, 0x50, 0x05, 0x50, 0x05, 0x50, 0x15, 0x54, 0x05, 0x50, 0x05, 0x50, 0x15, 0x54, 0x05, 0x50, 0x05, 0x55, 0x00, 0x00, 0x59, 0x65, 0x40, 0x11, 0x41, 0x41, 0x6a, 0x69, 0x19, 0xa4, 0x01, 0x40, 0x05, 0x50, 0x15, 0x54, 0x15, 0x54, 0x45, 0x51, 0x15, 0x54, 0x05, 0x50, 0x45, 0x51, 0x05, 0x54, 0x05, 0x50, 0x00, 0x00, 0x55, 0x55, 0x40, 0x01, 0x44, 0x11, 0x69, 0x69, 0x19, 0xa4, 0x01, 0x40, 0x05, 0x50, 0x15, 0x54, 0x45, 0x51, 0x05, 0x50, 0x45, 0x51, 0x05, 0x50, 0x05, 0x54, 0x04, 0x04, 0x05, 0x54, 0x00, 0x00, 0x59, 0x65, 0x40, 0x01, 0x50, 0x05, 0x1a, 0xa4, 0x06, 0x90, 0x01, 0x40, 0x04, 0x10, 0x04, 0x10, 0x01, 0x40, 0x01, 0x40, 0x01, 0x50, 0x04, 0x10, 0x04, 0x04, 0x04, 0x00, 0x01, 0x01, 0x00, 0x00, 0x15, 0x54, 0x40, 0x01, 0x55, 0x55, 0x05, 0x50, 0x01, 0x40, 0x01, 0x40, 0x04, 0x10, 0x04, 0x10, 0x00, 0x40, 0x01, 0x40, 0x01, 0x00, 0x04, 0x10, 0x04, 0x00, 0x00, 0x00, 0x00, 0x40, 0x02, 0x80, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0x80, 0x02, 0x80, 0x02, 0x80, 0x02, 0x80, 0x02, 0x80, 0x02, 0x80, 0x02, 0x80, 0x02, 0x80, 0x02, 0x80, 0x02, 0x80, 0x00, 0x00, 0x00, 0x00, 0x02, 0x80, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x0a, 0xa0, 0x0a, 0xa0, 0x0a, 0xa0, 0x02, 0x80, 0x02, 0x80, 0x02, 0x88, 0x02, 0x80, 0x22, 0x80, 0x02, 0x80, 0x02, 0x80, 0x02, 0x80, 0x02, 0x80, 0x0a, 0xa0, 0x0a, 0xa0, 0x0a, 0xa0, 0x08, 0x20, 0x0a, 0xa0, 0x29, 0x68, 0x0a, 0x60, 0x0a, 0xa0, 0x00, 0x00, 0x02, 0x88, 0x00, 0x00, 0x22, 0x80, 0x08, 0x20, 0x0a, 0xa0, 0x08, 0x20, 0x0a, 0xa0, 0x0a, 0xa0, 0xaa, 0x80, 0x02, 0xaa, 0x0a, 0xa0, 0xaa, 0x6a, 0x29, 0x68, 0xa9, 0x6a, 0x0a, 0xa0, 0xaa, 0xa0, 0xa2, 0xa0, 0x0a, 0xaa, 0x0a, 0x8a, 0x20, 0x08, 0x2a, 0xa8, 0xa0, 0x0a, 0xaa, 0xaa, 0x0a, 0xa0, 0xaa, 0x80, 0x02, 0xaa, 0x0a, 0xa0, 0xa9, 0x5a, 0x2a, 0xa8, 0xa6, 0x9a, 0x2a, 0xa8, 0xaa, 0xa0, 0xa2, 0xa0, 0x0a, 0xaa, 0x0a, 0x8a, 0x20, 0x08, 0x2a, 0xa8, 0xa0, 0x0a, 0xaa, 0xaa, 0x08, 0x20, 0x0a, 0xa0, 0x0a, 0xa0, 0x0a, 0xa0, 0x0a, 0x60, 0x29, 0x68, 0x0a, 0xa0, 0x2a, 0xa8, 0x02, 0x88, 0x02, 0x80, 0x22, 0x80, 0x02, 0x80, 0x08, 0x20, 0x0a, 0xa0, 0x08, 0x20, 0x0a, 0xa0, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0x80, 0x0a, 0xa0, 0x0a, 0xa0, 0x0a, 0xa0, 0x2a, 0xa8, 0x02, 0x88, 0x02, 0x80, 0x22, 0x80, 0x02, 0x80, 0x02, 0x80, 0x02, 0x80, 0x02, 0x80, 0x02, 0x80, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0x80, 0x00, 0x00, 0x02, 0x80, 0x00, 0x00, 0x02, 0x80, 0x02, 0x80, 0x02, 0x80, 0x02, 0x80, 0x02, 0x80, 0x02, 0x80, 0x02, 0x80, 0x00, 0x00, 0x00, 0x00, 0x69, 0x69, 0x15, 0x55, 0x55, 0x55, 0x55, 0x54, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xaa, 0xaa, 0x41, 0x00, 0x00, 0x00, 0x00, 0x41, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xaa, 0xaa, 0x41, 0x55, 0x55, 0x55, 0x55, 0x41, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x6a, 0xa9, 0x14, 0x00, 0x00, 0x00, 0x00, 0x14, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x6a, 0xa9, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xaa, 0xaa, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xaa, 0xaa, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x69, 0x69, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0x80, 0x02, 0x80, 0x00, 0x00, 0x02, 0x80, 0x00, 0x00, 0x02, 0x80, 0x00, 0x00, 0x02, 0x80, 0x00, 0x00, 0x02, 0x80, 0x00, 0x00, 0x02, 0x80, 0x00, 0x00, 0x02, 0x80, 0x00, 0x00, 0x00, 0x00, 0x02, 0x80, 0x02, 0x80, 0x00, 0x00, 0x02, 0x80, 0x00, 0x00, 0x02, 0x80, 0x00, 0x00, 0x02, 0x80, 0x00, 0x00, 0x02, 0x80, 0x00, 0x00, 0x02, 0x80, 0x00, 0x00, 0x02, 0x80, 0x00, 0x00, 0x00, 0x00, 0x02, 0x80, 0x02, 0x80, 0x02, 0x80, 0x02, 0x80, 0x02, 0x80, 0x02, 0x80, 0x00, 0x00, 0x02, 0x80, 0x02, 0x80, 0x02, 0x80, 0x00, 0x00, 0x02, 0x80, 0x00, 0x00, 0x02, 0x80, 0x00, 0x00, 0x02, 0x80, 0xaa, 0xaa, 0x0a, 0xa0, 0xaa, 0xa0, 0xaa, 0x80, 0x0a, 0xaa, 0x02, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0x0a, 0xa0, 0x02, 0x80, 0xaa, 0x00, 0xaa, 0x80, 0x00, 0xaa, 0x02, 0xaa, 0xaa, 0xaa, 0x0a, 0xa0, 0xaa, 0xaa, 0x0a, 0xa0, 0xaa, 0xa0, 0xaa, 0x00, 0x0a, 0xaa, 0x00, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0x0a, 0xa0, 0x02, 0x80, 0xaa, 0x80, 0xaa, 0x80, 0x02, 0xaa, 0x02, 0xaa, 0xaa, 0xaa, 0x0a, 0xa0, 0x02, 0x80, 0x02, 0x80, 0x02, 0x80, 0x00, 0x00, 0x02, 0x80, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0x80, 0x02, 0x80, 0x02, 0x80, 0x02, 0x80, 0x02, 0x80, 0x02, 0x80, 0x02, 0x80, 0x02, 0x80, 0x02, 0x80, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0x80, 0x02, 0x80, 0x02, 0x80, 0x02, 0x80, 0x02, 0x80, 0x02, 0x80, 0x02, 0x80, 0x00, 0x00, 0x02, 0x80, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0x80, 0x02, 0x80, 0x02, 0x80, 0x02, 0x80, 0x02, 0x80, 0x02, 0x80, 0x02, 0x80, 0x00, 0x00, 0x15, 0x54, 0x44, 0x01, 0x55, 0x54, 0x00, 0x01, 0x15, 0x55, 0x44, 0x00, 0x55, 0x55, 0x00, 0x00, 0x15, 0x54, 0x40, 0x01, 0x55, 0x54, 0x00, 0x01, 0x15, 0x55, 0x40, 0x00, 0x55, 0x55, 0x00, 0x00, 0x44, 0x05, 0x40, 0x01, 0x14, 0x05, 0x00, 0x05, 0x55, 0x10, 0x40, 0x00, 0x14, 0x04, 0x00, 0x00, 0x54, 0x05, 0x50, 0x05, 0x15, 0x11, 0x00, 0x05, 0x54, 0x01, 0x40, 0x00, 0x10, 0x11, 0x00, 0x00, 0x40, 0x05, 0x50, 0x05, 0x00, 0x05, 0x00, 0x05, 0x40, 0x00, 0x50, 0x00, 0x00, 0x00, 0x00, 0x00, 0x40, 0x11, 0x40, 0x11, 0x00, 0x01, 0x00, 0x05, 0x40, 0x10, 0x50, 0x00, 0x00, 0x00, 0x00, 0x00, 0x40, 0x41, 0x50, 0x01, 0x00, 0x41, 0x00, 0x41, 0x44, 0x04, 0x50, 0x00, 0x04, 0x00, 0x00, 0x00, 0x40, 0x01, 0x40, 0x01, 0x04, 0x05, 0x00, 0x01, 0x40, 0x00, 0x40, 0x00, 0x04, 0x00, 0x00, 0x00, 0x50, 0x01, 0x40, 0x41, 0x10, 0x01, 0x10, 0x01, 0x40, 0x00, 0x40, 0x00, 0x00, 0x00, 0x01, 0x00, 0x40, 0x01, 0x40, 0x01, 0x00, 0x01, 0x00, 0x41, 0x40, 0x00, 0x40, 0x00, 0x00, 0x00, 0x00, 0x00, 0x40, 0x01, 0x40, 0x01, 0x00, 0x01, 0x00, 0x01, 0x40, 0x00, 0x40, 0x00, 0x00, 0x10, 0x00, 0x00, 0x51, 0x05, 0x51, 0x05, 0x00, 0x41, 0x00, 0x05, 0x50, 0x00, 0x40, 0x00, 0x00, 0x00, 0x00, 0x00, 0x50, 0x11, 0x51, 0x05, 0x11, 0x15, 0x11, 0x15, 0x41, 0x04, 0x51, 0x01, 0x04, 0x04, 0x14, 0x11, 0x50, 0x01, 0x50, 0x01, 0x00, 0x05, 0x00, 0x05, 0x50, 0x00, 0x50, 0x00, 0x00, 0x00, 0x00, 0x00, 0x15, 0x54, 0x15, 0x54, 0x55, 0x54, 0x55, 0x54, 0x15, 0x55, 0x15, 0x55, 0x55, 0x55, 0x55, 0x55, 0x40, 0x01, 0x40, 0x01, 0x00, 0x01, 0x00, 0x01, 0x40, 0x00, 0x50, 0x00, 0x00, 0x00, 0x00, 0x00 };
|
0 | repos/wired | repos/wired/assets/assets.zig | pub usingnamespace @import("tiles.zig");
|
0 | repos/wired/assets | repos/wired/assets/maps/map.zig | const std = @import("std");
const Vec2 = std.meta.Vector(2, i32);
const AABB = struct { pos: Vec2, size: Vec2 };
const Wire = struct { p1: Vec2, p2: Vec2, a1: bool, a2: bool, divisions: u8 };
pub const solid_size: Vec2 = Vec2{ 60, 60 };
pub const solid: [3600]u8 = .{ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0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, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 37, 0, 0, 39, 0, 0, 0, 0, 0, 0, 0, 0, 20, 0, 0, 20, 0, 0, 0, 0, 37, 39, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 53, 55, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 53, 54, 54, 54, 52, 0, 0, 0, 0, 0, 50, 19, 34, 0, 0, 51, 0, 0, 0, 0, 37, 39, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 3, 0, 0, 0, 0, 37, 0, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 23, 0, 0, 0, 50, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 39, 0, 0, 0, 0, 53, 0, 54, 54, 54, 54, 54, 0, 0, 0, 0, 54, 54, 54, 54, 54, 54, 54, 54, 54, 54, 54, 54, 54, 54, 54, 54, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 23, 0, 0, 0, 0, 51, 0, 0, 0, 0, 0, 37, 0, 0, 39, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 37, 0, 54, 54, 54, 54, 54, 54, 54, 54, 54, 54, 54, 54, 54, 54, 54, 54, 54, 54, 54, 54, 54, 54, 54, 54, 0, 0, 0, 39, 0, 0, 0, 0, 3, 0, 0, 0, 0, 0, 37, 0, 0, 39, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 37, 39, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 37, 0, 0, 0, 22, 22, 22, 22, 22, 22, 52, 0, 0, 0, 37, 0, 0, 39, 0, 0, 0, 50, 65, 19, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 0, 39, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 53, 0, 0, 0, 0, 0, 0, 0, 0, 39, 0, 0, 0, 0, 37, 0, 0, 39, 0, 0, 0, 0, 51, 0, 37, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 39, 0, 0, 0, 0, 21, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 23, 0, 0, 0, 0, 0, 37, 54, 54, 54, 54, 54, 54, 54, 39, 0, 0, 0, 50, 0, 0, 0, 0, 52, 0, 0, 0, 4, 0, 37, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 39, 0, 0, 0, 50, 36, 0, 54, 54, 54, 54, 0, 0, 54, 54, 54, 54, 0, 0, 0, 39, 0, 0, 0, 50, 19, 34, 0, 0, 0, 0, 0, 0, 0, 20, 0, 0, 0, 0, 37, 0, 0, 39, 0, 0, 0, 0, 21, 22, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 39, 0, 0, 0, 0, 37, 39, 0, 0, 0, 0, 68, 55, 0, 0, 0, 0, 37, 0, 0, 39, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 53, 52, 0, 0, 0, 37, 0, 0, 39, 0, 0, 0, 50, 54, 54, 54, 54, 54, 54, 54, 54, 54, 54, 54, 54, 0, 36, 52, 0, 0, 0, 37, 39, 0, 0, 0, 0, 20, 0, 0, 0, 0, 0, 37, 0, 0, 0, 52, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 37, 0, 0, 39, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 37, 39, 0, 0, 0, 0, 37, 39, 0, 0, 0, 0, 33, 19, 52, 0, 0, 0, 37, 0, 0, 39, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 21, 0, 0, 0, 0, 52, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 37, 39, 0, 0, 0, 50, 54, 55, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 37, 0, 0, 0, 19, 19, 52, 4, 17, 19, 19, 19, 19, 19, 52, 4, 21, 22, 22, 22, 22, 0, 0, 0, 0, 39, 0, 0, 0, 0, 21, 22, 22, 22, 22, 19, 19, 19, 19, 19, 22, 22, 0, 39, 0, 0, 0, 0, 3, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 50, 36, 0, 0, 39, 0, 0, 0, 0, 20, 0, 0, 0, 0, 0, 0, 0, 37, 0, 0, 0, 0, 0, 0, 0, 0, 39, 0, 0, 0, 50, 54, 54, 54, 54, 55, 0, 0, 0, 0, 0, 37, 0, 0, 0, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 23, 0, 0, 0, 0, 37, 0, 0, 39, 0, 0, 0, 0, 20, 0, 0, 0, 0, 0, 0, 0, 37, 0, 0, 0, 0, 0, 0, 0, 0, 39, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 37, 0, 0, 0, 0, 54, 54, 54, 0, 54, 54, 54, 54, 0, 0, 36, 52, 0, 0, 0, 37, 0, 0, 39, 0, 0, 0, 50, 67, 0, 0, 0, 0, 0, 0, 21, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 19, 19, 19, 19, 19, 19, 19, 19, 65, 52, 0, 0, 21, 22, 0, 0, 0, 0, 39, 0, 0, 0, 20, 0, 0, 0, 0, 37, 0, 39, 0, 0, 0, 0, 37, 0, 0, 39, 0, 0, 0, 0, 33, 19, 19, 19, 19, 19, 19, 54, 54, 54, 54, 54, 54, 54, 54, 54, 54, 55, 0, 0, 0, 0, 0, 0, 0, 0, 20, 0, 0, 0, 37, 0, 0, 0, 0, 0, 39, 0, 0, 0, 53, 19, 52, 0, 0, 37, 0, 39, 0, 0, 0, 50, 36, 0, 0, 0, 23, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 51, 0, 0, 21, 0, 0, 0, 0, 0, 0, 55, 0, 0, 0, 0, 0, 0, 0, 0, 37, 0, 39, 0, 0, 0, 0, 53, 54, 54, 0, 0, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 23, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 3, 0, 0, 37, 0, 0, 0, 0, 0, 55, 0, 0, 0, 0, 0, 0, 0, 0, 50, 54, 54, 66, 52, 0, 0, 0, 0, 0, 49, 53, 54, 54, 54, 54, 54, 54, 54, 54, 54, 54, 54, 54, 54, 54, 54, 54, 54, 54, 54, 66, 52, 4, 21, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 0, 0, 0, 0, 0, 0, 3, 0, 0, 0, 0, 0, 0, 0, 0, 0, 3, 0, 0, 0, 0, 0, 0, 0, 35, 51, 35, 0, 0, 35, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 37, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22,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 27, 0, 27, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 27, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 27, 0, 0, 0, 0, 29, 0, 0, 0, 31, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 27, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 40, 26, 0, 0, 0, 27, 0, 0, 0, 27, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 27, 0, 0, 0, 27, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 40, 26, 72, 26, 41, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 };
pub const spawn: Vec2 = Vec2{ 1, 58 };
pub const wire: [10]Wire = [_]Wire{
.{ .a1 = true, .a2 = false, .divisions = 6, .p1 = Vec2{ 84, 396 }, .p2 = Vec2{ 50, 414 } },
.{ .a1 = true, .a2 = true, .divisions = 5, .p1 = Vec2{ 20, 436 }, .p2 = Vec2{ 36, 436 } },
.{ .a1 = true, .a2 = false, .divisions = 7, .p1 = Vec2{ 228, 380 }, .p2 = Vec2{ 268, 398 } },
.{ .a1 = false, .a2 = true, .divisions = 14, .p1 = Vec2{ 380, 236 }, .p2 = Vec2{ 468, 236 } },
.{ .a1 = true, .a2 = false, .divisions = 8, .p1 = Vec2{ 468, 228 }, .p2 = Vec2{ 420, 236 } },
.{ .a1 = false, .a2 = true, .divisions = 16, .p1 = Vec2{ 372, 204 }, .p2 = Vec2{ 468, 204 } },
.{ .a1 = true, .a2 = true, .divisions = 2, .p1 = Vec2{ 452, 268 }, .p2 = Vec2{ 436, 268 } },
.{ .a1 = false, .a2 = true, .divisions = 4, .p1 = Vec2{ 444, 396 }, .p2 = Vec2{ 468, 388 } },
.{ .a1 = false, .a2 = true, .divisions = 10, .p1 = Vec2{ 444, 396 }, .p2 = Vec2{ 380, 388 } },
.{ .a1 = true, .a2 = true, .divisions = 5, .p1 = Vec2{ 436, 340 }, .p2 = Vec2{ 468, 332 } },
};
pub const doors: [10]Vec2 = [_]Vec2{
Vec2{ 10, 58 },
Vec2{ 5, 51 },
Vec2{ 24, 50 },
Vec2{ 32, 50 },
Vec2{ 33, 42 },
Vec2{ 47, 22 },
Vec2{ 54, 38 },
Vec2{ 51, 56 },
Vec2{ 47, 45 },
Vec2{ 42, 57 },
};
pub const coins: [8]Vec2 = [_]Vec2{
Vec2{ 27, 52 },
Vec2{ 32, 58 },
Vec2{ 49, 22 },
Vec2{ 15, 58 },
Vec2{ 2, 51 },
Vec2{ 57, 38 },
Vec2{ 50, 52 },
Vec2{ 48, 45 },
};
pub const sources: [4]Vec2 = [_]Vec2{
Vec2{ 0, 41 },
Vec2{ 59, 39 },
Vec2{ 47, 59 },
Vec2{ 59, 50 },
};
pub const focus: [0]AABB = [_]AABB{};
|
0 | repos/wired/assets | repos/wired/assets/maps/test.json | { "compressionlevel":-1,
"height":20,
"infinite":false,
"layers":[
{
"data":[1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 54, 54, 54, 54, 54, 54, 54, 54, 54, 54, 54, 54, 54, 54, 54, 54, 1, 1, 1, 55, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 37, 1, 39, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 37, 1, 36, 19, 52, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 21, 36, 1, 39, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 50, 54, 36, 1, 39, 0, 50, 19, 19, 19, 22, 22, 22, 19, 19, 19, 19, 52, 0, 0, 0, 0, 37, 1, 39, 0, 0, 0, 0, 0, 37, 1, 55, 0, 0, 0, 0, 0, 0, 0, 0, 0, 37, 1, 1, 22, 52, 0, 0, 0, 37, 39, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 37, 1, 1, 39, 0, 0, 0, 0, 37, 54, 19, 52, 1, 1, 1, 1, 1, 1, 1, 1, 37, 1, 1, 39, 0, 0, 0, 50, 67, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 37, 1, 1, 39, 0, 0, 0, 0, 20, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 37, 1, 1, 36, 52, 0, 0, 0, 20, 0, 0, 17, 19, 19, 19, 19, 19, 19, 19, 19, 36, 1, 1, 39, 0, 0, 0, 0, 20, 0, 0, 20, 0, 0, 0, 0, 0, 0, 0, 0, 37, 1, 1, 39, 0, 0, 0, 50, 67, 0, 0, 51, 0, 0, 0, 0, 0, 0, 0, 0, 37, 1, 1, 39, 0, 0, 0, 1, 20, 0, 0, 3, 0, 0, 0, 0, 0, 0, 0, 0, 37, 1, 54, 66, 52, 0, 0, 1, 51, 0, 50, 19, 19, 19, 19, 19, 19, 19, 19, 19, 66, 54, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 3, 1, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 1, 1, 1, 1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0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 27, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 27, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
"height":20,
"id":2,
"name":"conduit",
"opacity":1,
"type":"tilelayer",
"visible":true,
"width":20,
"x":0,
"y":0
},
{
"draworder":"topdown",
"id":3,
"name":"wire",
"objects":[
{
"height":0,
"id":5,
"name":"",
"polyline":[
{
"x":0,
"y":0
},
{
"x":56,
"y":0
}],
"rotation":0,
"type":"wire",
"visible":true,
"width":0,
"x":20,
"y":20
},
{
"height":0,
"id":6,
"name":"",
"polyline":[
{
"x":-0.125,
"y":0.125
},
{
"x":55.875,
"y":0.125
}],
"properties":[
{
"name":"anchor2",
"type":"bool",
"value":false
}],
"rotation":0,
"type":"wire",
"visible":true,
"width":0,
"x":84.125,
"y":19.875
},
{
"height":0,
"id":7,
"name":"",
"polyline":[
{
"x":24,
"y":-0.181818181818187
},
{
"x":80,
"y":-0.181818181818187
}],
"properties":[
{
"name":"anchor1",
"type":"bool",
"value":false
},
{
"name":"anchor2",
"type":"bool",
"value":false
}],
"rotation":0,
"type":"wire",
"visible":true,
"width":0,
"x":60,
"y":94
},
{
"height":0,
"id":9,
"name":"",
"point":true,
"rotation":0,
"type":"source",
"visible":true,
"width":0,
"x":4,
"y":36
},
{
"height":0,
"id":10,
"name":"",
"point":true,
"rotation":0,
"type":"door",
"visible":true,
"width":0,
"x":148,
"y":140
},
{
"height":0,
"id":11,
"name":"",
"point":true,
"rotation":0,
"type":"door",
"visible":true,
"width":0,
"x":76,
"y":124
},
{
"height":0,
"id":12,
"name":"",
"point":true,
"rotation":0,
"type":"spawn",
"visible":true,
"width":0,
"x":4,
"y":140
}],
"opacity":1,
"type":"objectgroup",
"visible":true,
"x":0,
"y":0
}],
"nextlayerid":5,
"nextobjectid":13,
"orientation":"orthogonal",
"renderorder":"right-down",
"tiledversion":"1.7.2",
"tileheight":8,
"tilesets":[
{
"firstgid":1,
"source":"wired.tsx"
}],
"tilewidth":8,
"type":"map",
"version":"1.6",
"width":20
} |
0 | repos/wired/assets | repos/wired/assets/maps/map.json | { "compressionlevel":-1,
"editorsettings":
{
"chunksize":
{
"height":20,
"width":20
}
},
"height":60,
"infinite":false,
"layers":[
{
"data":[0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0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, 0, 0, 0, 0, 37, 39, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 3, 0, 0, 0, 0, 37, 0, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 23, 0, 0, 0, 50, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 39, 0, 0, 0, 0, 53, 0, 54, 54, 54, 54, 54, 0, 0, 0, 0, 54, 54, 54, 54, 54, 54, 54, 54, 54, 54, 54, 54, 54, 54, 54, 54, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 23, 0, 0, 0, 0, 51, 0, 0, 0, 0, 0, 37, 0, 0, 39, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 37, 0, 54, 54, 54, 54, 54, 54, 54, 54, 54, 54, 54, 54, 54, 54, 54, 54, 54, 54, 54, 54, 54, 54, 54, 54, 0, 0, 0, 39, 0, 0, 0, 0, 3, 0, 0, 0, 0, 0, 37, 0, 0, 39, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 37, 39, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 37, 0, 0, 0, 22, 22, 22, 22, 22, 22, 52, 0, 0, 0, 37, 0, 0, 39, 0, 0, 0, 50, 65, 19, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 0, 39, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 53, 0, 0, 0, 0, 0, 0, 0, 0, 39, 0, 0, 0, 0, 37, 0, 0, 39, 0, 0, 0, 0, 51, 0, 37, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 39, 0, 0, 0, 0, 21, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 23, 0, 0, 0, 0, 0, 37, 54, 54, 54, 54, 54, 54, 54, 39, 0, 0, 0, 50, 0, 0, 0, 0, 52, 0, 0, 0, 4, 0, 37, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 39, 0, 0, 0, 50, 36, 0, 54, 54, 54, 54, 0, 0, 54, 54, 54, 54, 0, 0, 0, 39, 0, 0, 0, 50, 19, 34, 0, 0, 0, 0, 0, 0, 0, 20, 0, 0, 0, 0, 37, 0, 0, 39, 0, 0, 0, 0, 21, 22, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 39, 0, 0, 0, 0, 37, 39, 0, 0, 0, 0, 68, 55, 0, 0, 0, 0, 37, 0, 0, 39, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 53, 52, 0, 0, 0, 37, 0, 0, 39, 0, 0, 0, 50, 54, 54, 54, 54, 54, 54, 54, 54, 54, 54, 54, 54, 0, 36, 52, 0, 0, 0, 37, 39, 0, 0, 0, 0, 20, 0, 0, 0, 0, 0, 37, 0, 0, 0, 52, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 37, 0, 0, 39, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 37, 39, 0, 0, 0, 0, 37, 39, 0, 0, 0, 0, 33, 19, 52, 0, 0, 0, 37, 0, 0, 39, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 21, 0, 0, 0, 0, 52, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 37, 39, 0, 0, 0, 50, 54, 55, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 37, 0, 0, 0, 19, 19, 52, 4, 17, 19, 19, 19, 19, 19, 52, 4, 21, 22, 22, 22, 22, 0, 0, 0, 0, 39, 0, 0, 0, 0, 21, 22, 22, 22, 22, 19, 19, 19, 19, 19, 22, 22, 0, 39, 0, 0, 0, 0, 3, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 50, 36, 0, 0, 39, 0, 0, 0, 0, 20, 0, 0, 0, 0, 0, 0, 0, 37, 0, 0, 0, 0, 0, 0, 0, 0, 39, 0, 0, 0, 50, 54, 54, 54, 54, 55, 0, 0, 0, 0, 0, 37, 0, 0, 0, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 23, 0, 0, 0, 0, 37, 0, 0, 39, 0, 0, 0, 0, 20, 0, 0, 0, 0, 0, 0, 0, 37, 0, 0, 0, 0, 0, 0, 0, 0, 39, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 37, 0, 0, 0, 0, 54, 54, 54, 0, 54, 54, 54, 54, 0, 0, 36, 52, 0, 0, 0, 37, 0, 0, 39, 0, 0, 0, 50, 67, 0, 0, 0, 0, 0, 0, 21, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 19, 19, 19, 19, 19, 19, 19, 19, 65, 52, 0, 0, 21, 22, 0, 0, 0, 0, 39, 0, 0, 0, 20, 0, 0, 0, 0, 37, 0, 39, 0, 0, 0, 0, 37, 0, 0, 39, 0, 0, 0, 0, 33, 19, 19, 19, 19, 19, 19, 54, 54, 54, 54, 54, 54, 54, 54, 54, 54, 55, 0, 0, 0, 0, 0, 0, 0, 0, 20, 0, 0, 0, 37, 0, 0, 0, 0, 0, 39, 0, 0, 0, 53, 19, 52, 0, 0, 37, 0, 39, 0, 0, 0, 50, 36, 0, 0, 0, 23, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 51, 0, 0, 21, 0, 0, 0, 0, 0, 0, 55, 0, 0, 0, 0, 0, 0, 0, 0, 37, 0, 39, 0, 0, 0, 0, 53, 54, 54, 0, 0, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 23, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 3, 0, 0, 37, 0, 0, 0, 0, 0, 55, 0, 0, 0, 0, 0, 0, 0, 0, 50, 54, 54, 66, 52, 0, 0, 0, 0, 0, 49, 53, 54, 54, 54, 54, 54, 54, 54, 54, 54, 54, 54, 54, 54, 54, 54, 54, 54, 54, 54, 66, 52, 4, 21, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 0, 0, 0, 0, 0, 0, 3, 0, 0, 0, 0, 0, 0, 0, 0, 0, 3, 0, 0, 0, 0, 0, 0, 0, 35, 51, 35, 0, 0, 35, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 37, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
"height":60,
"id":1,
"name":"solid",
"opacity":1,
"type":"tilelayer",
"visible":true,
"width":60,
"x":0,
"y":0
},
{
"data":[2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 27, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 40, 26, 0, 0, 0, 27, 0, 0, 0, 27, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 27, 0, 0, 0, 27, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 40, 26, 72, 26, 41, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
"height":60,
"id":2,
"name":"conduit",
"opacity":1,
"type":"tilelayer",
"visible":true,
"width":60,
"x":0,
"y":0
},
{
"draworder":"topdown",
"id":3,
"name":"objects",
"objects":[
{
"height":0,
"id":1,
"name":"",
"point":true,
"rotation":0,
"type":"spawn",
"visible":true,
"width":0,
"x":12,
"y":469
},
{
"height":0,
"id":2,
"name":"",
"point":true,
"rotation":0,
"type":"source",
"visible":true,
"width":0,
"x":4,
"y":332
},
{
"height":0,
"id":3,
"name":"",
"polyline":[
{
"x":32,
"y":-64
},
{
"x":-2,
"y":-46
}],
"properties":[
{
"name":"anchor1",
"type":"bool",
"value":true
},
{
"name":"anchor2",
"type":"bool",
"value":false
}],
"rotation":0,
"type":"wire",
"visible":true,
"width":0,
"x":52,
"y":460
},
{
"height":0,
"id":5,
"name":"",
"polyline":[
{
"x":0,
"y":0
},
{
"x":16,
"y":0
}],
"properties":[
{
"name":"divisions",
"type":"int",
"value":5
}],
"rotation":0,
"type":"wire",
"visible":true,
"width":0,
"x":20,
"y":436
},
{
"height":0,
"id":6,
"name":"",
"point":true,
"rotation":0,
"type":"door",
"visible":true,
"width":0,
"x":84,
"y":468
},
{
"height":0,
"id":7,
"name":"",
"point":true,
"rotation":0,
"type":"door",
"visible":true,
"width":0,
"x":44,
"y":412
},
{
"height":0,
"id":8,
"name":"",
"polyline":[
{
"x":56,
"y":-16
},
{
"x":96,
"y":2
}],
"properties":[
{
"name":"anchor2",
"type":"bool",
"value":false
}],
"rotation":0,
"type":"wire",
"visible":true,
"width":0,
"x":172,
"y":396
},
{
"height":0,
"id":10,
"name":"",
"point":true,
"rotation":0,
"type":"door",
"visible":true,
"width":0,
"x":196,
"y":404
},
{
"height":0,
"id":11,
"name":"",
"point":true,
"rotation":0,
"type":"door",
"visible":true,
"width":0,
"x":260,
"y":404
},
{
"height":0,
"id":12,
"name":"",
"point":true,
"rotation":0,
"type":"door",
"visible":true,
"width":0,
"x":268,
"y":340
},
{
"height":0,
"id":13,
"name":"",
"point":true,
"rotation":0,
"type":"source",
"visible":true,
"width":0,
"x":476,
"y":316
},
{
"height":0,
"id":14,
"name":"",
"polyline":[
{
"x":0,
"y":0
},
{
"x":88,
"y":0
}],
"properties":[
{
"name":"anchor1",
"type":"bool",
"value":false
},
{
"name":"anchor2",
"type":"bool",
"value":true
}],
"rotation":0,
"type":"wire",
"visible":true,
"width":0,
"x":380,
"y":236
},
{
"height":0,
"id":15,
"name":"",
"polyline":[
{
"x":0,
"y":0
},
{
"x":-48,
"y":8
}],
"properties":[
{
"name":"anchor2",
"type":"bool",
"value":false
}],
"rotation":0,
"type":"wire",
"visible":true,
"width":0,
"x":468,
"y":228
},
{
"height":0,
"id":17,
"name":"",
"polyline":[
{
"x":0,
"y":0
},
{
"x":96,
"y":0
}],
"properties":[
{
"name":"anchor1",
"type":"bool",
"value":false
},
{
"name":"anchor2",
"type":"bool",
"value":true
}],
"rotation":0,
"type":"wire",
"visible":true,
"width":0,
"x":372,
"y":204
},
{
"height":0,
"id":18,
"name":"",
"point":true,
"rotation":0,
"type":"door",
"visible":true,
"width":0,
"x":380,
"y":180
},
{
"height":0,
"id":26,
"name":"",
"point":true,
"rotation":0,
"type":"door",
"visible":true,
"width":0,
"x":436,
"y":310
},
{
"gid":5,
"height":8,
"id":19,
"name":"",
"rotation":0,
"type":"coin",
"visible":true,
"width":8,
"x":216,
"y":424
},
{
"gid":5,
"height":8,
"id":20,
"name":"",
"rotation":0,
"type":"coin",
"visible":true,
"width":8,
"x":256,
"y":472
},
{
"gid":5,
"height":8,
"id":21,
"name":"",
"rotation":0,
"type":"coin",
"visible":true,
"width":8,
"x":392,
"y":184
},
{
"gid":5,
"height":8,
"id":22,
"name":"",
"rotation":0,
"type":"coin",
"visible":true,
"width":8,
"x":120,
"y":472
},
{
"gid":5,
"height":8,
"id":23,
"name":"",
"rotation":0,
"type":"coin",
"visible":true,
"width":8,
"x":16,
"y":416
},
{
"gid":5,
"height":8,
"id":24,
"name":"",
"rotation":0,
"type":"coin",
"visible":true,
"width":8,
"x":456,
"y":312
},
{
"height":0,
"id":25,
"name":"",
"polyline":[
{
"x":0,
"y":0
},
{
"x":-16,
"y":0
}],
"rotation":0,
"type":"wire",
"visible":true,
"width":0,
"x":452,
"y":268
},
{
"height":0,
"id":27,
"name":"",
"point":true,
"rotation":0,
"type":"door",
"visible":true,
"width":0,
"x":412,
"y":452
},
{
"height":0,
"id":28,
"name":"",
"polyline":[
{
"x":0,
"y":0
},
{
"x":24,
"y":-8
}],
"properties":[
{
"name":"anchor1",
"type":"bool",
"value":false
},
{
"name":"anchor2",
"type":"bool",
"value":true
}],
"rotation":0,
"type":"wire",
"visible":true,
"width":0,
"x":444,
"y":396
},
{
"height":0,
"id":29,
"name":"",
"polyline":[
{
"x":8,
"y":0
},
{
"x":-56,
"y":-8
}],
"properties":[
{
"name":"anchor1",
"type":"bool",
"value":false
},
{
"name":"anchor2",
"type":"bool",
"value":true
}],
"rotation":0,
"type":"wire",
"visible":true,
"width":0,
"x":436,
"y":396
},
{
"height":0,
"id":30,
"name":"",
"polyline":[
{
"x":0,
"y":0
},
{
"x":32,
"y":-8
}],
"rotation":0,
"type":"wire",
"visible":true,
"width":0,
"x":436,
"y":340
},
{
"gid":5,
"height":8,
"id":32,
"name":"",
"rotation":0,
"type":"coin",
"visible":true,
"width":8,
"x":400,
"y":424
},
{
"gid":5,
"height":8,
"id":33,
"name":"",
"rotation":0,
"type":"coin",
"visible":true,
"width":8,
"x":384,
"y":368
},
{
"height":0,
"id":35,
"name":"",
"point":true,
"rotation":0,
"type":"door",
"visible":true,
"width":0,
"x":380,
"y":364
},
{
"height":0,
"id":36,
"name":"",
"point":true,
"rotation":0,
"type":"door",
"visible":true,
"width":0,
"x":340,
"y":460
},
{
"height":0,
"id":37,
"name":"",
"point":true,
"rotation":0,
"type":"source",
"visible":true,
"width":0,
"x":380,
"y":478
},
{
"height":0,
"id":38,
"name":"",
"point":true,
"rotation":0,
"type":"source",
"visible":true,
"width":0,
"x":476,
"y":404
}],
"opacity":1,
"type":"objectgroup",
"visible":true,
"x":0,
"y":0
}],
"nextlayerid":4,
"nextobjectid":39,
"orientation":"orthogonal",
"renderorder":"right-down",
"tiledversion":"1.7.2",
"tileheight":8,
"tilesets":[
{
"firstgid":1,
"source":"wired.tsx"
}],
"tilewidth":8,
"type":"map",
"version":"1.6",
"width":60
} |
0 | repos/wired/assets | repos/wired/assets/maps/wired.tsx | <?xml version="1.0" encoding="UTF-8"?>
<tileset version="1.5" tiledversion="1.7.2" name="wired" tilewidth="8" tileheight="8" tilecount="256" columns="16">
<editorsettings>
<export target="wired.json" format="json"/>
</editorsettings>
<image source="../tiles.png" width="128" height="128"/>
</tileset>
|
0 | repos/wired | repos/wired/src/circuit.zig | const std = @import("std");
const util = @import("util.zig");
const assets = @import("assets");
const world = @import("world.zig");
const T = world.Tiles;
const Vec2 = util.Vec2;
const Cell = util.Cell;
pub fn switchIsOn(tile: u8) bool {
return switch (tile) {
T.SwitchTeeWestOn,
T.SwitchTeeEastOn,
T.SwitchVerticalOn,
T.SwitchHorizontalOn,
=> true,
T.SwitchTeeWestOff,
T.SwitchTeeEastOff,
T.SwitchVerticalOff,
T.SwitchHorizontalOff,
=> false,
else => false,
};
}
pub fn toggle_switch(tile: u8) u8 {
return switch (tile) {
// Tee west
T.SwitchTeeWestOff => T.SwitchTeeWestOn,
T.SwitchTeeWestOn => T.SwitchTeeWestOff,
// Tee east
T.SwitchTeeEastOff => T.SwitchTeeEastOn,
T.SwitchTeeEastOn => T.SwitchTeeEastOff,
// Vertical
T.SwitchVerticalOn => T.SwitchVerticalOff,
T.SwitchVerticalOff => T.SwitchVerticalOn,
// Horizontal
T.SwitchHorizontalOn => T.SwitchHorizontalOff,
T.SwitchHorizontalOff => T.SwitchHorizontalOn,
// Not a switch, pass tile through
else => tile,
};
}
const Side = enum(u2) {
up,
right,
down,
left,
pub fn opposite(s: Side) Side {
return switch (s) {
.up => .down,
.down => .up,
.left => .right,
.right => .left,
};
}
pub fn side(s: Side) u2 {
return @intFromEnum(s);
}
pub fn dir(s: Side) Cell {
return switch (s) {
.up => util.Dir.up,
.down => util.Dir.down,
.left => util.Dir.left,
.right => util.Dir.right,
};
}
};
const Current = [4]bool;
/// Returns sides that can conduct current
fn get_inputs(tile: u8) Current {
return switch (tile) {
// Conduit recieves from every side
T.PlugNorth...T.PlugSouth,
T.ConduitCross...T.ConduitSingle,
=> .{ true, true, true, true },
// Switch_On
T.SwitchTeeWestOn,
T.SwitchTeeEastOn,
T.SwitchVerticalOn,
=> .{ true, false, true, false },
// Switch_Off
T.SwitchTeeWestOff => .{ false, false, true, true },
T.SwitchTeeEastOff => .{ false, true, true, false },
// And, Xor
T.LogicAnd,
T.LogicXor,
=> .{ false, true, false, true },
// Not
T.LogicNot => .{ false, false, true, false },
else => .{ false, false, false, false },
};
}
fn get_outputs(tile: u8) Current {
return switch (tile) {
// Conduit goes out every side
T.PlugNorth...T.PlugSouth,
T.ConduitCross...T.ConduitSingle,
=> .{ true, true, true, true },
// Switches
// Tee west
T.SwitchTeeWestOn => .{ false, false, true, true },
T.SwitchTeeWestOff => .{ true, false, true, false },
// Tee east
T.SwitchTeeEastOn => .{ false, true, true, false },
T.SwitchTeeEastOff => .{ true, false, true, false },
// Vertical
T.SwitchVerticalOn => .{ true, false, true, false },
T.SwitchVerticalOff => .{ false, false, true, false },
else => .{ false, false, false, false },
};
}
const Logic = union(enum) { Not, And, Xor };
fn get_logic(tile: u8) ?Logic {
return switch (tile) {
T.LogicAnd => .And,
T.LogicNot => .Not,
T.LogicXor => .Xor,
else => null,
};
}
const Plugs = [4]bool;
/// Returns sides where wires may be plugged
fn get_plugs(tile: u8) Plugs {
return switch (tile) {
world.Tiles.PlugNorth => .{ false, false, true, false },
world.Tiles.PlugWest => .{ false, true, false, false },
world.Tiles.PlugEast => .{ false, false, false, true },
world.Tiles.PlugSouth => .{ true, false, false, false },
else => .{ false, false, false, false },
};
}
pub fn getCoord(this: @This(), coord: world.Coordinate) ?u8 {
const i = this.indexOf(coord.toVec2()) orelse return null;
return if (this.map[i] != 0) this.map[i] else null;
}
pub fn setCoord(this: @This(), coord: world.Coordinate, tile: u8) void {
const i = this.indexOf(coord.toVec2()) orelse return;
this.map[i] = tile;
// this.levels[i] = 255;
}
const MAXCELLS = 400;
const MAXBRIDGES = 20;
const MAXSOURCES = 10;
const MAXDOORS = 40;
const MAXLOGIC = 40;
pub const NodeCoord = struct { coord: world.Coordinate, node_id: world.NodeID };
pub const Source = NodeCoord;
pub const BridgeState = struct { coords: [2]world.Coordinate, id: usize, enabled: bool };
pub const DoorState = struct { coord: world.Coordinate, enabled: bool };
/// Tile id of the tiles
map: []u8,
/// CircuitNode ID for each tile
nodes: []world.NodeID,
map_size: Vec2,
bridges: util.Buffer(BridgeState),
sources: util.Buffer(Source),
doors: util.Buffer(DoorState),
pub const Options = struct {
map: []u8,
nodes: []u8,
map_size: Vec2,
bridges: []BridgeState,
sources: []Source,
doors: []DoorState,
};
pub fn init(opt: Options) @This() {
std.debug.assert(opt.map.len == opt.nodes.len);
var this = @This(){
.map = opt.map,
.nodes = opt.nodes,
.map_size = opt.map_size,
.bridges = util.Buffer(BridgeState).init(opt.bridges),
.sources = util.Buffer(Source).init(opt.sources),
.doors = util.Buffer(DoorState).init(opt.doors),
};
return this;
}
pub fn indexOf(this: @This(), cell: Cell) ?usize {
if (cell[0] < 0 or cell[0] >= this.map_size[0] or cell[1] >= this.map_size[1] or cell[1] < 0) return null;
return @as(usize, @intCast(@mod(cell[0], this.map_size[0]) + (cell[1] * this.map_size[1])));
}
pub fn bridge(this: *@This(), coords: [2]world.Coordinate, bridgeID: usize) void {
if (this.indexOf(coords[0].toVec2())) |_| {
if (this.indexOf(coords[1].toVec2())) |_| {
this.bridges.append(.{ .coords = coords, .id = bridgeID, .enabled = false });
}
}
}
pub fn addSource(this: *@This(), source: Source) void {
w4.tracef("%d, %d", source.coord.val[0], source.coord.val[1]);
if (this.indexOf(source.coord.toVec2())) |_| {
this.sources.append(source);
}
}
pub fn addDoor(this: *@This(), coord: world.Coordinate) !void {
if (this.indexOf(coord.toVec2())) |_| {
this.doors.append(.{ .coord = coord, .enabled = false });
}
}
pub fn enabledBridge(this: @This(), id: usize) ?usize {
var count: usize = 0;
for (this.bridges.items) |b| {
if (b.enabled) {
if (count == id) {
return b.id;
}
count += 1;
}
}
return null;
}
pub fn enabledBridges(this: @This(), alloc: std.mem.Allocator) !util.Buffer(usize) {
var items = try alloc.alloc(usize, this.bridges.len);
var buffer = util.Buffer(usize).init(items);
for (this.bridges.items) |b| {
if (b.enabled) buffer.append(b.id);
}
return buffer;
}
pub fn enabledDoors(this: @This(), alloc: std.mem.Allocator) !util.Buffer(Cell) {
var items = try alloc.alloc(Cell, this.doors.items.len);
var buffer = util.Buffer(Cell).init(items);
for (this.doors.items) |d| {
const x = d.cell[0];
const y = d.cell[1];
w4.tracef("%d, %d", x, y);
if (d.enabled) buffer.append(d.cell);
}
return buffer;
}
pub fn getNodeID(this: @This(), coord: world.Coordinate) ?world.NodeID {
const i = this.indexOf(coord.toVec2()) orelse return null;
if (this.nodes[i] == std.math.maxInt(world.NodeID)) return null;
return this.nodes[i];
}
pub fn switchOn(this: *@This(), coord: world.Coordinate) void {
if (this.getCoord(coord)) |tile| {
if (T.is_switch(tile)) {
if (switchIsOn(tile)) return;
const toggled = toggle_switch(tile);
this.setCoord(coord, toggled);
return;
}
}
}
pub fn toggle(this: *@This(), coord: world.Coordinate) ?u8 {
if (this.getCoord(coord)) |tile| {
if (T.is_switch(tile)) {
const toggled = toggle_switch(tile);
this.setCoord(coord, toggled);
return toggled;
}
}
return null;
}
pub fn clearMap(this: *@This()) void {
this.clear();
std.mem.set(u8, this.map, 0);
this.doors.reset();
this.bridges.reset();
this.sources.reset();
}
pub fn clear(this: *@This()) void {
std.mem.set(u8, this.nodes, std.math.maxInt(world.NodeID));
for (this.doors.items) |*door| {
door.enabled = false;
}
this.bridges.reset();
}
pub fn reset(this: *@This()) void {
this.clear();
// Resizing to zero should always work
this.sources.reset();
}
const w4 = @import("wasm4.zig");
// Returns number of cells filled
pub fn fill(this: *@This(), alloc: std.mem.Allocator, db: world.Database, level: world.Level) !usize {
var count: usize = 0;
w4.tracef("[fill] begin");
const Queue = util.Queue(NodeCoord);
var q_buf = try alloc.alloc(NodeCoord, MAXCELLS);
var q = Queue.init(q_buf);
for (this.sources.items) |source| {
w4.tracef("[fill] inserting source (%d, %d)", source.coord.val[0], source.coord.val[1]);
try q.insert(source);
}
// if (this.sources.items.len == 0) {
// w4.tracef("[fill] no sources %d", this.sources.items.len);
// }
while (q.remove()) |node| {
const tile = this.getCoord(node.coord) orelse continue;
const index = this.indexOf(node.coord.toVec2()) orelse continue;
const hasVisited = this.nodes[index] != std.math.maxInt(world.NodeID);
w4.tracef("[fill] %d, %d, %d", tile, index, hasVisited);
if (hasVisited) continue;
this.nodes[index] = node.node_id;
count += 1;
if (get_logic(tile)) |_| {
// w4.tracef("[fill] logic");
const new_id = db.getLevelNodeID(level, node.coord) orelse {
w4.tracef("[fill] missing logic");
continue;
};
try q.insert(.{ .node_id = new_id, .coord = node.coord.add(.{ 0, -1 }) });
continue;
}
if (T.is_switch(tile)) {
const n = node.coord.add(.{ 0, -1 });
const w = node.coord.add(.{ -1, 0 });
const e = node.coord.add(.{ 1, 0 });
const s = node.coord.add(.{ 0, 1 });
const nid = db.getLevelNodeID(level, n);
const wid = db.getLevelNodeID(level, w);
const eid = db.getLevelNodeID(level, e);
const sid = db.getLevelNodeID(level, s);
if (nid) |new_id| try q.insert(.{ .node_id = new_id, .coord = n });
if (wid) |new_id| try q.insert(.{ .node_id = new_id, .coord = w });
if (eid) |new_id| try q.insert(.{ .node_id = new_id, .coord = e });
if (sid) |new_id| try q.insert(.{ .node_id = new_id, .coord = s });
continue;
}
for (get_outputs(tile), 0..) |conductor, i| {
// w4.tracef("[fill] outputs");
if (!conductor) continue;
// w4.tracef("[fill] conductor");
const s = @as(Side, @enumFromInt(i));
const delta = s.dir();
// TODO: check that cell can recieve from this side
const nextCoord = node.coord.addC(world.Coordinate.fromVec2(delta));
const tl = world.Coordinate.init(.{ 0, 0 });
const br = world.Coordinate.fromVec2(this.map_size);
// w4.tracef("[fill] next (%d, %d)", nextCoord.val[0], nextCoord.val[1]);
// w4.tracef("[fill] range (%d, %d)-(%d, %d)", tl.val[0], tl.val[1], br.val[0], br.val[1]);
if (!nextCoord.within(tl, br)) continue;
// w4.tracef("[fill] within %d", nextCoord.within(tl, br));
const nextTile = this.getCoord(nextCoord) orelse 0;
// w4.tracef("[fill] nextTile");
if (get_inputs(nextTile)[@intFromEnum(s.opposite())]) {
// w4.tracef("[fill] get_inputs");
try q.insert(.{
.node_id = node.node_id,
.coord = nextCoord,
});
}
}
if (T.is_plug(tile)) {
// w4.tracef("[fill] plug");
for (this.bridges.items) |*b| {
if (b.coords[0].eq(node.coord)) {
try q.insert(.{
.coord = b.coords[1],
.node_id = node.node_id,
});
b.enabled = true;
} else if (b.coords[1].eq(node.coord)) {
try q.insert(.{
.coord = b.coords[0],
.node_id = node.node_id,
});
b.enabled = true;
}
}
}
w4.tracef("[fill] end search step");
}
return count;
}
const width = 20;
const height = 20;
const tile_size = Vec2{ 8, 8 };
const tilemap_width = 16;
const tilemap_height = 16;
const tilemap_stride = 128;
pub fn draw(this: @This(), db: world.Database, offset: Vec2) void {
var y: usize = 0;
while (y < height) : (y += 1) {
var x: usize = 0;
while (x < width) : (x += 1) {
const cell = Vec2{ @as(i32, @intCast(x)), @as(i32, @intCast(y)) };
const pos = cell * tile_size;
const coord = world.Coordinate.fromVec2(cell + offset);
const tile = this.getCoord(coord) orelse continue;
if (tile == 0) continue;
const energized = if (this.getNodeID(coord)) |node| db.circuit_info[node].energized else false;
if (energized) w4.DRAW_COLORS.* = 0x0210 else w4.DRAW_COLORS.* = 0x0310;
const t = Vec2{
@as(i32, @intCast((tile % tilemap_width) * tile_size[0])),
@as(i32, @intCast((tile / tilemap_width) * tile_size[0])),
};
w4.blitSub(
&assets.tiles,
pos,
tile_size,
t,
tilemap_stride,
.{ .bpp = .b2 },
);
}
}
}
|
0 | repos/wired | repos/wired/src/map.zig | const std = @import("std");
const assets = @import("assets");
const util = @import("util.zig");
const w4 = @import("wasm4.zig");
const world = @import("world.zig");
const Vec2 = util.Vec2;
const Vec2f = util.Vec2f;
const Cell = util.Cell;
const width = 20;
const height = 20;
const tile_width = 8;
const tile_height = 8;
pub const tile_size = Vec2{ 8, 8 };
const tile_sizef = Vec2f{ 8, 8 };
const tilemap_width = 16;
const tilemap_height = 16;
const tilemap_stride = 128;
tiles: []u8,
map_size: Vec2,
pub fn init(map: []u8, map_size: Vec2) @This() {
var this = @This(){
.tiles = map,
.map_size = map_size,
};
return this;
}
pub fn clear(this: *@This()) void {
std.mem.set(u8, this.tiles, 0);
}
pub fn reset(this: *@This(), initialState: []const u8) void {
std.debug.assert(initialState.len == this.tiles.len);
std.mem.copy(u8, this.tiles, initialState);
}
pub fn write_diff(this: *@This(), initialState: []const u8, buf: anytype) !u8 {
var written: u8 = 0;
for (initialState, 0..) |init_tile, i| {
if (this.tiles[i] != init_tile) {
const x = @as(u8, @intCast(i % @as(usize, @intCast(this.map_size[0]))));
const y = @as(u8, @intCast(@divTrunc(i, @as(usize, @intCast(this.map_size[0])))));
const temp = [3]u8{ x, y, this.tiles[i] };
try buf.writeAll(&temp);
written += 1;
}
}
return written;
}
pub fn load_diff(this: *@This(), diff: []const u8) void {
var i: usize = 0;
while (i < diff.len) : (i += 3) {
const x = diff[i];
const y = diff[i + 1];
const tile = diff[i + 2];
this.set_cell(Cell{ x, y }, tile);
}
}
pub fn set_cell(this: *@This(), cell: Cell, tile: u8) !void {
const x = cell[0];
const y = cell[1];
if (x < 0 or x > this.map_size[0] or y < 0 or y > this.map_size[1]) return error.OutOfBounds;
const i = x + y * this.map_size[0];
this.tiles[@as(usize, @intCast(i))] = tile;
}
pub fn get_cell(this: @This(), cell: Cell) ?u8 {
const x = cell[0];
const y = cell[1];
if (x < 0 or x >= this.map_size[0] or y < 0 or y >= this.map_size[1]) return null;
const i = x + y * this.map_size[0];
return this.tiles[@as(u32, @intCast(i))];
}
pub fn draw(this: @This(), offset: Vec2) void {
w4.DRAW_COLORS.* = 0x0210;
var y: usize = 0;
while (y < height) : (y += 1) {
var x: usize = 0;
while (x < width) : (x += 1) {
const cell = Vec2{ @as(i32, @intCast(x)), @as(i32, @intCast(y)) } + offset;
const pos = Vec2{ @as(i32, @intCast(x)), @as(i32, @intCast(y)) } * tile_size;
const tile = this.get_cell(cell) orelse continue;
if (tile == world.Tiles.Empty) continue;
const t = Vec2{
@as(i32, @intCast((tile % tilemap_width) * tile_width)),
@as(i32, @intCast((tile / tilemap_width) * tile_width)),
};
w4.blitSub(
&assets.tiles,
pos,
.{ tile_width, tile_height },
t,
tilemap_stride,
.{ .bpp = .b2 },
);
}
}
}
/// pos should be in tile coordinates, not world coordinates
fn getTile(this: @This(), x: i32, y: i32) ?u8 {
if (x < 0 or x >= this.map_size[0] or y < 0 or y >= this.map_size[1]) return null;
const i = x + y * this.map_size[0];
return this.tiles[@as(u32, @intCast(i))];
}
pub const BodyInfo = struct {
/// Rectangle
rect: util.AABB,
/// Last position
last: Vec2f,
/// Next position
next: Vec2f,
/// Pass through one way platforms
is_passing: bool = false,
};
pub fn collide(this: @This(), body: BodyInfo) CollisionInfo {
const top_left = body.rect.pos / tile_sizef;
const bot_right = (body.rect.pos + body.rect.size) / tile_sizef;
var collisions = CollisionInfo.init();
var i: isize = @as(i32, @intFromFloat(top_left[0]));
while (i <= @as(i32, @intFromFloat(bot_right[0]))) : (i += 1) {
var a: isize = @as(i32, @intFromFloat(top_left[1]));
while (a <= @as(i32, @intFromFloat(bot_right[1]))) : (a += 1) {
const tile = this.getTile(i, a) orelse continue;
const tilex = @as(f32, @floatFromInt(i * tile_width));
const tiley = @as(f32, @floatFromInt(a * tile_height));
const bottom = @as(i32, @intFromFloat(bot_right[1]));
const foot = body.rect.pos[1] + body.rect.size[1];
if (world.Tiles.is_oneway(tile)) {
if (!body.is_passing and a == bottom and body.last[1] <= body.next[1] and foot < tiley + 2) {
collisions.append(util.AABB{
.pos = Vec2f{ tilex, tiley },
.size = tile_sizef,
});
}
} else if (world.Tiles.is_solid(tile)) {
collisions.append(util.AABB{
.pos = Vec2f{ tilex, tiley },
.size = tile_sizef,
});
}
}
}
return collisions;
}
pub const CollisionInfo = struct {
len: usize,
items: [9]util.AABB,
pub fn init() CollisionInfo {
return CollisionInfo{
.len = 0,
.items = undefined,
};
}
pub fn append(col: *CollisionInfo, item: util.AABB) void {
std.debug.assert(col.len < 9);
col.items[col.len] = item;
col.len += 1;
}
};
// Debug functions
pub fn trace(this: @This()) void {
var y: usize = 0;
while (y < height) : (y += 1) {
const i = y * width;
w4.trace("{any}", .{this.tiles[i .. i + width]});
}
}
pub fn traceDraw(this: @This()) void {
for (this.tiles, 0..) |tile, i| {
const t = Vec2{
@as(i32, @intCast((tile % tilemap_width) * tile_width)),
@as(i32, @intCast((tile / tilemap_width) * tile_width)),
};
const pos = Vec2{
@as(i32, @intCast((i % width) * tile_width)),
@as(i32, @intCast((i / width) * tile_width)),
};
w4.trace("{}, {}, {}, {}, {}", .{
pos,
.{ tile_width, tile_height },
t,
tilemap_stride,
.{ .bpp = .b2 },
});
}
}
|
0 | repos/wired | repos/wired/src/component.zig | const std = @import("std");
const w4 = @import("wasm4.zig");
const util = @import("util.zig");
const Vec2 = util.Vec2;
const Vec2f = util.Vec2f;
const AABB = util.AABB;
const Anim = @import("anim.zig");
const approxEqAbs = std.math.approxEqAbs;
const AnimData = []const Anim.Ops;
// Components
pub const Pos = struct {
pos: Vec2f,
last: Vec2f,
pinned: bool = false,
pub fn init(pos: Vec2f) @This() {
return @This(){ .pos = pos, .last = pos };
}
pub fn initVel(pos: Vec2f, vel: Vec2f) @This() {
return @This(){ .pos = pos, .last = pos - vel };
}
pub fn getDirection(pos: Pos) Vec2f {
return pos.pos - pos.last;
}
pub fn getVelocity(pos: Pos) Vec2f {
return pos.pos - pos.last;
}
};
pub const Control = struct {
controller: enum { player },
state: enum { stand, walk, jump, fall, wallSlide },
facing: enum { left, right, up, down } = .right,
grabbing: ?struct { id: usize, which: usize } = null,
};
pub const Sprite = struct {
offset: Vec2 = Vec2{ 0, 0 },
size: w4.Vec2,
index: usize,
flags: w4.BlitFlags,
};
pub const StaticAnim = Anim;
pub const ControlAnim = struct { anims: []AnimData, state: Anim };
pub const Kinematic = struct {
col: AABB,
move: Vec2f = Vec2f{ 0, 0 },
lastCol: Vec2f = Vec2f{ 0, 0 },
pass_start: ?usize = null,
pub fn inAir(this: @This()) bool {
return approxEqAbs(f32, this.lastCol[1], 0, 0.01);
}
pub fn onFloor(this: @This()) bool {
return approxEqAbs(f32, this.move[1], 0, 0.01) and this.lastCol[1] > 0;
}
pub fn isFalling(this: @This()) bool {
return this.move[1] > 0 and approxEqAbs(f32, this.lastCol[1], 0, 0.01);
}
pub fn onWall(this: @This()) bool {
return this.isFalling() and !approxEqAbs(f32, this.lastCol[0], 0, 0.01);
}
};
pub const Physics = struct { gravity: Vec2f, friction: Vec2f };
|
0 | repos/wired | repos/wired/src/world.zig | //! Data types used for storing world info
const std = @import("std");
/// This lists the most important tiles so I don't have to keep rewriting things
pub const Tiles = struct {
// Switches
pub const SwitchTeeWestOff = 24;
pub const SwitchTeeWestOn = 25;
pub const SwitchTeeEastOff = 26;
pub const SwitchTeeEastOn = 27;
pub const SwitchVerticalOff = 28;
pub const SwitchVerticalOn = 29;
pub const SwitchHorizontalOff = 30;
pub const SwitchHorizontalOn = 31;
pub fn is_switch(tile: u8) bool {
return tile >= SwitchTeeWestOff and tile <= SwitchHorizontalOn;
}
// Plugs, sorted by autotile order
pub const PlugNorth = 16;
pub const PlugWest = 17;
pub const PlugEast = 18;
pub const PlugSouth = 19;
pub fn is_plug(tile: u8) bool {
return tile >= 16 and tile < 20;
}
pub const LogicAnd = 20;
pub const LogicNot = 21;
pub const LogicXor = 22;
pub const LogicDiode = 23;
pub fn is_logic(tile: u8) bool {
return tile >= LogicAnd and tile <= LogicDiode;
}
pub const ConduitCross = 96;
pub const ConduitSingle = 112;
pub fn is_conduit(tile: u8) bool {
return tile >= ConduitCross and tile <= ConduitSingle;
}
pub fn is_circuit(tile: u8) bool {
return is_plug(tile) or is_conduit(tile) or is_switch(tile) or is_logic(tile);
}
pub const WallSingle = 112;
pub const WallSurrounded = 127;
pub fn is_wall(tile: u8) bool {
return tile >= WallSingle and tile <= WallSurrounded;
}
pub const Door = 2;
pub const Trapdoor = 3;
pub fn is_door(tile: u8) bool {
return tile == Door or tile == Trapdoor;
}
pub fn is_solid(tile: u8) bool {
return is_wall(tile) or is_door(tile);
}
pub const OneWayLeft = 33;
pub const OneWayMiddle = 34;
pub const OneWayRight = 35;
pub fn is_oneway(tile: u8) bool {
return tile >= OneWayLeft and tile <= OneWayRight;
}
pub const Empty = 0;
pub const Walls = AutoTileset.initOffsetFull(WallSingle);
pub const Conduit = AutoTileset.initOffsetFull(ConduitCross);
pub const Plugs = AutoTileset.initOffsetCardinal(PlugNorth);
pub const SwitchesOff = AutoTileset.initSwitches(&.{
SwitchVerticalOff, // South-North
SwitchTeeWestOff, // South-West-North
SwitchTeeEastOff, // South-East-North
}, 2);
pub const SwitchesOn = AutoTileset.initSwitches(&.{
SwitchVerticalOn, // South-North
SwitchTeeWestOn, // South-West-North
SwitchTeeEastOn, // South-East-North
}, 2);
};
pub const SolidType = enum(u2) {
Empty = 0,
Solid = 1,
Oneway = 2,
};
/// The CircuitType of a tile modifies how the tile responds to
/// electricity
pub const CircuitType = enum(u5) {
None = 0,
Conduit = 1,
Plug = 2,
Switch_Off = 3,
Switch_On = 4,
Join = 5,
And = 6,
Xor = 7,
Outlet = 8,
Source = 9,
Socket = 10,
Diode = 11,
Conduit_Vertical = 12,
Conduit_Horizontal = 13,
pub fn canConnect(circuit: CircuitType, side: Direction) bool {
return switch (circuit) {
.None => false,
.Conduit_Vertical => (side != .East and side != .West),
.Conduit_Horizontal => (side != .North and side != .South),
else => true,
};
}
};
pub const TileData = union(enum) {
tile: u7,
flags: struct {
solid: SolidType,
circuit: CircuitType,
},
pub fn getCircuit(data: TileData) ?CircuitType {
if (data == .flags) {
return data.flags.circuit;
}
return null;
}
const isTileBitMask = 0b1000_0000;
const tileBitMask = 0b0111_1111;
const solidBitMask = 0b0000_0011;
const circuitBitMask = 0b0111_1100;
pub fn toByte(data: TileData) u8 {
switch (data) {
.tile => |int| return 0b1000_0000 | @as(u8, @intCast(int)),
.flags => |flags| {
const solid = @intFromEnum(flags.solid);
const circuit = @intFromEnum(flags.circuit);
return ((@as(u8, @intCast(solid)) & solidBitMask) | ((@as(u8, @intCast(circuit)) << 2) & circuitBitMask));
},
}
}
pub fn fromByte(byte: u8) TileData {
const is_tile = (isTileBitMask & byte) > 0;
if (is_tile) {
const tile = @as(u7, @intCast((tileBitMask & byte)));
return TileData{ .tile = tile };
} else {
const solid = @as(u2, @intCast((solidBitMask & byte)));
const circuit = @as(u5, @intCast((circuitBitMask & byte) >> 2));
return TileData{ .flags = .{
.solid = @as(SolidType, @enumFromInt(solid)),
.circuit = @as(CircuitType, @enumFromInt(circuit)),
} };
}
}
};
// Shorthand
const Coord = Coordinate;
pub const Coordinate = struct {
const LEVELSIZE = 20;
val: [2]i16,
pub fn init(val: [2]i16) Coordinate {
return Coordinate{ .val = val };
}
pub fn read(reader: anytype) !Coordinate {
return Coordinate{ .val = .{
try reader.readInt(i16, .Little),
try reader.readInt(i16, .Little),
} };
}
pub fn write(coord: Coordinate, writer: anytype) !void {
try writer.writeInt(i16, coord.val[0], .Little);
try writer.writeInt(i16, coord.val[1], .Little);
}
pub fn add(coord: Coordinate, val: [2]i16) Coordinate {
return .{ .val = .{ coord.val[0] + val[0], coord.val[1] + val[1] } };
}
pub fn sub(coord: Coordinate, val: [2]i16) Coordinate {
return .{ .val = .{ coord.val[0] - val[0], coord.val[1] - val[1] } };
}
pub fn addC(coord: Coordinate, other: Coordinate) Coordinate {
return .{ .val = .{ coord.val[0] + other.val[0], coord.val[1] + other.val[1] } };
}
pub fn subC(coord: Coordinate, other: Coordinate) Coordinate {
return .{ .val = .{ coord.val[0] - other.val[0], coord.val[1] - other.val[1] } };
}
pub fn addOffset(coord: Coordinate, val: [2]i4) Coordinate {
return .{ .val = .{ coord.val[0] + val[0], coord.val[1] + val[1] } };
}
pub fn eq(coord: Coordinate, other: Coordinate) bool {
return coord.val[0] == other.val[0] and coord.val[1] == other.val[1];
}
pub fn within(coord: Coord, nw: Coord, se: Coord) bool {
return coord.val[0] >= nw.val[0] and coord.val[1] >= nw.val[1] and
coord.val[0] < se.val[0] and coord.val[1] < se.val[1];
}
pub fn toWorld(coord: Coordinate) [2]i8 {
const world_x = @as(i8, @intCast(@divFloor(coord.val[0], LEVELSIZE)));
const world_y = @as(i8, @intCast(@divFloor(coord.val[1], LEVELSIZE)));
return .{ world_x, world_y };
}
pub fn toVec2(coord: Coordinate) @Vector(2, i32) {
return .{ coord.val[0], coord.val[1] };
}
pub fn toOffset(coord: Coordinate) [2]i4 {
return .{ @as(i4, @intCast(coord.val[0])), @as(i4, @intCast(coord.val[1])) };
}
pub fn fromWorld(x: i8, y: i8) Coordinate {
return .{ .val = .{
@as(i16, @intCast(x)) * 20,
@as(i16, @intCast(y)) * 20,
} };
}
pub fn fromVec2(vec: @Vector(2, i32)) Coordinate {
return .{ .val = .{ @as(i16, @intCast(vec[0])), @as(i16, @intCast(vec[1])) } };
}
pub fn fromVec2f(vec: @Vector(2, f32)) Coordinate {
return fromVec2(.{ @as(i32, @intFromFloat(vec[0])), @as(i32, @intFromFloat(vec[1])) });
}
pub fn toLevelTopLeft(coord: Coordinate) Coordinate {
const worldc = coord.toWorld();
return .{ .val = .{
@as(i16, @intCast(worldc[0])) * LEVELSIZE,
@as(i16, @intCast(worldc[1])) * LEVELSIZE,
} };
}
pub fn format(coord: Coordinate, comptime fmt: []const u8, options: std.fmt.FormatOptions, writer: anytype) !void {
_ = options;
if (fmt.len == 0 or comptime std.mem.eql(u8, fmt, "p")) {
return std.fmt.format(writer, "({d:>5},{d:>5})", .{ coord.val[0], coord.val[1] });
} else {
@compileError("Unknown format character: '" ++ fmt ++ "'");
}
}
};
pub const Direction = enum {
North,
West,
East,
South,
pub const each = [_]Direction{ .North, .West, .East, .South };
pub fn toOffset(dir: Direction) [2]i16 {
return switch (dir) {
.North => .{ 0, -1 },
.West => .{ -1, 0 },
.East => .{ 1, 0 },
.South => .{ 0, 1 },
};
}
pub fn getOpposite(dir: Direction) Direction {
return switch (dir) {
.North => .South,
.West => .East,
.East => .West,
.South => .North,
};
}
};
pub const Level = struct {
world_x: i8,
world_y: i8,
width: u16,
size: u16,
tiles: ?[]TileData,
pub fn init(x: i8, y: i8, width: u16, buf: []TileData) Level {
return Level{
.world_x = x,
.world_y = y,
.width = width,
.size = @as(u16, @intCast(buf.len)),
.tiles = buf,
};
}
pub fn calculateSize(level: Level) !usize {
const tiles = level.tiles orelse return error.NullTiles;
return @sizeOf(i8) + // world_x
@sizeOf(i8) + // world_y
@sizeOf(u16) + // width
@sizeOf(u16) + // size
tiles.len;
}
pub fn write(level: Level, writer: anytype) !void {
var tiles = level.tiles orelse return error.NullTiles;
try writer.writeInt(i8, level.world_x, .Little);
try writer.writeInt(i8, level.world_y, .Little);
try writer.writeInt(u16, level.width, .Little);
try writer.writeInt(u16, level.size, .Little);
for (tiles) |tile| {
try writer.writeByte(tile.toByte());
}
}
pub fn read(reader: anytype) !Level {
return Level{
.world_x = try reader.readInt(i8, .Little),
.world_y = try reader.readInt(i8, .Little),
.width = try reader.readInt(u16, .Little),
.size = try reader.readInt(u16, .Little),
.tiles = null,
};
}
pub fn readTiles(level: *Level, reader: anytype, buf: []TileData) !void {
std.debug.assert(buf.len >= level.size);
level.tiles = buf;
var i: usize = 0;
while (i < level.size) : (i += 1) {
buf[i] = TileData.fromByte(try reader.readByte());
}
}
pub fn getTile(level: Level, globalc: Coord) ?TileData {
const tiles = level.tiles orelse return null;
const worldc = globalc.toLevelTopLeft();
const se = worldc.add(.{ 20, 20 });
if (!globalc.within(worldc, se)) return null;
const x = globalc.val[0] - worldc.val[0];
const y = globalc.val[1] - worldc.val[1];
const w = @as(i32, @intCast(level.width));
const i = @as(usize, @intCast(x + y * w));
return tiles[i];
}
pub fn getCircuit(level: Level, globalc: Coord) ?CircuitType {
const tile = level.getTile(globalc) orelse return null;
return tile.getCircuit();
}
pub fn getJoin(level: Level, which: usize) ?Coordinate {
const tiles = level.tiles orelse return null;
var joinCount: usize = 0;
for (tiles, 0..) |tile, i| {
switch (tile) {
.flags => |flag| {
if (flag.circuit == .Join) {
if (joinCount == which) {
const x = @as(i16, @intCast(@mod(i, 20)));
const y = @as(i16, @intCast(@divFloor(i, 20)));
return Coord.init(.{ x, y });
}
joinCount += 1;
}
},
else => continue,
}
}
return null;
}
pub fn getSwitch(level: Level, which: usize) ?Coordinate {
const tiles = level.tiles orelse return null;
var switchCount: usize = 0;
for (tiles, 0..) |tile, i| {
switch (tile) {
.flags => |flag| {
if (flag.circuit == .Switch_Off or flag.circuit == .Switch_On) {
if (switchCount == which) {
const x = @as(i16, @intCast(@mod(i, 20)));
const y = @as(i16, @intCast(@divFloor(i, 20)));
return Coord.init(.{ x, y });
}
switchCount += 1;
}
},
else => continue,
}
}
return null;
}
};
// AutoTile algorithm datatypes
pub const AutoTile = packed struct {
North: bool,
West: bool,
East: bool,
South: bool,
pub fn to_u4(autotile: AutoTile) u4 {
return @as(u4, @bitCast(autotile));
}
pub fn from_u4(int: u4) AutoTile {
return @as(AutoTile, @bitCast(int));
}
};
pub const AutoTileset = struct {
lookup: []const u8 = "",
offset: u8 = 0,
kind: enum {
Cardinal,
Switches,
Full,
OffsetFull,
OffsetCardinal,
},
default: u8 = 0,
pub fn initFull(table: []const u8) AutoTileset {
std.debug.assert(table.len == 16);
return AutoTileset{
.lookup = table,
.kind = .Full,
};
}
pub fn initCardinal(table: []const u8, default: u8) AutoTileset {
std.debug.assert(table.len == 4);
return AutoTileset{
.lookup = table,
.kind = .Cardinal,
.default = default,
};
}
pub fn initSwitches(table: []const u8, default: u8) AutoTileset {
std.debug.assert(table.len == 3);
return AutoTileset{
.lookup = table,
.kind = .Switches,
.default = default,
};
}
pub fn initOffsetFull(offset: u8) AutoTileset {
// std.debug.assert(offset < 128 - 16);
return AutoTileset{
.offset = offset,
.kind = .OffsetFull,
};
}
pub fn initOffsetCardinal(offset: u8) AutoTileset {
// std.debug.assert(offset < 128 - 4);
return AutoTileset{
.offset = offset,
.kind = .OffsetCardinal,
};
}
pub fn find(tileset: AutoTileset, autotile: AutoTile) u8 {
const autoint = autotile.to_u4();
switch (tileset.kind) {
.Full => return tileset.lookup[autoint],
.OffsetFull => return tileset.offset + autoint,
.Cardinal, .OffsetCardinal => {
const index: u8 = switch (autoint) {
0b0001 => 0,
0b0010 => 1,
0b0100 => 2,
0b1000 => 3,
else => return tileset.default,
};
if (tileset.kind == .Cardinal) {
return tileset.lookup[index];
} else {
return tileset.offset + index;
}
},
.Switches => switch (autoint) {
0b1001 => return tileset.lookup[0],
0b1011 => return tileset.lookup[1],
0b1101 => return tileset.lookup[2],
else => return tileset.default,
},
}
}
};
pub const EntityKind = enum(u8) {
Player,
Coin,
Door,
Trapdoor,
Collected,
};
pub const Entity = struct {
kind: EntityKind,
coord: Coordinate,
pub fn calculateSize() usize {
return @sizeOf(u8) + // kind
@sizeOf(i16) + // x
@sizeOf(i16); // y
}
pub fn write(entity: Entity, writer: anytype) !void {
try writer.writeInt(u8, @intFromEnum(entity.kind), .Little);
try entity.coord.write(writer);
}
pub fn read(reader: anytype) !Entity {
return Entity{
.kind = @as(EntityKind, @enumFromInt(try reader.readInt(u8, .Little))),
.coord = try Coordinate.read(reader),
};
}
};
const WireKind = enum {
Begin,
BeginPinned,
Point,
PointPinned,
End,
};
/// A wire is stored as a coordinate and at least one point relative to it,
/// and then an end byte
pub const Wire = union(enum) {
Begin: Coordinate,
BeginPinned: Coordinate,
/// Relative to the last point
Point: [2]i4,
/// Relative to the last point
PointPinned: [2]i4,
End,
const EndData = struct { coord: Coordinate, anchored: bool };
pub fn getEnds(wires: []Wire) ![2]EndData {
std.debug.assert(wires[0] == .Begin or wires[0] == .BeginPinned);
var ends: [2]EndData = undefined;
for (wires) |wire| {
switch (wire) {
.Begin => |coord| {
ends[0] = .{ .coord = coord, .anchored = false };
ends[1] = ends[0];
},
.BeginPinned => |coord| {
ends[0] = .{ .coord = coord, .anchored = true };
ends[1] = ends[0];
},
.Point => |offset| {
ends[1] = .{ .coord = ends[1].coord.addOffset(offset), .anchored = false };
},
.PointPinned => |offset| {
ends[1] = .{ .coord = ends[1].coord.addOffset(offset), .anchored = true };
},
.End => {
return ends;
},
}
}
return error.MissingEnds;
}
pub fn write(wire: Wire, writer: anytype) !void {
try writer.writeByte(@intFromEnum(wire));
switch (wire) {
.Begin => |coord| {
try coord.write(writer);
},
.BeginPinned => |coord| {
try coord.write(writer);
},
.Point => |point| {
const byte = (@as(u8, @bitCast(@as(i8, @intCast(point[0])))) & 0b0000_1111) | (@as(u8, @bitCast(@as(i8, @intCast(point[1])))) & 0b1111_0000) << 4;
try writer.writeByte(byte);
},
.PointPinned => |point| {
const byte = (@as(u8, @bitCast(@as(i8, @intCast(point[0])))) & 0b0000_1111) | (@as(u8, @bitCast(@as(i8, @intCast(point[1])))) & 0b1111_0000) << 4;
try writer.writeByte(byte);
},
.End => {},
}
}
pub fn read(reader: anytype) !Wire {
const kind = @as(WireKind, @enumFromInt(try reader.readByte()));
switch (kind) {
.Begin => return Wire{ .Begin = try Coord.read(reader) },
.BeginPinned => return Wire{ .BeginPinned = try Coord.read(reader) },
.Point => {
const byte = try reader.readByte();
return Wire{ .Point = .{
@as(i4, @bitCast(@as(u4, @truncate(0b0000_1111 & byte)))),
@as(i4, @bitCast(@as(u4, @truncate((0b1111_0000 & byte) >> 4)))),
} };
},
.PointPinned => {
const byte = try reader.readByte();
return Wire{ .PointPinned = .{
@as(i4, @bitCast(@as(u4, @truncate(0b0000_1111 & byte)))),
@as(i4, @bitCast(@as(u4, @truncate((0b1111_0000 & byte) >> 4)))),
} };
},
.End => return Wire.End,
}
}
};
/// Used to look up level data
pub const LevelHeader = struct {
x: i8,
y: i8,
offset: u16,
pub fn write(header: LevelHeader, writer: anytype) !void {
try writer.writeInt(i8, header.x, .Little);
try writer.writeInt(i8, header.y, .Little);
try writer.writeInt(u16, header.offset, .Little);
}
pub fn read(reader: anytype) !LevelHeader {
return LevelHeader{
.x = try reader.readInt(i8, .Little),
.y = try reader.readInt(i8, .Little),
.offset = try reader.readInt(u16, .Little),
};
}
};
pub fn write(
writer: anytype,
level_headers: []LevelHeader,
entities: []Entity,
wires: []Wire,
circuit_nodes: []CircuitNode,
levels: []Level,
) !void {
// Write number of levels
try writer.writeInt(u16, @as(u16, @intCast(level_headers.len)), .Little);
// Write number of entities
try writer.writeInt(u16, @as(u16, @intCast(entities.len)), .Little);
// Write number of entities
try writer.writeInt(u16, @as(u16, @intCast(wires.len)), .Little);
// Write number of circuit nodes
try writer.writeInt(u16, @as(u16, @intCast(circuit_nodes.len)), .Little);
// Write headers
for (level_headers) |lvl_header| {
try lvl_header.write(writer);
}
// Write entity data
for (entities) |entity| {
try entity.write(writer);
}
// Write wire data
for (wires) |wire| {
try wire.write(writer);
}
// Write node data
for (circuit_nodes) |node| {
try node.write(writer);
}
// Write levels
for (levels) |level| {
try level.write(writer);
}
}
const Cursor = std.io.FixedBufferStream([]const u8);
pub const Database = struct {
cursor: Cursor,
level_info: []LevelHeader,
entities: []Entity,
wires: []Wire,
wire_count: usize,
circuit_info: []CircuitNode,
level_data_begin: usize,
const world_data = @embedFile(@import("world_data").path);
pub fn init(alloc: std.mem.Allocator) !Database {
var cursor = Cursor{
.pos = 0,
.buffer = world_data,
};
var reader = cursor.reader();
// read number of levels
const level_count = try reader.readInt(u16, .Little);
// read number of entities
const entity_count = try reader.readInt(u16, .Little);
// read number of wires
const wire_count = try reader.readInt(u16, .Little);
// read number of nodes
const node_count = try reader.readInt(u16, .Little);
var level_headers = try alloc.alloc(LevelHeader, level_count);
// read headers
for (level_headers, 0..) |_, i| {
level_headers[i] = try LevelHeader.read(reader);
}
// read entities
var entities = try alloc.alloc(Entity, entity_count);
for (entities, 0..) |_, i| {
entities[i] = try Entity.read(reader);
}
// read wires
// Allocate a fixed amount of space since wires are likely to be shuffled around
var wires = try alloc.alloc(Wire, 255);
{
var i: usize = 0;
while (i < wire_count) : (i += 1) {
wires[i] = try Wire.read(reader);
}
}
// read circuits
var circuit_nodes = try alloc.alloc(CircuitNode, node_count);
for (circuit_nodes, 0..) |_, i| {
circuit_nodes[i] = try CircuitNode.read(reader);
}
// Save where the rest of the data ended, and the level data begins
var level_data_begin = @as(usize, @intCast(try cursor.getPos()));
return Database{
.cursor = cursor,
.level_info = level_headers,
.entities = entities,
.wires = wires,
.wire_count = wire_count,
.circuit_info = circuit_nodes,
.level_data_begin = level_data_begin,
};
}
// Level functions
pub fn levelInfo(db: *Database, level: usize) !Level {
if (level > db.level_info.len) return error.InvalidLevel;
try db.cursor.seekTo(db.level_data_begin + db.level_info[level].offset);
const reader = db.cursor.reader();
return try Level.read(reader);
}
pub fn levelLoad(db: *Database, alloc: std.mem.Allocator, level: usize) !Level {
var level_info = try db.levelInfo(level);
const reader = db.cursor.reader();
var level_buf = try alloc.alloc(TileData, level_info.size);
try level_info.readTiles(reader, level_buf);
return level_info;
}
pub fn findLevel(db: *Database, x: i8, y: i8) ?usize {
for (db.level_info, 0..) |level, i| {
if (level.x == x and level.y == y) {
return i;
}
}
return null;
}
// Circuit functions
pub fn getNodeID(db: Database, coord: Coord) ?NodeID {
for (db.circuit_info, 0..) |node, i| {
if (!coord.eq(node.coord)) continue;
return @as(NodeID, @intCast(i));
}
return null;
}
pub fn getLevelNodeID(db: Database, level: Level, coord: Coord) ?NodeID {
const levelc = Coord.fromWorld(level.world_x, level.world_y);
return db.getNodeID(coord.addC(levelc));
}
pub fn connectPlugs(db: *Database, level: Level, p1: Coord, p2: Coord) !void {
const p1id = db.getLevelNodeID(level, p1) orelse return;
const p2id = db.getLevelNodeID(level, p2) orelse return;
if (db.circuit_info[p1id].kind == .Plug and db.circuit_info[p2id].kind == .Socket) {
db.circuit_info[p2id].kind.Socket = p1id;
} else if (db.circuit_info[p2id].kind == .Plug and db.circuit_info[p1id].kind == .Socket) {
db.circuit_info[p1id].kind.Socket = p2id;
} else if (db.circuit_info[p2id].kind == .Socket and db.circuit_info[p1id].kind == .Plug) {
return error.Unimplemented;
}
}
pub fn disconnectPlug(db: *Database, level: Level, plug1: Coord, plug2: Coord) void {
const levelc = Coord.fromWorld(level.world_x, level.world_y);
const coord1 = plug1.addC(levelc);
const coord2 = plug2.addC(levelc);
var found: usize = 0;
for (db.circuit_info, 0..) |node, i| {
if (!coord1.eq(node.coord) and !coord2.eq(node.coord)) continue;
found += 1;
if (db.circuit_info[i].kind == .Socket) {
db.circuit_info[i].kind.Socket = null;
db.circuit_info[i].energized = false;
break;
}
}
}
pub fn getSwitchState(db: *Database, coord: Coord) ?u8 {
const _switch = db.getNodeID(coord) orelse return null;
return db.circuit_info[_switch].kind.Switch.state;
}
pub fn setSwitch(db: *Database, coord: Coord, new_state: u8) void {
const _switch = db.getNodeID(coord) orelse return;
db.circuit_info[_switch].kind.Switch.state = new_state;
}
pub fn isEnergized(db: *Database, coord: Coord) bool {
for (db.circuit_info, 0..) |node, i| {
if (!coord.eq(node.coord)) continue;
return db.circuit_info[i].energized;
}
return false;
}
fn updateCircuitFragment(db: *Database, i: usize, visited: []bool) bool {
if (visited[i]) return db.circuit_info[i].energized;
visited[i] = true;
const node = db.circuit_info[i];
const w4 = @import("wasm4.zig");
switch (node.kind) {
.And => |And| {
w4.tracef("[updateCircuitFragment] %d And %d %d", i, And[0], And[1]);
const input1 = db.updateCircuitFragment(And[0], visited);
const input2 = db.updateCircuitFragment(And[1], visited);
db.circuit_info[i].energized = (input1 and input2);
},
.Xor => |Xor| {
w4.tracef("[updateCircuitFragment] %d Xor", i);
const input1 = db.updateCircuitFragment(Xor[0], visited);
const input2 = db.updateCircuitFragment(Xor[1], visited);
db.circuit_info[i].energized = (input1 and !input2) or (input2 and !input1);
},
.Source => db.circuit_info[i].energized = true,
.Conduit => |Conduit| {
w4.tracef("[updateCircuitFragment] %d Conduit", i);
const input1 = db.updateCircuitFragment(Conduit[0], visited);
const input2 = db.updateCircuitFragment(Conduit[1], visited);
db.circuit_info[i].energized = (input1 or input2);
},
// TODO: Sockets may come before the plug they are connected to
.Socket => |socket_opt| {
w4.tracef("[updateCircuitFragment] %d Socket", i);
if (socket_opt) |input| {
db.circuit_info[i].energized = db.updateCircuitFragment(input, visited);
} else {
db.circuit_info[i].energized = false;
}
},
.Plug => |Plug| {
w4.tracef("[updateCircuitFragment] %d Plug", i);
db.circuit_info[i].energized = db.updateCircuitFragment(Plug, visited);
},
.Switch => |_Switch| {
w4.tracef("[updateCircuitFragment] %d Switch %d", i, _Switch.source);
db.circuit_info[i].energized = db.updateCircuitFragment(_Switch.source, visited);
},
.SwitchOutlet => |_Switch| {
w4.tracef("[updateCircuitFragment] %d Switch Outlet", i);
const is_energized = db.updateCircuitFragment(_Switch.source, visited);
const _switch = db.circuit_info[_Switch.source].kind.Switch;
const _outlet = db.circuit_info[i].kind.SwitchOutlet;
// If the switch isn't energized, this outlet is not energized
if (is_energized) db.circuit_info[i].energized = false;
// If the switch is energized, check that it is outputting to this outlet
db.circuit_info[i].energized = _outlet.which == _switch.state;
},
.Join => |Join| {
w4.tracef("[updateCircuitFragment] %d Join", i);
db.circuit_info[i].energized = db.updateCircuitFragment(Join, visited);
},
.Outlet => |Outlet| {
w4.tracef("[updateCircuitFragment] %d Outlet", i);
db.circuit_info[i].energized = db.updateCircuitFragment(Outlet, visited);
},
}
w4.tracef("[updateCircuitFragment] %d end", i);
return db.circuit_info[i].energized;
}
pub fn updateCircuit(db: *Database, alloc: std.mem.Allocator) !void {
var visited = try alloc.alloc(bool, db.circuit_info.len);
defer alloc.free(visited);
std.mem.set(bool, visited, false);
var i: usize = db.circuit_info.len - 1;
const w4 = @import("wasm4.zig");
w4.tracef("[updateCircuit] circuit info len %d", db.circuit_info.len);
while (i > 0) : (i -|= 1) {
_ = db.updateCircuitFragment(i, visited);
if (i == 0) break;
}
}
// Entity functions
pub fn getEntityID(database: *Database, coord: Coordinate) ?usize {
for (database.entities, 0..) |entity, i| {
if (!entity.coord.eq(coord)) continue;
return i;
}
return null;
}
pub fn collectCoin(db: *Database, coord: Coordinate) void {
const coin = db.getEntityID(coord) orelse return;
db.entities[coin].kind = .Collected;
}
/// Remove a wire slice from the wires array. Invalidates handles returned from findWire
pub fn deleteWire(database: *Database, wire: [2]usize) void {
const w4 = @import("wasm4.zig");
const wire_size = wire[1] - wire[0];
if (wire[0] + wire_size == database.wire_count) {
database.wire_count -= wire_size;
return;
}
const wires_end = database.wires[wire[0] + wire_size .. database.wire_count];
const new_end = database.wires[wire[0] .. database.wire_count - wire_size];
w4.tracef("%d, %d, %d", wire_size, wires_end.len, new_end.len);
std.mem.copy(Wire, new_end, wires_end);
database.wire_count -= wire_size;
}
/// Retrieve the slice of the wire from findWire
pub fn getWire(database: *Database, wire: [2]usize) []Wire {
return database.wires[wire[0]..wire[1]];
}
/// Retrieve the slice of the wire from findWire
pub fn addWire(database: *Database, wire: []Wire) void {
const start = database.wire_count;
const end = start + wire.len;
std.mem.copy(Wire, database.wires[start..end], wire);
database.wire_count += wire.len;
}
/// Find a wire within the limits of a given level
pub fn findWire(database: *Database, level: Level, num: usize) ?[2]usize {
const nw = Coord.fromWorld(level.world_x, level.world_y);
const se = nw.add(.{ 20, 20 });
var node_begin: ?usize = null;
var wire_count: usize = 0;
var i: usize = 0;
while (i < database.wire_count) : (i += 1) {
const wire = database.wires[i];
switch (wire) {
.Begin => |coord| {
if (!coord.within(nw, se)) continue;
node_begin = i;
},
.BeginPinned => |coord| {
if (!coord.within(nw, se)) continue;
node_begin = i;
},
.Point, .PointPinned => continue,
.End => {
if (node_begin) |node| {
if (wire_count == num) {
return [2]usize{ node, i + 1 };
}
wire_count += 1;
node_begin = null;
}
},
}
}
return null;
}
pub fn getDoor(database: *Database, level: Level, num: usize) ?Entity {
const nw = Coord.fromWorld(level.world_x, level.world_y);
const se = nw.add(.{ 20, 20 });
var count: usize = 0;
for (database.entities) |entity| {
if (!entity.coord.within(nw, se)) continue;
if (entity.kind == .Door or entity.kind == .Trapdoor) {
if (count == num) return entity;
count += 1;
}
}
return null;
}
pub fn getCoin(database: *Database, level: Level, num: usize) ?Entity {
const nw = Coord.fromWorld(level.world_x, level.world_y);
const se = nw.add(.{ 20, 20 });
var count: usize = 0;
for (database.entities) |entity| {
if (!entity.coord.within(nw, se)) continue;
if (entity.kind == .Coin) {
if (count == num) return entity;
count += 1;
}
}
return null;
}
/// Returns the players spawn location.
/// Assumes a spawn exists and that there is only one of them
pub fn getSpawn(database: *Database) Entity {
for (database.entities) |entity| {
if (entity.kind == .Player) {
return entity;
}
}
@panic("No player spawn found! Invalid state");
}
};
// All levels in the game. If two rooms are next to each other, they
// are assumed to be neighbors. Leaving the screen will load in the next
// level in that direction. The player is placed at the same position
// vertically, but on the opposite side of the screen horizontally. Vice versa
// for vertically moving between screens. The player will retain their momentum.
//
// When a wire crosses a screen boundary, it will coil up at the player's feet
// automatically. If one side of the wire is pinned, the wire will be let go of.
//
// Alternatively, the wire will be pinned outside of the level. If it isn't pinned,
// I will need to freeze it and move it in a snake like fashion. Or just leave the
// other level loaded.
// levels: []Level,
// An abstract representation of all circuits in game.
// abstract_circuit: []CircuitNode,
pub const NodeID = u8;
pub const CircuitNode = struct {
energized: bool = false,
kind: NodeKind,
coord: Coordinate,
pub fn read(reader: anytype) !CircuitNode {
return CircuitNode{
.coord = try Coordinate.read(reader),
.kind = try NodeKind.read(reader),
};
}
pub fn write(node: CircuitNode, writer: anytype) !void {
try node.coord.write(writer);
try node.kind.write(writer);
}
pub fn format(node: CircuitNode, comptime fmt: []const u8, options: std.fmt.FormatOptions, writer: anytype) !void {
_ = options;
if (fmt.len != 0) @compileError("Unknown format character: '" ++ fmt ++ "'");
return std.fmt.format(writer, "{} {c} {}", .{
node.coord,
if (node.energized) @as(u8, '1') else @as(u8, '0'),
node.kind,
});
}
};
const NodeEnum = enum(u4) {
And,
Xor,
Source,
Conduit,
Plug,
Socket,
Switch,
SwitchOutlet,
Join,
Outlet,
};
pub const NodeKind = union(NodeEnum) {
/// An And logic gate
And: [2]NodeID,
/// A Xor logic gate
Xor: [2]NodeID,
/// This node is a source of power
Source,
/// Connects multiple nodes
Conduit: [2]NodeID,
/// A "male" receptacle. Wires attached can provide power to
/// a socket on the other end.
Plug: NodeID,
/// A "female" receptacle. Wires attached provide power from
/// a plug on the other side.
///
/// No visual difference from a plug.
Socket: ?NodeID,
/// A switch can be in one of five states, though only
/// two apply to any one switch.
/// Vertical = Off or Top/Bottom, depending on flow
/// Horizontal = Off or Left/Right, depending on flow
/// Tee = Top/Bottom or Left/Right, depending on flow
Switch: Switch,
/// Interface between a switch and other components. Each one
/// of these represents a possible outlet on a switch, and reads
/// the state of the switch to determine if it is powered or not
SwitchOutlet: SwitchOutlet,
/// Connection between levels
Join: NodeID,
/// Used to identify entities that recieve power, like doors
Outlet: NodeID,
pub const Switch = struct {
source: NodeID,
state: u8,
};
pub const SwitchOutlet = struct {
source: NodeID,
which: u8,
};
pub fn read(reader: anytype) !NodeKind {
var kind: NodeKind = undefined;
const nodeEnum = @as(NodeEnum, @enumFromInt(try reader.readInt(u8, .Little)));
switch (nodeEnum) {
.And => {
kind = .{ .And = .{
try reader.readInt(NodeID, .Little),
try reader.readInt(NodeID, .Little),
} };
},
.Xor => {
kind = .{ .Xor = .{
try reader.readInt(NodeID, .Little),
try reader.readInt(NodeID, .Little),
} };
},
.Source => kind = .Source,
.Conduit => {
kind = .{ .Conduit = .{
try reader.readInt(NodeID, .Little),
try reader.readInt(NodeID, .Little),
} };
},
.Socket => {
const socket = try reader.readInt(NodeID, .Little);
if (socket == std.math.maxInt(NodeID)) {
kind = .{ .Socket = null };
} else {
kind = .{ .Socket = socket };
}
},
.Plug => {
kind = .{ .Plug = try reader.readInt(NodeID, .Little) };
},
.Switch => {
kind = .{ .Switch = .{
.source = try reader.readInt(NodeID, .Little),
.state = try reader.readInt(u8, .Little),
} };
},
.SwitchOutlet => {
kind = .{ .SwitchOutlet = .{
.source = try reader.readInt(NodeID, .Little),
.which = try reader.readInt(u8, .Little),
} };
},
.Join => {
kind = .{ .Join = try reader.readInt(NodeID, .Little) };
},
.Outlet => {
kind = .{ .Outlet = try reader.readInt(NodeID, .Little) };
},
}
return kind;
}
pub fn write(kind: NodeKind, writer: anytype) !void {
try writer.writeInt(u8, @intFromEnum(kind), .Little);
switch (kind) {
.And => |And| {
try writer.writeInt(NodeID, And[0], .Little);
try writer.writeInt(NodeID, And[1], .Little);
},
.Xor => |Xor| {
try writer.writeInt(NodeID, Xor[0], .Little);
try writer.writeInt(NodeID, Xor[1], .Little);
},
.Source => {},
.Conduit => |Conduit| {
try writer.writeInt(NodeID, Conduit[0], .Little);
try writer.writeInt(NodeID, Conduit[1], .Little);
},
.Plug => |Plug| {
try writer.writeInt(NodeID, Plug, .Little);
},
.Socket => |Socket| {
const socket = Socket orelse std.math.maxInt(NodeID);
try writer.writeInt(NodeID, socket, .Little);
},
.Switch => |_Switch| {
try writer.writeInt(NodeID, _Switch.source, .Little);
try writer.writeInt(u8, _Switch.state, .Little);
},
.SwitchOutlet => |_Switch| {
try writer.writeInt(NodeID, _Switch.source, .Little);
try writer.writeInt(u8, _Switch.which, .Little);
},
.Join => |Join| {
try writer.writeInt(NodeID, Join, .Little);
},
.Outlet => |Outlet| {
try writer.writeInt(NodeID, Outlet, .Little);
},
}
}
pub fn format(kind: NodeKind, comptime fmt: []const u8, options: std.fmt.FormatOptions, writer: anytype) !void {
_ = options;
if (fmt.len != 0) @compileError("Unknown format character: '" ++ fmt ++ "'");
const name = @tagName(kind);
return switch (kind) {
.Conduit => |Conduit| std.fmt.format(writer, "{s} [{}, {}]", .{ name, Conduit[0], Conduit[1] }),
.And => |And| std.fmt.format(writer, "{s} [{}, {}]", .{ name, And[0], And[1] }),
.Xor => |Xor| std.fmt.format(writer, "{s} [{}, {}]", .{ name, Xor[0], Xor[1] }),
.Source => std.fmt.format(writer, "{s}", .{name}),
.Plug => |Plug| std.fmt.format(writer, "{s} [{}]", .{ name, Plug }),
.Socket => |Socket| std.fmt.format(writer, "{s} [{?}]", .{ name, Socket }),
.Switch => |_Switch| std.fmt.format(writer, "{s} <{}> [{}]", .{ name, _Switch.state, _Switch.source }),
.SwitchOutlet => |_Switch| std.fmt.format(writer, "{s} <{}> [{}]", .{ name, _Switch.which, _Switch.source }),
.Join => |Join| std.fmt.format(writer, "{s} [{}]", .{ name, Join }),
.Outlet => |Outlet| std.fmt.format(writer, "{s} [{}]", .{ name, Outlet }),
};
}
};
|
Subsets and Splits
No saved queries yet
Save your SQL queries to embed, download, and access them later. Queries will appear here once saved.