code
stringlengths 38
801k
| repo_path
stringlengths 6
263
|
---|---|
const std = @import("std");
const zs = @import("zstack.zig");
pub const LockStyle = enum {
/// Lock delay is reset on entry of new piece.
Entry,
/// Lock delay is reset on downwards movement.
Step,
/// Lock delay is reset on any successful movement.
Move,
};
pub const InitialActionStyle = enum {
/// IHS/IRS is disabled.
None,
/// Can be triggered from last frame action.
Persistent,
/// Must get new event to trigger.
Trigger,
};
// Options are things that are runtime-configurable by the user for a specific game.
pub const Options = struct {
seed: ?u32 = null,
well_width: u8 = 10,
well_height: u8 = 22,
well_hidden: u8 = 2,
das_speed_ms: u16 = 0,
das_delay_ms: u16 = 150,
are_delay_ms: u16 = 0,
warn_on_bad_finesse: bool = false,
are_cancellable: bool = false,
lock_style: LockStyle = .Move,
lock_delay_ms: u32 = 150,
floorkick_limit: u32 = 1,
one_shot_soft_drop: bool = false,
rotation_system: zs.RotationSystem.Id = .srs,
initial_action_style: InitialActionStyle = .None,
gravity_ms_per_cell: u32 = 1000,
soft_drop_gravity_ms_per_cell: u32 = 200,
randomizer: zs.Randomizer.Id = .bag7seamcheck,
ready_phase_length_ms: u32 = 833,
go_phase_length_ms: u32 = 833,
infinite_ready_go_hold: bool = false,
preview_piece_count: u8 = 4,
goal: u32 = 40,
show_ghost: bool = true,
// Some options have tighter bounds than their types suggest. Verify the invariants
// hold for all values.
pub fn verify(options: *Options) bool {
if (options.well_width > zs.max_well_width) {
return false;
}
if (options.well_height > zs.max_well_height) {
return false;
}
if (options.preview_piece_count > zs.max_preview_count) {
return false;
}
return true;
}
};
fn toUpper(c: u8) u8 {
return if (c -% 'a' < 26) c & 0x5f else c;
}
fn eqli(a: []const u8, b: []const u8) bool {
if (a.len != b.len) return false;
for (a) |_, i| {
if (toUpper(a[i]) != toUpper(b[i])) {
return false;
}
}
return true;
}
// NOTE: This method can be be performed in the json parser to deserialize directly into
// types.
fn deserializeValue(dest: var, key: []const u8, value: []const u8) !void {
const T = @typeOf(dest).Child;
// Workaround since above errors at comptime, the above may be known completely and the branches
// will not be analyzed, thus no errors will be returned and a compile error will occur
// indicating that no inferred errors were found.
// TODO: Use explicit error set, is there a std.meta function to get error set value from func def?
if (zs.utility.forceRuntime(bool, false)) {
return error.Unreachable;
}
switch (@typeInfo(T)) {
// TODO: Handle fixed array type with length, iterate over, split by comma.
.Optional => |optional| {
if (eqli(value, "null")) {
dest.* = null;
} else {
try deserializeValue(@ptrCast(*optional.child, dest), key, value);
}
},
.Enum => |e| {
inline for (e.fields) |field| {
if (eqli(value, field.name)) {
dest.* = @intToEnum(T, field.value);
break;
}
} else {
return error.UnknownEnumEntry;
}
},
.Int => {
dest.* = try std.fmt.parseInt(T, value, 10);
},
.Bool => {
if (eqli(value, "true") or eqli(value, "yes") or eqli(value, "1")) {
dest.* = true;
} else if (eqli(value, "false") or eqli(value, "no") or eqli(value, "0")) {
dest.* = false;
} else {
return error.UnknownBoolValue;
}
},
else => {
@panic("unsupported deserialization type: " ++ @typeName(T));
},
}
}
fn processOption(
options: *Options,
keybindings: *zs.input.KeyBindings,
ui_options: var,
group: []const u8,
key: []const u8,
value: []const u8,
) !void {
if (eqli(group, "game")) {
inline for (@typeInfo(Options).Struct.fields) |field| {
if (eqli(key, field.name)) {
try deserializeValue(&@field(options, field.name), key, value);
}
}
} else if (eqli(group, "keybind")) {
inline for (@typeInfo(zs.input.KeyBindings).Struct.fields) |field| {
if (eqli(key, field.name)) {
try deserializeValue(&@field(keybindings, field.name), key, value);
}
}
} else if (eqli(group, "ui")) {
// TODO: Handle specific group names so multiple ui options can be configured? Or ignore non-useful?
inline for (@typeInfo(zs.window.Options).Struct.fields) |field| {
if (eqli(key, field.name)) {
try deserializeValue(&@field(ui_options, field.name), key, value);
}
}
} else {
std.debug.warn("unknown group: {}.{} = {}\n", group, key, value);
}
}
var buffer: [8192]u8 = undefined;
var fixed_buffer_allocator = std.heap.FixedBufferAllocator.init(buffer[0..]);
var allocator = &fixed_buffer_allocator.allocator;
pub fn loadFromIniFile(
options: *Options,
keybindings: *zs.input.KeyBindings,
ui_options: var,
ini_filename: []const u8,
) !void {
const ini_contents = try std.io.readFileAlloc(allocator, ini_filename);
defer allocator.free(ini_contents);
try parseIni(options, keybindings, ui_options, ini_contents);
}
pub fn parseIni(
options: *Options,
keybindings: *zs.input.KeyBindings,
ui_options: var,
ini: []const u8,
) !void {
const max_group_key_length = 64;
const whitespace = " \t";
var group_storage: [max_group_key_length]u8 = undefined;
var group = group_storage[0..0];
var lines = std.mem.separate(ini, "\n");
while (lines.next()) |line| {
if (line.len == 0 or line[0] == ';' or line[0] == '#') continue;
var line_it = std.mem.trimLeft(u8, line, whitespace);
if (line_it.len == 0) continue;
switch (line_it[0]) {
// [group.key]
'[' => {
line_it = line_it[1..]; // skip '['
line_it = std.mem.trimLeft(u8, line_it, whitespace);
const maybe_group_end = std.mem.indexOfScalar(u8, line_it, ']');
if (maybe_group_end == null) {
return error.UnmatchedBracket;
}
const group_key = line_it[0..maybe_group_end.?];
if (group_key.len > max_group_key_length) {
return error.KeyIsToolarge;
}
std.mem.copy(u8, group_storage[0..], group_key);
group = group_storage[0..group_key.len];
},
// k=v
else => {
const maybe_end_of_key = std.mem.indexOfScalar(u8, line_it, '=');
if (maybe_end_of_key == null) {
return error.MissingEqualFromKeyValue;
}
if (maybe_end_of_key.? == 0) {
return error.MissingKey;
}
const key = std.mem.trimRight(u8, line_it[0..maybe_end_of_key.?], whitespace);
line_it = line_it[maybe_end_of_key.? + 1 ..];
const value = std.mem.trim(u8, line_it, whitespace);
try processOption(options, keybindings, ui_options, group, key, value);
},
}
}
if (!options.verify()) {
return error.InvalidOptions;
}
}
test "parseIni" {
const example_ini =
\\; zstack config
\\; ================
\\;
\\; Note:
\\; * All values are case-insensitive.
\\;
\\; * Values specified in ms are usually rounded up to the nearest multiple
\\; of the tick rate.
\\
\\
\\[keybind]
\\
\\rotate_left = z
\\rotate_right = x
\\rotate_180= a
\\left = left
\\right = right
\\down = down
\\up = space
\\hold = c
\\quit = q
\\restart = rshift
\\
\\
\\[game]
\\
\\
\\; Which randomizer to use.
\\;
\\; simple - Memoryless
\\; bag6 - Bag of length 6
\\; bag7 - Standard Bag (default)
\\; bag7-seam - Standard Bag \w Seam Check
\\; bag14 - Double bag
\\; bag28 - Quadruple bag
\\; bag63 - Nontuple bag
\\; tgm1 - TGM1
\\; tgm2 - TGM2
\\; tgm3 - TGM3
\\randomizer = tgm3
\\
\\; Which rotation system to use.
\\;
\\; simple - Sega Rotation; No wallkicks
\\; sega - Sega Rotation
\\; srs - Super Rotation System (default)
\\; arikasrs - SRS \w symmetric I wallkick
\\; tgm12 - Sega Rotation; Symmetric Wallkicks
\\; tgm3 - tgm12 \w I floorkicks
\\; dtet - Sega Rotation; Simple Symmetric Wallkicks
\\rotation_system = srs
\\
\\; How many blocks gravity will cause the piece to fall every ms.
\\;
\\; To convert G's to this form, divide input by 17 and multiply by 10e6.
\\; i.e. 20G = 20 / 17 * 1000000 = 1127000.
\\gravity = 625
\\
\\; How many blocks soft drop will cause the piece to fall every ms.
\\; (multiplied by 10e6).
\\soft_drop_gravity = 5000000
\\
\\; Whether a sound should be played on bad finesse
\\warn_on_bad_finesse = false
\\
\\; Delay (in ms) between piece placement and piece spawn.
\\are_delay = 0
\\
\\; Whether ARE delay be cancelled on user input.
\\are_cancellable = false
\\
\\; Delay (in ms) before a piece begins to auto shift.
\\das_delay = 150
\\
\\; Number of blocks to move per ms during DAS (0 = infinite)
\\das_speed = 0
\\
\\; Delay (in ms) before a piece locks.
\\lock_delay_ms = 150
\\
\\; How many floorkicks can be performed before the piece locks. (0 = infinite)
\\floorkick_limit = 1
\\
\\; Behaviour used for initial actions (IRS/IHS).
\\;
\\; none - IRS/IHS disabled (default)
\\; persistent - Triggered solely by current keystate
\\; trigger - Explicit new event required (unimplemented)
\\initial_action_style = none
\\
\\; Behaviour used for lock reset.
\\;
\\; entry - Reset only on new piece spawn
\\; step - Reset on downward movement
\\; move - Reset on any succssful movement/rotation (default)
\\lock_style = move
\\
\\; Whether soft drop is held through new piece spawns.
\\;
\\; Note: The current implementation only works properly with 'softDropGravity'
\\; set to instant (above 2).
\\one_shot_soft_drop = true
\\
\\; Period at which the draw phase is performed.
\\ticks_per_draw = 2
\\
\\; Width of the play field.
\\field_width = 10
\\
\\; Height of the playfield.
\\field_height = 22
\\
\\; Number of hidden rows
\\field_hidden = 2
\\
\\; Whether we can hold as many times as we want during pre-game.
\\infinite_ready_go_hold = true
\\
\\; Length (in ms) of the Ready phase.
\\ready_phase_length_ms = 833
\\
\\; Length (in ms) of the Go phase.
\\go_phase_length_ms = 833
\\
\\; Number of preview pieces to display (max 4).
\\preview_piece_count = 2
\\
\\; Target number of lines to clear.
\\goal = 40
\\
\\
\\[frontend.sdl2]
\\
\\; Width of the display window
\\width = 800
\\
\\; Height of the display window
\\height = 600
\\
\\; Show the debug screen during execution
\\show_debug = false
\\
\\
\\[frontend.terminal]
\\
\\; Glyphs to use when drawing to screen
\\;
\\; ascii - Use only characters only from the ascii charset (default)
\\; unicode - Use unicode box-drawing chars for borders
\\glyphs = unicode
\\
\\; Center the field in the middle of the window.
\\;
\\; If not set, the field will be drawn from the top-left corner of the screen.
\\center_field = true
\\
\\; Should the field be colored or a single palette?
\\colored_field = false
;
var options = Options.default();
var ui_options = zs.window.Options.default();
var keys = zs.input.KeyBindings.default();
try parseIni(&options, &keys, &ui_options, example_ini);
}
test "parseIni k=v no space" {
const example_ini =
\\[game]
\\goal=10
\\seed=15
\\
;
var options = Options.default();
var ui_options = zs.window.Options.default();
var keys = zs.input.KeyBindings.default();
try parseIni(&options, &keys, &ui_options, example_ini);
std.testing.expectEqual(options.goal, 10);
std.testing.expectEqual(options.seed, 15);
} | src/config.zig |
usingnamespace @import("Zig-PSP/src/psp/include/pspge.zig");
usingnamespace @import("Zig-PSP/src/psp/include/psputils.zig");
usingnamespace @import("Zig-PSP/src/psp/utils/psp.zig");
usingnamespace @import("Zig-PSP/src/psp/include/pspdisplay.zig");
var draw_buffer: ?[*]u32 = null;
var disp_buffer: ?[*]u32 = null;
pub fn init() void{
draw_buffer = @intToPtr(?[*]u32, @ptrToInt(sceGeEdramGetAddr()));
disp_buffer = @intToPtr(?[*]u32, @ptrToInt(sceGeEdramGetAddr()) + (272 * SCR_BUF_WIDTH * 4));
_ = sceDisplaySetMode(0, SCREEN_WIDTH, SCREEN_HEIGHT);
_ = sceDisplaySetFrameBuf(disp_buffer, SCR_BUF_WIDTH, @enumToInt(PspDisplayPixelFormats.Format8888), 1);
}
pub fn drawRect(x : usize, y : usize, w : usize, h : usize, color : u32) void{
var x0 = x;
var y0 = y;
var w0 = w;
var h0 = h;
if(x0 > 480){
x0 = 480;
}
if(y0 > 272){
y0 = 272;
}
if( (x0 + w0) > 480){
w0 = 480 - x0;
}
if( (y0 + h0) > 272){
h0 = 272 - y0;
}
var off : usize = x0 + (y0 * SCR_BUF_WIDTH);
var y1 : usize = 0;
while(y1 < h0) : (y1 += 1){
var x1 : usize = 0;
while(x1 < w0) : (x1 += 1){
draw_buffer.?[x1 + off + y1 * SCR_BUF_WIDTH] = color;
}
}
}
pub fn swapBuffers() void{
var temp : ?[*]u32 = disp_buffer;
disp_buffer = draw_buffer;
draw_buffer = temp;
sceKernelDcacheWritebackInvalidateAll();
_ = sceDisplaySetFrameBuf(disp_buffer, SCR_BUF_WIDTH, @enumToInt(PspDisplayPixelFormats.Format8888), @enumToInt(PspDisplaySetBufSync.Nextframe));
}
pub fn clear(color : u32) void {
var i: usize = 0;
while (i < SCR_BUF_WIDTH * SCREEN_HEIGHT) : (i += 1) {
draw_buffer.?[i] = color;
}
}
//Print out a constant string
pub fn print(x : u32, y : u32, text: []const u8, color: u32) void {
var i : usize = 0;
while(i < text.len) : (i += 1){
internal_putchar(@as(u32,x), @as(u32,y+i*32), text[i], color);
}
}
const dbg = @import("Zig-PSP/src/psp/utils/debug.zig");
fn internal_putchar(cx: u32, cy: u32, ch: u8, color : u32) void{
var off : usize = (511 - cx) + (cy * SCR_BUF_WIDTH);
var i : usize = 0;
while (i < 32) : (i += 1){
var j: usize = 0;
while(j < 32) : (j += 1){
const mask : u32 = 128;
var idx : u32 = @as(u32, ch - 32) * 8 + j / 4;
var glyph : u8 = dbg.msxFont[idx];
if( (glyph & (mask >> @intCast(@import("std").math.Log2Int(c_int), i/4))) != 0 ){
draw_buffer.?[(480 - j) + (i) * SCR_BUF_WIDTH + off] = color;
}
}
}
} | src/gfx.zig |
const xcb = @import("../xcb.zig");
pub const id = xcb.Extension{ .name = "XpExtension", .global_id = 0 };
pub const STRING8 = u8;
/// @brief PRINTER
pub const PRINTER = struct {
@"nameLen": u32,
@"name": []xcb.xprint.STRING8,
@"descLen": u32,
@"description": []xcb.xprint.STRING8,
};
pub const PCONTEXT = u32;
pub const GetDoc = extern enum(c_uint) {
@"Finished" = 0,
@"SecondConsumer" = 1,
};
pub const EvMask = extern enum(c_uint) {
@"NoEventMask" = 0,
@"PrintMask" = 1,
@"AttributeMask" = 2,
};
pub const Detail = extern enum(c_uint) {
@"StartJobNotify" = 1,
@"EndJobNotify" = 2,
@"StartDocNotify" = 3,
@"EndDocNotify" = 4,
@"StartPageNotify" = 5,
@"EndPageNotify" = 6,
};
pub const Attr = extern enum(c_uint) {
@"JobAttr" = 1,
@"DocAttr" = 2,
@"PageAttr" = 3,
@"PrinterAttr" = 4,
@"ServerAttr" = 5,
@"MediumAttr" = 6,
@"SpoolerAttr" = 7,
};
/// @brief PrintQueryVersioncookie
pub const PrintQueryVersioncookie = struct {
sequence: c_uint,
};
/// @brief PrintQueryVersionRequest
pub const PrintQueryVersionRequest = struct {
@"major_opcode": u8,
@"minor_opcode": u8 = 0,
@"length": u16,
};
/// @brief PrintQueryVersionReply
pub const PrintQueryVersionReply = struct {
@"response_type": u8,
@"pad0": u8,
@"sequence": u16,
@"length": u32,
@"major_version": u16,
@"minor_version": u16,
};
/// @brief PrintGetPrinterListcookie
pub const PrintGetPrinterListcookie = struct {
sequence: c_uint,
};
/// @brief PrintGetPrinterListRequest
pub const PrintGetPrinterListRequest = struct {
@"major_opcode": u8,
@"minor_opcode": u8 = 1,
@"length": u16,
@"printerNameLen": u32,
@"localeLen": u32,
@"printer_name": []const xcb.xprint.STRING8,
@"locale": []const xcb.xprint.STRING8,
};
/// @brief PrintGetPrinterListReply
pub const PrintGetPrinterListReply = struct {
@"response_type": u8,
@"pad0": u8,
@"sequence": u16,
@"length": u32,
@"listCount": u32,
@"pad1": [20]u8,
@"printers": []xcb.xprint.PRINTER,
};
/// @brief PrintRehashPrinterListRequest
pub const PrintRehashPrinterListRequest = struct {
@"major_opcode": u8,
@"minor_opcode": u8 = 20,
@"length": u16,
};
/// @brief CreateContextRequest
pub const CreateContextRequest = struct {
@"major_opcode": u8,
@"minor_opcode": u8 = 2,
@"length": u16,
@"context_id": u32,
@"printerNameLen": u32,
@"localeLen": u32,
@"printerName": []const xcb.xprint.STRING8,
@"locale": []const xcb.xprint.STRING8,
};
/// @brief PrintSetContextRequest
pub const PrintSetContextRequest = struct {
@"major_opcode": u8,
@"minor_opcode": u8 = 3,
@"length": u16,
@"context": u32,
};
/// @brief PrintGetContextcookie
pub const PrintGetContextcookie = struct {
sequence: c_uint,
};
/// @brief PrintGetContextRequest
pub const PrintGetContextRequest = struct {
@"major_opcode": u8,
@"minor_opcode": u8 = 4,
@"length": u16,
};
/// @brief PrintGetContextReply
pub const PrintGetContextReply = struct {
@"response_type": u8,
@"pad0": u8,
@"sequence": u16,
@"length": u32,
@"context": u32,
};
/// @brief PrintDestroyContextRequest
pub const PrintDestroyContextRequest = struct {
@"major_opcode": u8,
@"minor_opcode": u8 = 5,
@"length": u16,
@"context": u32,
};
/// @brief PrintGetScreenOfContextcookie
pub const PrintGetScreenOfContextcookie = struct {
sequence: c_uint,
};
/// @brief PrintGetScreenOfContextRequest
pub const PrintGetScreenOfContextRequest = struct {
@"major_opcode": u8,
@"minor_opcode": u8 = 6,
@"length": u16,
};
/// @brief PrintGetScreenOfContextReply
pub const PrintGetScreenOfContextReply = struct {
@"response_type": u8,
@"pad0": u8,
@"sequence": u16,
@"length": u32,
@"root": xcb.WINDOW,
};
/// @brief PrintStartJobRequest
pub const PrintStartJobRequest = struct {
@"major_opcode": u8,
@"minor_opcode": u8 = 7,
@"length": u16,
@"output_mode": u8,
};
/// @brief PrintEndJobRequest
pub const PrintEndJobRequest = struct {
@"major_opcode": u8,
@"minor_opcode": u8 = 8,
@"length": u16,
@"cancel": u8,
};
/// @brief PrintStartDocRequest
pub const PrintStartDocRequest = struct {
@"major_opcode": u8,
@"minor_opcode": u8 = 9,
@"length": u16,
@"driver_mode": u8,
};
/// @brief PrintEndDocRequest
pub const PrintEndDocRequest = struct {
@"major_opcode": u8,
@"minor_opcode": u8 = 10,
@"length": u16,
@"cancel": u8,
};
/// @brief PrintPutDocumentDataRequest
pub const PrintPutDocumentDataRequest = struct {
@"major_opcode": u8,
@"minor_opcode": u8 = 11,
@"length": u16,
@"drawable": xcb.DRAWABLE,
@"len_data": u32,
@"len_fmt": u16,
@"len_options": u16,
@"data": []const u8,
@"doc_format": []const xcb.xprint.STRING8,
@"options": []const xcb.xprint.STRING8,
};
/// @brief PrintGetDocumentDatacookie
pub const PrintGetDocumentDatacookie = struct {
sequence: c_uint,
};
/// @brief PrintGetDocumentDataRequest
pub const PrintGetDocumentDataRequest = struct {
@"major_opcode": u8,
@"minor_opcode": u8 = 12,
@"length": u16,
@"context": xcb.xprint.PCONTEXT,
@"max_bytes": u32,
};
/// @brief PrintGetDocumentDataReply
pub const PrintGetDocumentDataReply = struct {
@"response_type": u8,
@"pad0": u8,
@"sequence": u16,
@"length": u32,
@"status_code": u32,
@"finished_flag": u32,
@"dataLen": u32,
@"pad1": [12]u8,
@"data": []u8,
};
/// @brief PrintStartPageRequest
pub const PrintStartPageRequest = struct {
@"major_opcode": u8,
@"minor_opcode": u8 = 13,
@"length": u16,
@"window": xcb.WINDOW,
};
/// @brief PrintEndPageRequest
pub const PrintEndPageRequest = struct {
@"major_opcode": u8,
@"minor_opcode": u8 = 14,
@"length": u16,
@"cancel": u8,
@"pad0": [3]u8,
};
/// @brief PrintSelectInputRequest
pub const PrintSelectInputRequest = struct {
@"major_opcode": u8,
@"minor_opcode": u8 = 15,
@"length": u16,
@"context": xcb.xprint.PCONTEXT,
@"event_mask": u32,
};
/// @brief PrintInputSelectedcookie
pub const PrintInputSelectedcookie = struct {
sequence: c_uint,
};
/// @brief PrintInputSelectedRequest
pub const PrintInputSelectedRequest = struct {
@"major_opcode": u8,
@"minor_opcode": u8 = 16,
@"length": u16,
@"context": xcb.xprint.PCONTEXT,
};
/// @brief PrintInputSelectedReply
pub const PrintInputSelectedReply = struct {
@"response_type": u8,
@"pad0": u8,
@"sequence": u16,
@"length": u32,
@"event_mask": u32,
@"all_events_mask": u32,
};
/// @brief PrintGetAttributescookie
pub const PrintGetAttributescookie = struct {
sequence: c_uint,
};
/// @brief PrintGetAttributesRequest
pub const PrintGetAttributesRequest = struct {
@"major_opcode": u8,
@"minor_opcode": u8 = 17,
@"length": u16,
@"context": xcb.xprint.PCONTEXT,
@"pool": u8,
@"pad0": [3]u8,
};
/// @brief PrintGetAttributesReply
pub const PrintGetAttributesReply = struct {
@"response_type": u8,
@"pad0": u8,
@"sequence": u16,
@"length": u32,
@"stringLen": u32,
@"pad1": [20]u8,
@"attributes": []xcb.xprint.STRING8,
};
/// @brief PrintGetOneAttributescookie
pub const PrintGetOneAttributescookie = struct {
sequence: c_uint,
};
/// @brief PrintGetOneAttributesRequest
pub const PrintGetOneAttributesRequest = struct {
@"major_opcode": u8,
@"minor_opcode": u8 = 19,
@"length": u16,
@"context": xcb.xprint.PCONTEXT,
@"nameLen": u32,
@"pool": u8,
@"pad0": [3]u8,
@"name": []const xcb.xprint.STRING8,
};
/// @brief PrintGetOneAttributesReply
pub const PrintGetOneAttributesReply = struct {
@"response_type": u8,
@"pad0": u8,
@"sequence": u16,
@"length": u32,
@"valueLen": u32,
@"pad1": [20]u8,
@"value": []xcb.xprint.STRING8,
};
/// @brief PrintSetAttributesRequest
pub const PrintSetAttributesRequest = struct {
@"major_opcode": u8,
@"minor_opcode": u8 = 18,
@"length": u16,
@"context": xcb.xprint.PCONTEXT,
@"stringLen": u32,
@"pool": u8,
@"rule": u8,
@"pad0": [2]u8,
@"attributes": []const xcb.xprint.STRING8,
};
/// @brief PrintGetPageDimensionscookie
pub const PrintGetPageDimensionscookie = struct {
sequence: c_uint,
};
/// @brief PrintGetPageDimensionsRequest
pub const PrintGetPageDimensionsRequest = struct {
@"major_opcode": u8,
@"minor_opcode": u8 = 21,
@"length": u16,
@"context": xcb.xprint.PCONTEXT,
};
/// @brief PrintGetPageDimensionsReply
pub const PrintGetPageDimensionsReply = struct {
@"response_type": u8,
@"pad0": u8,
@"sequence": u16,
@"length": u32,
@"width": u16,
@"height": u16,
@"offset_x": u16,
@"offset_y": u16,
@"reproducible_width": u16,
@"reproducible_height": u16,
};
/// @brief PrintQueryScreenscookie
pub const PrintQueryScreenscookie = struct {
sequence: c_uint,
};
/// @brief PrintQueryScreensRequest
pub const PrintQueryScreensRequest = struct {
@"major_opcode": u8,
@"minor_opcode": u8 = 22,
@"length": u16,
};
/// @brief PrintQueryScreensReply
pub const PrintQueryScreensReply = struct {
@"response_type": u8,
@"pad0": u8,
@"sequence": u16,
@"length": u32,
@"listCount": u32,
@"pad1": [20]u8,
@"roots": []xcb.WINDOW,
};
/// @brief PrintSetImageResolutioncookie
pub const PrintSetImageResolutioncookie = struct {
sequence: c_uint,
};
/// @brief PrintSetImageResolutionRequest
pub const PrintSetImageResolutionRequest = struct {
@"major_opcode": u8,
@"minor_opcode": u8 = 23,
@"length": u16,
@"context": xcb.xprint.PCONTEXT,
@"image_resolution": u16,
};
/// @brief PrintSetImageResolutionReply
pub const PrintSetImageResolutionReply = struct {
@"response_type": u8,
@"status": u8,
@"sequence": u16,
@"length": u32,
@"previous_resolutions": u16,
};
/// @brief PrintGetImageResolutioncookie
pub const PrintGetImageResolutioncookie = struct {
sequence: c_uint,
};
/// @brief PrintGetImageResolutionRequest
pub const PrintGetImageResolutionRequest = struct {
@"major_opcode": u8,
@"minor_opcode": u8 = 24,
@"length": u16,
@"context": xcb.xprint.PCONTEXT,
};
/// @brief PrintGetImageResolutionReply
pub const PrintGetImageResolutionReply = struct {
@"response_type": u8,
@"pad0": u8,
@"sequence": u16,
@"length": u32,
@"image_resolution": u16,
};
/// Opcode for Notify.
pub const NotifyOpcode = 0;
/// @brief NotifyEvent
pub const NotifyEvent = struct {
@"response_type": u8,
@"detail": u8,
@"sequence": u16,
@"context": xcb.xprint.PCONTEXT,
@"cancel": u8,
};
/// Opcode for AttributNotify.
pub const AttributNotifyOpcode = 1;
/// @brief AttributNotifyEvent
pub const AttributNotifyEvent = struct {
@"response_type": u8,
@"detail": u8,
@"sequence": u16,
@"context": xcb.xprint.PCONTEXT,
};
/// Opcode for BadContext.
pub const BadContextOpcode = 0;
/// @brief BadContextError
pub const BadContextError = struct {
@"response_type": u8,
@"error_code": u8,
@"sequence": u16,
};
/// Opcode for BadSequence.
pub const BadSequenceOpcode = 1;
/// @brief BadSequenceError
pub const BadSequenceError = struct {
@"response_type": u8,
@"error_code": u8,
@"sequence": u16,
};
test "" {
@import("std").testing.refAllDecls(@This());
} | src/auto/xprint.zig |
const std = @import("std");
const audiometa = @import("audiometa");
const Allocator = std.mem.Allocator;
const build_options = @import("build_options");
pub const log_level: std.log.Level = .warn;
pub export fn main() void {
zigMain() catch unreachable;
}
pub fn zigMain() !void {
var gpa = std.heap.GeneralPurposeAllocator(.{}){};
defer std.debug.assert(gpa.deinit() == false);
const gpa_allocator = gpa.allocator();
const stdin = std.io.getStdIn();
const data = try stdin.readToEndAlloc(gpa_allocator, std.math.maxInt(usize));
defer gpa_allocator.free(data);
// use a hash of the data as the initial failing index, this will
// almost certainly be way too large initially but we'll fix that after
// the first iteration
var failing_index: usize = std.hash.CityHash32.hash(data);
var should_have_failed = false;
while (true) : (should_have_failed = true) {
var failing_allocator = std.testing.FailingAllocator.init(gpa_allocator, failing_index);
// need to reset the stream_source each time to ensure that we're reading
// from the start each iteration
var stream_source = std.io.StreamSource{ .buffer = std.io.fixedBufferStream(data) };
// when debugging, it helps a lot to get the context of where the failing alloc
// actually occured, so further wrap the failing allocator to get a stack
// trace at the point of the OutOfMemory return.
var allocator: Allocator = allocator: {
// However, this will fail in the AFL-compiled version because it
// panics when trying to print a stack trace, so only do this when
// we are compiling the debug version of this code with the Zig compiler
if (build_options.is_zig_debug_version) {
var stack_trace_allocator = StackTraceOnErrorAllocator.init(failing_allocator.allocator());
break :allocator stack_trace_allocator.allocator();
} else {
break :allocator failing_allocator.allocator();
}
};
var metadata = audiometa.metadata.readAll(allocator, &stream_source) catch |err| switch (err) {
error.OutOfMemory => break,
else => return err,
};
defer metadata.deinit();
// if there were no allocations at all, then just break
if (failing_allocator.index == 0) {
break;
}
if (should_have_failed) {
@panic("OutOfMemory got swallowed somewhere");
}
// now that we've run this input once without hitting the fail index,
// we can treat the current index of the FailingAllocator as an upper bound
// for the amount of allocations, and use modulo to get a random-ish but
// predictable index that we know will fail on the second run
failing_index = failing_index % failing_allocator.index;
}
}
/// Wrapping allocator that prints a stack trace on error in alloc
const StackTraceOnErrorAllocator = struct {
parent_allocator: Allocator,
const Self = @This();
pub fn init(parent_allocator: Allocator) Self {
return .{
.parent_allocator = parent_allocator,
};
}
pub fn allocator(self: *Self) Allocator {
return Allocator.init(self, alloc, resize, free);
}
fn alloc(self: *Self, len: usize, ptr_align: u29, len_align: u29, ra: usize) error{OutOfMemory}![]u8 {
return self.parent_allocator.rawAlloc(len, ptr_align, len_align, ra) catch |err| {
std.debug.print(
"alloc: {s} - len: {}, ptr_align: {}, len_align: {}\n",
.{ @errorName(err), len, ptr_align, len_align },
);
const return_address = if (ra != 0) ra else @returnAddress();
std.debug.dumpCurrentStackTrace(return_address);
std.debug.print("^^^ allocation failure stack trace\n", .{});
return err;
};
}
fn resize(self: *Self, buf: []u8, buf_align: u29, new_len: usize, len_align: u29, ra: usize) ?usize {
// Do not catch errors here since this can return errors that are not 'real'
// See the doc comment of Allocotor.reallocBytes for more details.
// Also, the FailingAllocator does not induce failure in its resize implementation,
// which is what we're really interested in here.
return self.parent_allocator.rawResize(buf, buf_align, new_len, len_align, ra);
}
fn free(self: *Self, buf: []u8, buf_align: u29, ret_addr: usize) void {
return self.parent_allocator.rawFree(buf, buf_align, ret_addr);
}
}; | test/fuzz-oom.zig |
const std = @import("std");
const utils = @import("utils.zig");
const vector = @import("vector.zig");
const Vec4 = vector.Vec4;
const Mat4 = @import("matrix.zig").Mat4;
const Material = @import("material.zig").Material;
const Ray = @import("ray.zig").Ray;
const Intersections = @import("ray.zig").Intersections;
const initPoint = vector.initPoint;
const initVector = vector.initVector;
const Sphere = struct {
pub fn localNormalAt(shape: Shape, point: Vec4) Vec4 {
_ = shape;
return point.sub(initPoint(0, 0, 0)).normalize();
}
pub fn localIntersect(shape: Shape, allocator: std.mem.Allocator, ray: Ray) !Intersections {
var res = Intersections.init(allocator);
errdefer res.deinit();
const shape_to_ray = ray.origin.sub(initPoint(0, 0, 0));
const a = ray.direction.dot(ray.direction);
const b = 2.0 * ray.direction.dot(shape_to_ray);
const c = shape_to_ray.dot(shape_to_ray) - 1.0;
const discriminant = b * b - 4 * a * c;
if (discriminant < 0) // ray misses
return res;
const t1 = (-b - std.math.sqrt(discriminant)) / (2 * a);
const t2 = (-b + std.math.sqrt(discriminant)) / (2 * a);
try res.list.append(.{ .t = t1, .object = shape });
try res.list.append(.{ .t = t2, .object = shape });
return res;
}
};
const Plane = struct {
pub fn localNormalAt(shape: Shape, point: Vec4) Vec4 {
_ = shape;
_ = point;
return initVector(0, 1, 0);
}
pub fn localIntersect(shape: Shape, allocator: std.mem.Allocator, ray: Ray) !Intersections {
_ = ray;
var res = Intersections.init(allocator);
errdefer res.deinit();
// check if coplanar
if (std.math.absFloat(ray.direction.y) < std.math.epsilon(f64))
return res;
const t = -ray.origin.y / ray.direction.y;
try res.list.append(.{ .t = t, .object = shape });
return res;
}
};
pub const Shape = struct {
const Self = @This();
geo: union(enum) {
sphere: Sphere,
plane: Plane,
} = .sphere,
transform: Mat4 = Mat4.identity(),
material: Material = .{},
pub fn normalAt(self: Self, world_point: Vec4) Vec4 {
const object_space = self.transform.inverse();
const local_point = object_space.multVec(world_point);
const local_normal = switch (self.geo) {
.sphere => Sphere.localNormalAt(self, local_point),
.plane => Plane.localNormalAt(self, local_point),
};
var world_normal = object_space.transpose().multVec(local_normal);
world_normal.w = 0; // or use 3x3 submatrix without translation above
return world_normal.normalize();
}
pub fn intersect(self: Self, allocator: std.mem.Allocator, world_ray: Ray) !Intersections {
var object_space = self.transform.inverse();
var local_ray = world_ray.transform(object_space);
return switch (self.geo) {
.sphere => try Sphere.localIntersect(self, allocator, local_ray),
.plane => try Plane.localIntersect(self, allocator, local_ray),
};
}
};
test "A shape's default transformation" {
const s = Shape{};
try std.testing.expect(s.transform.eql(Mat4.identity()));
}
test "Changing a shape's transformation" {
var s = Shape{};
s.transform = Mat4.identity().translate(2, 3, 4);
try std.testing.expect(s.transform.eql(Mat4.identity().translate(2, 3, 4)));
}
test "A shape has a default material" {
const s = Shape{};
try std.testing.expectEqual(Material{}, s.material);
}
test "A shape may be assigned a material" {
const m = Material{
.ambient = 1.0,
};
const s = Shape{ .material = m };
try std.testing.expectEqual(m, s.material);
}
test "The normal on a sphere at a point on the x axis" {
const s = Shape{ .geo = .{ .sphere = .{} } };
const n = s.normalAt(initPoint(1, 0, 0));
try std.testing.expect(n.eql(initVector(1, 0, 0)));
}
test "The normal on a sphere at a point on the y axis" {
const s = Shape{ .geo = .{ .sphere = .{} } };
const n = s.normalAt(initPoint(0, 1, 0));
try std.testing.expect(n.eql(initVector(0, 1, 0)));
}
test "The normal on a sphere at a point on the z axis" {
const s = Shape{ .geo = .{ .sphere = .{} } };
const n = s.normalAt(initPoint(0, 0, 1));
try std.testing.expect(n.eql(initVector(0, 0, 1)));
}
test "The normal on a sphere at a point at a nonaxial point" {
const s = Shape{ .geo = .{ .sphere = .{} } };
const k = std.math.sqrt(3.0) / 3.0;
const n = s.normalAt(initPoint(k, k, k));
try std.testing.expect(n.eql(initVector(k, k, k)));
try std.testing.expect(n.eql(n.normalize()));
}
const alloc = std.testing.allocator;
test "Computing the normal on a translated sphere" {
const s = Shape{
.transform = Mat4.identity().translate(0, 1, 0),
.geo = .{ .sphere = .{} },
};
const n = s.normalAt(initPoint(0, 1.70711, -0.70711));
try utils.expectVec4ApproxEq(n, initVector(0, 0.70711, -0.70711));
}
test "Computing the normal on a transformed sphere" {
const s = Shape{
.geo = .{ .sphere = .{} },
.transform = Mat4.identity()
.rotateZ(std.math.pi / 5.0)
.scale(1, 0.5, 1),
};
const n = s.normalAt(initPoint(0, std.math.sqrt(2.0) / 2.0, -std.math.sqrt(2.0) / 2.0));
try utils.expectVec4ApproxEq(n, initVector(0, 0.97014, -0.24254));
}
test "a ray intersects shape at two points" {
const r = Ray.init(initPoint(0, 0, -5), initVector(0, 0, 1));
const s = Shape{ .geo = .{ .sphere = .{} } };
var xs = try s.intersect(alloc, r);
defer xs.deinit();
try std.testing.expectEqual(@as(usize, 2), xs.list.items.len);
try utils.expectEpsilonEq(@as(f64, 4.0), xs.list.items[0].t);
try utils.expectEpsilonEq(@as(f64, 6.0), xs.list.items[1].t);
try std.testing.expectEqual(s, xs.list.items[0].object);
try std.testing.expectEqual(s, xs.list.items[1].object);
}
test "a ray intersects a shape at a tangent" {
const r = Ray.init(initPoint(0, 1, -5), initVector(0, 0, 1));
const s = Shape{ .geo = .{ .sphere = .{} } };
var xs = try s.intersect(alloc, r);
defer xs.deinit();
try std.testing.expectEqual(@as(usize, 2), xs.list.items.len);
try utils.expectEpsilonEq(@as(f64, 5.0), xs.list.items[0].t);
try utils.expectEpsilonEq(@as(f64, 5.0), xs.list.items[1].t);
try std.testing.expectEqual(s, xs.list.items[0].object);
try std.testing.expectEqual(s, xs.list.items[1].object);
}
test "a ray misses a shape" {
const r = Ray.init(initPoint(0, 2, -5), initVector(0, 0, 1));
const s = Shape{ .geo = .{ .sphere = .{} } };
var xs = try s.intersect(alloc, r);
defer xs.deinit();
try std.testing.expectEqual(@as(usize, 0), xs.list.items.len);
}
test "a ray originates inside a shape" {
const r = Ray.init(initPoint(0, 0, 0), initVector(0, 0, 1));
const s = Shape{ .geo = .{ .sphere = .{} } };
var xs = try s.intersect(alloc, r);
defer xs.deinit();
try std.testing.expectEqual(@as(usize, 2), xs.list.items.len);
try utils.expectEpsilonEq(@as(f64, -1.0), xs.list.items[0].t);
try utils.expectEpsilonEq(@as(f64, 1.0), xs.list.items[1].t);
try std.testing.expectEqual(s, xs.list.items[0].object);
try std.testing.expectEqual(s, xs.list.items[1].object);
}
test "a shape is behind a ray" {
const r = Ray.init(initPoint(0, 0, 5), initVector(0, 0, 1));
const s = Shape{ .geo = .{ .sphere = .{} } };
var xs = try s.intersect(alloc, r);
defer xs.deinit();
try std.testing.expectEqual(@as(usize, 2), xs.list.items.len);
try utils.expectEpsilonEq(@as(f64, -6.0), xs.list.items[0].t);
try utils.expectEpsilonEq(@as(f64, -4.0), xs.list.items[1].t);
try std.testing.expectEqual(s, xs.list.items[0].object);
try std.testing.expectEqual(s, xs.list.items[1].object);
}
test "Intersecting a scaled shape with a ray" {
const r = Ray.init(initPoint(0, 0, -5), initVector(0, 0, 1));
const s = Shape{
.geo = .{ .sphere = .{} },
.transform = Mat4.identity().scale(2, 2, 2),
};
var xs = try s.intersect(alloc, r);
defer xs.deinit();
try std.testing.expectEqual(@as(usize, 2), xs.list.items.len);
try utils.expectEpsilonEq(@as(f64, 3.0), xs.list.items[0].t);
try utils.expectEpsilonEq(@as(f64, 7.0), xs.list.items[1].t);
}
test "Intersecting a translated shape with a ray" {
const r = Ray.init(initPoint(0, 0, -5), initVector(0, 0, 1));
const s = Shape{
.geo = .{ .sphere = .{} },
.transform = Mat4.identity().translate(5, 0, 0),
};
var xs = try s.intersect(alloc, r);
defer xs.deinit();
try std.testing.expectEqual(@as(usize, 0), xs.list.items.len);
}
test "The normal of a plane is constant everywhere" {
const p = Shape{ .geo = .{ .plane = .{} } };
const n1 = Plane.localNormalAt(p, initPoint(0, 0, 0));
const n2 = Plane.localNormalAt(p, initPoint(10, 0, -10));
const n3 = Plane.localNormalAt(p, initPoint(-5, 0, 150));
try utils.expectVec4ApproxEq(initVector(0, 1, 0), n1);
try utils.expectVec4ApproxEq(initVector(0, 1, 0), n2);
try utils.expectVec4ApproxEq(initVector(0, 1, 0), n3);
}
test "Intersect with a ray parallel to the plane" {
const p = Shape{ .geo = .{ .plane = .{} } };
const r = Ray.init(initPoint(0, 10, 0), initVector(0, 0, 1));
var xs = try Plane.localIntersect(p, alloc, r);
defer xs.deinit();
try std.testing.expectEqual(@as(usize, 0), xs.list.items.len);
}
test "Intersect with a coplanar ray" {
const p = Shape{ .geo = .{ .plane = .{} } };
const r = Ray.init(initPoint(0, 0, 0), initVector(0, 0, 1));
var xs = try Plane.localIntersect(p, alloc, r);
defer xs.deinit();
try std.testing.expectEqual(@as(usize, 0), xs.list.items.len);
}
test "Intersect with a ray parallel to the plane" {
const p = Shape{ .geo = .{ .plane = .{} } };
const r = Ray.init(initPoint(0, 10, 0), initVector(0, 0, 1));
var xs = try Plane.localIntersect(p, alloc, r);
defer xs.deinit();
try std.testing.expectEqual(@as(usize, 0), xs.list.items.len);
}
test "Intersect with a plane from above" {
const p = Shape{ .geo = .{ .plane = .{} } };
const r = Ray.init(initPoint(0, 1, 0), initVector(0, -1, 0));
var xs = try Plane.localIntersect(p, alloc, r);
defer xs.deinit();
try std.testing.expectEqual(@as(usize, 1), xs.list.items.len);
try utils.expectEpsilonEq(@as(f64, 1.0), xs.list.items[0].t);
}
test "Intersect with a plane from below" {
const p = Shape{ .geo = .{ .plane = .{} } };
const r = Ray.init(initPoint(0, -1, 0), initVector(0, 1, 0));
var xs = try Plane.localIntersect(p, alloc, r);
defer xs.deinit();
try std.testing.expectEqual(@as(usize, 1), xs.list.items.len);
try utils.expectEpsilonEq(@as(f64, 1.0), xs.list.items[0].t);
} | shape.zig |
const std = @import("std");
const Allocator = std.mem.Allocator;
const glfw = @import("glfw");
const gpu = @import("gpu");
const App = @import("app");
const structs = @import("structs.zig");
const enums = @import("enums.zig");
const Engine = @This();
/// Window, events, inputs etc.
core: Core,
/// WebGPU driver - stores device, swap chains, targets and more
gpu_driver: GpuDriver,
allocator: Allocator,
options: structs.Options,
/// The amount of time (in seconds) that has passed since the last frame was rendered.
///
/// For example, if you are animating a cube which should rotate 360 degrees every second,
/// instead of writing (360.0 / 60.0) and assuming the frame rate is 60hz, write
/// (360.0 * engine.delta_time)
delta_time: f64 = 0,
delta_time_ns: u64 = 0,
timer: std.time.Timer,
pub const Core = struct {
internal: GetCoreInternalType(),
pub fn setShouldClose(core: *Core, value: bool) void {
core.internal.setShouldClose(value);
}
pub fn getFramebufferSize(core: *Core) !structs.Size {
return core.internal.getFramebufferSize();
}
pub fn setSizeLimits(core: *Core, min: structs.SizeOptional, max: structs.SizeOptional) !void {
return core.internal.setSizeLimits(min, max);
}
pub fn setKeyCallback(core: *Core, comptime cb: fn (app: *App, engine: *Engine, key: enums.Key, action: enums.Action) void) void {
core.internal.setKeyCallback(cb);
}
};
pub const GpuDriver = struct {
internal: GetGpuDriverInternalType(),
device: gpu.Device,
backend_type: gpu.Adapter.BackendType,
swap_chain: ?gpu.SwapChain,
swap_chain_format: gpu.Texture.Format,
surface: ?gpu.Surface,
current_desc: gpu.SwapChain.Descriptor,
target_desc: gpu.SwapChain.Descriptor,
};
pub fn init(allocator: std.mem.Allocator, options: structs.Options) !Engine {
var engine = Engine{
.allocator = allocator,
.options = options,
.timer = try std.time.Timer.start(),
.core = undefined,
.gpu_driver = undefined,
};
// Note: if in future, there is a conflict in init() signature of different backends,
// move these calls to the entry point file, which is native.zig for Glfw, for example
engine.core.internal = try GetCoreInternalType().init(allocator, &engine);
engine.gpu_driver.internal = try GetGpuDriverInternalType().init(allocator, &engine);
return engine;
}
fn GetCoreInternalType() type {
return @import("native.zig").CoreGlfw;
}
fn GetGpuDriverInternalType() type {
return @import("native.zig").GpuDriverNative;
} | src/Engine.zig |
const std = @import("std");
const vk = @import("vulkan");
const c = @import("c.zig");
const err = @import("err.zig");
const glfw = @import("glfz.zig");
pub const Window = opaque {
pub const InitError = error{
OutOfMemory,
ApiUnavailable,
VersionUnavailable,
FormatUnavailable,
GlfwPlatformError,
};
pub fn init(width: u16, height: u16, title: [:0]const u8, config: Config) InitError!*Window {
glfwDefaultWindowHints();
// Skip the first two 'cause they're monitor and share
@setEvalBranchQuota(2000);
inline for (std.meta.fields(Config)[2..]) |hint| {
// Check if the value is different from the default
const value = @field(config, hint.name);
if (!std.meta.eql(value, hint.default_value.?)) {
// Get the hint id
const hint_name = comptime blk: {
var hint_name = ("GLFW_" ++ hint.name).*;
break :blk std.ascii.upperString(&hint_name, &hint_name);
};
const hinti = @field(c, hint_name);
// Convert the value to an i32
const valuei: i32 = switch (@typeInfo(hint.field_type)) {
.Bool => @boolToInt(value),
.Enum => @enumToInt(value),
.Optional => value orelse c.GLFW_DONT_CARE,
.Int => value,
else => unreachable,
};
// Set the hint
glfwWindowHint(hinti, valuei);
}
}
return glfwCreateWindow(width, height, title.ptr, config.monitor, config.share) orelse err.require(InitError);
}
extern fn glfwDefaultWindowHints() void;
extern fn glfwWindowHint(c_int, c_int) void;
extern fn glfwCreateWindow(c_int, c_int, [*:0]const u8, ?*Monitor, ?*Window) ?*Window;
pub const Config = struct {
monitor: ?*Monitor = null,
share: ?*Window = null,
resizable: bool = true,
visible: bool = true,
decorated: bool = true,
focused: bool = true,
auto_iconify: bool = true,
floating: bool = false,
maximized: bool = false,
center_cursor: bool = true,
transparent_framebuffer: bool = false,
focus_on_show: bool = true,
scale_to_monitor: bool = false,
red_bits: ?u31 = 8,
green_bits: ?u31 = 8,
blue_bits: ?u31 = 8,
alpha_bits: ?u31 = 8,
depth_bits: ?u31 = 24,
stencil_bits: ?u31 = 8,
client_api: glfw.ClientApi = .opengl,
context_creation_api: glfw.ContextCreationApi = .native,
context_version_major: u8 = 1,
context_version_minor: u8 = 0,
opengl_forward_compat: bool = false,
opengl_debug_context: bool = false,
opengl_profile: glfw.OpenglProfile = .any,
};
pub const deinit = glfwDestroyWindow;
extern fn glfwDestroyWindow(*Window) void;
pub fn windowSize(self: *Window) [2]u31 {
var x: c_int = undefined;
var y: c_int = undefined;
glfwGetWindowSize(self, &x, &y);
err.check();
return .{ @intCast(u31, x), @intCast(u31, y) };
}
extern fn glfwGetWindowSize(*Window, ?*c_int, ?*c_int) void;
pub fn framebufferSize(self: *Window) [2]u31 {
var x: c_int = undefined;
var y: c_int = undefined;
glfwGetFramebufferSize(self, &x, &y);
err.check();
return .{ @intCast(u31, x), @intCast(u31, y) };
}
extern fn glfwGetFramebufferSize(*Window, ?*c_int, ?*c_int) void;
pub fn makeContextCurrent(self: *Window) void {
glfwMakeContextCurrent(self);
err.check();
}
extern fn glfwMakeContextCurrent(*Window) void;
pub fn shouldClose(self: *Window) bool {
const res = glfwWindowShouldClose(self);
err.check();
return res != 0;
}
extern fn glfwWindowShouldClose(*Window) c_int;
pub fn setShouldClose(self: *Window, value: bool) void {
glfwSetWindowShouldClose(self, @boolToInt(value));
err.check();
}
extern fn glfwSetWindowShouldClose(*Window, c_int) void;
pub fn swapBuffers(self: *Window) void {
glfwSwapBuffers(self);
err.check();
}
extern fn glfwSwapBuffers(*Window) void;
pub fn setUserPointer(self: *Window, ptr: anytype) void {
glfwSetWindowUserPointer(self, @ptrCast(*c_void, ptr));
}
pub fn getUserPointer(self: *Window, comptime T: type) T {
const ptr = glfwGetWindowUserPointer(self);
return @ptrCast(T, @alignCast(std.meta.alignment(T), ptr));
}
extern fn glfwSetWindowUserPointer(*Window, *c_void) void;
extern fn glfwGetWindowUserPointer(*Window) *c_void;
//// Input ////
pub fn getKey(self: *Window, key: glfw.Key) bool {
const state = glfwGetKey(self, key);
err.check();
return state == .press;
}
extern fn glfwGetKey(*Window, glfw.Key) glfw.KeyAction;
pub fn getCursorPos(self: *Window, x: *f64, y: *f64) void {
glfwGetCursorPos(self, x, y);
err.check();
}
extern fn glfwGetCursorPos(*Window, *f64, *f64) void;
//// Callbacks ////
pub const setWindowSizeCallback = glfwSetWindowSizeCallback;
extern fn glfwSetWindowSizeCallback(self: *Window, callback: WindowSizeFn) WindowSizeFn;
pub const WindowSizeFn = fn (*Window, c_int, c_int) callconv(.C) void;
pub const setFramebufferSizeCallback = glfwSetFramebufferSizeCallback;
extern fn glfwSetFramebufferSizeCallback(self: *Window, callback: FramebufferSizeFn) FramebufferSizeFn;
pub const FramebufferSizeFn = fn (*Window, c_int, c_int) callconv(.C) void;
pub const setMouseButtonCallback = glfwSetMouseButtonCallback;
extern fn glfwSetMouseButtonCallback(self: *Window, callback: MouseButtonFn) MouseButtonFn;
pub const MouseButtonFn = fn (*Window, glfw.MouseButton, glfw.MouseAction, glfw.Modifiers) callconv(.C) void;
//// Vulkan ////
/// Vulkan must be supported.
/// The instance must have the required extensions enabled.
/// The window must have been created with client_api = .none.
pub fn createSurface(self: *Window, instance: vk.Instance, allocator: *const vk.AllocationCallbacks) vk.SurfaceKHR {
var surface: vk.SurfaceKHR = undefined;
switch (glfwCreateWindowSurface(instance, self, allocator, &surface)) {
.success => {},
.error_initialization_failed => unreachable, // Vulkan is not supported
.error_extension_not_present => unreachable, // Instance did not have required extensions
.error_native_window_in_use_khr => unreachable, // Window created with client_api != .none
else => unreachable,
}
return surface;
}
extern fn glfwCreateWindowSurface(vk.Instance, *Window, *const vk.AllocationCallbacks, *vk.SurfaceKHR) vk.Result;
};
pub const Monitor = opaque {
// TODO
}; | types.zig |
const std = @import("../std.zig");
const io = std.io;
const testing = std.testing;
const mem = std.mem;
const assert = std.debug.assert;
/// This turns a byte buffer into an `io.Writer`, `io.Reader`, or `io.SeekableStream`.
/// If the supplied byte buffer is const, then `io.Writer` is not available.
pub fn FixedBufferStream(comptime Buffer: type) type {
return struct {
/// `Buffer` is either a `[]u8` or `[]const u8`.
buffer: Buffer,
pos: usize,
pub const ReadError = error{};
pub const WriteError = error{NoSpaceLeft};
pub const SeekError = error{};
pub const GetSeekPosError = error{};
pub const Reader = io.Reader(*Self, ReadError, read);
/// Deprecated: use `Reader`
pub const InStream = io.InStream(*Self, ReadError, read);
pub const Writer = io.Writer(*Self, WriteError, write);
/// Deprecated: use `Writer`
pub const OutStream = Writer;
pub const SeekableStream = io.SeekableStream(
*Self,
SeekError,
GetSeekPosError,
seekTo,
seekBy,
getPos,
getEndPos,
);
const Self = @This();
pub fn reader(self: *Self) Reader {
return .{ .context = self };
}
/// Deprecated: use `inStream`
pub fn inStream(self: *Self) InStream {
return .{ .context = self };
}
pub fn writer(self: *Self) Writer {
return .{ .context = self };
}
/// Deprecated: use `writer`
pub fn outStream(self: *Self) OutStream {
return .{ .context = self };
}
pub fn seekableStream(self: *Self) SeekableStream {
return .{ .context = self };
}
pub fn read(self: *Self, dest: []u8) ReadError!usize {
const size = std.math.min(dest.len, self.buffer.len - self.pos);
const end = self.pos + size;
mem.copy(u8, dest[0..size], self.buffer[self.pos..end]);
self.pos = end;
return size;
}
/// If the returned number of bytes written is less than requested, the
/// buffer is full. Returns `error.NoSpaceLeft` when no bytes would be written.
/// Note: `error.NoSpaceLeft` matches the corresponding error from
/// `std.fs.File.WriteError`.
pub fn write(self: *Self, bytes: []const u8) WriteError!usize {
if (bytes.len == 0) return 0;
if (self.pos >= self.buffer.len) return error.NoSpaceLeft;
const n = if (self.pos + bytes.len <= self.buffer.len)
bytes.len
else
self.buffer.len - self.pos;
mem.copy(u8, self.buffer[self.pos .. self.pos + n], bytes[0..n]);
self.pos += n;
if (n == 0) return error.NoSpaceLeft;
return n;
}
pub fn seekTo(self: *Self, pos: u64) SeekError!void {
self.pos = if (std.math.cast(usize, pos)) |x| x else |_| self.buffer.len;
}
pub fn seekBy(self: *Self, amt: i64) SeekError!void {
if (amt < 0) {
const abs_amt = std.math.absCast(amt);
const abs_amt_usize = std.math.cast(usize, abs_amt) catch std.math.maxInt(usize);
if (abs_amt_usize > self.pos) {
self.pos = 0;
} else {
self.pos -= abs_amt_usize;
}
} else {
const amt_usize = std.math.cast(usize, amt) catch std.math.maxInt(usize);
const new_pos = std.math.add(usize, self.pos, amt_usize) catch std.math.maxInt(usize);
self.pos = std.math.min(self.buffer.len, new_pos);
}
}
pub fn getEndPos(self: *Self) GetSeekPosError!u64 {
return self.buffer.len;
}
pub fn getPos(self: *Self) GetSeekPosError!u64 {
return self.pos;
}
pub fn getWritten(self: Self) Buffer {
return self.buffer[0..self.pos];
}
pub fn reset(self: *Self) void {
self.pos = 0;
}
};
}
pub fn fixedBufferStream(buffer: var) FixedBufferStream(NonSentinelSpan(@TypeOf(buffer))) {
return .{ .buffer = mem.span(buffer), .pos = 0 };
}
fn NonSentinelSpan(comptime T: type) type {
var ptr_info = @typeInfo(mem.Span(T)).Pointer;
ptr_info.sentinel = null;
return @Type(std.builtin.TypeInfo{ .Pointer = ptr_info });
}
test "FixedBufferStream output" {
var buf: [255]u8 = undefined;
var fbs = fixedBufferStream(&buf);
const stream = fbs.writer();
try stream.print("{}{}!", .{ "Hello", "World" });
testing.expectEqualSlices(u8, "HelloWorld!", fbs.getWritten());
}
test "FixedBufferStream output 2" {
var buffer: [10]u8 = undefined;
var fbs = fixedBufferStream(&buffer);
try fbs.writer().writeAll("Hello");
testing.expect(mem.eql(u8, fbs.getWritten(), "Hello"));
try fbs.writer().writeAll("world");
testing.expect(mem.eql(u8, fbs.getWritten(), "Helloworld"));
testing.expectError(error.NoSpaceLeft, fbs.writer().writeAll("!"));
testing.expect(mem.eql(u8, fbs.getWritten(), "Helloworld"));
fbs.reset();
testing.expect(fbs.getWritten().len == 0);
testing.expectError(error.NoSpaceLeft, fbs.writer().writeAll("Hello world!"));
testing.expect(mem.eql(u8, fbs.getWritten(), "Hello worl"));
}
test "FixedBufferStream input" {
const bytes = [_]u8{ 1, 2, 3, 4, 5, 6, 7 };
var fbs = fixedBufferStream(&bytes);
var dest: [4]u8 = undefined;
var read = try fbs.reader().read(dest[0..4]);
testing.expect(read == 4);
testing.expect(mem.eql(u8, dest[0..4], bytes[0..4]));
read = try fbs.reader().read(dest[0..4]);
testing.expect(read == 3);
testing.expect(mem.eql(u8, dest[0..3], bytes[4..7]));
read = try fbs.reader().read(dest[0..4]);
testing.expect(read == 0);
} | lib/std/io/fixed_buffer_stream.zig |
const std = @import("std");
const mem = std.mem;
const ascii = @import("../../ascii.zig");
const Context = @import("../../Context.zig");
const Self = @This();
context: *Context,
pub fn new(ctx: *Context) Self {
return Self{ .context = ctx };
}
/// isCased detects cased letters.
pub fn isCased(self: Self, cp: u21) !bool {
var cased = try self.context.getCased();
return cased.isCased(cp);
}
/// isLetter covers all letters in Unicode, not just ASCII.
pub fn isLetter(self: Self, cp: u21) !bool {
const lower = try self.context.getLower();
const modifier_letter = try self.context.getModifierLetter();
const other_letter = try self.context.getOtherLetter();
const title = try self.context.getTitle();
const upper = try self.context.getUpper();
return lower.isLowercaseLetter(cp) or
modifier_letter.isModifierLetter(cp) or
other_letter.isOtherLetter(cp) or
title.isTitlecaseLetter(cp) or
upper.isUppercaseLetter(cp);
}
/// isAscii detects ASCII only letters.
pub fn isAscii(cp: u21) bool {
return if (cp < 128) ascii.isAlpha(@intCast(u8, cp)) else false;
}
/// isLower detects code points that are lowercase.
pub fn isLower(self: Self, cp: u21) !bool {
const lower = try self.context.getLower();
return lower.isLowercaseLetter(cp) or (!try self.isCased(cp));
}
/// isAsciiLower detects ASCII only lowercase letters.
pub fn isAsciiLower(cp: u21) bool {
return if (cp < 128) ascii.isLower(@intCast(u8, cp)) else false;
}
/// isTitle detects code points in titlecase.
pub fn isTitle(self: Self, cp: u21) !bool {
const title = try self.context.getTitle();
return title.isTitlecaseLetter(cp) or (!try self.isCased(cp));
}
/// isUpper detects code points in uppercase.
pub fn isUpper(self: Self, cp: u21) !bool {
const upper = try self.context.getUpper();
return upper.isUppercaseLetter(cp) or (!try self.isCased(cp));
}
/// isAsciiUpper detects ASCII only uppercase letters.
pub fn isAsciiUpper(cp: u21) bool {
return if (cp < 128) ascii.isUpper(@intCast(u8, cp)) else false;
}
/// toLower returns the lowercase code point for the given code point. It returns the same
/// code point given if no mapping exists.
pub fn toLower(self: Self, cp: u21) !u21 {
// Only cased letters.
if (!try self.isCased(cp)) return cp;
const lower_map = try self.context.getLowerMap();
return lower_map.toLower(cp);
}
/// toAsciiLower converts an ASCII letter to lowercase.
pub fn toAsciiLower(self: Self, cp: u21) !u21 {
return if (cp < 128) ascii.toLower(@intCast(u8, cp)) else cp;
}
/// toTitle returns the titlecase code point for the given code point. It returns the same
/// code point given if no mapping exists.
pub fn toTitle(self: Self, cp: u21) !u21 {
// Only cased letters.
if (!try self.isCased(cp)) return cp;
const title_map = try self.context.getTitleMap();
return title_map.toTitle(cp);
}
/// toUpper returns the uppercase code point for the given code point. It returns the same
/// code point given if no mapping exists.
pub fn toUpper(self: Self, cp: u21) !u21 {
// Only cased letters.
if (!try self.isCased(cp)) return cp;
const upper_map = try self.context.getUpperMap();
return upper_map.toUpper(cp);
}
/// toAsciiUpper converts an ASCII letter to uppercase.
pub fn toAsciiUpper(self: Self, cp: u21) !u21 {
return if (cp < 128) ascii.toUpper(@intCast(u8, cp)) else false;
}
/// toCaseFold will convert a code point into its case folded equivalent. Note that this can result
/// in a mapping to more than one code point, known as the full case fold.
pub fn toCaseFold(self: Self, cp: u21) !Context.CaseFold {
const fold_map = try self.context.getCaseFoldMap();
return fold_map.toCaseFold(cp);
}
const expect = std.testing.expect;
const expectEqual = std.testing.expectEqual;
test "Component struct" {
var ctx = Context.init(std.testing.allocator);
defer ctx.deinit();
var letter = new(&ctx);
const z = 'z';
expect(try letter.isLetter(z));
expect(!try letter.isUpper(z));
const uz = try letter.toUpper(z);
expect(try letter.isUpper(uz));
expectEqual(uz, 'Z');
}
test "Component isCased" {
var ctx = Context.init(std.testing.allocator);
defer ctx.deinit();
var letter = new(&ctx);
expect(try letter.isCased('a'));
expect(try letter.isCased('A'));
expect(!try letter.isCased('1'));
}
test "Component isLower" {
var ctx = Context.init(std.testing.allocator);
defer ctx.deinit();
var letter = new(&ctx);
expect(try letter.isLower('a'));
expect(try letter.isLower('é'));
expect(try letter.isLower('i'));
expect(!try letter.isLower('A'));
expect(!try letter.isLower('É'));
expect(!try letter.isLower('İ'));
// Numbers are lower, upper, and title all at once.
expect(try letter.isLower('1'));
}
const expectEqualSlices = std.testing.expectEqualSlices;
test "Component toCaseFold" {
var ctx = Context.init(std.testing.allocator);
defer ctx.deinit();
var letter = new(&ctx);
var result = try letter.toCaseFold('A');
switch (result) {
.simple => |cp| expectEqual(cp, 'a'),
.full => @panic("Got .full, wanted .simple for A"),
}
result = try letter.toCaseFold('a');
switch (result) {
.simple => |cp| expectEqual(cp, 'a'),
.full => @panic("Got .full, wanted .simple for a"),
}
result = try letter.toCaseFold('1');
switch (result) {
.simple => |cp| expectEqual(cp, '1'),
.full => @panic("Got .full, wanted .simple for 1"),
}
result = try letter.toCaseFold('\u{00DF}');
switch (result) {
.simple => @panic("Got .simple, wanted .full for 0x00DF"),
.full => |s| expectEqualSlices(u21, s, &[_]u21{ 0x0073, 0x0073 }),
}
result = try letter.toCaseFold('\u{0390}');
switch (result) {
.simple => @panic("Got .simple, wanted .full for 0x0390"),
.full => |s| expectEqualSlices(u21, s, &[_]u21{ 0x03B9, 0x0308, 0x0301 }),
}
}
test "Component toLower" {
var ctx = Context.init(std.testing.allocator);
defer ctx.deinit();
var letter = new(&ctx);
expectEqual(try letter.toLower('a'), 'a');
expectEqual(try letter.toLower('A'), 'a');
expectEqual(try letter.toLower('İ'), 'i');
expectEqual(try letter.toLower('É'), 'é');
expectEqual(try letter.toLower(0x80), 0x80);
expectEqual(try letter.toLower(0x80), 0x80);
expectEqual(try letter.toLower('Å'), 'å');
expectEqual(try letter.toLower('å'), 'å');
expectEqual(try letter.toLower('\u{212A}'), 'k');
expectEqual(try letter.toLower('1'), '1');
}
test "Component isUpper" {
var ctx = Context.init(std.testing.allocator);
defer ctx.deinit();
var letter = new(&ctx);
expect(!try letter.isUpper('a'));
expect(!try letter.isUpper('é'));
expect(!try letter.isUpper('i'));
expect(try letter.isUpper('A'));
expect(try letter.isUpper('É'));
expect(try letter.isUpper('İ'));
// Numbers are lower, upper, and title all at once.
expect(try letter.isUpper('1'));
}
test "Component toUpper" {
var ctx = Context.init(std.testing.allocator);
defer ctx.deinit();
var letter = new(&ctx);
expectEqual(try letter.toUpper('a'), 'A');
expectEqual(try letter.toUpper('A'), 'A');
expectEqual(try letter.toUpper('i'), 'I');
expectEqual(try letter.toUpper('é'), 'É');
expectEqual(try letter.toUpper(0x80), 0x80);
expectEqual(try letter.toUpper('Å'), 'Å');
expectEqual(try letter.toUpper('å'), 'Å');
expectEqual(try letter.toUpper('1'), '1');
}
test "Component isTitle" {
var ctx = Context.init(std.testing.allocator);
defer ctx.deinit();
var letter = new(&ctx);
expect(!try letter.isTitle('a'));
expect(!try letter.isTitle('é'));
expect(!try letter.isTitle('i'));
expect(try letter.isTitle('\u{1FBC}'));
expect(try letter.isTitle('\u{1FCC}'));
expect(try letter.isTitle('Lj'));
// Numbers are lower, upper, and title all at once.
expect(try letter.isTitle('1'));
}
test "Component toTitle" {
var ctx = Context.init(std.testing.allocator);
defer ctx.deinit();
var letter = new(&ctx);
expectEqual(try letter.toTitle('a'), 'A');
expectEqual(try letter.toTitle('A'), 'A');
expectEqual(try letter.toTitle('i'), 'I');
expectEqual(try letter.toTitle('é'), 'É');
expectEqual(try letter.toTitle('1'), '1');
}
test "Component isLetter" {
var ctx = Context.init(std.testing.allocator);
defer ctx.deinit();
var letter = new(&ctx);
var cp: u21 = 'a';
while (cp <= 'z') : (cp += 1) {
expect(try letter.isLetter(cp));
}
cp = 'A';
while (cp <= 'Z') : (cp += 1) {
expect(try letter.isLetter(cp));
}
expect(try letter.isLetter('É'));
expect(try letter.isLetter('\u{2CEB3}'));
expect(!try letter.isLetter('\u{0003}'));
} | src/components/aggregate/Letter.zig |
const std = @import("std");
const string = []const u8;
const ansi = @import("ansi");
const root = @import("root");
const zigmod = @import("../lib.zig");
const u = @import("./../util/index.zig");
const common = @import("./../common.zig");
const build_options = if (@hasDecl(root, "build_options")) root.build_options else struct {};
const bootstrap = if (@hasDecl(build_options, "bootstrap")) build_options.bootstrap else false;
//
//
pub fn execute(args: [][]u8) !void {
//
const gpa = std.heap.c_allocator;
const cachepath = try std.fs.path.join(gpa, &.{ ".zigmod", "deps" });
const dir = std.fs.cwd();
const should_update = !(args.len >= 1 and std.mem.eql(u8, args[0], "--no-update"));
var options = common.CollectOptions{
.log = should_update,
.update = should_update,
.alloc = gpa,
};
const top_module = try common.collect_deps_deep(cachepath, dir, &options);
var list = std.ArrayList(zigmod.Module).init(gpa);
try common.collect_pkgs(top_module, &list);
try create_depszig(gpa, cachepath, dir, top_module, &list);
if (bootstrap) return;
try create_lockfile(gpa, &list, cachepath, dir);
try diff_lockfile(gpa);
}
pub fn create_depszig(alloc: std.mem.Allocator, cachepath: string, dir: std.fs.Dir, top_module: zigmod.Module, list: *std.ArrayList(zigmod.Module)) !void {
const f = try dir.createFile("deps.zig", .{});
defer f.close();
const w = f.writer();
try w.writeAll("const std = @import(\"std\");\n");
try w.writeAll("const builtin = @import(\"builtin\");\n");
try w.writeAll("const Pkg = std.build.Pkg;\n");
try w.writeAll("const string = []const u8;\n");
try w.writeAll("\n");
try w.print("pub const cache = \"{}\";\n", .{std.zig.fmtEscapes(cachepath)});
try w.writeAll("\n");
try w.writeAll(
\\pub fn addAllTo(exe: *std.build.LibExeObjStep) void {
\\ checkMinZig(builtin.zig_version, exe);
\\ @setEvalBranchQuota(1_000_000);
\\ for (packages) |pkg| {
\\ exe.addPackage(pkg.pkg.?);
\\ }
\\ var llc = false;
\\ var vcpkg = false;
\\ inline for (std.meta.declarations(package_data)) |decl| {
\\ const pkg = @as(Package, @field(package_data, decl.name));
\\ inline for (pkg.system_libs) |item| {
\\ exe.linkSystemLibrary(item);
\\ llc = true;
\\ }
\\ inline for (pkg.c_include_dirs) |item| {
\\ exe.addIncludeDir(@field(dirs, decl.name) ++ "/" ++ item);
\\ llc = true;
\\ }
\\ inline for (pkg.c_source_files) |item| {
\\ exe.addCSourceFile(@field(dirs, decl.name) ++ "/" ++ item, pkg.c_source_flags);
\\ llc = true;
\\ }
\\ vcpkg = vcpkg or pkg.vcpkg;
\\ }
\\ if (llc) exe.linkLibC();
\\ if (builtin.os.tag == .windows and vcpkg) exe.addVcpkgPaths(.static) catch |err| @panic(@errorName(err));
\\}
\\
\\pub const Package = struct {
\\ directory: string,
\\ pkg: ?Pkg = null,
\\ c_include_dirs: []const string = &.{},
\\ c_source_files: []const string = &.{},
\\ c_source_flags: []const string = &.{},
\\ system_libs: []const string = &.{},
\\ vcpkg: bool = false,
\\};
\\
\\
);
try w.print(
\\fn checkMinZig(current: std.SemanticVersion, exe: *std.build.LibExeObjStep) void {{
\\ const min = std.SemanticVersion.parse("{}") catch return;
\\ if (current.order(min).compare(.lt)) @panic(exe.builder.fmt("Your Zig version v{{}} does not meet the minimum build requirement of v{{}}", .{{current, min}}));
\\}}
\\
\\
, .{top_module.minZigVersion()});
try w.writeAll("pub const dirs = struct {\n");
try print_dirs(w, list.items);
try w.writeAll("};\n\n");
try w.writeAll("pub const package_data = struct {\n");
var duped = std.ArrayList(zigmod.Module).init(alloc);
for (list.items) |mod| {
if (mod.is_sys_lib) {
continue;
}
try duped.append(mod);
}
try print_pkg_data_to(w, &duped, &std.ArrayList(zigmod.Module).init(alloc));
try w.writeAll("};\n\n");
try w.writeAll("pub const packages = ");
try print_deps(w, top_module);
try w.writeAll(";\n\n");
try w.writeAll("pub const pkgs = ");
try print_pkgs(alloc, w, top_module);
try w.writeAll(";\n\n");
try w.writeAll("pub const imports = struct {\n");
try print_imports(alloc, w, top_module, cachepath);
try w.writeAll("};\n");
}
fn create_lockfile(alloc: std.mem.Allocator, list: *std.ArrayList(zigmod.Module), path: string, dir: std.fs.Dir) !void {
const fl = try dir.createFile("zigmod.lock", .{});
defer fl.close();
const wl = fl.writer();
try wl.writeAll("2\n");
for (list.items) |m| {
if (m.dep) |md| {
if (md.type == .local) {
continue;
}
if (md.type == .system_lib) continue;
const mpath = try std.fs.path.join(alloc, &.{ path, m.clean_path });
const version = try md.exact_version(mpath);
try wl.print("{s} {s} {s}\n", .{ @tagName(md.type), md.path, version });
}
}
}
const DiffChange = struct {
from: string,
to: string,
};
fn diff_lockfile(alloc: std.mem.Allocator) !void {
const max = std.math.maxInt(usize);
if (try u.does_folder_exist(".git")) {
const result = try u.run_cmd_raw(alloc, null, &.{ "git", "diff", "zigmod.lock" });
const r = std.io.fixedBufferStream(result.stdout).reader();
while (try r.readUntilDelimiterOrEofAlloc(alloc, '\n', max)) |line| {
if (std.mem.startsWith(u8, line, "@@")) break;
}
var rems = std.ArrayList(string).init(alloc);
var adds = std.ArrayList(string).init(alloc);
while (try r.readUntilDelimiterOrEofAlloc(alloc, '\n', max)) |line| {
if (line[0] == ' ') continue;
if (line[0] == '-') try rems.append(line[1..]);
if (line[0] == '+') if (line[1] == '2') continue else try adds.append(line[1..]);
}
var changes = std.StringHashMap(DiffChange).init(alloc);
var didbreak = false;
var i: usize = 0;
while (i < rems.items.len) {
const it = rems.items[i];
const sni = u.indexOfN(it, ' ', 2).?;
var j: usize = 0;
while (j < adds.items.len) {
const jt = adds.items[j];
const snj = u.indexOfN(jt, ' ', 2).?;
if (std.mem.eql(u8, it[0..sni], jt[0..snj])) {
try changes.put(it[0..sni], .{
.from = it[u.indexOfAfter(it, '-', sni).? + 1 .. it.len],
.to = jt[u.indexOfAfter(jt, '-', snj).? + 1 .. jt.len],
});
_ = rems.orderedRemove(i);
_ = adds.orderedRemove(j);
didbreak = true;
break;
}
if (!didbreak) j += 1;
}
if (!didbreak) i += 1;
if (didbreak) didbreak = false;
}
if (adds.items.len > 0) {
std.debug.print(comptime ansi.color.Faint("Newly added packages:\n"), .{});
defer std.debug.print("\n", .{});
for (adds.items) |it| {
std.debug.print("- {s}\n", .{it});
}
}
if (rems.items.len > 0) {
std.debug.print(comptime ansi.color.Faint("Removed packages:\n"), .{});
defer std.debug.print("\n", .{});
for (rems.items) |it| {
std.debug.print("- {s}\n", .{it});
}
}
if (changes.unmanaged.size > 0) std.debug.print(comptime ansi.color.Faint("Updated packages:\n"), .{});
var iter = changes.iterator();
while (iter.next()) |it| {
if (diff_printchange("git https://github.com", "- {s}/compare/{s}...{s}\n", it)) continue;
if (diff_printchange("git https://gitlab.com", "- {s}/-/compare/{s}...{s}\n", it)) continue;
if (diff_printchange("git https://gitea.<EMAIL>", "- {s}/compare/{s}...{s}\n", it)) continue;
std.debug.print("- {s}\n", .{it.key_ptr.*});
std.debug.print(" - {s} ... {s}\n", .{ it.value_ptr.from, it.value_ptr.to });
}
}
}
fn diff_printchange(comptime testt: string, comptime replacement: string, item: std.StringHashMap(DiffChange).Entry) bool {
if (std.mem.startsWith(u8, item.key_ptr.*, testt)) {
std.debug.print(replacement, .{ item.key_ptr.*[4..], item.value_ptr.from, item.value_ptr.to });
return true;
}
return false;
}
fn print_dirs(w: std.fs.File.Writer, list: []const zigmod.Module) !void {
for (list) |mod| {
if (mod.is_sys_lib) continue;
if (std.mem.eql(u8, mod.id, "root")) {
try w.print(" pub const _root = \"\";\n", .{});
continue;
}
try w.print(" pub const _{s} = cache ++ \"/{}\";\n", .{ mod.short_id(), std.zig.fmtEscapes(mod.clean_path) });
}
}
fn print_deps(w: std.fs.File.Writer, m: zigmod.Module) !void {
try w.writeAll("&[_]Package{\n");
for (m.deps) |d| {
if (d.main.len == 0) {
continue;
}
if (d.for_build) {
continue;
}
try w.print(" package_data._{s},\n", .{d.id[0..12]});
}
try w.writeAll("}");
}
fn print_pkg_data_to(w: std.fs.File.Writer, notdone: *std.ArrayList(zigmod.Module), done: *std.ArrayList(zigmod.Module)) !void {
var len: usize = notdone.items.len;
while (notdone.items.len > 0) {
for (notdone.items) |mod, i| {
if (contains_all(mod.deps, done.items)) {
try w.print(
\\ pub const _{s} = Package{{
\\ .directory = dirs._{s},
\\
, .{
mod.short_id(),
mod.short_id(),
});
if (mod.main.len > 0 and !std.mem.eql(u8, mod.id, "root")) {
try w.print(
\\ .pkg = Pkg{{ .name = "{s}", .path = .{{ .path = dirs._{s} ++ "/{s}" }}, .dependencies =
, .{
mod.name,
mod.short_id(),
mod.main,
});
if (mod.has_no_zig_deps()) {
try w.writeAll(" null },\n");
} else {
try w.writeAll(" &.{");
for (mod.deps) |moddep, j| {
if (moddep.main.len == 0) continue;
try w.print(" _{s}.pkg.?", .{moddep.id[0..12]});
if (j != mod.deps.len - 1) try w.writeAll(",");
}
try w.writeAll(" } },\n");
}
}
if (mod.c_include_dirs.len > 0) {
try w.writeAll(" .c_include_dirs = &.{");
for (mod.c_include_dirs) |item, j| {
try w.print(" \"{}\"", .{std.zig.fmtEscapes(item)});
if (j != mod.c_include_dirs.len - 1) try w.writeAll(",");
}
try w.writeAll(" },\n");
}
if (mod.c_source_files.len > 0) {
try w.writeAll(" .c_source_files = &.{");
for (mod.c_source_files) |item, j| {
try w.print(" \"{}\"", .{std.zig.fmtEscapes(item)});
if (j != mod.c_source_files.len - 1) try w.writeAll(",");
}
try w.writeAll(" },\n");
}
if (mod.c_source_flags.len > 0) {
try w.writeAll(" .c_source_flags = &.{");
for (mod.c_source_flags) |item, j| {
try w.print(" \"{}\"", .{std.zig.fmtEscapes(item)});
if (j != mod.c_source_flags.len - 1) try w.writeAll(",");
}
try w.writeAll(" },\n");
}
if (mod.has_syslib_deps()) {
try w.writeAll(" .system_libs = &.{");
for (mod.deps) |item, j| {
if (!item.is_sys_lib) continue;
try w.print(" \"{}\"", .{std.zig.fmtEscapes(item.name)});
if (j != mod.deps.len - 1) try w.writeAll(",");
}
try w.writeAll(" },\n");
}
if (mod.vcpkg) {
try w.writeAll(" .vcpkg = true,\n");
}
try w.writeAll(" };\n");
try done.append(mod);
_ = notdone.orderedRemove(i);
break;
}
}
if (notdone.items.len == len) {
u.fail("notdone still has {d} items", .{len});
}
len = notdone.items.len;
}
}
/// returns if all of the zig modules in needles are in haystack
fn contains_all(needles: []zigmod.Module, haystack: []const zigmod.Module) bool {
for (needles) |item| {
if (item.main.len > 0 and !u.list_contains_gen(zigmod.Module, haystack, item)) {
return false;
}
}
return true;
}
fn print_pkgs(alloc: std.mem.Allocator, w: std.fs.File.Writer, m: zigmod.Module) !void {
try w.writeAll("struct {\n");
for (m.deps) |d| {
if (d.main.len == 0) {
continue;
}
if (d.for_build) {
continue;
}
const ident = try zig_name_from_pkg_name(alloc, d.name);
try w.print(" pub const {s} = package_data._{s};\n", .{ ident, d.id[0..12] });
}
try w.writeAll("}");
}
fn print_imports(alloc: std.mem.Allocator, w: std.fs.File.Writer, m: zigmod.Module, path: string) !void {
for (m.deps) |d| {
if (d.main.len == 0) {
continue;
}
if (!d.for_build) {
continue;
}
const ident = try zig_name_from_pkg_name(alloc, d.name);
try w.print(" pub const {s} = @import(\"{}/{}/{s}\");\n", .{ ident, std.zig.fmtEscapes(path), std.zig.fmtEscapes(d.clean_path), d.main });
}
}
fn zig_name_from_pkg_name(alloc: std.mem.Allocator, name: string) !string {
var legal = name;
legal = try std.mem.replaceOwned(u8, alloc, legal, "-", "_");
legal = try std.mem.replaceOwned(u8, alloc, legal, "/", "_");
legal = try std.mem.replaceOwned(u8, alloc, legal, ".", "_");
return legal;
} | src/cmd/fetch.zig |
const std = @import("std");
const string = []const u8;
const builtin = @import("builtin");
const deps = @import("./deps.zig");
pub fn build(b: *std.build.Builder) void {
const target = b.standardTargetOptions(.{});
b.setPreferredReleaseMode(.ReleaseSafe);
const mode = b.standardReleaseOptions();
const bootstrap = b.option(bool, "bootstrap", "bootstrapping with just the zig compiler");
const use_full_name = b.option(bool, "use-full-name", "") orelse false;
const with_arch_os = b.fmt("-{s}-{s}", .{ @tagName(target.cpu_arch orelse builtin.cpu.arch), @tagName(target.os_tag orelse builtin.os.tag) });
const exe_name = b.fmt("{s}{s}", .{ "zigmod", if (use_full_name) with_arch_os else "" });
const exe = makeExe(b, exe_name, target, mode, bootstrap);
const run_cmd = exe.run();
run_cmd.step.dependOn(b.getInstallStep());
if (b.args) |args| {
run_cmd.addArgs(args);
}
const run_step = b.step("run", "Run the app");
run_step.dependOn(&run_cmd.step);
}
fn makeExe(b: *std.build.Builder, exe_name: string, target: std.zig.CrossTarget, mode: std.builtin.Mode, bootstrap: ?bool) *std.build.LibExeObjStep {
const exe = b.addExecutable(exe_name, "src/main.zig");
exe.setTarget(target);
exe.setBuildMode(mode);
const exe_options = b.addOptions();
exe.addOptions("build_options", exe_options);
exe_options.addOption(string, "version", b.option(string, "tag", "") orelse "dev");
exe_options.addOption(bool, "bootstrap", bootstrap != null);
if (bootstrap != null) {
exe.linkLibC();
exe.addIncludeDir("./libs/yaml/include");
exe.addCSourceFile("./libs/yaml/src/api.c", &.{
// taken from https://github.com/yaml/libyaml/blob/0.2.5/CMakeLists.txt#L5-L8
"-DYAML_VERSION_MAJOR=0",
"-DYAML_VERSION_MINOR=2",
"-DYAML_VERSION_PATCH=5",
"-DYAML_VERSION_STRING=\"0.2.5\"",
"-DYAML_DECLARE_STATIC=1",
});
exe.addCSourceFile("./libs/yaml/src/dumper.c", &.{});
exe.addCSourceFile("./libs/yaml/src/emitter.c", &.{});
exe.addCSourceFile("./libs/yaml/src/loader.c", &.{});
exe.addCSourceFile("./libs/yaml/src/parser.c", &.{});
exe.addCSourceFile("./libs/yaml/src/reader.c", &.{});
exe.addCSourceFile("./libs/yaml/src/scanner.c", &.{});
exe.addCSourceFile("./libs/yaml/src/writer.c", &.{});
exe.addPackage(.{
.name = "zigmod",
.path = .{ .path = "./src/lib.zig" },
.dependencies = &[_]std.build.Pkg{
.{ .name = "zfetch", .path = .{ .path = "src/zfetch_stub.zig" } },
},
});
} else {
deps.addAllTo(exe);
}
exe.install();
return exe;
} | build.zig |
const std = @import("std");
const expect = std.testing.expect;
const expectEqual = std.testing.expectEqual;
const style = @import("style.zig");
const Style = style.Style;
const FontStyle = style.FontStyle;
const Color = style.Color;
const ParseState = enum {
Parse8,
ParseFgNon8,
ParseFg256,
ParseFgRed,
ParseFgGreen,
ParseFgBlue,
ParseBgNon8,
ParseBg256,
ParseBgRed,
ParseBgGreen,
ParseBgBlue,
};
pub fn parseStyle(code: []const u8) ?Style {
if (code.len == 0 or std.mem.eql(u8, code, "0") or std.mem.eql(u8, code, "00")) {
return null;
}
var font_style = FontStyle{};
var foreground: Color = .Default;
var background: Color = .Default;
var state = ParseState.Parse8;
var red: u8 = 0;
var green: u8 = 0;
var iter = std.mem.split(code, ";");
while (iter.next()) |str| {
const part = std.fmt.parseInt(u8, str, 10) catch return null;
switch (state) {
.Parse8 => {
switch (part) {
0 => font_style = FontStyle{},
1 => font_style.bold = true,
2 => font_style.dim = true,
3 => font_style.italic = true,
4 => font_style.underline = true,
5 => font_style.slowblink = true,
6 => font_style.rapidblink = true,
7 => font_style.reverse = true,
8 => font_style.hidden = true,
9 => font_style.crossedout = true,
20 => font_style.fraktur = true,
30 => foreground = Color.Black,
31 => foreground = Color.Red,
32 => foreground = Color.Green,
33 => foreground = Color.Yellow,
34 => foreground = Color.Blue,
35 => foreground = Color.Magenta,
36 => foreground = Color.Cyan,
37 => foreground = Color.White,
38 => state = ParseState.ParseFgNon8,
39 => foreground = Color.Default,
40 => background = Color.Black,
41 => background = Color.Red,
42 => background = Color.Green,
43 => background = Color.Yellow,
44 => background = Color.Blue,
45 => background = Color.Magenta,
46 => background = Color.Cyan,
47 => background = Color.White,
48 => state = ParseState.ParseBgNon8,
49 => background = Color.Default,
53 => font_style.overline = true,
else => {
return null;
},
}
},
.ParseFgNon8 => {
switch (part) {
5 => state = ParseState.ParseFg256,
2 => state = ParseState.ParseFgRed,
else => {
return null;
},
}
},
.ParseFg256 => {
foreground = Color{ .Fixed = part };
state = ParseState.Parse8;
},
.ParseFgRed => {
red = part;
state = ParseState.ParseFgGreen;
},
.ParseFgGreen => {
green = part;
state = ParseState.ParseFgBlue;
},
.ParseFgBlue => {
foreground = Color{
.RGB = .{
.r = red,
.g = green,
.b = part,
},
};
state = ParseState.Parse8;
},
.ParseBgNon8 => {
switch (part) {
5 => state = ParseState.ParseBg256,
2 => state = ParseState.ParseBgRed,
else => {
return null;
},
}
},
.ParseBg256 => {
background = Color{ .Fixed = part };
state = ParseState.Parse8;
},
.ParseBgRed => {
red = part;
state = ParseState.ParseBgGreen;
},
.ParseBgGreen => {
green = part;
state = ParseState.ParseBgBlue;
},
.ParseBgBlue => {
background = Color{
.RGB = .{
.r = red,
.g = green,
.b = part,
},
};
state = ParseState.Parse8;
},
}
}
if (state != ParseState.Parse8)
return null;
return Style{
.foreground = foreground,
.background = background,
.font_style = font_style,
};
}
test "parse empty style" {
expectEqual(@as(?Style, null), parseStyle(""));
expectEqual(@as(?Style, null), parseStyle("0"));
expectEqual(@as(?Style, null), parseStyle("00"));
}
test "parse bold style" {
const actual = parseStyle("01");
const expected = Style{
.font_style = FontStyle.bold,
};
expectEqual(@as(?Style, expected), actual);
}
test "parse yellow style" {
const actual = parseStyle("33");
const expected = Style{
.foreground = Color.Yellow,
.font_style = FontStyle{},
};
expectEqual(@as(?Style, expected), actual);
}
test "parse some fixed color" {
const actual = parseStyle("38;5;220;1");
const expected = Style{
.foreground = Color{ .Fixed = 220 },
.font_style = FontStyle.bold,
};
expectEqual(@as(?Style, expected), actual);
}
test "parse some rgb color" {
const actual = parseStyle("38;2;123;123;123;1");
const expected = Style{
.foreground = Color{ .RGB = .{ .r = 123, .g = 123, .b = 123 } },
.font_style = FontStyle.bold,
};
expectEqual(@as(?Style, expected), actual);
}
test "parse wrong rgb color" {
const actual = parseStyle("38;2;123");
expectEqual(@as(?Style, null), actual);
} | src/parse_style.zig |
const std = @import("std");
pub fn Earcut(comptime Scalar: type) type {
const Scalar_min = switch (Scalar) {
f16 => std.math.f16_min,
f32 => std.math.f32_min,
f64 => std.math.f64_min,
f128 => std.math.f128_min,
else => unreachable,
};
const Scalar_max = switch (Scalar) {
f16 => std.math.f16_max,
f32 => std.math.f32_max,
f64 => std.math.f64_max,
f128 => std.math.f128_max,
else => unreachable,
};
const Node = struct {
i: usize,
x: Scalar,
y: Scalar,
z: Scalar = Scalar_min,
steiner: bool = false,
prev: *@This(),
next: *@This(),
prevZ: ?*@This() = null,
nextZ: ?*@This() = null,
};
return struct {
arena: std.heap.ArenaAllocator,
const Self = @This();
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 earcut(self: *Self, data: []Scalar, hole_indicies: ?[]usize, dim: usize) ![]usize {
const hasHoles = hole_indicies != null and hole_indicies.?.len > 0;
const outerLen = if (hasHoles) hole_indicies.?[0] * dim else data.len;
const outerNode = try self.linkedList(data, 0, outerLen, dim, true);
var triangles = std.ArrayList(usize).init(&self.arena.allocator);
if (outerNode == null)
return triangles.items;
var minX: Scalar = 0.0;
var minY: Scalar = 0.0;
var maxX: Scalar = 0.0;
var maxY: Scalar = 0.0;
var size: Scalar = Scalar_min;
var node = outerNode.?;
if (hasHoles)
node = try self.eliminateHoles(data, hole_indicies.?, node, dim);
// if the shape is not too simple, we'll use z-order curve hash later;
// calculate polygon bbox
if (data.len > 80 * dim) {
minX = data[0];
maxX = data[0];
minY = data[1];
maxY = data[1];
var i = dim;
while (i < outerLen) : (i += dim) {
const x = data[i];
const y = data[i + 1];
if (x < minX) minX = x;
if (y < minY) minY = y;
if (x > maxX) maxX = x;
if (y > maxY) maxY = y;
}
// minX, minY and size are later used to transform coords into integers for z-order calculation
size = std.math.max(maxX - minX, maxY - minY);
}
try self.earcutLinked(node, &triangles, dim, minX, minY, size, -1);
return triangles.items;
}
pub const Flattened = struct {
allocator: *std.mem.Allocator,
vertices: []Scalar,
holes: []usize,
dimension: usize,
pub fn deinit(self: Flattened) void {
self.allocator.free(self.vertices);
self.allocator.free(self.holes);
}
};
pub fn flatten(comptime dim: usize, data: [][][dim]Scalar, allocator: *std.mem.Allocator) !Flattened {
var vertices_count: usize = 0;
var hole_count: usize = data.len - 1;
for (data) |ring| {
vertices_count += ring.len * dim;
}
var vertices = try allocator.alloc(Scalar, vertices_count);
var hole_indexes = try allocator.alloc(usize, hole_count);
var vert_idx: usize = 0;
var hole_idx: usize = 0;
var i: usize = 0;
while (i < data.len) : (i += 1) {
if (i > 0) {
hole_indexes[hole_idx] = vert_idx / dim;
hole_idx += 1;
}
var j: usize = 0;
while (j < data[i].len) : (j += 1) {
var d: usize = 0;
while (d < dim) : (d += 1) {
vertices[vert_idx] = data[i][j][d];
vert_idx += 1;
}
}
}
return Flattened{ .allocator = allocator, .vertices = vertices, .holes = hole_indexes, .dimension = dim };
}
fn earcutLinked(
self: *Self,
ear: ?*Node,
triangles: *std.ArrayList(usize),
dim: usize,
minX: Scalar,
minY: Scalar,
size: Scalar,
pass: isize,
) std.mem.Allocator.Error!void {
if (ear == null)
return;
if (pass == -1 and size != Scalar_min)
_ = indexCurve(ear.?, minX, minY, size);
var e = ear.?;
var stop = e;
while (e.prev != e.next) {
const prev = e.prev;
const next = e.next;
if (if (size != Scalar_min) isEarHashed(e, minX, minY, size) else isEar(e)) {
try triangles.append(prev.i / dim);
try triangles.append(e.i / dim);
try triangles.append(next.i / dim);
removeNode(e);
e = next.next;
stop = next.next;
continue;
}
e = next;
// if we looped through the while remining polygon and can't find any more ears
if (e == stop) {
if (pass == -1) {
try self.earcutLinked(filterPoints(e, null), triangles, dim, minX, minY, size, 1);
}
// if this didn't work, try curing all small self-intersections locally
else if (pass == 1) {
e = try self.cureLocalIntersections(e, triangles, dim);
try self.earcutLinked(e, triangles, dim, minX, minY, size, 2);
}
// as a last resort, try splitting the remainig polygon into two
else if (pass == 2) {
try self.splitEarcut(e, triangles, dim, minX, minY, size);
}
break;
}
}
}
fn splitEarcut(
self: *Self,
start: *Node,
triangles: *std.ArrayList(usize),
dim: usize,
minX: Scalar,
minY: Scalar,
size: Scalar,
) !void {
var a = start;
while (true) {
var b = a.next.next;
while (b != a.prev) {
if (a.i != b.i and isValidDiagonal(a, b)) {
var c = try self.splitPolygon(a, b);
//filter colinear points around the cuts
var wrapper: ?*Node = a.next;
a = filterPoints(a, wrapper).?;
wrapper = c.next;
c = filterPoints(c, wrapper).?;
// run earcut on each half
try self.earcutLinked(a, triangles, dim, minX, minY, size, -1);
try self.earcutLinked(c, triangles, dim, minX, minY, size, -1);
return;
}
b = b.next;
}
a = a.next;
if (a == start)
return;
}
}
fn cureLocalIntersections(_: *Self, start: *Node, triangles: *std.ArrayList(usize), dim: usize) !*Node {
var s = start;
var p = s;
while (true) {
var a = p.prev;
var b = p.next.next;
if (!equals(a, b) and intersects(a, p, p.next, b) and locallyInside(a, b) and locallyInside(b, a)) {
try triangles.append(a.i / dim);
try triangles.append(p.i / dim);
try triangles.append(b.i / dim);
// remove two nodes involved
removeNode(p);
removeNode(p.next);
p = b;
s = b;
}
p = p.next;
if (p == s)
return p;
}
}
fn isEar(ear: *const Node) bool {
var a = ear.prev;
var b = ear;
var c = ear.next;
if (area(a, b, c) >= 0)
return false; //reflex, can't be an ear
// now make sure we don't have other points inside the potential ear
//
var p = ear.next.next;
while (p != ear.prev) {
if (pointInTriangle(a.x, a.y, b.x, b.y, c.x, c.y, p.x, p.y) and area(p.prev, p, p.next) >= 0)
return false;
p = p.next;
}
return true;
}
fn isEarHashed(ear: *const Node, minX: Scalar, minY: Scalar, size: Scalar) bool {
var a = ear.prev;
var b = ear;
var c = ear.next;
if (area(a, b, c) >= 0)
return false; // reflex, can't be an ear
// triangle bbox; min & max are calculated like this for speed
var minTX: Scalar = 0;
var minTY: Scalar = 0;
var maxTX: Scalar = 0;
var maxTY: Scalar = 0;
if (a.x < b.x) {
minTX = if (a.x < c.x) a.x else c.x;
} else {
minTX = if (b.x < c.x) b.x else c.x;
}
if (a.y < b.y) {
minTY = if (a.y < c.y) a.y else c.y;
} else {
minTY = if (b.y < c.y) b.y else c.y;
}
if (a.x > b.x) {
maxTX = if (a.x > c.x) a.x else c.x;
} else {
maxTX = if (b.x > c.x) b.x else c.x;
}
if (a.y > b.y) {
maxTY = if (a.y > c.y) a.y else c.y;
} else {
maxTY = if (b.y > c.y) b.y else c.y;
}
// z-order range for the current triangle bbox;
const minZ = zOrder(minTX, minTY, minX, minY, size);
const maxZ = zOrder(maxTX, maxTY, minX, minY, size);
// first look for points inside the triangle in increasing z-order
var p = ear.nextZ;
while (p != null and p.?.z <= maxZ) {
if (p != ear.prev and p != ear.next and pointInTriangle(a.x, a.y, b.x, b.y, c.x, c.y, p.?.x, p.?.y) and area(p.?.prev, p.?, p.?.next) >= 0)
return false;
p = p.?.nextZ;
}
// then look for points in decreasing z-order
p = ear.prevZ;
while (p != null and p.?.z >= minZ) {
if (p != ear.prev and p != ear.next and pointInTriangle(a.x, a.y, b.x, b.y, c.x, c.y, p.?.x, p.?.y) and area(p.?.prev, p.?, p.?.next) >= 0)
return false;
p = p.?.prevZ;
}
return true;
}
fn zOrder(x: Scalar, y: Scalar, minX: Scalar, minY: Scalar, size: Scalar) Scalar {
// coords are transformed into non-negative 15-bit integer range
var lx = @floatToInt(i32, 32767 * (x - minX) / size);
var ly = @floatToInt(i32, 32767 * (y - minY) / size);
lx = (lx | (lx << 8)) & 0x00FF00FF;
lx = (lx | (lx << 4)) & 0x0F0F0F0F;
lx = (lx | (lx << 2)) & 0x33333333;
lx = (lx | (lx << 1)) & 0x55555555;
ly = (ly | (ly << 8)) & 0x00FF00FF;
ly = (ly | (ly << 4)) & 0x0F0F0F0F;
ly = (ly | (ly << 2)) & 0x33333333;
ly = (ly | (ly << 1)) & 0x55555555;
return @intToFloat(Scalar, lx | (ly << 1));
}
fn indexCurve(start: *Node, minX: Scalar, minY: Scalar, size: Scalar) void {
var p = start;
while (true) {
if (p.z == Scalar_min)
p.z = zOrder(p.x, p.y, minX, minY, size);
p.prevZ = p.prev;
p.nextZ = p.next;
p = p.next;
if (p == start)
break;
}
p.prevZ.?.nextZ = null;
p.prevZ = null;
_ = sortLinked(p);
}
fn sortLinked(list: *Node) *Node {
var inSize: i32 = 1;
var l: ?*Node = list;
while (true) {
var p = l;
l = null;
var tail: ?*Node = null;
var numMerges: usize = 0;
while (p != null) {
numMerges += 1;
var q = p;
var pSize: usize = 0;
var i: usize = 0;
while (i < inSize) : (i += 1) {
pSize += 1;
q = q.?.nextZ;
if (q == null)
break;
}
var qSize = inSize;
while (pSize > 0 or (qSize > 0 and q != null)) {
var e: ?*Node = p;
if (pSize == 0) {
e = q;
q = q.?.nextZ;
qSize -= 1;
} else if (qSize == 0 or q == null) {
e = p;
p = p.?.nextZ;
pSize -= 1;
} else if (p.?.z <= q.?.z) {
e = p;
p = p.?.nextZ;
pSize -= 1;
} else {
e = q;
q = q.?.nextZ;
qSize -= 1;
}
if (tail != null) {
tail.?.nextZ = e;
} else {
l = e;
}
e.?.prevZ = tail;
tail = e;
}
p = q;
}
tail.?.nextZ = null;
inSize *= 2;
if (numMerges <= 1)
break;
}
return l.?;
}
fn eliminateHoles(self: *Self, data: []Scalar, holeIndices: []usize, outerNode: *Node, dim: usize) !*Node {
var queue = std.ArrayList(*Node).init(&self.arena.allocator);
const len = holeIndices.len;
var i: usize = 0;
while (i < len) : (i += 1) {
var start = holeIndices[i] * dim;
var end = if (i < len - 1) holeIndices[i + 1] * dim else data.len;
var list = try self.linkedList(data, start, end, dim, false);
if (list) |v| {
if (v == v.next)
v.steiner = true;
try queue.append(getLeftmost(v));
}
}
std.sort.sort(*Node, queue.items, {}, nodeCompare);
var n = outerNode;
for (queue.items) |node| {
try self.eliminateHole(node, n);
n = filterPoints(n, n.next).?;
}
return n;
}
fn nodeCompare(_: void, left: *Node, right: *Node) bool {
if (left.x > right.x)
return false;
return true;
}
fn filterPoints(start: *Node, end: ?*Node) ?*Node {
var e = end;
if (end == null)
e = start;
var p = start;
while (true) {
var again = false;
if (!p.steiner and equals(p, p.next) or area(p.prev, p, p.next) == 0) {
removeNode(p);
p = p.prev;
e = p.prev;
if (p == p.next)
return null;
again = true;
} else {
p = p.next;
}
if (!(again or p != e))
break;
}
return e;
}
fn eliminateHole(self: *Self, hole: *Node, outerNode: *Node) !void {
var node = findHoleBridge(hole, outerNode);
if (node) |n| {
var b = try self.splitPolygon(n, hole);
_ = filterPoints(b, b.next);
}
}
fn splitPolygon(self: *Self, a: *Node, b: *Node) !*Node {
var a2 = try self.arena.allocator.create(Node);
a2.* = .{ .i = a.i, .x = a.x, .y = a.y, .next = a2, .prev = a2 };
var b2 = try self.arena.allocator.create(Node);
b2.* = .{ .i = b.i, .x = b.x, .y = b.y, .next = b2, .prev = b2 };
var an = a.next;
var bp = b.prev;
a.next = b;
b.prev = a;
a2.next = an;
an.prev = a2;
b2.next = a2;
a2.prev = b2;
bp.next = b2;
b2.prev = bp;
return b2;
}
fn findHoleBridge(hole: *Node, outerNode: *Node) ?*Node {
var p = outerNode;
var hx = hole.x;
var hy = hole.y;
var qx: Scalar = -Scalar_max;
var m: ?*Node = null;
// find a segment intersected by a ray from the hole's leftmost point to
// the left;
// segment's endpoint with lesser x will be potential connection point
while (true) {
if (hy <= p.y and hy >= p.next.y) {
var x = p.x + (hy - p.y) * (p.next.x - p.x) / (p.next.y - p.y);
if (x <= hx and x > qx) {
qx = x;
if (x == hx) {
if (hy == p.y)
return p;
if (hy == p.next.y)
return p.next;
}
m = if (p.x < p.next.x) p else p.next;
}
}
p = p.next;
if (p == outerNode)
break;
}
if (m == null)
return null;
if (hx == qx)
return m.?.prev; // hole touches outer segment; pick lower endpoint
// look for points inside the triangle of hole point, segment
// intersection and endpoint;
// if there are no points found, we have a valid connection;
// otherwise choose the point of the minimum angle with the ray as
// connection point
var stop = m;
var mx = m.?.x;
var my = m.?.y;
var tanMin: Scalar = Scalar_max;
p = m.?.next;
while (p != stop) {
if (hx >= p.x and p.x >= mx and pointInTriangle(if (hy < my) hx else qx, hy, mx, my, if (hy < my) qx else hx, hy, p.x, p.y)) {
const tan = std.math.fabs(hy - p.y) / (hx - p.x); // tangential
if ((tan < tanMin or (tan == tanMin and p.x > m.?.x)) and locallyInside(p, hole)) {
m = p;
tanMin = tan;
}
}
p = p.next;
}
return m;
}
fn linkedList(self: *Self, data: []Scalar, start: usize, end: usize, dim: usize, clockwise: bool) !?*Node {
var last: ?*Node = null;
if (clockwise == (signedArea(data, start, end, dim) > 0)) {
var i = start;
while (i < end) : (i += dim) {
last = try self.insertNode(i, data[i], data[i + 1], last);
}
} else {
var i = @intCast(i64, (end - dim));
while (i >= start) : (i -= @intCast(i64, dim)) {
const idx = @intCast(usize, i);
last = try self.insertNode(idx, data[idx], data[idx + 1], last);
}
}
if (last) |v| {
if (equals(v, v.next)) {
removeNode(v);
last = v.next;
}
}
return last;
}
fn removeNode(p: *Node) void {
p.next.prev = p.prev;
p.prev.next = p.next;
if (p.prevZ) |v| {
v.nextZ = p.nextZ;
}
if (p.nextZ) |v| {
v.prevZ = p.prevZ;
}
}
fn insertNode(self: *Self, i: usize, x: Scalar, y: Scalar, last: ?*Node) !*Node {
var p = try self.arena.allocator.create(Node);
if (last) |v| {
p.* = .{ .i = i, .x = x, .y = y, .next = v.next, .prev = v };
v.next.prev = p;
v.next = p;
} else {
p.* = .{ .i = i, .x = x, .y = y, .next = p, .prev = p };
}
return p;
}
fn signedArea(data: []Scalar, start: usize, end: usize, dim: usize) Scalar {
var sum: Scalar = 0.0;
var j = end - dim;
var i = start;
while (i < end) : (i += dim) {
sum += (data[j] - data[i]) * (data[i + 1] + data[j + 1]);
j = i;
}
return sum;
}
fn getLeftmost(start: *Node) *Node {
var p = start;
var leftmost = start;
while (true) {
if (p.x < leftmost.x)
leftmost = p;
p = p.next;
if (p == start)
break;
}
return leftmost;
}
fn equals(p1: *const Node, p2: *const Node) bool {
return p1.x == p2.x and p1.y == p2.y;
}
fn area(p: *const Node, q: *const Node, r: *const Node) Scalar {
return (q.y - p.y) * (r.x - q.x) - (q.x - p.x) * (r.y - q.y);
}
fn isValidDiagonal(a: *const Node, b: *const Node) bool {
return a.next.i != b.i and a.prev.i != b.i and !intersectsPolygon(a, b) and locallyInside(a, b) and locallyInside(b, a) and middleInside(a, b);
}
fn middleInside(a: *const Node, b: *const Node) bool {
var p = a;
var inside = false;
var px = (a.x + b.x) / 2;
var py = (a.y + b.y) / 2;
while (true) {
if (((p.y > py) != (p.next.y > py)) and (px < (p.next.x - p.x) * (py - p.y) / (p.next.y - p.y) + p.x))
inside = !inside;
p = p.next;
if (p == a)
break;
}
return inside;
}
fn intersectsPolygon(a: *const Node, b: *const Node) bool {
var p = a;
while (true) {
if (p.i != a.i and p.next.i != a.i and p.i != b.i and p.next.i != b.i and intersects(p, p.next, a, b))
return true;
p = p.next;
if (p == a)
break;
}
return false;
}
fn intersects(p1: *const Node, q1: *const Node, p2: *const Node, q2: *const Node) bool {
if ((equals(p1, q1) and equals(p2, q2)) or (equals(p1, q2) and equals(p2, q1)))
return true;
return (area(p1, q1, p2) > 0) != (area(p1, q1, q2) > 0) and (area(p2, q2, p1) > 0) != (area(p2, q2, q1) > 0);
}
fn locallyInside(a: *const Node, b: *const Node) bool {
return if (area(a.prev, a, a.next) < 0)
area(a, b, a.next) >= 0 and area(a, a.prev, b) >= 0
else
area(a, b, a.prev) < 0 or area(a, a.next, b) < 0;
}
fn pointInTriangle(ax: Scalar, ay: Scalar, bx: Scalar, by: Scalar, cx: Scalar, cy: Scalar, px: Scalar, py: Scalar) bool {
return (cx - px) * (ay - py) - (ax - px) * (cy - py) >= 0 and (ax - px) * (by - py) - (bx - px) * (ay - py) >= 0 and (bx - px) * (cy - py) - (cx - px) * (by - py) >= 0;
}
};
} | src/main.zig |
const std = @import("std");
const debug = std.debug;
const math = std.math;
const mem = std.mem;
const fmt = std.fmt;
const io = std.io;
const Endian = std.builtin.Endian;
const float_t = f64;
const int_t = u64;
const size_t = usize;
const FixedBufferReader = io.FixedBufferStream([]const u8).Reader;
comptime {
debug.assert(@bitSizeOf(float_t) == @bitSizeOf(int_t));
}
pub const State = struct {
version: u8,
endian: Endian,
sizeof_int: u8,
sizeof_size: u8,
sizeof_instruction: u8,
sizeof_number: u8,
number_type: NumberFormat,
pub fn format(self: State, comptime str: []const u8, options: fmt.FormatOptions, writer: anytype) !void {
try writer.print("Lua {x}, {s} Endian, {d}-bit Integers, {d}-bit Sizes, {d}-bit Instructions, {d}-bit {s} Numbers", .{
self.version, @tagName(self.endian), self.sizeof_int * 8, self.sizeof_size * 8, self.sizeof_instruction * 8,
self.sizeof_number * 8, @tagName(self.number_type),
});
}
pub fn init(header: []const u8) !State {
if (header.len < 12) return error.InvalidHeader;
if (!mem.eql(u8, header[0..4], "\x1BLua")) return error.InvalidBytecode;
const version_byte = header[4];
const format_byte = header[5];
const endian_byte = header[6];
const sizeof_int_byte = header[7];
const sizeof_size_byte = header[8];
const sizeof_instruction_byte = header[9];
const sizeof_number_byte = header[10];
const number_type_byte = header[11];
if (format_byte != 0x00) return error.InvalidFormat;
const endian = switch (endian_byte) {
0x00 => Endian.Big,
0x01 => Endian.Little,
else => return error.InvalidEndian,
};
if (sizeof_int_byte > @sizeOf(size_t)) return error.IntegerTooLarge;
if (sizeof_size_byte > @sizeOf(size_t)) return error.SizeTooLarge;
if (sizeof_instruction_byte != 4) return error.UnknownInstructionSize;
if (sizeof_number_byte > @sizeOf(size_t)) return error.NumberTooLarge;
const number_type = switch (number_type_byte) {
0x00 => NumberFormat.floating,
0x01 => NumberFormat.integer,
else => return error.InvalidNumberType,
};
return State{
.version = version_byte,
.endian = endian,
.sizeof_int = sizeof_int_byte,
.sizeof_size = sizeof_size_byte,
.sizeof_instruction = sizeof_instruction_byte,
.sizeof_number = sizeof_number_byte,
.number_type = number_type,
};
}
pub fn readInteger(self: State, reader: FixedBufferReader) !int_t {
var buffer = mem.zeroes([@divExact(@typeInfo(int_t).Int.bits, 8)]u8);
switch (self.endian) {
.Big => {
_ = try reader.readAll(buffer[buffer.len - self.sizeof_int ..]);
return mem.readIntBig(int_t, &buffer);
},
.Little => {
_ = try reader.readAll(buffer[0..self.sizeof_int]);
return mem.readIntLittle(int_t, &buffer);
},
}
}
pub fn readSize(self: State, reader: FixedBufferReader) !size_t {
var buffer = mem.zeroes([@divExact(@typeInfo(size_t).Int.bits, 8)]u8);
switch (self.endian) {
.Big => {
_ = try reader.readAll(buffer[buffer.len - self.sizeof_size ..]);
return mem.readIntBig(size_t, &buffer);
},
.Little => {
_ = try reader.readAll(buffer[0..self.sizeof_size]);
return mem.readIntLittle(size_t, &buffer);
},
}
}
pub fn readString(self: State, allocator: *mem.Allocator, reader: FixedBufferReader) ![:0]const u8 {
const size = try self.readSize(reader);
var buffer = try allocator.allocSentinel(u8, size, 0);
_ = try reader.readAll(buffer);
return buffer;
}
pub fn readNumber(self: State, reader: FixedBufferReader) !LuaNumber {
var buffer = mem.zeroes([@divExact(@typeInfo(int_t).Int.bits, 8)]u8);
switch (self.endian) {
.Big => {
_ = try reader.readAll(buffer[buffer.len - self.sizeof_number ..]);
const int = mem.readIntBig(int_t, &buffer);
switch (self.number_type) {
.integer => return LuaNumber{
.integer = int,
},
.floating => return LuaNumber{
.floating = @bitCast(float_t, int),
},
}
},
.Little => {
_ = try reader.readAll(buffer[0..self.sizeof_number]);
const int = mem.readIntLittle(int_t, &buffer);
switch (self.number_type) {
.integer => return LuaNumber{
.integer = int,
},
.floating => return LuaNumber{
.floating = @bitCast(float_t, int),
},
}
},
}
}
};
pub const NumberFormat = std.meta.TagType(LuaNumber);
pub const LuaNumber = union(enum) {
floating: float_t,
integer: int_t,
};
pub const String = [:0]const u8;
pub const Instruction = union(enum) {
pub const Opcode = enum(u6) {
MOVE = 0,
LOADK = 1,
LOADBOOL = 2,
LOADNIL = 3,
GETUPVAL = 4,
GETGLOBAL = 5,
GETTABLE = 6,
SETGLOBAL = 7,
SETUPVAL = 8,
SETTABLE = 9,
NEWTABLE = 10,
SELF = 11,
ADD = 12,
SUB = 13,
MUL = 14,
DIV = 15,
MOD = 16,
POW = 17,
UNM = 18,
NOT = 19,
LEN = 20,
CONCAT = 21,
JMP = 22,
EQ = 23,
LT = 24,
LE = 25,
TEST = 26,
TESTSET = 27,
CALL = 28,
TAILCALL = 29,
RETURN = 30,
FORLOOP = 31,
FORPREP = 32,
TFORLOOP = 33,
SETLIST = 34,
CLOSE = 35,
CLOSURE = 36,
VARARG = 37,
};
pub const iABC = struct {
opcode: Opcode,
A: u8,
B: u9,
C: u9,
};
pub const iABx = struct {
opcode: Opcode,
A: u8,
Bx: u18,
};
pub const iAsBx = struct {
pub const Bias = -math.maxInt(i18);
opcode: Opcode,
A: u8,
sBx: i19,
};
ABC: iABC,
ABx: iABx,
AsBx: iAsBx,
pub fn format(self: Instruction, comptime str: []const u8, options: fmt.FormatOptions, writer: anytype) !void {
switch (self) {
.ABC => |inst| {
try writer.print("{s: <9} ", .{@tagName(inst.opcode)});
switch (inst.opcode) {
.CLOSE => {
try writer.print("{d}", .{inst.A});
},
.MOVE, .LOADNIL, .GETUPVAL, .SETUPVAL, .UNM, .NOT, .LEN, .RETURN, .VARARG => {
try writer.print("{d}, {d}", .{ inst.A, inst.B });
},
.TEST, .TFORLOOP => {
try writer.print("{d}, {d}", .{ inst.A, inst.C });
},
.LOADBOOL, .GETTABLE, .SETTABLE, .NEWTABLE, .SELF, .ADD, .SUB, .MUL, .DIV, .MOD, .POW, .CONCAT, .EQ, .LT, .LE, .TESTSET, .CALL, .TAILCALL, .SETLIST => {
try writer.print("{d}, {d}, {d}", .{ inst.A, inst.B, inst.C });
},
else => unreachable,
}
},
.ABx => |inst| {
try writer.print("{s: <9} {d}, {d}", .{ @tagName(inst.opcode), inst.A, inst.Bx });
},
.AsBx => |inst| {
try writer.print("{s: <9} {d}, {d}", .{ @tagName(inst.opcode), inst.A, inst.sBx });
},
}
}
pub fn decode(input: u32) Instruction {
const opcode = @intToEnum(Opcode, @truncate(u6, input));
switch (opcode) {
.MOVE, .LOADBOOL, .LOADNIL, .GETUPVAL, .GETTABLE, .SETUPVAL, .SETTABLE, .NEWTABLE, .SELF, .ADD, .SUB, .MUL, .DIV, .MOD, .POW, .UNM, .NOT, .LEN, .CONCAT, .EQ, .LT, .LE, .TEST, .TESTSET, .CALL, .TAILCALL, .RETURN, .TFORLOOP, .SETLIST, .CLOSE, .VARARG => {
return .{
.ABC = .{
.opcode = opcode,
.A = @truncate(u8, input >> 6),
.B = @truncate(u9, input >> 14),
.C = @truncate(u9, input >> 23),
},
};
},
.LOADK, .GETGLOBAL, .SETGLOBAL, .CLOSURE => {
return .{
.ABx = .{
.opcode = opcode,
.A = @truncate(u8, input >> 6),
.Bx = @truncate(u18, input >> 14),
},
};
},
.JMP, .FORLOOP, .FORPREP => {
return .{
.AsBx = .{
.opcode = opcode,
.A = @truncate(u8, input >> 6),
.sBx = @intCast(i18, @intCast(i19, @truncate(u18, input >> 14)) + iAsBx.Bias),
},
};
},
}
}
};
pub const Constant = union(enum) {
nil: void,
boolean: bool,
number: LuaNumber,
string: String,
};
pub const Chunk = struct {
allocator: *mem.Allocator,
state: State,
name: String,
first_line: int_t,
last_line: int_t,
n_upvalues: u8,
n_arguments: u8,
vararg: u8,
stack_size: u8,
instructions: []const Instruction,
constants: []const Constant,
prototypes: []const *Chunk,
debug: DebugInfo,
const DecodeError = mem.Allocator.Error || FixedBufferReader.Error || error{ InvalidConstantType, EndOfStream };
pub fn format(self: Chunk, comptime str: []const u8, options: fmt.FormatOptions, writer: anytype) @TypeOf(writer).Error!void {
try writer.print("\nChunk[{}]: {s} on lines {} to {}, {} upvalues, {} arguments, {b:0>3} vararg\n", .{
self.stack_size, self.name, self.first_line, self.last_line, self.n_upvalues, self.n_arguments, self.vararg,
});
try writer.print("Constants[{}]: \n", .{self.constants.len});
for (self.constants) |constant, i| {
try writer.print(" {} ({s}): ", .{ i, @tagName(constant) });
switch (constant) {
.nil => try writer.writeAll("nil"),
.boolean => |data| try writer.print("{}", .{data}),
.number => |data| try writer.print("{}", .{data}),
.string => |data| {
if (data.len > 32) {
try writer.print("\"{}...\"", .{
std.zig.fmtEscapes(data[0..32]),
});
} else {
try writer.print("\"{}\"", .{
std.zig.fmtEscapes(data[0 .. data.len - 1]),
});
}
},
}
try writer.writeAll("\n");
}
try writer.print("Instructions[{}]: \n", .{self.instructions.len});
for (self.instructions) |instruction| {
try writer.print(" {}\n", .{instruction});
}
try writer.print("Prototypes[{}]: \n", .{self.prototypes.len});
for (self.prototypes) |proto| {
try proto.format(str, options, writer);
}
try writer.print("Source Lines[{}]: ", .{self.debug.lines.len});
for (self.debug.lines) |line| {
try writer.print("{}, ", .{line});
}
try writer.writeAll("\n");
try writer.print("Locals[{}]: \n", .{self.debug.locals.len});
for (self.debug.locals) |local, i| {
try writer.print(" {}: '{s}' from {} to {}\n", .{ i, local.name, local.start_pc, local.end_pc });
}
try writer.print("Upvalues[{}]: \n", .{self.debug.upvalues.len});
for (self.debug.upvalues) |upvalue, i| {
try writer.print(" {}: '{s}'", .{ i, upvalue.name });
}
}
pub fn decode(allocator: *mem.Allocator, state: State, reader: FixedBufferReader) DecodeError!*Chunk {
var chunk = try allocator.create(Chunk);
errdefer allocator.destroy(chunk);
chunk.allocator = allocator;
chunk.state = state;
chunk.name = try state.readString(allocator, reader);
errdefer allocator.free(chunk.name);
chunk.first_line = try state.readInteger(reader);
chunk.last_line = try state.readInteger(reader);
chunk.n_upvalues = try reader.readInt(u8, state.endian);
chunk.n_arguments = try reader.readInt(u8, state.endian);
chunk.vararg = try reader.readInt(u8, state.endian);
chunk.stack_size = try reader.readInt(u8, state.endian);
{
const list_size = try state.readInteger(reader);
var instructions = try allocator.alloc(Instruction, list_size);
var i: usize = 0;
while (i < list_size) : (i += 1) {
const instr_int = try reader.readInt(u32, state.endian);
instructions[i] = Instruction.decode(instr_int);
}
chunk.instructions = instructions;
}
{
const list_size = try state.readInteger(reader);
var constants = try allocator.alloc(Constant, list_size);
var i: usize = 0;
while (i < list_size) : (i += 1) {
const const_type = try reader.readInt(u8, state.endian);
switch (const_type) {
0 => {
constants[i] = Constant.nil;
},
1 => {
constants[i] = .{
.boolean = (try reader.readInt(u8, state.endian)) != 0,
};
},
3 => {
constants[i] = .{
.number = try state.readNumber(reader),
};
},
4 => {
constants[i] = .{
.string = try state.readString(allocator, reader),
};
},
else => return error.InvalidConstantType,
}
}
chunk.constants = constants;
}
{
const list_size = try state.readInteger(reader);
var prototypes = try allocator.alloc(*Chunk, list_size);
var i: usize = 0;
while (i < list_size) : (i += 1) {
prototypes[i] = try Chunk.decode(allocator, state, reader);
}
chunk.prototypes = prototypes;
}
var debug_info: DebugInfo = undefined;
{
const list_size = try state.readInteger(reader);
var lineinfo = try allocator.alloc(size_t, list_size);
var i: usize = 0;
while (i < list_size) : (i += 1) {
lineinfo[i] = try state.readInteger(reader);
}
debug_info.lines = lineinfo;
}
{
const list_size = try state.readInteger(reader);
var locals = try allocator.alloc(DebugLocal, list_size);
var i: usize = 0;
while (i < list_size) : (i += 1) {
locals[i] = .{
.name = try state.readString(allocator, reader),
.start_pc = try state.readInteger(reader),
.end_pc = try state.readInteger(reader),
};
}
debug_info.locals = locals;
}
{
const list_size = try state.readInteger(reader);
var upvalues = try allocator.alloc(DebugUpvalue, list_size);
var i: usize = 0;
while (i < list_size) : (i += 1) {
upvalues[i] = .{
.name = try state.readString(allocator, reader),
};
}
debug_info.upvalues = upvalues;
}
chunk.debug = debug_info;
return chunk;
}
pub fn deinit(self: *Chunk) void {
self.allocator.free(self.name);
for (self.constants) |constant| {
switch (constant) {
.string => |data| {
self.allocator.free(data);
},
else => {},
}
}
for (self.prototypes) |proto| {
proto.deinit();
}
for (self.debug.locals) |local| {
self.allocator.free(local.name);
}
for (self.debug.upvalues) |upvalue| {
self.allocator.free(upvalue.name);
}
self.allocator.free(self.instructions);
self.allocator.free(self.constants);
self.allocator.free(self.prototypes);
self.allocator.free(self.debug.lines);
self.allocator.free(self.debug.locals);
self.allocator.free(self.debug.upvalues);
self.allocator.destroy(self);
}
};
pub const DebugLocal = struct {
name: String,
start_pc: size_t,
end_pc: size_t,
};
pub const DebugUpvalue = struct {
name: String,
};
pub const DebugInfo = struct {
lines: []size_t,
locals: []DebugLocal,
upvalues: []DebugUpvalue,
}; | src/state.zig |
//--------------------------------------------------------------------------------
// Section: Types (9)
//--------------------------------------------------------------------------------
const CLSID_InkDesktopHost_Value = @import("../../zig.zig").Guid.initString("062584a6-f830-4bdc-a4d2-0a10ab062b1d");
pub const CLSID_InkDesktopHost = &CLSID_InkDesktopHost_Value;
// TODO: this type is limited to platform 'windows10.0.10240'
const IID_IInkCommitRequestHandler_Value = @import("../../zig.zig").Guid.initString("fabea3fc-b108-45b6-a9fc-8d08fa9f85cf");
pub const IID_IInkCommitRequestHandler = &IID_IInkCommitRequestHandler_Value;
pub const IInkCommitRequestHandler = extern struct {
pub const VTable = extern struct {
base: IUnknown.VTable,
OnCommitRequested: fn(
self: *const IInkCommitRequestHandler,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
};
vtable: *const VTable,
pub fn MethodMixin(comptime T: type) type { return struct {
pub usingnamespace IUnknown.MethodMixin(T);
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IInkCommitRequestHandler_OnCommitRequested(self: *const T) callconv(.Inline) HRESULT {
return @ptrCast(*const IInkCommitRequestHandler.VTable, self.vtable).OnCommitRequested(@ptrCast(*const IInkCommitRequestHandler, self));
}
};}
pub usingnamespace MethodMixin(@This());
};
// TODO: this type is limited to platform 'windows10.0.10240'
const IID_IInkPresenterDesktop_Value = @import("../../zig.zig").Guid.initString("73f3c0d9-2e8b-48f3-895e-20cbd27b723b");
pub const IID_IInkPresenterDesktop = &IID_IInkPresenterDesktop_Value;
pub const IInkPresenterDesktop = extern struct {
pub const VTable = extern struct {
base: IUnknown.VTable,
SetRootVisual: fn(
self: *const IInkPresenterDesktop,
rootVisual: ?*IUnknown,
device: ?*IUnknown,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
SetCommitRequestHandler: fn(
self: *const IInkPresenterDesktop,
handler: ?*IInkCommitRequestHandler,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
GetSize: fn(
self: *const IInkPresenterDesktop,
width: ?*f32,
height: ?*f32,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
SetSize: fn(
self: *const IInkPresenterDesktop,
width: f32,
height: f32,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
OnHighContrastChanged: fn(
self: *const IInkPresenterDesktop,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
};
vtable: *const VTable,
pub fn MethodMixin(comptime T: type) type { return struct {
pub usingnamespace IUnknown.MethodMixin(T);
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IInkPresenterDesktop_SetRootVisual(self: *const T, rootVisual: ?*IUnknown, device: ?*IUnknown) callconv(.Inline) HRESULT {
return @ptrCast(*const IInkPresenterDesktop.VTable, self.vtable).SetRootVisual(@ptrCast(*const IInkPresenterDesktop, self), rootVisual, device);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IInkPresenterDesktop_SetCommitRequestHandler(self: *const T, handler: ?*IInkCommitRequestHandler) callconv(.Inline) HRESULT {
return @ptrCast(*const IInkPresenterDesktop.VTable, self.vtable).SetCommitRequestHandler(@ptrCast(*const IInkPresenterDesktop, self), handler);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IInkPresenterDesktop_GetSize(self: *const T, width: ?*f32, height: ?*f32) callconv(.Inline) HRESULT {
return @ptrCast(*const IInkPresenterDesktop.VTable, self.vtable).GetSize(@ptrCast(*const IInkPresenterDesktop, self), width, height);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IInkPresenterDesktop_SetSize(self: *const T, width: f32, height: f32) callconv(.Inline) HRESULT {
return @ptrCast(*const IInkPresenterDesktop.VTable, self.vtable).SetSize(@ptrCast(*const IInkPresenterDesktop, self), width, height);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IInkPresenterDesktop_OnHighContrastChanged(self: *const T) callconv(.Inline) HRESULT {
return @ptrCast(*const IInkPresenterDesktop.VTable, self.vtable).OnHighContrastChanged(@ptrCast(*const IInkPresenterDesktop, self));
}
};}
pub usingnamespace MethodMixin(@This());
};
// TODO: this type is limited to platform 'windows10.0.10240'
const IID_IInkHostWorkItem_Value = @import("../../zig.zig").Guid.initString("ccda0a9a-1b78-4632-bb96-97800662e26c");
pub const IID_IInkHostWorkItem = &IID_IInkHostWorkItem_Value;
pub const IInkHostWorkItem = extern struct {
pub const VTable = extern struct {
base: IUnknown.VTable,
Invoke: fn(
self: *const IInkHostWorkItem,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
};
vtable: *const VTable,
pub fn MethodMixin(comptime T: type) type { return struct {
pub usingnamespace IUnknown.MethodMixin(T);
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IInkHostWorkItem_Invoke(self: *const T) callconv(.Inline) HRESULT {
return @ptrCast(*const IInkHostWorkItem.VTable, self.vtable).Invoke(@ptrCast(*const IInkHostWorkItem, self));
}
};}
pub usingnamespace MethodMixin(@This());
};
// TODO: this type is limited to platform 'windows10.0.10240'
const IID_IInkDesktopHost_Value = @import("../../zig.zig").Guid.initString("4ce7d875-a981-4140-a1ff-ad93258e8d59");
pub const IID_IInkDesktopHost = &IID_IInkDesktopHost_Value;
pub const IInkDesktopHost = extern struct {
pub const VTable = extern struct {
base: IUnknown.VTable,
QueueWorkItem: fn(
self: *const IInkDesktopHost,
workItem: ?*IInkHostWorkItem,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
CreateInkPresenter: fn(
self: *const IInkDesktopHost,
riid: ?*const Guid,
ppv: ?*?*anyopaque,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
CreateAndInitializeInkPresenter: fn(
self: *const IInkDesktopHost,
rootVisual: ?*IUnknown,
width: f32,
height: f32,
riid: ?*const Guid,
ppv: ?*?*anyopaque,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
};
vtable: *const VTable,
pub fn MethodMixin(comptime T: type) type { return struct {
pub usingnamespace IUnknown.MethodMixin(T);
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IInkDesktopHost_QueueWorkItem(self: *const T, workItem: ?*IInkHostWorkItem) callconv(.Inline) HRESULT {
return @ptrCast(*const IInkDesktopHost.VTable, self.vtable).QueueWorkItem(@ptrCast(*const IInkDesktopHost, self), workItem);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IInkDesktopHost_CreateInkPresenter(self: *const T, riid: ?*const Guid, ppv: ?*?*anyopaque) callconv(.Inline) HRESULT {
return @ptrCast(*const IInkDesktopHost.VTable, self.vtable).CreateInkPresenter(@ptrCast(*const IInkDesktopHost, self), riid, ppv);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IInkDesktopHost_CreateAndInitializeInkPresenter(self: *const T, rootVisual: ?*IUnknown, width: f32, height: f32, riid: ?*const Guid, ppv: ?*?*anyopaque) callconv(.Inline) HRESULT {
return @ptrCast(*const IInkDesktopHost.VTable, self.vtable).CreateAndInitializeInkPresenter(@ptrCast(*const IInkDesktopHost, self), rootVisual, width, height, riid, ppv);
}
};}
pub usingnamespace MethodMixin(@This());
};
const CLSID_InkD2DRenderer_Value = @import("../../zig.zig").Guid.initString("4044e60c-7b01-4671-a97c-04e0210a07a5");
pub const CLSID_InkD2DRenderer = &CLSID_InkD2DRenderer_Value;
pub const INK_HIGH_CONTRAST_ADJUSTMENT = enum(i32) {
SYSTEM_COLORS_WHEN_NECESSARY = 0,
SYSTEM_COLORS = 1,
ORIGINAL_COLORS = 2,
};
pub const USE_SYSTEM_COLORS_WHEN_NECESSARY = INK_HIGH_CONTRAST_ADJUSTMENT.SYSTEM_COLORS_WHEN_NECESSARY;
pub const USE_SYSTEM_COLORS = INK_HIGH_CONTRAST_ADJUSTMENT.SYSTEM_COLORS;
pub const USE_ORIGINAL_COLORS = INK_HIGH_CONTRAST_ADJUSTMENT.ORIGINAL_COLORS;
// TODO: this type is limited to platform 'windows10.0.10240'
const IID_IInkD2DRenderer_Value = @import("../../zig.zig").Guid.initString("407fb1de-f85a-4150-97cf-b7fb274fb4f8");
pub const IID_IInkD2DRenderer = &IID_IInkD2DRenderer_Value;
pub const IInkD2DRenderer = extern struct {
pub const VTable = extern struct {
base: IUnknown.VTable,
Draw: fn(
self: *const IInkD2DRenderer,
pD2D1DeviceContext: ?*IUnknown,
pInkStrokeIterable: ?*IUnknown,
fHighContrast: BOOL,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
};
vtable: *const VTable,
pub fn MethodMixin(comptime T: type) type { return struct {
pub usingnamespace IUnknown.MethodMixin(T);
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IInkD2DRenderer_Draw(self: *const T, pD2D1DeviceContext: ?*IUnknown, pInkStrokeIterable: ?*IUnknown, fHighContrast: BOOL) callconv(.Inline) HRESULT {
return @ptrCast(*const IInkD2DRenderer.VTable, self.vtable).Draw(@ptrCast(*const IInkD2DRenderer, self), pD2D1DeviceContext, pInkStrokeIterable, fHighContrast);
}
};}
pub usingnamespace MethodMixin(@This());
};
const IID_IInkD2DRenderer2_Value = @import("../../zig.zig").Guid.initString("0a95dcd9-4578-4b71-b20b-bf664d4bfeee");
pub const IID_IInkD2DRenderer2 = &IID_IInkD2DRenderer2_Value;
pub const IInkD2DRenderer2 = extern struct {
pub const VTable = extern struct {
base: IUnknown.VTable,
Draw: fn(
self: *const IInkD2DRenderer2,
pD2D1DeviceContext: ?*IUnknown,
pInkStrokeIterable: ?*IUnknown,
highContrastAdjustment: INK_HIGH_CONTRAST_ADJUSTMENT,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
};
vtable: *const VTable,
pub fn MethodMixin(comptime T: type) type { return struct {
pub usingnamespace IUnknown.MethodMixin(T);
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IInkD2DRenderer2_Draw(self: *const T, pD2D1DeviceContext: ?*IUnknown, pInkStrokeIterable: ?*IUnknown, highContrastAdjustment: INK_HIGH_CONTRAST_ADJUSTMENT) callconv(.Inline) HRESULT {
return @ptrCast(*const IInkD2DRenderer2.VTable, self.vtable).Draw(@ptrCast(*const IInkD2DRenderer2, self), pD2D1DeviceContext, pInkStrokeIterable, highContrastAdjustment);
}
};}
pub usingnamespace MethodMixin(@This());
};
//--------------------------------------------------------------------------------
// Section: Functions (0)
//--------------------------------------------------------------------------------
//--------------------------------------------------------------------------------
// Section: Unicode Aliases (0)
//--------------------------------------------------------------------------------
const thismodule = @This();
pub usingnamespace switch (@import("../../zig.zig").unicode_mode) {
.ansi => struct {
},
.wide => struct {
},
.unspecified => if (@import("builtin").is_test) struct {
} else struct {
},
};
//--------------------------------------------------------------------------------
// Section: Imports (4)
//--------------------------------------------------------------------------------
const Guid = @import("../../zig.zig").Guid;
const BOOL = @import("../../foundation.zig").BOOL;
const HRESULT = @import("../../foundation.zig").HRESULT;
const IUnknown = @import("../../system/com.zig").IUnknown;
test {
@setEvalBranchQuota(
@import("std").meta.declarations(@This()).len * 3
);
// reference all the pub declarations
if (!@import("builtin").is_test) return;
inline for (@import("std").meta.declarations(@This())) |decl| {
if (decl.is_pub) {
_ = decl;
}
}
} | win32/ui/input/ink.zig |
const std = @import("std");
const mem = std.mem;
const Allocator = mem.Allocator;
const Target = std.Target;
const Version = std.builtin.Version;
pub const macos = @import("darwin/macos.zig");
/// Check if SDK is installed on Darwin without triggering CLT installation popup window.
/// Note: simply invoking `xcrun` will inevitably trigger the CLT installation popup.
/// Therefore, we resort to the same tool used by Homebrew, namely, invoking `xcode-select --print-path`
/// and checking if the status is nonzero or the returned string in nonempty.
/// https://github.com/Homebrew/brew/blob/e119bdc571dcb000305411bc1e26678b132afb98/Library/Homebrew/brew.sh#L630
pub fn isDarwinSDKInstalled(allocator: Allocator) bool {
const argv = &[_][]const u8{ "/usr/bin/xcode-select", "--print-path" };
const result = std.ChildProcess.exec(.{ .allocator = allocator, .argv = argv }) catch return false;
defer {
allocator.free(result.stderr);
allocator.free(result.stdout);
}
if (result.stderr.len != 0 or result.term.Exited != 0) {
// We don't actually care if there were errors as this is best-effort check anyhow.
return false;
}
return result.stdout.len > 0;
}
/// Detect SDK on Darwin.
/// Calls `xcrun --sdk <target_sdk> --show-sdk-path` which fetches the path to the SDK sysroot (if any).
/// Subsequently calls `xcrun --sdk <target_sdk> --show-sdk-version` which fetches version of the SDK.
/// The caller needs to deinit the resulting struct.
pub fn getDarwinSDK(allocator: Allocator, target: Target) ?DarwinSDK {
const is_simulator_abi = target.abi == .simulator;
const sdk = switch (target.os.tag) {
.macos => "macosx",
.ios => if (is_simulator_abi) "iphonesimulator" else "iphoneos",
.watchos => if (is_simulator_abi) "watchsimulator" else "watchos",
.tvos => if (is_simulator_abi) "appletvsimulator" else "appletvos",
else => return null,
};
const path = path: {
const argv = &[_][]const u8{ "/usr/bin/xcrun", "--sdk", sdk, "--show-sdk-path" };
const result = std.ChildProcess.exec(.{ .allocator = allocator, .argv = argv }) catch return null;
defer {
allocator.free(result.stderr);
allocator.free(result.stdout);
}
if (result.stderr.len != 0 or result.term.Exited != 0) {
// We don't actually care if there were errors as this is best-effort check anyhow
// and in the worst case the user can specify the sysroot manually.
return null;
}
const path = allocator.dupe(u8, mem.trimRight(u8, result.stdout, "\r\n")) catch return null;
break :path path;
};
const version = version: {
const argv = &[_][]const u8{ "/usr/bin/xcrun", "--sdk", sdk, "--show-sdk-version" };
const result = std.ChildProcess.exec(.{ .allocator = allocator, .argv = argv }) catch return null;
defer {
allocator.free(result.stderr);
allocator.free(result.stdout);
}
if (result.stderr.len != 0 or result.term.Exited != 0) {
// We don't actually care if there were errors as this is best-effort check anyhow
// and in the worst case the user can specify the sysroot manually.
return null;
}
const raw_version = mem.trimRight(u8, result.stdout, "\r\n");
const version = Version.parse(raw_version) catch Version{
.major = 0,
.minor = 0,
};
break :version version;
};
return DarwinSDK{
.path = path,
.version = version,
};
}
pub const DarwinSDK = struct {
path: []const u8,
version: Version,
pub fn deinit(self: DarwinSDK, allocator: Allocator) void {
allocator.free(self.path);
}
};
test "" {
_ = macos;
} | lib/std/zig/system/darwin.zig |
const std = @import("std");
const pokemon = @import("index.zig");
const gba = @import("../gba.zig");
const bits = @import("../bits.zig");
const utils = @import("../utils/index.zig");
const common = @import("common.zig");
const fun = @import("../../lib/fun-with-zig/src/index.zig");
const mem = std.mem;
const debug = std.debug;
const io = std.io;
const os = std.os;
const math = std.math;
const assert = debug.assert;
const lu16 = fun.platform.lu16;
const lu32 = fun.platform.lu32;
const lu64 = fun.platform.lu64;
pub const constants = @import("gen3-constants.zig");
pub fn Ptr(comptime T: type) type {
return packed struct {
const Self = @This();
v: lu32,
pub fn initNull() Self {
return Self{ .v = lu32.init(0) };
}
pub fn init(i: u32) !Self {
const v = math.add(u32, i, 0x8000000) catch return error.InvalidPointer;
return Self{ .v = lu32.init(v) };
}
pub fn toMany(ptr: Self, data: []u8) ![*]T {
return (try ptr.toSlice(data, 0)).ptr;
}
pub fn toSlice(ptr: Self, data: []u8, len: u32) ![]T {
if (ptr.isNull()) {
if (len == 0)
return @bytesToSlice(T, data[0..0]);
return error.InvalidPointer;
}
const start = try ptr.toInt();
const end = start + len * @sizeOf(T);
if (data.len < start or data.len < end)
return error.InvalidPointer;
return @bytesToSlice(T, data[start..end]);
}
pub fn isNull(ptr: Self) bool {
return ptr.v.value() == 0;
}
pub fn toInt(ptr: Self) !u32 {
return math.sub(u32, ptr.v.value(), 0x8000000) catch return error.InvalidPointer;
}
};
}
pub fn Ref(comptime T: type) type {
return packed struct {
const Self = @This();
ptr: Ptr(T),
pub fn initNull() Self {
return Self{ .ptr = Ptr(T).initNull() };
}
pub fn init(i: u32) !Self {
return Self{ .ptr = try Ptr(T).init(i) };
}
pub fn toSingle(ref: Self, data: []u8) !*T {
return &(try ref.ptr.toSlice(data, 1))[0];
}
pub fn isNull(ref: Self) bool {
return ref.ptr.isNull();
}
pub fn toInt(ref: Self) !u32 {
return try ref.ptr.toInt();
}
};
}
pub fn Slice(comptime T: type) type {
return packed struct {
const Self = @This();
l: lu32,
ptr: Ptr(T),
pub fn initEmpty() !Self {
return Self{
.l = lu32.init(0),
.ptr = try Ptr(T).initNull(),
};
}
pub fn init(ptr: u32, l: u32) !Self {
return Self{
.l = lu32.init(l),
.ptr = try Ptr(T).init(ptr),
};
}
pub fn toSlice(slice: Self, data: []u8) ![]T {
return slice.ptr.toSlice(data, slice.len());
}
pub fn len(slice: Self) u32 {
return slice.l.value();
}
};
}
pub const BasePokemon = packed struct {
stats: common.Stats,
types: [2]Type,
catch_rate: u8,
base_exp_yield: u8,
ev_yield: common.EvYield,
items: [2]lu16,
gender_ratio: u8,
egg_cycles: u8,
base_friendship: u8,
growth_rate: common.GrowthRate,
egg_group1: common.EggGroup,
egg_group1_pad: u4,
egg_group2: common.EggGroup,
egg_group2_pad: u4,
abilities: [2]u8,
safari_zone_rate: u8,
color: common.Color,
flip: bool,
padding: [2]u8,
};
pub const Trainer = packed struct {
const has_item = 0b10;
const has_moves = 0b01;
party_type: u8,
class: u8,
encounter_music: u8,
trainer_picture: u8,
name: [12]u8,
items: [4]lu16,
is_double: lu32,
ai: lu32,
party: Slice(u8),
};
/// All party members have this as the base.
/// * If trainer.party_type & 0b10 then there is an additional u16 after the base, which is the held
/// item. If this is not true, the the party member is padded with u16
/// * If trainer.party_type & 0b01 then there is an additional 4 * u16 after the base, which are
/// the party members moveset.
pub const PartyMember = packed struct {
iv: lu16,
level: lu16,
species: lu16,
};
pub const Move = packed struct {
effect: u8,
power: u8,
@"type": Type,
accuracy: u8,
pp: u8,
side_effect_chance: u8,
target: u8,
priority: u8,
flags: lu32,
};
pub const Item = packed struct {
name: [14]u8,
id: lu16,
price: lu16,
hold_effect: u8,
hold_effect_param: u8,
description: Ptr(u8),
importance: u8,
unknown: u8,
pocked: u8,
@"type": u8,
field_use_func: Ref(u8),
battle_usage: lu32,
battle_use_func: Ref(u8),
secondary_id: lu32,
};
pub const Type = enum(u8) {
Normal = 0x00,
Fighting = 0x01,
Flying = 0x02,
Poison = 0x03,
Ground = 0x04,
Rock = 0x05,
Bug = 0x06,
Ghost = 0x07,
Steel = 0x08,
Fire = 0x0A,
Water = 0x0B,
Grass = 0x0C,
Electric = 0x0D,
Psychic = 0x0E,
Ice = 0x0F,
Dragon = 0x10,
Dark = 0x11,
};
pub const LevelUpMove = packed struct {
move_id: u9,
level: u7,
};
// TODO: Confirm layout
pub const WildPokemon = packed struct {
min_level: u8,
max_level: u8,
species: lu16,
};
// TODO: Confirm layout
pub fn WildPokemonInfo(comptime len: usize) type {
return packed struct {
encounter_rate: u8,
pad: [3]u8,
wild_pokemons: Ref([len]WildPokemon),
};
}
// TODO: Confirm layout
pub const WildPokemonHeader = packed struct {
map_group: u8,
map_num: u8,
pad: [2]u8,
land_pokemons: Ref(WildPokemonInfo(12)),
surf_pokemons: Ref(WildPokemonInfo(5)),
rock_smash_pokemons: Ref(WildPokemonInfo(5)),
fishing_pokemons: Ref(WildPokemonInfo(10)),
};
pub const Game = struct {
base: pokemon.BaseGame,
allocator: *mem.Allocator,
data: []u8,
// All these fields point into data
header: *gba.Header,
trainers: []Trainer,
moves: []Move,
machine_learnsets: []lu64,
base_stats: []BasePokemon,
evolutions: [][5]common.Evolution,
level_up_learnset_pointers: []Ref(LevelUpMove),
hms: []lu16,
tms: []lu16,
items: []Item,
wild_pokemon_headers: []WildPokemonHeader,
pub fn fromFile(file: os.File, allocator: *mem.Allocator) !Game {
var file_in_stream = file.inStream();
var in_stream = &file_in_stream.stream;
const header = try utils.stream.read(in_stream, gba.Header);
try header.validate();
try file.seekTo(0);
const info = try getInfo(header.game_title, header.gamecode);
const size = try file.getEndPos();
if (size % 0x1000000 != 0)
return error.InvalidRomSize;
const rom = try allocator.alloc(u8, size);
errdefer allocator.free(rom);
try in_stream.readNoEof(rom);
return Game{
.base = pokemon.BaseGame{ .version = info.version },
.allocator = allocator,
.data = rom,
.header = @ptrCast(*gba.Header, &rom[0]),
.trainers = info.trainers.slice(rom),
.moves = info.moves.slice(rom),
.machine_learnsets = info.machine_learnsets.slice(rom),
.base_stats = info.base_stats.slice(rom),
.evolutions = info.evolutions.slice(rom),
.level_up_learnset_pointers = info.level_up_learnset_pointers.slice(rom),
.hms = info.hms.slice(rom),
.tms = info.tms.slice(rom),
.items = info.items.slice(rom),
.wild_pokemon_headers = info.wild_pokemon_headers.slice(rom),
};
}
pub fn writeToStream(game: Game, in_stream: var) !void {
try game.header.validate();
try in_stream.write(game.data);
}
pub fn deinit(game: *Game) void {
game.allocator.free(game.data);
game.* = undefined;
}
fn getInfo(game_title: []const u8, gamecode: []const u8) !constants.Info {
for (constants.infos) |info| {
if (!mem.eql(u8, info.game_title, game_title))
continue;
if (!mem.eql(u8, info.gamecode, gamecode))
continue;
return info;
}
return error.NotGen3Game;
}
}; | src/pokemon/gen3.zig |
const builtin = @import("builtin");
const std = @import("std");
const assert = std.debug.assert;
const print = std.debug.print;
const arch = if (builtin.cpu.arch == .x86_64)
@import("x86_64.zig")
else
@compileError("Unimplemented for this architecture");
pub const VA_Errors = arch.VA_Errors;
pub const VAList = arch.VAList;
pub const callVarArgs = arch.callVarArgs;
pub const VAFunc = arch.VAFunc;
test "valist integers" {
const testfn = @ptrCast(VAFunc, &intTest);
var ret = callVarArgs(usize, testfn, .{
@as(u64, 7), // count
@as(u24, 2), // arg1
@as(u16, 2), // arg2
@as(u8, 2), // arg3
@as(u64, 2), // arg4
@as(u64, 2), // arg5
@as(u64, 2), // arg6 -- is on the stack
@as(u64, 2), // arg7 -- is on the stack
});
assert(ret == 14);
}
export fn intTest() callconv(.C) usize {
var valist = VAList.init();
const count = valist.next(u64) catch unreachable; // first arg is guaranteed
valist.count = count;
var ret: usize = 0;
while (valist.next(u64)) |num| {
ret += num;
} else |e| {
switch (e) {
error.NoMoreArgs => {},
error.CountUninitialized => unreachable,
}
}
return ret;
}
test "valist floats -- broken test" {
//const testfn = @ptrCast(VAFunc, &floatTest);
//const ret = callVarArgs(usize, testfn, .{
//@as(u64, 8), // count
//@as(f64, 2), // arg1 -- unseen
//@as(f64, 2), // arg2 -- unseen
//@as(f64, 2), // arg3
//@as(f64, 2), // arg4
//@as(f64, 2), // arg5
//@as(f64, 2), // arg6
//@as(f64, 2), // arg7
//@as(f64, 2), // arg8
//});
//std.debug.print("ret is: {}\n", .{ret});
//assert(ret == 16);
}
fn floatTest() callconv(.C) usize {
var valist = VAList.init();
const count = valist.next(u64) catch unreachable; // first arg is guaranteed
valist.count = count;
var ret: f64 = 0;
while (valist.next(f64)) |num| {
ret += num;
} else |e| {
switch (e) {
error.NoMoreArgs => {},
error.CountUninitialized => unreachable,
}
}
return @floatToInt(usize, ret);
}
test "valist pointers" {
if (true)
return;
const testfn = @ptrCast(VAFunc, &optionalPointerTest);
var val: u64 = 2;
var ret = callVarArgs(usize, testfn, .{
@as(u64, 2), // count
&val,
&val,
&val,
&val,
&val,
&val,
&val,
&val,
});
assert(ret == 16);
}
fn optionalPointerTest() callconv(.C) usize {
var valist = VAList.init();
const count = valist.next(u64) catch unreachable; // first arg is guaranteed
valist.count = count;
var ret: usize = 0;
while (valist.next(?*u64)) |num| {
ret += num.?.*;
} else |e| {
switch (e) {
error.NoMoreArgs => {},
error.CountUninitialized => unreachable,
}
}
return ret;
}
const libc = @cImport(@cInclude("stdio.h"));
test "call libc snprintf" {
if (!builtin.link_libc)
return;
const snprintf = @ptrCast(VAFunc, &libc.snprintf);
const in = "Test: %d";
var out = [_:0]u8{0} ** (in.len);
const ret = callVarArgs(c_int, snprintf, .{ &out, out.len + 1, in, 69 });
assert(ret == 8); // write 8 bytes
const expected = "Test: 69";
assert(std.mem.eql(u8, out[0..], expected));
print("out: {s} | len: {}\nexp: {s} | len: {}", .{ out, out.len, expected, expected.len });
} | src/varargs.zig |
const std = @import("std");
const eql = std.mem.eql;
const stdin = std.io.getStdIn().reader();
const stdout = std.io.getStdOut().writer();
const stderr = std.io.getStdErr().writer();
const print = @import("std").debug.print;
const page_allocator = std.heap.page_allocator;
const ArenaAllocator = std.heap.ArenaAllocator;
const ArrayList = std.ArrayList;
const Allocator = std.mem.Allocator;
const ChildProcess = std.ChildProcess;
fn shutdown() void {
print("🦀 Bye!\n", .{});
}
fn get_line(allocator: *Allocator) ![]u8 {
var buffer_size : u64 = 10;
var read_index : u64 = 0;
var buffer: []u8 = try allocator.alloc(u8, buffer_size);
while (true) {
const byte = try stdin.readByte();
if (byte) {
if (byte == '\n') {
break;
}
if(read_index == buffer_size - 1) {
buffer_size = buffer_size * 2;
buffer = try allocator.realloc(buffer, buffer_size);
}
buffer[read_index] = byte;
read_index = read_index + 1;
} else |err| {
if(err == error.EndOfStream) {
break;
} else {
return err;
}
}
}
return allocator.shrink(buffer, read_index + 1)[0..read_index];
}
pub fn main() !void {
while (true) {
// alloc Arena + dealloc each loop
var arena = ArenaAllocator.init(page_allocator);
defer arena.deinit();
const allocator = &arena.allocator;
var cwd : std.fs.Dir = std.fs.cwd();
const cwd_display : []u8 = try cwd.realpathAlloc(allocator, ".");
// prompt for line
try stdout.print("🐚{s}> ", .{cwd_display});
const line = get_line(allocator) catch "";
// split,collect argv into args = [][]
var args = ArrayList([]const u8).init(allocator);
var tokens = std.mem.tokenize(u8, line, " ");
while (tokens.next()) |token| {
try args.append(token);
}
const argv = args.items[0..];
if (argv.len < 1) {
continue;
}
const command = argv[0];
// Builtins!
if (eql(u8, command, "exit")) {
shutdown();
break;
}
if (eql(u8, command, "cd")) {
const new_dir = argv[1];
var nextdir = cwd.openDir(new_dir, .{});
if(nextdir) |cd_target| {
try cd_target.setAsCwd();
} else |err| {
if(err == error.FileNotFound) {
print("cd: no such directory: {s}\n", .{new_dir});
} else {
print("cd: {s}\n", .{err});
}
}
continue;
}
const child = ChildProcess.exec(.{
.allocator = allocator,
.argv = argv,
}) catch |err| switch (err) {
error.FileNotFound => {
print("{s}: command not found\n", .{args.items[0]});
continue;
},
else => |e| {
print("Fatal: {s}\n", .{e});
continue;
},
};
print("{s}", .{child.stdout[0..]});
}
} | src/main.zig |
const Self = @This();
const build_options = @import("build_options");
const std = @import("std");
const wlr = @import("wlroots");
const log = std.log.scoped(.input_config);
const c = @import("c.zig");
const server = &@import("main.zig").server;
const util = @import("util.zig");
const InputDevice = @import("InputManager.zig").InputDevice;
// TODO - keyboards
// - mapping to output / region
// - calibration matrices
// - scroll factor
pub const EventState = enum {
enabled,
disabled,
@"disabled-on-external-mouse",
pub fn apply(event_state: EventState, device: *c.libinput_device) void {
const want = switch (event_state) {
.enabled => c.LIBINPUT_CONFIG_SEND_EVENTS_ENABLED,
.disabled => c.LIBINPUT_CONFIG_SEND_EVENTS_DISABLED,
.@"disabled-on-external-mouse" => c.LIBINPUT_CONFIG_SEND_EVENTS_DISABLED_ON_EXTERNAL_MOUSE,
};
const current = c.libinput_device_config_send_events_get_mode(device);
if (want != current) {
_ = c.libinput_device_config_send_events_set_mode(device, @intCast(u32, want));
}
}
};
pub const AccelProfile = enum {
none,
flat,
adaptive,
pub fn apply(accel_profile: AccelProfile, device: *c.libinput_device) void {
const want = @intToEnum(c.libinput_config_accel_profile, switch (accel_profile) {
.none => c.LIBINPUT_CONFIG_ACCEL_PROFILE_NONE,
.flat => c.LIBINPUT_CONFIG_ACCEL_PROFILE_FLAT,
.adaptive => c.LIBINPUT_CONFIG_ACCEL_PROFILE_ADAPTIVE,
});
if (c.libinput_device_config_accel_is_available(device) == 0) return;
const current = c.libinput_device_config_accel_get_profile(device);
if (want != current) {
_ = c.libinput_device_config_accel_set_profile(device, want);
}
}
};
pub const ClickMethod = enum {
none,
@"button-areas",
clickfinger,
pub fn apply(click_method: ClickMethod, device: *c.libinput_device) void {
const want = @intToEnum(c.libinput_config_click_method, switch (click_method) {
.none => c.LIBINPUT_CONFIG_CLICK_METHOD_NONE,
.@"button-areas" => c.LIBINPUT_CONFIG_CLICK_METHOD_BUTTON_AREAS,
.clickfinger => c.LIBINPUT_CONFIG_CLICK_METHOD_CLICKFINGER,
});
const supports = c.libinput_device_config_click_get_methods(device);
if (supports & @intCast(u32, @enumToInt(want)) == 0) return;
_ = c.libinput_device_config_click_set_method(device, want);
}
};
pub const DragState = enum {
disabled,
enabled,
pub fn apply(drag_state: DragState, device: *c.libinput_device) void {
const want = @intToEnum(c.libinput_config_drag_state, switch (drag_state) {
.disabled => c.LIBINPUT_CONFIG_DRAG_DISABLED,
.enabled => c.LIBINPUT_CONFIG_DRAG_ENABLED,
});
if (c.libinput_device_config_tap_get_finger_count(device) <= 0) return;
const current = c.libinput_device_config_tap_get_drag_enabled(device);
if (want != current) {
_ = c.libinput_device_config_tap_set_drag_enabled(device, want);
}
}
};
pub const DragLock = enum {
disabled,
enabled,
pub fn apply(drag_lock: DragLock, device: *c.libinput_device) void {
const want = @intToEnum(c.libinput_config_drag_lock_state, switch (drag_lock) {
.disabled => c.LIBINPUT_CONFIG_DRAG_LOCK_DISABLED,
.enabled => c.LIBINPUT_CONFIG_DRAG_LOCK_ENABLED,
});
if (c.libinput_device_config_tap_get_finger_count(device) <= 0) return;
const current = c.libinput_device_config_tap_get_drag_lock_enabled(device);
if (want != current) {
_ = c.libinput_device_config_tap_set_drag_lock_enabled(device, want);
}
}
};
pub const DwtState = enum {
disabled,
enabled,
pub fn apply(dwt_state: DwtState, device: *c.libinput_device) void {
const want = @intToEnum(c.libinput_config_dwt_state, switch (dwt_state) {
.disabled => c.LIBINPUT_CONFIG_DWT_DISABLED,
.enabled => c.LIBINPUT_CONFIG_DWT_ENABLED,
});
if (c.libinput_device_config_dwt_is_available(device) == 0) return;
const current = c.libinput_device_config_dwt_get_enabled(device);
if (want != current) {
_ = c.libinput_device_config_dwt_set_enabled(device, want);
}
}
};
pub const MiddleEmulation = enum {
disabled,
enabled,
pub fn apply(middle_emulation: MiddleEmulation, device: *c.libinput_device) void {
const want = @intToEnum(c.libinput_config_middle_emulation_state, switch (middle_emulation) {
.disabled => c.LIBINPUT_CONFIG_MIDDLE_EMULATION_DISABLED,
.enabled => c.LIBINPUT_CONFIG_MIDDLE_EMULATION_ENABLED,
});
if (c.libinput_device_config_middle_emulation_is_available(device) == 0) return;
const current = c.libinput_device_config_middle_emulation_get_enabled(device);
if (want != current) {
_ = c.libinput_device_config_middle_emulation_set_enabled(device, want);
}
}
};
pub const NaturalScroll = enum {
disabled,
enabled,
pub fn apply(natural_scroll: NaturalScroll, device: *c.libinput_device) void {
const want: c_int = switch (natural_scroll) {
.disabled => 0,
.enabled => 1,
};
if (c.libinput_device_config_scroll_has_natural_scroll(device) == 0) return;
const current = c.libinput_device_config_scroll_get_natural_scroll_enabled(device);
if (want != current) {
_ = c.libinput_device_config_scroll_set_natural_scroll_enabled(device, want);
}
}
};
pub const LeftHanded = enum {
disabled,
enabled,
pub fn apply(left_handed: LeftHanded, device: *c.libinput_device) void {
const want: c_int = switch (left_handed) {
.disabled => 0,
.enabled => 1,
};
if (c.libinput_device_config_left_handed_is_available(device) == 0) return;
const current = c.libinput_device_config_left_handed_get(device);
if (want != current) {
_ = c.libinput_device_config_left_handed_set(device, want);
}
}
};
pub const TapState = enum {
disabled,
enabled,
pub fn apply(tap_state: TapState, device: *c.libinput_device) void {
const want = @intToEnum(c.libinput_config_tap_state, switch (tap_state) {
.disabled => c.LIBINPUT_CONFIG_TAP_DISABLED,
.enabled => c.LIBINPUT_CONFIG_TAP_ENABLED,
});
if (c.libinput_device_config_tap_get_finger_count(device) <= 0) return;
const current = c.libinput_device_config_tap_get_enabled(device);
if (want != current) {
_ = c.libinput_device_config_tap_set_enabled(device, want);
}
}
};
pub const TapButtonMap = enum {
@"left-middle-right",
@"left-right-middle",
pub fn apply(tap_button_map: TapButtonMap, device: *c.libinput_device) void {
const want = @intToEnum(c.libinput_config_tap_button_map, switch (tap_button_map) {
.@"left-right-middle" => c.LIBINPUT_CONFIG_TAP_MAP_LRM,
.@"left-middle-right" => c.LIBINPUT_CONFIG_TAP_MAP_LMR,
});
if (c.libinput_device_config_tap_get_finger_count(device) <= 0) return;
const current = c.libinput_device_config_tap_get_button_map(device);
if (want != current) {
_ = c.libinput_device_config_tap_set_button_map(device, want);
}
}
};
pub const PointerAccel = struct {
value: f32,
pub fn apply(pointer_accel: PointerAccel, device: *c.libinput_device) void {
if (c.libinput_device_config_accel_is_available(device) == 0) return;
if (c.libinput_device_config_accel_get_speed(device) != pointer_accel.value) {
_ = c.libinput_device_config_accel_set_speed(device, pointer_accel.value);
}
}
};
pub const ScrollMethod = enum {
none,
@"two-finger",
edge,
button,
pub fn apply(scroll_method: ScrollMethod, device: *c.libinput_device) void {
const want = @intToEnum(c.libinput_config_scroll_method, switch (scroll_method) {
.none => c.LIBINPUT_CONFIG_SCROLL_NO_SCROLL,
.@"two-finger" => c.LIBINPUT_CONFIG_SCROLL_2FG,
.edge => c.LIBINPUT_CONFIG_SCROLL_EDGE,
.button => c.LIBINPUT_CONFIG_SCROLL_ON_BUTTON_DOWN,
});
const supports = c.libinput_device_config_scroll_get_methods(device);
if (supports & @intCast(u32, @enumToInt(want)) == 0) return;
_ = c.libinput_device_config_scroll_set_method(device, want);
}
};
pub const ScrollButton = struct {
button: u32,
pub fn apply(scroll_button: ScrollButton, device: *c.libinput_device) void {
const supports = c.libinput_device_config_scroll_get_methods(device);
if (supports & ~@intCast(u32, c.LIBINPUT_CONFIG_SCROLL_NO_SCROLL) == 0) return;
_ = c.libinput_device_config_scroll_set_button(device, scroll_button.button);
}
};
identifier: []const u8,
event_state: ?EventState = null,
accel_profile: ?AccelProfile = null,
click_method: ?ClickMethod = null,
drag_state: ?DragState = null,
drag_lock: ?DragLock = null,
dwt_state: ?DwtState = null,
middle_emulation: ?MiddleEmulation = null,
natural_scroll: ?NaturalScroll = null,
left_handed: ?LeftHanded = null,
tap_state: ?TapState = null,
tap_button_map: ?TapButtonMap = null,
pointer_accel: ?PointerAccel = null,
scroll_method: ?ScrollMethod = null,
scroll_button: ?ScrollButton = null,
pub fn deinit(self: *Self) void {
util.gpa.free(self.identifier);
}
pub fn apply(self: *Self, device: *InputDevice) void {
const libinput_device = @ptrCast(
*c.libinput_device,
device.device.getLibinputDevice() orelse return,
);
log.debug("applying input configuration to device: {s}", .{device.identifier});
if (self.event_state) |setting| setting.apply(libinput_device);
if (self.accel_profile) |setting| setting.apply(libinput_device);
if (self.click_method) |setting| setting.apply(libinput_device);
if (self.drag_state) |setting| setting.apply(libinput_device);
if (self.drag_lock) |setting| setting.apply(libinput_device);
if (self.dwt_state) |setting| setting.apply(libinput_device);
if (self.middle_emulation) |setting| setting.apply(libinput_device);
if (self.natural_scroll) |setting| setting.apply(libinput_device);
if (self.left_handed) |setting| setting.apply(libinput_device);
if (self.pointer_accel) |setting| setting.apply(libinput_device);
if (self.scroll_button) |setting| setting.apply(libinput_device);
if (self.scroll_method) |setting| setting.apply(libinput_device);
if (self.tap_state) |setting| setting.apply(libinput_device);
if (self.tap_button_map) |setting| setting.apply(libinput_device);
} | source/river-0.1.0/river/InputConfig.zig |
const std = @import("std");
const builtin = @import("builtin");
const log = std.log.scoped(.@"brucelib.graphics.d3d11");
const common = @import("common.zig");
const VertexBufferHandle = common.VertexBufferHandle;
const VertexLayoutDesc = common.VertexLayoutDesc;
const VertexLayoutHandle = common.VertexLayoutHandle;
const TextureFormat = common.TextureFormat;
const TextureHandle = common.TextureHandle;
const ConstantBufferHandle = common.ConstantBufferHandle;
const RasteriserStateHandle = common.RasteriserStateHandle;
const BlendStateHandle = common.BlendStateHandle;
const ShaderProgramHandle = common.ShaderProgramHandle;
const win32 = @import("zwin32");
const SIZE_T = win32.base.SIZE_T;
const UINT64 = win32.base.UINT64;
const BOOL = win32.base.BOOL;
const TRUE = win32.base.TRUE;
const FALSE = win32.base.FALSE;
const UINT = win32.base.UINT;
const FLOAT = win32.base.FLOAT;
const S_OK = win32.base.S_OK;
const dxgi = win32.dxgi;
const d3d = win32.d3d;
const d3d11 = win32.d3d11;
const d3d11d = win32.d3d11d;
const d3dcompiler = win32.d3dcompiler;
var device: *d3d11.IDevice = undefined;
var device_context: *d3d11.IDeviceContext = undefined;
var render_target_view: *d3d11.IRenderTargetView = undefined;
var allocator: std.mem.Allocator = undefined;
const ShaderProgramList = std.ArrayList(struct {
vs: *d3d11.IVertexShader,
ps: *d3d11.IPixelShader,
input_layout: *d3d11.IInputLayout,
});
var shader_programs: ShaderProgramList = undefined;
const VertexLayoutList = std.ArrayList(struct {
buffers: []*d3d11.IBuffer,
strides: []UINT,
offsets: []UINT,
});
var vertex_layouts: VertexLayoutList = undefined;
const ConstantBufferList = std.ArrayList(struct {
slot: UINT,
buffer: *d3d11.IBuffer,
});
var constant_buffers: ConstantBufferList = undefined;
const TextureResourcesList = std.ArrayList(struct {
texture2d: *d3d11.ITexture2D,
shader_res_view: *d3d11.IShaderResourceView,
sampler_state: *d3d11.ISamplerState,
});
var textures: TextureResourcesList = undefined;
var debug_info_queue: *d3d11d.IInfoQueue = undefined;
pub fn init(platform: anytype, _allocator: std.mem.Allocator) !void {
device = @ptrCast(*d3d11.IDevice, platform.getD3D11Device());
device_context = @ptrCast(*d3d11.IDeviceContext, platform.getD3D11DeviceContext());
render_target_view = @ptrCast(*d3d11.IRenderTargetView, platform.getD3D11RenderTargetView());
allocator = _allocator;
shader_programs = ShaderProgramList.init(allocator);
vertex_layouts = VertexLayoutList.init(allocator);
constant_buffers = ConstantBufferList.init(allocator);
textures = TextureResourcesList.init(allocator);
if (builtin.mode == .Debug) {
try win32.hrErrorOnFail(device.QueryInterface(
&d3d11d.IID_IInfoQueue,
@ptrCast(*?*anyopaque, &debug_info_queue),
));
{ // set message filter
const deny_severities = [_]d3d11d.MESSAGE_SEVERITY{
.INFO,
.MESSAGE,
};
var filter: d3d11d.INFO_QUEUE_FILTER = std.mem.zeroes(d3d11d.INFO_QUEUE_FILTER);
filter.DenyList.NumSeverities = deny_severities.len;
filter.DenyList.pSeverityList = &deny_severities;
try win32.hrErrorOnFail(debug_info_queue.PushStorageFilter(&filter));
}
}
}
pub fn deinit() void {
for (textures.items) |texture| {
_ = texture.texture2d.Release();
_ = texture.shader_res_view.Release();
}
textures.deinit();
for (constant_buffers.items) |constant_buffer| {
_ = constant_buffer.buffer.Release();
}
constant_buffers.deinit();
for (vertex_layouts.items) |layout| {
allocator.free(layout.buffers);
allocator.free(layout.strides);
allocator.free(layout.offsets);
}
vertex_layouts.deinit();
for (shader_programs.items) |program| {
_ = program.vs.Release();
_ = program.ps.Release();
_ = program.input_layout.Release();
}
shader_programs.deinit();
}
pub fn logDebugMessages() !void {
if (builtin.mode == .Debug) {
var temp_arena = std.heap.ArenaAllocator.init(allocator);
defer temp_arena.deinit();
const temp_allocator = temp_arena.allocator();
const num_messages = debug_info_queue.GetNumStoredMessages();
var i: UINT64 = 0;
while (i < num_messages) : (i += 1) {
var msg_size: SIZE_T = 0;
// NOTE(hazeycode): calling GetMessage the first time, with null, to get the
// message size apparently returns S_FALSE, which we consider an error code,
// so we are just ignore the HRESULT here
_ = debug_info_queue.GetMessage(
i,
null,
&msg_size,
);
const buf_len = 0x1000;
std.debug.assert(buf_len >= msg_size);
var message_buf = @alignCast(
@alignOf(d3d11d.MESSAGE),
try temp_allocator.alloc(u8, buf_len),
);
var message = @ptrCast(*d3d11d.MESSAGE, message_buf);
try win32.hrErrorOnFail(debug_info_queue.GetMessage(
i,
message,
&msg_size,
));
log.debug("d3d11: {s}", .{message.pDescription[0..message.DescriptionByteLength]});
}
}
}
pub fn setViewport(x: u16, y: u16, width: u16, height: u16) void {
const viewports = [_]d3d11.VIEWPORT{
.{
.TopLeftX = @intToFloat(FLOAT, x),
.TopLeftY = @intToFloat(FLOAT, y),
.Width = @intToFloat(FLOAT, width),
.Height = @intToFloat(FLOAT, height),
.MinDepth = 0.0,
.MaxDepth = 1.0,
},
};
device_context.RSSetViewports(1, &viewports);
// TODO(hazeycode): delete in favour of setRenderTarget fn?
const render_target_views = [_]*d3d11.IRenderTargetView{
render_target_view,
};
device_context.OMSetRenderTargets(
1,
@ptrCast([*]const d3d11.IRenderTargetView, &render_target_views),
null,
);
}
pub fn clearWithColour(r: f32, g: f32, b: f32, a: f32) void {
const colour = [4]FLOAT{ r, g, b, a };
device_context.ClearRenderTargetView(render_target_view, &colour);
}
pub fn draw(offset: u32, count: u32) void {
const device_ctx = device_context;
device_ctx.IASetPrimitiveTopology(d3d11.PRIMITIVE_TOPOLOGY.TRIANGLELIST);
device_ctx.Draw(count, offset);
}
pub fn createVertexBuffer(size: u32) !VertexBufferHandle {
var buffer: ?*d3d11.IBuffer = null;
const desc = d3d11.BUFFER_DESC{
.ByteWidth = @intCast(UINT, size),
.Usage = d3d11.USAGE_DYNAMIC,
.BindFlags = d3d11.BIND_VERTEX_BUFFER,
.CPUAccessFlags = d3d11.CPU_ACCESS_WRITE,
};
try win32.hrErrorOnFail(device.CreateBuffer(
&desc,
null,
&buffer,
));
return @ptrToInt(buffer.?);
}
pub fn destroyVertexBuffer(buffer_handle: VertexBufferHandle) !void {
_ = buffer_handle;
// TODO(hazeycode): impl this!
}
pub fn mapBuffer(
buffer_handle: VertexBufferHandle,
offset: usize,
size: usize,
comptime alignment: u7,
) ![]align(alignment) u8 {
const vertex_buffer = @intToPtr(*d3d11.IResource, buffer_handle);
var subresource = std.mem.zeroes(d3d11.MAPPED_SUBRESOURCE);
try win32.hrErrorOnFail(device_context.Map(
vertex_buffer,
0,
d3d11.MAP.WRITE_DISCARD,
0,
&subresource,
));
const ptr = @ptrCast([*]u8, subresource.pData);
return @alignCast(alignment, ptr[offset..(offset + size)]);
}
pub fn unmapBuffer(buffer_handle: VertexBufferHandle) void {
const vertex_buffer = @intToPtr(*d3d11.IResource, buffer_handle);
device_context.Unmap(vertex_buffer, 0);
}
pub fn createVertexLayout(vertex_layout_desc: VertexLayoutDesc) !VertexLayoutHandle {
const num_entries = vertex_layout_desc.entries.len;
var buffers = try allocator.alloc(*d3d11.IBuffer, num_entries);
errdefer allocator.free(buffers);
var strides = try allocator.alloc(UINT, num_entries);
errdefer allocator.free(strides);
var offsets = try allocator.alloc(UINT, num_entries);
errdefer allocator.free(offsets);
for (vertex_layout_desc.entries) |entry, i| {
buffers[i] = @intToPtr(*d3d11.IBuffer, entry.buffer_handle);
strides[i] = entry.getStride();
offsets[i] = entry.offset;
}
try vertex_layouts.append(.{
.buffers = buffers,
.strides = strides,
.offsets = offsets,
});
return (vertex_layouts.items.len - 1);
}
pub fn bindVertexLayout(vertex_layout_handle: VertexLayoutHandle) void {
const vertex_layout = vertex_layouts.items[vertex_layout_handle];
device_context.IASetVertexBuffers(
0,
1,
vertex_layout.buffers.ptr,
vertex_layout.strides.ptr,
vertex_layout.offsets.ptr,
);
}
pub fn createTexture2dWithBytes(bytes: []const u8, width: u32, height: u32, format: TextureFormat) !TextureHandle {
var texture: ?*d3d11.ITexture2D = null;
{
const desc = d3d11.TEXTURE2D_DESC{
.Width = width,
.Height = height,
.MipLevels = 1,
.ArraySize = 1,
.Format = formatToDxgiFormat(format),
.SampleDesc = .{
.Count = 1,
.Quality = 0,
},
.Usage = d3d11.USAGE_DEFAULT,
.BindFlags = d3d11.BIND_SHADER_RESOURCE,
.CPUAccessFlags = 0,
.MiscFlags = 0,
};
const subresouce_data = d3d11.SUBRESOURCE_DATA{
.pSysMem = bytes.ptr,
.SysMemPitch = switch (format) {
.uint8 => width,
.rgba_u8 => width * 4,
},
};
try win32.hrErrorOnFail(device.CreateTexture2D(
&desc,
&subresouce_data,
&texture,
));
}
var shader_res_view: ?*d3d11.IShaderResourceView = null;
{
try win32.hrErrorOnFail(device.CreateShaderResourceView(
@ptrCast(*d3d11.IResource, texture.?),
null,
&shader_res_view,
));
}
var sampler_state: ?*d3d11.ISamplerState = null;
{
const desc = d3d11.SAMPLER_DESC{
.Filter = .MIN_MAG_MIP_POINT,
.AddressU = .WRAP,
.AddressV = .WRAP,
.AddressW = .WRAP,
.MipLODBias = 0,
.MaxAnisotropy = 1,
.ComparisonFunc = .NEVER,
.BorderColor = .{ 0, 0, 0, 0 },
.MinLOD = 0,
.MaxLOD = 0,
};
try win32.hrErrorOnFail(device.CreateSamplerState(
&desc,
&sampler_state,
));
}
try textures.append(.{
.texture2d = texture.?,
.shader_res_view = shader_res_view.?,
.sampler_state = sampler_state.?,
});
return (textures.items.len - 1);
}
pub fn bindTexture(slot: u32, texture_handle: TextureHandle) void {
const samplers = [_]*d3d11.ISamplerState{
textures.items[texture_handle].sampler_state,
};
device_context.PSSetSamplers(0, 1, &samplers);
const shader_res_views = [_]*d3d11.IShaderResourceView{
textures.items[texture_handle].shader_res_view,
};
device_context.PSSetShaderResources(slot, 1, &shader_res_views);
}
pub fn createConstantBuffer(size: usize) !ConstantBufferHandle {
var buffer: ?*d3d11.IBuffer = null;
const desc = d3d11.BUFFER_DESC{
.ByteWidth = @intCast(UINT, size),
.Usage = d3d11.USAGE_DYNAMIC,
.BindFlags = d3d11.BIND_CONSTANT_BUFFER,
.CPUAccessFlags = d3d11.CPU_ACCESS_WRITE,
};
try win32.hrErrorOnFail(device.CreateBuffer(
&desc,
null,
&buffer,
));
errdefer _ = buffer.?.Release();
try constant_buffers.append(.{
.slot = 0, // TODO(chris): set undefined here and provide a way to utilise more binding slots
.buffer = buffer.?,
});
return (constant_buffers.items.len - 1);
}
pub fn updateShaderConstantBuffer(
buffer_handle: ConstantBufferHandle,
bytes: []const u8,
) !void {
const constant_buffer = @ptrCast(
*d3d11.IResource,
constant_buffers.items[buffer_handle].buffer,
);
const device_ctx = device_context;
var subresource = std.mem.zeroes(d3d11.MAPPED_SUBRESOURCE);
try win32.hrErrorOnFail(device_ctx.Map(
constant_buffer,
0,
d3d11.MAP.WRITE_DISCARD,
0,
&subresource,
));
std.mem.copy(
u8,
@ptrCast([*]u8, subresource.pData)[0..bytes.len],
bytes,
);
device_ctx.Unmap(constant_buffer, 0);
}
pub fn setConstantBuffer(buffer_handle: ConstantBufferHandle) void {
const buffer = constant_buffers.items[buffer_handle];
const buffers = [_]*d3d11.IBuffer{buffer.buffer};
device_context.VSSetConstantBuffers(
buffer.slot,
1,
@ptrCast([*]const *d3d11.IBuffer, &buffers),
);
device_context.PSSetConstantBuffers(
buffer.slot,
1,
@ptrCast([*]const *d3d11.IBuffer, &buffers),
);
}
pub fn createRasteriserState() !RasteriserStateHandle {
var res: ?*d3d11.IRasterizerState = null;
const desc = d3d11.RASTERIZER_DESC{
.FrontCounterClockwise = TRUE,
};
try win32.hrErrorOnFail(device.CreateRasterizerState(&desc, &res));
return @ptrToInt(res);
}
pub fn setRasteriserState(state_handle: RasteriserStateHandle) void {
const state = @intToPtr(*d3d11.IRasterizerState, state_handle);
device_context.RSSetState(state);
}
pub fn createBlendState() !BlendStateHandle {
var blend_state: ?*d3d11.IBlendState = null;
var rt_blend_descs: [8]d3d11.RENDER_TARGET_BLEND_DESC = undefined;
rt_blend_descs[0] = .{
.BlendEnable = TRUE,
.SrcBlend = .SRC_ALPHA,
.DestBlend = .INV_SRC_ALPHA,
.BlendOp = .ADD,
.SrcBlendAlpha = .ONE,
.DestBlendAlpha = .ZERO,
.BlendOpAlpha = .ADD,
.RenderTargetWriteMask = d3d11.COLOR_WRITE_ENABLE_ALL,
};
const desc = d3d11.BLEND_DESC{
.AlphaToCoverageEnable = FALSE,
.IndependentBlendEnable = FALSE,
.RenderTarget = rt_blend_descs,
};
try win32.hrErrorOnFail(device.CreateBlendState(
&desc,
&blend_state,
));
return @ptrToInt(blend_state.?);
}
pub fn setBlendState(blend_state_handle: BlendStateHandle) void {
const blend_state = @intToPtr(*d3d11.IBlendState, blend_state_handle);
device_context.OMSetBlendState(
blend_state,
null,
0xffffffff,
);
}
pub fn setShaderProgram(program_handle: ShaderProgramHandle) void {
const shader_program = shader_programs.items[program_handle];
device_context.IASetInputLayout(shader_program.input_layout);
device_context.VSSetShader(shader_program.vs, null, 0);
device_context.PSSetShader(shader_program.ps, null, 0);
}
pub fn createUniformColourShader() !ShaderProgramHandle {
const shader_src = @embedFile("../data/uniform_colour.hlsl");
const vs_bytecode = try compileHLSL(shader_src, "vs_main", "vs_5_0");
defer _ = vs_bytecode.Release();
const ps_bytecode = try compileHLSL(shader_src, "ps_main", "ps_5_0");
defer _ = ps_bytecode.Release();
const vs = try createVertexShader(vs_bytecode);
errdefer _ = vs.Release();
const ps = try createPixelShader(ps_bytecode);
errdefer _ = ps.Release();
const input_element_desc = [_]d3d11.INPUT_ELEMENT_DESC{
.{
.SemanticName = "POSITION",
.SemanticIndex = 0,
.Format = dxgi.FORMAT.R32G32B32_FLOAT,
.InputSlot = 0,
.AlignedByteOffset = 0,
.InputSlotClass = d3d11.INPUT_CLASSIFICATION.INPUT_PER_VERTEX_DATA,
.InstanceDataStepRate = 0,
},
};
const input_layout = try createInputLayout(&input_element_desc, vs_bytecode);
try shader_programs.append(.{
.vs = vs,
.ps = ps,
.input_layout = input_layout,
});
return (shader_programs.items.len - 1);
}
pub fn createTexturedVertsMonoShader() !ShaderProgramHandle {
const shader_src = @embedFile("../data/textured_verts.hlsl");
const vs_bytecode = try compileHLSL(shader_src, "vs_main", "vs_5_0");
defer _ = vs_bytecode.Release();
const ps_bytecode = try compileHLSL(shader_src, "ps_mono_main", "ps_5_0");
defer _ = ps_bytecode.Release();
const vs = try createVertexShader(vs_bytecode);
errdefer _ = vs.Release();
const ps = try createPixelShader(ps_bytecode);
errdefer _ = ps.Release();
const input_element_desc = [_]d3d11.INPUT_ELEMENT_DESC{
.{
.SemanticName = "POSITION",
.SemanticIndex = 0,
.Format = dxgi.FORMAT.R32G32B32_FLOAT,
.InputSlot = 0,
.AlignedByteOffset = 0,
.InputSlotClass = d3d11.INPUT_CLASSIFICATION.INPUT_PER_VERTEX_DATA,
.InstanceDataStepRate = 0,
},
.{
.SemanticName = "TEXCOORD",
.SemanticIndex = 0,
.Format = dxgi.FORMAT.R32G32_FLOAT,
.InputSlot = 0,
.AlignedByteOffset = 12,
.InputSlotClass = d3d11.INPUT_CLASSIFICATION.INPUT_PER_VERTEX_DATA,
.InstanceDataStepRate = 0,
},
};
const input_layout = try createInputLayout(&input_element_desc, vs_bytecode);
try shader_programs.append(.{
.vs = vs,
.ps = ps,
.input_layout = input_layout,
});
return (shader_programs.items.len - 1);
}
pub fn createTexturedVertsShader() !ShaderProgramHandle {
const shader_src = @embedFile("../data/textured_verts.hlsl");
const vs_bytecode = try compileHLSL(shader_src, "vs_main", "vs_5_0");
defer _ = vs_bytecode.Release();
const ps_bytecode = try compileHLSL(shader_src, "ps_main", "ps_5_0");
defer _ = ps_bytecode.Release();
const vs = try createVertexShader(vs_bytecode);
errdefer _ = vs.Release();
const ps = try createPixelShader(ps_bytecode);
errdefer _ = ps.Release();
const input_element_desc = [_]d3d11.INPUT_ELEMENT_DESC{
.{
.SemanticName = "POSITION",
.SemanticIndex = 0,
.Format = dxgi.FORMAT.R32G32B32_FLOAT,
.InputSlot = 0,
.AlignedByteOffset = 0,
.InputSlotClass = d3d11.INPUT_CLASSIFICATION.INPUT_PER_VERTEX_DATA,
.InstanceDataStepRate = 0,
},
.{
.SemanticName = "TEXCOORD",
.SemanticIndex = 0,
.Format = dxgi.FORMAT.R32G32_FLOAT,
.InputSlot = 0,
.AlignedByteOffset = 12,
.InputSlotClass = d3d11.INPUT_CLASSIFICATION.INPUT_PER_VERTEX_DATA,
.InstanceDataStepRate = 0,
},
};
const input_layout = try createInputLayout(&input_element_desc, vs_bytecode);
try shader_programs.append(.{
.vs = vs,
.ps = ps,
.input_layout = input_layout,
});
return (shader_programs.items.len - 1);
}
fn createInputLayout(desc: []const d3d11.INPUT_ELEMENT_DESC, vs_bytecode: *d3d.IBlob) !*d3d11.IInputLayout {
var res: ?*d3d11.IInputLayout = null;
try win32.hrErrorOnFail(device.CreateInputLayout(
@ptrCast(*const d3d11.INPUT_ELEMENT_DESC, desc.ptr),
@intCast(UINT, desc.len),
vs_bytecode.GetBufferPointer(),
vs_bytecode.GetBufferSize(),
&res,
));
return res.?;
}
fn createVertexShader(bytecode: *d3d.IBlob) !*d3d11.IVertexShader {
var res: ?*d3d11.IVertexShader = null;
try win32.hrErrorOnFail(device.CreateVertexShader(
bytecode.GetBufferPointer(),
bytecode.GetBufferSize(),
null,
&res,
));
return res.?;
}
fn createPixelShader(bytecode: *d3d.IBlob) !*d3d11.IPixelShader {
var res: ?*d3d11.IPixelShader = null;
try win32.hrErrorOnFail(device.CreatePixelShader(
bytecode.GetBufferPointer(),
bytecode.GetBufferSize(),
null,
&res,
));
return res.?;
}
fn compileHLSL(source: [:0]const u8, entrypoint: [:0]const u8, target: [:0]const u8) !*d3d.IBlob {
var compile_flags = d3dcompiler.COMPILE_ENABLE_STRICTNESS;
if (builtin.mode == .Debug) {
compile_flags |= d3dcompiler.COMPILE_DEBUG;
}
var blob: *d3d.IBlob = undefined;
var err_blob: *d3d.IBlob = undefined;
const compile_result = d3dcompiler.D3DCompile(
source.ptr,
source.len,
null,
null,
null,
entrypoint,
target,
compile_flags,
0,
&blob,
&err_blob,
);
if (compile_result != S_OK) {
const err_msg = @ptrCast([*c]const u8, err_blob.GetBufferPointer());
log.err("Failed to compile shader:\n{s}", .{err_msg});
_ = err_blob.Release();
return win32.hrToError(compile_result);
}
return blob;
}
fn formatToDxgiFormat(format: TextureFormat) dxgi.FORMAT {
return switch (format) {
.uint8 => dxgi.FORMAT.R8_UNORM,
.rgba_u8 => dxgi.FORMAT.R8G8B8A8_UNORM,
};
} | modules/graphics/src/d3d11.zig |
const u = @import("../util.zig");
const std = @import("std");
const Expr = @import("../Expr.zig");
const IR = @import("../IR.zig");
const p = @import("parse.zig");
const Ctx = @import("../Wat.zig");
ctx: *Ctx,
bytes: std.ArrayListUnmanaged(u8) = .{},
relocs: std.ArrayListUnmanaged(IR.Linking.Reloc.Entry) = .{},
types: std.ArrayListUnmanaged(IR.Func.Sig) = .{},
locals: Locals,
blocks: std.ArrayListUnmanaged(Block) = .{},
stack: std.ArrayListUnmanaged(Stack) = .{},
consts: std.StringHashMapUnmanaged([]const Expr) = .{},
const Codegen = @This();
const Hardtype = IR.Sigtype;
pub fn load(ctx: *Ctx, insts: []const Expr, typ: IR.Func.Sig, localTyps: ?[]const Hardtype, ids: ?[]const ?u.Txt) !IR.Code {
var self = Codegen{
.ctx = ctx,
.locals = .{ .first = typ.params, .second = localTyps orelse &[_]Hardtype{}, .ids = ids orelse &[_]?u.Txt{} },
};
defer {
self.bytes.deinit(self.gpa());
self.relocs.deinit(self.gpa());
self.types.deinit(self.gpa());
self.blocks.deinit(self.gpa());
self.stack.deinit(self.gpa());
self.consts.deinit(self.gpa());
}
if (localTyps) |local_types| {
try self.reserve(1 + 2 * local_types.len);
try self.uleb(local_types.len);
for (local_types) |local| {
try self.uleb(1); // Can be RLE for space optimization
try self.byte(std.wasm.valtype(local.lower()));
}
}
try self.block(.{ .label = null, .typ = typ.results }, insts);
try self.end(typ.results);
try self.isEmpty();
return self.dupe(ctx.arena.allocator());
}
fn popInstsUntil(self: *Codegen, insts: []const Expr, comptime endKeywords: []const u.Txt) ![]const Expr {
var remain = insts;
while (remain.len > 0) {
const e = remain[0].val.asList() orelse remain;
if (e.len > 0) if (e[0].val.asKeyword()) |kv|
inline for (endKeywords) |endK| if (u.strEql(endK, kv)) return remain;
if (self.blocks.items[self.blocks.items.len - 1].typ == null)
std.log.warn("Unreachable instructions {any}", .{remain});
remain = try self.popInst(remain);
}
return remain;
}
inline fn popInsts(self: *Codegen, insts: []const Expr) !void {
_ = try self.popInstsUntil(insts, &[_]u.Txt{});
}
fn blockUntil(self: *Codegen, it: Block, insts: []const Expr, comptime endKeywords: []const u.Txt) ![]const Expr {
try self.blocks.append(self.gpa(), it);
defer _ = self.blocks.pop();
return self.popInstsUntil(insts, endKeywords);
}
inline fn block(self: *Codegen, it: Block, insts: []const Expr) !void {
_ = try self.blockUntil(it, insts, &[_]u.Txt{});
}
const Error = error{
NotOp,
Empty,
NotDigit,
Overflow,
NotKeyword,
OutOfMemory,
Signed,
TypeMismatch,
NotFound,
NotPow2,
NotValtype,
DuplicatedId,
MultipleImport,
NotString,
TooMany,
BadImport,
BadExport,
ImportWithBody,
NoBlockEnd,
};
fn popInst(codegen: *Codegen, in: []const Expr) Error![]const Expr {
std.debug.assert(in.len > 0);
codegen.ctx.at = in[0];
const folded = if (in[0].val.asList()) |l| l.len > 0 else false;
const operation = (try codegen.extractFunc(if (folded) in[0].val.list else in, folded)) orelse return error.NotOp;
const folded_rem = if (folded) in[1..] else null;
if (nameToOp(operation.name)) |op| {
const do = Op.get(op);
const nargs = switch (do.narg) {
.sf => |f| f(operation),
else => take: {
const n = switch (do.narg) {
.n => |n| n,
.nf => |f| f(operation),
.sf => unreachable,
};
if (n > operation.args.len) return error.Empty;
break :take operation.args[n..];
},
};
if (folded) {
try codegen.popInsts(nargs);
codegen.ctx.at = in[0];
}
try codegen.pops(do.stack.pop);
try codegen.opcode(op);
const remain = (try do.gen(codegen, operation)) orelse
(folded_rem orelse nargs);
try codegen.pushs(do.stack.push);
return remain;
} else if (std.meta.stringToEnum(CustomBinOp, operation.name)) |op| {
if (folded) {
try codegen.popInsts(operation.args);
codegen.ctx.at = in[0];
}
var tr = try codegen.pop();
const tl = try codegen.pop();
if (tl != .val or !tr.eqlOrCast(tl.val, codegen)) {
codegen.ctx.err = .{ .typeMismatch = .{ .expect = tl, .got = tr } };
return error.TypeMismatch;
}
const do = CustomBinOp.get(op);
try codegen.opcode(switch (tl.val) {
.i32 => if (do.n == .i) do.n.i.i32o else null,
.i64 => if (do.n == .i) do.n.i.i64o else null,
.s8, .s16, .s32 => switch (do.n) {
.i => |n| n.i32o,
.su => |n| n.s32o,
},
.u8, .u16, .u32 => switch (do.n) {
.i => |n| n.i32o,
.su => |n| n.u32o,
},
.s64 => switch (do.n) {
.i => |n| n.i64o,
.su => |n| n.s64o,
},
.u64 => switch (do.n) {
.i => |n| n.i64o,
.su => |n| n.u64o,
},
.f32 => do.f32o,
.f64 => do.f64o,
} orelse {
codegen.ctx.err = .{ .typeMismatch = .{ .expect = if (do.f32o != null) Stack.of(.f32) else Stack.of(.i32), .got = tl } };
return error.TypeMismatch;
});
try codegen.push(if (do.bin) tl.val else .i32);
return folded_rem orelse operation.args;
} else if (std.meta.stringToEnum(CustomOp, operation.name)) |op| {
switch (op) {
.@"const.define", .@":=" => {
if (operation.args.len < 2) return error.Empty;
const id = operation.args[0].val.asId() orelse return error.NotFound;
const exprs = if (folded) operation.args[1..] else operation.args[1..2];
try codegen.consts.put(codegen.gpa(), id, exprs);
return folded_rem orelse operation.args[2..];
},
.@"const.expand" => {
if (operation.args.len == 0) return error.Empty;
const id = operation.args[0].val.asId() orelse return error.NotFound;
const exprs = codegen.consts.get(id) orelse return error.NotFound;
try codegen.popInsts(exprs);
return folded_rem orelse operation.args[1..];
},
.@"*=" => {
const mem_start = try codegen.popInst(operation.args);
const narg = nMemarg(mem_start);
const remain = mem_start[narg..];
if (folded) {
try codegen.popInsts(remain);
codegen.ctx.at = in[0];
}
const val = try codegen.pop();
if (val != .val) return error.TypeMismatch;
try codegen.pops(&[_]Hardtype{.i32});
const default_align: u32 = switch (val.val) {
.u8, .s8 => 1,
.u16, .s16 => 2,
.u32, .s32, .i32, .f32 => 4,
.u64, .s64, .i64, .f64 => 8,
};
const arg = try memarg(mem_start, default_align);
try codegen.opcode(switch (val.val) {
.u8, .s8 => .i32_store8,
.u16, .s16 => .i32_store16,
.u32, .s32, .i32 => .i32_store,
.f32 => .f32_store,
.u64, .s64, .i64 => .i64_store,
.f64 => .f64_store,
});
try codegen.uleb(arg.align_);
try codegen.uleb(arg.offset);
return folded_rem orelse remain;
},
}
//TODO: more custom ops
} else if (std.meta.stringToEnum(Hardtype, operation.name)) |typ| {
if (folded) {
try codegen.popInsts(operation.args);
codegen.ctx.at = in[0];
}
var val = try codegen.pop();
// Relaxed cast
if (!val.eqlOrCast(typ, codegen) and (val != .val or val.val.lower() != typ.lower())) {
try Stack.err(codegen, Stack.of(typ), val, null);
}
try codegen.push(typ);
return folded_rem orelse operation.args;
} else if (!folded or operation.args.len == 0) { // keyword only
const n8 = operation.name.len > 2 and std.ascii.isAlpha(operation.name[operation.name.len - 2]);
if (n8 or operation.name.len > 3) { // Short const
const head = operation.name[0 .. operation.name.len - 3 + @boolToInt(n8)];
const tail = operation.name[operation.name.len - 3 + @boolToInt(n8) ..];
if (std.meta.stringToEnum(Hardtype, tail)) |typ| {
const ok = switch (typ) {
.i32, .s32, .u32, .u16, .s16, .u8, .s8 => blk: {
const i = p.i32s(head) catch break :blk false;
const unsigned = switch (typ) {
.u32, .u16, .u8 => true,
else => false,
};
if (unsigned and i < 0) return error.Signed;
//MAYBE: check for overflow of n16 and n8
try codegen.opcode(.i32_const);
try codegen.ileb(i);
break :blk true;
},
.i64, .s64, .u64 => blk: {
const i = p.i64s(head) catch break :blk false;
if (typ == .u64 and i < 0) return error.Signed;
try codegen.opcode(.i64_const);
try codegen.ileb(i);
break :blk true;
},
.f32, .f64 => blk: {
const f = p.fNs(head) catch break :blk false;
if (typ == .f64) {
try codegen.opcode(.f64_const);
try codegen.writer().writeIntNative(u64, @bitCast(u64, f));
} else {
try codegen.opcode(.f32_const);
try codegen.writer().writeIntNative(u32, @bitCast(u32, @floatCast(f32, f)));
}
break :blk true;
},
};
if (ok) {
try codegen.push(typ);
return operation.args;
}
}
}
if (operation.name.len > 0) { // Int litteral const
const tail = switch (operation.name[operation.name.len - 1]) {
'i', 's', 'u' => operation.name[operation.name.len - 1],
else => null,
};
const head = operation.name[0 .. operation.name.len - @boolToInt(tail != null)];
if (p.i64s(head) catch null) |i| {
if (i < std.math.maxInt(i32) and i > std.math.minInt(i32)) {
const at = codegen.bytes.items.len;
try codegen.opcode(.i32_const);
const sign = switch (tail orelse 'i') {
's' => .s,
'u' => if (i < 0) return error.Signed else Stack.Sign.u,
else => if (i < 0) Stack.Sign.n else .p,
};
try codegen.stack.append(codegen.gpa(), .{ .i32 = .{ .at = at, .sign = sign } });
} else {
try codegen.opcode(.i64_const);
try codegen.push(.i64);
}
try codegen.ileb(i);
return operation.args;
}
}
//TODO: more custom keyword
}
return error.NotOp;
}
const F = struct {
name: u.Txt,
args: []const Expr,
folded: bool,
};
fn extractFunc(codegen: *Codegen, in: []const Expr, folded: bool) !?F {
return switch (in[0].val) {
.keyword => |name| blk: {
var f = F{ .name = name, .args = in[1..], .folded = folded };
if (u.strEql("=", f.name)) {
if (f.args.len == 0) return error.Empty;
const id = f.args[0].val.asId() orelse return error.NotOp;
f.name = switch (try codegen.idKind(id)) {
.local => @tagName(.local_set),
.global => @tagName(.global_set),
else => return error.NotOp,
};
}
break :blk f;
},
.id => |id| F{ .name = switch (try codegen.idKind(id)) {
.local => @tagName(.local_get),
.func => @tagName(.call),
.global => @tagName(.global_get),
.@"const" => @tagName(.@"const.expand"),
}, .args = in, .folded = folded },
else => null,
};
}
fn idKind(codegen: *const Codegen, id: u.Txt) !enum { local, global, func, @"const" } {
const local = codegen.locals.find(id) != null;
const call = Ctx.indexFindById(codegen.ctx.I.funcs, id) != null;
const global = Ctx.indexFindById(codegen.ctx.I.globals, id) != null;
const cons = codegen.consts.contains(id);
if (@boolToInt(local) + @boolToInt(call) + @boolToInt(global) + @boolToInt(cons) > 1)
return error.DuplicatedId;
if (local) return .local;
if (call) return .func;
if (global) return .global;
if (cons) return .@"const";
return error.NotFound;
}
fn nameToOp(name: u.Txt) ?IR.Code.Op {
var buf: [32]u8 = undefined;
const opname = if (std.mem.indexOfScalar(u8, name, '.')) |i| blk: {
const opname = buf[0..name.len];
std.mem.copy(u8, opname, name);
opname[i] = '_';
break :blk opname;
} else name;
return std.meta.stringToEnum(IR.Code.Op, opname);
}
const Op = struct {
narg: Narg = .{ .n = 0 },
stack: struct {
pop: []const Hardtype = &[_]Hardtype{},
push: []const Hardtype = &[_]Hardtype{},
} = .{},
gen: fn (self: *Codegen, func: F) Error!?[]const Expr = struct {
fn unit(_: *Codegen, _: F) !?[]const Expr {
return null;
}
}.unit,
const Narg = union(enum) {
n: usize,
nf: fn (func: F) usize,
sf: fn (func: F) []const Expr,
const one = @This(){ .n = 1 };
};
inline fn get(op: IR.Code.Op) Op {
return switch (op) {
.i32_const => comptime iNconst(.i32, false),
.i64_const => comptime iNconst(.i64, true),
.f32_const => comptime fNconst(.f32, false),
.f64_const => comptime fNconst(.f64, true),
.i32_load => comptime tNload(.i32, 4),
.i64_load => comptime tNload(.i64, 8),
.f32_load => comptime tNload(.f32, 4),
.f64_load => comptime tNload(.f64, 8),
.i32_load8_s, .i32_load8_u => comptime tNload(.i32, 1),
.i32_load16_s, .i32_load16_u => comptime tNload(.i32, 2),
.i64_load8_s, .i64_load8_u => comptime tNload(.i64, 1),
.i64_load16_s, .i64_load16_u => comptime tNload(.i64, 2),
.i64_load32_s, .i64_load32_u => comptime tNload(.i64, 4),
.i32_store => comptime tNstore(.i32, 4),
.i64_store => comptime tNstore(.i64, 8),
.f32_store => comptime tNstore(.f32, 4),
.f64_store => comptime tNstore(.f64, 8),
.i32_store8 => comptime tNstore(.i32, 1),
.i32_store16 => comptime tNstore(.i32, 2),
.i64_store8 => comptime tNstore(.i32, 1),
.i64_store16 => comptime tNstore(.i32, 2),
.i64_store32 => comptime tNstore(.i32, 4),
.i32_eqz => comptime tNtest(.i32),
.i32_eq, .i32_ne, .i32_lt_s, .i32_lt_u, .i32_gt_s, .i32_gt_u, .i32_le_s, .i32_le_u, .i32_ge_s, .i32_ge_u => comptime tNcompare(.i32),
.i64_eqz => comptime tNtest(.i64),
.i64_eq, .i64_ne, .i64_lt_s, .i64_lt_u, .i64_gt_s, .i64_gt_u, .i64_le_s, .i64_le_u, .i64_ge_s, .i64_ge_u => comptime tNcompare(.i64),
.f32_eq, .f32_ne, .f32_lt, .f32_gt, .f32_le, .f32_ge => comptime tNcompare(.f32),
.f64_eq, .f64_ne, .f64_lt, .f64_gt, .f64_le, .f64_ge => comptime tNcompare(.f64),
.i32_clz, .i32_ctz, .i32_popcnt, .i32_extend8_s, .i32_extend16_s => comptime tNunary(.i32),
.i32_add, .i32_sub, .i32_mul, .i32_div_s, .i32_div_u, .i32_rem_s, .i32_rem_u, .i32_and, .i32_or, .i32_xor, .i32_shl, .i32_shr_s, .i32_shr_u, .i32_rotl, .i32_rotr => comptime tNbinary(.i32),
.i64_clz, .i64_ctz, .i64_popcnt, .i64_extend8_s, .i64_extend16_s, .i64_extend32_s => comptime tNunary(.i64),
.i64_add, .i64_sub, .i64_mul, .i64_div_s, .i64_div_u, .i64_rem_s, .i64_rem_u, .i64_and, .i64_or, .i64_xor, .i64_shl, .i64_shr_s, .i64_shr_u, .i64_rotl, .i64_rotr => comptime tNbinary(.i64),
.f32_abs, .f32_neg, .f32_ceil, .f32_floor, .f32_trunc, .f32_nearest, .f32_sqrt => comptime tNunary(.f32),
.f32_add, .f32_sub, .f32_mul, .f32_div, .f32_min, .f32_max, .f32_copysign => comptime tNbinary(.f32),
.f64_abs, .f64_neg, .f64_ceil, .f64_floor, .f64_trunc, .f64_nearest, .f64_sqrt => comptime tNunary(.f64),
.f64_add, .f64_sub, .f64_mul, .f64_div, .f64_min, .f64_max, .f64_copysign => comptime tNbinary(.f64),
.i32_wrap_i64 => comptime tNfrom(.i32, .i64),
.i32_trunc_f32_s, .i32_trunc_f32_u => comptime tNfrom(.i32, .f32),
.i32_trunc_f64_s, .i32_trunc_f64_u => comptime tNfrom(.i32, .f64),
.i64_extend_i32_s, .i64_extend_i32_u => comptime tNfrom(.i64, .i32),
.i64_trunc_f32_s, .i64_trunc_f32_u => comptime tNfrom(.i64, .f32),
.i64_trunc_f64_s, .i64_trunc_f64_u => comptime tNfrom(.i64, .f64),
.f32_convert_i32_s, .f32_convert_i32_u => comptime tNfrom(.f32, .i32),
.f32_convert_i64_s, .f32_convert_i64_u => comptime tNfrom(.f32, .i64),
.f32_demote_f64 => comptime tNfrom(.f32, .f64),
.f64_convert_i32_s, .f64_convert_i32_u => comptime tNfrom(.f64, .i32),
.f64_convert_i64_s, .f64_convert_i64_u => comptime tNfrom(.f64, .i64),
.f64_promote_f32 => comptime tNfrom(.f64, .f32),
.i32_reinterpret_f32 => comptime tNfrom(.i32, .f32),
.i64_reinterpret_f64 => comptime tNfrom(.i64, .f64),
.f32_reinterpret_i32 => comptime tNfrom(.f32, .i32),
.f64_reinterpret_i64 => comptime tNfrom(.f64, .i64),
.local_get => comptime Op{ .narg = Narg.one, .gen = struct {
fn gen(self: *Codegen, func: F) !?[]const Expr {
const l = try self.locals.find_(func.args[0]);
try self.uleb(l.idx);
try self.push(l.typ);
return null;
}
}.gen },
.local_set => comptime Op{ .narg = Narg.one, .gen = struct {
fn gen(self: *Codegen, func: F) !?[]const Expr {
const l = try self.locals.find_(func.args[0]);
try self.uleb(l.idx);
try self.pops(&[_]Hardtype{l.typ});
return null;
}
}.gen },
.local_tee => comptime Op{ .narg = Narg.one, .gen = struct {
fn gen(self: *Codegen, func: F) !?[]const Expr {
const l = try self.locals.find_(func.args[0]);
try self.uleb(l.idx);
try self.pops(&[_]Hardtype{l.typ});
try self.push(l.typ);
return null;
}
}.gen },
.global_get => comptime Op{
.narg = Narg.one,
.gen = struct {
fn gen(self: *Codegen, func: F) !?[]const Expr {
const gs = &self.ctx.I.globals;
const i = if (func.args[0].val.asId()) |id|
Ctx.indexFindById(gs, id) orelse
return error.NotFound
else
try p.u32_(func.args[0]);
if (i >= gs.items.len) return error.NotFound;
try self.uleb(i);
@panic("FIXME:");
// try self.push(self.ctx.loadGlobal().typ);
// return null;
}
}.gen,
},
.nop => comptime Op{},
.call => comptime Op{ .narg = Narg.one, .gen = struct {
fn gen(self: *Codegen, func: F) Error!?[]const Expr {
const fs = &self.ctx.I.funcs;
const i = if (func.args[0].val.asId()) |id|
Ctx.indexFindById(fs, id) orelse
return error.NotFound
else
try p.u32_(func.args[0]);
if (i >= fs.items.len) return error.NotFound;
const ptr = try self.ctx.typeFunc(&fs.items[i].val, fs.items[i].id);
try self.pops(ptr.type.params);
try self.uleb(i);
try self.pushs(ptr.type.results);
return null;
}
}.gen },
.drop => comptime Op{ .gen = struct {
fn gen(self: *Codegen, _: F) !?[]const Expr {
_ = try self.pop();
return null;
}
}.gen },
.@"if" => comptime Op{
.narg = .{
.sf = struct {
fn sf(f: F) []const Expr {
if (!f.folded) return &[_]Expr{};
const has_label = f.args.len > 0 and f.args[0].val == .id;
var i: usize = @boolToInt(has_label);
i += p.nTypeuse(f.args[i..]);
if (i >= f.args.len) return &[_]Expr{};
for (f.args[i..]) |arg, j| {
if (p.asFuncNamed(arg, "then") != null)
return f.args[i .. i + j];
} else {
const has_else = f.args.len > i + 1;
const k = f.args.len - 1 - @boolToInt(has_else);
return f.args[i..k];
}
}
}.sf,
},
.stack = .{ .pop = &[_]Hardtype{ibool} },
.gen = struct {
fn gen(self: *Codegen, func: F) !?[]const Expr {
var remain = func.args;
if (remain.len == 0) return error.Empty;
const label = remain[0].val.asId();
if (label != null) remain = remain[1..];
const typ = try self.ctx.typeuse(remain);
defer typ.deinit(self.ctx);
remain = typ.remain;
if (remain.len == 0) return error.Empty;
//TODO: handle unknown types size (compact or not)
//TODO: handle unknown types values ([]?Hardtype)
try self.pops(typ.val.params);
if (typ.val.params.len == 0 and typ.val.results.len <= 1) {
try self.byte(if (typ.val.results.len > 0)
std.wasm.valtype(typ.val.results[0].lower())
else
std.wasm.block_empty);
} else {
const typ_id = @truncate(u32, self.types.items.len);
try self.types.append(self.gpa(), typ.val);
try self.relocs.append(self.gpa(), .{ .type = .typeIndexLeb, .offset = @truncate(u32, self.bytes.items.len), .index = typ_id });
try self.uleb5(typ_id);
}
const saved_stack = self.stack;
self.stack = .{};
try self.pushs(typ.val.params);
const a_block = Block{ .label = label, .typ = typ.val.results };
const has_else = if (func.folded) blk: {
const insts = for (remain) |arg, j| {
if (p.asFuncNamed(arg, "then") != null) {
remain = remain[j + 1 ..];
break arg.val.list[j..];
}
} else no_then: {
const has_folded_else = remain.len > 1;
const k = remain.len - 1 - @boolToInt(has_folded_else);
remain = remain[k + 1 ..];
break :no_then typ.remain[k .. k + 1];
};
try self.block(a_block, insts);
break :blk remain.len > 0;
} else blk: {
remain = try self.blockUntil(a_block, remain, &[_]u.Txt{ "else", "end" });
if (remain.len == 0) return error.NoBlockEnd;
const e = remain[0].val.asList() orelse remain;
remain = remain[1..]; // pop .else or .end
break :blk u.strEql("else", e[0].val.keyword);
};
try self.pops(typ.val.results);
try self.isEmpty();
if (has_else) {
try self.opcode(.@"else");
try self.pushs(typ.val.params);
if (func.folded) {
if (remain.len == 1 and p.asFuncNamed(remain[0], "else") != null)
remain = remain[0].val.list[1..];
try self.block(a_block, remain);
} else {
remain = try self.blockUntil(a_block, remain, &[_]u.Txt{"end"});
if (remain.len == 0) return error.NoBlockEnd;
remain = remain[1..]; // pop .end
}
try self.pops(typ.val.results);
try self.isEmpty();
} else if (typ.val.params.len != typ.val.results.len)
return error.TypeMismatch;
try self.opcode(.end);
self.stack.deinit(self.gpa());
self.stack = saved_stack;
try self.pushs(typ.val.results);
return if (func.folded) null else remain;
}
}.gen,
},
.block, .loop => comptime Op{
.narg = .{ .nf = struct {
fn all(func: F) usize {
return func.args.len;
}
}.all },
.gen = struct {
fn gen(self: *Codegen, func: F) !?[]const Expr {
//TODO: refactor duplicated code of if
var remain = func.args;
if (remain.len == 0) return error.Empty;
const label = remain[0].val.asId();
if (label != null) remain = remain[1..];
const typ = try self.ctx.typeuse(remain);
defer typ.deinit(self.ctx);
remain = typ.remain;
if (remain.len == 0) return error.Empty;
//TODO: handle unknown types size (compact or not)
//TODO: handle unknown types values ([]?Hardtype)
try self.pops(typ.val.params);
if (typ.val.params.len == 0 and typ.val.results.len <= 1) {
try self.byte(if (typ.val.results.len > 0)
std.wasm.valtype(typ.val.results[0].lower())
else
std.wasm.block_empty);
} else {
const typ_id = @truncate(u32, self.types.items.len);
try self.types.append(self.gpa(), typ.val);
try self.relocs.append(self.gpa(), .{ .type = .typeIndexLeb, .offset = @truncate(u32, self.bytes.items.len), .index = typ_id });
try self.uleb5(typ_id);
}
const saved_stack = self.stack;
self.stack = .{};
try self.pushs(typ.val.params);
const a_block = Block{ .label = label, .typ = typ.val.results };
if (func.folded) {
try self.block(a_block, remain);
} else {
remain = try self.blockUntil(a_block, remain, &[_]u.Txt{"end"});
if (remain.len == 0) return error.NoBlockEnd;
remain = remain[1..]; // pop .end
}
try self.pops(typ.val.results);
try self.isEmpty();
try self.opcode(.end);
self.stack.deinit(self.gpa());
self.stack = saved_stack;
try self.pushs(typ.val.results);
return if (func.folded) null else remain;
}
}.gen,
},
.@"else", .end => comptime Op{
.gen = struct {
fn gen(_: *Codegen, _: F) !?[]const Expr {
return error.NotOp;
}
}.gen,
},
.br => comptime Op{
.narg = Narg.one,
.gen = struct {
fn gen(self: *Codegen, func: F) !?[]const Expr {
const b = try self.findBlock(func.args[0]);
if (b.val.typ) |s| try Stack.endsWithOrCast(self, s);
self.blockEndUnreachable();
try self.uleb(b.idx);
return null;
}
}.gen,
},
.br_if => comptime Op{
.narg = Narg.one,
.stack = .{ .pop = &[_]Hardtype{ibool} },
.gen = struct {
fn gen(self: *Codegen, func: F) !?[]const Expr {
const b = try self.findBlock(func.args[0]);
if (b.val.typ) |s| try Stack.endsWithOrCast(self, s);
try self.uleb(b.idx);
return null;
}
}.gen,
},
.@"unreachable" => comptime Op{
.gen = struct {
fn gen(self: *Codegen, _: F) !?[]const Expr {
self.blockEndUnreachable();
return null;
}
}.gen,
},
//TODO: remove else branch
else => {
std.log.warn("Unhandled {}", .{op});
unreachable;
},
};
}
inline fn iNconst(val: Hardtype, comptime is64: bool) Op {
return .{ .narg = Narg.one, .stack = .{ .push = &[_]Hardtype{val} }, .gen = struct {
fn Gen(comptime Is64: bool) type {
return struct {
fn gen(self: *Codegen, func: F) !?[]const Expr {
const kv = try p.keyword(func.args[0]);
try self.ileb(try if (Is64) p.i64s(kv) else p.i32s(kv));
return null;
}
};
}
}.Gen(is64).gen };
}
inline fn fNconst(val: Hardtype, comptime is64: bool) Op {
return .{ .narg = Narg.one, .stack = .{ .push = &[_]Hardtype{val} }, .gen = struct {
fn Gen(comptime Is64: bool) type {
return struct {
fn gen(self: *Codegen, func: F) !?[]const Expr {
const f = try p.fNs(try p.keyword(func.args[0]));
const I = if (Is64) u64 else u32;
const i = @bitCast(I, @floatCast(if (Is64) f64 else f32, f));
try self.writer().writeIntNative(I, i);
return null;
}
};
}
}.Gen(is64).gen };
}
fn GenMemarg(comptime align__: u32) type {
return struct {
fn gen(self: *Codegen, func: F) !?[]const Expr {
const arg = try memarg(func.args, align__);
try self.uleb(arg.align_);
try self.uleb(arg.offset);
return null;
}
};
}
fn nfMemarg(f: F) usize {
return nMemarg(f.args);
}
inline fn tNstore(val: Hardtype, comptime align_: u32) Op {
return .{
.narg = .{ .nf = nfMemarg },
.stack = .{
.pop = &[_]Hardtype{ .i32, val },
},
.gen = GenMemarg(align_).gen,
};
}
inline fn tNload(val: Hardtype, comptime align_: u32) Op {
return .{
.narg = .{ .nf = nfMemarg },
.stack = .{
.pop = &[_]Hardtype{.i32},
.push = &[_]Hardtype{val},
},
.gen = GenMemarg(align_).gen,
};
}
inline fn tNtest(val: Hardtype) Op {
return .{ .stack = .{
.pop = &[_]Hardtype{val},
.push = &[_]Hardtype{ibool},
} };
}
inline fn tNcompare(val: Hardtype) Op {
return .{ .stack = .{
.pop = &[_]Hardtype{ val, val },
.push = &[_]Hardtype{ibool},
} };
}
inline fn tNunary(val: Hardtype) Op {
return .{ .stack = .{
.pop = &[_]Hardtype{val},
.push = &[_]Hardtype{val},
} };
}
inline fn tNbinary(val: Hardtype) Op {
return .{ .stack = .{
.pop = &[_]Hardtype{ val, val },
.push = &[_]Hardtype{val},
} };
}
inline fn tNfrom(to: Hardtype, from: Hardtype) Op {
return .{ .stack = .{
.pop = &[_]Hardtype{from},
.push = &[_]Hardtype{to},
} };
}
};
const ibool = .i32;
const CustomBinOp = enum {
@"==",
@"!=",
@"<s",
@"<u",
@"<",
@">s",
@">u",
@">",
@"<=s",
@"<=u",
@"<=",
@">=s",
@">=u",
@">=",
@"+",
@"-",
@"*",
@"/s",
@"/u",
@"/",
@"%s",
@"%u",
@"%",
@"&",
@"|",
@"^",
@"<<",
@">>s",
@">>u",
@">>",
@"<<<",
@">>>",
const Gen = struct { n: union(enum) { i: struct { i32o: ?IR.Code.Op, i64o: ?IR.Code.Op }, su: struct { s32o: ?IR.Code.Op, s64o: ?IR.Code.Op, u32o: ?IR.Code.Op, u64o: ?IR.Code.Op } }, f32o: ?IR.Code.Op, f64o: ?IR.Code.Op, bin: bool };
inline fn get(op: @This()) Gen {
// Good luck compiler
@setEvalBranchQuota(100000);
return switch (op) {
.@"==" => comptime ifNbin("eq"),
.@"!=" => comptime ifNbin("ne"),
.@"<s" => comptime iNtest("lt_s"),
.@"<u" => comptime iNtest("lt_u"),
.@"<" => comptime sufNtest("lt"),
.@">s" => comptime iNtest("gt_s"),
.@">u" => comptime iNtest("gt_u"),
.@">" => comptime sufNtest("gt"),
.@"<=s" => comptime iNtest("le_s"),
.@"<=u" => comptime iNtest("le_u"),
.@"<=" => comptime sufNtest("le"),
.@">=s" => comptime iNtest("ge_s"),
.@">=u" => comptime iNtest("ge_u"),
.@">=" => comptime sufNtest("ge"),
.@"+" => comptime ifNbin("add"),
.@"-" => comptime ifNbin("sub"),
.@"*" => comptime ifNbin("mul"),
.@"/s" => comptime iNbin("div_s"),
.@"/u" => comptime iNbin("div_u"),
.@"/" => comptime sufN("div", true),
.@"%s" => comptime iNbin("rem_s"),
.@"%u" => comptime iNbin("rem_u"),
.@"%" => comptime suNbin("rem"),
.@">>s" => comptime iNbin("shr_s"),
.@">>u" => comptime iNbin("shr_u"),
.@">>" => comptime suNbin("shr"),
.@"&" => comptime iNbin("and"),
.@"|" => comptime iNbin("or"),
.@"^" => comptime iNbin("xor"),
.@"<<" => comptime iNbin("shl"),
.@"<<<" => comptime iNbin("rotl"),
.@">>>" => comptime iNbin("rotr"),
};
}
inline fn opFromStr(comptime t: IR.Valtype, comptime s: u.Txt) IR.Code.Op {
return std.meta.stringToEnum(IR.Code.Op, @tagName(t) ++ "_" ++ s) orelse @compileError("Missing op");
}
inline fn iN(comptime s: u.Txt, bin: bool) Gen {
return .{ .n = .{ .i = .{ .i32o = opFromStr(.i32, s), .i64o = opFromStr(.i64, s) } }, .f32o = null, .f64o = null, .bin = bin };
}
inline fn ifNbin(comptime s: u.Txt) Gen {
return .{ .n = .{ .i = .{ .i32o = opFromStr(.i32, s), .i64o = opFromStr(.i64, s) } }, .f32o = opFromStr(.f32, s), .f64o = opFromStr(.f64, s), .bin = true };
}
inline fn sufN(comptime s: u.Txt, bin: bool) Gen {
return .{ .n = .{ .su = .{
.s32o = opFromStr(.i32, s ++ "_s"),
.s64o = opFromStr(.i64, s ++ "_s"),
.u32o = opFromStr(.i32, s ++ "_u"),
.u64o = opFromStr(.i64, s ++ "_u"),
} }, .f32o = opFromStr(.f32, s), .f64o = opFromStr(.f64, s), .bin = bin };
}
inline fn suNbin(comptime s: u.Txt) Gen {
return .{ .n = .{ .su = .{
.s32o = opFromStr(.i32, s ++ "_s"),
.s64o = opFromStr(.i64, s ++ "_s"),
.u32o = opFromStr(.i32, s ++ "_u"),
.u64o = opFromStr(.i64, s ++ "_u"),
} }, .f32o = null, .f64o = null, .bin = true };
}
inline fn iNbin(comptime s: u.Txt) Gen {
return iN(s, true);
}
inline fn iNtest(comptime s: u.Txt) Gen {
return iN(s, false);
}
inline fn sufNtest(comptime s: u.Txt) Gen {
return sufN(s, false);
}
};
const CustomOp = enum { @"const.define", @":=", @"const.expand", @"*=" };
fn kvarg(exprs: []const Expr, comptime key: u.Txt) ?u.Txt {
if (exprs.len > 0) {
if (exprs[0].val.asKeyword()) |k| {
if (std.mem.startsWith(u8, k, key ++ "="))
return k[key.len + 1 ..];
}
}
return null;
}
fn nMemarg(exprs: []const Expr) usize {
var i: usize = 0;
if (kvarg(exprs, "offset") != null)
i += 1;
if (kvarg(exprs[i..], "align") != null)
i += 1;
return i;
}
fn memarg(exprs: []const Expr, n: u32) !IR.Code.MemArg {
var i: usize = 0;
const offset = if (kvarg(exprs, "offset")) |v|
try p.u32s(v)
else
0;
const x = if (kvarg(exprs[i..], "align")) |v|
try p.u32s(v)
else
n;
if (x == 0 or (x & (x - 1)) != 0) return error.NotPow2;
return IR.Code.MemArg{ .offset = offset, .align_ = @ctz(u32, x) };
}
const FoundBlock = struct {
idx: usize,
val: Block,
};
fn findBlock(self: *Codegen, expr: Expr) !FoundBlock {
const bs = self.blocks.items;
if (expr.val.asId()) |id| {
// shadow older
var i = bs.len;
while (i > 0) : (i -= 1) {
const b = bs[i - 1];
if (b.label) |lb| if (u.strEql(id, lb))
return FoundBlock{ .idx = bs.len - i, .val = b };
}
return error.NotFound;
} else {
const i = try p.u32_(expr);
if (i >= bs.len) return error.NotFound;
// 0 is current block
return FoundBlock{ .idx = i, .val = bs[bs.len - 1 - i] };
}
}
inline fn blockEndUnreachable(self: *Codegen) void {
self.blocks.items[self.blocks.items.len - 1].typ = null;
}
fn end(self: *Codegen, results: []const Hardtype) !void {
try self.pops(results);
try self.opcode(.end);
}
fn dupe(self: Codegen, allocator: std.mem.Allocator) !IR.Code {
return IR.Code{
.bytes = try allocator.dupe(u8, self.bytes.items),
.types = try allocator.dupe(IR.Func.Sig, self.types.items),
.relocs = try allocator.dupe(IR.Linking.Reloc.Entry, self.relocs.items),
};
}
inline fn gpa(self: *const Codegen) std.mem.Allocator {
return self.ctx.arena.child_allocator;
}
fn reserve(self: *Codegen, n: usize) !void {
try self.bytes.ensureUnusedCapacity(self.gpa(), n);
}
fn byte(self: *Codegen, b: u8) !void {
try self.bytes.append(self.gpa(), b);
}
inline fn writer(self: *Codegen) std.ArrayListUnmanaged(u8).Writer {
return self.bytes.writer(self.gpa());
}
inline fn opcode(self: *Codegen, op: IR.Code.Op) !void {
try self.byte(std.wasm.opcode(op));
}
fn uleb(self: *Codegen, v: u64) !void {
try std.leb.writeULEB128(self.writer(), v);
}
inline fn uleb5At(ptr: *[5]u8, v: u32) void {
std.leb.writeUnsignedFixed(5, ptr, v);
}
/// uleb with always 5-byte
fn uleb5(self: *Codegen, v: u32) !void {
var buf: [5]u8 = undefined;
uleb5At(&buf, v);
try self.writer().writeAll(&buf);
}
fn ileb(self: *Codegen, v: i64) !void {
try std.leb.writeILEB128(self.writer(), v);
}
fn push(self: *Codegen, typ: Hardtype) !void {
try self.stack.append(self.gpa(), .{ .val = typ });
}
fn pushs(self: *Codegen, typs: []const Hardtype) !void {
try self.stack.ensureUnusedCapacity(self.gpa(), typs.len);
for (typs) |typ|
self.stack.appendAssumeCapacity(.{ .val = typ });
}
fn pop(self: *Codegen) !Stack {
if (self.stack.items.len == 0)
return error.TypeMismatch;
return self.stack.pop();
}
fn pops(self: *Codegen, typs: []const Hardtype) !void {
try Stack.endsWithOrCast(self, typs);
self.stack.items.len -= typs.len;
}
fn isEmpty(self: *Codegen) !void {
const l = self.stack.items.len;
if (l == 0) return;
try Stack.err(self, null, self.stack.items[l - 1], l);
}
const Locals = struct {
first: []const Hardtype,
second: []const Hardtype,
ids: []const ?u.Txt,
fn find(it: @This(), id: u.Txt) ?u32 {
return for (it.ids) |f, j| {
if (f != null and u.strEql(id, f.?))
break @truncate(u32, j);
} else null;
}
const Found = struct {
idx: usize,
typ: Hardtype,
};
fn find_(it: @This(), expr: Expr) !Found {
const i = if (expr.val.asId()) |id|
it.find(id) orelse
return error.NotFound
else
try p.u32_(expr);
if (i >= it.first.len + it.second.len) return error.NotFound;
return Found{ .idx = i, .typ = if (i < it.first.len) it.first[i] else it.second[i - it.first.len] };
}
};
const Block = struct {
label: ?u.Txt,
/// null is unreachable
typ: ?[]const Hardtype,
};
pub const Stack = union(enum) {
val: Hardtype,
/// Can be implicitly converted to .i64_const op
i32: struct {
/// Offset of .i32_const op
at: usize,
sign: Sign,
},
//TODO: /// Can be implicitly converted to .f64_const op
// f32: usize,
const Sign = enum { p, n, s, u };
pub fn format(
self: Stack,
comptime _: []const u8,
_: std.fmt.FormatOptions,
w: anytype,
) !void {
return w.writeAll(switch (self) {
.val => |v| @tagName(v),
.i32 => |v| switch (v.sign) {
.p => "+N",
.n => "-N",
.s => "sN",
.u => "uN",
},
});
}
inline fn eql(self: Stack, other: Stack) bool {
return std.meta.eql(self, other) or (self == .i32 and other.eqlV(.i32)) or (other == .i32 and self.eqlV(.i32));
}
inline fn eqlV(self: Stack, v: Hardtype) bool {
return self.eql(.{ .val = v });
}
fn eqlOrCast(got: *Stack, expect: Hardtype, self: *Codegen) bool {
return switch (got.*) {
.val => |v| switch (expect) {
.i32, .i64 => v.lower() == expect.lower(),
else => v == expect,
},
.i32 => |v| switch (expect) {
//NOTE: i to s implicit cast is probably misleading
.i32, .s32 => true,
.u32 => v.sign == .p or v.sign == .u,
.i64, .s64, .u64 => {
if (!switch (v.sign) {
.s => expect == .s64,
.u => expect == .u64,
.n => expect == .i64 or expect == .s64,
.p => true,
}) return false;
self.bytes.items[v.at] = std.wasm.opcode(.i64_const);
got.* = .{ .val = expect };
return true;
},
else => false,
},
};
}
inline fn of(v: Hardtype) Stack {
return .{ .val = v };
}
inline fn err(self: *Codegen, expect: ?Stack, got: ?Stack, index: ?usize) !void {
self.ctx.err = .{ .typeMismatch = .{ .expect = expect, .got = got, .index = index } };
return error.TypeMismatch;
}
fn eqlOrCastSlice(self: *Codegen, offset: usize, typs: []const Hardtype) !void {
std.debug.assert(self.stack.items.len >= offset);
const st = self.stack.items[offset..];
if (st.len > typs.len) return err(self, null, st[typs.len], typs.len);
if (st.len < typs.len) return err(self, of(typs[st.len]), null, st.len);
for (st) |*got, i|
if (!got.eqlOrCast(typs[i], self))
return err(self, of(typs[i]), got.*, i);
}
fn eqlSliceV(self: *Codegen, st: []const Stack, typs: []const Hardtype) !void {
if (st.len > typs.len) return err(self, null, st[typs.len], typs.len);
if (st.len < typs.len) return err(self, of(typs[st.len]), null, st.len);
for (st) |got, i|
if (!got.eqlV(typs[i]))
return err(self, of(typs[i]), got, i);
}
fn eqlSlice(self: *Codegen, st: []const Stack, typs: []const Stack) !void {
if (st.len > typs.len) return err(self, null, st[typs.len], typs.len);
if (st.len < typs.len) return err(self, typs[st.len], null, st.len);
for (st) |got, i|
if (!typs[i].eql(got))
return err(self, typs[i], got, i);
}
inline fn fits(self: *Codegen, st: []const Stack, typs: []const Hardtype) !void {
if (st.len < typs.len) return err(self, of(typs[st.len]), null, st.len);
}
fn endsWith(self: *Codegen, st: []const Stack, typs: []const Hardtype) !void {
try fits(self, st, typs);
return eqlSliceV(self, st[st.len - typs.len ..], typs);
}
fn endsWithOrCast(self: *Codegen, typs: []const Hardtype) !void {
try fits(self, self.stack.items, typs);
return eqlOrCastSlice(self, self.stack.items.len - typs.len, typs);
}
}; | src/Wat/Codegen.zig |
const std = @import("std");
const gk = @import("../gamekit.zig");
const math = gk.math;
const rk = gk.renderkit;
const renderer = rk.renderer;
const fs = gk.utils.fs;
/// default params for the sprite shader. Translates the Mat32 into 2 arrays of f32 for the shader uniform slot.
pub const VertexParams = extern struct {
pub const metadata = .{
.uniforms = .{ .VertexParams = .{ .type = .float4, .array_count = 2 } },
.images = .{"main_tex"},
};
transform_matrix: [8]f32 = [_]f32{0} ** 8,
pub fn init(mat: *math.Mat32) VertexParams {
var params = VertexParams{};
std.mem.copy(f32, ¶ms.transform_matrix, &mat.data);
return params;
}
};
fn defaultVertexShader() [:0]const u8 {
return switch (rk.current_renderer) {
.opengl => @embedFile("../assets/sprite_vs.glsl"),
.metal => @embedFile("../assets/sprite_vs.metal"),
else => @panic("no default vert shader for renderer: " ++ rk.current_renderer),
};
}
fn defaultFragmentShader() [:0]const u8 {
return switch (rk.current_renderer) {
.opengl => @embedFile("../assets/sprite_fs.glsl"),
.metal => @embedFile("../assets/sprite_fs.metal"),
else => @panic("no default vert shader for renderer: " ++ rk.current_renderer),
};
}
pub const Shader = struct {
shader: rk.ShaderProgram,
onPostBind: ?fn (*Shader) void,
onSetTransformMatrix: ?fn (*math.Mat32) void,
const Empty = struct {};
pub const ShaderOptions = struct {
/// if vert and frag are file paths an Allocator is required. If they are the shader code then no Allocator should be provided
allocator: ?std.mem.Allocator = null,
/// optional vertex shader file path (without extension) or shader code. If null, the default sprite shader vertex shader is used
vert: ?[:0]const u8 = null,
/// required frag shader file path (without extension) or shader code.
frag: [:0]const u8,
/// optional function that will be called immediately after bind is called allowing you to auto-update uniforms
onPostBind: ?fn (*Shader) void = null,
/// optional function that lets you override the behavior when the transform matrix is set. This is used when there is a
/// custom vertex shader and isnt necessary if the standard sprite vertex shader is used. Note that the shader is already
/// bound when this is called if `gfx.setShader` is used so send your uniform immediately!
onSetTransformMatrix: ?fn (*math.Mat32) void = null,
};
pub fn initDefaultSpriteShader() !Shader {
return initWithVertFrag(VertexParams, Empty, .{ .vert = defaultVertexShader(), .frag = defaultFragmentShader() });
}
pub fn initWithFrag(comptime FragUniformT: type, options: ShaderOptions) !Shader {
return initWithVertFrag(VertexParams, FragUniformT, options);
}
pub fn initWithVertFrag(comptime VertUniformT: type, comptime FragUniformT: type, options: ShaderOptions) !Shader {
const vert = blk: {
// if we were not provided a vert shader we substitute in the sprite shader
if (options.vert) |vert| {
// if we were provided an allocator that means this is a file
if (options.allocator) |allocator| {
const vert_path = try std.mem.concat(allocator, u8, &[_][]const u8{ vert, rk.shaderFileExtension(), "\x00" });
defer allocator.free(vert_path);
break :blk try fs.readZ(allocator, vert_path);
}
break :blk vert;
} else {
break :blk defaultVertexShader();
}
};
const frag = blk: {
if (options.allocator) |allocator| {
const frag_path = try std.mem.concat(allocator, u8, &[_][]const u8{ options.frag, rk.shaderFileExtension() });
defer allocator.free(frag_path);
break :blk try fs.readZ(allocator, frag_path);
}
break :blk options.frag;
};
return Shader{
.shader = renderer.createShaderProgram(VertUniformT, FragUniformT, .{ .vs = vert, .fs = frag }),
.onPostBind = options.onPostBind,
.onSetTransformMatrix = options.onSetTransformMatrix,
};
}
pub fn deinit(self: Shader) void {
renderer.destroyShaderProgram(self.shader);
}
pub fn bind(self: *Shader) void {
renderer.useShaderProgram(self.shader);
if (self.onPostBind) |onPostBind| onPostBind(self);
}
pub fn setTransformMatrix(self: Shader, matrix: *math.Mat32) void {
if (self.onSetTransformMatrix) |setMatrix| {
setMatrix(matrix);
} else {
var params = VertexParams.init(matrix);
self.setVertUniform(VertexParams, ¶ms);
}
}
pub fn setVertUniform(self: Shader, comptime VertUniformT: type, value: *VertUniformT) void {
renderer.setShaderProgramUniformBlock(VertUniformT, self.shader, .vs, value);
}
pub fn setFragUniform(self: Shader, comptime FragUniformT: type, value: *FragUniformT) void {
renderer.setShaderProgramUniformBlock(FragUniformT, self.shader, .fs, value);
}
};
/// convenience object that binds a fragment uniform with a Shader. You can optionally wire up the onPostBind method
/// to the Shader.onPostBind so that the FragUniformT object is automatically updated when the Shader is bound.
pub fn ShaderState(comptime FragUniformT: type) type {
return struct {
shader: Shader,
frag_uniform: FragUniformT = .{},
pub fn init(options: Shader.ShaderOptions) @This() {
return .{
.shader = Shader.initWithFrag(FragUniformT, options) catch unreachable,
};
}
pub fn deinit(self: @This()) void {
self.shader.deinit();
}
pub fn onPostBind(shader: *Shader) void {
const self = @fieldParentPtr(@This(), "shader", shader);
shader.setFragUniform(FragUniformT, &self.frag_uniform);
}
};
} | gamekit/graphics/shader.zig |
const std = @import("std");
pub const gpu = @import("gpu/build.zig");
const gpu_dawn = @import("gpu-dawn/build.zig");
pub const glfw = @import("glfw/build.zig");
const Pkg = std.build.Pkg;
pub fn build(b: *std.build.Builder) void {
const mode = b.standardReleaseOptions();
const target = b.standardTargetOptions(.{});
const gpu_dawn_options = gpu_dawn.Options{
.from_source = b.option(bool, "dawn-from-source", "Build Dawn from source") orelse false,
};
const options = Options{ .gpu_dawn_options = gpu_dawn_options };
// TODO: re-enable tests
const main_tests = b.addTest("src/main.zig");
main_tests.setBuildMode(mode);
main_tests.setTarget(target);
main_tests.addPackage(pkg);
main_tests.addPackage(gpu.pkg);
main_tests.addPackage(glfw.pkg);
const test_step = b.step("test", "Run library tests");
test_step.dependOn(&main_tests.step);
// TODO(build-system): https://github.com/hexops/mach/issues/229#issuecomment-1100958939
ensureDependencySubmodule(b.allocator, "examples/libs/zmath") catch unreachable;
ensureDependencySubmodule(b.allocator, "examples/libs/zigimg") catch unreachable;
ensureDependencySubmodule(b.allocator, "examples/assets") catch unreachable;
inline for ([_]ExampleDefinition{
.{ .name = "triangle" },
.{ .name = "boids" },
.{ .name = "rotating-cube", .packages = &[_]Pkg{Packages.zmath} },
.{ .name = "two-cubes", .packages = &[_]Pkg{Packages.zmath} },
.{ .name = "instanced-cube", .packages = &[_]Pkg{Packages.zmath} },
.{ .name = "gkurve", .packages = &[_]Pkg{Packages.zmath} },
.{ .name = "advanced-gen-texture-light", .packages = &[_]Pkg{Packages.zmath} },
.{ .name = "textured-cube", .packages = &[_]Pkg{ Packages.zmath, Packages.zigimg } },
.{ .name = "fractal-cube", .packages = &[_]Pkg{Packages.zmath} },
}) |example| {
const example_app = App.init(
b,
.{
.name = "example-" ++ example.name,
.src = "examples/" ++ example.name ++ "/main.zig",
.deps = comptime example.packages ++ &[_]Pkg{ glfw.pkg, gpu.pkg, pkg },
},
);
const example_exe = example_app.step;
example_exe.setTarget(target);
example_exe.setBuildMode(mode);
example_app.link(options);
example_exe.install();
const example_run_cmd = example_exe.run();
example_run_cmd.step.dependOn(&example_exe.install_step.?.step);
const example_run_step = b.step("run-example-" ++ example.name, "Run the example");
example_run_step.dependOn(&example_run_cmd.step);
}
const shaderexp_app = App.init(
b,
.{
.name = "shaderexp",
.src = "shaderexp/main.zig",
.deps = &.{ glfw.pkg, gpu.pkg, pkg },
},
);
const shaderexp_exe = shaderexp_app.step;
shaderexp_exe.setTarget(target);
shaderexp_exe.setBuildMode(mode);
shaderexp_app.link(options);
shaderexp_exe.install();
const shaderexp_run_cmd = shaderexp_exe.run();
shaderexp_run_cmd.step.dependOn(&shaderexp_exe.install_step.?.step);
const shaderexp_run_step = b.step("run-shaderexp", "Run shaderexp");
shaderexp_run_step.dependOn(&shaderexp_run_cmd.step);
const compile_all = b.step("compile-all", "Compile all examples and applications");
compile_all.dependOn(b.getInstallStep());
}
pub const Options = struct {
glfw_options: glfw.Options = .{},
gpu_dawn_options: gpu_dawn.Options = .{},
};
const ExampleDefinition = struct {
name: []const u8,
packages: []const Pkg = &[_]Pkg{},
};
const Packages = struct {
// Declared here because submodule may not be cloned at the time build.zig runs.
const zmath = std.build.Pkg{
.name = "zmath",
.path = .{ .path = "examples/libs/zmath/src/zmath.zig" },
};
const zigimg = std.build.Pkg{
.name = "zigimg",
.path = .{ .path = "examples/libs/zigimg/zigimg.zig" },
};
};
const App = struct {
step: *std.build.LibExeObjStep,
b: *std.build.Builder,
pub fn init(b: *std.build.Builder, options: struct {
name: []const u8,
src: []const u8,
deps: ?[]const Pkg = null,
}) App {
const exe = b.addExecutable(options.name, "src/native.zig");
exe.addPackage(.{
.name = "app",
.path = .{ .path = options.src },
.dependencies = options.deps,
});
exe.addPackage(gpu.pkg);
exe.addPackage(glfw.pkg);
return .{
.b = b,
.step = exe,
};
}
pub fn link(app: *const App, options: Options) void {
const gpu_options = gpu.Options{
.glfw_options = @bitCast(@import("gpu/libs/mach-glfw/build.zig").Options, options.glfw_options),
.gpu_dawn_options = @bitCast(@import("gpu/libs/mach-gpu-dawn/build.zig").Options, options.gpu_dawn_options),
};
glfw.link(app.b, app.step, options.glfw_options);
gpu.link(app.b, app.step, gpu_options);
}
};
pub const pkg = std.build.Pkg{
.name = "mach",
.path = .{ .path = thisDir() ++ "/src/main.zig" },
.dependencies = &.{ gpu.pkg, glfw.pkg },
};
fn thisDir() []const u8 {
return std.fs.path.dirname(@src().file) orelse ".";
}
fn ensureDependencySubmodule(allocator: std.mem.Allocator, path: []const u8) !void {
if (std.process.getEnvVarOwned(allocator, "NO_ENSURE_SUBMODULES")) |no_ensure_submodules| {
if (std.mem.eql(u8, no_ensure_submodules, "true")) return;
} else |_| {}
var child = std.ChildProcess.init(&.{ "git", "submodule", "update", "--init", path }, allocator);
child.cwd = thisDir();
child.stderr = std.io.getStdErr();
child.stdout = std.io.getStdOut();
_ = try child.spawnAndWait();
} | build.zig |
const std = @import("std");
const aoc = @import("aoc-lib.zig");
const Cave = struct {
next: [16]u16,
lower: u16,
max: u16,
alloc: std.mem.Allocator,
const START = 1;
const END = 2;
pub fn init(alloc: std.mem.Allocator, inp: []const u8) !*Cave {
var cave = try alloc.create(Cave);
cave.alloc = alloc;
std.mem.set(u16, cave.next[0..], 0);
cave.lower = 0;
cave.max = END;
var ids = std.StringHashMap(u16).init(alloc);
defer ids.deinit();
try ids.put("start", START);
try ids.put("end", END);
var start: usize = 0;
var dash: usize = 0;
for (inp) |ch, i| {
switch (ch) {
'-' => {
dash = i;
},
'\n' => {
try cave.addpath(
&ids,
inp[start..dash],
inp[dash + 1 .. i],
);
start = i + 1;
},
else => {},
}
}
//aoc.print("{any}\n", .{cave}) catch unreachable;
return cave;
}
pub fn deinit(self: *Cave) void {
self.alloc.destroy(self);
}
pub fn solve(self: *Cave, start: u16, cseen: u16, cache: *std.AutoHashMap(usize, usize), p2: bool, twice: bool) anyerror!usize {
//try aoc.print("solving {b} {b}\n", .{ start, cseen });
var seen = cseen;
if (start == END) {
//try aoc.print(" found end\n", .{});
return 1;
}
if (self.lower & start != 0) {
seen |= start;
}
var k = ((@as(usize, @ctz(u16, start)) << 16) + seen) << 1;
if (twice) {
k += 1;
}
if (cache.get(k)) |v| {
//try aoc.print(" found in cache {}\n", .{v});
return v;
}
var paths: usize = 0;
var neighbors = self.next[@ctz(u16, start)];
//try aoc.print(" neighbors: {b}\n", .{neighbors});
var nb: u16 = 1;
while (nb <= self.max) : (nb <<= 1) {
if (nb & neighbors == 0) {
continue;
}
var ntwice = twice;
if (seen & nb != 0) {
if (!p2 or twice) {
continue;
}
ntwice = true;
}
paths += try self.solve(nb, seen, cache, p2, ntwice);
}
try cache.put(k, paths);
return paths;
}
pub fn part1(self: *Cave) !usize {
var cache = std.AutoHashMap(usize, usize).init(self.alloc);
defer cache.deinit();
return try self.solve(START, 0, &cache, false, false);
}
pub fn part2(self: *Cave) !usize {
var cache = std.AutoHashMap(usize, usize).init(self.alloc);
defer cache.deinit();
return try self.solve(START, 0, &cache, true, false);
}
fn id(self: *Cave, ids: *std.StringHashMap(u16), cave: []const u8) !u16 {
if (ids.get(cave)) |v| {
return v;
}
self.max <<= 1;
try ids.put(cave, self.max);
if ('a' <= cave[0] and cave[0] <= 'z') {
self.lower |= self.max;
}
return self.max;
}
fn addpath(self: *Cave, ids: *std.StringHashMap(u16), s: []const u8, e: []const u8) !void {
var start = try self.id(ids, s);
var end = try self.id(ids, e);
//aoc.print("would add path {s} {b} {} -> {s} {b} {}\n", .{
// s, start, @ctz(u16, start), e, end, @ctz(u16, end),
//}) catch unreachable;
if (end != START and start != END) { // don't add path to start
self.next[@ctz(u16, start)] |= end;
}
if (start != START and end != END) { // don't add path to start
self.next[@ctz(u16, end)] |= start;
}
}
};
test "part1" {
var t1 = try Cave.init(aoc.talloc, aoc.test1file);
defer t1.deinit();
try aoc.assertEq(@as(usize, 10), try t1.part1());
var t2 = try Cave.init(aoc.talloc, aoc.test2file);
defer t2.deinit();
try aoc.assertEq(@as(usize, 19), try t2.part1());
var t3 = try Cave.init(aoc.talloc, aoc.test3file);
defer t3.deinit();
try aoc.assertEq(@as(usize, 226), try t3.part1());
var r = try Cave.init(aoc.talloc, aoc.inputfile);
defer r.deinit();
try aoc.assertEq(@as(usize, 4691), try r.part1());
}
test "part2" {
var t1 = try Cave.init(aoc.talloc, aoc.test1file);
defer t1.deinit();
try aoc.assertEq(@as(usize, 36), try t1.part2());
var t2 = try Cave.init(aoc.talloc, aoc.test2file);
defer t2.deinit();
try aoc.assertEq(@as(usize, 103), try t2.part2());
var t3 = try Cave.init(aoc.talloc, aoc.test3file);
defer t3.deinit();
try aoc.assertEq(@as(usize, 3509), try t3.part2());
var r = try Cave.init(aoc.talloc, aoc.inputfile);
defer r.deinit();
try aoc.assertEq(@as(usize, 140718), try r.part2());
}
fn day12(inp: []const u8, bench: bool) anyerror!void {
var cave = try Cave.init(aoc.halloc, inp);
var p1 = try cave.part1();
var p2 = try cave.part2();
if (!bench) {
try aoc.print("Part 1: {}\nPart 2: {}\n", .{ p1, p2 });
}
}
pub fn main() anyerror!void {
try aoc.benchme(aoc.input(), day12);
} | 2021/12/aoc.zig |
const std = @import("std");
const TypeId = @import("builtin").TypeId;
fn is_signed(comptime N: type) bool {
switch (@typeInfo(N)) {
TypeId.Int => |int| {
return int.is_signed;
},
else => {
@compileError("Is_signed is only available on integer types. Found `" ++ @typeName(N) ++ "`.");
}
}
}
fn bitcount(comptime N: type) u32 {
switch (@typeInfo(N)) {
TypeId.Int => |int| {
return @intCast(u32, int.bits);
},
else => {
@compileError("Bitcount only available on integer types. Found `" ++ @typeName(N) ++ "`.");
}
}
}
fn starts_with(buff: []const u8, needle: u8) bool {
return buff[0] == needle;
}
fn is_negative(comptime N: type, num: N) bool {
return n < 0;
}
pub fn digits10(comptime N: type, n: N) usize {
if (comptime is_signed(N)) {
const nbits = comptime bitcount(N);
const unsigned_friend = @IntType(false, nbits);
if (is_negative(N, n)) {
return digits10(unsigned_friend, @intCast(unsigned_friend, n * -1));
}
else {
return digits10(unsigned_friend, @intCast(unsigned_friend, n));
}
}
comptime var digits = 1;
comptime var check = 10;
inline while (check <= @maxValue(N)) : ({check *= 10; digits += 1;}) {
if (n < check) {
return digits;
}
}
return digits;
}
const ParseError = error {
/// The input had a byte that was not a digit
InvalidCharacter,
/// The result cannot fit in the type specified
Overflow,
};
/// Returns a slice containing all the multiple powers of 10 that fit in the integer type `N`.
pub fn pow10array(comptime N: type) []N {
comptime var multiple_of_ten: N = 1;
comptime var table_size = comptime digits10(N, @maxValue(N));
comptime var counter = 0;
inline while(counter + 1 < table_size): ({counter += 1;}) {
multiple_of_ten *= 10;
}
// generate table
comptime var table: [table_size] N = undefined;
inline for(table) |*num| {
num.* = multiple_of_ten;
multiple_of_ten /= 10;
}
return table[0..];
}
/// Converts a byte-slice into the integer type `N`.
/// if the byte-slice contains a digit that is not valid, an error is returned.
/// An empty slice returns 0.
pub fn atoi(comptime N: type, buf: []const u8) ParseError!N {
if (comptime is_signed(N)) {
const nbits = comptime bitcount(N);
const unsigned_friend = @IntType(false, nbits);
if (starts_with(buf, '-')) {
return -@intCast(N, try atoi(unsigned_friend, buf[1..]));
}
else {
return @intCast(N, try atoi(unsigned_friend, buf));
}
}
comptime var table = comptime pow10array(N);
if (buf.len > table.len) {
return ParseError.Overflow;
}
var bytes = buf;
var result: N = 0;
var len = buf.len;
var idx = table.len - len;
while (len >= 4) {
comptime var UNROLL_IDX = 0;
comptime var UNROLL_MAX = 4;
// unroll
inline while(UNROLL_IDX < UNROLL_MAX): ({UNROLL_IDX += 1;}) {
const r1 = bytes[UNROLL_IDX] -% 48;
if (r1 > 9) {
return ParseError.InvalidCharacter;
}
//@NOTE: 30-10-2018
// It doesn't matter using a partial_result array,
// and then updating the result by 4 at a time. The assembly is the same with --release-fast,
// and this is just easier to read.
result = result +% r1 * table[idx + UNROLL_IDX];
}
len -= 4;
idx += 4;
bytes = bytes[4..];
}
for (bytes) |byte, offset| {
const r = byte -% 48;
if (r > 9) {
return ParseError.InvalidCharacter;
}
const d = r * table[idx + offset];
result = result +% d;
}
return result;
}
fn pow(base: usize, exp: usize) usize {
var x: usize = base;
var i: usize = 1;
while (i < exp) : (i += 1) {
x *= base;
}
return x;
}
pub fn itoa(comptime N: type, n: N, buff: []u8) void {
comptime var UNROLL_MAX: usize = 4;
comptime var DIV_CONST: usize = comptime pow(10, UNROLL_MAX);
var num = n;
var len = buff.len;
while(len >= UNROLL_MAX): (num = @divTrunc(num, DIV_CONST)) {
comptime var DIV10: N = 1;
comptime var CURRENT: usize = 0;
// Write digits backwards into the buffer
inline while(CURRENT != UNROLL_MAX): ({CURRENT += 1; DIV10 *= 10;}) {
var q = @divTrunc(num, DIV10);
var r = @intCast(u8, @rem(q, 10)) + 48;
buff[len - CURRENT - 1] = r;
}
len -= UNROLL_MAX;
}
// On an empty buffer, this will wrapparoo to 0xfffff
len -%= 1;
// Stops at 0xfffff
while(len != @maxValue(usize)): (len -%= 1) {
var q: N = @divTrunc(num, 10);
var r: u8 = @intCast(u8, @rem(num, 10)) + 48;
buff[len] = r;
num = q;
}
} | zig/week1/parse.zig |
const std = @import("std");
const math = @import("math.zig");
pub fn merge(a: math.sphereBound, b: math.sphereBound) math.sphereBound {
const dist: f32 = math.Vec3.norm(a.pos - b.pos);
if (dist + a.r <= b.r)
return b;
if (dist + b.r <= a.r)
return a;
const r: f32 = (a.r + b.r + dist) / 2.0;
const pos: math.vec3 = a.pos + (b.pos - a.pos) * @splat(3, (r - a.r) / dist);
return .{ .pos = pos, .r = r };
}
pub fn intersect(a: math.sphereBound, b: math.sphereBound) math.sphereBound {
const dist: f32 = math.Vec3.norm(a.pos - b.pos);
if (dist + a.r <= b.r)
return a;
if (dist + b.r <= a.r)
return b;
if (dist >= a.r + b.r)
return .{ .pos = math.Vec3.zeros(), .r = 0.0 };
var inter_c: math.vec3 = (a.pos + b.pos) * @splat(3, @as(f32, 0.5));
inter_c += @splat(3, (a.r * a.r - b.r * b.r) / (2 * dist * dist)) * (b.pos - a.pos);
const offset: math.vec3 = (b.pos - a.pos) * @splat(3, 0.5 * std.math.sqrt(2 * (a.r * a.r + b.r * b.r) / (dist * dist) - (std.math.pow(f32, a.r * a.r - b.r * b.r, 2) / std.math.pow(f32, dist, 4)) - 1));
return .{
.pos = inter_c,
.r = math.Vec3.norm(offset),
};
}
pub fn subtract(a: math.sphereBound, b: math.sphereBound) math.sphereBound {
const dist: f32 = math.Vec3.norm(a.pos - b.pos);
if (dist + a.r <= b.r)
return b;
if (dist + b.r <= a.r)
return a;
var inter_c: math.vec3 = (a.pos + b.pos) * @splat(3, @as(f32, 0.5));
inter_c += @splat(3, (a.r * a.r - b.r * b.r) / (2 * dist * dist)) * (b.pos - a.pos);
const offset: math.vec3 = (b.pos - a.pos) * @splat(3, 0.5 * std.math.sqrt(2 * (a.r * a.r + b.r * b.r) / (dist * dist) - (std.math.pow(f32, a.r * a.r - b.r * b.r, 2) / std.math.pow(f32, dist, 4)) - 1));
return .{
.pos = inter_c,
.r = @maximum(math.Vec3.norm(offset), math.Vec3.norm(inter_c - a.pos) + a.r),
};
}
pub fn from3Points(p0: math.vec3, p1: math.vec3, p2: math.vec3) math.sphereBound {
const a: math.vec3 = p2 - p1;
const b: math.vec3 = p0 - p2;
const c: math.vec3 = p1 - p0;
const u: f32 = math.Vec3.dot(a, a) * math.Vec3.dot(c, b);
const v: f32 = math.Vec3.dot(b, b) * math.Vec3.dot(c, a);
const w: f32 = math.Vec3.dot(c, c) * math.Vec3.dot(b, a);
const pos: math.vec3 = (p0 * @splat(3, u) + p1 * @splat(3, v) + p2 * @splat(3, w)) / @splat(3, u + v + w);
return .{
.pos = pos,
.r = math.Vec3.norm(p0 - pos),
};
} | src/math/sphere_bound.zig |
const c = @cImport({
@cInclude("aes.h");
@cInclude("zip.h");
});
const std = @import("std");
const ascii = std.ascii;
const base64 = std.base64;
const fmt = std.fmt;
const fs = std.fs;
const heap = std.heap;
const io = std.io;
const log = std.log;
const math = std.math;
const mem = std.mem;
const process = std.process;
const unicode = std.unicode;
const content_folder = "content";
pub fn main() !void {
var global_arena_state = heap.ArenaAllocator.init(heap.page_allocator);
defer global_arena_state.deinit();
const global_arena = global_arena_state.allocator();
const args = try process.argsAlloc(global_arena);
var jng_dir = if (args.len >= 2)
try fs.cwd().openDir(args[1], .{})
else
fs.cwd();
defer jng_dir.close();
if (jng_dir.access(content_folder, .{})) {
log.warn(
\\The 'content' folder already exists.
\\Type 'yes' and press enter if you want me to override it.
, .{});
var buf: [32]u8 = undefined;
const answer_len = try io.getStdIn().read(&buf);
const answer = mem.trim(u8, buf[0..answer_len], " \t\r\n");
if (!ascii.eqlIgnoreCase(answer, "yes")) {
log.info("I take '{s}' as a no. Exiting...", .{answer});
return;
}
try jng_dir.deleteTree(content_folder);
} else |err| switch (err) {
error.FileNotFound => {},
else => |e| return e,
}
try jng_dir.makeDir(content_folder);
var content_buf: [fs.MAX_PATH_BYTES:0]u8 = undefined;
const content_path = try jng_dir.realpath(content_folder, &content_buf);
content_buf[content_path.len] = 0;
var content_zip_buf: [fs.MAX_PATH_BYTES]u8 = undefined;
const content_zip_path = try fmt.bufPrintZ(&content_zip_buf, "{s}.zip", .{content_path});
log.info("Extracting 'content.zip'...", .{});
const res = c.zip_extract(content_zip_path.ptr, content_path.ptr, null, null);
if (res < 0) {
log.err("Failed to extract '{s}'", .{content_zip_path});
log.info("Make sure you are running me in the Jets'n'Guns 2 folder or passing that " ++
"folder to me as input.", .{});
return;
}
log.info("Decrypting files...", .{});
try walkContentFolder(std.heap.page_allocator, jng_dir, content_folder);
try jng_dir.writeFile("content.txt",
\\dir = content
\\// zip = content.zip
\\
);
}
fn walkContentFolder(allocator: mem.Allocator, parent: fs.Dir, folder: []const u8) anyerror!void {
var dir = try parent.openDir(folder, .{ .iterate = true });
var it = dir.iterate();
while (try it.next()) |entry| switch (entry.kind) {
.Directory => try walkContentFolder(allocator, dir, entry.name),
.File => {
const file = try dir.openFile(entry.name, .{ .mode = .read_write });
defer file.close();
// Only files starting with the header are encrypted
const header = "JnGeNc\r\n";
var header_buf: [header.len]u8 = undefined;
const len = try file.readAll(&header_buf);
if (!mem.eql(u8, mem.sliceAsBytes(header), header_buf[0..len]))
continue;
var arena_state = heap.ArenaAllocator.init(allocator);
defer arena_state.deinit();
const arena = arena_state.allocator();
const content = try file.readToEndAlloc(arena, math.maxInt(usize));
const decrypted = try decryptLines(arena, content);
try file.seekTo(0);
try file.writeAll(decrypted);
try file.setEndPos(decrypted.len);
},
else => {},
};
}
fn decryptLines(allocator: mem.Allocator, in: []const u8) ![]u8 {
var out = try std.ArrayListUnmanaged(u8).initCapacity(allocator, in.len);
errdefer out.deinit(allocator);
var decode_buf = std.ArrayListAligned(u8, 2).init(allocator);
defer decode_buf.deinit();
var it = mem.tokenize(u8, in, "\r\n");
while (it.next()) |line| {
const len = try base64.standard.Decoder.calcSizeForSlice(line);
try decode_buf.resize(len);
try base64.standard.Decoder.decode(decode_buf.items, line);
const decrypted = decryptInPlace(decode_buf.items);
const l = try unicode.utf16leToUtf8(
decrypted,
mem.bytesAsSlice(u16, decode_buf.items[0..decrypted.len]),
);
out.appendSliceAssumeCapacity(decrypted[0..l]);
out.appendAssumeCapacity('\n');
}
return out.toOwnedSlice(allocator);
}
const key = [_]u8{
0x7A, 0xE8, 0x79, 0xD4,
0x62, 0x33, 0x7D, 0xDE,
0xB9, 0x6E, 0xF4, 0x4A,
0x31, 0x38, 0x52, 0xBD,
0xF7, 0x85, 0xDB, 0x71,
0x9A, 0xD5, 0x48, 0x90,
0xE8, 0xDD, 0x93, 0x7C,
0xD5, 0x22, 0xDA, 0xB9,
};
const iv = [_]u8{
0x01, 0x14, 0x4C, 0xB9,
0xEC, 0x91, 0xE1, 0xDF,
0x48, 0xD1, 0xD1, 0xDF,
0x9B, 0xFE, 0x18, 0xD3,
};
fn decryptInPlace(bytes: []u8) []u8 {
if (bytes.len == 0)
return bytes;
var aes: c.AES_ctx = undefined;
c.AES_init_ctx_iv(&aes, &key, &iv);
c.AES_CBC_decrypt_buffer(&aes, bytes.ptr, bytes.len);
// Remove PKCS7 padding
var i: usize = 1;
const count = bytes[bytes.len - 1];
while (i != count) : (i += 1) {
if (i == bytes.len)
return bytes;
if (bytes[bytes.len - (i + 1)] != count)
return bytes;
}
return bytes[0 .. bytes.len - i];
} | src/main.zig |
// How input is expected to work:
//
// A window implementation maps physical keys through to a bitset of virtual keys that the
// engine can understand. This occurs every frame. Next, these virtual keys are matched against
// the existing movement state of the engine and mapped to specific movement and rotation
// accordingly.
//
// Window -> Returns BitSet(VirtualKey)
// Engine -> Maps BitSet(VirtualKey) to input.Actions
// Engine -> Performs game logic, as per input.Actions
const std = @import("std");
const zs = @import("zstack.zig");
const BitSet = zs.BitSet;
/// Virtual key input returned by a frontend.
pub const VirtualKey = enum(u32) {
Up = 0x01,
Down = 0x02,
Left = 0x04,
Right = 0x08,
RotateLeft = 0x10,
RotateRight = 0x20,
RotateHalf = 0x40,
Hold = 0x80,
Start = 0x100,
Restart = 0x200,
Quit = 0x400,
pub fn fromIndex(i: usize) VirtualKey {
std.debug.assert(i < @memberCount(VirtualKey));
return @intToEnum(VirtualKey, (u32(1) << @intCast(u5, i)));
}
};
pub const KeyBindings = struct {
Up: Key = .space,
Down: Key = .down,
Left: Key = .left,
Right: Key = .right,
RotateLeft: Key = .z,
RotateRight: Key = .x,
RotateHalf: Key = .s,
Hold: Key = .c,
Start: Key = .enter,
Restart: Key = .rshift,
Quit: Key = .q,
_scratch: [@memberCount(VirtualKey)]Key = undefined,
// Only valid until the next call to entries, don't keep this slice around.
pub fn entries(self: *KeyBindings) []const Key {
// Must match order of VirtualKey
self._scratch = [_]Key{
self.Up,
self.Down,
self.Left,
self.Right,
self.RotateLeft,
self.RotateRight,
self.RotateHalf,
self.Hold,
self.Start,
self.Restart,
self.Quit,
};
return self._scratch;
}
};
pub const Key = enum {
space,
enter,
tab,
right,
left,
down,
up,
rshift,
lshift,
capslock,
comma,
period,
slash,
semicolon,
apostrophe,
lbracket,
rbracket,
backslash,
a,
b,
c,
d,
e,
f,
g,
h,
i,
j,
k,
l,
m,
n,
o,
p,
q,
r,
s,
t,
u,
v,
w,
x,
y,
z,
};
/// Specific game actions for the engine.
pub const Actions = struct {
pub const Extra = enum(u32) {
// TODO: Enum set size determined by membercount and not min/max values in the set.
// Make an issue.
HardDrop = 0x01,
Hold = 0x02,
Lock = 0x04,
Quit = 0x08,
Restart = 0x10,
Move = 0x20,
Rotate = 0x40,
FinesseRotate = 0x80,
FinesseMove = 0x100,
};
/// Relative rotation action, e.g. Clockwise, Anticlockwise or Half.
rotation: ?zs.Rotation,
/// Left-right movemment in the x-axis (+ is right, - is left)
movement: i8,
/// Downwards movement in the y-axis (fractional, see fixed-point).
gravity: zs.uq8p24,
/// Extra actions to apply to the piece.
extra: BitSet(Extra),
/// All keys that are currently pressed this frame.
keys: BitSet(VirtualKey),
/// The new keys that were pressed this frame and not last.
new_keys: BitSet(VirtualKey),
// TODO: Don't need an init? Just make the virtualKeys map a member of Actions and construct
// directly. Keeps it a bit simpler since internally the engine doesn't actually care
// besides a few counters.
pub fn init() Actions {
return Actions{
.rotation = null,
.movement = 0,
.gravity = zs.uq8p24.init(0, 0),
.extra = BitSet(Extra).init(),
.keys = BitSet(VirtualKey).init(),
.new_keys = BitSet(VirtualKey).init(),
};
}
}; | src/input.zig |
const std = @import("std");
const testing = std.testing;
const input_file = "input05.txt";
const Seat = struct {
row: u32,
column: u32,
fn fromDescription(str: []const u8) !Seat {
if (str.len != 10) return error.WrongLength;
const row_desc = str[0..7];
const column_desc = str[7..10];
const row = blk: {
var hi: u32 = 127;
var lo: u32 = 0;
for (row_desc) |c| {
const mid = (hi + lo) / 2;
switch (c) {
'F' => hi = mid,
'B' => lo = mid + 1,
else => return error.InvalidCharacter,
}
}
break :blk hi;
};
const column = blk: {
var hi: u32 = 7;
var lo: u32 = 0;
for (column_desc) |c| {
const mid = (hi + lo) / 2;
switch (c) {
'L' => hi = mid,
'R' => lo = mid + 1,
else => return error.InvalidCharacter,
}
}
break :blk hi;
};
return Seat{
.row = row,
.column = column,
};
}
fn id(self: Seat) u32 {
return self.row * 8 + self.column;
}
};
test "from description" {
try testing.expectEqual(Seat{ .row = 44, .column = 5 }, try Seat.fromDescription("FBFBBFFRLR"));
try testing.expectEqual(Seat{ .row = 70, .column = 7 }, try Seat.fromDescription("BFFFBBFRRR"));
try testing.expectEqual(Seat{ .row = 14, .column = 7 }, try Seat.fromDescription("FFFBBBFRRR"));
try testing.expectEqual(Seat{ .row = 102, .column = 4 }, try Seat.fromDescription("BBFFBBFRLL"));
}
pub fn main() !void {
var gpa = std.heap.GeneralPurposeAllocator(.{}){};
defer _ = gpa.deinit();
const allocator = &gpa.allocator;
var file = try std.fs.cwd().openFile(input_file, .{});
defer file.close();
var seat_ids = std.ArrayList(u32).init(allocator);
defer seat_ids.deinit();
const reader = file.reader();
var buf: [1024]u8 = undefined;
while (try reader.readUntilDelimiterOrEof(&buf, '\n')) |line| {
const seat = try Seat.fromDescription(line);
const seat_id = seat.id();
try seat_ids.append(seat_id);
}
std.sort.sort(u32, seat_ids.items, {}, comptime std.sort.asc(u32));
const seat_id = for (seat_ids.items[0 .. seat_ids.items.len - 2]) |id, i| {
if (seat_ids.items[i + 1] == id + 2) break id + 1;
} else return error.SeatNotFound;
std.debug.print("my seat id: {}\n", .{seat_id});
} | src/05_2.zig |
const std = @import("std");
var a: *std.mem.Allocator = undefined;
const stdout = std.io.getStdOut().writer(); //prepare stdout to write in
// Problem-specific
const ROW_BITSIZE: u8 = 7;
const COLUMN_BITSIZE: u8 = 3;
test "aoc input 0" {
// FBFBBFFRLR: row 44, col 5, id 357
const t = "FBFBBFFRLR";
var b = t.*;
std.testing.expect(run(&b) == 357);
}
test "aoc input 1" {
// BFFFBBFRRR: row 70, column 7, seat ID 567.
const t = "BFFFBBFRRR";
var b = t.*;
std.testing.expect(run(&b) == 567);
}
test "aoc input 2" {
// FFFBBBFRRR: row 14, column 7, seat ID 119.\
const t = "FFFBBBFRRR";
var b = t.*;
std.testing.expect(run(&b) == 119);
}
test "aoc input 3" {
// BBFFBBFRLL: row 102, column 4, seat ID 820.
const t = "BBFFBBFRLL";
var b = t.*;
std.testing.expect(run(&b) == 820);
}
test "aoc all" {
const t =
\\FBFBBFFRLR
\\BFFFBBFRRR
\\FFFBBBFRRR
\\BBFFBBFRLL
;
var b = t.*;
std.testing.expect(run(&b) == 820);
}
fn run(input: [:0]u8) u32 {
var max_id: u32 = 0;
var cur_id: u32 = 0;
var row: u8 = 0;
var column: u8 = 0;
var all_lines = std.mem.tokenize(input, "\n");
while (all_lines.next()) |line| {
for (line[0..ROW_BITSIZE]) |char, i| {
if (char == 'B') {
row |= @as(u8, 1) << @intCast(u3, ROW_BITSIZE - i - 1);
}
}
for (line[(ROW_BITSIZE)..(ROW_BITSIZE + COLUMN_BITSIZE)]) |char, i| {
if (char == 'R') {
column |= @as(u8, 1) << @intCast(u3, COLUMN_BITSIZE - i - 1);
}
}
cur_id = @as(u32, row) * 8 + column;
//std.debug.print("{}: row {} col {} ID {}\n", .{ line, row, column, cur_id });
if (cur_id > max_id) {
max_id = cur_id;
}
cur_id = 0;
row = 0;
column = 0;
}
return max_id;
}
pub fn main() !void {
var arena = std.heap.ArenaAllocator.init(std.heap.page_allocator); // create memory allocator for strings
defer arena.deinit(); // clear memory
var arg_it = std.process.args();
_ = arg_it.skip(); // skip over exe name
a = &arena.allocator; // get ref to allocator
const input: [:0]u8 = try (arg_it.next(a)).?; // get the first argument
const start: i128 = std.time.nanoTimestamp(); // start time
const answer = run(input); // compute answer
const elapsed_nano: f128 = @intToFloat(f128, std.time.nanoTimestamp() - start);
const elapsed_milli: f64 = @floatCast(f64, @divFloor(elapsed_nano, 1_000_000));
try stdout.print("_duration:{d}\n{}\n", .{ elapsed_milli, answer }); // emit actual lines parsed by AOC
} | day-05/part-1/lelithium.zig |
pub const HealthComp = @import("ComponentData/HealthComp.zig").HealthComp;
pub const InputComp = @import("ComponentData/InputComp.zig").InputComp;
pub const MovementComp = @import("ComponentData/MovementComp.zig").MovementComp;
pub const SceneComp = @import("ComponentData/SceneComp.zig").SceneComp;
pub const TransformComp = @import("ComponentData/TransformComp.zig").TransformComp;
pub const PhysicsComp = @import("ComponentData/PhysicsComp.zig").PhysicsComp;
const std = @import("std");
const ArrayList = std.ArrayList;
const allocator = std.heap.page_allocator;
pub const compTypeEnumCount: comptime u32 = @typeInfo(EComponentType).Enum.fields.len;
pub const EComponentType = enum {
Health,
Input,
Movement,
Scene,
Transform,
Physics,
};
//TODO
// There should be some sanity checking/assurance that we're fetching the component
// of a living entity and not one that has died, with another entity back-filling the
// component data in the array
fn ComponentDataPair(comptime compType: type) type {
return struct {
m_ownerEid: u32,
m_data: compType = compType{}, // components must have defaults
};
}
fn ComponentDataArray(comptime compType: type) type {
return struct {
m_compData: ArrayList(ComponentDataPair(compType)) = ArrayList(ComponentDataPair(compType)).init(allocator),
pub fn GetComp(self: *ComponentDataArray(compType), id: u16) ?*compType {
if (id >= self.m_compData.len) {
return null;
} else {
return &self.m_compData.items[id].m_data;
}
}
pub fn GetOwnerId(self: *ComponentDataArray(compType), id: u16) ?u32 {
if (id >= self.m_compData.len) {
return null;
} else {
return self.m_compData.items[id].m_ownerEid;
}
}
pub fn AddComp(self: *ComponentDataArray(compType), owner: u32) u16 {
self.m_compData.append(ComponentDataPair(compType){ .m_ownerEid = owner }) catch |err| {
@panic("Could not add new component to array.");
};
const addedCompId = @intCast(u16, self.m_compData.len - 1);
//TODO add compId to entity's m_componentIds
return addedCompId;
}
};
}
pub const ComponentManager = struct {
m_healthCompData: ComponentDataArray(HealthComp) = ComponentDataArray(HealthComp){},
m_inputCompData: ComponentDataArray(InputComp) = ComponentDataArray(InputComp){},
m_movementCompData: ComponentDataArray(MovementComp) = ComponentDataArray(MovementComp){},
m_sceneCompData: ComponentDataArray(SceneComp) = ComponentDataArray(SceneComp){},
m_transformCompData: ComponentDataArray(TransformComp) = ComponentDataArray(TransformComp){},
m_physicsCompData: ComponentDataArray(PhysicsComp) = ComponentDataArray(PhysicsComp){},
pub fn Initialize() ComponentManager {
return ComponentManager{};
}
fn SwitchOnCompType(self: *ComponentManager, comptime compType: type) *ComponentDataArray(compType) {
return switch (compType) {
HealthComp => &self.m_healthCompData,
InputComp => &self.m_inputCompData,
MovementComp => &self.m_movementCompData,
SceneComp => &self.m_sceneCompData,
TransformComp => &self.m_transformCompData,
PhysicsComp => &self.m_physicsCompData,
else => @compileError("Component type not known."),
};
}
//TODO const?
pub fn GetComponent(self: *ComponentManager, comptime compType: type, compID: u16) ?*compType {
return self.SwitchOnCompType(compType).GetComp(compID);
}
pub fn GetComponentOwnerId(self: *ComponentManager, comptime compType: type, compID: u16) ?u32 {
return self.SwitchOnCompType(compType).GetOwnerId(compID);
}
// returns componentID
pub fn AddComponent(self: *ComponentManager, comptime compType: type, ownerEid: u32) u16 {
return self.SwitchOnCompType(compType).AddComp(ownerEid);
}
}; | src/game/ComponentData.zig |
const std = @import("std");
const Arena = std.heap.ArenaAllocator;
const expect = std.testing.expect;
const expectEqual = std.testing.expectEqual;
const expectEqualStrings = std.testing.expectEqualStrings;
const yeti = @import("yeti");
const initCodebase = yeti.initCodebase;
const tokenize = yeti.tokenize;
const parse = yeti.parse;
const analyzeSemantics = yeti.analyzeSemantics;
const codegen = yeti.codegen;
const printWasm = yeti.printWasm;
const components = yeti.components;
const literalOf = yeti.query.literalOf;
const typeOf = yeti.query.typeOf;
const parentType = yeti.query.parentType;
const valueType = yeti.query.valueType;
const Entity = yeti.ecs.Entity;
const MockFileSystem = yeti.FileSystem;
test "parse function with return type inference" {
var arena = Arena.init(std.heap.page_allocator);
defer arena.deinit();
var codebase = try initCodebase(&arena);
const module = try codebase.createEntity(.{});
const code =
\\start() {
\\ 0
\\}
;
var tokens = try tokenize(module, code);
try parse(module, &tokens);
const top_level = module.get(components.TopLevel);
const overloads = top_level.findString("start").get(components.Overloads).slice();
try expectEqual(overloads.len, 1);
const start = overloads[0];
try expect(!start.contains(components.ReturnTypeAst));
const body = overloads[0].get(components.Body).slice();
try expectEqual(body.len, 1);
const zero = body[0];
try expectEqual(zero.get(components.AstKind), .int);
try expectEqualStrings(literalOf(zero), "0");
}
test "analyze semantics of function with return type inference int literal" {
var arena = Arena.init(std.heap.page_allocator);
defer arena.deinit();
var codebase = try initCodebase(&arena);
const builtins = codebase.get(components.Builtins);
var fs = try MockFileSystem.init(&arena);
_ = try fs.newFile("foo.yeti",
\\start() {
\\ 0
\\}
);
_ = try analyzeSemantics(codebase, fs, "foo.yeti");
const module = try analyzeSemantics(codebase, fs, "foo.yeti");
const top_level = module.get(components.TopLevel);
const start = top_level.findString("start").get(components.Overloads).slice()[0];
try expectEqualStrings(literalOf(start.get(components.Module).entity), "foo");
try expectEqualStrings(literalOf(start.get(components.Name).entity), "start");
try expectEqual(start.get(components.Parameters).len(), 0);
try expectEqual(start.get(components.ReturnType).entity, builtins.I32);
const body = start.get(components.Body).slice();
try expectEqual(body.len, 1);
const zero = body[0];
try expectEqual(zero.get(components.AstKind), .int);
try expectEqual(typeOf(zero), builtins.I32);
try expectEqualStrings(literalOf(zero), "0");
}
test "analyze semantics of function with return type inference float literal" {
var arena = Arena.init(std.heap.page_allocator);
defer arena.deinit();
var codebase = try initCodebase(&arena);
const builtins = codebase.get(components.Builtins);
var fs = try MockFileSystem.init(&arena);
_ = try fs.newFile("foo.yeti",
\\start() {
\\ 0.5
\\}
);
_ = try analyzeSemantics(codebase, fs, "foo.yeti");
const module = try analyzeSemantics(codebase, fs, "foo.yeti");
const top_level = module.get(components.TopLevel);
const start = top_level.findString("start").get(components.Overloads).slice()[0];
try expectEqualStrings(literalOf(start.get(components.Module).entity), "foo");
try expectEqualStrings(literalOf(start.get(components.Name).entity), "start");
try expectEqual(start.get(components.Parameters).len(), 0);
try expectEqual(start.get(components.ReturnType).entity, builtins.F32);
const body = start.get(components.Body).slice();
try expectEqual(body.len, 1);
const zero = body[0];
try expectEqual(zero.get(components.AstKind), .float);
try expectEqual(typeOf(zero), builtins.F32);
try expectEqualStrings(literalOf(zero), "0.5");
}
test "analyze semantics of function with return type inference character literal" {
var arena = Arena.init(std.heap.page_allocator);
defer arena.deinit();
var codebase = try initCodebase(&arena);
const builtins = codebase.get(components.Builtins);
var fs = try MockFileSystem.init(&arena);
_ = try fs.newFile("foo.yeti",
\\start() {
\\ 'h'
\\}
);
_ = try analyzeSemantics(codebase, fs, "foo.yeti");
const module = try analyzeSemantics(codebase, fs, "foo.yeti");
const top_level = module.get(components.TopLevel);
const start = top_level.findString("start").get(components.Overloads).slice()[0];
try expectEqualStrings(literalOf(start.get(components.Module).entity), "foo");
try expectEqualStrings(literalOf(start.get(components.Name).entity), "start");
try expectEqual(start.get(components.Parameters).len(), 0);
try expectEqual(start.get(components.ReturnType).entity, builtins.U8);
const body = start.get(components.Body).slice();
try expectEqual(body.len, 1);
const h = body[0];
try expectEqual(h.get(components.AstKind), .int);
try expectEqual(typeOf(h), builtins.U8);
try expectEqualStrings(literalOf(h), "104");
} | src/tests/test_return_type_inference.zig |
const std = @import("std");
const Allocator = std.mem.Allocator;
const command = @import("./command.zig");
const ppack = @import("./parser.zig");
const Parser = ppack.Parser;
const ParseResult = ppack.ParseResult;
const iterators = @import("./iterators.zig");
const expect = std.testing.expect;
const alloc = std.testing.allocator;
fn run(cmd: *command.Command, items: []const []const u8) !ParseResult {
var it = iterators.StringSliceIterator{
.items = items,
};
var parser = try Parser(iterators.StringSliceIterator).init(cmd, it, alloc);
var result = try parser.parse();
parser.deinit();
return result;
}
fn dummy_action(_: []const []const u8) !void {}
test "long option" {
var opt = command.Option{
.long_name = "aa",
.help = "option aa",
.value = command.OptionValue{ .string = null },
};
var cmd = command.Command{
.name = "abc",
.options = &.{&opt},
.help = "help",
.action = dummy_action,
};
_ = try run(&cmd, &.{ "cmd", "--aa", "val" });
try expect(std.mem.eql(u8, opt.value.string.?, "val"));
_ = try run(&cmd, &.{ "cmd", "--aa=bb" });
try expect(std.mem.eql(u8, opt.value.string.?, "bb"));
}
test "short option" {
var opt = command.Option{
.long_name = "aa",
.short_alias = 'a',
.help = "option aa",
.value = command.OptionValue{ .string = null },
};
var cmd = command.Command{
.name = "abc",
.options = &.{&opt},
.help = "help",
.action = dummy_action,
};
_ = try run(&cmd, &.{ "abc", "-a", "val" });
try expect(std.mem.eql(u8, opt.value.string.?, "val"));
_ = try run(&cmd, &.{ "abc", "-a=bb" });
try expect(std.mem.eql(u8, opt.value.string.?, "bb"));
}
test "concatenated aliases" {
var bb = command.Option{
.long_name = "bb",
.short_alias = 'b',
.help = "option bb",
.value = command.OptionValue{ .bool = false },
};
var opt = command.Option{
.long_name = "aa",
.short_alias = 'a',
.help = "option aa",
.value = command.OptionValue{ .string = null },
};
var cmd = command.Command{
.name = "abc",
.options = &.{ &bb, &opt },
.help = "help",
.action = dummy_action,
};
_ = try run(&cmd, &.{ "abc", "-ba", "val" });
try expect(std.mem.eql(u8, opt.value.string.?, "val"));
try expect(bb.value.bool);
}
test "int and float" {
var aa = command.Option{
.long_name = "aa",
.help = "option aa",
.value = command.OptionValue{ .int = null },
};
var bb = command.Option{
.long_name = "bb",
.help = "option bb",
.value = command.OptionValue{ .float = null },
};
var cmd = command.Command{
.name = "abc",
.options = &.{ &aa, &bb },
.help = "help",
.action = dummy_action,
};
_ = try run(&cmd, &.{ "abc", "--aa=34", "--bb", "15.25" });
try expect(aa.value.int.? == 34);
try expect(bb.value.float.? == 15.25);
}
test "string list" {
var aa = command.Option{
.long_name = "aa",
.short_alias = 'a',
.help = "option aa",
.value = command.OptionValue{ .string_list = null },
};
var cmd = command.Command{
.name = "abc",
.options = &.{&aa},
.help = "help",
.action = dummy_action,
};
_ = try run(&cmd, &.{ "abc", "--aa=a1", "--aa", "a2", "-a", "a3", "-a=a4" });
try expect(aa.value.string_list.?.len == 4);
try expect(std.mem.eql(u8, aa.value.string_list.?[0], "a1"));
try expect(std.mem.eql(u8, aa.value.string_list.?[1], "a2"));
try expect(std.mem.eql(u8, aa.value.string_list.?[2], "a3"));
try expect(std.mem.eql(u8, aa.value.string_list.?[3], "a4"));
alloc.free(aa.value.string_list.?);
} | src/tests.zig |
const std = @import("std");
const Allocator = std.mem.Allocator;
pub fn targetTriple(allocator: *Allocator, target: std.Target) ![]u8 {
const llvm_arch = switch (target.cpu.arch) {
.arm => "arm",
.armeb => "armeb",
.aarch64 => "aarch64",
.aarch64_be => "aarch64_be",
.aarch64_32 => "aarch64_32",
.arc => "arc",
.avr => "avr",
.bpfel => "bpfel",
.bpfeb => "bpfeb",
.hexagon => "hexagon",
.mips => "mips",
.mipsel => "mipsel",
.mips64 => "mips64",
.mips64el => "mips64el",
.msp430 => "msp430",
.powerpc => "powerpc",
.powerpc64 => "powerpc64",
.powerpc64le => "powerpc64le",
.r600 => "r600",
.amdgcn => "amdgcn",
.riscv32 => "riscv32",
.riscv64 => "riscv64",
.sparc => "sparc",
.sparcv9 => "sparcv9",
.sparcel => "sparcel",
.s390x => "s390x",
.tce => "tce",
.tcele => "tcele",
.thumb => "thumb",
.thumbeb => "thumbeb",
.i386 => "i386",
.x86_64 => "x86_64",
.xcore => "xcore",
.nvptx => "nvptx",
.nvptx64 => "nvptx64",
.le32 => "le32",
.le64 => "le64",
.amdil => "amdil",
.amdil64 => "amdil64",
.hsail => "hsail",
.hsail64 => "hsail64",
.spir => "spir",
.spir64 => "spir64",
.kalimba => "kalimba",
.shave => "shave",
.lanai => "lanai",
.wasm32 => "wasm32",
.wasm64 => "wasm64",
.renderscript32 => "renderscript32",
.renderscript64 => "renderscript64",
.ve => "ve",
.spu_2 => return error.LLVMBackendDoesNotSupportSPUMarkII,
};
// TODO Add a sub-arch for some architectures depending on CPU features.
const llvm_os = switch (target.os.tag) {
.freestanding => "unknown",
.ananas => "ananas",
.cloudabi => "cloudabi",
.dragonfly => "dragonfly",
.freebsd => "freebsd",
.fuchsia => "fuchsia",
.ios => "ios",
.kfreebsd => "kfreebsd",
.linux => "linux",
.lv2 => "lv2",
.macos => "macosx",
.netbsd => "netbsd",
.openbsd => "openbsd",
.solaris => "solaris",
.windows => "windows",
.haiku => "haiku",
.minix => "minix",
.rtems => "rtems",
.nacl => "nacl",
.cnk => "cnk",
.aix => "aix",
.cuda => "cuda",
.nvcl => "nvcl",
.amdhsa => "amdhsa",
.ps4 => "ps4",
.elfiamcu => "elfiamcu",
.tvos => "tvos",
.watchos => "watchos",
.mesa3d => "mesa3d",
.contiki => "contiki",
.amdpal => "amdpal",
.hermit => "hermit",
.hurd => "hurd",
.wasi => "wasi",
.emscripten => "emscripten",
.uefi => "windows",
.other => "unknown",
};
const llvm_abi = switch (target.abi) {
.none => "unknown",
.gnu => "gnu",
.gnuabin32 => "gnuabin32",
.gnuabi64 => "gnuabi64",
.gnueabi => "gnueabi",
.gnueabihf => "gnueabihf",
.gnux32 => "gnux32",
.code16 => "code16",
.eabi => "eabi",
.eabihf => "eabihf",
.android => "android",
.musl => "musl",
.musleabi => "musleabi",
.musleabihf => "musleabihf",
.msvc => "msvc",
.itanium => "itanium",
.cygnus => "cygnus",
.coreclr => "coreclr",
.simulator => "simulator",
.macabi => "macabi",
};
return std.fmt.allocPrint(allocator, "{}-unknown-{}-{}", .{ llvm_arch, llvm_os, llvm_abi });
} | src/codegen/llvm.zig |
const std = @import("std");
const c = @import("c.zig");
const shaderc = @import("shaderc.zig");
const Scene = @import("scene.zig").Scene;
pub const AsyncShaderc = struct {
const Self = @This();
alloc: *std.mem.Allocator,
mutex: std.Thread.Mutex,
thread: std.Thread,
cancelled: bool,
device: c.WGPUDeviceId,
scene: Scene,
out: ?c.WGPUShaderModuleId,
pub fn init(scene: Scene, device: c.WGPUDeviceId) Self {
return Self{
.alloc = scene.alloc,
.mutex = std.Thread.Mutex{},
.thread = undefined, // defined in start()
.scene = scene,
.device = device,
.out = null,
.cancelled = false,
};
}
pub fn deinit(self: *Self) void {
self.thread.join();
self.scene.deinit();
}
pub fn start(self: *Self) !void {
// self.thread = try std.Thread.spawn(self, Self.run);
self.thread = try std.Thread.spawn(.{}, Self.run, .{self});
}
fn run(self: *Self) void {
const txt = self.scene.trace_glsl() catch |err| {
std.debug.panic("Failed to generate GLSL: {}\n", .{err});
};
defer self.alloc.free(txt);
const comp_spv = shaderc.build_shader(self.alloc, "rt", txt) catch |err| {
std.debug.panic("Failed to build shader: {}\n", .{err});
};
defer self.alloc.free(comp_spv);
// The fragment shader is pre-compiled in a separate thread, because
// it could take a while.
const comp_shader = c.wgpu_device_create_shader_module(
self.device,
&(c.WGPUShaderModuleDescriptor){
.label = "compiled comp shader",
.bytes = comp_spv.ptr,
.length = comp_spv.len,
.flags = c.WGPUShaderFlags_VALIDATION,
},
);
const lock = self.mutex.acquire();
defer lock.release();
self.out = comp_shader;
}
pub fn check(self: *Self) ?c.WGPUShaderModuleId {
const lock = self.mutex.acquire();
defer lock.release();
// Steal the value from out
const out = self.out;
if (out != null) {
self.out = null;
}
return out;
}
}; | src/async_shaderc.zig |
const os = @import("root").os;
const Bitset = os.lib.bitset.Bitset;
const range = os.lib.range.range;
const assert = @import("std").debug.assert;
const paging = os.memory.paging;
const page_size = os.platform.paging.page_sizes[0];
// O(1) worst case alloc() and free() buddy allocator I came up with (idk if anyone has done this before)
const free_node = struct {
next: ?*@This() = null,
prev: ?*@This() = null,
pub fn remove(self: *@This()) void {
assert(self.prev != null);
if (self.next != null)
self.next.?.prev = self.prev;
self.prev.?.next = self.next;
}
};
pub fn buddy_alloc(comptime allocator_size: usize, comptime minsize: usize) type {
var curr_size = minsize;
var allocator_levels = 1;
while (curr_size != allocator_size) {
allocator_levels += 1;
curr_size <<= 1;
}
const num_entries_at_bottom_level = allocator_size / minsize;
const bitset_sz = num_entries_at_bottom_level * 2 - 2;
assert(@sizeOf(free_node) <= minsize);
return struct {
bs: Bitset(bitset_sz) = .{},
freelists: [allocator_levels]free_node = [_]free_node{free_node{}} ** allocator_levels,
inited: bool = false,
base: usize,
pub fn init(self: *@This(), base: usize) !void {
if (self.inited)
return error.AlreadyInited;
self.inited = true;
self.base = base;
// Making up a new address here, need to make sure it's mapped
const root_node = @intToPtr(*free_node, self.base);
try paging.map(.{
.virt = self.base,
.size = page_size,
.perm = paging.rw(),
});
self.freelists[allocator_levels - 1].next = root_node;
root_node.prev = &self.freelists[allocator_levels - 1];
root_node.next = null;
}
pub fn deinit(self: *@This()) !void {
if (!self.inited)
return error.NotInited;
if (!self.freelists[allocator_levels - 1].next != @intToPtr(*free_node, self.base))
return error.CannotRollback;
self.inited = false;
}
pub fn alloc_size(self: *@This(), size: usize) !usize {
inline for (range(allocator_levels)) |lvl| {
if (size <= level_size(lvl))
return self.alloc(lvl);
}
return error.OutOfMemory;
}
pub fn free_size(self: *@This(), size: usize, addr: usize) !void {
inline for (range(allocator_levels)) |lvl| {
if (size <= level_size(lvl))
return self.free(lvl, addr);
}
return error.BadSize;
}
fn level_size(comptime level: usize) usize {
return minsize << level;
}
fn buddy_addr(comptime level: usize, addr: usize) usize {
return addr ^ level_size(level);
}
fn addr_bitset_index(self: @This(), comptime level: usize, addr: usize) usize {
var curr_step = num_entries_at_bottom_level;
var idx: usize = 0;
var block_size = minsize;
inline for (range(level)) |lvl| {
idx += curr_step;
curr_step /= 2;
block_size *= 2;
}
return idx + (addr - self.base) / block_size;
}
fn alloc(self: *@This(), comptime level: usize) !usize {
if (self.freelists[level].next) |v| {
// Hey, this thing on the freelist here looks as good as any.
v.remove();
return @ptrToInt(v);
} else {
if (level == allocator_levels - 1) {
return error.OutOfMemory;
}
const v = try self.alloc(level + 1);
errdefer self.free(level + 1, v) catch unreachable;
// Making up a new address here, need to make sure it's mapped
const buddy = buddy_addr(level, v);
paging.map(.{
.virt = buddy,
.size = page_size,
.perm = paging.rw(),
}) catch |err| switch (err) {
error.AlreadyPresent => {}, // That's fine to us.
else => return err,
};
errdefer paging.unmap(.{
.virt = buddy,
.size = page_size,
.perm = paging.rw(),
});
self.add_free(buddy, level);
return v;
}
}
// Free something without checking for its buddy, !only! use when its buddy is !not! free
fn add_free(self: *@This(), ptr: usize, comptime level: usize) void {
// Insert into freelist
const node = @intToPtr(*free_node, ptr);
node.next = self.freelists[level].next;
node.prev = &self.freelists[level];
self.freelists[level].next = node;
// Set bit in bitset
self.bs.set(self.addr_bitset_index(level, ptr));
}
fn free(self: *@This(), comptime level: usize, addr: usize) !void {
if (level == allocator_levels - 1) {
// We're done, this is the top level
self.add_free(addr, level);
return;
} else {
const buddy = buddy_addr(level, addr);
const buddy_index = self.addr_bitset_index(level, buddy);
// Is buddy free??
if (!self.bs.is_set(buddy_index)) {
// If not, just add this node to the freelist
self.add_free(addr, level);
return;
}
// Hey, it _is_ free
const buddy_node = @intToPtr(*free_node, buddy);
// The node has to be removed from the freelist
// before it's unmapped, otherwise we can't read its contents.
// Bubble it up
if (addr < buddy) {
try self.free(level + 1, addr);
buddy_node.remove();
paging.unmap(.{
.virt = buddy,
.size = page_size,
.reclaim_pages = true,
}) catch unreachable;
} else {
try self.free(level + 1, buddy);
buddy_node.remove();
paging.unmap(.{
.virt = addr,
.size = page_size,
.reclaim_pages = true,
}) catch unreachable;
}
self.bs.unset(buddy_index);
}
}
};
} | src/lib/buddy.zig |
const zgt = @import("zgt");
const std = @import("std");
const defaultcmd = "slock";
const defaulttime = "3m";
const shell = "/bin/sh";
const State = struct {
cmd: zgt.StringDataWrapper = zgt.StringDataWrapper.of(defaultcmd),
time: zgt.StringDataWrapper = zgt.StringDataWrapper.of(defaulttime),
};
var state: State = .{};
var window: zgt.Window = undefined;
var allocator = std.heap.GeneralPurposeAllocator(.{}){};
var gpa = allocator.allocator();
pub fn main() !void {
try zgt.backend.init();
const command = getCached("cmd") orelse defaultcmd;
const time = getCached("time") orelse defaulttime;
window = try zgt.Window.init();
try window.set(zgt.Column(.{}, .{
zgt.Label(.{ .text = "Ulysses" }),
zgt.Row(.{}, .{
zgt.Label(.{ .text = "Command To Run" }),
zgt.TextField(.{ .text = command }).setName("command"),
}),
zgt.Row(.{}, .{
zgt.Label(.{ .text = "Minutes In Future" }),
zgt.TextField(.{ .text = time }).setName("minutes"),
zgt.Button(.{ .label = "Run", .onclick = runcmd }),
}),
zgt.Button(.{ .label = "Exit", .onclick = exit }),
}));
window.show();
window.resize(400, 200);
zgt.runEventLoop();
}
fn exit(b: *zgt.Button_Impl) !void {
_ = b;
std.os.exit(0);
}
fn runcmd(b: *zgt.Button_Impl) !void {
const root = b.getRoot().?;
const minutes = root.get("minutes").?.as(zgt.TextField_Impl).getText();
const command = root.get("command").?.as(zgt.TextField_Impl).getText();
try setCached("time", minutes);
try setCached("cmd", command);
const command_with_sleep = try std.mem.concat(gpa, u8, &.{ "sleep ", minutes, "&&", command });
const argv: []const []const u8 = &.{ "/bin/sh", "-c", command_with_sleep };
_ = argv;
const pid = try std.os.fork();
if (pid > 0) {
std.os.exit(0);
}
// TODO other os??
if (comptime @import("builtin").os.tag == .linux)
_ = std.os.linux.syscall0(.setsid);
std.log.info("running the command: `{s}`", .{command_with_sleep});
std.process.execve(gpa, argv, null) catch std.os.exit(1);
}
fn getCached(name: []const u8) ?[]const u8 {
const app_data_dir_s = std.fs.getAppDataDir(gpa, "ulysses") catch return null;
const app_data_dir = std.fs.openDirAbsolute(app_data_dir_s, .{}) catch return null;
const f = app_data_dir.openFile(name, .{}) catch return null;
const bytes = f.readToEndAlloc(gpa, 4096) catch null;
return bytes;
}
fn setCached(name: []const u8, text: []const u8) !void {
const app_data_dir_s = try std.fs.getAppDataDir(gpa, "ulysses");
std.fs.makeDirAbsolute(app_data_dir_s) catch {};
const app_data_dir = try std.fs.openDirAbsolute(app_data_dir_s, .{});
const f = try app_data_dir.createFile(name, .{});
return f.writeAll(text);
} | src/main.zig |
const gpio = @import("gpio.zig");
const rs_pin = 8;
const en_pin = 9;
const data_pins = [4]comptime_int{ 4, 5, 6, 7 };
const cols = 16;
const rows = 2;
const Control = struct {
const clear_display: u8 = 0x01;
const return_home: u8 = 0x02;
const entry_mode_set: u8 = 0x04;
const display_control: u8 = 0x08;
const cursor_shift: u8 = 0x10;
const function_set: u8 = 0x20;
const set_CGRAM_address: u8 = 0x40;
const set_DDRAM_address: u8 = 0x80;
};
const Flags = struct {
const entry_shift_inc = 0x01;
const entry_left = 0x02;
const blink: u8 = 0x01;
const cursor: u8 = 0x02;
const display_on: u8 = 0x04;
const move_right: u8 = 0x04;
const display_move: u8 = 0x08;
const lcd_2lines: u8 = 0x08;
};
const CurrentDisp = struct {
var function: u8 = undefined;
var mode: u8 = undefined;
var control: u8 = undefined;
};
pub fn begin() void {
CurrentDisp.function = Flags.lcd_2lines;
CurrentDisp.mode = 0;
CurrentDisp.control = 0;
gpio.pinMode(en_pin, .output);
gpio.pinMode(rs_pin, .output);
inline for (data_pins) |pin| {
gpio.pinMode(pin, .output);
}
delayMilliseconds(45);
gpio.digitalWrite(en_pin, .low);
gpio.digitalWrite(rs_pin, .low);
write4bits(0x3);
delayMilliseconds(5);
write4bits(0x3);
delayMilliseconds(5);
write4bits(0x3);
delayMicroseconds(120);
write4bits(0x2);
command(Control.function_set | CurrentDisp.function);
displayOn();
clear();
CurrentDisp.mode |= Flags.entry_left;
command(Control.entry_mode_set | CurrentDisp.mode);
}
pub fn clear() void {
command(Control.set_DDRAM_address);
command(Control.clear_display);
delayMilliseconds(2);
}
fn displayOn() void {
CurrentDisp.control |= Flags.display_on;
command(Control.display_control | CurrentDisp.control);
}
fn write(value: u8) void {
gpio.digitalWrite(rs_pin, .high);
write4bitsTwice(value);
}
pub fn writeU16(value: u16) void {
var val = value;
var i: u3 = 0;
while (i < 4) : (i += 1) {
const nibble = @truncate(u8, (val & 0xf000) >> 12);
switch (nibble) {
0...9 => write('0' + nibble),
else => write('a' - 10 + nibble),
}
val <<= 4;
}
}
pub fn writeLines(line1: []const u8, line2: []const u8) void {
for (line1) |c|
write(c);
command(Control.set_DDRAM_address | 0x40);
for (line2) |c|
write(c);
}
pub fn writePanic(msg: []const u8) void {
begin();
for ("Panic! Msg:") |c|
write(c);
const short = if (msg.len > 16) msg[0..16] else msg;
command(Control.set_DDRAM_address | 0x40);
for (msg) |c|
write(c);
}
fn command(value: u8) void {
gpio.digitalWrite(rs_pin, .low);
write4bitsTwice(value);
}
fn write4bits(value: u4) void {
inline for (data_pins) |pin, i| {
if ((value >> i) & 1 != 0) {
gpio.digitalWrite(pin, .high);
} else {
gpio.digitalWrite(pin, .low);
}
}
pulseEnable();
}
fn write4bitsTwice(value: u8) void {
write4bits(@truncate(u4, (value >> 4) & 0xf));
write4bits(@truncate(u4, value & 0xf));
}
fn pulseEnable() void {
gpio.digitalWrite(en_pin, .low);
delayMicroseconds(1);
gpio.digitalWrite(en_pin, .high);
delayMicroseconds(1);
gpio.digitalWrite(en_pin, .low);
delayMicroseconds(100);
}
//Not exactly microseconds :c
fn delayMicroseconds(comptime microseconds: comptime_int) void {
var count: u32 = 0;
while (count < microseconds * 2) : (count += 1) {
asm volatile ("nop");
}
}
fn delayMilliseconds(comptime milliseconds: comptime_int) void {
var count: u32 = 0;
while (count < milliseconds * 1600) : (count += 1) {
asm volatile ("nop");
}
} | src/liquid_crystal.zig |
const std = @import("std");
const tcache = @import("texturecache.zig");
const slides = @import("slides.zig");
const upaya = @import("upaya");
const my_fonts = @import("myscalingfonts.zig");
const markdownlineparser = @import("markdownlineparser.zig");
usingnamespace upaya.imgui;
usingnamespace slides;
usingnamespace markdownlineparser;
const RenderElementKind = enum {
background,
text,
image,
};
const RenderElement = struct {
kind: RenderElementKind = .background,
position: ImVec2 = ImVec2{},
size: ImVec2 = ImVec2{},
color: ?ImVec4 = ImVec4{},
text: ?[*:0]const u8 = null,
fontSize: ?i32 = null,
fontStyle: my_fonts.FontStyle = .normal,
underlined: bool = false,
underline_width: ?i32 = null,
bullet_color: ?ImVec4 = null,
texture: ?*upaya.Texture = null,
bullet_symbol: [*:0]const u8 = "",
};
const RenderedSlide = struct {
elements: std.ArrayList(RenderElement) = undefined,
fn new(allocator: *std.mem.Allocator) !*RenderedSlide {
var self: *RenderedSlide = try allocator.create(RenderedSlide);
self.* = .{};
self.elements = std.ArrayList(RenderElement).init(allocator);
return self;
}
};
pub const SlideshowRenderer = struct {
renderedSlides: std.ArrayList(*RenderedSlide) = undefined,
allocator: *std.mem.Allocator = undefined,
md_parser: MdLineParser = .{},
pub fn new(allocator: *std.mem.Allocator) !*SlideshowRenderer {
var self: *SlideshowRenderer = try allocator.create(SlideshowRenderer);
self.* = .{};
self.*.allocator = allocator;
self.renderedSlides = std.ArrayList(*RenderedSlide).init(allocator);
self.md_parser.init(self.allocator);
return self;
}
pub fn preRender(self: *SlideshowRenderer, slideshow: *const SlideShow, slideshow_filp: []const u8) !void {
std.log.debug("ENTER preRender", .{});
if (slideshow.slides.items.len == 0) {
return;
}
self.renderedSlides.shrinkRetainingCapacity(0);
for (slideshow.slides.items) |slide, i| {
const slide_number = i + 1;
if (slide.items.items.len == 0) {
continue;
}
// add a renderedSlide
var renderSlide = try RenderedSlide.new(self.allocator);
for (slide.items.items) |item, j| {
switch (item.kind) {
.background => try self.createBg(renderSlide, item, slideshow_filp),
.textbox => try self.preRenderTextBlock(renderSlide, item, slide_number),
.img => try self.createImg(renderSlide, item, slideshow_filp),
}
}
// now add the slide
try self.renderedSlides.append(renderSlide);
}
std.log.debug("LEAVE preRender", .{});
}
fn createBg(self: *SlideshowRenderer, renderSlide: *RenderedSlide, item: SlideItem, slideshow_filp: []const u8) !void {
if (item.img_path) |p| {
var texptr = try tcache.getImg(p, slideshow_filp);
if (texptr) |t| {
try renderSlide.elements.append(RenderElement{ .kind = .background, .texture = t });
}
} else {
if (item.color) |color| {
try renderSlide.elements.append(RenderElement{ .kind = .background, .color = color });
}
}
}
fn preRenderTextBlock(self: *SlideshowRenderer, renderSlide: *RenderedSlide, item: SlideItem, slide_number: usize) !void {
// for line in lines:
// if line is bulleted: emit bullet, adjust x pos
// render spans
std.log.debug("ENTER preRenderTextBlock for slide {d}", .{slide_number});
const spaces_per_indent: usize = 4;
var fontSize: i32 = 0;
var line_height_bullet_width: ImVec2 = .{};
if (item.fontSize) |fs| {
line_height_bullet_width = self.lineHightAndBulletWidthForFontSize(fs);
fontSize = fs;
} else {
// no fontsize - error!
std.log.err("No fontsize for text {s}", .{item.text});
return;
}
var bulletColor: ImVec4 = .{};
if (item.bullet_color) |bc| {
bulletColor = bc;
} else {
// no bullet color - error!
std.log.err("No bullet color for text {s}", .{item.text});
return;
}
// actually, checking for a bullet symbol only makes sense if anywhere in the text a bulleted item exists
// but we'll leave it like this for now
// not sure I want to allocate here, though
var bulletSymbol: [*:0]const u8 = undefined;
if (item.bullet_symbol) |bs| {
bulletSymbol = try std.fmt.allocPrintZ(self.allocator, "{s}", .{bs});
} else {
// no bullet symbol - error
std.log.err("No bullet symbol for text {s}", .{item.text});
return;
}
const color = item.color orelse return;
const underline_width = item.underline_width orelse 0;
if (item.text) |t| {
const tl_pos = ImVec2{ .x = item.position.x, .y = item.position.y };
var layoutContext = TextLayoutContext{
.available_size = .{ .x = item.size.x, .y = item.size.y },
.origin_pos = tl_pos,
.current_pos = tl_pos,
.fontSize = fontSize,
.underline_width = @intCast(usize, underline_width),
.color = color,
.text = "", // will be overridden immediately
.current_line_height = line_height_bullet_width.y, // will be overridden immediately but needed if text starts with empty line(s)
};
// slide number
var slideNumStr: [10]u8 = undefined;
_ = try std.fmt.bufPrint(&slideNumStr, "{d}", .{slide_number});
const new_t = try std.mem.replaceOwned(u8, self.allocator, t, "$slide_number", &slideNumStr);
// split into lines
var it = std.mem.split(new_t, "\n");
while (it.next()) |line| {
if (line.len == 0) {
// empty line
layoutContext.current_pos.y += layoutContext.current_line_height;
continue;
}
// find out, if line is a list item:
// - starts with `-` or `>`
var bullet_indent_in_spaces: usize = 0;
const is_bulleted = self.countIndentOfBullet(line, &bullet_indent_in_spaces);
const indent_level = bullet_indent_in_spaces / spaces_per_indent;
const indent_in_pixels = line_height_bullet_width.x * @intToFloat(f32, bullet_indent_in_spaces / spaces_per_indent);
var available_width = item.size.x - indent_in_pixels;
layoutContext.available_size.x = available_width;
layoutContext.origin_pos.x = tl_pos.x + indent_in_pixels;
layoutContext.current_pos.x = tl_pos.x + indent_in_pixels;
layoutContext.fontSize = fontSize;
layoutContext.underline_width = @intCast(usize, underline_width);
layoutContext.color = color;
layoutContext.text = line;
if (is_bulleted) {
// 1. add indented bullet symbol at the current pos
try renderSlide.elements.append(RenderElement{
.kind = .text,
.position = .{ .x = tl_pos.x + indent_in_pixels, .y = layoutContext.current_pos.y },
.size = .{ .x = available_width, .y = layoutContext.available_size.y },
.fontSize = fontSize,
.underline_width = underline_width,
.text = bulletSymbol,
.color = bulletColor,
});
// 2. increase indent by 1 and add indented text block
available_width -= line_height_bullet_width.x;
layoutContext.origin_pos.x += line_height_bullet_width.x;
layoutContext.current_pos.x = layoutContext.origin_pos.x;
layoutContext.available_size.x = available_width;
layoutContext.text = std.mem.trimLeft(u8, line, " \t->");
}
try self.renderMdBlock(renderSlide, &layoutContext);
// advance to the next line
layoutContext.current_pos.x = tl_pos.x;
layoutContext.current_pos.y += layoutContext.current_line_height;
// don't render (much) beyond size
//
// with this check, we will not render anything that would start outside the size rect.
// Also, lines using the regular font will not exceed the size rect.
// however,
// - if a line uses a bigger font (more pixels) than the regular font, we might still exceed the size rect by the delta
// - we might still draw underlines beyond the size.y if the last line fits perfectly.
if (layoutContext.current_pos.y >= tl_pos.y + item.size.y - line_height_bullet_width.y) {
break;
}
}
}
std.log.debug("LEAVE preRenderTextBlock for slide {d}", .{slide_number});
}
const TextLayoutContext = struct {
origin_pos: ImVec2 = .{},
current_pos: ImVec2 = .{},
available_size: ImVec2 = .{},
current_line_height: f32 = 0,
fontSize: i32 = 0,
underline_width: usize = 0,
color: ImVec4 = .{},
text: []const u8 = undefined,
};
fn renderMdBlock(self: *SlideshowRenderer, renderSlide: *RenderedSlide, layoutContext: *TextLayoutContext) !void {
// remember original pos. its X will need to be reset at every line wrap
// for span in spans:
// calc size.x of span
// if width > available_width:
// reduce width by chopping of words to the right until it fits
// repeat that for the remainding shit
// for split in splits:
// # treat them as lines.
// if lastsplit did not end with newline
// we continue the next span right after the last split
//
// the visible line hight is determined by the highest text span in the visible line!
std.log.debug("ENTER renderMdBlock ", .{});
self.md_parser.init(self.allocator);
try self.md_parser.parseLine(layoutContext.text);
if (self.md_parser.result_spans) |spans| {
if (spans.items.len == 0) {
std.log.debug("LEAVE1 preRenderTextBlock ", .{});
return;
}
std.log.debug("SPANS:", .{});
self.md_parser.logSpans();
std.log.debug("ENDSPANS", .{});
const default_color = layoutContext.color;
var element = RenderElement{
.kind = .text,
.size = layoutContext.available_size,
.color = default_color,
.fontSize = layoutContext.fontSize,
.underline_width = @intCast(i32, layoutContext.underline_width),
};
// when we check if a piece of text fits into the available width, we calculate its size, giving it an infinite width
// so we can check the returned width against the available_width. Theoretically, Infinity_Width could be maxed out at
// current_surface_size.x - since widths beyond that one would make no sense
const Infinity_Width: f32 = 1000000;
for (spans.items) |span| {
if (span.text.?[0] == 0) {
std.log.debug("SKIPPING ZERO LENGTH SPAN", .{});
continue;
}
std.log.debug("new span, len=: `{d}`", .{span.text.?.len});
// work out the font
element.fontStyle = .normal;
element.underlined = span.styleflags & StyleFlags.underline > 0;
if (span.styleflags & StyleFlags.bold > 0) {
element.fontStyle = .bold;
}
if (span.styleflags & StyleFlags.italic > 0) {
element.fontStyle = .italic;
}
if (span.styleflags & StyleFlags.zig > 0) {
element.fontStyle = .zig;
}
if (span.styleflags & (StyleFlags.bold | StyleFlags.italic) == (StyleFlags.bold | StyleFlags.italic)) {
element.fontStyle = .bolditalic;
}
// work out the color
element.color = default_color;
if (span.styleflags & StyleFlags.colored > 0) {
if (span.color_override) |co| {
element.color = co;
} else {
std.log.debug(" ************************* NO COLOR OVERRIDE (styleflags: {x:02})", .{span.styleflags});
element.color = default_color;
}
}
// check the line hight of this span's fontstyle so we can check whether it wrapped
const ig_span_fontsize_text: [*c]const u8 = "XXX";
var ig_span_fontsize: ImVec2 = .{};
my_fonts.pushStyledFontScaled(layoutContext.fontSize, element.fontStyle);
igCalcTextSize(&ig_span_fontsize, ig_span_fontsize_text, ig_span_fontsize_text + 2, false, 2000);
my_fonts.popFontScaled();
// check if whole span fits width. - let's be opportunistic!
// if not, start chopping off from the right until it fits
// keep rest for later
// Q: is it better to try to pop words from the left until
// the text doesn't fit anymore?
// A: probably yes. Lines can be pretty long and hence wrap
// multiple times. Trying to find the max amount of words
// that fit until the first break is necessary is faster
// in that case.
// Also, doing it this way makes it pretty straight-forward
// to wrap superlong words that wouldn't even fit the
// current line width - and can be broken down easily.
// --
// One more thing: as we're looping through the spans,
// we don't render from the start of the line but
// from the end of the last span.
// check if whole line fits
// orelse start wrapping (see above)
//
//
var attempted_span_size: ImVec2 = .{};
var available_width: f32 = layoutContext.origin_pos.x + layoutContext.available_size.x - layoutContext.current_pos.x;
var render_text_c = try self.styledTextblockSize_toCstring(span.text.?, layoutContext.fontSize, element.fontStyle, Infinity_Width, &attempted_span_size);
std.log.debug("available_width: {d}, attempted_span_size: {d:3.0}", .{ available_width, attempted_span_size.x });
if (attempted_span_size.x < available_width) {
// we did not wrap so the entire span can be output!
element.text = render_text_c;
element.position = layoutContext.current_pos;
element.size.x = attempted_span_size.x;
//element.size = attempted_span_size;
std.log.debug(">>>>>>> appending non-wrapping text element: {s}@{d:3.0},{d:3.0}", .{ element.text, element.position.x, element.position.y });
try renderSlide.elements.append(element);
// advance render pos
layoutContext.current_pos.x += attempted_span_size.x;
// if something is rendered into the currend line, then adjust the line height if necessary
if (attempted_span_size.y > layoutContext.current_line_height) {
layoutContext.current_line_height = attempted_span_size.y;
}
} else {
// we need to check with how many words we can get away with:
std.log.debug(" -> we need to check where to wrap!", .{});
// first, let's pseudo-split into words:
// (what's so pseudo about that? we don't actually split, we just remember separator positions)
// we find the first index of word-separator, then the 2nd, ...
// and use it to determine the length of the slice
var lastIdxOfSpace: usize = 0;
var lastConsumedIdx: usize = 0;
var currentIdxOfSpace: usize = 0;
var wordCount: usize = 0;
// TODO: FIXME: we don't like tabs
while (true) {
std.log.debug("lastConsumedIdx: {}, lastIdxOfSpace: {}, currentIdxOfSpace: {}", .{ lastConsumedIdx, lastIdxOfSpace, currentIdxOfSpace });
if (std.mem.indexOfPos(u8, span.text.?, currentIdxOfSpace, " ")) |idx| {
currentIdxOfSpace = idx;
// look-ahead only allowed if there is more text
if (span.text.?.len > currentIdxOfSpace + 1) {
if (span.text.?[currentIdxOfSpace + 1] == ' ') {
currentIdxOfSpace += 1; // jump over consecutive spaces
continue;
}
}
if (currentIdxOfSpace == 0) {
// special case: we start with a space
// we start searching for the next space 1 after the last found one
if (currentIdxOfSpace + 1 < span.text.?.len) {
currentIdxOfSpace += 1;
continue;
} else {
// in this case we better break or else we will loop forever
break;
}
}
wordCount += 1;
} else {
std.log.debug("no more space found", .{});
if (wordCount == 0) {
wordCount = 1;
}
// no more space found, render the rest and then break
if (lastConsumedIdx < span.text.?.len - 1) {
// render the remainder
currentIdxOfSpace = span.text.?.len; //- 1;
std.log.debug("Trying with the remainder", .{});
} else {
break;
}
}
std.log.debug("current idx of spc {d}", .{currentIdxOfSpace});
// try if we fit. if we don't -> render up until last idx
var render_text = span.text.?[lastConsumedIdx..currentIdxOfSpace];
render_text_c = try self.styledTextblockSize_toCstring(render_text, layoutContext.fontSize, element.fontStyle, Infinity_Width, &attempted_span_size);
std.log.debug(" current available_width: {d}, attempted_span_size: {d:3.0}", .{ available_width, attempted_span_size.x });
if (attempted_span_size.x > available_width and wordCount > 1) {
// we wrapped!
// so render everything up until the last word
// then, render the new word in the new line?
if (wordCount == 1 and false) {
// special case: the first word wrapped, so we need to split it
// TODO: implement me
std.log.debug(">>>>>>>>>>>>> FIRST WORD !!!!!!!!!!!!!!!!!!! <<<<<<<<<<<<<<<<", .{});
} else {
// we check how large the current string (without that last word that caused wrapping) really is, to adjust our new current_pos.x:
available_width = layoutContext.origin_pos.x + layoutContext.available_size.x - layoutContext.current_pos.x;
render_text = span.text.?[lastConsumedIdx..lastIdxOfSpace];
render_text_c = try self.styledTextblockSize_toCstring(render_text, layoutContext.fontSize, element.fontStyle, available_width, &attempted_span_size);
lastConsumedIdx = lastIdxOfSpace;
lastIdxOfSpace = currentIdxOfSpace;
element.text = render_text_c;
element.position = layoutContext.current_pos;
element.size.x = attempted_span_size.x;
// element.size = attempted_span_size;
std.log.debug(">>>>>>> appending wrapping text element: {s} width={d:3.0}", .{ element.text, attempted_span_size.x });
try renderSlide.elements.append(element);
// advance render pos
layoutContext.current_pos.x += attempted_span_size.x;
// something is rendered into the currend line, so adjust the line height if necessary
if (attempted_span_size.y > layoutContext.current_line_height) {
layoutContext.current_line_height = attempted_span_size.y;
}
// we line break here and render the remaining word
// hmmm. if we render the remaining word - further words are likely to be rendered, too
// so maybe skip rendering it now?
std.log.debug(">>> BREAKING THE LINE, height: {}", .{layoutContext.current_line_height});
layoutContext.current_pos.x = layoutContext.origin_pos.x;
layoutContext.current_pos.y += layoutContext.current_line_height;
layoutContext.current_line_height = 0;
available_width = layoutContext.origin_pos.x + layoutContext.available_size.x - layoutContext.current_pos.x;
}
} else {
// if it's the last, uncommitted word
if (lastIdxOfSpace >= currentIdxOfSpace) {
available_width = layoutContext.origin_pos.x + layoutContext.available_size.x - layoutContext.current_pos.x;
render_text = span.text.?[lastConsumedIdx..currentIdxOfSpace];
render_text_c = try self.styledTextblockSize_toCstring(render_text, layoutContext.fontSize, element.fontStyle, available_width, &attempted_span_size);
lastConsumedIdx = lastIdxOfSpace;
lastIdxOfSpace = currentIdxOfSpace;
element.text = render_text_c;
element.position = layoutContext.current_pos;
// element.size = attempted_span_size;
std.log.debug(">>>>>>> appending final text element: {s} width={d:3.0}", .{ element.text, attempted_span_size.x });
element.size.x = attempted_span_size.x;
try renderSlide.elements.append(element);
// advance render pos
layoutContext.current_pos.x += attempted_span_size.x;
// something is rendered into the currend line, so adjust the line height if necessary
if (attempted_span_size.y > layoutContext.current_line_height) {
layoutContext.current_line_height = attempted_span_size.y;
}
// let's not break the line because of the last word
// std.log.debug(">>> BREAKING THE LINE, height: {}", .{layoutContext.current_line_height});
// layoutContext.current_pos.x = layoutContext.origin_pos.x;
// layoutContext.current_pos.y += layoutContext.current_line_height;
// layoutContext.current_line_height = 0;
break; // it's the last word after all
}
}
lastIdxOfSpace = currentIdxOfSpace + 1;
// we start searching for the next space 1 after the last found one
if (currentIdxOfSpace + 1 < span.text.?.len) {
currentIdxOfSpace += 1;
} else {
//break;
}
}
// we could have run out of text to check for wrapping
// if that's the case: render the remainder
}
}
} else {
// no spans
std.log.debug("LEAVE2 renderMdBlock ", .{});
return;
}
std.log.debug("LEAVE3 renderMdBlock ", .{});
}
fn lineHightAndBulletWidthForFontSize(self: *SlideshowRenderer, fontsize: i32) ImVec2 {
var size = ImVec2{};
var ret = ImVec2{};
my_fonts.pushFontScaled(fontsize);
const text: [*c]const u8 = "FontCheck";
igCalcTextSize(&size, text, text + 5, false, 8000);
ret.y = size.y;
var bullet_text: [*c]const u8 = undefined;
bullet_text = "> "; // TODO this should ideally honor the real bullet symbol but I don't care atm
igCalcTextSize(&size, bullet_text, bullet_text + std.mem.lenZ(bullet_text), false, 8000);
ret.x = size.x;
my_fonts.popFontScaled();
return ret;
}
fn countIndentOfBullet(self: *SlideshowRenderer, line: []const u8, indent_out: *usize) bool {
var indent: usize = 0;
for (line) |c, i| {
if (c == '-' or c == '>') {
indent_out.* = indent;
return true;
}
if (c != ' ' and c != '\t') {
return false;
}
if (c == ' ') {
indent += 1;
}
if (c == '\t') {
indent += 4;
// TODO: make tab to spaces ratio configurable
}
}
return false;
}
fn toCString(self: *SlideshowRenderer, text: []const u8) ![*c]const u8 {
return try self.allocator.dupeZ(u8, text);
}
fn heightOfTextblock_toCstring(self: *SlideshowRenderer, text: []const u8, fontsize: i32, block_width: f32, height_out: *f32) ![*c]const u8 {
var size = ImVec2{};
my_fonts.pushFontScaled(fontsize);
const ctext = try self.toCString(text);
igCalcTextSize(&size, ctext, &ctext[std.mem.len(ctext) - 1], false, block_width);
my_fonts.popFontScaled();
height_out.* = size.y;
return ctext;
}
fn styledTextblockSize_toCstring(self: *SlideshowRenderer, text: []const u8, fontsize: i32, fontstyle: my_fonts.FontStyle, block_width: f32, size_out: *ImVec2) ![*c]const u8 {
my_fonts.pushStyledFontScaled(fontsize, fontstyle);
defer my_fonts.popFontScaled();
const ctext = try self.toCString(text);
std.log.debug("cstring: of {s} = `{s}`", .{ text, ctext });
if (ctext[0] == 0) {
size_out.x = 0;
size_out.y = 0;
return ctext;
}
igCalcTextSize(size_out, ctext, &ctext[std.mem.len(ctext)], false, block_width);
return ctext;
}
fn createImg(self: *SlideshowRenderer, renderSlide: *RenderedSlide, item: SlideItem, slideshow_filp: []const u8) !void {
if (item.img_path) |p| {
var texptr = try tcache.getImg(p, slideshow_filp);
if (texptr) |t| {
try renderSlide.elements.append(RenderElement{
.kind = .image,
.position = item.position,
.size = item.size,
.texture = t,
});
}
}
}
pub fn render(self: *SlideshowRenderer, slide_number: i32, pos: ImVec2, size: ImVec2, internal_render_size: ImVec2) !void {
if (self.renderedSlides.items.len == 0) {
std.log.debug("0 renderedSlides", .{});
return;
}
const slide = self.renderedSlides.items[@intCast(usize, slide_number)];
if (slide.elements.items.len == 0) {
std.log.debug("0 elements", .{});
return;
}
// TODO: pass that in from G
const img_tint_col: ImVec4 = ImVec4{ .x = 1.0, .y = 1.0, .z = 1.0, .w = 1.0 }; // No tint
const img_border_col: ImVec4 = ImVec4{ .x = 0.0, .y = 0.0, .z = 0.0, .w = 0.0 }; // 50% opaque black
for (slide.elements.items) |element| {
switch (element.kind) {
.background => {
if (element.texture) |txt| {
renderImg(.{}, internal_render_size, txt, img_tint_col, img_border_col, pos, size, internal_render_size);
} else {
if (element.color) |color| {
renderBgColor(color, internal_render_size, pos, size, internal_render_size);
} else {
//. empty
}
}
},
.text => {
renderText(&element, pos, size, internal_render_size);
},
.image => {
renderImg(element.position, element.size, element.texture.?, img_tint_col, img_border_col, pos, size, internal_render_size);
},
}
}
}
};
fn slidePosToRenderPos(pos: ImVec2, slide_tl: ImVec2, slide_size: ImVec2, internal_render_size: ImVec2) ImVec2 {
const my_tl = ImVec2{
.x = slide_tl.x + pos.x * slide_size.x / internal_render_size.x,
.y = slide_tl.y + pos.y * slide_size.y / internal_render_size.y,
};
return my_tl;
}
fn slideSizeToRenderSize(size: ImVec2, slide_size: ImVec2, internal_render_size: ImVec2) ImVec2 {
const my_size = ImVec2{
.x = size.x * slide_size.x / internal_render_size.x,
.y = size.y * slide_size.y / internal_render_size.y,
};
return my_size;
}
fn renderImg(pos: ImVec2, size: ImVec2, texture: *upaya.Texture, tint_color: ImVec4, border_color: ImVec4, slide_tl: ImVec2, slide_size: ImVec2, internal_render_size: ImVec2) void {
var uv_min = ImVec2{ .x = 0.0, .y = 0.0 }; // Top-let
var uv_max = ImVec2{ .x = 1.0, .y = 1.0 }; // Lower-right
// position the img in the slide
const my_tl = slidePosToRenderPos(pos, slide_tl, slide_size, internal_render_size);
const my_size = slideSizeToRenderSize(size, slide_size, internal_render_size);
igSetCursorPos(my_tl);
igImage(texture.*.imTextureID(), my_size, uv_min, uv_max, tint_color, border_color);
}
fn renderBgColor(bgcol: ImVec4, size: ImVec2, slide_tl: ImVec2, slide_size: ImVec2, internal_render_size: ImVec2) void {
igSetCursorPos(slide_tl);
var drawlist = igGetForegroundDrawListNil();
if (drawlist == null) {
std.log.warn("drawlist is null!", .{});
} else {
var br = slide_tl;
br.x = slide_tl.x + slide_size.x;
br.y = slide_tl.y + slide_size.y;
const bgcolu32 = igGetColorU32Vec4(bgcol);
igRenderFrame(slide_tl, br, bgcolu32, true, 0.0);
}
}
fn renderText(item: *const RenderElement, slide_tl: ImVec2, slide_size: ImVec2, internal_render_size: ImVec2) void {
if (item.*.text.?[0] == 0) {
return;
}
var wrap_pos = item.position;
wrap_pos.x += item.size.x;
// we need to make the wrap pos slightly larger:
// since for underline, sizes are pixel exact, later scaling of this might screw the wrapping - safety margin is 10 pixels here
var wrap_offset = slidePosToRenderPos(.{ .x = 10, .y = 0 }, slide_tl, slide_size, internal_render_size).x;
if (wrap_offset < 10) {
wrap_offset = 10;
}
wrap_pos.x += wrap_offset;
igPushTextWrapPos(slidePosToRenderPos(wrap_pos, slide_tl, slide_size, internal_render_size).x);
const fs = item.fontSize.?;
const fsize = @floatToInt(i32, @intToFloat(f32, fs) * slide_size.y / internal_render_size.y);
const col = item.color;
my_fonts.pushStyledFontScaled(fsize, item.fontStyle);
defer my_fonts.popFontScaled();
// diplay the text
const t = item.text.?;
igSetCursorPos(slidePosToRenderPos(item.position, slide_tl, slide_size, internal_render_size));
igPushStyleColorVec4(ImGuiCol_Text, col.?);
igText(t);
igPopStyleColor(1);
igPopTextWrapPos();
// we need to rely on the size here, so better make sure, the width is correct
if (item.underlined) {
// how to draw the line?
var tl = item.position;
tl.y += @intToFloat(f32, fs) + 2;
var br = tl;
br.x += item.size.x;
br.y += 2;
const bgcolu32 = igGetColorU32Vec4(col.?);
igRenderFrame(slidePosToRenderPos(tl, slide_tl, slide_size, internal_render_size), slidePosToRenderPos(br, slide_tl, slide_size, internal_render_size), bgcolu32, true, 0.0);
}
} | src/sliderenderer.zig |
const std = @import("std");
const Allocator = std.mem.Allocator;
const ArrayList = std.ArrayList;
const assert = std.debug.assert;
const testing = std.testing;
const leb = std.leb;
const mem = std.mem;
const wasm = std.wasm;
const Module = @import("../Module.zig");
const Decl = Module.Decl;
const ir = @import("../ir.zig");
const Inst = ir.Inst;
const Type = @import("../type.zig").Type;
const Value = @import("../value.zig").Value;
const Compilation = @import("../Compilation.zig");
const AnyMCValue = @import("../codegen.zig").AnyMCValue;
const LazySrcLoc = Module.LazySrcLoc;
const link = @import("../link.zig");
const TypedValue = @import("../TypedValue.zig");
/// Wasm Value, created when generating an instruction
const WValue = union(enum) {
/// May be referenced but is unused
none: void,
/// Index of the local variable
local: u32,
/// Instruction holding a constant `Value`
constant: *Inst,
/// Offset position in the list of bytecode instructions
code_offset: usize,
/// The label of the block, used by breaks to find its relative distance
block_idx: u32,
/// Used for variables that create multiple locals on the stack when allocated
/// such as structs and optionals.
multi_value: u32,
};
/// Wasm ops, but without input/output/signedness information
/// Used for `buildOpcode`
const Op = enum {
@"unreachable",
nop,
block,
loop,
@"if",
@"else",
end,
br,
br_if,
br_table,
@"return",
call,
call_indirect,
drop,
select,
local_get,
local_set,
local_tee,
global_get,
global_set,
load,
store,
memory_size,
memory_grow,
@"const",
eqz,
eq,
ne,
lt,
gt,
le,
ge,
clz,
ctz,
popcnt,
add,
sub,
mul,
div,
rem,
@"and",
@"or",
xor,
shl,
shr,
rotl,
rotr,
abs,
neg,
ceil,
floor,
trunc,
nearest,
sqrt,
min,
max,
copysign,
wrap,
convert,
demote,
promote,
reinterpret,
extend,
};
/// Contains the settings needed to create an `Opcode` using `buildOpcode`.
///
/// The fields correspond to the opcode name. Here is an example
/// i32_trunc_f32_s
/// ^ ^ ^ ^
/// | | | |
/// valtype1 | | |
/// = .i32 | | |
/// | | |
/// op | |
/// = .trunc | |
/// | |
/// valtype2 |
/// = .f32 |
/// |
/// width |
/// = null |
/// |
/// signed
/// = true
///
/// There can be missing fields, here are some more examples:
/// i64_load8_u
/// --> .{ .valtype1 = .i64, .op = .load, .width = 8, signed = false }
/// i32_mul
/// --> .{ .valtype1 = .i32, .op = .trunc }
/// nop
/// --> .{ .op = .nop }
const OpcodeBuildArguments = struct {
/// First valtype in the opcode (usually represents the type of the output)
valtype1: ?wasm.Valtype = null,
/// The operation (e.g. call, unreachable, div, min, sqrt, etc.)
op: Op,
/// Width of the operation (e.g. 8 for i32_load8_s, 16 for i64_extend16_i32_s)
width: ?u8 = null,
/// Second valtype in the opcode name (usually represents the type of the input)
valtype2: ?wasm.Valtype = null,
/// Signedness of the op
signedness: ?std.builtin.Signedness = null,
};
/// Helper function that builds an Opcode given the arguments needed
fn buildOpcode(args: OpcodeBuildArguments) wasm.Opcode {
switch (args.op) {
.@"unreachable" => return .@"unreachable",
.nop => return .nop,
.block => return .block,
.loop => return .loop,
.@"if" => return .@"if",
.@"else" => return .@"else",
.end => return .end,
.br => return .br,
.br_if => return .br_if,
.br_table => return .br_table,
.@"return" => return .@"return",
.call => return .call,
.call_indirect => return .call_indirect,
.drop => return .drop,
.select => return .select,
.local_get => return .local_get,
.local_set => return .local_set,
.local_tee => return .local_tee,
.global_get => return .global_get,
.global_set => return .global_set,
.load => if (args.width) |width| switch (width) {
8 => switch (args.valtype1.?) {
.i32 => if (args.signedness.? == .signed) return .i32_load8_s else return .i32_load8_u,
.i64 => if (args.signedness.? == .signed) return .i64_load8_s else return .i64_load8_u,
.f32, .f64 => unreachable,
},
16 => switch (args.valtype1.?) {
.i32 => if (args.signedness.? == .signed) return .i32_load16_s else return .i32_load16_u,
.i64 => if (args.signedness.? == .signed) return .i64_load16_s else return .i64_load16_u,
.f32, .f64 => unreachable,
},
32 => switch (args.valtype1.?) {
.i64 => if (args.signedness.? == .signed) return .i64_load32_s else return .i64_load32_u,
.i32, .f32, .f64 => unreachable,
},
else => unreachable,
} else switch (args.valtype1.?) {
.i32 => return .i32_load,
.i64 => return .i64_load,
.f32 => return .f32_load,
.f64 => return .f64_load,
},
.store => if (args.width) |width| {
switch (width) {
8 => switch (args.valtype1.?) {
.i32 => return .i32_store8,
.i64 => return .i64_store8,
.f32, .f64 => unreachable,
},
16 => switch (args.valtype1.?) {
.i32 => return .i32_store16,
.i64 => return .i64_store16,
.f32, .f64 => unreachable,
},
32 => switch (args.valtype1.?) {
.i64 => return .i64_store32,
.i32, .f32, .f64 => unreachable,
},
else => unreachable,
}
} else {
switch (args.valtype1.?) {
.i32 => return .i32_store,
.i64 => return .i64_store,
.f32 => return .f32_store,
.f64 => return .f64_store,
}
},
.memory_size => return .memory_size,
.memory_grow => return .memory_grow,
.@"const" => switch (args.valtype1.?) {
.i32 => return .i32_const,
.i64 => return .i64_const,
.f32 => return .f32_const,
.f64 => return .f64_const,
},
.eqz => switch (args.valtype1.?) {
.i32 => return .i32_eqz,
.i64 => return .i64_eqz,
.f32, .f64 => unreachable,
},
.eq => switch (args.valtype1.?) {
.i32 => return .i32_eq,
.i64 => return .i64_eq,
.f32 => return .f32_eq,
.f64 => return .f64_eq,
},
.ne => switch (args.valtype1.?) {
.i32 => return .i32_ne,
.i64 => return .i64_ne,
.f32 => return .f32_ne,
.f64 => return .f64_ne,
},
.lt => switch (args.valtype1.?) {
.i32 => if (args.signedness.? == .signed) return .i32_lt_s else return .i32_lt_u,
.i64 => if (args.signedness.? == .signed) return .i64_lt_s else return .i64_lt_u,
.f32 => return .f32_lt,
.f64 => return .f64_lt,
},
.gt => switch (args.valtype1.?) {
.i32 => if (args.signedness.? == .signed) return .i32_gt_s else return .i32_gt_u,
.i64 => if (args.signedness.? == .signed) return .i64_gt_s else return .i64_gt_u,
.f32 => return .f32_gt,
.f64 => return .f64_gt,
},
.le => switch (args.valtype1.?) {
.i32 => if (args.signedness.? == .signed) return .i32_le_s else return .i32_le_u,
.i64 => if (args.signedness.? == .signed) return .i64_le_s else return .i64_le_u,
.f32 => return .f32_le,
.f64 => return .f64_le,
},
.ge => switch (args.valtype1.?) {
.i32 => if (args.signedness.? == .signed) return .i32_ge_s else return .i32_ge_u,
.i64 => if (args.signedness.? == .signed) return .i64_ge_s else return .i64_ge_u,
.f32 => return .f32_ge,
.f64 => return .f64_ge,
},
.clz => switch (args.valtype1.?) {
.i32 => return .i32_clz,
.i64 => return .i64_clz,
.f32, .f64 => unreachable,
},
.ctz => switch (args.valtype1.?) {
.i32 => return .i32_ctz,
.i64 => return .i64_ctz,
.f32, .f64 => unreachable,
},
.popcnt => switch (args.valtype1.?) {
.i32 => return .i32_popcnt,
.i64 => return .i64_popcnt,
.f32, .f64 => unreachable,
},
.add => switch (args.valtype1.?) {
.i32 => return .i32_add,
.i64 => return .i64_add,
.f32 => return .f32_add,
.f64 => return .f64_add,
},
.sub => switch (args.valtype1.?) {
.i32 => return .i32_sub,
.i64 => return .i64_sub,
.f32 => return .f32_sub,
.f64 => return .f64_sub,
},
.mul => switch (args.valtype1.?) {
.i32 => return .i32_mul,
.i64 => return .i64_mul,
.f32 => return .f32_mul,
.f64 => return .f64_mul,
},
.div => switch (args.valtype1.?) {
.i32 => if (args.signedness.? == .signed) return .i32_div_s else return .i32_div_u,
.i64 => if (args.signedness.? == .signed) return .i64_div_s else return .i64_div_u,
.f32 => return .f32_div,
.f64 => return .f64_div,
},
.rem => switch (args.valtype1.?) {
.i32 => if (args.signedness.? == .signed) return .i32_rem_s else return .i32_rem_u,
.i64 => if (args.signedness.? == .signed) return .i64_rem_s else return .i64_rem_u,
.f32, .f64 => unreachable,
},
.@"and" => switch (args.valtype1.?) {
.i32 => return .i32_and,
.i64 => return .i64_and,
.f32, .f64 => unreachable,
},
.@"or" => switch (args.valtype1.?) {
.i32 => return .i32_or,
.i64 => return .i64_or,
.f32, .f64 => unreachable,
},
.xor => switch (args.valtype1.?) {
.i32 => return .i32_xor,
.i64 => return .i64_xor,
.f32, .f64 => unreachable,
},
.shl => switch (args.valtype1.?) {
.i32 => return .i32_shl,
.i64 => return .i64_shl,
.f32, .f64 => unreachable,
},
.shr => switch (args.valtype1.?) {
.i32 => if (args.signedness.? == .signed) return .i32_shr_s else return .i32_shr_u,
.i64 => if (args.signedness.? == .signed) return .i64_shr_s else return .i64_shr_u,
.f32, .f64 => unreachable,
},
.rotl => switch (args.valtype1.?) {
.i32 => return .i32_rotl,
.i64 => return .i64_rotl,
.f32, .f64 => unreachable,
},
.rotr => switch (args.valtype1.?) {
.i32 => return .i32_rotr,
.i64 => return .i64_rotr,
.f32, .f64 => unreachable,
},
.abs => switch (args.valtype1.?) {
.i32, .i64 => unreachable,
.f32 => return .f32_abs,
.f64 => return .f64_abs,
},
.neg => switch (args.valtype1.?) {
.i32, .i64 => unreachable,
.f32 => return .f32_neg,
.f64 => return .f64_neg,
},
.ceil => switch (args.valtype1.?) {
.i32, .i64 => unreachable,
.f32 => return .f32_ceil,
.f64 => return .f64_ceil,
},
.floor => switch (args.valtype1.?) {
.i32, .i64 => unreachable,
.f32 => return .f32_floor,
.f64 => return .f64_floor,
},
.trunc => switch (args.valtype1.?) {
.i32 => switch (args.valtype2.?) {
.i32 => unreachable,
.i64 => unreachable,
.f32 => if (args.signedness.? == .signed) return .i32_trunc_f32_s else return .i32_trunc_f32_u,
.f64 => if (args.signedness.? == .signed) return .i32_trunc_f64_s else return .i32_trunc_f64_u,
},
.i64 => unreachable,
.f32 => return .f32_trunc,
.f64 => return .f64_trunc,
},
.nearest => switch (args.valtype1.?) {
.i32, .i64 => unreachable,
.f32 => return .f32_nearest,
.f64 => return .f64_nearest,
},
.sqrt => switch (args.valtype1.?) {
.i32, .i64 => unreachable,
.f32 => return .f32_sqrt,
.f64 => return .f64_sqrt,
},
.min => switch (args.valtype1.?) {
.i32, .i64 => unreachable,
.f32 => return .f32_min,
.f64 => return .f64_min,
},
.max => switch (args.valtype1.?) {
.i32, .i64 => unreachable,
.f32 => return .f32_max,
.f64 => return .f64_max,
},
.copysign => switch (args.valtype1.?) {
.i32, .i64 => unreachable,
.f32 => return .f32_copysign,
.f64 => return .f64_copysign,
},
.wrap => switch (args.valtype1.?) {
.i32 => switch (args.valtype2.?) {
.i32 => unreachable,
.i64 => return .i32_wrap_i64,
.f32, .f64 => unreachable,
},
.i64, .f32, .f64 => unreachable,
},
.convert => switch (args.valtype1.?) {
.i32, .i64 => unreachable,
.f32 => switch (args.valtype2.?) {
.i32 => if (args.signedness.? == .signed) return .f32_convert_i32_s else return .f32_convert_i32_u,
.i64 => if (args.signedness.? == .signed) return .f32_convert_i64_s else return .f32_convert_i64_u,
.f32, .f64 => unreachable,
},
.f64 => switch (args.valtype2.?) {
.i32 => if (args.signedness.? == .signed) return .f64_convert_i32_s else return .f64_convert_i32_u,
.i64 => if (args.signedness.? == .signed) return .f64_convert_i64_s else return .f64_convert_i64_u,
.f32, .f64 => unreachable,
},
},
.demote => if (args.valtype1.? == .f32 and args.valtype2.? == .f64) return .f32_demote_f64 else unreachable,
.promote => if (args.valtype1.? == .f64 and args.valtype2.? == .f32) return .f64_promote_f32 else unreachable,
.reinterpret => switch (args.valtype1.?) {
.i32 => if (args.valtype2.? == .f32) return .i32_reinterpret_f32 else unreachable,
.i64 => if (args.valtype2.? == .f64) return .i64_reinterpret_f64 else unreachable,
.f32 => if (args.valtype2.? == .i32) return .f32_reinterpret_i32 else unreachable,
.f64 => if (args.valtype2.? == .i64) return .f64_reinterpret_i64 else unreachable,
},
.extend => switch (args.valtype1.?) {
.i32 => switch (args.width.?) {
8 => if (args.signedness.? == .signed) return .i32_extend8_s else unreachable,
16 => if (args.signedness.? == .signed) return .i32_extend16_s else unreachable,
else => unreachable,
},
.i64 => switch (args.width.?) {
8 => if (args.signedness.? == .signed) return .i64_extend8_s else unreachable,
16 => if (args.signedness.? == .signed) return .i64_extend16_s else unreachable,
32 => if (args.signedness.? == .signed) return .i64_extend32_s else unreachable,
else => unreachable,
},
.f32, .f64 => unreachable,
},
}
}
test "Wasm - buildOpcode" {
// Make sure buildOpcode is referenced, and test some examples
const i32_const = buildOpcode(.{ .op = .@"const", .valtype1 = .i32 });
const end = buildOpcode(.{ .op = .end });
const local_get = buildOpcode(.{ .op = .local_get });
const i64_extend32_s = buildOpcode(.{ .op = .extend, .valtype1 = .i64, .width = 32, .signedness = .signed });
const f64_reinterpret_i64 = buildOpcode(.{ .op = .reinterpret, .valtype1 = .f64, .valtype2 = .i64 });
try testing.expectEqual(@as(wasm.Opcode, .i32_const), i32_const);
try testing.expectEqual(@as(wasm.Opcode, .end), end);
try testing.expectEqual(@as(wasm.Opcode, .local_get), local_get);
try testing.expectEqual(@as(wasm.Opcode, .i64_extend32_s), i64_extend32_s);
try testing.expectEqual(@as(wasm.Opcode, .f64_reinterpret_i64), f64_reinterpret_i64);
}
pub const Result = union(enum) {
/// The codegen bytes have been appended to `Context.code`
appended: void,
/// The data is managed externally and are part of the `Result`
externally_managed: []const u8,
};
/// Hashmap to store generated `WValue` for each `Inst`
pub const ValueTable = std.AutoHashMapUnmanaged(*Inst, WValue);
/// Code represents the `Code` section of wasm that
/// belongs to a function
pub const Context = struct {
/// Reference to the function declaration the code
/// section belongs to
decl: *Decl,
gpa: *mem.Allocator,
/// Table to save `WValue`'s generated by an `Inst`
values: ValueTable,
/// `bytes` contains the wasm bytecode belonging to the 'code' section.
code: ArrayList(u8),
/// Contains the generated function type bytecode for the current function
/// found in `decl`
func_type_data: ArrayList(u8),
/// The index the next local generated will have
/// NOTE: arguments share the index with locals therefore the first variable
/// will have the index that comes after the last argument's index
local_index: u32 = 0,
/// If codegen fails, an error messages will be allocated and saved in `err_msg`
err_msg: *Module.ErrorMsg,
/// Current block depth. Used to calculate the relative difference between a break
/// and block
block_depth: u32 = 0,
/// List of all locals' types generated throughout this declaration
/// used to emit locals count at start of 'code' section.
locals: std.ArrayListUnmanaged(u8),
/// The Target we're emitting (used to call intInfo)
target: std.Target,
const InnerError = error{
OutOfMemory,
CodegenFail,
/// Can occur when dereferencing a pointer that points to a `Decl` of which the analysis has failed
AnalysisFail,
};
pub fn deinit(self: *Context) void {
self.values.deinit(self.gpa);
self.locals.deinit(self.gpa);
self.* = undefined;
}
/// Sets `err_msg` on `Context` and returns `error.CodegemFail` which is caught in link/Wasm.zig
fn fail(self: *Context, src: LazySrcLoc, comptime fmt: []const u8, args: anytype) InnerError {
const src_loc = src.toSrcLocWithDecl(self.decl);
self.err_msg = try Module.ErrorMsg.create(self.gpa, src_loc, fmt, args);
return error.CodegenFail;
}
/// Resolves the `WValue` for the given instruction `inst`
/// When the given instruction has a `Value`, it returns a constant instead
fn resolveInst(self: Context, inst: *Inst) WValue {
if (!inst.ty.hasCodeGenBits()) return .none;
if (inst.value()) |_| {
return WValue{ .constant = inst };
}
return self.values.get(inst).?; // Instruction does not dominate all uses!
}
/// Using a given `Type`, returns the corresponding wasm Valtype
fn typeToValtype(self: *Context, src: LazySrcLoc, ty: Type) InnerError!wasm.Valtype {
return switch (ty.zigTypeTag()) {
.Float => blk: {
const bits = ty.floatBits(self.target);
if (bits == 16 or bits == 32) break :blk wasm.Valtype.f32;
if (bits == 64) break :blk wasm.Valtype.f64;
return self.fail(src, "Float bit size not supported by wasm: '{d}'", .{bits});
},
.Int => blk: {
const info = ty.intInfo(self.target);
if (info.bits <= 32) break :blk wasm.Valtype.i32;
if (info.bits > 32 and info.bits <= 64) break :blk wasm.Valtype.i64;
return self.fail(src, "Integer bit size not supported by wasm: '{d}'", .{info.bits});
},
.Bool, .Pointer, .Struct => wasm.Valtype.i32,
.Enum => switch (ty.tag()) {
.enum_simple => wasm.Valtype.i32,
else => self.typeToValtype(
src,
ty.cast(Type.Payload.EnumFull).?.data.tag_ty,
),
},
else => self.fail(src, "TODO - Wasm valtype for type '{s}'", .{ty.zigTypeTag()}),
};
}
/// Using a given `Type`, returns the byte representation of its wasm value type
fn genValtype(self: *Context, src: LazySrcLoc, ty: Type) InnerError!u8 {
return wasm.valtype(try self.typeToValtype(src, ty));
}
/// Using a given `Type`, returns the corresponding wasm value type
/// Differently from `genValtype` this also allows `void` to create a block
/// with no return type
fn genBlockType(self: *Context, src: LazySrcLoc, ty: Type) InnerError!u8 {
return switch (ty.tag()) {
.void, .noreturn => wasm.block_empty,
else => self.genValtype(src, ty),
};
}
/// Writes the bytecode depending on the given `WValue` in `val`
fn emitWValue(self: *Context, val: WValue) InnerError!void {
const writer = self.code.writer();
switch (val) {
.block_idx => unreachable, // block_idx cannot be referenced
.multi_value => unreachable, // multi_value can never be written directly, and must be accessed individually
.none, .code_offset => {}, // no-op
.local => |idx| {
try writer.writeByte(wasm.opcode(.local_get));
try leb.writeULEB128(writer, idx);
},
.constant => |inst| try self.emitConstant(inst.src, inst.value().?, inst.ty), // creates a new constant onto the stack
}
}
fn genFunctype(self: *Context) InnerError!void {
assert(self.decl.has_tv);
const ty = self.decl.ty;
const writer = self.func_type_data.writer();
try writer.writeByte(wasm.function_type);
// param types
try leb.writeULEB128(writer, @intCast(u32, ty.fnParamLen()));
if (ty.fnParamLen() != 0) {
const params = try self.gpa.alloc(Type, ty.fnParamLen());
defer self.gpa.free(params);
ty.fnParamTypes(params);
for (params) |param_type| {
// Can we maybe get the source index of each param?
const val_type = try self.genValtype(.{ .node_offset = 0 }, param_type);
try writer.writeByte(val_type);
}
}
// return type
const return_type = ty.fnReturnType();
switch (return_type.tag()) {
.void, .noreturn => try leb.writeULEB128(writer, @as(u32, 0)),
else => |ret_type| {
try leb.writeULEB128(writer, @as(u32, 1));
// Can we maybe get the source index of the return type?
const val_type = try self.genValtype(.{ .node_offset = 0 }, return_type);
try writer.writeByte(val_type);
},
}
}
/// Generates the wasm bytecode for the function declaration belonging to `Context`
pub fn gen(self: *Context, typed_value: TypedValue) InnerError!Result {
switch (typed_value.ty.zigTypeTag()) {
.Fn => {
try self.genFunctype();
// Write instructions
// TODO: check for and handle death of instructions
const mod_fn = blk: {
if (typed_value.val.castTag(.function)) |func| break :blk func.data;
if (typed_value.val.castTag(.extern_fn)) |ext_fn| return Result.appended; // don't need code body for extern functions
unreachable;
};
// Reserve space to write the size after generating the code as well as space for locals count
try self.code.resize(10);
try self.genBody(mod_fn.body);
// finally, write our local types at the 'offset' position
{
leb.writeUnsignedFixed(5, self.code.items[5..10], @intCast(u32, self.locals.items.len));
// offset into 'code' section where we will put our locals types
var local_offset: usize = 10;
// emit the actual locals amount
for (self.locals.items) |local| {
var buf: [6]u8 = undefined;
leb.writeUnsignedFixed(5, buf[0..5], @as(u32, 1));
buf[5] = local;
try self.code.insertSlice(local_offset, &buf);
local_offset += 6;
}
}
const writer = self.code.writer();
try writer.writeByte(wasm.opcode(.end));
// Fill in the size of the generated code to the reserved space at the
// beginning of the buffer.
const size = self.code.items.len - 5 + self.decl.fn_link.wasm.idx_refs.items.len * 5;
leb.writeUnsignedFixed(5, self.code.items[0..5], @intCast(u32, size));
// codegen data has been appended to `code`
return Result.appended;
},
.Array => {
if (typed_value.val.castTag(.bytes)) |payload| {
if (typed_value.ty.sentinel()) |sentinel| {
try self.code.appendSlice(payload.data);
switch (try self.gen(.{
.ty = typed_value.ty.elemType(),
.val = sentinel,
})) {
.appended => return Result.appended,
.externally_managed => |data| {
try self.code.appendSlice(data);
return Result.appended;
},
}
}
return Result{ .externally_managed = payload.data };
} else return self.fail(.{ .node_offset = 0 }, "TODO implement gen for more kinds of arrays", .{});
},
.Int => {
const info = typed_value.ty.intInfo(self.target);
if (info.bits == 8 and info.signedness == .unsigned) {
const int_byte = typed_value.val.toUnsignedInt();
try self.code.append(@intCast(u8, int_byte));
return Result.appended;
}
return self.fail(.{ .node_offset = 0 }, "TODO: Implement codegen for int type: '{}'", .{typed_value.ty});
},
else => |tag| return self.fail(.{ .node_offset = 0 }, "TODO: Implement zig type codegen for type: '{s}'", .{tag}),
}
}
fn genInst(self: *Context, inst: *Inst) InnerError!WValue {
return switch (inst.tag) {
.add => self.genBinOp(inst.castTag(.add).?, .add),
.alloc => self.genAlloc(inst.castTag(.alloc).?),
.arg => self.genArg(inst.castTag(.arg).?),
.bit_and => self.genBinOp(inst.castTag(.bit_and).?, .@"and"),
.bitcast => self.genBitcast(inst.castTag(.bitcast).?),
.bit_or => self.genBinOp(inst.castTag(.bit_or).?, .@"or"),
.block => self.genBlock(inst.castTag(.block).?),
.bool_and => self.genBinOp(inst.castTag(.bool_and).?, .@"and"),
.bool_or => self.genBinOp(inst.castTag(.bool_or).?, .@"or"),
.breakpoint => self.genBreakpoint(inst.castTag(.breakpoint).?),
.br => self.genBr(inst.castTag(.br).?),
.call => self.genCall(inst.castTag(.call).?),
.cmp_eq => self.genCmp(inst.castTag(.cmp_eq).?, .eq),
.cmp_gte => self.genCmp(inst.castTag(.cmp_gte).?, .gte),
.cmp_gt => self.genCmp(inst.castTag(.cmp_gt).?, .gt),
.cmp_lte => self.genCmp(inst.castTag(.cmp_lte).?, .lte),
.cmp_lt => self.genCmp(inst.castTag(.cmp_lt).?, .lt),
.cmp_neq => self.genCmp(inst.castTag(.cmp_neq).?, .neq),
.condbr => self.genCondBr(inst.castTag(.condbr).?),
.constant => unreachable,
.dbg_stmt => WValue.none,
.div => self.genBinOp(inst.castTag(.div).?, .div),
.load => self.genLoad(inst.castTag(.load).?),
.loop => self.genLoop(inst.castTag(.loop).?),
.mul => self.genBinOp(inst.castTag(.mul).?, .mul),
.not => self.genNot(inst.castTag(.not).?),
.ret => self.genRet(inst.castTag(.ret).?),
.retvoid => WValue.none,
.store => self.genStore(inst.castTag(.store).?),
.struct_field_ptr => self.genStructFieldPtr(inst.castTag(.struct_field_ptr).?),
.sub => self.genBinOp(inst.castTag(.sub).?, .sub),
.switchbr => self.genSwitchBr(inst.castTag(.switchbr).?),
.unreach => self.genUnreachable(inst.castTag(.unreach).?),
.xor => self.genBinOp(inst.castTag(.xor).?, .xor),
else => self.fail(.{ .node_offset = 0 }, "TODO: Implement wasm inst: {s}", .{inst.tag}),
};
}
fn genBody(self: *Context, body: ir.Body) InnerError!void {
for (body.instructions) |inst| {
const result = try self.genInst(inst);
try self.values.putNoClobber(self.gpa, inst, result);
}
}
fn genRet(self: *Context, inst: *Inst.UnOp) InnerError!WValue {
// TODO: Implement tail calls
const operand = self.resolveInst(inst.operand);
try self.emitWValue(operand);
try self.code.append(wasm.opcode(.@"return"));
return .none;
}
fn genCall(self: *Context, inst: *Inst.Call) InnerError!WValue {
const func_inst = inst.func.castTag(.constant).?;
const func_val = inst.func.value().?;
const target = blk: {
if (func_val.castTag(.function)) |func| {
break :blk func.data.owner_decl;
} else if (func_val.castTag(.extern_fn)) |ext_fn| {
break :blk ext_fn.data;
}
return self.fail(inst.base.src, "Expected a function, but instead found type '{s}'", .{func_val.tag()});
};
for (inst.args) |arg| {
const arg_val = self.resolveInst(arg);
try self.emitWValue(arg_val);
}
try self.code.append(wasm.opcode(.call));
// The function index immediate argument will be filled in using this data
// in link.Wasm.flush().
try self.decl.fn_link.wasm.idx_refs.append(self.gpa, .{
.offset = @intCast(u32, self.code.items.len),
.decl = target,
});
return .none;
}
fn genAlloc(self: *Context, inst: *Inst.NoOp) InnerError!WValue {
const elem_type = inst.base.ty.elemType();
const initial_index = self.local_index;
switch (elem_type.zigTypeTag()) {
.Struct => {
// for each struct field, generate a local
const struct_data: *Module.Struct = elem_type.castTag(.@"struct").?.data;
try self.locals.ensureCapacity(self.gpa, self.locals.items.len + struct_data.fields.count());
for (struct_data.fields.items()) |entry| {
const val_type = try self.genValtype(
.{ .node_offset = struct_data.node_offset },
entry.value.ty,
);
self.locals.appendAssumeCapacity(val_type);
self.local_index += 1;
}
return WValue{ .multi_value = initial_index };
},
else => {
const valtype = try self.genValtype(inst.base.src, elem_type);
try self.locals.append(self.gpa, valtype);
self.local_index += 1;
return WValue{ .local = initial_index };
},
}
}
fn genStore(self: *Context, inst: *Inst.BinOp) InnerError!WValue {
const writer = self.code.writer();
const lhs = self.resolveInst(inst.lhs);
const rhs = self.resolveInst(inst.rhs);
switch (lhs) {
// When assigning a value to a multi_value such as a struct,
// we simply assign the local_index to the rhs one.
// This allows us to update struct fields without having to individually
// set each local as each field's index will be calculated off the struct's base index
.multi_value => self.values.put(self.gpa, inst.lhs, rhs) catch unreachable, // Instruction does not dominate all uses!
.local => |local| {
try self.emitWValue(rhs);
try writer.writeByte(wasm.opcode(.local_set));
try leb.writeULEB128(writer, lhs.local);
},
else => unreachable,
}
return .none;
}
fn genLoad(self: *Context, inst: *Inst.UnOp) InnerError!WValue {
return self.resolveInst(inst.operand);
}
fn genArg(self: *Context, inst: *Inst.Arg) InnerError!WValue {
// arguments share the index with locals
defer self.local_index += 1;
return WValue{ .local = self.local_index };
}
fn genBinOp(self: *Context, inst: *Inst.BinOp, op: Op) InnerError!WValue {
const lhs = self.resolveInst(inst.lhs);
const rhs = self.resolveInst(inst.rhs);
// it's possible for both lhs and/or rhs to return an offset as well,
// in which case we return the first offset occurance we find.
const offset = blk: {
if (lhs == .code_offset) break :blk lhs.code_offset;
if (rhs == .code_offset) break :blk rhs.code_offset;
break :blk self.code.items.len;
};
try self.emitWValue(lhs);
try self.emitWValue(rhs);
const opcode: wasm.Opcode = buildOpcode(.{
.op = op,
.valtype1 = try self.typeToValtype(inst.base.src, inst.base.ty),
.signedness = if (inst.base.ty.isSignedInt()) .signed else .unsigned,
});
try self.code.append(wasm.opcode(opcode));
return WValue{ .code_offset = offset };
}
fn emitConstant(self: *Context, src: LazySrcLoc, value: Value, ty: Type) InnerError!void {
const writer = self.code.writer();
switch (ty.zigTypeTag()) {
.Int => {
// write opcode
const opcode: wasm.Opcode = buildOpcode(.{
.op = .@"const",
.valtype1 = try self.typeToValtype(src, ty),
});
try writer.writeByte(wasm.opcode(opcode));
// write constant
switch (ty.intInfo(self.target).signedness) {
.signed => try leb.writeILEB128(writer, value.toSignedInt()),
.unsigned => try leb.writeILEB128(writer, value.toUnsignedInt()),
}
},
.Bool => {
// write opcode
try writer.writeByte(wasm.opcode(.i32_const));
// write constant
try leb.writeILEB128(writer, value.toSignedInt());
},
.Float => {
// write opcode
const opcode: wasm.Opcode = buildOpcode(.{
.op = .@"const",
.valtype1 = try self.typeToValtype(src, ty),
});
try writer.writeByte(wasm.opcode(opcode));
// write constant
switch (ty.floatBits(self.target)) {
0...32 => try writer.writeIntLittle(u32, @bitCast(u32, value.toFloat(f32))),
64 => try writer.writeIntLittle(u64, @bitCast(u64, value.toFloat(f64))),
else => |bits| return self.fail(src, "Wasm TODO: emitConstant for float with {d} bits", .{bits}),
}
},
.Pointer => {
if (value.castTag(.decl_ref)) |payload| {
const decl = payload.data;
// offset into the offset table within the 'data' section
const ptr_width = self.target.cpu.arch.ptrBitWidth() / 8;
try writer.writeByte(wasm.opcode(.i32_const));
try leb.writeULEB128(writer, decl.link.wasm.offset_index * ptr_width);
// memory instruction followed by their memarg immediate
// memarg ::== x:u32, y:u32 => {align x, offset y}
try writer.writeByte(wasm.opcode(.i32_load));
try leb.writeULEB128(writer, @as(u32, 0));
try leb.writeULEB128(writer, @as(u32, 0));
} else return self.fail(src, "Wasm TODO: emitConstant for other const pointer tag {s}", .{value.tag()});
},
.Void => {},
.Enum => {
if (value.castTag(.enum_field_index)) |field_index| {
switch (ty.tag()) {
.enum_simple => {
try writer.writeByte(wasm.opcode(.i32_const));
try leb.writeULEB128(writer, field_index.data);
},
.enum_full, .enum_nonexhaustive => {
const enum_full = ty.cast(Type.Payload.EnumFull).?.data;
if (enum_full.values.count() != 0) {
const tag_val = enum_full.values.entries.items[field_index.data].key;
try self.emitConstant(src, tag_val, enum_full.tag_ty);
} else {
try writer.writeByte(wasm.opcode(.i32_const));
try leb.writeULEB128(writer, field_index.data);
}
},
else => unreachable,
}
} else {
var int_tag_buffer: Type.Payload.Bits = undefined;
const int_tag_ty = ty.intTagType(&int_tag_buffer);
try self.emitConstant(src, value, int_tag_ty);
}
},
else => |zig_type| return self.fail(src, "Wasm TODO: emitConstant for zigTypeTag {s}", .{zig_type}),
}
}
fn genBlock(self: *Context, block: *Inst.Block) InnerError!WValue {
const block_ty = try self.genBlockType(block.base.src, block.base.ty);
try self.startBlock(.block, block_ty, null);
block.codegen = .{
// we don't use relocs, so using `relocs` is illegal behaviour.
.relocs = undefined,
// Here we set the current block idx, so breaks know the depth to jump
// to when breaking out.
.mcv = @bitCast(AnyMCValue, WValue{ .block_idx = self.block_depth }),
};
try self.genBody(block.body);
try self.endBlock();
return .none;
}
/// appends a new wasm block to the code section and increases the `block_depth` by 1
fn startBlock(self: *Context, block_type: wasm.Opcode, valtype: u8, with_offset: ?usize) !void {
self.block_depth += 1;
if (with_offset) |offset| {
try self.code.insert(offset, wasm.opcode(block_type));
try self.code.insert(offset + 1, valtype);
} else {
try self.code.append(wasm.opcode(block_type));
try self.code.append(valtype);
}
}
/// Ends the current wasm block and decreases the `block_depth` by 1
fn endBlock(self: *Context) !void {
try self.code.append(wasm.opcode(.end));
self.block_depth -= 1;
}
fn genLoop(self: *Context, loop: *Inst.Loop) InnerError!WValue {
const loop_ty = try self.genBlockType(loop.base.src, loop.base.ty);
try self.startBlock(.loop, loop_ty, null);
try self.genBody(loop.body);
// breaking to the index of a loop block will continue the loop instead
try self.code.append(wasm.opcode(.br));
try leb.writeULEB128(self.code.writer(), @as(u32, 0));
try self.endBlock();
return .none;
}
fn genCondBr(self: *Context, condbr: *Inst.CondBr) InnerError!WValue {
const condition = self.resolveInst(condbr.condition);
const writer = self.code.writer();
// TODO: Handle death instructions for then and else body
// insert blocks at the position of `offset` so
// the condition can jump to it
const offset = switch (condition) {
.code_offset => |offset| offset,
else => blk: {
const offset = self.code.items.len;
try self.emitWValue(condition);
break :blk offset;
},
};
const block_ty = try self.genBlockType(condbr.base.src, condbr.base.ty);
try self.startBlock(.block, block_ty, offset);
// we inserted the block in front of the condition
// so now check if condition matches. If not, break outside this block
// and continue with the then codepath
try writer.writeByte(wasm.opcode(.br_if));
try leb.writeULEB128(writer, @as(u32, 0));
try self.genBody(condbr.else_body);
try self.endBlock();
// Outer block that matches the condition
try self.genBody(condbr.then_body);
return .none;
}
fn genCmp(self: *Context, inst: *Inst.BinOp, op: std.math.CompareOperator) InnerError!WValue {
const ty = inst.lhs.ty.tag();
// save offset, so potential conditions can insert blocks in front of
// the comparison that we can later jump back to
const offset = self.code.items.len;
const lhs = self.resolveInst(inst.lhs);
const rhs = self.resolveInst(inst.rhs);
try self.emitWValue(lhs);
try self.emitWValue(rhs);
const signedness: std.builtin.Signedness = blk: {
// by default we tell the operand type is unsigned (i.e. bools and enum values)
if (inst.lhs.ty.zigTypeTag() != .Int) break :blk .unsigned;
// incase of an actual integer, we emit the correct signedness
break :blk inst.lhs.ty.intInfo(self.target).signedness;
};
const opcode: wasm.Opcode = buildOpcode(.{
.valtype1 = try self.typeToValtype(inst.base.src, inst.lhs.ty),
.op = switch (op) {
.lt => .lt,
.lte => .le,
.eq => .eq,
.neq => .ne,
.gte => .ge,
.gt => .gt,
},
.signedness = signedness,
});
try self.code.append(wasm.opcode(opcode));
return WValue{ .code_offset = offset };
}
fn genBr(self: *Context, br: *Inst.Br) InnerError!WValue {
// if operand has codegen bits we should break with a value
if (br.operand.ty.hasCodeGenBits()) {
const operand = self.resolveInst(br.operand);
try self.emitWValue(operand);
}
// every block contains a `WValue` with its block index.
// We then determine how far we have to jump to it by substracting it from current block depth
const wvalue = @bitCast(WValue, br.block.codegen.mcv);
const idx: u32 = self.block_depth - wvalue.block_idx;
const writer = self.code.writer();
try writer.writeByte(wasm.opcode(.br));
try leb.writeULEB128(writer, idx);
return .none;
}
fn genNot(self: *Context, not: *Inst.UnOp) InnerError!WValue {
const offset = self.code.items.len;
const operand = self.resolveInst(not.operand);
try self.emitWValue(operand);
// wasm does not have booleans nor the `not` instruction, therefore compare with 0
// to create the same logic
const writer = self.code.writer();
try writer.writeByte(wasm.opcode(.i32_const));
try leb.writeILEB128(writer, @as(i32, 0));
try writer.writeByte(wasm.opcode(.i32_eq));
return WValue{ .code_offset = offset };
}
fn genBreakpoint(self: *Context, breakpoint: *Inst.NoOp) InnerError!WValue {
// unsupported by wasm itself. Can be implemented once we support DWARF
// for wasm
return .none;
}
fn genUnreachable(self: *Context, unreach: *Inst.NoOp) InnerError!WValue {
try self.code.append(wasm.opcode(.@"unreachable"));
return .none;
}
fn genBitcast(self: *Context, bitcast: *Inst.UnOp) InnerError!WValue {
return self.resolveInst(bitcast.operand);
}
fn genStructFieldPtr(self: *Context, inst: *Inst.StructFieldPtr) InnerError!WValue {
const struct_ptr = self.resolveInst(inst.struct_ptr);
return WValue{ .local = struct_ptr.multi_value + @intCast(u32, inst.field_index) };
}
fn genSwitchBr(self: *Context, inst: *Inst.SwitchBr) InnerError!WValue {
const target = self.resolveInst(inst.target);
const target_ty = inst.target.ty;
const valtype = try self.typeToValtype(.{ .node_offset = 0 }, target_ty);
const blocktype = try self.genBlockType(inst.base.src, inst.base.ty);
const signedness: std.builtin.Signedness = blk: {
// by default we tell the operand type is unsigned (i.e. bools and enum values)
if (target_ty.zigTypeTag() != .Int) break :blk .unsigned;
// incase of an actual integer, we emit the correct signedness
break :blk target_ty.intInfo(self.target).signedness;
};
for (inst.cases) |case| {
// create a block for each case, when the condition does not match we break out of it
try self.startBlock(.block, blocktype, null);
try self.emitWValue(target);
try self.emitConstant(.{ .node_offset = 0 }, case.item, target_ty);
const opcode = buildOpcode(.{
.valtype1 = valtype,
.op = .ne, // not equal because we jump out the block if it does not match the condition
.signedness = signedness,
});
try self.code.append(wasm.opcode(opcode));
try self.code.append(wasm.opcode(.br_if));
try leb.writeULEB128(self.code.writer(), @as(u32, 0));
// emit our block code
try self.genBody(case.body);
// end the block we created earlier
try self.endBlock();
}
// finally, emit the else case if it exists. Here we will not have to
// check for a condition, so also no need to emit a block.
try self.genBody(inst.else_body);
return .none;
}
}; | src/codegen/wasm.zig |
const std = @import("std");
const aoc = @import("aoc-lib.zig");
const fmtSliceHexLower = std.fmt.fmtSliceHexLower;
const Game = struct {
d1: []u8,
d2: []u8,
alloc: std.mem.Allocator,
debug: bool,
pub fn init(alloc: std.mem.Allocator, in: [][]const u8) !*Game {
var self = try alloc.create(Game);
var l: usize = 0;
var it = std.mem.split(u8, in[0], "\n");
while (it.next()) |_| {
l += 1;
}
l -= 1;
self.d1 = try alloc.alloc(u8, l);
it = std.mem.split(u8, in[0], "\n");
_ = it.next();
var i: usize = 0;
while (it.next()) |line| {
self.d1[i] = try std.fmt.parseUnsigned(u8, line, 10);
i += 1;
}
l = 0;
it = std.mem.split(u8, in[1], "\n");
while (it.next()) |_| {
l += 1;
}
l -= 1;
self.d2 = try alloc.alloc(u8, l);
it = std.mem.split(u8, in[1], "\n");
_ = it.next();
i = 0;
while (it.next()) |line| {
self.d2[i] = try std.fmt.parseUnsigned(u8, line, 10);
i += 1;
}
self.alloc = alloc;
self.debug = false;
return self;
}
pub fn deinit(self: *Game) void {
self.alloc.free(self.d1);
self.alloc.free(self.d2);
self.alloc.destroy(self);
}
pub fn Score(d: []const u8) usize {
var s: usize = 0;
var i: usize = 1;
while (i <= d.len) : (i += 1) {
s += (1 + d.len - i) * @as(usize, d[i - 1]);
}
return s;
}
const Result = struct {
player: usize,
deck: []const u8,
};
pub fn copyd(all: anytype, d: []u8) []u8 {
var result = all.alloc(u8, d.len) catch unreachable;
std.mem.copy(u8, result[0..], d);
return result;
}
pub fn append(all: anytype, d: []u8, a: u8, b: u8) []u8 {
var result = all.alloc(u8, d.len + 2) catch unreachable;
std.mem.copy(u8, result[0..], d);
result[d.len] = a;
result[d.len + 1] = b;
all.free(d);
return result;
}
pub fn tail(all: anytype, d: []u8) []u8 {
var result = all.alloc(u8, d.len - 1) catch unreachable;
std.mem.copy(u8, result[0..], d[1..d.len]);
all.free(d);
return result;
}
pub fn subdeck(all: anytype, d: []u8, c: u8) []u8 {
var result = all.alloc(u8, c) catch unreachable;
std.mem.copy(u8, result[0..], d[0..c]);
return result;
}
pub fn key(d1: []u8, d2: []u8) usize {
return Score(d1) * (31 + Score(d2));
}
pub fn Combat(g: *Game, in: [2][]u8, part2: bool) Result {
var round: usize = 1;
var arenaAllocator = std.heap.ArenaAllocator.init(g.alloc);
defer arenaAllocator.deinit();
var arena = arenaAllocator.allocator();
var d = [2][]u8{ copyd(arena, in[0]), copyd(arena, in[1]) };
var seen = std.AutoHashMap(usize, bool).init(arena);
defer seen.deinit();
while (d[0].len > 0 and d[1].len > 0) {
if (g.debug) {
std.debug.print("{}: d1={x} d2={x}\n", .{ round, fmtSliceHexLower(d[0]), fmtSliceHexLower(d[1]) });
}
const k = key(d[0], d[1]);
if (seen.contains(k)) {
if (g.debug) {
std.debug.print("{}: p1! (seen)\n", .{round});
}
return Result{ .player = 0, .deck = copyd(g.alloc, d[0]) };
}
seen.put(k, true) catch unreachable;
const c: [2]u8 = [2]u8{ d[0][0], d[1][0] };
d[0] = tail(arena, d[0]);
d[1] = tail(arena, d[1]);
if (g.debug) {
std.debug.print("{}: c1={} c2={}\n", .{ round, c[0], c[1] });
}
var w: usize = 0;
if (part2 and d[0].len >= c[0] and d[1].len >= c[1]) {
const sd = [2][]u8{
subdeck(arena, d[0], c[0]),
subdeck(arena, d[1], c[1]),
};
defer arena.free(sd[0]);
defer arena.free(sd[1]);
if (g.debug) {
std.debug.print("{}: subgame\n", .{round});
}
const subres = g.Combat(sd, part2);
w = subres.player;
g.alloc.free(subres.deck);
} else {
w = if (c[0] > c[1]) 0 else 1;
}
if (g.debug) {
std.debug.print("{}: p{}!\n", .{ round, w + 1 });
}
d[w] = append(arena, d[w], c[w], c[1 - w]);
round += 1;
}
if (d[0].len > 0) {
if (g.debug) {
std.debug.print("p1!\n", .{});
}
return Result{ .player = 0, .deck = copyd(g.alloc, d[0]) };
} else {
if (g.debug) {
std.debug.print("p2!\n", .{});
}
return Result{ .player = 1, .deck = copyd(g.alloc, d[1]) };
}
}
pub fn Part1(g: *Game) usize {
var d = [_][]u8{ g.d1, g.d2 };
var r = g.Combat(d, false);
defer g.alloc.free(r.deck);
return Score(r.deck);
}
pub fn Part2(g: *Game) usize {
var d = [_][]u8{ g.d1, g.d2 };
var r = g.Combat(d, true);
defer g.alloc.free(r.deck);
return Score(r.deck);
}
};
test "seen" {
const test1 = aoc.readChunks(aoc.talloc, aoc.test1file);
defer aoc.talloc.free(test1);
const inp = aoc.readChunks(aoc.talloc, aoc.inputfile);
defer aoc.talloc.free(inp);
var seen = std.AutoHashMap(usize, bool).init(aoc.talloc);
defer seen.deinit();
var g1 = try Game.init(aoc.talloc, test1);
defer g1.deinit();
var k1 = Game.key(g1.d1, g1.d2);
var k2 = Game.key(g1.d2, g1.d1);
try aoc.assertEq(false, seen.contains(k1));
try aoc.assertEq(false, seen.contains(k2));
try seen.put(k1, true);
try aoc.assertEq(true, seen.contains(k1));
try aoc.assertEq(false, seen.contains(k2));
try seen.put(k2, true);
try aoc.assertEq(true, seen.contains(k1));
try aoc.assertEq(true, seen.contains(k2));
var g = try Game.init(aoc.talloc, inp);
defer g.deinit();
k1 = Game.key(g.d1, g.d2);
k2 = Game.key(g.d2, g.d1);
try aoc.assertEq(false, seen.contains(k1));
try aoc.assertEq(false, seen.contains(k2));
try seen.put(k1, true);
try aoc.assertEq(true, seen.contains(k1));
try aoc.assertEq(false, seen.contains(k2));
try seen.put(k2, true);
try aoc.assertEq(true, seen.contains(k1));
try aoc.assertEq(true, seen.contains(k2));
}
test "examples" {
const test1 = aoc.readChunks(aoc.talloc, aoc.test1file);
defer aoc.talloc.free(test1);
const inp = aoc.readChunks(aoc.talloc, aoc.inputfile);
defer aoc.talloc.free(inp);
var g1 = try Game.init(aoc.talloc, test1);
defer g1.deinit();
try aoc.assertEq(@as(usize, 306), g1.Part1());
try aoc.assertEq(@as(usize, 291), g1.Part2());
var g2 = try Game.init(aoc.talloc, inp);
defer g2.deinit();
try aoc.assertEq(@as(usize, 32856), g2.Part1());
try aoc.assertEq(@as(usize, 33805), g2.Part2());
}
fn day22(inp: []const u8, bench: bool) anyerror!void {
const chunks = aoc.readChunks(aoc.halloc, inp);
defer aoc.halloc.free(chunks);
var g = try Game.init(aoc.halloc, chunks);
defer g.deinit();
var p1 = g.Part1();
var p2 = g.Part2();
if (!bench) {
try aoc.print("Part 1: {}\nPart 2: {}\n", .{ p1, p2 });
}
}
pub fn main() anyerror!void {
try aoc.benchme(aoc.input(), day22);
} | 2020/22/aoc.zig |
const QuerySet = @import("QuerySet.zig");
const RenderPassColorAttachment = @import("structs.zig").RenderPassColorAttachment;
const RenderPassDepthStencilAttachment = @import("structs.zig").RenderPassDepthStencilAttachment;
const RenderPassTimestampWrite = @import("structs.zig").RenderPassTimestampWrite;
const RenderPipeline = @import("RenderPipeline.zig");
const Buffer = @import("Buffer.zig");
const RenderBundle = @import("RenderBundle.zig");
const BindGroup = @import("BindGroup.zig");
const Color = @import("data.zig").Color;
const IndexFormat = @import("enums.zig").IndexFormat;
const RenderPassEncoder = @This();
/// The type erased pointer to the RenderPassEncoder implementation
/// Equal to c.WGPURenderPassEncoder for NativeInstance.
ptr: *anyopaque,
vtable: *const VTable,
pub const VTable = struct {
reference: fn (ptr: *anyopaque) void,
release: fn (ptr: *anyopaque) void,
draw: fn (ptr: *anyopaque, vertex_count: u32, instance_count: u32, first_vertex: u32, first_instance: u32) void,
drawIndexed: fn (
ptr: *anyopaque,
index_count: u32,
instance_count: u32,
first_index: u32,
base_vertex: i32,
first_instance: u32,
) void,
drawIndexedIndirect: fn (ptr: *anyopaque, indirect_buffer: Buffer, indirect_offset: u64) void,
drawIndirect: fn (ptr: *anyopaque, indirect_buffer: Buffer, indirect_offset: u64) void,
beginOcclusionQuery: fn (ptr: *anyopaque, query_index: u32) void,
endOcclusionQuery: fn (ptr: *anyopaque) void,
end: fn (ptr: *anyopaque) void,
executeBundles: fn (ptr: *anyopaque, bundles: []RenderBundle) void,
insertDebugMarker: fn (ptr: *anyopaque, marker_label: [*:0]const u8) void,
popDebugGroup: fn (ptr: *anyopaque) void,
pushDebugGroup: fn (ptr: *anyopaque, group_label: [*:0]const u8) void,
setBindGroup: fn (ptr: *anyopaque, group_index: u32, group: BindGroup, dynamic_offsets: []const u32) void,
setBlendConstant: fn (ptr: *anyopaque, color: *const Color) void,
setIndexBuffer: fn (ptr: *anyopaque, buffer: Buffer, format: IndexFormat, offset: u64, size: u64) void,
setLabel: fn (ptr: *anyopaque, label: [:0]const u8) void,
setPipeline: fn (ptr: *anyopaque, pipeline: RenderPipeline) void,
setScissorRect: fn (ptr: *anyopaque, x: u32, y: u32, width: u32, height: u32) void,
setStencilReference: fn (ptr: *anyopaque, reference: u32) void,
setVertexBuffer: fn (ptr: *anyopaque, slot: u32, buffer: Buffer, offset: u64, size: u64) void,
setViewport: fn (ptr: *anyopaque, x: f32, y: f32, width: f32, height: f32, min_depth: f32, max_depth: f32) void,
writeTimestamp: fn (ptr: *anyopaque, query_set: QuerySet, query_index: u32) void,
};
pub inline fn reference(pass: RenderPassEncoder) void {
pass.vtable.reference(pass.ptr);
}
pub inline fn release(pass: RenderPassEncoder) void {
pass.vtable.release(pass.ptr);
}
pub inline fn draw(
pass: RenderPassEncoder,
vertex_count: u32,
instance_count: u32,
first_vertex: u32,
first_instance: u32,
) void {
pass.vtable.draw(pass.ptr, vertex_count, instance_count, first_vertex, first_instance);
}
pub inline fn drawIndexed(
pass: RenderPassEncoder,
index_count: u32,
instance_count: u32,
first_index: u32,
base_vertex: i32,
first_instance: u32,
) void {
pass.vtable.drawIndexed(pass.ptr, index_count, instance_count, first_index, base_vertex, first_instance);
}
pub inline fn drawIndexedIndirect(pass: RenderPassEncoder, indirect_buffer: Buffer, indirect_offset: u64) void {
pass.vtable.drawIndexedIndirect(pass.ptr, indirect_buffer, indirect_offset);
}
pub inline fn drawIndirect(pass: RenderPassEncoder, indirect_buffer: Buffer, indirect_offset: u64) void {
pass.vtable.drawIndirect(pass.ptr, indirect_buffer, indirect_offset);
}
pub inline fn beginOcclusionQuery(pass: RenderPassEncoder, query_index: u32) void {
pass.vtable.beginOcclusionQuery(pass.ptr, query_index);
}
pub inline fn endOcclusionQuery(pass: RenderPassEncoder) void {
pass.vtable.endOcclusionQuery(pass.ptr);
}
pub inline fn end(pass: RenderPassEncoder) void {
pass.vtable.end(pass.ptr);
}
pub inline fn executeBundles(pass: RenderPassEncoder, bundles: []RenderBundle) void {
pass.vtable.executeBundles(pass.ptr, bundles);
}
pub inline fn insertDebugMarker(pass: RenderPassEncoder, marker_label: [*:0]const u8) void {
pass.vtable.insertDebugMarker(pass.ptr, marker_label);
}
pub inline fn popDebugGroup(pass: RenderPassEncoder) void {
pass.vtable.popDebugGroup(pass.ptr);
}
pub inline fn pushDebugGroup(pass: RenderPassEncoder, group_label: [*:0]const u8) void {
pass.vtable.pushDebugGroup(pass.ptr, group_label);
}
pub inline fn setBindGroup(
pass: RenderPassEncoder,
group_index: u32,
group: BindGroup,
dynamic_offsets: []const u32,
) void {
pass.vtable.setBindGroup(pass.ptr, group_index, group, dynamic_offsets);
}
pub inline fn setBlendConstant(pass: RenderPassEncoder, color: *const Color) void {
pass.vtable.setBlendConstant(pass.ptr, color);
}
pub inline fn setIndexBuffer(
pass: RenderPassEncoder,
buffer: Buffer,
format: IndexFormat,
offset: u64,
size: u64,
) void {
pass.vtable.setIndexBuffer(pass.ptr, buffer, format, offset, size);
}
pub inline fn setLabel(pass: RenderPassEncoder, label: [:0]const u8) void {
pass.vtable.setLabel(pass.ptr, label);
}
pub inline fn setPipeline(pass: RenderPassEncoder, pipeline: RenderPipeline) void {
pass.vtable.setPipeline(pass.ptr, pipeline);
}
pub inline fn setScissorRect(pass: RenderPassEncoder, x: u32, y: u32, width: u32, height: u32) void {
pass.vtable.setScissorRect(pass.ptr, x, y, width, height);
}
pub inline fn setStencilReference(pass: RenderPassEncoder, ref: u32) void {
pass.vtable.setStencilReference(pass.ptr, ref);
}
pub inline fn setVertexBuffer(
pass: RenderPassEncoder,
slot: u32,
buffer: Buffer,
offset: u64,
size: u64,
) void {
pass.vtable.setVertexBuffer(pass.ptr, slot, buffer, offset, size);
}
pub inline fn setViewport(
pass: RenderPassEncoder,
x: f32,
y: f32,
width: f32,
height: f32,
min_depth: f32,
max_depth: f32,
) void {
pass.vtable.setViewport(pass.ptr, x, y, width, height, min_depth, max_depth);
}
pub inline fn writeTimestamp(pass: RenderPassEncoder, query_set: QuerySet, query_index: u32) void {
pass.vtable.writeTimestamp(pass.ptr, query_set, query_index);
}
pub const Descriptor = struct {
label: ?[*:0]const u8 = null,
color_attachments: []const RenderPassColorAttachment,
depth_stencil_attachment: ?*const RenderPassDepthStencilAttachment,
occlusion_query_set: ?QuerySet = null,
timestamp_writes: ?[]RenderPassTimestampWrite = null,
};
test {
_ = VTable;
_ = reference;
_ = release;
_ = draw;
_ = drawIndexed;
_ = drawIndexedIndirect;
_ = drawIndirect;
_ = beginOcclusionQuery;
_ = endOcclusionQuery;
_ = end;
_ = executeBundles;
_ = insertDebugMarker;
_ = popDebugGroup;
_ = pushDebugGroup;
_ = setBindGroup;
_ = setBlendConstant;
_ = setIndexBuffer;
_ = setLabel;
_ = setPipeline;
_ = setPipeline;
_ = setStencilReference;
_ = setVertexBuffer;
_ = setViewport;
_ = writeTimestamp;
_ = Descriptor;
} | gpu/src/RenderPassEncoder.zig |
const std = @import("std");
//--------------------------------------------------------------------------------------------------
pub fn part1() anyerror!void
{
const file = std.fs.cwd().openFile("data/day01_input.txt", .{}) catch |err| label:
{
std.debug.print("unable to open file: {e}\n", .{err});
const stderr = std.io.getStdErr();
break :label stderr;
};
defer file.close();
const file_size = try file.getEndPos();
std.log.info("File size {}", .{file_size});
//var arena = std.heap.ArenaAllocator.init(std.heap.page_allocator);
//defer arena.deinit();
//const allocator = &arena.allocator;
//const contents = try file.readToEndAlloc(allocator, file_size);
//defer allocator.free(contents);
var reader = std.io.bufferedReader(file.reader());
var istream = reader.reader();
var buf: [8]u8 = undefined;
var increase_count: u32 = 0;
var last_val: u32 = std.math.maxInt(u32);
while (try istream.readUntilDelimiterOrEof(&buf, '\n')) |line|
{
//std.log.info("{s}", .{line});
var current_val = std.fmt.parseInt(u32, line, 10) catch std.math.minInt(u32);
if (current_val > last_val)
{
increase_count += 1;
}
last_val = current_val;
}
std.log.info("Part 1 increases: {d}", .{increase_count});
}
//--------------------------------------------------------------------------------------------------
pub fn part2() anyerror!void
{
const file = std.fs.cwd().openFile("data/day01_input.txt", .{}) catch |err| label:
{
std.debug.print("unable to open file: {e}\n", .{err});
const stderr = std.io.getStdErr();
break :label stderr;
};
defer file.close();
var reader = std.io.bufferedReader(file.reader());
var istream = reader.reader();
var buf: [8]u8 = undefined;
var increase_count: u32 = 0;
var head_pos: u32 = 0;
var window: [3]u32 = undefined;
var total: u32 = 0;
while (try istream.readUntilDelimiterOrEof(&buf, '\n')) |line|
{
var current_val = std.fmt.parseInt(u32, line, 10) catch std.math.minInt(u32);
// Priming the window for the first few round
if (head_pos < 3) {
window[head_pos] = current_val;
total += current_val;
head_pos += 1;
}
else
{
var new_total = total + current_val - window[0];
if (new_total > total)
{
increase_count += 1;
}
// Slide the 'sliding window'
window[0] = window[1];
window[1] = window[2];
window[2] = current_val;
total = new_total;
}
}
std.log.info("Part 2: increases: {d}", .{increase_count});
}
//--------------------------------------------------------------------------------------------------
pub fn main() anyerror!void
{
try part1();
try part2();
}
//-------------------------------------------------------------------------------------------------- | src/day01.zig |
const std = @import("std");
const tools = @import("tools");
const with_trace = false;
fn trace(comptime fmt: []const u8, args: anytype) void {
if (with_trace) std.debug.print(fmt, args);
}
const assert = std.debug.assert;
pub const main = tools.defaultMain("2021/day23.txt", run);
// positions:
//#############
//#abcdefghijk#
//###l#m#n#o###
// #p#q#r#s#
// #t#u#v#w#
// #x#y#z#{#
// #########
const Position = u8;
const all_positions_1 = [_]Position{ 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's' };
const all_positions_2 = [_]Position{ 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z', '{' };
const canonical_paths = [_][]const Position{
"abclptx", "abcdemquy", "abcdefgnrvz", "abcdefghiosw{", // chemins possibles depuis 'a' + retours
"kjiosw{", "kjihgnrvz", "kjihgfemquy", "kjihgfedclptx", // chemins possibles depuis 'k' + retours
"xtplcdemquy", "xtplcdefgnrvz", "xtplcdefghiosw{", // chemins possibles depuis 'p' + retours
"yuqmefgnrvz", "yuqmefghiosw{", // chemins possibles depuis 'q' + retours
"zvrnghiosw{", // chemins possibles depuis 'r' + retours
};
const no_parking_zones: []const Position = "cegi"; // TODO? merge into path_matrix to avoid separate test?
const target_zone = [4][4]Position{
.{ 'l', 'p', 't', 'x' },
.{ 'm', 'q', 'u', 'y' },
.{ 'n', 'r', 'v', 'z' },
.{ 'o', 's', 'w', '{' },
};
const move_energy_cost = [4]u32{ 1, 10, 100, 1000 };
const paths_matrix = blk: {
@setEvalBranchQuota(80000);
var paths: [all_positions_2.len][all_positions_2.len][]const Position = undefined;
for (all_positions_2) |from, i| {
assert(from == i + 'a');
const from_is_rooom = (from >= 'l');
for (all_positions_2) |to, j| {
const to_is_rooom = (to >= 'l');
paths[i][j] = &[0]Position{};
if (from == to) continue;
// "in the hallway, it will stay in that spot until it can move into a room"
if (!to_is_rooom and !from_is_rooom) continue;
// "never stop on the space immediately outside any room."
if (std.mem.indexOfScalar(Position, no_parking_zones, from) != null) continue;
if (std.mem.indexOfScalar(Position, no_parking_zones, to) != null) continue;
for (canonical_paths) |p| {
if (std.mem.indexOfScalar(Position, p, from)) |idx_from| {
if (std.mem.indexOfScalar(Position, p[idx_from..], to)) |len_to| {
const path = p[idx_from + 1 .. idx_from + len_to + 1];
paths[i][j] = path;
}
}
if (std.mem.indexOfScalar(Position, p, to)) |idx_to| {
if (std.mem.indexOfScalar(Position, p[idx_to..], from)) |len_from| {
const path = p[idx_to .. idx_to + len_from];
paths[i][j] = path;
}
}
}
}
}
break :blk paths;
};
fn State(room_sz: u32) type {
return struct {
amphipods: [4][room_sz]Position,
fn distanceToTarget(s: @This()) u32 {
var distance: u32 = 0;
for (s.amphipods) |pair, i| {
for (pair) |pos, j| {
const d = @intCast(u32, paths_matrix[target_zone[i][j] - 'a'][pos - 'a'].len);
distance += move_energy_cost[i] * d;
}
}
return distance;
}
fn isFree(s: @This(), p: Position) bool {
var occupied: u32 = 0;
for (s.amphipods) |pair| {
for (pair) |pos| {
occupied += @boolToInt(pos == p);
}
}
return occupied == 0;
}
};
}
fn searchLowestEnergySolution(allocator: std.mem.Allocator, comptime StateType: type, initial_state: StateType, all_positions: []const Position) !u32 {
var arena_alloc = std.heap.ArenaAllocator.init(allocator);
defer arena_alloc.deinit();
const arena = arena_alloc.allocator(); // for traces
const room_sz = initial_state.amphipods[0].len;
const Bfs = tools.BestFirstSearch(StateType, []u8);
var bfs = Bfs.init(allocator);
defer bfs.deinit();
try bfs.insert(Bfs.Node{
.rating = 100000,
.cost = 0,
.state = initial_state,
.trace = "",
});
var best_dist: u32 = 100000;
var best_energy: u32 = 100000;
while (bfs.pop()) |n| {
const cur_minimum_energy_to_target = n.rating;
if (cur_minimum_energy_to_target > best_energy) continue;
const d = n.state.distanceToTarget();
if (d == 0) {
if (best_energy > n.cost) {
best_energy = n.cost;
trace("solution: {d} {s}\n", .{ n.cost, n.trace });
}
continue;
}
if (d < best_dist) {
best_dist = d;
trace("best so far...: d={}, e={} {s}\n", .{ d, n.cost, n.trace });
}
for (n.state.amphipods) |pair, i| {
for (pair) |from, j| {
for (all_positions) |to| {
const to_is_room = (to >= 'l');
const path = paths_matrix[from - 'a'][to - 'a'];
if (path.len == 0) continue;
if (to_is_room) {
// "never move from the hallway into a room unless that room is their destination room..."
// "... and that room contains no amphipods which do not also have that room as their own destination"
const ok = good_room: for (target_zone[i][0..room_sz]) |zone, room_idx| {
if (zone == to) {
for (target_zone[i][0..room_sz]) |zone2, room_idx2| {
if (room_idx2 <= room_idx) {
if (!n.state.isFree(zone2)) break :good_room false;
} else {
const is_friend = for (pair) |friend| {
if (friend == zone2) break true;
} else false;
if (!is_friend) break :good_room false;
}
}
break true;
}
} else false;
if (!ok) continue;
}
// moving into an unoccupied open space
assert(path[0] == to or path[path.len - 1] == to);
const is_free = for (path) |p| {
if (!n.state.isFree(p)) break false;
} else true;
if (!is_free) continue;
const new_energy = n.cost + @intCast(u32, path.len * move_energy_cost[i]);
if (new_energy >= best_energy) continue;
var new = n;
new.state.amphipods[i][j] = to;
std.sort.sort(Position, &new.state.amphipods[i], {}, comptime std.sort.asc(Position)); // pour éviter de multiplier les états différents mais équivalents
new.cost = new_energy;
const minimum_energy_to_target = new_energy + new.state.distanceToTarget();
new.rating = @intCast(i32, minimum_energy_to_target);
if (with_trace)
new.trace = try std.fmt.allocPrint(arena, "{s},{c}:{c}->{c}", .{ n.trace, @intCast(u8, i + 'A'), from, to });
if (new.rating > best_energy) continue;
try bfs.insert(new);
}
}
}
}
return best_energy;
}
pub fn run(input: []const u8, gpa: std.mem.Allocator) tools.RunError![2][]const u8 {
const State_1 = State(2);
const initial_state_1 = blk: {
var state = State_1{ .amphipods = undefined };
var pop = [4]u2{ 0, 0, 0, 0 };
var it = std.mem.tokenize(u8, input, "\n");
if (tools.match_pattern("#############", it.next().?) == null) return error.UnsupportedInput;
if (tools.match_pattern("#...........#", it.next().?) == null) return error.UnsupportedInput;
if (tools.match_pattern("###{}#{}#{}#{}###", it.next().?)) |val| {
state.amphipods[val[0].lit[0] - 'A'][pop[val[0].lit[0] - 'A']] = target_zone[0][0];
pop[val[0].lit[0] - 'A'] += 1;
state.amphipods[val[1].lit[0] - 'A'][pop[val[1].lit[0] - 'A']] = target_zone[1][0];
pop[val[1].lit[0] - 'A'] += 1;
state.amphipods[val[2].lit[0] - 'A'][pop[val[2].lit[0] - 'A']] = target_zone[2][0];
pop[val[2].lit[0] - 'A'] += 1;
state.amphipods[val[3].lit[0] - 'A'][pop[val[3].lit[0] - 'A']] = target_zone[3][0];
pop[val[3].lit[0] - 'A'] += 1;
} else {
return error.UnsupportedInput;
}
if (tools.match_pattern("#{}#{}#{}#{}#", it.next().?)) |val| {
state.amphipods[val[0].lit[0] - 'A'][pop[val[0].lit[0] - 'A']] = target_zone[0][1];
pop[val[0].lit[0] - 'A'] += 1;
state.amphipods[val[1].lit[0] - 'A'][pop[val[1].lit[0] - 'A']] = target_zone[1][1];
pop[val[1].lit[0] - 'A'] += 1;
state.amphipods[val[2].lit[0] - 'A'][pop[val[2].lit[0] - 'A']] = target_zone[2][1];
pop[val[2].lit[0] - 'A'] += 1;
state.amphipods[val[3].lit[0] - 'A'][pop[val[3].lit[0] - 'A']] = target_zone[3][1];
pop[val[3].lit[0] - 'A'] += 1;
} else {
return error.UnsupportedInput;
}
if (tools.match_pattern("#########", it.next().?) == null) return error.UnsupportedInput;
break :blk state;
};
const ans1 = try searchLowestEnergySolution(gpa, State_1, initial_state_1, &all_positions_1);
const State_2 = State(4);
const initial_state_2 = blk: {
var state: State_2 = undefined;
for (initial_state_1.amphipods) |pair, i| {
state.amphipods[i][0] = if (pair[0] < 'p') pair[0] else pair[0] + ('x' - 'p');
state.amphipods[i][1] = if (pair[1] < 'p') pair[1] else pair[1] + ('x' - 'p');
}
// #p#q#r#s#
// #t#u#v#w#
// #D#C#B#A#
// #D#B#A#C#
state.amphipods[0][2] = 's';
state.amphipods[0][3] = 'v';
state.amphipods[1][2] = 'r';
state.amphipods[1][3] = 'u';
state.amphipods[2][2] = 'w';
state.amphipods[2][3] = 'q';
state.amphipods[3][2] = 'p';
state.amphipods[3][3] = 't';
break :blk state;
};
trace("init1= {}\n", .{initial_state_1});
trace("init2= {}\n", .{initial_state_2});
const ans2 = try searchLowestEnergySolution(gpa, State_2, initial_state_2, &all_positions_2);
return [_][]const u8{
try std.fmt.allocPrint(gpa, "{}", .{ans1}),
try std.fmt.allocPrint(gpa, "{}", .{ans2}),
};
}
test {
{
const res = try run(
\\#############
\\#...........#
\\###A#B#C#D###
\\ #A#B#C#D#
\\ #########
, std.testing.allocator);
defer std.testing.allocator.free(res[0]);
defer std.testing.allocator.free(res[1]);
try std.testing.expectEqualStrings("0", res[0]);
try std.testing.expectEqualStrings("28188", res[1]);
}
{
const res = try run(
\\#############
\\#...........#
\\###B#A#C#D###
\\ #A#B#C#D#
\\ #########
, std.testing.allocator);
defer std.testing.allocator.free(res[0]);
defer std.testing.allocator.free(res[1]);
try std.testing.expectEqualStrings("46", res[0]);
try std.testing.expectEqualStrings("28220", res[1]);
}
{
const res = try run(
\\#############
\\#...........#
\\###B#C#B#D###
\\ #A#D#C#A#
\\ #########
, std.testing.allocator);
defer std.testing.allocator.free(res[0]);
defer std.testing.allocator.free(res[1]);
try std.testing.expectEqualStrings("12521", res[0]);
try std.testing.expectEqualStrings("44169", res[1]);
}
} | 2021/day23.zig |
const std = @import("std");
const imgui = @import("imgui");
const gk = @import("../gamekit.zig");
const gfx = gk.gfx;
const rk = @import("renderkit");
pub const Renderer = struct {
font_texture: gfx.Texture,
vert_buffer_size: c_long,
index_buffer_size: c_long,
bindings: rk.BufferBindings,
const font_awesome_range: [3]imgui.ImWchar = [_]imgui.ImWchar{ imgui.icons.icon_range_min, imgui.icons.icon_range_max, 0 };
pub fn init(docking: bool, viewports: bool, icon_font: bool) Renderer {
const max_verts = 16384;
const index_buffer_size = @intCast(c_long, max_verts * 3 * @sizeOf(u16));
var ibuffer = rk.createBuffer(u16, .{
.type = .index,
.usage = .stream,
.size = index_buffer_size,
});
const vert_buffer_size = @intCast(c_long, max_verts * @sizeOf(gfx.Vertex));
var vertex_buffer = rk.createBuffer(gfx.Vertex, .{
.usage = .stream,
.size = vert_buffer_size,
});
_ = imgui.igCreateContext(null);
var io = imgui.igGetIO();
if (docking) io.ConfigFlags |= imgui.ImGuiConfigFlags_DockingEnable;
if (viewports) io.ConfigFlags |= imgui.ImGuiConfigFlags_ViewportsEnable;
io.ConfigDockingWithShift = true;
imgui.igStyleColorsDark(imgui.igGetStyle());
imgui.igGetStyle().FrameRounding = 0;
imgui.igGetStyle().WindowRounding = 0;
_ = imgui.ImFontAtlas_AddFontDefault(io.Fonts, null);
// add FontAwesome optionally
if (icon_font) {
var icons_config = imgui.ImFontConfig_ImFontConfig();
icons_config[0].MergeMode = true;
icons_config[0].PixelSnapH = true;
icons_config[0].FontDataOwnedByAtlas = false;
var data = @embedFile("assets/" ++ imgui.icons.font_icon_filename_fas);
_ = imgui.ImFontAtlas_AddFontFromMemoryTTF(io.Fonts, data, data.len, 13, icons_config, &font_awesome_range[0]);
}
var w: i32 = undefined;
var h: i32 = undefined;
var bytes_per_pixel: i32 = undefined;
var pixels: [*c]u8 = undefined;
imgui.ImFontAtlas_GetTexDataAsRGBA32(io.Fonts, &pixels, &w, &h, &bytes_per_pixel);
const font_tex = gfx.Texture.initWithData(u8, w, h, pixels[0..@intCast(usize, w * h * bytes_per_pixel)]);
imgui.ImFontAtlas_SetTexID(io.Fonts, font_tex.imTextureID());
return .{
.font_texture = font_tex,
.vert_buffer_size = vert_buffer_size,
.index_buffer_size = index_buffer_size,
.bindings = rk.BufferBindings.init(ibuffer, &[_]rk.Buffer{vertex_buffer}),
};
}
pub fn deinit(self: Renderer) void {
self.font_texture.deinit();
rk.destroyBuffer(self.bindings.index_buffer);
rk.destroyBuffer(self.bindings.vert_buffers[0]);
}
pub fn render(self: *Renderer) void {
imgui.igEndFrame();
imgui.igRender();
const io = imgui.igGetIO();
_ = io;
const draw_data = imgui.igGetDrawData();
if (draw_data.TotalVtxCount == 0) return;
self.updateBuffers(draw_data);
self.bindings.index_buffer_offset = 0;
var tex_id = imgui.igGetIO().Fonts.TexID;
self.bindings.images[0] = @intCast(rk.Image, @ptrToInt(tex_id));
var fb_scale = draw_data.FramebufferScale;
imgui.ogImDrawData_ScaleClipRects(draw_data, fb_scale);
const width = @floatToInt(i32, draw_data.DisplaySize.x * fb_scale.x);
const height = @floatToInt(i32, draw_data.DisplaySize.y * fb_scale.y);
rk.viewport(0, 0, width, height);
gfx.setShader(null);
rk.setRenderState(.{ .scissor = true });
var vb_offset: u32 = 0;
for (draw_data.CmdLists[0..@intCast(usize, draw_data.CmdListsCount)]) |list| {
// append vertices and indices to buffers
const indices = @ptrCast([*]u16, list.IdxBuffer.Data)[0..@intCast(usize, list.IdxBuffer.Size)];
self.bindings.index_buffer_offset = rk.appendBuffer(u16, self.bindings.index_buffer, indices);
const verts = @ptrCast([*]gfx.Vertex, list.VtxBuffer.Data)[0..@intCast(usize, list.VtxBuffer.Size)];
vb_offset = rk.appendBuffer(gfx.Vertex, self.bindings.vert_buffers[0], verts);
self.bindings.vertex_buffer_offsets[0] = vb_offset;
rk.applyBindings(self.bindings);
var base_element: c_int = 0;
var vtx_offset: u32 = 0;
for (list.CmdBuffer.Data[0..@intCast(usize, list.CmdBuffer.Size)]) |cmd| {
if (cmd.UserCallback) |cb| {
cb(list, &cmd);
} else {
// DisplayPos is 0,0 unless viewports is enabled
const clip_x = @floatToInt(i32, (cmd.ClipRect.x - draw_data.DisplayPos.x) * fb_scale.x);
const clip_y = @floatToInt(i32, (cmd.ClipRect.y - draw_data.DisplayPos.y) * fb_scale.y);
const clip_w = @floatToInt(i32, (cmd.ClipRect.z - draw_data.DisplayPos.x) * fb_scale.x);
const clip_h = @floatToInt(i32, (cmd.ClipRect.w - draw_data.DisplayPos.y) * fb_scale.y);
rk.scissor(clip_x, clip_y, clip_w - clip_x, clip_h - clip_y);
if (tex_id != cmd.TextureId or vtx_offset != cmd.VtxOffset) {
tex_id = cmd.TextureId;
self.bindings.images[0] = @intCast(rk.Image, @ptrToInt(tex_id));
vtx_offset = cmd.VtxOffset;
self.bindings.vertex_buffer_offsets[0] = vb_offset + vtx_offset * @sizeOf(imgui.ImDrawVert);
rk.applyBindings(self.bindings);
}
rk.draw(base_element, @intCast(c_int, cmd.ElemCount), 1);
}
base_element += @intCast(c_int, cmd.ElemCount);
} // end for CmdBuffer.Data
}
// reset the scissor
rk.scissor(0, 0, width, height);
rk.setRenderState(.{});
}
pub fn updateBuffers(self: *Renderer, draw_data: *imgui.ImDrawData) void {
// Expand buffers if we need more room
if (draw_data.TotalIdxCount > self.index_buffer_size) {
rk.destroyBuffer(self.bindings.index_buffer);
self.index_buffer_size = @floatToInt(c_long, @intToFloat(f32, draw_data.TotalIdxCount) * 1.5);
var ibuffer = rk.createBuffer(u16, .{
.type = .index,
.usage = .stream,
.size = self.index_buffer_size,
});
self.bindings.index_buffer = ibuffer;
}
if (draw_data.TotalVtxCount > self.vert_buffer_size) {
rk.destroyBuffer(self.bindings.vert_buffers[0]);
self.vert_buffer_size = @floatToInt(c_long, @intToFloat(f32, draw_data.TotalVtxCount) * 1.5);
var vertex_buffer = rk.createBuffer(gfx.Vertex, .{
.usage = .stream,
.size = self.vert_buffer_size,
});
_ = vertex_buffer;
}
}
}; | gamekit/imgui/renderer.zig |
const std = @import("std");
const math = std.math;
const sin = @import("sin.zig");
const cos = @import("cos.zig");
const trig = @import("trig.zig");
const rem_pio2 = @import("rem_pio2.zig").rem_pio2;
const rem_pio2f = @import("rem_pio2f.zig").rem_pio2f;
pub fn __sincosh(x: f16, r_sin: *f16, r_cos: *f16) callconv(.C) void {
// TODO: more efficient implementation
var big_sin: f32 = undefined;
var big_cos: f32 = undefined;
sincosf(x, &big_sin, &big_cos);
r_sin.* = @floatCast(f16, big_sin);
r_cos.* = @floatCast(f16, big_cos);
}
pub fn sincosf(x: f32, r_sin: *f32, r_cos: *f32) callconv(.C) void {
const sc1pio2: f64 = 1.0 * math.pi / 2.0; // 0x3FF921FB, 0x54442D18
const sc2pio2: f64 = 2.0 * math.pi / 2.0; // 0x400921FB, 0x54442D18
const sc3pio2: f64 = 3.0 * math.pi / 2.0; // 0x4012D97C, 0x7F3321D2
const sc4pio2: f64 = 4.0 * math.pi / 2.0; // 0x401921FB, 0x54442D18
const pre_ix = @bitCast(u32, x);
const sign = pre_ix >> 31 != 0;
const ix = pre_ix & 0x7fffffff;
// |x| ~<= pi/4
if (ix <= 0x3f490fda) {
// |x| < 2**-12
if (ix < 0x39800000) {
// raise inexact if x!=0 and underflow if subnormal
math.doNotOptimizeAway(if (ix < 0x00100000) x / 0x1p120 else x + 0x1p120);
r_sin.* = x;
r_cos.* = 1.0;
return;
}
r_sin.* = trig.__sindf(x);
r_cos.* = trig.__cosdf(x);
return;
}
// |x| ~<= 5*pi/4
if (ix <= 0x407b53d1) {
// |x| ~<= 3pi/4
if (ix <= 0x4016cbe3) {
if (sign) {
r_sin.* = -trig.__cosdf(x + sc1pio2);
r_cos.* = trig.__sindf(x + sc1pio2);
} else {
r_sin.* = trig.__cosdf(sc1pio2 - x);
r_cos.* = trig.__sindf(sc1pio2 - x);
}
return;
}
// -sin(x+c) is not correct if x+c could be 0: -0 vs +0
r_sin.* = -trig.__sindf(if (sign) x + sc2pio2 else x - sc2pio2);
r_cos.* = -trig.__cosdf(if (sign) x + sc2pio2 else x - sc2pio2);
return;
}
// |x| ~<= 9*pi/4
if (ix <= 0x40e231d5) {
// |x| ~<= 7*pi/4
if (ix <= 0x40afeddf) {
if (sign) {
r_sin.* = trig.__cosdf(x + sc3pio2);
r_cos.* = -trig.__sindf(x + sc3pio2);
} else {
r_sin.* = -trig.__cosdf(x - sc3pio2);
r_cos.* = trig.__sindf(x - sc3pio2);
}
return;
}
r_sin.* = trig.__sindf(if (sign) x + sc4pio2 else x - sc4pio2);
r_cos.* = trig.__cosdf(if (sign) x + sc4pio2 else x - sc4pio2);
return;
}
// sin(Inf or NaN) is NaN
if (ix >= 0x7f800000) {
const result = x - x;
r_sin.* = result;
r_cos.* = result;
return;
}
// general argument reduction needed
var y: f64 = undefined;
const n = rem_pio2f(x, &y);
const s = trig.__sindf(y);
const c = trig.__cosdf(y);
switch (n & 3) {
0 => {
r_sin.* = s;
r_cos.* = c;
},
1 => {
r_sin.* = c;
r_cos.* = -s;
},
2 => {
r_sin.* = -s;
r_cos.* = -c;
},
else => {
r_sin.* = -c;
r_cos.* = s;
},
}
}
pub fn sincos(x: f64, r_sin: *f64, r_cos: *f64) callconv(.C) void {
const ix = @truncate(u32, @bitCast(u64, x) >> 32) & 0x7fffffff;
// |x| ~< pi/4
if (ix <= 0x3fe921fb) {
// if |x| < 2**-27 * sqrt(2)
if (ix < 0x3e46a09e) {
// raise inexact if x != 0 and underflow if subnormal
math.doNotOptimizeAway(if (ix < 0x00100000) x / 0x1p120 else x + 0x1p120);
r_sin.* = x;
r_cos.* = 1.0;
return;
}
r_sin.* = trig.__sin(x, 0.0, 0);
r_cos.* = trig.__cos(x, 0.0);
return;
}
// sincos(Inf or NaN) is NaN
if (ix >= 0x7ff00000) {
const result = x - x;
r_sin.* = result;
r_cos.* = result;
return;
}
// argument reduction needed
var y: [2]f64 = undefined;
const n = rem_pio2(x, &y);
const s = trig.__sin(y[0], y[1], 1);
const c = trig.__cos(y[0], y[1]);
switch (n & 3) {
0 => {
r_sin.* = s;
r_cos.* = c;
},
1 => {
r_sin.* = c;
r_cos.* = -s;
},
2 => {
r_sin.* = -s;
r_cos.* = -c;
},
else => {
r_sin.* = -c;
r_cos.* = s;
},
}
}
pub fn __sincosx(x: f80, r_sin: *f80, r_cos: *f80) callconv(.C) void {
// TODO: more efficient implementation
//return sincos_generic(f80, x, r_sin, r_cos);
var big_sin: f128 = undefined;
var big_cos: f128 = undefined;
sincosq(x, &big_sin, &big_cos);
r_sin.* = @floatCast(f80, big_sin);
r_cos.* = @floatCast(f80, big_cos);
}
pub fn sincosq(x: f128, r_sin: *f128, r_cos: *f128) callconv(.C) void {
// TODO: more correct implementation
//return sincos_generic(f128, x, r_sin, r_cos);
var small_sin: f64 = undefined;
var small_cos: f64 = undefined;
sincos(@floatCast(f64, x), &small_sin, &small_cos);
r_sin.* = small_sin;
r_cos.* = small_cos;
}
pub fn sincosl(x: c_longdouble, r_sin: *c_longdouble, r_cos: *c_longdouble) callconv(.C) void {
switch (@typeInfo(c_longdouble).Float.bits) {
16 => return __sincosh(x, r_sin, r_cos),
32 => return sincosf(x, r_sin, r_cos),
64 => return sincos(x, r_sin, r_cos),
80 => return __sincosx(x, r_sin, r_cos),
128 => return sincosq(x, r_sin, r_cos),
else => @compileError("unreachable"),
}
}
const rem_pio2_generic = @compileError("TODO");
/// Ported from musl sincosl.c. Needs the following dependencies to be complete:
/// * rem_pio2_generic ported from __rem_pio2l.c
/// * trig.sin_generic ported from __sinl.c
/// * trig.cos_generic ported from __cosl.c
inline fn sincos_generic(comptime F: type, x: F, r_sin: *F, r_cos: *F) void {
const sc1pio4: F = 1.0 * math.pi / 4.0;
const bits = @typeInfo(F).Float.bits;
const I = std.meta.Int(.unsigned, bits);
const ix = @bitCast(I, x) & (math.maxInt(I) >> 1);
const se = @truncate(u16, ix >> (bits - 16));
if (se == 0x7fff) {
const result = x - x;
r_sin.* = result;
r_cos.* = result;
return;
}
if (@bitCast(F, ix) < sc1pio4) {
if (se < 0x3fff - math.floatFractionalBits(F) - 1) {
// raise underflow if subnormal
if (se == 0) {
math.doNotOptimizeAway(x * 0x1p-120);
}
r_sin.* = x;
// raise inexact if x!=0
r_cos.* = 1.0 + x;
return;
}
r_sin.* = trig.sin_generic(F, x, 0, 0);
r_cos.* = trig.cos_generic(F, x, 0);
return;
}
var y: [2]F = undefined;
const n = rem_pio2_generic(F, x, &y);
const s = trig.sin_generic(F, y[0], y[1], 1);
const c = trig.cos_generic(F, y[0], y[1]);
switch (n & 3) {
0 => {
r_sin.* = s;
r_cos.* = c;
},
1 => {
r_sin.* = c;
r_cos.* = -s;
},
2 => {
r_sin.* = -s;
r_cos.* = -c;
},
else => {
r_sin.* = -c;
r_cos.* = s;
},
}
} | lib/compiler_rt/sincos.zig |
const std = @import("std");
const time = std.os.time;
const mem = std.mem;
const AtomicInt = std.atomic.Int;
const Xoroshiro128 = std.rand.Xoroshiro128;
pub const OidError = error {
InvalidOid,
};
pub const Oid = packed struct {
const Size = @sizeOf(u32) * 3;
// data race!
var prng: ?Xoroshiro128 = null;
var incr = AtomicInt(usize).init(0);
time: u32,
fuzz: u32,
count: u32,
pub fn new() Oid {
const t = time.timestamp();
_ = incr.incr();
// data race!
if (prng == null) {
prng = Xoroshiro128.init(t);
}
return Oid {
.count = mem.endianSwapIfLe(u32, @truncate(u32, incr.incr())),
.time = mem.endianSwapIfLe(u32, @truncate(u32, t)),
.fuzz = @truncate(u32, prng.?.next()),
};
}
pub fn parse(str: []const u8) !Oid {
var result: Oid = undefined;
var bytes = std.mem.asBytes(&result);
try std.fmt.hexToBytes(bytes[0..], str);
return result;
}
// TODO make this simpler
pub fn toString(self: Oid) [Size * 2]u8 {
const hex = "0123456789abcdef";
var result = []u8{0} ** (Size * 2);
const bytes = std.mem.toBytes(self);
for (bytes) |b, i| {
result[2 * i] = hex[(b & 0xF0) >> 4];
result[2 * i + 1] = hex[b & 0x0F];
}
return result;
}
pub fn format(
self: Oid,
comptime fmt: []const u8,
context: var,
comptime FmtError: type,
output: fn (@typeOf(context), []const u8) FmtError!void,
) FmtError!void {
return std.fmt.format(context, FmtError, output, "{}", self.toString());
}
pub fn equal(self: Oid, other: Oid) bool {
return std.mem.eql(u8,
std.mem.asBytes(&self),
std.mem.asBytes(&other)
);
}
};
test "Oids" {
const assert = std.debug.assert;
const oid = Oid.new();
assert(oid.equal(try Oid.parse(oid.toString())));
} | src/oids.zig |
const std = @import("std");
const link = @import("link.zig");
const Module = @import("Module.zig");
const Allocator = std.mem.Allocator;
const zir = @import("zir.zig");
const Package = @import("Package.zig");
test "self-hosted" {
var ctx: TestContext = undefined;
try ctx.init();
defer ctx.deinit();
try @import("stage2_tests").addCases(&ctx);
try ctx.run();
}
pub const TestContext = struct {
zir_cmp_output_cases: std.ArrayList(ZIRCompareOutputCase),
zir_transform_cases: std.ArrayList(ZIRTransformCase),
pub const ZIRCompareOutputCase = struct {
name: []const u8,
src_list: []const []const u8,
expected_stdout_list: []const []const u8,
};
pub const ZIRTransformCase = struct {
name: []const u8,
src: [:0]const u8,
expected_zir: []const u8,
cross_target: std.zig.CrossTarget,
};
pub fn addZIRCompareOutput(
ctx: *TestContext,
name: []const u8,
src_list: []const []const u8,
expected_stdout_list: []const []const u8,
) void {
ctx.zir_cmp_output_cases.append(.{
.name = name,
.src_list = src_list,
.expected_stdout_list = expected_stdout_list,
}) catch unreachable;
}
pub fn addZIRTransform(
ctx: *TestContext,
name: []const u8,
cross_target: std.zig.CrossTarget,
src: [:0]const u8,
expected_zir: []const u8,
) void {
ctx.zir_transform_cases.append(.{
.name = name,
.src = src,
.expected_zir = expected_zir,
.cross_target = cross_target,
}) catch unreachable;
}
fn init(self: *TestContext) !void {
self.* = .{
.zir_cmp_output_cases = std.ArrayList(ZIRCompareOutputCase).init(std.heap.page_allocator),
.zir_transform_cases = std.ArrayList(ZIRTransformCase).init(std.heap.page_allocator),
};
}
fn deinit(self: *TestContext) void {
self.zir_cmp_output_cases.deinit();
self.zir_transform_cases.deinit();
self.* = undefined;
}
fn run(self: *TestContext) !void {
var progress = std.Progress{};
const root_node = try progress.start("zir", self.zir_cmp_output_cases.items.len +
self.zir_transform_cases.items.len);
defer root_node.end();
const native_info = try std.zig.system.NativeTargetInfo.detect(std.heap.page_allocator, .{});
for (self.zir_cmp_output_cases.items) |case| {
std.testing.base_allocator_instance.reset();
try self.runOneZIRCmpOutputCase(std.testing.allocator, root_node, case, native_info.target);
try std.testing.allocator_instance.validate();
}
for (self.zir_transform_cases.items) |case| {
std.testing.base_allocator_instance.reset();
const info = try std.zig.system.NativeTargetInfo.detect(std.testing.allocator, case.cross_target);
try self.runOneZIRTransformCase(std.testing.allocator, root_node, case, info.target);
try std.testing.allocator_instance.validate();
}
}
fn runOneZIRCmpOutputCase(
self: *TestContext,
allocator: *Allocator,
root_node: *std.Progress.Node,
case: ZIRCompareOutputCase,
target: std.Target,
) !void {
var tmp = std.testing.tmpDir(.{});
defer tmp.cleanup();
const tmp_src_path = "test-case.zir";
const root_pkg = try Package.create(allocator, tmp.dir, ".", tmp_src_path);
defer root_pkg.destroy();
var prg_node = root_node.start(case.name, case.src_list.len);
prg_node.activate();
defer prg_node.end();
var module = try Module.init(allocator, .{
.target = target,
.output_mode = .Exe,
.optimize_mode = .Debug,
.bin_file_dir = tmp.dir,
.bin_file_path = "a.out",
.root_pkg = root_pkg,
});
defer module.deinit();
for (case.src_list) |source, i| {
var src_node = prg_node.start("update", 2);
src_node.activate();
defer src_node.end();
try tmp.dir.writeFile(tmp_src_path, source);
var update_node = src_node.start("parse,analysis,codegen", null);
update_node.activate();
try module.makeBinFileWritable();
try module.update();
update_node.end();
var exec_result = x: {
var exec_node = src_node.start("execute", null);
exec_node.activate();
defer exec_node.end();
try module.makeBinFileExecutable();
break :x try std.ChildProcess.exec(.{
.allocator = allocator,
.argv = &[_][]const u8{"./a.out"},
.cwd_dir = tmp.dir,
});
};
defer allocator.free(exec_result.stdout);
defer allocator.free(exec_result.stderr);
switch (exec_result.term) {
.Exited => |code| {
if (code != 0) {
std.debug.warn("elf file exited with code {}\n", .{code});
return error.BinaryBadExitCode;
}
},
else => return error.BinaryCrashed,
}
const expected_stdout = case.expected_stdout_list[i];
if (!std.mem.eql(u8, expected_stdout, exec_result.stdout)) {
std.debug.panic(
"update index {}, mismatched stdout\n====Expected (len={}):====\n{}\n====Actual (len={}):====\n{}\n========\n",
.{ i, expected_stdout.len, expected_stdout, exec_result.stdout.len, exec_result.stdout },
);
}
}
}
fn runOneZIRTransformCase(
self: *TestContext,
allocator: *Allocator,
root_node: *std.Progress.Node,
case: ZIRTransformCase,
target: std.Target,
) !void {
var tmp = std.testing.tmpDir(.{});
defer tmp.cleanup();
var prg_node = root_node.start(case.name, 3);
prg_node.activate();
defer prg_node.end();
const tmp_src_path = "test-case.zir";
try tmp.dir.writeFile(tmp_src_path, case.src);
const root_pkg = try Package.create(allocator, tmp.dir, ".", tmp_src_path);
defer root_pkg.destroy();
var module = try Module.init(allocator, .{
.target = target,
.output_mode = .Obj,
.optimize_mode = .Debug,
.bin_file_dir = tmp.dir,
.bin_file_path = "test-case.o",
.root_pkg = root_pkg,
});
defer module.deinit();
var module_node = prg_node.start("parse/analysis/codegen", null);
module_node.activate();
try module.update();
module_node.end();
var emit_node = prg_node.start("emit", null);
emit_node.activate();
var new_zir_module = try zir.emit(allocator, module);
defer new_zir_module.deinit(allocator);
emit_node.end();
var write_node = prg_node.start("write", null);
write_node.activate();
var out_zir = std.ArrayList(u8).init(allocator);
defer out_zir.deinit();
try new_zir_module.writeToStream(allocator, out_zir.outStream());
write_node.end();
std.testing.expectEqualSlices(u8, case.expected_zir, out_zir.items);
}
};
fn debugPrintErrors(src: []const u8, errors: var) void {
std.debug.warn("\n", .{});
var nl = true;
var line: usize = 1;
for (src) |byte| {
if (nl) {
std.debug.warn("{: >3}| ", .{line});
nl = false;
}
if (byte == '\n') {
nl = true;
line += 1;
}
std.debug.warn("{c}", .{byte});
}
std.debug.warn("\n", .{});
for (errors) |err_msg| {
const loc = std.zig.findLineColumn(src, err_msg.byte_offset);
std.debug.warn("{}:{}: error: {}\n", .{ loc.line + 1, loc.column + 1, err_msg.msg });
}
} | src-self-hosted/test.zig |
const std = @import("std");
const expect = std.testing.expect;
// TODO: validate this matches the schema
pub const Smithy = struct {
version: []const u8,
metadata: ModelMetadata,
shapes: []ShapeInfo,
allocator: std.mem.Allocator,
const Self = @This();
pub fn init(allocator: std.mem.Allocator, version: []const u8, metadata: ModelMetadata, shapeinfo: []ShapeInfo) Smithy {
return .{
.version = version,
.metadata = metadata,
.shapes = shapeinfo,
.allocator = allocator,
};
}
pub fn deinit(self: Self) void {
for (self.shapes) |s| {
switch (s.shape) {
.string,
.byte,
.short,
.integer,
.long,
.float,
.double,
.bigInteger,
.bigDecimal,
.blob,
.boolean,
.timestamp,
.document,
.member,
.resource,
=> |v| self.allocator.free(v.traits),
.structure => |v| {
for (v.members) |m| self.allocator.free(m.traits);
self.allocator.free(v.members);
self.allocator.free(v.traits);
},
.uniontype => |v| {
for (v.members) |m| self.allocator.free(m.traits);
self.allocator.free(v.members);
self.allocator.free(v.traits);
},
.service => |v| {
self.allocator.free(v.traits);
self.allocator.free(v.operations);
},
.operation => |v| {
if (v.errors) |e| self.allocator.free(e);
self.allocator.free(v.traits);
},
.list => |v| {
self.allocator.free(v.traits);
},
.set => |v| {
self.allocator.free(v.traits);
},
.map => |v| {
self.allocator.free(v.key);
self.allocator.free(v.value);
self.allocator.free(v.traits);
},
}
}
self.allocator.free(self.shapes);
}
};
pub const ShapeInfo = struct {
id: []const u8,
namespace: []const u8,
name: []const u8,
member: ?[]const u8,
shape: Shape,
};
const ModelMetadata = struct {
suppressions: []struct {
id: []const u8,
namespace: []const u8,
},
};
pub const TraitType = enum {
aws_api_service,
aws_auth_sigv4,
aws_protocol,
ec2_query_name,
http,
http_header,
http_label,
http_query,
json_name,
required,
documentation,
pattern,
range,
length,
box,
sparse,
};
pub const Trait = union(TraitType) {
aws_api_service: struct {
sdk_id: []const u8,
arn_namespace: []const u8,
cloudformation_name: []const u8,
cloudtrail_event_source: []const u8,
endpoint_prefix: []const u8,
},
aws_auth_sigv4: struct {
name: []const u8,
},
aws_protocol: AwsProtocol,
ec2_query_name: []const u8,
json_name: []const u8,
http: struct {
method: []const u8,
uri: []const u8,
code: i64 = 200,
},
http_header: []const u8,
http_label: []const u8,
http_query: []const u8,
required: struct {},
documentation: []const u8,
pattern: []const u8,
range: struct { // most data is actually integers, but as some are floats, we'll use that here
min: ?f64,
max: ?f64,
},
length: struct {
min: ?f64,
max: ?f64,
},
box: struct {},
sparse: struct {},
};
const ShapeType = enum {
blob,
boolean,
string,
byte,
short,
integer,
long,
float,
double,
bigInteger,
bigDecimal,
timestamp,
document,
member,
list,
set,
map,
structure,
uniontype,
service,
operation,
resource,
};
const TraitsOnly = struct {
traits: []Trait,
};
pub const TypeMember = struct {
name: []const u8,
target: []const u8,
traits: []Trait,
};
const Shape = union(ShapeType) {
blob: TraitsOnly,
boolean: TraitsOnly,
string: TraitsOnly,
byte: TraitsOnly,
short: TraitsOnly,
integer: TraitsOnly,
long: TraitsOnly,
float: TraitsOnly,
double: TraitsOnly,
bigInteger: TraitsOnly,
bigDecimal: TraitsOnly,
timestamp: TraitsOnly,
document: TraitsOnly,
member: TraitsOnly,
list: struct {
member_target: []const u8,
traits: []Trait,
},
set: struct {
member_target: []const u8,
traits: []Trait,
},
map: struct {
key: []const u8,
value: []const u8,
traits: []Trait,
},
structure: struct {
members: []TypeMember,
traits: []Trait,
},
uniontype: struct {
members: []TypeMember,
traits: []Trait,
},
service: struct {
version: []const u8,
operations: [][]const u8,
resources: [][]const u8,
traits: []Trait,
},
operation: struct {
input: ?[]const u8,
output: ?[]const u8,
errors: ?[][]const u8,
traits: []Trait,
},
resource: TraitsOnly,
};
// https://awslabs.github.io/smithy/1.0/spec/aws/index.html
pub const AwsProtocol = enum {
query,
rest_xml,
json_1_1,
json_1_0,
rest_json_1,
ec2_query,
};
pub fn parse(allocator: std.mem.Allocator, json_model: []const u8) !Smithy {
// construct a parser. We're not copying strings here, but that may
// be a poor decision
var parser = std.json.Parser.init(allocator, false);
defer parser.deinit();
var vt = try parser.parse(json_model);
defer vt.deinit();
return Smithy.init(
allocator,
vt.root.Object.get("smithy").?.String,
ModelMetadata{
// TODO: implement
.suppressions = &.{},
},
try shapes(allocator, vt.root.Object.get("shapes").?.Object),
);
}
// anytype: HashMap([]const u8, std.json.Value...)
// list must be deinitialized by caller
fn shapes(allocator: std.mem.Allocator, map: anytype) ![]ShapeInfo {
var list = try std.ArrayList(ShapeInfo).initCapacity(allocator, map.count());
defer list.deinit();
var iterator = map.iterator();
while (iterator.next()) |kv| {
const id_info = try parseId(kv.key_ptr.*);
try list.append(.{
.id = id_info.id,
.namespace = id_info.namespace,
.name = id_info.name,
.member = id_info.member,
.shape = try getShape(allocator, kv.value_ptr.*),
});
}
// This seems to be a synonym for the simple type "string"
// https://awslabs.github.io/smithy/1.0/spec/core/model.html#simple-types
// But I don't see it in the spec. We might need to preload other similar
// simple types?
try list.append(.{
.id = "smithy.api#String",
.namespace = "smithy.api",
.name = "String",
.member = null,
.shape = Shape{
.string = .{
.traits = &.{},
},
},
});
try list.append(.{
.id = "smithy.api#Boolean",
.namespace = "smithy.api",
.name = "Boolean",
.member = null,
.shape = Shape{
.boolean = .{
.traits = &.{},
},
},
});
try list.append(.{
.id = "smithy.api#Integer",
.namespace = "smithy.api",
.name = "Integer",
.member = null,
.shape = Shape{
.integer = .{
.traits = &.{},
},
},
});
try list.append(.{
.id = "smithy.api#Double",
.namespace = "smithy.api",
.name = "Double",
.member = null,
.shape = Shape{
.double = .{
.traits = &.{},
},
},
});
try list.append(.{
.id = "smithy.api#Timestamp",
.namespace = "smithy.api",
.name = "Timestamp",
.member = null,
.shape = Shape{
.timestamp = .{
.traits = &.{},
},
},
});
return list.toOwnedSlice();
}
fn getShape(allocator: std.mem.Allocator, shape: std.json.Value) SmithyParseError!Shape {
const shape_type = shape.Object.get("type").?.String;
if (std.mem.eql(u8, shape_type, "service"))
return Shape{
.service = .{
.version = shape.Object.get("version").?.String,
.operations = if (shape.Object.get("operations")) |ops|
try parseTargetList(allocator, ops.Array)
else
&.{}, // this doesn't make much sense, but it's happening
// TODO: implement. We need some sample data tho
.resources = &.{},
.traits = try parseTraits(allocator, shape.Object.get("traits")),
},
};
if (std.mem.eql(u8, shape_type, "structure"))
return Shape{
.structure = .{
.members = try parseMembers(allocator, shape.Object.get("members")),
.traits = try parseTraits(allocator, shape.Object.get("traits")),
},
};
if (std.mem.eql(u8, shape_type, "union"))
return Shape{
.uniontype = .{
.members = try parseMembers(allocator, shape.Object.get("members")),
.traits = try parseTraits(allocator, shape.Object.get("traits")),
},
};
if (std.mem.eql(u8, shape_type, "operation"))
return Shape{
.operation = .{
.input = if (shape.Object.get("input")) |member| member.Object.get("target").?.String else null,
.output = if (shape.Object.get("output")) |member| member.Object.get("target").?.String else null,
.errors = blk: {
if (shape.Object.get("errors")) |e| {
break :blk try parseTargetList(allocator, e.Array);
}
break :blk null;
},
.traits = try parseTraits(allocator, shape.Object.get("traits")),
},
};
if (std.mem.eql(u8, shape_type, "list"))
return Shape{
.list = .{
.member_target = shape.Object.get("member").?.Object.get("target").?.String,
.traits = try parseTraits(allocator, shape.Object.get("traits")),
},
};
if (std.mem.eql(u8, shape_type, "set"))
return Shape{
.set = .{
.member_target = shape.Object.get("member").?.Object.get("target").?.String,
.traits = try parseTraits(allocator, shape.Object.get("traits")),
},
};
if (std.mem.eql(u8, shape_type, "map"))
return Shape{
.map = .{
.key = shape.Object.get("key").?.Object.get("target").?.String,
.value = shape.Object.get("value").?.Object.get("target").?.String,
.traits = try parseTraits(allocator, shape.Object.get("traits")),
},
};
if (std.mem.eql(u8, shape_type, "string"))
return Shape{ .string = try parseTraitsOnly(allocator, shape) };
if (std.mem.eql(u8, shape_type, "byte"))
return Shape{ .byte = try parseTraitsOnly(allocator, shape) };
if (std.mem.eql(u8, shape_type, "short"))
return Shape{ .short = try parseTraitsOnly(allocator, shape) };
if (std.mem.eql(u8, shape_type, "integer"))
return Shape{ .integer = try parseTraitsOnly(allocator, shape) };
if (std.mem.eql(u8, shape_type, "long"))
return Shape{ .long = try parseTraitsOnly(allocator, shape) };
if (std.mem.eql(u8, shape_type, "float"))
return Shape{ .float = try parseTraitsOnly(allocator, shape) };
if (std.mem.eql(u8, shape_type, "double"))
return Shape{ .double = try parseTraitsOnly(allocator, shape) };
if (std.mem.eql(u8, shape_type, "bigInteger"))
return Shape{ .bigInteger = try parseTraitsOnly(allocator, shape) };
if (std.mem.eql(u8, shape_type, "bigDecimal"))
return Shape{ .bigDecimal = try parseTraitsOnly(allocator, shape) };
if (std.mem.eql(u8, shape_type, "boolean"))
return Shape{ .boolean = try parseTraitsOnly(allocator, shape) };
if (std.mem.eql(u8, shape_type, "blob"))
return Shape{ .blob = try parseTraitsOnly(allocator, shape) };
if (std.mem.eql(u8, shape_type, "timestamp"))
return Shape{ .timestamp = try parseTraitsOnly(allocator, shape) };
if (std.mem.eql(u8, shape_type, "document"))
return Shape{ .document = try parseTraitsOnly(allocator, shape) };
if (std.mem.eql(u8, shape_type, "member"))
return Shape{ .member = try parseTraitsOnly(allocator, shape) };
if (std.mem.eql(u8, shape_type, "resource"))
return Shape{ .resource = try parseTraitsOnly(allocator, shape) };
std.debug.print("Invalid Type: {s}", .{shape_type});
return SmithyParseError.InvalidType;
}
fn parseMembers(allocator: std.mem.Allocator, shape: ?std.json.Value) SmithyParseError![]TypeMember {
var rc: []TypeMember = &.{};
if (shape == null)
return rc;
const map = shape.?.Object;
var list = std.ArrayList(TypeMember).initCapacity(allocator, map.count()) catch return SmithyParseError.OutOfMemory;
defer list.deinit();
var iterator = map.iterator();
while (iterator.next()) |kv| {
try list.append(TypeMember{
.name = kv.key_ptr.*,
.target = kv.value_ptr.*.Object.get("target").?.String,
.traits = try parseTraits(allocator, kv.value_ptr.*.Object.get("traits")),
});
}
return list.toOwnedSlice();
}
// ArrayList of std.Json.Value
fn parseTargetList(allocator: std.mem.Allocator, list: anytype) SmithyParseError![][]const u8 {
var array_list = std.ArrayList([]const u8).initCapacity(allocator, list.items.len) catch return SmithyParseError.OutOfMemory;
defer array_list.deinit();
for (list.items) |i| {
try array_list.append(i.Object.get("target").?.String);
}
return array_list.toOwnedSlice();
}
fn parseTraitsOnly(allocator: std.mem.Allocator, shape: std.json.Value) SmithyParseError!TraitsOnly {
return TraitsOnly{
.traits = try parseTraits(allocator, shape.Object.get("traits")),
};
}
fn parseTraits(allocator: std.mem.Allocator, shape: ?std.json.Value) SmithyParseError![]Trait {
var rc: []Trait = &.{};
if (shape == null)
return rc;
const map = shape.?.Object;
var list = std.ArrayList(Trait).initCapacity(allocator, map.count()) catch return SmithyParseError.OutOfMemory;
defer list.deinit();
var iterator = map.iterator();
while (iterator.next()) |kv| {
if (try getTrait(kv.key_ptr.*, kv.value_ptr.*)) |t|
try list.append(t);
}
return list.toOwnedSlice();
}
fn getTrait(trait_type: []const u8, value: std.json.Value) SmithyParseError!?Trait {
if (std.mem.eql(u8, trait_type, "aws.api#service"))
return Trait{
.aws_api_service = .{
.sdk_id = value.Object.get("sdkId").?.String,
.arn_namespace = value.Object.get("arnNamespace").?.String,
.cloudformation_name = value.Object.get("cloudFormationName").?.String,
.cloudtrail_event_source = value.Object.get("cloudTrailEventSource").?.String,
// what good is a service without an endpoint? I don't know - ask amp
.endpoint_prefix = if (value.Object.get("endpointPrefix")) |endpoint| endpoint.String else "",
},
};
if (std.mem.eql(u8, trait_type, "aws.auth#sigv4"))
return Trait{
.aws_auth_sigv4 = .{
.name = value.Object.get("name").?.String,
},
};
if (std.mem.eql(u8, trait_type, "smithy.api#required"))
return Trait{ .required = .{} };
if (std.mem.eql(u8, trait_type, "smithy.api#sparse"))
return Trait{ .sparse = .{} };
if (std.mem.eql(u8, trait_type, "smithy.api#box"))
return Trait{ .box = .{} };
if (std.mem.eql(u8, trait_type, "smithy.api#range"))
return Trait{
.range = .{
.min = getOptionalNumber(value, "min"),
.max = getOptionalNumber(value, "max"),
},
};
if (std.mem.eql(u8, trait_type, "smithy.api#length"))
return Trait{
.length = .{
.min = getOptionalNumber(value, "min"),
.max = getOptionalNumber(value, "max"),
},
};
if (std.mem.eql(u8, trait_type, "aws.protocols#restJson1"))
return Trait{
.aws_protocol = .rest_json_1,
};
if (std.mem.eql(u8, trait_type, "aws.protocols#awsJson1_0"))
return Trait{
.aws_protocol = .json_1_0,
};
if (std.mem.eql(u8, trait_type, "aws.protocols#awsJson1_1"))
return Trait{
.aws_protocol = .json_1_1,
};
if (std.mem.eql(u8, trait_type, "aws.protocols#restXml"))
return Trait{
.aws_protocol = .rest_xml,
};
if (std.mem.eql(u8, trait_type, "aws.protocols#awsQuery"))
return Trait{
.aws_protocol = .query,
};
if (std.mem.eql(u8, trait_type, "aws.protocols#ec2Query"))
return Trait{
.aws_protocol = .ec2_query,
};
if (std.mem.eql(u8, trait_type, "smithy.api#documentation"))
return Trait{ .documentation = value.String };
if (std.mem.eql(u8, trait_type, "smithy.api#pattern"))
return Trait{ .pattern = value.String };
if (std.mem.eql(u8, trait_type, "aws.protocols#ec2QueryName"))
return Trait{ .ec2_query_name = value.String };
if (std.mem.eql(u8, trait_type, "smithy.api#http")) {
var code: i64 = 200;
if (value.Object.get("code")) |v| {
if (v == .Integer)
code = v.Integer;
}
return Trait{ .http = .{
.method = value.Object.get("method").?.String,
.uri = value.Object.get("uri").?.String,
.code = code,
} };
}
if (std.mem.eql(u8, trait_type, "smithy.api#jsonName"))
return Trait{ .json_name = value.String };
if (std.mem.eql(u8, trait_type, "smithy.api#httpQuery"))
return Trait{ .http_query = value.String };
if (std.mem.eql(u8, trait_type, "smithy.api#httpHeader"))
return Trait{ .http_header = value.String };
// TODO: Maybe care about these traits?
if (std.mem.eql(u8, trait_type, "smithy.api#title"))
return null;
if (std.mem.eql(u8, trait_type, "smithy.api#xmlNamespace"))
return null;
// TODO: win argument with compiler to get this comptime
const list =
\\aws.api#arnReference
\\aws.api#clientDiscoveredEndpoint
\\aws.api#clientEndpointDiscovery
\\aws.api#arn
\\aws.auth#unsignedPayload
\\aws.iam#disableConditionKeyInference
\\smithy.api#auth
\\smithy.api#cors
\\smithy.api#deprecated
\\smithy.api#endpoint
\\smithy.api#enum
\\smithy.api#error
\\smithy.api#eventPayload
\\smithy.api#externalDocumentation
\\smithy.api#hostLabel
\\smithy.api#httpError
\\smithy.api#httpChecksumRequired
\\smithy.api#httpLabel
\\smithy.api#httpPayload
\\smithy.api#httpPrefixHeaders
\\smithy.api#httpQueryParams
\\smithy.api#httpResponseCode
\\smithy.api#idempotencyToken
\\smithy.api#idempotent
\\smithy.api#mediaType
\\smithy.api#noReplace
\\smithy.api#optionalAuth
\\smithy.api#paginated
\\smithy.api#readonly
\\smithy.api#references
\\smithy.api#requiresLength
\\smithy.api#retryable
\\smithy.api#sensitive
\\smithy.api#streaming
\\smithy.api#suppress
\\smithy.api#tags
\\smithy.api#timestampFormat
\\smithy.api#xmlAttribute
\\smithy.api#xmlFlattened
\\smithy.api#xmlName
\\smithy.waiters#waitable
;
var iterator = std.mem.split(u8, list, "\n");
while (iterator.next()) |known_but_unimplemented| {
if (std.mem.eql(u8, trait_type, known_but_unimplemented))
return null;
}
// Totally unknown type
std.log.err("Invalid Trait Type: {s}", .{trait_type});
return null;
}
fn getOptionalNumber(value: std.json.Value, key: []const u8) ?f64 {
if (value.Object.get(key)) |v|
return switch (v) {
.Integer => @intToFloat(f64, v.Integer),
.Float => v.Float,
.Null, .Bool, .NumberString, .String, .Array, .Object => null,
};
return null;
}
const IdInfo = struct { id: []const u8, namespace: []const u8, name: []const u8, member: ?[]const u8 };
const SmithyParseError = error{
NoHashtagFound,
InvalidType,
OutOfMemory,
};
fn parseId(id: []const u8) SmithyParseError!IdInfo {
var hashtag: ?usize = null;
var dollar: ?usize = null;
var inx: usize = 0;
for (id) |ch| {
switch (ch) {
'#' => hashtag = inx,
'$' => dollar = inx,
else => {},
}
inx = inx + 1;
}
if (hashtag == null) {
std.debug.print("no hashtag found on id: {s}\n", .{id});
return SmithyParseError.NoHashtagFound;
}
const namespace = id[0..hashtag.?];
var end = id.len;
var member: ?[]const u8 = null;
if (dollar) |d| {
member = id[dollar.? + 1 .. end];
end = d;
}
const name = id[hashtag.? + 1 .. end];
return IdInfo{
.id = id,
.namespace = namespace,
.name = name,
.member = member,
};
}
fn read_file_to_string(allocator: std.mem.Allocator, file_name: []const u8, max_bytes: usize) ![]const u8 {
const file = try std.fs.cwd().openFile(file_name, std.fs.File.OpenFlags{});
defer file.close();
return file.readToEndAlloc(allocator, max_bytes);
}
var test_data: ?[]const u8 = null;
const intrinsic_type_count: usize = 5; // 5 intrinsic types are added to every model
fn getTestData(_: *std.mem.Allocator) []const u8 {
if (test_data) |d| return d;
var gpa = std.heap.GeneralPurposeAllocator(.{}){};
test_data = read_file_to_string(gpa.allocator, "test.json", 150000) catch @panic("could not read test.json");
return test_data.?;
}
test "read file" {
var gpa = std.heap.GeneralPurposeAllocator(.{}){};
defer if (gpa.deinit()) @panic("leak");
const allocator = gpa.allocator;
_ = getTestData(allocator);
// test stuff
}
test "parse string" {
const test_string =
\\ {
\\ "smithy": "1.0",
\\ "shapes": {
\\ "com.amazonaws.sts#AWSSecurityTokenServiceV20110615": {
\\ "type": "service",
\\ "version": "2011-06-15",
\\ "operations": [
\\ {
\\ "target": "op"
\\ }
\\ ]
\\ }
\\ }
\\ }
\\
\\
;
var gpa = std.heap.GeneralPurposeAllocator(.{}){};
defer if (gpa.deinit()) @panic("leak");
const allocator = gpa.allocator;
const model = try parse(allocator, test_string);
defer model.deinit();
try expect(std.mem.eql(u8, model.version, "1.0"));
try std.testing.expectEqual(intrinsic_type_count + 1, model.shapes.len);
try std.testing.expectEqualStrings("com.amazonaws.sts#AWSSecurityTokenServiceV20110615", model.shapes[0].id);
try std.testing.expectEqualStrings("com.amazonaws.sts", model.shapes[0].namespace);
try std.testing.expectEqualStrings("AWSSecurityTokenServiceV20110615", model.shapes[0].name);
try std.testing.expect(model.shapes[0].member == null);
try std.testing.expectEqualStrings("2011-06-15", model.shapes[0].shape.service.version);
}
test "parse shape with member" {
const test_string =
\\ {
\\ "smithy": "1.0",
\\ "shapes": {
\\ "com.amazonaws.sts#AWSSecurityTokenServiceV20110615$member": {
\\ "type": "service",
\\ "version": "2011-06-15",
\\ "operations": [
\\ {
\\ "target": "op"
\\ }
\\ ]
\\ }
\\ }
\\ }
\\
\\
;
var gpa = std.heap.GeneralPurposeAllocator(.{}){};
defer if (gpa.deinit()) @panic("leak");
const allocator = gpa.allocator;
const model = try parse(allocator, test_string);
defer model.deinit();
try expect(std.mem.eql(u8, model.version, "1.0"));
try std.testing.expectEqual(intrinsic_type_count + 1, model.shapes.len);
try std.testing.expectEqualStrings("com.amazonaws.sts#AWSSecurityTokenServiceV20110615$member", model.shapes[0].id);
try std.testing.expectEqualStrings("com.amazonaws.sts", model.shapes[0].namespace);
try std.testing.expectEqualStrings("AWSSecurityTokenServiceV20110615", model.shapes[0].name);
try std.testing.expectEqualStrings("2011-06-15", model.shapes[0].shape.service.version);
try std.testing.expectEqualStrings("member", model.shapes[0].member.?);
}
test "parse file" {
var gpa = std.heap.GeneralPurposeAllocator(.{}){};
defer if (gpa.deinit()) @panic("leak");
const allocator = gpa.allocator;
const test_string = getTestData(allocator);
const model = try parse(allocator, test_string);
defer model.deinit();
try std.testing.expectEqualStrings(model.version, "1.0");
// metadata expectations
// try expect(std.mem.eql(u8, model.version, "version 1.0"));
// shape expectations
try std.testing.expectEqual(intrinsic_type_count + 81, model.shapes.len);
var optsvc: ?ShapeInfo = null;
for (model.shapes) |shape| {
if (std.mem.eql(u8, shape.id, "com.amazonaws.sts#AWSSecurityTokenServiceV20110615")) {
optsvc = shape;
break;
}
}
try std.testing.expect(optsvc != null);
const svc = optsvc.?;
try std.testing.expectEqualStrings("com.amazonaws.sts#AWSSecurityTokenServiceV20110615", svc.id);
try std.testing.expectEqualStrings("com.amazonaws.sts", svc.namespace);
try std.testing.expectEqualStrings("AWSSecurityTokenServiceV20110615", svc.name);
try std.testing.expectEqualStrings("2011-06-15", svc.shape.service.version);
// Should be 6, but we don't handle title or xml namespace
try std.testing.expectEqual(@as(usize, 4), svc.shape.service.traits.len);
try std.testing.expectEqual(@as(usize, 8), svc.shape.service.operations.len);
} | smithy/src/smithy.zig |
const std = @import("std");
const Arena = std.heap.ArenaAllocator;
const expectEqual = std.testing.expectEqual;
const expectEqualStrings = std.testing.expectEqualStrings;
const yeti = @import("yeti");
const initCodebase = yeti.initCodebase;
const tokenize = yeti.tokenize;
const parse = yeti.parse;
const analyzeSemantics = yeti.analyzeSemantics;
const codegen = yeti.codegen;
const printWasm = yeti.printWasm;
const components = yeti.components;
const literalOf = yeti.query.literalOf;
const MockFileSystem = yeti.FileSystem;
test "tokenize foreign export" {
var arena = Arena.init(std.heap.page_allocator);
defer arena.deinit();
var codebase = try initCodebase(&arena);
const module = try codebase.createEntity(.{});
const code = "@export";
var tokens = try tokenize(module, code);
{
const token = tokens.next().?;
try expectEqual(token.get(components.TokenKind), .attribute_export);
try expectEqual(token.get(components.Span), .{
.begin = .{ .column = 0, .row = 0 },
.end = .{ .column = 7, .row = 0 },
});
}
try expectEqual(tokens.next(), null);
}
test "parse function with int literal" {
var arena = Arena.init(std.heap.page_allocator);
defer arena.deinit();
var codebase = try initCodebase(&arena);
const module = try codebase.createEntity(.{});
const code =
\\@export
\\start() u64 {
\\ 0
\\}
;
var tokens = try tokenize(module, code);
try parse(module, &tokens);
const top_level = module.get(components.TopLevel);
const start = top_level.findString("start");
const overloads = start.get(components.Overloads).slice();
try expectEqual(overloads.len, 1);
const body = overloads[0].get(components.Body).slice();
try expectEqual(body.len, 1);
const zero = body[0];
try expectEqual(zero.get(components.AstKind), .int);
try expectEqualStrings(literalOf(zero), "0");
const foreign_exports = module.get(components.ForeignExports).slice();
try expectEqual(foreign_exports.len, 1);
try expectEqualStrings(literalOf(foreign_exports[0]), "start");
}
test "analyze semantics of foreign export" {
var arena = Arena.init(std.heap.page_allocator);
defer arena.deinit();
var codebase = try initCodebase(&arena);
const builtins = codebase.get(components.Builtins);
var fs = try MockFileSystem.init(&arena);
_ = try fs.newFile("foo.yeti",
\\@export
\\square(x: i64) i64 {
\\ x * x
\\}
);
const module = try analyzeSemantics(codebase, fs, "foo.yeti");
const top_level = module.get(components.TopLevel);
const square = top_level.findString("square").get(components.Overloads).slice()[0];
try expectEqualStrings(literalOf(square.get(components.Module).entity), "foo");
try expectEqualStrings(literalOf(square.get(components.Name).entity), "square");
try expectEqual(square.get(components.Parameters).len(), 1);
try expectEqual(square.get(components.ReturnType).entity, builtins.I64);
const body = square.get(components.Body).slice();
try expectEqual(body.len, 1);
}
test "analyze semantics of foreign exports with recursion" {
var arena = Arena.init(std.heap.page_allocator);
defer arena.deinit();
var codebase = try initCodebase(&arena);
const builtins = codebase.get(components.Builtins);
var fs = try MockFileSystem.init(&arena);
_ = try fs.newFile("foo.yeti",
\\@export
\\fib(n: i64) i64 {
\\ if n < 2 {
\\ 0
\\ } else {
\\ fib(n - 1) + fib(n - 2)
\\ }
\\}
);
const module = try analyzeSemantics(codebase, fs, "foo.yeti");
const top_level = module.get(components.TopLevel);
const fib = top_level.findString("fib").get(components.Overloads).slice()[0];
try expectEqualStrings(literalOf(fib.get(components.Module).entity), "foo");
try expectEqualStrings(literalOf(fib.get(components.Name).entity), "fib");
try expectEqual(fib.get(components.Parameters).len(), 1);
try expectEqual(fib.get(components.ReturnType).entity, builtins.I64);
const body = fib.get(components.Body).slice();
try expectEqual(body.len, 1);
}
test "print wasm foreign export" {
var arena = Arena.init(std.heap.page_allocator);
defer arena.deinit();
var codebase = try initCodebase(&arena);
var fs = try MockFileSystem.init(&arena);
_ = try fs.newFile("foo.yeti",
\\@export
\\square(x: i64) i64 {
\\ x * x
\\}
\\
\\@export
\\area(width: f64, height: f64) f64 {
\\ width * height
\\}
);
const module = try analyzeSemantics(codebase, fs, "foo.yeti");
try codegen(module);
const wasm = try printWasm(module);
try expectEqualStrings(wasm,
\\(module
\\
\\ (func $foo/square..x.i64 (param $x i64) (result i64)
\\ (local.get $x)
\\ (local.get $x)
\\ i64.mul)
\\
\\ (func $foo/area..width.f64..height.f64 (param $width f64) (param $height f64) (result f64)
\\ (local.get $width)
\\ (local.get $height)
\\ f64.mul)
\\
\\ (export "square" (func $foo/square..x.i64))
\\
\\ (export "area" (func $foo/area..width.f64..height.f64)))
);
} | src/tests/test_foreign_export.zig |
pub const WM_DEVICECHANGE = @as(u32, 537);
pub const BSM_VXDS = @as(u32, 1);
pub const BSM_NETDRIVER = @as(u32, 2);
pub const BSM_INSTALLABLEDRIVERS = @as(u32, 4);
pub const OFN_SHAREFALLTHROUGH = @as(u32, 2);
pub const OFN_SHARENOWARN = @as(u32, 1);
pub const OFN_SHAREWARN = @as(u32, 0);
pub const CDM_FIRST = @as(u32, 1124);
pub const CDM_LAST = @as(u32, 1224);
pub const CDM_GETSPEC = @as(u32, 1124);
pub const CDM_GETFILEPATH = @as(u32, 1125);
pub const CDM_GETFOLDERPATH = @as(u32, 1126);
pub const CDM_GETFOLDERIDLIST = @as(u32, 1127);
pub const CDM_SETCONTROLTEXT = @as(u32, 1128);
pub const CDM_HIDECONTROL = @as(u32, 1129);
pub const CDM_SETDEFEXT = @as(u32, 1130);
pub const FR_RAW = @as(u32, 131072);
pub const FR_SHOWWRAPAROUND = @as(u32, 262144);
pub const FR_NOWRAPAROUND = @as(u32, 524288);
pub const FR_WRAPAROUND = @as(u32, 1048576);
pub const FRM_FIRST = @as(u32, 1124);
pub const FRM_LAST = @as(u32, 1224);
pub const FRM_SETOPERATIONRESULT = @as(u32, 1124);
pub const FRM_SETOPERATIONRESULTTEXT = @as(u32, 1125);
pub const PS_OPENTYPE_FONTTYPE = @as(u32, 65536);
pub const TT_OPENTYPE_FONTTYPE = @as(u32, 131072);
pub const TYPE1_FONTTYPE = @as(u32, 262144);
pub const SYMBOL_FONTTYPE = @as(u32, 524288);
pub const WM_CHOOSEFONT_GETLOGFONT = @as(u32, 1025);
pub const WM_CHOOSEFONT_SETLOGFONT = @as(u32, 1125);
pub const WM_CHOOSEFONT_SETFLAGS = @as(u32, 1126);
pub const CD_LBSELNOITEMS = @as(i32, -1);
pub const CD_LBSELCHANGE = @as(u32, 0);
pub const CD_LBSELSUB = @as(u32, 1);
pub const CD_LBSELADD = @as(u32, 2);
pub const START_PAGE_GENERAL = @as(u32, 4294967295);
pub const PD_RESULT_CANCEL = @as(u32, 0);
pub const PD_RESULT_PRINT = @as(u32, 1);
pub const PD_RESULT_APPLY = @as(u32, 2);
pub const DN_DEFAULTPRN = @as(u32, 1);
pub const WM_PSD_FULLPAGERECT = @as(u32, 1025);
pub const WM_PSD_MINMARGINRECT = @as(u32, 1026);
pub const WM_PSD_MARGINRECT = @as(u32, 1027);
pub const WM_PSD_GREEKTEXTRECT = @as(u32, 1028);
pub const WM_PSD_ENVSTAMPRECT = @as(u32, 1029);
pub const WM_PSD_YAFULLPAGERECT = @as(u32, 1030);
// skipped 'RT_CURSOR'
// skipped 'RT_BITMAP'
// skipped 'RT_ICON'
// skipped 'RT_MENU'
// skipped 'RT_DIALOG'
// skipped 'RT_FONTDIR'
// skipped 'RT_FONT'
// skipped 'RT_ACCELERATOR'
// skipped 'RT_MESSAGETABLE'
pub const DIFFERENCE = @as(u32, 11);
// skipped 'RT_VERSION'
// skipped 'RT_DLGINCLUDE'
// skipped 'RT_PLUGPLAY'
// skipped 'RT_VXD'
// skipped 'RT_ANICURSOR'
// skipped 'RT_ANIICON'
// skipped 'RT_HTML'
pub const RT_MANIFEST = @as(u32, 24);
pub const CREATEPROCESS_MANIFEST_RESOURCE_ID = @as(u32, 1);
pub const ISOLATIONAWARE_MANIFEST_RESOURCE_ID = @as(u32, 2);
pub const ISOLATIONAWARE_NOSTATICIMPORT_MANIFEST_RESOURCE_ID = @as(u32, 3);
pub const ISOLATIONPOLICY_MANIFEST_RESOURCE_ID = @as(u32, 4);
pub const ISOLATIONPOLICY_BROWSER_MANIFEST_RESOURCE_ID = @as(u32, 5);
pub const MINIMUM_RESERVED_MANIFEST_RESOURCE_ID = @as(u32, 1);
pub const MAXIMUM_RESERVED_MANIFEST_RESOURCE_ID = @as(u32, 16);
pub const SB_LINEUP = @as(u32, 0);
pub const SB_LINELEFT = @as(u32, 0);
pub const SB_LINEDOWN = @as(u32, 1);
pub const SB_LINERIGHT = @as(u32, 1);
pub const SB_PAGEUP = @as(u32, 2);
pub const SB_PAGELEFT = @as(u32, 2);
pub const SB_PAGEDOWN = @as(u32, 3);
pub const SB_PAGERIGHT = @as(u32, 3);
pub const SB_THUMBPOSITION = @as(u32, 4);
pub const SB_THUMBTRACK = @as(u32, 5);
pub const SB_TOP = @as(u32, 6);
pub const SB_LEFT = @as(u32, 6);
pub const SB_BOTTOM = @as(u32, 7);
pub const SB_RIGHT = @as(u32, 7);
pub const SB_ENDSCROLL = @as(u32, 8);
pub const HIDE_WINDOW = @as(u32, 0);
pub const SHOW_OPENWINDOW = @as(u32, 1);
pub const SHOW_ICONWINDOW = @as(u32, 2);
pub const SHOW_FULLSCREEN = @as(u32, 3);
pub const SHOW_OPENNOACTIVATE = @as(u32, 4);
pub const KF_EXTENDED = @as(u32, 256);
pub const KF_DLGMODE = @as(u32, 2048);
pub const KF_MENUMODE = @as(u32, 4096);
pub const KF_ALTDOWN = @as(u32, 8192);
pub const KF_REPEAT = @as(u32, 16384);
pub const KF_UP = @as(u32, 32768);
pub const WH_MIN = @as(i32, -1);
pub const WH_HARDWARE = @as(u32, 8);
pub const WH_MAX = @as(u32, 14);
pub const HC_ACTION = @as(u32, 0);
pub const HC_GETNEXT = @as(u32, 1);
pub const HC_SKIP = @as(u32, 2);
pub const HC_NOREMOVE = @as(u32, 3);
pub const HC_SYSMODALON = @as(u32, 4);
pub const HC_SYSMODALOFF = @as(u32, 5);
pub const HCBT_MOVESIZE = @as(u32, 0);
pub const HCBT_MINMAX = @as(u32, 1);
pub const HCBT_QS = @as(u32, 2);
pub const HCBT_CREATEWND = @as(u32, 3);
pub const HCBT_DESTROYWND = @as(u32, 4);
pub const HCBT_ACTIVATE = @as(u32, 5);
pub const HCBT_CLICKSKIPPED = @as(u32, 6);
pub const HCBT_KEYSKIPPED = @as(u32, 7);
pub const HCBT_SYSCOMMAND = @as(u32, 8);
pub const HCBT_SETFOCUS = @as(u32, 9);
pub const WTS_CONSOLE_CONNECT = @as(u32, 1);
pub const WTS_CONSOLE_DISCONNECT = @as(u32, 2);
pub const WTS_REMOTE_CONNECT = @as(u32, 3);
pub const WTS_REMOTE_DISCONNECT = @as(u32, 4);
pub const WTS_SESSION_LOGON = @as(u32, 5);
pub const WTS_SESSION_LOGOFF = @as(u32, 6);
pub const WTS_SESSION_LOCK = @as(u32, 7);
pub const WTS_SESSION_UNLOCK = @as(u32, 8);
pub const WTS_SESSION_REMOTE_CONTROL = @as(u32, 9);
pub const WTS_SESSION_CREATE = @as(u32, 10);
pub const WTS_SESSION_TERMINATE = @as(u32, 11);
pub const MSGF_DIALOGBOX = @as(u32, 0);
pub const MSGF_MESSAGEBOX = @as(u32, 1);
pub const MSGF_MENU = @as(u32, 2);
pub const MSGF_SCROLLBAR = @as(u32, 5);
pub const MSGF_NEXTWINDOW = @as(u32, 6);
pub const MSGF_MAX = @as(u32, 8);
pub const MSGF_USER = @as(u32, 4096);
pub const HSHELL_WINDOWCREATED = @as(u32, 1);
pub const HSHELL_WINDOWDESTROYED = @as(u32, 2);
pub const HSHELL_ACTIVATESHELLWINDOW = @as(u32, 3);
pub const HSHELL_WINDOWACTIVATED = @as(u32, 4);
pub const HSHELL_GETMINRECT = @as(u32, 5);
pub const HSHELL_REDRAW = @as(u32, 6);
pub const HSHELL_TASKMAN = @as(u32, 7);
pub const HSHELL_LANGUAGE = @as(u32, 8);
pub const HSHELL_SYSMENU = @as(u32, 9);
pub const HSHELL_ENDTASK = @as(u32, 10);
pub const HSHELL_ACCESSIBILITYSTATE = @as(u32, 11);
pub const HSHELL_APPCOMMAND = @as(u32, 12);
pub const HSHELL_WINDOWREPLACED = @as(u32, 13);
pub const HSHELL_WINDOWREPLACING = @as(u32, 14);
pub const HSHELL_MONITORCHANGED = @as(u32, 16);
pub const HSHELL_HIGHBIT = @as(u32, 32768);
pub const FAPPCOMMAND_MOUSE = @as(u32, 32768);
pub const FAPPCOMMAND_KEY = @as(u32, 0);
pub const FAPPCOMMAND_OEM = @as(u32, 4096);
pub const FAPPCOMMAND_MASK = @as(u32, 61440);
pub const LLMHF_INJECTED = @as(u32, 1);
pub const LLMHF_LOWER_IL_INJECTED = @as(u32, 2);
pub const HKL_PREV = @as(u32, 0);
pub const HKL_NEXT = @as(u32, 1);
pub const INPUTLANGCHANGE_SYSCHARSET = @as(u32, 1);
pub const INPUTLANGCHANGE_FORWARD = @as(u32, 2);
pub const INPUTLANGCHANGE_BACKWARD = @as(u32, 4);
pub const KL_NAMELENGTH = @as(u32, 9);
pub const DESKTOP_READOBJECTS = @as(i32, 1);
pub const DESKTOP_CREATEWINDOW = @as(i32, 2);
pub const DESKTOP_CREATEMENU = @as(i32, 4);
pub const DESKTOP_HOOKCONTROL = @as(i32, 8);
pub const DESKTOP_JOURNALRECORD = @as(i32, 16);
pub const DESKTOP_JOURNALPLAYBACK = @as(i32, 32);
pub const DESKTOP_ENUMERATE = @as(i32, 64);
pub const DESKTOP_WRITEOBJECTS = @as(i32, 128);
pub const DESKTOP_SWITCHDESKTOP = @as(i32, 256);
pub const DF_ALLOWOTHERACCOUNTHOOK = @as(i32, 1);
pub const WINSTA_ENUMDESKTOPS = @as(i32, 1);
pub const WINSTA_READATTRIBUTES = @as(i32, 2);
pub const WINSTA_ACCESSCLIPBOARD = @as(i32, 4);
pub const WINSTA_CREATEDESKTOP = @as(i32, 8);
pub const WINSTA_WRITEATTRIBUTES = @as(i32, 16);
pub const WINSTA_ACCESSGLOBALATOMS = @as(i32, 32);
pub const WINSTA_EXITWINDOWS = @as(i32, 64);
pub const WINSTA_ENUMERATE = @as(i32, 256);
pub const WINSTA_READSCREEN = @as(i32, 512);
pub const CWF_CREATE_ONLY = @as(u32, 1);
pub const WSF_VISIBLE = @as(i32, 1);
pub const UOI_TIMERPROC_EXCEPTION_SUPPRESSION = @as(u32, 7);
pub const WM_NULL = @as(u32, 0);
pub const WM_CREATE = @as(u32, 1);
pub const WM_DESTROY = @as(u32, 2);
pub const WM_MOVE = @as(u32, 3);
pub const WM_SIZE = @as(u32, 5);
pub const WM_ACTIVATE = @as(u32, 6);
pub const WA_INACTIVE = @as(u32, 0);
pub const WA_ACTIVE = @as(u32, 1);
pub const WA_CLICKACTIVE = @as(u32, 2);
pub const WM_SETFOCUS = @as(u32, 7);
pub const WM_KILLFOCUS = @as(u32, 8);
pub const WM_ENABLE = @as(u32, 10);
pub const WM_SETREDRAW = @as(u32, 11);
pub const WM_SETTEXT = @as(u32, 12);
pub const WM_GETTEXT = @as(u32, 13);
pub const WM_GETTEXTLENGTH = @as(u32, 14);
pub const WM_PAINT = @as(u32, 15);
pub const WM_CLOSE = @as(u32, 16);
pub const WM_QUERYENDSESSION = @as(u32, 17);
pub const WM_QUERYOPEN = @as(u32, 19);
pub const WM_ENDSESSION = @as(u32, 22);
pub const WM_QUIT = @as(u32, 18);
pub const WM_ERASEBKGND = @as(u32, 20);
pub const WM_SYSCOLORCHANGE = @as(u32, 21);
pub const WM_SHOWWINDOW = @as(u32, 24);
pub const WM_WININICHANGE = @as(u32, 26);
pub const WM_DEVMODECHANGE = @as(u32, 27);
pub const WM_ACTIVATEAPP = @as(u32, 28);
pub const WM_FONTCHANGE = @as(u32, 29);
pub const WM_TIMECHANGE = @as(u32, 30);
pub const WM_CANCELMODE = @as(u32, 31);
pub const WM_SETCURSOR = @as(u32, 32);
pub const WM_MOUSEACTIVATE = @as(u32, 33);
pub const WM_CHILDACTIVATE = @as(u32, 34);
pub const WM_QUEUESYNC = @as(u32, 35);
pub const WM_GETMINMAXINFO = @as(u32, 36);
pub const WM_PAINTICON = @as(u32, 38);
pub const WM_ICONERASEBKGND = @as(u32, 39);
pub const WM_NEXTDLGCTL = @as(u32, 40);
pub const WM_SPOOLERSTATUS = @as(u32, 42);
pub const WM_DRAWITEM = @as(u32, 43);
pub const WM_MEASUREITEM = @as(u32, 44);
pub const WM_DELETEITEM = @as(u32, 45);
pub const WM_VKEYTOITEM = @as(u32, 46);
pub const WM_CHARTOITEM = @as(u32, 47);
pub const WM_SETFONT = @as(u32, 48);
pub const WM_GETFONT = @as(u32, 49);
pub const WM_SETHOTKEY = @as(u32, 50);
pub const WM_GETHOTKEY = @as(u32, 51);
pub const WM_QUERYDRAGICON = @as(u32, 55);
pub const WM_COMPAREITEM = @as(u32, 57);
pub const WM_GETOBJECT = @as(u32, 61);
pub const WM_COMPACTING = @as(u32, 65);
pub const WM_COMMNOTIFY = @as(u32, 68);
pub const WM_WINDOWPOSCHANGING = @as(u32, 70);
pub const WM_WINDOWPOSCHANGED = @as(u32, 71);
pub const WM_POWER = @as(u32, 72);
pub const PWR_OK = @as(u32, 1);
pub const PWR_FAIL = @as(i32, -1);
pub const PWR_SUSPENDREQUEST = @as(u32, 1);
pub const PWR_SUSPENDRESUME = @as(u32, 2);
pub const PWR_CRITICALRESUME = @as(u32, 3);
pub const WM_COPYDATA = @as(u32, 74);
pub const WM_CANCELJOURNAL = @as(u32, 75);
pub const WM_INPUTLANGCHANGEREQUEST = @as(u32, 80);
pub const WM_INPUTLANGCHANGE = @as(u32, 81);
pub const WM_TCARD = @as(u32, 82);
pub const WM_HELP = @as(u32, 83);
pub const WM_USERCHANGED = @as(u32, 84);
pub const WM_NOTIFYFORMAT = @as(u32, 85);
pub const NFR_ANSI = @as(u32, 1);
pub const NFR_UNICODE = @as(u32, 2);
pub const NF_QUERY = @as(u32, 3);
pub const NF_REQUERY = @as(u32, 4);
pub const WM_STYLECHANGING = @as(u32, 124);
pub const WM_STYLECHANGED = @as(u32, 125);
pub const WM_DISPLAYCHANGE = @as(u32, 126);
pub const WM_GETICON = @as(u32, 127);
pub const WM_SETICON = @as(u32, 128);
pub const WM_NCCREATE = @as(u32, 129);
pub const WM_NCDESTROY = @as(u32, 130);
pub const WM_NCCALCSIZE = @as(u32, 131);
pub const WM_NCHITTEST = @as(u32, 132);
pub const WM_NCPAINT = @as(u32, 133);
pub const WM_NCACTIVATE = @as(u32, 134);
pub const WM_GETDLGCODE = @as(u32, 135);
pub const WM_SYNCPAINT = @as(u32, 136);
pub const WM_NCMOUSEMOVE = @as(u32, 160);
pub const WM_NCLBUTTONDOWN = @as(u32, 161);
pub const WM_NCLBUTTONUP = @as(u32, 162);
pub const WM_NCLBUTTONDBLCLK = @as(u32, 163);
pub const WM_NCRBUTTONDOWN = @as(u32, 164);
pub const WM_NCRBUTTONUP = @as(u32, 165);
pub const WM_NCRBUTTONDBLCLK = @as(u32, 166);
pub const WM_NCMBUTTONDOWN = @as(u32, 167);
pub const WM_NCMBUTTONUP = @as(u32, 168);
pub const WM_NCMBUTTONDBLCLK = @as(u32, 169);
pub const WM_NCXBUTTONDOWN = @as(u32, 171);
pub const WM_NCXBUTTONUP = @as(u32, 172);
pub const WM_NCXBUTTONDBLCLK = @as(u32, 173);
pub const WM_INPUT_DEVICE_CHANGE = @as(u32, 254);
pub const WM_INPUT = @as(u32, 255);
pub const WM_KEYFIRST = @as(u32, 256);
pub const WM_KEYDOWN = @as(u32, 256);
pub const WM_KEYUP = @as(u32, 257);
pub const WM_CHAR = @as(u32, 258);
pub const WM_DEADCHAR = @as(u32, 259);
pub const WM_SYSKEYDOWN = @as(u32, 260);
pub const WM_SYSKEYUP = @as(u32, 261);
pub const WM_SYSCHAR = @as(u32, 262);
pub const WM_SYSDEADCHAR = @as(u32, 263);
pub const WM_KEYLAST = @as(u32, 265);
pub const UNICODE_NOCHAR = @as(u32, 65535);
pub const WM_IME_STARTCOMPOSITION = @as(u32, 269);
pub const WM_IME_ENDCOMPOSITION = @as(u32, 270);
pub const WM_IME_COMPOSITION = @as(u32, 271);
pub const WM_IME_KEYLAST = @as(u32, 271);
pub const WM_INITDIALOG = @as(u32, 272);
pub const WM_COMMAND = @as(u32, 273);
pub const WM_SYSCOMMAND = @as(u32, 274);
pub const WM_TIMER = @as(u32, 275);
pub const WM_HSCROLL = @as(u32, 276);
pub const WM_VSCROLL = @as(u32, 277);
pub const WM_INITMENU = @as(u32, 278);
pub const WM_INITMENUPOPUP = @as(u32, 279);
pub const WM_GESTURE = @as(u32, 281);
pub const WM_GESTURENOTIFY = @as(u32, 282);
pub const WM_MENUSELECT = @as(u32, 287);
pub const WM_MENUCHAR = @as(u32, 288);
pub const WM_ENTERIDLE = @as(u32, 289);
pub const WM_MENURBUTTONUP = @as(u32, 290);
pub const WM_MENUDRAG = @as(u32, 291);
pub const WM_MENUGETOBJECT = @as(u32, 292);
pub const WM_UNINITMENUPOPUP = @as(u32, 293);
pub const WM_MENUCOMMAND = @as(u32, 294);
pub const WM_CHANGEUISTATE = @as(u32, 295);
pub const WM_UPDATEUISTATE = @as(u32, 296);
pub const WM_QUERYUISTATE = @as(u32, 297);
pub const UIS_SET = @as(u32, 1);
pub const UIS_CLEAR = @as(u32, 2);
pub const UIS_INITIALIZE = @as(u32, 3);
pub const UISF_HIDEFOCUS = @as(u32, 1);
pub const UISF_HIDEACCEL = @as(u32, 2);
pub const UISF_ACTIVE = @as(u32, 4);
pub const WM_CTLCOLORMSGBOX = @as(u32, 306);
pub const WM_CTLCOLOREDIT = @as(u32, 307);
pub const WM_CTLCOLORLISTBOX = @as(u32, 308);
pub const WM_CTLCOLORBTN = @as(u32, 309);
pub const WM_CTLCOLORDLG = @as(u32, 310);
pub const WM_CTLCOLORSCROLLBAR = @as(u32, 311);
pub const WM_CTLCOLORSTATIC = @as(u32, 312);
pub const MN_GETHMENU = @as(u32, 481);
pub const WM_MOUSEFIRST = @as(u32, 512);
pub const WM_MOUSEMOVE = @as(u32, 512);
pub const WM_LBUTTONDOWN = @as(u32, 513);
pub const WM_LBUTTONUP = @as(u32, 514);
pub const WM_LBUTTONDBLCLK = @as(u32, 515);
pub const WM_RBUTTONDOWN = @as(u32, 516);
pub const WM_RBUTTONUP = @as(u32, 517);
pub const WM_RBUTTONDBLCLK = @as(u32, 518);
pub const WM_MBUTTONDOWN = @as(u32, 519);
pub const WM_MBUTTONUP = @as(u32, 520);
pub const WM_MBUTTONDBLCLK = @as(u32, 521);
pub const WM_MOUSEWHEEL = @as(u32, 522);
pub const WM_XBUTTONDOWN = @as(u32, 523);
pub const WM_XBUTTONUP = @as(u32, 524);
pub const WM_XBUTTONDBLCLK = @as(u32, 525);
pub const WM_MOUSEHWHEEL = @as(u32, 526);
pub const WM_MOUSELAST = @as(u32, 526);
pub const WHEEL_DELTA = @as(u32, 120);
pub const WM_PARENTNOTIFY = @as(u32, 528);
pub const WM_ENTERMENULOOP = @as(u32, 529);
pub const WM_EXITMENULOOP = @as(u32, 530);
pub const WM_NEXTMENU = @as(u32, 531);
pub const WM_SIZING = @as(u32, 532);
pub const WM_CAPTURECHANGED = @as(u32, 533);
pub const WM_MOVING = @as(u32, 534);
pub const WM_POWERBROADCAST = @as(u32, 536);
pub const PBT_APMQUERYSUSPEND = @as(u32, 0);
pub const PBT_APMQUERYSTANDBY = @as(u32, 1);
pub const PBT_APMQUERYSUSPENDFAILED = @as(u32, 2);
pub const PBT_APMQUERYSTANDBYFAILED = @as(u32, 3);
pub const PBT_APMSUSPEND = @as(u32, 4);
pub const PBT_APMSTANDBY = @as(u32, 5);
pub const PBT_APMRESUMECRITICAL = @as(u32, 6);
pub const PBT_APMRESUMESUSPEND = @as(u32, 7);
pub const PBT_APMRESUMESTANDBY = @as(u32, 8);
pub const PBTF_APMRESUMEFROMFAILURE = @as(u32, 1);
pub const PBT_APMBATTERYLOW = @as(u32, 9);
pub const PBT_APMPOWERSTATUSCHANGE = @as(u32, 10);
pub const PBT_APMOEMEVENT = @as(u32, 11);
pub const PBT_APMRESUMEAUTOMATIC = @as(u32, 18);
pub const PBT_POWERSETTINGCHANGE = @as(u32, 32787);
pub const WM_MDICREATE = @as(u32, 544);
pub const WM_MDIDESTROY = @as(u32, 545);
pub const WM_MDIACTIVATE = @as(u32, 546);
pub const WM_MDIRESTORE = @as(u32, 547);
pub const WM_MDINEXT = @as(u32, 548);
pub const WM_MDIMAXIMIZE = @as(u32, 549);
pub const WM_MDITILE = @as(u32, 550);
pub const WM_MDICASCADE = @as(u32, 551);
pub const WM_MDIICONARRANGE = @as(u32, 552);
pub const WM_MDIGETACTIVE = @as(u32, 553);
pub const WM_MDISETMENU = @as(u32, 560);
pub const WM_ENTERSIZEMOVE = @as(u32, 561);
pub const WM_EXITSIZEMOVE = @as(u32, 562);
pub const WM_DROPFILES = @as(u32, 563);
pub const WM_MDIREFRESHMENU = @as(u32, 564);
pub const WM_POINTERDEVICECHANGE = @as(u32, 568);
pub const WM_POINTERDEVICEINRANGE = @as(u32, 569);
pub const WM_POINTERDEVICEOUTOFRANGE = @as(u32, 570);
pub const WM_TOUCH = @as(u32, 576);
pub const WM_NCPOINTERUPDATE = @as(u32, 577);
pub const WM_NCPOINTERDOWN = @as(u32, 578);
pub const WM_NCPOINTERUP = @as(u32, 579);
pub const WM_POINTERUPDATE = @as(u32, 581);
pub const WM_POINTERDOWN = @as(u32, 582);
pub const WM_POINTERUP = @as(u32, 583);
pub const WM_POINTERENTER = @as(u32, 585);
pub const WM_POINTERLEAVE = @as(u32, 586);
pub const WM_POINTERACTIVATE = @as(u32, 587);
pub const WM_POINTERCAPTURECHANGED = @as(u32, 588);
pub const WM_TOUCHHITTESTING = @as(u32, 589);
pub const WM_POINTERWHEEL = @as(u32, 590);
pub const WM_POINTERHWHEEL = @as(u32, 591);
pub const DM_POINTERHITTEST = @as(u32, 592);
pub const WM_POINTERROUTEDTO = @as(u32, 593);
pub const WM_POINTERROUTEDAWAY = @as(u32, 594);
pub const WM_POINTERROUTEDRELEASED = @as(u32, 595);
pub const WM_IME_SETCONTEXT = @as(u32, 641);
pub const WM_IME_NOTIFY = @as(u32, 642);
pub const WM_IME_CONTROL = @as(u32, 643);
pub const WM_IME_COMPOSITIONFULL = @as(u32, 644);
pub const WM_IME_SELECT = @as(u32, 645);
pub const WM_IME_CHAR = @as(u32, 646);
pub const WM_IME_REQUEST = @as(u32, 648);
pub const WM_IME_KEYDOWN = @as(u32, 656);
pub const WM_IME_KEYUP = @as(u32, 657);
pub const WM_NCMOUSEHOVER = @as(u32, 672);
pub const WM_NCMOUSELEAVE = @as(u32, 674);
pub const WM_WTSSESSION_CHANGE = @as(u32, 689);
pub const WM_TABLET_FIRST = @as(u32, 704);
pub const WM_TABLET_LAST = @as(u32, 735);
pub const WM_DPICHANGED = @as(u32, 736);
pub const WM_DPICHANGED_BEFOREPARENT = @as(u32, 738);
pub const WM_DPICHANGED_AFTERPARENT = @as(u32, 739);
pub const WM_GETDPISCALEDSIZE = @as(u32, 740);
pub const WM_CUT = @as(u32, 768);
pub const WM_COPY = @as(u32, 769);
pub const WM_PASTE = @as(u32, 770);
pub const WM_CLEAR = @as(u32, 771);
pub const WM_UNDO = @as(u32, 772);
pub const WM_RENDERFORMAT = @as(u32, 773);
pub const WM_RENDERALLFORMATS = @as(u32, 774);
pub const WM_DESTROYCLIPBOARD = @as(u32, 775);
pub const WM_DRAWCLIPBOARD = @as(u32, 776);
pub const WM_PAINTCLIPBOARD = @as(u32, 777);
pub const WM_VSCROLLCLIPBOARD = @as(u32, 778);
pub const WM_SIZECLIPBOARD = @as(u32, 779);
pub const WM_ASKCBFORMATNAME = @as(u32, 780);
pub const WM_CHANGECBCHAIN = @as(u32, 781);
pub const WM_HSCROLLCLIPBOARD = @as(u32, 782);
pub const WM_QUERYNEWPALETTE = @as(u32, 783);
pub const WM_PALETTEISCHANGING = @as(u32, 784);
pub const WM_PALETTECHANGED = @as(u32, 785);
pub const WM_HOTKEY = @as(u32, 786);
pub const WM_PRINT = @as(u32, 791);
pub const WM_APPCOMMAND = @as(u32, 793);
pub const WM_THEMECHANGED = @as(u32, 794);
pub const WM_CLIPBOARDUPDATE = @as(u32, 797);
pub const WM_DWMCOMPOSITIONCHANGED = @as(u32, 798);
pub const WM_DWMNCRENDERINGCHANGED = @as(u32, 799);
pub const WM_DWMCOLORIZATIONCOLORCHANGED = @as(u32, 800);
pub const WM_DWMWINDOWMAXIMIZEDCHANGE = @as(u32, 801);
pub const WM_DWMSENDICONICTHUMBNAIL = @as(u32, 803);
pub const WM_DWMSENDICONICLIVEPREVIEWBITMAP = @as(u32, 806);
pub const WM_GETTITLEBARINFOEX = @as(u32, 831);
pub const WM_HANDHELDFIRST = @as(u32, 856);
pub const WM_HANDHELDLAST = @as(u32, 863);
pub const WM_AFXFIRST = @as(u32, 864);
pub const WM_AFXLAST = @as(u32, 895);
pub const WM_PENWINFIRST = @as(u32, 896);
pub const WM_PENWINLAST = @as(u32, 911);
pub const WM_APP = @as(u32, 32768);
pub const WM_USER = @as(u32, 1024);
pub const WMSZ_LEFT = @as(u32, 1);
pub const WMSZ_RIGHT = @as(u32, 2);
pub const WMSZ_TOP = @as(u32, 3);
pub const WMSZ_TOPLEFT = @as(u32, 4);
pub const WMSZ_TOPRIGHT = @as(u32, 5);
pub const WMSZ_BOTTOM = @as(u32, 6);
pub const WMSZ_BOTTOMLEFT = @as(u32, 7);
pub const WMSZ_BOTTOMRIGHT = @as(u32, 8);
pub const HTERROR = @as(i32, -2);
pub const HTTRANSPARENT = @as(i32, -1);
pub const HTNOWHERE = @as(u32, 0);
pub const HTCLIENT = @as(u32, 1);
pub const HTCAPTION = @as(u32, 2);
pub const HTSYSMENU = @as(u32, 3);
pub const HTGROWBOX = @as(u32, 4);
pub const HTMENU = @as(u32, 5);
pub const HTHSCROLL = @as(u32, 6);
pub const HTVSCROLL = @as(u32, 7);
pub const HTMINBUTTON = @as(u32, 8);
pub const HTMAXBUTTON = @as(u32, 9);
pub const HTLEFT = @as(u32, 10);
pub const HTRIGHT = @as(u32, 11);
pub const HTTOP = @as(u32, 12);
pub const HTTOPLEFT = @as(u32, 13);
pub const HTTOPRIGHT = @as(u32, 14);
pub const HTBOTTOM = @as(u32, 15);
pub const HTBOTTOMLEFT = @as(u32, 16);
pub const HTBOTTOMRIGHT = @as(u32, 17);
pub const HTBORDER = @as(u32, 18);
pub const HTOBJECT = @as(u32, 19);
pub const HTCLOSE = @as(u32, 20);
pub const HTHELP = @as(u32, 21);
pub const MA_ACTIVATE = @as(u32, 1);
pub const MA_ACTIVATEANDEAT = @as(u32, 2);
pub const MA_NOACTIVATE = @as(u32, 3);
pub const MA_NOACTIVATEANDEAT = @as(u32, 4);
pub const ICON_SMALL = @as(u32, 0);
pub const ICON_BIG = @as(u32, 1);
pub const ICON_SMALL2 = @as(u32, 2);
pub const SIZE_RESTORED = @as(u32, 0);
pub const SIZE_MINIMIZED = @as(u32, 1);
pub const SIZE_MAXIMIZED = @as(u32, 2);
pub const SIZE_MAXSHOW = @as(u32, 3);
pub const SIZE_MAXHIDE = @as(u32, 4);
pub const WVR_ALIGNTOP = @as(u32, 16);
pub const WVR_ALIGNLEFT = @as(u32, 32);
pub const WVR_ALIGNBOTTOM = @as(u32, 64);
pub const WVR_ALIGNRIGHT = @as(u32, 128);
pub const WVR_HREDRAW = @as(u32, 256);
pub const WVR_VREDRAW = @as(u32, 512);
pub const WVR_VALIDRECTS = @as(u32, 1024);
pub const MK_LBUTTON = @as(u32, 1);
pub const MK_RBUTTON = @as(u32, 2);
pub const MK_SHIFT = @as(u32, 4);
pub const MK_CONTROL = @as(u32, 8);
pub const MK_MBUTTON = @as(u32, 16);
pub const MK_XBUTTON1 = @as(u32, 32);
pub const MK_XBUTTON2 = @as(u32, 64);
pub const PRF_CHECKVISIBLE = @as(i32, 1);
pub const PRF_NONCLIENT = @as(i32, 2);
pub const PRF_CLIENT = @as(i32, 4);
pub const PRF_ERASEBKGND = @as(i32, 8);
pub const PRF_CHILDREN = @as(i32, 16);
pub const PRF_OWNED = @as(i32, 32);
pub const IDANI_OPEN = @as(u32, 1);
pub const IDANI_CAPTION = @as(u32, 3);
pub const FVIRTKEY = @as(u32, 1);
pub const FNOINVERT = @as(u32, 2);
pub const FSHIFT = @as(u32, 4);
pub const FCONTROL = @as(u32, 8);
pub const FALT = @as(u32, 16);
pub const ODA_DRAWENTIRE = @as(u32, 1);
pub const ODA_SELECT = @as(u32, 2);
pub const ODA_FOCUS = @as(u32, 4);
pub const ODS_SELECTED = @as(u32, 1);
pub const ODS_GRAYED = @as(u32, 2);
pub const ODS_DISABLED = @as(u32, 4);
pub const ODS_CHECKED = @as(u32, 8);
pub const ODS_FOCUS = @as(u32, 16);
pub const ODS_DEFAULT = @as(u32, 32);
pub const ODS_COMBOBOXEDIT = @as(u32, 4096);
pub const ODS_HOTLIGHT = @as(u32, 64);
pub const ODS_INACTIVE = @as(u32, 128);
pub const ODS_NOACCEL = @as(u32, 256);
pub const ODS_NOFOCUSRECT = @as(u32, 512);
pub const IDHOT_SNAPWINDOW = @as(i32, -1);
pub const IDHOT_SNAPDESKTOP = @as(i32, -2);
pub const ENDSESSION_CLOSEAPP = @as(u32, 1);
pub const ENDSESSION_CRITICAL = @as(u32, 1073741824);
pub const ENDSESSION_LOGOFF = @as(u32, 2147483648);
pub const EWX_FORCE = @as(u32, 4);
pub const EWX_FORCEIFHUNG = @as(u32, 16);
pub const EWX_QUICKRESOLVE = @as(u32, 32);
pub const EWX_BOOTOPTIONS = @as(u32, 16777216);
pub const EWX_ARSO = @as(u32, 67108864);
pub const BROADCAST_QUERY_DENY = @as(u32, 1112363332);
pub const DEVICE_NOTIFY_ALL_INTERFACE_CLASSES = @as(u32, 4);
pub const HWND_MESSAGE = @import("../zig.zig").typedConst(HWND, @as(i32, -3));
pub const ISMEX_NOSEND = @as(u32, 0);
pub const ISMEX_SEND = @as(u32, 1);
pub const ISMEX_NOTIFY = @as(u32, 2);
pub const ISMEX_CALLBACK = @as(u32, 4);
pub const ISMEX_REPLIED = @as(u32, 8);
// skipped 'HWND_DESKTOP'
pub const PW_RENDERFULLCONTENT = @as(u32, 2);
// skipped 'HWND_TOP'
pub const HWND_BOTTOM = @import("../zig.zig").typedConst(HWND, @as(i32, 1));
pub const HWND_TOPMOST = @import("../zig.zig").typedConst(HWND, @as(i32, -1));
pub const HWND_NOTOPMOST = @import("../zig.zig").typedConst(HWND, @as(i32, -2));
pub const DLGWINDOWEXTRA = @as(u32, 30);
pub const POINTER_MOD_SHIFT = @as(u32, 4);
pub const POINTER_MOD_CTRL = @as(u32, 8);
pub const TOUCH_FLAG_NONE = @as(u32, 0);
pub const TOUCH_MASK_NONE = @as(u32, 0);
pub const TOUCH_MASK_CONTACTAREA = @as(u32, 1);
pub const TOUCH_MASK_ORIENTATION = @as(u32, 2);
pub const TOUCH_MASK_PRESSURE = @as(u32, 4);
pub const PEN_FLAG_NONE = @as(u32, 0);
pub const PEN_FLAG_BARREL = @as(u32, 1);
pub const PEN_FLAG_INVERTED = @as(u32, 2);
pub const PEN_FLAG_ERASER = @as(u32, 4);
pub const PEN_MASK_NONE = @as(u32, 0);
pub const PEN_MASK_PRESSURE = @as(u32, 1);
pub const PEN_MASK_ROTATION = @as(u32, 2);
pub const PEN_MASK_TILT_X = @as(u32, 4);
pub const PEN_MASK_TILT_Y = @as(u32, 8);
pub const POINTER_MESSAGE_FLAG_NEW = @as(u32, 1);
pub const POINTER_MESSAGE_FLAG_INRANGE = @as(u32, 2);
pub const POINTER_MESSAGE_FLAG_INCONTACT = @as(u32, 4);
pub const POINTER_MESSAGE_FLAG_FIRSTBUTTON = @as(u32, 16);
pub const POINTER_MESSAGE_FLAG_SECONDBUTTON = @as(u32, 32);
pub const POINTER_MESSAGE_FLAG_THIRDBUTTON = @as(u32, 64);
pub const POINTER_MESSAGE_FLAG_FOURTHBUTTON = @as(u32, 128);
pub const POINTER_MESSAGE_FLAG_FIFTHBUTTON = @as(u32, 256);
pub const POINTER_MESSAGE_FLAG_PRIMARY = @as(u32, 8192);
pub const POINTER_MESSAGE_FLAG_CONFIDENCE = @as(u32, 16384);
pub const POINTER_MESSAGE_FLAG_CANCELED = @as(u32, 32768);
pub const MAX_TOUCH_COUNT = @as(u32, 256);
pub const TOUCH_HIT_TESTING_DEFAULT = @as(u32, 0);
pub const TOUCH_HIT_TESTING_CLIENT = @as(u32, 1);
pub const TOUCH_HIT_TESTING_NONE = @as(u32, 2);
pub const TOUCH_HIT_TESTING_PROXIMITY_CLOSEST = @as(u32, 0);
pub const TOUCH_HIT_TESTING_PROXIMITY_FARTHEST = @as(u32, 4095);
pub const GWFS_INCLUDE_ANCESTORS = @as(u32, 1);
pub const MAPVK_VK_TO_VSC = @as(u32, 0);
pub const MAPVK_VSC_TO_VK = @as(u32, 1);
pub const MAPVK_VK_TO_CHAR = @as(u32, 2);
pub const MAPVK_VSC_TO_VK_EX = @as(u32, 3);
pub const MAPVK_VK_TO_VSC_EX = @as(u32, 4);
pub const QS_TOUCH = @as(u32, 2048);
pub const QS_POINTER = @as(u32, 4096);
pub const USER_TIMER_MAXIMUM = @as(u32, 2147483647);
pub const USER_TIMER_MINIMUM = @as(u32, 10);
pub const TIMERV_DEFAULT_COALESCING = @as(u32, 0);
pub const TIMERV_NO_COALESCING = @as(u32, 4294967295);
pub const TIMERV_COALESCING_MIN = @as(u32, 1);
pub const TIMERV_COALESCING_MAX = @as(u32, 2147483637);
pub const SM_RESERVED1 = @as(u32, 24);
pub const SM_RESERVED2 = @as(u32, 25);
pub const SM_RESERVED3 = @as(u32, 26);
pub const SM_RESERVED4 = @as(u32, 27);
pub const SM_CMETRICS = @as(u32, 76);
pub const SM_CARETBLINKINGENABLED = @as(u32, 8194);
pub const SM_SYSTEMDOCKED = @as(u32, 8196);
pub const PMB_ACTIVE = @as(u32, 1);
pub const MNC_IGNORE = @as(u32, 0);
pub const MNC_CLOSE = @as(u32, 1);
pub const MNC_EXECUTE = @as(u32, 2);
pub const MNC_SELECT = @as(u32, 3);
pub const MND_CONTINUE = @as(u32, 0);
pub const MND_ENDMENU = @as(u32, 1);
pub const MNGO_NOINTERFACE = @as(u32, 0);
pub const MNGO_NOERROR = @as(u32, 1);
pub const DOF_EXECUTABLE = @as(u32, 32769);
pub const DOF_DOCUMENT = @as(u32, 32770);
pub const DOF_DIRECTORY = @as(u32, 32771);
pub const DOF_MULTIPLE = @as(u32, 32772);
pub const DOF_PROGMAN = @as(u32, 1);
pub const DOF_SHELLDATA = @as(u32, 2);
pub const DO_DROPFILE = @as(i32, 1162627398);
pub const DO_PRINTFILE = @as(i32, 1414419024);
pub const ASFW_ANY = @as(u32, 4294967295);
pub const DCX_EXCLUDEUPDATE = @as(i32, 256);
pub const HELPINFO_WINDOW = @as(u32, 1);
pub const HELPINFO_MENUITEM = @as(u32, 2);
pub const CTLCOLOR_MSGBOX = @as(u32, 0);
pub const CTLCOLOR_EDIT = @as(u32, 1);
pub const CTLCOLOR_LISTBOX = @as(u32, 2);
pub const CTLCOLOR_BTN = @as(u32, 3);
pub const CTLCOLOR_DLG = @as(u32, 4);
pub const CTLCOLOR_SCROLLBAR = @as(u32, 5);
pub const CTLCOLOR_STATIC = @as(u32, 6);
pub const CTLCOLOR_MAX = @as(u32, 7);
pub const COLOR_BTNHIGHLIGHT = @as(u32, 20);
pub const GW_MAX = @as(u32, 5);
pub const SC_SIZE = @as(u32, 61440);
pub const SC_MOVE = @as(u32, 61456);
pub const SC_MINIMIZE = @as(u32, 61472);
pub const SC_MAXIMIZE = @as(u32, 61488);
pub const SC_NEXTWINDOW = @as(u32, 61504);
pub const SC_PREVWINDOW = @as(u32, 61520);
pub const SC_CLOSE = @as(u32, 61536);
pub const SC_VSCROLL = @as(u32, 61552);
pub const SC_HSCROLL = @as(u32, 61568);
pub const SC_MOUSEMENU = @as(u32, 61584);
pub const SC_KEYMENU = @as(u32, 61696);
pub const SC_ARRANGE = @as(u32, 61712);
pub const SC_RESTORE = @as(u32, 61728);
pub const SC_TASKLIST = @as(u32, 61744);
pub const SC_SCREENSAVE = @as(u32, 61760);
pub const SC_HOTKEY = @as(u32, 61776);
pub const SC_DEFAULT = @as(u32, 61792);
pub const SC_MONITORPOWER = @as(u32, 61808);
pub const SC_CONTEXTHELP = @as(u32, 61824);
pub const SC_SEPARATOR = @as(u32, 61455);
pub const SCF_ISSECURE = @as(u32, 1);
pub const IDC_ARROW = @import("../zig.zig").typedConst([*:0]const u16, @as(i32, 32512));
// skipped 'IDC_IBEAM'
// skipped 'IDC_WAIT'
// skipped 'IDC_CROSS'
// skipped 'IDC_UPARROW'
// skipped 'IDC_SIZE'
// skipped 'IDC_ICON'
// skipped 'IDC_SIZENWSE'
// skipped 'IDC_SIZENESW'
// skipped 'IDC_SIZEWE'
// skipped 'IDC_SIZENS'
// skipped 'IDC_SIZEALL'
// skipped 'IDC_NO'
// skipped 'IDC_HAND'
// skipped 'IDC_APPSTARTING'
// skipped 'IDC_HELP'
// skipped 'IDC_PIN'
// skipped 'IDC_PERSON'
pub const IMAGE_ENHMETAFILE = @as(u32, 3);
pub const LR_COLOR = @as(u32, 2);
pub const RES_ICON = @as(u32, 1);
pub const RES_CURSOR = @as(u32, 2);
pub const OBM_CLOSE = @as(u32, 32754);
pub const OBM_UPARROW = @as(u32, 32753);
pub const OBM_DNARROW = @as(u32, 32752);
pub const OBM_RGARROW = @as(u32, 32751);
pub const OBM_LFARROW = @as(u32, 32750);
pub const OBM_REDUCE = @as(u32, 32749);
pub const OBM_ZOOM = @as(u32, 32748);
pub const OBM_RESTORE = @as(u32, 32747);
pub const OBM_REDUCED = @as(u32, 32746);
pub const OBM_ZOOMD = @as(u32, 32745);
pub const OBM_RESTORED = @as(u32, 32744);
pub const OBM_UPARROWD = @as(u32, 32743);
pub const OBM_DNARROWD = @as(u32, 32742);
pub const OBM_RGARROWD = @as(u32, 32741);
pub const OBM_LFARROWD = @as(u32, 32740);
pub const OBM_MNARROW = @as(u32, 32739);
pub const OBM_COMBO = @as(u32, 32738);
pub const OBM_UPARROWI = @as(u32, 32737);
pub const OBM_DNARROWI = @as(u32, 32736);
pub const OBM_RGARROWI = @as(u32, 32735);
pub const OBM_LFARROWI = @as(u32, 32734);
pub const OBM_OLD_CLOSE = @as(u32, 32767);
pub const OBM_SIZE = @as(u32, 32766);
pub const OBM_OLD_UPARROW = @as(u32, 32765);
pub const OBM_OLD_DNARROW = @as(u32, 32764);
pub const OBM_OLD_RGARROW = @as(u32, 32763);
pub const OBM_OLD_LFARROW = @as(u32, 32762);
pub const OBM_BTSIZE = @as(u32, 32761);
pub const OBM_CHECK = @as(u32, 32760);
pub const OBM_CHECKBOXES = @as(u32, 32759);
pub const OBM_BTNCORNERS = @as(u32, 32758);
pub const OBM_OLD_REDUCE = @as(u32, 32757);
pub const OBM_OLD_ZOOM = @as(u32, 32756);
pub const OBM_OLD_RESTORE = @as(u32, 32755);
pub const OCR_SIZE = @as(u32, 32640);
pub const OCR_ICON = @as(u32, 32641);
pub const OCR_ICOCUR = @as(u32, 32647);
pub const OIC_SAMPLE = @as(u32, 32512);
pub const OIC_HAND = @as(u32, 32513);
pub const OIC_QUES = @as(u32, 32514);
pub const OIC_BANG = @as(u32, 32515);
pub const OIC_NOTE = @as(u32, 32516);
pub const OIC_WINLOGO = @as(u32, 32517);
pub const OIC_SHIELD = @as(u32, 32518);
pub const ORD_LANGDRIVER = @as(u32, 1);
pub const IDI_APPLICATION = @import("../zig.zig").typedConst([*:0]const u16, @as(u32, 32512));
// skipped 'IDI_HAND'
// skipped 'IDI_QUESTION'
// skipped 'IDI_EXCLAMATION'
// skipped 'IDI_ASTERISK'
// skipped 'IDI_WINLOGO'
// skipped 'IDI_SHIELD'
pub const ES_LEFT = @as(i32, 0);
pub const ES_CENTER = @as(i32, 1);
pub const ES_RIGHT = @as(i32, 2);
pub const ES_MULTILINE = @as(i32, 4);
pub const ES_UPPERCASE = @as(i32, 8);
pub const ES_LOWERCASE = @as(i32, 16);
pub const ES_PASSWORD = @as(i32, 32);
pub const ES_AUTOVSCROLL = @as(i32, 64);
pub const ES_AUTOHSCROLL = @as(i32, 128);
pub const ES_NOHIDESEL = @as(i32, 256);
pub const ES_OEMCONVERT = @as(i32, 1024);
pub const ES_READONLY = @as(i32, 2048);
pub const ES_WANTRETURN = @as(i32, 4096);
pub const ES_NUMBER = @as(i32, 8192);
pub const EN_SETFOCUS = @as(u32, 256);
pub const EN_KILLFOCUS = @as(u32, 512);
pub const EN_CHANGE = @as(u32, 768);
pub const EN_UPDATE = @as(u32, 1024);
pub const EN_ERRSPACE = @as(u32, 1280);
pub const EN_MAXTEXT = @as(u32, 1281);
pub const EN_HSCROLL = @as(u32, 1537);
pub const EN_VSCROLL = @as(u32, 1538);
pub const EN_ALIGN_LTR_EC = @as(u32, 1792);
pub const EN_ALIGN_RTL_EC = @as(u32, 1793);
pub const EN_BEFORE_PASTE = @as(u32, 2048);
pub const EN_AFTER_PASTE = @as(u32, 2049);
pub const EC_LEFTMARGIN = @as(u32, 1);
pub const EC_RIGHTMARGIN = @as(u32, 2);
pub const EC_USEFONTINFO = @as(u32, 65535);
pub const EMSIS_COMPOSITIONSTRING = @as(u32, 1);
pub const EIMES_GETCOMPSTRATONCE = @as(u32, 1);
pub const EIMES_CANCELCOMPSTRINFOCUS = @as(u32, 2);
pub const EIMES_COMPLETECOMPSTRKILLFOCUS = @as(u32, 4);
pub const BS_PUSHBUTTON = @as(i32, 0);
pub const BS_DEFPUSHBUTTON = @as(i32, 1);
pub const BS_CHECKBOX = @as(i32, 2);
pub const BS_AUTOCHECKBOX = @as(i32, 3);
pub const BS_RADIOBUTTON = @as(i32, 4);
pub const BS_3STATE = @as(i32, 5);
pub const BS_AUTO3STATE = @as(i32, 6);
pub const BS_GROUPBOX = @as(i32, 7);
pub const BS_USERBUTTON = @as(i32, 8);
pub const BS_AUTORADIOBUTTON = @as(i32, 9);
pub const BS_PUSHBOX = @as(i32, 10);
pub const BS_OWNERDRAW = @as(i32, 11);
pub const BS_TYPEMASK = @as(i32, 15);
pub const BS_LEFTTEXT = @as(i32, 32);
pub const BS_TEXT = @as(i32, 0);
pub const BS_ICON = @as(i32, 64);
pub const BS_BITMAP = @as(i32, 128);
pub const BS_LEFT = @as(i32, 256);
pub const BS_RIGHT = @as(i32, 512);
pub const BS_CENTER = @as(i32, 768);
pub const BS_TOP = @as(i32, 1024);
pub const BS_BOTTOM = @as(i32, 2048);
pub const BS_VCENTER = @as(i32, 3072);
pub const BS_PUSHLIKE = @as(i32, 4096);
pub const BS_MULTILINE = @as(i32, 8192);
pub const BS_NOTIFY = @as(i32, 16384);
pub const BS_FLAT = @as(i32, 32768);
pub const BN_CLICKED = @as(u32, 0);
pub const BN_PAINT = @as(u32, 1);
pub const BN_HILITE = @as(u32, 2);
pub const BN_UNHILITE = @as(u32, 3);
pub const BN_DISABLE = @as(u32, 4);
pub const BN_DOUBLECLICKED = @as(u32, 5);
pub const BN_SETFOCUS = @as(u32, 6);
pub const BN_KILLFOCUS = @as(u32, 7);
pub const BM_GETCHECK = @as(u32, 240);
pub const BM_SETCHECK = @as(u32, 241);
pub const BM_GETSTATE = @as(u32, 242);
pub const BM_SETSTATE = @as(u32, 243);
pub const BM_SETSTYLE = @as(u32, 244);
pub const BM_CLICK = @as(u32, 245);
pub const BM_GETIMAGE = @as(u32, 246);
pub const BM_SETIMAGE = @as(u32, 247);
pub const BM_SETDONTCLICK = @as(u32, 248);
pub const BST_PUSHED = @as(u32, 4);
pub const BST_FOCUS = @as(u32, 8);
pub const SS_LEFT = @as(i32, 0);
pub const SS_CENTER = @as(i32, 1);
pub const SS_RIGHT = @as(i32, 2);
pub const SS_ICON = @as(i32, 3);
pub const SS_BLACKRECT = @as(i32, 4);
pub const SS_GRAYRECT = @as(i32, 5);
pub const SS_WHITERECT = @as(i32, 6);
pub const SS_BLACKFRAME = @as(i32, 7);
pub const SS_GRAYFRAME = @as(i32, 8);
pub const SS_WHITEFRAME = @as(i32, 9);
pub const SS_USERITEM = @as(i32, 10);
pub const SS_SIMPLE = @as(i32, 11);
pub const SS_LEFTNOWORDWRAP = @as(i32, 12);
pub const SS_OWNERDRAW = @as(i32, 13);
pub const SS_BITMAP = @as(i32, 14);
pub const SS_ENHMETAFILE = @as(i32, 15);
pub const SS_ETCHEDHORZ = @as(i32, 16);
pub const SS_ETCHEDVERT = @as(i32, 17);
pub const SS_ETCHEDFRAME = @as(i32, 18);
pub const SS_TYPEMASK = @as(i32, 31);
pub const SS_REALSIZECONTROL = @as(i32, 64);
pub const SS_NOPREFIX = @as(i32, 128);
pub const SS_NOTIFY = @as(i32, 256);
pub const SS_CENTERIMAGE = @as(i32, 512);
pub const SS_RIGHTJUST = @as(i32, 1024);
pub const SS_REALSIZEIMAGE = @as(i32, 2048);
pub const SS_SUNKEN = @as(i32, 4096);
pub const SS_EDITCONTROL = @as(i32, 8192);
pub const SS_ENDELLIPSIS = @as(i32, 16384);
pub const SS_PATHELLIPSIS = @as(i32, 32768);
pub const SS_WORDELLIPSIS = @as(i32, 49152);
pub const SS_ELLIPSISMASK = @as(i32, 49152);
pub const STM_SETICON = @as(u32, 368);
pub const STM_GETICON = @as(u32, 369);
pub const STM_SETIMAGE = @as(u32, 370);
pub const STM_GETIMAGE = @as(u32, 371);
pub const STN_CLICKED = @as(u32, 0);
pub const STN_DBLCLK = @as(u32, 1);
pub const STN_ENABLE = @as(u32, 2);
pub const STN_DISABLE = @as(u32, 3);
pub const STM_MSGMAX = @as(u32, 372);
pub const DWL_MSGRESULT = @as(u32, 0);
pub const DWL_DLGPROC = @as(u32, 4);
pub const DWL_USER = @as(u32, 8);
pub const DWLP_MSGRESULT = @as(u32, 0);
pub const DS_ABSALIGN = @as(i32, 1);
pub const DS_SYSMODAL = @as(i32, 2);
pub const DS_LOCALEDIT = @as(i32, 32);
pub const DS_SETFONT = @as(i32, 64);
pub const DS_MODALFRAME = @as(i32, 128);
pub const DS_NOIDLEMSG = @as(i32, 256);
pub const DS_SETFOREGROUND = @as(i32, 512);
pub const DS_3DLOOK = @as(i32, 4);
pub const DS_FIXEDSYS = @as(i32, 8);
pub const DS_NOFAILCREATE = @as(i32, 16);
pub const DS_CONTROL = @as(i32, 1024);
pub const DS_CENTER = @as(i32, 2048);
pub const DS_CENTERMOUSE = @as(i32, 4096);
pub const DS_CONTEXTHELP = @as(i32, 8192);
pub const DS_USEPIXELS = @as(i32, 32768);
pub const DM_GETDEFID = @as(u32, 1024);
pub const DM_SETDEFID = @as(u32, 1025);
pub const DM_REPOSITION = @as(u32, 1026);
pub const DC_HASDEFID = @as(u32, 21323);
pub const DLGC_WANTARROWS = @as(u32, 1);
pub const DLGC_WANTTAB = @as(u32, 2);
pub const DLGC_WANTALLKEYS = @as(u32, 4);
pub const DLGC_WANTMESSAGE = @as(u32, 4);
pub const DLGC_HASSETSEL = @as(u32, 8);
pub const DLGC_DEFPUSHBUTTON = @as(u32, 16);
pub const DLGC_UNDEFPUSHBUTTON = @as(u32, 32);
pub const DLGC_RADIOBUTTON = @as(u32, 64);
pub const DLGC_WANTCHARS = @as(u32, 128);
pub const DLGC_STATIC = @as(u32, 256);
pub const DLGC_BUTTON = @as(u32, 8192);
pub const LB_CTLCODE = @as(i32, 0);
pub const LB_OKAY = @as(u32, 0);
pub const LB_ERR = @as(i32, -1);
pub const LB_ERRSPACE = @as(i32, -2);
pub const LBN_ERRSPACE = @as(i32, -2);
pub const LBN_SELCHANGE = @as(u32, 1);
pub const LBN_DBLCLK = @as(u32, 2);
pub const LBN_SELCANCEL = @as(u32, 3);
pub const LBN_SETFOCUS = @as(u32, 4);
pub const LBN_KILLFOCUS = @as(u32, 5);
pub const LB_ADDSTRING = @as(u32, 384);
pub const LB_INSERTSTRING = @as(u32, 385);
pub const LB_DELETESTRING = @as(u32, 386);
pub const LB_SELITEMRANGEEX = @as(u32, 387);
pub const LB_RESETCONTENT = @as(u32, 388);
pub const LB_SETSEL = @as(u32, 389);
pub const LB_SETCURSEL = @as(u32, 390);
pub const LB_GETSEL = @as(u32, 391);
pub const LB_GETCURSEL = @as(u32, 392);
pub const LB_GETTEXT = @as(u32, 393);
pub const LB_GETTEXTLEN = @as(u32, 394);
pub const LB_GETCOUNT = @as(u32, 395);
pub const LB_SELECTSTRING = @as(u32, 396);
pub const LB_DIR = @as(u32, 397);
pub const LB_GETTOPINDEX = @as(u32, 398);
pub const LB_FINDSTRING = @as(u32, 399);
pub const LB_GETSELCOUNT = @as(u32, 400);
pub const LB_GETSELITEMS = @as(u32, 401);
pub const LB_SETTABSTOPS = @as(u32, 402);
pub const LB_GETHORIZONTALEXTENT = @as(u32, 403);
pub const LB_SETHORIZONTALEXTENT = @as(u32, 404);
pub const LB_SETCOLUMNWIDTH = @as(u32, 405);
pub const LB_ADDFILE = @as(u32, 406);
pub const LB_SETTOPINDEX = @as(u32, 407);
pub const LB_GETITEMRECT = @as(u32, 408);
pub const LB_GETITEMDATA = @as(u32, 409);
pub const LB_SETITEMDATA = @as(u32, 410);
pub const LB_SELITEMRANGE = @as(u32, 411);
pub const LB_SETANCHORINDEX = @as(u32, 412);
pub const LB_GETANCHORINDEX = @as(u32, 413);
pub const LB_SETCARETINDEX = @as(u32, 414);
pub const LB_GETCARETINDEX = @as(u32, 415);
pub const LB_SETITEMHEIGHT = @as(u32, 416);
pub const LB_GETITEMHEIGHT = @as(u32, 417);
pub const LB_FINDSTRINGEXACT = @as(u32, 418);
pub const LB_SETLOCALE = @as(u32, 421);
pub const LB_GETLOCALE = @as(u32, 422);
pub const LB_SETCOUNT = @as(u32, 423);
pub const LB_INITSTORAGE = @as(u32, 424);
pub const LB_ITEMFROMPOINT = @as(u32, 425);
pub const LB_MULTIPLEADDSTRING = @as(u32, 433);
pub const LB_GETLISTBOXINFO = @as(u32, 434);
pub const LB_MSGMAX = @as(u32, 435);
pub const LBS_NOTIFY = @as(i32, 1);
pub const LBS_SORT = @as(i32, 2);
pub const LBS_NOREDRAW = @as(i32, 4);
pub const LBS_MULTIPLESEL = @as(i32, 8);
pub const LBS_OWNERDRAWFIXED = @as(i32, 16);
pub const LBS_OWNERDRAWVARIABLE = @as(i32, 32);
pub const LBS_HASSTRINGS = @as(i32, 64);
pub const LBS_USETABSTOPS = @as(i32, 128);
pub const LBS_NOINTEGRALHEIGHT = @as(i32, 256);
pub const LBS_MULTICOLUMN = @as(i32, 512);
pub const LBS_WANTKEYBOARDINPUT = @as(i32, 1024);
pub const LBS_EXTENDEDSEL = @as(i32, 2048);
pub const LBS_DISABLENOSCROLL = @as(i32, 4096);
pub const LBS_NODATA = @as(i32, 8192);
pub const LBS_NOSEL = @as(i32, 16384);
pub const LBS_COMBOBOX = @as(i32, 32768);
pub const CB_OKAY = @as(u32, 0);
pub const CB_ERR = @as(i32, -1);
pub const CB_ERRSPACE = @as(i32, -2);
pub const CBN_ERRSPACE = @as(i32, -1);
pub const CBN_SELCHANGE = @as(u32, 1);
pub const CBN_DBLCLK = @as(u32, 2);
pub const CBN_SETFOCUS = @as(u32, 3);
pub const CBN_KILLFOCUS = @as(u32, 4);
pub const CBN_EDITCHANGE = @as(u32, 5);
pub const CBN_EDITUPDATE = @as(u32, 6);
pub const CBN_DROPDOWN = @as(u32, 7);
pub const CBN_CLOSEUP = @as(u32, 8);
pub const CBN_SELENDOK = @as(u32, 9);
pub const CBN_SELENDCANCEL = @as(u32, 10);
pub const CBS_SIMPLE = @as(i32, 1);
pub const CBS_DROPDOWN = @as(i32, 2);
pub const CBS_DROPDOWNLIST = @as(i32, 3);
pub const CBS_OWNERDRAWFIXED = @as(i32, 16);
pub const CBS_OWNERDRAWVARIABLE = @as(i32, 32);
pub const CBS_AUTOHSCROLL = @as(i32, 64);
pub const CBS_OEMCONVERT = @as(i32, 128);
pub const CBS_SORT = @as(i32, 256);
pub const CBS_HASSTRINGS = @as(i32, 512);
pub const CBS_NOINTEGRALHEIGHT = @as(i32, 1024);
pub const CBS_DISABLENOSCROLL = @as(i32, 2048);
pub const CBS_UPPERCASE = @as(i32, 8192);
pub const CBS_LOWERCASE = @as(i32, 16384);
pub const CB_GETEDITSEL = @as(u32, 320);
pub const CB_LIMITTEXT = @as(u32, 321);
pub const CB_SETEDITSEL = @as(u32, 322);
pub const CB_ADDSTRING = @as(u32, 323);
pub const CB_DELETESTRING = @as(u32, 324);
pub const CB_DIR = @as(u32, 325);
pub const CB_GETCOUNT = @as(u32, 326);
pub const CB_GETCURSEL = @as(u32, 327);
pub const CB_GETLBTEXT = @as(u32, 328);
pub const CB_GETLBTEXTLEN = @as(u32, 329);
pub const CB_INSERTSTRING = @as(u32, 330);
pub const CB_RESETCONTENT = @as(u32, 331);
pub const CB_FINDSTRING = @as(u32, 332);
pub const CB_SELECTSTRING = @as(u32, 333);
pub const CB_SETCURSEL = @as(u32, 334);
pub const CB_SHOWDROPDOWN = @as(u32, 335);
pub const CB_GETITEMDATA = @as(u32, 336);
pub const CB_SETITEMDATA = @as(u32, 337);
pub const CB_GETDROPPEDCONTROLRECT = @as(u32, 338);
pub const CB_SETITEMHEIGHT = @as(u32, 339);
pub const CB_GETITEMHEIGHT = @as(u32, 340);
pub const CB_SETEXTENDEDUI = @as(u32, 341);
pub const CB_GETEXTENDEDUI = @as(u32, 342);
pub const CB_GETDROPPEDSTATE = @as(u32, 343);
pub const CB_FINDSTRINGEXACT = @as(u32, 344);
pub const CB_SETLOCALE = @as(u32, 345);
pub const CB_GETLOCALE = @as(u32, 346);
pub const CB_GETTOPINDEX = @as(u32, 347);
pub const CB_SETTOPINDEX = @as(u32, 348);
pub const CB_GETHORIZONTALEXTENT = @as(u32, 349);
pub const CB_SETHORIZONTALEXTENT = @as(u32, 350);
pub const CB_GETDROPPEDWIDTH = @as(u32, 351);
pub const CB_SETDROPPEDWIDTH = @as(u32, 352);
pub const CB_INITSTORAGE = @as(u32, 353);
pub const CB_MULTIPLEADDSTRING = @as(u32, 355);
pub const CB_GETCOMBOBOXINFO = @as(u32, 356);
pub const CB_MSGMAX = @as(u32, 357);
pub const SBS_HORZ = @as(i32, 0);
pub const SBS_VERT = @as(i32, 1);
pub const SBS_TOPALIGN = @as(i32, 2);
pub const SBS_LEFTALIGN = @as(i32, 2);
pub const SBS_BOTTOMALIGN = @as(i32, 4);
pub const SBS_RIGHTALIGN = @as(i32, 4);
pub const SBS_SIZEBOXTOPLEFTALIGN = @as(i32, 2);
pub const SBS_SIZEBOXBOTTOMRIGHTALIGN = @as(i32, 4);
pub const SBS_SIZEBOX = @as(i32, 8);
pub const SBS_SIZEGRIP = @as(i32, 16);
pub const SBM_SETPOS = @as(u32, 224);
pub const SBM_GETPOS = @as(u32, 225);
pub const SBM_SETRANGE = @as(u32, 226);
pub const SBM_SETRANGEREDRAW = @as(u32, 230);
pub const SBM_GETRANGE = @as(u32, 227);
pub const SBM_ENABLE_ARROWS = @as(u32, 228);
pub const SBM_SETSCROLLINFO = @as(u32, 233);
pub const SBM_GETSCROLLINFO = @as(u32, 234);
pub const SBM_GETSCROLLBARINFO = @as(u32, 235);
pub const MDIS_ALLCHILDSTYLES = @as(u32, 1);
pub const HELP_CONTEXT = @as(i32, 1);
pub const HELP_QUIT = @as(i32, 2);
pub const HELP_INDEX = @as(i32, 3);
pub const HELP_CONTENTS = @as(i32, 3);
pub const HELP_HELPONHELP = @as(i32, 4);
pub const HELP_SETINDEX = @as(i32, 5);
pub const HELP_SETCONTENTS = @as(i32, 5);
pub const HELP_CONTEXTPOPUP = @as(i32, 8);
pub const HELP_FORCEFILE = @as(i32, 9);
pub const HELP_KEY = @as(i32, 257);
pub const HELP_COMMAND = @as(i32, 258);
pub const HELP_PARTIALKEY = @as(i32, 261);
pub const HELP_MULTIKEY = @as(i32, 513);
pub const HELP_SETWINPOS = @as(i32, 515);
pub const HELP_CONTEXTMENU = @as(u32, 10);
pub const HELP_FINDER = @as(u32, 11);
pub const HELP_WM_HELP = @as(u32, 12);
pub const HELP_SETPOPUP_POS = @as(u32, 13);
pub const HELP_TCARD = @as(u32, 32768);
pub const HELP_TCARD_DATA = @as(u32, 16);
pub const HELP_TCARD_OTHER_CALLER = @as(u32, 17);
pub const IDH_NO_HELP = @as(u32, 28440);
pub const IDH_MISSING_CONTEXT = @as(u32, 28441);
pub const IDH_GENERIC_HELP_BUTTON = @as(u32, 28442);
pub const IDH_OK = @as(u32, 28443);
pub const IDH_CANCEL = @as(u32, 28444);
pub const IDH_HELP = @as(u32, 28445);
pub const MAX_TOUCH_PREDICTION_FILTER_TAPS = @as(u32, 3);
pub const TOUCHPREDICTIONPARAMETERS_DEFAULT_LATENCY = @as(u32, 8);
pub const TOUCHPREDICTIONPARAMETERS_DEFAULT_SAMPLETIME = @as(u32, 8);
pub const TOUCHPREDICTIONPARAMETERS_DEFAULT_USE_HW_TIMESTAMP = @as(u32, 1);
pub const TOUCHPREDICTIONPARAMETERS_DEFAULT_RLS_DELTA = @as(f32, 1.0e-03);
pub const TOUCHPREDICTIONPARAMETERS_DEFAULT_RLS_LAMBDA_MIN = @as(f32, 9.0e-01);
pub const TOUCHPREDICTIONPARAMETERS_DEFAULT_RLS_LAMBDA_MAX = @as(f32, 9.99e-01);
pub const TOUCHPREDICTIONPARAMETERS_DEFAULT_RLS_LAMBDA_LEARNING_RATE = @as(f32, 1.0e-03);
pub const TOUCHPREDICTIONPARAMETERS_DEFAULT_RLS_EXPO_SMOOTH_ALPHA = @as(f32, 9.9e-01);
pub const MAX_LOGICALDPIOVERRIDE = @as(u32, 2);
pub const MIN_LOGICALDPIOVERRIDE = @as(i32, -2);
pub const FE_FONTSMOOTHINGSTANDARD = @as(u32, 1);
pub const FE_FONTSMOOTHINGCLEARTYPE = @as(u32, 2);
pub const FE_FONTSMOOTHINGORIENTATIONBGR = @as(u32, 0);
pub const FE_FONTSMOOTHINGORIENTATIONRGB = @as(u32, 1);
pub const CONTACTVISUALIZATION_OFF = @as(u32, 0);
pub const CONTACTVISUALIZATION_ON = @as(u32, 1);
pub const CONTACTVISUALIZATION_PRESENTATIONMODE = @as(u32, 2);
pub const GESTUREVISUALIZATION_OFF = @as(u32, 0);
pub const GESTUREVISUALIZATION_ON = @as(u32, 31);
pub const GESTUREVISUALIZATION_TAP = @as(u32, 1);
pub const GESTUREVISUALIZATION_DOUBLETAP = @as(u32, 2);
pub const GESTUREVISUALIZATION_PRESSANDTAP = @as(u32, 4);
pub const GESTUREVISUALIZATION_PRESSANDHOLD = @as(u32, 8);
pub const GESTUREVISUALIZATION_RIGHTTAP = @as(u32, 16);
pub const MOUSEWHEEL_ROUTING_FOCUS = @as(u32, 0);
pub const MOUSEWHEEL_ROUTING_HYBRID = @as(u32, 1);
pub const MOUSEWHEEL_ROUTING_MOUSE_POS = @as(u32, 2);
pub const PENVISUALIZATION_ON = @as(u32, 35);
pub const PENVISUALIZATION_OFF = @as(u32, 0);
pub const PENVISUALIZATION_TAP = @as(u32, 1);
pub const PENVISUALIZATION_DOUBLETAP = @as(u32, 2);
pub const PENVISUALIZATION_CURSOR = @as(u32, 32);
pub const PENARBITRATIONTYPE_NONE = @as(u32, 0);
pub const PENARBITRATIONTYPE_WIN8 = @as(u32, 1);
pub const PENARBITRATIONTYPE_FIS = @as(u32, 2);
pub const PENARBITRATIONTYPE_SPT = @as(u32, 3);
pub const PENARBITRATIONTYPE_MAX = @as(u32, 4);
pub const METRICS_USEDEFAULT = @as(i32, -1);
pub const ARW_STARTMASK = @as(i32, 3);
pub const ARW_STARTRIGHT = @as(i32, 1);
pub const ARW_STARTTOP = @as(i32, 2);
pub const ARW_LEFT = @as(i32, 0);
pub const ARW_RIGHT = @as(i32, 0);
pub const ARW_UP = @as(i32, 4);
pub const ARW_DOWN = @as(i32, 4);
pub const ARW_HIDE = @as(i32, 8);
pub const HCF_LOGONDESKTOP = @as(u32, 256);
pub const HCF_DEFAULTDESKTOP = @as(u32, 512);
pub const EDS_RAWMODE = @as(u32, 2);
pub const EDS_ROTATEDMODE = @as(u32, 4);
pub const EDD_GET_DEVICE_INTERFACE_NAME = @as(u32, 1);
pub const FKF_FILTERKEYSON = @as(u32, 1);
pub const FKF_AVAILABLE = @as(u32, 2);
pub const FKF_HOTKEYACTIVE = @as(u32, 4);
pub const FKF_CONFIRMHOTKEY = @as(u32, 8);
pub const FKF_HOTKEYSOUND = @as(u32, 16);
pub const FKF_INDICATOR = @as(u32, 32);
pub const FKF_CLICKON = @as(u32, 64);
pub const MKF_MOUSEKEYSON = @as(u32, 1);
pub const MKF_AVAILABLE = @as(u32, 2);
pub const MKF_HOTKEYACTIVE = @as(u32, 4);
pub const MKF_CONFIRMHOTKEY = @as(u32, 8);
pub const MKF_HOTKEYSOUND = @as(u32, 16);
pub const MKF_INDICATOR = @as(u32, 32);
pub const MKF_MODIFIERS = @as(u32, 64);
pub const MKF_REPLACENUMBERS = @as(u32, 128);
pub const MKF_LEFTBUTTONSEL = @as(u32, 268435456);
pub const MKF_RIGHTBUTTONSEL = @as(u32, 536870912);
pub const MKF_LEFTBUTTONDOWN = @as(u32, 16777216);
pub const MKF_RIGHTBUTTONDOWN = @as(u32, 33554432);
pub const MKF_MOUSEMODE = @as(u32, 2147483648);
pub const TKF_TOGGLEKEYSON = @as(u32, 1);
pub const TKF_AVAILABLE = @as(u32, 2);
pub const TKF_HOTKEYACTIVE = @as(u32, 4);
pub const TKF_CONFIRMHOTKEY = @as(u32, 8);
pub const TKF_HOTKEYSOUND = @as(u32, 16);
pub const TKF_INDICATOR = @as(u32, 32);
pub const MONITORINFOF_PRIMARY = @as(u32, 1);
pub const WINEVENT_OUTOFCONTEXT = @as(u32, 0);
pub const WINEVENT_SKIPOWNTHREAD = @as(u32, 1);
pub const WINEVENT_SKIPOWNPROCESS = @as(u32, 2);
pub const WINEVENT_INCONTEXT = @as(u32, 4);
pub const CHILDID_SELF = @as(u32, 0);
pub const INDEXID_OBJECT = @as(u32, 0);
pub const INDEXID_CONTAINER = @as(u32, 0);
pub const EVENT_MIN = @as(u32, 1);
pub const EVENT_MAX = @as(u32, 2147483647);
pub const EVENT_SYSTEM_SOUND = @as(u32, 1);
pub const EVENT_SYSTEM_ALERT = @as(u32, 2);
pub const EVENT_SYSTEM_FOREGROUND = @as(u32, 3);
pub const EVENT_SYSTEM_MENUSTART = @as(u32, 4);
pub const EVENT_SYSTEM_MENUEND = @as(u32, 5);
pub const EVENT_SYSTEM_MENUPOPUPSTART = @as(u32, 6);
pub const EVENT_SYSTEM_MENUPOPUPEND = @as(u32, 7);
pub const EVENT_SYSTEM_CAPTURESTART = @as(u32, 8);
pub const EVENT_SYSTEM_CAPTUREEND = @as(u32, 9);
pub const EVENT_SYSTEM_MOVESIZESTART = @as(u32, 10);
pub const EVENT_SYSTEM_MOVESIZEEND = @as(u32, 11);
pub const EVENT_SYSTEM_CONTEXTHELPSTART = @as(u32, 12);
pub const EVENT_SYSTEM_CONTEXTHELPEND = @as(u32, 13);
pub const EVENT_SYSTEM_DRAGDROPSTART = @as(u32, 14);
pub const EVENT_SYSTEM_DRAGDROPEND = @as(u32, 15);
pub const EVENT_SYSTEM_DIALOGSTART = @as(u32, 16);
pub const EVENT_SYSTEM_DIALOGEND = @as(u32, 17);
pub const EVENT_SYSTEM_SCROLLINGSTART = @as(u32, 18);
pub const EVENT_SYSTEM_SCROLLINGEND = @as(u32, 19);
pub const EVENT_SYSTEM_SWITCHSTART = @as(u32, 20);
pub const EVENT_SYSTEM_SWITCHEND = @as(u32, 21);
pub const EVENT_SYSTEM_MINIMIZESTART = @as(u32, 22);
pub const EVENT_SYSTEM_MINIMIZEEND = @as(u32, 23);
pub const EVENT_SYSTEM_DESKTOPSWITCH = @as(u32, 32);
pub const EVENT_SYSTEM_SWITCHER_APPGRABBED = @as(u32, 36);
pub const EVENT_SYSTEM_SWITCHER_APPOVERTARGET = @as(u32, 37);
pub const EVENT_SYSTEM_SWITCHER_APPDROPPED = @as(u32, 38);
pub const EVENT_SYSTEM_SWITCHER_CANCELLED = @as(u32, 39);
pub const EVENT_SYSTEM_IME_KEY_NOTIFICATION = @as(u32, 41);
pub const EVENT_SYSTEM_END = @as(u32, 255);
pub const EVENT_OEM_DEFINED_START = @as(u32, 257);
pub const EVENT_OEM_DEFINED_END = @as(u32, 511);
pub const EVENT_UIA_EVENTID_START = @as(u32, 19968);
pub const EVENT_UIA_EVENTID_END = @as(u32, 20223);
pub const EVENT_UIA_PROPID_START = @as(u32, 29952);
pub const EVENT_UIA_PROPID_END = @as(u32, 30207);
pub const EVENT_CONSOLE_CARET = @as(u32, 16385);
pub const EVENT_CONSOLE_UPDATE_REGION = @as(u32, 16386);
pub const EVENT_CONSOLE_UPDATE_SIMPLE = @as(u32, 16387);
pub const EVENT_CONSOLE_UPDATE_SCROLL = @as(u32, 16388);
pub const EVENT_CONSOLE_LAYOUT = @as(u32, 16389);
pub const EVENT_CONSOLE_START_APPLICATION = @as(u32, 16390);
pub const EVENT_CONSOLE_END_APPLICATION = @as(u32, 16391);
pub const CONSOLE_APPLICATION_16BIT = @as(u32, 0);
pub const CONSOLE_CARET_SELECTION = @as(u32, 1);
pub const CONSOLE_CARET_VISIBLE = @as(u32, 2);
pub const EVENT_CONSOLE_END = @as(u32, 16639);
pub const EVENT_OBJECT_CREATE = @as(u32, 32768);
pub const EVENT_OBJECT_DESTROY = @as(u32, 32769);
pub const EVENT_OBJECT_SHOW = @as(u32, 32770);
pub const EVENT_OBJECT_HIDE = @as(u32, 32771);
pub const EVENT_OBJECT_REORDER = @as(u32, 32772);
pub const EVENT_OBJECT_FOCUS = @as(u32, 32773);
pub const EVENT_OBJECT_SELECTION = @as(u32, 32774);
pub const EVENT_OBJECT_SELECTIONADD = @as(u32, 32775);
pub const EVENT_OBJECT_SELECTIONREMOVE = @as(u32, 32776);
pub const EVENT_OBJECT_SELECTIONWITHIN = @as(u32, 32777);
pub const EVENT_OBJECT_STATECHANGE = @as(u32, 32778);
pub const EVENT_OBJECT_LOCATIONCHANGE = @as(u32, 32779);
pub const EVENT_OBJECT_NAMECHANGE = @as(u32, 32780);
pub const EVENT_OBJECT_DESCRIPTIONCHANGE = @as(u32, 32781);
pub const EVENT_OBJECT_VALUECHANGE = @as(u32, 32782);
pub const EVENT_OBJECT_PARENTCHANGE = @as(u32, 32783);
pub const EVENT_OBJECT_HELPCHANGE = @as(u32, 32784);
pub const EVENT_OBJECT_DEFACTIONCHANGE = @as(u32, 32785);
pub const EVENT_OBJECT_ACCELERATORCHANGE = @as(u32, 32786);
pub const EVENT_OBJECT_INVOKED = @as(u32, 32787);
pub const EVENT_OBJECT_TEXTSELECTIONCHANGED = @as(u32, 32788);
pub const EVENT_OBJECT_CONTENTSCROLLED = @as(u32, 32789);
pub const EVENT_SYSTEM_ARRANGMENTPREVIEW = @as(u32, 32790);
pub const EVENT_OBJECT_CLOAKED = @as(u32, 32791);
pub const EVENT_OBJECT_UNCLOAKED = @as(u32, 32792);
pub const EVENT_OBJECT_LIVEREGIONCHANGED = @as(u32, 32793);
pub const EVENT_OBJECT_HOSTEDOBJECTSINVALIDATED = @as(u32, 32800);
pub const EVENT_OBJECT_DRAGSTART = @as(u32, 32801);
pub const EVENT_OBJECT_DRAGCANCEL = @as(u32, 32802);
pub const EVENT_OBJECT_DRAGCOMPLETE = @as(u32, 32803);
pub const EVENT_OBJECT_DRAGENTER = @as(u32, 32804);
pub const EVENT_OBJECT_DRAGLEAVE = @as(u32, 32805);
pub const EVENT_OBJECT_DRAGDROPPED = @as(u32, 32806);
pub const EVENT_OBJECT_IME_SHOW = @as(u32, 32807);
pub const EVENT_OBJECT_IME_HIDE = @as(u32, 32808);
pub const EVENT_OBJECT_IME_CHANGE = @as(u32, 32809);
pub const EVENT_OBJECT_TEXTEDIT_CONVERSIONTARGETCHANGED = @as(u32, 32816);
pub const EVENT_OBJECT_END = @as(u32, 33023);
pub const EVENT_AIA_START = @as(u32, 40960);
pub const EVENT_AIA_END = @as(u32, 45055);
pub const SOUND_SYSTEM_STARTUP = @as(u32, 1);
pub const SOUND_SYSTEM_SHUTDOWN = @as(u32, 2);
pub const SOUND_SYSTEM_BEEP = @as(u32, 3);
pub const SOUND_SYSTEM_ERROR = @as(u32, 4);
pub const SOUND_SYSTEM_QUESTION = @as(u32, 5);
pub const SOUND_SYSTEM_WARNING = @as(u32, 6);
pub const SOUND_SYSTEM_INFORMATION = @as(u32, 7);
pub const SOUND_SYSTEM_MAXIMIZE = @as(u32, 8);
pub const SOUND_SYSTEM_MINIMIZE = @as(u32, 9);
pub const SOUND_SYSTEM_RESTOREUP = @as(u32, 10);
pub const SOUND_SYSTEM_RESTOREDOWN = @as(u32, 11);
pub const SOUND_SYSTEM_APPSTART = @as(u32, 12);
pub const SOUND_SYSTEM_FAULT = @as(u32, 13);
pub const SOUND_SYSTEM_APPEND = @as(u32, 14);
pub const SOUND_SYSTEM_MENUCOMMAND = @as(u32, 15);
pub const SOUND_SYSTEM_MENUPOPUP = @as(u32, 16);
pub const CSOUND_SYSTEM = @as(u32, 16);
pub const CALERT_SYSTEM = @as(u32, 6);
pub const GUI_16BITTASK = @as(u32, 0);
pub const USER_DEFAULT_SCREEN_DPI = @as(u32, 96);
pub const STATE_SYSTEM_SELECTED = @as(u32, 2);
pub const STATE_SYSTEM_FOCUSED = @as(u32, 4);
pub const STATE_SYSTEM_CHECKED = @as(u32, 16);
pub const STATE_SYSTEM_MIXED = @as(u32, 32);
pub const STATE_SYSTEM_READONLY = @as(u32, 64);
pub const STATE_SYSTEM_HOTTRACKED = @as(u32, 128);
pub const STATE_SYSTEM_DEFAULT = @as(u32, 256);
pub const STATE_SYSTEM_EXPANDED = @as(u32, 512);
pub const STATE_SYSTEM_COLLAPSED = @as(u32, 1024);
pub const STATE_SYSTEM_BUSY = @as(u32, 2048);
pub const STATE_SYSTEM_FLOATING = @as(u32, 4096);
pub const STATE_SYSTEM_MARQUEED = @as(u32, 8192);
pub const STATE_SYSTEM_ANIMATED = @as(u32, 16384);
pub const STATE_SYSTEM_SIZEABLE = @as(u32, 131072);
pub const STATE_SYSTEM_MOVEABLE = @as(u32, 262144);
pub const STATE_SYSTEM_SELFVOICING = @as(u32, 524288);
pub const STATE_SYSTEM_SELECTABLE = @as(u32, 2097152);
pub const STATE_SYSTEM_LINKED = @as(u32, 4194304);
pub const STATE_SYSTEM_TRAVERSED = @as(u32, 8388608);
pub const STATE_SYSTEM_MULTISELECTABLE = @as(u32, 16777216);
pub const STATE_SYSTEM_EXTSELECTABLE = @as(u32, 33554432);
pub const STATE_SYSTEM_ALERT_LOW = @as(u32, 67108864);
pub const STATE_SYSTEM_ALERT_MEDIUM = @as(u32, 134217728);
pub const STATE_SYSTEM_ALERT_HIGH = @as(u32, 268435456);
pub const STATE_SYSTEM_PROTECTED = @as(u32, 536870912);
pub const STATE_SYSTEM_VALID = @as(u32, 1073741823);
pub const CCHILDREN_TITLEBAR = @as(u32, 5);
pub const CCHILDREN_SCROLLBAR = @as(u32, 5);
pub const RIM_INPUT = @as(u32, 0);
pub const RIM_INPUTSINK = @as(u32, 1);
pub const RIM_TYPEMAX = @as(u32, 2);
pub const RI_MOUSE_LEFT_BUTTON_DOWN = @as(u32, 1);
pub const RI_MOUSE_LEFT_BUTTON_UP = @as(u32, 2);
pub const RI_MOUSE_RIGHT_BUTTON_DOWN = @as(u32, 4);
pub const RI_MOUSE_RIGHT_BUTTON_UP = @as(u32, 8);
pub const RI_MOUSE_MIDDLE_BUTTON_DOWN = @as(u32, 16);
pub const RI_MOUSE_MIDDLE_BUTTON_UP = @as(u32, 32);
pub const RI_MOUSE_BUTTON_4_DOWN = @as(u32, 64);
pub const RI_MOUSE_BUTTON_4_UP = @as(u32, 128);
pub const RI_MOUSE_BUTTON_5_DOWN = @as(u32, 256);
pub const RI_MOUSE_BUTTON_5_UP = @as(u32, 512);
pub const RI_MOUSE_WHEEL = @as(u32, 1024);
pub const RI_MOUSE_HWHEEL = @as(u32, 2048);
pub const RI_KEY_MAKE = @as(u32, 0);
pub const RI_KEY_BREAK = @as(u32, 1);
pub const RI_KEY_E0 = @as(u32, 2);
pub const RI_KEY_E1 = @as(u32, 4);
pub const RI_KEY_TERMSRV_SET_LED = @as(u32, 8);
pub const RI_KEY_TERMSRV_SHADOW = @as(u32, 16);
pub const RIDEV_EXMODEMASK = @as(u32, 240);
pub const GIDC_ARRIVAL = @as(u32, 1);
pub const GIDC_REMOVAL = @as(u32, 2);
pub const POINTER_DEVICE_PRODUCT_STRING_MAX = @as(u32, 520);
pub const PDC_ARRIVAL = @as(u32, 1);
pub const PDC_REMOVAL = @as(u32, 2);
pub const PDC_ORIENTATION_0 = @as(u32, 4);
pub const PDC_ORIENTATION_90 = @as(u32, 8);
pub const PDC_ORIENTATION_180 = @as(u32, 16);
pub const PDC_ORIENTATION_270 = @as(u32, 32);
pub const PDC_MODE_DEFAULT = @as(u32, 64);
pub const PDC_MODE_CENTERED = @as(u32, 128);
pub const PDC_MAPPING_CHANGE = @as(u32, 256);
pub const PDC_RESOLUTION = @as(u32, 512);
pub const PDC_ORIGIN = @as(u32, 1024);
pub const PDC_MODE_ASPECTRATIOPRESERVED = @as(u32, 2048);
pub const GF_BEGIN = @as(u32, 1);
pub const GF_INERTIA = @as(u32, 2);
pub const GF_END = @as(u32, 4);
pub const GESTURECONFIGMAXCOUNT = @as(u32, 256);
pub const GCF_INCLUDE_ANCESTORS = @as(u32, 1);
pub const NID_INTEGRATED_TOUCH = @as(u32, 1);
pub const NID_EXTERNAL_TOUCH = @as(u32, 2);
pub const NID_INTEGRATED_PEN = @as(u32, 4);
pub const NID_EXTERNAL_PEN = @as(u32, 8);
pub const NID_MULTI_INPUT = @as(u32, 64);
pub const NID_READY = @as(u32, 128);
pub const MAX_STR_BLOCKREASON = @as(u32, 256);
pub const STRSAFE_USE_SECURE_CRT = @as(u32, 0);
pub const STRSAFE_MAX_CCH = @as(u32, 2147483647);
pub const STRSAFE_IGNORE_NULLS = @as(u32, 256);
pub const STRSAFE_FILL_BEHIND_NULL = @as(u32, 512);
pub const STRSAFE_FILL_ON_FAILURE = @as(u32, 1024);
pub const STRSAFE_NULL_ON_FAILURE = @as(u32, 2048);
pub const STRSAFE_NO_TRUNCATION = @as(u32, 4096);
pub const STRSAFE_E_INSUFFICIENT_BUFFER = @import("../zig.zig").typedConst(HRESULT, @as(i32, -2147024774));
pub const STRSAFE_E_INVALID_PARAMETER = @import("../zig.zig").typedConst(HRESULT, @as(i32, -2147024809));
pub const STRSAFE_E_END_OF_FILE = @import("../zig.zig").typedConst(HRESULT, @as(i32, -2147024858));
pub const __WARNING_CYCLOMATIC_COMPLEXITY = @as(u32, 28734);
pub const __WARNING_USING_UNINIT_VAR = @as(u32, 6001);
pub const __WARNING_RETURN_UNINIT_VAR = @as(u32, 6101);
pub const __WARNING_DEREF_NULL_PTR = @as(u32, 6011);
pub const __WARNING_MISSING_ZERO_TERMINATION2 = @as(u32, 6054);
pub const __WARNING_INVALID_PARAM_VALUE_1 = @as(u32, 6387);
pub const __WARNING_INCORRECT_ANNOTATION = @as(u32, 26007);
pub const __WARNING_POTENTIAL_BUFFER_OVERFLOW_HIGH_PRIORITY = @as(u32, 26015);
pub const __WARNING_PRECONDITION_NULLTERMINATION_VIOLATION = @as(u32, 26035);
pub const __WARNING_POSTCONDITION_NULLTERMINATION_VIOLATION = @as(u32, 26036);
pub const __WARNING_HIGH_PRIORITY_OVERFLOW_POSTCONDITION = @as(u32, 26045);
pub const __WARNING_RANGE_POSTCONDITION_VIOLATION = @as(u32, 26061);
pub const __WARNING_POTENTIAL_RANGE_POSTCONDITION_VIOLATION = @as(u32, 26071);
pub const __WARNING_INVALID_PARAM_VALUE_3 = @as(u32, 28183);
pub const __WARNING_RETURNING_BAD_RESULT = @as(u32, 28196);
pub const __WARNING_BANNED_API_USAGE = @as(u32, 28719);
pub const __WARNING_POST_EXPECTED = @as(u32, 28210);
pub const HBMMENU_CALLBACK = @import("../zig.zig").typedConst(HBITMAP, @as(i32, -1));
pub const HBMMENU_SYSTEM = @import("../zig.zig").typedConst(HBITMAP, @as(i32, 1));
pub const HBMMENU_MBAR_RESTORE = @import("../zig.zig").typedConst(HBITMAP, @as(i32, 2));
pub const HBMMENU_MBAR_MINIMIZE = @import("../zig.zig").typedConst(HBITMAP, @as(i32, 3));
pub const HBMMENU_MBAR_CLOSE = @import("../zig.zig").typedConst(HBITMAP, @as(i32, 5));
pub const HBMMENU_MBAR_CLOSE_D = @import("../zig.zig").typedConst(HBITMAP, @as(i32, 6));
pub const HBMMENU_MBAR_MINIMIZE_D = @import("../zig.zig").typedConst(HBITMAP, @as(i32, 7));
pub const HBMMENU_POPUP_CLOSE = @import("../zig.zig").typedConst(HBITMAP, @as(i32, 8));
pub const HBMMENU_POPUP_RESTORE = @import("../zig.zig").typedConst(HBITMAP, @as(i32, 9));
pub const HBMMENU_POPUP_MAXIMIZE = @import("../zig.zig").typedConst(HBITMAP, @as(i32, 10));
pub const HBMMENU_POPUP_MINIMIZE = @import("../zig.zig").typedConst(HBITMAP, @as(i32, 11));
pub const CW_USEDEFAULT = @as(i32, -2147483648);
pub const LBS_STANDARD = @as(i32, 10485763);
//--------------------------------------------------------------------------------
// Section: Types (214)
//--------------------------------------------------------------------------------
pub const WNDCLASS_STYLES = enum(u32) {
VREDRAW = 1,
HREDRAW = 2,
DBLCLKS = 8,
OWNDC = 32,
CLASSDC = 64,
PARENTDC = 128,
NOCLOSE = 512,
SAVEBITS = 2048,
BYTEALIGNCLIENT = 4096,
BYTEALIGNWINDOW = 8192,
GLOBALCLASS = 16384,
IME = 65536,
DROPSHADOW = 131072,
_,
pub fn initFlags(o: struct {
VREDRAW: u1 = 0,
HREDRAW: u1 = 0,
DBLCLKS: u1 = 0,
OWNDC: u1 = 0,
CLASSDC: u1 = 0,
PARENTDC: u1 = 0,
NOCLOSE: u1 = 0,
SAVEBITS: u1 = 0,
BYTEALIGNCLIENT: u1 = 0,
BYTEALIGNWINDOW: u1 = 0,
GLOBALCLASS: u1 = 0,
IME: u1 = 0,
DROPSHADOW: u1 = 0,
}) WNDCLASS_STYLES {
return @intToEnum(WNDCLASS_STYLES,
(if (o.VREDRAW == 1) @enumToInt(WNDCLASS_STYLES.VREDRAW) else 0)
| (if (o.HREDRAW == 1) @enumToInt(WNDCLASS_STYLES.HREDRAW) else 0)
| (if (o.DBLCLKS == 1) @enumToInt(WNDCLASS_STYLES.DBLCLKS) else 0)
| (if (o.OWNDC == 1) @enumToInt(WNDCLASS_STYLES.OWNDC) else 0)
| (if (o.CLASSDC == 1) @enumToInt(WNDCLASS_STYLES.CLASSDC) else 0)
| (if (o.PARENTDC == 1) @enumToInt(WNDCLASS_STYLES.PARENTDC) else 0)
| (if (o.NOCLOSE == 1) @enumToInt(WNDCLASS_STYLES.NOCLOSE) else 0)
| (if (o.SAVEBITS == 1) @enumToInt(WNDCLASS_STYLES.SAVEBITS) else 0)
| (if (o.BYTEALIGNCLIENT == 1) @enumToInt(WNDCLASS_STYLES.BYTEALIGNCLIENT) else 0)
| (if (o.BYTEALIGNWINDOW == 1) @enumToInt(WNDCLASS_STYLES.BYTEALIGNWINDOW) else 0)
| (if (o.GLOBALCLASS == 1) @enumToInt(WNDCLASS_STYLES.GLOBALCLASS) else 0)
| (if (o.IME == 1) @enumToInt(WNDCLASS_STYLES.IME) else 0)
| (if (o.DROPSHADOW == 1) @enumToInt(WNDCLASS_STYLES.DROPSHADOW) else 0)
);
}
};
pub const CS_VREDRAW = WNDCLASS_STYLES.VREDRAW;
pub const CS_HREDRAW = WNDCLASS_STYLES.HREDRAW;
pub const CS_DBLCLKS = WNDCLASS_STYLES.DBLCLKS;
pub const CS_OWNDC = WNDCLASS_STYLES.OWNDC;
pub const CS_CLASSDC = WNDCLASS_STYLES.CLASSDC;
pub const CS_PARENTDC = WNDCLASS_STYLES.PARENTDC;
pub const CS_NOCLOSE = WNDCLASS_STYLES.NOCLOSE;
pub const CS_SAVEBITS = WNDCLASS_STYLES.SAVEBITS;
pub const CS_BYTEALIGNCLIENT = WNDCLASS_STYLES.BYTEALIGNCLIENT;
pub const CS_BYTEALIGNWINDOW = WNDCLASS_STYLES.BYTEALIGNWINDOW;
pub const CS_GLOBALCLASS = WNDCLASS_STYLES.GLOBALCLASS;
pub const CS_IME = WNDCLASS_STYLES.IME;
pub const CS_DROPSHADOW = WNDCLASS_STYLES.DROPSHADOW;
pub const CWP_FLAGS = enum(u32) {
ALL = 0,
SKIPINVISIBLE = 1,
SKIPDISABLED = 2,
SKIPTRANSPARENT = 4,
_,
pub fn initFlags(o: struct {
ALL: u1 = 0,
SKIPINVISIBLE: u1 = 0,
SKIPDISABLED: u1 = 0,
SKIPTRANSPARENT: u1 = 0,
}) CWP_FLAGS {
return @intToEnum(CWP_FLAGS,
(if (o.ALL == 1) @enumToInt(CWP_FLAGS.ALL) else 0)
| (if (o.SKIPINVISIBLE == 1) @enumToInt(CWP_FLAGS.SKIPINVISIBLE) else 0)
| (if (o.SKIPDISABLED == 1) @enumToInt(CWP_FLAGS.SKIPDISABLED) else 0)
| (if (o.SKIPTRANSPARENT == 1) @enumToInt(CWP_FLAGS.SKIPTRANSPARENT) else 0)
);
}
};
pub const CWP_ALL = CWP_FLAGS.ALL;
pub const CWP_SKIPINVISIBLE = CWP_FLAGS.SKIPINVISIBLE;
pub const CWP_SKIPDISABLED = CWP_FLAGS.SKIPDISABLED;
pub const CWP_SKIPTRANSPARENT = CWP_FLAGS.SKIPTRANSPARENT;
pub const MESSAGEBOX_STYLE = enum(u32) {
ABORTRETRYIGNORE = 2,
CANCELTRYCONTINUE = 6,
HELP = 16384,
OK = 0,
OKCANCEL = 1,
RETRYCANCEL = 5,
YESNO = 4,
YESNOCANCEL = 3,
ICONHAND = 16,
ICONQUESTION = 32,
ICONEXCLAMATION = 48,
ICONASTERISK = 64,
USERICON = 128,
// ICONWARNING = 48, this enum value conflicts with ICONEXCLAMATION
// ICONERROR = 16, this enum value conflicts with ICONHAND
// ICONINFORMATION = 64, this enum value conflicts with ICONASTERISK
// ICONSTOP = 16, this enum value conflicts with ICONHAND
// DEFBUTTON1 = 0, this enum value conflicts with OK
DEFBUTTON2 = 256,
DEFBUTTON3 = 512,
DEFBUTTON4 = 768,
// APPLMODAL = 0, this enum value conflicts with OK
SYSTEMMODAL = 4096,
TASKMODAL = 8192,
NOFOCUS = 32768,
SETFOREGROUND = 65536,
DEFAULT_DESKTOP_ONLY = 131072,
TOPMOST = 262144,
RIGHT = 524288,
RTLREADING = 1048576,
SERVICE_NOTIFICATION = 2097152,
// SERVICE_NOTIFICATION_NT3X = 262144, this enum value conflicts with TOPMOST
TYPEMASK = 15,
ICONMASK = 240,
DEFMASK = 3840,
MODEMASK = 12288,
MISCMASK = 49152,
_,
pub fn initFlags(o: struct {
ABORTRETRYIGNORE: u1 = 0,
CANCELTRYCONTINUE: u1 = 0,
HELP: u1 = 0,
OK: u1 = 0,
OKCANCEL: u1 = 0,
RETRYCANCEL: u1 = 0,
YESNO: u1 = 0,
YESNOCANCEL: u1 = 0,
ICONHAND: u1 = 0,
ICONQUESTION: u1 = 0,
ICONEXCLAMATION: u1 = 0,
ICONASTERISK: u1 = 0,
USERICON: u1 = 0,
DEFBUTTON2: u1 = 0,
DEFBUTTON3: u1 = 0,
DEFBUTTON4: u1 = 0,
SYSTEMMODAL: u1 = 0,
TASKMODAL: u1 = 0,
NOFOCUS: u1 = 0,
SETFOREGROUND: u1 = 0,
DEFAULT_DESKTOP_ONLY: u1 = 0,
TOPMOST: u1 = 0,
RIGHT: u1 = 0,
RTLREADING: u1 = 0,
SERVICE_NOTIFICATION: u1 = 0,
TYPEMASK: u1 = 0,
ICONMASK: u1 = 0,
DEFMASK: u1 = 0,
MODEMASK: u1 = 0,
MISCMASK: u1 = 0,
}) MESSAGEBOX_STYLE {
return @intToEnum(MESSAGEBOX_STYLE,
(if (o.ABORTRETRYIGNORE == 1) @enumToInt(MESSAGEBOX_STYLE.ABORTRETRYIGNORE) else 0)
| (if (o.CANCELTRYCONTINUE == 1) @enumToInt(MESSAGEBOX_STYLE.CANCELTRYCONTINUE) else 0)
| (if (o.HELP == 1) @enumToInt(MESSAGEBOX_STYLE.HELP) else 0)
| (if (o.OK == 1) @enumToInt(MESSAGEBOX_STYLE.OK) else 0)
| (if (o.OKCANCEL == 1) @enumToInt(MESSAGEBOX_STYLE.OKCANCEL) else 0)
| (if (o.RETRYCANCEL == 1) @enumToInt(MESSAGEBOX_STYLE.RETRYCANCEL) else 0)
| (if (o.YESNO == 1) @enumToInt(MESSAGEBOX_STYLE.YESNO) else 0)
| (if (o.YESNOCANCEL == 1) @enumToInt(MESSAGEBOX_STYLE.YESNOCANCEL) else 0)
| (if (o.ICONHAND == 1) @enumToInt(MESSAGEBOX_STYLE.ICONHAND) else 0)
| (if (o.ICONQUESTION == 1) @enumToInt(MESSAGEBOX_STYLE.ICONQUESTION) else 0)
| (if (o.ICONEXCLAMATION == 1) @enumToInt(MESSAGEBOX_STYLE.ICONEXCLAMATION) else 0)
| (if (o.ICONASTERISK == 1) @enumToInt(MESSAGEBOX_STYLE.ICONASTERISK) else 0)
| (if (o.USERICON == 1) @enumToInt(MESSAGEBOX_STYLE.USERICON) else 0)
| (if (o.DEFBUTTON2 == 1) @enumToInt(MESSAGEBOX_STYLE.DEFBUTTON2) else 0)
| (if (o.DEFBUTTON3 == 1) @enumToInt(MESSAGEBOX_STYLE.DEFBUTTON3) else 0)
| (if (o.DEFBUTTON4 == 1) @enumToInt(MESSAGEBOX_STYLE.DEFBUTTON4) else 0)
| (if (o.SYSTEMMODAL == 1) @enumToInt(MESSAGEBOX_STYLE.SYSTEMMODAL) else 0)
| (if (o.TASKMODAL == 1) @enumToInt(MESSAGEBOX_STYLE.TASKMODAL) else 0)
| (if (o.NOFOCUS == 1) @enumToInt(MESSAGEBOX_STYLE.NOFOCUS) else 0)
| (if (o.SETFOREGROUND == 1) @enumToInt(MESSAGEBOX_STYLE.SETFOREGROUND) else 0)
| (if (o.DEFAULT_DESKTOP_ONLY == 1) @enumToInt(MESSAGEBOX_STYLE.DEFAULT_DESKTOP_ONLY) else 0)
| (if (o.TOPMOST == 1) @enumToInt(MESSAGEBOX_STYLE.TOPMOST) else 0)
| (if (o.RIGHT == 1) @enumToInt(MESSAGEBOX_STYLE.RIGHT) else 0)
| (if (o.RTLREADING == 1) @enumToInt(MESSAGEBOX_STYLE.RTLREADING) else 0)
| (if (o.SERVICE_NOTIFICATION == 1) @enumToInt(MESSAGEBOX_STYLE.SERVICE_NOTIFICATION) else 0)
| (if (o.TYPEMASK == 1) @enumToInt(MESSAGEBOX_STYLE.TYPEMASK) else 0)
| (if (o.ICONMASK == 1) @enumToInt(MESSAGEBOX_STYLE.ICONMASK) else 0)
| (if (o.DEFMASK == 1) @enumToInt(MESSAGEBOX_STYLE.DEFMASK) else 0)
| (if (o.MODEMASK == 1) @enumToInt(MESSAGEBOX_STYLE.MODEMASK) else 0)
| (if (o.MISCMASK == 1) @enumToInt(MESSAGEBOX_STYLE.MISCMASK) else 0)
);
}
};
pub const MB_ABORTRETRYIGNORE = MESSAGEBOX_STYLE.ABORTRETRYIGNORE;
pub const MB_CANCELTRYCONTINUE = MESSAGEBOX_STYLE.CANCELTRYCONTINUE;
pub const MB_HELP = MESSAGEBOX_STYLE.HELP;
pub const MB_OK = MESSAGEBOX_STYLE.OK;
pub const MB_OKCANCEL = MESSAGEBOX_STYLE.OKCANCEL;
pub const MB_RETRYCANCEL = MESSAGEBOX_STYLE.RETRYCANCEL;
pub const MB_YESNO = MESSAGEBOX_STYLE.YESNO;
pub const MB_YESNOCANCEL = MESSAGEBOX_STYLE.YESNOCANCEL;
pub const MB_ICONHAND = MESSAGEBOX_STYLE.ICONHAND;
pub const MB_ICONQUESTION = MESSAGEBOX_STYLE.ICONQUESTION;
pub const MB_ICONEXCLAMATION = MESSAGEBOX_STYLE.ICONEXCLAMATION;
pub const MB_ICONASTERISK = MESSAGEBOX_STYLE.ICONASTERISK;
pub const MB_USERICON = MESSAGEBOX_STYLE.USERICON;
pub const MB_ICONWARNING = MESSAGEBOX_STYLE.ICONEXCLAMATION;
pub const MB_ICONERROR = MESSAGEBOX_STYLE.ICONHAND;
pub const MB_ICONINFORMATION = MESSAGEBOX_STYLE.ICONASTERISK;
pub const MB_ICONSTOP = MESSAGEBOX_STYLE.ICONHAND;
pub const MB_DEFBUTTON1 = MESSAGEBOX_STYLE.OK;
pub const MB_DEFBUTTON2 = MESSAGEBOX_STYLE.DEFBUTTON2;
pub const MB_DEFBUTTON3 = MESSAGEBOX_STYLE.DEFBUTTON3;
pub const MB_DEFBUTTON4 = MESSAGEBOX_STYLE.DEFBUTTON4;
pub const MB_APPLMODAL = MESSAGEBOX_STYLE.OK;
pub const MB_SYSTEMMODAL = MESSAGEBOX_STYLE.SYSTEMMODAL;
pub const MB_TASKMODAL = MESSAGEBOX_STYLE.TASKMODAL;
pub const MB_NOFOCUS = MESSAGEBOX_STYLE.NOFOCUS;
pub const MB_SETFOREGROUND = MESSAGEBOX_STYLE.SETFOREGROUND;
pub const MB_DEFAULT_DESKTOP_ONLY = MESSAGEBOX_STYLE.DEFAULT_DESKTOP_ONLY;
pub const MB_TOPMOST = MESSAGEBOX_STYLE.TOPMOST;
pub const MB_RIGHT = MESSAGEBOX_STYLE.RIGHT;
pub const MB_RTLREADING = MESSAGEBOX_STYLE.RTLREADING;
pub const MB_SERVICE_NOTIFICATION = MESSAGEBOX_STYLE.SERVICE_NOTIFICATION;
pub const MB_SERVICE_NOTIFICATION_NT3X = MESSAGEBOX_STYLE.TOPMOST;
pub const MB_TYPEMASK = MESSAGEBOX_STYLE.TYPEMASK;
pub const MB_ICONMASK = MESSAGEBOX_STYLE.ICONMASK;
pub const MB_DEFMASK = MESSAGEBOX_STYLE.DEFMASK;
pub const MB_MODEMASK = MESSAGEBOX_STYLE.MODEMASK;
pub const MB_MISCMASK = MESSAGEBOX_STYLE.MISCMASK;
pub const MENU_ITEM_FLAGS = enum(u32) {
BYCOMMAND = 0,
BYPOSITION = 1024,
BITMAP = 4,
CHECKED = 8,
DISABLED = 2,
// ENABLED = 0, this enum value conflicts with BYCOMMAND
GRAYED = 1,
MENUBARBREAK = 32,
MENUBREAK = 64,
OWNERDRAW = 256,
POPUP = 16,
SEPARATOR = 2048,
// STRING = 0, this enum value conflicts with BYCOMMAND
// UNCHECKED = 0, this enum value conflicts with BYCOMMAND
// INSERT = 0, this enum value conflicts with BYCOMMAND
CHANGE = 128,
// APPEND = 256, this enum value conflicts with OWNERDRAW
DELETE = 512,
REMOVE = 4096,
// USECHECKBITMAPS = 512, this enum value conflicts with DELETE
// UNHILITE = 0, this enum value conflicts with BYCOMMAND
// HILITE = 128, this enum value conflicts with CHANGE
// DEFAULT = 4096, this enum value conflicts with REMOVE
SYSMENU = 8192,
HELP = 16384,
// RIGHTJUSTIFY = 16384, this enum value conflicts with HELP
MOUSESELECT = 32768,
// END = 128, this enum value conflicts with CHANGE
_,
pub fn initFlags(o: struct {
BYCOMMAND: u1 = 0,
BYPOSITION: u1 = 0,
BITMAP: u1 = 0,
CHECKED: u1 = 0,
DISABLED: u1 = 0,
GRAYED: u1 = 0,
MENUBARBREAK: u1 = 0,
MENUBREAK: u1 = 0,
OWNERDRAW: u1 = 0,
POPUP: u1 = 0,
SEPARATOR: u1 = 0,
CHANGE: u1 = 0,
DELETE: u1 = 0,
REMOVE: u1 = 0,
SYSMENU: u1 = 0,
HELP: u1 = 0,
MOUSESELECT: u1 = 0,
}) MENU_ITEM_FLAGS {
return @intToEnum(MENU_ITEM_FLAGS,
(if (o.BYCOMMAND == 1) @enumToInt(MENU_ITEM_FLAGS.BYCOMMAND) else 0)
| (if (o.BYPOSITION == 1) @enumToInt(MENU_ITEM_FLAGS.BYPOSITION) else 0)
| (if (o.BITMAP == 1) @enumToInt(MENU_ITEM_FLAGS.BITMAP) else 0)
| (if (o.CHECKED == 1) @enumToInt(MENU_ITEM_FLAGS.CHECKED) else 0)
| (if (o.DISABLED == 1) @enumToInt(MENU_ITEM_FLAGS.DISABLED) else 0)
| (if (o.GRAYED == 1) @enumToInt(MENU_ITEM_FLAGS.GRAYED) else 0)
| (if (o.MENUBARBREAK == 1) @enumToInt(MENU_ITEM_FLAGS.MENUBARBREAK) else 0)
| (if (o.MENUBREAK == 1) @enumToInt(MENU_ITEM_FLAGS.MENUBREAK) else 0)
| (if (o.OWNERDRAW == 1) @enumToInt(MENU_ITEM_FLAGS.OWNERDRAW) else 0)
| (if (o.POPUP == 1) @enumToInt(MENU_ITEM_FLAGS.POPUP) else 0)
| (if (o.SEPARATOR == 1) @enumToInt(MENU_ITEM_FLAGS.SEPARATOR) else 0)
| (if (o.CHANGE == 1) @enumToInt(MENU_ITEM_FLAGS.CHANGE) else 0)
| (if (o.DELETE == 1) @enumToInt(MENU_ITEM_FLAGS.DELETE) else 0)
| (if (o.REMOVE == 1) @enumToInt(MENU_ITEM_FLAGS.REMOVE) else 0)
| (if (o.SYSMENU == 1) @enumToInt(MENU_ITEM_FLAGS.SYSMENU) else 0)
| (if (o.HELP == 1) @enumToInt(MENU_ITEM_FLAGS.HELP) else 0)
| (if (o.MOUSESELECT == 1) @enumToInt(MENU_ITEM_FLAGS.MOUSESELECT) else 0)
);
}
};
pub const MF_BYCOMMAND = MENU_ITEM_FLAGS.BYCOMMAND;
pub const MF_BYPOSITION = MENU_ITEM_FLAGS.BYPOSITION;
pub const MF_BITMAP = MENU_ITEM_FLAGS.BITMAP;
pub const MF_CHECKED = MENU_ITEM_FLAGS.CHECKED;
pub const MF_DISABLED = MENU_ITEM_FLAGS.DISABLED;
pub const MF_ENABLED = MENU_ITEM_FLAGS.BYCOMMAND;
pub const MF_GRAYED = MENU_ITEM_FLAGS.GRAYED;
pub const MF_MENUBARBREAK = MENU_ITEM_FLAGS.MENUBARBREAK;
pub const MF_MENUBREAK = MENU_ITEM_FLAGS.MENUBREAK;
pub const MF_OWNERDRAW = MENU_ITEM_FLAGS.OWNERDRAW;
pub const MF_POPUP = MENU_ITEM_FLAGS.POPUP;
pub const MF_SEPARATOR = MENU_ITEM_FLAGS.SEPARATOR;
pub const MF_STRING = MENU_ITEM_FLAGS.BYCOMMAND;
pub const MF_UNCHECKED = MENU_ITEM_FLAGS.BYCOMMAND;
pub const MF_INSERT = MENU_ITEM_FLAGS.BYCOMMAND;
pub const MF_CHANGE = MENU_ITEM_FLAGS.CHANGE;
pub const MF_APPEND = MENU_ITEM_FLAGS.OWNERDRAW;
pub const MF_DELETE = MENU_ITEM_FLAGS.DELETE;
pub const MF_REMOVE = MENU_ITEM_FLAGS.REMOVE;
pub const MF_USECHECKBITMAPS = MENU_ITEM_FLAGS.DELETE;
pub const MF_UNHILITE = MENU_ITEM_FLAGS.BYCOMMAND;
pub const MF_HILITE = MENU_ITEM_FLAGS.CHANGE;
pub const MF_DEFAULT = MENU_ITEM_FLAGS.REMOVE;
pub const MF_SYSMENU = MENU_ITEM_FLAGS.SYSMENU;
pub const MF_HELP = MENU_ITEM_FLAGS.HELP;
pub const MF_RIGHTJUSTIFY = MENU_ITEM_FLAGS.HELP;
pub const MF_MOUSESELECT = MENU_ITEM_FLAGS.MOUSESELECT;
pub const MF_END = MENU_ITEM_FLAGS.CHANGE;
pub const SHOW_WINDOW_CMD = enum(u32) {
FORCEMINIMIZE = 11,
HIDE = 0,
MAXIMIZE = 3,
MINIMIZE = 6,
RESTORE = 9,
SHOW = 5,
SHOWDEFAULT = 10,
// SHOWMAXIMIZED = 3, this enum value conflicts with MAXIMIZE
SHOWMINIMIZED = 2,
SHOWMINNOACTIVE = 7,
SHOWNA = 8,
SHOWNOACTIVATE = 4,
SHOWNORMAL = 1,
// NORMAL = 1, this enum value conflicts with SHOWNORMAL
// MAX = 11, this enum value conflicts with FORCEMINIMIZE
// PARENTCLOSING = 1, this enum value conflicts with SHOWNORMAL
// OTHERZOOM = 2, this enum value conflicts with SHOWMINIMIZED
// PARENTOPENING = 3, this enum value conflicts with MAXIMIZE
// OTHERUNZOOM = 4, this enum value conflicts with SHOWNOACTIVATE
// SCROLLCHILDREN = 1, this enum value conflicts with SHOWNORMAL
// INVALIDATE = 2, this enum value conflicts with SHOWMINIMIZED
// ERASE = 4, this enum value conflicts with SHOWNOACTIVATE
SMOOTHSCROLL = 16,
_,
pub fn initFlags(o: struct {
FORCEMINIMIZE: u1 = 0,
HIDE: u1 = 0,
MAXIMIZE: u1 = 0,
MINIMIZE: u1 = 0,
RESTORE: u1 = 0,
SHOW: u1 = 0,
SHOWDEFAULT: u1 = 0,
SHOWMINIMIZED: u1 = 0,
SHOWMINNOACTIVE: u1 = 0,
SHOWNA: u1 = 0,
SHOWNOACTIVATE: u1 = 0,
SHOWNORMAL: u1 = 0,
SMOOTHSCROLL: u1 = 0,
}) SHOW_WINDOW_CMD {
return @intToEnum(SHOW_WINDOW_CMD,
(if (o.FORCEMINIMIZE == 1) @enumToInt(SHOW_WINDOW_CMD.FORCEMINIMIZE) else 0)
| (if (o.HIDE == 1) @enumToInt(SHOW_WINDOW_CMD.HIDE) else 0)
| (if (o.MAXIMIZE == 1) @enumToInt(SHOW_WINDOW_CMD.MAXIMIZE) else 0)
| (if (o.MINIMIZE == 1) @enumToInt(SHOW_WINDOW_CMD.MINIMIZE) else 0)
| (if (o.RESTORE == 1) @enumToInt(SHOW_WINDOW_CMD.RESTORE) else 0)
| (if (o.SHOW == 1) @enumToInt(SHOW_WINDOW_CMD.SHOW) else 0)
| (if (o.SHOWDEFAULT == 1) @enumToInt(SHOW_WINDOW_CMD.SHOWDEFAULT) else 0)
| (if (o.SHOWMINIMIZED == 1) @enumToInt(SHOW_WINDOW_CMD.SHOWMINIMIZED) else 0)
| (if (o.SHOWMINNOACTIVE == 1) @enumToInt(SHOW_WINDOW_CMD.SHOWMINNOACTIVE) else 0)
| (if (o.SHOWNA == 1) @enumToInt(SHOW_WINDOW_CMD.SHOWNA) else 0)
| (if (o.SHOWNOACTIVATE == 1) @enumToInt(SHOW_WINDOW_CMD.SHOWNOACTIVATE) else 0)
| (if (o.SHOWNORMAL == 1) @enumToInt(SHOW_WINDOW_CMD.SHOWNORMAL) else 0)
| (if (o.SMOOTHSCROLL == 1) @enumToInt(SHOW_WINDOW_CMD.SMOOTHSCROLL) else 0)
);
}
};
pub const SW_FORCEMINIMIZE = SHOW_WINDOW_CMD.FORCEMINIMIZE;
pub const SW_HIDE = SHOW_WINDOW_CMD.HIDE;
pub const SW_MAXIMIZE = SHOW_WINDOW_CMD.MAXIMIZE;
pub const SW_MINIMIZE = SHOW_WINDOW_CMD.MINIMIZE;
pub const SW_RESTORE = SHOW_WINDOW_CMD.RESTORE;
pub const SW_SHOW = SHOW_WINDOW_CMD.SHOW;
pub const SW_SHOWDEFAULT = SHOW_WINDOW_CMD.SHOWDEFAULT;
pub const SW_SHOWMAXIMIZED = SHOW_WINDOW_CMD.MAXIMIZE;
pub const SW_SHOWMINIMIZED = SHOW_WINDOW_CMD.SHOWMINIMIZED;
pub const SW_SHOWMINNOACTIVE = SHOW_WINDOW_CMD.SHOWMINNOACTIVE;
pub const SW_SHOWNA = SHOW_WINDOW_CMD.SHOWNA;
pub const SW_SHOWNOACTIVATE = SHOW_WINDOW_CMD.SHOWNOACTIVATE;
pub const SW_SHOWNORMAL = SHOW_WINDOW_CMD.SHOWNORMAL;
pub const SW_NORMAL = SHOW_WINDOW_CMD.SHOWNORMAL;
pub const SW_MAX = SHOW_WINDOW_CMD.FORCEMINIMIZE;
pub const SW_PARENTCLOSING = SHOW_WINDOW_CMD.SHOWNORMAL;
pub const SW_OTHERZOOM = SHOW_WINDOW_CMD.SHOWMINIMIZED;
pub const SW_PARENTOPENING = SHOW_WINDOW_CMD.MAXIMIZE;
pub const SW_OTHERUNZOOM = SHOW_WINDOW_CMD.SHOWNOACTIVATE;
pub const SW_SCROLLCHILDREN = SHOW_WINDOW_CMD.SHOWNORMAL;
pub const SW_INVALIDATE = SHOW_WINDOW_CMD.SHOWMINIMIZED;
pub const SW_ERASE = SHOW_WINDOW_CMD.SHOWNOACTIVATE;
pub const SW_SMOOTHSCROLL = SHOW_WINDOW_CMD.SMOOTHSCROLL;
pub const SYSTEM_PARAMETERS_INFO_ACTION = enum(u32) {
GETBEEP = 1,
SETBEEP = 2,
GETMOUSE = 3,
SETMOUSE = 4,
GETBORDER = 5,
SETBORDER = 6,
GETKEYBOARDSPEED = 10,
SETKEYBOARDSPEED = 11,
LANGDRIVER = 12,
ICONHORIZONTALSPACING = 13,
GETSCREENSAVETIMEOUT = 14,
SETSCREENSAVETIMEOUT = 15,
GETSCREENSAVEACTIVE = 16,
SETSCREENSAVEACTIVE = 17,
GETGRIDGRANULARITY = 18,
SETGRIDGRANULARITY = 19,
SETDESKWALLPAPER = 20,
SETDESKPATTERN = 21,
GETKEYBOARDDELAY = 22,
SETKEYBOARDDELAY = 23,
ICONVERTICALSPACING = 24,
GETICONTITLEWRAP = 25,
SETICONTITLEWRAP = 26,
GETMENUDROPALIGNMENT = 27,
SETMENUDROPALIGNMENT = 28,
SETDOUBLECLKWIDTH = 29,
SETDOUBLECLKHEIGHT = 30,
GETICONTITLELOGFONT = 31,
SETDOUBLECLICKTIME = 32,
SETMOUSEBUTTONSWAP = 33,
SETICONTITLELOGFONT = 34,
GETFASTTASKSWITCH = 35,
SETFASTTASKSWITCH = 36,
SETDRAGFULLWINDOWS = 37,
GETDRAGFULLWINDOWS = 38,
GETNONCLIENTMETRICS = 41,
SETNONCLIENTMETRICS = 42,
GETMINIMIZEDMETRICS = 43,
SETMINIMIZEDMETRICS = 44,
GETICONMETRICS = 45,
SETICONMETRICS = 46,
SETWORKAREA = 47,
GETWORKAREA = 48,
SETPENWINDOWS = 49,
GETHIGHCONTRAST = 66,
SETHIGHCONTRAST = 67,
GETKEYBOARDPREF = 68,
SETKEYBOARDPREF = 69,
GETSCREENREADER = 70,
SETSCREENREADER = 71,
GETANIMATION = 72,
SETANIMATION = 73,
GETFONTSMOOTHING = 74,
SETFONTSMOOTHING = 75,
SETDRAGWIDTH = 76,
SETDRAGHEIGHT = 77,
SETHANDHELD = 78,
GETLOWPOWERTIMEOUT = 79,
GETPOWEROFFTIMEOUT = 80,
SETLOWPOWERTIMEOUT = 81,
SETPOWEROFFTIMEOUT = 82,
GETLOWPOWERACTIVE = 83,
GETPOWEROFFACTIVE = 84,
SETLOWPOWERACTIVE = 85,
SETPOWEROFFACTIVE = 86,
SETCURSORS = 87,
SETICONS = 88,
GETDEFAULTINPUTLANG = 89,
SETDEFAULTINPUTLANG = 90,
SETLANGTOGGLE = 91,
GETWINDOWSEXTENSION = 92,
SETMOUSETRAILS = 93,
GETMOUSETRAILS = 94,
SETSCREENSAVERRUNNING = 97,
// SCREENSAVERRUNNING = 97, this enum value conflicts with SETSCREENSAVERRUNNING
GETFILTERKEYS = 50,
SETFILTERKEYS = 51,
GETTOGGLEKEYS = 52,
SETTOGGLEKEYS = 53,
GETMOUSEKEYS = 54,
SETMOUSEKEYS = 55,
GETSHOWSOUNDS = 56,
SETSHOWSOUNDS = 57,
GETSTICKYKEYS = 58,
SETSTICKYKEYS = 59,
GETACCESSTIMEOUT = 60,
SETACCESSTIMEOUT = 61,
GETSERIALKEYS = 62,
SETSERIALKEYS = 63,
GETSOUNDSENTRY = 64,
SETSOUNDSENTRY = 65,
GETSNAPTODEFBUTTON = 95,
SETSNAPTODEFBUTTON = 96,
GETMOUSEHOVERWIDTH = 98,
SETMOUSEHOVERWIDTH = 99,
GETMOUSEHOVERHEIGHT = 100,
SETMOUSEHOVERHEIGHT = 101,
GETMOUSEHOVERTIME = 102,
SETMOUSEHOVERTIME = 103,
GETWHEELSCROLLLINES = 104,
SETWHEELSCROLLLINES = 105,
GETMENUSHOWDELAY = 106,
SETMENUSHOWDELAY = 107,
GETWHEELSCROLLCHARS = 108,
SETWHEELSCROLLCHARS = 109,
GETSHOWIMEUI = 110,
SETSHOWIMEUI = 111,
GETMOUSESPEED = 112,
SETMOUSESPEED = 113,
GETSCREENSAVERRUNNING = 114,
GETDESKWALLPAPER = 115,
GETAUDIODESCRIPTION = 116,
SETAUDIODESCRIPTION = 117,
GETSCREENSAVESECURE = 118,
SETSCREENSAVESECURE = 119,
GETHUNGAPPTIMEOUT = 120,
SETHUNGAPPTIMEOUT = 121,
GETWAITTOKILLTIMEOUT = 122,
SETWAITTOKILLTIMEOUT = 123,
GETWAITTOKILLSERVICETIMEOUT = 124,
SETWAITTOKILLSERVICETIMEOUT = 125,
GETMOUSEDOCKTHRESHOLD = 126,
SETMOUSEDOCKTHRESHOLD = 127,
GETPENDOCKTHRESHOLD = 128,
SETPENDOCKTHRESHOLD = 129,
GETWINARRANGING = 130,
SETWINARRANGING = 131,
GETMOUSEDRAGOUTTHRESHOLD = 132,
SETMOUSEDRAGOUTTHRESHOLD = 133,
GETPENDRAGOUTTHRESHOLD = 134,
SETPENDRAGOUTTHRESHOLD = 135,
GETMOUSESIDEMOVETHRESHOLD = 136,
SETMOUSESIDEMOVETHRESHOLD = 137,
GETPENSIDEMOVETHRESHOLD = 138,
SETPENSIDEMOVETHRESHOLD = 139,
GETDRAGFROMMAXIMIZE = 140,
SETDRAGFROMMAXIMIZE = 141,
GETSNAPSIZING = 142,
SETSNAPSIZING = 143,
GETDOCKMOVING = 144,
SETDOCKMOVING = 145,
GETTOUCHPREDICTIONPARAMETERS = 156,
SETTOUCHPREDICTIONPARAMETERS = 157,
GETLOGICALDPIOVERRIDE = 158,
SETLOGICALDPIOVERRIDE = 159,
GETMENURECT = 162,
SETMENURECT = 163,
GETACTIVEWINDOWTRACKING = 4096,
SETACTIVEWINDOWTRACKING = 4097,
GETMENUANIMATION = 4098,
SETMENUANIMATION = 4099,
GETCOMBOBOXANIMATION = 4100,
SETCOMBOBOXANIMATION = 4101,
GETLISTBOXSMOOTHSCROLLING = 4102,
SETLISTBOXSMOOTHSCROLLING = 4103,
GETGRADIENTCAPTIONS = 4104,
SETGRADIENTCAPTIONS = 4105,
GETKEYBOARDCUES = 4106,
SETKEYBOARDCUES = 4107,
// GETMENUUNDERLINES = 4106, this enum value conflicts with GETKEYBOARDCUES
// SETMENUUNDERLINES = 4107, this enum value conflicts with SETKEYBOARDCUES
GETACTIVEWNDTRKZORDER = 4108,
SETACTIVEWNDTRKZORDER = 4109,
GETHOTTRACKING = 4110,
SETHOTTRACKING = 4111,
GETMENUFADE = 4114,
SETMENUFADE = 4115,
GETSELECTIONFADE = 4116,
SETSELECTIONFADE = 4117,
GETTOOLTIPANIMATION = 4118,
SETTOOLTIPANIMATION = 4119,
GETTOOLTIPFADE = 4120,
SETTOOLTIPFADE = 4121,
GETCURSORSHADOW = 4122,
SETCURSORSHADOW = 4123,
GETMOUSESONAR = 4124,
SETMOUSESONAR = 4125,
GETMOUSECLICKLOCK = 4126,
SETMOUSECLICKLOCK = 4127,
GETMOUSEVANISH = 4128,
SETMOUSEVANISH = 4129,
GETFLATMENU = 4130,
SETFLATMENU = 4131,
GETDROPSHADOW = 4132,
SETDROPSHADOW = 4133,
GETBLOCKSENDINPUTRESETS = 4134,
SETBLOCKSENDINPUTRESETS = 4135,
GETUIEFFECTS = 4158,
SETUIEFFECTS = 4159,
GETDISABLEOVERLAPPEDCONTENT = 4160,
SETDISABLEOVERLAPPEDCONTENT = 4161,
GETCLIENTAREAANIMATION = 4162,
SETCLIENTAREAANIMATION = 4163,
GETCLEARTYPE = 4168,
SETCLEARTYPE = 4169,
GETSPEECHRECOGNITION = 4170,
SETSPEECHRECOGNITION = 4171,
GETCARETBROWSING = 4172,
SETCARETBROWSING = 4173,
GETTHREADLOCALINPUTSETTINGS = 4174,
SETTHREADLOCALINPUTSETTINGS = 4175,
GETSYSTEMLANGUAGEBAR = 4176,
SETSYSTEMLANGUAGEBAR = 4177,
GETFOREGROUNDLOCKTIMEOUT = 8192,
SETFOREGROUNDLOCKTIMEOUT = 8193,
GETACTIVEWNDTRKTIMEOUT = 8194,
SETACTIVEWNDTRKTIMEOUT = 8195,
GETFOREGROUNDFLASHCOUNT = 8196,
SETFOREGROUNDFLASHCOUNT = 8197,
GETCARETWIDTH = 8198,
SETCARETWIDTH = 8199,
GETMOUSECLICKLOCKTIME = 8200,
SETMOUSECLICKLOCKTIME = 8201,
GETFONTSMOOTHINGTYPE = 8202,
SETFONTSMOOTHINGTYPE = 8203,
GETFONTSMOOTHINGCONTRAST = 8204,
SETFONTSMOOTHINGCONTRAST = 8205,
GETFOCUSBORDERWIDTH = 8206,
SETFOCUSBORDERWIDTH = 8207,
GETFOCUSBORDERHEIGHT = 8208,
SETFOCUSBORDERHEIGHT = 8209,
GETFONTSMOOTHINGORIENTATION = 8210,
SETFONTSMOOTHINGORIENTATION = 8211,
GETMINIMUMHITRADIUS = 8212,
SETMINIMUMHITRADIUS = 8213,
GETMESSAGEDURATION = 8214,
SETMESSAGEDURATION = 8215,
GETCONTACTVISUALIZATION = 8216,
SETCONTACTVISUALIZATION = 8217,
GETGESTUREVISUALIZATION = 8218,
SETGESTUREVISUALIZATION = 8219,
GETMOUSEWHEELROUTING = 8220,
SETMOUSEWHEELROUTING = 8221,
GETPENVISUALIZATION = 8222,
SETPENVISUALIZATION = 8223,
GETPENARBITRATIONTYPE = 8224,
SETPENARBITRATIONTYPE = 8225,
GETCARETTIMEOUT = 8226,
SETCARETTIMEOUT = 8227,
GETHANDEDNESS = 8228,
SETHANDEDNESS = 8229,
_,
pub fn initFlags(o: struct {
GETBEEP: u1 = 0,
SETBEEP: u1 = 0,
GETMOUSE: u1 = 0,
SETMOUSE: u1 = 0,
GETBORDER: u1 = 0,
SETBORDER: u1 = 0,
GETKEYBOARDSPEED: u1 = 0,
SETKEYBOARDSPEED: u1 = 0,
LANGDRIVER: u1 = 0,
ICONHORIZONTALSPACING: u1 = 0,
GETSCREENSAVETIMEOUT: u1 = 0,
SETSCREENSAVETIMEOUT: u1 = 0,
GETSCREENSAVEACTIVE: u1 = 0,
SETSCREENSAVEACTIVE: u1 = 0,
GETGRIDGRANULARITY: u1 = 0,
SETGRIDGRANULARITY: u1 = 0,
SETDESKWALLPAPER: u1 = 0,
SETDESKPATTERN: u1 = 0,
GETKEYBOARDDELAY: u1 = 0,
SETKEYBOARDDELAY: u1 = 0,
ICONVERTICALSPACING: u1 = 0,
GETICONTITLEWRAP: u1 = 0,
SETICONTITLEWRAP: u1 = 0,
GETMENUDROPALIGNMENT: u1 = 0,
SETMENUDROPALIGNMENT: u1 = 0,
SETDOUBLECLKWIDTH: u1 = 0,
SETDOUBLECLKHEIGHT: u1 = 0,
GETICONTITLELOGFONT: u1 = 0,
SETDOUBLECLICKTIME: u1 = 0,
SETMOUSEBUTTONSWAP: u1 = 0,
SETICONTITLELOGFONT: u1 = 0,
GETFASTTASKSWITCH: u1 = 0,
SETFASTTASKSWITCH: u1 = 0,
SETDRAGFULLWINDOWS: u1 = 0,
GETDRAGFULLWINDOWS: u1 = 0,
GETNONCLIENTMETRICS: u1 = 0,
SETNONCLIENTMETRICS: u1 = 0,
GETMINIMIZEDMETRICS: u1 = 0,
SETMINIMIZEDMETRICS: u1 = 0,
GETICONMETRICS: u1 = 0,
SETICONMETRICS: u1 = 0,
SETWORKAREA: u1 = 0,
GETWORKAREA: u1 = 0,
SETPENWINDOWS: u1 = 0,
GETHIGHCONTRAST: u1 = 0,
SETHIGHCONTRAST: u1 = 0,
GETKEYBOARDPREF: u1 = 0,
SETKEYBOARDPREF: u1 = 0,
GETSCREENREADER: u1 = 0,
SETSCREENREADER: u1 = 0,
GETANIMATION: u1 = 0,
SETANIMATION: u1 = 0,
GETFONTSMOOTHING: u1 = 0,
SETFONTSMOOTHING: u1 = 0,
SETDRAGWIDTH: u1 = 0,
SETDRAGHEIGHT: u1 = 0,
SETHANDHELD: u1 = 0,
GETLOWPOWERTIMEOUT: u1 = 0,
GETPOWEROFFTIMEOUT: u1 = 0,
SETLOWPOWERTIMEOUT: u1 = 0,
SETPOWEROFFTIMEOUT: u1 = 0,
GETLOWPOWERACTIVE: u1 = 0,
GETPOWEROFFACTIVE: u1 = 0,
SETLOWPOWERACTIVE: u1 = 0,
SETPOWEROFFACTIVE: u1 = 0,
SETCURSORS: u1 = 0,
SETICONS: u1 = 0,
GETDEFAULTINPUTLANG: u1 = 0,
SETDEFAULTINPUTLANG: u1 = 0,
SETLANGTOGGLE: u1 = 0,
GETWINDOWSEXTENSION: u1 = 0,
SETMOUSETRAILS: u1 = 0,
GETMOUSETRAILS: u1 = 0,
SETSCREENSAVERRUNNING: u1 = 0,
GETFILTERKEYS: u1 = 0,
SETFILTERKEYS: u1 = 0,
GETTOGGLEKEYS: u1 = 0,
SETTOGGLEKEYS: u1 = 0,
GETMOUSEKEYS: u1 = 0,
SETMOUSEKEYS: u1 = 0,
GETSHOWSOUNDS: u1 = 0,
SETSHOWSOUNDS: u1 = 0,
GETSTICKYKEYS: u1 = 0,
SETSTICKYKEYS: u1 = 0,
GETACCESSTIMEOUT: u1 = 0,
SETACCESSTIMEOUT: u1 = 0,
GETSERIALKEYS: u1 = 0,
SETSERIALKEYS: u1 = 0,
GETSOUNDSENTRY: u1 = 0,
SETSOUNDSENTRY: u1 = 0,
GETSNAPTODEFBUTTON: u1 = 0,
SETSNAPTODEFBUTTON: u1 = 0,
GETMOUSEHOVERWIDTH: u1 = 0,
SETMOUSEHOVERWIDTH: u1 = 0,
GETMOUSEHOVERHEIGHT: u1 = 0,
SETMOUSEHOVERHEIGHT: u1 = 0,
GETMOUSEHOVERTIME: u1 = 0,
SETMOUSEHOVERTIME: u1 = 0,
GETWHEELSCROLLLINES: u1 = 0,
SETWHEELSCROLLLINES: u1 = 0,
GETMENUSHOWDELAY: u1 = 0,
SETMENUSHOWDELAY: u1 = 0,
GETWHEELSCROLLCHARS: u1 = 0,
SETWHEELSCROLLCHARS: u1 = 0,
GETSHOWIMEUI: u1 = 0,
SETSHOWIMEUI: u1 = 0,
GETMOUSESPEED: u1 = 0,
SETMOUSESPEED: u1 = 0,
GETSCREENSAVERRUNNING: u1 = 0,
GETDESKWALLPAPER: u1 = 0,
GETAUDIODESCRIPTION: u1 = 0,
SETAUDIODESCRIPTION: u1 = 0,
GETSCREENSAVESECURE: u1 = 0,
SETSCREENSAVESECURE: u1 = 0,
GETHUNGAPPTIMEOUT: u1 = 0,
SETHUNGAPPTIMEOUT: u1 = 0,
GETWAITTOKILLTIMEOUT: u1 = 0,
SETWAITTOKILLTIMEOUT: u1 = 0,
GETWAITTOKILLSERVICETIMEOUT: u1 = 0,
SETWAITTOKILLSERVICETIMEOUT: u1 = 0,
GETMOUSEDOCKTHRESHOLD: u1 = 0,
SETMOUSEDOCKTHRESHOLD: u1 = 0,
GETPENDOCKTHRESHOLD: u1 = 0,
SETPENDOCKTHRESHOLD: u1 = 0,
GETWINARRANGING: u1 = 0,
SETWINARRANGING: u1 = 0,
GETMOUSEDRAGOUTTHRESHOLD: u1 = 0,
SETMOUSEDRAGOUTTHRESHOLD: u1 = 0,
GETPENDRAGOUTTHRESHOLD: u1 = 0,
SETPENDRAGOUTTHRESHOLD: u1 = 0,
GETMOUSESIDEMOVETHRESHOLD: u1 = 0,
SETMOUSESIDEMOVETHRESHOLD: u1 = 0,
GETPENSIDEMOVETHRESHOLD: u1 = 0,
SETPENSIDEMOVETHRESHOLD: u1 = 0,
GETDRAGFROMMAXIMIZE: u1 = 0,
SETDRAGFROMMAXIMIZE: u1 = 0,
GETSNAPSIZING: u1 = 0,
SETSNAPSIZING: u1 = 0,
GETDOCKMOVING: u1 = 0,
SETDOCKMOVING: u1 = 0,
GETTOUCHPREDICTIONPARAMETERS: u1 = 0,
SETTOUCHPREDICTIONPARAMETERS: u1 = 0,
GETLOGICALDPIOVERRIDE: u1 = 0,
SETLOGICALDPIOVERRIDE: u1 = 0,
GETMENURECT: u1 = 0,
SETMENURECT: u1 = 0,
GETACTIVEWINDOWTRACKING: u1 = 0,
SETACTIVEWINDOWTRACKING: u1 = 0,
GETMENUANIMATION: u1 = 0,
SETMENUANIMATION: u1 = 0,
GETCOMBOBOXANIMATION: u1 = 0,
SETCOMBOBOXANIMATION: u1 = 0,
GETLISTBOXSMOOTHSCROLLING: u1 = 0,
SETLISTBOXSMOOTHSCROLLING: u1 = 0,
GETGRADIENTCAPTIONS: u1 = 0,
SETGRADIENTCAPTIONS: u1 = 0,
GETKEYBOARDCUES: u1 = 0,
SETKEYBOARDCUES: u1 = 0,
GETACTIVEWNDTRKZORDER: u1 = 0,
SETACTIVEWNDTRKZORDER: u1 = 0,
GETHOTTRACKING: u1 = 0,
SETHOTTRACKING: u1 = 0,
GETMENUFADE: u1 = 0,
SETMENUFADE: u1 = 0,
GETSELECTIONFADE: u1 = 0,
SETSELECTIONFADE: u1 = 0,
GETTOOLTIPANIMATION: u1 = 0,
SETTOOLTIPANIMATION: u1 = 0,
GETTOOLTIPFADE: u1 = 0,
SETTOOLTIPFADE: u1 = 0,
GETCURSORSHADOW: u1 = 0,
SETCURSORSHADOW: u1 = 0,
GETMOUSESONAR: u1 = 0,
SETMOUSESONAR: u1 = 0,
GETMOUSECLICKLOCK: u1 = 0,
SETMOUSECLICKLOCK: u1 = 0,
GETMOUSEVANISH: u1 = 0,
SETMOUSEVANISH: u1 = 0,
GETFLATMENU: u1 = 0,
SETFLATMENU: u1 = 0,
GETDROPSHADOW: u1 = 0,
SETDROPSHADOW: u1 = 0,
GETBLOCKSENDINPUTRESETS: u1 = 0,
SETBLOCKSENDINPUTRESETS: u1 = 0,
GETUIEFFECTS: u1 = 0,
SETUIEFFECTS: u1 = 0,
GETDISABLEOVERLAPPEDCONTENT: u1 = 0,
SETDISABLEOVERLAPPEDCONTENT: u1 = 0,
GETCLIENTAREAANIMATION: u1 = 0,
SETCLIENTAREAANIMATION: u1 = 0,
GETCLEARTYPE: u1 = 0,
SETCLEARTYPE: u1 = 0,
GETSPEECHRECOGNITION: u1 = 0,
SETSPEECHRECOGNITION: u1 = 0,
GETCARETBROWSING: u1 = 0,
SETCARETBROWSING: u1 = 0,
GETTHREADLOCALINPUTSETTINGS: u1 = 0,
SETTHREADLOCALINPUTSETTINGS: u1 = 0,
GETSYSTEMLANGUAGEBAR: u1 = 0,
SETSYSTEMLANGUAGEBAR: u1 = 0,
GETFOREGROUNDLOCKTIMEOUT: u1 = 0,
SETFOREGROUNDLOCKTIMEOUT: u1 = 0,
GETACTIVEWNDTRKTIMEOUT: u1 = 0,
SETACTIVEWNDTRKTIMEOUT: u1 = 0,
GETFOREGROUNDFLASHCOUNT: u1 = 0,
SETFOREGROUNDFLASHCOUNT: u1 = 0,
GETCARETWIDTH: u1 = 0,
SETCARETWIDTH: u1 = 0,
GETMOUSECLICKLOCKTIME: u1 = 0,
SETMOUSECLICKLOCKTIME: u1 = 0,
GETFONTSMOOTHINGTYPE: u1 = 0,
SETFONTSMOOTHINGTYPE: u1 = 0,
GETFONTSMOOTHINGCONTRAST: u1 = 0,
SETFONTSMOOTHINGCONTRAST: u1 = 0,
GETFOCUSBORDERWIDTH: u1 = 0,
SETFOCUSBORDERWIDTH: u1 = 0,
GETFOCUSBORDERHEIGHT: u1 = 0,
SETFOCUSBORDERHEIGHT: u1 = 0,
GETFONTSMOOTHINGORIENTATION: u1 = 0,
SETFONTSMOOTHINGORIENTATION: u1 = 0,
GETMINIMUMHITRADIUS: u1 = 0,
SETMINIMUMHITRADIUS: u1 = 0,
GETMESSAGEDURATION: u1 = 0,
SETMESSAGEDURATION: u1 = 0,
GETCONTACTVISUALIZATION: u1 = 0,
SETCONTACTVISUALIZATION: u1 = 0,
GETGESTUREVISUALIZATION: u1 = 0,
SETGESTUREVISUALIZATION: u1 = 0,
GETMOUSEWHEELROUTING: u1 = 0,
SETMOUSEWHEELROUTING: u1 = 0,
GETPENVISUALIZATION: u1 = 0,
SETPENVISUALIZATION: u1 = 0,
GETPENARBITRATIONTYPE: u1 = 0,
SETPENARBITRATIONTYPE: u1 = 0,
GETCARETTIMEOUT: u1 = 0,
SETCARETTIMEOUT: u1 = 0,
GETHANDEDNESS: u1 = 0,
SETHANDEDNESS: u1 = 0,
}) SYSTEM_PARAMETERS_INFO_ACTION {
return @intToEnum(SYSTEM_PARAMETERS_INFO_ACTION,
(if (o.GETBEEP == 1) @enumToInt(SYSTEM_PARAMETERS_INFO_ACTION.GETBEEP) else 0)
| (if (o.SETBEEP == 1) @enumToInt(SYSTEM_PARAMETERS_INFO_ACTION.SETBEEP) else 0)
| (if (o.GETMOUSE == 1) @enumToInt(SYSTEM_PARAMETERS_INFO_ACTION.GETMOUSE) else 0)
| (if (o.SETMOUSE == 1) @enumToInt(SYSTEM_PARAMETERS_INFO_ACTION.SETMOUSE) else 0)
| (if (o.GETBORDER == 1) @enumToInt(SYSTEM_PARAMETERS_INFO_ACTION.GETBORDER) else 0)
| (if (o.SETBORDER == 1) @enumToInt(SYSTEM_PARAMETERS_INFO_ACTION.SETBORDER) else 0)
| (if (o.GETKEYBOARDSPEED == 1) @enumToInt(SYSTEM_PARAMETERS_INFO_ACTION.GETKEYBOARDSPEED) else 0)
| (if (o.SETKEYBOARDSPEED == 1) @enumToInt(SYSTEM_PARAMETERS_INFO_ACTION.SETKEYBOARDSPEED) else 0)
| (if (o.LANGDRIVER == 1) @enumToInt(SYSTEM_PARAMETERS_INFO_ACTION.LANGDRIVER) else 0)
| (if (o.ICONHORIZONTALSPACING == 1) @enumToInt(SYSTEM_PARAMETERS_INFO_ACTION.ICONHORIZONTALSPACING) else 0)
| (if (o.GETSCREENSAVETIMEOUT == 1) @enumToInt(SYSTEM_PARAMETERS_INFO_ACTION.GETSCREENSAVETIMEOUT) else 0)
| (if (o.SETSCREENSAVETIMEOUT == 1) @enumToInt(SYSTEM_PARAMETERS_INFO_ACTION.SETSCREENSAVETIMEOUT) else 0)
| (if (o.GETSCREENSAVEACTIVE == 1) @enumToInt(SYSTEM_PARAMETERS_INFO_ACTION.GETSCREENSAVEACTIVE) else 0)
| (if (o.SETSCREENSAVEACTIVE == 1) @enumToInt(SYSTEM_PARAMETERS_INFO_ACTION.SETSCREENSAVEACTIVE) else 0)
| (if (o.GETGRIDGRANULARITY == 1) @enumToInt(SYSTEM_PARAMETERS_INFO_ACTION.GETGRIDGRANULARITY) else 0)
| (if (o.SETGRIDGRANULARITY == 1) @enumToInt(SYSTEM_PARAMETERS_INFO_ACTION.SETGRIDGRANULARITY) else 0)
| (if (o.SETDESKWALLPAPER == 1) @enumToInt(SYSTEM_PARAMETERS_INFO_ACTION.SETDESKWALLPAPER) else 0)
| (if (o.SETDESKPATTERN == 1) @enumToInt(SYSTEM_PARAMETERS_INFO_ACTION.SETDESKPATTERN) else 0)
| (if (o.GETKEYBOARDDELAY == 1) @enumToInt(SYSTEM_PARAMETERS_INFO_ACTION.GETKEYBOARDDELAY) else 0)
| (if (o.SETKEYBOARDDELAY == 1) @enumToInt(SYSTEM_PARAMETERS_INFO_ACTION.SETKEYBOARDDELAY) else 0)
| (if (o.ICONVERTICALSPACING == 1) @enumToInt(SYSTEM_PARAMETERS_INFO_ACTION.ICONVERTICALSPACING) else 0)
| (if (o.GETICONTITLEWRAP == 1) @enumToInt(SYSTEM_PARAMETERS_INFO_ACTION.GETICONTITLEWRAP) else 0)
| (if (o.SETICONTITLEWRAP == 1) @enumToInt(SYSTEM_PARAMETERS_INFO_ACTION.SETICONTITLEWRAP) else 0)
| (if (o.GETMENUDROPALIGNMENT == 1) @enumToInt(SYSTEM_PARAMETERS_INFO_ACTION.GETMENUDROPALIGNMENT) else 0)
| (if (o.SETMENUDROPALIGNMENT == 1) @enumToInt(SYSTEM_PARAMETERS_INFO_ACTION.SETMENUDROPALIGNMENT) else 0)
| (if (o.SETDOUBLECLKWIDTH == 1) @enumToInt(SYSTEM_PARAMETERS_INFO_ACTION.SETDOUBLECLKWIDTH) else 0)
| (if (o.SETDOUBLECLKHEIGHT == 1) @enumToInt(SYSTEM_PARAMETERS_INFO_ACTION.SETDOUBLECLKHEIGHT) else 0)
| (if (o.GETICONTITLELOGFONT == 1) @enumToInt(SYSTEM_PARAMETERS_INFO_ACTION.GETICONTITLELOGFONT) else 0)
| (if (o.SETDOUBLECLICKTIME == 1) @enumToInt(SYSTEM_PARAMETERS_INFO_ACTION.SETDOUBLECLICKTIME) else 0)
| (if (o.SETMOUSEBUTTONSWAP == 1) @enumToInt(SYSTEM_PARAMETERS_INFO_ACTION.SETMOUSEBUTTONSWAP) else 0)
| (if (o.SETICONTITLELOGFONT == 1) @enumToInt(SYSTEM_PARAMETERS_INFO_ACTION.SETICONTITLELOGFONT) else 0)
| (if (o.GETFASTTASKSWITCH == 1) @enumToInt(SYSTEM_PARAMETERS_INFO_ACTION.GETFASTTASKSWITCH) else 0)
| (if (o.SETFASTTASKSWITCH == 1) @enumToInt(SYSTEM_PARAMETERS_INFO_ACTION.SETFASTTASKSWITCH) else 0)
| (if (o.SETDRAGFULLWINDOWS == 1) @enumToInt(SYSTEM_PARAMETERS_INFO_ACTION.SETDRAGFULLWINDOWS) else 0)
| (if (o.GETDRAGFULLWINDOWS == 1) @enumToInt(SYSTEM_PARAMETERS_INFO_ACTION.GETDRAGFULLWINDOWS) else 0)
| (if (o.GETNONCLIENTMETRICS == 1) @enumToInt(SYSTEM_PARAMETERS_INFO_ACTION.GETNONCLIENTMETRICS) else 0)
| (if (o.SETNONCLIENTMETRICS == 1) @enumToInt(SYSTEM_PARAMETERS_INFO_ACTION.SETNONCLIENTMETRICS) else 0)
| (if (o.GETMINIMIZEDMETRICS == 1) @enumToInt(SYSTEM_PARAMETERS_INFO_ACTION.GETMINIMIZEDMETRICS) else 0)
| (if (o.SETMINIMIZEDMETRICS == 1) @enumToInt(SYSTEM_PARAMETERS_INFO_ACTION.SETMINIMIZEDMETRICS) else 0)
| (if (o.GETICONMETRICS == 1) @enumToInt(SYSTEM_PARAMETERS_INFO_ACTION.GETICONMETRICS) else 0)
| (if (o.SETICONMETRICS == 1) @enumToInt(SYSTEM_PARAMETERS_INFO_ACTION.SETICONMETRICS) else 0)
| (if (o.SETWORKAREA == 1) @enumToInt(SYSTEM_PARAMETERS_INFO_ACTION.SETWORKAREA) else 0)
| (if (o.GETWORKAREA == 1) @enumToInt(SYSTEM_PARAMETERS_INFO_ACTION.GETWORKAREA) else 0)
| (if (o.SETPENWINDOWS == 1) @enumToInt(SYSTEM_PARAMETERS_INFO_ACTION.SETPENWINDOWS) else 0)
| (if (o.GETHIGHCONTRAST == 1) @enumToInt(SYSTEM_PARAMETERS_INFO_ACTION.GETHIGHCONTRAST) else 0)
| (if (o.SETHIGHCONTRAST == 1) @enumToInt(SYSTEM_PARAMETERS_INFO_ACTION.SETHIGHCONTRAST) else 0)
| (if (o.GETKEYBOARDPREF == 1) @enumToInt(SYSTEM_PARAMETERS_INFO_ACTION.GETKEYBOARDPREF) else 0)
| (if (o.SETKEYBOARDPREF == 1) @enumToInt(SYSTEM_PARAMETERS_INFO_ACTION.SETKEYBOARDPREF) else 0)
| (if (o.GETSCREENREADER == 1) @enumToInt(SYSTEM_PARAMETERS_INFO_ACTION.GETSCREENREADER) else 0)
| (if (o.SETSCREENREADER == 1) @enumToInt(SYSTEM_PARAMETERS_INFO_ACTION.SETSCREENREADER) else 0)
| (if (o.GETANIMATION == 1) @enumToInt(SYSTEM_PARAMETERS_INFO_ACTION.GETANIMATION) else 0)
| (if (o.SETANIMATION == 1) @enumToInt(SYSTEM_PARAMETERS_INFO_ACTION.SETANIMATION) else 0)
| (if (o.GETFONTSMOOTHING == 1) @enumToInt(SYSTEM_PARAMETERS_INFO_ACTION.GETFONTSMOOTHING) else 0)
| (if (o.SETFONTSMOOTHING == 1) @enumToInt(SYSTEM_PARAMETERS_INFO_ACTION.SETFONTSMOOTHING) else 0)
| (if (o.SETDRAGWIDTH == 1) @enumToInt(SYSTEM_PARAMETERS_INFO_ACTION.SETDRAGWIDTH) else 0)
| (if (o.SETDRAGHEIGHT == 1) @enumToInt(SYSTEM_PARAMETERS_INFO_ACTION.SETDRAGHEIGHT) else 0)
| (if (o.SETHANDHELD == 1) @enumToInt(SYSTEM_PARAMETERS_INFO_ACTION.SETHANDHELD) else 0)
| (if (o.GETLOWPOWERTIMEOUT == 1) @enumToInt(SYSTEM_PARAMETERS_INFO_ACTION.GETLOWPOWERTIMEOUT) else 0)
| (if (o.GETPOWEROFFTIMEOUT == 1) @enumToInt(SYSTEM_PARAMETERS_INFO_ACTION.GETPOWEROFFTIMEOUT) else 0)
| (if (o.SETLOWPOWERTIMEOUT == 1) @enumToInt(SYSTEM_PARAMETERS_INFO_ACTION.SETLOWPOWERTIMEOUT) else 0)
| (if (o.SETPOWEROFFTIMEOUT == 1) @enumToInt(SYSTEM_PARAMETERS_INFO_ACTION.SETPOWEROFFTIMEOUT) else 0)
| (if (o.GETLOWPOWERACTIVE == 1) @enumToInt(SYSTEM_PARAMETERS_INFO_ACTION.GETLOWPOWERACTIVE) else 0)
| (if (o.GETPOWEROFFACTIVE == 1) @enumToInt(SYSTEM_PARAMETERS_INFO_ACTION.GETPOWEROFFACTIVE) else 0)
| (if (o.SETLOWPOWERACTIVE == 1) @enumToInt(SYSTEM_PARAMETERS_INFO_ACTION.SETLOWPOWERACTIVE) else 0)
| (if (o.SETPOWEROFFACTIVE == 1) @enumToInt(SYSTEM_PARAMETERS_INFO_ACTION.SETPOWEROFFACTIVE) else 0)
| (if (o.SETCURSORS == 1) @enumToInt(SYSTEM_PARAMETERS_INFO_ACTION.SETCURSORS) else 0)
| (if (o.SETICONS == 1) @enumToInt(SYSTEM_PARAMETERS_INFO_ACTION.SETICONS) else 0)
| (if (o.GETDEFAULTINPUTLANG == 1) @enumToInt(SYSTEM_PARAMETERS_INFO_ACTION.GETDEFAULTINPUTLANG) else 0)
| (if (o.SETDEFAULTINPUTLANG == 1) @enumToInt(SYSTEM_PARAMETERS_INFO_ACTION.SETDEFAULTINPUTLANG) else 0)
| (if (o.SETLANGTOGGLE == 1) @enumToInt(SYSTEM_PARAMETERS_INFO_ACTION.SETLANGTOGGLE) else 0)
| (if (o.GETWINDOWSEXTENSION == 1) @enumToInt(SYSTEM_PARAMETERS_INFO_ACTION.GETWINDOWSEXTENSION) else 0)
| (if (o.SETMOUSETRAILS == 1) @enumToInt(SYSTEM_PARAMETERS_INFO_ACTION.SETMOUSETRAILS) else 0)
| (if (o.GETMOUSETRAILS == 1) @enumToInt(SYSTEM_PARAMETERS_INFO_ACTION.GETMOUSETRAILS) else 0)
| (if (o.SETSCREENSAVERRUNNING == 1) @enumToInt(SYSTEM_PARAMETERS_INFO_ACTION.SETSCREENSAVERRUNNING) else 0)
| (if (o.GETFILTERKEYS == 1) @enumToInt(SYSTEM_PARAMETERS_INFO_ACTION.GETFILTERKEYS) else 0)
| (if (o.SETFILTERKEYS == 1) @enumToInt(SYSTEM_PARAMETERS_INFO_ACTION.SETFILTERKEYS) else 0)
| (if (o.GETTOGGLEKEYS == 1) @enumToInt(SYSTEM_PARAMETERS_INFO_ACTION.GETTOGGLEKEYS) else 0)
| (if (o.SETTOGGLEKEYS == 1) @enumToInt(SYSTEM_PARAMETERS_INFO_ACTION.SETTOGGLEKEYS) else 0)
| (if (o.GETMOUSEKEYS == 1) @enumToInt(SYSTEM_PARAMETERS_INFO_ACTION.GETMOUSEKEYS) else 0)
| (if (o.SETMOUSEKEYS == 1) @enumToInt(SYSTEM_PARAMETERS_INFO_ACTION.SETMOUSEKEYS) else 0)
| (if (o.GETSHOWSOUNDS == 1) @enumToInt(SYSTEM_PARAMETERS_INFO_ACTION.GETSHOWSOUNDS) else 0)
| (if (o.SETSHOWSOUNDS == 1) @enumToInt(SYSTEM_PARAMETERS_INFO_ACTION.SETSHOWSOUNDS) else 0)
| (if (o.GETSTICKYKEYS == 1) @enumToInt(SYSTEM_PARAMETERS_INFO_ACTION.GETSTICKYKEYS) else 0)
| (if (o.SETSTICKYKEYS == 1) @enumToInt(SYSTEM_PARAMETERS_INFO_ACTION.SETSTICKYKEYS) else 0)
| (if (o.GETACCESSTIMEOUT == 1) @enumToInt(SYSTEM_PARAMETERS_INFO_ACTION.GETACCESSTIMEOUT) else 0)
| (if (o.SETACCESSTIMEOUT == 1) @enumToInt(SYSTEM_PARAMETERS_INFO_ACTION.SETACCESSTIMEOUT) else 0)
| (if (o.GETSERIALKEYS == 1) @enumToInt(SYSTEM_PARAMETERS_INFO_ACTION.GETSERIALKEYS) else 0)
| (if (o.SETSERIALKEYS == 1) @enumToInt(SYSTEM_PARAMETERS_INFO_ACTION.SETSERIALKEYS) else 0)
| (if (o.GETSOUNDSENTRY == 1) @enumToInt(SYSTEM_PARAMETERS_INFO_ACTION.GETSOUNDSENTRY) else 0)
| (if (o.SETSOUNDSENTRY == 1) @enumToInt(SYSTEM_PARAMETERS_INFO_ACTION.SETSOUNDSENTRY) else 0)
| (if (o.GETSNAPTODEFBUTTON == 1) @enumToInt(SYSTEM_PARAMETERS_INFO_ACTION.GETSNAPTODEFBUTTON) else 0)
| (if (o.SETSNAPTODEFBUTTON == 1) @enumToInt(SYSTEM_PARAMETERS_INFO_ACTION.SETSNAPTODEFBUTTON) else 0)
| (if (o.GETMOUSEHOVERWIDTH == 1) @enumToInt(SYSTEM_PARAMETERS_INFO_ACTION.GETMOUSEHOVERWIDTH) else 0)
| (if (o.SETMOUSEHOVERWIDTH == 1) @enumToInt(SYSTEM_PARAMETERS_INFO_ACTION.SETMOUSEHOVERWIDTH) else 0)
| (if (o.GETMOUSEHOVERHEIGHT == 1) @enumToInt(SYSTEM_PARAMETERS_INFO_ACTION.GETMOUSEHOVERHEIGHT) else 0)
| (if (o.SETMOUSEHOVERHEIGHT == 1) @enumToInt(SYSTEM_PARAMETERS_INFO_ACTION.SETMOUSEHOVERHEIGHT) else 0)
| (if (o.GETMOUSEHOVERTIME == 1) @enumToInt(SYSTEM_PARAMETERS_INFO_ACTION.GETMOUSEHOVERTIME) else 0)
| (if (o.SETMOUSEHOVERTIME == 1) @enumToInt(SYSTEM_PARAMETERS_INFO_ACTION.SETMOUSEHOVERTIME) else 0)
| (if (o.GETWHEELSCROLLLINES == 1) @enumToInt(SYSTEM_PARAMETERS_INFO_ACTION.GETWHEELSCROLLLINES) else 0)
| (if (o.SETWHEELSCROLLLINES == 1) @enumToInt(SYSTEM_PARAMETERS_INFO_ACTION.SETWHEELSCROLLLINES) else 0)
| (if (o.GETMENUSHOWDELAY == 1) @enumToInt(SYSTEM_PARAMETERS_INFO_ACTION.GETMENUSHOWDELAY) else 0)
| (if (o.SETMENUSHOWDELAY == 1) @enumToInt(SYSTEM_PARAMETERS_INFO_ACTION.SETMENUSHOWDELAY) else 0)
| (if (o.GETWHEELSCROLLCHARS == 1) @enumToInt(SYSTEM_PARAMETERS_INFO_ACTION.GETWHEELSCROLLCHARS) else 0)
| (if (o.SETWHEELSCROLLCHARS == 1) @enumToInt(SYSTEM_PARAMETERS_INFO_ACTION.SETWHEELSCROLLCHARS) else 0)
| (if (o.GETSHOWIMEUI == 1) @enumToInt(SYSTEM_PARAMETERS_INFO_ACTION.GETSHOWIMEUI) else 0)
| (if (o.SETSHOWIMEUI == 1) @enumToInt(SYSTEM_PARAMETERS_INFO_ACTION.SETSHOWIMEUI) else 0)
| (if (o.GETMOUSESPEED == 1) @enumToInt(SYSTEM_PARAMETERS_INFO_ACTION.GETMOUSESPEED) else 0)
| (if (o.SETMOUSESPEED == 1) @enumToInt(SYSTEM_PARAMETERS_INFO_ACTION.SETMOUSESPEED) else 0)
| (if (o.GETSCREENSAVERRUNNING == 1) @enumToInt(SYSTEM_PARAMETERS_INFO_ACTION.GETSCREENSAVERRUNNING) else 0)
| (if (o.GETDESKWALLPAPER == 1) @enumToInt(SYSTEM_PARAMETERS_INFO_ACTION.GETDESKWALLPAPER) else 0)
| (if (o.GETAUDIODESCRIPTION == 1) @enumToInt(SYSTEM_PARAMETERS_INFO_ACTION.GETAUDIODESCRIPTION) else 0)
| (if (o.SETAUDIODESCRIPTION == 1) @enumToInt(SYSTEM_PARAMETERS_INFO_ACTION.SETAUDIODESCRIPTION) else 0)
| (if (o.GETSCREENSAVESECURE == 1) @enumToInt(SYSTEM_PARAMETERS_INFO_ACTION.GETSCREENSAVESECURE) else 0)
| (if (o.SETSCREENSAVESECURE == 1) @enumToInt(SYSTEM_PARAMETERS_INFO_ACTION.SETSCREENSAVESECURE) else 0)
| (if (o.GETHUNGAPPTIMEOUT == 1) @enumToInt(SYSTEM_PARAMETERS_INFO_ACTION.GETHUNGAPPTIMEOUT) else 0)
| (if (o.SETHUNGAPPTIMEOUT == 1) @enumToInt(SYSTEM_PARAMETERS_INFO_ACTION.SETHUNGAPPTIMEOUT) else 0)
| (if (o.GETWAITTOKILLTIMEOUT == 1) @enumToInt(SYSTEM_PARAMETERS_INFO_ACTION.GETWAITTOKILLTIMEOUT) else 0)
| (if (o.SETWAITTOKILLTIMEOUT == 1) @enumToInt(SYSTEM_PARAMETERS_INFO_ACTION.SETWAITTOKILLTIMEOUT) else 0)
| (if (o.GETWAITTOKILLSERVICETIMEOUT == 1) @enumToInt(SYSTEM_PARAMETERS_INFO_ACTION.GETWAITTOKILLSERVICETIMEOUT) else 0)
| (if (o.SETWAITTOKILLSERVICETIMEOUT == 1) @enumToInt(SYSTEM_PARAMETERS_INFO_ACTION.SETWAITTOKILLSERVICETIMEOUT) else 0)
| (if (o.GETMOUSEDOCKTHRESHOLD == 1) @enumToInt(SYSTEM_PARAMETERS_INFO_ACTION.GETMOUSEDOCKTHRESHOLD) else 0)
| (if (o.SETMOUSEDOCKTHRESHOLD == 1) @enumToInt(SYSTEM_PARAMETERS_INFO_ACTION.SETMOUSEDOCKTHRESHOLD) else 0)
| (if (o.GETPENDOCKTHRESHOLD == 1) @enumToInt(SYSTEM_PARAMETERS_INFO_ACTION.GETPENDOCKTHRESHOLD) else 0)
| (if (o.SETPENDOCKTHRESHOLD == 1) @enumToInt(SYSTEM_PARAMETERS_INFO_ACTION.SETPENDOCKTHRESHOLD) else 0)
| (if (o.GETWINARRANGING == 1) @enumToInt(SYSTEM_PARAMETERS_INFO_ACTION.GETWINARRANGING) else 0)
| (if (o.SETWINARRANGING == 1) @enumToInt(SYSTEM_PARAMETERS_INFO_ACTION.SETWINARRANGING) else 0)
| (if (o.GETMOUSEDRAGOUTTHRESHOLD == 1) @enumToInt(SYSTEM_PARAMETERS_INFO_ACTION.GETMOUSEDRAGOUTTHRESHOLD) else 0)
| (if (o.SETMOUSEDRAGOUTTHRESHOLD == 1) @enumToInt(SYSTEM_PARAMETERS_INFO_ACTION.SETMOUSEDRAGOUTTHRESHOLD) else 0)
| (if (o.GETPENDRAGOUTTHRESHOLD == 1) @enumToInt(SYSTEM_PARAMETERS_INFO_ACTION.GETPENDRAGOUTTHRESHOLD) else 0)
| (if (o.SETPENDRAGOUTTHRESHOLD == 1) @enumToInt(SYSTEM_PARAMETERS_INFO_ACTION.SETPENDRAGOUTTHRESHOLD) else 0)
| (if (o.GETMOUSESIDEMOVETHRESHOLD == 1) @enumToInt(SYSTEM_PARAMETERS_INFO_ACTION.GETMOUSESIDEMOVETHRESHOLD) else 0)
| (if (o.SETMOUSESIDEMOVETHRESHOLD == 1) @enumToInt(SYSTEM_PARAMETERS_INFO_ACTION.SETMOUSESIDEMOVETHRESHOLD) else 0)
| (if (o.GETPENSIDEMOVETHRESHOLD == 1) @enumToInt(SYSTEM_PARAMETERS_INFO_ACTION.GETPENSIDEMOVETHRESHOLD) else 0)
| (if (o.SETPENSIDEMOVETHRESHOLD == 1) @enumToInt(SYSTEM_PARAMETERS_INFO_ACTION.SETPENSIDEMOVETHRESHOLD) else 0)
| (if (o.GETDRAGFROMMAXIMIZE == 1) @enumToInt(SYSTEM_PARAMETERS_INFO_ACTION.GETDRAGFROMMAXIMIZE) else 0)
| (if (o.SETDRAGFROMMAXIMIZE == 1) @enumToInt(SYSTEM_PARAMETERS_INFO_ACTION.SETDRAGFROMMAXIMIZE) else 0)
| (if (o.GETSNAPSIZING == 1) @enumToInt(SYSTEM_PARAMETERS_INFO_ACTION.GETSNAPSIZING) else 0)
| (if (o.SETSNAPSIZING == 1) @enumToInt(SYSTEM_PARAMETERS_INFO_ACTION.SETSNAPSIZING) else 0)
| (if (o.GETDOCKMOVING == 1) @enumToInt(SYSTEM_PARAMETERS_INFO_ACTION.GETDOCKMOVING) else 0)
| (if (o.SETDOCKMOVING == 1) @enumToInt(SYSTEM_PARAMETERS_INFO_ACTION.SETDOCKMOVING) else 0)
| (if (o.GETTOUCHPREDICTIONPARAMETERS == 1) @enumToInt(SYSTEM_PARAMETERS_INFO_ACTION.GETTOUCHPREDICTIONPARAMETERS) else 0)
| (if (o.SETTOUCHPREDICTIONPARAMETERS == 1) @enumToInt(SYSTEM_PARAMETERS_INFO_ACTION.SETTOUCHPREDICTIONPARAMETERS) else 0)
| (if (o.GETLOGICALDPIOVERRIDE == 1) @enumToInt(SYSTEM_PARAMETERS_INFO_ACTION.GETLOGICALDPIOVERRIDE) else 0)
| (if (o.SETLOGICALDPIOVERRIDE == 1) @enumToInt(SYSTEM_PARAMETERS_INFO_ACTION.SETLOGICALDPIOVERRIDE) else 0)
| (if (o.GETMENURECT == 1) @enumToInt(SYSTEM_PARAMETERS_INFO_ACTION.GETMENURECT) else 0)
| (if (o.SETMENURECT == 1) @enumToInt(SYSTEM_PARAMETERS_INFO_ACTION.SETMENURECT) else 0)
| (if (o.GETACTIVEWINDOWTRACKING == 1) @enumToInt(SYSTEM_PARAMETERS_INFO_ACTION.GETACTIVEWINDOWTRACKING) else 0)
| (if (o.SETACTIVEWINDOWTRACKING == 1) @enumToInt(SYSTEM_PARAMETERS_INFO_ACTION.SETACTIVEWINDOWTRACKING) else 0)
| (if (o.GETMENUANIMATION == 1) @enumToInt(SYSTEM_PARAMETERS_INFO_ACTION.GETMENUANIMATION) else 0)
| (if (o.SETMENUANIMATION == 1) @enumToInt(SYSTEM_PARAMETERS_INFO_ACTION.SETMENUANIMATION) else 0)
| (if (o.GETCOMBOBOXANIMATION == 1) @enumToInt(SYSTEM_PARAMETERS_INFO_ACTION.GETCOMBOBOXANIMATION) else 0)
| (if (o.SETCOMBOBOXANIMATION == 1) @enumToInt(SYSTEM_PARAMETERS_INFO_ACTION.SETCOMBOBOXANIMATION) else 0)
| (if (o.GETLISTBOXSMOOTHSCROLLING == 1) @enumToInt(SYSTEM_PARAMETERS_INFO_ACTION.GETLISTBOXSMOOTHSCROLLING) else 0)
| (if (o.SETLISTBOXSMOOTHSCROLLING == 1) @enumToInt(SYSTEM_PARAMETERS_INFO_ACTION.SETLISTBOXSMOOTHSCROLLING) else 0)
| (if (o.GETGRADIENTCAPTIONS == 1) @enumToInt(SYSTEM_PARAMETERS_INFO_ACTION.GETGRADIENTCAPTIONS) else 0)
| (if (o.SETGRADIENTCAPTIONS == 1) @enumToInt(SYSTEM_PARAMETERS_INFO_ACTION.SETGRADIENTCAPTIONS) else 0)
| (if (o.GETKEYBOARDCUES == 1) @enumToInt(SYSTEM_PARAMETERS_INFO_ACTION.GETKEYBOARDCUES) else 0)
| (if (o.SETKEYBOARDCUES == 1) @enumToInt(SYSTEM_PARAMETERS_INFO_ACTION.SETKEYBOARDCUES) else 0)
| (if (o.GETACTIVEWNDTRKZORDER == 1) @enumToInt(SYSTEM_PARAMETERS_INFO_ACTION.GETACTIVEWNDTRKZORDER) else 0)
| (if (o.SETACTIVEWNDTRKZORDER == 1) @enumToInt(SYSTEM_PARAMETERS_INFO_ACTION.SETACTIVEWNDTRKZORDER) else 0)
| (if (o.GETHOTTRACKING == 1) @enumToInt(SYSTEM_PARAMETERS_INFO_ACTION.GETHOTTRACKING) else 0)
| (if (o.SETHOTTRACKING == 1) @enumToInt(SYSTEM_PARAMETERS_INFO_ACTION.SETHOTTRACKING) else 0)
| (if (o.GETMENUFADE == 1) @enumToInt(SYSTEM_PARAMETERS_INFO_ACTION.GETMENUFADE) else 0)
| (if (o.SETMENUFADE == 1) @enumToInt(SYSTEM_PARAMETERS_INFO_ACTION.SETMENUFADE) else 0)
| (if (o.GETSELECTIONFADE == 1) @enumToInt(SYSTEM_PARAMETERS_INFO_ACTION.GETSELECTIONFADE) else 0)
| (if (o.SETSELECTIONFADE == 1) @enumToInt(SYSTEM_PARAMETERS_INFO_ACTION.SETSELECTIONFADE) else 0)
| (if (o.GETTOOLTIPANIMATION == 1) @enumToInt(SYSTEM_PARAMETERS_INFO_ACTION.GETTOOLTIPANIMATION) else 0)
| (if (o.SETTOOLTIPANIMATION == 1) @enumToInt(SYSTEM_PARAMETERS_INFO_ACTION.SETTOOLTIPANIMATION) else 0)
| (if (o.GETTOOLTIPFADE == 1) @enumToInt(SYSTEM_PARAMETERS_INFO_ACTION.GETTOOLTIPFADE) else 0)
| (if (o.SETTOOLTIPFADE == 1) @enumToInt(SYSTEM_PARAMETERS_INFO_ACTION.SETTOOLTIPFADE) else 0)
| (if (o.GETCURSORSHADOW == 1) @enumToInt(SYSTEM_PARAMETERS_INFO_ACTION.GETCURSORSHADOW) else 0)
| (if (o.SETCURSORSHADOW == 1) @enumToInt(SYSTEM_PARAMETERS_INFO_ACTION.SETCURSORSHADOW) else 0)
| (if (o.GETMOUSESONAR == 1) @enumToInt(SYSTEM_PARAMETERS_INFO_ACTION.GETMOUSESONAR) else 0)
| (if (o.SETMOUSESONAR == 1) @enumToInt(SYSTEM_PARAMETERS_INFO_ACTION.SETMOUSESONAR) else 0)
| (if (o.GETMOUSECLICKLOCK == 1) @enumToInt(SYSTEM_PARAMETERS_INFO_ACTION.GETMOUSECLICKLOCK) else 0)
| (if (o.SETMOUSECLICKLOCK == 1) @enumToInt(SYSTEM_PARAMETERS_INFO_ACTION.SETMOUSECLICKLOCK) else 0)
| (if (o.GETMOUSEVANISH == 1) @enumToInt(SYSTEM_PARAMETERS_INFO_ACTION.GETMOUSEVANISH) else 0)
| (if (o.SETMOUSEVANISH == 1) @enumToInt(SYSTEM_PARAMETERS_INFO_ACTION.SETMOUSEVANISH) else 0)
| (if (o.GETFLATMENU == 1) @enumToInt(SYSTEM_PARAMETERS_INFO_ACTION.GETFLATMENU) else 0)
| (if (o.SETFLATMENU == 1) @enumToInt(SYSTEM_PARAMETERS_INFO_ACTION.SETFLATMENU) else 0)
| (if (o.GETDROPSHADOW == 1) @enumToInt(SYSTEM_PARAMETERS_INFO_ACTION.GETDROPSHADOW) else 0)
| (if (o.SETDROPSHADOW == 1) @enumToInt(SYSTEM_PARAMETERS_INFO_ACTION.SETDROPSHADOW) else 0)
| (if (o.GETBLOCKSENDINPUTRESETS == 1) @enumToInt(SYSTEM_PARAMETERS_INFO_ACTION.GETBLOCKSENDINPUTRESETS) else 0)
| (if (o.SETBLOCKSENDINPUTRESETS == 1) @enumToInt(SYSTEM_PARAMETERS_INFO_ACTION.SETBLOCKSENDINPUTRESETS) else 0)
| (if (o.GETUIEFFECTS == 1) @enumToInt(SYSTEM_PARAMETERS_INFO_ACTION.GETUIEFFECTS) else 0)
| (if (o.SETUIEFFECTS == 1) @enumToInt(SYSTEM_PARAMETERS_INFO_ACTION.SETUIEFFECTS) else 0)
| (if (o.GETDISABLEOVERLAPPEDCONTENT == 1) @enumToInt(SYSTEM_PARAMETERS_INFO_ACTION.GETDISABLEOVERLAPPEDCONTENT) else 0)
| (if (o.SETDISABLEOVERLAPPEDCONTENT == 1) @enumToInt(SYSTEM_PARAMETERS_INFO_ACTION.SETDISABLEOVERLAPPEDCONTENT) else 0)
| (if (o.GETCLIENTAREAANIMATION == 1) @enumToInt(SYSTEM_PARAMETERS_INFO_ACTION.GETCLIENTAREAANIMATION) else 0)
| (if (o.SETCLIENTAREAANIMATION == 1) @enumToInt(SYSTEM_PARAMETERS_INFO_ACTION.SETCLIENTAREAANIMATION) else 0)
| (if (o.GETCLEARTYPE == 1) @enumToInt(SYSTEM_PARAMETERS_INFO_ACTION.GETCLEARTYPE) else 0)
| (if (o.SETCLEARTYPE == 1) @enumToInt(SYSTEM_PARAMETERS_INFO_ACTION.SETCLEARTYPE) else 0)
| (if (o.GETSPEECHRECOGNITION == 1) @enumToInt(SYSTEM_PARAMETERS_INFO_ACTION.GETSPEECHRECOGNITION) else 0)
| (if (o.SETSPEECHRECOGNITION == 1) @enumToInt(SYSTEM_PARAMETERS_INFO_ACTION.SETSPEECHRECOGNITION) else 0)
| (if (o.GETCARETBROWSING == 1) @enumToInt(SYSTEM_PARAMETERS_INFO_ACTION.GETCARETBROWSING) else 0)
| (if (o.SETCARETBROWSING == 1) @enumToInt(SYSTEM_PARAMETERS_INFO_ACTION.SETCARETBROWSING) else 0)
| (if (o.GETTHREADLOCALINPUTSETTINGS == 1) @enumToInt(SYSTEM_PARAMETERS_INFO_ACTION.GETTHREADLOCALINPUTSETTINGS) else 0)
| (if (o.SETTHREADLOCALINPUTSETTINGS == 1) @enumToInt(SYSTEM_PARAMETERS_INFO_ACTION.SETTHREADLOCALINPUTSETTINGS) else 0)
| (if (o.GETSYSTEMLANGUAGEBAR == 1) @enumToInt(SYSTEM_PARAMETERS_INFO_ACTION.GETSYSTEMLANGUAGEBAR) else 0)
| (if (o.SETSYSTEMLANGUAGEBAR == 1) @enumToInt(SYSTEM_PARAMETERS_INFO_ACTION.SETSYSTEMLANGUAGEBAR) else 0)
| (if (o.GETFOREGROUNDLOCKTIMEOUT == 1) @enumToInt(SYSTEM_PARAMETERS_INFO_ACTION.GETFOREGROUNDLOCKTIMEOUT) else 0)
| (if (o.SETFOREGROUNDLOCKTIMEOUT == 1) @enumToInt(SYSTEM_PARAMETERS_INFO_ACTION.SETFOREGROUNDLOCKTIMEOUT) else 0)
| (if (o.GETACTIVEWNDTRKTIMEOUT == 1) @enumToInt(SYSTEM_PARAMETERS_INFO_ACTION.GETACTIVEWNDTRKTIMEOUT) else 0)
| (if (o.SETACTIVEWNDTRKTIMEOUT == 1) @enumToInt(SYSTEM_PARAMETERS_INFO_ACTION.SETACTIVEWNDTRKTIMEOUT) else 0)
| (if (o.GETFOREGROUNDFLASHCOUNT == 1) @enumToInt(SYSTEM_PARAMETERS_INFO_ACTION.GETFOREGROUNDFLASHCOUNT) else 0)
| (if (o.SETFOREGROUNDFLASHCOUNT == 1) @enumToInt(SYSTEM_PARAMETERS_INFO_ACTION.SETFOREGROUNDFLASHCOUNT) else 0)
| (if (o.GETCARETWIDTH == 1) @enumToInt(SYSTEM_PARAMETERS_INFO_ACTION.GETCARETWIDTH) else 0)
| (if (o.SETCARETWIDTH == 1) @enumToInt(SYSTEM_PARAMETERS_INFO_ACTION.SETCARETWIDTH) else 0)
| (if (o.GETMOUSECLICKLOCKTIME == 1) @enumToInt(SYSTEM_PARAMETERS_INFO_ACTION.GETMOUSECLICKLOCKTIME) else 0)
| (if (o.SETMOUSECLICKLOCKTIME == 1) @enumToInt(SYSTEM_PARAMETERS_INFO_ACTION.SETMOUSECLICKLOCKTIME) else 0)
| (if (o.GETFONTSMOOTHINGTYPE == 1) @enumToInt(SYSTEM_PARAMETERS_INFO_ACTION.GETFONTSMOOTHINGTYPE) else 0)
| (if (o.SETFONTSMOOTHINGTYPE == 1) @enumToInt(SYSTEM_PARAMETERS_INFO_ACTION.SETFONTSMOOTHINGTYPE) else 0)
| (if (o.GETFONTSMOOTHINGCONTRAST == 1) @enumToInt(SYSTEM_PARAMETERS_INFO_ACTION.GETFONTSMOOTHINGCONTRAST) else 0)
| (if (o.SETFONTSMOOTHINGCONTRAST == 1) @enumToInt(SYSTEM_PARAMETERS_INFO_ACTION.SETFONTSMOOTHINGCONTRAST) else 0)
| (if (o.GETFOCUSBORDERWIDTH == 1) @enumToInt(SYSTEM_PARAMETERS_INFO_ACTION.GETFOCUSBORDERWIDTH) else 0)
| (if (o.SETFOCUSBORDERWIDTH == 1) @enumToInt(SYSTEM_PARAMETERS_INFO_ACTION.SETFOCUSBORDERWIDTH) else 0)
| (if (o.GETFOCUSBORDERHEIGHT == 1) @enumToInt(SYSTEM_PARAMETERS_INFO_ACTION.GETFOCUSBORDERHEIGHT) else 0)
| (if (o.SETFOCUSBORDERHEIGHT == 1) @enumToInt(SYSTEM_PARAMETERS_INFO_ACTION.SETFOCUSBORDERHEIGHT) else 0)
| (if (o.GETFONTSMOOTHINGORIENTATION == 1) @enumToInt(SYSTEM_PARAMETERS_INFO_ACTION.GETFONTSMOOTHINGORIENTATION) else 0)
| (if (o.SETFONTSMOOTHINGORIENTATION == 1) @enumToInt(SYSTEM_PARAMETERS_INFO_ACTION.SETFONTSMOOTHINGORIENTATION) else 0)
| (if (o.GETMINIMUMHITRADIUS == 1) @enumToInt(SYSTEM_PARAMETERS_INFO_ACTION.GETMINIMUMHITRADIUS) else 0)
| (if (o.SETMINIMUMHITRADIUS == 1) @enumToInt(SYSTEM_PARAMETERS_INFO_ACTION.SETMINIMUMHITRADIUS) else 0)
| (if (o.GETMESSAGEDURATION == 1) @enumToInt(SYSTEM_PARAMETERS_INFO_ACTION.GETMESSAGEDURATION) else 0)
| (if (o.SETMESSAGEDURATION == 1) @enumToInt(SYSTEM_PARAMETERS_INFO_ACTION.SETMESSAGEDURATION) else 0)
| (if (o.GETCONTACTVISUALIZATION == 1) @enumToInt(SYSTEM_PARAMETERS_INFO_ACTION.GETCONTACTVISUALIZATION) else 0)
| (if (o.SETCONTACTVISUALIZATION == 1) @enumToInt(SYSTEM_PARAMETERS_INFO_ACTION.SETCONTACTVISUALIZATION) else 0)
| (if (o.GETGESTUREVISUALIZATION == 1) @enumToInt(SYSTEM_PARAMETERS_INFO_ACTION.GETGESTUREVISUALIZATION) else 0)
| (if (o.SETGESTUREVISUALIZATION == 1) @enumToInt(SYSTEM_PARAMETERS_INFO_ACTION.SETGESTUREVISUALIZATION) else 0)
| (if (o.GETMOUSEWHEELROUTING == 1) @enumToInt(SYSTEM_PARAMETERS_INFO_ACTION.GETMOUSEWHEELROUTING) else 0)
| (if (o.SETMOUSEWHEELROUTING == 1) @enumToInt(SYSTEM_PARAMETERS_INFO_ACTION.SETMOUSEWHEELROUTING) else 0)
| (if (o.GETPENVISUALIZATION == 1) @enumToInt(SYSTEM_PARAMETERS_INFO_ACTION.GETPENVISUALIZATION) else 0)
| (if (o.SETPENVISUALIZATION == 1) @enumToInt(SYSTEM_PARAMETERS_INFO_ACTION.SETPENVISUALIZATION) else 0)
| (if (o.GETPENARBITRATIONTYPE == 1) @enumToInt(SYSTEM_PARAMETERS_INFO_ACTION.GETPENARBITRATIONTYPE) else 0)
| (if (o.SETPENARBITRATIONTYPE == 1) @enumToInt(SYSTEM_PARAMETERS_INFO_ACTION.SETPENARBITRATIONTYPE) else 0)
| (if (o.GETCARETTIMEOUT == 1) @enumToInt(SYSTEM_PARAMETERS_INFO_ACTION.GETCARETTIMEOUT) else 0)
| (if (o.SETCARETTIMEOUT == 1) @enumToInt(SYSTEM_PARAMETERS_INFO_ACTION.SETCARETTIMEOUT) else 0)
| (if (o.GETHANDEDNESS == 1) @enumToInt(SYSTEM_PARAMETERS_INFO_ACTION.GETHANDEDNESS) else 0)
| (if (o.SETHANDEDNESS == 1) @enumToInt(SYSTEM_PARAMETERS_INFO_ACTION.SETHANDEDNESS) else 0)
);
}
};
pub const SPI_GETBEEP = SYSTEM_PARAMETERS_INFO_ACTION.GETBEEP;
pub const SPI_SETBEEP = SYSTEM_PARAMETERS_INFO_ACTION.SETBEEP;
pub const SPI_GETMOUSE = SYSTEM_PARAMETERS_INFO_ACTION.GETMOUSE;
pub const SPI_SETMOUSE = SYSTEM_PARAMETERS_INFO_ACTION.SETMOUSE;
pub const SPI_GETBORDER = SYSTEM_PARAMETERS_INFO_ACTION.GETBORDER;
pub const SPI_SETBORDER = SYSTEM_PARAMETERS_INFO_ACTION.SETBORDER;
pub const SPI_GETKEYBOARDSPEED = SYSTEM_PARAMETERS_INFO_ACTION.GETKEYBOARDSPEED;
pub const SPI_SETKEYBOARDSPEED = SYSTEM_PARAMETERS_INFO_ACTION.SETKEYBOARDSPEED;
pub const SPI_LANGDRIVER = SYSTEM_PARAMETERS_INFO_ACTION.LANGDRIVER;
pub const SPI_ICONHORIZONTALSPACING = SYSTEM_PARAMETERS_INFO_ACTION.ICONHORIZONTALSPACING;
pub const SPI_GETSCREENSAVETIMEOUT = SYSTEM_PARAMETERS_INFO_ACTION.GETSCREENSAVETIMEOUT;
pub const SPI_SETSCREENSAVETIMEOUT = SYSTEM_PARAMETERS_INFO_ACTION.SETSCREENSAVETIMEOUT;
pub const SPI_GETSCREENSAVEACTIVE = SYSTEM_PARAMETERS_INFO_ACTION.GETSCREENSAVEACTIVE;
pub const SPI_SETSCREENSAVEACTIVE = SYSTEM_PARAMETERS_INFO_ACTION.SETSCREENSAVEACTIVE;
pub const SPI_GETGRIDGRANULARITY = SYSTEM_PARAMETERS_INFO_ACTION.GETGRIDGRANULARITY;
pub const SPI_SETGRIDGRANULARITY = SYSTEM_PARAMETERS_INFO_ACTION.SETGRIDGRANULARITY;
pub const SPI_SETDESKWALLPAPER = SYSTEM_PARAMETERS_INFO_ACTION.SETDESKWALLPAPER;
pub const SPI_SETDESKPATTERN = SYSTEM_PARAMETERS_INFO_ACTION.SETDESKPATTERN;
pub const SPI_GETKEYBOARDDELAY = SYSTEM_PARAMETERS_INFO_ACTION.GETKEYBOARDDELAY;
pub const SPI_SETKEYBOARDDELAY = SYSTEM_PARAMETERS_INFO_ACTION.SETKEYBOARDDELAY;
pub const SPI_ICONVERTICALSPACING = SYSTEM_PARAMETERS_INFO_ACTION.ICONVERTICALSPACING;
pub const SPI_GETICONTITLEWRAP = SYSTEM_PARAMETERS_INFO_ACTION.GETICONTITLEWRAP;
pub const SPI_SETICONTITLEWRAP = SYSTEM_PARAMETERS_INFO_ACTION.SETICONTITLEWRAP;
pub const SPI_GETMENUDROPALIGNMENT = SYSTEM_PARAMETERS_INFO_ACTION.GETMENUDROPALIGNMENT;
pub const SPI_SETMENUDROPALIGNMENT = SYSTEM_PARAMETERS_INFO_ACTION.SETMENUDROPALIGNMENT;
pub const SPI_SETDOUBLECLKWIDTH = SYSTEM_PARAMETERS_INFO_ACTION.SETDOUBLECLKWIDTH;
pub const SPI_SETDOUBLECLKHEIGHT = SYSTEM_PARAMETERS_INFO_ACTION.SETDOUBLECLKHEIGHT;
pub const SPI_GETICONTITLELOGFONT = SYSTEM_PARAMETERS_INFO_ACTION.GETICONTITLELOGFONT;
pub const SPI_SETDOUBLECLICKTIME = SYSTEM_PARAMETERS_INFO_ACTION.SETDOUBLECLICKTIME;
pub const SPI_SETMOUSEBUTTONSWAP = SYSTEM_PARAMETERS_INFO_ACTION.SETMOUSEBUTTONSWAP;
pub const SPI_SETICONTITLELOGFONT = SYSTEM_PARAMETERS_INFO_ACTION.SETICONTITLELOGFONT;
pub const SPI_GETFASTTASKSWITCH = SYSTEM_PARAMETERS_INFO_ACTION.GETFASTTASKSWITCH;
pub const SPI_SETFASTTASKSWITCH = SYSTEM_PARAMETERS_INFO_ACTION.SETFASTTASKSWITCH;
pub const SPI_SETDRAGFULLWINDOWS = SYSTEM_PARAMETERS_INFO_ACTION.SETDRAGFULLWINDOWS;
pub const SPI_GETDRAGFULLWINDOWS = SYSTEM_PARAMETERS_INFO_ACTION.GETDRAGFULLWINDOWS;
pub const SPI_GETNONCLIENTMETRICS = SYSTEM_PARAMETERS_INFO_ACTION.GETNONCLIENTMETRICS;
pub const SPI_SETNONCLIENTMETRICS = SYSTEM_PARAMETERS_INFO_ACTION.SETNONCLIENTMETRICS;
pub const SPI_GETMINIMIZEDMETRICS = SYSTEM_PARAMETERS_INFO_ACTION.GETMINIMIZEDMETRICS;
pub const SPI_SETMINIMIZEDMETRICS = SYSTEM_PARAMETERS_INFO_ACTION.SETMINIMIZEDMETRICS;
pub const SPI_GETICONMETRICS = SYSTEM_PARAMETERS_INFO_ACTION.GETICONMETRICS;
pub const SPI_SETICONMETRICS = SYSTEM_PARAMETERS_INFO_ACTION.SETICONMETRICS;
pub const SPI_SETWORKAREA = SYSTEM_PARAMETERS_INFO_ACTION.SETWORKAREA;
pub const SPI_GETWORKAREA = SYSTEM_PARAMETERS_INFO_ACTION.GETWORKAREA;
pub const SPI_SETPENWINDOWS = SYSTEM_PARAMETERS_INFO_ACTION.SETPENWINDOWS;
pub const SPI_GETHIGHCONTRAST = SYSTEM_PARAMETERS_INFO_ACTION.GETHIGHCONTRAST;
pub const SPI_SETHIGHCONTRAST = SYSTEM_PARAMETERS_INFO_ACTION.SETHIGHCONTRAST;
pub const SPI_GETKEYBOARDPREF = SYSTEM_PARAMETERS_INFO_ACTION.GETKEYBOARDPREF;
pub const SPI_SETKEYBOARDPREF = SYSTEM_PARAMETERS_INFO_ACTION.SETKEYBOARDPREF;
pub const SPI_GETSCREENREADER = SYSTEM_PARAMETERS_INFO_ACTION.GETSCREENREADER;
pub const SPI_SETSCREENREADER = SYSTEM_PARAMETERS_INFO_ACTION.SETSCREENREADER;
pub const SPI_GETANIMATION = SYSTEM_PARAMETERS_INFO_ACTION.GETANIMATION;
pub const SPI_SETANIMATION = SYSTEM_PARAMETERS_INFO_ACTION.SETANIMATION;
pub const SPI_GETFONTSMOOTHING = SYSTEM_PARAMETERS_INFO_ACTION.GETFONTSMOOTHING;
pub const SPI_SETFONTSMOOTHING = SYSTEM_PARAMETERS_INFO_ACTION.SETFONTSMOOTHING;
pub const SPI_SETDRAGWIDTH = SYSTEM_PARAMETERS_INFO_ACTION.SETDRAGWIDTH;
pub const SPI_SETDRAGHEIGHT = SYSTEM_PARAMETERS_INFO_ACTION.SETDRAGHEIGHT;
pub const SPI_SETHANDHELD = SYSTEM_PARAMETERS_INFO_ACTION.SETHANDHELD;
pub const SPI_GETLOWPOWERTIMEOUT = SYSTEM_PARAMETERS_INFO_ACTION.GETLOWPOWERTIMEOUT;
pub const SPI_GETPOWEROFFTIMEOUT = SYSTEM_PARAMETERS_INFO_ACTION.GETPOWEROFFTIMEOUT;
pub const SPI_SETLOWPOWERTIMEOUT = SYSTEM_PARAMETERS_INFO_ACTION.SETLOWPOWERTIMEOUT;
pub const SPI_SETPOWEROFFTIMEOUT = SYSTEM_PARAMETERS_INFO_ACTION.SETPOWEROFFTIMEOUT;
pub const SPI_GETLOWPOWERACTIVE = SYSTEM_PARAMETERS_INFO_ACTION.GETLOWPOWERACTIVE;
pub const SPI_GETPOWEROFFACTIVE = SYSTEM_PARAMETERS_INFO_ACTION.GETPOWEROFFACTIVE;
pub const SPI_SETLOWPOWERACTIVE = SYSTEM_PARAMETERS_INFO_ACTION.SETLOWPOWERACTIVE;
pub const SPI_SETPOWEROFFACTIVE = SYSTEM_PARAMETERS_INFO_ACTION.SETPOWEROFFACTIVE;
pub const SPI_SETCURSORS = SYSTEM_PARAMETERS_INFO_ACTION.SETCURSORS;
pub const SPI_SETICONS = SYSTEM_PARAMETERS_INFO_ACTION.SETICONS;
pub const SPI_GETDEFAULTINPUTLANG = SYSTEM_PARAMETERS_INFO_ACTION.GETDEFAULTINPUTLANG;
pub const SPI_SETDEFAULTINPUTLANG = SYSTEM_PARAMETERS_INFO_ACTION.SETDEFAULTINPUTLANG;
pub const SPI_SETLANGTOGGLE = SYSTEM_PARAMETERS_INFO_ACTION.SETLANGTOGGLE;
pub const SPI_GETWINDOWSEXTENSION = SYSTEM_PARAMETERS_INFO_ACTION.GETWINDOWSEXTENSION;
pub const SPI_SETMOUSETRAILS = SYSTEM_PARAMETERS_INFO_ACTION.SETMOUSETRAILS;
pub const SPI_GETMOUSETRAILS = SYSTEM_PARAMETERS_INFO_ACTION.GETMOUSETRAILS;
pub const SPI_SETSCREENSAVERRUNNING = SYSTEM_PARAMETERS_INFO_ACTION.SETSCREENSAVERRUNNING;
pub const SPI_SCREENSAVERRUNNING = SYSTEM_PARAMETERS_INFO_ACTION.SETSCREENSAVERRUNNING;
pub const SPI_GETFILTERKEYS = SYSTEM_PARAMETERS_INFO_ACTION.GETFILTERKEYS;
pub const SPI_SETFILTERKEYS = SYSTEM_PARAMETERS_INFO_ACTION.SETFILTERKEYS;
pub const SPI_GETTOGGLEKEYS = SYSTEM_PARAMETERS_INFO_ACTION.GETTOGGLEKEYS;
pub const SPI_SETTOGGLEKEYS = SYSTEM_PARAMETERS_INFO_ACTION.SETTOGGLEKEYS;
pub const SPI_GETMOUSEKEYS = SYSTEM_PARAMETERS_INFO_ACTION.GETMOUSEKEYS;
pub const SPI_SETMOUSEKEYS = SYSTEM_PARAMETERS_INFO_ACTION.SETMOUSEKEYS;
pub const SPI_GETSHOWSOUNDS = SYSTEM_PARAMETERS_INFO_ACTION.GETSHOWSOUNDS;
pub const SPI_SETSHOWSOUNDS = SYSTEM_PARAMETERS_INFO_ACTION.SETSHOWSOUNDS;
pub const SPI_GETSTICKYKEYS = SYSTEM_PARAMETERS_INFO_ACTION.GETSTICKYKEYS;
pub const SPI_SETSTICKYKEYS = SYSTEM_PARAMETERS_INFO_ACTION.SETSTICKYKEYS;
pub const SPI_GETACCESSTIMEOUT = SYSTEM_PARAMETERS_INFO_ACTION.GETACCESSTIMEOUT;
pub const SPI_SETACCESSTIMEOUT = SYSTEM_PARAMETERS_INFO_ACTION.SETACCESSTIMEOUT;
pub const SPI_GETSERIALKEYS = SYSTEM_PARAMETERS_INFO_ACTION.GETSERIALKEYS;
pub const SPI_SETSERIALKEYS = SYSTEM_PARAMETERS_INFO_ACTION.SETSERIALKEYS;
pub const SPI_GETSOUNDSENTRY = SYSTEM_PARAMETERS_INFO_ACTION.GETSOUNDSENTRY;
pub const SPI_SETSOUNDSENTRY = SYSTEM_PARAMETERS_INFO_ACTION.SETSOUNDSENTRY;
pub const SPI_GETSNAPTODEFBUTTON = SYSTEM_PARAMETERS_INFO_ACTION.GETSNAPTODEFBUTTON;
pub const SPI_SETSNAPTODEFBUTTON = SYSTEM_PARAMETERS_INFO_ACTION.SETSNAPTODEFBUTTON;
pub const SPI_GETMOUSEHOVERWIDTH = SYSTEM_PARAMETERS_INFO_ACTION.GETMOUSEHOVERWIDTH;
pub const SPI_SETMOUSEHOVERWIDTH = SYSTEM_PARAMETERS_INFO_ACTION.SETMOUSEHOVERWIDTH;
pub const SPI_GETMOUSEHOVERHEIGHT = SYSTEM_PARAMETERS_INFO_ACTION.GETMOUSEHOVERHEIGHT;
pub const SPI_SETMOUSEHOVERHEIGHT = SYSTEM_PARAMETERS_INFO_ACTION.SETMOUSEHOVERHEIGHT;
pub const SPI_GETMOUSEHOVERTIME = SYSTEM_PARAMETERS_INFO_ACTION.GETMOUSEHOVERTIME;
pub const SPI_SETMOUSEHOVERTIME = SYSTEM_PARAMETERS_INFO_ACTION.SETMOUSEHOVERTIME;
pub const SPI_GETWHEELSCROLLLINES = SYSTEM_PARAMETERS_INFO_ACTION.GETWHEELSCROLLLINES;
pub const SPI_SETWHEELSCROLLLINES = SYSTEM_PARAMETERS_INFO_ACTION.SETWHEELSCROLLLINES;
pub const SPI_GETMENUSHOWDELAY = SYSTEM_PARAMETERS_INFO_ACTION.GETMENUSHOWDELAY;
pub const SPI_SETMENUSHOWDELAY = SYSTEM_PARAMETERS_INFO_ACTION.SETMENUSHOWDELAY;
pub const SPI_GETWHEELSCROLLCHARS = SYSTEM_PARAMETERS_INFO_ACTION.GETWHEELSCROLLCHARS;
pub const SPI_SETWHEELSCROLLCHARS = SYSTEM_PARAMETERS_INFO_ACTION.SETWHEELSCROLLCHARS;
pub const SPI_GETSHOWIMEUI = SYSTEM_PARAMETERS_INFO_ACTION.GETSHOWIMEUI;
pub const SPI_SETSHOWIMEUI = SYSTEM_PARAMETERS_INFO_ACTION.SETSHOWIMEUI;
pub const SPI_GETMOUSESPEED = SYSTEM_PARAMETERS_INFO_ACTION.GETMOUSESPEED;
pub const SPI_SETMOUSESPEED = SYSTEM_PARAMETERS_INFO_ACTION.SETMOUSESPEED;
pub const SPI_GETSCREENSAVERRUNNING = SYSTEM_PARAMETERS_INFO_ACTION.GETSCREENSAVERRUNNING;
pub const SPI_GETDESKWALLPAPER = SYSTEM_PARAMETERS_INFO_ACTION.GETDESKWALLPAPER;
pub const SPI_GETAUDIODESCRIPTION = SYSTEM_PARAMETERS_INFO_ACTION.GETAUDIODESCRIPTION;
pub const SPI_SETAUDIODESCRIPTION = SYSTEM_PARAMETERS_INFO_ACTION.SETAUDIODESCRIPTION;
pub const SPI_GETSCREENSAVESECURE = SYSTEM_PARAMETERS_INFO_ACTION.GETSCREENSAVESECURE;
pub const SPI_SETSCREENSAVESECURE = SYSTEM_PARAMETERS_INFO_ACTION.SETSCREENSAVESECURE;
pub const SPI_GETHUNGAPPTIMEOUT = SYSTEM_PARAMETERS_INFO_ACTION.GETHUNGAPPTIMEOUT;
pub const SPI_SETHUNGAPPTIMEOUT = SYSTEM_PARAMETERS_INFO_ACTION.SETHUNGAPPTIMEOUT;
pub const SPI_GETWAITTOKILLTIMEOUT = SYSTEM_PARAMETERS_INFO_ACTION.GETWAITTOKILLTIMEOUT;
pub const SPI_SETWAITTOKILLTIMEOUT = SYSTEM_PARAMETERS_INFO_ACTION.SETWAITTOKILLTIMEOUT;
pub const SPI_GETWAITTOKILLSERVICETIMEOUT = SYSTEM_PARAMETERS_INFO_ACTION.GETWAITTOKILLSERVICETIMEOUT;
pub const SPI_SETWAITTOKILLSERVICETIMEOUT = SYSTEM_PARAMETERS_INFO_ACTION.SETWAITTOKILLSERVICETIMEOUT;
pub const SPI_GETMOUSEDOCKTHRESHOLD = SYSTEM_PARAMETERS_INFO_ACTION.GETMOUSEDOCKTHRESHOLD;
pub const SPI_SETMOUSEDOCKTHRESHOLD = SYSTEM_PARAMETERS_INFO_ACTION.SETMOUSEDOCKTHRESHOLD;
pub const SPI_GETPENDOCKTHRESHOLD = SYSTEM_PARAMETERS_INFO_ACTION.GETPENDOCKTHRESHOLD;
pub const SPI_SETPENDOCKTHRESHOLD = SYSTEM_PARAMETERS_INFO_ACTION.SETPENDOCKTHRESHOLD;
pub const SPI_GETWINARRANGING = SYSTEM_PARAMETERS_INFO_ACTION.GETWINARRANGING;
pub const SPI_SETWINARRANGING = SYSTEM_PARAMETERS_INFO_ACTION.SETWINARRANGING;
pub const SPI_GETMOUSEDRAGOUTTHRESHOLD = SYSTEM_PARAMETERS_INFO_ACTION.GETMOUSEDRAGOUTTHRESHOLD;
pub const SPI_SETMOUSEDRAGOUTTHRESHOLD = SYSTEM_PARAMETERS_INFO_ACTION.SETMOUSEDRAGOUTTHRESHOLD;
pub const SPI_GETPENDRAGOUTTHRESHOLD = SYSTEM_PARAMETERS_INFO_ACTION.GETPENDRAGOUTTHRESHOLD;
pub const SPI_SETPENDRAGOUTTHRESHOLD = SYSTEM_PARAMETERS_INFO_ACTION.SETPENDRAGOUTTHRESHOLD;
pub const SPI_GETMOUSESIDEMOVETHRESHOLD = SYSTEM_PARAMETERS_INFO_ACTION.GETMOUSESIDEMOVETHRESHOLD;
pub const SPI_SETMOUSESIDEMOVETHRESHOLD = SYSTEM_PARAMETERS_INFO_ACTION.SETMOUSESIDEMOVETHRESHOLD;
pub const SPI_GETPENSIDEMOVETHRESHOLD = SYSTEM_PARAMETERS_INFO_ACTION.GETPENSIDEMOVETHRESHOLD;
pub const SPI_SETPENSIDEMOVETHRESHOLD = SYSTEM_PARAMETERS_INFO_ACTION.SETPENSIDEMOVETHRESHOLD;
pub const SPI_GETDRAGFROMMAXIMIZE = SYSTEM_PARAMETERS_INFO_ACTION.GETDRAGFROMMAXIMIZE;
pub const SPI_SETDRAGFROMMAXIMIZE = SYSTEM_PARAMETERS_INFO_ACTION.SETDRAGFROMMAXIMIZE;
pub const SPI_GETSNAPSIZING = SYSTEM_PARAMETERS_INFO_ACTION.GETSNAPSIZING;
pub const SPI_SETSNAPSIZING = SYSTEM_PARAMETERS_INFO_ACTION.SETSNAPSIZING;
pub const SPI_GETDOCKMOVING = SYSTEM_PARAMETERS_INFO_ACTION.GETDOCKMOVING;
pub const SPI_SETDOCKMOVING = SYSTEM_PARAMETERS_INFO_ACTION.SETDOCKMOVING;
pub const SPI_GETTOUCHPREDICTIONPARAMETERS = SYSTEM_PARAMETERS_INFO_ACTION.GETTOUCHPREDICTIONPARAMETERS;
pub const SPI_SETTOUCHPREDICTIONPARAMETERS = SYSTEM_PARAMETERS_INFO_ACTION.SETTOUCHPREDICTIONPARAMETERS;
pub const SPI_GETLOGICALDPIOVERRIDE = SYSTEM_PARAMETERS_INFO_ACTION.GETLOGICALDPIOVERRIDE;
pub const SPI_SETLOGICALDPIOVERRIDE = SYSTEM_PARAMETERS_INFO_ACTION.SETLOGICALDPIOVERRIDE;
pub const SPI_GETMENURECT = SYSTEM_PARAMETERS_INFO_ACTION.GETMENURECT;
pub const SPI_SETMENURECT = SYSTEM_PARAMETERS_INFO_ACTION.SETMENURECT;
pub const SPI_GETACTIVEWINDOWTRACKING = SYSTEM_PARAMETERS_INFO_ACTION.GETACTIVEWINDOWTRACKING;
pub const SPI_SETACTIVEWINDOWTRACKING = SYSTEM_PARAMETERS_INFO_ACTION.SETACTIVEWINDOWTRACKING;
pub const SPI_GETMENUANIMATION = SYSTEM_PARAMETERS_INFO_ACTION.GETMENUANIMATION;
pub const SPI_SETMENUANIMATION = SYSTEM_PARAMETERS_INFO_ACTION.SETMENUANIMATION;
pub const SPI_GETCOMBOBOXANIMATION = SYSTEM_PARAMETERS_INFO_ACTION.GETCOMBOBOXANIMATION;
pub const SPI_SETCOMBOBOXANIMATION = SYSTEM_PARAMETERS_INFO_ACTION.SETCOMBOBOXANIMATION;
pub const SPI_GETLISTBOXSMOOTHSCROLLING = SYSTEM_PARAMETERS_INFO_ACTION.GETLISTBOXSMOOTHSCROLLING;
pub const SPI_SETLISTBOXSMOOTHSCROLLING = SYSTEM_PARAMETERS_INFO_ACTION.SETLISTBOXSMOOTHSCROLLING;
pub const SPI_GETGRADIENTCAPTIONS = SYSTEM_PARAMETERS_INFO_ACTION.GETGRADIENTCAPTIONS;
pub const SPI_SETGRADIENTCAPTIONS = SYSTEM_PARAMETERS_INFO_ACTION.SETGRADIENTCAPTIONS;
pub const SPI_GETKEYBOARDCUES = SYSTEM_PARAMETERS_INFO_ACTION.GETKEYBOARDCUES;
pub const SPI_SETKEYBOARDCUES = SYSTEM_PARAMETERS_INFO_ACTION.SETKEYBOARDCUES;
pub const SPI_GETMENUUNDERLINES = SYSTEM_PARAMETERS_INFO_ACTION.GETKEYBOARDCUES;
pub const SPI_SETMENUUNDERLINES = SYSTEM_PARAMETERS_INFO_ACTION.SETKEYBOARDCUES;
pub const SPI_GETACTIVEWNDTRKZORDER = SYSTEM_PARAMETERS_INFO_ACTION.GETACTIVEWNDTRKZORDER;
pub const SPI_SETACTIVEWNDTRKZORDER = SYSTEM_PARAMETERS_INFO_ACTION.SETACTIVEWNDTRKZORDER;
pub const SPI_GETHOTTRACKING = SYSTEM_PARAMETERS_INFO_ACTION.GETHOTTRACKING;
pub const SPI_SETHOTTRACKING = SYSTEM_PARAMETERS_INFO_ACTION.SETHOTTRACKING;
pub const SPI_GETMENUFADE = SYSTEM_PARAMETERS_INFO_ACTION.GETMENUFADE;
pub const SPI_SETMENUFADE = SYSTEM_PARAMETERS_INFO_ACTION.SETMENUFADE;
pub const SPI_GETSELECTIONFADE = SYSTEM_PARAMETERS_INFO_ACTION.GETSELECTIONFADE;
pub const SPI_SETSELECTIONFADE = SYSTEM_PARAMETERS_INFO_ACTION.SETSELECTIONFADE;
pub const SPI_GETTOOLTIPANIMATION = SYSTEM_PARAMETERS_INFO_ACTION.GETTOOLTIPANIMATION;
pub const SPI_SETTOOLTIPANIMATION = SYSTEM_PARAMETERS_INFO_ACTION.SETTOOLTIPANIMATION;
pub const SPI_GETTOOLTIPFADE = SYSTEM_PARAMETERS_INFO_ACTION.GETTOOLTIPFADE;
pub const SPI_SETTOOLTIPFADE = SYSTEM_PARAMETERS_INFO_ACTION.SETTOOLTIPFADE;
pub const SPI_GETCURSORSHADOW = SYSTEM_PARAMETERS_INFO_ACTION.GETCURSORSHADOW;
pub const SPI_SETCURSORSHADOW = SYSTEM_PARAMETERS_INFO_ACTION.SETCURSORSHADOW;
pub const SPI_GETMOUSESONAR = SYSTEM_PARAMETERS_INFO_ACTION.GETMOUSESONAR;
pub const SPI_SETMOUSESONAR = SYSTEM_PARAMETERS_INFO_ACTION.SETMOUSESONAR;
pub const SPI_GETMOUSECLICKLOCK = SYSTEM_PARAMETERS_INFO_ACTION.GETMOUSECLICKLOCK;
pub const SPI_SETMOUSECLICKLOCK = SYSTEM_PARAMETERS_INFO_ACTION.SETMOUSECLICKLOCK;
pub const SPI_GETMOUSEVANISH = SYSTEM_PARAMETERS_INFO_ACTION.GETMOUSEVANISH;
pub const SPI_SETMOUSEVANISH = SYSTEM_PARAMETERS_INFO_ACTION.SETMOUSEVANISH;
pub const SPI_GETFLATMENU = SYSTEM_PARAMETERS_INFO_ACTION.GETFLATMENU;
pub const SPI_SETFLATMENU = SYSTEM_PARAMETERS_INFO_ACTION.SETFLATMENU;
pub const SPI_GETDROPSHADOW = SYSTEM_PARAMETERS_INFO_ACTION.GETDROPSHADOW;
pub const SPI_SETDROPSHADOW = SYSTEM_PARAMETERS_INFO_ACTION.SETDROPSHADOW;
pub const SPI_GETBLOCKSENDINPUTRESETS = SYSTEM_PARAMETERS_INFO_ACTION.GETBLOCKSENDINPUTRESETS;
pub const SPI_SETBLOCKSENDINPUTRESETS = SYSTEM_PARAMETERS_INFO_ACTION.SETBLOCKSENDINPUTRESETS;
pub const SPI_GETUIEFFECTS = SYSTEM_PARAMETERS_INFO_ACTION.GETUIEFFECTS;
pub const SPI_SETUIEFFECTS = SYSTEM_PARAMETERS_INFO_ACTION.SETUIEFFECTS;
pub const SPI_GETDISABLEOVERLAPPEDCONTENT = SYSTEM_PARAMETERS_INFO_ACTION.GETDISABLEOVERLAPPEDCONTENT;
pub const SPI_SETDISABLEOVERLAPPEDCONTENT = SYSTEM_PARAMETERS_INFO_ACTION.SETDISABLEOVERLAPPEDCONTENT;
pub const SPI_GETCLIENTAREAANIMATION = SYSTEM_PARAMETERS_INFO_ACTION.GETCLIENTAREAANIMATION;
pub const SPI_SETCLIENTAREAANIMATION = SYSTEM_PARAMETERS_INFO_ACTION.SETCLIENTAREAANIMATION;
pub const SPI_GETCLEARTYPE = SYSTEM_PARAMETERS_INFO_ACTION.GETCLEARTYPE;
pub const SPI_SETCLEARTYPE = SYSTEM_PARAMETERS_INFO_ACTION.SETCLEARTYPE;
pub const SPI_GETSPEECHRECOGNITION = SYSTEM_PARAMETERS_INFO_ACTION.GETSPEECHRECOGNITION;
pub const SPI_SETSPEECHRECOGNITION = SYSTEM_PARAMETERS_INFO_ACTION.SETSPEECHRECOGNITION;
pub const SPI_GETCARETBROWSING = SYSTEM_PARAMETERS_INFO_ACTION.GETCARETBROWSING;
pub const SPI_SETCARETBROWSING = SYSTEM_PARAMETERS_INFO_ACTION.SETCARETBROWSING;
pub const SPI_GETTHREADLOCALINPUTSETTINGS = SYSTEM_PARAMETERS_INFO_ACTION.GETTHREADLOCALINPUTSETTINGS;
pub const SPI_SETTHREADLOCALINPUTSETTINGS = SYSTEM_PARAMETERS_INFO_ACTION.SETTHREADLOCALINPUTSETTINGS;
pub const SPI_GETSYSTEMLANGUAGEBAR = SYSTEM_PARAMETERS_INFO_ACTION.GETSYSTEMLANGUAGEBAR;
pub const SPI_SETSYSTEMLANGUAGEBAR = SYSTEM_PARAMETERS_INFO_ACTION.SETSYSTEMLANGUAGEBAR;
pub const SPI_GETFOREGROUNDLOCKTIMEOUT = SYSTEM_PARAMETERS_INFO_ACTION.GETFOREGROUNDLOCKTIMEOUT;
pub const SPI_SETFOREGROUNDLOCKTIMEOUT = SYSTEM_PARAMETERS_INFO_ACTION.SETFOREGROUNDLOCKTIMEOUT;
pub const SPI_GETACTIVEWNDTRKTIMEOUT = SYSTEM_PARAMETERS_INFO_ACTION.GETACTIVEWNDTRKTIMEOUT;
pub const SPI_SETACTIVEWNDTRKTIMEOUT = SYSTEM_PARAMETERS_INFO_ACTION.SETACTIVEWNDTRKTIMEOUT;
pub const SPI_GETFOREGROUNDFLASHCOUNT = SYSTEM_PARAMETERS_INFO_ACTION.GETFOREGROUNDFLASHCOUNT;
pub const SPI_SETFOREGROUNDFLASHCOUNT = SYSTEM_PARAMETERS_INFO_ACTION.SETFOREGROUNDFLASHCOUNT;
pub const SPI_GETCARETWIDTH = SYSTEM_PARAMETERS_INFO_ACTION.GETCARETWIDTH;
pub const SPI_SETCARETWIDTH = SYSTEM_PARAMETERS_INFO_ACTION.SETCARETWIDTH;
pub const SPI_GETMOUSECLICKLOCKTIME = SYSTEM_PARAMETERS_INFO_ACTION.GETMOUSECLICKLOCKTIME;
pub const SPI_SETMOUSECLICKLOCKTIME = SYSTEM_PARAMETERS_INFO_ACTION.SETMOUSECLICKLOCKTIME;
pub const SPI_GETFONTSMOOTHINGTYPE = SYSTEM_PARAMETERS_INFO_ACTION.GETFONTSMOOTHINGTYPE;
pub const SPI_SETFONTSMOOTHINGTYPE = SYSTEM_PARAMETERS_INFO_ACTION.SETFONTSMOOTHINGTYPE;
pub const SPI_GETFONTSMOOTHINGCONTRAST = SYSTEM_PARAMETERS_INFO_ACTION.GETFONTSMOOTHINGCONTRAST;
pub const SPI_SETFONTSMOOTHINGCONTRAST = SYSTEM_PARAMETERS_INFO_ACTION.SETFONTSMOOTHINGCONTRAST;
pub const SPI_GETFOCUSBORDERWIDTH = SYSTEM_PARAMETERS_INFO_ACTION.GETFOCUSBORDERWIDTH;
pub const SPI_SETFOCUSBORDERWIDTH = SYSTEM_PARAMETERS_INFO_ACTION.SETFOCUSBORDERWIDTH;
pub const SPI_GETFOCUSBORDERHEIGHT = SYSTEM_PARAMETERS_INFO_ACTION.GETFOCUSBORDERHEIGHT;
pub const SPI_SETFOCUSBORDERHEIGHT = SYSTEM_PARAMETERS_INFO_ACTION.SETFOCUSBORDERHEIGHT;
pub const SPI_GETFONTSMOOTHINGORIENTATION = SYSTEM_PARAMETERS_INFO_ACTION.GETFONTSMOOTHINGORIENTATION;
pub const SPI_SETFONTSMOOTHINGORIENTATION = SYSTEM_PARAMETERS_INFO_ACTION.SETFONTSMOOTHINGORIENTATION;
pub const SPI_GETMINIMUMHITRADIUS = SYSTEM_PARAMETERS_INFO_ACTION.GETMINIMUMHITRADIUS;
pub const SPI_SETMINIMUMHITRADIUS = SYSTEM_PARAMETERS_INFO_ACTION.SETMINIMUMHITRADIUS;
pub const SPI_GETMESSAGEDURATION = SYSTEM_PARAMETERS_INFO_ACTION.GETMESSAGEDURATION;
pub const SPI_SETMESSAGEDURATION = SYSTEM_PARAMETERS_INFO_ACTION.SETMESSAGEDURATION;
pub const SPI_GETCONTACTVISUALIZATION = SYSTEM_PARAMETERS_INFO_ACTION.GETCONTACTVISUALIZATION;
pub const SPI_SETCONTACTVISUALIZATION = SYSTEM_PARAMETERS_INFO_ACTION.SETCONTACTVISUALIZATION;
pub const SPI_GETGESTUREVISUALIZATION = SYSTEM_PARAMETERS_INFO_ACTION.GETGESTUREVISUALIZATION;
pub const SPI_SETGESTUREVISUALIZATION = SYSTEM_PARAMETERS_INFO_ACTION.SETGESTUREVISUALIZATION;
pub const SPI_GETMOUSEWHEELROUTING = SYSTEM_PARAMETERS_INFO_ACTION.GETMOUSEWHEELROUTING;
pub const SPI_SETMOUSEWHEELROUTING = SYSTEM_PARAMETERS_INFO_ACTION.SETMOUSEWHEELROUTING;
pub const SPI_GETPENVISUALIZATION = SYSTEM_PARAMETERS_INFO_ACTION.GETPENVISUALIZATION;
pub const SPI_SETPENVISUALIZATION = SYSTEM_PARAMETERS_INFO_ACTION.SETPENVISUALIZATION;
pub const SPI_GETPENARBITRATIONTYPE = SYSTEM_PARAMETERS_INFO_ACTION.GETPENARBITRATIONTYPE;
pub const SPI_SETPENARBITRATIONTYPE = SYSTEM_PARAMETERS_INFO_ACTION.SETPENARBITRATIONTYPE;
pub const SPI_GETCARETTIMEOUT = SYSTEM_PARAMETERS_INFO_ACTION.GETCARETTIMEOUT;
pub const SPI_SETCARETTIMEOUT = SYSTEM_PARAMETERS_INFO_ACTION.SETCARETTIMEOUT;
pub const SPI_GETHANDEDNESS = SYSTEM_PARAMETERS_INFO_ACTION.GETHANDEDNESS;
pub const SPI_SETHANDEDNESS = SYSTEM_PARAMETERS_INFO_ACTION.SETHANDEDNESS;
pub const TRACK_POPUP_MENU_FLAGS = enum(u32) {
LEFTBUTTON = 0,
RIGHTBUTTON = 2,
// LEFTALIGN = 0, this enum value conflicts with LEFTBUTTON
CENTERALIGN = 4,
RIGHTALIGN = 8,
// TOPALIGN = 0, this enum value conflicts with LEFTBUTTON
VCENTERALIGN = 16,
BOTTOMALIGN = 32,
// HORIZONTAL = 0, this enum value conflicts with LEFTBUTTON
VERTICAL = 64,
NONOTIFY = 128,
RETURNCMD = 256,
RECURSE = 1,
HORPOSANIMATION = 1024,
HORNEGANIMATION = 2048,
VERPOSANIMATION = 4096,
VERNEGANIMATION = 8192,
NOANIMATION = 16384,
LAYOUTRTL = 32768,
WORKAREA = 65536,
_,
pub fn initFlags(o: struct {
LEFTBUTTON: u1 = 0,
RIGHTBUTTON: u1 = 0,
CENTERALIGN: u1 = 0,
RIGHTALIGN: u1 = 0,
VCENTERALIGN: u1 = 0,
BOTTOMALIGN: u1 = 0,
VERTICAL: u1 = 0,
NONOTIFY: u1 = 0,
RETURNCMD: u1 = 0,
RECURSE: u1 = 0,
HORPOSANIMATION: u1 = 0,
HORNEGANIMATION: u1 = 0,
VERPOSANIMATION: u1 = 0,
VERNEGANIMATION: u1 = 0,
NOANIMATION: u1 = 0,
LAYOUTRTL: u1 = 0,
WORKAREA: u1 = 0,
}) TRACK_POPUP_MENU_FLAGS {
return @intToEnum(TRACK_POPUP_MENU_FLAGS,
(if (o.LEFTBUTTON == 1) @enumToInt(TRACK_POPUP_MENU_FLAGS.LEFTBUTTON) else 0)
| (if (o.RIGHTBUTTON == 1) @enumToInt(TRACK_POPUP_MENU_FLAGS.RIGHTBUTTON) else 0)
| (if (o.CENTERALIGN == 1) @enumToInt(TRACK_POPUP_MENU_FLAGS.CENTERALIGN) else 0)
| (if (o.RIGHTALIGN == 1) @enumToInt(TRACK_POPUP_MENU_FLAGS.RIGHTALIGN) else 0)
| (if (o.VCENTERALIGN == 1) @enumToInt(TRACK_POPUP_MENU_FLAGS.VCENTERALIGN) else 0)
| (if (o.BOTTOMALIGN == 1) @enumToInt(TRACK_POPUP_MENU_FLAGS.BOTTOMALIGN) else 0)
| (if (o.VERTICAL == 1) @enumToInt(TRACK_POPUP_MENU_FLAGS.VERTICAL) else 0)
| (if (o.NONOTIFY == 1) @enumToInt(TRACK_POPUP_MENU_FLAGS.NONOTIFY) else 0)
| (if (o.RETURNCMD == 1) @enumToInt(TRACK_POPUP_MENU_FLAGS.RETURNCMD) else 0)
| (if (o.RECURSE == 1) @enumToInt(TRACK_POPUP_MENU_FLAGS.RECURSE) else 0)
| (if (o.HORPOSANIMATION == 1) @enumToInt(TRACK_POPUP_MENU_FLAGS.HORPOSANIMATION) else 0)
| (if (o.HORNEGANIMATION == 1) @enumToInt(TRACK_POPUP_MENU_FLAGS.HORNEGANIMATION) else 0)
| (if (o.VERPOSANIMATION == 1) @enumToInt(TRACK_POPUP_MENU_FLAGS.VERPOSANIMATION) else 0)
| (if (o.VERNEGANIMATION == 1) @enumToInt(TRACK_POPUP_MENU_FLAGS.VERNEGANIMATION) else 0)
| (if (o.NOANIMATION == 1) @enumToInt(TRACK_POPUP_MENU_FLAGS.NOANIMATION) else 0)
| (if (o.LAYOUTRTL == 1) @enumToInt(TRACK_POPUP_MENU_FLAGS.LAYOUTRTL) else 0)
| (if (o.WORKAREA == 1) @enumToInt(TRACK_POPUP_MENU_FLAGS.WORKAREA) else 0)
);
}
};
pub const TPM_LEFTBUTTON = TRACK_POPUP_MENU_FLAGS.LEFTBUTTON;
pub const TPM_RIGHTBUTTON = TRACK_POPUP_MENU_FLAGS.RIGHTBUTTON;
pub const TPM_LEFTALIGN = TRACK_POPUP_MENU_FLAGS.LEFTBUTTON;
pub const TPM_CENTERALIGN = TRACK_POPUP_MENU_FLAGS.CENTERALIGN;
pub const TPM_RIGHTALIGN = TRACK_POPUP_MENU_FLAGS.RIGHTALIGN;
pub const TPM_TOPALIGN = TRACK_POPUP_MENU_FLAGS.LEFTBUTTON;
pub const TPM_VCENTERALIGN = TRACK_POPUP_MENU_FLAGS.VCENTERALIGN;
pub const TPM_BOTTOMALIGN = TRACK_POPUP_MENU_FLAGS.BOTTOMALIGN;
pub const TPM_HORIZONTAL = TRACK_POPUP_MENU_FLAGS.LEFTBUTTON;
pub const TPM_VERTICAL = TRACK_POPUP_MENU_FLAGS.VERTICAL;
pub const TPM_NONOTIFY = TRACK_POPUP_MENU_FLAGS.NONOTIFY;
pub const TPM_RETURNCMD = TRACK_POPUP_MENU_FLAGS.RETURNCMD;
pub const TPM_RECURSE = TRACK_POPUP_MENU_FLAGS.RECURSE;
pub const TPM_HORPOSANIMATION = TRACK_POPUP_MENU_FLAGS.HORPOSANIMATION;
pub const TPM_HORNEGANIMATION = TRACK_POPUP_MENU_FLAGS.HORNEGANIMATION;
pub const TPM_VERPOSANIMATION = TRACK_POPUP_MENU_FLAGS.VERPOSANIMATION;
pub const TPM_VERNEGANIMATION = TRACK_POPUP_MENU_FLAGS.VERNEGANIMATION;
pub const TPM_NOANIMATION = TRACK_POPUP_MENU_FLAGS.NOANIMATION;
pub const TPM_LAYOUTRTL = TRACK_POPUP_MENU_FLAGS.LAYOUTRTL;
pub const TPM_WORKAREA = TRACK_POPUP_MENU_FLAGS.WORKAREA;
pub const WINDOW_EX_STYLE = enum(u32) {
DLGMODALFRAME = 1,
NOPARENTNOTIFY = 4,
TOPMOST = 8,
ACCEPTFILES = 16,
TRANSPARENT = 32,
MDICHILD = 64,
TOOLWINDOW = 128,
WINDOWEDGE = 256,
CLIENTEDGE = 512,
CONTEXTHELP = 1024,
RIGHT = 4096,
LEFT = 0,
RTLREADING = 8192,
// LTRREADING = 0, this enum value conflicts with LEFT
LEFTSCROLLBAR = 16384,
// RIGHTSCROLLBAR = 0, this enum value conflicts with LEFT
CONTROLPARENT = 65536,
STATICEDGE = 131072,
APPWINDOW = 262144,
OVERLAPPEDWINDOW = 768,
PALETTEWINDOW = 392,
LAYERED = 524288,
NOINHERITLAYOUT = 1048576,
NOREDIRECTIONBITMAP = 2097152,
LAYOUTRTL = 4194304,
COMPOSITED = 33554432,
NOACTIVATE = 134217728,
_,
pub fn initFlags(o: struct {
DLGMODALFRAME: u1 = 0,
NOPARENTNOTIFY: u1 = 0,
TOPMOST: u1 = 0,
ACCEPTFILES: u1 = 0,
TRANSPARENT: u1 = 0,
MDICHILD: u1 = 0,
TOOLWINDOW: u1 = 0,
WINDOWEDGE: u1 = 0,
CLIENTEDGE: u1 = 0,
CONTEXTHELP: u1 = 0,
RIGHT: u1 = 0,
LEFT: u1 = 0,
RTLREADING: u1 = 0,
LEFTSCROLLBAR: u1 = 0,
CONTROLPARENT: u1 = 0,
STATICEDGE: u1 = 0,
APPWINDOW: u1 = 0,
OVERLAPPEDWINDOW: u1 = 0,
PALETTEWINDOW: u1 = 0,
LAYERED: u1 = 0,
NOINHERITLAYOUT: u1 = 0,
NOREDIRECTIONBITMAP: u1 = 0,
LAYOUTRTL: u1 = 0,
COMPOSITED: u1 = 0,
NOACTIVATE: u1 = 0,
}) WINDOW_EX_STYLE {
return @intToEnum(WINDOW_EX_STYLE,
(if (o.DLGMODALFRAME == 1) @enumToInt(WINDOW_EX_STYLE.DLGMODALFRAME) else 0)
| (if (o.NOPARENTNOTIFY == 1) @enumToInt(WINDOW_EX_STYLE.NOPARENTNOTIFY) else 0)
| (if (o.TOPMOST == 1) @enumToInt(WINDOW_EX_STYLE.TOPMOST) else 0)
| (if (o.ACCEPTFILES == 1) @enumToInt(WINDOW_EX_STYLE.ACCEPTFILES) else 0)
| (if (o.TRANSPARENT == 1) @enumToInt(WINDOW_EX_STYLE.TRANSPARENT) else 0)
| (if (o.MDICHILD == 1) @enumToInt(WINDOW_EX_STYLE.MDICHILD) else 0)
| (if (o.TOOLWINDOW == 1) @enumToInt(WINDOW_EX_STYLE.TOOLWINDOW) else 0)
| (if (o.WINDOWEDGE == 1) @enumToInt(WINDOW_EX_STYLE.WINDOWEDGE) else 0)
| (if (o.CLIENTEDGE == 1) @enumToInt(WINDOW_EX_STYLE.CLIENTEDGE) else 0)
| (if (o.CONTEXTHELP == 1) @enumToInt(WINDOW_EX_STYLE.CONTEXTHELP) else 0)
| (if (o.RIGHT == 1) @enumToInt(WINDOW_EX_STYLE.RIGHT) else 0)
| (if (o.LEFT == 1) @enumToInt(WINDOW_EX_STYLE.LEFT) else 0)
| (if (o.RTLREADING == 1) @enumToInt(WINDOW_EX_STYLE.RTLREADING) else 0)
| (if (o.LEFTSCROLLBAR == 1) @enumToInt(WINDOW_EX_STYLE.LEFTSCROLLBAR) else 0)
| (if (o.CONTROLPARENT == 1) @enumToInt(WINDOW_EX_STYLE.CONTROLPARENT) else 0)
| (if (o.STATICEDGE == 1) @enumToInt(WINDOW_EX_STYLE.STATICEDGE) else 0)
| (if (o.APPWINDOW == 1) @enumToInt(WINDOW_EX_STYLE.APPWINDOW) else 0)
| (if (o.OVERLAPPEDWINDOW == 1) @enumToInt(WINDOW_EX_STYLE.OVERLAPPEDWINDOW) else 0)
| (if (o.PALETTEWINDOW == 1) @enumToInt(WINDOW_EX_STYLE.PALETTEWINDOW) else 0)
| (if (o.LAYERED == 1) @enumToInt(WINDOW_EX_STYLE.LAYERED) else 0)
| (if (o.NOINHERITLAYOUT == 1) @enumToInt(WINDOW_EX_STYLE.NOINHERITLAYOUT) else 0)
| (if (o.NOREDIRECTIONBITMAP == 1) @enumToInt(WINDOW_EX_STYLE.NOREDIRECTIONBITMAP) else 0)
| (if (o.LAYOUTRTL == 1) @enumToInt(WINDOW_EX_STYLE.LAYOUTRTL) else 0)
| (if (o.COMPOSITED == 1) @enumToInt(WINDOW_EX_STYLE.COMPOSITED) else 0)
| (if (o.NOACTIVATE == 1) @enumToInt(WINDOW_EX_STYLE.NOACTIVATE) else 0)
);
}
};
pub const WS_EX_DLGMODALFRAME = WINDOW_EX_STYLE.DLGMODALFRAME;
pub const WS_EX_NOPARENTNOTIFY = WINDOW_EX_STYLE.NOPARENTNOTIFY;
pub const WS_EX_TOPMOST = WINDOW_EX_STYLE.TOPMOST;
pub const WS_EX_ACCEPTFILES = WINDOW_EX_STYLE.ACCEPTFILES;
pub const WS_EX_TRANSPARENT = WINDOW_EX_STYLE.TRANSPARENT;
pub const WS_EX_MDICHILD = WINDOW_EX_STYLE.MDICHILD;
pub const WS_EX_TOOLWINDOW = WINDOW_EX_STYLE.TOOLWINDOW;
pub const WS_EX_WINDOWEDGE = WINDOW_EX_STYLE.WINDOWEDGE;
pub const WS_EX_CLIENTEDGE = WINDOW_EX_STYLE.CLIENTEDGE;
pub const WS_EX_CONTEXTHELP = WINDOW_EX_STYLE.CONTEXTHELP;
pub const WS_EX_RIGHT = WINDOW_EX_STYLE.RIGHT;
pub const WS_EX_LEFT = WINDOW_EX_STYLE.LEFT;
pub const WS_EX_RTLREADING = WINDOW_EX_STYLE.RTLREADING;
pub const WS_EX_LTRREADING = WINDOW_EX_STYLE.LEFT;
pub const WS_EX_LEFTSCROLLBAR = WINDOW_EX_STYLE.LEFTSCROLLBAR;
pub const WS_EX_RIGHTSCROLLBAR = WINDOW_EX_STYLE.LEFT;
pub const WS_EX_CONTROLPARENT = WINDOW_EX_STYLE.CONTROLPARENT;
pub const WS_EX_STATICEDGE = WINDOW_EX_STYLE.STATICEDGE;
pub const WS_EX_APPWINDOW = WINDOW_EX_STYLE.APPWINDOW;
pub const WS_EX_OVERLAPPEDWINDOW = WINDOW_EX_STYLE.OVERLAPPEDWINDOW;
pub const WS_EX_PALETTEWINDOW = WINDOW_EX_STYLE.PALETTEWINDOW;
pub const WS_EX_LAYERED = WINDOW_EX_STYLE.LAYERED;
pub const WS_EX_NOINHERITLAYOUT = WINDOW_EX_STYLE.NOINHERITLAYOUT;
pub const WS_EX_NOREDIRECTIONBITMAP = WINDOW_EX_STYLE.NOREDIRECTIONBITMAP;
pub const WS_EX_LAYOUTRTL = WINDOW_EX_STYLE.LAYOUTRTL;
pub const WS_EX_COMPOSITED = WINDOW_EX_STYLE.COMPOSITED;
pub const WS_EX_NOACTIVATE = WINDOW_EX_STYLE.NOACTIVATE;
pub const WINDOW_STYLE = enum(u32) {
OVERLAPPED = 0,
POPUP = 2147483648,
CHILD = 1073741824,
MINIMIZE = 536870912,
VISIBLE = 268435456,
DISABLED = 134217728,
CLIPSIBLINGS = 67108864,
CLIPCHILDREN = 33554432,
MAXIMIZE = 16777216,
CAPTION = 12582912,
BORDER = 8388608,
DLGFRAME = 4194304,
VSCROLL = 2097152,
HSCROLL = 1048576,
SYSMENU = 524288,
THICKFRAME = 262144,
GROUP = 131072,
TABSTOP = 65536,
// MINIMIZEBOX = 131072, this enum value conflicts with GROUP
// MAXIMIZEBOX = 65536, this enum value conflicts with TABSTOP
// TILED = 0, this enum value conflicts with OVERLAPPED
// ICONIC = 536870912, this enum value conflicts with MINIMIZE
// SIZEBOX = 262144, this enum value conflicts with THICKFRAME
TILEDWINDOW = 13565952,
// OVERLAPPEDWINDOW = 13565952, this enum value conflicts with TILEDWINDOW
POPUPWINDOW = 2156396544,
// CHILDWINDOW = 1073741824, this enum value conflicts with CHILD
ACTIVECAPTION = 1,
_,
pub fn initFlags(o: struct {
OVERLAPPED: u1 = 0,
POPUP: u1 = 0,
CHILD: u1 = 0,
MINIMIZE: u1 = 0,
VISIBLE: u1 = 0,
DISABLED: u1 = 0,
CLIPSIBLINGS: u1 = 0,
CLIPCHILDREN: u1 = 0,
MAXIMIZE: u1 = 0,
CAPTION: u1 = 0,
BORDER: u1 = 0,
DLGFRAME: u1 = 0,
VSCROLL: u1 = 0,
HSCROLL: u1 = 0,
SYSMENU: u1 = 0,
THICKFRAME: u1 = 0,
GROUP: u1 = 0,
TABSTOP: u1 = 0,
TILEDWINDOW: u1 = 0,
POPUPWINDOW: u1 = 0,
ACTIVECAPTION: u1 = 0,
}) WINDOW_STYLE {
return @intToEnum(WINDOW_STYLE,
(if (o.OVERLAPPED == 1) @enumToInt(WINDOW_STYLE.OVERLAPPED) else 0)
| (if (o.POPUP == 1) @enumToInt(WINDOW_STYLE.POPUP) else 0)
| (if (o.CHILD == 1) @enumToInt(WINDOW_STYLE.CHILD) else 0)
| (if (o.MINIMIZE == 1) @enumToInt(WINDOW_STYLE.MINIMIZE) else 0)
| (if (o.VISIBLE == 1) @enumToInt(WINDOW_STYLE.VISIBLE) else 0)
| (if (o.DISABLED == 1) @enumToInt(WINDOW_STYLE.DISABLED) else 0)
| (if (o.CLIPSIBLINGS == 1) @enumToInt(WINDOW_STYLE.CLIPSIBLINGS) else 0)
| (if (o.CLIPCHILDREN == 1) @enumToInt(WINDOW_STYLE.CLIPCHILDREN) else 0)
| (if (o.MAXIMIZE == 1) @enumToInt(WINDOW_STYLE.MAXIMIZE) else 0)
| (if (o.CAPTION == 1) @enumToInt(WINDOW_STYLE.CAPTION) else 0)
| (if (o.BORDER == 1) @enumToInt(WINDOW_STYLE.BORDER) else 0)
| (if (o.DLGFRAME == 1) @enumToInt(WINDOW_STYLE.DLGFRAME) else 0)
| (if (o.VSCROLL == 1) @enumToInt(WINDOW_STYLE.VSCROLL) else 0)
| (if (o.HSCROLL == 1) @enumToInt(WINDOW_STYLE.HSCROLL) else 0)
| (if (o.SYSMENU == 1) @enumToInt(WINDOW_STYLE.SYSMENU) else 0)
| (if (o.THICKFRAME == 1) @enumToInt(WINDOW_STYLE.THICKFRAME) else 0)
| (if (o.GROUP == 1) @enumToInt(WINDOW_STYLE.GROUP) else 0)
| (if (o.TABSTOP == 1) @enumToInt(WINDOW_STYLE.TABSTOP) else 0)
| (if (o.TILEDWINDOW == 1) @enumToInt(WINDOW_STYLE.TILEDWINDOW) else 0)
| (if (o.POPUPWINDOW == 1) @enumToInt(WINDOW_STYLE.POPUPWINDOW) else 0)
| (if (o.ACTIVECAPTION == 1) @enumToInt(WINDOW_STYLE.ACTIVECAPTION) else 0)
);
}
};
pub const WS_OVERLAPPED = WINDOW_STYLE.OVERLAPPED;
pub const WS_POPUP = WINDOW_STYLE.POPUP;
pub const WS_CHILD = WINDOW_STYLE.CHILD;
pub const WS_MINIMIZE = WINDOW_STYLE.MINIMIZE;
pub const WS_VISIBLE = WINDOW_STYLE.VISIBLE;
pub const WS_DISABLED = WINDOW_STYLE.DISABLED;
pub const WS_CLIPSIBLINGS = WINDOW_STYLE.CLIPSIBLINGS;
pub const WS_CLIPCHILDREN = WINDOW_STYLE.CLIPCHILDREN;
pub const WS_MAXIMIZE = WINDOW_STYLE.MAXIMIZE;
pub const WS_CAPTION = WINDOW_STYLE.CAPTION;
pub const WS_BORDER = WINDOW_STYLE.BORDER;
pub const WS_DLGFRAME = WINDOW_STYLE.DLGFRAME;
pub const WS_VSCROLL = WINDOW_STYLE.VSCROLL;
pub const WS_HSCROLL = WINDOW_STYLE.HSCROLL;
pub const WS_SYSMENU = WINDOW_STYLE.SYSMENU;
pub const WS_THICKFRAME = WINDOW_STYLE.THICKFRAME;
pub const WS_GROUP = WINDOW_STYLE.GROUP;
pub const WS_TABSTOP = WINDOW_STYLE.TABSTOP;
pub const WS_MINIMIZEBOX = WINDOW_STYLE.GROUP;
pub const WS_MAXIMIZEBOX = WINDOW_STYLE.TABSTOP;
pub const WS_TILED = WINDOW_STYLE.OVERLAPPED;
pub const WS_ICONIC = WINDOW_STYLE.MINIMIZE;
pub const WS_SIZEBOX = WINDOW_STYLE.THICKFRAME;
pub const WS_TILEDWINDOW = WINDOW_STYLE.TILEDWINDOW;
pub const WS_OVERLAPPEDWINDOW = WINDOW_STYLE.TILEDWINDOW;
pub const WS_POPUPWINDOW = WINDOW_STYLE.POPUPWINDOW;
pub const WS_CHILDWINDOW = WINDOW_STYLE.CHILD;
pub const WS_ACTIVECAPTION = WINDOW_STYLE.ACTIVECAPTION;
pub const MENU_ITEM_TYPE = enum(u32) {
BITMAP = 4,
MENUBARBREAK = 32,
MENUBREAK = 64,
OWNERDRAW = 256,
RADIOCHECK = 512,
RIGHTJUSTIFY = 16384,
RIGHTORDER = 8192,
SEPARATOR = 2048,
STRING = 0,
_,
pub fn initFlags(o: struct {
BITMAP: u1 = 0,
MENUBARBREAK: u1 = 0,
MENUBREAK: u1 = 0,
OWNERDRAW: u1 = 0,
RADIOCHECK: u1 = 0,
RIGHTJUSTIFY: u1 = 0,
RIGHTORDER: u1 = 0,
SEPARATOR: u1 = 0,
STRING: u1 = 0,
}) MENU_ITEM_TYPE {
return @intToEnum(MENU_ITEM_TYPE,
(if (o.BITMAP == 1) @enumToInt(MENU_ITEM_TYPE.BITMAP) else 0)
| (if (o.MENUBARBREAK == 1) @enumToInt(MENU_ITEM_TYPE.MENUBARBREAK) else 0)
| (if (o.MENUBREAK == 1) @enumToInt(MENU_ITEM_TYPE.MENUBREAK) else 0)
| (if (o.OWNERDRAW == 1) @enumToInt(MENU_ITEM_TYPE.OWNERDRAW) else 0)
| (if (o.RADIOCHECK == 1) @enumToInt(MENU_ITEM_TYPE.RADIOCHECK) else 0)
| (if (o.RIGHTJUSTIFY == 1) @enumToInt(MENU_ITEM_TYPE.RIGHTJUSTIFY) else 0)
| (if (o.RIGHTORDER == 1) @enumToInt(MENU_ITEM_TYPE.RIGHTORDER) else 0)
| (if (o.SEPARATOR == 1) @enumToInt(MENU_ITEM_TYPE.SEPARATOR) else 0)
| (if (o.STRING == 1) @enumToInt(MENU_ITEM_TYPE.STRING) else 0)
);
}
};
pub const MFT_BITMAP = MENU_ITEM_TYPE.BITMAP;
pub const MFT_MENUBARBREAK = MENU_ITEM_TYPE.MENUBARBREAK;
pub const MFT_MENUBREAK = MENU_ITEM_TYPE.MENUBREAK;
pub const MFT_OWNERDRAW = MENU_ITEM_TYPE.OWNERDRAW;
pub const MFT_RADIOCHECK = MENU_ITEM_TYPE.RADIOCHECK;
pub const MFT_RIGHTJUSTIFY = MENU_ITEM_TYPE.RIGHTJUSTIFY;
pub const MFT_RIGHTORDER = MENU_ITEM_TYPE.RIGHTORDER;
pub const MFT_SEPARATOR = MENU_ITEM_TYPE.SEPARATOR;
pub const MFT_STRING = MENU_ITEM_TYPE.STRING;
pub const MESSAGEBOX_RESULT = enum(i32) {
OK = 1,
CANCEL = 2,
ABORT = 3,
RETRY = 4,
IGNORE = 5,
YES = 6,
NO = 7,
CLOSE = 8,
HELP = 9,
TRYAGAIN = 10,
CONTINUE = 11,
ASYNC = 32001,
TIMEOUT = 32000,
};
pub const IDOK = MESSAGEBOX_RESULT.OK;
pub const IDCANCEL = MESSAGEBOX_RESULT.CANCEL;
pub const IDABORT = MESSAGEBOX_RESULT.ABORT;
pub const IDRETRY = MESSAGEBOX_RESULT.RETRY;
pub const IDIGNORE = MESSAGEBOX_RESULT.IGNORE;
pub const IDYES = MESSAGEBOX_RESULT.YES;
pub const IDNO = MESSAGEBOX_RESULT.NO;
pub const IDCLOSE = MESSAGEBOX_RESULT.CLOSE;
pub const IDHELP = MESSAGEBOX_RESULT.HELP;
pub const IDTRYAGAIN = MESSAGEBOX_RESULT.TRYAGAIN;
pub const IDCONTINUE = MESSAGEBOX_RESULT.CONTINUE;
pub const IDASYNC = MESSAGEBOX_RESULT.ASYNC;
pub const IDTIMEOUT = MESSAGEBOX_RESULT.TIMEOUT;
pub const OPEN_FILENAME_FLAGS = enum(u32) {
READONLY = 1,
OVERWRITEPROMPT = 2,
HIDEREADONLY = 4,
NOCHANGEDIR = 8,
SHOWHELP = 16,
ENABLEHOOK = 32,
ENABLETEMPLATE = 64,
ENABLETEMPLATEHANDLE = 128,
NOVALIDATE = 256,
ALLOWMULTISELECT = 512,
EXTENSIONDIFFERENT = 1024,
PATHMUSTEXIST = 2048,
FILEMUSTEXIST = 4096,
CREATEPROMPT = 8192,
SHAREAWARE = 16384,
NOREADONLYRETURN = 32768,
NOTESTFILECREATE = 65536,
NONETWORKBUTTON = 131072,
NOLONGNAMES = 262144,
EXPLORER = 524288,
NODEREFERENCELINKS = 1048576,
LONGNAMES = 2097152,
ENABLEINCLUDENOTIFY = 4194304,
ENABLESIZING = 8388608,
DONTADDTORECENT = 33554432,
FORCESHOWHIDDEN = 268435456,
_,
pub fn initFlags(o: struct {
READONLY: u1 = 0,
OVERWRITEPROMPT: u1 = 0,
HIDEREADONLY: u1 = 0,
NOCHANGEDIR: u1 = 0,
SHOWHELP: u1 = 0,
ENABLEHOOK: u1 = 0,
ENABLETEMPLATE: u1 = 0,
ENABLETEMPLATEHANDLE: u1 = 0,
NOVALIDATE: u1 = 0,
ALLOWMULTISELECT: u1 = 0,
EXTENSIONDIFFERENT: u1 = 0,
PATHMUSTEXIST: u1 = 0,
FILEMUSTEXIST: u1 = 0,
CREATEPROMPT: u1 = 0,
SHAREAWARE: u1 = 0,
NOREADONLYRETURN: u1 = 0,
NOTESTFILECREATE: u1 = 0,
NONETWORKBUTTON: u1 = 0,
NOLONGNAMES: u1 = 0,
EXPLORER: u1 = 0,
NODEREFERENCELINKS: u1 = 0,
LONGNAMES: u1 = 0,
ENABLEINCLUDENOTIFY: u1 = 0,
ENABLESIZING: u1 = 0,
DONTADDTORECENT: u1 = 0,
FORCESHOWHIDDEN: u1 = 0,
}) OPEN_FILENAME_FLAGS {
return @intToEnum(OPEN_FILENAME_FLAGS,
(if (o.READONLY == 1) @enumToInt(OPEN_FILENAME_FLAGS.READONLY) else 0)
| (if (o.OVERWRITEPROMPT == 1) @enumToInt(OPEN_FILENAME_FLAGS.OVERWRITEPROMPT) else 0)
| (if (o.HIDEREADONLY == 1) @enumToInt(OPEN_FILENAME_FLAGS.HIDEREADONLY) else 0)
| (if (o.NOCHANGEDIR == 1) @enumToInt(OPEN_FILENAME_FLAGS.NOCHANGEDIR) else 0)
| (if (o.SHOWHELP == 1) @enumToInt(OPEN_FILENAME_FLAGS.SHOWHELP) else 0)
| (if (o.ENABLEHOOK == 1) @enumToInt(OPEN_FILENAME_FLAGS.ENABLEHOOK) else 0)
| (if (o.ENABLETEMPLATE == 1) @enumToInt(OPEN_FILENAME_FLAGS.ENABLETEMPLATE) else 0)
| (if (o.ENABLETEMPLATEHANDLE == 1) @enumToInt(OPEN_FILENAME_FLAGS.ENABLETEMPLATEHANDLE) else 0)
| (if (o.NOVALIDATE == 1) @enumToInt(OPEN_FILENAME_FLAGS.NOVALIDATE) else 0)
| (if (o.ALLOWMULTISELECT == 1) @enumToInt(OPEN_FILENAME_FLAGS.ALLOWMULTISELECT) else 0)
| (if (o.EXTENSIONDIFFERENT == 1) @enumToInt(OPEN_FILENAME_FLAGS.EXTENSIONDIFFERENT) else 0)
| (if (o.PATHMUSTEXIST == 1) @enumToInt(OPEN_FILENAME_FLAGS.PATHMUSTEXIST) else 0)
| (if (o.FILEMUSTEXIST == 1) @enumToInt(OPEN_FILENAME_FLAGS.FILEMUSTEXIST) else 0)
| (if (o.CREATEPROMPT == 1) @enumToInt(OPEN_FILENAME_FLAGS.CREATEPROMPT) else 0)
| (if (o.SHAREAWARE == 1) @enumToInt(OPEN_FILENAME_FLAGS.SHAREAWARE) else 0)
| (if (o.NOREADONLYRETURN == 1) @enumToInt(OPEN_FILENAME_FLAGS.NOREADONLYRETURN) else 0)
| (if (o.NOTESTFILECREATE == 1) @enumToInt(OPEN_FILENAME_FLAGS.NOTESTFILECREATE) else 0)
| (if (o.NONETWORKBUTTON == 1) @enumToInt(OPEN_FILENAME_FLAGS.NONETWORKBUTTON) else 0)
| (if (o.NOLONGNAMES == 1) @enumToInt(OPEN_FILENAME_FLAGS.NOLONGNAMES) else 0)
| (if (o.EXPLORER == 1) @enumToInt(OPEN_FILENAME_FLAGS.EXPLORER) else 0)
| (if (o.NODEREFERENCELINKS == 1) @enumToInt(OPEN_FILENAME_FLAGS.NODEREFERENCELINKS) else 0)
| (if (o.LONGNAMES == 1) @enumToInt(OPEN_FILENAME_FLAGS.LONGNAMES) else 0)
| (if (o.ENABLEINCLUDENOTIFY == 1) @enumToInt(OPEN_FILENAME_FLAGS.ENABLEINCLUDENOTIFY) else 0)
| (if (o.ENABLESIZING == 1) @enumToInt(OPEN_FILENAME_FLAGS.ENABLESIZING) else 0)
| (if (o.DONTADDTORECENT == 1) @enumToInt(OPEN_FILENAME_FLAGS.DONTADDTORECENT) else 0)
| (if (o.FORCESHOWHIDDEN == 1) @enumToInt(OPEN_FILENAME_FLAGS.FORCESHOWHIDDEN) else 0)
);
}
};
pub const OFN_READONLY = OPEN_FILENAME_FLAGS.READONLY;
pub const OFN_OVERWRITEPROMPT = OPEN_FILENAME_FLAGS.OVERWRITEPROMPT;
pub const OFN_HIDEREADONLY = OPEN_FILENAME_FLAGS.HIDEREADONLY;
pub const OFN_NOCHANGEDIR = OPEN_FILENAME_FLAGS.NOCHANGEDIR;
pub const OFN_SHOWHELP = OPEN_FILENAME_FLAGS.SHOWHELP;
pub const OFN_ENABLEHOOK = OPEN_FILENAME_FLAGS.ENABLEHOOK;
pub const OFN_ENABLETEMPLATE = OPEN_FILENAME_FLAGS.ENABLETEMPLATE;
pub const OFN_ENABLETEMPLATEHANDLE = OPEN_FILENAME_FLAGS.ENABLETEMPLATEHANDLE;
pub const OFN_NOVALIDATE = OPEN_FILENAME_FLAGS.NOVALIDATE;
pub const OFN_ALLOWMULTISELECT = OPEN_FILENAME_FLAGS.ALLOWMULTISELECT;
pub const OFN_EXTENSIONDIFFERENT = OPEN_FILENAME_FLAGS.EXTENSIONDIFFERENT;
pub const OFN_PATHMUSTEXIST = OPEN_FILENAME_FLAGS.PATHMUSTEXIST;
pub const OFN_FILEMUSTEXIST = OPEN_FILENAME_FLAGS.FILEMUSTEXIST;
pub const OFN_CREATEPROMPT = OPEN_FILENAME_FLAGS.CREATEPROMPT;
pub const OFN_SHAREAWARE = OPEN_FILENAME_FLAGS.SHAREAWARE;
pub const OFN_NOREADONLYRETURN = OPEN_FILENAME_FLAGS.NOREADONLYRETURN;
pub const OFN_NOTESTFILECREATE = OPEN_FILENAME_FLAGS.NOTESTFILECREATE;
pub const OFN_NONETWORKBUTTON = OPEN_FILENAME_FLAGS.NONETWORKBUTTON;
pub const OFN_NOLONGNAMES = OPEN_FILENAME_FLAGS.NOLONGNAMES;
pub const OFN_EXPLORER = OPEN_FILENAME_FLAGS.EXPLORER;
pub const OFN_NODEREFERENCELINKS = OPEN_FILENAME_FLAGS.NODEREFERENCELINKS;
pub const OFN_LONGNAMES = OPEN_FILENAME_FLAGS.LONGNAMES;
pub const OFN_ENABLEINCLUDENOTIFY = OPEN_FILENAME_FLAGS.ENABLEINCLUDENOTIFY;
pub const OFN_ENABLESIZING = OPEN_FILENAME_FLAGS.ENABLESIZING;
pub const OFN_DONTADDTORECENT = OPEN_FILENAME_FLAGS.DONTADDTORECENT;
pub const OFN_FORCESHOWHIDDEN = OPEN_FILENAME_FLAGS.FORCESHOWHIDDEN;
pub const OPEN_FILENAME_FLAGS_EX = enum(u32) {
NE = 0,
PLACESBAR = 1,
_,
pub fn initFlags(o: struct {
NE: u1 = 0,
PLACESBAR: u1 = 0,
}) OPEN_FILENAME_FLAGS_EX {
return @intToEnum(OPEN_FILENAME_FLAGS_EX,
(if (o.NE == 1) @enumToInt(OPEN_FILENAME_FLAGS_EX.NE) else 0)
| (if (o.PLACESBAR == 1) @enumToInt(OPEN_FILENAME_FLAGS_EX.PLACESBAR) else 0)
);
}
};
pub const OFN_EX_NONE = OPEN_FILENAME_FLAGS_EX.NE;
pub const OFN_EX_NOPLACESBAR = OPEN_FILENAME_FLAGS_EX.PLACESBAR;
pub const MENU_ITEM_STATE = enum(u32) {
GRAYED = 3,
// DISABLED = 3, this enum value conflicts with GRAYED
CHECKED = 8,
HILITE = 128,
ENABLED = 0,
// UNCHECKED = 0, this enum value conflicts with ENABLED
// UNHILITE = 0, this enum value conflicts with ENABLED
DEFAULT = 4096,
_,
pub fn initFlags(o: struct {
GRAYED: u1 = 0,
CHECKED: u1 = 0,
HILITE: u1 = 0,
ENABLED: u1 = 0,
DEFAULT: u1 = 0,
}) MENU_ITEM_STATE {
return @intToEnum(MENU_ITEM_STATE,
(if (o.GRAYED == 1) @enumToInt(MENU_ITEM_STATE.GRAYED) else 0)
| (if (o.CHECKED == 1) @enumToInt(MENU_ITEM_STATE.CHECKED) else 0)
| (if (o.HILITE == 1) @enumToInt(MENU_ITEM_STATE.HILITE) else 0)
| (if (o.ENABLED == 1) @enumToInt(MENU_ITEM_STATE.ENABLED) else 0)
| (if (o.DEFAULT == 1) @enumToInt(MENU_ITEM_STATE.DEFAULT) else 0)
);
}
};
pub const MFS_GRAYED = MENU_ITEM_STATE.GRAYED;
pub const MFS_DISABLED = MENU_ITEM_STATE.GRAYED;
pub const MFS_CHECKED = MENU_ITEM_STATE.CHECKED;
pub const MFS_HILITE = MENU_ITEM_STATE.HILITE;
pub const MFS_ENABLED = MENU_ITEM_STATE.ENABLED;
pub const MFS_UNCHECKED = MENU_ITEM_STATE.ENABLED;
pub const MFS_UNHILITE = MENU_ITEM_STATE.ENABLED;
pub const MFS_DEFAULT = MENU_ITEM_STATE.DEFAULT;
pub const GET_CLASS_LONG_INDEX = enum(i32) {
W_ATOM = -32,
L_CBCLSEXTRA = -20,
L_CBWNDEXTRA = -18,
L_HBRBACKGROUND = -10,
L_HCURSOR = -12,
L_HICON = -14,
L_HICONSM = -34,
L_HMODULE = -16,
L_MENUNAME = -8,
L_STYLE = -26,
L_WNDPROC = -24,
// LP_HBRBACKGROUND = -10, this enum value conflicts with L_HBRBACKGROUND
// LP_HCURSOR = -12, this enum value conflicts with L_HCURSOR
// LP_HICON = -14, this enum value conflicts with L_HICON
// LP_HICONSM = -34, this enum value conflicts with L_HICONSM
// LP_HMODULE = -16, this enum value conflicts with L_HMODULE
// LP_MENUNAME = -8, this enum value conflicts with L_MENUNAME
// LP_WNDPROC = -24, this enum value conflicts with L_WNDPROC
};
pub const GCW_ATOM = GET_CLASS_LONG_INDEX.W_ATOM;
pub const GCL_CBCLSEXTRA = GET_CLASS_LONG_INDEX.L_CBCLSEXTRA;
pub const GCL_CBWNDEXTRA = GET_CLASS_LONG_INDEX.L_CBWNDEXTRA;
pub const GCL_HBRBACKGROUND = GET_CLASS_LONG_INDEX.L_HBRBACKGROUND;
pub const GCL_HCURSOR = GET_CLASS_LONG_INDEX.L_HCURSOR;
pub const GCL_HICON = GET_CLASS_LONG_INDEX.L_HICON;
pub const GCL_HICONSM = GET_CLASS_LONG_INDEX.L_HICONSM;
pub const GCL_HMODULE = GET_CLASS_LONG_INDEX.L_HMODULE;
pub const GCL_MENUNAME = GET_CLASS_LONG_INDEX.L_MENUNAME;
pub const GCL_STYLE = GET_CLASS_LONG_INDEX.L_STYLE;
pub const GCL_WNDPROC = GET_CLASS_LONG_INDEX.L_WNDPROC;
pub const GCLP_HBRBACKGROUND = GET_CLASS_LONG_INDEX.L_HBRBACKGROUND;
pub const GCLP_HCURSOR = GET_CLASS_LONG_INDEX.L_HCURSOR;
pub const GCLP_HICON = GET_CLASS_LONG_INDEX.L_HICON;
pub const GCLP_HICONSM = GET_CLASS_LONG_INDEX.L_HICONSM;
pub const GCLP_HMODULE = GET_CLASS_LONG_INDEX.L_HMODULE;
pub const GCLP_MENUNAME = GET_CLASS_LONG_INDEX.L_MENUNAME;
pub const GCLP_WNDPROC = GET_CLASS_LONG_INDEX.L_WNDPROC;
pub const BROADCAST_SYSTEM_MESSAGE_FLAGS = enum(u32) {
ALLOWSFW = 128,
FLUSHDISK = 4,
FORCEIFHUNG = 32,
IGNORECURRENTTASK = 2,
NOHANG = 8,
NOTIMEOUTIFNOTHUNG = 64,
POSTMESSAGE = 16,
QUERY = 1,
SENDNOTIFYMESSAGE = 256,
LUID = 1024,
RETURNHDESK = 512,
_,
pub fn initFlags(o: struct {
ALLOWSFW: u1 = 0,
FLUSHDISK: u1 = 0,
FORCEIFHUNG: u1 = 0,
IGNORECURRENTTASK: u1 = 0,
NOHANG: u1 = 0,
NOTIMEOUTIFNOTHUNG: u1 = 0,
POSTMESSAGE: u1 = 0,
QUERY: u1 = 0,
SENDNOTIFYMESSAGE: u1 = 0,
LUID: u1 = 0,
RETURNHDESK: u1 = 0,
}) BROADCAST_SYSTEM_MESSAGE_FLAGS {
return @intToEnum(BROADCAST_SYSTEM_MESSAGE_FLAGS,
(if (o.ALLOWSFW == 1) @enumToInt(BROADCAST_SYSTEM_MESSAGE_FLAGS.ALLOWSFW) else 0)
| (if (o.FLUSHDISK == 1) @enumToInt(BROADCAST_SYSTEM_MESSAGE_FLAGS.FLUSHDISK) else 0)
| (if (o.FORCEIFHUNG == 1) @enumToInt(BROADCAST_SYSTEM_MESSAGE_FLAGS.FORCEIFHUNG) else 0)
| (if (o.IGNORECURRENTTASK == 1) @enumToInt(BROADCAST_SYSTEM_MESSAGE_FLAGS.IGNORECURRENTTASK) else 0)
| (if (o.NOHANG == 1) @enumToInt(BROADCAST_SYSTEM_MESSAGE_FLAGS.NOHANG) else 0)
| (if (o.NOTIMEOUTIFNOTHUNG == 1) @enumToInt(BROADCAST_SYSTEM_MESSAGE_FLAGS.NOTIMEOUTIFNOTHUNG) else 0)
| (if (o.POSTMESSAGE == 1) @enumToInt(BROADCAST_SYSTEM_MESSAGE_FLAGS.POSTMESSAGE) else 0)
| (if (o.QUERY == 1) @enumToInt(BROADCAST_SYSTEM_MESSAGE_FLAGS.QUERY) else 0)
| (if (o.SENDNOTIFYMESSAGE == 1) @enumToInt(BROADCAST_SYSTEM_MESSAGE_FLAGS.SENDNOTIFYMESSAGE) else 0)
| (if (o.LUID == 1) @enumToInt(BROADCAST_SYSTEM_MESSAGE_FLAGS.LUID) else 0)
| (if (o.RETURNHDESK == 1) @enumToInt(BROADCAST_SYSTEM_MESSAGE_FLAGS.RETURNHDESK) else 0)
);
}
};
pub const BSF_ALLOWSFW = BROADCAST_SYSTEM_MESSAGE_FLAGS.ALLOWSFW;
pub const BSF_FLUSHDISK = BROADCAST_SYSTEM_MESSAGE_FLAGS.FLUSHDISK;
pub const BSF_FORCEIFHUNG = BROADCAST_SYSTEM_MESSAGE_FLAGS.FORCEIFHUNG;
pub const BSF_IGNORECURRENTTASK = BROADCAST_SYSTEM_MESSAGE_FLAGS.IGNORECURRENTTASK;
pub const BSF_NOHANG = BROADCAST_SYSTEM_MESSAGE_FLAGS.NOHANG;
pub const BSF_NOTIMEOUTIFNOTHUNG = BROADCAST_SYSTEM_MESSAGE_FLAGS.NOTIMEOUTIFNOTHUNG;
pub const BSF_POSTMESSAGE = BROADCAST_SYSTEM_MESSAGE_FLAGS.POSTMESSAGE;
pub const BSF_QUERY = BROADCAST_SYSTEM_MESSAGE_FLAGS.QUERY;
pub const BSF_SENDNOTIFYMESSAGE = BROADCAST_SYSTEM_MESSAGE_FLAGS.SENDNOTIFYMESSAGE;
pub const BSF_LUID = BROADCAST_SYSTEM_MESSAGE_FLAGS.LUID;
pub const BSF_RETURNHDESK = BROADCAST_SYSTEM_MESSAGE_FLAGS.RETURNHDESK;
pub const UPDATE_LAYERED_WINDOW_FLAGS = enum(u32) {
ALPHA = 2,
COLORKEY = 1,
OPAQUE = 4,
EX_NORESIZE = 8,
};
pub const ULW_ALPHA = UPDATE_LAYERED_WINDOW_FLAGS.ALPHA;
pub const ULW_COLORKEY = UPDATE_LAYERED_WINDOW_FLAGS.COLORKEY;
pub const ULW_OPAQUE = UPDATE_LAYERED_WINDOW_FLAGS.OPAQUE;
pub const ULW_EX_NORESIZE = UPDATE_LAYERED_WINDOW_FLAGS.EX_NORESIZE;
pub const WINDOW_LONG_PTR_INDEX = enum(i32) {
_EXSTYLE = -20,
P_HINSTANCE = -6,
P_HWNDPARENT = -8,
P_ID = -12,
_STYLE = -16,
P_USERDATA = -21,
P_WNDPROC = -4,
// _HINSTANCE = -6, this enum value conflicts with P_HINSTANCE
// _ID = -12, this enum value conflicts with P_ID
// _USERDATA = -21, this enum value conflicts with P_USERDATA
// _WNDPROC = -4, this enum value conflicts with P_WNDPROC
// _HWNDPARENT = -8, this enum value conflicts with P_HWNDPARENT
_,
};
pub const GWL_EXSTYLE = WINDOW_LONG_PTR_INDEX._EXSTYLE;
pub const GWLP_HINSTANCE = WINDOW_LONG_PTR_INDEX.P_HINSTANCE;
pub const GWLP_HWNDPARENT = WINDOW_LONG_PTR_INDEX.P_HWNDPARENT;
pub const GWLP_ID = WINDOW_LONG_PTR_INDEX.P_ID;
pub const GWL_STYLE = WINDOW_LONG_PTR_INDEX._STYLE;
pub const GWLP_USERDATA = WINDOW_LONG_PTR_INDEX.P_USERDATA;
pub const GWLP_WNDPROC = WINDOW_LONG_PTR_INDEX.P_WNDPROC;
pub const GWL_HINSTANCE = WINDOW_LONG_PTR_INDEX.P_HINSTANCE;
pub const GWL_ID = WINDOW_LONG_PTR_INDEX.P_ID;
pub const GWL_USERDATA = WINDOW_LONG_PTR_INDEX.P_USERDATA;
pub const GWL_WNDPROC = WINDOW_LONG_PTR_INDEX.P_WNDPROC;
pub const GWL_HWNDPARENT = WINDOW_LONG_PTR_INDEX.P_HWNDPARENT;
pub const ANIMATE_WINDOW_FLAGS = enum(u32) {
ACTIVATE = 131072,
BLEND = 524288,
CENTER = 16,
HIDE = 65536,
HOR_POSITIVE = 1,
HOR_NEGATIVE = 2,
SLIDE = 262144,
VER_POSITIVE = 4,
VER_NEGATIVE = 8,
_,
pub fn initFlags(o: struct {
ACTIVATE: u1 = 0,
BLEND: u1 = 0,
CENTER: u1 = 0,
HIDE: u1 = 0,
HOR_POSITIVE: u1 = 0,
HOR_NEGATIVE: u1 = 0,
SLIDE: u1 = 0,
VER_POSITIVE: u1 = 0,
VER_NEGATIVE: u1 = 0,
}) ANIMATE_WINDOW_FLAGS {
return @intToEnum(ANIMATE_WINDOW_FLAGS,
(if (o.ACTIVATE == 1) @enumToInt(ANIMATE_WINDOW_FLAGS.ACTIVATE) else 0)
| (if (o.BLEND == 1) @enumToInt(ANIMATE_WINDOW_FLAGS.BLEND) else 0)
| (if (o.CENTER == 1) @enumToInt(ANIMATE_WINDOW_FLAGS.CENTER) else 0)
| (if (o.HIDE == 1) @enumToInt(ANIMATE_WINDOW_FLAGS.HIDE) else 0)
| (if (o.HOR_POSITIVE == 1) @enumToInt(ANIMATE_WINDOW_FLAGS.HOR_POSITIVE) else 0)
| (if (o.HOR_NEGATIVE == 1) @enumToInt(ANIMATE_WINDOW_FLAGS.HOR_NEGATIVE) else 0)
| (if (o.SLIDE == 1) @enumToInt(ANIMATE_WINDOW_FLAGS.SLIDE) else 0)
| (if (o.VER_POSITIVE == 1) @enumToInt(ANIMATE_WINDOW_FLAGS.VER_POSITIVE) else 0)
| (if (o.VER_NEGATIVE == 1) @enumToInt(ANIMATE_WINDOW_FLAGS.VER_NEGATIVE) else 0)
);
}
};
pub const AW_ACTIVATE = ANIMATE_WINDOW_FLAGS.ACTIVATE;
pub const AW_BLEND = ANIMATE_WINDOW_FLAGS.BLEND;
pub const AW_CENTER = ANIMATE_WINDOW_FLAGS.CENTER;
pub const AW_HIDE = ANIMATE_WINDOW_FLAGS.HIDE;
pub const AW_HOR_POSITIVE = ANIMATE_WINDOW_FLAGS.HOR_POSITIVE;
pub const AW_HOR_NEGATIVE = ANIMATE_WINDOW_FLAGS.HOR_NEGATIVE;
pub const AW_SLIDE = ANIMATE_WINDOW_FLAGS.SLIDE;
pub const AW_VER_POSITIVE = ANIMATE_WINDOW_FLAGS.VER_POSITIVE;
pub const AW_VER_NEGATIVE = ANIMATE_WINDOW_FLAGS.VER_NEGATIVE;
pub const CHANGE_WINDOW_MESSAGE_FILTER_FLAGS = enum(u32) {
ADD = 1,
REMOVE = 2,
};
pub const MSGFLT_ADD = CHANGE_WINDOW_MESSAGE_FILTER_FLAGS.ADD;
pub const MSGFLT_REMOVE = CHANGE_WINDOW_MESSAGE_FILTER_FLAGS.REMOVE;
pub const GDI_IMAGE_TYPE = enum(u32) {
BITMAP = 0,
CURSOR = 2,
ICON = 1,
};
pub const IMAGE_BITMAP = GDI_IMAGE_TYPE.BITMAP;
pub const IMAGE_CURSOR = GDI_IMAGE_TYPE.CURSOR;
pub const IMAGE_ICON = GDI_IMAGE_TYPE.ICON;
pub const WINDOWS_HOOK_ID = enum(i32) {
CALLWNDPROC = 4,
CALLWNDPROCRET = 12,
CBT = 5,
DEBUG = 9,
FOREGROUNDIDLE = 11,
GETMESSAGE = 3,
JOURNALPLAYBACK = 1,
JOURNALRECORD = 0,
KEYBOARD = 2,
KEYBOARD_LL = 13,
MOUSE = 7,
MOUSE_LL = 14,
MSGFILTER = -1,
SHELL = 10,
SYSMSGFILTER = 6,
};
pub const WH_CALLWNDPROC = WINDOWS_HOOK_ID.CALLWNDPROC;
pub const WH_CALLWNDPROCRET = WINDOWS_HOOK_ID.CALLWNDPROCRET;
pub const WH_CBT = WINDOWS_HOOK_ID.CBT;
pub const WH_DEBUG = WINDOWS_HOOK_ID.DEBUG;
pub const WH_FOREGROUNDIDLE = WINDOWS_HOOK_ID.FOREGROUNDIDLE;
pub const WH_GETMESSAGE = WINDOWS_HOOK_ID.GETMESSAGE;
pub const WH_JOURNALPLAYBACK = WINDOWS_HOOK_ID.JOURNALPLAYBACK;
pub const WH_JOURNALRECORD = WINDOWS_HOOK_ID.JOURNALRECORD;
pub const WH_KEYBOARD = WINDOWS_HOOK_ID.KEYBOARD;
pub const WH_KEYBOARD_LL = WINDOWS_HOOK_ID.KEYBOARD_LL;
pub const WH_MOUSE = WINDOWS_HOOK_ID.MOUSE;
pub const WH_MOUSE_LL = WINDOWS_HOOK_ID.MOUSE_LL;
pub const WH_MSGFILTER = WINDOWS_HOOK_ID.MSGFILTER;
pub const WH_SHELL = WINDOWS_HOOK_ID.SHELL;
pub const WH_SYSMSGFILTER = WINDOWS_HOOK_ID.SYSMSGFILTER;
pub const BROADCAST_SYSTEM_MESSAGE_INFO = enum(u32) {
LLCOMPONENTS = 0,
LLDESKTOPS = 16,
PPLICATIONS = 8,
_,
pub fn initFlags(o: struct {
LLCOMPONENTS: u1 = 0,
LLDESKTOPS: u1 = 0,
PPLICATIONS: u1 = 0,
}) BROADCAST_SYSTEM_MESSAGE_INFO {
return @intToEnum(BROADCAST_SYSTEM_MESSAGE_INFO,
(if (o.LLCOMPONENTS == 1) @enumToInt(BROADCAST_SYSTEM_MESSAGE_INFO.LLCOMPONENTS) else 0)
| (if (o.LLDESKTOPS == 1) @enumToInt(BROADCAST_SYSTEM_MESSAGE_INFO.LLDESKTOPS) else 0)
| (if (o.PPLICATIONS == 1) @enumToInt(BROADCAST_SYSTEM_MESSAGE_INFO.PPLICATIONS) else 0)
);
}
};
pub const BSM_ALLCOMPONENTS = BROADCAST_SYSTEM_MESSAGE_INFO.LLCOMPONENTS;
pub const BSM_ALLDESKTOPS = BROADCAST_SYSTEM_MESSAGE_INFO.LLDESKTOPS;
pub const BSM_APPLICATIONS = BROADCAST_SYSTEM_MESSAGE_INFO.PPLICATIONS;
pub const SYSTEM_PARAMETERS_INFO_UPDATE_FLAGS = enum(u32) {
UPDATEINIFILE = 1,
SENDCHANGE = 2,
// SENDWININICHANGE = 2, this enum value conflicts with SENDCHANGE
_,
pub fn initFlags(o: struct {
UPDATEINIFILE: u1 = 0,
SENDCHANGE: u1 = 0,
}) SYSTEM_PARAMETERS_INFO_UPDATE_FLAGS {
return @intToEnum(SYSTEM_PARAMETERS_INFO_UPDATE_FLAGS,
(if (o.UPDATEINIFILE == 1) @enumToInt(SYSTEM_PARAMETERS_INFO_UPDATE_FLAGS.UPDATEINIFILE) else 0)
| (if (o.SENDCHANGE == 1) @enumToInt(SYSTEM_PARAMETERS_INFO_UPDATE_FLAGS.SENDCHANGE) else 0)
);
}
};
pub const SPIF_UPDATEINIFILE = SYSTEM_PARAMETERS_INFO_UPDATE_FLAGS.UPDATEINIFILE;
pub const SPIF_SENDCHANGE = SYSTEM_PARAMETERS_INFO_UPDATE_FLAGS.SENDCHANGE;
pub const SPIF_SENDWININICHANGE = SYSTEM_PARAMETERS_INFO_UPDATE_FLAGS.SENDCHANGE;
pub const SET_WINDOW_POS_FLAGS = enum(u32) {
ASYNCWINDOWPOS = 16384,
DEFERERASE = 8192,
DRAWFRAME = 32,
// FRAMECHANGED = 32, this enum value conflicts with DRAWFRAME
HIDEWINDOW = 128,
NOACTIVATE = 16,
NOCOPYBITS = 256,
NOMOVE = 2,
NOOWNERZORDER = 512,
NOREDRAW = 8,
// NOREPOSITION = 512, this enum value conflicts with NOOWNERZORDER
NOSENDCHANGING = 1024,
NOSIZE = 1,
NOZORDER = 4,
SHOWWINDOW = 64,
// _NOOWNERZORDER = 512, this enum value conflicts with NOOWNERZORDER
_,
pub fn initFlags(o: struct {
ASYNCWINDOWPOS: u1 = 0,
DEFERERASE: u1 = 0,
DRAWFRAME: u1 = 0,
HIDEWINDOW: u1 = 0,
NOACTIVATE: u1 = 0,
NOCOPYBITS: u1 = 0,
NOMOVE: u1 = 0,
NOOWNERZORDER: u1 = 0,
NOREDRAW: u1 = 0,
NOSENDCHANGING: u1 = 0,
NOSIZE: u1 = 0,
NOZORDER: u1 = 0,
SHOWWINDOW: u1 = 0,
}) SET_WINDOW_POS_FLAGS {
return @intToEnum(SET_WINDOW_POS_FLAGS,
(if (o.ASYNCWINDOWPOS == 1) @enumToInt(SET_WINDOW_POS_FLAGS.ASYNCWINDOWPOS) else 0)
| (if (o.DEFERERASE == 1) @enumToInt(SET_WINDOW_POS_FLAGS.DEFERERASE) else 0)
| (if (o.DRAWFRAME == 1) @enumToInt(SET_WINDOW_POS_FLAGS.DRAWFRAME) else 0)
| (if (o.HIDEWINDOW == 1) @enumToInt(SET_WINDOW_POS_FLAGS.HIDEWINDOW) else 0)
| (if (o.NOACTIVATE == 1) @enumToInt(SET_WINDOW_POS_FLAGS.NOACTIVATE) else 0)
| (if (o.NOCOPYBITS == 1) @enumToInt(SET_WINDOW_POS_FLAGS.NOCOPYBITS) else 0)
| (if (o.NOMOVE == 1) @enumToInt(SET_WINDOW_POS_FLAGS.NOMOVE) else 0)
| (if (o.NOOWNERZORDER == 1) @enumToInt(SET_WINDOW_POS_FLAGS.NOOWNERZORDER) else 0)
| (if (o.NOREDRAW == 1) @enumToInt(SET_WINDOW_POS_FLAGS.NOREDRAW) else 0)
| (if (o.NOSENDCHANGING == 1) @enumToInt(SET_WINDOW_POS_FLAGS.NOSENDCHANGING) else 0)
| (if (o.NOSIZE == 1) @enumToInt(SET_WINDOW_POS_FLAGS.NOSIZE) else 0)
| (if (o.NOZORDER == 1) @enumToInt(SET_WINDOW_POS_FLAGS.NOZORDER) else 0)
| (if (o.SHOWWINDOW == 1) @enumToInt(SET_WINDOW_POS_FLAGS.SHOWWINDOW) else 0)
);
}
};
pub const SWP_ASYNCWINDOWPOS = SET_WINDOW_POS_FLAGS.ASYNCWINDOWPOS;
pub const SWP_DEFERERASE = SET_WINDOW_POS_FLAGS.DEFERERASE;
pub const SWP_DRAWFRAME = SET_WINDOW_POS_FLAGS.DRAWFRAME;
pub const SWP_FRAMECHANGED = SET_WINDOW_POS_FLAGS.DRAWFRAME;
pub const SWP_HIDEWINDOW = SET_WINDOW_POS_FLAGS.HIDEWINDOW;
pub const SWP_NOACTIVATE = SET_WINDOW_POS_FLAGS.NOACTIVATE;
pub const SWP_NOCOPYBITS = SET_WINDOW_POS_FLAGS.NOCOPYBITS;
pub const SWP_NOMOVE = SET_WINDOW_POS_FLAGS.NOMOVE;
pub const SWP_NOOWNERZORDER = SET_WINDOW_POS_FLAGS.NOOWNERZORDER;
pub const SWP_NOREDRAW = SET_WINDOW_POS_FLAGS.NOREDRAW;
pub const SWP_NOREPOSITION = SET_WINDOW_POS_FLAGS.NOOWNERZORDER;
pub const SWP_NOSENDCHANGING = SET_WINDOW_POS_FLAGS.NOSENDCHANGING;
pub const SWP_NOSIZE = SET_WINDOW_POS_FLAGS.NOSIZE;
pub const SWP_NOZORDER = SET_WINDOW_POS_FLAGS.NOZORDER;
pub const SWP_SHOWWINDOW = SET_WINDOW_POS_FLAGS.SHOWWINDOW;
pub const SWP__NOOWNERZORDER = SET_WINDOW_POS_FLAGS.NOOWNERZORDER;
pub const QUEUE_STATUS_FLAGS = enum(u32) {
ALLEVENTS = 1215,
ALLINPUT = 1279,
ALLPOSTMESSAGE = 256,
HOTKEY = 128,
INPUT = 1031,
KEY = 1,
MOUSE = 6,
MOUSEBUTTON = 4,
MOUSEMOVE = 2,
PAINT = 32,
POSTMESSAGE = 8,
RAWINPUT = 1024,
SENDMESSAGE = 64,
TIMER = 16,
_,
pub fn initFlags(o: struct {
ALLEVENTS: u1 = 0,
ALLINPUT: u1 = 0,
ALLPOSTMESSAGE: u1 = 0,
HOTKEY: u1 = 0,
INPUT: u1 = 0,
KEY: u1 = 0,
MOUSE: u1 = 0,
MOUSEBUTTON: u1 = 0,
MOUSEMOVE: u1 = 0,
PAINT: u1 = 0,
POSTMESSAGE: u1 = 0,
RAWINPUT: u1 = 0,
SENDMESSAGE: u1 = 0,
TIMER: u1 = 0,
}) QUEUE_STATUS_FLAGS {
return @intToEnum(QUEUE_STATUS_FLAGS,
(if (o.ALLEVENTS == 1) @enumToInt(QUEUE_STATUS_FLAGS.ALLEVENTS) else 0)
| (if (o.ALLINPUT == 1) @enumToInt(QUEUE_STATUS_FLAGS.ALLINPUT) else 0)
| (if (o.ALLPOSTMESSAGE == 1) @enumToInt(QUEUE_STATUS_FLAGS.ALLPOSTMESSAGE) else 0)
| (if (o.HOTKEY == 1) @enumToInt(QUEUE_STATUS_FLAGS.HOTKEY) else 0)
| (if (o.INPUT == 1) @enumToInt(QUEUE_STATUS_FLAGS.INPUT) else 0)
| (if (o.KEY == 1) @enumToInt(QUEUE_STATUS_FLAGS.KEY) else 0)
| (if (o.MOUSE == 1) @enumToInt(QUEUE_STATUS_FLAGS.MOUSE) else 0)
| (if (o.MOUSEBUTTON == 1) @enumToInt(QUEUE_STATUS_FLAGS.MOUSEBUTTON) else 0)
| (if (o.MOUSEMOVE == 1) @enumToInt(QUEUE_STATUS_FLAGS.MOUSEMOVE) else 0)
| (if (o.PAINT == 1) @enumToInt(QUEUE_STATUS_FLAGS.PAINT) else 0)
| (if (o.POSTMESSAGE == 1) @enumToInt(QUEUE_STATUS_FLAGS.POSTMESSAGE) else 0)
| (if (o.RAWINPUT == 1) @enumToInt(QUEUE_STATUS_FLAGS.RAWINPUT) else 0)
| (if (o.SENDMESSAGE == 1) @enumToInt(QUEUE_STATUS_FLAGS.SENDMESSAGE) else 0)
| (if (o.TIMER == 1) @enumToInt(QUEUE_STATUS_FLAGS.TIMER) else 0)
);
}
};
pub const QS_ALLEVENTS = QUEUE_STATUS_FLAGS.ALLEVENTS;
pub const QS_ALLINPUT = QUEUE_STATUS_FLAGS.ALLINPUT;
pub const QS_ALLPOSTMESSAGE = QUEUE_STATUS_FLAGS.ALLPOSTMESSAGE;
pub const QS_HOTKEY = QUEUE_STATUS_FLAGS.HOTKEY;
pub const QS_INPUT = QUEUE_STATUS_FLAGS.INPUT;
pub const QS_KEY = QUEUE_STATUS_FLAGS.KEY;
pub const QS_MOUSE = QUEUE_STATUS_FLAGS.MOUSE;
pub const QS_MOUSEBUTTON = QUEUE_STATUS_FLAGS.MOUSEBUTTON;
pub const QS_MOUSEMOVE = QUEUE_STATUS_FLAGS.MOUSEMOVE;
pub const QS_PAINT = QUEUE_STATUS_FLAGS.PAINT;
pub const QS_POSTMESSAGE = QUEUE_STATUS_FLAGS.POSTMESSAGE;
pub const QS_RAWINPUT = QUEUE_STATUS_FLAGS.RAWINPUT;
pub const QS_SENDMESSAGE = QUEUE_STATUS_FLAGS.SENDMESSAGE;
pub const QS_TIMER = QUEUE_STATUS_FLAGS.TIMER;
pub const SYSTEM_CURSOR_ID = enum(u32) {
APPSTARTING = 32650,
NORMAL = 32512,
CROSS = 32515,
HAND = 32649,
HELP = 32651,
IBEAM = 32513,
NO = 32648,
SIZEALL = 32646,
SIZENESW = 32643,
SIZENS = 32645,
SIZENWSE = 32642,
SIZEWE = 32644,
UP = 32516,
WAIT = 32514,
};
pub const OCR_APPSTARTING = SYSTEM_CURSOR_ID.APPSTARTING;
pub const OCR_NORMAL = SYSTEM_CURSOR_ID.NORMAL;
pub const OCR_CROSS = SYSTEM_CURSOR_ID.CROSS;
pub const OCR_HAND = SYSTEM_CURSOR_ID.HAND;
pub const OCR_HELP = SYSTEM_CURSOR_ID.HELP;
pub const OCR_IBEAM = SYSTEM_CURSOR_ID.IBEAM;
pub const OCR_NO = SYSTEM_CURSOR_ID.NO;
pub const OCR_SIZEALL = SYSTEM_CURSOR_ID.SIZEALL;
pub const OCR_SIZENESW = SYSTEM_CURSOR_ID.SIZENESW;
pub const OCR_SIZENS = SYSTEM_CURSOR_ID.SIZENS;
pub const OCR_SIZENWSE = SYSTEM_CURSOR_ID.SIZENWSE;
pub const OCR_SIZEWE = SYSTEM_CURSOR_ID.SIZEWE;
pub const OCR_UP = SYSTEM_CURSOR_ID.UP;
pub const OCR_WAIT = SYSTEM_CURSOR_ID.WAIT;
pub const LAYERED_WINDOW_ATTRIBUTES_FLAGS = enum(u32) {
ALPHA = 2,
COLORKEY = 1,
_,
pub fn initFlags(o: struct {
ALPHA: u1 = 0,
COLORKEY: u1 = 0,
}) LAYERED_WINDOW_ATTRIBUTES_FLAGS {
return @intToEnum(LAYERED_WINDOW_ATTRIBUTES_FLAGS,
(if (o.ALPHA == 1) @enumToInt(LAYERED_WINDOW_ATTRIBUTES_FLAGS.ALPHA) else 0)
| (if (o.COLORKEY == 1) @enumToInt(LAYERED_WINDOW_ATTRIBUTES_FLAGS.COLORKEY) else 0)
);
}
};
pub const LWA_ALPHA = LAYERED_WINDOW_ATTRIBUTES_FLAGS.ALPHA;
pub const LWA_COLORKEY = LAYERED_WINDOW_ATTRIBUTES_FLAGS.COLORKEY;
pub const SEND_MESSAGE_TIMEOUT_FLAGS = enum(u32) {
ABORTIFHUNG = 2,
BLOCK = 1,
NORMAL = 0,
NOTIMEOUTIFNOTHUNG = 8,
ERRORONEXIT = 32,
_,
pub fn initFlags(o: struct {
ABORTIFHUNG: u1 = 0,
BLOCK: u1 = 0,
NORMAL: u1 = 0,
NOTIMEOUTIFNOTHUNG: u1 = 0,
ERRORONEXIT: u1 = 0,
}) SEND_MESSAGE_TIMEOUT_FLAGS {
return @intToEnum(SEND_MESSAGE_TIMEOUT_FLAGS,
(if (o.ABORTIFHUNG == 1) @enumToInt(SEND_MESSAGE_TIMEOUT_FLAGS.ABORTIFHUNG) else 0)
| (if (o.BLOCK == 1) @enumToInt(SEND_MESSAGE_TIMEOUT_FLAGS.BLOCK) else 0)
| (if (o.NORMAL == 1) @enumToInt(SEND_MESSAGE_TIMEOUT_FLAGS.NORMAL) else 0)
| (if (o.NOTIMEOUTIFNOTHUNG == 1) @enumToInt(SEND_MESSAGE_TIMEOUT_FLAGS.NOTIMEOUTIFNOTHUNG) else 0)
| (if (o.ERRORONEXIT == 1) @enumToInt(SEND_MESSAGE_TIMEOUT_FLAGS.ERRORONEXIT) else 0)
);
}
};
pub const SMTO_ABORTIFHUNG = SEND_MESSAGE_TIMEOUT_FLAGS.ABORTIFHUNG;
pub const SMTO_BLOCK = SEND_MESSAGE_TIMEOUT_FLAGS.BLOCK;
pub const SMTO_NORMAL = SEND_MESSAGE_TIMEOUT_FLAGS.NORMAL;
pub const SMTO_NOTIMEOUTIFNOTHUNG = SEND_MESSAGE_TIMEOUT_FLAGS.NOTIMEOUTIFNOTHUNG;
pub const SMTO_ERRORONEXIT = SEND_MESSAGE_TIMEOUT_FLAGS.ERRORONEXIT;
pub const PEEK_MESSAGE_REMOVE_TYPE = enum(u32) {
NOREMOVE = 0,
REMOVE = 1,
NOYIELD = 2,
QS_INPUT = 67567616,
QS_POSTMESSAGE = 9961472,
QS_PAINT = 2097152,
QS_SENDMESSAGE = 4194304,
_,
pub fn initFlags(o: struct {
NOREMOVE: u1 = 0,
REMOVE: u1 = 0,
NOYIELD: u1 = 0,
QS_INPUT: u1 = 0,
QS_POSTMESSAGE: u1 = 0,
QS_PAINT: u1 = 0,
QS_SENDMESSAGE: u1 = 0,
}) PEEK_MESSAGE_REMOVE_TYPE {
return @intToEnum(PEEK_MESSAGE_REMOVE_TYPE,
(if (o.NOREMOVE == 1) @enumToInt(PEEK_MESSAGE_REMOVE_TYPE.NOREMOVE) else 0)
| (if (o.REMOVE == 1) @enumToInt(PEEK_MESSAGE_REMOVE_TYPE.REMOVE) else 0)
| (if (o.NOYIELD == 1) @enumToInt(PEEK_MESSAGE_REMOVE_TYPE.NOYIELD) else 0)
| (if (o.QS_INPUT == 1) @enumToInt(PEEK_MESSAGE_REMOVE_TYPE.QS_INPUT) else 0)
| (if (o.QS_POSTMESSAGE == 1) @enumToInt(PEEK_MESSAGE_REMOVE_TYPE.QS_POSTMESSAGE) else 0)
| (if (o.QS_PAINT == 1) @enumToInt(PEEK_MESSAGE_REMOVE_TYPE.QS_PAINT) else 0)
| (if (o.QS_SENDMESSAGE == 1) @enumToInt(PEEK_MESSAGE_REMOVE_TYPE.QS_SENDMESSAGE) else 0)
);
}
};
pub const PM_NOREMOVE = PEEK_MESSAGE_REMOVE_TYPE.NOREMOVE;
pub const PM_REMOVE = PEEK_MESSAGE_REMOVE_TYPE.REMOVE;
pub const PM_NOYIELD = PEEK_MESSAGE_REMOVE_TYPE.NOYIELD;
pub const PM_QS_INPUT = PEEK_MESSAGE_REMOVE_TYPE.QS_INPUT;
pub const PM_QS_POSTMESSAGE = PEEK_MESSAGE_REMOVE_TYPE.QS_POSTMESSAGE;
pub const PM_QS_PAINT = PEEK_MESSAGE_REMOVE_TYPE.QS_PAINT;
pub const PM_QS_SENDMESSAGE = PEEK_MESSAGE_REMOVE_TYPE.QS_SENDMESSAGE;
pub const SYS_COLOR_INDEX = enum(u32) {
COLOR_3DDKSHADOW = 21,
COLOR_3DFACE = 15,
COLOR_3DHIGHLIGHT = 20,
// COLOR_3DHILIGHT = 20, this enum value conflicts with COLOR_3DHIGHLIGHT
COLOR_3DLIGHT = 22,
COLOR_3DSHADOW = 16,
COLOR_ACTIVEBORDER = 10,
COLOR_ACTIVECAPTION = 2,
COLOR_APPWORKSPACE = 12,
COLOR_BACKGROUND = 1,
// COLOR_BTNFACE = 15, this enum value conflicts with COLOR_3DFACE
// _COLOR_BTNHIGHLIGHT = 20, this enum value conflicts with COLOR_3DHIGHLIGHT
// _COLOR_BTNHILIGHT = 20, this enum value conflicts with COLOR_3DHIGHLIGHT
// COLOR_BTNSHADOW = 16, this enum value conflicts with COLOR_3DSHADOW
COLOR_BTNTEXT = 18,
COLOR_CAPTIONTEXT = 9,
// COLOR_DESKTOP = 1, this enum value conflicts with COLOR_BACKGROUND
COLOR_GRADIENTACTIVECAPTION = 27,
COLOR_GRADIENTINACTIVECAPTION = 28,
COLOR_GRAYTEXT = 17,
COLOR_HIGHLIGHT = 13,
COLOR_HIGHLIGHTTEXT = 14,
COLOR_HOTLIGHT = 26,
COLOR_INACTIVEBORDER = 11,
COLOR_INACTIVECAPTION = 3,
COLOR_INACTIVECAPTIONTEXT = 19,
COLOR_INFOBK = 24,
COLOR_INFOTEXT = 23,
COLOR_MENU = 4,
COLOR_MENUHILIGHT = 29,
COLOR_MENUBAR = 30,
COLOR_MENUTEXT = 7,
COLOR_SCROLLBAR = 0,
COLOR_WINDOW = 5,
COLOR_WINDOWFRAME = 6,
COLOR_WINDOWTEXT = 8,
};
pub const COLOR_3DDKSHADOW = SYS_COLOR_INDEX.COLOR_3DDKSHADOW;
pub const COLOR_3DFACE = SYS_COLOR_INDEX.COLOR_3DFACE;
pub const COLOR_3DHIGHLIGHT = SYS_COLOR_INDEX.COLOR_3DHIGHLIGHT;
pub const COLOR_3DHILIGHT = SYS_COLOR_INDEX.COLOR_3DHIGHLIGHT;
pub const COLOR_3DLIGHT = SYS_COLOR_INDEX.COLOR_3DLIGHT;
pub const COLOR_3DSHADOW = SYS_COLOR_INDEX.COLOR_3DSHADOW;
pub const COLOR_ACTIVEBORDER = SYS_COLOR_INDEX.COLOR_ACTIVEBORDER;
pub const COLOR_ACTIVECAPTION = SYS_COLOR_INDEX.COLOR_ACTIVECAPTION;
pub const COLOR_APPWORKSPACE = SYS_COLOR_INDEX.COLOR_APPWORKSPACE;
pub const COLOR_BACKGROUND = SYS_COLOR_INDEX.COLOR_BACKGROUND;
pub const COLOR_BTNFACE = SYS_COLOR_INDEX.COLOR_3DFACE;
pub const _COLOR_BTNHIGHLIGHT = SYS_COLOR_INDEX.COLOR_3DHIGHLIGHT;
pub const _COLOR_BTNHILIGHT = SYS_COLOR_INDEX.COLOR_3DHIGHLIGHT;
pub const COLOR_BTNSHADOW = SYS_COLOR_INDEX.COLOR_3DSHADOW;
pub const COLOR_BTNTEXT = SYS_COLOR_INDEX.COLOR_BTNTEXT;
pub const COLOR_CAPTIONTEXT = SYS_COLOR_INDEX.COLOR_CAPTIONTEXT;
pub const COLOR_DESKTOP = SYS_COLOR_INDEX.COLOR_BACKGROUND;
pub const COLOR_GRADIENTACTIVECAPTION = SYS_COLOR_INDEX.COLOR_GRADIENTACTIVECAPTION;
pub const COLOR_GRADIENTINACTIVECAPTION = SYS_COLOR_INDEX.COLOR_GRADIENTINACTIVECAPTION;
pub const COLOR_GRAYTEXT = SYS_COLOR_INDEX.COLOR_GRAYTEXT;
pub const COLOR_HIGHLIGHT = SYS_COLOR_INDEX.COLOR_HIGHLIGHT;
pub const COLOR_HIGHLIGHTTEXT = SYS_COLOR_INDEX.COLOR_HIGHLIGHTTEXT;
pub const COLOR_HOTLIGHT = SYS_COLOR_INDEX.COLOR_HOTLIGHT;
pub const COLOR_INACTIVEBORDER = SYS_COLOR_INDEX.COLOR_INACTIVEBORDER;
pub const COLOR_INACTIVECAPTION = SYS_COLOR_INDEX.COLOR_INACTIVECAPTION;
pub const COLOR_INACTIVECAPTIONTEXT = SYS_COLOR_INDEX.COLOR_INACTIVECAPTIONTEXT;
pub const COLOR_INFOBK = SYS_COLOR_INDEX.COLOR_INFOBK;
pub const COLOR_INFOTEXT = SYS_COLOR_INDEX.COLOR_INFOTEXT;
pub const COLOR_MENU = SYS_COLOR_INDEX.COLOR_MENU;
pub const COLOR_MENUHILIGHT = SYS_COLOR_INDEX.COLOR_MENUHILIGHT;
pub const COLOR_MENUBAR = SYS_COLOR_INDEX.COLOR_MENUBAR;
pub const COLOR_MENUTEXT = SYS_COLOR_INDEX.COLOR_MENUTEXT;
pub const COLOR_SCROLLBAR = SYS_COLOR_INDEX.COLOR_SCROLLBAR;
pub const COLOR_WINDOW = SYS_COLOR_INDEX.COLOR_WINDOW;
pub const COLOR_WINDOWFRAME = SYS_COLOR_INDEX.COLOR_WINDOWFRAME;
pub const COLOR_WINDOWTEXT = SYS_COLOR_INDEX.COLOR_WINDOWTEXT;
pub const GET_WINDOW_CMD = enum(u32) {
CHILD = 5,
ENABLEDPOPUP = 6,
HWNDFIRST = 0,
HWNDLAST = 1,
HWNDNEXT = 2,
HWNDPREV = 3,
OWNER = 4,
};
pub const GW_CHILD = GET_WINDOW_CMD.CHILD;
pub const GW_ENABLEDPOPUP = GET_WINDOW_CMD.ENABLEDPOPUP;
pub const GW_HWNDFIRST = GET_WINDOW_CMD.HWNDFIRST;
pub const GW_HWNDLAST = GET_WINDOW_CMD.HWNDLAST;
pub const GW_HWNDNEXT = GET_WINDOW_CMD.HWNDNEXT;
pub const GW_HWNDPREV = GET_WINDOW_CMD.HWNDPREV;
pub const GW_OWNER = GET_WINDOW_CMD.OWNER;
pub const SYSTEM_METRICS_INDEX = enum(u32) {
ARRANGE = 56,
CLEANBOOT = 67,
CMONITORS = 80,
CMOUSEBUTTONS = 43,
CONVERTIBLESLATEMODE = 8195,
CXBORDER = 5,
CXCURSOR = 13,
CXDLGFRAME = 7,
CXDOUBLECLK = 36,
CXDRAG = 68,
CXEDGE = 45,
// CXFIXEDFRAME = 7, this enum value conflicts with CXDLGFRAME
CXFOCUSBORDER = 83,
CXFRAME = 32,
CXFULLSCREEN = 16,
CXHSCROLL = 21,
CXHTHUMB = 10,
CXICON = 11,
CXICONSPACING = 38,
CXMAXIMIZED = 61,
CXMAXTRACK = 59,
CXMENUCHECK = 71,
CXMENUSIZE = 54,
CXMIN = 28,
CXMINIMIZED = 57,
CXMINSPACING = 47,
CXMINTRACK = 34,
CXPADDEDBORDER = 92,
CXSCREEN = 0,
CXSIZE = 30,
// CXSIZEFRAME = 32, this enum value conflicts with CXFRAME
CXSMICON = 49,
CXSMSIZE = 52,
CXVIRTUALSCREEN = 78,
CXVSCROLL = 2,
CYBORDER = 6,
CYCAPTION = 4,
CYCURSOR = 14,
CYDLGFRAME = 8,
CYDOUBLECLK = 37,
CYDRAG = 69,
CYEDGE = 46,
// CYFIXEDFRAME = 8, this enum value conflicts with CYDLGFRAME
CYFOCUSBORDER = 84,
CYFRAME = 33,
CYFULLSCREEN = 17,
CYHSCROLL = 3,
CYICON = 12,
CYICONSPACING = 39,
CYKANJIWINDOW = 18,
CYMAXIMIZED = 62,
CYMAXTRACK = 60,
CYMENU = 15,
CYMENUCHECK = 72,
CYMENUSIZE = 55,
CYMIN = 29,
CYMINIMIZED = 58,
CYMINSPACING = 48,
CYMINTRACK = 35,
CYSCREEN = 1,
CYSIZE = 31,
// CYSIZEFRAME = 33, this enum value conflicts with CYFRAME
CYSMCAPTION = 51,
CYSMICON = 50,
CYSMSIZE = 53,
CYVIRTUALSCREEN = 79,
CYVSCROLL = 20,
CYVTHUMB = 9,
DBCSENABLED = 42,
DEBUG = 22,
DIGITIZER = 94,
IMMENABLED = 82,
MAXIMUMTOUCHES = 95,
MEDIACENTER = 87,
MENUDROPALIGNMENT = 40,
MIDEASTENABLED = 74,
MOUSEPRESENT = 19,
MOUSEHORIZONTALWHEELPRESENT = 91,
MOUSEWHEELPRESENT = 75,
NETWORK = 63,
PENWINDOWS = 41,
REMOTECONTROL = 8193,
REMOTESESSION = 4096,
SAMEDISPLAYFORMAT = 81,
SECURE = 44,
SERVERR2 = 89,
SHOWSOUNDS = 70,
SHUTTINGDOWN = 8192,
SLOWMACHINE = 73,
STARTER = 88,
SWAPBUTTON = 23,
SYSTEMDOCKED_ = 8196,
TABLETPC = 86,
XVIRTUALSCREEN = 76,
YVIRTUALSCREEN = 77,
};
pub const SM_ARRANGE = SYSTEM_METRICS_INDEX.ARRANGE;
pub const SM_CLEANBOOT = SYSTEM_METRICS_INDEX.CLEANBOOT;
pub const SM_CMONITORS = SYSTEM_METRICS_INDEX.CMONITORS;
pub const SM_CMOUSEBUTTONS = SYSTEM_METRICS_INDEX.CMOUSEBUTTONS;
pub const SM_CONVERTIBLESLATEMODE = SYSTEM_METRICS_INDEX.CONVERTIBLESLATEMODE;
pub const SM_CXBORDER = SYSTEM_METRICS_INDEX.CXBORDER;
pub const SM_CXCURSOR = SYSTEM_METRICS_INDEX.CXCURSOR;
pub const SM_CXDLGFRAME = SYSTEM_METRICS_INDEX.CXDLGFRAME;
pub const SM_CXDOUBLECLK = SYSTEM_METRICS_INDEX.CXDOUBLECLK;
pub const SM_CXDRAG = SYSTEM_METRICS_INDEX.CXDRAG;
pub const SM_CXEDGE = SYSTEM_METRICS_INDEX.CXEDGE;
pub const SM_CXFIXEDFRAME = SYSTEM_METRICS_INDEX.CXDLGFRAME;
pub const SM_CXFOCUSBORDER = SYSTEM_METRICS_INDEX.CXFOCUSBORDER;
pub const SM_CXFRAME = SYSTEM_METRICS_INDEX.CXFRAME;
pub const SM_CXFULLSCREEN = SYSTEM_METRICS_INDEX.CXFULLSCREEN;
pub const SM_CXHSCROLL = SYSTEM_METRICS_INDEX.CXHSCROLL;
pub const SM_CXHTHUMB = SYSTEM_METRICS_INDEX.CXHTHUMB;
pub const SM_CXICON = SYSTEM_METRICS_INDEX.CXICON;
pub const SM_CXICONSPACING = SYSTEM_METRICS_INDEX.CXICONSPACING;
pub const SM_CXMAXIMIZED = SYSTEM_METRICS_INDEX.CXMAXIMIZED;
pub const SM_CXMAXTRACK = SYSTEM_METRICS_INDEX.CXMAXTRACK;
pub const SM_CXMENUCHECK = SYSTEM_METRICS_INDEX.CXMENUCHECK;
pub const SM_CXMENUSIZE = SYSTEM_METRICS_INDEX.CXMENUSIZE;
pub const SM_CXMIN = SYSTEM_METRICS_INDEX.CXMIN;
pub const SM_CXMINIMIZED = SYSTEM_METRICS_INDEX.CXMINIMIZED;
pub const SM_CXMINSPACING = SYSTEM_METRICS_INDEX.CXMINSPACING;
pub const SM_CXMINTRACK = SYSTEM_METRICS_INDEX.CXMINTRACK;
pub const SM_CXPADDEDBORDER = SYSTEM_METRICS_INDEX.CXPADDEDBORDER;
pub const SM_CXSCREEN = SYSTEM_METRICS_INDEX.CXSCREEN;
pub const SM_CXSIZE = SYSTEM_METRICS_INDEX.CXSIZE;
pub const SM_CXSIZEFRAME = SYSTEM_METRICS_INDEX.CXFRAME;
pub const SM_CXSMICON = SYSTEM_METRICS_INDEX.CXSMICON;
pub const SM_CXSMSIZE = SYSTEM_METRICS_INDEX.CXSMSIZE;
pub const SM_CXVIRTUALSCREEN = SYSTEM_METRICS_INDEX.CXVIRTUALSCREEN;
pub const SM_CXVSCROLL = SYSTEM_METRICS_INDEX.CXVSCROLL;
pub const SM_CYBORDER = SYSTEM_METRICS_INDEX.CYBORDER;
pub const SM_CYCAPTION = SYSTEM_METRICS_INDEX.CYCAPTION;
pub const SM_CYCURSOR = SYSTEM_METRICS_INDEX.CYCURSOR;
pub const SM_CYDLGFRAME = SYSTEM_METRICS_INDEX.CYDLGFRAME;
pub const SM_CYDOUBLECLK = SYSTEM_METRICS_INDEX.CYDOUBLECLK;
pub const SM_CYDRAG = SYSTEM_METRICS_INDEX.CYDRAG;
pub const SM_CYEDGE = SYSTEM_METRICS_INDEX.CYEDGE;
pub const SM_CYFIXEDFRAME = SYSTEM_METRICS_INDEX.CYDLGFRAME;
pub const SM_CYFOCUSBORDER = SYSTEM_METRICS_INDEX.CYFOCUSBORDER;
pub const SM_CYFRAME = SYSTEM_METRICS_INDEX.CYFRAME;
pub const SM_CYFULLSCREEN = SYSTEM_METRICS_INDEX.CYFULLSCREEN;
pub const SM_CYHSCROLL = SYSTEM_METRICS_INDEX.CYHSCROLL;
pub const SM_CYICON = SYSTEM_METRICS_INDEX.CYICON;
pub const SM_CYICONSPACING = SYSTEM_METRICS_INDEX.CYICONSPACING;
pub const SM_CYKANJIWINDOW = SYSTEM_METRICS_INDEX.CYKANJIWINDOW;
pub const SM_CYMAXIMIZED = SYSTEM_METRICS_INDEX.CYMAXIMIZED;
pub const SM_CYMAXTRACK = SYSTEM_METRICS_INDEX.CYMAXTRACK;
pub const SM_CYMENU = SYSTEM_METRICS_INDEX.CYMENU;
pub const SM_CYMENUCHECK = SYSTEM_METRICS_INDEX.CYMENUCHECK;
pub const SM_CYMENUSIZE = SYSTEM_METRICS_INDEX.CYMENUSIZE;
pub const SM_CYMIN = SYSTEM_METRICS_INDEX.CYMIN;
pub const SM_CYMINIMIZED = SYSTEM_METRICS_INDEX.CYMINIMIZED;
pub const SM_CYMINSPACING = SYSTEM_METRICS_INDEX.CYMINSPACING;
pub const SM_CYMINTRACK = SYSTEM_METRICS_INDEX.CYMINTRACK;
pub const SM_CYSCREEN = SYSTEM_METRICS_INDEX.CYSCREEN;
pub const SM_CYSIZE = SYSTEM_METRICS_INDEX.CYSIZE;
pub const SM_CYSIZEFRAME = SYSTEM_METRICS_INDEX.CYFRAME;
pub const SM_CYSMCAPTION = SYSTEM_METRICS_INDEX.CYSMCAPTION;
pub const SM_CYSMICON = SYSTEM_METRICS_INDEX.CYSMICON;
pub const SM_CYSMSIZE = SYSTEM_METRICS_INDEX.CYSMSIZE;
pub const SM_CYVIRTUALSCREEN = SYSTEM_METRICS_INDEX.CYVIRTUALSCREEN;
pub const SM_CYVSCROLL = SYSTEM_METRICS_INDEX.CYVSCROLL;
pub const SM_CYVTHUMB = SYSTEM_METRICS_INDEX.CYVTHUMB;
pub const SM_DBCSENABLED = SYSTEM_METRICS_INDEX.DBCSENABLED;
pub const SM_DEBUG = SYSTEM_METRICS_INDEX.DEBUG;
pub const SM_DIGITIZER = SYSTEM_METRICS_INDEX.DIGITIZER;
pub const SM_IMMENABLED = SYSTEM_METRICS_INDEX.IMMENABLED;
pub const SM_MAXIMUMTOUCHES = SYSTEM_METRICS_INDEX.MAXIMUMTOUCHES;
pub const SM_MEDIACENTER = SYSTEM_METRICS_INDEX.MEDIACENTER;
pub const SM_MENUDROPALIGNMENT = SYSTEM_METRICS_INDEX.MENUDROPALIGNMENT;
pub const SM_MIDEASTENABLED = SYSTEM_METRICS_INDEX.MIDEASTENABLED;
pub const SM_MOUSEPRESENT = SYSTEM_METRICS_INDEX.MOUSEPRESENT;
pub const SM_MOUSEHORIZONTALWHEELPRESENT = SYSTEM_METRICS_INDEX.MOUSEHORIZONTALWHEELPRESENT;
pub const SM_MOUSEWHEELPRESENT = SYSTEM_METRICS_INDEX.MOUSEWHEELPRESENT;
pub const SM_NETWORK = SYSTEM_METRICS_INDEX.NETWORK;
pub const SM_PENWINDOWS = SYSTEM_METRICS_INDEX.PENWINDOWS;
pub const SM_REMOTECONTROL = SYSTEM_METRICS_INDEX.REMOTECONTROL;
pub const SM_REMOTESESSION = SYSTEM_METRICS_INDEX.REMOTESESSION;
pub const SM_SAMEDISPLAYFORMAT = SYSTEM_METRICS_INDEX.SAMEDISPLAYFORMAT;
pub const SM_SECURE = SYSTEM_METRICS_INDEX.SECURE;
pub const SM_SERVERR2 = SYSTEM_METRICS_INDEX.SERVERR2;
pub const SM_SHOWSOUNDS = SYSTEM_METRICS_INDEX.SHOWSOUNDS;
pub const SM_SHUTTINGDOWN = SYSTEM_METRICS_INDEX.SHUTTINGDOWN;
pub const SM_SLOWMACHINE = SYSTEM_METRICS_INDEX.SLOWMACHINE;
pub const SM_STARTER = SYSTEM_METRICS_INDEX.STARTER;
pub const SM_SWAPBUTTON = SYSTEM_METRICS_INDEX.SWAPBUTTON;
pub const SM_SYSTEMDOCKED_ = SYSTEM_METRICS_INDEX.SYSTEMDOCKED_;
pub const SM_TABLETPC = SYSTEM_METRICS_INDEX.TABLETPC;
pub const SM_XVIRTUALSCREEN = SYSTEM_METRICS_INDEX.XVIRTUALSCREEN;
pub const SM_YVIRTUALSCREEN = SYSTEM_METRICS_INDEX.YVIRTUALSCREEN;
pub const GET_ANCESTOR_FLAGS = enum(u32) {
PARENT = 1,
ROOT = 2,
ROOTOWNER = 3,
};
pub const GA_PARENT = GET_ANCESTOR_FLAGS.PARENT;
pub const GA_ROOT = GET_ANCESTOR_FLAGS.ROOT;
pub const GA_ROOTOWNER = GET_ANCESTOR_FLAGS.ROOTOWNER;
pub const TILE_WINDOWS_HOW = enum(u32) {
HORIZONTAL = 1,
VERTICAL = 0,
};
pub const MDITILE_HORIZONTAL = TILE_WINDOWS_HOW.HORIZONTAL;
pub const MDITILE_VERTICAL = TILE_WINDOWS_HOW.VERTICAL;
pub const WINDOW_DISPLAY_AFFINITY = enum(u32) {
NONE = 0,
MONITOR = 1,
EXCLUDEFROMCAPTURE = 17,
};
pub const WDA_NONE = WINDOW_DISPLAY_AFFINITY.NONE;
pub const WDA_MONITOR = WINDOW_DISPLAY_AFFINITY.MONITOR;
pub const WDA_EXCLUDEFROMCAPTURE = WINDOW_DISPLAY_AFFINITY.EXCLUDEFROMCAPTURE;
pub const FOREGROUND_WINDOW_LOCK_CODE = enum(u32) {
LOCK = 1,
UNLOCK = 2,
};
pub const LSFW_LOCK = FOREGROUND_WINDOW_LOCK_CODE.LOCK;
pub const LSFW_UNLOCK = FOREGROUND_WINDOW_LOCK_CODE.UNLOCK;
pub const CASCADE_WINDOWS_HOW = enum(u32) {
SKIPDISABLED = 2,
ZORDER = 4,
_,
pub fn initFlags(o: struct {
SKIPDISABLED: u1 = 0,
ZORDER: u1 = 0,
}) CASCADE_WINDOWS_HOW {
return @intToEnum(CASCADE_WINDOWS_HOW,
(if (o.SKIPDISABLED == 1) @enumToInt(CASCADE_WINDOWS_HOW.SKIPDISABLED) else 0)
| (if (o.ZORDER == 1) @enumToInt(CASCADE_WINDOWS_HOW.ZORDER) else 0)
);
}
};
pub const MDITILE_SKIPDISABLED = CASCADE_WINDOWS_HOW.SKIPDISABLED;
pub const MDITILE_ZORDER = CASCADE_WINDOWS_HOW.ZORDER;
pub const WINDOW_MESSAGE_FILTER_ACTION = enum(u32) {
ALLOW = 1,
DISALLOW = 2,
RESET = 0,
};
pub const MSGFLT_ALLOW = WINDOW_MESSAGE_FILTER_ACTION.ALLOW;
pub const MSGFLT_DISALLOW = WINDOW_MESSAGE_FILTER_ACTION.DISALLOW;
pub const MSGFLT_RESET = WINDOW_MESSAGE_FILTER_ACTION.RESET;
pub const GET_MENU_DEFAULT_ITEM_FLAGS = enum(u32) {
GOINTOPOPUPS = 2,
USEDISABLED = 1,
_,
pub fn initFlags(o: struct {
GOINTOPOPUPS: u1 = 0,
USEDISABLED: u1 = 0,
}) GET_MENU_DEFAULT_ITEM_FLAGS {
return @intToEnum(GET_MENU_DEFAULT_ITEM_FLAGS,
(if (o.GOINTOPOPUPS == 1) @enumToInt(GET_MENU_DEFAULT_ITEM_FLAGS.GOINTOPOPUPS) else 0)
| (if (o.USEDISABLED == 1) @enumToInt(GET_MENU_DEFAULT_ITEM_FLAGS.USEDISABLED) else 0)
);
}
};
pub const GMDI_GOINTOPOPUPS = GET_MENU_DEFAULT_ITEM_FLAGS.GOINTOPOPUPS;
pub const GMDI_USEDISABLED = GET_MENU_DEFAULT_ITEM_FLAGS.USEDISABLED;
pub const PAGESETUPDLG_FLAGS = enum(u32) {
DEFAULTMINMARGINS = 0,
DISABLEMARGINS = 16,
DISABLEORIENTATION = 256,
DISABLEPAGEPAINTING = 524288,
DISABLEPAPER = 512,
DISABLEPRINTER = 32,
ENABLEPAGEPAINTHOOK = 262144,
ENABLEPAGESETUPHOOK = 8192,
ENABLEPAGESETUPTEMPLATE = 32768,
ENABLEPAGESETUPTEMPLATEHANDLE = 131072,
INHUNDREDTHSOFMILLIMETERS = 8,
INTHOUSANDTHSOFINCHES = 4,
// INWININIINTLMEASURE = 0, this enum value conflicts with DEFAULTMINMARGINS
MARGINS = 2,
MINMARGINS = 1,
NONETWORKBUTTON = 2097152,
NOWARNING = 128,
RETURNDEFAULT = 1024,
SHOWHELP = 2048,
_,
pub fn initFlags(o: struct {
DEFAULTMINMARGINS: u1 = 0,
DISABLEMARGINS: u1 = 0,
DISABLEORIENTATION: u1 = 0,
DISABLEPAGEPAINTING: u1 = 0,
DISABLEPAPER: u1 = 0,
DISABLEPRINTER: u1 = 0,
ENABLEPAGEPAINTHOOK: u1 = 0,
ENABLEPAGESETUPHOOK: u1 = 0,
ENABLEPAGESETUPTEMPLATE: u1 = 0,
ENABLEPAGESETUPTEMPLATEHANDLE: u1 = 0,
INHUNDREDTHSOFMILLIMETERS: u1 = 0,
INTHOUSANDTHSOFINCHES: u1 = 0,
MARGINS: u1 = 0,
MINMARGINS: u1 = 0,
NONETWORKBUTTON: u1 = 0,
NOWARNING: u1 = 0,
RETURNDEFAULT: u1 = 0,
SHOWHELP: u1 = 0,
}) PAGESETUPDLG_FLAGS {
return @intToEnum(PAGESETUPDLG_FLAGS,
(if (o.DEFAULTMINMARGINS == 1) @enumToInt(PAGESETUPDLG_FLAGS.DEFAULTMINMARGINS) else 0)
| (if (o.DISABLEMARGINS == 1) @enumToInt(PAGESETUPDLG_FLAGS.DISABLEMARGINS) else 0)
| (if (o.DISABLEORIENTATION == 1) @enumToInt(PAGESETUPDLG_FLAGS.DISABLEORIENTATION) else 0)
| (if (o.DISABLEPAGEPAINTING == 1) @enumToInt(PAGESETUPDLG_FLAGS.DISABLEPAGEPAINTING) else 0)
| (if (o.DISABLEPAPER == 1) @enumToInt(PAGESETUPDLG_FLAGS.DISABLEPAPER) else 0)
| (if (o.DISABLEPRINTER == 1) @enumToInt(PAGESETUPDLG_FLAGS.DISABLEPRINTER) else 0)
| (if (o.ENABLEPAGEPAINTHOOK == 1) @enumToInt(PAGESETUPDLG_FLAGS.ENABLEPAGEPAINTHOOK) else 0)
| (if (o.ENABLEPAGESETUPHOOK == 1) @enumToInt(PAGESETUPDLG_FLAGS.ENABLEPAGESETUPHOOK) else 0)
| (if (o.ENABLEPAGESETUPTEMPLATE == 1) @enumToInt(PAGESETUPDLG_FLAGS.ENABLEPAGESETUPTEMPLATE) else 0)
| (if (o.ENABLEPAGESETUPTEMPLATEHANDLE == 1) @enumToInt(PAGESETUPDLG_FLAGS.ENABLEPAGESETUPTEMPLATEHANDLE) else 0)
| (if (o.INHUNDREDTHSOFMILLIMETERS == 1) @enumToInt(PAGESETUPDLG_FLAGS.INHUNDREDTHSOFMILLIMETERS) else 0)
| (if (o.INTHOUSANDTHSOFINCHES == 1) @enumToInt(PAGESETUPDLG_FLAGS.INTHOUSANDTHSOFINCHES) else 0)
| (if (o.MARGINS == 1) @enumToInt(PAGESETUPDLG_FLAGS.MARGINS) else 0)
| (if (o.MINMARGINS == 1) @enumToInt(PAGESETUPDLG_FLAGS.MINMARGINS) else 0)
| (if (o.NONETWORKBUTTON == 1) @enumToInt(PAGESETUPDLG_FLAGS.NONETWORKBUTTON) else 0)
| (if (o.NOWARNING == 1) @enumToInt(PAGESETUPDLG_FLAGS.NOWARNING) else 0)
| (if (o.RETURNDEFAULT == 1) @enumToInt(PAGESETUPDLG_FLAGS.RETURNDEFAULT) else 0)
| (if (o.SHOWHELP == 1) @enumToInt(PAGESETUPDLG_FLAGS.SHOWHELP) else 0)
);
}
};
pub const PSD_DEFAULTMINMARGINS = PAGESETUPDLG_FLAGS.DEFAULTMINMARGINS;
pub const PSD_DISABLEMARGINS = PAGESETUPDLG_FLAGS.DISABLEMARGINS;
pub const PSD_DISABLEORIENTATION = PAGESETUPDLG_FLAGS.DISABLEORIENTATION;
pub const PSD_DISABLEPAGEPAINTING = PAGESETUPDLG_FLAGS.DISABLEPAGEPAINTING;
pub const PSD_DISABLEPAPER = PAGESETUPDLG_FLAGS.DISABLEPAPER;
pub const PSD_DISABLEPRINTER = PAGESETUPDLG_FLAGS.DISABLEPRINTER;
pub const PSD_ENABLEPAGEPAINTHOOK = PAGESETUPDLG_FLAGS.ENABLEPAGEPAINTHOOK;
pub const PSD_ENABLEPAGESETUPHOOK = PAGESETUPDLG_FLAGS.ENABLEPAGESETUPHOOK;
pub const PSD_ENABLEPAGESETUPTEMPLATE = PAGESETUPDLG_FLAGS.ENABLEPAGESETUPTEMPLATE;
pub const PSD_ENABLEPAGESETUPTEMPLATEHANDLE = PAGESETUPDLG_FLAGS.ENABLEPAGESETUPTEMPLATEHANDLE;
pub const PSD_INHUNDREDTHSOFMILLIMETERS = PAGESETUPDLG_FLAGS.INHUNDREDTHSOFMILLIMETERS;
pub const PSD_INTHOUSANDTHSOFINCHES = PAGESETUPDLG_FLAGS.INTHOUSANDTHSOFINCHES;
pub const PSD_INWININIINTLMEASURE = PAGESETUPDLG_FLAGS.DEFAULTMINMARGINS;
pub const PSD_MARGINS = PAGESETUPDLG_FLAGS.MARGINS;
pub const PSD_MINMARGINS = PAGESETUPDLG_FLAGS.MINMARGINS;
pub const PSD_NONETWORKBUTTON = PAGESETUPDLG_FLAGS.NONETWORKBUTTON;
pub const PSD_NOWARNING = PAGESETUPDLG_FLAGS.NOWARNING;
pub const PSD_RETURNDEFAULT = PAGESETUPDLG_FLAGS.RETURNDEFAULT;
pub const PSD_SHOWHELP = PAGESETUPDLG_FLAGS.SHOWHELP;
pub const MSGFLTINFO_STATUS = enum(u32) {
NONE = 0,
ALLOWED_HIGHER = 3,
ALREADYALLOWED_FORWND = 1,
ALREADYDISALLOWED_FORWND = 2,
};
pub const MSGFLTINFO_NONE = MSGFLTINFO_STATUS.NONE;
pub const MSGFLTINFO_ALLOWED_HIGHER = MSGFLTINFO_STATUS.ALLOWED_HIGHER;
pub const MSGFLTINFO_ALREADYALLOWED_FORWND = MSGFLTINFO_STATUS.ALREADYALLOWED_FORWND;
pub const MSGFLTINFO_ALREADYDISALLOWED_FORWND = MSGFLTINFO_STATUS.ALREADYDISALLOWED_FORWND;
pub const CHOOSEFONT_FLAGS = enum(u32) {
APPLY = 512,
ANSIONLY = 1024,
BOTH = 3,
EFFECTS = 256,
ENABLEHOOK = 8,
ENABLETEMPLATE = 16,
ENABLETEMPLATEHANDLE = 32,
FIXEDPITCHONLY = 16384,
FORCEFONTEXIST = 65536,
INACTIVEFONTS = 33554432,
INITTOLOGFONTSTRUCT = 64,
LIMITSIZE = 8192,
NOOEMFONTS = 2048,
NOFACESEL = 524288,
NOSCRIPTSEL = 8388608,
NOSIMULATIONS = 4096,
NOSIZESEL = 2097152,
NOSTYLESEL = 1048576,
// NOVECTORFONTS = 2048, this enum value conflicts with NOOEMFONTS
NOVERTFONTS = 16777216,
PRINTERFONTS = 2,
SCALABLEONLY = 131072,
SCREENFONTS = 1,
// SCRIPTSONLY = 1024, this enum value conflicts with ANSIONLY
SELECTSCRIPT = 4194304,
SHOWHELP = 4,
TTONLY = 262144,
USESTYLE = 128,
WYSIWYG = 32768,
_,
pub fn initFlags(o: struct {
APPLY: u1 = 0,
ANSIONLY: u1 = 0,
BOTH: u1 = 0,
EFFECTS: u1 = 0,
ENABLEHOOK: u1 = 0,
ENABLETEMPLATE: u1 = 0,
ENABLETEMPLATEHANDLE: u1 = 0,
FIXEDPITCHONLY: u1 = 0,
FORCEFONTEXIST: u1 = 0,
INACTIVEFONTS: u1 = 0,
INITTOLOGFONTSTRUCT: u1 = 0,
LIMITSIZE: u1 = 0,
NOOEMFONTS: u1 = 0,
NOFACESEL: u1 = 0,
NOSCRIPTSEL: u1 = 0,
NOSIMULATIONS: u1 = 0,
NOSIZESEL: u1 = 0,
NOSTYLESEL: u1 = 0,
NOVERTFONTS: u1 = 0,
PRINTERFONTS: u1 = 0,
SCALABLEONLY: u1 = 0,
SCREENFONTS: u1 = 0,
SELECTSCRIPT: u1 = 0,
SHOWHELP: u1 = 0,
TTONLY: u1 = 0,
USESTYLE: u1 = 0,
WYSIWYG: u1 = 0,
}) CHOOSEFONT_FLAGS {
return @intToEnum(CHOOSEFONT_FLAGS,
(if (o.APPLY == 1) @enumToInt(CHOOSEFONT_FLAGS.APPLY) else 0)
| (if (o.ANSIONLY == 1) @enumToInt(CHOOSEFONT_FLAGS.ANSIONLY) else 0)
| (if (o.BOTH == 1) @enumToInt(CHOOSEFONT_FLAGS.BOTH) else 0)
| (if (o.EFFECTS == 1) @enumToInt(CHOOSEFONT_FLAGS.EFFECTS) else 0)
| (if (o.ENABLEHOOK == 1) @enumToInt(CHOOSEFONT_FLAGS.ENABLEHOOK) else 0)
| (if (o.ENABLETEMPLATE == 1) @enumToInt(CHOOSEFONT_FLAGS.ENABLETEMPLATE) else 0)
| (if (o.ENABLETEMPLATEHANDLE == 1) @enumToInt(CHOOSEFONT_FLAGS.ENABLETEMPLATEHANDLE) else 0)
| (if (o.FIXEDPITCHONLY == 1) @enumToInt(CHOOSEFONT_FLAGS.FIXEDPITCHONLY) else 0)
| (if (o.FORCEFONTEXIST == 1) @enumToInt(CHOOSEFONT_FLAGS.FORCEFONTEXIST) else 0)
| (if (o.INACTIVEFONTS == 1) @enumToInt(CHOOSEFONT_FLAGS.INACTIVEFONTS) else 0)
| (if (o.INITTOLOGFONTSTRUCT == 1) @enumToInt(CHOOSEFONT_FLAGS.INITTOLOGFONTSTRUCT) else 0)
| (if (o.LIMITSIZE == 1) @enumToInt(CHOOSEFONT_FLAGS.LIMITSIZE) else 0)
| (if (o.NOOEMFONTS == 1) @enumToInt(CHOOSEFONT_FLAGS.NOOEMFONTS) else 0)
| (if (o.NOFACESEL == 1) @enumToInt(CHOOSEFONT_FLAGS.NOFACESEL) else 0)
| (if (o.NOSCRIPTSEL == 1) @enumToInt(CHOOSEFONT_FLAGS.NOSCRIPTSEL) else 0)
| (if (o.NOSIMULATIONS == 1) @enumToInt(CHOOSEFONT_FLAGS.NOSIMULATIONS) else 0)
| (if (o.NOSIZESEL == 1) @enumToInt(CHOOSEFONT_FLAGS.NOSIZESEL) else 0)
| (if (o.NOSTYLESEL == 1) @enumToInt(CHOOSEFONT_FLAGS.NOSTYLESEL) else 0)
| (if (o.NOVERTFONTS == 1) @enumToInt(CHOOSEFONT_FLAGS.NOVERTFONTS) else 0)
| (if (o.PRINTERFONTS == 1) @enumToInt(CHOOSEFONT_FLAGS.PRINTERFONTS) else 0)
| (if (o.SCALABLEONLY == 1) @enumToInt(CHOOSEFONT_FLAGS.SCALABLEONLY) else 0)
| (if (o.SCREENFONTS == 1) @enumToInt(CHOOSEFONT_FLAGS.SCREENFONTS) else 0)
| (if (o.SELECTSCRIPT == 1) @enumToInt(CHOOSEFONT_FLAGS.SELECTSCRIPT) else 0)
| (if (o.SHOWHELP == 1) @enumToInt(CHOOSEFONT_FLAGS.SHOWHELP) else 0)
| (if (o.TTONLY == 1) @enumToInt(CHOOSEFONT_FLAGS.TTONLY) else 0)
| (if (o.USESTYLE == 1) @enumToInt(CHOOSEFONT_FLAGS.USESTYLE) else 0)
| (if (o.WYSIWYG == 1) @enumToInt(CHOOSEFONT_FLAGS.WYSIWYG) else 0)
);
}
};
pub const CF_APPLY = CHOOSEFONT_FLAGS.APPLY;
pub const CF_ANSIONLY = CHOOSEFONT_FLAGS.ANSIONLY;
pub const CF_BOTH = CHOOSEFONT_FLAGS.BOTH;
pub const CF_EFFECTS = CHOOSEFONT_FLAGS.EFFECTS;
pub const CF_ENABLEHOOK = CHOOSEFONT_FLAGS.ENABLEHOOK;
pub const CF_ENABLETEMPLATE = CHOOSEFONT_FLAGS.ENABLETEMPLATE;
pub const CF_ENABLETEMPLATEHANDLE = CHOOSEFONT_FLAGS.ENABLETEMPLATEHANDLE;
pub const CF_FIXEDPITCHONLY = CHOOSEFONT_FLAGS.FIXEDPITCHONLY;
pub const CF_FORCEFONTEXIST = CHOOSEFONT_FLAGS.FORCEFONTEXIST;
pub const CF_INACTIVEFONTS = CHOOSEFONT_FLAGS.INACTIVEFONTS;
pub const CF_INITTOLOGFONTSTRUCT = CHOOSEFONT_FLAGS.INITTOLOGFONTSTRUCT;
pub const CF_LIMITSIZE = CHOOSEFONT_FLAGS.LIMITSIZE;
pub const CF_NOOEMFONTS = CHOOSEFONT_FLAGS.NOOEMFONTS;
pub const CF_NOFACESEL = CHOOSEFONT_FLAGS.NOFACESEL;
pub const CF_NOSCRIPTSEL = CHOOSEFONT_FLAGS.NOSCRIPTSEL;
pub const CF_NOSIMULATIONS = CHOOSEFONT_FLAGS.NOSIMULATIONS;
pub const CF_NOSIZESEL = CHOOSEFONT_FLAGS.NOSIZESEL;
pub const CF_NOSTYLESEL = CHOOSEFONT_FLAGS.NOSTYLESEL;
pub const CF_NOVECTORFONTS = CHOOSEFONT_FLAGS.NOOEMFONTS;
pub const CF_NOVERTFONTS = CHOOSEFONT_FLAGS.NOVERTFONTS;
pub const CF_PRINTERFONTS = CHOOSEFONT_FLAGS.PRINTERFONTS;
pub const CF_SCALABLEONLY = CHOOSEFONT_FLAGS.SCALABLEONLY;
pub const CF_SCREENFONTS = CHOOSEFONT_FLAGS.SCREENFONTS;
pub const CF_SCRIPTSONLY = CHOOSEFONT_FLAGS.ANSIONLY;
pub const CF_SELECTSCRIPT = CHOOSEFONT_FLAGS.SELECTSCRIPT;
pub const CF_SHOWHELP = CHOOSEFONT_FLAGS.SHOWHELP;
pub const CF_TTONLY = CHOOSEFONT_FLAGS.TTONLY;
pub const CF_USESTYLE = CHOOSEFONT_FLAGS.USESTYLE;
pub const CF_WYSIWYG = CHOOSEFONT_FLAGS.WYSIWYG;
pub const FINDREPLACE_FLAGS = enum(u32) {
DIALOGTERM = 64,
DOWN = 1,
ENABLEHOOK = 256,
ENABLETEMPLATE = 512,
ENABLETEMPLATEHANDLE = 8192,
FINDNEXT = 8,
HIDEUPDOWN = 16384,
HIDEMATCHCASE = 32768,
HIDEWHOLEWORD = 65536,
MATCHCASE = 4,
NOMATCHCASE = 2048,
NOUPDOWN = 1024,
NOWHOLEWORD = 4096,
REPLACE = 16,
REPLACEALL = 32,
SHOWHELP = 128,
WHOLEWORD = 2,
_,
pub fn initFlags(o: struct {
DIALOGTERM: u1 = 0,
DOWN: u1 = 0,
ENABLEHOOK: u1 = 0,
ENABLETEMPLATE: u1 = 0,
ENABLETEMPLATEHANDLE: u1 = 0,
FINDNEXT: u1 = 0,
HIDEUPDOWN: u1 = 0,
HIDEMATCHCASE: u1 = 0,
HIDEWHOLEWORD: u1 = 0,
MATCHCASE: u1 = 0,
NOMATCHCASE: u1 = 0,
NOUPDOWN: u1 = 0,
NOWHOLEWORD: u1 = 0,
REPLACE: u1 = 0,
REPLACEALL: u1 = 0,
SHOWHELP: u1 = 0,
WHOLEWORD: u1 = 0,
}) FINDREPLACE_FLAGS {
return @intToEnum(FINDREPLACE_FLAGS,
(if (o.DIALOGTERM == 1) @enumToInt(FINDREPLACE_FLAGS.DIALOGTERM) else 0)
| (if (o.DOWN == 1) @enumToInt(FINDREPLACE_FLAGS.DOWN) else 0)
| (if (o.ENABLEHOOK == 1) @enumToInt(FINDREPLACE_FLAGS.ENABLEHOOK) else 0)
| (if (o.ENABLETEMPLATE == 1) @enumToInt(FINDREPLACE_FLAGS.ENABLETEMPLATE) else 0)
| (if (o.ENABLETEMPLATEHANDLE == 1) @enumToInt(FINDREPLACE_FLAGS.ENABLETEMPLATEHANDLE) else 0)
| (if (o.FINDNEXT == 1) @enumToInt(FINDREPLACE_FLAGS.FINDNEXT) else 0)
| (if (o.HIDEUPDOWN == 1) @enumToInt(FINDREPLACE_FLAGS.HIDEUPDOWN) else 0)
| (if (o.HIDEMATCHCASE == 1) @enumToInt(FINDREPLACE_FLAGS.HIDEMATCHCASE) else 0)
| (if (o.HIDEWHOLEWORD == 1) @enumToInt(FINDREPLACE_FLAGS.HIDEWHOLEWORD) else 0)
| (if (o.MATCHCASE == 1) @enumToInt(FINDREPLACE_FLAGS.MATCHCASE) else 0)
| (if (o.NOMATCHCASE == 1) @enumToInt(FINDREPLACE_FLAGS.NOMATCHCASE) else 0)
| (if (o.NOUPDOWN == 1) @enumToInt(FINDREPLACE_FLAGS.NOUPDOWN) else 0)
| (if (o.NOWHOLEWORD == 1) @enumToInt(FINDREPLACE_FLAGS.NOWHOLEWORD) else 0)
| (if (o.REPLACE == 1) @enumToInt(FINDREPLACE_FLAGS.REPLACE) else 0)
| (if (o.REPLACEALL == 1) @enumToInt(FINDREPLACE_FLAGS.REPLACEALL) else 0)
| (if (o.SHOWHELP == 1) @enumToInt(FINDREPLACE_FLAGS.SHOWHELP) else 0)
| (if (o.WHOLEWORD == 1) @enumToInt(FINDREPLACE_FLAGS.WHOLEWORD) else 0)
);
}
};
pub const FR_DIALOGTERM = FINDREPLACE_FLAGS.DIALOGTERM;
pub const FR_DOWN = FINDREPLACE_FLAGS.DOWN;
pub const FR_ENABLEHOOK = FINDREPLACE_FLAGS.ENABLEHOOK;
pub const FR_ENABLETEMPLATE = FINDREPLACE_FLAGS.ENABLETEMPLATE;
pub const FR_ENABLETEMPLATEHANDLE = FINDREPLACE_FLAGS.ENABLETEMPLATEHANDLE;
pub const FR_FINDNEXT = FINDREPLACE_FLAGS.FINDNEXT;
pub const FR_HIDEUPDOWN = FINDREPLACE_FLAGS.HIDEUPDOWN;
pub const FR_HIDEMATCHCASE = FINDREPLACE_FLAGS.HIDEMATCHCASE;
pub const FR_HIDEWHOLEWORD = FINDREPLACE_FLAGS.HIDEWHOLEWORD;
pub const FR_MATCHCASE = FINDREPLACE_FLAGS.MATCHCASE;
pub const FR_NOMATCHCASE = FINDREPLACE_FLAGS.NOMATCHCASE;
pub const FR_NOUPDOWN = FINDREPLACE_FLAGS.NOUPDOWN;
pub const FR_NOWHOLEWORD = FINDREPLACE_FLAGS.NOWHOLEWORD;
pub const FR_REPLACE = FINDREPLACE_FLAGS.REPLACE;
pub const FR_REPLACEALL = FINDREPLACE_FLAGS.REPLACEALL;
pub const FR_SHOWHELP = FINDREPLACE_FLAGS.SHOWHELP;
pub const FR_WHOLEWORD = FINDREPLACE_FLAGS.WHOLEWORD;
pub const PRINTDLGEX_FLAGS = enum(u32) {
ALLPAGES = 0,
COLLATE = 16,
CURRENTPAGE = 4194304,
DISABLEPRINTTOFILE = 524288,
ENABLEPRINTTEMPLATE = 16384,
ENABLEPRINTTEMPLATEHANDLE = 65536,
EXCLUSIONFLAGS = 16777216,
HIDEPRINTTOFILE = 1048576,
NOCURRENTPAGE = 8388608,
NOPAGENUMS = 8,
NOSELECTION = 4,
NOWARNING = 128,
PAGENUMS = 2,
PRINTTOFILE = 32,
RETURNDC = 256,
RETURNDEFAULT = 1024,
RETURNIC = 512,
SELECTION = 1,
USEDEVMODECOPIES = 262144,
// USEDEVMODECOPIESANDCOLLATE = 262144, this enum value conflicts with USEDEVMODECOPIES
USELARGETEMPLATE = 268435456,
ENABLEPRINTHOOK = 4096,
ENABLESETUPHOOK = 8192,
ENABLESETUPTEMPLATE = 32768,
ENABLESETUPTEMPLATEHANDLE = 131072,
NONETWORKBUTTON = 2097152,
PRINTSETUP = 64,
SHOWHELP = 2048,
_,
pub fn initFlags(o: struct {
ALLPAGES: u1 = 0,
COLLATE: u1 = 0,
CURRENTPAGE: u1 = 0,
DISABLEPRINTTOFILE: u1 = 0,
ENABLEPRINTTEMPLATE: u1 = 0,
ENABLEPRINTTEMPLATEHANDLE: u1 = 0,
EXCLUSIONFLAGS: u1 = 0,
HIDEPRINTTOFILE: u1 = 0,
NOCURRENTPAGE: u1 = 0,
NOPAGENUMS: u1 = 0,
NOSELECTION: u1 = 0,
NOWARNING: u1 = 0,
PAGENUMS: u1 = 0,
PRINTTOFILE: u1 = 0,
RETURNDC: u1 = 0,
RETURNDEFAULT: u1 = 0,
RETURNIC: u1 = 0,
SELECTION: u1 = 0,
USEDEVMODECOPIES: u1 = 0,
USELARGETEMPLATE: u1 = 0,
ENABLEPRINTHOOK: u1 = 0,
ENABLESETUPHOOK: u1 = 0,
ENABLESETUPTEMPLATE: u1 = 0,
ENABLESETUPTEMPLATEHANDLE: u1 = 0,
NONETWORKBUTTON: u1 = 0,
PRINTSETUP: u1 = 0,
SHOWHELP: u1 = 0,
}) PRINTDLGEX_FLAGS {
return @intToEnum(PRINTDLGEX_FLAGS,
(if (o.ALLPAGES == 1) @enumToInt(PRINTDLGEX_FLAGS.ALLPAGES) else 0)
| (if (o.COLLATE == 1) @enumToInt(PRINTDLGEX_FLAGS.COLLATE) else 0)
| (if (o.CURRENTPAGE == 1) @enumToInt(PRINTDLGEX_FLAGS.CURRENTPAGE) else 0)
| (if (o.DISABLEPRINTTOFILE == 1) @enumToInt(PRINTDLGEX_FLAGS.DISABLEPRINTTOFILE) else 0)
| (if (o.ENABLEPRINTTEMPLATE == 1) @enumToInt(PRINTDLGEX_FLAGS.ENABLEPRINTTEMPLATE) else 0)
| (if (o.ENABLEPRINTTEMPLATEHANDLE == 1) @enumToInt(PRINTDLGEX_FLAGS.ENABLEPRINTTEMPLATEHANDLE) else 0)
| (if (o.EXCLUSIONFLAGS == 1) @enumToInt(PRINTDLGEX_FLAGS.EXCLUSIONFLAGS) else 0)
| (if (o.HIDEPRINTTOFILE == 1) @enumToInt(PRINTDLGEX_FLAGS.HIDEPRINTTOFILE) else 0)
| (if (o.NOCURRENTPAGE == 1) @enumToInt(PRINTDLGEX_FLAGS.NOCURRENTPAGE) else 0)
| (if (o.NOPAGENUMS == 1) @enumToInt(PRINTDLGEX_FLAGS.NOPAGENUMS) else 0)
| (if (o.NOSELECTION == 1) @enumToInt(PRINTDLGEX_FLAGS.NOSELECTION) else 0)
| (if (o.NOWARNING == 1) @enumToInt(PRINTDLGEX_FLAGS.NOWARNING) else 0)
| (if (o.PAGENUMS == 1) @enumToInt(PRINTDLGEX_FLAGS.PAGENUMS) else 0)
| (if (o.PRINTTOFILE == 1) @enumToInt(PRINTDLGEX_FLAGS.PRINTTOFILE) else 0)
| (if (o.RETURNDC == 1) @enumToInt(PRINTDLGEX_FLAGS.RETURNDC) else 0)
| (if (o.RETURNDEFAULT == 1) @enumToInt(PRINTDLGEX_FLAGS.RETURNDEFAULT) else 0)
| (if (o.RETURNIC == 1) @enumToInt(PRINTDLGEX_FLAGS.RETURNIC) else 0)
| (if (o.SELECTION == 1) @enumToInt(PRINTDLGEX_FLAGS.SELECTION) else 0)
| (if (o.USEDEVMODECOPIES == 1) @enumToInt(PRINTDLGEX_FLAGS.USEDEVMODECOPIES) else 0)
| (if (o.USELARGETEMPLATE == 1) @enumToInt(PRINTDLGEX_FLAGS.USELARGETEMPLATE) else 0)
| (if (o.ENABLEPRINTHOOK == 1) @enumToInt(PRINTDLGEX_FLAGS.ENABLEPRINTHOOK) else 0)
| (if (o.ENABLESETUPHOOK == 1) @enumToInt(PRINTDLGEX_FLAGS.ENABLESETUPHOOK) else 0)
| (if (o.ENABLESETUPTEMPLATE == 1) @enumToInt(PRINTDLGEX_FLAGS.ENABLESETUPTEMPLATE) else 0)
| (if (o.ENABLESETUPTEMPLATEHANDLE == 1) @enumToInt(PRINTDLGEX_FLAGS.ENABLESETUPTEMPLATEHANDLE) else 0)
| (if (o.NONETWORKBUTTON == 1) @enumToInt(PRINTDLGEX_FLAGS.NONETWORKBUTTON) else 0)
| (if (o.PRINTSETUP == 1) @enumToInt(PRINTDLGEX_FLAGS.PRINTSETUP) else 0)
| (if (o.SHOWHELP == 1) @enumToInt(PRINTDLGEX_FLAGS.SHOWHELP) else 0)
);
}
};
pub const PD_ALLPAGES = PRINTDLGEX_FLAGS.ALLPAGES;
pub const PD_COLLATE = PRINTDLGEX_FLAGS.COLLATE;
pub const PD_CURRENTPAGE = PRINTDLGEX_FLAGS.CURRENTPAGE;
pub const PD_DISABLEPRINTTOFILE = PRINTDLGEX_FLAGS.DISABLEPRINTTOFILE;
pub const PD_ENABLEPRINTTEMPLATE = PRINTDLGEX_FLAGS.ENABLEPRINTTEMPLATE;
pub const PD_ENABLEPRINTTEMPLATEHANDLE = PRINTDLGEX_FLAGS.ENABLEPRINTTEMPLATEHANDLE;
pub const PD_EXCLUSIONFLAGS = PRINTDLGEX_FLAGS.EXCLUSIONFLAGS;
pub const PD_HIDEPRINTTOFILE = PRINTDLGEX_FLAGS.HIDEPRINTTOFILE;
pub const PD_NOCURRENTPAGE = PRINTDLGEX_FLAGS.NOCURRENTPAGE;
pub const PD_NOPAGENUMS = PRINTDLGEX_FLAGS.NOPAGENUMS;
pub const PD_NOSELECTION = PRINTDLGEX_FLAGS.NOSELECTION;
pub const PD_NOWARNING = PRINTDLGEX_FLAGS.NOWARNING;
pub const PD_PAGENUMS = PRINTDLGEX_FLAGS.PAGENUMS;
pub const PD_PRINTTOFILE = PRINTDLGEX_FLAGS.PRINTTOFILE;
pub const PD_RETURNDC = PRINTDLGEX_FLAGS.RETURNDC;
pub const PD_RETURNDEFAULT = PRINTDLGEX_FLAGS.RETURNDEFAULT;
pub const PD_RETURNIC = PRINTDLGEX_FLAGS.RETURNIC;
pub const PD_SELECTION = PRINTDLGEX_FLAGS.SELECTION;
pub const PD_USEDEVMODECOPIES = PRINTDLGEX_FLAGS.USEDEVMODECOPIES;
pub const PD_USEDEVMODECOPIESANDCOLLATE = PRINTDLGEX_FLAGS.USEDEVMODECOPIES;
pub const PD_USELARGETEMPLATE = PRINTDLGEX_FLAGS.USELARGETEMPLATE;
pub const PD_ENABLEPRINTHOOK = PRINTDLGEX_FLAGS.ENABLEPRINTHOOK;
pub const PD_ENABLESETUPHOOK = PRINTDLGEX_FLAGS.ENABLESETUPHOOK;
pub const PD_ENABLESETUPTEMPLATE = PRINTDLGEX_FLAGS.ENABLESETUPTEMPLATE;
pub const PD_ENABLESETUPTEMPLATEHANDLE = PRINTDLGEX_FLAGS.ENABLESETUPTEMPLATEHANDLE;
pub const PD_NONETWORKBUTTON = PRINTDLGEX_FLAGS.NONETWORKBUTTON;
pub const PD_PRINTSETUP = PRINTDLGEX_FLAGS.PRINTSETUP;
pub const PD_SHOWHELP = PRINTDLGEX_FLAGS.SHOWHELP;
pub const MOUSEHOOKSTRUCTEX_MOUSE_DATA = enum(u32) {
@"1" = 1,
@"2" = 2,
_,
pub fn initFlags(o: struct {
@"1": u1 = 0,
@"2": u1 = 0,
}) MOUSEHOOKSTRUCTEX_MOUSE_DATA {
return @intToEnum(MOUSEHOOKSTRUCTEX_MOUSE_DATA,
(if (o.@"1" == 1) @enumToInt(MOUSEHOOKSTRUCTEX_MOUSE_DATA.@"1") else 0)
| (if (o.@"2" == 1) @enumToInt(MOUSEHOOKSTRUCTEX_MOUSE_DATA.@"2") else 0)
);
}
};
pub const XBUTTON1 = MOUSEHOOKSTRUCTEX_MOUSE_DATA.@"1";
pub const XBUTTON2 = MOUSEHOOKSTRUCTEX_MOUSE_DATA.@"2";
pub const MENU_ITEM_MASK = enum(u32) {
BITMAP = 128,
CHECKMARKS = 8,
DATA = 32,
FTYPE = 256,
ID = 2,
STATE = 1,
STRING = 64,
SUBMENU = 4,
TYPE = 16,
_,
pub fn initFlags(o: struct {
BITMAP: u1 = 0,
CHECKMARKS: u1 = 0,
DATA: u1 = 0,
FTYPE: u1 = 0,
ID: u1 = 0,
STATE: u1 = 0,
STRING: u1 = 0,
SUBMENU: u1 = 0,
TYPE: u1 = 0,
}) MENU_ITEM_MASK {
return @intToEnum(MENU_ITEM_MASK,
(if (o.BITMAP == 1) @enumToInt(MENU_ITEM_MASK.BITMAP) else 0)
| (if (o.CHECKMARKS == 1) @enumToInt(MENU_ITEM_MASK.CHECKMARKS) else 0)
| (if (o.DATA == 1) @enumToInt(MENU_ITEM_MASK.DATA) else 0)
| (if (o.FTYPE == 1) @enumToInt(MENU_ITEM_MASK.FTYPE) else 0)
| (if (o.ID == 1) @enumToInt(MENU_ITEM_MASK.ID) else 0)
| (if (o.STATE == 1) @enumToInt(MENU_ITEM_MASK.STATE) else 0)
| (if (o.STRING == 1) @enumToInt(MENU_ITEM_MASK.STRING) else 0)
| (if (o.SUBMENU == 1) @enumToInt(MENU_ITEM_MASK.SUBMENU) else 0)
| (if (o.TYPE == 1) @enumToInt(MENU_ITEM_MASK.TYPE) else 0)
);
}
};
pub const MIIM_BITMAP = MENU_ITEM_MASK.BITMAP;
pub const MIIM_CHECKMARKS = MENU_ITEM_MASK.CHECKMARKS;
pub const MIIM_DATA = MENU_ITEM_MASK.DATA;
pub const MIIM_FTYPE = MENU_ITEM_MASK.FTYPE;
pub const MIIM_ID = MENU_ITEM_MASK.ID;
pub const MIIM_STATE = MENU_ITEM_MASK.STATE;
pub const MIIM_STRING = MENU_ITEM_MASK.STRING;
pub const MIIM_SUBMENU = MENU_ITEM_MASK.SUBMENU;
pub const MIIM_TYPE = MENU_ITEM_MASK.TYPE;
pub const FLASHWINFO_FLAGS = enum(u32) {
ALL = 3,
CAPTION = 1,
STOP = 0,
TIMER = 4,
TIMERNOFG = 12,
TRAY = 2,
_,
pub fn initFlags(o: struct {
ALL: u1 = 0,
CAPTION: u1 = 0,
STOP: u1 = 0,
TIMER: u1 = 0,
TIMERNOFG: u1 = 0,
TRAY: u1 = 0,
}) FLASHWINFO_FLAGS {
return @intToEnum(FLASHWINFO_FLAGS,
(if (o.ALL == 1) @enumToInt(FLASHWINFO_FLAGS.ALL) else 0)
| (if (o.CAPTION == 1) @enumToInt(FLASHWINFO_FLAGS.CAPTION) else 0)
| (if (o.STOP == 1) @enumToInt(FLASHWINFO_FLAGS.STOP) else 0)
| (if (o.TIMER == 1) @enumToInt(FLASHWINFO_FLAGS.TIMER) else 0)
| (if (o.TIMERNOFG == 1) @enumToInt(FLASHWINFO_FLAGS.TIMERNOFG) else 0)
| (if (o.TRAY == 1) @enumToInt(FLASHWINFO_FLAGS.TRAY) else 0)
);
}
};
pub const FLASHW_ALL = FLASHWINFO_FLAGS.ALL;
pub const FLASHW_CAPTION = FLASHWINFO_FLAGS.CAPTION;
pub const FLASHW_STOP = FLASHWINFO_FLAGS.STOP;
pub const FLASHW_TIMER = FLASHWINFO_FLAGS.TIMER;
pub const FLASHW_TIMERNOFG = FLASHWINFO_FLAGS.TIMERNOFG;
pub const FLASHW_TRAY = FLASHWINFO_FLAGS.TRAY;
pub const CURSORINFO_FLAGS = enum(u32) {
HOWING = 1,
UPPRESSED = 2,
};
pub const CURSOR_SHOWING = CURSORINFO_FLAGS.HOWING;
pub const CURSOR_SUPPRESSED = CURSORINFO_FLAGS.UPPRESSED;
pub const MENUINFO_STYLE = enum(u32) {
AUTODISMISS = 268435456,
CHECKORBMP = 67108864,
DRAGDROP = 536870912,
MODELESS = 1073741824,
NOCHECK = 2147483648,
NOTIFYBYPOS = 134217728,
_,
pub fn initFlags(o: struct {
AUTODISMISS: u1 = 0,
CHECKORBMP: u1 = 0,
DRAGDROP: u1 = 0,
MODELESS: u1 = 0,
NOCHECK: u1 = 0,
NOTIFYBYPOS: u1 = 0,
}) MENUINFO_STYLE {
return @intToEnum(MENUINFO_STYLE,
(if (o.AUTODISMISS == 1) @enumToInt(MENUINFO_STYLE.AUTODISMISS) else 0)
| (if (o.CHECKORBMP == 1) @enumToInt(MENUINFO_STYLE.CHECKORBMP) else 0)
| (if (o.DRAGDROP == 1) @enumToInt(MENUINFO_STYLE.DRAGDROP) else 0)
| (if (o.MODELESS == 1) @enumToInt(MENUINFO_STYLE.MODELESS) else 0)
| (if (o.NOCHECK == 1) @enumToInt(MENUINFO_STYLE.NOCHECK) else 0)
| (if (o.NOTIFYBYPOS == 1) @enumToInt(MENUINFO_STYLE.NOTIFYBYPOS) else 0)
);
}
};
pub const MNS_AUTODISMISS = MENUINFO_STYLE.AUTODISMISS;
pub const MNS_CHECKORBMP = MENUINFO_STYLE.CHECKORBMP;
pub const MNS_DRAGDROP = MENUINFO_STYLE.DRAGDROP;
pub const MNS_MODELESS = MENUINFO_STYLE.MODELESS;
pub const MNS_NOCHECK = MENUINFO_STYLE.NOCHECK;
pub const MNS_NOTIFYBYPOS = MENUINFO_STYLE.NOTIFYBYPOS;
pub const WINDOWPLACEMENT_FLAGS = enum(u32) {
ASYNCWINDOWPLACEMENT = 4,
RESTORETOMAXIMIZED = 2,
SETMINPOSITION = 1,
_,
pub fn initFlags(o: struct {
ASYNCWINDOWPLACEMENT: u1 = 0,
RESTORETOMAXIMIZED: u1 = 0,
SETMINPOSITION: u1 = 0,
}) WINDOWPLACEMENT_FLAGS {
return @intToEnum(WINDOWPLACEMENT_FLAGS,
(if (o.ASYNCWINDOWPLACEMENT == 1) @enumToInt(WINDOWPLACEMENT_FLAGS.ASYNCWINDOWPLACEMENT) else 0)
| (if (o.RESTORETOMAXIMIZED == 1) @enumToInt(WINDOWPLACEMENT_FLAGS.RESTORETOMAXIMIZED) else 0)
| (if (o.SETMINPOSITION == 1) @enumToInt(WINDOWPLACEMENT_FLAGS.SETMINPOSITION) else 0)
);
}
};
pub const WPF_ASYNCWINDOWPLACEMENT = WINDOWPLACEMENT_FLAGS.ASYNCWINDOWPLACEMENT;
pub const WPF_RESTORETOMAXIMIZED = WINDOWPLACEMENT_FLAGS.RESTORETOMAXIMIZED;
pub const WPF_SETMINPOSITION = WINDOWPLACEMENT_FLAGS.SETMINPOSITION;
pub const CHOOSEFONT_FONT_TYPE = enum(u16) {
BOLD_FONTTYPE = 256,
ITALIC_FONTTYPE = 512,
PRINTER_FONTTYPE = 16384,
REGULAR_FONTTYPE = 1024,
SCREEN_FONTTYPE = 8192,
SIMULATED_FONTTYPE = 32768,
_,
pub fn initFlags(o: struct {
BOLD_FONTTYPE: u1 = 0,
ITALIC_FONTTYPE: u1 = 0,
PRINTER_FONTTYPE: u1 = 0,
REGULAR_FONTTYPE: u1 = 0,
SCREEN_FONTTYPE: u1 = 0,
SIMULATED_FONTTYPE: u1 = 0,
}) CHOOSEFONT_FONT_TYPE {
return @intToEnum(CHOOSEFONT_FONT_TYPE,
(if (o.BOLD_FONTTYPE == 1) @enumToInt(CHOOSEFONT_FONT_TYPE.BOLD_FONTTYPE) else 0)
| (if (o.ITALIC_FONTTYPE == 1) @enumToInt(CHOOSEFONT_FONT_TYPE.ITALIC_FONTTYPE) else 0)
| (if (o.PRINTER_FONTTYPE == 1) @enumToInt(CHOOSEFONT_FONT_TYPE.PRINTER_FONTTYPE) else 0)
| (if (o.REGULAR_FONTTYPE == 1) @enumToInt(CHOOSEFONT_FONT_TYPE.REGULAR_FONTTYPE) else 0)
| (if (o.SCREEN_FONTTYPE == 1) @enumToInt(CHOOSEFONT_FONT_TYPE.SCREEN_FONTTYPE) else 0)
| (if (o.SIMULATED_FONTTYPE == 1) @enumToInt(CHOOSEFONT_FONT_TYPE.SIMULATED_FONTTYPE) else 0)
);
}
};
pub const BOLD_FONTTYPE = CHOOSEFONT_FONT_TYPE.BOLD_FONTTYPE;
pub const ITALIC_FONTTYPE = CHOOSEFONT_FONT_TYPE.ITALIC_FONTTYPE;
pub const PRINTER_FONTTYPE = CHOOSEFONT_FONT_TYPE.PRINTER_FONTTYPE;
pub const REGULAR_FONTTYPE = CHOOSEFONT_FONT_TYPE.REGULAR_FONTTYPE;
pub const SCREEN_FONTTYPE = CHOOSEFONT_FONT_TYPE.SCREEN_FONTTYPE;
pub const SIMULATED_FONTTYPE = CHOOSEFONT_FONT_TYPE.SIMULATED_FONTTYPE;
pub const MENUINFO_MASK = enum(u32) {
APPLYTOSUBMENUS = 2147483648,
BACKGROUND = 2,
HELPID = 4,
MAXHEIGHT = 1,
MENUDATA = 8,
STYLE = 16,
_,
pub fn initFlags(o: struct {
APPLYTOSUBMENUS: u1 = 0,
BACKGROUND: u1 = 0,
HELPID: u1 = 0,
MAXHEIGHT: u1 = 0,
MENUDATA: u1 = 0,
STYLE: u1 = 0,
}) MENUINFO_MASK {
return @intToEnum(MENUINFO_MASK,
(if (o.APPLYTOSUBMENUS == 1) @enumToInt(MENUINFO_MASK.APPLYTOSUBMENUS) else 0)
| (if (o.BACKGROUND == 1) @enumToInt(MENUINFO_MASK.BACKGROUND) else 0)
| (if (o.HELPID == 1) @enumToInt(MENUINFO_MASK.HELPID) else 0)
| (if (o.MAXHEIGHT == 1) @enumToInt(MENUINFO_MASK.MAXHEIGHT) else 0)
| (if (o.MENUDATA == 1) @enumToInt(MENUINFO_MASK.MENUDATA) else 0)
| (if (o.STYLE == 1) @enumToInt(MENUINFO_MASK.STYLE) else 0)
);
}
};
pub const MIM_APPLYTOSUBMENUS = MENUINFO_MASK.APPLYTOSUBMENUS;
pub const MIM_BACKGROUND = MENUINFO_MASK.BACKGROUND;
pub const MIM_HELPID = MENUINFO_MASK.HELPID;
pub const MIM_MAXHEIGHT = MENUINFO_MASK.MAXHEIGHT;
pub const MIM_MENUDATA = MENUINFO_MASK.MENUDATA;
pub const MIM_STYLE = MENUINFO_MASK.STYLE;
pub const MINIMIZEDMETRICS_ARRANGE = enum(i32) {
BOTTOMLEFT = 0,
BOTTOMRIGHT = 1,
TOPLEFT = 2,
TOPRIGHT = 3,
};
pub const ARW_BOTTOMLEFT = MINIMIZEDMETRICS_ARRANGE.BOTTOMLEFT;
pub const ARW_BOTTOMRIGHT = MINIMIZEDMETRICS_ARRANGE.BOTTOMRIGHT;
pub const ARW_TOPLEFT = MINIMIZEDMETRICS_ARRANGE.TOPLEFT;
pub const ARW_TOPRIGHT = MINIMIZEDMETRICS_ARRANGE.TOPRIGHT;
pub const MENUGETOBJECTINFO_FLAGS = enum(u32) {
BOTTOMGAP = 2,
TOPGAP = 1,
};
pub const MNGOF_BOTTOMGAP = MENUGETOBJECTINFO_FLAGS.BOTTOMGAP;
pub const MNGOF_TOPGAP = MENUGETOBJECTINFO_FLAGS.TOPGAP;
pub const GUITHREADINFO_FLAGS = enum(u32) {
CARETBLINKING = 1,
INMENUMODE = 4,
INMOVESIZE = 2,
POPUPMENUMODE = 16,
SYSTEMMENUMODE = 8,
_,
pub fn initFlags(o: struct {
CARETBLINKING: u1 = 0,
INMENUMODE: u1 = 0,
INMOVESIZE: u1 = 0,
POPUPMENUMODE: u1 = 0,
SYSTEMMENUMODE: u1 = 0,
}) GUITHREADINFO_FLAGS {
return @intToEnum(GUITHREADINFO_FLAGS,
(if (o.CARETBLINKING == 1) @enumToInt(GUITHREADINFO_FLAGS.CARETBLINKING) else 0)
| (if (o.INMENUMODE == 1) @enumToInt(GUITHREADINFO_FLAGS.INMENUMODE) else 0)
| (if (o.INMOVESIZE == 1) @enumToInt(GUITHREADINFO_FLAGS.INMOVESIZE) else 0)
| (if (o.POPUPMENUMODE == 1) @enumToInt(GUITHREADINFO_FLAGS.POPUPMENUMODE) else 0)
| (if (o.SYSTEMMENUMODE == 1) @enumToInt(GUITHREADINFO_FLAGS.SYSTEMMENUMODE) else 0)
);
}
};
pub const GUI_CARETBLINKING = GUITHREADINFO_FLAGS.CARETBLINKING;
pub const GUI_INMENUMODE = GUITHREADINFO_FLAGS.INMENUMODE;
pub const GUI_INMOVESIZE = GUITHREADINFO_FLAGS.INMOVESIZE;
pub const GUI_POPUPMENUMODE = GUITHREADINFO_FLAGS.POPUPMENUMODE;
pub const GUI_SYSTEMMENUMODE = GUITHREADINFO_FLAGS.SYSTEMMENUMODE;
pub const KBDLLHOOKSTRUCT_FLAGS = enum(u32) {
EXTENDED = 1,
ALTDOWN = 32,
UP = 128,
INJECTED = 16,
LOWER_IL_INJECTED = 2,
_,
pub fn initFlags(o: struct {
EXTENDED: u1 = 0,
ALTDOWN: u1 = 0,
UP: u1 = 0,
INJECTED: u1 = 0,
LOWER_IL_INJECTED: u1 = 0,
}) KBDLLHOOKSTRUCT_FLAGS {
return @intToEnum(KBDLLHOOKSTRUCT_FLAGS,
(if (o.EXTENDED == 1) @enumToInt(KBDLLHOOKSTRUCT_FLAGS.EXTENDED) else 0)
| (if (o.ALTDOWN == 1) @enumToInt(KBDLLHOOKSTRUCT_FLAGS.ALTDOWN) else 0)
| (if (o.UP == 1) @enumToInt(KBDLLHOOKSTRUCT_FLAGS.UP) else 0)
| (if (o.INJECTED == 1) @enumToInt(KBDLLHOOKSTRUCT_FLAGS.INJECTED) else 0)
| (if (o.LOWER_IL_INJECTED == 1) @enumToInt(KBDLLHOOKSTRUCT_FLAGS.LOWER_IL_INJECTED) else 0)
);
}
};
pub const LLKHF_EXTENDED = KBDLLHOOKSTRUCT_FLAGS.EXTENDED;
pub const LLKHF_ALTDOWN = KBDLLHOOKSTRUCT_FLAGS.ALTDOWN;
pub const LLKHF_UP = KBDLLHOOKSTRUCT_FLAGS.UP;
pub const LLKHF_INJECTED = KBDLLHOOKSTRUCT_FLAGS.INJECTED;
pub const LLKHF_LOWER_IL_INJECTED = KBDLLHOOKSTRUCT_FLAGS.LOWER_IL_INJECTED;
pub const WINSTAENUMPROCA = fn(
param0: ?PSTR,
param1: LPARAM,
) callconv(@import("std").os.windows.WINAPI) BOOL;
pub const WINSTAENUMPROCW = fn(
param0: ?PWSTR,
param1: LPARAM,
) callconv(@import("std").os.windows.WINAPI) BOOL;
pub const DESKTOPENUMPROCA = fn(
param0: ?PSTR,
param1: LPARAM,
) callconv(@import("std").os.windows.WINAPI) BOOL;
pub const DESKTOPENUMPROCW = fn(
param0: ?PWSTR,
param1: LPARAM,
) callconv(@import("std").os.windows.WINAPI) BOOL;
pub const DI_FLAGS = enum(u32) {
MASK = 1,
IMAGE = 2,
NORMAL = 3,
COMPAT = 4,
DEFAULTSIZE = 8,
NOMIRROR = 16,
_,
pub fn initFlags(o: struct {
MASK: u1 = 0,
IMAGE: u1 = 0,
NORMAL: u1 = 0,
COMPAT: u1 = 0,
DEFAULTSIZE: u1 = 0,
NOMIRROR: u1 = 0,
}) DI_FLAGS {
return @intToEnum(DI_FLAGS,
(if (o.MASK == 1) @enumToInt(DI_FLAGS.MASK) else 0)
| (if (o.IMAGE == 1) @enumToInt(DI_FLAGS.IMAGE) else 0)
| (if (o.NORMAL == 1) @enumToInt(DI_FLAGS.NORMAL) else 0)
| (if (o.COMPAT == 1) @enumToInt(DI_FLAGS.COMPAT) else 0)
| (if (o.DEFAULTSIZE == 1) @enumToInt(DI_FLAGS.DEFAULTSIZE) else 0)
| (if (o.NOMIRROR == 1) @enumToInt(DI_FLAGS.NOMIRROR) else 0)
);
}
};
pub const DI_MASK = DI_FLAGS.MASK;
pub const DI_IMAGE = DI_FLAGS.IMAGE;
pub const DI_NORMAL = DI_FLAGS.NORMAL;
pub const DI_COMPAT = DI_FLAGS.COMPAT;
pub const DI_DEFAULTSIZE = DI_FLAGS.DEFAULTSIZE;
pub const DI_NOMIRROR = DI_FLAGS.NOMIRROR;
// TODO: this type has a FreeFunc 'UnhookWindowsHookEx', what can Zig do with this information?
pub const HHOOK = *opaque{};
// TODO: this type has a FreeFunc 'DestroyIcon', what can Zig do with this information?
pub const HICON = *opaque{};
// TODO: this type has a FreeFunc 'DestroyMenu', what can Zig do with this information?
pub const HMENU = *opaque{};
// TODO: this type has a FreeFunc 'DestroyCursor', what can Zig do with this information?
//TODO: type 'HCURSOR' is "AlsoUsableFor" 'HICON' which means this type is implicitly
// convertible to 'HICON' but not the other way around. I don't know how to do this
// in Zig so for now I'm just defining it as an alias
pub const HCURSOR = HICON;
// TODO: this type has a FreeFunc 'DestroyAcceleratorTable', what can Zig do with this information?
pub const HACCEL = *opaque{};
pub const MESSAGE_RESOURCE_ENTRY = extern struct {
Length: u16,
Flags: u16,
Text: [1]u8,
};
pub const MESSAGE_RESOURCE_BLOCK = extern struct {
LowId: u32,
HighId: u32,
OffsetToEntries: u32,
};
pub const MESSAGE_RESOURCE_DATA = extern struct {
NumberOfBlocks: u32,
Blocks: [1]MESSAGE_RESOURCE_BLOCK,
};
pub const LPOFNHOOKPROC = fn(
param0: ?HWND,
param1: u32,
param2: WPARAM,
param3: LPARAM,
) callconv(@import("std").os.windows.WINAPI) usize;
pub const LPCCHOOKPROC = fn(
param0: ?HWND,
param1: u32,
param2: WPARAM,
param3: LPARAM,
) callconv(@import("std").os.windows.WINAPI) usize;
pub const LPFRHOOKPROC = fn(
param0: ?HWND,
param1: u32,
param2: WPARAM,
param3: LPARAM,
) callconv(@import("std").os.windows.WINAPI) usize;
pub const LPCFHOOKPROC = fn(
param0: ?HWND,
param1: u32,
param2: WPARAM,
param3: LPARAM,
) callconv(@import("std").os.windows.WINAPI) usize;
pub const LPPRINTHOOKPROC = fn(
param0: ?HWND,
param1: u32,
param2: WPARAM,
param3: LPARAM,
) callconv(@import("std").os.windows.WINAPI) usize;
pub const LPSETUPHOOKPROC = fn(
param0: ?HWND,
param1: u32,
param2: WPARAM,
param3: LPARAM,
) callconv(@import("std").os.windows.WINAPI) usize;
// TODO: this type is limited to platform 'windows5.0'
const IID_IPrintDialogCallback_Value = @import("../zig.zig").Guid.initString("5852a2c3-6530-11d1-b6a3-0000f8757bf9");
pub const IID_IPrintDialogCallback = &IID_IPrintDialogCallback_Value;
pub const IPrintDialogCallback = extern struct {
pub const VTable = extern struct {
base: IUnknown.VTable,
InitDone: fn(
self: *const IPrintDialogCallback,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
SelectionChange: fn(
self: *const IPrintDialogCallback,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
HandleMessage: fn(
self: *const IPrintDialogCallback,
hDlg: ?HWND,
uMsg: u32,
wParam: WPARAM,
lParam: LPARAM,
pResult: ?*LRESULT,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
};
vtable: *const VTable,
pub fn MethodMixin(comptime T: type) type { return struct {
pub usingnamespace IUnknown.MethodMixin(T);
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IPrintDialogCallback_InitDone(self: *const T) callconv(.Inline) HRESULT {
return @ptrCast(*const IPrintDialogCallback.VTable, self.vtable).InitDone(@ptrCast(*const IPrintDialogCallback, self));
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IPrintDialogCallback_SelectionChange(self: *const T) callconv(.Inline) HRESULT {
return @ptrCast(*const IPrintDialogCallback.VTable, self.vtable).SelectionChange(@ptrCast(*const IPrintDialogCallback, self));
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IPrintDialogCallback_HandleMessage(self: *const T, hDlg: ?HWND, uMsg: u32, wParam: WPARAM, lParam: LPARAM, pResult: ?*LRESULT) callconv(.Inline) HRESULT {
return @ptrCast(*const IPrintDialogCallback.VTable, self.vtable).HandleMessage(@ptrCast(*const IPrintDialogCallback, self), hDlg, uMsg, wParam, lParam, pResult);
}
};}
pub usingnamespace MethodMixin(@This());
};
// TODO: this type is limited to platform 'windows5.0'
const IID_IPrintDialogServices_Value = @import("../zig.zig").Guid.initString("509aaeda-5639-11d1-b6a1-0000f8757bf9");
pub const IID_IPrintDialogServices = &IID_IPrintDialogServices_Value;
pub const IPrintDialogServices = extern struct {
pub const VTable = extern struct {
base: IUnknown.VTable,
GetCurrentDevMode: fn(
self: *const IPrintDialogServices,
pDevMode: ?*DEVMODEA,
pcbSize: ?*u32,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
GetCurrentPrinterName: fn(
self: *const IPrintDialogServices,
pPrinterName: ?[*:0]u16,
pcchSize: ?*u32,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
GetCurrentPortName: fn(
self: *const IPrintDialogServices,
pPortName: ?[*:0]u16,
pcchSize: ?*u32,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
};
vtable: *const VTable,
pub fn MethodMixin(comptime T: type) type { return struct {
pub usingnamespace IUnknown.MethodMixin(T);
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IPrintDialogServices_GetCurrentDevMode(self: *const T, pDevMode: ?*DEVMODEA, pcbSize: ?*u32) callconv(.Inline) HRESULT {
return @ptrCast(*const IPrintDialogServices.VTable, self.vtable).GetCurrentDevMode(@ptrCast(*const IPrintDialogServices, self), pDevMode, pcbSize);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IPrintDialogServices_GetCurrentPrinterName(self: *const T, pPrinterName: ?[*:0]u16, pcchSize: ?*u32) callconv(.Inline) HRESULT {
return @ptrCast(*const IPrintDialogServices.VTable, self.vtable).GetCurrentPrinterName(@ptrCast(*const IPrintDialogServices, self), pPrinterName, pcchSize);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IPrintDialogServices_GetCurrentPortName(self: *const T, pPortName: ?[*:0]u16, pcchSize: ?*u32) callconv(.Inline) HRESULT {
return @ptrCast(*const IPrintDialogServices.VTable, self.vtable).GetCurrentPortName(@ptrCast(*const IPrintDialogServices, self), pPortName, pcchSize);
}
};}
pub usingnamespace MethodMixin(@This());
};
pub const LPPAGEPAINTHOOK = fn(
param0: ?HWND,
param1: u32,
param2: WPARAM,
param3: LPARAM,
) callconv(@import("std").os.windows.WINAPI) usize;
pub const LPPAGESETUPHOOK = fn(
param0: ?HWND,
param1: u32,
param2: WPARAM,
param3: LPARAM,
) callconv(@import("std").os.windows.WINAPI) usize;
pub const WNDPROC = fn(
param0: HWND,
param1: u32,
param2: WPARAM,
param3: LPARAM,
) callconv(@import("std").os.windows.WINAPI) LRESULT;
pub const DLGPROC = fn(
param0: HWND,
param1: u32,
param2: WPARAM,
param3: LPARAM,
) callconv(@import("std").os.windows.WINAPI) isize;
pub const TIMERPROC = fn(
param0: HWND,
param1: u32,
param2: usize,
param3: u32,
) callconv(@import("std").os.windows.WINAPI) void;
pub const WNDENUMPROC = fn(
param0: HWND,
param1: LPARAM,
) callconv(@import("std").os.windows.WINAPI) BOOL;
pub const HOOKPROC = fn(
code: i32,
wParam: WPARAM,
lParam: LPARAM,
) callconv(@import("std").os.windows.WINAPI) LRESULT;
pub const SENDASYNCPROC = fn(
param0: HWND,
param1: u32,
param2: usize,
param3: LRESULT,
) callconv(@import("std").os.windows.WINAPI) void;
pub const PROPENUMPROCA = fn(
param0: HWND,
param1: ?[*:0]const u8,
param2: ?HANDLE,
) callconv(@import("std").os.windows.WINAPI) BOOL;
pub const PROPENUMPROCW = fn(
param0: HWND,
param1: ?[*:0]const u16,
param2: ?HANDLE,
) callconv(@import("std").os.windows.WINAPI) BOOL;
pub const PROPENUMPROCEXA = fn(
param0: HWND,
param1: ?PSTR,
param2: ?HANDLE,
param3: usize,
) callconv(@import("std").os.windows.WINAPI) BOOL;
pub const PROPENUMPROCEXW = fn(
param0: HWND,
param1: ?PWSTR,
param2: ?HANDLE,
param3: usize,
) callconv(@import("std").os.windows.WINAPI) BOOL;
pub const NAMEENUMPROCA = fn(
param0: ?PSTR,
param1: LPARAM,
) callconv(@import("std").os.windows.WINAPI) BOOL;
pub const NAMEENUMPROCW = fn(
param0: ?PWSTR,
param1: LPARAM,
) callconv(@import("std").os.windows.WINAPI) BOOL;
pub const CBT_CREATEWNDA = extern struct {
lpcs: ?*CREATESTRUCTA,
hwndInsertAfter: ?HWND,
};
pub const CBT_CREATEWNDW = extern struct {
lpcs: ?*CREATESTRUCTW,
hwndInsertAfter: ?HWND,
};
pub const CBTACTIVATESTRUCT = extern struct {
fMouse: BOOL,
hWndActive: ?HWND,
};
pub const SHELLHOOKINFO = extern struct {
hwnd: ?HWND,
rc: RECT,
};
pub const EVENTMSG = extern struct {
message: u32,
paramL: u32,
paramH: u32,
time: u32,
hwnd: ?HWND,
};
pub const CWPSTRUCT = extern struct {
lParam: LPARAM,
wParam: WPARAM,
message: u32,
hwnd: ?HWND,
};
pub const CWPRETSTRUCT = extern struct {
lResult: LRESULT,
lParam: LPARAM,
wParam: WPARAM,
message: u32,
hwnd: ?HWND,
};
pub const KBDLLHOOKSTRUCT = extern struct {
vkCode: u32,
scanCode: u32,
flags: KBDLLHOOKSTRUCT_FLAGS,
time: u32,
dwExtraInfo: usize,
};
pub const MSLLHOOKSTRUCT = extern struct {
pt: POINT,
mouseData: MOUSEHOOKSTRUCTEX_MOUSE_DATA,
flags: u32,
time: u32,
dwExtraInfo: usize,
};
pub const DEBUGHOOKINFO = extern struct {
idThread: u32,
idThreadInstaller: u32,
lParam: LPARAM,
wParam: WPARAM,
code: i32,
};
pub const MOUSEHOOKSTRUCT = extern struct {
pt: POINT,
hwnd: ?HWND,
wHitTestCode: u32,
dwExtraInfo: usize,
};
pub const MOUSEHOOKSTRUCTEX = extern struct {
__AnonymousBase_winuser_L1173_C46: MOUSEHOOKSTRUCT,
mouseData: MOUSEHOOKSTRUCTEX_MOUSE_DATA,
};
pub const HARDWAREHOOKSTRUCT = extern struct {
hwnd: ?HWND,
message: u32,
wParam: WPARAM,
lParam: LPARAM,
};
pub const WNDCLASSEXA = extern struct {
cbSize: u32,
style: WNDCLASS_STYLES,
lpfnWndProc: ?WNDPROC,
cbClsExtra: i32,
cbWndExtra: i32,
hInstance: ?HINSTANCE,
hIcon: ?HICON,
hCursor: ?HCURSOR,
hbrBackground: ?HBRUSH,
lpszMenuName: ?[*:0]const u8,
lpszClassName: ?[*:0]const u8,
hIconSm: ?HICON,
};
pub const WNDCLASSEXW = extern struct {
cbSize: u32,
style: WNDCLASS_STYLES,
lpfnWndProc: ?WNDPROC,
cbClsExtra: i32,
cbWndExtra: i32,
hInstance: ?HINSTANCE,
hIcon: ?HICON,
hCursor: ?HCURSOR,
hbrBackground: ?HBRUSH,
lpszMenuName: ?[*:0]const u16,
lpszClassName: ?[*:0]const u16,
hIconSm: ?HICON,
};
pub const WNDCLASSA = extern struct {
style: WNDCLASS_STYLES,
lpfnWndProc: ?WNDPROC,
cbClsExtra: i32,
cbWndExtra: i32,
hInstance: ?HINSTANCE,
hIcon: ?HICON,
hCursor: ?HCURSOR,
hbrBackground: ?HBRUSH,
lpszMenuName: ?[*:0]const u8,
lpszClassName: ?[*:0]const u8,
};
pub const WNDCLASSW = extern struct {
style: WNDCLASS_STYLES,
lpfnWndProc: ?WNDPROC,
cbClsExtra: i32,
cbWndExtra: i32,
hInstance: ?HINSTANCE,
hIcon: ?HICON,
hCursor: ?HCURSOR,
hbrBackground: ?HBRUSH,
lpszMenuName: ?[*:0]const u16,
lpszClassName: ?[*:0]const u16,
};
pub const MSG = extern struct {
hwnd: ?HWND,
message: u32,
wParam: WPARAM,
lParam: LPARAM,
time: u32,
pt: POINT,
};
pub const MINMAXINFO = extern struct {
ptReserved: POINT,
ptMaxSize: POINT,
ptMaxPosition: POINT,
ptMinTrackSize: POINT,
ptMaxTrackSize: POINT,
};
pub const MDINEXTMENU = extern struct {
hmenuIn: ?HMENU,
hmenuNext: ?HMENU,
hwndNext: ?HWND,
};
pub const WINDOWPOS = extern struct {
hwnd: ?HWND,
hwndInsertAfter: ?HWND,
x: i32,
y: i32,
cx: i32,
cy: i32,
flags: SET_WINDOW_POS_FLAGS,
};
pub const NCCALCSIZE_PARAMS = extern struct {
rgrc: [3]RECT,
lppos: ?*WINDOWPOS,
};
pub const ACCEL = extern struct {
fVirt: u8,
key: u16,
cmd: u16,
};
pub const CREATESTRUCTA = extern struct {
lpCreateParams: ?*c_void,
hInstance: ?HINSTANCE,
hMenu: ?HMENU,
hwndParent: ?HWND,
cy: i32,
cx: i32,
y: i32,
x: i32,
style: i32,
lpszName: ?[*:0]const u8,
lpszClass: ?[*:0]const u8,
dwExStyle: u32,
};
pub const CREATESTRUCTW = extern struct {
lpCreateParams: ?*c_void,
hInstance: ?HINSTANCE,
hMenu: ?HMENU,
hwndParent: ?HWND,
cy: i32,
cx: i32,
y: i32,
x: i32,
style: i32,
lpszName: ?[*:0]const u16,
lpszClass: ?[*:0]const u16,
dwExStyle: u32,
};
pub const WINDOWPLACEMENT = extern struct {
length: u32,
flags: WINDOWPLACEMENT_FLAGS,
showCmd: SHOW_WINDOW_CMD,
ptMinPosition: POINT,
ptMaxPosition: POINT,
rcNormalPosition: RECT,
};
pub const STYLESTRUCT = extern struct {
styleOld: u32,
styleNew: u32,
};
pub const BSMINFO = extern struct {
cbSize: u32,
hdesk: ?HDESK,
hwnd: ?HWND,
luid: LUID,
};
pub const PREGISTERCLASSNAMEW = fn(
param0: ?[*:0]const u16,
) callconv(@import("std").os.windows.WINAPI) BOOLEAN;
pub const UPDATELAYEREDWINDOWINFO = extern struct {
cbSize: u32,
hdcDst: ?HDC,
pptDst: ?*const POINT,
psize: ?*const SIZE,
hdcSrc: ?HDC,
pptSrc: ?*const POINT,
crKey: u32,
pblend: ?*const BLENDFUNCTION,
dwFlags: UPDATE_LAYERED_WINDOW_FLAGS,
prcDirty: ?*const RECT,
};
pub const FLASHWINFO = extern struct {
cbSize: u32,
hwnd: ?HWND,
dwFlags: FLASHWINFO_FLAGS,
uCount: u32,
dwTimeout: u32,
};
pub const DLGTEMPLATE = extern struct {
// WARNING: unable to add field alignment because it's causing a compiler bug
style: u32,
dwExtendedStyle: u32,
cdit: u16,
x: i16,
y: i16,
cx: i16,
cy: i16,
};
pub const DLGITEMTEMPLATE = extern struct {
// WARNING: unable to add field alignment because it's causing a compiler bug
style: u32,
dwExtendedStyle: u32,
x: i16,
y: i16,
cx: i16,
cy: i16,
id: u16,
};
pub const POINTER_INPUT_TYPE = enum(i32) {
POINTER = 1,
TOUCH = 2,
PEN = 3,
MOUSE = 4,
TOUCHPAD = 5,
};
pub const PT_POINTER = POINTER_INPUT_TYPE.POINTER;
pub const PT_TOUCH = POINTER_INPUT_TYPE.TOUCH;
pub const PT_PEN = POINTER_INPUT_TYPE.PEN;
pub const PT_MOUSE = POINTER_INPUT_TYPE.MOUSE;
pub const PT_TOUCHPAD = POINTER_INPUT_TYPE.TOUCHPAD;
pub const TPMPARAMS = extern struct {
cbSize: u32,
rcExclude: RECT,
};
pub const MENUINFO = extern struct {
cbSize: u32,
fMask: MENUINFO_MASK,
dwStyle: MENUINFO_STYLE,
cyMax: u32,
hbrBack: ?HBRUSH,
dwContextHelpID: u32,
dwMenuData: usize,
};
pub const MENUGETOBJECTINFO = extern struct {
dwFlags: MENUGETOBJECTINFO_FLAGS,
uPos: u32,
hmenu: ?HMENU,
riid: ?*c_void,
pvObj: ?*c_void,
};
pub const MENUITEMINFOA = extern struct {
cbSize: u32,
fMask: MENU_ITEM_MASK,
fType: MENU_ITEM_TYPE,
fState: MENU_ITEM_STATE,
wID: u32,
hSubMenu: ?HMENU,
hbmpChecked: ?HBITMAP,
hbmpUnchecked: ?HBITMAP,
dwItemData: usize,
dwTypeData: ?PSTR,
cch: u32,
hbmpItem: ?HBITMAP,
};
pub const MENUITEMINFOW = extern struct {
cbSize: u32,
fMask: MENU_ITEM_MASK,
fType: MENU_ITEM_TYPE,
fState: MENU_ITEM_STATE,
wID: u32,
hSubMenu: ?HMENU,
hbmpChecked: ?HBITMAP,
hbmpUnchecked: ?HBITMAP,
dwItemData: usize,
dwTypeData: ?PWSTR,
cch: u32,
hbmpItem: ?HBITMAP,
};
pub const DROPSTRUCT = extern struct {
hwndSource: ?HWND,
hwndSink: ?HWND,
wFmt: u32,
dwData: usize,
ptDrop: POINT,
dwControlData: u32,
};
pub const MSGBOXCALLBACK = fn(
lpHelpInfo: ?*HELPINFO,
) callconv(@import("std").os.windows.WINAPI) void;
pub const MSGBOXPARAMSA = extern struct {
cbSize: u32,
hwndOwner: ?HWND,
hInstance: ?HINSTANCE,
lpszText: ?[*:0]const u8,
lpszCaption: ?[*:0]const u8,
dwStyle: MESSAGEBOX_STYLE,
lpszIcon: ?[*:0]const u8,
dwContextHelpId: usize,
lpfnMsgBoxCallback: ?MSGBOXCALLBACK,
dwLanguageId: u32,
};
pub const MSGBOXPARAMSW = extern struct {
cbSize: u32,
hwndOwner: ?HWND,
hInstance: ?HINSTANCE,
lpszText: ?[*:0]const u16,
lpszCaption: ?[*:0]const u16,
dwStyle: MESSAGEBOX_STYLE,
lpszIcon: ?[*:0]const u16,
dwContextHelpId: usize,
lpfnMsgBoxCallback: ?MSGBOXCALLBACK,
dwLanguageId: u32,
};
pub const MENUITEMTEMPLATEHEADER = extern struct {
versionNumber: u16,
offset: u16,
};
pub const MENUITEMTEMPLATE = extern struct {
mtOption: u16,
mtID: u16,
mtString: [1]u16,
};
pub const ICONINFO = extern struct {
fIcon: BOOL,
xHotspot: u32,
yHotspot: u32,
hbmMask: ?HBITMAP,
hbmColor: ?HBITMAP,
};
pub const CURSORSHAPE = extern struct {
xHotSpot: i32,
yHotSpot: i32,
cx: i32,
cy: i32,
cbWidth: i32,
Planes: u8,
BitsPixel: u8,
};
pub const ICONINFOEXA = extern struct {
cbSize: u32,
fIcon: BOOL,
xHotspot: u32,
yHotspot: u32,
hbmMask: ?HBITMAP,
hbmColor: ?HBITMAP,
wResID: u16,
szModName: [260]CHAR,
szResName: [260]CHAR,
};
pub const ICONINFOEXW = extern struct {
cbSize: u32,
fIcon: BOOL,
xHotspot: u32,
yHotspot: u32,
hbmMask: ?HBITMAP,
hbmColor: ?HBITMAP,
wResID: u16,
szModName: [260]u16,
szResName: [260]u16,
};
pub const EDIT_CONTROL_FEATURE = enum(i32) {
ENTERPRISE_DATA_PROTECTION_PASTE_SUPPORT = 0,
PASTE_NOTIFICATIONS = 1,
};
pub const EDIT_CONTROL_FEATURE_ENTERPRISE_DATA_PROTECTION_PASTE_SUPPORT = EDIT_CONTROL_FEATURE.ENTERPRISE_DATA_PROTECTION_PASTE_SUPPORT;
pub const EDIT_CONTROL_FEATURE_PASTE_NOTIFICATIONS = EDIT_CONTROL_FEATURE.PASTE_NOTIFICATIONS;
pub const MDICREATESTRUCTA = extern struct {
szClass: ?[*:0]const u8,
szTitle: ?[*:0]const u8,
hOwner: ?HANDLE,
x: i32,
y: i32,
cx: i32,
cy: i32,
style: WINDOW_STYLE,
lParam: LPARAM,
};
pub const MDICREATESTRUCTW = extern struct {
szClass: ?[*:0]const u16,
szTitle: ?[*:0]const u16,
hOwner: ?HANDLE,
x: i32,
y: i32,
cx: i32,
cy: i32,
style: WINDOW_STYLE,
lParam: LPARAM,
};
pub const CLIENTCREATESTRUCT = extern struct {
hWindowMenu: ?HANDLE,
idFirstChild: u32,
};
pub const TouchPredictionParameters = extern struct {
cbSize: u32,
dwLatency: u32,
dwSampleTime: u32,
bUseHWTimeStamp: u32,
};
pub const HANDEDNESS = enum(i32) {
LEFT = 0,
RIGHT = 1,
};
pub const HANDEDNESS_LEFT = HANDEDNESS.LEFT;
pub const HANDEDNESS_RIGHT = HANDEDNESS.RIGHT;
pub const NONCLIENTMETRICSA = extern struct {
cbSize: u32,
iBorderWidth: i32,
iScrollWidth: i32,
iScrollHeight: i32,
iCaptionWidth: i32,
iCaptionHeight: i32,
lfCaptionFont: LOGFONTA,
iSmCaptionWidth: i32,
iSmCaptionHeight: i32,
lfSmCaptionFont: LOGFONTA,
iMenuWidth: i32,
iMenuHeight: i32,
lfMenuFont: LOGFONTA,
lfStatusFont: LOGFONTA,
lfMessageFont: LOGFONTA,
iPaddedBorderWidth: i32,
};
pub const NONCLIENTMETRICSW = extern struct {
cbSize: u32,
iBorderWidth: i32,
iScrollWidth: i32,
iScrollHeight: i32,
iCaptionWidth: i32,
iCaptionHeight: i32,
lfCaptionFont: LOGFONTW,
iSmCaptionWidth: i32,
iSmCaptionHeight: i32,
lfSmCaptionFont: LOGFONTW,
iMenuWidth: i32,
iMenuHeight: i32,
lfMenuFont: LOGFONTW,
lfStatusFont: LOGFONTW,
lfMessageFont: LOGFONTW,
iPaddedBorderWidth: i32,
};
pub const MINIMIZEDMETRICS = extern struct {
cbSize: u32,
iWidth: i32,
iHorzGap: i32,
iVertGap: i32,
iArrange: MINIMIZEDMETRICS_ARRANGE,
};
pub const ICONMETRICSA = extern struct {
cbSize: u32,
iHorzSpacing: i32,
iVertSpacing: i32,
iTitleWrap: i32,
lfFont: LOGFONTA,
};
pub const ICONMETRICSW = extern struct {
cbSize: u32,
iHorzSpacing: i32,
iVertSpacing: i32,
iTitleWrap: i32,
lfFont: LOGFONTW,
};
pub const ANIMATIONINFO = extern struct {
cbSize: u32,
iMinAnimate: i32,
};
pub const AUDIODESCRIPTION = extern struct {
cbSize: u32,
Enabled: BOOL,
Locale: u32,
};
pub const GUITHREADINFO = extern struct {
cbSize: u32,
flags: GUITHREADINFO_FLAGS,
hwndActive: ?HWND,
hwndFocus: ?HWND,
hwndCapture: ?HWND,
hwndMenuOwner: ?HWND,
hwndMoveSize: ?HWND,
hwndCaret: ?HWND,
rcCaret: RECT,
};
pub const CURSORINFO = extern struct {
cbSize: u32,
flags: CURSORINFO_FLAGS,
hCursor: ?HCURSOR,
ptScreenPos: POINT,
};
pub const WINDOWINFO = extern struct {
cbSize: u32,
rcWindow: RECT,
rcClient: RECT,
dwStyle: u32,
dwExStyle: u32,
dwWindowStatus: u32,
cxWindowBorders: u32,
cyWindowBorders: u32,
atomWindowType: u16,
wCreatorVersion: u16,
};
pub const TITLEBARINFO = extern struct {
cbSize: u32,
rcTitleBar: RECT,
rgstate: [6]u32,
};
pub const TITLEBARINFOEX = extern struct {
cbSize: u32,
rcTitleBar: RECT,
rgstate: [6]u32,
rgrect: [6]RECT,
};
pub const MENUBARINFO = extern struct {
cbSize: u32,
rcBar: RECT,
hMenu: ?HMENU,
hwndMenu: ?HWND,
_bitfield: i32,
};
pub const ALTTABINFO = extern struct {
cbSize: u32,
cItems: i32,
cColumns: i32,
cRows: i32,
iColFocus: i32,
iRowFocus: i32,
cxItem: i32,
cyItem: i32,
ptStart: POINT,
};
pub const CHANGEFILTERSTRUCT = extern struct {
cbSize: u32,
ExtStatus: MSGFLTINFO_STATUS,
};
pub const IndexedResourceQualifier = extern struct {
name: ?PWSTR,
value: ?PWSTR,
};
pub const MrmPlatformVersion = enum(i32) {
Default = 0,
Windows10_0_0_0 = 17432576,
Windows10_0_0_5 = 17432581,
};
pub const MrmPlatformVersion_Default = MrmPlatformVersion.Default;
pub const MrmPlatformVersion_Windows10_0_0_0 = MrmPlatformVersion.Windows10_0_0_0;
pub const MrmPlatformVersion_Windows10_0_0_5 = MrmPlatformVersion.Windows10_0_0_5;
pub const MrmResourceIndexerHandle = extern struct {
handle: ?*c_void,
};
pub const MrmPackagingMode = enum(i32) {
StandaloneFile = 0,
AutoSplit = 1,
ResourcePack = 2,
};
pub const MrmPackagingModeStandaloneFile = MrmPackagingMode.StandaloneFile;
pub const MrmPackagingModeAutoSplit = MrmPackagingMode.AutoSplit;
pub const MrmPackagingModeResourcePack = MrmPackagingMode.ResourcePack;
pub const MrmPackagingOptions = enum(i32) {
None = 0,
OmitSchemaFromResourcePacks = 1,
SplitLanguageVariants = 2,
};
pub const MrmPackagingOptionsNone = MrmPackagingOptions.None;
pub const MrmPackagingOptionsOmitSchemaFromResourcePacks = MrmPackagingOptions.OmitSchemaFromResourcePacks;
pub const MrmPackagingOptionsSplitLanguageVariants = MrmPackagingOptions.SplitLanguageVariants;
pub const MrmDumpType = enum(i32) {
Basic = 0,
Detailed = 1,
Schema = 2,
};
pub const MrmDumpType_Basic = MrmDumpType.Basic;
pub const MrmDumpType_Detailed = MrmDumpType.Detailed;
pub const MrmDumpType_Schema = MrmDumpType.Schema;
pub const MrmResourceIndexerMessageSeverity = enum(i32) {
Verbose = 0,
Info = 1,
Warning = 2,
Error = 3,
};
pub const MrmResourceIndexerMessageSeverityVerbose = MrmResourceIndexerMessageSeverity.Verbose;
pub const MrmResourceIndexerMessageSeverityInfo = MrmResourceIndexerMessageSeverity.Info;
pub const MrmResourceIndexerMessageSeverityWarning = MrmResourceIndexerMessageSeverity.Warning;
pub const MrmResourceIndexerMessageSeverityError = MrmResourceIndexerMessageSeverity.Error;
pub const MrmResourceIndexerMessage = extern struct {
severity: MrmResourceIndexerMessageSeverity,
id: u32,
text: ?[*:0]const u16,
};
pub const OPENFILENAME_NT4A = switch(@import("../zig.zig").arch) {
.X64, .Arm64 => extern struct {
lStructSize: u32,
hwndOwner: ?HWND,
hInstance: ?HINSTANCE,
lpstrFilter: ?[*:0]const u8,
lpstrCustomFilter: ?PSTR,
nMaxCustFilter: u32,
nFilterIndex: u32,
lpstrFile: ?PSTR,
nMaxFile: u32,
lpstrFileTitle: ?PSTR,
nMaxFileTitle: u32,
lpstrInitialDir: ?[*:0]const u8,
lpstrTitle: ?[*:0]const u8,
Flags: u32,
nFileOffset: u16,
nFileExtension: u16,
lpstrDefExt: ?[*:0]const u8,
lCustData: LPARAM,
lpfnHook: ?LPOFNHOOKPROC,
lpTemplateName: ?[*:0]const u8,
},
.X86 => packed struct {
lStructSize: u32,
hwndOwner: ?HWND,
hInstance: ?HINSTANCE,
lpstrFilter: ?[*:0]const u8,
lpstrCustomFilter: ?PSTR,
nMaxCustFilter: u32,
nFilterIndex: u32,
lpstrFile: ?PSTR,
nMaxFile: u32,
lpstrFileTitle: ?PSTR,
nMaxFileTitle: u32,
lpstrInitialDir: ?[*:0]const u8,
lpstrTitle: ?[*:0]const u8,
Flags: u32,
nFileOffset: u16,
nFileExtension: u16,
lpstrDefExt: ?[*:0]const u8,
lCustData: LPARAM,
lpfnHook: ?LPOFNHOOKPROC,
lpTemplateName: ?[*:0]const u8,
},
};
pub const OPENFILENAME_NT4W = switch(@import("../zig.zig").arch) {
.X64, .Arm64 => extern struct {
lStructSize: u32,
hwndOwner: ?HWND,
hInstance: ?HINSTANCE,
lpstrFilter: ?[*:0]const u16,
lpstrCustomFilter: ?PWSTR,
nMaxCustFilter: u32,
nFilterIndex: u32,
lpstrFile: ?PWSTR,
nMaxFile: u32,
lpstrFileTitle: ?PWSTR,
nMaxFileTitle: u32,
lpstrInitialDir: ?[*:0]const u16,
lpstrTitle: ?[*:0]const u16,
Flags: u32,
nFileOffset: u16,
nFileExtension: u16,
lpstrDefExt: ?[*:0]const u16,
lCustData: LPARAM,
lpfnHook: ?LPOFNHOOKPROC,
lpTemplateName: ?[*:0]const u16,
},
.X86 => packed struct {
lStructSize: u32,
hwndOwner: ?HWND,
hInstance: ?HINSTANCE,
lpstrFilter: ?[*:0]const u16,
lpstrCustomFilter: ?PWSTR,
nMaxCustFilter: u32,
nFilterIndex: u32,
lpstrFile: ?PWSTR,
nMaxFile: u32,
lpstrFileTitle: ?PWSTR,
nMaxFileTitle: u32,
lpstrInitialDir: ?[*:0]const u16,
lpstrTitle: ?[*:0]const u16,
Flags: u32,
nFileOffset: u16,
nFileExtension: u16,
lpstrDefExt: ?[*:0]const u16,
lCustData: LPARAM,
lpfnHook: ?LPOFNHOOKPROC,
lpTemplateName: ?[*:0]const u16,
},
};
pub const OPENFILENAMEA = switch(@import("../zig.zig").arch) {
.X64, .Arm64 => extern struct {
lStructSize: u32,
hwndOwner: ?HWND,
hInstance: ?HINSTANCE,
lpstrFilter: ?[*:0]const u8,
lpstrCustomFilter: ?PSTR,
nMaxCustFilter: u32,
nFilterIndex: u32,
lpstrFile: ?PSTR,
nMaxFile: u32,
lpstrFileTitle: ?PSTR,
nMaxFileTitle: u32,
lpstrInitialDir: ?[*:0]const u8,
lpstrTitle: ?[*:0]const u8,
Flags: OPEN_FILENAME_FLAGS,
nFileOffset: u16,
nFileExtension: u16,
lpstrDefExt: ?[*:0]const u8,
lCustData: LPARAM,
lpfnHook: ?LPOFNHOOKPROC,
lpTemplateName: ?[*:0]const u8,
pvReserved: ?*c_void,
dwReserved: u32,
FlagsEx: OPEN_FILENAME_FLAGS_EX,
},
.X86 => packed struct {
lStructSize: u32,
hwndOwner: ?HWND,
hInstance: ?HINSTANCE,
lpstrFilter: ?[*:0]const u8,
lpstrCustomFilter: ?PSTR,
nMaxCustFilter: u32,
nFilterIndex: u32,
lpstrFile: ?PSTR,
nMaxFile: u32,
lpstrFileTitle: ?PSTR,
nMaxFileTitle: u32,
lpstrInitialDir: ?[*:0]const u8,
lpstrTitle: ?[*:0]const u8,
Flags: OPEN_FILENAME_FLAGS,
nFileOffset: u16,
nFileExtension: u16,
lpstrDefExt: ?[*:0]const u8,
lCustData: LPARAM,
lpfnHook: ?LPOFNHOOKPROC,
lpTemplateName: ?[*:0]const u8,
pvReserved: ?*c_void,
dwReserved: u32,
FlagsEx: OPEN_FILENAME_FLAGS_EX,
},
};
pub const OPENFILENAMEW = switch(@import("../zig.zig").arch) {
.X64, .Arm64 => extern struct {
lStructSize: u32,
hwndOwner: ?HWND,
hInstance: ?HINSTANCE,
lpstrFilter: ?[*:0]const u16,
lpstrCustomFilter: ?PWSTR,
nMaxCustFilter: u32,
nFilterIndex: u32,
lpstrFile: ?PWSTR,
nMaxFile: u32,
lpstrFileTitle: ?PWSTR,
nMaxFileTitle: u32,
lpstrInitialDir: ?[*:0]const u16,
lpstrTitle: ?[*:0]const u16,
Flags: OPEN_FILENAME_FLAGS,
nFileOffset: u16,
nFileExtension: u16,
lpstrDefExt: ?[*:0]const u16,
lCustData: LPARAM,
lpfnHook: ?LPOFNHOOKPROC,
lpTemplateName: ?[*:0]const u16,
pvReserved: ?*c_void,
dwReserved: u32,
FlagsEx: OPEN_FILENAME_FLAGS_EX,
},
.X86 => packed struct {
lStructSize: u32,
hwndOwner: ?HWND,
hInstance: ?HINSTANCE,
lpstrFilter: ?[*:0]const u16,
lpstrCustomFilter: ?PWSTR,
nMaxCustFilter: u32,
nFilterIndex: u32,
lpstrFile: ?PWSTR,
nMaxFile: u32,
lpstrFileTitle: ?PWSTR,
nMaxFileTitle: u32,
lpstrInitialDir: ?[*:0]const u16,
lpstrTitle: ?[*:0]const u16,
Flags: OPEN_FILENAME_FLAGS,
nFileOffset: u16,
nFileExtension: u16,
lpstrDefExt: ?[*:0]const u16,
lCustData: LPARAM,
lpfnHook: ?LPOFNHOOKPROC,
lpTemplateName: ?[*:0]const u16,
pvReserved: ?*c_void,
dwReserved: u32,
FlagsEx: OPEN_FILENAME_FLAGS_EX,
},
};
pub const OFNOTIFYA = switch(@import("../zig.zig").arch) {
.X64, .Arm64 => extern struct {
hdr: NMHDR,
lpOFN: ?*OPENFILENAMEA,
pszFile: ?PSTR,
},
.X86 => packed struct {
hdr: NMHDR,
lpOFN: ?*OPENFILENAMEA,
pszFile: ?PSTR,
},
};
pub const OFNOTIFYW = switch(@import("../zig.zig").arch) {
.X64, .Arm64 => extern struct {
hdr: NMHDR,
lpOFN: ?*OPENFILENAMEW,
pszFile: ?PWSTR,
},
.X86 => packed struct {
hdr: NMHDR,
lpOFN: ?*OPENFILENAMEW,
pszFile: ?PWSTR,
},
};
pub const OFNOTIFYEXA = switch(@import("../zig.zig").arch) {
.X64, .Arm64 => extern struct {
hdr: NMHDR,
lpOFN: ?*OPENFILENAMEA,
psf: ?*c_void,
pidl: ?*c_void,
},
.X86 => packed struct {
hdr: NMHDR,
lpOFN: ?*OPENFILENAMEA,
psf: ?*c_void,
pidl: ?*c_void,
},
};
pub const OFNOTIFYEXW = switch(@import("../zig.zig").arch) {
.X64, .Arm64 => extern struct {
hdr: NMHDR,
lpOFN: ?*OPENFILENAMEW,
psf: ?*c_void,
pidl: ?*c_void,
},
.X86 => packed struct {
hdr: NMHDR,
lpOFN: ?*OPENFILENAMEW,
psf: ?*c_void,
pidl: ?*c_void,
},
};
pub const CHOOSECOLORA = switch(@import("../zig.zig").arch) {
.X64, .Arm64 => extern struct {
lStructSize: u32,
hwndOwner: ?HWND,
hInstance: ?HWND,
rgbResult: u32,
lpCustColors: ?*u32,
Flags: u32,
lCustData: LPARAM,
lpfnHook: ?LPCCHOOKPROC,
lpTemplateName: ?[*:0]const u8,
},
.X86 => packed struct {
lStructSize: u32,
hwndOwner: ?HWND,
hInstance: ?HWND,
rgbResult: u32,
lpCustColors: ?*u32,
Flags: u32,
lCustData: LPARAM,
lpfnHook: ?LPCCHOOKPROC,
lpTemplateName: ?[*:0]const u8,
},
};
pub const CHOOSECOLORW = switch(@import("../zig.zig").arch) {
.X64, .Arm64 => extern struct {
lStructSize: u32,
hwndOwner: ?HWND,
hInstance: ?HWND,
rgbResult: u32,
lpCustColors: ?*u32,
Flags: u32,
lCustData: LPARAM,
lpfnHook: ?LPCCHOOKPROC,
lpTemplateName: ?[*:0]const u16,
},
.X86 => packed struct {
lStructSize: u32,
hwndOwner: ?HWND,
hInstance: ?HWND,
rgbResult: u32,
lpCustColors: ?*u32,
Flags: u32,
lCustData: LPARAM,
lpfnHook: ?LPCCHOOKPROC,
lpTemplateName: ?[*:0]const u16,
},
};
pub const FINDREPLACEA = switch(@import("../zig.zig").arch) {
.X64, .Arm64 => extern struct {
lStructSize: u32,
hwndOwner: ?HWND,
hInstance: ?HINSTANCE,
Flags: FINDREPLACE_FLAGS,
lpstrFindWhat: ?PSTR,
lpstrReplaceWith: ?PSTR,
wFindWhatLen: u16,
wReplaceWithLen: u16,
lCustData: LPARAM,
lpfnHook: ?LPFRHOOKPROC,
lpTemplateName: ?[*:0]const u8,
},
.X86 => packed struct {
lStructSize: u32,
hwndOwner: ?HWND,
hInstance: ?HINSTANCE,
Flags: FINDREPLACE_FLAGS,
lpstrFindWhat: ?PSTR,
lpstrReplaceWith: ?PSTR,
wFindWhatLen: u16,
wReplaceWithLen: u16,
lCustData: LPARAM,
lpfnHook: ?LPFRHOOKPROC,
lpTemplateName: ?[*:0]const u8,
},
};
pub const FINDREPLACEW = switch(@import("../zig.zig").arch) {
.X64, .Arm64 => extern struct {
lStructSize: u32,
hwndOwner: ?HWND,
hInstance: ?HINSTANCE,
Flags: FINDREPLACE_FLAGS,
lpstrFindWhat: ?PWSTR,
lpstrReplaceWith: ?PWSTR,
wFindWhatLen: u16,
wReplaceWithLen: u16,
lCustData: LPARAM,
lpfnHook: ?LPFRHOOKPROC,
lpTemplateName: ?[*:0]const u16,
},
.X86 => packed struct {
lStructSize: u32,
hwndOwner: ?HWND,
hInstance: ?HINSTANCE,
Flags: FINDREPLACE_FLAGS,
lpstrFindWhat: ?PWSTR,
lpstrReplaceWith: ?PWSTR,
wFindWhatLen: u16,
wReplaceWithLen: u16,
lCustData: LPARAM,
lpfnHook: ?LPFRHOOKPROC,
lpTemplateName: ?[*:0]const u16,
},
};
pub const CHOOSEFONTA = switch(@import("../zig.zig").arch) {
.X64, .Arm64 => extern struct {
lStructSize: u32,
hwndOwner: ?HWND,
hDC: ?HDC,
lpLogFont: ?*LOGFONTA,
iPointSize: i32,
Flags: CHOOSEFONT_FLAGS,
rgbColors: u32,
lCustData: LPARAM,
lpfnHook: ?LPCFHOOKPROC,
lpTemplateName: ?[*:0]const u8,
hInstance: ?HINSTANCE,
lpszStyle: ?PSTR,
nFontType: CHOOSEFONT_FONT_TYPE,
___MISSING_ALIGNMENT__: u16,
nSizeMin: i32,
nSizeMax: i32,
},
.X86 => packed struct {
lStructSize: u32,
hwndOwner: ?HWND,
hDC: ?HDC,
lpLogFont: ?*LOGFONTA,
iPointSize: i32,
Flags: CHOOSEFONT_FLAGS,
rgbColors: u32,
lCustData: LPARAM,
lpfnHook: ?LPCFHOOKPROC,
lpTemplateName: ?[*:0]const u8,
hInstance: ?HINSTANCE,
lpszStyle: ?PSTR,
nFontType: CHOOSEFONT_FONT_TYPE,
___MISSING_ALIGNMENT__: u16,
nSizeMin: i32,
nSizeMax: i32,
},
};
pub const CHOOSEFONTW = switch(@import("../zig.zig").arch) {
.X64, .Arm64 => extern struct {
lStructSize: u32,
hwndOwner: ?HWND,
hDC: ?HDC,
lpLogFont: ?*LOGFONTW,
iPointSize: i32,
Flags: CHOOSEFONT_FLAGS,
rgbColors: u32,
lCustData: LPARAM,
lpfnHook: ?LPCFHOOKPROC,
lpTemplateName: ?[*:0]const u16,
hInstance: ?HINSTANCE,
lpszStyle: ?PWSTR,
nFontType: CHOOSEFONT_FONT_TYPE,
___MISSING_ALIGNMENT__: u16,
nSizeMin: i32,
nSizeMax: i32,
},
.X86 => packed struct {
lStructSize: u32,
hwndOwner: ?HWND,
hDC: ?HDC,
lpLogFont: ?*LOGFONTW,
iPointSize: i32,
Flags: CHOOSEFONT_FLAGS,
rgbColors: u32,
lCustData: LPARAM,
lpfnHook: ?LPCFHOOKPROC,
lpTemplateName: ?[*:0]const u16,
hInstance: ?HINSTANCE,
lpszStyle: ?PWSTR,
nFontType: CHOOSEFONT_FONT_TYPE,
___MISSING_ALIGNMENT__: u16,
nSizeMin: i32,
nSizeMax: i32,
},
};
pub const PRINTDLGA = switch(@import("../zig.zig").arch) {
.X64, .Arm64 => extern struct {
lStructSize: u32,
hwndOwner: ?HWND,
hDevMode: isize,
hDevNames: isize,
hDC: ?HDC,
Flags: PRINTDLGEX_FLAGS,
nFromPage: u16,
nToPage: u16,
nMinPage: u16,
nMaxPage: u16,
nCopies: u16,
hInstance: ?HINSTANCE,
lCustData: LPARAM,
lpfnPrintHook: ?LPPRINTHOOKPROC,
lpfnSetupHook: ?LPSETUPHOOKPROC,
lpPrintTemplateName: ?[*:0]const u8,
lpSetupTemplateName: ?[*:0]const u8,
hPrintTemplate: isize,
hSetupTemplate: isize,
},
.X86 => packed struct {
lStructSize: u32,
hwndOwner: ?HWND,
hDevMode: isize,
hDevNames: isize,
hDC: ?HDC,
Flags: PRINTDLGEX_FLAGS,
nFromPage: u16,
nToPage: u16,
nMinPage: u16,
nMaxPage: u16,
nCopies: u16,
hInstance: ?HINSTANCE,
lCustData: LPARAM,
lpfnPrintHook: ?LPPRINTHOOKPROC,
lpfnSetupHook: ?LPSETUPHOOKPROC,
lpPrintTemplateName: ?[*:0]const u8,
lpSetupTemplateName: ?[*:0]const u8,
hPrintTemplate: isize,
hSetupTemplate: isize,
},
};
pub const PRINTDLGW = switch(@import("../zig.zig").arch) {
.X64, .Arm64 => extern struct {
lStructSize: u32,
hwndOwner: ?HWND,
hDevMode: isize,
hDevNames: isize,
hDC: ?HDC,
Flags: PRINTDLGEX_FLAGS,
nFromPage: u16,
nToPage: u16,
nMinPage: u16,
nMaxPage: u16,
nCopies: u16,
hInstance: ?HINSTANCE,
lCustData: LPARAM,
lpfnPrintHook: ?LPPRINTHOOKPROC,
lpfnSetupHook: ?LPSETUPHOOKPROC,
lpPrintTemplateName: ?[*:0]const u16,
lpSetupTemplateName: ?[*:0]const u16,
hPrintTemplate: isize,
hSetupTemplate: isize,
},
.X86 => packed struct {
lStructSize: u32,
hwndOwner: ?HWND,
hDevMode: isize,
hDevNames: isize,
hDC: ?HDC,
Flags: PRINTDLGEX_FLAGS,
nFromPage: u16,
nToPage: u16,
nMinPage: u16,
nMaxPage: u16,
nCopies: u16,
hInstance: ?HINSTANCE,
lCustData: LPARAM,
lpfnPrintHook: ?LPPRINTHOOKPROC,
lpfnSetupHook: ?LPSETUPHOOKPROC,
lpPrintTemplateName: ?[*:0]const u16,
lpSetupTemplateName: ?[*:0]const u16,
hPrintTemplate: isize,
hSetupTemplate: isize,
},
};
pub const PRINTPAGERANGE = switch(@import("../zig.zig").arch) {
.X64, .Arm64 => extern struct {
nFromPage: u32,
nToPage: u32,
},
.X86 => packed struct {
nFromPage: u32,
nToPage: u32,
},
};
pub const PRINTDLGEXA = switch(@import("../zig.zig").arch) {
.X64, .Arm64 => extern struct {
lStructSize: u32,
hwndOwner: ?HWND,
hDevMode: isize,
hDevNames: isize,
hDC: ?HDC,
Flags: PRINTDLGEX_FLAGS,
Flags2: u32,
ExclusionFlags: u32,
nPageRanges: u32,
nMaxPageRanges: u32,
lpPageRanges: ?*PRINTPAGERANGE,
nMinPage: u32,
nMaxPage: u32,
nCopies: u32,
hInstance: ?HINSTANCE,
lpPrintTemplateName: ?[*:0]const u8,
lpCallback: ?*IUnknown,
nPropertyPages: u32,
lphPropertyPages: ?*?HPROPSHEETPAGE,
nStartPage: u32,
dwResultAction: u32,
},
.X86 => packed struct {
lStructSize: u32,
hwndOwner: ?HWND,
hDevMode: isize,
hDevNames: isize,
hDC: ?HDC,
Flags: PRINTDLGEX_FLAGS,
Flags2: u32,
ExclusionFlags: u32,
nPageRanges: u32,
nMaxPageRanges: u32,
lpPageRanges: ?*PRINTPAGERANGE,
nMinPage: u32,
nMaxPage: u32,
nCopies: u32,
hInstance: ?HINSTANCE,
lpPrintTemplateName: ?[*:0]const u8,
lpCallback: ?*IUnknown,
nPropertyPages: u32,
lphPropertyPages: ?*?HPROPSHEETPAGE,
nStartPage: u32,
dwResultAction: u32,
},
};
pub const PRINTDLGEXW = switch(@import("../zig.zig").arch) {
.X64, .Arm64 => extern struct {
lStructSize: u32,
hwndOwner: ?HWND,
hDevMode: isize,
hDevNames: isize,
hDC: ?HDC,
Flags: PRINTDLGEX_FLAGS,
Flags2: u32,
ExclusionFlags: u32,
nPageRanges: u32,
nMaxPageRanges: u32,
lpPageRanges: ?*PRINTPAGERANGE,
nMinPage: u32,
nMaxPage: u32,
nCopies: u32,
hInstance: ?HINSTANCE,
lpPrintTemplateName: ?[*:0]const u16,
lpCallback: ?*IUnknown,
nPropertyPages: u32,
lphPropertyPages: ?*?HPROPSHEETPAGE,
nStartPage: u32,
dwResultAction: u32,
},
.X86 => packed struct {
lStructSize: u32,
hwndOwner: ?HWND,
hDevMode: isize,
hDevNames: isize,
hDC: ?HDC,
Flags: PRINTDLGEX_FLAGS,
Flags2: u32,
ExclusionFlags: u32,
nPageRanges: u32,
nMaxPageRanges: u32,
lpPageRanges: ?*PRINTPAGERANGE,
nMinPage: u32,
nMaxPage: u32,
nCopies: u32,
hInstance: ?HINSTANCE,
lpPrintTemplateName: ?[*:0]const u16,
lpCallback: ?*IUnknown,
nPropertyPages: u32,
lphPropertyPages: ?*?HPROPSHEETPAGE,
nStartPage: u32,
dwResultAction: u32,
},
};
pub const DEVNAMES = switch(@import("../zig.zig").arch) {
.X64, .Arm64 => extern struct {
wDriverOffset: u16,
wDeviceOffset: u16,
wOutputOffset: u16,
wDefault: u16,
},
.X86 => packed struct {
wDriverOffset: u16,
wDeviceOffset: u16,
wOutputOffset: u16,
wDefault: u16,
},
};
pub const PAGESETUPDLGA = switch(@import("../zig.zig").arch) {
.X64, .Arm64 => extern struct {
lStructSize: u32,
hwndOwner: ?HWND,
hDevMode: isize,
hDevNames: isize,
Flags: PAGESETUPDLG_FLAGS,
ptPaperSize: POINT,
rtMinMargin: RECT,
rtMargin: RECT,
hInstance: ?HINSTANCE,
lCustData: LPARAM,
lpfnPageSetupHook: ?LPPAGESETUPHOOK,
lpfnPagePaintHook: ?LPPAGEPAINTHOOK,
lpPageSetupTemplateName: ?[*:0]const u8,
hPageSetupTemplate: isize,
},
.X86 => packed struct {
lStructSize: u32,
hwndOwner: ?HWND,
hDevMode: isize,
hDevNames: isize,
Flags: PAGESETUPDLG_FLAGS,
ptPaperSize: POINT,
rtMinMargin: RECT,
rtMargin: RECT,
hInstance: ?HINSTANCE,
lCustData: LPARAM,
lpfnPageSetupHook: ?LPPAGESETUPHOOK,
lpfnPagePaintHook: ?LPPAGEPAINTHOOK,
lpPageSetupTemplateName: ?[*:0]const u8,
hPageSetupTemplate: isize,
},
};
pub const PAGESETUPDLGW = switch(@import("../zig.zig").arch) {
.X64, .Arm64 => extern struct {
lStructSize: u32,
hwndOwner: ?HWND,
hDevMode: isize,
hDevNames: isize,
Flags: PAGESETUPDLG_FLAGS,
ptPaperSize: POINT,
rtMinMargin: RECT,
rtMargin: RECT,
hInstance: ?HINSTANCE,
lCustData: LPARAM,
lpfnPageSetupHook: ?LPPAGESETUPHOOK,
lpfnPagePaintHook: ?LPPAGEPAINTHOOK,
lpPageSetupTemplateName: ?[*:0]const u16,
hPageSetupTemplate: isize,
},
.X86 => packed struct {
lStructSize: u32,
hwndOwner: ?HWND,
hDevMode: isize,
hDevNames: isize,
Flags: PAGESETUPDLG_FLAGS,
ptPaperSize: POINT,
rtMinMargin: RECT,
rtMargin: RECT,
hInstance: ?HINSTANCE,
lCustData: LPARAM,
lpfnPageSetupHook: ?LPPAGESETUPHOOK,
lpfnPagePaintHook: ?LPPAGEPAINTHOOK,
lpPageSetupTemplateName: ?[*:0]const u16,
hPageSetupTemplate: isize,
},
};
//--------------------------------------------------------------------------------
// Section: Functions (426)
//--------------------------------------------------------------------------------
pub usingnamespace switch (@import("../zig.zig").arch) {
.X64, .Arm64 => struct {
// TODO: this type is limited to platform 'windows5.0'
pub extern "USER32" fn GetWindowLongPtrA(
hWnd: ?HWND,
nIndex: WINDOW_LONG_PTR_INDEX,
) callconv(@import("std").os.windows.WINAPI) isize;
}, else => struct { } };
pub usingnamespace switch (@import("../zig.zig").arch) {
.X64, .Arm64 => struct {
// TODO: this type is limited to platform 'windows5.0'
pub extern "USER32" fn GetWindowLongPtrW(
hWnd: ?HWND,
nIndex: WINDOW_LONG_PTR_INDEX,
) callconv(@import("std").os.windows.WINAPI) isize;
}, else => struct { } };
pub usingnamespace switch (@import("../zig.zig").arch) {
.X64, .Arm64 => struct {
// TODO: this type is limited to platform 'windows5.0'
pub extern "USER32" fn SetWindowLongPtrA(
hWnd: ?HWND,
nIndex: WINDOW_LONG_PTR_INDEX,
dwNewLong: isize,
) callconv(@import("std").os.windows.WINAPI) isize;
}, else => struct { } };
pub usingnamespace switch (@import("../zig.zig").arch) {
.X64, .Arm64 => struct {
// TODO: this type is limited to platform 'windows5.0'
pub extern "USER32" fn SetWindowLongPtrW(
hWnd: ?HWND,
nIndex: WINDOW_LONG_PTR_INDEX,
dwNewLong: isize,
) callconv(@import("std").os.windows.WINAPI) isize;
}, else => struct { } };
pub usingnamespace switch (@import("../zig.zig").arch) {
.X64, .Arm64 => struct {
// TODO: this type is limited to platform 'windows5.0'
pub extern "USER32" fn GetClassLongPtrA(
hWnd: ?HWND,
nIndex: GET_CLASS_LONG_INDEX,
) callconv(@import("std").os.windows.WINAPI) usize;
}, else => struct { } };
pub usingnamespace switch (@import("../zig.zig").arch) {
.X64, .Arm64 => struct {
// TODO: this type is limited to platform 'windows5.0'
pub extern "USER32" fn GetClassLongPtrW(
hWnd: ?HWND,
nIndex: GET_CLASS_LONG_INDEX,
) callconv(@import("std").os.windows.WINAPI) usize;
}, else => struct { } };
pub usingnamespace switch (@import("../zig.zig").arch) {
.X64, .Arm64 => struct {
// TODO: this type is limited to platform 'windows5.0'
pub extern "USER32" fn SetClassLongPtrA(
hWnd: ?HWND,
nIndex: GET_CLASS_LONG_INDEX,
dwNewLong: isize,
) callconv(@import("std").os.windows.WINAPI) usize;
}, else => struct { } };
pub usingnamespace switch (@import("../zig.zig").arch) {
.X64, .Arm64 => struct {
// TODO: this type is limited to platform 'windows5.0'
pub extern "USER32" fn SetClassLongPtrW(
hWnd: ?HWND,
nIndex: GET_CLASS_LONG_INDEX,
dwNewLong: isize,
) callconv(@import("std").os.windows.WINAPI) usize;
}, else => struct { } };
// TODO: this type is limited to platform 'windows5.0'
pub extern "COMDLG32" fn GetOpenFileNameA(
param0: ?*OPENFILENAMEA,
) callconv(@import("std").os.windows.WINAPI) BOOL;
// TODO: this type is limited to platform 'windows5.0'
pub extern "COMDLG32" fn GetOpenFileNameW(
param0: ?*OPENFILENAMEW,
) callconv(@import("std").os.windows.WINAPI) BOOL;
// TODO: this type is limited to platform 'windows5.0'
pub extern "COMDLG32" fn GetSaveFileNameA(
param0: ?*OPENFILENAMEA,
) callconv(@import("std").os.windows.WINAPI) BOOL;
// TODO: this type is limited to platform 'windows5.0'
pub extern "COMDLG32" fn GetSaveFileNameW(
param0: ?*OPENFILENAMEW,
) callconv(@import("std").os.windows.WINAPI) BOOL;
// TODO: this type is limited to platform 'windows5.0'
pub extern "COMDLG32" fn GetFileTitleA(
param0: ?[*:0]const u8,
Buf: [*:0]u8,
cchSize: u16,
) callconv(@import("std").os.windows.WINAPI) i16;
// TODO: this type is limited to platform 'windows5.0'
pub extern "COMDLG32" fn GetFileTitleW(
param0: ?[*:0]const u16,
Buf: [*:0]u16,
cchSize: u16,
) callconv(@import("std").os.windows.WINAPI) i16;
pub extern "COMDLG32" fn ChooseColorA(
param0: ?*CHOOSECOLORA,
) callconv(@import("std").os.windows.WINAPI) BOOL;
pub extern "COMDLG32" fn ChooseColorW(
param0: ?*CHOOSECOLORW,
) callconv(@import("std").os.windows.WINAPI) BOOL;
// TODO: this type is limited to platform 'windows5.0'
pub extern "COMDLG32" fn FindTextA(
param0: ?*FINDREPLACEA,
) callconv(@import("std").os.windows.WINAPI) ?HWND;
// TODO: this type is limited to platform 'windows5.0'
pub extern "COMDLG32" fn FindTextW(
param0: ?*FINDREPLACEW,
) callconv(@import("std").os.windows.WINAPI) ?HWND;
// TODO: this type is limited to platform 'windows5.0'
pub extern "COMDLG32" fn ReplaceTextA(
param0: ?*FINDREPLACEA,
) callconv(@import("std").os.windows.WINAPI) ?HWND;
// TODO: this type is limited to platform 'windows5.0'
pub extern "COMDLG32" fn ReplaceTextW(
param0: ?*FINDREPLACEW,
) callconv(@import("std").os.windows.WINAPI) ?HWND;
pub extern "COMDLG32" fn ChooseFontA(
param0: ?*CHOOSEFONTA,
) callconv(@import("std").os.windows.WINAPI) BOOL;
pub extern "COMDLG32" fn ChooseFontW(
param0: ?*CHOOSEFONTW,
) callconv(@import("std").os.windows.WINAPI) BOOL;
pub extern "COMDLG32" fn PrintDlgA(
pPD: ?*PRINTDLGA,
) callconv(@import("std").os.windows.WINAPI) BOOL;
pub extern "COMDLG32" fn PrintDlgW(
pPD: ?*PRINTDLGW,
) callconv(@import("std").os.windows.WINAPI) BOOL;
pub extern "COMDLG32" fn PrintDlgExA(
pPD: ?*PRINTDLGEXA,
) callconv(@import("std").os.windows.WINAPI) HRESULT;
pub extern "COMDLG32" fn PrintDlgExW(
pPD: ?*PRINTDLGEXW,
) callconv(@import("std").os.windows.WINAPI) HRESULT;
// TODO: this type is limited to platform 'windows5.0'
pub extern "COMDLG32" fn CommDlgExtendedError(
) callconv(@import("std").os.windows.WINAPI) u32;
pub extern "COMDLG32" fn PageSetupDlgA(
param0: ?*PAGESETUPDLGA,
) callconv(@import("std").os.windows.WINAPI) BOOL;
pub extern "COMDLG32" fn PageSetupDlgW(
param0: ?*PAGESETUPDLGW,
) callconv(@import("std").os.windows.WINAPI) BOOL;
// TODO: this type is limited to platform 'windows5.0'
pub extern "USER32" fn LoadStringA(
hInstance: ?HINSTANCE,
uID: u32,
lpBuffer: [*:0]u8,
cchBufferMax: i32,
) callconv(@import("std").os.windows.WINAPI) i32;
// TODO: this type is limited to platform 'windows5.0'
pub extern "USER32" fn LoadStringW(
hInstance: ?HINSTANCE,
uID: u32,
lpBuffer: [*:0]u16,
cchBufferMax: i32,
) callconv(@import("std").os.windows.WINAPI) i32;
// TODO: this type is limited to platform 'windows5.0'
pub extern "USER32" fn wvsprintfA(
param0: ?PSTR,
param1: ?[*:0]const u8,
arglist: ?*i8,
) callconv(@import("std").os.windows.WINAPI) i32;
// TODO: this type is limited to platform 'windows5.0'
pub extern "USER32" fn wvsprintfW(
param0: ?PWSTR,
param1: ?[*:0]const u16,
arglist: ?*i8,
) callconv(@import("std").os.windows.WINAPI) i32;
// TODO: this type is limited to platform 'windows5.0'
pub extern "USER32" fn wsprintfA(
param0: ?PSTR,
param1: ?[*:0]const u8,
) callconv(@import("std").os.windows.WINAPI) i32;
// TODO: this type is limited to platform 'windows5.0'
pub extern "USER32" fn wsprintfW(
param0: ?PWSTR,
param1: ?[*:0]const u16,
) callconv(@import("std").os.windows.WINAPI) i32;
// TODO: this type is limited to platform 'windows5.0'
pub extern "USER32" fn IsHungAppWindow(
hwnd: ?HWND,
) callconv(@import("std").os.windows.WINAPI) BOOL;
// TODO: this type is limited to platform 'windows5.1.2600'
pub extern "USER32" fn DisableProcessWindowsGhosting(
) callconv(@import("std").os.windows.WINAPI) void;
// TODO: this type is limited to platform 'windows5.0'
pub extern "USER32" fn RegisterWindowMessageA(
lpString: ?[*:0]const u8,
) callconv(@import("std").os.windows.WINAPI) u32;
// TODO: this type is limited to platform 'windows5.0'
pub extern "USER32" fn RegisterWindowMessageW(
lpString: ?[*:0]const u16,
) callconv(@import("std").os.windows.WINAPI) u32;
// TODO: this type is limited to platform 'windows5.0'
pub extern "USER32" fn GetMessageA(
lpMsg: ?*MSG,
hWnd: ?HWND,
wMsgFilterMin: u32,
wMsgFilterMax: u32,
) callconv(@import("std").os.windows.WINAPI) BOOL;
// TODO: this type is limited to platform 'windows5.0'
pub extern "USER32" fn GetMessageW(
lpMsg: ?*MSG,
hWnd: ?HWND,
wMsgFilterMin: u32,
wMsgFilterMax: u32,
) callconv(@import("std").os.windows.WINAPI) BOOL;
// TODO: this type is limited to platform 'windows5.0'
pub extern "USER32" fn TranslateMessage(
lpMsg: ?*const MSG,
) callconv(@import("std").os.windows.WINAPI) BOOL;
// TODO: this type is limited to platform 'windows5.0'
pub extern "USER32" fn DispatchMessageA(
lpMsg: ?*const MSG,
) callconv(@import("std").os.windows.WINAPI) LRESULT;
// TODO: this type is limited to platform 'windows5.0'
pub extern "USER32" fn DispatchMessageW(
lpMsg: ?*const MSG,
) callconv(@import("std").os.windows.WINAPI) LRESULT;
pub extern "USER32" fn SetMessageQueue(
cMessagesMax: i32,
) callconv(@import("std").os.windows.WINAPI) BOOL;
// TODO: this type is limited to platform 'windows5.0'
pub extern "USER32" fn PeekMessageA(
lpMsg: ?*MSG,
hWnd: ?HWND,
wMsgFilterMin: u32,
wMsgFilterMax: u32,
wRemoveMsg: PEEK_MESSAGE_REMOVE_TYPE,
) callconv(@import("std").os.windows.WINAPI) BOOL;
// TODO: this type is limited to platform 'windows5.0'
pub extern "USER32" fn PeekMessageW(
lpMsg: ?*MSG,
hWnd: ?HWND,
wMsgFilterMin: u32,
wMsgFilterMax: u32,
wRemoveMsg: PEEK_MESSAGE_REMOVE_TYPE,
) callconv(@import("std").os.windows.WINAPI) BOOL;
// TODO: this type is limited to platform 'windows5.0'
pub extern "USER32" fn GetMessagePos(
) callconv(@import("std").os.windows.WINAPI) u32;
// TODO: this type is limited to platform 'windows5.0'
pub extern "USER32" fn GetMessageTime(
) callconv(@import("std").os.windows.WINAPI) i32;
// TODO: this type is limited to platform 'windows5.0'
pub extern "USER32" fn GetMessageExtraInfo(
) callconv(@import("std").os.windows.WINAPI) LPARAM;
// TODO: this type is limited to platform 'windows6.0.6000'
pub extern "USER32" fn IsWow64Message(
) callconv(@import("std").os.windows.WINAPI) BOOL;
// TODO: this type is limited to platform 'windows5.0'
pub extern "USER32" fn SetMessageExtraInfo(
lParam: LPARAM,
) callconv(@import("std").os.windows.WINAPI) LPARAM;
// TODO: this type is limited to platform 'windows5.0'
pub extern "USER32" fn SendMessageA(
hWnd: ?HWND,
Msg: u32,
wParam: WPARAM,
lParam: LPARAM,
) callconv(@import("std").os.windows.WINAPI) LRESULT;
// TODO: this type is limited to platform 'windows5.0'
pub extern "USER32" fn SendMessageW(
hWnd: ?HWND,
Msg: u32,
wParam: WPARAM,
lParam: LPARAM,
) callconv(@import("std").os.windows.WINAPI) LRESULT;
// TODO: this type is limited to platform 'windows5.0'
pub extern "USER32" fn SendMessageTimeoutA(
hWnd: ?HWND,
Msg: u32,
wParam: WPARAM,
lParam: LPARAM,
fuFlags: SEND_MESSAGE_TIMEOUT_FLAGS,
uTimeout: u32,
lpdwResult: ?*usize,
) callconv(@import("std").os.windows.WINAPI) LRESULT;
// TODO: this type is limited to platform 'windows5.0'
pub extern "USER32" fn SendMessageTimeoutW(
hWnd: ?HWND,
Msg: u32,
wParam: WPARAM,
lParam: LPARAM,
fuFlags: SEND_MESSAGE_TIMEOUT_FLAGS,
uTimeout: u32,
lpdwResult: ?*usize,
) callconv(@import("std").os.windows.WINAPI) LRESULT;
// TODO: this type is limited to platform 'windows5.0'
pub extern "USER32" fn SendNotifyMessageA(
hWnd: ?HWND,
Msg: u32,
wParam: WPARAM,
lParam: LPARAM,
) callconv(@import("std").os.windows.WINAPI) BOOL;
// TODO: this type is limited to platform 'windows5.0'
pub extern "USER32" fn SendNotifyMessageW(
hWnd: ?HWND,
Msg: u32,
wParam: WPARAM,
lParam: LPARAM,
) callconv(@import("std").os.windows.WINAPI) BOOL;
// TODO: this type is limited to platform 'windows5.0'
pub extern "USER32" fn SendMessageCallbackA(
hWnd: ?HWND,
Msg: u32,
wParam: WPARAM,
lParam: LPARAM,
lpResultCallBack: ?SENDASYNCPROC,
dwData: usize,
) callconv(@import("std").os.windows.WINAPI) BOOL;
// TODO: this type is limited to platform 'windows5.0'
pub extern "USER32" fn SendMessageCallbackW(
hWnd: ?HWND,
Msg: u32,
wParam: WPARAM,
lParam: LPARAM,
lpResultCallBack: ?SENDASYNCPROC,
dwData: usize,
) callconv(@import("std").os.windows.WINAPI) BOOL;
// TODO: this type is limited to platform 'windows5.1.2600'
pub extern "USER32" fn BroadcastSystemMessageExA(
flags: BROADCAST_SYSTEM_MESSAGE_FLAGS,
lpInfo: ?*BROADCAST_SYSTEM_MESSAGE_INFO,
Msg: u32,
wParam: WPARAM,
lParam: LPARAM,
pbsmInfo: ?*BSMINFO,
) callconv(@import("std").os.windows.WINAPI) i32;
// TODO: this type is limited to platform 'windows5.1.2600'
pub extern "USER32" fn BroadcastSystemMessageExW(
flags: BROADCAST_SYSTEM_MESSAGE_FLAGS,
lpInfo: ?*BROADCAST_SYSTEM_MESSAGE_INFO,
Msg: u32,
wParam: WPARAM,
lParam: LPARAM,
pbsmInfo: ?*BSMINFO,
) callconv(@import("std").os.windows.WINAPI) i32;
pub extern "USER32" fn BroadcastSystemMessageA(
flags: u32,
lpInfo: ?*u32,
Msg: u32,
wParam: WPARAM,
lParam: LPARAM,
) callconv(@import("std").os.windows.WINAPI) i32;
// TODO: this type is limited to platform 'windows5.0'
pub extern "USER32" fn BroadcastSystemMessageW(
flags: BROADCAST_SYSTEM_MESSAGE_FLAGS,
lpInfo: ?*BROADCAST_SYSTEM_MESSAGE_INFO,
Msg: u32,
wParam: WPARAM,
lParam: LPARAM,
) callconv(@import("std").os.windows.WINAPI) i32;
// TODO: this type is limited to platform 'windows5.0'
pub extern "USER32" fn PostMessageA(
hWnd: ?HWND,
Msg: u32,
wParam: WPARAM,
lParam: LPARAM,
) callconv(@import("std").os.windows.WINAPI) BOOL;
// TODO: this type is limited to platform 'windows5.0'
pub extern "USER32" fn PostMessageW(
hWnd: ?HWND,
Msg: u32,
wParam: WPARAM,
lParam: LPARAM,
) callconv(@import("std").os.windows.WINAPI) BOOL;
// TODO: this type is limited to platform 'windows5.0'
pub extern "USER32" fn PostThreadMessageA(
idThread: u32,
Msg: u32,
wParam: WPARAM,
lParam: LPARAM,
) callconv(@import("std").os.windows.WINAPI) BOOL;
// TODO: this type is limited to platform 'windows5.0'
pub extern "USER32" fn PostThreadMessageW(
idThread: u32,
Msg: u32,
wParam: WPARAM,
lParam: LPARAM,
) callconv(@import("std").os.windows.WINAPI) BOOL;
// TODO: this type is limited to platform 'windows5.0'
pub extern "USER32" fn ReplyMessage(
lResult: LRESULT,
) callconv(@import("std").os.windows.WINAPI) BOOL;
// TODO: this type is limited to platform 'windows5.0'
pub extern "USER32" fn WaitMessage(
) callconv(@import("std").os.windows.WINAPI) BOOL;
// TODO: this type is limited to platform 'windows5.0'
pub extern "USER32" fn DefWindowProcA(
hWnd: ?HWND,
Msg: u32,
wParam: WPARAM,
lParam: LPARAM,
) callconv(@import("std").os.windows.WINAPI) LRESULT;
// TODO: this type is limited to platform 'windows5.0'
pub extern "USER32" fn DefWindowProcW(
hWnd: ?HWND,
Msg: u32,
wParam: WPARAM,
lParam: LPARAM,
) callconv(@import("std").os.windows.WINAPI) LRESULT;
// TODO: this type is limited to platform 'windows5.0'
pub extern "USER32" fn PostQuitMessage(
nExitCode: i32,
) callconv(@import("std").os.windows.WINAPI) void;
// TODO: this type is limited to platform 'windows5.0'
pub extern "USER32" fn CallWindowProcA(
lpPrevWndFunc: ?WNDPROC,
hWnd: ?HWND,
Msg: u32,
wParam: WPARAM,
lParam: LPARAM,
) callconv(@import("std").os.windows.WINAPI) LRESULT;
// TODO: this type is limited to platform 'windows5.0'
pub extern "USER32" fn CallWindowProcW(
lpPrevWndFunc: ?WNDPROC,
hWnd: ?HWND,
Msg: u32,
wParam: WPARAM,
lParam: LPARAM,
) callconv(@import("std").os.windows.WINAPI) LRESULT;
// TODO: this type is limited to platform 'windows5.0'
pub extern "USER32" fn InSendMessage(
) callconv(@import("std").os.windows.WINAPI) BOOL;
// TODO: this type is limited to platform 'windows5.0'
pub extern "USER32" fn InSendMessageEx(
lpReserved: ?*c_void,
) callconv(@import("std").os.windows.WINAPI) u32;
// TODO: this type is limited to platform 'windows5.0'
pub extern "USER32" fn RegisterClassA(
lpWndClass: ?*const WNDCLASSA,
) callconv(@import("std").os.windows.WINAPI) u16;
// TODO: this type is limited to platform 'windows5.0'
pub extern "USER32" fn RegisterClassW(
lpWndClass: ?*const WNDCLASSW,
) callconv(@import("std").os.windows.WINAPI) u16;
// TODO: this type is limited to platform 'windows5.0'
pub extern "USER32" fn UnregisterClassA(
lpClassName: ?[*:0]const u8,
hInstance: ?HINSTANCE,
) callconv(@import("std").os.windows.WINAPI) BOOL;
// TODO: this type is limited to platform 'windows5.0'
pub extern "USER32" fn UnregisterClassW(
lpClassName: ?[*:0]const u16,
hInstance: ?HINSTANCE,
) callconv(@import("std").os.windows.WINAPI) BOOL;
// TODO: this type is limited to platform 'windows5.0'
pub extern "USER32" fn GetClassInfoA(
hInstance: ?HINSTANCE,
lpClassName: ?[*:0]const u8,
lpWndClass: ?*WNDCLASSA,
) callconv(@import("std").os.windows.WINAPI) BOOL;
// TODO: this type is limited to platform 'windows5.0'
pub extern "USER32" fn GetClassInfoW(
hInstance: ?HINSTANCE,
lpClassName: ?[*:0]const u16,
lpWndClass: ?*WNDCLASSW,
) callconv(@import("std").os.windows.WINAPI) BOOL;
// TODO: this type is limited to platform 'windows5.0'
pub extern "USER32" fn RegisterClassExA(
param0: ?*const WNDCLASSEXA,
) callconv(@import("std").os.windows.WINAPI) u16;
// TODO: this type is limited to platform 'windows5.0'
pub extern "USER32" fn RegisterClassExW(
param0: ?*const WNDCLASSEXW,
) callconv(@import("std").os.windows.WINAPI) u16;
// TODO: this type is limited to platform 'windows5.0'
pub extern "USER32" fn GetClassInfoExA(
hInstance: ?HINSTANCE,
lpszClass: ?[*:0]const u8,
lpwcx: ?*WNDCLASSEXA,
) callconv(@import("std").os.windows.WINAPI) BOOL;
// TODO: this type is limited to platform 'windows5.0'
pub extern "USER32" fn GetClassInfoExW(
hInstance: ?HINSTANCE,
lpszClass: ?[*:0]const u16,
lpwcx: ?*WNDCLASSEXW,
) callconv(@import("std").os.windows.WINAPI) BOOL;
// TODO: this type is limited to platform 'windows5.0'
pub extern "USER32" fn CreateWindowExA(
dwExStyle: WINDOW_EX_STYLE,
lpClassName: ?[*:0]const u8,
lpWindowName: ?[*:0]const u8,
dwStyle: WINDOW_STYLE,
X: i32,
Y: i32,
nWidth: i32,
nHeight: i32,
hWndParent: ?HWND,
hMenu: ?HMENU,
hInstance: ?HINSTANCE,
lpParam: ?*c_void,
) callconv(@import("std").os.windows.WINAPI) ?HWND;
// TODO: this type is limited to platform 'windows5.0'
pub extern "USER32" fn CreateWindowExW(
dwExStyle: WINDOW_EX_STYLE,
lpClassName: ?[*:0]const u16,
lpWindowName: ?[*:0]const u16,
dwStyle: WINDOW_STYLE,
X: i32,
Y: i32,
nWidth: i32,
nHeight: i32,
hWndParent: ?HWND,
hMenu: ?HMENU,
hInstance: ?HINSTANCE,
lpParam: ?*c_void,
) callconv(@import("std").os.windows.WINAPI) ?HWND;
// TODO: this type is limited to platform 'windows5.0'
pub extern "USER32" fn IsWindow(
hWnd: ?HWND,
) callconv(@import("std").os.windows.WINAPI) BOOL;
// TODO: this type is limited to platform 'windows5.0'
pub extern "USER32" fn IsMenu(
hMenu: ?HMENU,
) callconv(@import("std").os.windows.WINAPI) BOOL;
// TODO: this type is limited to platform 'windows5.0'
pub extern "USER32" fn IsChild(
hWndParent: ?HWND,
hWnd: ?HWND,
) callconv(@import("std").os.windows.WINAPI) BOOL;
// TODO: this type is limited to platform 'windows5.0'
pub extern "USER32" fn DestroyWindow(
hWnd: ?HWND,
) callconv(@import("std").os.windows.WINAPI) BOOL;
// TODO: this type is limited to platform 'windows5.0'
pub extern "USER32" fn ShowWindow(
hWnd: ?HWND,
nCmdShow: SHOW_WINDOW_CMD,
) callconv(@import("std").os.windows.WINAPI) BOOL;
// TODO: this type is limited to platform 'windows5.0'
pub extern "USER32" fn AnimateWindow(
hWnd: ?HWND,
dwTime: u32,
dwFlags: ANIMATE_WINDOW_FLAGS,
) callconv(@import("std").os.windows.WINAPI) BOOL;
// TODO: this type is limited to platform 'windows5.0'
pub extern "USER32" fn UpdateLayeredWindow(
hWnd: ?HWND,
hdcDst: ?HDC,
pptDst: ?*POINT,
psize: ?*SIZE,
hdcSrc: ?HDC,
pptSrc: ?*POINT,
crKey: u32,
pblend: ?*BLENDFUNCTION,
dwFlags: UPDATE_LAYERED_WINDOW_FLAGS,
) callconv(@import("std").os.windows.WINAPI) BOOL;
pub extern "USER32" fn UpdateLayeredWindowIndirect(
hWnd: ?HWND,
pULWInfo: ?*const UPDATELAYEREDWINDOWINFO,
) callconv(@import("std").os.windows.WINAPI) BOOL;
// TODO: this type is limited to platform 'windows5.1.2600'
pub extern "USER32" fn GetLayeredWindowAttributes(
hwnd: ?HWND,
pcrKey: ?*u32,
pbAlpha: ?*u8,
pdwFlags: ?*LAYERED_WINDOW_ATTRIBUTES_FLAGS,
) callconv(@import("std").os.windows.WINAPI) BOOL;
// TODO: this type is limited to platform 'windows5.0'
pub extern "USER32" fn SetLayeredWindowAttributes(
hwnd: ?HWND,
crKey: u32,
bAlpha: u8,
dwFlags: LAYERED_WINDOW_ATTRIBUTES_FLAGS,
) callconv(@import("std").os.windows.WINAPI) BOOL;
// TODO: this type is limited to platform 'windows5.0'
pub extern "USER32" fn ShowWindowAsync(
hWnd: ?HWND,
nCmdShow: SHOW_WINDOW_CMD,
) callconv(@import("std").os.windows.WINAPI) BOOL;
// TODO: this type is limited to platform 'windows5.1.2600'
pub extern "USER32" fn FlashWindow(
hWnd: ?HWND,
bInvert: BOOL,
) callconv(@import("std").os.windows.WINAPI) BOOL;
// TODO: this type is limited to platform 'windows5.1.2600'
pub extern "USER32" fn FlashWindowEx(
pfwi: ?*FLASHWINFO,
) callconv(@import("std").os.windows.WINAPI) BOOL;
// TODO: this type is limited to platform 'windows5.0'
pub extern "USER32" fn ShowOwnedPopups(
hWnd: ?HWND,
fShow: BOOL,
) callconv(@import("std").os.windows.WINAPI) BOOL;
// TODO: this type is limited to platform 'windows5.0'
pub extern "USER32" fn OpenIcon(
hWnd: ?HWND,
) callconv(@import("std").os.windows.WINAPI) BOOL;
// TODO: this type is limited to platform 'windows5.0'
pub extern "USER32" fn CloseWindow(
hWnd: ?HWND,
) callconv(@import("std").os.windows.WINAPI) BOOL;
// TODO: this type is limited to platform 'windows5.0'
pub extern "USER32" fn MoveWindow(
hWnd: ?HWND,
X: i32,
Y: i32,
nWidth: i32,
nHeight: i32,
bRepaint: BOOL,
) callconv(@import("std").os.windows.WINAPI) BOOL;
// TODO: this type is limited to platform 'windows5.0'
pub extern "USER32" fn SetWindowPos(
hWnd: ?HWND,
hWndInsertAfter: ?HWND,
X: i32,
Y: i32,
cx: i32,
cy: i32,
uFlags: SET_WINDOW_POS_FLAGS,
) callconv(@import("std").os.windows.WINAPI) BOOL;
// TODO: this type is limited to platform 'windows5.0'
pub extern "USER32" fn GetWindowPlacement(
hWnd: ?HWND,
lpwndpl: ?*WINDOWPLACEMENT,
) callconv(@import("std").os.windows.WINAPI) BOOL;
// TODO: this type is limited to platform 'windows5.0'
pub extern "USER32" fn SetWindowPlacement(
hWnd: ?HWND,
lpwndpl: ?*const WINDOWPLACEMENT,
) callconv(@import("std").os.windows.WINAPI) BOOL;
// TODO: this type is limited to platform 'windows6.1'
pub extern "USER32" fn GetWindowDisplayAffinity(
hWnd: ?HWND,
pdwAffinity: ?*u32,
) callconv(@import("std").os.windows.WINAPI) BOOL;
// TODO: this type is limited to platform 'windows6.1'
pub extern "USER32" fn SetWindowDisplayAffinity(
hWnd: ?HWND,
dwAffinity: WINDOW_DISPLAY_AFFINITY,
) callconv(@import("std").os.windows.WINAPI) BOOL;
// TODO: this type is limited to platform 'windows5.0'
pub extern "USER32" fn BeginDeferWindowPos(
nNumWindows: i32,
) callconv(@import("std").os.windows.WINAPI) isize;
// TODO: this type is limited to platform 'windows5.0'
pub extern "USER32" fn DeferWindowPos(
hWinPosInfo: isize,
hWnd: ?HWND,
hWndInsertAfter: ?HWND,
x: i32,
y: i32,
cx: i32,
cy: i32,
uFlags: SET_WINDOW_POS_FLAGS,
) callconv(@import("std").os.windows.WINAPI) isize;
// TODO: this type is limited to platform 'windows5.0'
pub extern "USER32" fn EndDeferWindowPos(
hWinPosInfo: isize,
) callconv(@import("std").os.windows.WINAPI) BOOL;
// TODO: this type is limited to platform 'windows5.0'
pub extern "USER32" fn IsWindowVisible(
hWnd: ?HWND,
) callconv(@import("std").os.windows.WINAPI) BOOL;
// TODO: this type is limited to platform 'windows5.0'
pub extern "USER32" fn IsIconic(
hWnd: ?HWND,
) callconv(@import("std").os.windows.WINAPI) BOOL;
// TODO: this type is limited to platform 'windows5.0'
pub extern "USER32" fn AnyPopup(
) callconv(@import("std").os.windows.WINAPI) BOOL;
// TODO: this type is limited to platform 'windows5.0'
pub extern "USER32" fn BringWindowToTop(
hWnd: ?HWND,
) callconv(@import("std").os.windows.WINAPI) BOOL;
// TODO: this type is limited to platform 'windows5.0'
pub extern "USER32" fn IsZoomed(
hWnd: ?HWND,
) callconv(@import("std").os.windows.WINAPI) BOOL;
// TODO: this type is limited to platform 'windows5.0'
pub extern "USER32" fn CreateDialogParamA(
hInstance: ?HINSTANCE,
lpTemplateName: ?[*:0]const u8,
hWndParent: ?HWND,
lpDialogFunc: ?DLGPROC,
dwInitParam: LPARAM,
) callconv(@import("std").os.windows.WINAPI) ?HWND;
// TODO: this type is limited to platform 'windows5.0'
pub extern "USER32" fn CreateDialogParamW(
hInstance: ?HINSTANCE,
lpTemplateName: ?[*:0]const u16,
hWndParent: ?HWND,
lpDialogFunc: ?DLGPROC,
dwInitParam: LPARAM,
) callconv(@import("std").os.windows.WINAPI) ?HWND;
// TODO: this type is limited to platform 'windows5.0'
pub extern "USER32" fn CreateDialogIndirectParamA(
hInstance: ?HINSTANCE,
lpTemplate: ?*DLGTEMPLATE,
hWndParent: ?HWND,
lpDialogFunc: ?DLGPROC,
dwInitParam: LPARAM,
) callconv(@import("std").os.windows.WINAPI) ?HWND;
// TODO: this type is limited to platform 'windows5.0'
pub extern "USER32" fn CreateDialogIndirectParamW(
hInstance: ?HINSTANCE,
lpTemplate: ?*DLGTEMPLATE,
hWndParent: ?HWND,
lpDialogFunc: ?DLGPROC,
dwInitParam: LPARAM,
) callconv(@import("std").os.windows.WINAPI) ?HWND;
// TODO: this type is limited to platform 'windows5.0'
pub extern "USER32" fn DialogBoxParamA(
hInstance: ?HINSTANCE,
lpTemplateName: ?[*:0]const u8,
hWndParent: ?HWND,
lpDialogFunc: ?DLGPROC,
dwInitParam: LPARAM,
) callconv(@import("std").os.windows.WINAPI) isize;
// TODO: this type is limited to platform 'windows5.0'
pub extern "USER32" fn DialogBoxParamW(
hInstance: ?HINSTANCE,
lpTemplateName: ?[*:0]const u16,
hWndParent: ?HWND,
lpDialogFunc: ?DLGPROC,
dwInitParam: LPARAM,
) callconv(@import("std").os.windows.WINAPI) isize;
// TODO: this type is limited to platform 'windows5.0'
pub extern "USER32" fn DialogBoxIndirectParamA(
hInstance: ?HINSTANCE,
hDialogTemplate: ?*DLGTEMPLATE,
hWndParent: ?HWND,
lpDialogFunc: ?DLGPROC,
dwInitParam: LPARAM,
) callconv(@import("std").os.windows.WINAPI) isize;
// TODO: this type is limited to platform 'windows5.0'
pub extern "USER32" fn DialogBoxIndirectParamW(
hInstance: ?HINSTANCE,
hDialogTemplate: ?*DLGTEMPLATE,
hWndParent: ?HWND,
lpDialogFunc: ?DLGPROC,
dwInitParam: LPARAM,
) callconv(@import("std").os.windows.WINAPI) isize;
// TODO: this type is limited to platform 'windows5.0'
pub extern "USER32" fn EndDialog(
hDlg: ?HWND,
nResult: isize,
) callconv(@import("std").os.windows.WINAPI) BOOL;
// TODO: this type is limited to platform 'windows5.0'
pub extern "USER32" fn GetDlgItem(
hDlg: ?HWND,
nIDDlgItem: i32,
) callconv(@import("std").os.windows.WINAPI) ?HWND;
// TODO: this type is limited to platform 'windows5.0'
pub extern "USER32" fn SetDlgItemInt(
hDlg: ?HWND,
nIDDlgItem: i32,
uValue: u32,
bSigned: BOOL,
) callconv(@import("std").os.windows.WINAPI) BOOL;
// TODO: this type is limited to platform 'windows5.0'
pub extern "USER32" fn GetDlgItemInt(
hDlg: ?HWND,
nIDDlgItem: i32,
lpTranslated: ?*BOOL,
bSigned: BOOL,
) callconv(@import("std").os.windows.WINAPI) u32;
// TODO: this type is limited to platform 'windows5.0'
pub extern "USER32" fn SetDlgItemTextA(
hDlg: ?HWND,
nIDDlgItem: i32,
lpString: ?[*:0]const u8,
) callconv(@import("std").os.windows.WINAPI) BOOL;
// TODO: this type is limited to platform 'windows5.0'
pub extern "USER32" fn SetDlgItemTextW(
hDlg: ?HWND,
nIDDlgItem: i32,
lpString: ?[*:0]const u16,
) callconv(@import("std").os.windows.WINAPI) BOOL;
// TODO: this type is limited to platform 'windows5.0'
pub extern "USER32" fn GetDlgItemTextA(
hDlg: ?HWND,
nIDDlgItem: i32,
lpString: [*:0]u8,
cchMax: i32,
) callconv(@import("std").os.windows.WINAPI) u32;
// TODO: this type is limited to platform 'windows5.0'
pub extern "USER32" fn GetDlgItemTextW(
hDlg: ?HWND,
nIDDlgItem: i32,
lpString: [*:0]u16,
cchMax: i32,
) callconv(@import("std").os.windows.WINAPI) u32;
// TODO: this type is limited to platform 'windows5.0'
pub extern "USER32" fn SendDlgItemMessageA(
hDlg: ?HWND,
nIDDlgItem: i32,
Msg: u32,
wParam: WPARAM,
lParam: LPARAM,
) callconv(@import("std").os.windows.WINAPI) LRESULT;
// TODO: this type is limited to platform 'windows5.0'
pub extern "USER32" fn SendDlgItemMessageW(
hDlg: ?HWND,
nIDDlgItem: i32,
Msg: u32,
wParam: WPARAM,
lParam: LPARAM,
) callconv(@import("std").os.windows.WINAPI) LRESULT;
// TODO: this type is limited to platform 'windows5.0'
pub extern "USER32" fn GetNextDlgGroupItem(
hDlg: ?HWND,
hCtl: ?HWND,
bPrevious: BOOL,
) callconv(@import("std").os.windows.WINAPI) ?HWND;
// TODO: this type is limited to platform 'windows5.0'
pub extern "USER32" fn GetNextDlgTabItem(
hDlg: ?HWND,
hCtl: ?HWND,
bPrevious: BOOL,
) callconv(@import("std").os.windows.WINAPI) ?HWND;
// TODO: this type is limited to platform 'windows5.0'
pub extern "USER32" fn GetDlgCtrlID(
hWnd: ?HWND,
) callconv(@import("std").os.windows.WINAPI) i32;
// TODO: this type is limited to platform 'windows5.0'
pub extern "USER32" fn GetDialogBaseUnits(
) callconv(@import("std").os.windows.WINAPI) i32;
pub extern "USER32" fn DefDlgProcA(
hDlg: ?HWND,
Msg: u32,
wParam: WPARAM,
lParam: LPARAM,
) callconv(@import("std").os.windows.WINAPI) LRESULT;
// TODO: this type is limited to platform 'windows5.0'
pub extern "USER32" fn DefDlgProcW(
hDlg: ?HWND,
Msg: u32,
wParam: WPARAM,
lParam: LPARAM,
) callconv(@import("std").os.windows.WINAPI) LRESULT;
// TODO: this type is limited to platform 'windows5.0'
pub extern "USER32" fn CallMsgFilterA(
lpMsg: ?*MSG,
nCode: i32,
) callconv(@import("std").os.windows.WINAPI) BOOL;
// TODO: this type is limited to platform 'windows5.0'
pub extern "USER32" fn CallMsgFilterW(
lpMsg: ?*MSG,
nCode: i32,
) callconv(@import("std").os.windows.WINAPI) BOOL;
// TODO: this type is limited to platform 'windows5.0'
pub extern "USER32" fn CharToOemA(
pSrc: ?[*:0]const u8,
pDst: ?PSTR,
) callconv(@import("std").os.windows.WINAPI) BOOL;
// TODO: this type is limited to platform 'windows5.0'
pub extern "USER32" fn CharToOemW(
pSrc: ?[*:0]const u16,
pDst: ?PSTR,
) callconv(@import("std").os.windows.WINAPI) BOOL;
// TODO: this type is limited to platform 'windows5.0'
pub extern "USER32" fn OemToCharA(
pSrc: ?[*:0]const u8,
pDst: ?PSTR,
) callconv(@import("std").os.windows.WINAPI) BOOL;
// TODO: this type is limited to platform 'windows5.0'
pub extern "USER32" fn OemToCharW(
pSrc: ?[*:0]const u8,
pDst: ?PWSTR,
) callconv(@import("std").os.windows.WINAPI) BOOL;
// TODO: this type is limited to platform 'windows5.0'
pub extern "USER32" fn CharToOemBuffA(
lpszSrc: ?[*:0]const u8,
lpszDst: [*:0]u8,
cchDstLength: u32,
) callconv(@import("std").os.windows.WINAPI) BOOL;
// TODO: this type is limited to platform 'windows5.0'
pub extern "USER32" fn CharToOemBuffW(
lpszSrc: ?[*:0]const u16,
lpszDst: [*:0]u8,
cchDstLength: u32,
) callconv(@import("std").os.windows.WINAPI) BOOL;
// TODO: this type is limited to platform 'windows5.0'
pub extern "USER32" fn OemToCharBuffA(
lpszSrc: ?[*:0]const u8,
lpszDst: [*:0]u8,
cchDstLength: u32,
) callconv(@import("std").os.windows.WINAPI) BOOL;
// TODO: this type is limited to platform 'windows5.0'
pub extern "USER32" fn OemToCharBuffW(
lpszSrc: ?[*:0]const u8,
lpszDst: [*:0]u16,
cchDstLength: u32,
) callconv(@import("std").os.windows.WINAPI) BOOL;
// TODO: this type is limited to platform 'windows5.0'
pub extern "USER32" fn CharUpperA(
lpsz: ?PSTR,
) callconv(@import("std").os.windows.WINAPI) ?PSTR;
// TODO: this type is limited to platform 'windows5.0'
pub extern "USER32" fn CharUpperW(
lpsz: ?PWSTR,
) callconv(@import("std").os.windows.WINAPI) ?PWSTR;
// TODO: this type is limited to platform 'windows5.0'
pub extern "USER32" fn CharUpperBuffA(
lpsz: [*:0]u8,
cchLength: u32,
) callconv(@import("std").os.windows.WINAPI) u32;
// TODO: this type is limited to platform 'windows5.0'
pub extern "USER32" fn CharUpperBuffW(
lpsz: [*:0]u16,
cchLength: u32,
) callconv(@import("std").os.windows.WINAPI) u32;
// TODO: this type is limited to platform 'windows5.0'
pub extern "USER32" fn CharLowerA(
lpsz: ?PSTR,
) callconv(@import("std").os.windows.WINAPI) ?PSTR;
// TODO: this type is limited to platform 'windows5.0'
pub extern "USER32" fn CharLowerW(
lpsz: ?PWSTR,
) callconv(@import("std").os.windows.WINAPI) ?PWSTR;
// TODO: this type is limited to platform 'windows5.0'
pub extern "USER32" fn CharLowerBuffA(
lpsz: [*:0]u8,
cchLength: u32,
) callconv(@import("std").os.windows.WINAPI) u32;
// TODO: this type is limited to platform 'windows5.0'
pub extern "USER32" fn CharLowerBuffW(
lpsz: [*:0]u16,
cchLength: u32,
) callconv(@import("std").os.windows.WINAPI) u32;
// TODO: this type is limited to platform 'windows5.0'
pub extern "USER32" fn CharNextA(
lpsz: ?[*:0]const u8,
) callconv(@import("std").os.windows.WINAPI) ?PSTR;
// TODO: this type is limited to platform 'windows5.0'
pub extern "USER32" fn CharNextW(
lpsz: ?[*:0]const u16,
) callconv(@import("std").os.windows.WINAPI) ?PWSTR;
// TODO: this type is limited to platform 'windows5.0'
pub extern "USER32" fn CharPrevA(
lpszStart: ?[*:0]const u8,
lpszCurrent: ?[*:0]const u8,
) callconv(@import("std").os.windows.WINAPI) ?PSTR;
// TODO: this type is limited to platform 'windows5.0'
pub extern "USER32" fn CharPrevW(
lpszStart: ?[*:0]const u16,
lpszCurrent: ?[*:0]const u16,
) callconv(@import("std").os.windows.WINAPI) ?PWSTR;
// TODO: this type is limited to platform 'windows5.0'
pub extern "USER32" fn CharNextExA(
CodePage: u16,
lpCurrentChar: ?[*:0]const u8,
dwFlags: u32,
) callconv(@import("std").os.windows.WINAPI) ?PSTR;
// TODO: this type is limited to platform 'windows5.0'
pub extern "USER32" fn CharPrevExA(
CodePage: u16,
lpStart: ?[*:0]const u8,
lpCurrentChar: ?[*:0]const u8,
dwFlags: u32,
) callconv(@import("std").os.windows.WINAPI) ?PSTR;
// TODO: this type is limited to platform 'windows5.0'
pub extern "USER32" fn IsCharAlphaA(
ch: CHAR,
) callconv(@import("std").os.windows.WINAPI) BOOL;
// TODO: this type is limited to platform 'windows5.0'
pub extern "USER32" fn IsCharAlphaW(
ch: u16,
) callconv(@import("std").os.windows.WINAPI) BOOL;
// TODO: this type is limited to platform 'windows5.0'
pub extern "USER32" fn IsCharAlphaNumericA(
ch: CHAR,
) callconv(@import("std").os.windows.WINAPI) BOOL;
// TODO: this type is limited to platform 'windows5.0'
pub extern "USER32" fn IsCharAlphaNumericW(
ch: u16,
) callconv(@import("std").os.windows.WINAPI) BOOL;
// TODO: this type is limited to platform 'windows5.0'
pub extern "USER32" fn IsCharUpperA(
ch: CHAR,
) callconv(@import("std").os.windows.WINAPI) BOOL;
// TODO: this type is limited to platform 'windows5.0'
pub extern "USER32" fn IsCharUpperW(
ch: u16,
) callconv(@import("std").os.windows.WINAPI) BOOL;
// TODO: this type is limited to platform 'windows5.0'
pub extern "USER32" fn IsCharLowerA(
ch: CHAR,
) callconv(@import("std").os.windows.WINAPI) BOOL;
// TODO: this type is limited to platform 'windows5.0'
pub extern "USER32" fn GetInputState(
) callconv(@import("std").os.windows.WINAPI) BOOL;
// TODO: this type is limited to platform 'windows5.0'
pub extern "USER32" fn GetQueueStatus(
flags: QUEUE_STATUS_FLAGS,
) callconv(@import("std").os.windows.WINAPI) u32;
// TODO: this type is limited to platform 'windows5.0'
pub extern "USER32" fn SetTimer(
hWnd: ?HWND,
nIDEvent: usize,
uElapse: u32,
lpTimerFunc: ?TIMERPROC,
) callconv(@import("std").os.windows.WINAPI) usize;
// TODO: this type is limited to platform 'windows8.0'
pub extern "USER32" fn SetCoalescableTimer(
hWnd: ?HWND,
nIDEvent: usize,
uElapse: u32,
lpTimerFunc: ?TIMERPROC,
uToleranceDelay: u32,
) callconv(@import("std").os.windows.WINAPI) usize;
// TODO: this type is limited to platform 'windows5.0'
pub extern "USER32" fn KillTimer(
hWnd: ?HWND,
uIDEvent: usize,
) callconv(@import("std").os.windows.WINAPI) BOOL;
// TODO: this type is limited to platform 'windows5.0'
pub extern "USER32" fn IsWindowUnicode(
hWnd: ?HWND,
) callconv(@import("std").os.windows.WINAPI) BOOL;
// TODO: this type is limited to platform 'windows5.0'
pub extern "USER32" fn LoadAcceleratorsA(
hInstance: ?HINSTANCE,
lpTableName: ?[*:0]const u8,
) callconv(@import("std").os.windows.WINAPI) ?HACCEL;
// TODO: this type is limited to platform 'windows5.0'
pub extern "USER32" fn LoadAcceleratorsW(
hInstance: ?HINSTANCE,
lpTableName: ?[*:0]const u16,
) callconv(@import("std").os.windows.WINAPI) ?HACCEL;
// TODO: this type is limited to platform 'windows5.0'
pub extern "USER32" fn CreateAcceleratorTableA(
paccel: [*]ACCEL,
cAccel: i32,
) callconv(@import("std").os.windows.WINAPI) ?HACCEL;
// TODO: this type is limited to platform 'windows5.0'
pub extern "USER32" fn CreateAcceleratorTableW(
paccel: [*]ACCEL,
cAccel: i32,
) callconv(@import("std").os.windows.WINAPI) ?HACCEL;
// TODO: this type is limited to platform 'windows5.0'
pub extern "USER32" fn DestroyAcceleratorTable(
hAccel: ?HACCEL,
) callconv(@import("std").os.windows.WINAPI) BOOL;
// TODO: this type is limited to platform 'windows5.0'
pub extern "USER32" fn CopyAcceleratorTableA(
hAccelSrc: ?HACCEL,
lpAccelDst: ?[*]ACCEL,
cAccelEntries: i32,
) callconv(@import("std").os.windows.WINAPI) i32;
// TODO: this type is limited to platform 'windows5.0'
pub extern "USER32" fn CopyAcceleratorTableW(
hAccelSrc: ?HACCEL,
lpAccelDst: ?[*]ACCEL,
cAccelEntries: i32,
) callconv(@import("std").os.windows.WINAPI) i32;
// TODO: this type is limited to platform 'windows5.0'
pub extern "USER32" fn TranslateAcceleratorA(
hWnd: ?HWND,
hAccTable: ?HACCEL,
lpMsg: ?*MSG,
) callconv(@import("std").os.windows.WINAPI) i32;
// TODO: this type is limited to platform 'windows5.0'
pub extern "USER32" fn TranslateAcceleratorW(
hWnd: ?HWND,
hAccTable: ?HACCEL,
lpMsg: ?*MSG,
) callconv(@import("std").os.windows.WINAPI) i32;
// TODO: this type is limited to platform 'windows5.0'
pub extern "USER32" fn GetSystemMetrics(
nIndex: SYSTEM_METRICS_INDEX,
) callconv(@import("std").os.windows.WINAPI) i32;
// TODO: this type is limited to platform 'windows5.0'
pub extern "USER32" fn LoadMenuA(
hInstance: ?HINSTANCE,
lpMenuName: ?[*:0]const u8,
) callconv(@import("std").os.windows.WINAPI) ?HMENU;
// TODO: this type is limited to platform 'windows5.0'
pub extern "USER32" fn LoadMenuW(
hInstance: ?HINSTANCE,
lpMenuName: ?[*:0]const u16,
) callconv(@import("std").os.windows.WINAPI) ?HMENU;
// TODO: this type is limited to platform 'windows5.0'
pub extern "USER32" fn LoadMenuIndirectA(
lpMenuTemplate: ?*const c_void,
) callconv(@import("std").os.windows.WINAPI) ?HMENU;
// TODO: this type is limited to platform 'windows5.0'
pub extern "USER32" fn LoadMenuIndirectW(
lpMenuTemplate: ?*const c_void,
) callconv(@import("std").os.windows.WINAPI) ?HMENU;
// TODO: this type is limited to platform 'windows5.0'
pub extern "USER32" fn GetMenu(
hWnd: ?HWND,
) callconv(@import("std").os.windows.WINAPI) ?HMENU;
// TODO: this type is limited to platform 'windows5.0'
pub extern "USER32" fn SetMenu(
hWnd: ?HWND,
hMenu: ?HMENU,
) callconv(@import("std").os.windows.WINAPI) BOOL;
pub extern "USER32" fn ChangeMenuA(
hMenu: ?HMENU,
cmd: u32,
lpszNewItem: ?[*:0]const u8,
cmdInsert: u32,
flags: u32,
) callconv(@import("std").os.windows.WINAPI) BOOL;
pub extern "USER32" fn ChangeMenuW(
hMenu: ?HMENU,
cmd: u32,
lpszNewItem: ?[*:0]const u16,
cmdInsert: u32,
flags: u32,
) callconv(@import("std").os.windows.WINAPI) BOOL;
// TODO: this type is limited to platform 'windows5.0'
pub extern "USER32" fn HiliteMenuItem(
hWnd: ?HWND,
hMenu: ?HMENU,
uIDHiliteItem: u32,
uHilite: u32,
) callconv(@import("std").os.windows.WINAPI) BOOL;
// TODO: this type is limited to platform 'windows5.0'
pub extern "USER32" fn GetMenuStringA(
hMenu: ?HMENU,
uIDItem: u32,
lpString: ?[*:0]u8,
cchMax: i32,
flags: MENU_ITEM_FLAGS,
) callconv(@import("std").os.windows.WINAPI) i32;
// TODO: this type is limited to platform 'windows5.0'
pub extern "USER32" fn GetMenuStringW(
hMenu: ?HMENU,
uIDItem: u32,
lpString: ?[*:0]u16,
cchMax: i32,
flags: MENU_ITEM_FLAGS,
) callconv(@import("std").os.windows.WINAPI) i32;
// TODO: this type is limited to platform 'windows5.0'
pub extern "USER32" fn GetMenuState(
hMenu: ?HMENU,
uId: u32,
uFlags: MENU_ITEM_FLAGS,
) callconv(@import("std").os.windows.WINAPI) u32;
// TODO: this type is limited to platform 'windows5.0'
pub extern "USER32" fn DrawMenuBar(
hWnd: ?HWND,
) callconv(@import("std").os.windows.WINAPI) BOOL;
// TODO: this type is limited to platform 'windows5.0'
pub extern "USER32" fn GetSystemMenu(
hWnd: ?HWND,
bRevert: BOOL,
) callconv(@import("std").os.windows.WINAPI) ?HMENU;
// TODO: this type is limited to platform 'windows5.0'
pub extern "USER32" fn CreateMenu(
) callconv(@import("std").os.windows.WINAPI) ?HMENU;
// TODO: this type is limited to platform 'windows5.0'
pub extern "USER32" fn CreatePopupMenu(
) callconv(@import("std").os.windows.WINAPI) ?HMENU;
// TODO: this type is limited to platform 'windows5.0'
pub extern "USER32" fn DestroyMenu(
hMenu: ?HMENU,
) callconv(@import("std").os.windows.WINAPI) BOOL;
// TODO: this type is limited to platform 'windows5.0'
pub extern "USER32" fn CheckMenuItem(
hMenu: ?HMENU,
uIDCheckItem: u32,
uCheck: u32,
) callconv(@import("std").os.windows.WINAPI) u32;
// TODO: this type is limited to platform 'windows5.0'
pub extern "USER32" fn EnableMenuItem(
hMenu: ?HMENU,
uIDEnableItem: u32,
uEnable: MENU_ITEM_FLAGS,
) callconv(@import("std").os.windows.WINAPI) BOOL;
// TODO: this type is limited to platform 'windows5.0'
pub extern "USER32" fn GetSubMenu(
hMenu: ?HMENU,
nPos: i32,
) callconv(@import("std").os.windows.WINAPI) ?HMENU;
// TODO: this type is limited to platform 'windows5.0'
pub extern "USER32" fn GetMenuItemID(
hMenu: ?HMENU,
nPos: i32,
) callconv(@import("std").os.windows.WINAPI) u32;
// TODO: this type is limited to platform 'windows5.0'
pub extern "USER32" fn GetMenuItemCount(
hMenu: ?HMENU,
) callconv(@import("std").os.windows.WINAPI) i32;
// TODO: this type is limited to platform 'windows5.0'
pub extern "USER32" fn InsertMenuA(
hMenu: ?HMENU,
uPosition: u32,
uFlags: MENU_ITEM_FLAGS,
uIDNewItem: usize,
lpNewItem: ?[*:0]const u8,
) callconv(@import("std").os.windows.WINAPI) BOOL;
// TODO: this type is limited to platform 'windows5.0'
pub extern "USER32" fn InsertMenuW(
hMenu: ?HMENU,
uPosition: u32,
uFlags: MENU_ITEM_FLAGS,
uIDNewItem: usize,
lpNewItem: ?[*:0]const u16,
) callconv(@import("std").os.windows.WINAPI) BOOL;
// TODO: this type is limited to platform 'windows5.0'
pub extern "USER32" fn AppendMenuA(
hMenu: ?HMENU,
uFlags: MENU_ITEM_FLAGS,
uIDNewItem: usize,
lpNewItem: ?[*:0]const u8,
) callconv(@import("std").os.windows.WINAPI) BOOL;
// TODO: this type is limited to platform 'windows5.0'
pub extern "USER32" fn AppendMenuW(
hMenu: ?HMENU,
uFlags: MENU_ITEM_FLAGS,
uIDNewItem: usize,
lpNewItem: ?[*:0]const u16,
) callconv(@import("std").os.windows.WINAPI) BOOL;
// TODO: this type is limited to platform 'windows5.0'
pub extern "USER32" fn ModifyMenuA(
hMnu: ?HMENU,
uPosition: u32,
uFlags: MENU_ITEM_FLAGS,
uIDNewItem: usize,
lpNewItem: ?[*:0]const u8,
) callconv(@import("std").os.windows.WINAPI) BOOL;
// TODO: this type is limited to platform 'windows5.0'
pub extern "USER32" fn ModifyMenuW(
hMnu: ?HMENU,
uPosition: u32,
uFlags: MENU_ITEM_FLAGS,
uIDNewItem: usize,
lpNewItem: ?[*:0]const u16,
) callconv(@import("std").os.windows.WINAPI) BOOL;
// TODO: this type is limited to platform 'windows5.0'
pub extern "USER32" fn RemoveMenu(
hMenu: ?HMENU,
uPosition: u32,
uFlags: MENU_ITEM_FLAGS,
) callconv(@import("std").os.windows.WINAPI) BOOL;
// TODO: this type is limited to platform 'windows5.0'
pub extern "USER32" fn DeleteMenu(
hMenu: ?HMENU,
uPosition: u32,
uFlags: MENU_ITEM_FLAGS,
) callconv(@import("std").os.windows.WINAPI) BOOL;
// TODO: this type is limited to platform 'windows5.0'
pub extern "USER32" fn SetMenuItemBitmaps(
hMenu: ?HMENU,
uPosition: u32,
uFlags: MENU_ITEM_FLAGS,
hBitmapUnchecked: ?HBITMAP,
hBitmapChecked: ?HBITMAP,
) callconv(@import("std").os.windows.WINAPI) BOOL;
// TODO: this type is limited to platform 'windows5.0'
pub extern "USER32" fn GetMenuCheckMarkDimensions(
) callconv(@import("std").os.windows.WINAPI) i32;
// TODO: this type is limited to platform 'windows5.0'
pub extern "USER32" fn TrackPopupMenu(
hMenu: ?HMENU,
uFlags: TRACK_POPUP_MENU_FLAGS,
x: i32,
y: i32,
nReserved: i32,
hWnd: ?HWND,
prcRect: ?*const RECT,
) callconv(@import("std").os.windows.WINAPI) BOOL;
// TODO: this type is limited to platform 'windows5.0'
pub extern "USER32" fn TrackPopupMenuEx(
hMenu: ?HMENU,
uFlags: u32,
x: i32,
y: i32,
hwnd: ?HWND,
lptpm: ?*TPMPARAMS,
) callconv(@import("std").os.windows.WINAPI) BOOL;
// TODO: this type is limited to platform 'windows6.1'
pub extern "USER32" fn CalculatePopupWindowPosition(
anchorPoint: ?*const POINT,
windowSize: ?*const SIZE,
flags: u32,
excludeRect: ?*RECT,
popupWindowPosition: ?*RECT,
) callconv(@import("std").os.windows.WINAPI) BOOL;
// TODO: this type is limited to platform 'windows5.0'
pub extern "USER32" fn GetMenuInfo(
param0: ?HMENU,
param1: ?*MENUINFO,
) callconv(@import("std").os.windows.WINAPI) BOOL;
// TODO: this type is limited to platform 'windows5.0'
pub extern "USER32" fn SetMenuInfo(
param0: ?HMENU,
param1: ?*MENUINFO,
) callconv(@import("std").os.windows.WINAPI) BOOL;
// TODO: this type is limited to platform 'windows5.0'
pub extern "USER32" fn EndMenu(
) callconv(@import("std").os.windows.WINAPI) BOOL;
// TODO: this type is limited to platform 'windows5.0'
pub extern "USER32" fn InsertMenuItemA(
hmenu: ?HMENU,
item: u32,
fByPosition: BOOL,
lpmi: ?*MENUITEMINFOA,
) callconv(@import("std").os.windows.WINAPI) BOOL;
// TODO: this type is limited to platform 'windows5.0'
pub extern "USER32" fn InsertMenuItemW(
hmenu: ?HMENU,
item: u32,
fByPosition: BOOL,
lpmi: ?*MENUITEMINFOW,
) callconv(@import("std").os.windows.WINAPI) BOOL;
// TODO: this type is limited to platform 'windows5.0'
pub extern "USER32" fn GetMenuItemInfoA(
hmenu: ?HMENU,
item: u32,
fByPosition: BOOL,
lpmii: ?*MENUITEMINFOA,
) callconv(@import("std").os.windows.WINAPI) BOOL;
// TODO: this type is limited to platform 'windows5.0'
pub extern "USER32" fn GetMenuItemInfoW(
hmenu: ?HMENU,
item: u32,
fByPosition: BOOL,
lpmii: ?*MENUITEMINFOW,
) callconv(@import("std").os.windows.WINAPI) BOOL;
// TODO: this type is limited to platform 'windows5.0'
pub extern "USER32" fn SetMenuItemInfoA(
hmenu: ?HMENU,
item: u32,
fByPositon: BOOL,
lpmii: ?*MENUITEMINFOA,
) callconv(@import("std").os.windows.WINAPI) BOOL;
// TODO: this type is limited to platform 'windows5.0'
pub extern "USER32" fn SetMenuItemInfoW(
hmenu: ?HMENU,
item: u32,
fByPositon: BOOL,
lpmii: ?*MENUITEMINFOW,
) callconv(@import("std").os.windows.WINAPI) BOOL;
// TODO: this type is limited to platform 'windows5.0'
pub extern "USER32" fn GetMenuDefaultItem(
hMenu: ?HMENU,
fByPos: u32,
gmdiFlags: GET_MENU_DEFAULT_ITEM_FLAGS,
) callconv(@import("std").os.windows.WINAPI) u32;
// TODO: this type is limited to platform 'windows5.0'
pub extern "USER32" fn SetMenuDefaultItem(
hMenu: ?HMENU,
uItem: u32,
fByPos: u32,
) callconv(@import("std").os.windows.WINAPI) BOOL;
// TODO: this type is limited to platform 'windows5.0'
pub extern "USER32" fn GetMenuItemRect(
hWnd: ?HWND,
hMenu: ?HMENU,
uItem: u32,
lprcItem: ?*RECT,
) callconv(@import("std").os.windows.WINAPI) BOOL;
// TODO: this type is limited to platform 'windows5.0'
pub extern "USER32" fn MenuItemFromPoint(
hWnd: ?HWND,
hMenu: ?HMENU,
ptScreen: POINT,
) callconv(@import("std").os.windows.WINAPI) i32;
pub extern "USER32" fn DragObject(
hwndParent: ?HWND,
hwndFrom: ?HWND,
fmt: u32,
data: usize,
hcur: ?HCURSOR,
) callconv(@import("std").os.windows.WINAPI) u32;
// TODO: this type is limited to platform 'windows5.0'
pub extern "USER32" fn DrawIcon(
hDC: ?HDC,
X: i32,
Y: i32,
hIcon: ?HICON,
) callconv(@import("std").os.windows.WINAPI) BOOL;
// TODO: this type is limited to platform 'windows5.0'
pub extern "USER32" fn GetForegroundWindow(
) callconv(@import("std").os.windows.WINAPI) ?HWND;
// TODO: this type is limited to platform 'windows5.0'
pub extern "USER32" fn SwitchToThisWindow(
hwnd: ?HWND,
fUnknown: BOOL,
) callconv(@import("std").os.windows.WINAPI) void;
// TODO: this type is limited to platform 'windows5.0'
pub extern "USER32" fn SetForegroundWindow(
hWnd: ?HWND,
) callconv(@import("std").os.windows.WINAPI) BOOL;
// TODO: this type is limited to platform 'windows5.0'
pub extern "USER32" fn AllowSetForegroundWindow(
dwProcessId: u32,
) callconv(@import("std").os.windows.WINAPI) BOOL;
// TODO: this type is limited to platform 'windows5.0'
pub extern "USER32" fn LockSetForegroundWindow(
uLockCode: FOREGROUND_WINDOW_LOCK_CODE,
) callconv(@import("std").os.windows.WINAPI) BOOL;
// TODO: this type is limited to platform 'windows5.0'
pub extern "USER32" fn SetPropA(
hWnd: ?HWND,
lpString: ?[*:0]const u8,
hData: ?HANDLE,
) callconv(@import("std").os.windows.WINAPI) BOOL;
// TODO: this type is limited to platform 'windows5.0'
pub extern "USER32" fn SetPropW(
hWnd: ?HWND,
lpString: ?[*:0]const u16,
hData: ?HANDLE,
) callconv(@import("std").os.windows.WINAPI) BOOL;
// TODO: this type is limited to platform 'windows5.0'
pub extern "USER32" fn GetPropA(
hWnd: ?HWND,
lpString: ?[*:0]const u8,
) callconv(@import("std").os.windows.WINAPI) ?HANDLE;
// TODO: this type is limited to platform 'windows5.0'
pub extern "USER32" fn GetPropW(
hWnd: ?HWND,
lpString: ?[*:0]const u16,
) callconv(@import("std").os.windows.WINAPI) ?HANDLE;
// TODO: this type is limited to platform 'windows5.0'
pub extern "USER32" fn RemovePropA(
hWnd: ?HWND,
lpString: ?[*:0]const u8,
) callconv(@import("std").os.windows.WINAPI) ?HANDLE;
// TODO: this type is limited to platform 'windows5.0'
pub extern "USER32" fn RemovePropW(
hWnd: ?HWND,
lpString: ?[*:0]const u16,
) callconv(@import("std").os.windows.WINAPI) ?HANDLE;
// TODO: this type is limited to platform 'windows5.0'
pub extern "USER32" fn EnumPropsExA(
hWnd: ?HWND,
lpEnumFunc: ?PROPENUMPROCEXA,
lParam: LPARAM,
) callconv(@import("std").os.windows.WINAPI) i32;
// TODO: this type is limited to platform 'windows5.0'
pub extern "USER32" fn EnumPropsExW(
hWnd: ?HWND,
lpEnumFunc: ?PROPENUMPROCEXW,
lParam: LPARAM,
) callconv(@import("std").os.windows.WINAPI) i32;
// TODO: this type is limited to platform 'windows5.0'
pub extern "USER32" fn EnumPropsA(
hWnd: ?HWND,
lpEnumFunc: ?PROPENUMPROCA,
) callconv(@import("std").os.windows.WINAPI) i32;
// TODO: this type is limited to platform 'windows5.0'
pub extern "USER32" fn EnumPropsW(
hWnd: ?HWND,
lpEnumFunc: ?PROPENUMPROCW,
) callconv(@import("std").os.windows.WINAPI) i32;
// TODO: this type is limited to platform 'windows5.0'
pub extern "USER32" fn SetWindowTextA(
hWnd: ?HWND,
lpString: ?[*:0]const u8,
) callconv(@import("std").os.windows.WINAPI) BOOL;
// TODO: this type is limited to platform 'windows5.0'
pub extern "USER32" fn SetWindowTextW(
hWnd: ?HWND,
lpString: ?[*:0]const u16,
) callconv(@import("std").os.windows.WINAPI) BOOL;
// TODO: this type is limited to platform 'windows5.0'
pub extern "USER32" fn GetWindowTextA(
hWnd: ?HWND,
lpString: [*:0]u8,
nMaxCount: i32,
) callconv(@import("std").os.windows.WINAPI) i32;
// TODO: this type is limited to platform 'windows5.0'
pub extern "USER32" fn GetWindowTextW(
hWnd: ?HWND,
lpString: [*:0]u16,
nMaxCount: i32,
) callconv(@import("std").os.windows.WINAPI) i32;
// TODO: this type is limited to platform 'windows5.0'
pub extern "USER32" fn GetWindowTextLengthA(
hWnd: ?HWND,
) callconv(@import("std").os.windows.WINAPI) i32;
// TODO: this type is limited to platform 'windows5.0'
pub extern "USER32" fn GetWindowTextLengthW(
hWnd: ?HWND,
) callconv(@import("std").os.windows.WINAPI) i32;
// TODO: this type is limited to platform 'windows5.0'
pub extern "USER32" fn GetClientRect(
hWnd: ?HWND,
lpRect: ?*RECT,
) callconv(@import("std").os.windows.WINAPI) BOOL;
// TODO: this type is limited to platform 'windows5.0'
pub extern "USER32" fn GetWindowRect(
hWnd: ?HWND,
lpRect: ?*RECT,
) callconv(@import("std").os.windows.WINAPI) BOOL;
// TODO: this type is limited to platform 'windows5.0'
pub extern "USER32" fn AdjustWindowRect(
lpRect: ?*RECT,
dwStyle: WINDOW_STYLE,
bMenu: BOOL,
) callconv(@import("std").os.windows.WINAPI) BOOL;
// TODO: this type is limited to platform 'windows5.0'
pub extern "USER32" fn AdjustWindowRectEx(
lpRect: ?*RECT,
dwStyle: WINDOW_STYLE,
bMenu: BOOL,
dwExStyle: WINDOW_EX_STYLE,
) callconv(@import("std").os.windows.WINAPI) BOOL;
// TODO: this type is limited to platform 'windows5.0'
pub extern "USER32" fn MessageBoxA(
hWnd: ?HWND,
lpText: ?[*:0]const u8,
lpCaption: ?[*:0]const u8,
uType: MESSAGEBOX_STYLE,
) callconv(@import("std").os.windows.WINAPI) MESSAGEBOX_RESULT;
// TODO: this type is limited to platform 'windows5.0'
pub extern "USER32" fn MessageBoxW(
hWnd: ?HWND,
lpText: ?[*:0]const u16,
lpCaption: ?[*:0]const u16,
uType: MESSAGEBOX_STYLE,
) callconv(@import("std").os.windows.WINAPI) MESSAGEBOX_RESULT;
// TODO: this type is limited to platform 'windows5.0'
pub extern "USER32" fn MessageBoxExA(
hWnd: ?HWND,
lpText: ?[*:0]const u8,
lpCaption: ?[*:0]const u8,
uType: MESSAGEBOX_STYLE,
wLanguageId: u16,
) callconv(@import("std").os.windows.WINAPI) MESSAGEBOX_RESULT;
// TODO: this type is limited to platform 'windows5.0'
pub extern "USER32" fn MessageBoxExW(
hWnd: ?HWND,
lpText: ?[*:0]const u16,
lpCaption: ?[*:0]const u16,
uType: MESSAGEBOX_STYLE,
wLanguageId: u16,
) callconv(@import("std").os.windows.WINAPI) MESSAGEBOX_RESULT;
// TODO: this type is limited to platform 'windows5.0'
pub extern "USER32" fn MessageBoxIndirectA(
lpmbp: ?*const MSGBOXPARAMSA,
) callconv(@import("std").os.windows.WINAPI) MESSAGEBOX_RESULT;
// TODO: this type is limited to platform 'windows5.0'
pub extern "USER32" fn MessageBoxIndirectW(
lpmbp: ?*const MSGBOXPARAMSW,
) callconv(@import("std").os.windows.WINAPI) MESSAGEBOX_RESULT;
// TODO: this type is limited to platform 'windows5.0'
pub extern "USER32" fn ShowCursor(
bShow: BOOL,
) callconv(@import("std").os.windows.WINAPI) i32;
// TODO: this type is limited to platform 'windows5.0'
pub extern "USER32" fn SetCursorPos(
X: i32,
Y: i32,
) callconv(@import("std").os.windows.WINAPI) BOOL;
// TODO: this type is limited to platform 'windows6.0.6000'
pub extern "USER32" fn SetPhysicalCursorPos(
X: i32,
Y: i32,
) callconv(@import("std").os.windows.WINAPI) BOOL;
// TODO: this type is limited to platform 'windows5.0'
pub extern "USER32" fn SetCursor(
hCursor: ?HCURSOR,
) callconv(@import("std").os.windows.WINAPI) ?HCURSOR;
// TODO: this type is limited to platform 'windows5.0'
pub extern "USER32" fn GetCursorPos(
lpPoint: ?*POINT,
) callconv(@import("std").os.windows.WINAPI) BOOL;
// TODO: this type is limited to platform 'windows6.0.6000'
pub extern "USER32" fn GetPhysicalCursorPos(
lpPoint: ?*POINT,
) callconv(@import("std").os.windows.WINAPI) BOOL;
// TODO: this type is limited to platform 'windows5.0'
pub extern "USER32" fn GetClipCursor(
lpRect: ?*RECT,
) callconv(@import("std").os.windows.WINAPI) BOOL;
// TODO: this type is limited to platform 'windows5.0'
pub extern "USER32" fn GetCursor(
) callconv(@import("std").os.windows.WINAPI) ?HCURSOR;
// TODO: this type is limited to platform 'windows5.0'
pub extern "USER32" fn CreateCaret(
hWnd: ?HWND,
hBitmap: ?HBITMAP,
nWidth: i32,
nHeight: i32,
) callconv(@import("std").os.windows.WINAPI) BOOL;
// TODO: this type is limited to platform 'windows5.0'
pub extern "USER32" fn GetCaretBlinkTime(
) callconv(@import("std").os.windows.WINAPI) u32;
// TODO: this type is limited to platform 'windows5.0'
pub extern "USER32" fn SetCaretBlinkTime(
uMSeconds: u32,
) callconv(@import("std").os.windows.WINAPI) BOOL;
// TODO: this type is limited to platform 'windows5.0'
pub extern "USER32" fn DestroyCaret(
) callconv(@import("std").os.windows.WINAPI) BOOL;
// TODO: this type is limited to platform 'windows5.0'
pub extern "USER32" fn HideCaret(
hWnd: ?HWND,
) callconv(@import("std").os.windows.WINAPI) BOOL;
// TODO: this type is limited to platform 'windows5.0'
pub extern "USER32" fn ShowCaret(
hWnd: ?HWND,
) callconv(@import("std").os.windows.WINAPI) BOOL;
// TODO: this type is limited to platform 'windows5.0'
pub extern "USER32" fn SetCaretPos(
X: i32,
Y: i32,
) callconv(@import("std").os.windows.WINAPI) BOOL;
// TODO: this type is limited to platform 'windows5.0'
pub extern "USER32" fn GetCaretPos(
lpPoint: ?*POINT,
) callconv(@import("std").os.windows.WINAPI) BOOL;
// TODO: this type is limited to platform 'windows6.0.6000'
pub extern "USER32" fn LogicalToPhysicalPoint(
hWnd: ?HWND,
lpPoint: ?*POINT,
) callconv(@import("std").os.windows.WINAPI) BOOL;
// TODO: this type is limited to platform 'windows6.0.6000'
pub extern "USER32" fn PhysicalToLogicalPoint(
hWnd: ?HWND,
lpPoint: ?*POINT,
) callconv(@import("std").os.windows.WINAPI) BOOL;
// TODO: this type is limited to platform 'windows5.0'
pub extern "USER32" fn WindowFromPoint(
Point: POINT,
) callconv(@import("std").os.windows.WINAPI) ?HWND;
// TODO: this type is limited to platform 'windows6.0.6000'
pub extern "USER32" fn WindowFromPhysicalPoint(
Point: POINT,
) callconv(@import("std").os.windows.WINAPI) ?HWND;
// TODO: this type is limited to platform 'windows5.0'
pub extern "USER32" fn ChildWindowFromPoint(
hWndParent: ?HWND,
Point: POINT,
) callconv(@import("std").os.windows.WINAPI) ?HWND;
// TODO: this type is limited to platform 'windows5.0'
pub extern "USER32" fn ClipCursor(
lpRect: ?*const RECT,
) callconv(@import("std").os.windows.WINAPI) BOOL;
// TODO: this type is limited to platform 'windows5.0'
pub extern "USER32" fn ChildWindowFromPointEx(
hwnd: ?HWND,
pt: POINT,
flags: CWP_FLAGS,
) callconv(@import("std").os.windows.WINAPI) ?HWND;
// TODO: this type is limited to platform 'windows5.0'
pub extern "USER32" fn GetSysColor(
nIndex: SYS_COLOR_INDEX,
) callconv(@import("std").os.windows.WINAPI) u32;
// TODO: this type is limited to platform 'windows5.0'
pub extern "USER32" fn SetSysColors(
cElements: i32,
lpaElements: [*]const i32,
lpaRgbValues: [*]const u32,
) callconv(@import("std").os.windows.WINAPI) BOOL;
pub extern "USER32" fn GetWindowWord(
hWnd: ?HWND,
nIndex: i32,
) callconv(@import("std").os.windows.WINAPI) u16;
pub extern "USER32" fn SetWindowWord(
hWnd: ?HWND,
nIndex: i32,
wNewWord: u16,
) callconv(@import("std").os.windows.WINAPI) u16;
// TODO: this type is limited to platform 'windows5.0'
pub extern "USER32" fn GetWindowLongA(
hWnd: ?HWND,
nIndex: WINDOW_LONG_PTR_INDEX,
) callconv(@import("std").os.windows.WINAPI) i32;
// TODO: this type is limited to platform 'windows5.0'
pub extern "USER32" fn GetWindowLongW(
hWnd: ?HWND,
nIndex: WINDOW_LONG_PTR_INDEX,
) callconv(@import("std").os.windows.WINAPI) i32;
// TODO: this type is limited to platform 'windows5.0'
pub extern "USER32" fn SetWindowLongA(
hWnd: ?HWND,
nIndex: WINDOW_LONG_PTR_INDEX,
dwNewLong: i32,
) callconv(@import("std").os.windows.WINAPI) i32;
// TODO: this type is limited to platform 'windows5.0'
pub extern "USER32" fn SetWindowLongW(
hWnd: ?HWND,
nIndex: WINDOW_LONG_PTR_INDEX,
dwNewLong: i32,
) callconv(@import("std").os.windows.WINAPI) i32;
// TODO: this type is limited to platform 'windows5.0'
pub extern "USER32" fn GetClassWord(
hWnd: ?HWND,
nIndex: i32,
) callconv(@import("std").os.windows.WINAPI) u16;
// TODO: this type is limited to platform 'windows5.0'
pub extern "USER32" fn SetClassWord(
hWnd: ?HWND,
nIndex: i32,
wNewWord: u16,
) callconv(@import("std").os.windows.WINAPI) u16;
// TODO: this type is limited to platform 'windows5.0'
pub extern "USER32" fn GetClassLongA(
hWnd: ?HWND,
nIndex: GET_CLASS_LONG_INDEX,
) callconv(@import("std").os.windows.WINAPI) u32;
// TODO: this type is limited to platform 'windows5.0'
pub extern "USER32" fn GetClassLongW(
hWnd: ?HWND,
nIndex: GET_CLASS_LONG_INDEX,
) callconv(@import("std").os.windows.WINAPI) u32;
// TODO: this type is limited to platform 'windows5.0'
pub extern "USER32" fn SetClassLongA(
hWnd: ?HWND,
nIndex: GET_CLASS_LONG_INDEX,
dwNewLong: i32,
) callconv(@import("std").os.windows.WINAPI) u32;
// TODO: this type is limited to platform 'windows5.0'
pub extern "USER32" fn SetClassLongW(
hWnd: ?HWND,
nIndex: GET_CLASS_LONG_INDEX,
dwNewLong: i32,
) callconv(@import("std").os.windows.WINAPI) u32;
// TODO: this type is limited to platform 'windows5.0'
pub extern "USER32" fn GetProcessDefaultLayout(
pdwDefaultLayout: ?*u32,
) callconv(@import("std").os.windows.WINAPI) BOOL;
// TODO: this type is limited to platform 'windows5.0'
pub extern "USER32" fn SetProcessDefaultLayout(
dwDefaultLayout: u32,
) callconv(@import("std").os.windows.WINAPI) BOOL;
// TODO: this type is limited to platform 'windows5.0'
pub extern "USER32" fn GetDesktopWindow(
) callconv(@import("std").os.windows.WINAPI) ?HWND;
// TODO: this type is limited to platform 'windows5.0'
pub extern "USER32" fn GetParent(
hWnd: ?HWND,
) callconv(@import("std").os.windows.WINAPI) ?HWND;
// TODO: this type is limited to platform 'windows5.0'
pub extern "USER32" fn SetParent(
hWndChild: ?HWND,
hWndNewParent: ?HWND,
) callconv(@import("std").os.windows.WINAPI) ?HWND;
// TODO: this type is limited to platform 'windows5.0'
pub extern "USER32" fn EnumChildWindows(
hWndParent: ?HWND,
lpEnumFunc: ?WNDENUMPROC,
lParam: LPARAM,
) callconv(@import("std").os.windows.WINAPI) BOOL;
// TODO: this type is limited to platform 'windows5.0'
pub extern "USER32" fn FindWindowA(
lpClassName: ?[*:0]const u8,
lpWindowName: ?[*:0]const u8,
) callconv(@import("std").os.windows.WINAPI) ?HWND;
// TODO: this type is limited to platform 'windows5.0'
pub extern "USER32" fn FindWindowW(
lpClassName: ?[*:0]const u16,
lpWindowName: ?[*:0]const u16,
) callconv(@import("std").os.windows.WINAPI) ?HWND;
// TODO: this type is limited to platform 'windows5.0'
pub extern "USER32" fn FindWindowExA(
hWndParent: ?HWND,
hWndChildAfter: ?HWND,
lpszClass: ?[*:0]const u8,
lpszWindow: ?[*:0]const u8,
) callconv(@import("std").os.windows.WINAPI) ?HWND;
// TODO: this type is limited to platform 'windows5.0'
pub extern "USER32" fn FindWindowExW(
hWndParent: ?HWND,
hWndChildAfter: ?HWND,
lpszClass: ?[*:0]const u16,
lpszWindow: ?[*:0]const u16,
) callconv(@import("std").os.windows.WINAPI) ?HWND;
// TODO: this type is limited to platform 'windows5.0'
pub extern "USER32" fn GetShellWindow(
) callconv(@import("std").os.windows.WINAPI) ?HWND;
// TODO: this type is limited to platform 'windows5.0'
pub extern "USER32" fn RegisterShellHookWindow(
hwnd: ?HWND,
) callconv(@import("std").os.windows.WINAPI) BOOL;
// TODO: this type is limited to platform 'windows5.0'
pub extern "USER32" fn DeregisterShellHookWindow(
hwnd: ?HWND,
) callconv(@import("std").os.windows.WINAPI) BOOL;
// TODO: this type is limited to platform 'windows5.0'
pub extern "USER32" fn EnumWindows(
lpEnumFunc: ?WNDENUMPROC,
lParam: LPARAM,
) callconv(@import("std").os.windows.WINAPI) BOOL;
// TODO: this type is limited to platform 'windows5.0'
pub extern "USER32" fn EnumThreadWindows(
dwThreadId: u32,
lpfn: ?WNDENUMPROC,
lParam: LPARAM,
) callconv(@import("std").os.windows.WINAPI) BOOL;
// TODO: this type is limited to platform 'windows5.0'
pub extern "USER32" fn GetClassNameA(
hWnd: ?HWND,
lpClassName: [*:0]u8,
nMaxCount: i32,
) callconv(@import("std").os.windows.WINAPI) i32;
// TODO: this type is limited to platform 'windows5.0'
pub extern "USER32" fn GetClassNameW(
hWnd: ?HWND,
lpClassName: [*:0]u16,
nMaxCount: i32,
) callconv(@import("std").os.windows.WINAPI) i32;
// TODO: this type is limited to platform 'windows5.0'
pub extern "USER32" fn GetTopWindow(
hWnd: ?HWND,
) callconv(@import("std").os.windows.WINAPI) ?HWND;
// TODO: this type is limited to platform 'windows5.0'
pub extern "USER32" fn GetWindowThreadProcessId(
hWnd: ?HWND,
lpdwProcessId: ?*u32,
) callconv(@import("std").os.windows.WINAPI) u32;
// TODO: this type is limited to platform 'windows5.1.2600'
pub extern "USER32" fn IsGUIThread(
bConvert: BOOL,
) callconv(@import("std").os.windows.WINAPI) BOOL;
// TODO: this type is limited to platform 'windows5.0'
pub extern "USER32" fn GetLastActivePopup(
hWnd: ?HWND,
) callconv(@import("std").os.windows.WINAPI) ?HWND;
// TODO: this type is limited to platform 'windows5.0'
pub extern "USER32" fn GetWindow(
hWnd: ?HWND,
uCmd: GET_WINDOW_CMD,
) callconv(@import("std").os.windows.WINAPI) ?HWND;
pub extern "USER32" fn SetWindowsHookA(
nFilterType: i32,
pfnFilterProc: ?HOOKPROC,
) callconv(@import("std").os.windows.WINAPI) ?HHOOK;
pub extern "USER32" fn SetWindowsHookW(
nFilterType: i32,
pfnFilterProc: ?HOOKPROC,
) callconv(@import("std").os.windows.WINAPI) ?HHOOK;
pub extern "USER32" fn UnhookWindowsHook(
nCode: i32,
pfnFilterProc: ?HOOKPROC,
) callconv(@import("std").os.windows.WINAPI) BOOL;
// TODO: this type is limited to platform 'windows5.0'
pub extern "USER32" fn SetWindowsHookExA(
idHook: WINDOWS_HOOK_ID,
lpfn: ?HOOKPROC,
hmod: ?HINSTANCE,
dwThreadId: u32,
) callconv(@import("std").os.windows.WINAPI) ?HHOOK;
// TODO: this type is limited to platform 'windows5.0'
pub extern "USER32" fn SetWindowsHookExW(
idHook: WINDOWS_HOOK_ID,
lpfn: ?HOOKPROC,
hmod: ?HINSTANCE,
dwThreadId: u32,
) callconv(@import("std").os.windows.WINAPI) ?HHOOK;
// TODO: this type is limited to platform 'windows5.0'
pub extern "USER32" fn UnhookWindowsHookEx(
hhk: ?HHOOK,
) callconv(@import("std").os.windows.WINAPI) BOOL;
// TODO: this type is limited to platform 'windows5.0'
pub extern "USER32" fn CallNextHookEx(
hhk: ?HHOOK,
nCode: i32,
wParam: WPARAM,
lParam: LPARAM,
) callconv(@import("std").os.windows.WINAPI) LRESULT;
// TODO: this type is limited to platform 'windows5.0'
pub extern "USER32" fn CheckMenuRadioItem(
hmenu: ?HMENU,
first: u32,
last: u32,
check: u32,
flags: u32,
) callconv(@import("std").os.windows.WINAPI) BOOL;
// TODO: this type is limited to platform 'windows5.0'
pub extern "USER32" fn LoadCursorA(
hInstance: ?HINSTANCE,
lpCursorName: ?[*:0]const u8,
) callconv(@import("std").os.windows.WINAPI) ?HCURSOR;
// TODO: this type is limited to platform 'windows5.0'
pub extern "USER32" fn LoadCursorW(
hInstance: ?HINSTANCE,
lpCursorName: ?[*:0]const u16,
) callconv(@import("std").os.windows.WINAPI) ?HCURSOR;
// TODO: this type is limited to platform 'windows5.0'
pub extern "USER32" fn LoadCursorFromFileA(
lpFileName: ?[*:0]const u8,
) callconv(@import("std").os.windows.WINAPI) ?HCURSOR;
// TODO: this type is limited to platform 'windows5.0'
pub extern "USER32" fn LoadCursorFromFileW(
lpFileName: ?[*:0]const u16,
) callconv(@import("std").os.windows.WINAPI) ?HCURSOR;
// TODO: this type is limited to platform 'windows5.0'
pub extern "USER32" fn CreateCursor(
hInst: ?HINSTANCE,
xHotSpot: i32,
yHotSpot: i32,
nWidth: i32,
nHeight: i32,
pvANDPlane: ?*const c_void,
pvXORPlane: ?*const c_void,
) callconv(@import("std").os.windows.WINAPI) ?HCURSOR;
// TODO: this type is limited to platform 'windows5.0'
pub extern "USER32" fn DestroyCursor(
hCursor: ?HCURSOR,
) callconv(@import("std").os.windows.WINAPI) BOOL;
// TODO: this type is limited to platform 'windows5.0'
pub extern "USER32" fn SetSystemCursor(
hcur: ?HCURSOR,
id: SYSTEM_CURSOR_ID,
) callconv(@import("std").os.windows.WINAPI) BOOL;
// TODO: this type is limited to platform 'windows5.0'
pub extern "USER32" fn LoadIconA(
hInstance: ?HINSTANCE,
lpIconName: ?[*:0]const u8,
) callconv(@import("std").os.windows.WINAPI) ?HICON;
// TODO: this type is limited to platform 'windows5.0'
pub extern "USER32" fn LoadIconW(
hInstance: ?HINSTANCE,
lpIconName: ?[*:0]const u16,
) callconv(@import("std").os.windows.WINAPI) ?HICON;
// TODO: this type is limited to platform 'windows5.0'
pub extern "USER32" fn PrivateExtractIconsA(
szFileName: *[260]u8,
nIconIndex: i32,
cxIcon: i32,
cyIcon: i32,
phicon: ?[*]?HICON,
piconid: ?[*]u32,
nIcons: u32,
flags: u32,
) callconv(@import("std").os.windows.WINAPI) u32;
// TODO: this type is limited to platform 'windows5.0'
pub extern "USER32" fn PrivateExtractIconsW(
szFileName: *[260]u16,
nIconIndex: i32,
cxIcon: i32,
cyIcon: i32,
phicon: ?[*]?HICON,
piconid: ?[*]u32,
nIcons: u32,
flags: u32,
) callconv(@import("std").os.windows.WINAPI) u32;
// TODO: this type is limited to platform 'windows5.0'
pub extern "USER32" fn CreateIcon(
hInstance: ?HINSTANCE,
nWidth: i32,
nHeight: i32,
cPlanes: u8,
cBitsPixel: u8,
lpbANDbits: [*:0]const u8,
lpbXORbits: [*:0]const u8,
) callconv(@import("std").os.windows.WINAPI) ?HICON;
// TODO: this type is limited to platform 'windows5.0'
pub extern "USER32" fn DestroyIcon(
hIcon: ?HICON,
) callconv(@import("std").os.windows.WINAPI) BOOL;
// TODO: this type is limited to platform 'windows5.0'
pub extern "USER32" fn LookupIconIdFromDirectory(
presbits: ?*u8,
fIcon: BOOL,
) callconv(@import("std").os.windows.WINAPI) i32;
// TODO: this type is limited to platform 'windows5.0'
pub extern "USER32" fn LookupIconIdFromDirectoryEx(
presbits: ?*u8,
fIcon: BOOL,
cxDesired: i32,
cyDesired: i32,
Flags: IMAGE_FLAGS,
) callconv(@import("std").os.windows.WINAPI) i32;
// TODO: this type is limited to platform 'windows5.0'
pub extern "USER32" fn CreateIconFromResource(
// TODO: what to do with BytesParamIndex 1?
presbits: ?*u8,
dwResSize: u32,
fIcon: BOOL,
dwVer: u32,
) callconv(@import("std").os.windows.WINAPI) ?HICON;
// TODO: this type is limited to platform 'windows5.0'
pub extern "USER32" fn CreateIconFromResourceEx(
// TODO: what to do with BytesParamIndex 1?
presbits: ?*u8,
dwResSize: u32,
fIcon: BOOL,
dwVer: u32,
cxDesired: i32,
cyDesired: i32,
Flags: IMAGE_FLAGS,
) callconv(@import("std").os.windows.WINAPI) ?HICON;
// TODO: this type is limited to platform 'windows5.0'
pub extern "USER32" fn LoadImageA(
hInst: ?HINSTANCE,
name: ?[*:0]const u8,
type: GDI_IMAGE_TYPE,
cx: i32,
cy: i32,
fuLoad: IMAGE_FLAGS,
) callconv(@import("std").os.windows.WINAPI) ?HANDLE;
// TODO: this type is limited to platform 'windows5.0'
pub extern "USER32" fn LoadImageW(
hInst: ?HINSTANCE,
name: ?[*:0]const u16,
type: GDI_IMAGE_TYPE,
cx: i32,
cy: i32,
fuLoad: IMAGE_FLAGS,
) callconv(@import("std").os.windows.WINAPI) ?HANDLE;
// TODO: this type is limited to platform 'windows5.0'
pub extern "USER32" fn CopyImage(
h: ?HANDLE,
type: GDI_IMAGE_TYPE,
cx: i32,
cy: i32,
flags: IMAGE_FLAGS,
) callconv(@import("std").os.windows.WINAPI) ?HANDLE;
// TODO: this type is limited to platform 'windows5.0'
pub extern "USER32" fn DrawIconEx(
hdc: ?HDC,
xLeft: i32,
yTop: i32,
hIcon: ?HICON,
cxWidth: i32,
cyWidth: i32,
istepIfAniCur: u32,
hbrFlickerFreeDraw: ?HBRUSH,
diFlags: DI_FLAGS,
) callconv(@import("std").os.windows.WINAPI) BOOL;
// TODO: this type is limited to platform 'windows5.0'
pub extern "USER32" fn CreateIconIndirect(
piconinfo: ?*ICONINFO,
) callconv(@import("std").os.windows.WINAPI) ?HICON;
// TODO: this type is limited to platform 'windows5.0'
pub extern "USER32" fn CopyIcon(
hIcon: ?HICON,
) callconv(@import("std").os.windows.WINAPI) ?HICON;
// TODO: this type is limited to platform 'windows5.0'
pub extern "USER32" fn GetIconInfo(
hIcon: ?HICON,
piconinfo: ?*ICONINFO,
) callconv(@import("std").os.windows.WINAPI) BOOL;
// TODO: this type is limited to platform 'windows6.0.6000'
pub extern "USER32" fn GetIconInfoExA(
hicon: ?HICON,
piconinfo: ?*ICONINFOEXA,
) callconv(@import("std").os.windows.WINAPI) BOOL;
// TODO: this type is limited to platform 'windows6.0.6000'
pub extern "USER32" fn GetIconInfoExW(
hicon: ?HICON,
piconinfo: ?*ICONINFOEXW,
) callconv(@import("std").os.windows.WINAPI) BOOL;
// TODO: this type is limited to platform 'windows5.0'
pub extern "USER32" fn IsDialogMessageA(
hDlg: ?HWND,
lpMsg: ?*MSG,
) callconv(@import("std").os.windows.WINAPI) BOOL;
// TODO: this type is limited to platform 'windows5.0'
pub extern "USER32" fn IsDialogMessageW(
hDlg: ?HWND,
lpMsg: ?*MSG,
) callconv(@import("std").os.windows.WINAPI) BOOL;
// TODO: this type is limited to platform 'windows5.0'
pub extern "USER32" fn MapDialogRect(
hDlg: ?HWND,
lpRect: ?*RECT,
) callconv(@import("std").os.windows.WINAPI) BOOL;
// TODO: this type is limited to platform 'windows5.0'
pub extern "USER32" fn DefFrameProcA(
hWnd: ?HWND,
hWndMDIClient: ?HWND,
uMsg: u32,
wParam: WPARAM,
lParam: LPARAM,
) callconv(@import("std").os.windows.WINAPI) LRESULT;
// TODO: this type is limited to platform 'windows5.0'
pub extern "USER32" fn DefFrameProcW(
hWnd: ?HWND,
hWndMDIClient: ?HWND,
uMsg: u32,
wParam: WPARAM,
lParam: LPARAM,
) callconv(@import("std").os.windows.WINAPI) LRESULT;
// TODO: this type is limited to platform 'windows5.0'
pub extern "USER32" fn DefMDIChildProcA(
hWnd: ?HWND,
uMsg: u32,
wParam: WPARAM,
lParam: LPARAM,
) callconv(@import("std").os.windows.WINAPI) LRESULT;
// TODO: this type is limited to platform 'windows5.0'
pub extern "USER32" fn DefMDIChildProcW(
hWnd: ?HWND,
uMsg: u32,
wParam: WPARAM,
lParam: LPARAM,
) callconv(@import("std").os.windows.WINAPI) LRESULT;
// TODO: this type is limited to platform 'windows5.0'
pub extern "USER32" fn TranslateMDISysAccel(
hWndClient: ?HWND,
lpMsg: ?*MSG,
) callconv(@import("std").os.windows.WINAPI) BOOL;
// TODO: this type is limited to platform 'windows5.0'
pub extern "USER32" fn ArrangeIconicWindows(
hWnd: ?HWND,
) callconv(@import("std").os.windows.WINAPI) u32;
// TODO: this type is limited to platform 'windows5.0'
pub extern "USER32" fn CreateMDIWindowA(
lpClassName: ?[*:0]const u8,
lpWindowName: ?[*:0]const u8,
dwStyle: WINDOW_STYLE,
X: i32,
Y: i32,
nWidth: i32,
nHeight: i32,
hWndParent: ?HWND,
hInstance: ?HINSTANCE,
lParam: LPARAM,
) callconv(@import("std").os.windows.WINAPI) ?HWND;
// TODO: this type is limited to platform 'windows5.0'
pub extern "USER32" fn CreateMDIWindowW(
lpClassName: ?[*:0]const u16,
lpWindowName: ?[*:0]const u16,
dwStyle: WINDOW_STYLE,
X: i32,
Y: i32,
nWidth: i32,
nHeight: i32,
hWndParent: ?HWND,
hInstance: ?HINSTANCE,
lParam: LPARAM,
) callconv(@import("std").os.windows.WINAPI) ?HWND;
// TODO: this type is limited to platform 'windows5.0'
pub extern "USER32" fn TileWindows(
hwndParent: ?HWND,
wHow: TILE_WINDOWS_HOW,
lpRect: ?*const RECT,
cKids: u32,
lpKids: ?[*]const ?HWND,
) callconv(@import("std").os.windows.WINAPI) u16;
// TODO: this type is limited to platform 'windows5.0'
pub extern "USER32" fn CascadeWindows(
hwndParent: ?HWND,
wHow: CASCADE_WINDOWS_HOW,
lpRect: ?*const RECT,
cKids: u32,
lpKids: ?[*]const ?HWND,
) callconv(@import("std").os.windows.WINAPI) u16;
// TODO: this type is limited to platform 'windows5.0'
pub extern "USER32" fn SystemParametersInfoA(
uiAction: SYSTEM_PARAMETERS_INFO_ACTION,
uiParam: u32,
pvParam: ?*c_void,
fWinIni: SYSTEM_PARAMETERS_INFO_UPDATE_FLAGS,
) callconv(@import("std").os.windows.WINAPI) BOOL;
// TODO: this type is limited to platform 'windows5.0'
pub extern "USER32" fn SystemParametersInfoW(
uiAction: SYSTEM_PARAMETERS_INFO_ACTION,
uiParam: u32,
pvParam: ?*c_void,
fWinIni: SYSTEM_PARAMETERS_INFO_UPDATE_FLAGS,
) callconv(@import("std").os.windows.WINAPI) BOOL;
// TODO: this type is limited to platform 'windows6.0.6000'
pub extern "USER32" fn SoundSentry(
) callconv(@import("std").os.windows.WINAPI) BOOL;
pub extern "USER32" fn SetDebugErrorLevel(
dwLevel: u32,
) callconv(@import("std").os.windows.WINAPI) void;
// TODO: this type is limited to platform 'windows5.0'
pub extern "USER32" fn InternalGetWindowText(
hWnd: ?HWND,
pString: [*:0]u16,
cchMaxCount: i32,
) callconv(@import("std").os.windows.WINAPI) i32;
pub extern "USER32" fn CancelShutdown(
) callconv(@import("std").os.windows.WINAPI) BOOL;
// TODO: this type is limited to platform 'windows5.0'
pub extern "USER32" fn GetGUIThreadInfo(
idThread: u32,
pgui: ?*GUITHREADINFO,
) callconv(@import("std").os.windows.WINAPI) BOOL;
// TODO: this type is limited to platform 'windows6.0.6000'
pub extern "USER32" fn SetProcessDPIAware(
) callconv(@import("std").os.windows.WINAPI) BOOL;
// TODO: this type is limited to platform 'windows6.0.6000'
pub extern "USER32" fn IsProcessDPIAware(
) callconv(@import("std").os.windows.WINAPI) BOOL;
pub extern "USER32" fn InheritWindowMonitor(
hwnd: ?HWND,
hwndInherit: ?HWND,
) callconv(@import("std").os.windows.WINAPI) BOOL;
pub extern "USER32" fn GetDpiAwarenessContextForProcess(
hProcess: ?HANDLE,
) callconv(@import("std").os.windows.WINAPI) DPI_AWARENESS_CONTEXT;
// TODO: this type is limited to platform 'windows5.0'
pub extern "USER32" fn GetWindowModuleFileNameA(
hwnd: ?HWND,
pszFileName: [*:0]u8,
cchFileNameMax: u32,
) callconv(@import("std").os.windows.WINAPI) u32;
// TODO: this type is limited to platform 'windows5.0'
pub extern "USER32" fn GetWindowModuleFileNameW(
hwnd: ?HWND,
pszFileName: [*:0]u16,
cchFileNameMax: u32,
) callconv(@import("std").os.windows.WINAPI) u32;
// TODO: this type is limited to platform 'windows5.0'
pub extern "USER32" fn GetCursorInfo(
pci: ?*CURSORINFO,
) callconv(@import("std").os.windows.WINAPI) BOOL;
// TODO: this type is limited to platform 'windows5.0'
pub extern "USER32" fn GetWindowInfo(
hwnd: ?HWND,
pwi: ?*WINDOWINFO,
) callconv(@import("std").os.windows.WINAPI) BOOL;
// TODO: this type is limited to platform 'windows5.0'
pub extern "USER32" fn GetTitleBarInfo(
hwnd: ?HWND,
pti: ?*TITLEBARINFO,
) callconv(@import("std").os.windows.WINAPI) BOOL;
// TODO: this type is limited to platform 'windows5.0'
pub extern "USER32" fn GetMenuBarInfo(
hwnd: ?HWND,
idObject: OBJECT_IDENTIFIER,
idItem: i32,
pmbi: ?*MENUBARINFO,
) callconv(@import("std").os.windows.WINAPI) BOOL;
// TODO: this type is limited to platform 'windows5.0'
pub extern "USER32" fn GetAncestor(
hwnd: ?HWND,
gaFlags: GET_ANCESTOR_FLAGS,
) callconv(@import("std").os.windows.WINAPI) ?HWND;
// TODO: this type is limited to platform 'windows5.0'
pub extern "USER32" fn RealChildWindowFromPoint(
hwndParent: ?HWND,
ptParentClientCoords: POINT,
) callconv(@import("std").os.windows.WINAPI) ?HWND;
pub extern "USER32" fn RealGetWindowClassA(
hwnd: ?HWND,
ptszClassName: [*:0]u8,
cchClassNameMax: u32,
) callconv(@import("std").os.windows.WINAPI) u32;
// TODO: this type is limited to platform 'windows5.0'
pub extern "USER32" fn RealGetWindowClassW(
hwnd: ?HWND,
ptszClassName: [*:0]u16,
cchClassNameMax: u32,
) callconv(@import("std").os.windows.WINAPI) u32;
// TODO: this type is limited to platform 'windows5.0'
pub extern "USER32" fn GetAltTabInfoA(
hwnd: ?HWND,
iItem: i32,
pati: ?*ALTTABINFO,
pszItemText: ?[*:0]u8,
cchItemText: u32,
) callconv(@import("std").os.windows.WINAPI) BOOL;
// TODO: this type is limited to platform 'windows5.0'
pub extern "USER32" fn GetAltTabInfoW(
hwnd: ?HWND,
iItem: i32,
pati: ?*ALTTABINFO,
pszItemText: ?[*:0]u16,
cchItemText: u32,
) callconv(@import("std").os.windows.WINAPI) BOOL;
// TODO: this type is limited to platform 'windows6.0.6000'
pub extern "USER32" fn ChangeWindowMessageFilter(
message: u32,
dwFlag: CHANGE_WINDOW_MESSAGE_FILTER_FLAGS,
) callconv(@import("std").os.windows.WINAPI) BOOL;
// TODO: this type is limited to platform 'windows6.1'
pub extern "USER32" fn ChangeWindowMessageFilterEx(
hwnd: ?HWND,
message: u32,
action: WINDOW_MESSAGE_FILTER_ACTION,
pChangeFilterStruct: ?*CHANGEFILTERSTRUCT,
) callconv(@import("std").os.windows.WINAPI) BOOL;
// TODO: this type is limited to platform 'windows10.0.10240'
pub extern "MrmSupport" fn CreateResourceIndexer(
projectRoot: ?[*:0]const u16,
extensionDllPath: ?[*:0]const u16,
ppResourceIndexer: ?*?*c_void,
) callconv(@import("std").os.windows.WINAPI) HRESULT;
// TODO: this type is limited to platform 'windows10.0.10240'
pub extern "MrmSupport" fn DestroyResourceIndexer(
resourceIndexer: ?*c_void,
) callconv(@import("std").os.windows.WINAPI) void;
// TODO: this type is limited to platform 'windows10.0.10240'
pub extern "MrmSupport" fn IndexFilePath(
resourceIndexer: ?*c_void,
filePath: ?[*:0]const u16,
ppResourceUri: ?*?PWSTR,
pQualifierCount: ?*u32,
ppQualifiers: [*]?*IndexedResourceQualifier,
) callconv(@import("std").os.windows.WINAPI) HRESULT;
// TODO: this type is limited to platform 'windows10.0.10240'
pub extern "MrmSupport" fn DestroyIndexedResults(
resourceUri: ?PWSTR,
qualifierCount: u32,
qualifiers: ?[*]IndexedResourceQualifier,
) callconv(@import("std").os.windows.WINAPI) void;
pub extern "MrmSupport" fn MrmCreateResourceIndexer(
packageFamilyName: ?[*:0]const u16,
projectRoot: ?[*:0]const u16,
platformVersion: MrmPlatformVersion,
defaultQualifiers: ?[*:0]const u16,
indexer: ?*MrmResourceIndexerHandle,
) callconv(@import("std").os.windows.WINAPI) HRESULT;
pub extern "MrmSupport" fn MrmCreateResourceIndexerFromPreviousSchemaFile(
projectRoot: ?[*:0]const u16,
platformVersion: MrmPlatformVersion,
defaultQualifiers: ?[*:0]const u16,
schemaFile: ?[*:0]const u16,
indexer: ?*MrmResourceIndexerHandle,
) callconv(@import("std").os.windows.WINAPI) HRESULT;
pub extern "MrmSupport" fn MrmCreateResourceIndexerFromPreviousPriFile(
projectRoot: ?[*:0]const u16,
platformVersion: MrmPlatformVersion,
defaultQualifiers: ?[*:0]const u16,
priFile: ?[*:0]const u16,
indexer: ?*MrmResourceIndexerHandle,
) callconv(@import("std").os.windows.WINAPI) HRESULT;
pub extern "MrmSupport" fn MrmCreateResourceIndexerFromPreviousSchemaData(
projectRoot: ?[*:0]const u16,
platformVersion: MrmPlatformVersion,
defaultQualifiers: ?[*:0]const u16,
// TODO: what to do with BytesParamIndex 4?
schemaXmlData: ?*u8,
schemaXmlSize: u32,
indexer: ?*MrmResourceIndexerHandle,
) callconv(@import("std").os.windows.WINAPI) HRESULT;
pub extern "MrmSupport" fn MrmCreateResourceIndexerFromPreviousPriData(
projectRoot: ?[*:0]const u16,
platformVersion: MrmPlatformVersion,
defaultQualifiers: ?[*:0]const u16,
// TODO: what to do with BytesParamIndex 4?
priData: ?*u8,
priSize: u32,
indexer: ?*MrmResourceIndexerHandle,
) callconv(@import("std").os.windows.WINAPI) HRESULT;
pub extern "MrmSupport" fn MrmIndexString(
indexer: MrmResourceIndexerHandle,
resourceUri: ?[*:0]const u16,
resourceString: ?[*:0]const u16,
qualifiers: ?[*:0]const u16,
) callconv(@import("std").os.windows.WINAPI) HRESULT;
pub extern "MrmSupport" fn MrmIndexEmbeddedData(
indexer: MrmResourceIndexerHandle,
resourceUri: ?[*:0]const u16,
// TODO: what to do with BytesParamIndex 3?
embeddedData: ?*const u8,
embeddedDataSize: u32,
qualifiers: ?[*:0]const u16,
) callconv(@import("std").os.windows.WINAPI) HRESULT;
pub extern "MrmSupport" fn MrmIndexFile(
indexer: MrmResourceIndexerHandle,
resourceUri: ?[*:0]const u16,
filePath: ?[*:0]const u16,
qualifiers: ?[*:0]const u16,
) callconv(@import("std").os.windows.WINAPI) HRESULT;
pub extern "MrmSupport" fn MrmIndexFileAutoQualifiers(
indexer: MrmResourceIndexerHandle,
filePath: ?[*:0]const u16,
) callconv(@import("std").os.windows.WINAPI) HRESULT;
pub extern "MrmSupport" fn MrmIndexResourceContainerAutoQualifiers(
indexer: MrmResourceIndexerHandle,
containerPath: ?[*:0]const u16,
) callconv(@import("std").os.windows.WINAPI) HRESULT;
pub extern "MrmSupport" fn MrmCreateResourceFile(
indexer: MrmResourceIndexerHandle,
packagingMode: MrmPackagingMode,
packagingOptions: MrmPackagingOptions,
outputDirectory: ?[*:0]const u16,
) callconv(@import("std").os.windows.WINAPI) HRESULT;
pub extern "MrmSupport" fn MrmCreateResourceFileInMemory(
indexer: MrmResourceIndexerHandle,
packagingMode: MrmPackagingMode,
packagingOptions: MrmPackagingOptions,
outputPriData: ?*?*u8,
outputPriSize: ?*u32,
) callconv(@import("std").os.windows.WINAPI) HRESULT;
pub extern "MrmSupport" fn MrmPeekResourceIndexerMessages(
handle: MrmResourceIndexerHandle,
messages: [*]?*MrmResourceIndexerMessage,
numMsgs: ?*u32,
) callconv(@import("std").os.windows.WINAPI) HRESULT;
pub extern "MrmSupport" fn MrmDestroyIndexerAndMessages(
indexer: MrmResourceIndexerHandle,
) callconv(@import("std").os.windows.WINAPI) HRESULT;
pub extern "MrmSupport" fn MrmFreeMemory(
data: ?*u8,
) callconv(@import("std").os.windows.WINAPI) HRESULT;
pub extern "MrmSupport" fn MrmDumpPriFile(
indexFileName: ?[*:0]const u16,
schemaPriFile: ?[*:0]const u16,
dumpType: MrmDumpType,
outputXmlFile: ?[*:0]const u16,
) callconv(@import("std").os.windows.WINAPI) HRESULT;
pub extern "MrmSupport" fn MrmDumpPriFileInMemory(
indexFileName: ?[*:0]const u16,
schemaPriFile: ?[*:0]const u16,
dumpType: MrmDumpType,
outputXmlData: ?*?*u8,
outputXmlSize: ?*u32,
) callconv(@import("std").os.windows.WINAPI) HRESULT;
pub extern "MrmSupport" fn MrmDumpPriDataInMemory(
// TODO: what to do with BytesParamIndex 1?
inputPriData: ?*u8,
inputPriSize: u32,
// TODO: what to do with BytesParamIndex 3?
schemaPriData: ?*u8,
schemaPriSize: u32,
dumpType: MrmDumpType,
outputXmlData: ?*?*u8,
outputXmlSize: ?*u32,
) callconv(@import("std").os.windows.WINAPI) HRESULT;
pub extern "MrmSupport" fn MrmCreateConfig(
platformVersion: MrmPlatformVersion,
defaultQualifiers: ?[*:0]const u16,
outputXmlFile: ?[*:0]const u16,
) callconv(@import("std").os.windows.WINAPI) HRESULT;
pub extern "MrmSupport" fn MrmCreateConfigInMemory(
platformVersion: MrmPlatformVersion,
defaultQualifiers: ?[*:0]const u16,
outputXmlData: ?*?*u8,
outputXmlSize: ?*u32,
) callconv(@import("std").os.windows.WINAPI) HRESULT;
//--------------------------------------------------------------------------------
// Section: Unicode Aliases (132)
//--------------------------------------------------------------------------------
const thismodule = @This();
pub usingnamespace switch (@import("../zig.zig").unicode_mode) {
.ansi => struct {
pub const WINSTAENUMPROC = thismodule.WINSTAENUMPROCA;
pub const DESKTOPENUMPROC = thismodule.DESKTOPENUMPROCA;
pub const OPENFILENAME_NT4 = thismodule.OPENFILENAME_NT4A;
pub const OPENFILENAME = thismodule.OPENFILENAMEA;
pub const OFNOTIFY = thismodule.OFNOTIFYA;
pub const OFNOTIFYEX = thismodule.OFNOTIFYEXA;
pub const CHOOSECOLOR = thismodule.CHOOSECOLORA;
pub const FINDREPLACE = thismodule.FINDREPLACEA;
pub const CHOOSEFONT = thismodule.CHOOSEFONTA;
pub const PRINTDLG = thismodule.PRINTDLGA;
pub const PRINTDLGEX = thismodule.PRINTDLGEXA;
pub const PAGESETUPDLG = thismodule.PAGESETUPDLGA;
pub const PROPENUMPROC = thismodule.PROPENUMPROCA;
pub const PROPENUMPROCEX = thismodule.PROPENUMPROCEXA;
pub const NAMEENUMPROC = thismodule.NAMEENUMPROCA;
pub const CBT_CREATEWND = thismodule.CBT_CREATEWNDA;
pub const WNDCLASSEX = thismodule.WNDCLASSEXA;
pub const WNDCLASS = thismodule.WNDCLASSA;
pub const CREATESTRUCT = thismodule.CREATESTRUCTA;
pub const MENUITEMINFO = thismodule.MENUITEMINFOA;
pub const MSGBOXPARAMS = thismodule.MSGBOXPARAMSA;
pub const ICONINFOEX = thismodule.ICONINFOEXA;
pub const MDICREATESTRUCT = thismodule.MDICREATESTRUCTA;
pub const NONCLIENTMETRICS = thismodule.NONCLIENTMETRICSA;
pub const ICONMETRICS = thismodule.ICONMETRICSA;
pub const GetWindowLongPtr = thismodule.GetWindowLongPtrA;
pub const SetWindowLongPtr = thismodule.SetWindowLongPtrA;
pub const GetClassLongPtr = thismodule.GetClassLongPtrA;
pub const SetClassLongPtr = thismodule.SetClassLongPtrA;
pub const GetOpenFileName = thismodule.GetOpenFileNameA;
pub const GetSaveFileName = thismodule.GetSaveFileNameA;
pub const GetFileTitle = thismodule.GetFileTitleA;
pub const ChooseColor = thismodule.ChooseColorA;
pub const FindText = thismodule.FindTextA;
pub const ReplaceText = thismodule.ReplaceTextA;
pub const ChooseFont = thismodule.ChooseFontA;
pub const PrintDlg = thismodule.PrintDlgA;
pub const PrintDlgEx = thismodule.PrintDlgExA;
pub const PageSetupDlg = thismodule.PageSetupDlgA;
pub const LoadString = thismodule.LoadStringA;
pub const wvsprintf = thismodule.wvsprintfA;
pub const wsprintf = thismodule.wsprintfA;
pub const RegisterWindowMessage = thismodule.RegisterWindowMessageA;
pub const GetMessage = thismodule.GetMessageA;
pub const DispatchMessage = thismodule.DispatchMessageA;
pub const PeekMessage = thismodule.PeekMessageA;
pub const SendMessage = thismodule.SendMessageA;
pub const SendMessageTimeout = thismodule.SendMessageTimeoutA;
pub const SendNotifyMessage = thismodule.SendNotifyMessageA;
pub const SendMessageCallback = thismodule.SendMessageCallbackA;
pub const BroadcastSystemMessageEx = thismodule.BroadcastSystemMessageExA;
pub const BroadcastSystemMessage = thismodule.BroadcastSystemMessageA;
pub const PostMessage = thismodule.PostMessageA;
pub const PostThreadMessage = thismodule.PostThreadMessageA;
pub const DefWindowProc = thismodule.DefWindowProcA;
pub const CallWindowProc = thismodule.CallWindowProcA;
pub const RegisterClass = thismodule.RegisterClassA;
pub const UnregisterClass = thismodule.UnregisterClassA;
pub const GetClassInfo = thismodule.GetClassInfoA;
pub const RegisterClassEx = thismodule.RegisterClassExA;
pub const GetClassInfoEx = thismodule.GetClassInfoExA;
pub const CreateWindowEx = thismodule.CreateWindowExA;
pub const CreateDialogParam = thismodule.CreateDialogParamA;
pub const CreateDialogIndirectParam = thismodule.CreateDialogIndirectParamA;
pub const DialogBoxParam = thismodule.DialogBoxParamA;
pub const DialogBoxIndirectParam = thismodule.DialogBoxIndirectParamA;
pub const SetDlgItemText = thismodule.SetDlgItemTextA;
pub const GetDlgItemText = thismodule.GetDlgItemTextA;
pub const SendDlgItemMessage = thismodule.SendDlgItemMessageA;
pub const DefDlgProc = thismodule.DefDlgProcA;
pub const CallMsgFilter = thismodule.CallMsgFilterA;
pub const CharToOem = thismodule.CharToOemA;
pub const OemToChar = thismodule.OemToCharA;
pub const CharToOemBuff = thismodule.CharToOemBuffA;
pub const OemToCharBuff = thismodule.OemToCharBuffA;
pub const CharUpper = thismodule.CharUpperA;
pub const CharUpperBuff = thismodule.CharUpperBuffA;
pub const CharLower = thismodule.CharLowerA;
pub const CharLowerBuff = thismodule.CharLowerBuffA;
pub const CharNext = thismodule.CharNextA;
pub const CharPrev = thismodule.CharPrevA;
pub const IsCharAlpha = thismodule.IsCharAlphaA;
pub const IsCharAlphaNumeric = thismodule.IsCharAlphaNumericA;
pub const IsCharUpper = thismodule.IsCharUpperA;
pub const LoadAccelerators = thismodule.LoadAcceleratorsA;
pub const CreateAcceleratorTable = thismodule.CreateAcceleratorTableA;
pub const CopyAcceleratorTable = thismodule.CopyAcceleratorTableA;
pub const TranslateAccelerator = thismodule.TranslateAcceleratorA;
pub const LoadMenu = thismodule.LoadMenuA;
pub const LoadMenuIndirect = thismodule.LoadMenuIndirectA;
pub const ChangeMenu = thismodule.ChangeMenuA;
pub const GetMenuString = thismodule.GetMenuStringA;
pub const InsertMenu = thismodule.InsertMenuA;
pub const AppendMenu = thismodule.AppendMenuA;
pub const ModifyMenu = thismodule.ModifyMenuA;
pub const InsertMenuItem = thismodule.InsertMenuItemA;
pub const GetMenuItemInfo = thismodule.GetMenuItemInfoA;
pub const SetMenuItemInfo = thismodule.SetMenuItemInfoA;
pub const SetProp = thismodule.SetPropA;
pub const GetProp = thismodule.GetPropA;
pub const RemoveProp = thismodule.RemovePropA;
pub const EnumPropsEx = thismodule.EnumPropsExA;
pub const EnumProps = thismodule.EnumPropsA;
pub const SetWindowText = thismodule.SetWindowTextA;
pub const GetWindowText = thismodule.GetWindowTextA;
pub const GetWindowTextLength = thismodule.GetWindowTextLengthA;
pub const MessageBox = thismodule.MessageBoxA;
pub const MessageBoxEx = thismodule.MessageBoxExA;
pub const MessageBoxIndirect = thismodule.MessageBoxIndirectA;
pub const GetWindowLong = thismodule.GetWindowLongA;
pub const SetWindowLong = thismodule.SetWindowLongA;
pub const GetClassLong = thismodule.GetClassLongA;
pub const SetClassLong = thismodule.SetClassLongA;
pub const FindWindow = thismodule.FindWindowA;
pub const FindWindowEx = thismodule.FindWindowExA;
pub const GetClassName = thismodule.GetClassNameA;
pub const SetWindowsHook = thismodule.SetWindowsHookA;
pub const SetWindowsHookEx = thismodule.SetWindowsHookExA;
pub const LoadCursor = thismodule.LoadCursorA;
pub const LoadCursorFromFile = thismodule.LoadCursorFromFileA;
pub const LoadIcon = thismodule.LoadIconA;
pub const PrivateExtractIcons = thismodule.PrivateExtractIconsA;
pub const LoadImage = thismodule.LoadImageA;
pub const GetIconInfoEx = thismodule.GetIconInfoExA;
pub const IsDialogMessage = thismodule.IsDialogMessageA;
pub const DefFrameProc = thismodule.DefFrameProcA;
pub const DefMDIChildProc = thismodule.DefMDIChildProcA;
pub const CreateMDIWindow = thismodule.CreateMDIWindowA;
pub const SystemParametersInfo = thismodule.SystemParametersInfoA;
pub const GetWindowModuleFileName = thismodule.GetWindowModuleFileNameA;
pub const RealGetWindowClass = thismodule.RealGetWindowClassA;
pub const GetAltTabInfo = thismodule.GetAltTabInfoA;
},
.wide => struct {
pub const WINSTAENUMPROC = thismodule.WINSTAENUMPROCW;
pub const DESKTOPENUMPROC = thismodule.DESKTOPENUMPROCW;
pub const OPENFILENAME_NT4 = thismodule.OPENFILENAME_NT4W;
pub const OPENFILENAME = thismodule.OPENFILENAMEW;
pub const OFNOTIFY = thismodule.OFNOTIFYW;
pub const OFNOTIFYEX = thismodule.OFNOTIFYEXW;
pub const CHOOSECOLOR = thismodule.CHOOSECOLORW;
pub const FINDREPLACE = thismodule.FINDREPLACEW;
pub const CHOOSEFONT = thismodule.CHOOSEFONTW;
pub const PRINTDLG = thismodule.PRINTDLGW;
pub const PRINTDLGEX = thismodule.PRINTDLGEXW;
pub const PAGESETUPDLG = thismodule.PAGESETUPDLGW;
pub const PROPENUMPROC = thismodule.PROPENUMPROCW;
pub const PROPENUMPROCEX = thismodule.PROPENUMPROCEXW;
pub const NAMEENUMPROC = thismodule.NAMEENUMPROCW;
pub const CBT_CREATEWND = thismodule.CBT_CREATEWNDW;
pub const WNDCLASSEX = thismodule.WNDCLASSEXW;
pub const WNDCLASS = thismodule.WNDCLASSW;
pub const CREATESTRUCT = thismodule.CREATESTRUCTW;
pub const MENUITEMINFO = thismodule.MENUITEMINFOW;
pub const MSGBOXPARAMS = thismodule.MSGBOXPARAMSW;
pub const ICONINFOEX = thismodule.ICONINFOEXW;
pub const MDICREATESTRUCT = thismodule.MDICREATESTRUCTW;
pub const NONCLIENTMETRICS = thismodule.NONCLIENTMETRICSW;
pub const ICONMETRICS = thismodule.ICONMETRICSW;
pub const GetWindowLongPtr = thismodule.GetWindowLongPtrW;
pub const SetWindowLongPtr = thismodule.SetWindowLongPtrW;
pub const GetClassLongPtr = thismodule.GetClassLongPtrW;
pub const SetClassLongPtr = thismodule.SetClassLongPtrW;
pub const GetOpenFileName = thismodule.GetOpenFileNameW;
pub const GetSaveFileName = thismodule.GetSaveFileNameW;
pub const GetFileTitle = thismodule.GetFileTitleW;
pub const ChooseColor = thismodule.ChooseColorW;
pub const FindText = thismodule.FindTextW;
pub const ReplaceText = thismodule.ReplaceTextW;
pub const ChooseFont = thismodule.ChooseFontW;
pub const PrintDlg = thismodule.PrintDlgW;
pub const PrintDlgEx = thismodule.PrintDlgExW;
pub const PageSetupDlg = thismodule.PageSetupDlgW;
pub const LoadString = thismodule.LoadStringW;
pub const wvsprintf = thismodule.wvsprintfW;
pub const wsprintf = thismodule.wsprintfW;
pub const RegisterWindowMessage = thismodule.RegisterWindowMessageW;
pub const GetMessage = thismodule.GetMessageW;
pub const DispatchMessage = thismodule.DispatchMessageW;
pub const PeekMessage = thismodule.PeekMessageW;
pub const SendMessage = thismodule.SendMessageW;
pub const SendMessageTimeout = thismodule.SendMessageTimeoutW;
pub const SendNotifyMessage = thismodule.SendNotifyMessageW;
pub const SendMessageCallback = thismodule.SendMessageCallbackW;
pub const BroadcastSystemMessageEx = thismodule.BroadcastSystemMessageExW;
pub const BroadcastSystemMessage = thismodule.BroadcastSystemMessageW;
pub const PostMessage = thismodule.PostMessageW;
pub const PostThreadMessage = thismodule.PostThreadMessageW;
pub const DefWindowProc = thismodule.DefWindowProcW;
pub const CallWindowProc = thismodule.CallWindowProcW;
pub const RegisterClass = thismodule.RegisterClassW;
pub const UnregisterClass = thismodule.UnregisterClassW;
pub const GetClassInfo = thismodule.GetClassInfoW;
pub const RegisterClassEx = thismodule.RegisterClassExW;
pub const GetClassInfoEx = thismodule.GetClassInfoExW;
pub const CreateWindowEx = thismodule.CreateWindowExW;
pub const CreateDialogParam = thismodule.CreateDialogParamW;
pub const CreateDialogIndirectParam = thismodule.CreateDialogIndirectParamW;
pub const DialogBoxParam = thismodule.DialogBoxParamW;
pub const DialogBoxIndirectParam = thismodule.DialogBoxIndirectParamW;
pub const SetDlgItemText = thismodule.SetDlgItemTextW;
pub const GetDlgItemText = thismodule.GetDlgItemTextW;
pub const SendDlgItemMessage = thismodule.SendDlgItemMessageW;
pub const DefDlgProc = thismodule.DefDlgProcW;
pub const CallMsgFilter = thismodule.CallMsgFilterW;
pub const CharToOem = thismodule.CharToOemW;
pub const OemToChar = thismodule.OemToCharW;
pub const CharToOemBuff = thismodule.CharToOemBuffW;
pub const OemToCharBuff = thismodule.OemToCharBuffW;
pub const CharUpper = thismodule.CharUpperW;
pub const CharUpperBuff = thismodule.CharUpperBuffW;
pub const CharLower = thismodule.CharLowerW;
pub const CharLowerBuff = thismodule.CharLowerBuffW;
pub const CharNext = thismodule.CharNextW;
pub const CharPrev = thismodule.CharPrevW;
pub const IsCharAlpha = thismodule.IsCharAlphaW;
pub const IsCharAlphaNumeric = thismodule.IsCharAlphaNumericW;
pub const IsCharUpper = thismodule.IsCharUpperW;
pub const LoadAccelerators = thismodule.LoadAcceleratorsW;
pub const CreateAcceleratorTable = thismodule.CreateAcceleratorTableW;
pub const CopyAcceleratorTable = thismodule.CopyAcceleratorTableW;
pub const TranslateAccelerator = thismodule.TranslateAcceleratorW;
pub const LoadMenu = thismodule.LoadMenuW;
pub const LoadMenuIndirect = thismodule.LoadMenuIndirectW;
pub const ChangeMenu = thismodule.ChangeMenuW;
pub const GetMenuString = thismodule.GetMenuStringW;
pub const InsertMenu = thismodule.InsertMenuW;
pub const AppendMenu = thismodule.AppendMenuW;
pub const ModifyMenu = thismodule.ModifyMenuW;
pub const InsertMenuItem = thismodule.InsertMenuItemW;
pub const GetMenuItemInfo = thismodule.GetMenuItemInfoW;
pub const SetMenuItemInfo = thismodule.SetMenuItemInfoW;
pub const SetProp = thismodule.SetPropW;
pub const GetProp = thismodule.GetPropW;
pub const RemoveProp = thismodule.RemovePropW;
pub const EnumPropsEx = thismodule.EnumPropsExW;
pub const EnumProps = thismodule.EnumPropsW;
pub const SetWindowText = thismodule.SetWindowTextW;
pub const GetWindowText = thismodule.GetWindowTextW;
pub const GetWindowTextLength = thismodule.GetWindowTextLengthW;
pub const MessageBox = thismodule.MessageBoxW;
pub const MessageBoxEx = thismodule.MessageBoxExW;
pub const MessageBoxIndirect = thismodule.MessageBoxIndirectW;
pub const GetWindowLong = thismodule.GetWindowLongW;
pub const SetWindowLong = thismodule.SetWindowLongW;
pub const GetClassLong = thismodule.GetClassLongW;
pub const SetClassLong = thismodule.SetClassLongW;
pub const FindWindow = thismodule.FindWindowW;
pub const FindWindowEx = thismodule.FindWindowExW;
pub const GetClassName = thismodule.GetClassNameW;
pub const SetWindowsHook = thismodule.SetWindowsHookW;
pub const SetWindowsHookEx = thismodule.SetWindowsHookExW;
pub const LoadCursor = thismodule.LoadCursorW;
pub const LoadCursorFromFile = thismodule.LoadCursorFromFileW;
pub const LoadIcon = thismodule.LoadIconW;
pub const PrivateExtractIcons = thismodule.PrivateExtractIconsW;
pub const LoadImage = thismodule.LoadImageW;
pub const GetIconInfoEx = thismodule.GetIconInfoExW;
pub const IsDialogMessage = thismodule.IsDialogMessageW;
pub const DefFrameProc = thismodule.DefFrameProcW;
pub const DefMDIChildProc = thismodule.DefMDIChildProcW;
pub const CreateMDIWindow = thismodule.CreateMDIWindowW;
pub const SystemParametersInfo = thismodule.SystemParametersInfoW;
pub const GetWindowModuleFileName = thismodule.GetWindowModuleFileNameW;
pub const RealGetWindowClass = thismodule.RealGetWindowClassW;
pub const GetAltTabInfo = thismodule.GetAltTabInfoW;
},
.unspecified => if (@import("builtin").is_test) struct {
pub const WINSTAENUMPROC = *opaque{};
pub const DESKTOPENUMPROC = *opaque{};
pub const OPENFILENAME_NT4 = *opaque{};
pub const OPENFILENAME = *opaque{};
pub const OFNOTIFY = *opaque{};
pub const OFNOTIFYEX = *opaque{};
pub const CHOOSECOLOR = *opaque{};
pub const FINDREPLACE = *opaque{};
pub const CHOOSEFONT = *opaque{};
pub const PRINTDLG = *opaque{};
pub const PRINTDLGEX = *opaque{};
pub const PAGESETUPDLG = *opaque{};
pub const PROPENUMPROC = *opaque{};
pub const PROPENUMPROCEX = *opaque{};
pub const NAMEENUMPROC = *opaque{};
pub const CBT_CREATEWND = *opaque{};
pub const WNDCLASSEX = *opaque{};
pub const WNDCLASS = *opaque{};
pub const CREATESTRUCT = *opaque{};
pub const MENUITEMINFO = *opaque{};
pub const MSGBOXPARAMS = *opaque{};
pub const ICONINFOEX = *opaque{};
pub const MDICREATESTRUCT = *opaque{};
pub const NONCLIENTMETRICS = *opaque{};
pub const ICONMETRICS = *opaque{};
pub const GetWindowLongPtr = *opaque{};
pub const SetWindowLongPtr = *opaque{};
pub const GetClassLongPtr = *opaque{};
pub const SetClassLongPtr = *opaque{};
pub const GetOpenFileName = *opaque{};
pub const GetSaveFileName = *opaque{};
pub const GetFileTitle = *opaque{};
pub const ChooseColor = *opaque{};
pub const FindText = *opaque{};
pub const ReplaceText = *opaque{};
pub const ChooseFont = *opaque{};
pub const PrintDlg = *opaque{};
pub const PrintDlgEx = *opaque{};
pub const PageSetupDlg = *opaque{};
pub const LoadString = *opaque{};
pub const wvsprintf = *opaque{};
pub const wsprintf = *opaque{};
pub const RegisterWindowMessage = *opaque{};
pub const GetMessage = *opaque{};
pub const DispatchMessage = *opaque{};
pub const PeekMessage = *opaque{};
pub const SendMessage = *opaque{};
pub const SendMessageTimeout = *opaque{};
pub const SendNotifyMessage = *opaque{};
pub const SendMessageCallback = *opaque{};
pub const BroadcastSystemMessageEx = *opaque{};
pub const BroadcastSystemMessage = *opaque{};
pub const PostMessage = *opaque{};
pub const PostThreadMessage = *opaque{};
pub const DefWindowProc = *opaque{};
pub const CallWindowProc = *opaque{};
pub const RegisterClass = *opaque{};
pub const UnregisterClass = *opaque{};
pub const GetClassInfo = *opaque{};
pub const RegisterClassEx = *opaque{};
pub const GetClassInfoEx = *opaque{};
pub const CreateWindowEx = *opaque{};
pub const CreateDialogParam = *opaque{};
pub const CreateDialogIndirectParam = *opaque{};
pub const DialogBoxParam = *opaque{};
pub const DialogBoxIndirectParam = *opaque{};
pub const SetDlgItemText = *opaque{};
pub const GetDlgItemText = *opaque{};
pub const SendDlgItemMessage = *opaque{};
pub const DefDlgProc = *opaque{};
pub const CallMsgFilter = *opaque{};
pub const CharToOem = *opaque{};
pub const OemToChar = *opaque{};
pub const CharToOemBuff = *opaque{};
pub const OemToCharBuff = *opaque{};
pub const CharUpper = *opaque{};
pub const CharUpperBuff = *opaque{};
pub const CharLower = *opaque{};
pub const CharLowerBuff = *opaque{};
pub const CharNext = *opaque{};
pub const CharPrev = *opaque{};
pub const IsCharAlpha = *opaque{};
pub const IsCharAlphaNumeric = *opaque{};
pub const IsCharUpper = *opaque{};
pub const LoadAccelerators = *opaque{};
pub const CreateAcceleratorTable = *opaque{};
pub const CopyAcceleratorTable = *opaque{};
pub const TranslateAccelerator = *opaque{};
pub const LoadMenu = *opaque{};
pub const LoadMenuIndirect = *opaque{};
pub const ChangeMenu = *opaque{};
pub const GetMenuString = *opaque{};
pub const InsertMenu = *opaque{};
pub const AppendMenu = *opaque{};
pub const ModifyMenu = *opaque{};
pub const InsertMenuItem = *opaque{};
pub const GetMenuItemInfo = *opaque{};
pub const SetMenuItemInfo = *opaque{};
pub const SetProp = *opaque{};
pub const GetProp = *opaque{};
pub const RemoveProp = *opaque{};
pub const EnumPropsEx = *opaque{};
pub const EnumProps = *opaque{};
pub const SetWindowText = *opaque{};
pub const GetWindowText = *opaque{};
pub const GetWindowTextLength = *opaque{};
pub const MessageBox = *opaque{};
pub const MessageBoxEx = *opaque{};
pub const MessageBoxIndirect = *opaque{};
pub const GetWindowLong = *opaque{};
pub const SetWindowLong = *opaque{};
pub const GetClassLong = *opaque{};
pub const SetClassLong = *opaque{};
pub const FindWindow = *opaque{};
pub const FindWindowEx = *opaque{};
pub const GetClassName = *opaque{};
pub const SetWindowsHook = *opaque{};
pub const SetWindowsHookEx = *opaque{};
pub const LoadCursor = *opaque{};
pub const LoadCursorFromFile = *opaque{};
pub const LoadIcon = *opaque{};
pub const PrivateExtractIcons = *opaque{};
pub const LoadImage = *opaque{};
pub const GetIconInfoEx = *opaque{};
pub const IsDialogMessage = *opaque{};
pub const DefFrameProc = *opaque{};
pub const DefMDIChildProc = *opaque{};
pub const CreateMDIWindow = *opaque{};
pub const SystemParametersInfo = *opaque{};
pub const GetWindowModuleFileName = *opaque{};
pub const RealGetWindowClass = *opaque{};
pub const GetAltTabInfo = *opaque{};
} else struct {
pub const WINSTAENUMPROC = @compileError("'WINSTAENUMPROC' requires that UNICODE be set to true or false in the root module");
pub const DESKTOPENUMPROC = @compileError("'DESKTOPENUMPROC' requires that UNICODE be set to true or false in the root module");
pub const OPENFILENAME_NT4 = @compileError("'OPENFILENAME_NT4' requires that UNICODE be set to true or false in the root module");
pub const OPENFILENAME = @compileError("'OPENFILENAME' requires that UNICODE be set to true or false in the root module");
pub const OFNOTIFY = @compileError("'OFNOTIFY' requires that UNICODE be set to true or false in the root module");
pub const OFNOTIFYEX = @compileError("'OFNOTIFYEX' requires that UNICODE be set to true or false in the root module");
pub const CHOOSECOLOR = @compileError("'CHOOSECOLOR' requires that UNICODE be set to true or false in the root module");
pub const FINDREPLACE = @compileError("'FINDREPLACE' requires that UNICODE be set to true or false in the root module");
pub const CHOOSEFONT = @compileError("'CHOOSEFONT' requires that UNICODE be set to true or false in the root module");
pub const PRINTDLG = @compileError("'PRINTDLG' requires that UNICODE be set to true or false in the root module");
pub const PRINTDLGEX = @compileError("'PRINTDLGEX' requires that UNICODE be set to true or false in the root module");
pub const PAGESETUPDLG = @compileError("'PAGESETUPDLG' requires that UNICODE be set to true or false in the root module");
pub const PROPENUMPROC = @compileError("'PROPENUMPROC' requires that UNICODE be set to true or false in the root module");
pub const PROPENUMPROCEX = @compileError("'PROPENUMPROCEX' requires that UNICODE be set to true or false in the root module");
pub const NAMEENUMPROC = @compileError("'NAMEENUMPROC' requires that UNICODE be set to true or false in the root module");
pub const CBT_CREATEWND = @compileError("'CBT_CREATEWND' requires that UNICODE be set to true or false in the root module");
pub const WNDCLASSEX = @compileError("'WNDCLASSEX' requires that UNICODE be set to true or false in the root module");
pub const WNDCLASS = @compileError("'WNDCLASS' requires that UNICODE be set to true or false in the root module");
pub const CREATESTRUCT = @compileError("'CREATESTRUCT' requires that UNICODE be set to true or false in the root module");
pub const MENUITEMINFO = @compileError("'MENUITEMINFO' requires that UNICODE be set to true or false in the root module");
pub const MSGBOXPARAMS = @compileError("'MSGBOXPARAMS' requires that UNICODE be set to true or false in the root module");
pub const ICONINFOEX = @compileError("'ICONINFOEX' requires that UNICODE be set to true or false in the root module");
pub const MDICREATESTRUCT = @compileError("'MDICREATESTRUCT' requires that UNICODE be set to true or false in the root module");
pub const NONCLIENTMETRICS = @compileError("'NONCLIENTMETRICS' requires that UNICODE be set to true or false in the root module");
pub const ICONMETRICS = @compileError("'ICONMETRICS' requires that UNICODE be set to true or false in the root module");
pub const GetWindowLongPtr = @compileError("'GetWindowLongPtr' requires that UNICODE be set to true or false in the root module");
pub const SetWindowLongPtr = @compileError("'SetWindowLongPtr' requires that UNICODE be set to true or false in the root module");
pub const GetClassLongPtr = @compileError("'GetClassLongPtr' requires that UNICODE be set to true or false in the root module");
pub const SetClassLongPtr = @compileError("'SetClassLongPtr' requires that UNICODE be set to true or false in the root module");
pub const GetOpenFileName = @compileError("'GetOpenFileName' requires that UNICODE be set to true or false in the root module");
pub const GetSaveFileName = @compileError("'GetSaveFileName' requires that UNICODE be set to true or false in the root module");
pub const GetFileTitle = @compileError("'GetFileTitle' requires that UNICODE be set to true or false in the root module");
pub const ChooseColor = @compileError("'ChooseColor' requires that UNICODE be set to true or false in the root module");
pub const FindText = @compileError("'FindText' requires that UNICODE be set to true or false in the root module");
pub const ReplaceText = @compileError("'ReplaceText' requires that UNICODE be set to true or false in the root module");
pub const ChooseFont = @compileError("'ChooseFont' requires that UNICODE be set to true or false in the root module");
pub const PrintDlg = @compileError("'PrintDlg' requires that UNICODE be set to true or false in the root module");
pub const PrintDlgEx = @compileError("'PrintDlgEx' requires that UNICODE be set to true or false in the root module");
pub const PageSetupDlg = @compileError("'PageSetupDlg' requires that UNICODE be set to true or false in the root module");
pub const LoadString = @compileError("'LoadString' requires that UNICODE be set to true or false in the root module");
pub const wvsprintf = @compileError("'wvsprintf' requires that UNICODE be set to true or false in the root module");
pub const wsprintf = @compileError("'wsprintf' requires that UNICODE be set to true or false in the root module");
pub const RegisterWindowMessage = @compileError("'RegisterWindowMessage' requires that UNICODE be set to true or false in the root module");
pub const GetMessage = @compileError("'GetMessage' requires that UNICODE be set to true or false in the root module");
pub const DispatchMessage = @compileError("'DispatchMessage' requires that UNICODE be set to true or false in the root module");
pub const PeekMessage = @compileError("'PeekMessage' requires that UNICODE be set to true or false in the root module");
pub const SendMessage = @compileError("'SendMessage' requires that UNICODE be set to true or false in the root module");
pub const SendMessageTimeout = @compileError("'SendMessageTimeout' requires that UNICODE be set to true or false in the root module");
pub const SendNotifyMessage = @compileError("'SendNotifyMessage' requires that UNICODE be set to true or false in the root module");
pub const SendMessageCallback = @compileError("'SendMessageCallback' requires that UNICODE be set to true or false in the root module");
pub const BroadcastSystemMessageEx = @compileError("'BroadcastSystemMessageEx' requires that UNICODE be set to true or false in the root module");
pub const BroadcastSystemMessage = @compileError("'BroadcastSystemMessage' requires that UNICODE be set to true or false in the root module");
pub const PostMessage = @compileError("'PostMessage' requires that UNICODE be set to true or false in the root module");
pub const PostThreadMessage = @compileError("'PostThreadMessage' requires that UNICODE be set to true or false in the root module");
pub const DefWindowProc = @compileError("'DefWindowProc' requires that UNICODE be set to true or false in the root module");
pub const CallWindowProc = @compileError("'CallWindowProc' requires that UNICODE be set to true or false in the root module");
pub const RegisterClass = @compileError("'RegisterClass' requires that UNICODE be set to true or false in the root module");
pub const UnregisterClass = @compileError("'UnregisterClass' requires that UNICODE be set to true or false in the root module");
pub const GetClassInfo = @compileError("'GetClassInfo' requires that UNICODE be set to true or false in the root module");
pub const RegisterClassEx = @compileError("'RegisterClassEx' requires that UNICODE be set to true or false in the root module");
pub const GetClassInfoEx = @compileError("'GetClassInfoEx' requires that UNICODE be set to true or false in the root module");
pub const CreateWindowEx = @compileError("'CreateWindowEx' requires that UNICODE be set to true or false in the root module");
pub const CreateDialogParam = @compileError("'CreateDialogParam' requires that UNICODE be set to true or false in the root module");
pub const CreateDialogIndirectParam = @compileError("'CreateDialogIndirectParam' requires that UNICODE be set to true or false in the root module");
pub const DialogBoxParam = @compileError("'DialogBoxParam' requires that UNICODE be set to true or false in the root module");
pub const DialogBoxIndirectParam = @compileError("'DialogBoxIndirectParam' requires that UNICODE be set to true or false in the root module");
pub const SetDlgItemText = @compileError("'SetDlgItemText' requires that UNICODE be set to true or false in the root module");
pub const GetDlgItemText = @compileError("'GetDlgItemText' requires that UNICODE be set to true or false in the root module");
pub const SendDlgItemMessage = @compileError("'SendDlgItemMessage' requires that UNICODE be set to true or false in the root module");
pub const DefDlgProc = @compileError("'DefDlgProc' requires that UNICODE be set to true or false in the root module");
pub const CallMsgFilter = @compileError("'CallMsgFilter' requires that UNICODE be set to true or false in the root module");
pub const CharToOem = @compileError("'CharToOem' requires that UNICODE be set to true or false in the root module");
pub const OemToChar = @compileError("'OemToChar' requires that UNICODE be set to true or false in the root module");
pub const CharToOemBuff = @compileError("'CharToOemBuff' requires that UNICODE be set to true or false in the root module");
pub const OemToCharBuff = @compileError("'OemToCharBuff' requires that UNICODE be set to true or false in the root module");
pub const CharUpper = @compileError("'CharUpper' requires that UNICODE be set to true or false in the root module");
pub const CharUpperBuff = @compileError("'CharUpperBuff' requires that UNICODE be set to true or false in the root module");
pub const CharLower = @compileError("'CharLower' requires that UNICODE be set to true or false in the root module");
pub const CharLowerBuff = @compileError("'CharLowerBuff' requires that UNICODE be set to true or false in the root module");
pub const CharNext = @compileError("'CharNext' requires that UNICODE be set to true or false in the root module");
pub const CharPrev = @compileError("'CharPrev' requires that UNICODE be set to true or false in the root module");
pub const IsCharAlpha = @compileError("'IsCharAlpha' requires that UNICODE be set to true or false in the root module");
pub const IsCharAlphaNumeric = @compileError("'IsCharAlphaNumeric' requires that UNICODE be set to true or false in the root module");
pub const IsCharUpper = @compileError("'IsCharUpper' requires that UNICODE be set to true or false in the root module");
pub const LoadAccelerators = @compileError("'LoadAccelerators' requires that UNICODE be set to true or false in the root module");
pub const CreateAcceleratorTable = @compileError("'CreateAcceleratorTable' requires that UNICODE be set to true or false in the root module");
pub const CopyAcceleratorTable = @compileError("'CopyAcceleratorTable' requires that UNICODE be set to true or false in the root module");
pub const TranslateAccelerator = @compileError("'TranslateAccelerator' requires that UNICODE be set to true or false in the root module");
pub const LoadMenu = @compileError("'LoadMenu' requires that UNICODE be set to true or false in the root module");
pub const LoadMenuIndirect = @compileError("'LoadMenuIndirect' requires that UNICODE be set to true or false in the root module");
pub const ChangeMenu = @compileError("'ChangeMenu' requires that UNICODE be set to true or false in the root module");
pub const GetMenuString = @compileError("'GetMenuString' requires that UNICODE be set to true or false in the root module");
pub const InsertMenu = @compileError("'InsertMenu' requires that UNICODE be set to true or false in the root module");
pub const AppendMenu = @compileError("'AppendMenu' requires that UNICODE be set to true or false in the root module");
pub const ModifyMenu = @compileError("'ModifyMenu' requires that UNICODE be set to true or false in the root module");
pub const InsertMenuItem = @compileError("'InsertMenuItem' requires that UNICODE be set to true or false in the root module");
pub const GetMenuItemInfo = @compileError("'GetMenuItemInfo' requires that UNICODE be set to true or false in the root module");
pub const SetMenuItemInfo = @compileError("'SetMenuItemInfo' requires that UNICODE be set to true or false in the root module");
pub const SetProp = @compileError("'SetProp' requires that UNICODE be set to true or false in the root module");
pub const GetProp = @compileError("'GetProp' requires that UNICODE be set to true or false in the root module");
pub const RemoveProp = @compileError("'RemoveProp' requires that UNICODE be set to true or false in the root module");
pub const EnumPropsEx = @compileError("'EnumPropsEx' requires that UNICODE be set to true or false in the root module");
pub const EnumProps = @compileError("'EnumProps' requires that UNICODE be set to true or false in the root module");
pub const SetWindowText = @compileError("'SetWindowText' requires that UNICODE be set to true or false in the root module");
pub const GetWindowText = @compileError("'GetWindowText' requires that UNICODE be set to true or false in the root module");
pub const GetWindowTextLength = @compileError("'GetWindowTextLength' requires that UNICODE be set to true or false in the root module");
pub const MessageBox = @compileError("'MessageBox' requires that UNICODE be set to true or false in the root module");
pub const MessageBoxEx = @compileError("'MessageBoxEx' requires that UNICODE be set to true or false in the root module");
pub const MessageBoxIndirect = @compileError("'MessageBoxIndirect' requires that UNICODE be set to true or false in the root module");
pub const GetWindowLong = @compileError("'GetWindowLong' requires that UNICODE be set to true or false in the root module");
pub const SetWindowLong = @compileError("'SetWindowLong' requires that UNICODE be set to true or false in the root module");
pub const GetClassLong = @compileError("'GetClassLong' requires that UNICODE be set to true or false in the root module");
pub const SetClassLong = @compileError("'SetClassLong' requires that UNICODE be set to true or false in the root module");
pub const FindWindow = @compileError("'FindWindow' requires that UNICODE be set to true or false in the root module");
pub const FindWindowEx = @compileError("'FindWindowEx' requires that UNICODE be set to true or false in the root module");
pub const GetClassName = @compileError("'GetClassName' requires that UNICODE be set to true or false in the root module");
pub const SetWindowsHook = @compileError("'SetWindowsHook' requires that UNICODE be set to true or false in the root module");
pub const SetWindowsHookEx = @compileError("'SetWindowsHookEx' requires that UNICODE be set to true or false in the root module");
pub const LoadCursor = @compileError("'LoadCursor' requires that UNICODE be set to true or false in the root module");
pub const LoadCursorFromFile = @compileError("'LoadCursorFromFile' requires that UNICODE be set to true or false in the root module");
pub const LoadIcon = @compileError("'LoadIcon' requires that UNICODE be set to true or false in the root module");
pub const PrivateExtractIcons = @compileError("'PrivateExtractIcons' requires that UNICODE be set to true or false in the root module");
pub const LoadImage = @compileError("'LoadImage' requires that UNICODE be set to true or false in the root module");
pub const GetIconInfoEx = @compileError("'GetIconInfoEx' requires that UNICODE be set to true or false in the root module");
pub const IsDialogMessage = @compileError("'IsDialogMessage' requires that UNICODE be set to true or false in the root module");
pub const DefFrameProc = @compileError("'DefFrameProc' requires that UNICODE be set to true or false in the root module");
pub const DefMDIChildProc = @compileError("'DefMDIChildProc' requires that UNICODE be set to true or false in the root module");
pub const CreateMDIWindow = @compileError("'CreateMDIWindow' requires that UNICODE be set to true or false in the root module");
pub const SystemParametersInfo = @compileError("'SystemParametersInfo' requires that UNICODE be set to true or false in the root module");
pub const GetWindowModuleFileName = @compileError("'GetWindowModuleFileName' requires that UNICODE be set to true or false in the root module");
pub const RealGetWindowClass = @compileError("'RealGetWindowClass' requires that UNICODE be set to true or false in the root module");
pub const GetAltTabInfo = @compileError("'GetAltTabInfo' requires that UNICODE be set to true or false in the root module");
},
};
//--------------------------------------------------------------------------------
// Section: Imports (31)
//--------------------------------------------------------------------------------
const BLENDFUNCTION = @import("../graphics/gdi.zig").BLENDFUNCTION;
const BOOL = @import("../foundation.zig").BOOL;
const BOOLEAN = @import("../foundation.zig").BOOLEAN;
const CHAR = @import("../system/system_services.zig").CHAR;
const DEVMODEA = @import("../ui/display_devices.zig").DEVMODEA;
const DPI_AWARENESS_CONTEXT = @import("../system/system_services.zig").DPI_AWARENESS_CONTEXT;
const HANDLE = @import("../foundation.zig").HANDLE;
const HBITMAP = @import("../graphics/gdi.zig").HBITMAP;
const HBRUSH = @import("../graphics/gdi.zig").HBRUSH;
const HDC = @import("../graphics/gdi.zig").HDC;
const HDESK = @import("../system/stations_and_desktops.zig").HDESK;
const HELPINFO = @import("../ui/shell.zig").HELPINFO;
const HINSTANCE = @import("../foundation.zig").HINSTANCE;
const HPROPSHEETPAGE = @import("../ui/controls.zig").HPROPSHEETPAGE;
const HRESULT = @import("../foundation.zig").HRESULT;
const HWND = @import("../foundation.zig").HWND;
const IMAGE_FLAGS = @import("../ui/controls.zig").IMAGE_FLAGS;
const IUnknown = @import("../system/com.zig").IUnknown;
const LOGFONTA = @import("../graphics/gdi.zig").LOGFONTA;
const LOGFONTW = @import("../graphics/gdi.zig").LOGFONTW;
const LPARAM = @import("../foundation.zig").LPARAM;
const LRESULT = @import("../foundation.zig").LRESULT;
const LUID = @import("../system/system_services.zig").LUID;
const NMHDR = @import("../ui/controls.zig").NMHDR;
const OBJECT_IDENTIFIER = @import("../ui/controls.zig").OBJECT_IDENTIFIER;
const POINT = @import("../foundation.zig").POINT;
const PSTR = @import("../foundation.zig").PSTR;
const PWSTR = @import("../foundation.zig").PWSTR;
const RECT = @import("../foundation.zig").RECT;
const SIZE = @import("../foundation.zig").SIZE;
const WPARAM = @import("../foundation.zig").WPARAM;
test {
// The following '_ = <FuncPtrType>' lines are a workaround for https://github.com/ziglang/zig/issues/4476
if (@hasDecl(@This(), "WINSTAENUMPROCA")) { _ = WINSTAENUMPROCA; }
if (@hasDecl(@This(), "WINSTAENUMPROCW")) { _ = WINSTAENUMPROCW; }
if (@hasDecl(@This(), "DESKTOPENUMPROCA")) { _ = DESKTOPENUMPROCA; }
if (@hasDecl(@This(), "DESKTOPENUMPROCW")) { _ = DESKTOPENUMPROCW; }
if (@hasDecl(@This(), "LPOFNHOOKPROC")) { _ = LPOFNHOOKPROC; }
if (@hasDecl(@This(), "LPCCHOOKPROC")) { _ = LPCCHOOKPROC; }
if (@hasDecl(@This(), "LPFRHOOKPROC")) { _ = LPFRHOOKPROC; }
if (@hasDecl(@This(), "LPCFHOOKPROC")) { _ = LPCFHOOKPROC; }
if (@hasDecl(@This(), "LPPRINTHOOKPROC")) { _ = LPPRINTHOOKPROC; }
if (@hasDecl(@This(), "LPSETUPHOOKPROC")) { _ = LPSETUPHOOKPROC; }
if (@hasDecl(@This(), "LPPAGEPAINTHOOK")) { _ = LPPAGEPAINTHOOK; }
if (@hasDecl(@This(), "LPPAGESETUPHOOK")) { _ = LPPAGESETUPHOOK; }
if (@hasDecl(@This(), "WNDPROC")) { _ = WNDPROC; }
if (@hasDecl(@This(), "DLGPROC")) { _ = DLGPROC; }
if (@hasDecl(@This(), "TIMERPROC")) { _ = TIMERPROC; }
if (@hasDecl(@This(), "WNDENUMPROC")) { _ = WNDENUMPROC; }
if (@hasDecl(@This(), "HOOKPROC")) { _ = HOOKPROC; }
if (@hasDecl(@This(), "SENDASYNCPROC")) { _ = SENDASYNCPROC; }
if (@hasDecl(@This(), "PROPENUMPROCA")) { _ = PROPENUMPROCA; }
if (@hasDecl(@This(), "PROPENUMPROCW")) { _ = PROPENUMPROCW; }
if (@hasDecl(@This(), "PROPENUMPROCEXA")) { _ = PROPENUMPROCEXA; }
if (@hasDecl(@This(), "PROPENUMPROCEXW")) { _ = PROPENUMPROCEXW; }
if (@hasDecl(@This(), "NAMEENUMPROCA")) { _ = NAMEENUMPROCA; }
if (@hasDecl(@This(), "NAMEENUMPROCW")) { _ = NAMEENUMPROCW; }
if (@hasDecl(@This(), "PREGISTERCLASSNAMEW")) { _ = PREGISTERCLASSNAMEW; }
if (@hasDecl(@This(), "MSGBOXCALLBACK")) { _ = MSGBOXCALLBACK; }
@setEvalBranchQuota(
@import("std").meta.declarations(@This()).len * 3
);
// reference all the pub declarations
if (!@import("builtin").is_test) return;
inline for (@import("std").meta.declarations(@This())) |decl| {
if (decl.is_pub) {
_ = decl;
}
}
} | deps/zigwin32/win32/ui/windows_and_messaging.zig |
const __fixtfsi = @import("fixtfsi.zig").__fixtfsi;
const std = @import("std");
const math = std.math;
const testing = std.testing;
const warn = std.debug.warn;
fn test__fixtfsi(a: f128, expected: i32) !void {
const x = __fixtfsi(a);
//warn("a={}:{x} x={}:{x} expected={}:{x}:@as(u32, {x})\n", .{a, @bitCast(u128, a), x, x, expected, expected, @bitCast(u32, expected)});
try testing.expect(x == expected);
}
test "fixtfsi" {
//warn("\n", .{});
try test__fixtfsi(-math.f128_max, math.minInt(i32));
try test__fixtfsi(-0x1.FFFFFFFFFFFFFp+1023, math.minInt(i32));
try test__fixtfsi(-0x1.FFFFFFFFFFFFFp+1023, -0x80000000);
try test__fixtfsi(-0x1.0000000000000p+127, -0x80000000);
try test__fixtfsi(-0x1.FFFFFFFFFFFFFp+126, -0x80000000);
try test__fixtfsi(-0x1.FFFFFFFFFFFFEp+126, -0x80000000);
try test__fixtfsi(-0x1.0000000000001p+63, -0x80000000);
try test__fixtfsi(-0x1.0000000000000p+63, -0x80000000);
try test__fixtfsi(-0x1.FFFFFFFFFFFFFp+62, -0x80000000);
try test__fixtfsi(-0x1.FFFFFFFFFFFFEp+62, -0x80000000);
try test__fixtfsi(-0x1.FFFFFEp+62, -0x80000000);
try test__fixtfsi(-0x1.FFFFFCp+62, -0x80000000);
try test__fixtfsi(-0x1.000000p+31, -0x80000000);
try test__fixtfsi(-0x1.FFFFFFp+30, -0x7FFFFFC0);
try test__fixtfsi(-0x1.FFFFFEp+30, -0x7FFFFF80);
try test__fixtfsi(-0x1.FFFFFCp+30, -0x7FFFFF00);
try test__fixtfsi(-2.01, -2);
try test__fixtfsi(-2.0, -2);
try test__fixtfsi(-1.99, -1);
try test__fixtfsi(-1.0, -1);
try test__fixtfsi(-0.99, 0);
try test__fixtfsi(-0.5, 0);
try test__fixtfsi(-math.f32_min, 0);
try test__fixtfsi(0.0, 0);
try test__fixtfsi(math.f32_min, 0);
try test__fixtfsi(0.5, 0);
try test__fixtfsi(0.99, 0);
try test__fixtfsi(1.0, 1);
try test__fixtfsi(1.5, 1);
try test__fixtfsi(1.99, 1);
try test__fixtfsi(2.0, 2);
try test__fixtfsi(2.01, 2);
try test__fixtfsi(0x1.FFFFFCp+30, 0x7FFFFF00);
try test__fixtfsi(0x1.FFFFFEp+30, 0x7FFFFF80);
try test__fixtfsi(0x1.FFFFFFp+30, 0x7FFFFFC0);
try test__fixtfsi(0x1.000000p+31, 0x7FFFFFFF);
try test__fixtfsi(0x1.FFFFFCp+62, 0x7FFFFFFF);
try test__fixtfsi(0x1.FFFFFEp+62, 0x7FFFFFFF);
try test__fixtfsi(0x1.FFFFFFFFFFFFEp+62, 0x7FFFFFFF);
try test__fixtfsi(0x1.FFFFFFFFFFFFFp+62, 0x7FFFFFFF);
try test__fixtfsi(0x1.0000000000000p+63, 0x7FFFFFFF);
try test__fixtfsi(0x1.0000000000001p+63, 0x7FFFFFFF);
try test__fixtfsi(0x1.FFFFFFFFFFFFEp+126, 0x7FFFFFFF);
try test__fixtfsi(0x1.FFFFFFFFFFFFFp+126, 0x7FFFFFFF);
try test__fixtfsi(0x1.0000000000000p+127, 0x7FFFFFFF);
try test__fixtfsi(0x1.FFFFFFFFFFFFFp+1023, 0x7FFFFFFF);
try test__fixtfsi(0x1.FFFFFFFFFFFFFp+1023, math.maxInt(i32));
try test__fixtfsi(math.f128_max, math.maxInt(i32));
} | lib/std/special/compiler_rt/fixtfsi_test.zig |
const std = @import("std");
const aoc = @import("aoc-lib.zig");
test "direction" {
const TC = struct { c: u8, dx: i64, dy: i64 };
const tests = [_]TC{
TC{ .c = 'N', .dx = 0, .dy = -1 },
TC{ .c = 'S', .dx = 0, .dy = 1 },
TC{ .c = 'E', .dx = 1, .dy = 0 },
TC{ .c = 'W', .dx = -1, .dy = 0 },
};
for (tests) |tc| {
var dir = Direction.newFromCompass(tc.c) catch unreachable;
try aoc.assertEq(dir.dx, tc.dx);
try aoc.assertEq(dir.dy, tc.dy);
}
}
const Direction = struct {
dx: i64,
dy: i64,
pub fn newFromCompass(c: u8) !*Direction {
var d = try aoc.halloc.create(Direction);
switch (c) {
'N' => {
d.dx = 0;
d.dy = -1;
},
'S' => {
d.dx = 0;
d.dy = 1;
},
'E' => {
d.dx = 1;
d.dy = 0;
},
'W' => {
d.dx = -1;
d.dy = 0;
},
else => {
std.debug.panic("Compass {} not supported", .{c});
},
}
return d;
}
pub fn CCW(self: *Direction) void {
var t = self.dx;
self.dx = self.dy;
self.dy = -1 * t;
}
pub fn CW(self: *Direction) void {
var t = self.dx;
self.dx = -1 * self.dy;
self.dy = t;
}
};
const Point = struct {
x: i64,
y: i64,
pub fn Add(self: *Point, p: Point) void {
self.x += p.x;
self.y += p.y;
}
pub fn In(self: *Point, d: *Direction) void {
self.x += d.dx;
self.y += d.dy;
}
pub fn ManDist(self: *Point) usize {
return std.math.absCast(self.x) + std.math.absCast(self.y);
}
pub fn CCW(self: *Point) void {
var t = self.x;
self.x = self.y;
self.y = -1 * t;
}
pub fn CW(self: *Point) void {
var t = self.x;
self.x = -1 * self.y;
self.y = t;
}
};
const Nav = struct {
pub const Inst = struct {
act: u8,
val: usize,
};
inst: []Inst,
ship: Point,
dir: *Direction,
wp: Point,
alloc: std.mem.Allocator,
debug: bool,
pub fn fromInput(alloc: std.mem.Allocator, inp: [][]const u8) !*Nav {
var l = inp.len;
var inst = try alloc.alloc(Inst, l);
var nav = try alloc.create(Nav);
for (inp) |line, i| {
const n = try std.fmt.parseUnsigned(usize, line[1..], 10);
inst[i].act = line[0];
inst[i].val = n;
}
nav.inst = inst;
nav.ship = Point{ .x = 0, .y = 0 };
nav.dir = try Direction.newFromCompass('E');
nav.wp = Point{ .x = 10, .y = -1 };
nav.debug = false;
nav.alloc = alloc;
return nav;
}
pub fn deinit(self: *Nav) void {
self.alloc.free(self.inst);
self.alloc.destroy(self);
}
pub fn Part1(self: *Nav) usize {
if (self.debug) {
self.Print();
}
for (self.inst) |in| {
switch (in.act) {
'N', 'S', 'E', 'W' => {
var dir = Direction.newFromCompass(in.act) catch unreachable;
var i: usize = 0;
while (i < in.val) : (i += 1) {
self.ship.In(dir);
}
},
'L' => {
var i: usize = 0;
while (i < in.val) : (i += 90) {
self.dir.CCW();
}
},
'R' => {
var i: usize = 0;
while (i < in.val) : (i += 90) {
self.dir.CW();
}
},
'F' => {
var i: usize = 0;
while (i < in.val) : (i += 1) {
self.ship.In(self.dir);
}
},
else => {
std.debug.panic("Invalid nav instruction: {}", .{in});
},
}
if (self.debug) {
self.Print();
}
}
return self.ship.ManDist();
}
pub fn Part2(self: *Nav) u64 {
if (self.debug) {
self.Print();
}
for (self.inst) |in| {
switch (in.act) {
'N', 'S', 'E', 'W' => {
var dir = Direction.newFromCompass(in.act) catch unreachable;
var i: usize = 0;
while (i < in.val) : (i += 1) {
self.wp.In(dir);
}
},
'L' => {
var i: usize = 0;
while (i < in.val) : (i += 90) {
self.wp.CCW();
}
},
'R' => {
var i: usize = 0;
while (i < in.val) : (i += 90) {
self.wp.CW();
}
},
'F' => {
var i: usize = 0;
while (i < in.val) : (i += 1) {
self.ship.Add(self.wp);
}
},
else => {
std.debug.panic("Invalid nav instruction: {}", .{in});
},
}
if (self.debug) {
self.Print();
}
}
return self.ship.ManDist();
}
pub fn Print(self: *Nav) void {
if (self.ship.x >= 0) {
aoc.print("{s} {}", .{ "east", std.math.absCast(self.ship.x) }) catch unreachable;
} else {
aoc.print("{s} {}", .{ "west", std.math.absCast(self.ship.x) }) catch unreachable;
}
if (self.ship.y <= 0) {
aoc.print(" {s} {}", .{ "north", std.math.absCast(self.ship.y) }) catch unreachable;
} else {
aoc.print(" {s} {}", .{ "south", std.math.absCast(self.ship.y) }) catch unreachable;
}
aoc.print(" [{},{}]\n", .{ self.dir.dx, self.dir.dy }) catch unreachable;
}
};
fn part1(alloc: std.mem.Allocator, in: [][]const u8) usize {
var nav = Nav.fromInput(alloc, in) catch unreachable;
defer nav.deinit();
return nav.Part1();
}
fn part2(alloc: std.mem.Allocator, in: [][]const u8) usize {
var nav = Nav.fromInput(alloc, in) catch unreachable;
defer nav.deinit();
return nav.Part2();
}
test "examples" {
const test1 = aoc.readLines(aoc.talloc, aoc.test1file);
defer aoc.talloc.free(test1);
const inp = aoc.readLines(aoc.talloc, aoc.inputfile);
defer aoc.talloc.free(inp);
try aoc.assertEq(@as(usize, 25), part1(aoc.talloc, test1));
try aoc.assertEq(@as(usize, 286), part2(aoc.talloc, test1));
try aoc.assertEq(@as(usize, 759), part1(aoc.talloc, inp));
try aoc.assertEq(@as(usize, 45763), part2(aoc.talloc, inp));
}
fn day12(inp: []const u8, bench: bool) anyerror!void {
const lines = aoc.readLines(aoc.halloc, inp);
defer aoc.halloc.free(lines);
var p1 = part1(aoc.halloc, lines);
var p2 = part2(aoc.halloc, lines);
if (!bench) {
try aoc.print("Part 1: {}\nPart 2: {}\n", .{ p1, p2 });
}
}
pub fn main() anyerror!void {
try aoc.benchme(aoc.input(), day12);
} | 2020/12/aoc.zig |
const std = @import("std");
fn tagKind(tree: *std.zig.ast.Tree, node: *std.zig.ast.Node) u8 {
const NTag = std.zig.ast.Node.Tag;
return switch (node.tag) {
NTag.FnProto => 'f',
NTag.VarDecl => {
const var_decl_node = node.cast(std.zig.ast.Node.VarDecl).?;
if (var_decl_node.getInitNode()) |init_node| {
if (init_node.tag == NTag.ContainerDecl) {
const container_node = init_node.cast(std.zig.ast.Node.ContainerDecl).?;
return switch (tree.token_ids[container_node.kind_token]) {
std.zig.Token.Id.Keyword_struct => 's',
std.zig.Token.Id.Keyword_union => 'u',
std.zig.Token.Id.Keyword_enum => 'g',
else => @as(u8, 0),
};
} else if (init_node.tag == NTag.ErrorType or init_node.tag == NTag.ErrorSetDecl) {
return 'r';
}
}
return 'v';
},
NTag.ContainerField => {
const member_decl_node = node.castTag(NTag.ContainerField).?;
// hacky but enumerated types do not allow for type expressions while union/structs require
// this just happens to be an easy check if the container field is a enum or otherwise (assuming valid code).
if (member_decl_node.type_expr == null) {
return 'e';
} else {
return 'm';
}
},
else => @as(u8, 0),
};
}
fn escapeString(allocator: *std.mem.Allocator, line: []const u8) ![]const u8 {
var result = std.ArrayList(u8).init(allocator);
errdefer result.deinit();
// Max length of escaped string is twice the length of the original line.
try result.ensureCapacity(line.len * 2);
for (line) |ch| {
switch (ch) {
'/', '\\' => {
try result.append('\\');
try result.append(ch);
},
else => {
try result.append(ch);
},
}
}
return result.toOwnedSlice();
}
const ErrorSet = error{
OutOfMemory,
WriteError,
};
fn findTags(
allocator: *std.mem.Allocator,
tree: *std.zig.ast.Tree,
node: *std.zig.ast.Node,
path: []const u8,
scope_field_name: []const u8,
scope: []const u8,
tags_file_stream: anytype,
) ErrorSet!void {
var token_index: ?std.zig.ast.TokenIndex = null;
const NTag = std.zig.ast.Node.Tag;
switch (node.tag) {
NTag.ContainerField => {
const container_field = node.castTag(NTag.ContainerField).?;
token_index = container_field.name_token;
},
NTag.FnProto => {
const fn_node = node.castTag(NTag.FnProto).?;
if (fn_node.getNameToken()) |name_index| {
token_index = name_index;
}
},
NTag.VarDecl => {
const var_node = node.castTag(NTag.VarDecl).?;
token_index = var_node.name_token;
if (var_node.getInitNode()) |init_node| {
if (init_node.tag == NTag.ContainerDecl) {
const container_node = init_node.cast(std.zig.ast.Node.ContainerDecl).?;
const container_kind = tree.tokenSlice(container_node.kind_token);
const container_name = tree.tokenSlice(token_index.?);
const delim = ".";
var sub_scope: []u8 = undefined;
if (scope.len > 0) {
sub_scope = try allocator.alloc(u8, scope.len + delim.len + container_name.len);
std.mem.copy(u8, sub_scope[0..scope.len], scope);
std.mem.copy(u8, sub_scope[scope.len .. scope.len + delim.len], delim);
std.mem.copy(u8, sub_scope[scope.len + delim.len ..], container_name);
} else {
sub_scope = try std.mem.dupe(allocator, u8, container_name);
}
defer allocator.free(sub_scope);
for (container_node.fieldsAndDecls()) |child| {
try findTags(allocator, tree, child, path, container_kind, sub_scope, tags_file_stream);
}
}
}
},
else => {},
}
if (token_index == null) {
return;
}
const name = tree.tokenSlice(token_index.?);
const location = tree.tokenLocation(0, token_index.?);
const line = tree.source[location.line_start..location.line_end];
const escaped_line = try escapeString(allocator, line);
defer allocator.free(escaped_line);
tags_file_stream.print("{s}\t{s}\t/^{s}$/;\"\t{c}", .{
name,
path,
escaped_line,
tagKind(tree, node),
}) catch return ErrorSet.WriteError;
if (scope.len > 0) {
tags_file_stream.print("\t{s}:{s}", .{ scope_field_name, scope }) catch return ErrorSet.WriteError;
}
tags_file_stream.print("\n", .{}) catch return ErrorSet.WriteError;
}
pub fn main() !u8 {
var gpa = std.heap.GeneralPurposeAllocator(.{}){};
defer _ = gpa.deinit();
const allocator = &gpa.allocator;
var args_it = std.process.args();
// storing program name for bash sort helper script
const program_name = try args_it.next(allocator) orelse unreachable;
defer allocator.free(program_name);
var stdout = std.io.getStdOut().writer();
var parsed_files: usize = 0;
while (args_it.next(allocator)) |try_path| {
const path = try try_path;
defer allocator.free(path);
const source = std.fs.cwd().readFileAlloc(allocator, path, std.math.maxInt(usize)) catch |err| {
switch (err) {
error.IsDir => {
std.debug.warn("Input '{s}' is a directory, skipping...\n", .{path});
continue;
},
error.FileNotFound => {
std.debug.warn("Input '{s}' not found, skipping...\n", .{path});
continue;
},
else => {
return err;
},
}
};
defer allocator.free(source);
var tree = try std.zig.parse(allocator, source);
defer tree.deinit();
const node = &tree.root_node.base;
var child_i: usize = 0;
while (node.iterate(child_i)) |child| : (child_i += 1) {
try findTags(allocator, tree, child, path, "", "", stdout);
}
parsed_files += 1;
}
if (parsed_files == 0) {
std.debug.warn("Usage: ztags FILE(s)\n", .{});
std.debug.warn("\nTo sort and speed up large tag files you may want to use the following pipe-able bash script to generate a tags file\n", .{});
try stdout.print(@embedFile("helper.sh"), .{program_name});
return 1;
}
return 0;
} | src/main.zig |
const std = @import("std");
const testing = std.testing;
const bufwriter = @import("bufwriter.zig");
// Takes 0-indexed idx into buffer, and returns the corresponding 1-indexed line and col of said character
// Intended to be used in error-situations
// Returns line and col=0 in in case of invalid input
pub fn idxToLineCol(src: []const u8, idx: usize) struct { line: usize, col: usize, line_start: usize } {
if (idx >= src.len) return .{ .line = 0, .col = 0, .line_start = 0 }; // TODO: throw error?
var l: usize = 1;
var lc: usize = 0;
var ls: usize = 0;
for (src[0 .. idx + 1]) |c, i| {
if (c == '\n') {
l += 1;
lc = 0;
ls = i + 1; // TODO: invalid idx if src ends with nl
continue;
}
lc += 1;
}
return .{ .line = l, .col = lc, .line_start = ls };
}
test "idxToLineCol" {
var buf =
\\0123
\\56
\\
\\9
;
try testing.expectEqual(idxToLineCol(buf[0..], 0), .{ .line = 1, .col = 1, .line_start = 0 });
try testing.expectEqual(idxToLineCol(buf[0..], 3), .{ .line = 1, .col = 4, .line_start = 0 });
try testing.expectEqual(idxToLineCol(buf[0..], 5), .{ .line = 2, .col = 1, .line_start = 5 });
}
pub fn dumpSrcChunkRef(comptime Writer: type, writer: Writer, src: []const u8, start_idx: usize) void {
const writeByte = writer.writeByte;
// Prints the line in which the start-idx resides.
// Assumes idx'es are valid within src-range
// Assumed used for error-scenarios, perf not a priority
const lc = idxToLineCol(src, start_idx);
// Print until from start of line and until end of line/buf whichever comes first
for (src[lc.line_start..]) |c| {
if (c == '\n') break;
writeByte(c) catch {};
}
}
// Take a string and with simple heuristics try to make it more readable (replaces _ with space upon print)
// TODO: Support unicode properly
pub fn printPrettify(comptime Writer: type, writer: Writer, label: []const u8, comptime opts: struct {
do_caps: bool = false,
}) !void {
const State = enum {
space,
plain,
};
var state: State = .space;
for (label) |c| {
var fc = blk: {
switch (state) {
// First char of string or after space
.space => switch (c) {
'_', ' ' => break :blk ' ',
else => {
state = .plain;
break :blk if (opts.do_caps) std.ascii.toUpper(c) else c;
},
},
.plain => switch (c) {
'_', ' ' => {
state = .space;
break :blk ' ';
},
else => break :blk c,
},
}
};
try writer.print("{c}", .{fc});
}
}
test "printPrettify" {
// Setup custom writer with buffer we can inspect
var buf: [128]u8 = undefined;
var bufctx = bufwriter.ArrayBuf{ .buf = buf[0..] };
const writer = bufctx.writer();
try printPrettify(@TypeOf(writer), writer, "label", .{});
try testing.expectEqualStrings("label", bufctx.slice());
bufctx.reset();
try printPrettify(@TypeOf(writer), writer, "label", .{ .do_caps = true });
try testing.expectEqualStrings("Label", bufctx.slice());
bufctx.reset();
try printPrettify(@TypeOf(writer), writer, "label_part", .{});
try testing.expectEqualStrings("label part", bufctx.slice());
bufctx.reset();
try printPrettify(@TypeOf(writer), writer, "<NAME>", .{});
try testing.expectEqualStrings("Hey Der", bufctx.slice());
bufctx.reset();
try printPrettify(@TypeOf(writer), writer, "æøå_æøå", .{}); // Att: unicode not handled
try testing.expectEqualStrings("æøå æøå", bufctx.slice());
bufctx.reset();
// Not working
// try printPrettify(@TypeOf(writer), writer, "æøå_æøå", .{.do_caps=true}); // Att: unicode not handled
// try testing.expectEqualStrings("Æøå Æøå", bufctx.slice());
// bufctx.reset();
}
pub const Color = struct {
r: f16,
g: f16,
b: f16,
a: f16,
fn hexToFloat(color: []const u8) f16 {
std.debug.assert(color.len == 2);
var buf: [1]u8 = undefined;
_ = std.fmt.hexToBytes(buf[0..], color) catch 0;
return @intToFloat(f16, buf[0]) / 255;
}
pub fn fromHexstring(color: []const u8) Color {
std.debug.assert(color.len == 7 or color.len == 9);
// const
if (color.len == 7) {
return .{
.r = hexToFloat(color[1..3]),
.g = hexToFloat(color[3..5]),
.b = hexToFloat(color[5..7]),
.a = 1.0,
};
} else {
return .{
.r = hexToFloat(color[1..3]),
.g = hexToFloat(color[3..5]),
.b = hexToFloat(color[5..7]),
.a = hexToFloat(color[7..9]),
};
}
}
pub fn write(_: *Color, writer: anytype) void {
writer.print("#{s}{s}{s}", .{ "FF", "00", "00" }) catch unreachable;
}
};
test "Color.fromHexstring" {
var c1 = Color.fromHexstring("#FFFFFF");
try testing.expectApproxEqAbs(@as(f16, 1.0), c1.r, 0.01);
try testing.expectApproxEqAbs(@as(f16, 1.0), c1.g, 0.01);
try testing.expectApproxEqAbs(@as(f16, 1.0), c1.b, 0.01);
try testing.expectApproxEqAbs(@as(f16, 1.0), c1.a, 0.01);
var c2 = Color.fromHexstring("#006699FF");
try testing.expectApproxEqAbs(@as(f16, 0.0), c2.r, 0.01);
try testing.expectApproxEqAbs(@as(f16, 0.4), c2.g, 0.01);
try testing.expectApproxEqAbs(@as(f16, 0.6), c2.b, 0.01);
try testing.expectApproxEqAbs(@as(f16, 1.0), c2.a, 0.01);
}
/// Checks for string-needle in a string-haystack. TBD: Can generalize.
pub fn any(comptime haystack: [][]const u8, needle: []const u8) bool {
var found_any = false;
inline for (haystack) |candidate| {
if (std.mem.eql(u8, candidate, needle)) {
found_any = true;
}
}
return found_any;
}
test "any" {
comptime var haystack = [_][]const u8{"label"};
try testing.expect(any(haystack[0..], "label"));
try testing.expect(!any(haystack[0..], "lable"));
}
/// Returns the slice which is without the last path-segment - but including any path-separator
pub fn getParent(fileOrDir: []const u8) []const u8 {
if(fileOrDir.len == 0) return fileOrDir[0..];
var i: usize = fileOrDir.len - 1;
while (i > 0) : (i -= 1) {
if (fileOrDir[i] == '/' or fileOrDir[i] == '\\') {
break;
}
} else {
return fileOrDir[0..0];
}
return fileOrDir[0..i+1];
}
test "getParent" {
try testing.expectEqualStrings("", getParent("myfile"));
try testing.expectEqualStrings("folder/", getParent("folder/file"));
}
/// Combines the detected folder-segment of base_path with sub_path.
pub fn pathRelativeTo(scrap: []u8, base_path: []const u8, sub_path: []const u8) ![]const u8 {
var parent = getParent(base_path);
std.mem.copy(u8, scrap, parent);
std.mem.copy(u8, scrap[parent.len..], sub_path);
return scrap[0..parent.len+sub_path.len];
}
test "pathRelativeTo" {
var scrap: [256]u8 = undefined;
try testing.expectEqualStrings("", try pathRelativeTo(scrap[0..], "", ""));
try testing.expectEqualStrings("relativebase/anotherfile", try pathRelativeTo(scrap[0..], "relativebase/file.txt", "anotherfile"));
try testing.expectEqualStrings("relativebase/anotherfile", try pathRelativeTo(scrap[0..], "relativebase/", "anotherfile"));
try testing.expectEqualStrings("anotherfile", try pathRelativeTo(scrap[0..], "justfile", "anotherfile"));
try testing.expectEqualStrings("relativebase\\anotherfile", try pathRelativeTo(scrap[0..], "relativebase\\file.txt", "anotherfile"));
try testing.expectEqualStrings("relativebase\\anotherfile", try pathRelativeTo(scrap[0..], "relativebase\\", "anotherfile"));
try testing.expectEqualStrings("relativebase\\", try pathRelativeTo(scrap[0..], "relativebase\\", ""));
} | libdaya/src/utils.zig |
const std = @import("std");
const tools = @import("tools");
const with_trace = false;
fn trace(comptime fmt: []const u8, args: anytype) void {
if (with_trace) std.debug.print(fmt, args);
}
const assert = std.debug.assert;
pub const main = tools.defaultMain("2021/day25.txt", run);
pub fn run(input: []const u8, gpa: std.mem.Allocator) tools.RunError![2][]const u8 {
const stride = std.mem.indexOfScalar(u8, input, '\n').? + 1;
const height = @intCast(u32, (input.len + 1) / stride);
const width = @intCast(u32, stride - 1);
trace("input: {}x{}\n", .{ width, height });
const ans1 = ans: {
const map = try gpa.dupe(u8, input);
defer gpa.free(map);
const tmp = try gpa.dupe(u8, input);
defer gpa.free(tmp);
var gen: u32 = 0;
var dirty = true;
while (dirty) : (gen += 1) {
dirty = false;
trace("== gen:{} ==\n{s}\n", .{ gen, map });
{
// horiz
var y: u32 = 0;
while (y < height) : (y += 1) {
var x: u32 = 0;
while (x < width) : (x += 1) {
const x1 = (x + 1) % width;
tmp[x + y * stride] = if (map[x + y * stride] == '>' and map[x1 + y * stride] == '.') 'm' else '.';
}
}
y = 0;
while (y < height) : (y += 1) {
var x: u32 = 0;
while (x < width) : (x += 1) {
if (tmp[x + y * stride] == 'm') {
const x1 = (x + 1) % width;
assert(map[x + y * stride] == '>');
assert(map[x1 + y * stride] == '.');
map[x1 + y * stride] = '>';
map[x + y * stride] = '.';
dirty = true;
}
}
}
}
{
// vert
var y: u32 = 0;
while (y < height) : (y += 1) {
var x: u32 = 0;
while (x < width) : (x += 1) {
const y1 = (y + 1) % height;
tmp[x + y * stride] = if (map[x + y * stride] == 'v' and map[x + y1 * stride] == '.') 'm' else '.';
}
}
y = 0;
while (y < height) : (y += 1) {
var x: u32 = 0;
while (x < width) : (x += 1) {
if (tmp[x + y * stride] == 'm') {
const y1 = (y + 1) % height;
assert(map[x + y * stride] == 'v');
assert(map[x + y1 * stride] == '.');
map[x + y1 * stride] = 'v';
map[x + y * stride] = '.';
dirty = true;
}
}
}
}
}
break :ans gen;
};
const ans2 = "gratis";
return [_][]const u8{
try std.fmt.allocPrint(gpa, "{}", .{ans1}),
try std.fmt.allocPrint(gpa, "{s}", .{ans2}),
};
}
test {
{
const res = try run(
\\v...>>.vv>
\\.vv>>.vv..
\\>>.>v>...v
\\>>v>>.>.v.
\\v>v.vv.v..
\\>.>>..v...
\\.vv..>.>v.
\\v.v..>>v.v
\\....v..v.>
, std.testing.allocator);
defer std.testing.allocator.free(res[0]);
defer std.testing.allocator.free(res[1]);
try std.testing.expectEqualStrings("58", res[0]);
try std.testing.expectEqualStrings("gratis", res[1]);
}
} | 2021/day25.zig |
const std = @import("std");
const Allocator = std.mem.Allocator;
const builtin = @import("builtin");
const zfetch = @import("zfetch");
pub fn requestGet(allocator: Allocator, url: []const u8) ![]const u8 {
var headers = zfetch.Headers.init(allocator);
defer headers.deinit();
try headers.appendValue("Accept", "application/json");
var req = try zfetch.Request.init(allocator, url, null);
defer req.deinit();
try req.do(.GET, headers, null);
if (req.status.code != 200) {
std.log.err("request return status code: {}: {s}\n", .{ req.status.code, req.status.reason });
std.process.exit(1);
}
const reader = req.reader();
var buf: [1024]u8 = undefined;
var source = std.ArrayList(u8).init(allocator);
defer source.deinit();
while (true) {
const read = try reader.read(&buf);
if (read == 0) break;
try source.appendSlice(buf[0..read]);
}
return source.toOwnedSlice();
}
pub const Color = enum {
red,
green,
yellow,
blue,
purple,
};
const windows = std.os.windows;
pub const ConsoleStyle = struct {
f: std.fs.File,
attrs: AttrType(),
fn AttrType() type {
return switch (builtin.os.tag) {
.windows => windows.WORD,
else => void,
};
}
const Self = @This();
pub fn init(f: std.fs.File) Self {
const attrs: AttrType() = blk: {
switch (builtin.os.tag) {
.windows => {
var info: windows.CONSOLE_SCREEN_BUFFER_INFO = undefined;
_ = windows.kernel32.GetConsoleScreenBufferInfo(f.handle, &info);
_ = windows.kernel32.SetConsoleOutputCP(65001);
break :blk info.wAttributes;
},
else => break :blk {},
}
};
return .{
.f = f,
.attrs = attrs,
};
}
pub fn setColor(self: *const Self, color: Color) !void {
if (builtin.os.tag == .windows) {
const col: u16 = switch (color) {
.red => windows.FOREGROUND_RED,
.green => windows.FOREGROUND_GREEN,
.blue => windows.FOREGROUND_BLUE,
.yellow => windows.FOREGROUND_RED | windows.FOREGROUND_GREEN,
.purple => windows.FOREGROUND_RED | windows.FOREGROUND_BLUE,
};
try self.setAttrWin(col);
} else {
const code = switch (color) {
.red => "31;1",
.green => "32;1",
.yellow => "33;1",
.blue => "34;1",
.purple => "35;1",
};
try self.writeCodeAscii(code);
}
}
pub fn setBold(self: *const Self) !void {
if (builtin.os.tag == .windows) {
try self.setAttrWin(windows.FOREGROUND_INTENSITY);
} else {
try self.writeCodeAscii("1");
}
}
pub fn reset(self: *const Self) !void {
if (builtin.os.tag == .windows) {
try self.setAttrWin(self.attrs);
} else {
try self.writeCodeAscii("0");
}
}
fn setAttrWin(self: *const Self, attr: windows.WORD) !void {
try windows.SetConsoleTextAttribute(self.f.handle, attr);
}
fn writeCodeAscii(self: *const Self, code: []const u8) !void {
try self.f.writer().print("\x1b[{s}m", .{code});
}
}; | src/utils.zig |
const std = @import("std");
const Allocator = std.mem.Allocator;
const List = std.ArrayList;
const Map = std.AutoHashMap;
const StrMap = std.StringHashMap;
const BitSet = std.DynamicBitSet;
const PriorityQueue = std.PriorityQueue;
const Str = []const u8;
const util = @import("util.zig");
const gpa = util.gpa;
// const data = @embedFile("../data/test/day15.txt");
const data = @embedFile("../data/puzzle/day15.txt");
const Coord = struct {
const Self = @This();
x: usize,
y: usize,
risk: u64,
fn cmp(a: Self, b: Self) std.math.Order {
return std.math.order(a.risk, b.risk);
}
};
fn cycle(a: u64, b: u64) u64 {
return (a + b - 1) % 9 + 1;
}
pub fn main() !void {
var map = std.mem.zeroes([500][500]u64);
var risk: [500][500]u64 = undefined;
var queue = PriorityQueue(Coord).init(gpa, Coord.cmp);
defer queue.deinit();
var lines = tokenize(data, "\n\r");
var idx: usize = 0;
var n: usize = 0;
var m: usize = 0;
while (lines.next()) |line| : (idx += 1) {
m = line.len;
n = max(idx + 1, n);
}
print("{} {}\n", .{ n, m });
idx = 0;
lines = tokenize(data, "\n\r");
while (lines.next()) |line| : (idx += 1) {
for (line) |cell, jdx| {
map[idx][jdx] = cell - '0';
risk[idx][jdx] = 9999999999999;
var offx: usize = 0;
while (offx < 5) : (offx += 1) {
var offy: usize = 0;
while (offy < 5) : (offy += 1) {
var tile = offx + offy;
if (offx == 0 and offy == 0) continue;
var ax = idx + n * offx;
var ay = jdx + m * offy;
map[ax][ay] = cycle(map[idx][jdx], tile);
risk[ax][ay] = 9999999999999;
}
}
// break :outer;
}
}
print("Made map!\n", .{});
try queue.add(.{ .x = 0, .y = 0, .risk = 0 });
var nn = n * 5;
var mm = m * 5;
while (risk[n * 5 - 1][m * 5 - 1] == 9999999999999) {
var next = queue.remove();
if (risk[next.x][next.y] != 9999999999999) continue;
risk[next.x][next.y] = next.risk;
if (next.x > 0 and risk[next.x - 1][next.y] > next.risk + map[next.x - 1][next.y]) {
try queue.add(.{ .x = next.x - 1, .y = next.y, .risk = next.risk + map[next.x - 1][next.y] });
}
if (next.x < nn - 1 and risk[next.x + 1][next.y] > next.risk + map[next.x + 1][next.y]) {
try queue.add(.{ .x = next.x + 1, .y = next.y, .risk = next.risk + map[next.x + 1][next.y] });
}
if (next.y > 0 and risk[next.x][next.y - 1] > next.risk + map[next.x][next.y - 1]) {
try queue.add(.{ .x = next.x, .y = next.y - 1, .risk = next.risk + map[next.x][next.y - 1] });
}
if (next.y < mm - 1 and risk[next.x][next.y + 1] > next.risk + map[next.x][next.y + 1]) {
try queue.add(.{ .x = next.x, .y = next.y + 1, .risk = next.risk + map[next.x][next.y + 1] });
}
}
print("{}\n", .{risk[n - 1][m - 1]});
print("{}\n", .{risk[n * 5 - 1][m * 5 - 1]});
}
// Useful stdlib functions
const tokenize = std.mem.tokenize;
const split = std.mem.split;
const indexOf = std.mem.indexOfScalar;
const indexOfAny = std.mem.indexOfAny;
const indexOfStr = std.mem.indexOfPosLinear;
const lastIndexOf = std.mem.lastIndexOfScalar;
const lastIndexOfAny = std.mem.lastIndexOfAny;
const lastIndexOfStr = std.mem.lastIndexOfLinear;
const trim = std.mem.trim;
const sliceMin = std.mem.min;
const sliceMax = std.mem.max;
const parseInt = std.fmt.parseInt;
const parseFloat = std.fmt.parseFloat;
const min = std.math.min;
const min3 = std.math.min3;
const max = std.math.max;
const max3 = std.math.max3;
const print = std.debug.print;
const assert = std.debug.assert;
const sort = std.sort.sort;
const asc = std.sort.asc;
const desc = std.sort.desc; | src/day15.zig |
const std = @import("std");
const assert = std.debug.assert;
const warn = std.debug.warn;
const ModelData = @import("../ModelFiles/ModelFiles.zig").ModelData;
const VertexAttributeType = ModelData.VertexAttributeType;
const Buffer = @import("../WindowGraphicsInput/WindowGraphicsInput.zig").Buffer;
const VertexMeta = @import("../WindowGraphicsInput/WindowGraphicsInput.zig").VertexMeta;
const ShaderInstance = @import("Shader.zig").ShaderInstance;
const Matrix = @import("../Mathematics/Mathematics.zig").Matrix;
const wgi = @import("../WindowGraphicsInput/WindowGraphicsInput.zig");
const Texture2D = @import("Texture2D.zig").Texture2D;
const Animation = @import("Animation.zig").Animation;
const rtrenderengine = @import("RTRenderEngine.zig");
const getSettings = rtrenderengine.getSettings;
const min = std.math.min;
const ReferenceCounter = @import("../RefCount.zig").ReferenceCounter;
const Asset = @import("../Assets/Assets.zig").Asset;
const Mesh = @import("Mesh.zig").Mesh;
pub const MeshRenderer = struct {
ref_count: ReferenceCounter = ReferenceCounter{},
mesh: ?*Mesh,
vao: VertexMeta,
max_vertex_lights: u32 = 8,
max_fragment_lights: u32 = 4,
// Allow for objects that have different scale values in different axis
// E.g. An object can be stretched by 2 units in the X axis only
// Skeletal animation does not work when this is enabled
non_uniform_scale: bool = false,
recieve_shadows: bool = true,
enable_specular_light: bool = true,
enable_point_lights: bool = true,
enable_directional_lights: bool = true,
enable_spot_lights: bool = true,
// Used when too many lights are affecting an object.
// Only works for smallish objects such as players.
// Should be disabled for large objects such as terrain.
enable_per_object_light: bool = true,
pub const Material = struct {
// DO NOT SET THESE VARIABLES USE fn setTexture AND fn setNormalMap
texture: ?*Texture2D = null,
normal_map: ?*Texture2D = null,
pub fn setTexture(self: *Material, texture: ?*Texture2D) void {
ReferenceCounter.set(Texture2D, &self.texture, texture);
}
pub fn setNormalMap(self: *Material, normal_map: ?*Texture2D) void {
ReferenceCounter.set(Texture2D, &self.normal_map, normal_map);
}
pub fn freeTexturesIfUnused(self: *Material) void {
if (self.texture != null) {
self.texture.?.ref_count.dec();
self.texture.?.freeIfUnused();
}
if (self.normal_map != null) {
self.normal_map.?.ref_count.dec();
self.normal_map.?.freeIfUnused();
}
}
colour_override: ?[3]f32 = null,
specular_size: f32 = 0.05, // 0 - 1
specular_intensity: f32 = 1.0,
specular_colourisation: f32 = 0.025, // 0 = white, 1 = colour of light source
flat_shading: bool = false,
};
// Use as few materials as possible to reduce draw calls
// Materials here map directly to the materials in the mesh's model file
materials: [32]Material = [1]Material{Material{}} ** 32,
animation_object: ?*Animation = null,
pub fn init(mesh: *Mesh, allocator: *std.mem.Allocator) !MeshRenderer {
mesh.ref_count.inc();
errdefer mesh.ref_count.dec();
var inputs: []VertexMeta.VertexInput = try allocator.alloc(VertexMeta.VertexInput, mesh.model.attributes_count);
defer allocator.free(inputs);
const interleaved = mesh.model.interleaved;
const stride = if (interleaved) mesh.model.vertex_size else 0;
const vertCount = mesh.model.vertex_count;
var attr: u3 = 0;
var i: u32 = 0;
var offset: u32 = 0;
while (attr < 7) : (attr += 1) {
if ((mesh.model.attributes_bitmap & (@as(u8, 1) << attr)) != 0) {
inputs[i].offset = offset;
inputs[i].stride = stride;
inputs[i].source = &mesh.vertex_data_buffer;
if (attr == @enumToInt(VertexAttributeType.Position)) {
// positions
inputs[i].componentCount = 3;
inputs[i].dataType = VertexMeta.VertexInput.DataType.Float;
inputs[i].dataElementSize = 4;
inputs[i].signed = true;
inputs[i].normalised = false;
offset += if (interleaved) (3 * 4) else (vertCount * 3 * 4);
} else {
if (attr == @enumToInt(VertexAttributeType.Colour)) {
// colours
inputs[i].componentCount = 4;
inputs[i].dataType = VertexMeta.VertexInput.DataType.IntegerToFloat;
inputs[i].dataElementSize = 1;
inputs[i].signed = false;
inputs[i].normalised = true;
} else if (attr == @enumToInt(VertexAttributeType.TextureCoordinates)) {
// tex coords
inputs[i].componentCount = 2;
inputs[i].dataType = VertexMeta.VertexInput.DataType.IntegerToFloat;
inputs[i].dataElementSize = 2;
inputs[i].signed = false;
inputs[i].normalised = true;
} else if (attr == @enumToInt(VertexAttributeType.Normal)) {
// normals
inputs[i].componentCount = 0;
inputs[i].dataType = VertexMeta.VertexInput.DataType.CompactInts;
inputs[i].signed = true;
inputs[i].normalised = true;
} else if (attr == @enumToInt(VertexAttributeType.BoneIndices)) {
// bone indices
inputs[i].componentCount = 4;
inputs[i].dataType = VertexMeta.VertexInput.DataType.Integer;
inputs[i].dataElementSize = 1;
inputs[i].signed = false;
} else if (attr == @enumToInt(VertexAttributeType.BoneWeights)) {
// bone weights
inputs[i].componentCount = 4;
inputs[i].dataType = VertexMeta.VertexInput.DataType.IntegerToFloat;
inputs[i].dataElementSize = 1;
inputs[i].signed = false;
inputs[i].normalised = true;
} else if (attr == @enumToInt(VertexAttributeType.Tangent)) {
// tangents
inputs[i].componentCount = 0;
inputs[i].dataType = VertexMeta.VertexInput.DataType.CompactInts;
inputs[i].signed = true;
inputs[i].normalised = true;
}
offset += if (interleaved) 4 else (vertCount * 4);
}
i += 1;
}
}
return MeshRenderer{
.vao = try VertexMeta.init(inputs, if (mesh.index_data_buffer == null) null else &mesh.index_data_buffer.?),
.mesh = mesh,
};
}
pub const DrawData = struct {
mvp_matrix: *const Matrix(f32, 4),
model_matrix: *const Matrix(f32, 4),
model_view_matrix: *const Matrix(f32, 4),
light: [3]f32,
vertex_light_indices: [8]i32,
fragment_light_indices: [4]i32,
fragment_light_matrices: [4]Matrix(f32, 4),
};
pub fn draw(self: *MeshRenderer, draw_data: DrawData, allocator: *std.mem.Allocator) !void {
if (self.mesh == null) {
return error.MeshRendererDestroyed;
}
var shader_config = ShaderInstance.ShaderConfig{
.shadow = false,
.inputs_bitmap = self.mesh.?.model.attributes_bitmap,
.max_vertex_lights = min(self.max_vertex_lights, getSettings().max_vertex_lights),
.max_fragment_lights = min(self.max_fragment_lights, getSettings().max_fragment_lights),
.non_uniform_scale = self.non_uniform_scale,
.recieve_shadows = self.recieve_shadows and getSettings().enable_shadows,
.enable_specular_light = self.enable_specular_light and getSettings().enable_specular_light,
.enable_point_lights = self.enable_point_lights and getSettings().enable_point_lights,
.enable_directional_lights = self.enable_directional_lights and getSettings().enable_directional_lights,
.enable_spot_lights = self.enable_spot_lights and getSettings().enable_spot_lights,
};
var shader: *const ShaderInstance = try ShaderInstance.getShader(shader_config, allocator);
try shader.setMVPMatrix(draw_data.mvp_matrix);
try shader.setModelMatrix(draw_data.model_matrix);
try shader.setModelViewMatrix(draw_data.model_view_matrix);
try shader.setPerObjLight(draw_data.light);
try shader.setVertexLightIndices(draw_data.vertex_light_indices);
try shader.setFragmentLightIndices(draw_data.fragment_light_indices);
try shader.setLightMatrices(draw_data.fragment_light_matrices);
if (self.mesh.?.model.attributes_bitmap & (1 << @enumToInt(ModelData.VertexAttributeType.BoneIndices)) != 0) {
if (self.animation_object == null) {
Animation.setAnimationIdentityMatrices(shader, allocator) catch {
assert(false);
};
} else {
try self.animation_object.?.setAnimationMatrices(shader, self.mesh.?.model);
}
}
if (shader.config.non_uniform_scale) {
const normal_mat = try draw_data.model_view_matrix.decreaseDimension().transpose().inverse();
try shader.setNormalMatrix(&normal_mat);
}
var i: u32 = 0;
while (i < self.mesh.?.model.material_count and i < 32) : (i += 1) {
if (self.materials[i].texture == null) {
try rtrenderengine.getDefaultTexture().bindToUnit(0);
} else {
try self.materials[i].texture.?.texture.bindToUnit(0);
}
if (self.materials[i].normal_map == null) {
try rtrenderengine.getDefaultNormalMap().bindToUnit(1);
} else {
try self.materials[i].normal_map.?.texture.bindToUnit(1);
}
try shader.setSpecularIntensity(self.materials[i].specular_intensity);
try shader.setSpecularSize(self.materials[i].specular_size);
try shader.setSpecularColouration(self.materials[i].specular_colourisation);
try shader.setFlatShadingEnabled(self.materials[i].flat_shading);
var first_index: u32 = undefined;
var index_vertex_count: u32 = undefined;
var utf8_name: []const u8 = undefined;
var colour: [3]f32 = undefined;
self.mesh.?.model.getMaterial(i, &first_index, &index_vertex_count, &colour, &utf8_name) catch break;
if (self.materials[i].colour_override == null) {
try shader.setColour(colour);
} else {
try shader.setColour(self.materials[i].colour_override.?);
}
if (index_vertex_count > 0) {
shader.validate(allocator);
if (self.mesh.?.index_data_buffer == null) {
try self.vao.draw(VertexMeta.PrimitiveType.Triangles, first_index, index_vertex_count);
} else {
try self.vao.drawWithIndices(VertexMeta.PrimitiveType.Triangles, self.mesh.?.model.vertex_count > 65536, first_index, index_vertex_count);
}
}
}
}
// For shadow maps
pub fn drawDepthOnly(self: *MeshRenderer, allocator: *std.mem.Allocator, mvp_matrix: *const Matrix(f32, 4), model_matrix: *const Matrix(f32, 4)) !void {
if (self.mesh == null) {
return error.MeshRendererDestroyed;
}
var shader_config = ShaderInstance.ShaderConfig{
.shadow = true,
.inputs_bitmap = self.mesh.?.model.attributes_bitmap,
// Not used for shadows
.max_vertex_lights = 0,
.max_fragment_lights = 0,
.non_uniform_scale = self.non_uniform_scale,
.recieve_shadows = false,
.enable_specular_light = false,
.enable_point_lights = false,
.enable_directional_lights = false,
.enable_spot_lights = false,
};
var shader: *const ShaderInstance = try ShaderInstance.getShader(shader_config, allocator);
try shader.setMVPMatrix(mvp_matrix);
try shader.setModelMatrix(model_matrix);
// try shader.setModelViewMatrix(model_view_matrix);
if (self.mesh.?.model.attributes_bitmap & (1 << @enumToInt(ModelData.VertexAttributeType.BoneIndices)) != 0) {
if (self.animation_object == null) {
Animation.setAnimationIdentityMatrices(shader, allocator) catch {
assert(false);
};
} else {
try self.animation_object.?.setAnimationMatrices(shader, self.mesh.?.model);
}
}
var first_index: u32 = 0;
var index_count: u32 = 0;
var utf8_name: []const u8 = undefined;
var colour: [3]f32 = undefined;
var i: u32 = 0;
while (i < self.mesh.?.model.material_count and i < 32) : (i += 1) {
var first_index_: u32 = undefined;
var index_count_: u32 = undefined;
self.mesh.?.model.getMaterial(i, &first_index_, &index_count_, &colour, &utf8_name) catch break;
var do_draw: bool = false;
if (first_index_ == first_index + index_count) {
index_count += index_count_;
if (i < self.mesh.?.model.material_count - 1 and i < 32 - 1) {
continue;
} else {
do_draw = true;
}
} else {
do_draw = true;
}
if (do_draw) {
if (index_count > 0) {
if (self.mesh.?.index_data_buffer == null) {
try self.vao.draw(VertexMeta.PrimitiveType.Triangles, first_index, index_count);
} else {
try self.vao.drawWithIndices(VertexMeta.PrimitiveType.Triangles, self.mesh.?.model.vertex_count > 65536, first_index, index_count);
}
}
first_index = first_index_;
index_count = index_count_;
}
}
}
pub fn setAnimationObject(self: *MeshRenderer, animation_object: *Animation) void {
ReferenceCounter.set(Animation, &self.animation_object, animation_object);
}
pub fn free(self: *MeshRenderer) void {
self.ref_count.deinit();
if (self.mesh != null) {
self.mesh.?.ref_count.dec();
self.mesh = null;
var i: u32 = 0;
while (i < 32) : (i += 1) {
self.materials[i].setTexture(null);
self.materials[i].setNormalMap(null);
}
}
}
// Frees mesh and textures if they become unused
pub fn freeIfUnused(self: *MeshRenderer) void {
if (self.ref_count.n != 0 or self.mesh == null) {
return;
}
self.mesh.?.ref_count.dec();
self.mesh.?.freeIfUnused();
self.mesh = null;
var i: u32 = 0;
while (i < 32) : (i += 1) {
self.materials[i].freeTexturesIfUnused();
}
if (self.animation_object != null) {
self.animation_object.?.ref_count.dec();
self.animation_object.?.freeIfUnused();
}
}
}; | src/RTRenderEngine/MeshRenderer.zig |
const std = @import("std");
pub const simd = @import("utils/simd.zig");
pub fn readStruct(comptime T: type, instance: *T, reader: anytype, comptime expected_size: usize) !void {
const fields = std.meta.fields(T);
var buf: [expected_size]u8 = undefined;
const read = try reader.readAll(&buf);
if (read != expected_size) return error.EndOfStream;
comptime var index = 0;
inline for (fields) |field| {
const child = field.field_type;
switch (@typeInfo(child)) {
.Struct => |data| {
if (data.layout == .Packed) {
const Int = std.meta.Int(.unsigned, @sizeOf(child) * 8);
@field(instance, field.name) = @bitCast(field.field_type, std.mem.readIntLittle(Int, buf[index..][0..@sizeOf(Int)]));
index += @sizeOf(Int);
} else {
const Int = @typeInfo(@TypeOf(child.read)).Fn.args[0].arg_type.?;
@field(instance, field.name) = child.read(std.mem.readIntLittle(Int, buf[index..][0..@sizeOf(Int)]));
index += @sizeOf(Int);
}
},
.Enum => |data| {
@field(instance, field.name) = @intToEnum(child, std.mem.readIntLittle(data.tag_type, buf[index..][0..@sizeOf(data.tag_type)]));
index += @sizeOf(data.tag_type);
},
.Int => {
@field(instance, field.name) = std.mem.readIntLittle(child, buf[index..][0..@sizeOf(child)]);
index += @sizeOf(child);
},
.Array => |data| {
if (data.child == u8) {
@field(instance, field.name) = buf[index..][0 .. @sizeOf(data.child) * data.len].*;
index += @sizeOf(data.child) * data.len;
} else unreachable;
},
else => unreachable,
}
}
if (index != expected_size) @compileError("invalid size");
}
pub fn LimitedReader(comptime ReaderType: type) type {
return struct {
unlimited_reader: ReaderType,
limit: usize,
pos: usize = 0,
pub const Error = ReaderType.Error;
pub const Reader = std.io.Reader(*Self, Error, read);
const Self = @This();
pub fn init(unlimited_reader: ReaderType, limit: usize) Self {
return .{
.unlimited_reader = unlimited_reader,
.limit = limit,
};
}
fn read(self: *Self, dest: []u8) Error!usize {
if (self.pos >= self.limit) return 0;
const left = std.math.min(self.limit - self.pos, dest.len);
const num_read = try self.unlimited_reader.read(dest[0..left]);
self.pos += num_read;
return num_read;
}
pub fn reader(self: *Self) Reader {
return .{ .context = self };
}
};
} | src/utils.zig |
const std = @import("std");
const mem = @import("../std.zig").mem;
const testing = std.testing;
const debug = std.debug;
pub fn ArrayList(comptime T: type) type {
return ArrayListCustomAllocator(mem.Allocator, T);
}
pub fn AlignedArrayList(comptime T: type, comptime A: u29) type {
return AlignedArrayListCustomAllocator(mem.Allocator, T, A);
}
pub fn ArrayListCustomAllocator(comptime Allocator: type, comptime T: type) type {
return AlignedArrayListCustomAllocator(Allocator, T, @alignOf(T));
}
pub fn AlignedArrayListCustomAllocator(comptime Allocator: type, comptime T: type, comptime A: u29) type {
return struct {
const Self = @This();
const Inner = AlignedArrayListNoAllocator(T, A);
inner: Inner = Inner{},
allocator: Allocator,
pub fn deinit(self: *Self) void {
self.inner.deinit(self.allocator);
}
pub fn count(self: Self) usize {
return self.inner.count();
}
pub fn capacity(self: Self) usize {
return self.inner.capacity();
}
pub fn append(self: *Self, item: T) !void {
try self.inner.append(self.allocator, item);
}
pub fn addOne(self: *Self) !*T {
return try self.inner.addOne(self.allocator);
}
pub fn addOneAssumeCapacity(self: *Self) *T {
return self.inner.addOneAssumeCapacity();
}
pub fn ensureCapacity(self: *Self, new_capacity: usize) !void {
return self.inner.ensureCapacity(self.allocator, new_capacity);
}
};
}
pub fn ArrayListNoAllocator(comptime T: type) type {
return AlignedArrayListNoAllocator(T, @alignOf(T));
}
pub fn AlignedArrayListNoAllocator(comptime T: type, comptime A: u29) type {
return struct {
const Self = @This();
items: []align(A) T = &[_]T{},
len: usize = 0,
pub fn deinit(self: *Self, allocator: var) void {
mem.free(allocator, self.items);
self.* = undefined;
}
pub fn count(self: Self) usize {
return self.len;
}
pub fn capacity(self: Self) usize {
return self.items.len;
}
pub fn append(self: *Self, allocator: var, item: T) !void {
const new_item_ptr = try self.addOne(allocator);
new_item_ptr.* = item;
}
pub fn addOne(self: *Self, allocator: var) !*T {
const new_length = self.len + 1;
try self.ensureCapacity(allocator, new_length);
return self.addOneAssumeCapacity();
}
pub fn addOneAssumeCapacity(self: *Self) *T {
debug.assert(self.count() < self.capacity());
defer self.len += 1;
return &self.items[self.len];
}
pub fn ensureCapacity(self: *Self, allocator: var, new_capacity: usize) !void {
var better_capacity = self.capacity();
if (better_capacity >= new_capacity)
return;
while (true) {
better_capacity += better_capacity / 2 + 8;
if (better_capacity >= new_capacity)
break;
}
self.items = try mem.alignedRealloc(allocator, T, A, self.items, better_capacity);
}
};
}
test "std.ArrayList.init" {
var bytes: [1024]u8 = undefined;
var fba = mem.FixedBufferAllocator{ .buffer = bytes[0..] };
var list = ArrayList(i32){ .allocator = mem.Allocator.init(&fba) };
defer list.deinit();
testing.expectEqual(@as(usize, 0), list.count());
testing.expectEqual(@as(usize, 0), list.capacity());
}
test "std.ArrayList.basic" {
var bytes: [1024]u8 = undefined;
var fba = mem.FixedBufferAllocator{ .buffer = bytes[0..] };
var list = ArrayList(i32){ .allocator = mem.Allocator.init(&fba) };
defer list.deinit();
{
var i: usize = 0;
while (i < 10) : (i += 1) {
list.append(@intCast(i32, i + 1)) catch @panic("");
}
}
{
var i: usize = 0;
while (i < 10) : (i += 1) {
testing.expectEqual(@intCast(i32, i + 1), list.inner.items[i]);
}
}
} | src/array_list.zig |
const std = @import("std");
const Camera = @import("Camera.zig");
const Material = @import("Material.zig");
const Mesh = @import("Mesh.zig");
const zp = @import("../../zplay.zig");
const drawcall = zp.graphics.common.drawcall;
const VertexArray = zp.graphics.common.VertexArray;
const alg = zp.deps.alg;
const Vec3 = alg.Vec3;
const Mat4 = alg.Mat4;
const Renderer = @This();
// The type erased pointer to the renderer implementation
ptr: *anyopaque,
vtable: *const VTable,
pub const VTable = struct {
/// begin using renderer
beginFn: fn (ptr: *anyopaque) void,
/// stop using renderer
endFn: fn (ptr: *anyopaque) void,
/// generic rendering
renderFn: fn (
ptr: *anyopaque,
vertex_array: VertexArray,
use_elements: bool,
primitive: drawcall.PrimitiveType,
offset: u32,
count: u32,
model: Mat4,
projection: Mat4,
camera: ?Camera,
material: ?Material,
instance_count: ?u32,
) anyerror!void,
/// mesh rendering
renderMeshFn: fn (
ptr: *anyopaque,
mesh: Mesh,
model: Mat4,
projection: Mat4,
camera: ?Camera,
material: ?Material,
instance_count: ?u32,
) anyerror!void,
};
pub fn init(
pointer: anytype,
comptime beginFn: fn (ptr: @TypeOf(pointer)) void,
comptime endFn: fn (ptr: @TypeOf(pointer)) void,
comptime renderFn: fn (
ptr: @TypeOf(pointer),
vertex_array: VertexArray,
use_elements: bool,
primitive: drawcall.PrimitiveType,
offset: u32,
count: u32,
model: Mat4,
projection: Mat4,
camera: ?Camera,
material: ?Material,
instance_count: ?u32,
) anyerror!void,
comptime renderMeshFn: fn (
ptr: @TypeOf(pointer),
mesh: Mesh,
model: Mat4,
projection: Mat4,
camera: ?Camera,
material: ?Material,
instance_count: ?u32,
) anyerror!void,
) Renderer {
const Ptr = @TypeOf(pointer);
const ptr_info = @typeInfo(Ptr);
std.debug.assert(ptr_info == .Pointer); // Must be a pointer
std.debug.assert(ptr_info.Pointer.size == .One); // Must be a single-item pointer
const alignment = ptr_info.Pointer.alignment;
const gen = struct {
fn beginImpl(ptr: *anyopaque) void {
const self = @ptrCast(Ptr, @alignCast(alignment, ptr));
return @call(.{ .modifier = .always_inline }, beginFn, .{self});
}
fn endImpl(ptr: *anyopaque) void {
const self = @ptrCast(Ptr, @alignCast(alignment, ptr));
return @call(.{ .modifier = .always_inline }, endFn, .{self});
}
fn renderImpl(
ptr: *anyopaque,
vertex_array: VertexArray,
use_elements: bool,
primitive: drawcall.PrimitiveType,
offset: u32,
count: u32,
model: Mat4,
projection: Mat4,
camera: ?Camera,
material: ?Material,
instance_count: ?u32,
) anyerror!void {
const self = @ptrCast(Ptr, @alignCast(alignment, ptr));
return @call(.{ .modifier = .always_inline }, renderFn, .{
self,
vertex_array,
use_elements,
primitive,
offset,
count,
model,
projection,
camera,
material,
instance_count,
});
}
fn renderMeshImpl(
ptr: *anyopaque,
mesh: Mesh,
model: Mat4,
projection: Mat4,
camera: ?Camera,
material: ?Material,
instance_count: ?u32,
) anyerror!void {
const self = @ptrCast(Ptr, @alignCast(alignment, ptr));
return @call(.{ .modifier = .always_inline }, renderMeshFn, .{
self,
mesh,
model,
projection,
camera,
material,
instance_count,
});
}
const vtable = VTable{
.beginFn = beginImpl,
.endFn = endImpl,
.renderFn = renderImpl,
.renderMeshFn = renderMeshImpl,
};
};
return .{
.ptr = pointer,
.vtable = &gen.vtable,
};
}
pub fn begin(renderer: Renderer) void {
renderer.vtable.beginFn(renderer.ptr);
}
pub fn end(renderer: Renderer) void {
renderer.vtable.endFn(renderer.ptr);
}
pub fn render(
renderer: Renderer,
vertex_array: VertexArray,
use_elements: bool,
primitive: drawcall.PrimitiveType,
offset: u32,
count: u32,
model: Mat4,
projection: Mat4,
camera: ?Camera,
material: ?Material,
instance_count: ?u32,
) anyerror!void {
return renderer.vtable.renderFn(
renderer.ptr,
vertex_array,
use_elements,
primitive,
offset,
count,
model,
projection,
camera,
material,
instance_count,
);
}
/// render a mesh
pub fn renderMesh(
renderer: Renderer,
mesh: Mesh,
model: Mat4,
projection: Mat4,
camera: ?Camera,
material: ?Material,
instance_count: ?u32,
) anyerror!void {
return renderer.vtable.renderMeshFn(
renderer.ptr,
mesh,
model,
projection,
camera,
material,
instance_count,
);
} | src/graphics/3d/Renderer.zig |
const std = @import("std");
const Builder = std.build.Builder;
pub fn build(b: *Builder) void {
const mode = b.standardReleaseOptions();
const exe = b.addExecutable("zua", "src/zua.zig");
exe.setBuildMode(mode);
exe.install();
const run_cmd = exe.run();
run_cmd.step.dependOn(b.getInstallStep());
const run_step = b.step("run", "Run the app");
run_step.dependOn(&run_cmd.step);
var tests = b.addTest("src/zua.zig");
tests.setBuildMode(mode);
const test_step = b.step("test", "Run all tests");
test_step.dependOn(&tests.step);
const fuzzed_lex_inputs_dir_default = "test/corpus/fuzz_llex";
const fuzzed_lex_outputs_dir_default = "test/output/fuzz_llex";
const fuzzed_lex_inputs_dir = b.option([]const u8, "fuzzed_lex_inputs_dir", "Directory with input corpus for fuzzed_lex tests") orelse fuzzed_lex_inputs_dir_default;
const fuzzed_lex_outputs_dir = b.option([]const u8, "fuzzed_lex_outputs_dir", "Directory with expected outputs for fuzzed_lex tests") orelse fuzzed_lex_outputs_dir_default;
const fuzzed_lex_options = b.addOptions();
fuzzed_lex_options.addOption([]const u8, "fuzzed_lex_inputs_dir", fuzzed_lex_inputs_dir);
fuzzed_lex_options.addOption([]const u8, "fuzzed_lex_outputs_dir", fuzzed_lex_outputs_dir);
var fuzzed_lex_tests = b.addTest("test/fuzzed_lex.zig");
fuzzed_lex_tests.setBuildMode(mode);
fuzzed_lex_tests.addOptions("build_options", fuzzed_lex_options);
fuzzed_lex_tests.addPackagePath("zua", "src/zua.zig");
const fuzzed_lex_test_step = b.step("fuzzed_lex", "Test lexer against a fuzzed corpus from fuzzing-lua");
fuzzed_lex_test_step.dependOn(&fuzzed_lex_tests.step);
var bench_lex_tests = b.addTest("test/bench_lex.zig");
bench_lex_tests.setBuildMode(.ReleaseFast);
bench_lex_tests.addOptions("build_options", fuzzed_lex_options);
bench_lex_tests.addPackagePath("zua", "src/zua.zig");
const bench_lex_test_step = b.step("bench_lex", "Bench lexer against a fuzzed corpus from fuzzing-lua");
bench_lex_test_step.dependOn(&bench_lex_tests.step);
const fuzzed_strings_inputs_dir_default = "test/corpus/fuzz_strings";
const fuzzed_strings_outputs_dir_default = "test/output/fuzz_strings";
const fuzzed_strings_gen_dir_default = "test/corpus/fuzz_strings_generated";
const fuzzed_strings_inputs_dir = b.option([]const u8, "fuzzed_strings_inputs_dir", "Directory with input strings for string parsing tests") orelse fuzzed_strings_inputs_dir_default;
const fuzzed_strings_outputs_dir = b.option([]const u8, "fuzzed_strings_outputs_dir", "Directory with output strings for string parsing tests") orelse fuzzed_strings_outputs_dir_default;
const fuzzed_strings_gen_dir = b.option([]const u8, "fuzzed_strings_gen_dir", "Directory to output generated string inputs to") orelse fuzzed_strings_gen_dir_default;
const fuzzed_strings_options = b.addOptions();
fuzzed_strings_options.addOption([]const u8, "fuzzed_strings_inputs_dir", fuzzed_strings_inputs_dir);
fuzzed_strings_options.addOption([]const u8, "fuzzed_strings_outputs_dir", fuzzed_strings_outputs_dir);
fuzzed_strings_options.addOption([]const u8, "fuzzed_strings_gen_dir", fuzzed_strings_gen_dir);
var fuzzed_strings = b.addTest("test/fuzzed_strings.zig");
fuzzed_strings.setBuildMode(mode);
fuzzed_strings.addOptions("build_options", fuzzed_strings_options);
fuzzed_strings.addPackagePath("zua", "src/zua.zig");
const fuzzed_strings_step = b.step("fuzzed_strings", "Test string parsing against a fuzzed corpus from fuzzing-lua");
fuzzed_strings_step.dependOn(&fuzzed_strings.step);
const fuzzed_strings_gen_options = b.addOptions();
fuzzed_strings_gen_options.addOption([]const u8, "fuzzed_lex_inputs_dir", fuzzed_lex_inputs_dir);
fuzzed_strings_gen_options.addOption([]const u8, "fuzzed_strings_gen_dir", fuzzed_strings_gen_dir);
var fuzzed_strings_gen = b.addExecutable("fuzzed_strings_gen", "test/fuzzed_strings_gen.zig");
fuzzed_strings_gen.setBuildMode(mode);
fuzzed_strings_gen.addOptions("build_options", fuzzed_strings_gen_options);
fuzzed_strings_gen.addPackagePath("zua", "src/zua.zig");
const fuzzed_strings_gen_run_step = b.step("fuzzed_strings_gen_run", "Generate string inputs from a fuzzed corpus of lexer inputs");
fuzzed_strings_gen_run_step.dependOn(&fuzzed_strings_gen.run().step);
const fuzzed_parse_inputs_dir_default = "test/corpus/fuzz_lparser";
const fuzzed_parse_outputs_dir_default = "test/output/fuzz_lparser";
const fuzzed_parse_inputs_dir = b.option([]const u8, "fuzzed_parse_inputs_dir", "Directory with input corpus for fuzzed_parse tests") orelse fuzzed_parse_inputs_dir_default;
const fuzzed_parse_outputs_dir = b.option([]const u8, "fuzzed_parse_outputs_dir", "Directory with expected outputs for fuzzed_parse tests") orelse fuzzed_parse_outputs_dir_default;
const fuzzed_parse_options = b.addOptions();
fuzzed_parse_options.addOption([]const u8, "fuzzed_parse_inputs_dir", fuzzed_parse_inputs_dir);
fuzzed_parse_options.addOption([]const u8, "fuzzed_parse_outputs_dir", fuzzed_parse_outputs_dir);
var fuzzed_parse_tests = b.addTest("test/fuzzed_parse.zig");
fuzzed_parse_tests.setBuildMode(mode);
fuzzed_parse_tests.addOptions("build_options", fuzzed_parse_options);
fuzzed_parse_tests.addPackagePath("zua", "src/zua.zig");
const fuzzed_parse_test_step = b.step("fuzzed_parse", "Test parser against a fuzzed corpus from fuzzing-lua");
fuzzed_parse_test_step.dependOn(&fuzzed_parse_tests.step);
var fuzzed_parse_prune = b.addExecutable("fuzzed_parse_prune", "test/fuzzed_parse_prune.zig");
fuzzed_parse_prune.setBuildMode(mode);
fuzzed_parse_prune.addOptions("build_options", fuzzed_parse_options);
fuzzed_parse_prune.addPackagePath("zua", "src/zua.zig");
const fuzzed_parse_prune_step = b.step("fuzzed_parse_prune", "Prune fuzzed parser corpus to remove lexer-specific error outputs");
fuzzed_parse_prune_step.dependOn(&fuzzed_parse_prune.run().step);
} | build.zig |
usingnamespace @import("root").preamble;
const heap = os.memory.pmm.phys_heap;
const platform = os.platform;
const PagingContext = platform.paging.PagingContext;
const address_space = os.kernel.process.address_space;
const MemoryObjectRegionVtab: address_space.MemoryRegionVtable = .{
.pageFault = MemoryObjectRegion.pageFault,
//.dup = MemoryObjectRegion.dup,
};
fn pageSize() usize {
return os.platform.paging.page_sizes[0];
}
const MemoryObjectRegion = struct {
region: address_space.MemoryRegion = .{
.vtab = &MemoryObjectRegionVtab,
},
memobj: *MemoryObject,
page_perms: os.memory.paging.Perms,
fn pageFault(
region: *address_space.MemoryRegion,
offset: usize,
present: bool,
fault_type: platform.PageFaultAccess,
page_table: *PagingContext,
) address_space.PageFaultError!void {
const self = @fieldParentPtr(@This(), "region", region);
// If this was an access fault, and not a non-present entry, don't handle it
if (present)
return error.RangeRefusedHandling;
const physmem = os.memory.pmm.allocPhys(pageSize()) catch |err| {
switch (err) {
error.PhysAllocTooSmall => unreachable,
else => |q| return q,
}
};
errdefer os.memory.pmm.freePhys(physmem, pageSize());
const page_aligned_offset = lib.util.libalign.alignDown(usize, pageSize(), offset);
{
const phys_ptr = os.platform.phys_ptr([*]u8).from_int(physmem);
var source_data = self.memobj.data[page_aligned_offset..];
if (source_data.len > pageSize())
source_data.len = pageSize();
const data_dest = phys_ptr.get_writeback()[0..pageSize()];
std.mem.copy(u8, data_dest, source_data);
if (source_data.len < pageSize()) {
std.mem.set(u8, data_dest[source_data.len..], 0);
}
}
const vaddr = region.base + page_aligned_offset;
os.memory.paging.mapPhys(.{
.context = page_table,
.virt = vaddr,
.phys = physmem,
.size = pageSize(),
.perm = os.memory.paging.user(self.page_perms),
.memtype = .MemoryWriteBack,
}) catch |err| {
switch (err) {
error.IncompleteMapping, error.PhysAllocTooSmall => unreachable,
error.AlreadyPresent, error.BadAlignment => return error.InternalError,
error.OutOfMemory => return error.OutOfMemory,
}
};
}
fn dup(region: *address_space.MemoryRegion) !*address_space.MemoryRegion {
const self = @fieldParentPtr(@This(), "region", region);
const new = try heap.create(@This());
errdefer heap.destroy(new);
self.memobj.addRef();
errdefer {
if (self.removeRef()) {
unreachable;
}
}
new.* = .{
.memobj = self.memobj,
};
return &new.region;
}
};
pub const MemoryObject = struct {
data: []const u8,
refcount: usize,
page_perms: os.memory.paging.Perms,
pub fn makeRegion(self: *@This()) !*address_space.MemoryRegion {
const region = try heap.create(MemoryObjectRegion);
errdefer heap.destroy(region);
region.* = .{
.memobj = self,
.page_perms = self.page_perms,
};
self.addRef();
errdefer {
if (self.removeRef()) {
unreachable;
}
}
return ®ion.region;
}
fn addRef(self: *@This()) void {
_ = @atomicRmw(usize, &self.refcount, .Add, 1, .AcqRel);
}
fn removeRef(self: *@This()) bool {
return @atomicRmw(usize, &self.refcount, .Sub, 1, .AcqRel) == 1;
}
};
pub fn staticMemoryObject(data: []const u8, page_perms: os.memory.paging.Perms) MemoryObject {
return .{
.data = data,
.refcount = 1, // Permanent 1 reference for keeping alive
.page_perms = page_perms,
};
}
const LazyZeroRegionVtab: address_space.MemoryRegionVtable = .{
.pageFault = LazyZeroRegion.pageFault,
//.dup = LazyZeroRegion.dup,
};
const LazyZeroRegion = struct {
region: address_space.MemoryRegion = .{
.vtab = &LazyZeroRegionVtab,
},
page_perms: os.memory.paging.Perms,
fn pageFault(
region: *address_space.MemoryRegion,
offset: usize,
present: bool,
fault_type: platform.PageFaultAccess,
page_table: *PagingContext,
) address_space.PageFaultError!void {
const self = @fieldParentPtr(@This(), "region", region);
// If this was an access fault, and not a non-present entry, don't handle it
if (present)
return error.RangeRefusedHandling;
const physmem = os.memory.pmm.allocPhys(pageSize()) catch |err| {
switch (err) {
error.PhysAllocTooSmall => unreachable,
else => |q| return q,
}
};
errdefer os.memory.pmm.freePhys(physmem, pageSize());
{
const phys_ptr = os.platform.phys_ptr([*]u8).from_int(physmem);
std.mem.set(u8, phys_ptr.get_writeback()[0..pageSize()], 0);
}
const vaddr = lib.util.libalign.alignDown(usize, pageSize(), region.base + offset);
os.memory.paging.mapPhys(.{
.context = page_table,
.virt = vaddr,
.phys = physmem,
.size = pageSize(),
.perm = os.memory.paging.user(self.page_perms),
.memtype = .MemoryWriteBack,
}) catch |err| {
switch (err) {
error.IncompleteMapping, error.PhysAllocTooSmall => unreachable,
error.AlreadyPresent, error.BadAlignment => return error.InternalError,
error.OutOfMemory => return error.OutOfMemory,
}
};
}
fn dup(region: *address_space.MemoryRegion) !*address_space.MemoryRegion {
const self = @fieldParentPtr(@This(), "region", region);
const new = try heap.create(@This());
errdefer heap.destroy(new);
self.memobj.addRef();
errdefer {
if (self.removeRef()) {
unreachable;
}
}
new.* = .{
.memobj = self.memobj,
};
return &new.region;
}
};
const LazyZeroes = struct {
page_perms: os.memory.paging.Perms,
pub fn makeRegion(self: *@This()) !*address_space.MemoryRegion {
const region = try heap.create(LazyZeroRegion);
errdefer heap.destroy(region);
region.* = .{ .page_perms = self.page_perms };
return ®ion.region;
}
};
pub fn lazyZeroes(page_perms: os.memory.paging.Perms) LazyZeroes {
return .{ .page_perms = page_perms };
} | subprojects/flork/src/kernel/process/memory_object.zig |
const std = @import("std");
const c = std.c;
const json = std.json;
const ldns = @import("zdns");
const testing = std.testing;
pub fn rrFieldNames(type_: ldns.rr_type, ctx: anytype) ![]const []const u8 {
const str = []const u8;
return switch (type_) {
.A, .AAAA => &[_]str{"ip"},
.AFSDB => &[_]str{ "subtype", "hostname" },
.CAA => &[_]str{ "flags", "tag", "value" },
.CERT => &[_]str{ "type", "key_tag", "alg", "cert" },
.CNAME, .DNAME, .NS, .PTR => &[_]str{"dname"},
.DHCID => &[_]str{"data"},
.DLV, .DS, .CDS => &[_]str{ "keytag", "alg", "digest_type", "digest" },
.DNSKEY, .CDNSKEY => &[_]str{ "flags", "protocol", "alg", "public_key", "key_tag" },
.HINFO => &[_]str{ "cpu", "os" },
.IPSECKEY => &[_]str{ "precedence", "alg", "gateway", "public_key" },
.KEY => &[_]str{ "type", "xt", "name_type", "sig", "protocol", "alg", "public_key" },
.KX, .MX => &[_]str{ "preference", "exchange" },
.LOC => &[_]str{ "size", "horiz", "vert", "lat", "lon", "alt" },
.MB, .MG => &[_]str{"madname"},
.MINFO => &[_]str{ "rmailbx", "emailbx" },
.MR => &[_]str{"newname"},
.NAPTR => &[_]str{ "order", "preference", "flags", "services", "regexp", "replacement" },
.NSEC => &[_]str{ "next_dname", "types" },
.NSEC3 => &[_]str{ "hash_alg", "opt_out", "iterations", "salt", "hash", "types" },
.NSEC3PARAM => &[_]str{ "hash_alg", "flags", "iterations", "salt" },
.NXT => &[_]str{ "dname", "types" },
.RP => &[_]str{ "mbox", "txt" },
.RRSIG => &[_]str{ "type_covered", "alg", "labels", "original_ttl", "expiration", "inception", "key_tag", "signers_name", "signature" },
.RT => &[_]str{ "preference", "host" },
.SOA => &[_]str{ "mname", "rname", "serial", "refresh", "retry", "expire", "minimum" },
.SPF => &[_]str{"spf"},
.SRV => &[_]str{ "priority", "weight", "port", "target" },
.SSHFP => &[_]str{ "alg", "fp_type", "fp" },
.TSIG => &[_]str{ "alg", "time", "fudge", "mac", "msgid", "err", "other" },
.TXT => &[_]str{"txt"},
else => {
try ctx.ok(type_.appendStr(ctx.tmp_buf));
try ctx.err_writer.print("unsupported record type: {s}", .{ctx.tmp_buf.data()});
return error.UnsupportedRecordType;
},
};
}
pub fn emitRdf(rdf: *ldns.rdf, ctx: anytype) !void {
const type_ = rdf.get_type();
switch (type_) {
.INT32, .PERIOD => try ctx.out.emitNumber(rdf.int32()),
.INT16 => try ctx.out.emitNumber(rdf.int16()),
.INT8 => try ctx.out.emitNumber(rdf.int8()),
else => {
try ctx.ok(rdf.appendStr(ctx.tmp_buf));
var text = ctx.tmp_buf.data();
switch (type_) {
// strip the trailing dot
.DNAME => text = text[0 .. text.len - 1],
// strip the quotes
.STR => text = text[1 .. text.len - 1],
else => {},
}
try ctx.out.emitString(text);
ctx.tmp_buf.clear();
},
}
}
fn testRdf(type_: ldns.rdf_type, expected_out: []const u8, in: [*:0]const u8) !void {
var outBuf: [4096]u8 = undefined;
var bufStream = std.io.fixedBufferStream(&outBuf);
var out = json.writeStream(bufStream.writer(), 6);
var errBuf: [4096]u8 = undefined;
var errStream = std.io.fixedBufferStream(&outBuf);
const buf = try ldns.buffer.new(4096);
defer buf.free();
const rdf = ldns.rdf.new_frm_str(type_, in) orelse return error.LdnsError;
defer rdf.deep_free();
var ctx = Context(@TypeOf(&out), @TypeOf(errStream.writer())){ .out = &out, .err_writer = errStream.writer(), .tmp_buf = buf };
try emitRdf(rdf, &ctx);
try testing.expectEqualStrings(expected_out, bufStream.getWritten());
try testing.expectEqual(@as(usize, 0), errStream.getWritten().len);
}
test "emitRdf" {
try testRdf(.STR,
\\"m\\196\\133ka"
,
\\m\196\133ka
);
try testRdf(.DNAME, "\"www.example.com\"", "www.example.com.");
try testRdf(.INT8, "243", "243");
try testRdf(.INT16, "5475", "5475");
try testRdf(.INT32, "7464567", "7464567");
try testRdf(.PERIOD, "7464567", "7464567");
try testRdf(.A, "\"192.168.1.1\"", "192.168.1.1");
try testing.expectError(error.LdnsError, testRdf(.INT32, "", "bogus"));
}
pub fn emitRr(rr: *ldns.rr, ctx: anytype) !void {
const type_ = rr.get_type();
try ctx.out.beginObject();
try ctx.out.objectField("name");
try emitRdf(rr.owner(), ctx);
try ctx.out.objectField("type");
try ctx.ok(type_.appendStr(ctx.tmp_buf));
try ctx.out.emitString(ctx.tmp_buf.data());
ctx.tmp_buf.clear();
try ctx.out.objectField("ttl");
try ctx.out.emitNumber(rr.ttl());
try ctx.out.objectField("data");
try ctx.out.beginObject();
const fieldNames = try rrFieldNames(type_, ctx);
const rdf_count = rr.rd_count();
var rdf_index: usize = 0;
while (rdf_index < rdf_count) : (rdf_index += 1) {
try ctx.out.objectField(fieldNames[rdf_index]);
try emitRdf(rr.rdf(rdf_index), ctx);
}
try ctx.out.endObject();
try ctx.out.endObject();
}
fn testRr(expected_out: []const u8, in: [*:0]const u8) !void {
var outBuf: [4096]u8 = undefined;
var bufStream = std.io.fixedBufferStream(&outBuf);
var out = json.writeStream(bufStream.writer(), 6);
var errBuf: [4096]u8 = undefined;
var errStream = std.io.fixedBufferStream(&outBuf);
const buf = try ldns.buffer.new(4096);
defer buf.free();
const rr = switch (ldns.rr.new_frm_str(in, 0, null, null)) {
.ok => |row| row,
.err => |stat| return error.LdnsError,
};
defer rr.free();
var ctx = Context(@TypeOf(&out), @TypeOf(errStream.writer())){ .out = &out, .err_writer = errStream.writer(), .tmp_buf = buf };
try emitRr(rr, &ctx);
try testing.expectEqualStrings(expected_out, bufStream.getWritten());
try testing.expectEqual(@as(usize, 0), errStream.getWritten().len);
}
test "emitRr" {
try testRr(
\\{
\\ "name": "minimal.com",
\\ "type": "SOA",
\\ "ttl": 3600,
\\ "data": {
\\ "mname": "ns.example.net",
\\ "rname": "admin.minimal.com",
\\ "serial": 2013022001,
\\ "refresh": 86400,
\\ "retry": 7200,
\\ "expire": 3600,
\\ "minimum": 3600
\\ }
\\}
,
\\minimal.com. 3600 IN SOA ns.example.net. admin.minimal.com. 2013022001 86400 7200 3600 3600
);
try testRr(
\\{
\\ "name": "minimal.com",
\\ "type": "AAAA",
\\ "ttl": 3600,
\\ "data": {
\\ "ip": "fc00:db20:35b:7399::5"
\\ }
\\}
,
\\minimal.com. 3600 IN AAAA fc00:db20:35b:7399::5
);
try testing.expectError(error.LdnsError, testRr("", "bogus"));
}
pub fn emitZone(zone: *ldns.zone, ctx: anytype) !void {
const rr_list = zone.rrs();
const rr_count = rr_list.rr_count();
const soa = zone.soa() orelse {
try ctx.err_writer.print("no SOA record in zone", .{});
return error.NoSoaRecord;
};
try ctx.out.beginObject();
try ctx.out.objectField("name");
try emitRdf(soa.owner(), ctx);
try ctx.out.objectField("records");
try ctx.out.beginArray();
try ctx.out.arrayElem();
try emitRr(soa, ctx);
var rr_index: usize = 0;
while (rr_index < rr_count) : (rr_index += 1) {
const rr = rr_list.rr(rr_index);
try ctx.out.arrayElem();
try emitRr(rr, ctx);
}
try ctx.out.endArray();
try ctx.out.endObject();
}
pub fn Context(comptime Writer: type, comptime ErrWriter: type) type {
return struct {
out: Writer,
err_writer: ErrWriter,
tmp_buf: *ldns.buffer,
pub fn ok(self: *@This(), status: ldns.status) !void {
if (status != .OK) {
std.log.err("unexpected ldns error: {s}", .{status.get_errorstr()});
return error.Unexpected;
}
}
};
}
pub fn convertCFile(file: *c.FILE, json_writer: anytype, err_writer: anytype) !void {
const zone = switch (ldns.zone.new_frm_fp(file, null, 0, .IN)) {
.ok => |z| z,
.err => |err| {
try err_writer.print("parsing zone failed on line {}: {s}", .{ err.line, err.code.get_errorstr() });
return error.ParseError;
},
};
defer zone.deep_free();
const buf = try ldns.buffer.new(4096);
defer buf.free();
var ctx = Context(@TypeOf(json_writer), @TypeOf(err_writer)){ .out = json_writer, .err_writer = err_writer, .tmp_buf = buf };
try emitZone(zone, &ctx);
}
pub fn convertMem(zone: []const u8, json_writer: anytype, err_writer: anytype) !void {
const file = c.fmemopen(@intToPtr(?*c_void, @ptrToInt(zone.ptr)), zone.len, "r") orelse return error.SystemResources;
defer _ = c.fclose(file);
return convertCFile(file, json_writer, err_writer);
}
pub fn convertApi(zone: []const u8, json_out: *std.ArrayList(u8)) !void {
var err_buf: [256]u8 = undefined;
var err_stream = std.io.fixedBufferStream(&err_buf);
var json_writer = std.json.writeStream(json_out.writer(), 10);
try json_writer.beginObject();
try json_writer.objectField("ok");
convertMem(zone, &json_writer, err_stream.writer()) catch |err| switch (err) {
error.OutOfMemory, error.SystemResources, error.NoSpaceLeft, error.Unexpected => return err,
error.ParseError, error.UnsupportedRecordType, error.NoSoaRecord => {
json_out.shrinkRetainingCapacity(0);
json_writer = std.json.writeStream(json_out.writer(), 10);
try json_writer.beginObject();
try json_writer.objectField("error");
try json_writer.emitString(err_stream.getWritten());
},
};
try json_writer.endObject();
} | src/zone2json.zig |
const global =
\\ let gamma: f32 = 2.2;
\\ let pi: f32 = 3.1415926;
\\
\\ fn saturate(x: f32) -> f32 {
\\ return clamp(x, 0.0, 1.0);
\\ }
\\
\\ fn radicalInverseVdc(in_bits: u32) -> f32 {
\\ var bits = (in_bits << 16u) | (in_bits >> 16u);
\\ bits = ((bits & 0x55555555u) << 1u) | ((bits & 0xAAAAAAAAu) >> 1u);
\\ bits = ((bits & 0x33333333u) << 2u) | ((bits & 0xCCCCCCCCu) >> 2u);
\\ bits = ((bits & 0x0F0F0F0Fu) << 4u) | ((bits & 0xF0F0F0F0u) >> 4u);
\\ bits = ((bits & 0x00FF00FFu) << 8u) | ((bits & 0xFF00FF00u) >> 8u);
\\ return f32(bits) * bitcast<f32>(0x2f800000);
\\ }
\\
\\ fn hammersley(idx: u32, n: u32) -> vec2<f32> {
\\ return vec2(f32(idx) / f32(n), radicalInverseVdc(idx));
\\ }
\\
\\ fn importanceSampleGgx(xi: vec2<f32>, roughness: f32, n: vec3<f32>) -> vec3<f32> {
\\ let alpha = roughness * roughness;
\\ let phi = 2.0 * pi * xi.x;
\\ let cos_theta = sqrt((1.0 - xi.y) / (1.0 + (alpha * alpha - 1.0) * xi.y));
\\ let sin_theta = sqrt(1.0 - cos_theta * cos_theta);
\\
\\ var h: vec3<f32>;
\\ h.x = sin_theta * cos(phi);
\\ h.y = sin_theta * sin(phi);
\\ h.z = cos_theta;
\\
\\ // This is Right-Handed coordinate system and works for upper-left UV coordinate systems.
\\ var up_vector: vec3<f32>;
\\ if (abs(n.y) < 0.999) {
\\ up_vector = vec3(0.0, 1.0, 0.0);
\\ } else {
\\ up_vector = vec3(0.0, 0.0, 1.0);
\\ }
\\ let tangent_x = normalize(cross(up_vector, n));
\\ let tangent_y = normalize(cross(n, tangent_x));
\\
\\ // Tangent to world space.
\\ return normalize(tangent_x * h.x + tangent_y * h.y + n * h.z);
\\ }
\\
\\ fn geometrySchlickGgx(cos_theta: f32, roughness: f32) -> f32 {
\\ let k = (roughness * roughness) * 0.5;
\\ return cos_theta / (cos_theta * (1.0 - k) + k);
\\ }
\\
\\ fn geometrySmith(n_dot_l: f32, n_dot_v: f32, roughness: f32) -> f32 {
\\ return geometrySchlickGgx(n_dot_v, roughness) * geometrySchlickGgx(n_dot_l, roughness);
\\ }
\\
;
pub const precompute_env_tex_vs =
\\ struct Uniforms {
\\ object_to_clip: mat4x4<f32>,
\\ }
\\ @group(0) @binding(0) var<uniform> uniforms: Uniforms;
\\ struct VertexOut {
\\ @builtin(position) position_clip: vec4<f32>,
\\ @location(0) position: vec3<f32>,
\\ }
\\
\\ @stage(vertex) fn main(
\\ @location(0) position: vec3<f32>,
\\ ) -> VertexOut {
\\ var output: VertexOut;
\\ output.position_clip = vec4(position, 1.0) * uniforms.object_to_clip;
\\ output.position = position;
\\ return output;
\\ }
;
pub const precompute_env_tex_fs =
\\ @group(0) @binding(1) var equirect_tex: texture_2d<f32>;
\\ @group(0) @binding(2) var equirect_sam: sampler;
\\
\\ fn sampleSphericalMap(v: vec3<f32>) -> vec2<f32> {
\\ var uv = vec2(atan2(v.z, v.x), asin(v.y));
\\ uv = uv * vec2(0.1591, 0.3183);
\\ uv = uv + vec2(0.5);
\\ return uv;
\\ }
\\
\\ @stage(fragment) fn main(
\\ @location(0) position: vec3<f32>,
\\ ) -> @location(0) vec4<f32> {
\\ let uv = sampleSphericalMap(normalize(position));
\\ let color = textureSampleLevel(equirect_tex, equirect_sam, uv, 0.0).xyz;
\\ return vec4(color, 1.0);
\\ }
;
pub const precompute_irradiance_tex_vs =
\\ struct Uniforms {
\\ object_to_clip: mat4x4<f32>,
\\ }
\\ @group(0) @binding(0) var<uniform> uniforms: Uniforms;
\\
\\ struct VertexOut {
\\ @builtin(position) position_clip: vec4<f32>,
\\ @location(0) position: vec3<f32>,
\\ }
\\
\\ @stage(vertex) fn main(
\\ @location(0) position: vec3<f32>,
\\ ) -> VertexOut {
\\ var output: VertexOut;
\\ output.position_clip = vec4(position, 1.0) * uniforms.object_to_clip;
\\ output.position = position;
\\ return output;
\\ }
;
pub const precompute_irradiance_tex_fs = global ++
\\ @group(0) @binding(1) var env_tex: texture_cube<f32>;
\\ @group(0) @binding(2) var env_sam: sampler;
\\
\\ @stage(fragment) fn main(
\\ @location(0) position: vec3<f32>,
\\ ) -> @location(0) vec4<f32> {
\\ let n = normalize(position);
\\
\\ // This is Right-Handed coordinate system and works for upper-left UV coordinate systems.
\\ var up_vector: vec3<f32>;
\\ if (abs(n.y) < 0.999) {
\\ up_vector = vec3(0.0, 1.0, 0.0);
\\ } else {
\\ up_vector = vec3(0.0, 0.0, 1.0);
\\ }
\\ let tangent_x = normalize(cross(up_vector, n));
\\ let tangent_y = normalize(cross(n, tangent_x));
\\
\\ var num_samples: i32 = 0;
\\ var irradiance = vec3(0.0);
\\
\\ for (var phi = 0.0; phi < 2.0 * pi; phi = phi + 0.025) {
\\ let sin_phi = sin(phi);
\\ let cos_phi = cos(phi);
\\
\\ for (var theta = 0.0; theta < 0.5 * pi; theta = theta + 0.025) {
\\ let sin_theta = sin(theta);
\\ let cos_theta = cos(theta);
\\
\\ // Point on a hemisphere.
\\ let h = vec3(sin_theta * cos_phi, sin_theta * sin_phi, cos_theta);
\\
\\ // Transform from tangent space to world space.
\\ let sample_vector = tangent_x * h.x + tangent_y * h.y + n * h.z;
\\
\\ let irr = textureSample(env_tex, env_sam, sample_vector).xyz * cos_theta * sin_theta;
\\
\\ irradiance = irradiance + irr;
\\ num_samples = num_samples + 1;
\\ }
\\ }
\\
\\ irradiance = pi * irradiance * vec3(1.0 / f32(num_samples));
\\ return vec4(irradiance, 1.0);
\\ }
;
const precompute_filtered_env_tex_common =
\\ struct Uniforms {
\\ object_to_clip: mat4x4<f32>,
\\ roughness: f32,
\\ }
\\ @group(0) @binding(0) var<uniform> uniforms: Uniforms;
\\
;
pub const precompute_filtered_env_tex_vs = precompute_filtered_env_tex_common ++
\\ struct VertexOut {
\\ @builtin(position) position_clip: vec4<f32>,
\\ @location(0) position: vec3<f32>,
\\ }
\\
\\ @stage(vertex) fn main(
\\ @location(0) position: vec3<f32>,
\\ ) -> VertexOut {
\\ var output: VertexOut;
\\ output.position_clip = vec4(position, 1.0) * uniforms.object_to_clip;
\\ output.position = position;
\\ return output;
\\ }
;
pub const precompute_filtered_env_tex_fs = global ++ precompute_filtered_env_tex_common ++
\\ @group(0) @binding(1) var env_tex: texture_cube<f32>;
\\ @group(0) @binding(2) var env_sam: sampler;
\\
\\ @stage(fragment) fn main(
\\ @location(0) position: vec3<f32>,
\\ ) -> @location(0) vec4<f32> {
\\ let roughness = uniforms.roughness;
\\ let n = normalize(position);
\\ let r = n;
\\ let v = r;
\\
\\ var prefiltered_color = vec3(0.0);
\\ var total_weight = 0.0;
\\ let num_samples = 4096u;
\\
\\ for (var sample_idx = 0u; sample_idx < num_samples; sample_idx = sample_idx + 1u) {
\\ let xi = hammersley(sample_idx, num_samples);
\\ let h = importanceSampleGgx(xi, roughness, n);
\\ let lvec = 2.0 * dot(v, h) * h - v;
\\ let l = normalize(2.0 * dot(v, h) * h - v);
\\ let n_dot_l = saturate(dot(n, l));
\\ if (n_dot_l > 0.0) {
\\ var color = textureSample(env_tex, env_sam, lvec).xyz * n_dot_l;
\\ prefiltered_color = prefiltered_color + color;
\\ total_weight = total_weight + n_dot_l;
\\ }
\\ }
\\ return vec4(prefiltered_color / max(total_weight, 0.001), 1.0);
\\ }
;
pub const precompute_brdf_integration_tex_cs = global ++
\\ @group(0) @binding(0) var brdf_tex: texture_storage_2d<rgba16float, write>;
\\
\\ fn integrate(roughness: f32, n_dot_v: f32) -> vec2<f32> {
\\ var v: vec3<f32>;
\\ v.x = 0.0;
\\ v.y = n_dot_v; // cos
\\ v.z = sqrt(1.0 - n_dot_v * n_dot_v); // sin
\\
\\ let n = vec3(0.0, 1.0, 0.0);
\\
\\ var a = 0.0;
\\ var b = 0.0;
\\ let num_samples = 1024u;
\\
\\ for (var sample_idx = 0u; sample_idx < num_samples; sample_idx = sample_idx + 1u) {
\\ let xi = hammersley(sample_idx, num_samples);
\\ let h = importanceSampleGgx(xi, roughness, n);
\\ let l = normalize(2.0 * dot(v, h) * h - v);
\\
\\ let n_dot_l = saturate(l.y);
\\ let n_dot_h = saturate(h.y);
\\ let v_dot_h = saturate(dot(v, h));
\\
\\ if (n_dot_l > 0.0) {
\\ let g = geometrySmith(n_dot_l, n_dot_v, roughness);
\\ let g_vis = g * v_dot_h / (n_dot_h * n_dot_v);
\\ let fc = pow(1.0 - v_dot_h, 5.0);
\\ a = a + (1.0 - fc) * g_vis;
\\ b = b + fc * g_vis;
\\ }
\\ }
\\ return vec2(a, b) / vec2(f32(num_samples));
\\ }
\\
\\ @stage(compute) @workgroup_size(8, 8, 1)
\\ fn main(
\\ @builtin(global_invocation_id) global_id: vec3<u32>,
\\ ) {
\\ let dim = textureDimensions(brdf_tex);
\\ let roughness = f32(global_id.y + 1u) / f32(dim.y);
\\ let n_dot_v = f32(global_id.x + 1u) / f32(dim.x);
\\ let result = integrate(roughness, n_dot_v);
\\ textureStore(brdf_tex, vec2<i32>(global_id.xy), vec4(result, 0.0, 1.0));
\\ }
;
const mesh_common =
\\ struct MeshUniforms {
\\ object_to_world: mat4x4<f32>,
\\ world_to_clip: mat4x4<f32>,
\\ camera_position: vec3<f32>,
\\ draw_mode: i32,
\\ }
\\ @group(0) @binding(0) var<uniform> uniforms: MeshUniforms;
\\
;
pub const mesh_vs = mesh_common ++
\\ struct VertexOut {
\\ @builtin(position) position_clip: vec4<f32>,
\\ @location(0) position: vec3<f32>,
\\ @location(1) normal: vec3<f32>,
\\ @location(2) texcoord: vec2<f32>,
\\ @location(3) tangent: vec4<f32>,
\\ }
\\
\\ @stage(vertex) fn main(
\\ @location(0) position: vec3<f32>,
\\ @location(1) normal: vec3<f32>,
\\ @location(2) texcoord: vec2<f32>,
\\ @location(3) tangent: vec4<f32>,
\\ ) -> VertexOut {
\\ var output: VertexOut;
\\ output.position_clip = vec4(position, 1.0) * uniforms.object_to_world * uniforms.world_to_clip;
\\ output.position = (vec4(position, 1.0) * uniforms.object_to_world).xyz;
\\ output.normal = normal;
\\ output.texcoord = texcoord;
\\ output.tangent = tangent;
\\ return output;
\\ }
;
pub const mesh_fs = global ++ mesh_common ++
\\ @group(0) @binding(1) var ao_tex: texture_2d<f32>;
\\ @group(0) @binding(2) var base_color_tex: texture_2d<f32>;
\\ @group(0) @binding(3) var metallic_roughness_tex: texture_2d<f32>;
\\ @group(0) @binding(4) var normal_tex: texture_2d<f32>;
\\
\\ @group(0) @binding(5) var irradiance_tex: texture_cube<f32>;
\\ @group(0) @binding(6) var filtered_env_tex: texture_cube<f32>;
\\ @group(0) @binding(7) var brdf_integration_tex: texture_2d<f32>;
\\
\\ @group(0) @binding(8) var aniso_sam: sampler;
\\
\\ fn fresnelSchlickRoughness(cos_theta: f32, f0: vec3<f32>, roughness: f32) -> vec3<f32> {
\\ return f0 + (max(vec3(1.0 - roughness), f0) - f0) * pow(1.0 - cos_theta, 5.0);
\\ }
\\
\\ @stage(fragment) fn main(
\\ @location(0) position: vec3<f32>,
\\ @location(1) normal: vec3<f32>,
\\ @location(2) texcoord: vec2<f32>,
\\ @location(3) tangent: vec4<f32>,
\\ ) -> @location(0) vec4<f32> {
\\ if (uniforms.draw_mode == 1) {
\\ return vec4(pow(textureSample(ao_tex, aniso_sam, texcoord).xyz, vec3(1.0 / gamma)), 1.0);
\\ } else if (uniforms.draw_mode == 2) {
\\ return vec4(textureSample(base_color_tex, aniso_sam, texcoord).xyz, 1.0);
\\ } else if (uniforms.draw_mode == 3) {
\\ let m = pow(textureSample(metallic_roughness_tex, aniso_sam, texcoord).z, 1.0 / gamma);
\\ return vec4(m, m, m, 1.0);
\\ } else if (uniforms.draw_mode == 4) {
\\ let r = pow(textureSample(metallic_roughness_tex, aniso_sam, texcoord).y, 1.0 / gamma);
\\ return vec4(r, r, r, 1.0);
\\ } else if (uniforms.draw_mode == 5) {
\\ return vec4(pow(textureSample(normal_tex, aniso_sam, texcoord).xyz, vec3(1.0 / gamma)), 1.0);
\\ }
\\
\\ let unit_normal = normalize(normal);
\\ let unit_tangent = vec4(normalize(tangent.xyz), tangent.w);
\\ let unit_bitangent = normalize(cross(normal, unit_tangent.xyz)) * unit_tangent.w;
\\
\\ let object_to_world = mat3x3(
\\ uniforms.object_to_world[0].xyz,
\\ uniforms.object_to_world[1].xyz,
\\ uniforms.object_to_world[2].xyz,
\\ );
\\ var n = normalize(textureSample(normal_tex, aniso_sam, texcoord).xyz * 2.0 - 1.0);
\\ n = n * transpose(mat3x3(unit_tangent.xyz, unit_bitangent, unit_normal));
\\ n = normalize(n * object_to_world);
\\
\\ var metallic: f32;
\\ var roughness: f32;
\\ {
\\ let rm = textureSample(metallic_roughness_tex, aniso_sam, texcoord).yz;
\\ roughness = rm.x;
\\ metallic = rm.y;
\\ }
\\ let base_color = pow(textureSample(base_color_tex, aniso_sam, texcoord).xyz, vec3(gamma));
\\ let ao = textureSample(ao_tex, aniso_sam, texcoord).x;
\\
\\ let v = normalize(uniforms.camera_position - position);
\\ let n_dot_v = saturate(dot(n, v));
\\
\\ let f0 = mix(vec3(0.04), base_color, vec3(metallic));
\\
\\ let r = reflect(-v, n);
\\ let f = fresnelSchlickRoughness(n_dot_v, f0, roughness);
\\
\\ let kd = (1.0 - f) * (1.0 - metallic);
\\
\\ let irradiance = textureSample(irradiance_tex, aniso_sam, n).xyz;
\\ let prefiltered_color = textureSampleLevel(
\\ filtered_env_tex,
\\ aniso_sam,
\\ r,
\\ roughness * 5.0, // roughness * (num_mip_levels - 1.0)
\\ ).xyz;
\\ let env_brdf = textureSample(
\\ brdf_integration_tex,
\\ aniso_sam,
\\ vec2(min(n_dot_v, 0.999), roughness),
\\ ).xy;
\\
\\ let diffuse = irradiance * base_color;
\\ let specular = prefiltered_color * (f * env_brdf.x + env_brdf.y);
\\ let ambient = (kd * diffuse + specular) * ao;
\\
\\ var color = ambient;
\\ color = color / (color + 1.0);
\\
\\ return vec4(pow(color, vec3(1.0 / gamma)), 1.0);
\\ }
;
pub const sample_env_tex_vs =
\\ struct Uniforms {
\\ object_to_clip: mat4x4<f32>,
\\ }
\\ @group(0) @binding(0) var<uniform> uniforms: Uniforms;
\\
\\ struct VertexOut {
\\ @builtin(position) position_clip: vec4<f32>,
\\ @location(0) position: vec3<f32>,
\\ }
\\
\\ @stage(vertex) fn main(
\\ @location(0) position: vec3<f32>,
\\ ) -> VertexOut {
\\ var output: VertexOut;
\\ output.position_clip = (vec4(position, 1.0) * uniforms.object_to_clip).xyww;
\\ output.position = position;
\\ return output;
\\ }
;
pub const sample_env_tex_fs = global ++
\\ @group(0) @binding(1) var env_tex: texture_cube<f32>;
\\ @group(0) @binding(2) var env_sam: sampler;
\\
\\ @stage(fragment) fn main(
\\ @location(0) position: vec3<f32>,
\\ ) -> @location(0) vec4<f32> {
\\ var color = textureSample(env_tex, env_sam, position).xyz;
\\ color = color / (color + vec3(1.0));
\\ return vec4(pow(color, vec3(1.0 / gamma)), 1.0);
\\ }
;
// zig fmt: on | samples/physically_based_rendering_wgpu/src/physically_based_rendering_wgsl.zig |
const std = @import("std");
const os = @import("os");
const ArrayList = std.ArrayList;
const utils = @import("utils.zig");
const c = @import("c.zig");
const Vec3 = @import("vec.zig").Vec3;
const Ray = @import("ray.zig").Ray;
const Sphere = @import("sphere.zig").Sphere;
const HitRecord = @import("sphere.zig").HitRecord;
const Camera = @import("camera.zig").Camera;
const Material = @import("materials.zig").Material;
const width = 1280;
const height = 720;
const sample_count = 100;
const bounce_count = 25;
const ThreadContext = struct {
idx: i32,
chunk_size: i32,
width: i32,
height: i32,
buf: [][3]u8,
spheres: []const Sphere,
camera: *const Camera,
};
pub fn main() !void {
@setFloatMode(std.builtin.FloatMode.Optimized);
_ = c.glfwSetErrorCallback(glfwErrorCallback);
if (c.glfwInit() == 0) return error.GlfwInitFailed;
defer c.glfwTerminate();
c.glfwWindowHint(c.GLFW_CONTEXT_VERSION_MAJOR, 4);
c.glfwWindowHint(c.GLFW_CONTEXT_VERSION_MINOR, 6);
c.glfwWindowHint(c.GLFW_FLOATING, 1);
c.glfwWindowHint(c.GLFW_RESIZABLE, 0);
const window = c.glfwCreateWindow(width, height, "rtiaw", null, null) orelse
return error.GlfwCreateWindowFailed;
defer c.glfwDestroyWindow(window);
c.glfwMakeContextCurrent(window);
if (c.gladLoadGLLoader(@ptrCast(
fn ([*c]const u8) callconv(.C) ?*c_void,
c.glfwGetProcAddress,
)) == 0) return error.GlInitFailed;
var buf: c_uint = undefined;
c.glGenBuffers(1, &buf);
c.glBindBuffer(c.GL_PIXEL_UNPACK_BUFFER, buf);
const pixel_count = width * height;
const flags: c_uint = c.GL_MAP_WRITE_BIT | c.GL_MAP_PERSISTENT_BIT |
c.GL_MAP_COHERENT_BIT;
c.glNamedBufferStorage(buf, pixel_count * 3, null, flags);
var mapped_buf = @ptrCast(
[*][3]u8,
c.glMapNamedBufferRange(buf, 0, pixel_count * 3, flags).?,
)[0..pixel_count];
@memset(&mapped_buf[0], 0, @sizeOf(@TypeOf(mapped_buf.*)));
var tex: c_uint = undefined;
c.glCreateTextures(c.GL_TEXTURE_2D, 1, &tex);
c.glTextureStorage2D(tex, 1, c.GL_RGB8, width, height);
var framebuf: c_uint = undefined;
c.glGenFramebuffers(1, &framebuf);
c.glBindFramebuffer(c.GL_READ_FRAMEBUFFER, framebuf);
c.glNamedFramebufferTexture(framebuf, c.GL_COLOR_ATTACHMENT0, tex, 0);
var gpa = std.heap.GeneralPurposeAllocator(.{}){};
defer _ = gpa.deinit();
var spheres = ArrayList(Sphere).init(&gpa.allocator);
defer _ = spheres.deinit();
try initializeScene(&spheres);
const camera = Camera.init(&.{
.origin = Vec3.init(13, 2, 3),
.target = Vec3.init(0, 0, 0),
.up = Vec3.init(0, 1, 0),
.vertical_fov = 20,
.aspect_ratio = @intToFloat(f32, width) / @intToFloat(f32, height),
.aperture = 0.1,
.focus_distance = 10,
});
const thread_count = @intCast(i32, (try std.Thread.getCpuCount()) - 1);
var threads = try ArrayList(std.Thread).initCapacity(&gpa.allocator, @intCast(usize, thread_count));
defer _ = threads.deinit();
var thread_idx: i32 = 0;
while (thread_idx < thread_count) : (thread_idx += 1) {
const ctx = ThreadContext{
.idx = thread_idx,
.chunk_size = @divTrunc(width * height, thread_count),
.width = width,
.height = height,
.buf = mapped_buf,
.spheres = spheres.items,
.camera = &camera,
};
try threads.append(try std.Thread.spawn(.{}, traceRays, .{ctx}));
}
for (threads.items) |thread|
thread.detach();
const zeroPtr = @intToPtr(*allowzero c_void, 0);
c.glfwSwapInterval(1);
while (c.glfwWindowShouldClose(window) == 0) {
defer {
c.glfwPollEvents();
c.glfwSwapBuffers(window);
}
c.glTextureSubImage2D(tex, 0, 0, 0, width, height, c.GL_RGB, c.GL_UNSIGNED_BYTE, zeroPtr);
c.glBlitNamedFramebuffer(framebuf, 0, 0, 0, width, height, 0, 0, width, height, c.GL_COLOR_BUFFER_BIT, c.GL_NEAREST);
}
}
fn traceRays(ctx: ThreadContext) void {
const width_inv = 1.0 / @intToFloat(f32, ctx.width - 1);
const height_inv = 1.0 / @intToFloat(f32, ctx.height - 1);
const start_idx = ctx.idx * ctx.chunk_size;
const stop_idx = std.math.min(
start_idx + ctx.chunk_size,
ctx.width * ctx.height,
);
var random = std.rand.DefaultPrng.init(@intCast(u64, ctx.idx)).random();
var idx: i32 = start_idx;
while (idx < stop_idx) : (idx += 1) {
const i = @mod(idx, ctx.width);
const j = @divTrunc(idx, ctx.width);
var col = Vec3.initAll(0);
var s: i32 = 0;
while (s < sample_count) : (s += 1) {
const u = (@intToFloat(f32, i) + random.float(f32)) * width_inv;
const v = (@intToFloat(f32, j) + random.float(f32)) * height_inv;
const ray = ctx.camera.ray(u, v, &random);
col = col.add(rayColor(&ray, ctx.spheres, bounce_count, &random));
}
col = col.div(sample_count)
.sqrt() // Gamma correction.
.scale(255.99);
const offset = @intCast(usize, i + j * ctx.width);
ctx.buf[offset][0] = @floatToInt(u8, col.x);
ctx.buf[offset][1] = @floatToInt(u8, col.y);
ctx.buf[offset][2] = @floatToInt(u8, col.z);
}
}
fn initializeScene(spheres: *ArrayList(Sphere)) !void {
var rand = std.rand.DefaultPrng.init(42).random();
var a: i32 = -11;
while (a < 11) : (a += 1) {
var b: i32 = -11;
while (b < 11) : (b += 1) {
const choose_mat = rand.float(f32);
const center = Vec3.init(
@intToFloat(f32, a) + 0.9 * rand.float(f32),
0.2,
@intToFloat(f32, b) + 0.9 * rand.float(f32),
);
if ((center.sub(Vec3.init(4, 0.2, 0))).len() > 0.9) {
try spheres.append(if (choose_mat < 0.8)
Sphere.init(
center,
0.2,
Material.lambertian(
Vec3.random(&rand).mul(Vec3.random(&rand)),
),
)
else if (choose_mat < 0.95)
Sphere.init(
center,
0.2,
Material.metal(
Vec3.random(&rand),
utils.randomRange(
utils.Range(f32){ .min = 0, .max = 0.5 },
&rand,
),
),
)
else
Sphere.init(
center,
0.2,
Material.dielectric(1.5),
));
}
}
}
try spheres.append(Sphere.init(
Vec3.init(0, -1000, 0),
1000,
Material.lambertian(Vec3.initAll(0.5)),
));
try spheres.append(Sphere.init(
Vec3.init(0, 1, 0),
1.0,
Material.dielectric(1.5),
));
try spheres.append(Sphere.init(
Vec3.init(-4, 1, 0),
1.0,
Material.lambertian(Vec3.init(0.4, 0.2, 0.1)),
));
try spheres.append(Sphere.init(
Vec3.init(4, 1, 0),
1.0,
Material.metal(Vec3.init(0.7, 0.6, 0.5), 0),
));
}
fn rayColor(
ray_in: *const Ray,
spheres: []const Sphere,
depth: u32,
random: *std.rand.Random,
) Vec3 {
var t_range = utils.Range(f32){ .min = 0.001, .max = std.math.inf(f32) };
var rec: HitRecord = undefined;
var hit_anything = false;
var material: Material = undefined;
if (depth == 0) return Vec3.initAll(0);
for (spheres) |sphere| {
if (sphere.hit(ray_in, t_range, &rec)) {
hit_anything = true;
t_range.max = rec.t;
material = rec.material.*;
}
}
if (hit_anything) {
var ray_out: Ray = undefined;
var atten: Vec3 = undefined;
const bounce = switch (material) {
Material.Lambertian => |l| l.scatter(&rec, &atten, &ray_out, random),
Material.Metal => |m| m.scatter(ray_in, &rec, &atten, &ray_out, random),
Material.Dielectric => |d| d.scatter(ray_in, &rec, &atten, &ray_out, random),
};
return if (bounce) atten.mul(rayColor(&ray_out, spheres, depth - 1, random)) else Vec3.zero;
}
const unit_dir = ray_in.dir.normalize();
const t = (unit_dir.y + 1) * 0.5;
return Vec3.lerp(Vec3.initAll(1), Vec3.init(0.5, 0.7, 1.0), t);
}
export fn glfwErrorCallback(err: c_int, description: [*c]const u8) void {
std.debug.panic("GLFW error ({}): {s}\n", .{ err, description });
} | src/main.zig |
const std = @import("std");
const input = @import("input.zig");
pub fn run(allocator: std.mem.Allocator, stdout: anytype) anyerror!void {
{
var input_ = try input.readFile("inputs/day3");
defer input_.deinit();
const result = try part1(&input_);
try stdout.print("3a: {}\n", .{ result });
std.debug.assert(result == 4147524);
}
{
var input_ = try input.readFile("inputs/day3");
defer input_.deinit();
const result = try part2(allocator, &input_);
try stdout.print("3b: {}\n", .{ result });
std.debug.assert(result == 3570354);
}
}
const Datum = u12;
const DatumBits = std.math.Log2Int(Datum);
const Answer = std.math.IntFittingRange(0, std.math.maxInt(Datum) * std.math.maxInt(Datum));
fn part1(input_: anytype) !Answer {
const Count = struct {
ones: usize = 0,
zeroes: usize = 0,
};
var counts = [_]Count { .{} } ** @bitSizeOf(Datum);
while (try input_.next()) |line| {
const datum = try std.fmt.parseInt(Datum, line, 2);
var i: DatumBits = @bitSizeOf(Datum) - 1;
while (true) : (i -= 1) {
if (datum & (@as(Datum, 1) << i) == 0) {
counts[i].zeroes += 1;
}
else {
counts[i].ones += 1;
}
if (i == 0) {
break;
}
}
}
var gamma_rate: Datum = 0;
var epsilon_rate: Datum = 0;
for (counts) |count, i| {
if (count.ones == count.zeroes) {
return error.InvalidInput;
}
if (count.ones > count.zeroes) {
gamma_rate |= (@as(Datum, 1) << @intCast(DatumBits, i));
}
else if (count.ones > 0) {
epsilon_rate |= (@as(Datum, 1) << @intCast(DatumBits, i));
}
}
return @as(Answer, gamma_rate) * @as(Answer, epsilon_rate);
}
fn part2(allocator: std.mem.Allocator, input_: anytype) !Answer {
var input_list = std.ArrayList(Datum).init(allocator);
defer input_list.deinit();
while (try input_.next()) |line| {
const datum = try std.fmt.parseInt(Datum, line, 2);
try input_list.append(datum);
}
std.sort.sort(Datum, input_list.items, {}, comptime std.sort.asc(Datum));
const input_slice: []const Datum = input_list.items;
const oxygen_generator_rating = oxygen_generator_rating: {
var oxygen_generator_input = input_slice;
break :oxygen_generator_rating part2_inner(&oxygen_generator_input, .larger);
};
const co2_scrubber_rating = co2_scrubber_rating: {
var co2_scrubber_input = input_slice;
break :co2_scrubber_rating part2_inner(&co2_scrubber_input, .smaller);
};
return @as(Answer, oxygen_generator_rating) * @as(Answer, co2_scrubber_rating);
}
const Part2Choice = enum {
larger,
smaller,
};
fn part2_inner(input_: *[]const Datum, subslice_choice: Part2Choice) Datum {
var num_bits_remaining: DatumBits = @bitSizeOf(Datum) - 1;
while (true) : (num_bits_remaining -= 1) {
const mid =
((input_.*)[0] & ~(@as(Datum, std.math.maxInt(Datum)) >> (@bitSizeOf(Datum) - 1 - num_bits_remaining))) |
(@as(Datum, 1) << num_bits_remaining);
var i: usize = input_.len / 2;
while (i > 0 and (input_.*)[i - 1] >= mid) {
i -= 1;
}
while (i < input_.len and (input_.*)[i] < mid) {
i += 1;
}
const num_less_than_mid = i;
const num_greater_than_mid = input_.len - i;
if (num_less_than_mid > 0 and num_greater_than_mid > 0) {
switch (subslice_choice) {
.larger => {
if (num_less_than_mid <= num_greater_than_mid) {
input_.* = (input_.*)[i..];
}
else {
input_.* = (input_.*)[0..i];
}
},
.smaller => {
if (num_less_than_mid > num_greater_than_mid) {
input_.* = (input_.*)[i..];
}
else {
input_.* = (input_.*)[0..i];
}
},
}
}
if (input_.len == 1 or num_bits_remaining == 0) {
return (input_.*)[0];
}
}
}
test "day 3 example 1" {
const input_ =
\\00100
\\11110
\\10110
\\10111
\\10101
\\01111
\\00111
\\11100
\\10000
\\11001
\\00010
\\01010
;
try std.testing.expectEqual(@as(Answer, 22 * 9), try part1(&input.readString(input_)));
try std.testing.expectEqual(@as(Answer, 23 * 10), try part2(std.testing.allocator, &input.readString(input_)));
} | src/day3.zig |
const expect = @import("std").testing.expect;
pub const GLFWmonitor = opaque {};
pub const GLFWwindow = opaque {};
pub const GLFWcursor = opaque {};
pub const GLFWvidmode = extern struct {
width: c_int,
height: c_int,
redBits: c_int,
greenBits: c_int,
blueBits: c_int,
refreshRate: c_int,
};
test "sizeof GLFWvidmode" {
// Optional pointers are the same size as normal pointers, because pointer
// value 0 is used as the null value.
try expect(@sizeOf(GLFWvidmode) == 24);
}
pub const GLFWgammaramp = extern struct {
red: ?*c_ushort,
green: ?*c_ushort,
blue: ?*c_ushort,
size: c_uint,
};
test "sizeof GLFWgammaramp" {
// Optional pointers are the same size as normal pointers, because pointer
// value 0 is used as the null value.
try expect(@sizeOf(GLFWgammaramp) == 32);
}
pub const GLFWimage = extern struct {
width: c_int,
height: c_int,
pixels: ?*u8,
};
test "sizeof GLFWimage" {
// Optional pointers are the same size as normal pointers, because pointer
// value 0 is used as the null value.
try expect(@sizeOf(GLFWimage) == 16);
}
pub extern "c" fn glfwInit() c_int;
pub extern "c" fn glfwTerminate() void;
pub extern "c" fn glfwGetVersion(major: ?*c_int, minor: ?*c_int, rev: ?*c_int) void;
pub extern "c" fn glfwGetVersionString() ?[*]const u8;
pub extern "c" fn glfwSetErrorCallback(cbfun: ?*?*anyopaque) ?*?*anyopaque;
pub extern "c" fn glfwGetMonitors(count: ?*c_int) ?*?*GLFWmonitor;
pub extern "c" fn glfwGetPrimaryMonitor() ?*GLFWmonitor;
pub extern "c" fn glfwGetMonitorPos(monitor: ?*GLFWmonitor, xpos: ?*c_int, ypos: ?*c_int) void;
pub extern "c" fn glfwGetMonitorPhysicalSize(monitor: ?*GLFWmonitor, widthMM: ?*c_int, heightMM: ?*c_int) void;
pub extern "c" fn glfwGetMonitorName(monitor: ?*GLFWmonitor) ?[*]const u8;
pub extern "c" fn glfwSetMonitorCallback(cbfun: ?*?*anyopaque) ?*?*anyopaque;
pub extern "c" fn glfwGetVideoModes(monitor: ?*GLFWmonitor, count: ?*c_int) ?*GLFWvidmode;
pub extern "c" fn glfwGetVideoMode(monitor: ?*GLFWmonitor) ?*GLFWvidmode;
pub extern "c" fn glfwSetGamma(monitor: ?*GLFWmonitor, gamma: f32) void;
pub extern "c" fn glfwGetGammaRamp(monitor: ?*GLFWmonitor) ?*GLFWgammaramp;
pub extern "c" fn glfwSetGammaRamp(monitor: ?*GLFWmonitor, ramp: ?*const GLFWgammaramp) void;
pub extern "c" fn glfwDefaultWindowHints() void;
pub extern "c" fn glfwWindowHint(hint: c_int, value: c_int) void;
pub extern "c" fn glfwCreateWindow(width: c_int, height: c_int, title: ?[*]const u8, monitor: ?*GLFWmonitor, share: ?*GLFWwindow) ?*GLFWwindow;
pub extern "c" fn glfwDestroyWindow(window: ?*GLFWwindow) void;
pub extern "c" fn glfwWindowShouldClose(window: ?*GLFWwindow) c_int;
pub extern "c" fn glfwSetWindowShouldClose(window: ?*GLFWwindow, value: c_int) void;
pub extern "c" fn glfwSetWindowTitle(window: ?*GLFWwindow, title: ?[*]const u8) void;
pub extern "c" fn glfwSetWindowIcon(window: ?*GLFWwindow, count: c_int, images: ?*const GLFWimage) void;
pub extern "c" fn glfwGetWindowPos(window: ?*GLFWwindow, xpos: ?*c_int, ypos: ?*c_int) void;
pub extern "c" fn glfwSetWindowPos(window: ?*GLFWwindow, xpos: c_int, ypos: c_int) void;
pub extern "c" fn glfwGetWindowSize(window: ?*GLFWwindow, width: ?*c_int, height: ?*c_int) void;
pub extern "c" fn glfwSetWindowSizeLimits(window: ?*GLFWwindow, minwidth: c_int, minheight: c_int, maxwidth: c_int, maxheight: c_int) void;
pub extern "c" fn glfwSetWindowAspectRatio(window: ?*GLFWwindow, numer: c_int, denom: c_int) void;
pub extern "c" fn glfwSetWindowSize(window: ?*GLFWwindow, width: c_int, height: c_int) void;
pub extern "c" fn glfwGetFramebufferSize(window: ?*GLFWwindow, width: ?*c_int, height: ?*c_int) void;
pub extern "c" fn glfwGetWindowFrameSize(window: ?*GLFWwindow, left: ?*c_int, top: ?*c_int, right: ?*c_int, bottom: ?*c_int) void;
pub extern "c" fn glfwIconifyWindow(window: ?*GLFWwindow) void;
pub extern "c" fn glfwRestoreWindow(window: ?*GLFWwindow) void;
pub extern "c" fn glfwMaximizeWindow(window: ?*GLFWwindow) void;
pub extern "c" fn glfwShowWindow(window: ?*GLFWwindow) void;
pub extern "c" fn glfwHideWindow(window: ?*GLFWwindow) void;
pub extern "c" fn glfwFocusWindow(window: ?*GLFWwindow) void;
pub extern "c" fn glfwGetWindowMonitor(window: ?*GLFWwindow) ?*GLFWmonitor;
pub extern "c" fn glfwSetWindowMonitor(window: ?*GLFWwindow, monitor: ?*GLFWmonitor, xpos: c_int, ypos: c_int, width: c_int, height: c_int, refreshRate: c_int) void;
pub extern "c" fn glfwGetWindowAttrib(window: ?*GLFWwindow, attrib: c_int) c_int;
pub extern "c" fn glfwSetWindowUserPointer(window: ?*GLFWwindow, pointer: ?*anyopaque) void;
pub extern "c" fn glfwGetWindowUserPointer(window: ?*GLFWwindow) ?*anyopaque;
pub extern "c" fn glfwSetWindowPosCallback(window: ?*GLFWwindow, cbfun: ?*?*anyopaque) ?*?*anyopaque;
pub extern "c" fn glfwSetWindowSizeCallback(window: ?*GLFWwindow, cbfun: ?*?*anyopaque) ?*?*anyopaque;
pub extern "c" fn glfwSetWindowCloseCallback(window: ?*GLFWwindow, cbfun: ?*?*anyopaque) ?*?*anyopaque;
pub extern "c" fn glfwSetWindowRefreshCallback(window: ?*GLFWwindow, cbfun: ?*?*anyopaque) ?*?*anyopaque;
pub extern "c" fn glfwSetWindowFocusCallback(window: ?*GLFWwindow, cbfun: ?*?*anyopaque) ?*?*anyopaque;
pub extern "c" fn glfwSetWindowIconifyCallback(window: ?*GLFWwindow, cbfun: ?*?*anyopaque) ?*?*anyopaque;
pub extern "c" fn glfwSetFramebufferSizeCallback(window: ?*GLFWwindow, cbfun: ?*?*anyopaque) ?*?*anyopaque;
pub extern "c" fn glfwPollEvents() void;
pub extern "c" fn glfwWaitEvents() void;
pub extern "c" fn glfwWaitEventsTimeout(timeout: f64) void;
pub extern "c" fn glfwPostEmptyEvent() void;
pub extern "c" fn glfwGetInputMode(window: ?*GLFWwindow, mode: c_int) c_int;
pub extern "c" fn glfwSetInputMode(window: ?*GLFWwindow, mode: c_int, value: c_int) void;
pub extern "c" fn glfwGetKeyName(key: c_int, scancode: c_int) ?[*]const u8;
pub extern "c" fn glfwGetKey(window: ?*GLFWwindow, key: c_int) c_int;
pub extern "c" fn glfwGetMouseButton(window: ?*GLFWwindow, button: c_int) c_int;
pub extern "c" fn glfwGetCursorPos(window: ?*GLFWwindow, xpos: ?*f64, ypos: ?*f64) void;
pub extern "c" fn glfwSetCursorPos(window: ?*GLFWwindow, xpos: f64, ypos: f64) void;
pub extern "c" fn glfwCreateCursor(image: ?*const GLFWimage, xhot: c_int, yhot: c_int) ?*GLFWcursor;
pub extern "c" fn glfwCreateStandardCursor(shape: c_int) ?*GLFWcursor;
pub extern "c" fn glfwDestroyCursor(cursor: ?*GLFWcursor) void;
pub extern "c" fn glfwSetCursor(window: ?*GLFWwindow, cursor: ?*GLFWcursor) void;
pub extern "c" fn glfwSetKeyCallback(window: ?*GLFWwindow, cbfun: ?*?*anyopaque) ?*?*anyopaque;
pub extern "c" fn glfwSetCharCallback(window: ?*GLFWwindow, cbfun: ?*?*anyopaque) ?*?*anyopaque;
pub extern "c" fn glfwSetCharModsCallback(window: ?*GLFWwindow, cbfun: ?*?*anyopaque) ?*?*anyopaque;
pub extern "c" fn glfwSetMouseButtonCallback(window: ?*GLFWwindow, cbfun: ?*?*anyopaque) ?*?*anyopaque;
pub extern "c" fn glfwSetCursorPosCallback(window: ?*GLFWwindow, cbfun: ?*?*anyopaque) ?*?*anyopaque;
pub extern "c" fn glfwSetCursorEnterCallback(window: ?*GLFWwindow, cbfun: ?*?*anyopaque) ?*?*anyopaque;
pub extern "c" fn glfwSetScrollCallback(window: ?*GLFWwindow, cbfun: ?*?*anyopaque) ?*?*anyopaque;
pub extern "c" fn glfwSetDropCallback(window: ?*GLFWwindow, cbfun: ?*?*anyopaque) ?*?*anyopaque;
pub extern "c" fn glfwJoystickPresent(joy: c_int) c_int;
pub extern "c" fn glfwGetJoystickAxes(joy: c_int, count: ?*c_int) ?*f32;
pub extern "c" fn glfwGetJoystickButtons(joy: c_int, count: ?*c_int) ?*u8;
pub extern "c" fn glfwGetJoystickName(joy: c_int) ?[*]const u8;
pub extern "c" fn glfwSetJoystickCallback(cbfun: ?*?*anyopaque) ?*?*anyopaque;
pub extern "c" fn glfwSetClipboardString(window: ?*GLFWwindow, string: ?[*]const u8) void;
pub extern "c" fn glfwGetClipboardString(window: ?*GLFWwindow) ?[*]const u8;
pub extern "c" fn glfwGetTime() f64;
pub extern "c" fn glfwSetTime(time: f64) void;
pub extern "c" fn glfwGetTimerValue() c_int;
pub extern "c" fn glfwGetTimerFrequency() c_int;
pub extern "c" fn glfwMakeContextCurrent(window: ?*GLFWwindow) void;
pub extern "c" fn glfwGetCurrentContext() ?*GLFWwindow;
pub extern "c" fn glfwSwapBuffers(window: ?*GLFWwindow) void;
pub extern "c" fn glfwSwapInterval(interval: c_int) void;
pub extern "c" fn glfwExtensionSupported(extension: ?[*]const u8) c_int;
pub extern "c" fn glfwGetProcAddress(procname: ?[*]const u8) ?*?*anyopaque;
pub extern "c" fn glfwVulkanSupported() c_int;
pub extern "c" fn glfwGetRequiredInstanceExtensions(count: ?*c_int) ?*?[*]const u8; | pkgs/glfw/src/main.zig |
const std = @import( "std" );
const min = std.math.min;
const pow = std.math.pow;
const inf = std.math.inf;
const isNan = std.math.isNan;
usingnamespace @import( "util.zig" );
usingnamespace @import( "core.zig" );
usingnamespace @import( "glz.zig" );
usingnamespace @import( "gtkz.zig" );
pub fn AxisUpdatingHandler( comptime N: usize ) type {
return struct {
const Self = @This();
axes: [N]*Axis,
screenCoordIndices: [N]u1,
// Axis scales and viewport sizes from the most recent time
// one of their scales was explicitly changed; used below
// to implicitly rescale when widget size or hidpi scaling
// changes
sizesFromLastRealRescale_PX: [N]f64,
scalesFromLastRealRescale: [N]f64,
// Axis scales, explicit or not, from the most recent render
scalesFromLastRender: [N]f64,
pub fn init( axes: [N]*Axis, screenCoordIndices: [N]u1 ) Self {
return Self {
.axes = axes,
.screenCoordIndices = screenCoordIndices,
.sizesFromLastRealRescale_PX = axisSizes_PX( axes ),
.scalesFromLastRealRescale = axisScales( axes ),
.scalesFromLastRender = axisScales( axes ),
};
}
pub fn onRender( glArea: *GtkGLArea, glContext: *GdkGLContext, self: *Self ) callconv(.C) gboolean {
const viewport_PX = glzGetViewport_PX( );
for ( self.axes ) |axis, n| {
axis.viewport_PX = viewport_PX[ self.screenCoordIndices[n] ];
}
var isRealRescale = false;
for ( self.axes ) |axis, n| {
if ( axis.scale != self.scalesFromLastRender[n] ) {
isRealRescale = true;
break;
}
}
if ( isRealRescale ) {
self.sizesFromLastRealRescale_PX = axisSizes_PX( self.axes );
self.scalesFromLastRealRescale = axisScales( self.axes );
}
else {
// Auto-adjust axis *scales* so that the axis *bounds* stay as
// close as possible to what they were the last time there was
// a "real" scale change
var autoRescaleFactor = inf( f64 );
for ( self.axes ) |axis, n| {
// If this is the first time this axis has had a valid size,
// init its sizeFromLastRealRescale based on its defaultSpan
if ( isNan( self.sizesFromLastRealRescale_PX[n] ) ) {
const initialRescaleFactor = axis.span( ) / axis.defaultSpan;
self.sizesFromLastRealRescale_PX[n] = axis.viewport_PX.span / initialRescaleFactor;
}
// The highest factor we can multiply this axis scale by
// and still keep its previous bounds within its viewport
const maxRescaleFactor = axis.viewport_PX.span / self.sizesFromLastRealRescale_PX[n];
// We will rescale all axes by a single factor that keeps
// all their previous bounds within their viewports
autoRescaleFactor = min( autoRescaleFactor, maxRescaleFactor );
}
// Rescale all axes by a single factor
for ( self.axes ) |axis, n| {
axis.scale = autoRescaleFactor * self.scalesFromLastRealRescale[n];
}
}
self.scalesFromLastRender = axisScales( self.axes );
return 0;
}
fn axisSizes_PX( axes: [N]*const Axis ) [N]f64 {
var sizes_PX = @as( [N]f64, undefined );
for ( axes ) |axis, n| {
sizes_PX[n] = axis.viewport_PX.span;
}
return sizes_PX;
}
fn axisScales( axes: [N]*const Axis ) [N]f64 {
var scales = @as( [N]f64, undefined );
for ( axes ) |axis, n| {
scales[n] = axis.scale;
}
return scales;
}
pub fn onMouseWheel( widget: *GtkWidget, ev: *GdkEventScroll, self: *Self ) callconv(.C) gboolean {
const zoomStepFactor = 1.12;
const zoomSteps = gtkzWheelSteps( ev );
const zoomFactor = pow( f64, zoomStepFactor, -zoomSteps );
const mouse_PX = gtkzMousePos_PX( widget, ev );
for ( self.axes ) |axis, n| {
const mouseFrac = axis.viewport_PX.valueToFrac( mouse_PX[ self.screenCoordIndices[n] ] );
const mouseCoord = axis.bounds( ).fracToValue( mouseFrac );
const scale = zoomFactor*axis.scale;
axis.set( mouseFrac, mouseCoord, scale );
}
gtk_widget_queue_draw( widget );
return 1;
}
};
}
pub const PaintingHandler = struct {
painters: []const *Painter,
pub fn init( painters: []const *Painter ) PaintingHandler {
return PaintingHandler {
.painters = painters,
};
}
pub fn onRender( glArea: *GtkGLArea, glContext: *GdkGLContext, self: *PaintingHandler ) callconv(.C) gboolean {
const pc = PainterContext {
.viewport_PX = glzGetViewport_PX( ),
.lpxToPx = gtkzScaleFactor( @ptrCast( *GtkWidget, glArea ) ),
};
for ( self.painters ) |painter| {
painter.glPaint( &pc ) catch |e| {
std.debug.warn( "Failed to paint: painter = {s}, error = {}\n", .{ painter.name, e } );
};
}
return 0;
}
pub fn onWindowClosing( window: *GtkWindow, ev: *GdkEvent, self: *PaintingHandler ) callconv(.C) gboolean {
if ( glzHasCurrentContext( ) ) {
for ( self.painters ) |painter| {
painter.glDeinit( );
}
}
else {
std.debug.warn( "Failed to deinit painters; no current GL Context\n", .{} );
}
return 0;
}
};
pub const DraggingHandler = struct {
draggers: []const *Dragger,
activeDragger: ?*Dragger = null,
pub fn init( widget: gpointer, draggers: []const *Dragger ) !DraggingHandler {
return DraggingHandler {
.draggers = draggers,
};
}
pub fn onMouseDown( widget: *GtkWidget, ev: *GdkEventButton, self: *DraggingHandler ) callconv(.C) gboolean {
const clickCount = gtkzClickCount( ev );
if ( ev.button == 1 and clickCount >= 1 ) {
const mouse_PX = gtkzMousePos_PX( widget, ev );
const context = DraggerContext {
.lpxToPx = gtkzScaleFactor( widget ),
};
const newDragger = findDragger( self.draggers, context, mouse_PX, clickCount );
if ( newDragger != null and newDragger != self.activeDragger ) {
if ( self.activeDragger != null ) {
self.activeDragger.?.handleRelease( context, mouse_PX );
}
self.activeDragger = newDragger;
self.activeDragger.?.handlePress( context, mouse_PX, clickCount );
gtk_widget_queue_draw( widget );
}
}
return 1;
}
pub fn onMouseMove( widget: *GtkWidget, ev: *GdkEventMotion, self: *DraggingHandler ) callconv(.C) gboolean {
if ( self.activeDragger != null ) {
const mouse_PX = gtkzMousePos_PX( widget, ev );
const context = DraggerContext {
.lpxToPx = gtkzScaleFactor( widget ),
};
self.activeDragger.?.handleDrag( context, mouse_PX );
gtk_widget_queue_draw( widget );
}
return 1;
}
pub fn onMouseUp( widget: *GtkWidget, ev: *GdkEventButton, self: *DraggingHandler ) callconv(.C) gboolean {
if ( self.activeDragger != null and ev.button == 1 ) {
const mouse_PX = gtkzMousePos_PX( widget, ev );
const context = DraggerContext {
.lpxToPx = gtkzScaleFactor( widget ),
};
self.activeDragger.?.handleRelease( context, mouse_PX );
self.activeDragger = null;
gtk_widget_queue_draw( widget );
}
return 1;
}
fn findDragger( draggers: []const *Dragger, context: DraggerContext, mouse_PX: [2]f64, clickCount: u32 ) ?*Dragger {
for ( draggers ) |dragger| {
if ( dragger.canHandlePress( context, mouse_PX, clickCount ) ) {
return dragger;
}
}
return null;
}
};
pub const MultiPaintable = struct {
childPainters: ArrayList( *Painter ),
painter: Painter,
pub fn init( name: []const u8, allocator: *Allocator ) MultiPaintable {
return MultiPaintable {
.childPainters = ArrayList( *Painter ).init( allocator ),
.painter = Painter {
.name = name,
.glInitFn = glInit,
.glPaintFn = glPaint,
.glDeinitFn = glDeinit,
},
};
}
fn glInit( painter: *Painter, pc: *const PainterContext ) !void {
// Do nothing
}
fn glPaint( painter: *Painter, pc: *const PainterContext ) !void {
const self = @fieldParentPtr( MultiPaintable, "painter", painter );
for ( self.childPainters.items ) |childPainter| {
childPainter.glPaint( pc ) catch |e| {
std.debug.warn( "Failed to paint: painter = {s}, error = {}\n", .{ childPainter.name, e } );
if ( @errorReturnTrace( ) ) |trace| {
std.debug.dumpStackTrace( trace.* );
}
};
}
}
fn glDeinit( painter: *Painter ) void {
const self = @fieldParentPtr( MultiPaintable, "painter", painter );
for ( self.childPainters.items ) |childPainter| {
childPainter.glDeinit( );
}
self.childPainters.items.len = 0;
}
pub fn deinit( self: *MultiPaintable ) void {
for ( self.childPainters.items ) |childPainter| {
if ( childPainter.glResourcesAreSet ) {
std.debug.warn( "glDeinit was never called for painter \"{}\"\n", .{ childPainter.name } );
}
}
self.childPainters.deinit( );
}
};
pub const ClearPaintable = struct {
mask: GLbitfield,
rgba: [4]GLfloat,
depth: GLfloat,
stencil: GLint,
painter: Painter,
pub fn init( name: []const u8, mask: GLbitfield ) ClearPaintable {
return ClearPaintable {
.mask = mask,
.rgba = [_]GLfloat { 0.0, 0.0, 0.0, 0.0 },
.depth = 1.0,
.stencil = 0,
.painter = Painter {
.name = name,
.glInitFn = glInit,
.glPaintFn = glPaint,
.glDeinitFn = glDeinit,
},
};
}
fn glInit( painter: *Painter, pc: *const PainterContext ) !void {
// Do nothing
}
fn glPaint( painter: *Painter, pc: *const PainterContext ) !void {
const self = @fieldParentPtr( ClearPaintable, "painter", painter );
if ( self.mask & GL_COLOR_BUFFER_BIT != 0 ) {
glClearColor( self.rgba[0], self.rgba[1], self.rgba[2], self.rgba[3] );
}
if ( self.mask & GL_DEPTH_BUFFER_BIT != 0 ) {
glClearDepthf( self.depth );
}
if ( self.mask & GL_STENCIL_BUFFER_BIT != 0 ) {
glClearStencil( self.stencil );
}
glClear( self.mask );
}
fn glDeinit( painter: *Painter ) void {
// Do nothing
}
}; | src/core/support.zig |
const std = @import("std");
pub fn main() anyerror!void {
std.log.info("All your codebase are belong to us.", .{});
}
const expect = @import("std").testing.expect;
const assert = @import("std").debug.assert;
const mem = @import("std").mem;
// array literal
const message = [_]u8{ 'h', 'e', 'l', 'l', 'o' };
// get the size of an array
comptime {
assert(message.len == 5);
}
// A string literal is a single-item pointer to an array literal.
const same_message = "hello";
comptime {
assert(mem.eql(u8, &message, same_message));
}
test "iterate over an array" {
var sum: usize = 0;
for (message) |byte| {
sum += byte;
}
try expect(sum == 'h' + 'e' + 'l' * 2 + 'o');
}
// modifiable array
var some_integers: [100]i32 = undefined;
test "modify an array" {
for (some_integers) |*item, i| {
item.* = @intCast(i32, i);
}
try expect(some_integers[10] == 10);
try expect(some_integers[99] == 99);
}
// array concatenation works if the values are known
// at compile time
const part_one = [_]i32{ 1, 2, 3, 4 };
const part_two = [_]i32{ 5, 6, 7, 8 };
const all_of_it = part_one ++ part_two;
comptime {
assert(mem.eql(i32, &all_of_it, &[_]i32{ 1, 2, 3, 4, 5, 6, 7, 8 }));
}
// remember that string literals are arrays
const hello = "hello";
const world = "world";
const hello_world = hello ++ " " ++ world;
comptime {
assert(mem.eql(u8, hello_world, "hello world"));
}
// ** does repeating patterns
const pattern = "ab" ** 3;
comptime {
assert(mem.eql(u8, pattern, "ababab"));
}
// initialize an array to zero
const all_zero = [_]u16{0} ** 10;
comptime {
assert(all_zero.len == 10);
assert(all_zero[5] == 0);
}
// use compile-time code to initialize an array
var fancy_array = init: {
var initial_value: [10]Point = undefined;
for (initial_value) |*pt, i| {
pt.* = Point{
.x = @intCast(i32, i),
.y = @intCast(i32, i) * 2,
};
}
break :init initial_value;
};
const Point = struct {
x: i32,
y: i32,
};
test "compile-time array initialization" {
try expect(fancy_array[4].x == 4);
try expect(fancy_array[4].y == 8);
}
// call a function to initialize an array
var more_points = [_]Point{makePoint(3)} ** 10;
fn makePoint(x: i32) Point {
return Point{
.x = x,
.y = x * 2,
};
}
test "array initialization with function calls" {
try expect(more_points[4].x == 3);
try expect(more_points[4].y == 6);
try expect(more_points.len == 10);
} | arrays/src/main.zig |
const utils = @import("utils.zig");
const x86 = @import("x86.zig");
const platform = @import("platform.zig");
const pmem = @import("pmem.zig");
const layout = @import("layout.zig");
const assert = @import("std").debug.assert;
const serial = @import("../../debug/serial.zig");
const PageEntry = usize;
const PageMapLevel5 = @intToPtr([*]PageEntry, layout.PageMapLevel5);
const PageMapLevel4 = @intToPtr([*]PageEntry, layout.PageMapLevel4);
const PageDirectoryPointer = @intToPtr([*]PageEntry, layout.PageDirectoryPointer);
const PageDirectory = @intToPtr([*]PageEntry, layout.PageDirectory);
const PageTables = @intToPtr([*]PageEntry, layout.PageTables);
pub const PAGE_PRESENT = (1 << 0);
pub const PAGE_WRITE = (1 << 1);
pub const PAGE_USER = (1 << 2);
pub const PAGE_4MB = (1 << 7);
pub const PAGE_GLOBAL = (1 << 8);
pub const PAGE_ALLOCATED = (1 << 9);
fn pdIndex(vaddr: usize) usize {
return v_addr >> 22;
}
fn ptIndex(vaddr: usize) usize {
return (vaddr >> 12) & 0x3FF;
}
fn pdEntry(vaddr: usize) *PageEntry {
return &PageDirectory[pdIndex(vaddr)];
}
fn ptEntry(vaddr: usize) *PageEntry {
return &PageTables[(pdIndex(vaddr) * 0x400) + ptIndex(vaddr)];
}
pub fn virtualToPhysical(vaddr: usize) ?usize {
const pd_entry = pdEntry(vaddr);
if (pd_entry.* == 0) return null;
const pt_entry = ptEntry(vaddr);
return x86.pageBase(pt_entry.*);
}
pub fn map(vaddr: usize, paddr: ?usize, flags: u32) void {
assert(vaddr >= layout.Identity);
const pd_entry = pdEntry(vaddr);
const pt_entry = ptEntry(vaddr);
if (pd_entry.* == 0) {
pd_entry.* = pmem.allocate() | flags | PAGE_PRESENT | PAGE_WRITE | PAGE_USER;
invlpg(@ptrToInt(pt_entry));
const pt = @ptrCast([*]PageEntry, x86.pageBase(pt_entry));
zeroPageTable(pt);
}
if (paddr) |p| {
if (pt_entry.* & PAGE_ALLOCATED != 0) pmem.free(pt_entry.*);
pt_entry.* = x86.pageBase(p) | flags | PAGE_PRESENT;
} else {
if (pt_entry.* & PAGE_ALLOCATED != 0) {
pt_entry.* = x86.pageBase(pt_entry.*) | flags | PAGE_PRESENT | PAGE_ALLOCATED;
} else {
pt_entry.* = pmem.allocate() | flags | PAGE_PRESENT | PAGE_ALLOCATED;
}
}
invlpg(vaddr);
}
pub fn unmap(vaddr: usize) void {
assert(vaddr >= layout.Identity);
const pd_entry = pdEntry(vaddr);
if (pd_entry.* == 0) return;
const pt_entry = ptEntry(vaddr);
if (pt_entry.* & PAGE_ALLOCATED != 0) pmem.free(pt_entry.*);
pt_entry.* = 0;
invlpg(vaddr);
}
pub fn mapZone(vaddr: usize, paddr: ?usize, size: usize, flags: u32) void {
var i: usize = 0;
while (i < size) : (i += x86.PAGE_SIZE) {
map(vaddr + i, if (p_addr) |p| p + i else null, flags);
}
}
pub fn unmapZone(vaddr: usize, size: usize) void {
var i: usize = 0;
while (i < size) : (i += x86.PAGE_SIZE) {
unmap(vaddr + i);
}
}
fn zeroPageTable(page_table: [*]PageEntry) void {
const pt = @ptrCast([*]u8, page_table);
@memset(pt, 0, x86.PAGE_SIZE);
}
// Invalidate TLB entry associated with given vaddr
pub fn invlpg(v_addr: usize) void {
asm volatile ("invlpg (%[v_addr])"
:
: [v_addr] "r" (v_addr)
: "memory"
);
}
extern fn setupPaging(pd: usize) void;
pub fn initialize() void {
serial.writeText("Virtual memory and paging initializing...\n");
const pd = @intToPtr([*]PageEntry, pmem.allocate()); // Page directory's page.
serial.writeText("PD entry allocated.\n");
zeroPageTable(pd);
// Identity mapping of the kernel (first 8MB) and make the PD loop on the last entry.
pd[0] = 0x000000 | PAGE_PRESENT | PAGE_WRITE | PAGE_4MB | PAGE_GLOBAL;
pd[1] = 0x400000 | PAGE_PRESENT | PAGE_WRITE | PAGE_4MB | PAGE_GLOBAL;
pd[1023] = @ptrToInt(pd) | PAGE_PRESENT | PAGE_WRITE;
// TODO: register an interruption for page fault handler
platform.writeCR("3", @ptrToInt(pd));
// TODO: actually perform a real setup, loadPML5(@ptrToInt(PML5));
// TODO: signal end of paging setup.
serial.writeText("Virtual memory and paging initialized.\n");
} | src/kernel/arch/x86/vmem.zig |
const std = @import("std");
const util = @import("util.zig");
const data = @embedFile("../data/day05.txt");
const Point2 = struct {
x: i16,
y: i16,
};
const VentMap = struct {
map: std.AutoHashMap(Point2, u32) = undefined,
pub fn init(allocator: std.mem.Allocator) @This() {
var map = std.AutoHashMap(Point2, u32).init(allocator);
return @This(){
.map = map,
};
}
pub fn deinit(self: *@This()) void {
self.map.deinit();
self.* = undefined;
}
pub fn add(self: *@This(), point: Point2) void {
if (self.map.getOrPut(point)) |result| {
if (!result.found_existing) {
result.value_ptr.* = 0;
}
result.value_ptr.* += 1;
} else |err| {
print("getOrPut error: {}\n", .{err});
}
}
};
const VentLine = struct {
x1: i16,
y1: i16,
x2: i16,
y2: i16,
};
const Input = struct {
lines: std.ArrayList(VentLine) = std.ArrayList(VentLine).init(std.testing.allocator),
pub fn deinit(self: @This()) void {
self.lines.deinit();
}
};
fn parseInput(input_text: []const u8) Input {
var input = Input{};
var lines = std.mem.tokenize(u8, input_text, "\r\n");
while (lines.next()) |line| {
var endpoints = std.mem.tokenize(u8, line, ",- >");
input.lines.append(VentLine{
.x1 = parseInt(i16, endpoints.next().?, 10) catch unreachable,
.y1 = parseInt(i16, endpoints.next().?, 10) catch unreachable,
.x2 = parseInt(i16, endpoints.next().?, 10) catch unreachable,
.y2 = parseInt(i16, endpoints.next().?, 10) catch unreachable,
}) catch unreachable;
}
return input;
}
fn part1(input: Input) i64 {
var map = VentMap.init(std.testing.allocator);
defer map.deinit();
for (input.lines.items) |line| {
//print("line from {d},{d} to {d},{d}\n", .{line.x1, line.y1, line.x2, line.y2});
if (line.x1 == line.x2) {
const y_min = min(line.y1, line.y2);
const y_max = max(line.y1, line.y2);
var y = y_min;
while (y <= y_max) : (y += 1) {
//print(" point at {d},{d}\n", .{line.x1, y});
map.add(Point2{ .x = line.x1, .y = y });
}
} else if (line.y1 == line.y2) {
const x_min = min(line.x1, line.x2);
const x_max = max(line.x1, line.x2);
var x = x_min;
while (x <= x_max) : (x += 1) {
//print(" point at {d},{d}\n", .{x, line.y1});
map.add(Point2{ .x = x, .y = line.y1 });
}
}
}
var values = map.map.valueIterator();
var count: i64 = 0;
while (values.next()) |val| {
if (val.* > 1) {
count += 1;
}
}
return count;
}
fn part2(input: Input) i64 {
var map = VentMap.init(std.testing.allocator);
defer map.deinit();
for (input.lines.items) |line| {
//print("line from {d},{d} to {d},{d}\n", .{line.x1, line.y1, line.x2, line.y2});
var x = line.x1;
var y = line.y1;
var dx: i16 = 0;
if (line.x2 > line.x1) {
dx = 1;
} else if (line.x2 < line.x1) {
dx = -1;
}
var dy: i16 = 0;
if (line.y2 > line.y1) {
dy = 1;
} else if (line.y2 < line.y1) {
dy = -1;
}
while (x != line.x2 or y != line.y2) : ({
x += dx;
y += dy;
}) {
//print(" point at {d},{d}\n", .{x, y});
map.add(Point2{ .x = x, .y = y });
}
//print(" point at {d},{d}\n", .{line.x2, line.y2});
map.add(Point2{ .x = line.x2, .y = line.y2 });
}
var values = map.map.valueIterator();
var count: i64 = 0;
while (values.next()) |val| {
if (val.* > 1) {
count += 1;
}
}
return count;
}
fn testPart1() !void {
var test_input = parseInput(test_data);
defer test_input.deinit();
try std.testing.expectEqual(@as(i64, 5), part1(test_input));
var input = parseInput(data);
defer input.deinit();
try std.testing.expectEqual(@as(i64, 6225), part1(input));
}
fn testPart2() !void {
var test_input = parseInput(test_data);
defer test_input.deinit();
try std.testing.expectEqual(@as(i64, 12), part2(test_input));
var input = parseInput(data);
defer input.deinit();
try std.testing.expectEqual(@as(i64, 22116), part2(input));
}
pub fn main() !void {
try testPart1();
try testPart2();
}
const test_data =
\\0,9 -> 5,9
\\8,0 -> 0,8
\\9,4 -> 3,4
\\2,2 -> 2,1
\\7,0 -> 7,4
\\6,4 -> 2,0
\\0,9 -> 2,9
\\3,4 -> 1,4
\\0,0 -> 8,8
\\5,5 -> 8,2
;
test "part1" {
try testPart1();
}
test "part2" {
try testPart2();
}
// Useful stdlib functions
const tokenize = std.mem.tokenize;
const split = std.mem.split;
const parseInt = std.fmt.parseInt;
const min = std.math.min;
const max = std.math.max;
const print = std.debug.print;
const expect = std.testing.expect;
const assert = std.debug.assert; | src/day05.zig |
const std = @import("std");
const Builder = @import("std").build.Builder;
pub fn build(b: *Builder) !void {
const target = try std.zig.CrossTarget.parse(.{
.arch_os_abi = "native-native-msvc",
});
const mode = b.standardReleaseOptions();
const bindings = b.addStaticLibrary("wwiseBindings", null);
bindings.linkLibC();
bindings.linkSystemLibrary("AkSoundEngine");
bindings.linkSystemLibrary("AkStreamMgr");
bindings.linkSystemLibrary("AkMemoryMgr");
bindings.linkSystemLibrary("CommunicationCentral");
bindings.linkSystemLibrary("AkRoomVerbFX");
bindings.linkSystemLibrary("AkStereoDelayFX");
bindings.linkSystemLibrary("AkVorbisDecoder");
bindings.linkSystemLibrary("ole32");
bindings.linkSystemLibrary("user32");
bindings.linkSystemLibrary("advapi32");
bindings.linkSystemLibrary("ws2_32");
bindings.addIncludeDir("bindings/IOHook/Win32");
bindings.addIncludeDir("WwiseSDK/include");
bindings.addLibPath("WwiseSDK/x64_vc150/Profile(StaticCRT)/lib");
bindings.setTarget(target);
const bindingsSources = &[_][]const u8{
"bindings/zig_wwise.cpp",
"bindings/IOHook/Common/AkFilePackage.cpp",
"bindings/IOHook/Common/AkFilePackageLUT.cpp",
"bindings/IOHook/Common/AkMultipleFileLocation.cpp",
"bindings/IOHook/Win32/AkDefaultIOHookBlocking.cpp",
};
for (bindingsSources) |src| {
bindings.addCSourceFile(src, &[_][]const u8{ "-std=c++17", "-DUNICODE" });
}
const imgui = b.addStaticLibrary("zigimgui", null);
imgui.linkLibC();
imgui.setTarget(target);
const imguiSources = &[_][]const u8{
"imgui/cimgui.cpp",
"imgui/imgui/imgui.cpp",
"imgui/imgui/imgui_demo.cpp",
"imgui/imgui/imgui_draw.cpp",
"imgui/imgui/imgui_impl_dx11.cpp",
"imgui/imgui/imgui_impl_win32.cpp",
"imgui/imgui/imgui_widgets.cpp",
};
for (imguiSources) |src| {
imgui.addCSourceFile(src, &[_][]const u8{"-std=c++17"});
}
const exe = b.addExecutable("wwiseZig", "src/main.zig");
exe.setTarget(target);
exe.setBuildMode(mode);
exe.addPackage(.{
.name = "zigwin32",
.path = .{ .path = "zigwin32/win32.zig" },
});
exe.addIncludeDir("bindings");
exe.addIncludeDir("imgui");
exe.addIncludeDir("WwiseSDK/include");
exe.addLibPath("WwiseSDK/x64_vc150/Profile(StaticCRT)/lib");
exe.linkLibrary(bindings);
exe.linkLibrary(imgui);
exe.linkLibC();
exe.linkSystemLibrary("D3D11");
exe.subsystem = .Windows;
exe.install();
const run_cmd = exe.run();
run_cmd.step.dependOn(b.getInstallStep());
const run_step = b.step("run", "Run the app");
run_step.dependOn(&run_cmd.step);
} | build.zig |
const std = @import("std");
const mem = std.mem;
const testing = std.testing;
const Allocator = mem.Allocator;
const Yaml = @import("yaml").Yaml;
const gpa = testing.allocator;
fn loadFromFile(file_path: []const u8) !Yaml {
const file = try std.fs.cwd().openFile(file_path, .{});
defer file.close();
const source = try file.readToEndAlloc(gpa, std.math.maxInt(u32));
defer gpa.free(source);
return Yaml.load(gpa, source);
}
test "simple" {
const Simple = struct {
names: []const []const u8,
numbers: []const i16,
nested: struct {
some: []const u8,
wick: []const u8,
},
finally: [4]f16,
pub fn eql(self: @This(), other: @This()) bool {
if (self.names.len != other.names.len) return false;
if (self.numbers.len != other.numbers.len) return false;
if (self.finally.len != other.finally.len) return false;
for (self.names) |lhs, i| {
if (!mem.eql(u8, lhs, other.names[i])) return false;
}
for (self.numbers) |lhs, i| {
if (lhs != other.numbers[i]) return false;
}
for (self.finally) |lhs, i| {
if (lhs != other.finally[i]) return false;
}
if (!mem.eql(u8, self.nested.some, other.nested.some)) return false;
if (!mem.eql(u8, self.nested.wick, other.nested.wick)) return false;
return true;
}
};
var parsed = try loadFromFile("test/simple.yaml");
defer parsed.deinit();
const result = try parsed.parse(Simple);
const expected = .{
.names = &[_][]const u8{ "<NAME>", "MacIntosh", "<NAME>" },
.numbers = &[_]i16{ 10, -8, 6 },
.nested = .{
.some = "one",
.wick = "<NAME>",
},
.finally = [_]f16{ 8.17, 19.78, 17, 21 },
};
try testing.expect(result.eql(expected));
}
const LibTbd = struct {
tbd_version: u3,
targets: []const []const u8,
uuids: []const struct {
target: []const u8,
value: []const u8,
},
install_name: []const u8,
current_version: union(enum) {
string: []const u8,
int: usize,
},
reexported_libraries: ?[]const struct {
targets: []const []const u8,
libraries: []const []const u8,
},
parent_umbrella: ?[]const struct {
targets: []const []const u8,
umbrella: []const u8,
},
exports: []const struct {
targets: []const []const u8,
symbols: []const []const u8,
},
pub fn eql(self: LibTbd, other: LibTbd) bool {
if (self.tbd_version != other.tbd_version) return false;
if (self.targets.len != other.targets.len) return false;
for (self.targets) |target, i| {
if (!mem.eql(u8, target, other.targets[i])) return false;
}
if (!mem.eql(u8, self.install_name, other.install_name)) return false;
switch (self.current_version) {
.string => |string| {
if (other.current_version != .string) return false;
if (!mem.eql(u8, string, other.current_version.string)) return false;
},
.int => |int| {
if (other.current_version != .int) return false;
if (int != other.current_version.int) return false;
},
}
if (self.reexported_libraries) |reexported_libraries| {
const o_reexported_libraries = other.reexported_libraries orelse return false;
if (reexported_libraries.len != o_reexported_libraries.len) return false;
for (reexported_libraries) |reexport, i| {
const o_reexport = o_reexported_libraries[i];
if (reexport.targets.len != o_reexport.targets.len) return false;
if (reexport.libraries.len != o_reexport.libraries.len) return false;
for (reexport.targets) |target, j| {
const o_target = o_reexport.targets[j];
if (!mem.eql(u8, target, o_target)) return false;
}
for (reexport.libraries) |library, j| {
const o_library = o_reexport.libraries[j];
if (!mem.eql(u8, library, o_library)) return false;
}
}
}
if (self.parent_umbrella) |parent_umbrella| {
const o_parent_umbrella = other.parent_umbrella orelse return false;
if (parent_umbrella.len != o_parent_umbrella.len) return false;
for (parent_umbrella) |pumbrella, i| {
const o_pumbrella = o_parent_umbrella[i];
if (pumbrella.targets.len != o_pumbrella.targets.len) return false;
for (pumbrella.targets) |target, j| {
const o_target = o_pumbrella.targets[j];
if (!mem.eql(u8, target, o_target)) return false;
}
if (!mem.eql(u8, pumbrella.umbrella, o_pumbrella.umbrella)) return false;
}
}
if (self.exports.len != other.exports.len) return false;
for (self.exports) |exp, i| {
const o_exp = other.exports[i];
if (exp.targets.len != o_exp.targets.len) return false;
if (exp.symbols.len != o_exp.symbols.len) return false;
for (exp.targets) |target, j| {
const o_target = o_exp.targets[j];
if (!mem.eql(u8, target, o_target)) return false;
}
for (exp.symbols) |symbol, j| {
const o_symbol = o_exp.symbols[j];
if (!mem.eql(u8, symbol, o_symbol)) return false;
}
}
return true;
}
};
test "single lib tbd" {
var parsed = try loadFromFile("test/single_lib.tbd");
defer parsed.deinit();
const result = try parsed.parse(LibTbd);
const expected = .{
.tbd_version = 4,
.targets = &[_][]const u8{
"x86_64-macos",
"x86_64-maccatalyst",
"arm64-macos",
"arm64-maccatalyst",
"arm64e-macos",
"arm64e-maccatalyst",
},
.uuids = &.{
.{ .target = "x86_64-macos", .value = "F86CC732-D5E4-30B5-AA7D-167DF5EC2708" },
.{ .target = "x86_64-maccatalyst", .value = "F86CC732-D5E4-30B5-AA7D-167DF5EC2708" },
.{ .target = "arm64-macos", .value = "00000000-0000-0000-0000-000000000000" },
.{ .target = "arm64-maccatalyst", .value = "00000000-0000-0000-0000-000000000000" },
.{ .target = "arm64e-macos", .value = "A17E8744-051E-356E-8619-66F2A6E89AD4" },
.{ .target = "arm64e-maccatalyst", .value = "A17E8744-051E-356E-8619-66F2A6E89AD4" },
},
.install_name = "/usr/lib/libSystem.B.dylib",
.current_version = .{ .string = "1292.60.1" },
.reexported_libraries = &.{
.{
.targets = &.{
"x86_64-macos",
"x86_64-maccatalyst",
"arm64-macos",
"arm64-maccatalyst",
"arm64e-macos",
"arm64e-maccatalyst",
},
.libraries = &.{
"/usr/lib/system/libcache.dylib", "/usr/lib/system/libcommonCrypto.dylib",
"/usr/lib/system/libcompiler_rt.dylib", "/usr/lib/system/libcopyfile.dylib",
"/usr/lib/system/libxpc.dylib",
},
},
},
.exports = &.{
.{
.targets = &.{
"x86_64-maccatalyst",
"x86_64-macos",
},
.symbols = &.{
"R8289209$_close", "R8289209$_fork", "R8289209$_fsync", "R8289209$_getattrlist",
"R8289209$_write",
},
},
.{
.targets = &.{
"x86_64-maccatalyst",
"x86_64-macos",
"arm64e-maccatalyst",
"arm64e-macos",
"arm64-macos",
"arm64-maccatalyst",
},
.symbols = &.{
"___crashreporter_info__", "_libSystem_atfork_child", "_libSystem_atfork_parent",
"_libSystem_atfork_prepare", "_mach_init_routine",
},
},
},
.parent_umbrella = null,
};
try testing.expect(result.eql(expected));
}
test "multi lib tbd" {
var parsed = try loadFromFile("test/multi_lib.tbd");
defer parsed.deinit();
const result = try parsed.parse([]LibTbd);
const expected = &[_]LibTbd{
.{
.tbd_version = 4,
.targets = &[_][]const u8{"x86_64-macos"},
.uuids = &.{
.{ .target = "x86_64-macos", .value = "F86CC732-D5E4-30B5-AA7D-167DF5EC2708" },
},
.install_name = "/usr/lib/libSystem.B.dylib",
.current_version = .{ .string = "1292.60.1" },
.reexported_libraries = &.{
.{
.targets = &.{"x86_64-macos"},
.libraries = &.{"/usr/lib/system/libcache.dylib"},
},
},
.exports = &.{
.{
.targets = &.{"x86_64-macos"},
.symbols = &.{ "R8289209$_close", "R8289209$_fork" },
},
.{
.targets = &.{"x86_64-macos"},
.symbols = &.{ "___crashreporter_info__", "_libSystem_atfork_child" },
},
},
.parent_umbrella = null,
},
.{
.tbd_version = 4,
.targets = &[_][]const u8{"x86_64-macos"},
.uuids = &.{
.{ .target = "x86_64-macos", .value = "2F7F7303-DB23-359E-85CD-8B2F93223E2A" },
},
.install_name = "/usr/lib/system/libcache.dylib",
.current_version = .{ .int = 83 },
.parent_umbrella = &.{
.{
.targets = &.{"x86_64-macos"},
.umbrella = "System",
},
},
.exports = &.{
.{
.targets = &.{"x86_64-macos"},
.symbols = &.{ "_cache_create", "_cache_destroy" },
},
},
.reexported_libraries = null,
},
};
for (result) |lib, i| {
try testing.expect(lib.eql(expected[i]));
}
} | test/test.zig |
const std = @import("std");
const errors = @import("errors.zig");
const mem = std.mem;
const math = std.math;
const testing = std.testing;
const unicode = std.unicode;
const LexerErrors = error{TokenizerError};
pub fn isIdentifier(c: u32) bool {
return switch (c) {
'a'...'z',
'A'...'Z',
'_',
'0'...'9',
=> true,
else => false,
};
}
fn isWhitespace(c: u32) bool {
return switch (c) {
'\n', ' ', '\t', '\r' => true,
else => false,
};
}
fn expectTokens(source: []const u8, expected_tokens: []const Token.Id) !void {
var source_with_space = std.ArrayList(u8).init(std.testing.allocator);
defer source_with_space.deinit();
try source_with_space.appendSlice(source);
try source_with_space.append('\n');
var tokenizer = Tokenizer{ .tokens = undefined, .it = .{
.i = 0,
.bytes = source_with_space.items,
} };
blk: {
for (expected_tokens) |e_token| {
const token = tokenizer.next() catch break :blk;
try std.testing.expectEqual(e_token, token.id);
}
const last_token = tokenizer.next() catch break :blk;
try std.testing.expect(last_token.id == .Eof);
return;
}
@panic("Test failed");
}
pub const Token = struct {
start: u32,
end: u32,
id: Id,
pub const List = std.ArrayList(Token);
pub const Index = u32;
pub const Id = union(enum) {
Atom,
BracketLeft,
BracketRight,
BuiltinDefine,
BuiltinLocalDefine,
BuiltinDup,
BuiltinAsType,
BuiltinFor,
BuiltinRange,
BuiltinIf,
BuiltinIfElse,
BuiltinPrint,
BuiltinReturn,
BuiltinRequireStack,
BuiltinSwap,
BuiltinWhile,
Comment,
Eof,
Number,
Function,
PreProcUse,
OperatorDivide,
OperatorEqual,
OperatorGreaterThan,
OperatorGreaterThanOrEqual,
OperatorLessThan,
OperatorLessThanOrEqual,
OperatorMinus,
OperatorModulo,
OperatorMultiply,
OperatorNotEqual,
OperatorPlus,
String,
};
pub const keywords = std.ComptimeStringMap(Id, .{
.{ "local", .BuiltinLocalDefine },
.{ "global", .BuiltinDefine },
.{ "dup", .BuiltinDup },
.{ "for", .BuiltinFor },
.{ "if", .BuiltinIf },
.{ "ifelse", .BuiltinIfElse },
.{ "astype", .BuiltinAsType },
.{ "print", .BuiltinPrint },
.{ "range", .BuiltinRange },
.{ "require_stack", .BuiltinRequireStack },
.{ "return", .BuiltinReturn },
.{ "swap", .BuiltinSwap },
.{ "while", .BuiltinWhile },
});
pub const directives = std.ComptimeStringMap(Id, .{
.{ "@use", .PreProcUse },
});
};
pub const Tokenizer = struct {
tokens: Token.List,
it: unicode.Utf8Iterator,
string: bool = false,
comment: bool = false,
fn reportError(self: *Tokenizer, message: []const u8, c: u32) LexerErrors {
var character: [1]u8 = undefined;
_ = unicode.utf8Encode(@truncate(u21, c), &character) catch unreachable;
errors.lexer_panic(message, character);
self.it.i = self.it.bytes.len;
return LexerErrors.TokenizerError;
}
fn next(self: *Tokenizer) !Token {
var start_index = self.it.i;
var state: enum {
Start,
String,
Colon,
ColonedIdentifier,
At,
AtIdentifier,
Minus,
Identifier,
Comment,
Number,
NumberDecimal,
NumberFractional,
Exclaimation,
LessThan,
GreaterThan,
} = .Start;
var res: Token.Id = .Eof;
while (self.it.nextCodepoint()) |c| {
switch (state) {
.Start => switch (c) {
'#' => {
self.comment = true;
state = .Comment;
},
'\"' => {
self.string = true;
state = .String;
},
'[' => {
res = .BracketLeft;
break;
},
']' => {
res = .BracketRight;
break;
},
':' => {
state = .Colon;
},
'!' => {
state = .Exclaimation;
},
'+' => {
res = .OperatorPlus;
break;
},
'-' => {
state = .Minus;
},
'/' => {
res = .OperatorDivide;
break;
},
'*' => {
res = .OperatorMultiply;
break;
},
'%' => {
res = .OperatorModulo;
break;
},
'=' => {
res = .OperatorEqual;
break;
},
'@' => {
state = .At;
},
'<' => {
state = .LessThan;
},
'>' => {
state = .GreaterThan;
},
'0'...'9' => {
state = .Number;
},
else => {
if (isWhitespace(c)) {
start_index = self.it.i;
} else if (isIdentifier(c)) {
state = .Identifier;
} else {
return self.reportError("Invalid Character", c);
}
},
},
.String => {
if (c == '\"') {
self.string = false;
res = .String;
break;
}
},
.Comment => {
if (c == '#') {
self.comment = false;
res = .Comment;
break;
}
},
.Colon => switch (c) {
'0'...'9' => {
return self.reportError("Atomic name cannot start with number.", c);
},
else => {
if (isWhitespace(c)) {
return self.reportError("Colon requires valid name following it.", c);
} else if (isIdentifier(c)) {
state = .ColonedIdentifier;
}
},
},
.ColonedIdentifier => {
if (!isIdentifier(c)) {
self.it.i -= unicode.utf8CodepointSequenceLength(c) catch unreachable;
res = .Atom;
break;
}
},
.At => {
if (isWhitespace(c)) {
return self.reportError("At requires preprocessor statement following it.", c);
} else if (isIdentifier(c)) {
state = .AtIdentifier;
}
},
.AtIdentifier => {
if (!isIdentifier(c)) {
self.it.i -= unicode.utf8CodepointSequenceLength(c) catch unreachable;
const slice = self.it.bytes[start_index..self.it.i];
res = Token.directives.get(slice) orelse unreachable;
break;
}
},
.Minus => {
switch (c) {
'0'...'9' => {
state = .Number;
},
else => {
self.it.i = start_index + 1;
res = .OperatorMinus;
break;
},
}
},
.Identifier => {
if (!isIdentifier(c)) {
self.it.i -= unicode.utf8CodepointSequenceLength(c) catch unreachable;
const slice = self.it.bytes[start_index..self.it.i];
res = Token.keywords.get(slice) orelse .Function;
break;
}
},
.Number => switch (c) {
'0'...'9', '_' => {},
'.' => {
state = .NumberDecimal;
},
else => {
self.it.i -= unicode.utf8CodepointSequenceLength(c) catch unreachable;
res = .Number;
break;
},
},
.NumberDecimal => switch (c) {
'0'...'9' => {
state = .NumberFractional;
},
else => {
return self.reportError("Float number requires digits after decimal point.", c);
},
},
.NumberFractional => switch (c) {
'0'...'9', '_' => {},
else => {
self.it.i -= unicode.utf8CodepointSequenceLength(c) catch unreachable;
res = .Number;
break;
},
},
.Exclaimation => switch (c) {
'=' => {
res = .OperatorNotEqual;
break;
},
else => {
return self.reportError("Invalid Exclaimation Mark. Use 'not' function for boolean not.", c);
},
},
.GreaterThan => switch (c) {
'=' => {
res = .OperatorGreaterThanOrEqual;
break;
},
else => {
if (isWhitespace(c)) {
res = .OperatorGreaterThan;
break;
} else {
return self.reportError("Surround 'greater than' symbols in spaces.", c);
}
},
},
.LessThan => switch (c) {
'=' => {
res = .OperatorLessThanOrEqual;
break;
},
else => {
if (isWhitespace(c)) {
res = .OperatorLessThan;
break;
} else {
return self.reportError("Surround 'less than' symbols in spaces.", c);
}
},
},
}
}
return Token{ .id = res, .start = @truncate(u32, start_index), .end = @truncate(u32, self.it.i) };
}
};
pub fn tokenize(alloc: std.mem.Allocator, source: []const u8) ![]const Token {
var source_with_space = std.ArrayList(u8).init(alloc);
defer source_with_space.deinit();
try source_with_space.appendSlice(source);
try source_with_space.append('\n');
const estimated_tokens = source.len / 8;
var tokenizer = Tokenizer{ .tokens = try Token.List.initCapacity(alloc, estimated_tokens), .it = .{
.i = 0,
.bytes = source_with_space.items,
} };
errdefer tokenizer.tokens.deinit();
while (true) {
const tok = try tokenizer.tokens.addOne();
tok.* = try tokenizer.next();
if (tok.id == .Eof) {
return tokenizer.tokens.toOwnedSlice();
}
}
}
test "single_tokens" {
try expectTokens("+ - / * [] = %", &[_]Token.Id{
.OperatorPlus,
.OperatorMinus,
.OperatorDivide,
.OperatorMultiply,
.BracketLeft,
.BracketRight,
.OperatorEqual,
.OperatorModulo,
});
}
test "strings_n_things" {
try expectTokens("\"Hello World\" + +", &[_]Token.Id{
.String,
.OperatorPlus,
.OperatorPlus,
});
}
test "average_hello_world" {
try expectTokens("\"Hello World\" puts #This program prints HELLO WORLD!#", &[_]Token.Id{
.String,
.Function,
.Comment,
});
}
test "atomics" {
try expectTokens(":hello_there :this_atomic", &[_]Token.Id{
.Atom,
.Atom,
});
} | src/lexer.zig |
const std = @import("std");
const use_test_input = false;
const filename = if (use_test_input) "day-8_test-input" else "day-8_real-input";
const line_count = if (use_test_input) 10 else 200;
pub fn main() !void {
std.debug.print("--- Day 8 ---\n", .{});
var file = try std.fs.cwd().openFile(filename, .{});
defer file.close();
var output_sum: u32 = 0;
var line_num: u32 = 0;
while (line_num < line_count):(line_num += 1) {
var buffer: [100]u8 = undefined;
const line = try file.reader().readUntilDelimiter(buffer[0..], '\n');
var outer_split = std.mem.split(u8, line, " | ");
const patterns = outer_split.next() orelse unreachable;
var one: []const u8 = undefined; // given by count 2
var four: []const u8 = undefined; // given by count 4
var seven: []const u8 = undefined; // given by count 3
var eight: []const u8 = undefined; // given by count 7
{
var patterns_split = std.mem.split(u8, patterns, " ");
while (patterns_split.next()) |digit| {
switch (digit.len) {
2 => one = digit,
4 => four = digit,
3 => seven = digit,
7 => eight = digit,
else => { }
}
}
}
var three: []const u8 = undefined; // count 5, shares 3 with seven
var six: []const u8 = undefined; // count 6, shares 2 with seven
var nine: []const u8 = undefined; // count 6, shares 4 with four
{
var patterns_split = std.mem.split(u8, patterns, " ");
while (patterns_split.next()) |digit| {
switch (digit.len) {
5 => {
if (shareCount(digit, seven) == 3) {
three = digit;
}
},
6 => {
if (shareCount(digit, seven) == 2) {
six = digit;
}
else if (shareCount(digit, four) == 4) {
nine = digit;
}
},
else => { }
}
}
}
var zero: []const u8 = undefined; // count 6, not six or nine
var five: []const u8 = undefined; // count 5, shares 5 with six
{
var patterns_split = std.mem.split(u8, patterns, " ");
while (patterns_split.next()) |digit| {
switch (digit.len) {
6 => {
if (shareCount(digit, six) != 6 and shareCount(digit, nine) != 6) {
zero = digit;
}
},
5 => {
if (shareCount(digit, six) == 5) {
five = digit;
}
},
else => { }
}
}
}
var two: []const u8 = undefined; // count 5 and not three or five
{
var patterns_split = std.mem.split(u8, patterns, " ");
while (patterns_split.next()) |digit| {
switch (digit.len) {
5 => {
if (shareCount(digit, three) != 5 and shareCount(digit, five) != 5) {
two = digit;
}
},
else => { }
}
}
}
const output = outer_split.next() orelse unreachable;
var output_split = std.mem.split(u8, output, " ");
var digit_index: u4 = 0;
while (digit_index < 4):(digit_index += 1) {
const digit_string = output_split.next() orelse unreachable;
var digit: u32 = undefined;
if (equals(digit_string, zero)) {
digit = 0;
}
else if (equals(digit_string, one)) {
digit = 1;
}
else if (equals(digit_string, two)) {
digit = 2;
}
else if (equals(digit_string, three)) {
digit = 3;
}
else if (equals(digit_string, four)) {
digit = 4;
}
else if (equals(digit_string, five)) {
digit = 5;
}
else if (equals(digit_string, six)) {
digit = 6;
}
else if (equals(digit_string, seven)) {
digit = 7;
}
else if (equals(digit_string, eight)) {
digit = 8;
}
else if (equals(digit_string, nine)) {
digit = 9;
}
switch (digit_index) {
0 => output_sum += digit * 1000,
1 => output_sum += digit * 100,
2 => output_sum += digit * 10,
3 => output_sum += digit,
else => unreachable
}
}
}
std.debug.print("total output sum is {}\n", .{ output_sum });
}
fn equals(lhs: []const u8, rhs: []const u8) bool {
return lhs.len == rhs.len and shareCount(lhs, rhs) == lhs.len;
}
fn shareCount(lhs: []const u8, rhs: []const u8) u32 {
var count: u32 = 0;
for (lhs) |l_char| {
for (rhs) |r_char| {
if (l_char == r_char) {
count += 1;
break;
}
}
}
return count;
} | day-8.zig |
const std = @import("std");
const testing = std.testing;
const case_fold_map = @import("../ziglyph.zig").case_fold_map;
const props = @import("../ziglyph.zig").derived_core_properties;
const cats = @import("../ziglyph.zig").derived_general_category;
const lower_map = @import("../ziglyph.zig").lower_map;
const title_map = @import("../ziglyph.zig").title_map;
const upper_map = @import("../ziglyph.zig").upper_map;
/// `isCased` detects letters that can be either upper, lower, or title cased.
pub fn isCased(cp: u21) bool {
// ASCII optimization.
if ((cp >= 'A' and cp <= 'Z') or (cp >= 'a' and cp <= 'z')) return true;
return props.isCased(cp);
}
/// `isLetter` covers all letters in Unicode, not just ASCII.
pub fn isLetter(cp: u21) bool {
// ASCII optimization.
if ((cp >= 'A' and cp <= 'Z') or (cp >= 'a' and cp <= 'z')) return true;
return cats.isLowercaseLetter(cp) or cats.isModifierLetter(cp) or cats.isOtherLetter(cp) or
cats.isTitlecaseLetter(cp) or cats.isUppercaseLetter(cp);
}
/// `isAscii` detects ASCII only letters.
pub fn isAsciiLetter(cp: u21) bool {
return (cp >= 'A' and cp <= 'Z') or (cp >= 'a' and cp <= 'z');
}
/// `isLower` detects code points that are lowercase.
pub fn isLower(cp: u21) bool {
// ASCII optimization.
if (cp >= 'a' and cp <= 'z') return true;
return props.isLowercase(cp);
}
/// `isAsciiLower` detects ASCII only lowercase letters.
pub fn isAsciiLower(cp: u21) bool {
return cp >= 'a' and cp <= 'z';
}
/// `isTitle` detects code points in titlecase.
pub fn isTitle(cp: u21) bool {
return cats.isTitlecaseLetter(cp);
}
/// `isUpper` detects code points in uppercase.
pub fn isUpper(cp: u21) bool {
// ASCII optimization.
if (cp >= 'A' and cp <= 'Z') return true;
return props.isUppercase(cp);
}
/// `isAsciiUpper` detects ASCII only uppercase letters.
pub fn isAsciiUpper(cp: u21) bool {
return cp >= 'A' and cp <= 'Z';
}
/// `toLower` returns the lowercase mapping for the given code point, or itself if none found.
pub fn toLower(cp: u21) u21 {
// ASCII optimization.
if (cp >= 'A' and cp <= 'Z') return cp ^ 32;
// Only cased letters.
if (!props.isChangesWhenCasemapped(cp)) return cp;
return lower_map.toLower(cp);
}
/// `toAsciiLower` converts an ASCII letter to lowercase.
pub fn toAsciiLower(cp: u21) u21 {
return if (cp >= 'A' and cp <= 'Z') cp ^ 32 else cp;
}
/// `toTitle` returns the titlecase mapping for the given code point, or itself if none found.
pub fn toTitle(cp: u21) u21 {
// Only cased letters.
if (!props.isChangesWhenCasemapped(cp)) return cp;
return title_map.toTitle(cp);
}
/// `toUpper` returns the uppercase mapping for the given code point, or itself if none found.
pub fn toUpper(cp: u21) u21 {
// ASCII optimization.
if (cp >= 'a' and cp <= 'z') return cp ^ 32;
// Only cased letters.
if (!props.isChangesWhenCasemapped(cp)) return cp;
return upper_map.toUpper(cp);
}
/// `toAsciiUpper` converts an ASCII letter to uppercase.
pub fn toAsciiUpper(cp: u21) u21 {
return if (cp >= 'a' and cp <= 'z') cp ^ 32 else cp;
}
/// `toCaseFold` will convert a code point into its case folded equivalent. Note that this can result
/// in a mapping to more than one code point, known as the full case fold. The returned array has 3
/// elements and the code points span until the first element equal to 0 or the end, whichever is first.
pub fn toCaseFold(cp: u21) [3]u21 {
return case_fold_map.toCaseFold(cp);
}
test "letter" {
const z = 'z';
try testing.expect(isLetter(z));
try testing.expect(!isUpper(z));
const uz = toUpper(z);
try testing.expect(isUpper(uz));
try testing.expectEqual(uz, 'Z');
}
test "letter isCased" {
try testing.expect(isCased('a'));
try testing.expect(isCased('A'));
try testing.expect(!isCased('1'));
}
test "letter isLower" {
try testing.expect(isLower('a'));
try testing.expect(isAsciiLower('a'));
try testing.expect(isLower('é'));
try testing.expect(isLower('i'));
try testing.expect(!isLower('A'));
try testing.expect(!isLower('É'));
try testing.expect(!isLower('İ'));
}
const expectEqualSlices = std.testing.expectEqualSlices;
test "letter toCaseFold" {
var result = toCaseFold('A');
try testing.expectEqualSlices(u21, &[_]u21{ 'a', 0, 0 }, &result);
result = toCaseFold('a');
try testing.expectEqualSlices(u21, &[_]u21{ 'a', 0, 0 }, &result);
result = toCaseFold('1');
try testing.expectEqualSlices(u21, &[_]u21{ '1', 0, 0 }, &result);
result = toCaseFold('\u{00DF}');
try testing.expectEqualSlices(u21, &[_]u21{ 0x0073, 0x0073, 0 }, &result);
result = toCaseFold('\u{0390}');
try testing.expectEqualSlices(u21, &[_]u21{ 0x03B9, 0x0308, 0x0301 }, &result);
}
test "letter toLower" {
try testing.expectEqual(toLower('a'), 'a');
try testing.expectEqual(toLower('A'), 'a');
try testing.expectEqual(toLower('İ'), 'i');
try testing.expectEqual(toLower('É'), 'é');
try testing.expectEqual(toLower(0x80), 0x80);
try testing.expectEqual(toLower(0x80), 0x80);
try testing.expectEqual(toLower('Å'), 'å');
try testing.expectEqual(toLower('å'), 'å');
try testing.expectEqual(toLower('\u{212A}'), 'k');
try testing.expectEqual(toLower('1'), '1');
}
test "letter isUpper" {
try testing.expect(!isUpper('a'));
try testing.expect(!isAsciiUpper('a'));
try testing.expect(!isUpper('é'));
try testing.expect(!isUpper('i'));
try testing.expect(isUpper('A'));
try testing.expect(isUpper('É'));
try testing.expect(isUpper('İ'));
}
test "letter toUpper" {
try testing.expectEqual(toUpper('a'), 'A');
try testing.expectEqual(toUpper('A'), 'A');
try testing.expectEqual(toUpper('i'), 'I');
try testing.expectEqual(toUpper('é'), 'É');
try testing.expectEqual(toUpper(0x80), 0x80);
try testing.expectEqual(toUpper('Å'), 'Å');
try testing.expectEqual(toUpper('å'), 'Å');
try testing.expectEqual(toUpper('1'), '1');
}
test "letter isTitle" {
try testing.expect(!isTitle('a'));
try testing.expect(!isTitle('é'));
try testing.expect(!isTitle('i'));
try testing.expect(isTitle('\u{1FBC}'));
try testing.expect(isTitle('\u{1FCC}'));
try testing.expect(isTitle('Lj'));
}
test "letter toTitle" {
try testing.expectEqual(toTitle('a'), 'A');
try testing.expectEqual(toTitle('A'), 'A');
try testing.expectEqual(toTitle('i'), 'I');
try testing.expectEqual(toTitle('é'), 'É');
try testing.expectEqual(toTitle('1'), '1');
}
test "letter isLetter" {
var cp: u21 = 'a';
while (cp <= 'z') : (cp += 1) {
try testing.expect(isLetter(cp));
}
cp = 'A';
while (cp <= 'Z') : (cp += 1) {
try testing.expect(isLetter(cp));
}
try testing.expect(isLetter('É'));
try testing.expect(isLetter('\u{2CEB3}'));
try testing.expect(!isLetter('\u{0003}'));
} | .gyro/ziglyph-jecolon-github.com-c37d93b6/pkg/src/category/letter.zig |
const Vec2 = @import("vec2.zig").Vec2;
const Rect = @import("rect.zig").Rect;
const RectI = @import("rect.zig").RectI;
pub const Quad = struct {
img_w: f32,
img_h: f32,
positions: [4]Vec2 = undefined,
uvs: [4]Vec2 = undefined,
pub fn init(x: f32, y: f32, width: f32, height: f32, img_w: f32, img_h: f32) Quad {
var q = Quad{
.img_w = img_w,
.img_h = img_h,
};
q.setViewport(x, y, width, height);
return q;
}
pub fn setViewportRect(self: *Quad, viewport: Rect) void {
self.setViewport(viewport.x, viewport.y, viewport.w, viewport.h);
}
pub fn setViewportRectI(self: *Quad, viewport: RectI) void {
self.setViewport(@intToFloat(f32, viewport.x), @intToFloat(f32, viewport.y), @intToFloat(f32, viewport.w), @intToFloat(f32, viewport.h));
}
pub fn setViewport(self: *Quad, x: f32, y: f32, width: f32, height: f32) void {
self.positions[0] = Vec2{ .x = 0, .y = 0 }; // bl
self.positions[1] = Vec2{ .x = width, .y = 0 }; // br
self.positions[2] = Vec2{ .x = width, .y = height }; // tr
self.positions[3] = Vec2{ .x = 0, .y = height }; // tl
// squeeze texcoords in by 128th of a pixel to avoid bleed
const w_tol = (1.0 / self.img_w) / 128.0;
const h_tol = (1.0 / self.img_h) / 128.0;
const inv_w = 1.0 / self.img_w;
const inv_h = 1.0 / self.img_h;
self.uvs[0] = Vec2{ .x = x * inv_w + w_tol, .y = y * inv_h + h_tol };
self.uvs[1] = Vec2{ .x = (x + width) * inv_w - w_tol, .y = y * inv_h + h_tol };
self.uvs[2] = Vec2{ .x = (x + width) * inv_w - w_tol, .y = (y + height) * inv_h - h_tol };
self.uvs[3] = Vec2{ .x = x * inv_w + w_tol, .y = (y + height) * inv_h - h_tol };
}
/// sets the Quad to be the full size of the texture
pub fn setFill(self: *Quad, img_w: f32, img_h: f32) void {
self.setImageDimensions(img_w, img_h);
self.setViewport(0, 0, img_w, img_h);
}
pub fn setImageDimensions(self: *Quad, w: f32, h: f32) void {
self.img_w = w;
self.img_h = h;
}
};
test "quad tests" {
var q1 = Quad.init(0, 0, 50, 50, 600, 400);
q1.setImageDimensions(600, 400);
q1.setViewportRect(.{ .x = 0, .y = 0, .w = 50, .h = 0 });
} | gamekit/math/quad.zig |
// TODO: Updated recently.
const builtin = @import("builtin");
const std = @import("../std.zig");
const math = std.math;
const expect = std.testing.expect;
/// Returns e raised to the power of x, minus 1 (e^x - 1). This is more accurate than exp(e, x) - 1
/// when x is near 0.
///
/// Special Cases:
/// - expm1(+inf) = +inf
/// - expm1(-inf) = -1
/// - expm1(nan) = nan
pub fn expm1(x: var) @typeOf(x) {
const T = @typeOf(x);
return switch (T) {
f32 => expm1_32(x),
f64 => expm1_64(x),
else => @compileError("exp1m not implemented for " ++ @typeName(T)),
};
}
fn expm1_32(x_: f32) f32 {
if (math.isNan(x_))
return math.nan(f32);
const o_threshold: f32 = 8.8721679688e+01;
const ln2_hi: f32 = 6.9313812256e-01;
const ln2_lo: f32 = 9.0580006145e-06;
const invln2: f32 = 1.4426950216e+00;
const Q1: f32 = -3.3333212137e-2;
const Q2: f32 = 1.5807170421e-3;
var x = x_;
const ux = @bitCast(u32, x);
const hx = ux & 0x7FFFFFFF;
const sign = hx >> 31;
// TODO: Shouldn't need this check explicitly.
if (math.isNegativeInf(x)) {
return -1.0;
}
// |x| >= 27 * ln2
if (hx >= 0x4195B844) {
// nan
if (hx > 0x7F800000) {
return x;
}
if (sign != 0) {
return -1;
}
if (x > o_threshold) {
x *= 0x1.0p127;
return x;
}
}
var hi: f32 = undefined;
var lo: f32 = undefined;
var c: f32 = undefined;
var k: i32 = undefined;
// |x| > 0.5 * ln2
if (hx > 0x3EB17218) {
// |x| < 1.5 * ln2
if (hx < 0x3F851592) {
if (sign == 0) {
hi = x - ln2_hi;
lo = ln2_lo;
k = 1;
} else {
hi = x + ln2_hi;
lo = -ln2_lo;
k = -1;
}
} else {
var kf = invln2 * x;
if (sign != 0) {
kf -= 0.5;
} else {
kf += 0.5;
}
k = @floatToInt(i32, kf);
const t = @intToFloat(f32, k);
hi = x - t * ln2_hi;
lo = t * ln2_lo;
}
x = hi - lo;
c = (hi - x) - lo;
}
// |x| < 2^(-25)
else if (hx < 0x33000000) {
if (hx < 0x00800000) {
math.forceEval(x * x);
}
return x;
} else {
k = 0;
}
const hfx = 0.5 * x;
const hxs = x * hfx;
const r1 = 1.0 + hxs * (Q1 + hxs * Q2);
const t = 3.0 - r1 * hfx;
var e = hxs * ((r1 - t) / (6.0 - x * t));
// c is 0
if (k == 0) {
return x - (x * e - hxs);
}
e = x * (e - c) - c;
e -= hxs;
// exp(x) ~ 2^k (x_reduced - e + 1)
if (k == -1) {
return 0.5 * (x - e) - 0.5;
}
if (k == 1) {
if (x < -0.25) {
return -2.0 * (e - (x + 0.5));
} else {
return 1.0 + 2.0 * (x - e);
}
}
const twopk = @bitCast(f32, @intCast(u32, (0x7F +% k) << 23));
if (k < 0 or k > 56) {
var y = x - e + 1.0;
if (k == 128) {
y = y * 2.0 * 0x1.0p127;
} else {
y = y * twopk;
}
return y - 1.0;
}
const uf = @bitCast(f32, @intCast(u32, 0x7F -% k) << 23);
if (k < 23) {
return (x - e + (1 - uf)) * twopk;
} else {
return (x - (e + uf) + 1) * twopk;
}
}
fn expm1_64(x_: f64) f64 {
if (math.isNan(x_))
return math.nan(f64);
const o_threshold: f64 = 7.09782712893383973096e+02;
const ln2_hi: f64 = 6.93147180369123816490e-01;
const ln2_lo: f64 = 1.90821492927058770002e-10;
const invln2: f64 = 1.44269504088896338700e+00;
const Q1: f64 = -3.33333333333331316428e-02;
const Q2: f64 = 1.58730158725481460165e-03;
const Q3: f64 = -7.93650757867487942473e-05;
const Q4: f64 = 4.00821782732936239552e-06;
const Q5: f64 = -2.01099218183624371326e-07;
var x = x_;
const ux = @bitCast(u64, x);
const hx = @intCast(u32, ux >> 32) & 0x7FFFFFFF;
const sign = ux >> 63;
if (math.isNegativeInf(x)) {
return -1.0;
}
// |x| >= 56 * ln2
if (hx >= 0x4043687A) {
// exp1md(nan) = nan
if (hx > 0x7FF00000) {
return x;
}
// exp1md(-ve) = -1
if (sign != 0) {
return -1;
}
if (x > o_threshold) {
math.raiseOverflow();
return math.inf(f64);
}
}
var hi: f64 = undefined;
var lo: f64 = undefined;
var c: f64 = undefined;
var k: i32 = undefined;
// |x| > 0.5 * ln2
if (hx > 0x3FD62E42) {
// |x| < 1.5 * ln2
if (hx < 0x3FF0A2B2) {
if (sign == 0) {
hi = x - ln2_hi;
lo = ln2_lo;
k = 1;
} else {
hi = x + ln2_hi;
lo = -ln2_lo;
k = -1;
}
} else {
var kf = invln2 * x;
if (sign != 0) {
kf -= 0.5;
} else {
kf += 0.5;
}
k = @floatToInt(i32, kf);
const t = @intToFloat(f64, k);
hi = x - t * ln2_hi;
lo = t * ln2_lo;
}
x = hi - lo;
c = (hi - x) - lo;
}
// |x| < 2^(-54)
else if (hx < 0x3C900000) {
if (hx < 0x00100000) {
math.forceEval(@floatCast(f32, x));
}
return x;
} else {
k = 0;
}
const hfx = 0.5 * x;
const hxs = x * hfx;
const r1 = 1.0 + hxs * (Q1 + hxs * (Q2 + hxs * (Q3 + hxs * (Q4 + hxs * Q5))));
const t = 3.0 - r1 * hfx;
var e = hxs * ((r1 - t) / (6.0 - x * t));
// c is 0
if (k == 0) {
return x - (x * e - hxs);
}
e = x * (e - c) - c;
e -= hxs;
// exp(x) ~ 2^k (x_reduced - e + 1)
if (k == -1) {
return 0.5 * (x - e) - 0.5;
}
if (k == 1) {
if (x < -0.25) {
return -2.0 * (e - (x + 0.5));
} else {
return 1.0 + 2.0 * (x - e);
}
}
const twopk = @bitCast(f64, @intCast(u64, 0x3FF +% k) << 52);
if (k < 0 or k > 56) {
var y = x - e + 1.0;
if (k == 1024) {
y = y * 2.0 * 0x1.0p1023;
} else {
y = y * twopk;
}
return y - 1.0;
}
const uf = @bitCast(f64, @intCast(u64, 0x3FF -% k) << 52);
if (k < 20) {
return (x - e + (1 - uf)) * twopk;
} else {
return (x - (e + uf) + 1) * twopk;
}
}
test "math.exp1m" {
expect(expm1(@as(f32, 0.0)) == expm1_32(0.0));
expect(expm1(@as(f64, 0.0)) == expm1_64(0.0));
}
test "math.expm1_32" {
const epsilon = 0.000001;
expect(expm1_32(0.0) == 0.0);
expect(math.approxEq(f32, expm1_32(0.0), 0.0, epsilon));
expect(math.approxEq(f32, expm1_32(0.2), 0.221403, epsilon));
expect(math.approxEq(f32, expm1_32(0.8923), 1.440737, epsilon));
expect(math.approxEq(f32, expm1_32(1.5), 3.481689, epsilon));
}
test "math.expm1_64" {
const epsilon = 0.000001;
expect(expm1_64(0.0) == 0.0);
expect(math.approxEq(f64, expm1_64(0.0), 0.0, epsilon));
expect(math.approxEq(f64, expm1_64(0.2), 0.221403, epsilon));
expect(math.approxEq(f64, expm1_64(0.8923), 1.440737, epsilon));
expect(math.approxEq(f64, expm1_64(1.5), 3.481689, epsilon));
}
test "math.expm1_32.special" {
const epsilon = 0.000001;
expect(math.isPositiveInf(expm1_32(math.inf(f32))));
expect(expm1_32(-math.inf(f32)) == -1.0);
expect(math.isNan(expm1_32(math.nan(f32))));
}
test "math.expm1_64.special" {
const epsilon = 0.000001;
expect(math.isPositiveInf(expm1_64(math.inf(f64))));
expect(expm1_64(-math.inf(f64)) == -1.0);
expect(math.isNan(expm1_64(math.nan(f64))));
} | lib/std/math/expm1.zig |
const std = @import("std");
const debug = std.debug;
const mem = std.mem;
const math = std.math;
const testing = std.testing;
const AuthenticationError = std.crypto.errors.AuthenticationError;
/// ISAPv2 is an authenticated encryption system hardened against side channels and fault attacks.
/// https://csrc.nist.gov/CSRC/media/Projects/lightweight-cryptography/documents/round-2/spec-doc-rnd2/isap-spec-round2.pdf
///
/// Note that ISAP is not suitable for high-performance applications.
///
/// However:
/// - if allowing physical access to the device is part of your threat model,
/// - or if you need resistance against microcode/hardware-level side channel attacks,
/// - or if software-induced fault attacks such as rowhammer are a concern,
///
/// then you may consider ISAP for highly sensitive data.
pub const IsapA128A = struct {
pub const key_length = 16;
pub const nonce_length = 16;
pub const tag_length: usize = 16;
const iv1 = [_]u8{ 0x01, 0x80, 0x40, 0x01, 0x0c, 0x01, 0x06, 0x0c };
const iv2 = [_]u8{ 0x02, 0x80, 0x40, 0x01, 0x0c, 0x01, 0x06, 0x0c };
const iv3 = [_]u8{ 0x03, 0x80, 0x40, 0x01, 0x0c, 0x01, 0x06, 0x0c };
const Block = [5]u64;
block: Block,
fn round(isap: *IsapA128A, rk: u64) void {
var x = &isap.block;
x[2] ^= rk;
x[0] ^= x[4];
x[4] ^= x[3];
x[2] ^= x[1];
var t = x.*;
x[0] = t[0] ^ ((~t[1]) & t[2]);
x[2] = t[2] ^ ((~t[3]) & t[4]);
x[4] = t[4] ^ ((~t[0]) & t[1]);
x[1] = t[1] ^ ((~t[2]) & t[3]);
x[3] = t[3] ^ ((~t[4]) & t[0]);
x[1] ^= x[0];
t[1] = x[1];
x[1] = math.rotr(u64, x[1], 39);
x[3] ^= x[2];
t[2] = x[2];
x[2] = math.rotr(u64, x[2], 1);
t[4] = x[4];
t[2] ^= x[2];
x[2] = math.rotr(u64, x[2], 5);
t[3] = x[3];
t[1] ^= x[1];
x[3] = math.rotr(u64, x[3], 10);
x[0] ^= x[4];
x[4] = math.rotr(u64, x[4], 7);
t[3] ^= x[3];
x[2] ^= t[2];
x[1] = math.rotr(u64, x[1], 22);
t[0] = x[0];
x[2] = ~x[2];
x[3] = math.rotr(u64, x[3], 7);
t[4] ^= x[4];
x[4] = math.rotr(u64, x[4], 34);
x[3] ^= t[3];
x[1] ^= t[1];
x[0] = math.rotr(u64, x[0], 19);
x[4] ^= t[4];
t[0] ^= x[0];
x[0] = math.rotr(u64, x[0], 9);
x[0] ^= t[0];
}
fn p12(isap: *IsapA128A) void {
const rks = [12]u64{ 0xf0, 0xe1, 0xd2, 0xc3, 0xb4, 0xa5, 0x96, 0x87, 0x78, 0x69, 0x5a, 0x4b };
inline for (rks) |rk| {
isap.round(rk);
}
}
fn p6(isap: *IsapA128A) void {
const rks = [6]u64{ 0x96, 0x87, 0x78, 0x69, 0x5a, 0x4b };
inline for (rks) |rk| {
isap.round(rk);
}
}
fn p1(isap: *IsapA128A) void {
isap.round(0x4b);
}
fn absorb(isap: *IsapA128A, m: []const u8) void {
var block = &isap.block;
var i: usize = 0;
while (true) : (i += 8) {
const left = m.len - i;
if (left >= 8) {
block[0] ^= mem.readIntBig(u64, m[i..][0..8]);
isap.p12();
if (left == 8) {
block[0] ^= 0x8000000000000000;
isap.p12();
break;
}
} else {
var padded = [_]u8{0} ** 8;
mem.copy(u8, padded[0..left], m[i..]);
padded[left] = 0x80;
block[0] ^= mem.readIntBig(u64, padded[0..]);
isap.p12();
break;
}
}
}
fn trickle(k: [16]u8, iv: [8]u8, y: []const u8, comptime out_len: usize) [out_len]u8 {
var isap = IsapA128A{
.block = Block{
mem.readIntBig(u64, k[0..8]),
mem.readIntBig(u64, k[8..16]),
mem.readIntBig(u64, iv[0..8]),
0,
0,
},
};
isap.p12();
var i: usize = 0;
while (i < y.len * 8 - 1) : (i += 1) {
const cur_byte_pos = i / 8;
const cur_bit_pos = @truncate(u3, 7 - (i % 8));
const cur_bit = @as(u64, ((y[cur_byte_pos] >> cur_bit_pos) & 1) << 7);
isap.block[0] ^= cur_bit << 56;
isap.p1();
}
const cur_bit = @as(u64, (y[y.len - 1] & 1) << 7);
isap.block[0] ^= cur_bit << 56;
isap.p12();
var out: [out_len]u8 = undefined;
var j: usize = 0;
while (j < out_len) : (j += 8) {
mem.writeIntBig(u64, out[j..][0..8], isap.block[j / 8]);
}
std.crypto.utils.secureZero(u64, &isap.block);
return out;
}
fn mac(c: []const u8, ad: []const u8, npub: [16]u8, key: [16]u8) [16]u8 {
var isap = IsapA128A{
.block = Block{
mem.readIntBig(u64, npub[0..8]),
mem.readIntBig(u64, npub[8..16]),
mem.readIntBig(u64, iv1[0..]),
0,
0,
},
};
isap.p12();
isap.absorb(ad);
isap.block[4] ^= 1;
isap.absorb(c);
var y: [16]u8 = undefined;
mem.writeIntBig(u64, y[0..8], isap.block[0]);
mem.writeIntBig(u64, y[8..16], isap.block[1]);
const nb = trickle(key, iv2, y[0..], 16);
isap.block[0] = mem.readIntBig(u64, nb[0..8]);
isap.block[1] = mem.readIntBig(u64, nb[8..16]);
isap.p12();
var tag: [16]u8 = undefined;
mem.writeIntBig(u64, tag[0..8], isap.block[0]);
mem.writeIntBig(u64, tag[8..16], isap.block[1]);
std.crypto.utils.secureZero(u64, &isap.block);
return tag;
}
fn xor(out: []u8, in: []const u8, npub: [16]u8, key: [16]u8) void {
debug.assert(in.len == out.len);
const nb = trickle(key, iv3, npub[0..], 24);
var isap = IsapA128A{
.block = Block{
mem.readIntBig(u64, nb[0..8]),
mem.readIntBig(u64, nb[8..16]),
mem.readIntBig(u64, nb[16..24]),
mem.readIntBig(u64, npub[0..8]),
mem.readIntBig(u64, npub[8..16]),
},
};
isap.p6();
var i: usize = 0;
while (true) : (i += 8) {
const left = in.len - i;
if (left >= 8) {
mem.writeIntNative(u64, out[i..][0..8], mem.bigToNative(u64, isap.block[0]) ^ mem.readIntNative(u64, in[i..][0..8]));
if (left == 8) {
break;
}
isap.p6();
} else {
var pad = [_]u8{0} ** 8;
mem.copy(u8, pad[0..left], in[i..][0..left]);
mem.writeIntNative(u64, pad[i..][0..8], mem.bigToNative(u64, isap.block[0]) ^ mem.readIntNative(u64, pad[i..][0..8]));
mem.copy(u8, out[i..][0..left], pad[0..left]);
break;
}
}
std.crypto.utils.secureZero(u64, &isap.block);
}
pub fn encrypt(c: []u8, tag: *[tag_length]u8, m: []const u8, ad: []const u8, npub: [nonce_length]u8, key: [key_length]u8) void {
xor(c, m, npub, key);
tag.* = mac(c, ad, npub, key);
}
pub fn decrypt(m: []u8, c: []const u8, tag: [tag_length]u8, ad: []const u8, npub: [nonce_length]u8, key: [key_length]u8) AuthenticationError!void {
var computed_tag = mac(c, ad, npub, key);
var acc: u8 = 0;
for (computed_tag) |_, j| {
acc |= (computed_tag[j] ^ tag[j]);
}
std.crypto.utils.secureZero(u8, &computed_tag);
if (acc != 0) {
return error.AuthenticationFailed;
}
xor(m, c, npub, key);
}
};
test "ISAP" {
const k = [_]u8{1} ** 16;
const n = [_]u8{2} ** 16;
var tag: [16]u8 = undefined;
const ad = "ad";
var msg = "test";
var c: [msg.len]u8 = undefined;
IsapA128A.encrypt(c[0..], &tag, msg[0..], ad, n, k);
testing.expect(mem.eql(u8, &[_]u8{ 0x8f, 0x68, 0x03, 0x8d }, c[0..]));
testing.expect(mem.eql(u8, &[_]u8{ 0x6c, 0x25, 0xe8, 0xe2, 0xe1, 0x1f, 0x38, 0xe9, 0x80, 0x75, 0xde, 0xd5, 0x2d, 0xb2, 0x31, 0x82 }, tag[0..]));
try IsapA128A.decrypt(c[0..], c[0..], tag, ad, n, k);
testing.expect(mem.eql(u8, msg, c[0..]));
} | lib/std/crypto/isap.zig |
const Mir = @This();
const std = @import("std");
/// A struct of array that represents each individual wasm
instructions: std.MultiArrayList(Inst).Slice,
/// A slice of indexes where the meaning of the data is determined by the
/// `Inst.Tag` value.
extra: []const u32,
pub const Inst = struct {
/// The opcode that represents this instruction
tag: Tag,
/// This opcode will be set when `tag` represents an extended
/// instruction with prefix 0xFC, or a simd instruction with prefix 0xFD.
secondary: u8 = 0,
/// Data is determined by the set `tag`.
/// For example, `data` will be an i32 for when `tag` is 'i32_const'.
data: Data,
/// The position of a given MIR isntruction with the instruction list.
pub const Index = u32;
/// Contains all possible wasm opcodes the Zig compiler may emit
/// Rather than re-using std.wasm.Opcode, we only declare the opcodes
/// we need, and also use this possibility to document how to access
/// their payload.
///
/// Note: Uses its actual opcode value representation to easily convert
/// to and from its binary representation.
pub const Tag = enum(u8) {
/// Uses `nop`
@"unreachable" = 0x00,
/// Creates a new block that can be jump from.
///
/// Type of the block is given in data `block_type`
block = 0x02,
/// Creates a new loop.
///
/// Type of the loop is given in data `block_type`
loop = 0x03,
/// Represents the end of a function body or an initialization expression
///
/// Payload is `nop`
end = 0x0B,
/// Breaks from the current block to a label
///
/// Data is `label` where index represents the label to jump to
br = 0x0C,
/// Breaks from the current block if the stack value is non-zero
///
/// Data is `label` where index represents the label to jump to
br_if = 0x0D,
/// Jump table that takes the stack value as an index where each value
/// represents the label to jump to.
///
/// Data is extra of which the Payload's type is `JumpTable`
br_table = 0x0E,
/// Returns from the function
///
/// Uses `nop`
@"return" = 0x0F,
/// Calls a function by its index
///
/// Uses `label`
call = 0x10,
/// Calls a function pointer by its function signature
/// and index into the function table.
///
/// Uses `label`
call_indirect = 0x11,
/// Pops three values from the stack and pushes
/// the first or second value dependent on the third value.
/// Uses `tag`
select = 0x1B,
/// Loads a local at given index onto the stack.
///
/// Uses `label`
local_get = 0x20,
/// Pops a value from the stack into the local at given index.
/// Stack value must be of the same type as the local.
///
/// Uses `label`
local_set = 0x21,
/// Sets a local at given index using the value at the top of the stack without popping the value.
/// Stack value must have the same type as the local.
///
/// Uses `label`
local_tee = 0x22,
/// Loads a (mutable) global at given index onto the stack
///
/// Uses `label`
global_get = 0x23,
/// Pops a value from the stack and sets the global at given index.
/// Note: Both types must be equal and global must be marked mutable.
///
/// Uses `label`.
global_set = 0x24,
/// Loads a 32-bit integer from memory (data section) onto the stack
/// Pops the value from the stack which represents the offset into memory.
///
/// Uses `payload` of type `MemArg`.
i32_load = 0x28,
/// Loads a value from memory onto the stack, based on the signedness
/// and bitsize of the type.
///
/// Uses `payload` with type `MemArg`
i64_load = 0x29,
/// Loads a value from memory onto the stack, based on the signedness
/// and bitsize of the type.
///
/// Uses `payload` with type `MemArg`
f32_load = 0x2A,
/// Loads a value from memory onto the stack, based on the signedness
/// and bitsize of the type.
///
/// Uses `payload` with type `MemArg`
f64_load = 0x2B,
/// Loads a value from memory onto the stack, based on the signedness
/// and bitsize of the type.
///
/// Uses `payload` with type `MemArg`
i32_load8_s = 0x2C,
/// Loads a value from memory onto the stack, based on the signedness
/// and bitsize of the type.
///
/// Uses `payload` with type `MemArg`
i32_load8_u = 0x2D,
/// Loads a value from memory onto the stack, based on the signedness
/// and bitsize of the type.
///
/// Uses `payload` with type `MemArg`
i32_load16_s = 0x2E,
/// Loads a value from memory onto the stack, based on the signedness
/// and bitsize of the type.
///
/// Uses `payload` with type `MemArg`
i32_load16_u = 0x2F,
/// Loads a value from memory onto the stack, based on the signedness
/// and bitsize of the type.
///
/// Uses `payload` with type `MemArg`
i64_load8_s = 0x30,
/// Loads a value from memory onto the stack, based on the signedness
/// and bitsize of the type.
///
/// Uses `payload` with type `MemArg`
i64_load8_u = 0x31,
/// Loads a value from memory onto the stack, based on the signedness
/// and bitsize of the type.
///
/// Uses `payload` with type `MemArg`
i64_load16_s = 0x32,
/// Loads a value from memory onto the stack, based on the signedness
/// and bitsize of the type.
///
/// Uses `payload` with type `MemArg`
i64_load16_u = 0x33,
/// Loads a value from memory onto the stack, based on the signedness
/// and bitsize of the type.
///
/// Uses `payload` with type `MemArg`
i64_load32_s = 0x34,
/// Loads a value from memory onto the stack, based on the signedness
/// and bitsize of the type.
///
/// Uses `payload` with type `MemArg`
i64_load32_u = 0x35,
/// Pops 2 values from the stack, where the first value represents the value to write into memory
/// and the second value represents the offset into memory where the value must be written to.
/// This opcode is typed and expects the stack value's type to be equal to this opcode's type.
///
/// Uses `payload` of type `MemArg`.
i32_store = 0x36,
/// Pops 2 values from the stack, where the first value represents the value to write into memory
/// and the second value represents the offset into memory where the value must be written to.
/// This opcode is typed and expects the stack value's type to be equal to this opcode's type.
///
/// Uses `Payload` with type `MemArg`
i64_store = 0x37,
/// Pops 2 values from the stack, where the first value represents the value to write into memory
/// and the second value represents the offset into memory where the value must be written to.
/// This opcode is typed and expects the stack value's type to be equal to this opcode's type.
///
/// Uses `Payload` with type `MemArg`
f32_store = 0x38,
/// Pops 2 values from the stack, where the first value represents the value to write into memory
/// and the second value represents the offset into memory where the value must be written to.
/// This opcode is typed and expects the stack value's type to be equal to this opcode's type.
///
/// Uses `Payload` with type `MemArg`
f64_store = 0x39,
/// Pops 2 values from the stack, where the first value represents the value to write into memory
/// and the second value represents the offset into memory where the value must be written to.
/// This opcode is typed and expects the stack value's type to be equal to this opcode's type.
///
/// Uses `Payload` with type `MemArg`
i32_store8 = 0x3A,
/// Pops 2 values from the stack, where the first value represents the value to write into memory
/// and the second value represents the offset into memory where the value must be written to.
/// This opcode is typed and expects the stack value's type to be equal to this opcode's type.
///
/// Uses `Payload` with type `MemArg`
i32_store16 = 0x3B,
/// Pops 2 values from the stack, where the first value represents the value to write into memory
/// and the second value represents the offset into memory where the value must be written to.
/// This opcode is typed and expects the stack value's type to be equal to this opcode's type.
///
/// Uses `Payload` with type `MemArg`
i64_store8 = 0x3C,
/// Pops 2 values from the stack, where the first value represents the value to write into memory
/// and the second value represents the offset into memory where the value must be written to.
/// This opcode is typed and expects the stack value's type to be equal to this opcode's type.
///
/// Uses `Payload` with type `MemArg`
i64_store16 = 0x3D,
/// Pops 2 values from the stack, where the first value represents the value to write into memory
/// and the second value represents the offset into memory where the value must be written to.
/// This opcode is typed and expects the stack value's type to be equal to this opcode's type.
///
/// Uses `Payload` with type `MemArg`
i64_store32 = 0x3E,
/// Returns the memory size in amount of pages.
///
/// Uses `label`
memory_size = 0x3F,
/// Increases the memory by given number of pages.
///
/// Uses `label`
memory_grow = 0x40,
/// Loads a 32-bit signed immediate value onto the stack
///
/// Uses `imm32`
i32_const = 0x41,
/// Loads a i64-bit signed immediate value onto the stack
///
/// uses `payload` of type `Imm64`
i64_const = 0x42,
/// Loads a 32-bit float value onto the stack.
///
/// Uses `float32`
f32_const = 0x43,
/// Loads a 64-bit float value onto the stack.
///
/// Uses `payload` of type `Float64`
f64_const = 0x44,
/// Uses `tag`
i32_eqz = 0x45,
/// Uses `tag`
i32_eq = 0x46,
/// Uses `tag`
i32_ne = 0x47,
/// Uses `tag`
i32_lt_s = 0x48,
/// Uses `tag`
i32_lt_u = 0x49,
/// Uses `tag`
i32_gt_s = 0x4A,
/// Uses `tag`
i32_gt_u = 0x4B,
/// Uses `tag`
i32_le_s = 0x4C,
/// Uses `tag`
i32_le_u = 0x4D,
/// Uses `tag`
i32_ge_s = 0x4E,
/// Uses `tag`
i32_ge_u = 0x4F,
/// Uses `tag`
i64_eqz = 0x50,
/// Uses `tag`
i64_eq = 0x51,
/// Uses `tag`
i64_ne = 0x52,
/// Uses `tag`
i64_lt_s = 0x53,
/// Uses `tag`
i64_lt_u = 0x54,
/// Uses `tag`
i64_gt_s = 0x55,
/// Uses `tag`
i64_gt_u = 0x56,
/// Uses `tag`
i64_le_s = 0x57,
/// Uses `tag`
i64_le_u = 0x58,
/// Uses `tag`
i64_ge_s = 0x59,
/// Uses `tag`
i64_ge_u = 0x5A,
/// Uses `tag`
f32_eq = 0x5B,
/// Uses `tag`
f32_ne = 0x5C,
/// Uses `tag`
f32_lt = 0x5D,
/// Uses `tag`
f32_gt = 0x5E,
/// Uses `tag`
f32_le = 0x5F,
/// Uses `tag`
f32_ge = 0x60,
/// Uses `tag`
f64_eq = 0x61,
/// Uses `tag`
f64_ne = 0x62,
/// Uses `tag`
f64_lt = 0x63,
/// Uses `tag`
f64_gt = 0x64,
/// Uses `tag`
f64_le = 0x65,
/// Uses `tag`
f64_ge = 0x66,
/// Uses `tag`
i32_clz = 0x67,
/// Uses `tag`
i32_ctz = 0x68,
/// Uses `tag`
i32_popcnt = 0x69,
/// Uses `tag`
i32_add = 0x6A,
/// Uses `tag`
i32_sub = 0x6B,
/// Uses `tag`
i32_mul = 0x6C,
/// Uses `tag`
i32_div_s = 0x6D,
/// Uses `tag`
i32_div_u = 0x6E,
/// Uses `tag`
i32_rem_s = 0x6F,
/// Uses `tag`
i32_rem_u = 0x70,
/// Uses `tag`
i32_and = 0x71,
/// Uses `tag`
i32_or = 0x72,
/// Uses `tag`
i32_xor = 0x73,
/// Uses `tag`
i32_shl = 0x74,
/// Uses `tag`
i32_shr_s = 0x75,
/// Uses `tag`
i32_shr_u = 0x76,
/// Uses `tag`
i64_clz = 0x79,
/// Uses `tag`
i64_ctz = 0x7A,
/// Uses `tag`
i64_popcnt = 0x7B,
/// Uses `tag`
i64_add = 0x7C,
/// Uses `tag`
i64_sub = 0x7D,
/// Uses `tag`
i64_mul = 0x7E,
/// Uses `tag`
i64_div_s = 0x7F,
/// Uses `tag`
i64_div_u = 0x80,
/// Uses `tag`
i64_rem_s = 0x81,
/// Uses `tag`
i64_rem_u = 0x82,
/// Uses `tag`
i64_and = 0x83,
/// Uses `tag`
i64_or = 0x84,
/// Uses `tag`
i64_xor = 0x85,
/// Uses `tag`
i64_shl = 0x86,
/// Uses `tag`
i64_shr_s = 0x87,
/// Uses `tag`
i64_shr_u = 0x88,
/// Uses `tag`
f32_abs = 0x8B,
/// Uses `tag`
f32_neg = 0x8C,
/// Uses `tag`
f32_ceil = 0x8D,
/// Uses `tag`
f32_floor = 0x8E,
/// Uses `tag`
f32_trunc = 0x8F,
/// Uses `tag`
f32_nearest = 0x90,
/// Uses `tag`
f32_sqrt = 0x91,
/// Uses `tag`
f32_add = 0x92,
/// Uses `tag`
f32_sub = 0x93,
/// Uses `tag`
f32_mul = 0x94,
/// Uses `tag`
f32_div = 0x95,
/// Uses `tag`
f32_min = 0x96,
/// Uses `tag`
f32_max = 0x97,
/// Uses `tag`
f32_copysign = 0x98,
/// Uses `tag`
f64_abs = 0x99,
/// Uses `tag`
f64_neg = 0x9A,
/// Uses `tag`
f64_ceil = 0x9B,
/// Uses `tag`
f64_floor = 0x9C,
/// Uses `tag`
f64_trunc = 0x9D,
/// Uses `tag`
f64_nearest = 0x9E,
/// Uses `tag`
f64_sqrt = 0x9F,
/// Uses `tag`
f64_add = 0xA0,
/// Uses `tag`
f64_sub = 0xA1,
/// Uses `tag`
f64_mul = 0xA2,
/// Uses `tag`
f64_div = 0xA3,
/// Uses `tag`
f64_min = 0xA4,
/// Uses `tag`
f64_max = 0xA5,
/// Uses `tag`
f64_copysign = 0xA6,
/// Uses `tag`
i32_wrap_i64 = 0xA7,
/// Uses `tag`
i32_trunc_f32_s = 0xA8,
/// Uses `tag`
i32_trunc_f32_u = 0xA9,
/// Uses `tag`
i32_trunc_f64_s = 0xAA,
/// Uses `tag`
i32_trunc_f64_u = 0xAB,
/// Uses `tag`
i64_extend_i32_s = 0xAC,
/// Uses `tag`
i64_extend_i32_u = 0xAD,
/// Uses `tag`
i64_trunc_f32_s = 0xAE,
/// Uses `tag`
i64_trunc_f32_u = 0xAF,
/// Uses `tag`
i64_trunc_f64_s = 0xB0,
/// Uses `tag`
i64_trunc_f64_u = 0xB1,
/// Uses `tag`
f32_convert_i32_s = 0xB2,
/// Uses `tag`
f32_convert_i32_u = 0xB3,
/// Uses `tag`
f32_convert_i64_s = 0xB4,
/// Uses `tag`
f32_convert_i64_u = 0xB5,
/// Uses `tag`
f32_demote_f64 = 0xB6,
/// Uses `tag`
f64_convert_i32_s = 0xB7,
/// Uses `tag`
f64_convert_i32_u = 0xB8,
/// Uses `tag`
f64_convert_i64_s = 0xB9,
/// Uses `tag`
f64_convert_i64_u = 0xBA,
/// Uses `tag`
f64_promote_f32 = 0xBB,
/// Uses `tag`
i32_reinterpret_f32 = 0xBC,
/// Uses `tag`
i64_reinterpret_f64 = 0xBD,
/// Uses `tag`
f32_reinterpret_i32 = 0xBE,
/// Uses `tag`
f64_reinterpret_i64 = 0xBF,
/// Uses `tag`
i32_extend8_s = 0xC0,
/// Uses `tag`
i32_extend16_s = 0xC1,
/// Uses `tag`
i64_extend8_s = 0xC2,
/// Uses `tag`
i64_extend16_s = 0xC3,
/// Uses `tag`
i64_extend32_s = 0xC4,
/// The instruction consists of an extension opcode
/// set in `secondary`
///
/// The `data` field depends on the extension instruction
extended = 0xFC,
/// Contains a symbol to a function pointer
/// uses `label`
///
/// Note: This uses `0xFE` as value as it is unused and not reserved
/// by the wasm specification, making it safe to use.
function_index = 0xFE,
/// Contains a symbol to a memory address
/// Uses `label`
///
/// Note: This uses `0xFF` as value as it is unused and not reserved
/// by the wasm specification, making it safe to use.
memory_address = 0xFF,
/// From a given wasm opcode, returns a MIR tag.
pub fn fromOpcode(opcode: std.wasm.Opcode) Tag {
return @intToEnum(Tag, @enumToInt(opcode)); // Given `Opcode` is not present as a tag for MIR yet
}
/// Returns a wasm opcode from a given MIR tag.
pub fn toOpcode(self: Tag) std.wasm.Opcode {
return @intToEnum(std.wasm.Opcode, @enumToInt(self));
}
};
/// All instructions contain a 4-byte payload, which is contained within
/// this union. `Tag` determines which union tag is active, as well as
/// how to interpret the data within.
pub const Data = union {
/// Uses no additional data
tag: void,
/// Contains the result type of a block
///
/// Used by `block` and `loop`
block_type: u8,
/// Contains an u32 index into a wasm section entry, such as a local.
/// Note: This is not an index to another instruction.
///
/// Used by e.g. `local_get`, `local_set`, etc.
label: u32,
/// A 32-bit immediate value.
///
/// Used by `i32_const`
imm32: i32,
/// A 32-bit float value
///
/// Used by `f32_float`
float32: f32,
/// Index into `extra`. Meaning of what can be found there is context-dependent.
///
/// Used by e.g. `br_table`
payload: u32,
};
};
pub fn deinit(self: *Mir, gpa: std.mem.Allocator) void {
self.instructions.deinit(gpa);
gpa.free(self.extra);
self.* = undefined;
}
pub fn extraData(self: Mir, comptime T: type, index: usize) struct { data: T, end: usize } {
const fields = std.meta.fields(T);
var i: usize = index;
var result: T = undefined;
inline for (fields) |field| {
@field(result, field.name) = switch (field.field_type) {
u32 => self.extra[i],
else => |field_type| @compileError("Unsupported field type " ++ @typeName(field_type)),
};
i += 1;
}
return .{ .data = result, .end = i };
}
pub const JumpTable = struct {
/// Length of the jump table and the amount of entries it contains (includes default)
length: u32,
};
/// Stores an unsigned 64bit integer
/// into a 32bit most significant bits field
/// and a 32bit least significant bits field.
///
/// This uses an unsigned integer rather than a signed integer
/// as we can easily store those into `extra`
pub const Imm64 = struct {
msb: u32,
lsb: u32,
pub fn fromU64(imm: u64) Imm64 {
return .{
.msb = @truncate(u32, imm >> 32),
.lsb = @truncate(u32, imm),
};
}
pub fn toU64(self: Imm64) u64 {
var result: u64 = 0;
result |= @as(u64, self.msb) << 32;
result |= @as(u64, self.lsb);
return result;
}
};
pub const Float64 = struct {
msb: u32,
lsb: u32,
pub fn fromFloat64(float: f64) Float64 {
const tmp = @bitCast(u64, float);
return .{
.msb = @truncate(u32, tmp >> 32),
.lsb = @truncate(u32, tmp),
};
}
pub fn toF64(self: Float64) f64 {
@bitCast(f64, self.toU64());
}
pub fn toU64(self: Float64) u64 {
var result: u64 = 0;
result |= @as(u64, self.msb) << 32;
result |= @as(u64, self.lsb);
return result;
}
};
pub const MemArg = struct {
offset: u32,
alignment: u32,
};
/// Represents a memory address, which holds both the pointer
/// or the parent pointer and the offset to it.
pub const Memory = struct {
pointer: u32,
offset: u32,
}; | src/arch/wasm/Mir.zig |
const std = @import("std");
const assert = std.debug.assert;
const glfw = @import("glfw");
const c = @import("c.zig").c;
// #include "SampleUtils.h"
// #include "common/Assert.h"
// #include "common/Log.h"
// #include "common/Platform.h"
// #include "common/SystemUtils.h"
// #include "utils/BackendBinding.h"
// #include "utils/GLFWUtils.h"
// #include "utils/TerribleCommandBuffer.h"
// #include <dawn/dawn_proc.h>
// #include <dawn/dawn_wsi.h>
// #include <dawn_native/DawnNative.h>
// #include <dawn_wire/WireClient.h>
// #include <dawn_wire/WireServer.h>
// #include "GLFW/glfw3.h"
// #include <algorithm>
// #include <cstring>
fn printDeviceError(error_type: c.WGPUErrorType, message: [*c]const u8, _: ?*c_void) callconv(.C) void {
switch (error_type) {
c.WGPUErrorType_Validation => std.debug.print("dawn: validation error: {s}\n", .{message}),
c.WGPUErrorType_OutOfMemory => std.debug.print("dawn: out of memory: {s}\n", .{message}),
c.WGPUErrorType_Unknown => std.debug.print("dawn: unknown error: {s}\n", .{message}),
c.WGPUErrorType_DeviceLost => std.debug.print("dawn: device lost: {s}\n", .{message}),
else => unreachable,
}
}
const CmdBufType = enum { none, terrible };
// static std::unique_ptr<dawn_native::Instance> instance;
// static utils::BackendBinding* binding = nullptr;
// static GLFWwindow* window = nullptr;
// static dawn_wire::WireServer* wireServer = nullptr;
// static dawn_wire::WireClient* wireClient = nullptr;
// static utils::TerribleCommandBuffer* c2sBuf = nullptr;
// static utils::TerribleCommandBuffer* s2cBuf = nullptr;
const Setup = struct {
device: c.WGPUDevice,
binding: c.MachUtilsBackendBinding,
window: glfw.Window,
};
fn detectBackendType() c.WGPUBackendType {
if (std.os.getenv("WGPU_BACKEND")) |backend| {
if (std.ascii.eqlIgnoreCase(backend, "opengl")) return c.WGPUBackendType_OpenGL;
if (std.ascii.eqlIgnoreCase(backend, "opengles")) return c.WGPUBackendType_OpenGLES;
if (std.ascii.eqlIgnoreCase(backend, "d3d11")) return c.WGPUBackendType_D3D11;
if (std.ascii.eqlIgnoreCase(backend, "d3d12")) return c.WGPUBackendType_D3D12;
if (std.ascii.eqlIgnoreCase(backend, "metal")) return c.WGPUBackendType_Metal;
if (std.ascii.eqlIgnoreCase(backend, "null")) return c.WGPUBackendType_Null;
if (std.ascii.eqlIgnoreCase(backend, "vulkan")) return c.WGPUBackendType_Vulkan;
@panic("unknown BACKEND type");
}
const target = @import("builtin").target;
if (target.isDarwin()) return c.WGPUBackendType_Metal;
if (target.os.tag == .windows) return c.WGPUBackendType_D3D12;
return c.WGPUBackendType_Vulkan;
}
fn backendTypeString(t: c.WGPUBackendType) []const u8 {
return switch (t) {
c.WGPUBackendType_OpenGL => "OpenGL",
c.WGPUBackendType_OpenGLES => "OpenGLES",
c.WGPUBackendType_D3D11 => "D3D11",
c.WGPUBackendType_D3D12 => "D3D12",
c.WGPUBackendType_Metal => "Metal",
c.WGPUBackendType_Null => "Null",
c.WGPUBackendType_Vulkan => "Vulkan",
else => unreachable,
};
}
pub fn setup() !Setup {
const backend_type = detectBackendType();
const cmd_buf_type = CmdBufType.none;
try glfw.init(.{});
// Create the test window and discover adapters using it (esp. for OpenGL)
var hints = glfwWindowHintsForBackend(backend_type);
hints.cocoa_retina_framebuffer = false;
const window = try glfw.Window.create(640, 480, "Dawn window", null, null, hints);
const instance = c.machDawnNativeInstance_init();
try discoverAdapter(instance, window, backend_type);
const adapters = c.machDawnNativeInstance_getAdapters(instance);
var backend_adapter: ?c.MachDawnNativeAdapter = null;
var i: usize = 0;
while (i < c.machDawnNativeAdapters_length(adapters)) : (i += 1) {
const adapter = c.machDawnNativeAdapters_index(adapters, i);
const properties = c.machDawnNativeAdapter_getProperties(adapter);
if (c.machDawnNativeAdapterProperties_getBackendType(properties) == backend_type) {
const name = c.machDawnNativeAdapterProperties_getName(properties);
const driver_description = c.machDawnNativeAdapterProperties_getDriverDescription(properties);
std.debug.print("found {s} adapter: {s}, {s}\n", .{ backendTypeString(backend_type), name, driver_description });
backend_adapter = adapter;
}
}
assert(backend_adapter != null);
const backend_device = c.machDawnNativeAdapter_createDevice(backend_adapter.?, null);
const backend_procs = c.machDawnNativeGetProcs();
const binding = c.machUtilsCreateBinding(backend_type, @ptrCast(*c.GLFWwindow, window.handle), backend_device);
if (binding == null) {
@panic("failed to create binding");
}
// Choose whether to use the backend procs and devices directly, or set up the wire.
var procs: ?*const c.DawnProcTable = null;
var c_device: ?c.WGPUDevice = null;
switch (cmd_buf_type) {
CmdBufType.none => {
procs = backend_procs;
c_device = backend_device;
},
CmdBufType.terrible => {
// TODO(slimsag):
@panic("not implemented");
// c2sBuf = new utils::TerribleCommandBuffer();
// s2cBuf = new utils::TerribleCommandBuffer();
// dawn_wire::WireServerDescriptor serverDesc = {};
// serverDesc.procs = &backendProcs;
// serverDesc.serializer = s2cBuf;
// wireServer = new dawn_wire::WireServer(serverDesc);
// c2sBuf->SetHandler(wireServer);
// dawn_wire::WireClientDescriptor clientDesc = {};
// clientDesc.serializer = c2sBuf;
// wireClient = new dawn_wire::WireClient(clientDesc);
// procs = dawn_wire::client::GetProcs();
// s2cBuf->SetHandler(wireClient);
// auto deviceReservation = wireClient->ReserveDevice();
// wireServer->InjectDevice(backendDevice, deviceReservation.id,
// deviceReservation.generation);
// cDevice = deviceReservation.device;
},
}
c.dawnProcSetProcs(procs.?);
procs.?.deviceSetUncapturedErrorCallback.?(c_device.?, printDeviceError, null);
return Setup{
.device = c_device.?,
.binding = binding,
.window = window,
};
}
fn glfwWindowHintsForBackend(backend: c.WGPUBackendType) glfw.Window.Hints {
return switch (backend) {
c.WGPUBackendType_OpenGL => .{
// Ask for OpenGL 4.4 which is what the GL backend requires for compute shaders and
// texture views.
.context_version_major = 4,
.context_version_minor = 4,
.opengl_forward_compat = true,
.opengl_profile = .opengl_core_profile,
},
c.WGPUBackendType_OpenGLES => .{
.context_version_major = 3,
.context_version_minor = 1,
.client_api = .opengl_es_api,
.context_creation_api = .egl_context_api,
},
else => .{
// Without this GLFW will initialize a GL context on the window, which prevents using
// the window with other APIs (by crashing in weird ways).
.client_api = .no_api,
},
};
}
fn discoverAdapter(instance: c.MachDawnNativeInstance, window: glfw.Window, typ: c.WGPUBackendType) !void {
if (typ == c.WGPUBackendType_OpenGL) {
try glfw.makeContextCurrent(window);
const adapter_options = c.MachDawnNativeAdapterDiscoveryOptions_OpenGL{
.getProc = @ptrCast(fn ([*c]const u8) callconv(.C) ?*c_void, glfw.getProcAddress),
};
_ = c.machDawnNativeInstance_discoverAdapters(instance, typ, &adapter_options);
} else if (typ == c.WGPUBackendType_OpenGLES) {
try glfw.makeContextCurrent(window);
const adapter_options = c.MachDawnNativeAdapterDiscoveryOptions_OpenGLES{
.getProc = @ptrCast(fn ([*c]const u8) callconv(.C) ?*c_void, glfw.getProcAddress),
};
_ = c.machDawnNativeInstance_discoverAdapters(instance, typ, &adapter_options);
} else {
c.machDawnNativeInstance_discoverDefaultAdapters(instance);
}
}
// wgpu::TextureFormat GetPreferredSwapChainTextureFormat() {
// DoFlush();
// return static_cast<wgpu::TextureFormat>(binding->GetPreferredSwapChainTextureFormat());
// }
// wgpu::TextureView CreateDefaultDepthStencilView(const wgpu::Device& device) {
// wgpu::TextureDescriptor descriptor;
// descriptor.dimension = wgpu::TextureDimension::e2D;
// descriptor.size.width = 640;
// descriptor.size.height = 480;
// descriptor.size.depthOrArrayLayers = 1;
// descriptor.sampleCount = 1;
// descriptor.format = wgpu::TextureFormat::Depth24PlusStencil8;
// descriptor.mipLevelCount = 1;
// descriptor.usage = wgpu::TextureUsage::RenderAttachment;
// auto depthStencilTexture = device.CreateTexture(&descriptor);
// return depthStencilTexture.CreateView();
// }
// bool InitSample(int argc, const char** argv) {
// for (int i = 1; i < argc; i++) {
// if (std::string("-b") == argv[i] || std::string("--backend") == argv[i]) {
// i++;
// if (i < argc && std::string("d3d12") == argv[i]) {
// backendType = wgpu::BackendType::D3D12;
// continue;
// }
// if (i < argc && std::string("metal") == argv[i]) {
// backendType = wgpu::BackendType::Metal;
// continue;
// }
// if (i < argc && std::string("null") == argv[i]) {
// backendType = wgpu::BackendType::Null;
// continue;
// }
// if (i < argc && std::string("opengl") == argv[i]) {
// backendType = wgpu::BackendType::OpenGL;
// continue;
// }
// if (i < argc && std::string("opengles") == argv[i]) {
// backendType = wgpu::BackendType::OpenGLES;
// continue;
// }
// if (i < argc && std::string("vulkan") == argv[i]) {
// backendType = wgpu::BackendType::Vulkan;
// continue;
// }
// fprintf(stderr,
// "--backend expects a backend name (opengl, opengles, metal, d3d12, null, "
// "vulkan)\n");
// return false;
// }
// if (std::string("-c") == argv[i] || std::string("--command-buffer") == argv[i]) {
// i++;
// if (i < argc && std::string("none") == argv[i]) {
// cmdBufType = CmdBufType::None;
// continue;
// }
// if (i < argc && std::string("terrible") == argv[i]) {
// cmdBufType = CmdBufType::Terrible;
// continue;
// }
// fprintf(stderr, "--command-buffer expects a command buffer name (none, terrible)\n");
// return false;
// }
// if (std::string("-h") == argv[i] || std::string("--help") == argv[i]) {
// printf("Usage: %s [-b BACKEND] [-c COMMAND_BUFFER]\n", argv[0]);
// printf(" BACKEND is one of: d3d12, metal, null, opengl, opengles, vulkan\n");
// printf(" COMMAND_BUFFER is one of: none, terrible\n");
// return false;
// }
// }
// return true;
// } | gpu/src/dawn/sample_utils.zig |
const std = @import("std");
const mem = std.mem;
const ascii = std.ascii;
const fmt = std.fmt;
const warn = std.debug.warn;
const svd = @import("svd.zig");
var line_buffer: [1024 * 1024]u8 = undefined;
const register_def =
\\pub fn Register(comptime R: type) type {
\\ return RegisterRW(R, R);
\\}
\\
\\pub fn RegisterRW(comptime Read: type, comptime Write: type) type {
\\ return struct {
\\ raw_ptr: *volatile u32,
\\
\\ const Self = @This();
\\
\\ pub fn init(address: usize) Self {
\\ return Self{ .raw_ptr = @intToPtr(*volatile u32, address) };
\\ }
\\
\\ pub fn initRange(address: usize, comptime dim_increment: usize, comptime num_registers: usize) [num_registers]Self {
\\ var registers: [num_registers]Self = undefined;
\\ var i: usize = 0;
\\ while (i < num_registers) : (i += 1) {
\\ registers[i] = Self.init(address + (i * dim_increment));
\\ }
\\ return registers;
\\ }
\\
\\ pub fn read(self: Self) Read {
\\ return @bitCast(Read, self.raw_ptr.*);
\\ }
\\
\\ pub fn write(self: Self, value: Write) void {
\\ self.raw_ptr.* = @bitCast(u32, value);
\\ }
\\
\\ pub fn modify(self: Self, new_value: anytype) void {
\\ if (Read != Write) {
\\ @compileError("Can't modify because read and write types for this register aren't the same.");
\\ }
\\ var old_value = self.read();
\\ const info = @typeInfo(@TypeOf(new_value));
\\ inline for (info.Struct.fields) |field| {
\\ @field(old_value, field.name) = @field(new_value, field.name);
\\ }
\\ self.write(old_value);
\\ }
\\
\\ pub fn read_raw(self: Self) u32 {
\\ return self.raw_ptr.*;
\\ }
\\
\\ pub fn write_raw(self: Self, value: u32) void {
\\ self.raw_ptr.* = value;
\\ }
\\
\\ pub fn default_read_value(self: Self) Read {
\\ return Read{};
\\ }
\\
\\ pub fn default_write_value(self: Self) Write {
\\ return Write{};
\\ }
\\ };
\\}
\\
;
pub fn main() anyerror!void {
var arena = std.heap.ArenaAllocator.init(std.heap.page_allocator);
defer arena.deinit();
const allocator = &arena.allocator;
var args = std.process.args();
_ = args.next(allocator); // skip application name
// Note memory will be freed on exit since using arena
const file_name = try args.next(allocator) orelse return error.MandatoryFilenameArgumentNotGiven;
const file = try std.fs.cwd().openFile(file_name, .{ .read = true, .write = false });
const stream = &file.reader();
var state = SvdParseState.Device;
var dev = try svd.Device.init(allocator);
var cur_interrupt: svd.Interrupt = undefined;
while (try stream.readUntilDelimiterOrEof(&line_buffer, '\n')) |line| {
if (line.len == 0) {
break;
}
var chunk = getChunk(line) orelse continue;
switch (state) {
.Device => {
if (ascii.eqlIgnoreCase(chunk.tag, "/device")) {
state = .Finished;
} else if (ascii.eqlIgnoreCase(chunk.tag, "name")) {
if (chunk.data) |data| {
try dev.name.insertSlice(0, data);
}
} else if (ascii.eqlIgnoreCase(chunk.tag, "version")) {
if (chunk.data) |data| {
try dev.version.insertSlice(0, data);
}
} else if (ascii.eqlIgnoreCase(chunk.tag, "description")) {
if (chunk.data) |data| {
try dev.description.insertSlice(0, data);
}
} else if (ascii.eqlIgnoreCase(chunk.tag, "cpu")) {
var cpu = try svd.Cpu.init(allocator);
dev.cpu = cpu;
state = .Cpu;
} else if (ascii.eqlIgnoreCase(chunk.tag, "addressUnitBits")) {
if (chunk.data) |data| {
dev.address_unit_bits = fmt.parseInt(u32, data, 10) catch null;
}
} else if (ascii.eqlIgnoreCase(chunk.tag, "width")) {
if (chunk.data) |data| {
dev.max_bit_width = fmt.parseInt(u32, data, 10) catch null;
}
} else if (ascii.eqlIgnoreCase(chunk.tag, "size")) {
if (chunk.data) |data| {
dev.reg_default_size = fmt.parseInt(u32, data, 10) catch null;
}
} else if (ascii.eqlIgnoreCase(chunk.tag, "resetValue")) {
if (chunk.data) |data| {
dev.reg_default_reset_value = fmt.parseInt(u32, data, 10) catch null;
}
} else if (ascii.eqlIgnoreCase(chunk.tag, "resetMask")) {
if (chunk.data) |data| {
dev.reg_default_reset_mask = fmt.parseInt(u32, data, 10) catch null;
}
} else if (ascii.eqlIgnoreCase(chunk.tag, "peripherals")) {
state = .Peripherals;
}
},
.Cpu => {
if (ascii.eqlIgnoreCase(chunk.tag, "/cpu")) {
state = .Device;
} else if (ascii.eqlIgnoreCase(chunk.tag, "name")) {
if (chunk.data) |data| {
try dev.cpu.?.name.insertSlice(0, data);
}
} else if (ascii.eqlIgnoreCase(chunk.tag, "revision")) {
if (chunk.data) |data| {
try dev.cpu.?.revision.insertSlice(0, data);
}
} else if (ascii.eqlIgnoreCase(chunk.tag, "endian")) {
if (chunk.data) |data| {
try dev.cpu.?.endian.insertSlice(0, data);
}
} else if (ascii.eqlIgnoreCase(chunk.tag, "mpuPresent")) {
if (chunk.data) |data| {
dev.cpu.?.mpu_present = textToBool(data);
}
} else if (ascii.eqlIgnoreCase(chunk.tag, "fpuPresent")) {
if (chunk.data) |data| {
dev.cpu.?.fpu_present = textToBool(data);
}
} else if (ascii.eqlIgnoreCase(chunk.tag, "nvicPrioBits")) {
if (chunk.data) |data| {
dev.cpu.?.nvic_prio_bits = fmt.parseInt(u32, data, 10) catch null;
}
} else if (ascii.eqlIgnoreCase(chunk.tag, "vendorSystickConfig")) {
if (chunk.data) |data| {
dev.cpu.?.vendor_systick_config = textToBool(data);
}
}
},
.Peripherals => {
if (ascii.eqlIgnoreCase(chunk.tag, "/peripherals")) {
state = .Device;
} else if (ascii.eqlIgnoreCase(chunk.tag, "peripheral")) {
if (chunk.derivedFrom) |derivedFrom| {
for (dev.peripherals.items) |periph_being_checked| {
if (mem.eql(u8, periph_being_checked.name.items, derivedFrom)) {
try dev.peripherals.append(try periph_being_checked.copy(allocator));
state = .Peripheral;
break;
}
}
} else {
var periph = try svd.Peripheral.init(allocator);
try dev.peripherals.append(periph);
state = .Peripheral;
}
}
},
.Peripheral => {
var cur_periph = &dev.peripherals.items[dev.peripherals.items.len - 1];
if (ascii.eqlIgnoreCase(chunk.tag, "/peripheral")) {
state = .Peripherals;
} else if (ascii.eqlIgnoreCase(chunk.tag, "name")) {
if (chunk.data) |data| {
// periph could be copy, must update periph name in sub-fields
try cur_periph.name.replaceRange(0, cur_periph.name.items.len, data);
for (cur_periph.registers.items) |*reg| {
try reg.periph_containing.replaceRange(0, reg.periph_containing.items.len, data);
for (reg.fields.items) |*field| {
try field.periph.replaceRange(0, field.periph.items.len, data);
}
}
}
} else if (ascii.eqlIgnoreCase(chunk.tag, "description")) {
if (chunk.data) |data| {
try cur_periph.description.insertSlice(0, data);
}
} else if (ascii.eqlIgnoreCase(chunk.tag, "groupName")) {
if (chunk.data) |data| {
try cur_periph.group_name.insertSlice(0, data);
}
} else if (ascii.eqlIgnoreCase(chunk.tag, "baseAddress")) {
if (chunk.data) |data| {
cur_periph.base_address = parseHexLiteral(data);
}
} else if (ascii.eqlIgnoreCase(chunk.tag, "addressBlock")) {
if (cur_periph.address_block) |x| {
// do nothing
} else {
var block = try svd.AddressBlock.init(allocator);
cur_periph.address_block = block;
}
state = .AddressBlock;
} else if (ascii.eqlIgnoreCase(chunk.tag, "interrupt")) {
cur_interrupt = try svd.Interrupt.init(allocator);
state = .Interrupt;
} else if (ascii.eqlIgnoreCase(chunk.tag, "registers")) {
state = .Registers;
}
},
.AddressBlock => {
var cur_periph = &dev.peripherals.items[dev.peripherals.items.len - 1];
var address_block = &cur_periph.address_block.?;
if (ascii.eqlIgnoreCase(chunk.tag, "/addressBlock")) {
state = .Peripheral;
} else if (ascii.eqlIgnoreCase(chunk.tag, "offset")) {
if (chunk.data) |data| {
address_block.offset = parseHexLiteral(data);
}
} else if (ascii.eqlIgnoreCase(chunk.tag, "size")) {
if (chunk.data) |data| {
address_block.size = parseHexLiteral(data);
}
} else if (ascii.eqlIgnoreCase(chunk.tag, "usage")) {
if (chunk.data) |data| {
try address_block.usage.insertSlice(0, data);
}
}
},
.Interrupt => {
if (ascii.eqlIgnoreCase(chunk.tag, "/interrupt")) {
if (cur_interrupt.value) |value| {
// If we find a duplicate interrupt, deinit the old one
if (try dev.interrupts.fetchPut(value, cur_interrupt)) |old_entry| {
var old_interrupt = old_entry.value;
var old_name = old_interrupt.name.items;
var cur_name = cur_interrupt.name.items;
if (!mem.eql(u8, old_name, cur_name)) {
warn(
\\ Found duplicate interrupt values with different names: {s} and {s}
\\ The latter will be discarded.
\\
, .{
cur_name,
old_name,
});
}
old_interrupt.deinit();
}
}
state = .Peripheral;
} else if (ascii.eqlIgnoreCase(chunk.tag, "name")) {
if (chunk.data) |data| {
try cur_interrupt.name.insertSlice(0, data);
}
} else if (ascii.eqlIgnoreCase(chunk.tag, "description")) {
if (chunk.data) |data| {
try cur_interrupt.description.insertSlice(0, data);
}
} else if (ascii.eqlIgnoreCase(chunk.tag, "value")) {
if (chunk.data) |data| {
cur_interrupt.value = fmt.parseInt(u32, data, 10) catch null;
}
}
},
.Registers => {
var cur_periph = &dev.peripherals.items[dev.peripherals.items.len - 1];
if (ascii.eqlIgnoreCase(chunk.tag, "/registers")) {
state = .Peripheral;
} else if (ascii.eqlIgnoreCase(chunk.tag, "register")) {
const reset_value = dev.reg_default_reset_value orelse 0;
const size = dev.reg_default_size orelse 32;
var register = try svd.Register.init(allocator, cur_periph.name.items, reset_value, size);
try cur_periph.registers.append(register);
state = .Register;
}
},
.Register => {
var cur_periph = &dev.peripherals.items[dev.peripherals.items.len - 1];
var cur_reg = &cur_periph.registers.items[cur_periph.registers.items.len - 1];
if (ascii.eqlIgnoreCase(chunk.tag, "/register")) {
state = .Registers;
} else if (ascii.eqlIgnoreCase(chunk.tag, "name")) {
if (chunk.data) |data| {
try cur_reg.name.insertSlice(0, data);
}
} else if (ascii.eqlIgnoreCase(chunk.tag, "displayName")) {
if (chunk.data) |data| {
try cur_reg.display_name.insertSlice(0, data);
}
} else if (ascii.eqlIgnoreCase(chunk.tag, "description")) {
if (chunk.data) |data| {
try cur_reg.description.insertSlice(0, data);
}
} else if (ascii.eqlIgnoreCase(chunk.tag, "addressOffset")) {
if (chunk.data) |data| {
cur_reg.address_offset = parseHexLiteral(data);
}
} else if (ascii.eqlIgnoreCase(chunk.tag, "size")) {
if (chunk.data) |data| {
cur_reg.size = parseHexLiteral(data) orelse cur_reg.size;
}
} else if (ascii.eqlIgnoreCase(chunk.tag, "access")) {
if (chunk.data) |data| {
cur_reg.access = parseAccessValue(data) orelse cur_reg.access;
}
} else if (ascii.eqlIgnoreCase(chunk.tag, "resetValue")) {
if (chunk.data) |data| {
cur_reg.reset_value = parseHexLiteral(data) orelse cur_reg.reset_value; // TODO: test orelse break
}
} else if (ascii.eqlIgnoreCase(chunk.tag, "fields")) {
state = .Fields;
}
},
.Fields => {
var cur_periph = &dev.peripherals.items[dev.peripherals.items.len - 1];
var cur_reg = &cur_periph.registers.items[cur_periph.registers.items.len - 1];
if (ascii.eqlIgnoreCase(chunk.tag, "/fields")) {
state = .Register;
} else if (ascii.eqlIgnoreCase(chunk.tag, "field")) {
var field = try svd.Field.init(allocator, cur_periph.name.items, cur_reg.name.items, cur_reg.reset_value);
try cur_reg.fields.append(field);
state = .Field;
}
},
.Field => {
var cur_periph = &dev.peripherals.items[dev.peripherals.items.len - 1];
var cur_reg = &cur_periph.registers.items[cur_periph.registers.items.len - 1];
var cur_field = &cur_reg.fields.items[cur_reg.fields.items.len - 1];
if (ascii.eqlIgnoreCase(chunk.tag, "/field")) {
state = .Fields;
} else if (ascii.eqlIgnoreCase(chunk.tag, "name")) {
if (chunk.data) |data| {
try cur_field.name.insertSlice(0, data);
}
} else if (ascii.eqlIgnoreCase(chunk.tag, "description")) {
if (chunk.data) |data| {
try cur_field.description.insertSlice(0, data);
}
} else if (ascii.eqlIgnoreCase(chunk.tag, "bitOffset")) {
if (chunk.data) |data| {
cur_field.bit_offset = fmt.parseInt(u32, data, 10) catch null;
}
} else if (ascii.eqlIgnoreCase(chunk.tag, "bitWidth")) {
if (chunk.data) |data| {
cur_field.bit_width = fmt.parseInt(u32, data, 10) catch null;
}
} else if (ascii.eqlIgnoreCase(chunk.tag, "access")) {
if (chunk.data) |data| {
cur_field.access = parseAccessValue(data) orelse cur_field.access;
}
}
},
.Finished => {
// wait for EOF
},
}
}
if (state == .Finished) {
try std.io.getStdOut().writer().print("{s}\n", .{register_def});
try std.io.getStdOut().writer().print("{}\n", .{dev});
} else {
return error.InvalidXML;
}
}
const SvdParseState = enum {
Device,
Cpu,
Peripherals,
Peripheral,
AddressBlock,
Interrupt,
Registers,
Register,
Fields,
Field,
Finished,
};
const XmlChunk = struct {
tag: []const u8,
data: ?[]const u8,
derivedFrom: ?[]const u8,
};
fn getChunk(line: []const u8) ?XmlChunk {
var chunk = XmlChunk{
.tag = undefined,
.data = null,
.derivedFrom = null,
};
var trimmed = mem.trim(u8, line, " \n");
var toker = mem.tokenize(trimmed, "<>"); //" =\n<>\"");
if (toker.next()) |maybe_tag| {
var tag_toker = mem.tokenize(maybe_tag, " =\"");
chunk.tag = tag_toker.next() orelse return null;
if (tag_toker.next()) |maybe_tag_property| {
if (ascii.eqlIgnoreCase(maybe_tag_property, "derivedFrom")) {
chunk.derivedFrom = tag_toker.next();
}
}
} else {
return null;
}
if (toker.next()) |chunk_data| {
chunk.data = chunk_data;
}
return chunk;
}
test "getChunk" {
const valid_xml = " <name>STM32F7x7</name> \n";
const expected_chunk = XmlChunk{ .tag = "name", .data = "STM32F7x7", .derivedFrom = null };
const chunk = getChunk(valid_xml).?;
std.testing.expectEqualSlices(u8, chunk.tag, expected_chunk.tag);
std.testing.expectEqualSlices(u8, chunk.data.?, expected_chunk.data.?);
const no_data_xml = " <name> \n";
const expected_no_data_chunk = XmlChunk{ .tag = "name", .data = null, .derivedFrom = null };
const no_data_chunk = getChunk(no_data_xml).?;
std.testing.expectEqualSlices(u8, no_data_chunk.tag, expected_no_data_chunk.tag);
std.testing.expectEqual(no_data_chunk.data, expected_no_data_chunk.data);
const comments_xml = "<description>Auxiliary Cache Control register</description>";
const expected_comments_chunk = XmlChunk{ .tag = "description", .data = "Auxiliary Cache Control register", .derivedFrom = null };
const comments_chunk = getChunk(comments_xml).?;
std.testing.expectEqualSlices(u8, comments_chunk.tag, expected_comments_chunk.tag);
std.testing.expectEqualSlices(u8, comments_chunk.data.?, expected_comments_chunk.data.?);
const derived = " <peripheral derivedFrom=\"TIM10\">";
const expected_derived_chunk = XmlChunk{ .tag = "peripheral", .data = null, .derivedFrom = "TIM10" };
const derived_chunk = getChunk(derived).?;
std.testing.expectEqualSlices(u8, derived_chunk.tag, expected_derived_chunk.tag);
std.testing.expectEqualSlices(u8, derived_chunk.derivedFrom.?, expected_derived_chunk.derivedFrom.?);
std.testing.expectEqual(derived_chunk.data, expected_derived_chunk.data);
}
fn textToBool(data: []const u8) ?bool {
if (ascii.eqlIgnoreCase(data, "true")) {
return true;
} else if (ascii.eqlIgnoreCase(data, "false")) {
return false;
} else {
return null;
}
}
fn parseHexLiteral(data: []const u8) ?u32 {
if (data.len <= 2) return null;
return fmt.parseInt(u32, data[2..], 16) catch null;
}
fn parseAccessValue(data: []const u8) ?svd.Access {
if (ascii.eqlIgnoreCase(data, "read-write")) {
return .ReadWrite;
} else if (ascii.eqlIgnoreCase(data, "read-only")) {
return .ReadOnly;
} else if (ascii.eqlIgnoreCase(data, "write-only")) {
return .WriteOnly;
}
return null;
} | src/main.zig |
const builtin = @import("builtin");
const fmath = @import("index.zig");
pub fn floor(x: var) -> @typeOf(x) {
const T = @typeOf(x);
switch (T) {
f32 => @inlineCall(floor32, x),
f64 => @inlineCall(floor64, x),
else => @compileError("floor not implemented for " ++ @typeName(T)),
}
}
fn floor32(x: f32) -> f32 {
var u = @bitCast(u32, x);
const e = i32((u >> 23) & 0xFF) - 0x7F;
var m: u32 = undefined;
if (e >= 23) {
return x;
}
if (e >= 0) {
m = 0x007FFFFF >> u32(e);
if (u & m == 0) {
return x;
}
fmath.forceEval(x + 0x1.0p120);
if (u >> 31 != 0) {
u += m;
}
@bitCast(f32, u & ~m)
} else {
fmath.forceEval(x + 0x1.0p120);
if (u >> 31 == 0) {
return 0.0; // Compiler requires return
} else {
-1.0
}
}
}
fn floor64(x: f64) -> f64 {
const u = @bitCast(u64, x);
const e = (u >> 52) & 0x7FF;
var y: f64 = undefined;
if (e >= 0x3FF+52 or x == 0) {
return x;
}
if (u >> 63 != 0) {
@setFloatMode(this, builtin.FloatMode.Strict);
y = x - fmath.f64_toint + fmath.f64_toint - x;
} else {
@setFloatMode(this, builtin.FloatMode.Strict);
y = x + fmath.f64_toint - fmath.f64_toint - x;
}
if (e <= 0x3FF-1) {
fmath.forceEval(y);
if (u >> 63 != 0) {
return -1.0; // Compiler requires return.
} else {
0.0
}
} else if (y > 0) {
x + y - 1
} else {
x + y
}
}
test "floor" {
fmath.assert(floor(f32(1.3)) == floor32(1.3));
fmath.assert(floor(f64(1.3)) == floor64(1.3));
}
test "floor32" {
fmath.assert(floor32(1.3) == 1.0);
fmath.assert(floor32(-1.3) == -2.0);
fmath.assert(floor32(0.2) == 0.0);
}
test "floor64" {
fmath.assert(floor64(1.3) == 1.0);
fmath.assert(floor64(-1.3) == -2.0);
fmath.assert(floor64(0.2) == 0.0);
} | src/floor.zig |
const fmath = @import("index.zig");
pub fn atan2(comptime T: type, x: T, y: T) -> T {
switch (T) {
f32 => @inlineCall(atan2f, x, y),
f64 => @inlineCall(atan2d, x, y),
else => @compileError("atan2 not implemented for " ++ @typeName(T)),
}
}
fn atan2f(y: f32, x: f32) -> f32 {
const pi: f32 = 3.1415927410e+00;
const pi_lo: f32 = -8.7422776573e-08;
if (fmath.isNan(x) or fmath.isNan(y)) {
return x + y;
}
var ix = @bitCast(u32, x);
var iy = @bitCast(u32, y);
// x = 1.0
if (ix == 0x3F800000) {
return fmath.atan(y);
}
// 2 * sign(x) + sign(y)
const m = ((iy >> 31) & 1) | ((ix >> 30) & 2);
ix &= 0x7FFFFFFF;
iy &= 0x7FFFFFFF;
if (iy == 0) {
switch (m) {
0, 1 => return y, // atan(+-0, +...)
2 => return pi, // atan(+0, -...)
3 => return -pi, // atan(-0, -...)
else => unreachable,
}
}
if (ix == 0) {
if (m & 1 != 0) {
return -pi / 2;
} else {
return pi / 2;
}
}
if (ix == 0x7F800000) {
if (iy == 0x7F800000) {
switch (m) {
0 => return pi / 4, // atan(+inf, +inf)
1 => return -pi / 4, // atan(-inf, +inf)
2 => return 3*pi / 4, // atan(+inf, -inf)
3 => return -3*pi / 4, // atan(-inf, -inf)
else => unreachable,
}
} else {
switch (m) {
0 => return 0.0, // atan(+..., +inf)
1 => return -0.0, // atan(-..., +inf)
2 => return pi, // atan(+..., -inf)
3 => return -pi, // atan(-...f, -inf)
else => unreachable,
}
}
}
// |y / x| > 0x1p26
if (ix + (26 << 23) < iy or iy == 0x7F800000) {
if (m & 1 != 0) {
return -pi / 2;
} else {
return pi / 2;
}
}
// z = atan(|y / x|) with correct underflow
var z = {
if ((m & 2) != 0 and iy + (26 << 23) < ix) {
0.0
} else {
fmath.atan(fmath.fabs(y / x))
}
};
switch (m) {
0 => return z, // atan(+, +)
1 => return -z, // atan(-, +)
2 => return pi - (z - pi_lo), // atan(+, -)
3 => return (z - pi_lo) - pi, // atan(-, -)
else => unreachable,
}
}
fn atan2d(y: f64, x: f64) -> f64 {
const pi: f64 = 3.1415926535897931160E+00;
const pi_lo: f64 = 1.2246467991473531772E-16;
if (fmath.isNan(x) or fmath.isNan(y)) {
return x + y;
}
var ux = @bitCast(u64, x);
var ix = u32(ux >> 32);
var lx = u32(ux & 0xFFFFFFFF);
var uy = @bitCast(u64, y);
var iy = u32(uy >> 32);
var ly = u32(uy & 0xFFFFFFFF);
// x = 1.0
if ((ix -% 0x3FF00000) | lx == 0) {
return fmath.atan(y);
}
// 2 * sign(x) + sign(y)
const m = ((iy >> 31) & 1) | ((ix >> 30) & 2);
ix &= 0x7FFFFFFF;
iy &= 0x7FFFFFFF;
if (iy | ly == 0) {
switch (m) {
0, 1 => return y, // atan(+-0, +...)
2 => return pi, // atan(+0, -...)
3 => return -pi, // atan(-0, -...)
else => unreachable,
}
}
if (ix | lx == 0) {
if (m & 1 != 0) {
return -pi / 2;
} else {
return pi / 2;
}
}
if (ix == 0x7FF00000) {
if (iy == 0x7FF00000) {
switch (m) {
0 => return pi / 4, // atan(+inf, +inf)
1 => return -pi / 4, // atan(-inf, +inf)
2 => return 3*pi / 4, // atan(+inf, -inf)
3 => return -3*pi / 4, // atan(-inf, -inf)
else => unreachable,
}
} else {
switch (m) {
0 => return 0.0, // atan(+..., +inf)
1 => return -0.0, // atan(-..., +inf)
2 => return pi, // atan(+..., -inf)
3 => return -pi, // atan(-...f, -inf)
else => unreachable,
}
}
}
// |y / x| > 0x1p64
if (ix +% (64 << 20) < iy or iy == 0x7FF00000) {
if (m & 1 != 0) {
return -pi / 2;
} else {
return pi / 2;
}
}
// z = atan(|y / x|) with correct underflow
var z = {
if ((m & 2) != 0 and iy +% (64 << 20) < ix) {
0.0
} else {
fmath.atan(fmath.fabs(y / x))
}
};
switch (m) {
0 => return z, // atan(+, +)
1 => return -z, // atan(-, +)
2 => return pi - (z - pi_lo), // atan(+, -)
3 => return (z - pi_lo) - pi, // atan(-, -)
else => unreachable,
}
}
test "atan2" {
fmath.assert(atan2(f32, 0.2, 0.21) == atan2f(0.2, 0.21));
fmath.assert(atan2(f64, 0.2, 0.21) == atan2d(0.2, 0.21));
}
test "atan2f" {
const epsilon = 0.000001;
fmath.assert(fmath.approxEq(f32, atan2f(0.0, 0.0), 0.0, epsilon));
fmath.assert(fmath.approxEq(f32, atan2f(0.2, 0.2), 0.785398, epsilon));
fmath.assert(fmath.approxEq(f32, atan2f(-0.2, 0.2), -0.785398, epsilon));
fmath.assert(fmath.approxEq(f32, atan2f(0.2, -0.2), 2.356194, epsilon));
fmath.assert(fmath.approxEq(f32, atan2f(-0.2, -0.2), -2.356194, epsilon));
fmath.assert(fmath.approxEq(f32, atan2f(0.34, -0.4), 2.437099, epsilon));
fmath.assert(fmath.approxEq(f32, atan2f(0.34, 1.243), 0.267001, epsilon));
}
test "atan2d" {
const epsilon = 0.000001;
fmath.assert(fmath.approxEq(f64, atan2d(0.0, 0.0), 0.0, epsilon));
fmath.assert(fmath.approxEq(f64, atan2d(0.2, 0.2), 0.785398, epsilon));
fmath.assert(fmath.approxEq(f64, atan2d(-0.2, 0.2), -0.785398, epsilon));
fmath.assert(fmath.approxEq(f64, atan2d(0.2, -0.2), 2.356194, epsilon));
fmath.assert(fmath.approxEq(f64, atan2d(-0.2, -0.2), -2.356194, epsilon));
fmath.assert(fmath.approxEq(f64, atan2d(0.34, -0.4), 2.437099, epsilon));
fmath.assert(fmath.approxEq(f64, atan2d(0.34, 1.243), 0.267001, epsilon));
} | src/atan2.zig |
const std = @import("std");
const cast = std.meta.cast;
const mode = std.builtin.mode; // Checked arithmetic is disabled in non-debug modes to avoid side channels
// The type MontgomeryDomainFieldElement is a field element in the Montgomery domain.
// Bounds: [[0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff]]
pub const MontgomeryDomainFieldElement = [7]u32;
// The type NonMontgomeryDomainFieldElement is a field element NOT in the Montgomery domain.
// Bounds: [[0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff]]
pub const NonMontgomeryDomainFieldElement = [7]u32;
/// The function addcarryxU32 is an addition with carry.
///
/// Postconditions:
/// out1 = (arg1 + arg2 + arg3) mod 2^32
/// out2 = ⌊(arg1 + arg2 + arg3) / 2^32⌋
///
/// Input Bounds:
/// arg1: [0x0 ~> 0x1]
/// arg2: [0x0 ~> 0xffffffff]
/// arg3: [0x0 ~> 0xffffffff]
/// Output Bounds:
/// out1: [0x0 ~> 0xffffffff]
/// out2: [0x0 ~> 0x1]
inline fn addcarryxU32(out1: *u32, out2: *u1, arg1: u1, arg2: u32, arg3: u32) void {
@setRuntimeSafety(mode == .Debug);
const x1 = ((cast(u64, arg1) + cast(u64, arg2)) + cast(u64, arg3));
const x2 = cast(u32, (x1 & cast(u64, 0xffffffff)));
const x3 = cast(u1, (x1 >> 32));
out1.* = x2;
out2.* = x3;
}
/// The function subborrowxU32 is a subtraction with borrow.
///
/// Postconditions:
/// out1 = (-arg1 + arg2 + -arg3) mod 2^32
/// out2 = -⌊(-arg1 + arg2 + -arg3) / 2^32⌋
///
/// Input Bounds:
/// arg1: [0x0 ~> 0x1]
/// arg2: [0x0 ~> 0xffffffff]
/// arg3: [0x0 ~> 0xffffffff]
/// Output Bounds:
/// out1: [0x0 ~> 0xffffffff]
/// out2: [0x0 ~> 0x1]
inline fn subborrowxU32(out1: *u32, out2: *u1, arg1: u1, arg2: u32, arg3: u32) void {
@setRuntimeSafety(mode == .Debug);
const x1 = ((cast(i64, arg2) - cast(i64, arg1)) - cast(i64, arg3));
const x2 = cast(i1, (x1 >> 32));
const x3 = cast(u32, (x1 & cast(i64, 0xffffffff)));
out1.* = x3;
out2.* = cast(u1, (cast(i2, 0x0) - cast(i2, x2)));
}
/// The function mulxU32 is a multiplication, returning the full double-width result.
///
/// Postconditions:
/// out1 = (arg1 * arg2) mod 2^32
/// out2 = ⌊arg1 * arg2 / 2^32⌋
///
/// Input Bounds:
/// arg1: [0x0 ~> 0xffffffff]
/// arg2: [0x0 ~> 0xffffffff]
/// Output Bounds:
/// out1: [0x0 ~> 0xffffffff]
/// out2: [0x0 ~> 0xffffffff]
inline fn mulxU32(out1: *u32, out2: *u32, arg1: u32, arg2: u32) void {
@setRuntimeSafety(mode == .Debug);
const x1 = (cast(u64, arg1) * cast(u64, arg2));
const x2 = cast(u32, (x1 & cast(u64, 0xffffffff)));
const x3 = cast(u32, (x1 >> 32));
out1.* = x2;
out2.* = x3;
}
/// The function cmovznzU32 is a single-word conditional move.
///
/// Postconditions:
/// out1 = (if arg1 = 0 then arg2 else arg3)
///
/// Input Bounds:
/// arg1: [0x0 ~> 0x1]
/// arg2: [0x0 ~> 0xffffffff]
/// arg3: [0x0 ~> 0xffffffff]
/// Output Bounds:
/// out1: [0x0 ~> 0xffffffff]
inline fn cmovznzU32(out1: *u32, arg1: u1, arg2: u32, arg3: u32) void {
@setRuntimeSafety(mode == .Debug);
const x1 = (~(~arg1));
const x2 = cast(u32, (cast(i64, cast(i1, (cast(i2, 0x0) - cast(i2, x1)))) & cast(i64, 0xffffffff)));
const x3 = ((x2 & arg3) | ((~x2) & arg2));
out1.* = x3;
}
/// The function mul multiplies two field elements in the Montgomery domain.
///
/// Preconditions:
/// 0 ≤ eval arg1 < m
/// 0 ≤ eval arg2 < m
/// Postconditions:
/// eval (from_montgomery out1) mod m = (eval (from_montgomery arg1) * eval (from_montgomery arg2)) mod m
/// 0 ≤ eval out1 < m
///
pub fn mul(out1: *MontgomeryDomainFieldElement, arg1: MontgomeryDomainFieldElement, arg2: MontgomeryDomainFieldElement) void {
@setRuntimeSafety(mode == .Debug);
const x1 = (arg1[1]);
const x2 = (arg1[2]);
const x3 = (arg1[3]);
const x4 = (arg1[4]);
const x5 = (arg1[5]);
const x6 = (arg1[6]);
const x7 = (arg1[0]);
var x8: u32 = undefined;
var x9: u32 = undefined;
mulxU32(&x8, &x9, x7, (arg2[6]));
var x10: u32 = undefined;
var x11: u32 = undefined;
mulxU32(&x10, &x11, x7, (arg2[5]));
var x12: u32 = undefined;
var x13: u32 = undefined;
mulxU32(&x12, &x13, x7, (arg2[4]));
var x14: u32 = undefined;
var x15: u32 = undefined;
mulxU32(&x14, &x15, x7, (arg2[3]));
var x16: u32 = undefined;
var x17: u32 = undefined;
mulxU32(&x16, &x17, x7, (arg2[2]));
var x18: u32 = undefined;
var x19: u32 = undefined;
mulxU32(&x18, &x19, x7, (arg2[1]));
var x20: u32 = undefined;
var x21: u32 = undefined;
mulxU32(&x20, &x21, x7, (arg2[0]));
var x22: u32 = undefined;
var x23: u1 = undefined;
addcarryxU32(&x22, &x23, 0x0, x21, x18);
var x24: u32 = undefined;
var x25: u1 = undefined;
addcarryxU32(&x24, &x25, x23, x19, x16);
var x26: u32 = undefined;
var x27: u1 = undefined;
addcarryxU32(&x26, &x27, x25, x17, x14);
var x28: u32 = undefined;
var x29: u1 = undefined;
addcarryxU32(&x28, &x29, x27, x15, x12);
var x30: u32 = undefined;
var x31: u1 = undefined;
addcarryxU32(&x30, &x31, x29, x13, x10);
var x32: u32 = undefined;
var x33: u1 = undefined;
addcarryxU32(&x32, &x33, x31, x11, x8);
const x34 = (cast(u32, x33) + x9);
var x35: u32 = undefined;
var x36: u32 = undefined;
mulxU32(&x35, &x36, x20, 0xffffffff);
var x37: u32 = undefined;
var x38: u32 = undefined;
mulxU32(&x37, &x38, x35, 0xffffffff);
var x39: u32 = undefined;
var x40: u32 = undefined;
mulxU32(&x39, &x40, x35, 0xffffffff);
var x41: u32 = undefined;
var x42: u32 = undefined;
mulxU32(&x41, &x42, x35, 0xffffffff);
var x43: u32 = undefined;
var x44: u32 = undefined;
mulxU32(&x43, &x44, x35, 0xffffffff);
var x45: u32 = undefined;
var x46: u1 = undefined;
addcarryxU32(&x45, &x46, 0x0, x44, x41);
var x47: u32 = undefined;
var x48: u1 = undefined;
addcarryxU32(&x47, &x48, x46, x42, x39);
var x49: u32 = undefined;
var x50: u1 = undefined;
addcarryxU32(&x49, &x50, x48, x40, x37);
const x51 = (cast(u32, x50) + x38);
var x52: u32 = undefined;
var x53: u1 = undefined;
addcarryxU32(&x52, &x53, 0x0, x20, x35);
var x54: u32 = undefined;
var x55: u1 = undefined;
addcarryxU32(&x54, &x55, x53, x22, cast(u32, 0x0));
var x56: u32 = undefined;
var x57: u1 = undefined;
addcarryxU32(&x56, &x57, x55, x24, cast(u32, 0x0));
var x58: u32 = undefined;
var x59: u1 = undefined;
addcarryxU32(&x58, &x59, x57, x26, x43);
var x60: u32 = undefined;
var x61: u1 = undefined;
addcarryxU32(&x60, &x61, x59, x28, x45);
var x62: u32 = undefined;
var x63: u1 = undefined;
addcarryxU32(&x62, &x63, x61, x30, x47);
var x64: u32 = undefined;
var x65: u1 = undefined;
addcarryxU32(&x64, &x65, x63, x32, x49);
var x66: u32 = undefined;
var x67: u1 = undefined;
addcarryxU32(&x66, &x67, x65, x34, x51);
var x68: u32 = undefined;
var x69: u32 = undefined;
mulxU32(&x68, &x69, x1, (arg2[6]));
var x70: u32 = undefined;
var x71: u32 = undefined;
mulxU32(&x70, &x71, x1, (arg2[5]));
var x72: u32 = undefined;
var x73: u32 = undefined;
mulxU32(&x72, &x73, x1, (arg2[4]));
var x74: u32 = undefined;
var x75: u32 = undefined;
mulxU32(&x74, &x75, x1, (arg2[3]));
var x76: u32 = undefined;
var x77: u32 = undefined;
mulxU32(&x76, &x77, x1, (arg2[2]));
var x78: u32 = undefined;
var x79: u32 = undefined;
mulxU32(&x78, &x79, x1, (arg2[1]));
var x80: u32 = undefined;
var x81: u32 = undefined;
mulxU32(&x80, &x81, x1, (arg2[0]));
var x82: u32 = undefined;
var x83: u1 = undefined;
addcarryxU32(&x82, &x83, 0x0, x81, x78);
var x84: u32 = undefined;
var x85: u1 = undefined;
addcarryxU32(&x84, &x85, x83, x79, x76);
var x86: u32 = undefined;
var x87: u1 = undefined;
addcarryxU32(&x86, &x87, x85, x77, x74);
var x88: u32 = undefined;
var x89: u1 = undefined;
addcarryxU32(&x88, &x89, x87, x75, x72);
var x90: u32 = undefined;
var x91: u1 = undefined;
addcarryxU32(&x90, &x91, x89, x73, x70);
var x92: u32 = undefined;
var x93: u1 = undefined;
addcarryxU32(&x92, &x93, x91, x71, x68);
const x94 = (cast(u32, x93) + x69);
var x95: u32 = undefined;
var x96: u1 = undefined;
addcarryxU32(&x95, &x96, 0x0, x54, x80);
var x97: u32 = undefined;
var x98: u1 = undefined;
addcarryxU32(&x97, &x98, x96, x56, x82);
var x99: u32 = undefined;
var x100: u1 = undefined;
addcarryxU32(&x99, &x100, x98, x58, x84);
var x101: u32 = undefined;
var x102: u1 = undefined;
addcarryxU32(&x101, &x102, x100, x60, x86);
var x103: u32 = undefined;
var x104: u1 = undefined;
addcarryxU32(&x103, &x104, x102, x62, x88);
var x105: u32 = undefined;
var x106: u1 = undefined;
addcarryxU32(&x105, &x106, x104, x64, x90);
var x107: u32 = undefined;
var x108: u1 = undefined;
addcarryxU32(&x107, &x108, x106, x66, x92);
var x109: u32 = undefined;
var x110: u1 = undefined;
addcarryxU32(&x109, &x110, x108, cast(u32, x67), x94);
var x111: u32 = undefined;
var x112: u32 = undefined;
mulxU32(&x111, &x112, x95, 0xffffffff);
var x113: u32 = undefined;
var x114: u32 = undefined;
mulxU32(&x113, &x114, x111, 0xffffffff);
var x115: u32 = undefined;
var x116: u32 = undefined;
mulxU32(&x115, &x116, x111, 0xffffffff);
var x117: u32 = undefined;
var x118: u32 = undefined;
mulxU32(&x117, &x118, x111, 0xffffffff);
var x119: u32 = undefined;
var x120: u32 = undefined;
mulxU32(&x119, &x120, x111, 0xffffffff);
var x121: u32 = undefined;
var x122: u1 = undefined;
addcarryxU32(&x121, &x122, 0x0, x120, x117);
var x123: u32 = undefined;
var x124: u1 = undefined;
addcarryxU32(&x123, &x124, x122, x118, x115);
var x125: u32 = undefined;
var x126: u1 = undefined;
addcarryxU32(&x125, &x126, x124, x116, x113);
const x127 = (cast(u32, x126) + x114);
var x128: u32 = undefined;
var x129: u1 = undefined;
addcarryxU32(&x128, &x129, 0x0, x95, x111);
var x130: u32 = undefined;
var x131: u1 = undefined;
addcarryxU32(&x130, &x131, x129, x97, cast(u32, 0x0));
var x132: u32 = undefined;
var x133: u1 = undefined;
addcarryxU32(&x132, &x133, x131, x99, cast(u32, 0x0));
var x134: u32 = undefined;
var x135: u1 = undefined;
addcarryxU32(&x134, &x135, x133, x101, x119);
var x136: u32 = undefined;
var x137: u1 = undefined;
addcarryxU32(&x136, &x137, x135, x103, x121);
var x138: u32 = undefined;
var x139: u1 = undefined;
addcarryxU32(&x138, &x139, x137, x105, x123);
var x140: u32 = undefined;
var x141: u1 = undefined;
addcarryxU32(&x140, &x141, x139, x107, x125);
var x142: u32 = undefined;
var x143: u1 = undefined;
addcarryxU32(&x142, &x143, x141, x109, x127);
const x144 = (cast(u32, x143) + cast(u32, x110));
var x145: u32 = undefined;
var x146: u32 = undefined;
mulxU32(&x145, &x146, x2, (arg2[6]));
var x147: u32 = undefined;
var x148: u32 = undefined;
mulxU32(&x147, &x148, x2, (arg2[5]));
var x149: u32 = undefined;
var x150: u32 = undefined;
mulxU32(&x149, &x150, x2, (arg2[4]));
var x151: u32 = undefined;
var x152: u32 = undefined;
mulxU32(&x151, &x152, x2, (arg2[3]));
var x153: u32 = undefined;
var x154: u32 = undefined;
mulxU32(&x153, &x154, x2, (arg2[2]));
var x155: u32 = undefined;
var x156: u32 = undefined;
mulxU32(&x155, &x156, x2, (arg2[1]));
var x157: u32 = undefined;
var x158: u32 = undefined;
mulxU32(&x157, &x158, x2, (arg2[0]));
var x159: u32 = undefined;
var x160: u1 = undefined;
addcarryxU32(&x159, &x160, 0x0, x158, x155);
var x161: u32 = undefined;
var x162: u1 = undefined;
addcarryxU32(&x161, &x162, x160, x156, x153);
var x163: u32 = undefined;
var x164: u1 = undefined;
addcarryxU32(&x163, &x164, x162, x154, x151);
var x165: u32 = undefined;
var x166: u1 = undefined;
addcarryxU32(&x165, &x166, x164, x152, x149);
var x167: u32 = undefined;
var x168: u1 = undefined;
addcarryxU32(&x167, &x168, x166, x150, x147);
var x169: u32 = undefined;
var x170: u1 = undefined;
addcarryxU32(&x169, &x170, x168, x148, x145);
const x171 = (cast(u32, x170) + x146);
var x172: u32 = undefined;
var x173: u1 = undefined;
addcarryxU32(&x172, &x173, 0x0, x130, x157);
var x174: u32 = undefined;
var x175: u1 = undefined;
addcarryxU32(&x174, &x175, x173, x132, x159);
var x176: u32 = undefined;
var x177: u1 = undefined;
addcarryxU32(&x176, &x177, x175, x134, x161);
var x178: u32 = undefined;
var x179: u1 = undefined;
addcarryxU32(&x178, &x179, x177, x136, x163);
var x180: u32 = undefined;
var x181: u1 = undefined;
addcarryxU32(&x180, &x181, x179, x138, x165);
var x182: u32 = undefined;
var x183: u1 = undefined;
addcarryxU32(&x182, &x183, x181, x140, x167);
var x184: u32 = undefined;
var x185: u1 = undefined;
addcarryxU32(&x184, &x185, x183, x142, x169);
var x186: u32 = undefined;
var x187: u1 = undefined;
addcarryxU32(&x186, &x187, x185, x144, x171);
var x188: u32 = undefined;
var x189: u32 = undefined;
mulxU32(&x188, &x189, x172, 0xffffffff);
var x190: u32 = undefined;
var x191: u32 = undefined;
mulxU32(&x190, &x191, x188, 0xffffffff);
var x192: u32 = undefined;
var x193: u32 = undefined;
mulxU32(&x192, &x193, x188, 0xffffffff);
var x194: u32 = undefined;
var x195: u32 = undefined;
mulxU32(&x194, &x195, x188, 0xffffffff);
var x196: u32 = undefined;
var x197: u32 = undefined;
mulxU32(&x196, &x197, x188, 0xffffffff);
var x198: u32 = undefined;
var x199: u1 = undefined;
addcarryxU32(&x198, &x199, 0x0, x197, x194);
var x200: u32 = undefined;
var x201: u1 = undefined;
addcarryxU32(&x200, &x201, x199, x195, x192);
var x202: u32 = undefined;
var x203: u1 = undefined;
addcarryxU32(&x202, &x203, x201, x193, x190);
const x204 = (cast(u32, x203) + x191);
var x205: u32 = undefined;
var x206: u1 = undefined;
addcarryxU32(&x205, &x206, 0x0, x172, x188);
var x207: u32 = undefined;
var x208: u1 = undefined;
addcarryxU32(&x207, &x208, x206, x174, cast(u32, 0x0));
var x209: u32 = undefined;
var x210: u1 = undefined;
addcarryxU32(&x209, &x210, x208, x176, cast(u32, 0x0));
var x211: u32 = undefined;
var x212: u1 = undefined;
addcarryxU32(&x211, &x212, x210, x178, x196);
var x213: u32 = undefined;
var x214: u1 = undefined;
addcarryxU32(&x213, &x214, x212, x180, x198);
var x215: u32 = undefined;
var x216: u1 = undefined;
addcarryxU32(&x215, &x216, x214, x182, x200);
var x217: u32 = undefined;
var x218: u1 = undefined;
addcarryxU32(&x217, &x218, x216, x184, x202);
var x219: u32 = undefined;
var x220: u1 = undefined;
addcarryxU32(&x219, &x220, x218, x186, x204);
const x221 = (cast(u32, x220) + cast(u32, x187));
var x222: u32 = undefined;
var x223: u32 = undefined;
mulxU32(&x222, &x223, x3, (arg2[6]));
var x224: u32 = undefined;
var x225: u32 = undefined;
mulxU32(&x224, &x225, x3, (arg2[5]));
var x226: u32 = undefined;
var x227: u32 = undefined;
mulxU32(&x226, &x227, x3, (arg2[4]));
var x228: u32 = undefined;
var x229: u32 = undefined;
mulxU32(&x228, &x229, x3, (arg2[3]));
var x230: u32 = undefined;
var x231: u32 = undefined;
mulxU32(&x230, &x231, x3, (arg2[2]));
var x232: u32 = undefined;
var x233: u32 = undefined;
mulxU32(&x232, &x233, x3, (arg2[1]));
var x234: u32 = undefined;
var x235: u32 = undefined;
mulxU32(&x234, &x235, x3, (arg2[0]));
var x236: u32 = undefined;
var x237: u1 = undefined;
addcarryxU32(&x236, &x237, 0x0, x235, x232);
var x238: u32 = undefined;
var x239: u1 = undefined;
addcarryxU32(&x238, &x239, x237, x233, x230);
var x240: u32 = undefined;
var x241: u1 = undefined;
addcarryxU32(&x240, &x241, x239, x231, x228);
var x242: u32 = undefined;
var x243: u1 = undefined;
addcarryxU32(&x242, &x243, x241, x229, x226);
var x244: u32 = undefined;
var x245: u1 = undefined;
addcarryxU32(&x244, &x245, x243, x227, x224);
var x246: u32 = undefined;
var x247: u1 = undefined;
addcarryxU32(&x246, &x247, x245, x225, x222);
const x248 = (cast(u32, x247) + x223);
var x249: u32 = undefined;
var x250: u1 = undefined;
addcarryxU32(&x249, &x250, 0x0, x207, x234);
var x251: u32 = undefined;
var x252: u1 = undefined;
addcarryxU32(&x251, &x252, x250, x209, x236);
var x253: u32 = undefined;
var x254: u1 = undefined;
addcarryxU32(&x253, &x254, x252, x211, x238);
var x255: u32 = undefined;
var x256: u1 = undefined;
addcarryxU32(&x255, &x256, x254, x213, x240);
var x257: u32 = undefined;
var x258: u1 = undefined;
addcarryxU32(&x257, &x258, x256, x215, x242);
var x259: u32 = undefined;
var x260: u1 = undefined;
addcarryxU32(&x259, &x260, x258, x217, x244);
var x261: u32 = undefined;
var x262: u1 = undefined;
addcarryxU32(&x261, &x262, x260, x219, x246);
var x263: u32 = undefined;
var x264: u1 = undefined;
addcarryxU32(&x263, &x264, x262, x221, x248);
var x265: u32 = undefined;
var x266: u32 = undefined;
mulxU32(&x265, &x266, x249, 0xffffffff);
var x267: u32 = undefined;
var x268: u32 = undefined;
mulxU32(&x267, &x268, x265, 0xffffffff);
var x269: u32 = undefined;
var x270: u32 = undefined;
mulxU32(&x269, &x270, x265, 0xffffffff);
var x271: u32 = undefined;
var x272: u32 = undefined;
mulxU32(&x271, &x272, x265, 0xffffffff);
var x273: u32 = undefined;
var x274: u32 = undefined;
mulxU32(&x273, &x274, x265, 0xffffffff);
var x275: u32 = undefined;
var x276: u1 = undefined;
addcarryxU32(&x275, &x276, 0x0, x274, x271);
var x277: u32 = undefined;
var x278: u1 = undefined;
addcarryxU32(&x277, &x278, x276, x272, x269);
var x279: u32 = undefined;
var x280: u1 = undefined;
addcarryxU32(&x279, &x280, x278, x270, x267);
const x281 = (cast(u32, x280) + x268);
var x282: u32 = undefined;
var x283: u1 = undefined;
addcarryxU32(&x282, &x283, 0x0, x249, x265);
var x284: u32 = undefined;
var x285: u1 = undefined;
addcarryxU32(&x284, &x285, x283, x251, cast(u32, 0x0));
var x286: u32 = undefined;
var x287: u1 = undefined;
addcarryxU32(&x286, &x287, x285, x253, cast(u32, 0x0));
var x288: u32 = undefined;
var x289: u1 = undefined;
addcarryxU32(&x288, &x289, x287, x255, x273);
var x290: u32 = undefined;
var x291: u1 = undefined;
addcarryxU32(&x290, &x291, x289, x257, x275);
var x292: u32 = undefined;
var x293: u1 = undefined;
addcarryxU32(&x292, &x293, x291, x259, x277);
var x294: u32 = undefined;
var x295: u1 = undefined;
addcarryxU32(&x294, &x295, x293, x261, x279);
var x296: u32 = undefined;
var x297: u1 = undefined;
addcarryxU32(&x296, &x297, x295, x263, x281);
const x298 = (cast(u32, x297) + cast(u32, x264));
var x299: u32 = undefined;
var x300: u32 = undefined;
mulxU32(&x299, &x300, x4, (arg2[6]));
var x301: u32 = undefined;
var x302: u32 = undefined;
mulxU32(&x301, &x302, x4, (arg2[5]));
var x303: u32 = undefined;
var x304: u32 = undefined;
mulxU32(&x303, &x304, x4, (arg2[4]));
var x305: u32 = undefined;
var x306: u32 = undefined;
mulxU32(&x305, &x306, x4, (arg2[3]));
var x307: u32 = undefined;
var x308: u32 = undefined;
mulxU32(&x307, &x308, x4, (arg2[2]));
var x309: u32 = undefined;
var x310: u32 = undefined;
mulxU32(&x309, &x310, x4, (arg2[1]));
var x311: u32 = undefined;
var x312: u32 = undefined;
mulxU32(&x311, &x312, x4, (arg2[0]));
var x313: u32 = undefined;
var x314: u1 = undefined;
addcarryxU32(&x313, &x314, 0x0, x312, x309);
var x315: u32 = undefined;
var x316: u1 = undefined;
addcarryxU32(&x315, &x316, x314, x310, x307);
var x317: u32 = undefined;
var x318: u1 = undefined;
addcarryxU32(&x317, &x318, x316, x308, x305);
var x319: u32 = undefined;
var x320: u1 = undefined;
addcarryxU32(&x319, &x320, x318, x306, x303);
var x321: u32 = undefined;
var x322: u1 = undefined;
addcarryxU32(&x321, &x322, x320, x304, x301);
var x323: u32 = undefined;
var x324: u1 = undefined;
addcarryxU32(&x323, &x324, x322, x302, x299);
const x325 = (cast(u32, x324) + x300);
var x326: u32 = undefined;
var x327: u1 = undefined;
addcarryxU32(&x326, &x327, 0x0, x284, x311);
var x328: u32 = undefined;
var x329: u1 = undefined;
addcarryxU32(&x328, &x329, x327, x286, x313);
var x330: u32 = undefined;
var x331: u1 = undefined;
addcarryxU32(&x330, &x331, x329, x288, x315);
var x332: u32 = undefined;
var x333: u1 = undefined;
addcarryxU32(&x332, &x333, x331, x290, x317);
var x334: u32 = undefined;
var x335: u1 = undefined;
addcarryxU32(&x334, &x335, x333, x292, x319);
var x336: u32 = undefined;
var x337: u1 = undefined;
addcarryxU32(&x336, &x337, x335, x294, x321);
var x338: u32 = undefined;
var x339: u1 = undefined;
addcarryxU32(&x338, &x339, x337, x296, x323);
var x340: u32 = undefined;
var x341: u1 = undefined;
addcarryxU32(&x340, &x341, x339, x298, x325);
var x342: u32 = undefined;
var x343: u32 = undefined;
mulxU32(&x342, &x343, x326, 0xffffffff);
var x344: u32 = undefined;
var x345: u32 = undefined;
mulxU32(&x344, &x345, x342, 0xffffffff);
var x346: u32 = undefined;
var x347: u32 = undefined;
mulxU32(&x346, &x347, x342, 0xffffffff);
var x348: u32 = undefined;
var x349: u32 = undefined;
mulxU32(&x348, &x349, x342, 0xffffffff);
var x350: u32 = undefined;
var x351: u32 = undefined;
mulxU32(&x350, &x351, x342, 0xffffffff);
var x352: u32 = undefined;
var x353: u1 = undefined;
addcarryxU32(&x352, &x353, 0x0, x351, x348);
var x354: u32 = undefined;
var x355: u1 = undefined;
addcarryxU32(&x354, &x355, x353, x349, x346);
var x356: u32 = undefined;
var x357: u1 = undefined;
addcarryxU32(&x356, &x357, x355, x347, x344);
const x358 = (cast(u32, x357) + x345);
var x359: u32 = undefined;
var x360: u1 = undefined;
addcarryxU32(&x359, &x360, 0x0, x326, x342);
var x361: u32 = undefined;
var x362: u1 = undefined;
addcarryxU32(&x361, &x362, x360, x328, cast(u32, 0x0));
var x363: u32 = undefined;
var x364: u1 = undefined;
addcarryxU32(&x363, &x364, x362, x330, cast(u32, 0x0));
var x365: u32 = undefined;
var x366: u1 = undefined;
addcarryxU32(&x365, &x366, x364, x332, x350);
var x367: u32 = undefined;
var x368: u1 = undefined;
addcarryxU32(&x367, &x368, x366, x334, x352);
var x369: u32 = undefined;
var x370: u1 = undefined;
addcarryxU32(&x369, &x370, x368, x336, x354);
var x371: u32 = undefined;
var x372: u1 = undefined;
addcarryxU32(&x371, &x372, x370, x338, x356);
var x373: u32 = undefined;
var x374: u1 = undefined;
addcarryxU32(&x373, &x374, x372, x340, x358);
const x375 = (cast(u32, x374) + cast(u32, x341));
var x376: u32 = undefined;
var x377: u32 = undefined;
mulxU32(&x376, &x377, x5, (arg2[6]));
var x378: u32 = undefined;
var x379: u32 = undefined;
mulxU32(&x378, &x379, x5, (arg2[5]));
var x380: u32 = undefined;
var x381: u32 = undefined;
mulxU32(&x380, &x381, x5, (arg2[4]));
var x382: u32 = undefined;
var x383: u32 = undefined;
mulxU32(&x382, &x383, x5, (arg2[3]));
var x384: u32 = undefined;
var x385: u32 = undefined;
mulxU32(&x384, &x385, x5, (arg2[2]));
var x386: u32 = undefined;
var x387: u32 = undefined;
mulxU32(&x386, &x387, x5, (arg2[1]));
var x388: u32 = undefined;
var x389: u32 = undefined;
mulxU32(&x388, &x389, x5, (arg2[0]));
var x390: u32 = undefined;
var x391: u1 = undefined;
addcarryxU32(&x390, &x391, 0x0, x389, x386);
var x392: u32 = undefined;
var x393: u1 = undefined;
addcarryxU32(&x392, &x393, x391, x387, x384);
var x394: u32 = undefined;
var x395: u1 = undefined;
addcarryxU32(&x394, &x395, x393, x385, x382);
var x396: u32 = undefined;
var x397: u1 = undefined;
addcarryxU32(&x396, &x397, x395, x383, x380);
var x398: u32 = undefined;
var x399: u1 = undefined;
addcarryxU32(&x398, &x399, x397, x381, x378);
var x400: u32 = undefined;
var x401: u1 = undefined;
addcarryxU32(&x400, &x401, x399, x379, x376);
const x402 = (cast(u32, x401) + x377);
var x403: u32 = undefined;
var x404: u1 = undefined;
addcarryxU32(&x403, &x404, 0x0, x361, x388);
var x405: u32 = undefined;
var x406: u1 = undefined;
addcarryxU32(&x405, &x406, x404, x363, x390);
var x407: u32 = undefined;
var x408: u1 = undefined;
addcarryxU32(&x407, &x408, x406, x365, x392);
var x409: u32 = undefined;
var x410: u1 = undefined;
addcarryxU32(&x409, &x410, x408, x367, x394);
var x411: u32 = undefined;
var x412: u1 = undefined;
addcarryxU32(&x411, &x412, x410, x369, x396);
var x413: u32 = undefined;
var x414: u1 = undefined;
addcarryxU32(&x413, &x414, x412, x371, x398);
var x415: u32 = undefined;
var x416: u1 = undefined;
addcarryxU32(&x415, &x416, x414, x373, x400);
var x417: u32 = undefined;
var x418: u1 = undefined;
addcarryxU32(&x417, &x418, x416, x375, x402);
var x419: u32 = undefined;
var x420: u32 = undefined;
mulxU32(&x419, &x420, x403, 0xffffffff);
var x421: u32 = undefined;
var x422: u32 = undefined;
mulxU32(&x421, &x422, x419, 0xffffffff);
var x423: u32 = undefined;
var x424: u32 = undefined;
mulxU32(&x423, &x424, x419, 0xffffffff);
var x425: u32 = undefined;
var x426: u32 = undefined;
mulxU32(&x425, &x426, x419, 0xffffffff);
var x427: u32 = undefined;
var x428: u32 = undefined;
mulxU32(&x427, &x428, x419, 0xffffffff);
var x429: u32 = undefined;
var x430: u1 = undefined;
addcarryxU32(&x429, &x430, 0x0, x428, x425);
var x431: u32 = undefined;
var x432: u1 = undefined;
addcarryxU32(&x431, &x432, x430, x426, x423);
var x433: u32 = undefined;
var x434: u1 = undefined;
addcarryxU32(&x433, &x434, x432, x424, x421);
const x435 = (cast(u32, x434) + x422);
var x436: u32 = undefined;
var x437: u1 = undefined;
addcarryxU32(&x436, &x437, 0x0, x403, x419);
var x438: u32 = undefined;
var x439: u1 = undefined;
addcarryxU32(&x438, &x439, x437, x405, cast(u32, 0x0));
var x440: u32 = undefined;
var x441: u1 = undefined;
addcarryxU32(&x440, &x441, x439, x407, cast(u32, 0x0));
var x442: u32 = undefined;
var x443: u1 = undefined;
addcarryxU32(&x442, &x443, x441, x409, x427);
var x444: u32 = undefined;
var x445: u1 = undefined;
addcarryxU32(&x444, &x445, x443, x411, x429);
var x446: u32 = undefined;
var x447: u1 = undefined;
addcarryxU32(&x446, &x447, x445, x413, x431);
var x448: u32 = undefined;
var x449: u1 = undefined;
addcarryxU32(&x448, &x449, x447, x415, x433);
var x450: u32 = undefined;
var x451: u1 = undefined;
addcarryxU32(&x450, &x451, x449, x417, x435);
const x452 = (cast(u32, x451) + cast(u32, x418));
var x453: u32 = undefined;
var x454: u32 = undefined;
mulxU32(&x453, &x454, x6, (arg2[6]));
var x455: u32 = undefined;
var x456: u32 = undefined;
mulxU32(&x455, &x456, x6, (arg2[5]));
var x457: u32 = undefined;
var x458: u32 = undefined;
mulxU32(&x457, &x458, x6, (arg2[4]));
var x459: u32 = undefined;
var x460: u32 = undefined;
mulxU32(&x459, &x460, x6, (arg2[3]));
var x461: u32 = undefined;
var x462: u32 = undefined;
mulxU32(&x461, &x462, x6, (arg2[2]));
var x463: u32 = undefined;
var x464: u32 = undefined;
mulxU32(&x463, &x464, x6, (arg2[1]));
var x465: u32 = undefined;
var x466: u32 = undefined;
mulxU32(&x465, &x466, x6, (arg2[0]));
var x467: u32 = undefined;
var x468: u1 = undefined;
addcarryxU32(&x467, &x468, 0x0, x466, x463);
var x469: u32 = undefined;
var x470: u1 = undefined;
addcarryxU32(&x469, &x470, x468, x464, x461);
var x471: u32 = undefined;
var x472: u1 = undefined;
addcarryxU32(&x471, &x472, x470, x462, x459);
var x473: u32 = undefined;
var x474: u1 = undefined;
addcarryxU32(&x473, &x474, x472, x460, x457);
var x475: u32 = undefined;
var x476: u1 = undefined;
addcarryxU32(&x475, &x476, x474, x458, x455);
var x477: u32 = undefined;
var x478: u1 = undefined;
addcarryxU32(&x477, &x478, x476, x456, x453);
const x479 = (cast(u32, x478) + x454);
var x480: u32 = undefined;
var x481: u1 = undefined;
addcarryxU32(&x480, &x481, 0x0, x438, x465);
var x482: u32 = undefined;
var x483: u1 = undefined;
addcarryxU32(&x482, &x483, x481, x440, x467);
var x484: u32 = undefined;
var x485: u1 = undefined;
addcarryxU32(&x484, &x485, x483, x442, x469);
var x486: u32 = undefined;
var x487: u1 = undefined;
addcarryxU32(&x486, &x487, x485, x444, x471);
var x488: u32 = undefined;
var x489: u1 = undefined;
addcarryxU32(&x488, &x489, x487, x446, x473);
var x490: u32 = undefined;
var x491: u1 = undefined;
addcarryxU32(&x490, &x491, x489, x448, x475);
var x492: u32 = undefined;
var x493: u1 = undefined;
addcarryxU32(&x492, &x493, x491, x450, x477);
var x494: u32 = undefined;
var x495: u1 = undefined;
addcarryxU32(&x494, &x495, x493, x452, x479);
var x496: u32 = undefined;
var x497: u32 = undefined;
mulxU32(&x496, &x497, x480, 0xffffffff);
var x498: u32 = undefined;
var x499: u32 = undefined;
mulxU32(&x498, &x499, x496, 0xffffffff);
var x500: u32 = undefined;
var x501: u32 = undefined;
mulxU32(&x500, &x501, x496, 0xffffffff);
var x502: u32 = undefined;
var x503: u32 = undefined;
mulxU32(&x502, &x503, x496, 0xffffffff);
var x504: u32 = undefined;
var x505: u32 = undefined;
mulxU32(&x504, &x505, x496, 0xffffffff);
var x506: u32 = undefined;
var x507: u1 = undefined;
addcarryxU32(&x506, &x507, 0x0, x505, x502);
var x508: u32 = undefined;
var x509: u1 = undefined;
addcarryxU32(&x508, &x509, x507, x503, x500);
var x510: u32 = undefined;
var x511: u1 = undefined;
addcarryxU32(&x510, &x511, x509, x501, x498);
const x512 = (cast(u32, x511) + x499);
var x513: u32 = undefined;
var x514: u1 = undefined;
addcarryxU32(&x513, &x514, 0x0, x480, x496);
var x515: u32 = undefined;
var x516: u1 = undefined;
addcarryxU32(&x515, &x516, x514, x482, cast(u32, 0x0));
var x517: u32 = undefined;
var x518: u1 = undefined;
addcarryxU32(&x517, &x518, x516, x484, cast(u32, 0x0));
var x519: u32 = undefined;
var x520: u1 = undefined;
addcarryxU32(&x519, &x520, x518, x486, x504);
var x521: u32 = undefined;
var x522: u1 = undefined;
addcarryxU32(&x521, &x522, x520, x488, x506);
var x523: u32 = undefined;
var x524: u1 = undefined;
addcarryxU32(&x523, &x524, x522, x490, x508);
var x525: u32 = undefined;
var x526: u1 = undefined;
addcarryxU32(&x525, &x526, x524, x492, x510);
var x527: u32 = undefined;
var x528: u1 = undefined;
addcarryxU32(&x527, &x528, x526, x494, x512);
const x529 = (cast(u32, x528) + cast(u32, x495));
var x530: u32 = undefined;
var x531: u1 = undefined;
subborrowxU32(&x530, &x531, 0x0, x515, cast(u32, 0x1));
var x532: u32 = undefined;
var x533: u1 = undefined;
subborrowxU32(&x532, &x533, x531, x517, cast(u32, 0x0));
var x534: u32 = undefined;
var x535: u1 = undefined;
subborrowxU32(&x534, &x535, x533, x519, cast(u32, 0x0));
var x536: u32 = undefined;
var x537: u1 = undefined;
subborrowxU32(&x536, &x537, x535, x521, 0xffffffff);
var x538: u32 = undefined;
var x539: u1 = undefined;
subborrowxU32(&x538, &x539, x537, x523, 0xffffffff);
var x540: u32 = undefined;
var x541: u1 = undefined;
subborrowxU32(&x540, &x541, x539, x525, 0xffffffff);
var x542: u32 = undefined;
var x543: u1 = undefined;
subborrowxU32(&x542, &x543, x541, x527, 0xffffffff);
var x544: u32 = undefined;
var x545: u1 = undefined;
subborrowxU32(&x544, &x545, x543, x529, cast(u32, 0x0));
var x546: u32 = undefined;
cmovznzU32(&x546, x545, x530, x515);
var x547: u32 = undefined;
cmovznzU32(&x547, x545, x532, x517);
var x548: u32 = undefined;
cmovznzU32(&x548, x545, x534, x519);
var x549: u32 = undefined;
cmovznzU32(&x549, x545, x536, x521);
var x550: u32 = undefined;
cmovznzU32(&x550, x545, x538, x523);
var x551: u32 = undefined;
cmovznzU32(&x551, x545, x540, x525);
var x552: u32 = undefined;
cmovznzU32(&x552, x545, x542, x527);
out1[0] = x546;
out1[1] = x547;
out1[2] = x548;
out1[3] = x549;
out1[4] = x550;
out1[5] = x551;
out1[6] = x552;
}
/// The function square squares a field element in the Montgomery domain.
///
/// Preconditions:
/// 0 ≤ eval arg1 < m
/// Postconditions:
/// eval (from_montgomery out1) mod m = (eval (from_montgomery arg1) * eval (from_montgomery arg1)) mod m
/// 0 ≤ eval out1 < m
///
pub fn square(out1: *MontgomeryDomainFieldElement, arg1: MontgomeryDomainFieldElement) void {
@setRuntimeSafety(mode == .Debug);
const x1 = (arg1[1]);
const x2 = (arg1[2]);
const x3 = (arg1[3]);
const x4 = (arg1[4]);
const x5 = (arg1[5]);
const x6 = (arg1[6]);
const x7 = (arg1[0]);
var x8: u32 = undefined;
var x9: u32 = undefined;
mulxU32(&x8, &x9, x7, (arg1[6]));
var x10: u32 = undefined;
var x11: u32 = undefined;
mulxU32(&x10, &x11, x7, (arg1[5]));
var x12: u32 = undefined;
var x13: u32 = undefined;
mulxU32(&x12, &x13, x7, (arg1[4]));
var x14: u32 = undefined;
var x15: u32 = undefined;
mulxU32(&x14, &x15, x7, (arg1[3]));
var x16: u32 = undefined;
var x17: u32 = undefined;
mulxU32(&x16, &x17, x7, (arg1[2]));
var x18: u32 = undefined;
var x19: u32 = undefined;
mulxU32(&x18, &x19, x7, (arg1[1]));
var x20: u32 = undefined;
var x21: u32 = undefined;
mulxU32(&x20, &x21, x7, (arg1[0]));
var x22: u32 = undefined;
var x23: u1 = undefined;
addcarryxU32(&x22, &x23, 0x0, x21, x18);
var x24: u32 = undefined;
var x25: u1 = undefined;
addcarryxU32(&x24, &x25, x23, x19, x16);
var x26: u32 = undefined;
var x27: u1 = undefined;
addcarryxU32(&x26, &x27, x25, x17, x14);
var x28: u32 = undefined;
var x29: u1 = undefined;
addcarryxU32(&x28, &x29, x27, x15, x12);
var x30: u32 = undefined;
var x31: u1 = undefined;
addcarryxU32(&x30, &x31, x29, x13, x10);
var x32: u32 = undefined;
var x33: u1 = undefined;
addcarryxU32(&x32, &x33, x31, x11, x8);
const x34 = (cast(u32, x33) + x9);
var x35: u32 = undefined;
var x36: u32 = undefined;
mulxU32(&x35, &x36, x20, 0xffffffff);
var x37: u32 = undefined;
var x38: u32 = undefined;
mulxU32(&x37, &x38, x35, 0xffffffff);
var x39: u32 = undefined;
var x40: u32 = undefined;
mulxU32(&x39, &x40, x35, 0xffffffff);
var x41: u32 = undefined;
var x42: u32 = undefined;
mulxU32(&x41, &x42, x35, 0xffffffff);
var x43: u32 = undefined;
var x44: u32 = undefined;
mulxU32(&x43, &x44, x35, 0xffffffff);
var x45: u32 = undefined;
var x46: u1 = undefined;
addcarryxU32(&x45, &x46, 0x0, x44, x41);
var x47: u32 = undefined;
var x48: u1 = undefined;
addcarryxU32(&x47, &x48, x46, x42, x39);
var x49: u32 = undefined;
var x50: u1 = undefined;
addcarryxU32(&x49, &x50, x48, x40, x37);
const x51 = (cast(u32, x50) + x38);
var x52: u32 = undefined;
var x53: u1 = undefined;
addcarryxU32(&x52, &x53, 0x0, x20, x35);
var x54: u32 = undefined;
var x55: u1 = undefined;
addcarryxU32(&x54, &x55, x53, x22, cast(u32, 0x0));
var x56: u32 = undefined;
var x57: u1 = undefined;
addcarryxU32(&x56, &x57, x55, x24, cast(u32, 0x0));
var x58: u32 = undefined;
var x59: u1 = undefined;
addcarryxU32(&x58, &x59, x57, x26, x43);
var x60: u32 = undefined;
var x61: u1 = undefined;
addcarryxU32(&x60, &x61, x59, x28, x45);
var x62: u32 = undefined;
var x63: u1 = undefined;
addcarryxU32(&x62, &x63, x61, x30, x47);
var x64: u32 = undefined;
var x65: u1 = undefined;
addcarryxU32(&x64, &x65, x63, x32, x49);
var x66: u32 = undefined;
var x67: u1 = undefined;
addcarryxU32(&x66, &x67, x65, x34, x51);
var x68: u32 = undefined;
var x69: u32 = undefined;
mulxU32(&x68, &x69, x1, (arg1[6]));
var x70: u32 = undefined;
var x71: u32 = undefined;
mulxU32(&x70, &x71, x1, (arg1[5]));
var x72: u32 = undefined;
var x73: u32 = undefined;
mulxU32(&x72, &x73, x1, (arg1[4]));
var x74: u32 = undefined;
var x75: u32 = undefined;
mulxU32(&x74, &x75, x1, (arg1[3]));
var x76: u32 = undefined;
var x77: u32 = undefined;
mulxU32(&x76, &x77, x1, (arg1[2]));
var x78: u32 = undefined;
var x79: u32 = undefined;
mulxU32(&x78, &x79, x1, (arg1[1]));
var x80: u32 = undefined;
var x81: u32 = undefined;
mulxU32(&x80, &x81, x1, (arg1[0]));
var x82: u32 = undefined;
var x83: u1 = undefined;
addcarryxU32(&x82, &x83, 0x0, x81, x78);
var x84: u32 = undefined;
var x85: u1 = undefined;
addcarryxU32(&x84, &x85, x83, x79, x76);
var x86: u32 = undefined;
var x87: u1 = undefined;
addcarryxU32(&x86, &x87, x85, x77, x74);
var x88: u32 = undefined;
var x89: u1 = undefined;
addcarryxU32(&x88, &x89, x87, x75, x72);
var x90: u32 = undefined;
var x91: u1 = undefined;
addcarryxU32(&x90, &x91, x89, x73, x70);
var x92: u32 = undefined;
var x93: u1 = undefined;
addcarryxU32(&x92, &x93, x91, x71, x68);
const x94 = (cast(u32, x93) + x69);
var x95: u32 = undefined;
var x96: u1 = undefined;
addcarryxU32(&x95, &x96, 0x0, x54, x80);
var x97: u32 = undefined;
var x98: u1 = undefined;
addcarryxU32(&x97, &x98, x96, x56, x82);
var x99: u32 = undefined;
var x100: u1 = undefined;
addcarryxU32(&x99, &x100, x98, x58, x84);
var x101: u32 = undefined;
var x102: u1 = undefined;
addcarryxU32(&x101, &x102, x100, x60, x86);
var x103: u32 = undefined;
var x104: u1 = undefined;
addcarryxU32(&x103, &x104, x102, x62, x88);
var x105: u32 = undefined;
var x106: u1 = undefined;
addcarryxU32(&x105, &x106, x104, x64, x90);
var x107: u32 = undefined;
var x108: u1 = undefined;
addcarryxU32(&x107, &x108, x106, x66, x92);
var x109: u32 = undefined;
var x110: u1 = undefined;
addcarryxU32(&x109, &x110, x108, cast(u32, x67), x94);
var x111: u32 = undefined;
var x112: u32 = undefined;
mulxU32(&x111, &x112, x95, 0xffffffff);
var x113: u32 = undefined;
var x114: u32 = undefined;
mulxU32(&x113, &x114, x111, 0xffffffff);
var x115: u32 = undefined;
var x116: u32 = undefined;
mulxU32(&x115, &x116, x111, 0xffffffff);
var x117: u32 = undefined;
var x118: u32 = undefined;
mulxU32(&x117, &x118, x111, 0xffffffff);
var x119: u32 = undefined;
var x120: u32 = undefined;
mulxU32(&x119, &x120, x111, 0xffffffff);
var x121: u32 = undefined;
var x122: u1 = undefined;
addcarryxU32(&x121, &x122, 0x0, x120, x117);
var x123: u32 = undefined;
var x124: u1 = undefined;
addcarryxU32(&x123, &x124, x122, x118, x115);
var x125: u32 = undefined;
var x126: u1 = undefined;
addcarryxU32(&x125, &x126, x124, x116, x113);
const x127 = (cast(u32, x126) + x114);
var x128: u32 = undefined;
var x129: u1 = undefined;
addcarryxU32(&x128, &x129, 0x0, x95, x111);
var x130: u32 = undefined;
var x131: u1 = undefined;
addcarryxU32(&x130, &x131, x129, x97, cast(u32, 0x0));
var x132: u32 = undefined;
var x133: u1 = undefined;
addcarryxU32(&x132, &x133, x131, x99, cast(u32, 0x0));
var x134: u32 = undefined;
var x135: u1 = undefined;
addcarryxU32(&x134, &x135, x133, x101, x119);
var x136: u32 = undefined;
var x137: u1 = undefined;
addcarryxU32(&x136, &x137, x135, x103, x121);
var x138: u32 = undefined;
var x139: u1 = undefined;
addcarryxU32(&x138, &x139, x137, x105, x123);
var x140: u32 = undefined;
var x141: u1 = undefined;
addcarryxU32(&x140, &x141, x139, x107, x125);
var x142: u32 = undefined;
var x143: u1 = undefined;
addcarryxU32(&x142, &x143, x141, x109, x127);
const x144 = (cast(u32, x143) + cast(u32, x110));
var x145: u32 = undefined;
var x146: u32 = undefined;
mulxU32(&x145, &x146, x2, (arg1[6]));
var x147: u32 = undefined;
var x148: u32 = undefined;
mulxU32(&x147, &x148, x2, (arg1[5]));
var x149: u32 = undefined;
var x150: u32 = undefined;
mulxU32(&x149, &x150, x2, (arg1[4]));
var x151: u32 = undefined;
var x152: u32 = undefined;
mulxU32(&x151, &x152, x2, (arg1[3]));
var x153: u32 = undefined;
var x154: u32 = undefined;
mulxU32(&x153, &x154, x2, (arg1[2]));
var x155: u32 = undefined;
var x156: u32 = undefined;
mulxU32(&x155, &x156, x2, (arg1[1]));
var x157: u32 = undefined;
var x158: u32 = undefined;
mulxU32(&x157, &x158, x2, (arg1[0]));
var x159: u32 = undefined;
var x160: u1 = undefined;
addcarryxU32(&x159, &x160, 0x0, x158, x155);
var x161: u32 = undefined;
var x162: u1 = undefined;
addcarryxU32(&x161, &x162, x160, x156, x153);
var x163: u32 = undefined;
var x164: u1 = undefined;
addcarryxU32(&x163, &x164, x162, x154, x151);
var x165: u32 = undefined;
var x166: u1 = undefined;
addcarryxU32(&x165, &x166, x164, x152, x149);
var x167: u32 = undefined;
var x168: u1 = undefined;
addcarryxU32(&x167, &x168, x166, x150, x147);
var x169: u32 = undefined;
var x170: u1 = undefined;
addcarryxU32(&x169, &x170, x168, x148, x145);
const x171 = (cast(u32, x170) + x146);
var x172: u32 = undefined;
var x173: u1 = undefined;
addcarryxU32(&x172, &x173, 0x0, x130, x157);
var x174: u32 = undefined;
var x175: u1 = undefined;
addcarryxU32(&x174, &x175, x173, x132, x159);
var x176: u32 = undefined;
var x177: u1 = undefined;
addcarryxU32(&x176, &x177, x175, x134, x161);
var x178: u32 = undefined;
var x179: u1 = undefined;
addcarryxU32(&x178, &x179, x177, x136, x163);
var x180: u32 = undefined;
var x181: u1 = undefined;
addcarryxU32(&x180, &x181, x179, x138, x165);
var x182: u32 = undefined;
var x183: u1 = undefined;
addcarryxU32(&x182, &x183, x181, x140, x167);
var x184: u32 = undefined;
var x185: u1 = undefined;
addcarryxU32(&x184, &x185, x183, x142, x169);
var x186: u32 = undefined;
var x187: u1 = undefined;
addcarryxU32(&x186, &x187, x185, x144, x171);
var x188: u32 = undefined;
var x189: u32 = undefined;
mulxU32(&x188, &x189, x172, 0xffffffff);
var x190: u32 = undefined;
var x191: u32 = undefined;
mulxU32(&x190, &x191, x188, 0xffffffff);
var x192: u32 = undefined;
var x193: u32 = undefined;
mulxU32(&x192, &x193, x188, 0xffffffff);
var x194: u32 = undefined;
var x195: u32 = undefined;
mulxU32(&x194, &x195, x188, 0xffffffff);
var x196: u32 = undefined;
var x197: u32 = undefined;
mulxU32(&x196, &x197, x188, 0xffffffff);
var x198: u32 = undefined;
var x199: u1 = undefined;
addcarryxU32(&x198, &x199, 0x0, x197, x194);
var x200: u32 = undefined;
var x201: u1 = undefined;
addcarryxU32(&x200, &x201, x199, x195, x192);
var x202: u32 = undefined;
var x203: u1 = undefined;
addcarryxU32(&x202, &x203, x201, x193, x190);
const x204 = (cast(u32, x203) + x191);
var x205: u32 = undefined;
var x206: u1 = undefined;
addcarryxU32(&x205, &x206, 0x0, x172, x188);
var x207: u32 = undefined;
var x208: u1 = undefined;
addcarryxU32(&x207, &x208, x206, x174, cast(u32, 0x0));
var x209: u32 = undefined;
var x210: u1 = undefined;
addcarryxU32(&x209, &x210, x208, x176, cast(u32, 0x0));
var x211: u32 = undefined;
var x212: u1 = undefined;
addcarryxU32(&x211, &x212, x210, x178, x196);
var x213: u32 = undefined;
var x214: u1 = undefined;
addcarryxU32(&x213, &x214, x212, x180, x198);
var x215: u32 = undefined;
var x216: u1 = undefined;
addcarryxU32(&x215, &x216, x214, x182, x200);
var x217: u32 = undefined;
var x218: u1 = undefined;
addcarryxU32(&x217, &x218, x216, x184, x202);
var x219: u32 = undefined;
var x220: u1 = undefined;
addcarryxU32(&x219, &x220, x218, x186, x204);
const x221 = (cast(u32, x220) + cast(u32, x187));
var x222: u32 = undefined;
var x223: u32 = undefined;
mulxU32(&x222, &x223, x3, (arg1[6]));
var x224: u32 = undefined;
var x225: u32 = undefined;
mulxU32(&x224, &x225, x3, (arg1[5]));
var x226: u32 = undefined;
var x227: u32 = undefined;
mulxU32(&x226, &x227, x3, (arg1[4]));
var x228: u32 = undefined;
var x229: u32 = undefined;
mulxU32(&x228, &x229, x3, (arg1[3]));
var x230: u32 = undefined;
var x231: u32 = undefined;
mulxU32(&x230, &x231, x3, (arg1[2]));
var x232: u32 = undefined;
var x233: u32 = undefined;
mulxU32(&x232, &x233, x3, (arg1[1]));
var x234: u32 = undefined;
var x235: u32 = undefined;
mulxU32(&x234, &x235, x3, (arg1[0]));
var x236: u32 = undefined;
var x237: u1 = undefined;
addcarryxU32(&x236, &x237, 0x0, x235, x232);
var x238: u32 = undefined;
var x239: u1 = undefined;
addcarryxU32(&x238, &x239, x237, x233, x230);
var x240: u32 = undefined;
var x241: u1 = undefined;
addcarryxU32(&x240, &x241, x239, x231, x228);
var x242: u32 = undefined;
var x243: u1 = undefined;
addcarryxU32(&x242, &x243, x241, x229, x226);
var x244: u32 = undefined;
var x245: u1 = undefined;
addcarryxU32(&x244, &x245, x243, x227, x224);
var x246: u32 = undefined;
var x247: u1 = undefined;
addcarryxU32(&x246, &x247, x245, x225, x222);
const x248 = (cast(u32, x247) + x223);
var x249: u32 = undefined;
var x250: u1 = undefined;
addcarryxU32(&x249, &x250, 0x0, x207, x234);
var x251: u32 = undefined;
var x252: u1 = undefined;
addcarryxU32(&x251, &x252, x250, x209, x236);
var x253: u32 = undefined;
var x254: u1 = undefined;
addcarryxU32(&x253, &x254, x252, x211, x238);
var x255: u32 = undefined;
var x256: u1 = undefined;
addcarryxU32(&x255, &x256, x254, x213, x240);
var x257: u32 = undefined;
var x258: u1 = undefined;
addcarryxU32(&x257, &x258, x256, x215, x242);
var x259: u32 = undefined;
var x260: u1 = undefined;
addcarryxU32(&x259, &x260, x258, x217, x244);
var x261: u32 = undefined;
var x262: u1 = undefined;
addcarryxU32(&x261, &x262, x260, x219, x246);
var x263: u32 = undefined;
var x264: u1 = undefined;
addcarryxU32(&x263, &x264, x262, x221, x248);
var x265: u32 = undefined;
var x266: u32 = undefined;
mulxU32(&x265, &x266, x249, 0xffffffff);
var x267: u32 = undefined;
var x268: u32 = undefined;
mulxU32(&x267, &x268, x265, 0xffffffff);
var x269: u32 = undefined;
var x270: u32 = undefined;
mulxU32(&x269, &x270, x265, 0xffffffff);
var x271: u32 = undefined;
var x272: u32 = undefined;
mulxU32(&x271, &x272, x265, 0xffffffff);
var x273: u32 = undefined;
var x274: u32 = undefined;
mulxU32(&x273, &x274, x265, 0xffffffff);
var x275: u32 = undefined;
var x276: u1 = undefined;
addcarryxU32(&x275, &x276, 0x0, x274, x271);
var x277: u32 = undefined;
var x278: u1 = undefined;
addcarryxU32(&x277, &x278, x276, x272, x269);
var x279: u32 = undefined;
var x280: u1 = undefined;
addcarryxU32(&x279, &x280, x278, x270, x267);
const x281 = (cast(u32, x280) + x268);
var x282: u32 = undefined;
var x283: u1 = undefined;
addcarryxU32(&x282, &x283, 0x0, x249, x265);
var x284: u32 = undefined;
var x285: u1 = undefined;
addcarryxU32(&x284, &x285, x283, x251, cast(u32, 0x0));
var x286: u32 = undefined;
var x287: u1 = undefined;
addcarryxU32(&x286, &x287, x285, x253, cast(u32, 0x0));
var x288: u32 = undefined;
var x289: u1 = undefined;
addcarryxU32(&x288, &x289, x287, x255, x273);
var x290: u32 = undefined;
var x291: u1 = undefined;
addcarryxU32(&x290, &x291, x289, x257, x275);
var x292: u32 = undefined;
var x293: u1 = undefined;
addcarryxU32(&x292, &x293, x291, x259, x277);
var x294: u32 = undefined;
var x295: u1 = undefined;
addcarryxU32(&x294, &x295, x293, x261, x279);
var x296: u32 = undefined;
var x297: u1 = undefined;
addcarryxU32(&x296, &x297, x295, x263, x281);
const x298 = (cast(u32, x297) + cast(u32, x264));
var x299: u32 = undefined;
var x300: u32 = undefined;
mulxU32(&x299, &x300, x4, (arg1[6]));
var x301: u32 = undefined;
var x302: u32 = undefined;
mulxU32(&x301, &x302, x4, (arg1[5]));
var x303: u32 = undefined;
var x304: u32 = undefined;
mulxU32(&x303, &x304, x4, (arg1[4]));
var x305: u32 = undefined;
var x306: u32 = undefined;
mulxU32(&x305, &x306, x4, (arg1[3]));
var x307: u32 = undefined;
var x308: u32 = undefined;
mulxU32(&x307, &x308, x4, (arg1[2]));
var x309: u32 = undefined;
var x310: u32 = undefined;
mulxU32(&x309, &x310, x4, (arg1[1]));
var x311: u32 = undefined;
var x312: u32 = undefined;
mulxU32(&x311, &x312, x4, (arg1[0]));
var x313: u32 = undefined;
var x314: u1 = undefined;
addcarryxU32(&x313, &x314, 0x0, x312, x309);
var x315: u32 = undefined;
var x316: u1 = undefined;
addcarryxU32(&x315, &x316, x314, x310, x307);
var x317: u32 = undefined;
var x318: u1 = undefined;
addcarryxU32(&x317, &x318, x316, x308, x305);
var x319: u32 = undefined;
var x320: u1 = undefined;
addcarryxU32(&x319, &x320, x318, x306, x303);
var x321: u32 = undefined;
var x322: u1 = undefined;
addcarryxU32(&x321, &x322, x320, x304, x301);
var x323: u32 = undefined;
var x324: u1 = undefined;
addcarryxU32(&x323, &x324, x322, x302, x299);
const x325 = (cast(u32, x324) + x300);
var x326: u32 = undefined;
var x327: u1 = undefined;
addcarryxU32(&x326, &x327, 0x0, x284, x311);
var x328: u32 = undefined;
var x329: u1 = undefined;
addcarryxU32(&x328, &x329, x327, x286, x313);
var x330: u32 = undefined;
var x331: u1 = undefined;
addcarryxU32(&x330, &x331, x329, x288, x315);
var x332: u32 = undefined;
var x333: u1 = undefined;
addcarryxU32(&x332, &x333, x331, x290, x317);
var x334: u32 = undefined;
var x335: u1 = undefined;
addcarryxU32(&x334, &x335, x333, x292, x319);
var x336: u32 = undefined;
var x337: u1 = undefined;
addcarryxU32(&x336, &x337, x335, x294, x321);
var x338: u32 = undefined;
var x339: u1 = undefined;
addcarryxU32(&x338, &x339, x337, x296, x323);
var x340: u32 = undefined;
var x341: u1 = undefined;
addcarryxU32(&x340, &x341, x339, x298, x325);
var x342: u32 = undefined;
var x343: u32 = undefined;
mulxU32(&x342, &x343, x326, 0xffffffff);
var x344: u32 = undefined;
var x345: u32 = undefined;
mulxU32(&x344, &x345, x342, 0xffffffff);
var x346: u32 = undefined;
var x347: u32 = undefined;
mulxU32(&x346, &x347, x342, 0xffffffff);
var x348: u32 = undefined;
var x349: u32 = undefined;
mulxU32(&x348, &x349, x342, 0xffffffff);
var x350: u32 = undefined;
var x351: u32 = undefined;
mulxU32(&x350, &x351, x342, 0xffffffff);
var x352: u32 = undefined;
var x353: u1 = undefined;
addcarryxU32(&x352, &x353, 0x0, x351, x348);
var x354: u32 = undefined;
var x355: u1 = undefined;
addcarryxU32(&x354, &x355, x353, x349, x346);
var x356: u32 = undefined;
var x357: u1 = undefined;
addcarryxU32(&x356, &x357, x355, x347, x344);
const x358 = (cast(u32, x357) + x345);
var x359: u32 = undefined;
var x360: u1 = undefined;
addcarryxU32(&x359, &x360, 0x0, x326, x342);
var x361: u32 = undefined;
var x362: u1 = undefined;
addcarryxU32(&x361, &x362, x360, x328, cast(u32, 0x0));
var x363: u32 = undefined;
var x364: u1 = undefined;
addcarryxU32(&x363, &x364, x362, x330, cast(u32, 0x0));
var x365: u32 = undefined;
var x366: u1 = undefined;
addcarryxU32(&x365, &x366, x364, x332, x350);
var x367: u32 = undefined;
var x368: u1 = undefined;
addcarryxU32(&x367, &x368, x366, x334, x352);
var x369: u32 = undefined;
var x370: u1 = undefined;
addcarryxU32(&x369, &x370, x368, x336, x354);
var x371: u32 = undefined;
var x372: u1 = undefined;
addcarryxU32(&x371, &x372, x370, x338, x356);
var x373: u32 = undefined;
var x374: u1 = undefined;
addcarryxU32(&x373, &x374, x372, x340, x358);
const x375 = (cast(u32, x374) + cast(u32, x341));
var x376: u32 = undefined;
var x377: u32 = undefined;
mulxU32(&x376, &x377, x5, (arg1[6]));
var x378: u32 = undefined;
var x379: u32 = undefined;
mulxU32(&x378, &x379, x5, (arg1[5]));
var x380: u32 = undefined;
var x381: u32 = undefined;
mulxU32(&x380, &x381, x5, (arg1[4]));
var x382: u32 = undefined;
var x383: u32 = undefined;
mulxU32(&x382, &x383, x5, (arg1[3]));
var x384: u32 = undefined;
var x385: u32 = undefined;
mulxU32(&x384, &x385, x5, (arg1[2]));
var x386: u32 = undefined;
var x387: u32 = undefined;
mulxU32(&x386, &x387, x5, (arg1[1]));
var x388: u32 = undefined;
var x389: u32 = undefined;
mulxU32(&x388, &x389, x5, (arg1[0]));
var x390: u32 = undefined;
var x391: u1 = undefined;
addcarryxU32(&x390, &x391, 0x0, x389, x386);
var x392: u32 = undefined;
var x393: u1 = undefined;
addcarryxU32(&x392, &x393, x391, x387, x384);
var x394: u32 = undefined;
var x395: u1 = undefined;
addcarryxU32(&x394, &x395, x393, x385, x382);
var x396: u32 = undefined;
var x397: u1 = undefined;
addcarryxU32(&x396, &x397, x395, x383, x380);
var x398: u32 = undefined;
var x399: u1 = undefined;
addcarryxU32(&x398, &x399, x397, x381, x378);
var x400: u32 = undefined;
var x401: u1 = undefined;
addcarryxU32(&x400, &x401, x399, x379, x376);
const x402 = (cast(u32, x401) + x377);
var x403: u32 = undefined;
var x404: u1 = undefined;
addcarryxU32(&x403, &x404, 0x0, x361, x388);
var x405: u32 = undefined;
var x406: u1 = undefined;
addcarryxU32(&x405, &x406, x404, x363, x390);
var x407: u32 = undefined;
var x408: u1 = undefined;
addcarryxU32(&x407, &x408, x406, x365, x392);
var x409: u32 = undefined;
var x410: u1 = undefined;
addcarryxU32(&x409, &x410, x408, x367, x394);
var x411: u32 = undefined;
var x412: u1 = undefined;
addcarryxU32(&x411, &x412, x410, x369, x396);
var x413: u32 = undefined;
var x414: u1 = undefined;
addcarryxU32(&x413, &x414, x412, x371, x398);
var x415: u32 = undefined;
var x416: u1 = undefined;
addcarryxU32(&x415, &x416, x414, x373, x400);
var x417: u32 = undefined;
var x418: u1 = undefined;
addcarryxU32(&x417, &x418, x416, x375, x402);
var x419: u32 = undefined;
var x420: u32 = undefined;
mulxU32(&x419, &x420, x403, 0xffffffff);
var x421: u32 = undefined;
var x422: u32 = undefined;
mulxU32(&x421, &x422, x419, 0xffffffff);
var x423: u32 = undefined;
var x424: u32 = undefined;
mulxU32(&x423, &x424, x419, 0xffffffff);
var x425: u32 = undefined;
var x426: u32 = undefined;
mulxU32(&x425, &x426, x419, 0xffffffff);
var x427: u32 = undefined;
var x428: u32 = undefined;
mulxU32(&x427, &x428, x419, 0xffffffff);
var x429: u32 = undefined;
var x430: u1 = undefined;
addcarryxU32(&x429, &x430, 0x0, x428, x425);
var x431: u32 = undefined;
var x432: u1 = undefined;
addcarryxU32(&x431, &x432, x430, x426, x423);
var x433: u32 = undefined;
var x434: u1 = undefined;
addcarryxU32(&x433, &x434, x432, x424, x421);
const x435 = (cast(u32, x434) + x422);
var x436: u32 = undefined;
var x437: u1 = undefined;
addcarryxU32(&x436, &x437, 0x0, x403, x419);
var x438: u32 = undefined;
var x439: u1 = undefined;
addcarryxU32(&x438, &x439, x437, x405, cast(u32, 0x0));
var x440: u32 = undefined;
var x441: u1 = undefined;
addcarryxU32(&x440, &x441, x439, x407, cast(u32, 0x0));
var x442: u32 = undefined;
var x443: u1 = undefined;
addcarryxU32(&x442, &x443, x441, x409, x427);
var x444: u32 = undefined;
var x445: u1 = undefined;
addcarryxU32(&x444, &x445, x443, x411, x429);
var x446: u32 = undefined;
var x447: u1 = undefined;
addcarryxU32(&x446, &x447, x445, x413, x431);
var x448: u32 = undefined;
var x449: u1 = undefined;
addcarryxU32(&x448, &x449, x447, x415, x433);
var x450: u32 = undefined;
var x451: u1 = undefined;
addcarryxU32(&x450, &x451, x449, x417, x435);
const x452 = (cast(u32, x451) + cast(u32, x418));
var x453: u32 = undefined;
var x454: u32 = undefined;
mulxU32(&x453, &x454, x6, (arg1[6]));
var x455: u32 = undefined;
var x456: u32 = undefined;
mulxU32(&x455, &x456, x6, (arg1[5]));
var x457: u32 = undefined;
var x458: u32 = undefined;
mulxU32(&x457, &x458, x6, (arg1[4]));
var x459: u32 = undefined;
var x460: u32 = undefined;
mulxU32(&x459, &x460, x6, (arg1[3]));
var x461: u32 = undefined;
var x462: u32 = undefined;
mulxU32(&x461, &x462, x6, (arg1[2]));
var x463: u32 = undefined;
var x464: u32 = undefined;
mulxU32(&x463, &x464, x6, (arg1[1]));
var x465: u32 = undefined;
var x466: u32 = undefined;
mulxU32(&x465, &x466, x6, (arg1[0]));
var x467: u32 = undefined;
var x468: u1 = undefined;
addcarryxU32(&x467, &x468, 0x0, x466, x463);
var x469: u32 = undefined;
var x470: u1 = undefined;
addcarryxU32(&x469, &x470, x468, x464, x461);
var x471: u32 = undefined;
var x472: u1 = undefined;
addcarryxU32(&x471, &x472, x470, x462, x459);
var x473: u32 = undefined;
var x474: u1 = undefined;
addcarryxU32(&x473, &x474, x472, x460, x457);
var x475: u32 = undefined;
var x476: u1 = undefined;
addcarryxU32(&x475, &x476, x474, x458, x455);
var x477: u32 = undefined;
var x478: u1 = undefined;
addcarryxU32(&x477, &x478, x476, x456, x453);
const x479 = (cast(u32, x478) + x454);
var x480: u32 = undefined;
var x481: u1 = undefined;
addcarryxU32(&x480, &x481, 0x0, x438, x465);
var x482: u32 = undefined;
var x483: u1 = undefined;
addcarryxU32(&x482, &x483, x481, x440, x467);
var x484: u32 = undefined;
var x485: u1 = undefined;
addcarryxU32(&x484, &x485, x483, x442, x469);
var x486: u32 = undefined;
var x487: u1 = undefined;
addcarryxU32(&x486, &x487, x485, x444, x471);
var x488: u32 = undefined;
var x489: u1 = undefined;
addcarryxU32(&x488, &x489, x487, x446, x473);
var x490: u32 = undefined;
var x491: u1 = undefined;
addcarryxU32(&x490, &x491, x489, x448, x475);
var x492: u32 = undefined;
var x493: u1 = undefined;
addcarryxU32(&x492, &x493, x491, x450, x477);
var x494: u32 = undefined;
var x495: u1 = undefined;
addcarryxU32(&x494, &x495, x493, x452, x479);
var x496: u32 = undefined;
var x497: u32 = undefined;
mulxU32(&x496, &x497, x480, 0xffffffff);
var x498: u32 = undefined;
var x499: u32 = undefined;
mulxU32(&x498, &x499, x496, 0xffffffff);
var x500: u32 = undefined;
var x501: u32 = undefined;
mulxU32(&x500, &x501, x496, 0xffffffff);
var x502: u32 = undefined;
var x503: u32 = undefined;
mulxU32(&x502, &x503, x496, 0xffffffff);
var x504: u32 = undefined;
var x505: u32 = undefined;
mulxU32(&x504, &x505, x496, 0xffffffff);
var x506: u32 = undefined;
var x507: u1 = undefined;
addcarryxU32(&x506, &x507, 0x0, x505, x502);
var x508: u32 = undefined;
var x509: u1 = undefined;
addcarryxU32(&x508, &x509, x507, x503, x500);
var x510: u32 = undefined;
var x511: u1 = undefined;
addcarryxU32(&x510, &x511, x509, x501, x498);
const x512 = (cast(u32, x511) + x499);
var x513: u32 = undefined;
var x514: u1 = undefined;
addcarryxU32(&x513, &x514, 0x0, x480, x496);
var x515: u32 = undefined;
var x516: u1 = undefined;
addcarryxU32(&x515, &x516, x514, x482, cast(u32, 0x0));
var x517: u32 = undefined;
var x518: u1 = undefined;
addcarryxU32(&x517, &x518, x516, x484, cast(u32, 0x0));
var x519: u32 = undefined;
var x520: u1 = undefined;
addcarryxU32(&x519, &x520, x518, x486, x504);
var x521: u32 = undefined;
var x522: u1 = undefined;
addcarryxU32(&x521, &x522, x520, x488, x506);
var x523: u32 = undefined;
var x524: u1 = undefined;
addcarryxU32(&x523, &x524, x522, x490, x508);
var x525: u32 = undefined;
var x526: u1 = undefined;
addcarryxU32(&x525, &x526, x524, x492, x510);
var x527: u32 = undefined;
var x528: u1 = undefined;
addcarryxU32(&x527, &x528, x526, x494, x512);
const x529 = (cast(u32, x528) + cast(u32, x495));
var x530: u32 = undefined;
var x531: u1 = undefined;
subborrowxU32(&x530, &x531, 0x0, x515, cast(u32, 0x1));
var x532: u32 = undefined;
var x533: u1 = undefined;
subborrowxU32(&x532, &x533, x531, x517, cast(u32, 0x0));
var x534: u32 = undefined;
var x535: u1 = undefined;
subborrowxU32(&x534, &x535, x533, x519, cast(u32, 0x0));
var x536: u32 = undefined;
var x537: u1 = undefined;
subborrowxU32(&x536, &x537, x535, x521, 0xffffffff);
var x538: u32 = undefined;
var x539: u1 = undefined;
subborrowxU32(&x538, &x539, x537, x523, 0xffffffff);
var x540: u32 = undefined;
var x541: u1 = undefined;
subborrowxU32(&x540, &x541, x539, x525, 0xffffffff);
var x542: u32 = undefined;
var x543: u1 = undefined;
subborrowxU32(&x542, &x543, x541, x527, 0xffffffff);
var x544: u32 = undefined;
var x545: u1 = undefined;
subborrowxU32(&x544, &x545, x543, x529, cast(u32, 0x0));
var x546: u32 = undefined;
cmovznzU32(&x546, x545, x530, x515);
var x547: u32 = undefined;
cmovznzU32(&x547, x545, x532, x517);
var x548: u32 = undefined;
cmovznzU32(&x548, x545, x534, x519);
var x549: u32 = undefined;
cmovznzU32(&x549, x545, x536, x521);
var x550: u32 = undefined;
cmovznzU32(&x550, x545, x538, x523);
var x551: u32 = undefined;
cmovznzU32(&x551, x545, x540, x525);
var x552: u32 = undefined;
cmovznzU32(&x552, x545, x542, x527);
out1[0] = x546;
out1[1] = x547;
out1[2] = x548;
out1[3] = x549;
out1[4] = x550;
out1[5] = x551;
out1[6] = x552;
}
/// The function add adds two field elements in the Montgomery domain.
///
/// Preconditions:
/// 0 ≤ eval arg1 < m
/// 0 ≤ eval arg2 < m
/// Postconditions:
/// eval (from_montgomery out1) mod m = (eval (from_montgomery arg1) + eval (from_montgomery arg2)) mod m
/// 0 ≤ eval out1 < m
///
pub fn add(out1: *MontgomeryDomainFieldElement, arg1: MontgomeryDomainFieldElement, arg2: MontgomeryDomainFieldElement) void {
@setRuntimeSafety(mode == .Debug);
var x1: u32 = undefined;
var x2: u1 = undefined;
addcarryxU32(&x1, &x2, 0x0, (arg1[0]), (arg2[0]));
var x3: u32 = undefined;
var x4: u1 = undefined;
addcarryxU32(&x3, &x4, x2, (arg1[1]), (arg2[1]));
var x5: u32 = undefined;
var x6: u1 = undefined;
addcarryxU32(&x5, &x6, x4, (arg1[2]), (arg2[2]));
var x7: u32 = undefined;
var x8: u1 = undefined;
addcarryxU32(&x7, &x8, x6, (arg1[3]), (arg2[3]));
var x9: u32 = undefined;
var x10: u1 = undefined;
addcarryxU32(&x9, &x10, x8, (arg1[4]), (arg2[4]));
var x11: u32 = undefined;
var x12: u1 = undefined;
addcarryxU32(&x11, &x12, x10, (arg1[5]), (arg2[5]));
var x13: u32 = undefined;
var x14: u1 = undefined;
addcarryxU32(&x13, &x14, x12, (arg1[6]), (arg2[6]));
var x15: u32 = undefined;
var x16: u1 = undefined;
subborrowxU32(&x15, &x16, 0x0, x1, cast(u32, 0x1));
var x17: u32 = undefined;
var x18: u1 = undefined;
subborrowxU32(&x17, &x18, x16, x3, cast(u32, 0x0));
var x19: u32 = undefined;
var x20: u1 = undefined;
subborrowxU32(&x19, &x20, x18, x5, cast(u32, 0x0));
var x21: u32 = undefined;
var x22: u1 = undefined;
subborrowxU32(&x21, &x22, x20, x7, 0xffffffff);
var x23: u32 = undefined;
var x24: u1 = undefined;
subborrowxU32(&x23, &x24, x22, x9, 0xffffffff);
var x25: u32 = undefined;
var x26: u1 = undefined;
subborrowxU32(&x25, &x26, x24, x11, 0xffffffff);
var x27: u32 = undefined;
var x28: u1 = undefined;
subborrowxU32(&x27, &x28, x26, x13, 0xffffffff);
var x29: u32 = undefined;
var x30: u1 = undefined;
subborrowxU32(&x29, &x30, x28, cast(u32, x14), cast(u32, 0x0));
var x31: u32 = undefined;
cmovznzU32(&x31, x30, x15, x1);
var x32: u32 = undefined;
cmovznzU32(&x32, x30, x17, x3);
var x33: u32 = undefined;
cmovznzU32(&x33, x30, x19, x5);
var x34: u32 = undefined;
cmovznzU32(&x34, x30, x21, x7);
var x35: u32 = undefined;
cmovznzU32(&x35, x30, x23, x9);
var x36: u32 = undefined;
cmovznzU32(&x36, x30, x25, x11);
var x37: u32 = undefined;
cmovznzU32(&x37, x30, x27, x13);
out1[0] = x31;
out1[1] = x32;
out1[2] = x33;
out1[3] = x34;
out1[4] = x35;
out1[5] = x36;
out1[6] = x37;
}
/// The function sub subtracts two field elements in the Montgomery domain.
///
/// Preconditions:
/// 0 ≤ eval arg1 < m
/// 0 ≤ eval arg2 < m
/// Postconditions:
/// eval (from_montgomery out1) mod m = (eval (from_montgomery arg1) - eval (from_montgomery arg2)) mod m
/// 0 ≤ eval out1 < m
///
pub fn sub(out1: *MontgomeryDomainFieldElement, arg1: MontgomeryDomainFieldElement, arg2: MontgomeryDomainFieldElement) void {
@setRuntimeSafety(mode == .Debug);
var x1: u32 = undefined;
var x2: u1 = undefined;
subborrowxU32(&x1, &x2, 0x0, (arg1[0]), (arg2[0]));
var x3: u32 = undefined;
var x4: u1 = undefined;
subborrowxU32(&x3, &x4, x2, (arg1[1]), (arg2[1]));
var x5: u32 = undefined;
var x6: u1 = undefined;
subborrowxU32(&x5, &x6, x4, (arg1[2]), (arg2[2]));
var x7: u32 = undefined;
var x8: u1 = undefined;
subborrowxU32(&x7, &x8, x6, (arg1[3]), (arg2[3]));
var x9: u32 = undefined;
var x10: u1 = undefined;
subborrowxU32(&x9, &x10, x8, (arg1[4]), (arg2[4]));
var x11: u32 = undefined;
var x12: u1 = undefined;
subborrowxU32(&x11, &x12, x10, (arg1[5]), (arg2[5]));
var x13: u32 = undefined;
var x14: u1 = undefined;
subborrowxU32(&x13, &x14, x12, (arg1[6]), (arg2[6]));
var x15: u32 = undefined;
cmovznzU32(&x15, x14, cast(u32, 0x0), 0xffffffff);
var x16: u32 = undefined;
var x17: u1 = undefined;
addcarryxU32(&x16, &x17, 0x0, x1, cast(u32, cast(u1, (x15 & cast(u32, 0x1)))));
var x18: u32 = undefined;
var x19: u1 = undefined;
addcarryxU32(&x18, &x19, x17, x3, cast(u32, 0x0));
var x20: u32 = undefined;
var x21: u1 = undefined;
addcarryxU32(&x20, &x21, x19, x5, cast(u32, 0x0));
var x22: u32 = undefined;
var x23: u1 = undefined;
addcarryxU32(&x22, &x23, x21, x7, x15);
var x24: u32 = undefined;
var x25: u1 = undefined;
addcarryxU32(&x24, &x25, x23, x9, x15);
var x26: u32 = undefined;
var x27: u1 = undefined;
addcarryxU32(&x26, &x27, x25, x11, x15);
var x28: u32 = undefined;
var x29: u1 = undefined;
addcarryxU32(&x28, &x29, x27, x13, x15);
out1[0] = x16;
out1[1] = x18;
out1[2] = x20;
out1[3] = x22;
out1[4] = x24;
out1[5] = x26;
out1[6] = x28;
}
/// The function opp negates a field element in the Montgomery domain.
///
/// Preconditions:
/// 0 ≤ eval arg1 < m
/// Postconditions:
/// eval (from_montgomery out1) mod m = -eval (from_montgomery arg1) mod m
/// 0 ≤ eval out1 < m
///
pub fn opp(out1: *MontgomeryDomainFieldElement, arg1: MontgomeryDomainFieldElement) void {
@setRuntimeSafety(mode == .Debug);
var x1: u32 = undefined;
var x2: u1 = undefined;
subborrowxU32(&x1, &x2, 0x0, cast(u32, 0x0), (arg1[0]));
var x3: u32 = undefined;
var x4: u1 = undefined;
subborrowxU32(&x3, &x4, x2, cast(u32, 0x0), (arg1[1]));
var x5: u32 = undefined;
var x6: u1 = undefined;
subborrowxU32(&x5, &x6, x4, cast(u32, 0x0), (arg1[2]));
var x7: u32 = undefined;
var x8: u1 = undefined;
subborrowxU32(&x7, &x8, x6, cast(u32, 0x0), (arg1[3]));
var x9: u32 = undefined;
var x10: u1 = undefined;
subborrowxU32(&x9, &x10, x8, cast(u32, 0x0), (arg1[4]));
var x11: u32 = undefined;
var x12: u1 = undefined;
subborrowxU32(&x11, &x12, x10, cast(u32, 0x0), (arg1[5]));
var x13: u32 = undefined;
var x14: u1 = undefined;
subborrowxU32(&x13, &x14, x12, cast(u32, 0x0), (arg1[6]));
var x15: u32 = undefined;
cmovznzU32(&x15, x14, cast(u32, 0x0), 0xffffffff);
var x16: u32 = undefined;
var x17: u1 = undefined;
addcarryxU32(&x16, &x17, 0x0, x1, cast(u32, cast(u1, (x15 & cast(u32, 0x1)))));
var x18: u32 = undefined;
var x19: u1 = undefined;
addcarryxU32(&x18, &x19, x17, x3, cast(u32, 0x0));
var x20: u32 = undefined;
var x21: u1 = undefined;
addcarryxU32(&x20, &x21, x19, x5, cast(u32, 0x0));
var x22: u32 = undefined;
var x23: u1 = undefined;
addcarryxU32(&x22, &x23, x21, x7, x15);
var x24: u32 = undefined;
var x25: u1 = undefined;
addcarryxU32(&x24, &x25, x23, x9, x15);
var x26: u32 = undefined;
var x27: u1 = undefined;
addcarryxU32(&x26, &x27, x25, x11, x15);
var x28: u32 = undefined;
var x29: u1 = undefined;
addcarryxU32(&x28, &x29, x27, x13, x15);
out1[0] = x16;
out1[1] = x18;
out1[2] = x20;
out1[3] = x22;
out1[4] = x24;
out1[5] = x26;
out1[6] = x28;
}
/// The function fromMontgomery translates a field element out of the Montgomery domain.
///
/// Preconditions:
/// 0 ≤ eval arg1 < m
/// Postconditions:
/// eval out1 mod m = (eval arg1 * ((2^32)⁻¹ mod m)^7) mod m
/// 0 ≤ eval out1 < m
///
pub fn fromMontgomery(out1: *NonMontgomeryDomainFieldElement, arg1: MontgomeryDomainFieldElement) void {
@setRuntimeSafety(mode == .Debug);
const x1 = (arg1[0]);
var x2: u32 = undefined;
var x3: u32 = undefined;
mulxU32(&x2, &x3, x1, 0xffffffff);
var x4: u32 = undefined;
var x5: u32 = undefined;
mulxU32(&x4, &x5, x2, 0xffffffff);
var x6: u32 = undefined;
var x7: u32 = undefined;
mulxU32(&x6, &x7, x2, 0xffffffff);
var x8: u32 = undefined;
var x9: u32 = undefined;
mulxU32(&x8, &x9, x2, 0xffffffff);
var x10: u32 = undefined;
var x11: u32 = undefined;
mulxU32(&x10, &x11, x2, 0xffffffff);
var x12: u32 = undefined;
var x13: u1 = undefined;
addcarryxU32(&x12, &x13, 0x0, x11, x8);
var x14: u32 = undefined;
var x15: u1 = undefined;
addcarryxU32(&x14, &x15, x13, x9, x6);
var x16: u32 = undefined;
var x17: u1 = undefined;
addcarryxU32(&x16, &x17, x15, x7, x4);
var x18: u32 = undefined;
var x19: u1 = undefined;
addcarryxU32(&x18, &x19, 0x0, x1, x2);
var x20: u32 = undefined;
var x21: u1 = undefined;
addcarryxU32(&x20, &x21, 0x0, cast(u32, x19), (arg1[1]));
var x22: u32 = undefined;
var x23: u32 = undefined;
mulxU32(&x22, &x23, x20, 0xffffffff);
var x24: u32 = undefined;
var x25: u32 = undefined;
mulxU32(&x24, &x25, x22, 0xffffffff);
var x26: u32 = undefined;
var x27: u32 = undefined;
mulxU32(&x26, &x27, x22, 0xffffffff);
var x28: u32 = undefined;
var x29: u32 = undefined;
mulxU32(&x28, &x29, x22, 0xffffffff);
var x30: u32 = undefined;
var x31: u32 = undefined;
mulxU32(&x30, &x31, x22, 0xffffffff);
var x32: u32 = undefined;
var x33: u1 = undefined;
addcarryxU32(&x32, &x33, 0x0, x31, x28);
var x34: u32 = undefined;
var x35: u1 = undefined;
addcarryxU32(&x34, &x35, x33, x29, x26);
var x36: u32 = undefined;
var x37: u1 = undefined;
addcarryxU32(&x36, &x37, x35, x27, x24);
var x38: u32 = undefined;
var x39: u1 = undefined;
addcarryxU32(&x38, &x39, 0x0, x12, x30);
var x40: u32 = undefined;
var x41: u1 = undefined;
addcarryxU32(&x40, &x41, x39, x14, x32);
var x42: u32 = undefined;
var x43: u1 = undefined;
addcarryxU32(&x42, &x43, x41, x16, x34);
var x44: u32 = undefined;
var x45: u1 = undefined;
addcarryxU32(&x44, &x45, x43, (cast(u32, x17) + x5), x36);
var x46: u32 = undefined;
var x47: u1 = undefined;
addcarryxU32(&x46, &x47, x45, cast(u32, 0x0), (cast(u32, x37) + x25));
var x48: u32 = undefined;
var x49: u1 = undefined;
addcarryxU32(&x48, &x49, 0x0, x20, x22);
var x50: u32 = undefined;
var x51: u1 = undefined;
addcarryxU32(&x50, &x51, 0x0, (cast(u32, x49) + cast(u32, x21)), (arg1[2]));
var x52: u32 = undefined;
var x53: u1 = undefined;
addcarryxU32(&x52, &x53, x51, x10, cast(u32, 0x0));
var x54: u32 = undefined;
var x55: u1 = undefined;
addcarryxU32(&x54, &x55, x53, x38, cast(u32, 0x0));
var x56: u32 = undefined;
var x57: u1 = undefined;
addcarryxU32(&x56, &x57, x55, x40, cast(u32, 0x0));
var x58: u32 = undefined;
var x59: u1 = undefined;
addcarryxU32(&x58, &x59, x57, x42, cast(u32, 0x0));
var x60: u32 = undefined;
var x61: u1 = undefined;
addcarryxU32(&x60, &x61, x59, x44, cast(u32, 0x0));
var x62: u32 = undefined;
var x63: u1 = undefined;
addcarryxU32(&x62, &x63, x61, x46, cast(u32, 0x0));
var x64: u32 = undefined;
var x65: u32 = undefined;
mulxU32(&x64, &x65, x50, 0xffffffff);
var x66: u32 = undefined;
var x67: u32 = undefined;
mulxU32(&x66, &x67, x64, 0xffffffff);
var x68: u32 = undefined;
var x69: u32 = undefined;
mulxU32(&x68, &x69, x64, 0xffffffff);
var x70: u32 = undefined;
var x71: u32 = undefined;
mulxU32(&x70, &x71, x64, 0xffffffff);
var x72: u32 = undefined;
var x73: u32 = undefined;
mulxU32(&x72, &x73, x64, 0xffffffff);
var x74: u32 = undefined;
var x75: u1 = undefined;
addcarryxU32(&x74, &x75, 0x0, x73, x70);
var x76: u32 = undefined;
var x77: u1 = undefined;
addcarryxU32(&x76, &x77, x75, x71, x68);
var x78: u32 = undefined;
var x79: u1 = undefined;
addcarryxU32(&x78, &x79, x77, x69, x66);
var x80: u32 = undefined;
var x81: u1 = undefined;
addcarryxU32(&x80, &x81, 0x0, x50, x64);
var x82: u32 = undefined;
var x83: u1 = undefined;
addcarryxU32(&x82, &x83, x81, x52, cast(u32, 0x0));
var x84: u32 = undefined;
var x85: u1 = undefined;
addcarryxU32(&x84, &x85, x83, x54, cast(u32, 0x0));
var x86: u32 = undefined;
var x87: u1 = undefined;
addcarryxU32(&x86, &x87, x85, x56, x72);
var x88: u32 = undefined;
var x89: u1 = undefined;
addcarryxU32(&x88, &x89, x87, x58, x74);
var x90: u32 = undefined;
var x91: u1 = undefined;
addcarryxU32(&x90, &x91, x89, x60, x76);
var x92: u32 = undefined;
var x93: u1 = undefined;
addcarryxU32(&x92, &x93, x91, x62, x78);
var x94: u32 = undefined;
var x95: u1 = undefined;
addcarryxU32(&x94, &x95, x93, (cast(u32, x63) + cast(u32, x47)), (cast(u32, x79) + x67));
var x96: u32 = undefined;
var x97: u1 = undefined;
addcarryxU32(&x96, &x97, 0x0, x82, (arg1[3]));
var x98: u32 = undefined;
var x99: u1 = undefined;
addcarryxU32(&x98, &x99, x97, x84, cast(u32, 0x0));
var x100: u32 = undefined;
var x101: u1 = undefined;
addcarryxU32(&x100, &x101, x99, x86, cast(u32, 0x0));
var x102: u32 = undefined;
var x103: u1 = undefined;
addcarryxU32(&x102, &x103, x101, x88, cast(u32, 0x0));
var x104: u32 = undefined;
var x105: u1 = undefined;
addcarryxU32(&x104, &x105, x103, x90, cast(u32, 0x0));
var x106: u32 = undefined;
var x107: u1 = undefined;
addcarryxU32(&x106, &x107, x105, x92, cast(u32, 0x0));
var x108: u32 = undefined;
var x109: u1 = undefined;
addcarryxU32(&x108, &x109, x107, x94, cast(u32, 0x0));
var x110: u32 = undefined;
var x111: u32 = undefined;
mulxU32(&x110, &x111, x96, 0xffffffff);
var x112: u32 = undefined;
var x113: u32 = undefined;
mulxU32(&x112, &x113, x110, 0xffffffff);
var x114: u32 = undefined;
var x115: u32 = undefined;
mulxU32(&x114, &x115, x110, 0xffffffff);
var x116: u32 = undefined;
var x117: u32 = undefined;
mulxU32(&x116, &x117, x110, 0xffffffff);
var x118: u32 = undefined;
var x119: u32 = undefined;
mulxU32(&x118, &x119, x110, 0xffffffff);
var x120: u32 = undefined;
var x121: u1 = undefined;
addcarryxU32(&x120, &x121, 0x0, x119, x116);
var x122: u32 = undefined;
var x123: u1 = undefined;
addcarryxU32(&x122, &x123, x121, x117, x114);
var x124: u32 = undefined;
var x125: u1 = undefined;
addcarryxU32(&x124, &x125, x123, x115, x112);
var x126: u32 = undefined;
var x127: u1 = undefined;
addcarryxU32(&x126, &x127, 0x0, x96, x110);
var x128: u32 = undefined;
var x129: u1 = undefined;
addcarryxU32(&x128, &x129, x127, x98, cast(u32, 0x0));
var x130: u32 = undefined;
var x131: u1 = undefined;
addcarryxU32(&x130, &x131, x129, x100, cast(u32, 0x0));
var x132: u32 = undefined;
var x133: u1 = undefined;
addcarryxU32(&x132, &x133, x131, x102, x118);
var x134: u32 = undefined;
var x135: u1 = undefined;
addcarryxU32(&x134, &x135, x133, x104, x120);
var x136: u32 = undefined;
var x137: u1 = undefined;
addcarryxU32(&x136, &x137, x135, x106, x122);
var x138: u32 = undefined;
var x139: u1 = undefined;
addcarryxU32(&x138, &x139, x137, x108, x124);
var x140: u32 = undefined;
var x141: u1 = undefined;
addcarryxU32(&x140, &x141, x139, (cast(u32, x109) + cast(u32, x95)), (cast(u32, x125) + x113));
var x142: u32 = undefined;
var x143: u1 = undefined;
addcarryxU32(&x142, &x143, 0x0, x128, (arg1[4]));
var x144: u32 = undefined;
var x145: u1 = undefined;
addcarryxU32(&x144, &x145, x143, x130, cast(u32, 0x0));
var x146: u32 = undefined;
var x147: u1 = undefined;
addcarryxU32(&x146, &x147, x145, x132, cast(u32, 0x0));
var x148: u32 = undefined;
var x149: u1 = undefined;
addcarryxU32(&x148, &x149, x147, x134, cast(u32, 0x0));
var x150: u32 = undefined;
var x151: u1 = undefined;
addcarryxU32(&x150, &x151, x149, x136, cast(u32, 0x0));
var x152: u32 = undefined;
var x153: u1 = undefined;
addcarryxU32(&x152, &x153, x151, x138, cast(u32, 0x0));
var x154: u32 = undefined;
var x155: u1 = undefined;
addcarryxU32(&x154, &x155, x153, x140, cast(u32, 0x0));
var x156: u32 = undefined;
var x157: u32 = undefined;
mulxU32(&x156, &x157, x142, 0xffffffff);
var x158: u32 = undefined;
var x159: u32 = undefined;
mulxU32(&x158, &x159, x156, 0xffffffff);
var x160: u32 = undefined;
var x161: u32 = undefined;
mulxU32(&x160, &x161, x156, 0xffffffff);
var x162: u32 = undefined;
var x163: u32 = undefined;
mulxU32(&x162, &x163, x156, 0xffffffff);
var x164: u32 = undefined;
var x165: u32 = undefined;
mulxU32(&x164, &x165, x156, 0xffffffff);
var x166: u32 = undefined;
var x167: u1 = undefined;
addcarryxU32(&x166, &x167, 0x0, x165, x162);
var x168: u32 = undefined;
var x169: u1 = undefined;
addcarryxU32(&x168, &x169, x167, x163, x160);
var x170: u32 = undefined;
var x171: u1 = undefined;
addcarryxU32(&x170, &x171, x169, x161, x158);
var x172: u32 = undefined;
var x173: u1 = undefined;
addcarryxU32(&x172, &x173, 0x0, x142, x156);
var x174: u32 = undefined;
var x175: u1 = undefined;
addcarryxU32(&x174, &x175, x173, x144, cast(u32, 0x0));
var x176: u32 = undefined;
var x177: u1 = undefined;
addcarryxU32(&x176, &x177, x175, x146, cast(u32, 0x0));
var x178: u32 = undefined;
var x179: u1 = undefined;
addcarryxU32(&x178, &x179, x177, x148, x164);
var x180: u32 = undefined;
var x181: u1 = undefined;
addcarryxU32(&x180, &x181, x179, x150, x166);
var x182: u32 = undefined;
var x183: u1 = undefined;
addcarryxU32(&x182, &x183, x181, x152, x168);
var x184: u32 = undefined;
var x185: u1 = undefined;
addcarryxU32(&x184, &x185, x183, x154, x170);
var x186: u32 = undefined;
var x187: u1 = undefined;
addcarryxU32(&x186, &x187, x185, (cast(u32, x155) + cast(u32, x141)), (cast(u32, x171) + x159));
var x188: u32 = undefined;
var x189: u1 = undefined;
addcarryxU32(&x188, &x189, 0x0, x174, (arg1[5]));
var x190: u32 = undefined;
var x191: u1 = undefined;
addcarryxU32(&x190, &x191, x189, x176, cast(u32, 0x0));
var x192: u32 = undefined;
var x193: u1 = undefined;
addcarryxU32(&x192, &x193, x191, x178, cast(u32, 0x0));
var x194: u32 = undefined;
var x195: u1 = undefined;
addcarryxU32(&x194, &x195, x193, x180, cast(u32, 0x0));
var x196: u32 = undefined;
var x197: u1 = undefined;
addcarryxU32(&x196, &x197, x195, x182, cast(u32, 0x0));
var x198: u32 = undefined;
var x199: u1 = undefined;
addcarryxU32(&x198, &x199, x197, x184, cast(u32, 0x0));
var x200: u32 = undefined;
var x201: u1 = undefined;
addcarryxU32(&x200, &x201, x199, x186, cast(u32, 0x0));
var x202: u32 = undefined;
var x203: u32 = undefined;
mulxU32(&x202, &x203, x188, 0xffffffff);
var x204: u32 = undefined;
var x205: u32 = undefined;
mulxU32(&x204, &x205, x202, 0xffffffff);
var x206: u32 = undefined;
var x207: u32 = undefined;
mulxU32(&x206, &x207, x202, 0xffffffff);
var x208: u32 = undefined;
var x209: u32 = undefined;
mulxU32(&x208, &x209, x202, 0xffffffff);
var x210: u32 = undefined;
var x211: u32 = undefined;
mulxU32(&x210, &x211, x202, 0xffffffff);
var x212: u32 = undefined;
var x213: u1 = undefined;
addcarryxU32(&x212, &x213, 0x0, x211, x208);
var x214: u32 = undefined;
var x215: u1 = undefined;
addcarryxU32(&x214, &x215, x213, x209, x206);
var x216: u32 = undefined;
var x217: u1 = undefined;
addcarryxU32(&x216, &x217, x215, x207, x204);
var x218: u32 = undefined;
var x219: u1 = undefined;
addcarryxU32(&x218, &x219, 0x0, x188, x202);
var x220: u32 = undefined;
var x221: u1 = undefined;
addcarryxU32(&x220, &x221, x219, x190, cast(u32, 0x0));
var x222: u32 = undefined;
var x223: u1 = undefined;
addcarryxU32(&x222, &x223, x221, x192, cast(u32, 0x0));
var x224: u32 = undefined;
var x225: u1 = undefined;
addcarryxU32(&x224, &x225, x223, x194, x210);
var x226: u32 = undefined;
var x227: u1 = undefined;
addcarryxU32(&x226, &x227, x225, x196, x212);
var x228: u32 = undefined;
var x229: u1 = undefined;
addcarryxU32(&x228, &x229, x227, x198, x214);
var x230: u32 = undefined;
var x231: u1 = undefined;
addcarryxU32(&x230, &x231, x229, x200, x216);
var x232: u32 = undefined;
var x233: u1 = undefined;
addcarryxU32(&x232, &x233, x231, (cast(u32, x201) + cast(u32, x187)), (cast(u32, x217) + x205));
var x234: u32 = undefined;
var x235: u1 = undefined;
addcarryxU32(&x234, &x235, 0x0, x220, (arg1[6]));
var x236: u32 = undefined;
var x237: u1 = undefined;
addcarryxU32(&x236, &x237, x235, x222, cast(u32, 0x0));
var x238: u32 = undefined;
var x239: u1 = undefined;
addcarryxU32(&x238, &x239, x237, x224, cast(u32, 0x0));
var x240: u32 = undefined;
var x241: u1 = undefined;
addcarryxU32(&x240, &x241, x239, x226, cast(u32, 0x0));
var x242: u32 = undefined;
var x243: u1 = undefined;
addcarryxU32(&x242, &x243, x241, x228, cast(u32, 0x0));
var x244: u32 = undefined;
var x245: u1 = undefined;
addcarryxU32(&x244, &x245, x243, x230, cast(u32, 0x0));
var x246: u32 = undefined;
var x247: u1 = undefined;
addcarryxU32(&x246, &x247, x245, x232, cast(u32, 0x0));
var x248: u32 = undefined;
var x249: u32 = undefined;
mulxU32(&x248, &x249, x234, 0xffffffff);
var x250: u32 = undefined;
var x251: u32 = undefined;
mulxU32(&x250, &x251, x248, 0xffffffff);
var x252: u32 = undefined;
var x253: u32 = undefined;
mulxU32(&x252, &x253, x248, 0xffffffff);
var x254: u32 = undefined;
var x255: u32 = undefined;
mulxU32(&x254, &x255, x248, 0xffffffff);
var x256: u32 = undefined;
var x257: u32 = undefined;
mulxU32(&x256, &x257, x248, 0xffffffff);
var x258: u32 = undefined;
var x259: u1 = undefined;
addcarryxU32(&x258, &x259, 0x0, x257, x254);
var x260: u32 = undefined;
var x261: u1 = undefined;
addcarryxU32(&x260, &x261, x259, x255, x252);
var x262: u32 = undefined;
var x263: u1 = undefined;
addcarryxU32(&x262, &x263, x261, x253, x250);
var x264: u32 = undefined;
var x265: u1 = undefined;
addcarryxU32(&x264, &x265, 0x0, x234, x248);
var x266: u32 = undefined;
var x267: u1 = undefined;
addcarryxU32(&x266, &x267, x265, x236, cast(u32, 0x0));
var x268: u32 = undefined;
var x269: u1 = undefined;
addcarryxU32(&x268, &x269, x267, x238, cast(u32, 0x0));
var x270: u32 = undefined;
var x271: u1 = undefined;
addcarryxU32(&x270, &x271, x269, x240, x256);
var x272: u32 = undefined;
var x273: u1 = undefined;
addcarryxU32(&x272, &x273, x271, x242, x258);
var x274: u32 = undefined;
var x275: u1 = undefined;
addcarryxU32(&x274, &x275, x273, x244, x260);
var x276: u32 = undefined;
var x277: u1 = undefined;
addcarryxU32(&x276, &x277, x275, x246, x262);
var x278: u32 = undefined;
var x279: u1 = undefined;
addcarryxU32(&x278, &x279, x277, (cast(u32, x247) + cast(u32, x233)), (cast(u32, x263) + x251));
var x280: u32 = undefined;
var x281: u1 = undefined;
subborrowxU32(&x280, &x281, 0x0, x266, cast(u32, 0x1));
var x282: u32 = undefined;
var x283: u1 = undefined;
subborrowxU32(&x282, &x283, x281, x268, cast(u32, 0x0));
var x284: u32 = undefined;
var x285: u1 = undefined;
subborrowxU32(&x284, &x285, x283, x270, cast(u32, 0x0));
var x286: u32 = undefined;
var x287: u1 = undefined;
subborrowxU32(&x286, &x287, x285, x272, 0xffffffff);
var x288: u32 = undefined;
var x289: u1 = undefined;
subborrowxU32(&x288, &x289, x287, x274, 0xffffffff);
var x290: u32 = undefined;
var x291: u1 = undefined;
subborrowxU32(&x290, &x291, x289, x276, 0xffffffff);
var x292: u32 = undefined;
var x293: u1 = undefined;
subborrowxU32(&x292, &x293, x291, x278, 0xffffffff);
var x294: u32 = undefined;
var x295: u1 = undefined;
subborrowxU32(&x294, &x295, x293, cast(u32, x279), cast(u32, 0x0));
var x296: u32 = undefined;
cmovznzU32(&x296, x295, x280, x266);
var x297: u32 = undefined;
cmovznzU32(&x297, x295, x282, x268);
var x298: u32 = undefined;
cmovznzU32(&x298, x295, x284, x270);
var x299: u32 = undefined;
cmovznzU32(&x299, x295, x286, x272);
var x300: u32 = undefined;
cmovznzU32(&x300, x295, x288, x274);
var x301: u32 = undefined;
cmovznzU32(&x301, x295, x290, x276);
var x302: u32 = undefined;
cmovznzU32(&x302, x295, x292, x278);
out1[0] = x296;
out1[1] = x297;
out1[2] = x298;
out1[3] = x299;
out1[4] = x300;
out1[5] = x301;
out1[6] = x302;
}
/// The function toMontgomery translates a field element into the Montgomery domain.
///
/// Preconditions:
/// 0 ≤ eval arg1 < m
/// Postconditions:
/// eval (from_montgomery out1) mod m = eval arg1 mod m
/// 0 ≤ eval out1 < m
///
pub fn toMontgomery(out1: *MontgomeryDomainFieldElement, arg1: NonMontgomeryDomainFieldElement) void {
@setRuntimeSafety(mode == .Debug);
const x1 = (arg1[1]);
const x2 = (arg1[2]);
const x3 = (arg1[3]);
const x4 = (arg1[4]);
const x5 = (arg1[5]);
const x6 = (arg1[6]);
const x7 = (arg1[0]);
var x8: u32 = undefined;
var x9: u32 = undefined;
mulxU32(&x8, &x9, x7, 0xffffffff);
var x10: u32 = undefined;
var x11: u32 = undefined;
mulxU32(&x10, &x11, x7, 0xffffffff);
var x12: u32 = undefined;
var x13: u32 = undefined;
mulxU32(&x12, &x13, x7, 0xfffffffe);
var x14: u32 = undefined;
var x15: u1 = undefined;
addcarryxU32(&x14, &x15, 0x0, x13, x10);
var x16: u32 = undefined;
var x17: u1 = undefined;
addcarryxU32(&x16, &x17, x15, x11, x8);
var x18: u32 = undefined;
var x19: u32 = undefined;
mulxU32(&x18, &x19, x7, 0xffffffff);
var x20: u32 = undefined;
var x21: u32 = undefined;
mulxU32(&x20, &x21, x18, 0xffffffff);
var x22: u32 = undefined;
var x23: u32 = undefined;
mulxU32(&x22, &x23, x18, 0xffffffff);
var x24: u32 = undefined;
var x25: u32 = undefined;
mulxU32(&x24, &x25, x18, 0xffffffff);
var x26: u32 = undefined;
var x27: u32 = undefined;
mulxU32(&x26, &x27, x18, 0xffffffff);
var x28: u32 = undefined;
var x29: u1 = undefined;
addcarryxU32(&x28, &x29, 0x0, x27, x24);
var x30: u32 = undefined;
var x31: u1 = undefined;
addcarryxU32(&x30, &x31, x29, x25, x22);
var x32: u32 = undefined;
var x33: u1 = undefined;
addcarryxU32(&x32, &x33, x31, x23, x20);
var x34: u32 = undefined;
var x35: u1 = undefined;
addcarryxU32(&x34, &x35, 0x0, x12, x26);
var x36: u32 = undefined;
var x37: u1 = undefined;
addcarryxU32(&x36, &x37, x35, x14, x28);
var x38: u32 = undefined;
var x39: u1 = undefined;
addcarryxU32(&x38, &x39, x37, x16, x30);
var x40: u32 = undefined;
var x41: u1 = undefined;
addcarryxU32(&x40, &x41, x39, (cast(u32, x17) + x9), x32);
var x42: u32 = undefined;
var x43: u1 = undefined;
addcarryxU32(&x42, &x43, x41, cast(u32, 0x0), (cast(u32, x33) + x21));
var x44: u32 = undefined;
var x45: u32 = undefined;
mulxU32(&x44, &x45, x1, 0xffffffff);
var x46: u32 = undefined;
var x47: u32 = undefined;
mulxU32(&x46, &x47, x1, 0xffffffff);
var x48: u32 = undefined;
var x49: u32 = undefined;
mulxU32(&x48, &x49, x1, 0xfffffffe);
var x50: u32 = undefined;
var x51: u1 = undefined;
addcarryxU32(&x50, &x51, 0x0, x49, x46);
var x52: u32 = undefined;
var x53: u1 = undefined;
addcarryxU32(&x52, &x53, x51, x47, x44);
var x54: u32 = undefined;
var x55: u1 = undefined;
addcarryxU32(&x54, &x55, 0x0, x7, x18);
var x56: u32 = undefined;
var x57: u1 = undefined;
addcarryxU32(&x56, &x57, 0x0, cast(u32, x55), x1);
var x58: u32 = undefined;
var x59: u1 = undefined;
addcarryxU32(&x58, &x59, 0x0, x36, x48);
var x60: u32 = undefined;
var x61: u1 = undefined;
addcarryxU32(&x60, &x61, x59, x38, x50);
var x62: u32 = undefined;
var x63: u1 = undefined;
addcarryxU32(&x62, &x63, x61, x40, x52);
var x64: u32 = undefined;
var x65: u1 = undefined;
addcarryxU32(&x64, &x65, x63, x42, (cast(u32, x53) + x45));
var x66: u32 = undefined;
var x67: u32 = undefined;
mulxU32(&x66, &x67, x56, 0xffffffff);
var x68: u32 = undefined;
var x69: u32 = undefined;
mulxU32(&x68, &x69, x66, 0xffffffff);
var x70: u32 = undefined;
var x71: u32 = undefined;
mulxU32(&x70, &x71, x66, 0xffffffff);
var x72: u32 = undefined;
var x73: u32 = undefined;
mulxU32(&x72, &x73, x66, 0xffffffff);
var x74: u32 = undefined;
var x75: u32 = undefined;
mulxU32(&x74, &x75, x66, 0xffffffff);
var x76: u32 = undefined;
var x77: u1 = undefined;
addcarryxU32(&x76, &x77, 0x0, x75, x72);
var x78: u32 = undefined;
var x79: u1 = undefined;
addcarryxU32(&x78, &x79, x77, x73, x70);
var x80: u32 = undefined;
var x81: u1 = undefined;
addcarryxU32(&x80, &x81, x79, x71, x68);
var x82: u32 = undefined;
var x83: u1 = undefined;
addcarryxU32(&x82, &x83, 0x0, x58, x74);
var x84: u32 = undefined;
var x85: u1 = undefined;
addcarryxU32(&x84, &x85, x83, x60, x76);
var x86: u32 = undefined;
var x87: u1 = undefined;
addcarryxU32(&x86, &x87, x85, x62, x78);
var x88: u32 = undefined;
var x89: u1 = undefined;
addcarryxU32(&x88, &x89, x87, x64, x80);
var x90: u32 = undefined;
var x91: u1 = undefined;
addcarryxU32(&x90, &x91, x89, (cast(u32, x65) + cast(u32, x43)), (cast(u32, x81) + x69));
var x92: u32 = undefined;
var x93: u32 = undefined;
mulxU32(&x92, &x93, x2, 0xffffffff);
var x94: u32 = undefined;
var x95: u32 = undefined;
mulxU32(&x94, &x95, x2, 0xffffffff);
var x96: u32 = undefined;
var x97: u32 = undefined;
mulxU32(&x96, &x97, x2, 0xfffffffe);
var x98: u32 = undefined;
var x99: u1 = undefined;
addcarryxU32(&x98, &x99, 0x0, x97, x94);
var x100: u32 = undefined;
var x101: u1 = undefined;
addcarryxU32(&x100, &x101, x99, x95, x92);
var x102: u32 = undefined;
var x103: u1 = undefined;
addcarryxU32(&x102, &x103, 0x0, x56, x66);
var x104: u32 = undefined;
var x105: u1 = undefined;
addcarryxU32(&x104, &x105, 0x0, (cast(u32, x103) + cast(u32, x57)), x2);
var x106: u32 = undefined;
var x107: u1 = undefined;
addcarryxU32(&x106, &x107, x105, x34, cast(u32, 0x0));
var x108: u32 = undefined;
var x109: u1 = undefined;
addcarryxU32(&x108, &x109, x107, x82, cast(u32, 0x0));
var x110: u32 = undefined;
var x111: u1 = undefined;
addcarryxU32(&x110, &x111, x109, x84, x96);
var x112: u32 = undefined;
var x113: u1 = undefined;
addcarryxU32(&x112, &x113, x111, x86, x98);
var x114: u32 = undefined;
var x115: u1 = undefined;
addcarryxU32(&x114, &x115, x113, x88, x100);
var x116: u32 = undefined;
var x117: u1 = undefined;
addcarryxU32(&x116, &x117, x115, x90, (cast(u32, x101) + x93));
var x118: u32 = undefined;
var x119: u32 = undefined;
mulxU32(&x118, &x119, x104, 0xffffffff);
var x120: u32 = undefined;
var x121: u32 = undefined;
mulxU32(&x120, &x121, x118, 0xffffffff);
var x122: u32 = undefined;
var x123: u32 = undefined;
mulxU32(&x122, &x123, x118, 0xffffffff);
var x124: u32 = undefined;
var x125: u32 = undefined;
mulxU32(&x124, &x125, x118, 0xffffffff);
var x126: u32 = undefined;
var x127: u32 = undefined;
mulxU32(&x126, &x127, x118, 0xffffffff);
var x128: u32 = undefined;
var x129: u1 = undefined;
addcarryxU32(&x128, &x129, 0x0, x127, x124);
var x130: u32 = undefined;
var x131: u1 = undefined;
addcarryxU32(&x130, &x131, x129, x125, x122);
var x132: u32 = undefined;
var x133: u1 = undefined;
addcarryxU32(&x132, &x133, x131, x123, x120);
var x134: u32 = undefined;
var x135: u1 = undefined;
addcarryxU32(&x134, &x135, 0x0, x104, x118);
var x136: u32 = undefined;
var x137: u1 = undefined;
addcarryxU32(&x136, &x137, x135, x106, cast(u32, 0x0));
var x138: u32 = undefined;
var x139: u1 = undefined;
addcarryxU32(&x138, &x139, x137, x108, cast(u32, 0x0));
var x140: u32 = undefined;
var x141: u1 = undefined;
addcarryxU32(&x140, &x141, x139, x110, x126);
var x142: u32 = undefined;
var x143: u1 = undefined;
addcarryxU32(&x142, &x143, x141, x112, x128);
var x144: u32 = undefined;
var x145: u1 = undefined;
addcarryxU32(&x144, &x145, x143, x114, x130);
var x146: u32 = undefined;
var x147: u1 = undefined;
addcarryxU32(&x146, &x147, x145, x116, x132);
var x148: u32 = undefined;
var x149: u1 = undefined;
addcarryxU32(&x148, &x149, x147, (cast(u32, x117) + cast(u32, x91)), (cast(u32, x133) + x121));
var x150: u32 = undefined;
var x151: u32 = undefined;
mulxU32(&x150, &x151, x3, 0xffffffff);
var x152: u32 = undefined;
var x153: u32 = undefined;
mulxU32(&x152, &x153, x3, 0xffffffff);
var x154: u32 = undefined;
var x155: u32 = undefined;
mulxU32(&x154, &x155, x3, 0xfffffffe);
var x156: u32 = undefined;
var x157: u1 = undefined;
addcarryxU32(&x156, &x157, 0x0, x155, x152);
var x158: u32 = undefined;
var x159: u1 = undefined;
addcarryxU32(&x158, &x159, x157, x153, x150);
var x160: u32 = undefined;
var x161: u1 = undefined;
addcarryxU32(&x160, &x161, 0x0, x136, x3);
var x162: u32 = undefined;
var x163: u1 = undefined;
addcarryxU32(&x162, &x163, x161, x138, cast(u32, 0x0));
var x164: u32 = undefined;
var x165: u1 = undefined;
addcarryxU32(&x164, &x165, x163, x140, cast(u32, 0x0));
var x166: u32 = undefined;
var x167: u1 = undefined;
addcarryxU32(&x166, &x167, x165, x142, x154);
var x168: u32 = undefined;
var x169: u1 = undefined;
addcarryxU32(&x168, &x169, x167, x144, x156);
var x170: u32 = undefined;
var x171: u1 = undefined;
addcarryxU32(&x170, &x171, x169, x146, x158);
var x172: u32 = undefined;
var x173: u1 = undefined;
addcarryxU32(&x172, &x173, x171, x148, (cast(u32, x159) + x151));
var x174: u32 = undefined;
var x175: u32 = undefined;
mulxU32(&x174, &x175, x160, 0xffffffff);
var x176: u32 = undefined;
var x177: u32 = undefined;
mulxU32(&x176, &x177, x174, 0xffffffff);
var x178: u32 = undefined;
var x179: u32 = undefined;
mulxU32(&x178, &x179, x174, 0xffffffff);
var x180: u32 = undefined;
var x181: u32 = undefined;
mulxU32(&x180, &x181, x174, 0xffffffff);
var x182: u32 = undefined;
var x183: u32 = undefined;
mulxU32(&x182, &x183, x174, 0xffffffff);
var x184: u32 = undefined;
var x185: u1 = undefined;
addcarryxU32(&x184, &x185, 0x0, x183, x180);
var x186: u32 = undefined;
var x187: u1 = undefined;
addcarryxU32(&x186, &x187, x185, x181, x178);
var x188: u32 = undefined;
var x189: u1 = undefined;
addcarryxU32(&x188, &x189, x187, x179, x176);
var x190: u32 = undefined;
var x191: u1 = undefined;
addcarryxU32(&x190, &x191, 0x0, x160, x174);
var x192: u32 = undefined;
var x193: u1 = undefined;
addcarryxU32(&x192, &x193, x191, x162, cast(u32, 0x0));
var x194: u32 = undefined;
var x195: u1 = undefined;
addcarryxU32(&x194, &x195, x193, x164, cast(u32, 0x0));
var x196: u32 = undefined;
var x197: u1 = undefined;
addcarryxU32(&x196, &x197, x195, x166, x182);
var x198: u32 = undefined;
var x199: u1 = undefined;
addcarryxU32(&x198, &x199, x197, x168, x184);
var x200: u32 = undefined;
var x201: u1 = undefined;
addcarryxU32(&x200, &x201, x199, x170, x186);
var x202: u32 = undefined;
var x203: u1 = undefined;
addcarryxU32(&x202, &x203, x201, x172, x188);
var x204: u32 = undefined;
var x205: u1 = undefined;
addcarryxU32(&x204, &x205, x203, (cast(u32, x173) + cast(u32, x149)), (cast(u32, x189) + x177));
var x206: u32 = undefined;
var x207: u32 = undefined;
mulxU32(&x206, &x207, x4, 0xffffffff);
var x208: u32 = undefined;
var x209: u32 = undefined;
mulxU32(&x208, &x209, x4, 0xffffffff);
var x210: u32 = undefined;
var x211: u32 = undefined;
mulxU32(&x210, &x211, x4, 0xfffffffe);
var x212: u32 = undefined;
var x213: u1 = undefined;
addcarryxU32(&x212, &x213, 0x0, x211, x208);
var x214: u32 = undefined;
var x215: u1 = undefined;
addcarryxU32(&x214, &x215, x213, x209, x206);
var x216: u32 = undefined;
var x217: u1 = undefined;
addcarryxU32(&x216, &x217, 0x0, x192, x4);
var x218: u32 = undefined;
var x219: u1 = undefined;
addcarryxU32(&x218, &x219, x217, x194, cast(u32, 0x0));
var x220: u32 = undefined;
var x221: u1 = undefined;
addcarryxU32(&x220, &x221, x219, x196, cast(u32, 0x0));
var x222: u32 = undefined;
var x223: u1 = undefined;
addcarryxU32(&x222, &x223, x221, x198, x210);
var x224: u32 = undefined;
var x225: u1 = undefined;
addcarryxU32(&x224, &x225, x223, x200, x212);
var x226: u32 = undefined;
var x227: u1 = undefined;
addcarryxU32(&x226, &x227, x225, x202, x214);
var x228: u32 = undefined;
var x229: u1 = undefined;
addcarryxU32(&x228, &x229, x227, x204, (cast(u32, x215) + x207));
var x230: u32 = undefined;
var x231: u32 = undefined;
mulxU32(&x230, &x231, x216, 0xffffffff);
var x232: u32 = undefined;
var x233: u32 = undefined;
mulxU32(&x232, &x233, x230, 0xffffffff);
var x234: u32 = undefined;
var x235: u32 = undefined;
mulxU32(&x234, &x235, x230, 0xffffffff);
var x236: u32 = undefined;
var x237: u32 = undefined;
mulxU32(&x236, &x237, x230, 0xffffffff);
var x238: u32 = undefined;
var x239: u32 = undefined;
mulxU32(&x238, &x239, x230, 0xffffffff);
var x240: u32 = undefined;
var x241: u1 = undefined;
addcarryxU32(&x240, &x241, 0x0, x239, x236);
var x242: u32 = undefined;
var x243: u1 = undefined;
addcarryxU32(&x242, &x243, x241, x237, x234);
var x244: u32 = undefined;
var x245: u1 = undefined;
addcarryxU32(&x244, &x245, x243, x235, x232);
var x246: u32 = undefined;
var x247: u1 = undefined;
addcarryxU32(&x246, &x247, 0x0, x216, x230);
var x248: u32 = undefined;
var x249: u1 = undefined;
addcarryxU32(&x248, &x249, x247, x218, cast(u32, 0x0));
var x250: u32 = undefined;
var x251: u1 = undefined;
addcarryxU32(&x250, &x251, x249, x220, cast(u32, 0x0));
var x252: u32 = undefined;
var x253: u1 = undefined;
addcarryxU32(&x252, &x253, x251, x222, x238);
var x254: u32 = undefined;
var x255: u1 = undefined;
addcarryxU32(&x254, &x255, x253, x224, x240);
var x256: u32 = undefined;
var x257: u1 = undefined;
addcarryxU32(&x256, &x257, x255, x226, x242);
var x258: u32 = undefined;
var x259: u1 = undefined;
addcarryxU32(&x258, &x259, x257, x228, x244);
var x260: u32 = undefined;
var x261: u1 = undefined;
addcarryxU32(&x260, &x261, x259, (cast(u32, x229) + cast(u32, x205)), (cast(u32, x245) + x233));
var x262: u32 = undefined;
var x263: u32 = undefined;
mulxU32(&x262, &x263, x5, 0xffffffff);
var x264: u32 = undefined;
var x265: u32 = undefined;
mulxU32(&x264, &x265, x5, 0xffffffff);
var x266: u32 = undefined;
var x267: u32 = undefined;
mulxU32(&x266, &x267, x5, 0xfffffffe);
var x268: u32 = undefined;
var x269: u1 = undefined;
addcarryxU32(&x268, &x269, 0x0, x267, x264);
var x270: u32 = undefined;
var x271: u1 = undefined;
addcarryxU32(&x270, &x271, x269, x265, x262);
var x272: u32 = undefined;
var x273: u1 = undefined;
addcarryxU32(&x272, &x273, 0x0, x248, x5);
var x274: u32 = undefined;
var x275: u1 = undefined;
addcarryxU32(&x274, &x275, x273, x250, cast(u32, 0x0));
var x276: u32 = undefined;
var x277: u1 = undefined;
addcarryxU32(&x276, &x277, x275, x252, cast(u32, 0x0));
var x278: u32 = undefined;
var x279: u1 = undefined;
addcarryxU32(&x278, &x279, x277, x254, x266);
var x280: u32 = undefined;
var x281: u1 = undefined;
addcarryxU32(&x280, &x281, x279, x256, x268);
var x282: u32 = undefined;
var x283: u1 = undefined;
addcarryxU32(&x282, &x283, x281, x258, x270);
var x284: u32 = undefined;
var x285: u1 = undefined;
addcarryxU32(&x284, &x285, x283, x260, (cast(u32, x271) + x263));
var x286: u32 = undefined;
var x287: u32 = undefined;
mulxU32(&x286, &x287, x272, 0xffffffff);
var x288: u32 = undefined;
var x289: u32 = undefined;
mulxU32(&x288, &x289, x286, 0xffffffff);
var x290: u32 = undefined;
var x291: u32 = undefined;
mulxU32(&x290, &x291, x286, 0xffffffff);
var x292: u32 = undefined;
var x293: u32 = undefined;
mulxU32(&x292, &x293, x286, 0xffffffff);
var x294: u32 = undefined;
var x295: u32 = undefined;
mulxU32(&x294, &x295, x286, 0xffffffff);
var x296: u32 = undefined;
var x297: u1 = undefined;
addcarryxU32(&x296, &x297, 0x0, x295, x292);
var x298: u32 = undefined;
var x299: u1 = undefined;
addcarryxU32(&x298, &x299, x297, x293, x290);
var x300: u32 = undefined;
var x301: u1 = undefined;
addcarryxU32(&x300, &x301, x299, x291, x288);
var x302: u32 = undefined;
var x303: u1 = undefined;
addcarryxU32(&x302, &x303, 0x0, x272, x286);
var x304: u32 = undefined;
var x305: u1 = undefined;
addcarryxU32(&x304, &x305, x303, x274, cast(u32, 0x0));
var x306: u32 = undefined;
var x307: u1 = undefined;
addcarryxU32(&x306, &x307, x305, x276, cast(u32, 0x0));
var x308: u32 = undefined;
var x309: u1 = undefined;
addcarryxU32(&x308, &x309, x307, x278, x294);
var x310: u32 = undefined;
var x311: u1 = undefined;
addcarryxU32(&x310, &x311, x309, x280, x296);
var x312: u32 = undefined;
var x313: u1 = undefined;
addcarryxU32(&x312, &x313, x311, x282, x298);
var x314: u32 = undefined;
var x315: u1 = undefined;
addcarryxU32(&x314, &x315, x313, x284, x300);
var x316: u32 = undefined;
var x317: u1 = undefined;
addcarryxU32(&x316, &x317, x315, (cast(u32, x285) + cast(u32, x261)), (cast(u32, x301) + x289));
var x318: u32 = undefined;
var x319: u32 = undefined;
mulxU32(&x318, &x319, x6, 0xffffffff);
var x320: u32 = undefined;
var x321: u32 = undefined;
mulxU32(&x320, &x321, x6, 0xffffffff);
var x322: u32 = undefined;
var x323: u32 = undefined;
mulxU32(&x322, &x323, x6, 0xfffffffe);
var x324: u32 = undefined;
var x325: u1 = undefined;
addcarryxU32(&x324, &x325, 0x0, x323, x320);
var x326: u32 = undefined;
var x327: u1 = undefined;
addcarryxU32(&x326, &x327, x325, x321, x318);
var x328: u32 = undefined;
var x329: u1 = undefined;
addcarryxU32(&x328, &x329, 0x0, x304, x6);
var x330: u32 = undefined;
var x331: u1 = undefined;
addcarryxU32(&x330, &x331, x329, x306, cast(u32, 0x0));
var x332: u32 = undefined;
var x333: u1 = undefined;
addcarryxU32(&x332, &x333, x331, x308, cast(u32, 0x0));
var x334: u32 = undefined;
var x335: u1 = undefined;
addcarryxU32(&x334, &x335, x333, x310, x322);
var x336: u32 = undefined;
var x337: u1 = undefined;
addcarryxU32(&x336, &x337, x335, x312, x324);
var x338: u32 = undefined;
var x339: u1 = undefined;
addcarryxU32(&x338, &x339, x337, x314, x326);
var x340: u32 = undefined;
var x341: u1 = undefined;
addcarryxU32(&x340, &x341, x339, x316, (cast(u32, x327) + x319));
var x342: u32 = undefined;
var x343: u32 = undefined;
mulxU32(&x342, &x343, x328, 0xffffffff);
var x344: u32 = undefined;
var x345: u32 = undefined;
mulxU32(&x344, &x345, x342, 0xffffffff);
var x346: u32 = undefined;
var x347: u32 = undefined;
mulxU32(&x346, &x347, x342, 0xffffffff);
var x348: u32 = undefined;
var x349: u32 = undefined;
mulxU32(&x348, &x349, x342, 0xffffffff);
var x350: u32 = undefined;
var x351: u32 = undefined;
mulxU32(&x350, &x351, x342, 0xffffffff);
var x352: u32 = undefined;
var x353: u1 = undefined;
addcarryxU32(&x352, &x353, 0x0, x351, x348);
var x354: u32 = undefined;
var x355: u1 = undefined;
addcarryxU32(&x354, &x355, x353, x349, x346);
var x356: u32 = undefined;
var x357: u1 = undefined;
addcarryxU32(&x356, &x357, x355, x347, x344);
var x358: u32 = undefined;
var x359: u1 = undefined;
addcarryxU32(&x358, &x359, 0x0, x328, x342);
var x360: u32 = undefined;
var x361: u1 = undefined;
addcarryxU32(&x360, &x361, x359, x330, cast(u32, 0x0));
var x362: u32 = undefined;
var x363: u1 = undefined;
addcarryxU32(&x362, &x363, x361, x332, cast(u32, 0x0));
var x364: u32 = undefined;
var x365: u1 = undefined;
addcarryxU32(&x364, &x365, x363, x334, x350);
var x366: u32 = undefined;
var x367: u1 = undefined;
addcarryxU32(&x366, &x367, x365, x336, x352);
var x368: u32 = undefined;
var x369: u1 = undefined;
addcarryxU32(&x368, &x369, x367, x338, x354);
var x370: u32 = undefined;
var x371: u1 = undefined;
addcarryxU32(&x370, &x371, x369, x340, x356);
var x372: u32 = undefined;
var x373: u1 = undefined;
addcarryxU32(&x372, &x373, x371, (cast(u32, x341) + cast(u32, x317)), (cast(u32, x357) + x345));
var x374: u32 = undefined;
var x375: u1 = undefined;
subborrowxU32(&x374, &x375, 0x0, x360, cast(u32, 0x1));
var x376: u32 = undefined;
var x377: u1 = undefined;
subborrowxU32(&x376, &x377, x375, x362, cast(u32, 0x0));
var x378: u32 = undefined;
var x379: u1 = undefined;
subborrowxU32(&x378, &x379, x377, x364, cast(u32, 0x0));
var x380: u32 = undefined;
var x381: u1 = undefined;
subborrowxU32(&x380, &x381, x379, x366, 0xffffffff);
var x382: u32 = undefined;
var x383: u1 = undefined;
subborrowxU32(&x382, &x383, x381, x368, 0xffffffff);
var x384: u32 = undefined;
var x385: u1 = undefined;
subborrowxU32(&x384, &x385, x383, x370, 0xffffffff);
var x386: u32 = undefined;
var x387: u1 = undefined;
subborrowxU32(&x386, &x387, x385, x372, 0xffffffff);
var x388: u32 = undefined;
var x389: u1 = undefined;
subborrowxU32(&x388, &x389, x387, cast(u32, x373), cast(u32, 0x0));
var x390: u32 = undefined;
cmovznzU32(&x390, x389, x374, x360);
var x391: u32 = undefined;
cmovznzU32(&x391, x389, x376, x362);
var x392: u32 = undefined;
cmovznzU32(&x392, x389, x378, x364);
var x393: u32 = undefined;
cmovznzU32(&x393, x389, x380, x366);
var x394: u32 = undefined;
cmovznzU32(&x394, x389, x382, x368);
var x395: u32 = undefined;
cmovznzU32(&x395, x389, x384, x370);
var x396: u32 = undefined;
cmovznzU32(&x396, x389, x386, x372);
out1[0] = x390;
out1[1] = x391;
out1[2] = x392;
out1[3] = x393;
out1[4] = x394;
out1[5] = x395;
out1[6] = x396;
}
/// The function nonzero outputs a single non-zero word if the input is non-zero and zero otherwise.
///
/// Preconditions:
/// 0 ≤ eval arg1 < m
/// Postconditions:
/// out1 = 0 ↔ eval (from_montgomery arg1) mod m = 0
///
/// Input Bounds:
/// arg1: [[0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff]]
/// Output Bounds:
/// out1: [0x0 ~> 0xffffffff]
pub fn nonzero(out1: *u32, arg1: [7]u32) void {
@setRuntimeSafety(mode == .Debug);
const x1 = ((arg1[0]) | ((arg1[1]) | ((arg1[2]) | ((arg1[3]) | ((arg1[4]) | ((arg1[5]) | (arg1[6])))))));
out1.* = x1;
}
/// The function selectznz is a multi-limb conditional select.
///
/// Postconditions:
/// eval out1 = (if arg1 = 0 then eval arg2 else eval arg3)
///
/// Input Bounds:
/// arg1: [0x0 ~> 0x1]
/// arg2: [[0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff]]
/// arg3: [[0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff]]
/// Output Bounds:
/// out1: [[0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff]]
pub fn selectznz(out1: *[7]u32, arg1: u1, arg2: [7]u32, arg3: [7]u32) void {
@setRuntimeSafety(mode == .Debug);
var x1: u32 = undefined;
cmovznzU32(&x1, arg1, (arg2[0]), (arg3[0]));
var x2: u32 = undefined;
cmovznzU32(&x2, arg1, (arg2[1]), (arg3[1]));
var x3: u32 = undefined;
cmovznzU32(&x3, arg1, (arg2[2]), (arg3[2]));
var x4: u32 = undefined;
cmovznzU32(&x4, arg1, (arg2[3]), (arg3[3]));
var x5: u32 = undefined;
cmovznzU32(&x5, arg1, (arg2[4]), (arg3[4]));
var x6: u32 = undefined;
cmovznzU32(&x6, arg1, (arg2[5]), (arg3[5]));
var x7: u32 = undefined;
cmovznzU32(&x7, arg1, (arg2[6]), (arg3[6]));
out1[0] = x1;
out1[1] = x2;
out1[2] = x3;
out1[3] = x4;
out1[4] = x5;
out1[5] = x6;
out1[6] = x7;
}
/// The function toBytes serializes a field element NOT in the Montgomery domain to bytes in little-endian order.
///
/// Preconditions:
/// 0 ≤ eval arg1 < m
/// Postconditions:
/// out1 = map (λ x, ⌊((eval arg1 mod m) mod 2^(8 * (x + 1))) / 2^(8 * x)⌋) [0..27]
///
/// Input Bounds:
/// arg1: [[0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff]]
/// Output Bounds:
/// out1: [[0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff]]
pub fn toBytes(out1: *[28]u8, arg1: [7]u32) void {
@setRuntimeSafety(mode == .Debug);
const x1 = (arg1[6]);
const x2 = (arg1[5]);
const x3 = (arg1[4]);
const x4 = (arg1[3]);
const x5 = (arg1[2]);
const x6 = (arg1[1]);
const x7 = (arg1[0]);
const x8 = cast(u8, (x7 & cast(u32, 0xff)));
const x9 = (x7 >> 8);
const x10 = cast(u8, (x9 & cast(u32, 0xff)));
const x11 = (x9 >> 8);
const x12 = cast(u8, (x11 & cast(u32, 0xff)));
const x13 = cast(u8, (x11 >> 8));
const x14 = cast(u8, (x6 & cast(u32, 0xff)));
const x15 = (x6 >> 8);
const x16 = cast(u8, (x15 & cast(u32, 0xff)));
const x17 = (x15 >> 8);
const x18 = cast(u8, (x17 & cast(u32, 0xff)));
const x19 = cast(u8, (x17 >> 8));
const x20 = cast(u8, (x5 & cast(u32, 0xff)));
const x21 = (x5 >> 8);
const x22 = cast(u8, (x21 & cast(u32, 0xff)));
const x23 = (x21 >> 8);
const x24 = cast(u8, (x23 & cast(u32, 0xff)));
const x25 = cast(u8, (x23 >> 8));
const x26 = cast(u8, (x4 & cast(u32, 0xff)));
const x27 = (x4 >> 8);
const x28 = cast(u8, (x27 & cast(u32, 0xff)));
const x29 = (x27 >> 8);
const x30 = cast(u8, (x29 & cast(u32, 0xff)));
const x31 = cast(u8, (x29 >> 8));
const x32 = cast(u8, (x3 & cast(u32, 0xff)));
const x33 = (x3 >> 8);
const x34 = cast(u8, (x33 & cast(u32, 0xff)));
const x35 = (x33 >> 8);
const x36 = cast(u8, (x35 & cast(u32, 0xff)));
const x37 = cast(u8, (x35 >> 8));
const x38 = cast(u8, (x2 & cast(u32, 0xff)));
const x39 = (x2 >> 8);
const x40 = cast(u8, (x39 & cast(u32, 0xff)));
const x41 = (x39 >> 8);
const x42 = cast(u8, (x41 & cast(u32, 0xff)));
const x43 = cast(u8, (x41 >> 8));
const x44 = cast(u8, (x1 & cast(u32, 0xff)));
const x45 = (x1 >> 8);
const x46 = cast(u8, (x45 & cast(u32, 0xff)));
const x47 = (x45 >> 8);
const x48 = cast(u8, (x47 & cast(u32, 0xff)));
const x49 = cast(u8, (x47 >> 8));
out1[0] = x8;
out1[1] = x10;
out1[2] = x12;
out1[3] = x13;
out1[4] = x14;
out1[5] = x16;
out1[6] = x18;
out1[7] = x19;
out1[8] = x20;
out1[9] = x22;
out1[10] = x24;
out1[11] = x25;
out1[12] = x26;
out1[13] = x28;
out1[14] = x30;
out1[15] = x31;
out1[16] = x32;
out1[17] = x34;
out1[18] = x36;
out1[19] = x37;
out1[20] = x38;
out1[21] = x40;
out1[22] = x42;
out1[23] = x43;
out1[24] = x44;
out1[25] = x46;
out1[26] = x48;
out1[27] = x49;
}
/// The function fromBytes deserializes a field element NOT in the Montgomery domain from bytes in little-endian order.
///
/// Preconditions:
/// 0 ≤ bytes_eval arg1 < m
/// Postconditions:
/// eval out1 mod m = bytes_eval arg1 mod m
/// 0 ≤ eval out1 < m
///
/// Input Bounds:
/// arg1: [[0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff]]
/// Output Bounds:
/// out1: [[0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff]]
pub fn fromBytes(out1: *[7]u32, arg1: [28]u8) void {
@setRuntimeSafety(mode == .Debug);
const x1 = (cast(u32, (arg1[27])) << 24);
const x2 = (cast(u32, (arg1[26])) << 16);
const x3 = (cast(u32, (arg1[25])) << 8);
const x4 = (arg1[24]);
const x5 = (cast(u32, (arg1[23])) << 24);
const x6 = (cast(u32, (arg1[22])) << 16);
const x7 = (cast(u32, (arg1[21])) << 8);
const x8 = (arg1[20]);
const x9 = (cast(u32, (arg1[19])) << 24);
const x10 = (cast(u32, (arg1[18])) << 16);
const x11 = (cast(u32, (arg1[17])) << 8);
const x12 = (arg1[16]);
const x13 = (cast(u32, (arg1[15])) << 24);
const x14 = (cast(u32, (arg1[14])) << 16);
const x15 = (cast(u32, (arg1[13])) << 8);
const x16 = (arg1[12]);
const x17 = (cast(u32, (arg1[11])) << 24);
const x18 = (cast(u32, (arg1[10])) << 16);
const x19 = (cast(u32, (arg1[9])) << 8);
const x20 = (arg1[8]);
const x21 = (cast(u32, (arg1[7])) << 24);
const x22 = (cast(u32, (arg1[6])) << 16);
const x23 = (cast(u32, (arg1[5])) << 8);
const x24 = (arg1[4]);
const x25 = (cast(u32, (arg1[3])) << 24);
const x26 = (cast(u32, (arg1[2])) << 16);
const x27 = (cast(u32, (arg1[1])) << 8);
const x28 = (arg1[0]);
const x29 = (x27 + cast(u32, x28));
const x30 = (x26 + x29);
const x31 = (x25 + x30);
const x32 = (x23 + cast(u32, x24));
const x33 = (x22 + x32);
const x34 = (x21 + x33);
const x35 = (x19 + cast(u32, x20));
const x36 = (x18 + x35);
const x37 = (x17 + x36);
const x38 = (x15 + cast(u32, x16));
const x39 = (x14 + x38);
const x40 = (x13 + x39);
const x41 = (x11 + cast(u32, x12));
const x42 = (x10 + x41);
const x43 = (x9 + x42);
const x44 = (x7 + cast(u32, x8));
const x45 = (x6 + x44);
const x46 = (x5 + x45);
const x47 = (x3 + cast(u32, x4));
const x48 = (x2 + x47);
const x49 = (x1 + x48);
out1[0] = x31;
out1[1] = x34;
out1[2] = x37;
out1[3] = x40;
out1[4] = x43;
out1[5] = x46;
out1[6] = x49;
}
/// The function setOne returns the field element one in the Montgomery domain.
///
/// Postconditions:
/// eval (from_montgomery out1) mod m = 1 mod m
/// 0 ≤ eval out1 < m
///
pub fn setOne(out1: *MontgomeryDomainFieldElement) void {
@setRuntimeSafety(mode == .Debug);
out1[0] = 0xffffffff;
out1[1] = 0xffffffff;
out1[2] = 0xffffffff;
out1[3] = cast(u32, 0x0);
out1[4] = cast(u32, 0x0);
out1[5] = cast(u32, 0x0);
out1[6] = cast(u32, 0x0);
}
/// The function msat returns the saturated representation of the prime modulus.
///
/// Postconditions:
/// twos_complement_eval out1 = m
/// 0 ≤ eval out1 < m
///
/// Output Bounds:
/// out1: [[0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff]]
pub fn msat(out1: *[8]u32) void {
@setRuntimeSafety(mode == .Debug);
out1[0] = cast(u32, 0x1);
out1[1] = cast(u32, 0x0);
out1[2] = cast(u32, 0x0);
out1[3] = 0xffffffff;
out1[4] = 0xffffffff;
out1[5] = 0xffffffff;
out1[6] = 0xffffffff;
out1[7] = cast(u32, 0x0);
}
/// The function divstep computes a divstep.
///
/// Preconditions:
/// 0 ≤ eval arg4 < m
/// 0 ≤ eval arg5 < m
/// Postconditions:
/// out1 = (if 0 < arg1 ∧ (twos_complement_eval arg3) is odd then 1 - arg1 else 1 + arg1)
/// twos_complement_eval out2 = (if 0 < arg1 ∧ (twos_complement_eval arg3) is odd then twos_complement_eval arg3 else twos_complement_eval arg2)
/// twos_complement_eval out3 = (if 0 < arg1 ∧ (twos_complement_eval arg3) is odd then ⌊(twos_complement_eval arg3 - twos_complement_eval arg2) / 2⌋ else ⌊(twos_complement_eval arg3 + (twos_complement_eval arg3 mod 2) * twos_complement_eval arg2) / 2⌋)
/// eval (from_montgomery out4) mod m = (if 0 < arg1 ∧ (twos_complement_eval arg3) is odd then (2 * eval (from_montgomery arg5)) mod m else (2 * eval (from_montgomery arg4)) mod m)
/// eval (from_montgomery out5) mod m = (if 0 < arg1 ∧ (twos_complement_eval arg3) is odd then (eval (from_montgomery arg4) - eval (from_montgomery arg4)) mod m else (eval (from_montgomery arg5) + (twos_complement_eval arg3 mod 2) * eval (from_montgomery arg4)) mod m)
/// 0 ≤ eval out5 < m
/// 0 ≤ eval out5 < m
/// 0 ≤ eval out2 < m
/// 0 ≤ eval out3 < m
///
/// Input Bounds:
/// arg1: [0x0 ~> 0xffffffff]
/// arg2: [[0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff]]
/// arg3: [[0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff]]
/// arg4: [[0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff]]
/// arg5: [[0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff]]
/// Output Bounds:
/// out1: [0x0 ~> 0xffffffff]
/// out2: [[0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff]]
/// out3: [[0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff]]
/// out4: [[0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff]]
/// out5: [[0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff]]
pub fn divstep(out1: *u32, out2: *[8]u32, out3: *[8]u32, out4: *[7]u32, out5: *[7]u32, arg1: u32, arg2: [8]u32, arg3: [8]u32, arg4: [7]u32, arg5: [7]u32) void {
@setRuntimeSafety(mode == .Debug);
var x1: u32 = undefined;
var x2: u1 = undefined;
addcarryxU32(&x1, &x2, 0x0, (~arg1), cast(u32, 0x1));
const x3 = (cast(u1, (x1 >> 31)) & cast(u1, ((arg3[0]) & cast(u32, 0x1))));
var x4: u32 = undefined;
var x5: u1 = undefined;
addcarryxU32(&x4, &x5, 0x0, (~arg1), cast(u32, 0x1));
var x6: u32 = undefined;
cmovznzU32(&x6, x3, arg1, x4);
var x7: u32 = undefined;
cmovznzU32(&x7, x3, (arg2[0]), (arg3[0]));
var x8: u32 = undefined;
cmovznzU32(&x8, x3, (arg2[1]), (arg3[1]));
var x9: u32 = undefined;
cmovznzU32(&x9, x3, (arg2[2]), (arg3[2]));
var x10: u32 = undefined;
cmovznzU32(&x10, x3, (arg2[3]), (arg3[3]));
var x11: u32 = undefined;
cmovznzU32(&x11, x3, (arg2[4]), (arg3[4]));
var x12: u32 = undefined;
cmovznzU32(&x12, x3, (arg2[5]), (arg3[5]));
var x13: u32 = undefined;
cmovznzU32(&x13, x3, (arg2[6]), (arg3[6]));
var x14: u32 = undefined;
cmovznzU32(&x14, x3, (arg2[7]), (arg3[7]));
var x15: u32 = undefined;
var x16: u1 = undefined;
addcarryxU32(&x15, &x16, 0x0, cast(u32, 0x1), (~(arg2[0])));
var x17: u32 = undefined;
var x18: u1 = undefined;
addcarryxU32(&x17, &x18, x16, cast(u32, 0x0), (~(arg2[1])));
var x19: u32 = undefined;
var x20: u1 = undefined;
addcarryxU32(&x19, &x20, x18, cast(u32, 0x0), (~(arg2[2])));
var x21: u32 = undefined;
var x22: u1 = undefined;
addcarryxU32(&x21, &x22, x20, cast(u32, 0x0), (~(arg2[3])));
var x23: u32 = undefined;
var x24: u1 = undefined;
addcarryxU32(&x23, &x24, x22, cast(u32, 0x0), (~(arg2[4])));
var x25: u32 = undefined;
var x26: u1 = undefined;
addcarryxU32(&x25, &x26, x24, cast(u32, 0x0), (~(arg2[5])));
var x27: u32 = undefined;
var x28: u1 = undefined;
addcarryxU32(&x27, &x28, x26, cast(u32, 0x0), (~(arg2[6])));
var x29: u32 = undefined;
var x30: u1 = undefined;
addcarryxU32(&x29, &x30, x28, cast(u32, 0x0), (~(arg2[7])));
var x31: u32 = undefined;
cmovznzU32(&x31, x3, (arg3[0]), x15);
var x32: u32 = undefined;
cmovznzU32(&x32, x3, (arg3[1]), x17);
var x33: u32 = undefined;
cmovznzU32(&x33, x3, (arg3[2]), x19);
var x34: u32 = undefined;
cmovznzU32(&x34, x3, (arg3[3]), x21);
var x35: u32 = undefined;
cmovznzU32(&x35, x3, (arg3[4]), x23);
var x36: u32 = undefined;
cmovznzU32(&x36, x3, (arg3[5]), x25);
var x37: u32 = undefined;
cmovznzU32(&x37, x3, (arg3[6]), x27);
var x38: u32 = undefined;
cmovznzU32(&x38, x3, (arg3[7]), x29);
var x39: u32 = undefined;
cmovznzU32(&x39, x3, (arg4[0]), (arg5[0]));
var x40: u32 = undefined;
cmovznzU32(&x40, x3, (arg4[1]), (arg5[1]));
var x41: u32 = undefined;
cmovznzU32(&x41, x3, (arg4[2]), (arg5[2]));
var x42: u32 = undefined;
cmovznzU32(&x42, x3, (arg4[3]), (arg5[3]));
var x43: u32 = undefined;
cmovznzU32(&x43, x3, (arg4[4]), (arg5[4]));
var x44: u32 = undefined;
cmovznzU32(&x44, x3, (arg4[5]), (arg5[5]));
var x45: u32 = undefined;
cmovznzU32(&x45, x3, (arg4[6]), (arg5[6]));
var x46: u32 = undefined;
var x47: u1 = undefined;
addcarryxU32(&x46, &x47, 0x0, x39, x39);
var x48: u32 = undefined;
var x49: u1 = undefined;
addcarryxU32(&x48, &x49, x47, x40, x40);
var x50: u32 = undefined;
var x51: u1 = undefined;
addcarryxU32(&x50, &x51, x49, x41, x41);
var x52: u32 = undefined;
var x53: u1 = undefined;
addcarryxU32(&x52, &x53, x51, x42, x42);
var x54: u32 = undefined;
var x55: u1 = undefined;
addcarryxU32(&x54, &x55, x53, x43, x43);
var x56: u32 = undefined;
var x57: u1 = undefined;
addcarryxU32(&x56, &x57, x55, x44, x44);
var x58: u32 = undefined;
var x59: u1 = undefined;
addcarryxU32(&x58, &x59, x57, x45, x45);
var x60: u32 = undefined;
var x61: u1 = undefined;
subborrowxU32(&x60, &x61, 0x0, x46, cast(u32, 0x1));
var x62: u32 = undefined;
var x63: u1 = undefined;
subborrowxU32(&x62, &x63, x61, x48, cast(u32, 0x0));
var x64: u32 = undefined;
var x65: u1 = undefined;
subborrowxU32(&x64, &x65, x63, x50, cast(u32, 0x0));
var x66: u32 = undefined;
var x67: u1 = undefined;
subborrowxU32(&x66, &x67, x65, x52, 0xffffffff);
var x68: u32 = undefined;
var x69: u1 = undefined;
subborrowxU32(&x68, &x69, x67, x54, 0xffffffff);
var x70: u32 = undefined;
var x71: u1 = undefined;
subborrowxU32(&x70, &x71, x69, x56, 0xffffffff);
var x72: u32 = undefined;
var x73: u1 = undefined;
subborrowxU32(&x72, &x73, x71, x58, 0xffffffff);
var x74: u32 = undefined;
var x75: u1 = undefined;
subborrowxU32(&x74, &x75, x73, cast(u32, x59), cast(u32, 0x0));
const x76 = (arg4[6]);
const x77 = (arg4[5]);
const x78 = (arg4[4]);
const x79 = (arg4[3]);
const x80 = (arg4[2]);
const x81 = (arg4[1]);
const x82 = (arg4[0]);
var x83: u32 = undefined;
var x84: u1 = undefined;
subborrowxU32(&x83, &x84, 0x0, cast(u32, 0x0), x82);
var x85: u32 = undefined;
var x86: u1 = undefined;
subborrowxU32(&x85, &x86, x84, cast(u32, 0x0), x81);
var x87: u32 = undefined;
var x88: u1 = undefined;
subborrowxU32(&x87, &x88, x86, cast(u32, 0x0), x80);
var x89: u32 = undefined;
var x90: u1 = undefined;
subborrowxU32(&x89, &x90, x88, cast(u32, 0x0), x79);
var x91: u32 = undefined;
var x92: u1 = undefined;
subborrowxU32(&x91, &x92, x90, cast(u32, 0x0), x78);
var x93: u32 = undefined;
var x94: u1 = undefined;
subborrowxU32(&x93, &x94, x92, cast(u32, 0x0), x77);
var x95: u32 = undefined;
var x96: u1 = undefined;
subborrowxU32(&x95, &x96, x94, cast(u32, 0x0), x76);
var x97: u32 = undefined;
cmovznzU32(&x97, x96, cast(u32, 0x0), 0xffffffff);
var x98: u32 = undefined;
var x99: u1 = undefined;
addcarryxU32(&x98, &x99, 0x0, x83, cast(u32, cast(u1, (x97 & cast(u32, 0x1)))));
var x100: u32 = undefined;
var x101: u1 = undefined;
addcarryxU32(&x100, &x101, x99, x85, cast(u32, 0x0));
var x102: u32 = undefined;
var x103: u1 = undefined;
addcarryxU32(&x102, &x103, x101, x87, cast(u32, 0x0));
var x104: u32 = undefined;
var x105: u1 = undefined;
addcarryxU32(&x104, &x105, x103, x89, x97);
var x106: u32 = undefined;
var x107: u1 = undefined;
addcarryxU32(&x106, &x107, x105, x91, x97);
var x108: u32 = undefined;
var x109: u1 = undefined;
addcarryxU32(&x108, &x109, x107, x93, x97);
var x110: u32 = undefined;
var x111: u1 = undefined;
addcarryxU32(&x110, &x111, x109, x95, x97);
var x112: u32 = undefined;
cmovznzU32(&x112, x3, (arg5[0]), x98);
var x113: u32 = undefined;
cmovznzU32(&x113, x3, (arg5[1]), x100);
var x114: u32 = undefined;
cmovznzU32(&x114, x3, (arg5[2]), x102);
var x115: u32 = undefined;
cmovznzU32(&x115, x3, (arg5[3]), x104);
var x116: u32 = undefined;
cmovznzU32(&x116, x3, (arg5[4]), x106);
var x117: u32 = undefined;
cmovznzU32(&x117, x3, (arg5[5]), x108);
var x118: u32 = undefined;
cmovznzU32(&x118, x3, (arg5[6]), x110);
const x119 = cast(u1, (x31 & cast(u32, 0x1)));
var x120: u32 = undefined;
cmovznzU32(&x120, x119, cast(u32, 0x0), x7);
var x121: u32 = undefined;
cmovznzU32(&x121, x119, cast(u32, 0x0), x8);
var x122: u32 = undefined;
cmovznzU32(&x122, x119, cast(u32, 0x0), x9);
var x123: u32 = undefined;
cmovznzU32(&x123, x119, cast(u32, 0x0), x10);
var x124: u32 = undefined;
cmovznzU32(&x124, x119, cast(u32, 0x0), x11);
var x125: u32 = undefined;
cmovznzU32(&x125, x119, cast(u32, 0x0), x12);
var x126: u32 = undefined;
cmovznzU32(&x126, x119, cast(u32, 0x0), x13);
var x127: u32 = undefined;
cmovznzU32(&x127, x119, cast(u32, 0x0), x14);
var x128: u32 = undefined;
var x129: u1 = undefined;
addcarryxU32(&x128, &x129, 0x0, x31, x120);
var x130: u32 = undefined;
var x131: u1 = undefined;
addcarryxU32(&x130, &x131, x129, x32, x121);
var x132: u32 = undefined;
var x133: u1 = undefined;
addcarryxU32(&x132, &x133, x131, x33, x122);
var x134: u32 = undefined;
var x135: u1 = undefined;
addcarryxU32(&x134, &x135, x133, x34, x123);
var x136: u32 = undefined;
var x137: u1 = undefined;
addcarryxU32(&x136, &x137, x135, x35, x124);
var x138: u32 = undefined;
var x139: u1 = undefined;
addcarryxU32(&x138, &x139, x137, x36, x125);
var x140: u32 = undefined;
var x141: u1 = undefined;
addcarryxU32(&x140, &x141, x139, x37, x126);
var x142: u32 = undefined;
var x143: u1 = undefined;
addcarryxU32(&x142, &x143, x141, x38, x127);
var x144: u32 = undefined;
cmovznzU32(&x144, x119, cast(u32, 0x0), x39);
var x145: u32 = undefined;
cmovznzU32(&x145, x119, cast(u32, 0x0), x40);
var x146: u32 = undefined;
cmovznzU32(&x146, x119, cast(u32, 0x0), x41);
var x147: u32 = undefined;
cmovznzU32(&x147, x119, cast(u32, 0x0), x42);
var x148: u32 = undefined;
cmovznzU32(&x148, x119, cast(u32, 0x0), x43);
var x149: u32 = undefined;
cmovznzU32(&x149, x119, cast(u32, 0x0), x44);
var x150: u32 = undefined;
cmovznzU32(&x150, x119, cast(u32, 0x0), x45);
var x151: u32 = undefined;
var x152: u1 = undefined;
addcarryxU32(&x151, &x152, 0x0, x112, x144);
var x153: u32 = undefined;
var x154: u1 = undefined;
addcarryxU32(&x153, &x154, x152, x113, x145);
var x155: u32 = undefined;
var x156: u1 = undefined;
addcarryxU32(&x155, &x156, x154, x114, x146);
var x157: u32 = undefined;
var x158: u1 = undefined;
addcarryxU32(&x157, &x158, x156, x115, x147);
var x159: u32 = undefined;
var x160: u1 = undefined;
addcarryxU32(&x159, &x160, x158, x116, x148);
var x161: u32 = undefined;
var x162: u1 = undefined;
addcarryxU32(&x161, &x162, x160, x117, x149);
var x163: u32 = undefined;
var x164: u1 = undefined;
addcarryxU32(&x163, &x164, x162, x118, x150);
var x165: u32 = undefined;
var x166: u1 = undefined;
subborrowxU32(&x165, &x166, 0x0, x151, cast(u32, 0x1));
var x167: u32 = undefined;
var x168: u1 = undefined;
subborrowxU32(&x167, &x168, x166, x153, cast(u32, 0x0));
var x169: u32 = undefined;
var x170: u1 = undefined;
subborrowxU32(&x169, &x170, x168, x155, cast(u32, 0x0));
var x171: u32 = undefined;
var x172: u1 = undefined;
subborrowxU32(&x171, &x172, x170, x157, 0xffffffff);
var x173: u32 = undefined;
var x174: u1 = undefined;
subborrowxU32(&x173, &x174, x172, x159, 0xffffffff);
var x175: u32 = undefined;
var x176: u1 = undefined;
subborrowxU32(&x175, &x176, x174, x161, 0xffffffff);
var x177: u32 = undefined;
var x178: u1 = undefined;
subborrowxU32(&x177, &x178, x176, x163, 0xffffffff);
var x179: u32 = undefined;
var x180: u1 = undefined;
subborrowxU32(&x179, &x180, x178, cast(u32, x164), cast(u32, 0x0));
var x181: u32 = undefined;
var x182: u1 = undefined;
addcarryxU32(&x181, &x182, 0x0, x6, cast(u32, 0x1));
const x183 = ((x128 >> 1) | ((x130 << 31) & 0xffffffff));
const x184 = ((x130 >> 1) | ((x132 << 31) & 0xffffffff));
const x185 = ((x132 >> 1) | ((x134 << 31) & 0xffffffff));
const x186 = ((x134 >> 1) | ((x136 << 31) & 0xffffffff));
const x187 = ((x136 >> 1) | ((x138 << 31) & 0xffffffff));
const x188 = ((x138 >> 1) | ((x140 << 31) & 0xffffffff));
const x189 = ((x140 >> 1) | ((x142 << 31) & 0xffffffff));
const x190 = ((x142 & 0x80000000) | (x142 >> 1));
var x191: u32 = undefined;
cmovznzU32(&x191, x75, x60, x46);
var x192: u32 = undefined;
cmovznzU32(&x192, x75, x62, x48);
var x193: u32 = undefined;
cmovznzU32(&x193, x75, x64, x50);
var x194: u32 = undefined;
cmovznzU32(&x194, x75, x66, x52);
var x195: u32 = undefined;
cmovznzU32(&x195, x75, x68, x54);
var x196: u32 = undefined;
cmovznzU32(&x196, x75, x70, x56);
var x197: u32 = undefined;
cmovznzU32(&x197, x75, x72, x58);
var x198: u32 = undefined;
cmovznzU32(&x198, x180, x165, x151);
var x199: u32 = undefined;
cmovznzU32(&x199, x180, x167, x153);
var x200: u32 = undefined;
cmovznzU32(&x200, x180, x169, x155);
var x201: u32 = undefined;
cmovznzU32(&x201, x180, x171, x157);
var x202: u32 = undefined;
cmovznzU32(&x202, x180, x173, x159);
var x203: u32 = undefined;
cmovznzU32(&x203, x180, x175, x161);
var x204: u32 = undefined;
cmovznzU32(&x204, x180, x177, x163);
out1.* = x181;
out2[0] = x7;
out2[1] = x8;
out2[2] = x9;
out2[3] = x10;
out2[4] = x11;
out2[5] = x12;
out2[6] = x13;
out2[7] = x14;
out3[0] = x183;
out3[1] = x184;
out3[2] = x185;
out3[3] = x186;
out3[4] = x187;
out3[5] = x188;
out3[6] = x189;
out3[7] = x190;
out4[0] = x191;
out4[1] = x192;
out4[2] = x193;
out4[3] = x194;
out4[4] = x195;
out4[5] = x196;
out4[6] = x197;
out5[0] = x198;
out5[1] = x199;
out5[2] = x200;
out5[3] = x201;
out5[4] = x202;
out5[5] = x203;
out5[6] = x204;
}
/// The function divstepPrecomp returns the precomputed value for Bernstein-Yang-inversion (in montgomery form).
///
/// Postconditions:
/// eval (from_montgomery out1) = ⌊(m - 1) / 2⌋^(if ⌊log2 m⌋ + 1 < 46 then ⌊(49 * (⌊log2 m⌋ + 1) + 80) / 17⌋ else ⌊(49 * (⌊log2 m⌋ + 1) + 57) / 17⌋)
/// 0 ≤ eval out1 < m
///
/// Output Bounds:
/// out1: [[0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff]]
pub fn divstepPrecomp(out1: *[7]u32) void {
@setRuntimeSafety(mode == .Debug);
out1[0] = 0x800000;
out1[1] = 0x800000;
out1[2] = 0xfe000000;
out1[3] = 0xffffff;
out1[4] = cast(u32, 0x0);
out1[5] = 0xff800000;
out1[6] = 0x17fffff;
} | fiat-zig/src/p224_32.zig |
const std = @import("std");
const assert = std.debug.assert;
const allocator = std.testing.allocator;
pub const Board = struct {
dist: Distance,
map: std.AutoHashMap(i32, u32),
md: u32,
mx: i32,
my: i32,
pub const Distance = enum {
Manhattan,
Travelled,
};
pub fn init(dist: Board.Distance) Board {
var self = Board{
.dist = dist,
.map = std.AutoHashMap(i32, u32).init(allocator),
.md = std.math.maxInt(u32),
.mx = 0,
.my = 0,
};
return self;
}
pub fn deinit(self: *Board) void {
self.map.deinit();
}
pub fn trace(self: *Board, str: []const u8, first: bool) void {
var it = std.mem.split(u8, str, ",");
var cx: i32 = 0;
var cy: i32 = 0;
var cl: u32 = 0;
while (it.next()) |what| {
const dir = what[0];
const len = std.fmt.parseInt(usize, what[1..], 10) catch 0;
var dx: i32 = 0;
dx = switch (dir) {
'R' => 1,
'L' => -1,
else => 0,
};
var dy: i32 = 0;
dy = switch (dir) {
'U' => 1,
'D' => -1,
else => 0,
};
var j: usize = 0;
while (j < len) : (j += 1) {
cx += dx;
cy += dy;
cl += 1;
const pos = cx * 10000 + cy;
if (first) {
_ = self.map.put(pos, cl) catch unreachable;
} else if (self.map.contains(pos)) {
const val = self.map.getEntry(pos).?.value_ptr.*;
const d = switch (self.dist) {
Distance.Manhattan => manhattan(cx, cy),
Distance.Travelled => travelled(val, cl),
};
if (self.md > d) {
self.md = d;
self.mx = cx;
self.my = cy;
}
}
}
}
}
};
fn manhattan(x: i32, y: i32) u32 {
const ax = std.math.absInt(x) catch 0;
const ay = std.math.absInt(y) catch 0;
return @intCast(u32, ax) + @intCast(u32, ay);
}
fn travelled(v0: u32, v1: u32) u32 {
return v0 + v1;
}
test "Manhattan - distance 6" {
const wire0: []const u8 = "R8,U5,L5,D3";
const wire1: []const u8 = "U7,R6,D4,L4";
var board = Board.init(Board.Distance.Manhattan);
defer board.deinit();
board.trace(wire0, true);
board.trace(wire1, false);
assert(board.md == 6);
}
test "Manhattan - distance 159" {
const wire0: []const u8 = "R75,D30,R83,U83,L12,D49,R71,U7,L72";
const wire1: []const u8 = "U62,R66,U55,R34,D71,R55,D58,R83";
var board = Board.init(Board.Distance.Manhattan);
defer board.deinit();
board.trace(wire0, true);
board.trace(wire1, false);
assert(board.md == 159);
}
test "Manhattan - distance 135" {
const wire0: []const u8 = "R98,U47,R26,D63,R33,U87,L62,D20,R33,U53,R51";
const wire1: []const u8 = "U98,R91,D20,R16,D67,R40,U7,R15,U6,R7";
var board = Board.init(Board.Distance.Manhattan);
defer board.deinit();
board.trace(wire0, true);
board.trace(wire1, false);
assert(board.md == 135);
}
test "Travelled - distance 30" {
const wire0: []const u8 = "R8,U5,L5,D3";
const wire1: []const u8 = "U7,R6,D4,L4";
var board = Board.init(Board.Distance.Travelled);
defer board.deinit();
board.trace(wire0, true);
board.trace(wire1, false);
assert(board.md == 30);
}
test "Travelled - distance 159" {
const wire0: []const u8 = "R75,D30,R83,U83,L12,D49,R71,U7,L72";
const wire1: []const u8 = "U62,R66,U55,R34,D71,R55,D58,R83";
var board = Board.init(Board.Distance.Travelled);
defer board.deinit();
board.trace(wire0, true);
board.trace(wire1, false);
assert(board.md == 610);
}
test "Travelled - distance 135" {
const wire0: []const u8 = "R98,U47,R26,D63,R33,U87,L62,D20,R33,U53,R51";
const wire1: []const u8 = "U98,R91,D20,R16,D67,R40,U7,R15,U6,R7";
var board = Board.init(Board.Distance.Travelled);
defer board.deinit();
board.trace(wire0, true);
board.trace(wire1, false);
assert(board.md == 410);
} | 2019/p03/board.zig |
const builtin = @import("builtin");
const std = @import("std");
const Mode = builtin.Mode;
const Builder = std.build.Builder;
pub fn build(b: *Builder) void {
const mode = b.standardReleaseOptions();
const randomizer = b.addExecutable("randomizer", "src/main.zig");
randomizer.setBuildMode(mode);
randomizer.addPackagePath("crc", "lib/zig-crc/crc.zig");
randomizer.addPackagePath("fun", "lib/fun-with-zig/src/index.zig");
randomizer.addPackagePath("blz", "lib/blz/blz.zig");
const randomizer_step = b.step("randomizer", "Build randomizer");
randomizer_step.dependOn(&randomizer.step);
const offset_finder = b.addExecutable("offset-finder", "tools/offset-finder/main.zig");
offset_finder.setBuildMode(mode);
offset_finder.addPackagePath("gba", "src/gba.zig");
offset_finder.addPackagePath("gb", "src/gb.zig");
offset_finder.addPackagePath("int", "src/int.zig");
offset_finder.addPackagePath("utils", "src/utils/index.zig");
offset_finder.addPackagePath("pokemon", "src/pokemon/index.zig");
offset_finder.addPackagePath("fun", "lib/fun-with-zig/src/index.zig");
const nds_util = b.addExecutable("nds-util", "tools/nds-util/main.zig");
nds_util.setBuildMode(mode);
nds_util.addPackagePath("crc", "lib/zig-crc/crc.zig");
nds_util.addPackagePath("fun", "lib/fun-with-zig/src/index.zig");
nds_util.addPackagePath("blz", "lib/blz/blz.zig");
// TODO: When https://github.com/zig-lang/zig/issues/855 is fixed. Add this line.
// nds_util.addPackagePath("nds", "src/nds/index.zig");
const tools_step = b.step("tools", "Build tools");
tools_step.dependOn(&offset_finder.step);
tools_step.dependOn(&nds_util.step);
const test_all_step = b.step("test", "Run all tests in all modes.");
inline for ([]Mode{ Mode.Debug, Mode.ReleaseFast, Mode.ReleaseSafe, Mode.ReleaseSmall }) |test_mode| {
const mode_str = comptime modeToString(test_mode);
const src_tests = b.addTest("src/test.zig");
const test_tests = b.addTest("test/index.zig");
src_tests.setBuildMode(test_mode);
src_tests.setNamePrefix(mode_str ++ " ");
test_tests.setBuildMode(test_mode);
test_tests.setNamePrefix(mode_str ++ " ");
const test_step = b.step("test-" ++ mode_str, "Run all tests in " ++ mode_str ++ ".");
test_step.dependOn(&src_tests.step);
test_step.dependOn(&test_tests.step);
test_all_step.dependOn(test_step);
}
const all_step = b.step("all", "Build everything and runs all tests");
all_step.dependOn(test_all_step);
all_step.dependOn(randomizer_step);
all_step.dependOn(tools_step);
b.default_step.dependOn(randomizer_step);
}
fn modeToString(mode: Mode) []const u8 {
return switch (mode) {
Mode.Debug => "debug",
Mode.ReleaseFast => "release-fast",
Mode.ReleaseSafe => "release-safe",
Mode.ReleaseSmall => "release-small",
};
} | build.zig |
const std = @import("std");
const fs = std.fs;
const io = std.io;
const mem = std.mem;
const testing = std.testing;
const warn = std.debug.warn;
const StdInStream = io.InStream(fs.File.ReadError);
const StdOutStream = io.OutStream(fs.File.WriteError);
const StdErrStream = io.OutStream(fs.File.WriteError);
/// Defines a commandline application.
pub const Cli = struct {
name: []const u8,
commands: ?[]const Command,
flags: ?[]const Flag,
action: ?fn (
ctx: *Context,
) anyerror!void,
pub fn format(
self: Cli,
comptime fmt: []const u8,
comptime options: std.fmt.FormatOptions,
context: var,
comptime Errors: type,
output: fn (@typeOf(context), []const u8) Errors!void,
) Errors!void {
try std.fmt.format(
context,
Errors,
output,
"{} - a commandline app \n",
self.name,
);
try output(context, "USAGE\n");
try std.fmt.format(
context,
Errors,
output,
" {} [GLOBAL FLAG] command [FLAG] \n",
self.name,
);
try output(context, "list of commands :\n");
if (self.commands) |commands| {
for (commands) |cmd| {
try std.fmt.format(context, Errors, output, " {} -\n", cmd.name);
}
}
}
pub fn run(
self: *const Cli,
a: *mem.Allocator,
arg: []const []u8,
stdin: ?*StdInStream,
stdout: ?*StdOutStream,
stderr: ?*StdErrStream,
) !void {
var args = &try Args.initList(a, arg);
defer args.deinit();
var ctx = &try self.parse(a, args);
ctx.stdin = stdin;
ctx.stdout = stdout;
ctx.stderr = stderr;
if (ctx.command) |cmd| {
if (ctx.show_help) {
if (stdout != null) {
try stdout.?.print("{}\n", cmd);
}
return;
}
if (cmd.action) |action| {
try action(ctx);
}
return;
}
if (stdout != null) {
try stdout.?.print("{}\n", self);
}
}
// parses args and finds which commands is to be invoked.
pub fn parse(self: *const Cli, a: *mem.Allocator, args: *Args) !Context {
var it = &args.iterator(0);
if (it.peek() == null) {
// no any arguments were provided. We return context with the global
// command set or help text if no action was provided on Cli object.
return Context{
.allocator = a,
.cli = self,
.args = args,
.mode = .Global,
.global_flags = FlagSet.init(a),
.local_flags = FlagSet.init(a),
.args_position = 0,
.command = null,
.stdin = null,
.stdout = null,
.stderr = null,
.show_help = false,
};
}
var ctx = Context{
.allocator = a,
.cli = self,
.args = args,
.mode = .Local,
.global_flags = FlagSet.init(a),
.local_flags = FlagSet.init(a),
.command = null,
.args_position = 0,
.stdin = null,
.stdout = null,
.stderr = null,
.show_help = false,
};
var global_scope = true;
while (it.peek()) |next_arg| {
if (checkFlag(next_arg)) |flag| {
if (global_scope) {
if (isHelpFlag(flag)) {
ctx.show_help = true;
} else {
try ctx.addGlobalFlag(flag, it);
}
} else {
try ctx.addLocalFlag(flag, it);
}
} else {
if (ctx.command) |cmd| {
if (cmd.sub_commands != null) {
var match = false;
for (cmd.sub_commands.?) |sub| {
if (mem.eql(u8, next_arg, sub.name)) {
ctx.command = ⊂
match = true;
}
}
if (!match) {
return error.CommandNotFound;
}
} else {
// No need to keep going. We take everything that is
// left on argument list to be the arguments passed
// to the active command.
ctx.args_position = it.position;
break;
}
} else {
if (ctx.cli.commands) |cmds| {
var match = false;
for (cmds) |cmd| {
if (mem.eql(u8, cmd.name, next_arg)) {
ctx.command = &cmd;
match = true;
}
}
if (!match) {
return error.CommandNotFound;
}
global_scope = false;
} else {
break;
}
}
}
_ = it.next();
}
ctx.args_position = it.position;
return ctx;
}
};
fn isHelpFlag(s: []const u8) bool {
if (mem.eql(u8, s, "h")) {
return true;
}
return mem.eql(u8, s, "help");
}
fn checkFlag(s: []const u8) ?[]const u8 {
if (s.len <= 1) return null;
var i: usize = 0;
for (s) |x| {
if (x == '-') {
i += 1;
} else {
break;
}
}
if (i == 0) return null;
if (i <= 2 and i < s.len) return s[i..];
return null;
}
pub const Command = struct {
name: []const u8,
flags: ?[]const Flag,
// nested commands that uses the current command as a namespace.
sub_commands: ?[]const Command,
/// This is the function that will be called when this command is matched.
/// stdin,stdout and stderr are streams for writing results. There is no
/// need for the fucntion to call os.exit. Any error returned will result in
/// the program to exit with os.exit(1).
action: ?fn (
ctx: *Context,
) anyerror!void,
pub fn format(
self: Command,
comptime fmt: []const u8,
comptime options: std.fmt.FormatOptions,
context: var,
comptime Errors: type,
output: fn (@typeOf(context), []const u8) Errors!void,
) Errors!void {
try std.fmt.format(context, Errors, output, "{}\n", self.name);
try output(context, "list of flags:\n");
if (self.flags) |flags| {
for (flags) |flag| {
try std.fmt.format(context, Errors, output, "{}\n", flag);
}
}
}
};
/// represent a commandline flag. This is text after - or --
/// for instance
/// -f test.txt
/// --f test.txt
/// The above example `f` is the flag name and test.txt is the flag value.
pub const Flag = struct {
name: []const u8,
/// desc text explaining what this flag is doing.
desc: ?[]const u8,
/// the type of value this flag accepts.
kind: Kind,
pub const Kind = enum {
Bool,
String,
Number,
};
pub fn format(
self: Flag,
comptime fmt: []const u8,
comptime options: std.fmt.FormatOptions,
context: var,
comptime Errors: type,
output: fn (@typeOf(context), []const u8) Errors!void,
) Errors!void {
if (self.name.len > 1) {
try std.fmt.format(
context,
Errors,
output,
" --{} {}\n",
self.name,
self.desc,
);
} else {
try std.fmt.format(
context,
Errors,
output,
" -{} {}\n",
self.name,
self.desc,
);
}
}
pub fn init(name: []const u8, kind: Kind) Flag {
return Flag{
.name = name,
.desc = null,
.kind = kind,
};
}
};
pub const FlagSet = struct {
list: List,
pub const List = std.ArrayList(FlagItem);
/// stores the flag and the position where the flag was found. Allows easy
/// getting the value of the flag from arguments linst.
pub const FlagItem = struct {
flag: Flag,
index: usize,
};
pub fn init(a: *mem.Allocator) FlagSet {
return FlagSet{ .list = List.init(a) };
}
pub fn get(self: FlagSet, name: []const u8) ?FlagItem {
for (self.list.toSlice()) |f| {
if (mem.eql(u8, f.flag.name, name)) {
return f;
}
}
return null;
}
// prints all flags contained in this flag set
pub fn format(
self: FlagSet,
comptime fmt: []const u8,
comptime options: std.fmt.FormatOptions,
context: var,
comptime Errors: type,
output: fn (@typeOf(context), []const u8) Errors!void,
) Errors!void {
for (self.list.toSlice()) |item| {
try std.fmt.format(context, Errors, output, "{}", item);
}
}
pub fn addFlag(self: *FlagSet, flag: Flag, index: usize) !void {
try self.list.append(FlagItem{
.flag = flag,
.index = index,
});
}
};
/// Context stores information about the application.
pub const Context = struct {
allocator: *mem.Allocator,
cli: *const Cli,
args: *const Args,
command: ?*const Command,
mode: Mode,
args_position: usize,
global_flags: FlagSet,
local_flags: FlagSet,
stdin: ?*StdInStream,
stdout: ?*StdOutStream,
stderr: ?*StdErrStream,
show_help: bool,
pub const Mode = enum {
Global,
Local,
};
pub fn addGlobalFlag(self: *Context, name: []const u8, it: *Args.Iterator) !void {
if (self.cli.flags) |flags| {
for (flags) |f| {
if (mem.eql(u8, f.name, name)) {
try self.global_flags.addFlag(f, it.position);
return;
}
}
}
return error.UknownFlag;
}
pub fn addLocalFlag(self: *Context, name: []const u8, it: *Args.Iterator) !void {
if (self.command) |cmd| {
if (cmd.flags) |flags| {
for (flags) |f| {
if (mem.eql(u8, f.name, name)) {
try self.local_flags.addFlag(f, it.position);
return;
}
}
}
}
return error.UknownFlag;
}
pub fn flag(ctx: *const Context, name: []const u8) ?FlagSet.FlagItem {
return ctx.local_flags.get(name);
}
pub fn boolean(ctx: *const Context, name: []const u8) bool {
if (ctx.flag(name)) |_| {
// boolean flags don't carry any values. If they are present then ii implies the flag is set to true.
return true;
}
return false;
}
pub fn getArgs(self: *const Context) Args.Iterator {
return self.args.iterator(self.args_position);
}
pub fn firstArg(self: *const Context) ?[]const u8 {
if (self.args_position >= self.args.args.len) return null;
return self.args.args.at(self.args_position);
}
};
pub const Args = struct {
args: List,
a: *mem.Allocator,
pub const List = std.ArrayList([]const u8);
pub const Iterator = struct {
args: *const Args,
position: usize,
pub fn next(self: *Iterator) ?[]const u8 {
if (self.position >= self.args.args.len) return null;
const e = self.args.at(self.position);
self.position += 1;
return e;
}
pub fn peek(self: *Iterator) ?[]const u8 {
if (self.position >= self.args.args.len) return null;
const e = self.args.at(self.position);
return e;
}
};
pub fn init(a: *mem.Allocator) Args {
return Args{
.a = a,
.args = List.init(a),
};
}
pub fn deinit(self: Args) void {
self.args.deinit();
}
pub fn initList(a: *mem.Allocator, ls: []const []const u8) !Args {
var arg = init(a);
try arg.addList(ls);
return arg;
}
pub fn addList(self: *Args, ls: []const []const u8) !void {
for (ls) |_, i| {
try self.add(ls[i]);
}
}
pub fn add(self: *Args, elem: []const u8) !void {
return self.args.append(elem);
}
pub fn at(self: *const Args, index: usize) []const u8 {
return self.args.toSlice()[index];
}
pub fn iterator(self: *const Args, index: usize) Iterator {
return Iterator{
.args = self,
.position = index,
};
}
}; | src/flags/flags.zig |
const std = @import("std");
const mem = std.mem;
const FLIR = @import("./FLIR.zig");
const print = std.debug.print;
const CFO = @import("./CFO.zig");
const IPReg = CFO.IPReg;
const VMathOp = CFO.VMathOp;
const Inst = FLIR.Inst;
const uv = FLIR.uv;
fn regmovmc(cfo: *CFO, dst: IPReg, src: Inst) !void {
switch (src.mckind) {
.frameslot => try cfo.movrm(dst, CFO.a(.rbp).o(-8 * @as(i32, src.mcidx))),
.ipreg => {
const reg = @intToEnum(IPReg, src.mcidx);
if (dst != reg) try cfo.mov(dst, reg);
},
.fused => {
if (src.tag != .constant) return error.TheDinnerConversationIsLively;
if (src.op1 != 0) { // TODO: proper constval
try cfo.movri(dst, src.op1);
} else {
// THANKS INTEL
try cfo.arit(.xor, dst, dst);
}
},
else => return error.AAA_AA_A,
}
}
fn regaritmc(cfo: *CFO, op: CFO.AOp, dst: IPReg, i: Inst) !void {
switch (i.mckind) {
.frameslot => try cfo.aritrm(op, dst, CFO.a(.rbp).o(-8 * @as(i32, i.mcidx))),
.ipreg => {
const reg = @intToEnum(IPReg, i.mcidx);
try cfo.arit(op, dst, reg);
},
.fused => {
if (i.tag != .constant) return error.GetLostHeIsNeverComingBack;
try cfo.aritri(op, dst, i.op1); // TODO: proper constval
},
else => return error.AAA_AA_A,
}
}
fn mcmovreg(cfo: *CFO, dst: Inst, src: IPReg) !void {
switch (dst.mckind) {
.frameslot => try cfo.movmr(CFO.a(.rbp).o(-8 * @as(i32, dst.mcidx)), .rax),
.ipreg => {
const reg = @intToEnum(IPReg, dst.mcidx);
if (reg != src) try cfo.mov(reg, src);
},
else => return error.AAA_AA_A,
}
}
fn mcmovi(cfo: *CFO, i: Inst) !void {
switch (i.mckind) {
.frameslot => try cfo.movmi(CFO.a(.rbp).o(-8 * @as(i32, i.mcidx)), i.op1),
.ipreg => {
const reg = @intToEnum(IPReg, i.mcidx);
if (i.op1 != 0) {
try cfo.movri(reg, i.op1);
} else {
// THANKS INTEL
try cfo.arit(.xor, reg, reg);
}
},
.fused => {}, // let user lookup value
else => return error.AAA_AA_A,
}
}
// TODO: obviously better handling of scratch register
fn movmcs(cfo: *CFO, dst: Inst, src: Inst, scratch: IPReg) !void {
if (dst.mckind == src.mckind and dst.mcidx == src.mcidx) {
return;
}
if (dst.mckind == .ipreg) {
try regmovmc(cfo, @intToEnum(IPReg, dst.mcidx), src);
} else {
const reg = if (src.mckind == .ipreg)
@intToEnum(IPReg, src.mcidx)
else reg: {
try regmovmc(cfo, scratch, src);
break :reg scratch;
};
try mcmovreg(cfo, dst, reg);
}
}
pub fn makejmp(self: *FLIR, cfo: *CFO, cond: ?CFO.Cond, ni: u16, si: u1, labels: []u32, targets: [][2]u32) !void {
const succ = self.n.items[ni].s[si];
// NOTE: we assume blk 0 always has the prologue (push rbp; mov rbp, rsp)
// at least, so that even if blk 0 is empty, blk 1 has target larger than 0x00
if (labels[succ] != 0) {
try cfo.jbck(cond, labels[succ]);
} else {
targets[ni][si] = try cfo.jfwd(cond);
}
}
pub fn codegen(self: *FLIR, cfo: *CFO) !u32 {
var labels = try self.a.alloc(u32, self.dfs.items.len);
var targets = try self.a.alloc([2]u32, self.dfs.items.len);
defer self.a.free(labels);
defer self.a.free(targets);
mem.set(u32, labels, 0);
mem.set([2]u32, targets, .{ 0, 0 });
const target = cfo.get_target();
try cfo.enter();
const stacksize = 8 * @as(i32, self.nslots);
if (stacksize > 0) {
const padding = (-stacksize) & 0xF;
// print("size: {}, extrasize: {}\n", .{ stacksize, padding });
try cfo.aritri(.sub, .rsp, stacksize + padding);
}
for (self.n.items) |*n, ni| {
if (n.dfnum == 0 and ni > 0) {
// non-entry block not reached by df search is dead.
// TODO: these should already been cleaned up at this point
continue;
}
labels[ni] = cfo.get_target();
print("LABEL: {x} {}\n", .{ labels[ni], ni });
for (self.preds(uv(ni))) |pred| {
const pr = &self.n.items[pred];
const si: u1 = if (pr.s[0] == ni) 0 else 1;
if (targets[pred][si] != 0) {
try cfo.set_target(targets[pred][si]);
targets[pred][si] = 0;
}
}
var cur_blk: ?u16 = n.firstblk;
var ea_fused: CFO.EAddr = undefined;
var fused_inst: ?*Inst = null;
while (cur_blk) |blk| {
var b = &self.b.items[blk];
for (b.i) |*i| {
if (i.tag == .empty) continue;
var was_fused: bool = false;
switch (i.tag) {
// empty doesn't flush fused value
.empty => continue,
.ret => try regmovmc(cfo, .rax, self.iref(i.op1).?.*),
.iop => {
const dst = i.ipreg() orelse .rax;
try regmovmc(cfo, dst, self.iref(i.op1).?.*);
try regaritmc(cfo, @intToEnum(CFO.AOp, i.spec), dst, self.iref(i.op2).?.*);
try mcmovreg(cfo, i.*, dst); // elided if dst is register
},
.constant => try mcmovi(cfo, i.*),
.ilessthan => {
const firstop = self.iref(i.op1).?.ipreg() orelse .rax;
try regmovmc(cfo, firstop, self.iref(i.op1).?.*);
try regaritmc(cfo, .cmp, firstop, self.iref(i.op2).?.*);
},
.putphi => {
// TODO: actually check for parallell-move conflicts
// either here or as an extra deconstruction step
try movmcs(cfo, self.iref(i.op2).?.*, self.iref(i.op1).?.*, .rax);
},
.load => {
// TODO: spill spall supllit?
const base = self.iref(i.op1).?.ipreg() orelse unreachable;
const idx = self.iref(i.op2).?.ipreg() orelse unreachable;
const eaddr = CFO.qi(base, idx);
if (i.spec_type() == .intptr) {
const dst = i.ipreg() orelse .rax;
try cfo.movrm(dst, eaddr);
try mcmovreg(cfo, i.*, dst); // elided if dst is register
} else {
const dst = i.avxreg() orelse unreachable;
try cfo.vmovurm(i.fmode(), dst, eaddr);
}
},
.lea => {
// TODO: spill spall supllit?
const base = self.iref(i.op1).?.ipreg() orelse unreachable;
const idx = self.iref(i.op2).?.ipreg() orelse unreachable;
const eaddr = CFO.qi(base, idx);
if (i.mckind == .fused) {
ea_fused = eaddr;
was_fused = true;
} else {
const dst = i.ipreg() orelse .rax;
try cfo.lea(dst, CFO.qi(base, idx));
try mcmovreg(cfo, i.*, dst); // elided if dst is register
}
},
.store => {
// TODO: fuse lea with store
const addr = self.iref(i.op1).?;
const eaddr = if (addr == fused_inst)
ea_fused
else
CFO.a(self.iref(i.op1).?.ipreg() orelse unreachable);
const val = self.iref(i.op2).?;
if (val.res_type().? == .intptr) {
unreachable;
} else {
const src = val.avxreg() orelse unreachable;
try cfo.vmovumr(i.fmode(), eaddr, src);
}
},
.vmath => {
const x = self.iref(i.op1).?.avxreg() orelse unreachable;
const y = self.iref(i.op2).?.avxreg() orelse unreachable;
const dst = i.avxreg() orelse unreachable;
try cfo.vmathf(i.vop(), i.fmode(), dst, x, y);
},
else => {},
}
fused_inst = if (was_fused) i else null;
}
cur_blk = b.next();
}
// TODO: handle trivial critical-edge block.
const fallthru = ni + 1;
if (n.s[0] == fallthru and n.s[1] != 0) {
try makejmp(self, cfo, .nl, uv(ni), 1, labels, targets);
} else {
const default: u1 = default: {
if (n.s[1] != 0) {
try makejmp(self, cfo, .l, uv(ni), 0, labels, targets);
break :default 1;
} else break :default 0;
};
if (n.s[default] != fallthru and n.s[default] != 0) {
try makejmp(self, cfo, null, uv(ni), default, labels, targets);
}
}
}
try cfo.leave();
try cfo.ret();
return target;
} | src/codegen.zig |
const std = @import("std");
const build_options = @import("build_options");
const debugDisp = build_options.debugDisp;
const debugLoop = build_options.debugLoop;
const debugStages = build_options.debugStages;
const debugCmd = build_options.debugCmd;
const debugStart = build_options.debugStart;
//const debugStart = true;
// using std.meta.argsTuple implies that no filter can use generic functions. We use Filter to generate filter functions
// that are not generic. We do not have the functions in StageType since we generate the args for the functions via
// PipeInstance.args and can set the first arg of the non generic filter function to the StageType used by the pipe.
pub fn Filters(comptime StageType: type, comptime SelectedType: type) type {
std.debug.assert(StageType.TU.inUnion(SelectedType));
return struct {
pub const S = StageType;
pub const T = SelectedType;
pub const F = @This();
// we need to return the global error set. When used, the fn type includes the name of the function. We use this
// to set the name of the stage...
pub fn exactdiv(self: *S, d: T) callconv(.Async) !void {
defer
self.endStage();
if (debugStart) std.log.info("start {}_{s}", .{ self.i, self.name });
//try commit(0);
while (true) {
if (debugStages) std.log.info("div pre peek {}_{s} {*}", .{ self.i, self.name, self.outC });
var i = try self.peekTo(T);
//if (debugStages) std.log.info("div post peek {}_{s} {}",.{self.i, self.name, i});
if (i % d == 0) {
try self.selectOutput(0);
try self.output(i);
} else {
self.selectOutput(1) catch {};
if (self.outC != null) // if an output stream is selected
try self.output(i);
}
if (debugStages) std.log.info("div out {}_{s} {*}", .{ self.i, self.name, self.outC });
_ = try self.readTo(T);
}
return self.ok();
}
// send items to selected output stream using the index of the type in the item's typeUnion
pub fn collateTypes(self: *S) callconv(.Async) !void {
defer
self.endStage();
//const y = struct {
// pub var a:u64 = 16;
//};
//
//try self.call(y,.{
// .{ ._i },
// .{ gen, .{"a"} },
// .{ exactdiv, .{3} },
// .{ console},
// .{ ._o, ._ },
//});
if (debugStart) std.log.info("start {}_{s}", .{ self.i, self.name });
while (true) {
const tu = try self.peekTo(S.TU);
self.selectOutput(@enumToInt(tu.type)) catch {};
if (self.outC != null) { // if an output stream is selected
try self.output(tu);
}
_ = try self.readTo(S.TU);
}
}
pub fn hole(self: *S) callconv(.Async) !void {
defer
self.endStage();
while (true) {
_ = try self.readTo(S.TU);
}
}
pub fn locate(self: *S, d: T) callconv(.Async) !void {
defer
self.endStage();
if (debugStart) std.log.info("start {}_{s}", .{ self.i, self.name });
std.debug.assert(T == []const u8 or T == ?[]const u8 or
T == [:0]const u8 or T == ?[:0]const u8);
while (true) {
var i = try self.peekTo(T);
if (std.mem.indexOfPos(u8, i, 0, d)) {
try self.selectOutput(0);
} else {
self.selectOutput(1) catch {};
}
if (self.outC != null)
try self.output(i);
_ = try self.readTo(S.TU);
}
}
pub fn typeUnion(self: *S, slc: *[]S.TU) callconv(.Async) !void {
defer
self.endStage();
if (debugStart) std.log.info("start {}_{s}", .{ self.i, self.name });
for (slc.*) |d| {
_ = try self.output(d);
}
//while (true) { // copy rest stream to output
// const tu = self.peekTo(S.TU) catch break;
// self.output(tu) catch break;
// _ = self.readTo(S.TU) catch break;
//}
return self.ok();
}
// put the contents of the slice into the pipe, then copy any inputs to output
pub fn slice(self: *S, slc: ?[]T) callconv(.Async) !void {
defer
self.endStage();
//const y = struct {
// pub var a:u64 = 7;
//};
//
//try self.call(y,.{
// .{ gen, .{"a"} },
// .{ console, ._}
//});
if (debugStart) std.log.info("start {}_{s}", .{ self.i, self.name });
if (slc == null) {
//const xxx = try self.peekTo(S.TU);
//std.debug.print("slice {any}\n",.{xxx.type});
while (true) {
const d = try self.peekTo([]T);
for (d) |i| {
try self.output(i);
}
_ = try self.readTo([]T);
}
} else {
for (slc.?) |d| {
_ = try self.output(d);
}
while (true) { // copy rest stream to output
const d = self.peekTo(S.TU) catch break;
self.output(d) catch break;
_ = self.readTo(S.TU) catch break;
}
}
return self.ok();
}
// .read input ArrayList putting elements onto the pipe
// .write clear the ArrayList, read elements from the pipe, appending to the ArrayList
// .append read elements from the pipe, appending to the ArrayList
// .pipe read an ArrayList(s) from the pipe and write the elements to the pipe. Arguement should be null
pub fn arrayList(self: *S, al: ?*std.ArrayList(T), e:enum{read, write, append, pipe}) callconv(.Async) !void {
defer
self.endStage();
if (debugStart) std.log.info("start {}_{s}", .{ self.i, self.name });
if (e != .pipe) {
if (val: { self.selectInput(0) catch break :val true; break :val false; }) { // output items of arrayList arg
std.debug.assert(e == .read);
for (al.?.items) |i| {
try self.output(i);
}
} else { // read elements from pipe and append to passed arrayList
std.debug.assert(e == .write or e == .append);
self.err = error.ok;
loop: {
var i: u32 = 0;
if (e == .write)
try al.?.resize(0);
while (true) : (i += 1) {
const d = self.peekTo(T) catch {
break :loop;
};
try al.?.append(d);
_ = try self.readTo(T);
}
}
// if output stream connected out a copy of the arrayList onto it
if (val: { self.selectOutput(0) catch break :val false; break :val true; }) {
var an = std.ArrayList(T).init(al.?.allocator); // use the original arraylist's allocator
try an.appendSlice(al.?.items);
try self.output(an);
} else
self.err = error.ok;
}
} else { // read arrayList(s) from pipe and output elements
std.debug.assert(al == null);
self.err = error.ok;
while (true) {
//std.debug.print("peekto ArrayList\n",.{});
const d = try self.peekTo(std.ArrayList(T));
// std.debug.print("ArrayList {any}\n",.{d});
for (d.items) |i| {
_ = try self.output(i);
}
_ = try self.readTo(std.ArrayList(T));
}
}
return self.ok();
}
pub fn variable(self: *S, v: *T) callconv(.Async) !void {
defer
self.endStage();
if (debugStart) std.log.info("start {}_{s}", .{ self.i, self.name });
if (val: { self.selectInput(0) catch { break :val true; }; break :val false; }) {
try self.output(v.*);
} else {
v.* = try self.peekTo(T);
_ = try self.readTo(S.TU);
}
while (true) {
const d = self.peekTo(S.TU) catch break;
self.output(d) catch break;
_ = self.readTo(S.TU) catch break;
}
return self.ok();
}
pub fn console(self: *S) callconv(.Async) !void {
defer
self.endStage();
const stdout = std.io.getStdOut().writer();
if (debugStart) std.log.info("start {}_{s}", .{ self.i, self.name });
while (true) {
if (debugStages) std.log.info("console in {}_{s} {*}", .{ self.i, self.name, self.inC });
if (try self.typeIs(T)) {
const e = try self.peekTo(T);
try stdout.print("{any} ", .{e});
self.output(e) catch { self.err = error.ok; };
_ = try self.readTo(T);
} else if (try self.typeIs(*[]T)) {
const e = try self.peekTo(*[]T);
try stdout.print("{any} ", .{e});
self.output(e) catch { self.err = error.ok; };
_ = try self.readTo(*[]T);
} else if (try self.typeIs(std.ArrayList(T))) {
const e = try self.peekTo(std.ArrayList(T));
try stdout.print("{any} ", .{e});
self.output(e) catch { self.err = error.ok; };
_ = try self.readTo(std.ArrayList(T));
} else if (try self.typeIs([]const u8)) {
const e = try self.peekTo([]const u8);
try stdout.print("{s} ", .{e});
self.output(e) catch { self.err = error.ok; };
_ = try self.readTo([]const u8);
} else if (try self.typeIs([:0]const u8)) {
const e = try self.peekTo([:0]const u8);
try stdout.print("{s} ", .{e});
self.output(e) catch { self.err = error.ok; };
_ = try self.readTo([:0]const u8);
} else {
const e = try self.peekTo(S.TU);
try stdout.print("{any} ", .{e});
self.output(e) catch { self.err = error.ok; };
_ = try self.readTo(std.ArrayList(T));
}
}
return self.ok();
}
pub fn fanin(self: *S) callconv(.Async) !void {
defer
self.endStage();
if (debugStart) std.log.info("start {}_{s}", .{ self.i, self.name });
var done:bool = false;
var s:u32 = try self.inStream();
self.selectInput(s) catch |e| {
if (e == error.noInStream) done = true;
};
while (!done) {
if (debugStages) std.log.info("fanin {}_{s} {*} {*}", .{ self.i, self.name, self.inC, self.outC });
while (true) {
const tmp = try self.peekTo(S.TU);
try self.output(tmp);
_ = try self.readTo(S.TU);
}
s += 1;
self.selectInput(s) catch {
done = true;
};
}
return;
}
pub fn faninany(self: *S) callconv(.Async) !void {
defer
self.endStage();
if (debugStart) std.log.info("start {}_{s}", .{ self.i, self.name });
while (true) {
_ = try self.selectAnyInput();
if (debugStages) std.log.info("faninany {}_{s} {*} {*}", .{ self.i, self.name, self.inC, self.outC });
const tmp = try self.peekTo(S.TU);
try self.output(tmp);
_ = try self.readTo(S.TU);
}
return self.ok;
}
pub fn copy(self: *S) callconv(.Async) !void {
defer
self.endStage();
if (debugStart) std.log.info("start {}_{s}", .{ self.i, self.name });
while (true) {
const tmp = self.peekTo(S.TU) catch break;
self.output(tmp) catch break;
_ = self.readTo(S.TU) catch break;
}
return self.ok();
}
pub fn gen(self: *S, limit: T) callconv(.Async) !void {
defer
self.endStage();
//std.debug.print("{*}\n",.{@intToPtr(S.PS.getPT(), self.pipeAddr)}); // extract a PipeType
if (debugStart) std.log.info("start {}_{s}", .{ self.i, self.name });
var i: T = 0;
while (i < limit) : (i += 1) {
if (debugStages) std.log.info("gen out {}_{s} {*}", .{ self.i, self.name, self.outC });
try self.output(i);
}
}
pub fn replace(self: *S, with: T) callconv(.Async) !void {
defer
self.endStage();
if (debugStart) std.log.info("start {}_{s}", .{ self.i, self.name });
while (true) {
_ = self.peekTo(S.TU) catch break;
self.output(with) catch break;
_ = self.readTo(S.TU) catch break;
}
return self.ok();
}
};
} | filters.zig |
const std = @import("std");
const Builder = std.build.Builder;
pub fn createPackage(comptime root: []const u8) std.build.Pkg {
return std.build.Pkg{
.name = "lola",
.path = root ++ "/src/library/main.zig",
.dependencies = &[_]std.build.Pkg{
std.build.Pkg{
.name = "interface",
.path = root ++ "/libs/interface.zig/interface.zig",
.dependencies = &[_]std.build.Pkg{},
},
},
};
}
const linkPcre = @import("libs/koino/vendor/libpcre.zig/build.zig").linkPcre;
const pkgs = struct {
const args = std.build.Pkg{
.name = "args",
.path = "libs/args/args.zig",
.dependencies = &[_]std.build.Pkg{},
};
const interface = std.build.Pkg{
.name = "interface",
.path = "libs/interface.zig/interface.zig",
.dependencies = &[_]std.build.Pkg{},
};
const lola = std.build.Pkg{
.name = "lola",
.path = "src/library/main.zig",
.dependencies = &[_]std.build.Pkg{
interface,
},
};
const koino = std.build.Pkg{
.name = "koino",
.path = "libs/koino/src/koino.zig",
.dependencies = &[_]std.build.Pkg{
std.build.Pkg{ .name = "libpcre", .path = "libs/koino/vendor/libpcre.zig/src/main.zig" },
std.build.Pkg{ .name = "htmlentities", .path = "libs/koino/vendor/htmlentities.zig/src/main.zig" },
std.build.Pkg{ .name = "clap", .path = "libs/koino/vendor/zig-clap/clap.zig" },
std.build.Pkg{ .name = "zunicode", .path = "libs/koino/vendor/zunicode/src/zunicode.zig" },
},
};
const zee_alloc = std.build.Pkg{
.name = "zee_alloc",
.path = "libs/zee_alloc/src/main.zig",
};
};
const Example = struct {
name: []const u8,
path: []const u8,
};
const examples = [_]Example{
Example{
.name = "minimal-host",
.path = "examples/host/minimal-host/main.zig",
},
Example{
.name = "multi-environment",
.path = "examples/host/multi-environment/main.zig",
},
Example{
.name = "serialization",
.path = "examples/host/serialization/main.zig",
},
};
pub fn build(b: *Builder) !void {
const version_tag = b.option([]const u8, "version", "Sets the version displayed in the docs and for `lola version`");
const mode = b.standardReleaseOptions();
const target = b.standardTargetOptions(.{
.default_target = if (std.builtin.os.tag == .windows)
std.zig.CrossTarget.parse(.{ .arch_os_abi = "native-native-gnu" }) catch unreachable
else if (std.builtin.os.tag == .linux)
std.zig.CrossTarget.fromTarget(.{
.cpu = std.builtin.cpu,
.os = std.builtin.os,
.abi = .musl,
})
else
std.zig.CrossTarget{},
});
const exe = b.addExecutable("lola", "src/frontend/main.zig");
exe.setBuildMode(mode);
exe.setTarget(target);
exe.addPackage(pkgs.lola);
exe.addPackage(pkgs.args);
exe.addBuildOption([]const u8, "version", version_tag orelse "development");
exe.install();
const wasm_runtime = b.addStaticLibrary("lola", "src/wasm-compiler/main.zig");
wasm_runtime.addPackage(pkgs.lola);
wasm_runtime.addPackage(pkgs.zee_alloc);
wasm_runtime.setTarget(.{ .cpu_arch = .wasm32, .os_tag = .freestanding });
wasm_runtime.setBuildMode(.ReleaseSafe);
wasm_runtime.install();
const examples_step = b.step("examples", "Compiles all examples");
inline for (examples) |example| {
const example_exe = b.addExecutable("example-" ++ example.name, example.path);
example_exe.setBuildMode(mode);
example_exe.setTarget(target);
example_exe.addPackage(pkgs.lola);
examples_step.dependOn(&b.addInstallArtifact(example_exe).step);
}
var main_tests = b.addTest("src/library/test.zig");
if (pkgs.lola.dependencies) |deps| {
for (deps) |pkg| {
main_tests.addPackage(pkg);
}
}
main_tests.setBuildMode(mode);
const test_step = b.step("test", "Run test suite");
test_step.dependOn(&main_tests.step);
// Run compiler test suites
{
const prefix = "src/test/";
const behaviour_tests = exe.run();
behaviour_tests.addArg("run");
behaviour_tests.addArg("--no-stdlib"); // we don't want the behaviour tests to be run with any stdlib functions
behaviour_tests.addArg(prefix ++ "behaviour.lola");
behaviour_tests.expectStdOutEqual("Behaviour test suite passed.\n");
test_step.dependOn(&behaviour_tests.step);
const stdib_test = exe.run();
stdib_test.addArg("run");
stdib_test.addArg(prefix ++ "stdlib.lola");
stdib_test.expectStdOutEqual("Standard library test suite passed.\n");
test_step.dependOn(&stdib_test.step);
// when the host is windows, this won't work :(
if (std.builtin.os.tag != .windows) {
std.fs.cwd().makeDir("zig-cache/tmp") catch |err| switch (err) {
error.PathAlreadyExists => {}, // nice
else => |e| return e,
};
const runlib_test = exe.run();
// execute in the zig-cache directory so we have a "safe" playfield
// for file I/O
runlib_test.cwd = "zig-cache/tmp";
// `Exit(123)` is the last call in the runtime suite
runlib_test.expected_exit_code = 123;
runlib_test.expectStdOutEqual(
\\
\\1
\\1.2
\\[ ]
\\[ 1, 2 ]
\\truefalse
\\hello
\\Runtime library test suite passed.
\\
);
runlib_test.addArg("run");
runlib_test.addArg("../../" ++ prefix ++ "runtime.lola");
test_step.dependOn(&runlib_test.step);
}
const emptyfile_test = exe.run();
emptyfile_test.addArg("run");
emptyfile_test.addArg(prefix ++ "empty.lola");
emptyfile_test.expectStdOutEqual("");
test_step.dependOn(&emptyfile_test.step);
const globreturn_test = exe.run();
globreturn_test.addArg("run");
globreturn_test.addArg(prefix ++ "global-return.lola");
globreturn_test.expectStdOutEqual("");
test_step.dependOn(&globreturn_test.step);
const extended_behaviour_test = exe.run();
extended_behaviour_test.addArg("run");
extended_behaviour_test.addArg(prefix ++ "behaviour-with-stdlib.lola");
extended_behaviour_test.expectStdOutEqual("Extended behaviour test suite passed.\n");
test_step.dependOn(&extended_behaviour_test.step);
const compiler_test = exe.run();
compiler_test.addArg("compile");
compiler_test.addArg("--verify"); // verify should not emit a compiled module
compiler_test.addArg(prefix ++ "compiler.lola");
compiler_test.expectStdOutEqual("");
test_step.dependOn(&compiler_test.step);
}
const run_cmd = exe.run();
run_cmd.step.dependOn(b.getInstallStep());
const run_step = b.step("run", "Run the app");
run_step.dependOn(&run_cmd.step);
/////////////////////////////////////////////////////////////////////////
// Documentation and Website generation:
// this is disabed by-default so we don't depend on any vcpkgs
if (b.option(bool, "enable-website", "Enables website generation.") orelse false) {
// Generates documentation and future files.
const gen_website_step = b.step("website", "Generates the website and all required resources.");
// TODO: Figure out how to emit docs into the right directory
// var gen_docs_runner = b.addTest("src/library/main.zig");
// gen_docs_runner.emit_bin = false;
// gen_docs_runner.emit_docs = true;
// gen_docs_runner.setOutputDir("./website");
// gen_docs_runner.setBuildMode(mode);
const gen_docs_runner = b.addSystemCommand(&[_][]const u8{
"zig",
"test",
pkgs.lola.path,
"-femit-docs",
"-fno-emit-bin",
"--output-dir",
"website/",
"--pkg-begin",
"interface",
pkgs.interface.path,
"--pkg-end",
});
// Only generates documentation
const gen_docs_step = b.step("docs", "Generate the code documentation");
gen_docs_step.dependOn(&gen_docs_runner.step);
gen_website_step.dependOn(&gen_docs_runner.step);
const md_renderer = b.addExecutable("markdown-md-page", "src/tools/render-md-page.zig");
md_renderer.addPackage(pkgs.koino);
try linkPcre(md_renderer);
const render = md_renderer.run();
render.addArg(version_tag orelse "development");
gen_website_step.dependOn(&render.step);
const copy_wasm_runtime = b.addSystemCommand(&[_][]const u8{
"cp",
});
copy_wasm_runtime.addArtifactArg(wasm_runtime);
copy_wasm_runtime.addArg("website/lola.wasm");
gen_website_step.dependOn(©_wasm_runtime.step);
}
} | build.zig |
pub const DMO_E_INVALIDSTREAMINDEX = @import("../zig.zig").typedConst(HRESULT, @as(i32, -2147220991));
pub const DMO_E_INVALIDTYPE = @import("../zig.zig").typedConst(HRESULT, @as(i32, -2147220990));
pub const DMO_E_TYPE_NOT_SET = @import("../zig.zig").typedConst(HRESULT, @as(i32, -2147220989));
pub const DMO_E_NOTACCEPTING = @import("../zig.zig").typedConst(HRESULT, @as(i32, -2147220988));
pub const DMO_E_TYPE_NOT_ACCEPTED = @import("../zig.zig").typedConst(HRESULT, @as(i32, -2147220987));
pub const DMO_E_NO_MORE_ITEMS = @import("../zig.zig").typedConst(HRESULT, @as(i32, -2147220986));
pub const DMOCATEGORY_AUDIO_DECODER = Guid.initString("57f2db8b-e6bb-4513-9d43-dcd2a6593125");
pub const DMOCATEGORY_AUDIO_ENCODER = Guid.initString("33d9a761-90c8-11d0-bd43-00a0c911ce86");
pub const DMOCATEGORY_VIDEO_DECODER = Guid.initString("4a69b442-28be-4991-969c-b500adf5d8a8");
pub const DMOCATEGORY_VIDEO_ENCODER = Guid.initString("33d9a760-90c8-11d0-bd43-00a0c911ce86");
pub const DMOCATEGORY_AUDIO_EFFECT = Guid.initString("f3602b3f-0592-48df-a4cd-674721e7ebeb");
pub const DMOCATEGORY_VIDEO_EFFECT = Guid.initString("d990ee14-776c-4723-be46-3da2f56f10b9");
pub const DMOCATEGORY_AUDIO_CAPTURE_EFFECT = Guid.initString("f665aaba-3e09-4920-aa5f-219811148f09");
pub const DMOCATEGORY_ACOUSTIC_ECHO_CANCEL = Guid.initString("bf963d80-c559-11d0-8a2b-00a0c9255ac1");
pub const DMOCATEGORY_AUDIO_NOISE_SUPPRESS = Guid.initString("e07f903f-62fd-4e60-8cdd-dea7236665b5");
pub const DMOCATEGORY_AGC = Guid.initString("e88c9ba0-c557-11d0-8a2b-00a0c9255ac1");
//--------------------------------------------------------------------------------
// Section: Types (21)
//--------------------------------------------------------------------------------
pub const DMO_MEDIA_TYPE = extern struct {
majortype: Guid,
subtype: Guid,
bFixedSizeSamples: BOOL,
bTemporalCompression: BOOL,
lSampleSize: u32,
formattype: Guid,
pUnk: ?*IUnknown,
cbFormat: u32,
pbFormat: ?*u8,
};
pub const _DMO_INPUT_DATA_BUFFER_FLAGS = enum(i32) {
SYNCPOINT = 1,
TIME = 2,
TIMELENGTH = 4,
DISCONTINUITY = 8,
};
pub const DMO_INPUT_DATA_BUFFERF_SYNCPOINT = _DMO_INPUT_DATA_BUFFER_FLAGS.SYNCPOINT;
pub const DMO_INPUT_DATA_BUFFERF_TIME = _DMO_INPUT_DATA_BUFFER_FLAGS.TIME;
pub const DMO_INPUT_DATA_BUFFERF_TIMELENGTH = _DMO_INPUT_DATA_BUFFER_FLAGS.TIMELENGTH;
pub const DMO_INPUT_DATA_BUFFERF_DISCONTINUITY = _DMO_INPUT_DATA_BUFFER_FLAGS.DISCONTINUITY;
pub const _DMO_OUTPUT_DATA_BUFFER_FLAGS = enum(i32) {
SYNCPOINT = 1,
TIME = 2,
TIMELENGTH = 4,
DISCONTINUITY = 8,
INCOMPLETE = 16777216,
};
pub const DMO_OUTPUT_DATA_BUFFERF_SYNCPOINT = _DMO_OUTPUT_DATA_BUFFER_FLAGS.SYNCPOINT;
pub const DMO_OUTPUT_DATA_BUFFERF_TIME = _DMO_OUTPUT_DATA_BUFFER_FLAGS.TIME;
pub const DMO_OUTPUT_DATA_BUFFERF_TIMELENGTH = _DMO_OUTPUT_DATA_BUFFER_FLAGS.TIMELENGTH;
pub const DMO_OUTPUT_DATA_BUFFERF_DISCONTINUITY = _DMO_OUTPUT_DATA_BUFFER_FLAGS.DISCONTINUITY;
pub const DMO_OUTPUT_DATA_BUFFERF_INCOMPLETE = _DMO_OUTPUT_DATA_BUFFER_FLAGS.INCOMPLETE;
pub const _DMO_INPUT_STATUS_FLAGS = enum(i32) {
A = 1,
};
pub const DMO_INPUT_STATUSF_ACCEPT_DATA = _DMO_INPUT_STATUS_FLAGS.A;
pub const _DMO_INPUT_STREAM_INFO_FLAGS = enum(i32) {
WHOLE_SAMPLES = 1,
SINGLE_SAMPLE_PER_BUFFER = 2,
FIXED_SAMPLE_SIZE = 4,
HOLDS_BUFFERS = 8,
};
pub const DMO_INPUT_STREAMF_WHOLE_SAMPLES = _DMO_INPUT_STREAM_INFO_FLAGS.WHOLE_SAMPLES;
pub const DMO_INPUT_STREAMF_SINGLE_SAMPLE_PER_BUFFER = _DMO_INPUT_STREAM_INFO_FLAGS.SINGLE_SAMPLE_PER_BUFFER;
pub const DMO_INPUT_STREAMF_FIXED_SAMPLE_SIZE = _DMO_INPUT_STREAM_INFO_FLAGS.FIXED_SAMPLE_SIZE;
pub const DMO_INPUT_STREAMF_HOLDS_BUFFERS = _DMO_INPUT_STREAM_INFO_FLAGS.HOLDS_BUFFERS;
pub const _DMO_OUTPUT_STREAM_INFO_FLAGS = enum(i32) {
WHOLE_SAMPLES = 1,
SINGLE_SAMPLE_PER_BUFFER = 2,
FIXED_SAMPLE_SIZE = 4,
DISCARDABLE = 8,
OPTIONAL = 16,
};
pub const DMO_OUTPUT_STREAMF_WHOLE_SAMPLES = _DMO_OUTPUT_STREAM_INFO_FLAGS.WHOLE_SAMPLES;
pub const DMO_OUTPUT_STREAMF_SINGLE_SAMPLE_PER_BUFFER = _DMO_OUTPUT_STREAM_INFO_FLAGS.SINGLE_SAMPLE_PER_BUFFER;
pub const DMO_OUTPUT_STREAMF_FIXED_SAMPLE_SIZE = _DMO_OUTPUT_STREAM_INFO_FLAGS.FIXED_SAMPLE_SIZE;
pub const DMO_OUTPUT_STREAMF_DISCARDABLE = _DMO_OUTPUT_STREAM_INFO_FLAGS.DISCARDABLE;
pub const DMO_OUTPUT_STREAMF_OPTIONAL = _DMO_OUTPUT_STREAM_INFO_FLAGS.OPTIONAL;
pub const _DMO_SET_TYPE_FLAGS = enum(i32) {
TEST_ONLY = 1,
CLEAR = 2,
};
pub const DMO_SET_TYPEF_TEST_ONLY = _DMO_SET_TYPE_FLAGS.TEST_ONLY;
pub const DMO_SET_TYPEF_CLEAR = _DMO_SET_TYPE_FLAGS.CLEAR;
pub const _DMO_PROCESS_OUTPUT_FLAGS = enum(i32) {
R = 1,
};
pub const DMO_PROCESS_OUTPUT_DISCARD_WHEN_NO_BUFFER = _DMO_PROCESS_OUTPUT_FLAGS.R;
const IID_IMediaBuffer_Value = Guid.initString("59eff8b9-938c-4a26-82f2-95cb84cdc837");
pub const IID_IMediaBuffer = &IID_IMediaBuffer_Value;
pub const IMediaBuffer = extern struct {
pub const VTable = extern struct {
base: IUnknown.VTable,
SetLength: fn(
self: *const IMediaBuffer,
cbLength: u32,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
GetMaxLength: fn(
self: *const IMediaBuffer,
pcbMaxLength: ?*u32,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
GetBufferAndLength: fn(
self: *const IMediaBuffer,
ppBuffer: ?*?*u8,
pcbLength: ?*u32,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
};
vtable: *const VTable,
pub fn MethodMixin(comptime T: type) type { return struct {
pub usingnamespace IUnknown.MethodMixin(T);
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IMediaBuffer_SetLength(self: *const T, cbLength: u32) callconv(.Inline) HRESULT {
return @ptrCast(*const IMediaBuffer.VTable, self.vtable).SetLength(@ptrCast(*const IMediaBuffer, self), cbLength);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IMediaBuffer_GetMaxLength(self: *const T, pcbMaxLength: ?*u32) callconv(.Inline) HRESULT {
return @ptrCast(*const IMediaBuffer.VTable, self.vtable).GetMaxLength(@ptrCast(*const IMediaBuffer, self), pcbMaxLength);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IMediaBuffer_GetBufferAndLength(self: *const T, ppBuffer: ?*?*u8, pcbLength: ?*u32) callconv(.Inline) HRESULT {
return @ptrCast(*const IMediaBuffer.VTable, self.vtable).GetBufferAndLength(@ptrCast(*const IMediaBuffer, self), ppBuffer, pcbLength);
}
};}
pub usingnamespace MethodMixin(@This());
};
pub const DMO_OUTPUT_DATA_BUFFER = extern struct {
pBuffer: ?*IMediaBuffer,
dwStatus: u32,
rtTimestamp: i64,
rtTimelength: i64,
};
const IID_IMediaObject_Value = Guid.initString("d8ad0f58-5494-4102-97c5-ec798e59bcf4");
pub const IID_IMediaObject = &IID_IMediaObject_Value;
pub const IMediaObject = extern struct {
pub const VTable = extern struct {
base: IUnknown.VTable,
GetStreamCount: fn(
self: *const IMediaObject,
pcInputStreams: ?*u32,
pcOutputStreams: ?*u32,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
GetInputStreamInfo: fn(
self: *const IMediaObject,
dwInputStreamIndex: u32,
pdwFlags: ?*u32,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
GetOutputStreamInfo: fn(
self: *const IMediaObject,
dwOutputStreamIndex: u32,
pdwFlags: ?*u32,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
GetInputType: fn(
self: *const IMediaObject,
dwInputStreamIndex: u32,
dwTypeIndex: u32,
pmt: ?*DMO_MEDIA_TYPE,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
GetOutputType: fn(
self: *const IMediaObject,
dwOutputStreamIndex: u32,
dwTypeIndex: u32,
pmt: ?*DMO_MEDIA_TYPE,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
SetInputType: fn(
self: *const IMediaObject,
dwInputStreamIndex: u32,
pmt: ?*const DMO_MEDIA_TYPE,
dwFlags: u32,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
SetOutputType: fn(
self: *const IMediaObject,
dwOutputStreamIndex: u32,
pmt: ?*const DMO_MEDIA_TYPE,
dwFlags: u32,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
GetInputCurrentType: fn(
self: *const IMediaObject,
dwInputStreamIndex: u32,
pmt: ?*DMO_MEDIA_TYPE,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
GetOutputCurrentType: fn(
self: *const IMediaObject,
dwOutputStreamIndex: u32,
pmt: ?*DMO_MEDIA_TYPE,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
GetInputSizeInfo: fn(
self: *const IMediaObject,
dwInputStreamIndex: u32,
pcbSize: ?*u32,
pcbMaxLookahead: ?*u32,
pcbAlignment: ?*u32,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
GetOutputSizeInfo: fn(
self: *const IMediaObject,
dwOutputStreamIndex: u32,
pcbSize: ?*u32,
pcbAlignment: ?*u32,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
GetInputMaxLatency: fn(
self: *const IMediaObject,
dwInputStreamIndex: u32,
prtMaxLatency: ?*i64,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
SetInputMaxLatency: fn(
self: *const IMediaObject,
dwInputStreamIndex: u32,
rtMaxLatency: i64,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
Flush: fn(
self: *const IMediaObject,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
Discontinuity: fn(
self: *const IMediaObject,
dwInputStreamIndex: u32,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
AllocateStreamingResources: fn(
self: *const IMediaObject,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
FreeStreamingResources: fn(
self: *const IMediaObject,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
GetInputStatus: fn(
self: *const IMediaObject,
dwInputStreamIndex: u32,
dwFlags: ?*u32,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
ProcessInput: fn(
self: *const IMediaObject,
dwInputStreamIndex: u32,
pBuffer: ?*IMediaBuffer,
dwFlags: u32,
rtTimestamp: i64,
rtTimelength: i64,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
ProcessOutput: fn(
self: *const IMediaObject,
dwFlags: u32,
cOutputBufferCount: u32,
pOutputBuffers: [*]DMO_OUTPUT_DATA_BUFFER,
pdwStatus: ?*u32,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
Lock: fn(
self: *const IMediaObject,
bLock: i32,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
};
vtable: *const VTable,
pub fn MethodMixin(comptime T: type) type { return struct {
pub usingnamespace IUnknown.MethodMixin(T);
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IMediaObject_GetStreamCount(self: *const T, pcInputStreams: ?*u32, pcOutputStreams: ?*u32) callconv(.Inline) HRESULT {
return @ptrCast(*const IMediaObject.VTable, self.vtable).GetStreamCount(@ptrCast(*const IMediaObject, self), pcInputStreams, pcOutputStreams);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IMediaObject_GetInputStreamInfo(self: *const T, dwInputStreamIndex: u32, pdwFlags: ?*u32) callconv(.Inline) HRESULT {
return @ptrCast(*const IMediaObject.VTable, self.vtable).GetInputStreamInfo(@ptrCast(*const IMediaObject, self), dwInputStreamIndex, pdwFlags);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IMediaObject_GetOutputStreamInfo(self: *const T, dwOutputStreamIndex: u32, pdwFlags: ?*u32) callconv(.Inline) HRESULT {
return @ptrCast(*const IMediaObject.VTable, self.vtable).GetOutputStreamInfo(@ptrCast(*const IMediaObject, self), dwOutputStreamIndex, pdwFlags);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IMediaObject_GetInputType(self: *const T, dwInputStreamIndex: u32, dwTypeIndex: u32, pmt: ?*DMO_MEDIA_TYPE) callconv(.Inline) HRESULT {
return @ptrCast(*const IMediaObject.VTable, self.vtable).GetInputType(@ptrCast(*const IMediaObject, self), dwInputStreamIndex, dwTypeIndex, pmt);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IMediaObject_GetOutputType(self: *const T, dwOutputStreamIndex: u32, dwTypeIndex: u32, pmt: ?*DMO_MEDIA_TYPE) callconv(.Inline) HRESULT {
return @ptrCast(*const IMediaObject.VTable, self.vtable).GetOutputType(@ptrCast(*const IMediaObject, self), dwOutputStreamIndex, dwTypeIndex, pmt);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IMediaObject_SetInputType(self: *const T, dwInputStreamIndex: u32, pmt: ?*const DMO_MEDIA_TYPE, dwFlags: u32) callconv(.Inline) HRESULT {
return @ptrCast(*const IMediaObject.VTable, self.vtable).SetInputType(@ptrCast(*const IMediaObject, self), dwInputStreamIndex, pmt, dwFlags);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IMediaObject_SetOutputType(self: *const T, dwOutputStreamIndex: u32, pmt: ?*const DMO_MEDIA_TYPE, dwFlags: u32) callconv(.Inline) HRESULT {
return @ptrCast(*const IMediaObject.VTable, self.vtable).SetOutputType(@ptrCast(*const IMediaObject, self), dwOutputStreamIndex, pmt, dwFlags);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IMediaObject_GetInputCurrentType(self: *const T, dwInputStreamIndex: u32, pmt: ?*DMO_MEDIA_TYPE) callconv(.Inline) HRESULT {
return @ptrCast(*const IMediaObject.VTable, self.vtable).GetInputCurrentType(@ptrCast(*const IMediaObject, self), dwInputStreamIndex, pmt);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IMediaObject_GetOutputCurrentType(self: *const T, dwOutputStreamIndex: u32, pmt: ?*DMO_MEDIA_TYPE) callconv(.Inline) HRESULT {
return @ptrCast(*const IMediaObject.VTable, self.vtable).GetOutputCurrentType(@ptrCast(*const IMediaObject, self), dwOutputStreamIndex, pmt);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IMediaObject_GetInputSizeInfo(self: *const T, dwInputStreamIndex: u32, pcbSize: ?*u32, pcbMaxLookahead: ?*u32, pcbAlignment: ?*u32) callconv(.Inline) HRESULT {
return @ptrCast(*const IMediaObject.VTable, self.vtable).GetInputSizeInfo(@ptrCast(*const IMediaObject, self), dwInputStreamIndex, pcbSize, pcbMaxLookahead, pcbAlignment);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IMediaObject_GetOutputSizeInfo(self: *const T, dwOutputStreamIndex: u32, pcbSize: ?*u32, pcbAlignment: ?*u32) callconv(.Inline) HRESULT {
return @ptrCast(*const IMediaObject.VTable, self.vtable).GetOutputSizeInfo(@ptrCast(*const IMediaObject, self), dwOutputStreamIndex, pcbSize, pcbAlignment);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IMediaObject_GetInputMaxLatency(self: *const T, dwInputStreamIndex: u32, prtMaxLatency: ?*i64) callconv(.Inline) HRESULT {
return @ptrCast(*const IMediaObject.VTable, self.vtable).GetInputMaxLatency(@ptrCast(*const IMediaObject, self), dwInputStreamIndex, prtMaxLatency);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IMediaObject_SetInputMaxLatency(self: *const T, dwInputStreamIndex: u32, rtMaxLatency: i64) callconv(.Inline) HRESULT {
return @ptrCast(*const IMediaObject.VTable, self.vtable).SetInputMaxLatency(@ptrCast(*const IMediaObject, self), dwInputStreamIndex, rtMaxLatency);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IMediaObject_Flush(self: *const T) callconv(.Inline) HRESULT {
return @ptrCast(*const IMediaObject.VTable, self.vtable).Flush(@ptrCast(*const IMediaObject, self));
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IMediaObject_Discontinuity(self: *const T, dwInputStreamIndex: u32) callconv(.Inline) HRESULT {
return @ptrCast(*const IMediaObject.VTable, self.vtable).Discontinuity(@ptrCast(*const IMediaObject, self), dwInputStreamIndex);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IMediaObject_AllocateStreamingResources(self: *const T) callconv(.Inline) HRESULT {
return @ptrCast(*const IMediaObject.VTable, self.vtable).AllocateStreamingResources(@ptrCast(*const IMediaObject, self));
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IMediaObject_FreeStreamingResources(self: *const T) callconv(.Inline) HRESULT {
return @ptrCast(*const IMediaObject.VTable, self.vtable).FreeStreamingResources(@ptrCast(*const IMediaObject, self));
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IMediaObject_GetInputStatus(self: *const T, dwInputStreamIndex: u32, dwFlags: ?*u32) callconv(.Inline) HRESULT {
return @ptrCast(*const IMediaObject.VTable, self.vtable).GetInputStatus(@ptrCast(*const IMediaObject, self), dwInputStreamIndex, dwFlags);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IMediaObject_ProcessInput(self: *const T, dwInputStreamIndex: u32, pBuffer: ?*IMediaBuffer, dwFlags: u32, rtTimestamp: i64, rtTimelength: i64) callconv(.Inline) HRESULT {
return @ptrCast(*const IMediaObject.VTable, self.vtable).ProcessInput(@ptrCast(*const IMediaObject, self), dwInputStreamIndex, pBuffer, dwFlags, rtTimestamp, rtTimelength);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IMediaObject_ProcessOutput(self: *const T, dwFlags: u32, cOutputBufferCount: u32, pOutputBuffers: [*]DMO_OUTPUT_DATA_BUFFER, pdwStatus: ?*u32) callconv(.Inline) HRESULT {
return @ptrCast(*const IMediaObject.VTable, self.vtable).ProcessOutput(@ptrCast(*const IMediaObject, self), dwFlags, cOutputBufferCount, pOutputBuffers, pdwStatus);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IMediaObject_Lock(self: *const T, bLock: i32) callconv(.Inline) HRESULT {
return @ptrCast(*const IMediaObject.VTable, self.vtable).Lock(@ptrCast(*const IMediaObject, self), bLock);
}
};}
pub usingnamespace MethodMixin(@This());
};
const IID_IEnumDMO_Value = Guid.initString("2c3cd98a-2bfa-4a53-9c27-5249ba64ba0f");
pub const IID_IEnumDMO = &IID_IEnumDMO_Value;
pub const IEnumDMO = extern struct {
pub const VTable = extern struct {
base: IUnknown.VTable,
Next: fn(
self: *const IEnumDMO,
cItemsToFetch: u32,
pCLSID: [*]Guid,
Names: [*]?PWSTR,
pcItemsFetched: ?*u32,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
Skip: fn(
self: *const IEnumDMO,
cItemsToSkip: u32,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
Reset: fn(
self: *const IEnumDMO,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
Clone: fn(
self: *const IEnumDMO,
ppEnum: ?*?*IEnumDMO,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
};
vtable: *const VTable,
pub fn MethodMixin(comptime T: type) type { return struct {
pub usingnamespace IUnknown.MethodMixin(T);
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IEnumDMO_Next(self: *const T, cItemsToFetch: u32, pCLSID: [*]Guid, Names: [*]?PWSTR, pcItemsFetched: ?*u32) callconv(.Inline) HRESULT {
return @ptrCast(*const IEnumDMO.VTable, self.vtable).Next(@ptrCast(*const IEnumDMO, self), cItemsToFetch, pCLSID, Names, pcItemsFetched);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IEnumDMO_Skip(self: *const T, cItemsToSkip: u32) callconv(.Inline) HRESULT {
return @ptrCast(*const IEnumDMO.VTable, self.vtable).Skip(@ptrCast(*const IEnumDMO, self), cItemsToSkip);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IEnumDMO_Reset(self: *const T) callconv(.Inline) HRESULT {
return @ptrCast(*const IEnumDMO.VTable, self.vtable).Reset(@ptrCast(*const IEnumDMO, self));
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IEnumDMO_Clone(self: *const T, ppEnum: ?*?*IEnumDMO) callconv(.Inline) HRESULT {
return @ptrCast(*const IEnumDMO.VTable, self.vtable).Clone(@ptrCast(*const IEnumDMO, self), ppEnum);
}
};}
pub usingnamespace MethodMixin(@This());
};
pub const _DMO_INPLACE_PROCESS_FLAGS = enum(i32) {
NORMAL = 0,
ZERO = 1,
};
pub const DMO_INPLACE_NORMAL = _DMO_INPLACE_PROCESS_FLAGS.NORMAL;
pub const DMO_INPLACE_ZERO = _DMO_INPLACE_PROCESS_FLAGS.ZERO;
const IID_IMediaObjectInPlace_Value = Guid.initString("651b9ad0-0fc7-4aa9-9538-d89931010741");
pub const IID_IMediaObjectInPlace = &IID_IMediaObjectInPlace_Value;
pub const IMediaObjectInPlace = extern struct {
pub const VTable = extern struct {
base: IUnknown.VTable,
Process: fn(
self: *const IMediaObjectInPlace,
ulSize: u32,
// TODO: what to do with BytesParamIndex 0?
pData: ?*u8,
refTimeStart: i64,
dwFlags: u32,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
Clone: fn(
self: *const IMediaObjectInPlace,
ppMediaObject: ?*?*IMediaObjectInPlace,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
GetLatency: fn(
self: *const IMediaObjectInPlace,
pLatencyTime: ?*i64,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
};
vtable: *const VTable,
pub fn MethodMixin(comptime T: type) type { return struct {
pub usingnamespace IUnknown.MethodMixin(T);
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IMediaObjectInPlace_Process(self: *const T, ulSize: u32, pData: ?*u8, refTimeStart: i64, dwFlags: u32) callconv(.Inline) HRESULT {
return @ptrCast(*const IMediaObjectInPlace.VTable, self.vtable).Process(@ptrCast(*const IMediaObjectInPlace, self), ulSize, pData, refTimeStart, dwFlags);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IMediaObjectInPlace_Clone(self: *const T, ppMediaObject: ?*?*IMediaObjectInPlace) callconv(.Inline) HRESULT {
return @ptrCast(*const IMediaObjectInPlace.VTable, self.vtable).Clone(@ptrCast(*const IMediaObjectInPlace, self), ppMediaObject);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IMediaObjectInPlace_GetLatency(self: *const T, pLatencyTime: ?*i64) callconv(.Inline) HRESULT {
return @ptrCast(*const IMediaObjectInPlace.VTable, self.vtable).GetLatency(@ptrCast(*const IMediaObjectInPlace, self), pLatencyTime);
}
};}
pub usingnamespace MethodMixin(@This());
};
pub const _DMO_QUALITY_STATUS_FLAGS = enum(i32) {
D = 1,
};
pub const DMO_QUALITY_STATUS_ENABLED = _DMO_QUALITY_STATUS_FLAGS.D;
const IID_IDMOQualityControl_Value = Guid.initString("65abea96-cf36-453f-af8a-705e98f16260");
pub const IID_IDMOQualityControl = &IID_IDMOQualityControl_Value;
pub const IDMOQualityControl = extern struct {
pub const VTable = extern struct {
base: IUnknown.VTable,
SetNow: fn(
self: *const IDMOQualityControl,
rtNow: i64,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
SetStatus: fn(
self: *const IDMOQualityControl,
dwFlags: u32,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
GetStatus: fn(
self: *const IDMOQualityControl,
pdwFlags: ?*u32,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
};
vtable: *const VTable,
pub fn MethodMixin(comptime T: type) type { return struct {
pub usingnamespace IUnknown.MethodMixin(T);
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IDMOQualityControl_SetNow(self: *const T, rtNow: i64) callconv(.Inline) HRESULT {
return @ptrCast(*const IDMOQualityControl.VTable, self.vtable).SetNow(@ptrCast(*const IDMOQualityControl, self), rtNow);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IDMOQualityControl_SetStatus(self: *const T, dwFlags: u32) callconv(.Inline) HRESULT {
return @ptrCast(*const IDMOQualityControl.VTable, self.vtable).SetStatus(@ptrCast(*const IDMOQualityControl, self), dwFlags);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IDMOQualityControl_GetStatus(self: *const T, pdwFlags: ?*u32) callconv(.Inline) HRESULT {
return @ptrCast(*const IDMOQualityControl.VTable, self.vtable).GetStatus(@ptrCast(*const IDMOQualityControl, self), pdwFlags);
}
};}
pub usingnamespace MethodMixin(@This());
};
pub const _DMO_VIDEO_OUTPUT_STREAM_FLAGS = enum(i32) {
E = 1,
};
pub const DMO_VOSF_NEEDS_PREVIOUS_SAMPLE = _DMO_VIDEO_OUTPUT_STREAM_FLAGS.E;
const IID_IDMOVideoOutputOptimizations_Value = Guid.initString("be8f4f4e-5b16-4d29-b350-7f6b5d9298ac");
pub const IID_IDMOVideoOutputOptimizations = &IID_IDMOVideoOutputOptimizations_Value;
pub const IDMOVideoOutputOptimizations = extern struct {
pub const VTable = extern struct {
base: IUnknown.VTable,
QueryOperationModePreferences: fn(
self: *const IDMOVideoOutputOptimizations,
ulOutputStreamIndex: u32,
pdwRequestedCapabilities: ?*u32,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
SetOperationMode: fn(
self: *const IDMOVideoOutputOptimizations,
ulOutputStreamIndex: u32,
dwEnabledFeatures: u32,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
GetCurrentOperationMode: fn(
self: *const IDMOVideoOutputOptimizations,
ulOutputStreamIndex: u32,
pdwEnabledFeatures: ?*u32,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
GetCurrentSampleRequirements: fn(
self: *const IDMOVideoOutputOptimizations,
ulOutputStreamIndex: u32,
pdwRequestedFeatures: ?*u32,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
};
vtable: *const VTable,
pub fn MethodMixin(comptime T: type) type { return struct {
pub usingnamespace IUnknown.MethodMixin(T);
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IDMOVideoOutputOptimizations_QueryOperationModePreferences(self: *const T, ulOutputStreamIndex: u32, pdwRequestedCapabilities: ?*u32) callconv(.Inline) HRESULT {
return @ptrCast(*const IDMOVideoOutputOptimizations.VTable, self.vtable).QueryOperationModePreferences(@ptrCast(*const IDMOVideoOutputOptimizations, self), ulOutputStreamIndex, pdwRequestedCapabilities);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IDMOVideoOutputOptimizations_SetOperationMode(self: *const T, ulOutputStreamIndex: u32, dwEnabledFeatures: u32) callconv(.Inline) HRESULT {
return @ptrCast(*const IDMOVideoOutputOptimizations.VTable, self.vtable).SetOperationMode(@ptrCast(*const IDMOVideoOutputOptimizations, self), ulOutputStreamIndex, dwEnabledFeatures);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IDMOVideoOutputOptimizations_GetCurrentOperationMode(self: *const T, ulOutputStreamIndex: u32, pdwEnabledFeatures: ?*u32) callconv(.Inline) HRESULT {
return @ptrCast(*const IDMOVideoOutputOptimizations.VTable, self.vtable).GetCurrentOperationMode(@ptrCast(*const IDMOVideoOutputOptimizations, self), ulOutputStreamIndex, pdwEnabledFeatures);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IDMOVideoOutputOptimizations_GetCurrentSampleRequirements(self: *const T, ulOutputStreamIndex: u32, pdwRequestedFeatures: ?*u32) callconv(.Inline) HRESULT {
return @ptrCast(*const IDMOVideoOutputOptimizations.VTable, self.vtable).GetCurrentSampleRequirements(@ptrCast(*const IDMOVideoOutputOptimizations, self), ulOutputStreamIndex, pdwRequestedFeatures);
}
};}
pub usingnamespace MethodMixin(@This());
};
pub const DMO_PARTIAL_MEDIATYPE = extern struct {
type: Guid,
subtype: Guid,
};
pub const DMO_REGISTER_FLAGS = enum(i32) {
D = 1,
};
pub const DMO_REGISTERF_IS_KEYED = DMO_REGISTER_FLAGS.D;
pub const DMO_ENUM_FLAGS = enum(i32) {
D = 1,
};
pub const DMO_ENUMF_INCLUDE_KEYED = DMO_ENUM_FLAGS.D;
//--------------------------------------------------------------------------------
// Section: Functions (11)
//--------------------------------------------------------------------------------
pub extern "msdmo" fn DMORegister(
szName: ?[*:0]const u16,
clsidDMO: ?*const Guid,
guidCategory: ?*const Guid,
dwFlags: u32,
cInTypes: u32,
pInTypes: ?*const DMO_PARTIAL_MEDIATYPE,
cOutTypes: u32,
pOutTypes: ?*const DMO_PARTIAL_MEDIATYPE,
) callconv(@import("std").os.windows.WINAPI) HRESULT;
pub extern "msdmo" fn DMOUnregister(
clsidDMO: ?*const Guid,
guidCategory: ?*const Guid,
) callconv(@import("std").os.windows.WINAPI) HRESULT;
pub extern "msdmo" fn DMOEnum(
guidCategory: ?*const Guid,
dwFlags: u32,
cInTypes: u32,
pInTypes: ?*const DMO_PARTIAL_MEDIATYPE,
cOutTypes: u32,
pOutTypes: ?*const DMO_PARTIAL_MEDIATYPE,
ppEnum: ?*?*IEnumDMO,
) callconv(@import("std").os.windows.WINAPI) HRESULT;
pub extern "msdmo" fn DMOGetTypes(
clsidDMO: ?*const Guid,
ulInputTypesRequested: u32,
pulInputTypesSupplied: ?*u32,
pInputTypes: ?*DMO_PARTIAL_MEDIATYPE,
ulOutputTypesRequested: u32,
pulOutputTypesSupplied: ?*u32,
pOutputTypes: ?*DMO_PARTIAL_MEDIATYPE,
) callconv(@import("std").os.windows.WINAPI) HRESULT;
pub extern "msdmo" fn DMOGetName(
clsidDMO: ?*const Guid,
szName: *[80]u16,
) callconv(@import("std").os.windows.WINAPI) HRESULT;
pub extern "msdmo" fn MoInitMediaType(
pmt: ?*DMO_MEDIA_TYPE,
cbFormat: u32,
) callconv(@import("std").os.windows.WINAPI) HRESULT;
pub extern "msdmo" fn MoFreeMediaType(
pmt: ?*DMO_MEDIA_TYPE,
) callconv(@import("std").os.windows.WINAPI) HRESULT;
pub extern "msdmo" fn MoCopyMediaType(
pmtDest: ?*DMO_MEDIA_TYPE,
pmtSrc: ?*const DMO_MEDIA_TYPE,
) callconv(@import("std").os.windows.WINAPI) HRESULT;
pub extern "msdmo" fn MoCreateMediaType(
ppmt: ?*?*DMO_MEDIA_TYPE,
cbFormat: u32,
) callconv(@import("std").os.windows.WINAPI) HRESULT;
pub extern "msdmo" fn MoDeleteMediaType(
pmt: ?*DMO_MEDIA_TYPE,
) callconv(@import("std").os.windows.WINAPI) HRESULT;
pub extern "msdmo" fn MoDuplicateMediaType(
ppmtDest: ?*?*DMO_MEDIA_TYPE,
pmtSrc: ?*const DMO_MEDIA_TYPE,
) callconv(@import("std").os.windows.WINAPI) HRESULT;
//--------------------------------------------------------------------------------
// Section: Unicode Aliases (0)
//--------------------------------------------------------------------------------
const thismodule = @This();
pub usingnamespace switch (@import("../zig.zig").unicode_mode) {
.ansi => struct {
},
.wide => struct {
},
.unspecified => if (@import("builtin").is_test) struct {
} else struct {
},
};
//--------------------------------------------------------------------------------
// Section: Imports (5)
//--------------------------------------------------------------------------------
const Guid = @import("../zig.zig").Guid;
const BOOL = @import("../foundation.zig").BOOL;
const HRESULT = @import("../foundation.zig").HRESULT;
const IUnknown = @import("../system/com.zig").IUnknown;
const PWSTR = @import("../foundation.zig").PWSTR;
test {
@setEvalBranchQuota(
@import("std").meta.declarations(@This()).len * 3
);
// reference all the pub declarations
if (!@import("builtin").is_test) return;
inline for (@import("std").meta.declarations(@This())) |decl| {
if (decl.is_pub) {
_ = decl;
}
}
} | win32/media/dx_media_objects.zig |
const std = @import("std");
pub fn main() !void {
var arena = std.heap.ArenaAllocator.init(std.heap.page_allocator);
defer arena.deinit();
const allocator = &arena.allocator;
var args = std.process.args();
_ = args.skip();
while (args.next(allocator)) |arg| {
const path = arg catch "input.txt";
const file = try std.fs.cwd().openFile(path, .{ .read = true });
defer file.close();
var line_buffer = try std.ArrayList(u8).initCapacity(allocator, 300);
defer line_buffer.deinit();
file.reader().readUntilDelimiterArrayList(&line_buffer, '\n', std.math.maxInt(usize)) catch |err| switch (err) {
error.EndOfStream => {},
else => |e| return e,
};
var iter = std.mem.split(line_buffer.items, "target area: ");
const tmp = iter.next();
const coords = iter.next();
iter = std.mem.split(coords.?, ", ");
const xrange = iter.next().?[2..];
const yrange = iter.next().?[2..];
iter = std.mem.split(xrange, "..");
const xtarget_min = std.fmt.parseInt(i32, iter.next().?, 10);
const xtarget_max = std.fmt.parseInt(i32, iter.next().?, 10);
iter = std.mem.split(yrange, "..");
const ytarget_min = std.fmt.parseInt(i32, iter.next().?, 10);
const ytarget_max = std.fmt.parseInt(i32, iter.next().?, 10);
const xtarget = Range {
.min = xtarget_min catch 0,
.max = xtarget_max catch 0,
};
const ytarget = Range {
.min = ytarget_min catch 0,
.max = ytarget_max catch 0,
};
part1(xtarget, ytarget);
part2(xtarget, ytarget);
}
}
fn part1(xtarget: Range, ytarget: Range) void {
var ymax: i32 = 0;
var x: i32 = 1;
while (x != xtarget.max + 1) {
var y: i32 = 0;
while (y != -ytarget.min) {
if (reaches_target(Vec2 {.x = x, .y = y}, xtarget, ytarget)) {
const new_max = get_max_y(Vec2 {.x = x, .y = y}, xtarget, ytarget);
if (new_max > ymax) {
ymax = new_max;
}
}
y += 1;
}
x += 1;
}
std.debug.print("Part 1: {}\n", .{ymax});
}
fn part2(xtarget: Range, ytarget: Range) void {
var count: u64 = 0;
var x: i32 = 1;
while (x != xtarget.max + 1) {
var y: i32 = ytarget.min;
while (y != -ytarget.min) {
if (reaches_target(Vec2 {.x = x, .y = y}, xtarget, ytarget)) {
count += 1;
}
if (ytarget.min < 0) y += 1 else y += -1;
}
x += 1;
}
std.debug.print("Part 2: {}\n", .{count});
}
const Range = struct {
min: i32,
max: i32,
};
const Vec2 = struct {
x: i32,
y: i32,
};
fn get_max_y(vel_in: Vec2, xtarget: Range, ytarget: Range) i32 {
var max_y: i32 = 0;
var pos = Vec2 {.x = 0, .y = 0};
var vel = vel_in;
while (true) {
if (pos.x > xtarget.max and pos.y < ytarget.max) {
break;
}
if (pos.x >= xtarget.min and pos.x <= xtarget.max and pos.y >= ytarget.min and pos.y <= ytarget.max) {
break;
}
if (pos.y > max_y) {
max_y = pos.y;
}
const new_pos_vel = step(pos, vel);
pos = new_pos_vel[0];
vel = new_pos_vel[1];
}
return max_y;
}
fn reaches_target(vel_in: Vec2, xtarget: Range, ytarget: Range) bool {
var pos = Vec2 {.x = 0, .y = 0};
var vel = vel_in;
while (true) {
if (pos.x > xtarget.max) {
break;
}
if (pos.y < ytarget.min) {
break;
}
if (pos.x >= xtarget.min and pos.x <= xtarget.max and pos.y >= ytarget.min and pos.y <= ytarget.max) {
break;
}
const new_pos_vel = step(pos, vel);
pos = new_pos_vel[0];
vel = new_pos_vel[1];
}
return pos.x >= xtarget.min and pos.x <= xtarget.max and pos.y >= ytarget.min and pos.y <= ytarget.max;
}
fn step(pos_in: Vec2, vel_in: Vec2) [2]Vec2 {
var pos = pos_in;
var vel = vel_in;
pos.x += vel.x;
pos.y += vel.y;
if (vel.x > 0) {
vel.x += -1;
} else if (vel.x < 0) {
vel.x += 1;
}
vel.y -= 1;
return .{pos, vel};
} | day-17-zig/day_17.zig |
pub fn build(b: *std.build.Builder) !void {
const display_option = b.option(bool, "display", "graphics display for qemu") orelse false;
const build_exe = b.addExecutable("main", "main.zig");
_ = buildExeDetails: {
build_exe.emit_asm = true;
build_exe.install();
build_exe.setBuildMode(b.standardReleaseOptions());
build_exe.setLinkerScriptPath(std.build.FileSource.relative("linker_script.ld"));
build_exe.setTarget(model.target);
build_exe.link_function_sections = true;
break :buildExeDetails 0;
};
const format_source = b.addFmt(&[_][]const u8{ "build.zig", "main.zig" });
const install_raw = b.addInstallRaw(build_exe, "main.img");
const make_hex_file = addCustomStep(b, MakeHexFileStep{ .input_name = "zig-out/bin/main.img", .output_name = "main.hex" });
const run_qemu = b.addSystemCommand(&[_][]const u8{
"qemu-system-arm",
"-kernel",
"zig-out/bin/main.img",
"-M",
model.qemu.machine,
"-serial",
"stdio",
"-display",
if (display_option) "gtk" else "none",
});
_ = declareDependencies: {
build_exe.step.dependOn(&format_source.step);
install_raw.step.dependOn(&build_exe.step);
make_hex_file.step.dependOn(&install_raw.step);
run_qemu.step.dependOn(&install_raw.step);
break :declareDependencies 0;
};
_ = declareCommandLineSteps: {
b.step("make-hex", "make hex file to copy to device").dependOn(&make_hex_file.step);
b.step("qemu", "run in qemu").dependOn(&run_qemu.step);
b.default_step.dependOn(&build_exe.step);
break :declareCommandLineSteps 0;
};
}
const MakeHexFileStep = struct {
step: std.build.Step = undefined,
input_name: []const u8,
output_name: []const u8,
pub fn make(step: *std.build.Step) anyerror!void {
const self = @fieldParentPtr(MakeHexFileStep, "step", step);
const cwd = fs.cwd();
const image = try cwd.openFile(self.input_name, fs.File.OpenFlags{});
defer image.close();
const hex = try cwd.createFile(self.output_name, fs.File.CreateFlags{});
defer hex.close();
var offset: usize = 0;
var read_buf: [model.memory.flash.size]u8 = undefined;
while (true) {
var n = try image.read(&read_buf);
if (n == 0) {
break;
}
while (offset < n) {
if (offset % 0x10000 == 0) {
try writeHexRecord(hex, 0, 0x04, &[_]u8{ @truncate(u8, offset >> 24), @truncate(u8, offset >> 16) });
}
const i = std.math.min(hex_record_len, n - offset);
try writeHexRecord(hex, offset % 0x10000, 0x00, read_buf[offset .. offset + i]);
offset += i;
}
}
try writeHexRecord(hex, 0, 0x01, &[_]u8{});
}
fn writeHexRecord(file: fs.File, offset: usize, code: u8, bytes: []u8) !void {
var record_buf: [1 + 2 + 1 + hex_record_len + 1]u8 = undefined;
var record: []u8 = record_buf[0 .. 1 + 2 + 1 + bytes.len + 1];
record[0] = @truncate(u8, bytes.len);
record[1] = @truncate(u8, offset >> 8);
record[2] = @truncate(u8, offset >> 0);
record[3] = code;
for (bytes) |b, i| {
record[4 + i] = b;
}
var checksum: u8 = 0;
for (record[0 .. record.len - 1]) |b| {
checksum = checksum -% b;
}
record[record.len - 1] = checksum;
var line_buf: [1 + record_buf.len * 2 + 1]u8 = undefined;
_ = try file.write(try std.fmt.bufPrint(&line_buf, ":{}\n", .{std.fmt.fmtSliceHexUpper(record)}));
}
const hex_record_len = 32;
};
pub fn addCustomStep(self: *std.build.Builder, customStep: anytype) *@TypeOf(customStep) {
var allocated = self.allocator.create(@TypeOf(customStep)) catch unreachable;
allocated.* = customStep;
allocated.*.step = std.build.Step.init(.custom, @typeName(@TypeOf(customStep)), self.allocator, @TypeOf(customStep).make);
return allocated;
}
const fs = std.fs;
const model = @import("system_model.zig");
const std = @import("std"); | build.zig |
const std = @import("std");
const x86 = @import("x86");
const Token = union(enum) {
op: u8,
int: i64,
};
const TokenIterator = struct {
toks: std.mem.TokenIterator,
pub fn init(expr: []const u8) TokenIterator {
return .{ .toks = std.mem.tokenize(expr, " \t\n") };
}
pub fn next(self: *TokenIterator) !?Token {
if (self.toks.next()) |tok| {
if (tok.len == 1 and std.mem.indexOf(u8, "+-*/", tok) != null) {
return Token{ .op = tok[0] };
} else {
const i = try std.fmt.parseInt(i64, tok, 0);
return Token{ .int = i };
}
} else {
return null;
}
}
};
fn Compiler(comptime Writer: type) type {
return struct {
w: Writer,
m: x86.Machine,
stackSize: u32 = 0,
const Self = @This();
// Create a new compiler that will output machine code to the provided writer
pub fn init(w: Writer) !Self {
const self = Self{
.w = w,
.m = x86.Machine.init(.x64),
};
try self.begin();
return self;
}
const rax = x86.Operand.register(.RAX);
const rdi = x86.Operand.register(.RDI);
const rbp = x86.Operand.register(.RBP);
const rsp = x86.Operand.register(.RSP);
// Emit a single instruction
fn emit(self: Self, mnem: x86.Mnemonic, operands: anytype) !void {
var ops = [5]?*const x86.Operand{ null, null, null, null, null };
for (@as([operands.len]x86.Operand, operands)) |*op, i| {
ops[i] = op;
}
const insn = try self.m.build(null, mnem, ops[0], ops[1], ops[2], ops[3], ops[4]);
try self.w.writeAll(insn.asSlice());
}
// Emit the function prelude instructions
fn begin(self: Self) !void {
try self.emit(.PUSH, .{rbp});
try self.emit(.MOV, .{ rbp, rsp });
}
// Emit the function teardown and finish the compilation
pub fn finish(self: Self) !void {
if (self.stackSize < 1) {
return error.StackUnderflow;
} else if (self.stackSize > 1) {
return error.UnusedOperands;
}
try self.emit(.POP, .{rax});
try self.emit(.LEAVE, .{});
try self.emit(.RET, .{});
}
// Emit the instructions for a given token
pub fn compile(self: *Self, tok: Token) !void {
switch (tok) {
.int => |x| {
const val = x86.Operand.immediateSigned64(x);
try self.emit(.MOV, .{ rax, val });
try self.emit(.PUSH, .{rax});
self.stackSize += 1;
},
.op => |operator| {
try self.emit(.POP, .{rdi});
try self.emit(.POP, .{rax});
switch (operator) {
'+' => try self.emit(.ADD, .{ rax, rdi }),
'-' => try self.emit(.SUB, .{ rax, rdi }),
'*' => try self.emit(.IMUL, .{ rax, rdi }),
'/' => {
try self.emit(.CDQ, .{});
try self.emit(.IDIV, .{rdi});
},
else => return error.InvalidOperator,
}
try self.emit(.PUSH, .{rax});
if (self.stackSize < 2) {
return error.StackUnderflow;
}
self.stackSize -= 1;
},
}
}
};
}
fn compile(w: anytype, toks: *TokenIterator) !void {
var compiler = try Compiler(@TypeOf(w)).init(w);
while (try toks.next()) |tok| {
try compiler.compile(tok);
}
try compiler.finish();
}
const JitResult = struct {
allocator: *std.mem.Allocator,
code: []align(std.mem.page_size) u8,
func: fn () callconv(.C) i64,
pub fn deinit(self: JitResult) void {
std.os.mprotect(self.code, std.os.PROT_READ | std.os.PROT_WRITE) catch {};
self.allocator.free(self.code);
}
};
fn jit(toks: *TokenIterator) !JitResult {
const allocator = std.heap.page_allocator;
// FIXME: use ArrayListAligned. See ziglang/zig#8647
var buf = try std.ArrayList(u8).initCapacity(allocator, std.mem.page_size);
defer buf.deinit();
try compile(buf.writer(), toks);
var code = @alignCast(std.mem.page_size, buf.toOwnedSlice());
errdefer allocator.free(code);
code.len = alignup(usize, code.len, std.mem.page_size);
try std.os.mprotect(code, std.os.PROT_READ | std.os.PROT_EXEC);
return JitResult{
.allocator = allocator,
.code = code,
.func = @ptrCast(fn () callconv(.C) i64, code.ptr),
};
}
fn alignup(comptime T: type, x: T, a: T) T {
return 1 +% ~(1 +% ~x & 1 +% ~a);
}
fn printEval(expr: []const u8) !void {
var toks = TokenIterator.init(expr);
const jitted = try jit(&toks);
defer jitted.deinit();
const out = std.io.getStdOut().writer();
try out.print("{}\n", .{jitted.func()});
}
pub fn main() !void {
var args = std.process.args();
_ = args.skip();
if (args.nextPosix()) |arg| {
try printEval(arg);
} else {
var gpa = std.heap.GeneralPurposeAllocator(.{}){};
const allocator = &gpa.allocator;
var buf = std.ArrayList(u8).init(allocator);
const in = std.io.getStdIn().reader();
while (true) {
in.readUntilDelimiterArrayList(&buf, '\n', 1 << 20) catch |err| {
if (err == error.EndOfStream) break;
return err;
};
printEval(buf.items) catch |err| {
try std.io.getStdErr().writer().print("{}\n", .{err});
};
}
}
} | src/main.zig |
const std = @import("std");
const platform = @import("platform.zig");
const Allocator = std.mem.Allocator;
const ComptimeBitmap = @import("lib/bitmap.zig").ComptimeBitmap;
pub const PidBitmap = ComptimeBitmap(u128);
pub const Entrypoint = usize;
pub const STACK_SIZE: u64 = (4096 * 1024) / @sizeOf(u64); // 4KB pages.
var all_pids: PidBitmap = brk: {
var pids = PidBitmap.init();
_ = pids.setFirstFree() orelse unreachable;
break :brk pids;
};
// var taskByPid: [PidBitmap.NUM_ENTRIES]?*Task = undefined;
pub const TaskState = enum(u8) {
Runnable,
Stopped,
Sleep,
SleepNoInterrupt,
Zombie,
};
pub const Task = struct {
pid: PidBitmap.IndexType,
kernel_stack: []usize, // Pointer to the kernel stack, allocated @ init
user_stack: []usize, // Pointer to the user stack, allocated @ init, empty if it's a ktask
stack_pointer: usize, // Current sp to task
kernel: bool, // Is it a kernel task?
scheduled: bool,
priority: u8,
state: TaskState,
timeout: u64,
pub fn create(entrypoint: Entrypoint, kernel: bool, allocator: *Allocator, priority: u8) Allocator.Error!*Task {
var task = try allocator.create(Task);
errdefer allocator.destroy(task);
const pid = allocatePid();
errdefer freePid(pid);
var kstack = try allocator.alloc(usize, STACK_SIZE);
errdefer allocator.free(kstack);
var ustack = if (kernel) &[_]usize{} else try allocator.alloc(usize, STACK_SIZE);
errdefer if (!kernel) allocator.free(ustack);
task.* = .{
.pid = pid,
.kernel_stack = kstack,
.user_stack = ustack,
.kernel = kernel,
.stack_pointer = @ptrToInt(&kstack[STACK_SIZE - 1]),
.priority = priority,
.state = TaskState.Runnable,
.scheduled = false,
.timeout = 0, // In nano seconds
};
try platform.initializeTask(task, entrypoint, allocator);
// taskByPid[pid] = task;
return task;
}
pub fn destroy(self: *Task, allocator: *Allocator) void {
// taskByPid[self.pid] = null;
freePid(self.pid);
if (@ptrToInt(self.kernel_stack.ptr) != @frameAddress()) {
allocator.free(self.kernel_stack);
}
if (!self.kernel) {
allocator.free(self.user_stack);
}
allocator.destroy(self);
}
};
fn allocatePid() PidBitmap.IndexType {
return all_pids.setFirstFree() orelse @panic("Out of PIDs");
}
fn freePid(pid: PidBitmap.IndexType) void {
if (!all_pids.isSet(pid)) {
@panic("PID being freed not allocated");
}
all_pids.clearEntry(pid);
}
// pub fn getTask(pid: PidBitmap.IndexType) ?*Task {
// return taskByPid[pid];
// } | src/kernel/task.zig |
const std = @import("std");
const Entity = @import("./Entity.zig");
const ArrayList = std.ArrayList;
const Allocator = std.mem.Allocator;
const Bitset = std.bit_set.StaticBitSet(MAX_ENTITIES);
// testing
const Entities = @import("./Entities.zig");
const benchmark = @import("benchmark");
const MAX_ENTITIES = @import("./main.zig").MAX_ENTITIES;
const expect = std.testing.expect;
/// Holds components of a given type indexed by `Entity`.
/// We do not check if the given entity is alive here, this should be done using
/// `Entities`.
pub fn Components(comptime T: type) type {
return struct {
bitset: Bitset,
components: ArrayList(?T),
next_id: u32 = 0,
const InnerType: type = T;
/// Allocates a new Components(T) struct.
pub fn init(allocator: *Allocator) !@This() {
var comps = try ArrayList(?T).initCapacity(allocator, 64);
errdefer comps.deinit();
comps.appendNTimesAssumeCapacity(null, 64);
const bitset = Bitset.initEmpty();
//const bitset = Bitset.initAllTo(0);
return @This(){
.bitset = bitset,
.components = comps,
};
}
/// Inserts a component for the given `Entity` index.
/// Returns the previous component, if any.
pub fn insert(self: *@This(), entity: Entity, component: T) !?T {
var ins: ?T = component;
if (self.bitset.isSet(entity.index)) {
std.mem.swap(?T, &ins, &self.components.items[entity.index]);
return ins;
} else {
try self.allocate_enough(entity.index);
self.bitset.set(entity.index);
self.components.items[entity.index] = component;
return null;
}
}
/// Ensures that we have the vec filled at least until the `until`
/// variable. Usually, set this to `entity.index`.
fn allocate_enough(self: *@This(), until: u32) !void {
self.next_id = until + 1;
const qty = @intCast(i32, until) - (@intCast(i32, self.components.items.len) - 1);
if (qty > 0) {
try self.components.appendNTimes(null, @intCast(usize, qty));
}
}
/// Deinitializes Component(T).
pub fn deinit(self: *@This()) void {
self.components.deinit();
}
/// Gets a reference to the component of `Entity`, if any.
/// Do not store the returned pointer.
///
/// The entity argument must be a valid index.
/// To ensure this, take it from an `Entity` using entity.index.
pub fn get(self: *const @This(), entity: u32) ?*const T {
if (std.builtin.mode == .Debug or std.builtin.mode == .ReleaseSafe) {
if (self.bitset.isSet(entity)) {
return &self.components.items[entity].?;
} else {
return null;
}
} else {
return &self.components.items[entity].?;
}
}
/// Gets a reference to the component of `Entity`, if any.
/// Do not store the returned pointer.
///
/// The entity argument must be a valid index.
/// To ensure this, take it from an `Entity` using entity.index.
pub fn getMut(self: *@This(), entity: u32) ?*T {
if (std.builtin.mode == .Debug or std.builtin.mode == .ReleaseSafe) {
if (self.bitset.isSet(entity)) {
return &self.components.items[entity].?;
} else {
return null;
}
} else {
return &self.components.items[entity].?;
}
}
/// Removes the component of `Entity`.
/// If the entity already had this component, we return it.
pub fn remove(self: *@This(), entity: Entity) ?T {
if (self.bitset.isSet(entity.index)) {
self.bitset.unset(entity.index);
const ret = self.components.items[entity.index];
self.components.items[entity.index] = null;
return ret;
} else {
return null;
}
}
/// Removes dead entities from this component storage.
pub fn maintain(self: *@This(), entities: *const Entities) void {
for (entities.killed.items) |e| {
_ = self.remove(e);
}
}
};
}
test "Insert Component" {
var entities = try Entities.init(std.testing.allocator);
defer entities.deinit();
var comps = try Components(u32).init(std.testing.allocator);
defer comps.deinit();
const e1 = entities.create();
const e2 = entities.create();
_ = try comps.insert(e1, 1);
_ = try comps.insert(e2, 2);
const ret = comps.get(e1.index).?.*;
try expect(ret == 1);
const ret2 = comps.get(e2.index).?.*;
try expect(ret2 == 2);
}
fn optToBool(comptime T: type, v: ?T) bool {
if (v) |_| {
return true;
} else {
return false;
}
}
test "Insert remove component" {
var entities = try Entities.init(std.testing.allocator);
defer entities.deinit();
var comps = try Components(u32).init(std.testing.allocator);
defer comps.deinit();
const e1 = entities.create();
const not_inserted = entities.create();
try expect(!optToBool(u32, comps.remove(e1))); // no return value.
try expect(!optToBool(u32, try comps.insert(e1, 1))); // no return value.
try expect(optToBool(u32, comps.remove(e1))); // now a return value.
try expect(!optToBool(u32, try comps.insert(e1, 1))); // no return value.
try expect((try comps.insert(e1, 2)).? == 1); // a return value.
try expect(!optToBool(u32, comps.remove(not_inserted))); // no return value.
try expect(comps.remove(e1).? == 2); // a return value.
}
test "Maintain" {
var entities = try Entities.init(std.testing.allocator);
defer entities.deinit();
var comps = try Components(u32).init(std.testing.allocator);
defer comps.deinit();
const e1 = entities.create();
_ = try comps.insert(e1, 3);
try entities.kill(e1);
comps.maintain(&entities);
try expect(!optToBool(u32, comps.remove(e1))); // no return value.
}
test "Benchmark component insertion" {
const b = struct {
fn bench(ctx: *benchmark.Context) void {
var entities = Entities.init(std.testing.allocator) catch unreachable;
defer entities.deinit();
var comps = Components(u32).init(std.testing.allocator) catch unreachable;
defer comps.deinit();
const e1 = entities.create();
while (ctx.runExplicitTiming()) {
ctx.startTimer();
_ = comps.insert(e1, 1) catch unreachable;
ctx.stopTimer();
}
}
}.bench;
benchmark.benchmark("insert component", b);
} | src/components.zig |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.