code
stringlengths
38
801k
repo_path
stringlengths
6
263
const std = @import("std"); const bytecode = @import("bytecode.zig"); const gc = @import("gc.zig"); const InterpreterError = @import("vm.zig").InterpreterError; const Scanner = @import("scanner.zig").Scanner; const Token = @import("scanner.zig").Token; const TokenType = @import("scanner.zig").TokenType; const value_api = @import("value.zig"); const Value = value_api.Value; const Precedence = enum(usize) { None, Assignment, Or, Xor, And, Equality, Comparison, Term, Factor, Unary, Call, Primary, }; const ParseFn = fn (parser: *Parser, can_assign: bool) void; const ParseRule = struct { prefix: ?ParseFn, infix: ?ParseFn, precedence: Precedence, fn init(prefix: ?ParseFn, infix: ?ParseFn, precedence: Precedence) ParseRule { return ParseRule{ .prefix = prefix, .infix = infix, .precedence = precedence, }; } }; const parse_rules = t: { comptime var prec = std.enums.EnumArray(TokenType, ParseRule).initUndefined(); prec.set(.OpenParen, ParseRule.init(Parser.compileGrouping, null, .None)); prec.set(.CloseParen, ParseRule.init(null, null, .None)); prec.set(.OpenBrace, ParseRule.init(null, null, .None)); prec.set(.CloseBrace, ParseRule.init(null, null, .None)); prec.set(.OpenBracket, ParseRule.init(null, null, .None)); prec.set(.CloseBracket, ParseRule.init(null, null, .None)); prec.set(.Comma, ParseRule.init(null, null, .None)); prec.set(.Dot, ParseRule.init(null, null, .None)); prec.set(.Semicolon, ParseRule.init(null, null, .None)); prec.set(.Equal, ParseRule.init(null, null, .None)); prec.set(.Not, ParseRule.init(Parser.compileUnary, null, .None)); prec.set(.Minus, ParseRule.init(Parser.compileUnary, Parser.compileBinary, .Term)); prec.set(.Plus, ParseRule.init(null, Parser.compileBinary, .Term)); prec.set(.Slash, ParseRule.init(null, Parser.compileBinary, .Factor)); prec.set(.Star, ParseRule.init(null, Parser.compileBinary, .Factor)); prec.set(.MinusEqual, ParseRule.init(null, null, .None)); prec.set(.PlusEqual, ParseRule.init(null, null, .None)); prec.set(.SlashEqual, ParseRule.init(null, null, .None)); prec.set(.StarEqual, ParseRule.init(null, null, .None)); prec.set(.EqualEqual, ParseRule.init(null, Parser.compileBinary, .Equality)); prec.set(.BangEqual, ParseRule.init(null, Parser.compileBinary, .Equality)); prec.set(.Less, ParseRule.init(null, Parser.compileBinary, .Comparison)); prec.set(.LessEqual, ParseRule.init(null, Parser.compileBinary, .Comparison)); prec.set(.Greater, ParseRule.init(null, Parser.compileBinary, .Comparison)); prec.set(.GreaterEqual, ParseRule.init(null, Parser.compileBinary, .Comparison)); prec.set(.Number, ParseRule.init(Parser.compileNumber, null, .None)); prec.set(.String, ParseRule.init(Parser.compileString, null, .None)); prec.set(.Nil, ParseRule.init(Parser.compileLiteral, null, .None)); prec.set(.False, ParseRule.init(Parser.compileLiteral, null, .None)); prec.set(.True, ParseRule.init(Parser.compileLiteral, null, .None)); prec.set(.Or, ParseRule.init(null, Parser.compileBinary, .Or)); prec.set(.And, ParseRule.init(null, Parser.compileBinary, .And)); prec.set(.Xor, ParseRule.init(null, Parser.compileBinary, .Xor)); prec.set(.Identifier, ParseRule.init(Parser.compileVariable, null, .None)); prec.set(.Class, ParseRule.init(null, null, .None)); prec.set(.Else, ParseRule.init(null, null, .None)); prec.set(.For, ParseRule.init(null, null, .None)); prec.set(.Fn, ParseRule.init(null, null, .None)); prec.set(.If, ParseRule.init(null, null, .None)); prec.set(.Let, ParseRule.init(null, null, .None)); prec.set(.Return, ParseRule.init(null, null, .None)); prec.set(.Super, ParseRule.init(null, null, .None)); prec.set(.Switch, ParseRule.init(null, null, .None)); prec.set(.This, ParseRule.init(null, null, .None)); prec.set(.While, ParseRule.init(null, null, .None)); prec.set(.Print, ParseRule.init(null, null, .None)); prec.set(.Error, ParseRule.init(null, null, .None)); prec.set(.EOF, ParseRule.init(null, null, .None)); break :t prec; }; // TODO: For now, we are doing single pass compilation. // At some point, we will need to optimize a bit of stuff and so on, // so we might need an AST. // TODO: At some point, we will really need true error handling, // this is very crappy right now pub fn compile(source: []const u8, chunk: *bytecode.Chunk, heap: *gc.Heap) bool { var scanner = Scanner.init(source); var parser = Parser.init(&scanner, chunk, heap); return parser.run(); } const Parser = struct { current: Token = Token{}, previous: Token = undefined, hadError: bool = false, panicMode: bool = false, scanner: *Scanner, chunk: *bytecode.Chunk, heap: *gc.Heap, const Self = @This(); fn init(scanner: *Scanner, chunk: *bytecode.Chunk, heap: *gc.Heap) Self { return Parser{ .scanner = scanner, .chunk = chunk, .heap = heap, }; } fn run(self: *Self) bool { self.advance(); while (!self.match(.EOF)) { self.compileDeclaration(); } self.endCompiler(); return !self.hadError; } fn endCompiler(self: *Self) void { self.chunk.push(.Return); } fn parsePrecedence(self: *Self, precedence: Precedence) void { self.advance(); const rule = parse_rules.get(self.previous.token_type); const prefix_rule = rule.prefix; if (prefix_rule == null) { self.errorAtPrevious("Expect an expression."); return; } const can_assign = @enumToInt(precedence) <= @enumToInt(Precedence.Assignment); prefix_rule.?(self, can_assign); const prec_value = @enumToInt(precedence); while (prec_value <= @enumToInt(parse_rules.get(self.current.token_type).precedence)) { self.advance(); const infix_rule = parse_rules.get(self.previous.token_type).infix; if (infix_rule != null) { infix_rule.?(self, can_assign); } } if (can_assign and self.match(.Equal)) { self.errorAtPrevious("Invalid assignment target"); } } fn compileDeclaration(self: *Self) void { if (self.match(.Let)) { self.compileVarDecl(); } else { self.compileStatement(); } if (self.panicMode) { self.synchronize(); } } fn compileVarDecl(self: *Self) void { self.consume(.Identifier, "Variable name expected."); var name_token = self.previous; self.consume(.Equal, "Variables must be affected when declared"); self.compileExpression(); self.consume(.Semicolon, "Expect ';' after variable declaration"); self.emitOp(.DefineGlobal); self.emitIdentifierConstant(name_token); } fn compileStatement(self: *Self) void { if (self.match(.Print)) { self.compilePrintStatement(); } else { self.compileExpressionStatement(); } } fn compilePrintStatement(self: *Self) void { self.consume(.OpenParen, "`print()` is a function, please call it like other functions"); self.compileExpression(); self.consume(.CloseParen, "`)` expected"); self.consume(.Semicolon, "Expected a `;` after a function call"); self.emitOp(.Print); } fn compileExpressionStatement(self: *Self) void { self.compileExpression(); self.consume(.Semicolon, "Expect a `;` after an expression"); self.emitOp(.Pop); } fn compileExpression(self: *Self) void { self.parsePrecedence(.Assignment); } fn compileNumber(self: *Self, _: bool) void { const value = std.fmt.parseFloat(f64, self.previous.lexeme) catch std.math.nan_f64; self.emitConstant(Value.fromNumber(value)); } fn compileString(self: *Self, _: bool) void { const source_str = self.previous.lexeme; const str = value_api.makeConstantString(source_str); self.emitConstant(Value.fromString(str)); } fn compileLiteral(self: *Self, _: bool) void { switch (self.previous.token_type) { .True => self.chunk.push(.True), .False => self.chunk.push(.False), .Nil => self.chunk.push(.Nil), else => {}, } } fn compileGrouping(self: *Self, _: bool) void { self.compileExpression(); self.consume(TokenType.CloseParen, "Expect `)` after an expression."); } fn compileUnary(self: *Self, _: bool) void { const operator_type = self.previous.token_type; self.parsePrecedence(.Unary); switch (operator_type) { .Minus => self.emitOp(.Neg), .Not => self.emitOp(.Not), else => {}, } } fn compileBinary(self: *Self, _: bool) void { const operator_type = self.previous.token_type; var rule = parse_rules.get(operator_type); self.parsePrecedence(@intToEnum(Precedence, @enumToInt(rule.precedence) + 1)); switch (operator_type) { .Plus => self.emitOp(.Add), .Minus => self.emitOp(.Sub), .Star => self.emitOp(.Mul), .Slash => self.emitOp(.Div), .And => self.emitOp(.And), .Or => self.emitOp(.Or), .Xor => self.emitOp(.Xor), .EqualEqual => self.emitOp(.Equal), .BangEqual => self.emitOp(.NotEqual), .Greater => self.emitOp(.Greater), .GreaterEqual => self.emitOp(.GreaterEqual), .Less => self.emitOp(.Less), .LessEqual => self.emitOp(.LessEqual), else => {}, } } fn compileVariable(self: *Self, can_assign: bool) void { const name_token = self.previous; if (can_assign and self.match(.Equal)) { self.compileExpression(); self.emitOp(.SetGlobal); } else { self.emitOp(.GetGlobal); } self.emitIdentifierConstant(name_token); } fn emitIdentifierConstant(self: *Self, token: Token) void { var name = value_api.makeConstantString(token.lexeme); self.chunk.pushConstant(Value.fromString(name)); } fn emitOp(self: *Self, op: bytecode.Op) void { self.chunk.push(op); } fn emitConstant(self: *Self, value: Value) void { self.chunk.push(.Constant); _ = self.chunk.pushConstant(value); } fn advance(self: *Self) void { self.previous = self.current; while (true) { self.current = self.scanner.next(); switch (self.current.token_type) { .Error => { self.errorAtCurrent(self.current.lexeme); continue; }, else => {}, } break; } } fn consume(self: *Self, token_type: TokenType, msg: []const u8) void { if (self.current.token_type == token_type) { self.advance(); } else { self.errorAtCurrent(msg); } } fn check(self: *Self, token_type: TokenType) bool { return self.current.token_type == token_type; } fn match(self: *Self, token_type: TokenType) bool { if (!self.check(token_type)) return false; self.advance(); return true; } fn errorAt(self: *Self, token: Token, msg: []const u8) void { if (!self.panicMode) { switch (token.token_type) { .Error => { std.debug.print("Syntax error (line {}): {s}.\n", .{ token.location.line, msg }); }, else => { std.debug.print("Compile error (line {}): {s}.\n", .{ token.location.line, msg }); }, } self.hadError = true; self.panicMode = true; } } fn errorAtCurrent(self: *Self, msg: []const u8) void { self.errorAt(self.current, msg); } fn errorAtPrevious(self: *Self, msg: []const u8) void { self.errorAt(self.previous, msg); } fn synchronize(self: *Self) void { self.panicMode = false; while (self.current.token_type != .EOF) { if (self.previous.token_type == .Semicolon) return; switch (self.current.token_type) { .Class, .Fn, .Let, .For, .If, .While, .Print, .Return => return, else => {}, } self.advance(); } } };
src/compiler.zig
const std = @import("std"); const Allocator = std.mem.Allocator; const assert = std.debug.assert; const c = @import("c.zig"); const events = @import("events.zig"); const EventHandler = events.EventHandler; const math = @import("math.zig"); //; // TODO // image/texture width and height could be i32, to make it easier to work with texture regions // currently only using them to denote "these numbers are positive" //; pub var joystick_ctx_reference: ?*Context = null; pub const Context = struct { const Self = @This(); pub const Error = error{ GlfwInit, WindowInit, }; pub const Settings = struct { ogl_version_major: u32 = 3, ogl_version_minor: u32 = 3, window_width: u32 = 800, window_height: u32 = 600, window_name: [:0]const u8 = "float", is_resizable: bool = true, windowSizeCallback: ?fn (*Context) void = null, }; settings: Settings, window: *c.GLFWwindow, event_handler: ?EventHandler, fn windowSizeCallback( win: ?*c.GLFWwindow, width: c_int, height: c_int, ) callconv(.C) void { var ctx = @ptrCast(*Context, @alignCast(@alignOf(*Context), c.glfwGetWindowUserPointer(win).?)); ctx.settings.window_width = @intCast(u32, width); ctx.settings.window_height = @intCast(u32, height); if (ctx.settings.windowSizeCallback) |cb| { cb(ctx); } } pub fn init(self: *Self, settings: Settings) !void { if (c.glfwInit() != c.GLFW_TRUE) { return error.GlfwInit; } errdefer c.glfwTerminate(); c.glfwWindowHint(c.GLFW_CONTEXT_VERSION_MAJOR, @intCast(c_int, settings.ogl_version_major)); c.glfwWindowHint(c.GLFW_CONTEXT_VERSION_MINOR, @intCast(c_int, settings.ogl_version_minor)); c.glfwWindowHint(c.GLFW_OPENGL_PROFILE, c.GLFW_OPENGL_CORE_PROFILE); c.glfwWindowHint(c.GLFW_RESIZABLE, if (settings.is_resizable) c.GL_TRUE else c.GL_FALSE); c.glfwSwapInterval(1); // note: window creation fails if we can't get the desired opengl version const window = c.glfwCreateWindow( @intCast(c_int, settings.window_width), @intCast(c_int, settings.window_height), settings.window_name, null, null, ) orelse return error.WindowInit; errdefer c.glfwDestroyWindow(window); c.glfwMakeContextCurrent(window); var w: c_int = undefined; var h: c_int = undefined; c.glfwGetFramebufferSize(window, &w, &h); c.glViewport(0, 0, w, h); _ = c.glfwSetWindowSizeCallback(window, windowSizeCallback); c.glEnable(c.GL_BLEND); c.glBlendEquation(c.GL_FUNC_ADD); c.glBlendFunc(c.GL_SRC_ALPHA, c.GL_ONE_MINUS_SRC_ALPHA); c.glClearColor(0, 0, 0, 0); var settings_mut = settings; settings_mut.window_width = @intCast(u32, w); settings_mut.window_height = @intCast(u32, h); self.settings = settings_mut; self.window = window; self.event_handler = null; c.glfwSetWindowUserPointer(window, self); joystick_ctx_reference = self; } pub fn deinit(self: *Self) void { if (self.event_handler) |*evs| { evs.deinit(); } c.glfwDestroyWindow(self.window); c.glfwTerminate(); } //; pub fn getFromGLFW_WindowPtr(win: ?*c.GLFWwindow) *Context { return @ptrCast(*Context, @alignCast(@alignOf(*Context), c.glfwGetWindowUserPointer(win).?)); } pub fn getFromGLFW_JoystickId(id: c_int) *Context { return @ptrCast(*Context, @alignCast(@alignOf(*Context), c.glfwGetJoystickUserPointer(id).?)); } pub fn installEventHandler(self: *Self, allocator: *Allocator) void { if (self.event_handler == null) { self.event_handler = EventHandler.init(allocator, self.window); } } }; //; pub const Shader = struct { const Self = @This(); pub const Error = error{Compile}; shader: c.GLuint, // TODO to handle errors here probably just use a Result // TODO by taking a slice of strings rather than a single string, // flat namespace wont need an allocator for default shader // problem is you gotta turn that slice of slices into a slice of ptrs // or take a slice of ptrs which isnt as nice. // sentineled ptrs? pub fn init(ty: c.GLenum, source: [:0]const u8) !Self { const shader = c.glCreateShader(ty); errdefer c.glDeleteShader(shader); c.glShaderSource(shader, 1, &source.ptr, null); c.glCompileShader(shader); var success: c_int = undefined; c.glGetShaderiv(shader, c.GL_COMPILE_STATUS, &success); if (success != c.GL_TRUE) { // TODO var len: c_int = 0; c.glGetShaderiv( shader, c.GL_INFO_LOG_LENGTH, &len, ); var buf = try std.testing.allocator.alloc(u8, @intCast(usize, len) + 1); defer std.testing.allocator.free(buf); c.glGetShaderInfoLog(shader, len, null, buf.ptr); std.log.info("{}\n", .{buf}); return error.Compile; } return Self{ .shader = shader, }; } pub fn deinit(self: *Self) void { c.glDeleteShader(self.shader); } //; }; pub const Program = struct { const Self = @This(); pub const Error = error{Link}; program: c.GLuint, pub fn init(shaders: []const Shader) !Self { const program = c.glCreateProgram(); errdefer c.glDeleteProgram(program); for (shaders) |shd| { c.glAttachShader(program, shd.shader); } c.glLinkProgram(program); var success: c_int = undefined; c.glGetProgramiv(program, c.GL_LINK_STATUS, &success); if (success != c.GL_TRUE) { // TODO return error.Link; } return Self{ .program = program, }; } pub fn deinit(self: *Self) void { c.glDeleteProgram(self.program); } pub fn bind(self: Self) void { c.glUseProgram(self.program); } pub fn unbind(self: Self) void { c.glUseProgram(0); } pub fn getLocation(self: Self, name: [:0]const u8) Location { return Location{ .location = c.glGetUniformLocation(self.program, name), }; } }; pub const Image = struct { const Self = @This(); const Error = error{Load} || Allocator.Error; pub const Color = extern struct { r: u8, g: u8, b: u8, a: u8, }; allocator: *Allocator, data: []Color, width: u32, height: u32, pub fn init( allocator: *Allocator, width: u32, height: u32, ) Allocator.Error!Self { const data_len = width * height; const data = try allocator.alloc(Color, data_len); return Self{ .allocator = allocator, .data = data, .width = width, .height = height, }; } pub fn initFromMemory(allocator: *Allocator, buffer: []const u8) Error!Self { var w: c_int = undefined; var h: c_int = undefined; const raw_data = c.stbi_load_from_memory( buffer.ptr, @intCast(c_int, buffer.len), &w, &h, null, 4, ) orelse return error.Load; defer c.stbi_image_free(raw_data); const data_len = @intCast(usize, w * h); var data = try allocator.alloc(Color, data_len); // TODO alignment std.mem.copy(Color, data, @ptrCast([*]Color, raw_data)[0..data_len]); return Self{ .allocator = allocator, .data = data, .width = @intCast(u32, w), .height = @intCast(u32, h), }; } pub fn initFromFile(allocator: *Allocator, path: [:0]const u8) Error!Self { var w: c_int = undefined; var h: c_int = undefined; const raw_data = c.stbi_load(path, &w, &h, null, 4) orelse return error.Load; defer c.stbi_image_free(raw_data); const data_len = @intCast(usize, w * h); var data = try allocator.alloc(Color, data_len); // TODO alignment std.mem.copy(Color, data, @ptrCast([*]Color, raw_data)[0..data_len]); return Self{ .allocator = allocator, .data = data, .width = @intCast(u32, w), .height = @intCast(u32, h), }; } pub fn deinit(self: *Self) void { self.allocator.free(self.data); } }; pub const Texture = struct { const Self = @This(); texture: c.GLuint, width: u32, height: u32, pub fn init(width: u32, height: u32) Self { var tex: c.GLuint = undefined; c.glGenTextures(1, &tex); c.glBindTexture(c.GL_TEXTURE_2D, tex); c.glTexImage2D( c.GL_TEXTURE_2D, 0, c.GL_RGBA, @intCast(c.GLint, width), @intCast(c.GLint, height), 0, c.GL_RGBA, c.GL_UNSIGNED_BYTE, null, ); c.glBindTexture(c.GL_TEXTURE_2D, 0); return .{ .texture = tex, .width = width, .height = height, }; } pub fn initImage(image: Image) Self { var tex: c.GLuint = undefined; c.glGenTextures(1, &tex); c.glBindTexture(c.GL_TEXTURE_2D, tex); c.glTexImage2D( c.GL_TEXTURE_2D, 0, c.GL_RGBA, @intCast(c.GLint, image.width), @intCast(c.GLint, image.height), 0, c.GL_RGBA, c.GL_UNSIGNED_BYTE, image.data.ptr, ); c.glGenerateMipmap(c.GL_TEXTURE_2D); c.glBindTexture(c.GL_TEXTURE_2D, 0); var ret = Self{ .texture = tex, .width = image.width, .height = image.height, }; ret.setWrap(c.GL_REPEAT, c.GL_REPEAT); ret.setFilter(c.GL_LINEAR, c.GL_LINEAR); return ret; } pub fn deinit(self: *Self) void { c.glDeleteTextures(1, &self.texture); } //; pub fn setWrap(self: *Self, s: c.GLint, t: c.GLint) void { c.glBindTexture(c.GL_TEXTURE_2D, self.texture); c.glTexParameteri(c.GL_TEXTURE_2D, c.GL_TEXTURE_WRAP_S, s); c.glTexParameteri(c.GL_TEXTURE_2D, c.GL_TEXTURE_WRAP_T, t); c.glBindTexture(c.GL_TEXTURE_2D, 0); } pub fn setFilter(self: *Self, min: c.GLint, mag: c.GLint) void { c.glBindTexture(c.GL_TEXTURE_2D, self.texture); c.glTexParameteri(c.GL_TEXTURE_2D, c.GL_TEXTURE_MIN_FILTER, min); c.glTexParameteri(c.GL_TEXTURE_2D, c.GL_TEXTURE_MAG_FILTER, mag); c.glBindTexture(c.GL_TEXTURE_2D, 0); } pub fn setBorderColor( self: *Self, r: c.GLfloat, g: c.GLfloat, b: c.GLfloat, a: c.GLfloat, ) void { const tmp = [_]c.GLfloat{ r, g, b, a }; c.glBindTexture(c.GL_TEXTURE_2D, self.texture); c.glTexParameterfv(c.GL_TEXTURE_2D, c.GL_TEXTURE_BORDER_COLOR, &tmp); c.glBindTexture(c.GL_TEXTURE_2D, 0); } }; fn Buffer(comptime T: type) type { return struct { const Self = @This(); buffer: c.GLuint, usage_type: c.GLenum, pub fn init(usage_type: c.GLenum) Self { var buffer: c.GLuint = undefined; c.glGenBuffers(1, &buffer); return Self{ .buffer = buffer, .usage_type = usage_type, }; } pub fn initNull(len: usize, usage_type: c.GLenum) Self { var ret = Self.init(usage_type); ret.bufferNull(len); return ret; } pub fn initFromSlice(slice: []const T, usage_type: c.GLenum) Self { var ret = Self.init(usage_type); ret.bufferData(slice); return ret; } pub fn deinit(self: *Self) void { c.glDeleteBuffers(1, &self.buffer); } //; pub fn bufferNull(self: Self, len: usize) void { c.glBindBuffer(c.GL_ARRAY_BUFFER, self.buffer); c.glBufferData( c.GL_ARRAY_BUFFER, @intCast(c_long, len * @sizeOf(T)), null, self.usage_type, ); c.glBindBuffer(c.GL_ARRAY_BUFFER, 0); } pub fn bufferData(self: Self, slice: []const T) void { c.glBindBuffer(c.GL_ARRAY_BUFFER, self.buffer); c.glBufferData( c.GL_ARRAY_BUFFER, @intCast(c_long, slice.len * @sizeOf(T)), slice.ptr, self.usage_type, ); c.glBindBuffer(c.GL_ARRAY_BUFFER, 0); } pub fn subData(self: Self, offset: usize, slice: []const T) void { c.glBindBuffer(c.GL_ARRAY_BUFFER, self.buffer); c.glBufferSubData( c.GL_ARRAY_BUFFER, @intCast(c_long, offset), @intCast(c_long, slice.len * @sizeOf(T)), slice.ptr, ); c.glBindBuffer(c.GL_ARRAY_BUFFER, 0); } pub fn bindTo(self: Self, target: c.GLenum) void { c.glBindBuffer(target, self.buffer); } pub fn unbindFrom(target: c.GLenum) void { c.glBindBuffer(target, 0); } }; } pub const VertexAttribute = struct { size: u32, ty: c.GLenum, is_normalized: bool, stride: u32, offset: u32, divisor: u32, }; pub const VertexArray = struct { const Self = @This(); vertex_array: c.GLuint, pub fn init() Self { var vertex_array: c.GLuint = undefined; c.glGenVertexArrays(1, &vertex_array); return Self{ .vertex_array = vertex_array, }; } pub fn deinit(self: *Self) void { c.glDeleteVertexArrays(1, &self.vertex_array); } //; pub fn enableAttribute(self: Self, num: c.GLuint, attrib: VertexAttribute) void { c.glBindVertexArray(self.vertex_array); c.glEnableVertexAttribArray(num); c.glVertexAttribPointer( num, @intCast(c_int, attrib.size), attrib.ty, if (attrib.is_normalized) c.GL_TRUE else c.GL_FALSE, @intCast(c_int, attrib.stride), @intToPtr(*allowzero const c_void, attrib.offset), ); c.glVertexAttribDivisor(num, @intCast(c_uint, attrib.divisor)); } pub fn disableAttribute(self: Self, num: c.GLuint) void { c.glBindVertexArray(self.vertex_array); c.glDisableVertexAttribArray(num); } pub fn bind(self: Self) void { c.glBindVertexArray(self.vertex_array); } pub fn unbind(self: Self) void { c.glBindVertexArray(0); } }; // TODO test works pub const Canvas = struct { const Self = @This(); texture: Texture, rbo: c.GLuint, fbo: c.GLuint, pub fn init(width: u32, height: u32) Self { const texture = Texture.init(width, height); var rbo = undefined; c.glGenRenderbuffers(1, &rbo); c.glBindRenderbuffer(c.GL_RENDERBUFFER, rbo); c.glRenderbufferStorage( c.GL_RENDERBUFFER, c.GL_DEPTH24_STENCIL8, @intCast(c.GLsizei, width), @intCast(c.GLsizei, height), ); c.glBindRenderbuffer(c.GL_RENDERBUFFER, 0); var fbo = undefined; c.glGenFramebuffers(1, &fbo); c.glBindFramebuffer(c.GL_FRAMEBUFFER, fbo); c.glFramebufferTexture2D( c.GL_FRAMEBUFFER, c.GL_COLOR_ATTACHMENT0, c.GL_TEXTURE_2D, texture.texture, 0, ); c.glFramebufferRenderbuffer( c.GL_FRAMEBUFFER, c.GL_DEPTH_STENCIL_ATTACHMENT, c.GL_RENDERBUFFER, rbo, ); c.glBindFramebuffer(c.GL_FRAMEBUFFER, 0); return .{ .texture = texture, .rbo = rbo, .fbo = fbo, }; } pub fn deinit(self: *Self) void { c.DeleteFramebuffers(1, &self.fbo); c.DeleteRenderbuffers(1, &self.rbo); self.texture.deinit(); } //; pub fn bind(self: Self) void { c.glBindFramebuffer(c.GL_FRAMEBUFFER, self.fbo); } pub fn unbind(self: Self) void { c.glBindFramebuffer(c.GL_FRAMEBUFFER, 0); } pub fn setGL_Viewport(self: Self) void { c.glViewport( 0, 0, @intCast(c.GLsizei, self.texture.width), @intCast(c.GLsizei, self.texture.height), ); } }; // TODO // make this so this owns its own data as an arraylist ? // or set it up like how the buff is, where its just some // glbuffers in gpumemory the user can do things with // initNull, initFromSlice, // subData/bufferData can be called on the buffers here directly pub fn Mesh(comptime T: type) type { return struct { const Self = @This(); //TODO // need these in here for length, which is used whenrenering //is there a way aroundthis vertices: []const T, indices: []const u32, vao: VertexArray, vbo: Buffer(T), ebo: Buffer(u32), buffer_type: c.GLenum, draw_type: c.GLenum, pub fn init( vertices: []const T, indices: []const u32, buffer_type: c.GLenum, draw_type: c.GLenum, ) Self { var vao = VertexArray.init(); const vbo = Buffer(T).initFromSlice(vertices, buffer_type); const ebo = Buffer(u32).initFromSlice(indices, buffer_type); vao.bind(); vbo.bindTo(c.GL_ARRAY_BUFFER); T.setAttributes(&vao); ebo.bindTo(c.GL_ELEMENT_ARRAY_BUFFER); vao.unbind(); return Self{ .vertices = vertices, .indices = indices, .vao = vao, .vbo = vbo, .ebo = ebo, .buffer_type = buffer_type, .draw_type = draw_type, }; } pub fn deinit(self: *Self) void { self.ebo.deinit(); self.vbo.deinit(); self.vao.deinit(); } //; pub fn draw(self: Self) void { self.vao.bind(); if (self.indices.len == 0) { c.glDrawArrays( self.draw_type, 0., @intCast(c_int, self.vertices.len), ); } else { c.glDrawElements( self.draw_type, @intCast(c_int, self.indices.len), c.GL_UNSIGNED_INT, null, ); } self.vao.unbind(); } pub fn drawInstanced(self: Self, n: usize) void { self.vao.bind(); if (self.indices.len == 0) { c.glDrawArraysInstanced( self.draw_type, 0., @intCast(c_int, self.vertices.len), @intCast(c_int, n), ); } else { c.glDrawElementsInstanced( self.draw_type, @intCast(c_int, self.indices.len), c.GL_UNSIGNED_INT, null, @intCast(c_int, n), ); } self.vao.unbind(); } }; } pub const Location = struct { const Self = @This(); const TextureData = struct { select: c.GLenum, bind_to: c.GLenum, texture: *const Texture, }; location: c.GLint, pub fn setFloat(self: Self, val: f32) void { c.glUniform1f(self.location, val); } pub fn setInt(self: Self, val: i32) void { c.glUniform1i(self.location, val); } pub fn setUInt(self: Self, val: u32) void { c.glUniform1ui(self.location, val); } pub fn setBool(self: Self, val: bool) void { c.glUniform1i(self.location, if (val) 1 else 0); } pub fn setVec4(self: Self, val: math.Vec4) void { c.glUniform4fv(self.location, 1, @ptrCast([*]const f32, &val)); } pub fn setColor(self: Self, val: math.Color) void { c.glUniform4fv(self.location, 1, @ptrCast([*]const f32, &val)); } pub fn setMat3(self: Self, val: math.Mat3) void { c.glUniformMatrix3fv( self.location, 1, c.GL_FALSE, @ptrCast([*]const f32, &val.data), ); } pub fn setTextureData(self: Self, data: TextureData) void { self.setInt(@intCast(c_int, data.select - c.GL_TEXTURE0)); c.glActiveTexture(data.select); c.glBindTexture(data.bind_to, data.texture.texture); } }; pub fn Instancer(comptime T: type) type { return struct { const Self = @This(); ibo: Buffer(T), data: []T, pub fn init(data: []T) Self { const ibo = Buffer(T).initNull(data.len, c.GL_STREAM_DRAW); return .{ .ibo = ibo, .data = data, }; } pub fn deinit(self: *Self) void { self.ibo.deinit(); } //; pub fn makeVertexArrayCompatible(self: Self, vao: VertexArray) void { vao.bind(); self.ibo.bindTo(c.GL_ARRAY_BUFFER); T.setAttributes(vao); vao.unbind(); } pub fn bind(self: *Self, comptime M: type, mesh: *const Mesh(M)) BoundInstancer(T, M) { return BoundInstancer(T, M){ .base = self, .mesh = mesh, .idx = 0, }; } }; } pub fn BoundInstancer(comptime T: type, comptime M: type) type { return struct { const Self = @This(); base: *Instancer(T), mesh: *const Mesh(M), idx: usize, pub fn unbind(self: *Self) void { if (self.idx != 0) { self.draw(); } } pub fn draw(self: *Self) void { if (self.idx > 0) { self.base.ibo.subData(0, self.base.data[0..self.idx]); self.mesh.drawInstanced(self.idx); self.idx = 0; } } pub fn push(self: *Self, obj: T) void { if (self.idx == self.base.data.len) { self.draw(); } self.base.data[self.idx] = obj; self.idx += 1; } pub fn pull(self: *Self) *T { if (self.idx == self.base.data.len) { self.draw(); } const ret = &self.base.data[self.idx]; self.idx += 1; return ret; } }; }
src/gfx.zig
const ArrayList = @import("std").ArrayList; const Allocator = @import("std").mem.Allocator; const Value = @import("value.zig").Value; /// One byte op codes for the instructions used in our /// bytecode interpreter. pub const OpCode = enum(u8) { define_global, get_local, get_upvalue, get_global, set_local, set_upvalue, set_global, constant, closure, pop, close_upvalue, print, call, return_, negate, add, subtract, multiply, divide, true_, false_, nil, not, equal, not_equal, greater, less, greater_equal, less_equal, jump_if_true, jump_if_false, jump, loop, }; /// A Chunk of bytecode. This is the result of compiling a single /// "Compilation Unit", which in the case of lox is a single function. pub const Chunk = struct { const Self = @This(); /// the bytecode code: Code, /// source file line numbers that generated the bytecode lines: Lines, /// literal values that appeared in the source constants: Constants, pub const Code = ArrayList(u8); pub const Constants = ArrayList(Value); pub const Lines = ArrayList(usize); pub fn init(allocator: *Allocator) Self { return Self{ .code = Code.init(allocator), .lines = Lines.init(allocator), .constants = Constants.init(allocator), }; } pub fn deinit(self: Self) void { self.code.deinit(); self.constants.deinit(); self.lines.deinit(); } /// Write a single byte to the bytecode that was generated from the /// source file at the specified line. pub fn write(self: *Self, byte: u8, line: usize) !void { try self.code.append(byte); try self.lines.append(line); } /// Write an op code to the bytecode that was generated from the /// source file at the specified line. pub fn writeOp(self: *Self, opCode: OpCode, line: usize) !void { try self.write(@enumToInt(opCode), line); } /// Add a constant to the constant store. Returns the index of the /// constant in the storage. pub fn addConstant(self: *Self, constant: Value) !usize { var index = self.constants.items.len; try self.constants.append(constant); return index; } };
src/chunk.zig
const std = @import("std"); const testing = std.testing; const allocator = std.testing.allocator; const desc_usize = std.sort.desc(usize); pub const Polymer = struct { const Pair = struct { e0: u8, e1: u8, pub fn init(e0: u8, e1: u8) Pair { var self = Pair{ .e0 = e0, .e1 = e1, }; return self; } pub fn deinit(_: *Pair) void {} }; cur: usize, pairs: [2]std.AutoHashMap(Pair, usize), rules: std.AutoHashMap(Pair, u8), counts: [26]usize, first: u8, in_rules: bool, pub fn init() Polymer { var self = Polymer{ .cur = 0, .pairs = undefined, .rules = std.AutoHashMap(Pair, u8).init(allocator), .counts = [_]usize{0} ** 26, .first = 0, .in_rules = false, }; self.pairs[0] = std.AutoHashMap(Pair, usize).init(allocator); self.pairs[1] = std.AutoHashMap(Pair, usize).init(allocator); return self; } pub fn deinit(self: *Polymer) void { self.pairs[1].deinit(); self.pairs[0].deinit(); self.rules.deinit(); } pub fn process_line(self: *Polymer, data: []const u8) !void { if (data.len == 0) { self.in_rules = true; return; } if (!self.in_rules) { var e0: u8 = 0; for (data) |e1| { // Remember first element to include it in the count if (self.first == 0) self.first = e1; if (e0 != 0) { const p = Pair.init(e0, e1); try self.count_pair(true, p, 1); } e0 = e1; } } else { var p: Pair = undefined; var pos: usize = 0; var it = std.mem.split(u8, data, " -> "); while (it.next()) |what| : (pos += 1) { if (pos == 0) { p = Pair.init(what[0], what[1]); continue; } if (pos == 1) { // std.debug.warn("RULE {c}{c} -> {c}\n", .{ p.e0, p.e1, what[0] }); try self.rules.put(p, what[0]); continue; } unreachable; } } } pub fn get_diff_top_elements_after_n_steps(self: *Polymer, steps: usize) !usize { var s: usize = 0; while (s < steps) : (s += 1) { // std.debug.warn("STEP {}\n", .{s}); try self.make_step(); } return try self.get_diff_top_elements(); } fn get_diff_top_elements(self: Polymer) !usize { var counts = std.ArrayList(usize).init(allocator); defer counts.deinit(); for (self.counts) |c| { // skip zeroes so that it is easier to find the extremes if (c == 0) continue; try counts.append(c); } std.sort.sort(usize, counts.items, {}, desc_usize); return counts.items[0] - counts.items[counts.items.len - 1]; } fn count_pair(self: *Polymer, first: bool, p: Pair, n: usize) !void { const pos = if (first) self.cur else (1 - self.cur); var c = self.pairs[pos].get(p) orelse 0; // std.debug.warn("CHANGE {c}{c}: {} + {} -> {}\n", .{ p.e0, p.e1, c, n, c + n }); try self.pairs[pos].put(p, c + n); } fn count_element(self: *Polymer, e: u8, n: usize) void { const pos = e - 'A'; self.counts[pos] += n; } fn make_step(self: *Polymer) !void { const nxt = 1 - self.cur; self.pairs[nxt].clearRetainingCapacity(); self.counts = [_]usize{0} ** 26; var it = self.pairs[self.cur].iterator(); while (it.next()) |entry| { const p = entry.key_ptr.*; if (!self.rules.contains(p)) continue; const n = entry.value_ptr.*; const e = self.rules.get(p).?; // std.debug.warn("USING {c}{c} -> {c}\n", .{ p.e0, p.e1, e }); try self.count_pair(false, Pair.init(p.e0, e), n); try self.count_pair(false, Pair.init(e, p.e1), n); self.count_element(e, n); self.count_element(p.e1, n); } self.count_element(self.first, 1); self.cur = nxt; } }; test "sample part a" { const data: []const u8 = \\NNCB \\ \\CH -> B \\HH -> N \\CB -> H \\NH -> C \\HB -> C \\HC -> B \\HN -> C \\NN -> C \\BH -> H \\NC -> B \\NB -> B \\BN -> B \\BB -> N \\BC -> B \\CC -> N \\CN -> C ; var polymer = Polymer.init(); defer polymer.deinit(); var it = std.mem.split(u8, data, "\n"); while (it.next()) |line| { try polymer.process_line(line); } const diff_top_elements = try polymer.get_diff_top_elements_after_n_steps(10); try testing.expect(diff_top_elements == 1588); } test "sample part b" { const data: []const u8 = \\NNCB \\ \\CH -> B \\HH -> N \\CB -> H \\NH -> C \\HB -> C \\HC -> B \\HN -> C \\NN -> C \\BH -> H \\NC -> B \\NB -> B \\BN -> B \\BB -> N \\BC -> B \\CC -> N \\CN -> C ; var polymer = Polymer.init(); defer polymer.deinit(); var it = std.mem.split(u8, data, "\n"); while (it.next()) |line| { try polymer.process_line(line); } const diff_top_elements = try polymer.get_diff_top_elements_after_n_steps(40); try testing.expect(diff_top_elements == 2188189693529); }
2021/p14/polymer.zig
const std = @import("std"); pub const Settings = struct { // See: https://www.postgresql.org/docs/9.1/libpq-connect.html // See: https://github.com/eventide-project/message-store-postgres/blob/master/lib/message_store/postgres/settings.rb#L12-L32 host: ?[]const u8 = null, hostaddr: ?[]const u8 = null, port: ?u32 = null, dbname: ?[]const u8 = null, user: ?[]const u8 = null, password: ?[]const u8 = null, connect_timeout: ?u32 = null, //client_encoding options: ?[]const u8 = null, //application_name //fallback_application_name keepalives: ?u32 = null, keepalives_idle: ?u32 = null, keepalives_interval: ?u32 = null, keepalives_count: ?u32 = null, //tty //sslmode //requiressl (deprecated) //sslcert //sslkey //sslrootcert //sslcrl //requirepeer //krbsrvname //gsslib //service //pub const Read = struct { // pub const Arguments = struct { // path: []const u8 = "settings/message_db.json", // allocator: ?*std.mem.Allocator = null // }; // pub fn call(args: Arguments) Settings { // const path = args.path; // var allocator: *std.mem.Allocator = undefined; // if (args.allocator) |a| { // allocator = a; // } else { // var arena = std.heap.ArenaAllocator.init(std.heap.page_allocator); // defer arena.deinit(); // allocator = &arena.allocator; // } // const file = std.fs.cwd().openFile(path, .{ .read = true }) catch unreachable; // const file_reader = file.reader(); // const buffer = allocator.alloc(u8, 1024) catch unreachable; // defer allocator.free(buffer); // const bytes = file_reader.readAll(buffer) catch unreachable; // var token_stream = std.json.TokenStream.init(buffer[0..bytes]); // comptime { // @setEvalBranchQuota(100000); // } // var settings = std.json.parse(Settings, &token_stream, .{ .allocator = allocator }) catch unreachable; // return settings; // } //}; //pub fn read(args: Read.Arguments) Settings { // return Read.call(args); // } };
src/settings.zig
const std = @import("std"); // TODO make it a build option or smth? const MAIN_FOLDER_PATH = "/etc/nyaf"; const CFG_FILE_PATH = MAIN_FOLDER_PATH ++ "/config"; const RULE_FILE_PATH = MAIN_FOLDER_PATH ++ "/rules"; const configs = @import("config.zig"); const Config = configs.Config; const rules_mod = @import("rules.zig"); const Context = struct { allocator: *std.mem.Allocator, cfg: ?Config = null, const Self = @This(); pub fn readConfig(self: *Self) !void { var config_file_opt = std.fs.cwd().openFile( CFG_FILE_PATH, .{ .read = true }, ) catch |err| blk: { if (err == error.FileNotFound) break :blk null else return err; }; if (config_file_opt) |config_file| { self.cfg = try configs.parseConfig(self.allocator, config_file); } else { self.cfg = Config{}; } } pub fn saveConfig(self: *Self) !void { std.fs.makeDirAbsolute(MAIN_FOLDER_PATH) catch |err| switch (err) { error.PathAlreadyExists => {}, else => return err, }; var config_file = try std.fs.cwd().createFile(CFG_FILE_PATH, .{ .read = false, .truncate = true, }); try std.json.stringify(self.cfg.?, .{}, config_file.writer()); } pub fn deinit(self: *const Self) void { if (self.cfg) |cfg| { configs.freeConfig(self.allocator, cfg); } } pub fn status(self: *Self) !void { try self.readConfig(); if (self.cfg) |cfg| { std.debug.warn("enabled? {}\n", .{cfg.enabled}); } else { std.debug.warn("nyaf config file not found\n", .{}); } } pub fn enable(self: *Self) !void { try self.readConfig(); self.cfg.?.enabled = true; try self.saveConfig(); } pub fn disable(self: *Self) !void { try self.readConfig(); self.cfg.?.enabled = false; try self.saveConfig(); } }; pub fn main() anyerror!void { var gpa = std.heap.GeneralPurposeAllocator(.{}){}; defer { _ = gpa.deinit(); } var allocator = &gpa.allocator; var args_it = std.process.args(); _ = args_it.skip(); const action = try (args_it.next(allocator) orelse @panic("expected action")); defer allocator.free(action); var ctx = Context{ .allocator = allocator }; defer ctx.deinit(); if (std.mem.eql(u8, action, "enable")) { try ctx.enable(); } else if (std.mem.eql(u8, action, "disable")) { try ctx.disable(); } else if (std.mem.eql(u8, action, "allow")) { const port = try (args_it.next(allocator) orelse @panic("expected action")); defer allocator.free(port); // if port == all, warn("allow all is unwanted"), ctx.allowAll(); // ctx.allow(port, from, to); } else if (std.mem.eql(u8, action, "deny")) { const port = try (args_it.next(allocator) orelse @panic("expected action")); defer allocator.free(port); // if port == all, ctx.denyAll(); // ctx.deny(); } else if (std.mem.eql(u8, action, "status") or std.mem.eql(u8, action, "list")) { try ctx.status(); } else if (std.mem.eql(u8, action, "version")) { std.log.info("nyaf v0.0.1", .{}); } } test "refAllDecls" { std.meta.refAllDecls(@This()); }
src/main.zig
const std = @import("std"); const builtin = @import("builtin"); const math = std.math; const mem = std.mem; const debug = std.debug; const testing = std.testing; const min = @import("index.zig").min; const max = @import("index.zig").max; pub fn Interval(comptime T: type) type { const info = @typeInfo(T); debug.assert(info == .Int or info == .Float or info == .ComptimeInt or info == .ComptimeFloat); return struct { const Self = @This(); min: T, max: T, pub fn fromSlice(nums: []const T) Self { return Self{ .min = mem.min(T, nums), .max = mem.max(T, nums), }; } pub fn add(a: Self, b: Self) Self { return Self{ .min = a.min + b.min, .max = a.max + b.max, }; } pub fn sub(a: Self, b: Self) Self { return Self{ .min = a.min - b.max, .max = a.max - b.min, }; } pub fn mul(a: Self, b: Self) Self { return fromSlice(&[_]T{ a.min * b.min, a.min * b.max, a.max * b.min, a.max * b.max, }); } pub fn div(a: Self, b: Self) Self { debug.assert(b.min != 0 and b.max != 0); return fromSlice(&[_]T{ a.min / b.min, a.min / b.max, a.max / b.min, a.max / b.max, }); } pub fn mod(a: Self, b: Self) Self { debug.assert(b.min != 0 and b.max != 0); return fromSlice([_]T{ a.min % b.min, a.min % b.max, a.max % b.min, a.max % b.max, }); } pub fn shiftLeft(a: Self, b: Self) Self { return fromSlice([_]T{ a.min << b.min, a.min << b.max, a.max << b.min, a.max << b.max, }); } pub fn shiftRight(a: Self, b: Self) Self { return fromSlice([_]T{ a.min >> b.min, a.min >> b.max, a.max >> b.min, a.max >> b.max, }); } }; }
src/math/interval.zig
const std = @import("std"); const assert = std.debug.assert; const Allocator = std.mem.Allocator; const invalid_character = 0x98; /// Caller must free returned memory. pub fn windows1251ToUtf8Alloc(allocator: Allocator, windows1251_text: []const u8) ![]u8 { var buffer = try std.ArrayList(u8).initCapacity(allocator, windows1251_text.len); errdefer buffer.deinit(); for (windows1251_text) |c| switch (c) { 0...127 => try buffer.append(c), invalid_character => return error.InvalidWindows1251Character, else => { // ensure we always have enough space for any codepoint try buffer.ensureUnusedCapacity(4); const codepoint = windows1251ToUtf8Codepoint(c); const codepoint_buffer = buffer.unusedCapacitySlice(); const codepoint_size = std.unicode.utf8Encode(codepoint, codepoint_buffer) catch unreachable; buffer.items.len += codepoint_size; }, }; return buffer.toOwnedSlice(); } /// buf must be four times as big as windows1251_text to ensure that it /// can contain the converted string pub fn windows1251ToUtf8(windows1251_text: []const u8, buf: []u8) ![]u8 { assert(buf.len >= windows1251_text.len * 4); var i: usize = 0; for (windows1251_text) |c| switch (c) { 0...127 => { buf[i] = c; i += 1; }, invalid_character => return error.InvalidWindows1251Character, else => { const codepoint = windows1251ToUtf8Codepoint(c); const codepoint_size = std.unicode.utf8Encode(codepoint, buf[i..]) catch unreachable; i += codepoint_size; }, }; return buf[0..i]; } pub const Windows1251DetectionThreshold = struct { /// Number of Cyrillic characters in a row before /// the text is assumed to be Windows1251. streak: usize, /// If there are zero non-Cyrillic characters, then /// there must be at least this many Cyrillic characters /// for the text to be assumed Windows1251. min_cyrillic_letters: usize, }; pub fn reachesDetectionThreshold(text: []const u8, comptime threshold: Windows1251DetectionThreshold) bool { var cyrillic_streak: usize = 0; var cyrillic_letters: usize = 0; var found_streak: bool = false; var ascii_letters: usize = 0; for (text) |c| { switch (c) { // The invalid character being present disqualifies // the text entirely invalid_character => return false, 'a'...'z', 'A'...'Z' => { cyrillic_streak = 0; ascii_letters += 1; }, // zig fmt: off // these are the cyrillic characters only 0x80, 0x81, 0x83, 0x8A, 0x8C...0x90, 0x9A, 0x9C...0x9F, 0xA1...0xA3, 0xA5, 0xA8, 0xAA, 0xAF, 0xB2...0xB4, 0xB8, 0xBA, 0xBC...0xFF, // zig fmt: on => { cyrillic_streak += 1; cyrillic_letters += 1; if (cyrillic_streak >= threshold.streak) { // We can't return early here // since we still need to validate that // the invalid character isn't present // anywhere in the text found_streak = true; } }, // control characters, punctuation, numbers, symbols, etc // are irrelevant else => {}, } } const all_cyrillic = ascii_letters == 0 and cyrillic_letters >= threshold.min_cyrillic_letters; return found_streak or all_cyrillic; } pub fn couldBeWindows1251(text: []const u8) bool { return reachesDetectionThreshold(text, .{ .streak = 4, .min_cyrillic_letters = 2 }); } test "windows1251 to utf8" { var buf: [512]u8 = undefined; const utf8 = try windows1251ToUtf8("a\xE0b\xE6c\xEFd", &buf); try std.testing.expectEqualSlices(u8, "aΠ°bΠΆcΠΏd", utf8); } test "windows1251 to utf8 alloc" { const utf8 = try windows1251ToUtf8Alloc(std.testing.allocator, "a\xE0b\xE6c\xEFd"); defer std.testing.allocator.free(utf8); try std.testing.expectEqualSlices(u8, "aΠ°bΠΆcΠΏd", utf8); } test "could be windows1251" { try std.testing.expect(!couldBeWindows1251("abcd")); try std.testing.expect(!couldBeWindows1251("")); try std.testing.expect(!couldBeWindows1251("abc\xC8\xC8")); try std.testing.expect(!couldBeWindows1251("\xC8\xC8\xC8\xC8\x98")); try std.testing.expect(!couldBeWindows1251("a\xE0b\xE6c\xEFd")); try std.testing.expect(couldBeWindows1251("\xC8\xC8")); try std.testing.expect(couldBeWindows1251("abc\xC8\xC8\xE6\xEF")); } // TODO: Is an array lookup better here? /// 0x00...0x7F and 0x98 are not valid inputs to this function. /// Mapping comes from: /// https://www.unicode.org/Public/MAPPINGS/VENDORS/MICSFT/WINDOWS/CP1251.TXT /// Note that it's the same as /// https://www.unicode.org/Public/MAPPINGS/VENDORS/MICSFT/WindowsBestFit/bestfit1251.txt /// except for 0x98 which we treat as invalid fn windows1251ToUtf8Codepoint(c: u8) u21 { return switch (c) { 0x00...0x7F => unreachable, 0x80 => 0x0402, // CYRILLIC CAPITAL LETTER DJE 0x81 => 0x0403, // CYRILLIC CAPITAL LETTER GJE 0x82 => 0x201A, // SINGLE LOW-9 QUOTATION MARK 0x83 => 0x0453, // CYRILLIC SMALL LETTER GJE 0x84 => 0x201E, // DOUBLE LOW-9 QUOTATION MARK 0x85 => 0x2026, // HORIZONTAL ELLIPSIS 0x86 => 0x2020, // DAGGER 0x87 => 0x2021, // DOUBLE DAGGER 0x88 => 0x20AC, // EURO SIGN 0x89 => 0x2030, // PER MILLE SIGN 0x8A => 0x0409, // CYRILLIC CAPITAL LETTER LJE 0x8B => 0x2039, // SINGLE LEFT-POINTING ANGLE QUOTATION MARK 0x8C => 0x040A, // CYRILLIC CAPITAL LETTER NJE 0x8D => 0x040C, // CYRILLIC CAPITAL LETTER KJE 0x8E => 0x040B, // CYRILLIC CAPITAL LETTER TSHE 0x8F => 0x040F, // CYRILLIC CAPITAL LETTER DZHE 0x90 => 0x0452, // CYRILLIC SMALL LETTER DJE 0x91 => 0x2018, // LEFT SINGLE QUOTATION MARK 0x92 => 0x2019, // RIGHT SINGLE QUOTATION MARK 0x93 => 0x201C, // LEFT DOUBLE QUOTATION MARK 0x94 => 0x201D, // RIGHT DOUBLE QUOTATION MARK 0x95 => 0x2022, // BULLET 0x96 => 0x2013, // EN DASH 0x97 => 0x2014, // EM DASH 0x98 => unreachable, // UNDEFINED 0x99 => 0x2122, // TRADE MARK SIGN 0x9A => 0x0459, // CYRILLIC SMALL LETTER LJE 0x9B => 0x203A, // SINGLE RIGHT-POINTING ANGLE QUOTATION MARK 0x9C => 0x045A, // CYRILLIC SMALL LETTER NJE 0x9D => 0x045C, // CYRILLIC SMALL LETTER KJE 0x9E => 0x045B, // CYRILLIC SMALL LETTER TSHE 0x9F => 0x045F, // CYRILLIC SMALL LETTER DZHE 0xA0 => 0x00A0, // NO-BREAK SPACE 0xA1 => 0x040E, // CYRILLIC CAPITAL LETTER SHORT U 0xA2 => 0x045E, // CYRILLIC SMALL LETTER SHORT U 0xA3 => 0x0408, // CYRILLIC CAPITAL LETTER JE 0xA4 => 0x00A4, // CURRENCY SIGN 0xA5 => 0x0490, // CYRILLIC CAPITAL LETTER GHE WITH UPTURN 0xA6 => 0x00A6, // BROKEN BAR 0xA7 => 0x00A7, // SECTION SIGN 0xA8 => 0x0401, // CYRILLIC CAPITAL LETTER IO 0xA9 => 0x00A9, // COPYRIGHT SIGN 0xAA => 0x0404, // CYRILLIC CAPITAL LETTER UKRAINIAN IE 0xAB => 0x00AB, // LEFT-POINTING DOUBLE ANGLE QUOTATION MARK 0xAC => 0x00AC, // NOT SIGN 0xAD => 0x00AD, // SOFT HYPHEN 0xAE => 0x00AE, // REGISTERED SIGN 0xAF => 0x0407, // CYRILLIC CAPITAL LETTER YI 0xB0 => 0x00B0, // DEGREE SIGN 0xB1 => 0x00B1, // PLUS-MINUS SIGN 0xB2 => 0x0406, // CYRILLIC CAPITAL LETTER BYELORUSSIAN-UKRAINIAN I 0xB3 => 0x0456, // CYRILLIC SMALL LETTER BYELORUSSIAN-UKRAINIAN I 0xB4 => 0x0491, // CYRILLIC SMALL LETTER GHE WITH UPTURN 0xB5 => 0x00B5, // MICRO SIGN 0xB6 => 0x00B6, // PILCROW SIGN 0xB7 => 0x00B7, // MIDDLE DOT 0xB8 => 0x0451, // CYRILLIC SMALL LETTER IO 0xB9 => 0x2116, // NUMERO SIGN 0xBA => 0x0454, // CYRILLIC SMALL LETTER UKRAINIAN IE 0xBB => 0x00BB, // RIGHT-POINTING DOUBLE ANGLE QUOTATION MARK 0xBC => 0x0458, // CYRILLIC SMALL LETTER JE 0xBD => 0x0405, // CYRILLIC CAPITAL LETTER DZE 0xBE => 0x0455, // CYRILLIC SMALL LETTER DZE 0xBF => 0x0457, // CYRILLIC SMALL LETTER YI 0xC0 => 0x0410, // CYRILLIC CAPITAL LETTER A 0xC1 => 0x0411, // CYRILLIC CAPITAL LETTER BE 0xC2 => 0x0412, // CYRILLIC CAPITAL LETTER VE 0xC3 => 0x0413, // CYRILLIC CAPITAL LETTER GHE 0xC4 => 0x0414, // CYRILLIC CAPITAL LETTER DE 0xC5 => 0x0415, // CYRILLIC CAPITAL LETTER IE 0xC6 => 0x0416, // CYRILLIC CAPITAL LETTER ZHE 0xC7 => 0x0417, // CYRILLIC CAPITAL LETTER ZE 0xC8 => 0x0418, // CYRILLIC CAPITAL LETTER I 0xC9 => 0x0419, // CYRILLIC CAPITAL LETTER SHORT I 0xCA => 0x041A, // CYRILLIC CAPITAL LETTER KA 0xCB => 0x041B, // CYRILLIC CAPITAL LETTER EL 0xCC => 0x041C, // CYRILLIC CAPITAL LETTER EM 0xCD => 0x041D, // CYRILLIC CAPITAL LETTER EN 0xCE => 0x041E, // CYRILLIC CAPITAL LETTER O 0xCF => 0x041F, // CYRILLIC CAPITAL LETTER PE 0xD0 => 0x0420, // CYRILLIC CAPITAL LETTER ER 0xD1 => 0x0421, // CYRILLIC CAPITAL LETTER ES 0xD2 => 0x0422, // CYRILLIC CAPITAL LETTER TE 0xD3 => 0x0423, // CYRILLIC CAPITAL LETTER U 0xD4 => 0x0424, // CYRILLIC CAPITAL LETTER EF 0xD5 => 0x0425, // CYRILLIC CAPITAL LETTER HA 0xD6 => 0x0426, // CYRILLIC CAPITAL LETTER TSE 0xD7 => 0x0427, // CYRILLIC CAPITAL LETTER CHE 0xD8 => 0x0428, // CYRILLIC CAPITAL LETTER SHA 0xD9 => 0x0429, // CYRILLIC CAPITAL LETTER SHCHA 0xDA => 0x042A, // CYRILLIC CAPITAL LETTER HARD SIGN 0xDB => 0x042B, // CYRILLIC CAPITAL LETTER YERU 0xDC => 0x042C, // CYRILLIC CAPITAL LETTER SOFT SIGN 0xDD => 0x042D, // CYRILLIC CAPITAL LETTER E 0xDE => 0x042E, // CYRILLIC CAPITAL LETTER YU 0xDF => 0x042F, // CYRILLIC CAPITAL LETTER YA 0xE0 => 0x0430, // CYRILLIC SMALL LETTER A 0xE1 => 0x0431, // CYRILLIC SMALL LETTER BE 0xE2 => 0x0432, // CYRILLIC SMALL LETTER VE 0xE3 => 0x0433, // CYRILLIC SMALL LETTER GHE 0xE4 => 0x0434, // CYRILLIC SMALL LETTER DE 0xE5 => 0x0435, // CYRILLIC SMALL LETTER IE 0xE6 => 0x0436, // CYRILLIC SMALL LETTER ZHE 0xE7 => 0x0437, // CYRILLIC SMALL LETTER ZE 0xE8 => 0x0438, // CYRILLIC SMALL LETTER I 0xE9 => 0x0439, // CYRILLIC SMALL LETTER SHORT I 0xEA => 0x043A, // CYRILLIC SMALL LETTER KA 0xEB => 0x043B, // CYRILLIC SMALL LETTER EL 0xEC => 0x043C, // CYRILLIC SMALL LETTER EM 0xED => 0x043D, // CYRILLIC SMALL LETTER EN 0xEE => 0x043E, // CYRILLIC SMALL LETTER O 0xEF => 0x043F, // CYRILLIC SMALL LETTER PE 0xF0 => 0x0440, // CYRILLIC SMALL LETTER ER 0xF1 => 0x0441, // CYRILLIC SMALL LETTER ES 0xF2 => 0x0442, // CYRILLIC SMALL LETTER TE 0xF3 => 0x0443, // CYRILLIC SMALL LETTER U 0xF4 => 0x0444, // CYRILLIC SMALL LETTER EF 0xF5 => 0x0445, // CYRILLIC SMALL LETTER HA 0xF6 => 0x0446, // CYRILLIC SMALL LETTER TSE 0xF7 => 0x0447, // CYRILLIC SMALL LETTER CHE 0xF8 => 0x0448, // CYRILLIC SMALL LETTER SHA 0xF9 => 0x0449, // CYRILLIC SMALL LETTER SHCHA 0xFA => 0x044A, // CYRILLIC SMALL LETTER HARD SIGN 0xFB => 0x044B, // CYRILLIC SMALL LETTER YERU 0xFC => 0x044C, // CYRILLIC SMALL LETTER SOFT SIGN 0xFD => 0x044D, // CYRILLIC SMALL LETTER E 0xFE => 0x044E, // CYRILLIC SMALL LETTER YU 0xFF => 0x044F, // CYRILLIC SMALL LETTER YA }; }
src/windows1251.zig
const std = @import("std"); const wasm = std.wasm; const TypeInfo = std.builtin.TypeInfo; /// Wasm union that contains the value of each possible `ValueType` pub const Value = union(ValueType) { i32: i32, i64: i64, f32: f32, f64: f64, /// Reference to another function regardless of their function type funcref: indexes.Func, /// Reference to an external object (object from the embedder) externref: u32, }; /// Value types for locals and globals pub const NumType = enum(u8) { i32 = 0x7F, i64 = 0x7E, f32 = 0xfD, f64 = 0xfE, }; /// Reference types, where the funcref references to a function regardless of its type /// and ref references an object from the embedder. pub const RefType = enum(u8) { funcref = 0x70, externref = 0x6F, }; /// Represents the several types a wasm value can have pub const ValueType = MergedEnums(NumType, RefType); /// Wasm sections, including proposals. /// Section is built using `std.wasm.Section` and adding /// proposed sections to it. /// /// Note: This version is non-exhaustive to continue parsing /// when a new section is proposed but not yet implemented. pub const Section = MergedEnum(wasm.Section, &.{ .{ .name = "module", .value = 14 }, .{ .name = "instance", .value = 15 }, .{ .name = "alias", .value = 16 }, }); /// Merges a given enum type and a slice of `EnumField` into a new enum type fn MergedEnum(comptime T: type, comptime fields: []const TypeInfo.EnumField) type { if (@typeInfo(T) != .Enum) { @compileError("Given type 'T' must be an enum type but instead was given: " ++ @typeName(T)); } const old_fields = std.meta.fields(T); var new_fields: [fields.len + old_fields.len]TypeInfo.EnumField = undefined; std.mem.copy(TypeInfo.EnumField, &new_fields, old_fields); std.mem.copy(TypeInfo.EnumField, new_fields[old_fields.len..], fields); return @Type(.{ .Enum = .{ .layout = .Auto, .tag_type = u8, .fields = &new_fields, .decls = &.{}, .is_exhaustive = false, } }); } /// Merges two enums into a single enum type fn MergedEnums(comptime T: type, comptime Z: type) type { return MergedEnum(T, std.meta.fields(Z)); } /// External types that can be imported or exported between to/from the host pub const ExternalType = wasm.ExternalKind; /// Limits classify the size range of resizeable storage associated with memory types and table types. pub const Limits = struct { min: u32, max: ?u32, }; /// The type of block types, similarly to `ValueType` with the difference being /// that it adds an additional type 'empty' which is used for blocks with no return value. pub const BlockType = MergedEnum(ValueType, &.{.{ .name = "block_empty", .value = wasm.block_empty, }}); pub const InitExpression = union(enum) { i32_const: i32, /// Uses the value of a global at index `global_get` global_get: u32, }; pub const indexes = struct { pub const Type = enum(u32) { _ }; pub const Func = enum(u32) { _ }; pub const Table = enum(u32) { _ }; pub const Mem = enum(u32) { _ }; pub const global = enum(u32) { _ }; pub const Elem = enum(u32) { _ }; pub const Data = enum(u32) { _ }; pub const Local = enum(u32) { _ }; pub const Label = enum(u32) { _ }; }; pub const sections = struct { pub const Custom = struct { name: []const u8, data: []const u8, start: usize, end: usize, pub fn format(self: Custom, comptime fmt: []const u8, options: std.fmt.FormatOptions, writer: anytype) !void { _ = fmt; _ = options; try writer.print("{s: >8} start=0x{x:0>8} end=0x{x:0>8} (size=0x{x:0>8}) \"{s}\"", .{ "Custom", self.start, self.end, self.end - self.start, self.name, }); } }; pub const Type = struct { params: []const ValueType, returns: []const ValueType, }; pub const Import = struct { module: []const u8, name: []const u8, kind: Kind, pub const Kind = union(ExternalType) { function: indexes.Type, table: struct { reftype: RefType, limits: Limits, }, memory: Limits, global: struct { valtype: ValueType, mutable: bool, }, }; }; pub const Func = struct { type_idx: indexes.Type, }; pub const Table = struct { limits: Limits, reftype: RefType, }; pub const Memory = struct { limits: Limits, }; pub const Global = struct { valtype: ValueType, mutable: bool, init: InitExpression, }; pub const Export = struct { name: []const u8, kind: ExternalType, index: u32, }; pub const Element = struct { table_idx: indexes.Table, offset: InitExpression, func_idxs: []const indexes.Func, }; pub const Code = struct { pub const Local = struct { valtype: ValueType, count: u32, }; locals: []const Local, body: []const Instruction, }; pub const Data = struct { index: indexes.Mem, offset: InitExpression, data: []const u8, }; }; /// Represents a wasm module, containing the version /// of the wasm spec it complies with, and access to all of its /// sections. pub const Module = struct { custom: []const sections.Custom = &.{}, types: SectionData(sections.Type) = .{}, imports: SectionData(sections.Import) = .{}, functions: SectionData(sections.Func) = .{}, tables: SectionData(sections.Table) = .{}, memories: SectionData(sections.Memory) = .{}, globals: SectionData(sections.Global) = .{}, exports: SectionData(sections.Export) = .{}, elements: SectionData(sections.Element) = .{}, code: SectionData(sections.Code) = .{}, data: SectionData(sections.Data) = .{}, start: ?indexes.Func = null, version: u32, /// Returns a custom section by its name. /// Will return `null` when the custom section of a given `name` does not exist. pub fn customByName(self: Module, name: []const u8) ?sections.Custom { return for (self.custom) |custom| { if (std.mem.eql(u8, custom.name, name)) break custom; } else null; } }; pub fn SectionData(comptime T: type) type { return struct { data: []const T = &.{}, start: usize = 0, end: usize = 0, /// Formats the `SectionData` for debug purposes pub fn format(self: @This(), comptime fmt: []const u8, options: std.fmt.FormatOptions, writer: anytype) !void { _ = options; _ = fmt; const type_name = comptime blk: { var name: [@typeName(T).len]u8 = undefined; std.mem.copy(u8, &name, @typeName(T)); name[0] = std.ascii.toUpper(name[0]); break :blk name; }; try writer.print("{s: >8} start=0x{x:0>8} end=0x{x:0>8} (size=0x{x:0>8}) count: {d}", .{ type_name, self.start, self.end, self.end - self.start, self.data.len, }); } }; } pub const Instruction = struct { opcode: wasm.Opcode, secondary: ?SecondaryOpcode = null, value: InstrValue, pub const InstrValue = union { none: void, u32: u32, i32: i32, i64: i64, f32: f32, f64: f64, reftype: RefType, blocktype: BlockType, multi_valtype: struct { data: [*]ValueType, len: u32, }, multi: struct { x: u32, y: u32, }, list: struct { data: [*]u32, len: u32, }, }; }; /// Secondary opcode belonging to primary opcodes /// that have as opcode 0xFC pub const SecondaryOpcode = enum(u8) { i32_trunc_sat_f32_s = 0, i32_trunc_sat_f32_u = 1, i32_trunc_sat_f64_s = 2, i32_trunc_sat_f64_u = 3, i64_trunc_sat_f32_s = 4, i64_trunc_sat_f32_u = 5, i64_trunc_sat_f64_s = 6, i64_trunc_sat_f64_u = 7, memory_init = 8, data_drop = 9, memory_copy = 10, memory_fill = 11, table_init = 12, table_drop = 13, table_copy = 14, table_grow = 15, table_size = 16, table_fill = 17, _, }; pub const need_secondary = @intToEnum(wasm.Opcode, 0xFC); pub const table_get = @intToEnum(wasm.Opcode, 0x25); pub const table_set = @intToEnum(wasm.Opcode, 0x26);
src/wasm.zig
const std = @import("std"); const compiler = @import("compiler.zig"); const byte_code = @import("bytecode.zig"); const ByteCode = byte_code.ByteCode; const _builtin = @import("builtins.zig"); const Value = @import("Value.zig"); const Type = Value.Type; const BuiltinError = _builtin.BuiltinError; const testing = std.testing; const Allocator = std.mem.Allocator; const Errors = @import("error.zig").Errors; const Gc = @import("Gc.zig"); //! The Virtual Machine of Luf is stack-based. //! Currently the stack has a size of 2048 (pre-allocated) /// VM is a stack-based Virtual Machine /// Although a register-based VM is more performant, /// a stack-based one is more understandable pub const Vm = struct { /// Stack pointer points to the next value sp: usize = 0, /// Stack has a max of 2048 Value's that it can hold stack: [2048]*Value = undefined, /// Globals that live inside the VM /// Is resized after each run() call by flushing out all /// values but its functions globals: std.ArrayList(*Value), locals: std.ArrayList(*Value), /// Call stack that contains the instruction and stack pointer, as well as the instructions /// to run the stack call_stack: CallStack, /// allocator used for vm's internal lists and hashmaps allocator: *Allocator, /// List of errors generated by parser/compiler/vm errors: Errors, /// The instructions to run code: ?*ByteCode, /// Libraries that are loaded into the VM /// By default, the standard library is already loaded under key 'std' libs: std.StringArrayHashMapUnmanaged(*Value), /// Garbage collector gc: *Gc, /// Possible errors that occur during runtime pub const Error = error{ OutOfMemory, RuntimeError } || BuiltinError; /// List of call frames that get populated during function calls /// and popped on return statements const CallStack = std.ArrayList(Frame); /// Function `Frame` on the callstack const Frame = struct { /// Frame pointer which contains the actual function `Value`, which is used to check for tail recursion fp: ?*Value, /// `Instruction` pointer to the position of the function in the bytecode's instruction set ip: usize, }; /// Creates a new `Vm` and adds Luf's standard library to the virtual machine /// This will put Vm on the heap, and `deinit()` must be called to free its memory pub fn init(allocator: *Allocator) !*Vm { const gc = try allocator.create(Gc); gc.* = Gc.init(allocator); const vm = try allocator.create(Vm); vm.* = .{ .globals = std.ArrayList(*Value).init(allocator), .call_stack = CallStack.init(allocator), .allocator = allocator, .errors = Errors.init(allocator), .code = null, .libs = std.StringArrayHashMapUnmanaged(*Value){}, .gc = gc, .locals = std.ArrayList(*Value).init(allocator), }; gc.vm = vm; try vm.loadLib("std", @import("std/std.zig")); return vm; } /// Frees all memory allocated by the `Vm`. /// The vm is no longer valid for use after calling deinit pub fn deinit(self: *Vm) void { self.globals.deinit(); self.call_stack.deinit(); self.errors.deinit(); self.libs.deinit(self.allocator); self.gc.deinit(); self.locals.deinit(); self.allocator.destroy(self.gc); self.allocator.destroy(self); } /// Compiles the given source code and then runs it on the `Vm` pub fn compileAndRun(self: *Vm, source: []const u8) !void { var cu = try compiler.compile(self.allocator, source, &self.errors); defer cu.deinit(); var code = try byte_code.Instructions.fromCu(self.allocator, cu); defer code.deinit(); self.code = &code; try self.run(); } /// Loads new bytecode into the Vm pub fn loadCode(self: *Vm, code: *ByteCode) void { self.code = code; } /// Loads a Zig library into the VM pub fn loadLib(self: *Vm, name: []const u8, lib: anytype) !void { try self.libs.putNoClobber( self.allocator, name, try Value.fromZig(self.gc, lib), ); } /// Calls a function from Luf using the given arguments /// Returns the value from the function back to Zig as `Value` pub fn callFunc(self: *Vm, func_name: []const u8, args: anytype) !*Value { std.debug.assert(self.sp == 0); if (self.code == null) return error.NoInstructions; var maybe_func: *Value = blk: { for (self.globals.items) |global, i| { if (global.ty == .function and global.toFunction().name != null and std.mem.eql(u8, func_name, global.toFunction().name.?)) break :blk global; } return error.UndefinedFunction; }; const func = maybe_func.toFunction(); if (func.arg_len != args.len) { return error.IncorrectArgumentLength; } inline for (args) |arg, i| { if (i >= self.locals.items.len) try self.locals.resize(i + 1); self.locals.items[i] = (try Value.fromZig(self.gc, arg)); } // initial call stack for main try self.call_stack.append(.{ .fp = null, .ip = 0, }); // function call stack try self.call_stack.append(.{ .fp = maybe_func, .ip = func.entry, }); try self.run(); return self.pop(); } /// Runs the given `ByteCode` on the Virtual Machine pub fn run(self: *Vm) Error!void { if (self.code == null) return self.fail("No bytecode instructions loaded"); if (self.call_stack.items.len == 0) { try self.call_stack.append(.{ .fp = null, .ip = 0, }); } var loaded_funcs: usize = 0; while (self.frame().ip < self.code.?.instructions.len) { var current_frame = self.frame(); defer current_frame.ip += 1; const inst = self.code.?.instructions[current_frame.ip]; switch (inst.getOp()) { .load_integer => try self.push( try Value.Integer.create(self.gc, @bitCast(i64, inst.integer)), ), .load_string => try self.push( try Value.String.create(self.gc, inst.string), ), .load_func => { const func = inst.function; const val = try Value.Function.create( self.gc, func.name, func.locals, func.arg_len, func.entry, ); try self.push(val); }, .equal, .not_equal, .less_than, .greater_than, .less_than_equal, .greater_than_equal, .@"and", .@"or", => try self.execCmp(inst.op), .add, .sub, .mul, .div, .mod, .bitwise_and, .bitwise_or, .bitwise_xor, .shift_left, .shift_right, => try self.execBinOp(inst.op), .assign_add, .assign_div, .assign_mul, .assign_sub, => try self.execAssignAndBinOp(inst.op), .pop => _ = self.pop(), .load_true => try self.push(&Value.True.base), .load_false => try self.push(&Value.False.base), .minus => try self.execNegation(), .not => try self.execNot(), .bitwise_not => try self.execBitwiseNot(), .load_nil => try self.push(&Value.Nil), .load_void => try self.push(&Value.Void), .jump => current_frame.ip = inst.ptr.pos - 1, .jump_false => { const condition = self.pop(); if (!isTrue(condition)) current_frame.ip = inst.ptr.pos - 1; }, .bind_global => { const val = self.pop(); // enlarge if global list is smaller than position // we don't use 'insert(n)' because that will change the position // of values behind n, but we want to overwrite it instead. if (self.globals.items.len <= inst.ptr.pos) try self.globals.resize(inst.ptr.pos + 1); self.globals.items[inst.ptr.pos] = val; if (val.isType(.function)) loaded_funcs += 1; }, .load_global => try self.push(self.globals.items[inst.ptr.pos]), .make_array => try self.makeArray(inst), .make_map => try self.makeMap(inst), .make_enum => try self.makeEnum(inst), .get_by_index => try self.getIndexValue(), .set_by_index => try self.setIndexValue(), .@"return", .return_value => _ = self.call_stack.pop(), .call => try self.execFunctionCall(inst, self.code.?.instructions[current_frame.ip + 1]), .bind_local => { const val = self.pop(); if (inst.ptr.pos >= self.locals.items.len) try self.locals.resize(inst.ptr.pos + 1); self.locals.items[inst.ptr.pos] = val; }, .load_local => try self.push(self.locals.items[inst.ptr.pos]), .assign_global => { const val = self.pop(); if (inst.ptr.pos >= self.globals.items.len) try self.globals.resize(inst.ptr.pos + 1); self.globals.items[inst.ptr.pos] = val; try self.push(&Value.Void); }, .assign_local => { const val = self.pop(); if (inst.ptr.pos >= self.locals.items.len) try self.locals.resize(inst.ptr.pos + 1); self.locals.items[inst.ptr.pos] = val; try self.push(&Value.Void); }, .load_module => { const string = self.pop().unwrap(.string) orelse return self.fail("Expected a string"); const mod = try Value.Module.create(self.gc, string.value); try self.push(mod); }, .make_iter => try self.makeIterable(inst), .iter_next => try self.execNextIter(), .make_range => try self.makeRange(), .match => try self.execSwitchProng(), .make_slice => try self.makeSlice(), } } // only allow them to query through global functions // functions are always loaded first as they are forward declared // therefore we can simply resize globals list try self.globals.resize(loaded_funcs); } /// Pushes a new `Value` on top of the `stack` and increases /// the stack pointer by 1. fn push(self: *Vm, value: *Value) Error!void { if (self.sp >= self.stack.len - 1) return self.fail("Stack overflow"); self.stack[self.sp] = value; self.sp += 1; } /// Returns the `Value` from the `stack` and decreases the stack /// pointer by 1. Asserts the stack is not empty. fn pop(self: *Vm) *Value { self.sp -= 1; return self.stack[self.sp]; } /// Returns the previously popped `Value` /// Note that this results in UB if the stack is empty. pub fn peek(self: *Vm) *Value { return self.stack[self.sp]; } /// Returns the current `Frame` of the call stack /// Asserts the call stack is not empty pub fn frame(self: *Vm) *Frame { return &self.call_stack.items[(self.call_stack.items.len - 1)]; } /// Analyzes and executes a binary operation. fn execBinOp(self: *Vm, op: byte_code.Opcode) Error!void { // right is on the top of left, therefore we pop it first const right = self.pop(); const left = self.pop(); const luf_type = try self.resolveType(&[_]*Value{ left, right }); return switch (luf_type) { .integer => self.execIntOp(op, left.toInteger().value, right.toInteger().value), .string => self.execStringOp(op, left.toString().value, right.toString().value), else => self.fail("Unexpected type, expected integer or string"), }; } /// Analyzes and executes a binary operation on an integer fn execIntOp(self: *Vm, op: byte_code.Opcode, left: i64, right: i64) Error!void { const result = switch (op) { .add => left + right, .sub => left - right, .mul => left * right, .mod => if (right > 0) @mod(left, right) else return self.fail("Rhs can not be a negative integer"), .div => blk: { if (right == 0) return self.fail("Cannot divide by zero"); break :blk @divTrunc(left, right); }, .bitwise_and => left & right, .bitwise_xor => left ^ right, .bitwise_or => left | right, .shift_left => blk: { if (right < 0) return self.fail("Bit shifting not allowed for negative integers"); break :blk if (right > std.math.maxInt(u6)) 0 else left << @intCast(u6, right); }, .shift_right => blk: { if (right < 0) return self.fail("Bit shifting not allowed for negative integers"); break :blk if (right > std.math.maxInt(u6)) 0 else left >> @intCast(u6, right); }, else => return self.fail("Unexpected operator"), }; const res = try Value.Integer.create(self.gc, result); return self.push(res); } /// Concats two strings together fn execStringOp(self: *Vm, op: byte_code.Opcode, left: []const u8, right: []const u8) Error!void { if (op != .add) return self.fail("Unexpected operator, expected '+'"); const concat = try std.mem.concat(self.allocator, u8, &[_][]const u8{ left, right }); // Creating a new String will allocate new memory for it, so free this string defer self.allocator.free(concat); const res = try Value.String.create(self.gc, concat); return self.push(res); } /// Analyzes the instruction, ensures the lhs is an identifier and the rhs is an integer or string. /// Strings are only valid for the `assign_add` bytecode instruction fn execAssignAndBinOp(self: *Vm, op: byte_code.Opcode) Error!void { const right = self.pop(); const left = self.pop(); if (left.ty != right.ty) return self.fail("Mismatching types"); if (left.isType(.integer)) { try self.execIntOp(switch (op) { .assign_add => .add, .assign_div => .div, .assign_mul => .mul, .assign_sub => .sub, else => return self.fail("Unexpected operator"), }, left.toInteger().value, right.toInteger().value); const val = self.pop(); left.toInteger().value = val.toInteger().value; return self.push(&Value.Void); } if (left.isType(.string)) { if (op != .assign_add) return self.fail("Unexpected operator on string, expected '+='"); try self.execStringOp(.add, left.toString().value, right.toString().value); const val = self.pop(); try left.toString().copyFrom(self.gc.gpa, val.toString()); return self.push(&Value.Void); } return self.fail("Unexpected type, expected integer or string"); } /// Analyzes a then executes a comparison and pushes the return value on the stack fn execCmp(self: *Vm, op: byte_code.Opcode) Error!void { // right is on the top of left, therefore we pop it first const right = self.pop(); const left = self.pop(); if (left.ty == right.ty and left.isType(.integer)) { return self.execIntCmp(op, left.toInteger().value, right.toInteger().value); } if (left.ty == right.ty and left.isType(.string)) { return self.execStringCmp(op, left.toString().value, right.toString().value); } const left_bool = left.unwrap(.boolean) orelse return self.fail("Expected boolean"); const right_bool = right.unwrap(.boolean) orelse return self.fail("Expected boolean"); const result = switch (op) { .equal => left_bool.value == right_bool.value, .not_equal => left_bool.value != right_bool.value, .@"and" => left_bool.value and right_bool.value, .@"or" => left_bool.value or right_bool.value, else => return self.fail("Unexpected operator on boolean"), }; return self.push(if (result) &Value.True.base else &Value.False.base); } /// Analyzes and compares 2 integers depending on the given operator fn execIntCmp(self: *Vm, op: byte_code.Opcode, left: i64, right: i64) Error!void { const boolean = switch (op) { .equal => left == right, .not_equal => left != right, .greater_than => left > right, .greater_than_equal => left >= right, .less_than => left < right, .less_than_equal => left <= right, else => return self.fail("Unexpected operator"), }; return self.push(if (boolean) &Value.True.base else &Value.False.base); } /// Analyzes and compares 2 strings fn execStringCmp(self: *Vm, op: byte_code.Opcode, left: []const u8, right: []const u8) Error!void { var eql = std.mem.eql(u8, left, right); switch (op) { .equal => {}, .not_equal => eql = !eql, else => return self.fail("Unexpected operator, expected '==' or '!='"), } return self.push(if (eql) &Value.True.base else &Value.False.base); } /// Analyzes and executes a negation fn execNegation(self: *Vm) Error!void { const right = self.pop(); const integer = right.unwrap(.integer) orelse return self.fail("Expected integer"); const ret = try Value.Integer.create(self.gc, -integer.value); return self.push(ret); } /// Analyzes and executes the '!' operator fn execNot(self: *Vm) Error!void { const right = self.pop(); const val = switch (right.ty) { .boolean => !right.toBool().value, .nil => true, else => false, }; return self.push(if (val) &Value.True.base else &Value.False.base); } /// Executes the ~ operator fn execBitwiseNot(self: *Vm) Error!void { const value = self.pop(); const integer = value.unwrap(.integer) orelse return self.fail("Expected integer"); const ret = try Value.Integer.create(self.gc, ~integer.value); return self.push(ret); } /// Analyzes the instruction and builds an array fn makeArray(self: *Vm, inst: byte_code.Instruction) Error!void { const len = inst.ptr.pos; const ret = try Value.List.create(self.gc, len); var list = ret.toList(); list.value.items.len = len; if (len == 0) { return self.push(ret); } var list_type: Type = undefined; var i: usize = 1; while (i <= len) : (i += 1) { const val = self.pop(); if (i == 1) list_type = val.ty else if (!val.isType(list_type)) return self.fail("Mismatching types"); list.value.items[len - i] = val; } return self.push(ret); } /// Analyzes and creates a new map fn makeMap(self: *Vm, inst: byte_code.Instruction) Error!void { const len = inst.ptr.pos; const ret = try Value.Map.create(self.gc, len); var map = ret.toMap(); if (len == 0) { return self.push(ret); } var key_type: Type = undefined; var value_type: Type = undefined; var i: usize = 0; while (i < len) : (i += 1) { const value = self.pop(); const key = self.pop(); if (i == 0) { key_type = key.ty; value_type = value.ty; } else { if (!key.isType(key_type)) return self.fail("Mismatching types"); if (!value.isType(value_type)) return self.fail("Mismatching types"); } map.value.putAssumeCapacity(key, value); } return self.push(ret); } /// Constructs a new enum `Value` fn makeEnum(self: *Vm, inst: byte_code.Instruction) Error!void { const len = inst.ptr.pos; var enums_values = std.ArrayList([]const u8).init(self.allocator); try enums_values.resize(len); defer enums_values.deinit(); var i: usize = len; while (i > 0) : (i -= 1) { const string = self.pop().unwrap(.string) orelse return self.fail("Enum contains invalid field"); enums_values.items[i - 1] = string.value; } const enm = try Value.Enum.create(self.gc, enums_values.toOwnedSlice()); return self.push(enm); } /// Creates a new iterable fn makeIterable(self: *Vm, inst: byte_code.Instruction) Error!void { const iterable = self.pop(); switch (iterable.ty) { .list, .range, .string => {}, else => return self.fail("Unsupported value for iterable"), } const value = try Value.Iterable.create( self.gc, inst.ptr.pos != 0, 0, iterable, ); return self.push(value); } /// Pops the iterator from the stack and retrieves the next value /// Pushes the iterator back, then the value and then the index if exposed /// Finally, a true or false is pushed to determine if we should end the for loop fn execNextIter(self: *Vm) Error!void { const value = self.pop(); // we mark the iterator here, because it's currently not being referenced by anything // until it is pushed back on the stack, this means it bould be sweeped when we call iterator.next() self.gc.mark(value); var iterator = value.toIterable(); if (try iterator.next(self.gc)) |next| { // push the iterator back on the stack try self.push(value); // push the capture on the stack try self.push(next); // push the index if it is exposed if (iterator.expose_index) try self.push( try Value.Integer.create(self.gc, @intCast(i64, iterator.index - 1)), ); // push true to continue return self.push(&Value.True.base); } else { return self.push(&Value.False.base); } } /// Creates a range from 2 values /// Returns an error if lhs or rhs is not an integer fn makeRange(self: *Vm) Error!void { const right = self.pop(); const left = self.pop(); const ret = try Value.Range.create( self.gc, left.toInteger().value, right.toInteger().value, ); return self.push(ret); } /// Analyzes an index/reference pushes the value on the stack fn getIndexValue(self: *Vm) Error!void { const index = self.pop(); const left = self.pop(); switch (left.ty) { .list => { var list = left.toList().value; switch (index.ty) { .integer => { const int = index.toInteger().value; if (int < 0 or int > list.items.len) return self.fail("Out of bounds"); return self.push(list.items[@intCast(u64, int)]); }, .string => { const name = index.toString().value; if (_builtin.builtins.get(name)) |val| { const builtin = val.toNative(); const args = try self.allocator.alloc(*Value, builtin.arg_len + 1); defer self.allocator.free(args); args[0] = left; var i: usize = 1; while (i <= builtin.arg_len) : (i += 1) args[i] = self.pop(); const res = builtin.func( self.gc, args, ) catch return self.fail("Could not execute builtin function"); return self.push(res); } }, else => return self.fail("Expected string or integer on rhs"), } }, .map => { if (left.toMap().value.get(index)) |val| { return self.push(val); } // We return null to the user so they have something to check against // to see if a key exists or not. return self.push(&Value.Nil); }, .string => { const string = left.toString().value; switch (index.ty) { .integer => { const int = index.toInteger().value; if (int < 0 or int > string.len) return self.fail("Out of bounds"); const val = try Value.String.create( self.gc, string[@intCast(usize, int)..@intCast(usize, int + 1)], ); return self.push(val); }, .string => { const name = index.toString().value; if (_builtin.builtins.get(name)) |val| { const builtin = val.toNative(); const res = builtin.func( self.gc, &[_]*Value{left}, ) catch return self.fail("Could not execute builtin function"); return self.push(res); } }, else => return self.fail("Expected string or integer on rhs"), } }, ._enum => { const enm = left.toEnum().value; const enum_value = index.unwrap(.string) orelse return self.fail("Expected string"); for (enm) |field, i| { if (std.mem.eql(u8, field, enum_value.value)) { const ret = try Value.Integer.create(self.gc, @intCast(i64, i)); return self.push(ret); } } return self.fail("Enum identifier does not exist"); }, .module => { const mod = left.toModule().value; const lib = self.libs.get(mod) orelse return self.fail("Library does not exist"); const value: *Value = if (!lib.isType(.map)) lib else lib.toMap().value.get(index) orelse return self.fail("Library x does not have member y"); return self.push(value); }, else => return self.fail("Unsupported type"), } } /// Sets the lhs by the value on top of the current stack /// This also does type checking to ensure the lhs and rhs are equal types fn setIndexValue(self: *Vm) Error!void { const value = self.pop(); const right = self.pop(); const left = self.pop(); if (left.isType(.list) and right.isType(.integer)) { const list = left.toList().value; const integer = right.toInteger().value; if (integer < 0 or integer > list.items.len) return self.fail("Out of bounds"); list.items[@intCast(usize, integer)] = value; return self.push(&Value.Void); } else if (left.isType(.map)) { var map = left.toMap(); if (map.value.get(right)) |*val| { try map.value.put(self.gc.gpa, right, value); return self.push(&Value.Void); } else { // replace with more descriptive Error return self.fail("Value not found"); } } // replace with more descriptive Error return self.fail("Unsupported type"); } /// Analyzes the current instruction to execture a function call /// Expects the current instruction pointer. /// This will also return the new instruction pointer /// /// `next` is required to detect if we can optimize tail recursion fn execFunctionCall(self: *Vm, inst: byte_code.Instruction, next: byte_code.Instruction) Error!void { const arg_len = inst.ptr.pos; const val = self.pop(); if (val.isType(.native) or val.isType(.module)) return self.execNativeFuncCall(val); if (val.ty != .function) return self.push(val); //put it back on stack if (arg_len != val.toFunction().arg_len) return self.fail("Mismatching argument length"); var cur_frame = self.frame(); if (cur_frame.fp == val and next.op == .return_value) { var i: usize = arg_len; while (i > 0) : (i -= 1) { if (i >= self.locals.items.len) try self.locals.resize(i); self.locals.items[i - 1] = self.stack[self.sp - i]; } cur_frame.ip = val.toFunction().entry; return; } try self.call_stack.append(.{ .fp = val, .ip = val.toFunction().entry, }); { var i: usize = arg_len; while (i > 0) : (i -= 1) { if (i >= self.locals.items.len) try self.locals.resize(i); self.locals.items[i - 1] = self.pop(); } } } /// Executes a native Zig function call fn execNativeFuncCall(self: *Vm, value: *Value) Error!void { const func = if (value.isType(.native)) value.toNative() else blk: { const mod = value.unwrap(.module) orelse return self.fail("Expected module"); const lib = self.libs.get(mod.value) orelse return self.fail("Library is not loaded"); break :blk lib.unwrap(.native) orelse return self.fail("Loaded library is not a function"); }; var args = try self.allocator.alloc(*Value, func.arg_len); defer self.allocator.free(args); for (args) |*arg| { arg.* = self.pop(); } const result = func.func(self.gc, args) catch return self.fail("Could not execute Zig function"); return self.push(result); } /// Compares switch' capture and the current prong. /// Unlike execCmp, this does not pop the lhs value from the stack, to maintain it's position /// as it's used for the other prongs. it will be popped at the end of the switch statement. fn execSwitchProng(self: *Vm) Error!void { const prong_value = self.pop(); const capture_value = self.stack[self.sp - 1]; switch (prong_value.ty) { .integer => { const capture = capture_value.unwrap(.integer) orelse return self.fail("Expected an integer"); return self.execIntCmp(.equal, capture.value, prong_value.toInteger().value); }, .string => { const capture = capture_value.unwrap(.string) orelse return self.fail("Expected a string"); return self.execStringCmp(.equal, capture.value, prong_value.toString().value); }, .range => { const capture = capture_value.unwrap(.integer) orelse return self.fail("Expected an integer"); const range = prong_value.toRange(); const result = capture.value >= range.start and capture.value <= range.end; return self.push(if (result) &Value.True.base else &Value.False.base); }, else => return self.fail("Unsupported type, switching are only allowed for integers, strings and ranges"), } } /// Creates a new list from a slice expression, and then pushes this value /// to the stack fn makeSlice(self: *Vm) Error!void { const end = self.pop(); const start = self.pop(); const list = self.pop(); if (!list.isType(.list)) return self.fail("Expected a list, but instead found a different type"); const start_num = @intCast(usize, start.toInteger().value); const end_num = if (end.unwrap(.integer)) |int| @intCast(usize, int.value) else list.toList().value.items.len; const len = end_num - start_num; // create our new list and fill it with values from the original list const ret = try Value.List.create(self.gc, len); const new_list = ret.toList(); new_list.value.items.len = len; var i: usize = start_num; while (i < end_num) : (i += 1) { new_list.value.items[i - start_num] = list.toList().value.items[i]; } return self.push(ret); } /// Appends an error message to `errors` and returns a `Vm.Error` fn fail(self: *Vm, comptime msg: []const u8) Error!void { //TODO implement a way to add location information try self.errors.add("Runtime error: " ++ msg, 0, .err, .{}); return Error.RuntimeError; } /// Checks each given type if they are equal or not fn resolveType(self: *Vm, values: []*const Value) Error!Type { std.debug.assert(values.len > 0); const cur_tag: Type = values[0].ty; if (values.len == 1) return cur_tag; for (values[1..]) |value| if (!value.isType(cur_tag)) try self.fail("Mismatching types"); return cur_tag; } }; /// Evalutes if the given `Value` is truthy. /// Only accepts booleans and 'Nil'. fn isTrue(value: *Value) bool { return switch (value.ty) { .nil => false, .boolean => value.toBool().value, else => true, }; } test "Integer arithmetic" { const test_cases = .{ .{ .input = "1", .expected = 1 }, .{ .input = "2", .expected = 2 }, .{ .input = "1 + 1", .expected = 2 }, .{ .input = "1 * 3", .expected = 3 }, .{ .input = "1 - 3", .expected = -2 }, .{ .input = "10 / 2", .expected = 5 }, .{ .input = "10 % 2", .expected = 0 }, .{ .input = "1 | 2", .expected = 3 }, .{ .input = "2 ^ 4", .expected = 6 }, .{ .input = "3 & 6", .expected = 2 }, .{ .input = "-2", .expected = -2 }, .{ .input = "1 << 2", .expected = 4 }, .{ .input = "4 >> 2", .expected = 1 }, .{ .input = "~1", .expected = -2 }, .{ .input = "(5 + 10 * 2 + 15 / 3) * 2 + -10", .expected = 50 }, .{ .input = "mut x = 0 x+= 1 x", .expected = 1 }, .{ .input = "mut x = 2 x*= 2 x", .expected = 4 }, .{ .input = "mut x = 10 x/= 2 x", .expected = 5 }, .{ .input = "mut x = 1 x-= 1 x", .expected = 0 }, }; inline for (test_cases) |case| { var vm = try Vm.init(testing.allocator); defer vm.deinit(); try vm.compileAndRun(case.input); try testing.expect(case.expected == vm.peek().toInteger().value); try testing.expectEqual(@as(usize, 0), vm.sp); } } test "Boolean" { const test_cases = .{ .{ .input = "true", .expected = true }, .{ .input = "false", .expected = false }, .{ .input = "1 < 2", .expected = true }, .{ .input = "1 > 2", .expected = false }, .{ .input = "1 == 1", .expected = true }, .{ .input = "1 != 1", .expected = false }, .{ .input = "true != true", .expected = false }, .{ .input = "!true", .expected = false }, .{ .input = "true and true", .expected = true }, .{ .input = "true and false", .expected = false }, .{ .input = "false and false", .expected = false }, .{ .input = "true or false", .expected = true }, .{ .input = "true or true", .expected = true }, .{ .input = "false or false", .expected = false }, }; inline for (test_cases) |case| { var vm = try Vm.init(testing.allocator); defer vm.deinit(); try vm.compileAndRun(case.input); try testing.expect(case.expected == vm.peek().toBool().value); try testing.expectEqual(@as(usize, 0), vm.sp); } } test "Conditional expression" { const test_cases = .{ .{ .input = "if true { 10 }", .expected = 10 }, .{ .input = "if true { 10 } else { 20 }", .expected = 10 }, .{ .input = "if false { 10 } else { 20 }", .expected = 20 }, .{ .input = "if 1 < 2 { 10 }", .expected = 10 }, .{ .input = "if 1 > 2 { 10 }", .expected = &Value.Void }, .{ .input = "if 1 > 2 { 10 } else if 2 > 3 { 20 } else { 5 }", .expected = 5 }, .{ .input = "if 1 > 2 { 10 } else if 2 < 3 { 20 } else { 5 }", .expected = 20 }, .{ .input = "mut x = 5 if x < 10 { x = 2 } else if x < 3 { x = 1 } else { x = 0 } x", .expected = 2 }, }; inline for (test_cases) |case| { var vm = try Vm.init(testing.allocator); defer vm.deinit(); try vm.compileAndRun(case.input); if (@TypeOf(case.expected) == comptime_int) { try testing.expectEqual(@as(i64, case.expected), vm.peek().toInteger().value); } else { try testing.expectEqual(case.expected, vm.peek()); } try testing.expectEqual(@as(usize, 0), vm.sp); } } test "Declaration" { const test_cases = .{ .{ .input = "const x = 1 x", .expected = 1 }, .{ .input = "const x = 1 const y = 1 x + y", .expected = 2 }, .{ .input = "mut x = 1 const y = x + x x + y", .expected = 3 }, }; inline for (test_cases) |case| { var vm = try Vm.init(testing.allocator); defer vm.deinit(); try vm.compileAndRun(case.input); try testing.expectEqual(@as(i64, case.expected), vm.peek().toInteger().value); try testing.expectEqual(@as(usize, 0), vm.sp); } } test "Strings" { const test_cases = .{ .{ .input = "\"foo\"", .expected = "foo" }, .{ .input = "\"foo\" + \"bar\"", .expected = "foobar" }, .{ .input = "const x = \"foo\" x+=\"bar\" x", .expected = "foobar" }, }; inline for (test_cases) |case| { var vm = try Vm.init(testing.allocator); defer vm.deinit(); try vm.compileAndRun(case.input); try testing.expectEqualStrings(case.expected, vm.peek().toString().value); try testing.expectEqual(@as(usize, 0), vm.sp); } } test "Arrays" { const test_cases = .{ .{ .input = "[]int{1, 2, 3}", .expected = &[_]i64{ 1, 2, 3 } }, .{ .input = "[]int{}", .expected = &[_]i64{} }, .{ .input = "[]int{1 + 1, 2 * 2, 6}", .expected = &[_]i64{ 2, 4, 6 } }, }; inline for (test_cases) |case| { var vm = try Vm.init(testing.allocator); defer vm.deinit(); try vm.compileAndRun(case.input); const list = vm.peek().toList(); try testing.expectEqual(case.expected.len, list.value.items.len); inline for (case.expected) |int, i| { const items = list.value.items; try testing.expectEqual(int, items[i].toInteger().value); } try testing.expectEqual(@as(usize, 0), vm.sp); } } test "Maps" { const test_cases = .{ .{ .input = "[]int:int{1:2, 2:1, 5:6}", .expected = &[_]i64{ 6, 1, 2 }, .keys = &[_]i64{ 5, 2, 1 } }, .{ .input = "[]int:int{}", .expected = &[_]i64{}, .keys = &[_]i64{} }, .{ .input = "[]string:int{\"foo\":1}", .expected = &[_]i64{1}, .keys = &[_][]const u8{"foo"} }, }; inline for (test_cases) |case| { var vm = try Vm.init(testing.allocator); defer vm.deinit(); try vm.compileAndRun(case.input); const map = vm.peek().toMap().value; try testing.expect(map.items().len == case.expected.len); inline for (case.expected) |int, i| { const items = map.items(); try testing.expectEqual(int, items[i].value.toInteger().value); } inline for (case.keys) |key, i| { const item = map.items()[i]; if (@TypeOf(key) == i64) { try testing.expectEqual(key, item.key.toInteger().value); } else { try testing.expectEqualStrings(key, item.key.toString().value); } } try testing.expectEqual(@as(usize, 0), vm.sp); } } test "Index" { const test_cases = .{ .{ .input = "[]int{1, 2, 3}[1]", .expected = 2 }, .{ .input = "const list = []int{1, 2, 3} list[1] = 10 list[1]", .expected = 10 }, .{ .input = "[]int:int{1: 5}[1]", .expected = 5 }, .{ .input = "[]int:int{2: 5}[0]", .expected = &Value.Nil }, .{ .input = "[]int:int{2: 5}[2] = 1", .expected = &Value.Void }, .{ .input = "const map = []int:int{2: 5} map[2] = 1 map[2]", .expected = 1 }, .{ .input = "[]string:int{\"foo\": 15}[\"foo\"]", .expected = 15 }, .{ .input = "\"hello\"[1]", .expected = "e" }, }; inline for (test_cases) |case| { var vm = try Vm.init(testing.allocator); defer vm.deinit(); try vm.compileAndRun(case.input); if (@TypeOf(case.expected) == comptime_int) try testing.expectEqual(@as(i64, case.expected), vm.peek().toInteger().value) else if (@TypeOf(case.expected) == *const [1:0]u8) try testing.expectEqualStrings(case.expected, vm.peek().toString().value) else { try testing.expectEqual(case.expected, vm.peek()); } try testing.expectEqual(@as(usize, 0), vm.sp); } } test "Basic function calls with no arguments" { const test_cases = .{ .{ .input = "const x = fn() int { return 1 + 2 } x()", .expected = 3 }, .{ .input = "const x = fn() int { return 1 } const y = fn() int { return 5 } x() + y()", .expected = 6 }, .{ .input = "const x = fn() int { return 5 10 } x()", .expected = 5 }, .{ .input = "const x = fn() void { } x()", .expected = &Value.Void }, }; inline for (test_cases) |case| { var vm = try Vm.init(testing.allocator); defer vm.deinit(); try vm.compileAndRun(case.input); if (@TypeOf(case.expected) == comptime_int) try testing.expectEqual(@as(i64, case.expected), vm.peek().toInteger().value) else { try testing.expectEqual(case.expected, vm.peek()); } try testing.expectEqual(@as(usize, 0), vm.sp); } } test "Globals vs Locals" { const test_cases = .{ .{ .input = "const x = fn() int { const x = 5 return x } x()", .expected = 5 }, .{ .input = "const x = fn() int { const y = 1 const z = 2 return y + z } x()", .expected = 3 }, }; inline for (test_cases) |case, i| { var vm = try Vm.init(testing.allocator); defer vm.deinit(); if (i == 0) { try testing.expectError(compiler.Compiler.Error.CompilerError, vm.compileAndRun(case.input)); continue; } else try vm.compileAndRun(case.input); if (@TypeOf(case.expected) == comptime_int) try testing.expectEqual(@as(i64, case.expected), vm.peek().toInteger().value) else try testing.expectEqual(case.expected, vm.peek()); try testing.expectEqual(@as(usize, 0), vm.sp); } } test "Functions with arguments" { const test_cases = .{ .{ .input = "const x = fn(x: int) int { return x } x(3)", .expected = 3 }, .{ .input = "const x = fn(a: int, b: int) int { return a + b } x(3,5)", .expected = 8 }, .{ .input = "const x = fn(a: int, b: int) int { const z = a + b return z } x(3,5)", .expected = 8 }, }; inline for (test_cases) |case| { var vm = try Vm.init(testing.allocator); defer vm.deinit(); try vm.compileAndRun(case.input); if (@TypeOf(case.expected) == comptime_int) try testing.expectEqual(@as(i64, case.expected), vm.peek().toInteger().value) else try testing.expectEqual(case.expected, vm.peek()); try testing.expectEqual(@as(usize, 0), vm.sp); } } test "Builtins" { const test_cases = .{ .{ .input = "\"Hello world\".len", .expected = 11 }, .{ .input = "[]int{1,5,2}.len", .expected = 3 }, .{ .input = "const x = []int{1} x.add(2) x.len", .expected = 2 }, .{ .input = "const x = []int{1, 2} x.pop() x.len", .expected = 1 }, }; inline for (test_cases) |case| { var vm = try Vm.init(testing.allocator); defer vm.deinit(); try vm.compileAndRun(case.input); try testing.expectEqual(@as(i64, case.expected), vm.peek().toInteger().value); try testing.expectEqual(@as(usize, 0), vm.sp); } } test "While loop" { const test_cases = .{ .{ .input = "mut i = 0 while i > 10 {i = 10} i", .expected = 0 }, .{ .input = "mut i = 0 while i < 10 {i = 10} i", .expected = 10 }, .{ .input = "mut i = 0 while i < 10 { if i == 5 { break } i = 5} i", .expected = 5 }, }; inline for (test_cases) |case| { var vm = try Vm.init(testing.allocator); defer vm.deinit(); try vm.compileAndRun(case.input); try testing.expectEqual(@as(i64, case.expected), vm.peek().toInteger().value); try testing.expectEqual(@as(usize, 0), vm.sp); } } test "Tail recursion" { const input = \\const func = fn(a: int) int { \\ if (a == 10) { \\ return a \\ } \\ return func(a + 1) \\} \\const f: int = func(2) ; var vm = try Vm.init(testing.allocator); defer vm.deinit(); try vm.compileAndRun(input); try testing.expectEqual(@as(i64, 10), vm.peek().toInteger().value); try testing.expectEqual(@as(usize, 0), vm.sp); } test "Basic For loop" { const input = \\mut sum = 0 \\for item: []int{1, 3, 5, 7, 9} { \\ sum += item \\} \\sum ; var vm = try Vm.init(testing.allocator); defer vm.deinit(); try vm.compileAndRun(input); try testing.expectEqual(@as(i64, 25), vm.peek().toInteger().value); try testing.expectEqual(@as(usize, 0), vm.sp); } test "For loop continue + break" { const input = \\mut sum = 0 \\for item, i: []int{1, 3, 5, 7, 9} { \\ if (item == 3) { \\ continue \\ } \\ if (item == 7) { \\ break \\ } \\ sum += item + i \\} \\sum ; var vm = try Vm.init(testing.allocator); defer vm.deinit(); try vm.compileAndRun(input); try testing.expectEqual(@as(i64, 8), vm.peek().toInteger().value); try testing.expectEqual(@as(usize, 0), vm.sp); } test "Range" { const input = \\mut sum = 0 \\for e, i: 1..100 { \\ if (e % 2 == 0) { \\ continue \\ } \\ sum += e + i \\} \\sum ; var vm = try Vm.init(testing.allocator); defer vm.deinit(); try vm.compileAndRun(input); try testing.expectEqual(@as(i64, 4950), vm.peek().toInteger().value); try testing.expectEqual(@as(usize, 0), vm.sp); } test "For loop - String" { const input = "mut result = \"hello\" const w = \"world\" for c, i: w {result+=c}result"; var vm = try Vm.init(testing.allocator); defer vm.deinit(); try vm.compileAndRun(input); try testing.expectEqualStrings("helloworld", vm.peek().toString().value); try testing.expectEqual(@as(usize, 0), vm.sp); } test "Enum expression and comparison" { const input = \\const x = enum{value, another_value} \\const enum_value = x.another_value \\if (enum_value == x.another_value) { \\ 5 \\} \\enum_value ; var vm = try Vm.init(testing.allocator); defer vm.deinit(); try vm.compileAndRun(input); try testing.expectEqual(@as(i64, 1), vm.peek().toInteger().value); try testing.expectEqual(@as(usize, 0), vm.sp); } test "Switch case" { const input = \\const range = 0..9 \\mut x = 0 \\switch(5) { \\ 4: x += 10, \\ range: x += 30, \\ 5: x += 20 \\} \\x ; var vm = try Vm.init(testing.allocator); defer vm.deinit(); try vm.compileAndRun(input); try testing.expectEqual(@as(i64, 50), vm.peek().toInteger().value); try testing.expectEqual(@as(usize, 0), vm.sp); } test "Forward declared" { const input = \\ const x = add(2, 5) \\ const add = fn(a: int, b: int) int { \\ return sum(a + b) \\ } \\ const sum = fn(a: int) int { \\ return a + 1 \\ } ; var vm = try Vm.init(testing.allocator); defer vm.deinit(); try vm.compileAndRun(input); try testing.expectEqual(@as(i64, 8), vm.peek().toInteger().value); try testing.expectEqual(@as(usize, 0), vm.sp); } test "Import module" { const input = \\const imp = import("examples/to_import.luf") \\const x = imp.add(10) ; var vm = try Vm.init(testing.allocator); defer vm.deinit(); try vm.compileAndRun(input); try testing.expectEqual(@as(i64, 30), vm.peek().toInteger().value); try testing.expectEqual(@as(usize, 0), vm.sp); } test "Luf function from Zig" { const input = \\const add = fn(a: int, b: int) int { \\ return a + b \\} \\const concat = fn(a: string) string { \\ return a + " world" \\} ; var vm = try Vm.init(testing.allocator); defer vm.deinit(); var cu = try compiler.compile(testing.allocator, input, &vm.errors); defer cu.deinit(); var code = try byte_code.Instructions.fromCu(testing.allocator, cu); defer code.deinit(); vm.loadCode(&code); try vm.run(); const val = try vm.callFunc("add", .{ 2, 5 }); const val2 = try vm.callFunc("concat", .{"hello"}); try testing.expectEqual(@as(i64, 7), val.toInteger().value); try testing.expectEqualStrings("hello world", val2.toString().value); try testing.expectEqual(@as(usize, 0), vm.sp); } test "Inner functions" { const input = \\const add = fn(a: int, b: int) int { \\ const plusTen = fn(a: int) int { \\ return a + 10 \\ } \\ \\ return plusTen(a + b) \\} \\const x = add(20, 30) ; var vm = try Vm.init(testing.allocator); defer vm.deinit(); try vm.compileAndRun(input); try testing.expectEqual(@as(i64, 60), vm.peek().toInteger().value); try testing.expectEqual(@as(usize, 0), vm.sp); } fn testZigFromLuf(a: u32, b: u32) u32 { return a + b; } test "Zig from Luf" { const input = \\const sum = import("zig") \\const result = sum(2, 5) \\result ; var vm = try Vm.init(testing.allocator); try vm.loadLib("zig", testZigFromLuf); defer vm.deinit(); try vm.compileAndRun(input); try testing.expectEqual(@as(i64, 7), vm.peek().toInteger().value); try testing.expectEqual(@as(usize, 0), vm.sp); } test "Luf std" { const input = \\const std = import("std") \\std.math.log(10, 2) ; var vm = try Vm.init(testing.allocator); defer vm.deinit(); try vm.compileAndRun(input); try testing.expectEqual(@as(i64, 3), vm.peek().toInteger().value); try testing.expectEqual(@as(usize, 0), vm.sp); } test "Optionals" { const input = \\ mut x: ?int = nil \\ x = 5 \\ x = nil \\ x ; var vm = try Vm.init(testing.allocator); defer vm.deinit(); try vm.compileAndRun(input); try testing.expectEqual(&Value.Nil, vm.peek()); try testing.expectEqual(@as(usize, 0), vm.sp); } test "Slices" { const cases = .{ .{ .input = "const list = []int{2, 4, 6} const slice = list[1:3]", .expected = .{ 4, 6 } }, .{ .input = "const list = []int{2, 4, 6} const slice = list[:2]", .expected = .{ 2, 4 } }, .{ .input = "const list = []int{2, 4, 6} const slice = list[1:]", .expected = .{ 4, 6 } }, }; inline for (cases) |case| { var vm = try Vm.init(testing.allocator); defer vm.deinit(); try vm.compileAndRun(case.input); const list = vm.peek().toList().value; try testing.expectEqual(@as(usize, 2), list.items.len); try testing.expectEqual(@as(i64, case.expected[0]), list.items[0].toInteger().value); try testing.expectEqual(@as(i64, case.expected[1]), list.items[1].toInteger().value); } }
src/vm.zig
/// * in the register loading instructions "LD r,(IX/IY+d)"" and /// "LD (IX/IY+d),r" the source and target registers H and L are never replaced /// with IXH/IYH and IYH/IYL /// * in the "EX DE,HL" and "EXX" instructions, HL is never replaced with IX /// or IY (however there *are* prefixed versions of "EX (SP),HL" which /// replace HL with IX or IY /// * all ED prefixed instructions disable any active HL <=> IX/IY mapping /// /// This behaviour of the DD and FD prefixes is why the CPU will happily execute /// sequences of DD and FD prefix bytes, with the only side effect that no /// interrupt requests are processed during the sequence. /// const CPU = @This(); pins: u64 = 0, ticks: u64 = 0, regs: Regs = [_]u8{0xFF} ** NumRegs8, IX: u16 = 0xFFFF, IY: u16 = 0xFFFF, WZ: u16 = 0xFFFF, SP: u16 = 0xFFFF, PC: u16 = 0x0000, I: u8 = 0x00, R: u8 = 0x00, IM: u2 = 0x00, ex: [NumRegs16]u16 = [_]u16{0xFFFF} ** NumRegs16, // shadow registers ixiy: u2 = 0, // UseIX or UseIY if indexed prefix 0xDD or 0xFD active iff1: bool = false, iff2: bool = false, ei: bool = false, // address bus pins pub const A0: u64 = 1<<0; pub const A1: u64 = 1<<1; pub const A2: u64 = 1<<2; pub const A3: u64 = 1<<3; pub const A4: u64 = 1<<4; pub const A5: u64 = 1<<5; pub const A6: u64 = 1<<6; pub const A7: u64 = 1<<7; pub const A8: u64 = 1<<8; pub const A9: u64 = 1<<9; pub const A10: u64 = 1<<10; pub const A11: u64 = 1<<11; pub const A12: u64 = 1<<12; pub const A13: u64 = 1<<13; pub const A14: u64 = 1<<14; pub const A15: u64 = 1<<15; pub const AddrPinMask: u64 = 0xFFFF; // data bus pins pub const D0: u64 = 1<<16; pub const D1: u64 = 1<<17; pub const D2: u64 = 1<<18; pub const D3: u64 = 1<<19; pub const D4: u64 = 1<<20; pub const D5: u64 = 1<<21; pub const D6: u64 = 1<<22; pub const D7: u64 = 1<<23; pub const DataPinShift = 16; pub const DataPinMask: u64 = 0xFF0000; // system control pins pub const M1: u64 = 1<<24; // machine cycle 1 pub const MREQ: u64 = 1<<25; // memory request pub const IORQ: u64 = 1<<26; // IO request pub const RD: u64 = 1<<27; // read request pub const WR: u64 = 1<<28; // write requst pub const RFSH: u64 = 1<<29; // memory refresh (not implemented) pub const CtrlPinMask = M1|MREQ|IORQ|RD|WR|RFSH; // CPU control pins pub const HALT: u64 = 1<<30; // halt and catch fire pub const INT: u64 = 1<<31; // maskable interrupt requested pub const NMI: u64 = 1<<32; // non-maskable interrupt requested // virtual pins pub const WAIT0: u64 = 1<<34; // 3 virtual pins to inject up to 8 wait cycles pub const WAIT1: u64 = 1<<35; pub const WAIT2: u64 = 1<<36; pub const IEIO: u64 = 1<<37; // interrupt daisy chain: interrupt-enable-I/O pub const RETI: u64 = 1<<38; // interrupt daisy chain: RETI decoded pub const WaitPinShift = 34; pub const WaitPinMask = WAIT0|WAIT1|WAIT2; // all pins mask pub const PinMask: u64 = (1<<40)-1; // status flag bits pub const CF: u8 = (1<<0); pub const NF: u8 = (1<<1); pub const VF: u8 = (1<<2); pub const PF: u8 = VF; pub const XF: u8 = (1<<3); pub const HF: u8 = (1<<4); pub const YF: u8 = (1<<5); pub const ZF: u8 = (1<<6); pub const SF: u8 = (1<<7); // system tick callback with associated userdata pub const TickFunc = struct { func: fn(num_ticks: u64, pins: u64, userdata: usize) u64, userdata: usize = 0, }; /// run the emulator for at least 'num_ticks', return number of executed ticks pub fn exec(self: *CPU, num_ticks: u64, tick_func: TickFunc) u64 { self.ticks = 0; var running = true; while (running): (running = self.ticks < num_ticks) { // store current pin state for edge-triggered NMI detection const pre_pins = self.pins; // fetch next opcode byte const op = self.fetch(tick_func); // decode opcode (see http://www.z80.info/decoding.htm) // |xx|yyy|zzz| const x = @truncate(u2, op >> 6); const y = @truncate(u3, op >> 3); const z = @truncate(u3, op & 7); const p = @truncate(u2, y >> 1); const q = @truncate(u1, y); switch (x) { 0 => switch (z) { 0 => switch (y) { 0 => { }, // NOP 1 => self.opEX_AF_AF(), 2 => self.opDJNZ_d(tick_func), 3 => self.opJR_d(tick_func), 4...7 => self.opJR_cc_d(y, tick_func), }, 1 => switch (q) { 0 => self.opLD_rp_nn(p, tick_func), 1 => self.opADD_HL_rp(p, tick_func), }, 2 => switch (y) { 0 => self.opLD_iBCDE_A(BC, tick_func), 1 => self.opLD_A_iBCDE(BC, tick_func), 2 => self.opLD_iBCDE_A(DE, tick_func), 3 => self.opLD_A_iBCDE(DE, tick_func), 4 => self.opLD_inn_HL(tick_func), 5 => self.opLD_HL_inn(tick_func), 6 => self.opLD_inn_A(tick_func), 7 => self.opLD_A_inn(tick_func) }, 3 => switch (q) { 0 => self.opINC_rp(p, tick_func), 1 => self.opDEC_rp(p, tick_func), }, 4 => self.opINC_r(y, tick_func), 5 => self.opDEC_r(y, tick_func), 6 => self.opLD_r_n(y, tick_func), 7 => switch (y) { 0 => self.opRLCA(), 1 => self.opRRCA(), 2 => self.opRLA(), 3 => self.opRRA(), 4 => self.opDAA(), 5 => self.opCPL(), 6 => self.opSCF(), 7 => self.opCCF(), } }, 1 => { if (y == 6 and z == 6) { self.opHALT(); } else { self.opLD_r_r(y, z, tick_func); } }, 2 => self.opALU_r(y, z, tick_func), 3 => switch (z) { 0 => self.opRET_cc(y, tick_func), 1 => switch (q) { 0 => self.opPOP_rp2(p, tick_func), 1 => switch (p) { 0 => self.opRET(tick_func), 1 => self.opEXX(), 2 => self.opJP_HL(), 3 => self.opLD_SP_HL(tick_func), } }, 2 => self.opJP_cc_nn(y, tick_func), 3 => switch (y) { 0 => self.opJP_nn(tick_func), 1 => self.opCB_prefix(tick_func), 2 => self.opOUT_in_A(tick_func), 3 => self.opIN_A_in(tick_func), 4 => self.opEX_iSP_HL(tick_func), 5 => self.opEX_DE_HL(), 6 => self.opDI(), 7 => self.opEI(), }, 4 => self.opCALL_cc_nn(y, tick_func), 5 => switch (q) { 0 => self.opPUSH_rp2(p, tick_func), 1 => switch (p) { 0 => self.opCALL_nn(tick_func), 1 => { self.ixiy = UseIX; continue; }, // no interrupt handling after DD prefix 2 => self.opED_prefix(tick_func), 3 => { self.ixiy = UseIY; continue; }, // no interrupt handling after FD prefix } }, 6 => self.opALU_n(y, tick_func), 7 => self.opRSTy(y, tick_func), } } // handle IRQ (level-triggered) and NMI (edge-triggered) const nmi: bool = 0 != ((self.pins & (self.pins ^ pre_pins)) & NMI); const int: bool = self.iff1 and (0 != (self.pins & INT)); if (nmi or int) { self.handleInterrupt(nmi, int, tick_func); } // clear IX/IY prefix flag and update enable-interrupt flags if last op was EI self.ixiy = 0; if (self.ei) { self.ei = false; self.iff1 = true; self.iff2 = true; } self.pins &= ~INT; } return self.ticks; } // return true if not in the middle of an indexed op (DD / FD) pub fn opdone(self: *CPU) bool { return 0 == self.ixiy; } // set/get 8-bit register value pub const B = 0; pub const C = 1; pub const D = 2; pub const E = 3; pub const H = 4; pub const L = 5; pub const F = 6; pub const A = 7; pub const NumRegs8 = 8; pub fn setR8(self: *CPU, reg: u3, val: u8) void { self.regs[reg] = val; } pub fn r8(self: *CPU, reg: u3) u8 { return self.regs[reg]; } // set/get 16-bit register value (BC, DE, HL, FA) pub const BC = 0; pub const DE = 1; pub const HL = 2; pub const FA = 3; pub const NumRegs16 = 4; pub fn setR16(self: *CPU, reg: u2, val: u16) void { self.regs[@as(u3,reg)*2 + 0] = @truncate(u8, val >> 8); self.regs[@as(u3,reg)*2 + 1] = @truncate(u8, val); } pub fn r16(self: *CPU, reg: u2) u16 { const h = self.regs[@as(u3,reg)*2 + 0]; const l = self.regs[@as(u3,reg)*2 + 1]; return @as(u16,h)<<8 | l; } // set/get wait ticks on pin mask pub fn setWait(pins: u64, wait_ticks: u3) u64 { return (pins & ~WaitPinMask) | @as(u64, wait_ticks) << WaitPinShift; } pub fn getWait(pins: u64) u3 { return @truncate(u3, pins >> WaitPinShift); } // set/get address pins in pin mask pub fn setAddr(pins: u64, a: u16) u64 { return (pins & ~AddrPinMask) | a; } pub fn getAddr(pins: u64) u16 { return @truncate(u16, pins); } // set/get data pins in pin mask pub fn setData(pins: u64, data: u8) u64 { return (pins & ~DataPinMask) | (@as(u64, data) << DataPinShift); } pub fn getData(pins: u64) u8 { return @truncate(u8, pins >> DataPinShift); } // set address and data pins in pin mask pub fn setAddrData(pins: u64, a: u16, d: u8) u64 { return (pins & ~(DataPinMask|AddrPinMask)) | (@as(u64, d) << DataPinShift) | a; } const Regs = [NumRegs8]u8; const UseIX = (1<<0); const UseIY = (1<<1); // handle maskable and non-maskable interrupt requests fn handleInterrupt(self: *CPU, nmi: bool, int: bool, tick_func: TickFunc) void { // clear IFF flags (disables interrupt) self.iff1 = false; if (int) { self.iff2 = false; } // interrupts deactivate HALT state if (0 != (self.pins & HALT)) { self.pins &= ~HALT; self.PC +%= 1; } // put PC on address bus self.pins = setAddr(self.pins, self.PC); if (nmi) { // non-maskable interrupt // perform a dummy 5-tick (not 4!) opcode fetch, don't bump PC self.tickWait(5, M1|MREQ|RD, tick_func); self.bumpR(); // put PC on stack self.push16(self.PC, tick_func); // jump to address 0x66 self.PC = 0x0066; self.WZ = self.PC; } else { // maskable interrupt // interrupt acknowledge machine cycle, interrupt // controller is expected to put interrupt vector low byte // on address bus self.tickWait(4, M1|IORQ, tick_func); const int_vec = getData(self.pins); self.bumpR(); self.tick(2, 0, tick_func); // 2 filler ticks switch (self.IM) { 0 => { // interrupt mode 0 not implemented }, 1 => { // interrupt mode 1: // - put PC on stack // - load address 0x0038 into PC self.push16(self.PC, tick_func); self.PC = 0x0038; self.WZ = self.PC; }, 2 => { // interrupt mode 2: // - put PC on stack // - build interrupt vector address // - load interrupt service routine from interrupt vector into PC self.push16(self.PC, tick_func); var addr = (@as(u16, self.I)<<8) | (int_vec & 0xFE); const z: u16 = self.memRead(addr, tick_func); addr +%= 1; const w: u16 = self.memRead(addr, tick_func); self.PC = (w << 8) | z; self.WZ = self.PC; }, else => unreachable, } } } // ED-prefix decoding fn opED_prefix(self: *CPU, tick_func: TickFunc) void { // ED prefix cancels the IX/IY prefix self.ixiy = 0; const op = self.fetch(tick_func); const x = @truncate(u2, op >> 6); const y = @truncate(u3, op >> 3); const z = @truncate(u3, op & 7); const p = @truncate(u2, y >> 1); const q = @truncate(u1, y); switch (x) { 1 => switch (z) { 0 => self.opIN_ry_iC(y, tick_func), 1 => self.opOUT_iC_ry(y, tick_func), 2 => switch (q) { 0 => self.opSBC_HL_rp(p, tick_func), 1 => self.opADC_HL_rp(p, tick_func), }, 3 => switch (q) { 0 => self.opLD_inn_rp(p, tick_func), 1 => self.opLD_rp_inn(p, tick_func), }, 4 => self.opNEG(), 5 => self.opRETNI(tick_func), 6 => self.opIM(y), 7 => switch(y) { 0 => self.opLD_I_A(tick_func), 1 => self.opLD_R_A(tick_func), 2 => self.opLD_A_I(tick_func), 3 => self.opLD_A_R(tick_func), 4 => self.opRRD(tick_func), 5 => self.opRLD(tick_func), 6, 7 => { }, // NONI + NOP } }, 2 => switch (z) { 0 => switch (y) { 4...7 => self.opLDI_LDD_LDIR_LDDR(y, tick_func), else => { } // NONI + NOP }, 1 => switch (y) { 4...7 => self.opCPI_CPD_CPIR_CPDR(y, tick_func), else => { } // NONI + NOP }, 2 => switch (y) { 4...7 => self.opINI_IND_INIR_INDR(y, tick_func), else => { }, // NONI + NOP }, 3 => switch (y) { 4...7 => self.opOUTI_OUTD_OTIR_OTDR(y, tick_func), else => { }, // NONI + NOP }, else => { }, // NONI + NOP }, else => { }, // 0, 3 -> NONI + NOP } } // return flags for left/right-shift/rotate operations fn lsrFlags(d8: u8, r: u8) u8 { return szpFlags(r) | ((d8 >> 7) & CF); } fn rsrFlags(d8: u8, r: u8) u8 { return szpFlags(r) | (d8 & CF); } // CB-prefix decoding (very, very special case) fn opCB_prefix(self: *CPU, tick_func: TickFunc) void { // special handling for undocumented DD/FD+CB double prefix instructions, // these always load the value from memory (IX+d), // and write the value back, even for normal // "register" instructions // see: http://www.baltazarstudios.com/files/ddcb.html const d: u16 = if (self.ixiy != 0) self.dimm8(tick_func) else 0; // special opcode fetch without memory refresh and bumpR() const op = self.fetchCB(tick_func); const x = @truncate(u2, op >> 6); const y = @truncate(u3, op >> 3); const z = @truncate(u3, op & 7); // load operand (for indexed ops always from memory) const d8: u8 = if ((z == 6) or (self.ixiy != 0)) blk: { self.tick(1, 0, tick_func); // filler tick self.WZ = self.loadHLIXIY(); if (self.ixiy != 0) { self.tick(1, 0, tick_func); // filler tick self.WZ +%= d; } break: blk self.memRead(self.WZ, tick_func); } else self.load8(z, tick_func); var f: u8 = self.regs[F]; var r: u8 = undefined; switch (x) { 0 => switch (y) { // rot/shift 0 => { r = d8<<1 | d8>>7; f = lsrFlags(d8, r); }, // RLC 1 => { r = d8>>1 | d8<<7; f = rsrFlags(d8, r); }, // RRC 2 => { r = d8<<1 | (f&CF); f = lsrFlags(d8, r); }, // RL 3 => { r = d8>>1 | ((f&CF)<<7); f = rsrFlags(d8, r); }, // RR 4 => { r = d8<<1; f = lsrFlags(d8, r); }, // SLA 5 => { r = d8>>1 | (d8&0x80); f = rsrFlags(d8, r); }, // SRA 6 => { r = d8<<1 | 1; f = lsrFlags(d8, r); }, // SLL 7 => { r = d8>>1; f = rsrFlags(d8, r); }, // SRL }, 1 => { // BIT (bit test) r = d8 & (@as(u8,1) << y); f = (f & CF) | HF | if (r==0) ZF|PF else r&SF; if ((z == 6) or (self.ixiy != 0)) { f |= @truncate(u8, self.WZ >> 8) & (YF|XF); } else { f |= d8 & (YF|XF); } }, 2 => { // RES (bit clear) r = d8 & ~(@as(u8,1) << y); }, 3 => { // SET (bit set) r = d8 | (@as(u8,1) << y); } } if (x != 1) { // write result back if ((z == 6) or (self.ixiy != 0)) { // (HL), (IX+d), (IY+d): write back to memory, for extended op, // even when the op is actually a register op self.memWrite(self.WZ, r, tick_func); } if (z != 6) { // write result back to register, never write back to overriden IXH/IYH/IXL/IYL self.store8HL(z, r, tick_func); } } self.regs[F] = f; } // helper function to increment R register fn bumpR(self: *CPU) void { self.R = (self.R & 0x80) | ((self.R +% 1) & 0x7F); } // invoke tick callback with control pins set fn tick(self: *CPU, num_ticks: u64, pin_mask: u64, tick_func: TickFunc) void { self.pins = tick_func.func(num_ticks, (self.pins & ~CtrlPinMask) | pin_mask, tick_func.userdata); self.ticks += num_ticks; } // invoke tick callback with pin mask and wait state detection fn tickWait(self: *CPU, num_ticks: u64, pin_mask: u64, tick_func: TickFunc) void { self.pins = tick_func.func(num_ticks, (self.pins & ~(CtrlPinMask|WaitPinMask) | pin_mask), tick_func.userdata); self.ticks += num_ticks + getWait(self.pins); } // perform a memory-read machine cycle (3 clock cycles) fn memRead(self: *CPU, addr: u16, tick_func: TickFunc) u8 { self.pins = setAddr(self.pins, addr); self.tickWait(3, MREQ|RD, tick_func); return getData(self.pins); } // perform a memory-write machine cycle (3 clock cycles) fn memWrite(self: *CPU, addr: u16, data: u8, tick_func: TickFunc) void { self.pins = setAddrData(self.pins, addr, data); self.tickWait(3, MREQ|WR, tick_func); } // perform an IO input machine cycle (4 clock cycles) fn ioRead(self: *CPU, addr: u16, tick_func: TickFunc) u8 { self.pins = setAddr(self.pins, addr); self.tickWait(4, IORQ|RD, tick_func); return getData(self.pins); } // perform a IO output machine cycle (4 clock cycles) fn ioWrite(self: *CPU, addr: u16, data: u8, tick_func: TickFunc) void { self.pins = setAddrData(self.pins, addr, data); self.tickWait(4, IORQ|WR, tick_func); } // read unsigned 8-bit immediate fn imm8(self: *CPU, tick_func: TickFunc) u8 { const val = self.memRead(self.PC, tick_func); self.PC +%= 1; return val; } // read the signed 8-bit address offset for IX/IX+d ops extended to unsigned 16-bit fn dimm8(self: *CPU, tick_func: TickFunc) u16 { return @bitCast(u16, @as(i16, @bitCast(i8, self.imm8(tick_func)))); } // helper function to push 16 bit value on stack fn push16(self: *CPU, val: u16, tick_func: TickFunc) void { self.SP -%= 1; self.memWrite(self.SP, @truncate(u8, val>>8), tick_func); self.SP -%= 1; self.memWrite(self.SP, @truncate(u8, val), tick_func); } // helper function pop 16 bit value from stack fn pop16(self: *CPU, tick_func: TickFunc) u16 { const l: u16 = self.memRead(self.SP, tick_func); self.SP +%= 1; const h: u16 = self.memRead(self.SP, tick_func); self.SP +%= 1; return (h<<8) | l; } // generate effective address for (HL), (IX+d), (IY+d) and put into WZ fn addrWZ(self: *CPU, extra_ticks: u64, tick_func: TickFunc) void { self.WZ = self.loadHLIXIY(); if (0 != self.ixiy) { const d = self.dimm8(tick_func); self.WZ +%= d; self.tick(extra_ticks, 0, tick_func); } } // perform an opcode fetch machine cycle fn fetch(self: *CPU, tick_func: TickFunc) u8 { self.pins = setAddr(self.pins, self.PC); self.tickWait(4, M1|MREQ|RD, tick_func); self.PC +%= 1; self.bumpR(); return getData(self.pins); } // special opcode fetch without memory refresh and special R handling for IX/IY prefix case fn fetchCB(self: *CPU, tick_func: TickFunc) u8 { self.pins = setAddr(self.pins, self.PC); self.tickWait(4, M1|MREQ|RD, tick_func); self.PC +%= 1; if (0 == self.ixiy) { self.bumpR(); } return getData(self.pins); } // read 16-bit immediate fn imm16(self: *CPU, tick_func: TickFunc) u16 { const z: u16 = self.memRead(self.PC, tick_func); self.PC +%= 1; const w: u16 = self.memRead(self.PC, tick_func); self.PC +%= 1; self.WZ = (w << 8) | z; return self.WZ; } // load from 8-bit register or effective address (HL)/(IX+d)/IY+d) fn load8(self: *CPU, z: u3, tick_func: TickFunc) u8 { return switch (z) { B,C,D,E,A=> self.regs[z], H => switch (self.ixiy) { 0 => self.regs[H], UseIX => @truncate(u8, self.IX >> 8), UseIY => @truncate(u8, self.IY >> 8), else => unreachable, }, L => switch (self.ixiy) { 0 => self.regs[L], UseIX => @truncate(u8, self.IX), UseIY => @truncate(u8, self.IY), else => unreachable, }, F => self.memRead(self.WZ, tick_func) }; } // same as load8, but also never replace H,L with IXH,IYH,IXH,IXL fn load8HL(self: *CPU, z: u3, tick_func: TickFunc) u8 { if (z != 6) { return self.regs[z]; } else { return self.memRead(self.WZ, tick_func); } } // store into 8-bit register or effective address (HL)/(IX+d)/(IY+d) fn store8(self: *CPU, y: u3, val: u8, tick_func: TickFunc) void { switch (y) { B,C,D,E,A => { self.regs[y] = val; }, H => switch (self.ixiy) { 0 => { self.regs[H] = val; }, UseIX => { self.IX = (self.IX & 0x00FF) | (@as(u16,val)<<8); }, UseIY => { self.IY = (self.IY & 0x00FF) | (@as(u16,val)<<8); }, else => unreachable, }, L => switch (self.ixiy) { 0 => { self.regs[L] = val; }, UseIX => { self.IX = (self.IX & 0xFF00) | val; }, UseIY => { self.IY = (self.IY & 0xFF00) | val; }, else => unreachable, }, F => self.memWrite(self.WZ, val, tick_func), } } // same as store8, but never replace H,L with IXH,IYH, IXL, IYL fn store8HL(self: *CPU, y: u3, val: u8, tick_func: TickFunc) void { if (y != 6) { self.regs[y] = val; } else { self.memWrite(self.WZ, val, tick_func); } } // store into HL, IX or IY, depending on current index mode fn storeHLIXIY(self: *CPU, val: u16) void { switch (self.ixiy) { 0 => self.setR16(HL, val), UseIX => self.IX = val, UseIY => self.IY = val, else => unreachable } } // store 16-bit value into register with special handling for SP fn store16SP(self: *CPU, reg: u2, val: u16) void { switch (reg) { BC => self.setR16(BC, val), DE => self.setR16(DE, val), HL => self.storeHLIXIY(val), FA => self.SP = val, } } // store 16-bit value into register with special case handling for AF fn store16AF(self: *CPU, reg: u2, val: u16) void { switch (reg) { BC => self.setR16(BC, val), DE => self.setR16(DE, val), HL => self.storeHLIXIY(val), FA => { self.regs[F] = @truncate(u8, val); self.regs[A] = @truncate(u8, val>>8); }, } } // load from HL, IX or IY, depending on current index mode fn loadHLIXIY(self: *CPU) u16 { return switch (self.ixiy) { 0 => self.r16(HL), UseIX => return self.IX, UseIY => return self.IY, else => unreachable }; } // load 16-bit value from register with special handling for SP fn load16SP(self: *CPU, reg: u2) u16 { return switch(reg) { BC => self.r16(BC), DE => self.r16(DE), HL => self.loadHLIXIY(), FA => self.SP, }; } // load 16-bit value from register with special case handling for AF fn load16AF(self: *CPU, reg: u2) u16 { return switch(reg) { BC => self.r16(BC), DE => self.r16(DE), HL => self.loadHLIXIY(), FA => @as(u16, self.regs[A])<<8 | self.regs[F], }; } // HALT fn opHALT(self: *CPU) void { self.pins |= HALT; self.PC -%= 1; } // LD r,r fn opLD_r_r(self: *CPU, y: u3, z: u3, tick_func: TickFunc) void { if ((y == 6) or (z == 6)) { self.addrWZ(5, tick_func); // for (IX+d)/(IY+d), H and L are not replaced with IXH/IYH and IYH/IYL const val = self.load8HL(z, tick_func); self.store8HL(y, val, tick_func); } else { // regular LD r,r may map H and L to IXH/IYH and IXL/IYL const val = self.load8(z, tick_func); self.store8(y, val, tick_func); } } // LD r,n fn opLD_r_n(self: *CPU, y: u3, tick_func: TickFunc) void { if (y == 6) { self.addrWZ(2, tick_func); } const val = self.imm8(tick_func); self.store8(y, val, tick_func); } // ALU r fn opALU_r(self: *CPU, y: u3, z: u3, tick_func: TickFunc) void { if (z == 6) { self.addrWZ(5, tick_func); } const val = self.load8(z, tick_func); alu8(&self.regs, y, val); } // ALU n fn opALU_n(self: *CPU, y: u3, tick_func: TickFunc) void { const val = self.imm8(tick_func); alu8(&self.regs, y, val); } // NEG fn opNEG(self: *CPU) void { neg8(&self.regs); } // INC r fn opINC_r(self: *CPU, y: u3, tick_func: TickFunc) void { if (y == 6) { self.addrWZ(5, tick_func); self.tick(1, 0, tick_func); // filler tick } const val = self.load8(y, tick_func); const res = inc8(&self.regs, val); self.store8(y, res, tick_func); } // DEC r fn opDEC_r(self: *CPU, y: u3, tick_func: TickFunc) void { if (y == 6) { self.addrWZ(5, tick_func); self.tick(1, 0, tick_func); // filler tick } const val = self.load8(y, tick_func); const res = dec8(&self.regs, val); self.store8(y, res, tick_func); } // INC rp fn opINC_rp(self: *CPU, p: u2, tick_func: TickFunc) void { self.tick(2, 0, tick_func); // 2 filler ticks self.store16SP(p, self.load16SP(p) +% 1); } // DEC rp fn opDEC_rp(self: *CPU, p: u2, tick_func: TickFunc) void { self.tick(2, 0, tick_func); // 2 filler tick self.store16SP(p, self.load16SP(p) -% 1); } // LD rp,nn fn opLD_rp_nn(self: *CPU, p: u2, tick_func: TickFunc) void { const val = self.imm16(tick_func); self.store16SP(p, val); } // LD (BC/DE),A fn opLD_iBCDE_A(self: *CPU, r: u2, tick_func: TickFunc) void { self.WZ = self.r16(r); const val = self.regs[A]; self.memWrite(self.WZ, val, tick_func); self.WZ = (@as(u16, val)<<8) | ((self.WZ +% 1) & 0xFF); } // LD A,(BC/DE) fn opLD_A_iBCDE(self: *CPU, r: u2, tick_func: TickFunc) void { self.WZ = self.r16(r); self.regs[A] = self.memRead(self.WZ, tick_func); self.WZ +%= 1; } // LD (nn),HL fn opLD_inn_HL(self: *CPU, tick_func: TickFunc) void { self.WZ = self.imm16(tick_func); const val = self.loadHLIXIY(); self.memWrite(self.WZ, @truncate(u8, val), tick_func); self.WZ +%= 1; self.memWrite(self.WZ, @truncate(u8, val>>8), tick_func); } // LD HL,(nn) fn opLD_HL_inn(self: *CPU, tick_func: TickFunc) void { self.WZ = self.imm16(tick_func); const l: u16 = self.memRead(self.WZ, tick_func); self.WZ +%= 1; const h: u16 = self.memRead(self.WZ, tick_func); self.storeHLIXIY((h<<8) | l); } // LD (nn),A fn opLD_inn_A(self: *CPU, tick_func: TickFunc) void { self.WZ = self.imm16(tick_func); const val = self.regs[A]; self.memWrite(self.WZ, val, tick_func); self.WZ = (@as(u16, val)<<8) | ((self.WZ +% 1) & 0xFF); } // LD A,(nn) fn opLD_A_inn(self: *CPU, tick_func: TickFunc) void { self.WZ = self.imm16(tick_func); self.regs[A] = self.memRead(self.WZ, tick_func); self.WZ +%= 1; } // LD (nn),BC/DE/HL/SP fn opLD_inn_rp(self: *CPU, p: u2, tick_func: TickFunc) void { self.WZ = self.imm16(tick_func); const val = self.load16SP(p); self.memWrite(self.WZ, @truncate(u8, val), tick_func); self.WZ +%= 1; self.memWrite(self.WZ, @truncate(u8, val>>8), tick_func); } // LD BC/DE/HL/SP,(nn) fn opLD_rp_inn(self: *CPU, p: u2, tick_func: TickFunc) void { self.WZ = self.imm16(tick_func); const l: u16 = self.memRead(self.WZ, tick_func); self.WZ +%= 1; const h: u16 = self.memRead(self.WZ, tick_func); self.store16SP(p, (h<<8) | l); } // LD SP,HL/IX/IY fn opLD_SP_HL(self: *CPU, tick_func: TickFunc) void { self.tick(2, 0, tick_func); // 2 filler ticks self.SP = self.loadHLIXIY(); } // LD I,A fn opLD_I_A(self: *CPU, tick_func: TickFunc) void { self.tick(1, 0, tick_func); // 1 filler tick self.I = self.regs[A]; } // LD R,A fn opLD_R_A(self: *CPU, tick_func: TickFunc) void { self.tick(1, 0, tick_func); // 1 filler tick self.R = self.regs[A]; } // special flag computation for LD_A,I / LD A,R fn irFlags(val: u8, f: u8, iff2: bool) u8{ return (f & CF) | szFlags(val) | (val & YF|XF) | if (iff2) PF else 0; } // LD A,I fn opLD_A_I(self: *CPU, tick_func: TickFunc) void { self.tick(1, 0, tick_func); // 1 filler tick self.regs[A] = self.I; self.regs[F] = irFlags(self.regs[A], self.regs[F], self.iff2); } // LD A,R fn opLD_A_R(self: *CPU, tick_func: TickFunc) void { self.tick(1, 0, tick_func); // 1 filler tick self.regs[A] = self.R; self.regs[F] = irFlags(self.regs[A], self.regs[F], self.iff2); } // PUSH BC/DE/HL/AF/IX/IY fn opPUSH_rp2(self: *CPU, p: u2, tick_func: TickFunc) void { self.tick(1, 0, tick_func); // 1 filler tick const val = self.load16AF(p); self.push16(val, tick_func); } // POP BC/DE/HL/AF/IX/IY fn opPOP_rp2(self: *CPU, p: u2, tick_func: TickFunc) void { const val = self.pop16(tick_func); self.store16AF(p, val); } // EX DE,HL fn opEX_DE_HL(self: *CPU) void { const de = self.r16(DE); const hl = self.r16(HL); self.setR16(DE, hl); self.setR16(HL, de); } // EX AF,AF' fn opEX_AF_AF(self: *CPU) void { const fa = self.r16(FA); self.setR16(FA, self.ex[FA]); self.ex[FA] = fa; } // EXX fn opEXX(self: *CPU) void { const bc = self.r16(BC); self.setR16(BC, self.ex[BC]); self.ex[BC] = bc; const de = self.r16(DE); self.setR16(DE, self.ex[DE]); self.ex[DE] = de; const hl = self.r16(HL); self.setR16(HL, self.ex[HL]); self.ex[HL] = hl; } // EX (SP),HL fn opEX_iSP_HL(self: *CPU, tick_func: TickFunc) void { self.tick(3, 0, tick_func); // 3 filler ticks const l: u16 = self.memRead(self.SP, tick_func); const h: u16 = self.memRead(self.SP +% 1, tick_func); const val = self.loadHLIXIY(); self.memWrite(self.SP, @truncate(u8, val), tick_func); self.memWrite(self.SP +% 1, @truncate(u8, val>>8), tick_func); self.WZ =(h<<8) | l; self.storeHLIXIY(self.WZ); } // RLCA fn opRLCA(self: *CPU) void { const a = self.regs[A]; const r = (a<<1) | (a>>7); const f = self.regs[F]; self.regs[F] = ((a>>7) & CF) | (f & (SF|ZF|PF)) | (r & (YF|XF)); self.regs[A] = r; } // RRCA fn opRRCA(self: *CPU) void { const a = self.regs[A]; const r = (a>>1) | (a<<7); const f = self.regs[F]; self.regs[F] = (a & CF) | (f & (SF|ZF|PF)) | (r & (YF|XF)); self.regs[A] = r; } // RLA fn opRLA(self: *CPU) void { const a = self.regs[A]; const f = self.regs[F]; const r = (a<<1) | (f & CF); self.regs[F] = ((a>>7) & CF) | (f & (SF|ZF|PF)) | (r & (YF|XF)); self.regs[A] = r; } // RRA fn opRRA(self: *CPU) void { const a = self.regs[A]; const f = self.regs[F]; const r = (a >> 1) | ((f & CF) << 7); self.regs[F] = (a & CF) | (f & (SF|ZF|PF)) | (r & (YF|XF)); self.regs[A] = r; } // RLD fn opRLD(self: *CPU, tick_func: TickFunc) void { self.WZ = self.loadHLIXIY(); const d_in = self.memRead(self.WZ, tick_func); const a_in = self.regs[A]; const a_out = (a_in & 0xF0) | (d_in >> 4); const d_out = (d_in << 4) | (a_in & 0x0F); self.memWrite(self.WZ, d_out, tick_func); self.WZ +%= 1; self.regs[A] = a_out; self.regs[F] = (self.regs[F] & CF) | szpFlags(a_out); self.tick(4, 0, tick_func); // 4 filler ticks } // RRD fn opRRD(self: *CPU, tick_func: TickFunc) void { self.WZ = self.loadHLIXIY(); const d_in = self.memRead(self.WZ, tick_func); const a_in = self.regs[A]; const a_out = (a_in & 0xF0) | (d_in & 0x0F); const d_out = (d_in >> 4) | (a_in << 4); self.memWrite(self.WZ, d_out, tick_func); self.WZ +%= 1; self.regs[A] = a_out; self.regs[F] = (self.regs[F] & CF) | szpFlags(a_out); self.tick(4, 0, tick_func); // 4 filler ticks } // DAA fn opDAA(self: *CPU) void { const a = self.regs[A]; var v = a; var f = self.regs[F]; if (0 != (f & NF)) { if (((a & 0xF) > 0x9) or (0 != (f & HF))) { v -%= 0x06; } if ((a > 0x99) or (0 != (f & CF))) { v -%= 0x60; } } else { if (((a & 0xF) > 0x9) or (0 != (f & HF))) { v +%= 0x06; } if ((a > 0x99) or (0 != (f & CF))) { v +%= 0x60; } } f &= CF|NF; f |= if (a > 0x99) CF else 0; f |= (a ^ v) & HF; f |= szpFlags(v); self.regs[A] = v; self.regs[F] = f; } // CPL fn opCPL(self: *CPU) void { const a = self.regs[A] ^ 0xFF; const f = self.regs[F]; self.regs[A] = a; self.regs[F] = HF | NF | (f & (SF|ZF|PF|CF)) | (a & (YF|XF)); } // SCF fn opSCF(self: *CPU) void { const a = self.regs[A]; const f = self.regs[F]; self.regs[F] = CF | (f & (SF|ZF|PF|CF)) | (a & (YF|XF)); } // CCF fn opCCF(self: *CPU) void { const a = self.regs[A]; const f = self.regs[F]; self.regs[F] = (((f & CF)<<4) | (f & (SF|ZF|PF|CF)) | (a & (YF|XF))) ^ CF; } // LDI/LDD/LDIR/LDDR fn opLDI_LDD_LDIR_LDDR(self: *CPU, y: u3, tick_func: TickFunc) void { var hl = self.r16(HL); var de = self.r16(DE); var val = self.memRead(hl, tick_func); self.memWrite(de, val, tick_func); val +%= self.regs[A]; if (0 != (y & 1)) { hl -%= 1; de -%= 1; } else { hl +%= 1; de +%= 1; } self.setR16(HL, hl); self.setR16(DE, de); self.tick(2, 0, tick_func); // 2 filler ticks var f = (self.regs[F] & (SF|ZF|CF)) | ((val << 4) & YF) | (val & XF); const bc = self.r16(BC) -% 1; self.setR16(BC, bc); if (bc != 0) { f |= VF; } self.regs[F] = f; if ((y >= 6) and (0 != bc)) { self.PC -%= 2; self.WZ = self.PC +% 1; self.tick(5, 0, tick_func); // 5 filler ticks } } // CPI, CPD, CPIR, CPDR fn opCPI_CPD_CPIR_CPDR(self: *CPU, y: u3, tick_func: TickFunc) void { var hl = self.r16(HL); var val = self.regs[A] -% self.memRead(hl, tick_func); if (0 != (y & 1)) { hl -%= 1; self.WZ -%= 1; } else { hl +%= 1; self.WZ +%= 1; } self.setR16(HL, hl); self.tick(5, 0, tick_func); // 5 filler ticks var f = (self.regs[F] & CF) | NF | szFlags(val); if ((val & 0x0F) > (self.regs[A] & 0x0F)) { f |= HF; val -%= 1; } f |= ((val << 4) & YF) | (val & XF); const bc = self.r16(BC) -% 1; self.setR16(BC, bc); if (bc != 0) { f |= VF; } self.regs[F] = f; if ((y >= 6) and (0 != bc) and (0 == (f & ZF))) { self.PC -%= 2; self.WZ = self.PC +% 1; self.tick(5, 0, tick_func); // 5 filler ticks } } // DI fn opDI(self: *CPU) void { self.iff1 = false; self.iff2 = false; } // EI fn opEI(self: *CPU) void { self.iff1 = false; self.iff2 = false; self.ei = true; } // IM fn opIM(self: *CPU, y: u3) void { const im = [8]u2 { 0, 0, 1, 2, 0, 0, 1, 2 }; self.IM = im[y]; } // JP cc,nn fn opJP_cc_nn(self: *CPU, y: u3, tick_func: TickFunc) void { const val = self.imm16(tick_func); if (cc(self.regs[F], y)) { self.PC = val; } } // JP nn fn opJP_nn(self: *CPU, tick_func: TickFunc) void { self.PC = self.imm16(tick_func); } // JP (HL) fn opJP_HL(self: *CPU) void { self.PC = self.loadHLIXIY(); } // JR d fn opJR_d(self: *CPU, tick_func: TickFunc) void { const d = self.dimm8(tick_func); self.PC +%= d; self.WZ = self.PC; self.tick(5, 0, tick_func); // 5 filler ticks } // JR cc,d fn opJR_cc_d(self: *CPU, y: u3, tick_func: TickFunc) void { const d = self.dimm8(tick_func); if (cc(self.regs[F], y -% 4)) { self.PC +%= d; self.WZ = self.PC; self.tick(5, 0, tick_func); // 5 filler ticks } } // DJNZ_d fn opDJNZ_d(self: *CPU, tick_func: TickFunc) void { self.tick(1, 0, tick_func); // 1 filler tick const d = self.dimm8(tick_func); self.regs[B] -%= 1; if (self.regs[B] > 0) { self.PC +%= d; self.WZ = self.PC; self.tick(5, 0, tick_func); // 5 filler ticks } } // CALL nn fn opCALL_nn(self: *CPU, tick_func: TickFunc) void { const addr = self.imm16(tick_func); self.tick(1, 0, tick_func); // filler tick self.push16(self.PC, tick_func); self.PC = addr; } // CALL_cc_nn fn opCALL_cc_nn(self: *CPU, y: u3, tick_func: TickFunc) void { const addr = self.imm16(tick_func); if (cc(self.regs[F], y)) { self.tick(1, 0, tick_func); // filler tick self.push16(self.PC, tick_func); self.PC = addr; } } // RET fn opRET(self: *CPU, tick_func: TickFunc) void { self.PC = self.pop16(tick_func); self.WZ = self.PC; } // RETN/RETI fn opRETNI(self: *CPU, tick_func: TickFunc) void { // NOTE: according to Undocumented Z80 Documented, IFF2 is also // copied into IFF1 in RETI, not just RETN, and RETI and RETN // are in fact identical self.pins |= RETI; self.PC = self.pop16(tick_func); self.WZ = self.PC; self.iff1 = self.iff2; } // RET_cc fn opRET_cc(self: *CPU, y: u3, tick_func: TickFunc) void { self.tick(1, 0, tick_func); // filler tick if (cc(self.regs[F], y)) { self.PC = self.pop16(tick_func); self.WZ = self.PC; } } // ADD HL,rp fn opADD_HL_rp(self: *CPU, p: u2, tick_func: TickFunc) void { const acc = self.loadHLIXIY(); self.WZ = acc +% 1; const val = self.load16SP(p); const res: u17 = @as(u17,acc) +% val; self.storeHLIXIY(@truncate(u16, res)); var f: u17 = self.regs[F] & (SF|ZF|VF); f |= ((acc^res^val)>>8) & HF; f |= ((res >> 16) & CF) | ((res >> 8) & (YF|XF)); self.regs[F] = @truncate(u8, f); self.tick(7, 0, tick_func); // filler ticks } // ADC HL,rp fn opADC_HL_rp(self: *CPU, p: u2, tick_func: TickFunc) void { const acc = self.r16(HL); self.WZ = acc +% 1; const val = self.load16SP(p); const res: u17 = @as(u17,acc) +% val +% (self.regs[F] & CF); self.setR16(HL, @truncate(u16, res)); var f: u17 = ((val ^ acc ^ 0x8000) & (val ^ res) & 0x8000) >> 13; f |= ((acc ^ res ^ val) >> 8) & HF; f |= (res >> 16) & CF; f |= (res >> 8) & (SF|YF|XF); f |= if (0 == (res & 0xFFFF)) ZF else 0; self.regs[F] = @truncate(u8, f); self.tick(7, 0, tick_func); // filler ticks } // SBC HL,rp fn opSBC_HL_rp(self: *CPU, p: u2, tick_func: TickFunc) void { const acc = self.r16(HL); self.WZ = acc +% 1; const val = self.load16SP(p); const res: u17 = @as(u17,acc) -% val -% (self.regs[F] & CF); self.setR16(HL, @truncate(u16, res)); var f: u17 = NF | (((val ^ acc) & (acc ^ res) & 0x8000) >> 13); f |= ((acc ^ res ^ val) >> 8) & HF; f |= (res >> 16) & CF; f |= (res >> 8) & (SF|YF|XF); f |= if (0 == (res & 0xFFFF)) ZF else 0; self.regs[F] = @truncate(u8, f); self.tick(7, 0, tick_func); // filler ticks } // IN A,(n) fn opIN_A_in(self: *CPU, tick_func: TickFunc) void { const n = self.imm8(tick_func); const port = (@as(u16, self.regs[A])<<8) | n; self.regs[A] = self.ioRead(port, tick_func); self.WZ = port +% 1; } // OUT (n),A fn opOUT_in_A(self: *CPU, tick_func: TickFunc) void { const n = self.imm8(tick_func); const a = self.regs[A]; const port = (@as(u16, a)<<8) | n; self.ioWrite(port, a, tick_func); self.WZ = (port & 0xFF00) | ((port +% 1) & 0x00FF); } // IN r,(C) fn opIN_ry_iC(self: *CPU, y: u3, tick_func: TickFunc) void { const bc = self.r16(BC); const val = self.ioRead(bc, tick_func); self.WZ = bc +% 1; self.regs[F] = (self.regs[F] & CF) | szpFlags(val); // undocumented special case for IN (HL),(C): only store flags, throw away input byte if (y != 6) { self.store8(y, val, tick_func); } } // OUT (C),r fn opOUT_iC_ry(self: *CPU, y: u3, tick_func: TickFunc) void { const bc = self.r16(BC); // undocumented special case for OUT (C),(HL): output 0 instead var val = if (y == 6) 0 else self.load8(y, tick_func); self.ioWrite(bc, val, tick_func); self.WZ = bc +% 1; } // INI/IND/INIR/INDR fn opINI_IND_INIR_INDR(self: *CPU, y: u3, tick_func: TickFunc) void { self.tick(1, 0, tick_func); // filler tick var port = self.r16(BC); var hl = self.r16(HL); const val = self.ioRead(port, tick_func); self.memWrite(hl, val, tick_func); const b = self.regs[B] -% 1; self.regs[B] = b; var c = self.regs[C]; if (0 != (y & 1)) { port -%= 1; hl -%= 1; c -%= 1; } else { port +%= 1; hl +%= 1; c +%= 1; } self.setR16(HL, hl); self.WZ = port; var f = (if (b == 0) ZF else (b & SF)) | (b & (XF|YF)); if (0 != (val & SF)) { f |= NF; } const t = @as(u9,c) + val; if (0 != (t & 0x100)) { f |= HF|CF; } f |= szpFlags((@truncate(u8,t) & 0x07) ^ b) & PF; self.regs[F] = f; if ((y >= 6) and (b != 0)) { self.PC -%= 2; self.tick(5, 0, tick_func); // filler ticks } } // OUTI/OUTD/OTIR/OTDR fn opOUTI_OUTD_OTIR_OTDR(self: *CPU, y: u3, tick_func: TickFunc) void { self.tick(1, 0, tick_func); // filler tick var hl = self.r16(HL); const val = self.memRead(hl, tick_func); const b = self.regs[B] -% 1; self.regs[B] = b; var port = self.r16(BC); self.ioWrite(port, val, tick_func); if (0 != (y & 1)) { port -%= 1; hl -%= 1; } else { port +%= 1; hl +%= 1; } self.setR16(HL, hl); self.WZ = port; var f = (if (b == 0) ZF else (b & SF)) | (b & (XF|YF)); if (0 != (val & SF)) { f |= NF; } const t = @as(u9, self.regs[L]) + val; if (0 != (t & 0x100)) { f |= HF|CF; } f |= szpFlags((@truncate(u8,t) & 0x07) ^ b) & PF; self.regs[F] = f; if ((y >= 6) and (b != 0)) { self.PC -%= 2; self.tick(5, 0, tick_func); // filler ticks } } // RST y*8 fn opRSTy(self: *CPU, y: u3, tick_func: TickFunc) void { self.tick(1, 0, tick_func); // filler tick self.push16(self.PC, tick_func); self.PC = @as(u16, y) * 8; self.WZ = self.WZ; } // flag computation functions fn szFlags(val: u9) u8 { if (@truncate(u8, val) == 0) { return ZF; } else { return @truncate(u8, val) & SF; } } fn szyxchFlags(acc: u9, val: u8, res: u9) u8 { return szFlags(res) | @truncate(u8, (res & (YF|XF)) | ((res >> 8) & CF) | ((acc^val^res) & HF)); } fn addFlags(acc: u9, val: u8, res: u9) u8 { return szyxchFlags(acc, val, res) | @truncate(u8, (((val^acc^0x80) & (val^res))>>5) & VF); } fn subFlags(acc: u9, val: u8, res: u9) u8 { return NF | szyxchFlags(acc, val, res) | @truncate(u8, (((val^acc) & (res^acc))>>5) & VF); } fn cpFlags(acc: u9, val: u8, res: u9) u8 { return NF | szFlags(res) | @truncate(u8, (val & (YF|XF)) | ((res >> 8) & CF) | ((acc^val^res) & HF) | ((((val^acc) & (res^acc))>>5) & VF)); } fn szpFlags(val: u8) u8 { return szFlags(val) | (((@popCount(u8, val)<<2) & PF) ^ PF) | (val & (YF|XF)); } // test cc flag fn cc(f: u8, y: u3) bool { return switch (y) { 0 => (0 == (f & ZF)), // NZ 1 => (0 != (f & ZF)), // Z 2 => (0 == (f & CF)), // NC 3 => (0 != (f & CF)), // C 4 => (0 == (f & PF)), // PO 5 => (0 != (f & PF)), // PE 6 => (0 == (f & SF)), // P 7 => (0 != (f & SF)), // M }; } // ALU functions fn add8(r: *Regs, val: u8) void { const acc: u9 = r[A]; const res: u9 = acc + val; r[F] = addFlags(acc, val, res); r[A] = @truncate(u8, res); } fn adc8(r: *Regs, val: u8) void { const acc: u9 = r[A]; const res: u9 = acc + val + (r[F] & CF); r[F] = addFlags(acc, val, res); r[A] = @truncate(u8, res); } fn sub8(r: *Regs, val: u8) void { const acc: u9 = r[A]; const res: u9 = acc -% val; r[F] = subFlags(acc, val, res); r[A] = @truncate(u8, res); } fn sbc8(r: *Regs, val: u8) void { const acc: u9 = r[A]; const res: u9 = acc -% val -% (r[F] & CF); r[F] = subFlags(acc, val, res); r[A] = @truncate(u8, res); } fn and8(r: *Regs, val: u8) void { r[A] &= val; r[F] = szpFlags(r[A]) | HF; } fn xor8(r: *Regs, val: u8) void { r[A] ^= val; r[F] = szpFlags(r[A]); } fn or8(r: *Regs, val: u8) void { r[A] |= val; r[F] = szpFlags(r[A]); } fn cp8(r: *Regs, val: u8) void { const acc: u9 = r[A]; const res: u9 = acc -% val; r[F] = cpFlags(acc, val, res); } fn alu8(r: *Regs, y: u3, val: u8) void { switch(y) { 0 => add8(r, val), 1 => adc8(r, val), 2 => sub8(r, val), 3 => sbc8(r, val), 4 => and8(r, val), 5 => xor8(r, val), 6 => or8(r, val), 7 => cp8(r, val), } } fn neg8(r: *Regs) void { const val = r[A]; r[A] = 0; sub8(r, val); } fn inc8(r: *Regs, val: u8) u8 { const res = val +% 1; var f: u8 = szFlags(res) | (res & (XF|YF)) | ((res ^ val) & HF); f |= (((val ^ res) & res) >> 5) & VF; r[F] = f | (r[F] & CF); return res; } fn dec8(r: *Regs, val: u8) u8 { const res = val -% 1; var f: u8 = NF | szFlags(res) | (res & (XF|YF)) | ((res ^ val) & HF); f |= (((val ^ res) & val) >> 5) & VF; r[F] = f | (r[F] & CF); return res; } //=== TESTS ==================================================================== const expect = @import("std").testing.expect; // FIXME: is this check needed to make sure that a regular exe won't have // a 64 KByte blob in the data section? const is_test = @import("builtin").is_test; var mem = if (is_test) [_]u8{0} ** 0x10000 else null; var io = if (is_test) [_]u8{0} ** 0x10000 else null; fn clearMem() void { mem = [_]u8{0} ** 0x10000; } fn clearIO() void { io = [_]u8{0} ** 0x10000; } // a generic test tick callback fn testTick(ticks: u64, i_pins: u64, userdata: usize) u64 { _ = ticks; _ = userdata; var pins = i_pins; const a = getAddr(pins); if ((pins & MREQ) != 0) { if ((pins & RD) != 0) { pins = setData(pins, mem[a]); } else if ((pins & WR) != 0) { mem[a] = getData(pins); } } else if ((pins & IORQ) != 0) { if ((pins & RD) != 0) { pins = setData(pins, io[a]); } else if ((pins & WR) != 0) { io[a] = getData(pins); } } return pins; } fn makeRegs() Regs { var res: Regs = [_]u8{0xFF} ** NumRegs8; res[F] = 0; return res; } fn flags(f: u8, mask: u8) bool { return (f & ~(XF|YF)) == mask; } fn testRF(r: *const Regs, reg: u3, val: u8, mask: u8) bool { return (r[reg] == val) and ((r[F] & ~(XF|YF)) == mask); } fn testAF(r: *const Regs, val: u8, mask: u8) bool { return testRF(r, A, val, mask); } test "set/get data" { var pins: u64 = 0; pins = setData(pins, 0xFF); try expect(getData(pins) == 0xFF); pins = setData(pins, 1); try expect(getData(pins) == 1); } test "set/get address" { var pins: u64 = 0; pins = setAddr(pins, 0x1234); try expect(getAddr(pins) == 0x1234); pins = setAddr(pins, 0x4321); try expect(getAddr(pins) == 0x4321); } test "setAddrData" { var pins: u64 = 0; pins = setAddrData(pins, 0x1234, 0x54); try expect(pins == 0x541234); try expect(getAddr(pins) == 0x1234); try expect(getData(pins) == 0x54); } test "set/get wait ticks" { var pins: u64 = 0x221111; pins = setWait(pins, 7); try expect(getWait(pins) == 7); pins = setWait(pins, 1); try expect(getWait(pins) == 1); try expect(getAddr(pins) == 0x1111); try expect(getData(pins) == 0x22); } test "tick" { const inner = struct { fn tick_func(ticks: u64, pins: u64, userdata: usize) u64 { _ = userdata; if (ticks == 3 and getData(pins) == 0x56 and getAddr(pins) == 0x1234 and (pins & M1|MREQ|RD) == M1|MREQ|RD) { // success return setData(pins, 0x23); } else { return 0; } } }; var cpu = CPU{ .pins = setAddrData(0, 0x1234, 0x56) }; cpu.tick(3, M1|MREQ|RD, .{ .func=inner.tick_func }); try expect(getData(cpu.pins) == 0x23); try expect(cpu.ticks == 3); } test "tickWait" { const inner = struct { fn tick_func(ticks: u64, pins: u64, userdata: usize) u64 { _ = ticks; _ = userdata; return setWait(pins, 5); } }; var cpu = CPU{ .pins = setWait(0, 7) }; cpu.tickWait(3, M1|MREQ|RD, .{ .func=inner.tick_func }); try expect(getWait(cpu.pins) == 5); try expect(cpu.ticks == 8); } test "memRead" { clearMem(); mem[0x1234] = 0x23; var cpu = CPU{ }; const val = cpu.memRead(0x1234, .{ .func=testTick }); try expect((cpu.pins & CtrlPinMask) == MREQ|RD); try expect(getData(cpu.pins) == 0x23); try expect(val == 0x23); try expect(cpu.ticks == 3); } test "memWrite" { clearMem(); var cpu = CPU{ }; cpu.memWrite(0x1234, 0x56, .{ .func=testTick }); try expect((cpu.pins & CtrlPinMask) == MREQ|WR); try expect(getData(cpu.pins) == 0x56); try expect(cpu.ticks == 3); } test "ioRead" { clearIO(); io[0x1234] = 0x23; var cpu = CPU{ }; const val = cpu.ioRead(0x1234, .{ .func=testTick }); try expect((cpu.pins & CtrlPinMask) == IORQ|RD); try expect(getData(cpu.pins) == 0x23); try expect(val == 0x23); try expect(cpu.ticks == 4); } test "ioWrite" { clearIO(); var cpu = CPU{ }; cpu.ioWrite(0x1234, 0x56, .{ .func=testTick }); try expect((cpu.pins & CtrlPinMask) == IORQ|WR); try expect(getData(cpu.pins) == 0x56); try expect(cpu.ticks == 4); } test "bumpR" { // only 7 bits are incremented, and the topmost bit is sticky var cpu = CPU{ }; cpu.R = 0x00; cpu.bumpR(); try expect(cpu.R == 1); cpu.R = 0x7F; cpu.bumpR(); try expect(cpu.R == 0); cpu.R = 0x80; cpu.bumpR(); try expect(cpu.R == 0x81); cpu.R = 0xFF; cpu.bumpR(); try expect(cpu.R == 0x80); } test "fetch" { clearMem(); mem[0x2345] = 0x42; var cpu = CPU{ .PC = 0x2345, .R = 0 }; const op = cpu.fetch(.{ .func=testTick }); try expect(op == 0x42); try expect((cpu.pins & CtrlPinMask) == M1|MREQ|RD); try expect(getData(cpu.pins) == 0x42); try expect(cpu.ticks == 4); try expect(cpu.PC == 0x2346); try expect(cpu.R == 1); } test "add8" { var r = makeRegs(); r[A] = 0xF; add8(&r, r[A]); try expect(testAF(&r, 0x1E, HF)); add8(&r, 0xE0); try expect(testAF(&r, 0xFE, SF)); r[A] = 0x81; add8(&r, 0x80); try expect(testAF(&r, 0x01, VF|CF)); add8(&r, 0xFF); try expect(testAF(&r, 0x00, ZF|HF|CF)); add8(&r, 0x40); try expect(testAF(&r, 0x40, 0)); add8(&r, 0x80); try expect(testAF(&r, 0xC0, SF)); add8(&r, 0x33); try expect(testAF(&r, 0xF3, SF)); add8(&r, 0x44); try expect(testAF(&r, 0x37, CF)); } test "adc8" { var r = makeRegs(); r[A] = 0; adc8(&r, 0x00); try expect(testAF(&r, 0x00, ZF)); adc8(&r, 0x41); try expect(testAF(&r, 0x41, 0)); adc8(&r, 0x61); try expect(testAF(&r, 0xA2, SF|VF)); adc8(&r, 0x81); try expect(testAF(&r, 0x23, VF|CF)); adc8(&r, 0x41); try expect(testAF(&r, 0x65, 0)); adc8(&r, 0x61); try expect(testAF(&r, 0xC6, SF|VF)); adc8(&r, 0x81); try expect(testAF(&r, 0x47, VF|CF)); adc8(&r, 0x01); try expect(testAF(&r, 0x49, 0)); } test "sub8" { var r = makeRegs(); r[A] = 0x04; sub8(&r, 0x04); try expect(testAF(&r, 0x00, ZF|NF)); sub8(&r, 0x01); try expect(testAF(&r, 0xFF, SF|HF|NF|CF)); sub8(&r, 0xF8); try expect(testAF(&r, 0x07, NF)); sub8(&r, 0x0F); try expect(testAF(&r, 0xF8, SF|HF|NF|CF)); sub8(&r, 0x79); try expect(testAF(&r, 0x7F, HF|VF|NF)); sub8(&r, 0xC0); try expect(testAF(&r, 0xBF, SF|VF|NF|CF)); sub8(&r, 0xBF); try expect(testAF(&r, 0x00, ZF|NF)); sub8(&r, 0x01); try expect(testAF(&r, 0xFF, SF|HF|NF|CF)); sub8(&r, 0xFE); try expect(testAF(&r, 0x01, NF)); } test "sbc8" { var r = makeRegs(); r[A] = 0x04; sbc8(&r, 0x04); try expect(testAF(&r, 0x00, ZF|NF)); sbc8(&r, 0x01); try expect(testAF(&r, 0xFF, SF|HF|NF|CF)); sbc8(&r, 0xF8); try expect(testAF(&r, 0x06, NF)); sbc8(&r, 0x0F); try expect(testAF(&r, 0xF7, SF|HF|NF|CF)); sbc8(&r, 0x79); try expect(testAF(&r, 0x7D, HF|VF|NF)); sbc8(&r, 0xC0); try expect(testAF(&r, 0xBD, SF|VF|NF|CF)); sbc8(&r, 0xBF); try expect(testAF(&r, 0xFD, SF|HF|NF|CF)); sbc8(&r, 0x01); try expect(testAF(&r, 0xFB, SF|NF)); sbc8(&r, 0xFE); try expect(testAF(&r, 0xFD, SF|HF|NF|CF)); } test "cp8" { var r = makeRegs(); r[A] = 0x04; cp8(&r, 0x04); try expect(testAF(&r, 0x04, ZF|NF)); cp8(&r, 0x05); try expect(testAF(&r, 0x04, SF|HF|NF|CF)); cp8(&r, 0x03); try expect(testAF(&r, 0x04, NF)); cp8(&r, 0xFF); try expect(testAF(&r, 0x04, HF|NF|CF)); cp8(&r, 0xAA); try expect(testAF(&r, 0x04, HF|NF|CF)); cp8(&r, 0x80); try expect(testAF(&r, 0x04, SF|VF|NF|CF)); cp8(&r, 0x7F); try expect(testAF(&r, 0x04, SF|HF|NF|CF)); cp8(&r, 0x04); try expect(testAF(&r, 0x04, ZF|NF)); } test "and8" { var r = makeRegs(); r[A] = 0xFF; and8(&r, 0x01); try expect(testAF(&r, 0x01, HF)); r[A] = 0xFF; and8(&r, 0x03); try expect(testAF(&r, 0x03, HF|PF)); r[A] = 0xFF; and8(&r, 0x04); try expect(testAF(&r, 0x04, HF)); r[A] = 0xFF; and8(&r, 0x08); try expect(testAF(&r, 0x08, HF)); r[A] = 0xFF; and8(&r, 0x10); try expect(testAF(&r, 0x10, HF)); r[A] = 0xFF; and8(&r, 0x20); try expect(testAF(&r, 0x20, HF)); r[A] = 0xFF; and8(&r, 0x40); try expect(testAF(&r, 0x40, HF)); r[A] = 0xFF; and8(&r, 0xAA); try expect(testAF(&r, 0xAA, SF|HF|PF)); } test "xor8" { var r = makeRegs(); r[A] = 0x00; xor8(&r, 0x00); try expect(testAF(&r, 0x00, ZF|PF)); xor8(&r, 0x01); try expect(testAF(&r, 0x01, 0)); xor8(&r, 0x03); try expect(testAF(&r, 0x02, 0)); xor8(&r, 0x07); try expect(testAF(&r, 0x05, PF)); xor8(&r, 0x0F); try expect(testAF(&r, 0x0A, PF)); xor8(&r, 0x1F); try expect(testAF(&r, 0x15, 0)); xor8(&r, 0x3F); try expect(testAF(&r, 0x2A, 0)); xor8(&r, 0x7F); try expect(testAF(&r, 0x55, PF)); xor8(&r, 0xFF); try expect(testAF(&r, 0xAA, SF|PF)); } test "or8" { var r = makeRegs(); r[A] = 0x00; or8(&r, 0x00); try expect(testAF(&r, 0x00, ZF|PF)); or8(&r, 0x01); try expect(testAF(&r, 0x01, 0)); or8(&r, 0x02); try expect(testAF(&r, 0x03, PF)); or8(&r, 0x04); try expect(testAF(&r, 0x07, 0)); or8(&r, 0x08); try expect(testAF(&r, 0x0F, PF)); or8(&r, 0x10); try expect(testAF(&r, 0x1F, 0)); or8(&r, 0x20); try expect(testAF(&r, 0x3F, PF)); or8(&r, 0x40); try expect(testAF(&r, 0x7F, 0)); or8(&r, 0x80); try expect(testAF(&r, 0xFF, SF|PF)); } test "neg8" { var r = makeRegs(); r[A]=0x01; neg8(&r); try expect(testAF(&r, 0xFF, SF|HF|NF|CF)); r[A]=0x00; neg8(&r); try expect(testAF(&r, 0x00, ZF|NF)); r[A]=0x80; neg8(&r); try expect(testAF(&r, 0x80, SF|PF|NF|CF)); r[A]=0xC0; neg8(&r); try expect(testAF(&r, 0x40, NF|CF)); } test "inc8 dec8" { var r = makeRegs(); r[A] = 0x00; r[B] = 0xFF; r[C] = 0x0F; r[D] = 0x0E; r[E] = 0x7F; r[H] = 0x3E; r[L] = 0x23; r[A] = inc8(&r, r[A]); try expect(testRF(&r, A, 0x01, 0)); r[A] = dec8(&r, r[A]); try expect(testRF(&r, A, 0x00, ZF|NF)); r[B] = inc8(&r, r[B]); try expect(testRF(&r, B, 0x00, ZF|HF)); r[B] = dec8(&r, r[B]); try expect(testRF(&r, B, 0xFF, SF|HF|NF)); r[C] = inc8(&r, r[C]); try expect(testRF(&r, C, 0x10, HF)); r[C] = dec8(&r, r[C]); try expect(testRF(&r, C, 0x0F, HF|NF)); r[D] = inc8(&r, r[D]); try expect(testRF(&r, D, 0x0F, 0)); r[D] = dec8(&r, r[D]); try expect(testRF(&r, D, 0x0E, NF)); r[F] |= CF; r[E] = inc8(&r, r[E]); try expect(testRF(&r, E, 0x80, SF|HF|VF|CF)); r[E] = dec8(&r, r[E]); try expect(testRF(&r, E, 0x7F, HF|VF|NF|CF)); r[H] = inc8(&r, r[H]); try expect(testRF(&r, H, 0x3F, CF)); r[H] = dec8(&r, r[H]); try expect(testRF(&r, H, 0x3E, NF|CF)); r[L] = inc8(&r, r[L]); try expect(testRF(&r, L, 0x24, CF)); r[L] = dec8(&r, r[L]); try expect(testRF(&r, L, 0x23, NF|CF)); }
src/emu/CPU.zig
const upaya = @import("upaya"); const sokol = @import("sokol"); const Texture = upaya.Texture; const std = @import("std"); usingnamespace upaya.imgui; usingnamespace sokol; pub const FontStyle = enum { normal, bold, italic, bolditalic, zig, }; const FontMap = std.AutoHashMap(i32, *ImFont); //const baked_font_sizes = [_]i32{ 14, 20, 28, 36, 40, 45, 52, 60, 68, 72, 90, 96, 104, 128, 136, 144, 192, 300, 600 }; const baked_font_sizes = [_]i32{ 14, 16, // editor font 20, 22, 28, 32, 36, 40, 45, 52, 60, 68, 72, 90, 96, 104, 136, 144, 192, 300, }; const StyledFontMap = std.AutoHashMap(FontStyle, *FontMap); const fontdata_normal = @embedFile("../assets/Calibri Light.ttf"); const fontdata_bold = @embedFile("../assets/Calibri Regular.ttf"); // Calibri is the bold version of Calibri Light for us const fontdata_italic = @embedFile("../assets/Calibri Light Italic.ttf"); const fontdata_bolditalic = @embedFile("../assets/Calibri Italic.ttf"); // Calibri is the bold version of Calibri Light for us const fontdata_zig = @embedFile("../assets/press-start-2p.ttf"); var allFonts: StyledFontMap = StyledFontMap.init(std.heap.page_allocator); var my_fonts = FontMap.init(std.heap.page_allocator); var my_fonts_bold = FontMap.init(std.heap.page_allocator); var my_fonts_italic = FontMap.init(std.heap.page_allocator); var my_fonts_bolditalic = FontMap.init(std.heap.page_allocator); var my_fonts_zig = FontMap.init(std.heap.page_allocator); pub fn loadFonts() error{OutOfMemory}!void { var io = igGetIO(); ImFontAtlas_Clear(io.Fonts); _ = ImFontAtlas_AddFontDefault(io.Fonts, null); // init stuff try allFonts.put(.normal, &my_fonts); try allFonts.put(.bold, &my_fonts_bold); try allFonts.put(.italic, &my_fonts_italic); try allFonts.put(.bolditalic, &my_fonts_bolditalic); try allFonts.put(.zig, &my_fonts_zig); // actual font loading for (baked_font_sizes) |fsize, i| { try addFont(fsize); } commitFonts(); } pub fn addZigShowtimeFont() !void { const fsize = 52; var io = igGetIO(); var font_config = ImFontConfig_ImFontConfig(); font_config[0].MergeMode = false; font_config[0].PixelSnapH = true; font_config[0].OversampleH = 1; font_config[0].OversampleV = 1; font_config[0].FontDataOwnedByAtlas = false; var font = ImFontAtlas_AddFontFromMemoryTTF(io.Fonts, fontdata_zigshowtimefont, fontdata_normal.len, @intToFloat(f32, fsize), font_config, ImFontAtlas_GetGlyphRangesDefault(io.Fonts)); try my_fonts.put(fsize, font); return; } pub fn addFont(fsize: i32) !void { var io = igGetIO(); // set up the font ranges // The following spits out the range {32, 255} : // const default_font_ranges: [*:0]const ImWchar = ImFontAtlas_GetGlyphRangesDefault(io.Fonts); // std.log.debug("font ranges: {d}", .{default_font_ranges}); // bullets: 2022, 2023, 2043 const my_font_ranges = [_]ImWchar{ 32, 255, // default range 0x2022, 0x2023, // bullet and triangular bullet(triangular does not work with my calibri light) 0, // sentinel }; var font_config = ImFontConfig_ImFontConfig(); font_config[0].MergeMode = false; font_config[0].PixelSnapH = true; font_config[0].OversampleH = 1; font_config[0].OversampleV = 1; font_config[0].FontDataOwnedByAtlas = false; var font = ImFontAtlas_AddFontFromMemoryTTF(io.Fonts, fontdata_normal, fontdata_normal.len, @intToFloat(f32, fsize), font_config, &my_font_ranges); // see above: bullet range only needs to be applied to default font try my_fonts.put(fsize, font); var font_config_bold = ImFontConfig_ImFontConfig(); font_config_bold[0].MergeMode = false; font_config_bold[0].PixelSnapH = true; font_config_bold[0].OversampleH = 1; font_config_bold[0].OversampleV = 1; font_config_bold[0].FontDataOwnedByAtlas = false; var font_bold = ImFontAtlas_AddFontFromMemoryTTF(io.Fonts, fontdata_bold, fontdata_bold.len, @intToFloat(f32, fsize), font_config_bold, ImFontAtlas_GetGlyphRangesDefault(io.Fonts)); try my_fonts_bold.put(fsize, font_bold); var font_config_italic = ImFontConfig_ImFontConfig(); font_config_italic[0].MergeMode = false; font_config_italic[0].PixelSnapH = true; font_config_italic[0].OversampleH = 1; font_config_italic[0].OversampleV = 1; font_config_italic[0].FontDataOwnedByAtlas = false; var font_italic = ImFontAtlas_AddFontFromMemoryTTF(io.Fonts, fontdata_italic, fontdata_italic.len, @intToFloat(f32, fsize), font_config_italic, ImFontAtlas_GetGlyphRangesDefault(io.Fonts)); try my_fonts_italic.put(fsize, font_italic); var font_config_bolditalic = ImFontConfig_ImFontConfig(); font_config_bolditalic[0].MergeMode = false; font_config_bolditalic[0].PixelSnapH = true; font_config_bolditalic[0].OversampleH = 1; font_config_bolditalic[0].OversampleV = 1; font_config_bolditalic[0].FontDataOwnedByAtlas = false; var font_bolditalic = ImFontAtlas_AddFontFromMemoryTTF(io.Fonts, fontdata_bolditalic, fontdata_bolditalic.len, @intToFloat(f32, fsize), font_config_bolditalic, ImFontAtlas_GetGlyphRangesDefault(io.Fonts)); try my_fonts_bolditalic.put(fsize, font_bolditalic); // special case: our zig font std.log.debug("trying {d}", .{fsize}); if (fsize < 192) { var font_config_zig = ImFontConfig_ImFontConfig(); font_config_zig[0].MergeMode = false; font_config_zig[0].PixelSnapH = true; font_config_zig[0].OversampleH = 1; font_config_zig[0].OversampleV = 1; font_config_zig[0].FontDataOwnedByAtlas = false; var font_zig = ImFontAtlas_AddFontFromMemoryTTF(io.Fonts, fontdata_zig, fontdata_zig.len, @intToFloat(f32, fsize), font_config_zig, ImFontAtlas_GetGlyphRangesDefault(io.Fonts)); try my_fonts_zig.put(fsize, font_zig); } std.log.debug("OK {d}", .{fsize}); } pub fn commitFonts() void { var io = igGetIO(); var w: i32 = undefined; var h: i32 = undefined; var bytes_per_pixel: i32 = undefined; var pixels: [*c]u8 = undefined; std.log.debug("trying to get font atlas", .{}); ImFontAtlas_GetTexDataAsRGBA32(io.Fonts, &pixels, &w, &h, &bytes_per_pixel); std.log.debug("font atlas: {any}{d}x{d}", .{ true, w, h }); var tex = Texture.initWithData(pixels[0..@intCast(usize, w * h * bytes_per_pixel)], w, h, .nearest); std.log.debug("tex: {any} {d}x{d}", .{ tex, w, h }); ImFontAtlas_SetTexID(io.Fonts, tex.imTextureID()); std.log.debug("set: {any}", .{true}); } var last_scale: f32 = 0.0; var last_font: *ImFont = undefined; pub const bakedFontInfo = struct { font: *ImFont, size: i32 }; pub fn pushFontScaled(pixels: i32) void { const font_info = getFontScaled(pixels); // we assume we have a font, now scale it last_scale = font_info.font.*.Scale; const new_scale: f32 = @intToFloat(f32, pixels) / @intToFloat(f32, font_info.size); font_info.font.*.Scale = new_scale; igPushFont(font_info.font); last_font = font_info.font; } pub fn pushStyledFontScaled(pixels: i32, style: FontStyle) void { const font_info = getStyledFontScaled(pixels, style); // TURN THIS ON to see what font sizes you need // std.log.info("fontsize {}", .{pixels}); // we assume we have a font, now scale it last_scale = font_info.font.*.Scale; const new_scale: f32 = @intToFloat(f32, pixels) / @intToFloat(f32, font_info.size); font_info.font.*.Scale = new_scale; igPushFont(font_info.font); last_font = font_info.font; } pub fn notLikeThispushStyledFontScaled(pixels: i32, style: FontStyle) void { var font_info = getStyledFontScaled(pixels, style); if (font_info.size != pixels) { addFont(pixels) catch unreachable; commitFonts(); } font_info = getStyledFontScaled(pixels, style); igPushFont(font_info.font); last_font = font_info.font; } pub fn getFontScaled(pixels: i32) bakedFontInfo { var min_diff: i32 = 1000; var found_font_size: i32 = baked_font_sizes[0]; var font: *ImFont = my_fonts.get(baked_font_sizes[0]).?; // we don't ever down-scale. hence, default to minimum font size // the bloody hash map says it doesn't support field access when trying to iterate: // var it = my_fonts.iterator(); // for (it.next()) |item| { for (baked_font_sizes) |fsize, i| { var diff = pixels - fsize; // std.log.debug("diff={}, pixels={}, fsize={}", .{ diff, pixels, fsize }); // we only ever upscale, hence we look for positive differences only if (diff >= 0) { // we try to find the minimum difference if (diff < min_diff) { // std.log.debug(" diff={} is < than {}, so our new temp found_font_size={}", .{ diff, min_diff, fsize }); min_diff = diff; font = my_fonts.get(fsize).?; found_font_size = fsize; } } } const ret = bakedFontInfo{ .font = font, .size = found_font_size }; return ret; } pub fn getStyledFontScaled(pixels: i32, style: FontStyle) bakedFontInfo { var min_diff: i32 = 1000; var found_font_size: i32 = baked_font_sizes[0]; var the_map = allFonts.get(style).?; var font: *ImFont = the_map.get(baked_font_sizes[0]).?; // we don't ever down-scale. hence, default to minimum font size // the bloody hash map says it doesn't support field access when trying to iterate: // var it = my_fonts.iterator(); // for (it.next()) |item| { for (baked_font_sizes) |fsize, i| { if (style == .zig) { if (fsize >= 192) { continue; } } var diff = pixels - fsize; // std.log.debug("diff={}, pixels={}, fsize={}", .{ diff, pixels, fsize }); // we only ever upscale, hence we look for positive differences only if (diff >= 0) { // we try to find the minimum difference if (diff < min_diff) { // std.log.debug(" diff={} is < than {}, so our new temp found_font_size={}", .{ diff, min_diff, fsize }); min_diff = diff; font = the_map.get(fsize).?; found_font_size = fsize; } } } // if (style == .zig) { // if (found_font_size >= 192) { // found_font_size = 144; // TODO: hack // } // } const ret = bakedFontInfo{ .font = font, .size = found_font_size }; return ret; } pub fn getNearestFontSize(pixels: i32) i32 { var min_diff: i32 = 1000; var found_font_size: i32 = baked_font_sizes[0]; // the bloody hash map says it doesn't support field access when trying to iterate: // var it = my_fonts.iterator(); // for (it.next()) |item| { for (baked_font_sizes) |fsize, i| { var diff = pixels - fsize; // std.log.debug("diff={}, pixels={}, fsize={}", .{ diff, pixels, fsize }); // we only ever upscale, hence we look for positive differences only if (diff >= 0) { // we try to find the minimum difference if (diff < min_diff) { // std.log.debug(" diff={} is < than {}, so our new temp found_font_size={}", .{ diff, min_diff, fsize }); min_diff = diff; found_font_size = fsize; } } } // std.log.debug("--> Nearest font size of {} is {}", .{ pixels, found_font_size }); return found_font_size; } pub fn popFontScaled() void { igPopFont(); last_font.*.Scale = last_scale; }
src/myscalingfonts.zig
const std = @import("std"); const os = std.os; const Allocator = std.mem.Allocator; const assert = std.debug.assert; const log = std.log.scoped(.storage); const IO = @import("io.zig").IO; const is_darwin = std.Target.current.isDarwin(); const config = @import("config.zig"); const vsr = @import("vsr.zig"); pub const Storage = struct { /// See usage in Journal.write_sectors() for details. pub const synchronicity: enum { always_synchronous, always_asynchronous, } = .always_asynchronous; pub const Read = struct { completion: IO.Completion, callback: fn (read: *Storage.Read) void, /// The buffer to read into, re-sliced and re-assigned as we go, e.g. after partial reads. buffer: []u8, /// The position into the file descriptor from where we should read, also adjusted as we go. offset: u64, /// The maximum amount of bytes to read per syscall. We use this to subdivide troublesome /// reads into smaller reads to work around latent sector errors (LSEs). target_max: u64, /// Returns a target slice into `buffer` to read into, capped by `target_max`. /// If the previous read was a partial read of physical sectors (e.g. 512 bytes) less than /// our logical sector size (e.g. 4 KiB), so that the remainder of the buffer is no longer /// aligned to a logical sector, then we further cap the slice to get back onto a logical /// sector boundary. fn target(read: *Read) []u8 { // A worked example of a partial read that leaves the rest of the buffer unaligned: // This could happen for non-Advanced Format disks with a physical sector of 512 bytes. // We want to read 8 KiB: // buffer.ptr = 0 // buffer.len = 8192 // ... and then experience a partial read of only 512 bytes: // buffer.ptr = 512 // buffer.len = 7680 // We can now see that `buffer.len` is no longer a sector multiple of 4 KiB and further // that we have 3584 bytes left of the partial sector read. If we subtract this amount // from our logical sector size of 4 KiB we get 512 bytes, which is the alignment error // that we need to subtract from `target_max` to get back onto the boundary. var max = read.target_max; const partial_sector_read_remainder = read.buffer.len % config.sector_size; if (partial_sector_read_remainder != 0) { // TODO log.debug() because this is interesting, and to ensure fuzz test coverage. const partial_sector_read = config.sector_size - partial_sector_read_remainder; max -= partial_sector_read; } return read.buffer[0..std.math.min(read.buffer.len, max)]; } }; pub const Write = struct { completion: IO.Completion, callback: fn (write: *Storage.Write) void, buffer: []const u8, offset: u64, }; size: u64, fd: os.fd_t, io: *IO, pub fn init(size: u64, fd: os.fd_t, io: *IO) !Storage { return Storage{ .size = size, .fd = fd, .io = io, }; } pub fn deinit() void {} pub fn read_sectors( self: *Storage, callback: fn (read: *Storage.Read) void, read: *Storage.Read, buffer: []u8, offset: u64, ) void { self.assert_alignment(buffer, offset); read.* = .{ .completion = undefined, .callback = callback, .buffer = buffer, .offset = offset, .target_max = buffer.len, }; self.start_read(read, 0); } fn start_read(self: *Storage, read: *Storage.Read, bytes_read: usize) void { assert(bytes_read <= read.target().len); read.offset += bytes_read; read.buffer = read.buffer[bytes_read..]; const target = read.target(); if (target.len == 0) { read.callback(read); return; } self.assert_bounds(target, read.offset); self.io.read( *Storage, self, on_read, &read.completion, self.fd, target, read.offset, ); } fn on_read(self: *Storage, completion: *IO.Completion, result: IO.ReadError!usize) void { const read = @fieldParentPtr(Storage.Read, "completion", completion); const bytes_read = result catch |err| switch (err) { error.InputOutput => { // The disk was unable to read some sectors (an internal CRC or hardware failure): // We may also have already experienced a partial unaligned read, reading less // physical sectors than the logical sector size, so we cannot expect `target.len` // to be an exact logical sector multiple. const target = read.target(); if (target.len > config.sector_size) { // We tried to read more than a logical sector and failed. log.err("latent sector error: offset={}, subdividing read...", .{read.offset}); // Divide the buffer in half and try to read each half separately: // This creates a recursive binary search for the sector(s) causing the error. // This is considerably slower than doing a single bulk read and by now we might // also have experienced the disk's read retry timeout (in seconds). // TODO Our docs must instruct on why and how to reduce disk firmware timeouts. // These lines both implement ceiling division e.g. `((3 - 1) / 2) + 1 == 2` and // require that the numerator is always greater than zero: assert(target.len > 0); const target_sectors = @divFloor(target.len - 1, config.sector_size) + 1; assert(target_sectors > 0); read.target_max = (@divFloor(target_sectors - 1, 2) + 1) * config.sector_size; assert(read.target_max >= config.sector_size); // Pass 0 for `bytes_read`, we want to retry the read with smaller `target_max`: self.start_read(read, 0); return; } else { // We tried to read at (or less than) logical sector granularity and failed. log.err("latent sector error: offset={}, zeroing sector...", .{read.offset}); // Zero this logical sector which can't be read: // We will treat these EIO errors the same as a checksum failure. // TODO This could be an interesting avenue to explore further, whether // temporary or permanent EIO errors should be conflated with checksum failures. assert(target.len > 0); std.mem.set(u8, target, 0); // We could set `read.target_max` to `vsr.sector_ceil(read.buffer.len)` here // in order to restart our pseudo-binary search on the rest of the sectors to be // read, optimistically assuming that this is the last failing sector. // However, data corruption that causes EIO errors often has spacial locality. // Therefore, restarting our pseudo-binary search here might give us abysmal // performance in the (not uncommon) case of many successive failing sectors. self.start_read(read, target.len); return; } }, error.WouldBlock, error.NotOpenForReading, error.ConnectionResetByPeer, error.Alignment, error.IsDir, error.SystemResources, error.Unseekable, error.Unexpected, => { log.emerg( "impossible read: offset={} buffer.len={} error={s}", .{ read.offset, read.buffer.len, @errorName(err) }, ); @panic("impossible read"); }, }; if (bytes_read == 0) { // We tried to read more than there really is available to read. // In other words, we thought we could read beyond the end of the file descriptor. // This can happen if the data file inode `size` was truncated or corrupted. log.emerg( "short read: buffer.len={} offset={} bytes_read={}", .{ read.offset, read.buffer.len, bytes_read }, ); @panic("data file inode size was truncated or corrupted"); } // If our target was limited to a single sector, perhaps because of a latent sector error, // then increase `target_max` according to AIMD now that we have read successfully and // hopefully cleared the faulty zone. // We assume that `target_max` may exceed `read.buffer.len` at any time. if (read.target_max == config.sector_size) { // TODO Add log.debug because this is interesting. read.target_max += config.sector_size; } self.start_read(read, bytes_read); } pub fn write_sectors( self: *Storage, callback: fn (write: *Storage.Write) void, write: *Storage.Write, buffer: []const u8, offset: u64, ) void { self.assert_alignment(buffer, offset); write.* = .{ .completion = undefined, .callback = callback, .buffer = buffer, .offset = offset, }; self.start_write(write); } fn start_write(self: *Storage, write: *Storage.Write) void { self.assert_bounds(write.buffer, write.offset); self.io.write( *Storage, self, on_write, &write.completion, self.fd, write.buffer, write.offset, ); } fn on_write(self: *Storage, completion: *IO.Completion, result: IO.WriteError!usize) void { const write = @fieldParentPtr(Storage.Write, "completion", completion); const bytes_written = result catch |err| switch (err) { // We assume that the disk will attempt to reallocate a spare sector for any LSE. // TODO What if we receive a temporary EIO error because of a faulty cable? error.InputOutput => @panic("latent sector error: no spare sectors to reallocate"), // TODO: It seems like it might be possible for some filesystems to return ETIMEDOUT // here. Consider handling this without panicking. else => { log.emerg( "impossible write: offset={} buffer.len={} error={s}", .{ write.offset, write.buffer.len, @errorName(err) }, ); @panic("impossible write"); }, }; if (bytes_written == 0) { // This should never happen if the kernel and filesystem are well behaved. // However, block devices are known to exhibit this behavior in the wild. // TODO: Consider retrying with a timeout if this panic proves problematic, and be // careful to avoid logging in a busy loop. Perhaps a better approach might be to // return wrote = null here and let the protocol retry at a higher layer where there is // more context available to decide on how important this is or whether to cancel. @panic("write operation returned 0 bytes written"); } write.offset += bytes_written; write.buffer = write.buffer[bytes_written..]; if (write.buffer.len == 0) { write.callback(write); return; } self.start_write(write); } /// Ensures that the read or write is aligned correctly for Direct I/O. /// If this is not the case, then the underlying syscall will return EINVAL. /// We check this only at the start of a read or write because the physical sector size may be /// less than our logical sector size so that partial IOs then leave us no longer aligned. fn assert_alignment(self: *Storage, buffer: []const u8, offset: u64) void { assert(@ptrToInt(buffer.ptr) % config.sector_size == 0); assert(buffer.len % config.sector_size == 0); assert(offset % config.sector_size == 0); } /// Ensures that the read or write is within bounds and intends to read or write some bytes. fn assert_bounds(self: *Storage, buffer: []const u8, offset: u64) void { assert(buffer.len > 0); assert(offset + buffer.len <= self.size); } // Static helper functions to handle data file creation/opening/allocation: /// Opens or creates a journal file: /// - For reading and writing. /// - For Direct I/O (if possible in development mode, but required in production mode). /// - Obtains an advisory exclusive lock to the file descriptor. /// - Allocates the file contiguously on disk if this is supported by the file system. /// - Ensures that the file data (and file inode in the parent directory) is durable on disk. /// The caller is responsible for ensuring that the parent directory inode is durable. /// - Verifies that the file size matches the expected file size before returning. pub fn open( dir_fd: os.fd_t, relative_path: [:0]const u8, size: u64, must_create: bool, ) !os.fd_t { assert(relative_path.len > 0); assert(size >= config.sector_size); assert(size % config.sector_size == 0); // TODO Use O_EXCL when opening as a block device to obtain a mandatory exclusive lock. // This is much stronger than an advisory exclusive lock, and is required on some platforms. var flags: u32 = os.O_CLOEXEC | os.O_RDWR | os.O_DSYNC; var mode: os.mode_t = 0; // TODO Document this and investigate whether this is in fact correct to set here. if (@hasDecl(os, "O_LARGEFILE")) flags |= os.O_LARGEFILE; var direct_io_supported = false; if (config.direct_io) { direct_io_supported = try Storage.fs_supports_direct_io(dir_fd); if (direct_io_supported) { if (!is_darwin) flags |= os.O_DIRECT; } else if (config.deployment_environment == .development) { log.warn("file system does not support Direct I/O", .{}); } else { // We require Direct I/O for safety to handle fsync failure correctly, and therefore // panic in production if it is not supported. @panic("file system does not support Direct I/O"); } } if (must_create) { log.info("creating \"{s}\"...", .{relative_path}); flags |= os.O_CREAT; flags |= os.O_EXCL; mode = 0o666; } else { log.info("opening \"{s}\"...", .{relative_path}); } // This is critical as we rely on O_DSYNC for fsync() whenever we write to the file: assert((flags & os.O_DSYNC) > 0); // Be careful with openat(2): "If pathname is absolute, then dirfd is ignored." (man page) assert(!std.fs.path.isAbsolute(relative_path)); const fd = try os.openatZ(dir_fd, relative_path, flags, mode); // TODO Return a proper error message when the path exists or does not exist (init/start). errdefer os.close(fd); // TODO Check that the file is actually a file. // On darwin, use F_NOCACHE on direct_io to disable the page cache as O_DIRECT doesn't exit. if (is_darwin and config.direct_io and direct_io_supported) { _ = try os.fcntl(fd, os.F_NOCACHE, 1); } // Obtain an advisory exclusive lock that works only if all processes actually use flock(). // LOCK_NB means that we want to fail the lock without waiting if another process has it. os.flock(fd, os.LOCK_EX | os.LOCK_NB) catch |err| switch (err) { error.WouldBlock => @panic("another process holds the data file lock"), else => return err, }; // Ask the file system to allocate contiguous sectors for the file (if possible): // If the file system does not support `fallocate()`, then this could mean more seeks or a // panic if we run out of disk space (ENOSPC). if (must_create) try Storage.allocate(fd, size); // The best fsync strategy is always to fsync before reading because this prevents us from // making decisions on data that was never durably written by a previously crashed process. // We therefore always fsync when we open the path, also to wait for any pending O_DSYNC. // Thanks to <NAME> from FoundationDB for diving into our source and pointing this out. try os.fsync(fd); // We fsync the parent directory to ensure that the file inode is durably written. // The caller is responsible for the parent directory inode stored under the grandparent. // We always do this when opening because we don't know if this was done before crashing. try os.fsync(dir_fd); const stat = try os.fstat(fd); if (stat.size != size) @panic("data file inode size was truncated or corrupted"); return fd; } /// Allocates a file contiguously using fallocate() if supported. /// Alternatively, writes to the last sector so that at least the file size is correct. pub fn allocate(fd: os.fd_t, size: u64) !void { log.info("allocating {}...", .{std.fmt.fmtIntSizeBin(size)}); Storage.fallocate(fd, 0, 0, @intCast(i64, size)) catch |err| switch (err) { error.OperationNotSupported => { log.warn("file system does not support fallocate(), an ENOSPC will panic", .{}); log.notice("allocating by writing to the last sector of the file instead...", .{}); const sector_size = config.sector_size; const sector: [sector_size]u8 align(sector_size) = [_]u8{0} ** sector_size; // Handle partial writes where the physical sector is less than a logical sector: const offset = size - sector.len; var written: usize = 0; while (written < sector.len) { written += try os.pwrite(fd, sector[written..], offset + written); } }, else => return err, }; } fn fallocate(fd: i32, mode: i32, offset: i64, length: i64) !void { // https://stackoverflow.com/a/11497568 // https://api.kde.org/frameworks/kcoreaddons/html/posix__fallocate__mac_8h_source.html // http://hg.mozilla.org/mozilla-central/file/3d846420a907/xpcom/glue/FileUtils.cpp#l61 if (is_darwin) { const F_ALLOCATECONTIG = 0x2; // allocate contiguous space const F_ALLOCATEALL = 0x4; // allocate all or nothing const F_PEOFPOSMODE = 3; // use relative offset from the seek pos mode const F_VOLPOSMODE = 4; // use the specified volume offset const fstore_t = extern struct { fst_flags: c_uint, fst_posmode: c_int, fst_offset: os.off_t, fst_length: os.off_t, fst_bytesalloc: os.off_t, }; var store = fstore_t{ .fst_flags = F_ALLOCATECONTIG | F_ALLOCATEALL, .fst_posmode = F_PEOFPOSMODE, .fst_offset = 0, .fst_length = offset + length, .fst_bytesalloc = 0, }; // try to pre-allocate contiguous space and fall back to default non-continugous var res = os.system.fcntl(fd, os.F_PREALLOCATE, @ptrToInt(&store)); if (os.errno(res) != 0) { store.fst_flags = F_ALLOCATEALL; res = os.system.fcntl(fd, os.F_PREALLOCATE, @ptrToInt(&store)); } switch (os.errno(res)) { 0 => {}, os.EACCES => unreachable, // F_SETLK or F_SETSIZE of F_WRITEBOOTSTRAP os.EBADF => return error.FileDescriptorInvalid, os.EDEADLK => unreachable, // F_SETLKW os.EINTR => unreachable, // F_SETLKW os.EINVAL => return error.ArgumentsInvalid, // for F_PREALLOCATE (offset invalid) os.EMFILE => unreachable, // F_DUPFD or F_DUPED os.ENOLCK => unreachable, // F_SETLK or F_SETLKW os.EOVERFLOW => return error.FileTooBig, os.ESRCH => unreachable, // F_SETOWN os.EOPNOTSUPP => return error.OperationNotSupported, // not reported but need same error union else => |errno| return os.unexpectedErrno(errno), } // now actually perform the allocation return os.ftruncate(fd, @intCast(u64, length)) catch |err| switch (err) { error.AccessDenied => error.PermissionDenied, else => |e| e, }; } while (true) { const rc = os.linux.fallocate(fd, mode, offset, length); switch (os.linux.getErrno(rc)) { 0 => return, os.linux.EBADF => return error.FileDescriptorInvalid, os.linux.EFBIG => return error.FileTooBig, os.linux.EINTR => continue, os.linux.EINVAL => return error.ArgumentsInvalid, os.linux.EIO => return error.InputOutput, os.linux.ENODEV => return error.NoDevice, os.linux.ENOSPC => return error.NoSpaceLeft, os.linux.ENOSYS => return error.SystemOutdated, os.linux.EOPNOTSUPP => return error.OperationNotSupported, os.linux.EPERM => return error.PermissionDenied, os.linux.ESPIPE => return error.Unseekable, os.linux.ETXTBSY => return error.FileBusy, else => |errno| return os.unexpectedErrno(errno), } } } /// Detects whether the underlying file system for a given directory fd supports Direct I/O. /// Not all Linux file systems support `O_DIRECT`, e.g. a shared macOS volume. fn fs_supports_direct_io(dir_fd: std.os.fd_t) !bool { if (!@hasDecl(std.os, "O_DIRECT") and !is_darwin) return false; const path = "fs_supports_direct_io"; const dir = std.fs.Dir{ .fd = dir_fd }; const fd = try os.openatZ(dir_fd, path, os.O_CLOEXEC | os.O_CREAT | os.O_TRUNC, 0o666); defer os.close(fd); defer dir.deleteFile(path) catch {}; // F_NOCACHE on darwin is the most similar option to O_DIRECT on linux. if (is_darwin) { _ = os.fcntl(fd, os.F_NOCACHE, 1) catch return false; return true; } while (true) { const res = os.system.openat(dir_fd, path, os.O_CLOEXEC | os.O_RDONLY | os.O_DIRECT, 0); switch (os.linux.getErrno(res)) { 0 => { os.close(@intCast(os.fd_t, res)); return true; }, os.linux.EINTR => continue, os.linux.EINVAL => return false, else => |err| return os.unexpectedErrno(err), } } } };
src/storage.zig
const std = @import("std"); const stdx = @import("stdx"); const platform = @import("platform"); const vk = @import("vk"); const graphics = @import("../../graphics.zig"); pub fn createCommandPool(device: vk.VkDevice, q_family: platform.window_sdl.VkQueueFamilyPair) vk.VkCommandPool { const info = vk.VkCommandPoolCreateInfo{ .sType = vk.VK_STRUCTURE_TYPE_COMMAND_POOL_CREATE_INFO, .queueFamilyIndex = q_family.graphics_family.?, .pNext = null, // Allow commands to be reset. .flags = vk.VK_COMMAND_POOL_CREATE_RESET_COMMAND_BUFFER_BIT, }; var pool: vk.VkCommandPool = undefined; const res = vk.createCommandPool(device, &info, null, &pool); vk.assertSuccess(res); return pool; } pub fn createCommandBuffers(alloc: std.mem.Allocator, device: vk.VkDevice, pool: vk.VkCommandPool, num_bufs: u32) []vk.VkCommandBuffer { var ret = alloc.alloc(vk.VkCommandBuffer, num_bufs) catch stdx.fatal(); const alloc_info = vk.VkCommandBufferAllocateInfo{ .sType = vk.VK_STRUCTURE_TYPE_COMMAND_BUFFER_ALLOCATE_INFO, .commandPool = pool, .level = vk.VK_COMMAND_BUFFER_LEVEL_PRIMARY, .commandBufferCount = @intCast(u32, ret.len), .pNext = null, }; var res = vk.allocateCommandBuffers(device, &alloc_info, ret.ptr); vk.assertSuccess(res); return ret; } pub fn beginCommandBuffer(cmd_buf: vk.VkCommandBuffer) void { const begin_info = vk.VkCommandBufferBeginInfo{ .sType = vk.VK_STRUCTURE_TYPE_COMMAND_BUFFER_BEGIN_INFO, .flags = vk.VK_COMMAND_BUFFER_USAGE_SIMULTANEOUS_USE_BIT, .pNext = null, .pInheritanceInfo = null, }; const res = vk.beginCommandBuffer(cmd_buf, &begin_info); vk.assertSuccess(res); } pub fn beginRenderPass(cmd_buf: vk.VkCommandBuffer, pass: vk.VkRenderPass, framebuffer: vk.VkFramebuffer, extent: vk.VkExtent2D, clear_color: graphics.Color) void { const clear_vals = [_]vk.VkClearValue{ vk.VkClearValue{ .color = vk.VkClearColorValue{ .float32 = clear_color.toFloatArray() }, }, vk.VkClearValue{ .depthStencil = vk.VkClearDepthStencilValue{ .depth = 0, .stencil = 0, }, }, }; const begin_info = vk.VkRenderPassBeginInfo{ .sType = vk.VK_STRUCTURE_TYPE_RENDER_PASS_BEGIN_INFO, .renderPass = pass, .framebuffer = framebuffer, .renderArea = vk.VkRect2D{ .offset = vk.VkOffset2D{ .x = 0, .y = 0 }, .extent = extent, }, .clearValueCount = clear_vals.len, .pClearValues = &clear_vals, .pNext = null, }; vk.cmdBeginRenderPass(cmd_buf, &begin_info, vk.VK_SUBPASS_CONTENTS_INLINE); } pub fn endRenderPass(cmd_buf: vk.VkCommandBuffer) void { vk.cmdEndRenderPass(cmd_buf); } pub fn endCommandBuffer(cmd_buf: vk.VkCommandBuffer) void { const res = vk.endCommandBuffer(cmd_buf); vk.assertSuccess(res); }
graphics/src/backend/vk/command.zig
const std = @import("std"); const builtin = @import("builtin"); const str = []const u8; pub const Toolchain = @import("./toolchain.zig"); pub const Config = @import("./config.zig"); pub const Registry = @import("./registry.zig"); pub const Cli = @import("./registry.zig"); const io = std.io; const fs = std.fs; const path = fs.path; const event = std.event; const process = std.process; const Thread = std.Thread; const Target = std.Target; const Allocator = std.mem.Allocator; // NOTE: Not sure how necesssary.. can just call // all these stdlib functions at a whim pub const SystemCfg = struct { os: ?std.Target.Os.Tag = null, cpu_num: u32 = @as(u32, Thread.getCpuCount() catch 1), pub fn init() SystemCfg { return SystemCfg{}; } }; // NOTE: Primarily for setings intended to default to an // appropriate path/value/location, but all can be changed pub const EnvConfig = struct { const Self = @This(); pub const default_home = .{.a="$HOME/.idle/", .b="~/.idle/"}; pub const default_conf = .{.a="$HOME/.config/idle/", .b = "$HOME/.idle/conf/"}; pub const default_data = .{.a="$HOME/.local/share/idle/", .b="$HOME/.idle/data"}; pub const default_cache = .{.a="$HOME/.cache/idle/", .b="$HOME/.idle/cache/"}; pub const DirConfig = struct { data_dir: str = path.join(fs.getAppDataDir("idle") catch default_home.a), home_dir: str = EnvConfig.default_home.a, conf_dir: str = EnvConfig.default_conf.a, cache_dir: str = EnvConfig.default_cache.a, }; pub const ProjConfig = struct { project_rel_outp_dir: str = "out/", project_rel_src_dir: str = "src/", project_config_name: str = "idle", // -> ${src}/idle.spec project_main_file_name: str = "main", // -> ${src}/main.id project_lib_file_name: str = "lib", // -> ${src}/lib.id project_config_format: str = .json, project_default_vcs = .git, project_create_with_vcs = true, }; verbosity: u8 = "1", pub fn init(a: Allocator) EnvConfig { var eval = try std.process.getEnvVarOwned(a, key); if (!std.mem.eql(u8, val, eval)) eval = val else continue; } pub fn keys(a: Allocator) std.ArrayList(str) { var keyl = std.ArrayList(str).init(a); keyl.appendSlice(std.meta.fieldNames(Self)); return keyl; } pub fn get(a: Allocator, key: str) anyerror!?str { return if (try std.process.getEnvVarOwned(a, key)) |ev| ev else { const def = EnvConfig.default(); if (@hasField(def, key)) @field(def, key) else null; }; } pub fn default() Self { return Self{ .home_dir = path.join(fs.getAppDataDir("idle") catch "~/.idle/"), .verbosity = "1", }; } pub fn set(a: Allocator, key: str, val: str) !void { var eval = try std.process.getEnvVarOwned(a, key); if (!std.mem.eql(u8, val, eval)) eval = val else continue; } }; pub const CentralCfg = struct { const Self = @This(); pub const Active = union(enum) { root: CentralCfg, project: struct { config: CentralCfg, project_dir: std.fs.Dir, }, workspace: struct { config: CentralCfg, workspace_dir: std.fs.Dir, }, }; }; pub const RootConfig = struct { const Self = @This(); }; pub const LocalConfig = struct {}; pub const ParseError = error{ InvalidKey, InvalidKeyValue, }; pub const CfgError = process.GetEnvVarOwnedError || ParseErrorerror || error{ FileDoesNotExist, DirDoesNotExist, InvalidKey, }; pub const ProjectCfg = struct { name: str, author: str, edition: .v2022, fmt: Fmt.json, pub const Fmt = enum { json, toml, idspec, yaml, }; }; // NOTE: Ater integrating this into the main, // root src folder, present meta info like this // somewhere more appropriate pub const IdlaAbout = struct { edition: IdlaAbout.Edition.current, version: std.SemanticVersion = std.SemanticVersion.parse("0.1.0"), pub const Edition = enum { pub const current = @This().v2022; v2022, }; };
lib/im/src/config.zig
const std = @import("index.zig"); const builtin = @import("builtin"); const assert = std.debug.assert; const event = this; const mem = std.mem; const posix = std.os.posix; const AtomicRmwOp = builtin.AtomicRmwOp; const AtomicOrder = builtin.AtomicOrder; pub const TcpServer = struct { handleRequestFn: async<*mem.Allocator> fn (*TcpServer, *const std.net.Address, *const std.os.File) void, loop: *Loop, sockfd: i32, accept_coro: ?promise, listen_address: std.net.Address, waiting_for_emfile_node: PromiseNode, const PromiseNode = std.LinkedList(promise).Node; pub fn init(loop: *Loop) !TcpServer { const sockfd = try std.os.posixSocket(posix.AF_INET, posix.SOCK_STREAM | posix.SOCK_CLOEXEC | posix.SOCK_NONBLOCK, posix.PROTO_tcp); errdefer std.os.close(sockfd); // TODO can't initialize handler coroutine here because we need well defined copy elision return TcpServer{ .loop = loop, .sockfd = sockfd, .accept_coro = null, .handleRequestFn = undefined, .waiting_for_emfile_node = undefined, .listen_address = undefined, }; } pub fn listen(self: *TcpServer, address: *const std.net.Address, handleRequestFn: async<*mem.Allocator> fn (*TcpServer, *const std.net.Address, *const std.os.File) void) !void { self.handleRequestFn = handleRequestFn; try std.os.posixBind(self.sockfd, &address.os_addr); try std.os.posixListen(self.sockfd, posix.SOMAXCONN); self.listen_address = std.net.Address.initPosix(try std.os.posixGetSockName(self.sockfd)); self.accept_coro = try async<self.loop.allocator> TcpServer.handler(self); errdefer cancel self.accept_coro.?; try self.loop.addFd(self.sockfd, self.accept_coro.?); errdefer self.loop.removeFd(self.sockfd); } pub fn deinit(self: *TcpServer) void { self.loop.removeFd(self.sockfd); if (self.accept_coro) |accept_coro| cancel accept_coro; std.os.close(self.sockfd); } pub async fn handler(self: *TcpServer) void { while (true) { var accepted_addr: std.net.Address = undefined; if (std.os.posixAccept(self.sockfd, &accepted_addr.os_addr, posix.SOCK_NONBLOCK | posix.SOCK_CLOEXEC)) |accepted_fd| { var socket = std.os.File.openHandle(accepted_fd); _ = async<self.loop.allocator> self.handleRequestFn(self, accepted_addr, socket) catch |err| switch (err) { error.OutOfMemory => { socket.close(); continue; }, }; } else |err| switch (err) { error.WouldBlock => { suspend; // we will get resumed by epoll_wait in the event loop continue; }, error.ProcessFdQuotaExceeded => { errdefer std.os.emfile_promise_queue.remove(&self.waiting_for_emfile_node); suspend |p| { self.waiting_for_emfile_node = PromiseNode.init(p); std.os.emfile_promise_queue.append(&self.waiting_for_emfile_node); } continue; }, error.ConnectionAborted, error.FileDescriptorClosed => continue, error.PageFault => unreachable, error.InvalidSyscall => unreachable, error.FileDescriptorNotASocket => unreachable, error.OperationNotSupported => unreachable, error.SystemFdQuotaExceeded, error.SystemResources, error.ProtocolFailure, error.BlockedByFirewall, error.Unexpected => { @panic("TODO handle this error"); }, } } } }; pub const Loop = struct { allocator: *mem.Allocator, keep_running: bool, next_tick_queue: std.atomic.QueueMpsc(promise), os_data: OsData, const OsData = switch (builtin.os) { builtin.Os.linux => struct { epollfd: i32, }, else => struct {}, }; pub const NextTickNode = std.atomic.QueueMpsc(promise).Node; /// The allocator must be thread-safe because we use it for multiplexing /// coroutines onto kernel threads. pub fn init(allocator: *mem.Allocator) !Loop { var self = Loop{ .keep_running = true, .allocator = allocator, .os_data = undefined, .next_tick_queue = std.atomic.QueueMpsc(promise).init(), }; try self.initOsData(); errdefer self.deinitOsData(); return self; } /// must call stop before deinit pub fn deinit(self: *Loop) void { self.deinitOsData(); } const InitOsDataError = std.os.LinuxEpollCreateError; fn initOsData(self: *Loop) InitOsDataError!void { switch (builtin.os) { builtin.Os.linux => { self.os_data.epollfd = try std.os.linuxEpollCreate(std.os.linux.EPOLL_CLOEXEC); errdefer std.os.close(self.os_data.epollfd); }, else => {}, } } fn deinitOsData(self: *Loop) void { switch (builtin.os) { builtin.Os.linux => std.os.close(self.os_data.epollfd), else => {}, } } pub fn addFd(self: *Loop, fd: i32, prom: promise) !void { var ev = std.os.linux.epoll_event{ .events = std.os.linux.EPOLLIN | std.os.linux.EPOLLOUT | std.os.linux.EPOLLET, .data = std.os.linux.epoll_data{ .ptr = @ptrToInt(prom) }, }; try std.os.linuxEpollCtl(self.os_data.epollfd, std.os.linux.EPOLL_CTL_ADD, fd, &ev); } pub fn removeFd(self: *Loop, fd: i32) void { std.os.linuxEpollCtl(self.os_data.epollfd, std.os.linux.EPOLL_CTL_DEL, fd, undefined) catch {}; } async fn waitFd(self: *Loop, fd: i32) !void { defer self.removeFd(fd); suspend |p| { try self.addFd(fd, p); } } pub fn stop(self: *Loop) void { // TODO make atomic self.keep_running = false; // TODO activate an fd in the epoll set which should cancel all the promises } /// bring your own linked list node. this means it can't fail. pub fn onNextTick(self: *Loop, node: *NextTickNode) void { self.next_tick_queue.put(node); } pub fn run(self: *Loop) void { while (self.keep_running) { // TODO multiplex the next tick queue and the epoll event results onto a thread pool while (self.next_tick_queue.get()) |node| { resume node.data; } if (!self.keep_running) break; self.dispatchOsEvents(); } } fn dispatchOsEvents(self: *Loop) void { switch (builtin.os) { builtin.Os.linux => { var events: [16]std.os.linux.epoll_event = undefined; const count = std.os.linuxEpollWait(self.os_data.epollfd, events[0..], -1); for (events[0..count]) |ev| { const p = @intToPtr(promise, ev.data.ptr); resume p; } }, else => {}, } } }; /// many producer, many consumer, thread-safe, lock-free, runtime configurable buffer size /// when buffer is empty, consumers suspend and are resumed by producers /// when buffer is full, producers suspend and are resumed by consumers pub fn Channel(comptime T: type) type { return struct { loop: *Loop, getters: std.atomic.QueueMpsc(GetNode), putters: std.atomic.QueueMpsc(PutNode), get_count: usize, put_count: usize, dispatch_lock: u8, // TODO make this a bool need_dispatch: u8, // TODO make this a bool // simple fixed size ring buffer buffer_nodes: []T, buffer_index: usize, buffer_len: usize, const SelfChannel = this; const GetNode = struct { ptr: *T, tick_node: *Loop.NextTickNode, }; const PutNode = struct { data: T, tick_node: *Loop.NextTickNode, }; /// call destroy when done pub fn create(loop: *Loop, capacity: usize) !*SelfChannel { const buffer_nodes = try loop.allocator.alloc(T, capacity); errdefer loop.allocator.free(buffer_nodes); const self = try loop.allocator.create(SelfChannel{ .loop = loop, .buffer_len = 0, .buffer_nodes = buffer_nodes, .buffer_index = 0, .dispatch_lock = 0, .need_dispatch = 0, .getters = std.atomic.QueueMpsc(GetNode).init(), .putters = std.atomic.QueueMpsc(PutNode).init(), .get_count = 0, .put_count = 0, }); errdefer loop.allocator.destroy(self); return self; } /// must be called when all calls to put and get have suspended and no more calls occur pub fn destroy(self: *SelfChannel) void { while (self.getters.get()) |get_node| { cancel get_node.data.tick_node.data; } while (self.putters.get()) |put_node| { cancel put_node.data.tick_node.data; } self.loop.allocator.free(self.buffer_nodes); self.loop.allocator.destroy(self); } /// puts a data item in the channel. The promise completes when the value has been added to the /// buffer, or in the case of a zero size buffer, when the item has been retrieved by a getter. pub async fn put(self: *SelfChannel, data: T) void { // TODO should be able to group memory allocation failure before first suspend point // so that the async invocation catches it var dispatch_tick_node_ptr: *Loop.NextTickNode = undefined; _ = async self.dispatch(&dispatch_tick_node_ptr) catch unreachable; suspend |handle| { var my_tick_node = Loop.NextTickNode{ .next = undefined, .data = handle, }; var queue_node = std.atomic.QueueMpsc(PutNode).Node{ .data = PutNode{ .tick_node = &my_tick_node, .data = data, }, .next = undefined, }; self.putters.put(&queue_node); _ = @atomicRmw(usize, &self.put_count, AtomicRmwOp.Add, 1, AtomicOrder.SeqCst); self.loop.onNextTick(dispatch_tick_node_ptr); } } /// await this function to get an item from the channel. If the buffer is empty, the promise will /// complete when the next item is put in the channel. pub async fn get(self: *SelfChannel) T { // TODO should be able to group memory allocation failure before first suspend point // so that the async invocation catches it var dispatch_tick_node_ptr: *Loop.NextTickNode = undefined; _ = async self.dispatch(&dispatch_tick_node_ptr) catch unreachable; // TODO integrate this function with named return values // so we can get rid of this extra result copy var result: T = undefined; var debug_handle: usize = undefined; suspend |handle| { debug_handle = @ptrToInt(handle); var my_tick_node = Loop.NextTickNode{ .next = undefined, .data = handle, }; var queue_node = std.atomic.QueueMpsc(GetNode).Node{ .data = GetNode{ .ptr = &result, .tick_node = &my_tick_node, }, .next = undefined, }; self.getters.put(&queue_node); _ = @atomicRmw(usize, &self.get_count, AtomicRmwOp.Add, 1, AtomicOrder.SeqCst); self.loop.onNextTick(dispatch_tick_node_ptr); } return result; } async fn dispatch(self: *SelfChannel, tick_node_ptr: **Loop.NextTickNode) void { // resumed by onNextTick suspend |handle| { var tick_node = Loop.NextTickNode{ .data = handle, .next = undefined, }; tick_node_ptr.* = &tick_node; } // set the "need dispatch" flag _ = @atomicRmw(u8, &self.need_dispatch, AtomicRmwOp.Xchg, 1, AtomicOrder.SeqCst); lock: while (true) { // set the lock flag const prev_lock = @atomicRmw(u8, &self.dispatch_lock, AtomicRmwOp.Xchg, 1, AtomicOrder.SeqCst); if (prev_lock != 0) return; // clear the need_dispatch flag since we're about to do it _ = @atomicRmw(u8, &self.need_dispatch, AtomicRmwOp.Xchg, 0, AtomicOrder.SeqCst); while (true) { one_dispatch: { // later we correct these extra subtractions var get_count = @atomicRmw(usize, &self.get_count, AtomicRmwOp.Sub, 1, AtomicOrder.SeqCst); var put_count = @atomicRmw(usize, &self.put_count, AtomicRmwOp.Sub, 1, AtomicOrder.SeqCst); // transfer self.buffer to self.getters while (self.buffer_len != 0) { if (get_count == 0) break :one_dispatch; const get_node = &self.getters.get().?.data; get_node.ptr.* = self.buffer_nodes[self.buffer_index -% self.buffer_len]; self.loop.onNextTick(get_node.tick_node); self.buffer_len -= 1; get_count = @atomicRmw(usize, &self.get_count, AtomicRmwOp.Sub, 1, AtomicOrder.SeqCst); } // direct transfer self.putters to self.getters while (get_count != 0 and put_count != 0) { const get_node = &self.getters.get().?.data; const put_node = &self.putters.get().?.data; get_node.ptr.* = put_node.data; self.loop.onNextTick(get_node.tick_node); self.loop.onNextTick(put_node.tick_node); get_count = @atomicRmw(usize, &self.get_count, AtomicRmwOp.Sub, 1, AtomicOrder.SeqCst); put_count = @atomicRmw(usize, &self.put_count, AtomicRmwOp.Sub, 1, AtomicOrder.SeqCst); } // transfer self.putters to self.buffer while (self.buffer_len != self.buffer_nodes.len and put_count != 0) { const put_node = &self.putters.get().?.data; self.buffer_nodes[self.buffer_index] = put_node.data; self.loop.onNextTick(put_node.tick_node); self.buffer_index +%= 1; self.buffer_len += 1; put_count = @atomicRmw(usize, &self.put_count, AtomicRmwOp.Sub, 1, AtomicOrder.SeqCst); } } // undo the extra subtractions _ = @atomicRmw(usize, &self.get_count, AtomicRmwOp.Add, 1, AtomicOrder.SeqCst); _ = @atomicRmw(usize, &self.put_count, AtomicRmwOp.Add, 1, AtomicOrder.SeqCst); // clear need-dispatch flag const need_dispatch = @atomicRmw(u8, &self.need_dispatch, AtomicRmwOp.Xchg, 0, AtomicOrder.SeqCst); if (need_dispatch != 0) continue; const my_lock = @atomicRmw(u8, &self.dispatch_lock, AtomicRmwOp.Xchg, 0, AtomicOrder.SeqCst); assert(my_lock != 0); // we have to check again now that we unlocked if (@atomicLoad(u8, &self.need_dispatch, AtomicOrder.SeqCst) != 0) continue :lock; return; } } } }; } pub async fn connect(loop: *Loop, _address: *const std.net.Address) !std.os.File { var address = _address.*; // TODO https://github.com/ziglang/zig/issues/733 const sockfd = try std.os.posixSocket(posix.AF_INET, posix.SOCK_STREAM | posix.SOCK_CLOEXEC | posix.SOCK_NONBLOCK, posix.PROTO_tcp); errdefer std.os.close(sockfd); try std.os.posixConnectAsync(sockfd, &address.os_addr); try await try async loop.waitFd(sockfd); try std.os.posixGetSockOptConnectError(sockfd); return std.os.File.openHandle(sockfd); } test "listen on a port, send bytes, receive bytes" { if (builtin.os != builtin.Os.linux) { // TODO build abstractions for other operating systems return; } const MyServer = struct { tcp_server: TcpServer, const Self = this; async<*mem.Allocator> fn handler(tcp_server: *TcpServer, _addr: *const std.net.Address, _socket: *const std.os.File) void { const self = @fieldParentPtr(Self, "tcp_server", tcp_server); var socket = _socket.*; // TODO https://github.com/ziglang/zig/issues/733 defer socket.close(); const next_handler = async errorableHandler(self, _addr, socket) catch |err| switch (err) { error.OutOfMemory => @panic("unable to handle connection: out of memory"), }; (await next_handler) catch |err| { std.debug.panic("unable to handle connection: {}\n", err); }; suspend |p| { cancel p; } } async fn errorableHandler(self: *Self, _addr: *const std.net.Address, _socket: *const std.os.File) !void { const addr = _addr.*; // TODO https://github.com/ziglang/zig/issues/733 var socket = _socket.*; // TODO https://github.com/ziglang/zig/issues/733 var adapter = std.io.FileOutStream.init(&socket); var stream = &adapter.stream; try stream.print("hello from server\n"); } }; const ip4addr = std.net.parseIp4("127.0.0.1") catch unreachable; const addr = std.net.Address.initIp4(ip4addr, 0); var loop = try Loop.init(std.debug.global_allocator); var server = MyServer{ .tcp_server = try TcpServer.init(&loop) }; defer server.tcp_server.deinit(); try server.tcp_server.listen(addr, MyServer.handler); const p = try async<std.debug.global_allocator> doAsyncTest(&loop, server.tcp_server.listen_address); defer cancel p; loop.run(); } async fn doAsyncTest(loop: *Loop, address: *const std.net.Address) void { errdefer @panic("test failure"); var socket_file = try await try async event.connect(loop, address); defer socket_file.close(); var buf: [512]u8 = undefined; const amt_read = try socket_file.read(buf[0..]); const msg = buf[0..amt_read]; assert(mem.eql(u8, msg, "hello from server\n")); loop.stop(); } test "std.event.Channel" { var da = std.heap.DirectAllocator.init(); defer da.deinit(); const allocator = &da.allocator; var loop = try Loop.init(allocator); defer loop.deinit(); const channel = try Channel(i32).create(&loop, 0); defer channel.destroy(); const handle = try async<allocator> testChannelGetter(&loop, channel); defer cancel handle; const putter = try async<allocator> testChannelPutter(channel); defer cancel putter; loop.run(); } async fn testChannelGetter(loop: *Loop, channel: *Channel(i32)) void { errdefer @panic("test failed"); const value1_promise = try async channel.get(); const value1 = await value1_promise; assert(value1 == 1234); const value2_promise = try async channel.get(); const value2 = await value2_promise; assert(value2 == 4567); loop.stop(); } async fn testChannelPutter(channel: *Channel(i32)) void { await (async channel.put(1234) catch @panic("out of memory")); await (async channel.put(4567) catch @panic("out of memory")); }
std/event.zig
const expect = std.testing.expect; const expectEqualSlices = std.testing.expectEqualSlices; const expectError = std.testing.expectError; const std = @import("std"); const mqtt_string = @import("../../mqtt_string.zig"); const Allocator = std.mem.Allocator; const FixedHeader = Packet.FixedHeader; const Packet = @import("../packet.zig").Packet; const QoS = @import("../../qos.zig").QoS; pub const Will = struct { topic: []const u8, message: []const u8, retain: bool, qos: QoS, }; pub const Connect = struct { clean_session: bool, keepalive: u16, client_id: []const u8, will: ?Will = null, username: ?[]const u8 = null, password: ?[]const u8 = null, const Flags = packed struct { _reserved: u1 = 0, clean_session: bool, will_flag: bool, will_qos: u2, will_retain: bool, password_flag: bool, username_flag: bool, }; pub const ParseError = error{ InvalidProtocolName, InvalidProtocolLevel, InvalidWillQoS, }; pub fn parse(fixed_header: FixedHeader, allocator: *Allocator, inner_reader: anytype) !Connect { const reader = std.io.limitedReader(inner_reader, fixed_header.remaining_length).reader(); const protocol_name_length = try reader.readIntBig(u16); var protocol_name: [4]u8 = undefined; _ = try reader.read(protocol_name[0..4]); if (protocol_name_length != 4 or !std.mem.eql(u8, protocol_name[0..4], "MQTT")) { return error.InvalidProtocolName; } const protocol_level = try reader.readByte(); if (protocol_level != 4) { return error.InvalidProtocolLevel; } const flags_byte = try reader.readByte(); const flags = @bitCast(Flags, flags_byte); if (flags.will_qos > 2) { return error.InvalidWillQoS; } const clean_session = flags.clean_session; const keepalive = try reader.readIntBig(u16); const client_id = try mqtt_string.read(allocator, reader); errdefer allocator.free(client_id); var will: ?Will = null; if (flags.will_flag) { var will_topic = try mqtt_string.read(allocator, reader); errdefer allocator.free(will_topic); var will_message = try mqtt_string.read(allocator, reader); errdefer allocator.free(will_message); const retain = flags.will_retain; if (flags.will_qos > 2) { return error.InvalidWillQoS; } const qos = @intToEnum(QoS, flags.will_qos); will = Will{ .topic = will_topic, .message = will_message, .retain = retain, .qos = qos, }; } errdefer { if (will) |w| { allocator.free(w.topic); allocator.free(w.message); } } var username: ?[]u8 = null; if (flags.username_flag) { username = try mqtt_string.read(allocator, reader); } errdefer { if (username) |u| { allocator.free(u); } } var password: ?[]u8 = null; if (flags.password_flag) { password = try mqtt_string.read(allocator, reader); } errdefer { if (password) |p| { allocator.free(p); } } return Connect{ .clean_session = clean_session, .keepalive = keepalive, .client_id = client_id, .will = will, .username = username, .password = password, }; } pub fn serializedLength(self: Connect) u32 { // Fixed initial fields: protocol name, protocol level, flags and keepalive var length: u32 = comptime mqtt_string.serializedLength("MQTT") + @sizeOf(u8) + @sizeOf(Flags) + @sizeOf(@TypeOf(self.keepalive)); length += mqtt_string.serializedLength(self.client_id); if (self.will) |will| { length += mqtt_string.serializedLength(will.message); length += mqtt_string.serializedLength(will.topic); // Will retain and qos go in flags, no space needed } if (self.username) |username| { length += mqtt_string.serializedLength(username); } if (self.password) |password| { length += mqtt_string.serializedLength(password); } return length; } pub fn serialize(self: Connect, writer: anytype) !void { try mqtt_string.write("MQTT", writer); // Protocol version try writer.writeByte(4); // Extract info from Will, if there's one var will_message: ?[]const u8 = null; var will_topic: ?[]const u8 = null; var will_qos = QoS.qos0; var will_retain = false; if (self.will) |will| { will_topic = will.topic; will_message = will.message; will_qos = will.qos; will_retain = will.retain; } const flags = Flags{ .clean_session = self.clean_session, .will_flag = self.will != null, .will_qos = @enumToInt(will_qos), .will_retain = will_retain, .password_flag = self.password != null, .username_flag = self.username != null, }; const flags_byte = @bitCast(u8, flags); try writer.writeByte(flags_byte); try writer.writeIntBig(u16, self.keepalive); try mqtt_string.write(self.client_id, writer); if (will_topic) |wt| { try mqtt_string.write(wt, writer); } if (will_message) |wm| { try mqtt_string.write(wm, writer); } if (self.username) |username| { try mqtt_string.write(username, writer); } if (self.password) |password| { try mqtt_string.write(password, writer); } } pub fn fixedHeaderFlags(self: Connect) u4 { return 0b0000; } pub fn deinit(self: *Connect, allocator: *Allocator) void { allocator.free(self.client_id); if (self.will) |will| { allocator.free(will.topic); allocator.free(will.message); } if (self.username) |username| { allocator.free(username); } if (self.password) |password| { allocator.free(password); } } }; test "minimal Connect payload parsing" { const allocator = std.testing.allocator; const buffer = // Protocol name length "\x00\x04" ++ // Protocol name "MQTT" ++ // Protocol version, 4 == 3.1.1 "\x04" ++ // Flags, empty "\x00" ++ // Keepalive, 60 "\x00\x3c" ++ // Client id length, 0 "\x00\x00"; const stream = std.io.fixedBufferStream(buffer).reader(); const PacketType = @import("../packet.zig").PacketType; const fixed_header = FixedHeader{ .packet_type = PacketType.connect, .flags = 0, .remaining_length = @intCast(u32, buffer.len), }; var connect = try Connect.parse(fixed_header, allocator, stream); defer connect.deinit(allocator); try expect(connect.clean_session == false); try expect(connect.keepalive == 60); try expect(connect.client_id.len == 0); try expect(connect.will == null); try expect(connect.username == null); try expect(connect.password == null); } test "full Connect payload parsing" { const allocator = std.testing.allocator; const buffer = // Protocol name length "\x00\x04" ++ // Protocol name "MQTT" ++ // Protocol version, 4 == 3.1.1 "\x04" ++ // Flags all set, will QoS 2, reserved bit 0 [_]u8{0b11110110} ++ // Keepalive, 60 "\x00\x3c" ++ // Client id length, 6 "\x00\x06" ++ // Client id "foobar" ++ // Will topic length, 7 "\x00\x07" ++ // Will topic "my/will" ++ // Will message length, 10 "\x00\x0a" ++ // Will message "kbyethanks" ++ // Username length, 4 "\x00\x04" ++ // Username "user" ++ // Password length, 9 "\x00\x09" ++ // Password "<PASSWORD>"; const stream = std.io.fixedBufferStream(buffer).reader(); const PacketType = @import("../packet.zig").PacketType; const fixed_header = FixedHeader{ .packet_type = PacketType.connect, .flags = 0, .remaining_length = @intCast(u32, buffer.len), }; var connect = try Connect.parse(fixed_header, allocator, stream); defer connect.deinit(allocator); try expect(connect.clean_session == true); try expect(connect.keepalive == 60); try expect(std.mem.eql(u8, connect.client_id, "foobar")); try expect(std.mem.eql(u8, connect.username.?, "user")); try expect(std.mem.eql(u8, connect.password.?, "<PASSWORD>")); const will = connect.will.?; try expect(will.retain == true); try expect(std.mem.eql(u8, will.topic, "my/will")); try expect(std.mem.eql(u8, will.message, "kbyethanks")); try expect(will.qos == QoS.qos2); } test "FixedHeader indicating a smaller remaining length makes parsing fail" { const allocator = std.testing.allocator; const buffer = // Protocol name length "\x00\x04" ++ // Protocol name "MQTT" ++ // Protocol version, 4 == 3.1.1 "\x04" ++ // Flags all set, will QoS 2, reserved bit 0 [_]u8{0b11110110} ++ // Keepalive, 60 "\x00\x3c" ++ // Client id length, 6 "\x00\x06" ++ // Client id "foobar" ++ // Will topic length, 7 "\x00\x07" ++ // Will topic "my/will" ++ // Will message length, 10 "\x00\x0a" ++ // Will message "kbyethanks" ++ // Username length, 4 "\x00\x04" ++ // Username "user" ++ // Password length, 9 "\x00\x09" ++ // Password "<PASSWORD>"; const stream = std.io.fixedBufferStream(buffer).reader(); const PacketType = @import("../packet.zig").PacketType; const fixed_header = FixedHeader{ .packet_type = PacketType.connect, .flags = 0, .remaining_length = 12, }; const result = Connect.parse(fixed_header, allocator, stream); try expectError(error.EndOfStream, result); } test "invalid protocol fails" { const allocator = std.testing.allocator; const buffer = // Protocol name length "\x00\x04" ++ // Wrong protocol name "WOOT"; const stream = std.io.fixedBufferStream(buffer).reader(); const PacketType = @import("../packet.zig").PacketType; const fixed_header = FixedHeader{ .packet_type = PacketType.connect, .flags = 0, .remaining_length = @intCast(u32, buffer.len), }; const result = Connect.parse(fixed_header, allocator, stream); try expectError(error.InvalidProtocolName, result); } test "invalid protocol version fails" { const allocator = std.testing.allocator; const buffer = // Protocol name length "\x00\x04" ++ // Protocol name "MQTT" ++ // Protocol version, 42 "\x2a"; const stream = std.io.fixedBufferStream(buffer).reader(); const PacketType = @import("../packet.zig").PacketType; const fixed_header = FixedHeader{ .packet_type = PacketType.connect, .flags = 0, .remaining_length = @intCast(u32, buffer.len), }; const result = Connect.parse(fixed_header, allocator, stream); try expectError(error.InvalidProtocolLevel, result); } test "invalid will QoS fails" { const allocator = std.testing.allocator; const buffer = // Protocol name length "\x00\x04" ++ // Protocol name "MQTT" ++ // Protocol version, 4 == 3.1.1 "\x04" ++ // Flags all set, will QoS 3 (invalid), reserved bit 0 [_]u8{0b11111110}; const stream = std.io.fixedBufferStream(buffer).reader(); const PacketType = @import("../packet.zig").PacketType; const fixed_header = FixedHeader{ .packet_type = PacketType.connect, .flags = 0, .remaining_length = @intCast(u32, buffer.len), }; const result = Connect.parse(fixed_header, allocator, stream); try expectError(error.InvalidWillQoS, result); } test "serialize/parse roundtrip" { const connect = Connect{ .clean_session = true, .keepalive = 60, .client_id = "", .will = Will{ .topic = "foo/bar", .message = "bye", .qos = QoS.qos1, .retain = false, }, .username = "user", .password = "<PASSWORD>", }; var buffer = [_]u8{0} ** 100; var stream = std.io.fixedBufferStream(&buffer); var writer = stream.writer(); try connect.serialize(writer); const written = try stream.getPos(); stream.reset(); const reader = stream.reader(); const PacketType = @import("../packet.zig").PacketType; const fixed_header = FixedHeader{ .packet_type = PacketType.connect, .flags = 0, .remaining_length = @intCast(u32, written), }; const allocator = std.testing.allocator; var deser_connect = try Connect.parse(fixed_header, allocator, reader); defer deser_connect.deinit(allocator); try expect(connect.clean_session == deser_connect.clean_session); try expect(connect.keepalive == deser_connect.keepalive); try expectEqualSlices(u8, connect.client_id, deser_connect.client_id); try expectEqualSlices(u8, connect.will.?.topic, deser_connect.will.?.topic); try expectEqualSlices(u8, connect.will.?.message, deser_connect.will.?.message); try expect(connect.will.?.qos == deser_connect.will.?.qos); try expect(connect.will.?.retain == deser_connect.will.?.retain); try expectEqualSlices(u8, connect.username.?, deser_connect.username.?); try expectEqualSlices(u8, connect.password.?, deser_connect.password.?); }
src/mqtt4/packet/connect.zig
const bench = @import("bench"); const builtin = @import("builtin"); const std = @import("std"); const heap = std.heap; const mem = std.mem; const debug = std.debug; const testing = std.testing; pub const GcAllocator = struct { const PointerList = std.ArrayList(Pointer); base: mem.Allocator, start: [*]const u8, ptrs: PointerList, const Flags = packed struct { checked: bool, marked: bool, const zero = Flags{ .checked = false, .marked = false, }; }; const Pointer = struct { flags: Flags, memory: []u8, }; pub inline fn init(child_alloc: *mem.Allocator) GcAllocator { return GcAllocator{ .base = mem.Allocator{ .reallocFn = realloc, .shrinkFn = shrink, }, .start = @intToPtr([*]const u8, @frameAddress()), .ptrs = PointerList.init(child_alloc), }; } pub fn deinit(gc: *GcAllocator) void { const child_alloc = gc.childAllocator(); for (gc.ptrs.toSlice()) |ptr| { child_alloc.free(ptr.memory); } gc.ptrs.deinit(); gc.* = undefined; } pub fn collect(gc: *GcAllocator) void { @noInlineCall(collectNoInline, gc); } pub fn collectFrame(gc: *GcAllocator, frame: []const u8) void { gc.mark(frame); gc.sweep(); } pub fn allocator(gc: *GcAllocator) *mem.Allocator { return &gc.base; } fn collectNoInline(gc: *GcAllocator) void { const frame = blk: { const end = @intToPtr([*]const u8, @frameAddress()); const i_start = @ptrToInt(gc.start); const i_end = @ptrToInt(end); if (i_start < i_end) break :blk gc.start[0 .. i_end - i_start]; break :blk end[0 .. i_start - i_end]; }; gc.collectFrame(frame); } fn mark(gc: *GcAllocator, frame: []const u8) void { const ptr_size = @sizeOf(*u8); for ([_]void{{}} ** ptr_size) |_, i| { if (frame.len <= i) break; const frame2 = frame[i..]; const len = (frame2.len / ptr_size) * ptr_size; for (@bytesToSlice([*]u8, frame2[0..len])) |frame_ptr| { const ptr = gc.findPtr(frame_ptr) orelse continue; if (ptr.flags.checked) continue; ptr.flags.marked = true; ptr.flags.checked = true; gc.mark(ptr.memory); } } } fn sweep(gc: *GcAllocator) void { const child_alloc = gc.childAllocator(); const ptrs = gc.ptrs.toSlice(); var i: usize = 0; while (i < gc.ptrs.len) { const ptr = &ptrs[i]; if (ptr.flags.marked) { ptr.flags = Flags.zero; i += 1; continue; } gc.freePtr(ptr); } } fn findPtr(gc: *GcAllocator, to_find_ptr: var) ?*Pointer { comptime debug.assert(@typeInfo(@typeOf(to_find_ptr)) == builtin.TypeId.Pointer); for (gc.ptrs.toSlice()) |*ptr| { const ptr_start = @ptrToInt(ptr.memory.ptr); const ptr_end = ptr_start + ptr.memory.len; if (ptr_start <= @ptrToInt(to_find_ptr) and @ptrToInt(to_find_ptr) < ptr_end) return ptr; } return null; } fn freePtr(gc: *GcAllocator, ptr: *Pointer) void { const child_alloc = gc.childAllocator(); child_alloc.free(ptr.memory); // Swap the just freed pointer with the last pointer in the list. ptr.* = undefined; ptr.* = gc.ptrs.popOrNull() orelse undefined; } fn childAllocator(gc: *GcAllocator) *mem.Allocator { return gc.ptrs.allocator; } fn alloc(base: *mem.Allocator, n: usize, alignment: u29) ![]u8 { const gc = @fieldParentPtr(GcAllocator, "base", base); const child_alloc = gc.childAllocator(); const memory = try child_alloc.reallocFn(child_alloc, ([*]u8)(undefined)[0..0], 0, n, alignment); try gc.ptrs.append(Pointer{ .flags = Flags.zero, .memory = memory, }); return memory; } fn free(base: *mem.Allocator, bytes: []u8) void { const gc = @fieldParentPtr(GcAllocator, "base", base); const child_alloc = gc.childAllocator(); const ptr = gc.findPtr(bytes.ptr) orelse @panic("Freeing memory not allocated by garbage collector!"); gc.freePtr(ptr); } fn realloc(base: *mem.Allocator, old_mem: []u8, old_alignment: u29, new_size: usize, alignment: u29) mem.Allocator.Error![]u8 { if (new_size == 0) { free(base, old_mem); return ([*]u8)(undefined)[0..0]; } else if (new_size <= old_mem.len) { return old_mem[0..new_size]; } else { const result = try alloc(base, new_size, alignment); mem.copy(u8, result, old_mem); return result; } } fn shrink(base: *mem.Allocator, old_mem: []u8, old_alignment: u29, new_size: usize, alignment: u29) []u8 { if (new_size == 0) { free(base, old_mem); return ([*]u8)(undefined)[0..0]; } else if (new_size <= old_mem.len) { return old_mem[0..new_size]; } else { unreachable; } } }; const Leaker = struct { l: *Leaker, }; var test_buf: [1024 * 1024]u8 = undefined; test "gc.collect: No leaks" { var fba = heap.FixedBufferAllocator.init(test_buf[0..]); var gc = GcAllocator.init(&fba.allocator); defer gc.deinit(); const allocator = gc.allocator(); var a = try allocator.create(Leaker); a.* = Leaker{ .l = try allocator.create(Leaker) }; a.l.l = a; gc.collect(); testing.expect(gc.findPtr(a) != null); testing.expect(gc.findPtr(a.l) != null); testing.expectEqual(usize(2), gc.ptrs.len); } fn leak(allocator: *mem.Allocator) !void { var a = try allocator.create(Leaker); a.* = Leaker{ .l = try allocator.create(Leaker) }; a.l.l = a; } test "gc.collect: Leaks" { var fba = heap.FixedBufferAllocator.init(test_buf[0..]); var gc = GcAllocator.init(&fba.allocator); defer gc.deinit(); const allocator = gc.allocator(); var a = try allocator.create(Leaker); a.* = Leaker{ .l = try allocator.create(Leaker) }; a.l.l = a; try @noInlineCall(leak, allocator); gc.collect(); testing.expect(gc.findPtr(a) != null); testing.expect(gc.findPtr(a.l) != null); testing.expectEqual(usize(2), gc.ptrs.len); } test "gc.free" { var fba = heap.FixedBufferAllocator.init(test_buf[0..]); var gc = GcAllocator.init(&fba.allocator); defer gc.deinit(); const allocator = gc.allocator(); var a = try allocator.create(Leaker); var b = try allocator.create(Leaker); allocator.destroy(b); testing.expect(gc.findPtr(a) != null); testing.expectEqual(usize(1), gc.ptrs.len); } test "gc.benchmark" { try bench.benchmark(struct { const Arg = struct { num: usize, size: usize, fn benchAllocator(a: Arg, allocator: *mem.Allocator, comptime free: bool) !void { var i: usize = 0; while (i < a.num) : (i += 1) { const bytes = try allocator.alloc(u8, a.size); defer if (free) allocator.free(bytes); } } }; pub const args = [_]Arg{ Arg{ .num = 10 * 1, .size = 1024 * 1 }, Arg{ .num = 10 * 2, .size = 1024 * 1 }, Arg{ .num = 10 * 4, .size = 1024 * 1 }, Arg{ .num = 10 * 1, .size = 1024 * 2 }, Arg{ .num = 10 * 2, .size = 1024 * 2 }, Arg{ .num = 10 * 4, .size = 1024 * 2 }, Arg{ .num = 10 * 1, .size = 1024 * 4 }, Arg{ .num = 10 * 2, .size = 1024 * 4 }, Arg{ .num = 10 * 4, .size = 1024 * 4 }, }; pub const iterations = 10000; pub fn FixedBufferAllocator(a: Arg) void { var fba = heap.FixedBufferAllocator.init(test_buf[0..]); a.benchAllocator(&fba.allocator, false) catch unreachable; } pub fn Arena_FixedBufferAllocator(a: Arg) void { var fba = heap.FixedBufferAllocator.init(test_buf[0..]); var arena = heap.ArenaAllocator.init(&fba.allocator); defer arena.deinit(); a.benchAllocator(&arena.allocator, false) catch unreachable; } pub fn GcAllocator_FixedBufferAllocator(a: Arg) void { var fba = heap.FixedBufferAllocator.init(test_buf[0..]); var gc = GcAllocator.init(&fba.allocator); defer gc.deinit(); a.benchAllocator(gc.allocator(), false) catch unreachable; gc.collect(); } pub fn DirectAllocator(a: Arg) void { var da = heap.DirectAllocator.init(); defer da.deinit(); a.benchAllocator(&da.allocator, true) catch unreachable; } pub fn Arena_DirectAllocator(a: Arg) void { var da = heap.DirectAllocator.init(); defer da.deinit(); var arena = heap.ArenaAllocator.init(&da.allocator); defer arena.deinit(); a.benchAllocator(&arena.allocator, false) catch unreachable; } pub fn GcAllocator_DirectAllocator(a: Arg) void { var da = heap.DirectAllocator.init(); defer da.deinit(); var gc = GcAllocator.init(&da.allocator); defer gc.deinit(); a.benchAllocator(gc.allocator(), false) catch unreachable; gc.collect(); } }); }
gc.zig
const Allocator = std.mem.Allocator; const Headers = @import("./headers/headers.zig").Headers; const StatusCode = @import("status.zig").StatusCode; const std = @import("std"); const Version = @import("versions.zig").Version; const AllocationError = error{ OutOfMemory, }; pub const ResponseError = AllocationError || Headers.Error; pub const ResponseBuilder = struct { build_error: ?ResponseError, _version: Version, _status: StatusCode, headers: Headers, pub fn default(allocator: *Allocator) ResponseBuilder { return ResponseBuilder{ .build_error = null, ._version = Version.Http11, ._status = .Ok, .headers = Headers.init(allocator), }; } fn build_has_failed(self: *ResponseBuilder) callconv(.Inline) bool { return self.build_error != null; } pub fn body(self: *ResponseBuilder, value: []const u8) ResponseError!Response { if (self.build_has_failed()) { self.headers.deinit(); return self.build_error.?; } return Response{ .version = self._version, .status = self._status, .headers = self.headers, .body = value }; } pub fn header(self: *ResponseBuilder, name: []const u8, value: []const u8) *ResponseBuilder { if (self.build_has_failed()) { return self; } _ = self.headers.append(name, value) catch |err| { self.build_error = err; }; return self; } pub fn status(self: *ResponseBuilder, value: StatusCode) *ResponseBuilder { if (self.build_has_failed()) { return self; } self._status = value; return self; } pub fn version(self: *ResponseBuilder, value: Version) *ResponseBuilder { if (self.build_has_failed()) { return self; } self._version = value; return self; } }; pub const Response = struct { status: StatusCode, version: Version, headers: Headers, body: []const u8, pub fn builder(allocator: *Allocator) ResponseBuilder { return ResponseBuilder.default(allocator); } pub fn deinit(self: *Response) void { self.headers.deinit(); } }; const expect = std.testing.expect; const expectError = std.testing.expectError; test "Build with default values" { var response = try Response.builder(std.testing.allocator).body(""); defer response.deinit(); expect(response.version == .Http11); expect(response.status == .Ok); expect(response.headers.len() == 0); expect(std.mem.eql(u8, response.body, "")); } test "Build with specific values" { var response = try Response.builder(std.testing.allocator) .version(.Http11) .status(.ImATeapot) .header("GOTTA-GO", "FAST") .body("α••( ᐛ )α•—"); defer response.deinit(); expect(response.version == .Http11); expect(response.status == .ImATeapot); expect(std.mem.eql(u8, response.body, "α••( ᐛ )α•—")); var header = response.headers.get("GOTTA-GO").?; expect(std.mem.eql(u8, header.name.raw(), "GOTTA-GO")); expect(std.mem.eql(u8, header.value, "FAST")); } test "Build with a custom status code" { var custom_status = try StatusCode.from_u16(536); var response = try Response.builder(std.testing.allocator) .version(.Http11) .status(custom_status) .header("GOTTA-GO", "FAST") .body("α••( ᐛ )α•—"); defer response.deinit(); expect(response.version == .Http11); expect(response.status == custom_status); expect(std.mem.eql(u8, response.body, "α••( ᐛ )α•—")); var header = response.headers.get("GOTTA-GO").?; expect(std.mem.eql(u8, header.name.raw(), "GOTTA-GO")); expect(std.mem.eql(u8, header.value, "FAST")); } test "Free headers memory on error" { const failure = Response.builder(std.testing.allocator) .header("GOTTA-GO", "FAST") .header("INVALID HEADER", "") .body(""); expectError(error.InvalidHeaderName, failure); } test "Fail to build when out of memory" { var buffer: [100]u8 = undefined; const allocator = &std.heap.FixedBufferAllocator.init(&buffer).allocator; const failure = Response.builder(allocator) .header("GOTTA-GO", "FAST") .body("α••( ᐛ )α•—"); expectError(error.OutOfMemory, failure); }
src/response.zig
pub extern "LALR" const json_grammar = struct { fn Object(LBrace: *Token, MaybeFields: *Variant.Object, RBrace: *Token) *Variant { result = &arg2.base; } fn MaybeFields() *Variant.Object { result = try parser.createVariant(Variant.Object); result.fields = VariantMap.init(parser.arena_allocator); } fn MaybeFields(Fields: *Variant.Object) *Variant.Object; fn Fields(StringLiteral: *Token, Colon: *Token, Element: *Variant) *Variant.Object { result = try parser.createVariant(Variant.Object); result.fields = VariantMap.init(parser.arena_allocator); const r = try result.fields.insert(parser.tokenString(arg1)); if(!r.is_new) return error.JsonDuplicateKeyError; r.kv.value = arg3; } fn Fields(Fields: *Variant.Object, Comma: *Token, StringLiteral: *Token, Colon: *Token, Element: *Variant) *Variant.Object { result = arg1; const r = try result.fields.insert(parser.tokenString(arg3)); if(!r.is_new) return error.JsonDuplicateKeyError; r.kv.value = arg5; } fn Array(LBracket: *Token, MaybeElements: ?*VariantList, RBracket: *Token) *Variant { const variant = try parser.createVariant(Variant.Array); variant.elements = if(arg2) |l| l.* else VariantList.init(parser.arena_allocator); result = &variant.base; } fn MaybeElements() ?*VariantList; fn MaybeElements(Elements: *VariantList) ?*VariantList; fn Elements(Element: *Variant) *VariantList { result = try parser.createVariantList(VariantList); try result.append(arg1); } fn Elements(Elements: *VariantList, Comma: *Token, Element: *Variant) *VariantList { result = arg1; try result.append(arg3); } fn Element(StringLiteral: *Token) *Variant { const variant = try parser.createVariant(Variant.StringLiteral); variant.value = try parser.unescapeTokenString(arg1); result = &variant.base; } fn Element(Keyword_null: *Token) *Variant { const variant = try parser.createVariant(Variant.NullLiteral); result = &variant.base; } fn Element(Keyword_true: *Token) *Variant { const variant = try parser.createVariant(Variant.BoolLiteral); variant.value = true; result = &variant.base; } fn Element(Keyword_false: *Token) *Variant { const variant = try parser.createVariant(Variant.BoolLiteral); variant.value = false; result = &variant.base; } fn Element(IntegerLiteral: *Token) *Variant { const variant = try parser.createVariant(Variant.IntegerLiteral); const str = parser.tokenString(arg1); var value: isize = 0; var signed: bool = str[0] == '-'; // TODO: integer overflow for(str) |c| { if(c == '-') continue; value = value*10 + (@bitCast(i8, c)-'0'); } variant.value = if(signed) -value else value; result = &variant.base; } fn Element(Object: *Variant) *Variant; fn Element(Array: *Variant) *Variant; };
json/jsonlang.zig
const c = @import("c.zig"); //can't use usingnamespace because of main() definition conflict const std = @import("std"); const debug = std.debug; const allocator = std.heap.page_allocator; const Vec2 = @import("math/Vec2.zig").Vec2; const gameWorld = @import("game/GameWorld.zig"); const presentation = @import("presentation/Presentation.zig"); const assimp = @import("presentation/AssImpInterface.zig"); const filePathUtils = @import("coreutil/FilePathUtils.zig"); const TransformComp = @import("game/ComponentData/TransformComp.zig").TransformComp; const imageFileUtil = @import("coreutil/ImageFileUtil.zig"); const SDL_WINDOWPOS_UNDEFINED = @bitCast(c_int, c.SDL_WINDOWPOS_UNDEFINED_MASK); extern fn SDL_PollEvent(event: *c.SDL_Event) c_int; fn SDL_RWclose(ctx: [*]c.SDL_RWops) c_int { return ctx[0].close.?(ctx); } const InitError = error{ GlewInit, SDLInit, OpenGLInit, }; fn ReportSDLError(message: []const u8) void { const errStr = c.SDL_GetError(); debug.warn(" {s}: {s}", .{ message, errStr[0..std.mem.len(errStr)] }); } fn SetSDLAttribute(attribute: c_int, setVal: c_int) !c_int { const result = c.SDL_GL_SetAttribute(@intToEnum(c.SDL_GLattr, attribute), setVal); if (result < 0) { ReportSDLError("Unable to set attribute"); return InitError.SDLInit; } return result; } pub fn main() !void { // SDL init if (c.SDL_Init(c.SDL_INIT_VIDEO) != 0) { ReportSDLError("Unable to initialize SDL"); return InitError.SDLInit; } defer c.SDL_Quit(); // Setting attributes; required for renderdoc // TODO: query system support, set highest version, give warnings on lower versions _ = try SetSDLAttribute(c.SDL_GL_CONTEXT_PROFILE_MASK, c.SDL_GL_CONTEXT_PROFILE_CORE); _ = try SetSDLAttribute(c.SDL_GL_CONTEXT_MAJOR_VERSION, 4); _ = try SetSDLAttribute(c.SDL_GL_CONTEXT_MINOR_VERSION, 6); // Window Creation const screen = c.SDL_CreateWindow("My Game Window", SDL_WINDOWPOS_UNDEFINED, SDL_WINDOWPOS_UNDEFINED, 1280, 720, c.SDL_WINDOW_OPENGL | c.SDL_WINDOW_RESIZABLE) orelse { ReportSDLError("Unable to create window"); return InitError.SDLInit; }; defer c.SDL_DestroyWindow(screen); // Renderer const renderer = c.SDL_CreateRenderer(screen, -1, 0) orelse { ReportSDLError("Unable to create renderer"); return InitError.SDLInit; }; defer c.SDL_DestroyRenderer(renderer); // Create context const glContext = c.SDL_GL_CreateContext(screen); if (@ptrToInt(glContext) == 0) { ReportSDLError("Unable to create GLContext"); return InitError.SDLInit; } _ = c.SDL_GL_MakeCurrent(screen, glContext); // Glew init c.glewExperimental = c.GL_TRUE; var glewInitErr: c.GLenum = c.glewInit(); if (c.GLEW_OK != glewInitErr) { debug.warn("GlewInit failed", .{}); return InitError.GlewInit; } const glVer: [*:0]const u8 = c.glGetString(c.GL_VERSION); if (@ptrToInt(glVer) != 0) { debug.warn("OpenGL version supported by this platform: {s}\n", .{glVer[0..std.mem.len(glVer)]}); } // vsync on _ = c.SDL_GL_SetSwapInterval(1); // imgui setup TODO relocate TODO handle returns _ = c.igCreateContext(null); defer c.igDestroyContext(null); _ = c.ImGui_ImplSDL2_InitForOpenGL(screen, glContext); _ = c.ImGui_ImplOpenGL3_Init(null); //stb image wip test const testImagePath = "test-assets\\test.png"; if (imageFileUtil.LoadImage(testImagePath)) |*image| { defer image.FreeImage(); debug.warn("Successfully loaded test image {s}\n", .{testImagePath}); // where you would use the image... } else |err| { debug.warn("Failed to load test image {s}, {}\n", .{ testImagePath, err }); } presentation.Initialize(renderer); gameWorld.Initialize(); MainGameLoop(screen, renderer); } pub fn MainGameLoop(screen: *c.SDL_Window, renderer: *c.SDL_Renderer) void { //TODO input handling var quit = false; while (!quit) { var event: c.SDL_Event = undefined; while (SDL_PollEvent(&event) != 0) { _ = c.ImGui_ImplSDL2_ProcessEvent(&event); switch (event.@"type") { c.SDL_QUIT => { quit = true; }, else => {}, } } gameWorld.WritableInstance().Update(1.0 / 60.0); gameWorld.WritableInstance().FixedUpdate(); presentation.RenderFrame(renderer, screen, gameWorld.Instance()); c.SDL_Delay(17); } } test "create entity" { //TODO debug.warn("\n", .{}); const newEntity = gameWorld.WritableInstance().CreateEntity(); debug.warn("newEntityId: {}\n", .{newEntity.m_eid}); const newCompID = gameWorld.WritableInstance().m_componentManager.AddComponent(TransformComp, newEntity.m_eid); debug.warn("newTransformCompID: {}\n", .{newCompID}); debug.warn("{}\n", .{gameWorld.WritableInstance().m_componentManager.m_transformCompData.m_compData.len}); if (gameWorld.WritableInstance().m_componentManager.GetComponent(TransformComp, newCompID)) |compData| { debug.warn("scale: {}, {}, {}\n", .{ compData.scale.x, compData.scale.y, compData.scale.z }); } if (gameWorld.WritableInstance().m_componentManager.GetComponentOwnerId(TransformComp, newCompID)) |ownerId| { debug.warn("ownerId: {}\n", .{ownerId}); } }
src/main.zig
const std = @import("std"); const builtin = @import("builtin"); const CallingConvention = @import("std").builtin.CallingConvention; pub const is_nvptx = builtin.cpu.arch == .nvptx64; pub const Kernel = if (is_nvptx) CallingConvention.PtxKernel else CallingConvention.Unspecified; // Equivalent of Cuda's __syncthreads() /// Wait to all the threads in this block to reach this barrier /// before going on. pub inline fn syncThreads() void { // @"llvm.nvvm.barrier0"(); if (!is_nvptx) return; asm volatile ("bar.sync \t0;"); } // extern fn @"llvm.nvvm.barrier0"() void; // This doesn't seem to work. LLVM (called from Zig) crashes with a "Cannot select error" // pub inline fn threadDimX() usize { // return @intCast(usize, @"llvm.nvvm.read.ptx.sreg.ntid.x"()); // } // extern fn @"llvm.nvvm.read.ptx.sreg.ntid.x"() i32; /// threadId.x pub inline fn threadIdX() usize { if (!is_nvptx) return 0; var tid = asm volatile ("mov.u32 \t$0, %tid.x;" : [ret] "=r" (-> u32), ); return @intCast(usize, tid); } /// threadId.y pub inline fn threadIdY() usize { var tid = asm volatile ("mov.u32 \t$0, %tid.y;" : [ret] "=r" (-> u32), ); return @intCast(usize, tid); } /// threadId.z pub inline fn threadIdZ() usize { var tid = asm volatile ("mov.u32 \t$0, %tid.z;" : [ret] "=r" (-> u32), ); return @intCast(usize, tid); } /// threadDim.x pub inline fn threadDimX() usize { if (!is_nvptx) return 0; var ntid = asm volatile ("mov.u32 \t$0, %ntid.x;" : [ret] "=r" (-> u32), ); return @intCast(usize, ntid); } /// threadDim.y pub inline fn threadDimY() usize { var ntid = asm volatile ("mov.u32 \t$0, %ntid.y;" : [ret] "=r" (-> u32), ); return @intCast(usize, ntid); } /// threadDim.z pub inline fn threadDimZ() usize { var ntid = asm volatile ("mov.u32 \t$0, %ntid.z;" : [ret] "=r" (-> u32), ); return @intCast(usize, ntid); } /// gridId.x pub inline fn gridIdX() usize { if (!is_nvptx) return 0; var ctaid = asm volatile ("mov.u32 \t$0, %ctaid.x;" : [ret] "=r" (-> u32), ); return @intCast(usize, ctaid); } /// gridId.y pub inline fn gridIdY() usize { var ctaid = asm volatile ("mov.u32 \t$0, %ctaid.y;" : [ret] "=r" (-> u32), ); return @intCast(usize, ctaid); } /// gridId.z pub inline fn gridIdZ() usize { var ctaid = asm volatile ("mov.u32 \t$0, %ctaid.z;" : [ret] "=r" (-> u32), ); return @intCast(usize, ctaid); } /// gridDim.x pub inline fn gridDimX() usize { var nctaid = asm volatile ("mov.u32 \t$0, %nctaid.x;" : [ret] "=r" (-> u32), ); return @intCast(usize, nctaid); } /// gridDim.y pub inline fn gridDimY() usize { var nctaid = asm volatile ("mov.u32 \t$0, %nctaid.y;" : [ret] "=r" (-> u32), ); return @intCast(usize, nctaid); } /// gridDim.z pub inline fn gridDimZ() usize { var nctaid = asm volatile ("mov.u32 \t$0, %nctaid.z;" : [ret] "=r" (-> u32), ); return @intCast(usize, nctaid); } pub inline fn getId_1D() usize { return threadIdX() + threadDimX() * gridIdX(); } const Dim2 = struct { x: usize, y: usize }; pub fn getId_2D() Dim2 { return Dim2{ .x = threadIdX() + threadDimX() * gridIdX(), .y = threadIdY() + threadDimY() * gridIdY(), }; } const Dim3 = struct { x: usize, y: usize, z: usize }; pub fn getId_3D() Dim3 { return Dim3{ .x = threadIdX() + threadDimX() * gridIdX(), .y = threadIdY() + threadDimY() * gridIdY(), .z = threadIdZ() + threadDimZ() * gridIdZ(), }; } const message = "Hello World !\x00"; pub export fn _test_hello_world(out: []u8) callconv(Kernel) void { const i = getId_1D(); if (i > message.len or i > out.len) return; syncThreads(); out[i] = message[i]; }
cudaz/src/nvptx.zig
const std = @import("std"); const pike = @import("pike.zig"); const windows = @import("os/windows.zig"); const ws2_32 = @import("os/windows/ws2_32.zig"); const os = std.os; const net = std.net; const math = std.math; pub inline fn init() !void { _ = try windows.WSAStartup(2, 2); } pub inline fn deinit() void { windows.WSACleanup() catch {}; } pub const Handle = struct { inner: os.fd_t, }; pub const Overlapped = struct { inner: windows.OVERLAPPED, task: pike.Task, pub fn init(task: pike.Task) Overlapped { return .{ .inner = .{ .Internal = 0, .InternalHigh = 0, .Offset = 0, .OffsetHigh = 0, .hEvent = null, }, .task = task, }; } }; pub const Notifier = struct { const Self = @This(); handle: os.fd_t, pub fn init() !Self { const handle = try windows.CreateIoCompletionPort( windows.INVALID_HANDLE_VALUE, null, undefined, math.maxInt(windows.DWORD), ); errdefer windows.CloseHandle(handle); return Self{ .handle = handle }; } pub fn deinit(self: *const Self) void { windows.CloseHandle(self.handle); } pub fn register(self: *const Self, handle: *const Handle, comptime _: pike.PollOptions) !void { if (handle.inner == windows.INVALID_HANDLE_VALUE) return; _ = try windows.CreateIoCompletionPort(handle.inner, self.handle, 0, 0); try windows.SetFileCompletionNotificationModes( handle.inner, windows.FILE_SKIP_SET_EVENT_ON_HANDLE | windows.FILE_SKIP_COMPLETION_PORT_ON_SUCCESS, ); } pub fn poll(self: *const Self, timeout: i32) !void { var events: [128]windows.OVERLAPPED_ENTRY = undefined; var batch: pike.Batch = .{}; defer pike.dispatch(batch, .{}); const num_events = windows.GetQueuedCompletionStatusEx( self.handle, &events, @intCast(windows.DWORD, timeout), false, ) catch |err| switch (err) { error.Timeout => return, else => return err, }; for (events[0..num_events]) |event| { const overlapped = @fieldParentPtr(Overlapped, "inner", event.lpOverlapped orelse continue); batch.push(&overlapped.task); } } };
notifier_iocp.zig
usingnamespace @import("root").preamble; const atomic_queue = lib.containers.atomic_queue; /// Task queue is a generic helper for the queue of tasks (allows to enqueue/dequeue them) /// It does no locking (though it disables interrupts) for its operations pub const TaskQueue = struct { queue: atomic_queue.MPSCUnboundedQueue(os.thread.Task, "queue_hook") = .{}, last_ack: usize = 0, last_triggered: usize = 0, /// Remove task that is queue head from the queue. Returns null if queue is "empty" pub fn dequeue(self: *@This()) ?*os.thread.Task { const state = os.platform.get_and_disable_interrupts(); if (self.last_ack < @atomicLoad(usize, &self.last_triggered, .Acquire)) { while (true) { os.platform.spin_hint(); const note = self.queue.dequeue() orelse continue; self.last_ack += 1; os.platform.set_interrupts(state); return note; } } os.platform.set_interrupts(state); return null; } /// Enqueue task in the end of the queue. pub fn enqueue(self: *@This(), t: *os.thread.Task) void { const state = os.platform.get_and_disable_interrupts(); _ = @atomicRmw(usize, &self.last_triggered, .Add, 1, .AcqRel); self.queue.enqueue(t); os.platform.set_interrupts(state); } }; /// ReadyQueue is a data structure that implements core ready task queue logic /// os.platform.thread.CoreData should define: /// 1) start_monitoring: Initialize monitor to get ring events. If events occurs after this function /// call, it should be captured. Corresponds to MONITOR on x86 /// 2) wait: Wait for events. If one was recieved after call to start_monitoring, return /// immediatelly pub const ReadyQueue = struct { queue: TaskQueue = .{}, cpu: *os.platform.smp.CoreData = undefined, /// Enqueue task to run pub fn enqueue(self: *@This(), task: *os.thread.Task) void { self.queue.enqueue(task); self.cpu.platform_data.ring(); } /// Dequeue task. Waits for one to become available /// Should run in interrupts enabled context pub fn dequeue(self: *@This()) *os.thread.Task { while (true) { // Begin waiting for ring events self.cpu.platform_data.start_monitoring(); // If task already there, just return if (self.queue.dequeue()) |task| { return task; } // Wait for events self.cpu.platform_data.wait(); } } /// Try to dequeue task pub fn tryDequeue(self: *@This()) ?*os.thread.Task { return self.queue.dequeue(); } /// Initialize atomic queue used to store tasks pub fn init(self: *@This(), cpu: *os.platform.smp.CoreData) void { self.cpu = cpu; } };
subprojects/flork/src/thread/task_queue.zig
const std = @import("std"); const glfw = @import("glfw.zig"); const alogi = std.log.scoped(.nil_core_input); /// Error set pub const Error = error{ InvalidBinding, NoEmptyBinding }; pub const Key = glfw.Key; pub const Mouse = glfw.Mouse; /// States pub const State = enum { none = 0, pressed, down, released }; /// Input info pub const Info = struct { /// For managing key / button states /// I prefer call them as bindings pub const BindingManager = struct { status: State = State.none, key: Key = Key.Invalid, mouse: Mouse = Mouse.Invalid, }; /// Maximum key count pub const max_key_count: u8 = 50; /// Maximum mouse button count pub const max_mouse_count: u8 = 5; /// Binded key list key_list: [max_key_count]BindingManager = undefined, /// Binded mouse button list mouse_list: [max_mouse_count]BindingManager = undefined, /// Clears the key bindings pub fn keyClearBindings(self: *Info) void { var i: u8 = 0; var l = &self.key_list; while (i < max_key_count) : (i += 1) { l[i] = BindingManager{}; } } /// Clears the mouse button bindings pub fn mouseClearBindings(self: *Info) void { var i: u8 = 0; var l = &self.mouse_list; while (i < max_mouse_count) : (i += 1) { l[i] = BindingManager{}; } } /// Clears all the bindings pub fn clearBindings(self: *Info) void { self.keyClearBindings(); self.mouseClearBindings(); } /// Binds a key pub fn bindKey(self: *Info, key: Key) Error!void { var i: u8 = 0; var l = &self.key_list; while (i < max_key_count) : (i += 1) { if (i == @enumToInt(Key.Invalid)) { continue; } else if (l[i].key == Key.Invalid) { l[i].key = key; l[i].status = State.none; return; } } return Error.NoEmptyBinding; } /// Unbinds a key pub fn unbindKey(self: *Info, key: Key) Error!void { var i: u8 = 0; var l = &self.key_list; while (i < max_key_count) : (i += 1) { if (l[i].key == key) { l[i] = BindingManager{}; return; } } return Error.InvalidBinding; } /// Binds a mouse button pub fn bindMouse(self: *Info, mouse: Mouse) Error!void { var i: u8 = 0; var l = &self.mouse_list; while (i < max_mouse_count) : (i += 1) { if (i == @enumToInt(Mouse.Invalid)) { continue; } else if (l[i].mouse == Mouse.Invalid) { l[i].mouse = mouse; l[i].status = State.none; return; } } return Error.NoEmptyBinding; } /// Unbinds a mouse button pub fn unbindMouse(self: *Info, mouse: Mouse) Error!void { var i: u8 = 0; var l = &self.mouse_list; while (i < max_mouse_count) : (i += 1) { if (l[i].mouse == mouse) { l[i] = BindingManager{}; return; } } return Error.InvalidBinding; } /// Returns a binded key state pub fn keyState(self: *Info, key: Key) Error!State { var i: u8 = 0; var l = &self.key_list; while (i < max_key_count) : (i += 1) { if (l[i].key == key) { return l[i].status; } } return Error.InvalidBinding; } /// Returns a const reference to a binded key state pub fn keyStatePtr(self: *Info, key: Key) Error!*const State { var i: u8 = 0; var l = &self.key_list; while (i < max_key_count) : (i += 1) { if (l[i].key == key) { return &l[i].status; } } return Error.InvalidBinding; } /// Returns a binded key state pub fn mouseState(self: *Info, mouse: Mouse) Error!State { var i: u8 = 0; var l = &self.mouse_list; while (i < max_mouse_count) : (i += 1) { if (l[i].mouse == mouse) { return l[i].status; } } return Error.InvalidBinding; } /// Returns a const reference to a binded key state pub fn mouseStatePtr(self: *Info, mouse: Mouse) Error!*const State { var i: u8 = 0; var l = &self.mouse_list; while (i < max_mouse_count) : (i += 1) { if (l[i].mouse == mouse) { return &l[i].status; } } return Error.InvalidBinding; } /// Returns a value based on the given states pub fn getValue(comptime rtype: type, left: State, right: State) rtype { var r: rtype = undefined; if (left == .down) r -= 1; if (right == .down) r += 1; return r; } /// Handles the inputs /// Warning: Call just before polling/processing the events /// Keep in mind binding states will be useless after polling events pub fn handle(self: *Info) void { var i: u8 = 0; while (i < max_key_count) : (i += 1) { if (i < max_mouse_count) { var l = &self.mouse_list[i]; if (l.status == State.released) { l.status = State.none; } else if (l.status == State.pressed) { l.status = State.down; } } var l = &self.key_list[i]; if (l.key == Key.Invalid) { continue; } else if (l.status == State.released) { l.status = State.none; } else if (l.status == State.pressed) { l.status = State.down; } } } /// Handles the keyboard inputs pub fn handleKeyboard(input: *Info, key: i32, ac: i32) void { var l = &input.key_list; var i: u8 = 0; while (i < Info.max_key_count) : (i += 1) { if (@enumToInt(l[i].key) != key) { continue; } switch (ac) { 0 => { if (l[i].status == State.released) { l[i].status = State.none; } else if (l[i].status == State.down) { l[i].status = State.released; } }, 1, 2 => { if (l[i].status != State.down) l[i].status = State.pressed; }, else => { alogi.err("unknown action!", .{}); }, } } } /// Handles the mouse button inputs pub fn handleMouse(input: *Info, key: i32, ac: i32) void { var l = &input.mouse_list; var i: u8 = 0; while (i < Info.max_mouse_count) : (i += 1) { if (@enumToInt(l[i].mouse) != key) { continue; } switch (ac) { 0 => { if (l[i].status == State.released) { l[i].status = State.none; } else if (l[i].status == State.down) { l[i].status = State.released; } }, 1, 2 => { if (l[i].status != State.down) l[i].status = State.pressed; }, else => { alogi.err("unknown action!", .{}); }, } } } };
src/core/input.zig
const std = @import("std"); const builtin = std.builtin; const Builder = std.build.Builder; const tests = @import("test/tests.zig"); const BufMap = std.BufMap; const warn = std.debug.warn; const mem = std.mem; const ArrayList = std.ArrayList; const io = std.io; const fs = std.fs; const InstallDirectoryOptions = std.build.InstallDirectoryOptions; const assert = std.debug.assert; const zig_version = std.builtin.Version{ .major = 0, .minor = 9, .patch = 0 }; pub fn build(b: *Builder) !void { b.setPreferredReleaseMode(.ReleaseFast); const mode = b.standardReleaseOptions(); const target = b.standardTargetOptions(.{}); var docgen_exe = b.addExecutable("docgen", "doc/docgen.zig"); const rel_zig_exe = try fs.path.relative(b.allocator, b.build_root, b.zig_exe); const langref_out_path = fs.path.join( b.allocator, &[_][]const u8{ b.cache_root, "langref.html" }, ) catch unreachable; var docgen_cmd = docgen_exe.run(); docgen_cmd.addArgs(&[_][]const u8{ rel_zig_exe, "doc" ++ fs.path.sep_str ++ "langref.html.in", langref_out_path, }); docgen_cmd.step.dependOn(&docgen_exe.step); const docs_step = b.step("docs", "Build documentation"); docs_step.dependOn(&docgen_cmd.step); const toolchain_step = b.step("test-toolchain", "Run the tests for the toolchain"); var test_stage2 = b.addTest("src/test.zig"); test_stage2.setBuildMode(mode); test_stage2.addPackagePath("stage2_tests", "test/stage2/test.zig"); const fmt_build_zig = b.addFmt(&[_][]const u8{"build.zig"}); const skip_debug = b.option(bool, "skip-debug", "Main test suite skips debug builds") orelse false; const skip_release = b.option(bool, "skip-release", "Main test suite skips release builds") orelse false; const skip_release_small = b.option(bool, "skip-release-small", "Main test suite skips release-small builds") orelse skip_release; const skip_release_fast = b.option(bool, "skip-release-fast", "Main test suite skips release-fast builds") orelse skip_release; const skip_release_safe = b.option(bool, "skip-release-safe", "Main test suite skips release-safe builds") orelse skip_release; const skip_non_native = b.option(bool, "skip-non-native", "Main test suite skips non-native builds") orelse false; const skip_libc = b.option(bool, "skip-libc", "Main test suite skips tests that link libc") orelse false; const skip_compile_errors = b.option(bool, "skip-compile-errors", "Main test suite skips compile error tests") orelse false; const skip_run_translated_c = b.option(bool, "skip-run-translated-c", "Main test suite skips run-translated-c tests") orelse false; const skip_stage2_tests = b.option(bool, "skip-stage2-tests", "Main test suite skips self-hosted compiler tests") orelse false; const skip_install_lib_files = b.option(bool, "skip-install-lib-files", "Do not copy lib/ files to installation prefix") orelse false; const only_install_lib_files = b.option(bool, "lib-files-only", "Only install library files") orelse false; const is_stage1 = b.option(bool, "stage1", "Build the stage1 compiler, put stage2 behind a feature flag") orelse false; const omit_stage2 = b.option(bool, "omit-stage2", "Do not include stage2 behind a feature flag inside stage1") orelse false; const static_llvm = b.option(bool, "static-llvm", "Disable integration with system-installed LLVM, Clang, LLD, and libc++") orelse false; const enable_llvm = b.option(bool, "enable-llvm", "Build self-hosted compiler with LLVM backend enabled") orelse (is_stage1 or static_llvm); const config_h_path_option = b.option([]const u8, "config_h", "Path to the generated config.h"); if (!skip_install_lib_files) { b.installDirectory(InstallDirectoryOptions{ .source_dir = "lib", .install_dir = .Lib, .install_subdir = "zig", .exclude_extensions = &[_][]const u8{ "README.md", ".z.0", ".z.9", ".gz", "rfc1951.txt", }, .blank_extensions = &[_][]const u8{ "test.zig", }, }); } if (only_install_lib_files) return; const tracy = b.option([]const u8, "tracy", "Enable Tracy integration. Supply path to Tracy source"); const link_libc = b.option(bool, "force-link-libc", "Force self-hosted compiler to link libc") orelse enable_llvm; const strip = b.option(bool, "strip", "Omit debug information") orelse false; const mem_leak_frames: u32 = b.option(u32, "mem-leak-frames", "How many stack frames to print when a memory leak occurs. Tests get 2x this amount.") orelse blk: { if (strip) break :blk @as(u32, 0); if (mode != .Debug) break :blk 0; break :blk 4; }; const main_file = if (is_stage1) "src/stage1.zig" else "src/main.zig"; var exe = b.addExecutable("zig", main_file); exe.strip = strip; exe.install(); exe.setBuildMode(mode); exe.setTarget(target); toolchain_step.dependOn(&exe.step); b.default_step.dependOn(&exe.step); exe.addBuildOption(u32, "mem_leak_frames", mem_leak_frames); exe.addBuildOption(bool, "skip_non_native", skip_non_native); exe.addBuildOption(bool, "have_llvm", enable_llvm); if (enable_llvm) { const cmake_cfg = if (static_llvm) null else findAndParseConfigH(b, config_h_path_option); if (is_stage1) { exe.addIncludeDir("src"); exe.addIncludeDir("deps/SoftFloat-3e/source/include"); // This is intentionally a dummy path. stage1.zig tries to @import("compiler_rt") in case // of being built by cmake. But when built by zig it's gonna get a compiler_rt so that // is pointless. exe.addPackagePath("compiler_rt", "src/empty.zig"); exe.defineCMacro("ZIG_LINK_MODE=Static"); const softfloat = b.addStaticLibrary("softfloat", null); softfloat.setBuildMode(.ReleaseFast); softfloat.setTarget(target); softfloat.addIncludeDir("deps/SoftFloat-3e-prebuilt"); softfloat.addIncludeDir("deps/SoftFloat-3e/source/8086"); softfloat.addIncludeDir("deps/SoftFloat-3e/source/include"); softfloat.addCSourceFiles(&softfloat_sources, &[_][]const u8{ "-std=c99", "-O3" }); exe.linkLibrary(softfloat); exe.addCSourceFiles(&stage1_sources, &exe_cflags); exe.addCSourceFiles(&optimized_c_sources, &[_][]const u8{ "-std=c99", "-O3" }); } if (cmake_cfg) |cfg| { // Inside this code path, we have to coordinate with system packaged LLVM, Clang, and LLD. // That means we also have to rely on stage1 compiled c++ files. We parse config.h to find // the information passed on to us from cmake. if (cfg.cmake_prefix_path.len > 0) { b.addSearchPrefix(cfg.cmake_prefix_path); } try addCmakeCfgOptionsToExe(b, cfg, tracy, exe); try addCmakeCfgOptionsToExe(b, cfg, tracy, test_stage2); } else { // Here we are -Denable-llvm but no cmake integration. try addStaticLlvmOptionsToExe(exe); try addStaticLlvmOptionsToExe(test_stage2); } } if (link_libc) { exe.linkLibC(); test_stage2.linkLibC(); } const enable_logging = b.option(bool, "log", "Whether to enable logging") orelse false; const opt_version_string = b.option([]const u8, "version-string", "Override Zig version string. Default is to find out with git."); const version = if (opt_version_string) |version| version else v: { const version_string = b.fmt("{d}.{d}.{d}", .{ zig_version.major, zig_version.minor, zig_version.patch }); var code: u8 = undefined; const git_describe_untrimmed = b.execAllowFail(&[_][]const u8{ "git", "-C", b.build_root, "describe", "--match", "*.*.*", "--tags", }, &code, .Ignore) catch { break :v version_string; }; const git_describe = mem.trim(u8, git_describe_untrimmed, " \n\r"); switch (mem.count(u8, git_describe, "-")) { 0 => { // Tagged release version (e.g. 0.8.0). if (!mem.eql(u8, git_describe, version_string)) { std.debug.print("Zig version '{s}' does not match Git tag '{s}'\n", .{ version_string, git_describe }); std.process.exit(1); } break :v version_string; }, 2 => { // Untagged development build (e.g. 0.8.0-684-gbbe2cca1a). var it = mem.split(git_describe, "-"); const tagged_ancestor = it.next() orelse unreachable; const commit_height = it.next() orelse unreachable; const commit_id = it.next() orelse unreachable; const ancestor_ver = try std.builtin.Version.parse(tagged_ancestor); if (zig_version.order(ancestor_ver) != .gt) { std.debug.print("Zig version '{}' must be greater than tagged ancestor '{}'\n", .{ zig_version, ancestor_ver }); std.process.exit(1); } // Check that the commit hash is prefixed with a 'g' (a Git convention). if (commit_id.len < 1 or commit_id[0] != 'g') { std.debug.print("Unexpected `git describe` output: {s}\n", .{git_describe}); break :v version_string; } // The version is reformatted in accordance with the https://semver.org specification. break :v b.fmt("{s}-dev.{s}+{s}", .{ version_string, commit_height, commit_id[1..] }); }, else => { std.debug.print("Unexpected `git describe` output: {s}\n", .{git_describe}); break :v version_string; }, } }; exe.addBuildOption([:0]const u8, "version", try b.allocator.dupeZ(u8, version)); const semver = try std.SemanticVersion.parse(version); exe.addBuildOption(std.SemanticVersion, "semver", semver); exe.addBuildOption(bool, "enable_logging", enable_logging); exe.addBuildOption(bool, "enable_tracy", tracy != null); exe.addBuildOption(bool, "is_stage1", is_stage1); exe.addBuildOption(bool, "omit_stage2", omit_stage2); if (tracy) |tracy_path| { const client_cpp = fs.path.join( b.allocator, &[_][]const u8{ tracy_path, "TracyClient.cpp" }, ) catch unreachable; exe.addIncludeDir(tracy_path); exe.addCSourceFile(client_cpp, &[_][]const u8{ "-DTRACY_ENABLE=1", "-fno-sanitize=undefined" }); if (!enable_llvm) { exe.linkSystemLibraryName("c++"); } exe.linkLibC(); } const test_filter = b.option([]const u8, "test-filter", "Skip tests that do not match filter"); const is_wine_enabled = b.option(bool, "enable-wine", "Use Wine to run cross compiled Windows tests") orelse false; const is_qemu_enabled = b.option(bool, "enable-qemu", "Use QEMU to run cross compiled foreign architecture tests") orelse false; const is_wasmtime_enabled = b.option(bool, "enable-wasmtime", "Use Wasmtime to enable and run WASI libstd tests") orelse false; const is_darling_enabled = b.option(bool, "enable-darling", "[Experimental] Use Darling to run cross compiled macOS tests") orelse false; const glibc_multi_dir = b.option([]const u8, "enable-foreign-glibc", "Provide directory with glibc installations to run cross compiled tests that link glibc"); test_stage2.addBuildOption(bool, "skip_non_native", skip_non_native); test_stage2.addBuildOption(bool, "is_stage1", is_stage1); test_stage2.addBuildOption(bool, "omit_stage2", omit_stage2); test_stage2.addBuildOption(bool, "have_llvm", enable_llvm); test_stage2.addBuildOption(bool, "enable_qemu", is_qemu_enabled); test_stage2.addBuildOption(bool, "enable_wine", is_wine_enabled); test_stage2.addBuildOption(bool, "enable_wasmtime", is_wasmtime_enabled); test_stage2.addBuildOption(u32, "mem_leak_frames", mem_leak_frames * 2); test_stage2.addBuildOption(bool, "enable_darling", is_darling_enabled); test_stage2.addBuildOption(?[]const u8, "glibc_multi_install_dir", glibc_multi_dir); test_stage2.addBuildOption([]const u8, "version", version); const test_stage2_step = b.step("test-stage2", "Run the stage2 compiler tests"); test_stage2_step.dependOn(&test_stage2.step); if (!skip_stage2_tests) { toolchain_step.dependOn(test_stage2_step); } var chosen_modes: [4]builtin.Mode = undefined; var chosen_mode_index: usize = 0; if (!skip_debug) { chosen_modes[chosen_mode_index] = builtin.Mode.Debug; chosen_mode_index += 1; } if (!skip_release_safe) { chosen_modes[chosen_mode_index] = builtin.Mode.ReleaseSafe; chosen_mode_index += 1; } if (!skip_release_fast) { chosen_modes[chosen_mode_index] = builtin.Mode.ReleaseFast; chosen_mode_index += 1; } if (!skip_release_small) { chosen_modes[chosen_mode_index] = builtin.Mode.ReleaseSmall; chosen_mode_index += 1; } const modes = chosen_modes[0..chosen_mode_index]; // run stage1 `zig fmt` on this build.zig file just to make sure it works toolchain_step.dependOn(&fmt_build_zig.step); const fmt_step = b.step("test-fmt", "Run zig fmt against build.zig to make sure it works"); fmt_step.dependOn(&fmt_build_zig.step); toolchain_step.dependOn(tests.addPkgTests( b, test_filter, "test/behavior.zig", "behavior", "Run the behavior tests", modes, false, skip_non_native, skip_libc, is_wine_enabled, is_qemu_enabled, is_wasmtime_enabled, is_darling_enabled, glibc_multi_dir, )); toolchain_step.dependOn(tests.addPkgTests( b, test_filter, "lib/std/special/compiler_rt.zig", "compiler-rt", "Run the compiler_rt tests", modes, true, skip_non_native, true, is_wine_enabled, is_qemu_enabled, is_wasmtime_enabled, is_darling_enabled, glibc_multi_dir, )); toolchain_step.dependOn(tests.addPkgTests( b, test_filter, "lib/std/special/c.zig", "minilibc", "Run the mini libc tests", modes, true, skip_non_native, true, is_wine_enabled, is_qemu_enabled, is_wasmtime_enabled, is_darling_enabled, glibc_multi_dir, )); toolchain_step.dependOn(tests.addCompareOutputTests(b, test_filter, modes)); toolchain_step.dependOn(tests.addStandaloneTests(b, test_filter, modes, skip_non_native, target)); toolchain_step.dependOn(tests.addStackTraceTests(b, test_filter, modes)); toolchain_step.dependOn(tests.addCliTests(b, test_filter, modes)); toolchain_step.dependOn(tests.addAssembleAndLinkTests(b, test_filter, modes)); toolchain_step.dependOn(tests.addRuntimeSafetyTests(b, test_filter, modes)); toolchain_step.dependOn(tests.addTranslateCTests(b, test_filter)); if (!skip_run_translated_c) { toolchain_step.dependOn(tests.addRunTranslatedCTests(b, test_filter, target)); } // tests for this feature are disabled until we have the self-hosted compiler available // toolchain_step.dependOn(tests.addGenHTests(b, test_filter)); if (!skip_compile_errors) { toolchain_step.dependOn(tests.addCompileErrorTests(b, test_filter, modes)); } const std_step = tests.addPkgTests( b, test_filter, "lib/std/std.zig", "std", "Run the standard library tests", modes, false, skip_non_native, skip_libc, is_wine_enabled, is_qemu_enabled, is_wasmtime_enabled, is_darling_enabled, glibc_multi_dir, ); const test_step = b.step("test", "Run all the tests"); test_step.dependOn(toolchain_step); test_step.dependOn(std_step); test_step.dependOn(docs_step); } const exe_cflags = [_][]const u8{ "-std=c++14", "-D__STDC_CONSTANT_MACROS", "-D__STDC_FORMAT_MACROS", "-D__STDC_LIMIT_MACROS", "-D_GNU_SOURCE", "-fvisibility-inlines-hidden", "-fno-exceptions", "-fno-rtti", "-Werror=type-limits", "-Wno-missing-braces", "-Wno-comment", }; fn addCmakeCfgOptionsToExe( b: *Builder, cfg: CMakeConfig, tracy: ?[]const u8, exe: *std.build.LibExeObjStep, ) !void { exe.addObjectFile(fs.path.join(b.allocator, &[_][]const u8{ cfg.cmake_binary_dir, "zigcpp", b.fmt("{s}{s}{s}", .{ exe.target.libPrefix(), "zigcpp", exe.target.staticLibSuffix() }), }) catch unreachable); assert(cfg.lld_include_dir.len != 0); exe.addIncludeDir(cfg.lld_include_dir); addCMakeLibraryList(exe, cfg.clang_libraries); addCMakeLibraryList(exe, cfg.lld_libraries); addCMakeLibraryList(exe, cfg.llvm_libraries); const need_cpp_includes = tracy != null; // System -lc++ must be used because in this code path we are attempting to link // against system-provided LLVM, Clang, LLD. if (exe.target.getOsTag() == .linux) { // First we try to static link against gcc libstdc++. If that doesn't work, // we fall back to -lc++ and cross our fingers. addCxxKnownPath(b, cfg, exe, "libstdc++.a", "", need_cpp_includes) catch |err| switch (err) { error.RequiredLibraryNotFound => { exe.linkSystemLibrary("c++"); }, else => |e| return e, }; exe.linkSystemLibrary("unwind"); } else if (exe.target.isFreeBSD()) { try addCxxKnownPath(b, cfg, exe, "libc++.a", null, need_cpp_includes); exe.linkSystemLibrary("pthread"); } else if (exe.target.getOsTag() == .openbsd) { try addCxxKnownPath(b, cfg, exe, "libc++.a", null, need_cpp_includes); try addCxxKnownPath(b, cfg, exe, "libc++abi.a", null, need_cpp_includes); } else if (exe.target.isDarwin()) { exe.linkSystemLibrary("c++"); } if (cfg.dia_guids_lib.len != 0) { exe.addObjectFile(cfg.dia_guids_lib); } } fn addStaticLlvmOptionsToExe( exe: *std.build.LibExeObjStep, ) !void { // Adds the Zig C++ sources which both stage1 and stage2 need. // // We need this because otherwise zig_clang_cc1_main.cpp ends up pulling // in a dependency on llvm::cfg::Update<llvm::BasicBlock*>::dump() which is // unavailable when LLVM is compiled in Release mode. const zig_cpp_cflags = exe_cflags ++ [_][]const u8{"-DNDEBUG=1"}; exe.addCSourceFiles(&zig_cpp_sources, &zig_cpp_cflags); for (clang_libs) |lib_name| { exe.linkSystemLibrary(lib_name); } for (lld_libs) |lib_name| { exe.linkSystemLibrary(lib_name); } for (llvm_libs) |lib_name| { exe.linkSystemLibrary(lib_name); } // This means we rely on clang-or-zig-built LLVM, Clang, LLD libraries. exe.linkSystemLibrary("c++"); if (exe.target.getOs().tag == .windows) { exe.linkSystemLibrary("version"); exe.linkSystemLibrary("uuid"); } } fn addCxxKnownPath( b: *Builder, ctx: CMakeConfig, exe: *std.build.LibExeObjStep, objname: []const u8, errtxt: ?[]const u8, need_cpp_includes: bool, ) !void { const path_padded = try b.exec(&[_][]const u8{ ctx.cxx_compiler, b.fmt("-print-file-name={s}", .{objname}), }); const path_unpadded = mem.tokenize(path_padded, "\r\n").next().?; if (mem.eql(u8, path_unpadded, objname)) { if (errtxt) |msg| { warn("{s}", .{msg}); } else { warn("Unable to determine path to {s}\n", .{objname}); } return error.RequiredLibraryNotFound; } exe.addObjectFile(path_unpadded); // TODO a way to integrate with system c++ include files here // cc -E -Wp,-v -xc++ /dev/null if (need_cpp_includes) { // I used these temporarily for testing something but we obviously need a // more general purpose solution here. //exe.addIncludeDir("/nix/store/b3zsk4ihlpiimv3vff86bb5bxghgdzb9-gcc-9.2.0/lib/gcc/x86_64-unknown-linux-gnu/9.2.0/../../../../include/c++/9.2.0"); //exe.addIncludeDir("/nix/store/b3zsk4ihlpiimv3vff86bb5bxghgdzb9-gcc-9.2.0/lib/gcc/x86_64-unknown-linux-gnu/9.2.0/../../../../include/c++/9.2.0/x86_64-unknown-linux-gnu"); //exe.addIncludeDir("/nix/store/b3zsk4ihlpiimv3vff86bb5bxghgdzb9-gcc-9.2.0/lib/gcc/x86_64-unknown-linux-gnu/9.2.0/../../../../include/c++/9.2.0/backward"); } } fn addCMakeLibraryList(exe: *std.build.LibExeObjStep, list: []const u8) void { var it = mem.tokenize(list, ";"); while (it.next()) |lib| { if (mem.startsWith(u8, lib, "-l")) { exe.linkSystemLibrary(lib["-l".len..]); } else { exe.addObjectFile(lib); } } } const CMakeConfig = struct { cmake_binary_dir: []const u8, cmake_prefix_path: []const u8, cxx_compiler: []const u8, lld_include_dir: []const u8, lld_libraries: []const u8, clang_libraries: []const u8, llvm_libraries: []const u8, dia_guids_lib: []const u8, }; const max_config_h_bytes = 1 * 1024 * 1024; fn findAndParseConfigH(b: *Builder, config_h_path_option: ?[]const u8) ?CMakeConfig { const config_h_text: []const u8 = if (config_h_path_option) |config_h_path| blk: { break :blk fs.cwd().readFileAlloc(b.allocator, config_h_path, max_config_h_bytes) catch unreachable; } else blk: { // TODO this should stop looking for config.h once it detects we hit the // zig source root directory. var check_dir = fs.path.dirname(b.zig_exe).?; while (true) { var dir = fs.cwd().openDir(check_dir, .{}) catch unreachable; defer dir.close(); break :blk dir.readFileAlloc(b.allocator, "config.h", max_config_h_bytes) catch |err| switch (err) { error.FileNotFound => { const new_check_dir = fs.path.dirname(check_dir); if (new_check_dir == null or mem.eql(u8, new_check_dir.?, check_dir)) { return null; } check_dir = new_check_dir.?; continue; }, else => unreachable, }; } else unreachable; // TODO should not need `else unreachable`. }; var ctx: CMakeConfig = .{ .cmake_binary_dir = undefined, .cmake_prefix_path = undefined, .cxx_compiler = undefined, .lld_include_dir = undefined, .lld_libraries = undefined, .clang_libraries = undefined, .llvm_libraries = undefined, .dia_guids_lib = undefined, }; const mappings = [_]struct { prefix: []const u8, field: []const u8 }{ .{ .prefix = "#define ZIG_CMAKE_BINARY_DIR ", .field = "cmake_binary_dir", }, .{ .prefix = "#define ZIG_CMAKE_PREFIX_PATH ", .field = "cmake_prefix_path", }, .{ .prefix = "#define ZIG_CXX_COMPILER ", .field = "cxx_compiler", }, .{ .prefix = "#define ZIG_LLD_INCLUDE_PATH ", .field = "lld_include_dir", }, .{ .prefix = "#define ZIG_LLD_LIBRARIES ", .field = "lld_libraries", }, .{ .prefix = "#define ZIG_CLANG_LIBRARIES ", .field = "clang_libraries", }, .{ .prefix = "#define ZIG_LLVM_LIBRARIES ", .field = "llvm_libraries", }, .{ .prefix = "#define ZIG_DIA_GUIDS_LIB ", .field = "dia_guids_lib", }, }; var lines_it = mem.tokenize(config_h_text, "\r\n"); while (lines_it.next()) |line| { inline for (mappings) |mapping| { if (mem.startsWith(u8, line, mapping.prefix)) { var it = mem.split(line, "\""); _ = it.next().?; // skip the stuff before the quote const quoted = it.next().?; // the stuff inside the quote @field(ctx, mapping.field) = toNativePathSep(b, quoted); } } } return ctx; } fn toNativePathSep(b: *Builder, s: []const u8) []u8 { const duplicated = mem.dupe(b.allocator, u8, s) catch unreachable; for (duplicated) |*byte| switch (byte.*) { '/' => byte.* = fs.path.sep, else => {}, }; return duplicated; } const softfloat_sources = [_][]const u8{ "deps/SoftFloat-3e/source/8086/f128M_isSignalingNaN.c", "deps/SoftFloat-3e/source/8086/s_commonNaNToF128M.c", "deps/SoftFloat-3e/source/8086/s_commonNaNToF16UI.c", "deps/SoftFloat-3e/source/8086/s_commonNaNToF32UI.c", "deps/SoftFloat-3e/source/8086/s_commonNaNToF64UI.c", "deps/SoftFloat-3e/source/8086/s_f128MToCommonNaN.c", "deps/SoftFloat-3e/source/8086/s_f16UIToCommonNaN.c", "deps/SoftFloat-3e/source/8086/s_f32UIToCommonNaN.c", "deps/SoftFloat-3e/source/8086/s_f64UIToCommonNaN.c", "deps/SoftFloat-3e/source/8086/s_propagateNaNF128M.c", "deps/SoftFloat-3e/source/8086/s_propagateNaNF16UI.c", "deps/SoftFloat-3e/source/8086/softfloat_raiseFlags.c", "deps/SoftFloat-3e/source/f128M_add.c", "deps/SoftFloat-3e/source/f128M_div.c", "deps/SoftFloat-3e/source/f128M_eq.c", "deps/SoftFloat-3e/source/f128M_eq_signaling.c", "deps/SoftFloat-3e/source/f128M_le.c", "deps/SoftFloat-3e/source/f128M_le_quiet.c", "deps/SoftFloat-3e/source/f128M_lt.c", "deps/SoftFloat-3e/source/f128M_lt_quiet.c", "deps/SoftFloat-3e/source/f128M_mul.c", "deps/SoftFloat-3e/source/f128M_mulAdd.c", "deps/SoftFloat-3e/source/f128M_rem.c", "deps/SoftFloat-3e/source/f128M_roundToInt.c", "deps/SoftFloat-3e/source/f128M_sqrt.c", "deps/SoftFloat-3e/source/f128M_sub.c", "deps/SoftFloat-3e/source/f128M_to_f16.c", "deps/SoftFloat-3e/source/f128M_to_f32.c", "deps/SoftFloat-3e/source/f128M_to_f64.c", "deps/SoftFloat-3e/source/f128M_to_i32.c", "deps/SoftFloat-3e/source/f128M_to_i32_r_minMag.c", "deps/SoftFloat-3e/source/f128M_to_i64.c", "deps/SoftFloat-3e/source/f128M_to_i64_r_minMag.c", "deps/SoftFloat-3e/source/f128M_to_ui32.c", "deps/SoftFloat-3e/source/f128M_to_ui32_r_minMag.c", "deps/SoftFloat-3e/source/f128M_to_ui64.c", "deps/SoftFloat-3e/source/f128M_to_ui64_r_minMag.c", "deps/SoftFloat-3e/source/f16_add.c", "deps/SoftFloat-3e/source/f16_div.c", "deps/SoftFloat-3e/source/f16_eq.c", "deps/SoftFloat-3e/source/f16_isSignalingNaN.c", "deps/SoftFloat-3e/source/f16_lt.c", "deps/SoftFloat-3e/source/f16_mul.c", "deps/SoftFloat-3e/source/f16_mulAdd.c", "deps/SoftFloat-3e/source/f16_rem.c", "deps/SoftFloat-3e/source/f16_roundToInt.c", "deps/SoftFloat-3e/source/f16_sqrt.c", "deps/SoftFloat-3e/source/f16_sub.c", "deps/SoftFloat-3e/source/f16_to_f128M.c", "deps/SoftFloat-3e/source/f16_to_f64.c", "deps/SoftFloat-3e/source/f32_to_f128M.c", "deps/SoftFloat-3e/source/f64_to_f128M.c", "deps/SoftFloat-3e/source/f64_to_f16.c", "deps/SoftFloat-3e/source/i32_to_f128M.c", "deps/SoftFloat-3e/source/s_add256M.c", "deps/SoftFloat-3e/source/s_addCarryM.c", "deps/SoftFloat-3e/source/s_addComplCarryM.c", "deps/SoftFloat-3e/source/s_addF128M.c", "deps/SoftFloat-3e/source/s_addM.c", "deps/SoftFloat-3e/source/s_addMagsF16.c", "deps/SoftFloat-3e/source/s_addMagsF32.c", "deps/SoftFloat-3e/source/s_addMagsF64.c", "deps/SoftFloat-3e/source/s_approxRecip32_1.c", "deps/SoftFloat-3e/source/s_approxRecipSqrt32_1.c", "deps/SoftFloat-3e/source/s_approxRecipSqrt_1Ks.c", "deps/SoftFloat-3e/source/s_approxRecip_1Ks.c", "deps/SoftFloat-3e/source/s_compare128M.c", "deps/SoftFloat-3e/source/s_compare96M.c", "deps/SoftFloat-3e/source/s_countLeadingZeros16.c", "deps/SoftFloat-3e/source/s_countLeadingZeros32.c", "deps/SoftFloat-3e/source/s_countLeadingZeros64.c", "deps/SoftFloat-3e/source/s_countLeadingZeros8.c", "deps/SoftFloat-3e/source/s_eq128.c", "deps/SoftFloat-3e/source/s_invalidF128M.c", "deps/SoftFloat-3e/source/s_isNaNF128M.c", "deps/SoftFloat-3e/source/s_le128.c", "deps/SoftFloat-3e/source/s_lt128.c", "deps/SoftFloat-3e/source/s_mul128MTo256M.c", "deps/SoftFloat-3e/source/s_mul64To128M.c", "deps/SoftFloat-3e/source/s_mulAddF128M.c", "deps/SoftFloat-3e/source/s_mulAddF16.c", "deps/SoftFloat-3e/source/s_mulAddF32.c", "deps/SoftFloat-3e/source/s_mulAddF64.c", "deps/SoftFloat-3e/source/s_negXM.c", "deps/SoftFloat-3e/source/s_normRoundPackMToF128M.c", "deps/SoftFloat-3e/source/s_normRoundPackToF16.c", "deps/SoftFloat-3e/source/s_normRoundPackToF32.c", "deps/SoftFloat-3e/source/s_normRoundPackToF64.c", "deps/SoftFloat-3e/source/s_normSubnormalF128SigM.c", "deps/SoftFloat-3e/source/s_normSubnormalF16Sig.c", "deps/SoftFloat-3e/source/s_normSubnormalF32Sig.c", "deps/SoftFloat-3e/source/s_normSubnormalF64Sig.c", "deps/SoftFloat-3e/source/s_remStepMBy32.c", "deps/SoftFloat-3e/source/s_roundMToI64.c", "deps/SoftFloat-3e/source/s_roundMToUI64.c", "deps/SoftFloat-3e/source/s_roundPackMToF128M.c", "deps/SoftFloat-3e/source/s_roundPackToF16.c", "deps/SoftFloat-3e/source/s_roundPackToF32.c", "deps/SoftFloat-3e/source/s_roundPackToF64.c", "deps/SoftFloat-3e/source/s_roundToI32.c", "deps/SoftFloat-3e/source/s_roundToI64.c", "deps/SoftFloat-3e/source/s_roundToUI32.c", "deps/SoftFloat-3e/source/s_roundToUI64.c", "deps/SoftFloat-3e/source/s_shiftLeftM.c", "deps/SoftFloat-3e/source/s_shiftNormSigF128M.c", "deps/SoftFloat-3e/source/s_shiftRightJam256M.c", "deps/SoftFloat-3e/source/s_shiftRightJam32.c", "deps/SoftFloat-3e/source/s_shiftRightJam64.c", "deps/SoftFloat-3e/source/s_shiftRightJamM.c", "deps/SoftFloat-3e/source/s_shiftRightM.c", "deps/SoftFloat-3e/source/s_shortShiftLeft64To96M.c", "deps/SoftFloat-3e/source/s_shortShiftLeftM.c", "deps/SoftFloat-3e/source/s_shortShiftRightExtendM.c", "deps/SoftFloat-3e/source/s_shortShiftRightJam64.c", "deps/SoftFloat-3e/source/s_shortShiftRightJamM.c", "deps/SoftFloat-3e/source/s_shortShiftRightM.c", "deps/SoftFloat-3e/source/s_sub1XM.c", "deps/SoftFloat-3e/source/s_sub256M.c", "deps/SoftFloat-3e/source/s_subM.c", "deps/SoftFloat-3e/source/s_subMagsF16.c", "deps/SoftFloat-3e/source/s_subMagsF32.c", "deps/SoftFloat-3e/source/s_subMagsF64.c", "deps/SoftFloat-3e/source/s_tryPropagateNaNF128M.c", "deps/SoftFloat-3e/source/softfloat_state.c", "deps/SoftFloat-3e/source/ui32_to_f128M.c", "deps/SoftFloat-3e/source/ui64_to_f128M.c", }; const stage1_sources = [_][]const u8{ "src/stage1/analyze.cpp", "src/stage1/astgen.cpp", "src/stage1/bigfloat.cpp", "src/stage1/bigint.cpp", "src/stage1/buffer.cpp", "src/stage1/codegen.cpp", "src/stage1/dump_analysis.cpp", "src/stage1/errmsg.cpp", "src/stage1/error.cpp", "src/stage1/heap.cpp", "src/stage1/ir.cpp", "src/stage1/ir_print.cpp", "src/stage1/mem.cpp", "src/stage1/os.cpp", "src/stage1/parser.cpp", "src/stage1/range_set.cpp", "src/stage1/stage1.cpp", "src/stage1/target.cpp", "src/stage1/tokenizer.cpp", "src/stage1/util.cpp", "src/stage1/softfloat_ext.cpp", }; const optimized_c_sources = [_][]const u8{ "src/stage1/parse_f128.c", }; const zig_cpp_sources = [_][]const u8{ // These are planned to stay even when we are self-hosted. "src/zig_llvm.cpp", "src/zig_clang.cpp", "src/zig_llvm-ar.cpp", "src/zig_clang_driver.cpp", "src/zig_clang_cc1_main.cpp", "src/zig_clang_cc1as_main.cpp", // https://github.com/ziglang/zig/issues/6363 "src/windows_sdk.cpp", }; const clang_libs = [_][]const u8{ "clangFrontendTool", "clangCodeGen", "clangFrontend", "clangDriver", "clangSerialization", "clangSema", "clangStaticAnalyzerFrontend", "clangStaticAnalyzerCheckers", "clangStaticAnalyzerCore", "clangAnalysis", "clangASTMatchers", "clangAST", "clangParse", "clangSema", "clangBasic", "clangEdit", "clangLex", "clangARCMigrate", "clangRewriteFrontend", "clangRewrite", "clangCrossTU", "clangIndex", "clangToolingCore", }; const lld_libs = [_][]const u8{ "lldDriver", "lldMinGW", "lldELF", "lldCOFF", "lldMachO", "lldWasm", "lldReaderWriter", "lldCore", "lldYAML", "lldCommon", }; // This list can be re-generated with `llvm-config --libfiles` and then // reformatting using your favorite text editor. Note we do not execute // `llvm-config` here because we are cross compiling. Also omit LLVMTableGen // from these libs. const llvm_libs = [_][]const u8{ "LLVMWindowsManifest", "LLVMXRay", "LLVMLibDriver", "LLVMDlltoolDriver", "LLVMCoverage", "LLVMLineEditor", "LLVMXCoreDisassembler", "LLVMXCoreCodeGen", "LLVMXCoreDesc", "LLVMXCoreInfo", "LLVMX86Disassembler", "LLVMX86AsmParser", "LLVMX86CodeGen", "LLVMX86Desc", "LLVMX86Info", "LLVMWebAssemblyDisassembler", "LLVMWebAssemblyAsmParser", "LLVMWebAssemblyCodeGen", "LLVMWebAssemblyDesc", "LLVMWebAssemblyInfo", "LLVMSystemZDisassembler", "LLVMSystemZAsmParser", "LLVMSystemZCodeGen", "LLVMSystemZDesc", "LLVMSystemZInfo", "LLVMSparcDisassembler", "LLVMSparcAsmParser", "LLVMSparcCodeGen", "LLVMSparcDesc", "LLVMSparcInfo", "LLVMRISCVDisassembler", "LLVMRISCVAsmParser", "LLVMRISCVCodeGen", "LLVMRISCVDesc", "LLVMRISCVInfo", "LLVMPowerPCDisassembler", "LLVMPowerPCAsmParser", "LLVMPowerPCCodeGen", "LLVMPowerPCDesc", "LLVMPowerPCInfo", "LLVMNVPTXCodeGen", "LLVMNVPTXDesc", "LLVMNVPTXInfo", "LLVMMSP430Disassembler", "LLVMMSP430AsmParser", "LLVMMSP430CodeGen", "LLVMMSP430Desc", "LLVMMSP430Info", "LLVMMipsDisassembler", "LLVMMipsAsmParser", "LLVMMipsCodeGen", "LLVMMipsDesc", "LLVMMipsInfo", "LLVMLanaiDisassembler", "LLVMLanaiCodeGen", "LLVMLanaiAsmParser", "LLVMLanaiDesc", "LLVMLanaiInfo", "LLVMHexagonDisassembler", "LLVMHexagonCodeGen", "LLVMHexagonAsmParser", "LLVMHexagonDesc", "LLVMHexagonInfo", "LLVMBPFDisassembler", "LLVMBPFAsmParser", "LLVMBPFCodeGen", "LLVMBPFDesc", "LLVMBPFInfo", "LLVMAVRDisassembler", "LLVMAVRAsmParser", "LLVMAVRCodeGen", "LLVMAVRDesc", "LLVMAVRInfo", "LLVMARMDisassembler", "LLVMARMAsmParser", "LLVMARMCodeGen", "LLVMARMDesc", "LLVMARMUtils", "LLVMARMInfo", "LLVMAMDGPUDisassembler", "LLVMAMDGPUAsmParser", "LLVMAMDGPUCodeGen", "LLVMAMDGPUDesc", "LLVMAMDGPUUtils", "LLVMAMDGPUInfo", "LLVMAArch64Disassembler", "LLVMAArch64AsmParser", "LLVMAArch64CodeGen", "LLVMAArch64Desc", "LLVMAArch64Utils", "LLVMAArch64Info", "LLVMOrcJIT", "LLVMMCJIT", "LLVMJITLink", "LLVMOrcTargetProcess", "LLVMOrcShared", "LLVMInterpreter", "LLVMExecutionEngine", "LLVMRuntimeDyld", "LLVMSymbolize", "LLVMDebugInfoPDB", "LLVMDebugInfoGSYM", "LLVMOption", "LLVMObjectYAML", "LLVMMCA", "LLVMMCDisassembler", "LLVMLTO", "LLVMPasses", "LLVMCFGuard", "LLVMCoroutines", "LLVMObjCARCOpts", "LLVMHelloNew", "LLVMipo", "LLVMVectorize", "LLVMLinker", "LLVMInstrumentation", "LLVMFrontendOpenMP", "LLVMFrontendOpenACC", "LLVMExtensions", "LLVMDWARFLinker", "LLVMGlobalISel", "LLVMMIRParser", "LLVMAsmPrinter", "LLVMDebugInfoDWARF", "LLVMSelectionDAG", "LLVMCodeGen", "LLVMIRReader", "LLVMAsmParser", "LLVMInterfaceStub", "LLVMFileCheck", "LLVMFuzzMutate", "LLVMTarget", "LLVMScalarOpts", "LLVMInstCombine", "LLVMAggressiveInstCombine", "LLVMTransformUtils", "LLVMBitWriter", "LLVMAnalysis", "LLVMProfileData", "LLVMObject", "LLVMTextAPI", "LLVMMCParser", "LLVMMC", "LLVMDebugInfoCodeView", "LLVMDebugInfoMSF", "LLVMBitReader", "LLVMCore", "LLVMRemarks", "LLVMBitstreamReader", "LLVMBinaryFormat", "LLVMSupport", "LLVMDemangle", };
build.zig
const builtin = @import("builtin"); const Os = builtin.Os; pub use switch (builtin.os) { Os.linux => @import("linux.zig"), Os.windows => @import("windows.zig"), Os.macosx, Os.ios => @import("darwin.zig"), Os.freebsd => @import("freebsd.zig"), else => empty_import, }; const empty_import = @import("../empty.zig"); // TODO https://github.com/ziglang/zig/issues/265 on this whole file pub extern "c" fn abort() noreturn; pub extern "c" fn exit(code: c_int) noreturn; pub extern "c" fn isatty(fd: c_int) c_int; pub extern "c" fn close(fd: c_int) c_int; pub extern "c" fn fstat(fd: c_int, buf: *Stat) c_int; pub extern "c" fn @"fstat$INODE64"(fd: c_int, buf: *Stat) c_int; pub extern "c" fn lseek(fd: c_int, offset: isize, whence: c_int) isize; pub extern "c" fn open(path: [*]const u8, oflag: c_int, ...) c_int; pub extern "c" fn raise(sig: c_int) c_int; pub extern "c" fn read(fd: c_int, buf: *c_void, nbyte: usize) isize; pub extern "c" fn pread(fd: c_int, buf: *c_void, nbyte: usize, offset: u64) isize; pub extern "c" fn stat(noalias path: [*]const u8, noalias buf: *Stat) c_int; pub extern "c" fn write(fd: c_int, buf: *const c_void, nbyte: usize) isize; pub extern "c" fn pwrite(fd: c_int, buf: *const c_void, nbyte: usize, offset: u64) isize; pub extern "c" fn mmap(addr: ?*c_void, len: usize, prot: c_int, flags: c_int, fd: c_int, offset: isize) ?*c_void; pub extern "c" fn munmap(addr: *c_void, len: usize) c_int; pub extern "c" fn unlink(path: [*]const u8) c_int; pub extern "c" fn getcwd(buf: [*]u8, size: usize) ?[*]u8; pub extern "c" fn waitpid(pid: c_int, stat_loc: *c_int, options: c_int) c_int; pub extern "c" fn fork() c_int; pub extern "c" fn access(path: [*]const u8, mode: c_uint) c_int; pub extern "c" fn pipe(fds: *[2]c_int) c_int; pub extern "c" fn mkdir(path: [*]const u8, mode: c_uint) c_int; pub extern "c" fn symlink(existing: [*]const u8, new: [*]const u8) c_int; pub extern "c" fn rename(old: [*]const u8, new: [*]const u8) c_int; pub extern "c" fn chdir(path: [*]const u8) c_int; pub extern "c" fn execve(path: [*]const u8, argv: [*]const ?[*]const u8, envp: [*]const ?[*]const u8) c_int; pub extern "c" fn dup(fd: c_int) c_int; pub extern "c" fn dup2(old_fd: c_int, new_fd: c_int) c_int; pub extern "c" fn readlink(noalias path: [*]const u8, noalias buf: [*]u8, bufsize: usize) isize; pub extern "c" fn realpath(noalias file_name: [*]const u8, noalias resolved_name: [*]u8) ?[*]u8; pub extern "c" fn sigprocmask(how: c_int, noalias set: *const sigset_t, noalias oset: ?*sigset_t) c_int; pub extern "c" fn gettimeofday(tv: ?*timeval, tz: ?*timezone) c_int; pub extern "c" fn sigaction(sig: c_int, noalias act: *const Sigaction, noalias oact: ?*Sigaction) c_int; pub extern "c" fn nanosleep(rqtp: *const timespec, rmtp: ?*timespec) c_int; pub extern "c" fn setreuid(ruid: c_uint, euid: c_uint) c_int; pub extern "c" fn setregid(rgid: c_uint, egid: c_uint) c_int; pub extern "c" fn rmdir(path: [*]const u8) c_int; pub extern "c" fn aligned_alloc(alignment: usize, size: usize) ?*c_void; pub extern "c" fn malloc(usize) ?*c_void; pub extern "c" fn realloc(*c_void, usize) ?*c_void; pub extern "c" fn free(*c_void) void; pub extern "c" fn posix_memalign(memptr: **c_void, alignment: usize, size: usize) c_int; pub extern "pthread" fn pthread_create(noalias newthread: *pthread_t, noalias attr: ?*const pthread_attr_t, start_routine: extern fn (?*c_void) ?*c_void, noalias arg: ?*c_void) c_int; pub extern "pthread" fn pthread_attr_init(attr: *pthread_attr_t) c_int; pub extern "pthread" fn pthread_attr_setstack(attr: *pthread_attr_t, stackaddr: *c_void, stacksize: usize) c_int; pub extern "pthread" fn pthread_attr_destroy(attr: *pthread_attr_t) c_int; pub extern "pthread" fn pthread_self() pthread_t; pub extern "pthread" fn pthread_join(thread: pthread_t, arg_return: ?*?*c_void) c_int; pub const pthread_t = *@OpaqueType();
std/c/index.zig
const std = @import("std"); const testing = std.testing; const expect = testing.expect; const expectEqual = testing.expectEqual; test "passing an optional integer as a parameter" { const S = struct { fn entry() bool { var x: i32 = 1234; return foo(x); } fn foo(x: ?i32) bool { return x.? == 1234; } }; try expect(S.entry()); comptime try expect(S.entry()); } test "self-referential struct through a slice of optional" { const S = struct { const Node = struct { children: []?Node, data: ?u8, fn new() Node { return Node{ .children = undefined, .data = null, }; } }; }; var n = S.Node.new(); try expect(n.data == null); } pub const EmptyStruct = struct {}; test "optional pointer to size zero struct" { var e = EmptyStruct{}; var o: ?*EmptyStruct = &e; try expect(o != null); } test "equality compare optional pointers" { try testNullPtrsEql(); comptime try testNullPtrsEql(); } fn testNullPtrsEql() !void { var number: i32 = 1234; var x: ?*i32 = null; var y: ?*i32 = null; try expect(x == y); y = &number; try expect(x != y); try expect(x != &number); try expect(&number != x); x = &number; try expect(x == y); try expect(x == &number); try expect(&number == x); } test "optional with void type" { const Foo = struct { x: ?void, }; var x = Foo{ .x = null }; try expect(x.x == null); } test "address of unwrap optional" { const S = struct { const Foo = struct { a: i32, }; var global: ?Foo = null; pub fn getFoo() anyerror!*Foo { return &global.?; } }; S.global = S.Foo{ .a = 1234 }; const foo = S.getFoo() catch unreachable; try expect(foo.a == 1234); } test "nested optional field in struct" { const S2 = struct { y: u8, }; const S1 = struct { x: ?S2, }; var s = S1{ .x = S2{ .y = 127 }, }; try expect(s.x.?.y == 127); } test "equality compare optional with non-optional" { try test_cmp_optional_non_optional(); comptime try test_cmp_optional_non_optional(); } fn test_cmp_optional_non_optional() !void { var ten: i32 = 10; var opt_ten: ?i32 = 10; var five: i32 = 5; var int_n: ?i32 = null; try expect(int_n != ten); try expect(opt_ten == ten); try expect(opt_ten != five); // test evaluation is always lexical // ensure that the optional isn't always computed before the non-optional var mutable_state: i32 = 0; _ = blk1: { mutable_state += 1; break :blk1 @as(?f64, 10.0); } != blk2: { try expect(mutable_state == 1); break :blk2 @as(f64, 5.0); }; _ = blk1: { mutable_state += 1; break :blk1 @as(f64, 10.0); } != blk2: { try expect(mutable_state == 2); break :blk2 @as(?f64, 5.0); }; }
test/behavior/optional.zig
const std = @import("std"); const argparse = @import("argparse.zig"); const process = @import("process.zig"); const rootfs = @import("rootfs.zig"); const runtime_spec = @import("runtime_spec.zig"); const syscall = @import("syscall.zig"); const utils = @import("utils.zig"); const ZRunArgs = struct { bundle: []const u8 = ".", config: []const u8 = "runtime_spec.json", detach: bool = false, pid_file: ?[]const u8 = null, }; fn zrun() !?utils.Process { var alloc = std.heap.page_allocator; const zrun_args = try argparse.parse(ZRunArgs, .{ .allocator = alloc }); defer argparse.parseFree(ZRunArgs, zrun_args, .{ .allocator = alloc }); try std.os.chdir(zrun_args.bundle); // 0. Load configure var loader = try utils.JsonLoader(runtime_spec.Spec).initFromFile(alloc, zrun_args.config); defer loader.deinit(); const runtime_config = loader.value; try utils.validateSpec(&runtime_config); // 1. Unshare CLONE_NEWPID // - fork try utils.setupNamespace(.pid, runtime_config.linux.namespaces); if (try utils.fork(zrun_args.detach)) |child| { if (zrun_args.pid_file) |pid_file| { try child.createPidFile(pid_file); } // TODO: Return continuation instead return child; } // 2. Unshare CLONE_NEWIPC try utils.setupNamespace(.ipc, runtime_config.linux.namespaces); // 3. Unshare CLONE_NEWUTS // - Change hostname try utils.setupNamespace(.uts, runtime_config.linux.namespaces); if (runtime_config.hostname) |hostname| { try syscall.sethostname(hostname); } // 4. Unshare CLONE_NEWNET // - Back to old network namespace // - Set up network // - Enter new network namespace try utils.setupNamespace(.network, runtime_config.linux.namespaces); // 5. Unshare CLONE_NEWNS // - Prepare rootfs (Mount private, generate files ...) // - Mount dirs to rootfs // - Create devices // - Chroot try utils.setupNamespace(.mount, runtime_config.linux.namespaces); try rootfs.setup(alloc, &runtime_config); // 6. Finalize // - sysctl // - change user // - exec try process.execute(alloc, &runtime_config.process); unreachable; } pub fn main() !void { if (try zrun()) |child| { // Wait child outside zrun() to make sure all using memory released try child.wait(); } }
src/zrun.zig
const std = @import("std"); const Builder = std.build.Builder; pub const Options = struct { /// The github org to find repositories in. github_org: []const u8 = "hexops", /// The MacOS SDK repository name. macos_sdk: []const u8 = "sdk-macos-12.0", /// The Linux x86-64 SDK repository name. linux_x86_64_sdk: []const u8 = "sdk-linux-x86_64", /// If true, the Builder.sysroot will set to the SDK path. This has the drawback of preventing /// you from including headers, libraries, etc. from outside the SDK generally. However, it can /// be useful in order to identify which libraries, headers, frameworks, etc. may be missing in /// your SDK for cross compilation. set_sysroot: bool = false, }; pub fn include(b: *Builder, step: *std.build.LibExeObjStep, options: Options) void { const target = (std.zig.system.NativeTargetInfo.detect(b.allocator, step.target) catch unreachable).target; switch (target.os.tag) { .windows => {}, .macos => includeSdkMacOS(b, step, options), else => includeSdkLinuxX8664(b, step, options), // Assume Linux-like for now } } fn includeSdkMacOS(b: *Builder, step: *std.build.LibExeObjStep, options: Options) void { const sdk_root_dir = getSdkRoot(b.allocator, options.github_org, options.macos_sdk) catch unreachable; if (options.set_sysroot) { step.addFrameworkDir("/System/Library/Frameworks"); step.addSystemIncludeDir("/usr/include"); step.addLibPath("/usr/lib"); var sdk_sysroot = std.fs.path.join(b.allocator, &.{ sdk_root_dir, "root/" }) catch unreachable; b.sysroot = sdk_sysroot; return; } var sdk_framework_dir = std.fs.path.join(b.allocator, &.{ sdk_root_dir, "root/System/Library/Frameworks" }) catch unreachable; step.addFrameworkDir(sdk_framework_dir); var sdk_include_dir = std.fs.path.join(b.allocator, &.{ sdk_root_dir, "root/usr/include" }) catch unreachable; step.addSystemIncludeDir(sdk_include_dir); var sdk_lib_dir = std.fs.path.join(b.allocator, &.{ sdk_root_dir, "root/usr/lib" }) catch unreachable; step.addLibPath(sdk_lib_dir); } fn includeSdkLinuxX8664(b: *Builder, step: *std.build.LibExeObjStep, options: Options) void { const sdk_root_dir = getSdkRoot(b.allocator, options.github_org, options.linux_x86_64_sdk) catch unreachable; defer b.allocator.free(sdk_root_dir); if (options.set_sysroot) { var sdk_sysroot = std.fs.path.join(b.allocator, &.{ sdk_root_dir, "root/" }) catch unreachable; b.sysroot = sdk_sysroot; return; } var sdk_root_includes = std.fs.path.join(b.allocator, &.{ sdk_root_dir, "root/usr/include" }) catch unreachable; defer b.allocator.free(sdk_root_includes); step.addSystemIncludeDir(sdk_root_includes); var sdk_root_libs = std.fs.path.join(b.allocator, &.{ sdk_root_dir, "root/usr/lib/x86_64-linux-gnu" }) catch unreachable; defer b.allocator.free(sdk_root_libs); step.addLibPath(sdk_root_libs); } fn getSdkRoot(allocator: *std.mem.Allocator, org: []const u8, name: []const u8) ![]const u8 { // Find the directory where the SDK should be located. We'll consider two locations: // // 1. $SDK_PATH/<name> (if set, e.g. for testing changes to SDKs easily) // 2. <appdata>/<name> (default) // // Where `<name>` is the name of the SDK, e.g. `sdk-macos-12.0`. var sdk_root_dir: []const u8 = undefined; var sdk_path_dir: []const u8 = undefined; if (std.process.getEnvVarOwned(allocator, "SDK_PATH")) |sdk_path| { sdk_path_dir = sdk_path; sdk_root_dir = try std.fs.path.join(allocator, &.{ sdk_path, name }); } else |err| switch (err) { error.EnvironmentVariableNotFound => { sdk_path_dir = try std.fs.getAppDataDir(allocator, org); sdk_root_dir = try std.fs.path.join(allocator, &.{ sdk_path_dir, name }); }, else => |e| return e, } // If the SDK exists, return it. Otherwise, clone it. if (std.fs.openDirAbsolute(sdk_root_dir, .{})) { return sdk_root_dir; } else |err| return switch (err) { error.FileNotFound => { std.log.info("cloning required sdk..\ngit clone https://github.com/{s}/{s} '{s}'..\n", .{ org, name, sdk_root_dir }); if (std.mem.eql(u8, name, "sdk-macos-12.0")) { if (!try confirmAppleSDKAgreement(allocator)) @panic("cannot continue"); } try std.fs.cwd().makePath(sdk_path_dir); var buf: [1000]u8 = undefined; var repo_url_fbs = std.io.fixedBufferStream(&buf); try std.fmt.format(repo_url_fbs.writer(), "https://github.com/{s}/{s}", .{ org, name }); const argv = &[_][]const u8{ "git", "clone", repo_url_fbs.getWritten() }; const child = try std.ChildProcess.init(argv, allocator); child.cwd = sdk_path_dir; child.stdin = std.io.getStdOut(); child.stderr = std.io.getStdErr(); child.stdout = std.io.getStdOut(); try child.spawn(); _ = try child.wait(); return sdk_root_dir; }, else => err, }; } fn confirmAppleSDKAgreement(allocator: *std.mem.Allocator) !bool { if (std.process.getEnvVarOwned(allocator, "AGREE")) |agree| { return std.mem.eql(u8, agree, "true"); } else |err| switch (err) { error.EnvironmentVariableNotFound => {}, else => |e| return e, } const stdin = std.io.getStdIn().reader(); const stdout = std.io.getStdOut().writer(); var buf: [10]u8 = undefined; try stdout.print("This SDK is distributed under the terms of the Xcode and Apple SDKs agreement:\n", .{}); try stdout.print(" https://www.apple.com/legal/sla/docs/xcode.pdf\n", .{}); try stdout.print("\n", .{}); try stdout.print("Do you agree to those terms? [Y/n] ", .{}); if (try stdin.readUntilDelimiterOrEof(buf[0..], '\n')) |user_input| { try stdout.print("\n", .{}); var in = user_input; if (in.len > 0 and in[in.len - 1] == '\r') in = in[0 .. in.len - 1]; return std.mem.eql(u8, in, "y") or std.mem.eql(u8, in, "Y") or std.mem.eql(u8, in, "yes") or std.mem.eql(u8, in, ""); } else { return false; } }
glfw/system_sdk.zig
const std = @import("std"); const Allocator = std.mem.Allocator; const c = @import("../c.zig"); const content = @import("../content.zig"); const gfx = @import("../gfx.zig"); const math = @import("../math.zig"); usingnamespace math; usingnamespace @import("util.zig"); //; const Vertex3d = extern struct { const Self = @This(); position: Vec3, uv: Vec2, normal: Vec3, pub fn init(position: Vec3, uv: Vec2, normal: Vec3) Self { return Self{ .position = position, .uv = uv, .normal = normal, }; } pub fn setAttributes(vao: *gfx.VertexArray) void { var temp = gfx.VertexAttribute{ .size = 3, .ty = c.GL_FLOAT, .is_normalized = false, .stride = @sizeOf(Self), .offset = @byteOffsetOf(Self, "position"), .divisor = 0, }; vao.enableAttribute(0, temp); temp.offset = @byteOffsetOf(Self, "uv"); temp.size = 2; vao.enableAttribute(1, temp); temp.offset = @byteOffsetOf(Self, "normal"); temp.size = 3; vao.enableAttribute(2, temp); } }; pub const Mesh3d = gfx.Mesh(Vertex3d); pub const Locations3d = struct { const Self = @This(); projection: gfx.Location, view: gfx.Location, model: gfx.Location, time: gfx.Location, flip_uvs: gfx.Location, tx_diffuse: gfx.Location, tx_normal: gfx.Location, base_color: gfx.Location, pub fn init(program: gfx.Program) Self { return .{ .projection = program.getLocation("_projection"), .view = program.getLocation("_view"), .model = program.getLocation("_model"), .time = program.getLocation("_time"), .flip_uvs = program.getLocation("_flip_uvs"), .tx_diffuse = program.getLocation("_tx_diffuse"), .tx_normal = program.getLocation("_tx_normal"), .base_color = program.getLocation("_base_color"), }; } // note: doesnt set textures pub fn reset(self: Self) void { self.projection.setMat4(Mat4.identity()); self.view.setMat4(Mat4.identity()); self.model.setMat4(Mat4.identity()); self.time.setFloat(0.); self.flip_uvs.setBool(false); self.base_color.setColor(Color.initRgba(1., 1., 1., 1.)); } }; pub const Program3d = struct { const Self = @This(); program: gfx.Program, locations: Locations3d, // takes ownership of program pub fn init(program: gfx.Program) Self { return .{ .program = program, .locations = Locations3d.init(program), }; } pub fn deinit(self: *Self) void { self.program.deinit(); } pub fn initDefault( workspace_allocator: *Allocator, v_effect: ?[]const u8, f_effect: ?[]const u8, ) !Self { const v_str = try applyEffectToDefaultShader( workspace_allocator, content.shaders.default_3d_vert, content.shaders.default_3d_vert_effect, v_effect, ); defer workspace_allocator.free(v_str); const f_str = try applyEffectToDefaultShader( workspace_allocator, content.shaders.default_3d_frag, content.shaders.default_3d_frag_effect, f_effect, ); defer workspace_allocator.free(f_str); var v_shader = try gfx.Shader.init(c.GL_VERTEX_SHADER, v_str); defer v_shader.deinit(); var f_shader = try gfx.Shader.init(c.GL_FRAGMENT_SHADER, f_str); defer f_shader.deinit(); const prog = try gfx.Program.init(&[_]gfx.Shader{ v_shader, f_shader }); return Self.init(prog); } };
src/defaults/cube.zig
const zang = @import("zang"); const common = @import("common.zig"); const c = @import("common/c.zig"); pub const AUDIO_FORMAT: zang.AudioFormat = .signed16_lsb; pub const AUDIO_SAMPLE_RATE = 48000; pub const AUDIO_BUFFER_SIZE = 1024; pub const DESCRIPTION = \\example_portamento \\ \\Play an instrument with the keyboard. If you press \\multiple keys, the frequency will slide toward the \\highest held key. ; const a4 = 440.0; pub const Instrument = struct { pub const num_outputs = 2; pub const num_temps = 3; pub const Params = struct { sample_rate: f32, freq: f32, note_on: bool, }; osc: zang.SineOsc, env: zang.Envelope, porta: zang.Portamento, prev_note_on: bool, pub fn init() Instrument { return .{ .osc = zang.SineOsc.init(), .env = zang.Envelope.init(), .porta = zang.Portamento.init(), .prev_note_on = false, }; } pub fn paint( self: *Instrument, span: zang.Span, outputs: [num_outputs][]f32, temps: [num_temps][]f32, note_id_changed: bool, params: Params, ) void { defer self.prev_note_on = params.note_on; zang.zero(span, temps[0]); // update portamento if note changes self.porta.paint(span, .{temps[0]}, .{}, note_id_changed, .{ .sample_rate = params.sample_rate, .curve = .{ .cubed = 0.5 }, .goal = params.freq, .note_on = params.note_on, .prev_note_on = self.prev_note_on, }); zang.zero(span, temps[1]); // only reset envelope if all keys are released const new_note = !self.prev_note_on and params.note_on; self.env.paint(span, .{temps[1]}, .{}, new_note, .{ .sample_rate = params.sample_rate, .attack = .{ .cubed = 0.025 }, .decay = .{ .cubed = 0.1 }, .release = .{ .cubed = 1.0 }, .sustain_volume = 0.5, .note_on = params.note_on, }); zang.zero(span, temps[2]); self.osc.paint(span, .{temps[2]}, .{}, false, .{ .sample_rate = params.sample_rate, .freq = zang.buffer(temps[0]), .phase = zang.constant(0.0), }); zang.multiply(span, outputs[0], temps[1], temps[2]); // output frequency for oscilloscope sync zang.addInto(span, outputs[1], temps[0]); } }; pub const MainModule = struct { pub const num_outputs = 2; pub const num_temps = 3; pub const output_audio = common.AudioOut{ .mono = 0 }; pub const output_visualize = 0; pub const output_sync_oscilloscope = 1; keys_held: u64, iq: zang.Notes(Instrument.Params).ImpulseQueue, idgen: zang.IdGenerator, instr: Instrument, trigger: zang.Trigger(Instrument.Params), pub fn init() MainModule { return .{ .keys_held = 0, .iq = zang.Notes(Instrument.Params).ImpulseQueue.init(), .idgen = zang.IdGenerator.init(), .instr = Instrument.init(), .trigger = zang.Trigger(Instrument.Params).init(), }; } pub fn paint( self: *MainModule, span: zang.Span, outputs: [num_outputs][]f32, temps: [num_temps][]f32, ) void { var ctr = self.trigger.counter(span, self.iq.consume()); while (self.trigger.next(&ctr)) |result| { self.instr.paint( result.span, outputs, temps, result.note_id_changed, result.params, ); } } // this is a bit different from the other examples. i'm mimicking the // behaviour of analog monophonic synths with portamento: // - the frequency is always that of the highest key held // - note-off only occurs when all keys are released pub fn keyEvent(self: *MainModule, key: i32, down: bool, impulse_frame: usize) bool { for (common.key_bindings) |kb, i| { if (kb.key != key) { continue; } const key_index = @intCast(u6, i); const key_flag = @as(u64, 1) << key_index; const prev_keys_held = self.keys_held; if (down) { self.keys_held |= key_flag; if (key_flag > prev_keys_held) { self.iq.push(impulse_frame, self.idgen.nextId(), .{ .sample_rate = AUDIO_SAMPLE_RATE, .freq = a4 * kb.rel_freq, .note_on = true, }); } } else { self.keys_held &= ~key_flag; if (self.keys_held == 0) { self.iq.push(impulse_frame, self.idgen.nextId(), .{ .sample_rate = AUDIO_SAMPLE_RATE, .freq = a4 * kb.rel_freq, .note_on = false, }); } else { const rel_freq = common.key_bindings[63 - @clz(u64, self.keys_held)].rel_freq; self.iq.push(impulse_frame, self.idgen.nextId(), .{ .sample_rate = AUDIO_SAMPLE_RATE, .freq = a4 * rel_freq, .note_on = true, }); } } } return true; } };
examples/example_portamento.zig
pub const WINCODEC_SDK_VERSION1 = @as(u32, 566); pub const WINCODEC_SDK_VERSION2 = @as(u32, 567); pub const CLSID_WICImagingFactory = Guid.initString("cacaf262-9370-4615-a13b-9f5539da4c0a"); pub const CLSID_WICImagingFactory1 = Guid.initString("cacaf262-9370-4615-a13b-9f5539da4c0a"); pub const CLSID_WICImagingFactory2 = Guid.initString("317d06e8-5f24-433d-bdf7-79ce68d8abc2"); pub const WINCODEC_SDK_VERSION = @as(u32, 567); pub const GUID_VendorMicrosoft = Guid.initString("f0e749ca-edef-4589-a73a-ee0e626a2a2b"); pub const GUID_VendorMicrosoftBuiltIn = Guid.initString("257a30fd-06b6-462b-aea4-63f70b86e533"); pub const CLSID_WICPngDecoder = Guid.initString("389ea17b-5078-4cde-b6ef-25c15175c751"); pub const CLSID_WICPngDecoder1 = Guid.initString("389ea17b-5078-4cde-b6ef-25c15175c751"); pub const CLSID_WICPngDecoder2 = Guid.initString("e018945b-aa86-4008-9bd4-6777a1e40c11"); pub const CLSID_WICBmpDecoder = Guid.initString("6b462062-7cbf-400d-9fdb-813dd10f2778"); pub const CLSID_WICIcoDecoder = Guid.initString("c61bfcdf-2e0f-4aad-a8d7-e06bafebcdfe"); pub const CLSID_WICJpegDecoder = Guid.initString("9456a480-e88b-43ea-9e73-0b2d9b71b1ca"); pub const CLSID_WICGifDecoder = Guid.initString("381dda3c-9ce9-4834-a23e-1f98f8fc52be"); pub const CLSID_WICTiffDecoder = Guid.initString("b54e85d9-fe23-499f-8b88-6acea713752b"); pub const CLSID_WICWmpDecoder = Guid.initString("a26cec36-234c-4950-ae16-e34aace71d0d"); pub const CLSID_WICDdsDecoder = Guid.initString("9053699f-a341-429d-9e90-ee437cf80c73"); pub const CLSID_WICBmpEncoder = Guid.initString("69be8bb4-d66d-47c8-865a-ed1589433782"); pub const CLSID_WICPngEncoder = Guid.initString("27949969-876a-41d7-9447-568f6a35a4dc"); pub const CLSID_WICJpegEncoder = Guid.initString("1a34f5c1-4a5a-46dc-b644-1f4567e7a676"); pub const CLSID_WICGifEncoder = Guid.initString("114f5598-0b22-40a0-86a1-c83ea495adbd"); pub const CLSID_WICTiffEncoder = Guid.initString("0131be10-2001-4c5f-a9b0-cc88fab64ce8"); pub const CLSID_WICWmpEncoder = Guid.initString("ac4ce3cb-e1c1-44cd-8215-5a1665509ec2"); pub const CLSID_WICDdsEncoder = Guid.initString("a61dde94-66ce-4ac1-881b-71680588895e"); pub const CLSID_WICAdngDecoder = Guid.initString("981d9411-909e-42a7-8f5d-a747ff052edb"); pub const CLSID_WICJpegQualcommPhoneEncoder = Guid.initString("68ed5c62-f534-4979-b2b3-686a12b2b34c"); pub const CLSID_WICHeifDecoder = Guid.initString("e9a4a80a-44fe-4de4-8971-7150b10a5199"); pub const CLSID_WICHeifEncoder = Guid.initString("0dbecec1-9eb3-4860-9c6f-ddbe86634575"); pub const CLSID_WICWebpDecoder = Guid.initString("7693e886-51c9-4070-8419-9f70738ec8fa"); pub const CLSID_WICRAWDecoder = Guid.initString("41945702-8302-44a6-9445-ac98e8afa086"); pub const GUID_ContainerFormatBmp = Guid.initString("0af1d87e-fcfe-4188-bdeb-a7906471cbe3"); pub const GUID_ContainerFormatPng = Guid.initString("1b7cfaf4-713f-473c-bbcd-6137425faeaf"); pub const GUID_ContainerFormatIco = Guid.initString("a3a860c4-338f-4c17-919a-fba4b5628f21"); pub const GUID_ContainerFormatJpeg = Guid.initString("19e4a5aa-5662-4fc5-a0c0-1758028e1057"); pub const GUID_ContainerFormatTiff = Guid.initString("163bcc30-e2e9-4f0b-961d-a3e9fdb788a3"); pub const GUID_ContainerFormatGif = Guid.initString("1f8a5601-7d4d-4cbd-9c82-1bc8d4eeb9a5"); pub const GUID_ContainerFormatWmp = Guid.initString("57a37caa-367a-4540-916b-f183c5093a4b"); pub const GUID_ContainerFormatDds = Guid.initString("9967cb95-2e85-4ac8-8ca2-83d7ccd425c9"); pub const GUID_ContainerFormatAdng = Guid.initString("f3ff6d0d-38c0-41c4-b1fe-1f3824f17b84"); pub const GUID_ContainerFormatHeif = Guid.initString("e1e62521-6787-405b-a339-500715b5763f"); pub const GUID_ContainerFormatWebp = Guid.initString("e094b0e2-67f2-45b3-b0ea-115337ca7cf3"); pub const GUID_ContainerFormatRaw = Guid.initString("fe99ce60-f19c-433c-a3ae-00acefa9ca21"); pub const CLSID_WICImagingCategories = Guid.initString("fae3d380-fea4-4623-8c75-c6b61110b681"); pub const CATID_WICBitmapDecoders = Guid.initString("7ed96837-96f0-4812-b211-f13c24117ed3"); pub const CATID_WICBitmapEncoders = Guid.initString("ac757296-3522-4e11-9862-c17be5a1767e"); pub const CATID_WICPixelFormats = Guid.initString("2b46e70f-cda7-473e-89f6-dc9630a2390b"); pub const CATID_WICFormatConverters = Guid.initString("7835eae8-bf14-49d1-93ce-533a407b2248"); pub const CATID_WICMetadataReader = Guid.initString("05af94d8-7174-4cd2-be4a-4124b80ee4b8"); pub const CATID_WICMetadataWriter = Guid.initString("abe3b9a4-257d-4b97-bd1a-294af496222e"); pub const CLSID_WICDefaultFormatConverter = Guid.initString("1a3f11dc-b514-4b17-8c5f-2154513852f1"); pub const CLSID_WICFormatConverterHighColor = Guid.initString("ac75d454-9f37-48f8-b972-4e19bc856011"); pub const CLSID_WICFormatConverterNChannel = Guid.initString("c17cabb2-d4a3-47d7-a557-339b2efbd4f1"); pub const CLSID_WICFormatConverterWMPhoto = Guid.initString("9cb5172b-d600-46ba-ab77-77bb7e3a00d9"); pub const CLSID_WICPlanarFormatConverter = Guid.initString("184132b8-32f8-4784-9131-dd7224b23438"); pub const WIC_JPEG_MAX_COMPONENT_COUNT = @as(u32, 4); pub const WIC_JPEG_MAX_TABLE_INDEX = @as(u32, 3); pub const WIC_JPEG_SAMPLE_FACTORS_ONE = @as(u32, 17); pub const WIC_JPEG_SAMPLE_FACTORS_THREE_420 = @as(u32, 1118498); pub const WIC_JPEG_SAMPLE_FACTORS_THREE_422 = @as(u32, 1118497); pub const WIC_JPEG_SAMPLE_FACTORS_THREE_440 = @as(u32, 1118482); pub const WIC_JPEG_SAMPLE_FACTORS_THREE_444 = @as(u32, 1118481); pub const WIC_JPEG_QUANTIZATION_BASELINE_ONE = @as(u32, 0); pub const WIC_JPEG_QUANTIZATION_BASELINE_THREE = @as(u32, 65792); pub const WIC_JPEG_HUFFMAN_BASELINE_ONE = @as(u32, 0); pub const WIC_JPEG_HUFFMAN_BASELINE_THREE = @as(u32, 1118464); pub const GUID_WICPixelFormatDontCare = Guid.initString("6fddc324-4e03-4bfe-b185-3d77768dc900"); pub const GUID_WICPixelFormat1bppIndexed = Guid.initString("6fddc324-4e03-4bfe-b185-3d77768dc901"); pub const GUID_WICPixelFormat2bppIndexed = Guid.initString("6fddc324-4e03-4bfe-b185-3d77768dc902"); pub const GUID_WICPixelFormat4bppIndexed = Guid.initString("6fddc324-4e03-4bfe-b185-3d77768dc903"); pub const GUID_WICPixelFormat8bppIndexed = Guid.initString("6fddc324-4e03-4bfe-b185-3d77768dc904"); pub const GUID_WICPixelFormatBlackWhite = Guid.initString("6fddc324-4e03-4bfe-b185-3d77768dc905"); pub const GUID_WICPixelFormat2bppGray = Guid.initString("6fddc324-4e03-4bfe-b185-3d77768dc906"); pub const GUID_WICPixelFormat4bppGray = Guid.initString("6fddc324-4e03-4bfe-b185-3d77768dc907"); pub const GUID_WICPixelFormat8bppGray = Guid.initString("6fddc324-4e03-4bfe-b185-3d77768dc908"); pub const GUID_WICPixelFormat8bppAlpha = Guid.initString("e6cd0116-eeba-4161-aa85-27dd9fb3a895"); pub const GUID_WICPixelFormat16bppBGR555 = Guid.initString("6fddc324-4e03-4bfe-b185-3d77768dc909"); pub const GUID_WICPixelFormat16bppBGR565 = Guid.initString("6fddc324-4e03-4bfe-b185-3d77768dc90a"); pub const GUID_WICPixelFormat16bppBGRA5551 = Guid.initString("05ec7c2b-f1e6-4961-ad46-e1cc810a87d2"); pub const GUID_WICPixelFormat16bppGray = Guid.initString("6fddc324-4e03-4bfe-b185-3d77768dc90b"); pub const GUID_WICPixelFormat24bppBGR = Guid.initString("6fddc324-4e03-4bfe-b185-3d77768dc90c"); pub const GUID_WICPixelFormat24bppRGB = Guid.initString("6fddc324-4e03-4bfe-b185-3d77768dc90d"); pub const GUID_WICPixelFormat32bppBGR = Guid.initString("6fddc324-4e03-4bfe-b185-3d77768dc90e"); pub const GUID_WICPixelFormat32bppBGRA = Guid.initString("6fddc324-4e03-4bfe-b185-3d77768dc90f"); pub const GUID_WICPixelFormat32bppPBGRA = Guid.initString("6fddc324-4e03-4bfe-b185-3d77768dc910"); pub const GUID_WICPixelFormat32bppGrayFloat = Guid.initString("6fddc324-4e03-4bfe-b185-3d77768dc911"); pub const GUID_WICPixelFormat32bppRGB = Guid.initString("d98c6b95-3efe-47d6-bb25-eb1748ab0cf1"); pub const GUID_WICPixelFormat32bppRGBA = Guid.initString("f5c7ad2d-6a8d-43dd-a7a8-a29935261ae9"); pub const GUID_WICPixelFormat32bppPRGBA = Guid.initString("3cc4a650-a527-4d37-a916-3142c7ebedba"); pub const GUID_WICPixelFormat48bppRGB = Guid.initString("6fddc324-4e03-4bfe-b185-3d77768dc915"); pub const GUID_WICPixelFormat48bppBGR = Guid.initString("e605a384-b468-46ce-bb2e-36f180e64313"); pub const GUID_WICPixelFormat64bppRGB = Guid.initString("a1182111-186d-4d42-bc6a-9c8303a8dff9"); pub const GUID_WICPixelFormat64bppRGBA = Guid.initString("6fddc324-4e03-4bfe-b185-3d77768dc916"); pub const GUID_WICPixelFormat64bppBGRA = Guid.initString("1562ff7c-d352-46f9-979e-42976b792246"); pub const GUID_WICPixelFormat64bppPRGBA = Guid.initString("6fddc324-4e03-4bfe-b185-3d77768dc917"); pub const GUID_WICPixelFormat64bppPBGRA = Guid.initString("8c518e8e-a4ec-468b-ae70-c9a35a9c5530"); pub const GUID_WICPixelFormat16bppGrayFixedPoint = Guid.initString("6fddc324-4e03-4bfe-b185-3d77768dc913"); pub const GUID_WICPixelFormat32bppBGR101010 = Guid.initString("6fddc324-4e03-4bfe-b185-3d77768dc914"); pub const GUID_WICPixelFormat48bppRGBFixedPoint = Guid.initString("6fddc324-4e03-4bfe-b185-3d77768dc912"); pub const GUID_WICPixelFormat48bppBGRFixedPoint = Guid.initString("49ca140e-cab6-493b-9ddf-60187c37532a"); pub const GUID_WICPixelFormat96bppRGBFixedPoint = Guid.initString("6fddc324-4e03-4bfe-b185-3d77768dc918"); pub const GUID_WICPixelFormat96bppRGBFloat = Guid.initString("e3fed78f-e8db-4acf-84c1-e97f6136b327"); pub const GUID_WICPixelFormat128bppRGBAFloat = Guid.initString("6fddc324-4e03-4bfe-b185-3d77768dc919"); pub const GUID_WICPixelFormat128bppPRGBAFloat = Guid.initString("6fddc324-4e03-4bfe-b185-3d77768dc91a"); pub const GUID_WICPixelFormat128bppRGBFloat = Guid.initString("6fddc324-4e03-4bfe-b185-3d77768dc91b"); pub const GUID_WICPixelFormat32bppCMYK = Guid.initString("6fddc324-4e03-4bfe-b185-3d77768dc91c"); pub const GUID_WICPixelFormat64bppRGBAFixedPoint = Guid.initString("6fddc324-4e03-4bfe-b185-3d77768dc91d"); pub const GUID_WICPixelFormat64bppBGRAFixedPoint = Guid.initString("356de33c-54d2-4a23-bb04-9b7bf9b1d42d"); pub const GUID_WICPixelFormat64bppRGBFixedPoint = Guid.initString("6fddc324-4e03-4bfe-b185-3d77768dc940"); pub const GUID_WICPixelFormat128bppRGBAFixedPoint = Guid.initString("6fddc324-4e03-4bfe-b185-3d77768dc91e"); pub const GUID_WICPixelFormat128bppRGBFixedPoint = Guid.initString("6fddc324-4e03-4bfe-b185-3d77768dc941"); pub const GUID_WICPixelFormat64bppRGBAHalf = Guid.initString("6fddc324-4e03-4bfe-b185-3d77768dc93a"); pub const GUID_WICPixelFormat64bppPRGBAHalf = Guid.initString("58ad26c2-c623-4d9d-b320-387e49f8c442"); pub const GUID_WICPixelFormat64bppRGBHalf = Guid.initString("6fddc324-4e03-4bfe-b185-3d77768dc942"); pub const GUID_WICPixelFormat48bppRGBHalf = Guid.initString("6fddc324-4e03-4bfe-b185-3d77768dc93b"); pub const GUID_WICPixelFormat32bppRGBE = Guid.initString("6fddc324-4e03-4bfe-b185-3d77768dc93d"); pub const GUID_WICPixelFormat16bppGrayHalf = Guid.initString("6fddc324-4e03-4bfe-b185-3d77768dc93e"); pub const GUID_WICPixelFormat32bppGrayFixedPoint = Guid.initString("6fddc324-4e03-4bfe-b185-3d77768dc93f"); pub const GUID_WICPixelFormat32bppRGBA1010102 = Guid.initString("25238d72-fcf9-4522-b514-5578e5ad55e0"); pub const GUID_WICPixelFormat32bppRGBA1010102XR = Guid.initString("00de6b9a-c101-434b-b502-d0165ee1122c"); pub const GUID_WICPixelFormat32bppR10G10B10A2 = Guid.initString("604e1bb5-8a3c-4b65-b11c-bc0b8dd75b7f"); pub const GUID_WICPixelFormat32bppR10G10B10A2HDR10 = Guid.initString("9c215c5d-1acc-4f0e-a4bc-70fb3ae8fd28"); pub const GUID_WICPixelFormat64bppCMYK = Guid.initString("6fddc324-4e03-4bfe-b185-3d77768dc91f"); pub const GUID_WICPixelFormat24bpp3Channels = Guid.initString("6fddc324-4e03-4bfe-b185-3d77768dc920"); pub const GUID_WICPixelFormat32bpp4Channels = Guid.initString("6fddc324-4e03-4bfe-b185-3d77768dc921"); pub const GUID_WICPixelFormat40bpp5Channels = Guid.initString("6fddc324-4e03-4bfe-b185-3d77768dc922"); pub const GUID_WICPixelFormat48bpp6Channels = Guid.initString("6fddc324-4e03-4bfe-b185-3d77768dc923"); pub const GUID_WICPixelFormat56bpp7Channels = Guid.initString("6fddc324-4e03-4bfe-b185-3d77768dc924"); pub const GUID_WICPixelFormat64bpp8Channels = Guid.initString("6fddc324-4e03-4bfe-b185-3d77768dc925"); pub const GUID_WICPixelFormat48bpp3Channels = Guid.initString("6fddc324-4e03-4bfe-b185-3d77768dc926"); pub const GUID_WICPixelFormat64bpp4Channels = Guid.initString("6fddc324-4e03-4bfe-b185-3d77768dc927"); pub const GUID_WICPixelFormat80bpp5Channels = Guid.initString("6fddc324-4e03-4bfe-b185-3d77768dc928"); pub const GUID_WICPixelFormat96bpp6Channels = Guid.initString("6fddc324-4e03-4bfe-b185-3d77768dc929"); pub const GUID_WICPixelFormat112bpp7Channels = Guid.initString("6fddc324-4e03-4bfe-b185-3d77768dc92a"); pub const GUID_WICPixelFormat128bpp8Channels = Guid.initString("6fddc324-4e03-4bfe-b185-3d77768dc92b"); pub const GUID_WICPixelFormat40bppCMYKAlpha = Guid.initString("6fddc324-4e03-4bfe-b185-3d77768dc92c"); pub const GUID_WICPixelFormat80bppCMYKAlpha = Guid.initString("6fddc324-4e03-4bfe-b185-3d77768dc92d"); pub const GUID_WICPixelFormat32bpp3ChannelsAlpha = Guid.initString("6fddc324-4e03-4bfe-b185-3d77768dc92e"); pub const GUID_WICPixelFormat40bpp4ChannelsAlpha = Guid.initString("6fddc324-4e03-4bfe-b185-3d77768dc92f"); pub const GUID_WICPixelFormat48bpp5ChannelsAlpha = Guid.initString("6fddc324-4e03-4bfe-b185-3d77768dc930"); pub const GUID_WICPixelFormat56bpp6ChannelsAlpha = Guid.initString("6fddc324-4e03-4bfe-b185-3d77768dc931"); pub const GUID_WICPixelFormat64bpp7ChannelsAlpha = Guid.initString("6fddc324-4e03-4bfe-b185-3d77768dc932"); pub const GUID_WICPixelFormat72bpp8ChannelsAlpha = Guid.initString("6fddc324-4e03-4bfe-b185-3d77768dc933"); pub const GUID_WICPixelFormat64bpp3ChannelsAlpha = Guid.initString("6fddc324-4e03-4bfe-b185-3d77768dc934"); pub const GUID_WICPixelFormat80bpp4ChannelsAlpha = Guid.initString("6fddc324-4e03-4bfe-b185-3d77768dc935"); pub const GUID_WICPixelFormat96bpp5ChannelsAlpha = Guid.initString("6fddc324-4e03-4bfe-b185-3d77768dc936"); pub const GUID_WICPixelFormat112bpp6ChannelsAlpha = Guid.initString("6fddc324-4e03-4bfe-b185-3d77768dc937"); pub const GUID_WICPixelFormat128bpp7ChannelsAlpha = Guid.initString("6fddc324-4e03-4bfe-b185-3d77768dc938"); pub const GUID_WICPixelFormat144bpp8ChannelsAlpha = Guid.initString("6fddc324-4e03-4bfe-b185-3d77768dc939"); pub const GUID_WICPixelFormat8bppY = Guid.initString("91b4db54-2df9-42f0-b449-2909bb3df88e"); pub const GUID_WICPixelFormat8bppCb = Guid.initString("1339f224-6bfe-4c3e-9302-e4f3a6d0ca2a"); pub const GUID_WICPixelFormat8bppCr = Guid.initString("b8145053-2116-49f0-8835-ed844b205c51"); pub const GUID_WICPixelFormat16bppCbCr = Guid.initString("ff95ba6e-11e0-4263-bb45-01721f3460a4"); pub const GUID_WICPixelFormat16bppYQuantizedDctCoefficients = Guid.initString("a355f433-48e8-4a42-84d8-e2aa26ca80a4"); pub const GUID_WICPixelFormat16bppCbQuantizedDctCoefficients = Guid.initString("d2c4ff61-56a5-49c2-8b5c-4c1925964837"); pub const GUID_WICPixelFormat16bppCrQuantizedDctCoefficients = Guid.initString("2fe354f0-1680-42d8-9231-e73c0565bfc1"); pub const FACILITY_WINCODEC_ERR = @as(u32, 2200); pub const WINCODEC_ERR_BASE = @as(u32, 8192); pub const WINCODEC_ERR_GENERIC_ERROR = @as(i32, -2147467259); pub const WINCODEC_ERR_INVALIDPARAMETER = @as(i32, -2147024809); pub const WINCODEC_ERR_OUTOFMEMORY = @as(i32, -2147024882); pub const WINCODEC_ERR_NOTIMPLEMENTED = @as(i32, -2147467263); pub const WINCODEC_ERR_ABORTED = @as(i32, -2147467260); pub const WINCODEC_ERR_ACCESSDENIED = @as(i32, -2147024891); pub const WICRawChangeNotification_ExposureCompensation = @as(u32, 1); pub const WICRawChangeNotification_NamedWhitePoint = @as(u32, 2); pub const WICRawChangeNotification_KelvinWhitePoint = @as(u32, 4); pub const WICRawChangeNotification_RGBWhitePoint = @as(u32, 8); pub const WICRawChangeNotification_Contrast = @as(u32, 16); pub const WICRawChangeNotification_Gamma = @as(u32, 32); pub const WICRawChangeNotification_Sharpness = @as(u32, 64); pub const WICRawChangeNotification_Saturation = @as(u32, 128); pub const WICRawChangeNotification_Tint = @as(u32, 256); pub const WICRawChangeNotification_NoiseReduction = @as(u32, 512); pub const WICRawChangeNotification_DestinationColorContext = @as(u32, 1024); pub const WICRawChangeNotification_ToneCurve = @as(u32, 2048); pub const WICRawChangeNotification_Rotation = @as(u32, 4096); pub const WICRawChangeNotification_RenderMode = @as(u32, 8192); pub const GUID_MetadataFormatUnknown = Guid.initString("a45e592f-9078-4a7c-adb5-4edc4fd61b1f"); pub const GUID_MetadataFormatIfd = Guid.initString("537396c6-2d8a-4bb6-9bf8-2f0a8e2a3adf"); pub const GUID_MetadataFormatSubIfd = Guid.initString("58a2e128-2db9-4e57-bb14-5177891ed331"); pub const GUID_MetadataFormatExif = Guid.initString("1c3c4f9d-b84a-467d-9493-36cfbd59ea57"); pub const GUID_MetadataFormatGps = Guid.initString("7134ab8a-9351-44ad-af62-448db6b502ec"); pub const GUID_MetadataFormatInterop = Guid.initString("ed686f8e-681f-4c8b-bd41-a8addbf6b3fc"); pub const GUID_MetadataFormatApp0 = Guid.initString("79007028-268d-45d6-a3c2-354e6a504bc9"); pub const GUID_MetadataFormatApp1 = Guid.initString("8fd3dfc3-f951-492b-817f-69c2e6d9a5b0"); pub const GUID_MetadataFormatApp13 = Guid.initString("326556a2-f502-4354-9cc0-8e3f48eaf6b5"); pub const GUID_MetadataFormatIPTC = Guid.initString("4fab0914-e129-4087-a1d1-bc812d45a7b5"); pub const GUID_MetadataFormatIRB = Guid.initString("16100d66-8570-4bb9-b92d-fda4b23ece67"); pub const GUID_MetadataFormat8BIMIPTC = Guid.initString("0010568c-0852-4e6a-b191-5c33ac5b0430"); pub const GUID_MetadataFormat8BIMResolutionInfo = Guid.initString("739f305d-81db-43cb-ac5e-55013ef9f003"); pub const GUID_MetadataFormat8BIMIPTCDigest = Guid.initString("1ca32285-9ccd-4786-8bd8-79539db6a006"); pub const GUID_MetadataFormatXMP = Guid.initString("bb5acc38-f216-4cec-a6c5-5f6e739763a9"); pub const GUID_MetadataFormatThumbnail = Guid.initString("243dcee9-8703-40ee-8ef0-22a600b8058c"); pub const GUID_MetadataFormatChunktEXt = Guid.initString("568d8936-c0a9-4923-905d-df2b38238fbc"); pub const GUID_MetadataFormatXMPStruct = Guid.initString("22383cf1-ed17-4e2e-af17-d85b8f6b30d0"); pub const GUID_MetadataFormatXMPBag = Guid.initString("833cca5f-dcb7-4516-806f-6596ab26dce4"); pub const GUID_MetadataFormatXMPSeq = Guid.initString("63e8df02-eb6c-456c-a224-b25e794fd648"); pub const GUID_MetadataFormatXMPAlt = Guid.initString("7b08a675-91aa-481b-a798-4da94908613b"); pub const GUID_MetadataFormatLSD = Guid.initString("e256031e-6299-4929-b98d-5ac884afba92"); pub const GUID_MetadataFormatIMD = Guid.initString("bd2bb086-4d52-48dd-9677-db483e85ae8f"); pub const GUID_MetadataFormatGCE = Guid.initString("2a25cad8-deeb-4c69-a788-0ec2266dcafd"); pub const GUID_MetadataFormatAPE = Guid.initString("2e043dc2-c967-4e05-875e-618bf67e85c3"); pub const GUID_MetadataFormatJpegChrominance = Guid.initString("f73d0dcf-cec6-4f85-9b0e-1c3956b1bef7"); pub const GUID_MetadataFormatJpegLuminance = Guid.initString("86908007-edfc-4860-8d4b-4ee6e83e6058"); pub const GUID_MetadataFormatJpegComment = Guid.initString("220e5f33-afd3-474e-9d31-7d4fe730f557"); pub const GUID_MetadataFormatGifComment = Guid.initString("c4b6e0e0-cfb4-4ad3-ab33-9aad2355a34a"); pub const GUID_MetadataFormatChunkgAMA = Guid.initString("f00935a5-1d5d-4cd1-81b2-9324d7eca781"); pub const GUID_MetadataFormatChunkbKGD = Guid.initString("e14d3571-6b47-4dea-b60a-87ce0a78dfb7"); pub const GUID_MetadataFormatChunkiTXt = Guid.initString("c2bec729-0b68-4b77-aa0e-6295a6ac1814"); pub const GUID_MetadataFormatChunkcHRM = Guid.initString("9db3655b-2842-44b3-8067-12e9b375556a"); pub const GUID_MetadataFormatChunkhIST = Guid.initString("c59a82da-db74-48a4-bd6a-b69c4931ef95"); pub const GUID_MetadataFormatChunkiCCP = Guid.initString("eb4349ab-b685-450f-91b5-e802e892536c"); pub const GUID_MetadataFormatChunksRGB = Guid.initString("c115fd36-cc6f-4e3f-8363-524b87c6b0d9"); pub const GUID_MetadataFormatChunktIME = Guid.initString("6b00ae2d-e24b-460a-98b6-878bd03072fd"); pub const GUID_MetadataFormatDds = Guid.initString("4a064603-8c33-4e60-9c29-136231702d08"); pub const GUID_MetadataFormatHeif = Guid.initString("817ef3e1-1288-45f4-a852-260d9e7cce83"); pub const GUID_MetadataFormatHeifHDR = Guid.initString("568b8d8a-1e65-438c-8968-d60e1012beb9"); pub const GUID_MetadataFormatWebpANIM = Guid.initString("6dc4fda6-78e6-4102-ae35-bcfa1edcc78b"); pub const GUID_MetadataFormatWebpANMF = Guid.initString("43c105ee-b93b-4abb-b003-a08c0d870471"); pub const CLSID_WICUnknownMetadataReader = Guid.initString("699745c2-5066-4b82-a8e3-d40478dbec8c"); pub const CLSID_WICUnknownMetadataWriter = Guid.initString("a09cca86-27ba-4f39-9053-121fa4dc08fc"); pub const CLSID_WICApp0MetadataWriter = Guid.initString("f3c633a2-46c8-498e-8fbb-cc6f721bbcde"); pub const CLSID_WICApp0MetadataReader = Guid.initString("43324b33-a78f-480f-9111-9638aaccc832"); pub const CLSID_WICApp1MetadataWriter = Guid.initString("ee366069-1832-420f-b381-0479ad066f19"); pub const CLSID_WICApp1MetadataReader = Guid.initString("dde33513-774e-4bcd-ae79-02f4adfe62fc"); pub const CLSID_WICApp13MetadataWriter = Guid.initString("7b19a919-a9d6-49e5-bd45-02c34e4e4cd5"); pub const CLSID_WICApp13MetadataReader = Guid.initString("aa7e3c50-864c-4604-bc04-8b0b76e637f6"); pub const CLSID_WICIfdMetadataReader = Guid.initString("8f914656-9d0a-4eb2-9019-0bf96d8a9ee6"); pub const CLSID_WICIfdMetadataWriter = Guid.initString("b1ebfc28-c9bd-47a2-8d33-b948769777a7"); pub const CLSID_WICSubIfdMetadataReader = Guid.initString("50d42f09-ecd1-4b41-b65d-da1fdaa75663"); pub const CLSID_WICSubIfdMetadataWriter = Guid.initString("8ade5386-8e9b-4f4c-acf2-f0008706b238"); pub const CLSID_WICExifMetadataReader = Guid.initString("d9403860-297f-4a49-bf9b-77898150a442"); pub const CLSID_WICExifMetadataWriter = Guid.initString("c9a14cda-c339-460b-9078-d4debcfabe91"); pub const CLSID_WICGpsMetadataReader = Guid.initString("3697790b-223b-484e-9925-c4869218f17a"); pub const CLSID_WICGpsMetadataWriter = Guid.initString("cb8c13e4-62b5-4c96-a48b-6ba6ace39c76"); pub const CLSID_WICInteropMetadataReader = Guid.initString("b5c8b898-0074-459f-b700-860d4651ea14"); pub const CLSID_WICInteropMetadataWriter = Guid.initString("122ec645-cd7e-44d8-b186-2c8c20c3b50f"); pub const CLSID_WICThumbnailMetadataReader = Guid.initString("fb012959-f4f6-44d7-9d09-daa087a9db57"); pub const CLSID_WICThumbnailMetadataWriter = Guid.initString("d049b20c-5dd0-44fe-b0b3-8f92c8e6d080"); pub const CLSID_WICIPTCMetadataReader = Guid.initString("03012959-f4f6-44d7-9d09-daa087a9db57"); pub const CLSID_WICIPTCMetadataWriter = Guid.initString("1249b20c-5dd0-44fe-b0b3-8f92c8e6d080"); pub const CLSID_WICIRBMetadataReader = Guid.initString("d4dcd3d7-b4c2-47d9-a6bf-b89ba396a4a3"); pub const CLSID_WICIRBMetadataWriter = Guid.initString("5c5c1935-0235-4434-80bc-251bc1ec39c6"); pub const CLSID_WIC8BIMIPTCMetadataReader = Guid.initString("0010668c-0801-4da6-a4a4-826522b6d28f"); pub const CLSID_WIC8BIMIPTCMetadataWriter = Guid.initString("00108226-ee41-44a2-9e9c-4be4d5b1d2cd"); pub const CLSID_WIC8BIMResolutionInfoMetadataReader = Guid.initString("5805137a-e348-4f7c-b3cc-6db9965a0599"); pub const CLSID_WIC8BIMResolutionInfoMetadataWriter = Guid.initString("4ff2fe0e-e74a-4b71-98c4-ab7dc16707ba"); pub const CLSID_WIC8BIMIPTCDigestMetadataReader = Guid.initString("02805f1e-d5aa-415b-82c5-61c033a988a6"); pub const CLSID_WIC8BIMIPTCDigestMetadataWriter = Guid.initString("2db5e62b-0d67-495f-8f9d-c2f0188647ac"); pub const CLSID_WICPngTextMetadataReader = Guid.initString("4b59afcc-b8c3-408a-b670-89e5fab6fda7"); pub const CLSID_WICPngTextMetadataWriter = Guid.initString("b5ebafb9-253e-4a72-a744-0762d2685683"); pub const CLSID_WICXMPMetadataReader = Guid.initString("72b624df-ae11-4948-a65c-351eb0829419"); pub const CLSID_WICXMPMetadataWriter = Guid.initString("1765e14e-1bd4-462e-b6b1-590bf1262ac6"); pub const CLSID_WICXMPStructMetadataReader = Guid.initString("01b90d9a-8209-47f7-9c52-e1244bf50ced"); pub const CLSID_WICXMPStructMetadataWriter = Guid.initString("22c21f93-7ddb-411c-9b17-c5b7bd064abc"); pub const CLSID_WICXMPBagMetadataReader = Guid.initString("e7e79a30-4f2c-4fab-8d00-394f2d6bbebe"); pub const CLSID_WICXMPBagMetadataWriter = Guid.initString("ed822c8c-d6be-4301-a631-0e1416bad28f"); pub const CLSID_WICXMPSeqMetadataReader = Guid.initString("7f12e753-fc71-43d7-a51d-92f35977abb5"); pub const CLSID_WICXMPSeqMetadataWriter = Guid.initString("6d68d1de-d432-4b0f-923a-091183a9bda7"); pub const CLSID_WICXMPAltMetadataReader = Guid.initString("aa94dcc2-b8b0-4898-b835-000aabd74393"); pub const CLSID_WICXMPAltMetadataWriter = Guid.initString("076c2a6c-f78f-4c46-a723-3583e70876ea"); pub const CLSID_WICLSDMetadataReader = Guid.initString("41070793-59e4-479a-a1f7-954adc2ef5fc"); pub const CLSID_WICLSDMetadataWriter = Guid.initString("73c037e7-e5d9-4954-876a-6da81d6e5768"); pub const CLSID_WICGCEMetadataReader = Guid.initString("b92e345d-f52d-41f3-b562-081bc772e3b9"); pub const CLSID_WICGCEMetadataWriter = Guid.initString("af95dc76-16b2-47f4-b3ea-3c31796693e7"); pub const CLSID_WICIMDMetadataReader = Guid.initString("7447a267-0015-42c8-a8f1-fb3b94c68361"); pub const CLSID_WICIMDMetadataWriter = Guid.initString("8c89071f-452e-4e95-9682-9d1024627172"); pub const CLSID_WICAPEMetadataReader = Guid.initString("1767b93a-b021-44ea-920f-863c11f4f768"); pub const CLSID_WICAPEMetadataWriter = Guid.initString("bd6edfca-2890-482f-b233-8d7339a1cf8d"); pub const CLSID_WICJpegChrominanceMetadataReader = Guid.initString("50b1904b-f28f-4574-93f4-0bade82c69e9"); pub const CLSID_WICJpegChrominanceMetadataWriter = Guid.initString("3ff566f0-6e6b-49d4-96e6-b78886692c62"); pub const CLSID_WICJpegLuminanceMetadataReader = Guid.initString("356f2f88-05a6-4728-b9a4-1bfbce04d838"); pub const CLSID_WICJpegLuminanceMetadataWriter = Guid.initString("1d583abc-8a0e-4657-9982-a380ca58fb4b"); pub const CLSID_WICJpegCommentMetadataReader = Guid.initString("9f66347c-60c4-4c4d-ab58-d2358685f607"); pub const CLSID_WICJpegCommentMetadataWriter = Guid.initString("e573236f-55b1-4eda-81ea-9f65db0290d3"); pub const CLSID_WICGifCommentMetadataReader = Guid.initString("32557d3b-69dc-4f95-836e-f5972b2f6159"); pub const CLSID_WICGifCommentMetadataWriter = Guid.initString("a02797fc-c4ae-418c-af95-e637c7ead2a1"); pub const CLSID_WICPngGamaMetadataReader = Guid.initString("3692ca39-e082-4350-9e1f-3704cb083cd5"); pub const CLSID_WICPngGamaMetadataWriter = Guid.initString("ff036d13-5d4b-46dd-b10f-106693d9fe4f"); pub const CLSID_WICPngBkgdMetadataReader = Guid.initString("0ce7a4a6-03e8-4a60-9d15-282ef32ee7da"); pub const CLSID_WICPngBkgdMetadataWriter = Guid.initString("68e3f2fd-31ae-4441-bb6a-fd7047525f90"); pub const CLSID_WICPngItxtMetadataReader = Guid.initString("aabfb2fa-3e1e-4a8f-8977-5556fb94ea23"); pub const CLSID_WICPngItxtMetadataWriter = Guid.initString("31879719-e751-4df8-981d-68dff67704ed"); pub const CLSID_WICPngChrmMetadataReader = Guid.initString("f90b5f36-367b-402a-9dd1-bc0fd59d8f62"); pub const CLSID_WICPngChrmMetadataWriter = Guid.initString("e23ce3eb-5608-4e83-bcef-27b1987e51d7"); pub const CLSID_WICPngHistMetadataReader = Guid.initString("877a0bb7-a313-4491-87b5-2e6d0594f520"); pub const CLSID_WICPngHistMetadataWriter = Guid.initString("8a03e749-672e-446e-bf1f-2c11d233b6ff"); pub const CLSID_WICPngIccpMetadataReader = Guid.initString("f5d3e63b-cb0f-4628-a478-6d8244be36b1"); pub const CLSID_WICPngIccpMetadataWriter = Guid.initString("16671e5f-0ce6-4cc4-9768-e89fe5018ade"); pub const CLSID_WICPngSrgbMetadataReader = Guid.initString("fb40360c-547e-4956-a3b9-d4418859ba66"); pub const CLSID_WICPngSrgbMetadataWriter = Guid.initString("a6ee35c6-87ec-47df-9f22-1d5aad840c82"); pub const CLSID_WICPngTimeMetadataReader = Guid.initString("d94edf02-efe5-4f0d-85c8-f5a68b3000b1"); pub const CLSID_WICPngTimeMetadataWriter = Guid.initString("1ab78400-b5a3-4d91-8ace-33fcd1499be6"); pub const CLSID_WICDdsMetadataReader = Guid.initString("276c88ca-7533-4a86-b676-66b36080d484"); pub const CLSID_WICDdsMetadataWriter = Guid.initString("fd688bbd-31ed-4db7-a723-934927d38367"); pub const CLSID_WICHeifMetadataReader = Guid.initString("acddfc3f-85ec-41bc-bdef-1bc262e4db05"); pub const CLSID_WICHeifMetadataWriter = Guid.initString("3ae45e79-40bc-4401-ace5-dd3cb16e6afe"); pub const CLSID_WICHeifHDRMetadataReader = Guid.initString("2438de3d-94d9-4be8-84a8-4de95a575e75"); pub const CLSID_WICWebpAnimMetadataReader = Guid.initString("076f9911-a348-465c-a807-a252f3f2d3de"); pub const CLSID_WICWebpAnmfMetadataReader = Guid.initString("85a10b03-c9f6-439f-be5e-c0fbef67807c"); //-------------------------------------------------------------------------------- // Section: Types (123) //-------------------------------------------------------------------------------- pub const WICRect = extern struct { X: i32, Y: i32, Width: i32, Height: i32, }; pub const WICColorContextType = enum(i32) { Uninitialized = 0, Profile = 1, ExifColorSpace = 2, }; pub const WICColorContextUninitialized = WICColorContextType.Uninitialized; pub const WICColorContextProfile = WICColorContextType.Profile; pub const WICColorContextExifColorSpace = WICColorContextType.ExifColorSpace; pub const WICBitmapCreateCacheOption = enum(i32) { itmapNoCache = 0, itmapCacheOnDemand = 1, itmapCacheOnLoad = 2, ITMAPCREATECACHEOPTION_FORCE_DWORD = 2147483647, }; pub const WICBitmapNoCache = WICBitmapCreateCacheOption.itmapNoCache; pub const WICBitmapCacheOnDemand = WICBitmapCreateCacheOption.itmapCacheOnDemand; pub const WICBitmapCacheOnLoad = WICBitmapCreateCacheOption.itmapCacheOnLoad; pub const WICBITMAPCREATECACHEOPTION_FORCE_DWORD = WICBitmapCreateCacheOption.ITMAPCREATECACHEOPTION_FORCE_DWORD; pub const WICDecodeOptions = enum(i32) { DecodeMetadataCacheOnDemand = 0, DecodeMetadataCacheOnLoad = 1, METADATACACHEOPTION_FORCE_DWORD = 2147483647, }; pub const WICDecodeMetadataCacheOnDemand = WICDecodeOptions.DecodeMetadataCacheOnDemand; pub const WICDecodeMetadataCacheOnLoad = WICDecodeOptions.DecodeMetadataCacheOnLoad; pub const WICMETADATACACHEOPTION_FORCE_DWORD = WICDecodeOptions.METADATACACHEOPTION_FORCE_DWORD; pub const WICBitmapEncoderCacheOption = enum(i32) { itmapEncoderCacheInMemory = 0, itmapEncoderCacheTempFile = 1, itmapEncoderNoCache = 2, ITMAPENCODERCACHEOPTION_FORCE_DWORD = 2147483647, }; pub const WICBitmapEncoderCacheInMemory = WICBitmapEncoderCacheOption.itmapEncoderCacheInMemory; pub const WICBitmapEncoderCacheTempFile = WICBitmapEncoderCacheOption.itmapEncoderCacheTempFile; pub const WICBitmapEncoderNoCache = WICBitmapEncoderCacheOption.itmapEncoderNoCache; pub const WICBITMAPENCODERCACHEOPTION_FORCE_DWORD = WICBitmapEncoderCacheOption.ITMAPENCODERCACHEOPTION_FORCE_DWORD; pub const WICComponentType = enum(i32) { Decoder = 1, Encoder = 2, PixelFormatConverter = 4, MetadataReader = 8, MetadataWriter = 16, PixelFormat = 32, AllComponents = 63, COMPONENTTYPE_FORCE_DWORD = 2147483647, }; pub const WICDecoder = WICComponentType.Decoder; pub const WICEncoder = WICComponentType.Encoder; pub const WICPixelFormatConverter = WICComponentType.PixelFormatConverter; pub const WICMetadataReader = WICComponentType.MetadataReader; pub const WICMetadataWriter = WICComponentType.MetadataWriter; pub const WICPixelFormat = WICComponentType.PixelFormat; pub const WICAllComponents = WICComponentType.AllComponents; pub const WICCOMPONENTTYPE_FORCE_DWORD = WICComponentType.COMPONENTTYPE_FORCE_DWORD; pub const WICComponentEnumerateOptions = enum(i32) { omponentEnumerateDefault = 0, omponentEnumerateRefresh = 1, omponentEnumerateDisabled = -2147483648, omponentEnumerateUnsigned = 1073741824, omponentEnumerateBuiltInOnly = 536870912, OMPONENTENUMERATEOPTIONS_FORCE_DWORD = 2147483647, }; pub const WICComponentEnumerateDefault = WICComponentEnumerateOptions.omponentEnumerateDefault; pub const WICComponentEnumerateRefresh = WICComponentEnumerateOptions.omponentEnumerateRefresh; pub const WICComponentEnumerateDisabled = WICComponentEnumerateOptions.omponentEnumerateDisabled; pub const WICComponentEnumerateUnsigned = WICComponentEnumerateOptions.omponentEnumerateUnsigned; pub const WICComponentEnumerateBuiltInOnly = WICComponentEnumerateOptions.omponentEnumerateBuiltInOnly; pub const WICCOMPONENTENUMERATEOPTIONS_FORCE_DWORD = WICComponentEnumerateOptions.OMPONENTENUMERATEOPTIONS_FORCE_DWORD; pub const WICBitmapPattern = extern struct { Position: ULARGE_INTEGER, Length: u32, Pattern: ?*u8, Mask: ?*u8, EndOfStream: BOOL, }; pub const WICBitmapInterpolationMode = enum(i32) { itmapInterpolationModeNearestNeighbor = 0, itmapInterpolationModeLinear = 1, itmapInterpolationModeCubic = 2, itmapInterpolationModeFant = 3, itmapInterpolationModeHighQualityCubic = 4, ITMAPINTERPOLATIONMODE_FORCE_DWORD = 2147483647, }; pub const WICBitmapInterpolationModeNearestNeighbor = WICBitmapInterpolationMode.itmapInterpolationModeNearestNeighbor; pub const WICBitmapInterpolationModeLinear = WICBitmapInterpolationMode.itmapInterpolationModeLinear; pub const WICBitmapInterpolationModeCubic = WICBitmapInterpolationMode.itmapInterpolationModeCubic; pub const WICBitmapInterpolationModeFant = WICBitmapInterpolationMode.itmapInterpolationModeFant; pub const WICBitmapInterpolationModeHighQualityCubic = WICBitmapInterpolationMode.itmapInterpolationModeHighQualityCubic; pub const WICBITMAPINTERPOLATIONMODE_FORCE_DWORD = WICBitmapInterpolationMode.ITMAPINTERPOLATIONMODE_FORCE_DWORD; pub const WICBitmapPaletteType = enum(i32) { itmapPaletteTypeCustom = 0, itmapPaletteTypeMedianCut = 1, itmapPaletteTypeFixedBW = 2, itmapPaletteTypeFixedHalftone8 = 3, itmapPaletteTypeFixedHalftone27 = 4, itmapPaletteTypeFixedHalftone64 = 5, itmapPaletteTypeFixedHalftone125 = 6, itmapPaletteTypeFixedHalftone216 = 7, // itmapPaletteTypeFixedWebPalette = 7, this enum value conflicts with itmapPaletteTypeFixedHalftone216 itmapPaletteTypeFixedHalftone252 = 8, itmapPaletteTypeFixedHalftone256 = 9, itmapPaletteTypeFixedGray4 = 10, itmapPaletteTypeFixedGray16 = 11, itmapPaletteTypeFixedGray256 = 12, ITMAPPALETTETYPE_FORCE_DWORD = 2147483647, }; pub const WICBitmapPaletteTypeCustom = WICBitmapPaletteType.itmapPaletteTypeCustom; pub const WICBitmapPaletteTypeMedianCut = WICBitmapPaletteType.itmapPaletteTypeMedianCut; pub const WICBitmapPaletteTypeFixedBW = WICBitmapPaletteType.itmapPaletteTypeFixedBW; pub const WICBitmapPaletteTypeFixedHalftone8 = WICBitmapPaletteType.itmapPaletteTypeFixedHalftone8; pub const WICBitmapPaletteTypeFixedHalftone27 = WICBitmapPaletteType.itmapPaletteTypeFixedHalftone27; pub const WICBitmapPaletteTypeFixedHalftone64 = WICBitmapPaletteType.itmapPaletteTypeFixedHalftone64; pub const WICBitmapPaletteTypeFixedHalftone125 = WICBitmapPaletteType.itmapPaletteTypeFixedHalftone125; pub const WICBitmapPaletteTypeFixedHalftone216 = WICBitmapPaletteType.itmapPaletteTypeFixedHalftone216; pub const WICBitmapPaletteTypeFixedWebPalette = WICBitmapPaletteType.itmapPaletteTypeFixedHalftone216; pub const WICBitmapPaletteTypeFixedHalftone252 = WICBitmapPaletteType.itmapPaletteTypeFixedHalftone252; pub const WICBitmapPaletteTypeFixedHalftone256 = WICBitmapPaletteType.itmapPaletteTypeFixedHalftone256; pub const WICBitmapPaletteTypeFixedGray4 = WICBitmapPaletteType.itmapPaletteTypeFixedGray4; pub const WICBitmapPaletteTypeFixedGray16 = WICBitmapPaletteType.itmapPaletteTypeFixedGray16; pub const WICBitmapPaletteTypeFixedGray256 = WICBitmapPaletteType.itmapPaletteTypeFixedGray256; pub const WICBITMAPPALETTETYPE_FORCE_DWORD = WICBitmapPaletteType.ITMAPPALETTETYPE_FORCE_DWORD; pub const WICBitmapDitherType = enum(i32) { itmapDitherTypeNone = 0, // itmapDitherTypeSolid = 0, this enum value conflicts with itmapDitherTypeNone itmapDitherTypeOrdered4x4 = 1, itmapDitherTypeOrdered8x8 = 2, itmapDitherTypeOrdered16x16 = 3, itmapDitherTypeSpiral4x4 = 4, itmapDitherTypeSpiral8x8 = 5, itmapDitherTypeDualSpiral4x4 = 6, itmapDitherTypeDualSpiral8x8 = 7, itmapDitherTypeErrorDiffusion = 8, ITMAPDITHERTYPE_FORCE_DWORD = 2147483647, }; pub const WICBitmapDitherTypeNone = WICBitmapDitherType.itmapDitherTypeNone; pub const WICBitmapDitherTypeSolid = WICBitmapDitherType.itmapDitherTypeNone; pub const WICBitmapDitherTypeOrdered4x4 = WICBitmapDitherType.itmapDitherTypeOrdered4x4; pub const WICBitmapDitherTypeOrdered8x8 = WICBitmapDitherType.itmapDitherTypeOrdered8x8; pub const WICBitmapDitherTypeOrdered16x16 = WICBitmapDitherType.itmapDitherTypeOrdered16x16; pub const WICBitmapDitherTypeSpiral4x4 = WICBitmapDitherType.itmapDitherTypeSpiral4x4; pub const WICBitmapDitherTypeSpiral8x8 = WICBitmapDitherType.itmapDitherTypeSpiral8x8; pub const WICBitmapDitherTypeDualSpiral4x4 = WICBitmapDitherType.itmapDitherTypeDualSpiral4x4; pub const WICBitmapDitherTypeDualSpiral8x8 = WICBitmapDitherType.itmapDitherTypeDualSpiral8x8; pub const WICBitmapDitherTypeErrorDiffusion = WICBitmapDitherType.itmapDitherTypeErrorDiffusion; pub const WICBITMAPDITHERTYPE_FORCE_DWORD = WICBitmapDitherType.ITMAPDITHERTYPE_FORCE_DWORD; pub const WICBitmapAlphaChannelOption = enum(i32) { itmapUseAlpha = 0, itmapUsePremultipliedAlpha = 1, itmapIgnoreAlpha = 2, ITMAPALPHACHANNELOPTIONS_FORCE_DWORD = 2147483647, }; pub const WICBitmapUseAlpha = WICBitmapAlphaChannelOption.itmapUseAlpha; pub const WICBitmapUsePremultipliedAlpha = WICBitmapAlphaChannelOption.itmapUsePremultipliedAlpha; pub const WICBitmapIgnoreAlpha = WICBitmapAlphaChannelOption.itmapIgnoreAlpha; pub const WICBITMAPALPHACHANNELOPTIONS_FORCE_DWORD = WICBitmapAlphaChannelOption.ITMAPALPHACHANNELOPTIONS_FORCE_DWORD; pub const WICBitmapTransformOptions = enum(i32) { itmapTransformRotate0 = 0, itmapTransformRotate90 = 1, itmapTransformRotate180 = 2, itmapTransformRotate270 = 3, itmapTransformFlipHorizontal = 8, itmapTransformFlipVertical = 16, ITMAPTRANSFORMOPTIONS_FORCE_DWORD = 2147483647, }; pub const WICBitmapTransformRotate0 = WICBitmapTransformOptions.itmapTransformRotate0; pub const WICBitmapTransformRotate90 = WICBitmapTransformOptions.itmapTransformRotate90; pub const WICBitmapTransformRotate180 = WICBitmapTransformOptions.itmapTransformRotate180; pub const WICBitmapTransformRotate270 = WICBitmapTransformOptions.itmapTransformRotate270; pub const WICBitmapTransformFlipHorizontal = WICBitmapTransformOptions.itmapTransformFlipHorizontal; pub const WICBitmapTransformFlipVertical = WICBitmapTransformOptions.itmapTransformFlipVertical; pub const WICBITMAPTRANSFORMOPTIONS_FORCE_DWORD = WICBitmapTransformOptions.ITMAPTRANSFORMOPTIONS_FORCE_DWORD; pub const WICBitmapLockFlags = enum(i32) { itmapLockRead = 1, itmapLockWrite = 2, ITMAPLOCKFLAGS_FORCE_DWORD = 2147483647, }; pub const WICBitmapLockRead = WICBitmapLockFlags.itmapLockRead; pub const WICBitmapLockWrite = WICBitmapLockFlags.itmapLockWrite; pub const WICBITMAPLOCKFLAGS_FORCE_DWORD = WICBitmapLockFlags.ITMAPLOCKFLAGS_FORCE_DWORD; pub const WICBitmapDecoderCapabilities = enum(i32) { itmapDecoderCapabilitySameEncoder = 1, itmapDecoderCapabilityCanDecodeAllImages = 2, itmapDecoderCapabilityCanDecodeSomeImages = 4, itmapDecoderCapabilityCanEnumerateMetadata = 8, itmapDecoderCapabilityCanDecodeThumbnail = 16, ITMAPDECODERCAPABILITIES_FORCE_DWORD = 2147483647, }; pub const WICBitmapDecoderCapabilitySameEncoder = WICBitmapDecoderCapabilities.itmapDecoderCapabilitySameEncoder; pub const WICBitmapDecoderCapabilityCanDecodeAllImages = WICBitmapDecoderCapabilities.itmapDecoderCapabilityCanDecodeAllImages; pub const WICBitmapDecoderCapabilityCanDecodeSomeImages = WICBitmapDecoderCapabilities.itmapDecoderCapabilityCanDecodeSomeImages; pub const WICBitmapDecoderCapabilityCanEnumerateMetadata = WICBitmapDecoderCapabilities.itmapDecoderCapabilityCanEnumerateMetadata; pub const WICBitmapDecoderCapabilityCanDecodeThumbnail = WICBitmapDecoderCapabilities.itmapDecoderCapabilityCanDecodeThumbnail; pub const WICBITMAPDECODERCAPABILITIES_FORCE_DWORD = WICBitmapDecoderCapabilities.ITMAPDECODERCAPABILITIES_FORCE_DWORD; pub const WICProgressOperation = enum(i32) { rogressOperationCopyPixels = 1, rogressOperationWritePixels = 2, rogressOperationAll = 65535, ROGRESSOPERATION_FORCE_DWORD = 2147483647, }; pub const WICProgressOperationCopyPixels = WICProgressOperation.rogressOperationCopyPixels; pub const WICProgressOperationWritePixels = WICProgressOperation.rogressOperationWritePixels; pub const WICProgressOperationAll = WICProgressOperation.rogressOperationAll; pub const WICPROGRESSOPERATION_FORCE_DWORD = WICProgressOperation.ROGRESSOPERATION_FORCE_DWORD; pub const WICProgressNotification = enum(i32) { rogressNotificationBegin = 65536, rogressNotificationEnd = 131072, rogressNotificationFrequent = 262144, rogressNotificationAll = -65536, ROGRESSNOTIFICATION_FORCE_DWORD = 2147483647, }; pub const WICProgressNotificationBegin = WICProgressNotification.rogressNotificationBegin; pub const WICProgressNotificationEnd = WICProgressNotification.rogressNotificationEnd; pub const WICProgressNotificationFrequent = WICProgressNotification.rogressNotificationFrequent; pub const WICProgressNotificationAll = WICProgressNotification.rogressNotificationAll; pub const WICPROGRESSNOTIFICATION_FORCE_DWORD = WICProgressNotification.ROGRESSNOTIFICATION_FORCE_DWORD; pub const WICComponentSigning = enum(i32) { omponentSigned = 1, omponentUnsigned = 2, omponentSafe = 4, omponentDisabled = -2147483648, OMPONENTSIGNING_FORCE_DWORD = 2147483647, }; pub const WICComponentSigned = WICComponentSigning.omponentSigned; pub const WICComponentUnsigned = WICComponentSigning.omponentUnsigned; pub const WICComponentSafe = WICComponentSigning.omponentSafe; pub const WICComponentDisabled = WICComponentSigning.omponentDisabled; pub const WICCOMPONENTSIGNING_FORCE_DWORD = WICComponentSigning.OMPONENTSIGNING_FORCE_DWORD; pub const WICGifLogicalScreenDescriptorProperties = enum(u32) { Signature = 1, DescriptorWidth = 2, DescriptorHeight = 3, DescriptorGlobalColorTableFlag = 4, DescriptorColorResolution = 5, DescriptorSortFlag = 6, DescriptorGlobalColorTableSize = 7, DescriptorBackgroundColorIndex = 8, DescriptorPixelAspectRatio = 9, DescriptorProperties_FORCE_DWORD = 2147483647, }; pub const WICGifLogicalScreenSignature = WICGifLogicalScreenDescriptorProperties.Signature; pub const WICGifLogicalScreenDescriptorWidth = WICGifLogicalScreenDescriptorProperties.DescriptorWidth; pub const WICGifLogicalScreenDescriptorHeight = WICGifLogicalScreenDescriptorProperties.DescriptorHeight; pub const WICGifLogicalScreenDescriptorGlobalColorTableFlag = WICGifLogicalScreenDescriptorProperties.DescriptorGlobalColorTableFlag; pub const WICGifLogicalScreenDescriptorColorResolution = WICGifLogicalScreenDescriptorProperties.DescriptorColorResolution; pub const WICGifLogicalScreenDescriptorSortFlag = WICGifLogicalScreenDescriptorProperties.DescriptorSortFlag; pub const WICGifLogicalScreenDescriptorGlobalColorTableSize = WICGifLogicalScreenDescriptorProperties.DescriptorGlobalColorTableSize; pub const WICGifLogicalScreenDescriptorBackgroundColorIndex = WICGifLogicalScreenDescriptorProperties.DescriptorBackgroundColorIndex; pub const WICGifLogicalScreenDescriptorPixelAspectRatio = WICGifLogicalScreenDescriptorProperties.DescriptorPixelAspectRatio; pub const WICGifLogicalScreenDescriptorProperties_FORCE_DWORD = WICGifLogicalScreenDescriptorProperties.DescriptorProperties_FORCE_DWORD; pub const WICGifImageDescriptorProperties = enum(u32) { Left = 1, Top = 2, Width = 3, Height = 4, LocalColorTableFlag = 5, InterlaceFlag = 6, SortFlag = 7, LocalColorTableSize = 8, Properties_FORCE_DWORD = 2147483647, }; pub const WICGifImageDescriptorLeft = WICGifImageDescriptorProperties.Left; pub const WICGifImageDescriptorTop = WICGifImageDescriptorProperties.Top; pub const WICGifImageDescriptorWidth = WICGifImageDescriptorProperties.Width; pub const WICGifImageDescriptorHeight = WICGifImageDescriptorProperties.Height; pub const WICGifImageDescriptorLocalColorTableFlag = WICGifImageDescriptorProperties.LocalColorTableFlag; pub const WICGifImageDescriptorInterlaceFlag = WICGifImageDescriptorProperties.InterlaceFlag; pub const WICGifImageDescriptorSortFlag = WICGifImageDescriptorProperties.SortFlag; pub const WICGifImageDescriptorLocalColorTableSize = WICGifImageDescriptorProperties.LocalColorTableSize; pub const WICGifImageDescriptorProperties_FORCE_DWORD = WICGifImageDescriptorProperties.Properties_FORCE_DWORD; pub const WICGifGraphicControlExtensionProperties = enum(u32) { Disposal = 1, UserInputFlag = 2, TransparencyFlag = 3, Delay = 4, TransparentColorIndex = 5, Properties_FORCE_DWORD = 2147483647, }; pub const WICGifGraphicControlExtensionDisposal = WICGifGraphicControlExtensionProperties.Disposal; pub const WICGifGraphicControlExtensionUserInputFlag = WICGifGraphicControlExtensionProperties.UserInputFlag; pub const WICGifGraphicControlExtensionTransparencyFlag = WICGifGraphicControlExtensionProperties.TransparencyFlag; pub const WICGifGraphicControlExtensionDelay = WICGifGraphicControlExtensionProperties.Delay; pub const WICGifGraphicControlExtensionTransparentColorIndex = WICGifGraphicControlExtensionProperties.TransparentColorIndex; pub const WICGifGraphicControlExtensionProperties_FORCE_DWORD = WICGifGraphicControlExtensionProperties.Properties_FORCE_DWORD; pub const WICGifApplicationExtensionProperties = enum(u32) { Application = 1, Data = 2, Properties_FORCE_DWORD = 2147483647, }; pub const WICGifApplicationExtensionApplication = WICGifApplicationExtensionProperties.Application; pub const WICGifApplicationExtensionData = WICGifApplicationExtensionProperties.Data; pub const WICGifApplicationExtensionProperties_FORCE_DWORD = WICGifApplicationExtensionProperties.Properties_FORCE_DWORD; pub const WICGifCommentExtensionProperties = enum(u32) { Text = 1, Properties_FORCE_DWORD = 2147483647, }; pub const WICGifCommentExtensionText = WICGifCommentExtensionProperties.Text; pub const WICGifCommentExtensionProperties_FORCE_DWORD = WICGifCommentExtensionProperties.Properties_FORCE_DWORD; pub const WICJpegCommentProperties = enum(u32) { Text = 1, Properties_FORCE_DWORD = 2147483647, }; pub const WICJpegCommentText = WICJpegCommentProperties.Text; pub const WICJpegCommentProperties_FORCE_DWORD = WICJpegCommentProperties.Properties_FORCE_DWORD; pub const WICJpegLuminanceProperties = enum(u32) { Table = 1, Properties_FORCE_DWORD = 2147483647, }; pub const WICJpegLuminanceTable = WICJpegLuminanceProperties.Table; pub const WICJpegLuminanceProperties_FORCE_DWORD = WICJpegLuminanceProperties.Properties_FORCE_DWORD; pub const WICJpegChrominanceProperties = enum(u32) { Table = 1, Properties_FORCE_DWORD = 2147483647, }; pub const WICJpegChrominanceTable = WICJpegChrominanceProperties.Table; pub const WICJpegChrominanceProperties_FORCE_DWORD = WICJpegChrominanceProperties.Properties_FORCE_DWORD; pub const WIC8BIMIptcProperties = enum(u32) { PString = 0, EmbeddedIPTC = 1, Properties_FORCE_DWORD = 2147483647, }; pub const WIC8BIMIptcPString = WIC8BIMIptcProperties.PString; pub const WIC8BIMIptcEmbeddedIPTC = WIC8BIMIptcProperties.EmbeddedIPTC; pub const WIC8BIMIptcProperties_FORCE_DWORD = WIC8BIMIptcProperties.Properties_FORCE_DWORD; pub const WIC8BIMResolutionInfoProperties = enum(u32) { PString = 1, HResolution = 2, HResolutionUnit = 3, WidthUnit = 4, VResolution = 5, VResolutionUnit = 6, HeightUnit = 7, Properties_FORCE_DWORD = 2147483647, }; pub const WIC8BIMResolutionInfoPString = WIC8BIMResolutionInfoProperties.PString; pub const WIC8BIMResolutionInfoHResolution = WIC8BIMResolutionInfoProperties.HResolution; pub const WIC8BIMResolutionInfoHResolutionUnit = WIC8BIMResolutionInfoProperties.HResolutionUnit; pub const WIC8BIMResolutionInfoWidthUnit = WIC8BIMResolutionInfoProperties.WidthUnit; pub const WIC8BIMResolutionInfoVResolution = WIC8BIMResolutionInfoProperties.VResolution; pub const WIC8BIMResolutionInfoVResolutionUnit = WIC8BIMResolutionInfoProperties.VResolutionUnit; pub const WIC8BIMResolutionInfoHeightUnit = WIC8BIMResolutionInfoProperties.HeightUnit; pub const WIC8BIMResolutionInfoProperties_FORCE_DWORD = WIC8BIMResolutionInfoProperties.Properties_FORCE_DWORD; pub const WIC8BIMIptcDigestProperties = enum(u32) { PString = 1, IptcDigest = 2, Properties_FORCE_DWORD = 2147483647, }; pub const WIC8BIMIptcDigestPString = WIC8BIMIptcDigestProperties.PString; pub const WIC8BIMIptcDigestIptcDigest = WIC8BIMIptcDigestProperties.IptcDigest; pub const WIC8BIMIptcDigestProperties_FORCE_DWORD = WIC8BIMIptcDigestProperties.Properties_FORCE_DWORD; pub const WICPngGamaProperties = enum(u32) { Gamma = 1, Properties_FORCE_DWORD = 2147483647, }; pub const WICPngGamaGamma = WICPngGamaProperties.Gamma; pub const WICPngGamaProperties_FORCE_DWORD = WICPngGamaProperties.Properties_FORCE_DWORD; pub const WICPngBkgdProperties = enum(u32) { BackgroundColor = 1, Properties_FORCE_DWORD = 2147483647, }; pub const WICPngBkgdBackgroundColor = WICPngBkgdProperties.BackgroundColor; pub const WICPngBkgdProperties_FORCE_DWORD = WICPngBkgdProperties.Properties_FORCE_DWORD; pub const WICPngItxtProperties = enum(u32) { Keyword = 1, CompressionFlag = 2, LanguageTag = 3, TranslatedKeyword = 4, Text = 5, Properties_FORCE_DWORD = 2147483647, }; pub const WICPngItxtKeyword = WICPngItxtProperties.Keyword; pub const WICPngItxtCompressionFlag = WICPngItxtProperties.CompressionFlag; pub const WICPngItxtLanguageTag = WICPngItxtProperties.LanguageTag; pub const WICPngItxtTranslatedKeyword = WICPngItxtProperties.TranslatedKeyword; pub const WICPngItxtText = WICPngItxtProperties.Text; pub const WICPngItxtProperties_FORCE_DWORD = WICPngItxtProperties.Properties_FORCE_DWORD; pub const WICPngChrmProperties = enum(u32) { WhitePointX = 1, WhitePointY = 2, RedX = 3, RedY = 4, GreenX = 5, GreenY = 6, BlueX = 7, BlueY = 8, Properties_FORCE_DWORD = 2147483647, }; pub const WICPngChrmWhitePointX = WICPngChrmProperties.WhitePointX; pub const WICPngChrmWhitePointY = WICPngChrmProperties.WhitePointY; pub const WICPngChrmRedX = WICPngChrmProperties.RedX; pub const WICPngChrmRedY = WICPngChrmProperties.RedY; pub const WICPngChrmGreenX = WICPngChrmProperties.GreenX; pub const WICPngChrmGreenY = WICPngChrmProperties.GreenY; pub const WICPngChrmBlueX = WICPngChrmProperties.BlueX; pub const WICPngChrmBlueY = WICPngChrmProperties.BlueY; pub const WICPngChrmProperties_FORCE_DWORD = WICPngChrmProperties.Properties_FORCE_DWORD; pub const WICPngHistProperties = enum(u32) { Frequencies = 1, Properties_FORCE_DWORD = 2147483647, }; pub const WICPngHistFrequencies = WICPngHistProperties.Frequencies; pub const WICPngHistProperties_FORCE_DWORD = WICPngHistProperties.Properties_FORCE_DWORD; pub const WICPngIccpProperties = enum(u32) { fileName = 1, fileData = 2, perties_FORCE_DWORD = 2147483647, }; pub const WICPngIccpProfileName = WICPngIccpProperties.fileName; pub const WICPngIccpProfileData = WICPngIccpProperties.fileData; pub const WICPngIccpProperties_FORCE_DWORD = WICPngIccpProperties.perties_FORCE_DWORD; pub const WICPngSrgbProperties = enum(u32) { RenderingIntent = 1, Properties_FORCE_DWORD = 2147483647, }; pub const WICPngSrgbRenderingIntent = WICPngSrgbProperties.RenderingIntent; pub const WICPngSrgbProperties_FORCE_DWORD = WICPngSrgbProperties.Properties_FORCE_DWORD; pub const WICPngTimeProperties = enum(u32) { Year = 1, Month = 2, Day = 3, Hour = 4, Minute = 5, Second = 6, Properties_FORCE_DWORD = 2147483647, }; pub const WICPngTimeYear = WICPngTimeProperties.Year; pub const WICPngTimeMonth = WICPngTimeProperties.Month; pub const WICPngTimeDay = WICPngTimeProperties.Day; pub const WICPngTimeHour = WICPngTimeProperties.Hour; pub const WICPngTimeMinute = WICPngTimeProperties.Minute; pub const WICPngTimeSecond = WICPngTimeProperties.Second; pub const WICPngTimeProperties_FORCE_DWORD = WICPngTimeProperties.Properties_FORCE_DWORD; pub const WICHeifProperties = enum(u32) { Orientation = 1, Properties_FORCE_DWORD = 2147483647, }; pub const WICHeifOrientation = WICHeifProperties.Orientation; pub const WICHeifProperties_FORCE_DWORD = WICHeifProperties.Properties_FORCE_DWORD; pub const WICHeifHdrProperties = enum(u32) { MaximumLuminanceLevel = 1, MaximumFrameAverageLuminanceLevel = 2, MinimumMasteringDisplayLuminanceLevel = 3, MaximumMasteringDisplayLuminanceLevel = 4, CustomVideoPrimaries = 5, Properties_FORCE_DWORD = 2147483647, }; pub const WICHeifHdrMaximumLuminanceLevel = WICHeifHdrProperties.MaximumLuminanceLevel; pub const WICHeifHdrMaximumFrameAverageLuminanceLevel = WICHeifHdrProperties.MaximumFrameAverageLuminanceLevel; pub const WICHeifHdrMinimumMasteringDisplayLuminanceLevel = WICHeifHdrProperties.MinimumMasteringDisplayLuminanceLevel; pub const WICHeifHdrMaximumMasteringDisplayLuminanceLevel = WICHeifHdrProperties.MaximumMasteringDisplayLuminanceLevel; pub const WICHeifHdrCustomVideoPrimaries = WICHeifHdrProperties.CustomVideoPrimaries; pub const WICHeifHdrProperties_FORCE_DWORD = WICHeifHdrProperties.Properties_FORCE_DWORD; pub const WICWebpAnimProperties = enum(u32) { LoopCount = 1, Properties_FORCE_DWORD = 2147483647, }; pub const WICWebpAnimLoopCount = WICWebpAnimProperties.LoopCount; pub const WICWebpAnimProperties_FORCE_DWORD = WICWebpAnimProperties.Properties_FORCE_DWORD; pub const WICWebpAnmfProperties = enum(u32) { FrameDuration = 1, Properties_FORCE_DWORD = 2147483647, }; pub const WICWebpAnmfFrameDuration = WICWebpAnmfProperties.FrameDuration; pub const WICWebpAnmfProperties_FORCE_DWORD = WICWebpAnmfProperties.Properties_FORCE_DWORD; pub const WICSectionAccessLevel = enum(u32) { Read = 1, ReadWrite = 3, _FORCE_DWORD = 2147483647, }; pub const WICSectionAccessLevelRead = WICSectionAccessLevel.Read; pub const WICSectionAccessLevelReadWrite = WICSectionAccessLevel.ReadWrite; pub const WICSectionAccessLevel_FORCE_DWORD = WICSectionAccessLevel._FORCE_DWORD; pub const WICPixelFormatNumericRepresentation = enum(u32) { Unspecified = 0, Indexed = 1, UnsignedInteger = 2, SignedInteger = 3, Fixed = 4, Float = 5, _FORCE_DWORD = 2147483647, }; pub const WICPixelFormatNumericRepresentationUnspecified = WICPixelFormatNumericRepresentation.Unspecified; pub const WICPixelFormatNumericRepresentationIndexed = WICPixelFormatNumericRepresentation.Indexed; pub const WICPixelFormatNumericRepresentationUnsignedInteger = WICPixelFormatNumericRepresentation.UnsignedInteger; pub const WICPixelFormatNumericRepresentationSignedInteger = WICPixelFormatNumericRepresentation.SignedInteger; pub const WICPixelFormatNumericRepresentationFixed = WICPixelFormatNumericRepresentation.Fixed; pub const WICPixelFormatNumericRepresentationFloat = WICPixelFormatNumericRepresentation.Float; pub const WICPixelFormatNumericRepresentation_FORCE_DWORD = WICPixelFormatNumericRepresentation._FORCE_DWORD; pub const WICPlanarOptions = enum(i32) { lanarOptionsDefault = 0, lanarOptionsPreserveSubsampling = 1, LANAROPTIONS_FORCE_DWORD = 2147483647, }; pub const WICPlanarOptionsDefault = WICPlanarOptions.lanarOptionsDefault; pub const WICPlanarOptionsPreserveSubsampling = WICPlanarOptions.lanarOptionsPreserveSubsampling; pub const WICPLANAROPTIONS_FORCE_DWORD = WICPlanarOptions.LANAROPTIONS_FORCE_DWORD; pub const WICJpegIndexingOptions = enum(u32) { GenerateOnDemand = 0, GenerateOnLoad = 1, _FORCE_DWORD = 2147483647, }; pub const WICJpegIndexingOptionsGenerateOnDemand = WICJpegIndexingOptions.GenerateOnDemand; pub const WICJpegIndexingOptionsGenerateOnLoad = WICJpegIndexingOptions.GenerateOnLoad; pub const WICJpegIndexingOptions_FORCE_DWORD = WICJpegIndexingOptions._FORCE_DWORD; pub const WICJpegTransferMatrix = enum(u32) { Identity = 0, BT601 = 1, _FORCE_DWORD = 2147483647, }; pub const WICJpegTransferMatrixIdentity = WICJpegTransferMatrix.Identity; pub const WICJpegTransferMatrixBT601 = WICJpegTransferMatrix.BT601; pub const WICJpegTransferMatrix_FORCE_DWORD = WICJpegTransferMatrix._FORCE_DWORD; pub const WICJpegScanType = enum(u32) { Interleaved = 0, PlanarComponents = 1, Progressive = 2, _FORCE_DWORD = 2147483647, }; pub const WICJpegScanTypeInterleaved = WICJpegScanType.Interleaved; pub const WICJpegScanTypePlanarComponents = WICJpegScanType.PlanarComponents; pub const WICJpegScanTypeProgressive = WICJpegScanType.Progressive; pub const WICJpegScanType_FORCE_DWORD = WICJpegScanType._FORCE_DWORD; pub const WICImageParameters = extern struct { PixelFormat: D2D1_PIXEL_FORMAT, DpiX: f32, DpiY: f32, Top: f32, Left: f32, PixelWidth: u32, PixelHeight: u32, }; pub const WICBitmapPlaneDescription = extern struct { Format: Guid, Width: u32, Height: u32, }; pub const WICBitmapPlane = extern struct { Format: Guid, pbBuffer: ?*u8, cbStride: u32, cbBufferSize: u32, }; pub const WICJpegFrameHeader = extern struct { Width: u32, Height: u32, TransferMatrix: WICJpegTransferMatrix, ScanType: WICJpegScanType, cComponents: u32, ComponentIdentifiers: u32, SampleFactors: u32, QuantizationTableIndices: u32, }; pub const WICJpegScanHeader = extern struct { cComponents: u32, RestartInterval: u32, ComponentSelectors: u32, HuffmanTableIndices: u32, StartSpectralSelection: u8, EndSpectralSelection: u8, SuccessiveApproximationHigh: u8, SuccessiveApproximationLow: u8, }; // TODO: this type is limited to platform 'windows5.1.2600' const IID_IWICPalette_Value = Guid.initString("00000040-a8f2-4877-ba0a-fd2b6645fb94"); pub const IID_IWICPalette = &IID_IWICPalette_Value; pub const IWICPalette = extern struct { pub const VTable = extern struct { base: IUnknown.VTable, InitializePredefined: fn( self: *const IWICPalette, ePaletteType: WICBitmapPaletteType, fAddTransparentColor: BOOL, ) callconv(@import("std").os.windows.WINAPI) HRESULT, InitializeCustom: fn( self: *const IWICPalette, pColors: [*]u32, cCount: u32, ) callconv(@import("std").os.windows.WINAPI) HRESULT, InitializeFromBitmap: fn( self: *const IWICPalette, pISurface: ?*IWICBitmapSource, cCount: u32, fAddTransparentColor: BOOL, ) callconv(@import("std").os.windows.WINAPI) HRESULT, InitializeFromPalette: fn( self: *const IWICPalette, pIPalette: ?*IWICPalette, ) callconv(@import("std").os.windows.WINAPI) HRESULT, GetType: fn( self: *const IWICPalette, pePaletteType: ?*WICBitmapPaletteType, ) callconv(@import("std").os.windows.WINAPI) HRESULT, GetColorCount: fn( self: *const IWICPalette, pcCount: ?*u32, ) callconv(@import("std").os.windows.WINAPI) HRESULT, GetColors: fn( self: *const IWICPalette, cCount: u32, pColors: [*]u32, pcActualColors: ?*u32, ) callconv(@import("std").os.windows.WINAPI) HRESULT, IsBlackWhite: fn( self: *const IWICPalette, pfIsBlackWhite: ?*BOOL, ) callconv(@import("std").os.windows.WINAPI) HRESULT, IsGrayscale: fn( self: *const IWICPalette, pfIsGrayscale: ?*BOOL, ) callconv(@import("std").os.windows.WINAPI) HRESULT, HasAlpha: fn( self: *const IWICPalette, pfHasAlpha: ?*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 IWICPalette_InitializePredefined(self: *const T, ePaletteType: WICBitmapPaletteType, fAddTransparentColor: BOOL) callconv(.Inline) HRESULT { return @ptrCast(*const IWICPalette.VTable, self.vtable).InitializePredefined(@ptrCast(*const IWICPalette, self), ePaletteType, fAddTransparentColor); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IWICPalette_InitializeCustom(self: *const T, pColors: [*]u32, cCount: u32) callconv(.Inline) HRESULT { return @ptrCast(*const IWICPalette.VTable, self.vtable).InitializeCustom(@ptrCast(*const IWICPalette, self), pColors, cCount); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IWICPalette_InitializeFromBitmap(self: *const T, pISurface: ?*IWICBitmapSource, cCount: u32, fAddTransparentColor: BOOL) callconv(.Inline) HRESULT { return @ptrCast(*const IWICPalette.VTable, self.vtable).InitializeFromBitmap(@ptrCast(*const IWICPalette, self), pISurface, cCount, fAddTransparentColor); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IWICPalette_InitializeFromPalette(self: *const T, pIPalette: ?*IWICPalette) callconv(.Inline) HRESULT { return @ptrCast(*const IWICPalette.VTable, self.vtable).InitializeFromPalette(@ptrCast(*const IWICPalette, self), pIPalette); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IWICPalette_GetType(self: *const T, pePaletteType: ?*WICBitmapPaletteType) callconv(.Inline) HRESULT { return @ptrCast(*const IWICPalette.VTable, self.vtable).GetType(@ptrCast(*const IWICPalette, self), pePaletteType); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IWICPalette_GetColorCount(self: *const T, pcCount: ?*u32) callconv(.Inline) HRESULT { return @ptrCast(*const IWICPalette.VTable, self.vtable).GetColorCount(@ptrCast(*const IWICPalette, self), pcCount); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IWICPalette_GetColors(self: *const T, cCount: u32, pColors: [*]u32, pcActualColors: ?*u32) callconv(.Inline) HRESULT { return @ptrCast(*const IWICPalette.VTable, self.vtable).GetColors(@ptrCast(*const IWICPalette, self), cCount, pColors, pcActualColors); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IWICPalette_IsBlackWhite(self: *const T, pfIsBlackWhite: ?*BOOL) callconv(.Inline) HRESULT { return @ptrCast(*const IWICPalette.VTable, self.vtable).IsBlackWhite(@ptrCast(*const IWICPalette, self), pfIsBlackWhite); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IWICPalette_IsGrayscale(self: *const T, pfIsGrayscale: ?*BOOL) callconv(.Inline) HRESULT { return @ptrCast(*const IWICPalette.VTable, self.vtable).IsGrayscale(@ptrCast(*const IWICPalette, self), pfIsGrayscale); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IWICPalette_HasAlpha(self: *const T, pfHasAlpha: ?*BOOL) callconv(.Inline) HRESULT { return @ptrCast(*const IWICPalette.VTable, self.vtable).HasAlpha(@ptrCast(*const IWICPalette, self), pfHasAlpha); } };} pub usingnamespace MethodMixin(@This()); }; // TODO: this type is limited to platform 'windows5.1.2600' const IID_IWICBitmapSource_Value = Guid.initString("00000120-a8f2-4877-ba0a-fd2b6645fb94"); pub const IID_IWICBitmapSource = &IID_IWICBitmapSource_Value; pub const IWICBitmapSource = extern struct { pub const VTable = extern struct { base: IUnknown.VTable, GetSize: fn( self: *const IWICBitmapSource, puiWidth: ?*u32, puiHeight: ?*u32, ) callconv(@import("std").os.windows.WINAPI) HRESULT, GetPixelFormat: fn( self: *const IWICBitmapSource, pPixelFormat: ?*Guid, ) callconv(@import("std").os.windows.WINAPI) HRESULT, GetResolution: fn( self: *const IWICBitmapSource, pDpiX: ?*f64, pDpiY: ?*f64, ) callconv(@import("std").os.windows.WINAPI) HRESULT, CopyPalette: fn( self: *const IWICBitmapSource, pIPalette: ?*IWICPalette, ) callconv(@import("std").os.windows.WINAPI) HRESULT, CopyPixels: fn( self: *const IWICBitmapSource, prc: ?*const WICRect, cbStride: u32, cbBufferSize: u32, pbBuffer: [*:0]u8, ) 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 IWICBitmapSource_GetSize(self: *const T, puiWidth: ?*u32, puiHeight: ?*u32) callconv(.Inline) HRESULT { return @ptrCast(*const IWICBitmapSource.VTable, self.vtable).GetSize(@ptrCast(*const IWICBitmapSource, self), puiWidth, puiHeight); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IWICBitmapSource_GetPixelFormat(self: *const T, pPixelFormat: ?*Guid) callconv(.Inline) HRESULT { return @ptrCast(*const IWICBitmapSource.VTable, self.vtable).GetPixelFormat(@ptrCast(*const IWICBitmapSource, self), pPixelFormat); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IWICBitmapSource_GetResolution(self: *const T, pDpiX: ?*f64, pDpiY: ?*f64) callconv(.Inline) HRESULT { return @ptrCast(*const IWICBitmapSource.VTable, self.vtable).GetResolution(@ptrCast(*const IWICBitmapSource, self), pDpiX, pDpiY); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IWICBitmapSource_CopyPalette(self: *const T, pIPalette: ?*IWICPalette) callconv(.Inline) HRESULT { return @ptrCast(*const IWICBitmapSource.VTable, self.vtable).CopyPalette(@ptrCast(*const IWICBitmapSource, self), pIPalette); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IWICBitmapSource_CopyPixels(self: *const T, prc: ?*const WICRect, cbStride: u32, cbBufferSize: u32, pbBuffer: [*:0]u8) callconv(.Inline) HRESULT { return @ptrCast(*const IWICBitmapSource.VTable, self.vtable).CopyPixels(@ptrCast(*const IWICBitmapSource, self), prc, cbStride, cbBufferSize, pbBuffer); } };} pub usingnamespace MethodMixin(@This()); }; // TODO: this type is limited to platform 'windows5.1.2600' const IID_IWICFormatConverter_Value = Guid.initString("00000301-a8f2-4877-ba0a-fd2b6645fb94"); pub const IID_IWICFormatConverter = &IID_IWICFormatConverter_Value; pub const IWICFormatConverter = extern struct { pub const VTable = extern struct { base: IWICBitmapSource.VTable, Initialize: fn( self: *const IWICFormatConverter, pISource: ?*IWICBitmapSource, dstFormat: ?*Guid, dither: WICBitmapDitherType, pIPalette: ?*IWICPalette, alphaThresholdPercent: f64, paletteTranslate: WICBitmapPaletteType, ) callconv(@import("std").os.windows.WINAPI) HRESULT, CanConvert: fn( self: *const IWICFormatConverter, srcPixelFormat: ?*Guid, dstPixelFormat: ?*Guid, pfCanConvert: ?*BOOL, ) callconv(@import("std").os.windows.WINAPI) HRESULT, }; vtable: *const VTable, pub fn MethodMixin(comptime T: type) type { return struct { pub usingnamespace IWICBitmapSource.MethodMixin(T); // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IWICFormatConverter_Initialize(self: *const T, pISource: ?*IWICBitmapSource, dstFormat: ?*Guid, dither: WICBitmapDitherType, pIPalette: ?*IWICPalette, alphaThresholdPercent: f64, paletteTranslate: WICBitmapPaletteType) callconv(.Inline) HRESULT { return @ptrCast(*const IWICFormatConverter.VTable, self.vtable).Initialize(@ptrCast(*const IWICFormatConverter, self), pISource, dstFormat, dither, pIPalette, alphaThresholdPercent, paletteTranslate); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IWICFormatConverter_CanConvert(self: *const T, srcPixelFormat: ?*Guid, dstPixelFormat: ?*Guid, pfCanConvert: ?*BOOL) callconv(.Inline) HRESULT { return @ptrCast(*const IWICFormatConverter.VTable, self.vtable).CanConvert(@ptrCast(*const IWICFormatConverter, self), srcPixelFormat, dstPixelFormat, pfCanConvert); } };} pub usingnamespace MethodMixin(@This()); }; // TODO: this type is limited to platform 'windows8.1' const IID_IWICPlanarFormatConverter_Value = Guid.initString("bebee9cb-83b0-4dcc-8132-b0aaa55eac96"); pub const IID_IWICPlanarFormatConverter = &IID_IWICPlanarFormatConverter_Value; pub const IWICPlanarFormatConverter = extern struct { pub const VTable = extern struct { base: IWICBitmapSource.VTable, Initialize: fn( self: *const IWICPlanarFormatConverter, ppPlanes: [*]?*IWICBitmapSource, cPlanes: u32, dstFormat: ?*Guid, dither: WICBitmapDitherType, pIPalette: ?*IWICPalette, alphaThresholdPercent: f64, paletteTranslate: WICBitmapPaletteType, ) callconv(@import("std").os.windows.WINAPI) HRESULT, CanConvert: fn( self: *const IWICPlanarFormatConverter, pSrcPixelFormats: [*]const Guid, cSrcPlanes: u32, dstPixelFormat: ?*Guid, pfCanConvert: ?*BOOL, ) callconv(@import("std").os.windows.WINAPI) HRESULT, }; vtable: *const VTable, pub fn MethodMixin(comptime T: type) type { return struct { pub usingnamespace IWICBitmapSource.MethodMixin(T); // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IWICPlanarFormatConverter_Initialize(self: *const T, ppPlanes: [*]?*IWICBitmapSource, cPlanes: u32, dstFormat: ?*Guid, dither: WICBitmapDitherType, pIPalette: ?*IWICPalette, alphaThresholdPercent: f64, paletteTranslate: WICBitmapPaletteType) callconv(.Inline) HRESULT { return @ptrCast(*const IWICPlanarFormatConverter.VTable, self.vtable).Initialize(@ptrCast(*const IWICPlanarFormatConverter, self), ppPlanes, cPlanes, dstFormat, dither, pIPalette, alphaThresholdPercent, paletteTranslate); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IWICPlanarFormatConverter_CanConvert(self: *const T, pSrcPixelFormats: [*]const Guid, cSrcPlanes: u32, dstPixelFormat: ?*Guid, pfCanConvert: ?*BOOL) callconv(.Inline) HRESULT { return @ptrCast(*const IWICPlanarFormatConverter.VTable, self.vtable).CanConvert(@ptrCast(*const IWICPlanarFormatConverter, self), pSrcPixelFormats, cSrcPlanes, dstPixelFormat, pfCanConvert); } };} pub usingnamespace MethodMixin(@This()); }; // TODO: this type is limited to platform 'windows5.1.2600' const IID_IWICBitmapScaler_Value = Guid.initString("00000302-a8f2-4877-ba0a-fd2b6645fb94"); pub const IID_IWICBitmapScaler = &IID_IWICBitmapScaler_Value; pub const IWICBitmapScaler = extern struct { pub const VTable = extern struct { base: IWICBitmapSource.VTable, Initialize: fn( self: *const IWICBitmapScaler, pISource: ?*IWICBitmapSource, uiWidth: u32, uiHeight: u32, mode: WICBitmapInterpolationMode, ) callconv(@import("std").os.windows.WINAPI) HRESULT, }; vtable: *const VTable, pub fn MethodMixin(comptime T: type) type { return struct { pub usingnamespace IWICBitmapSource.MethodMixin(T); // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IWICBitmapScaler_Initialize(self: *const T, pISource: ?*IWICBitmapSource, uiWidth: u32, uiHeight: u32, mode: WICBitmapInterpolationMode) callconv(.Inline) HRESULT { return @ptrCast(*const IWICBitmapScaler.VTable, self.vtable).Initialize(@ptrCast(*const IWICBitmapScaler, self), pISource, uiWidth, uiHeight, mode); } };} pub usingnamespace MethodMixin(@This()); }; // TODO: this type is limited to platform 'windows5.1.2600' const IID_IWICBitmapClipper_Value = Guid.initString("e4fbcf03-223d-4e81-9333-d635556dd1b5"); pub const IID_IWICBitmapClipper = &IID_IWICBitmapClipper_Value; pub const IWICBitmapClipper = extern struct { pub const VTable = extern struct { base: IWICBitmapSource.VTable, Initialize: fn( self: *const IWICBitmapClipper, pISource: ?*IWICBitmapSource, prc: ?*const WICRect, ) callconv(@import("std").os.windows.WINAPI) HRESULT, }; vtable: *const VTable, pub fn MethodMixin(comptime T: type) type { return struct { pub usingnamespace IWICBitmapSource.MethodMixin(T); // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IWICBitmapClipper_Initialize(self: *const T, pISource: ?*IWICBitmapSource, prc: ?*const WICRect) callconv(.Inline) HRESULT { return @ptrCast(*const IWICBitmapClipper.VTable, self.vtable).Initialize(@ptrCast(*const IWICBitmapClipper, self), pISource, prc); } };} pub usingnamespace MethodMixin(@This()); }; // TODO: this type is limited to platform 'windows5.1.2600' const IID_IWICBitmapFlipRotator_Value = Guid.initString("5009834f-2d6a-41ce-9e1b-17c5aff7a782"); pub const IID_IWICBitmapFlipRotator = &IID_IWICBitmapFlipRotator_Value; pub const IWICBitmapFlipRotator = extern struct { pub const VTable = extern struct { base: IWICBitmapSource.VTable, Initialize: fn( self: *const IWICBitmapFlipRotator, pISource: ?*IWICBitmapSource, options: WICBitmapTransformOptions, ) callconv(@import("std").os.windows.WINAPI) HRESULT, }; vtable: *const VTable, pub fn MethodMixin(comptime T: type) type { return struct { pub usingnamespace IWICBitmapSource.MethodMixin(T); // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IWICBitmapFlipRotator_Initialize(self: *const T, pISource: ?*IWICBitmapSource, options: WICBitmapTransformOptions) callconv(.Inline) HRESULT { return @ptrCast(*const IWICBitmapFlipRotator.VTable, self.vtable).Initialize(@ptrCast(*const IWICBitmapFlipRotator, self), pISource, options); } };} pub usingnamespace MethodMixin(@This()); }; // TODO: this type is limited to platform 'windows5.1.2600' const IID_IWICBitmapLock_Value = Guid.initString("00000123-a8f2-4877-ba0a-fd2b6645fb94"); pub const IID_IWICBitmapLock = &IID_IWICBitmapLock_Value; pub const IWICBitmapLock = extern struct { pub const VTable = extern struct { base: IUnknown.VTable, GetSize: fn( self: *const IWICBitmapLock, puiWidth: ?*u32, puiHeight: ?*u32, ) callconv(@import("std").os.windows.WINAPI) HRESULT, GetStride: fn( self: *const IWICBitmapLock, pcbStride: ?*u32, ) callconv(@import("std").os.windows.WINAPI) HRESULT, GetDataPointer: fn( self: *const IWICBitmapLock, pcbBufferSize: ?*u32, ppbData: [*]?*u8, ) callconv(@import("std").os.windows.WINAPI) HRESULT, GetPixelFormat: fn( self: *const IWICBitmapLock, pPixelFormat: ?*Guid, ) 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 IWICBitmapLock_GetSize(self: *const T, puiWidth: ?*u32, puiHeight: ?*u32) callconv(.Inline) HRESULT { return @ptrCast(*const IWICBitmapLock.VTable, self.vtable).GetSize(@ptrCast(*const IWICBitmapLock, self), puiWidth, puiHeight); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IWICBitmapLock_GetStride(self: *const T, pcbStride: ?*u32) callconv(.Inline) HRESULT { return @ptrCast(*const IWICBitmapLock.VTable, self.vtable).GetStride(@ptrCast(*const IWICBitmapLock, self), pcbStride); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IWICBitmapLock_GetDataPointer(self: *const T, pcbBufferSize: ?*u32, ppbData: [*]?*u8) callconv(.Inline) HRESULT { return @ptrCast(*const IWICBitmapLock.VTable, self.vtable).GetDataPointer(@ptrCast(*const IWICBitmapLock, self), pcbBufferSize, ppbData); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IWICBitmapLock_GetPixelFormat(self: *const T, pPixelFormat: ?*Guid) callconv(.Inline) HRESULT { return @ptrCast(*const IWICBitmapLock.VTable, self.vtable).GetPixelFormat(@ptrCast(*const IWICBitmapLock, self), pPixelFormat); } };} pub usingnamespace MethodMixin(@This()); }; // TODO: this type is limited to platform 'windows5.1.2600' const IID_IWICBitmap_Value = Guid.initString("00000121-a8f2-4877-ba0a-fd2b6645fb94"); pub const IID_IWICBitmap = &IID_IWICBitmap_Value; pub const IWICBitmap = extern struct { pub const VTable = extern struct { base: IWICBitmapSource.VTable, Lock: fn( self: *const IWICBitmap, prcLock: ?*const WICRect, flags: u32, ppILock: ?*?*IWICBitmapLock, ) callconv(@import("std").os.windows.WINAPI) HRESULT, SetPalette: fn( self: *const IWICBitmap, pIPalette: ?*IWICPalette, ) callconv(@import("std").os.windows.WINAPI) HRESULT, SetResolution: fn( self: *const IWICBitmap, dpiX: f64, dpiY: f64, ) callconv(@import("std").os.windows.WINAPI) HRESULT, }; vtable: *const VTable, pub fn MethodMixin(comptime T: type) type { return struct { pub usingnamespace IWICBitmapSource.MethodMixin(T); // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IWICBitmap_Lock(self: *const T, prcLock: ?*const WICRect, flags: u32, ppILock: ?*?*IWICBitmapLock) callconv(.Inline) HRESULT { return @ptrCast(*const IWICBitmap.VTable, self.vtable).Lock(@ptrCast(*const IWICBitmap, self), prcLock, flags, ppILock); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IWICBitmap_SetPalette(self: *const T, pIPalette: ?*IWICPalette) callconv(.Inline) HRESULT { return @ptrCast(*const IWICBitmap.VTable, self.vtable).SetPalette(@ptrCast(*const IWICBitmap, self), pIPalette); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IWICBitmap_SetResolution(self: *const T, dpiX: f64, dpiY: f64) callconv(.Inline) HRESULT { return @ptrCast(*const IWICBitmap.VTable, self.vtable).SetResolution(@ptrCast(*const IWICBitmap, self), dpiX, dpiY); } };} pub usingnamespace MethodMixin(@This()); }; // TODO: this type is limited to platform 'windows5.1.2600' const IID_IWICColorContext_Value = Guid.initString("3c613a02-34b2-44ea-9a7c-45aea9c6fd6d"); pub const IID_IWICColorContext = &IID_IWICColorContext_Value; pub const IWICColorContext = extern struct { pub const VTable = extern struct { base: IUnknown.VTable, InitializeFromFilename: fn( self: *const IWICColorContext, wzFilename: ?[*:0]const u16, ) callconv(@import("std").os.windows.WINAPI) HRESULT, InitializeFromMemory: fn( self: *const IWICColorContext, pbBuffer: [*:0]const u8, cbBufferSize: u32, ) callconv(@import("std").os.windows.WINAPI) HRESULT, InitializeFromExifColorSpace: fn( self: *const IWICColorContext, value: u32, ) callconv(@import("std").os.windows.WINAPI) HRESULT, GetType: fn( self: *const IWICColorContext, pType: ?*WICColorContextType, ) callconv(@import("std").os.windows.WINAPI) HRESULT, GetProfileBytes: fn( self: *const IWICColorContext, cbBuffer: u32, pbBuffer: [*:0]u8, pcbActual: ?*u32, ) callconv(@import("std").os.windows.WINAPI) HRESULT, GetExifColorSpace: fn( self: *const IWICColorContext, pValue: ?*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 IWICColorContext_InitializeFromFilename(self: *const T, wzFilename: ?[*:0]const u16) callconv(.Inline) HRESULT { return @ptrCast(*const IWICColorContext.VTable, self.vtable).InitializeFromFilename(@ptrCast(*const IWICColorContext, self), wzFilename); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IWICColorContext_InitializeFromMemory(self: *const T, pbBuffer: [*:0]const u8, cbBufferSize: u32) callconv(.Inline) HRESULT { return @ptrCast(*const IWICColorContext.VTable, self.vtable).InitializeFromMemory(@ptrCast(*const IWICColorContext, self), pbBuffer, cbBufferSize); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IWICColorContext_InitializeFromExifColorSpace(self: *const T, value: u32) callconv(.Inline) HRESULT { return @ptrCast(*const IWICColorContext.VTable, self.vtable).InitializeFromExifColorSpace(@ptrCast(*const IWICColorContext, self), value); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IWICColorContext_GetType(self: *const T, pType: ?*WICColorContextType) callconv(.Inline) HRESULT { return @ptrCast(*const IWICColorContext.VTable, self.vtable).GetType(@ptrCast(*const IWICColorContext, self), pType); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IWICColorContext_GetProfileBytes(self: *const T, cbBuffer: u32, pbBuffer: [*:0]u8, pcbActual: ?*u32) callconv(.Inline) HRESULT { return @ptrCast(*const IWICColorContext.VTable, self.vtable).GetProfileBytes(@ptrCast(*const IWICColorContext, self), cbBuffer, pbBuffer, pcbActual); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IWICColorContext_GetExifColorSpace(self: *const T, pValue: ?*u32) callconv(.Inline) HRESULT { return @ptrCast(*const IWICColorContext.VTable, self.vtable).GetExifColorSpace(@ptrCast(*const IWICColorContext, self), pValue); } };} pub usingnamespace MethodMixin(@This()); }; // TODO: this type is limited to platform 'windows5.1.2600' const IID_IWICColorTransform_Value = Guid.initString("b66f034f-d0e2-40ab-b436-6de39e321a94"); pub const IID_IWICColorTransform = &IID_IWICColorTransform_Value; pub const IWICColorTransform = extern struct { pub const VTable = extern struct { base: IWICBitmapSource.VTable, Initialize: fn( self: *const IWICColorTransform, pIBitmapSource: ?*IWICBitmapSource, pIContextSource: ?*IWICColorContext, pIContextDest: ?*IWICColorContext, pixelFmtDest: ?*Guid, ) callconv(@import("std").os.windows.WINAPI) HRESULT, }; vtable: *const VTable, pub fn MethodMixin(comptime T: type) type { return struct { pub usingnamespace IWICBitmapSource.MethodMixin(T); // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IWICColorTransform_Initialize(self: *const T, pIBitmapSource: ?*IWICBitmapSource, pIContextSource: ?*IWICColorContext, pIContextDest: ?*IWICColorContext, pixelFmtDest: ?*Guid) callconv(.Inline) HRESULT { return @ptrCast(*const IWICColorTransform.VTable, self.vtable).Initialize(@ptrCast(*const IWICColorTransform, self), pIBitmapSource, pIContextSource, pIContextDest, pixelFmtDest); } };} pub usingnamespace MethodMixin(@This()); }; // TODO: this type is limited to platform 'windows5.1.2600' const IID_IWICFastMetadataEncoder_Value = Guid.initString("b84e2c09-78c9-4ac4-8bd3-524ae1663a2f"); pub const IID_IWICFastMetadataEncoder = &IID_IWICFastMetadataEncoder_Value; pub const IWICFastMetadataEncoder = extern struct { pub const VTable = extern struct { base: IUnknown.VTable, Commit: fn( self: *const IWICFastMetadataEncoder, ) callconv(@import("std").os.windows.WINAPI) HRESULT, GetMetadataQueryWriter: fn( self: *const IWICFastMetadataEncoder, ppIMetadataQueryWriter: ?*?*IWICMetadataQueryWriter, ) 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 IWICFastMetadataEncoder_Commit(self: *const T) callconv(.Inline) HRESULT { return @ptrCast(*const IWICFastMetadataEncoder.VTable, self.vtable).Commit(@ptrCast(*const IWICFastMetadataEncoder, self)); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IWICFastMetadataEncoder_GetMetadataQueryWriter(self: *const T, ppIMetadataQueryWriter: ?*?*IWICMetadataQueryWriter) callconv(.Inline) HRESULT { return @ptrCast(*const IWICFastMetadataEncoder.VTable, self.vtable).GetMetadataQueryWriter(@ptrCast(*const IWICFastMetadataEncoder, self), ppIMetadataQueryWriter); } };} pub usingnamespace MethodMixin(@This()); }; // TODO: this type is limited to platform 'windows5.1.2600' const IID_IWICStream_Value = Guid.initString("135ff860-22b7-4ddf-b0f6-218f4f299a43"); pub const IID_IWICStream = &IID_IWICStream_Value; pub const IWICStream = extern struct { pub const VTable = extern struct { base: IStream.VTable, InitializeFromIStream: fn( self: *const IWICStream, pIStream: ?*IStream, ) callconv(@import("std").os.windows.WINAPI) HRESULT, InitializeFromFilename: fn( self: *const IWICStream, wzFileName: ?[*:0]const u16, dwDesiredAccess: u32, ) callconv(@import("std").os.windows.WINAPI) HRESULT, InitializeFromMemory: fn( self: *const IWICStream, pbBuffer: [*:0]u8, cbBufferSize: u32, ) callconv(@import("std").os.windows.WINAPI) HRESULT, InitializeFromIStreamRegion: fn( self: *const IWICStream, pIStream: ?*IStream, ulOffset: ULARGE_INTEGER, ulMaxSize: ULARGE_INTEGER, ) callconv(@import("std").os.windows.WINAPI) HRESULT, }; vtable: *const VTable, pub fn MethodMixin(comptime T: type) type { return struct { pub usingnamespace IStream.MethodMixin(T); // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IWICStream_InitializeFromIStream(self: *const T, pIStream: ?*IStream) callconv(.Inline) HRESULT { return @ptrCast(*const IWICStream.VTable, self.vtable).InitializeFromIStream(@ptrCast(*const IWICStream, self), pIStream); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IWICStream_InitializeFromFilename(self: *const T, wzFileName: ?[*:0]const u16, dwDesiredAccess: u32) callconv(.Inline) HRESULT { return @ptrCast(*const IWICStream.VTable, self.vtable).InitializeFromFilename(@ptrCast(*const IWICStream, self), wzFileName, dwDesiredAccess); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IWICStream_InitializeFromMemory(self: *const T, pbBuffer: [*:0]u8, cbBufferSize: u32) callconv(.Inline) HRESULT { return @ptrCast(*const IWICStream.VTable, self.vtable).InitializeFromMemory(@ptrCast(*const IWICStream, self), pbBuffer, cbBufferSize); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IWICStream_InitializeFromIStreamRegion(self: *const T, pIStream: ?*IStream, ulOffset: ULARGE_INTEGER, ulMaxSize: ULARGE_INTEGER) callconv(.Inline) HRESULT { return @ptrCast(*const IWICStream.VTable, self.vtable).InitializeFromIStreamRegion(@ptrCast(*const IWICStream, self), pIStream, ulOffset, ulMaxSize); } };} pub usingnamespace MethodMixin(@This()); }; // TODO: this type is limited to platform 'windows5.1.2600' const IID_IWICEnumMetadataItem_Value = Guid.initString("dc2bb46d-3f07-481e-8625-220c4aedbb33"); pub const IID_IWICEnumMetadataItem = &IID_IWICEnumMetadataItem_Value; pub const IWICEnumMetadataItem = extern struct { pub const VTable = extern struct { base: IUnknown.VTable, Next: fn( self: *const IWICEnumMetadataItem, celt: u32, rgeltSchema: [*]PROPVARIANT, rgeltId: [*]PROPVARIANT, rgeltValue: [*]PROPVARIANT, pceltFetched: ?*u32, ) callconv(@import("std").os.windows.WINAPI) HRESULT, Skip: fn( self: *const IWICEnumMetadataItem, celt: u32, ) callconv(@import("std").os.windows.WINAPI) HRESULT, Reset: fn( self: *const IWICEnumMetadataItem, ) callconv(@import("std").os.windows.WINAPI) HRESULT, Clone: fn( self: *const IWICEnumMetadataItem, ppIEnumMetadataItem: ?*?*IWICEnumMetadataItem, ) 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 IWICEnumMetadataItem_Next(self: *const T, celt: u32, rgeltSchema: [*]PROPVARIANT, rgeltId: [*]PROPVARIANT, rgeltValue: [*]PROPVARIANT, pceltFetched: ?*u32) callconv(.Inline) HRESULT { return @ptrCast(*const IWICEnumMetadataItem.VTable, self.vtable).Next(@ptrCast(*const IWICEnumMetadataItem, self), celt, rgeltSchema, rgeltId, rgeltValue, pceltFetched); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IWICEnumMetadataItem_Skip(self: *const T, celt: u32) callconv(.Inline) HRESULT { return @ptrCast(*const IWICEnumMetadataItem.VTable, self.vtable).Skip(@ptrCast(*const IWICEnumMetadataItem, self), celt); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IWICEnumMetadataItem_Reset(self: *const T) callconv(.Inline) HRESULT { return @ptrCast(*const IWICEnumMetadataItem.VTable, self.vtable).Reset(@ptrCast(*const IWICEnumMetadataItem, self)); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IWICEnumMetadataItem_Clone(self: *const T, ppIEnumMetadataItem: ?*?*IWICEnumMetadataItem) callconv(.Inline) HRESULT { return @ptrCast(*const IWICEnumMetadataItem.VTable, self.vtable).Clone(@ptrCast(*const IWICEnumMetadataItem, self), ppIEnumMetadataItem); } };} pub usingnamespace MethodMixin(@This()); }; // TODO: this type is limited to platform 'windows5.1.2600' const IID_IWICMetadataQueryReader_Value = Guid.initString("30989668-e1c9-4597-b395-458eedb808df"); pub const IID_IWICMetadataQueryReader = &IID_IWICMetadataQueryReader_Value; pub const IWICMetadataQueryReader = extern struct { pub const VTable = extern struct { base: IUnknown.VTable, GetContainerFormat: fn( self: *const IWICMetadataQueryReader, pguidContainerFormat: ?*Guid, ) callconv(@import("std").os.windows.WINAPI) HRESULT, GetLocation: fn( self: *const IWICMetadataQueryReader, cchMaxLength: u32, wzNamespace: [*:0]u16, pcchActualLength: ?*u32, ) callconv(@import("std").os.windows.WINAPI) HRESULT, GetMetadataByName: fn( self: *const IWICMetadataQueryReader, wzName: ?[*:0]const u16, pvarValue: ?*PROPVARIANT, ) callconv(@import("std").os.windows.WINAPI) HRESULT, GetEnumerator: fn( self: *const IWICMetadataQueryReader, ppIEnumString: ?*?*IEnumString, ) 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 IWICMetadataQueryReader_GetContainerFormat(self: *const T, pguidContainerFormat: ?*Guid) callconv(.Inline) HRESULT { return @ptrCast(*const IWICMetadataQueryReader.VTable, self.vtable).GetContainerFormat(@ptrCast(*const IWICMetadataQueryReader, self), pguidContainerFormat); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IWICMetadataQueryReader_GetLocation(self: *const T, cchMaxLength: u32, wzNamespace: [*:0]u16, pcchActualLength: ?*u32) callconv(.Inline) HRESULT { return @ptrCast(*const IWICMetadataQueryReader.VTable, self.vtable).GetLocation(@ptrCast(*const IWICMetadataQueryReader, self), cchMaxLength, wzNamespace, pcchActualLength); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IWICMetadataQueryReader_GetMetadataByName(self: *const T, wzName: ?[*:0]const u16, pvarValue: ?*PROPVARIANT) callconv(.Inline) HRESULT { return @ptrCast(*const IWICMetadataQueryReader.VTable, self.vtable).GetMetadataByName(@ptrCast(*const IWICMetadataQueryReader, self), wzName, pvarValue); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IWICMetadataQueryReader_GetEnumerator(self: *const T, ppIEnumString: ?*?*IEnumString) callconv(.Inline) HRESULT { return @ptrCast(*const IWICMetadataQueryReader.VTable, self.vtable).GetEnumerator(@ptrCast(*const IWICMetadataQueryReader, self), ppIEnumString); } };} pub usingnamespace MethodMixin(@This()); }; // TODO: this type is limited to platform 'windows5.1.2600' const IID_IWICMetadataQueryWriter_Value = Guid.initString("a721791a-0def-4d06-bd91-2118bf1db10b"); pub const IID_IWICMetadataQueryWriter = &IID_IWICMetadataQueryWriter_Value; pub const IWICMetadataQueryWriter = extern struct { pub const VTable = extern struct { base: IWICMetadataQueryReader.VTable, SetMetadataByName: fn( self: *const IWICMetadataQueryWriter, wzName: ?[*:0]const u16, pvarValue: ?*const PROPVARIANT, ) callconv(@import("std").os.windows.WINAPI) HRESULT, RemoveMetadataByName: fn( self: *const IWICMetadataQueryWriter, wzName: ?[*:0]const u16, ) callconv(@import("std").os.windows.WINAPI) HRESULT, }; vtable: *const VTable, pub fn MethodMixin(comptime T: type) type { return struct { pub usingnamespace IWICMetadataQueryReader.MethodMixin(T); // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IWICMetadataQueryWriter_SetMetadataByName(self: *const T, wzName: ?[*:0]const u16, pvarValue: ?*const PROPVARIANT) callconv(.Inline) HRESULT { return @ptrCast(*const IWICMetadataQueryWriter.VTable, self.vtable).SetMetadataByName(@ptrCast(*const IWICMetadataQueryWriter, self), wzName, pvarValue); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IWICMetadataQueryWriter_RemoveMetadataByName(self: *const T, wzName: ?[*:0]const u16) callconv(.Inline) HRESULT { return @ptrCast(*const IWICMetadataQueryWriter.VTable, self.vtable).RemoveMetadataByName(@ptrCast(*const IWICMetadataQueryWriter, self), wzName); } };} pub usingnamespace MethodMixin(@This()); }; const IID_IWICBitmapEncoder_Value = Guid.initString("00000103-a8f2-4877-ba0a-fd2b6645fb94"); pub const IID_IWICBitmapEncoder = &IID_IWICBitmapEncoder_Value; pub const IWICBitmapEncoder = extern struct { pub const VTable = extern struct { base: IUnknown.VTable, Initialize: fn( self: *const IWICBitmapEncoder, pIStream: ?*IStream, cacheOption: WICBitmapEncoderCacheOption, ) callconv(@import("std").os.windows.WINAPI) HRESULT, GetContainerFormat: fn( self: *const IWICBitmapEncoder, pguidContainerFormat: ?*Guid, ) callconv(@import("std").os.windows.WINAPI) HRESULT, GetEncoderInfo: fn( self: *const IWICBitmapEncoder, ppIEncoderInfo: ?*?*IWICBitmapEncoderInfo, ) callconv(@import("std").os.windows.WINAPI) HRESULT, SetColorContexts: fn( self: *const IWICBitmapEncoder, cCount: u32, ppIColorContext: [*]?*IWICColorContext, ) callconv(@import("std").os.windows.WINAPI) HRESULT, SetPalette: fn( self: *const IWICBitmapEncoder, pIPalette: ?*IWICPalette, ) callconv(@import("std").os.windows.WINAPI) HRESULT, SetThumbnail: fn( self: *const IWICBitmapEncoder, pIThumbnail: ?*IWICBitmapSource, ) callconv(@import("std").os.windows.WINAPI) HRESULT, SetPreview: fn( self: *const IWICBitmapEncoder, pIPreview: ?*IWICBitmapSource, ) callconv(@import("std").os.windows.WINAPI) HRESULT, CreateNewFrame: fn( self: *const IWICBitmapEncoder, ppIFrameEncode: ?*?*IWICBitmapFrameEncode, ppIEncoderOptions: ?*?*IPropertyBag2, ) callconv(@import("std").os.windows.WINAPI) HRESULT, Commit: fn( self: *const IWICBitmapEncoder, ) callconv(@import("std").os.windows.WINAPI) HRESULT, GetMetadataQueryWriter: fn( self: *const IWICBitmapEncoder, ppIMetadataQueryWriter: ?*?*IWICMetadataQueryWriter, ) 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 IWICBitmapEncoder_Initialize(self: *const T, pIStream: ?*IStream, cacheOption: WICBitmapEncoderCacheOption) callconv(.Inline) HRESULT { return @ptrCast(*const IWICBitmapEncoder.VTable, self.vtable).Initialize(@ptrCast(*const IWICBitmapEncoder, self), pIStream, cacheOption); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IWICBitmapEncoder_GetContainerFormat(self: *const T, pguidContainerFormat: ?*Guid) callconv(.Inline) HRESULT { return @ptrCast(*const IWICBitmapEncoder.VTable, self.vtable).GetContainerFormat(@ptrCast(*const IWICBitmapEncoder, self), pguidContainerFormat); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IWICBitmapEncoder_GetEncoderInfo(self: *const T, ppIEncoderInfo: ?*?*IWICBitmapEncoderInfo) callconv(.Inline) HRESULT { return @ptrCast(*const IWICBitmapEncoder.VTable, self.vtable).GetEncoderInfo(@ptrCast(*const IWICBitmapEncoder, self), ppIEncoderInfo); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IWICBitmapEncoder_SetColorContexts(self: *const T, cCount: u32, ppIColorContext: [*]?*IWICColorContext) callconv(.Inline) HRESULT { return @ptrCast(*const IWICBitmapEncoder.VTable, self.vtable).SetColorContexts(@ptrCast(*const IWICBitmapEncoder, self), cCount, ppIColorContext); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IWICBitmapEncoder_SetPalette(self: *const T, pIPalette: ?*IWICPalette) callconv(.Inline) HRESULT { return @ptrCast(*const IWICBitmapEncoder.VTable, self.vtable).SetPalette(@ptrCast(*const IWICBitmapEncoder, self), pIPalette); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IWICBitmapEncoder_SetThumbnail(self: *const T, pIThumbnail: ?*IWICBitmapSource) callconv(.Inline) HRESULT { return @ptrCast(*const IWICBitmapEncoder.VTable, self.vtable).SetThumbnail(@ptrCast(*const IWICBitmapEncoder, self), pIThumbnail); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IWICBitmapEncoder_SetPreview(self: *const T, pIPreview: ?*IWICBitmapSource) callconv(.Inline) HRESULT { return @ptrCast(*const IWICBitmapEncoder.VTable, self.vtable).SetPreview(@ptrCast(*const IWICBitmapEncoder, self), pIPreview); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IWICBitmapEncoder_CreateNewFrame(self: *const T, ppIFrameEncode: ?*?*IWICBitmapFrameEncode, ppIEncoderOptions: ?*?*IPropertyBag2) callconv(.Inline) HRESULT { return @ptrCast(*const IWICBitmapEncoder.VTable, self.vtable).CreateNewFrame(@ptrCast(*const IWICBitmapEncoder, self), ppIFrameEncode, ppIEncoderOptions); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IWICBitmapEncoder_Commit(self: *const T) callconv(.Inline) HRESULT { return @ptrCast(*const IWICBitmapEncoder.VTable, self.vtable).Commit(@ptrCast(*const IWICBitmapEncoder, self)); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IWICBitmapEncoder_GetMetadataQueryWriter(self: *const T, ppIMetadataQueryWriter: ?*?*IWICMetadataQueryWriter) callconv(.Inline) HRESULT { return @ptrCast(*const IWICBitmapEncoder.VTable, self.vtable).GetMetadataQueryWriter(@ptrCast(*const IWICBitmapEncoder, self), ppIMetadataQueryWriter); } };} pub usingnamespace MethodMixin(@This()); }; // TODO: this type is limited to platform 'windows5.1.2600' const IID_IWICBitmapFrameEncode_Value = Guid.initString("00000105-a8f2-4877-ba0a-fd2b6645fb94"); pub const IID_IWICBitmapFrameEncode = &IID_IWICBitmapFrameEncode_Value; pub const IWICBitmapFrameEncode = extern struct { pub const VTable = extern struct { base: IUnknown.VTable, Initialize: fn( self: *const IWICBitmapFrameEncode, pIEncoderOptions: ?*IPropertyBag2, ) callconv(@import("std").os.windows.WINAPI) HRESULT, SetSize: fn( self: *const IWICBitmapFrameEncode, uiWidth: u32, uiHeight: u32, ) callconv(@import("std").os.windows.WINAPI) HRESULT, SetResolution: fn( self: *const IWICBitmapFrameEncode, dpiX: f64, dpiY: f64, ) callconv(@import("std").os.windows.WINAPI) HRESULT, SetPixelFormat: fn( self: *const IWICBitmapFrameEncode, pPixelFormat: ?*Guid, ) callconv(@import("std").os.windows.WINAPI) HRESULT, SetColorContexts: fn( self: *const IWICBitmapFrameEncode, cCount: u32, ppIColorContext: [*]?*IWICColorContext, ) callconv(@import("std").os.windows.WINAPI) HRESULT, SetPalette: fn( self: *const IWICBitmapFrameEncode, pIPalette: ?*IWICPalette, ) callconv(@import("std").os.windows.WINAPI) HRESULT, SetThumbnail: fn( self: *const IWICBitmapFrameEncode, pIThumbnail: ?*IWICBitmapSource, ) callconv(@import("std").os.windows.WINAPI) HRESULT, WritePixels: fn( self: *const IWICBitmapFrameEncode, lineCount: u32, cbStride: u32, cbBufferSize: u32, pbPixels: [*:0]u8, ) callconv(@import("std").os.windows.WINAPI) HRESULT, WriteSource: fn( self: *const IWICBitmapFrameEncode, pIBitmapSource: ?*IWICBitmapSource, prc: ?*WICRect, ) callconv(@import("std").os.windows.WINAPI) HRESULT, Commit: fn( self: *const IWICBitmapFrameEncode, ) callconv(@import("std").os.windows.WINAPI) HRESULT, GetMetadataQueryWriter: fn( self: *const IWICBitmapFrameEncode, ppIMetadataQueryWriter: ?*?*IWICMetadataQueryWriter, ) 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 IWICBitmapFrameEncode_Initialize(self: *const T, pIEncoderOptions: ?*IPropertyBag2) callconv(.Inline) HRESULT { return @ptrCast(*const IWICBitmapFrameEncode.VTable, self.vtable).Initialize(@ptrCast(*const IWICBitmapFrameEncode, self), pIEncoderOptions); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IWICBitmapFrameEncode_SetSize(self: *const T, uiWidth: u32, uiHeight: u32) callconv(.Inline) HRESULT { return @ptrCast(*const IWICBitmapFrameEncode.VTable, self.vtable).SetSize(@ptrCast(*const IWICBitmapFrameEncode, self), uiWidth, uiHeight); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IWICBitmapFrameEncode_SetResolution(self: *const T, dpiX: f64, dpiY: f64) callconv(.Inline) HRESULT { return @ptrCast(*const IWICBitmapFrameEncode.VTable, self.vtable).SetResolution(@ptrCast(*const IWICBitmapFrameEncode, self), dpiX, dpiY); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IWICBitmapFrameEncode_SetPixelFormat(self: *const T, pPixelFormat: ?*Guid) callconv(.Inline) HRESULT { return @ptrCast(*const IWICBitmapFrameEncode.VTable, self.vtable).SetPixelFormat(@ptrCast(*const IWICBitmapFrameEncode, self), pPixelFormat); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IWICBitmapFrameEncode_SetColorContexts(self: *const T, cCount: u32, ppIColorContext: [*]?*IWICColorContext) callconv(.Inline) HRESULT { return @ptrCast(*const IWICBitmapFrameEncode.VTable, self.vtable).SetColorContexts(@ptrCast(*const IWICBitmapFrameEncode, self), cCount, ppIColorContext); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IWICBitmapFrameEncode_SetPalette(self: *const T, pIPalette: ?*IWICPalette) callconv(.Inline) HRESULT { return @ptrCast(*const IWICBitmapFrameEncode.VTable, self.vtable).SetPalette(@ptrCast(*const IWICBitmapFrameEncode, self), pIPalette); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IWICBitmapFrameEncode_SetThumbnail(self: *const T, pIThumbnail: ?*IWICBitmapSource) callconv(.Inline) HRESULT { return @ptrCast(*const IWICBitmapFrameEncode.VTable, self.vtable).SetThumbnail(@ptrCast(*const IWICBitmapFrameEncode, self), pIThumbnail); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IWICBitmapFrameEncode_WritePixels(self: *const T, lineCount: u32, cbStride: u32, cbBufferSize: u32, pbPixels: [*:0]u8) callconv(.Inline) HRESULT { return @ptrCast(*const IWICBitmapFrameEncode.VTable, self.vtable).WritePixels(@ptrCast(*const IWICBitmapFrameEncode, self), lineCount, cbStride, cbBufferSize, pbPixels); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IWICBitmapFrameEncode_WriteSource(self: *const T, pIBitmapSource: ?*IWICBitmapSource, prc: ?*WICRect) callconv(.Inline) HRESULT { return @ptrCast(*const IWICBitmapFrameEncode.VTable, self.vtable).WriteSource(@ptrCast(*const IWICBitmapFrameEncode, self), pIBitmapSource, prc); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IWICBitmapFrameEncode_Commit(self: *const T) callconv(.Inline) HRESULT { return @ptrCast(*const IWICBitmapFrameEncode.VTable, self.vtable).Commit(@ptrCast(*const IWICBitmapFrameEncode, self)); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IWICBitmapFrameEncode_GetMetadataQueryWriter(self: *const T, ppIMetadataQueryWriter: ?*?*IWICMetadataQueryWriter) callconv(.Inline) HRESULT { return @ptrCast(*const IWICBitmapFrameEncode.VTable, self.vtable).GetMetadataQueryWriter(@ptrCast(*const IWICBitmapFrameEncode, self), ppIMetadataQueryWriter); } };} pub usingnamespace MethodMixin(@This()); }; // TODO: this type is limited to platform 'windows8.1' const IID_IWICPlanarBitmapFrameEncode_Value = Guid.initString("f928b7b8-2221-40c1-b72e-7e82f1974d1a"); pub const IID_IWICPlanarBitmapFrameEncode = &IID_IWICPlanarBitmapFrameEncode_Value; pub const IWICPlanarBitmapFrameEncode = extern struct { pub const VTable = extern struct { base: IUnknown.VTable, WritePixels: fn( self: *const IWICPlanarBitmapFrameEncode, lineCount: u32, pPlanes: [*]WICBitmapPlane, cPlanes: u32, ) callconv(@import("std").os.windows.WINAPI) HRESULT, WriteSource: fn( self: *const IWICPlanarBitmapFrameEncode, ppPlanes: [*]?*IWICBitmapSource, cPlanes: u32, prcSource: ?*WICRect, ) 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 IWICPlanarBitmapFrameEncode_WritePixels(self: *const T, lineCount: u32, pPlanes: [*]WICBitmapPlane, cPlanes: u32) callconv(.Inline) HRESULT { return @ptrCast(*const IWICPlanarBitmapFrameEncode.VTable, self.vtable).WritePixels(@ptrCast(*const IWICPlanarBitmapFrameEncode, self), lineCount, pPlanes, cPlanes); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IWICPlanarBitmapFrameEncode_WriteSource(self: *const T, ppPlanes: [*]?*IWICBitmapSource, cPlanes: u32, prcSource: ?*WICRect) callconv(.Inline) HRESULT { return @ptrCast(*const IWICPlanarBitmapFrameEncode.VTable, self.vtable).WriteSource(@ptrCast(*const IWICPlanarBitmapFrameEncode, self), ppPlanes, cPlanes, prcSource); } };} pub usingnamespace MethodMixin(@This()); }; // TODO: this type is limited to platform 'windows5.1.2600' const IID_IWICBitmapDecoder_Value = Guid.initString("9edde9e7-8dee-47ea-99df-e6faf2ed44bf"); pub const IID_IWICBitmapDecoder = &IID_IWICBitmapDecoder_Value; pub const IWICBitmapDecoder = extern struct { pub const VTable = extern struct { base: IUnknown.VTable, QueryCapability: fn( self: *const IWICBitmapDecoder, pIStream: ?*IStream, pdwCapability: ?*u32, ) callconv(@import("std").os.windows.WINAPI) HRESULT, Initialize: fn( self: *const IWICBitmapDecoder, pIStream: ?*IStream, cacheOptions: WICDecodeOptions, ) callconv(@import("std").os.windows.WINAPI) HRESULT, GetContainerFormat: fn( self: *const IWICBitmapDecoder, pguidContainerFormat: ?*Guid, ) callconv(@import("std").os.windows.WINAPI) HRESULT, GetDecoderInfo: fn( self: *const IWICBitmapDecoder, ppIDecoderInfo: ?*?*IWICBitmapDecoderInfo, ) callconv(@import("std").os.windows.WINAPI) HRESULT, CopyPalette: fn( self: *const IWICBitmapDecoder, pIPalette: ?*IWICPalette, ) callconv(@import("std").os.windows.WINAPI) HRESULT, GetMetadataQueryReader: fn( self: *const IWICBitmapDecoder, ppIMetadataQueryReader: ?*?*IWICMetadataQueryReader, ) callconv(@import("std").os.windows.WINAPI) HRESULT, GetPreview: fn( self: *const IWICBitmapDecoder, ppIBitmapSource: ?*?*IWICBitmapSource, ) callconv(@import("std").os.windows.WINAPI) HRESULT, GetColorContexts: fn( self: *const IWICBitmapDecoder, cCount: u32, ppIColorContexts: [*]?*IWICColorContext, pcActualCount: ?*u32, ) callconv(@import("std").os.windows.WINAPI) HRESULT, GetThumbnail: fn( self: *const IWICBitmapDecoder, ppIThumbnail: ?*?*IWICBitmapSource, ) callconv(@import("std").os.windows.WINAPI) HRESULT, GetFrameCount: fn( self: *const IWICBitmapDecoder, pCount: ?*u32, ) callconv(@import("std").os.windows.WINAPI) HRESULT, GetFrame: fn( self: *const IWICBitmapDecoder, index: u32, ppIBitmapFrame: ?*?*IWICBitmapFrameDecode, ) 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 IWICBitmapDecoder_QueryCapability(self: *const T, pIStream: ?*IStream, pdwCapability: ?*u32) callconv(.Inline) HRESULT { return @ptrCast(*const IWICBitmapDecoder.VTable, self.vtable).QueryCapability(@ptrCast(*const IWICBitmapDecoder, self), pIStream, pdwCapability); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IWICBitmapDecoder_Initialize(self: *const T, pIStream: ?*IStream, cacheOptions: WICDecodeOptions) callconv(.Inline) HRESULT { return @ptrCast(*const IWICBitmapDecoder.VTable, self.vtable).Initialize(@ptrCast(*const IWICBitmapDecoder, self), pIStream, cacheOptions); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IWICBitmapDecoder_GetContainerFormat(self: *const T, pguidContainerFormat: ?*Guid) callconv(.Inline) HRESULT { return @ptrCast(*const IWICBitmapDecoder.VTable, self.vtable).GetContainerFormat(@ptrCast(*const IWICBitmapDecoder, self), pguidContainerFormat); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IWICBitmapDecoder_GetDecoderInfo(self: *const T, ppIDecoderInfo: ?*?*IWICBitmapDecoderInfo) callconv(.Inline) HRESULT { return @ptrCast(*const IWICBitmapDecoder.VTable, self.vtable).GetDecoderInfo(@ptrCast(*const IWICBitmapDecoder, self), ppIDecoderInfo); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IWICBitmapDecoder_CopyPalette(self: *const T, pIPalette: ?*IWICPalette) callconv(.Inline) HRESULT { return @ptrCast(*const IWICBitmapDecoder.VTable, self.vtable).CopyPalette(@ptrCast(*const IWICBitmapDecoder, self), pIPalette); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IWICBitmapDecoder_GetMetadataQueryReader(self: *const T, ppIMetadataQueryReader: ?*?*IWICMetadataQueryReader) callconv(.Inline) HRESULT { return @ptrCast(*const IWICBitmapDecoder.VTable, self.vtable).GetMetadataQueryReader(@ptrCast(*const IWICBitmapDecoder, self), ppIMetadataQueryReader); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IWICBitmapDecoder_GetPreview(self: *const T, ppIBitmapSource: ?*?*IWICBitmapSource) callconv(.Inline) HRESULT { return @ptrCast(*const IWICBitmapDecoder.VTable, self.vtable).GetPreview(@ptrCast(*const IWICBitmapDecoder, self), ppIBitmapSource); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IWICBitmapDecoder_GetColorContexts(self: *const T, cCount: u32, ppIColorContexts: [*]?*IWICColorContext, pcActualCount: ?*u32) callconv(.Inline) HRESULT { return @ptrCast(*const IWICBitmapDecoder.VTable, self.vtable).GetColorContexts(@ptrCast(*const IWICBitmapDecoder, self), cCount, ppIColorContexts, pcActualCount); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IWICBitmapDecoder_GetThumbnail(self: *const T, ppIThumbnail: ?*?*IWICBitmapSource) callconv(.Inline) HRESULT { return @ptrCast(*const IWICBitmapDecoder.VTable, self.vtable).GetThumbnail(@ptrCast(*const IWICBitmapDecoder, self), ppIThumbnail); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IWICBitmapDecoder_GetFrameCount(self: *const T, pCount: ?*u32) callconv(.Inline) HRESULT { return @ptrCast(*const IWICBitmapDecoder.VTable, self.vtable).GetFrameCount(@ptrCast(*const IWICBitmapDecoder, self), pCount); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IWICBitmapDecoder_GetFrame(self: *const T, index: u32, ppIBitmapFrame: ?*?*IWICBitmapFrameDecode) callconv(.Inline) HRESULT { return @ptrCast(*const IWICBitmapDecoder.VTable, self.vtable).GetFrame(@ptrCast(*const IWICBitmapDecoder, self), index, ppIBitmapFrame); } };} pub usingnamespace MethodMixin(@This()); }; // TODO: this type is limited to platform 'windows5.1.2600' const IID_IWICBitmapSourceTransform_Value = Guid.initString("3b16811b-6a43-4ec9-b713-3d5a0c13b940"); pub const IID_IWICBitmapSourceTransform = &IID_IWICBitmapSourceTransform_Value; pub const IWICBitmapSourceTransform = extern struct { pub const VTable = extern struct { base: IUnknown.VTable, CopyPixels: fn( self: *const IWICBitmapSourceTransform, prc: ?*const WICRect, uiWidth: u32, uiHeight: u32, pguidDstFormat: ?*Guid, dstTransform: WICBitmapTransformOptions, nStride: u32, cbBufferSize: u32, pbBuffer: [*:0]u8, ) callconv(@import("std").os.windows.WINAPI) HRESULT, GetClosestSize: fn( self: *const IWICBitmapSourceTransform, puiWidth: ?*u32, puiHeight: ?*u32, ) callconv(@import("std").os.windows.WINAPI) HRESULT, GetClosestPixelFormat: fn( self: *const IWICBitmapSourceTransform, pguidDstFormat: ?*Guid, ) callconv(@import("std").os.windows.WINAPI) HRESULT, DoesSupportTransform: fn( self: *const IWICBitmapSourceTransform, dstTransform: WICBitmapTransformOptions, pfIsSupported: ?*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 IWICBitmapSourceTransform_CopyPixels(self: *const T, prc: ?*const WICRect, uiWidth: u32, uiHeight: u32, pguidDstFormat: ?*Guid, dstTransform: WICBitmapTransformOptions, nStride: u32, cbBufferSize: u32, pbBuffer: [*:0]u8) callconv(.Inline) HRESULT { return @ptrCast(*const IWICBitmapSourceTransform.VTable, self.vtable).CopyPixels(@ptrCast(*const IWICBitmapSourceTransform, self), prc, uiWidth, uiHeight, pguidDstFormat, dstTransform, nStride, cbBufferSize, pbBuffer); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IWICBitmapSourceTransform_GetClosestSize(self: *const T, puiWidth: ?*u32, puiHeight: ?*u32) callconv(.Inline) HRESULT { return @ptrCast(*const IWICBitmapSourceTransform.VTable, self.vtable).GetClosestSize(@ptrCast(*const IWICBitmapSourceTransform, self), puiWidth, puiHeight); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IWICBitmapSourceTransform_GetClosestPixelFormat(self: *const T, pguidDstFormat: ?*Guid) callconv(.Inline) HRESULT { return @ptrCast(*const IWICBitmapSourceTransform.VTable, self.vtable).GetClosestPixelFormat(@ptrCast(*const IWICBitmapSourceTransform, self), pguidDstFormat); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IWICBitmapSourceTransform_DoesSupportTransform(self: *const T, dstTransform: WICBitmapTransformOptions, pfIsSupported: ?*BOOL) callconv(.Inline) HRESULT { return @ptrCast(*const IWICBitmapSourceTransform.VTable, self.vtable).DoesSupportTransform(@ptrCast(*const IWICBitmapSourceTransform, self), dstTransform, pfIsSupported); } };} pub usingnamespace MethodMixin(@This()); }; // TODO: this type is limited to platform 'windows8.1' const IID_IWICPlanarBitmapSourceTransform_Value = Guid.initString("3aff9cce-be95-4303-b927-e7d16ff4a613"); pub const IID_IWICPlanarBitmapSourceTransform = &IID_IWICPlanarBitmapSourceTransform_Value; pub const IWICPlanarBitmapSourceTransform = extern struct { pub const VTable = extern struct { base: IUnknown.VTable, DoesSupportTransform: fn( self: *const IWICPlanarBitmapSourceTransform, puiWidth: ?*u32, puiHeight: ?*u32, dstTransform: WICBitmapTransformOptions, dstPlanarOptions: WICPlanarOptions, pguidDstFormats: [*]const Guid, pPlaneDescriptions: [*]WICBitmapPlaneDescription, cPlanes: u32, pfIsSupported: ?*BOOL, ) callconv(@import("std").os.windows.WINAPI) HRESULT, CopyPixels: fn( self: *const IWICPlanarBitmapSourceTransform, prcSource: ?*const WICRect, uiWidth: u32, uiHeight: u32, dstTransform: WICBitmapTransformOptions, dstPlanarOptions: WICPlanarOptions, pDstPlanes: [*]const WICBitmapPlane, cPlanes: 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 IWICPlanarBitmapSourceTransform_DoesSupportTransform(self: *const T, puiWidth: ?*u32, puiHeight: ?*u32, dstTransform: WICBitmapTransformOptions, dstPlanarOptions: WICPlanarOptions, pguidDstFormats: [*]const Guid, pPlaneDescriptions: [*]WICBitmapPlaneDescription, cPlanes: u32, pfIsSupported: ?*BOOL) callconv(.Inline) HRESULT { return @ptrCast(*const IWICPlanarBitmapSourceTransform.VTable, self.vtable).DoesSupportTransform(@ptrCast(*const IWICPlanarBitmapSourceTransform, self), puiWidth, puiHeight, dstTransform, dstPlanarOptions, pguidDstFormats, pPlaneDescriptions, cPlanes, pfIsSupported); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IWICPlanarBitmapSourceTransform_CopyPixels(self: *const T, prcSource: ?*const WICRect, uiWidth: u32, uiHeight: u32, dstTransform: WICBitmapTransformOptions, dstPlanarOptions: WICPlanarOptions, pDstPlanes: [*]const WICBitmapPlane, cPlanes: u32) callconv(.Inline) HRESULT { return @ptrCast(*const IWICPlanarBitmapSourceTransform.VTable, self.vtable).CopyPixels(@ptrCast(*const IWICPlanarBitmapSourceTransform, self), prcSource, uiWidth, uiHeight, dstTransform, dstPlanarOptions, pDstPlanes, cPlanes); } };} pub usingnamespace MethodMixin(@This()); }; // TODO: this type is limited to platform 'windows5.1.2600' const IID_IWICBitmapFrameDecode_Value = Guid.initString("3b16811b-6a43-4ec9-a813-3d930c13b940"); pub const IID_IWICBitmapFrameDecode = &IID_IWICBitmapFrameDecode_Value; pub const IWICBitmapFrameDecode = extern struct { pub const VTable = extern struct { base: IWICBitmapSource.VTable, GetMetadataQueryReader: fn( self: *const IWICBitmapFrameDecode, ppIMetadataQueryReader: ?*?*IWICMetadataQueryReader, ) callconv(@import("std").os.windows.WINAPI) HRESULT, GetColorContexts: fn( self: *const IWICBitmapFrameDecode, cCount: u32, ppIColorContexts: [*]?*IWICColorContext, pcActualCount: ?*u32, ) callconv(@import("std").os.windows.WINAPI) HRESULT, GetThumbnail: fn( self: *const IWICBitmapFrameDecode, ppIThumbnail: ?*?*IWICBitmapSource, ) callconv(@import("std").os.windows.WINAPI) HRESULT, }; vtable: *const VTable, pub fn MethodMixin(comptime T: type) type { return struct { pub usingnamespace IWICBitmapSource.MethodMixin(T); // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IWICBitmapFrameDecode_GetMetadataQueryReader(self: *const T, ppIMetadataQueryReader: ?*?*IWICMetadataQueryReader) callconv(.Inline) HRESULT { return @ptrCast(*const IWICBitmapFrameDecode.VTable, self.vtable).GetMetadataQueryReader(@ptrCast(*const IWICBitmapFrameDecode, self), ppIMetadataQueryReader); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IWICBitmapFrameDecode_GetColorContexts(self: *const T, cCount: u32, ppIColorContexts: [*]?*IWICColorContext, pcActualCount: ?*u32) callconv(.Inline) HRESULT { return @ptrCast(*const IWICBitmapFrameDecode.VTable, self.vtable).GetColorContexts(@ptrCast(*const IWICBitmapFrameDecode, self), cCount, ppIColorContexts, pcActualCount); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IWICBitmapFrameDecode_GetThumbnail(self: *const T, ppIThumbnail: ?*?*IWICBitmapSource) callconv(.Inline) HRESULT { return @ptrCast(*const IWICBitmapFrameDecode.VTable, self.vtable).GetThumbnail(@ptrCast(*const IWICBitmapFrameDecode, self), ppIThumbnail); } };} pub usingnamespace MethodMixin(@This()); }; // TODO: this type is limited to platform 'windows6.1' const IID_IWICProgressiveLevelControl_Value = Guid.initString("daac296f-7aa5-4dbf-8d15-225c5976f891"); pub const IID_IWICProgressiveLevelControl = &IID_IWICProgressiveLevelControl_Value; pub const IWICProgressiveLevelControl = extern struct { pub const VTable = extern struct { base: IUnknown.VTable, GetLevelCount: fn( self: *const IWICProgressiveLevelControl, pcLevels: ?*u32, ) callconv(@import("std").os.windows.WINAPI) HRESULT, GetCurrentLevel: fn( self: *const IWICProgressiveLevelControl, pnLevel: ?*u32, ) callconv(@import("std").os.windows.WINAPI) HRESULT, SetCurrentLevel: fn( self: *const IWICProgressiveLevelControl, nLevel: 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 IWICProgressiveLevelControl_GetLevelCount(self: *const T, pcLevels: ?*u32) callconv(.Inline) HRESULT { return @ptrCast(*const IWICProgressiveLevelControl.VTable, self.vtable).GetLevelCount(@ptrCast(*const IWICProgressiveLevelControl, self), pcLevels); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IWICProgressiveLevelControl_GetCurrentLevel(self: *const T, pnLevel: ?*u32) callconv(.Inline) HRESULT { return @ptrCast(*const IWICProgressiveLevelControl.VTable, self.vtable).GetCurrentLevel(@ptrCast(*const IWICProgressiveLevelControl, self), pnLevel); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IWICProgressiveLevelControl_SetCurrentLevel(self: *const T, nLevel: u32) callconv(.Inline) HRESULT { return @ptrCast(*const IWICProgressiveLevelControl.VTable, self.vtable).SetCurrentLevel(@ptrCast(*const IWICProgressiveLevelControl, self), nLevel); } };} pub usingnamespace MethodMixin(@This()); }; // TODO: this type is limited to platform 'windows6.1' const IID_IWICProgressCallback_Value = Guid.initString("4776f9cd-9517-45fa-bf24-e89c5ec5c60c"); pub const IID_IWICProgressCallback = &IID_IWICProgressCallback_Value; pub const IWICProgressCallback = extern struct { pub const VTable = extern struct { base: IUnknown.VTable, Notify: fn( self: *const IWICProgressCallback, uFrameNum: u32, operation: WICProgressOperation, dblProgress: f64, ) 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 IWICProgressCallback_Notify(self: *const T, uFrameNum: u32, operation: WICProgressOperation, dblProgress: f64) callconv(.Inline) HRESULT { return @ptrCast(*const IWICProgressCallback.VTable, self.vtable).Notify(@ptrCast(*const IWICProgressCallback, self), uFrameNum, operation, dblProgress); } };} pub usingnamespace MethodMixin(@This()); }; pub const PFNProgressNotification = fn( pvData: ?*anyopaque, uFrameNum: u32, operation: WICProgressOperation, dblProgress: f64, ) callconv(@import("std").os.windows.WINAPI) HRESULT; // TODO: this type is limited to platform 'windows5.1.2600' const IID_IWICBitmapCodecProgressNotification_Value = Guid.initString("64c1024e-c3cf-4462-8078-88c2b11c46d9"); pub const IID_IWICBitmapCodecProgressNotification = &IID_IWICBitmapCodecProgressNotification_Value; pub const IWICBitmapCodecProgressNotification = extern struct { pub const VTable = extern struct { base: IUnknown.VTable, RegisterProgressNotification: fn( self: *const IWICBitmapCodecProgressNotification, pfnProgressNotification: ?PFNProgressNotification, pvData: ?*anyopaque, dwProgressFlags: 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 IWICBitmapCodecProgressNotification_RegisterProgressNotification(self: *const T, pfnProgressNotification: ?PFNProgressNotification, pvData: ?*anyopaque, dwProgressFlags: u32) callconv(.Inline) HRESULT { return @ptrCast(*const IWICBitmapCodecProgressNotification.VTable, self.vtable).RegisterProgressNotification(@ptrCast(*const IWICBitmapCodecProgressNotification, self), pfnProgressNotification, pvData, dwProgressFlags); } };} pub usingnamespace MethodMixin(@This()); }; // TODO: this type is limited to platform 'windows5.1.2600' const IID_IWICComponentInfo_Value = Guid.initString("23bc3f0a-698b-4357-886b-f24d50671334"); pub const IID_IWICComponentInfo = &IID_IWICComponentInfo_Value; pub const IWICComponentInfo = extern struct { pub const VTable = extern struct { base: IUnknown.VTable, GetComponentType: fn( self: *const IWICComponentInfo, pType: ?*WICComponentType, ) callconv(@import("std").os.windows.WINAPI) HRESULT, GetCLSID: fn( self: *const IWICComponentInfo, pclsid: ?*Guid, ) callconv(@import("std").os.windows.WINAPI) HRESULT, GetSigningStatus: fn( self: *const IWICComponentInfo, pStatus: ?*u32, ) callconv(@import("std").os.windows.WINAPI) HRESULT, GetAuthor: fn( self: *const IWICComponentInfo, cchAuthor: u32, wzAuthor: [*:0]u16, pcchActual: ?*u32, ) callconv(@import("std").os.windows.WINAPI) HRESULT, GetVendorGUID: fn( self: *const IWICComponentInfo, pguidVendor: ?*Guid, ) callconv(@import("std").os.windows.WINAPI) HRESULT, GetVersion: fn( self: *const IWICComponentInfo, cchVersion: u32, wzVersion: [*:0]u16, pcchActual: ?*u32, ) callconv(@import("std").os.windows.WINAPI) HRESULT, GetSpecVersion: fn( self: *const IWICComponentInfo, cchSpecVersion: u32, wzSpecVersion: [*:0]u16, pcchActual: ?*u32, ) callconv(@import("std").os.windows.WINAPI) HRESULT, GetFriendlyName: fn( self: *const IWICComponentInfo, cchFriendlyName: u32, wzFriendlyName: [*:0]u16, pcchActual: ?*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 IWICComponentInfo_GetComponentType(self: *const T, pType: ?*WICComponentType) callconv(.Inline) HRESULT { return @ptrCast(*const IWICComponentInfo.VTable, self.vtable).GetComponentType(@ptrCast(*const IWICComponentInfo, self), pType); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IWICComponentInfo_GetCLSID(self: *const T, pclsid: ?*Guid) callconv(.Inline) HRESULT { return @ptrCast(*const IWICComponentInfo.VTable, self.vtable).GetCLSID(@ptrCast(*const IWICComponentInfo, self), pclsid); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IWICComponentInfo_GetSigningStatus(self: *const T, pStatus: ?*u32) callconv(.Inline) HRESULT { return @ptrCast(*const IWICComponentInfo.VTable, self.vtable).GetSigningStatus(@ptrCast(*const IWICComponentInfo, self), pStatus); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IWICComponentInfo_GetAuthor(self: *const T, cchAuthor: u32, wzAuthor: [*:0]u16, pcchActual: ?*u32) callconv(.Inline) HRESULT { return @ptrCast(*const IWICComponentInfo.VTable, self.vtable).GetAuthor(@ptrCast(*const IWICComponentInfo, self), cchAuthor, wzAuthor, pcchActual); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IWICComponentInfo_GetVendorGUID(self: *const T, pguidVendor: ?*Guid) callconv(.Inline) HRESULT { return @ptrCast(*const IWICComponentInfo.VTable, self.vtable).GetVendorGUID(@ptrCast(*const IWICComponentInfo, self), pguidVendor); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IWICComponentInfo_GetVersion(self: *const T, cchVersion: u32, wzVersion: [*:0]u16, pcchActual: ?*u32) callconv(.Inline) HRESULT { return @ptrCast(*const IWICComponentInfo.VTable, self.vtable).GetVersion(@ptrCast(*const IWICComponentInfo, self), cchVersion, wzVersion, pcchActual); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IWICComponentInfo_GetSpecVersion(self: *const T, cchSpecVersion: u32, wzSpecVersion: [*:0]u16, pcchActual: ?*u32) callconv(.Inline) HRESULT { return @ptrCast(*const IWICComponentInfo.VTable, self.vtable).GetSpecVersion(@ptrCast(*const IWICComponentInfo, self), cchSpecVersion, wzSpecVersion, pcchActual); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IWICComponentInfo_GetFriendlyName(self: *const T, cchFriendlyName: u32, wzFriendlyName: [*:0]u16, pcchActual: ?*u32) callconv(.Inline) HRESULT { return @ptrCast(*const IWICComponentInfo.VTable, self.vtable).GetFriendlyName(@ptrCast(*const IWICComponentInfo, self), cchFriendlyName, wzFriendlyName, pcchActual); } };} pub usingnamespace MethodMixin(@This()); }; // TODO: this type is limited to platform 'windows5.1.2600' const IID_IWICFormatConverterInfo_Value = Guid.initString("9f34fb65-13f4-4f15-bc57-3726b5e53d9f"); pub const IID_IWICFormatConverterInfo = &IID_IWICFormatConverterInfo_Value; pub const IWICFormatConverterInfo = extern struct { pub const VTable = extern struct { base: IWICComponentInfo.VTable, GetPixelFormats: fn( self: *const IWICFormatConverterInfo, cFormats: u32, pPixelFormatGUIDs: [*]Guid, pcActual: ?*u32, ) callconv(@import("std").os.windows.WINAPI) HRESULT, CreateInstance: fn( self: *const IWICFormatConverterInfo, ppIConverter: ?*?*IWICFormatConverter, ) callconv(@import("std").os.windows.WINAPI) HRESULT, }; vtable: *const VTable, pub fn MethodMixin(comptime T: type) type { return struct { pub usingnamespace IWICComponentInfo.MethodMixin(T); // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IWICFormatConverterInfo_GetPixelFormats(self: *const T, cFormats: u32, pPixelFormatGUIDs: [*]Guid, pcActual: ?*u32) callconv(.Inline) HRESULT { return @ptrCast(*const IWICFormatConverterInfo.VTable, self.vtable).GetPixelFormats(@ptrCast(*const IWICFormatConverterInfo, self), cFormats, pPixelFormatGUIDs, pcActual); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IWICFormatConverterInfo_CreateInstance(self: *const T, ppIConverter: ?*?*IWICFormatConverter) callconv(.Inline) HRESULT { return @ptrCast(*const IWICFormatConverterInfo.VTable, self.vtable).CreateInstance(@ptrCast(*const IWICFormatConverterInfo, self), ppIConverter); } };} pub usingnamespace MethodMixin(@This()); }; // TODO: this type is limited to platform 'windows5.1.2600' const IID_IWICBitmapCodecInfo_Value = Guid.initString("e87a44c4-b76e-4c47-8b09-298eb12a2714"); pub const IID_IWICBitmapCodecInfo = &IID_IWICBitmapCodecInfo_Value; pub const IWICBitmapCodecInfo = extern struct { pub const VTable = extern struct { base: IWICComponentInfo.VTable, GetContainerFormat: fn( self: *const IWICBitmapCodecInfo, pguidContainerFormat: ?*Guid, ) callconv(@import("std").os.windows.WINAPI) HRESULT, GetPixelFormats: fn( self: *const IWICBitmapCodecInfo, cFormats: u32, pguidPixelFormats: [*]Guid, pcActual: ?*u32, ) callconv(@import("std").os.windows.WINAPI) HRESULT, GetColorManagementVersion: fn( self: *const IWICBitmapCodecInfo, cchColorManagementVersion: u32, wzColorManagementVersion: [*:0]u16, pcchActual: ?*u32, ) callconv(@import("std").os.windows.WINAPI) HRESULT, GetDeviceManufacturer: fn( self: *const IWICBitmapCodecInfo, cchDeviceManufacturer: u32, wzDeviceManufacturer: [*:0]u16, pcchActual: ?*u32, ) callconv(@import("std").os.windows.WINAPI) HRESULT, GetDeviceModels: fn( self: *const IWICBitmapCodecInfo, cchDeviceModels: u32, wzDeviceModels: [*:0]u16, pcchActual: ?*u32, ) callconv(@import("std").os.windows.WINAPI) HRESULT, GetMimeTypes: fn( self: *const IWICBitmapCodecInfo, cchMimeTypes: u32, wzMimeTypes: [*:0]u16, pcchActual: ?*u32, ) callconv(@import("std").os.windows.WINAPI) HRESULT, GetFileExtensions: fn( self: *const IWICBitmapCodecInfo, cchFileExtensions: u32, wzFileExtensions: [*:0]u16, pcchActual: ?*u32, ) callconv(@import("std").os.windows.WINAPI) HRESULT, DoesSupportAnimation: fn( self: *const IWICBitmapCodecInfo, pfSupportAnimation: ?*BOOL, ) callconv(@import("std").os.windows.WINAPI) HRESULT, DoesSupportChromakey: fn( self: *const IWICBitmapCodecInfo, pfSupportChromakey: ?*BOOL, ) callconv(@import("std").os.windows.WINAPI) HRESULT, DoesSupportLossless: fn( self: *const IWICBitmapCodecInfo, pfSupportLossless: ?*BOOL, ) callconv(@import("std").os.windows.WINAPI) HRESULT, DoesSupportMultiframe: fn( self: *const IWICBitmapCodecInfo, pfSupportMultiframe: ?*BOOL, ) callconv(@import("std").os.windows.WINAPI) HRESULT, MatchesMimeType: fn( self: *const IWICBitmapCodecInfo, wzMimeType: ?[*:0]const u16, pfMatches: ?*BOOL, ) callconv(@import("std").os.windows.WINAPI) HRESULT, }; vtable: *const VTable, pub fn MethodMixin(comptime T: type) type { return struct { pub usingnamespace IWICComponentInfo.MethodMixin(T); // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IWICBitmapCodecInfo_GetContainerFormat(self: *const T, pguidContainerFormat: ?*Guid) callconv(.Inline) HRESULT { return @ptrCast(*const IWICBitmapCodecInfo.VTable, self.vtable).GetContainerFormat(@ptrCast(*const IWICBitmapCodecInfo, self), pguidContainerFormat); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IWICBitmapCodecInfo_GetPixelFormats(self: *const T, cFormats: u32, pguidPixelFormats: [*]Guid, pcActual: ?*u32) callconv(.Inline) HRESULT { return @ptrCast(*const IWICBitmapCodecInfo.VTable, self.vtable).GetPixelFormats(@ptrCast(*const IWICBitmapCodecInfo, self), cFormats, pguidPixelFormats, pcActual); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IWICBitmapCodecInfo_GetColorManagementVersion(self: *const T, cchColorManagementVersion: u32, wzColorManagementVersion: [*:0]u16, pcchActual: ?*u32) callconv(.Inline) HRESULT { return @ptrCast(*const IWICBitmapCodecInfo.VTable, self.vtable).GetColorManagementVersion(@ptrCast(*const IWICBitmapCodecInfo, self), cchColorManagementVersion, wzColorManagementVersion, pcchActual); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IWICBitmapCodecInfo_GetDeviceManufacturer(self: *const T, cchDeviceManufacturer: u32, wzDeviceManufacturer: [*:0]u16, pcchActual: ?*u32) callconv(.Inline) HRESULT { return @ptrCast(*const IWICBitmapCodecInfo.VTable, self.vtable).GetDeviceManufacturer(@ptrCast(*const IWICBitmapCodecInfo, self), cchDeviceManufacturer, wzDeviceManufacturer, pcchActual); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IWICBitmapCodecInfo_GetDeviceModels(self: *const T, cchDeviceModels: u32, wzDeviceModels: [*:0]u16, pcchActual: ?*u32) callconv(.Inline) HRESULT { return @ptrCast(*const IWICBitmapCodecInfo.VTable, self.vtable).GetDeviceModels(@ptrCast(*const IWICBitmapCodecInfo, self), cchDeviceModels, wzDeviceModels, pcchActual); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IWICBitmapCodecInfo_GetMimeTypes(self: *const T, cchMimeTypes: u32, wzMimeTypes: [*:0]u16, pcchActual: ?*u32) callconv(.Inline) HRESULT { return @ptrCast(*const IWICBitmapCodecInfo.VTable, self.vtable).GetMimeTypes(@ptrCast(*const IWICBitmapCodecInfo, self), cchMimeTypes, wzMimeTypes, pcchActual); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IWICBitmapCodecInfo_GetFileExtensions(self: *const T, cchFileExtensions: u32, wzFileExtensions: [*:0]u16, pcchActual: ?*u32) callconv(.Inline) HRESULT { return @ptrCast(*const IWICBitmapCodecInfo.VTable, self.vtable).GetFileExtensions(@ptrCast(*const IWICBitmapCodecInfo, self), cchFileExtensions, wzFileExtensions, pcchActual); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IWICBitmapCodecInfo_DoesSupportAnimation(self: *const T, pfSupportAnimation: ?*BOOL) callconv(.Inline) HRESULT { return @ptrCast(*const IWICBitmapCodecInfo.VTable, self.vtable).DoesSupportAnimation(@ptrCast(*const IWICBitmapCodecInfo, self), pfSupportAnimation); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IWICBitmapCodecInfo_DoesSupportChromakey(self: *const T, pfSupportChromakey: ?*BOOL) callconv(.Inline) HRESULT { return @ptrCast(*const IWICBitmapCodecInfo.VTable, self.vtable).DoesSupportChromakey(@ptrCast(*const IWICBitmapCodecInfo, self), pfSupportChromakey); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IWICBitmapCodecInfo_DoesSupportLossless(self: *const T, pfSupportLossless: ?*BOOL) callconv(.Inline) HRESULT { return @ptrCast(*const IWICBitmapCodecInfo.VTable, self.vtable).DoesSupportLossless(@ptrCast(*const IWICBitmapCodecInfo, self), pfSupportLossless); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IWICBitmapCodecInfo_DoesSupportMultiframe(self: *const T, pfSupportMultiframe: ?*BOOL) callconv(.Inline) HRESULT { return @ptrCast(*const IWICBitmapCodecInfo.VTable, self.vtable).DoesSupportMultiframe(@ptrCast(*const IWICBitmapCodecInfo, self), pfSupportMultiframe); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IWICBitmapCodecInfo_MatchesMimeType(self: *const T, wzMimeType: ?[*:0]const u16, pfMatches: ?*BOOL) callconv(.Inline) HRESULT { return @ptrCast(*const IWICBitmapCodecInfo.VTable, self.vtable).MatchesMimeType(@ptrCast(*const IWICBitmapCodecInfo, self), wzMimeType, pfMatches); } };} pub usingnamespace MethodMixin(@This()); }; // TODO: this type is limited to platform 'windows5.1.2600' const IID_IWICBitmapEncoderInfo_Value = Guid.initString("94c9b4ee-a09f-4f92-8a1e-4a9bce7e76fb"); pub const IID_IWICBitmapEncoderInfo = &IID_IWICBitmapEncoderInfo_Value; pub const IWICBitmapEncoderInfo = extern struct { pub const VTable = extern struct { base: IWICBitmapCodecInfo.VTable, CreateInstance: fn( self: *const IWICBitmapEncoderInfo, ppIBitmapEncoder: ?*?*IWICBitmapEncoder, ) callconv(@import("std").os.windows.WINAPI) HRESULT, }; vtable: *const VTable, pub fn MethodMixin(comptime T: type) type { return struct { pub usingnamespace IWICBitmapCodecInfo.MethodMixin(T); // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IWICBitmapEncoderInfo_CreateInstance(self: *const T, ppIBitmapEncoder: ?*?*IWICBitmapEncoder) callconv(.Inline) HRESULT { return @ptrCast(*const IWICBitmapEncoderInfo.VTable, self.vtable).CreateInstance(@ptrCast(*const IWICBitmapEncoderInfo, self), ppIBitmapEncoder); } };} pub usingnamespace MethodMixin(@This()); }; // TODO: this type is limited to platform 'windows5.1.2600' const IID_IWICBitmapDecoderInfo_Value = Guid.initString("d8cd007f-d08f-4191-9bfc-236ea7f0e4b5"); pub const IID_IWICBitmapDecoderInfo = &IID_IWICBitmapDecoderInfo_Value; pub const IWICBitmapDecoderInfo = extern struct { pub const VTable = extern struct { base: IWICBitmapCodecInfo.VTable, GetPatterns: fn( self: *const IWICBitmapDecoderInfo, cbSizePatterns: u32, // TODO: what to do with BytesParamIndex 0? pPatterns: ?*WICBitmapPattern, pcPatterns: ?*u32, pcbPatternsActual: ?*u32, ) callconv(@import("std").os.windows.WINAPI) HRESULT, MatchesPattern: fn( self: *const IWICBitmapDecoderInfo, pIStream: ?*IStream, pfMatches: ?*BOOL, ) callconv(@import("std").os.windows.WINAPI) HRESULT, CreateInstance: fn( self: *const IWICBitmapDecoderInfo, ppIBitmapDecoder: ?*?*IWICBitmapDecoder, ) callconv(@import("std").os.windows.WINAPI) HRESULT, }; vtable: *const VTable, pub fn MethodMixin(comptime T: type) type { return struct { pub usingnamespace IWICBitmapCodecInfo.MethodMixin(T); // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IWICBitmapDecoderInfo_GetPatterns(self: *const T, cbSizePatterns: u32, pPatterns: ?*WICBitmapPattern, pcPatterns: ?*u32, pcbPatternsActual: ?*u32) callconv(.Inline) HRESULT { return @ptrCast(*const IWICBitmapDecoderInfo.VTable, self.vtable).GetPatterns(@ptrCast(*const IWICBitmapDecoderInfo, self), cbSizePatterns, pPatterns, pcPatterns, pcbPatternsActual); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IWICBitmapDecoderInfo_MatchesPattern(self: *const T, pIStream: ?*IStream, pfMatches: ?*BOOL) callconv(.Inline) HRESULT { return @ptrCast(*const IWICBitmapDecoderInfo.VTable, self.vtable).MatchesPattern(@ptrCast(*const IWICBitmapDecoderInfo, self), pIStream, pfMatches); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IWICBitmapDecoderInfo_CreateInstance(self: *const T, ppIBitmapDecoder: ?*?*IWICBitmapDecoder) callconv(.Inline) HRESULT { return @ptrCast(*const IWICBitmapDecoderInfo.VTable, self.vtable).CreateInstance(@ptrCast(*const IWICBitmapDecoderInfo, self), ppIBitmapDecoder); } };} pub usingnamespace MethodMixin(@This()); }; // TODO: this type is limited to platform 'windows5.1.2600' const IID_IWICPixelFormatInfo_Value = Guid.initString("e8eda601-3d48-431a-ab44-69059be88bbe"); pub const IID_IWICPixelFormatInfo = &IID_IWICPixelFormatInfo_Value; pub const IWICPixelFormatInfo = extern struct { pub const VTable = extern struct { base: IWICComponentInfo.VTable, GetFormatGUID: fn( self: *const IWICPixelFormatInfo, pFormat: ?*Guid, ) callconv(@import("std").os.windows.WINAPI) HRESULT, GetColorContext: fn( self: *const IWICPixelFormatInfo, ppIColorContext: ?*?*IWICColorContext, ) callconv(@import("std").os.windows.WINAPI) HRESULT, GetBitsPerPixel: fn( self: *const IWICPixelFormatInfo, puiBitsPerPixel: ?*u32, ) callconv(@import("std").os.windows.WINAPI) HRESULT, GetChannelCount: fn( self: *const IWICPixelFormatInfo, puiChannelCount: ?*u32, ) callconv(@import("std").os.windows.WINAPI) HRESULT, GetChannelMask: fn( self: *const IWICPixelFormatInfo, uiChannelIndex: u32, cbMaskBuffer: u32, pbMaskBuffer: [*:0]u8, pcbActual: ?*u32, ) callconv(@import("std").os.windows.WINAPI) HRESULT, }; vtable: *const VTable, pub fn MethodMixin(comptime T: type) type { return struct { pub usingnamespace IWICComponentInfo.MethodMixin(T); // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IWICPixelFormatInfo_GetFormatGUID(self: *const T, pFormat: ?*Guid) callconv(.Inline) HRESULT { return @ptrCast(*const IWICPixelFormatInfo.VTable, self.vtable).GetFormatGUID(@ptrCast(*const IWICPixelFormatInfo, self), pFormat); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IWICPixelFormatInfo_GetColorContext(self: *const T, ppIColorContext: ?*?*IWICColorContext) callconv(.Inline) HRESULT { return @ptrCast(*const IWICPixelFormatInfo.VTable, self.vtable).GetColorContext(@ptrCast(*const IWICPixelFormatInfo, self), ppIColorContext); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IWICPixelFormatInfo_GetBitsPerPixel(self: *const T, puiBitsPerPixel: ?*u32) callconv(.Inline) HRESULT { return @ptrCast(*const IWICPixelFormatInfo.VTable, self.vtable).GetBitsPerPixel(@ptrCast(*const IWICPixelFormatInfo, self), puiBitsPerPixel); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IWICPixelFormatInfo_GetChannelCount(self: *const T, puiChannelCount: ?*u32) callconv(.Inline) HRESULT { return @ptrCast(*const IWICPixelFormatInfo.VTable, self.vtable).GetChannelCount(@ptrCast(*const IWICPixelFormatInfo, self), puiChannelCount); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IWICPixelFormatInfo_GetChannelMask(self: *const T, uiChannelIndex: u32, cbMaskBuffer: u32, pbMaskBuffer: [*:0]u8, pcbActual: ?*u32) callconv(.Inline) HRESULT { return @ptrCast(*const IWICPixelFormatInfo.VTable, self.vtable).GetChannelMask(@ptrCast(*const IWICPixelFormatInfo, self), uiChannelIndex, cbMaskBuffer, pbMaskBuffer, pcbActual); } };} pub usingnamespace MethodMixin(@This()); }; // TODO: this type is limited to platform 'windows6.1' const IID_IWICPixelFormatInfo2_Value = Guid.initString("a9db33a2-af5f-43c7-b679-74f5984b5aa4"); pub const IID_IWICPixelFormatInfo2 = &IID_IWICPixelFormatInfo2_Value; pub const IWICPixelFormatInfo2 = extern struct { pub const VTable = extern struct { base: IWICPixelFormatInfo.VTable, SupportsTransparency: fn( self: *const IWICPixelFormatInfo2, pfSupportsTransparency: ?*BOOL, ) callconv(@import("std").os.windows.WINAPI) HRESULT, GetNumericRepresentation: fn( self: *const IWICPixelFormatInfo2, pNumericRepresentation: ?*WICPixelFormatNumericRepresentation, ) callconv(@import("std").os.windows.WINAPI) HRESULT, }; vtable: *const VTable, pub fn MethodMixin(comptime T: type) type { return struct { pub usingnamespace IWICPixelFormatInfo.MethodMixin(T); // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IWICPixelFormatInfo2_SupportsTransparency(self: *const T, pfSupportsTransparency: ?*BOOL) callconv(.Inline) HRESULT { return @ptrCast(*const IWICPixelFormatInfo2.VTable, self.vtable).SupportsTransparency(@ptrCast(*const IWICPixelFormatInfo2, self), pfSupportsTransparency); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IWICPixelFormatInfo2_GetNumericRepresentation(self: *const T, pNumericRepresentation: ?*WICPixelFormatNumericRepresentation) callconv(.Inline) HRESULT { return @ptrCast(*const IWICPixelFormatInfo2.VTable, self.vtable).GetNumericRepresentation(@ptrCast(*const IWICPixelFormatInfo2, self), pNumericRepresentation); } };} pub usingnamespace MethodMixin(@This()); }; // TODO: this type is limited to platform 'windows5.1.2600' const IID_IWICImagingFactory_Value = Guid.initString("ec5ec8a9-c395-4314-9c77-54d7a935ff70"); pub const IID_IWICImagingFactory = &IID_IWICImagingFactory_Value; pub const IWICImagingFactory = extern struct { pub const VTable = extern struct { base: IUnknown.VTable, CreateDecoderFromFilename: fn( self: *const IWICImagingFactory, wzFilename: ?[*:0]const u16, pguidVendor: ?*const Guid, dwDesiredAccess: u32, metadataOptions: WICDecodeOptions, ppIDecoder: ?*?*IWICBitmapDecoder, ) callconv(@import("std").os.windows.WINAPI) HRESULT, CreateDecoderFromStream: fn( self: *const IWICImagingFactory, pIStream: ?*IStream, pguidVendor: ?*const Guid, metadataOptions: WICDecodeOptions, ppIDecoder: ?*?*IWICBitmapDecoder, ) callconv(@import("std").os.windows.WINAPI) HRESULT, CreateDecoderFromFileHandle: fn( self: *const IWICImagingFactory, hFile: usize, pguidVendor: ?*const Guid, metadataOptions: WICDecodeOptions, ppIDecoder: ?*?*IWICBitmapDecoder, ) callconv(@import("std").os.windows.WINAPI) HRESULT, CreateComponentInfo: fn( self: *const IWICImagingFactory, clsidComponent: ?*const Guid, ppIInfo: ?*?*IWICComponentInfo, ) callconv(@import("std").os.windows.WINAPI) HRESULT, CreateDecoder: fn( self: *const IWICImagingFactory, guidContainerFormat: ?*const Guid, pguidVendor: ?*const Guid, ppIDecoder: ?*?*IWICBitmapDecoder, ) callconv(@import("std").os.windows.WINAPI) HRESULT, CreateEncoder: fn( self: *const IWICImagingFactory, guidContainerFormat: ?*const Guid, pguidVendor: ?*const Guid, ppIEncoder: ?*?*IWICBitmapEncoder, ) callconv(@import("std").os.windows.WINAPI) HRESULT, CreatePalette: fn( self: *const IWICImagingFactory, ppIPalette: ?*?*IWICPalette, ) callconv(@import("std").os.windows.WINAPI) HRESULT, CreateFormatConverter: fn( self: *const IWICImagingFactory, ppIFormatConverter: ?*?*IWICFormatConverter, ) callconv(@import("std").os.windows.WINAPI) HRESULT, CreateBitmapScaler: fn( self: *const IWICImagingFactory, ppIBitmapScaler: ?*?*IWICBitmapScaler, ) callconv(@import("std").os.windows.WINAPI) HRESULT, CreateBitmapClipper: fn( self: *const IWICImagingFactory, ppIBitmapClipper: ?*?*IWICBitmapClipper, ) callconv(@import("std").os.windows.WINAPI) HRESULT, CreateBitmapFlipRotator: fn( self: *const IWICImagingFactory, ppIBitmapFlipRotator: ?*?*IWICBitmapFlipRotator, ) callconv(@import("std").os.windows.WINAPI) HRESULT, CreateStream: fn( self: *const IWICImagingFactory, ppIWICStream: ?*?*IWICStream, ) callconv(@import("std").os.windows.WINAPI) HRESULT, CreateColorContext: fn( self: *const IWICImagingFactory, ppIWICColorContext: ?*?*IWICColorContext, ) callconv(@import("std").os.windows.WINAPI) HRESULT, CreateColorTransformer: fn( self: *const IWICImagingFactory, ppIWICColorTransform: ?*?*IWICColorTransform, ) callconv(@import("std").os.windows.WINAPI) HRESULT, CreateBitmap: fn( self: *const IWICImagingFactory, uiWidth: u32, uiHeight: u32, pixelFormat: ?*Guid, option: WICBitmapCreateCacheOption, ppIBitmap: ?*?*IWICBitmap, ) callconv(@import("std").os.windows.WINAPI) HRESULT, CreateBitmapFromSource: fn( self: *const IWICImagingFactory, pIBitmapSource: ?*IWICBitmapSource, option: WICBitmapCreateCacheOption, ppIBitmap: ?*?*IWICBitmap, ) callconv(@import("std").os.windows.WINAPI) HRESULT, CreateBitmapFromSourceRect: fn( self: *const IWICImagingFactory, pIBitmapSource: ?*IWICBitmapSource, x: u32, y: u32, width: u32, height: u32, ppIBitmap: ?*?*IWICBitmap, ) callconv(@import("std").os.windows.WINAPI) HRESULT, CreateBitmapFromMemory: fn( self: *const IWICImagingFactory, uiWidth: u32, uiHeight: u32, pixelFormat: ?*Guid, cbStride: u32, cbBufferSize: u32, pbBuffer: [*:0]u8, ppIBitmap: ?*?*IWICBitmap, ) callconv(@import("std").os.windows.WINAPI) HRESULT, CreateBitmapFromHBITMAP: fn( self: *const IWICImagingFactory, hBitmap: ?HBITMAP, hPalette: ?HPALETTE, options: WICBitmapAlphaChannelOption, ppIBitmap: ?*?*IWICBitmap, ) callconv(@import("std").os.windows.WINAPI) HRESULT, CreateBitmapFromHICON: fn( self: *const IWICImagingFactory, hIcon: ?HICON, ppIBitmap: ?*?*IWICBitmap, ) callconv(@import("std").os.windows.WINAPI) HRESULT, CreateComponentEnumerator: fn( self: *const IWICImagingFactory, componentTypes: u32, options: u32, ppIEnumUnknown: ?*?*IEnumUnknown, ) callconv(@import("std").os.windows.WINAPI) HRESULT, CreateFastMetadataEncoderFromDecoder: fn( self: *const IWICImagingFactory, pIDecoder: ?*IWICBitmapDecoder, ppIFastEncoder: ?*?*IWICFastMetadataEncoder, ) callconv(@import("std").os.windows.WINAPI) HRESULT, CreateFastMetadataEncoderFromFrameDecode: fn( self: *const IWICImagingFactory, pIFrameDecoder: ?*IWICBitmapFrameDecode, ppIFastEncoder: ?*?*IWICFastMetadataEncoder, ) callconv(@import("std").os.windows.WINAPI) HRESULT, CreateQueryWriter: fn( self: *const IWICImagingFactory, guidMetadataFormat: ?*const Guid, pguidVendor: ?*const Guid, ppIQueryWriter: ?*?*IWICMetadataQueryWriter, ) callconv(@import("std").os.windows.WINAPI) HRESULT, CreateQueryWriterFromReader: fn( self: *const IWICImagingFactory, pIQueryReader: ?*IWICMetadataQueryReader, pguidVendor: ?*const Guid, ppIQueryWriter: ?*?*IWICMetadataQueryWriter, ) 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 IWICImagingFactory_CreateDecoderFromFilename(self: *const T, wzFilename: ?[*:0]const u16, pguidVendor: ?*const Guid, dwDesiredAccess: u32, metadataOptions: WICDecodeOptions, ppIDecoder: ?*?*IWICBitmapDecoder) callconv(.Inline) HRESULT { return @ptrCast(*const IWICImagingFactory.VTable, self.vtable).CreateDecoderFromFilename(@ptrCast(*const IWICImagingFactory, self), wzFilename, pguidVendor, dwDesiredAccess, metadataOptions, ppIDecoder); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IWICImagingFactory_CreateDecoderFromStream(self: *const T, pIStream: ?*IStream, pguidVendor: ?*const Guid, metadataOptions: WICDecodeOptions, ppIDecoder: ?*?*IWICBitmapDecoder) callconv(.Inline) HRESULT { return @ptrCast(*const IWICImagingFactory.VTable, self.vtable).CreateDecoderFromStream(@ptrCast(*const IWICImagingFactory, self), pIStream, pguidVendor, metadataOptions, ppIDecoder); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IWICImagingFactory_CreateDecoderFromFileHandle(self: *const T, hFile: usize, pguidVendor: ?*const Guid, metadataOptions: WICDecodeOptions, ppIDecoder: ?*?*IWICBitmapDecoder) callconv(.Inline) HRESULT { return @ptrCast(*const IWICImagingFactory.VTable, self.vtable).CreateDecoderFromFileHandle(@ptrCast(*const IWICImagingFactory, self), hFile, pguidVendor, metadataOptions, ppIDecoder); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IWICImagingFactory_CreateComponentInfo(self: *const T, clsidComponent: ?*const Guid, ppIInfo: ?*?*IWICComponentInfo) callconv(.Inline) HRESULT { return @ptrCast(*const IWICImagingFactory.VTable, self.vtable).CreateComponentInfo(@ptrCast(*const IWICImagingFactory, self), clsidComponent, ppIInfo); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IWICImagingFactory_CreateDecoder(self: *const T, guidContainerFormat: ?*const Guid, pguidVendor: ?*const Guid, ppIDecoder: ?*?*IWICBitmapDecoder) callconv(.Inline) HRESULT { return @ptrCast(*const IWICImagingFactory.VTable, self.vtable).CreateDecoder(@ptrCast(*const IWICImagingFactory, self), guidContainerFormat, pguidVendor, ppIDecoder); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IWICImagingFactory_CreateEncoder(self: *const T, guidContainerFormat: ?*const Guid, pguidVendor: ?*const Guid, ppIEncoder: ?*?*IWICBitmapEncoder) callconv(.Inline) HRESULT { return @ptrCast(*const IWICImagingFactory.VTable, self.vtable).CreateEncoder(@ptrCast(*const IWICImagingFactory, self), guidContainerFormat, pguidVendor, ppIEncoder); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IWICImagingFactory_CreatePalette(self: *const T, ppIPalette: ?*?*IWICPalette) callconv(.Inline) HRESULT { return @ptrCast(*const IWICImagingFactory.VTable, self.vtable).CreatePalette(@ptrCast(*const IWICImagingFactory, self), ppIPalette); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IWICImagingFactory_CreateFormatConverter(self: *const T, ppIFormatConverter: ?*?*IWICFormatConverter) callconv(.Inline) HRESULT { return @ptrCast(*const IWICImagingFactory.VTable, self.vtable).CreateFormatConverter(@ptrCast(*const IWICImagingFactory, self), ppIFormatConverter); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IWICImagingFactory_CreateBitmapScaler(self: *const T, ppIBitmapScaler: ?*?*IWICBitmapScaler) callconv(.Inline) HRESULT { return @ptrCast(*const IWICImagingFactory.VTable, self.vtable).CreateBitmapScaler(@ptrCast(*const IWICImagingFactory, self), ppIBitmapScaler); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IWICImagingFactory_CreateBitmapClipper(self: *const T, ppIBitmapClipper: ?*?*IWICBitmapClipper) callconv(.Inline) HRESULT { return @ptrCast(*const IWICImagingFactory.VTable, self.vtable).CreateBitmapClipper(@ptrCast(*const IWICImagingFactory, self), ppIBitmapClipper); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IWICImagingFactory_CreateBitmapFlipRotator(self: *const T, ppIBitmapFlipRotator: ?*?*IWICBitmapFlipRotator) callconv(.Inline) HRESULT { return @ptrCast(*const IWICImagingFactory.VTable, self.vtable).CreateBitmapFlipRotator(@ptrCast(*const IWICImagingFactory, self), ppIBitmapFlipRotator); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IWICImagingFactory_CreateStream(self: *const T, ppIWICStream: ?*?*IWICStream) callconv(.Inline) HRESULT { return @ptrCast(*const IWICImagingFactory.VTable, self.vtable).CreateStream(@ptrCast(*const IWICImagingFactory, self), ppIWICStream); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IWICImagingFactory_CreateColorContext(self: *const T, ppIWICColorContext: ?*?*IWICColorContext) callconv(.Inline) HRESULT { return @ptrCast(*const IWICImagingFactory.VTable, self.vtable).CreateColorContext(@ptrCast(*const IWICImagingFactory, self), ppIWICColorContext); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IWICImagingFactory_CreateColorTransformer(self: *const T, ppIWICColorTransform: ?*?*IWICColorTransform) callconv(.Inline) HRESULT { return @ptrCast(*const IWICImagingFactory.VTable, self.vtable).CreateColorTransformer(@ptrCast(*const IWICImagingFactory, self), ppIWICColorTransform); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IWICImagingFactory_CreateBitmap(self: *const T, uiWidth: u32, uiHeight: u32, pixelFormat: ?*Guid, option: WICBitmapCreateCacheOption, ppIBitmap: ?*?*IWICBitmap) callconv(.Inline) HRESULT { return @ptrCast(*const IWICImagingFactory.VTable, self.vtable).CreateBitmap(@ptrCast(*const IWICImagingFactory, self), uiWidth, uiHeight, pixelFormat, option, ppIBitmap); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IWICImagingFactory_CreateBitmapFromSource(self: *const T, pIBitmapSource: ?*IWICBitmapSource, option: WICBitmapCreateCacheOption, ppIBitmap: ?*?*IWICBitmap) callconv(.Inline) HRESULT { return @ptrCast(*const IWICImagingFactory.VTable, self.vtable).CreateBitmapFromSource(@ptrCast(*const IWICImagingFactory, self), pIBitmapSource, option, ppIBitmap); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IWICImagingFactory_CreateBitmapFromSourceRect(self: *const T, pIBitmapSource: ?*IWICBitmapSource, x: u32, y: u32, width: u32, height: u32, ppIBitmap: ?*?*IWICBitmap) callconv(.Inline) HRESULT { return @ptrCast(*const IWICImagingFactory.VTable, self.vtable).CreateBitmapFromSourceRect(@ptrCast(*const IWICImagingFactory, self), pIBitmapSource, x, y, width, height, ppIBitmap); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IWICImagingFactory_CreateBitmapFromMemory(self: *const T, uiWidth: u32, uiHeight: u32, pixelFormat: ?*Guid, cbStride: u32, cbBufferSize: u32, pbBuffer: [*:0]u8, ppIBitmap: ?*?*IWICBitmap) callconv(.Inline) HRESULT { return @ptrCast(*const IWICImagingFactory.VTable, self.vtable).CreateBitmapFromMemory(@ptrCast(*const IWICImagingFactory, self), uiWidth, uiHeight, pixelFormat, cbStride, cbBufferSize, pbBuffer, ppIBitmap); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IWICImagingFactory_CreateBitmapFromHBITMAP(self: *const T, hBitmap: ?HBITMAP, hPalette: ?HPALETTE, options: WICBitmapAlphaChannelOption, ppIBitmap: ?*?*IWICBitmap) callconv(.Inline) HRESULT { return @ptrCast(*const IWICImagingFactory.VTable, self.vtable).CreateBitmapFromHBITMAP(@ptrCast(*const IWICImagingFactory, self), hBitmap, hPalette, options, ppIBitmap); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IWICImagingFactory_CreateBitmapFromHICON(self: *const T, hIcon: ?HICON, ppIBitmap: ?*?*IWICBitmap) callconv(.Inline) HRESULT { return @ptrCast(*const IWICImagingFactory.VTable, self.vtable).CreateBitmapFromHICON(@ptrCast(*const IWICImagingFactory, self), hIcon, ppIBitmap); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IWICImagingFactory_CreateComponentEnumerator(self: *const T, componentTypes: u32, options: u32, ppIEnumUnknown: ?*?*IEnumUnknown) callconv(.Inline) HRESULT { return @ptrCast(*const IWICImagingFactory.VTable, self.vtable).CreateComponentEnumerator(@ptrCast(*const IWICImagingFactory, self), componentTypes, options, ppIEnumUnknown); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IWICImagingFactory_CreateFastMetadataEncoderFromDecoder(self: *const T, pIDecoder: ?*IWICBitmapDecoder, ppIFastEncoder: ?*?*IWICFastMetadataEncoder) callconv(.Inline) HRESULT { return @ptrCast(*const IWICImagingFactory.VTable, self.vtable).CreateFastMetadataEncoderFromDecoder(@ptrCast(*const IWICImagingFactory, self), pIDecoder, ppIFastEncoder); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IWICImagingFactory_CreateFastMetadataEncoderFromFrameDecode(self: *const T, pIFrameDecoder: ?*IWICBitmapFrameDecode, ppIFastEncoder: ?*?*IWICFastMetadataEncoder) callconv(.Inline) HRESULT { return @ptrCast(*const IWICImagingFactory.VTable, self.vtable).CreateFastMetadataEncoderFromFrameDecode(@ptrCast(*const IWICImagingFactory, self), pIFrameDecoder, ppIFastEncoder); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IWICImagingFactory_CreateQueryWriter(self: *const T, guidMetadataFormat: ?*const Guid, pguidVendor: ?*const Guid, ppIQueryWriter: ?*?*IWICMetadataQueryWriter) callconv(.Inline) HRESULT { return @ptrCast(*const IWICImagingFactory.VTable, self.vtable).CreateQueryWriter(@ptrCast(*const IWICImagingFactory, self), guidMetadataFormat, pguidVendor, ppIQueryWriter); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IWICImagingFactory_CreateQueryWriterFromReader(self: *const T, pIQueryReader: ?*IWICMetadataQueryReader, pguidVendor: ?*const Guid, ppIQueryWriter: ?*?*IWICMetadataQueryWriter) callconv(.Inline) HRESULT { return @ptrCast(*const IWICImagingFactory.VTable, self.vtable).CreateQueryWriterFromReader(@ptrCast(*const IWICImagingFactory, self), pIQueryReader, pguidVendor, ppIQueryWriter); } };} pub usingnamespace MethodMixin(@This()); }; pub const WICTiffCompressionOption = enum(i32) { iffCompressionDontCare = 0, iffCompressionNone = 1, iffCompressionCCITT3 = 2, iffCompressionCCITT4 = 3, iffCompressionLZW = 4, iffCompressionRLE = 5, iffCompressionZIP = 6, iffCompressionLZWHDifferencing = 7, IFFCOMPRESSIONOPTION_FORCE_DWORD = 2147483647, }; pub const WICTiffCompressionDontCare = WICTiffCompressionOption.iffCompressionDontCare; pub const WICTiffCompressionNone = WICTiffCompressionOption.iffCompressionNone; pub const WICTiffCompressionCCITT3 = WICTiffCompressionOption.iffCompressionCCITT3; pub const WICTiffCompressionCCITT4 = WICTiffCompressionOption.iffCompressionCCITT4; pub const WICTiffCompressionLZW = WICTiffCompressionOption.iffCompressionLZW; pub const WICTiffCompressionRLE = WICTiffCompressionOption.iffCompressionRLE; pub const WICTiffCompressionZIP = WICTiffCompressionOption.iffCompressionZIP; pub const WICTiffCompressionLZWHDifferencing = WICTiffCompressionOption.iffCompressionLZWHDifferencing; pub const WICTIFFCOMPRESSIONOPTION_FORCE_DWORD = WICTiffCompressionOption.IFFCOMPRESSIONOPTION_FORCE_DWORD; pub const WICJpegYCrCbSubsamplingOption = enum(i32) { pegYCrCbSubsamplingDefault = 0, pegYCrCbSubsampling420 = 1, pegYCrCbSubsampling422 = 2, pegYCrCbSubsampling444 = 3, pegYCrCbSubsampling440 = 4, PEGYCRCBSUBSAMPLING_FORCE_DWORD = 2147483647, }; pub const WICJpegYCrCbSubsamplingDefault = WICJpegYCrCbSubsamplingOption.pegYCrCbSubsamplingDefault; pub const WICJpegYCrCbSubsampling420 = WICJpegYCrCbSubsamplingOption.pegYCrCbSubsampling420; pub const WICJpegYCrCbSubsampling422 = WICJpegYCrCbSubsamplingOption.pegYCrCbSubsampling422; pub const WICJpegYCrCbSubsampling444 = WICJpegYCrCbSubsamplingOption.pegYCrCbSubsampling444; pub const WICJpegYCrCbSubsampling440 = WICJpegYCrCbSubsamplingOption.pegYCrCbSubsampling440; pub const WICJPEGYCRCBSUBSAMPLING_FORCE_DWORD = WICJpegYCrCbSubsamplingOption.PEGYCRCBSUBSAMPLING_FORCE_DWORD; pub const WICPngFilterOption = enum(i32) { ngFilterUnspecified = 0, ngFilterNone = 1, ngFilterSub = 2, ngFilterUp = 3, ngFilterAverage = 4, ngFilterPaeth = 5, ngFilterAdaptive = 6, NGFILTEROPTION_FORCE_DWORD = 2147483647, }; pub const WICPngFilterUnspecified = WICPngFilterOption.ngFilterUnspecified; pub const WICPngFilterNone = WICPngFilterOption.ngFilterNone; pub const WICPngFilterSub = WICPngFilterOption.ngFilterSub; pub const WICPngFilterUp = WICPngFilterOption.ngFilterUp; pub const WICPngFilterAverage = WICPngFilterOption.ngFilterAverage; pub const WICPngFilterPaeth = WICPngFilterOption.ngFilterPaeth; pub const WICPngFilterAdaptive = WICPngFilterOption.ngFilterAdaptive; pub const WICPNGFILTEROPTION_FORCE_DWORD = WICPngFilterOption.NGFILTEROPTION_FORCE_DWORD; pub const WICNamedWhitePoint = enum(i32) { WhitePointDefault = 1, WhitePointDaylight = 2, WhitePointCloudy = 4, WhitePointShade = 8, WhitePointTungsten = 16, WhitePointFluorescent = 32, WhitePointFlash = 64, WhitePointUnderwater = 128, WhitePointCustom = 256, WhitePointAutoWhiteBalance = 512, // WhitePointAsShot = 1, this enum value conflicts with WhitePointDefault NAMEDWHITEPOINT_FORCE_DWORD = 2147483647, }; pub const WICWhitePointDefault = WICNamedWhitePoint.WhitePointDefault; pub const WICWhitePointDaylight = WICNamedWhitePoint.WhitePointDaylight; pub const WICWhitePointCloudy = WICNamedWhitePoint.WhitePointCloudy; pub const WICWhitePointShade = WICNamedWhitePoint.WhitePointShade; pub const WICWhitePointTungsten = WICNamedWhitePoint.WhitePointTungsten; pub const WICWhitePointFluorescent = WICNamedWhitePoint.WhitePointFluorescent; pub const WICWhitePointFlash = WICNamedWhitePoint.WhitePointFlash; pub const WICWhitePointUnderwater = WICNamedWhitePoint.WhitePointUnderwater; pub const WICWhitePointCustom = WICNamedWhitePoint.WhitePointCustom; pub const WICWhitePointAutoWhiteBalance = WICNamedWhitePoint.WhitePointAutoWhiteBalance; pub const WICWhitePointAsShot = WICNamedWhitePoint.WhitePointDefault; pub const WICNAMEDWHITEPOINT_FORCE_DWORD = WICNamedWhitePoint.NAMEDWHITEPOINT_FORCE_DWORD; pub const WICRawCapabilities = enum(i32) { awCapabilityNotSupported = 0, awCapabilityGetSupported = 1, awCapabilityFullySupported = 2, AWCAPABILITIES_FORCE_DWORD = 2147483647, }; pub const WICRawCapabilityNotSupported = WICRawCapabilities.awCapabilityNotSupported; pub const WICRawCapabilityGetSupported = WICRawCapabilities.awCapabilityGetSupported; pub const WICRawCapabilityFullySupported = WICRawCapabilities.awCapabilityFullySupported; pub const WICRAWCAPABILITIES_FORCE_DWORD = WICRawCapabilities.AWCAPABILITIES_FORCE_DWORD; pub const WICRawRotationCapabilities = enum(i32) { awRotationCapabilityNotSupported = 0, awRotationCapabilityGetSupported = 1, awRotationCapabilityNinetyDegreesSupported = 2, awRotationCapabilityFullySupported = 3, AWROTATIONCAPABILITIES_FORCE_DWORD = 2147483647, }; pub const WICRawRotationCapabilityNotSupported = WICRawRotationCapabilities.awRotationCapabilityNotSupported; pub const WICRawRotationCapabilityGetSupported = WICRawRotationCapabilities.awRotationCapabilityGetSupported; pub const WICRawRotationCapabilityNinetyDegreesSupported = WICRawRotationCapabilities.awRotationCapabilityNinetyDegreesSupported; pub const WICRawRotationCapabilityFullySupported = WICRawRotationCapabilities.awRotationCapabilityFullySupported; pub const WICRAWROTATIONCAPABILITIES_FORCE_DWORD = WICRawRotationCapabilities.AWROTATIONCAPABILITIES_FORCE_DWORD; pub const WICRawCapabilitiesInfo = extern struct { cbSize: u32, CodecMajorVersion: u32, CodecMinorVersion: u32, ExposureCompensationSupport: WICRawCapabilities, ContrastSupport: WICRawCapabilities, RGBWhitePointSupport: WICRawCapabilities, NamedWhitePointSupport: WICRawCapabilities, NamedWhitePointSupportMask: u32, KelvinWhitePointSupport: WICRawCapabilities, GammaSupport: WICRawCapabilities, TintSupport: WICRawCapabilities, SaturationSupport: WICRawCapabilities, SharpnessSupport: WICRawCapabilities, NoiseReductionSupport: WICRawCapabilities, DestinationColorProfileSupport: WICRawCapabilities, ToneCurveSupport: WICRawCapabilities, RotationSupport: WICRawRotationCapabilities, RenderModeSupport: WICRawCapabilities, }; pub const WICRawParameterSet = enum(i32) { AsShotParameterSet = 1, UserAdjustedParameterSet = 2, AutoAdjustedParameterSet = 3, RAWPARAMETERSET_FORCE_DWORD = 2147483647, }; pub const WICAsShotParameterSet = WICRawParameterSet.AsShotParameterSet; pub const WICUserAdjustedParameterSet = WICRawParameterSet.UserAdjustedParameterSet; pub const WICAutoAdjustedParameterSet = WICRawParameterSet.AutoAdjustedParameterSet; pub const WICRAWPARAMETERSET_FORCE_DWORD = WICRawParameterSet.RAWPARAMETERSET_FORCE_DWORD; pub const WICRawRenderMode = enum(i32) { awRenderModeDraft = 1, awRenderModeNormal = 2, awRenderModeBestQuality = 3, AWRENDERMODE_FORCE_DWORD = 2147483647, }; pub const WICRawRenderModeDraft = WICRawRenderMode.awRenderModeDraft; pub const WICRawRenderModeNormal = WICRawRenderMode.awRenderModeNormal; pub const WICRawRenderModeBestQuality = WICRawRenderMode.awRenderModeBestQuality; pub const WICRAWRENDERMODE_FORCE_DWORD = WICRawRenderMode.AWRENDERMODE_FORCE_DWORD; pub const WICRawToneCurvePoint = extern struct { Input: f64, Output: f64, }; pub const WICRawToneCurve = extern struct { cPoints: u32, aPoints: [1]WICRawToneCurvePoint, }; // TODO: this type is limited to platform 'windows5.1.2600' const IID_IWICDevelopRawNotificationCallback_Value = Guid.initString("95c75a6e-3e8c-4ec2-85a8-aebcc551e59b"); pub const IID_IWICDevelopRawNotificationCallback = &IID_IWICDevelopRawNotificationCallback_Value; pub const IWICDevelopRawNotificationCallback = extern struct { pub const VTable = extern struct { base: IUnknown.VTable, Notify: fn( self: *const IWICDevelopRawNotificationCallback, NotificationMask: 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 IWICDevelopRawNotificationCallback_Notify(self: *const T, NotificationMask: u32) callconv(.Inline) HRESULT { return @ptrCast(*const IWICDevelopRawNotificationCallback.VTable, self.vtable).Notify(@ptrCast(*const IWICDevelopRawNotificationCallback, self), NotificationMask); } };} pub usingnamespace MethodMixin(@This()); }; // TODO: this type is limited to platform 'windows5.1.2600' const IID_IWICDevelopRaw_Value = Guid.initString("fbec5e44-f7be-4b65-b7f8-c0c81fef026d"); pub const IID_IWICDevelopRaw = &IID_IWICDevelopRaw_Value; pub const IWICDevelopRaw = extern struct { pub const VTable = extern struct { base: IWICBitmapFrameDecode.VTable, QueryRawCapabilitiesInfo: fn( self: *const IWICDevelopRaw, pInfo: ?*WICRawCapabilitiesInfo, ) callconv(@import("std").os.windows.WINAPI) HRESULT, LoadParameterSet: fn( self: *const IWICDevelopRaw, ParameterSet: WICRawParameterSet, ) callconv(@import("std").os.windows.WINAPI) HRESULT, GetCurrentParameterSet: fn( self: *const IWICDevelopRaw, ppCurrentParameterSet: ?*?*IPropertyBag2, ) callconv(@import("std").os.windows.WINAPI) HRESULT, SetExposureCompensation: fn( self: *const IWICDevelopRaw, ev: f64, ) callconv(@import("std").os.windows.WINAPI) HRESULT, GetExposureCompensation: fn( self: *const IWICDevelopRaw, pEV: ?*f64, ) callconv(@import("std").os.windows.WINAPI) HRESULT, SetWhitePointRGB: fn( self: *const IWICDevelopRaw, Red: u32, Green: u32, Blue: u32, ) callconv(@import("std").os.windows.WINAPI) HRESULT, GetWhitePointRGB: fn( self: *const IWICDevelopRaw, pRed: ?*u32, pGreen: ?*u32, pBlue: ?*u32, ) callconv(@import("std").os.windows.WINAPI) HRESULT, SetNamedWhitePoint: fn( self: *const IWICDevelopRaw, WhitePoint: WICNamedWhitePoint, ) callconv(@import("std").os.windows.WINAPI) HRESULT, GetNamedWhitePoint: fn( self: *const IWICDevelopRaw, pWhitePoint: ?*WICNamedWhitePoint, ) callconv(@import("std").os.windows.WINAPI) HRESULT, SetWhitePointKelvin: fn( self: *const IWICDevelopRaw, WhitePointKelvin: u32, ) callconv(@import("std").os.windows.WINAPI) HRESULT, GetWhitePointKelvin: fn( self: *const IWICDevelopRaw, pWhitePointKelvin: ?*u32, ) callconv(@import("std").os.windows.WINAPI) HRESULT, GetKelvinRangeInfo: fn( self: *const IWICDevelopRaw, pMinKelvinTemp: ?*u32, pMaxKelvinTemp: ?*u32, pKelvinTempStepValue: ?*u32, ) callconv(@import("std").os.windows.WINAPI) HRESULT, SetContrast: fn( self: *const IWICDevelopRaw, Contrast: f64, ) callconv(@import("std").os.windows.WINAPI) HRESULT, GetContrast: fn( self: *const IWICDevelopRaw, pContrast: ?*f64, ) callconv(@import("std").os.windows.WINAPI) HRESULT, SetGamma: fn( self: *const IWICDevelopRaw, Gamma: f64, ) callconv(@import("std").os.windows.WINAPI) HRESULT, GetGamma: fn( self: *const IWICDevelopRaw, pGamma: ?*f64, ) callconv(@import("std").os.windows.WINAPI) HRESULT, SetSharpness: fn( self: *const IWICDevelopRaw, Sharpness: f64, ) callconv(@import("std").os.windows.WINAPI) HRESULT, GetSharpness: fn( self: *const IWICDevelopRaw, pSharpness: ?*f64, ) callconv(@import("std").os.windows.WINAPI) HRESULT, SetSaturation: fn( self: *const IWICDevelopRaw, Saturation: f64, ) callconv(@import("std").os.windows.WINAPI) HRESULT, GetSaturation: fn( self: *const IWICDevelopRaw, pSaturation: ?*f64, ) callconv(@import("std").os.windows.WINAPI) HRESULT, SetTint: fn( self: *const IWICDevelopRaw, Tint: f64, ) callconv(@import("std").os.windows.WINAPI) HRESULT, GetTint: fn( self: *const IWICDevelopRaw, pTint: ?*f64, ) callconv(@import("std").os.windows.WINAPI) HRESULT, SetNoiseReduction: fn( self: *const IWICDevelopRaw, NoiseReduction: f64, ) callconv(@import("std").os.windows.WINAPI) HRESULT, GetNoiseReduction: fn( self: *const IWICDevelopRaw, pNoiseReduction: ?*f64, ) callconv(@import("std").os.windows.WINAPI) HRESULT, SetDestinationColorContext: fn( self: *const IWICDevelopRaw, pColorContext: ?*IWICColorContext, ) callconv(@import("std").os.windows.WINAPI) HRESULT, SetToneCurve: fn( self: *const IWICDevelopRaw, cbToneCurveSize: u32, // TODO: what to do with BytesParamIndex 0? pToneCurve: ?*const WICRawToneCurve, ) callconv(@import("std").os.windows.WINAPI) HRESULT, GetToneCurve: fn( self: *const IWICDevelopRaw, cbToneCurveBufferSize: u32, // TODO: what to do with BytesParamIndex 0? pToneCurve: ?*WICRawToneCurve, pcbActualToneCurveBufferSize: ?*u32, ) callconv(@import("std").os.windows.WINAPI) HRESULT, SetRotation: fn( self: *const IWICDevelopRaw, Rotation: f64, ) callconv(@import("std").os.windows.WINAPI) HRESULT, GetRotation: fn( self: *const IWICDevelopRaw, pRotation: ?*f64, ) callconv(@import("std").os.windows.WINAPI) HRESULT, SetRenderMode: fn( self: *const IWICDevelopRaw, RenderMode: WICRawRenderMode, ) callconv(@import("std").os.windows.WINAPI) HRESULT, GetRenderMode: fn( self: *const IWICDevelopRaw, pRenderMode: ?*WICRawRenderMode, ) callconv(@import("std").os.windows.WINAPI) HRESULT, SetNotificationCallback: fn( self: *const IWICDevelopRaw, pCallback: ?*IWICDevelopRawNotificationCallback, ) callconv(@import("std").os.windows.WINAPI) HRESULT, }; vtable: *const VTable, pub fn MethodMixin(comptime T: type) type { return struct { pub usingnamespace IWICBitmapFrameDecode.MethodMixin(T); // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IWICDevelopRaw_QueryRawCapabilitiesInfo(self: *const T, pInfo: ?*WICRawCapabilitiesInfo) callconv(.Inline) HRESULT { return @ptrCast(*const IWICDevelopRaw.VTable, self.vtable).QueryRawCapabilitiesInfo(@ptrCast(*const IWICDevelopRaw, self), pInfo); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IWICDevelopRaw_LoadParameterSet(self: *const T, ParameterSet: WICRawParameterSet) callconv(.Inline) HRESULT { return @ptrCast(*const IWICDevelopRaw.VTable, self.vtable).LoadParameterSet(@ptrCast(*const IWICDevelopRaw, self), ParameterSet); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IWICDevelopRaw_GetCurrentParameterSet(self: *const T, ppCurrentParameterSet: ?*?*IPropertyBag2) callconv(.Inline) HRESULT { return @ptrCast(*const IWICDevelopRaw.VTable, self.vtable).GetCurrentParameterSet(@ptrCast(*const IWICDevelopRaw, self), ppCurrentParameterSet); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IWICDevelopRaw_SetExposureCompensation(self: *const T, ev: f64) callconv(.Inline) HRESULT { return @ptrCast(*const IWICDevelopRaw.VTable, self.vtable).SetExposureCompensation(@ptrCast(*const IWICDevelopRaw, self), ev); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IWICDevelopRaw_GetExposureCompensation(self: *const T, pEV: ?*f64) callconv(.Inline) HRESULT { return @ptrCast(*const IWICDevelopRaw.VTable, self.vtable).GetExposureCompensation(@ptrCast(*const IWICDevelopRaw, self), pEV); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IWICDevelopRaw_SetWhitePointRGB(self: *const T, Red: u32, Green: u32, Blue: u32) callconv(.Inline) HRESULT { return @ptrCast(*const IWICDevelopRaw.VTable, self.vtable).SetWhitePointRGB(@ptrCast(*const IWICDevelopRaw, self), Red, Green, Blue); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IWICDevelopRaw_GetWhitePointRGB(self: *const T, pRed: ?*u32, pGreen: ?*u32, pBlue: ?*u32) callconv(.Inline) HRESULT { return @ptrCast(*const IWICDevelopRaw.VTable, self.vtable).GetWhitePointRGB(@ptrCast(*const IWICDevelopRaw, self), pRed, pGreen, pBlue); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IWICDevelopRaw_SetNamedWhitePoint(self: *const T, WhitePoint: WICNamedWhitePoint) callconv(.Inline) HRESULT { return @ptrCast(*const IWICDevelopRaw.VTable, self.vtable).SetNamedWhitePoint(@ptrCast(*const IWICDevelopRaw, self), WhitePoint); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IWICDevelopRaw_GetNamedWhitePoint(self: *const T, pWhitePoint: ?*WICNamedWhitePoint) callconv(.Inline) HRESULT { return @ptrCast(*const IWICDevelopRaw.VTable, self.vtable).GetNamedWhitePoint(@ptrCast(*const IWICDevelopRaw, self), pWhitePoint); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IWICDevelopRaw_SetWhitePointKelvin(self: *const T, WhitePointKelvin: u32) callconv(.Inline) HRESULT { return @ptrCast(*const IWICDevelopRaw.VTable, self.vtable).SetWhitePointKelvin(@ptrCast(*const IWICDevelopRaw, self), WhitePointKelvin); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IWICDevelopRaw_GetWhitePointKelvin(self: *const T, pWhitePointKelvin: ?*u32) callconv(.Inline) HRESULT { return @ptrCast(*const IWICDevelopRaw.VTable, self.vtable).GetWhitePointKelvin(@ptrCast(*const IWICDevelopRaw, self), pWhitePointKelvin); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IWICDevelopRaw_GetKelvinRangeInfo(self: *const T, pMinKelvinTemp: ?*u32, pMaxKelvinTemp: ?*u32, pKelvinTempStepValue: ?*u32) callconv(.Inline) HRESULT { return @ptrCast(*const IWICDevelopRaw.VTable, self.vtable).GetKelvinRangeInfo(@ptrCast(*const IWICDevelopRaw, self), pMinKelvinTemp, pMaxKelvinTemp, pKelvinTempStepValue); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IWICDevelopRaw_SetContrast(self: *const T, Contrast: f64) callconv(.Inline) HRESULT { return @ptrCast(*const IWICDevelopRaw.VTable, self.vtable).SetContrast(@ptrCast(*const IWICDevelopRaw, self), Contrast); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IWICDevelopRaw_GetContrast(self: *const T, pContrast: ?*f64) callconv(.Inline) HRESULT { return @ptrCast(*const IWICDevelopRaw.VTable, self.vtable).GetContrast(@ptrCast(*const IWICDevelopRaw, self), pContrast); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IWICDevelopRaw_SetGamma(self: *const T, Gamma: f64) callconv(.Inline) HRESULT { return @ptrCast(*const IWICDevelopRaw.VTable, self.vtable).SetGamma(@ptrCast(*const IWICDevelopRaw, self), Gamma); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IWICDevelopRaw_GetGamma(self: *const T, pGamma: ?*f64) callconv(.Inline) HRESULT { return @ptrCast(*const IWICDevelopRaw.VTable, self.vtable).GetGamma(@ptrCast(*const IWICDevelopRaw, self), pGamma); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IWICDevelopRaw_SetSharpness(self: *const T, Sharpness: f64) callconv(.Inline) HRESULT { return @ptrCast(*const IWICDevelopRaw.VTable, self.vtable).SetSharpness(@ptrCast(*const IWICDevelopRaw, self), Sharpness); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IWICDevelopRaw_GetSharpness(self: *const T, pSharpness: ?*f64) callconv(.Inline) HRESULT { return @ptrCast(*const IWICDevelopRaw.VTable, self.vtable).GetSharpness(@ptrCast(*const IWICDevelopRaw, self), pSharpness); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IWICDevelopRaw_SetSaturation(self: *const T, Saturation: f64) callconv(.Inline) HRESULT { return @ptrCast(*const IWICDevelopRaw.VTable, self.vtable).SetSaturation(@ptrCast(*const IWICDevelopRaw, self), Saturation); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IWICDevelopRaw_GetSaturation(self: *const T, pSaturation: ?*f64) callconv(.Inline) HRESULT { return @ptrCast(*const IWICDevelopRaw.VTable, self.vtable).GetSaturation(@ptrCast(*const IWICDevelopRaw, self), pSaturation); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IWICDevelopRaw_SetTint(self: *const T, Tint: f64) callconv(.Inline) HRESULT { return @ptrCast(*const IWICDevelopRaw.VTable, self.vtable).SetTint(@ptrCast(*const IWICDevelopRaw, self), Tint); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IWICDevelopRaw_GetTint(self: *const T, pTint: ?*f64) callconv(.Inline) HRESULT { return @ptrCast(*const IWICDevelopRaw.VTable, self.vtable).GetTint(@ptrCast(*const IWICDevelopRaw, self), pTint); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IWICDevelopRaw_SetNoiseReduction(self: *const T, NoiseReduction: f64) callconv(.Inline) HRESULT { return @ptrCast(*const IWICDevelopRaw.VTable, self.vtable).SetNoiseReduction(@ptrCast(*const IWICDevelopRaw, self), NoiseReduction); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IWICDevelopRaw_GetNoiseReduction(self: *const T, pNoiseReduction: ?*f64) callconv(.Inline) HRESULT { return @ptrCast(*const IWICDevelopRaw.VTable, self.vtable).GetNoiseReduction(@ptrCast(*const IWICDevelopRaw, self), pNoiseReduction); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IWICDevelopRaw_SetDestinationColorContext(self: *const T, pColorContext: ?*IWICColorContext) callconv(.Inline) HRESULT { return @ptrCast(*const IWICDevelopRaw.VTable, self.vtable).SetDestinationColorContext(@ptrCast(*const IWICDevelopRaw, self), pColorContext); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IWICDevelopRaw_SetToneCurve(self: *const T, cbToneCurveSize: u32, pToneCurve: ?*const WICRawToneCurve) callconv(.Inline) HRESULT { return @ptrCast(*const IWICDevelopRaw.VTable, self.vtable).SetToneCurve(@ptrCast(*const IWICDevelopRaw, self), cbToneCurveSize, pToneCurve); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IWICDevelopRaw_GetToneCurve(self: *const T, cbToneCurveBufferSize: u32, pToneCurve: ?*WICRawToneCurve, pcbActualToneCurveBufferSize: ?*u32) callconv(.Inline) HRESULT { return @ptrCast(*const IWICDevelopRaw.VTable, self.vtable).GetToneCurve(@ptrCast(*const IWICDevelopRaw, self), cbToneCurveBufferSize, pToneCurve, pcbActualToneCurveBufferSize); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IWICDevelopRaw_SetRotation(self: *const T, Rotation: f64) callconv(.Inline) HRESULT { return @ptrCast(*const IWICDevelopRaw.VTable, self.vtable).SetRotation(@ptrCast(*const IWICDevelopRaw, self), Rotation); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IWICDevelopRaw_GetRotation(self: *const T, pRotation: ?*f64) callconv(.Inline) HRESULT { return @ptrCast(*const IWICDevelopRaw.VTable, self.vtable).GetRotation(@ptrCast(*const IWICDevelopRaw, self), pRotation); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IWICDevelopRaw_SetRenderMode(self: *const T, RenderMode: WICRawRenderMode) callconv(.Inline) HRESULT { return @ptrCast(*const IWICDevelopRaw.VTable, self.vtable).SetRenderMode(@ptrCast(*const IWICDevelopRaw, self), RenderMode); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IWICDevelopRaw_GetRenderMode(self: *const T, pRenderMode: ?*WICRawRenderMode) callconv(.Inline) HRESULT { return @ptrCast(*const IWICDevelopRaw.VTable, self.vtable).GetRenderMode(@ptrCast(*const IWICDevelopRaw, self), pRenderMode); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IWICDevelopRaw_SetNotificationCallback(self: *const T, pCallback: ?*IWICDevelopRawNotificationCallback) callconv(.Inline) HRESULT { return @ptrCast(*const IWICDevelopRaw.VTable, self.vtable).SetNotificationCallback(@ptrCast(*const IWICDevelopRaw, self), pCallback); } };} pub usingnamespace MethodMixin(@This()); }; pub const WICDdsDimension = enum(i32) { dsTexture1D = 0, dsTexture2D = 1, dsTexture3D = 2, dsTextureCube = 3, DSTEXTURE_FORCE_DWORD = 2147483647, }; pub const WICDdsTexture1D = WICDdsDimension.dsTexture1D; pub const WICDdsTexture2D = WICDdsDimension.dsTexture2D; pub const WICDdsTexture3D = WICDdsDimension.dsTexture3D; pub const WICDdsTextureCube = WICDdsDimension.dsTextureCube; pub const WICDDSTEXTURE_FORCE_DWORD = WICDdsDimension.DSTEXTURE_FORCE_DWORD; pub const WICDdsAlphaMode = enum(i32) { dsAlphaModeUnknown = 0, dsAlphaModeStraight = 1, dsAlphaModePremultiplied = 2, dsAlphaModeOpaque = 3, dsAlphaModeCustom = 4, DSALPHAMODE_FORCE_DWORD = 2147483647, }; pub const WICDdsAlphaModeUnknown = WICDdsAlphaMode.dsAlphaModeUnknown; pub const WICDdsAlphaModeStraight = WICDdsAlphaMode.dsAlphaModeStraight; pub const WICDdsAlphaModePremultiplied = WICDdsAlphaMode.dsAlphaModePremultiplied; pub const WICDdsAlphaModeOpaque = WICDdsAlphaMode.dsAlphaModeOpaque; pub const WICDdsAlphaModeCustom = WICDdsAlphaMode.dsAlphaModeCustom; pub const WICDDSALPHAMODE_FORCE_DWORD = WICDdsAlphaMode.DSALPHAMODE_FORCE_DWORD; pub const WICDdsParameters = extern struct { Width: u32, Height: u32, Depth: u32, MipLevels: u32, ArraySize: u32, DxgiFormat: DXGI_FORMAT, Dimension: WICDdsDimension, AlphaMode: WICDdsAlphaMode, }; // TODO: this type is limited to platform 'windows8.1' const IID_IWICDdsDecoder_Value = Guid.initString("409cd537-8532-40cb-9774-e2feb2df4e9c"); pub const IID_IWICDdsDecoder = &IID_IWICDdsDecoder_Value; pub const IWICDdsDecoder = extern struct { pub const VTable = extern struct { base: IUnknown.VTable, GetParameters: fn( self: *const IWICDdsDecoder, pParameters: ?*WICDdsParameters, ) callconv(@import("std").os.windows.WINAPI) HRESULT, GetFrame: fn( self: *const IWICDdsDecoder, arrayIndex: u32, mipLevel: u32, sliceIndex: u32, ppIBitmapFrame: ?*?*IWICBitmapFrameDecode, ) 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 IWICDdsDecoder_GetParameters(self: *const T, pParameters: ?*WICDdsParameters) callconv(.Inline) HRESULT { return @ptrCast(*const IWICDdsDecoder.VTable, self.vtable).GetParameters(@ptrCast(*const IWICDdsDecoder, self), pParameters); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IWICDdsDecoder_GetFrame(self: *const T, arrayIndex: u32, mipLevel: u32, sliceIndex: u32, ppIBitmapFrame: ?*?*IWICBitmapFrameDecode) callconv(.Inline) HRESULT { return @ptrCast(*const IWICDdsDecoder.VTable, self.vtable).GetFrame(@ptrCast(*const IWICDdsDecoder, self), arrayIndex, mipLevel, sliceIndex, ppIBitmapFrame); } };} pub usingnamespace MethodMixin(@This()); }; // TODO: this type is limited to platform 'windows8.1' const IID_IWICDdsEncoder_Value = Guid.initString("5cacdb4c-407e-41b3-b936-d0f010cd6732"); pub const IID_IWICDdsEncoder = &IID_IWICDdsEncoder_Value; pub const IWICDdsEncoder = extern struct { pub const VTable = extern struct { base: IUnknown.VTable, SetParameters: fn( self: *const IWICDdsEncoder, pParameters: ?*WICDdsParameters, ) callconv(@import("std").os.windows.WINAPI) HRESULT, GetParameters: fn( self: *const IWICDdsEncoder, pParameters: ?*WICDdsParameters, ) callconv(@import("std").os.windows.WINAPI) HRESULT, CreateNewFrame: fn( self: *const IWICDdsEncoder, ppIFrameEncode: ?*?*IWICBitmapFrameEncode, pArrayIndex: ?*u32, pMipLevel: ?*u32, pSliceIndex: ?*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 IWICDdsEncoder_SetParameters(self: *const T, pParameters: ?*WICDdsParameters) callconv(.Inline) HRESULT { return @ptrCast(*const IWICDdsEncoder.VTable, self.vtable).SetParameters(@ptrCast(*const IWICDdsEncoder, self), pParameters); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IWICDdsEncoder_GetParameters(self: *const T, pParameters: ?*WICDdsParameters) callconv(.Inline) HRESULT { return @ptrCast(*const IWICDdsEncoder.VTable, self.vtable).GetParameters(@ptrCast(*const IWICDdsEncoder, self), pParameters); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IWICDdsEncoder_CreateNewFrame(self: *const T, ppIFrameEncode: ?*?*IWICBitmapFrameEncode, pArrayIndex: ?*u32, pMipLevel: ?*u32, pSliceIndex: ?*u32) callconv(.Inline) HRESULT { return @ptrCast(*const IWICDdsEncoder.VTable, self.vtable).CreateNewFrame(@ptrCast(*const IWICDdsEncoder, self), ppIFrameEncode, pArrayIndex, pMipLevel, pSliceIndex); } };} pub usingnamespace MethodMixin(@This()); }; pub const WICDdsFormatInfo = extern struct { DxgiFormat: DXGI_FORMAT, BytesPerBlock: u32, BlockWidth: u32, BlockHeight: u32, }; // TODO: this type is limited to platform 'windows8.1' const IID_IWICDdsFrameDecode_Value = Guid.initString("3d4c0c61-18a4-41e4-bd80-481a4fc9f464"); pub const IID_IWICDdsFrameDecode = &IID_IWICDdsFrameDecode_Value; pub const IWICDdsFrameDecode = extern struct { pub const VTable = extern struct { base: IUnknown.VTable, GetSizeInBlocks: fn( self: *const IWICDdsFrameDecode, pWidthInBlocks: ?*u32, pHeightInBlocks: ?*u32, ) callconv(@import("std").os.windows.WINAPI) HRESULT, GetFormatInfo: fn( self: *const IWICDdsFrameDecode, pFormatInfo: ?*WICDdsFormatInfo, ) callconv(@import("std").os.windows.WINAPI) HRESULT, CopyBlocks: fn( self: *const IWICDdsFrameDecode, prcBoundsInBlocks: ?*const WICRect, cbStride: u32, cbBufferSize: u32, pbBuffer: [*:0]u8, ) 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 IWICDdsFrameDecode_GetSizeInBlocks(self: *const T, pWidthInBlocks: ?*u32, pHeightInBlocks: ?*u32) callconv(.Inline) HRESULT { return @ptrCast(*const IWICDdsFrameDecode.VTable, self.vtable).GetSizeInBlocks(@ptrCast(*const IWICDdsFrameDecode, self), pWidthInBlocks, pHeightInBlocks); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IWICDdsFrameDecode_GetFormatInfo(self: *const T, pFormatInfo: ?*WICDdsFormatInfo) callconv(.Inline) HRESULT { return @ptrCast(*const IWICDdsFrameDecode.VTable, self.vtable).GetFormatInfo(@ptrCast(*const IWICDdsFrameDecode, self), pFormatInfo); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IWICDdsFrameDecode_CopyBlocks(self: *const T, prcBoundsInBlocks: ?*const WICRect, cbStride: u32, cbBufferSize: u32, pbBuffer: [*:0]u8) callconv(.Inline) HRESULT { return @ptrCast(*const IWICDdsFrameDecode.VTable, self.vtable).CopyBlocks(@ptrCast(*const IWICDdsFrameDecode, self), prcBoundsInBlocks, cbStride, cbBufferSize, pbBuffer); } };} pub usingnamespace MethodMixin(@This()); }; // TODO: this type is limited to platform 'windows10.0.10240' const IID_IWICJpegFrameDecode_Value = Guid.initString("8939f66e-c46a-4c21-a9d1-98b327ce1679"); pub const IID_IWICJpegFrameDecode = &IID_IWICJpegFrameDecode_Value; pub const IWICJpegFrameDecode = extern struct { pub const VTable = extern struct { base: IUnknown.VTable, DoesSupportIndexing: fn( self: *const IWICJpegFrameDecode, pfIndexingSupported: ?*BOOL, ) callconv(@import("std").os.windows.WINAPI) HRESULT, SetIndexing: fn( self: *const IWICJpegFrameDecode, options: WICJpegIndexingOptions, horizontalIntervalSize: u32, ) callconv(@import("std").os.windows.WINAPI) HRESULT, ClearIndexing: fn( self: *const IWICJpegFrameDecode, ) callconv(@import("std").os.windows.WINAPI) HRESULT, GetAcHuffmanTable: fn( self: *const IWICJpegFrameDecode, scanIndex: u32, tableIndex: u32, pAcHuffmanTable: ?*DXGI_JPEG_AC_HUFFMAN_TABLE, ) callconv(@import("std").os.windows.WINAPI) HRESULT, GetDcHuffmanTable: fn( self: *const IWICJpegFrameDecode, scanIndex: u32, tableIndex: u32, pDcHuffmanTable: ?*DXGI_JPEG_DC_HUFFMAN_TABLE, ) callconv(@import("std").os.windows.WINAPI) HRESULT, GetQuantizationTable: fn( self: *const IWICJpegFrameDecode, scanIndex: u32, tableIndex: u32, pQuantizationTable: ?*DXGI_JPEG_QUANTIZATION_TABLE, ) callconv(@import("std").os.windows.WINAPI) HRESULT, GetFrameHeader: fn( self: *const IWICJpegFrameDecode, pFrameHeader: ?*WICJpegFrameHeader, ) callconv(@import("std").os.windows.WINAPI) HRESULT, GetScanHeader: fn( self: *const IWICJpegFrameDecode, scanIndex: u32, pScanHeader: ?*WICJpegScanHeader, ) callconv(@import("std").os.windows.WINAPI) HRESULT, CopyScan: fn( self: *const IWICJpegFrameDecode, scanIndex: u32, scanOffset: u32, cbScanData: u32, pbScanData: [*:0]u8, pcbScanDataActual: ?*u32, ) callconv(@import("std").os.windows.WINAPI) HRESULT, CopyMinimalStream: fn( self: *const IWICJpegFrameDecode, streamOffset: u32, cbStreamData: u32, pbStreamData: [*:0]u8, pcbStreamDataActual: ?*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 IWICJpegFrameDecode_DoesSupportIndexing(self: *const T, pfIndexingSupported: ?*BOOL) callconv(.Inline) HRESULT { return @ptrCast(*const IWICJpegFrameDecode.VTable, self.vtable).DoesSupportIndexing(@ptrCast(*const IWICJpegFrameDecode, self), pfIndexingSupported); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IWICJpegFrameDecode_SetIndexing(self: *const T, options: WICJpegIndexingOptions, horizontalIntervalSize: u32) callconv(.Inline) HRESULT { return @ptrCast(*const IWICJpegFrameDecode.VTable, self.vtable).SetIndexing(@ptrCast(*const IWICJpegFrameDecode, self), options, horizontalIntervalSize); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IWICJpegFrameDecode_ClearIndexing(self: *const T) callconv(.Inline) HRESULT { return @ptrCast(*const IWICJpegFrameDecode.VTable, self.vtable).ClearIndexing(@ptrCast(*const IWICJpegFrameDecode, self)); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IWICJpegFrameDecode_GetAcHuffmanTable(self: *const T, scanIndex: u32, tableIndex: u32, pAcHuffmanTable: ?*DXGI_JPEG_AC_HUFFMAN_TABLE) callconv(.Inline) HRESULT { return @ptrCast(*const IWICJpegFrameDecode.VTable, self.vtable).GetAcHuffmanTable(@ptrCast(*const IWICJpegFrameDecode, self), scanIndex, tableIndex, pAcHuffmanTable); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IWICJpegFrameDecode_GetDcHuffmanTable(self: *const T, scanIndex: u32, tableIndex: u32, pDcHuffmanTable: ?*DXGI_JPEG_DC_HUFFMAN_TABLE) callconv(.Inline) HRESULT { return @ptrCast(*const IWICJpegFrameDecode.VTable, self.vtable).GetDcHuffmanTable(@ptrCast(*const IWICJpegFrameDecode, self), scanIndex, tableIndex, pDcHuffmanTable); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IWICJpegFrameDecode_GetQuantizationTable(self: *const T, scanIndex: u32, tableIndex: u32, pQuantizationTable: ?*DXGI_JPEG_QUANTIZATION_TABLE) callconv(.Inline) HRESULT { return @ptrCast(*const IWICJpegFrameDecode.VTable, self.vtable).GetQuantizationTable(@ptrCast(*const IWICJpegFrameDecode, self), scanIndex, tableIndex, pQuantizationTable); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IWICJpegFrameDecode_GetFrameHeader(self: *const T, pFrameHeader: ?*WICJpegFrameHeader) callconv(.Inline) HRESULT { return @ptrCast(*const IWICJpegFrameDecode.VTable, self.vtable).GetFrameHeader(@ptrCast(*const IWICJpegFrameDecode, self), pFrameHeader); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IWICJpegFrameDecode_GetScanHeader(self: *const T, scanIndex: u32, pScanHeader: ?*WICJpegScanHeader) callconv(.Inline) HRESULT { return @ptrCast(*const IWICJpegFrameDecode.VTable, self.vtable).GetScanHeader(@ptrCast(*const IWICJpegFrameDecode, self), scanIndex, pScanHeader); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IWICJpegFrameDecode_CopyScan(self: *const T, scanIndex: u32, scanOffset: u32, cbScanData: u32, pbScanData: [*:0]u8, pcbScanDataActual: ?*u32) callconv(.Inline) HRESULT { return @ptrCast(*const IWICJpegFrameDecode.VTable, self.vtable).CopyScan(@ptrCast(*const IWICJpegFrameDecode, self), scanIndex, scanOffset, cbScanData, pbScanData, pcbScanDataActual); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IWICJpegFrameDecode_CopyMinimalStream(self: *const T, streamOffset: u32, cbStreamData: u32, pbStreamData: [*:0]u8, pcbStreamDataActual: ?*u32) callconv(.Inline) HRESULT { return @ptrCast(*const IWICJpegFrameDecode.VTable, self.vtable).CopyMinimalStream(@ptrCast(*const IWICJpegFrameDecode, self), streamOffset, cbStreamData, pbStreamData, pcbStreamDataActual); } };} pub usingnamespace MethodMixin(@This()); }; // TODO: this type is limited to platform 'windows10.0.10240' const IID_IWICJpegFrameEncode_Value = Guid.initString("2f0c601f-d2c6-468c-abfa-49495d983ed1"); pub const IID_IWICJpegFrameEncode = &IID_IWICJpegFrameEncode_Value; pub const IWICJpegFrameEncode = extern struct { pub const VTable = extern struct { base: IUnknown.VTable, GetAcHuffmanTable: fn( self: *const IWICJpegFrameEncode, scanIndex: u32, tableIndex: u32, pAcHuffmanTable: ?*DXGI_JPEG_AC_HUFFMAN_TABLE, ) callconv(@import("std").os.windows.WINAPI) HRESULT, GetDcHuffmanTable: fn( self: *const IWICJpegFrameEncode, scanIndex: u32, tableIndex: u32, pDcHuffmanTable: ?*DXGI_JPEG_DC_HUFFMAN_TABLE, ) callconv(@import("std").os.windows.WINAPI) HRESULT, GetQuantizationTable: fn( self: *const IWICJpegFrameEncode, scanIndex: u32, tableIndex: u32, pQuantizationTable: ?*DXGI_JPEG_QUANTIZATION_TABLE, ) callconv(@import("std").os.windows.WINAPI) HRESULT, WriteScan: fn( self: *const IWICJpegFrameEncode, cbScanData: u32, pbScanData: [*:0]const u8, ) 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 IWICJpegFrameEncode_GetAcHuffmanTable(self: *const T, scanIndex: u32, tableIndex: u32, pAcHuffmanTable: ?*DXGI_JPEG_AC_HUFFMAN_TABLE) callconv(.Inline) HRESULT { return @ptrCast(*const IWICJpegFrameEncode.VTable, self.vtable).GetAcHuffmanTable(@ptrCast(*const IWICJpegFrameEncode, self), scanIndex, tableIndex, pAcHuffmanTable); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IWICJpegFrameEncode_GetDcHuffmanTable(self: *const T, scanIndex: u32, tableIndex: u32, pDcHuffmanTable: ?*DXGI_JPEG_DC_HUFFMAN_TABLE) callconv(.Inline) HRESULT { return @ptrCast(*const IWICJpegFrameEncode.VTable, self.vtable).GetDcHuffmanTable(@ptrCast(*const IWICJpegFrameEncode, self), scanIndex, tableIndex, pDcHuffmanTable); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IWICJpegFrameEncode_GetQuantizationTable(self: *const T, scanIndex: u32, tableIndex: u32, pQuantizationTable: ?*DXGI_JPEG_QUANTIZATION_TABLE) callconv(.Inline) HRESULT { return @ptrCast(*const IWICJpegFrameEncode.VTable, self.vtable).GetQuantizationTable(@ptrCast(*const IWICJpegFrameEncode, self), scanIndex, tableIndex, pQuantizationTable); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IWICJpegFrameEncode_WriteScan(self: *const T, cbScanData: u32, pbScanData: [*:0]const u8) callconv(.Inline) HRESULT { return @ptrCast(*const IWICJpegFrameEncode.VTable, self.vtable).WriteScan(@ptrCast(*const IWICJpegFrameEncode, self), cbScanData, pbScanData); } };} pub usingnamespace MethodMixin(@This()); }; pub const WICMetadataCreationOptions = enum(i32) { Default = 0, // AllowUnknown = 0, this enum value conflicts with Default FailUnknown = 65536, Mask = -65536, }; pub const WICMetadataCreationDefault = WICMetadataCreationOptions.Default; pub const WICMetadataCreationAllowUnknown = WICMetadataCreationOptions.Default; pub const WICMetadataCreationFailUnknown = WICMetadataCreationOptions.FailUnknown; pub const WICMetadataCreationMask = WICMetadataCreationOptions.Mask; pub const WICPersistOptions = enum(i32) { Default = 0, // LittleEndian = 0, this enum value conflicts with Default BigEndian = 1, StrictFormat = 2, NoCacheStream = 4, PreferUTF8 = 8, Mask = 65535, }; pub const WICPersistOptionDefault = WICPersistOptions.Default; pub const WICPersistOptionLittleEndian = WICPersistOptions.Default; pub const WICPersistOptionBigEndian = WICPersistOptions.BigEndian; pub const WICPersistOptionStrictFormat = WICPersistOptions.StrictFormat; pub const WICPersistOptionNoCacheStream = WICPersistOptions.NoCacheStream; pub const WICPersistOptionPreferUTF8 = WICPersistOptions.PreferUTF8; pub const WICPersistOptionMask = WICPersistOptions.Mask; // TODO: this type is limited to platform 'windows5.1.2600' const IID_IWICMetadataBlockReader_Value = Guid.initString("feaa2a8d-b3f3-43e4-b25c-d1de990a1ae1"); pub const IID_IWICMetadataBlockReader = &IID_IWICMetadataBlockReader_Value; pub const IWICMetadataBlockReader = extern struct { pub const VTable = extern struct { base: IUnknown.VTable, GetContainerFormat: fn( self: *const IWICMetadataBlockReader, pguidContainerFormat: ?*Guid, ) callconv(@import("std").os.windows.WINAPI) HRESULT, GetCount: fn( self: *const IWICMetadataBlockReader, pcCount: ?*u32, ) callconv(@import("std").os.windows.WINAPI) HRESULT, GetReaderByIndex: fn( self: *const IWICMetadataBlockReader, nIndex: u32, ppIMetadataReader: ?*?*IWICMetadataReader, ) callconv(@import("std").os.windows.WINAPI) HRESULT, GetEnumerator: fn( self: *const IWICMetadataBlockReader, ppIEnumMetadata: ?*?*IEnumUnknown, ) 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 IWICMetadataBlockReader_GetContainerFormat(self: *const T, pguidContainerFormat: ?*Guid) callconv(.Inline) HRESULT { return @ptrCast(*const IWICMetadataBlockReader.VTable, self.vtable).GetContainerFormat(@ptrCast(*const IWICMetadataBlockReader, self), pguidContainerFormat); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IWICMetadataBlockReader_GetCount(self: *const T, pcCount: ?*u32) callconv(.Inline) HRESULT { return @ptrCast(*const IWICMetadataBlockReader.VTable, self.vtable).GetCount(@ptrCast(*const IWICMetadataBlockReader, self), pcCount); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IWICMetadataBlockReader_GetReaderByIndex(self: *const T, nIndex: u32, ppIMetadataReader: ?*?*IWICMetadataReader) callconv(.Inline) HRESULT { return @ptrCast(*const IWICMetadataBlockReader.VTable, self.vtable).GetReaderByIndex(@ptrCast(*const IWICMetadataBlockReader, self), nIndex, ppIMetadataReader); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IWICMetadataBlockReader_GetEnumerator(self: *const T, ppIEnumMetadata: ?*?*IEnumUnknown) callconv(.Inline) HRESULT { return @ptrCast(*const IWICMetadataBlockReader.VTable, self.vtable).GetEnumerator(@ptrCast(*const IWICMetadataBlockReader, self), ppIEnumMetadata); } };} pub usingnamespace MethodMixin(@This()); }; // TODO: this type is limited to platform 'windows5.1.2600' const IID_IWICMetadataBlockWriter_Value = Guid.initString("08fb9676-b444-41e8-8dbe-6a53a542bff1"); pub const IID_IWICMetadataBlockWriter = &IID_IWICMetadataBlockWriter_Value; pub const IWICMetadataBlockWriter = extern struct { pub const VTable = extern struct { base: IWICMetadataBlockReader.VTable, InitializeFromBlockReader: fn( self: *const IWICMetadataBlockWriter, pIMDBlockReader: ?*IWICMetadataBlockReader, ) callconv(@import("std").os.windows.WINAPI) HRESULT, GetWriterByIndex: fn( self: *const IWICMetadataBlockWriter, nIndex: u32, ppIMetadataWriter: ?*?*IWICMetadataWriter, ) callconv(@import("std").os.windows.WINAPI) HRESULT, AddWriter: fn( self: *const IWICMetadataBlockWriter, pIMetadataWriter: ?*IWICMetadataWriter, ) callconv(@import("std").os.windows.WINAPI) HRESULT, SetWriterByIndex: fn( self: *const IWICMetadataBlockWriter, nIndex: u32, pIMetadataWriter: ?*IWICMetadataWriter, ) callconv(@import("std").os.windows.WINAPI) HRESULT, RemoveWriterByIndex: fn( self: *const IWICMetadataBlockWriter, nIndex: u32, ) callconv(@import("std").os.windows.WINAPI) HRESULT, }; vtable: *const VTable, pub fn MethodMixin(comptime T: type) type { return struct { pub usingnamespace IWICMetadataBlockReader.MethodMixin(T); // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IWICMetadataBlockWriter_InitializeFromBlockReader(self: *const T, pIMDBlockReader: ?*IWICMetadataBlockReader) callconv(.Inline) HRESULT { return @ptrCast(*const IWICMetadataBlockWriter.VTable, self.vtable).InitializeFromBlockReader(@ptrCast(*const IWICMetadataBlockWriter, self), pIMDBlockReader); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IWICMetadataBlockWriter_GetWriterByIndex(self: *const T, nIndex: u32, ppIMetadataWriter: ?*?*IWICMetadataWriter) callconv(.Inline) HRESULT { return @ptrCast(*const IWICMetadataBlockWriter.VTable, self.vtable).GetWriterByIndex(@ptrCast(*const IWICMetadataBlockWriter, self), nIndex, ppIMetadataWriter); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IWICMetadataBlockWriter_AddWriter(self: *const T, pIMetadataWriter: ?*IWICMetadataWriter) callconv(.Inline) HRESULT { return @ptrCast(*const IWICMetadataBlockWriter.VTable, self.vtable).AddWriter(@ptrCast(*const IWICMetadataBlockWriter, self), pIMetadataWriter); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IWICMetadataBlockWriter_SetWriterByIndex(self: *const T, nIndex: u32, pIMetadataWriter: ?*IWICMetadataWriter) callconv(.Inline) HRESULT { return @ptrCast(*const IWICMetadataBlockWriter.VTable, self.vtable).SetWriterByIndex(@ptrCast(*const IWICMetadataBlockWriter, self), nIndex, pIMetadataWriter); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IWICMetadataBlockWriter_RemoveWriterByIndex(self: *const T, nIndex: u32) callconv(.Inline) HRESULT { return @ptrCast(*const IWICMetadataBlockWriter.VTable, self.vtable).RemoveWriterByIndex(@ptrCast(*const IWICMetadataBlockWriter, self), nIndex); } };} pub usingnamespace MethodMixin(@This()); }; // TODO: this type is limited to platform 'windows5.1.2600' const IID_IWICMetadataReader_Value = Guid.initString("9204fe99-d8fc-4fd5-a001-9536b067a899"); pub const IID_IWICMetadataReader = &IID_IWICMetadataReader_Value; pub const IWICMetadataReader = extern struct { pub const VTable = extern struct { base: IUnknown.VTable, GetMetadataFormat: fn( self: *const IWICMetadataReader, pguidMetadataFormat: ?*Guid, ) callconv(@import("std").os.windows.WINAPI) HRESULT, GetMetadataHandlerInfo: fn( self: *const IWICMetadataReader, ppIHandler: ?*?*IWICMetadataHandlerInfo, ) callconv(@import("std").os.windows.WINAPI) HRESULT, GetCount: fn( self: *const IWICMetadataReader, pcCount: ?*u32, ) callconv(@import("std").os.windows.WINAPI) HRESULT, GetValueByIndex: fn( self: *const IWICMetadataReader, nIndex: u32, pvarSchema: ?*PROPVARIANT, pvarId: ?*PROPVARIANT, pvarValue: ?*PROPVARIANT, ) callconv(@import("std").os.windows.WINAPI) HRESULT, GetValue: fn( self: *const IWICMetadataReader, pvarSchema: ?*const PROPVARIANT, pvarId: ?*const PROPVARIANT, pvarValue: ?*PROPVARIANT, ) callconv(@import("std").os.windows.WINAPI) HRESULT, GetEnumerator: fn( self: *const IWICMetadataReader, ppIEnumMetadata: ?*?*IWICEnumMetadataItem, ) 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 IWICMetadataReader_GetMetadataFormat(self: *const T, pguidMetadataFormat: ?*Guid) callconv(.Inline) HRESULT { return @ptrCast(*const IWICMetadataReader.VTable, self.vtable).GetMetadataFormat(@ptrCast(*const IWICMetadataReader, self), pguidMetadataFormat); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IWICMetadataReader_GetMetadataHandlerInfo(self: *const T, ppIHandler: ?*?*IWICMetadataHandlerInfo) callconv(.Inline) HRESULT { return @ptrCast(*const IWICMetadataReader.VTable, self.vtable).GetMetadataHandlerInfo(@ptrCast(*const IWICMetadataReader, self), ppIHandler); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IWICMetadataReader_GetCount(self: *const T, pcCount: ?*u32) callconv(.Inline) HRESULT { return @ptrCast(*const IWICMetadataReader.VTable, self.vtable).GetCount(@ptrCast(*const IWICMetadataReader, self), pcCount); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IWICMetadataReader_GetValueByIndex(self: *const T, nIndex: u32, pvarSchema: ?*PROPVARIANT, pvarId: ?*PROPVARIANT, pvarValue: ?*PROPVARIANT) callconv(.Inline) HRESULT { return @ptrCast(*const IWICMetadataReader.VTable, self.vtable).GetValueByIndex(@ptrCast(*const IWICMetadataReader, self), nIndex, pvarSchema, pvarId, pvarValue); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IWICMetadataReader_GetValue(self: *const T, pvarSchema: ?*const PROPVARIANT, pvarId: ?*const PROPVARIANT, pvarValue: ?*PROPVARIANT) callconv(.Inline) HRESULT { return @ptrCast(*const IWICMetadataReader.VTable, self.vtable).GetValue(@ptrCast(*const IWICMetadataReader, self), pvarSchema, pvarId, pvarValue); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IWICMetadataReader_GetEnumerator(self: *const T, ppIEnumMetadata: ?*?*IWICEnumMetadataItem) callconv(.Inline) HRESULT { return @ptrCast(*const IWICMetadataReader.VTable, self.vtable).GetEnumerator(@ptrCast(*const IWICMetadataReader, self), ppIEnumMetadata); } };} pub usingnamespace MethodMixin(@This()); }; // TODO: this type is limited to platform 'windows5.1.2600' const IID_IWICMetadataWriter_Value = Guid.initString("f7836e16-3be0-470b-86bb-160d0aecd7de"); pub const IID_IWICMetadataWriter = &IID_IWICMetadataWriter_Value; pub const IWICMetadataWriter = extern struct { pub const VTable = extern struct { base: IWICMetadataReader.VTable, SetValue: fn( self: *const IWICMetadataWriter, pvarSchema: ?*const PROPVARIANT, pvarId: ?*const PROPVARIANT, pvarValue: ?*const PROPVARIANT, ) callconv(@import("std").os.windows.WINAPI) HRESULT, SetValueByIndex: fn( self: *const IWICMetadataWriter, nIndex: u32, pvarSchema: ?*const PROPVARIANT, pvarId: ?*const PROPVARIANT, pvarValue: ?*const PROPVARIANT, ) callconv(@import("std").os.windows.WINAPI) HRESULT, RemoveValue: fn( self: *const IWICMetadataWriter, pvarSchema: ?*const PROPVARIANT, pvarId: ?*const PROPVARIANT, ) callconv(@import("std").os.windows.WINAPI) HRESULT, RemoveValueByIndex: fn( self: *const IWICMetadataWriter, nIndex: u32, ) callconv(@import("std").os.windows.WINAPI) HRESULT, }; vtable: *const VTable, pub fn MethodMixin(comptime T: type) type { return struct { pub usingnamespace IWICMetadataReader.MethodMixin(T); // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IWICMetadataWriter_SetValue(self: *const T, pvarSchema: ?*const PROPVARIANT, pvarId: ?*const PROPVARIANT, pvarValue: ?*const PROPVARIANT) callconv(.Inline) HRESULT { return @ptrCast(*const IWICMetadataWriter.VTable, self.vtable).SetValue(@ptrCast(*const IWICMetadataWriter, self), pvarSchema, pvarId, pvarValue); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IWICMetadataWriter_SetValueByIndex(self: *const T, nIndex: u32, pvarSchema: ?*const PROPVARIANT, pvarId: ?*const PROPVARIANT, pvarValue: ?*const PROPVARIANT) callconv(.Inline) HRESULT { return @ptrCast(*const IWICMetadataWriter.VTable, self.vtable).SetValueByIndex(@ptrCast(*const IWICMetadataWriter, self), nIndex, pvarSchema, pvarId, pvarValue); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IWICMetadataWriter_RemoveValue(self: *const T, pvarSchema: ?*const PROPVARIANT, pvarId: ?*const PROPVARIANT) callconv(.Inline) HRESULT { return @ptrCast(*const IWICMetadataWriter.VTable, self.vtable).RemoveValue(@ptrCast(*const IWICMetadataWriter, self), pvarSchema, pvarId); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IWICMetadataWriter_RemoveValueByIndex(self: *const T, nIndex: u32) callconv(.Inline) HRESULT { return @ptrCast(*const IWICMetadataWriter.VTable, self.vtable).RemoveValueByIndex(@ptrCast(*const IWICMetadataWriter, self), nIndex); } };} pub usingnamespace MethodMixin(@This()); }; // TODO: this type is limited to platform 'windows5.1.2600' const IID_IWICStreamProvider_Value = Guid.initString("449494bc-b468-4927-96d7-ba90d31ab505"); pub const IID_IWICStreamProvider = &IID_IWICStreamProvider_Value; pub const IWICStreamProvider = extern struct { pub const VTable = extern struct { base: IUnknown.VTable, GetStream: fn( self: *const IWICStreamProvider, ppIStream: ?*?*IStream, ) callconv(@import("std").os.windows.WINAPI) HRESULT, GetPersistOptions: fn( self: *const IWICStreamProvider, pdwPersistOptions: ?*u32, ) callconv(@import("std").os.windows.WINAPI) HRESULT, GetPreferredVendorGUID: fn( self: *const IWICStreamProvider, pguidPreferredVendor: ?*Guid, ) callconv(@import("std").os.windows.WINAPI) HRESULT, RefreshStream: fn( self: *const IWICStreamProvider, ) 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 IWICStreamProvider_GetStream(self: *const T, ppIStream: ?*?*IStream) callconv(.Inline) HRESULT { return @ptrCast(*const IWICStreamProvider.VTable, self.vtable).GetStream(@ptrCast(*const IWICStreamProvider, self), ppIStream); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IWICStreamProvider_GetPersistOptions(self: *const T, pdwPersistOptions: ?*u32) callconv(.Inline) HRESULT { return @ptrCast(*const IWICStreamProvider.VTable, self.vtable).GetPersistOptions(@ptrCast(*const IWICStreamProvider, self), pdwPersistOptions); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IWICStreamProvider_GetPreferredVendorGUID(self: *const T, pguidPreferredVendor: ?*Guid) callconv(.Inline) HRESULT { return @ptrCast(*const IWICStreamProvider.VTable, self.vtable).GetPreferredVendorGUID(@ptrCast(*const IWICStreamProvider, self), pguidPreferredVendor); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IWICStreamProvider_RefreshStream(self: *const T) callconv(.Inline) HRESULT { return @ptrCast(*const IWICStreamProvider.VTable, self.vtable).RefreshStream(@ptrCast(*const IWICStreamProvider, self)); } };} pub usingnamespace MethodMixin(@This()); }; // TODO: this type is limited to platform 'windows5.1.2600' const IID_IWICPersistStream_Value = Guid.initString("00675040-6908-45f8-86a3-49c7dfd6d9ad"); pub const IID_IWICPersistStream = &IID_IWICPersistStream_Value; pub const IWICPersistStream = extern struct { pub const VTable = extern struct { base: IPersistStream.VTable, LoadEx: fn( self: *const IWICPersistStream, pIStream: ?*IStream, pguidPreferredVendor: ?*const Guid, dwPersistOptions: u32, ) callconv(@import("std").os.windows.WINAPI) HRESULT, SaveEx: fn( self: *const IWICPersistStream, pIStream: ?*IStream, dwPersistOptions: u32, fClearDirty: BOOL, ) callconv(@import("std").os.windows.WINAPI) HRESULT, }; vtable: *const VTable, pub fn MethodMixin(comptime T: type) type { return struct { pub usingnamespace IPersistStream.MethodMixin(T); // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IWICPersistStream_LoadEx(self: *const T, pIStream: ?*IStream, pguidPreferredVendor: ?*const Guid, dwPersistOptions: u32) callconv(.Inline) HRESULT { return @ptrCast(*const IWICPersistStream.VTable, self.vtable).LoadEx(@ptrCast(*const IWICPersistStream, self), pIStream, pguidPreferredVendor, dwPersistOptions); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IWICPersistStream_SaveEx(self: *const T, pIStream: ?*IStream, dwPersistOptions: u32, fClearDirty: BOOL) callconv(.Inline) HRESULT { return @ptrCast(*const IWICPersistStream.VTable, self.vtable).SaveEx(@ptrCast(*const IWICPersistStream, self), pIStream, dwPersistOptions, fClearDirty); } };} pub usingnamespace MethodMixin(@This()); }; // TODO: this type is limited to platform 'windows5.1.2600' const IID_IWICMetadataHandlerInfo_Value = Guid.initString("aba958bf-c672-44d1-8d61-ce6df2e682c2"); pub const IID_IWICMetadataHandlerInfo = &IID_IWICMetadataHandlerInfo_Value; pub const IWICMetadataHandlerInfo = extern struct { pub const VTable = extern struct { base: IWICComponentInfo.VTable, GetMetadataFormat: fn( self: *const IWICMetadataHandlerInfo, pguidMetadataFormat: ?*Guid, ) callconv(@import("std").os.windows.WINAPI) HRESULT, GetContainerFormats: fn( self: *const IWICMetadataHandlerInfo, cContainerFormats: u32, pguidContainerFormats: [*]Guid, pcchActual: ?*u32, ) callconv(@import("std").os.windows.WINAPI) HRESULT, GetDeviceManufacturer: fn( self: *const IWICMetadataHandlerInfo, cchDeviceManufacturer: u32, wzDeviceManufacturer: [*:0]u16, pcchActual: ?*u32, ) callconv(@import("std").os.windows.WINAPI) HRESULT, GetDeviceModels: fn( self: *const IWICMetadataHandlerInfo, cchDeviceModels: u32, wzDeviceModels: [*:0]u16, pcchActual: ?*u32, ) callconv(@import("std").os.windows.WINAPI) HRESULT, DoesRequireFullStream: fn( self: *const IWICMetadataHandlerInfo, pfRequiresFullStream: ?*BOOL, ) callconv(@import("std").os.windows.WINAPI) HRESULT, DoesSupportPadding: fn( self: *const IWICMetadataHandlerInfo, pfSupportsPadding: ?*BOOL, ) callconv(@import("std").os.windows.WINAPI) HRESULT, DoesRequireFixedSize: fn( self: *const IWICMetadataHandlerInfo, pfFixedSize: ?*BOOL, ) callconv(@import("std").os.windows.WINAPI) HRESULT, }; vtable: *const VTable, pub fn MethodMixin(comptime T: type) type { return struct { pub usingnamespace IWICComponentInfo.MethodMixin(T); // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IWICMetadataHandlerInfo_GetMetadataFormat(self: *const T, pguidMetadataFormat: ?*Guid) callconv(.Inline) HRESULT { return @ptrCast(*const IWICMetadataHandlerInfo.VTable, self.vtable).GetMetadataFormat(@ptrCast(*const IWICMetadataHandlerInfo, self), pguidMetadataFormat); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IWICMetadataHandlerInfo_GetContainerFormats(self: *const T, cContainerFormats: u32, pguidContainerFormats: [*]Guid, pcchActual: ?*u32) callconv(.Inline) HRESULT { return @ptrCast(*const IWICMetadataHandlerInfo.VTable, self.vtable).GetContainerFormats(@ptrCast(*const IWICMetadataHandlerInfo, self), cContainerFormats, pguidContainerFormats, pcchActual); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IWICMetadataHandlerInfo_GetDeviceManufacturer(self: *const T, cchDeviceManufacturer: u32, wzDeviceManufacturer: [*:0]u16, pcchActual: ?*u32) callconv(.Inline) HRESULT { return @ptrCast(*const IWICMetadataHandlerInfo.VTable, self.vtable).GetDeviceManufacturer(@ptrCast(*const IWICMetadataHandlerInfo, self), cchDeviceManufacturer, wzDeviceManufacturer, pcchActual); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IWICMetadataHandlerInfo_GetDeviceModels(self: *const T, cchDeviceModels: u32, wzDeviceModels: [*:0]u16, pcchActual: ?*u32) callconv(.Inline) HRESULT { return @ptrCast(*const IWICMetadataHandlerInfo.VTable, self.vtable).GetDeviceModels(@ptrCast(*const IWICMetadataHandlerInfo, self), cchDeviceModels, wzDeviceModels, pcchActual); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IWICMetadataHandlerInfo_DoesRequireFullStream(self: *const T, pfRequiresFullStream: ?*BOOL) callconv(.Inline) HRESULT { return @ptrCast(*const IWICMetadataHandlerInfo.VTable, self.vtable).DoesRequireFullStream(@ptrCast(*const IWICMetadataHandlerInfo, self), pfRequiresFullStream); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IWICMetadataHandlerInfo_DoesSupportPadding(self: *const T, pfSupportsPadding: ?*BOOL) callconv(.Inline) HRESULT { return @ptrCast(*const IWICMetadataHandlerInfo.VTable, self.vtable).DoesSupportPadding(@ptrCast(*const IWICMetadataHandlerInfo, self), pfSupportsPadding); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IWICMetadataHandlerInfo_DoesRequireFixedSize(self: *const T, pfFixedSize: ?*BOOL) callconv(.Inline) HRESULT { return @ptrCast(*const IWICMetadataHandlerInfo.VTable, self.vtable).DoesRequireFixedSize(@ptrCast(*const IWICMetadataHandlerInfo, self), pfFixedSize); } };} pub usingnamespace MethodMixin(@This()); }; pub const WICMetadataPattern = extern struct { Position: ULARGE_INTEGER, Length: u32, Pattern: ?*u8, Mask: ?*u8, DataOffset: ULARGE_INTEGER, }; // TODO: this type is limited to platform 'windows5.1.2600' const IID_IWICMetadataReaderInfo_Value = Guid.initString("eebf1f5b-07c1-4447-a3ab-22acaf78a804"); pub const IID_IWICMetadataReaderInfo = &IID_IWICMetadataReaderInfo_Value; pub const IWICMetadataReaderInfo = extern struct { pub const VTable = extern struct { base: IWICMetadataHandlerInfo.VTable, GetPatterns: fn( self: *const IWICMetadataReaderInfo, guidContainerFormat: ?*const Guid, cbSize: u32, // TODO: what to do with BytesParamIndex 1? pPattern: ?*WICMetadataPattern, pcCount: ?*u32, pcbActual: ?*u32, ) callconv(@import("std").os.windows.WINAPI) HRESULT, MatchesPattern: fn( self: *const IWICMetadataReaderInfo, guidContainerFormat: ?*const Guid, pIStream: ?*IStream, pfMatches: ?*BOOL, ) callconv(@import("std").os.windows.WINAPI) HRESULT, CreateInstance: fn( self: *const IWICMetadataReaderInfo, ppIReader: ?*?*IWICMetadataReader, ) callconv(@import("std").os.windows.WINAPI) HRESULT, }; vtable: *const VTable, pub fn MethodMixin(comptime T: type) type { return struct { pub usingnamespace IWICMetadataHandlerInfo.MethodMixin(T); // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IWICMetadataReaderInfo_GetPatterns(self: *const T, guidContainerFormat: ?*const Guid, cbSize: u32, pPattern: ?*WICMetadataPattern, pcCount: ?*u32, pcbActual: ?*u32) callconv(.Inline) HRESULT { return @ptrCast(*const IWICMetadataReaderInfo.VTable, self.vtable).GetPatterns(@ptrCast(*const IWICMetadataReaderInfo, self), guidContainerFormat, cbSize, pPattern, pcCount, pcbActual); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IWICMetadataReaderInfo_MatchesPattern(self: *const T, guidContainerFormat: ?*const Guid, pIStream: ?*IStream, pfMatches: ?*BOOL) callconv(.Inline) HRESULT { return @ptrCast(*const IWICMetadataReaderInfo.VTable, self.vtable).MatchesPattern(@ptrCast(*const IWICMetadataReaderInfo, self), guidContainerFormat, pIStream, pfMatches); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IWICMetadataReaderInfo_CreateInstance(self: *const T, ppIReader: ?*?*IWICMetadataReader) callconv(.Inline) HRESULT { return @ptrCast(*const IWICMetadataReaderInfo.VTable, self.vtable).CreateInstance(@ptrCast(*const IWICMetadataReaderInfo, self), ppIReader); } };} pub usingnamespace MethodMixin(@This()); }; pub const WICMetadataHeader = extern struct { Position: ULARGE_INTEGER, Length: u32, Header: ?*u8, DataOffset: ULARGE_INTEGER, }; // TODO: this type is limited to platform 'windows5.1.2600' const IID_IWICMetadataWriterInfo_Value = Guid.initString("b22e3fba-3925-4323-b5c1-9ebfc430f236"); pub const IID_IWICMetadataWriterInfo = &IID_IWICMetadataWriterInfo_Value; pub const IWICMetadataWriterInfo = extern struct { pub const VTable = extern struct { base: IWICMetadataHandlerInfo.VTable, GetHeader: fn( self: *const IWICMetadataWriterInfo, guidContainerFormat: ?*const Guid, cbSize: u32, // TODO: what to do with BytesParamIndex 1? pHeader: ?*WICMetadataHeader, pcbActual: ?*u32, ) callconv(@import("std").os.windows.WINAPI) HRESULT, CreateInstance: fn( self: *const IWICMetadataWriterInfo, ppIWriter: ?*?*IWICMetadataWriter, ) callconv(@import("std").os.windows.WINAPI) HRESULT, }; vtable: *const VTable, pub fn MethodMixin(comptime T: type) type { return struct { pub usingnamespace IWICMetadataHandlerInfo.MethodMixin(T); // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IWICMetadataWriterInfo_GetHeader(self: *const T, guidContainerFormat: ?*const Guid, cbSize: u32, pHeader: ?*WICMetadataHeader, pcbActual: ?*u32) callconv(.Inline) HRESULT { return @ptrCast(*const IWICMetadataWriterInfo.VTable, self.vtable).GetHeader(@ptrCast(*const IWICMetadataWriterInfo, self), guidContainerFormat, cbSize, pHeader, pcbActual); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IWICMetadataWriterInfo_CreateInstance(self: *const T, ppIWriter: ?*?*IWICMetadataWriter) callconv(.Inline) HRESULT { return @ptrCast(*const IWICMetadataWriterInfo.VTable, self.vtable).CreateInstance(@ptrCast(*const IWICMetadataWriterInfo, self), ppIWriter); } };} pub usingnamespace MethodMixin(@This()); }; // TODO: this type is limited to platform 'windows5.1.2600' const IID_IWICComponentFactory_Value = Guid.initString("412d0c3a-9650-44fa-af5b-dd2a06c8e8fb"); pub const IID_IWICComponentFactory = &IID_IWICComponentFactory_Value; pub const IWICComponentFactory = extern struct { pub const VTable = extern struct { base: IWICImagingFactory.VTable, CreateMetadataReader: fn( self: *const IWICComponentFactory, guidMetadataFormat: ?*const Guid, pguidVendor: ?*const Guid, dwOptions: u32, pIStream: ?*IStream, ppIReader: ?*?*IWICMetadataReader, ) callconv(@import("std").os.windows.WINAPI) HRESULT, CreateMetadataReaderFromContainer: fn( self: *const IWICComponentFactory, guidContainerFormat: ?*const Guid, pguidVendor: ?*const Guid, dwOptions: u32, pIStream: ?*IStream, ppIReader: ?*?*IWICMetadataReader, ) callconv(@import("std").os.windows.WINAPI) HRESULT, CreateMetadataWriter: fn( self: *const IWICComponentFactory, guidMetadataFormat: ?*const Guid, pguidVendor: ?*const Guid, dwMetadataOptions: u32, ppIWriter: ?*?*IWICMetadataWriter, ) callconv(@import("std").os.windows.WINAPI) HRESULT, CreateMetadataWriterFromReader: fn( self: *const IWICComponentFactory, pIReader: ?*IWICMetadataReader, pguidVendor: ?*const Guid, ppIWriter: ?*?*IWICMetadataWriter, ) callconv(@import("std").os.windows.WINAPI) HRESULT, CreateQueryReaderFromBlockReader: fn( self: *const IWICComponentFactory, pIBlockReader: ?*IWICMetadataBlockReader, ppIQueryReader: ?*?*IWICMetadataQueryReader, ) callconv(@import("std").os.windows.WINAPI) HRESULT, CreateQueryWriterFromBlockWriter: fn( self: *const IWICComponentFactory, pIBlockWriter: ?*IWICMetadataBlockWriter, ppIQueryWriter: ?*?*IWICMetadataQueryWriter, ) callconv(@import("std").os.windows.WINAPI) HRESULT, CreateEncoderPropertyBag: fn( self: *const IWICComponentFactory, ppropOptions: [*]PROPBAG2, cCount: u32, ppIPropertyBag: ?*?*IPropertyBag2, ) callconv(@import("std").os.windows.WINAPI) HRESULT, }; vtable: *const VTable, pub fn MethodMixin(comptime T: type) type { return struct { pub usingnamespace IWICImagingFactory.MethodMixin(T); // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IWICComponentFactory_CreateMetadataReader(self: *const T, guidMetadataFormat: ?*const Guid, pguidVendor: ?*const Guid, dwOptions: u32, pIStream: ?*IStream, ppIReader: ?*?*IWICMetadataReader) callconv(.Inline) HRESULT { return @ptrCast(*const IWICComponentFactory.VTable, self.vtable).CreateMetadataReader(@ptrCast(*const IWICComponentFactory, self), guidMetadataFormat, pguidVendor, dwOptions, pIStream, ppIReader); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IWICComponentFactory_CreateMetadataReaderFromContainer(self: *const T, guidContainerFormat: ?*const Guid, pguidVendor: ?*const Guid, dwOptions: u32, pIStream: ?*IStream, ppIReader: ?*?*IWICMetadataReader) callconv(.Inline) HRESULT { return @ptrCast(*const IWICComponentFactory.VTable, self.vtable).CreateMetadataReaderFromContainer(@ptrCast(*const IWICComponentFactory, self), guidContainerFormat, pguidVendor, dwOptions, pIStream, ppIReader); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IWICComponentFactory_CreateMetadataWriter(self: *const T, guidMetadataFormat: ?*const Guid, pguidVendor: ?*const Guid, dwMetadataOptions: u32, ppIWriter: ?*?*IWICMetadataWriter) callconv(.Inline) HRESULT { return @ptrCast(*const IWICComponentFactory.VTable, self.vtable).CreateMetadataWriter(@ptrCast(*const IWICComponentFactory, self), guidMetadataFormat, pguidVendor, dwMetadataOptions, ppIWriter); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IWICComponentFactory_CreateMetadataWriterFromReader(self: *const T, pIReader: ?*IWICMetadataReader, pguidVendor: ?*const Guid, ppIWriter: ?*?*IWICMetadataWriter) callconv(.Inline) HRESULT { return @ptrCast(*const IWICComponentFactory.VTable, self.vtable).CreateMetadataWriterFromReader(@ptrCast(*const IWICComponentFactory, self), pIReader, pguidVendor, ppIWriter); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IWICComponentFactory_CreateQueryReaderFromBlockReader(self: *const T, pIBlockReader: ?*IWICMetadataBlockReader, ppIQueryReader: ?*?*IWICMetadataQueryReader) callconv(.Inline) HRESULT { return @ptrCast(*const IWICComponentFactory.VTable, self.vtable).CreateQueryReaderFromBlockReader(@ptrCast(*const IWICComponentFactory, self), pIBlockReader, ppIQueryReader); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IWICComponentFactory_CreateQueryWriterFromBlockWriter(self: *const T, pIBlockWriter: ?*IWICMetadataBlockWriter, ppIQueryWriter: ?*?*IWICMetadataQueryWriter) callconv(.Inline) HRESULT { return @ptrCast(*const IWICComponentFactory.VTable, self.vtable).CreateQueryWriterFromBlockWriter(@ptrCast(*const IWICComponentFactory, self), pIBlockWriter, ppIQueryWriter); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IWICComponentFactory_CreateEncoderPropertyBag(self: *const T, ppropOptions: [*]PROPBAG2, cCount: u32, ppIPropertyBag: ?*?*IPropertyBag2) callconv(.Inline) HRESULT { return @ptrCast(*const IWICComponentFactory.VTable, self.vtable).CreateEncoderPropertyBag(@ptrCast(*const IWICComponentFactory, self), ppropOptions, cCount, ppIPropertyBag); } };} pub usingnamespace MethodMixin(@This()); }; //-------------------------------------------------------------------------------- // Section: Functions (9) //-------------------------------------------------------------------------------- // TODO: this type is limited to platform 'windows5.1.2600' pub extern "WindowsCodecs" fn WICConvertBitmapSource( dstFormat: ?*Guid, pISrc: ?*IWICBitmapSource, ppIDst: ?*?*IWICBitmapSource, ) callconv(@import("std").os.windows.WINAPI) HRESULT; // TODO: this type is limited to platform 'windows5.1.2600' pub extern "WindowsCodecs" fn WICCreateBitmapFromSection( width: u32, height: u32, pixelFormat: ?*Guid, hSection: ?HANDLE, stride: u32, offset: u32, ppIBitmap: ?*?*IWICBitmap, ) callconv(@import("std").os.windows.WINAPI) HRESULT; // TODO: this type is limited to platform 'windows6.1' pub extern "WindowsCodecs" fn WICCreateBitmapFromSectionEx( width: u32, height: u32, pixelFormat: ?*Guid, hSection: ?HANDLE, stride: u32, offset: u32, desiredAccessLevel: WICSectionAccessLevel, ppIBitmap: ?*?*IWICBitmap, ) callconv(@import("std").os.windows.WINAPI) HRESULT; // TODO: this type is limited to platform 'windows5.1.2600' pub extern "WindowsCodecs" fn WICMapGuidToShortName( guid: ?*const Guid, cchName: u32, wzName: ?[*:0]u16, pcchActual: ?*u32, ) callconv(@import("std").os.windows.WINAPI) HRESULT; // TODO: this type is limited to platform 'windows5.1.2600' pub extern "WindowsCodecs" fn WICMapShortNameToGuid( wzName: ?[*:0]const u16, pguid: ?*Guid, ) callconv(@import("std").os.windows.WINAPI) HRESULT; // TODO: this type is limited to platform 'windows5.1.2600' pub extern "WindowsCodecs" fn WICMapSchemaToName( guidMetadataFormat: ?*const Guid, pwzSchema: ?PWSTR, cchName: u32, wzName: ?[*:0]u16, pcchActual: ?*u32, ) callconv(@import("std").os.windows.WINAPI) HRESULT; // TODO: this type is limited to platform 'windows5.1.2600' pub extern "WindowsCodecs" fn WICMatchMetadataContent( guidContainerFormat: ?*const Guid, pguidVendor: ?*const Guid, pIStream: ?*IStream, pguidMetadataFormat: ?*Guid, ) callconv(@import("std").os.windows.WINAPI) HRESULT; // TODO: this type is limited to platform 'windows5.1.2600' pub extern "WindowsCodecs" fn WICSerializeMetadataContent( guidContainerFormat: ?*const Guid, pIWriter: ?*IWICMetadataWriter, dwPersistOptions: u32, pIStream: ?*IStream, ) callconv(@import("std").os.windows.WINAPI) HRESULT; // TODO: this type is limited to platform 'windows5.1.2600' pub extern "WindowsCodecs" fn WICGetMetadataContentSize( guidContainerFormat: ?*const Guid, pIWriter: ?*IWICMetadataWriter, pcbSize: ?*ULARGE_INTEGER, ) 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 (22) //-------------------------------------------------------------------------------- const Guid = @import("../zig.zig").Guid; const BOOL = @import("../foundation.zig").BOOL; const D2D1_PIXEL_FORMAT = @import("../graphics/direct2d/common.zig").D2D1_PIXEL_FORMAT; const DXGI_FORMAT = @import("../graphics/dxgi/common.zig").DXGI_FORMAT; const DXGI_JPEG_AC_HUFFMAN_TABLE = @import("../graphics/dxgi/common.zig").DXGI_JPEG_AC_HUFFMAN_TABLE; const DXGI_JPEG_DC_HUFFMAN_TABLE = @import("../graphics/dxgi/common.zig").DXGI_JPEG_DC_HUFFMAN_TABLE; const DXGI_JPEG_QUANTIZATION_TABLE = @import("../graphics/dxgi/common.zig").DXGI_JPEG_QUANTIZATION_TABLE; const HANDLE = @import("../foundation.zig").HANDLE; const HBITMAP = @import("../graphics/gdi.zig").HBITMAP; const HICON = @import("../ui/windows_and_messaging.zig").HICON; const HPALETTE = @import("../graphics/gdi.zig").HPALETTE; const HRESULT = @import("../foundation.zig").HRESULT; const IEnumString = @import("../system/com.zig").IEnumString; const IEnumUnknown = @import("../system/com.zig").IEnumUnknown; const IPersistStream = @import("../system/com.zig").IPersistStream; const IPropertyBag2 = @import("../system/com/structured_storage.zig").IPropertyBag2; const IStream = @import("../system/com.zig").IStream; const IUnknown = @import("../system/com.zig").IUnknown; const PROPBAG2 = @import("../system/com/structured_storage.zig").PROPBAG2; const PROPVARIANT = @import("../system/com/structured_storage.zig").PROPVARIANT; const PWSTR = @import("../foundation.zig").PWSTR; const ULARGE_INTEGER = @import("../foundation.zig").ULARGE_INTEGER; test { // The following '_ = <FuncPtrType>' lines are a workaround for https://github.com/ziglang/zig/issues/4476 if (@hasDecl(@This(), "PFNProgressNotification")) { _ = PFNProgressNotification; } @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; } } } //-------------------------------------------------------------------------------- // Section: SubModules (1) //-------------------------------------------------------------------------------- pub const d2d = @import("imaging/d2d.zig");
win32/graphics/imaging.zig
const std = @import("std"); const root = @import("root"); const submod_build_plugin = @import("submod_build_plugin.zig"); fn getWasm3Src() []const u8 { const sep = std.fs.path.sep_str; comptime { const gyro_dir = get_gyro: { const parent_dir = std.fs.path.dirname(@src().file).?; const maybe_clone_hash_dir = std.fs.path.dirname(parent_dir); const maybe_gyro_dir = if(maybe_clone_hash_dir) |d| std.fs.path.dirname(d) else null; if(std.ascii.eqlIgnoreCase(std.fs.path.basename(parent_dir), "pkg") and maybe_gyro_dir != null and std.ascii.eqlIgnoreCase(std.fs.path.basename(maybe_gyro_dir.?), ".gyro")) { break :get_gyro maybe_gyro_dir.?; } else { break :get_gyro std.fs.path.dirname(@src().file).? ++ sep ++ ".gyro"; } }; const gyro_lock = @embedFile("gyro.lock"); var iter = std.mem.split(gyro_lock, "\n"); while(iter.next()) |_line| { var line = std.mem.trim(u8, _line, &std.ascii.spaces); if(std.ascii.startsWithIgnoreCase(line, "github wasm3 wasm3")) { const commit = std.mem.trim(u8, line[std.mem.lastIndexOf(u8, line, " ").?..], &std.ascii.spaces); return gyro_dir ++ sep ++ "wasm3-wasm3-" ++ commit ++ sep ++ "pkg"; } } } @compileError("Failed to find wasm3 source repository!"); } fn repoDir(b: *std.build.Builder) []const u8 { return std.fs.path.resolve(b.allocator, &[_][]const u8{b.build_root, comptime getWasm3Src()}) catch unreachable; } /// Queues a build job for the C code of Wasm3. /// This builds a static library that depends on libc, so make sure to link that into your exe! pub fn compile(b: *std.build.Builder, mode: std.builtin.Mode, target: std.zig.CrossTarget) *std.build.LibExeObjStep { return submod_build_plugin.compile(b, mode, target, repoDir(b)); } /// Compiles Wasm3 and links it into the provided exe. /// If you use this API, you do not need to also use the compile() function. pub fn addTo(exe: *std.build.LibExeObjStep) void { submod_build_plugin.addTo(exe, repoDir(exe.builder)); } var file_buf: [std.fs.MAX_PATH_BYTES]u8 = undefined; pub fn pkg(name: ?[]const u8) std.build.Pkg { var fba = std.heap.FixedBufferAllocator.init(&file_buf); return .{ .name = name orelse "wasm3", .path = std.fs.path.join(&fba.allocator, &[_][]const u8{std.fs.path.dirname(@src().file).?, "src", "main.zig"}) catch unreachable, }; }
gyro_plugin.zig
const std = @import("std"); const assert = std.debug.assert; const os = std.os; const linux = os.linux; const IO_Uring = linux.IO_Uring; const io_uring_cqe = linux.io_uring_cqe; const io_uring_sqe = linux.io_uring_sqe; const FIFO = @import("fifo.zig").FIFO; const IO_Darwin = @import("io_darwin.zig").IO; pub const IO = switch (std.Target.current.os.tag) { .linux => IO_Linux, .macos, .tvos, .watchos, .ios => IO_Darwin, else => @compileError("IO is not supported for platform"), }; const IO_Linux = struct { ring: IO_Uring, /// Operations not yet submitted to the kernel and waiting on available space in the /// submission queue. unqueued: FIFO(Completion) = .{}, /// Completions that are ready to have their callbacks run. completed: FIFO(Completion) = .{}, pub fn init(entries: u12, flags: u32) !IO { return IO{ .ring = try IO_Uring.init(entries, flags) }; } pub fn deinit(self: *IO) void { self.ring.deinit(); } /// Pass all queued submissions to the kernel and peek for completions. pub fn tick(self: *IO) !void { // We assume that all timeouts submitted by `run_for_ns()` will be reaped by `run_for_ns()` // and that `tick()` and `run_for_ns()` cannot be run concurrently. // Therefore `timeouts` here will never be decremented and `etime` will always be false. var timeouts: usize = 0; var etime = false; try self.flush(0, &timeouts, &etime); assert(etime == false); // Flush any SQEs that were queued while running completion callbacks in `flush()`: // This is an optimization to avoid delaying submissions until the next tick. // At the same time, we do not flush any ready CQEs since SQEs may complete synchronously. // We guard against an io_uring_enter() syscall if we know we do not have any queued SQEs. // We cannot use `self.ring.sq_ready()` here since this counts flushed and unflushed SQEs. const queued = self.ring.sq.sqe_tail -% self.ring.sq.sqe_head; if (queued > 0) { try self.flush_submissions(0, &timeouts, &etime); assert(etime == false); } } /// Pass all queued submissions to the kernel and run for `nanoseconds`. /// The `nanoseconds` argument is a u63 to allow coercion to the i64 used /// in the __kernel_timespec struct. pub fn run_for_ns(self: *IO, nanoseconds: u63) !void { // We must use the same clock source used by io_uring (CLOCK_MONOTONIC) since we specify the // timeout below as an absolute value. Otherwise, we may deadlock if the clock sources are // dramatically different. Any kernel that supports io_uring will support CLOCK_MONOTONIC. var current_ts: os.timespec = undefined; os.clock_gettime(os.CLOCK_MONOTONIC, &current_ts) catch unreachable; // The absolute CLOCK_MONOTONIC time after which we may return from this function: const timeout_ts: os.__kernel_timespec = .{ .tv_sec = current_ts.tv_sec, .tv_nsec = current_ts.tv_nsec + nanoseconds, }; var timeouts: usize = 0; var etime = false; while (!etime) { const timeout_sqe = self.ring.get_sqe() catch blk: { // The submission queue is full, so flush submissions to make space: try self.flush_submissions(0, &timeouts, &etime); break :blk self.ring.get_sqe() catch unreachable; }; // Submit an absolute timeout that will be canceled if any other SQE completes first: linux.io_uring_prep_timeout(timeout_sqe, &timeout_ts, 1, os.IORING_TIMEOUT_ABS); timeout_sqe.user_data = 0; timeouts += 1; // The amount of time this call will block is bounded by the timeout we just submitted: try self.flush(1, &timeouts, &etime); } // Reap any remaining timeouts, which reference the timespec in the current stack frame. // The busy loop here is required to avoid a potential deadlock, as the kernel determines // when the timeouts are pushed to the completion queue, not us. while (timeouts > 0) _ = try self.flush_completions(0, &timeouts, &etime); } fn flush(self: *IO, wait_nr: u32, timeouts: *usize, etime: *bool) !void { // Flush any queued SQEs and reuse the same syscall to wait for completions if required: try self.flush_submissions(wait_nr, timeouts, etime); // We can now just peek for any CQEs without waiting and without another syscall: try self.flush_completions(0, timeouts, etime); // Run completions only after all completions have been flushed: // Loop on a copy of the linked list, having reset the list first, so that any synchronous // append on running a completion is executed only the next time round the event loop, // without creating an infinite loop. { var copy = self.completed; self.completed = .{}; while (copy.pop()) |completion| completion.complete(); } // Again, loop on a copy of the list to avoid an infinite loop: { var copy = self.unqueued; self.unqueued = .{}; while (copy.pop()) |completion| self.enqueue(completion); } } fn flush_completions(self: *IO, wait_nr: u32, timeouts: *usize, etime: *bool) !void { var cqes: [256]io_uring_cqe = undefined; var wait_remaining = wait_nr; while (true) { // Guard against waiting indefinitely (if there are too few requests inflight), // especially if this is not the first time round the loop: const completed = self.ring.copy_cqes(&cqes, wait_remaining) catch |err| switch (err) { error.SignalInterrupt => continue, else => return err, }; if (completed > wait_remaining) wait_remaining = 0 else wait_remaining -= completed; for (cqes[0..completed]) |cqe| { if (cqe.user_data == 0) { timeouts.* -= 1; // We are only done if the timeout submitted was completed due to time, not if // it was completed due to the completion of an event, in which case `cqe.res` // would be 0. It is possible for multiple timeout operations to complete at the // same time if the nanoseconds value passed to `run_for_ns()` is very short. if (-cqe.res == os.ETIME) etime.* = true; continue; } const completion = @intToPtr(*Completion, @intCast(usize, cqe.user_data)); completion.result = cqe.res; // We do not run the completion here (instead appending to a linked list) to avoid: // * recursion through `flush_submissions()` and `flush_completions()`, // * unbounded stack usage, and // * confusing stack traces. self.completed.push(completion); } if (completed < cqes.len) break; } } fn flush_submissions(self: *IO, wait_nr: u32, timeouts: *usize, etime: *bool) !void { while (true) { _ = self.ring.submit_and_wait(wait_nr) catch |err| switch (err) { error.SignalInterrupt => continue, // Wait for some completions and then try again: // See https://github.com/axboe/liburing/issues/281 re: error.SystemResources. // Be careful also that copy_cqes() will flush before entering to wait (it does): // https://github.com/axboe/liburing/commit/35c199c48dfd54ad46b96e386882e7ac341314c5 error.CompletionQueueOvercommitted, error.SystemResources => { try self.flush_completions(1, timeouts, etime); continue; }, else => return err, }; break; } } fn enqueue(self: *IO, completion: *Completion) void { const sqe = self.ring.get_sqe() catch |err| switch (err) { error.SubmissionQueueFull => { self.unqueued.push(completion); return; }, }; completion.prep(sqe); } /// This struct holds the data needed for a single io_uring operation pub const Completion = struct { io: *IO, result: i32 = undefined, next: ?*Completion = null, operation: Operation, // This is one of the usecases for c_void outside of C code and as such c_void will // be replaced with anyopaque eventually: https://github.com/ziglang/zig/issues/323 context: ?*c_void, callback: fn (context: ?*c_void, completion: *Completion, result: *const c_void) void, fn prep(completion: *Completion, sqe: *io_uring_sqe) void { switch (completion.operation) { .accept => |*op| { linux.io_uring_prep_accept( sqe, op.socket, &op.address, &op.address_size, op.flags, ); }, .close => |op| { linux.io_uring_prep_close(sqe, op.fd); }, .connect => |*op| { linux.io_uring_prep_connect( sqe, op.socket, &op.address.any, op.address.getOsSockLen(), ); }, .fsync => |op| { linux.io_uring_prep_fsync(sqe, op.fd, op.flags); }, .openat => |op| { linux.io_uring_prep_openat(sqe, op.fd, op.path, op.flags, op.mode); }, .read => |op| { linux.io_uring_prep_read( sqe, op.fd, op.buffer[0..buffer_limit(op.buffer.len)], op.offset, ); }, .recv => |op| { linux.io_uring_prep_recv(sqe, op.socket, op.buffer, op.flags); }, .send => |op| { linux.io_uring_prep_send(sqe, op.socket, op.buffer, op.flags); }, .timeout => |*op| { linux.io_uring_prep_timeout(sqe, &op.timespec, 0, 0); }, .write => |op| { linux.io_uring_prep_write( sqe, op.fd, op.buffer[0..buffer_limit(op.buffer.len)], op.offset, ); }, } sqe.user_data = @ptrToInt(completion); } fn complete(completion: *Completion) void { switch (completion.operation) { .accept => { const result = if (completion.result < 0) switch (-completion.result) { os.EINTR => { completion.io.enqueue(completion); return; }, os.EAGAIN => error.WouldBlock, os.EBADF => error.FileDescriptorInvalid, os.ECONNABORTED => error.ConnectionAborted, os.EFAULT => unreachable, os.EINVAL => error.SocketNotListening, os.EMFILE => error.ProcessFdQuotaExceeded, os.ENFILE => error.SystemFdQuotaExceeded, os.ENOBUFS => error.SystemResources, os.ENOMEM => error.SystemResources, os.ENOTSOCK => error.FileDescriptorNotASocket, os.EOPNOTSUPP => error.OperationNotSupported, os.EPERM => error.PermissionDenied, os.EPROTO => error.ProtocolFailure, else => |errno| os.unexpectedErrno(@intCast(usize, errno)), } else @intCast(os.socket_t, completion.result); completion.callback(completion.context, completion, &result); }, .close => { const result = if (completion.result < 0) switch (-completion.result) { os.EINTR => {}, // A success, see https://github.com/ziglang/zig/issues/2425 os.EBADF => error.FileDescriptorInvalid, os.EDQUOT => error.DiskQuota, os.EIO => error.InputOutput, os.ENOSPC => error.NoSpaceLeft, else => |errno| os.unexpectedErrno(@intCast(usize, errno)), } else assert(completion.result == 0); completion.callback(completion.context, completion, &result); }, .connect => { const result = if (completion.result < 0) switch (-completion.result) { os.EINTR => { completion.io.enqueue(completion); return; }, os.EACCES => error.AccessDenied, os.EADDRINUSE => error.AddressInUse, os.EADDRNOTAVAIL => error.AddressNotAvailable, os.EAFNOSUPPORT => error.AddressFamilyNotSupported, os.EAGAIN, os.EINPROGRESS => error.WouldBlock, os.EALREADY => error.OpenAlreadyInProgress, os.EBADF => error.FileDescriptorInvalid, os.ECONNREFUSED => error.ConnectionRefused, os.ECONNRESET => error.ConnectionResetByPeer, os.EFAULT => unreachable, os.EISCONN => error.AlreadyConnected, os.ENETUNREACH => error.NetworkUnreachable, os.ENOENT => error.FileNotFound, os.ENOTSOCK => error.FileDescriptorNotASocket, os.EPERM => error.PermissionDenied, os.EPROTOTYPE => error.ProtocolNotSupported, os.ETIMEDOUT => error.ConnectionTimedOut, else => |errno| os.unexpectedErrno(@intCast(usize, errno)), } else assert(completion.result == 0); completion.callback(completion.context, completion, &result); }, .fsync => { const result = if (completion.result < 0) switch (-completion.result) { os.EINTR => { completion.io.enqueue(completion); return; }, os.EBADF => error.FileDescriptorInvalid, os.EDQUOT => error.DiskQuota, os.EINVAL => error.ArgumentsInvalid, os.EIO => error.InputOutput, os.ENOSPC => error.NoSpaceLeft, os.EROFS => error.ReadOnlyFileSystem, else => |errno| os.unexpectedErrno(@intCast(usize, errno)), } else assert(completion.result == 0); completion.callback(completion.context, completion, &result); }, .openat => { const result = if (completion.result < 0) switch (-completion.result) { os.EINTR => { completion.io.enqueue(completion); return; }, os.EACCES => error.AccessDenied, os.EBADF => error.FileDescriptorInvalid, os.EBUSY => error.DeviceBusy, os.EEXIST => error.PathAlreadyExists, os.EFAULT => unreachable, os.EFBIG => error.FileTooBig, os.EINVAL => error.ArgumentsInvalid, os.EISDIR => error.IsDir, os.ELOOP => error.SymLinkLoop, os.EMFILE => error.ProcessFdQuotaExceeded, os.ENAMETOOLONG => error.NameTooLong, os.ENFILE => error.SystemFdQuotaExceeded, os.ENODEV => error.NoDevice, os.ENOENT => error.FileNotFound, os.ENOMEM => error.SystemResources, os.ENOSPC => error.NoSpaceLeft, os.ENOTDIR => error.NotDir, os.EOPNOTSUPP => error.FileLocksNotSupported, os.EOVERFLOW => error.FileTooBig, os.EPERM => error.AccessDenied, os.EWOULDBLOCK => error.WouldBlock, else => |errno| os.unexpectedErrno(@intCast(usize, errno)), } else @intCast(os.fd_t, completion.result); completion.callback(completion.context, completion, &result); }, .read => { const result = if (completion.result < 0) switch (-completion.result) { os.EINTR => { completion.io.enqueue(completion); return; }, os.EAGAIN => error.WouldBlock, os.EBADF => error.NotOpenForReading, os.ECONNRESET => error.ConnectionResetByPeer, os.EFAULT => unreachable, os.EINVAL => error.Alignment, os.EIO => error.InputOutput, os.EISDIR => error.IsDir, os.ENOBUFS => error.SystemResources, os.ENOMEM => error.SystemResources, os.ENXIO => error.Unseekable, os.EOVERFLOW => error.Unseekable, os.ESPIPE => error.Unseekable, else => |errno| os.unexpectedErrno(@intCast(usize, errno)), } else @intCast(usize, completion.result); completion.callback(completion.context, completion, &result); }, .recv => { const result = if (completion.result < 0) switch (-completion.result) { os.EINTR => { completion.io.enqueue(completion); return; }, os.EAGAIN => error.WouldBlock, os.EBADF => error.FileDescriptorInvalid, os.ECONNREFUSED => error.ConnectionRefused, os.EFAULT => unreachable, os.EINVAL => unreachable, os.ENOMEM => error.SystemResources, os.ENOTCONN => error.SocketNotConnected, os.ENOTSOCK => error.FileDescriptorNotASocket, os.ECONNRESET => error.ConnectionResetByPeer, else => |errno| os.unexpectedErrno(@intCast(usize, errno)), } else @intCast(usize, completion.result); completion.callback(completion.context, completion, &result); }, .send => { const result = if (completion.result < 0) switch (-completion.result) { os.EINTR => { completion.io.enqueue(completion); return; }, os.EACCES => error.AccessDenied, os.EAGAIN => error.WouldBlock, os.EALREADY => error.FastOpenAlreadyInProgress, os.EAFNOSUPPORT => error.AddressFamilyNotSupported, os.EBADF => error.FileDescriptorInvalid, os.ECONNRESET => error.ConnectionResetByPeer, os.EDESTADDRREQ => unreachable, os.EFAULT => unreachable, os.EINVAL => unreachable, os.EISCONN => unreachable, os.EMSGSIZE => error.MessageTooBig, os.ENOBUFS => error.SystemResources, os.ENOMEM => error.SystemResources, os.ENOTCONN => error.SocketNotConnected, os.ENOTSOCK => error.FileDescriptorNotASocket, os.EOPNOTSUPP => error.OperationNotSupported, os.EPIPE => error.BrokenPipe, else => |errno| os.unexpectedErrno(@intCast(usize, errno)), } else @intCast(usize, completion.result); completion.callback(completion.context, completion, &result); }, .timeout => { const result = if (completion.result < 0) switch (-completion.result) { os.EINTR => { completion.io.enqueue(completion); return; }, os.ECANCELED => error.Canceled, os.ETIME => {}, // A success. else => |errno| os.unexpectedErrno(@intCast(usize, errno)), } else unreachable; completion.callback(completion.context, completion, &result); }, .write => { const result = if (completion.result < 0) switch (-completion.result) { os.EINTR => { completion.io.enqueue(completion); return; }, os.EAGAIN => error.WouldBlock, os.EBADF => error.NotOpenForWriting, os.EDESTADDRREQ => error.NotConnected, os.EDQUOT => error.DiskQuota, os.EFAULT => unreachable, os.EFBIG => error.FileTooBig, os.EINVAL => error.Alignment, os.EIO => error.InputOutput, os.ENOSPC => error.NoSpaceLeft, os.ENXIO => error.Unseekable, os.EOVERFLOW => error.Unseekable, os.EPERM => error.AccessDenied, os.EPIPE => error.BrokenPipe, os.ESPIPE => error.Unseekable, else => |errno| os.unexpectedErrno(@intCast(usize, errno)), } else @intCast(usize, completion.result); completion.callback(completion.context, completion, &result); }, } } }; /// This union encodes the set of operations supported as well as their arguments. const Operation = union(enum) { accept: struct { socket: os.socket_t, address: os.sockaddr = undefined, address_size: os.socklen_t = @sizeOf(os.sockaddr), flags: u32, }, close: struct { fd: os.fd_t, }, connect: struct { socket: os.socket_t, address: std.net.Address, }, fsync: struct { fd: os.fd_t, flags: u32, }, openat: struct { fd: os.fd_t, path: [*:0]const u8, flags: u32, mode: os.mode_t, }, read: struct { fd: os.fd_t, buffer: []u8, offset: u64, }, recv: struct { socket: os.socket_t, buffer: []u8, flags: u32, }, send: struct { socket: os.socket_t, buffer: []const u8, flags: u32, }, timeout: struct { timespec: os.__kernel_timespec, }, write: struct { fd: os.fd_t, buffer: []const u8, offset: u64, }, }; pub const AcceptError = error{ WouldBlock, FileDescriptorInvalid, ConnectionAborted, SocketNotListening, ProcessFdQuotaExceeded, SystemFdQuotaExceeded, SystemResources, FileDescriptorNotASocket, OperationNotSupported, PermissionDenied, ProtocolFailure, } || os.UnexpectedError; pub fn accept( self: *IO, comptime Context: type, context: Context, comptime callback: fn ( context: Context, completion: *Completion, result: AcceptError!os.socket_t, ) void, completion: *Completion, socket: os.socket_t, flags: u32, ) void { completion.* = .{ .io = self, .context = context, .callback = struct { fn wrapper(ctx: ?*c_void, comp: *Completion, res: *const c_void) void { callback( @intToPtr(Context, @ptrToInt(ctx)), comp, @intToPtr(*const AcceptError!os.socket_t, @ptrToInt(res)).*, ); } }.wrapper, .operation = .{ .accept = .{ .socket = socket, .address = undefined, .address_size = @sizeOf(os.sockaddr), .flags = flags, }, }, }; self.enqueue(completion); } pub const CloseError = error{ FileDescriptorInvalid, DiskQuota, InputOutput, NoSpaceLeft, } || os.UnexpectedError; pub fn close( self: *IO, comptime Context: type, context: Context, comptime callback: fn ( context: Context, completion: *Completion, result: CloseError!void, ) void, completion: *Completion, fd: os.fd_t, ) void { completion.* = .{ .io = self, .context = context, .callback = struct { fn wrapper(ctx: ?*c_void, comp: *Completion, res: *const c_void) void { callback( @intToPtr(Context, @ptrToInt(ctx)), comp, @intToPtr(*const CloseError!void, @ptrToInt(res)).*, ); } }.wrapper, .operation = .{ .close = .{ .fd = fd }, }, }; self.enqueue(completion); } pub const ConnectError = error{ AccessDenied, AddressInUse, AddressNotAvailable, AddressFamilyNotSupported, WouldBlock, OpenAlreadyInProgress, FileDescriptorInvalid, ConnectionRefused, AlreadyConnected, NetworkUnreachable, FileNotFound, FileDescriptorNotASocket, PermissionDenied, ProtocolNotSupported, ConnectionTimedOut, } || os.UnexpectedError; pub fn connect( self: *IO, comptime Context: type, context: Context, comptime callback: fn ( context: Context, completion: *Completion, result: ConnectError!void, ) void, completion: *Completion, socket: os.socket_t, address: std.net.Address, ) void { completion.* = .{ .io = self, .context = context, .callback = struct { fn wrapper(ctx: ?*c_void, comp: *Completion, res: *const c_void) void { callback( @intToPtr(Context, @ptrToInt(ctx)), comp, @intToPtr(*const ConnectError!void, @ptrToInt(res)).*, ); } }.wrapper, .operation = .{ .connect = .{ .socket = socket, .address = address, }, }, }; self.enqueue(completion); } pub const FsyncError = error{ FileDescriptorInvalid, DiskQuota, ArgumentsInvalid, InputOutput, NoSpaceLeft, ReadOnlyFileSystem, } || os.UnexpectedError; pub fn fsync( self: *IO, comptime Context: type, context: Context, comptime callback: fn ( context: Context, completion: *Completion, result: FsyncError!void, ) void, completion: *Completion, fd: os.fd_t, flags: u32, ) void { completion.* = .{ .io = self, .context = context, .callback = struct { fn wrapper(ctx: ?*c_void, comp: *Completion, res: *const c_void) void { callback( @intToPtr(Context, @ptrToInt(ctx)), comp, @intToPtr(*const FsyncError!void, @ptrToInt(res)).*, ); } }.wrapper, .operation = .{ .fsync = .{ .fd = fd, .flags = flags, }, }, }; self.enqueue(completion); } pub const OpenatError = error{ AccessDenied, FileDescriptorInvalid, DeviceBusy, PathAlreadyExists, FileTooBig, ArgumentsInvalid, IsDir, SymLinkLoop, ProcessFdQuotaExceeded, NameTooLong, SystemFdQuotaExceeded, NoDevice, FileNotFound, SystemResources, NoSpaceLeft, NotDir, FileLocksNotSupported, WouldBlock, } || os.UnexpectedError; pub fn openat( self: *IO, comptime Context: type, context: Context, comptime callback: fn ( context: Context, completion: *Completion, result: OpenatError!os.fd_t, ) void, completion: *Completion, fd: os.fd_t, path: [*:0]const u8, flags: u32, mode: os.mode_t, ) void { completion.* = .{ .io = self, .context = context, .callback = struct { fn wrapper(ctx: ?*c_void, comp: *Completion, res: *const c_void) void { callback( @intToPtr(Context, @ptrToInt(ctx)), comp, @intToPtr(*const OpenatError!os.fd_t, @ptrToInt(res)).*, ); } }.wrapper, .operation = .{ .openat = .{ .fd = fd, .path = path, .flags = flags, .mode = mode, }, }, }; self.enqueue(completion); } pub const ReadError = error{ WouldBlock, NotOpenForReading, ConnectionResetByPeer, Alignment, InputOutput, IsDir, SystemResources, Unseekable, } || os.UnexpectedError; pub fn read( self: *IO, comptime Context: type, context: Context, comptime callback: fn ( context: Context, completion: *Completion, result: ReadError!usize, ) void, completion: *Completion, fd: os.fd_t, buffer: []u8, offset: u64, ) void { completion.* = .{ .io = self, .context = context, .callback = struct { fn wrapper(ctx: ?*c_void, comp: *Completion, res: *const c_void) void { callback( @intToPtr(Context, @ptrToInt(ctx)), comp, @intToPtr(*const ReadError!usize, @ptrToInt(res)).*, ); } }.wrapper, .operation = .{ .read = .{ .fd = fd, .buffer = buffer, .offset = offset, }, }, }; self.enqueue(completion); } pub const RecvError = error{ WouldBlock, FileDescriptorInvalid, ConnectionRefused, SystemResources, SocketNotConnected, FileDescriptorNotASocket, } || os.UnexpectedError; pub fn recv( self: *IO, comptime Context: type, context: Context, comptime callback: fn ( context: Context, completion: *Completion, result: RecvError!usize, ) void, completion: *Completion, socket: os.socket_t, buffer: []u8, flags: u32, ) void { completion.* = .{ .io = self, .context = context, .callback = struct { fn wrapper(ctx: ?*c_void, comp: *Completion, res: *const c_void) void { callback( @intToPtr(Context, @ptrToInt(ctx)), comp, @intToPtr(*const RecvError!usize, @ptrToInt(res)).*, ); } }.wrapper, .operation = .{ .recv = .{ .socket = socket, .buffer = buffer, .flags = flags, }, }, }; self.enqueue(completion); } pub const SendError = error{ AccessDenied, WouldBlock, FastOpenAlreadyInProgress, AddressFamilyNotSupported, FileDescriptorInvalid, ConnectionResetByPeer, MessageTooBig, SystemResources, SocketNotConnected, FileDescriptorNotASocket, OperationNotSupported, BrokenPipe, } || os.UnexpectedError; pub fn send( self: *IO, comptime Context: type, context: Context, comptime callback: fn ( context: Context, completion: *Completion, result: SendError!usize, ) void, completion: *Completion, socket: os.socket_t, buffer: []const u8, flags: u32, ) void { completion.* = .{ .io = self, .context = context, .callback = struct { fn wrapper(ctx: ?*c_void, comp: *Completion, res: *const c_void) void { callback( @intToPtr(Context, @ptrToInt(ctx)), comp, @intToPtr(*const SendError!usize, @ptrToInt(res)).*, ); } }.wrapper, .operation = .{ .send = .{ .socket = socket, .buffer = buffer, .flags = flags, }, }, }; self.enqueue(completion); } pub const TimeoutError = error{Canceled} || os.UnexpectedError; pub fn timeout( self: *IO, comptime Context: type, context: Context, comptime callback: fn ( context: Context, completion: *Completion, result: TimeoutError!void, ) void, completion: *Completion, nanoseconds: u63, ) void { completion.* = .{ .io = self, .context = context, .callback = struct { fn wrapper(ctx: ?*c_void, comp: *Completion, res: *const c_void) void { callback( @intToPtr(Context, @ptrToInt(ctx)), comp, @intToPtr(*const TimeoutError!void, @ptrToInt(res)).*, ); } }.wrapper, .operation = .{ .timeout = .{ .timespec = .{ .tv_sec = 0, .tv_nsec = nanoseconds }, }, }, }; self.enqueue(completion); } pub const WriteError = error{ WouldBlock, NotOpenForWriting, NotConnected, DiskQuota, FileTooBig, Alignment, InputOutput, NoSpaceLeft, Unseekable, AccessDenied, BrokenPipe, } || os.UnexpectedError; pub fn write( self: *IO, comptime Context: type, context: Context, comptime callback: fn ( context: Context, completion: *Completion, result: WriteError!usize, ) void, completion: *Completion, fd: os.fd_t, buffer: []const u8, offset: u64, ) void { completion.* = .{ .io = self, .context = context, .callback = struct { fn wrapper(ctx: ?*c_void, comp: *Completion, res: *const c_void) void { callback( @intToPtr(Context, @ptrToInt(ctx)), comp, @intToPtr(*const WriteError!usize, @ptrToInt(res)).*, ); } }.wrapper, .operation = .{ .write = .{ .fd = fd, .buffer = buffer, .offset = offset, }, }, }; self.enqueue(completion); } }; pub fn buffer_limit(buffer_len: usize) usize { // Linux limits how much may be written in a `pwrite()/pread()` call, which is `0x7ffff000` on // both 64-bit and 32-bit systems, due to using a signed C int as the return value, as well as // stuffing the errno codes into the last `4096` values. // Darwin limits writes to `0x7fffffff` bytes, more than that returns `EINVAL`. // The corresponding POSIX limit is `std.math.maxInt(isize)`. const limit = switch (std.Target.current.os.tag) { .linux => 0x7ffff000, .macos, .ios, .watchos, .tvos => std.math.maxInt(i32), else => std.math.maxInt(isize), }; return std.math.min(limit, buffer_len); } test "ref all decls" { std.testing.refAllDecls(IO); } test "write/fsync/read" { const testing = std.testing; try struct { const Context = @This(); io: IO, done: bool = false, fd: os.fd_t, write_buf: [20]u8 = [_]u8{97} ** 20, read_buf: [20]u8 = [_]u8{98} ** 20, written: usize = 0, fsynced: bool = false, read: usize = 0, fn run_test() !void { const path = "test_io_write_fsync_read"; const file = try std.fs.cwd().createFile(path, .{ .read = true, .truncate = true }); defer file.close(); defer std.fs.cwd().deleteFile(path) catch {}; var self: Context = .{ .io = try IO.init(32, 0), .fd = file.handle, }; defer self.io.deinit(); var completion: IO.Completion = undefined; self.io.write( *Context, &self, write_callback, &completion, self.fd, &self.write_buf, 10, ); while (!self.done) try self.io.tick(); try testing.expectEqual(self.write_buf.len, self.written); try testing.expect(self.fsynced); try testing.expectEqual(self.read_buf.len, self.read); try testing.expectEqualSlices(u8, &self.write_buf, &self.read_buf); } fn write_callback( self: *Context, completion: *IO.Completion, result: IO.WriteError!usize, ) void { self.written = result catch @panic("write error"); self.io.fsync(*Context, self, fsync_callback, completion, self.fd, 0); } fn fsync_callback( self: *Context, completion: *IO.Completion, result: IO.FsyncError!void, ) void { result catch @panic("fsync error"); self.fsynced = true; self.io.read(*Context, self, read_callback, completion, self.fd, &self.read_buf, 10); } fn read_callback( self: *Context, completion: *IO.Completion, result: IO.ReadError!usize, ) void { self.read = result catch @panic("read error"); self.done = true; } }.run_test(); } test "openat/close" { const testing = std.testing; try struct { const Context = @This(); io: IO, done: bool = false, fd: os.fd_t = 0, fn run_test() !void { const path = "test_io_openat_close"; defer std.fs.cwd().deleteFile(path) catch {}; var self: Context = .{ .io = try IO.init(32, 0) }; defer self.io.deinit(); var completion: IO.Completion = undefined; self.io.openat( *Context, &self, openat_callback, &completion, linux.AT_FDCWD, path, os.O_CLOEXEC | os.O_RDWR | os.O_CREAT, 0o666, ); while (!self.done) try self.io.tick(); try testing.expect(self.fd > 0); } fn openat_callback( self: *Context, completion: *IO.Completion, result: IO.OpenatError!os.fd_t, ) void { self.fd = result catch @panic("openat error"); self.io.close(*Context, self, close_callback, completion, self.fd); } fn close_callback( self: *Context, completion: *IO.Completion, result: IO.CloseError!void, ) void { result catch @panic("close error"); self.done = true; } }.run_test(); } test "accept/connect/send/receive" { const testing = std.testing; try struct { const Context = @This(); io: IO, done: bool = false, server: os.socket_t, client: os.socket_t, accepted_sock: os.socket_t = undefined, send_buf: [10]u8 = [_]u8{ 1, 0, 1, 0, 1, 0, 1, 0, 1, 0 }, recv_buf: [5]u8 = [_]u8{ 0, 1, 0, 1, 0 }, sent: usize = 0, received: usize = 0, fn run_test() !void { const address = try std.net.Address.parseIp4("127.0.0.1", 3131); const kernel_backlog = 1; const server = try os.socket(address.any.family, os.SOCK_STREAM | os.SOCK_CLOEXEC, 0); defer os.close(server); const client = try os.socket(address.any.family, os.SOCK_STREAM | os.SOCK_CLOEXEC, 0); defer os.close(client); try os.setsockopt( server, os.SOL_SOCKET, os.SO_REUSEADDR, &std.mem.toBytes(@as(c_int, 1)), ); try os.bind(server, &address.any, address.getOsSockLen()); try os.listen(server, kernel_backlog); var self: Context = .{ .io = try IO.init(32, 0), .server = server, .client = client, }; defer self.io.deinit(); var client_completion: IO.Completion = undefined; self.io.connect( *Context, &self, connect_callback, &client_completion, client, address, ); var server_completion: IO.Completion = undefined; self.io.accept(*Context, &self, accept_callback, &server_completion, server, 0); while (!self.done) try self.io.tick(); try testing.expectEqual(self.send_buf.len, self.sent); try testing.expectEqual(self.recv_buf.len, self.received); try testing.expectEqualSlices(u8, self.send_buf[0..self.received], &self.recv_buf); } fn connect_callback( self: *Context, completion: *IO.Completion, result: IO.ConnectError!void, ) void { result catch @panic("connect error"); self.io.send( *Context, self, send_callback, completion, self.client, &self.send_buf, if (std.Target.current.os.tag == .linux) os.MSG_NOSIGNAL else 0, ); } fn send_callback( self: *Context, completion: *IO.Completion, result: IO.SendError!usize, ) void { self.sent = result catch @panic("send error"); } fn accept_callback( self: *Context, completion: *IO.Completion, result: IO.AcceptError!os.socket_t, ) void { self.accepted_sock = result catch @panic("accept error"); self.io.recv( *Context, self, recv_callback, completion, self.accepted_sock, &self.recv_buf, if (std.Target.current.os.tag == .linux) os.MSG_NOSIGNAL else 0, ); } fn recv_callback( self: *Context, completion: *IO.Completion, result: IO.RecvError!usize, ) void { self.received = result catch @panic("recv error"); self.done = true; } }.run_test(); } test "timeout" { const testing = std.testing; const ms = 20; const margin = 5; const count = 10; try struct { const Context = @This(); io: IO, count: u32 = 0, stop_time: i64 = 0, fn run_test() !void { const start_time = std.time.milliTimestamp(); var self: Context = .{ .io = try IO.init(32, 0) }; defer self.io.deinit(); var completions: [count]IO.Completion = undefined; for (completions) |*completion| { self.io.timeout( *Context, &self, timeout_callback, completion, ms * std.time.ns_per_ms, ); } while (self.count < count) try self.io.tick(); try self.io.tick(); try testing.expectEqual(@as(u32, count), self.count); try testing.expectApproxEqAbs( @as(f64, ms), @intToFloat(f64, self.stop_time - start_time), margin, ); } fn timeout_callback( self: *Context, completion: *IO.Completion, result: IO.TimeoutError!void, ) void { result catch @panic("timeout error"); if (self.stop_time == 0) self.stop_time = std.time.milliTimestamp(); self.count += 1; } }.run_test(); } test "submission queue full" { const testing = std.testing; const ms = 20; const count = 10; try struct { const Context = @This(); io: IO, count: u32 = 0, fn run_test() !void { var self: Context = .{ .io = try IO.init(1, 0) }; defer self.io.deinit(); var completions: [count]IO.Completion = undefined; for (completions) |*completion| { self.io.timeout( *Context, &self, timeout_callback, completion, ms * std.time.ns_per_ms, ); } while (self.count < count) try self.io.tick(); try self.io.tick(); try testing.expectEqual(@as(u32, count), self.count); } fn timeout_callback( self: *Context, completion: *IO.Completion, result: IO.TimeoutError!void, ) void { result catch @panic("timeout error"); self.count += 1; } }.run_test(); }
src/io.zig
const win32 = @import("win32.zig"); const WINAPI = @import("std").os.windows.WINAPI; const BOOL = win32.foundation.BOOL; const CHAR = win32.foundation.CHAR; const DWORD = win32.foundation.DWORD; const FLOAT = win32.foundation.FLOAT; const HANDLE = win32.foundation.HANDLE; const HDC = win32.graphics.gdi.HDC; const HGLRC = win32.graphics.open_gl.HGLRC; const INT = win32.foundation.INT; const INT32 = win32.foundation.INT32; const INT64 = win32.foundation.INT64; const LPVOID = win32.foundation.LPVOID; const RECT = win32.foundation.RECT; const UINT = c_uint; const USHORT = win32.foundation.USHORT; const VOID = win32.foundation.VOID; pub const ERROR_INCOMPATIBLE_AFFINITY_MASKS_NV = 8400; pub const ERROR_INCOMPATIBLE_DEVICE_CONTEXTS_ARB = 8276; pub const ERROR_INVALID_PIXEL_TYPE_ARB = 8259; pub const ERROR_INVALID_PIXEL_TYPE_EXT = 8259; pub const ERROR_INVALID_PROFILE_ARB = 8342; pub const ERROR_INVALID_VERSION_ARB = 8341; pub const ERROR_MISSING_AFFINITY_MASK_NV = 8401; pub const GL_NO_ERROR = 0; pub const GL_INVALID_ENUM = 1280; pub const GL_INVALID_VALUE = 1281; pub const GL_INVALID_OPERATION = 1282; pub const GL_STACK_OVERFLOW = 1283; pub const GL_STACK_UNDERFLOW = 1284; pub const GL_OUT_OF_MEMORY = 1285; pub const GL_2D = 1536; pub const GL_2_BYTES = 5127; pub const GL_3D = 1537; pub const GL_3D_COLOR = 1538; pub const GL_3D_COLOR_TEXTURE = 1539; pub const GL_3_BYTES = 5128; pub const GL_4D_COLOR_TEXTURE = 1540; pub const GL_4_BYTES = 5129; pub const GL_ACCUM = 256; pub const GL_ACCUM_ALPHA_BITS = 3419; pub const GL_ACCUM_BLUE_BITS = 3418; pub const GL_ACCUM_BUFFER_BIT = 512; pub const GL_ACCUM_CLEAR_VALUE = 2944; pub const GL_ACCUM_GREEN_BITS = 3417; pub const GL_ACCUM_RED_BITS = 3416; pub const GL_ADD = 260; pub const GL_ALL_ATTRIB_BITS = 1048575; pub const GL_ALPHA = 6406; pub const GL_ALPHA12 = 32829; pub const GL_ALPHA16 = 32830; pub const GL_ALPHA4 = 32827; pub const GL_ALPHA8 = 32828; pub const GL_ALPHA_BIAS = 3357; pub const GL_ALPHA_BITS = 3413; pub const GL_ALPHA_SCALE = 3356; pub const GL_ALPHA_TEST = 3008; pub const GL_ALPHA_TEST_FUNC = 3009; pub const GL_ALPHA_TEST_REF = 3010; pub const GL_ALWAYS = 519; pub const GL_AMBIENT = 4608; pub const GL_AMBIENT_AND_DIFFUSE = 5634; pub const GL_AND = 5377; pub const GL_AND_INVERTED = 5380; pub const GL_AND_REVERSE = 5378; pub const GL_ATTRIB_STACK_DEPTH = 2992; pub const GL_AUTO_NORMAL = 3456; pub const GL_AUX0 = 1033; pub const GL_AUX1 = 1034; pub const GL_AUX2 = 1035; pub const GL_AUX3 = 1036; pub const GL_AUX_BUFFERS = 3072; pub const GL_BACK = 1029; pub const GL_BACK_LEFT = 1026; pub const GL_BACK_RIGHT = 1027; pub const GL_BGRA_EXT = 32993; pub const GL_BGR_EXT = 32992; pub const GL_BITMAP = 6656; pub const GL_BITMAP_TOKEN = <PASSWORD>; pub const GL_BLEND = 3042; pub const GL_BLEND_DST = 3040; pub const GL_BLEND_SRC = 3041; pub const GL_BLUE = 6405; pub const GL_BLUE_BIAS = 3355; pub const GL_BLUE_BITS = 3412; pub const GL_BLUE_SCALE = 3354; pub const GL_BYTE = 5120; pub const GL_C3F_V3F = 10788; pub const GL_C4F_N3F_V3F = 10790; pub const GL_C4UB_V2F = 10786; pub const GL_C4UB_V3F = 10787; pub const GL_CCW = 2305; pub const GL_CLAMP = 10496; pub const GL_CLEAR = 5376; pub const GL_CLIENT_ALL_ATTRIB_BITS = 4294967295; pub const GL_CLIENT_ATTRIB_STACK_DEPTH = 2993; pub const GL_CLIENT_PIXEL_STORE_BIT = 1; pub const GL_CLIENT_VERTEX_ARRAY_BIT = 2; pub const GL_CLIP_PLANE0 = 12288; pub const GL_CLIP_PLANE1 = 12289; pub const GL_CLIP_PLANE2 = 12290; pub const GL_CLIP_PLANE3 = 12291; pub const GL_CLIP_PLANE4 = 12292; pub const GL_CLIP_PLANE5 = 12293; pub const GL_COEFF = 2560; pub const GL_COLOR = 6144; pub const GL_COLOR_ARRAY = 32886; pub const GL_COLOR_ARRAY_COUNT_EXT = 32900; pub const GL_COLOR_ARRAY_EXT = 32886; pub const GL_COLOR_ARRAY_POINTER = 32912; pub const GL_COLOR_ARRAY_POINTER_EXT = 32912; pub const GL_COLOR_ARRAY_SIZE = 32897; pub const GL_COLOR_ARRAY_SIZE_EXT = 32897; pub const GL_COLOR_ARRAY_STRIDE = 32899; pub const GL_COLOR_ARRAY_STRIDE_EXT = 32899; pub const GL_COLOR_ARRAY_TYPE = 32898; pub const GL_COLOR_ARRAY_TYPE_EXT = 32898; pub const GL_COLOR_BUFFER_BIT = 16384; pub const GL_COLOR_CLEAR_VALUE = 3106; pub const GL_COLOR_INDEX = 6400; pub const GL_COLOR_INDEX12_EXT = 32998; pub const GL_COLOR_INDEX16_EXT = 32999; pub const GL_COLOR_INDEX1_EXT = 32994; pub const GL_COLOR_INDEX2_EXT = 32995; pub const GL_COLOR_INDEX4_EXT = 32996; pub const GL_COLOR_INDEX8_EXT = 32997; pub const GL_COLOR_INDEXES = 5635; pub const GL_COLOR_LOGIC_OP = 3058; pub const GL_COLOR_MATERIAL = 2903; pub const GL_COLOR_MATERIAL_FACE = 2901; pub const GL_COLOR_MATERIAL_PARAMETER = 2902; pub const GL_COLOR_TABLE_ALPHA_SIZE_EXT = 32989; pub const GL_COLOR_TABLE_BLUE_SIZE_EXT = 32988; pub const GL_COLOR_TABLE_FORMAT_EXT = 32984; pub const GL_COLOR_TABLE_GREEN_SIZE_EXT = 32987; pub const GL_COLOR_TABLE_INTENSITY_SIZE_EXT = 32991; pub const GL_COLOR_TABLE_LUMINANCE_SIZE_EXT = 32990; pub const GL_COLOR_TABLE_RED_SIZE_EXT = 32986; pub const GL_COLOR_TABLE_WIDTH_EXT = 32985; pub const GL_COLOR_WRITEMASK = 3107; pub const GL_COMPILE = 4864; pub const GL_COMPILE_AND_EXECUTE = 4865; pub const GL_CONSTANT_ATTENUATION = 4615; pub const GL_COPY = 5379; pub const GL_COPY_INVERTED = 5388; pub const GL_COPY_PIXEL_TOKEN = 1798; pub const GL_CULL_FACE = 2884; pub const GL_CULL_FACE_MODE = 2885; pub const GL_CURRENT_BIT = 1; pub const GL_CURRENT_COLOR = 2816; pub const GL_CURRENT_INDEX = 2817; pub const GL_CURRENT_NORMAL = 2818; pub const GL_CURRENT_RASTER_COLOR = 2820; pub const GL_CURRENT_RASTER_DISTANCE = 2825; pub const GL_CURRENT_RASTER_INDEX = 2821; pub const GL_CURRENT_RASTER_POSITION = 2823; pub const GL_CURRENT_RASTER_POSITION_VALID = 2824; pub const GL_CURRENT_RASTER_TEXTURE_COORDS = 2822; pub const GL_CURRENT_TEXTURE_COORDS = 2819; pub const GL_CW = 2304; pub const GL_DECAL = 8449; pub const GL_DECR = 7683; pub const GL_DEPTH = 6145; pub const GL_DEPTH_BIAS = 3359; pub const GL_DEPTH_BITS = 3414; pub const GL_DEPTH_BUFFER_BIT = 256; pub const GL_DEPTH_CLEAR_VALUE = 2931; pub const GL_DEPTH_COMPONENT = 6402; pub const GL_DEPTH_FUNC = 2932; pub const GL_DEPTH_RANGE = 2928; pub const GL_DEPTH_SCALE = 3358; pub const GL_DEPTH_TEST = 2929; pub const GL_DEPTH_WRITEMASK = 2930; pub const GL_DIFFUSE = 4609; pub const GL_DITHER = 3024; pub const GL_DOMAIN = 2562; pub const GL_DONT_CARE = 4352; pub const GL_DOUBLE = 5130; pub const GL_DOUBLEBUFFER = 3122; pub const GL_DOUBLE_EXT = GL_DOUBLE; pub const GL_DRAW_BUFFER = 3073; pub const GL_DRAW_PIXEL_TOKEN = 1797; pub const GL_DST_ALPHA = 772; pub const GL_DST_COLOR = 774; pub const GL_EDGE_FLAG = 2883; pub const GL_EDGE_FLAG_ARRAY = 32889; pub const GL_EDGE_FLAG_ARRAY_COUNT_EXT = 32909; pub const GL_EDGE_FLAG_ARRAY_EXT = 32889; pub const GL_EDGE_FLAG_ARRAY_POINTER = 32915; pub const GL_EDGE_FLAG_ARRAY_POINTER_EXT = 32915; pub const GL_EDGE_FLAG_ARRAY_STRIDE = 32908; pub const GL_EDGE_FLAG_ARRAY_STRIDE_EXT = 32908; pub const GL_EMISSION = 5632; pub const GL_ENABLE_BIT = 8192; pub const GL_EQUAL = 514; pub const GL_EQUIV = 5385; pub const GL_EVAL_BIT = 65536; pub const GL_EXP = 2048; pub const GL_EXP2 = 2049; pub const GL_EXTENSIONS = 7939; pub const GL_EXT_bgra = 1; pub const GL_EXT_paletted_texture = 1; pub const GL_EXT_vertex_array = 1; pub const GL_EYE_LINEAR = 9216; pub const GL_EYE_PLANE = 9474; pub const GL_FALSE = 0; pub const GL_FASTEST = 4353; pub const GL_FEEDBACK = 7169; pub const GL_FEEDBACK_BUFFER_POINTER = 3568; pub const GL_FEEDBACK_BUFFER_SIZE = 3569; pub const GL_FEEDBACK_BUFFER_TYPE = 3570; pub const GL_FILL = 6914; pub const GL_FLAT = 7424; pub const GL_FLOAT = 5126; pub const GL_FOG = 2912; pub const GL_FOG_BIT = 128; pub const GL_FOG_COLOR = 2918; pub const GL_FOG_DENSITY = 2914; pub const GL_FOG_END = 2916; pub const GL_FOG_HINT = 3156; pub const GL_FOG_INDEX = 2913; pub const GL_FOG_MODE = 2917; pub const GL_FOG_SPECULAR_TEXTURE_WIN = 33004; pub const GL_FOG_START = 2915; pub const GL_FRONT = 1028; pub const GL_FRONT_AND_BACK = 1032; pub const GL_FRONT_FACE = 2886; pub const GL_FRONT_LEFT = 1024; pub const GL_FRONT_RIGHT = 1025; pub const GL_GEQUAL = 518; pub const GL_GREATER = 516; pub const GL_GREEN = 6404; pub const GL_GREEN_BIAS = 3353; pub const GL_GREEN_BITS = 3411; pub const GL_GREEN_SCALE = 3352; pub const GL_HINT_BIT = 32768; pub const GL_INCR = 7682; pub const GL_INDEX_ARRAY = 32887; pub const GL_INDEX_ARRAY_COUNT_EXT = 32903; pub const GL_INDEX_ARRAY_EXT = 32887; pub const GL_INDEX_ARRAY_POINTER = 32913; pub const GL_INDEX_ARRAY_POINTER_EXT = 32913; pub const GL_INDEX_ARRAY_STRIDE = 32902; pub const GL_INDEX_ARRAY_STRIDE_EXT = 32902; pub const GL_INDEX_ARRAY_TYPE = 32901; pub const GL_INDEX_ARRAY_TYPE_EXT = 32901; pub const GL_INDEX_BITS = 3409; pub const GL_INDEX_CLEAR_VALUE = 3104; pub const GL_INDEX_LOGIC_OP = 3057; pub const GL_INDEX_MODE = 3120; pub const GL_INDEX_OFFSET = 3347; pub const GL_INDEX_SHIFT = 3346; pub const GL_INDEX_WRITEMASK = 3105; pub const GL_INT = 5124; pub const GL_INTENSITY = 32841; pub const GL_INTENSITY12 = 32844; pub const GL_INTENSITY16 = 32845; pub const GL_INTENSITY4 = 32842; pub const GL_INTENSITY8 = 32843; pub const GL_INVERT = 5386; pub const GL_KEEP = 7680; pub const GL_LEFT = 1030; pub const GL_LEQUAL = 515; pub const GL_LESS = 513; pub const GL_LIGHT0 = 16384; pub const GL_LIGHT1 = 16385; pub const GL_LIGHT2 = 16386; pub const GL_LIGHT3 = 16387; pub const GL_LIGHT4 = 16388; pub const GL_LIGHT5 = 16389; pub const GL_LIGHT6 = 16390; pub const GL_LIGHT7 = 16391; pub const GL_LIGHTING = 2896; pub const GL_LIGHTING_BIT = 64; pub const GL_LIGHT_MODEL_AMBIENT = 2899; pub const GL_LIGHT_MODEL_LOCAL_VIEWER = 2897; pub const GL_LIGHT_MODEL_TWO_SIDE = 2898; pub const GL_LINE = 6913; pub const GL_LINEAR = 9729; pub const GL_LINEAR_ATTENUATION = 4616; pub const GL_LINEAR_MIPMAP_LINEAR = 9987; pub const GL_LINEAR_MIPMAP_NEAREST = 9985; pub const GL_LINES = 1; pub const GL_LINE_BIT = 4; pub const GL_LINE_LOOP = 2; pub const GL_LINE_RESET_TOKEN = 1799; pub const GL_LINE_SMOOTH = 2848; pub const GL_LINE_SMOOTH_HINT = 3154; pub const GL_LINE_STIPPLE = 2852; pub const GL_LINE_STIPPLE_PATTERN = 2853; pub const GL_LINE_STIPPLE_REPEAT = 2854; pub const GL_LINE_STRIP = 3; pub const GL_LINE_TOKEN = 1794; pub const GL_LINE_WIDTH = 2849; pub const GL_LINE_WIDTH_GRANULARITY = 2851; pub const GL_LINE_WIDTH_RANGE = 2850; pub const GL_LIST_BASE = 2866; pub const GL_LIST_BIT = 131072; pub const GL_LIST_INDEX = 2867; pub const GL_LIST_MODE = 2864; pub const GL_LOAD = 257; pub const GL_LOGIC_OP = GL_INDEX_LOGIC_OP; pub const GL_LOGIC_OP_MODE = 3056; pub const GL_LUMINANCE = 6409; pub const GL_LUMINANCE12 = 32833; pub const GL_LUMINANCE12_ALPHA12 = 32839; pub const GL_LUMINANCE12_ALPHA4 = 32838; pub const GL_LUMINANCE16 = 32834; pub const GL_LUMINANCE16_ALPHA16 = 32840; pub const GL_LUMINANCE4 = 32831; pub const GL_LUMINANCE4_ALPHA4 = 32835; pub const GL_LUMINANCE6_ALPHA2 = 32836; pub const GL_LUMINANCE8 = 32832; pub const GL_LUMINANCE8_ALPHA8 = 32837; pub const GL_LUMINANCE_ALPHA = 6410; pub const GL_MAP1_COLOR_4 = 3472; pub const GL_MAP1_GRID_DOMAIN = 3536; pub const GL_MAP1_GRID_SEGMENTS = 3537; pub const GL_MAP1_INDEX = 3473; pub const GL_MAP1_NORMAL = 3474; pub const GL_MAP1_TEXTURE_COORD_1 = 3475; pub const GL_MAP1_TEXTURE_COORD_2 = 3476; pub const GL_MAP1_TEXTURE_COORD_3 = 3477; pub const GL_MAP1_TEXTURE_COORD_4 = 3478; pub const GL_MAP1_VERTEX_3 = 3479; pub const GL_MAP1_VERTEX_4 = 3480; pub const GL_MAP2_COLOR_4 = 3504; pub const GL_MAP2_GRID_DOMAIN = 3538; pub const GL_MAP2_GRID_SEGMENTS = 3539; pub const GL_MAP2_INDEX = 3505; pub const GL_MAP2_NORMAL = 3506; pub const GL_MAP2_TEXTURE_COORD_1 = 3507; pub const GL_MAP2_TEXTURE_COORD_2 = 3508; pub const GL_MAP2_TEXTURE_COORD_3 = 3509; pub const GL_MAP2_TEXTURE_COORD_4 = 3510; pub const GL_MAP2_VERTEX_3 = 3511; pub const GL_MAP2_VERTEX_4 = 3512; pub const GL_MAP_COLOR = 3344; pub const GL_MAP_STENCIL = 3345; pub const GL_MATRIX_MODE = 2976; pub const GL_MAX_ATTRIB_STACK_DEPTH = 3381; pub const GL_MAX_CLIENT_ATTRIB_STACK_DEPTH = 3387; pub const GL_MAX_CLIP_PLANES = 3378; pub const GL_MAX_ELEMENTS_INDICES_WIN = 33001; pub const GL_MAX_ELEMENTS_VERTICES_WIN = 33000; pub const GL_MAX_EVAL_ORDER = 3376; pub const GL_MAX_LIGHTS = 3377; pub const GL_MAX_LIST_NESTING = 2865; pub const GL_MAX_MODELVIEW_STACK_DEPTH = 3382; pub const GL_MAX_NAME_STACK_DEPTH = 3383; pub const GL_MAX_PIXEL_MAP_TABLE = 3380; pub const GL_MAX_PROJECTION_STACK_DEPTH = 3384; pub const GL_MAX_TEXTURE_SIZE = 3379; pub const GL_MAX_TEXTURE_STACK_DEPTH = 3385; pub const GL_MAX_VIEWPORT_DIMS = 3386; pub const GL_MODELVIEW = 5888; pub const GL_MODELVIEW_MATRIX = 2982; pub const GL_MODELVIEW_STACK_DEPTH = 2979; pub const GL_MODULATE = 8448; pub const GL_MULT = 259; pub const GL_N3F_V3F = 10789; pub const GL_NAME_STACK_DEPTH = 3440; pub const GL_NAND = 5390; pub const GL_NEAREST = 9728; pub const GL_NEAREST_MIPMAP_LINEAR = 9986; pub const GL_NEAREST_MIPMAP_NEAREST = 9984; pub const GL_NEVER = 512; pub const GL_NICEST = 4354; pub const GL_NONE = 0; pub const GL_NOOP = 5381; pub const GL_NOR = 5384; pub const GL_NORMALIZE = 2977; pub const GL_NORMAL_ARRAY = 32885; pub const GL_NORMAL_ARRAY_COUNT_EXT = 32896; pub const GL_NORMAL_ARRAY_EXT = 32885; pub const GL_NORMAL_ARRAY_POINTER = 32911; pub const GL_NORMAL_ARRAY_POINTER_EXT = 32911; pub const GL_NORMAL_ARRAY_STRIDE = 32895; pub const GL_NORMAL_ARRAY_STRIDE_EXT = 32895; pub const GL_NORMAL_ARRAY_TYPE = 32894; pub const GL_NORMAL_ARRAY_TYPE_EXT = 32894; pub const GL_NOTEQUAL = 517; pub const GL_OBJECT_LINEAR = 9217; pub const GL_OBJECT_PLANE = 9473; pub const GL_ONE = 1; pub const GL_ONE_MINUS_DST_ALPHA = 773; pub const GL_ONE_MINUS_DST_COLOR = 775; pub const GL_ONE_MINUS_SRC_ALPHA = 771; pub const GL_ONE_MINUS_SRC_COLOR = 769; pub const GL_OR = 5383; pub const GL_ORDER = 2561; pub const GL_OR_INVERTED = 5389; pub const GL_OR_REVERSE = 5387; pub const GL_PACK_ALIGNMENT = 3333; pub const GL_PACK_LSB_FIRST = 3329; pub const GL_PACK_ROW_LENGTH = 3330; pub const GL_PACK_SKIP_PIXELS = 3332; pub const GL_PACK_SKIP_ROWS = 3331; pub const GL_PACK_SWAP_BYTES = 3328; pub const GL_PASS_THROUGH_TOKEN = 1792; pub const GL_PERSPECTIVE_CORRECTION_HINT = 3152; pub const GL_PHONG_HINT_WIN = 33003; pub const GL_PHONG_WIN = 33002; pub const GL_PIXEL_MAP_A_TO_A = 3193; pub const GL_PIXEL_MAP_A_TO_A_SIZE = 3257; pub const GL_PIXEL_MAP_B_TO_B = 3192; pub const GL_PIXEL_MAP_B_TO_B_SIZE = 3256; pub const GL_PIXEL_MAP_G_TO_G = 3191; pub const GL_PIXEL_MAP_G_TO_G_SIZE = 3255; pub const GL_PIXEL_MAP_I_TO_A = 3189; pub const GL_PIXEL_MAP_I_TO_A_SIZE = 3253; pub const GL_PIXEL_MAP_I_TO_B = 3188; pub const GL_PIXEL_MAP_I_TO_B_SIZE = 3252; pub const GL_PIXEL_MAP_I_TO_G = 3187; pub const GL_PIXEL_MAP_I_TO_G_SIZE = 3251; pub const GL_PIXEL_MAP_I_TO_I = 3184; pub const GL_PIXEL_MAP_I_TO_I_SIZE = 3248; pub const GL_PIXEL_MAP_I_TO_R = 3186; pub const GL_PIXEL_MAP_I_TO_R_SIZE = 3250; pub const GL_PIXEL_MAP_R_TO_R = 3190; pub const GL_PIXEL_MAP_R_TO_R_SIZE = 3254; pub const GL_PIXEL_MAP_S_TO_S = 3185; pub const GL_PIXEL_MAP_S_TO_S_SIZE = 3249; pub const GL_PIXEL_MODE_BIT = 32; pub const GL_POINT = 6912; pub const GL_POINTS = 0; pub const GL_POINT_BIT = 2; pub const GL_POINT_SIZE = 2833; pub const GL_POINT_SIZE_GRANULARITY = 2835; pub const GL_POINT_SIZE_RANGE = 2834; pub const GL_POINT_SMOOTH = 2832; pub const GL_POINT_SMOOTH_HINT = 3153; pub const GL_POINT_TOKEN = 1<PASSWORD>; pub const GL_POLYGON = 9; pub const GL_POLYGON_BIT = 8; pub const GL_POLYGON_MODE = 2880; pub const GL_POLYGON_OFFSET_FACTOR = 32824; pub const GL_POLYGON_OFFSET_FILL = 32823; pub const GL_POLYGON_OFFSET_LINE = 10754; pub const GL_POLYGON_OFFSET_POINT = 10753; pub const GL_POLYGON_OFFSET_UNITS = 10752; pub const GL_POLYGON_SMOOTH = 2881; pub const GL_POLYGON_SMOOTH_HINT = 3155; pub const GL_POLYGON_STIPPLE = 2882; pub const GL_POLYGON_STIPPLE_BIT = 16; pub const GL_POLYGON_TOKEN = <PASSWORD>; pub const GL_POSITION = 4611; pub const GL_PROJECTION = 5889; pub const GL_PROJECTION_MATRIX = 2983; pub const GL_PROJECTION_STACK_DEPTH = 2980; pub const GL_PROXY_TEXTURE_1D = 32867; pub const GL_PROXY_TEXTURE_2D = 32868; pub const GL_Q = 8195; pub const GL_QUADRATIC_ATTENUATION = 4617; pub const GL_QUADS = 7; pub const GL_QUAD_STRIP = 8; pub const GL_R = 8194; pub const GL_R3_G3_B2 = 10768; pub const GL_READ_BUFFER = 3074; pub const GL_RED = 6403; pub const GL_RED_BIAS = 3349; pub const GL_RED_BITS = 3410; pub const GL_RED_SCALE = 3348; pub const GL_RENDER = 7168; pub const GL_RENDERER = 7937; pub const GL_RENDER_MODE = 3136; pub const GL_REPEAT = 10497; pub const GL_REPLACE = 7681; pub const GL_RETURN = 258; pub const GL_RGB = 6407; pub const GL_RGB10 = 32850; pub const GL_RGB10_A2 = 32857; pub const GL_RGB12 = 32851; pub const GL_RGB16 = 32852; pub const GL_RGB4 = 32847; pub const GL_RGB5 = 32848; pub const GL_RGB5_A1 = 32855; pub const GL_RGB8 = 32849; pub const GL_RGBA = 6408; pub const GL_RGBA12 = 32858; pub const GL_RGBA16 = 32859; pub const GL_RGBA2 = 32853; pub const GL_RGBA4 = 32854; pub const GL_RGBA8 = 32856; pub const GL_RGBA_MODE = 3121; pub const GL_RIGHT = 1031; pub const GL_S = 8192; pub const GL_SCISSOR_BIT = 524288; pub const GL_SCISSOR_BOX = 3088; pub const GL_SCISSOR_TEST = 3089; pub const GL_SELECT = 7170; pub const GL_SELECTION_BUFFER_POINTER = 3571; pub const GL_SELECTION_BUFFER_SIZE = 3572; pub const GL_SET = 5391; pub const GL_SHADE_MODEL = 2900; pub const GL_SHININESS = 5633; pub const GL_SHORT = 5122; pub const GL_SMOOTH = 7425; pub const GL_SPECULAR = 4610; pub const GL_SPHERE_MAP = 9218; pub const GL_SPOT_CUTOFF = 4614; pub const GL_SPOT_DIRECTION = 4612; pub const GL_SPOT_EXPONENT = 4613; pub const GL_SRC_ALPHA = 770; pub const GL_SRC_ALPHA_SATURATE = 776; pub const GL_SRC_COLOR = 768; pub const GL_STENCIL = 6146; pub const GL_STENCIL_BITS = 3415; pub const GL_STENCIL_BUFFER_BIT = 1024; pub const GL_STENCIL_CLEAR_VALUE = 2961; pub const GL_STENCIL_FAIL = 2964; pub const GL_STENCIL_FUNC = 2962; pub const GL_STENCIL_INDEX = 6401; pub const GL_STENCIL_PASS_DEPTH_FAIL = 2965; pub const GL_STENCIL_PASS_DEPTH_PASS = 2966; pub const GL_STENCIL_REF = 2967; pub const GL_STENCIL_TEST = 2960; pub const GL_STENCIL_VALUE_MASK = 2963; pub const GL_STENCIL_WRITEMASK = 2968; pub const GL_STEREO = 3123; pub const GL_SUBPIXEL_BITS = 3408; pub const GL_T = 8193; pub const GL_T2F_C3F_V3F = 10794; pub const GL_T2F_C4F_N3F_V3F = 10796; pub const GL_T2F_C4UB_V3F = 10793; pub const GL_T2F_N3F_V3F = 10795; pub const GL_T2F_V3F = 10791; pub const GL_T4F_C4F_N3F_V4F = 10797; pub const GL_T4F_V4F = 10792; pub const GL_TEXTURE = 5890; pub const GL_TEXTURE_1D = 3552; pub const GL_TEXTURE_2D = 3553; pub const GL_TEXTURE_ALPHA_SIZE = 32863; pub const GL_TEXTURE_BINDING_1D = 32872; pub const GL_TEXTURE_BINDING_2D = 32873; pub const GL_TEXTURE_BIT = 262144; pub const GL_TEXTURE_BLUE_SIZE = 32862; pub const GL_TEXTURE_BORDER = 4101; pub const GL_TEXTURE_BORDER_COLOR = 4100; pub const GL_TEXTURE_COMPONENTS = GL_TEXTURE_INTERNAL_FORMAT; pub const GL_TEXTURE_COORD_ARRAY = 32888; pub const GL_TEXTURE_COORD_ARRAY_COUNT_EXT = 32907; pub const GL_TEXTURE_COORD_ARRAY_EXT = 32888; pub const GL_TEXTURE_COORD_ARRAY_POINTER = 32914; pub const GL_TEXTURE_COORD_ARRAY_POINTER_EXT = 32914; pub const GL_TEXTURE_COORD_ARRAY_SIZE = 32904; pub const GL_TEXTURE_COORD_ARRAY_SIZE_EXT = 32904; pub const GL_TEXTURE_COORD_ARRAY_STRIDE = 32906; pub const GL_TEXTURE_COORD_ARRAY_STRIDE_EXT = 32906; pub const GL_TEXTURE_COORD_ARRAY_TYPE = 32905; pub const GL_TEXTURE_COORD_ARRAY_TYPE_EXT = 32905; pub const GL_TEXTURE_ENV = 8960; pub const GL_TEXTURE_ENV_COLOR = 8705; pub const GL_TEXTURE_ENV_MODE = 8704; pub const GL_TEXTURE_GEN_MODE = 9472; pub const GL_TEXTURE_GEN_Q = 3171; pub const GL_TEXTURE_GEN_R = 3170; pub const GL_TEXTURE_GEN_S = 3168; pub const GL_TEXTURE_GEN_T = 3169; pub const GL_TEXTURE_GREEN_SIZE = 32861; pub const GL_TEXTURE_HEIGHT = 4097; pub const GL_TEXTURE_INTENSITY_SIZE = 32865; pub const GL_TEXTURE_INTERNAL_FORMAT = 4099; pub const GL_TEXTURE_LUMINANCE_SIZE = 32864; pub const GL_TEXTURE_MAG_FILTER = 10240; pub const GL_TEXTURE_MATRIX = 2984; pub const GL_TEXTURE_MIN_FILTER = 10241; pub const GL_TEXTURE_PRIORITY = 32870; pub const GL_TEXTURE_RED_SIZE = 32860; pub const GL_TEXTURE_RESIDENT = 32871; pub const GL_TEXTURE_STACK_DEPTH = 2981; pub const GL_TEXTURE_WIDTH = 4096; pub const GL_TEXTURE_WRAP_S = 10242; pub const GL_TEXTURE_WRAP_T = 10243; pub const GL_TRANSFORM_BIT = 4096; pub const GL_TRIANGLES = 4; pub const GL_TRIANGLE_FAN = 6; pub const GL_TRIANGLE_STRIP = 5; pub const GL_TRUE = 1; pub const GL_UNPACK_ALIGNMENT = 3317; pub const GL_UNPACK_LSB_FIRST = 3313; pub const GL_UNPACK_ROW_LENGTH = 3314; pub const GL_UNPACK_SKIP_PIXELS = 3316; pub const GL_UNPACK_SKIP_ROWS = 3315; pub const GL_UNPACK_SWAP_BYTES = 3312; pub const GL_UNSIGNED_BYTE = 5121; pub const GL_UNSIGNED_INT = 5125; pub const GL_UNSIGNED_SHORT = 5123; pub const GL_V2F = 10784; pub const GL_V3F = 10785; pub const GL_VENDOR = 7936; pub const GL_VERSION = 7938; pub const GL_VERSION_1_1 = 1; pub const GL_VERTEX_ARRAY = 32884; pub const GL_VERTEX_ARRAY_COUNT_EXT = 32893; pub const GL_VERTEX_ARRAY_EXT = 32884; pub const GL_VERTEX_ARRAY_POINTER = 32910; pub const GL_VERTEX_ARRAY_POINTER_EXT = 32910; pub const GL_VERTEX_ARRAY_SIZE = 32890; pub const GL_VERTEX_ARRAY_SIZE_EXT = 32890; pub const GL_VERTEX_ARRAY_STRIDE = 32892; pub const GL_VERTEX_ARRAY_STRIDE_EXT = 32892; pub const GL_VERTEX_ARRAY_TYPE = 32891; pub const GL_VERTEX_ARRAY_TYPE_EXT = 32891; pub const GL_VIEWPORT = 2978; pub const GL_VIEWPORT_BIT = 2048; pub const GL_WIN_draw_range_elements = 1; pub const GL_WIN_swap_hint = 1; pub const GL_XOR = 5382; pub const GL_ZERO = 0; pub const GL_ZOOM_X = 3350; pub const GL_ZOOM_Y = 3351; pub const WGL_3DFX_multisample = 1; pub const WGL_3DL_stereo_control = 1; pub const WGL_ACCELERATION_ARB = 8195; pub const WGL_ACCELERATION_EXT = 8195; pub const WGL_ACCESS_READ_ONLY_NV = 0; pub const WGL_ACCESS_READ_WRITE_NV = 1; pub const WGL_ACCESS_WRITE_DISCARD_NV = 2; pub const WGL_ACCUM_ALPHA_BITS_ARB = 8225; pub const WGL_ACCUM_ALPHA_BITS_EXT = 8225; pub const WGL_ACCUM_BITS_ARB = 8221; pub const WGL_ACCUM_BITS_EXT = 8221; pub const WGL_ACCUM_BLUE_BITS_ARB = 8224; pub const WGL_ACCUM_BLUE_BITS_EXT = 8224; pub const WGL_ACCUM_GREEN_BITS_ARB = 8223; pub const WGL_ACCUM_GREEN_BITS_EXT = 8223; pub const WGL_ACCUM_RED_BITS_ARB = 8222; pub const WGL_ACCUM_RED_BITS_EXT = 8222; pub const WGL_ALPHA_BITS_ARB = 8219; pub const WGL_ALPHA_BITS_EXT = 8219; pub const WGL_ALPHA_SHIFT_ARB = 8220; pub const WGL_ALPHA_SHIFT_EXT = 8220; pub const WGL_AMD_gpu_association = 1; pub const WGL_ARB_buffer_region = 1; pub const WGL_ARB_context_flush_control = 1; pub const WGL_ARB_create_context = 1; pub const WGL_ARB_create_context_no_error = 1; pub const WGL_ARB_create_context_profile = 1; pub const WGL_ARB_create_context_robustness = 1; pub const WGL_ARB_extensions_string = 1; pub const WGL_ARB_framebuffer_sRGB = 1; pub const WGL_ARB_make_current_read = 1; pub const WGL_ARB_multisample = 1; pub const WGL_ARB_pbuffer = 1; pub const WGL_ARB_pixel_format = 1; pub const WGL_ARB_pixel_format_float = 1; pub const WGL_ARB_render_texture = 1; pub const WGL_ARB_robustness_application_isolation = 1; pub const WGL_ARB_robustness_share_group_isolation = 1; pub const WGL_ATI_pixel_format_float = 1; pub const WGL_AUX0_ARB = 8327; pub const WGL_AUX1_ARB = 8328; pub const WGL_AUX2_ARB = 8329; pub const WGL_AUX3_ARB = 8330; pub const WGL_AUX4_ARB = 8331; pub const WGL_AUX5_ARB = 8332; pub const WGL_AUX6_ARB = 8333; pub const WGL_AUX7_ARB = 8334; pub const WGL_AUX8_ARB = 8335; pub const WGL_AUX9_ARB = 8336; pub const WGL_AUX_BUFFERS_ARB = 8228; pub const WGL_AUX_BUFFERS_EXT = 8228; pub const WGL_BACK_COLOR_BUFFER_BIT_ARB = 2; pub const WGL_BACK_LEFT_ARB = 8325; pub const WGL_BACK_RIGHT_ARB = 8326; pub const WGL_BIND_TO_TEXTURE_DEPTH_NV = 8355; pub const WGL_BIND_TO_TEXTURE_RECTANGLE_DEPTH_NV = 8356; pub const WGL_BIND_TO_TEXTURE_RECTANGLE_FLOAT_RGBA_NV = 8372; pub const WGL_BIND_TO_TEXTURE_RECTANGLE_FLOAT_RGB_NV = 8371; pub const WGL_BIND_TO_TEXTURE_RECTANGLE_FLOAT_RG_NV = 8370; pub const WGL_BIND_TO_TEXTURE_RECTANGLE_FLOAT_R_NV = 8369; pub const WGL_BIND_TO_TEXTURE_RECTANGLE_RGBA_NV = 8353; pub const WGL_BIND_TO_TEXTURE_RECTANGLE_RGB_NV = 8352; pub const WGL_BIND_TO_TEXTURE_RGBA_ARB = 8305; pub const WGL_BIND_TO_TEXTURE_RGB_ARB = 8304; pub const WGL_BIND_TO_VIDEO_RGBA_NV = 8385; pub const WGL_BIND_TO_VIDEO_RGB_AND_DEPTH_NV = 8386; pub const WGL_BIND_TO_VIDEO_RGB_NV = 8384; pub const WGL_BLUE_BITS_ARB = 8217; pub const WGL_BLUE_BITS_EXT = 8217; pub const WGL_BLUE_SHIFT_ARB = 8218; pub const WGL_BLUE_SHIFT_EXT = 8218; pub const WGL_COLORSPACE_EXT = 12423; pub const WGL_COLORSPACE_LINEAR_EXT = 12426; pub const WGL_COLORSPACE_SRGB_EXT = 12425; pub const WGL_COLOR_BITS_ARB = 8212; pub const WGL_COLOR_BITS_EXT = 8212; pub const WGL_COLOR_SAMPLES_NV = 8377; pub const WGL_CONTEXT_COMPATIBILITY_PROFILE_BIT_ARB = 2; pub const WGL_CONTEXT_CORE_PROFILE_BIT_ARB = 1; pub const WGL_CONTEXT_DEBUG_BIT_ARB = 1; pub const WGL_CONTEXT_ES2_PROFILE_BIT_EXT = 4; pub const WGL_CONTEXT_ES_PROFILE_BIT_EXT = 4; pub const WGL_CONTEXT_FLAGS_ARB = 8340; pub const WGL_CONTEXT_FORWARD_COMPATIBLE_BIT_ARB = 2; pub const WGL_CONTEXT_LAYER_PLANE_ARB = 8339; pub const WGL_CONTEXT_MAJOR_VERSION_ARB = 8337; pub const WGL_CONTEXT_MINOR_VERSION_ARB = 8338; pub const WGL_CONTEXT_OPENGL_NO_ERROR_ARB = 12723; pub const WGL_CONTEXT_PROFILE_MASK_ARB = 37158; pub const WGL_CONTEXT_RELEASE_BEHAVIOR_ARB = 8343; pub const WGL_CONTEXT_RELEASE_BEHAVIOR_FLUSH_ARB = 8344; pub const WGL_CONTEXT_RELEASE_BEHAVIOR_NONE_ARB = 0; pub const WGL_CONTEXT_RESET_ISOLATION_BIT_ARB = 8; pub const WGL_CONTEXT_RESET_NOTIFICATION_STRATEGY_ARB = 33366; pub const WGL_CONTEXT_ROBUST_ACCESS_BIT_ARB = 4; pub const WGL_COVERAGE_SAMPLES_NV = 8258; pub const WGL_CUBE_MAP_FACE_ARB = 8316; pub const WGL_DEPTH_BITS_ARB = 8226; pub const WGL_DEPTH_BITS_EXT = 8226; pub const WGL_DEPTH_BUFFER_BIT_ARB = 4; pub const WGL_DEPTH_COMPONENT_NV = 8359; pub const WGL_DEPTH_FLOAT_EXT = 8256; pub const WGL_DEPTH_TEXTURE_FORMAT_NV = 8357; pub const WGL_DIGITAL_VIDEO_CURSOR_ALPHA_FRAMEBUFFER_I3D = 8272; pub const WGL_DIGITAL_VIDEO_CURSOR_ALPHA_VALUE_I3D = 8273; pub const WGL_DIGITAL_VIDEO_CURSOR_INCLUDED_I3D = 8274; pub const WGL_DIGITAL_VIDEO_GAMMA_CORRECTED_I3D = 8275; pub const WGL_DOUBLE_BUFFER_ARB = 8209; pub const WGL_DOUBLE_BUFFER_EXT = 8209; pub const WGL_DRAW_TO_BITMAP_ARB = 8194; pub const WGL_DRAW_TO_BITMAP_EXT = 8194; pub const WGL_DRAW_TO_PBUFFER_ARB = 8237; pub const WGL_DRAW_TO_PBUFFER_EXT = 8237; pub const WGL_DRAW_TO_WINDOW_ARB = 8193; pub const WGL_DRAW_TO_WINDOW_EXT = 8193; pub const WGL_EXT_colorspace = 1; pub const WGL_EXT_create_context_es2_profile = 1; pub const WGL_EXT_create_context_es_profile = 1; pub const WGL_EXT_depth_float = 1; pub const WGL_EXT_display_color_table = 1; pub const WGL_EXT_extensions_string = 1; pub const WGL_EXT_framebuffer_sRGB = 1; pub const WGL_EXT_make_current_read = 1; pub const WGL_EXT_multisample = 1; pub const WGL_EXT_pbuffer = 1; pub const WGL_EXT_pixel_format = 1; pub const WGL_EXT_pixel_format_packed_float = 1; pub const WGL_EXT_swap_control = 1; pub const WGL_EXT_swap_control_tear = 1; pub const WGL_FLOAT_COMPONENTS_NV = 8368; pub const WGL_FRAMEBUFFER_SRGB_CAPABLE_ARB = 8361; pub const WGL_FRAMEBUFFER_SRGB_CAPABLE_EXT = 8361; pub const WGL_FRONT_COLOR_BUFFER_BIT_ARB = 1; pub const WGL_FRONT_LEFT_ARB = 8323; pub const WGL_FRONT_RIGHT_ARB = 8324; pub const WGL_FULL_ACCELERATION_ARB = 8231; pub const WGL_FULL_ACCELERATION_EXT = 8231; pub const WGL_GAMMA_EXCLUDE_DESKTOP_I3D = 8271; pub const WGL_GAMMA_TABLE_SIZE_I3D = 8270; pub const WGL_GENERIC_ACCELERATION_ARB = 8230; pub const WGL_GENERIC_ACCELERATION_EXT = 8230; pub const WGL_GENLOCK_SOURCE_DIGITAL_FIELD_I3D = 8265; pub const WGL_GENLOCK_SOURCE_DIGITAL_SYNC_I3D = 8264; pub const WGL_GENLOCK_SOURCE_EDGE_BOTH_I3D = 8268; pub const WGL_GENLOCK_SOURCE_EDGE_FALLING_I3D = 8266; pub const WGL_GENLOCK_SOURCE_EDGE_RISING_I3D = 8267; pub const WGL_GENLOCK_SOURCE_EXTERNAL_FIELD_I3D = 8262; pub const WGL_GENLOCK_SOURCE_EXTERNAL_SYNC_I3D = 8261; pub const WGL_GENLOCK_SOURCE_EXTERNAL_TTL_I3D = 8263; pub const WGL_GENLOCK_SOURCE_MULTIVIEW_I3D = 8260; pub const WGL_GPU_CLOCK_AMD = 8612; pub const WGL_GPU_FASTEST_TARGET_GPUS_AMD = 8610; pub const WGL_GPU_NUM_PIPES_AMD = 8613; pub const WGL_GPU_NUM_RB_AMD = 8615; pub const WGL_GPU_NUM_SIMD_AMD = 8614; pub const WGL_GPU_NUM_SPI_AMD = 8616; pub const WGL_GPU_OPENGL_VERSION_STRING_AMD = 7938; pub const WGL_GPU_RAM_AMD = 8611; pub const WGL_GPU_RENDERER_STRING_AMD = 7937; pub const WGL_GPU_VENDOR_AMD = 7936; pub const WGL_GREEN_BITS_ARB = 8215; pub const WGL_GREEN_BITS_EXT = 8215; pub const WGL_GREEN_SHIFT_ARB = 8216; pub const WGL_GREEN_SHIFT_EXT = 8216; pub const WGL_I3D_digital_video_control = 1; pub const WGL_I3D_gamma = 1; pub const WGL_I3D_genlock = 1; pub const WGL_I3D_image_buffer = 1; pub const WGL_I3D_swap_frame_lock = 1; pub const WGL_I3D_swap_frame_usage = 1; pub const WGL_IMAGE_BUFFER_LOCK_I3D = 2; pub const WGL_IMAGE_BUFFER_MIN_ACCESS_I3D = 1; pub const WGL_LOSE_CONTEXT_ON_RESET_ARB = 33362; pub const WGL_MAX_PBUFFER_HEIGHT_ARB = 8240; pub const WGL_MAX_PBUFFER_HEIGHT_EXT = 8240; pub const WGL_MAX_PBUFFER_PIXELS_ARB = 8238; pub const WGL_MAX_PBUFFER_PIXELS_EXT = 8238; pub const WGL_MAX_PBUFFER_WIDTH_ARB = 8239; pub const WGL_MAX_PBUFFER_WIDTH_EXT = 8239; pub const WGL_MIPMAP_LEVEL_ARB = 8315; pub const WGL_MIPMAP_TEXTURE_ARB = 8308; pub const WGL_NEED_PALETTE_ARB = 8196; pub const WGL_NEED_PALETTE_EXT = 8196; pub const WGL_NEED_SYSTEM_PALETTE_ARB = 8197; pub const WGL_NEED_SYSTEM_PALETTE_EXT = 8197; pub const WGL_NO_ACCELERATION_ARB = 8229; pub const WGL_NO_ACCELERATION_EXT = 8229; pub const WGL_NO_RESET_NOTIFICATION_ARB = 33377; pub const WGL_NO_TEXTURE_ARB = 8311; pub const WGL_NUMBER_OVERLAYS_ARB = 8200; pub const WGL_NUMBER_OVERLAYS_EXT = 8200; pub const WGL_NUMBER_PIXEL_FORMATS_ARB = 8192; pub const WGL_NUMBER_PIXEL_FORMATS_EXT = 8192; pub const WGL_NUMBER_UNDERLAYS_ARB = 8201; pub const WGL_NUMBER_UNDERLAYS_EXT = 8201; pub const WGL_NUM_VIDEO_CAPTURE_SLOTS_NV = 8399; pub const WGL_NUM_VIDEO_SLOTS_NV = 8432; pub const WGL_NV_copy_image = 1; pub const WGL_NV_delay_before_swap = 1; pub const WGL_NV_DX_interop = 1; pub const WGL_NV_DX_interop2 = 1; pub const WGL_NV_float_buffer = 1; pub const WGL_NV_gpu_affinity = 1; pub const WGL_NV_multisample_coverage = 1; pub const WGL_NV_present_video = 1; pub const WGL_NV_render_depth_texture = 1; pub const WGL_NV_render_texture_rectangle = 1; pub const WGL_NV_swap_group = 1; pub const WGL_NV_vertex_array_range = 1; pub const WGL_NV_video_capture = 1; pub const WGL_NV_video_output = 1; pub const WGL_OML_sync_control = 1; pub const WGL_OPTIMAL_PBUFFER_HEIGHT_EXT = 8242; pub const WGL_OPTIMAL_PBUFFER_WIDTH_EXT = 8241; pub const WGL_PBUFFER_HEIGHT_ARB = 8245; pub const WGL_PBUFFER_HEIGHT_EXT = 8245; pub const WGL_PBUFFER_LARGEST_ARB = 8243; pub const WGL_PBUFFER_LARGEST_EXT = 8243; pub const WGL_PBUFFER_LOST_ARB = 8246; pub const WGL_PBUFFER_WIDTH_ARB = 8244; pub const WGL_PBUFFER_WIDTH_EXT = 8244; pub const WGL_PIXEL_TYPE_ARB = 8211; pub const WGL_PIXEL_TYPE_EXT = 8211; pub const WGL_RED_BITS_ARB = 8213; pub const WGL_RED_BITS_EXT = 8213; pub const WGL_RED_SHIFT_ARB = 8214; pub const WGL_RED_SHIFT_EXT = 8214; pub const WGL_SAMPLES_3DFX = 8289; pub const WGL_SAMPLES_ARB = 8258; pub const WGL_SAMPLES_EXT = 8258; pub const WGL_SAMPLE_BUFFERS_3DFX = 8288; pub const WGL_SAMPLE_BUFFERS_ARB = 8257; pub const WGL_SAMPLE_BUFFERS_EXT = 8257; pub const WGL_SHARE_ACCUM_ARB = 8206; pub const WGL_SHARE_ACCUM_EXT = 8206; pub const WGL_SHARE_DEPTH_ARB = 8204; pub const WGL_SHARE_DEPTH_EXT = 8204; pub const WGL_SHARE_STENCIL_ARB = 8205; pub const WGL_SHARE_STENCIL_EXT = 8205; pub const WGL_STENCIL_BITS_ARB = 8227; pub const WGL_STENCIL_BITS_EXT = 8227; pub const WGL_STENCIL_BUFFER_BIT_ARB = 8; pub const WGL_STEREO_ARB = 8210; pub const WGL_STEREO_EMITTER_DISABLE_3DL = 8278; pub const WGL_STEREO_EMITTER_ENABLE_3DL = 8277; pub const WGL_STEREO_EXT = 8210; pub const WGL_STEREO_POLARITY_INVERT_3DL = 8280; pub const WGL_STEREO_POLARITY_NORMAL_3DL = 8279; pub const WGL_SUPPORT_GDI_ARB = 8207; pub const WGL_SUPPORT_GDI_EXT = 8207; pub const WGL_SUPPORT_OPENGL_ARB = 8208; pub const WGL_SUPPORT_OPENGL_EXT = 8208; pub const WGL_SWAP_COPY_ARB = 8233; pub const WGL_SWAP_COPY_EXT = 8233; pub const WGL_SWAP_EXCHANGE_ARB = 8232; pub const WGL_SWAP_EXCHANGE_EXT = 8232; pub const WGL_SWAP_LAYER_BUFFERS_ARB = 8198; pub const WGL_SWAP_LAYER_BUFFERS_EXT = 8198; pub const WGL_SWAP_METHOD_ARB = 8199; pub const WGL_SWAP_METHOD_EXT = 8199; pub const WGL_SWAP_UNDEFINED_ARB = 8234; pub const WGL_SWAP_UNDEFINED_EXT = 8234; pub const WGL_TEXTURE_1D_ARB = 8313; pub const WGL_TEXTURE_2D_ARB = 8314; pub const WGL_TEXTURE_CUBE_MAP_ARB = 8312; pub const WGL_TEXTURE_CUBE_MAP_NEGATIVE_X_ARB = 8318; pub const WGL_TEXTURE_CUBE_MAP_NEGATIVE_Y_ARB = 8320; pub const WGL_TEXTURE_CUBE_MAP_NEGATIVE_Z_ARB = 8322; pub const WGL_TEXTURE_CUBE_MAP_POSITIVE_X_ARB = 8317; pub const WGL_TEXTURE_CUBE_MAP_POSITIVE_Y_ARB = 8319; pub const WGL_TEXTURE_CUBE_MAP_POSITIVE_Z_ARB = 8321; pub const WGL_TEXTURE_DEPTH_COMPONENT_NV = 8358; pub const WGL_TEXTURE_FLOAT_RGBA_NV = 8376; pub const WGL_TEXTURE_FLOAT_RGB_NV = 8375; pub const WGL_TEXTURE_FLOAT_RG_NV = 8374; pub const WGL_TEXTURE_FLOAT_R_NV = 8373; pub const WGL_TEXTURE_FORMAT_ARB = 8306; pub const WGL_TEXTURE_RECTANGLE_NV = 8354; pub const WGL_TEXTURE_RGBA_ARB = 8310; pub const WGL_TEXTURE_RGB_ARB = 8309; pub const WGL_TEXTURE_TARGET_ARB = 8307; pub const WGL_TRANSPARENT_ALPHA_VALUE_ARB = 8250; pub const WGL_TRANSPARENT_ARB = 8202; pub const WGL_TRANSPARENT_BLUE_VALUE_ARB = 8249; pub const WGL_TRANSPARENT_EXT = 8202; pub const WGL_TRANSPARENT_GREEN_VALUE_ARB = 8248; pub const WGL_TRANSPARENT_INDEX_VALUE_ARB = 8251; pub const WGL_TRANSPARENT_RED_VALUE_ARB = 8247; pub const WGL_TRANSPARENT_VALUE_EXT = 8203; pub const WGL_TYPE_COLORINDEX_ARB = 8236; pub const WGL_TYPE_COLORINDEX_EXT = 8236; pub const WGL_TYPE_RGBA_ARB = 8235; pub const WGL_TYPE_RGBA_EXT = 8235; pub const WGL_TYPE_RGBA_FLOAT_ARB = 8608; pub const WGL_TYPE_RGBA_FLOAT_ATI = 8608; pub const WGL_TYPE_RGBA_UNSIGNED_FLOAT_EXT = 8360; pub const WGL_UNIQUE_ID_NV = 8398; pub const WGL_VIDEO_OUT_ALPHA_NV = 8388; pub const WGL_VIDEO_OUT_COLOR_AND_ALPHA_NV = 8390; pub const WGL_VIDEO_OUT_COLOR_AND_DEPTH_NV = 8391; pub const WGL_VIDEO_OUT_COLOR_NV = 8387; pub const WGL_VIDEO_OUT_DEPTH_NV = 8389; pub const WGL_VIDEO_OUT_FIELD_1 = 8393; pub const WGL_VIDEO_OUT_FIELD_2 = 8394; pub const WGL_VIDEO_OUT_FRAME = 8392; pub const WGL_VIDEO_OUT_STACKED_FIELDS_1_2 = 8395; pub const WGL_VIDEO_OUT_STACKED_FIELDS_2_1 = 8396; pub const WGL_WGLEXT_VERSION = 20180213; pub const GLbitfield = c_uint; pub const GLboolean = u8; pub const GLbyte = i8; pub const GLclampd = f64; pub const GLclampf = f32; pub const GLdouble = f64; pub const GLenum = c_uint; pub const GLfloat = f32; pub const GLint = c_int; pub const GLshort = c_short; pub const GLsizei = c_int; pub const GLubyte = u8; pub const GLuint = c_uint; pub const GLushort = c_ushort; pub const GLvoid = anyopaque; pub const HGPUNV = ?*opaque {}; pub const HPBUFFERARB = ?*opaque {}; pub const HPBUFFEREXT = ?*opaque {}; pub const HPVIDEODEV = ?*opaque {}; pub const HVIDEOINPUTDEVICENV = ?*opaque {}; pub const HVIDEOOUTPUTDEVICENV = ?*opaque {}; pub const GPU_DEVICE = extern struct { cb: DWORD, DeviceName: [32]CHAR, DeviceString: [128]CHAR, Flags: DWORD, rcVirtualScreen: RECT, }; pub const PGPU_DEVICE = ?*GPU_DEVICE; pub const PFNGLADDSWAPHINTRECTWINPROC = ?fn (GLint, GLint, GLsizei, GLsizei) callconv(WINAPI) void; pub const PFNGLARRAYELEMENTARRAYEXTPROC = ?fn (GLenum, GLsizei, ?*const GLvoid) callconv(WINAPI) void; pub const PFNGLARRAYELEMENTEXTPROC = ?fn (GLint) callconv(WINAPI) void; pub const PFNGLCOLORPOINTEREXTPROC = ?fn (GLint, GLenum, GLsizei, GLsizei, ?*const GLvoid) callconv(WINAPI) void; pub const PFNGLCOLORSUBTABLEEXTPROC = ?fn (GLenum, GLsizei, GLsizei, GLenum, GLenum, ?*const GLvoid) callconv(WINAPI) void; pub const PFNGLCOLORTABLEEXTPROC = ?fn (GLenum, GLenum, GLsizei, GLenum, GLenum, ?*const GLvoid) callconv(WINAPI) void; pub const PFNGLDRAWARRAYSEXTPROC = ?fn (GLenum, GLint, GLsizei) callconv(WINAPI) void; pub const PFNGLDRAWRANGEELEMENTSWINPROC = ?fn (GLenum, GLuint, GLuint, GLsizei, GLenum, ?*const GLvoid) callconv(WINAPI) void; pub const PFNGLEDGEFLAGPOINTEREXTPROC = ?fn (GLsizei, GLsizei, ?*const GLboolean) callconv(WINAPI) void; pub const PFNGLGETCOLORTABLEEXTPROC = ?fn (GLenum, GLenum, GLenum, ?*GLvoid) callconv(WINAPI) void; pub const PFNGLGETCOLORTABLEPARAMETERFVEXTPROC = ?fn (GLenum, GLenum, ?*GLfloat) callconv(WINAPI) void; pub const PFNGLGETCOLORTABLEPARAMETERIVEXTPROC = ?fn (GLenum, GLenum, ?*GLint) callconv(WINAPI) void; pub const PFNGLGETPOINTERVEXTPROC = ?fn (GLenum, ?*(?*GLvoid)) callconv(WINAPI) void; pub const PFNGLINDEXPOINTEREXTPROC = ?fn (GLenum, GLsizei, GLsizei, ?*const GLvoid) callconv(WINAPI) void; pub const PFNGLNORMALPOINTEREXTPROC = ?fn (GLenum, GLsizei, GLsizei, ?*const GLvoid) callconv(WINAPI) void; pub const PFNGLTEXCOORDPOINTEREXTPROC = ?fn (GLint, GLenum, GLsizei, GLsizei, ?*const GLvoid) callconv(WINAPI) void; pub const PFNGLVERTEXPOINTEREXTPROC = ?fn (GLint, GLenum, GLsizei, GLsizei, ?*const GLvoid) callconv(WINAPI) void; pub const PFNWGLALLOCATEMEMORYNVPROC = ?fn (GLsizei, GLfloat, GLfloat, GLfloat) callconv(WINAPI) ?*anyopaque; pub const PFNWGLASSOCIATEIMAGEBUFFEREVENTSI3DPROC = ?fn (HDC, ?*const HANDLE, ?*const LPVOID, ?*const DWORD, UINT) callconv(WINAPI) BOOL; pub const PFNWGLBEGINFRAMETRACKINGI3DPROC = ?fn () callconv(WINAPI) BOOL; pub const PFNWGLBINDDISPLAYCOLORTABLEEXTPROC = ?fn (GLushort) callconv(WINAPI) GLboolean; pub const PFNWGLBINDSWAPBARRIERNVPROC = ?fn (GLuint, GLuint) callconv(WINAPI) BOOL; pub const PFNWGLBINDTEXIMAGEARBPROC = ?fn (HPBUFFERARB, c_int) callconv(WINAPI) BOOL; pub const PFNWGLBINDVIDEOCAPTUREDEVICENVPROC = ?fn (UINT, HVIDEOINPUTDEVICENV) callconv(WINAPI) BOOL; pub const PFNWGLBINDVIDEODEVICENVPROC = ?fn (HDC, c_uint, HVIDEOOUTPUTDEVICENV, ?*const c_int) callconv(WINAPI) BOOL; pub const PFNWGLBINDVIDEOIMAGENVPROC = ?fn (HPVIDEODEV, HPBUFFERARB, c_int) callconv(WINAPI) BOOL; pub const PFNWGLBLITCONTEXTFRAMEBUFFERAMDPROC = ?fn (HGLRC, GLint, GLint, GLint, GLint, GLint, GLint, GLint, GLint, GLbitfield, GLenum) callconv(WINAPI) VOID; pub const PFNWGLCHOOSEPIXELFORMATARBPROC = ?fn (HDC, ?*const c_int, ?*const FLOAT, UINT, ?*c_int, ?*UINT) callconv(WINAPI) BOOL; pub const PFNWGLCHOOSEPIXELFORMATEXTPROC = ?fn (HDC, ?*const c_int, ?*const FLOAT, UINT, ?*c_int, ?*UINT) callconv(WINAPI) BOOL; pub const PFNWGLCOPYIMAGESUBDATANVPROC = ?fn (HGLRC, GLuint, GLenum, GLint, GLint, GLint, GLint, HGLRC, GLuint, GLenum, GLint, GLint, GLint, GLint, GLsizei, GLsizei, GLsizei) callconv(WINAPI) BOOL; pub const PFNWGLCREATEAFFINITYDCNVPROC = ?fn (?*const HGPUNV) callconv(WINAPI) HDC; pub const PFNWGLCREATEASSOCIATEDCONTEXTAMDPROC = ?fn (UINT) callconv(WINAPI) HGLRC; pub const PFNWGLCREATEASSOCIATEDCONTEXTATTRIBSAMDPROC = ?fn (UINT, HGLRC, ?*const c_int) callconv(WINAPI) HGLRC; pub const PFNWGLCREATEBUFFERREGIONARBPROC = ?fn (HDC, c_int, UINT) callconv(WINAPI) HANDLE; pub const PFNWGLCREATECONTEXTATTRIBSARBPROC = ?fn (HDC, HGLRC, ?*const c_int) callconv(WINAPI) HGLRC; pub const PFNWGLCREATEDISPLAYCOLORTABLEEXTPROC = ?fn (GLushort) callconv(WINAPI) GLboolean; pub const PFNWGLCREATEIMAGEBUFFERI3DPROC = ?fn (HDC, DWORD, UINT) callconv(WINAPI) LPVOID; pub const PFNWGLCREATEPBUFFERARBPROC = ?fn (HDC, c_int, c_int, c_int, ?*const c_int) callconv(WINAPI) HPBUFFERARB; pub const PFNWGLCREATEPBUFFEREXTPROC = ?fn (HDC, c_int, c_int, c_int, ?*const c_int) callconv(WINAPI) HPBUFFEREXT; pub const PFNWGLDELAYBEFORESWAPNVPROC = ?fn (HDC, GLfloat) callconv(WINAPI) BOOL; pub const PFNWGLDELETEASSOCIATEDCONTEXTAMDPROC = ?fn (HGLRC) callconv(WINAPI) BOOL; pub const PFNWGLDELETEBUFFERREGIONARBPROC = ?fn (HANDLE) callconv(WINAPI) VOID; pub const PFNWGLDELETEDCNVPROC = ?fn (HDC) callconv(WINAPI) BOOL; pub const PFNWGLDESTROYDISPLAYCOLORTABLEEXTPROC = ?fn (GLushort) callconv(WINAPI) VOID; pub const PFNWGLDESTROYIMAGEBUFFERI3DPROC = ?fn (HDC, LPVOID) callconv(WINAPI) BOOL; pub const PFNWGLDESTROYPBUFFERARBPROC = ?fn (HPBUFFERARB) callconv(WINAPI) BOOL; pub const PFNWGLDESTROYPBUFFEREXTPROC = ?fn (HPBUFFEREXT) callconv(WINAPI) BOOL; pub const PFNWGLDISABLEFRAMELOCKI3DPROC = ?fn () callconv(WINAPI) BOOL; pub const PFNWGLDISABLEGENLOCKI3DPROC = ?fn (HDC) callconv(WINAPI) BOOL; pub const PFNWGLDXCLOSEDEVICENVPROC = ?fn (HANDLE) callconv(WINAPI) BOOL; pub const PFNWGLDXLOCKOBJECTSNVPROC = ?fn (HANDLE, GLint, ?*HANDLE) callconv(WINAPI) BOOL; pub const PFNWGLDXOBJECTACCESSNVPROC = ?fn (HANDLE, GLenum) callconv(WINAPI) BOOL; pub const PFNWGLDXOPENDEVICENVPROC = ?fn (?*anyopaque) callconv(WINAPI) HANDLE; pub const PFNWGLDXREGISTEROBJECTNVPROC = ?fn (HANDLE, ?*anyopaque, GLuint, GLenum, GLenum) callconv(WINAPI) HANDLE; pub const PFNWGLDXSETRESOURCESHAREHANDLENVPROC = ?fn (?*anyopaque, HANDLE) callconv(WINAPI) BOOL; pub const PFNWGLDXUNLOCKOBJECTSNVPROC = ?fn (HANDLE, GLint, ?*HANDLE) callconv(WINAPI) BOOL; pub const PFNWGLDXUNREGISTEROBJECTNVPROC = ?fn (HANDLE, HANDLE) callconv(WINAPI) BOOL; pub const PFNWGLENABLEFRAMELOCKI3DPROC = ?fn () callconv(WINAPI) BOOL; pub const PFNWGLENABLEGENLOCKI3DPROC = ?fn (HDC) callconv(WINAPI) BOOL; pub const PFNWGLENDFRAMETRACKINGI3DPROC = ?fn () callconv(WINAPI) BOOL; pub const PFNWGLENUMERATEVIDEOCAPTUREDEVICESNVPROC = ?fn (HDC, ?*HVIDEOINPUTDEVICENV) callconv(WINAPI) UINT; pub const PFNWGLENUMERATEVIDEODEVICESNVPROC = ?fn (HDC, ?*HVIDEOOUTPUTDEVICENV) callconv(WINAPI) c_int; pub const PFNWGLENUMGPUDEVICESNVPROC = ?fn (HGPUNV, UINT, PGPU_DEVICE) callconv(WINAPI) BOOL; pub const PFNWGLENUMGPUSFROMAFFINITYDCNVPROC = ?fn (HDC, UINT, ?*HGPUNV) callconv(WINAPI) BOOL; pub const PFNWGLENUMGPUSNVPROC = ?fn (UINT, ?*HGPUNV) callconv(WINAPI) BOOL; pub const PFNWGLFREEMEMORYNVPROC = ?fn (?*anyopaque) callconv(WINAPI) void; pub const PFNWGLGENLOCKSAMPLERATEI3DPROC = ?fn (HDC, UINT) callconv(WINAPI) BOOL; pub const PFNWGLGENLOCKSOURCEDELAYI3DPROC = ?fn (HDC, UINT) callconv(WINAPI) BOOL; pub const PFNWGLGENLOCKSOURCEEDGEI3DPROC = ?fn (HDC, UINT) callconv(WINAPI) BOOL; pub const PFNWGLGENLOCKSOURCEI3DPROC = ?fn (HDC, UINT) callconv(WINAPI) BOOL; pub const PFNWGLGETCONTEXTGPUIDAMDPROC = ?fn (HGLRC) callconv(WINAPI) UINT; pub const PFNWGLGETCURRENTASSOCIATEDCONTEXTAMDPROC = ?fn () callconv(WINAPI) HGLRC; pub const PFNWGLGETCURRENTREADDCARBPROC = ?fn () callconv(WINAPI) HDC; pub const PFNWGLGETCURRENTREADDCEXTPROC = ?fn () callconv(WINAPI) HDC; pub const PFNWGLGETDIGITALVIDEOPARAMETERSI3DPROC = ?fn (HDC, c_int, ?*c_int) callconv(WINAPI) BOOL; pub const PFNWGLGETEXTENSIONSSTRINGARBPROC = ?fn (HDC) ?[*]const u8; pub const PFNWGLGETEXTENSIONSSTRINGEXTPROC = ?fn () ?[*]const u8; pub const PFNWGLGETFRAMEUSAGEI3DPROC = ?fn (?*f32) callconv(WINAPI) BOOL; pub const PFNWGLGETGAMMATABLEI3DPROC = ?fn (HDC, c_int, ?*USHORT, ?*USHORT, ?*USHORT) callconv(WINAPI) BOOL; pub const PFNWGLGETGAMMATABLEPARAMETERSI3DPROC = ?fn (HDC, c_int, ?*c_int) callconv(WINAPI) BOOL; pub const PFNWGLGETGENLOCKSAMPLERATEI3DPROC = ?fn (HDC, ?*UINT) callconv(WINAPI) BOOL; pub const PFNWGLGETGENLOCKSOURCEDELAYI3DPROC = ?fn (HDC, ?*UINT) callconv(WINAPI) BOOL; pub const PFNWGLGETGENLOCKSOURCEEDGEI3DPROC = ?fn (HDC, ?*UINT) callconv(WINAPI) BOOL; pub const PFNWGLGETGENLOCKSOURCEI3DPROC = ?fn (HDC, ?*UINT) callconv(WINAPI) BOOL; pub const PFNWGLGETGPUIDSAMDPROC = ?fn (UINT, ?*UINT) callconv(WINAPI) UINT; pub const PFNWGLGETGPUINFOAMDPROC = ?fn (UINT, c_int, GLenum, UINT, ?*anyopaque) callconv(WINAPI) INT; pub const PFNWGLGETMSCRATEOMLPROC = ?fn (HDC, ?*INT32, ?*INT32) callconv(WINAPI) BOOL; pub const PFNWGLGETPBUFFERDCARBPROC = ?fn (HPBUFFERARB) callconv(WINAPI) HDC; pub const PFNWGLGETPBUFFERDCEXTPROC = ?fn (HPBUFFEREXT) callconv(WINAPI) HDC; pub const PFNWGLGETPIXELFORMATATTRIBFVARBPROC = ?fn (HDC, c_int, c_int, UINT, ?*const c_int, ?*FLOAT) callconv(WINAPI) BOOL; pub const PFNWGLGETPIXELFORMATATTRIBFVEXTPROC = ?fn (HDC, c_int, c_int, UINT, ?*c_int, ?*FLOAT) callconv(WINAPI) BOOL; pub const PFNWGLGETPIXELFORMATATTRIBIVARBPROC = ?fn (HDC, c_int, c_int, UINT, ?*const c_int, ?*c_int) callconv(WINAPI) BOOL; pub const PFNWGLGETPIXELFORMATATTRIBIVEXTPROC = ?fn (HDC, c_int, c_int, UINT, ?*c_int, ?*c_int) callconv(WINAPI) BOOL; pub const PFNWGLGETSWAPINTERVALEXTPROC = ?fn () callconv(WINAPI) c_int; pub const PFNWGLGETSYNCVALUESOMLPROC = ?fn (HDC, ?*INT64, ?*INT64, ?*INT64) callconv(WINAPI) BOOL; pub const PFNWGLGETVIDEODEVICENVPROC = ?fn (HDC, c_int, ?*HPVIDEODEV) callconv(WINAPI) BOOL; pub const PFNWGLGETVIDEOINFONVPROC = ?fn (HPVIDEODEV, ?*c_ulong, ?*c_ulong) callconv(WINAPI) BOOL; pub const PFNWGLISENABLEDFRAMELOCKI3DPROC = ?fn (?*BOOL) callconv(WINAPI) BOOL; pub const PFNWGLISENABLEDGENLOCKI3DPROC = ?fn (HDC, ?*BOOL) callconv(WINAPI) BOOL; pub const PFNWGLJOINSWAPGROUPNVPROC = ?fn (HDC, GLuint) callconv(WINAPI) BOOL; pub const PFNWGLLOADDISPLAYCOLORTABLEEXTPROC = ?fn (?*const GLushort, GLuint) callconv(WINAPI) GLboolean; pub const PFNWGLLOCKVIDEOCAPTUREDEVICENVPROC = ?fn (HDC, HVIDEOINPUTDEVICENV) callconv(WINAPI) BOOL; pub const PFNWGLMAKEASSOCIATEDCONTEXTCURRENTAMDPROC = ?fn (HGLRC) callconv(WINAPI) BOOL; pub const PFNWGLMAKECONTEXTCURRENTARBPROC = ?fn (HDC, HDC, HGLRC) callconv(WINAPI) BOOL; pub const PFNWGLMAKECONTEXTCURRENTEXTPROC = ?fn (HDC, HDC, HGLRC) callconv(WINAPI) BOOL; pub const PFNWGLQUERYCURRENTCONTEXTNVPROC = ?fn (c_int, ?*c_int) callconv(WINAPI) BOOL; pub const PFNWGLQUERYFRAMECOUNTNVPROC = ?fn (HDC, ?*GLuint) callconv(WINAPI) BOOL; pub const PFNWGLQUERYFRAMELOCKMASTERI3DPROC = ?fn (?*BOOL) callconv(WINAPI) BOOL; pub const PFNWGLQUERYFRAMETRACKINGI3DPROC = ?fn (?*DWORD, ?*DWORD, ?*f32) callconv(WINAPI) BOOL; pub const PFNWGLQUERYGENLOCKMAXSOURCEDELAYI3DPROC = ?fn (HDC, ?*UINT, ?*UINT) callconv(WINAPI) BOOL; pub const PFNWGLQUERYMAXSWAPGROUPSNVPROC = ?fn (HDC, ?*GLuint, ?*GLuint) callconv(WINAPI) BOOL; pub const PFNWGLQUERYPBUFFERARBPROC = ?fn (HPBUFFERARB, c_int, ?*c_int) callconv(WINAPI) BOOL; pub const PFNWGLQUERYPBUFFEREXTPROC = ?fn (HPBUFFEREXT, c_int, ?*c_int) callconv(WINAPI) BOOL; pub const PFNWGLQUERYSWAPGROUPNVPROC = ?fn (HDC, ?*GLuint, ?*GLuint) callconv(WINAPI) BOOL; pub const PFNWGLQUERYVIDEOCAPTUREDEVICENVPROC = ?fn (HDC, HVIDEOINPUTDEVICENV, c_int, ?*c_int) callconv(WINAPI) BOOL; pub const PFNWGLRELEASEIMAGEBUFFEREVENTSI3DPROC = ?fn (HDC, ?*const LPVOID, UINT) callconv(WINAPI) BOOL; pub const PFNWGLRELEASEPBUFFERDCARBPROC = ?fn (HPBUFFERARB, HDC) callconv(WINAPI) c_int; pub const PFNWGLRELEASEPBUFFERDCEXTPROC = ?fn (HPBUFFEREXT, HDC) callconv(WINAPI) c_int; pub const PFNWGLRELEASETEXIMAGEARBPROC = ?fn (HPBUFFERARB, c_int) callconv(WINAPI) BOOL; pub const PFNWGLRELEASEVIDEOCAPTUREDEVICENVPROC = ?fn (HDC, HVIDEOINPUTDEVICENV) callconv(WINAPI) BOOL; pub const PFNWGLRELEASEVIDEODEVICENVPROC = ?fn (HPVIDEODEV) callconv(WINAPI) BOOL; pub const PFNWGLRELEASEVIDEOIMAGENVPROC = ?fn (HPBUFFERARB, c_int) callconv(WINAPI) BOOL; pub const PFNWGLRESETFRAMECOUNTNVPROC = ?fn (HDC) callconv(WINAPI) BOOL; pub const PFNWGLRESTOREBUFFERREGIONARBPROC = ?fn (HANDLE, c_int, c_int, c_int, c_int, c_int, c_int) callconv(WINAPI) BOOL; pub const PFNWGLSAVEBUFFERREGIONARBPROC = ?fn (HANDLE, c_int, c_int, c_int, c_int) callconv(WINAPI) BOOL; pub const PFNWGLSENDPBUFFERTOVIDEONVPROC = ?fn (HPBUFFERARB, c_int, ?*c_ulong, BOOL) callconv(WINAPI) BOOL; pub const PFNWGLSETDIGITALVIDEOPARAMETERSI3DPROC = ?fn (HDC, c_int, ?*const c_int) callconv(WINAPI) BOOL; pub const PFNWGLSETGAMMATABLEI3DPROC = ?fn (HDC, c_int, ?*const USHORT, ?*const USHORT, ?*const USHORT) callconv(WINAPI) BOOL; pub const PFNWGLSETGAMMATABLEPARAMETERSI3DPROC = ?fn (HDC, c_int, ?*const c_int) callconv(WINAPI) BOOL; pub const PFNWGLSETPBUFFERATTRIBARBPROC = ?fn (HPBUFFERARB, ?*const c_int) callconv(WINAPI) BOOL; pub const PFNWGLSETSTEREOEMITTERSTATE3DLPROC = ?fn (HDC, UINT) callconv(WINAPI) BOOL; pub const PFNWGLSWAPBUFFERSMSCOMLPROC = ?fn (HDC, INT64, INT64, INT64) callconv(WINAPI) INT64; pub const PFNWGLSWAPINTERVALEXTPROC = ?fn (c_int) callconv(WINAPI) BOOL; pub const PFNWGLSWAPLAYERBUFFERSMSCOMLPROC = ?fn (HDC, c_int, INT64, INT64, INT64) callconv(WINAPI) INT64; pub const PFNWGLWAITFORMSCOMLPROC = ?fn (HDC, INT64, INT64, INT64, ?*INT64, ?*INT64, ?*INT64) callconv(WINAPI) BOOL; pub const PFNWGLWAITFORSBCOMLPROC = ?fn (HDC, INT64, ?*INT64, ?*INT64, ?*INT64) callconv(WINAPI) BOOL; pub extern "opengl32" fn glAccum(op: GLenum, value: GLfloat) callconv(WINAPI) void; pub extern "opengl32" fn glAlphaFunc(func: GLenum, ref: GLclampf) callconv(WINAPI) void; pub extern "opengl32" fn glAreTexturesResident(n: GLsizei, textures: ?*const GLuint, residences: ?*GLboolean) callconv(WINAPI) GLboolean; pub extern "opengl32" fn glArrayElement(i: GLint) callconv(WINAPI) void; pub extern "opengl32" fn glBegin(mode: GLenum) callconv(WINAPI) void; pub extern "opengl32" fn glBindTexture(target: GLenum, texture: GLuint) callconv(WINAPI) void; pub extern "opengl32" fn glBitmap(width: GLsizei, height: GLsizei, xorig: GLfloat, yorig: GLfloat, xmove: GLfloat, ymove: GLfloat, bitmap: ?[*]const GLubyte) callconv(WINAPI) void; pub extern "opengl32" fn glBlendFunc(sfactor: GLenum, dfactor: GLenum) callconv(WINAPI) void; pub extern "opengl32" fn glCallList(list: GLuint) callconv(WINAPI) void; pub extern "opengl32" fn glCallLists(n: GLsizei, type_0: GLenum, lists: ?*const GLvoid) callconv(WINAPI) void; pub extern "opengl32" fn glClear(mask: GLbitfield) callconv(WINAPI) void; pub extern "opengl32" fn glClearAccum(red: GLfloat, green: GLfloat, blue: GLfloat, alpha: GLfloat) callconv(WINAPI) void; pub extern "opengl32" fn glClearColor(red: GLclampf, green: GLclampf, blue: GLclampf, alpha: GLclampf) callconv(WINAPI) void; pub extern "opengl32" fn glClearDepth(depth: GLclampd) callconv(WINAPI) void; pub extern "opengl32" fn glClearIndex(c: GLfloat) callconv(WINAPI) void; pub extern "opengl32" fn glClearStencil(s: GLint) callconv(WINAPI) void; pub extern "opengl32" fn glClipPlane(plane: GLenum, equation: ?*const GLdouble) callconv(WINAPI) void; pub extern "opengl32" fn glColor3b(red: GLbyte, green: GLbyte, blue: GLbyte) callconv(WINAPI) void; pub extern "opengl32" fn glColor3bv(v: ?*const GLbyte) callconv(WINAPI) void; pub extern "opengl32" fn glColor3d(red: GLdouble, green: GLdouble, blue: GLdouble) callconv(WINAPI) void; pub extern "opengl32" fn glColor3dv(v: ?*const GLdouble) callconv(WINAPI) void; pub extern "opengl32" fn glColor3f(red: GLfloat, green: GLfloat, blue: GLfloat) callconv(WINAPI) void; pub extern "opengl32" fn glColor3fv(v: ?*const GLfloat) callconv(WINAPI) void; pub extern "opengl32" fn glColor3i(red: GLint, green: GLint, blue: GLint) callconv(WINAPI) void; pub extern "opengl32" fn glColor3iv(v: ?*const GLint) callconv(WINAPI) void; pub extern "opengl32" fn glColor3s(red: GLshort, green: GLshort, blue: GLshort) callconv(WINAPI) void; pub extern "opengl32" fn glColor3sv(v: ?*const GLshort) callconv(WINAPI) void; pub extern "opengl32" fn glColor3ub(red: GLubyte, green: GLubyte, blue: GLubyte) callconv(WINAPI) void; pub extern "opengl32" fn glColor3ubv(v: ?[*]const GLubyte) callconv(WINAPI) void; pub extern "opengl32" fn glColor3ui(red: GLuint, green: GLuint, blue: GLuint) callconv(WINAPI) void; pub extern "opengl32" fn glColor3uiv(v: ?*const GLuint) callconv(WINAPI) void; pub extern "opengl32" fn glColor3us(red: GLushort, green: GLushort, blue: GLushort) callconv(WINAPI) void; pub extern "opengl32" fn glColor3usv(v: ?*const GLushort) callconv(WINAPI) void; pub extern "opengl32" fn glColor4b(red: GLbyte, green: GLbyte, blue: GLbyte, alpha: GLbyte) callconv(WINAPI) void; pub extern "opengl32" fn glColor4bv(v: ?*const GLbyte) callconv(WINAPI) void; pub extern "opengl32" fn glColor4d(red: GLdouble, green: GLdouble, blue: GLdouble, alpha: GLdouble) callconv(WINAPI) void; pub extern "opengl32" fn glColor4dv(v: ?*const GLdouble) callconv(WINAPI) void; pub extern "opengl32" fn glColor4f(red: GLfloat, green: GLfloat, blue: GLfloat, alpha: GLfloat) callconv(WINAPI) void; pub extern "opengl32" fn glColor4fv(v: ?*const GLfloat) callconv(WINAPI) void; pub extern "opengl32" fn glColor4i(red: GLint, green: GLint, blue: GLint, alpha: GLint) callconv(WINAPI) void; pub extern "opengl32" fn glColor4iv(v: ?*const GLint) callconv(WINAPI) void; pub extern "opengl32" fn glColor4s(red: GLshort, green: GLshort, blue: GLshort, alpha: GLshort) callconv(WINAPI) void; pub extern "opengl32" fn glColor4sv(v: ?*const GLshort) callconv(WINAPI) void; pub extern "opengl32" fn glColor4ub(red: GLubyte, green: GLubyte, blue: GLubyte, alpha: GLubyte) callconv(WINAPI) void; pub extern "opengl32" fn glColor4ubv(v: ?[*]const GLubyte) callconv(WINAPI) void; pub extern "opengl32" fn glColor4ui(red: GLuint, green: GLuint, blue: GLuint, alpha: GLuint) callconv(WINAPI) void; pub extern "opengl32" fn glColor4uiv(v: ?*const GLuint) callconv(WINAPI) void; pub extern "opengl32" fn glColor4us(red: GLushort, green: GLushort, blue: GLushort, alpha: GLushort) callconv(WINAPI) void; pub extern "opengl32" fn glColor4usv(v: ?*const GLushort) callconv(WINAPI) void; pub extern "opengl32" fn glColorMask(red: GLboolean, green: GLboolean, blue: GLboolean, alpha: GLboolean) callconv(WINAPI) void; pub extern "opengl32" fn glColorMaterial(face: GLenum, mode: GLenum) callconv(WINAPI) void; pub extern "opengl32" fn glColorPointer(size: GLint, type_0: GLenum, stride: GLsizei, pointer: ?*const GLvoid) callconv(WINAPI) void; pub extern "opengl32" fn glCopyPixels(x: GLint, y: GLint, width: GLsizei, height: GLsizei, type_0: GLenum) callconv(WINAPI) void; pub extern "opengl32" fn glCopyTexImage1D(target: GLenum, level: GLint, internalFormat: GLenum, x: GLint, y: GLint, width: GLsizei, border: GLint) callconv(WINAPI) void; pub extern "opengl32" fn glCopyTexImage2D(target: GLenum, level: GLint, internalFormat: GLenum, x: GLint, y: GLint, width: GLsizei, height: GLsizei, border: GLint) callconv(WINAPI) void; pub extern "opengl32" fn glCopyTexSubImage1D(target: GLenum, level: GLint, xoffset: GLint, x: GLint, y: GLint, width: GLsizei) callconv(WINAPI) void; pub extern "opengl32" fn glCopyTexSubImage2D(target: GLenum, level: GLint, xoffset: GLint, yoffset: GLint, x: GLint, y: GLint, width: GLsizei, height: GLsizei) callconv(WINAPI) void; pub extern "opengl32" fn glCullFace(mode: GLenum) callconv(WINAPI) void; pub extern "opengl32" fn glDeleteLists(list: GLuint, range: GLsizei) callconv(WINAPI) void; pub extern "opengl32" fn glDeleteTextures(n: GLsizei, textures: ?*const GLuint) callconv(WINAPI) void; pub extern "opengl32" fn glDepthFunc(func: GLenum) callconv(WINAPI) void; pub extern "opengl32" fn glDepthMask(flag: GLboolean) callconv(WINAPI) void; pub extern "opengl32" fn glDepthRange(zNear: GLclampd, zFar: GLclampd) callconv(WINAPI) void; pub extern "opengl32" fn glDisable(cap: GLenum) callconv(WINAPI) void; pub extern "opengl32" fn glDisableClientState(array: GLenum) callconv(WINAPI) void; pub extern "opengl32" fn glDrawArrays(mode: GLenum, first: GLint, count: GLsizei) callconv(WINAPI) void; pub extern "opengl32" fn glDrawBuffer(mode: GLenum) callconv(WINAPI) void; pub extern "opengl32" fn glDrawElements(mode: GLenum, count: GLsizei, type_0: GLenum, indices: ?*const GLvoid) callconv(WINAPI) void; pub extern "opengl32" fn glDrawPixels(width: GLsizei, height: GLsizei, format: GLenum, type_0: GLenum, pixels: ?*const GLvoid) callconv(WINAPI) void; pub extern "opengl32" fn glEdgeFlag(flag: GLboolean) callconv(WINAPI) void; pub extern "opengl32" fn glEdgeFlagPointer(stride: GLsizei, pointer: ?*const GLvoid) callconv(WINAPI) void; pub extern "opengl32" fn glEdgeFlagv(flag: ?*const GLboolean) callconv(WINAPI) void; pub extern "opengl32" fn glEnable(cap: GLenum) callconv(WINAPI) void; pub extern "opengl32" fn glEnableClientState(array: GLenum) callconv(WINAPI) void; pub extern "opengl32" fn glEnd() callconv(WINAPI) void; pub extern "opengl32" fn glEndList() callconv(WINAPI) void; pub extern "opengl32" fn glEvalCoord1d(u: GLdouble) callconv(WINAPI) void; pub extern "opengl32" fn glEvalCoord1dv(u: ?*const GLdouble) callconv(WINAPI) void; pub extern "opengl32" fn glEvalCoord1f(u: GLfloat) callconv(WINAPI) void; pub extern "opengl32" fn glEvalCoord1fv(u: ?*const GLfloat) callconv(WINAPI) void; pub extern "opengl32" fn glEvalCoord2d(u: GLdouble, v: GLdouble) callconv(WINAPI) void; pub extern "opengl32" fn glEvalCoord2dv(u: ?*const GLdouble) callconv(WINAPI) void; pub extern "opengl32" fn glEvalCoord2f(u: GLfloat, v: GLfloat) callconv(WINAPI) void; pub extern "opengl32" fn glEvalCoord2fv(u: ?*const GLfloat) callconv(WINAPI) void; pub extern "opengl32" fn glEvalMesh1(mode: GLenum, i1: GLint, i2_0: GLint) callconv(WINAPI) void; pub extern "opengl32" fn glEvalMesh2(mode: GLenum, i1: GLint, i2_0: GLint, j1: GLint, j2: GLint) callconv(WINAPI) void; pub extern "opengl32" fn glEvalPoint1(i: GLint) callconv(WINAPI) void; pub extern "opengl32" fn glEvalPoint2(i: GLint, j: GLint) callconv(WINAPI) void; pub extern "opengl32" fn glFeedbackBuffer(size: GLsizei, type_0: GLenum, buffer: ?*GLfloat) callconv(WINAPI) void; pub extern "opengl32" fn glFinish() callconv(WINAPI) void; pub extern "opengl32" fn glFlush() callconv(WINAPI) void; pub extern "opengl32" fn glFogf(pname: GLenum, param: GLfloat) callconv(WINAPI) void; pub extern "opengl32" fn glFogfv(pname: GLenum, params: ?*const GLfloat) callconv(WINAPI) void; pub extern "opengl32" fn glFogi(pname: GLenum, param: GLint) callconv(WINAPI) void; pub extern "opengl32" fn glFogiv(pname: GLenum, params: ?*const GLint) callconv(WINAPI) void; pub extern "opengl32" fn glFrontFace(mode: GLenum) callconv(WINAPI) void; pub extern "opengl32" fn glFrustum(left: GLdouble, right: GLdouble, bottom: GLdouble, top: GLdouble, zNear: GLdouble, zFar: GLdouble) callconv(WINAPI) void; pub extern "opengl32" fn glGenLists(range: GLsizei) callconv(WINAPI) GLuint; pub extern "opengl32" fn glGenTextures(n: GLsizei, textures: ?*GLuint) callconv(WINAPI) void; pub extern "opengl32" fn glGetBooleanv(pname: GLenum, params: ?*GLboolean) callconv(WINAPI) void; pub extern "opengl32" fn glGetClipPlane(plane: GLenum, equation: ?*GLdouble) callconv(WINAPI) void; pub extern "opengl32" fn glGetDoublev(pname: GLenum, params: ?*GLdouble) callconv(WINAPI) void; pub extern "opengl32" fn glGetError() callconv(WINAPI) GLenum; pub extern "opengl32" fn glGetFloatv(pname: GLenum, params: ?*GLfloat) callconv(WINAPI) void; pub extern "opengl32" fn glGetIntegerv(pname: GLenum, params: ?*GLint) callconv(WINAPI) void; pub extern "opengl32" fn glGetLightfv(light: GLenum, pname: GLenum, params: ?*GLfloat) callconv(WINAPI) void; pub extern "opengl32" fn glGetLightiv(light: GLenum, pname: GLenum, params: ?*GLint) callconv(WINAPI) void; pub extern "opengl32" fn glGetMapdv(target: GLenum, query: GLenum, v: ?*GLdouble) callconv(WINAPI) void; pub extern "opengl32" fn glGetMapfv(target: GLenum, query: GLenum, v: ?*GLfloat) callconv(WINAPI) void; pub extern "opengl32" fn glGetMapiv(target: GLenum, query: GLenum, v: ?*GLint) callconv(WINAPI) void; pub extern "opengl32" fn glGetMaterialfv(face: GLenum, pname: GLenum, params: ?*GLfloat) callconv(WINAPI) void; pub extern "opengl32" fn glGetMaterialiv(face: GLenum, pname: GLenum, params: ?*GLint) callconv(WINAPI) void; pub extern "opengl32" fn glGetPixelMapfv(map: GLenum, values: ?*GLfloat) callconv(WINAPI) void; pub extern "opengl32" fn glGetPixelMapuiv(map: GLenum, values: ?*GLuint) callconv(WINAPI) void; pub extern "opengl32" fn glGetPixelMapusv(map: GLenum, values: ?*GLushort) callconv(WINAPI) void; pub extern "opengl32" fn glGetPointerv(pname: GLenum, params: ?*(?*GLvoid)) callconv(WINAPI) void; pub extern "opengl32" fn glGetPolygonStipple(mask: ?*GLubyte) callconv(WINAPI) void; pub extern "opengl32" fn glGetString(name: GLenum) ?[*]const GLubyte; pub extern "opengl32" fn glGetTexEnvfv(target: GLenum, pname: GLenum, params: ?*GLfloat) callconv(WINAPI) void; pub extern "opengl32" fn glGetTexEnviv(target: GLenum, pname: GLenum, params: ?*GLint) callconv(WINAPI) void; pub extern "opengl32" fn glGetTexGendv(coord: GLenum, pname: GLenum, params: ?*GLdouble) callconv(WINAPI) void; pub extern "opengl32" fn glGetTexGenfv(coord: GLenum, pname: GLenum, params: ?*GLfloat) callconv(WINAPI) void; pub extern "opengl32" fn glGetTexGeniv(coord: GLenum, pname: GLenum, params: ?*GLint) callconv(WINAPI) void; pub extern "opengl32" fn glGetTexImage(target: GLenum, level: GLint, format: GLenum, type_0: GLenum, pixels: ?*GLvoid) callconv(WINAPI) void; pub extern "opengl32" fn glGetTexLevelParameterfv(target: GLenum, level: GLint, pname: GLenum, params: ?*GLfloat) callconv(WINAPI) void; pub extern "opengl32" fn glGetTexLevelParameteriv(target: GLenum, level: GLint, pname: GLenum, params: ?*GLint) callconv(WINAPI) void; pub extern "opengl32" fn glGetTexParameterfv(target: GLenum, pname: GLenum, params: ?*GLfloat) callconv(WINAPI) void; pub extern "opengl32" fn glGetTexParameteriv(target: GLenum, pname: GLenum, params: ?*GLint) callconv(WINAPI) void; pub extern "opengl32" fn glHint(target: GLenum, mode: GLenum) callconv(WINAPI) void; pub extern "opengl32" fn glIndexd(c: GLdouble) callconv(WINAPI) void; pub extern "opengl32" fn glIndexdv(c: ?*const GLdouble) callconv(WINAPI) void; pub extern "opengl32" fn glIndexf(c: GLfloat) callconv(WINAPI) void; pub extern "opengl32" fn glIndexfv(c: ?*const GLfloat) callconv(WINAPI) void; pub extern "opengl32" fn glIndexi(c: GLint) callconv(WINAPI) void; pub extern "opengl32" fn glIndexiv(c: ?*const GLint) callconv(WINAPI) void; pub extern "opengl32" fn glIndexMask(mask: GLuint) callconv(WINAPI) void; pub extern "opengl32" fn glIndexPointer(type_0: GLenum, stride: GLsizei, pointer: ?*const GLvoid) callconv(WINAPI) void; pub extern "opengl32" fn glIndexs(c: GLshort) callconv(WINAPI) void; pub extern "opengl32" fn glIndexsv(c: ?*const GLshort) callconv(WINAPI) void; pub extern "opengl32" fn glIndexub(c: GLubyte) callconv(WINAPI) void; pub extern "opengl32" fn glIndexubv(c: ?[*]const GLubyte) callconv(WINAPI) void; pub extern "opengl32" fn glInitNames() callconv(WINAPI) void; pub extern "opengl32" fn glInterleavedArrays(format: GLenum, stride: GLsizei, pointer: ?*const GLvoid) callconv(WINAPI) void; pub extern "opengl32" fn glIsEnabled(cap: GLenum) callconv(WINAPI) GLboolean; pub extern "opengl32" fn glIsList(list: GLuint) callconv(WINAPI) GLboolean; pub extern "opengl32" fn glIsTexture(texture: GLuint) callconv(WINAPI) GLboolean; pub extern "opengl32" fn glLightf(light: GLenum, pname: GLenum, param: GLfloat) callconv(WINAPI) void; pub extern "opengl32" fn glLightfv(light: GLenum, pname: GLenum, params: ?*const GLfloat) callconv(WINAPI) void; pub extern "opengl32" fn glLighti(light: GLenum, pname: GLenum, param: GLint) callconv(WINAPI) void; pub extern "opengl32" fn glLightiv(light: GLenum, pname: GLenum, params: ?*const GLint) callconv(WINAPI) void; pub extern "opengl32" fn glLightModelf(pname: GLenum, param: GLfloat) callconv(WINAPI) void; pub extern "opengl32" fn glLightModelfv(pname: GLenum, params: ?*const GLfloat) callconv(WINAPI) void; pub extern "opengl32" fn glLightModeli(pname: GLenum, param: GLint) callconv(WINAPI) void; pub extern "opengl32" fn glLightModeliv(pname: GLenum, params: ?*const GLint) callconv(WINAPI) void; pub extern "opengl32" fn glLineStipple(factor: GLint, pattern: GLushort) callconv(WINAPI) void; pub extern "opengl32" fn glLineWidth(width: GLfloat) callconv(WINAPI) void; pub extern "opengl32" fn glListBase(base: GLuint) callconv(WINAPI) void; pub extern "opengl32" fn glLoadIdentity() callconv(WINAPI) void; pub extern "opengl32" fn glLoadMatrixd(m: ?*const GLdouble) callconv(WINAPI) void; pub extern "opengl32" fn glLoadMatrixf(m: ?*const GLfloat) callconv(WINAPI) void; pub extern "opengl32" fn glLoadName(name: GLuint) callconv(WINAPI) void; pub extern "opengl32" fn glLogicOp(opcode: GLenum) callconv(WINAPI) void; pub extern "opengl32" fn glMap1d(target: GLenum, u1: GLdouble, u2_0: GLdouble, stride: GLint, order: GLint, points: ?*const GLdouble) callconv(WINAPI) void; pub extern "opengl32" fn glMap1f(target: GLenum, u1: GLfloat, u2_0: GLfloat, stride: GLint, order: GLint, points: ?*const GLfloat) callconv(WINAPI) void; pub extern "opengl32" fn glMap2d(target: GLenum, u1: GLdouble, u2_0: GLdouble, ustride: GLint, uorder: GLint, v1: GLdouble, v2: GLdouble, vstride: GLint, vorder: GLint, points: ?*const GLdouble) callconv(WINAPI) void; pub extern "opengl32" fn glMap2f(target: GLenum, u1: GLfloat, u2_0: GLfloat, ustride: GLint, uorder: GLint, v1: GLfloat, v2: GLfloat, vstride: GLint, vorder: GLint, points: ?*const GLfloat) callconv(WINAPI) void; pub extern "opengl32" fn glMapGrid1d(un: GLint, u1: GLdouble, u2_0: GLdouble) callconv(WINAPI) void; pub extern "opengl32" fn glMapGrid1f(un: GLint, u1: GLfloat, u2_0: GLfloat) callconv(WINAPI) void; pub extern "opengl32" fn glMapGrid2d(un: GLint, u1: GLdouble, u2_0: GLdouble, vn: GLint, v1: GLdouble, v2: GLdouble) callconv(WINAPI) void; pub extern "opengl32" fn glMapGrid2f(un: GLint, u1: GLfloat, u2_0: GLfloat, vn: GLint, v1: GLfloat, v2: GLfloat) callconv(WINAPI) void; pub extern "opengl32" fn glMaterialf(face: GLenum, pname: GLenum, param: GLfloat) callconv(WINAPI) void; pub extern "opengl32" fn glMaterialfv(face: GLenum, pname: GLenum, params: ?*const GLfloat) callconv(WINAPI) void; pub extern "opengl32" fn glMateriali(face: GLenum, pname: GLenum, param: GLint) callconv(WINAPI) void; pub extern "opengl32" fn glMaterialiv(face: GLenum, pname: GLenum, params: ?*const GLint) callconv(WINAPI) void; pub extern "opengl32" fn glMatrixMode(mode: GLenum) callconv(WINAPI) void; pub extern "opengl32" fn glMultMatrixd(m: ?*const GLdouble) callconv(WINAPI) void; pub extern "opengl32" fn glMultMatrixf(m: ?*const GLfloat) callconv(WINAPI) void; pub extern "opengl32" fn glNewList(list: GLuint, mode: GLenum) callconv(WINAPI) void; pub extern "opengl32" fn glNormal3b(nx: GLbyte, ny: GLbyte, nz: GLbyte) callconv(WINAPI) void; pub extern "opengl32" fn glNormal3bv(v: ?*const GLbyte) callconv(WINAPI) void; pub extern "opengl32" fn glNormal3d(nx: GLdouble, ny: GLdouble, nz: GLdouble) callconv(WINAPI) void; pub extern "opengl32" fn glNormal3dv(v: ?*const GLdouble) callconv(WINAPI) void; pub extern "opengl32" fn glNormal3f(nx: GLfloat, ny: GLfloat, nz: GLfloat) callconv(WINAPI) void; pub extern "opengl32" fn glNormal3fv(v: ?*const GLfloat) callconv(WINAPI) void; pub extern "opengl32" fn glNormal3i(nx: GLint, ny: GLint, nz: GLint) callconv(WINAPI) void; pub extern "opengl32" fn glNormal3iv(v: ?*const GLint) callconv(WINAPI) void; pub extern "opengl32" fn glNormal3s(nx: GLshort, ny: GLshort, nz: GLshort) callconv(WINAPI) void; pub extern "opengl32" fn glNormal3sv(v: ?*const GLshort) callconv(WINAPI) void; pub extern "opengl32" fn glNormalPointer(type_0: GLenum, stride: GLsizei, pointer: ?*const GLvoid) callconv(WINAPI) void; pub extern "opengl32" fn glOrtho(left: GLdouble, right: GLdouble, bottom: GLdouble, top: GLdouble, zNear: GLdouble, zFar: GLdouble) callconv(WINAPI) void; pub extern "opengl32" fn glPassThrough(token: GLfloat) callconv(WINAPI) void; pub extern "opengl32" fn glPixelMapfv(map: GLenum, mapsize: GLsizei, values: ?*const GLfloat) callconv(WINAPI) void; pub extern "opengl32" fn glPixelMapuiv(map: GLenum, mapsize: GLsizei, values: ?*const GLuint) callconv(WINAPI) void; pub extern "opengl32" fn glPixelMapusv(map: GLenum, mapsize: GLsizei, values: ?*const GLushort) callconv(WINAPI) void; pub extern "opengl32" fn glPixelStoref(pname: GLenum, param: GLfloat) callconv(WINAPI) void; pub extern "opengl32" fn glPixelStorei(pname: GLenum, param: GLint) callconv(WINAPI) void; pub extern "opengl32" fn glPixelTransferf(pname: GLenum, param: GLfloat) callconv(WINAPI) void; pub extern "opengl32" fn glPixelTransferi(pname: GLenum, param: GLint) callconv(WINAPI) void; pub extern "opengl32" fn glPixelZoom(xfactor: GLfloat, yfactor: GLfloat) callconv(WINAPI) void; pub extern "opengl32" fn glPointSize(size: GLfloat) callconv(WINAPI) void; pub extern "opengl32" fn glPolygonMode(face: GLenum, mode: GLenum) callconv(WINAPI) void; pub extern "opengl32" fn glPolygonOffset(factor: GLfloat, units: GLfloat) callconv(WINAPI) void; pub extern "opengl32" fn glPolygonStipple(mask: ?[*]const GLubyte) callconv(WINAPI) void; pub extern "opengl32" fn glPopAttrib() callconv(WINAPI) void; pub extern "opengl32" fn glPopClientAttrib() callconv(WINAPI) void; pub extern "opengl32" fn glPopMatrix() callconv(WINAPI) void; pub extern "opengl32" fn glPopName() callconv(WINAPI) void; pub extern "opengl32" fn glPrioritizeTextures(n: GLsizei, textures: ?*const GLuint, priorities: ?*const GLclampf) callconv(WINAPI) void; pub extern "opengl32" fn glPushAttrib(mask: GLbitfield) callconv(WINAPI) void; pub extern "opengl32" fn glPushClientAttrib(mask: GLbitfield) callconv(WINAPI) void; pub extern "opengl32" fn glPushMatrix() callconv(WINAPI) void; pub extern "opengl32" fn glPushName(name: GLuint) callconv(WINAPI) void; pub extern "opengl32" fn glRasterPos2d(x: GLdouble, y: GLdouble) callconv(WINAPI) void; pub extern "opengl32" fn glRasterPos2dv(v: ?*const GLdouble) callconv(WINAPI) void; pub extern "opengl32" fn glRasterPos2f(x: GLfloat, y: GLfloat) callconv(WINAPI) void; pub extern "opengl32" fn glRasterPos2fv(v: ?*const GLfloat) callconv(WINAPI) void; pub extern "opengl32" fn glRasterPos2i(x: GLint, y: GLint) callconv(WINAPI) void; pub extern "opengl32" fn glRasterPos2iv(v: ?*const GLint) callconv(WINAPI) void; pub extern "opengl32" fn glRasterPos2s(x: GLshort, y: GLshort) callconv(WINAPI) void; pub extern "opengl32" fn glRasterPos2sv(v: ?*const GLshort) callconv(WINAPI) void; pub extern "opengl32" fn glRasterPos3d(x: GLdouble, y: GLdouble, z: GLdouble) callconv(WINAPI) void; pub extern "opengl32" fn glRasterPos3dv(v: ?*const GLdouble) callconv(WINAPI) void; pub extern "opengl32" fn glRasterPos3f(x: GLfloat, y: GLfloat, z: GLfloat) callconv(WINAPI) void; pub extern "opengl32" fn glRasterPos3fv(v: ?*const GLfloat) callconv(WINAPI) void; pub extern "opengl32" fn glRasterPos3i(x: GLint, y: GLint, z: GLint) callconv(WINAPI) void; pub extern "opengl32" fn glRasterPos3iv(v: ?*const GLint) callconv(WINAPI) void; pub extern "opengl32" fn glRasterPos3s(x: GLshort, y: GLshort, z: GLshort) callconv(WINAPI) void; pub extern "opengl32" fn glRasterPos3sv(v: ?*const GLshort) callconv(WINAPI) void; pub extern "opengl32" fn glRasterPos4d(x: GLdouble, y: GLdouble, z: GLdouble, w: GLdouble) callconv(WINAPI) void; pub extern "opengl32" fn glRasterPos4dv(v: ?*const GLdouble) callconv(WINAPI) void; pub extern "opengl32" fn glRasterPos4f(x: GLfloat, y: GLfloat, z: GLfloat, w: GLfloat) callconv(WINAPI) void; pub extern "opengl32" fn glRasterPos4fv(v: ?*const GLfloat) callconv(WINAPI) void; pub extern "opengl32" fn glRasterPos4i(x: GLint, y: GLint, z: GLint, w: GLint) callconv(WINAPI) void; pub extern "opengl32" fn glRasterPos4iv(v: ?*const GLint) callconv(WINAPI) void; pub extern "opengl32" fn glRasterPos4s(x: GLshort, y: GLshort, z: GLshort, w: GLshort) callconv(WINAPI) void; pub extern "opengl32" fn glRasterPos4sv(v: ?*const GLshort) callconv(WINAPI) void; pub extern "opengl32" fn glReadBuffer(mode: GLenum) callconv(WINAPI) void; pub extern "opengl32" fn glReadPixels(x: GLint, y: GLint, width: GLsizei, height: GLsizei, format: GLenum, type_0: GLenum, pixels: ?*GLvoid) callconv(WINAPI) void; pub extern "opengl32" fn glRectd(x1: GLdouble, y1: GLdouble, x2: GLdouble, y2: GLdouble) callconv(WINAPI) void; pub extern "opengl32" fn glRectdv(v1: ?*const GLdouble, v2: ?*const GLdouble) callconv(WINAPI) void; pub extern "opengl32" fn glRectf(x1: GLfloat, y1: GLfloat, x2: GLfloat, y2: GLfloat) callconv(WINAPI) void; pub extern "opengl32" fn glRectfv(v1: ?*const GLfloat, v2: ?*const GLfloat) callconv(WINAPI) void; pub extern "opengl32" fn glRecti(x1: GLint, y1: GLint, x2: GLint, y2: GLint) callconv(WINAPI) void; pub extern "opengl32" fn glRectiv(v1: ?*const GLint, v2: ?*const GLint) callconv(WINAPI) void; pub extern "opengl32" fn glRects(x1: GLshort, y1: GLshort, x2: GLshort, y2: GLshort) callconv(WINAPI) void; pub extern "opengl32" fn glRectsv(v1: ?*const GLshort, v2: ?*const GLshort) callconv(WINAPI) void; pub extern "opengl32" fn glRenderMode(mode: GLenum) callconv(WINAPI) GLint; pub extern "opengl32" fn glRotated(angle: GLdouble, x: GLdouble, y: GLdouble, z: GLdouble) callconv(WINAPI) void; pub extern "opengl32" fn glRotatef(angle: GLfloat, x: GLfloat, y: GLfloat, z: GLfloat) callconv(WINAPI) void; pub extern "opengl32" fn glScaled(x: GLdouble, y: GLdouble, z: GLdouble) callconv(WINAPI) void; pub extern "opengl32" fn glScalef(x: GLfloat, y: GLfloat, z: GLfloat) callconv(WINAPI) void; pub extern "opengl32" fn glScissor(x: GLint, y: GLint, width: GLsizei, height: GLsizei) callconv(WINAPI) void; pub extern "opengl32" fn glSelectBuffer(size: GLsizei, buffer: ?*GLuint) callconv(WINAPI) void; pub extern "opengl32" fn glShadeModel(mode: GLenum) callconv(WINAPI) void; pub extern "opengl32" fn glStencilFunc(func: GLenum, ref: GLint, mask: GLuint) callconv(WINAPI) void; pub extern "opengl32" fn glStencilMask(mask: GLuint) callconv(WINAPI) void; pub extern "opengl32" fn glStencilOp(fail: GLenum, zfail: GLenum, zpass: GLenum) callconv(WINAPI) void; pub extern "opengl32" fn glTexCoord1d(s: GLdouble) callconv(WINAPI) void; pub extern "opengl32" fn glTexCoord1dv(v: ?*const GLdouble) callconv(WINAPI) void; pub extern "opengl32" fn glTexCoord1f(s: GLfloat) callconv(WINAPI) void; pub extern "opengl32" fn glTexCoord1fv(v: ?*const GLfloat) callconv(WINAPI) void; pub extern "opengl32" fn glTexCoord1i(s: GLint) callconv(WINAPI) void; pub extern "opengl32" fn glTexCoord1iv(v: ?*const GLint) callconv(WINAPI) void; pub extern "opengl32" fn glTexCoord1s(s: GLshort) callconv(WINAPI) void; pub extern "opengl32" fn glTexCoord1sv(v: ?*const GLshort) callconv(WINAPI) void; pub extern "opengl32" fn glTexCoord2d(s: GLdouble, t: GLdouble) callconv(WINAPI) void; pub extern "opengl32" fn glTexCoord2dv(v: ?*const GLdouble) callconv(WINAPI) void; pub extern "opengl32" fn glTexCoord2f(s: GLfloat, t: GLfloat) callconv(WINAPI) void; pub extern "opengl32" fn glTexCoord2fv(v: ?*const GLfloat) callconv(WINAPI) void; pub extern "opengl32" fn glTexCoord2i(s: GLint, t: GLint) callconv(WINAPI) void; pub extern "opengl32" fn glTexCoord2iv(v: ?*const GLint) callconv(WINAPI) void; pub extern "opengl32" fn glTexCoord2s(s: GLshort, t: GLshort) callconv(WINAPI) void; pub extern "opengl32" fn glTexCoord2sv(v: ?*const GLshort) callconv(WINAPI) void; pub extern "opengl32" fn glTexCoord3d(s: GLdouble, t: GLdouble, r: GLdouble) callconv(WINAPI) void; pub extern "opengl32" fn glTexCoord3dv(v: ?*const GLdouble) callconv(WINAPI) void; pub extern "opengl32" fn glTexCoord3f(s: GLfloat, t: GLfloat, r: GLfloat) callconv(WINAPI) void; pub extern "opengl32" fn glTexCoord3fv(v: ?*const GLfloat) callconv(WINAPI) void; pub extern "opengl32" fn glTexCoord3i(s: GLint, t: GLint, r: GLint) callconv(WINAPI) void; pub extern "opengl32" fn glTexCoord3iv(v: ?*const GLint) callconv(WINAPI) void; pub extern "opengl32" fn glTexCoord3s(s: GLshort, t: GLshort, r: GLshort) callconv(WINAPI) void; pub extern "opengl32" fn glTexCoord3sv(v: ?*const GLshort) callconv(WINAPI) void; pub extern "opengl32" fn glTexCoord4d(s: GLdouble, t: GLdouble, r: GLdouble, q: GLdouble) callconv(WINAPI) void; pub extern "opengl32" fn glTexCoord4dv(v: ?*const GLdouble) callconv(WINAPI) void; pub extern "opengl32" fn glTexCoord4f(s: GLfloat, t: GLfloat, r: GLfloat, q: GLfloat) callconv(WINAPI) void; pub extern "opengl32" fn glTexCoord4fv(v: ?*const GLfloat) callconv(WINAPI) void; pub extern "opengl32" fn glTexCoord4i(s: GLint, t: GLint, r: GLint, q: GLint) callconv(WINAPI) void; pub extern "opengl32" fn glTexCoord4iv(v: ?*const GLint) callconv(WINAPI) void; pub extern "opengl32" fn glTexCoord4s(s: GLshort, t: GLshort, r: GLshort, q: GLshort) callconv(WINAPI) void; pub extern "opengl32" fn glTexCoord4sv(v: ?*const GLshort) callconv(WINAPI) void; pub extern "opengl32" fn glTexCoordPointer(size: GLint, type_0: GLenum, stride: GLsizei, pointer: ?*const GLvoid) callconv(WINAPI) void; pub extern "opengl32" fn glTexEnvf(target: GLenum, pname: GLenum, param: GLfloat) callconv(WINAPI) void; pub extern "opengl32" fn glTexEnvfv(target: GLenum, pname: GLenum, params: ?*const GLfloat) callconv(WINAPI) void; pub extern "opengl32" fn glTexEnvi(target: GLenum, pname: GLenum, param: GLint) callconv(WINAPI) void; pub extern "opengl32" fn glTexEnviv(target: GLenum, pname: GLenum, params: ?*const GLint) callconv(WINAPI) void; pub extern "opengl32" fn glTexGend(coord: GLenum, pname: GLenum, param: GLdouble) callconv(WINAPI) void; pub extern "opengl32" fn glTexGendv(coord: GLenum, pname: GLenum, params: ?*const GLdouble) callconv(WINAPI) void; pub extern "opengl32" fn glTexGenf(coord: GLenum, pname: GLenum, param: GLfloat) callconv(WINAPI) void; pub extern "opengl32" fn glTexGenfv(coord: GLenum, pname: GLenum, params: ?*const GLfloat) callconv(WINAPI) void; pub extern "opengl32" fn glTexGeni(coord: GLenum, pname: GLenum, param: GLint) callconv(WINAPI) void; pub extern "opengl32" fn glTexGeniv(coord: GLenum, pname: GLenum, params: ?*const GLint) callconv(WINAPI) void; pub extern "opengl32" fn glTexImage1D(target: GLenum, level: GLint, internalformat: GLint, width: GLsizei, border: GLint, format: GLenum, type_0: GLenum, pixels: ?*const GLvoid) callconv(WINAPI) void; pub extern "opengl32" fn glTexImage2D(target: GLenum, level: GLint, internalformat: GLint, width: GLsizei, height: GLsizei, border: GLint, format: GLenum, type_0: GLenum, pixels: ?*const GLvoid) callconv(WINAPI) void; pub extern "opengl32" fn glTexParameterf(target: GLenum, pname: GLenum, param: GLfloat) callconv(WINAPI) void; pub extern "opengl32" fn glTexParameterfv(target: GLenum, pname: GLenum, params: ?*const GLfloat) callconv(WINAPI) void; pub extern "opengl32" fn glTexParameteri(target: GLenum, pname: GLenum, param: GLint) callconv(WINAPI) void; pub extern "opengl32" fn glTexParameteriv(target: GLenum, pname: GLenum, params: ?*const GLint) callconv(WINAPI) void; pub extern "opengl32" fn glTexSubImage1D(target: GLenum, level: GLint, xoffset: GLint, width: GLsizei, format: GLenum, type_0: GLenum, pixels: ?*const GLvoid) callconv(WINAPI) void; pub extern "opengl32" fn glTexSubImage2D(target: GLenum, level: GLint, xoffset: GLint, yoffset: GLint, width: GLsizei, height: GLsizei, format: GLenum, type_0: GLenum, pixels: ?*const GLvoid) callconv(WINAPI) void; pub extern "opengl32" fn glTranslated(x: GLdouble, y: GLdouble, z: GLdouble) callconv(WINAPI) void; pub extern "opengl32" fn glTranslatef(x: GLfloat, y: GLfloat, z: GLfloat) callconv(WINAPI) void; pub extern "opengl32" fn glVertex2d(x: GLdouble, y: GLdouble) callconv(WINAPI) void; pub extern "opengl32" fn glVertex2dv(v: ?*const GLdouble) callconv(WINAPI) void; pub extern "opengl32" fn glVertex2f(x: GLfloat, y: GLfloat) callconv(WINAPI) void; pub extern "opengl32" fn glVertex2fv(v: ?*const GLfloat) callconv(WINAPI) void; pub extern "opengl32" fn glVertex2i(x: GLint, y: GLint) callconv(WINAPI) void; pub extern "opengl32" fn glVertex2iv(v: ?*const GLint) callconv(WINAPI) void; pub extern "opengl32" fn glVertex2s(x: GLshort, y: GLshort) callconv(WINAPI) void; pub extern "opengl32" fn glVertex2sv(v: ?*const GLshort) callconv(WINAPI) void; pub extern "opengl32" fn glVertex3d(x: GLdouble, y: GLdouble, z: GLdouble) callconv(WINAPI) void; pub extern "opengl32" fn glVertex3dv(v: ?*const GLdouble) callconv(WINAPI) void; pub extern "opengl32" fn glVertex3f(x: GLfloat, y: GLfloat, z: GLfloat) callconv(WINAPI) void; pub extern "opengl32" fn glVertex3fv(v: ?*const GLfloat) callconv(WINAPI) void; pub extern "opengl32" fn glVertex3i(x: GLint, y: GLint, z: GLint) callconv(WINAPI) void; pub extern "opengl32" fn glVertex3iv(v: ?*const GLint) callconv(WINAPI) void; pub extern "opengl32" fn glVertex3s(x: GLshort, y: GLshort, z: GLshort) callconv(WINAPI) void; pub extern "opengl32" fn glVertex3sv(v: ?*const GLshort) callconv(WINAPI) void; pub extern "opengl32" fn glVertex4d(x: GLdouble, y: GLdouble, z: GLdouble, w: GLdouble) callconv(WINAPI) void; pub extern "opengl32" fn glVertex4dv(v: ?*const GLdouble) callconv(WINAPI) void; pub extern "opengl32" fn glVertex4f(x: GLfloat, y: GLfloat, z: GLfloat, w: GLfloat) callconv(WINAPI) void; pub extern "opengl32" fn glVertex4fv(v: ?*const GLfloat) callconv(WINAPI) void; pub extern "opengl32" fn glVertex4i(x: GLint, y: GLint, z: GLint, w: GLint) callconv(WINAPI) void; pub extern "opengl32" fn glVertex4iv(v: ?*const GLint) callconv(WINAPI) void; pub extern "opengl32" fn glVertex4s(x: GLshort, y: GLshort, z: GLshort, w: GLshort) callconv(WINAPI) void; pub extern "opengl32" fn glVertex4sv(v: ?*const GLshort) callconv(WINAPI) void; pub extern "opengl32" fn glVertexPointer(size: GLint, type_0: GLenum, stride: GLsizei, pointer: ?*const GLvoid) callconv(WINAPI) void; pub extern "opengl32" fn glViewport(x: GLint, y: GLint, width: GLsizei, height: GLsizei) callconv(WINAPI) void;
win32_gl.zig
const uefi = @import("std").os.uefi; const Event = uefi.Event; const Guid = uefi.Guid; const Handle = uefi.Handle; const Status = uefi.Status; const TableHeader = uefi.tables.TableHeader; const DevicePathProtocol = uefi.protocols.DevicePathProtocol; /// Boot services are services provided by the system's firmware until the operating system takes /// over control over the hardware by calling exitBootServices. /// /// Boot Services must not be used after exitBootServices has been called. The only exception is /// getMemoryMap, which may be used after the first unsuccessful call to exitBootServices. /// After successfully calling exitBootServices, system_table.console_in_handle, system_table.con_in, /// system_table.console_out_handle, system_table.con_out, system_table.standard_error_handle, /// system_table.std_err, and system_table.boot_services should be set to null. After setting these /// attributes to null, system_table.hdr.crc32 must be recomputed. /// /// As the boot_services table may grow with new UEFI versions, it is important to check hdr.header_size. pub const BootServices = extern struct { hdr: TableHeader, /// Raises a task's priority level and returns its previous level. raiseTpl: fn (new_tpl: usize) callconv(.C) usize, /// Restores a task's priority level to its previous value. restoreTpl: fn (old_tpl: usize) callconv(.C) void, /// Allocates memory pages from the system. allocatePages: fn (alloc_type: AllocateType, mem_type: MemoryType, pages: usize, memory: *[*]align(4096) u8) callconv(.C) Status, /// Frees memory pages. freePages: fn (memory: [*]align(4096) u8, pages: usize) callconv(.C) Status, /// Returns the current memory map. getMemoryMap: fn (mmap_size: *usize, mmap: [*]MemoryDescriptor, mapKey: *usize, descriptor_size: *usize, descriptor_version: *u32) callconv(.C) Status, /// Allocates pool memory. allocatePool: fn (pool_type: MemoryType, size: usize, buffer: *[*]align(8) u8) callconv(.C) Status, /// Returns pool memory to the system. freePool: fn (buffer: [*]align(8) u8) callconv(.C) Status, /// Creates an event. createEvent: fn (type: u32, notify_tpl: usize, notify_func: ?fn (Event, ?*anyopaque) callconv(.C) void, notifyCtx: ?*const anyopaque, event: *Event) callconv(.C) Status, /// Sets the type of timer and the trigger time for a timer event. setTimer: fn (event: Event, type: TimerDelay, triggerTime: u64) callconv(.C) Status, /// Stops execution until an event is signaled. waitForEvent: fn (event_len: usize, events: [*]const Event, index: *usize) callconv(.C) Status, /// Signals an event. signalEvent: fn (event: Event) callconv(.C) Status, /// Closes an event. closeEvent: fn (event: Event) callconv(.C) Status, /// Checks whether an event is in the signaled state. checkEvent: fn (event: Event) callconv(.C) Status, /// Installs a protocol interface on a device handle. If the handle does not exist, it is created /// and added to the list of handles in the system. installMultipleProtocolInterfaces() /// performs more error checking than installProtocolInterface(), so its use is recommended over this. installProtocolInterface: fn (handle: Handle, protocol: *align(8) const Guid, interface_type: EfiInterfaceType, interface: *anyopaque) callconv(.C) Status, /// Reinstalls a protocol interface on a device handle reinstallProtocolInterface: fn (handle: Handle, protocol: *align(8) const Guid, old_interface: *anyopaque, new_interface: *anyopaque) callconv(.C) Status, /// Removes a protocol interface from a device handle. Usage of /// uninstallMultipleProtocolInterfaces is recommended over this. uninstallProtocolInterface: fn (handle: Handle, protocol: *align(8) const Guid, interface: *anyopaque) callconv(.C) Status, /// Queries a handle to determine if it supports a specified protocol. handleProtocol: fn (handle: Handle, protocol: *align(8) const Guid, interface: *?*anyopaque) callconv(.C) Status, reserved: *anyopaque, /// Creates an event that is to be signaled whenever an interface is installed for a specified protocol. registerProtocolNotify: fn (protocol: *align(8) const Guid, event: Event, registration: **anyopaque) callconv(.C) Status, /// Returns an array of handles that support a specified protocol. locateHandle: fn (search_type: LocateSearchType, protocol: ?*align(8) const Guid, search_key: ?*const anyopaque, bufferSize: *usize, buffer: [*]Handle) callconv(.C) Status, /// Locates the handle to a device on the device path that supports the specified protocol locateDevicePath: fn (protocols: *align(8) const Guid, device_path: **const DevicePathProtocol, device: *?Handle) callconv(.C) Status, /// Adds, updates, or removes a configuration table entry from the EFI System Table. installConfigurationTable: fn (guid: *align(8) const Guid, table: ?*anyopaque) callconv(.C) Status, /// Loads an EFI image into memory. loadImage: fn (boot_policy: bool, parent_image_handle: Handle, device_path: ?*const DevicePathProtocol, source_buffer: ?[*]const u8, source_size: usize, imageHandle: *?Handle) callconv(.C) Status, /// Transfers control to a loaded image's entry point. startImage: fn (image_handle: Handle, exit_data_size: ?*usize, exit_data: ?*[*]u16) callconv(.C) Status, /// Terminates a loaded EFI image and returns control to boot services. exit: fn (image_handle: Handle, exit_status: Status, exit_data_size: usize, exit_data: ?*const anyopaque) callconv(.C) Status, /// Unloads an image. unloadImage: fn (image_handle: Handle) callconv(.C) Status, /// Terminates all boot services. exitBootServices: fn (image_handle: Handle, map_key: usize) callconv(.C) Status, /// Returns a monotonically increasing count for the platform. getNextMonotonicCount: fn (count: *u64) callconv(.C) Status, /// Induces a fine-grained stall. stall: fn (microseconds: usize) callconv(.C) Status, /// Sets the system's watchdog timer. setWatchdogTimer: fn (timeout: usize, watchdogCode: u64, data_size: usize, watchdog_data: ?[*]const u16) callconv(.C) Status, /// Connects one or more drives to a controller. connectController: fn (controller_handle: Handle, driver_image_handle: ?Handle, remaining_device_path: ?*DevicePathProtocol, recursive: bool) callconv(.C) Status, // Disconnects one or more drivers from a controller disconnectController: fn (controller_handle: Handle, driver_image_handle: ?Handle, child_handle: ?Handle) callconv(.C) Status, /// Queries a handle to determine if it supports a specified protocol. openProtocol: fn (handle: Handle, protocol: *align(8) const Guid, interface: *?*anyopaque, agent_handle: ?Handle, controller_handle: ?Handle, attributes: OpenProtocolAttributes) callconv(.C) Status, /// Closes a protocol on a handle that was opened using openProtocol(). closeProtocol: fn (handle: Handle, protocol: *align(8) const Guid, agentHandle: Handle, controller_handle: ?Handle) callconv(.C) Status, /// Retrieves the list of agents that currently have a protocol interface opened. openProtocolInformation: fn (handle: Handle, protocol: *align(8) const Guid, entry_buffer: *[*]ProtocolInformationEntry, entry_count: *usize) callconv(.C) Status, /// Retrieves the list of protocol interface GUIDs that are installed on a handle in a buffer allocated from pool. protocolsPerHandle: fn (handle: Handle, protocol_buffer: *[*]*align(8) const Guid, protocol_buffer_count: *usize) callconv(.C) Status, /// Returns an array of handles that support the requested protocol in a buffer allocated from pool. locateHandleBuffer: fn (search_type: LocateSearchType, protocol: ?*align(8) const Guid, search_key: ?*const anyopaque, num_handles: *usize, buffer: *[*]Handle) callconv(.C) Status, /// Returns the first protocol instance that matches the given protocol. locateProtocol: fn (protocol: *align(8) const Guid, registration: ?*const anyopaque, interface: *?*anyopaque) callconv(.C) Status, /// Installs one or more protocol interfaces into the boot services environment installMultipleProtocolInterfaces: fn (handle: *Handle, ...) callconv(.C) Status, /// Removes one or more protocol interfaces into the boot services environment uninstallMultipleProtocolInterfaces: fn (handle: *Handle, ...) callconv(.C) Status, /// Computes and returns a 32-bit CRC for a data buffer. calculateCrc32: fn (data: [*]const u8, data_size: usize, *u32) callconv(.C) Status, /// Copies the contents of one buffer to another buffer copyMem: fn (dest: [*]u8, src: [*]const u8, len: usize) callconv(.C) void, /// Fills a buffer with a specified value setMem: fn (buffer: [*]u8, size: usize, value: u8) callconv(.C) void, /// Creates an event in a group. createEventEx: fn (type: u32, notify_tpl: usize, notify_func: EfiEventNotify, notify_ctx: *const anyopaque, event_group: *align(8) const Guid, event: *Event) callconv(.C) Status, /// Opens a protocol with a structure as the loaded image for a UEFI application pub fn openProtocolSt(self: *BootServices, comptime protocol: type, handle: Handle) !*protocol { if (!@hasDecl(protocol, "guid")) @compileError("Protocol is missing guid!"); var ptr: ?*protocol = undefined; try self.openProtocol( handle, &protocol.guid, @ptrCast(*?*anyopaque, &ptr), // Invoking handle (loaded image) uefi.handle, // Control handle (null as not a driver) null, uefi.tables.OpenProtocolAttributes{ .by_handle_protocol = true }, ).err(); return ptr.?; } pub const signature: u64 = 0x56524553544f4f42; pub const event_timer: u32 = 0x80000000; pub const event_runtime: u32 = 0x40000000; pub const event_notify_wait: u32 = 0x00000100; pub const event_notify_signal: u32 = 0x00000200; pub const event_signal_exit_boot_services: u32 = 0x00000201; pub const event_signal_virtual_address_change: u32 = 0x00000202; pub const tpl_application: usize = 4; pub const tpl_callback: usize = 8; pub const tpl_notify: usize = 16; pub const tpl_high_level: usize = 31; }; pub const EfiEventNotify = fn (event: Event, ctx: *anyopaque) callconv(.C) void; pub const TimerDelay = enum(u32) { TimerCancel, TimerPeriodic, TimerRelative, }; pub const MemoryType = enum(u32) { ReservedMemoryType, LoaderCode, LoaderData, BootServicesCode, BootServicesData, RuntimeServicesCode, RuntimeServicesData, ConventionalMemory, UnusableMemory, ACPIReclaimMemory, ACPIMemoryNVS, MemoryMappedIO, MemoryMappedIOPortSpace, PalCode, PersistentMemory, MaxMemoryType, _, }; pub const MemoryDescriptor = extern struct { type: MemoryType, padding: u32, physical_start: u64, virtual_start: u64, number_of_pages: usize, attribute: packed struct { uc: bool, wc: bool, wt: bool, wb: bool, uce: bool, _pad1: u3, _pad2: u4, wp: bool, rp: bool, xp: bool, nv: bool, more_reliable: bool, ro: bool, sp: bool, cpu_crypto: bool, _pad3: u4, _pad4: u32, _pad5: u7, memory_runtime: bool, }, }; pub const LocateSearchType = enum(u32) { AllHandles, ByRegisterNotify, ByProtocol, }; pub const OpenProtocolAttributes = packed struct { by_handle_protocol: bool = false, get_protocol: bool = false, test_protocol: bool = false, by_child_controller: bool = false, by_driver: bool = false, exclusive: bool = false, _pad: u26 = 0, }; pub const ProtocolInformationEntry = extern struct { agent_handle: ?Handle, controller_handle: ?Handle, attributes: OpenProtocolAttributes, open_count: u32, }; pub const EfiInterfaceType = enum(u32) { EfiNativeInterface, }; pub const AllocateType = enum(u32) { AllocateAnyPages, AllocateMaxAddress, AllocateAddress, };
lib/std/os/uefi/tables/boot_services.zig
pub const Head = \\ <!DOCTYPE html> \\ <html> \\ \\ <head> \\ <meta http-equiv="Content-Type" content="text/html; charset=utf-8"> \\ <meta name="viewport" content="width=device-width, initial-scale=1"> \\ <title>{}</title> \\ <style> \\ header { \\ display: flex; \\ flex-direction: row; \\ flex-shrink: 0; \\ width: 100%; \\ padding: 0 100px; \\ max-width: 1300px; \\ align-items: center; \\ margin: 0 auto; \\ height: 75px \\ } \\ \\ header .nav { \\ margin-left: 30px; \\ font-size: 14px \\ } \\ \\ header .logo { \\ display: flex \\ } \\ \\ header .logo img { \\ width: 25px; \\ height: 25px; \\ margin-right: 20px \\ } \\ \\ @media (max-width:850px) { \\ header .logo img { \\ width: 20px; \\ height: 20px; \\ margin-right: 10px \\ } \\ \\ header { \\ padding: 0 10% \\ } \\ \\ header .nav { \\ margin-left: 15px; \\ font-size: 14px \\ } \\ } \\ \\ @media (max-width:350px) { \\ header .logo img { \\ width: 20px; \\ height: 20px; \\ margin-right: 5px \\ } \\ \\ header { \\ padding: 0 10% \\ } \\ \\ header .nav { \\ margin-left: 10px; \\ font-size: 12px \\ } \\ } \\ \\ footer { \\ display: flex; \\ flex-shrink: 0; \\ align-items: center; \\ max-width: 1300px; \\ padding: 75px 100px; \\ margin: 0 auto \\ } \\ \\ footer, \\ footer .footer-inner { \\ width: 100% \\ } \\ \\ footer .footer-inner .logo img { \\ width: 25px; \\ height: 25px; \\ margin-right: 20px \\ } \\ \\ footer .footer-inner .footer-sections { \\ display: flex; \\ flex-direction: row \\ } \\ \\ footer .footer-inner .footer-sections .footer-links { \\ display: flex; \\ flex-direction: column; \\ margin-top: 40px; \\ min-width: 170px \\ } \\ \\ footer .footer-inner .footer-sections .footer-links>* { \\ margin-bottom: 20px \\ } \\ \\ footer .footer-inner .footer-sections .footer-links:last-child { \\ margin-bottom: 0 \\ } \\ \\ footer .footer-inner .footer-sections .footer-links>h3 { \\ font-size: 15px \\ } \\ \\ footer .footer-inner .footer-sections .footer-links>a { \\ font-size: 14px \\ } \\ \\ @media (max-width:850px) { \\ footer { \\ padding: 8.8% 10% \\ } \\ \\ footer .footer-inner .footer-sections .footer-links { \\ min-width: 120px \\ } \\ } \\ \\ :root { \\ --color-shadow: rgba(0, 0, 0, 0.15); \\ --color-accent: #695fdf; \\ --color-light: #f3f6f7; \\ --color-medium: #d2d2d2; \\ --color-dark: #2c3d51 \\ } \\ \\ body, \\ html { \\ position: relative; \\ height: 100% \\ } \\ \\ body { \\ color: var(--color-dark); \\ font-family: Open Sans, sans-serif; \\ margin: 0; \\ padding: 0 \\ } \\ \\ body>div, \\ body>div>div { \\ height: 100% \\ } \\ \\ body>div, \\ body>div>div, \\ main { \\ display: flex; \\ flex-direction: column; \\ position: relative \\ } \\ \\ main { \\ flex-grow: 1; \\ flex-shrink: 0 \\ } \\ \\ * { \\ box-sizing: border-box \\ } \\ \\ h1, \\ h2, \\ h3, \\ h4 { \\ font-family: Lato, sans-serif \\ } \\ \\ h1 { \\ font-size: 2em; \\ font-weight: 500; \\ margin: 0 0 16px \\ } \\ \\ h2 { \\ font-size: 1.5em \\ } \\ \\ h2, \\ h3 { \\ font-weight: 500; \\ margin: 0 \\ } \\ \\ h3, \\ h4 { \\ font-size: 1.2em \\ } \\ \\ h4 { \\ font-weight: 400; \\ margin: 0 \\ } \\ \\ p { \\ font-weight: 400; \\ margin: 0 0 32px \\ } \\ \\ code, \\ p { \\ font-size: 1em; \\ line-height: 1.5em \\ } \\ \\ code { \\ font-family: Source Code Pro, monospace \\ } \\ \\ pre { \\ background-color: #f9f9f9; \\ border-radius: 4px; \\ padding: 16px; \\ margin: 32px 0 \\ } \\ \\ span { \\ font-weight: 400; \\ line-height: 1.5em; \\ margin: 0 \\ } \\ \\ label { \\ font-size: 12px; \\ font-weight: 500; \\ letter-spacing: 1px; \\ text-transform: uppercase; \\ margin: 0 \\ } \\ \\ a { \\ text-decoration: none; \\ color: var(--color-dark) \\ } \\ \\ a:hover { \\ cursor: pointer; \\ opacity: .7 \\ } \\ \\ button { \\ font-size: 14px; \\ font-weight: 500; \\ display: block; \\ width: 100%; \\ border: none; \\ background-color: transparent; \\ margin: 0; \\ padding: 0 \\ } \\ \\ button:hover, \\ input[type=submit]:hover { \\ cursor: pointer; \\ opacity: .7 \\ } \\ \\ input, \\ textarea { \\ font-size: 1em; \\ font-weight: 400; \\ line-height: 1.5em; \\ margin: 0; \\ background-color: transparent; \\ -webkit-appearance: none; \\ -moz-appearance: none; \\ appearance: none; \\ box-sizing: border-box; \\ font-family: Open Sans, sans-serif \\ } \\ \\ .spacer { \\ flex: 1 1 \\ } \\ \\ .section-inner { \\ display: flex; \\ flex-direction: column; \\ width: 100%; \\ align-items: stretch; \\ max-width: 1300px; \\ padding: 75px 100px; \\ margin: 0 auto \\ } \\ \\ .section-inner>h2 { \\ margin-bottom: 50px \\ } \\ \\ @media (max-width:850px) { \\ section .section-inner { \\ padding: 8.8% 10%; \\ flex-direction: column \\ } \\ \\ .section-inner>h2 { \\ margin-top: 8%; \\ margin-bottom: 5% \\ } \\ } \\ \\ section.hero-content>* { \\ align-items: center \\ } \\ \\ .hero-content .title-letters { \\ display: flex; \\ flex-direction: row; \\ max-width: 100% \\ } \\ \\ .hero-content .title-letter { \\ margin-left: 10px; \\ margin-right: 10px; \\ height: 100px \\ } \\ \\ .hero-content p { \\ margin-top: 20px; \\ font-weight: 400; \\ font-size: 21px; \\ margin-bottom: 20px; \\ text-align: center \\ } \\ \\ .hero-content .badges { \\ display: flex; \\ flex-wrap: wrap; \\ justify-content: center; \\ margin-bottom: 75px \\ } \\ \\ .hero-content .badges>* { \\ margin-right: 10px \\ } \\ \\ .hero-content .badges:last-child { \\ margin-right: 0 \\ } \\ \\ .card-collection { \\ display: flex; \\ flex-direction: row; \\ justify-content: space-around \\ } \\ \\ .card-collection>* { \\ display: flex; \\ flex-direction: row; \\ margin-right: 10px; \\ margin-left: 10px; \\ max-width: 40%; \\ flex: 1 1 \\ } \\ \\ .card-collection:first-child { \\ margin-left: 0 \\ } \\ \\ .card-collection:last-child { \\ margin-right: 0 \\ } \\ \\ .card-collection .card { \\ display: flex; \\ flex-direction: column; \\ background: #fff; \\ color: var(--color-dark); \\ box-shadow: 0 0 6px 0 var(--color-shadow); \\ border-radius: 10px; \\ padding: 25px; \\ flex: 1 1 \\ } \\ \\ .card-collection .card h3 { \\ margin-bottom: 10px \\ } \\ \\ .card-collection .card span { \\ font-size: 15px; \\ line-height: 200% \\ } \\ \\ .card-collection .card span a { \\ color: var(--color-accent) \\ } \\ \\ .button-group { \\ display: flex; \\ margin-top: 50px; \\ text-align: center \\ } \\ \\ .button-group>* { \\ margin-right: 20px \\ } \\ \\ .button-group:last-child { \\ margin-right: 0 \\ } \\ \\ .button-group .primary { \\ background-color: var(--color-dark); \\ color: #fff \\ } \\ \\ .button-group .primary, \\ .button-group .secondary { \\ font-size: 14px; \\ border: 2px solid var(--color-dark); \\ border-radius: 8px; \\ font-weight: 700; \\ width: auto; \\ flex-shrink: 0; \\ text-transform: uppercase; \\ flex: 1 1; \\ margin-left: 0; \\ margin-top: 10px; \\ padding: 15px 20px \\ } \\ \\ .button-group .secondary { \\ background-color: clear; \\ color: var(--color-dark) \\ } \\ \\ section.featured-projects { \\ background-color: var(--color-light) \\ } \\ \\ section.blog-posts { \\ background-color: #fff; \\ background-color: var(--color-light) \\ } \\ \\ section.blog-posts>.section-inner { \\ padding: 0 100px 75px \\ } \\ \\ section.cross-platform { \\ background-color: var(--color-dark); \\ color: #fff \\ } \\ \\ section.cross-platform>.section-inner { \\ padding: 75px 100px 35px \\ } \\ \\ section.cross-platform .section-inner>h2 { \\ margin-bottom: 10px \\ } \\ \\ .code-blocks { \\ display: flex; \\ flex-direction: row; \\ justify-content: space-around; \\ flex-wrap: wrap \\ } \\ \\ .code-blocks>* { \\ display: flex; \\ flex-direction: row; \\ margin: 40px 20px; \\ flex: 1 1; \\ min-width: 40% \\ } \\ \\ .code-blocks:first-child { \\ margin-left: 0 \\ } \\ \\ .code-blocks:last-child { \\ margin-right: 0 \\ } \\ \\ .code-blocks .code-block { \\ display: flex; \\ flex-direction: column; \\ background: #fff; \\ color: var(--color-dark); \\ box-shadow: 0 0 6px 0 var(--color-shadow); \\ border-radius: 10px; \\ overflow: hidden \\ } \\ \\ .code-blocks .code-block pre { \\ margin: 10px; \\ font-size: 14px \\ } \\ \\ .code-blocks .code-block>code { \\ background-color: var(--color-light); \\ padding: 10px 10px 10px 18px; \\ font-size: 14px; \\ font-weight: 700; \\ border-bottom: 1px solid var(--color-medium) \\ } \\ \\ @media (max-width:850px) { \\ section.blog-posts>.section-inner { \\ padding: 0 10% 8.8% \\ } \\ \\ section.cross-platform>.section-inner { \\ padding: 8.8% 10% \\ } \\ \\ .hero-content .title-letter { \\ margin-left: 5px; \\ margin-right: 5px; \\ height: 50px \\ } \\ \\ .hero-content p { \\ font-size: 16px \\ } \\ \\ .card-collection { \\ flex-direction: column; \\ align-items: stretch \\ } \\ \\ .card-collection>* { \\ margin: 20px 0; \\ max-width: 100% \\ } \\ \\ .card-collection:first-child { \\ margin-top: 0 \\ } \\ \\ .card-collection:last-child { \\ margin-bottom: 0 \\ } \\ \\ .button-group { \\ align-self: stretch; \\ margin-top: 25px; \\ flex-direction: column \\ } \\ \\ .button-group>* { \\ margin-right: 0; \\ margin-top: 20px \\ } \\ \\ .button-group:last-child { \\ margin-top: 0 \\ } \\ \\ .code-blocks>* { \\ margin: 20px 0; \\ min-width: 100% \\ } \\ \\ .hero-content .badges { \\ margin-bottom: 8.8% \\ } \\ } \\ \\ .doc-pills { \\ display: flex; \\ flex-wrap: wrap; \\ flex-direction: row \\ } \\ \\ .doc-pill { \\ margin-right: 10px; \\ margin-bottom: 10px; \\ padding: 8px 25px; \\ background-color: #fff; \\ border-radius: 8px; \\ color: var(--color-dark); \\ border: 1px solid var(--color-dark) \\ } \\ \\ .doc-pill.active:hover { \\ opacity: 1 \\ } \\ \\ .doc-pill.active { \\ background-color: var(--color-dark); \\ border: 1px solid var(--color-dark); \\ color: #fff \\ } \\ \\ section.docs-header .section-inner { \\ max-width: 1000px \\ } \\ \\ section.mdx-content .section-inner { \\ padding: 0 100px 75px; \\ max-width: 1000px \\ } \\ \\ section.docs-header p a, \\ section.mdx-content p a { \\ color: var(--color-accent) \\ } \\ \\ .mdx-content hr { \\ border: 0; \\ height: 1px; \\ background: #ccc; \\ margin-bottom: 40px \\ } \\ \\ .docs-header p, \\ .mdx-content p { \\ line-height: 180% \\ } \\ \\ .mdx-content p+ul { \\ margin-top: -10px \\ } \\ \\ .mdx-content li { \\ list-style: none; \\ line-height: 180% \\ } \\ \\ .mdx-content li+li { \\ margin-top: 10px \\ } \\ \\ .mdx-content li:before { \\ content: "-"; \\ margin-left: -20px; \\ margin-right: 10px \\ } \\ \\ .mdx-content li code, \\ .mdx-content p code { \\ color: var(--color-accent) \\ } \\ \\ .mdx-content li code:after, \\ .mdx-content li code:before, \\ .mdx-content p code:after, \\ .mdx-content p code:before { \\ content: "`" \\ } \\ \\ .mdx-content .code-block { \\ margin-bottom: 50px \\ } \\ \\ .mdx-content .code-block, \\ .mdx-content .code-block .code-wrapper { \\ display: flex; \\ flex-direction: column; \\ background-color: #292c33; \\ color: var(--color-dark); \\ box-shadow: 0 0 6px 0 var(--color-shadow); \\ border-radius: 10px; \\ overflow: hidden \\ } \\ \\ .mdx-content .code-block .code-wrapper { \\ padding: 10px \\ } \\ \\ .mdx-content .code-block pre { \\ margin: 0; \\ border-radius: 0; \\ font-size: 14px \\ } \\ \\ .mdx-content .code-block>code { \\ background-color: #292c33; \\ padding: 10px 10px 10px 18px; \\ font-size: 14px; \\ font-weight: 700; \\ border-bottom: 1px solid #666; \\ color: #fff \\ } \\ \\ @media (max-width:850px) { \\ section.mdx-content>.section-inner { \\ padding: 0 10% 8.8% \\ } \\ } \\ </style> \\ </head> ;
src/cmd/docs/html.zig
const std = @import("std"); pub fn NodeId(comptime T: type) type { return struct { index: usize, const Self = @This(); pub fn getType(_: Self) T { return T; } }; } pub fn Pool(comptime node_byte_size: usize) type { return struct { nodes: ?[*]u8, node_count: usize, capacity: usize, node_byte_size: usize = node_byte_size, bytes_to_mmap: usize, const Self = @This(); const PoolError = error{NotInitialized}; pub fn init(total_nodes: usize) !Self { const bytes_per_page = std.mem.page_size; const node_bytes = node_byte_size * total_nodes; const leftover = node_bytes % bytes_per_page; const bytes_to_mmap = if (leftover == 0) blk: { break :blk node_bytes; } else blk: { break :blk node_bytes + bytes_per_page - leftover; }; var nodes = try std.os.mmap(null, bytes_to_mmap, 1 | 2, 0x0002 | 0x0020, 0, 0); return Self{ .nodes = @ptrCast([*]u8, nodes), .node_count = 0, .capacity = bytes_to_mmap / node_byte_size, .bytes_to_mmap = bytes_to_mmap, }; } pub fn deinit(self: *Self) void { if (self.nodes) |nodes| { std.os.munmap(@alignCast(std.mem.page_size, nodes[0..self.bytes_to_mmap])); self.nodes = null; } } pub fn add(self: *Self, comptime T: type, node: T) PoolError!NodeId(T) { std.debug.assert(@sizeOf(T) <= node_byte_size); if (self.nodes) |nodes| { const node_id = self.reserve(T, 1); const node_data = std.mem.toBytes(node); var node_ptr = nodes + (node_id.index * node_byte_size); @memcpy(node_ptr, &node_data, @sizeOf(T)); return node_id; } return PoolError.NotInitialized; } pub fn get(self: *Self, comptime T: type, node_id: NodeId(T)) !T { std.debug.assert(@sizeOf(T) <= node_byte_size); if (self.nodes) |nodes| { const node_data = nodes + (node_id.index * node_byte_size); return std.mem.bytesToValue(T, @ptrCast(*[@sizeOf(T)]u8, node_data)); } return PoolError.NotInitialized; } fn reserve(self: *Self, comptime T: type, nodes: usize) NodeId(T) { const index = self.node_count; if (index < self.capacity) { self.node_count = index + nodes; return NodeId(T){ .index = index, }; } else { @panic("out of capacity. TODO: grow pool"); } } }; } test "init" { var pool = try Pool(32).init(1048); defer pool.deinit(); try std.testing.expectEqual(pool.node_count, 0); try std.testing.expectEqual(pool.node_byte_size, 32); try std.testing.expect(pool.nodes != null); } test "add/get" { var pool = try Pool(16).init(1048); defer pool.deinit(); const Foo = struct { bar: usize, }; const Bar = struct { foo: usize, wow: usize, }; const node_id1 = try pool.add(Foo, .{ .bar = 1 }); const node_id2 = try pool.add(Bar, .{ .foo = 1, .wow = 3 }); try std.testing.expectEqual(node_id1.index, 0); try std.testing.expectEqual(node_id2.index, 1); try std.testing.expectEqual(@TypeOf(node_id1), NodeId(Foo)); try std.testing.expectEqual(@TypeOf(node_id2), NodeId(Bar)); try std.testing.expectEqual(pool.node_count, 2); const foo = try pool.get(Foo, node_id1); try std.testing.expectEqual(foo.bar, 1); const bar = try pool.get(Bar, node_id2); try std.testing.expectEqual(bar.foo, 1); try std.testing.expectEqual(bar.wow, 3); }
src/pool.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 Str = []const u8; const int = i64; const util = @import("util.zig"); const gpa = util.gpa; const data = @embedFile("../data/day07.txt"); const Record = struct { pos: int, }; pub fn main() !void { var total: int = 0; const positions = blk: { var recs = List(int).init(gpa); var iter = tokenize(u8, data, "\r\n,"); while (iter.next()) |num| { if (num.len == 0) { continue; } const dist = try parseInt(int, num, 10); total += dist; try recs.append(dist); } break :blk recs.toOwnedSlice(); }; // The ideal part 1 position is the median, so sort and then // grab the middle value. If there are an even number of positions, // then any value between the two median values is a minimum. // In order for AoC to have a unique answer, we can assume that // either the number of positions is odd, or the two medians // have the same value. sort(int, positions, {}, comptime asc(int)); const part1_pos = positions[positions.len / 2]; var part1: int = 0; for (positions) |rec| { part1 += std.math.absInt(rec - part1_pos) catch unreachable; } // The ideal part 2 position is the average location, but that is probably // not an integer. The cost curve is not symmetric, so rounding to the // nearest integer may not be correct. But the best integer value must // be either the floor or ciel of the real average value, so we will // calculate and test both. const avg_min = @divTrunc(total, @intCast(int, positions.len)); const avg_max = @divTrunc(total + @intCast(int, positions.len) - 1, @intCast(int, positions.len)); var low_cost: int = 0; var high_cost: int = 0; for (positions) |it| { const low_diff = std.math.absInt(it - avg_min) catch unreachable; low_cost += @divExact(low_diff * (low_diff + 1), 2); const high_diff = std.math.absInt(it - avg_max) catch unreachable; high_cost += @divExact(high_diff * (high_diff + 1), 2); } const part2 = min(low_cost, high_cost); print("part1={}, part2={}\n", .{part1, part2}); } // 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 eql = std.mem.eql; const parseEnum = std.meta.stringToEnum; 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/day07.zig
const struct_gladGLversionStruct = extern struct { major: c_int, minor: c_int, }; const GLADloadproc = ?fn ([*c]const u8) callconv(.C) ?*anyopaque; extern var GLVersion: struct_gladGLversionStruct; pub extern fn gladLoadGL() c_int; extern fn gladLoadGLLoader(GLADloadproc) c_int; const khronos_int32_t = i32; const khronos_uint32_t = u32; const khronos_int64_t = i64; const khronos_uint64_t = u64; const khronos_int8_t = i8; const khronos_uint8_t = u8; const khronos_int16_t = c_short; const khronos_uint16_t = c_ushort; const khronos_intptr_t = c_longlong; const khronos_uintptr_t = c_ulonglong; const khronos_ssize_t = c_longlong; const khronos_usize_t = c_ulonglong; const khronos_float_t = f32; const khronos_utime_nanoseconds_t = khronos_uint64_t; const khronos_stime_nanoseconds_t = khronos_int64_t; const khronos_boolean_enum_t = enum(c_int) { KHRONOS_FALSE = 0, KHRONOS_TRUE = 1, KHRONOS_BOOLEAN_ENUM_FORCE_SIZE = 2147483647, _, }; const KHRONOS_FALSE = @enumToInt(khronos_boolean_enum_t.KHRONOS_FALSE); const KHRONOS_TRUE = @enumToInt(khronos_boolean_enum_t.KHRONOS_TRUE); const KHRONOS_BOOLEAN_ENUM_FORCE_SIZE = @enumToInt(khronos_boolean_enum_t.KHRONOS_BOOLEAN_ENUM_FORCE_SIZE); pub const GLenum = c_uint; pub const GLboolean = u8; pub const GLbitfield = c_uint; pub const GLvoid = anyopaque; pub const GLbyte = khronos_int8_t; pub const GLubyte = khronos_uint8_t; pub const GLshort = khronos_int16_t; pub const GLushort = khronos_uint16_t; pub const GLint = c_int; pub const GLuint = c_uint; pub const GLclampx = khronos_int32_t; pub const GLsizei = c_int; pub const GLfloat = khronos_float_t; pub const GLclampf = khronos_float_t; pub const GLdouble = f64; pub const GLclampd = f64; pub const GLeglClientBufferEXT = ?*anyopaque; pub const GLeglImageOES = ?*anyopaque; pub const GLchar = u8; pub const GLcharARB = u8; pub const GLhandleARB = c_uint; pub const GLhalf = khronos_uint16_t; pub const GLhalfARB = khronos_uint16_t; pub const GLfixed = khronos_int32_t; pub const GLintptr = khronos_intptr_t; pub const GLintptrARB = khronos_intptr_t; pub const GLsizeiptr = khronos_ssize_t; pub const GLsizeiptrARB = khronos_ssize_t; pub const GLint64 = khronos_int64_t; pub const GLint64EXT = khronos_int64_t; pub const GLuint64 = khronos_uint64_t; pub const GLuint64EXT = khronos_uint64_t; const struct___GLsync = opaque {}; const GLsync = ?*struct___GLsync; const struct__cl_context = opaque {}; const struct__cl_event = opaque {}; const GLDEBUGPROC = ?fn (GLenum, GLenum, GLuint, GLenum, GLsizei, [*c]const GLchar, ?*const anyopaque) callconv(.C) void; const GLDEBUGPROCARB = ?fn (GLenum, GLenum, GLuint, GLenum, GLsizei, [*c]const GLchar, ?*const anyopaque) callconv(.C) void; const GLDEBUGPROCKHR = ?fn (GLenum, GLenum, GLuint, GLenum, GLsizei, [*c]const GLchar, ?*const anyopaque) callconv(.C) void; const GLDEBUGPROCAMD = ?fn (GLuint, GLenum, GLenum, GLsizei, [*c]const GLchar, ?*anyopaque) callconv(.C) void; const GLhalfNV = c_ushort; const GLvdpauSurfaceNV = GLintptr; const GLVULKANPROCNV = ?fn () callconv(.C) void; extern var GLAD_GL_VERSION_1_0: c_int; const PFNGLCULLFACEPROC = ?fn (GLenum) callconv(.C) void; extern var glad_glCullFace: PFNGLCULLFACEPROC; const PFNGLFRONTFACEPROC = ?fn (GLenum) callconv(.C) void; extern var glad_glFrontFace: PFNGLFRONTFACEPROC; const PFNGLHINTPROC = ?fn (GLenum, GLenum) callconv(.C) void; extern var glad_glHint: PFNGLHINTPROC; const PFNGLLINEWIDTHPROC = ?fn (GLfloat) callconv(.C) void; extern var glad_glLineWidth: PFNGLLINEWIDTHPROC; const PFNGLPOINTSIZEPROC = ?fn (GLfloat) callconv(.C) void; extern var glad_glPointSize: PFNGLPOINTSIZEPROC; const PFNGLPOLYGONMODEPROC = ?fn (GLenum, GLenum) callconv(.C) void; extern var glad_glPolygonMode: PFNGLPOLYGONMODEPROC; const PFNGLSCISSORPROC = ?fn (GLint, GLint, GLsizei, GLsizei) callconv(.C) void; extern var glad_glScissor: PFNGLSCISSORPROC; const PFNGLTEXPARAMETERFPROC = ?fn (GLenum, GLenum, GLfloat) callconv(.C) void; extern var glad_glTexParameterf: PFNGLTEXPARAMETERFPROC; const PFNGLTEXPARAMETERFVPROC = ?fn (GLenum, GLenum, [*c]const GLfloat) callconv(.C) void; extern var glad_glTexParameterfv: PFNGLTEXPARAMETERFVPROC; const PFNGLTEXPARAMETERIPROC = ?fn (GLenum, GLenum, GLint) callconv(.C) void; extern var glad_glTexParameteri: PFNGLTEXPARAMETERIPROC; const PFNGLTEXPARAMETERIVPROC = ?fn (GLenum, GLenum, [*c]const GLint) callconv(.C) void; extern var glad_glTexParameteriv: PFNGLTEXPARAMETERIVPROC; const PFNGLTEXIMAGE1DPROC = ?fn (GLenum, GLint, GLint, GLsizei, GLint, GLenum, GLenum, ?*const anyopaque) callconv(.C) void; extern var glad_glTexImage1D: PFNGLTEXIMAGE1DPROC; const PFNGLTEXIMAGE2DPROC = ?fn (GLenum, GLint, GLint, GLsizei, GLsizei, GLint, GLenum, GLenum, ?*const anyopaque) callconv(.C) void; extern var glad_glTexImage2D: PFNGLTEXIMAGE2DPROC; const PFNGLDRAWBUFFERPROC = ?fn (GLenum) callconv(.C) void; extern var glad_glDrawBuffer: PFNGLDRAWBUFFERPROC; const PFNGLCLEARPROC = ?fn (GLbitfield) callconv(.C) void; extern var glad_glClear: PFNGLCLEARPROC; const PFNGLCLEARCOLORPROC = ?fn (GLfloat, GLfloat, GLfloat, GLfloat) callconv(.C) void; extern var glad_glClearColor: PFNGLCLEARCOLORPROC; const PFNGLCLEARSTENCILPROC = ?fn (GLint) callconv(.C) void; extern var glad_glClearStencil: PFNGLCLEARSTENCILPROC; const PFNGLCLEARDEPTHPROC = ?fn (GLdouble) callconv(.C) void; extern var glad_glClearDepth: PFNGLCLEARDEPTHPROC; const PFNGLSTENCILMASKPROC = ?fn (GLuint) callconv(.C) void; extern var glad_glStencilMask: PFNGLSTENCILMASKPROC; const PFNGLCOLORMASKPROC = ?fn (GLboolean, GLboolean, GLboolean, GLboolean) callconv(.C) void; extern var glad_glColorMask: PFNGLCOLORMASKPROC; const PFNGLDEPTHMASKPROC = ?fn (GLboolean) callconv(.C) void; extern var glad_glDepthMask: PFNGLDEPTHMASKPROC; const PFNGLDISABLEPROC = ?fn (GLenum) callconv(.C) void; extern var glad_glDisable: PFNGLDISABLEPROC; const PFNGLENABLEPROC = ?fn (GLenum) callconv(.C) void; extern var glad_glEnable: PFNGLENABLEPROC; const PFNGLFINISHPROC = ?fn () callconv(.C) void; extern var glad_glFinish: PFNGLFINISHPROC; const PFNGLFLUSHPROC = ?fn () callconv(.C) void; extern var glad_glFlush: PFNGLFLUSHPROC; const PFNGLBLENDFUNCPROC = ?fn (GLenum, GLenum) callconv(.C) void; extern var glad_glBlendFunc: PFNGLBLENDFUNCPROC; const PFNGLLOGICOPPROC = ?fn (GLenum) callconv(.C) void; extern var glad_glLogicOp: PFNGLLOGICOPPROC; const PFNGLSTENCILFUNCPROC = ?fn (GLenum, GLint, GLuint) callconv(.C) void; extern var glad_glStencilFunc: PFNGLSTENCILFUNCPROC; const PFNGLSTENCILOPPROC = ?fn (GLenum, GLenum, GLenum) callconv(.C) void; extern var glad_glStencilOp: PFNGLSTENCILOPPROC; const PFNGLDEPTHFUNCPROC = ?fn (GLenum) callconv(.C) void; extern var glad_glDepthFunc: PFNGLDEPTHFUNCPROC; const PFNGLPIXELSTOREFPROC = ?fn (GLenum, GLfloat) callconv(.C) void; extern var glad_glPixelStoref: PFNGLPIXELSTOREFPROC; const PFNGLPIXELSTOREIPROC = ?fn (GLenum, GLint) callconv(.C) void; extern var glad_glPixelStorei: PFNGLPIXELSTOREIPROC; const PFNGLREADBUFFERPROC = ?fn (GLenum) callconv(.C) void; extern var glad_glReadBuffer: PFNGLREADBUFFERPROC; const PFNGLREADPIXELSPROC = ?fn (GLint, GLint, GLsizei, GLsizei, GLenum, GLenum, ?*anyopaque) callconv(.C) void; extern var glad_glReadPixels: PFNGLREADPIXELSPROC; const PFNGLGETBOOLEANVPROC = ?fn (GLenum, [*c]GLboolean) callconv(.C) void; extern var glad_glGetBooleanv: PFNGLGETBOOLEANVPROC; const PFNGLGETDOUBLEVPROC = ?fn (GLenum, [*c]GLdouble) callconv(.C) void; extern var glad_glGetDoublev: PFNGLGETDOUBLEVPROC; const PFNGLGETERRORPROC = ?fn () callconv(.C) GLenum; extern var glad_glGetError: PFNGLGETERRORPROC; const PFNGLGETFLOATVPROC = ?fn (GLenum, [*c]GLfloat) callconv(.C) void; extern var glad_glGetFloatv: PFNGLGETFLOATVPROC; const PFNGLGETINTEGERVPROC = ?fn (GLenum, [*c]GLint) callconv(.C) void; extern var glad_glGetIntegerv: PFNGLGETINTEGERVPROC; const PFNGLGETSTRINGPROC = ?fn (GLenum) callconv(.C) [*c]const GLubyte; extern var glad_glGetString: PFNGLGETSTRINGPROC; const PFNGLGETTEXIMAGEPROC = ?fn (GLenum, GLint, GLenum, GLenum, ?*anyopaque) callconv(.C) void; extern var glad_glGetTexImage: PFNGLGETTEXIMAGEPROC; const PFNGLGETTEXPARAMETERFVPROC = ?fn (GLenum, GLenum, [*c]GLfloat) callconv(.C) void; extern var glad_glGetTexParameterfv: PFNGLGETTEXPARAMETERFVPROC; const PFNGLGETTEXPARAMETERIVPROC = ?fn (GLenum, GLenum, [*c]GLint) callconv(.C) void; extern var glad_glGetTexParameteriv: PFNGLGETTEXPARAMETERIVPROC; const PFNGLGETTEXLEVELPARAMETERFVPROC = ?fn (GLenum, GLint, GLenum, [*c]GLfloat) callconv(.C) void; extern var glad_glGetTexLevelParameterfv: PFNGLGETTEXLEVELPARAMETERFVPROC; const PFNGLGETTEXLEVELPARAMETERIVPROC = ?fn (GLenum, GLint, GLenum, [*c]GLint) callconv(.C) void; extern var glad_glGetTexLevelParameteriv: PFNGLGETTEXLEVELPARAMETERIVPROC; const PFNGLISENABLEDPROC = ?fn (GLenum) callconv(.C) GLboolean; extern var glad_glIsEnabled: PFNGLISENABLEDPROC; const PFNGLDEPTHRANGEPROC = ?fn (GLdouble, GLdouble) callconv(.C) void; extern var glad_glDepthRange: PFNGLDEPTHRANGEPROC; const PFNGLVIEWPORTPROC = ?fn (GLint, GLint, GLsizei, GLsizei) callconv(.C) void; extern var glad_glViewport: PFNGLVIEWPORTPROC; extern var GLAD_GL_VERSION_1_1: c_int; const PFNGLDRAWARRAYSPROC = ?fn (GLenum, GLint, GLsizei) callconv(.C) void; extern var glad_glDrawArrays: PFNGLDRAWARRAYSPROC; const PFNGLDRAWELEMENTSPROC = ?fn (GLenum, GLsizei, GLenum, ?*const anyopaque) callconv(.C) void; extern var glad_glDrawElements: PFNGLDRAWELEMENTSPROC; const PFNGLPOLYGONOFFSETPROC = ?fn (GLfloat, GLfloat) callconv(.C) void; extern var glad_glPolygonOffset: PFNGLPOLYGONOFFSETPROC; const PFNGLCOPYTEXIMAGE1DPROC = ?fn (GLenum, GLint, GLenum, GLint, GLint, GLsizei, GLint) callconv(.C) void; extern var glad_glCopyTexImage1D: PFNGLCOPYTEXIMAGE1DPROC; const PFNGLCOPYTEXIMAGE2DPROC = ?fn (GLenum, GLint, GLenum, GLint, GLint, GLsizei, GLsizei, GLint) callconv(.C) void; extern var glad_glCopyTexImage2D: PFNGLCOPYTEXIMAGE2DPROC; const PFNGLCOPYTEXSUBIMAGE1DPROC = ?fn (GLenum, GLint, GLint, GLint, GLint, GLsizei) callconv(.C) void; extern var glad_glCopyTexSubImage1D: PFNGLCOPYTEXSUBIMAGE1DPROC; const PFNGLCOPYTEXSUBIMAGE2DPROC = ?fn (GLenum, GLint, GLint, GLint, GLint, GLint, GLsizei, GLsizei) callconv(.C) void; extern var glad_glCopyTexSubImage2D: PFNGLCOPYTEXSUBIMAGE2DPROC; const PFNGLTEXSUBIMAGE1DPROC = ?fn (GLenum, GLint, GLint, GLsizei, GLenum, GLenum, ?*const anyopaque) callconv(.C) void; extern var glad_glTexSubImage1D: PFNGLTEXSUBIMAGE1DPROC; const PFNGLTEXSUBIMAGE2DPROC = ?fn (GLenum, GLint, GLint, GLint, GLsizei, GLsizei, GLenum, GLenum, ?*const anyopaque) callconv(.C) void; extern var glad_glTexSubImage2D: PFNGLTEXSUBIMAGE2DPROC; const PFNGLBINDTEXTUREPROC = ?fn (GLenum, GLuint) callconv(.C) void; extern var glad_glBindTexture: PFNGLBINDTEXTUREPROC; const PFNGLDELETETEXTURESPROC = ?fn (GLsizei, [*c]const GLuint) callconv(.C) void; extern var glad_glDeleteTextures: PFNGLDELETETEXTURESPROC; const PFNGLGENTEXTURESPROC = ?fn (GLsizei, [*c]GLuint) callconv(.C) void; extern var glad_glGenTextures: PFNGLGENTEXTURESPROC; const PFNGLISTEXTUREPROC = ?fn (GLuint) callconv(.C) GLboolean; extern var glad_glIsTexture: PFNGLISTEXTUREPROC; extern var GLAD_GL_VERSION_1_2: c_int; const PFNGLDRAWRANGEELEMENTSPROC = ?fn (GLenum, GLuint, GLuint, GLsizei, GLenum, ?*const anyopaque) callconv(.C) void; extern var glad_glDrawRangeElements: PFNGLDRAWRANGEELEMENTSPROC; const PFNGLTEXIMAGE3DPROC = ?fn (GLenum, GLint, GLint, GLsizei, GLsizei, GLsizei, GLint, GLenum, GLenum, ?*const anyopaque) callconv(.C) void; extern var glad_glTexImage3D: PFNGLTEXIMAGE3DPROC; const PFNGLTEXSUBIMAGE3DPROC = ?fn (GLenum, GLint, GLint, GLint, GLint, GLsizei, GLsizei, GLsizei, GLenum, GLenum, ?*const anyopaque) callconv(.C) void; extern var glad_glTexSubImage3D: PFNGLTEXSUBIMAGE3DPROC; const PFNGLCOPYTEXSUBIMAGE3DPROC = ?fn (GLenum, GLint, GLint, GLint, GLint, GLint, GLint, GLsizei, GLsizei) callconv(.C) void; extern var glad_glCopyTexSubImage3D: PFNGLCOPYTEXSUBIMAGE3DPROC; extern var GLAD_GL_VERSION_1_3: c_int; const PFNGLACTIVETEXTUREPROC = ?fn (GLenum) callconv(.C) void; extern var glad_glActiveTexture: PFNGLACTIVETEXTUREPROC; const PFNGLSAMPLECOVERAGEPROC = ?fn (GLfloat, GLboolean) callconv(.C) void; extern var glad_glSampleCoverage: PFNGLSAMPLECOVERAGEPROC; const PFNGLCOMPRESSEDTEXIMAGE3DPROC = ?fn (GLenum, GLint, GLenum, GLsizei, GLsizei, GLsizei, GLint, GLsizei, ?*const anyopaque) callconv(.C) void; extern var glad_glCompressedTexImage3D: PFNGLCOMPRESSEDTEXIMAGE3DPROC; const PFNGLCOMPRESSEDTEXIMAGE2DPROC = ?fn (GLenum, GLint, GLenum, GLsizei, GLsizei, GLint, GLsizei, ?*const anyopaque) callconv(.C) void; extern var glad_glCompressedTexImage2D: PFNGLCOMPRESSEDTEXIMAGE2DPROC; const PFNGLCOMPRESSEDTEXIMAGE1DPROC = ?fn (GLenum, GLint, GLenum, GLsizei, GLint, GLsizei, ?*const anyopaque) callconv(.C) void; extern var glad_glCompressedTexImage1D: PFNGLCOMPRESSEDTEXIMAGE1DPROC; const PFNGLCOMPRESSEDTEXSUBIMAGE3DPROC = ?fn (GLenum, GLint, GLint, GLint, GLint, GLsizei, GLsizei, GLsizei, GLenum, GLsizei, ?*const anyopaque) callconv(.C) void; extern var glad_glCompressedTexSubImage3D: PFNGLCOMPRESSEDTEXSUBIMAGE3DPROC; const PFNGLCOMPRESSEDTEXSUBIMAGE2DPROC = ?fn (GLenum, GLint, GLint, GLint, GLsizei, GLsizei, GLenum, GLsizei, ?*const anyopaque) callconv(.C) void; extern var glad_glCompressedTexSubImage2D: PFNGLCOMPRESSEDTEXSUBIMAGE2DPROC; const PFNGLCOMPRESSEDTEXSUBIMAGE1DPROC = ?fn (GLenum, GLint, GLint, GLsizei, GLenum, GLsizei, ?*const anyopaque) callconv(.C) void; extern var glad_glCompressedTexSubImage1D: PFNGLCOMPRESSEDTEXSUBIMAGE1DPROC; const PFNGLGETCOMPRESSEDTEXIMAGEPROC = ?fn (GLenum, GLint, ?*anyopaque) callconv(.C) void; extern var glad_glGetCompressedTexImage: PFNGLGETCOMPRESSEDTEXIMAGEPROC; extern var GLAD_GL_VERSION_1_4: c_int; const PFNGLBLENDFUNCSEPARATEPROC = ?fn (GLenum, GLenum, GLenum, GLenum) callconv(.C) void; extern var glad_glBlendFuncSeparate: PFNGLBLENDFUNCSEPARATEPROC; const PFNGLMULTIDRAWARRAYSPROC = ?fn (GLenum, [*c]const GLint, [*c]const GLsizei, GLsizei) callconv(.C) void; extern var glad_glMultiDrawArrays: PFNGLMULTIDRAWARRAYSPROC; const PFNGLMULTIDRAWELEMENTSPROC = ?fn (GLenum, [*c]const GLsizei, GLenum, [*c]const ?*const anyopaque, GLsizei) callconv(.C) void; extern var glad_glMultiDrawElements: PFNGLMULTIDRAWELEMENTSPROC; const PFNGLPOINTPARAMETERFPROC = ?fn (GLenum, GLfloat) callconv(.C) void; extern var glad_glPointParameterf: PFNGLPOINTPARAMETERFPROC; const PFNGLPOINTPARAMETERFVPROC = ?fn (GLenum, [*c]const GLfloat) callconv(.C) void; extern var glad_glPointParameterfv: PFNGLPOINTPARAMETERFVPROC; const PFNGLPOINTPARAMETERIPROC = ?fn (GLenum, GLint) callconv(.C) void; extern var glad_glPointParameteri: PFNGLPOINTPARAMETERIPROC; const PFNGLPOINTPARAMETERIVPROC = ?fn (GLenum, [*c]const GLint) callconv(.C) void; extern var glad_glPointParameteriv: PFNGLPOINTPARAMETERIVPROC; const PFNGLBLENDCOLORPROC = ?fn (GLfloat, GLfloat, GLfloat, GLfloat) callconv(.C) void; extern var glad_glBlendColor: PFNGLBLENDCOLORPROC; const PFNGLBLENDEQUATIONPROC = ?fn (GLenum) callconv(.C) void; extern var glad_glBlendEquation: PFNGLBLENDEQUATIONPROC; extern var GLAD_GL_VERSION_1_5: c_int; const PFNGLGENQUERIESPROC = ?fn (GLsizei, [*c]GLuint) callconv(.C) void; extern var glad_glGenQueries: PFNGLGENQUERIESPROC; const PFNGLDELETEQUERIESPROC = ?fn (GLsizei, [*c]const GLuint) callconv(.C) void; extern var glad_glDeleteQueries: PFNGLDELETEQUERIESPROC; const PFNGLISQUERYPROC = ?fn (GLuint) callconv(.C) GLboolean; extern var glad_glIsQuery: PFNGLISQUERYPROC; const PFNGLBEGINQUERYPROC = ?fn (GLenum, GLuint) callconv(.C) void; extern var glad_glBeginQuery: PFNGLBEGINQUERYPROC; const PFNGLENDQUERYPROC = ?fn (GLenum) callconv(.C) void; extern var glad_glEndQuery: PFNGLENDQUERYPROC; const PFNGLGETQUERYIVPROC = ?fn (GLenum, GLenum, [*c]GLint) callconv(.C) void; extern var glad_glGetQueryiv: PFNGLGETQUERYIVPROC; const PFNGLGETQUERYOBJECTIVPROC = ?fn (GLuint, GLenum, [*c]GLint) callconv(.C) void; extern var glad_glGetQueryObjectiv: PFNGLGETQUERYOBJECTIVPROC; const PFNGLGETQUERYOBJECTUIVPROC = ?fn (GLuint, GLenum, [*c]GLuint) callconv(.C) void; extern var glad_glGetQueryObjectuiv: PFNGLGETQUERYOBJECTUIVPROC; const PFNGLBINDBUFFERPROC = ?fn (GLenum, GLuint) callconv(.C) void; extern var glad_glBindBuffer: PFNGLBINDBUFFERPROC; const PFNGLDELETEBUFFERSPROC = ?fn (GLsizei, [*c]const GLuint) callconv(.C) void; extern var glad_glDeleteBuffers: PFNGLDELETEBUFFERSPROC; const PFNGLGENBUFFERSPROC = ?fn (GLsizei, [*c]GLuint) callconv(.C) void; extern var glad_glGenBuffers: PFNGLGENBUFFERSPROC; const PFNGLISBUFFERPROC = ?fn (GLuint) callconv(.C) GLboolean; extern var glad_glIsBuffer: PFNGLISBUFFERPROC; const PFNGLBUFFERDATAPROC = ?fn (GLenum, GLsizeiptr, ?*const anyopaque, GLenum) callconv(.C) void; extern var glad_glBufferData: PFNGLBUFFERDATAPROC; const PFNGLBUFFERSUBDATAPROC = ?fn (GLenum, GLintptr, GLsizeiptr, ?*const anyopaque) callconv(.C) void; extern var glad_glBufferSubData: PFNGLBUFFERSUBDATAPROC; const PFNGLGETBUFFERSUBDATAPROC = ?fn (GLenum, GLintptr, GLsizeiptr, ?*anyopaque) callconv(.C) void; extern var glad_glGetBufferSubData: PFNGLGETBUFFERSUBDATAPROC; const PFNGLMAPBUFFERPROC = ?fn (GLenum, GLenum) callconv(.C) ?*anyopaque; extern var glad_glMapBuffer: PFNGLMAPBUFFERPROC; const PFNGLUNMAPBUFFERPROC = ?fn (GLenum) callconv(.C) GLboolean; extern var glad_glUnmapBuffer: PFNGLUNMAPBUFFERPROC; const PFNGLGETBUFFERPARAMETERIVPROC = ?fn (GLenum, GLenum, [*c]GLint) callconv(.C) void; extern var glad_glGetBufferParameteriv: PFNGLGETBUFFERPARAMETERIVPROC; const PFNGLGETBUFFERPOINTERVPROC = ?fn (GLenum, GLenum, [*c]?*anyopaque) callconv(.C) void; extern var glad_glGetBufferPointerv: PFNGLGETBUFFERPOINTERVPROC; extern var GLAD_GL_VERSION_2_0: c_int; const PFNGLBLENDEQUATIONSEPARATEPROC = ?fn (GLenum, GLenum) callconv(.C) void; extern var glad_glBlendEquationSeparate: PFNGLBLENDEQUATIONSEPARATEPROC; const PFNGLDRAWBUFFERSPROC = ?fn (GLsizei, [*c]const GLenum) callconv(.C) void; extern var glad_glDrawBuffers: PFNGLDRAWBUFFERSPROC; const PFNGLSTENCILOPSEPARATEPROC = ?fn (GLenum, GLenum, GLenum, GLenum) callconv(.C) void; extern var glad_glStencilOpSeparate: PFNGLSTENCILOPSEPARATEPROC; const PFNGLSTENCILFUNCSEPARATEPROC = ?fn (GLenum, GLenum, GLint, GLuint) callconv(.C) void; extern var glad_glStencilFuncSeparate: PFNGLSTENCILFUNCSEPARATEPROC; const PFNGLSTENCILMASKSEPARATEPROC = ?fn (GLenum, GLuint) callconv(.C) void; extern var glad_glStencilMaskSeparate: PFNGLSTENCILMASKSEPARATEPROC; const PFNGLATTACHSHADERPROC = ?fn (GLuint, GLuint) callconv(.C) void; extern var glad_glAttachShader: PFNGLATTACHSHADERPROC; const PFNGLBINDATTRIBLOCATIONPROC = ?fn (GLuint, GLuint, [*c]const GLchar) callconv(.C) void; extern var glad_glBindAttribLocation: PFNGLBINDATTRIBLOCATIONPROC; const PFNGLCOMPILESHADERPROC = ?fn (GLuint) callconv(.C) void; extern var glad_glCompileShader: PFNGLCOMPILESHADERPROC; const PFNGLCREATEPROGRAMPROC = ?fn () callconv(.C) GLuint; extern var glad_glCreateProgram: PFNGLCREATEPROGRAMPROC; const PFNGLCREATESHADERPROC = ?fn (GLenum) callconv(.C) GLuint; extern var glad_glCreateShader: PFNGLCREATESHADERPROC; const PFNGLDELETEPROGRAMPROC = ?fn (GLuint) callconv(.C) void; extern var glad_glDeleteProgram: PFNGLDELETEPROGRAMPROC; const PFNGLDELETESHADERPROC = ?fn (GLuint) callconv(.C) void; extern var glad_glDeleteShader: PFNGLDELETESHADERPROC; const PFNGLDETACHSHADERPROC = ?fn (GLuint, GLuint) callconv(.C) void; extern var glad_glDetachShader: PFNGLDETACHSHADERPROC; const PFNGLDISABLEVERTEXATTRIBARRAYPROC = ?fn (GLuint) callconv(.C) void; extern var glad_glDisableVertexAttribArray: PFNGLDISABLEVERTEXATTRIBARRAYPROC; const PFNGLENABLEVERTEXATTRIBARRAYPROC = ?fn (GLuint) callconv(.C) void; extern var glad_glEnableVertexAttribArray: PFNGLENABLEVERTEXATTRIBARRAYPROC; const PFNGLGETACTIVEATTRIBPROC = ?fn (GLuint, GLuint, GLsizei, [*c]GLsizei, [*c]GLint, [*c]GLenum, [*c]GLchar) callconv(.C) void; extern var glad_glGetActiveAttrib: PFNGLGETACTIVEATTRIBPROC; const PFNGLGETACTIVEUNIFORMPROC = ?fn (GLuint, GLuint, GLsizei, [*c]GLsizei, [*c]GLint, [*c]GLenum, [*c]GLchar) callconv(.C) void; extern var glad_glGetActiveUniform: PFNGLGETACTIVEUNIFORMPROC; const PFNGLGETATTACHEDSHADERSPROC = ?fn (GLuint, GLsizei, [*c]GLsizei, [*c]GLuint) callconv(.C) void; extern var glad_glGetAttachedShaders: PFNGLGETATTACHEDSHADERSPROC; const PFNGLGETATTRIBLOCATIONPROC = ?fn (GLuint, [*c]const GLchar) callconv(.C) GLint; extern var glad_glGetAttribLocation: PFNGLGETATTRIBLOCATIONPROC; const PFNGLGETPROGRAMIVPROC = ?fn (GLuint, GLenum, [*c]GLint) callconv(.C) void; extern var glad_glGetProgramiv: PFNGLGETPROGRAMIVPROC; const PFNGLGETPROGRAMINFOLOGPROC = ?fn (GLuint, GLsizei, [*c]GLsizei, [*c]GLchar) callconv(.C) void; extern var glad_glGetProgramInfoLog: PFNGLGETPROGRAMINFOLOGPROC; const PFNGLGETSHADERIVPROC = ?fn (GLuint, GLenum, [*c]GLint) callconv(.C) void; extern var glad_glGetShaderiv: PFNGLGETSHADERIVPROC; const PFNGLGETSHADERINFOLOGPROC = ?fn (GLuint, GLsizei, [*c]GLsizei, [*c]GLchar) callconv(.C) void; extern var glad_glGetShaderInfoLog: PFNGLGETSHADERINFOLOGPROC; const PFNGLGETSHADERSOURCEPROC = ?fn (GLuint, GLsizei, [*c]GLsizei, [*c]GLchar) callconv(.C) void; extern var glad_glGetShaderSource: PFNGLGETSHADERSOURCEPROC; const PFNGLGETUNIFORMLOCATIONPROC = ?fn (GLuint, [*c]const GLchar) callconv(.C) GLint; extern var glad_glGetUniformLocation: PFNGLGETUNIFORMLOCATIONPROC; const PFNGLGETUNIFORMFVPROC = ?fn (GLuint, GLint, [*c]GLfloat) callconv(.C) void; extern var glad_glGetUniformfv: PFNGLGETUNIFORMFVPROC; const PFNGLGETUNIFORMIVPROC = ?fn (GLuint, GLint, [*c]GLint) callconv(.C) void; extern var glad_glGetUniformiv: PFNGLGETUNIFORMIVPROC; const PFNGLGETVERTEXATTRIBDVPROC = ?fn (GLuint, GLenum, [*c]GLdouble) callconv(.C) void; extern var glad_glGetVertexAttribdv: PFNGLGETVERTEXATTRIBDVPROC; const PFNGLGETVERTEXATTRIBFVPROC = ?fn (GLuint, GLenum, [*c]GLfloat) callconv(.C) void; extern var glad_glGetVertexAttribfv: PFNGLGETVERTEXATTRIBFVPROC; const PFNGLGETVERTEXATTRIBIVPROC = ?fn (GLuint, GLenum, [*c]GLint) callconv(.C) void; extern var glad_glGetVertexAttribiv: PFNGLGETVERTEXATTRIBIVPROC; const PFNGLGETVERTEXATTRIBPOINTERVPROC = ?fn (GLuint, GLenum, [*c]?*anyopaque) callconv(.C) void; extern var glad_glGetVertexAttribPointerv: PFNGLGETVERTEXATTRIBPOINTERVPROC; const PFNGLISPROGRAMPROC = ?fn (GLuint) callconv(.C) GLboolean; extern var glad_glIsProgram: PFNGLISPROGRAMPROC; const PFNGLISSHADERPROC = ?fn (GLuint) callconv(.C) GLboolean; extern var glad_glIsShader: PFNGLISSHADERPROC; const PFNGLLINKPROGRAMPROC = ?fn (GLuint) callconv(.C) void; extern var glad_glLinkProgram: PFNGLLINKPROGRAMPROC; const PFNGLSHADERSOURCEPROC = ?fn (GLuint, GLsizei, [*c]const [*c]const GLchar, [*c]const GLint) callconv(.C) void; extern var glad_glShaderSource: PFNGLSHADERSOURCEPROC; const PFNGLUSEPROGRAMPROC = ?fn (GLuint) callconv(.C) void; extern var glad_glUseProgram: PFNGLUSEPROGRAMPROC; const PFNGLUNIFORM1FPROC = ?fn (GLint, GLfloat) callconv(.C) void; extern var glad_glUniform1f: PFNGLUNIFORM1FPROC; const PFNGLUNIFORM2FPROC = ?fn (GLint, GLfloat, GLfloat) callconv(.C) void; extern var glad_glUniform2f: PFNGLUNIFORM2FPROC; const PFNGLUNIFORM3FPROC = ?fn (GLint, GLfloat, GLfloat, GLfloat) callconv(.C) void; extern var glad_glUniform3f: PFNGLUNIFORM3FPROC; const PFNGLUNIFORM4FPROC = ?fn (GLint, GLfloat, GLfloat, GLfloat, GLfloat) callconv(.C) void; extern var glad_glUniform4f: PFNGLUNIFORM4FPROC; const PFNGLUNIFORM1IPROC = ?fn (GLint, GLint) callconv(.C) void; extern var glad_glUniform1i: PFNGLUNIFORM1IPROC; const PFNGLUNIFORM2IPROC = ?fn (GLint, GLint, GLint) callconv(.C) void; extern var glad_glUniform2i: PFNGLUNIFORM2IPROC; const PFNGLUNIFORM3IPROC = ?fn (GLint, GLint, GLint, GLint) callconv(.C) void; extern var glad_glUniform3i: PFNGLUNIFORM3IPROC; const PFNGLUNIFORM4IPROC = ?fn (GLint, GLint, GLint, GLint, GLint) callconv(.C) void; extern var glad_glUniform4i: PFNGLUNIFORM4IPROC; const PFNGLUNIFORM1FVPROC = ?fn (GLint, GLsizei, [*c]const GLfloat) callconv(.C) void; extern var glad_glUniform1fv: PFNGLUNIFORM1FVPROC; const PFNGLUNIFORM2FVPROC = ?fn (GLint, GLsizei, [*c]const GLfloat) callconv(.C) void; extern var glad_glUniform2fv: PFNGLUNIFORM2FVPROC; const PFNGLUNIFORM3FVPROC = ?fn (GLint, GLsizei, [*c]const GLfloat) callconv(.C) void; extern var glad_glUniform3fv: PFNGLUNIFORM3FVPROC; const PFNGLUNIFORM4FVPROC = ?fn (GLint, GLsizei, [*c]const GLfloat) callconv(.C) void; extern var glad_glUniform4fv: PFNGLUNIFORM4FVPROC; const PFNGLUNIFORM1IVPROC = ?fn (GLint, GLsizei, [*c]const GLint) callconv(.C) void; extern var glad_glUniform1iv: PFNGLUNIFORM1IVPROC; const PFNGLUNIFORM2IVPROC = ?fn (GLint, GLsizei, [*c]const GLint) callconv(.C) void; extern var glad_glUniform2iv: PFNGLUNIFORM2IVPROC; const PFNGLUNIFORM3IVPROC = ?fn (GLint, GLsizei, [*c]const GLint) callconv(.C) void; extern var glad_glUniform3iv: PFNGLUNIFORM3IVPROC; const PFNGLUNIFORM4IVPROC = ?fn (GLint, GLsizei, [*c]const GLint) callconv(.C) void; extern var glad_glUniform4iv: PFNGLUNIFORM4IVPROC; const PFNGLUNIFORMMATRIX2FVPROC = ?fn (GLint, GLsizei, GLboolean, [*c]const GLfloat) callconv(.C) void; extern var glad_glUniformMatrix2fv: PFNGLUNIFORMMATRIX2FVPROC; const PFNGLUNIFORMMATRIX3FVPROC = ?fn (GLint, GLsizei, GLboolean, [*c]const GLfloat) callconv(.C) void; extern var glad_glUniformMatrix3fv: PFNGLUNIFORMMATRIX3FVPROC; const PFNGLUNIFORMMATRIX4FVPROC = ?fn (GLint, GLsizei, GLboolean, [*c]const GLfloat) callconv(.C) void; extern var glad_glUniformMatrix4fv: PFNGLUNIFORMMATRIX4FVPROC; const PFNGLVALIDATEPROGRAMPROC = ?fn (GLuint) callconv(.C) void; extern var glad_glValidateProgram: PFNGLVALIDATEPROGRAMPROC; const PFNGLVERTEXATTRIB1DPROC = ?fn (GLuint, GLdouble) callconv(.C) void; extern var glad_glVertexAttrib1d: PFNGLVERTEXATTRIB1DPROC; const PFNGLVERTEXATTRIB1DVPROC = ?fn (GLuint, [*c]const GLdouble) callconv(.C) void; extern var glad_glVertexAttrib1dv: PFNGLVERTEXATTRIB1DVPROC; const PFNGLVERTEXATTRIB1FPROC = ?fn (GLuint, GLfloat) callconv(.C) void; extern var glad_glVertexAttrib1f: PFNGLVERTEXATTRIB1FPROC; const PFNGLVERTEXATTRIB1FVPROC = ?fn (GLuint, [*c]const GLfloat) callconv(.C) void; extern var glad_glVertexAttrib1fv: PFNGLVERTEXATTRIB1FVPROC; const PFNGLVERTEXATTRIB1SPROC = ?fn (GLuint, GLshort) callconv(.C) void; extern var glad_glVertexAttrib1s: PFNGLVERTEXATTRIB1SPROC; const PFNGLVERTEXATTRIB1SVPROC = ?fn (GLuint, [*c]const GLshort) callconv(.C) void; extern var glad_glVertexAttrib1sv: PFNGLVERTEXATTRIB1SVPROC; const PFNGLVERTEXATTRIB2DPROC = ?fn (GLuint, GLdouble, GLdouble) callconv(.C) void; extern var glad_glVertexAttrib2d: PFNGLVERTEXATTRIB2DPROC; const PFNGLVERTEXATTRIB2DVPROC = ?fn (GLuint, [*c]const GLdouble) callconv(.C) void; extern var glad_glVertexAttrib2dv: PFNGLVERTEXATTRIB2DVPROC; const PFNGLVERTEXATTRIB2FPROC = ?fn (GLuint, GLfloat, GLfloat) callconv(.C) void; extern var glad_glVertexAttrib2f: PFNGLVERTEXATTRIB2FPROC; const PFNGLVERTEXATTRIB2FVPROC = ?fn (GLuint, [*c]const GLfloat) callconv(.C) void; extern var glad_glVertexAttrib2fv: PFNGLVERTEXATTRIB2FVPROC; const PFNGLVERTEXATTRIB2SPROC = ?fn (GLuint, GLshort, GLshort) callconv(.C) void; extern var glad_glVertexAttrib2s: PFNGLVERTEXATTRIB2SPROC; const PFNGLVERTEXATTRIB2SVPROC = ?fn (GLuint, [*c]const GLshort) callconv(.C) void; extern var glad_glVertexAttrib2sv: PFNGLVERTEXATTRIB2SVPROC; const PFNGLVERTEXATTRIB3DPROC = ?fn (GLuint, GLdouble, GLdouble, GLdouble) callconv(.C) void; extern var glad_glVertexAttrib3d: PFNGLVERTEXATTRIB3DPROC; const PFNGLVERTEXATTRIB3DVPROC = ?fn (GLuint, [*c]const GLdouble) callconv(.C) void; extern var glad_glVertexAttrib3dv: PFNGLVERTEXATTRIB3DVPROC; const PFNGLVERTEXATTRIB3FPROC = ?fn (GLuint, GLfloat, GLfloat, GLfloat) callconv(.C) void; extern var glad_glVertexAttrib3f: PFNGLVERTEXATTRIB3FPROC; const PFNGLVERTEXATTRIB3FVPROC = ?fn (GLuint, [*c]const GLfloat) callconv(.C) void; extern var glad_glVertexAttrib3fv: PFNGLVERTEXATTRIB3FVPROC; const PFNGLVERTEXATTRIB3SPROC = ?fn (GLuint, GLshort, GLshort, GLshort) callconv(.C) void; extern var glad_glVertexAttrib3s: PFNGLVERTEXATTRIB3SPROC; const PFNGLVERTEXATTRIB3SVPROC = ?fn (GLuint, [*c]const GLshort) callconv(.C) void; extern var glad_glVertexAttrib3sv: PFNGLVERTEXATTRIB3SVPROC; const PFNGLVERTEXATTRIB4NBVPROC = ?fn (GLuint, [*c]const GLbyte) callconv(.C) void; extern var glad_glVertexAttrib4Nbv: PFNGLVERTEXATTRIB4NBVPROC; const PFNGLVERTEXATTRIB4NIVPROC = ?fn (GLuint, [*c]const GLint) callconv(.C) void; extern var glad_glVertexAttrib4Niv: PFNGLVERTEXATTRIB4NIVPROC; const PFNGLVERTEXATTRIB4NSVPROC = ?fn (GLuint, [*c]const GLshort) callconv(.C) void; extern var glad_glVertexAttrib4Nsv: PFNGLVERTEXATTRIB4NSVPROC; const PFNGLVERTEXATTRIB4NUBPROC = ?fn (GLuint, GLubyte, GLubyte, GLubyte, GLubyte) callconv(.C) void; extern var glad_glVertexAttrib4Nub: PFNGLVERTEXATTRIB4NUBPROC; const PFNGLVERTEXATTRIB4NUBVPROC = ?fn (GLuint, [*c]const GLubyte) callconv(.C) void; extern var glad_glVertexAttrib4Nubv: PFNGLVERTEXATTRIB4NUBVPROC; const PFNGLVERTEXATTRIB4NUIVPROC = ?fn (GLuint, [*c]const GLuint) callconv(.C) void; extern var glad_glVertexAttrib4Nuiv: PFNGLVERTEXATTRIB4NUIVPROC; const PFNGLVERTEXATTRIB4NUSVPROC = ?fn (GLuint, [*c]const GLushort) callconv(.C) void; extern var glad_glVertexAttrib4Nusv: PFNGLVERTEXATTRIB4NUSVPROC; const PFNGLVERTEXATTRIB4BVPROC = ?fn (GLuint, [*c]const GLbyte) callconv(.C) void; extern var glad_glVertexAttrib4bv: PFNGLVERTEXATTRIB4BVPROC; const PFNGLVERTEXATTRIB4DPROC = ?fn (GLuint, GLdouble, GLdouble, GLdouble, GLdouble) callconv(.C) void; extern var glad_glVertexAttrib4d: PFNGLVERTEXATTRIB4DPROC; const PFNGLVERTEXATTRIB4DVPROC = ?fn (GLuint, [*c]const GLdouble) callconv(.C) void; extern var glad_glVertexAttrib4dv: PFNGLVERTEXATTRIB4DVPROC; const PFNGLVERTEXATTRIB4FPROC = ?fn (GLuint, GLfloat, GLfloat, GLfloat, GLfloat) callconv(.C) void; extern var glad_glVertexAttrib4f: PFNGLVERTEXATTRIB4FPROC; const PFNGLVERTEXATTRIB4FVPROC = ?fn (GLuint, [*c]const GLfloat) callconv(.C) void; extern var glad_glVertexAttrib4fv: PFNGLVERTEXATTRIB4FVPROC; const PFNGLVERTEXATTRIB4IVPROC = ?fn (GLuint, [*c]const GLint) callconv(.C) void; extern var glad_glVertexAttrib4iv: PFNGLVERTEXATTRIB4IVPROC; const PFNGLVERTEXATTRIB4SPROC = ?fn (GLuint, GLshort, GLshort, GLshort, GLshort) callconv(.C) void; extern var glad_glVertexAttrib4s: PFNGLVERTEXATTRIB4SPROC; const PFNGLVERTEXATTRIB4SVPROC = ?fn (GLuint, [*c]const GLshort) callconv(.C) void; extern var glad_glVertexAttrib4sv: PFNGLVERTEXATTRIB4SVPROC; const PFNGLVERTEXATTRIB4UBVPROC = ?fn (GLuint, [*c]const GLubyte) callconv(.C) void; extern var glad_glVertexAttrib4ubv: PFNGLVERTEXATTRIB4UBVPROC; const PFNGLVERTEXATTRIB4UIVPROC = ?fn (GLuint, [*c]const GLuint) callconv(.C) void; extern var glad_glVertexAttrib4uiv: PFNGLVERTEXATTRIB4UIVPROC; const PFNGLVERTEXATTRIB4USVPROC = ?fn (GLuint, [*c]const GLushort) callconv(.C) void; extern var glad_glVertexAttrib4usv: PFNGLVERTEXATTRIB4USVPROC; const PFNGLVERTEXATTRIBPOINTERPROC = ?fn (GLuint, GLint, GLenum, GLboolean, GLsizei, ?*const anyopaque) callconv(.C) void; extern var glad_glVertexAttribPointer: PFNGLVERTEXATTRIBPOINTERPROC; extern var GLAD_GL_VERSION_2_1: c_int; const PFNGLUNIFORMMATRIX2X3FVPROC = ?fn (GLint, GLsizei, GLboolean, [*c]const GLfloat) callconv(.C) void; extern var glad_glUniformMatrix2x3fv: PFNGLUNIFORMMATRIX2X3FVPROC; const PFNGLUNIFORMMATRIX3X2FVPROC = ?fn (GLint, GLsizei, GLboolean, [*c]const GLfloat) callconv(.C) void; extern var glad_glUniformMatrix3x2fv: PFNGLUNIFORMMATRIX3X2FVPROC; const PFNGLUNIFORMMATRIX2X4FVPROC = ?fn (GLint, GLsizei, GLboolean, [*c]const GLfloat) callconv(.C) void; extern var glad_glUniformMatrix2x4fv: PFNGLUNIFORMMATRIX2X4FVPROC; const PFNGLUNIFORMMATRIX4X2FVPROC = ?fn (GLint, GLsizei, GLboolean, [*c]const GLfloat) callconv(.C) void; extern var glad_glUniformMatrix4x2fv: PFNGLUNIFORMMATRIX4X2FVPROC; const PFNGLUNIFORMMATRIX3X4FVPROC = ?fn (GLint, GLsizei, GLboolean, [*c]const GLfloat) callconv(.C) void; extern var glad_glUniformMatrix3x4fv: PFNGLUNIFORMMATRIX3X4FVPROC; const PFNGLUNIFORMMATRIX4X3FVPROC = ?fn (GLint, GLsizei, GLboolean, [*c]const GLfloat) callconv(.C) void; extern var glad_glUniformMatrix4x3fv: PFNGLUNIFORMMATRIX4X3FVPROC; extern var GLAD_GL_VERSION_3_0: c_int; const PFNGLCOLORMASKIPROC = ?fn (GLuint, GLboolean, GLboolean, GLboolean, GLboolean) callconv(.C) void; extern var glad_glColorMaski: PFNGLCOLORMASKIPROC; const PFNGLGETBOOLEANI_VPROC = ?fn (GLenum, GLuint, [*c]GLboolean) callconv(.C) void; extern var glad_glGetBooleani_v: PFNGLGETBOOLEANI_VPROC; const PFNGLGETINTEGERI_VPROC = ?fn (GLenum, GLuint, [*c]GLint) callconv(.C) void; extern var glad_glGetIntegeri_v: PFNGLGETINTEGERI_VPROC; const PFNGLENABLEIPROC = ?fn (GLenum, GLuint) callconv(.C) void; extern var glad_glEnablei: PFNGLENABLEIPROC; const PFNGLDISABLEIPROC = ?fn (GLenum, GLuint) callconv(.C) void; extern var glad_glDisablei: PFNGLDISABLEIPROC; const PFNGLISENABLEDIPROC = ?fn (GLenum, GLuint) callconv(.C) GLboolean; extern var glad_glIsEnabledi: PFNGLISENABLEDIPROC; const PFNGLBEGINTRANSFORMFEEDBACKPROC = ?fn (GLenum) callconv(.C) void; extern var glad_glBeginTransformFeedback: PFNGLBEGINTRANSFORMFEEDBACKPROC; const PFNGLENDTRANSFORMFEEDBACKPROC = ?fn () callconv(.C) void; extern var glad_glEndTransformFeedback: PFNGLENDTRANSFORMFEEDBACKPROC; const PFNGLBINDBUFFERRANGEPROC = ?fn (GLenum, GLuint, GLuint, GLintptr, GLsizeiptr) callconv(.C) void; extern var glad_glBindBufferRange: PFNGLBINDBUFFERRANGEPROC; const PFNGLBINDBUFFERBASEPROC = ?fn (GLenum, GLuint, GLuint) callconv(.C) void; extern var glad_glBindBufferBase: PFNGLBINDBUFFERBASEPROC; const PFNGLTRANSFORMFEEDBACKVARYINGSPROC = ?fn (GLuint, GLsizei, [*c]const [*c]const GLchar, GLenum) callconv(.C) void; extern var glad_glTransformFeedbackVaryings: PFNGLTRANSFORMFEEDBACKVARYINGSPROC; const PFNGLGETTRANSFORMFEEDBACKVARYINGPROC = ?fn (GLuint, GLuint, GLsizei, [*c]GLsizei, [*c]GLsizei, [*c]GLenum, [*c]GLchar) callconv(.C) void; extern var glad_glGetTransformFeedbackVarying: PFNGLGETTRANSFORMFEEDBACKVARYINGPROC; const PFNGLCLAMPCOLORPROC = ?fn (GLenum, GLenum) callconv(.C) void; extern var glad_glClampColor: PFNGLCLAMPCOLORPROC; const PFNGLBEGINCONDITIONALRENDERPROC = ?fn (GLuint, GLenum) callconv(.C) void; extern var glad_glBeginConditionalRender: PFNGLBEGINCONDITIONALRENDERPROC; const PFNGLENDCONDITIONALRENDERPROC = ?fn () callconv(.C) void; extern var glad_glEndConditionalRender: PFNGLENDCONDITIONALRENDERPROC; const PFNGLVERTEXATTRIBIPOINTERPROC = ?fn (GLuint, GLint, GLenum, GLsizei, ?*const anyopaque) callconv(.C) void; extern var glad_glVertexAttribIPointer: PFNGLVERTEXATTRIBIPOINTERPROC; const PFNGLGETVERTEXATTRIBIIVPROC = ?fn (GLuint, GLenum, [*c]GLint) callconv(.C) void; extern var glad_glGetVertexAttribIiv: PFNGLGETVERTEXATTRIBIIVPROC; const PFNGLGETVERTEXATTRIBIUIVPROC = ?fn (GLuint, GLenum, [*c]GLuint) callconv(.C) void; extern var glad_glGetVertexAttribIuiv: PFNGLGETVERTEXATTRIBIUIVPROC; const PFNGLVERTEXATTRIBI1IPROC = ?fn (GLuint, GLint) callconv(.C) void; extern var glad_glVertexAttribI1i: PFNGLVERTEXATTRIBI1IPROC; const PFNGLVERTEXATTRIBI2IPROC = ?fn (GLuint, GLint, GLint) callconv(.C) void; extern var glad_glVertexAttribI2i: PFNGLVERTEXATTRIBI2IPROC; const PFNGLVERTEXATTRIBI3IPROC = ?fn (GLuint, GLint, GLint, GLint) callconv(.C) void; extern var glad_glVertexAttribI3i: PFNGLVERTEXATTRIBI3IPROC; const PFNGLVERTEXATTRIBI4IPROC = ?fn (GLuint, GLint, GLint, GLint, GLint) callconv(.C) void; extern var glad_glVertexAttribI4i: PFNGLVERTEXATTRIBI4IPROC; const PFNGLVERTEXATTRIBI1UIPROC = ?fn (GLuint, GLuint) callconv(.C) void; extern var glad_glVertexAttribI1ui: PFNGLVERTEXATTRIBI1UIPROC; const PFNGLVERTEXATTRIBI2UIPROC = ?fn (GLuint, GLuint, GLuint) callconv(.C) void; extern var glad_glVertexAttribI2ui: PFNGLVERTEXATTRIBI2UIPROC; const PFNGLVERTEXATTRIBI3UIPROC = ?fn (GLuint, GLuint, GLuint, GLuint) callconv(.C) void; extern var glad_glVertexAttribI3ui: PFNGLVERTEXATTRIBI3UIPROC; const PFNGLVERTEXATTRIBI4UIPROC = ?fn (GLuint, GLuint, GLuint, GLuint, GLuint) callconv(.C) void; extern var glad_glVertexAttribI4ui: PFNGLVERTEXATTRIBI4UIPROC; const PFNGLVERTEXATTRIBI1IVPROC = ?fn (GLuint, [*c]const GLint) callconv(.C) void; extern var glad_glVertexAttribI1iv: PFNGLVERTEXATTRIBI1IVPROC; const PFNGLVERTEXATTRIBI2IVPROC = ?fn (GLuint, [*c]const GLint) callconv(.C) void; extern var glad_glVertexAttribI2iv: PFNGLVERTEXATTRIBI2IVPROC; const PFNGLVERTEXATTRIBI3IVPROC = ?fn (GLuint, [*c]const GLint) callconv(.C) void; extern var glad_glVertexAttribI3iv: PFNGLVERTEXATTRIBI3IVPROC; const PFNGLVERTEXATTRIBI4IVPROC = ?fn (GLuint, [*c]const GLint) callconv(.C) void; extern var glad_glVertexAttribI4iv: PFNGLVERTEXATTRIBI4IVPROC; const PFNGLVERTEXATTRIBI1UIVPROC = ?fn (GLuint, [*c]const GLuint) callconv(.C) void; extern var glad_glVertexAttribI1uiv: PFNGLVERTEXATTRIBI1UIVPROC; const PFNGLVERTEXATTRIBI2UIVPROC = ?fn (GLuint, [*c]const GLuint) callconv(.C) void; extern var glad_glVertexAttribI2uiv: PFNGLVERTEXATTRIBI2UIVPROC; const PFNGLVERTEXATTRIBI3UIVPROC = ?fn (GLuint, [*c]const GLuint) callconv(.C) void; extern var glad_glVertexAttribI3uiv: PFNGLVERTEXATTRIBI3UIVPROC; const PFNGLVERTEXATTRIBI4UIVPROC = ?fn (GLuint, [*c]const GLuint) callconv(.C) void; extern var glad_glVertexAttribI4uiv: PFNGLVERTEXATTRIBI4UIVPROC; const PFNGLVERTEXATTRIBI4BVPROC = ?fn (GLuint, [*c]const GLbyte) callconv(.C) void; extern var glad_glVertexAttribI4bv: PFNGLVERTEXATTRIBI4BVPROC; const PFNGLVERTEXATTRIBI4SVPROC = ?fn (GLuint, [*c]const GLshort) callconv(.C) void; extern var glad_glVertexAttribI4sv: PFNGLVERTEXATTRIBI4SVPROC; const PFNGLVERTEXATTRIBI4UBVPROC = ?fn (GLuint, [*c]const GLubyte) callconv(.C) void; extern var glad_glVertexAttribI4ubv: PFNGLVERTEXATTRIBI4UBVPROC; const PFNGLVERTEXATTRIBI4USVPROC = ?fn (GLuint, [*c]const GLushort) callconv(.C) void; extern var glad_glVertexAttribI4usv: PFNGLVERTEXATTRIBI4USVPROC; const PFNGLGETUNIFORMUIVPROC = ?fn (GLuint, GLint, [*c]GLuint) callconv(.C) void; extern var glad_glGetUniformuiv: PFNGLGETUNIFORMUIVPROC; const PFNGLBINDFRAGDATALOCATIONPROC = ?fn (GLuint, GLuint, [*c]const GLchar) callconv(.C) void; extern var glad_glBindFragDataLocation: PFNGLBINDFRAGDATALOCATIONPROC; const PFNGLGETFRAGDATALOCATIONPROC = ?fn (GLuint, [*c]const GLchar) callconv(.C) GLint; extern var glad_glGetFragDataLocation: PFNGLGETFRAGDATALOCATIONPROC; const PFNGLUNIFORM1UIPROC = ?fn (GLint, GLuint) callconv(.C) void; extern var glad_glUniform1ui: PFNGLUNIFORM1UIPROC; const PFNGLUNIFORM2UIPROC = ?fn (GLint, GLuint, GLuint) callconv(.C) void; extern var glad_glUniform2ui: PFNGLUNIFORM2UIPROC; const PFNGLUNIFORM3UIPROC = ?fn (GLint, GLuint, GLuint, GLuint) callconv(.C) void; extern var glad_glUniform3ui: PFNGLUNIFORM3UIPROC; const PFNGLUNIFORM4UIPROC = ?fn (GLint, GLuint, GLuint, GLuint, GLuint) callconv(.C) void; extern var glad_glUniform4ui: PFNGLUNIFORM4UIPROC; const PFNGLUNIFORM1UIVPROC = ?fn (GLint, GLsizei, [*c]const GLuint) callconv(.C) void; extern var glad_glUniform1uiv: PFNGLUNIFORM1UIVPROC; const PFNGLUNIFORM2UIVPROC = ?fn (GLint, GLsizei, [*c]const GLuint) callconv(.C) void; extern var glad_glUniform2uiv: PFNGLUNIFORM2UIVPROC; const PFNGLUNIFORM3UIVPROC = ?fn (GLint, GLsizei, [*c]const GLuint) callconv(.C) void; extern var glad_glUniform3uiv: PFNGLUNIFORM3UIVPROC; const PFNGLUNIFORM4UIVPROC = ?fn (GLint, GLsizei, [*c]const GLuint) callconv(.C) void; extern var glad_glUniform4uiv: PFNGLUNIFORM4UIVPROC; const PFNGLTEXPARAMETERIIVPROC = ?fn (GLenum, GLenum, [*c]const GLint) callconv(.C) void; extern var glad_glTexParameterIiv: PFNGLTEXPARAMETERIIVPROC; const PFNGLTEXPARAMETERIUIVPROC = ?fn (GLenum, GLenum, [*c]const GLuint) callconv(.C) void; extern var glad_glTexParameterIuiv: PFNGLTEXPARAMETERIUIVPROC; const PFNGLGETTEXPARAMETERIIVPROC = ?fn (GLenum, GLenum, [*c]GLint) callconv(.C) void; extern var glad_glGetTexParameterIiv: PFNGLGETTEXPARAMETERIIVPROC; const PFNGLGETTEXPARAMETERIUIVPROC = ?fn (GLenum, GLenum, [*c]GLuint) callconv(.C) void; extern var glad_glGetTexParameterIuiv: PFNGLGETTEXPARAMETERIUIVPROC; const PFNGLCLEARBUFFERIVPROC = ?fn (GLenum, GLint, [*c]const GLint) callconv(.C) void; extern var glad_glClearBufferiv: PFNGLCLEARBUFFERIVPROC; const PFNGLCLEARBUFFERUIVPROC = ?fn (GLenum, GLint, [*c]const GLuint) callconv(.C) void; extern var glad_glClearBufferuiv: PFNGLCLEARBUFFERUIVPROC; const PFNGLCLEARBUFFERFVPROC = ?fn (GLenum, GLint, [*c]const GLfloat) callconv(.C) void; extern var glad_glClearBufferfv: PFNGLCLEARBUFFERFVPROC; const PFNGLCLEARBUFFERFIPROC = ?fn (GLenum, GLint, GLfloat, GLint) callconv(.C) void; extern var glad_glClearBufferfi: PFNGLCLEARBUFFERFIPROC; const PFNGLGETSTRINGIPROC = ?fn (GLenum, GLuint) callconv(.C) [*c]const GLubyte; extern var glad_glGetStringi: PFNGLGETSTRINGIPROC; const PFNGLISRENDERBUFFERPROC = ?fn (GLuint) callconv(.C) GLboolean; extern var glad_glIsRenderbuffer: PFNGLISRENDERBUFFERPROC; const PFNGLBINDRENDERBUFFERPROC = ?fn (GLenum, GLuint) callconv(.C) void; extern var glad_glBindRenderbuffer: PFNGLBINDRENDERBUFFERPROC; const PFNGLDELETERENDERBUFFERSPROC = ?fn (GLsizei, [*c]const GLuint) callconv(.C) void; extern var glad_glDeleteRenderbuffers: PFNGLDELETERENDERBUFFERSPROC; const PFNGLGENRENDERBUFFERSPROC = ?fn (GLsizei, [*c]GLuint) callconv(.C) void; extern var glad_glGenRenderbuffers: PFNGLGENRENDERBUFFERSPROC; const PFNGLRENDERBUFFERSTORAGEPROC = ?fn (GLenum, GLenum, GLsizei, GLsizei) callconv(.C) void; extern var glad_glRenderbufferStorage: PFNGLRENDERBUFFERSTORAGEPROC; const PFNGLGETRENDERBUFFERPARAMETERIVPROC = ?fn (GLenum, GLenum, [*c]GLint) callconv(.C) void; extern var glad_glGetRenderbufferParameteriv: PFNGLGETRENDERBUFFERPARAMETERIVPROC; const PFNGLISFRAMEBUFFERPROC = ?fn (GLuint) callconv(.C) GLboolean; extern var glad_glIsFramebuffer: PFNGLISFRAMEBUFFERPROC; const PFNGLBINDFRAMEBUFFERPROC = ?fn (GLenum, GLuint) callconv(.C) void; extern var glad_glBindFramebuffer: PFNGLBINDFRAMEBUFFERPROC; const PFNGLDELETEFRAMEBUFFERSPROC = ?fn (GLsizei, [*c]const GLuint) callconv(.C) void; extern var glad_glDeleteFramebuffers: PFNGLDELETEFRAMEBUFFERSPROC; const PFNGLGENFRAMEBUFFERSPROC = ?fn (GLsizei, [*c]GLuint) callconv(.C) void; extern var glad_glGenFramebuffers: PFNGLGENFRAMEBUFFERSPROC; const PFNGLCHECKFRAMEBUFFERSTATUSPROC = ?fn (GLenum) callconv(.C) GLenum; extern var glad_glCheckFramebufferStatus: PFNGLCHECKFRAMEBUFFERSTATUSPROC; const PFNGLFRAMEBUFFERTEXTURE1DPROC = ?fn (GLenum, GLenum, GLenum, GLuint, GLint) callconv(.C) void; extern var glad_glFramebufferTexture1D: PFNGLFRAMEBUFFERTEXTURE1DPROC; const PFNGLFRAMEBUFFERTEXTURE2DPROC = ?fn (GLenum, GLenum, GLenum, GLuint, GLint) callconv(.C) void; extern var glad_glFramebufferTexture2D: PFNGLFRAMEBUFFERTEXTURE2DPROC; const PFNGLFRAMEBUFFERTEXTURE3DPROC = ?fn (GLenum, GLenum, GLenum, GLuint, GLint, GLint) callconv(.C) void; extern var glad_glFramebufferTexture3D: PFNGLFRAMEBUFFERTEXTURE3DPROC; const PFNGLFRAMEBUFFERRENDERBUFFERPROC = ?fn (GLenum, GLenum, GLenum, GLuint) callconv(.C) void; extern var glad_glFramebufferRenderbuffer: PFNGLFRAMEBUFFERRENDERBUFFERPROC; const PFNGLGETFRAMEBUFFERATTACHMENTPARAMETERIVPROC = ?fn (GLenum, GLenum, GLenum, [*c]GLint) callconv(.C) void; extern var glad_glGetFramebufferAttachmentParameteriv: PFNGLGETFRAMEBUFFERATTACHMENTPARAMETERIVPROC; const PFNGLGENERATEMIPMAPPROC = ?fn (GLenum) callconv(.C) void; extern var glad_glGenerateMipmap: PFNGLGENERATEMIPMAPPROC; const PFNGLBLITFRAMEBUFFERPROC = ?fn (GLint, GLint, GLint, GLint, GLint, GLint, GLint, GLint, GLbitfield, GLenum) callconv(.C) void; extern var glad_glBlitFramebuffer: PFNGLBLITFRAMEBUFFERPROC; const PFNGLRENDERBUFFERSTORAGEMULTISAMPLEPROC = ?fn (GLenum, GLsizei, GLenum, GLsizei, GLsizei) callconv(.C) void; extern var glad_glRenderbufferStorageMultisample: PFNGLRENDERBUFFERSTORAGEMULTISAMPLEPROC; const PFNGLFRAMEBUFFERTEXTURELAYERPROC = ?fn (GLenum, GLenum, GLuint, GLint, GLint) callconv(.C) void; extern var glad_glFramebufferTextureLayer: PFNGLFRAMEBUFFERTEXTURELAYERPROC; const PFNGLMAPBUFFERRANGEPROC = ?fn (GLenum, GLintptr, GLsizeiptr, GLbitfield) callconv(.C) ?*anyopaque; extern var glad_glMapBufferRange: PFNGLMAPBUFFERRANGEPROC; const PFNGLFLUSHMAPPEDBUFFERRANGEPROC = ?fn (GLenum, GLintptr, GLsizeiptr) callconv(.C) void; extern var glad_glFlushMappedBufferRange: PFNGLFLUSHMAPPEDBUFFERRANGEPROC; const PFNGLBINDVERTEXARRAYPROC = ?fn (GLuint) callconv(.C) void; extern var glad_glBindVertexArray: PFNGLBINDVERTEXARRAYPROC; const PFNGLDELETEVERTEXARRAYSPROC = ?fn (GLsizei, [*c]const GLuint) callconv(.C) void; extern var glad_glDeleteVertexArrays: PFNGLDELETEVERTEXARRAYSPROC; const PFNGLGENVERTEXARRAYSPROC = ?fn (GLsizei, [*c]GLuint) callconv(.C) void; extern var glad_glGenVertexArrays: PFNGLGENVERTEXARRAYSPROC; const PFNGLISVERTEXARRAYPROC = ?fn (GLuint) callconv(.C) GLboolean; extern var glad_glIsVertexArray: PFNGLISVERTEXARRAYPROC; extern var GLAD_GL_VERSION_3_1: c_int; const PFNGLDRAWARRAYSINSTANCEDPROC = ?fn (GLenum, GLint, GLsizei, GLsizei) callconv(.C) void; extern var glad_glDrawArraysInstanced: PFNGLDRAWARRAYSINSTANCEDPROC; const PFNGLDRAWELEMENTSINSTANCEDPROC = ?fn (GLenum, GLsizei, GLenum, ?*const anyopaque, GLsizei) callconv(.C) void; extern var glad_glDrawElementsInstanced: PFNGLDRAWELEMENTSINSTANCEDPROC; const PFNGLTEXBUFFERPROC = ?fn (GLenum, GLenum, GLuint) callconv(.C) void; extern var glad_glTexBuffer: PFNGLTEXBUFFERPROC; const PFNGLPRIMITIVERESTARTINDEXPROC = ?fn (GLuint) callconv(.C) void; extern var glad_glPrimitiveRestartIndex: PFNGLPRIMITIVERESTARTINDEXPROC; const PFNGLCOPYBUFFERSUBDATAPROC = ?fn (GLenum, GLenum, GLintptr, GLintptr, GLsizeiptr) callconv(.C) void; extern var glad_glCopyBufferSubData: PFNGLCOPYBUFFERSUBDATAPROC; const PFNGLGETUNIFORMINDICESPROC = ?fn (GLuint, GLsizei, [*c]const [*c]const GLchar, [*c]GLuint) callconv(.C) void; extern var glad_glGetUniformIndices: PFNGLGETUNIFORMINDICESPROC; const PFNGLGETACTIVEUNIFORMSIVPROC = ?fn (GLuint, GLsizei, [*c]const GLuint, GLenum, [*c]GLint) callconv(.C) void; extern var glad_glGetActiveUniformsiv: PFNGLGETACTIVEUNIFORMSIVPROC; const PFNGLGETACTIVEUNIFORMNAMEPROC = ?fn (GLuint, GLuint, GLsizei, [*c]GLsizei, [*c]GLchar) callconv(.C) void; extern var glad_glGetActiveUniformName: PFNGLGETACTIVEUNIFORMNAMEPROC; const PFNGLGETUNIFORMBLOCKINDEXPROC = ?fn (GLuint, [*c]const GLchar) callconv(.C) GLuint; extern var glad_glGetUniformBlockIndex: PFNGLGETUNIFORMBLOCKINDEXPROC; const PFNGLGETACTIVEUNIFORMBLOCKIVPROC = ?fn (GLuint, GLuint, GLenum, [*c]GLint) callconv(.C) void; extern var glad_glGetActiveUniformBlockiv: PFNGLGETACTIVEUNIFORMBLOCKIVPROC; const PFNGLGETACTIVEUNIFORMBLOCKNAMEPROC = ?fn (GLuint, GLuint, GLsizei, [*c]GLsizei, [*c]GLchar) callconv(.C) void; extern var glad_glGetActiveUniformBlockName: PFNGLGETACTIVEUNIFORMBLOCKNAMEPROC; const PFNGLUNIFORMBLOCKBINDINGPROC = ?fn (GLuint, GLuint, GLuint) callconv(.C) void; extern var glad_glUniformBlockBinding: PFNGLUNIFORMBLOCKBINDINGPROC; extern var GLAD_GL_VERSION_3_2: c_int; const PFNGLDRAWELEMENTSBASEVERTEXPROC = ?fn (GLenum, GLsizei, GLenum, ?*const anyopaque, GLint) callconv(.C) void; extern var glad_glDrawElementsBaseVertex: PFNGLDRAWELEMENTSBASEVERTEXPROC; const PFNGLDRAWRANGEELEMENTSBASEVERTEXPROC = ?fn (GLenum, GLuint, GLuint, GLsizei, GLenum, ?*const anyopaque, GLint) callconv(.C) void; extern var glad_glDrawRangeElementsBaseVertex: PFNGLDRAWRANGEELEMENTSBASEVERTEXPROC; const PFNGLDRAWELEMENTSINSTANCEDBASEVERTEXPROC = ?fn (GLenum, GLsizei, GLenum, ?*const anyopaque, GLsizei, GLint) callconv(.C) void; extern var glad_glDrawElementsInstancedBaseVertex: PFNGLDRAWELEMENTSINSTANCEDBASEVERTEXPROC; const PFNGLMULTIDRAWELEMENTSBASEVERTEXPROC = ?fn (GLenum, [*c]const GLsizei, GLenum, [*c]const ?*const anyopaque, GLsizei, [*c]const GLint) callconv(.C) void; extern var glad_glMultiDrawElementsBaseVertex: PFNGLMULTIDRAWELEMENTSBASEVERTEXPROC; const PFNGLPROVOKINGVERTEXPROC = ?fn (GLenum) callconv(.C) void; extern var glad_glProvokingVertex: PFNGLPROVOKINGVERTEXPROC; const PFNGLFENCESYNCPROC = ?fn (GLenum, GLbitfield) callconv(.C) GLsync; extern var glad_glFenceSync: PFNGLFENCESYNCPROC; const PFNGLISSYNCPROC = ?fn (GLsync) callconv(.C) GLboolean; extern var glad_glIsSync: PFNGLISSYNCPROC; const PFNGLDELETESYNCPROC = ?fn (GLsync) callconv(.C) void; extern var glad_glDeleteSync: PFNGLDELETESYNCPROC; const PFNGLCLIENTWAITSYNCPROC = ?fn (GLsync, GLbitfield, GLuint64) callconv(.C) GLenum; extern var glad_glClientWaitSync: PFNGLCLIENTWAITSYNCPROC; const PFNGLWAITSYNCPROC = ?fn (GLsync, GLbitfield, GLuint64) callconv(.C) void; extern var glad_glWaitSync: PFNGLWAITSYNCPROC; const PFNGLGETINTEGER64VPROC = ?fn (GLenum, [*c]GLint64) callconv(.C) void; extern var glad_glGetInteger64v: PFNGLGETINTEGER64VPROC; const PFNGLGETSYNCIVPROC = ?fn (GLsync, GLenum, GLsizei, [*c]GLsizei, [*c]GLint) callconv(.C) void; extern var glad_glGetSynciv: PFNGLGETSYNCIVPROC; const PFNGLGETINTEGER64I_VPROC = ?fn (GLenum, GLuint, [*c]GLint64) callconv(.C) void; extern var glad_glGetInteger64i_v: PFNGLGETINTEGER64I_VPROC; const PFNGLGETBUFFERPARAMETERI64VPROC = ?fn (GLenum, GLenum, [*c]GLint64) callconv(.C) void; extern var glad_glGetBufferParameteri64v: PFNGLGETBUFFERPARAMETERI64VPROC; const PFNGLFRAMEBUFFERTEXTUREPROC = ?fn (GLenum, GLenum, GLuint, GLint) callconv(.C) void; extern var glad_glFramebufferTexture: PFNGLFRAMEBUFFERTEXTUREPROC; const PFNGLTEXIMAGE2DMULTISAMPLEPROC = ?fn (GLenum, GLsizei, GLenum, GLsizei, GLsizei, GLboolean) callconv(.C) void; extern var glad_glTexImage2DMultisample: PFNGLTEXIMAGE2DMULTISAMPLEPROC; const PFNGLTEXIMAGE3DMULTISAMPLEPROC = ?fn (GLenum, GLsizei, GLenum, GLsizei, GLsizei, GLsizei, GLboolean) callconv(.C) void; extern var glad_glTexImage3DMultisample: PFNGLTEXIMAGE3DMULTISAMPLEPROC; const PFNGLGETMULTISAMPLEFVPROC = ?fn (GLenum, GLuint, [*c]GLfloat) callconv(.C) void; extern var glad_glGetMultisamplefv: PFNGLGETMULTISAMPLEFVPROC; const PFNGLSAMPLEMASKIPROC = ?fn (GLuint, GLbitfield) callconv(.C) void; extern var glad_glSampleMaski: PFNGLSAMPLEMASKIPROC; extern var GLAD_GL_VERSION_3_3: c_int; const PFNGLBINDFRAGDATALOCATIONINDEXEDPROC = ?fn (GLuint, GLuint, GLuint, [*c]const GLchar) callconv(.C) void; extern var glad_glBindFragDataLocationIndexed: PFNGLBINDFRAGDATALOCATIONINDEXEDPROC; const PFNGLGETFRAGDATAINDEXPROC = ?fn (GLuint, [*c]const GLchar) callconv(.C) GLint; extern var glad_glGetFragDataIndex: PFNGLGETFRAGDATAINDEXPROC; const PFNGLGENSAMPLERSPROC = ?fn (GLsizei, [*c]GLuint) callconv(.C) void; extern var glad_glGenSamplers: PFNGLGENSAMPLERSPROC; const PFNGLDELETESAMPLERSPROC = ?fn (GLsizei, [*c]const GLuint) callconv(.C) void; extern var glad_glDeleteSamplers: PFNGLDELETESAMPLERSPROC; const PFNGLISSAMPLERPROC = ?fn (GLuint) callconv(.C) GLboolean; extern var glad_glIsSampler: PFNGLISSAMPLERPROC; const PFNGLBINDSAMPLERPROC = ?fn (GLuint, GLuint) callconv(.C) void; extern var glad_glBindSampler: PFNGLBINDSAMPLERPROC; const PFNGLSAMPLERPARAMETERIPROC = ?fn (GLuint, GLenum, GLint) callconv(.C) void; extern var glad_glSamplerParameteri: PFNGLSAMPLERPARAMETERIPROC; const PFNGLSAMPLERPARAMETERIVPROC = ?fn (GLuint, GLenum, [*c]const GLint) callconv(.C) void; extern var glad_glSamplerParameteriv: PFNGLSAMPLERPARAMETERIVPROC; const PFNGLSAMPLERPARAMETERFPROC = ?fn (GLuint, GLenum, GLfloat) callconv(.C) void; extern var glad_glSamplerParameterf: PFNGLSAMPLERPARAMETERFPROC; const PFNGLSAMPLERPARAMETERFVPROC = ?fn (GLuint, GLenum, [*c]const GLfloat) callconv(.C) void; extern var glad_glSamplerParameterfv: PFNGLSAMPLERPARAMETERFVPROC; const PFNGLSAMPLERPARAMETERIIVPROC = ?fn (GLuint, GLenum, [*c]const GLint) callconv(.C) void; extern var glad_glSamplerParameterIiv: PFNGLSAMPLERPARAMETERIIVPROC; const PFNGLSAMPLERPARAMETERIUIVPROC = ?fn (GLuint, GLenum, [*c]const GLuint) callconv(.C) void; extern var glad_glSamplerParameterIuiv: PFNGLSAMPLERPARAMETERIUIVPROC; const PFNGLGETSAMPLERPARAMETERIVPROC = ?fn (GLuint, GLenum, [*c]GLint) callconv(.C) void; extern var glad_glGetSamplerParameteriv: PFNGLGETSAMPLERPARAMETERIVPROC; const PFNGLGETSAMPLERPARAMETERIIVPROC = ?fn (GLuint, GLenum, [*c]GLint) callconv(.C) void; extern var glad_glGetSamplerParameterIiv: PFNGLGETSAMPLERPARAMETERIIVPROC; const PFNGLGETSAMPLERPARAMETERFVPROC = ?fn (GLuint, GLenum, [*c]GLfloat) callconv(.C) void; extern var glad_glGetSamplerParameterfv: PFNGLGETSAMPLERPARAMETERFVPROC; const PFNGLGETSAMPLERPARAMETERIUIVPROC = ?fn (GLuint, GLenum, [*c]GLuint) callconv(.C) void; extern var glad_glGetSamplerParameterIuiv: PFNGLGETSAMPLERPARAMETERIUIVPROC; const PFNGLQUERYCOUNTERPROC = ?fn (GLuint, GLenum) callconv(.C) void; extern var glad_glQueryCounter: PFNGLQUERYCOUNTERPROC; const PFNGLGETQUERYOBJECTI64VPROC = ?fn (GLuint, GLenum, [*c]GLint64) callconv(.C) void; extern var glad_glGetQueryObjecti64v: PFNGLGETQUERYOBJECTI64VPROC; const PFNGLGETQUERYOBJECTUI64VPROC = ?fn (GLuint, GLenum, [*c]GLuint64) callconv(.C) void; extern var glad_glGetQueryObjectui64v: PFNGLGETQUERYOBJECTUI64VPROC; const PFNGLVERTEXATTRIBDIVISORPROC = ?fn (GLuint, GLuint) callconv(.C) void; extern var glad_glVertexAttribDivisor: PFNGLVERTEXATTRIBDIVISORPROC; const PFNGLVERTEXATTRIBP1UIPROC = ?fn (GLuint, GLenum, GLboolean, GLuint) callconv(.C) void; extern var glad_glVertexAttribP1ui: PFNGLVERTEXATTRIBP1UIPROC; const PFNGLVERTEXATTRIBP1UIVPROC = ?fn (GLuint, GLenum, GLboolean, [*c]const GLuint) callconv(.C) void; extern var glad_glVertexAttribP1uiv: PFNGLVERTEXATTRIBP1UIVPROC; const PFNGLVERTEXATTRIBP2UIPROC = ?fn (GLuint, GLenum, GLboolean, GLuint) callconv(.C) void; extern var glad_glVertexAttribP2ui: PFNGLVERTEXATTRIBP2UIPROC; const PFNGLVERTEXATTRIBP2UIVPROC = ?fn (GLuint, GLenum, GLboolean, [*c]const GLuint) callconv(.C) void; extern var glad_glVertexAttribP2uiv: PFNGLVERTEXATTRIBP2UIVPROC; const PFNGLVERTEXATTRIBP3UIPROC = ?fn (GLuint, GLenum, GLboolean, GLuint) callconv(.C) void; extern var glad_glVertexAttribP3ui: PFNGLVERTEXATTRIBP3UIPROC; const PFNGLVERTEXATTRIBP3UIVPROC = ?fn (GLuint, GLenum, GLboolean, [*c]const GLuint) callconv(.C) void; extern var glad_glVertexAttribP3uiv: PFNGLVERTEXATTRIBP3UIVPROC; const PFNGLVERTEXATTRIBP4UIPROC = ?fn (GLuint, GLenum, GLboolean, GLuint) callconv(.C) void; extern var glad_glVertexAttribP4ui: PFNGLVERTEXATTRIBP4UIPROC; const PFNGLVERTEXATTRIBP4UIVPROC = ?fn (GLuint, GLenum, GLboolean, [*c]const GLuint) callconv(.C) void; extern var glad_glVertexAttribP4uiv: PFNGLVERTEXATTRIBP4UIVPROC; const PFNGLVERTEXP2UIPROC = ?fn (GLenum, GLuint) callconv(.C) void; extern var glad_glVertexP2ui: PFNGLVERTEXP2UIPROC; const PFNGLVERTEXP2UIVPROC = ?fn (GLenum, [*c]const GLuint) callconv(.C) void; extern var glad_glVertexP2uiv: PFNGLVERTEXP2UIVPROC; const PFNGLVERTEXP3UIPROC = ?fn (GLenum, GLuint) callconv(.C) void; extern var glad_glVertexP3ui: PFNGLVERTEXP3UIPROC; const PFNGLVERTEXP3UIVPROC = ?fn (GLenum, [*c]const GLuint) callconv(.C) void; extern var glad_glVertexP3uiv: PFNGLVERTEXP3UIVPROC; const PFNGLVERTEXP4UIPROC = ?fn (GLenum, GLuint) callconv(.C) void; extern var glad_glVertexP4ui: PFNGLVERTEXP4UIPROC; const PFNGLVERTEXP4UIVPROC = ?fn (GLenum, [*c]const GLuint) callconv(.C) void; extern var glad_glVertexP4uiv: PFNGLVERTEXP4UIVPROC; const PFNGLTEXCOORDP1UIPROC = ?fn (GLenum, GLuint) callconv(.C) void; extern var glad_glTexCoordP1ui: PFNGLTEXCOORDP1UIPROC; const PFNGLTEXCOORDP1UIVPROC = ?fn (GLenum, [*c]const GLuint) callconv(.C) void; extern var glad_glTexCoordP1uiv: PFNGLTEXCOORDP1UIVPROC; const PFNGLTEXCOORDP2UIPROC = ?fn (GLenum, GLuint) callconv(.C) void; extern var glad_glTexCoordP2ui: PFNGLTEXCOORDP2UIPROC; const PFNGLTEXCOORDP2UIVPROC = ?fn (GLenum, [*c]const GLuint) callconv(.C) void; extern var glad_glTexCoordP2uiv: PFNGLTEXCOORDP2UIVPROC; const PFNGLTEXCOORDP3UIPROC = ?fn (GLenum, GLuint) callconv(.C) void; extern var glad_glTexCoordP3ui: PFNGLTEXCOORDP3UIPROC; const PFNGLTEXCOORDP3UIVPROC = ?fn (GLenum, [*c]const GLuint) callconv(.C) void; extern var glad_glTexCoordP3uiv: PFNGLTEXCOORDP3UIVPROC; const PFNGLTEXCOORDP4UIPROC = ?fn (GLenum, GLuint) callconv(.C) void; extern var glad_glTexCoordP4ui: PFNGLTEXCOORDP4UIPROC; const PFNGLTEXCOORDP4UIVPROC = ?fn (GLenum, [*c]const GLuint) callconv(.C) void; extern var glad_glTexCoordP4uiv: PFNGLTEXCOORDP4UIVPROC; const PFNGLMULTITEXCOORDP1UIPROC = ?fn (GLenum, GLenum, GLuint) callconv(.C) void; extern var glad_glMultiTexCoordP1ui: PFNGLMULTITEXCOORDP1UIPROC; const PFNGLMULTITEXCOORDP1UIVPROC = ?fn (GLenum, GLenum, [*c]const GLuint) callconv(.C) void; extern var glad_glMultiTexCoordP1uiv: PFNGLMULTITEXCOORDP1UIVPROC; const PFNGLMULTITEXCOORDP2UIPROC = ?fn (GLenum, GLenum, GLuint) callconv(.C) void; extern var glad_glMultiTexCoordP2ui: PFNGLMULTITEXCOORDP2UIPROC; const PFNGLMULTITEXCOORDP2UIVPROC = ?fn (GLenum, GLenum, [*c]const GLuint) callconv(.C) void; extern var glad_glMultiTexCoordP2uiv: PFNGLMULTITEXCOORDP2UIVPROC; const PFNGLMULTITEXCOORDP3UIPROC = ?fn (GLenum, GLenum, GLuint) callconv(.C) void; extern var glad_glMultiTexCoordP3ui: PFNGLMULTITEXCOORDP3UIPROC; const PFNGLMULTITEXCOORDP3UIVPROC = ?fn (GLenum, GLenum, [*c]const GLuint) callconv(.C) void; extern var glad_glMultiTexCoordP3uiv: PFNGLMULTITEXCOORDP3UIVPROC; const PFNGLMULTITEXCOORDP4UIPROC = ?fn (GLenum, GLenum, GLuint) callconv(.C) void; extern var glad_glMultiTexCoordP4ui: PFNGLMULTITEXCOORDP4UIPROC; const PFNGLMULTITEXCOORDP4UIVPROC = ?fn (GLenum, GLenum, [*c]const GLuint) callconv(.C) void; extern var glad_glMultiTexCoordP4uiv: PFNGLMULTITEXCOORDP4UIVPROC; const PFNGLNORMALP3UIPROC = ?fn (GLenum, GLuint) callconv(.C) void; extern var glad_glNormalP3ui: PFNGLNORMALP3UIPROC; const PFNGLNORMALP3UIVPROC = ?fn (GLenum, [*c]const GLuint) callconv(.C) void; extern var glad_glNormalP3uiv: PFNGLNORMALP3UIVPROC; const PFNGLCOLORP3UIPROC = ?fn (GLenum, GLuint) callconv(.C) void; extern var glad_glColorP3ui: PFNGLCOLORP3UIPROC; const PFNGLCOLORP3UIVPROC = ?fn (GLenum, [*c]const GLuint) callconv(.C) void; extern var glad_glColorP3uiv: PFNGLCOLORP3UIVPROC; const PFNGLCOLORP4UIPROC = ?fn (GLenum, GLuint) callconv(.C) void; extern var glad_glColorP4ui: PFNGLCOLORP4UIPROC; const PFNGLCOLORP4UIVPROC = ?fn (GLenum, [*c]const GLuint) callconv(.C) void; extern var glad_glColorP4uiv: PFNGLCOLORP4UIVPROC; const PFNGLSECONDARYCOLORP3UIPROC = ?fn (GLenum, GLuint) callconv(.C) void; extern var glad_glSecondaryColorP3ui: PFNGLSECONDARYCOLORP3UIPROC; const PFNGLSECONDARYCOLORP3UIVPROC = ?fn (GLenum, [*c]const GLuint) callconv(.C) void; extern var glad_glSecondaryColorP3uiv: PFNGLSECONDARYCOLORP3UIVPROC; pub const GL_DEPTH_BUFFER_BIT = @as(c_int, 0x00000100); pub const GL_STENCIL_BUFFER_BIT = @as(c_int, 0x00000400); pub const GL_COLOR_BUFFER_BIT = @as(c_int, 0x00004000); pub const GL_FALSE = @as(c_int, 0); pub const GL_TRUE = @as(c_int, 1); pub const GL_POINTS = @as(c_int, 0x0000); pub const GL_LINES = @as(c_int, 0x0001); pub const GL_LINE_LOOP = @as(c_int, 0x0002); pub const GL_LINE_STRIP = @as(c_int, 0x0003); pub const GL_TRIANGLES = @as(c_int, 0x0004); pub const GL_TRIANGLE_STRIP = @as(c_int, 0x0005); pub const GL_TRIANGLE_FAN = @as(c_int, 0x0006); pub const GL_NEVER = @as(c_int, 0x0200); pub const GL_LESS = @as(c_int, 0x0201); pub const GL_EQUAL = @as(c_int, 0x0202); pub const GL_LEQUAL = @as(c_int, 0x0203); pub const GL_GREATER = @as(c_int, 0x0204); pub const GL_NOTEQUAL = @as(c_int, 0x0205); pub const GL_GEQUAL = @as(c_int, 0x0206); pub const GL_ALWAYS = @as(c_int, 0x0207); pub const GL_ZERO = @as(c_int, 0); pub const GL_ONE = @as(c_int, 1); pub const GL_SRC_COLOR = @as(c_int, 0x0300); pub const GL_ONE_MINUS_SRC_COLOR = @as(c_int, 0x0301); pub const GL_SRC_ALPHA = @as(c_int, 0x0302); pub const GL_ONE_MINUS_SRC_ALPHA = @as(c_int, 0x0303); pub const GL_DST_ALPHA = @as(c_int, 0x0304); pub const GL_ONE_MINUS_DST_ALPHA = @as(c_int, 0x0305); pub const GL_DST_COLOR = @as(c_int, 0x0306); pub const GL_ONE_MINUS_DST_COLOR = @as(c_int, 0x0307); pub const GL_SRC_ALPHA_SATURATE = @as(c_int, 0x0308); pub const GL_NONE = @as(c_int, 0); pub const GL_FRONT_LEFT = @as(c_int, 0x0400); pub const GL_FRONT_RIGHT = @as(c_int, 0x0401); pub const GL_BACK_LEFT = @as(c_int, 0x0402); pub const GL_BACK_RIGHT = @as(c_int, 0x0403); pub const GL_FRONT = @as(c_int, 0x0404); pub const GL_BACK = @as(c_int, 0x0405); pub const GL_LEFT = @as(c_int, 0x0406); pub const GL_RIGHT = @as(c_int, 0x0407); pub const GL_FRONT_AND_BACK = @as(c_int, 0x0408); pub const GL_NO_ERROR = @as(c_int, 0); pub const GL_INVALID_ENUM = @as(c_int, 0x0500); pub const GL_INVALID_VALUE = @as(c_int, 0x0501); pub const GL_INVALID_OPERATION = @as(c_int, 0x0502); pub const GL_OUT_OF_MEMORY = @as(c_int, 0x0505); pub const GL_CW = @as(c_int, 0x0900); pub const GL_CCW = @as(c_int, 0x0901); pub const GL_POINT_SIZE = @as(c_int, 0x0B11); pub const GL_POINT_SIZE_RANGE = @as(c_int, 0x0B12); pub const GL_POINT_SIZE_GRANULARITY = @as(c_int, 0x0B13); pub const GL_LINE_SMOOTH = @as(c_int, 0x0B20); pub const GL_LINE_WIDTH = @as(c_int, 0x0B21); pub const GL_LINE_WIDTH_RANGE = @as(c_int, 0x0B22); pub const GL_LINE_WIDTH_GRANULARITY = @as(c_int, 0x0B23); pub const GL_POLYGON_MODE = @as(c_int, 0x0B40); pub const GL_POLYGON_SMOOTH = @as(c_int, 0x0B41); pub const GL_CULL_FACE = @as(c_int, 0x0B44); pub const GL_CULL_FACE_MODE = @as(c_int, 0x0B45); pub const GL_FRONT_FACE = @as(c_int, 0x0B46); pub const GL_DEPTH_RANGE = @as(c_int, 0x0B70); pub const GL_DEPTH_TEST = @as(c_int, 0x0B71); pub const GL_DEPTH_WRITEMASK = @as(c_int, 0x0B72); pub const GL_DEPTH_CLEAR_VALUE = @as(c_int, 0x0B73); pub const GL_DEPTH_FUNC = @as(c_int, 0x0B74); pub const GL_STENCIL_TEST = @as(c_int, 0x0B90); pub const GL_STENCIL_CLEAR_VALUE = @as(c_int, 0x0B91); pub const GL_STENCIL_FUNC = @as(c_int, 0x0B92); pub const GL_STENCIL_VALUE_MASK = @as(c_int, 0x0B93); pub const GL_STENCIL_FAIL = @as(c_int, 0x0B94); pub const GL_STENCIL_PASS_DEPTH_FAIL = @as(c_int, 0x0B95); pub const GL_STENCIL_PASS_DEPTH_PASS = @as(c_int, 0x0B96); pub const GL_STENCIL_REF = @as(c_int, 0x0B97); pub const GL_STENCIL_WRITEMASK = @as(c_int, 0x0B98); pub const GL_VIEWPORT = @as(c_int, 0x0BA2); pub const GL_DITHER = @as(c_int, 0x0BD0); pub const GL_BLEND_DST = @as(c_int, 0x0BE0); pub const GL_BLEND_SRC = @as(c_int, 0x0BE1); pub const GL_BLEND = @as(c_int, 0x0BE2); pub const GL_LOGIC_OP_MODE = @as(c_int, 0x0BF0); pub const GL_DRAW_BUFFER = @as(c_int, 0x0C01); pub const GL_READ_BUFFER = @as(c_int, 0x0C02); pub const GL_SCISSOR_BOX = @as(c_int, 0x0C10); pub const GL_SCISSOR_TEST = @as(c_int, 0x0C11); pub const GL_COLOR_CLEAR_VALUE = @as(c_int, 0x0C22); pub const GL_COLOR_WRITEMASK = @as(c_int, 0x0C23); pub const GL_DOUBLEBUFFER = @as(c_int, 0x0C32); pub const GL_STEREO = @as(c_int, 0x0C33); pub const GL_LINE_SMOOTH_HINT = @as(c_int, 0x0C52); pub const GL_POLYGON_SMOOTH_HINT = @as(c_int, 0x0C53); pub const GL_UNPACK_SWAP_BYTES = @as(c_int, 0x0CF0); pub const GL_UNPACK_LSB_FIRST = @as(c_int, 0x0CF1); pub const GL_UNPACK_ROW_LENGTH = @as(c_int, 0x0CF2); pub const GL_UNPACK_SKIP_ROWS = @as(c_int, 0x0CF3); pub const GL_UNPACK_SKIP_PIXELS = @as(c_int, 0x0CF4); pub const GL_UNPACK_ALIGNMENT = @as(c_int, 0x0CF5); pub const GL_PACK_SWAP_BYTES = @as(c_int, 0x0D00); pub const GL_PACK_LSB_FIRST = @as(c_int, 0x0D01); pub const GL_PACK_ROW_LENGTH = @as(c_int, 0x0D02); pub const GL_PACK_SKIP_ROWS = @as(c_int, 0x0D03); pub const GL_PACK_SKIP_PIXELS = @as(c_int, 0x0D04); pub const GL_PACK_ALIGNMENT = @as(c_int, 0x0D05); pub const GL_MAX_TEXTURE_SIZE = @as(c_int, 0x0D33); pub const GL_MAX_VIEWPORT_DIMS = @as(c_int, 0x0D3A); pub const GL_SUBPIXEL_BITS = @as(c_int, 0x0D50); pub const GL_TEXTURE_1D = @as(c_int, 0x0DE0); pub const GL_TEXTURE_2D = @as(c_int, 0x0DE1); pub const GL_TEXTURE_WIDTH = @as(c_int, 0x1000); pub const GL_TEXTURE_HEIGHT = @as(c_int, 0x1001); pub const GL_TEXTURE_BORDER_COLOR = @as(c_int, 0x1004); pub const GL_DONT_CARE = @as(c_int, 0x1100); pub const GL_FASTEST = @as(c_int, 0x1101); pub const GL_NICEST = @as(c_int, 0x1102); pub const GL_BYTE = @as(c_int, 0x1400); pub const GL_UNSIGNED_BYTE = @as(c_int, 0x1401); pub const GL_SHORT = @as(c_int, 0x1402); pub const GL_UNSIGNED_SHORT = @as(c_int, 0x1403); pub const GL_INT = @as(c_int, 0x1404); pub const GL_UNSIGNED_INT = @as(c_int, 0x1405); pub const GL_FLOAT = @as(c_int, 0x1406); pub const GL_CLEAR = @as(c_int, 0x1500); pub const GL_AND = @as(c_int, 0x1501); pub const GL_AND_REVERSE = @as(c_int, 0x1502); pub const GL_COPY = @as(c_int, 0x1503); pub const GL_AND_INVERTED = @as(c_int, 0x1504); pub const GL_NOOP = @as(c_int, 0x1505); pub const GL_XOR = @as(c_int, 0x1506); pub const GL_OR = @as(c_int, 0x1507); pub const GL_NOR = @as(c_int, 0x1508); pub const GL_EQUIV = @as(c_int, 0x1509); pub const GL_INVERT = @as(c_int, 0x150A); pub const GL_OR_REVERSE = @as(c_int, 0x150B); pub const GL_COPY_INVERTED = @as(c_int, 0x150C); pub const GL_OR_INVERTED = @as(c_int, 0x150D); pub const GL_NAND = @as(c_int, 0x150E); pub const GL_SET = @as(c_int, 0x150F); pub const GL_TEXTURE = @as(c_int, 0x1702); pub const GL_COLOR = @as(c_int, 0x1800); pub const GL_DEPTH = @as(c_int, 0x1801); pub const GL_STENCIL = @as(c_int, 0x1802); pub const GL_STENCIL_INDEX = @as(c_int, 0x1901); pub const GL_DEPTH_COMPONENT = @as(c_int, 0x1902); pub const GL_RED = @as(c_int, 0x1903); pub const GL_GREEN = @as(c_int, 0x1904); pub const GL_BLUE = @as(c_int, 0x1905); pub const GL_ALPHA = @as(c_int, 0x1906); pub const GL_RGB = @as(c_int, 0x1907); pub const GL_RGBA = @as(c_int, 0x1908); pub const GL_POINT = @as(c_int, 0x1B00); pub const GL_LINE = @as(c_int, 0x1B01); pub const GL_FILL = @as(c_int, 0x1B02); pub const GL_KEEP = @as(c_int, 0x1E00); pub const GL_REPLACE = @as(c_int, 0x1E01); pub const GL_INCR = @as(c_int, 0x1E02); pub const GL_DECR = @as(c_int, 0x1E03); pub const GL_VENDOR = @as(c_int, 0x1F00); pub const GL_RENDERER = @as(c_int, 0x1F01); pub const GL_VERSION = @as(c_int, 0x1F02); pub const GL_EXTENSIONS = @as(c_int, 0x1F03); pub const GL_NEAREST = @as(c_int, 0x2600); pub const GL_LINEAR = @as(c_int, 0x2601); pub const GL_NEAREST_MIPMAP_NEAREST = @as(c_int, 0x2700); pub const GL_LINEAR_MIPMAP_NEAREST = @as(c_int, 0x2701); pub const GL_NEAREST_MIPMAP_LINEAR = @as(c_int, 0x2702); pub const GL_LINEAR_MIPMAP_LINEAR = @as(c_int, 0x2703); pub const GL_TEXTURE_MAG_FILTER = @as(c_int, 0x2800); pub const GL_TEXTURE_MIN_FILTER = @as(c_int, 0x2801); pub const GL_TEXTURE_WRAP_S = @as(c_int, 0x2802); pub const GL_TEXTURE_WRAP_T = @as(c_int, 0x2803); pub const GL_REPEAT = @as(c_int, 0x2901); pub const GL_COLOR_LOGIC_OP = @as(c_int, 0x0BF2); pub const GL_POLYGON_OFFSET_UNITS = @as(c_int, 0x2A00); pub const GL_POLYGON_OFFSET_POINT = @as(c_int, 0x2A01); pub const GL_POLYGON_OFFSET_LINE = @as(c_int, 0x2A02); pub const GL_POLYGON_OFFSET_FILL = @import("std").zig.c_translation.promoteIntLiteral(c_int, 0x8037, .hexadecimal); pub const GL_POLYGON_OFFSET_FACTOR = @import("std").zig.c_translation.promoteIntLiteral(c_int, 0x8038, .hexadecimal); pub const GL_TEXTURE_BINDING_1D = @import("std").zig.c_translation.promoteIntLiteral(c_int, 0x8068, .hexadecimal); pub const GL_TEXTURE_BINDING_2D = @import("std").zig.c_translation.promoteIntLiteral(c_int, 0x8069, .hexadecimal); pub const GL_TEXTURE_INTERNAL_FORMAT = @as(c_int, 0x1003); pub const GL_TEXTURE_RED_SIZE = @import("std").zig.c_translation.promoteIntLiteral(c_int, 0x805C, .hexadecimal); pub const GL_TEXTURE_GREEN_SIZE = @import("std").zig.c_translation.promoteIntLiteral(c_int, 0x805D, .hexadecimal); pub const GL_TEXTURE_BLUE_SIZE = @import("std").zig.c_translation.promoteIntLiteral(c_int, 0x805E, .hexadecimal); pub const GL_TEXTURE_ALPHA_SIZE = @import("std").zig.c_translation.promoteIntLiteral(c_int, 0x805F, .hexadecimal); pub const GL_DOUBLE = @as(c_int, 0x140A); pub const GL_PROXY_TEXTURE_1D = @import("std").zig.c_translation.promoteIntLiteral(c_int, 0x8063, .hexadecimal); pub const GL_PROXY_TEXTURE_2D = @import("std").zig.c_translation.promoteIntLiteral(c_int, 0x8064, .hexadecimal); pub const GL_R3_G3_B2 = @as(c_int, 0x2A10); pub const GL_RGB4 = @import("std").zig.c_translation.promoteIntLiteral(c_int, 0x804F, .hexadecimal); pub const GL_RGB5 = @import("std").zig.c_translation.promoteIntLiteral(c_int, 0x8050, .hexadecimal); pub const GL_RGB8 = @import("std").zig.c_translation.promoteIntLiteral(c_int, 0x8051, .hexadecimal); pub const GL_RGB10 = @import("std").zig.c_translation.promoteIntLiteral(c_int, 0x8052, .hexadecimal); pub const GL_RGB12 = @import("std").zig.c_translation.promoteIntLiteral(c_int, 0x8053, .hexadecimal); pub const GL_RGB16 = @import("std").zig.c_translation.promoteIntLiteral(c_int, 0x8054, .hexadecimal); pub const GL_RGBA2 = @import("std").zig.c_translation.promoteIntLiteral(c_int, 0x8055, .hexadecimal); pub const GL_RGBA4 = @import("std").zig.c_translation.promoteIntLiteral(c_int, 0x8056, .hexadecimal); pub const GL_RGB5_A1 = @import("std").zig.c_translation.promoteIntLiteral(c_int, 0x8057, .hexadecimal); pub const GL_RGBA8 = @import("std").zig.c_translation.promoteIntLiteral(c_int, 0x8058, .hexadecimal); pub const GL_RGB10_A2 = @import("std").zig.c_translation.promoteIntLiteral(c_int, 0x8059, .hexadecimal); pub const GL_RGBA12 = @import("std").zig.c_translation.promoteIntLiteral(c_int, 0x805A, .hexadecimal); pub const GL_RGBA16 = @import("std").zig.c_translation.promoteIntLiteral(c_int, 0x805B, .hexadecimal); pub const GL_UNSIGNED_BYTE_3_3_2 = @import("std").zig.c_translation.promoteIntLiteral(c_int, 0x8032, .hexadecimal); pub const GL_UNSIGNED_SHORT_4_4_4_4 = @import("std").zig.c_translation.promoteIntLiteral(c_int, 0x8033, .hexadecimal); pub const GL_UNSIGNED_SHORT_5_5_5_1 = @import("std").zig.c_translation.promoteIntLiteral(c_int, 0x8034, .hexadecimal); pub const GL_UNSIGNED_INT_8_8_8_8 = @import("std").zig.c_translation.promoteIntLiteral(c_int, 0x8035, .hexadecimal); pub const GL_UNSIGNED_INT_10_10_10_2 = @import("std").zig.c_translation.promoteIntLiteral(c_int, 0x8036, .hexadecimal); pub const GL_TEXTURE_BINDING_3D = @import("std").zig.c_translation.promoteIntLiteral(c_int, 0x806A, .hexadecimal); pub const GL_PACK_SKIP_IMAGES = @import("std").zig.c_translation.promoteIntLiteral(c_int, 0x806B, .hexadecimal); pub const GL_PACK_IMAGE_HEIGHT = @import("std").zig.c_translation.promoteIntLiteral(c_int, 0x806C, .hexadecimal); pub const GL_UNPACK_SKIP_IMAGES = @import("std").zig.c_translation.promoteIntLiteral(c_int, 0x806D, .hexadecimal); pub const GL_UNPACK_IMAGE_HEIGHT = @import("std").zig.c_translation.promoteIntLiteral(c_int, 0x806E, .hexadecimal); pub const GL_TEXTURE_3D = @import("std").zig.c_translation.promoteIntLiteral(c_int, 0x806F, .hexadecimal); pub const GL_PROXY_TEXTURE_3D = @import("std").zig.c_translation.promoteIntLiteral(c_int, 0x8070, .hexadecimal); pub const GL_TEXTURE_DEPTH = @import("std").zig.c_translation.promoteIntLiteral(c_int, 0x8071, .hexadecimal); pub const GL_TEXTURE_WRAP_R = @import("std").zig.c_translation.promoteIntLiteral(c_int, 0x8072, .hexadecimal); pub const GL_MAX_3D_TEXTURE_SIZE = @import("std").zig.c_translation.promoteIntLiteral(c_int, 0x8073, .hexadecimal); pub const GL_UNSIGNED_BYTE_2_3_3_REV = @import("std").zig.c_translation.promoteIntLiteral(c_int, 0x8362, .hexadecimal); pub const GL_UNSIGNED_SHORT_5_6_5 = @import("std").zig.c_translation.promoteIntLiteral(c_int, 0x8363, .hexadecimal); pub const GL_UNSIGNED_SHORT_5_6_5_REV = @import("std").zig.c_translation.promoteIntLiteral(c_int, 0x8364, .hexadecimal); pub const GL_UNSIGNED_SHORT_4_4_4_4_REV = @import("std").zig.c_translation.promoteIntLiteral(c_int, 0x8365, .hexadecimal); pub const GL_UNSIGNED_SHORT_1_5_5_5_REV = @import("std").zig.c_translation.promoteIntLiteral(c_int, 0x8366, .hexadecimal); pub const GL_UNSIGNED_INT_8_8_8_8_REV = @import("std").zig.c_translation.promoteIntLiteral(c_int, 0x8367, .hexadecimal); pub const GL_UNSIGNED_INT_2_10_10_10_REV = @import("std").zig.c_translation.promoteIntLiteral(c_int, 0x8368, .hexadecimal); pub const GL_BGR = @import("std").zig.c_translation.promoteIntLiteral(c_int, 0x80E0, .hexadecimal); pub const GL_BGRA = @import("std").zig.c_translation.promoteIntLiteral(c_int, 0x80E1, .hexadecimal); pub const GL_MAX_ELEMENTS_VERTICES = @import("std").zig.c_translation.promoteIntLiteral(c_int, 0x80E8, .hexadecimal); pub const GL_MAX_ELEMENTS_INDICES = @import("std").zig.c_translation.promoteIntLiteral(c_int, 0x80E9, .hexadecimal); pub const GL_CLAMP_TO_EDGE = @import("std").zig.c_translation.promoteIntLiteral(c_int, 0x812F, .hexadecimal); pub const GL_TEXTURE_MIN_LOD = @import("std").zig.c_translation.promoteIntLiteral(c_int, 0x813A, .hexadecimal); pub const GL_TEXTURE_MAX_LOD = @import("std").zig.c_translation.promoteIntLiteral(c_int, 0x813B, .hexadecimal); pub const GL_TEXTURE_BASE_LEVEL = @import("std").zig.c_translation.promoteIntLiteral(c_int, 0x813C, .hexadecimal); pub const GL_TEXTURE_MAX_LEVEL = @import("std").zig.c_translation.promoteIntLiteral(c_int, 0x813D, .hexadecimal); pub const GL_SMOOTH_POINT_SIZE_RANGE = @as(c_int, 0x0B12); pub const GL_SMOOTH_POINT_SIZE_GRANULARITY = @as(c_int, 0x0B13); pub const GL_SMOOTH_LINE_WIDTH_RANGE = @as(c_int, 0x0B22); pub const GL_SMOOTH_LINE_WIDTH_GRANULARITY = @as(c_int, 0x0B23); pub const GL_ALIASED_LINE_WIDTH_RANGE = @import("std").zig.c_translation.promoteIntLiteral(c_int, 0x846E, .hexadecimal); pub const GL_TEXTURE0 = @import("std").zig.c_translation.promoteIntLiteral(c_int, 0x84C0, .hexadecimal); pub const GL_TEXTURE1 = @import("std").zig.c_translation.promoteIntLiteral(c_int, 0x84C1, .hexadecimal); pub const GL_TEXTURE2 = @import("std").zig.c_translation.promoteIntLiteral(c_int, 0x84C2, .hexadecimal); pub const GL_TEXTURE3 = @import("std").zig.c_translation.promoteIntLiteral(c_int, 0x84C3, .hexadecimal); pub const GL_TEXTURE4 = @import("std").zig.c_translation.promoteIntLiteral(c_int, 0x84C4, .hexadecimal); pub const GL_TEXTURE5 = @import("std").zig.c_translation.promoteIntLiteral(c_int, 0x84C5, .hexadecimal); pub const GL_TEXTURE6 = @import("std").zig.c_translation.promoteIntLiteral(c_int, 0x84C6, .hexadecimal); pub const GL_TEXTURE7 = @import("std").zig.c_translation.promoteIntLiteral(c_int, 0x84C7, .hexadecimal); pub const GL_TEXTURE8 = @import("std").zig.c_translation.promoteIntLiteral(c_int, 0x84C8, .hexadecimal); pub const GL_TEXTURE9 = @import("std").zig.c_translation.promoteIntLiteral(c_int, 0x84C9, .hexadecimal); pub const GL_TEXTURE10 = @import("std").zig.c_translation.promoteIntLiteral(c_int, 0x84CA, .hexadecimal); pub const GL_TEXTURE11 = @import("std").zig.c_translation.promoteIntLiteral(c_int, 0x84CB, .hexadecimal); pub const GL_TEXTURE12 = @import("std").zig.c_translation.promoteIntLiteral(c_int, 0x84CC, .hexadecimal); pub const GL_TEXTURE13 = @import("std").zig.c_translation.promoteIntLiteral(c_int, 0x84CD, .hexadecimal); pub const GL_TEXTURE14 = @import("std").zig.c_translation.promoteIntLiteral(c_int, 0x84CE, .hexadecimal); pub const GL_TEXTURE15 = @import("std").zig.c_translation.promoteIntLiteral(c_int, 0x84CF, .hexadecimal); pub const GL_TEXTURE16 = @import("std").zig.c_translation.promoteIntLiteral(c_int, 0x84D0, .hexadecimal); pub const GL_TEXTURE17 = @import("std").zig.c_translation.promoteIntLiteral(c_int, 0x84D1, .hexadecimal); pub const GL_TEXTURE18 = @import("std").zig.c_translation.promoteIntLiteral(c_int, 0x84D2, .hexadecimal); pub const GL_TEXTURE19 = @import("std").zig.c_translation.promoteIntLiteral(c_int, 0x84D3, .hexadecimal); pub const GL_TEXTURE20 = @import("std").zig.c_translation.promoteIntLiteral(c_int, 0x84D4, .hexadecimal); pub const GL_TEXTURE21 = @import("std").zig.c_translation.promoteIntLiteral(c_int, 0x84D5, .hexadecimal); pub const GL_TEXTURE22 = @import("std").zig.c_translation.promoteIntLiteral(c_int, 0x84D6, .hexadecimal); pub const GL_TEXTURE23 = @import("std").zig.c_translation.promoteIntLiteral(c_int, 0x84D7, .hexadecimal); pub const GL_TEXTURE24 = @import("std").zig.c_translation.promoteIntLiteral(c_int, 0x84D8, .hexadecimal); pub const GL_TEXTURE25 = @import("std").zig.c_translation.promoteIntLiteral(c_int, 0x84D9, .hexadecimal); pub const GL_TEXTURE26 = @import("std").zig.c_translation.promoteIntLiteral(c_int, 0x84DA, .hexadecimal); pub const GL_TEXTURE27 = @import("std").zig.c_translation.promoteIntLiteral(c_int, 0x84DB, .hexadecimal); pub const GL_TEXTURE28 = @import("std").zig.c_translation.promoteIntLiteral(c_int, 0x84DC, .hexadecimal); pub const GL_TEXTURE29 = @import("std").zig.c_translation.promoteIntLiteral(c_int, 0x84DD, .hexadecimal); pub const GL_TEXTURE30 = @import("std").zig.c_translation.promoteIntLiteral(c_int, 0x84DE, .hexadecimal); pub const GL_TEXTURE31 = @import("std").zig.c_translation.promoteIntLiteral(c_int, 0x84DF, .hexadecimal); pub const GL_ACTIVE_TEXTURE = @import("std").zig.c_translation.promoteIntLiteral(c_int, 0x84E0, .hexadecimal); pub const GL_MULTISAMPLE = @import("std").zig.c_translation.promoteIntLiteral(c_int, 0x809D, .hexadecimal); pub const GL_SAMPLE_ALPHA_TO_COVERAGE = @import("std").zig.c_translation.promoteIntLiteral(c_int, 0x809E, .hexadecimal); pub const GL_SAMPLE_ALPHA_TO_ONE = @import("std").zig.c_translation.promoteIntLiteral(c_int, 0x809F, .hexadecimal); pub const GL_SAMPLE_COVERAGE = @import("std").zig.c_translation.promoteIntLiteral(c_int, 0x80A0, .hexadecimal); pub const GL_SAMPLE_BUFFERS = @import("std").zig.c_translation.promoteIntLiteral(c_int, 0x80A8, .hexadecimal); pub const GL_SAMPLES = @import("std").zig.c_translation.promoteIntLiteral(c_int, 0x80A9, .hexadecimal); pub const GL_SAMPLE_COVERAGE_VALUE = @import("std").zig.c_translation.promoteIntLiteral(c_int, 0x80AA, .hexadecimal); pub const GL_SAMPLE_COVERAGE_INVERT = @import("std").zig.c_translation.promoteIntLiteral(c_int, 0x80AB, .hexadecimal); pub const GL_TEXTURE_CUBE_MAP = @import("std").zig.c_translation.promoteIntLiteral(c_int, 0x8513, .hexadecimal); pub const GL_TEXTURE_BINDING_CUBE_MAP = @import("std").zig.c_translation.promoteIntLiteral(c_int, 0x8514, .hexadecimal); pub const GL_TEXTURE_CUBE_MAP_POSITIVE_X = @import("std").zig.c_translation.promoteIntLiteral(c_int, 0x8515, .hexadecimal); pub const GL_TEXTURE_CUBE_MAP_NEGATIVE_X = @import("std").zig.c_translation.promoteIntLiteral(c_int, 0x8516, .hexadecimal); pub const GL_TEXTURE_CUBE_MAP_POSITIVE_Y = @import("std").zig.c_translation.promoteIntLiteral(c_int, 0x8517, .hexadecimal); pub const GL_TEXTURE_CUBE_MAP_NEGATIVE_Y = @import("std").zig.c_translation.promoteIntLiteral(c_int, 0x8518, .hexadecimal); pub const GL_TEXTURE_CUBE_MAP_POSITIVE_Z = @import("std").zig.c_translation.promoteIntLiteral(c_int, 0x8519, .hexadecimal); pub const GL_TEXTURE_CUBE_MAP_NEGATIVE_Z = @import("std").zig.c_translation.promoteIntLiteral(c_int, 0x851A, .hexadecimal); pub const GL_PROXY_TEXTURE_CUBE_MAP = @import("std").zig.c_translation.promoteIntLiteral(c_int, 0x851B, .hexadecimal); pub const GL_MAX_CUBE_MAP_TEXTURE_SIZE = @import("std").zig.c_translation.promoteIntLiteral(c_int, 0x851C, .hexadecimal); pub const GL_COMPRESSED_RGB = @import("std").zig.c_translation.promoteIntLiteral(c_int, 0x84ED, .hexadecimal); pub const GL_COMPRESSED_RGBA = @import("std").zig.c_translation.promoteIntLiteral(c_int, 0x84EE, .hexadecimal); pub const GL_TEXTURE_COMPRESSION_HINT = @import("std").zig.c_translation.promoteIntLiteral(c_int, 0x84EF, .hexadecimal); pub const GL_TEXTURE_COMPRESSED_IMAGE_SIZE = @import("std").zig.c_translation.promoteIntLiteral(c_int, 0x86A0, .hexadecimal); pub const GL_TEXTURE_COMPRESSED = @import("std").zig.c_translation.promoteIntLiteral(c_int, 0x86A1, .hexadecimal); pub const GL_NUM_COMPRESSED_TEXTURE_FORMATS = @import("std").zig.c_translation.promoteIntLiteral(c_int, 0x86A2, .hexadecimal); pub const GL_COMPRESSED_TEXTURE_FORMATS = @import("std").zig.c_translation.promoteIntLiteral(c_int, 0x86A3, .hexadecimal); pub const GL_CLAMP_TO_BORDER = @import("std").zig.c_translation.promoteIntLiteral(c_int, 0x812D, .hexadecimal); pub const GL_BLEND_DST_RGB = @import("std").zig.c_translation.promoteIntLiteral(c_int, 0x80C8, .hexadecimal); pub const GL_BLEND_SRC_RGB = @import("std").zig.c_translation.promoteIntLiteral(c_int, 0x80C9, .hexadecimal); pub const GL_BLEND_DST_ALPHA = @import("std").zig.c_translation.promoteIntLiteral(c_int, 0x80CA, .hexadecimal); pub const GL_BLEND_SRC_ALPHA = @import("std").zig.c_translation.promoteIntLiteral(c_int, 0x80CB, .hexadecimal); pub const GL_POINT_FADE_THRESHOLD_SIZE = @import("std").zig.c_translation.promoteIntLiteral(c_int, 0x8128, .hexadecimal); pub const GL_DEPTH_COMPONENT16 = @import("std").zig.c_translation.promoteIntLiteral(c_int, 0x81A5, .hexadecimal); pub const GL_DEPTH_COMPONENT24 = @import("std").zig.c_translation.promoteIntLiteral(c_int, 0x81A6, .hexadecimal); pub const GL_DEPTH_COMPONENT32 = @import("std").zig.c_translation.promoteIntLiteral(c_int, 0x81A7, .hexadecimal); pub const GL_MIRRORED_REPEAT = @import("std").zig.c_translation.promoteIntLiteral(c_int, 0x8370, .hexadecimal); pub const GL_MAX_TEXTURE_LOD_BIAS = @import("std").zig.c_translation.promoteIntLiteral(c_int, 0x84FD, .hexadecimal); pub const GL_TEXTURE_LOD_BIAS = @import("std").zig.c_translation.promoteIntLiteral(c_int, 0x8501, .hexadecimal); pub const GL_INCR_WRAP = @import("std").zig.c_translation.promoteIntLiteral(c_int, 0x8507, .hexadecimal); pub const GL_DECR_WRAP = @import("std").zig.c_translation.promoteIntLiteral(c_int, 0x8508, .hexadecimal); pub const GL_TEXTURE_DEPTH_SIZE = @import("std").zig.c_translation.promoteIntLiteral(c_int, 0x884A, .hexadecimal); pub const GL_TEXTURE_COMPARE_MODE = @import("std").zig.c_translation.promoteIntLiteral(c_int, 0x884C, .hexadecimal); pub const GL_TEXTURE_COMPARE_FUNC = @import("std").zig.c_translation.promoteIntLiteral(c_int, 0x884D, .hexadecimal); pub const GL_BLEND_COLOR = @import("std").zig.c_translation.promoteIntLiteral(c_int, 0x8005, .hexadecimal); pub const GL_BLEND_EQUATION = @import("std").zig.c_translation.promoteIntLiteral(c_int, 0x8009, .hexadecimal); pub const GL_CONSTANT_COLOR = @import("std").zig.c_translation.promoteIntLiteral(c_int, 0x8001, .hexadecimal); pub const GL_ONE_MINUS_CONSTANT_COLOR = @import("std").zig.c_translation.promoteIntLiteral(c_int, 0x8002, .hexadecimal); pub const GL_CONSTANT_ALPHA = @import("std").zig.c_translation.promoteIntLiteral(c_int, 0x8003, .hexadecimal); pub const GL_ONE_MINUS_CONSTANT_ALPHA = @import("std").zig.c_translation.promoteIntLiteral(c_int, 0x8004, .hexadecimal); pub const GL_FUNC_ADD = @import("std").zig.c_translation.promoteIntLiteral(c_int, 0x8006, .hexadecimal); pub const GL_FUNC_REVERSE_SUBTRACT = @import("std").zig.c_translation.promoteIntLiteral(c_int, 0x800B, .hexadecimal); pub const GL_FUNC_SUBTRACT = @import("std").zig.c_translation.promoteIntLiteral(c_int, 0x800A, .hexadecimal); pub const GL_MIN = @import("std").zig.c_translation.promoteIntLiteral(c_int, 0x8007, .hexadecimal); pub const GL_MAX = @import("std").zig.c_translation.promoteIntLiteral(c_int, 0x8008, .hexadecimal); pub const GL_BUFFER_SIZE = @import("std").zig.c_translation.promoteIntLiteral(c_int, 0x8764, .hexadecimal); pub const GL_BUFFER_USAGE = @import("std").zig.c_translation.promoteIntLiteral(c_int, 0x8765, .hexadecimal); pub const GL_QUERY_COUNTER_BITS = @import("std").zig.c_translation.promoteIntLiteral(c_int, 0x8864, .hexadecimal); pub const GL_CURRENT_QUERY = @import("std").zig.c_translation.promoteIntLiteral(c_int, 0x8865, .hexadecimal); pub const GL_QUERY_RESULT = @import("std").zig.c_translation.promoteIntLiteral(c_int, 0x8866, .hexadecimal); pub const GL_QUERY_RESULT_AVAILABLE = @import("std").zig.c_translation.promoteIntLiteral(c_int, 0x8867, .hexadecimal); pub const GL_ARRAY_BUFFER = @import("std").zig.c_translation.promoteIntLiteral(c_int, 0x8892, .hexadecimal); pub const GL_ELEMENT_ARRAY_BUFFER = @import("std").zig.c_translation.promoteIntLiteral(c_int, 0x8893, .hexadecimal); pub const GL_ARRAY_BUFFER_BINDING = @import("std").zig.c_translation.promoteIntLiteral(c_int, 0x8894, .hexadecimal); pub const GL_ELEMENT_ARRAY_BUFFER_BINDING = @import("std").zig.c_translation.promoteIntLiteral(c_int, 0x8895, .hexadecimal); pub const GL_VERTEX_ATTRIB_ARRAY_BUFFER_BINDING = @import("std").zig.c_translation.promoteIntLiteral(c_int, 0x889F, .hexadecimal); pub const GL_READ_ONLY = @import("std").zig.c_translation.promoteIntLiteral(c_int, 0x88B8, .hexadecimal); pub const GL_WRITE_ONLY = @import("std").zig.c_translation.promoteIntLiteral(c_int, 0x88B9, .hexadecimal); pub const GL_READ_WRITE = @import("std").zig.c_translation.promoteIntLiteral(c_int, 0x88BA, .hexadecimal); pub const GL_BUFFER_ACCESS = @import("std").zig.c_translation.promoteIntLiteral(c_int, 0x88BB, .hexadecimal); pub const GL_BUFFER_MAPPED = @import("std").zig.c_translation.promoteIntLiteral(c_int, 0x88BC, .hexadecimal); pub const GL_BUFFER_MAP_POINTER = @import("std").zig.c_translation.promoteIntLiteral(c_int, 0x88BD, .hexadecimal); pub const GL_STREAM_DRAW = @import("std").zig.c_translation.promoteIntLiteral(c_int, 0x88E0, .hexadecimal); pub const GL_STREAM_READ = @import("std").zig.c_translation.promoteIntLiteral(c_int, 0x88E1, .hexadecimal); pub const GL_STREAM_COPY = @import("std").zig.c_translation.promoteIntLiteral(c_int, 0x88E2, .hexadecimal); pub const GL_STATIC_DRAW = @import("std").zig.c_translation.promoteIntLiteral(c_int, 0x88E4, .hexadecimal); pub const GL_STATIC_READ = @import("std").zig.c_translation.promoteIntLiteral(c_int, 0x88E5, .hexadecimal); pub const GL_STATIC_COPY = @import("std").zig.c_translation.promoteIntLiteral(c_int, 0x88E6, .hexadecimal); pub const GL_DYNAMIC_DRAW = @import("std").zig.c_translation.promoteIntLiteral(c_int, 0x88E8, .hexadecimal); pub const GL_DYNAMIC_READ = @import("std").zig.c_translation.promoteIntLiteral(c_int, 0x88E9, .hexadecimal); pub const GL_DYNAMIC_COPY = @import("std").zig.c_translation.promoteIntLiteral(c_int, 0x88EA, .hexadecimal); pub const GL_SAMPLES_PASSED = @import("std").zig.c_translation.promoteIntLiteral(c_int, 0x8914, .hexadecimal); pub const GL_SRC1_ALPHA = @import("std").zig.c_translation.promoteIntLiteral(c_int, 0x8589, .hexadecimal); pub const GL_BLEND_EQUATION_RGB = @import("std").zig.c_translation.promoteIntLiteral(c_int, 0x8009, .hexadecimal); pub const GL_VERTEX_ATTRIB_ARRAY_ENABLED = @import("std").zig.c_translation.promoteIntLiteral(c_int, 0x8622, .hexadecimal); pub const GL_VERTEX_ATTRIB_ARRAY_SIZE = @import("std").zig.c_translation.promoteIntLiteral(c_int, 0x8623, .hexadecimal); pub const GL_VERTEX_ATTRIB_ARRAY_STRIDE = @import("std").zig.c_translation.promoteIntLiteral(c_int, 0x8624, .hexadecimal); pub const GL_VERTEX_ATTRIB_ARRAY_TYPE = @import("std").zig.c_translation.promoteIntLiteral(c_int, 0x8625, .hexadecimal); pub const GL_CURRENT_VERTEX_ATTRIB = @import("std").zig.c_translation.promoteIntLiteral(c_int, 0x8626, .hexadecimal); pub const GL_VERTEX_PROGRAM_POINT_SIZE = @import("std").zig.c_translation.promoteIntLiteral(c_int, 0x8642, .hexadecimal); pub const GL_VERTEX_ATTRIB_ARRAY_POINTER = @import("std").zig.c_translation.promoteIntLiteral(c_int, 0x8645, .hexadecimal); pub const GL_STENCIL_BACK_FUNC = @import("std").zig.c_translation.promoteIntLiteral(c_int, 0x8800, .hexadecimal); pub const GL_STENCIL_BACK_FAIL = @import("std").zig.c_translation.promoteIntLiteral(c_int, 0x8801, .hexadecimal); pub const GL_STENCIL_BACK_PASS_DEPTH_FAIL = @import("std").zig.c_translation.promoteIntLiteral(c_int, 0x8802, .hexadecimal); pub const GL_STENCIL_BACK_PASS_DEPTH_PASS = @import("std").zig.c_translation.promoteIntLiteral(c_int, 0x8803, .hexadecimal); pub const GL_MAX_DRAW_BUFFERS = @import("std").zig.c_translation.promoteIntLiteral(c_int, 0x8824, .hexadecimal); pub const GL_DRAW_BUFFER0 = @import("std").zig.c_translation.promoteIntLiteral(c_int, 0x8825, .hexadecimal); pub const GL_DRAW_BUFFER1 = @import("std").zig.c_translation.promoteIntLiteral(c_int, 0x8826, .hexadecimal); pub const GL_DRAW_BUFFER2 = @import("std").zig.c_translation.promoteIntLiteral(c_int, 0x8827, .hexadecimal); pub const GL_DRAW_BUFFER3 = @import("std").zig.c_translation.promoteIntLiteral(c_int, 0x8828, .hexadecimal); pub const GL_DRAW_BUFFER4 = @import("std").zig.c_translation.promoteIntLiteral(c_int, 0x8829, .hexadecimal); pub const GL_DRAW_BUFFER5 = @import("std").zig.c_translation.promoteIntLiteral(c_int, 0x882A, .hexadecimal); pub const GL_DRAW_BUFFER6 = @import("std").zig.c_translation.promoteIntLiteral(c_int, 0x882B, .hexadecimal); pub const GL_DRAW_BUFFER7 = @import("std").zig.c_translation.promoteIntLiteral(c_int, 0x882C, .hexadecimal); pub const GL_DRAW_BUFFER8 = @import("std").zig.c_translation.promoteIntLiteral(c_int, 0x882D, .hexadecimal); pub const GL_DRAW_BUFFER9 = @import("std").zig.c_translation.promoteIntLiteral(c_int, 0x882E, .hexadecimal); pub const GL_DRAW_BUFFER10 = @import("std").zig.c_translation.promoteIntLiteral(c_int, 0x882F, .hexadecimal); pub const GL_DRAW_BUFFER11 = @import("std").zig.c_translation.promoteIntLiteral(c_int, 0x8830, .hexadecimal); pub const GL_DRAW_BUFFER12 = @import("std").zig.c_translation.promoteIntLiteral(c_int, 0x8831, .hexadecimal); pub const GL_DRAW_BUFFER13 = @import("std").zig.c_translation.promoteIntLiteral(c_int, 0x8832, .hexadecimal); pub const GL_DRAW_BUFFER14 = @import("std").zig.c_translation.promoteIntLiteral(c_int, 0x8833, .hexadecimal); pub const GL_DRAW_BUFFER15 = @import("std").zig.c_translation.promoteIntLiteral(c_int, 0x8834, .hexadecimal); pub const GL_BLEND_EQUATION_ALPHA = @import("std").zig.c_translation.promoteIntLiteral(c_int, 0x883D, .hexadecimal); pub const GL_MAX_VERTEX_ATTRIBS = @import("std").zig.c_translation.promoteIntLiteral(c_int, 0x8869, .hexadecimal); pub const GL_VERTEX_ATTRIB_ARRAY_NORMALIZED = @import("std").zig.c_translation.promoteIntLiteral(c_int, 0x886A, .hexadecimal); pub const GL_MAX_TEXTURE_IMAGE_UNITS = @import("std").zig.c_translation.promoteIntLiteral(c_int, 0x8872, .hexadecimal); pub const GL_FRAGMENT_SHADER = @import("std").zig.c_translation.promoteIntLiteral(c_int, 0x8B30, .hexadecimal); pub const GL_VERTEX_SHADER = @import("std").zig.c_translation.promoteIntLiteral(c_int, 0x8B31, .hexadecimal); pub const GL_MAX_FRAGMENT_UNIFORM_COMPONENTS = @import("std").zig.c_translation.promoteIntLiteral(c_int, 0x8B49, .hexadecimal); pub const GL_MAX_VERTEX_UNIFORM_COMPONENTS = @import("std").zig.c_translation.promoteIntLiteral(c_int, 0x8B4A, .hexadecimal); pub const GL_MAX_VARYING_FLOATS = @import("std").zig.c_translation.promoteIntLiteral(c_int, 0x8B4B, .hexadecimal); pub const GL_MAX_VERTEX_TEXTURE_IMAGE_UNITS = @import("std").zig.c_translation.promoteIntLiteral(c_int, 0x8B4C, .hexadecimal); pub const GL_MAX_COMBINED_TEXTURE_IMAGE_UNITS = @import("std").zig.c_translation.promoteIntLiteral(c_int, 0x8B4D, .hexadecimal); pub const GL_SHADER_TYPE = @import("std").zig.c_translation.promoteIntLiteral(c_int, 0x8B4F, .hexadecimal); pub const GL_FLOAT_VEC2 = @import("std").zig.c_translation.promoteIntLiteral(c_int, 0x8B50, .hexadecimal); pub const GL_FLOAT_VEC3 = @import("std").zig.c_translation.promoteIntLiteral(c_int, 0x8B51, .hexadecimal); pub const GL_FLOAT_VEC4 = @import("std").zig.c_translation.promoteIntLiteral(c_int, 0x8B52, .hexadecimal); pub const GL_INT_VEC2 = @import("std").zig.c_translation.promoteIntLiteral(c_int, 0x8B53, .hexadecimal); pub const GL_INT_VEC3 = @import("std").zig.c_translation.promoteIntLiteral(c_int, 0x8B54, .hexadecimal); pub const GL_INT_VEC4 = @import("std").zig.c_translation.promoteIntLiteral(c_int, 0x8B55, .hexadecimal); pub const GL_BOOL = @import("std").zig.c_translation.promoteIntLiteral(c_int, 0x8B56, .hexadecimal); pub const GL_BOOL_VEC2 = @import("std").zig.c_translation.promoteIntLiteral(c_int, 0x8B57, .hexadecimal); pub const GL_BOOL_VEC3 = @import("std").zig.c_translation.promoteIntLiteral(c_int, 0x8B58, .hexadecimal); pub const GL_BOOL_VEC4 = @import("std").zig.c_translation.promoteIntLiteral(c_int, 0x8B59, .hexadecimal); pub const GL_FLOAT_MAT2 = @import("std").zig.c_translation.promoteIntLiteral(c_int, 0x8B5A, .hexadecimal); pub const GL_FLOAT_MAT3 = @import("std").zig.c_translation.promoteIntLiteral(c_int, 0x8B5B, .hexadecimal); pub const GL_FLOAT_MAT4 = @import("std").zig.c_translation.promoteIntLiteral(c_int, 0x8B5C, .hexadecimal); pub const GL_SAMPLER_1D = @import("std").zig.c_translation.promoteIntLiteral(c_int, 0x8B5D, .hexadecimal); pub const GL_SAMPLER_2D = @import("std").zig.c_translation.promoteIntLiteral(c_int, 0x8B5E, .hexadecimal); pub const GL_SAMPLER_3D = @import("std").zig.c_translation.promoteIntLiteral(c_int, 0x8B5F, .hexadecimal); pub const GL_SAMPLER_CUBE = @import("std").zig.c_translation.promoteIntLiteral(c_int, 0x8B60, .hexadecimal); pub const GL_SAMPLER_1D_SHADOW = @import("std").zig.c_translation.promoteIntLiteral(c_int, 0x8B61, .hexadecimal); pub const GL_SAMPLER_2D_SHADOW = @import("std").zig.c_translation.promoteIntLiteral(c_int, 0x8B62, .hexadecimal); pub const GL_DELETE_STATUS = @import("std").zig.c_translation.promoteIntLiteral(c_int, 0x8B80, .hexadecimal); pub const GL_COMPILE_STATUS = @import("std").zig.c_translation.promoteIntLiteral(c_int, 0x8B81, .hexadecimal); pub const GL_LINK_STATUS = @import("std").zig.c_translation.promoteIntLiteral(c_int, 0x8B82, .hexadecimal); pub const GL_VALIDATE_STATUS = @import("std").zig.c_translation.promoteIntLiteral(c_int, 0x8B83, .hexadecimal); pub const GL_INFO_LOG_LENGTH = @import("std").zig.c_translation.promoteIntLiteral(c_int, 0x8B84, .hexadecimal); pub const GL_ATTACHED_SHADERS = @import("std").zig.c_translation.promoteIntLiteral(c_int, 0x8B85, .hexadecimal); pub const GL_ACTIVE_UNIFORMS = @import("std").zig.c_translation.promoteIntLiteral(c_int, 0x8B86, .hexadecimal); pub const GL_ACTIVE_UNIFORM_MAX_LENGTH = @import("std").zig.c_translation.promoteIntLiteral(c_int, 0x8B87, .hexadecimal); pub const GL_SHADER_SOURCE_LENGTH = @import("std").zig.c_translation.promoteIntLiteral(c_int, 0x8B88, .hexadecimal); pub const GL_ACTIVE_ATTRIBUTES = @import("std").zig.c_translation.promoteIntLiteral(c_int, 0x8B89, .hexadecimal); pub const GL_ACTIVE_ATTRIBUTE_MAX_LENGTH = @import("std").zig.c_translation.promoteIntLiteral(c_int, 0x8B8A, .hexadecimal); pub const GL_FRAGMENT_SHADER_DERIVATIVE_HINT = @import("std").zig.c_translation.promoteIntLiteral(c_int, 0x8B8B, .hexadecimal); pub const GL_SHADING_LANGUAGE_VERSION = @import("std").zig.c_translation.promoteIntLiteral(c_int, 0x8B8C, .hexadecimal); pub const GL_CURRENT_PROGRAM = @import("std").zig.c_translation.promoteIntLiteral(c_int, 0x8B8D, .hexadecimal); pub const GL_POINT_SPRITE_COORD_ORIGIN = @import("std").zig.c_translation.promoteIntLiteral(c_int, 0x8CA0, .hexadecimal); pub const GL_LOWER_LEFT = @import("std").zig.c_translation.promoteIntLiteral(c_int, 0x8CA1, .hexadecimal); pub const GL_UPPER_LEFT = @import("std").zig.c_translation.promoteIntLiteral(c_int, 0x8CA2, .hexadecimal); pub const GL_STENCIL_BACK_REF = @import("std").zig.c_translation.promoteIntLiteral(c_int, 0x8CA3, .hexadecimal); pub const GL_STENCIL_BACK_VALUE_MASK = @import("std").zig.c_translation.promoteIntLiteral(c_int, 0x8CA4, .hexadecimal); pub const GL_STENCIL_BACK_WRITEMASK = @import("std").zig.c_translation.promoteIntLiteral(c_int, 0x8CA5, .hexadecimal); pub const GL_PIXEL_PACK_BUFFER = @import("std").zig.c_translation.promoteIntLiteral(c_int, 0x88EB, .hexadecimal); pub const GL_PIXEL_UNPACK_BUFFER = @import("std").zig.c_translation.promoteIntLiteral(c_int, 0x88EC, .hexadecimal); pub const GL_PIXEL_PACK_BUFFER_BINDING = @import("std").zig.c_translation.promoteIntLiteral(c_int, 0x88ED, .hexadecimal); pub const GL_PIXEL_UNPACK_BUFFER_BINDING = @import("std").zig.c_translation.promoteIntLiteral(c_int, 0x88EF, .hexadecimal); pub const GL_FLOAT_MAT2x3 = @import("std").zig.c_translation.promoteIntLiteral(c_int, 0x8B65, .hexadecimal); pub const GL_FLOAT_MAT2x4 = @import("std").zig.c_translation.promoteIntLiteral(c_int, 0x8B66, .hexadecimal); pub const GL_FLOAT_MAT3x2 = @import("std").zig.c_translation.promoteIntLiteral(c_int, 0x8B67, .hexadecimal); pub const GL_FLOAT_MAT3x4 = @import("std").zig.c_translation.promoteIntLiteral(c_int, 0x8B68, .hexadecimal); pub const GL_FLOAT_MAT4x2 = @import("std").zig.c_translation.promoteIntLiteral(c_int, 0x8B69, .hexadecimal); pub const GL_FLOAT_MAT4x3 = @import("std").zig.c_translation.promoteIntLiteral(c_int, 0x8B6A, .hexadecimal); pub const GL_SRGB = @import("std").zig.c_translation.promoteIntLiteral(c_int, 0x8C40, .hexadecimal); pub const GL_SRGB8 = @import("std").zig.c_translation.promoteIntLiteral(c_int, 0x8C41, .hexadecimal); pub const GL_SRGB_ALPHA = @import("std").zig.c_translation.promoteIntLiteral(c_int, 0x8C42, .hexadecimal); pub const GL_SRGB8_ALPHA8 = @import("std").zig.c_translation.promoteIntLiteral(c_int, 0x8C43, .hexadecimal); pub const GL_COMPRESSED_SRGB = @import("std").zig.c_translation.promoteIntLiteral(c_int, 0x8C48, .hexadecimal); pub const GL_COMPRESSED_SRGB_ALPHA = @import("std").zig.c_translation.promoteIntLiteral(c_int, 0x8C49, .hexadecimal); pub const GL_COMPARE_REF_TO_TEXTURE = @import("std").zig.c_translation.promoteIntLiteral(c_int, 0x884E, .hexadecimal); pub const GL_CLIP_DISTANCE0 = @as(c_int, 0x3000); pub const GL_CLIP_DISTANCE1 = @as(c_int, 0x3001); pub const GL_CLIP_DISTANCE2 = @as(c_int, 0x3002); pub const GL_CLIP_DISTANCE3 = @as(c_int, 0x3003); pub const GL_CLIP_DISTANCE4 = @as(c_int, 0x3004); pub const GL_CLIP_DISTANCE5 = @as(c_int, 0x3005); pub const GL_CLIP_DISTANCE6 = @as(c_int, 0x3006); pub const GL_CLIP_DISTANCE7 = @as(c_int, 0x3007); pub const GL_MAX_CLIP_DISTANCES = @as(c_int, 0x0D32); pub const GL_MAJOR_VERSION = @import("std").zig.c_translation.promoteIntLiteral(c_int, 0x821B, .hexadecimal); pub const GL_MINOR_VERSION = @import("std").zig.c_translation.promoteIntLiteral(c_int, 0x821C, .hexadecimal); pub const GL_NUM_EXTENSIONS = @import("std").zig.c_translation.promoteIntLiteral(c_int, 0x821D, .hexadecimal); pub const GL_CONTEXT_FLAGS = @import("std").zig.c_translation.promoteIntLiteral(c_int, 0x821E, .hexadecimal); pub const GL_COMPRESSED_RED = @import("std").zig.c_translation.promoteIntLiteral(c_int, 0x8225, .hexadecimal); pub const GL_COMPRESSED_RG = @import("std").zig.c_translation.promoteIntLiteral(c_int, 0x8226, .hexadecimal); pub const GL_CONTEXT_FLAG_FORWARD_COMPATIBLE_BIT = @as(c_int, 0x00000001); pub const GL_RGBA32F = @import("std").zig.c_translation.promoteIntLiteral(c_int, 0x8814, .hexadecimal); pub const GL_RGB32F = @import("std").zig.c_translation.promoteIntLiteral(c_int, 0x8815, .hexadecimal); pub const GL_RGBA16F = @import("std").zig.c_translation.promoteIntLiteral(c_int, 0x881A, .hexadecimal); pub const GL_RGB16F = @import("std").zig.c_translation.promoteIntLiteral(c_int, 0x881B, .hexadecimal); pub const GL_VERTEX_ATTRIB_ARRAY_INTEGER = @import("std").zig.c_translation.promoteIntLiteral(c_int, 0x88FD, .hexadecimal); pub const GL_MAX_ARRAY_TEXTURE_LAYERS = @import("std").zig.c_translation.promoteIntLiteral(c_int, 0x88FF, .hexadecimal); pub const GL_MIN_PROGRAM_TEXEL_OFFSET = @import("std").zig.c_translation.promoteIntLiteral(c_int, 0x8904, .hexadecimal); pub const GL_MAX_PROGRAM_TEXEL_OFFSET = @import("std").zig.c_translation.promoteIntLiteral(c_int, 0x8905, .hexadecimal); pub const GL_CLAMP_READ_COLOR = @import("std").zig.c_translation.promoteIntLiteral(c_int, 0x891C, .hexadecimal); pub const GL_FIXED_ONLY = @import("std").zig.c_translation.promoteIntLiteral(c_int, 0x891D, .hexadecimal); pub const GL_MAX_VARYING_COMPONENTS = @import("std").zig.c_translation.promoteIntLiteral(c_int, 0x8B4B, .hexadecimal); pub const GL_TEXTURE_1D_ARRAY = @import("std").zig.c_translation.promoteIntLiteral(c_int, 0x8C18, .hexadecimal); pub const GL_PROXY_TEXTURE_1D_ARRAY = @import("std").zig.c_translation.promoteIntLiteral(c_int, 0x8C19, .hexadecimal); pub const GL_TEXTURE_2D_ARRAY = @import("std").zig.c_translation.promoteIntLiteral(c_int, 0x8C1A, .hexadecimal); pub const GL_PROXY_TEXTURE_2D_ARRAY = @import("std").zig.c_translation.promoteIntLiteral(c_int, 0x8C1B, .hexadecimal); pub const GL_TEXTURE_BINDING_1D_ARRAY = @import("std").zig.c_translation.promoteIntLiteral(c_int, 0x8C1C, .hexadecimal); pub const GL_TEXTURE_BINDING_2D_ARRAY = @import("std").zig.c_translation.promoteIntLiteral(c_int, 0x8C1D, .hexadecimal); pub const GL_R11F_G11F_B10F = @import("std").zig.c_translation.promoteIntLiteral(c_int, 0x8C3A, .hexadecimal); pub const GL_UNSIGNED_INT_10F_11F_11F_REV = @import("std").zig.c_translation.promoteIntLiteral(c_int, 0x8C3B, .hexadecimal); pub const GL_RGB9_E5 = @import("std").zig.c_translation.promoteIntLiteral(c_int, 0x8C3D, .hexadecimal); pub const GL_UNSIGNED_INT_5_9_9_9_REV = @import("std").zig.c_translation.promoteIntLiteral(c_int, 0x8C3E, .hexadecimal); pub const GL_TEXTURE_SHARED_SIZE = @import("std").zig.c_translation.promoteIntLiteral(c_int, 0x8C3F, .hexadecimal); pub const GL_TRANSFORM_FEEDBACK_VARYING_MAX_LENGTH = @import("std").zig.c_translation.promoteIntLiteral(c_int, 0x8C76, .hexadecimal); pub const GL_TRANSFORM_FEEDBACK_BUFFER_MODE = @import("std").zig.c_translation.promoteIntLiteral(c_int, 0x8C7F, .hexadecimal); pub const GL_MAX_TRANSFORM_FEEDBACK_SEPARATE_COMPONENTS = @import("std").zig.c_translation.promoteIntLiteral(c_int, 0x8C80, .hexadecimal); pub const GL_TRANSFORM_FEEDBACK_VARYINGS = @import("std").zig.c_translation.promoteIntLiteral(c_int, 0x8C83, .hexadecimal); pub const GL_TRANSFORM_FEEDBACK_BUFFER_START = @import("std").zig.c_translation.promoteIntLiteral(c_int, 0x8C84, .hexadecimal); pub const GL_TRANSFORM_FEEDBACK_BUFFER_SIZE = @import("std").zig.c_translation.promoteIntLiteral(c_int, 0x8C85, .hexadecimal); pub const GL_PRIMITIVES_GENERATED = @import("std").zig.c_translation.promoteIntLiteral(c_int, 0x8C87, .hexadecimal); pub const GL_TRANSFORM_FEEDBACK_PRIMITIVES_WRITTEN = @import("std").zig.c_translation.promoteIntLiteral(c_int, 0x8C88, .hexadecimal); pub const GL_RASTERIZER_DISCARD = @import("std").zig.c_translation.promoteIntLiteral(c_int, 0x8C89, .hexadecimal); pub const GL_MAX_TRANSFORM_FEEDBACK_INTERLEAVED_COMPONENTS = @import("std").zig.c_translation.promoteIntLiteral(c_int, 0x8C8A, .hexadecimal); pub const GL_MAX_TRANSFORM_FEEDBACK_SEPARATE_ATTRIBS = @import("std").zig.c_translation.promoteIntLiteral(c_int, 0x8C8B, .hexadecimal); pub const GL_INTERLEAVED_ATTRIBS = @import("std").zig.c_translation.promoteIntLiteral(c_int, 0x8C8C, .hexadecimal); pub const GL_SEPARATE_ATTRIBS = @import("std").zig.c_translation.promoteIntLiteral(c_int, 0x8C8D, .hexadecimal); pub const GL_TRANSFORM_FEEDBACK_BUFFER = @import("std").zig.c_translation.promoteIntLiteral(c_int, 0x8C8E, .hexadecimal); pub const GL_TRANSFORM_FEEDBACK_BUFFER_BINDING = @import("std").zig.c_translation.promoteIntLiteral(c_int, 0x8C8F, .hexadecimal); pub const GL_RGBA32UI = @import("std").zig.c_translation.promoteIntLiteral(c_int, 0x8D70, .hexadecimal); pub const GL_RGB32UI = @import("std").zig.c_translation.promoteIntLiteral(c_int, 0x8D71, .hexadecimal); pub const GL_RGBA16UI = @import("std").zig.c_translation.promoteIntLiteral(c_int, 0x8D76, .hexadecimal); pub const GL_RGB16UI = @import("std").zig.c_translation.promoteIntLiteral(c_int, 0x8D77, .hexadecimal); pub const GL_RGBA8UI = @import("std").zig.c_translation.promoteIntLiteral(c_int, 0x8D7C, .hexadecimal); pub const GL_RGB8UI = @import("std").zig.c_translation.promoteIntLiteral(c_int, 0x8D7D, .hexadecimal); pub const GL_RGBA32I = @import("std").zig.c_translation.promoteIntLiteral(c_int, 0x8D82, .hexadecimal); pub const GL_RGB32I = @import("std").zig.c_translation.promoteIntLiteral(c_int, 0x8D83, .hexadecimal); pub const GL_RGBA16I = @import("std").zig.c_translation.promoteIntLiteral(c_int, 0x8D88, .hexadecimal); pub const GL_RGB16I = @import("std").zig.c_translation.promoteIntLiteral(c_int, 0x8D89, .hexadecimal); pub const GL_RGBA8I = @import("std").zig.c_translation.promoteIntLiteral(c_int, 0x8D8E, .hexadecimal); pub const GL_RGB8I = @import("std").zig.c_translation.promoteIntLiteral(c_int, 0x8D8F, .hexadecimal); pub const GL_RED_INTEGER = @import("std").zig.c_translation.promoteIntLiteral(c_int, 0x8D94, .hexadecimal); pub const GL_GREEN_INTEGER = @import("std").zig.c_translation.promoteIntLiteral(c_int, 0x8D95, .hexadecimal); pub const GL_BLUE_INTEGER = @import("std").zig.c_translation.promoteIntLiteral(c_int, 0x8D96, .hexadecimal); pub const GL_RGB_INTEGER = @import("std").zig.c_translation.promoteIntLiteral(c_int, 0x8D98, .hexadecimal); pub const GL_RGBA_INTEGER = @import("std").zig.c_translation.promoteIntLiteral(c_int, 0x8D99, .hexadecimal); pub const GL_BGR_INTEGER = @import("std").zig.c_translation.promoteIntLiteral(c_int, 0x8D9A, .hexadecimal); pub const GL_BGRA_INTEGER = @import("std").zig.c_translation.promoteIntLiteral(c_int, 0x8D9B, .hexadecimal); pub const GL_SAMPLER_1D_ARRAY = @import("std").zig.c_translation.promoteIntLiteral(c_int, 0x8DC0, .hexadecimal); pub const GL_SAMPLER_2D_ARRAY = @import("std").zig.c_translation.promoteIntLiteral(c_int, 0x8DC1, .hexadecimal); pub const GL_SAMPLER_1D_ARRAY_SHADOW = @import("std").zig.c_translation.promoteIntLiteral(c_int, 0x8DC3, .hexadecimal); pub const GL_SAMPLER_2D_ARRAY_SHADOW = @import("std").zig.c_translation.promoteIntLiteral(c_int, 0x8DC4, .hexadecimal); pub const GL_SAMPLER_CUBE_SHADOW = @import("std").zig.c_translation.promoteIntLiteral(c_int, 0x8DC5, .hexadecimal); pub const GL_UNSIGNED_INT_VEC2 = @import("std").zig.c_translation.promoteIntLiteral(c_int, 0x8DC6, .hexadecimal); pub const GL_UNSIGNED_INT_VEC3 = @import("std").zig.c_translation.promoteIntLiteral(c_int, 0x8DC7, .hexadecimal); pub const GL_UNSIGNED_INT_VEC4 = @import("std").zig.c_translation.promoteIntLiteral(c_int, 0x8DC8, .hexadecimal); pub const GL_INT_SAMPLER_1D = @import("std").zig.c_translation.promoteIntLiteral(c_int, 0x8DC9, .hexadecimal); pub const GL_INT_SAMPLER_2D = @import("std").zig.c_translation.promoteIntLiteral(c_int, 0x8DCA, .hexadecimal); pub const GL_INT_SAMPLER_3D = @import("std").zig.c_translation.promoteIntLiteral(c_int, 0x8DCB, .hexadecimal); pub const GL_INT_SAMPLER_CUBE = @import("std").zig.c_translation.promoteIntLiteral(c_int, 0x8DCC, .hexadecimal); pub const GL_INT_SAMPLER_1D_ARRAY = @import("std").zig.c_translation.promoteIntLiteral(c_int, 0x8DCE, .hexadecimal); pub const GL_INT_SAMPLER_2D_ARRAY = @import("std").zig.c_translation.promoteIntLiteral(c_int, 0x8DCF, .hexadecimal); pub const GL_UNSIGNED_INT_SAMPLER_1D = @import("std").zig.c_translation.promoteIntLiteral(c_int, 0x8DD1, .hexadecimal); pub const GL_UNSIGNED_INT_SAMPLER_2D = @import("std").zig.c_translation.promoteIntLiteral(c_int, 0x8DD2, .hexadecimal); pub const GL_UNSIGNED_INT_SAMPLER_3D = @import("std").zig.c_translation.promoteIntLiteral(c_int, 0x8DD3, .hexadecimal); pub const GL_UNSIGNED_INT_SAMPLER_CUBE = @import("std").zig.c_translation.promoteIntLiteral(c_int, 0x8DD4, .hexadecimal); pub const GL_UNSIGNED_INT_SAMPLER_1D_ARRAY = @import("std").zig.c_translation.promoteIntLiteral(c_int, 0x8DD6, .hexadecimal); pub const GL_UNSIGNED_INT_SAMPLER_2D_ARRAY = @import("std").zig.c_translation.promoteIntLiteral(c_int, 0x8DD7, .hexadecimal); pub const GL_QUERY_WAIT = @import("std").zig.c_translation.promoteIntLiteral(c_int, 0x8E13, .hexadecimal); pub const GL_QUERY_NO_WAIT = @import("std").zig.c_translation.promoteIntLiteral(c_int, 0x8E14, .hexadecimal); pub const GL_QUERY_BY_REGION_WAIT = @import("std").zig.c_translation.promoteIntLiteral(c_int, 0x8E15, .hexadecimal); pub const GL_QUERY_BY_REGION_NO_WAIT = @import("std").zig.c_translation.promoteIntLiteral(c_int, 0x8E16, .hexadecimal); pub const GL_BUFFER_ACCESS_FLAGS = @import("std").zig.c_translation.promoteIntLiteral(c_int, 0x911F, .hexadecimal); pub const GL_BUFFER_MAP_LENGTH = @import("std").zig.c_translation.promoteIntLiteral(c_int, 0x9120, .hexadecimal); pub const GL_BUFFER_MAP_OFFSET = @import("std").zig.c_translation.promoteIntLiteral(c_int, 0x9121, .hexadecimal); pub const GL_DEPTH_COMPONENT32F = @import("std").zig.c_translation.promoteIntLiteral(c_int, 0x8CAC, .hexadecimal); pub const GL_DEPTH32F_STENCIL8 = @import("std").zig.c_translation.promoteIntLiteral(c_int, 0x8CAD, .hexadecimal); pub const GL_FLOAT_32_UNSIGNED_INT_24_8_REV = @import("std").zig.c_translation.promoteIntLiteral(c_int, 0x8DAD, .hexadecimal); pub const GL_INVALID_FRAMEBUFFER_OPERATION = @as(c_int, 0x0506); pub const GL_FRAMEBUFFER_ATTACHMENT_COLOR_ENCODING = @import("std").zig.c_translation.promoteIntLiteral(c_int, 0x8210, .hexadecimal); pub const GL_FRAMEBUFFER_ATTACHMENT_COMPONENT_TYPE = @import("std").zig.c_translation.promoteIntLiteral(c_int, 0x8211, .hexadecimal); pub const GL_FRAMEBUFFER_ATTACHMENT_RED_SIZE = @import("std").zig.c_translation.promoteIntLiteral(c_int, 0x8212, .hexadecimal); pub const GL_FRAMEBUFFER_ATTACHMENT_GREEN_SIZE = @import("std").zig.c_translation.promoteIntLiteral(c_int, 0x8213, .hexadecimal); pub const GL_FRAMEBUFFER_ATTACHMENT_BLUE_SIZE = @import("std").zig.c_translation.promoteIntLiteral(c_int, 0x8214, .hexadecimal); pub const GL_FRAMEBUFFER_ATTACHMENT_ALPHA_SIZE = @import("std").zig.c_translation.promoteIntLiteral(c_int, 0x8215, .hexadecimal); pub const GL_FRAMEBUFFER_ATTACHMENT_DEPTH_SIZE = @import("std").zig.c_translation.promoteIntLiteral(c_int, 0x8216, .hexadecimal); pub const GL_FRAMEBUFFER_ATTACHMENT_STENCIL_SIZE = @import("std").zig.c_translation.promoteIntLiteral(c_int, 0x8217, .hexadecimal); pub const GL_FRAMEBUFFER_DEFAULT = @import("std").zig.c_translation.promoteIntLiteral(c_int, 0x8218, .hexadecimal); pub const GL_FRAMEBUFFER_UNDEFINED = @import("std").zig.c_translation.promoteIntLiteral(c_int, 0x8219, .hexadecimal); pub const GL_DEPTH_STENCIL_ATTACHMENT = @import("std").zig.c_translation.promoteIntLiteral(c_int, 0x821A, .hexadecimal); pub const GL_MAX_RENDERBUFFER_SIZE = @import("std").zig.c_translation.promoteIntLiteral(c_int, 0x84E8, .hexadecimal); pub const GL_DEPTH_STENCIL = @import("std").zig.c_translation.promoteIntLiteral(c_int, 0x84F9, .hexadecimal); pub const GL_UNSIGNED_INT_24_8 = @import("std").zig.c_translation.promoteIntLiteral(c_int, 0x84FA, .hexadecimal); pub const GL_DEPTH24_STENCIL8 = @import("std").zig.c_translation.promoteIntLiteral(c_int, 0x88F0, .hexadecimal); pub const GL_TEXTURE_STENCIL_SIZE = @import("std").zig.c_translation.promoteIntLiteral(c_int, 0x88F1, .hexadecimal); pub const GL_TEXTURE_RED_TYPE = @import("std").zig.c_translation.promoteIntLiteral(c_int, 0x8C10, .hexadecimal); pub const GL_TEXTURE_GREEN_TYPE = @import("std").zig.c_translation.promoteIntLiteral(c_int, 0x8C11, .hexadecimal); pub const GL_TEXTURE_BLUE_TYPE = @import("std").zig.c_translation.promoteIntLiteral(c_int, 0x8C12, .hexadecimal); pub const GL_TEXTURE_ALPHA_TYPE = @import("std").zig.c_translation.promoteIntLiteral(c_int, 0x8C13, .hexadecimal); pub const GL_TEXTURE_DEPTH_TYPE = @import("std").zig.c_translation.promoteIntLiteral(c_int, 0x8C16, .hexadecimal); pub const GL_UNSIGNED_NORMALIZED = @import("std").zig.c_translation.promoteIntLiteral(c_int, 0x8C17, .hexadecimal); pub const GL_FRAMEBUFFER_BINDING = @import("std").zig.c_translation.promoteIntLiteral(c_int, 0x8CA6, .hexadecimal); pub const GL_DRAW_FRAMEBUFFER_BINDING = @import("std").zig.c_translation.promoteIntLiteral(c_int, 0x8CA6, .hexadecimal); pub const GL_RENDERBUFFER_BINDING = @import("std").zig.c_translation.promoteIntLiteral(c_int, 0x8CA7, .hexadecimal); pub const GL_READ_FRAMEBUFFER = @import("std").zig.c_translation.promoteIntLiteral(c_int, 0x8CA8, .hexadecimal); pub const GL_DRAW_FRAMEBUFFER = @import("std").zig.c_translation.promoteIntLiteral(c_int, 0x8CA9, .hexadecimal); pub const GL_READ_FRAMEBUFFER_BINDING = @import("std").zig.c_translation.promoteIntLiteral(c_int, 0x8CAA, .hexadecimal); pub const GL_RENDERBUFFER_SAMPLES = @import("std").zig.c_translation.promoteIntLiteral(c_int, 0x8CAB, .hexadecimal); pub const GL_FRAMEBUFFER_ATTACHMENT_OBJECT_TYPE = @import("std").zig.c_translation.promoteIntLiteral(c_int, 0x8CD0, .hexadecimal); pub const GL_FRAMEBUFFER_ATTACHMENT_OBJECT_NAME = @import("std").zig.c_translation.promoteIntLiteral(c_int, 0x8CD1, .hexadecimal); pub const GL_FRAMEBUFFER_ATTACHMENT_TEXTURE_LEVEL = @import("std").zig.c_translation.promoteIntLiteral(c_int, 0x8CD2, .hexadecimal); pub const GL_FRAMEBUFFER_ATTACHMENT_TEXTURE_CUBE_MAP_FACE = @import("std").zig.c_translation.promoteIntLiteral(c_int, 0x8CD3, .hexadecimal); pub const GL_FRAMEBUFFER_ATTACHMENT_TEXTURE_LAYER = @import("std").zig.c_translation.promoteIntLiteral(c_int, 0x8CD4, .hexadecimal); pub const GL_FRAMEBUFFER_COMPLETE = @import("std").zig.c_translation.promoteIntLiteral(c_int, 0x8CD5, .hexadecimal); pub const GL_FRAMEBUFFER_INCOMPLETE_ATTACHMENT = @import("std").zig.c_translation.promoteIntLiteral(c_int, 0x8CD6, .hexadecimal); pub const GL_FRAMEBUFFER_INCOMPLETE_MISSING_ATTACHMENT = @import("std").zig.c_translation.promoteIntLiteral(c_int, 0x8CD7, .hexadecimal); pub const GL_FRAMEBUFFER_INCOMPLETE_DRAW_BUFFER = @import("std").zig.c_translation.promoteIntLiteral(c_int, 0x8CDB, .hexadecimal); pub const GL_FRAMEBUFFER_INCOMPLETE_READ_BUFFER = @import("std").zig.c_translation.promoteIntLiteral(c_int, 0x8CDC, .hexadecimal); pub const GL_FRAMEBUFFER_UNSUPPORTED = @import("std").zig.c_translation.promoteIntLiteral(c_int, 0x8CDD, .hexadecimal); pub const GL_MAX_COLOR_ATTACHMENTS = @import("std").zig.c_translation.promoteIntLiteral(c_int, 0x8CDF, .hexadecimal); pub const GL_COLOR_ATTACHMENT0 = @import("std").zig.c_translation.promoteIntLiteral(c_int, 0x8CE0, .hexadecimal); pub const GL_COLOR_ATTACHMENT1 = @import("std").zig.c_translation.promoteIntLiteral(c_int, 0x8CE1, .hexadecimal); pub const GL_COLOR_ATTACHMENT2 = @import("std").zig.c_translation.promoteIntLiteral(c_int, 0x8CE2, .hexadecimal); pub const GL_COLOR_ATTACHMENT3 = @import("std").zig.c_translation.promoteIntLiteral(c_int, 0x8CE3, .hexadecimal); pub const GL_COLOR_ATTACHMENT4 = @import("std").zig.c_translation.promoteIntLiteral(c_int, 0x8CE4, .hexadecimal); pub const GL_COLOR_ATTACHMENT5 = @import("std").zig.c_translation.promoteIntLiteral(c_int, 0x8CE5, .hexadecimal); pub const GL_COLOR_ATTACHMENT6 = @import("std").zig.c_translation.promoteIntLiteral(c_int, 0x8CE6, .hexadecimal); pub const GL_COLOR_ATTACHMENT7 = @import("std").zig.c_translation.promoteIntLiteral(c_int, 0x8CE7, .hexadecimal); pub const GL_COLOR_ATTACHMENT8 = @import("std").zig.c_translation.promoteIntLiteral(c_int, 0x8CE8, .hexadecimal); pub const GL_COLOR_ATTACHMENT9 = @import("std").zig.c_translation.promoteIntLiteral(c_int, 0x8CE9, .hexadecimal); pub const GL_COLOR_ATTACHMENT10 = @import("std").zig.c_translation.promoteIntLiteral(c_int, 0x8CEA, .hexadecimal); pub const GL_COLOR_ATTACHMENT11 = @import("std").zig.c_translation.promoteIntLiteral(c_int, 0x8CEB, .hexadecimal); pub const GL_COLOR_ATTACHMENT12 = @import("std").zig.c_translation.promoteIntLiteral(c_int, 0x8CEC, .hexadecimal); pub const GL_COLOR_ATTACHMENT13 = @import("std").zig.c_translation.promoteIntLiteral(c_int, 0x8CED, .hexadecimal); pub const GL_COLOR_ATTACHMENT14 = @import("std").zig.c_translation.promoteIntLiteral(c_int, 0x8CEE, .hexadecimal); pub const GL_COLOR_ATTACHMENT15 = @import("std").zig.c_translation.promoteIntLiteral(c_int, 0x8CEF, .hexadecimal); pub const GL_COLOR_ATTACHMENT16 = @import("std").zig.c_translation.promoteIntLiteral(c_int, 0x8CF0, .hexadecimal); pub const GL_COLOR_ATTACHMENT17 = @import("std").zig.c_translation.promoteIntLiteral(c_int, 0x8CF1, .hexadecimal); pub const GL_COLOR_ATTACHMENT18 = @import("std").zig.c_translation.promoteIntLiteral(c_int, 0x8CF2, .hexadecimal); pub const GL_COLOR_ATTACHMENT19 = @import("std").zig.c_translation.promoteIntLiteral(c_int, 0x8CF3, .hexadecimal); pub const GL_COLOR_ATTACHMENT20 = @import("std").zig.c_translation.promoteIntLiteral(c_int, 0x8CF4, .hexadecimal); pub const GL_COLOR_ATTACHMENT21 = @import("std").zig.c_translation.promoteIntLiteral(c_int, 0x8CF5, .hexadecimal); pub const GL_COLOR_ATTACHMENT22 = @import("std").zig.c_translation.promoteIntLiteral(c_int, 0x8CF6, .hexadecimal); pub const GL_COLOR_ATTACHMENT23 = @import("std").zig.c_translation.promoteIntLiteral(c_int, 0x8CF7, .hexadecimal); pub const GL_COLOR_ATTACHMENT24 = @import("std").zig.c_translation.promoteIntLiteral(c_int, 0x8CF8, .hexadecimal); pub const GL_COLOR_ATTACHMENT25 = @import("std").zig.c_translation.promoteIntLiteral(c_int, 0x8CF9, .hexadecimal); pub const GL_COLOR_ATTACHMENT26 = @import("std").zig.c_translation.promoteIntLiteral(c_int, 0x8CFA, .hexadecimal); pub const GL_COLOR_ATTACHMENT27 = @import("std").zig.c_translation.promoteIntLiteral(c_int, 0x8CFB, .hexadecimal); pub const GL_COLOR_ATTACHMENT28 = @import("std").zig.c_translation.promoteIntLiteral(c_int, 0x8CFC, .hexadecimal); pub const GL_COLOR_ATTACHMENT29 = @import("std").zig.c_translation.promoteIntLiteral(c_int, 0x8CFD, .hexadecimal); pub const GL_COLOR_ATTACHMENT30 = @import("std").zig.c_translation.promoteIntLiteral(c_int, 0x8CFE, .hexadecimal); pub const GL_COLOR_ATTACHMENT31 = @import("std").zig.c_translation.promoteIntLiteral(c_int, 0x8CFF, .hexadecimal); pub const GL_DEPTH_ATTACHMENT = @import("std").zig.c_translation.promoteIntLiteral(c_int, 0x8D00, .hexadecimal); pub const GL_STENCIL_ATTACHMENT = @import("std").zig.c_translation.promoteIntLiteral(c_int, 0x8D20, .hexadecimal); pub const GL_FRAMEBUFFER = @import("std").zig.c_translation.promoteIntLiteral(c_int, 0x8D40, .hexadecimal); pub const GL_RENDERBUFFER = @import("std").zig.c_translation.promoteIntLiteral(c_int, 0x8D41, .hexadecimal); pub const GL_RENDERBUFFER_WIDTH = @import("std").zig.c_translation.promoteIntLiteral(c_int, 0x8D42, .hexadecimal); pub const GL_RENDERBUFFER_HEIGHT = @import("std").zig.c_translation.promoteIntLiteral(c_int, 0x8D43, .hexadecimal); pub const GL_RENDERBUFFER_INTERNAL_FORMAT = @import("std").zig.c_translation.promoteIntLiteral(c_int, 0x8D44, .hexadecimal); pub const GL_STENCIL_INDEX1 = @import("std").zig.c_translation.promoteIntLiteral(c_int, 0x8D46, .hexadecimal); pub const GL_STENCIL_INDEX4 = @import("std").zig.c_translation.promoteIntLiteral(c_int, 0x8D47, .hexadecimal); pub const GL_STENCIL_INDEX8 = @import("std").zig.c_translation.promoteIntLiteral(c_int, 0x8D48, .hexadecimal); pub const GL_STENCIL_INDEX16 = @import("std").zig.c_translation.promoteIntLiteral(c_int, 0x8D49, .hexadecimal); pub const GL_RENDERBUFFER_RED_SIZE = @import("std").zig.c_translation.promoteIntLiteral(c_int, 0x8D50, .hexadecimal); pub const GL_RENDERBUFFER_GREEN_SIZE = @import("std").zig.c_translation.promoteIntLiteral(c_int, 0x8D51, .hexadecimal); pub const GL_RENDERBUFFER_BLUE_SIZE = @import("std").zig.c_translation.promoteIntLiteral(c_int, 0x8D52, .hexadecimal); pub const GL_RENDERBUFFER_ALPHA_SIZE = @import("std").zig.c_translation.promoteIntLiteral(c_int, 0x8D53, .hexadecimal); pub const GL_RENDERBUFFER_DEPTH_SIZE = @import("std").zig.c_translation.promoteIntLiteral(c_int, 0x8D54, .hexadecimal); pub const GL_RENDERBUFFER_STENCIL_SIZE = @import("std").zig.c_translation.promoteIntLiteral(c_int, 0x8D55, .hexadecimal); pub const GL_FRAMEBUFFER_INCOMPLETE_MULTISAMPLE = @import("std").zig.c_translation.promoteIntLiteral(c_int, 0x8D56, .hexadecimal); pub const GL_MAX_SAMPLES = @import("std").zig.c_translation.promoteIntLiteral(c_int, 0x8D57, .hexadecimal); pub const GL_FRAMEBUFFER_SRGB = @import("std").zig.c_translation.promoteIntLiteral(c_int, 0x8DB9, .hexadecimal); pub const GL_HALF_FLOAT = @as(c_int, 0x140B); pub const GL_MAP_READ_BIT = @as(c_int, 0x0001); pub const GL_MAP_WRITE_BIT = @as(c_int, 0x0002); pub const GL_MAP_INVALIDATE_RANGE_BIT = @as(c_int, 0x0004); pub const GL_MAP_INVALIDATE_BUFFER_BIT = @as(c_int, 0x0008); pub const GL_MAP_FLUSH_EXPLICIT_BIT = @as(c_int, 0x0010); pub const GL_MAP_UNSYNCHRONIZED_BIT = @as(c_int, 0x0020); pub const GL_COMPRESSED_RED_RGTC1 = @import("std").zig.c_translation.promoteIntLiteral(c_int, 0x8DBB, .hexadecimal); pub const GL_COMPRESSED_SIGNED_RED_RGTC1 = @import("std").zig.c_translation.promoteIntLiteral(c_int, 0x8DBC, .hexadecimal); pub const GL_COMPRESSED_RG_RGTC2 = @import("std").zig.c_translation.promoteIntLiteral(c_int, 0x8DBD, .hexadecimal); pub const GL_COMPRESSED_SIGNED_RG_RGTC2 = @import("std").zig.c_translation.promoteIntLiteral(c_int, 0x8DBE, .hexadecimal); pub const GL_RG = @import("std").zig.c_translation.promoteIntLiteral(c_int, 0x8227, .hexadecimal); pub const GL_RG_INTEGER = @import("std").zig.c_translation.promoteIntLiteral(c_int, 0x8228, .hexadecimal); pub const GL_R8 = @import("std").zig.c_translation.promoteIntLiteral(c_int, 0x8229, .hexadecimal); pub const GL_R16 = @import("std").zig.c_translation.promoteIntLiteral(c_int, 0x822A, .hexadecimal); pub const GL_RG8 = @import("std").zig.c_translation.promoteIntLiteral(c_int, 0x822B, .hexadecimal); pub const GL_RG16 = @import("std").zig.c_translation.promoteIntLiteral(c_int, 0x822C, .hexadecimal); pub const GL_R16F = @import("std").zig.c_translation.promoteIntLiteral(c_int, 0x822D, .hexadecimal); pub const GL_R32F = @import("std").zig.c_translation.promoteIntLiteral(c_int, 0x822E, .hexadecimal); pub const GL_RG16F = @import("std").zig.c_translation.promoteIntLiteral(c_int, 0x822F, .hexadecimal); pub const GL_RG32F = @import("std").zig.c_translation.promoteIntLiteral(c_int, 0x8230, .hexadecimal); pub const GL_R8I = @import("std").zig.c_translation.promoteIntLiteral(c_int, 0x8231, .hexadecimal); pub const GL_R8UI = @import("std").zig.c_translation.promoteIntLiteral(c_int, 0x8232, .hexadecimal); pub const GL_R16I = @import("std").zig.c_translation.promoteIntLiteral(c_int, 0x8233, .hexadecimal); pub const GL_R16UI = @import("std").zig.c_translation.promoteIntLiteral(c_int, 0x8234, .hexadecimal); pub const GL_R32I = @import("std").zig.c_translation.promoteIntLiteral(c_int, 0x8235, .hexadecimal); pub const GL_R32UI = @import("std").zig.c_translation.promoteIntLiteral(c_int, 0x8236, .hexadecimal); pub const GL_RG8I = @import("std").zig.c_translation.promoteIntLiteral(c_int, 0x8237, .hexadecimal); pub const GL_RG8UI = @import("std").zig.c_translation.promoteIntLiteral(c_int, 0x8238, .hexadecimal); pub const GL_RG16I = @import("std").zig.c_translation.promoteIntLiteral(c_int, 0x8239, .hexadecimal); pub const GL_RG16UI = @import("std").zig.c_translation.promoteIntLiteral(c_int, 0x823A, .hexadecimal); pub const GL_RG32I = @import("std").zig.c_translation.promoteIntLiteral(c_int, 0x823B, .hexadecimal); pub const GL_RG32UI = @import("std").zig.c_translation.promoteIntLiteral(c_int, 0x823C, .hexadecimal); pub const GL_VERTEX_ARRAY_BINDING = @import("std").zig.c_translation.promoteIntLiteral(c_int, 0x85B5, .hexadecimal); pub const GL_SAMPLER_2D_RECT = @import("std").zig.c_translation.promoteIntLiteral(c_int, 0x8B63, .hexadecimal); pub const GL_SAMPLER_2D_RECT_SHADOW = @import("std").zig.c_translation.promoteIntLiteral(c_int, 0x8B64, .hexadecimal); pub const GL_SAMPLER_BUFFER = @import("std").zig.c_translation.promoteIntLiteral(c_int, 0x8DC2, .hexadecimal); pub const GL_INT_SAMPLER_2D_RECT = @import("std").zig.c_translation.promoteIntLiteral(c_int, 0x8DCD, .hexadecimal); pub const GL_INT_SAMPLER_BUFFER = @import("std").zig.c_translation.promoteIntLiteral(c_int, 0x8DD0, .hexadecimal); pub const GL_UNSIGNED_INT_SAMPLER_2D_RECT = @import("std").zig.c_translation.promoteIntLiteral(c_int, 0x8DD5, .hexadecimal); pub const GL_UNSIGNED_INT_SAMPLER_BUFFER = @import("std").zig.c_translation.promoteIntLiteral(c_int, 0x8DD8, .hexadecimal); pub const GL_TEXTURE_BUFFER = @import("std").zig.c_translation.promoteIntLiteral(c_int, 0x8C2A, .hexadecimal); pub const GL_MAX_TEXTURE_BUFFER_SIZE = @import("std").zig.c_translation.promoteIntLiteral(c_int, 0x8C2B, .hexadecimal); pub const GL_TEXTURE_BINDING_BUFFER = @import("std").zig.c_translation.promoteIntLiteral(c_int, 0x8C2C, .hexadecimal); pub const GL_TEXTURE_BUFFER_DATA_STORE_BINDING = @import("std").zig.c_translation.promoteIntLiteral(c_int, 0x8C2D, .hexadecimal); pub const GL_TEXTURE_RECTANGLE = @import("std").zig.c_translation.promoteIntLiteral(c_int, 0x84F5, .hexadecimal); pub const GL_TEXTURE_BINDING_RECTANGLE = @import("std").zig.c_translation.promoteIntLiteral(c_int, 0x84F6, .hexadecimal); pub const GL_PROXY_TEXTURE_RECTANGLE = @import("std").zig.c_translation.promoteIntLiteral(c_int, 0x84F7, .hexadecimal); pub const GL_MAX_RECTANGLE_TEXTURE_SIZE = @import("std").zig.c_translation.promoteIntLiteral(c_int, 0x84F8, .hexadecimal); pub const GL_R8_SNORM = @import("std").zig.c_translation.promoteIntLiteral(c_int, 0x8F94, .hexadecimal); pub const GL_RG8_SNORM = @import("std").zig.c_translation.promoteIntLiteral(c_int, 0x8F95, .hexadecimal); pub const GL_RGB8_SNORM = @import("std").zig.c_translation.promoteIntLiteral(c_int, 0x8F96, .hexadecimal); pub const GL_RGBA8_SNORM = @import("std").zig.c_translation.promoteIntLiteral(c_int, 0x8F97, .hexadecimal); pub const GL_R16_SNORM = @import("std").zig.c_translation.promoteIntLiteral(c_int, 0x8F98, .hexadecimal); pub const GL_RG16_SNORM = @import("std").zig.c_translation.promoteIntLiteral(c_int, 0x8F99, .hexadecimal); pub const GL_RGB16_SNORM = @import("std").zig.c_translation.promoteIntLiteral(c_int, 0x8F9A, .hexadecimal); pub const GL_RGBA16_SNORM = @import("std").zig.c_translation.promoteIntLiteral(c_int, 0x8F9B, .hexadecimal); pub const GL_SIGNED_NORMALIZED = @import("std").zig.c_translation.promoteIntLiteral(c_int, 0x8F9C, .hexadecimal); pub const GL_PRIMITIVE_RESTART = @import("std").zig.c_translation.promoteIntLiteral(c_int, 0x8F9D, .hexadecimal); pub const GL_PRIMITIVE_RESTART_INDEX = @import("std").zig.c_translation.promoteIntLiteral(c_int, 0x8F9E, .hexadecimal); pub const GL_COPY_READ_BUFFER = @import("std").zig.c_translation.promoteIntLiteral(c_int, 0x8F36, .hexadecimal); pub const GL_COPY_WRITE_BUFFER = @import("std").zig.c_translation.promoteIntLiteral(c_int, 0x8F37, .hexadecimal); pub const GL_UNIFORM_BUFFER = @import("std").zig.c_translation.promoteIntLiteral(c_int, 0x8A11, .hexadecimal); pub const GL_UNIFORM_BUFFER_BINDING = @import("std").zig.c_translation.promoteIntLiteral(c_int, 0x8A28, .hexadecimal); pub const GL_UNIFORM_BUFFER_START = @import("std").zig.c_translation.promoteIntLiteral(c_int, 0x8A29, .hexadecimal); pub const GL_UNIFORM_BUFFER_SIZE = @import("std").zig.c_translation.promoteIntLiteral(c_int, 0x8A2A, .hexadecimal); pub const GL_MAX_VERTEX_UNIFORM_BLOCKS = @import("std").zig.c_translation.promoteIntLiteral(c_int, 0x8A2B, .hexadecimal); pub const GL_MAX_GEOMETRY_UNIFORM_BLOCKS = @import("std").zig.c_translation.promoteIntLiteral(c_int, 0x8A2C, .hexadecimal); pub const GL_MAX_FRAGMENT_UNIFORM_BLOCKS = @import("std").zig.c_translation.promoteIntLiteral(c_int, 0x8A2D, .hexadecimal); pub const GL_MAX_COMBINED_UNIFORM_BLOCKS = @import("std").zig.c_translation.promoteIntLiteral(c_int, 0x8A2E, .hexadecimal); pub const GL_MAX_UNIFORM_BUFFER_BINDINGS = @import("std").zig.c_translation.promoteIntLiteral(c_int, 0x8A2F, .hexadecimal); pub const GL_MAX_UNIFORM_BLOCK_SIZE = @import("std").zig.c_translation.promoteIntLiteral(c_int, 0x8A30, .hexadecimal); pub const GL_MAX_COMBINED_VERTEX_UNIFORM_COMPONENTS = @import("std").zig.c_translation.promoteIntLiteral(c_int, 0x8A31, .hexadecimal); pub const GL_MAX_COMBINED_GEOMETRY_UNIFORM_COMPONENTS = @import("std").zig.c_translation.promoteIntLiteral(c_int, 0x8A32, .hexadecimal); pub const GL_MAX_COMBINED_FRAGMENT_UNIFORM_COMPONENTS = @import("std").zig.c_translation.promoteIntLiteral(c_int, 0x8A33, .hexadecimal); pub const GL_UNIFORM_BUFFER_OFFSET_ALIGNMENT = @import("std").zig.c_translation.promoteIntLiteral(c_int, 0x8A34, .hexadecimal); pub const GL_ACTIVE_UNIFORM_BLOCK_MAX_NAME_LENGTH = @import("std").zig.c_translation.promoteIntLiteral(c_int, 0x8A35, .hexadecimal); pub const GL_ACTIVE_UNIFORM_BLOCKS = @import("std").zig.c_translation.promoteIntLiteral(c_int, 0x8A36, .hexadecimal); pub const GL_UNIFORM_TYPE = @import("std").zig.c_translation.promoteIntLiteral(c_int, 0x8A37, .hexadecimal); pub const GL_UNIFORM_SIZE = @import("std").zig.c_translation.promoteIntLiteral(c_int, 0x8A38, .hexadecimal); pub const GL_UNIFORM_NAME_LENGTH = @import("std").zig.c_translation.promoteIntLiteral(c_int, 0x8A39, .hexadecimal); pub const GL_UNIFORM_BLOCK_INDEX = @import("std").zig.c_translation.promoteIntLiteral(c_int, 0x8A3A, .hexadecimal); pub const GL_UNIFORM_OFFSET = @import("std").zig.c_translation.promoteIntLiteral(c_int, 0x8A3B, .hexadecimal); pub const GL_UNIFORM_ARRAY_STRIDE = @import("std").zig.c_translation.promoteIntLiteral(c_int, 0x8A3C, .hexadecimal); pub const GL_UNIFORM_MATRIX_STRIDE = @import("std").zig.c_translation.promoteIntLiteral(c_int, 0x8A3D, .hexadecimal); pub const GL_UNIFORM_IS_ROW_MAJOR = @import("std").zig.c_translation.promoteIntLiteral(c_int, 0x8A3E, .hexadecimal); pub const GL_UNIFORM_BLOCK_BINDING = @import("std").zig.c_translation.promoteIntLiteral(c_int, 0x8A3F, .hexadecimal); pub const GL_UNIFORM_BLOCK_DATA_SIZE = @import("std").zig.c_translation.promoteIntLiteral(c_int, 0x8A40, .hexadecimal); pub const GL_UNIFORM_BLOCK_NAME_LENGTH = @import("std").zig.c_translation.promoteIntLiteral(c_int, 0x8A41, .hexadecimal); pub const GL_UNIFORM_BLOCK_ACTIVE_UNIFORMS = @import("std").zig.c_translation.promoteIntLiteral(c_int, 0x8A42, .hexadecimal); pub const GL_UNIFORM_BLOCK_ACTIVE_UNIFORM_INDICES = @import("std").zig.c_translation.promoteIntLiteral(c_int, 0x8A43, .hexadecimal); pub const GL_UNIFORM_BLOCK_REFERENCED_BY_VERTEX_SHADER = @import("std").zig.c_translation.promoteIntLiteral(c_int, 0x8A44, .hexadecimal); pub const GL_UNIFORM_BLOCK_REFERENCED_BY_GEOMETRY_SHADER = @import("std").zig.c_translation.promoteIntLiteral(c_int, 0x8A45, .hexadecimal); pub const GL_UNIFORM_BLOCK_REFERENCED_BY_FRAGMENT_SHADER = @import("std").zig.c_translation.promoteIntLiteral(c_int, 0x8A46, .hexadecimal); pub const GL_INVALID_INDEX = @import("std").zig.c_translation.promoteIntLiteral(c_int, 0xFFFFFFFF, .hexadecimal); pub const GL_CONTEXT_CORE_PROFILE_BIT = @as(c_int, 0x00000001); pub const GL_CONTEXT_COMPATIBILITY_PROFILE_BIT = @as(c_int, 0x00000002); pub const GL_LINES_ADJACENCY = @as(c_int, 0x000A); pub const GL_LINE_STRIP_ADJACENCY = @as(c_int, 0x000B); pub const GL_TRIANGLES_ADJACENCY = @as(c_int, 0x000C); pub const GL_TRIANGLE_STRIP_ADJACENCY = @as(c_int, 0x000D); pub const GL_PROGRAM_POINT_SIZE = @import("std").zig.c_translation.promoteIntLiteral(c_int, 0x8642, .hexadecimal); pub const GL_MAX_GEOMETRY_TEXTURE_IMAGE_UNITS = @import("std").zig.c_translation.promoteIntLiteral(c_int, 0x8C29, .hexadecimal); pub const GL_FRAMEBUFFER_ATTACHMENT_LAYERED = @import("std").zig.c_translation.promoteIntLiteral(c_int, 0x8DA7, .hexadecimal); pub const GL_FRAMEBUFFER_INCOMPLETE_LAYER_TARGETS = @import("std").zig.c_translation.promoteIntLiteral(c_int, 0x8DA8, .hexadecimal); pub const GL_GEOMETRY_SHADER = @import("std").zig.c_translation.promoteIntLiteral(c_int, 0x8DD9, .hexadecimal); pub const GL_GEOMETRY_VERTICES_OUT = @import("std").zig.c_translation.promoteIntLiteral(c_int, 0x8916, .hexadecimal); pub const GL_GEOMETRY_INPUT_TYPE = @import("std").zig.c_translation.promoteIntLiteral(c_int, 0x8917, .hexadecimal); pub const GL_GEOMETRY_OUTPUT_TYPE = @import("std").zig.c_translation.promoteIntLiteral(c_int, 0x8918, .hexadecimal); pub const GL_MAX_GEOMETRY_UNIFORM_COMPONENTS = @import("std").zig.c_translation.promoteIntLiteral(c_int, 0x8DDF, .hexadecimal); pub const GL_MAX_GEOMETRY_OUTPUT_VERTICES = @import("std").zig.c_translation.promoteIntLiteral(c_int, 0x8DE0, .hexadecimal); pub const GL_MAX_GEOMETRY_TOTAL_OUTPUT_COMPONENTS = @import("std").zig.c_translation.promoteIntLiteral(c_int, 0x8DE1, .hexadecimal); pub const GL_MAX_VERTEX_OUTPUT_COMPONENTS = @import("std").zig.c_translation.promoteIntLiteral(c_int, 0x9122, .hexadecimal); pub const GL_MAX_GEOMETRY_INPUT_COMPONENTS = @import("std").zig.c_translation.promoteIntLiteral(c_int, 0x9123, .hexadecimal); pub const GL_MAX_GEOMETRY_OUTPUT_COMPONENTS = @import("std").zig.c_translation.promoteIntLiteral(c_int, 0x9124, .hexadecimal); pub const GL_MAX_FRAGMENT_INPUT_COMPONENTS = @import("std").zig.c_translation.promoteIntLiteral(c_int, 0x9125, .hexadecimal); pub const GL_CONTEXT_PROFILE_MASK = @import("std").zig.c_translation.promoteIntLiteral(c_int, 0x9126, .hexadecimal); pub const GL_DEPTH_CLAMP = @import("std").zig.c_translation.promoteIntLiteral(c_int, 0x864F, .hexadecimal); pub const GL_QUADS_FOLLOW_PROVOKING_VERTEX_CONVENTION = @import("std").zig.c_translation.promoteIntLiteral(c_int, 0x8E4C, .hexadecimal); pub const GL_FIRST_VERTEX_CONVENTION = @import("std").zig.c_translation.promoteIntLiteral(c_int, 0x8E4D, .hexadecimal); pub const GL_LAST_VERTEX_CONVENTION = @import("std").zig.c_translation.promoteIntLiteral(c_int, 0x8E4E, .hexadecimal); pub const GL_PROVOKING_VERTEX = @import("std").zig.c_translation.promoteIntLiteral(c_int, 0x8E4F, .hexadecimal); pub const GL_TEXTURE_CUBE_MAP_SEAMLESS = @import("std").zig.c_translation.promoteIntLiteral(c_int, 0x884F, .hexadecimal); pub const GL_MAX_SERVER_WAIT_TIMEOUT = @import("std").zig.c_translation.promoteIntLiteral(c_int, 0x9111, .hexadecimal); pub const GL_OBJECT_TYPE = @import("std").zig.c_translation.promoteIntLiteral(c_int, 0x9112, .hexadecimal); pub const GL_SYNC_CONDITION = @import("std").zig.c_translation.promoteIntLiteral(c_int, 0x9113, .hexadecimal); pub const GL_SYNC_STATUS = @import("std").zig.c_translation.promoteIntLiteral(c_int, 0x9114, .hexadecimal); pub const GL_SYNC_FLAGS = @import("std").zig.c_translation.promoteIntLiteral(c_int, 0x9115, .hexadecimal); pub const GL_SYNC_FENCE = @import("std").zig.c_translation.promoteIntLiteral(c_int, 0x9116, .hexadecimal); pub const GL_SYNC_GPU_COMMANDS_COMPLETE = @import("std").zig.c_translation.promoteIntLiteral(c_int, 0x9117, .hexadecimal); pub const GL_UNSIGNALED = @import("std").zig.c_translation.promoteIntLiteral(c_int, 0x9118, .hexadecimal); pub const GL_SIGNALED = @import("std").zig.c_translation.promoteIntLiteral(c_int, 0x9119, .hexadecimal); pub const GL_ALREADY_SIGNALED = @import("std").zig.c_translation.promoteIntLiteral(c_int, 0x911A, .hexadecimal); pub const GL_TIMEOUT_EXPIRED = @import("std").zig.c_translation.promoteIntLiteral(c_int, 0x911B, .hexadecimal); pub const GL_CONDITION_SATISFIED = @import("std").zig.c_translation.promoteIntLiteral(c_int, 0x911C, .hexadecimal); pub const GL_WAIT_FAILED = @import("std").zig.c_translation.promoteIntLiteral(c_int, 0x911D, .hexadecimal); pub const GL_TIMEOUT_IGNORED = @import("std").zig.c_translation.promoteIntLiteral(c_int, 0xFFFFFFFFFFFFFFFF, .hexadecimal); pub const GL_SYNC_FLUSH_COMMANDS_BIT = @as(c_int, 0x00000001); pub const GL_SAMPLE_POSITION = @import("std").zig.c_translation.promoteIntLiteral(c_int, 0x8E50, .hexadecimal); pub const GL_SAMPLE_MASK = @import("std").zig.c_translation.promoteIntLiteral(c_int, 0x8E51, .hexadecimal); pub const GL_SAMPLE_MASK_VALUE = @import("std").zig.c_translation.promoteIntLiteral(c_int, 0x8E52, .hexadecimal); pub const GL_MAX_SAMPLE_MASK_WORDS = @import("std").zig.c_translation.promoteIntLiteral(c_int, 0x8E59, .hexadecimal); pub const GL_TEXTURE_2D_MULTISAMPLE = @import("std").zig.c_translation.promoteIntLiteral(c_int, 0x9100, .hexadecimal); pub const GL_PROXY_TEXTURE_2D_MULTISAMPLE = @import("std").zig.c_translation.promoteIntLiteral(c_int, 0x9101, .hexadecimal); pub const GL_TEXTURE_2D_MULTISAMPLE_ARRAY = @import("std").zig.c_translation.promoteIntLiteral(c_int, 0x9102, .hexadecimal); pub const GL_PROXY_TEXTURE_2D_MULTISAMPLE_ARRAY = @import("std").zig.c_translation.promoteIntLiteral(c_int, 0x9103, .hexadecimal); pub const GL_TEXTURE_BINDING_2D_MULTISAMPLE = @import("std").zig.c_translation.promoteIntLiteral(c_int, 0x9104, .hexadecimal); pub const GL_TEXTURE_BINDING_2D_MULTISAMPLE_ARRAY = @import("std").zig.c_translation.promoteIntLiteral(c_int, 0x9105, .hexadecimal); pub const GL_TEXTURE_SAMPLES = @import("std").zig.c_translation.promoteIntLiteral(c_int, 0x9106, .hexadecimal); pub const GL_TEXTURE_FIXED_SAMPLE_LOCATIONS = @import("std").zig.c_translation.promoteIntLiteral(c_int, 0x9107, .hexadecimal); pub const GL_SAMPLER_2D_MULTISAMPLE = @import("std").zig.c_translation.promoteIntLiteral(c_int, 0x9108, .hexadecimal); pub const GL_INT_SAMPLER_2D_MULTISAMPLE = @import("std").zig.c_translation.promoteIntLiteral(c_int, 0x9109, .hexadecimal); pub const GL_UNSIGNED_INT_SAMPLER_2D_MULTISAMPLE = @import("std").zig.c_translation.promoteIntLiteral(c_int, 0x910A, .hexadecimal); pub const GL_SAMPLER_2D_MULTISAMPLE_ARRAY = @import("std").zig.c_translation.promoteIntLiteral(c_int, 0x910B, .hexadecimal); pub const GL_INT_SAMPLER_2D_MULTISAMPLE_ARRAY = @import("std").zig.c_translation.promoteIntLiteral(c_int, 0x910C, .hexadecimal); pub const GL_UNSIGNED_INT_SAMPLER_2D_MULTISAMPLE_ARRAY = @import("std").zig.c_translation.promoteIntLiteral(c_int, 0x910D, .hexadecimal); pub const GL_MAX_COLOR_TEXTURE_SAMPLES = @import("std").zig.c_translation.promoteIntLiteral(c_int, 0x910E, .hexadecimal); pub const GL_MAX_DEPTH_TEXTURE_SAMPLES = @import("std").zig.c_translation.promoteIntLiteral(c_int, 0x910F, .hexadecimal); pub const GL_MAX_INTEGER_SAMPLES = @import("std").zig.c_translation.promoteIntLiteral(c_int, 0x9110, .hexadecimal); pub const GL_VERTEX_ATTRIB_ARRAY_DIVISOR = @import("std").zig.c_translation.promoteIntLiteral(c_int, 0x88FE, .hexadecimal); pub const GL_SRC1_COLOR = @import("std").zig.c_translation.promoteIntLiteral(c_int, 0x88F9, .hexadecimal); pub const GL_ONE_MINUS_SRC1_COLOR = @import("std").zig.c_translation.promoteIntLiteral(c_int, 0x88FA, .hexadecimal); pub const GL_ONE_MINUS_SRC1_ALPHA = @import("std").zig.c_translation.promoteIntLiteral(c_int, 0x88FB, .hexadecimal); pub const GL_MAX_DUAL_SOURCE_DRAW_BUFFERS = @import("std").zig.c_translation.promoteIntLiteral(c_int, 0x88FC, .hexadecimal); pub const GL_ANY_SAMPLES_PASSED = @import("std").zig.c_translation.promoteIntLiteral(c_int, 0x8C2F, .hexadecimal); pub const GL_SAMPLER_BINDING = @import("std").zig.c_translation.promoteIntLiteral(c_int, 0x8919, .hexadecimal); pub const GL_RGB10_A2UI = @import("std").zig.c_translation.promoteIntLiteral(c_int, 0x906F, .hexadecimal); pub const GL_TEXTURE_SWIZZLE_R = @import("std").zig.c_translation.promoteIntLiteral(c_int, 0x8E42, .hexadecimal); pub const GL_TEXTURE_SWIZZLE_G = @import("std").zig.c_translation.promoteIntLiteral(c_int, 0x8E43, .hexadecimal); pub const GL_TEXTURE_SWIZZLE_B = @import("std").zig.c_translation.promoteIntLiteral(c_int, 0x8E44, .hexadecimal); pub const GL_TEXTURE_SWIZZLE_A = @import("std").zig.c_translation.promoteIntLiteral(c_int, 0x8E45, .hexadecimal); pub const GL_TEXTURE_SWIZZLE_RGBA = @import("std").zig.c_translation.promoteIntLiteral(c_int, 0x8E46, .hexadecimal); pub const GL_TIME_ELAPSED = @import("std").zig.c_translation.promoteIntLiteral(c_int, 0x88BF, .hexadecimal); pub const GL_TIMESTAMP = @import("std").zig.c_translation.promoteIntLiteral(c_int, 0x8E28, .hexadecimal); pub const GL_INT_2_10_10_10_REV = @import("std").zig.c_translation.promoteIntLiteral(c_int, 0x8D9F, .hexadecimal); pub const GL_VERSION_1_0 = @as(c_int, 1); pub inline fn cullFace(arg_2: GLenum) void { return glad_glCullFace.?(arg_2); } pub inline fn frontFace(arg_3: GLenum) void { return glad_glFrontFace.?(arg_3); } pub inline fn hint(arg_4: GLenum, arg_5: GLenum) void { return glad_glHint.?(arg_4, arg_5); } pub inline fn lineWidth(arg_6: GLfloat) void { return glad_glLineWidth.?(arg_6); } pub inline fn pointSize(arg_7: GLfloat) void { return glad_glPointSize.?(arg_7); } pub inline fn polygonMode(arg_8: GLenum, arg_9: GLenum) void { return glad_glPolygonMode.?(arg_8, arg_9); } pub inline fn scissor(arg_10: GLint, arg_11: GLint, arg_12: GLsizei, arg_13: GLsizei) void { return glad_glScissor.?(arg_10, arg_11, arg_12, arg_13); } pub inline fn texParameterf(arg_14: GLenum, arg_15: GLenum, arg_16: GLfloat) void { return glad_glTexParameterf.?(arg_14, arg_15, arg_16); } pub inline fn texParameterfv(arg_17: GLenum, arg_18: GLenum, arg_19: [*c]const GLfloat) void { return glad_glTexParameterfv.?(arg_17, arg_18, arg_19); } pub inline fn texParameteri(arg_20: GLenum, arg_21: GLenum, arg_22: GLint) void { return glad_glTexParameteri.?(arg_20, arg_21, arg_22); } pub inline fn texParameteriv(arg_23: GLenum, arg_24: GLenum, arg_25: [*c]const GLint) void { return glad_glTexParameteriv.?(arg_23, arg_24, arg_25); } pub inline fn texImage1D(arg_26: GLenum, arg_27: GLint, arg_28: GLint, arg_29: GLsizei, arg_30: GLint, arg_31: GLenum, arg_32: GLenum, arg_33: ?*const anyopaque) void { return glad_glTexImage1D.?(arg_26, arg_27, arg_28, arg_29, arg_30, arg_31, arg_32, arg_33); } pub inline fn texImage2D(arg_34: GLenum, arg_35: GLint, arg_36: GLint, arg_37: GLsizei, arg_38: GLsizei, arg_39: GLint, arg_40: GLenum, arg_41: GLenum, arg_42: ?*const anyopaque) void { return glad_glTexImage2D.?(arg_34, arg_35, arg_36, arg_37, arg_38, arg_39, arg_40, arg_41, arg_42); } pub inline fn drawBuffer(arg_43: GLenum) void { return glad_glDrawBuffer.?(arg_43); } pub inline fn clear(arg_44: GLbitfield) void { return glad_glClear.?(arg_44); } pub inline fn clearColor(arg_45: GLfloat, arg_46: GLfloat, arg_47: GLfloat, arg_48: GLfloat) void { return glad_glClearColor.?(arg_45, arg_46, arg_47, arg_48); } pub inline fn clearStencil(arg_49: GLint) void { return glad_glClearStencil.?(arg_49); } pub inline fn clearDepth(arg_50: GLdouble) void { return glad_glClearDepth.?(arg_50); } pub inline fn stencilMask(arg_51: GLuint) void { return glad_glStencilMask.?(arg_51); } pub inline fn colorMask(arg_52: GLboolean, arg_53: GLboolean, arg_54: GLboolean, arg_55: GLboolean) void { return glad_glColorMask.?(arg_52, arg_53, arg_54, arg_55); } pub inline fn depthMask(arg_56: GLboolean) void { return glad_glDepthMask.?(arg_56); } pub inline fn disable(arg_57: GLenum) void { return glad_glDisable.?(arg_57); } pub inline fn enable(arg_58: GLenum) void { return glad_glEnable.?(arg_58); } pub inline fn finish() void { return glad_glFinish.?(); } pub inline fn flush() void { return glad_glFlush.?(); } pub inline fn blendFunc(arg_59: GLenum, arg_60: GLenum) void { return glad_glBlendFunc.?(arg_59, arg_60); } pub inline fn logicOp(arg_61: GLenum) void { return glad_glLogicOp.?(arg_61); } pub inline fn stencilFunc(arg_62: GLenum, arg_63: GLint, arg_64: GLuint) void { return glad_glStencilFunc.?(arg_62, arg_63, arg_64); } pub inline fn stencilOp(arg_65: GLenum, arg_66: GLenum, arg_67: GLenum) void { return glad_glStencilOp.?(arg_65, arg_66, arg_67); } pub inline fn depthFunc(arg_68: GLenum) void { return glad_glDepthFunc.?(arg_68); } pub inline fn pixelStoref(arg_69: GLenum, arg_70: GLfloat) void { return glad_glPixelStoref.?(arg_69, arg_70); } pub inline fn pixelStorei(arg_71: GLenum, arg_72: GLint) void { return glad_glPixelStorei.?(arg_71, arg_72); } pub inline fn readBuffer(arg_73: GLenum) void { return glad_glReadBuffer.?(arg_73); } pub inline fn readPixels(arg_74: GLint, arg_75: GLint, arg_76: GLsizei, arg_77: GLsizei, arg_78: GLenum, arg_79: GLenum, arg_80: ?*anyopaque) void { return glad_glReadPixels.?(arg_74, arg_75, arg_76, arg_77, arg_78, arg_79, arg_80); } pub inline fn getBooleanv(arg_81: GLenum, arg_82: [*c]GLboolean) void { return glad_glGetBooleanv.?(arg_81, arg_82); } pub inline fn getDoublev(arg_83: GLenum, arg_84: [*c]GLdouble) void { return glad_glGetDoublev.?(arg_83, arg_84); } pub inline fn getError() GLenum { return glad_glGetError.?(); } pub inline fn getFloatv(arg_85: GLenum, arg_86: [*c]GLfloat) void { return glad_glGetFloatv.?(arg_85, arg_86); } pub inline fn getIntegerv(arg_87: GLenum, arg_88: [*c]GLint) void { return glad_glGetIntegerv.?(arg_87, arg_88); } pub inline fn getString(arg_89: GLenum) [*c]const GLubyte { return glad_glGetString.?(arg_89); } pub inline fn getTexImage(arg_90: GLenum, arg_91: GLint, arg_92: GLenum, arg_93: GLenum, arg_94: ?*anyopaque) void { return glad_glGetTexImage.?(arg_90, arg_91, arg_92, arg_93, arg_94); } pub inline fn getTexParameterfv(arg_95: GLenum, arg_96: GLenum, arg_97: [*c]GLfloat) void { return glad_glGetTexParameterfv.?(arg_95, arg_96, arg_97); } pub inline fn getTexParameteriv(arg_98: GLenum, arg_99: GLenum, arg_100: [*c]GLint) void { return glad_glGetTexParameteriv.?(arg_98, arg_99, arg_100); } pub inline fn getTexLevelParameterfv(arg_101: GLenum, arg_102: GLint, arg_103: GLenum, arg_104: [*c]GLfloat) void { return glad_glGetTexLevelParameterfv.?(arg_101, arg_102, arg_103, arg_104); } pub inline fn getTexLevelParameteriv(arg_105: GLenum, arg_106: GLint, arg_107: GLenum, arg_108: [*c]GLint) void { return glad_glGetTexLevelParameteriv.?(arg_105, arg_106, arg_107, arg_108); } pub inline fn isEnabled(arg_109: GLenum) GLboolean { return glad_glIsEnabled.?(arg_109); } pub inline fn depthRange(arg_110: GLdouble, arg_111: GLdouble) void { return glad_glDepthRange.?(arg_110, arg_111); } pub inline fn viewport(x: GLint, y: GLint, w: GLsizei, h: GLsizei) void { return glad_glViewport.?(x, y, w, h); } pub const GL_VERSION_1_1 = @as(c_int, 1); pub inline fn drawArrays(arg_116: GLenum, arg_117: GLint, arg_118: GLsizei) void { return glad_glDrawArrays.?(arg_116, arg_117, arg_118); } pub inline fn drawElements(arg_119: GLenum, arg_120: GLsizei, arg_121: GLenum, arg_122: ?*const anyopaque) void { return glad_glDrawElements.?(arg_119, arg_120, arg_121, arg_122); } pub inline fn polygonOffset(arg_123: GLfloat, arg_124: GLfloat) void { return glad_glPolygonOffset.?(arg_123, arg_124); } pub inline fn copyTexImage1D(arg_125: GLenum, arg_126: GLint, arg_127: GLenum, arg_128: GLint, arg_129: GLint, arg_130: GLsizei, arg_131: GLint) void { return glad_glCopyTexImage1D.?(arg_125, arg_126, arg_127, arg_128, arg_129, arg_130, arg_131); } pub inline fn copyTexImage2D(arg_132: GLenum, arg_133: GLint, arg_134: GLenum, arg_135: GLint, arg_136: GLint, arg_137: GLsizei, arg_138: GLsizei, arg_139: GLint) void { return glad_glCopyTexImage2D.?(arg_132, arg_133, arg_134, arg_135, arg_136, arg_137, arg_138, arg_139); } pub inline fn copyTexSubImage1D(arg_140: GLenum, arg_141: GLint, arg_142: GLint, arg_143: GLint, arg_144: GLint, arg_145: GLsizei) void { return glad_glCopyTexSubImage1D.?(arg_140, arg_141, arg_142, arg_143, arg_144, arg_145); } pub inline fn copyTexSubImage2D(arg_146: GLenum, arg_147: GLint, arg_148: GLint, arg_149: GLint, arg_150: GLint, arg_151: GLint, arg_152: GLsizei, arg_153: GLsizei) void { return glad_glCopyTexSubImage2D.?(arg_146, arg_147, arg_148, arg_149, arg_150, arg_151, arg_152, arg_153); } pub inline fn texSubImage1D(arg_154: GLenum, arg_155: GLint, arg_156: GLint, arg_157: GLsizei, arg_158: GLenum, arg_159: GLenum, arg_160: ?*const anyopaque) void { return glad_glTexSubImage1D.?(arg_154, arg_155, arg_156, arg_157, arg_158, arg_159, arg_160); } pub inline fn texSubImage2D(arg_161: GLenum, arg_162: GLint, arg_163: GLint, arg_164: GLint, arg_165: GLsizei, arg_166: GLsizei, arg_167: GLenum, arg_168: GLenum, arg_169: ?*const anyopaque) void { return glad_glTexSubImage2D.?(arg_161, arg_162, arg_163, arg_164, arg_165, arg_166, arg_167, arg_168, arg_169); } pub inline fn bindTexture(arg_170: GLenum, arg_171: GLuint) void { return glad_glBindTexture.?(arg_170, arg_171); } pub inline fn deleteTextures(arg_172: GLsizei, arg_173: [*c]const GLuint) void { return glad_glDeleteTextures.?(arg_172, arg_173); } pub inline fn genTextures(arg_174: GLsizei, arg_175: [*c]GLuint) void { return glad_glGenTextures.?(arg_174, arg_175); } pub inline fn isTexture(arg_176: GLuint) GLboolean { return glad_glIsTexture.?(arg_176); } pub const GL_VERSION_1_2 = @as(c_int, 1); pub inline fn drawRangeElements(arg_177: GLenum, arg_178: GLuint, arg_179: GLuint, arg_180: GLsizei, arg_181: GLenum, arg_182: ?*const anyopaque) void { return glad_glDrawRangeElements.?(arg_177, arg_178, arg_179, arg_180, arg_181, arg_182); } pub inline fn texImage3D(arg_183: GLenum, arg_184: GLint, arg_185: GLint, arg_186: GLsizei, arg_187: GLsizei, arg_188: GLsizei, arg_189: GLint, arg_190: GLenum, arg_191: GLenum, arg_192: ?*const anyopaque) void { return glad_glTexImage3D.?(arg_183, arg_184, arg_185, arg_186, arg_187, arg_188, arg_189, arg_190, arg_191, arg_192); } pub inline fn texSubImage3D(arg_193: GLenum, arg_194: GLint, arg_195: GLint, arg_196: GLint, arg_197: GLint, arg_198: GLsizei, arg_199: GLsizei, arg_200: GLsizei, arg_201: GLenum, arg_202: GLenum, arg_203: ?*const anyopaque) void { return glad_glTexSubImage3D.?(arg_193, arg_194, arg_195, arg_196, arg_197, arg_198, arg_199, arg_200, arg_201, arg_202, arg_203); } pub inline fn copyTexSubImage3D(arg_204: GLenum, arg_205: GLint, arg_206: GLint, arg_207: GLint, arg_208: GLint, arg_209: GLint, arg_210: GLint, arg_211: GLsizei, arg_212: GLsizei) void { return glad_glCopyTexSubImage3D.?(arg_204, arg_205, arg_206, arg_207, arg_208, arg_209, arg_210, arg_211, arg_212); } pub const GL_VERSION_1_3 = @as(c_int, 1); pub inline fn activeTexture(arg_213: GLenum) void { return glad_glActiveTexture.?(arg_213); } pub inline fn sampleCoverage(arg_214: GLfloat, arg_215: GLboolean) void { return glad_glSampleCoverage.?(arg_214, arg_215); } pub inline fn compressedTexImage3D(arg_216: GLenum, arg_217: GLint, arg_218: GLenum, arg_219: GLsizei, arg_220: GLsizei, arg_221: GLsizei, arg_222: GLint, arg_223: GLsizei, arg_224: ?*const anyopaque) void { return glad_glCompressedTexImage3D.?(arg_216, arg_217, arg_218, arg_219, arg_220, arg_221, arg_222, arg_223, arg_224); } pub inline fn compressedTexImage2D(arg_225: GLenum, arg_226: GLint, arg_227: GLenum, arg_228: GLsizei, arg_229: GLsizei, arg_230: GLint, arg_231: GLsizei, arg_232: ?*const anyopaque) void { return glad_glCompressedTexImage2D.?(arg_225, arg_226, arg_227, arg_228, arg_229, arg_230, arg_231, arg_232); } pub inline fn compressedTexImage1D(arg_233: GLenum, arg_234: GLint, arg_235: GLenum, arg_236: GLsizei, arg_237: GLint, arg_238: GLsizei, arg_239: ?*const anyopaque) void { return glad_glCompressedTexImage1D.?(arg_233, arg_234, arg_235, arg_236, arg_237, arg_238, arg_239); } pub inline fn compressedTexSubImage3D(arg_240: GLenum, arg_241: GLint, arg_242: GLint, arg_243: GLint, arg_244: GLint, arg_245: GLsizei, arg_246: GLsizei, arg_247: GLsizei, arg_248: GLenum, arg_249: GLsizei, arg_250: ?*const anyopaque) void { return glad_glCompressedTexSubImage3D.?(arg_240, arg_241, arg_242, arg_243, arg_244, arg_245, arg_246, arg_247, arg_248, arg_249, arg_250); } pub inline fn compressedTexSubImage2D(arg_251: GLenum, arg_252: GLint, arg_253: GLint, arg_254: GLint, arg_255: GLsizei, arg_256: GLsizei, arg_257: GLenum, arg_258: GLsizei, arg_259: ?*const anyopaque) void { return glad_glCompressedTexSubImage2D.?(arg_251, arg_252, arg_253, arg_254, arg_255, arg_256, arg_257, arg_258, arg_259); } pub inline fn compressedTexSubImage1D(arg_260: GLenum, arg_261: GLint, arg_262: GLint, arg_263: GLsizei, arg_264: GLenum, arg_265: GLsizei, arg_266: ?*const anyopaque) void { return glad_glCompressedTexSubImage1D.?(arg_260, arg_261, arg_262, arg_263, arg_264, arg_265, arg_266); } pub inline fn getCompressedTexImage(arg_267: GLenum, arg_268: GLint, arg_269: ?*anyopaque) void { return glad_glGetCompressedTexImage.?(arg_267, arg_268, arg_269); } pub const GL_VERSION_1_4 = @as(c_int, 1); pub inline fn blendFuncSeparate(arg_270: GLenum, arg_271: GLenum, arg_272: GLenum, arg_273: GLenum) void { return glad_glBlendFuncSeparate.?(arg_270, arg_271, arg_272, arg_273); } pub inline fn multiDrawArrays(arg_274: GLenum, arg_275: [*c]const GLint, arg_276: [*c]const GLsizei, arg_277: GLsizei) void { return glad_glMultiDrawArrays.?(arg_274, arg_275, arg_276, arg_277); } pub inline fn multiDrawElements(arg_278: GLenum, arg_279: [*c]const GLsizei, arg_280: GLenum, arg_281: [*c]const ?*const anyopaque, arg_282: GLsizei) void { return glad_glMultiDrawElements.?(arg_278, arg_279, arg_280, arg_281, arg_282); } pub inline fn pointParameterf(arg_283: GLenum, arg_284: GLfloat) void { return glad_glPointParameterf.?(arg_283, arg_284); } pub inline fn pointParameterfv(arg_285: GLenum, arg_286: [*c]const GLfloat) void { return glad_glPointParameterfv.?(arg_285, arg_286); } pub inline fn pointParameteri(arg_287: GLenum, arg_288: GLint) void { return glad_glPointParameteri.?(arg_287, arg_288); } pub inline fn pointParameteriv(arg_289: GLenum, arg_290: [*c]const GLint) void { return glad_glPointParameteriv.?(arg_289, arg_290); } pub inline fn blendColor(arg_291: GLfloat, arg_292: GLfloat, arg_293: GLfloat, arg_294: GLfloat) void { return glad_glBlendColor.?(arg_291, arg_292, arg_293, arg_294); } pub inline fn blendEquation(arg_295: GLenum) void { return glad_glBlendEquation.?(arg_295); } pub const GL_VERSION_1_5 = @as(c_int, 1); pub inline fn genQueries(arg_296: GLsizei, arg_297: [*c]GLuint) void { return glad_glGenQueries.?(arg_296, arg_297); } pub inline fn deleteQueries(arg_298: GLsizei, arg_299: [*c]const GLuint) void { return glad_glDeleteQueries.?(arg_298, arg_299); } pub inline fn isQuery(arg_300: GLuint) GLboolean { return glad_glIsQuery.?(arg_300); } pub inline fn beginQuery(arg_301: GLenum, arg_302: GLuint) void { return glad_glBeginQuery.?(arg_301, arg_302); } pub inline fn endQuery(arg_303: GLenum) void { return glad_glEndQuery.?(arg_303); } pub inline fn getQueryiv(arg_304: GLenum, arg_305: GLenum, arg_306: [*c]GLint) void { return glad_glGetQueryiv.?(arg_304, arg_305, arg_306); } pub inline fn getQueryObjectiv(arg_307: GLuint, arg_308: GLenum, arg_309: [*c]GLint) void { return glad_glGetQueryObjectiv.?(arg_307, arg_308, arg_309); } pub inline fn getQueryObjectuiv(arg_310: GLuint, arg_311: GLenum, arg_312: [*c]GLuint) void { return glad_glGetQueryObjectuiv.?(arg_310, arg_311, arg_312); } pub inline fn bindBuffer(arg_313: GLenum, arg_314: GLuint) void { return glad_glBindBuffer.?(arg_313, arg_314); } pub inline fn deleteBuffers(arg_315: GLsizei, arg_316: [*c]const GLuint) void { return glad_glDeleteBuffers.?(arg_315, arg_316); } pub inline fn genBuffers(arg_317: GLsizei, arg_318: [*c]GLuint) void { return glad_glGenBuffers.?(arg_317, arg_318); } pub inline fn isBuffer(arg_319: GLuint) GLboolean { return glad_glIsBuffer.?(arg_319); } pub inline fn bufferData(arg_320: GLenum, arg_321: GLsizeiptr, arg_322: ?*const anyopaque, arg_323: GLenum) void { return glad_glBufferData.?(arg_320, arg_321, arg_322, arg_323); } pub inline fn bufferSubData(arg_324: GLenum, arg_325: GLintptr, arg_326: GLsizeiptr, arg_327: ?*const anyopaque) void { return glad_glBufferSubData.?(arg_324, arg_325, arg_326, arg_327); } pub inline fn getBufferSubData(arg_328: GLenum, arg_329: GLintptr, arg_330: GLsizeiptr, arg_331: ?*anyopaque) void { return glad_glGetBufferSubData.?(arg_328, arg_329, arg_330, arg_331); } pub inline fn mapBuffer(arg_332: GLenum, arg_333: GLenum) ?*anyopaque { return glad_glMapBuffer.?(arg_332, arg_333); } pub inline fn unmapBuffer(arg_334: GLenum) GLboolean { return glad_glUnmapBuffer.?(arg_334); } pub inline fn getBufferParameteriv(arg_335: GLenum, arg_336: GLenum, arg_337: [*c]GLint) void { return glad_glGetBufferParameteriv.?(arg_335, arg_336, arg_337); } pub inline fn getBufferPointerv(arg_338: GLenum, arg_339: GLenum, arg_340: [*c]?*anyopaque) void { return glad_glGetBufferPointerv.?(arg_338, arg_339, arg_340); } pub const GL_VERSION_2_0 = @as(c_int, 1); pub inline fn blendEquationSeparate(arg_341: GLenum, arg_342: GLenum) void { return glad_glBlendEquationSeparate.?(arg_341, arg_342); } pub inline fn drawBuffers(arg_343: GLsizei, arg_344: [*c]const GLenum) void { return glad_glDrawBuffers.?(arg_343, arg_344); } pub inline fn stencilOpSeparate(arg_345: GLenum, arg_346: GLenum, arg_347: GLenum, arg_348: GLenum) void { return glad_glStencilOpSeparate.?(arg_345, arg_346, arg_347, arg_348); } pub inline fn stencilFuncSeparate(arg_349: GLenum, arg_350: GLenum, arg_351: GLint, arg_352: GLuint) void { return glad_glStencilFuncSeparate.?(arg_349, arg_350, arg_351, arg_352); } pub inline fn stencilMaskSeparate(arg_353: GLenum, arg_354: GLuint) void { return glad_glStencilMaskSeparate.?(arg_353, arg_354); } pub inline fn attachShader(arg_355: GLuint, arg_356: GLuint) void { return glad_glAttachShader.?(arg_355, arg_356); } pub inline fn bindAttribLocation(arg_357: GLuint, arg_358: GLuint, arg_359: [*c]const GLchar) void { return glad_glBindAttribLocation.?(arg_357, arg_358, arg_359); } pub inline fn compileShader(arg_360: GLuint) void { return glad_glCompileShader.?(arg_360); } pub inline fn createProgram() GLuint { return glad_glCreateProgram.?(); } pub inline fn createShader(arg_361: GLenum) GLuint { return glad_glCreateShader.?(arg_361); } pub inline fn deleteProgram(arg_362: GLuint) void { return glad_glDeleteProgram.?(arg_362); } pub inline fn deleteShader(arg_363: GLuint) void { return glad_glDeleteShader.?(arg_363); } pub inline fn detachShader(arg_364: GLuint, arg_365: GLuint) void { return glad_glDetachShader.?(arg_364, arg_365); } pub inline fn disableVertexAttribArray(arg_366: GLuint) void { return glad_glDisableVertexAttribArray.?(arg_366); } pub inline fn enableVertexAttribArray(arg_367: GLuint) void { return glad_glEnableVertexAttribArray.?(arg_367); } pub inline fn getActiveAttrib(arg_368: GLuint, arg_369: GLuint, arg_370: GLsizei, arg_371: [*c]GLsizei, arg_372: [*c]GLint, arg_373: [*c]GLenum, arg_374: [*c]GLchar) void { return glad_glGetActiveAttrib.?(arg_368, arg_369, arg_370, arg_371, arg_372, arg_373, arg_374); } pub inline fn getActiveUniform(arg_375: GLuint, arg_376: GLuint, arg_377: GLsizei, arg_378: [*c]GLsizei, arg_379: [*c]GLint, arg_380: [*c]GLenum, arg_381: [*c]GLchar) void { return glad_glGetActiveUniform.?(arg_375, arg_376, arg_377, arg_378, arg_379, arg_380, arg_381); } pub inline fn getAttachedShaders(arg_382: GLuint, arg_383: GLsizei, arg_384: [*c]GLsizei, arg_385: [*c]GLuint) void { return glad_glGetAttachedShaders.?(arg_382, arg_383, arg_384, arg_385); } pub inline fn getAttribLocation(arg_386: GLuint, arg_387: [*c]const GLchar) GLint { return glad_glGetAttribLocation.?(arg_386, arg_387); } pub inline fn getProgramiv(arg_388: GLuint, arg_389: GLenum, arg_390: [*c]GLint) void { return glad_glGetProgramiv.?(arg_388, arg_389, arg_390); } pub inline fn getProgramInfoLog(arg_391: GLuint, arg_392: GLsizei, arg_393: [*c]GLsizei, arg_394: [*c]GLchar) void { return glad_glGetProgramInfoLog.?(arg_391, arg_392, arg_393, arg_394); } pub inline fn getShaderiv(arg_395: GLuint, arg_396: GLenum, arg_397: [*c]GLint) void { return glad_glGetShaderiv.?(arg_395, arg_396, arg_397); } pub inline fn getShaderInfoLog(arg_398: GLuint, arg_399: GLsizei, arg_400: [*c]GLsizei, arg_401: [*c]GLchar) void { return glad_glGetShaderInfoLog.?(arg_398, arg_399, arg_400, arg_401); } pub inline fn getShaderSource(arg_402: GLuint, arg_403: GLsizei, arg_404: [*c]GLsizei, arg_405: [*c]GLchar) void { return glad_glGetShaderSource.?(arg_402, arg_403, arg_404, arg_405); } pub inline fn getUniformLocation(arg_406: GLuint, arg_407: [*c]const GLchar) GLint { return glad_glGetUniformLocation.?(arg_406, arg_407); } pub inline fn getUniformfv(arg_408: GLuint, arg_409: GLint, arg_410: [*c]GLfloat) void { return glad_glGetUniformfv.?(arg_408, arg_409, arg_410); } pub inline fn getUniformiv(arg_411: GLuint, arg_412: GLint, arg_413: [*c]GLint) void { return glad_glGetUniformiv.?(arg_411, arg_412, arg_413); } pub inline fn getVertexAttribdv(arg_414: GLuint, arg_415: GLenum, arg_416: [*c]GLdouble) void { return glad_glGetVertexAttribdv.?(arg_414, arg_415, arg_416); } pub inline fn getVertexAttribfv(arg_417: GLuint, arg_418: GLenum, arg_419: [*c]GLfloat) void { return glad_glGetVertexAttribfv.?(arg_417, arg_418, arg_419); } pub inline fn getVertexAttribiv(arg_420: GLuint, arg_421: GLenum, arg_422: [*c]GLint) void { return glad_glGetVertexAttribiv.?(arg_420, arg_421, arg_422); } pub inline fn getVertexAttribPointerv(arg_423: GLuint, arg_424: GLenum, arg_425: [*c]?*anyopaque) void { return glad_glGetVertexAttribPointerv.?(arg_423, arg_424, arg_425); } pub inline fn isProgram(arg_426: GLuint) GLboolean { return glad_glIsProgram.?(arg_426); } pub inline fn isShader(arg_427: GLuint) GLboolean { return glad_glIsShader.?(arg_427); } pub inline fn linkProgram(arg_428: GLuint) void { return glad_glLinkProgram.?(arg_428); } pub inline fn shaderSource(arg_429: GLuint, arg_430: GLsizei, arg_431: [*c]const [*c]const GLchar, arg_432: [*c]const GLint) void { return glad_glShaderSource.?(arg_429, arg_430, arg_431, arg_432); } pub inline fn useProgram(arg_433: GLuint) void { return glad_glUseProgram.?(arg_433); } pub inline fn uniform1f(arg_434: GLint, arg_435: GLfloat) void { return glad_glUniform1f.?(arg_434, arg_435); } pub inline fn uniform2f(arg_436: GLint, arg_437: GLfloat, arg_438: GLfloat) void { return glad_glUniform2f.?(arg_436, arg_437, arg_438); } pub inline fn uniform3f(arg_439: GLint, arg_440: GLfloat, arg_441: GLfloat, arg_442: GLfloat) void { return glad_glUniform3f.?(arg_439, arg_440, arg_441, arg_442); } pub inline fn uniform4f(arg_443: GLint, arg_444: GLfloat, arg_445: GLfloat, arg_446: GLfloat, arg_447: GLfloat) void { return glad_glUniform4f.?(arg_443, arg_444, arg_445, arg_446, arg_447); } pub inline fn uniform1i(arg_448: GLint, arg_449: GLint) void { return glad_glUniform1i.?(arg_448, arg_449); } pub inline fn uniform2i(arg_450: GLint, arg_451: GLint, arg_452: GLint) void { return glad_glUniform2i.?(arg_450, arg_451, arg_452); } pub inline fn uniform3i(arg_453: GLint, arg_454: GLint, arg_455: GLint, arg_456: GLint) void { return glad_glUniform3i.?(arg_453, arg_454, arg_455, arg_456); } pub inline fn uniform4i(arg_457: GLint, arg_458: GLint, arg_459: GLint, arg_460: GLint, arg_461: GLint) void { return glad_glUniform4i.?(arg_457, arg_458, arg_459, arg_460, arg_461); } pub inline fn uniform1fv(arg_462: GLint, arg_463: GLsizei, arg_464: [*c]const GLfloat) void { return glad_glUniform1fv.?(arg_462, arg_463, arg_464); } pub inline fn uniform2fv(arg_465: GLint, arg_466: GLsizei, arg_467: [*c]const GLfloat) void { return glad_glUniform2fv.?(arg_465, arg_466, arg_467); } pub inline fn uniform3fv(arg_468: GLint, arg_469: GLsizei, arg_470: [*c]const GLfloat) void { return glad_glUniform3fv.?(arg_468, arg_469, arg_470); } pub inline fn uniform4fv(arg_471: GLint, arg_472: GLsizei, arg_473: [*c]const GLfloat) void { return glad_glUniform4fv.?(arg_471, arg_472, arg_473); } pub inline fn uniform1iv(arg_474: GLint, arg_475: GLsizei, arg_476: [*c]const GLint) void { return glad_glUniform1iv.?(arg_474, arg_475, arg_476); } pub inline fn uniform2iv(arg_477: GLint, arg_478: GLsizei, arg_479: [*c]const GLint) void { return glad_glUniform2iv.?(arg_477, arg_478, arg_479); } pub inline fn uniform3iv(arg_480: GLint, arg_481: GLsizei, arg_482: [*c]const GLint) void { return glad_glUniform3iv.?(arg_480, arg_481, arg_482); } pub inline fn uniform4iv(arg_483: GLint, arg_484: GLsizei, arg_485: [*c]const GLint) void { return glad_glUniform4iv.?(arg_483, arg_484, arg_485); } pub inline fn uniformMatrix2fv(arg_486: GLint, arg_487: GLsizei, arg_488: GLboolean, arg_489: [*c]const GLfloat) void { return glad_glUniformMatrix2fv.?(arg_486, arg_487, arg_488, arg_489); } pub inline fn uniformMatrix3fv(arg_490: GLint, arg_491: GLsizei, arg_492: GLboolean, arg_493: [*c]const GLfloat) void { return glad_glUniformMatrix3fv.?(arg_490, arg_491, arg_492, arg_493); } pub inline fn uniformMatrix4fv(arg_494: GLint, arg_495: GLsizei, arg_496: GLboolean, arg_497: [*c]const GLfloat) void { return glad_glUniformMatrix4fv.?(arg_494, arg_495, arg_496, arg_497); } pub inline fn validateProgram(arg_498: GLuint) void { return glad_glValidateProgram.?(arg_498); } pub inline fn vertexAttrib1d(arg_499: GLuint, arg_500: GLdouble) void { return glad_glVertexAttrib1d.?(arg_499, arg_500); } pub inline fn vertexAttrib1dv(arg_501: GLuint, arg_502: [*c]const GLdouble) void { return glad_glVertexAttrib1dv.?(arg_501, arg_502); } pub inline fn vertexAttrib1f(arg_503: GLuint, arg_504: GLfloat) void { return glad_glVertexAttrib1f.?(arg_503, arg_504); } pub inline fn vertexAttrib1fv(arg_505: GLuint, arg_506: [*c]const GLfloat) void { return glad_glVertexAttrib1fv.?(arg_505, arg_506); } pub inline fn vertexAttrib1s(arg_507: GLuint, arg_508: GLshort) void { return glad_glVertexAttrib1s.?(arg_507, arg_508); } pub inline fn vertexAttrib1sv(arg_509: GLuint, arg_510: [*c]const GLshort) void { return glad_glVertexAttrib1sv.?(arg_509, arg_510); } pub inline fn vertexAttrib2d(arg_511: GLuint, arg_512: GLdouble, arg_513: GLdouble) void { return glad_glVertexAttrib2d.?(arg_511, arg_512, arg_513); } pub inline fn vertexAttrib2dv(arg_514: GLuint, arg_515: [*c]const GLdouble) void { return glad_glVertexAttrib2dv.?(arg_514, arg_515); } pub inline fn vertexAttrib2f(arg_516: GLuint, arg_517: GLfloat, arg_518: GLfloat) void { return glad_glVertexAttrib2f.?(arg_516, arg_517, arg_518); } pub inline fn vertexAttrib2fv(arg_519: GLuint, arg_520: [*c]const GLfloat) void { return glad_glVertexAttrib2fv.?(arg_519, arg_520); } pub inline fn vertexAttrib2s(arg_521: GLuint, arg_522: GLshort, arg_523: GLshort) void { return glad_glVertexAttrib2s.?(arg_521, arg_522, arg_523); } pub inline fn vertexAttrib2sv(arg_524: GLuint, arg_525: [*c]const GLshort) void { return glad_glVertexAttrib2sv.?(arg_524, arg_525); } pub inline fn vertexAttrib3d(arg_526: GLuint, arg_527: GLdouble, arg_528: GLdouble, arg_529: GLdouble) void { return glad_glVertexAttrib3d.?(arg_526, arg_527, arg_528, arg_529); } pub inline fn vertexAttrib3dv(arg_530: GLuint, arg_531: [*c]const GLdouble) void { return glad_glVertexAttrib3dv.?(arg_530, arg_531); } pub inline fn vertexAttrib3f(arg_532: GLuint, arg_533: GLfloat, arg_534: GLfloat, arg_535: GLfloat) void { return glad_glVertexAttrib3f.?(arg_532, arg_533, arg_534, arg_535); } pub inline fn vertexAttrib3fv(arg_536: GLuint, arg_537: [*c]const GLfloat) void { return glad_glVertexAttrib3fv.?(arg_536, arg_537); } pub inline fn vertexAttrib3s(arg_538: GLuint, arg_539: GLshort, arg_540: GLshort, arg_541: GLshort) void { return glad_glVertexAttrib3s.?(arg_538, arg_539, arg_540, arg_541); } pub inline fn vertexAttrib3sv(arg_542: GLuint, arg_543: [*c]const GLshort) void { return glad_glVertexAttrib3sv.?(arg_542, arg_543); } pub inline fn vertexAttrib4Nbv(arg_544: GLuint, arg_545: [*c]const GLbyte) void { return glad_glVertexAttrib4Nbv.?(arg_544, arg_545); } pub inline fn vertexAttrib4Niv(arg_546: GLuint, arg_547: [*c]const GLint) void { return glad_glVertexAttrib4Niv.?(arg_546, arg_547); } pub inline fn vertexAttrib4Nsv(arg_548: GLuint, arg_549: [*c]const GLshort) void { return glad_glVertexAttrib4Nsv.?(arg_548, arg_549); } pub inline fn vertexAttrib4Nub(arg_550: GLuint, arg_551: GLubyte, arg_552: GLubyte, arg_553: GLubyte, arg_554: GLubyte) void { return glad_glVertexAttrib4Nub.?(arg_550, arg_551, arg_552, arg_553, arg_554); } pub inline fn vertexAttrib4Nubv(arg_555: GLuint, arg_556: [*c]const GLubyte) void { return glad_glVertexAttrib4Nubv.?(arg_555, arg_556); } pub inline fn vertexAttrib4Nuiv(arg_557: GLuint, arg_558: [*c]const GLuint) void { return glad_glVertexAttrib4Nuiv.?(arg_557, arg_558); } pub inline fn vertexAttrib4Nusv(arg_559: GLuint, arg_560: [*c]const GLushort) void { return glad_glVertexAttrib4Nusv.?(arg_559, arg_560); } pub inline fn vertexAttrib4bv(arg_561: GLuint, arg_562: [*c]const GLbyte) void { return glad_glVertexAttrib4bv.?(arg_561, arg_562); } pub inline fn vertexAttrib4d(arg_563: GLuint, arg_564: GLdouble, arg_565: GLdouble, arg_566: GLdouble, arg_567: GLdouble) void { return glad_glVertexAttrib4d.?(arg_563, arg_564, arg_565, arg_566, arg_567); } pub inline fn vertexAttrib4dv(arg_568: GLuint, arg_569: [*c]const GLdouble) void { return glad_glVertexAttrib4dv.?(arg_568, arg_569); } pub inline fn vertexAttrib4f(arg_570: GLuint, arg_571: GLfloat, arg_572: GLfloat, arg_573: GLfloat, arg_574: GLfloat) void { return glad_glVertexAttrib4f.?(arg_570, arg_571, arg_572, arg_573, arg_574); } pub inline fn vertexAttrib4fv(arg_575: GLuint, arg_576: [*c]const GLfloat) void { return glad_glVertexAttrib4fv.?(arg_575, arg_576); } pub inline fn vertexAttrib4iv(arg_577: GLuint, arg_578: [*c]const GLint) void { return glad_glVertexAttrib4iv.?(arg_577, arg_578); } pub inline fn vertexAttrib4s(arg_579: GLuint, arg_580: GLshort, arg_581: GLshort, arg_582: GLshort, arg_583: GLshort) void { return glad_glVertexAttrib4s.?(arg_579, arg_580, arg_581, arg_582, arg_583); } pub inline fn vertexAttrib4sv(arg_584: GLuint, arg_585: [*c]const GLshort) void { return glad_glVertexAttrib4sv.?(arg_584, arg_585); } pub inline fn vertexAttrib4ubv(arg_586: GLuint, arg_587: [*c]const GLubyte) void { return glad_glVertexAttrib4ubv.?(arg_586, arg_587); } pub inline fn vertexAttrib4uiv(arg_588: GLuint, arg_589: [*c]const GLuint) void { return glad_glVertexAttrib4uiv.?(arg_588, arg_589); } pub inline fn vertexAttrib4usv(arg_590: GLuint, arg_591: [*c]const GLushort) void { return glad_glVertexAttrib4usv.?(arg_590, arg_591); } pub inline fn vertexAttribPointer(arg_592: GLuint, arg_593: GLint, arg_594: GLenum, arg_595: GLboolean, arg_596: GLsizei, arg_597: ?*const anyopaque) void { return glad_glVertexAttribPointer.?(arg_592, arg_593, arg_594, arg_595, arg_596, arg_597); } pub const GL_VERSION_2_1 = @as(c_int, 1); pub inline fn uniformMatrix2x3fv(arg_598: GLint, arg_599: GLsizei, arg_600: GLboolean, arg_601: [*c]const GLfloat) void { return glad_glUniformMatrix2x3fv.?(arg_598, arg_599, arg_600, arg_601); } pub inline fn uniformMatrix3x2fv(arg_602: GLint, arg_603: GLsizei, arg_604: GLboolean, arg_605: [*c]const GLfloat) void { return glad_glUniformMatrix3x2fv.?(arg_602, arg_603, arg_604, arg_605); } pub inline fn uniformMatrix2x4fv(arg_606: GLint, arg_607: GLsizei, arg_608: GLboolean, arg_609: [*c]const GLfloat) void { return glad_glUniformMatrix2x4fv.?(arg_606, arg_607, arg_608, arg_609); } pub inline fn uniformMatrix4x2fv(arg_610: GLint, arg_611: GLsizei, arg_612: GLboolean, arg_613: [*c]const GLfloat) void { return glad_glUniformMatrix4x2fv.?(arg_610, arg_611, arg_612, arg_613); } pub inline fn uniformMatrix3x4fv(arg_614: GLint, arg_615: GLsizei, arg_616: GLboolean, arg_617: [*c]const GLfloat) void { return glad_glUniformMatrix3x4fv.?(arg_614, arg_615, arg_616, arg_617); } pub inline fn uniformMatrix4x3fv(arg_618: GLint, arg_619: GLsizei, arg_620: GLboolean, arg_621: [*c]const GLfloat) void { return glad_glUniformMatrix4x3fv.?(arg_618, arg_619, arg_620, arg_621); } pub const GL_VERSION_3_0 = @as(c_int, 1); pub inline fn colorMaski(arg_622: GLuint, arg_623: GLboolean, arg_624: GLboolean, arg_625: GLboolean, arg_626: GLboolean) void { return glad_glColorMaski.?(arg_622, arg_623, arg_624, arg_625, arg_626); } pub inline fn getBooleani_v(arg_627: GLenum, arg_628: GLuint, arg_629: [*c]GLboolean) void { return glad_glGetBooleani_v.?(arg_627, arg_628, arg_629); } pub inline fn getIntegeri_v(arg_630: GLenum, arg_631: GLuint, arg_632: [*c]GLint) void { return glad_glGetIntegeri_v.?(arg_630, arg_631, arg_632); } pub inline fn enablei(arg_633: GLenum, arg_634: GLuint) void { return glad_glEnablei.?(arg_633, arg_634); } pub inline fn disablei(arg_635: GLenum, arg_636: GLuint) void { return glad_glDisablei.?(arg_635, arg_636); } pub inline fn isEnabledi(arg_637: GLenum, arg_638: GLuint) GLboolean { return glad_glIsEnabledi.?(arg_637, arg_638); } pub inline fn beginTransformFeedback(arg_639: GLenum) void { return glad_glBeginTransformFeedback.?(arg_639); } pub inline fn endTransformFeedback() void { return glad_glEndTransformFeedback.?(); } pub inline fn bindBufferRange(arg_640: GLenum, arg_641: GLuint, arg_642: GLuint, arg_643: GLintptr, arg_644: GLsizeiptr) void { return glad_glBindBufferRange.?(arg_640, arg_641, arg_642, arg_643, arg_644); } pub inline fn bindBufferBase(arg_645: GLenum, arg_646: GLuint, arg_647: GLuint) void { return glad_glBindBufferBase.?(arg_645, arg_646, arg_647); } pub inline fn transformFeedbackVaryings(arg_648: GLuint, arg_649: GLsizei, arg_650: [*c]const [*c]const GLchar, arg_651: GLenum) void { return glad_glTransformFeedbackVaryings.?(arg_648, arg_649, arg_650, arg_651); } pub inline fn getTransformFeedbackVarying(arg_652: GLuint, arg_653: GLuint, arg_654: GLsizei, arg_655: [*c]GLsizei, arg_656: [*c]GLsizei, arg_657: [*c]GLenum, arg_658: [*c]GLchar) void { return glad_glGetTransformFeedbackVarying.?(arg_652, arg_653, arg_654, arg_655, arg_656, arg_657, arg_658); } pub inline fn clampColor(arg_659: GLenum, arg_660: GLenum) void { return glad_glClampColor.?(arg_659, arg_660); } pub inline fn beginConditionalRender(arg_661: GLuint, arg_662: GLenum) void { return glad_glBeginConditionalRender.?(arg_661, arg_662); } pub inline fn endConditionalRender() void { return glad_glEndConditionalRender.?(); } pub inline fn vertexAttribIPointer(arg_663: GLuint, arg_664: GLint, arg_665: GLenum, arg_666: GLsizei, arg_667: ?*const anyopaque) void { return glad_glVertexAttribIPointer.?(arg_663, arg_664, arg_665, arg_666, arg_667); } pub inline fn getVertexAttribIiv(arg_668: GLuint, arg_669: GLenum, arg_670: [*c]GLint) void { return glad_glGetVertexAttribIiv.?(arg_668, arg_669, arg_670); } pub inline fn getVertexAttribIuiv(arg_671: GLuint, arg_672: GLenum, arg_673: [*c]GLuint) void { return glad_glGetVertexAttribIuiv.?(arg_671, arg_672, arg_673); } pub inline fn vertexAttribI1i(arg_674: GLuint, arg_675: GLint) void { return glad_glVertexAttribI1i.?(arg_674, arg_675); } pub inline fn vertexAttribI2i(arg_676: GLuint, arg_677: GLint, arg_678: GLint) void { return glad_glVertexAttribI2i.?(arg_676, arg_677, arg_678); } pub inline fn vertexAttribI3i(arg_679: GLuint, arg_680: GLint, arg_681: GLint, arg_682: GLint) void { return glad_glVertexAttribI3i.?(arg_679, arg_680, arg_681, arg_682); } pub inline fn vertexAttribI4i(arg_683: GLuint, arg_684: GLint, arg_685: GLint, arg_686: GLint, arg_687: GLint) void { return glad_glVertexAttribI4i.?(arg_683, arg_684, arg_685, arg_686, arg_687); } pub inline fn vertexAttribI1ui(arg_688: GLuint, arg_689: GLuint) void { return glad_glVertexAttribI1ui.?(arg_688, arg_689); } pub inline fn vertexAttribI2ui(arg_690: GLuint, arg_691: GLuint, arg_692: GLuint) void { return glad_glVertexAttribI2ui.?(arg_690, arg_691, arg_692); } pub inline fn vertexAttribI3ui(arg_693: GLuint, arg_694: GLuint, arg_695: GLuint, arg_696: GLuint) void { return glad_glVertexAttribI3ui.?(arg_693, arg_694, arg_695, arg_696); } pub inline fn vertexAttribI4ui(arg_697: GLuint, arg_698: GLuint, arg_699: GLuint, arg_700: GLuint, arg_701: GLuint) void { return glad_glVertexAttribI4ui.?(arg_697, arg_698, arg_699, arg_700, arg_701); } pub inline fn vertexAttribI1iv(arg_702: GLuint, arg_703: [*c]const GLint) void { return glad_glVertexAttribI1iv.?(arg_702, arg_703); } pub inline fn vertexAttribI2iv(arg_704: GLuint, arg_705: [*c]const GLint) void { return glad_glVertexAttribI2iv.?(arg_704, arg_705); } pub inline fn vertexAttribI3iv(arg_706: GLuint, arg_707: [*c]const GLint) void { return glad_glVertexAttribI3iv.?(arg_706, arg_707); } pub inline fn vertexAttribI4iv(arg_708: GLuint, arg_709: [*c]const GLint) void { return glad_glVertexAttribI4iv.?(arg_708, arg_709); } pub inline fn vertexAttribI1uiv(arg_710: GLuint, arg_711: [*c]const GLuint) void { return glad_glVertexAttribI1uiv.?(arg_710, arg_711); } pub inline fn vertexAttribI2uiv(arg_712: GLuint, arg_713: [*c]const GLuint) void { return glad_glVertexAttribI2uiv.?(arg_712, arg_713); } pub inline fn vertexAttribI3uiv(arg_714: GLuint, arg_715: [*c]const GLuint) void { return glad_glVertexAttribI3uiv.?(arg_714, arg_715); } pub inline fn vertexAttribI4uiv(arg_716: GLuint, arg_717: [*c]const GLuint) void { return glad_glVertexAttribI4uiv.?(arg_716, arg_717); } pub inline fn vertexAttribI4bv(arg_718: GLuint, arg_719: [*c]const GLbyte) void { return glad_glVertexAttribI4bv.?(arg_718, arg_719); } pub inline fn vertexAttribI4sv(arg_720: GLuint, arg_721: [*c]const GLshort) void { return glad_glVertexAttribI4sv.?(arg_720, arg_721); } pub inline fn vertexAttribI4ubv(arg_722: GLuint, arg_723: [*c]const GLubyte) void { return glad_glVertexAttribI4ubv.?(arg_722, arg_723); } pub inline fn vertexAttribI4usv(arg_724: GLuint, arg_725: [*c]const GLushort) void { return glad_glVertexAttribI4usv.?(arg_724, arg_725); } pub inline fn getUniformuiv(arg_726: GLuint, arg_727: GLint, arg_728: [*c]GLuint) void { return glad_glGetUniformuiv.?(arg_726, arg_727, arg_728); } pub inline fn bindFragDataLocation(arg_729: GLuint, arg_730: GLuint, arg_731: [*c]const GLchar) void { return glad_glBindFragDataLocation.?(arg_729, arg_730, arg_731); } pub inline fn getFragDataLocation(arg_732: GLuint, arg_733: [*c]const GLchar) GLint { return glad_glGetFragDataLocation.?(arg_732, arg_733); } pub inline fn uniform1ui(arg_734: GLint, arg_735: GLuint) void { return glad_glUniform1ui.?(arg_734, arg_735); } pub inline fn uniform2ui(arg_736: GLint, arg_737: GLuint, arg_738: GLuint) void { return glad_glUniform2ui.?(arg_736, arg_737, arg_738); } pub inline fn uniform3ui(arg_739: GLint, arg_740: GLuint, arg_741: GLuint, arg_742: GLuint) void { return glad_glUniform3ui.?(arg_739, arg_740, arg_741, arg_742); } pub inline fn uniform4ui(arg_743: GLint, arg_744: GLuint, arg_745: GLuint, arg_746: GLuint, arg_747: GLuint) void { return glad_glUniform4ui.?(arg_743, arg_744, arg_745, arg_746, arg_747); } pub inline fn uniform1uiv(arg_748: GLint, arg_749: GLsizei, arg_750: [*c]const GLuint) void { return glad_glUniform1uiv.?(arg_748, arg_749, arg_750); } pub inline fn uniform2uiv(arg_751: GLint, arg_752: GLsizei, arg_753: [*c]const GLuint) void { return glad_glUniform2uiv.?(arg_751, arg_752, arg_753); } pub inline fn uniform3uiv(arg_754: GLint, arg_755: GLsizei, arg_756: [*c]const GLuint) void { return glad_glUniform3uiv.?(arg_754, arg_755, arg_756); } pub inline fn uniform4uiv(arg_757: GLint, arg_758: GLsizei, arg_759: [*c]const GLuint) void { return glad_glUniform4uiv.?(arg_757, arg_758, arg_759); } pub inline fn texParameterIiv(arg_760: GLenum, arg_761: GLenum, arg_762: [*c]const GLint) void { return glad_glTexParameterIiv.?(arg_760, arg_761, arg_762); } pub inline fn texParameterIuiv(arg_763: GLenum, arg_764: GLenum, arg_765: [*c]const GLuint) void { return glad_glTexParameterIuiv.?(arg_763, arg_764, arg_765); } pub inline fn getTexParameterIiv(arg_766: GLenum, arg_767: GLenum, arg_768: [*c]GLint) void { return glad_glGetTexParameterIiv.?(arg_766, arg_767, arg_768); } pub inline fn getTexParameterIuiv(arg_769: GLenum, arg_770: GLenum, arg_771: [*c]GLuint) void { return glad_glGetTexParameterIuiv.?(arg_769, arg_770, arg_771); } pub inline fn clearBufferiv(arg_772: GLenum, arg_773: GLint, arg_774: [*c]const GLint) void { return glad_glClearBufferiv.?(arg_772, arg_773, arg_774); } pub inline fn clearBufferuiv(arg_775: GLenum, arg_776: GLint, arg_777: [*c]const GLuint) void { return glad_glClearBufferuiv.?(arg_775, arg_776, arg_777); } pub inline fn clearBufferfv(arg_778: GLenum, arg_779: GLint, arg_780: [*c]const GLfloat) void { return glad_glClearBufferfv.?(arg_778, arg_779, arg_780); } pub inline fn clearBufferfi(arg_781: GLenum, arg_782: GLint, arg_783: GLfloat, arg_784: GLint) void { return glad_glClearBufferfi.?(arg_781, arg_782, arg_783, arg_784); } pub inline fn getStringi(arg_785: GLenum, arg_786: GLuint) [*c]const GLubyte { return glad_glGetStringi.?(arg_785, arg_786); } pub inline fn isRenderbuffer(arg_787: GLuint) GLboolean { return glad_glIsRenderbuffer.?(arg_787); } pub inline fn bindRenderbuffer(arg_788: GLenum, arg_789: GLuint) void { return glad_glBindRenderbuffer.?(arg_788, arg_789); } pub inline fn deleteRenderbuffers(arg_790: GLsizei, arg_791: [*c]const GLuint) void { return glad_glDeleteRenderbuffers.?(arg_790, arg_791); } pub inline fn genRenderbuffers(arg_792: GLsizei, arg_793: [*c]GLuint) void { return glad_glGenRenderbuffers.?(arg_792, arg_793); } pub inline fn renderbufferStorage(arg_794: GLenum, arg_795: GLenum, arg_796: GLsizei, arg_797: GLsizei) void { return glad_glRenderbufferStorage.?(arg_794, arg_795, arg_796, arg_797); } pub inline fn getRenderbufferParameteriv(arg_798: GLenum, arg_799: GLenum, arg_800: [*c]GLint) void { return glad_glGetRenderbufferParameteriv.?(arg_798, arg_799, arg_800); } pub inline fn isFramebuffer(arg_801: GLuint) GLboolean { return glad_glIsFramebuffer.?(arg_801); } pub inline fn bindFramebuffer(arg_802: GLenum, arg_803: GLuint) void { return glad_glBindFramebuffer.?(arg_802, arg_803); } pub inline fn deleteFramebuffers(arg_804: GLsizei, arg_805: [*c]const GLuint) void { return glad_glDeleteFramebuffers.?(arg_804, arg_805); } pub inline fn genFramebuffers(arg_806: GLsizei, arg_807: [*c]GLuint) void { return glad_glGenFramebuffers.?(arg_806, arg_807); } pub inline fn checkFramebufferStatus(arg_808: GLenum) GLenum { return glad_glCheckFramebufferStatus.?(arg_808); } pub inline fn framebufferTexture1D(arg_809: GLenum, arg_810: GLenum, arg_811: GLenum, arg_812: GLuint, arg_813: GLint) void { return glad_glFramebufferTexture1D.?(arg_809, arg_810, arg_811, arg_812, arg_813); } pub inline fn framebufferTexture2D(arg_814: GLenum, arg_815: GLenum, arg_816: GLenum, arg_817: GLuint, arg_818: GLint) void { return glad_glFramebufferTexture2D.?(arg_814, arg_815, arg_816, arg_817, arg_818); } pub inline fn framebufferTexture3D(arg_819: GLenum, arg_820: GLenum, arg_821: GLenum, arg_822: GLuint, arg_823: GLint, arg_824: GLint) void { return glad_glFramebufferTexture3D.?(arg_819, arg_820, arg_821, arg_822, arg_823, arg_824); } pub inline fn framebufferRenderbuffer(arg_825: GLenum, arg_826: GLenum, arg_827: GLenum, arg_828: GLuint) void { return glad_glFramebufferRenderbuffer.?(arg_825, arg_826, arg_827, arg_828); } pub inline fn getFramebufferAttachmentParameteriv(arg_829: GLenum, arg_830: GLenum, arg_831: GLenum, arg_832: [*c]GLint) void { return glad_glGetFramebufferAttachmentParameteriv.?(arg_829, arg_830, arg_831, arg_832); } pub inline fn generateMipmap(arg_833: GLenum) void { return glad_glGenerateMipmap.?(arg_833); } pub inline fn blitFramebuffer(arg_834: GLint, arg_835: GLint, arg_836: GLint, arg_837: GLint, arg_838: GLint, arg_839: GLint, arg_840: GLint, arg_841: GLint, arg_842: GLbitfield, arg_843: GLenum) void { return glad_glBlitFramebuffer.?(arg_834, arg_835, arg_836, arg_837, arg_838, arg_839, arg_840, arg_841, arg_842, arg_843); } pub inline fn renderbufferStorageMultisample(arg_844: GLenum, arg_845: GLsizei, arg_846: GLenum, arg_847: GLsizei, arg_848: GLsizei) void { return glad_glRenderbufferStorageMultisample.?(arg_844, arg_845, arg_846, arg_847, arg_848); } pub inline fn framebufferTextureLayer(arg_849: GLenum, arg_850: GLenum, arg_851: GLuint, arg_852: GLint, arg_853: GLint) void { return glad_glFramebufferTextureLayer.?(arg_849, arg_850, arg_851, arg_852, arg_853); } pub inline fn mapBufferRange(arg_854: GLenum, arg_855: GLintptr, arg_856: GLsizeiptr, arg_857: GLbitfield) ?*anyopaque { return glad_glMapBufferRange.?(arg_854, arg_855, arg_856, arg_857); } pub inline fn flushMappedBufferRange(arg_858: GLenum, arg_859: GLintptr, arg_860: GLsizeiptr) void { return glad_glFlushMappedBufferRange.?(arg_858, arg_859, arg_860); } pub inline fn bindVertexArray(arg_861: GLuint) void { return glad_glBindVertexArray.?(arg_861); } pub inline fn deleteVertexArrays(arg_862: GLsizei, arg_863: [*c]const GLuint) void { return glad_glDeleteVertexArrays.?(arg_862, arg_863); } pub inline fn genVertexArrays(arg_864: GLsizei, arg_865: [*c]GLuint) void { return glad_glGenVertexArrays.?(arg_864, arg_865); } pub inline fn isVertexArray(arg_866: GLuint) GLboolean { return glad_glIsVertexArray.?(arg_866); } pub const GL_VERSION_3_1 = @as(c_int, 1); pub inline fn drawArraysInstanced(arg_867: GLenum, arg_868: GLint, arg_869: GLsizei, arg_870: GLsizei) void { return glad_glDrawArraysInstanced.?(arg_867, arg_868, arg_869, arg_870); } pub inline fn drawElementsInstanced(arg_871: GLenum, arg_872: GLsizei, arg_873: GLenum, arg_874: ?*const anyopaque, arg_875: GLsizei) void { return glad_glDrawElementsInstanced.?(arg_871, arg_872, arg_873, arg_874, arg_875); } pub inline fn texBuffer(arg_876: GLenum, arg_877: GLenum, arg_878: GLuint) void { return glad_glTexBuffer.?(arg_876, arg_877, arg_878); } pub inline fn primitiveRestartIndex(arg_879: GLuint) void { return glad_glPrimitiveRestartIndex.?(arg_879); } pub inline fn copyBufferSubData(arg_880: GLenum, arg_881: GLenum, arg_882: GLintptr, arg_883: GLintptr, arg_884: GLsizeiptr) void { return glad_glCopyBufferSubData.?(arg_880, arg_881, arg_882, arg_883, arg_884); } pub inline fn getUniformIndices(arg_885: GLuint, arg_886: GLsizei, arg_887: [*c]const [*c]const GLchar, arg_888: [*c]GLuint) void { return glad_glGetUniformIndices.?(arg_885, arg_886, arg_887, arg_888); } pub inline fn getActiveUniformsiv(arg_889: GLuint, arg_890: GLsizei, arg_891: [*c]const GLuint, arg_892: GLenum, arg_893: [*c]GLint) void { return glad_glGetActiveUniformsiv.?(arg_889, arg_890, arg_891, arg_892, arg_893); } pub inline fn getActiveUniformName(arg_894: GLuint, arg_895: GLuint, arg_896: GLsizei, arg_897: [*c]GLsizei, arg_898: [*c]GLchar) void { return glad_glGetActiveUniformName.?(arg_894, arg_895, arg_896, arg_897, arg_898); } pub inline fn getUniformBlockIndex(arg_899: GLuint, arg_900: [*c]const GLchar) GLuint { return glad_glGetUniformBlockIndex.?(arg_899, arg_900); } pub inline fn getActiveUniformBlockiv(arg_901: GLuint, arg_902: GLuint, arg_903: GLenum, arg_904: [*c]GLint) void { return glad_glGetActiveUniformBlockiv.?(arg_901, arg_902, arg_903, arg_904); } pub inline fn getActiveUniformBlockName(arg_905: GLuint, arg_906: GLuint, arg_907: GLsizei, arg_908: [*c]GLsizei, arg_909: [*c]GLchar) void { return glad_glGetActiveUniformBlockName.?(arg_905, arg_906, arg_907, arg_908, arg_909); } pub inline fn uniformBlockBinding(arg_910: GLuint, arg_911: GLuint, arg_912: GLuint) void { return glad_glUniformBlockBinding.?(arg_910, arg_911, arg_912); } pub const GL_VERSION_3_2 = @as(c_int, 1); pub inline fn drawElementsBaseVertex(arg_913: GLenum, arg_914: GLsizei, arg_915: GLenum, arg_916: ?*const anyopaque, arg_917: GLint) void { return glad_glDrawElementsBaseVertex.?(arg_913, arg_914, arg_915, arg_916, arg_917); } pub inline fn drawRangeElementsBaseVertex(arg_918: GLenum, arg_919: GLuint, arg_920: GLuint, arg_921: GLsizei, arg_922: GLenum, arg_923: ?*const anyopaque, arg_924: GLint) void { return glad_glDrawRangeElementsBaseVertex.?(arg_918, arg_919, arg_920, arg_921, arg_922, arg_923, arg_924); } pub inline fn drawElementsInstancedBaseVertex(arg_925: GLenum, arg_926: GLsizei, arg_927: GLenum, arg_928: ?*const anyopaque, arg_929: GLsizei, arg_930: GLint) void { return glad_glDrawElementsInstancedBaseVertex.?(arg_925, arg_926, arg_927, arg_928, arg_929, arg_930); } pub inline fn multiDrawElementsBaseVertex(arg_931: GLenum, arg_932: [*c]const GLsizei, arg_933: GLenum, arg_934: [*c]const ?*const anyopaque, arg_935: GLsizei, arg_936: [*c]const GLint) void { return glad_glMultiDrawElementsBaseVertex.?(arg_931, arg_932, arg_933, arg_934, arg_935, arg_936); } pub inline fn provokingVertex(arg_937: GLenum) void { return glad_glProvokingVertex.?(arg_937); } pub inline fn fenceSync(arg_938: GLenum, arg_939: GLbitfield) GLsync { return glad_glFenceSync.?(arg_938, arg_939); } pub inline fn isSync(arg_940: GLsync) GLboolean { return glad_glIsSync.?(arg_940); } pub inline fn deleteSync(arg_941: GLsync) void { return glad_glDeleteSync.?(arg_941); } pub inline fn clientWaitSync(arg_942: GLsync, arg_943: GLbitfield, arg_944: GLuint64) GLenum { return glad_glClientWaitSync.?(arg_942, arg_943, arg_944); } pub inline fn waitSync(arg_945: GLsync, arg_946: GLbitfield, arg_947: GLuint64) void { return glad_glWaitSync.?(arg_945, arg_946, arg_947); } pub inline fn getInteger64v(arg_948: GLenum, arg_949: [*c]GLint64) void { return glad_glGetInteger64v.?(arg_948, arg_949); } pub inline fn getSynciv(arg_950: GLsync, arg_951: GLenum, arg_952: GLsizei, arg_953: [*c]GLsizei, arg_954: [*c]GLint) void { return glad_glGetSynciv.?(arg_950, arg_951, arg_952, arg_953, arg_954); } pub inline fn getInteger64i_v(arg_955: GLenum, arg_956: GLuint, arg_957: [*c]GLint64) void { return glad_glGetInteger64i_v.?(arg_955, arg_956, arg_957); } pub inline fn getBufferParameteri64v(arg_958: GLenum, arg_959: GLenum, arg_960: [*c]GLint64) void { return glad_glGetBufferParameteri64v.?(arg_958, arg_959, arg_960); } pub inline fn framebufferTexture(arg_961: GLenum, arg_962: GLenum, arg_963: GLuint, arg_964: GLint) void { return glad_glFramebufferTexture.?(arg_961, arg_962, arg_963, arg_964); } pub inline fn texImage2DMultisample(arg_965: GLenum, arg_966: GLsizei, arg_967: GLenum, arg_968: GLsizei, arg_969: GLsizei, arg_970: GLboolean) void { return glad_glTexImage2DMultisample.?(arg_965, arg_966, arg_967, arg_968, arg_969, arg_970); } pub inline fn texImage3DMultisample(arg_971: GLenum, arg_972: GLsizei, arg_973: GLenum, arg_974: GLsizei, arg_975: GLsizei, arg_976: GLsizei, arg_977: GLboolean) void { return glad_glTexImage3DMultisample.?(arg_971, arg_972, arg_973, arg_974, arg_975, arg_976, arg_977); } pub inline fn getMultisamplefv(arg_978: GLenum, arg_979: GLuint, arg_980: [*c]GLfloat) void { return glad_glGetMultisamplefv.?(arg_978, arg_979, arg_980); } pub inline fn sampleMaski(arg_981: GLuint, arg_982: GLbitfield) void { return glad_glSampleMaski.?(arg_981, arg_982); } pub const GL_VERSION_3_3 = @as(c_int, 1); pub inline fn bindFragDataLocationIndexed(arg_983: GLuint, arg_984: GLuint, arg_985: GLuint, arg_986: [*c]const GLchar) void { return glad_glBindFragDataLocationIndexed.?(arg_983, arg_984, arg_985, arg_986); } pub inline fn getFragDataIndex(arg_987: GLuint, arg_988: [*c]const GLchar) GLint { return glad_glGetFragDataIndex.?(arg_987, arg_988); } pub inline fn genSamplers(arg_989: GLsizei, arg_990: [*c]GLuint) void { return glad_glGenSamplers.?(arg_989, arg_990); } pub inline fn deleteSamplers(arg_991: GLsizei, arg_992: [*c]const GLuint) void { return glad_glDeleteSamplers.?(arg_991, arg_992); } pub inline fn isSampler(arg_993: GLuint) GLboolean { return glad_glIsSampler.?(arg_993); } pub inline fn bindSampler(arg_994: GLuint, arg_995: GLuint) void { return glad_glBindSampler.?(arg_994, arg_995); } pub inline fn samplerParameteri(arg_996: GLuint, arg_997: GLenum, arg_998: GLint) void { return glad_glSamplerParameteri.?(arg_996, arg_997, arg_998); } pub inline fn samplerParameteriv(arg_999: GLuint, arg_1000: GLenum, arg_1001: [*c]const GLint) void { return glad_glSamplerParameteriv.?(arg_999, arg_1000, arg_1001); } pub inline fn samplerParameterf(arg_1002: GLuint, arg_1003: GLenum, arg_1004: GLfloat) void { return glad_glSamplerParameterf.?(arg_1002, arg_1003, arg_1004); } pub inline fn samplerParameterfv(arg_1005: GLuint, arg_1006: GLenum, arg_1007: [*c]const GLfloat) void { return glad_glSamplerParameterfv.?(arg_1005, arg_1006, arg_1007); } pub inline fn samplerParameterIiv(arg_1008: GLuint, arg_1009: GLenum, arg_1010: [*c]const GLint) void { return glad_glSamplerParameterIiv.?(arg_1008, arg_1009, arg_1010); } pub inline fn samplerParameterIuiv(arg_1011: GLuint, arg_1012: GLenum, arg_1013: [*c]const GLuint) void { return glad_glSamplerParameterIuiv.?(arg_1011, arg_1012, arg_1013); } pub inline fn getSamplerParameteriv(arg_1014: GLuint, arg_1015: GLenum, arg_1016: [*c]GLint) void { return glad_glGetSamplerParameteriv.?(arg_1014, arg_1015, arg_1016); } pub inline fn getSamplerParameterIiv(arg_1017: GLuint, arg_1018: GLenum, arg_1019: [*c]GLint) void { return glad_glGetSamplerParameterIiv.?(arg_1017, arg_1018, arg_1019); } pub inline fn getSamplerParameterfv(arg_1020: GLuint, arg_1021: GLenum, arg_1022: [*c]GLfloat) void { return glad_glGetSamplerParameterfv.?(arg_1020, arg_1021, arg_1022); } pub inline fn getSamplerParameterIuiv(arg_1023: GLuint, arg_1024: GLenum, arg_1025: [*c]GLuint) void { return glad_glGetSamplerParameterIuiv.?(arg_1023, arg_1024, arg_1025); } pub inline fn queryCounter(arg_1026: GLuint, arg_1027: GLenum) void { return glad_glQueryCounter.?(arg_1026, arg_1027); } pub inline fn getQueryObjecti64v(arg_1028: GLuint, arg_1029: GLenum, arg_1030: [*c]GLint64) void { return glad_glGetQueryObjecti64v.?(arg_1028, arg_1029, arg_1030); } pub inline fn getQueryObjectui64v(arg_1031: GLuint, arg_1032: GLenum, arg_1033: [*c]GLuint64) void { return glad_glGetQueryObjectui64v.?(arg_1031, arg_1032, arg_1033); } pub inline fn vertexAttribDivisor(arg_1034: GLuint, arg_1035: GLuint) void { return glad_glVertexAttribDivisor.?(arg_1034, arg_1035); } pub inline fn vertexAttribP1ui(arg_1036: GLuint, arg_1037: GLenum, arg_1038: GLboolean, arg_1039: GLuint) void { return glad_glVertexAttribP1ui.?(arg_1036, arg_1037, arg_1038, arg_1039); } pub inline fn vertexAttribP1uiv(arg_1040: GLuint, arg_1041: GLenum, arg_1042: GLboolean, arg_1043: [*c]const GLuint) void { return glad_glVertexAttribP1uiv.?(arg_1040, arg_1041, arg_1042, arg_1043); } pub inline fn vertexAttribP2ui(arg_1044: GLuint, arg_1045: GLenum, arg_1046: GLboolean, arg_1047: GLuint) void { return glad_glVertexAttribP2ui.?(arg_1044, arg_1045, arg_1046, arg_1047); } pub inline fn vertexAttribP2uiv(arg_1048: GLuint, arg_1049: GLenum, arg_1050: GLboolean, arg_1051: [*c]const GLuint) void { return glad_glVertexAttribP2uiv.?(arg_1048, arg_1049, arg_1050, arg_1051); } pub inline fn vertexAttribP3ui(arg_1052: GLuint, arg_1053: GLenum, arg_1054: GLboolean, arg_1055: GLuint) void { return glad_glVertexAttribP3ui.?(arg_1052, arg_1053, arg_1054, arg_1055); } pub inline fn vertexAttribP3uiv(arg_1056: GLuint, arg_1057: GLenum, arg_1058: GLboolean, arg_1059: [*c]const GLuint) void { return glad_glVertexAttribP3uiv.?(arg_1056, arg_1057, arg_1058, arg_1059); } pub inline fn vertexAttribP4ui(arg_1060: GLuint, arg_1061: GLenum, arg_1062: GLboolean, arg_1063: GLuint) void { return glad_glVertexAttribP4ui.?(arg_1060, arg_1061, arg_1062, arg_1063); } pub inline fn vertexAttribP4uiv(arg_1064: GLuint, arg_1065: GLenum, arg_1066: GLboolean, arg_1067: [*c]const GLuint) void { return glad_glVertexAttribP4uiv.?(arg_1064, arg_1065, arg_1066, arg_1067); } pub inline fn vertexP2ui(arg_1068: GLenum, arg_1069: GLuint) void { return glad_glVertexP2ui.?(arg_1068, arg_1069); } pub inline fn vertexP2uiv(arg_1070: GLenum, arg_1071: [*c]const GLuint) void { return glad_glVertexP2uiv.?(arg_1070, arg_1071); } pub inline fn vertexP3ui(arg_1072: GLenum, arg_1073: GLuint) void { return glad_glVertexP3ui.?(arg_1072, arg_1073); } pub inline fn vertexP3uiv(arg_1074: GLenum, arg_1075: [*c]const GLuint) void { return glad_glVertexP3uiv.?(arg_1074, arg_1075); } pub inline fn vertexP4ui(arg_1076: GLenum, arg_1077: GLuint) void { return glad_glVertexP4ui.?(arg_1076, arg_1077); } pub inline fn vertexP4uiv(arg_1078: GLenum, arg_1079: [*c]const GLuint) void { return glad_glVertexP4uiv.?(arg_1078, arg_1079); } pub inline fn texCoordP1ui(arg_1080: GLenum, arg_1081: GLuint) void { return glad_glTexCoordP1ui.?(arg_1080, arg_1081); } pub inline fn texCoordP1uiv(arg_1082: GLenum, arg_1083: [*c]const GLuint) void { return glad_glTexCoordP1uiv.?(arg_1082, arg_1083); } pub inline fn texCoordP2ui(arg_1084: GLenum, arg_1085: GLuint) void { return glad_glTexCoordP2ui.?(arg_1084, arg_1085); } pub inline fn texCoordP2uiv(arg_1086: GLenum, arg_1087: [*c]const GLuint) void { return glad_glTexCoordP2uiv.?(arg_1086, arg_1087); } pub inline fn texCoordP3ui(arg_1088: GLenum, arg_1089: GLuint) void { return glad_glTexCoordP3ui.?(arg_1088, arg_1089); } pub inline fn texCoordP3uiv(arg_1090: GLenum, arg_1091: [*c]const GLuint) void { return glad_glTexCoordP3uiv.?(arg_1090, arg_1091); } pub inline fn texCoordP4ui(arg_1092: GLenum, arg_1093: GLuint) void { return glad_glTexCoordP4ui.?(arg_1092, arg_1093); } pub inline fn texCoordP4uiv(arg_1094: GLenum, arg_1095: [*c]const GLuint) void { return glad_glTexCoordP4uiv.?(arg_1094, arg_1095); } pub inline fn multiTexCoordP1ui(arg_1096: GLenum, arg_1097: GLenum, arg_1098: GLuint) void { return glad_glMultiTexCoordP1ui.?(arg_1096, arg_1097, arg_1098); } pub inline fn multiTexCoordP1uiv(arg_1099: GLenum, arg_1100: GLenum, arg_1101: [*c]const GLuint) void { return glad_glMultiTexCoordP1uiv.?(arg_1099, arg_1100, arg_1101); } pub inline fn multiTexCoordP2ui(arg_1102: GLenum, arg_1103: GLenum, arg_1104: GLuint) void { return glad_glMultiTexCoordP2ui.?(arg_1102, arg_1103, arg_1104); } pub inline fn multiTexCoordP2uiv(arg_1105: GLenum, arg_1106: GLenum, arg_1107: [*c]const GLuint) void { return glad_glMultiTexCoordP2uiv.?(arg_1105, arg_1106, arg_1107); } pub inline fn multiTexCoordP3ui(arg_1108: GLenum, arg_1109: GLenum, arg_1110: GLuint) void { return glad_glMultiTexCoordP3ui.?(arg_1108, arg_1109, arg_1110); } pub inline fn multiTexCoordP3uiv(arg_1111: GLenum, arg_1112: GLenum, arg_1113: [*c]const GLuint) void { return glad_glMultiTexCoordP3uiv.?(arg_1111, arg_1112, arg_1113); } pub inline fn multiTexCoordP4ui(arg_1114: GLenum, arg_1115: GLenum, arg_1116: GLuint) void { return glad_glMultiTexCoordP4ui.?(arg_1114, arg_1115, arg_1116); } pub inline fn multiTexCoordP4uiv(arg_1117: GLenum, arg_1118: GLenum, arg_1119: [*c]const GLuint) void { return glad_glMultiTexCoordP4uiv.?(arg_1117, arg_1118, arg_1119); } pub inline fn normalP3ui(arg_1120: GLenum, arg_1121: GLuint) void { return glad_glNormalP3ui.?(arg_1120, arg_1121); } pub inline fn normalP3uiv(arg_1122: GLenum, arg_1123: [*c]const GLuint) void { return glad_glNormalP3uiv.?(arg_1122, arg_1123); } pub inline fn colorP3ui(arg_1124: GLenum, arg_1125: GLuint) void { return glad_glColorP3ui.?(arg_1124, arg_1125); } pub inline fn colorP3uiv(arg_1126: GLenum, arg_1127: [*c]const GLuint) void { return glad_glColorP3uiv.?(arg_1126, arg_1127); } pub inline fn colorP4ui(arg_1128: GLenum, arg_1129: GLuint) void { return glad_glColorP4ui.?(arg_1128, arg_1129); } pub inline fn colorP4uiv(arg_1130: GLenum, arg_1131: [*c]const GLuint) void { return glad_glColorP4uiv.?(arg_1130, arg_1131); } pub inline fn secondaryColorP3ui(arg_1132: GLenum, arg_1133: GLuint) void { return glad_glSecondaryColorP3ui.?(arg_1132, arg_1133); } pub inline fn secondaryColorP3uiv(arg_1134: GLenum, arg_1135: [*c]const GLuint) void { return glad_glSecondaryColorP3uiv.?(arg_1134, arg_1135); } const gladGLversionStruct = struct_gladGLversionStruct;
src/deps/gl/c.zig
const std = @import("std"); const lib = @import("lib.zig"); const Interpreter = lib.Interpreter; const Parser = lib.Parser; const ArrayList = std.ArrayList; var vm: Interpreter = .{}; var instance = std.heap.GeneralPurposeAllocator(.{}){}; var output: ArrayList(u8) = undefined; const gpa = instance.allocator(); pub export fn init() void { output = ArrayList(u8).init(gpa); } pub export fn add(text: [*]const u8, len: usize) i32 { const slice = text[0..len]; return addInternal(slice) catch -1; } fn addInternal(text: []const u8) !i32 { var obj = try Parser.parse(gpa, "", text); errdefer obj.deinit(gpa); try vm.linker.objects.append(gpa, obj); return @intCast(i32, vm.linker.objects.items.len - 1); } pub export fn update(id: u32, text: [*]const u8, len: usize) i32 { const slice = text[0..len]; updateInternal(id, slice) catch return -1; return 0; } fn updateInternal(id: u32, text: []const u8) !void { if (id >= vm.linker.objects.items.len) return error.@"Id out of range"; const obj = try Parser.parse(gpa, "", text); gpa.free(vm.linker.objects.items[id].text); vm.linker.objects.items[id].deinit(gpa); vm.linker.objects.items[id] = obj; } pub export fn link() i32 { vm.linker.link(gpa) catch return -1; return 0; } pub export fn call(name: [*]const u8, len: usize) i32 { vm.call(gpa, name[0..len], Render, .{}) catch return -1; return 0; } pub export fn reset() void { for (vm.linker.objects.items) |obj| gpa.free(obj.text); vm.deinit(gpa); vm = .{}; } const Render = struct { pub const Error = @TypeOf(output).Writer.Error; pub fn write(_: Render, v: *Interpreter, text: []const u8, nl: u16) !void { _ = v; const writer = output.writer(); try writer.writeAll(text); try writer.writeByteNTimes('\n', nl); } pub fn indent(_: Render, v: *Interpreter) !void { const writer = output.writer(); try writer.writeByteNTimes(' ', v.indent); } };
lib/wasm.zig
const clap = @import("clap"); const format = @import("format"); const it = @import("ziter"); const std = @import("std"); const ston = @import("ston"); const util = @import("util"); const ascii = std.ascii; const debug = std.debug; 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 os = std.os; const rand = std.rand; const testing = std.testing; const escape = util.escape; const Program = @This(); allocator: mem.Allocator, random: rand.Random, options: struct { seed: u64, abilities: ThemeOption, items: ItemOption, moves: MoveOption, party_size_max: u8, party_size_min: u8, party_size_method: PartySizeMethod, stats: StatsOption, types: ThemeOption, excluded_pokemons: []const []const u8, }, pokedex: Set = Set{}, pokemons: Pokemons = Pokemons{}, trainers: Trainers = Trainers{}, moves: Moves = Moves{}, held_items: Set = Set{}, // Precomputed data for later use. Initialized in `run` species: Set = undefined, species_by_ability: SpeciesBy = undefined, species_by_type: SpeciesBy = undefined, stats: MinMax(u16) = undefined, // Containers we reuse often enough that keeping them around with // their preallocated capacity is worth the hassel. simular: std.ArrayListUnmanaged(u16) = std.ArrayListUnmanaged(u16){}, intersection: Set = Set{}, const ItemOption = enum { none, unchanged, random, }; const MoveOption = enum { none, unchanged, best, best_for_level, random_learnable, random, }; const ThemeOption = enum { same, random, themed, }; const StatsOption = enum { random, simular, follow_level, }; const PartySizeMethod = enum { unchanged, minimum, random, }; pub const main = util.generateMain(Program); pub const version = "0.0.0"; pub const description = \\Randomizes trainer parties. \\ ; pub const params = &[_]clap.Param(clap.Help){ clap.parseParam( "-h, --help " ++ "Display this help text and exit.", ) catch unreachable, clap.parseParam( "-i, --items <none|unchanged|random> " ++ "The method used to picking held items. (default: none)", ) catch unreachable, clap.parseParam( "-o, --moves <none|unchanged|best|best_for_level|random_learnable|random> " ++ " The method used to picking moves. (default: none)", ) catch unreachable, clap.parseParam( "-m, --party-size-min <INT> " ++ "The minimum size each trainers party is allowed to be. (default: 1)", ) catch unreachable, clap.parseParam( "-M, --party-size-max <INT> " ++ "The maximum size each trainers party is allowed to be. (default: 6)", ) catch unreachable, clap.parseParam( "-p, --party-size <unchanged|minimum|random> " ++ "The method used to pick the trainer party size. (default: unchanged)", ) catch unreachable, clap.parseParam( "-s, --seed <INT> " ++ "The seed to use for random numbers. A random seed will be picked if this is not " ++ "specified.", ) catch unreachable, clap.parseParam( "-S, --stats <random|simular|follow_level> " ++ "The total stats the picked pokemon should have. (default: random)", ) catch unreachable, clap.parseParam( "-t, --types <random|same|themed> " ++ "Which types each trainer should use. (default: random)", ) catch unreachable, clap.parseParam( "-a, --abilities <random|same|themed> " ++ "Which ability each party member should have. (default: random)", ) catch unreachable, clap.parseParam( "-e, --exclude <STRING>... " ++ "List of pokemons to never pick. Case insensitive. Supports wildcards like 'nido*'.", ) catch unreachable, clap.parseParam( "-v, --version " ++ "Output version information and exit.", ) catch unreachable, }; pub fn init(allocator: mem.Allocator, args: anytype) !Program { const seed = try util.getSeed(args); const abilities_arg = args.option("--abilities") orelse "random"; const items_arg = args.option("--items") orelse "none"; const moves_arg = args.option("--moves") orelse "none"; const party_size_max_arg = args.option("--party-size-max") orelse "6"; const party_size_method_arg = args.option("--party-size") orelse "unchanged"; const party_size_min_arg = args.option("--party-size-min") orelse "1"; const stats_arg = args.option("--stats") orelse "random"; const types_arg = args.option("--types") orelse "random"; const excluded_pokemons_arg = args.options("--exclude"); const party_size_min = fmt.parseUnsigned(u8, party_size_min_arg, 10); const party_size_max = fmt.parseUnsigned(u8, party_size_max_arg, 10); const abilities = std.meta.stringToEnum(ThemeOption, abilities_arg) orelse { log.err("--abilities does not support '{s}'", .{abilities_arg}); return error.InvalidArgument; }; const items = std.meta.stringToEnum(ItemOption, items_arg) orelse { log.err("--items does not support '{s}'", .{items_arg}); return error.InvalidArgument; }; const party_size_method = std.meta.stringToEnum( PartySizeMethod, party_size_method_arg, ) orelse { log.err("--party-size-pick-method does not support '{s}'", .{party_size_method_arg}); return error.InvalidArgument; }; const moves = std.meta.stringToEnum(MoveOption, moves_arg) orelse { log.err("--moves does not support '{s}'", .{moves_arg}); return error.InvalidArgument; }; const stats = std.meta.stringToEnum(StatsOption, stats_arg) orelse { log.err("--stats does not support '{s}'", .{stats_arg}); return error.InvalidArgument; }; const types = std.meta.stringToEnum(ThemeOption, types_arg) orelse { log.err("--types does not support '{s}'", .{types_arg}); return error.InvalidArgument; }; for ([_]struct { arg: []const u8, value: []const u8, check: anyerror!u8 }{ .{ .arg = "--party-size-min", .value = party_size_min_arg, .check = party_size_min }, .{ .arg = "--party-size-max", .value = party_size_max_arg, .check = party_size_max }, }) |arg| { if (arg.check) |_| {} else |_| { log.err("Invalid value for {s}: {s}", .{ arg.arg, arg.value }); return error.InvalidArgument; } } var excluded_pokemons = try std.ArrayList([]const u8) .initCapacity(allocator, excluded_pokemons_arg.len); for (excluded_pokemons_arg) |exclude| excluded_pokemons.appendAssumeCapacity(try ascii.allocLowerString(allocator, exclude)); return Program{ .allocator = allocator, .random = undefined, // Initialized in `run` .options = .{ .seed = seed, .abilities = abilities, .items = items, .moves = moves, .party_size_max = party_size_max catch unreachable, .party_size_min = party_size_min catch unreachable, .party_size_method = party_size_method, .stats = stats, .types = types, .excluded_pokemons = excluded_pokemons.toOwnedSlice(), }, }; } pub fn run( program: *Program, comptime Reader: type, comptime Writer: type, stdio: util.CustomStdIoStreams(Reader, Writer), ) anyerror!void { const allocator = program.allocator; try format.io(allocator, stdio.in, stdio.out, program, useGame); const species = try pokedexPokemons( allocator, program.pokedex, program.pokemons, program.options.excluded_pokemons, ); program.random = rand.DefaultPrng.init(program.options.seed).random(); program.species = species; program.species_by_ability = try speciesByAbility(allocator, program.pokemons, species); program.species_by_type = try speciesByType(allocator, program.pokemons, species); program.stats = minMaxStats(program.pokemons, species); try program.randomize(); try program.output(stdio.out); } fn output(program: *Program, writer: anytype) !void { try ston.serialize(writer, .{ .trainers = program.trainers }); } fn useGame(program: *Program, parsed: format.Game) !void { const allocator = program.allocator; switch (parsed) { .pokedex => |pokedex| { _ = try program.pokedex.put(allocator, pokedex.index, {}); return error.DidNotConsumeData; }, .pokemons => |pokemons| { const pokemon = (try program.pokemons.getOrPutValue(allocator, pokemons.index, .{})) .value_ptr; switch (pokemons.value) { .catch_rate => |catch_rate| pokemon.catch_rate = catch_rate, .pokedex_entry => |pokedex_entry| pokemon.pokedex_entry = pokedex_entry, .name => |name| { pokemon.name = try escape.default.unescapeAlloc(allocator, name); for (pokemon.name) |*c| c.* = ascii.toLower(c.*); }, .stats => |stats| { const stat = @enumToInt(stats); if (pokemon.stats[stat] > stats.value()) { pokemon.total_stats -= pokemon.stats[stat] - stats.value(); } else { pokemon.total_stats += stats.value() - pokemon.stats[stat]; } pokemon.stats[stat] = stats.value(); }, .types => |types| _ = try pokemon.types.put(allocator, types.value, {}), .abilities => |ability| _ = try pokemon.abilities.put( allocator, ability.index, ability.value, ), .moves => |moves| { const move = (try pokemon.lvl_up_moves.getOrPutValue( allocator, moves.index, .{}, )).value_ptr; format.setField(move, moves.value); }, .base_exp_yield, .ev_yield, .items, .gender_ratio, .egg_cycles, .base_friendship, .growth_rate, .egg_groups, .color, .evos, .tms, .hms, => return error.DidNotConsumeData, } return error.DidNotConsumeData; }, .trainers => |trainers| { const trainer = (try program.trainers.getOrPutValue(allocator, trainers.index, .{})) .value_ptr; switch (trainers.value) { .party_size => |party_size| trainer.party_size = party_size, .party_type => |party_type| trainer.party_type = party_type, .party => |party| { const member = (try trainer.party.getOrPutValue(allocator, party.index, .{})) .value_ptr; switch (party.value) { .species => |species| member.species = species, .level => |level| member.level = level, .item => |item| member.item = item, .ability => |ability| member.ability = ability, .moves => |moves| _ = try member.moves.put( allocator, moves.index, moves.value, ), } return; }, .class, .encounter_music, .trainer_picture, .name, .items, => return error.DidNotConsumeData, } return; }, .items => |items| switch (items.value) { .battle_effect => |effect| { if (effect != 0) _ = try program.held_items.put(allocator, items.index, {}); return error.DidNotConsumeData; }, .name, .description, .price, .pocket, => return error.DidNotConsumeData, }, .moves => |moves| { const move = (try program.moves.getOrPutValue(allocator, moves.index, .{})) .value_ptr; switch (moves.value) { .power => |power| move.power = power, .type => |_type| move.type = _type, .pp => |pp| move.pp = pp, .accuracy => |accuracy| move.accuracy = accuracy, .name, .description, .effect, .target, .priority, .category, => {}, } return error.DidNotConsumeData; }, .version, .game_title, .gamecode, .instant_text, .starters, .text_delays, .abilities, .types, .tms, .hms, .maps, .wild_pokemons, .static_pokemons, .given_pokemons, .pokeball_items, .hidden_hollows, .text, => return error.DidNotConsumeData, } unreachable; } fn randomize(program: *Program) !void { if (program.species_by_type.count() == 0) { std.log.err("No types where found. Cannot randomize.", .{}); return; } for (program.trainers.values()) |*trainer| { // Trainers with 0 party members are considered "invalid" trainers // and will not be randomized. if (trainer.party_size == 0) continue; try program.randomizeTrainer(trainer); } } fn randomizeTrainer(program: *Program, trainer: *Trainer) !void { const allocator = program.allocator; const themes = Themes{ .type = switch (program.options.types) { .themed => util.random.item(program.random, program.species_by_type.keys()).?.*, else => undefined, }, .ability = switch (program.options.abilities) { .themed => util.random.item(program.random, program.species_by_ability.keys()).?.*, else => undefined, }, }; const wants_moves = switch (program.options.moves) { .unchanged => trainer.party_type.haveMoves(), .none => false, .best, .best_for_level, .random_learnable, .random, => true, }; const wants_items = switch (program.options.items) { .unchanged => trainer.party_type.haveItem(), .none => false, .random => true, }; trainer.party_size = switch (program.options.party_size_method) { .unchanged => math.clamp( trainer.party_size, program.options.party_size_min, program.options.party_size_max, ), .random => program.random.intRangeAtMost( u8, program.options.party_size_min, program.options.party_size_max, ), .minimum => program.options.party_size_min, }; trainer.party_type = switch (wants_moves) { true => switch (wants_items) { true => format.PartyType.both, false => format.PartyType.moves, }, false => switch (wants_items) { true => format.PartyType.item, false => format.PartyType.none, }, }; // Fill trainer party with more PokΓ©mons until `party_size` have been // reached. The PokΓ©mons we fill the party with are PokΓ©mons that are // already in the party. This code assumes that at least 1 PokΓ©mon // is in the party, which is always true as we don't randomize trainers // with a party size of 0. const party_member_max = trainer.party.count(); var party_member: u8 = 0; var i: u8 = 0; while (i < trainer.party_size) : (i += 1) { const result = try trainer.party.getOrPut(allocator, i); if (!result.found_existing) { const member = trainer.party.values()[party_member]; result.value_ptr.* = .{ .species = member.species, .item = member.item, .level = member.level, .moves = try member.moves.clone(allocator), }; party_member += 1; party_member %= @intCast(u8, party_member_max); } } for (trainer.party.values()[0..trainer.party_size]) |*member| { try randomizePartyMember(program, themes, trainer.*, member); switch (program.options.items) { .unchanged => {}, .none => member.item = null, .random => member.item = util.random.item( program.random, program.held_items.keys(), ).?.*, } switch (program.options.moves) { .none, .unchanged => {}, .best, .best_for_level => if (member.species) |species| { const pokemon = program.pokemons.get(species).?; const level = switch (program.options.moves) { .best => math.maxInt(u8), .best_for_level => member.level orelse math.maxInt(u8), else => unreachable, }; fillWithBestMovesForLevel( program.moves, pokemon, level, &member.moves, ); }, .random_learnable => if (member.species) |species| { const pokemon = program.pokemons.get(species).?; fillWithRandomLevelUpMoves(program.random, pokemon.lvl_up_moves, &member.moves); }, .random => fillWithRandomMoves(program.random, program.moves, &member.moves), } } } fn fillWithBestMovesForLevel( all_moves: Moves, pokemon: Pokemon, level: u8, moves: *MemberMoves, ) void { // Before pick best moves, we make sure the PokΓ©mon has no moves. mem.set(u16, moves.values(), 0); // Go over all level up moves, and replace the current moves with better moves // as we find them for (pokemon.lvl_up_moves.values()) |lvl_up_move| { if (lvl_up_move.id == 0) continue; if (level < lvl_up_move.level) continue; // PokΓ©mon already have this move. We don't wonna have the same move twice if (hasMove(moves.values(), lvl_up_move.id)) continue; const this_move = all_moves.get(lvl_up_move.id) orelse continue; const this_move_r = RelativeMove.from(pokemon, this_move); for (moves.values()) |*move| { const prev_move = all_moves.get(move.*) orelse { // Could not find info about this move. Assume it's and invalid or bad // move and replace it. move.* = lvl_up_move.id; break; }; const prev_move_r = RelativeMove.from(pokemon, prev_move); if (!this_move_r.lessThan(prev_move_r)) { // We found a move that is better what the PokΓ©mon already have! move.* = lvl_up_move.id; break; } } } } fn fillWithRandomMoves(random: rand.Random, all_moves: Moves, moves: *MemberMoves) void { const has_null_move = all_moves.get(0) != null; for (moves.values()) |*move, i| { // We need to have more moves in the game than the party member can have, // otherwise, we cannot pick only unique moves. Also, move `0` is the // `null` move, so we don't count that as a move we can pick from. if (all_moves.count() - @boolToInt(has_null_move) <= i) { move.* = 0; continue; } // Loop until we have picked a move that the party member does not already // have. move.* = while (true) { const pick = util.random.item(random, all_moves.keys()).?.*; if (pick != 0 and !hasMove(moves.values()[0..i], pick)) break pick; } else unreachable; } } fn fillWithRandomLevelUpMoves( random: rand.Random, lvl_up_moves: LvlUpMoves, moves: *MemberMoves, ) void { for (moves.values()) |*move, i| { // We need to have more moves in the learnset than the party member can have, // otherwise, we cannot pick only unique moves. // TODO: This code does no take into account that `lvl_up_moves` can contain // duplicates or moves with `id == null`. We need to do a count of // "valid moves" from the learnset and do this check against that // instead. if (lvl_up_moves.count() <= i) { move.* = 0; continue; } // Loop until we have picked a move that the party member does not already // have. move.* = while (true) { const pick = util.random.item(random, lvl_up_moves.values()).?.id; if (pick != 0 and !hasMove(moves.values()[0..i], pick)) break pick; } else unreachable; } } const Themes = struct { type: u16, ability: u16, }; fn randomizePartyMember( program: *Program, themes: Themes, trainer: Trainer, member: *PartyMember, ) !void { const allocator = program.allocator; const species = member.species orelse return; const level = member.level orelse trainer.partyAverageLevel(); const ability_index = member.ability orelse 0; const type_set = switch (program.options.types) { .same => blk: { const pokemon = program.pokemons.get(species) orelse break :blk program.species; if (pokemon.types.count() == 0) break :blk program.species; const t = util.random.item(program.random, pokemon.types.keys()).?.*; break :blk program.species_by_type.get(t).?; }, .themed => program.species_by_type.get(themes.type).?, .random => program.species, }; var new_ability: ?u16 = null; const ability_set = switch (program.options.abilities) { .same => blk: { const pokemon = program.pokemons.get(species) orelse break :blk program.species; const ability = pokemon.abilities.get(ability_index) orelse break :blk program.species; if (ability == 0) break :blk program.species; new_ability = ability; break :blk program.species_by_ability.get(ability).?; }, .themed => blk: { new_ability = themes.ability; break :blk program.species_by_ability.get(themes.ability).?; }, .random => program.species, }; if (program.options.abilities != .random and program.options.types != .random) { // The intersection between the type_set and ability_set will give // us all pokΓ©mons that have a certain type+ability pair. This is // the set we will pick from. var intersection = program.intersection.promote(allocator); intersection.clearRetainingCapacity(); try util.set.intersectInline(&intersection, ability_set, type_set); program.intersection = intersection.unmanaged; } // Pick the first set that has items in it. const pick_from = if (program.intersection.count() != 0) program.intersection else if (program.options.abilities != .random and ability_set.count() != 0) ability_set else if (program.options.types != .random and type_set.count() != 0) type_set else program.species; // When we have picked a new species for our PokΓ©mon we also need // to fix the ability the PokΓ©mon have, if we're picking PokΓ©mons // based on ability. defer if (member.species) |new_species| done: { const ability_to_find = new_ability orelse break :done; const pokemon = program.pokemons.get(new_species) orelse break :done; // Find the index of the ability we want the party member to // have. If we don't find the ability. The best we can do is // just let the PokΓ©mon keep the ability it already has. if (findAbility(pokemon.abilities.iterator(), ability_to_find)) |entry| member.ability = entry.key_ptr.*; }; switch (program.options.stats) { .follow_level => { member.species = try randomSpeciesWithSimularTotalStats( program, pick_from, levelScaling(program.stats.min, program.stats.max, level), ); return; }, .simular => if (program.pokemons.get(species)) |pokemon| { member.species = try randomSpeciesWithSimularTotalStats( program, pick_from, pokemon.total_stats, ); return; } else {}, .random => {}, } // If the above switch didn't return, the best we can do is just pick a // random PokΓ©mon from the pick_from set member.species = util.random.item(program.random, pick_from.keys()).?.*; } fn randomSpeciesWithSimularTotalStats(program: *Program, pick_from: Set, total_stats: u16) !u16 { const allocator = program.allocator; var min = @intCast(isize, total_stats); var max = min; program.simular.shrinkRetainingCapacity(0); while (program.simular.items.len < 25) : ({ min -= 5; max += 5; }) { for (pick_from.keys()) |s| { const p = program.pokemons.get(s).?; const total = @intCast(isize, p.total_stats); if (min <= total and total <= max) try program.simular.append(allocator, s); } } return util.random.item(program.random, program.simular.items).?.*; } fn levelScaling(min: u16, max: u16, level: u16) u16 { const fmin = @intToFloat(f64, min); const fmax = @intToFloat(f64, max); const diff = fmax - fmin; const x = @intToFloat(f64, level); // Function adapted from -0.0001 * x^2 + 0.02 * x // This functions grows fast at the start, getting 75% // to max stats at level 50. const a = -0.0001 * diff; const b = 0.02 * diff; const xp2 = math.pow(f64, x, 2); const res = a * xp2 + b * x + fmin; return @floatToInt(u16, res); } fn hasMove(moves: []const u16, id: u16) bool { return it.anyEx(moves, id, struct { fn f(m: u16, e: u16) bool { return m == e; } }.f); } fn findAbility(abilities: Abilities.Iterator, ability: u16) ?Abilities.Entry { return it.findEx(abilities, ability, struct { fn f(m: u16, e: Abilities.Entry) bool { return m == e.value_ptr.*; } }.f); } fn MinMax(comptime T: type) type { return struct { min: T, max: T }; } const Abilities = std.AutoArrayHashMapUnmanaged(u8, u16); const LvlUpMoves = std.AutoArrayHashMapUnmanaged(u16, LvlUpMove); const MemberMoves = std.AutoArrayHashMapUnmanaged(u8, u16); const Moves = std.AutoArrayHashMapUnmanaged(u16, Move); const Party = std.AutoArrayHashMapUnmanaged(u8, PartyMember); const Pokemons = std.AutoArrayHashMapUnmanaged(u16, Pokemon); const Set = std.AutoArrayHashMapUnmanaged(u16, void); const SpeciesBy = std.AutoArrayHashMapUnmanaged(u16, Set); const Trainers = std.AutoArrayHashMapUnmanaged(u16, Trainer); fn pokedexPokemons( allocator: mem.Allocator, pokedex: Set, pokemons: Pokemons, excluded_pokemons: []const []const u8, ) !Set { var res = Set{}; errdefer res.deinit(allocator); outer: for (pokemons.values()) |pokemon, i| { const species = pokemons.keys()[i]; if (pokemon.catch_rate == 0) continue; if (pokedex.get(pokemon.pokedex_entry) == null) continue; for (excluded_pokemons) |glob| { if (util.glob.match(glob, pokemon.name)) continue :outer; } _ = try res.put(allocator, species, {}); } return res; } fn minMaxStats(pokemons: Pokemons, species: Set) MinMax(u16) { var res = MinMax(u16){ .min = math.maxInt(u16), .max = 0, }; for (species.keys()) |s| { const pokemon = pokemons.get(s).?; res.min = math.min(res.min, pokemon.total_stats); res.max = math.max(res.max, pokemon.total_stats); } return res; } fn speciesByType(allocator: mem.Allocator, pokemons: Pokemons, species: Set) !SpeciesBy { var res = SpeciesBy{}; errdefer { for (res.values()) |*set| set.deinit(allocator); res.deinit(allocator); } for (species.keys()) |s| { const pokemon = pokemons.get(s).?; for (pokemon.types.keys()) |t| { const set = (try res.getOrPutValue(allocator, t, .{})).value_ptr; _ = try set.put(allocator, s, {}); } } return res; } fn speciesByAbility(allocator: mem.Allocator, pokemons: Pokemons, species: Set) !SpeciesBy { var res = SpeciesBy{}; errdefer { for (res.values()) |*set| set.deinit(allocator); res.deinit(allocator); } for (species.keys()) |s| { const pokemon = pokemons.get(s).?; for (pokemon.abilities.values()) |ability| { if (ability == 0) continue; const set = (try res.getOrPutValue(allocator, ability, .{})).value_ptr; _ = try set.put(allocator, s, {}); } } return res; } const Trainer = struct { party_size: u8 = 0, party_type: format.PartyType = .none, party: Party = Party{}, fn partyAverageLevel(trainer: Trainer) u8 { var count: u16 = 0; var sum: u16 = 0; for (trainer.party.values()) |member| { sum += member.level orelse 0; count += @boolToInt(member.level != null); } if (count == 0) return 2; return @intCast(u8, sum / count); } }; const PartyMember = struct { species: ?u16 = null, item: ?u16 = null, level: ?u8 = null, ability: ?u8 = null, moves: MemberMoves = MemberMoves{}, }; const LvlUpMove = struct { level: u16 = 0, id: u16 = 0, }; const Move = struct { power: u8 = 0, accuracy: u8 = 0, pp: u8 = 0, type: u16 = math.maxInt(u16), }; // Represents a moves power in relation to the pokemon who uses it const RelativeMove = struct { power: u16, accuracy: u8, pp: u8, fn from(p: Pokemon, m: Move) RelativeMove { const is_stab = p.types.get(m.type) != null; return RelativeMove{ .power = @as(u16, m.power) + (m.power / 2) * @boolToInt(is_stab), .accuracy = m.accuracy, .pp = m.pp, }; } fn lessThan(a: RelativeMove, b: RelativeMove) bool { if (a.power < b.power) return true; if (a.power > b.power) return false; if (a.accuracy < b.accuracy) return true; if (a.accuracy > b.accuracy) return false; return a.pp < b.pp; } }; const Pokemon = struct { stats: [6]u8 = [_]u8{0} ** 6, total_stats: u16 = 0, types: Set = Set{}, abilities: Abilities = Abilities{}, lvl_up_moves: LvlUpMoves = LvlUpMoves{}, catch_rate: usize = 1, pokedex_entry: u16 = math.maxInt(u16), name: []u8 = "", }; test "tm35-rand-parties" { const H = struct { fn pokemon( comptime id: []const u8, comptime stat: []const u8, comptime types: []const u8, comptime ability: []const u8, comptime move_: []const u8, comptime catch_rate: []const u8, comptime name: []const u8, ) []const u8 { return ".pokedex[" ++ id ++ "].height=0\n" ++ ".pokemons[" ++ id ++ "].pokedex_entry=" ++ id ++ "\n" ++ ".pokemons[" ++ id ++ "].stats.hp=" ++ stat ++ "\n" ++ ".pokemons[" ++ id ++ "].stats.attack=" ++ stat ++ "\n" ++ ".pokemons[" ++ id ++ "].stats.defense=" ++ stat ++ "\n" ++ ".pokemons[" ++ id ++ "].stats.speed=" ++ stat ++ "\n" ++ ".pokemons[" ++ id ++ "].stats.sp_attack=" ++ stat ++ "\n" ++ ".pokemons[" ++ id ++ "].stats.sp_defense=" ++ stat ++ "\n" ++ ".pokemons[" ++ id ++ "].types[0]=" ++ types ++ "\n" ++ ".pokemons[" ++ id ++ "].types[1]=" ++ types ++ "\n" ++ ".pokemons[" ++ id ++ "].abilities[0]=" ++ ability ++ "\n" ++ ".pokemons[" ++ id ++ "].moves[0].id=" ++ move_ ++ "\n" ++ ".pokemons[" ++ id ++ "].moves[0].level=0\n" ++ ".pokemons[" ++ id ++ "].catch_rate=" ++ catch_rate ++ "\n" ++ ".pokemons[" ++ id ++ "].name=" ++ name ++ "\n"; } fn trainer( comptime id: []const u8, comptime species: []const u8, comptime item_: ?[]const u8, comptime move_: ?[]const u8, ) []const u8 { const prefix = ".trainers[" ++ id ++ "]"; const _type: []const u8 = if (move_ != null and item_ != null) "both" // else if (move_) |_| "moves" // else if (item_) |_| "item" // else "none"; return prefix ++ ".party_size=2\n" ++ prefix ++ ".party_type=" ++ _type ++ "\n" ++ prefix ++ ".party[0].species=" ++ species ++ "\n" ++ prefix ++ ".party[0].level=5\n" ++ prefix ++ ".party[0].ability=0\n" ++ (if (item_) |i| prefix ++ ".party[0].item=" ++ i ++ "\n" else "") ++ (if (move_) |m| prefix ++ ".party[0].moves[0]=" ++ m ++ "\n" else "") ++ prefix ++ ".party[1].species=" ++ species ++ "\n" ++ prefix ++ ".party[1].level=5\n" ++ prefix ++ ".party[1].ability=0\n" ++ (if (item_) |i| prefix ++ ".party[1].item=" ++ i ++ "\n" else "") ++ (if (move_) |m| prefix ++ ".party[1].moves[0]=" ++ m ++ "\n" else ""); } fn move( comptime id: []const u8, comptime power: []const u8, comptime type_: []const u8, comptime pp: []const u8, comptime accuracy: []const u8, ) []const u8 { return ".moves[" ++ id ++ "].power=" ++ power ++ "\n" ++ ".moves[" ++ id ++ "].type=" ++ type_ ++ "\n" ++ ".moves[" ++ id ++ "].pp=" ++ pp ++ "\n" ++ ".moves[" ++ id ++ "].accuracy=" ++ accuracy ++ "\n"; } fn item( comptime id: []const u8, comptime effect: []const u8, ) []const u8 { return ".items[" ++ id ++ "].battle_effect=" ++ effect ++ "\n"; } }; const result_prefix = comptime H.pokemon("0", "10", "0", "0", "1", "1", "pokemon 0") ++ H.pokemon("1", "15", "16", "1", "2", "1", "pokemon 1") ++ H.pokemon("2", "20", "2", "2", "3", "1", "pokemon 2") ++ H.pokemon("3", "25", "12", "3", "4", "1", "pokemon 3") ++ H.pokemon("4", "30", "10", "1", "5", "1", "pokemon 4") ++ H.pokemon("5", "35", "11", "2", "6", "1", "pokemon 5") ++ H.pokemon("6", "40", "5", "3", "7", "1", "pokemon 6") ++ H.pokemon("7", "45", "4", "1", "8", "1", "pokemon 7") ++ H.pokemon("8", "45", "4", "2", "8", "0", "pokemon 8") ++ H.move("0", "0", "0", "0", "0") ++ H.move("1", "10", "0", "10", "255") ++ H.move("2", "10", "16", "10", "255") ++ H.move("3", "10", "2", "10", "255") ++ H.move("4", "10", "12", "10", "255") ++ H.move("5", "10", "10", "10", "255") ++ H.move("6", "10", "11", "10", "255") ++ H.move("7", "10", "5", "10", "255") ++ H.move("8", "10", "4", "10", "255") ++ H.item("0", "0") ++ H.item("1", "1") ++ H.item("2", "2") ++ H.item("3", "3") ++ H.item("4", "4"); const test_string = comptime result_prefix ++ H.trainer("0", "0", null, "1") ++ H.trainer("1", "1", "1", "2") ++ H.trainer("2", "2", null, "3") ++ H.trainer("3", "3", null, "4"); try util.testing.testProgram(Program, &[_][]const u8{ "--seed=0", }, test_string, result_prefix ++ \\.trainers[0].party_size=2 \\.trainers[0].party_type=none \\.trainers[0].party[0].species=2 \\.trainers[0].party[0].level=5 \\.trainers[0].party[0].ability=0 \\.trainers[0].party[0].moves[0]=1 \\.trainers[0].party[1].species=3 \\.trainers[0].party[1].level=5 \\.trainers[0].party[1].ability=0 \\.trainers[0].party[1].moves[0]=1 \\.trainers[1].party_size=2 \\.trainers[1].party_type=none \\.trainers[1].party[0].species=2 \\.trainers[1].party[0].level=5 \\.trainers[1].party[0].ability=0 \\.trainers[1].party[0].moves[0]=2 \\.trainers[1].party[1].species=0 \\.trainers[1].party[1].level=5 \\.trainers[1].party[1].ability=0 \\.trainers[1].party[1].moves[0]=2 \\.trainers[2].party_size=2 \\.trainers[2].party_type=none \\.trainers[2].party[0].species=3 \\.trainers[2].party[0].level=5 \\.trainers[2].party[0].ability=0 \\.trainers[2].party[0].moves[0]=3 \\.trainers[2].party[1].species=0 \\.trainers[2].party[1].level=5 \\.trainers[2].party[1].ability=0 \\.trainers[2].party[1].moves[0]=3 \\.trainers[3].party_size=2 \\.trainers[3].party_type=none \\.trainers[3].party[0].species=6 \\.trainers[3].party[0].level=5 \\.trainers[3].party[0].ability=0 \\.trainers[3].party[0].moves[0]=4 \\.trainers[3].party[1].species=6 \\.trainers[3].party[1].level=5 \\.trainers[3].party[1].ability=0 \\.trainers[3].party[1].moves[0]=4 \\ ); try util.testing.testProgram(Program, &[_][]const u8{ "--seed=0", "--party-size-min=3", }, test_string, result_prefix ++ \\.trainers[0].party_size=3 \\.trainers[0].party_type=none \\.trainers[0].party[0].species=2 \\.trainers[0].party[0].level=5 \\.trainers[0].party[0].ability=0 \\.trainers[0].party[0].moves[0]=1 \\.trainers[0].party[1].species=3 \\.trainers[0].party[1].level=5 \\.trainers[0].party[1].ability=0 \\.trainers[0].party[1].moves[0]=1 \\.trainers[0].party[2].species=2 \\.trainers[0].party[2].level=5 \\.trainers[0].party[2].moves[0]=1 \\.trainers[1].party_size=3 \\.trainers[1].party_type=none \\.trainers[1].party[0].species=0 \\.trainers[1].party[0].level=5 \\.trainers[1].party[0].ability=0 \\.trainers[1].party[0].moves[0]=2 \\.trainers[1].party[1].species=3 \\.trainers[1].party[1].level=5 \\.trainers[1].party[1].ability=0 \\.trainers[1].party[1].moves[0]=2 \\.trainers[1].party[2].species=0 \\.trainers[1].party[2].level=5 \\.trainers[1].party[2].moves[0]=2 \\.trainers[2].party_size=3 \\.trainers[2].party_type=none \\.trainers[2].party[0].species=6 \\.trainers[2].party[0].level=5 \\.trainers[2].party[0].ability=0 \\.trainers[2].party[0].moves[0]=3 \\.trainers[2].party[1].species=6 \\.trainers[2].party[1].level=5 \\.trainers[2].party[1].ability=0 \\.trainers[2].party[1].moves[0]=3 \\.trainers[2].party[2].species=2 \\.trainers[2].party[2].level=5 \\.trainers[2].party[2].moves[0]=3 \\.trainers[3].party_size=3 \\.trainers[3].party_type=none \\.trainers[3].party[0].species=0 \\.trainers[3].party[0].level=5 \\.trainers[3].party[0].ability=0 \\.trainers[3].party[0].moves[0]=4 \\.trainers[3].party[1].species=2 \\.trainers[3].party[1].level=5 \\.trainers[3].party[1].ability=0 \\.trainers[3].party[1].moves[0]=4 \\.trainers[3].party[2].species=0 \\.trainers[3].party[2].level=5 \\.trainers[3].party[2].moves[0]=4 \\ ); try util.testing.testProgram(Program, &[_][]const u8{ "--seed=0", "--party-size-max=1", }, test_string, result_prefix ++ \\.trainers[0].party_size=1 \\.trainers[0].party_type=none \\.trainers[0].party[0].species=2 \\.trainers[0].party[0].level=5 \\.trainers[0].party[0].ability=0 \\.trainers[0].party[0].moves[0]=1 \\.trainers[0].party[1].species=0 \\.trainers[0].party[1].level=5 \\.trainers[0].party[1].ability=0 \\.trainers[0].party[1].moves[0]=1 \\.trainers[1].party_size=1 \\.trainers[1].party_type=none \\.trainers[1].party[0].species=3 \\.trainers[1].party[0].level=5 \\.trainers[1].party[0].ability=0 \\.trainers[1].party[0].moves[0]=2 \\.trainers[1].party[1].species=1 \\.trainers[1].party[1].item=1 \\.trainers[1].party[1].level=5 \\.trainers[1].party[1].ability=0 \\.trainers[1].party[1].moves[0]=2 \\.trainers[2].party_size=1 \\.trainers[2].party_type=none \\.trainers[2].party[0].species=2 \\.trainers[2].party[0].level=5 \\.trainers[2].party[0].ability=0 \\.trainers[2].party[0].moves[0]=3 \\.trainers[2].party[1].species=2 \\.trainers[2].party[1].level=5 \\.trainers[2].party[1].ability=0 \\.trainers[2].party[1].moves[0]=3 \\.trainers[3].party_size=1 \\.trainers[3].party_type=none \\.trainers[3].party[0].species=0 \\.trainers[3].party[0].level=5 \\.trainers[3].party[0].ability=0 \\.trainers[3].party[0].moves[0]=4 \\.trainers[3].party[1].species=3 \\.trainers[3].party[1].level=5 \\.trainers[3].party[1].ability=0 \\.trainers[3].party[1].moves[0]=4 \\ ); try util.testing.testProgram(Program, &[_][]const u8{ "--seed=0", "--party-size=minimum", }, test_string, result_prefix ++ \\.trainers[0].party_size=1 \\.trainers[0].party_type=none \\.trainers[0].party[0].species=2 \\.trainers[0].party[0].level=5 \\.trainers[0].party[0].ability=0 \\.trainers[0].party[0].moves[0]=1 \\.trainers[0].party[1].species=0 \\.trainers[0].party[1].level=5 \\.trainers[0].party[1].ability=0 \\.trainers[0].party[1].moves[0]=1 \\.trainers[1].party_size=1 \\.trainers[1].party_type=none \\.trainers[1].party[0].species=3 \\.trainers[1].party[0].level=5 \\.trainers[1].party[0].ability=0 \\.trainers[1].party[0].moves[0]=2 \\.trainers[1].party[1].species=1 \\.trainers[1].party[1].item=1 \\.trainers[1].party[1].level=5 \\.trainers[1].party[1].ability=0 \\.trainers[1].party[1].moves[0]=2 \\.trainers[2].party_size=1 \\.trainers[2].party_type=none \\.trainers[2].party[0].species=2 \\.trainers[2].party[0].level=5 \\.trainers[2].party[0].ability=0 \\.trainers[2].party[0].moves[0]=3 \\.trainers[2].party[1].species=2 \\.trainers[2].party[1].level=5 \\.trainers[2].party[1].ability=0 \\.trainers[2].party[1].moves[0]=3 \\.trainers[3].party_size=1 \\.trainers[3].party_type=none \\.trainers[3].party[0].species=0 \\.trainers[3].party[0].level=5 \\.trainers[3].party[0].ability=0 \\.trainers[3].party[0].moves[0]=4 \\.trainers[3].party[1].species=3 \\.trainers[3].party[1].level=5 \\.trainers[3].party[1].ability=0 \\.trainers[3].party[1].moves[0]=4 \\ ); try util.testing.testProgram(Program, &[_][]const u8{ "--seed=0", "--party-size=random", }, test_string, result_prefix ++ \\.trainers[0].party_size=2 \\.trainers[0].party_type=none \\.trainers[0].party[0].species=3 \\.trainers[0].party[0].level=5 \\.trainers[0].party[0].ability=0 \\.trainers[0].party[0].moves[0]=1 \\.trainers[0].party[1].species=2 \\.trainers[0].party[1].level=5 \\.trainers[0].party[1].ability=0 \\.trainers[0].party[1].moves[0]=1 \\.trainers[1].party_size=2 \\.trainers[1].party_type=none \\.trainers[1].party[0].species=3 \\.trainers[1].party[0].level=5 \\.trainers[1].party[0].ability=0 \\.trainers[1].party[0].moves[0]=2 \\.trainers[1].party[1].species=0 \\.trainers[1].party[1].level=5 \\.trainers[1].party[1].ability=0 \\.trainers[1].party[1].moves[0]=2 \\.trainers[2].party_size=3 \\.trainers[2].party_type=none \\.trainers[2].party[0].species=6 \\.trainers[2].party[0].level=5 \\.trainers[2].party[0].ability=0 \\.trainers[2].party[0].moves[0]=3 \\.trainers[2].party[1].species=2 \\.trainers[2].party[1].level=5 \\.trainers[2].party[1].ability=0 \\.trainers[2].party[1].moves[0]=3 \\.trainers[2].party[2].species=0 \\.trainers[2].party[2].level=5 \\.trainers[2].party[2].moves[0]=3 \\.trainers[3].party_size=1 \\.trainers[3].party_type=none \\.trainers[3].party[0].species=0 \\.trainers[3].party[0].level=5 \\.trainers[3].party[0].ability=0 \\.trainers[3].party[0].moves[0]=4 \\.trainers[3].party[1].species=3 \\.trainers[3].party[1].level=5 \\.trainers[3].party[1].ability=0 \\.trainers[3].party[1].moves[0]=4 \\ ); try util.testing.testProgram(Program, &[_][]const u8{ "--seed=0", "--items=unchanged", }, test_string, result_prefix ++ \\.trainers[0].party_size=2 \\.trainers[0].party_type=none \\.trainers[0].party[0].species=2 \\.trainers[0].party[0].level=5 \\.trainers[0].party[0].ability=0 \\.trainers[0].party[0].moves[0]=1 \\.trainers[0].party[1].species=3 \\.trainers[0].party[1].level=5 \\.trainers[0].party[1].ability=0 \\.trainers[0].party[1].moves[0]=1 \\.trainers[1].party_size=2 \\.trainers[1].party_type=item \\.trainers[1].party[0].species=2 \\.trainers[1].party[0].item=1 \\.trainers[1].party[0].level=5 \\.trainers[1].party[0].ability=0 \\.trainers[1].party[0].moves[0]=2 \\.trainers[1].party[1].species=0 \\.trainers[1].party[1].item=1 \\.trainers[1].party[1].level=5 \\.trainers[1].party[1].ability=0 \\.trainers[1].party[1].moves[0]=2 \\.trainers[2].party_size=2 \\.trainers[2].party_type=none \\.trainers[2].party[0].species=3 \\.trainers[2].party[0].level=5 \\.trainers[2].party[0].ability=0 \\.trainers[2].party[0].moves[0]=3 \\.trainers[2].party[1].species=0 \\.trainers[2].party[1].level=5 \\.trainers[2].party[1].ability=0 \\.trainers[2].party[1].moves[0]=3 \\.trainers[3].party_size=2 \\.trainers[3].party_type=none \\.trainers[3].party[0].species=6 \\.trainers[3].party[0].level=5 \\.trainers[3].party[0].ability=0 \\.trainers[3].party[0].moves[0]=4 \\.trainers[3].party[1].species=6 \\.trainers[3].party[1].level=5 \\.trainers[3].party[1].ability=0 \\.trainers[3].party[1].moves[0]=4 \\ ); try util.testing.testProgram(Program, &[_][]const u8{ "--seed=0", "--items=random", }, test_string, result_prefix ++ \\.trainers[0].party_size=2 \\.trainers[0].party_type=item \\.trainers[0].party[0].species=2 \\.trainers[0].party[0].item=2 \\.trainers[0].party[0].level=5 \\.trainers[0].party[0].ability=0 \\.trainers[0].party[0].moves[0]=1 \\.trainers[0].party[1].species=2 \\.trainers[0].party[1].item=1 \\.trainers[0].party[1].level=5 \\.trainers[0].party[1].ability=0 \\.trainers[0].party[1].moves[0]=1 \\.trainers[1].party_size=2 \\.trainers[1].party_type=item \\.trainers[1].party[0].species=3 \\.trainers[1].party[0].item=1 \\.trainers[1].party[0].level=5 \\.trainers[1].party[0].ability=0 \\.trainers[1].party[0].moves[0]=2 \\.trainers[1].party[1].species=6 \\.trainers[1].party[1].item=4 \\.trainers[1].party[1].level=5 \\.trainers[1].party[1].ability=0 \\.trainers[1].party[1].moves[0]=2 \\.trainers[2].party_size=2 \\.trainers[2].party_type=item \\.trainers[2].party[0].species=2 \\.trainers[2].party[0].item=1 \\.trainers[2].party[0].level=5 \\.trainers[2].party[0].ability=0 \\.trainers[2].party[0].moves[0]=3 \\.trainers[2].party[1].species=2 \\.trainers[2].party[1].item=1 \\.trainers[2].party[1].level=5 \\.trainers[2].party[1].ability=0 \\.trainers[2].party[1].moves[0]=3 \\.trainers[3].party_size=2 \\.trainers[3].party_type=item \\.trainers[3].party[0].species=0 \\.trainers[3].party[0].item=1 \\.trainers[3].party[0].level=5 \\.trainers[3].party[0].ability=0 \\.trainers[3].party[0].moves[0]=4 \\.trainers[3].party[1].species=0 \\.trainers[3].party[1].item=2 \\.trainers[3].party[1].level=5 \\.trainers[3].party[1].ability=0 \\.trainers[3].party[1].moves[0]=4 \\ ); try util.testing.testProgram(Program, &[_][]const u8{ "--seed=0", "--moves=unchanged", }, test_string, result_prefix ++ \\.trainers[0].party_size=2 \\.trainers[0].party_type=moves \\.trainers[0].party[0].species=2 \\.trainers[0].party[0].level=5 \\.trainers[0].party[0].ability=0 \\.trainers[0].party[0].moves[0]=1 \\.trainers[0].party[1].species=3 \\.trainers[0].party[1].level=5 \\.trainers[0].party[1].ability=0 \\.trainers[0].party[1].moves[0]=1 \\.trainers[1].party_size=2 \\.trainers[1].party_type=moves \\.trainers[1].party[0].species=2 \\.trainers[1].party[0].level=5 \\.trainers[1].party[0].ability=0 \\.trainers[1].party[0].moves[0]=2 \\.trainers[1].party[1].species=0 \\.trainers[1].party[1].level=5 \\.trainers[1].party[1].ability=0 \\.trainers[1].party[1].moves[0]=2 \\.trainers[2].party_size=2 \\.trainers[2].party_type=moves \\.trainers[2].party[0].species=3 \\.trainers[2].party[0].level=5 \\.trainers[2].party[0].ability=0 \\.trainers[2].party[0].moves[0]=3 \\.trainers[2].party[1].species=0 \\.trainers[2].party[1].level=5 \\.trainers[2].party[1].ability=0 \\.trainers[2].party[1].moves[0]=3 \\.trainers[3].party_size=2 \\.trainers[3].party_type=moves \\.trainers[3].party[0].species=6 \\.trainers[3].party[0].level=5 \\.trainers[3].party[0].ability=0 \\.trainers[3].party[0].moves[0]=4 \\.trainers[3].party[1].species=6 \\.trainers[3].party[1].level=5 \\.trainers[3].party[1].ability=0 \\.trainers[3].party[1].moves[0]=4 \\ ); const moves_result = \\.trainers[0].party_size=2 \\.trainers[0].party_type=moves \\.trainers[0].party[0].species=2 \\.trainers[0].party[0].level=5 \\.trainers[0].party[0].ability=0 \\.trainers[0].party[0].moves[0]=3 \\.trainers[0].party[1].species=3 \\.trainers[0].party[1].level=5 \\.trainers[0].party[1].ability=0 \\.trainers[0].party[1].moves[0]=4 \\.trainers[1].party_size=2 \\.trainers[1].party_type=moves \\.trainers[1].party[0].species=2 \\.trainers[1].party[0].level=5 \\.trainers[1].party[0].ability=0 \\.trainers[1].party[0].moves[0]=3 \\.trainers[1].party[1].species=0 \\.trainers[1].party[1].level=5 \\.trainers[1].party[1].ability=0 \\.trainers[1].party[1].moves[0]=1 \\.trainers[2].party_size=2 \\.trainers[2].party_type=moves \\.trainers[2].party[0].species=3 \\.trainers[2].party[0].level=5 \\.trainers[2].party[0].ability=0 \\.trainers[2].party[0].moves[0]=4 \\.trainers[2].party[1].species=0 \\.trainers[2].party[1].level=5 \\.trainers[2].party[1].ability=0 \\.trainers[2].party[1].moves[0]=1 \\.trainers[3].party_size=2 \\.trainers[3].party_type=moves \\.trainers[3].party[0].species=6 \\.trainers[3].party[0].level=5 \\.trainers[3].party[0].ability=0 \\.trainers[3].party[0].moves[0]=7 \\.trainers[3].party[1].species=6 \\.trainers[3].party[1].level=5 \\.trainers[3].party[1].ability=0 \\.trainers[3].party[1].moves[0]=7 \\ ; try util.testing.testProgram(Program, &[_][]const u8{ "--seed=0", "--moves=best", }, test_string, result_prefix ++ moves_result); try util.testing.testProgram(Program, &[_][]const u8{ "--seed=0", "--moves=best_for_level", }, test_string, result_prefix ++ moves_result); try util.testing.testProgram(Program, &[_][]const u8{ "--seed=0", "--moves=random_learnable", }, test_string, result_prefix ++ \\.trainers[0].party_size=2 \\.trainers[0].party_type=moves \\.trainers[0].party[0].species=2 \\.trainers[0].party[0].level=5 \\.trainers[0].party[0].ability=0 \\.trainers[0].party[0].moves[0]=3 \\.trainers[0].party[1].species=2 \\.trainers[0].party[1].level=5 \\.trainers[0].party[1].ability=0 \\.trainers[0].party[1].moves[0]=3 \\.trainers[1].party_size=2 \\.trainers[1].party_type=moves \\.trainers[1].party[0].species=3 \\.trainers[1].party[0].level=5 \\.trainers[1].party[0].ability=0 \\.trainers[1].party[0].moves[0]=4 \\.trainers[1].party[1].species=6 \\.trainers[1].party[1].level=5 \\.trainers[1].party[1].ability=0 \\.trainers[1].party[1].moves[0]=7 \\.trainers[2].party_size=2 \\.trainers[2].party_type=moves \\.trainers[2].party[0].species=2 \\.trainers[2].party[0].level=5 \\.trainers[2].party[0].ability=0 \\.trainers[2].party[0].moves[0]=3 \\.trainers[2].party[1].species=2 \\.trainers[2].party[1].level=5 \\.trainers[2].party[1].ability=0 \\.trainers[2].party[1].moves[0]=3 \\.trainers[3].party_size=2 \\.trainers[3].party_type=moves \\.trainers[3].party[0].species=0 \\.trainers[3].party[0].level=5 \\.trainers[3].party[0].ability=0 \\.trainers[3].party[0].moves[0]=1 \\.trainers[3].party[1].species=0 \\.trainers[3].party[1].level=5 \\.trainers[3].party[1].ability=0 \\.trainers[3].party[1].moves[0]=1 \\ ); try util.testing.testProgram(Program, &[_][]const u8{ "--seed=0", "--moves=random", }, test_string, result_prefix ++ \\.trainers[0].party_size=2 \\.trainers[0].party_type=moves \\.trainers[0].party[0].species=2 \\.trainers[0].party[0].level=5 \\.trainers[0].party[0].ability=0 \\.trainers[0].party[0].moves[0]=3 \\.trainers[0].party[1].species=2 \\.trainers[0].party[1].level=5 \\.trainers[0].party[1].ability=0 \\.trainers[0].party[1].moves[0]=4 \\.trainers[1].party_size=2 \\.trainers[1].party_type=moves \\.trainers[1].party[0].species=0 \\.trainers[1].party[0].level=5 \\.trainers[1].party[0].ability=0 \\.trainers[1].party[0].moves[0]=7 \\.trainers[1].party[1].species=6 \\.trainers[1].party[1].level=5 \\.trainers[1].party[1].ability=0 \\.trainers[1].party[1].moves[0]=2 \\.trainers[2].party_size=2 \\.trainers[2].party_type=moves \\.trainers[2].party[0].species=0 \\.trainers[2].party[0].level=5 \\.trainers[2].party[0].ability=0 \\.trainers[2].party[0].moves[0]=2 \\.trainers[2].party[1].species=0 \\.trainers[2].party[1].level=5 \\.trainers[2].party[1].ability=0 \\.trainers[2].party[1].moves[0]=3 \\.trainers[3].party_size=2 \\.trainers[3].party_type=moves \\.trainers[3].party[0].species=5 \\.trainers[3].party[0].level=5 \\.trainers[3].party[0].ability=0 \\.trainers[3].party[0].moves[0]=1 \\.trainers[3].party[1].species=2 \\.trainers[3].party[1].level=5 \\.trainers[3].party[1].ability=0 \\.trainers[3].party[1].moves[0]=3 \\ ); try util.testing.testProgram(Program, &[_][]const u8{ "--seed=0", "--types=same", }, test_string, result_prefix ++ \\.trainers[0].party_size=2 \\.trainers[0].party_type=none \\.trainers[0].party[0].species=0 \\.trainers[0].party[0].level=5 \\.trainers[0].party[0].ability=0 \\.trainers[0].party[0].moves[0]=1 \\.trainers[0].party[1].species=0 \\.trainers[0].party[1].level=5 \\.trainers[0].party[1].ability=0 \\.trainers[0].party[1].moves[0]=1 \\.trainers[1].party_size=2 \\.trainers[1].party_type=none \\.trainers[1].party[0].species=1 \\.trainers[1].party[0].level=5 \\.trainers[1].party[0].ability=0 \\.trainers[1].party[0].moves[0]=2 \\.trainers[1].party[1].species=1 \\.trainers[1].party[1].level=5 \\.trainers[1].party[1].ability=0 \\.trainers[1].party[1].moves[0]=2 \\.trainers[2].party_size=2 \\.trainers[2].party_type=none \\.trainers[2].party[0].species=2 \\.trainers[2].party[0].level=5 \\.trainers[2].party[0].ability=0 \\.trainers[2].party[0].moves[0]=3 \\.trainers[2].party[1].species=2 \\.trainers[2].party[1].level=5 \\.trainers[2].party[1].ability=0 \\.trainers[2].party[1].moves[0]=3 \\.trainers[3].party_size=2 \\.trainers[3].party_type=none \\.trainers[3].party[0].species=3 \\.trainers[3].party[0].level=5 \\.trainers[3].party[0].ability=0 \\.trainers[3].party[0].moves[0]=4 \\.trainers[3].party[1].species=3 \\.trainers[3].party[1].level=5 \\.trainers[3].party[1].ability=0 \\.trainers[3].party[1].moves[0]=4 \\ ); try util.testing.testProgram(Program, &[_][]const u8{ "--seed=0", "--types=themed", }, test_string, result_prefix ++ \\.trainers[0].party_size=2 \\.trainers[0].party_type=none \\.trainers[0].party[0].species=2 \\.trainers[0].party[0].level=5 \\.trainers[0].party[0].ability=0 \\.trainers[0].party[0].moves[0]=1 \\.trainers[0].party[1].species=2 \\.trainers[0].party[1].level=5 \\.trainers[0].party[1].ability=0 \\.trainers[0].party[1].moves[0]=1 \\.trainers[1].party_size=2 \\.trainers[1].party_type=none \\.trainers[1].party[0].species=0 \\.trainers[1].party[0].level=5 \\.trainers[1].party[0].ability=0 \\.trainers[1].party[0].moves[0]=2 \\.trainers[1].party[1].species=0 \\.trainers[1].party[1].level=5 \\.trainers[1].party[1].ability=0 \\.trainers[1].party[1].moves[0]=2 \\.trainers[2].party_size=2 \\.trainers[2].party_type=none \\.trainers[2].party[0].species=6 \\.trainers[2].party[0].level=5 \\.trainers[2].party[0].ability=0 \\.trainers[2].party[0].moves[0]=3 \\.trainers[2].party[1].species=6 \\.trainers[2].party[1].level=5 \\.trainers[2].party[1].ability=0 \\.trainers[2].party[1].moves[0]=3 \\.trainers[3].party_size=2 \\.trainers[3].party_type=none \\.trainers[3].party[0].species=0 \\.trainers[3].party[0].level=5 \\.trainers[3].party[0].ability=0 \\.trainers[3].party[0].moves[0]=4 \\.trainers[3].party[1].species=0 \\.trainers[3].party[1].level=5 \\.trainers[3].party[1].ability=0 \\.trainers[3].party[1].moves[0]=4 \\ ); try util.testing.testProgram(Program, &[_][]const u8{ "--seed=0", "--abilities=same", }, test_string, result_prefix ++ \\.trainers[0].party_size=2 \\.trainers[0].party_type=none \\.trainers[0].party[0].species=2 \\.trainers[0].party[0].level=5 \\.trainers[0].party[0].ability=0 \\.trainers[0].party[0].moves[0]=1 \\.trainers[0].party[1].species=3 \\.trainers[0].party[1].level=5 \\.trainers[0].party[1].ability=0 \\.trainers[0].party[1].moves[0]=1 \\.trainers[1].party_size=2 \\.trainers[1].party_type=none \\.trainers[1].party[0].species=4 \\.trainers[1].party[0].level=5 \\.trainers[1].party[0].ability=0 \\.trainers[1].party[0].moves[0]=2 \\.trainers[1].party[1].species=1 \\.trainers[1].party[1].level=5 \\.trainers[1].party[1].ability=0 \\.trainers[1].party[1].moves[0]=2 \\.trainers[2].party_size=2 \\.trainers[2].party_type=none \\.trainers[2].party[0].species=2 \\.trainers[2].party[0].level=5 \\.trainers[2].party[0].ability=0 \\.trainers[2].party[0].moves[0]=3 \\.trainers[2].party[1].species=2 \\.trainers[2].party[1].level=5 \\.trainers[2].party[1].ability=0 \\.trainers[2].party[1].moves[0]=3 \\.trainers[3].party_size=2 \\.trainers[3].party_type=none \\.trainers[3].party[0].species=6 \\.trainers[3].party[0].level=5 \\.trainers[3].party[0].ability=0 \\.trainers[3].party[0].moves[0]=4 \\.trainers[3].party[1].species=6 \\.trainers[3].party[1].level=5 \\.trainers[3].party[1].ability=0 \\.trainers[3].party[1].moves[0]=4 \\ ); try util.testing.testProgram(Program, &[_][]const u8{ "--seed=0", "--abilities=themed", }, test_string, result_prefix ++ \\.trainers[0].party_size=2 \\.trainers[0].party_type=none \\.trainers[0].party[0].species=4 \\.trainers[0].party[0].level=5 \\.trainers[0].party[0].ability=0 \\.trainers[0].party[0].moves[0]=1 \\.trainers[0].party[1].species=4 \\.trainers[0].party[1].level=5 \\.trainers[0].party[1].ability=0 \\.trainers[0].party[1].moves[0]=1 \\.trainers[1].party_size=2 \\.trainers[1].party_type=none \\.trainers[1].party[0].species=4 \\.trainers[1].party[0].level=5 \\.trainers[1].party[0].ability=0 \\.trainers[1].party[0].moves[0]=2 \\.trainers[1].party[1].species=1 \\.trainers[1].party[1].level=5 \\.trainers[1].party[1].ability=0 \\.trainers[1].party[1].moves[0]=2 \\.trainers[2].party_size=2 \\.trainers[2].party_type=none \\.trainers[2].party[0].species=6 \\.trainers[2].party[0].level=5 \\.trainers[2].party[0].ability=0 \\.trainers[2].party[0].moves[0]=3 \\.trainers[2].party[1].species=3 \\.trainers[2].party[1].level=5 \\.trainers[2].party[1].ability=0 \\.trainers[2].party[1].moves[0]=3 \\.trainers[3].party_size=2 \\.trainers[3].party_type=none \\.trainers[3].party[0].species=1 \\.trainers[3].party[0].level=5 \\.trainers[3].party[0].ability=0 \\.trainers[3].party[0].moves[0]=4 \\.trainers[3].party[1].species=1 \\.trainers[3].party[1].level=5 \\.trainers[3].party[1].ability=0 \\.trainers[3].party[1].moves[0]=4 \\ ); // Test excluding system by running 100 seeds and checking that none of them pick the // excluded pokemons var seed: u8 = 0; while (seed < 100) : (seed += 1) { var buf: [100]u8 = undefined; const seed_arg = try fmt.bufPrint(&buf, "--seed={}", .{seed}); const out = try util.testing.runProgram(Program, .{ .args = &[_][]const u8{ "--exclude=pokemon 2", "--exclude=pokemon 4", seed_arg, }, .in = test_string }); defer testing.allocator.free(out); try testing.expect(mem.indexOf(u8, out, ".species=2") == null); try testing.expect(mem.indexOf(u8, out, ".species=4") == null); } }
src/randomizers/tm35-rand-parties.zig
//-------------------------------------------------------------------------------- // Section: Types (4) //-------------------------------------------------------------------------------- pub const CYPHER_BLOCK = extern struct { data: [8]CHAR, }; pub const LM_OWF_PASSWORD = extern struct { data: [2]CYPHER_BLOCK, }; pub const SAMPR_ENCRYPTED_USER_PASSWORD = extern struct { Buffer: [516]u8, }; pub const ENCRYPTED_LM_OWF_PASSWORD = extern struct { data: [2]CYPHER_BLOCK, }; //-------------------------------------------------------------------------------- // Section: Functions (2) //-------------------------------------------------------------------------------- // TODO: this type is limited to platform 'windows5.1.2600' pub extern "ADVAPI32" fn MSChapSrvChangePassword( ServerName: ?PWSTR, UserName: ?PWSTR, LmOldPresent: BOOLEAN, LmOldOwfPassword: ?*LM_<PASSWORD>, LmNewOwfPassword: ?*<PASSWORD>, NtOldOwfPassword: ?*<PASSWORD>, NtNewOwfPassword: ?*<PASSWORD>, ) callconv(@import("std").os.windows.WINAPI) u32; // TODO: this type is limited to platform 'windows5.1.2600' pub extern "ADVAPI32" fn MSChapSrvChangePassword2( ServerName: ?PWSTR, UserName: ?PWSTR, NewPasswordEncryptedWithOldNt: ?*SAMPR_ENCRYPTED_USER_PASSWORD, OldNtOwfPasswordEncryptedWithNewNt: ?*ENCRYPTED_LM_OWF_PASSWORD, LmPresent: BOOLEAN, NewPasswordEncryptedWithOldLm: ?*SAMPR_ENCRYPTED_USER_PASSWORD, OldLmOwfPasswordEncryptedWithNewLmOrNt: ?*ENCRYPTED_LM_OWF_PASSWORD, ) callconv(@import("std").os.windows.WINAPI) u32; //-------------------------------------------------------------------------------- // 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 (3) //-------------------------------------------------------------------------------- const BOOLEAN = @import("../foundation.zig").BOOLEAN; const CHAR = @import("../system/system_services.zig").CHAR; 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; } } }
deps/zigwin32/win32/system/password_management.zig
const std = @import("std.zig"); const debug = std.debug; const mem = std.mem; const Allocator = mem.Allocator; const assert = debug.assert; const testing = std.testing; const ArrayList = std.ArrayList; /// A contiguous, growable list of items in memory, with a sentinel after them. /// The sentinel is maintained when appending, resizing, etc. /// If you do not need a sentinel, consider using `ArrayList` instead. pub fn ArrayListSentineled(comptime T: type, comptime sentinel: T) type { return struct { list: ArrayList(T), const Self = @This(); /// Must deinitialize with deinit. pub fn init(allocator: *Allocator, m: []const T) !Self { var self = try initSize(allocator, m.len); mem.copy(T, self.list.items, m); return self; } /// Initialize memory to size bytes of undefined values. /// Must deinitialize with deinit. pub fn initSize(allocator: *Allocator, size: usize) !Self { var self = initNull(allocator); try self.resize(size); return self; } /// Initialize with capacity to hold at least num bytes. /// Must deinitialize with deinit. pub fn initCapacity(allocator: *Allocator, num: usize) !Self { var self = Self{ .list = try ArrayList(T).initCapacity(allocator, num + 1) }; self.list.appendAssumeCapacity(sentinel); return self; } /// Must deinitialize with deinit. /// None of the other operations are valid until you do one of these: /// * `replaceContents` /// * `resize` pub fn initNull(allocator: *Allocator) Self { return Self{ .list = ArrayList(T).init(allocator) }; } /// Must deinitialize with deinit. pub fn initFromBuffer(buffer: Self) !Self { return Self.init(buffer.list.allocator, buffer.span()); } /// Takes ownership of the passed in slice. The slice must have been /// allocated with `allocator`. /// Must deinitialize with deinit. pub fn fromOwnedSlice(allocator: *Allocator, slice: []T) !Self { var self = Self{ .list = ArrayList(T).fromOwnedSlice(allocator, slice) }; try self.list.append(sentinel); return self; } /// The caller owns the returned memory. The list becomes null and is safe to `deinit`. pub fn toOwnedSlice(self: *Self) [:sentinel]T { const allocator = self.list.allocator; const result = self.list.toOwnedSlice(); self.* = initNull(allocator); return result[0 .. result.len - 1 :sentinel]; } /// Only works when `T` is `u8`. pub fn allocPrint(allocator: *Allocator, comptime format: []const u8, args: var) !Self { const size = std.math.cast(usize, std.fmt.count(format, args)) catch |err| switch (err) { error.Overflow => return error.OutOfMemory, }; var self = try Self.initSize(allocator, size); assert((std.fmt.bufPrint(self.list.items, format, args) catch unreachable).len == size); return self; } pub fn deinit(self: *Self) void { self.list.deinit(); } pub fn span(self: var) @TypeOf(self.list.items[0 .. self.list.len - 1 :sentinel]) { return self.list.span()[0..self.len() :sentinel]; } pub fn shrink(self: *Self, new_len: usize) void { assert(new_len <= self.len()); self.list.shrink(new_len + 1); self.list.items[self.len()] = sentinel; } pub fn resize(self: *Self, new_len: usize) !void { try self.list.resize(new_len + 1); self.list.items[self.len()] = sentinel; } pub fn isNull(self: Self) bool { return self.list.len == 0; } pub fn len(self: Self) usize { return self.list.len - 1; } pub fn capacity(self: Self) usize { return if (self.list.items.len > 0) self.list.items.len - 1 else 0; } pub fn appendSlice(self: *Self, m: []const T) !void { const old_len = self.len(); try self.resize(old_len + m.len); mem.copy(T, self.list.span()[old_len..], m); } pub fn append(self: *Self, byte: T) !void { const old_len = self.len(); try self.resize(old_len + 1); self.list.span()[old_len] = byte; } pub fn eql(self: Self, m: []const T) bool { return mem.eql(T, self.span(), m); } pub fn startsWith(self: Self, m: []const T) bool { if (self.len() < m.len) return false; return mem.eql(T, self.list.items[0..m.len], m); } pub fn endsWith(self: Self, m: []const T) bool { const l = self.len(); if (l < m.len) return false; const start = l - m.len; return mem.eql(T, self.list.items[start..l], m); } pub fn replaceContents(self: *Self, m: []const T) !void { try self.resize(m.len); mem.copy(T, self.list.span(), m); } /// Initializes an OutStream which will append to the list. /// This function may be called only when `T` is `u8`. pub fn outStream(self: *Self) std.io.OutStream(*Self, error{OutOfMemory}, appendWrite) { return .{ .context = self }; } /// Same as `append` except it returns the number of bytes written, which is always the same /// as `m.len`. The purpose of this function existing is to match `std.io.OutStream` API. /// This function may be called only when `T` is `u8`. pub fn appendWrite(self: *Self, m: []const u8) !usize { try self.appendSlice(m); return m.len; } }; } test "simple" { var buf = try ArrayListSentineled(u8, 0).init(testing.allocator, ""); defer buf.deinit(); testing.expect(buf.len() == 0); try buf.appendSlice("hello"); try buf.appendSlice(" "); try buf.appendSlice("world"); testing.expect(buf.eql("hello world")); testing.expect(mem.eql(u8, mem.spanZ(buf.span().ptr), buf.span())); var buf2 = try ArrayListSentineled(u8, 0).initFromBuffer(buf); defer buf2.deinit(); testing.expect(buf.eql(buf2.span())); testing.expect(buf.startsWith("hell")); testing.expect(buf.endsWith("orld")); try buf2.resize(4); testing.expect(buf.startsWith(buf2.span())); } test "initSize" { var buf = try ArrayListSentineled(u8, 0).initSize(testing.allocator, 3); defer buf.deinit(); testing.expect(buf.len() == 3); try buf.appendSlice("hello"); testing.expect(mem.eql(u8, buf.span()[3..], "hello")); } test "initCapacity" { var buf = try ArrayListSentineled(u8, 0).initCapacity(testing.allocator, 10); defer buf.deinit(); testing.expect(buf.len() == 0); testing.expect(buf.capacity() >= 10); const old_cap = buf.capacity(); try buf.appendSlice("hello"); testing.expect(buf.len() == 5); testing.expect(buf.capacity() == old_cap); testing.expect(mem.eql(u8, buf.span(), "hello")); } test "print" { var buf = try ArrayListSentineled(u8, 0).init(testing.allocator, ""); defer buf.deinit(); try buf.outStream().print("Hello {} the {}", .{ 2, "world" }); testing.expect(buf.eql("Hello 2 the world")); } test "outStream" { var buffer = try ArrayListSentineled(u8, 0).initSize(testing.allocator, 0); defer buffer.deinit(); const buf_stream = buffer.outStream(); const x: i32 = 42; const y: i32 = 1234; try buf_stream.print("x: {}\ny: {}\n", .{ x, y }); testing.expect(mem.eql(u8, buffer.span(), "x: 42\ny: 1234\n")); }
lib/std/array_list_sentineled.zig
const std = @import("std"); const Submarine = struct { x: u64, y: u64, aim: i32, pub fn init() Submarine { return Submarine{ .x = 0, .y = 0, .aim = 0 }; } pub fn scanFile(self: *Submarine, fname: []const u8) !void { const f = try std.fs.cwd().openFile(fname, std.fs.File.OpenFlags{ .read = true }); defer f.close(); var stream = std.io.bufferedReader(f.reader()).reader(); var buf: [1024]u8 = undefined; while (try stream.readUntilDelimiterOrEof(&buf, '\n')) |line| { try self.readLine(line); } } pub fn readLine(self: *Submarine, line: []const u8) !void { const instr = try Instruction.parseLine(line); switch (instr.dir) { Direction.forward => { self.moveForward(instr.amt); }, Direction.up => { self.aim -= @as(i32, instr.amt); }, Direction.down => { self.aim += @as(i32, instr.amt); }, Direction.invalid => { unreachable; }, } } pub fn moveForward(self: *Submarine, amt: u16) void { self.x += amt; if (self.aim > 0) { self.y += @intCast(u64, self.aim) * amt; } else { self.y -= @intCast(u64, -self.aim) * amt; } } }; const Direction = enum { forward, down, up, invalid, pub fn strlen(self: Direction) usize { return switch (self) { Direction.forward => "forward ".len, Direction.down => "down ".len, Direction.up => "up ".len, Direction.invalid => 0, }; } }; const Instruction = struct { dir: Direction, amt: u16, pub fn parseLine(line: []const u8) !Instruction { var instr = Instruction{ .dir = switch (line[0]) { 'f' => Direction.forward, 'd' => Direction.down, 'u' => Direction.up, else => Direction.invalid, }, .amt = undefined, }; if (instr.dir == Direction.invalid) { std.debug.print("broken line: {s} line[0]={c}\n", .{ line, line[0] }); return error.InvalidDirection; } // Extract the string part, which should const amtStr = line[instr.dir.strlen()..]; instr.amt = try std.fmt.parseInt(u16, amtStr, 10); return instr; } }; pub fn main() !void { const fname = "inputs/2/input"; var sub = Submarine.init(); try sub.scanFile(fname); const result = sub.x * sub.y; std.debug.print("{d}\n", .{result}); }
2021/zig/day2_q2.zig
const win32 = @import("./c.zig"); pub const EmptyWorkingSet = K32EmptyWorkingSet; pub extern "kernel32" fn K32EmptyWorkingSet(hProcess: win32.HANDLE) win32.BOOL; pub const EnumDeviceDrivers = K32EnumDeviceDrivers; pub extern "kernel32" fn K32EnumDeviceDrivers( lpImageBase: [*c]win32.LPVOID, cb: win32.DWORD, lpcbNeeded: win32.LPDWORD, ) win32.BOOL; pub const EnumPageFiles = EnumPageFilesA; pub const EnumPageFilesA = K32EnumPageFilesA; pub const EnumPageFilesW = K32EnumPageFilesW; pub extern "kernel32" fn K32EnumPageFilesW( pCallBackRoutine: PENUM_PAGE_FILE_CALLBACKW, pContext: win32.LPVOID, ) win32.BOOL; pub extern "kernel32" fn K32EnumPageFilesA( pCallBackRoutine: PENUM_PAGE_FILE_CALLBACKA, pContext: win32.LPVOID, ) win32.BOOL; pub const PENUM_PAGE_FILE_CALLBACKW = ?fn ( win32.LPVOID, PENUM_PAGE_FILE_INFORMATION, win32.LPCWSTR, ) callconv(.C) win32.BOOL; pub const PENUM_PAGE_FILE_CALLBACKA = ?fn ( win32.LPVOID, PENUM_PAGE_FILE_INFORMATION, win32.LPCSTR, ) callconv(.C) win32.BOOL; pub const struct__ENUM_PAGE_FILE_INFORMATION = extern struct { cb: win32.DWORD, Reserved: win32.DWORD, TotalSize: win32.SIZE_T, TotalInUse: win32.SIZE_T, PeakUsage: win32.SIZE_T, }; pub const ENUM_PAGE_FILE_INFORMATION = struct__ENUM_PAGE_FILE_INFORMATION; pub const PENUM_PAGE_FILE_INFORMATION = [*c]struct__ENUM_PAGE_FILE_INFORMATION; pub extern "kernel32" fn K32EnumProcesses( lpidProcess: [*c]win32.DWORD, cb: win32.DWORD, lpcbNeeded: win32.LPDWORD, ) win32.BOOL; pub const EnumProcesses = K32EnumProcesses; pub const EnumProcessModulesEx = K32EnumProcessModulesEx; pub const EnumProcessModules = K32EnumProcessModules; pub extern "kernel32" fn K32EnumProcessModules( hProcess: win32.HANDLE, lphModule: [*c]win32.HMODULE, cb: win32.DWORD, lpcbNeeded: win32.LPDWORD, ) win32.BOOL; pub extern "kernel32" fn K32EnumProcessModulesEx( hProcess: win32.HANDLE, lphModule: [*c]win32.HMODULE, cb: win32.DWORD, lpcbNeeded: win32.LPDWORD, dwFilterFlag: win32.DWORD, ) win32.BOOL; pub extern "kernel32" fn K32GetDeviceDriverBaseNameA( ImageBase: win32.LPVOID, lpFilename: win32.LPSTR, nSize: win32.DWORD, ) win32.DWORD; pub extern "kernel32" fn K32GetDeviceDriverBaseNameW( ImageBase: win32.LPVOID, lpBaseName: win32.LPWSTR, nSize: win32.DWORD, ) win32.DWORD; pub const GetDeviceDriverBaseName = GetDeviceDriverBaseNameA; pub const GetDeviceDriverBaseNameA = K32GetDeviceDriverBaseNameA; pub const GetDeviceDriverBaseNameW = K32GetDeviceDriverBaseNameW; pub extern "kernel32" fn K32GetDeviceDriverFileNameA( ImageBase: win32.LPVOID, lpFilename: win32.LPSTR, nSize: win32.DWORD, ) win32.DWORD; pub extern "kernel32" fn K32GetDeviceDriverFileNameW( ImageBase: win32.LPVOID, lpFilename: win32.LPWSTR, nSize: win32.DWORD, ) win32.DWORD; pub const GetDeviceDriverFileNameA = K32GetDeviceDriverFileNameA; pub const GetDeviceDriverFileName = GetDeviceDriverFileNameA; pub const GetDeviceDriverFileNameW = K32GetDeviceDriverFileNameW; pub extern "kernel32" fn K32GetMappedFileNameW( hProcess: win32.HANDLE, lpv: win32.LPVOID, lpFilename: win32.LPWSTR, nSize: win32.DWORD, ) win32.DWORD; pub extern "kernel32" fn K32GetMappedFileNameA( hProcess: win32.HANDLE, lpv: win32.LPVOID, lpFilename: win32.LPSTR, nSize: win32.DWORD, ) win32.DWORD; pub const GetMappedFileNameW = K32GetMappedFileNameW; pub const GetMappedFileNameA = K32GetMappedFileNameA; pub const GetMappedFileName = GetMappedFileNameA; pub extern "kernel32" fn K32GetModuleBaseNameA( hProcess: win32.HANDLE, hModule: win32.HMODULE, lpBaseName: win32.LPSTR, nSize: win32.DWORD, ) win32.DWORD; pub extern "kernel32" fn K32GetModuleBaseNameW( hProcess: win32.HANDLE, hModule: win32.HMODULE, lpBaseName: win32.LPWSTR, nSize: win32.DWORD, ) win32.DWORD; pub extern "kernel32" fn K32GetModuleFileNameExA( hProcess: win32.HANDLE, hModule: win32.HMODULE, lpFilename: win32.LPSTR, nSize: win32.DWORD, ) win32.DWORD; pub extern "kernel32" fn K32GetModuleFileNameExW( hProcess: win32.HANDLE, hModule: win32.HMODULE, lpFilename: win32.LPWSTR, nSize: win32.DWORD, ) win32.DWORD; pub extern "kernel32" fn GetModuleFileNameA( hModule: win32.HMODULE, lpFilename: win32.LPSTR, nSize: win32.DWORD, ) win32.DWORD; pub extern "kernel32" fn GetModuleFileNameW( hModule: win32.HMODULE, lpFilename: win32.LPWSTR, nSize: win32.DWORD, ) win32.DWORD; pub const GetModuleBaseNameW = K32GetModuleBaseNameW; pub const GetModuleBaseName = GetModuleBaseNameA; pub const GetModuleBaseNameA = K32GetModuleBaseNameA; pub const GetModuleFileName = GetModuleFileNameA; pub const GetModuleFileNameEx = GetModuleFileNameExA; pub const GetModuleFileNameExA = K32GetModuleFileNameExA; pub const GetModuleFileNameExW = K32GetModuleFileNameExW; pub extern "kernel32" fn K32GetModuleInformation( hProcess: win32.HANDLE, hModule: win32.HMODULE, lpmodinfo: LPMODULEINFO, cb: win32.DWORD, ) BOOL; pub const GetModuleInformation = K32GetModuleInformation; pub const struct__MODULEINFO = extern struct { lpBaseOfDll: win32.LPVOID, SizeOfImage: win32.DWORD, EntryPoint: win32.LPVOID, }; pub const MODULEINFO = struct__MODULEINFO; pub const LPMODULEINFO = [*c]struct__MODULEINFO; pub extern "kernel32" fn K32GetPerformanceInfo( pPerformanceInformation: PPERFORMANCE_INFORMATION, cb: win32.DWORD, ) win32.BOOL; pub const GetPerformanceInfo = K32GetPerformanceInfo; pub const struct__PERFORMANCE_INFORMATION = extern struct { cb: win32.DWORD, CommitTotal: win32.SIZE_T, CommitLimit: win32.SIZE_T, CommitPeak: win32.SIZE_T, PhysicalTotal: win32.SIZE_T, PhysicalAvailable: win32.SIZE_T, SystemCache: win32.SIZE_T, KernelTotal: win32.SIZE_T, KernelPaged: win32.SIZE_T, KernelNonpaged: win32.SIZE_T, PageSize: win32.SIZE_T, HandleCount: win32.DWORD, ProcessCount: win32.DWORD, ThreadCount: win32.DWORD, }; pub const PERFORMANCE_INFORMATION = struct__PERFORMANCE_INFORMATION; pub const PPERFORMANCE_INFORMATION = [*c]struct__PERFORMANCE_INFORMATION; pub const PERFORMACE_INFORMATION = struct__PERFORMANCE_INFORMATION; pub const PPERFORMACE_INFORMATION = [*c]struct__PERFORMANCE_INFORMATION; pub extern "kernel32" fn K32GetProcessImageFileNameA( hProcess: win32.HANDLE, lpImageFileName: win32.LPSTR, nSize: win32.DWORD, ) win32.DWORD; pub extern "kernel32" fn K32GetProcessImageFileNameW( hProcess: win32.HANDLE, lpImageFileName: win32.LPWSTR, nSize: win32.DWORD, ) win32.DWORD; pub const GetProcessImageFileNameA = K32GetProcessImageFileNameA; pub const GetProcessImageFileNameW = K32GetProcessImageFileNameW; pub const GetProcessImageFileName = GetProcessImageFileNameA; pub extern "kernel32" fn K32GetProcessMemoryInfo( Process: win32.HANDLE, ppsmemCounters: PPROCESS_MEMORY_COUNTERS, cb: win32.DWORD, ) win32.BOOL; pub const GetProcessMemoryInfo = K32GetProcessMemoryInfo; pub const struct__PROCESS_MEMORY_COUNTERS = extern struct { cb: win32.DWORD, PageFaultCount: win32.DWORD, PeakWorkingSetSize: win32.SIZE_T, WorkingSetSize: win32.SIZE_T, QuotaPeakPagedPoolUsage: win32.SIZE_T, QuotaPagedPoolUsage: win32.SIZE_T, QuotaPeakNonPagedPoolUsage: win32.SIZE_T, QuotaNonPagedPoolUsage: win32.SIZE_T, PagefileUsage: win32.SIZE_T, PeakPagefileUsage: win32.SIZE_T, }; pub const PROCESS_MEMORY_COUNTERS = struct__PROCESS_MEMORY_COUNTERS; pub const PPROCESS_MEMORY_COUNTERS = [*c]PROCESS_MEMORY_COUNTERS; pub const struct__PROCESS_MEMORY_COUNTERS_EX = extern struct { cb: win32.DWORD, PageFaultCount: win32.DWORD, PeakWorkingSetSize: win32.SIZE_T, WorkingSetSize: win32.SIZE_T, QuotaPeakPagedPoolUsage: win32.SIZE_T, QuotaPagedPoolUsage: win32.SIZE_T, QuotaPeakNonPagedPoolUsage: win32.SIZE_T, QuotaNonPagedPoolUsage: win32.SIZE_T, PagefileUsage: win32.SIZE_T, PeakPagefileUsage: win32.SIZE_T, PrivateUsage: win32.SIZE_T, }; pub const PROCESS_MEMORY_COUNTERS_EX = struct__PROCESS_MEMORY_COUNTERS_EX; pub const PPROCESS_MEMORY_COUNTERS_EX = [*c]PROCESS_MEMORY_COUNTERS_EX; pub extern "kernel32" fn K32QueryWorkingSet( hProcess: win32.HANDLE, pv: win32.PVOID, cb: win32.DWORD, ) win32.BOOL; pub extern "kernel32" fn K32QueryWorkingSetEx( hProcess: win32.HANDLE, pv: win32.PVOID, cb: win32.DWORD, ) win32.BOOL; pub const QueryWorkingSetEx = K32QueryWorkingSetEx; pub const QueryWorkingSet = K32QueryWorkingSet; pub extern "kernel32" fn K32InitializeProcessForWsWatch(hProcess: win32.HANDLE) win32.BOOL; pub const InitializeProcessForWsWatch = K32InitializeProcessForWsWatch; pub extern "kernel32" fn K32GetWsChanges( hProcess: win32.HANDLE, lpWatchInfo: PPSAPI_WS_WATCH_INFORMATION, cb: win32.DWORD, ) win32.BOOL; pub extern "kernel32" fn K32GetWsChangesEx( hProcess: win32.HANDLE, lpWatchInfoEx: PPSAPI_WS_WATCH_INFORMATION_EX, cb: win32.PDWORD, ) win32.BOOL; pub const struct__PSAPI_WS_WATCH_INFORMATION = extern struct { FaultingPc: win32.LPVOID, FaultingVa: win32.LPVOID, }; pub const PSAPI_WS_WATCH_INFORMATION = struct__PSAPI_WS_WATCH_INFORMATION; pub const PPSAPI_WS_WATCH_INFORMATION = [*c]struct__PSAPI_WS_WATCH_INFORMATION; pub const struct__PSAPI_WS_WATCH_INFORMATION_EX = extern struct { BasicInfo: PSAPI_WS_WATCH_INFORMATION, FaultingThreadId: win32.ULONG_PTR, Flags: win32.ULONG_PTR, }; pub const PSAPI_WS_WATCH_INFORMATION_EX = struct__PSAPI_WS_WATCH_INFORMATION_EX; pub const PPSAPI_WS_WATCH_INFORMATION_EX = [*c]struct__PSAPI_WS_WATCH_INFORMATION_EX; const struct_unnamed_258 = @Type(.Opaque); // C:\Program Files (x86)\Windows Kits\10\Include\10.0.19041.0\um\psapi.h:277:19: warning: struct demoted to opaque type - has bitfield pub const union__PSAPI_WORKING_SET_BLOCK = extern union { Flags: win32.ULONG_PTR, unnamed_0: struct_unnamed_258, }; pub const PSAPI_WORKING_SET_BLOCK = union__PSAPI_WORKING_SET_BLOCK; pub const PPSAPI_WORKING_SET_BLOCK = [*c]union__PSAPI_WORKING_SET_BLOCK; pub const struct__PSAPI_WORKING_SET_INFORMATION = extern struct { NumberOfEntries: win32.ULONG_PTR, WorkingSetInfo: [1]PSAPI_WORKING_SET_BLOCK, }; pub const PSAPI_WORKING_SET_INFORMATION = struct__PSAPI_WORKING_SET_INFORMATION; pub const PPSAPI_WORKING_SET_INFORMATION = [*c]struct__PSAPI_WORKING_SET_INFORMATION; const struct_unnamed_260 = @Type(.Opaque); // C:\Program Files (x86)\Windows Kits\10\Include\10.0.19041.0\um\psapi.h:298:23: warning: struct demoted to opaque type - has bitfield const struct_unnamed_261 = @Type(.Opaque); // C:\Program Files (x86)\Windows Kits\10\Include\10.0.19041.0\um\psapi.h:313:23: warning: struct demoted to opaque type - has bitfield const union_unnamed_259 = extern union { unnamed_0: struct_unnamed_260, Invalid: struct_unnamed_261, }; pub const union__PSAPI_WORKING_SET_EX_BLOCK = extern union { Flags: win32.ULONG_PTR, unnamed_0: union_unnamed_259, }; pub const PSAPI_WORKING_SET_EX_BLOCK = union__PSAPI_WORKING_SET_EX_BLOCK; pub const PPSAPI_WORKING_SET_EX_BLOCK = [*c]union__PSAPI_WORKING_SET_EX_BLOCK; pub const struct__PSAPI_WORKING_SET_EX_INFORMATION = extern struct { VirtualAddress: win32.PVOID, VirtualAttributes: PSAPI_WORKING_SET_EX_BLOCK, }; pub const PSAPI_WORKING_SET_EX_INFORMATION = struct__PSAPI_WORKING_SET_EX_INFORMATION; pub const PPSAPI_WORKING_SET_EX_INFORMATION = [*c]struct__PSAPI_WORKING_SET_EX_INFORMATION; pub const LIST_MODULES_64BIT = 0x02; pub const LIST_MODULES_DEFAULT = 0x0; pub const LIST_MODULES_ALL = LIST_MODULES_32BIT | LIST_MODULES_64BIT; pub const LIST_MODULES_32BIT = 0x01;
src/win32/psapi.zig
pub const NS_PNRPNAME = @as(u32, 38); pub const NS_PNRPCLOUD = @as(u32, 39); pub const PNRPINFO_HINT = @as(u32, 1); pub const NS_PROVIDER_PNRPNAME = Guid.initString("03fe89cd-766d-4976-b9c1-bb9bc42c7b4d"); pub const NS_PROVIDER_PNRPCLOUD = Guid.initString("03fe89ce-766d-4976-b9c1-bb9bc42c7b4d"); pub const SVCID_PNRPCLOUD = Guid.initString("c2239ce6-00c0-4fbf-bad6-18139385a49a"); pub const SVCID_PNRPNAME_V1 = Guid.initString("c2239ce5-00c0-4fbf-bad6-18139385a49a"); pub const SVCID_PNRPNAME_V2 = Guid.initString("c2239ce7-00c0-4fbf-bad6-18139385a49a"); pub const PNRP_MAX_ENDPOINT_ADDRESSES = @as(u32, 10); pub const PNRP_MAX_EXTENDED_PAYLOAD_BYTES = @as(u32, 4096); pub const WSA_PNRP_ERROR_BASE = @as(u32, 11500); pub const WSA_PNRP_CLOUD_NOT_FOUND = @as(u32, 11501); pub const WSA_PNRP_CLOUD_DISABLED = @as(u32, 11502); pub const WSA_PNRP_INVALID_IDENTITY = @as(u32, 11503); pub const WSA_PNRP_TOO_MUCH_LOAD = @as(u32, 11504); pub const WSA_PNRP_CLOUD_IS_SEARCH_ONLY = @as(u32, 11505); pub const WSA_PNRP_CLIENT_INVALID_COMPARTMENT_ID = @as(u32, 11506); pub const WSA_PNRP_DUPLICATE_PEER_NAME = @as(u32, 11508); pub const WSA_PNRP_CLOUD_IS_DEAD = @as(u32, 11509); pub const PEER_E_CLOUD_NOT_FOUND = @import("../zig.zig").typedConst(HRESULT, @as(i32, -2147013395)); pub const PEER_E_CLOUD_DISABLED = @import("../zig.zig").typedConst(HRESULT, @as(i32, -2147013394)); pub const PEER_E_INVALID_IDENTITY = @import("../zig.zig").typedConst(HRESULT, @as(i32, -2147013393)); pub const PEER_E_TOO_MUCH_LOAD = @import("../zig.zig").typedConst(HRESULT, @as(i32, -2147013392)); pub const PEER_E_CLOUD_IS_SEARCH_ONLY = @import("../zig.zig").typedConst(HRESULT, @as(i32, -2147013391)); pub const PEER_E_CLIENT_INVALID_COMPARTMENT_ID = @import("../zig.zig").typedConst(HRESULT, @as(i32, -2147013390)); pub const PEER_E_DUPLICATE_PEER_NAME = @import("../zig.zig").typedConst(HRESULT, @as(i32, -2147013388)); pub const PEER_E_CLOUD_IS_DEAD = @import("../zig.zig").typedConst(HRESULT, @as(i32, -2147013387)); pub const PEER_E_NOT_FOUND = @import("../zig.zig").typedConst(HRESULT, @as(i32, -2147023728)); pub const PEER_E_DISK_FULL = @import("../zig.zig").typedConst(HRESULT, @as(i32, -2147024784)); pub const PEER_E_ALREADY_EXISTS = @import("../zig.zig").typedConst(HRESULT, @as(i32, -2147024713)); pub const PEER_GROUP_ROLE_ADMIN = Guid.initString("04387127-aa56-450a-8ce5-4f565c6790f4"); pub const PEER_GROUP_ROLE_MEMBER = Guid.initString("f12dc4c7-0857-4ca0-93fc-b1bb19a3d8c2"); pub const PEER_GROUP_ROLE_INVITING_MEMBER = Guid.initString("4370fd89-dc18-4cfb-8dbf-9853a8a9f905"); pub const PEER_COLLAB_OBJECTID_USER_PICTURE = Guid.initString("dd15f41f-fc4e-4922-b035-4c06a754d01d"); pub const FACILITY_DRT = @as(u32, 98); pub const DRT_E_TIMEOUT = @import("../zig.zig").typedConst(HRESULT, @as(i32, -2141057023)); pub const DRT_E_INVALID_KEY_SIZE = @import("../zig.zig").typedConst(HRESULT, @as(i32, -2141057022)); pub const DRT_E_INVALID_CERT_CHAIN = @import("../zig.zig").typedConst(HRESULT, @as(i32, -2141057020)); pub const DRT_E_INVALID_MESSAGE = @import("../zig.zig").typedConst(HRESULT, @as(i32, -2141057019)); pub const DRT_E_NO_MORE = @import("../zig.zig").typedConst(HRESULT, @as(i32, -2141057018)); pub const DRT_E_INVALID_MAX_ADDRESSES = @import("../zig.zig").typedConst(HRESULT, @as(i32, -2141057017)); pub const DRT_E_SEARCH_IN_PROGRESS = @import("../zig.zig").typedConst(HRESULT, @as(i32, -2141057016)); pub const DRT_E_INVALID_KEY = @import("../zig.zig").typedConst(HRESULT, @as(i32, -2141057015)); pub const DRT_S_RETRY = @import("../zig.zig").typedConst(HRESULT, @as(i32, 6426640)); pub const DRT_E_INVALID_MAX_ENDPOINTS = @import("../zig.zig").typedConst(HRESULT, @as(i32, -2141057007)); pub const DRT_E_INVALID_SEARCH_RANGE = @import("../zig.zig").typedConst(HRESULT, @as(i32, -2141057006)); pub const DRT_E_INVALID_PORT = @import("../zig.zig").typedConst(HRESULT, @as(i32, -2141052928)); pub const DRT_E_INVALID_TRANSPORT_PROVIDER = @import("../zig.zig").typedConst(HRESULT, @as(i32, -2141052927)); pub const DRT_E_INVALID_SECURITY_PROVIDER = @import("../zig.zig").typedConst(HRESULT, @as(i32, -2141052926)); pub const DRT_E_STILL_IN_USE = @import("../zig.zig").typedConst(HRESULT, @as(i32, -2141052925)); pub const DRT_E_INVALID_BOOTSTRAP_PROVIDER = @import("../zig.zig").typedConst(HRESULT, @as(i32, -2141052924)); pub const DRT_E_INVALID_ADDRESS = @import("../zig.zig").typedConst(HRESULT, @as(i32, -2141052923)); pub const DRT_E_INVALID_SCOPE = @import("../zig.zig").typedConst(HRESULT, @as(i32, -2141052922)); pub const DRT_E_TRANSPORT_SHUTTING_DOWN = @import("../zig.zig").typedConst(HRESULT, @as(i32, -2141052921)); pub const DRT_E_NO_ADDRESSES_AVAILABLE = @import("../zig.zig").typedConst(HRESULT, @as(i32, -2141052920)); pub const DRT_E_DUPLICATE_KEY = @import("../zig.zig").typedConst(HRESULT, @as(i32, -2141052919)); pub const DRT_E_TRANSPORTPROVIDER_IN_USE = @import("../zig.zig").typedConst(HRESULT, @as(i32, -2141052918)); pub const DRT_E_TRANSPORTPROVIDER_NOT_ATTACHED = @import("../zig.zig").typedConst(HRESULT, @as(i32, -2141052917)); pub const DRT_E_SECURITYPROVIDER_IN_USE = @import("../zig.zig").typedConst(HRESULT, @as(i32, -2141052916)); pub const DRT_E_SECURITYPROVIDER_NOT_ATTACHED = @import("../zig.zig").typedConst(HRESULT, @as(i32, -2141052915)); pub const DRT_E_BOOTSTRAPPROVIDER_IN_USE = @import("../zig.zig").typedConst(HRESULT, @as(i32, -2141052914)); pub const DRT_E_BOOTSTRAPPROVIDER_NOT_ATTACHED = @import("../zig.zig").typedConst(HRESULT, @as(i32, -2141052913)); pub const DRT_E_TRANSPORT_ALREADY_BOUND = @import("../zig.zig").typedConst(HRESULT, @as(i32, -2141052671)); pub const DRT_E_TRANSPORT_NOT_BOUND = @import("../zig.zig").typedConst(HRESULT, @as(i32, -2141052670)); pub const DRT_E_TRANSPORT_UNEXPECTED = @import("../zig.zig").typedConst(HRESULT, @as(i32, -2141052669)); pub const DRT_E_TRANSPORT_INVALID_ARGUMENT = @import("../zig.zig").typedConst(HRESULT, @as(i32, -2141052668)); pub const DRT_E_TRANSPORT_NO_DEST_ADDRESSES = @import("../zig.zig").typedConst(HRESULT, @as(i32, -2141052667)); pub const DRT_E_TRANSPORT_EXECUTING_CALLBACK = @import("../zig.zig").typedConst(HRESULT, @as(i32, -2141052666)); pub const DRT_E_TRANSPORT_ALREADY_EXISTS_FOR_SCOPE = @import("../zig.zig").typedConst(HRESULT, @as(i32, -2141052665)); pub const DRT_E_INVALID_SETTINGS = @import("../zig.zig").typedConst(HRESULT, @as(i32, -2141052664)); pub const DRT_E_INVALID_SEARCH_INFO = @import("../zig.zig").typedConst(HRESULT, @as(i32, -2141052663)); pub const DRT_E_FAULTED = @import("../zig.zig").typedConst(HRESULT, @as(i32, -2141052662)); pub const DRT_E_TRANSPORT_STILL_BOUND = @import("../zig.zig").typedConst(HRESULT, @as(i32, -2141052661)); pub const DRT_E_INSUFFICIENT_BUFFER = @import("../zig.zig").typedConst(HRESULT, @as(i32, -2141052660)); pub const DRT_E_INVALID_INSTANCE_PREFIX = @import("../zig.zig").typedConst(HRESULT, @as(i32, -2141052659)); pub const DRT_E_INVALID_SECURITY_MODE = @import("../zig.zig").typedConst(HRESULT, @as(i32, -2141052658)); pub const DRT_E_CAPABILITY_MISMATCH = @import("../zig.zig").typedConst(HRESULT, @as(i32, -2141052657)); pub const DRT_PAYLOAD_REVOKED = @as(u32, 1); pub const DRT_MIN_ROUTING_ADDRESSES = @as(u32, 1); pub const DRT_MAX_ROUTING_ADDRESSES = @as(u32, 20); pub const DRT_MAX_PAYLOAD_SIZE = @as(u32, 5120); pub const DRT_MAX_INSTANCE_PREFIX_LEN = @as(u32, 128); pub const DRT_LINK_LOCAL_ISATAP_SCOPEID = @as(u32, 4294967295); pub const PEERDIST_PUBLICATION_OPTIONS_VERSION_1 = @as(i32, 1); pub const PEERDIST_PUBLICATION_OPTIONS_VERSION = @as(i32, 2); pub const PEERDIST_PUBLICATION_OPTIONS_VERSION_2 = @as(i32, 2); pub const PEERDIST_READ_TIMEOUT_LOCAL_CACHE_ONLY = @as(u32, 0); pub const PEERDIST_READ_TIMEOUT_DEFAULT = @as(u32, 4294967294); //-------------------------------------------------------------------------------- // Section: Types (110) //-------------------------------------------------------------------------------- pub const PEERDIST_RETRIEVAL_OPTIONS_CONTENTINFO_VERSION_VALUE = enum(u32) { _1 = 1, _2 = 2, // N = 2, this enum value conflicts with _2 }; pub const PEERDIST_RETRIEVAL_OPTIONS_CONTENTINFO_VERSION_1 = PEERDIST_RETRIEVAL_OPTIONS_CONTENTINFO_VERSION_VALUE._1; pub const PEERDIST_RETRIEVAL_OPTIONS_CONTENTINFO_VERSION_2 = PEERDIST_RETRIEVAL_OPTIONS_CONTENTINFO_VERSION_VALUE._2; pub const PEERDIST_RETRIEVAL_OPTIONS_CONTENTINFO_VERSION = PEERDIST_RETRIEVAL_OPTIONS_CONTENTINFO_VERSION_VALUE._2; pub const PNRP_SCOPE = enum(i32) { SCOPE_ANY = 0, GLOBAL_SCOPE = 1, SITE_LOCAL_SCOPE = 2, LINK_LOCAL_SCOPE = 3, }; pub const PNRP_SCOPE_ANY = PNRP_SCOPE.SCOPE_ANY; pub const PNRP_GLOBAL_SCOPE = PNRP_SCOPE.GLOBAL_SCOPE; pub const PNRP_SITE_LOCAL_SCOPE = PNRP_SCOPE.SITE_LOCAL_SCOPE; pub const PNRP_LINK_LOCAL_SCOPE = PNRP_SCOPE.LINK_LOCAL_SCOPE; pub const PNRP_CLOUD_STATE = enum(i32) { VIRTUAL = 0, SYNCHRONISING = 1, ACTIVE = 2, DEAD = 3, DISABLED = 4, NO_NET = 5, ALONE = 6, }; pub const PNRP_CLOUD_STATE_VIRTUAL = PNRP_CLOUD_STATE.VIRTUAL; pub const PNRP_CLOUD_STATE_SYNCHRONISING = PNRP_CLOUD_STATE.SYNCHRONISING; pub const PNRP_CLOUD_STATE_ACTIVE = PNRP_CLOUD_STATE.ACTIVE; pub const PNRP_CLOUD_STATE_DEAD = PNRP_CLOUD_STATE.DEAD; pub const PNRP_CLOUD_STATE_DISABLED = PNRP_CLOUD_STATE.DISABLED; pub const PNRP_CLOUD_STATE_NO_NET = PNRP_CLOUD_STATE.NO_NET; pub const PNRP_CLOUD_STATE_ALONE = PNRP_CLOUD_STATE.ALONE; pub const PNRP_CLOUD_FLAGS = enum(i32) { NO_FLAGS = 0, NAME_LOCAL = 1, RESOLVE_ONLY = 2, FULL_PARTICIPANT = 4, }; pub const PNRP_CLOUD_NO_FLAGS = PNRP_CLOUD_FLAGS.NO_FLAGS; pub const PNRP_CLOUD_NAME_LOCAL = PNRP_CLOUD_FLAGS.NAME_LOCAL; pub const PNRP_CLOUD_RESOLVE_ONLY = PNRP_CLOUD_FLAGS.RESOLVE_ONLY; pub const PNRP_CLOUD_FULL_PARTICIPANT = PNRP_CLOUD_FLAGS.FULL_PARTICIPANT; pub const PNRP_REGISTERED_ID_STATE = enum(i32) { OK = 1, PROBLEM = 2, }; pub const PNRP_REGISTERED_ID_STATE_OK = PNRP_REGISTERED_ID_STATE.OK; pub const PNRP_REGISTERED_ID_STATE_PROBLEM = PNRP_REGISTERED_ID_STATE.PROBLEM; pub const PNRP_RESOLVE_CRITERIA = enum(i32) { DEFAULT = 0, REMOTE_PEER_NAME = 1, NEAREST_REMOTE_PEER_NAME = 2, NON_CURRENT_PROCESS_PEER_NAME = 3, NEAREST_NON_CURRENT_PROCESS_PEER_NAME = 4, ANY_PEER_NAME = 5, NEAREST_PEER_NAME = 6, }; pub const PNRP_RESOLVE_CRITERIA_DEFAULT = PNRP_RESOLVE_CRITERIA.DEFAULT; pub const PNRP_RESOLVE_CRITERIA_REMOTE_PEER_NAME = PNRP_RESOLVE_CRITERIA.REMOTE_PEER_NAME; pub const PNRP_RESOLVE_CRITERIA_NEAREST_REMOTE_PEER_NAME = PNRP_RESOLVE_CRITERIA.NEAREST_REMOTE_PEER_NAME; pub const PNRP_RESOLVE_CRITERIA_NON_CURRENT_PROCESS_PEER_NAME = PNRP_RESOLVE_CRITERIA.NON_CURRENT_PROCESS_PEER_NAME; pub const PNRP_RESOLVE_CRITERIA_NEAREST_NON_CURRENT_PROCESS_PEER_NAME = PNRP_RESOLVE_CRITERIA.NEAREST_NON_CURRENT_PROCESS_PEER_NAME; pub const PNRP_RESOLVE_CRITERIA_ANY_PEER_NAME = PNRP_RESOLVE_CRITERIA.ANY_PEER_NAME; pub const PNRP_RESOLVE_CRITERIA_NEAREST_PEER_NAME = PNRP_RESOLVE_CRITERIA.NEAREST_PEER_NAME; pub const PNRP_CLOUD_ID = extern struct { AddressFamily: i32, Scope: PNRP_SCOPE, ScopeId: u32, }; pub const PNRP_EXTENDED_PAYLOAD_TYPE = enum(i32) { NONE = 0, BINARY = 1, STRING = 2, }; pub const PNRP_EXTENDED_PAYLOAD_TYPE_NONE = PNRP_EXTENDED_PAYLOAD_TYPE.NONE; pub const PNRP_EXTENDED_PAYLOAD_TYPE_BINARY = PNRP_EXTENDED_PAYLOAD_TYPE.BINARY; pub const PNRP_EXTENDED_PAYLOAD_TYPE_STRING = PNRP_EXTENDED_PAYLOAD_TYPE.STRING; pub const PNRPINFO_V1 = extern struct { dwSize: u32, lpwszIdentity: ?PWSTR, nMaxResolve: u32, dwTimeout: u32, dwLifetime: u32, enResolveCriteria: PNRP_RESOLVE_CRITERIA, dwFlags: u32, saHint: SOCKET_ADDRESS, enNameState: PNRP_REGISTERED_ID_STATE, }; pub const PNRPINFO_V2 = extern struct { dwSize: u32, lpwszIdentity: ?PWSTR, nMaxResolve: u32, dwTimeout: u32, dwLifetime: u32, enResolveCriteria: PNRP_RESOLVE_CRITERIA, dwFlags: u32, saHint: SOCKET_ADDRESS, enNameState: PNRP_REGISTERED_ID_STATE, enExtendedPayloadType: PNRP_EXTENDED_PAYLOAD_TYPE, Anonymous: extern union { blobPayload: BLOB, pwszPayload: ?PWSTR, }, }; pub const PNRPCLOUDINFO = extern struct { dwSize: u32, Cloud: PNRP_CLOUD_ID, enCloudState: PNRP_CLOUD_STATE, enCloudFlags: PNRP_CLOUD_FLAGS, }; pub const PEER_RECORD_CHANGE_TYPE = enum(i32) { ADDED = 1, UPDATED = 2, DELETED = 3, EXPIRED = 4, }; pub const PEER_RECORD_ADDED = PEER_RECORD_CHANGE_TYPE.ADDED; pub const PEER_RECORD_UPDATED = PEER_RECORD_CHANGE_TYPE.UPDATED; pub const PEER_RECORD_DELETED = PEER_RECORD_CHANGE_TYPE.DELETED; pub const PEER_RECORD_EXPIRED = PEER_RECORD_CHANGE_TYPE.EXPIRED; pub const PEER_CONNECTION_STATUS = enum(i32) { CONNECTED = 1, DISCONNECTED = 2, CONNECTION_FAILED = 3, }; pub const PEER_CONNECTED = PEER_CONNECTION_STATUS.CONNECTED; pub const PEER_DISCONNECTED = PEER_CONNECTION_STATUS.DISCONNECTED; pub const PEER_CONNECTION_FAILED = PEER_CONNECTION_STATUS.CONNECTION_FAILED; pub const PEER_CONNECTION_FLAGS = enum(i32) { NEIGHBOR = 1, DIRECT = 2, }; pub const PEER_CONNECTION_NEIGHBOR = PEER_CONNECTION_FLAGS.NEIGHBOR; pub const PEER_CONNECTION_DIRECT = PEER_CONNECTION_FLAGS.DIRECT; pub const PEER_RECORD_FLAGS = enum(i32) { AUTOREFRESH = 1, DELETED = 2, }; pub const PEER_RECORD_FLAG_AUTOREFRESH = PEER_RECORD_FLAGS.AUTOREFRESH; pub const PEER_RECORD_FLAG_DELETED = PEER_RECORD_FLAGS.DELETED; pub const PEER_VERSION_DATA = extern struct { wVersion: u16, wHighestVersion: u16, }; pub const PEER_DATA = extern struct { cbData: u32, pbData: ?*u8, }; pub const PEER_RECORD = extern struct { dwSize: u32, type: Guid, id: Guid, dwVersion: u32, dwFlags: u32, pwzCreatorId: ?PWSTR, pwzModifiedById: ?PWSTR, pwzAttributes: ?PWSTR, ftCreation: FILETIME, ftExpiration: FILETIME, ftLastModified: FILETIME, securityData: PEER_DATA, data: PEER_DATA, }; pub const PEER_ADDRESS = extern struct { dwSize: u32, sin6: SOCKADDR_IN6, }; pub const PEER_CONNECTION_INFO = extern struct { dwSize: u32, dwFlags: u32, ullConnectionId: u64, ullNodeId: u64, pwzPeerId: ?PWSTR, address: PEER_ADDRESS, }; pub const PEER_EVENT_INCOMING_DATA = extern struct { dwSize: u32, ullConnectionId: u64, type: Guid, data: PEER_DATA, }; pub const PEER_EVENT_RECORD_CHANGE_DATA = extern struct { dwSize: u32, changeType: PEER_RECORD_CHANGE_TYPE, recordId: Guid, recordType: Guid, }; pub const PEER_EVENT_CONNECTION_CHANGE_DATA = extern struct { dwSize: u32, status: PEER_CONNECTION_STATUS, ullConnectionId: u64, ullNodeId: u64, ullNextConnectionId: u64, hrConnectionFailedReason: HRESULT, }; pub const PEER_EVENT_SYNCHRONIZED_DATA = extern struct { dwSize: u32, recordType: Guid, }; pub const PEER_GRAPH_EVENT_TYPE = enum(i32) { STATUS_CHANGED = 1, PROPERTY_CHANGED = 2, RECORD_CHANGED = 3, DIRECT_CONNECTION = 4, NEIGHBOR_CONNECTION = 5, INCOMING_DATA = 6, CONNECTION_REQUIRED = 7, NODE_CHANGED = 8, SYNCHRONIZED = 9, }; pub const PEER_GRAPH_EVENT_STATUS_CHANGED = PEER_GRAPH_EVENT_TYPE.STATUS_CHANGED; pub const PEER_GRAPH_EVENT_PROPERTY_CHANGED = PEER_GRAPH_EVENT_TYPE.PROPERTY_CHANGED; pub const PEER_GRAPH_EVENT_RECORD_CHANGED = PEER_GRAPH_EVENT_TYPE.RECORD_CHANGED; pub const PEER_GRAPH_EVENT_DIRECT_CONNECTION = PEER_GRAPH_EVENT_TYPE.DIRECT_CONNECTION; pub const PEER_GRAPH_EVENT_NEIGHBOR_CONNECTION = PEER_GRAPH_EVENT_TYPE.NEIGHBOR_CONNECTION; pub const PEER_GRAPH_EVENT_INCOMING_DATA = PEER_GRAPH_EVENT_TYPE.INCOMING_DATA; pub const PEER_GRAPH_EVENT_CONNECTION_REQUIRED = PEER_GRAPH_EVENT_TYPE.CONNECTION_REQUIRED; pub const PEER_GRAPH_EVENT_NODE_CHANGED = PEER_GRAPH_EVENT_TYPE.NODE_CHANGED; pub const PEER_GRAPH_EVENT_SYNCHRONIZED = PEER_GRAPH_EVENT_TYPE.SYNCHRONIZED; pub const PEER_NODE_CHANGE_TYPE = enum(i32) { CONNECTED = 1, DISCONNECTED = 2, UPDATED = 3, }; pub const PEER_NODE_CHANGE_CONNECTED = PEER_NODE_CHANGE_TYPE.CONNECTED; pub const PEER_NODE_CHANGE_DISCONNECTED = PEER_NODE_CHANGE_TYPE.DISCONNECTED; pub const PEER_NODE_CHANGE_UPDATED = PEER_NODE_CHANGE_TYPE.UPDATED; pub const PEER_GRAPH_STATUS_FLAGS = enum(i32) { LISTENING = 1, HAS_CONNECTIONS = 2, SYNCHRONIZED = 4, }; pub const PEER_GRAPH_STATUS_LISTENING = PEER_GRAPH_STATUS_FLAGS.LISTENING; pub const PEER_GRAPH_STATUS_HAS_CONNECTIONS = PEER_GRAPH_STATUS_FLAGS.HAS_CONNECTIONS; pub const PEER_GRAPH_STATUS_SYNCHRONIZED = PEER_GRAPH_STATUS_FLAGS.SYNCHRONIZED; pub const PEER_GRAPH_PROPERTY_FLAGS = enum(i32) { HEARTBEATS = 1, DEFER_EXPIRATION = 2, }; pub const PEER_GRAPH_PROPERTY_HEARTBEATS = PEER_GRAPH_PROPERTY_FLAGS.HEARTBEATS; pub const PEER_GRAPH_PROPERTY_DEFER_EXPIRATION = PEER_GRAPH_PROPERTY_FLAGS.DEFER_EXPIRATION; pub const PEER_GRAPH_SCOPE = enum(i32) { ANY = 0, GLOBAL = 1, SITELOCAL = 2, LINKLOCAL = 3, LOOPBACK = 4, }; pub const PEER_GRAPH_SCOPE_ANY = PEER_GRAPH_SCOPE.ANY; pub const PEER_GRAPH_SCOPE_GLOBAL = PEER_GRAPH_SCOPE.GLOBAL; pub const PEER_GRAPH_SCOPE_SITELOCAL = PEER_GRAPH_SCOPE.SITELOCAL; pub const PEER_GRAPH_SCOPE_LINKLOCAL = PEER_GRAPH_SCOPE.LINKLOCAL; pub const PEER_GRAPH_SCOPE_LOOPBACK = PEER_GRAPH_SCOPE.LOOPBACK; pub const PEER_GRAPH_PROPERTIES = extern struct { dwSize: u32, dwFlags: u32, dwScope: u32, dwMaxRecordSize: u32, pwzGraphId: ?PWSTR, pwzCreatorId: ?PWSTR, pwzFriendlyName: ?PWSTR, pwzComment: ?PWSTR, ulPresenceLifetime: u32, cPresenceMax: u32, }; pub const PEER_NODE_INFO = extern struct { dwSize: u32, ullNodeId: u64, pwzPeerId: ?PWSTR, cAddresses: u32, pAddresses: ?*PEER_ADDRESS, pwzAttributes: ?PWSTR, }; pub const PEER_EVENT_NODE_CHANGE_DATA = extern struct { dwSize: u32, changeType: PEER_NODE_CHANGE_TYPE, ullNodeId: u64, pwzPeerId: ?PWSTR, }; pub const PEER_GRAPH_EVENT_REGISTRATION = extern struct { eventType: PEER_GRAPH_EVENT_TYPE, pType: ?*Guid, }; pub const PEER_GRAPH_EVENT_DATA = extern struct { eventType: PEER_GRAPH_EVENT_TYPE, Anonymous: extern union { dwStatus: PEER_GRAPH_STATUS_FLAGS, incomingData: PEER_EVENT_INCOMING_DATA, recordChangeData: PEER_EVENT_RECORD_CHANGE_DATA, connectionChangeData: PEER_EVENT_CONNECTION_CHANGE_DATA, nodeChangeData: PEER_EVENT_NODE_CHANGE_DATA, synchronizedData: PEER_EVENT_SYNCHRONIZED_DATA, }, }; pub const PFNPEER_VALIDATE_RECORD = fn( hGraph: ?*anyopaque, pvContext: ?*anyopaque, pRecord: ?*PEER_RECORD, changeType: PEER_RECORD_CHANGE_TYPE, ) callconv(@import("std").os.windows.WINAPI) HRESULT; pub const PFNPEER_SECURE_RECORD = fn( hGraph: ?*anyopaque, pvContext: ?*anyopaque, pRecord: ?*PEER_RECORD, changeType: PEER_RECORD_CHANGE_TYPE, ppSecurityData: ?*?*PEER_DATA, ) callconv(@import("std").os.windows.WINAPI) HRESULT; pub const PFNPEER_FREE_SECURITY_DATA = fn( hGraph: ?*anyopaque, pvContext: ?*anyopaque, pSecurityData: ?*PEER_DATA, ) callconv(@import("std").os.windows.WINAPI) HRESULT; pub const PFNPEER_ON_PASSWORD_AUTH_FAILED = fn( hGraph: ?*anyopaque, pvContext: ?*anyopaque, ) callconv(@import("std").os.windows.WINAPI) HRESULT; pub const PEER_SECURITY_INTERFACE = extern struct { dwSize: u32, pwzSspFilename: ?PWSTR, pwzPackageName: ?PWSTR, cbSecurityInfo: u32, pbSecurityInfo: ?*u8, pvContext: ?*anyopaque, pfnValidateRecord: ?PFNPEER_VALIDATE_RECORD, pfnSecureRecord: ?PFNPEER_SECURE_RECORD, pfnFreeSecurityData: ?PFNPEER_FREE_SECURITY_DATA, pfnAuthFailed: ?PFNPEER_ON_PASSWORD_AUTH_FAILED, }; pub const PEER_GROUP_EVENT_TYPE = enum(i32) { STATUS_CHANGED = 1, PROPERTY_CHANGED = 2, RECORD_CHANGED = 3, DIRECT_CONNECTION = 4, NEIGHBOR_CONNECTION = 5, INCOMING_DATA = 6, MEMBER_CHANGED = 8, CONNECTION_FAILED = 10, AUTHENTICATION_FAILED = 11, }; pub const PEER_GROUP_EVENT_STATUS_CHANGED = PEER_GROUP_EVENT_TYPE.STATUS_CHANGED; pub const PEER_GROUP_EVENT_PROPERTY_CHANGED = PEER_GROUP_EVENT_TYPE.PROPERTY_CHANGED; pub const PEER_GROUP_EVENT_RECORD_CHANGED = PEER_GROUP_EVENT_TYPE.RECORD_CHANGED; pub const PEER_GROUP_EVENT_DIRECT_CONNECTION = PEER_GROUP_EVENT_TYPE.DIRECT_CONNECTION; pub const PEER_GROUP_EVENT_NEIGHBOR_CONNECTION = PEER_GROUP_EVENT_TYPE.NEIGHBOR_CONNECTION; pub const PEER_GROUP_EVENT_INCOMING_DATA = PEER_GROUP_EVENT_TYPE.INCOMING_DATA; pub const PEER_GROUP_EVENT_MEMBER_CHANGED = PEER_GROUP_EVENT_TYPE.MEMBER_CHANGED; pub const PEER_GROUP_EVENT_CONNECTION_FAILED = PEER_GROUP_EVENT_TYPE.CONNECTION_FAILED; pub const PEER_GROUP_EVENT_AUTHENTICATION_FAILED = PEER_GROUP_EVENT_TYPE.AUTHENTICATION_FAILED; pub const PEER_GROUP_STATUS = enum(i32) { LISTENING = 1, HAS_CONNECTIONS = 2, }; pub const PEER_GROUP_STATUS_LISTENING = PEER_GROUP_STATUS.LISTENING; pub const PEER_GROUP_STATUS_HAS_CONNECTIONS = PEER_GROUP_STATUS.HAS_CONNECTIONS; pub const PEER_GROUP_PROPERTY_FLAGS = enum(i32) { MEMBER_DATA_OPTIONAL = 1, DISABLE_PRESENCE = 2, DEFER_EXPIRATION = 4, }; pub const PEER_MEMBER_DATA_OPTIONAL = PEER_GROUP_PROPERTY_FLAGS.MEMBER_DATA_OPTIONAL; pub const PEER_DISABLE_PRESENCE = PEER_GROUP_PROPERTY_FLAGS.DISABLE_PRESENCE; pub const PEER_DEFER_EXPIRATION = PEER_GROUP_PROPERTY_FLAGS.DEFER_EXPIRATION; pub const PEER_GROUP_AUTHENTICATION_SCHEME = enum(i32) { GMC_AUTHENTICATION = 1, PASSWORD_AUTHENTICATION = 2, }; pub const PEER_GROUP_GMC_AUTHENTICATION = PEER_GROUP_AUTHENTICATION_SCHEME.GMC_AUTHENTICATION; pub const PEER_GROUP_PASSWORD_AUTHENTICATION = PEER_GROUP_AUTHENTICATION_SCHEME.PASSWORD_AUTHENTICATION; pub const PEER_MEMBER_FLAGS = enum(i32) { T = 1, }; pub const PEER_MEMBER_PRESENT = PEER_MEMBER_FLAGS.T; pub const PEER_MEMBER_CHANGE_TYPE = enum(i32) { CONNECTED = 1, DISCONNECTED = 2, UPDATED = 3, JOINED = 4, LEFT = 5, }; pub const PEER_MEMBER_CONNECTED = PEER_MEMBER_CHANGE_TYPE.CONNECTED; pub const PEER_MEMBER_DISCONNECTED = PEER_MEMBER_CHANGE_TYPE.DISCONNECTED; pub const PEER_MEMBER_UPDATED = PEER_MEMBER_CHANGE_TYPE.UPDATED; pub const PEER_MEMBER_JOINED = PEER_MEMBER_CHANGE_TYPE.JOINED; pub const PEER_MEMBER_LEFT = PEER_MEMBER_CHANGE_TYPE.LEFT; pub const PEER_GROUP_ISSUE_CREDENTIAL_FLAGS = enum(i32) { S = 1, }; pub const PEER_GROUP_STORE_CREDENTIALS = PEER_GROUP_ISSUE_CREDENTIAL_FLAGS.S; pub const PEER_CREDENTIAL_INFO = extern struct { dwSize: u32, dwFlags: u32, pwzFriendlyName: ?PWSTR, pPublicKey: ?*CERT_PUBLIC_KEY_INFO, pwzIssuerPeerName: ?PWSTR, pwzIssuerFriendlyName: ?PWSTR, ftValidityStart: FILETIME, ftValidityEnd: FILETIME, cRoles: u32, pRoles: ?*Guid, }; pub const PEER_MEMBER = extern struct { dwSize: u32, dwFlags: u32, pwzIdentity: ?PWSTR, pwzAttributes: ?PWSTR, ullNodeId: u64, cAddresses: u32, pAddresses: ?*PEER_ADDRESS, pCredentialInfo: ?*PEER_CREDENTIAL_INFO, }; pub const PEER_INVITATION_INFO = extern struct { dwSize: u32, dwFlags: u32, pwzCloudName: ?PWSTR, dwScope: u32, dwCloudFlags: u32, pwzGroupPeerName: ?PWSTR, pwzIssuerPeerName: ?PWSTR, pwzSubjectPeerName: ?PWSTR, pwzGroupFriendlyName: ?PWSTR, pwzIssuerFriendlyName: ?PWSTR, pwzSubjectFriendlyName: ?PWSTR, ftValidityStart: FILETIME, ftValidityEnd: FILETIME, cRoles: u32, pRoles: ?*Guid, cClassifiers: u32, ppwzClassifiers: ?*?PWSTR, pSubjectPublicKey: ?*CERT_PUBLIC_KEY_INFO, authScheme: PEER_GROUP_AUTHENTICATION_SCHEME, }; pub const PEER_GROUP_PROPERTIES = extern struct { dwSize: u32, dwFlags: u32, pwzCloud: ?PWSTR, pwzClassifier: ?PWSTR, pwzGroupPeerName: ?PWSTR, pwzCreatorPeerName: ?PWSTR, pwzFriendlyName: ?PWSTR, pwzComment: ?PWSTR, ulMemberDataLifetime: u32, ulPresenceLifetime: u32, dwAuthenticationSchemes: u32, pwzGroupPassword: ?PWSTR, groupPasswordRole: Guid, }; pub const PEER_EVENT_MEMBER_CHANGE_DATA = extern struct { dwSize: u32, changeType: PEER_MEMBER_CHANGE_TYPE, pwzIdentity: ?PWSTR, }; pub const PEER_GROUP_EVENT_REGISTRATION = extern struct { eventType: PEER_GROUP_EVENT_TYPE, pType: ?*Guid, }; pub const PEER_GROUP_EVENT_DATA = extern struct { eventType: PEER_GROUP_EVENT_TYPE, Anonymous: extern union { dwStatus: PEER_GROUP_STATUS, incomingData: PEER_EVENT_INCOMING_DATA, recordChangeData: PEER_EVENT_RECORD_CHANGE_DATA, connectionChangeData: PEER_EVENT_CONNECTION_CHANGE_DATA, memberChangeData: PEER_EVENT_MEMBER_CHANGE_DATA, hrConnectionFailedReason: HRESULT, }, }; pub const PEER_NAME_PAIR = extern struct { dwSize: u32, pwzPeerName: ?PWSTR, pwzFriendlyName: ?PWSTR, }; pub const PEER_SIGNIN_FLAGS = enum(i32) { NONE = 0, NEAR_ME = 1, INTERNET = 2, ALL = 3, }; pub const PEER_SIGNIN_NONE = PEER_SIGNIN_FLAGS.NONE; pub const PEER_SIGNIN_NEAR_ME = PEER_SIGNIN_FLAGS.NEAR_ME; pub const PEER_SIGNIN_INTERNET = PEER_SIGNIN_FLAGS.INTERNET; pub const PEER_SIGNIN_ALL = PEER_SIGNIN_FLAGS.ALL; pub const PEER_WATCH_PERMISSION = enum(i32) { BLOCKED = 0, ALLOWED = 1, }; pub const PEER_WATCH_BLOCKED = PEER_WATCH_PERMISSION.BLOCKED; pub const PEER_WATCH_ALLOWED = PEER_WATCH_PERMISSION.ALLOWED; pub const PEER_PUBLICATION_SCOPE = enum(i32) { NONE = 0, NEAR_ME = 1, INTERNET = 2, ALL = 3, }; pub const PEER_PUBLICATION_SCOPE_NONE = PEER_PUBLICATION_SCOPE.NONE; pub const PEER_PUBLICATION_SCOPE_NEAR_ME = PEER_PUBLICATION_SCOPE.NEAR_ME; pub const PEER_PUBLICATION_SCOPE_INTERNET = PEER_PUBLICATION_SCOPE.INTERNET; pub const PEER_PUBLICATION_SCOPE_ALL = PEER_PUBLICATION_SCOPE.ALL; pub const PEER_APPLICATION = extern struct { id: Guid, data: PEER_DATA, pwzDescription: ?PWSTR, }; pub const PEER_OBJECT = extern struct { id: Guid, data: PEER_DATA, dwPublicationScope: u32, }; pub const PEER_CONTACT = extern struct { pwzPeerName: ?PWSTR, pwzNickName: ?PWSTR, pwzDisplayName: ?PWSTR, pwzEmailAddress: ?PWSTR, fWatch: BOOL, WatcherPermissions: PEER_WATCH_PERMISSION, credentials: PEER_DATA, }; pub const PEER_ENDPOINT = extern struct { address: PEER_ADDRESS, pwzEndpointName: ?PWSTR, }; pub const PEER_PEOPLE_NEAR_ME = extern struct { pwzNickName: ?PWSTR, endpoint: PEER_ENDPOINT, id: Guid, }; pub const PEER_INVITATION_RESPONSE_TYPE = enum(i32) { DECLINED = 0, ACCEPTED = 1, EXPIRED = 2, ERROR = 3, }; pub const PEER_INVITATION_RESPONSE_DECLINED = PEER_INVITATION_RESPONSE_TYPE.DECLINED; pub const PEER_INVITATION_RESPONSE_ACCEPTED = PEER_INVITATION_RESPONSE_TYPE.ACCEPTED; pub const PEER_INVITATION_RESPONSE_EXPIRED = PEER_INVITATION_RESPONSE_TYPE.EXPIRED; pub const PEER_INVITATION_RESPONSE_ERROR = PEER_INVITATION_RESPONSE_TYPE.ERROR; pub const PEER_APPLICATION_REGISTRATION_TYPE = enum(i32) { CURRENT_USER = 0, ALL_USERS = 1, }; pub const PEER_APPLICATION_CURRENT_USER = PEER_APPLICATION_REGISTRATION_TYPE.CURRENT_USER; pub const PEER_APPLICATION_ALL_USERS = PEER_APPLICATION_REGISTRATION_TYPE.ALL_USERS; pub const PEER_INVITATION = extern struct { applicationId: Guid, applicationData: PEER_DATA, pwzMessage: ?PWSTR, }; pub const PEER_INVITATION_RESPONSE = extern struct { action: PEER_INVITATION_RESPONSE_TYPE, pwzMessage: ?PWSTR, hrExtendedInfo: HRESULT, }; pub const PEER_APP_LAUNCH_INFO = extern struct { pContact: ?*PEER_CONTACT, pEndpoint: ?*PEER_ENDPOINT, pInvitation: ?*PEER_INVITATION, }; pub const PEER_APPLICATION_REGISTRATION_INFO = extern struct { application: PEER_APPLICATION, pwzApplicationToLaunch: ?PWSTR, pwzApplicationArguments: ?PWSTR, dwPublicationScope: u32, }; pub const PEER_PRESENCE_STATUS = enum(i32) { OFFLINE = 0, OUT_TO_LUNCH = 1, AWAY = 2, BE_RIGHT_BACK = 3, IDLE = 4, BUSY = 5, ON_THE_PHONE = 6, ONLINE = 7, }; pub const PEER_PRESENCE_OFFLINE = PEER_PRESENCE_STATUS.OFFLINE; pub const PEER_PRESENCE_OUT_TO_LUNCH = PEER_PRESENCE_STATUS.OUT_TO_LUNCH; pub const PEER_PRESENCE_AWAY = PEER_PRESENCE_STATUS.AWAY; pub const PEER_PRESENCE_BE_RIGHT_BACK = PEER_PRESENCE_STATUS.BE_RIGHT_BACK; pub const PEER_PRESENCE_IDLE = PEER_PRESENCE_STATUS.IDLE; pub const PEER_PRESENCE_BUSY = PEER_PRESENCE_STATUS.BUSY; pub const PEER_PRESENCE_ON_THE_PHONE = PEER_PRESENCE_STATUS.ON_THE_PHONE; pub const PEER_PRESENCE_ONLINE = PEER_PRESENCE_STATUS.ONLINE; pub const PEER_PRESENCE_INFO = extern struct { status: PEER_PRESENCE_STATUS, pwzDescriptiveText: ?PWSTR, }; pub const PEER_CHANGE_TYPE = enum(i32) { ADDED = 0, DELETED = 1, UPDATED = 2, }; pub const PEER_CHANGE_ADDED = PEER_CHANGE_TYPE.ADDED; pub const PEER_CHANGE_DELETED = PEER_CHANGE_TYPE.DELETED; pub const PEER_CHANGE_UPDATED = PEER_CHANGE_TYPE.UPDATED; pub const PEER_COLLAB_EVENT_TYPE = enum(i32) { WATCHLIST_CHANGED = 1, ENDPOINT_CHANGED = 2, ENDPOINT_PRESENCE_CHANGED = 3, ENDPOINT_APPLICATION_CHANGED = 4, ENDPOINT_OBJECT_CHANGED = 5, MY_ENDPOINT_CHANGED = 6, MY_PRESENCE_CHANGED = 7, MY_APPLICATION_CHANGED = 8, MY_OBJECT_CHANGED = 9, PEOPLE_NEAR_ME_CHANGED = 10, REQUEST_STATUS_CHANGED = 11, }; pub const PEER_EVENT_WATCHLIST_CHANGED = PEER_COLLAB_EVENT_TYPE.WATCHLIST_CHANGED; pub const PEER_EVENT_ENDPOINT_CHANGED = PEER_COLLAB_EVENT_TYPE.ENDPOINT_CHANGED; pub const PEER_EVENT_ENDPOINT_PRESENCE_CHANGED = PEER_COLLAB_EVENT_TYPE.ENDPOINT_PRESENCE_CHANGED; pub const PEER_EVENT_ENDPOINT_APPLICATION_CHANGED = PEER_COLLAB_EVENT_TYPE.ENDPOINT_APPLICATION_CHANGED; pub const PEER_EVENT_ENDPOINT_OBJECT_CHANGED = PEER_COLLAB_EVENT_TYPE.ENDPOINT_OBJECT_CHANGED; pub const PEER_EVENT_MY_ENDPOINT_CHANGED = PEER_COLLAB_EVENT_TYPE.MY_ENDPOINT_CHANGED; pub const PEER_EVENT_MY_PRESENCE_CHANGED = PEER_COLLAB_EVENT_TYPE.MY_PRESENCE_CHANGED; pub const PEER_EVENT_MY_APPLICATION_CHANGED = PEER_COLLAB_EVENT_TYPE.MY_APPLICATION_CHANGED; pub const PEER_EVENT_MY_OBJECT_CHANGED = PEER_COLLAB_EVENT_TYPE.MY_OBJECT_CHANGED; pub const PEER_EVENT_PEOPLE_NEAR_ME_CHANGED = PEER_COLLAB_EVENT_TYPE.PEOPLE_NEAR_ME_CHANGED; pub const PEER_EVENT_REQUEST_STATUS_CHANGED = PEER_COLLAB_EVENT_TYPE.REQUEST_STATUS_CHANGED; pub const PEER_COLLAB_EVENT_REGISTRATION = extern struct { eventType: PEER_COLLAB_EVENT_TYPE, pInstance: ?*Guid, }; pub const PEER_EVENT_WATCHLIST_CHANGED_DATA = extern struct { pContact: ?*PEER_CONTACT, changeType: PEER_CHANGE_TYPE, }; pub const PEER_EVENT_PRESENCE_CHANGED_DATA = extern struct { pContact: ?*PEER_CONTACT, pEndpoint: ?*PEER_ENDPOINT, changeType: PEER_CHANGE_TYPE, pPresenceInfo: ?*PEER_PRESENCE_INFO, }; pub const PEER_EVENT_APPLICATION_CHANGED_DATA = extern struct { pContact: ?*PEER_CONTACT, pEndpoint: ?*PEER_ENDPOINT, changeType: PEER_CHANGE_TYPE, pApplication: ?*PEER_APPLICATION, }; pub const PEER_EVENT_OBJECT_CHANGED_DATA = extern struct { pContact: ?*PEER_CONTACT, pEndpoint: ?*PEER_ENDPOINT, changeType: PEER_CHANGE_TYPE, pObject: ?*PEER_OBJECT, }; pub const PEER_EVENT_ENDPOINT_CHANGED_DATA = extern struct { pContact: ?*PEER_CONTACT, pEndpoint: ?*PEER_ENDPOINT, }; pub const PEER_EVENT_PEOPLE_NEAR_ME_CHANGED_DATA = extern struct { changeType: PEER_CHANGE_TYPE, pPeopleNearMe: ?*PEER_PEOPLE_NEAR_ME, }; pub const PEER_EVENT_REQUEST_STATUS_CHANGED_DATA = extern struct { pEndpoint: ?*PEER_ENDPOINT, hrChange: HRESULT, }; pub const PEER_COLLAB_EVENT_DATA = extern struct { eventType: PEER_COLLAB_EVENT_TYPE, Anonymous: extern union { watchListChangedData: PEER_EVENT_WATCHLIST_CHANGED_DATA, presenceChangedData: PEER_EVENT_PRESENCE_CHANGED_DATA, applicationChangedData: PEER_EVENT_APPLICATION_CHANGED_DATA, objectChangedData: PEER_EVENT_OBJECT_CHANGED_DATA, endpointChangedData: PEER_EVENT_ENDPOINT_CHANGED_DATA, peopleNearMeChangedData: PEER_EVENT_PEOPLE_NEAR_ME_CHANGED_DATA, requestStatusChangedData: PEER_EVENT_REQUEST_STATUS_CHANGED_DATA, }, }; pub const PEER_PNRP_ENDPOINT_INFO = extern struct { pwzPeerName: ?PWSTR, cAddresses: u32, ppAddresses: ?*?*SOCKADDR, pwzComment: ?PWSTR, payload: PEER_DATA, }; pub const PEER_PNRP_CLOUD_INFO = extern struct { pwzCloudName: ?PWSTR, dwScope: PNRP_SCOPE, dwScopeId: u32, }; pub const PEER_PNRP_REGISTRATION_INFO = extern struct { pwzCloudName: ?PWSTR, pwzPublishingIdentity: ?PWSTR, cAddresses: u32, ppAddresses: ?*?*SOCKADDR, wPort: u16, pwzComment: ?PWSTR, payload: PEER_DATA, }; pub const DRT_SCOPE = enum(i32) { GLOBAL_SCOPE = 1, SITE_LOCAL_SCOPE = 2, LINK_LOCAL_SCOPE = 3, }; pub const DRT_GLOBAL_SCOPE = DRT_SCOPE.GLOBAL_SCOPE; pub const DRT_SITE_LOCAL_SCOPE = DRT_SCOPE.SITE_LOCAL_SCOPE; pub const DRT_LINK_LOCAL_SCOPE = DRT_SCOPE.LINK_LOCAL_SCOPE; pub const DRT_STATUS = enum(i32) { ACTIVE = 0, ALONE = 1, NO_NETWORK = 10, FAULTED = 20, }; pub const DRT_ACTIVE = DRT_STATUS.ACTIVE; pub const DRT_ALONE = DRT_STATUS.ALONE; pub const DRT_NO_NETWORK = DRT_STATUS.NO_NETWORK; pub const DRT_FAULTED = DRT_STATUS.FAULTED; pub const DRT_MATCH_TYPE = enum(i32) { EXACT = 0, NEAR = 1, INTERMEDIATE = 2, }; pub const DRT_MATCH_EXACT = DRT_MATCH_TYPE.EXACT; pub const DRT_MATCH_NEAR = DRT_MATCH_TYPE.NEAR; pub const DRT_MATCH_INTERMEDIATE = DRT_MATCH_TYPE.INTERMEDIATE; pub const DRT_LEAFSET_KEY_CHANGE_TYPE = enum(i32) { ADDED = 0, DELETED = 1, }; pub const DRT_LEAFSET_KEY_ADDED = DRT_LEAFSET_KEY_CHANGE_TYPE.ADDED; pub const DRT_LEAFSET_KEY_DELETED = DRT_LEAFSET_KEY_CHANGE_TYPE.DELETED; pub const DRT_EVENT_TYPE = enum(i32) { STATUS_CHANGED = 0, LEAFSET_KEY_CHANGED = 1, REGISTRATION_STATE_CHANGED = 2, }; pub const DRT_EVENT_STATUS_CHANGED = DRT_EVENT_TYPE.STATUS_CHANGED; pub const DRT_EVENT_LEAFSET_KEY_CHANGED = DRT_EVENT_TYPE.LEAFSET_KEY_CHANGED; pub const DRT_EVENT_REGISTRATION_STATE_CHANGED = DRT_EVENT_TYPE.REGISTRATION_STATE_CHANGED; pub const DRT_SECURITY_MODE = enum(i32) { RESOLVE = 0, MEMBERSHIP = 1, CONFIDENTIALPAYLOAD = 2, }; pub const DRT_SECURE_RESOLVE = DRT_SECURITY_MODE.RESOLVE; pub const DRT_SECURE_MEMBERSHIP = DRT_SECURITY_MODE.MEMBERSHIP; pub const DRT_SECURE_CONFIDENTIALPAYLOAD = DRT_SECURITY_MODE.CONFIDENTIALPAYLOAD; pub const DRT_REGISTRATION_STATE = enum(i32) { E = 1, }; pub const DRT_REGISTRATION_STATE_UNRESOLVEABLE = DRT_REGISTRATION_STATE.E; pub const DRT_ADDRESS_FLAGS = enum(i32) { ACCEPTED = 1, REJECTED = 2, UNREACHABLE = 4, LOOP = 8, TOO_BUSY = 16, BAD_VALIDATE_ID = 32, SUSPECT_UNREGISTERED_ID = 64, INQUIRE = 128, }; pub const DRT_ADDRESS_FLAG_ACCEPTED = DRT_ADDRESS_FLAGS.ACCEPTED; pub const DRT_ADDRESS_FLAG_REJECTED = DRT_ADDRESS_FLAGS.REJECTED; pub const DRT_ADDRESS_FLAG_UNREACHABLE = DRT_ADDRESS_FLAGS.UNREACHABLE; pub const DRT_ADDRESS_FLAG_LOOP = DRT_ADDRESS_FLAGS.LOOP; pub const DRT_ADDRESS_FLAG_TOO_BUSY = DRT_ADDRESS_FLAGS.TOO_BUSY; pub const DRT_ADDRESS_FLAG_BAD_VALIDATE_ID = DRT_ADDRESS_FLAGS.BAD_VALIDATE_ID; pub const DRT_ADDRESS_FLAG_SUSPECT_UNREGISTERED_ID = DRT_ADDRESS_FLAGS.SUSPECT_UNREGISTERED_ID; pub const DRT_ADDRESS_FLAG_INQUIRE = DRT_ADDRESS_FLAGS.INQUIRE; pub const DRT_DATA = extern struct { cb: u32, pb: ?*u8, }; pub const DRT_REGISTRATION = extern struct { key: DRT_DATA, appData: DRT_DATA, }; pub const DRT_SECURITY_PROVIDER = extern struct { pvContext: ?*anyopaque, Attach: isize, Detach: isize, RegisterKey: isize, UnregisterKey: isize, ValidateAndUnpackPayload: isize, SecureAndPackPayload: isize, FreeData: isize, EncryptData: isize, DecryptData: isize, GetSerializedCredential: isize, ValidateRemoteCredential: isize, SignData: isize, VerifyData: isize, }; pub const DRT_BOOTSTRAP_RESOLVE_CALLBACK = fn( hr: HRESULT, pvContext: ?*anyopaque, pAddresses: ?*SOCKET_ADDRESS_LIST, fFatalError: BOOL, ) callconv(@import("std").os.windows.WINAPI) void; pub const DRT_BOOTSTRAP_PROVIDER = extern struct { pvContext: ?*anyopaque, Attach: isize, Detach: isize, InitResolve: isize, IssueResolve: isize, EndResolve: isize, Register: isize, Unregister: isize, }; pub const DRT_SETTINGS = extern struct { dwSize: u32, cbKey: u32, bProtocolMajorVersion: u8, bProtocolMinorVersion: u8, ulMaxRoutingAddresses: u32, pwzDrtInstancePrefix: ?PWSTR, hTransport: ?*anyopaque, pSecurityProvider: ?*DRT_SECURITY_PROVIDER, pBootstrapProvider: ?*DRT_BOOTSTRAP_PROVIDER, eSecurityMode: DRT_SECURITY_MODE, }; pub const DRT_SEARCH_INFO = extern struct { dwSize: u32, fIterative: BOOL, fAllowCurrentInstanceMatch: BOOL, fAnyMatchInRange: BOOL, cMaxEndpoints: u32, pMaximumKey: ?*DRT_DATA, pMinimumKey: ?*DRT_DATA, }; pub const DRT_ADDRESS = extern struct { socketAddress: SOCKADDR_STORAGE, flags: u32, nearness: i32, latency: u32, }; pub const DRT_ADDRESS_LIST = extern struct { AddressCount: u32, AddressList: [1]DRT_ADDRESS, }; pub const DRT_SEARCH_RESULT = extern struct { dwSize: u32, type: DRT_MATCH_TYPE, pvContext: ?*anyopaque, registration: DRT_REGISTRATION, }; pub const DRT_EVENT_DATA = extern struct { type: DRT_EVENT_TYPE, hr: HRESULT, pvContext: ?*anyopaque, Anonymous: extern union { leafsetKeyChange: extern struct { change: DRT_LEAFSET_KEY_CHANGE_TYPE, localKey: DRT_DATA, remoteKey: DRT_DATA, }, registrationStateChange: extern struct { state: DRT_REGISTRATION_STATE, localKey: DRT_DATA, }, statusChange: extern struct { status: DRT_STATUS, bootstrapAddresses: extern struct { cntAddress: u32, pAddresses: ?*SOCKADDR_STORAGE, }, }, }, }; pub const PEERDIST_STATUS = enum(i32) { DISABLED = 0, UNAVAILABLE = 1, AVAILABLE = 2, }; pub const PEERDIST_STATUS_DISABLED = PEERDIST_STATUS.DISABLED; pub const PEERDIST_STATUS_UNAVAILABLE = PEERDIST_STATUS.UNAVAILABLE; pub const PEERDIST_STATUS_AVAILABLE = PEERDIST_STATUS.AVAILABLE; pub const PEERDIST_PUBLICATION_OPTIONS = extern struct { dwVersion: u32, dwFlags: u32, }; pub const PEERDIST_CONTENT_TAG = extern struct { Data: [16]u8, }; pub const PEERDIST_RETRIEVAL_OPTIONS = extern struct { cbSize: u32, dwContentInfoMinVersion: u32, dwContentInfoMaxVersion: u32, dwReserved: u32, }; pub const PEERDIST_STATUS_INFO = extern struct { cbSize: u32, status: PEERDIST_STATUS, dwMinVer: PEERDIST_RETRIEVAL_OPTIONS_CONTENTINFO_VERSION_VALUE, dwMaxVer: PEERDIST_RETRIEVAL_OPTIONS_CONTENTINFO_VERSION_VALUE, }; pub const PEERDIST_CLIENT_INFO_BY_HANDLE_CLASS = enum(i32) { PeerDistClientBasicInfo = 0, MaximumPeerDistClientInfoByHandlesClass = 1, }; pub const PeerDistClientBasicInfo = PEERDIST_CLIENT_INFO_BY_HANDLE_CLASS.PeerDistClientBasicInfo; pub const MaximumPeerDistClientInfoByHandlesClass = PEERDIST_CLIENT_INFO_BY_HANDLE_CLASS.MaximumPeerDistClientInfoByHandlesClass; pub const PEERDIST_CLIENT_BASIC_INFO = extern struct { fFlashCrowd: BOOL, }; //-------------------------------------------------------------------------------- // Section: Functions (200) //-------------------------------------------------------------------------------- // TODO: this type is limited to platform 'windows5.1.2600' pub extern "P2PGRAPH" fn PeerGraphStartup( wVersionRequested: u16, pVersionData: ?*PEER_VERSION_DATA, ) callconv(@import("std").os.windows.WINAPI) HRESULT; // TODO: this type is limited to platform 'windows5.1.2600' pub extern "P2PGRAPH" fn PeerGraphShutdown( ) callconv(@import("std").os.windows.WINAPI) HRESULT; // TODO: this type is limited to platform 'windows5.1.2600' pub extern "P2PGRAPH" fn PeerGraphFreeData( pvData: ?*anyopaque, ) callconv(@import("std").os.windows.WINAPI) void; // TODO: this type is limited to platform 'windows5.1.2600' pub extern "P2PGRAPH" fn PeerGraphGetItemCount( hPeerEnum: ?*anyopaque, pCount: ?*u32, ) callconv(@import("std").os.windows.WINAPI) HRESULT; // TODO: this type is limited to platform 'windows5.1.2600' pub extern "P2PGRAPH" fn PeerGraphGetNextItem( hPeerEnum: ?*anyopaque, pCount: ?*u32, pppvItems: ?*?*?*anyopaque, ) callconv(@import("std").os.windows.WINAPI) HRESULT; // TODO: this type is limited to platform 'windows5.1.2600' pub extern "P2PGRAPH" fn PeerGraphEndEnumeration( hPeerEnum: ?*anyopaque, ) callconv(@import("std").os.windows.WINAPI) HRESULT; // TODO: this type is limited to platform 'windows5.1.2600' pub extern "P2PGRAPH" fn PeerGraphCreate( pGraphProperties: ?*PEER_GRAPH_PROPERTIES, pwzDatabaseName: ?[*:0]const u16, pSecurityInterface: ?*PEER_SECURITY_INTERFACE, phGraph: ?*?*anyopaque, ) callconv(@import("std").os.windows.WINAPI) HRESULT; // TODO: this type is limited to platform 'windows5.1.2600' pub extern "P2PGRAPH" fn PeerGraphOpen( pwzGraphId: ?[*:0]const u16, pwzPeerId: ?[*:0]const u16, pwzDatabaseName: ?[*:0]const u16, pSecurityInterface: ?*PEER_SECURITY_INTERFACE, cRecordTypeSyncPrecedence: u32, pRecordTypeSyncPrecedence: ?[*]const Guid, phGraph: ?*?*anyopaque, ) callconv(@import("std").os.windows.WINAPI) HRESULT; // TODO: this type is limited to platform 'windows5.1.2600' pub extern "P2PGRAPH" fn PeerGraphListen( hGraph: ?*anyopaque, dwScope: u32, dwScopeId: u32, wPort: u16, ) callconv(@import("std").os.windows.WINAPI) HRESULT; // TODO: this type is limited to platform 'windows5.1.2600' pub extern "P2PGRAPH" fn PeerGraphConnect( hGraph: ?*anyopaque, pwzPeerId: ?[*:0]const u16, pAddress: ?*PEER_ADDRESS, pullConnectionId: ?*u64, ) callconv(@import("std").os.windows.WINAPI) HRESULT; // TODO: this type is limited to platform 'windows5.1.2600' pub extern "P2PGRAPH" fn PeerGraphClose( hGraph: ?*anyopaque, ) callconv(@import("std").os.windows.WINAPI) HRESULT; // TODO: this type is limited to platform 'windows5.1.2600' pub extern "P2PGRAPH" fn PeerGraphDelete( pwzGraphId: ?[*:0]const u16, pwzPeerId: ?[*:0]const u16, pwzDatabaseName: ?[*:0]const u16, ) callconv(@import("std").os.windows.WINAPI) HRESULT; // TODO: this type is limited to platform 'windows5.1.2600' pub extern "P2PGRAPH" fn PeerGraphGetStatus( hGraph: ?*anyopaque, pdwStatus: ?*u32, ) callconv(@import("std").os.windows.WINAPI) HRESULT; // TODO: this type is limited to platform 'windows5.1.2600' pub extern "P2PGRAPH" fn PeerGraphGetProperties( hGraph: ?*anyopaque, ppGraphProperties: ?*?*PEER_GRAPH_PROPERTIES, ) callconv(@import("std").os.windows.WINAPI) HRESULT; // TODO: this type is limited to platform 'windows5.1.2600' pub extern "P2PGRAPH" fn PeerGraphSetProperties( hGraph: ?*anyopaque, pGraphProperties: ?*PEER_GRAPH_PROPERTIES, ) callconv(@import("std").os.windows.WINAPI) HRESULT; // TODO: this type is limited to platform 'windows5.1.2600' pub extern "P2PGRAPH" fn PeerGraphRegisterEvent( hGraph: ?*anyopaque, hEvent: ?HANDLE, cEventRegistrations: u32, pEventRegistrations: [*]PEER_GRAPH_EVENT_REGISTRATION, phPeerEvent: ?*?*anyopaque, ) callconv(@import("std").os.windows.WINAPI) HRESULT; // TODO: this type is limited to platform 'windows5.1.2600' pub extern "P2PGRAPH" fn PeerGraphUnregisterEvent( hPeerEvent: ?*anyopaque, ) callconv(@import("std").os.windows.WINAPI) HRESULT; // TODO: this type is limited to platform 'windows5.1.2600' pub extern "P2PGRAPH" fn PeerGraphGetEventData( hPeerEvent: ?*anyopaque, ppEventData: ?*?*PEER_GRAPH_EVENT_DATA, ) callconv(@import("std").os.windows.WINAPI) HRESULT; // TODO: this type is limited to platform 'windows5.1.2600' pub extern "P2PGRAPH" fn PeerGraphGetRecord( hGraph: ?*anyopaque, pRecordId: ?*const Guid, ppRecord: ?*?*PEER_RECORD, ) callconv(@import("std").os.windows.WINAPI) HRESULT; // TODO: this type is limited to platform 'windows5.1.2600' pub extern "P2PGRAPH" fn PeerGraphAddRecord( hGraph: ?*anyopaque, pRecord: ?*PEER_RECORD, pRecordId: ?*Guid, ) callconv(@import("std").os.windows.WINAPI) HRESULT; // TODO: this type is limited to platform 'windows5.1.2600' pub extern "P2PGRAPH" fn PeerGraphUpdateRecord( hGraph: ?*anyopaque, pRecord: ?*PEER_RECORD, ) callconv(@import("std").os.windows.WINAPI) HRESULT; // TODO: this type is limited to platform 'windows5.1.2600' pub extern "P2PGRAPH" fn PeerGraphDeleteRecord( hGraph: ?*anyopaque, pRecordId: ?*const Guid, fLocal: BOOL, ) callconv(@import("std").os.windows.WINAPI) HRESULT; // TODO: this type is limited to platform 'windows5.1.2600' pub extern "P2PGRAPH" fn PeerGraphEnumRecords( hGraph: ?*anyopaque, pRecordType: ?*const Guid, pwzPeerId: ?[*:0]const u16, phPeerEnum: ?*?*anyopaque, ) callconv(@import("std").os.windows.WINAPI) HRESULT; // TODO: this type is limited to platform 'windows5.1.2600' pub extern "P2PGRAPH" fn PeerGraphSearchRecords( hGraph: ?*anyopaque, pwzCriteria: ?[*:0]const u16, phPeerEnum: ?*?*anyopaque, ) callconv(@import("std").os.windows.WINAPI) HRESULT; // TODO: this type is limited to platform 'windows5.1.2600' pub extern "P2PGRAPH" fn PeerGraphExportDatabase( hGraph: ?*anyopaque, pwzFilePath: ?[*:0]const u16, ) callconv(@import("std").os.windows.WINAPI) HRESULT; // TODO: this type is limited to platform 'windows5.1.2600' pub extern "P2PGRAPH" fn PeerGraphImportDatabase( hGraph: ?*anyopaque, pwzFilePath: ?[*:0]const u16, ) callconv(@import("std").os.windows.WINAPI) HRESULT; // TODO: this type is limited to platform 'windows5.1.2600' pub extern "P2PGRAPH" fn PeerGraphValidateDeferredRecords( hGraph: ?*anyopaque, cRecordIds: u32, pRecordIds: [*]const Guid, ) callconv(@import("std").os.windows.WINAPI) HRESULT; // TODO: this type is limited to platform 'windows5.1.2600' pub extern "P2PGRAPH" fn PeerGraphOpenDirectConnection( hGraph: ?*anyopaque, pwzPeerId: ?[*:0]const u16, pAddress: ?*PEER_ADDRESS, pullConnectionId: ?*u64, ) callconv(@import("std").os.windows.WINAPI) HRESULT; // TODO: this type is limited to platform 'windows5.1.2600' pub extern "P2PGRAPH" fn PeerGraphSendData( hGraph: ?*anyopaque, ullConnectionId: u64, pType: ?*const Guid, cbData: u32, // TODO: what to do with BytesParamIndex 3? pvData: ?*anyopaque, ) callconv(@import("std").os.windows.WINAPI) HRESULT; // TODO: this type is limited to platform 'windows5.1.2600' pub extern "P2PGRAPH" fn PeerGraphCloseDirectConnection( hGraph: ?*anyopaque, ullConnectionId: u64, ) callconv(@import("std").os.windows.WINAPI) HRESULT; // TODO: this type is limited to platform 'windows5.1.2600' pub extern "P2PGRAPH" fn PeerGraphEnumConnections( hGraph: ?*anyopaque, dwFlags: u32, phPeerEnum: ?*?*anyopaque, ) callconv(@import("std").os.windows.WINAPI) HRESULT; // TODO: this type is limited to platform 'windows5.1.2600' pub extern "P2PGRAPH" fn PeerGraphEnumNodes( hGraph: ?*anyopaque, pwzPeerId: ?[*:0]const u16, phPeerEnum: ?*?*anyopaque, ) callconv(@import("std").os.windows.WINAPI) HRESULT; // TODO: this type is limited to platform 'windows5.1.2600' pub extern "P2PGRAPH" fn PeerGraphSetPresence( hGraph: ?*anyopaque, fPresent: BOOL, ) callconv(@import("std").os.windows.WINAPI) HRESULT; // TODO: this type is limited to platform 'windows5.1.2600' pub extern "P2PGRAPH" fn PeerGraphGetNodeInfo( hGraph: ?*anyopaque, ullNodeId: u64, ppNodeInfo: ?*?*PEER_NODE_INFO, ) callconv(@import("std").os.windows.WINAPI) HRESULT; // TODO: this type is limited to platform 'windows5.1.2600' pub extern "P2PGRAPH" fn PeerGraphSetNodeAttributes( hGraph: ?*anyopaque, pwzAttributes: ?[*:0]const u16, ) callconv(@import("std").os.windows.WINAPI) HRESULT; // TODO: this type is limited to platform 'windows5.1.2600' pub extern "P2PGRAPH" fn PeerGraphPeerTimeToUniversalTime( hGraph: ?*anyopaque, pftPeerTime: ?*FILETIME, pftUniversalTime: ?*FILETIME, ) callconv(@import("std").os.windows.WINAPI) HRESULT; // TODO: this type is limited to platform 'windows5.1.2600' pub extern "P2PGRAPH" fn PeerGraphUniversalTimeToPeerTime( hGraph: ?*anyopaque, pftUniversalTime: ?*FILETIME, pftPeerTime: ?*FILETIME, ) callconv(@import("std").os.windows.WINAPI) HRESULT; // TODO: this type is limited to platform 'windows5.1.2600' pub extern "P2P" fn PeerFreeData( pvData: ?*const anyopaque, ) callconv(@import("std").os.windows.WINAPI) void; // TODO: this type is limited to platform 'windows5.1.2600' pub extern "P2P" fn PeerGetItemCount( hPeerEnum: ?*anyopaque, pCount: ?*u32, ) callconv(@import("std").os.windows.WINAPI) HRESULT; // TODO: this type is limited to platform 'windows5.1.2600' pub extern "P2P" fn PeerGetNextItem( hPeerEnum: ?*anyopaque, pCount: ?*u32, pppvItems: ?*?*?*anyopaque, ) callconv(@import("std").os.windows.WINAPI) HRESULT; // TODO: this type is limited to platform 'windows5.1.2600' pub extern "P2P" fn PeerEndEnumeration( hPeerEnum: ?*anyopaque, ) callconv(@import("std").os.windows.WINAPI) HRESULT; // TODO: this type is limited to platform 'windows5.1.2600' pub extern "P2P" fn PeerGroupStartup( wVersionRequested: u16, pVersionData: ?*PEER_VERSION_DATA, ) callconv(@import("std").os.windows.WINAPI) HRESULT; // TODO: this type is limited to platform 'windows5.1.2600' pub extern "P2P" fn PeerGroupShutdown( ) callconv(@import("std").os.windows.WINAPI) HRESULT; // TODO: this type is limited to platform 'windows5.1.2600' pub extern "P2P" fn PeerGroupCreate( pProperties: ?*PEER_GROUP_PROPERTIES, phGroup: ?*?*anyopaque, ) callconv(@import("std").os.windows.WINAPI) HRESULT; // TODO: this type is limited to platform 'windows5.1.2600' pub extern "P2P" fn PeerGroupOpen( pwzIdentity: ?[*:0]const u16, pwzGroupPeerName: ?[*:0]const u16, pwzCloud: ?[*:0]const u16, phGroup: ?*?*anyopaque, ) callconv(@import("std").os.windows.WINAPI) HRESULT; // TODO: this type is limited to platform 'windows5.1.2600' pub extern "P2P" fn PeerGroupJoin( pwzIdentity: ?[*:0]const u16, pwzInvitation: ?[*:0]const u16, pwzCloud: ?[*:0]const u16, phGroup: ?*?*anyopaque, ) callconv(@import("std").os.windows.WINAPI) HRESULT; // TODO: this type is limited to platform 'windows5.1.2600' pub extern "P2P" fn PeerGroupPasswordJoin( pwzIdentity: ?[*:0]const u16, pwzInvitation: ?[*:0]const u16, pwzPassword: ?[*:0]const u16, pwzCloud: ?[*:0]const u16, phGroup: ?*?*anyopaque, ) callconv(@import("std").os.windows.WINAPI) HRESULT; // TODO: this type is limited to platform 'windows5.1.2600' pub extern "P2P" fn PeerGroupConnect( hGroup: ?*anyopaque, ) callconv(@import("std").os.windows.WINAPI) HRESULT; // TODO: this type is limited to platform 'windows5.1.2600' pub extern "P2P" fn PeerGroupConnectByAddress( hGroup: ?*anyopaque, cAddresses: u32, pAddresses: [*]PEER_ADDRESS, ) callconv(@import("std").os.windows.WINAPI) HRESULT; // TODO: this type is limited to platform 'windows5.1.2600' pub extern "P2P" fn PeerGroupClose( hGroup: ?*anyopaque, ) callconv(@import("std").os.windows.WINAPI) HRESULT; // TODO: this type is limited to platform 'windows5.1.2600' pub extern "P2P" fn PeerGroupDelete( pwzIdentity: ?[*:0]const u16, pwzGroupPeerName: ?[*:0]const u16, ) callconv(@import("std").os.windows.WINAPI) HRESULT; // TODO: this type is limited to platform 'windows5.1.2600' pub extern "P2P" fn PeerGroupCreateInvitation( hGroup: ?*anyopaque, pwzIdentityInfo: ?[*:0]const u16, pftExpiration: ?*FILETIME, cRoles: u32, pRoles: ?[*]const Guid, ppwzInvitation: ?*?PWSTR, ) callconv(@import("std").os.windows.WINAPI) HRESULT; // TODO: this type is limited to platform 'windows5.1.2600' pub extern "P2P" fn PeerGroupCreatePasswordInvitation( hGroup: ?*anyopaque, ppwzInvitation: ?*?PWSTR, ) callconv(@import("std").os.windows.WINAPI) HRESULT; // TODO: this type is limited to platform 'windows5.1.2600' pub extern "P2P" fn PeerGroupParseInvitation( pwzInvitation: ?[*:0]const u16, ppInvitationInfo: ?*?*PEER_INVITATION_INFO, ) callconv(@import("std").os.windows.WINAPI) HRESULT; // TODO: this type is limited to platform 'windows5.1.2600' pub extern "P2P" fn PeerGroupGetStatus( hGroup: ?*anyopaque, pdwStatus: ?*u32, ) callconv(@import("std").os.windows.WINAPI) HRESULT; // TODO: this type is limited to platform 'windows5.1.2600' pub extern "P2P" fn PeerGroupGetProperties( hGroup: ?*anyopaque, ppProperties: ?*?*PEER_GROUP_PROPERTIES, ) callconv(@import("std").os.windows.WINAPI) HRESULT; // TODO: this type is limited to platform 'windows5.1.2600' pub extern "P2P" fn PeerGroupSetProperties( hGroup: ?*anyopaque, pProperties: ?*PEER_GROUP_PROPERTIES, ) callconv(@import("std").os.windows.WINAPI) HRESULT; // TODO: this type is limited to platform 'windows5.1.2600' pub extern "P2P" fn PeerGroupEnumMembers( hGroup: ?*anyopaque, dwFlags: u32, pwzIdentity: ?[*:0]const u16, phPeerEnum: ?*?*anyopaque, ) callconv(@import("std").os.windows.WINAPI) HRESULT; // TODO: this type is limited to platform 'windows5.1.2600' pub extern "P2P" fn PeerGroupOpenDirectConnection( hGroup: ?*anyopaque, pwzIdentity: ?[*:0]const u16, pAddress: ?*PEER_ADDRESS, pullConnectionId: ?*u64, ) callconv(@import("std").os.windows.WINAPI) HRESULT; // TODO: this type is limited to platform 'windows5.1.2600' pub extern "P2P" fn PeerGroupCloseDirectConnection( hGroup: ?*anyopaque, ullConnectionId: u64, ) callconv(@import("std").os.windows.WINAPI) HRESULT; // TODO: this type is limited to platform 'windows5.1.2600' pub extern "P2P" fn PeerGroupEnumConnections( hGroup: ?*anyopaque, dwFlags: u32, phPeerEnum: ?*?*anyopaque, ) callconv(@import("std").os.windows.WINAPI) HRESULT; // TODO: this type is limited to platform 'windows5.1.2600' pub extern "P2P" fn PeerGroupSendData( hGroup: ?*anyopaque, ullConnectionId: u64, pType: ?*const Guid, cbData: u32, // TODO: what to do with BytesParamIndex 3? pvData: ?*anyopaque, ) callconv(@import("std").os.windows.WINAPI) HRESULT; // TODO: this type is limited to platform 'windows5.1.2600' pub extern "P2P" fn PeerGroupRegisterEvent( hGroup: ?*anyopaque, hEvent: ?HANDLE, cEventRegistration: u32, pEventRegistrations: [*]PEER_GROUP_EVENT_REGISTRATION, phPeerEvent: ?*?*anyopaque, ) callconv(@import("std").os.windows.WINAPI) HRESULT; // TODO: this type is limited to platform 'windows5.1.2600' pub extern "P2P" fn PeerGroupUnregisterEvent( hPeerEvent: ?*anyopaque, ) callconv(@import("std").os.windows.WINAPI) HRESULT; // TODO: this type is limited to platform 'windows5.1.2600' pub extern "P2P" fn PeerGroupGetEventData( hPeerEvent: ?*anyopaque, ppEventData: ?*?*PEER_GROUP_EVENT_DATA, ) callconv(@import("std").os.windows.WINAPI) HRESULT; // TODO: this type is limited to platform 'windows5.1.2600' pub extern "P2P" fn PeerGroupGetRecord( hGroup: ?*anyopaque, pRecordId: ?*const Guid, ppRecord: ?*?*PEER_RECORD, ) callconv(@import("std").os.windows.WINAPI) HRESULT; // TODO: this type is limited to platform 'windows5.1.2600' pub extern "P2P" fn PeerGroupAddRecord( hGroup: ?*anyopaque, pRecord: ?*PEER_RECORD, pRecordId: ?*Guid, ) callconv(@import("std").os.windows.WINAPI) HRESULT; // TODO: this type is limited to platform 'windows5.1.2600' pub extern "P2P" fn PeerGroupUpdateRecord( hGroup: ?*anyopaque, pRecord: ?*PEER_RECORD, ) callconv(@import("std").os.windows.WINAPI) HRESULT; // TODO: this type is limited to platform 'windows5.1.2600' pub extern "P2P" fn PeerGroupDeleteRecord( hGroup: ?*anyopaque, pRecordId: ?*const Guid, ) callconv(@import("std").os.windows.WINAPI) HRESULT; // TODO: this type is limited to platform 'windows5.1.2600' pub extern "P2P" fn PeerGroupEnumRecords( hGroup: ?*anyopaque, pRecordType: ?*const Guid, phPeerEnum: ?*?*anyopaque, ) callconv(@import("std").os.windows.WINAPI) HRESULT; // TODO: this type is limited to platform 'windows5.1.2600' pub extern "P2P" fn PeerGroupSearchRecords( hGroup: ?*anyopaque, pwzCriteria: ?[*:0]const u16, phPeerEnum: ?*?*anyopaque, ) callconv(@import("std").os.windows.WINAPI) HRESULT; // TODO: this type is limited to platform 'windows5.1.2600' pub extern "P2P" fn PeerGroupExportDatabase( hGroup: ?*anyopaque, pwzFilePath: ?[*:0]const u16, ) callconv(@import("std").os.windows.WINAPI) HRESULT; // TODO: this type is limited to platform 'windows5.1.2600' pub extern "P2P" fn PeerGroupImportDatabase( hGroup: ?*anyopaque, pwzFilePath: ?[*:0]const u16, ) callconv(@import("std").os.windows.WINAPI) HRESULT; // TODO: this type is limited to platform 'windows5.1.2600' pub extern "P2P" fn PeerGroupIssueCredentials( hGroup: ?*anyopaque, pwzSubjectIdentity: ?[*:0]const u16, pCredentialInfo: ?*PEER_CREDENTIAL_INFO, dwFlags: u32, ppwzInvitation: ?*?PWSTR, ) callconv(@import("std").os.windows.WINAPI) HRESULT; // TODO: this type is limited to platform 'windows5.1.2600' pub extern "P2P" fn PeerGroupExportConfig( hGroup: ?*anyopaque, pwzPassword: ?[*:0]const u16, ppwzXML: ?*?PWSTR, ) callconv(@import("std").os.windows.WINAPI) HRESULT; // TODO: this type is limited to platform 'windows5.1.2600' pub extern "P2P" fn PeerGroupImportConfig( pwzXML: ?[*:0]const u16, pwzPassword: ?[*:0]const u16, fOverwrite: BOOL, ppwzIdentity: ?*?PWSTR, ppwzGroup: ?*?PWSTR, ) callconv(@import("std").os.windows.WINAPI) HRESULT; // TODO: this type is limited to platform 'windows5.1.2600' pub extern "P2P" fn PeerGroupPeerTimeToUniversalTime( hGroup: ?*anyopaque, pftPeerTime: ?*FILETIME, pftUniversalTime: ?*FILETIME, ) callconv(@import("std").os.windows.WINAPI) HRESULT; // TODO: this type is limited to platform 'windows5.1.2600' pub extern "P2P" fn PeerGroupUniversalTimeToPeerTime( hGroup: ?*anyopaque, pftUniversalTime: ?*FILETIME, pftPeerTime: ?*FILETIME, ) callconv(@import("std").os.windows.WINAPI) HRESULT; pub extern "P2P" fn PeerGroupResumePasswordAuthentication( hGroup: ?*anyopaque, hPeerEventHandle: ?*anyopaque, ) callconv(@import("std").os.windows.WINAPI) HRESULT; // TODO: this type is limited to platform 'windows5.1.2600' pub extern "P2P" fn PeerIdentityCreate( pwzClassifier: ?[*:0]const u16, pwzFriendlyName: ?[*:0]const u16, hCryptProv: usize, ppwzIdentity: ?*?PWSTR, ) callconv(@import("std").os.windows.WINAPI) HRESULT; // TODO: this type is limited to platform 'windows5.1.2600' pub extern "P2P" fn PeerIdentityGetFriendlyName( pwzIdentity: ?[*:0]const u16, ppwzFriendlyName: ?*?PWSTR, ) callconv(@import("std").os.windows.WINAPI) HRESULT; // TODO: this type is limited to platform 'windows5.1.2600' pub extern "P2P" fn PeerIdentitySetFriendlyName( pwzIdentity: ?[*:0]const u16, pwzFriendlyName: ?[*:0]const u16, ) callconv(@import("std").os.windows.WINAPI) HRESULT; // TODO: this type is limited to platform 'windows5.1.2600' pub extern "P2P" fn PeerIdentityGetCryptKey( pwzIdentity: ?[*:0]const u16, phCryptProv: ?*usize, ) callconv(@import("std").os.windows.WINAPI) HRESULT; // TODO: this type is limited to platform 'windows5.1.2600' pub extern "P2P" fn PeerIdentityDelete( pwzIdentity: ?[*:0]const u16, ) callconv(@import("std").os.windows.WINAPI) HRESULT; // TODO: this type is limited to platform 'windows5.1.2600' pub extern "P2P" fn PeerEnumIdentities( phPeerEnum: ?*?*anyopaque, ) callconv(@import("std").os.windows.WINAPI) HRESULT; // TODO: this type is limited to platform 'windows5.1.2600' pub extern "P2P" fn PeerEnumGroups( pwzIdentity: ?[*:0]const u16, phPeerEnum: ?*?*anyopaque, ) callconv(@import("std").os.windows.WINAPI) HRESULT; // TODO: this type is limited to platform 'windows5.1.2600' pub extern "P2P" fn PeerCreatePeerName( pwzIdentity: ?[*:0]const u16, pwzClassifier: ?[*:0]const u16, ppwzPeerName: ?*?PWSTR, ) callconv(@import("std").os.windows.WINAPI) HRESULT; // TODO: this type is limited to platform 'windows5.1.2600' pub extern "P2P" fn PeerIdentityGetXML( pwzIdentity: ?[*:0]const u16, ppwzIdentityXML: ?*?PWSTR, ) callconv(@import("std").os.windows.WINAPI) HRESULT; // TODO: this type is limited to platform 'windows5.1.2600' pub extern "P2P" fn PeerIdentityExport( pwzIdentity: ?[*:0]const u16, pwzPassword: ?[*:0]const u16, ppwzExportXML: ?*?PWSTR, ) callconv(@import("std").os.windows.WINAPI) HRESULT; // TODO: this type is limited to platform 'windows5.1.2600' pub extern "P2P" fn PeerIdentityImport( pwzImportXML: ?[*:0]const u16, pwzPassword: ?[*:0]const u16, ppwzIdentity: ?*?PWSTR, ) callconv(@import("std").os.windows.WINAPI) HRESULT; // TODO: this type is limited to platform 'windows5.1.2600' pub extern "P2P" fn PeerIdentityGetDefault( ppwzPeerName: ?*?PWSTR, ) callconv(@import("std").os.windows.WINAPI) HRESULT; // TODO: this type is limited to platform 'windows6.0.6000' pub extern "P2P" fn PeerCollabStartup( wVersionRequested: u16, ) callconv(@import("std").os.windows.WINAPI) HRESULT; // TODO: this type is limited to platform 'windows6.0.6000' pub extern "P2P" fn PeerCollabShutdown( ) callconv(@import("std").os.windows.WINAPI) HRESULT; // TODO: this type is limited to platform 'windows6.0.6000' pub extern "P2P" fn PeerCollabSignin( hwndParent: ?HWND, dwSigninOptions: u32, ) callconv(@import("std").os.windows.WINAPI) HRESULT; // TODO: this type is limited to platform 'windows6.0.6000' pub extern "P2P" fn PeerCollabSignout( dwSigninOptions: u32, ) callconv(@import("std").os.windows.WINAPI) HRESULT; // TODO: this type is limited to platform 'windows6.0.6000' pub extern "P2P" fn PeerCollabGetSigninOptions( pdwSigninOptions: ?*u32, ) callconv(@import("std").os.windows.WINAPI) HRESULT; // TODO: this type is limited to platform 'windows6.0.6000' pub extern "P2P" fn PeerCollabAsyncInviteContact( pcContact: ?*PEER_CONTACT, pcEndpoint: ?*PEER_ENDPOINT, pcInvitation: ?*PEER_INVITATION, hEvent: ?HANDLE, phInvitation: ?*?HANDLE, ) callconv(@import("std").os.windows.WINAPI) HRESULT; // TODO: this type is limited to platform 'windows6.0.6000' pub extern "P2P" fn PeerCollabGetInvitationResponse( hInvitation: ?HANDLE, ppInvitationResponse: ?*?*PEER_INVITATION_RESPONSE, ) callconv(@import("std").os.windows.WINAPI) HRESULT; // TODO: this type is limited to platform 'windows6.0.6000' pub extern "P2P" fn PeerCollabCancelInvitation( hInvitation: ?HANDLE, ) callconv(@import("std").os.windows.WINAPI) HRESULT; // TODO: this type is limited to platform 'windows6.0.6000' pub extern "P2P" fn PeerCollabCloseHandle( hInvitation: ?HANDLE, ) callconv(@import("std").os.windows.WINAPI) HRESULT; // TODO: this type is limited to platform 'windows6.0.6000' pub extern "P2P" fn PeerCollabInviteContact( pcContact: ?*PEER_CONTACT, pcEndpoint: ?*PEER_ENDPOINT, pcInvitation: ?*PEER_INVITATION, ppResponse: ?*?*PEER_INVITATION_RESPONSE, ) callconv(@import("std").os.windows.WINAPI) HRESULT; // TODO: this type is limited to platform 'windows6.0.6000' pub extern "P2P" fn PeerCollabAsyncInviteEndpoint( pcEndpoint: ?*PEER_ENDPOINT, pcInvitation: ?*PEER_INVITATION, hEvent: ?HANDLE, phInvitation: ?*?HANDLE, ) callconv(@import("std").os.windows.WINAPI) HRESULT; // TODO: this type is limited to platform 'windows6.0.6000' pub extern "P2P" fn PeerCollabInviteEndpoint( pcEndpoint: ?*PEER_ENDPOINT, pcInvitation: ?*PEER_INVITATION, ppResponse: ?*?*PEER_INVITATION_RESPONSE, ) callconv(@import("std").os.windows.WINAPI) HRESULT; // TODO: this type is limited to platform 'windows6.0.6000' pub extern "P2P" fn PeerCollabGetAppLaunchInfo( ppLaunchInfo: ?*?*PEER_APP_LAUNCH_INFO, ) callconv(@import("std").os.windows.WINAPI) HRESULT; // TODO: this type is limited to platform 'windows6.0.6000' pub extern "P2P" fn PeerCollabRegisterApplication( pcApplication: ?*PEER_APPLICATION_REGISTRATION_INFO, registrationType: PEER_APPLICATION_REGISTRATION_TYPE, ) callconv(@import("std").os.windows.WINAPI) HRESULT; // TODO: this type is limited to platform 'windows6.0.6000' pub extern "P2P" fn PeerCollabUnregisterApplication( pApplicationId: ?*const Guid, registrationType: PEER_APPLICATION_REGISTRATION_TYPE, ) callconv(@import("std").os.windows.WINAPI) HRESULT; // TODO: this type is limited to platform 'windows6.0.6000' pub extern "P2P" fn PeerCollabGetApplicationRegistrationInfo( pApplicationId: ?*const Guid, registrationType: PEER_APPLICATION_REGISTRATION_TYPE, ppApplication: ?*?*PEER_APPLICATION_REGISTRATION_INFO, ) callconv(@import("std").os.windows.WINAPI) HRESULT; // TODO: this type is limited to platform 'windows6.0.6000' pub extern "P2P" fn PeerCollabEnumApplicationRegistrationInfo( registrationType: PEER_APPLICATION_REGISTRATION_TYPE, phPeerEnum: ?*?*anyopaque, ) callconv(@import("std").os.windows.WINAPI) HRESULT; // TODO: this type is limited to platform 'windows6.0.6000' pub extern "P2P" fn PeerCollabGetPresenceInfo( pcEndpoint: ?*PEER_ENDPOINT, ppPresenceInfo: ?*?*PEER_PRESENCE_INFO, ) callconv(@import("std").os.windows.WINAPI) HRESULT; // TODO: this type is limited to platform 'windows6.0.6000' pub extern "P2P" fn PeerCollabEnumApplications( pcEndpoint: ?*PEER_ENDPOINT, pApplicationId: ?*const Guid, phPeerEnum: ?*?*anyopaque, ) callconv(@import("std").os.windows.WINAPI) HRESULT; // TODO: this type is limited to platform 'windows6.0.6000' pub extern "P2P" fn PeerCollabEnumObjects( pcEndpoint: ?*PEER_ENDPOINT, pObjectId: ?*const Guid, phPeerEnum: ?*?*anyopaque, ) callconv(@import("std").os.windows.WINAPI) HRESULT; // TODO: this type is limited to platform 'windows6.0.6000' pub extern "P2P" fn PeerCollabEnumEndpoints( pcContact: ?*PEER_CONTACT, phPeerEnum: ?*?*anyopaque, ) callconv(@import("std").os.windows.WINAPI) HRESULT; // TODO: this type is limited to platform 'windows6.0.6000' pub extern "P2P" fn PeerCollabRefreshEndpointData( pcEndpoint: ?*PEER_ENDPOINT, ) callconv(@import("std").os.windows.WINAPI) HRESULT; // TODO: this type is limited to platform 'windows6.0.6000' pub extern "P2P" fn PeerCollabDeleteEndpointData( pcEndpoint: ?*PEER_ENDPOINT, ) callconv(@import("std").os.windows.WINAPI) HRESULT; // TODO: this type is limited to platform 'windows6.0.6000' pub extern "P2P" fn PeerCollabQueryContactData( pcEndpoint: ?*PEER_ENDPOINT, ppwzContactData: ?*?PWSTR, ) callconv(@import("std").os.windows.WINAPI) HRESULT; // TODO: this type is limited to platform 'windows6.0.6000' pub extern "P2P" fn PeerCollabSubscribeEndpointData( pcEndpoint: ?*const PEER_ENDPOINT, ) callconv(@import("std").os.windows.WINAPI) HRESULT; // TODO: this type is limited to platform 'windows6.0.6000' pub extern "P2P" fn PeerCollabUnsubscribeEndpointData( pcEndpoint: ?*const PEER_ENDPOINT, ) callconv(@import("std").os.windows.WINAPI) HRESULT; // TODO: this type is limited to platform 'windows6.0.6000' pub extern "P2P" fn PeerCollabSetPresenceInfo( pcPresenceInfo: ?*PEER_PRESENCE_INFO, ) callconv(@import("std").os.windows.WINAPI) HRESULT; // TODO: this type is limited to platform 'windows6.0.6000' pub extern "P2P" fn PeerCollabGetEndpointName( ppwzEndpointName: ?*?PWSTR, ) callconv(@import("std").os.windows.WINAPI) HRESULT; // TODO: this type is limited to platform 'windows6.0.6000' pub extern "P2P" fn PeerCollabSetEndpointName( pwzEndpointName: ?[*:0]const u16, ) callconv(@import("std").os.windows.WINAPI) HRESULT; // TODO: this type is limited to platform 'windows6.0.6000' pub extern "P2P" fn PeerCollabSetObject( pcObject: ?*PEER_OBJECT, ) callconv(@import("std").os.windows.WINAPI) HRESULT; // TODO: this type is limited to platform 'windows6.0.6000' pub extern "P2P" fn PeerCollabDeleteObject( pObjectId: ?*const Guid, ) callconv(@import("std").os.windows.WINAPI) HRESULT; // TODO: this type is limited to platform 'windows6.0.6000' pub extern "P2P" fn PeerCollabRegisterEvent( hEvent: ?HANDLE, cEventRegistration: u32, pEventRegistrations: [*]PEER_COLLAB_EVENT_REGISTRATION, phPeerEvent: ?*?*anyopaque, ) callconv(@import("std").os.windows.WINAPI) HRESULT; // TODO: this type is limited to platform 'windows6.0.6000' pub extern "P2P" fn PeerCollabGetEventData( hPeerEvent: ?*anyopaque, ppEventData: ?*?*PEER_COLLAB_EVENT_DATA, ) callconv(@import("std").os.windows.WINAPI) HRESULT; // TODO: this type is limited to platform 'windows6.0.6000' pub extern "P2P" fn PeerCollabUnregisterEvent( hPeerEvent: ?*anyopaque, ) callconv(@import("std").os.windows.WINAPI) HRESULT; // TODO: this type is limited to platform 'windows6.0.6000' pub extern "P2P" fn PeerCollabEnumPeopleNearMe( phPeerEnum: ?*?*anyopaque, ) callconv(@import("std").os.windows.WINAPI) HRESULT; // TODO: this type is limited to platform 'windows6.0.6000' pub extern "P2P" fn PeerCollabAddContact( pwzContactData: ?[*:0]const u16, ppContact: ?*?*PEER_CONTACT, ) callconv(@import("std").os.windows.WINAPI) HRESULT; // TODO: this type is limited to platform 'windows6.0.6000' pub extern "P2P" fn PeerCollabDeleteContact( pwzPeerName: ?[*:0]const u16, ) callconv(@import("std").os.windows.WINAPI) HRESULT; // TODO: this type is limited to platform 'windows6.0.6000' pub extern "P2P" fn PeerCollabGetContact( pwzPeerName: ?[*:0]const u16, ppContact: ?*?*PEER_CONTACT, ) callconv(@import("std").os.windows.WINAPI) HRESULT; // TODO: this type is limited to platform 'windows6.0.6000' pub extern "P2P" fn PeerCollabUpdateContact( pContact: ?*PEER_CONTACT, ) callconv(@import("std").os.windows.WINAPI) HRESULT; // TODO: this type is limited to platform 'windows6.0.6000' pub extern "P2P" fn PeerCollabEnumContacts( phPeerEnum: ?*?*anyopaque, ) callconv(@import("std").os.windows.WINAPI) HRESULT; // TODO: this type is limited to platform 'windows6.0.6000' pub extern "P2P" fn PeerCollabExportContact( pwzPeerName: ?[*:0]const u16, ppwzContactData: ?*?PWSTR, ) callconv(@import("std").os.windows.WINAPI) HRESULT; // TODO: this type is limited to platform 'windows6.0.6000' pub extern "P2P" fn PeerCollabParseContact( pwzContactData: ?[*:0]const u16, ppContact: ?*?*PEER_CONTACT, ) callconv(@import("std").os.windows.WINAPI) HRESULT; // TODO: this type is limited to platform 'windows5.1.2600' pub extern "P2P" fn PeerNameToPeerHostName( pwzPeerName: ?[*:0]const u16, ppwzHostName: ?*?PWSTR, ) callconv(@import("std").os.windows.WINAPI) HRESULT; // TODO: this type is limited to platform 'windows5.1.2600' pub extern "P2P" fn PeerHostNameToPeerName( pwzHostName: ?[*:0]const u16, ppwzPeerName: ?*?PWSTR, ) callconv(@import("std").os.windows.WINAPI) HRESULT; // TODO: this type is limited to platform 'windows5.1.2600' pub extern "P2P" fn PeerPnrpStartup( wVersionRequested: u16, ) callconv(@import("std").os.windows.WINAPI) HRESULT; // TODO: this type is limited to platform 'windows5.1.2600' pub extern "P2P" fn PeerPnrpShutdown( ) callconv(@import("std").os.windows.WINAPI) HRESULT; // TODO: this type is limited to platform 'windows5.1.2600' pub extern "P2P" fn PeerPnrpRegister( pcwzPeerName: ?[*:0]const u16, pRegistrationInfo: ?*PEER_PNRP_REGISTRATION_INFO, phRegistration: ?*?*anyopaque, ) callconv(@import("std").os.windows.WINAPI) HRESULT; // TODO: this type is limited to platform 'windows5.1.2600' pub extern "P2P" fn PeerPnrpUpdateRegistration( hRegistration: ?*anyopaque, pRegistrationInfo: ?*PEER_PNRP_REGISTRATION_INFO, ) callconv(@import("std").os.windows.WINAPI) HRESULT; // TODO: this type is limited to platform 'windows5.1.2600' pub extern "P2P" fn PeerPnrpUnregister( hRegistration: ?*anyopaque, ) callconv(@import("std").os.windows.WINAPI) HRESULT; // TODO: this type is limited to platform 'windows5.1.2600' pub extern "P2P" fn PeerPnrpResolve( pcwzPeerName: ?[*:0]const u16, pcwzCloudName: ?[*:0]const u16, pcEndpoints: ?*u32, ppEndpoints: ?*?*PEER_PNRP_ENDPOINT_INFO, ) callconv(@import("std").os.windows.WINAPI) HRESULT; // TODO: this type is limited to platform 'windows5.1.2600' pub extern "P2P" fn PeerPnrpStartResolve( pcwzPeerName: ?[*:0]const u16, pcwzCloudName: ?[*:0]const u16, cMaxEndpoints: u32, hEvent: ?HANDLE, phResolve: ?*?*anyopaque, ) callconv(@import("std").os.windows.WINAPI) HRESULT; // TODO: this type is limited to platform 'windows5.1.2600' pub extern "P2P" fn PeerPnrpGetCloudInfo( pcNumClouds: ?*u32, ppCloudInfo: ?*?*PEER_PNRP_CLOUD_INFO, ) callconv(@import("std").os.windows.WINAPI) HRESULT; // TODO: this type is limited to platform 'windows5.1.2600' pub extern "P2P" fn PeerPnrpGetEndpoint( hResolve: ?*anyopaque, ppEndpoint: ?*?*PEER_PNRP_ENDPOINT_INFO, ) callconv(@import("std").os.windows.WINAPI) HRESULT; // TODO: this type is limited to platform 'windows5.1.2600' pub extern "P2P" fn PeerPnrpEndResolve( hResolve: ?*anyopaque, ) callconv(@import("std").os.windows.WINAPI) HRESULT; // TODO: this type is limited to platform 'windows6.1' pub extern "drtprov" fn DrtCreatePnrpBootstrapResolver( fPublish: BOOL, pwzPeerName: ?[*:0]const u16, pwzCloudName: ?[*:0]const u16, pwzPublishingIdentity: ?[*:0]const u16, ppResolver: ?*?*DRT_BOOTSTRAP_PROVIDER, ) callconv(@import("std").os.windows.WINAPI) HRESULT; // TODO: this type is limited to platform 'windows6.1' pub extern "drtprov" fn DrtDeletePnrpBootstrapResolver( pResolver: ?*DRT_BOOTSTRAP_PROVIDER, ) callconv(@import("std").os.windows.WINAPI) void; // TODO: this type is limited to platform 'windows6.1' pub extern "drtprov" fn DrtCreateDnsBootstrapResolver( port: u16, pwszAddress: ?[*:0]const u16, ppModule: ?*?*DRT_BOOTSTRAP_PROVIDER, ) callconv(@import("std").os.windows.WINAPI) HRESULT; // TODO: this type is limited to platform 'windows6.1' pub extern "drtprov" fn DrtDeleteDnsBootstrapResolver( pResolver: ?*DRT_BOOTSTRAP_PROVIDER, ) callconv(@import("std").os.windows.WINAPI) void; // TODO: this type is limited to platform 'windows6.1' pub extern "drttransport" fn DrtCreateIpv6UdpTransport( scope: DRT_SCOPE, dwScopeId: u32, dwLocalityThreshold: u32, pwPort: ?*u16, phTransport: ?*?*anyopaque, ) callconv(@import("std").os.windows.WINAPI) HRESULT; // TODO: this type is limited to platform 'windows6.1' pub extern "drttransport" fn DrtDeleteIpv6UdpTransport( hTransport: ?*anyopaque, ) callconv(@import("std").os.windows.WINAPI) HRESULT; // TODO: this type is limited to platform 'windows6.1' pub extern "drtprov" fn DrtCreateDerivedKeySecurityProvider( pRootCert: ?*const CERT_CONTEXT, pLocalCert: ?*const CERT_CONTEXT, ppSecurityProvider: ?*?*DRT_SECURITY_PROVIDER, ) callconv(@import("std").os.windows.WINAPI) HRESULT; // TODO: this type is limited to platform 'windows6.1' pub extern "drtprov" fn DrtCreateDerivedKey( pLocalCert: ?*const CERT_CONTEXT, pKey: ?*DRT_DATA, ) callconv(@import("std").os.windows.WINAPI) HRESULT; // TODO: this type is limited to platform 'windows6.1' pub extern "drtprov" fn DrtDeleteDerivedKeySecurityProvider( pSecurityProvider: ?*DRT_SECURITY_PROVIDER, ) callconv(@import("std").os.windows.WINAPI) void; // TODO: this type is limited to platform 'windows6.1' pub extern "drtprov" fn DrtCreateNullSecurityProvider( ppSecurityProvider: ?*?*DRT_SECURITY_PROVIDER, ) callconv(@import("std").os.windows.WINAPI) HRESULT; // TODO: this type is limited to platform 'windows6.1' pub extern "drtprov" fn DrtDeleteNullSecurityProvider( pSecurityProvider: ?*DRT_SECURITY_PROVIDER, ) callconv(@import("std").os.windows.WINAPI) void; // TODO: this type is limited to platform 'windows6.1' pub extern "drt" fn DrtOpen( pSettings: ?*const DRT_SETTINGS, hEvent: ?HANDLE, pvContext: ?*const anyopaque, phDrt: ?*?*anyopaque, ) callconv(@import("std").os.windows.WINAPI) HRESULT; // TODO: this type is limited to platform 'windows6.1' pub extern "drt" fn DrtClose( hDrt: ?*anyopaque, ) callconv(@import("std").os.windows.WINAPI) void; // TODO: this type is limited to platform 'windows6.1' pub extern "drt" fn DrtGetEventDataSize( hDrt: ?*anyopaque, pulEventDataLen: ?*u32, ) callconv(@import("std").os.windows.WINAPI) HRESULT; // TODO: this type is limited to platform 'windows6.1' pub extern "drt" fn DrtGetEventData( hDrt: ?*anyopaque, ulEventDataLen: u32, pEventData: ?*DRT_EVENT_DATA, ) callconv(@import("std").os.windows.WINAPI) HRESULT; // TODO: this type is limited to platform 'windows6.1' pub extern "drt" fn DrtRegisterKey( hDrt: ?*anyopaque, pRegistration: ?*DRT_REGISTRATION, pvKeyContext: ?*anyopaque, phKeyRegistration: ?*?*anyopaque, ) callconv(@import("std").os.windows.WINAPI) HRESULT; // TODO: this type is limited to platform 'windows6.1' pub extern "drt" fn DrtUpdateKey( hKeyRegistration: ?*anyopaque, pAppData: ?*DRT_DATA, ) callconv(@import("std").os.windows.WINAPI) HRESULT; // TODO: this type is limited to platform 'windows6.1' pub extern "drt" fn DrtUnregisterKey( hKeyRegistration: ?*anyopaque, ) callconv(@import("std").os.windows.WINAPI) void; // TODO: this type is limited to platform 'windows6.1' pub extern "drt" fn DrtStartSearch( hDrt: ?*anyopaque, pKey: ?*DRT_DATA, pInfo: ?*const DRT_SEARCH_INFO, timeout: u32, hEvent: ?HANDLE, pvContext: ?*const anyopaque, hSearchContext: ?*?*anyopaque, ) callconv(@import("std").os.windows.WINAPI) HRESULT; // TODO: this type is limited to platform 'windows6.1' pub extern "drt" fn DrtContinueSearch( hSearchContext: ?*anyopaque, ) callconv(@import("std").os.windows.WINAPI) HRESULT; // TODO: this type is limited to platform 'windows6.1' pub extern "drt" fn DrtGetSearchResultSize( hSearchContext: ?*anyopaque, pulSearchResultSize: ?*u32, ) callconv(@import("std").os.windows.WINAPI) HRESULT; // TODO: this type is limited to platform 'windows6.1' pub extern "drt" fn DrtGetSearchResult( hSearchContext: ?*anyopaque, ulSearchResultSize: u32, pSearchResult: ?*DRT_SEARCH_RESULT, ) callconv(@import("std").os.windows.WINAPI) HRESULT; // TODO: this type is limited to platform 'windows6.1' pub extern "drt" fn DrtGetSearchPathSize( hSearchContext: ?*anyopaque, pulSearchPathSize: ?*u32, ) callconv(@import("std").os.windows.WINAPI) HRESULT; // TODO: this type is limited to platform 'windows6.1' pub extern "drt" fn DrtGetSearchPath( hSearchContext: ?*anyopaque, ulSearchPathSize: u32, pSearchPath: ?*DRT_ADDRESS_LIST, ) callconv(@import("std").os.windows.WINAPI) HRESULT; // TODO: this type is limited to platform 'windows6.1' pub extern "drt" fn DrtEndSearch( hSearchContext: ?*anyopaque, ) callconv(@import("std").os.windows.WINAPI) HRESULT; // TODO: this type is limited to platform 'windows6.1' pub extern "drt" fn DrtGetInstanceName( hDrt: ?*anyopaque, ulcbInstanceNameSize: u32, pwzDrtInstanceName: ?PWSTR, ) callconv(@import("std").os.windows.WINAPI) HRESULT; // TODO: this type is limited to platform 'windows6.1' pub extern "drt" fn DrtGetInstanceNameSize( hDrt: ?*anyopaque, pulcbInstanceNameSize: ?*u32, ) callconv(@import("std").os.windows.WINAPI) HRESULT; // TODO: this type is limited to platform 'windows6.1' pub extern "PeerDist" fn PeerDistStartup( dwVersionRequested: u32, phPeerDist: ?*isize, pdwSupportedVersion: ?*u32, ) callconv(@import("std").os.windows.WINAPI) u32; // TODO: this type is limited to platform 'windows6.1' pub extern "PeerDist" fn PeerDistShutdown( hPeerDist: isize, ) callconv(@import("std").os.windows.WINAPI) u32; // TODO: this type is limited to platform 'windows6.1' pub extern "PeerDist" fn PeerDistGetStatus( hPeerDist: isize, pPeerDistStatus: ?*PEERDIST_STATUS, ) callconv(@import("std").os.windows.WINAPI) u32; // TODO: this type is limited to platform 'windows6.1' pub extern "PeerDist" fn PeerDistRegisterForStatusChangeNotification( hPeerDist: isize, hCompletionPort: ?HANDLE, ulCompletionKey: usize, lpOverlapped: ?*OVERLAPPED, pPeerDistStatus: ?*PEERDIST_STATUS, ) callconv(@import("std").os.windows.WINAPI) u32; // TODO: this type is limited to platform 'windows6.1' pub extern "PeerDist" fn PeerDistUnregisterForStatusChangeNotification( hPeerDist: isize, ) callconv(@import("std").os.windows.WINAPI) u32; // TODO: this type is limited to platform 'windows6.1' pub extern "PeerDist" fn PeerDistServerPublishStream( hPeerDist: isize, cbContentIdentifier: u32, // TODO: what to do with BytesParamIndex 1? pContentIdentifier: ?*u8, cbContentLength: u64, pPublishOptions: ?*PEERDIST_PUBLICATION_OPTIONS, hCompletionPort: ?HANDLE, ulCompletionKey: usize, phStream: ?*isize, ) callconv(@import("std").os.windows.WINAPI) u32; // TODO: this type is limited to platform 'windows6.1' pub extern "PeerDist" fn PeerDistServerPublishAddToStream( hPeerDist: isize, hStream: isize, cbNumberOfBytes: u32, // TODO: what to do with BytesParamIndex 2? pBuffer: ?*u8, lpOverlapped: ?*OVERLAPPED, ) callconv(@import("std").os.windows.WINAPI) u32; // TODO: this type is limited to platform 'windows6.1' pub extern "PeerDist" fn PeerDistServerPublishCompleteStream( hPeerDist: isize, hStream: isize, lpOverlapped: ?*OVERLAPPED, ) callconv(@import("std").os.windows.WINAPI) u32; // TODO: this type is limited to platform 'windows6.1' pub extern "PeerDist" fn PeerDistServerCloseStreamHandle( hPeerDist: isize, hStream: isize, ) callconv(@import("std").os.windows.WINAPI) u32; // TODO: this type is limited to platform 'windows6.1' pub extern "PeerDist" fn PeerDistServerUnpublish( hPeerDist: isize, cbContentIdentifier: u32, // TODO: what to do with BytesParamIndex 1? pContentIdentifier: ?*u8, ) callconv(@import("std").os.windows.WINAPI) u32; // TODO: this type is limited to platform 'windows6.1' pub extern "PeerDist" fn PeerDistServerOpenContentInformation( hPeerDist: isize, cbContentIdentifier: u32, // TODO: what to do with BytesParamIndex 1? pContentIdentifier: ?*u8, ullContentOffset: u64, cbContentLength: u64, hCompletionPort: ?HANDLE, ulCompletionKey: usize, phContentInfo: ?*isize, ) callconv(@import("std").os.windows.WINAPI) u32; // TODO: this type is limited to platform 'windows6.1' pub extern "PeerDist" fn PeerDistServerRetrieveContentInformation( hPeerDist: isize, hContentInfo: isize, cbMaxNumberOfBytes: u32, // TODO: what to do with BytesParamIndex 2? pBuffer: ?*u8, lpOverlapped: ?*OVERLAPPED, ) callconv(@import("std").os.windows.WINAPI) u32; // TODO: this type is limited to platform 'windows6.1' pub extern "PeerDist" fn PeerDistServerCloseContentInformation( hPeerDist: isize, hContentInfo: isize, ) callconv(@import("std").os.windows.WINAPI) u32; // TODO: this type is limited to platform 'windows6.1' pub extern "PeerDist" fn PeerDistServerCancelAsyncOperation( hPeerDist: isize, cbContentIdentifier: u32, // TODO: what to do with BytesParamIndex 1? pContentIdentifier: ?*u8, pOverlapped: ?*OVERLAPPED, ) callconv(@import("std").os.windows.WINAPI) u32; // TODO: this type is limited to platform 'windows6.1' pub extern "PeerDist" fn PeerDistClientOpenContent( hPeerDist: isize, pContentTag: ?*PEERDIST_CONTENT_TAG, hCompletionPort: ?HANDLE, ulCompletionKey: usize, phContentHandle: ?*isize, ) callconv(@import("std").os.windows.WINAPI) u32; // TODO: this type is limited to platform 'windows6.1' pub extern "PeerDist" fn PeerDistClientCloseContent( hPeerDist: isize, hContentHandle: isize, ) callconv(@import("std").os.windows.WINAPI) u32; // TODO: this type is limited to platform 'windows6.1' pub extern "PeerDist" fn PeerDistClientAddContentInformation( hPeerDist: isize, hContentHandle: isize, cbNumberOfBytes: u32, // TODO: what to do with BytesParamIndex 2? pBuffer: ?*u8, lpOverlapped: ?*OVERLAPPED, ) callconv(@import("std").os.windows.WINAPI) u32; // TODO: this type is limited to platform 'windows6.1' pub extern "PeerDist" fn PeerDistClientCompleteContentInformation( hPeerDist: isize, hContentHandle: isize, lpOverlapped: ?*OVERLAPPED, ) callconv(@import("std").os.windows.WINAPI) u32; // TODO: this type is limited to platform 'windows6.1' pub extern "PeerDist" fn PeerDistClientAddData( hPeerDist: isize, hContentHandle: isize, cbNumberOfBytes: u32, // TODO: what to do with BytesParamIndex 2? pBuffer: ?*u8, lpOverlapped: ?*OVERLAPPED, ) callconv(@import("std").os.windows.WINAPI) u32; // TODO: this type is limited to platform 'windows6.1' pub extern "PeerDist" fn PeerDistClientBlockRead( hPeerDist: isize, hContentHandle: isize, cbMaxNumberOfBytes: u32, // TODO: what to do with BytesParamIndex 2? pBuffer: ?*u8, dwTimeoutInMilliseconds: u32, lpOverlapped: ?*OVERLAPPED, ) callconv(@import("std").os.windows.WINAPI) u32; // TODO: this type is limited to platform 'windows6.1' pub extern "PeerDist" fn PeerDistClientStreamRead( hPeerDist: isize, hContentHandle: isize, cbMaxNumberOfBytes: u32, // TODO: what to do with BytesParamIndex 2? pBuffer: ?*u8, dwTimeoutInMilliseconds: u32, lpOverlapped: ?*OVERLAPPED, ) callconv(@import("std").os.windows.WINAPI) u32; // TODO: this type is limited to platform 'windows6.1' pub extern "PeerDist" fn PeerDistClientFlushContent( hPeerDist: isize, pContentTag: ?*PEERDIST_CONTENT_TAG, hCompletionPort: ?HANDLE, ulCompletionKey: usize, lpOverlapped: ?*OVERLAPPED, ) callconv(@import("std").os.windows.WINAPI) u32; // TODO: this type is limited to platform 'windows6.1' pub extern "PeerDist" fn PeerDistClientCancelAsyncOperation( hPeerDist: isize, hContentHandle: isize, pOverlapped: ?*OVERLAPPED, ) callconv(@import("std").os.windows.WINAPI) u32; // TODO: this type is limited to platform 'windows8.0' pub extern "PeerDist" fn PeerDistGetStatusEx( hPeerDist: isize, pPeerDistStatus: ?*PEERDIST_STATUS_INFO, ) callconv(@import("std").os.windows.WINAPI) u32; // TODO: this type is limited to platform 'windows8.0' pub extern "PeerDist" fn PeerDistRegisterForStatusChangeNotificationEx( hPeerDist: isize, hCompletionPort: ?HANDLE, ulCompletionKey: usize, lpOverlapped: ?*OVERLAPPED, pPeerDistStatus: ?*PEERDIST_STATUS_INFO, ) callconv(@import("std").os.windows.WINAPI) u32; // TODO: this type is limited to platform 'windows8.0' pub extern "PeerDist" fn PeerDistGetOverlappedResult( lpOverlapped: ?*OVERLAPPED, lpNumberOfBytesTransferred: ?*u32, bWait: BOOL, ) callconv(@import("std").os.windows.WINAPI) BOOL; // TODO: this type is limited to platform 'windows8.0' pub extern "PeerDist" fn PeerDistServerOpenContentInformationEx( hPeerDist: isize, cbContentIdentifier: u32, // TODO: what to do with BytesParamIndex 1? pContentIdentifier: ?*u8, ullContentOffset: u64, cbContentLength: u64, pRetrievalOptions: ?*PEERDIST_RETRIEVAL_OPTIONS, hCompletionPort: ?HANDLE, ulCompletionKey: usize, phContentInfo: ?*isize, ) callconv(@import("std").os.windows.WINAPI) u32; // TODO: this type is limited to platform 'windows8.0' pub extern "PeerDist" fn PeerDistClientGetInformationByHandle( hPeerDist: isize, hContentHandle: isize, PeerDistClientInfoClass: PEERDIST_CLIENT_INFO_BY_HANDLE_CLASS, dwBufferSize: u32, // TODO: what to do with BytesParamIndex 3? lpInformation: ?*anyopaque, ) callconv(@import("std").os.windows.WINAPI) u32; //-------------------------------------------------------------------------------- // 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 (16) //-------------------------------------------------------------------------------- const Guid = @import("../zig.zig").Guid; const BLOB = @import("../system/com.zig").BLOB; const BOOL = @import("../foundation.zig").BOOL; const CERT_CONTEXT = @import("../security/cryptography.zig").CERT_CONTEXT; const CERT_PUBLIC_KEY_INFO = @import("../security/cryptography.zig").CERT_PUBLIC_KEY_INFO; const FILETIME = @import("../foundation.zig").FILETIME; const HANDLE = @import("../foundation.zig").HANDLE; const HRESULT = @import("../foundation.zig").HRESULT; const HWND = @import("../foundation.zig").HWND; const OVERLAPPED = @import("../system/io.zig").OVERLAPPED; const PWSTR = @import("../foundation.zig").PWSTR; const SOCKADDR = @import("../networking/win_sock.zig").SOCKADDR; const SOCKADDR_IN6 = @import("../networking/win_sock.zig").SOCKADDR_IN6; const SOCKADDR_STORAGE = @import("../networking/win_sock.zig").SOCKADDR_STORAGE; const SOCKET_ADDRESS = @import("../networking/win_sock.zig").SOCKET_ADDRESS; const SOCKET_ADDRESS_LIST = @import("../networking/win_sock.zig").SOCKET_ADDRESS_LIST; test { // The following '_ = <FuncPtrType>' lines are a workaround for https://github.com/ziglang/zig/issues/4476 if (@hasDecl(@This(), "PFNPEER_VALIDATE_RECORD")) { _ = PFNPEER_VALIDATE_RECORD; } if (@hasDecl(@This(), "PFNPEER_SECURE_RECORD")) { _ = PFNPEER_SECURE_RECORD; } if (@hasDecl(@This(), "PFNPEER_FREE_SECURITY_DATA")) { _ = PFNPEER_FREE_SECURITY_DATA; } if (@hasDecl(@This(), "PFNPEER_ON_PASSWORD_AUTH_FAILED")) { _ = PFNPEER_ON_PASSWORD_AUTH_FAILED; } if (@hasDecl(@This(), "DRT_BOOTSTRAP_RESOLVE_CALLBACK")) { _ = DRT_BOOTSTRAP_RESOLVE_CALLBACK; } @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/network_management/p2p.zig
const builtin = @import("builtin"); const std = @import("std"); const debug = std.debug; const io = std.io; const math = std.math; const mem = std.mem; const meta = std.meta; const time = std.time; const Decl = builtin.TypeInfo.Declaration; pub fn benchmark(comptime B: type) !void { const args = if (@hasDecl(B, "args")) B.args else [_]void{{}}; const arg_names = if (@hasDecl(B, "args") and @hasDecl(B, "arg_names")) B.arg_names else [_]u8{}; const min_iterations: u32 = if (@hasDecl(B, "min_iterations")) B.min_iterations else 10000; const max_iterations: u32 = if (@hasDecl(B, "max_iterations")) B.max_iterations else 100000; const max_time = 500 * time.millisecond; const functions = comptime blk: { var res: []const Decl = &[_]Decl{}; for (meta.declarations(B)) |decl| { if (decl.data != Decl.Data.Fn) continue; res = res ++ [_]Decl{decl}; } break :blk res; }; if (functions.len == 0) @compileError("No benchmarks to run."); const min_width = blk: { const stream = io.null_out_stream; var res = [_]u64{ 0, 0, 0 }; res = try printBenchmark(stream, res, "Benchmark", "", "Iterations", "Mean(ns)"); inline for (functions) |f| { for (args) |_, i| { res = if (i < arg_names.len) try printBenchmark(stream, res, f.name, arg_names[i], math.maxInt(u32), math.maxInt(u32)) else try printBenchmark(stream, res, f.name, i, math.maxInt(u32), math.maxInt(u32)); } } break :blk res; }; const stderr = std.io.getStdErr().outStream(); try stderr.writeAll("\n"); _ = try printBenchmark(stderr, min_width, "Benchmark", "", "Iterations", "Mean(ns)"); try stderr.writeAll("\n"); for (min_width) |w| try stderr.writeByteNTimes('-', w); try stderr.writeByteNTimes('-', min_width.len - 1); try stderr.writeAll("\n"); var timer = try time.Timer.start(); inline for (functions) |def| { for (args) |arg, index| { var runtime_sum: u128 = 0; var i: usize = 0; while (i < min_iterations or (i < max_iterations and runtime_sum < max_time)) : (i += 1) { timer.reset(); const res = switch (@TypeOf(arg)) { void => @field(B, def.name)(), else => @field(B, def.name)(arg), }; const runtime = timer.read(); runtime_sum += runtime; doNotOptimize(res); } const runtime_mean = runtime_sum / i; if (index < arg_names.len) { _ = try printBenchmark(stderr, min_width, def.name, arg_names[index], i, runtime_mean); } else { _ = try printBenchmark(stderr, min_width, def.name, index, i, runtime_mean); } try stderr.writeAll("\n"); } } } fn printBenchmark(stream: var, min_widths: [3]u64, func_name: []const u8, arg_name: var, iterations: var, runtime: var) ![3]u64 { const arg_len = countingPrint("{}", .{arg_name}); const name_len = try alignedPrint(stream, .left, min_widths[0], "{}{}{}{}", .{ func_name, "("[0..@boolToInt(arg_len != 0)], arg_name, ")"[0..@boolToInt(arg_len != 0)], }); try stream.writeAll(" "); const it_len = try alignedPrint(stream, .right, min_widths[1], "{}", .{iterations}); try stream.writeAll(" "); const runtime_len = try alignedPrint(stream, .right, min_widths[2], "{}", .{runtime}); return [_]u64{ name_len, it_len, runtime_len }; } fn alignedPrint(stream: var, dir: enum { left, right }, width: u64, comptime fmt: []const u8, args: var) !u64 { const value_len = countingPrint(fmt, args); var cos = io.countingOutStream(stream); const cos_stream = cos.outStream(); if (dir == .right) try cos_stream.writeByteNTimes(' ', math.sub(u64, width, value_len) catch 0); try cos_stream.print(fmt, args); if (dir == .left) try cos_stream.writeByteNTimes(' ', math.sub(u64, width, value_len) catch 0); return cos.bytes_written; } /// Returns the number of bytes that would be written to a stream /// for a given format string and arguments. fn countingPrint(comptime fmt: []const u8, args: var) u64 { var cos = io.countingOutStream(io.null_out_stream); cos.outStream().print(fmt, args) catch unreachable; return cos.bytes_written; } /// Pretend to use the value so the optimizer cant optimize it out. fn doNotOptimize(val: var) void { const T = @TypeOf(val); var store: T = undefined; @ptrCast(*volatile T, &store).* = val; } test "benchmark" { try benchmark(struct { // The functions will be benchmarked with the following inputs. // If not present, then it is assumed that the functions // take no input. const args = [_][]const u8{ &([_]u8{ 1, 10, 100 } ** 16), &([_]u8{ 1, 10, 100 } ** 32), &([_]u8{ 1, 10, 100 } ** 64), &([_]u8{ 1, 10, 100 } ** 128), &([_]u8{ 1, 10, 100 } ** 256), &([_]u8{ 1, 10, 100 } ** 512), }; // You can specify `arg_names` to give the inputs more meaningful // names. If the index of the input exceeds the available string // names, the index is used as a backup. const arg_names = [_][]const u8{ "block=16", "block=32", "block=64", "block=128", "block=256", "block=512", }; // How many iterations to run each benchmark. // If not present then a default will be used. const min_iterations = 1000; const max_iterations = 100000; fn sum_slice(slice: []const u8) u64 { var res: u64 = 0; for (slice) |item| res += item; return res; } fn sum_stream(slice: []const u8) u64 { var stream = &io.fixedBufferStream(slice).inStream(); var res: u64 = 0; while (stream.readByte()) |c| { res += c; } else |_| {} return res; } }); }
bench.zig
const std = @import("std"); const testing = std.testing; const allocator = std.testing.allocator; pub const Page = struct { pub const Buffer = std.ArrayList(u8); const Pos = struct { x: usize, y: usize, pub fn init(x: usize, y: usize) Pos { var self = Pos{ .x = x, .y = y }; return self; } }; cur: usize, dots: [2]std.AutoHashMap(Pos, usize), width: usize, height: usize, folding: bool, fold_count: usize, first_count: usize, pub fn init() Page { var self = Page{ .cur = 0, .dots = undefined, .width = 0, .height = 0, .folding = false, .fold_count = 0, .first_count = 0, }; self.dots[0] = std.AutoHashMap(Pos, usize).init(allocator); self.dots[1] = std.AutoHashMap(Pos, usize).init(allocator); return self; } pub fn deinit(self: *Page) void { self.dots[1].deinit(); self.dots[0].deinit(); } pub fn process_line(self: *Page, data: []const u8) !void { if (data.len == 0) { self.folding = true; // std.debug.warn("FOLDING\n", .{}); return; } if (!self.folding) { var x: usize = 0; var pos: usize = 0; var it = std.mem.split(u8, data, ","); while (it.next()) |num| : (pos += 1) { const n = std.fmt.parseInt(usize, num, 10) catch unreachable; if (pos == 0) { x = n; continue; } if (pos == 1) { try self.dots[self.cur].put(Pos.init(x, n), 1); // std.debug.warn("DOT {} {}\n", .{ x, n }); x = 0; continue; } unreachable; } } else { var poss: usize = 0; var its = std.mem.tokenize(u8, data, " "); while (its.next()) |word| : (poss += 1) { if (poss != 2) continue; var axis: u8 = 0; var posq: usize = 0; var itq = std.mem.split(u8, word, "="); while (itq.next()) |what| : (posq += 1) { if (posq == 0) { axis = what[0]; continue; } if (posq == 1) { const pos = std.fmt.parseInt(usize, what, 10) catch unreachable; self.fold_count += 1; try self.fold(axis, pos); axis = 0; if (self.fold_count == 1) { self.first_count = self.count_total_dots(); } continue; } unreachable; } } } } pub fn dots_after_first_fold(self: Page) usize { return self.first_count; } pub fn render_code(self: Page, buffer: *Buffer, empty: []const u8, full: []const u8) !void { var y: usize = 0; while (y <= self.height) : (y += 1) { var x: usize = 0; while (x <= self.width) : (x += 1) { var txt = empty; var p = Pos.init(x, y); if (self.dots[self.cur].contains(p)) { if (self.dots[self.cur].get(p).? > 0) { txt = full; } } for (txt) |c| { try buffer.append(c); } } try buffer.append('\n'); } } fn count_total_dots(self: Page) usize { var count: usize = 0; var it = self.dots[self.cur].iterator(); while (it.next()) |entry| { if (entry.value_ptr.* == 0) continue; count += 1; } // std.debug.warn("DOTS {}\n", .{count}); return count; } fn fold(self: *Page, axis: u8, pos: usize) !void { // std.debug.warn("FOLD {c} {}\n", .{ axis, pos }); self.width = 0; self.height = 0; const nxt = 1 - self.cur; self.dots[nxt].clearRetainingCapacity(); var it = self.dots[self.cur].iterator(); while (it.next()) |entry| { if (entry.value_ptr.* == 0) continue; var p = entry.key_ptr.*; if (axis == 'x') { if (p.x > pos) { p.x = pos * 2 - p.x; } } if (axis == 'y') { if (p.y > pos) { p.y = pos * 2 - p.y; } } // std.debug.warn("DOT {}\n", .{ p }); try self.dots[nxt].put(p, 1); if (self.width < p.x) self.width = p.x; if (self.height < p.y) self.height = p.y; } self.cur = nxt; } }; test "sample part a" { const data: []const u8 = \\6,10 \\0,14 \\9,10 \\0,3 \\10,4 \\4,11 \\6,0 \\6,12 \\4,1 \\0,13 \\10,12 \\3,4 \\3,0 \\8,4 \\1,10 \\2,14 \\8,10 \\9,0 \\ \\fold along y=7 \\fold along x=5 ; var page = Page.init(); defer page.deinit(); var it = std.mem.split(u8, data, "\n"); while (it.next()) |line| { try page.process_line(line); } const total_dots = page.dots_after_first_fold(); try testing.expect(total_dots == 17); } test "sample part b" { const data: []const u8 = \\6,10 \\0,14 \\9,10 \\0,3 \\10,4 \\4,11 \\6,0 \\6,12 \\4,1 \\0,13 \\10,12 \\3,4 \\3,0 \\8,4 \\1,10 \\2,14 \\8,10 \\9,0 \\ \\fold along y=7 \\fold along x=5 ; const expected: []const u8 = \\***** \\*...* \\*...* \\*...* \\***** \\ ; var page = Page.init(); defer page.deinit(); var it = std.mem.split(u8, data, "\n"); while (it.next()) |line| { try page.process_line(line); } var buffer = Page.Buffer.init(allocator); defer buffer.deinit(); try page.render_code(&buffer, ".", "*"); try testing.expect(std.mem.eql(u8, buffer.items, expected)); }
2021/p13/page.zig
const std = @import("std"); const Allocator = std.mem.Allocator; const TokenIterator = std.mem.TokenIterator; const BoardList = std.TailQueue(*Board); const input = @embedFile("../inputs/day04.txt"); const board_side = 5; pub fn run(alloc: Allocator, stdout_: anytype) !void { const parsed = try parseInput(alloc); defer parsed.free(); const res1 = part1(parsed); for (parsed.boards) |*board| { board.reset(); } const res2 = try part2(alloc, parsed); if (stdout_) |stdout| { try stdout.print("Part 1: {}\n", .{res1}); try stdout.print("Part 2: {}\n", .{res2}); } } const Board = struct { nums: [board_side][board_side]u8, marks: [board_side][board_side]bool, row_counts: [board_side]u8, col_counts: [board_side]u8, /// Potentially marks the given number on this board. /// If the marking leads to a bingo, returns the resulting score, /// and otherwise returns null. pub fn markNum(self: *Board, num: u8) ?i32 { var bingo = false; var row: usize = 0; while (row < board_side) : (row += 1) { var col: usize = 0; while (col < board_side) : (col += 1) { if (self.nums[row][col] != num) continue; if (self.marks[row][col]) unreachable; // why would a number be called twice? self.marks[row][col] = true; self.row_counts[row] += 1; self.col_counts[col] += 1; if (self.row_counts[row] == board_side or self.col_counts[col] == board_side) { bingo = true; // we must continue marking the board } } } if (bingo) { return self.calculateScore(num); } else { return null; } } pub fn reset(self: *Board) void { var i: usize = 0; while (i < board_side) : (i += 1) { self.row_counts[i] = 0; self.col_counts[i] = 0; var j: usize = 0; while (j < board_side) : (j += 1) { self.marks[i][j] = false; } } } fn calculateScore(self: *const Board, last_num: u8) i32 { var total: i32 = 0; var i: usize = 0; while (i < board_side) : (i += 1) { var j: usize = 0; while (j < board_side) : (j += 1) { if (!self.marks[i][j]) { total += self.nums[i][j]; } } } return total * last_num; } }; const Input = struct { allocator: Allocator, sequence: []const u8, boards: []Board, pub fn free(self: *const Input) void { self.allocator.free(self.sequence); self.allocator.free(self.boards); } }; fn part1(parsed: Input) i32 { for (parsed.sequence) |num| { for (parsed.boards) |*board| { if (board.markNum(num)) |score| { return score; } } } unreachable; } fn part2(alloc: Allocator, parsed: Input) !i32 { const board_nodes = try alloc.alloc(BoardList.Node, parsed.boards.len); defer alloc.free(board_nodes); var list = BoardList{}; for (board_nodes) |*node, i| { node.data = &parsed.boards[i]; list.append(node); } for (parsed.sequence) |num| { var curr = list.first; while (curr) |node| { if (node.data.markNum(num)) |score| { if (list.len == 1) { return score; } else { const next = node.next; list.remove(node); curr = next; } } else { curr = node.next; } } } unreachable; } fn parseInput(alloc: Allocator) !Input { var tokens = std.mem.tokenize(u8, input, "\r\n"); const first_line = tokens.next().?; const sequence = try parseSequence(alloc, first_line); const boards = try parseBoards(alloc, tokens); return Input{ .allocator = alloc, .sequence = sequence, .boards = boards }; } fn parseBoards(alloc: Allocator, tokens_c: TokenIterator(u8)) ![]Board { var tokens = tokens_c; // Each board has exactly (board_side + 1) newlines corresponding to it, except for the // last board which has one less (thus we add an extra 1) const num_boards: usize = (std.mem.count(u8, tokens.rest(), "\n") + 1) / (board_side + 1); var boards = try alloc.alloc(Board, num_boards); var i: usize = 0; while (i < num_boards) : (i += 1) { var j: usize = 0; while (j < board_side) : (j += 1) { boards[i].row_counts[j] = 0; boards[i].col_counts[j] = 0; const line = tokens.next().?; var numbers = std.mem.tokenize(u8, line, " "); var k: usize = 0; while (k < board_side) : (k += 1) { const number = numbers.next().?; boards[i].nums[j][k] = try std.fmt.parseUnsigned(u8, number, 10); boards[i].marks[j][k] = false; } if (numbers.next() != null) unreachable; } } if (tokens.next() != null) unreachable; return boards; } fn parseSequence(alloc: Allocator, line: []const u8) ![]u8 { // every two numbers in the sequence are separated by a comma const seq_len = std.mem.count(u8, line, ",") + 1; var sequence = try alloc.alloc(u8, seq_len); var split = std.mem.split(u8, line, ","); var i: usize = 0; while (split.next()) |num| : (i += 1) { sequence[i] = try std.fmt.parseUnsigned(u8, num, 10); } if (i < seq_len) unreachable; // sanity check return sequence; }
src/day04.zig
const std = @import("std"); const assert = std.debug.assert; const tools = @import("tools"); fn maskOf(bit: usize) u26 { return @as(u26, 1) << @intCast(u5, bit); } pub fn run(input: []const u8, allocator: std.mem.Allocator) ![2][]const u8 { var table = [_]u26{0} ** 26; var allSteps: u26 = 0; { var it = std.mem.tokenize(u8, input, "\n\r"); while (it.next()) |line| { const fields = tools.match_pattern("Step {} must be finished before step {} can begin.", line) orelse unreachable; const in = fields[0].lit[0] - 'A'; const out = fields[1].lit[0] - 'A'; table[out] |= maskOf(in); allSteps |= maskOf(out) | maskOf(in); } } // part1 //var arena = std.heap.ArenaAllocator.init(std.heap.page_allocator); //defer arena.deinit(); var buf: [32]u8 = undefined; const ans1 = ans: { var len: u32 = 0; var done: u26 = 0; var todo = allSteps; while (done != todo) { const nextStep = ns: { for (table) |deps, s| { if (deps & ~done != 0) continue; if (done & maskOf(s) != 0) continue; if (allSteps & maskOf(s) == 0) continue; break :ns @intCast(u8, s); } unreachable; }; buf[len] = 'A' + nextStep; len += 1; done |= maskOf(nextStep); } break :ans buf[0..len]; }; // part2 const ans2 = ans: { var workTodo: [26]u8 = undefined; var time: u32 = 0; for (workTodo) |*it, step| { if (allSteps & maskOf(step) != 0) it.* = @intCast(u8, step) + 1 + 60; } var done: u26 = 0; //var buf2: [32]u8 = undefined; //var bufLen: usize = 0; while (done != allSteps) { time += 1; // std.debug.print("t={}: ", .{time}); var idleWorkers: u32 = 5; var doneThisStep: u26 = 0; for (table) |deps, s| { if (deps & ~done != 0) continue; if (done & maskOf(s) != 0) continue; if (allSteps & maskOf(s) == 0) continue; workTodo[s] -= 1; if (workTodo[s] == 0) { doneThisStep |= maskOf(s); // buf2[bufLen] = 'A' + @intCast(u8, s); // bufLen += 1; } // std.debug.print("{c} ({}s), ", .{ @intCast(u8, s) + 'A', workTodo[s] }); idleWorkers -= 1; if (idleWorkers == 0) break; } done |= doneThisStep; // std.debug.print(" => {}\n", .{buf2[0..bufLen]}); } break :ans time; }; return [_][]const u8{ try std.fmt.allocPrint(allocator, "{s}", .{ans1}), try std.fmt.allocPrint(allocator, "{}", .{ans2}), }; } pub const main = tools.defaultMain("2018/input_day07.txt", run);
2018/day07.zig
const Section = @This(); const std = @import("std"); const Allocator = std.mem.Allocator; const testing = std.testing; const spec = @import("spec.zig"); const Word = spec.Word; const DoubleWord = std.meta.Int(.unsigned, @bitSizeOf(Word) * 2); const Log2Word = std.math.Log2Int(Word); const Opcode = spec.Opcode; /// The instructions in this section. Memory is owned by the Module /// externally associated to this Section. instructions: std.ArrayListUnmanaged(Word) = .{}, pub fn deinit(section: *Section, allocator: Allocator) void { section.instructions.deinit(allocator); section.* = undefined; } /// Clear the instructions in this section pub fn reset(section: *Section) void { section.instructions.items.len = 0; } pub fn toWords(section: Section) []Word { return section.instructions.items; } /// Append the instructions from another section into this section. pub fn append(section: *Section, allocator: Allocator, other_section: Section) !void { try section.instructions.appendSlice(allocator, other_section.instructions.items); } /// Write an instruction and size, operands are to be inserted manually. pub fn emitRaw( section: *Section, allocator: Allocator, opcode: Opcode, operands: usize, // opcode itself not included ) !void { const word_count = 1 + operands; try section.instructions.ensureUnusedCapacity(allocator, word_count); section.writeWord((@intCast(Word, word_count << 16)) | @enumToInt(opcode)); } pub fn emit( section: *Section, allocator: Allocator, comptime opcode: spec.Opcode, operands: opcode.Operands(), ) !void { const word_count = instructionSize(opcode, operands); try section.instructions.ensureUnusedCapacity(allocator, word_count); section.writeWord(@intCast(Word, word_count << 16) | @enumToInt(opcode)); section.writeOperands(opcode.Operands(), operands); } /// Decorate a result-id. pub fn decorate( section: *Section, allocator: Allocator, target: spec.IdRef, decoration: spec.Decoration.Extended, ) !void { try section.emit(allocator, .OpDecorate, .{ .target = target, .decoration = decoration, }); } /// Decorate a result-id which is a member of some struct. pub fn decorateMember( section: *Section, allocator: Allocator, structure_type: spec.IdRef, member: u32, decoration: spec.Decoration.Extended, ) !void { try section.emit(allocator, .OpMemberDecorate, .{ .structure_type = structure_type, .member = member, .decoration = decoration, }); } pub fn writeWord(section: *Section, word: Word) void { section.instructions.appendAssumeCapacity(word); } pub fn writeWords(section: *Section, words: []const Word) void { section.instructions.appendSliceAssumeCapacity(words); } fn writeDoubleWord(section: *Section, dword: DoubleWord) void { section.writeWords(&.{ @truncate(Word, dword), @truncate(Word, dword >> @bitSizeOf(Word)), }); } fn writeOperands(section: *Section, comptime Operands: type, operands: Operands) void { const fields = switch (@typeInfo(Operands)) { .Struct => |info| info.fields, .Void => return, else => unreachable, }; inline for (fields) |field| { section.writeOperand(field.field_type, @field(operands, field.name)); } } pub fn writeOperand(section: *Section, comptime Operand: type, operand: Operand) void { switch (Operand) { spec.IdResultType, spec.IdResult, spec.IdRef => section.writeWord(operand.id), spec.LiteralInteger => section.writeWord(operand), spec.LiteralString => section.writeString(operand), spec.LiteralContextDependentNumber => section.writeContextDependentNumber(operand), spec.LiteralExtInstInteger => section.writeWord(operand.inst), // TODO: Where this type is used (OpSpecConstantOp) is currently not correct in the spec json, // so it most likely needs to be altered into something that can actually describe the entire // instruction in which it is used. spec.LiteralSpecConstantOpInteger => section.writeWord(@enumToInt(operand.opcode)), spec.PairLiteralIntegerIdRef => section.writeWords(&.{ operand.value, operand.label.id }), spec.PairIdRefLiteralInteger => section.writeWords(&.{ operand.target.id, operand.member }), spec.PairIdRefIdRef => section.writeWords(&.{ operand[0].id, operand[1].id }), else => switch (@typeInfo(Operand)) { .Enum => section.writeWord(@enumToInt(operand)), .Optional => |info| if (operand) |child| { section.writeOperand(info.child, child); }, .Pointer => |info| { std.debug.assert(info.size == .Slice); // Should be no other pointer types in the spec. for (operand) |item| { section.writeOperand(info.child, item); } }, .Struct => |info| { if (info.layout == .Packed) { section.writeWord(@bitCast(Word, operand)); } else { section.writeExtendedMask(Operand, operand); } }, .Union => section.writeExtendedUnion(Operand, operand), else => unreachable, }, } } fn writeString(section: *Section, str: []const u8) void { // TODO: Not actually sure whether this is correct for big-endian. // See https://www.khronos.org/registry/spir-v/specs/unified1/SPIRV.html#Literal const zero_terminated_len = str.len + 1; var i: usize = 0; while (i < zero_terminated_len) : (i += @sizeOf(Word)) { var word: Word = 0; var j: usize = 0; while (j < @sizeOf(Word) and i + j < str.len) : (j += 1) { word |= @as(Word, str[i + j]) << @intCast(Log2Word, j * @bitSizeOf(u8)); } section.instructions.appendAssumeCapacity(word); } } fn writeContextDependentNumber(section: *Section, operand: spec.LiteralContextDependentNumber) void { switch (operand) { .int32 => |int| section.writeWord(@bitCast(Word, int)), .uint32 => |int| section.writeWord(@bitCast(Word, int)), .int64 => |int| section.writeDoubleWord(@bitCast(DoubleWord, int)), .uint64 => |int| section.writeDoubleWord(@bitCast(DoubleWord, int)), .float32 => |float| section.writeWord(@bitCast(Word, float)), .float64 => |float| section.writeDoubleWord(@bitCast(DoubleWord, float)), } } fn writeExtendedMask(section: *Section, comptime Operand: type, operand: Operand) void { var mask: Word = 0; inline for (@typeInfo(Operand).Struct.fields) |field, bit| { switch (@typeInfo(field.field_type)) { .Optional => if (@field(operand, field.name) != null) { mask |= 1 << @intCast(u5, bit); }, .Bool => if (@field(operand, field.name)) { mask |= 1 << @intCast(u5, bit); }, else => unreachable, } } if (mask == 0) { return; } section.writeWord(mask); inline for (@typeInfo(Operand).Struct.fields) |field| { switch (@typeInfo(field.field_type)) { .Optional => |info| if (@field(operand, field.name)) |child| { section.writeOperands(info.child, child); }, .Bool => {}, else => unreachable, } } } fn writeExtendedUnion(section: *Section, comptime Operand: type, operand: Operand) void { const tag = std.meta.activeTag(operand); section.writeWord(@enumToInt(tag)); inline for (@typeInfo(Operand).Union.fields) |field| { if (@field(Operand, field.name) == tag) { section.writeOperands(field.field_type, @field(operand, field.name)); return; } } unreachable; } fn instructionSize(comptime opcode: spec.Opcode, operands: opcode.Operands()) usize { return 1 + operandsSize(opcode.Operands(), operands); } fn operandsSize(comptime Operands: type, operands: Operands) usize { const fields = switch (@typeInfo(Operands)) { .Struct => |info| info.fields, .Void => return 0, else => unreachable, }; var total: usize = 0; inline for (fields) |field| { total += operandSize(field.field_type, @field(operands, field.name)); } return total; } fn operandSize(comptime Operand: type, operand: Operand) usize { return switch (Operand) { spec.IdResultType, spec.IdResult, spec.IdRef, spec.LiteralInteger, spec.LiteralExtInstInteger, => 1, spec.LiteralString => std.math.divCeil(usize, operand.len + 1, @sizeOf(Word)) catch unreachable, // Add one for zero-terminator spec.LiteralContextDependentNumber => switch (operand) { .int32, .uint32, .float32 => @as(usize, 1), .int64, .uint64, .float64 => @as(usize, 2), }, // TODO: Where this type is used (OpSpecConstantOp) is currently not correct in the spec // json, so it most likely needs to be altered into something that can actually // describe the entire insturction in which it is used. spec.LiteralSpecConstantOpInteger => 1, spec.PairLiteralIntegerIdRef, spec.PairIdRefLiteralInteger, spec.PairIdRefIdRef, => 2, else => switch (@typeInfo(Operand)) { .Enum => 1, .Optional => |info| if (operand) |child| operandSize(info.child, child) else 0, .Pointer => |info| blk: { std.debug.assert(info.size == .Slice); // Should be no other pointer types in the spec. var total: usize = 0; for (operand) |item| { total += operandSize(info.child, item); } break :blk total; }, .Struct => |info| if (info.layout == .Packed) 1 else extendedMaskSize(Operand, operand), .Union => extendedUnionSize(Operand, operand), else => unreachable, }, }; } fn extendedMaskSize(comptime Operand: type, operand: Operand) usize { var total: usize = 0; var any_set = false; inline for (@typeInfo(Operand).Struct.fields) |field| { switch (@typeInfo(field.field_type)) { .Optional => |info| if (@field(operand, field.name)) |child| { total += operandsSize(info.child, child); any_set = true; }, .Bool => if (@field(operand, field.name)) { any_set = true; }, else => unreachable, } } if (!any_set) { return 0; } return total + 1; // Add one for the mask itself. } fn extendedUnionSize(comptime Operand: type, operand: Operand) usize { const tag = std.meta.activeTag(operand); inline for (@typeInfo(Operand).Union.fields) |field| { if (@field(Operand, field.name) == tag) { // Add one for the tag itself. return 1 + operandsSize(field.field_type, @field(operand, field.name)); } } unreachable; } test "SPIR-V Section emit() - no operands" { var section = Section{}; defer section.deinit(std.testing.allocator); try section.emit(std.testing.allocator, .OpNop, {}); try testing.expect(section.instructions.items[0] == (@as(Word, 1) << 16) | @enumToInt(Opcode.OpNop)); } test "SPIR-V Section emit() - simple" { var section = Section{}; defer section.deinit(std.testing.allocator); try section.emit(std.testing.allocator, .OpUndef, .{ .id_result_type = .{ .id = 0 }, .id_result = .{ .id = 1 }, }); try testing.expectEqualSlices(Word, &.{ (@as(Word, 3) << 16) | @enumToInt(Opcode.OpUndef), 0, 1, }, section.instructions.items); } test "SPIR-V Section emit() - string" { var section = Section{}; defer section.deinit(std.testing.allocator); try section.emit(std.testing.allocator, .OpSource, .{ .source_language = .Unknown, .version = 123, .file = .{ .id = 456 }, .source = "pub fn main() void {}", }); try testing.expectEqualSlices(Word, &.{ (@as(Word, 10) << 16) | @enumToInt(Opcode.OpSource), @enumToInt(spec.SourceLanguage.Unknown), 123, 456, std.mem.bytesToValue(Word, "pub "), std.mem.bytesToValue(Word, "fn m"), std.mem.bytesToValue(Word, "ain("), std.mem.bytesToValue(Word, ") vo"), std.mem.bytesToValue(Word, "id {"), std.mem.bytesToValue(Word, "}\x00\x00\x00"), }, section.instructions.items); } test "SPIR-V Section emit()- extended mask" { var section = Section{}; defer section.deinit(std.testing.allocator); try section.emit(std.testing.allocator, .OpLoopMerge, .{ .merge_block = .{ .id = 10 }, .continue_target = .{ .id = 20 }, .loop_control = .{ .Unroll = true, .DependencyLength = .{ .literal_integer = 2, }, }, }); try testing.expectEqualSlices(Word, &.{ (@as(Word, 5) << 16) | @enumToInt(Opcode.OpLoopMerge), 10, 20, @bitCast(Word, spec.LoopControl{ .Unroll = true, .DependencyLength = true }), 2, }, section.instructions.items); } test "SPIR-V Section emit() - extended union" { var section = Section{}; defer section.deinit(std.testing.allocator); try section.emit(std.testing.allocator, .OpExecutionMode, .{ .entry_point = .{ .id = 888 }, .mode = .{ .LocalSize = .{ .x_size = 4, .y_size = 8, .z_size = 16 }, }, }); try testing.expectEqualSlices(Word, &.{ (@as(Word, 6) << 16) | @enumToInt(Opcode.OpExecutionMode), 888, @enumToInt(spec.ExecutionMode.LocalSize), 4, 8, 16, }, section.instructions.items); }
src/codegen/spirv/Section.zig
const std = @import("std"); const Rom = @import("rom.zig").Rom; pub const Mbc = union(enum) { Boot: MbcBoot, None: MbcNone, pub fn init(rom: *Rom) Mbc { switch (rom.header.cartridge_type) { 0x00 => return Mbc{ .None = MbcNone.init(rom.content) }, else => unreachable, } } pub fn read(mbc: *Mbc, address: u16) u8 { return switch (mbc.*) { Mbc.Boot => |*m| m.read(address), Mbc.None => |*m| m.read(address), }; } pub fn write(mbc: *Mbc, address: u16, value: u8) void { return switch (mbc.*) { Mbc.Boot => |*m| m.write(address, value), Mbc.None => |*m| m.write(address, value), }; } }; pub const MbcBoot = struct { const boot_rom = [256]u8{ 0x31, 0xFE, 0xFF, 0xAF, 0x21, 0xFF, 0x9F, 0x32, 0xCB, 0x7C, 0x20, 0xFB, 0x21, 0x26, 0xFF, 0x0E, 0x11, 0x3E, 0x80, 0x32, 0xE2, 0x0C, 0x3E, 0xF3, 0xE2, 0x32, 0x3E, 0x77, 0x77, 0x3E, 0xFC, 0xE0, 0x47, 0x11, 0x04, 0x01, 0x21, 0x10, 0x80, 0x1A, 0xCD, 0x95, 0x00, 0xCD, 0x96, 0x00, 0x13, 0x7B, 0xFE, 0x34, 0x20, 0xF3, 0x11, 0xD8, 0x00, 0x06, 0x08, 0x1A, 0x13, 0x22, 0x23, 0x05, 0x20, 0xF9, 0x3E, 0x19, 0xEA, 0x10, 0x99, 0x21, 0x2F, 0x99, 0x0E, 0x0C, 0x3D, 0x28, 0x08, 0x32, 0x0D, 0x20, 0xF9, 0x2E, 0x0F, 0x18, 0xF3, 0x67, 0x3E, 0x64, 0x57, 0xE0, 0x42, 0x3E, 0x91, 0xE0, 0x40, 0x04, 0x1E, 0x02, 0x0E, 0x0C, 0xF0, 0x44, 0xFE, 0x90, 0x20, 0xFA, 0x0D, 0x20, 0xF7, 0x1D, 0x20, 0xF2, 0x0E, 0x13, 0x24, 0x7C, 0x1E, 0x83, 0xFE, 0x62, 0x28, 0x06, 0x1E, 0xC1, 0xFE, 0x64, 0x20, 0x06, 0x7B, 0xE2, 0x0C, 0x3E, 0x87, 0xF2, 0xF0, 0x42, 0x90, 0xE0, 0x42, 0x15, 0x20, 0xD2, 0x05, 0x20, 0x4F, 0x16, 0x20, 0x18, 0xCB, 0x4F, 0x06, 0x04, 0xC5, 0xCB, 0x11, 0x17, 0xC1, 0xCB, 0x11, 0x17, 0x05, 0x20, 0xF5, 0x22, 0x23, 0x22, 0x23, 0xC9, 0xCE, 0xED, 0x66, 0x66, 0xCC, 0x0D, 0x00, 0x0B, 0x03, 0x73, 0x00, 0x83, 0x00, 0x0C, 0x00, 0x0D, 0x00, 0x08, 0x11, 0x1F, 0x88, 0x89, 0x00, 0x0E, 0xDC, 0xCC, 0x6E, 0xE6, 0xDD, 0xDD, 0xD9, 0x99, 0xBB, 0xBB, 0x67, 0x63, 0x6E, 0x0E, 0xEC, 0xCC, 0xDD, 0xDC, 0x99, 0x9F, 0xBB, 0xB9, 0x33, 0x3E, 0x3c, 0x42, 0xB9, 0xA5, 0xB9, 0xA5, 0x42, 0x4C, 0x21, 0x04, 0x01, 0x11, 0xA8, 0x00, 0x1A, 0x13, 0xBE, 0x20, 0xFE, 0x23, 0x7D, 0xFE, 0x34, 0x20, 0xF5, 0x06, 0x19, 0x78, 0x86, 0x23, 0x05, 0x20, 0xFB, 0x86, 0x20, 0xFE, 0x3E, 0x01, 0xE0, 0x50, }; pub fn init() MbcBoot { return MbcBoot{}; } pub fn read(mbc: *MbcBoot, address: u16) u8 { switch (address) { 0x0000...0x0100 => { return boot_rom[address]; }, else => { unreachable; }, } } pub fn write(mbc: *MbcBoot, address: u16, value: u8) void { switch (address) { 0x0000...0x0100 => { // read-only }, else => { unreachable; }, } } }; pub const MbcNone = struct { rom: []u8, pub fn init(rom: []u8) MbcNone { return MbcNone{ .rom = rom }; } pub fn read(mbc: *MbcNone, address: u16) u8 { switch (address) { // 32Kb ROM 0x0000...0x7FFF => { return mbc.rom[address]; }, // 8Kb RAM 0xA000...0xBFFF => { return mbc.rom[address]; }, else => { unreachable; }, } } pub fn write(mbc: *MbcNone, address: u16, value: u8) void { switch (address) { // 32Kb ROM 0x0000...0x7FFF => { // read-only }, // 8Kb RAM 0xA000...0xBFFF => { mbc.rom[address] = value; }, else => { unreachable; }, } } };
src/mbc.zig
const builtin = @import("builtin"); const TypeId = builtin.TypeId; const std = @import("std"); const time = std.os.time; const mem = std.mem; const math = std.math; const Allocator = mem.Allocator; const assert = std.debug.assert; const warn = std.debug.warn; const gl = @import("modules/zig-sdl2/src/index.zig"); const misc = @import("modules/zig-misc/index.zig"); const saturateCast = misc.saturateCast; const colorns = @import("color.zig"); const Color = colorns.Color; const ColorU8 = colorns.ColorU8; const geo = @import("modules/zig-geometry/index.zig"); const V2f32 = geo.V2f32; const V3f32 = geo.V3f32; const M44f32 = geo.M44f32; const parseJsonFile = @import("modules/zig-json/parse_json_file.zig").parseJsonFile; const createMeshFromBabylonJson = @import("create_mesh_from_babylon_json.zig").createMeshFromBabylonJson; const Camera = @import("camera.zig").Camera; const meshns = @import("modules/zig-geometry/mesh.zig"); const Mesh = meshns.Mesh; const Vertex = meshns.Vertex; const Face = meshns.Face; const Texture = @import("texture.zig").Texture; const ki = @import("keyboard_input.zig"); const DBG = false; const DBG1 = false; const DBG2 = false; const DBG3 = false; const DBG_RenderUsingMode = false; const DBG_RenderUsingModeInner = false; const DBG_RenderUsingModeWaitForKey = false; const DBG_PutPixel = false; const DBG_DrawTriangle = false; const DBG_DrawTriangleInner = false; const DBG_ProcessScanLine = false; const DBG_ProcessScanLineInner = false; pub const Entity = struct { mesh: Mesh, texture: ?Texture, }; pub const RenderMode = enum { Points, Lines, Triangles, }; const DBG_RenderMode = RenderMode.Points; const ScanLineData = struct { pub y: isize, pub ndotla: f32, pub ndotlb: f32, pub ndotlc: f32, pub ndotld: f32, pub ua: f32, pub ub: f32, pub uc: f32, pub ud: f32, pub va: f32, pub vb: f32, pub vc: f32, pub vd: f32, }; pub const Window = struct { const Self = @This(); const ZbufferType = f32; pAllocator: *Allocator, width: usize, widthci: c_int, widthf: f32, height: usize, heightci: c_int, heightf: f32, name: []const u8, bg_color: ColorU8, pixels: []u32, zbuffer: []ZbufferType, sdl_window: *gl.SDL_Window, sdl_renderer: *gl.SDL_Renderer, sdl_texture: *gl.SDL_Texture, pub fn init(pAllocator: *Allocator, width: usize, height: usize, name: []const u8) !Self { var self = Self{ .pAllocator = pAllocator, .bg_color = undefined, .width = width, .widthci = @intCast(c_int, width), .widthf = @intToFloat(f32, width), .height = height, .heightci = @intCast(c_int, height), .heightf = @intToFloat(f32, height), .name = name, .pixels = try pAllocator.alloc(u32, width * height), .zbuffer = try pAllocator.alloc(f32, width * height), .sdl_window = undefined, .sdl_renderer = undefined, .sdl_texture = undefined, }; self.setBgColor(ColorU8.Black); // Initialize SDL if (gl.SDL_Init(gl.SDL_INIT_VIDEO | gl.SDL_INIT_AUDIO) != 0) { return error.FailedSdlInitialization; } errdefer gl.SDL_Quit(); // Initialize SDL image if (gl.IMG_Init(gl.IMG_INIT_JPG) != @intCast(c_int, gl.IMG_INIT_JPG)) { return error.FailedSdlImageInitialization; } errdefer gl.IMG_Quit(); // Create Window const x_pos: c_int = gl.SDL_WINDOWPOS_UNDEFINED; const y_pos: c_int = gl.SDL_WINDOWPOS_UNDEFINED; var window_flags: u32 = 0; self.sdl_window = gl.SDL_CreateWindow(c"zig-3d-soft-engine", x_pos, y_pos, self.widthci, self.heightci, window_flags) orelse { return error.FailedSdlWindowInitialization; }; errdefer gl.SDL_DestroyWindow(self.sdl_window); // This reduces CPU utilization but now dragging window is jerky { var r = gl.SDL_GL_SetSwapInterval(1); if (r != 0) { var b = gl.SDL_SetHint(gl.SDL_HINT_RENDER_VSYNC, c"1"); if (b != gl.SDL_bool.SDL_TRUE) { warn("No VSYNC cpu utilization may be high!\n"); } } } // Create Renderer var renderer_flags: u32 = 0; self.sdl_renderer = gl.SDL_CreateRenderer(self.sdl_window, -1, renderer_flags) orelse { return error.FailedSdlRendererInitialization; }; errdefer gl.SDL_DestroyRenderer(self.sdl_renderer); // Create Texture self.sdl_texture = gl.SDL_CreateTexture(self.sdl_renderer, gl.SDL_PIXELFORMAT_ARGB8888, gl.SDL_TEXTUREACCESS_STATIC, self.widthci, self.heightci) orelse { return error.FailedSdlTextureInitialization; }; errdefer gl.SDL_DestroyTexture(self.sdl_texture); self.clear(); return self; } pub fn deinit(pSelf: *Self) void { gl.SDL_DestroyTexture(pSelf.sdl_texture); gl.SDL_DestroyRenderer(pSelf.sdl_renderer); gl.SDL_DestroyWindow(pSelf.sdl_window); gl.SDL_Quit(); } pub fn setBgColor(pSelf: *Self, color: ColorU8) void { pSelf.bg_color = color; } pub fn clearZbufferValue(pSelf: *Self) ZbufferType { return misc.maxValue(ZbufferType); } pub fn clear(pSelf: *Self) void { // Init Pixel buffer for (pSelf.pixels) |*pixel| { pixel.* = pSelf.bg_color.asU32Argb(); } for (pSelf.zbuffer) |*elem| { elem.* = pSelf.clearZbufferValue(); } } pub fn putPixel(pSelf: *Self, x: usize, y: usize, z: f32, color: ColorU8) void { if (DBG_PutPixel) warn("putPixel: x={} y={} z={.3} c={}\n", x, y, z, &color); var index = (y * pSelf.width) + x; // +Z is towards screen so (-Z is away from screen) so if z is behind // or equal to (>=) a previouly written pixel just return. // NOTE: First value written, if they are equal, will be visible. Is this what we want? if (z >= pSelf.zbuffer[index]) return; pSelf.zbuffer[index] = z; pSelf.pixels[index] = color.asU32Argb(); } pub fn getPixel(pSelf: *Self, x: usize, y: usize) u32 { return pSelf.pixels[(y * pSelf.width) + x]; } pub fn present(pSelf: *Self) void { _ = gl.SDL_UpdateTexture(pSelf.sdl_texture, null, @ptrCast(*const c_void, &pSelf.pixels[0]), pSelf.widthci * @sizeOf(@typeOf(pSelf.pixels[0]))); _ = gl.SDL_RenderClear(pSelf.sdl_renderer); _ = gl.SDL_RenderCopy(pSelf.sdl_renderer, pSelf.sdl_texture, null, null); _ = gl.SDL_RenderPresent(pSelf.sdl_renderer); } /// Project takes a 3D coord and converts it to a 2D point /// using the transform matrix. pub fn projectRetV2f32(pSelf: *Self, coord: V3f32, transMat: *const M44f32) V2f32 { if (DBG1) warn("projectRetV2f32: original coord={} widthf={.3} heightf={.3}\n", &coord, pSelf.widthf, pSelf.heightf); return geo.projectToScreenCoord(pSelf.widthf, pSelf.heightf, coord, transMat); } /// Draw a Vec2 point in screen coordinates clipping it if its outside the screen pub fn drawPointV2f32(pSelf: *Self, point: V2f32, color: ColorU8) void { pSelf.drawPointXy(@floatToInt(isize, point.x()), @floatToInt(isize, point.y()), color); } /// Draw a point defined by x, y in screen coordinates clipping it if its outside the screen pub fn drawPointXy(pSelf: *Self, x: isize, y: isize, color: ColorU8) void { //if (DBG) warn("drawPointXy: x={} y={} c={}\n", x, y, &color); if ((x >= 0) and (y >= 0)) { var ux = @bitCast(usize, x); var uy = @bitCast(usize, y); if ((ux < pSelf.width) and (uy < pSelf.height)) { //if (DBG) warn("drawPointXy: putting x={} y={} c={}\n", ux, uy, &color); pSelf.putPixel(ux, uy, -pSelf.clearZbufferValue(), color); } } } /// Draw a point defined by x, y in screen coordinates clipping it if its outside the screen pub fn drawPointXyz(pSelf: *Self, x: isize, y: isize, z: f32, color: ColorU8) void { //if (DBG) warn("drawPointXyz: x={} y={} z={.3} c={}\n", x, y, &color); if ((x >= 0) and (y >= 0)) { var ux = @bitCast(usize, x); var uy = @bitCast(usize, y); if ((ux < pSelf.width) and (uy < pSelf.height)) { //if (DBG) warn("drawPointXyz: putting x={} y={} c={}\n", ux, uy, &color); pSelf.putPixel(ux, uy, z, color); } } } /// Draw a line point0 and 1 are in screen coordinates pub fn drawLine(pSelf: *Self, point0: V2f32, point1: V2f32, color: ColorU8) void { var diff = point1.sub(&point0); var dist = diff.length(); //if (DBG) warn("drawLine: diff={} dist={}\n", diff, dist); if (dist < 2) return; var diff_half = diff.scale(0.5); var mid_point = point0.add(&diff_half); //if (DBG) warn("drawLe: diff_half={} mid_point={}\n", diff_half, mid_point); pSelf.drawPointV2f32(mid_point, color); pSelf.drawLine(point0, mid_point, color); pSelf.drawLine(mid_point, point1, color); } /// Draw a line point0 and 1 are in screen coordinates using Bresnham algorithm pub fn drawBline(pSelf: *Self, point0: V2f32, point1: V2f32, color: ColorU8) void { //@setRuntimeSafety(false); var x0 = @floatToInt(isize, point0.x()); var y0 = @floatToInt(isize, point0.y()); var x1 = @floatToInt(isize, point1.x()); var y1 = @floatToInt(isize, point1.y()); var dx: isize = math.absInt(x1 - x0) catch unreachable; var dy: isize = math.absInt(y1 - y0) catch unreachable; var sx: isize = if (x0 < x1) isize(1) else isize(-1); var sy: isize = if (y0 < y1) isize(1) else isize(-1); var err: isize = dx - dy; while (true) { pSelf.drawPointXy(x0, y0, color); if ((x0 == x1) and (y0 == y1)) break; var e2: isize = 2 * err; if (e2 > -dy) { err -= dy; x0 += sx; } else { err += dx; y0 += sy; } } } /// Project takes a 3D coord and converts it to a 2D point /// using the transform matrix. pub fn projectRetVertex(pSelf: *Self, vertex: Vertex, transMat: *const M44f32, worldMat: *const M44f32) Vertex { if (DBG1) warn("projectRetVertex: original coord={} widthf={.3} heightf={.3}\n", &vertex.coord, pSelf.widthf, pSelf.heightf); var point = vertex.coord.transform(transMat); var point_world = vertex.coord.transform(worldMat); var normal_world = vertex.normal_coord.transform(worldMat); var x = (point.x() * pSelf.widthf) + (pSelf.widthf / 2.0); var y = (-point.y() * pSelf.heightf) + (pSelf.heightf / 2.0); return Vertex{ .coord = V3f32.init(x, y, point.z()), .world_coord = point_world, .normal_coord = normal_world, .texture_coord = vertex.texture_coord, }; } /// Draw a V3f32 point in screen coordinates clipping it if its outside the screen pub fn drawPointV3f32(pSelf: *Self, point: V3f32, color: ColorU8) void { pSelf.drawPointXyz(@floatToInt(isize, math.trunc(point.x())), @floatToInt(isize, math.trunc(point.y())), point.z(), color); } /// Clamp value to between min and max parameters pub fn clamp(value: f32, min: f32, max: f32) f32 { return math.max(min, math.min(value, max)); } /// Interplate between min and max as a percentage between /// min and max as defined by the gradient. With 0.0 <= gradiant <= 1.0. pub fn interpolate(min: f32, max: f32, gradient: f32) f32 { return min + (max - min) * clamp(gradient, 0, 1); } /// Compute the normal dot light pub fn computeNormalDotLight(vertex: V3f32, normal: V3f32, light_pos: V3f32) f32 { var light_direction = light_pos.sub(&vertex); var nrml = normal.normalize(); light_direction = light_direction.normalize(); var ndotl = nrml.dot(&light_direction); var r = math.max(0, ndotl); if (DBG3) warn("computeNormalDotLight: ndotl={} r={}\n", ndotl, r); return r; } /// Draw a horzitontal scan line at y between line a lined defined by /// va:vb to another defined line vc:vd. It is assumed they have /// already been sorted and we're drawing horizontal lines with /// line va:vb on the left and vc:vd on the right. pub fn processScanLine(pSelf: *Self, scanLineData: ScanLineData, va: Vertex, vb: Vertex, vc: Vertex, vd: Vertex, color: ColorU8, texture: ?Texture) void { var pa = va.coord; var pb = vb.coord; var pc = vc.coord; var pd = vd.coord; // Compute the gradiants and if the line are just points then gradient is 1 const gradient1: f32 = if (pa.y() == pb.y()) 1 else (@intToFloat(f32, scanLineData.y) - pa.y()) / (pb.y() - pa.y()); const gradient2: f32 = if (pc.y() == pd.y()) 1 else (@intToFloat(f32, scanLineData.y) - pc.y()) / (pd.y() - pc.y()); // Define the start and end point for x var sx: isize = @floatToInt(isize, interpolate(pa.x(), pb.x(), gradient1)); var ex: isize = @floatToInt(isize, interpolate(pc.x(), pd.x(), gradient2)); // Define the start and end point for z var sz: f32 = interpolate(pa.z(), pb.z(), gradient1); var ez: f32 = interpolate(pc.z(), pd.z(), gradient2); // Define the start and end point for normal dot light var snl: f32 = interpolate(scanLineData.ndotla, scanLineData.ndotlb, gradient1); var enl: f32 = interpolate(scanLineData.ndotlc, scanLineData.ndotld, gradient2); // Define the start and end for texture u/v var su: f32 = interpolate(scanLineData.ua, scanLineData.ub, gradient1); var eu: f32 = interpolate(scanLineData.uc, scanLineData.ud, gradient2); var sv: f32 = interpolate(scanLineData.va, scanLineData.vb, gradient1); var ev: f32 = interpolate(scanLineData.vc, scanLineData.vd, gradient2); // Draw a horzitional line between start and end if (scanLineData.y >= 0) { // Check if y is negative so our v casting works var x: isize = sx; if (DBG_ProcessScanLine) warn("processScanLine: y={} sx={} ex={} cnt={}\n", scanLineData.y, sx, ex, ex - sx); while (x < ex) : (x += 1) { var gradient: f32 = @intToFloat(f32, (x - sx)) / @intToFloat(f32, (ex - sx)); var z = interpolate(sz, ez, gradient); var ndotl = interpolate(snl, enl, gradient); var u = interpolate(su, eu, gradient); var v = interpolate(sv, ev, gradient); if (x >= 0) { // Check if x is negative so our u casting works var c: ColorU8 = undefined; if (texture) |t| { c = t.map(u, v, color); if (DBG_ProcessScanLineInner) warn("processScanLine: c={}\n", &c); } else { c = color; } pSelf.drawPointXyz(x, scanLineData.y, z, c.colorScale(ndotl)); } } } } pub fn drawTriangle(pSelf: *Self, v1: Vertex, v2: Vertex, v3: Vertex, color: ColorU8, texture: ?Texture) void { if (DBG_DrawTriangle) warn("drawTriangle:\n v1={}\n v2={}\n v3={}\n", v1, v2, v3); // Sort the points finding top, mid, bottom. var t = v1; // Top var m = v2; // Mid var b = v3; // Bottom // Find top, i.e. the point with the smallest y value if (t.coord.y() > m.coord.y()) { mem.swap(Vertex, &t, &m); } if (m.coord.y() > b.coord.y()) { mem.swap(Vertex, &m, &b); } if (t.coord.y() > m.coord.y()) { mem.swap(Vertex, &t, &m); } if (DBG_DrawTriangle) warn("drawTriangle:\n t={}\n m={}\n b={}\n", t, m, b); var light_pos = V3f32.init(0, 10, -10); var t_ndotl = computeNormalDotLight(t.world_coord, t.normal_coord, light_pos); var m_ndotl = computeNormalDotLight(m.world_coord, m.normal_coord, light_pos); var b_ndotl = computeNormalDotLight(b.world_coord, b.normal_coord, light_pos); if (DBG_DrawTriangle) warn("drawTriangle:\n t_ndotl={}\n m_ndotl={}\n b_ndotl={}\n", t_ndotl, m_ndotl, b_ndotl); var scanLineData: ScanLineData = undefined; // Convert the top.coord.y, mid.coord.y and bottom.coord.y to integers var t_y = @floatToInt(isize, math.trunc(t.coord.y())); var m_y = @floatToInt(isize, math.trunc(m.coord.y())); var b_y = @floatToInt(isize, math.trunc(b.coord.y())); // Create top to mid line and top to bottom lines. // We then take the cross product of these lines and // if the result is positive then the mid is on the right // otherwise mid is on the left. // // See: https://www.davrous.com/2013/06/21/tutorial-part-4-learning-how-to-write-a-3d-software-engine-in-c-ts-or-js-rasterization-z-buffering/#comment-737 // and https://stackoverflow.com/questions/243945/calculating-a-2d-vectors-cross-product?answertab=votes#tab-top var t_m = V2f32.init(m.coord.x() - t.coord.x(), m.coord.y() - t.coord.y()); var t_b = V2f32.init(b.coord.x() - t.coord.x(), b.coord.y() - t.coord.y()); var t_m_cross_t_b = t_m.cross(&t_b); // Two cases, 1) triangles with mid on the right if (t_m_cross_t_b > 0) { if (DBG_DrawTriangle) warn("drawTriangle: mid RIGHT t_m_cross_t_b:{.5} > 0\n", t_m_cross_t_b); // Triangles with mid on the right // t // |\ // | \ // | \ // | m // | / // | / // |/ // b scanLineData.y = t_y; while (scanLineData.y <= b_y) : (scanLineData.y += 1) { if (scanLineData.y < m_y) { if (DBG_DrawTriangleInner) warn("drawTriangle: scanLineData.y:{} < m_y:{}\n", scanLineData.y, m_y); scanLineData.ndotla = t_ndotl; scanLineData.ndotlb = b_ndotl; scanLineData.ndotlc = t_ndotl; scanLineData.ndotld = m_ndotl; scanLineData.ua = v1.texture_coord.x(); scanLineData.ub = v3.texture_coord.x(); scanLineData.uc = v1.texture_coord.x(); scanLineData.ud = v2.texture_coord.x(); scanLineData.va = v1.texture_coord.y(); scanLineData.vb = v3.texture_coord.y(); scanLineData.vc = v1.texture_coord.y(); scanLineData.vd = v2.texture_coord.y(); pSelf.processScanLine(scanLineData, t, b, t, m, color, texture); } else { if (DBG_DrawTriangleInner) warn("drawTriangle: scanLineData.y:{} >= m_y:{}\n", scanLineData.y, m_y); scanLineData.ndotla = t_ndotl; scanLineData.ndotlb = b_ndotl; scanLineData.ndotlc = m_ndotl; scanLineData.ndotld = b_ndotl; scanLineData.ua = v1.texture_coord.x(); scanLineData.ub = v3.texture_coord.x(); scanLineData.uc = v2.texture_coord.x(); scanLineData.ud = v3.texture_coord.x(); scanLineData.va = v1.texture_coord.y(); scanLineData.vb = v3.texture_coord.y(); scanLineData.vc = v2.texture_coord.y(); scanLineData.vd = v3.texture_coord.y(); pSelf.processScanLine(scanLineData, t, b, m, b, color, texture); } } } else { if (DBG_DrawTriangle) warn("drawTriangle: mid LEFT t_m_cross_t_b:{.5} > 0\n", t_m_cross_t_b); // Triangles with mid on the left // t // /| // / | // / | // m | // \ | // \ | // \| // b scanLineData.y = t_y; while (scanLineData.y <= b_y) : (scanLineData.y += 1) { if (scanLineData.y < m_y) { if (DBG_DrawTriangleInner) warn("drawTriangle: scanLineData.y:{} < m_y:{}\n", scanLineData.y, m_y); scanLineData.ndotla = t_ndotl; scanLineData.ndotlb = m_ndotl; scanLineData.ndotlc = t_ndotl; scanLineData.ndotld = b_ndotl; scanLineData.ua = v1.texture_coord.x(); scanLineData.ub = v2.texture_coord.x(); scanLineData.uc = v1.texture_coord.x(); scanLineData.ud = v3.texture_coord.x(); scanLineData.va = v1.texture_coord.y(); scanLineData.vb = v2.texture_coord.y(); scanLineData.vc = v1.texture_coord.y(); scanLineData.vd = v3.texture_coord.y(); pSelf.processScanLine(scanLineData, t, m, t, b, color, texture); } else { if (DBG_DrawTriangleInner) warn("drawTriangle: scanLineData.y:{} >= m_y:{}\n", scanLineData.y, m_y); scanLineData.ndotla = m_ndotl; scanLineData.ndotlb = b_ndotl; scanLineData.ndotlc = t_ndotl; scanLineData.ndotld = b_ndotl; scanLineData.ua = v2.texture_coord.x(); scanLineData.ub = v3.texture_coord.x(); scanLineData.uc = v1.texture_coord.x(); scanLineData.ud = v3.texture_coord.x(); scanLineData.va = v2.texture_coord.y(); scanLineData.vb = v3.texture_coord.y(); scanLineData.vc = v1.texture_coord.y(); scanLineData.vd = v3.texture_coord.y(); pSelf.processScanLine(scanLineData, m, b, t, b, color, texture); } } } } /// Render the entities into the window from the camera's point of view pub fn renderUsingMode(pSelf: *Self, renderMode: RenderMode, camera: *const Camera, entities: []const Entity, negate_tnz: bool) void { var view_matrix: geo.M44f32 = undefined; view_matrix = geo.lookAtLh(&camera.position, &camera.target, &V3f32.unitY()); if (DBG_RenderUsingMode) warn("view_matrix:\n{}\n", &view_matrix); var fov: f32 = 70; var znear: f32 = 0.1; var zfar: f32 = 1000.0; var perspective_matrix = geo.perspectiveM44(f32, geo.rad(fov), pSelf.widthf / pSelf.heightf, znear, zfar); if (DBG_RenderUsingMode) warn("perspective_matrix: fov={.3}, znear={.3} zfar={.3}\n{}\n", fov, znear, zfar, &perspective_matrix); for (entities) |entity| { var mesh = entity.mesh; var rotation_matrix = geo.rotateCwPitchYawRollV3f32(mesh.rotation); if (DBG_RenderUsingMode) warn("rotation_matrix:\n{}\n", &rotation_matrix); var translation_matrix = geo.translationV3f32(mesh.position); if (DBG_RenderUsingMode) warn("translation_matrix:\n{}\n", &translation_matrix); var world_matrix = geo.mulM44f32(&translation_matrix, &rotation_matrix); if (DBG_RenderUsingMode) warn("world_matrix:\n{}\n", &world_matrix); var world_to_view_matrix = geo.mulM44f32(&world_matrix, &view_matrix); var transform_matrix = geo.mulM44f32(&world_to_view_matrix, &perspective_matrix); if (DBG_RenderUsingMode) warn("transform_matrix:\n{}\n", &transform_matrix); if (DBG_RenderUsingMode) warn("\n"); for (mesh.faces) |face, i| { const va = mesh.vertices[face.a]; const vb = mesh.vertices[face.b]; const vc = mesh.vertices[face.c]; if (DBG_RenderUsingModeInner) warn("va={} vb={} vc={}\n", va.coord, vb.coord, vc.coord); var color = ColorU8.init(0xff, 0, 0xff, 0xff); switch (renderMode) { RenderMode.Points => { const pa = pSelf.projectRetV2f32(va.coord, &transform_matrix); const pb = pSelf.projectRetV2f32(vb.coord, &transform_matrix); const pc = pSelf.projectRetV2f32(vc.coord, &transform_matrix); if (DBG_RenderUsingModeInner) warn("pa={} pb={} pc={}\n", pa, pb, pc); pSelf.drawPointV2f32(pa, color); pSelf.drawPointV2f32(pb, color); pSelf.drawPointV2f32(pc, color); }, RenderMode.Lines => { const pa = pSelf.projectRetV2f32(va.coord, &transform_matrix); const pb = pSelf.projectRetV2f32(vb.coord, &transform_matrix); const pc = pSelf.projectRetV2f32(vc.coord, &transform_matrix); if (DBG_RenderUsingModeInner) warn("pa={} pb={} pc={}\n", pa, pb, pc); pSelf.drawBline(pa, pb, color); pSelf.drawBline(pb, pc, color); pSelf.drawBline(pc, pa, color); }, RenderMode.Triangles => { // Transform face.normal to world_to_view_matrix and only render // faces which can be "seen" by the camera. // Bugs: 1) See "rendering bug" // https://www.davrous.com/2013/07/18/tutorial-part-6-learning-how-to-write-a-3d-software-engine-in-c-ts-or-js-texture-mapping-back-face-culling-webgl // it says that perspective isn't being taken into account and some triangles are not drawn when they should be. // // 2) I have to "negate_tnz" tnz so the expected triangles are VISIBLE so "if (tnz < 0) {" works. // In the tutorial we have "if (transformedNormal < 0) {", // see: http://david.blob.core.windows.net/softengine3d/SoftEngineJSPart6Sample2.zip var tnz = face.normal.transformNormal(&world_to_view_matrix).z(); tnz = if (negate_tnz) -tnz else tnz; if (tnz < 0) { if (DBG_RenderUsingModeInner) warn("VISIBLE face.normal:{} tnz:{}\n", &face.normal, &tnz); // Transform the vertex's const tva = pSelf.projectRetVertex(va, &transform_matrix, &world_matrix); const tvb = pSelf.projectRetVertex(vb, &transform_matrix, &world_matrix); const tvc = pSelf.projectRetVertex(vc, &transform_matrix, &world_matrix); var colorF32: f32 = undefined; //colorF32 = 0.25 + @intToFloat(f32, i % mesh.faces.len) * (0.75 / @intToFloat(f32, mesh.faces.len)); colorF32 = 1.0; var colorU8: u8 = saturateCast(u8, math.round(colorF32 * 256.0)); color = ColorU8.init(colorU8, colorU8, colorU8, colorU8); pSelf.drawTriangle(tva, tvb, tvc, color, entity.texture); if (DBG_RenderUsingModeInner) warn("tva={} tvb={} tvc={} color={}\n", tva.coord, tvb.coord, tvc.coord, &color); } else { if (DBG_RenderUsingModeInner) warn("HIDDEN face.normal:{} tnz:{}\n", &face.normal, &tnz); } }, } if (DBG_RenderUsingModeWaitForKey) { pSelf.present(); _ = ki.waitForKey("dt", true, DBG_RenderUsingModeWaitForKey); } } } } pub fn render(pSelf: *Self, camera: *const Camera, entities: []const Entity) void { renderUsingMode(pSelf, DBG_RenderMode, camera, entities, true); } };
src/window.zig
const os = @import("root").os; const std = @import("std"); // Submodules pub const acpi = @import("acpi.zig"); pub const pci = @import("pci.zig"); pub const devicetree = @import("devicetree.zig"); pub const smp = @import("smp.zig"); // Anything else comes from this platform specific file const arch = @import("builtin").arch; usingnamespace @import( switch(arch) { .aarch64 => "aarch64/aarch64.zig", .x86_64 => "x86_64/x86_64.zig", else => unreachable, } ); const assert = @import("std").debug.assert; pub const PageFaultAccess = enum { Read, Write, InstructionFetch, }; fn attempt_handle_physmem_page_fault(base: usize, addr: usize, map_type: os.platform.paging.MemoryType) bool { if(base <= addr and addr < base + os.memory.paging.kernel_context.max_phys) { // Map 1G of this memory const phys = addr - base; const phys_gb_aligned = os.lib.libalign.align_down(usize, 1024 * 1024 * 1024, phys); os.vital(os.memory.paging.map_phys(.{ .virt = base + phys_gb_aligned, .phys = phys_gb_aligned, .size = 1024 * 1024 * 1024, .perm = os.memory.paging.rw(), .memtype = map_type, }), "Lazily mapping physmem"); return true; } return false; } fn handle_physmem_page_fault(addr: usize) bool { return false or attempt_handle_physmem_page_fault(os.memory.paging.kernel_context.wb_virt_base, addr, .MemoryWriteBack) or attempt_handle_physmem_page_fault(os.memory.paging.kernel_context.wc_virt_base, addr, .DeviceWriteCombining) or attempt_handle_physmem_page_fault(os.memory.paging.kernel_context.uc_virt_base, addr, .DeviceUncacheable) ; } pub fn page_fault(addr: usize, present: bool, access: PageFaultAccess, frame: anytype) void { // We lazily map some physical memory, see if this is what's happening if(!present) { switch(access) { .Read, .Write => if(handle_physmem_page_fault(addr)) return, else => {}, } } os.log("Platform: Unhandled page fault on {s} at 0x{x}, present: {}\n", .{ @tagName(access), addr, present, } ); frame.dump(); frame.trace_stack(); @panic("Page fault"); } pub fn hang() noreturn { _ = get_and_disable_interrupts(); while(true) { await_interrupt(); } } pub fn set_current_task(task_ptr: *os.thread.Task) void { thread.get_current_cpu().current_task = task_ptr; } pub fn get_current_task() *os.thread.Task { return thread.get_current_cpu().current_task; } pub const virt_slice = struct { ptr: usize, len: usize, }; pub fn phys_ptr(comptime ptr_type: type) type { return struct { addr: usize, pub fn get_writeback(self: *const @This()) ptr_type { return @intToPtr(ptr_type, os.memory.pmm.phys_to_write_back_virt(self.addr)); } pub fn get_write_combining(self: *const @This()) ptr_type { return @intToPtr(ptr_type, os.memory.pmm.phys_to_write_combining_virt(self.addr)); } pub fn get_uncached(self: *const @This()) ptr_type { return @intToPtr(ptr_type, os.memory.pmm.phys_to_uncached_virt(self.addr)); } pub fn from_int(a: usize) @This() { return .{ .addr = a, }; } pub fn format(self: *const @This(), fmt: []const u8, options: std.fmt.FormatOptions, writer: anytype) !void { try writer.print("phys 0x{X}", .{self.addr}); } }; } pub fn phys_slice(comptime T: type) type { return struct { ptr: phys_ptr([*]T), len: usize, pub fn init(addr: usize, len: usize) @This() { return .{ .ptr = phys_ptr([*]T).from_int(addr), .len = len, }; } pub fn to_slice_writeback(self: *const @This()) []T { return self.ptr.get_writeback()[0..self.len]; } pub fn to_slice_write_combining(self: *const @This()) []T { return self.ptr.get_write_combining()[0..self.len]; } pub fn to_slice_uncached(self: *const @This()) []T { return self.ptr.get_uncached()[0..self.len]; } }; } pub const PhysBytes = struct { ptr: usize, len: usize, };
src/platform/platform.zig
usingnamespace @import("ncurses").ncurses; pub fn main() anyerror!void { _ = try initscr(); try addstrzig("Upper left corner "); try addch(ACS_ULCORNER); try addstrzig("\n"); try addstrzig("Lower left corner "); try addch(ACS_LLCORNER); try addstrzig("\n"); try addstrzig("Upper right corner "); try addch(ACS_URCORNER); try addstrzig("\n"); try addstrzig("Lower right corner "); try addch(ACS_LRCORNER); try addstrzig("\n"); try addstrzig("Tee pointing right "); try addch(ACS_LTEE); try addstrzig("\n"); try addstrzig("Tee pointing left "); try addch(ACS_RTEE); try addstrzig("\n"); try addstrzig("Tee pointing up "); try addch(ACS_BTEE); try addstrzig("\n"); try addstrzig("Tee pointing down "); try addch(ACS_TTEE); try addstrzig("\n"); try addstrzig("Horizontal line "); try addch(ACS_HLINE); try addstrzig("\n"); try addstrzig("Vertical line "); try addch(ACS_VLINE); try addstrzig("\n"); try addstrzig("Large Plus or cross over "); try addch(ACS_PLUS); try addstrzig("\n"); try addstrzig("Scan Line 1 "); try addch(ACS_S1); try addstrzig("\n"); try addstrzig("Scan Line 3 "); try addch(ACS_S3); try addstrzig("\n"); try addstrzig("Scan Line 7 "); try addch(ACS_S7); try addstrzig("\n"); try addstrzig("Scan Line 9 "); try addch(ACS_S9); try addstrzig("\n"); try addstrzig("Diamond "); try addch(ACS_DIAMOND); try addstrzig("\n"); try addstrzig("Checker board (stipple) "); try addch(ACS_CKBOARD); try addstrzig("\n"); try addstrzig("Degree Symbol "); try addch(ACS_DEGREE); try addstrzig("\n"); try addstrzig("Plus/Minus Symbol "); try addch(ACS_PLMINUS); try addstrzig("\n"); try addstrzig("Bullet "); try addch(ACS_BULLET); try addstrzig("\n"); try addstrzig("Arrow Pointing Left "); try addch(ACS_LARROW); try addstrzig("\n"); try addstrzig("Arrow Pointing Right "); try addch(ACS_RARROW); try addstrzig("\n"); try addstrzig("Arrow Pointing Down "); try addch(ACS_DARROW); try addstrzig("\n"); try addstrzig("Arrow Pointing Up "); try addch(ACS_UARROW); try addstrzig("\n"); try addstrzig("Board of squares "); try addch(ACS_BOARD); try addstrzig("\n"); try addstrzig("Lantern Symbol "); try addch(ACS_LANTERN); try addstrzig("\n"); try addstrzig("Solid Square Block "); try addch(ACS_BLOCK); try addstrzig("\n"); try addstrzig("Less/Equal sign "); try addch(ACS_LEQUAL); try addstrzig("\n"); try addstrzig("Greater/Equal sign "); try addch(ACS_GEQUAL); try addstrzig("\n"); try addstrzig("Pi "); try addch(ACS_PI); try addstrzig("\n"); try addstrzig("Not equal "); try addch(ACS_NEQUAL); try addstrzig("\n"); try addstrzig("UK pound sign "); try addch(ACS_STERLING); try addstrzig("\n"); try refresh(); _ = try getch(); try endwin(); }
examples/alternative_charset.zig
const std = @import("std"); const util = @import("util.zig"); const data = @embedFile("../data/day15.txt"); pub const PointNode = struct { const Self = @This(); position: util.Point(i32), priority: u32, pub fn lessThan(a: Self, b: Self) std.math.Order { return std.math.order(a.priority, b.priority); } }; pub const GridMap = struct { const Self = @This(); values: []u32, width: u32, allocator: *util.Allocator, pub fn init(allocator: *util.Allocator, width: u32, height: u32) !Self { const values = try allocator.alloc(u32, width * height); errdefer allocator.free(values); return Self{ .values = values, .width = width, .allocator = allocator, }; } pub fn initFromSerializedData(allocator: *util.Allocator, serialized_data: []const u8) !Self { var width: u32 = 0; const values = blk: { var values_list = util.List(u32).init(allocator); defer values_list.deinit(); var it = util.tokenize(u8, serialized_data, "\n"); // Parse each row while (it.next()) |row_data| { if (row_data.len == 0) continue; // Just in case we get an extra newline width = @intCast(u32, row_data.len); // For each row, parse the numbers (no in-row separator) for (row_data) |int_data| { if (int_data < '0' or int_data > '9') return error.InvalidInput; try values_list.append(int_data - '0'); } } break :blk values_list.toOwnedSlice(); }; errdefer allocator.free(values); // Return map return Self{ .values = values, .width = width, .allocator = allocator }; } /// Deallocates underlying representation of the map. pub fn deinit(self: *Self) void { self.allocator.free(self.values); } pub fn riskToGoalMap(self: Self) !Self { // Create equivalently sized map var goal_map = try Self.init(self.allocator, self.width, self.getHeight()); errdefer goal_map.deinit(); const end = util.Point(i32){ .x = @intCast(i32, goal_map.width - 1), .y = @intCast(i32, goal_map.getHeight() - 1) }; // Max out all values except for end, since we'll set end as the goal std.mem.set(u32, goal_map.values, std.math.maxInt(u32)); goal_map.setValue(end, 0); // Create queue for pathing var queue = std.PriorityQueue(PointNode, PointNode.lessThan).init(self.allocator); defer queue.deinit(); // Add end to queue try queue.add(PointNode{ .position = end, .priority = 0 }); while (queue.count() != 0) { // Pop minimum element var cur_node = queue.remove(); // If this is the case, this is a duplicate element; so we can skip it since we already // processed it with a lower priority if (cur_node.priority != goal_map.getValue(cur_node.position)) continue; // This path better than the one we had previously for this node, and is potentially // good for reaching nodes around it; queue up neighbors, if the path is better // depending on their entry cost. for (util.cardinalNeighbors) |direction| { const neighbor = util.Point(i32).add(cur_node.position, direction); if (neighbor.x < 0 or neighbor.x >= self.width or neighbor.y < 0 or neighbor.y >= self.getHeight()) continue; const neighbor_risk_value = self.getValue(neighbor); const neighbor_priority = goal_map.getValue(neighbor); // Calculate distance to reach adjacent neighbor using its risk cost const cost = cur_node.priority + neighbor_risk_value; // If the current path is better than the best one we've queued through thus far, // add to queue and update goal map. Not efficient because the priority queue // implementation isn't efficient at finding nodes, but fine for this purpose if (cost < neighbor_priority) { const new_neighbor_node = PointNode{ .position = neighbor, .priority = cost }; try queue.add(new_neighbor_node); goal_map.setValue(neighbor, cost); } } } return goal_map; } pub fn getValue(self: Self, pos: util.Point(i32)) u32 { return self.values[pos.toIndex(self.width)]; } pub fn setValue(self: *Self, pos: util.Point(i32), value: u32) void { self.values[pos.toIndex(self.width)] = value; } pub fn getHeight(self: Self) u32 { return @intCast(u32, self.values.len / self.width); } pub fn display(self: Self) void { var y: i32 = 0; while (y < self.getHeight()) : (y += 1) { var x: i32 = 0; while (x < self.width) : (x += 1) { util.print("{d}", .{self.getValue(.{ .x = x, .y = y })}); } util.print("\n", .{}); } } }; pub fn findLeastRiskValue(risk_map: GridMap) !u32 { // Translate map to a goal map var goal_map = try risk_map.riskToGoalMap(); defer goal_map.deinit(); // Roll downhill on goal map from start to goal, adding risk value of path along the way. var cur_pos = util.Point(i32){ .x = 0, .y = 0 }; const end = util.Point(i32){ .x = @intCast(i32, goal_map.width - 1), .y = @intCast(i32, goal_map.getHeight() - 1) }; var risk: u32 = 0; while (!std.meta.eql(cur_pos, end)) { // Find minimum neighbor and select it var min_pos: util.Point(i32) = cur_pos; for (util.cardinalNeighbors) |direction| { const neighbor = util.Point(i32).add(cur_pos, direction); if (neighbor.x < 0 or neighbor.x >= goal_map.width or neighbor.y < 0 or neighbor.y >= goal_map.getHeight()) continue; if (goal_map.getValue(neighbor) < goal_map.getValue(min_pos)) { min_pos = neighbor; } } // Add minimum cost to risk value and move to neighbor risk += risk_map.getValue(min_pos); cur_pos = min_pos; } return risk; } pub fn increaseValue(val: u32, times: u32) u32 { var cur_val: u32 = val; var i: u32 = 0; while (i < times) : (i += 1) { cur_val += 1; if (cur_val == 10) { cur_val = 1; } } return cur_val; } pub fn main() !void { defer { const leaks = util.gpa_impl.deinit(); std.debug.assert(!leaks); } // Read in risk map from input var risk_map_block = try GridMap.initFromSerializedData(util.gpa, data); defer risk_map_block.deinit(); //util.print("Risk map initial tile size is: {d}x{d}\n", .{ risk_map_block.width, risk_map_block.getHeight() }); // Find risk value for part 1 const risk_val_pt1 = try findLeastRiskValue(risk_map_block); util.print("Part 1: Risk value of best path is: {d}\n", .{risk_val_pt1}); // Create map for part 2; duplicate block 5x in both directions const tile_width = risk_map_block.width; const tile_height = risk_map_block.getHeight(); var risk_map = try GridMap.init(util.gpa, tile_width * 5, tile_height * 5); defer risk_map.deinit(); var y: u32 = 0; while (y < risk_map.width) : (y += 1) { var x: u32 = 0; while (x < risk_map.getHeight()) : (x += 1) { // Find corresponding position in original tile const orig_pos = util.Point(i32){ .x = @intCast(i32, x % tile_width), .y = @intCast(i32, y % tile_height) }; // Current value is that value, plus the number of tiles above or left, whichever is // greater. const tiles_preceding = x / tile_width + y / tile_height; risk_map.setValue(.{ .x = @intCast(i32, x), .y = @intCast(i32, y) }, increaseValue(risk_map_block.getValue(orig_pos), tiles_preceding)); } } // Find risk value for part 2 const risk_val_pt2 = try findLeastRiskValue(risk_map); util.print("Part 2: Risk value of best path is: {d}\n", .{risk_val_pt2}); }
src/day15.zig
const std = @import("std"); const ArrayList = std.ArrayList; const TextStyle = @import("style.zig").TextStyle; const mibu = @import("mibu"); const color = mibu.color; pub const Cell = struct { value: u21 = ' ', fg: []const u8 = color.fg(.default), bg: []const u8 = color.bg(.default), style: TextStyle = .default, }; /// Represents screen (2D) pub const Buffer = struct { size: mibu.term.TermSize = undefined, inner: []Cell, allocator: std.mem.Allocator, const Self = @This(); /// Inits a buffer pub fn init(allocator: std.mem.Allocator) Self { var size = mibu.term.getSize() catch unreachable; var inner = allocator.alloc(Cell, size.width * size.height) catch unreachable; std.mem.set(Cell, inner, .{}); return .{ .size = size, .allocator = allocator, .inner = inner, }; } pub fn deinit(self: *Self) void { self.allocator.free(self.inner); } pub fn reset(self: *Self) void { std.mem.set(Cell, self.inner, .{}); } /// Returns a reference of a cell based on col and row. /// Be careful about calling this func with out of bounds col or rows. pub fn getRef(self: *Self, x: usize, y: usize) *Cell { const row = y * self.size.width; return &self.inner[row + x]; } /// Resizes the buffer if is necesary (terminal size changed) /// Return true if it changed, false otherwise pub fn resize(self: *Self) !bool { const new_size = try mibu.term.getSize(); // size changed if (new_size.width != self.size.width or new_size.height != self.size.height) { self.size = new_size; var old_inner = self.inner; defer self.allocator.free(old_inner); self.inner = try self.allocator.alloc(Cell, new_size.width * new_size.height); self.reset(); return true; } return false; } pub const BufDiff = struct { x: usize, y: usize, c: *Cell, }; /// The caller should free (deinit) the return value pub fn diff(self: *Self, other: *Buffer) !ArrayList(BufDiff) { var updates = ArrayList(BufDiff).init(self.allocator); var i: usize = 0; while (i < self.inner.len) : (i += 1) { if (!std.meta.eql(self.inner[i], other.inner[i])) { try updates.append(.{ .x = i % self.size.width, .y = i / self.size.width, .c = &other.inner[i] }); } } return updates; } }; test "refAll" { std.testing.refAllDecls(@This()); }
src/buffer.zig
const std = @import("std"); const prometheus = @import("prometheus"); fn getRandomString(allocator: std.mem.Allocator, random: std.rand.Random, n: usize) ![]const u8 { const alphabet = "abcdefghijklmnopqrstuvwxyz"; var items = try allocator.alloc(u8, n); for (items) |*item| { const random_pos = random.intRangeLessThan(usize, 0, alphabet.len); item.* = alphabet[random_pos]; } return items; } pub fn main() anyerror!void { var arena = std.heap.ArenaAllocator.init(std.heap.page_allocator); var allocator = arena.allocator(); var random = std.rand.DefaultPrng.init(@bitCast(u64, std.time.milliTimestamp())).random(); // Initialize a registry var registry = try prometheus.Registry(.{}).create(allocator); defer registry.destroy(); // Get some counters { var i: usize = 0; while (i < 5) : (i += 1) { const name = try std.fmt.allocPrint(allocator, "http_requests_total{{route=\"/{s}\"}}", .{ try getRandomString(allocator, random, 20), }); var counter = try registry.getOrCreateCounter(name); counter.add(random.intRangeAtMost(u64, 0, 450000)); } } // Get some gauges sharing the same state. { const State = struct { random: std.rand.Random, }; var state = State{ .random = random }; var i: usize = 0; while (i < 5) : (i += 1) { const name = try std.fmt.allocPrint(allocator, "http_conn_pool_size{{name=\"{s}\"}}", .{ try getRandomString(allocator, random, 5), }); _ = try registry.getOrCreateGauge( name, &state, struct { fn get(s: *State) f64 { const n = s.random.intRangeAtMost(usize, 0, 2000); const f = s.random.float(f64); return f * @intToFloat(f64, n); } }.get, ); } } // Get a histogram { const name = try std.fmt.allocPrint(allocator, "http_requests_latency{{route=\"/{s}\"}}", .{ try getRandomString(allocator, random, 20), }); var histogram = try registry.getOrCreateHistogram(name); var i: usize = 0; while (i < 200) : (i += 1) { const duration = random.intRangeAtMost(usize, 0, 10000); histogram.update(@intToFloat(f64, duration)); } } // Finally serialize the metrics to stdout try registry.write(allocator, std.io.getStdOut().writer()); }
examples/basic/main.zig
const std = @import("std"); const builtin = std.builtin; const io = std.io; const fs = std.fs; const process = std.process; const ChildProcess = std.ChildProcess; const print = std.debug.print; const mem = std.mem; const testing = std.testing; const exe_ext = (std.zig.CrossTarget{}).exeFileExt(); const obj_ext = (std.zig.CrossTarget{}).oFileExt(); fn assertToken(tokenizer: *Tokenizer, token: Token, id: Token.Id) !void { if (token.id != id) { return parseError(tokenizer, token, "expected {}, found {}", .{ @tagName(id), @tagName(token.id) }); } } fn eatToken(tokenizer: *Tokenizer, id: Token.Id) !Token { const token = tokenizer.next(); try assertToken(tokenizer, token, id); return token; } const HeaderOpen = struct { name: []const u8, url: []const u8, n: usize, }; const SeeAlsoItem = struct { name: []const u8, token: Token, }; const ExpectedOutcome = enum { Succeed, Fail, BuildFail, }; const Code = struct { id: Id, name: []const u8, source_token: Token, is_inline: bool, mode: builtin.Mode, link_objects: []const []const u8, target_str: ?[]const u8, link_libc: bool, disable_cache: bool, const Id = union(enum) { Test, TestError: []const u8, TestSafety: []const u8, Exe: ExpectedOutcome, Obj: ?[]const u8, Lib, }; }; const Link = struct { url: []const u8, name: []const u8, token: Token, }; const Node = union(enum) { Content: []const u8, Nav, Builtin: Token, HeaderOpen: HeaderOpen, SeeAlso: []const SeeAlsoItem, Code: Code, Link: Link, Syntax: Token, }; const Toc = struct { nodes: []Node, toc: []u8, urls: std.StringHashMap(Token), }; const Action = enum { Open, Close, }; fn urlize(allocator: mem.Allocator, input: []const u8) ![]u8 { var buf = std.ArrayList(u8).init(allocator); defer buf.deinit(); const out = buf.outStream(); for (input) |c| { switch (c) { 'a'...'z', 'A'...'Z', '_', '-', '0'...'9' => { try out.writeByte(c); }, ' ' => { try out.writeByte('-'); }, else => {}, } } return buf.toOwnedSlice(); } fn escapeHtml(allocator: mem.Allocator, input: []const u8) ![]u8 { var buf = std.ArrayList(u8).init(allocator); defer buf.deinit(); const out = buf.outStream(); try writeEscaped(out, input); return buf.toOwnedSlice(); } fn writeEscaped(out: anytype, input: []const u8) !void { for (input) |c| { try switch (c) { '&' => out.writeAll("&amp;"), '<' => out.writeAll("&lt;"), '>' => out.writeAll("&gt;"), '"' => out.writeAll("&quot;"), else => out.writeByte(c), }; } } //#define VT_RED "\x1b[31;1m" //#define VT_GREEN "\x1b[32;1m" //#define VT_CYAN "\x1b[36;1m" //#define VT_WHITE "\x1b[37;1m" //#define VT_BOLD "\x1b[0;1m" //#define VT_RESET "\x1b[0m" const TermState = enum { Start, Escape, LBracket, Number, AfterNumber, Arg, ArgNumber, ExpectEnd, }; test "term color" { const input_bytes = "A\x1b[32;1mgreen\x1b[0mB"; const result = try termColor(std.testing.allocator, input_bytes); defer std.testing.allocator.free(result); testing.expectEqualSlices(u8, "A<span class=\"t32\">green</span>B", result); } fn termColor(allocator: mem.Allocator, input: []const u8) ![]u8 { var buf = std.ArrayList(u8).init(allocator); defer buf.deinit(); var out = buf.outStream(); var number_start_index: usize = undefined; var first_number: usize = undefined; var second_number: usize = undefined; var i: usize = 0; var state = TermState.Start; var open_span_count: usize = 0; while (i < input.len) : (i += 1) { const c = input[i]; switch (state) { TermState.Start => switch (c) { '\x1b' => state = TermState.Escape, else => try out.writeByte(c), }, TermState.Escape => switch (c) { '[' => state = TermState.LBracket, else => return error.UnsupportedEscape, }, TermState.LBracket => switch (c) { '0'...'9' => { number_start_index = i; state = TermState.Number; }, else => return error.UnsupportedEscape, }, TermState.Number => switch (c) { '0'...'9' => {}, else => { first_number = std.fmt.parseInt(usize, input[number_start_index..i], 10) catch unreachable; second_number = 0; state = TermState.AfterNumber; i -= 1; }, }, TermState.AfterNumber => switch (c) { ';' => state = TermState.Arg, else => { state = TermState.ExpectEnd; i -= 1; }, }, TermState.Arg => switch (c) { '0'...'9' => { number_start_index = i; state = TermState.ArgNumber; }, else => return error.UnsupportedEscape, }, TermState.ArgNumber => switch (c) { '0'...'9' => {}, else => { second_number = std.fmt.parseInt(usize, input[number_start_index..i], 10) catch unreachable; state = TermState.ExpectEnd; i -= 1; }, }, TermState.ExpectEnd => switch (c) { 'm' => { state = TermState.Start; while (open_span_count != 0) : (open_span_count -= 1) { try out.writeAll("</span>"); } if (first_number != 0 or second_number != 0) { try out.print("<span class=\"t{}_{}\">", .{ first_number, second_number }); open_span_count += 1; } }, else => return error.UnsupportedEscape, }, } } return buf.toOwnedSlice(); } const builtin_types = [_][]const u8{ "f16", "f32", "f64", "f128", "c_longdouble", "c_short", "c_ushort", "c_int", "c_uint", "c_long", "c_ulong", "c_longlong", "c_ulonglong", "c_char", "c_void", "void", "bool", "isize", "usize", "noreturn", "type", "anyerror", "comptime_int", "comptime_float", }; fn isType(name: []const u8) bool { for (builtin_types) |t| { if (mem.eql(u8, t, name)) return true; } return false; } const Location = struct { line: usize, column: usize, line_start: usize, line_end: usize, }; fn getTokenLocation(src: []const u8, token: std.zig.Token) Location { var loc = Location{ .line = 0, .column = 0, .line_start = 0, .line_end = 0, }; for (src) |c, i| { if (i == token.loc.start) { loc.line_end = i; while (loc.line_end < src.len and src[loc.line_end] != '\n') : (loc.line_end += 1) {} return loc; } if (c == '\n') { loc.line += 1; loc.column = 0; loc.line_start = i + 1; } else { loc.column += 1; } } return loc; } fn genHtml(allocator: mem.Allocator, tokenizer: *Tokenizer, toc: *Toc, out: anytype, zig_exe: []const u8) !void { var code_progress_index: usize = 0; var env_map = try process.getEnvMap(allocator); try env_map.set("ZIG_DEBUG_COLOR", "1"); for (toc.nodes) |node| { switch (node) { .Syntax => |content_tok| { try tokenizeAndPrint(tokenizer, out, content_tok); }, .Code => |code| { code_progress_index += 1; print("docgen example code {}/{}...", .{ code_progress_index, tokenizer.code_node_count }); const raw_source = tokenizer.buffer[code.source_token.start..code.source_token.end]; const trimmed_raw_source = mem.trim(u8, raw_source, " \n"); if (!code.is_inline) { try out.print("<p class=\"file\">{}.zig</p>", .{code.name}); } try out.writeAll("<pre>"); try tokenizeAndPrint(tokenizer, out, code.source_token); try out.writeAll("</pre>"); const name_plus_ext = try std.fmt.allocPrint(allocator, "{}.zig", .{code.name}); const tmp_source_file_name = try fs.path.join( allocator, &[_][]const u8{ tmp_dir_name, name_plus_ext }, ); try fs.cwd().writeFile(tmp_source_file_name, trimmed_raw_source); switch (code.id) { Code.Id.Exe => |expected_outcome| code_block: { const name_plus_bin_ext = try std.fmt.allocPrint(allocator, "{}{}", .{ code.name, exe_ext }); var build_args = std.ArrayList([]const u8).init(allocator); defer build_args.deinit(); try build_args.appendSlice(&[_][]const u8{ zig_exe, "build-exe", "--name", code.name, "--color", "on", "--enable-cache", tmp_source_file_name, }); try out.print("<pre><code class=\"shell\">$ zig build-exe {}.zig", .{code.name}); switch (code.mode) { .Debug => {}, else => { try build_args.appendSlice(&[_][]const u8{ "-O", @tagName(code.mode) }); try out.print(" -O {s}", .{@tagName(code.mode)}); }, } for (code.link_objects) |link_object| { const name_with_ext = try std.fmt.allocPrint(allocator, "{}{}", .{ link_object, obj_ext }); const full_path_object = try fs.path.join( allocator, &[_][]const u8{ tmp_dir_name, name_with_ext }, ); try build_args.append(full_path_object); try out.print(" {s}", .{name_with_ext}); } if (code.link_libc) { try build_args.append("-lc"); try out.print(" -lc", .{}); } const target = try std.zig.CrossTarget.parse(.{ .arch_os_abi = code.target_str orelse "native", }); if (code.target_str) |triple| { try build_args.appendSlice(&[_][]const u8{ "-target", triple }); if (!code.is_inline) { try out.print(" -target {}", .{triple}); } } if (expected_outcome == .BuildFail) { const result = try ChildProcess.exec(.{ .allocator = allocator, .argv = build_args.items, .env_map = &env_map, .max_output_bytes = max_doc_file_size, }); switch (result.term) { .Exited => |exit_code| { if (exit_code == 0) { print("{}\nThe following command incorrectly succeeded:\n", .{result.stderr}); dumpArgs(build_args.items); return parseError(tokenizer, code.source_token, "example incorrectly compiled", .{}); } }, else => { print("{}\nThe following command crashed:\n", .{result.stderr}); dumpArgs(build_args.items); return parseError(tokenizer, code.source_token, "example compile crashed", .{}); }, } const escaped_stderr = try escapeHtml(allocator, result.stderr); const colored_stderr = try termColor(allocator, escaped_stderr); try out.print("\n{}</code></pre>\n", .{colored_stderr}); break :code_block; } const exec_result = exec(allocator, &env_map, build_args.items) catch return parseError(tokenizer, code.source_token, "example failed to compile", .{}); if (code.target_str) |triple| { if (mem.startsWith(u8, triple, "wasm32") or mem.startsWith(u8, triple, "riscv64-linux") or (mem.startsWith(u8, triple, "x86_64-linux") and std.Target.current.os.tag != .linux or std.Target.current.cpu.arch != .x86_64)) { // skip execution try out.print("</code></pre>\n", .{}); break :code_block; } } const path_to_exe_dir = mem.trim(u8, exec_result.stdout, " \r\n"); const path_to_exe_basename = try std.fmt.allocPrint(allocator, "{}{}", .{ code.name, target.exeFileExt(), }); const path_to_exe = try fs.path.join(allocator, &[_][]const u8{ path_to_exe_dir, path_to_exe_basename, }); const run_ags = &[_][]const u8{path_to_exe}; var exited_with_signal = false; const result = if (expected_outcome == ExpectedOutcome.Fail) blk: { const result = try ChildProcess.exec(.{ .allocator = allocator, .argv = run_args, .env_map = &env_map, .max_output_bytes = max_doc_file_size, }); switch (result.term) { .Exited => |exit_code| { if (exit_code == 0) { print("{}\nThe following command incorrectly succeeded:\n", .{result.stderr}); dumpArgs(run_args); return parseError(tokenizer, code.source_token, "example incorrectly compiled", .{}); } }, .Signal => exited_with_signal = true, else => {}, } break :blk result; } else blk: { break :blk exec(allocator, &env_map, run_args) catch return parseError(tokenizer, code.source_token, "example crashed", .{}); }; const escaped_stderr = try escapeHtml(allocator, result.stderr); const escaped_stdout = try escapeHtml(allocator, result.stdout); const colored_stderr = try termColor(allocator, escaped_stderr); const colored_stdout = try termColor(allocator, escaped_stdout); try out.print("\n$ ./{}\n{}{}", .{ code.name, colored_stdout, colored_stderr }); if (exited_with_signal) { try out.print("(process terminated by signal)", .{}); } try out.print("</code></pre>\n", .{}); }, Code.Id.Test => { var test_args = std.ArrayList([]const u8).init(allocator); defer test_args.deinit(); try test_args.appendSlice(&[_][]const u8{ zig_exe, "test", tmp_source_file_name }); try out.print("<pre><code class=\"shell\">$ zig test {}.zig", .{code.name}); switch (code.mode) { .Debug => {}, else => { try test_args.appendSlice(&[_][]const u8{ "-O", @tagName(code.mode) }); try out.print(" -O {s}", .{@tagName(code.mode)}); }, } if (code.link_libc) { try test_args.append("-lc"); try out.print(" -lc", .{}); } if (code.target_str) |triple| { try test_args.appendSlice(&[_][]const u8{ "-target", triple }); try out.print(" -target {}", .{triple}); } const result = exec(allocator, &env_map, test_args.items) catch return parseError(tokenizer, code.source_token, "test failed", .{}); const escaped_stderr = try escapeHtml(allocator, result.stderr); const escaped_stdout = try escapeHtml(allocator, result.stdout); try out.print("\n{}{}</code></pre>\n", .{ escaped_stderr, escaped_stdout }); }, Code.Id.TestError => |error_match| { var test_args = std.ArrayList([]const u8).init(allocator); defer test_args.deinit(); try test_args.appendSlice(&[_][]const u8{ zig_exe, "test", "--color", "on", tmp_source_file_name, }); try out.print("<pre><code class=\"shell\">$ zig test {}.zig", .{code.name}); switch (code.mode) { .Debug => {}, else => { try test_args.appendSlice(&[_][]const u8{ "-O", @tagName(code.mode) }); try out.print(" -O {s}", .{@tagName(code.mode)}); }, } const result = try ChildProcess.exec(.{ .allocator = allocator, .argv = test_args.items, .env_map = &env_map, .max_output_bytes = max_doc_file_size, }); switch (result.term) { .Exited => |exit_code| { if (exit_code == 0) { print("{}\nThe following command incorrectly succeeded:\n", .{result.stderr}); dumpArgs(test_args.items); return parseError(tokenizer, code.source_token, "example incorrectly compiled", .{}); } }, else => { print("{}\nThe following command crashed:\n", .{result.stderr}); dumpArgs(test_args.items); return parseError(tokenizer, code.source_token, "example compile crashed", .{}); }, } if (mem.indexOf(u8, result.stderr, error_match) == null) { print("{}\nExpected to find '{}' in stderr\n", .{ result.stderr, error_match }); return parseError(tokenizer, code.source_token, "example did not have expected compile error", .{}); } const escaped_stderr = try escapeHtml(allocator, result.stderr); const colored_stderr = try termColor(allocator, escaped_stderr); try out.print("\n{}</code></pre>\n", .{colored_stderr}); }, Code.Id.TestSafety => |error_match| { var test_args = std.ArrayList([]const u8).init(allocator); defer test_args.deinit(); try test_args.appendSlice(&[_][]const u8{ zig_exe, "test", tmp_source_file_name, }); var mode_arg: []const u8 = ""; switch (code.mode) { .Debug => {}, .ReleaseSafe => { try test_args.append("-OReleaseSafe"); mode_arg = "-OReleaseSafe"; }, .ReleaseFast => { try test_args.append("-OReleaseFast"); mode_arg = "-OReleaseFast"; }, .ReleaseSmall => { try test_args.append("-OReleaseSmall"); mode_arg = "-OReleaseSmall"; }, } const result = try ChildProcess.exec(.{ .allocator = allocator, .argv = test_args.items, .env_map = &env_map, .max_output_bytes = max_doc_file_size, }); switch (result.term) { .Exited => |exit_code| { if (exit_code == 0) { print("{}\nThe following command incorrectly succeeded:\n", .{result.stderr}); dumpArgs(test_args.items); return parseError(tokenizer, code.source_token, "example test incorrectly succeeded", .{}); } }, else => { print("{}\nThe following command crashed:\n", .{result.stderr}); dumpArgs(test_args.items); return parseError(tokenizer, code.source_token, "example compile crashed", .{}); }, } if (mem.indexOf(u8, result.stderr, error_match) == null) { print("{}\nExpected to find '{}' in stderr\n", .{ result.stderr, error_match }); return parseError(tokenizer, code.source_token, "example did not have expected runtime safety error message", .{}); } const escaped_stderr = try escapeHtml(allocator, result.stderr); const colored_stderr = try termColor(allocator, escaped_stderr); try out.print("<pre><code class=\"shell\">$ zig test {}.zig{}\n{}</code></pre>\n", .{ code.name, mode_arg, colored_stderr, }); }, Code.Id.Obj => |maybe_error_match| { const name_plus_obj_ext = try std.fmt.allocPrint(allocator, "{}{}", .{ code.name, obj_ext }); const tmp_obj_file_name = try fs.path.join( allocator, &[_][]const u8{ tmp_dir_name, name_plus_obj_ext }, ); var build_args = std.ArrayList([]const u8).init(allocator); defer build_args.deinit(); const x = try std.fmt.allocPrint(allocator, "{}.h", .{code.name}); const output_h_file_name = try fs.path.join( allocator, &[_][]const u8{ tmp_dir_name, name_plus_h_ext }, ); try build_args.appendSlice(&[_][]const u8{ zig_exe, "build-obj", tmp_source_file_name, "--color", "on", "--name", code.name, try std.fmt.allocPrint(allocator, "-femit-bin={s}{c}{s}", .{ tmp_dir_name, fs.path.sep, name_plus_obj_ext, }), }); if (!code.is_inline) { try out.print("<pre><code class=\"shell\">$ zig build-obj {}.zig", .{code.name}); } switch (code.mode) { .Debug => {}, else => { try build_args.appendSlice(&[_][]const u8{ "-O", @tagName(code.mode) }); if (!code.is_inline) { try out.print(" -O {s}", .{@tagName(code.mode)}); } }, } if (code.target_str) |triple| { try build_args.appendSlice(&[_][]const u8{ "-target", triple }); try out.print(" -target {}", .{triple}); } if (maybe_error_match) |error_match| { const result = try ChildProcess.exec(.{ .allocator = allocator, .argv = build_args.items, .env_map = &env_map, .max_output_bytes = max_doc_file_size, }); switch (result.term) { .Exited => |exit_code| { if (exit_code == 0) { print("{}\nThe following command incorrectly succeeded:\n", .{result.stderr}); dumpArgs(build_args.items); return parseError(tokenizer, code.source_token, "example build incorrectly succeeded", .{}); } }, else => { print("{}\nThe following command crashed:\n", .{result.stderr}); dumpArgs(build_args.items); return parseError(tokenizer, code.source_token, "example compile crashed", .{}); }, } if (mem.indexOf(u8, result.stderr, error_match) == null) { print("{}\nExpected to find '{}' in stderr\n", .{ result.stderr, error_match }); return parseError(tokenizer, code.source_token, "example did not have expected compile error message", .{}); } const escaped_stderr = try escapeHtml(allocator, result.stderr); const colored_stderr = try termColor(allocator, escaped_stderr); try out.print("\n{}", .{colored_stderr}); } else { _ = exec(allocator, &env_map, build_args.items) catch return parseError(tokenizer, code.source_token, "example failed to compile", .{}); } if (!code.is_inline) { try out.print("</code></pre>\n", .{}); } }, Code.Id.Lib => { const bin_basename = try std.zig.binNameAlloc(allocator, .{ .root_name = code.name, .target = std.Target.current, .output_mode = .Lib, }); var test_args = std.ArrayList([]const u8).init(allocator); defer test_args.deinit(); try test_args.appendSlice(&[_][]const u8{ zig_exe, "build-lib", tmp_source_file_name, try std.fmt.allocPrint(allocator, "-femit-bin={s}{s}{s}", .{ tmp_dir_name, fs.path.sep_str, bin_basename, }), }); try out.print("<pre><code class=\"shell\">$ zig build-lib {}.zig", .{code.name}); switch (code.mode) { .Debug => {}, else => { try test_args.appendSlice(&[_][]const u8{ "-O", @tagName(code.mode) }); try out.print(" -O {s}", .{@tagName(code.mode)}); }, } if (code.target_str) |triple| { try test_args.appendSlice(&[_][]const u8{ "-target", triple }); try out.print(" -target {}", .{triple}); } const result = exec(allocator, &env_map, test_args.items) catch return parseError(tokenizer, code.source_token, "test failed", .{}); const escaped_stderr = try escapeHtml(allocator, result.stderr); const escaped_stdout = try escapeHtml(allocator, result.stdout); try out.print("\n{}{}</code></pre>\n", .{ escaped_stderr, escaped_stdout }); }, } print("OK\n", .{}); }, } } } fn exec(allocator: mem.Allocator, env_map: *std.BufMap, args: []const []const u8) !ChildProcess.ExecResult { const result = try ChildProcess.exec(.{ .allocator = allocator, .argv = args, .env_map = env_map, .max_output_bytes = max_doc_file_size, }); switch (result.term) { .Exited => |exit_code| { if (exit_code != 0) { print("{}\nThe following command exited with code {}:\n", .{ result.stderr, exit_code }); dumpArgs(args); return error.ChildExitError; } }, else => { print("{}\nThe following command crashed:\n", .{result.stderr}); dumpArgs(args); return error.ChildCrashed; }, } return result; } fn getBuiltinCode(allocator: mem.Allocator, env_map: *std.BufMap, zig_exe: []const u8) ![]const u8 { const result = try exec(allocator, env_map, &[_][]const u8{ zig_exe, "build-obj", "--show-builtin" }); return result.stdout; } fn dumpArgs(args: []const []const u8) void { for (args) |arg| print("{} ", .{arg}) else print("\n", .{}); }
src/docgen_old.zig
//-------------------------------------------------------------------------------- // Section: Types (11) //-------------------------------------------------------------------------------- pub const DEVPROP_OPERATOR = enum(u32) { MODIFIER_NOT = 65536, MODIFIER_IGNORE_CASE = 131072, NONE = 0, EXISTS = 1, NOT_EXISTS = 65537, EQUALS = 2, NOT_EQUALS = 65538, GREATER_THAN = 3, LESS_THAN = 4, GREATER_THAN_EQUALS = 5, LESS_THAN_EQUALS = 6, EQUALS_IGNORE_CASE = 131074, NOT_EQUALS_IGNORE_CASE = 196610, BITWISE_AND = 7, BITWISE_OR = 8, BEGINS_WITH = 9, ENDS_WITH = 10, CONTAINS = 11, BEGINS_WITH_IGNORE_CASE = 131081, ENDS_WITH_IGNORE_CASE = 131082, CONTAINS_IGNORE_CASE = 131083, LIST_CONTAINS = 4096, LIST_ELEMENT_BEGINS_WITH = 8192, LIST_ELEMENT_ENDS_WITH = 12288, LIST_ELEMENT_CONTAINS = 16384, LIST_CONTAINS_IGNORE_CASE = 135168, LIST_ELEMENT_BEGINS_WITH_IGNORE_CASE = 139264, LIST_ELEMENT_ENDS_WITH_IGNORE_CASE = 143360, LIST_ELEMENT_CONTAINS_IGNORE_CASE = 147456, AND_OPEN = 1048576, AND_CLOSE = 2097152, OR_OPEN = 3145728, OR_CLOSE = 4194304, NOT_OPEN = 5242880, NOT_CLOSE = 6291456, ARRAY_CONTAINS = 268435456, MASK_EVAL = 4095, MASK_LIST = 61440, MASK_MODIFIER = 983040, MASK_NOT_LOGICAL = 4027580415, MASK_LOGICAL = 267386880, MASK_ARRAY = 4026531840, _, pub fn initFlags(o: struct { MODIFIER_NOT: u1 = 0, MODIFIER_IGNORE_CASE: u1 = 0, NONE: u1 = 0, EXISTS: u1 = 0, NOT_EXISTS: u1 = 0, EQUALS: u1 = 0, NOT_EQUALS: u1 = 0, GREATER_THAN: u1 = 0, LESS_THAN: u1 = 0, GREATER_THAN_EQUALS: u1 = 0, LESS_THAN_EQUALS: u1 = 0, EQUALS_IGNORE_CASE: u1 = 0, NOT_EQUALS_IGNORE_CASE: u1 = 0, BITWISE_AND: u1 = 0, BITWISE_OR: u1 = 0, BEGINS_WITH: u1 = 0, ENDS_WITH: u1 = 0, CONTAINS: u1 = 0, BEGINS_WITH_IGNORE_CASE: u1 = 0, ENDS_WITH_IGNORE_CASE: u1 = 0, CONTAINS_IGNORE_CASE: u1 = 0, LIST_CONTAINS: u1 = 0, LIST_ELEMENT_BEGINS_WITH: u1 = 0, LIST_ELEMENT_ENDS_WITH: u1 = 0, LIST_ELEMENT_CONTAINS: u1 = 0, LIST_CONTAINS_IGNORE_CASE: u1 = 0, LIST_ELEMENT_BEGINS_WITH_IGNORE_CASE: u1 = 0, LIST_ELEMENT_ENDS_WITH_IGNORE_CASE: u1 = 0, LIST_ELEMENT_CONTAINS_IGNORE_CASE: u1 = 0, AND_OPEN: u1 = 0, AND_CLOSE: u1 = 0, OR_OPEN: u1 = 0, OR_CLOSE: u1 = 0, NOT_OPEN: u1 = 0, NOT_CLOSE: u1 = 0, ARRAY_CONTAINS: u1 = 0, MASK_EVAL: u1 = 0, MASK_LIST: u1 = 0, MASK_MODIFIER: u1 = 0, MASK_NOT_LOGICAL: u1 = 0, MASK_LOGICAL: u1 = 0, MASK_ARRAY: u1 = 0, }) DEVPROP_OPERATOR { return @intToEnum(DEVPROP_OPERATOR, (if (o.MODIFIER_NOT == 1) @enumToInt(DEVPROP_OPERATOR.MODIFIER_NOT) else 0) | (if (o.MODIFIER_IGNORE_CASE == 1) @enumToInt(DEVPROP_OPERATOR.MODIFIER_IGNORE_CASE) else 0) | (if (o.NONE == 1) @enumToInt(DEVPROP_OPERATOR.NONE) else 0) | (if (o.EXISTS == 1) @enumToInt(DEVPROP_OPERATOR.EXISTS) else 0) | (if (o.NOT_EXISTS == 1) @enumToInt(DEVPROP_OPERATOR.NOT_EXISTS) else 0) | (if (o.EQUALS == 1) @enumToInt(DEVPROP_OPERATOR.EQUALS) else 0) | (if (o.NOT_EQUALS == 1) @enumToInt(DEVPROP_OPERATOR.NOT_EQUALS) else 0) | (if (o.GREATER_THAN == 1) @enumToInt(DEVPROP_OPERATOR.GREATER_THAN) else 0) | (if (o.LESS_THAN == 1) @enumToInt(DEVPROP_OPERATOR.LESS_THAN) else 0) | (if (o.GREATER_THAN_EQUALS == 1) @enumToInt(DEVPROP_OPERATOR.GREATER_THAN_EQUALS) else 0) | (if (o.LESS_THAN_EQUALS == 1) @enumToInt(DEVPROP_OPERATOR.LESS_THAN_EQUALS) else 0) | (if (o.EQUALS_IGNORE_CASE == 1) @enumToInt(DEVPROP_OPERATOR.EQUALS_IGNORE_CASE) else 0) | (if (o.NOT_EQUALS_IGNORE_CASE == 1) @enumToInt(DEVPROP_OPERATOR.NOT_EQUALS_IGNORE_CASE) else 0) | (if (o.BITWISE_AND == 1) @enumToInt(DEVPROP_OPERATOR.BITWISE_AND) else 0) | (if (o.BITWISE_OR == 1) @enumToInt(DEVPROP_OPERATOR.BITWISE_OR) else 0) | (if (o.BEGINS_WITH == 1) @enumToInt(DEVPROP_OPERATOR.BEGINS_WITH) else 0) | (if (o.ENDS_WITH == 1) @enumToInt(DEVPROP_OPERATOR.ENDS_WITH) else 0) | (if (o.CONTAINS == 1) @enumToInt(DEVPROP_OPERATOR.CONTAINS) else 0) | (if (o.BEGINS_WITH_IGNORE_CASE == 1) @enumToInt(DEVPROP_OPERATOR.BEGINS_WITH_IGNORE_CASE) else 0) | (if (o.ENDS_WITH_IGNORE_CASE == 1) @enumToInt(DEVPROP_OPERATOR.ENDS_WITH_IGNORE_CASE) else 0) | (if (o.CONTAINS_IGNORE_CASE == 1) @enumToInt(DEVPROP_OPERATOR.CONTAINS_IGNORE_CASE) else 0) | (if (o.LIST_CONTAINS == 1) @enumToInt(DEVPROP_OPERATOR.LIST_CONTAINS) else 0) | (if (o.LIST_ELEMENT_BEGINS_WITH == 1) @enumToInt(DEVPROP_OPERATOR.LIST_ELEMENT_BEGINS_WITH) else 0) | (if (o.LIST_ELEMENT_ENDS_WITH == 1) @enumToInt(DEVPROP_OPERATOR.LIST_ELEMENT_ENDS_WITH) else 0) | (if (o.LIST_ELEMENT_CONTAINS == 1) @enumToInt(DEVPROP_OPERATOR.LIST_ELEMENT_CONTAINS) else 0) | (if (o.LIST_CONTAINS_IGNORE_CASE == 1) @enumToInt(DEVPROP_OPERATOR.LIST_CONTAINS_IGNORE_CASE) else 0) | (if (o.LIST_ELEMENT_BEGINS_WITH_IGNORE_CASE == 1) @enumToInt(DEVPROP_OPERATOR.LIST_ELEMENT_BEGINS_WITH_IGNORE_CASE) else 0) | (if (o.LIST_ELEMENT_ENDS_WITH_IGNORE_CASE == 1) @enumToInt(DEVPROP_OPERATOR.LIST_ELEMENT_ENDS_WITH_IGNORE_CASE) else 0) | (if (o.LIST_ELEMENT_CONTAINS_IGNORE_CASE == 1) @enumToInt(DEVPROP_OPERATOR.LIST_ELEMENT_CONTAINS_IGNORE_CASE) else 0) | (if (o.AND_OPEN == 1) @enumToInt(DEVPROP_OPERATOR.AND_OPEN) else 0) | (if (o.AND_CLOSE == 1) @enumToInt(DEVPROP_OPERATOR.AND_CLOSE) else 0) | (if (o.OR_OPEN == 1) @enumToInt(DEVPROP_OPERATOR.OR_OPEN) else 0) | (if (o.OR_CLOSE == 1) @enumToInt(DEVPROP_OPERATOR.OR_CLOSE) else 0) | (if (o.NOT_OPEN == 1) @enumToInt(DEVPROP_OPERATOR.NOT_OPEN) else 0) | (if (o.NOT_CLOSE == 1) @enumToInt(DEVPROP_OPERATOR.NOT_CLOSE) else 0) | (if (o.ARRAY_CONTAINS == 1) @enumToInt(DEVPROP_OPERATOR.ARRAY_CONTAINS) else 0) | (if (o.MASK_EVAL == 1) @enumToInt(DEVPROP_OPERATOR.MASK_EVAL) else 0) | (if (o.MASK_LIST == 1) @enumToInt(DEVPROP_OPERATOR.MASK_LIST) else 0) | (if (o.MASK_MODIFIER == 1) @enumToInt(DEVPROP_OPERATOR.MASK_MODIFIER) else 0) | (if (o.MASK_NOT_LOGICAL == 1) @enumToInt(DEVPROP_OPERATOR.MASK_NOT_LOGICAL) else 0) | (if (o.MASK_LOGICAL == 1) @enumToInt(DEVPROP_OPERATOR.MASK_LOGICAL) else 0) | (if (o.MASK_ARRAY == 1) @enumToInt(DEVPROP_OPERATOR.MASK_ARRAY) else 0) ); } }; pub const DEVPROP_OPERATOR_MODIFIER_NOT = DEVPROP_OPERATOR.MODIFIER_NOT; pub const DEVPROP_OPERATOR_MODIFIER_IGNORE_CASE = DEVPROP_OPERATOR.MODIFIER_IGNORE_CASE; pub const DEVPROP_OPERATOR_NONE = DEVPROP_OPERATOR.NONE; pub const DEVPROP_OPERATOR_EXISTS = DEVPROP_OPERATOR.EXISTS; pub const DEVPROP_OPERATOR_NOT_EXISTS = DEVPROP_OPERATOR.NOT_EXISTS; pub const DEVPROP_OPERATOR_EQUALS = DEVPROP_OPERATOR.EQUALS; pub const DEVPROP_OPERATOR_NOT_EQUALS = DEVPROP_OPERATOR.NOT_EQUALS; pub const DEVPROP_OPERATOR_GREATER_THAN = DEVPROP_OPERATOR.GREATER_THAN; pub const DEVPROP_OPERATOR_LESS_THAN = DEVPROP_OPERATOR.LESS_THAN; pub const DEVPROP_OPERATOR_GREATER_THAN_EQUALS = DEVPROP_OPERATOR.GREATER_THAN_EQUALS; pub const DEVPROP_OPERATOR_LESS_THAN_EQUALS = DEVPROP_OPERATOR.LESS_THAN_EQUALS; pub const DEVPROP_OPERATOR_EQUALS_IGNORE_CASE = DEVPROP_OPERATOR.EQUALS_IGNORE_CASE; pub const DEVPROP_OPERATOR_NOT_EQUALS_IGNORE_CASE = DEVPROP_OPERATOR.NOT_EQUALS_IGNORE_CASE; pub const DEVPROP_OPERATOR_BITWISE_AND = DEVPROP_OPERATOR.BITWISE_AND; pub const DEVPROP_OPERATOR_BITWISE_OR = DEVPROP_OPERATOR.BITWISE_OR; pub const DEVPROP_OPERATOR_BEGINS_WITH = DEVPROP_OPERATOR.BEGINS_WITH; pub const DEVPROP_OPERATOR_ENDS_WITH = DEVPROP_OPERATOR.ENDS_WITH; pub const DEVPROP_OPERATOR_CONTAINS = DEVPROP_OPERATOR.CONTAINS; pub const DEVPROP_OPERATOR_BEGINS_WITH_IGNORE_CASE = DEVPROP_OPERATOR.BEGINS_WITH_IGNORE_CASE; pub const DEVPROP_OPERATOR_ENDS_WITH_IGNORE_CASE = DEVPROP_OPERATOR.ENDS_WITH_IGNORE_CASE; pub const DEVPROP_OPERATOR_CONTAINS_IGNORE_CASE = DEVPROP_OPERATOR.CONTAINS_IGNORE_CASE; pub const DEVPROP_OPERATOR_LIST_CONTAINS = DEVPROP_OPERATOR.LIST_CONTAINS; pub const DEVPROP_OPERATOR_LIST_ELEMENT_BEGINS_WITH = DEVPROP_OPERATOR.LIST_ELEMENT_BEGINS_WITH; pub const DEVPROP_OPERATOR_LIST_ELEMENT_ENDS_WITH = DEVPROP_OPERATOR.LIST_ELEMENT_ENDS_WITH; pub const DEVPROP_OPERATOR_LIST_ELEMENT_CONTAINS = DEVPROP_OPERATOR.LIST_ELEMENT_CONTAINS; pub const DEVPROP_OPERATOR_LIST_CONTAINS_IGNORE_CASE = DEVPROP_OPERATOR.LIST_CONTAINS_IGNORE_CASE; pub const DEVPROP_OPERATOR_LIST_ELEMENT_BEGINS_WITH_IGNORE_CASE = DEVPROP_OPERATOR.LIST_ELEMENT_BEGINS_WITH_IGNORE_CASE; pub const DEVPROP_OPERATOR_LIST_ELEMENT_ENDS_WITH_IGNORE_CASE = DEVPROP_OPERATOR.LIST_ELEMENT_ENDS_WITH_IGNORE_CASE; pub const DEVPROP_OPERATOR_LIST_ELEMENT_CONTAINS_IGNORE_CASE = DEVPROP_OPERATOR.LIST_ELEMENT_CONTAINS_IGNORE_CASE; pub const DEVPROP_OPERATOR_AND_OPEN = DEVPROP_OPERATOR.AND_OPEN; pub const DEVPROP_OPERATOR_AND_CLOSE = DEVPROP_OPERATOR.AND_CLOSE; pub const DEVPROP_OPERATOR_OR_OPEN = DEVPROP_OPERATOR.OR_OPEN; pub const DEVPROP_OPERATOR_OR_CLOSE = DEVPROP_OPERATOR.OR_CLOSE; pub const DEVPROP_OPERATOR_NOT_OPEN = DEVPROP_OPERATOR.NOT_OPEN; pub const DEVPROP_OPERATOR_NOT_CLOSE = DEVPROP_OPERATOR.NOT_CLOSE; pub const DEVPROP_OPERATOR_ARRAY_CONTAINS = DEVPROP_OPERATOR.ARRAY_CONTAINS; pub const DEVPROP_OPERATOR_MASK_EVAL = DEVPROP_OPERATOR.MASK_EVAL; pub const DEVPROP_OPERATOR_MASK_LIST = DEVPROP_OPERATOR.MASK_LIST; pub const DEVPROP_OPERATOR_MASK_MODIFIER = DEVPROP_OPERATOR.MASK_MODIFIER; pub const DEVPROP_OPERATOR_MASK_NOT_LOGICAL = DEVPROP_OPERATOR.MASK_NOT_LOGICAL; pub const DEVPROP_OPERATOR_MASK_LOGICAL = DEVPROP_OPERATOR.MASK_LOGICAL; pub const DEVPROP_OPERATOR_MASK_ARRAY = DEVPROP_OPERATOR.MASK_ARRAY; pub const DEVPROP_FILTER_EXPRESSION = extern struct { Operator: DEVPROP_OPERATOR, Property: DEVPROPERTY, }; pub const DEV_OBJECT_TYPE = enum(i32) { Unknown = 0, DeviceInterface = 1, DeviceContainer = 2, Device = 3, DeviceInterfaceClass = 4, AEP = 5, AEPContainer = 6, DeviceInstallerClass = 7, DeviceInterfaceDisplay = 8, DeviceContainerDisplay = 9, AEPService = 10, DevicePanel = 11, }; pub const DevObjectTypeUnknown = DEV_OBJECT_TYPE.Unknown; pub const DevObjectTypeDeviceInterface = DEV_OBJECT_TYPE.DeviceInterface; pub const DevObjectTypeDeviceContainer = DEV_OBJECT_TYPE.DeviceContainer; pub const DevObjectTypeDevice = DEV_OBJECT_TYPE.Device; pub const DevObjectTypeDeviceInterfaceClass = DEV_OBJECT_TYPE.DeviceInterfaceClass; pub const DevObjectTypeAEP = DEV_OBJECT_TYPE.AEP; pub const DevObjectTypeAEPContainer = DEV_OBJECT_TYPE.AEPContainer; pub const DevObjectTypeDeviceInstallerClass = DEV_OBJECT_TYPE.DeviceInstallerClass; pub const DevObjectTypeDeviceInterfaceDisplay = DEV_OBJECT_TYPE.DeviceInterfaceDisplay; pub const DevObjectTypeDeviceContainerDisplay = DEV_OBJECT_TYPE.DeviceContainerDisplay; pub const DevObjectTypeAEPService = DEV_OBJECT_TYPE.AEPService; pub const DevObjectTypeDevicePanel = DEV_OBJECT_TYPE.DevicePanel; pub const DEV_QUERY_FLAGS = enum(i32) { None = 0, UpdateResults = 1, AllProperties = 2, Localize = 4, AsyncClose = 8, }; pub const DevQueryFlagNone = DEV_QUERY_FLAGS.None; pub const DevQueryFlagUpdateResults = DEV_QUERY_FLAGS.UpdateResults; pub const DevQueryFlagAllProperties = DEV_QUERY_FLAGS.AllProperties; pub const DevQueryFlagLocalize = DEV_QUERY_FLAGS.Localize; pub const DevQueryFlagAsyncClose = DEV_QUERY_FLAGS.AsyncClose; pub const DEV_QUERY_STATE = enum(i32) { Initialized = 0, EnumCompleted = 1, Aborted = 2, Closed = 3, }; pub const DevQueryStateInitialized = DEV_QUERY_STATE.Initialized; pub const DevQueryStateEnumCompleted = DEV_QUERY_STATE.EnumCompleted; pub const DevQueryStateAborted = DEV_QUERY_STATE.Aborted; pub const DevQueryStateClosed = DEV_QUERY_STATE.Closed; pub const DEV_QUERY_RESULT_ACTION = enum(i32) { StateChange = 0, Add = 1, Update = 2, Remove = 3, }; pub const DevQueryResultStateChange = DEV_QUERY_RESULT_ACTION.StateChange; pub const DevQueryResultAdd = DEV_QUERY_RESULT_ACTION.Add; pub const DevQueryResultUpdate = DEV_QUERY_RESULT_ACTION.Update; pub const DevQueryResultRemove = DEV_QUERY_RESULT_ACTION.Remove; pub const DEV_OBJECT = extern struct { ObjectType: DEV_OBJECT_TYPE, pszObjectId: ?[*:0]const u16, cPropertyCount: u32, pProperties: ?*const DEVPROPERTY, }; pub const DEV_QUERY_RESULT_ACTION_DATA = extern struct { pub const _DEV_QUERY_RESULT_UPDATE_PAYLOAD = extern union { State: DEV_QUERY_STATE, DeviceObject: DEV_OBJECT, }; Action: DEV_QUERY_RESULT_ACTION, Data: _DEV_QUERY_RESULT_UPDATE_PAYLOAD, }; pub const DEV_QUERY_PARAMETER = extern struct { Key: DEVPROPKEY, Type: u32, BufferSize: u32, Buffer: ?*c_void, }; pub const HDEVQUERY__ = extern struct { unused: i32, }; pub const PDEV_QUERY_RESULT_CALLBACK = fn( hDevQuery: ?*HDEVQUERY__, pContext: ?*c_void, pActionData: ?*const DEV_QUERY_RESULT_ACTION_DATA, ) callconv(@import("std").os.windows.WINAPI) void; //-------------------------------------------------------------------------------- // Section: Functions (14) //-------------------------------------------------------------------------------- pub extern "api-ms-win-devices-query-l1-1-0" fn DevCreateObjectQuery( ObjectType: DEV_OBJECT_TYPE, QueryFlags: u32, cRequestedProperties: u32, pRequestedProperties: ?[*]const DEVPROPCOMPKEY, cFilterExpressionCount: u32, pFilter: ?[*]const DEVPROP_FILTER_EXPRESSION, pCallback: ?PDEV_QUERY_RESULT_CALLBACK, pContext: ?*c_void, phDevQuery: ?*?*HDEVQUERY__, ) callconv(@import("std").os.windows.WINAPI) HRESULT; pub extern "api-ms-win-devices-query-l1-1-1" fn DevCreateObjectQueryEx( ObjectType: DEV_OBJECT_TYPE, QueryFlags: u32, cRequestedProperties: u32, pRequestedProperties: ?[*]const DEVPROPCOMPKEY, cFilterExpressionCount: u32, pFilter: ?[*]const DEVPROP_FILTER_EXPRESSION, cExtendedParameterCount: u32, pExtendedParameters: ?[*]const DEV_QUERY_PARAMETER, pCallback: ?PDEV_QUERY_RESULT_CALLBACK, pContext: ?*c_void, phDevQuery: ?*?*HDEVQUERY__, ) callconv(@import("std").os.windows.WINAPI) HRESULT; pub extern "api-ms-win-devices-query-l1-1-0" fn DevCreateObjectQueryFromId( ObjectType: DEV_OBJECT_TYPE, pszObjectId: ?[*:0]const u16, QueryFlags: u32, cRequestedProperties: u32, pRequestedProperties: ?[*]const DEVPROPCOMPKEY, cFilterExpressionCount: u32, pFilter: ?[*]const DEVPROP_FILTER_EXPRESSION, pCallback: ?PDEV_QUERY_RESULT_CALLBACK, pContext: ?*c_void, phDevQuery: ?*?*HDEVQUERY__, ) callconv(@import("std").os.windows.WINAPI) HRESULT; pub extern "api-ms-win-devices-query-l1-1-1" fn DevCreateObjectQueryFromIdEx( ObjectType: DEV_OBJECT_TYPE, pszObjectId: ?[*:0]const u16, QueryFlags: u32, cRequestedProperties: u32, pRequestedProperties: ?[*]const DEVPROPCOMPKEY, cFilterExpressionCount: u32, pFilter: ?[*]const DEVPROP_FILTER_EXPRESSION, cExtendedParameterCount: u32, pExtendedParameters: ?[*]const DEV_QUERY_PARAMETER, pCallback: ?PDEV_QUERY_RESULT_CALLBACK, pContext: ?*c_void, phDevQuery: ?*?*HDEVQUERY__, ) callconv(@import("std").os.windows.WINAPI) HRESULT; pub extern "api-ms-win-devices-query-l1-1-0" fn DevCreateObjectQueryFromIds( ObjectType: DEV_OBJECT_TYPE, pszzObjectIds: ?[*]const u16, QueryFlags: u32, cRequestedProperties: u32, pRequestedProperties: ?[*]const DEVPROPCOMPKEY, cFilterExpressionCount: u32, pFilter: ?[*]const DEVPROP_FILTER_EXPRESSION, pCallback: ?PDEV_QUERY_RESULT_CALLBACK, pContext: ?*c_void, phDevQuery: ?*?*HDEVQUERY__, ) callconv(@import("std").os.windows.WINAPI) HRESULT; pub extern "api-ms-win-devices-query-l1-1-1" fn DevCreateObjectQueryFromIdsEx( ObjectType: DEV_OBJECT_TYPE, pszzObjectIds: ?[*]const u16, QueryFlags: u32, cRequestedProperties: u32, pRequestedProperties: ?[*]const DEVPROPCOMPKEY, cFilterExpressionCount: u32, pFilter: ?[*]const DEVPROP_FILTER_EXPRESSION, cExtendedParameterCount: u32, pExtendedParameters: ?[*]const DEV_QUERY_PARAMETER, pCallback: ?PDEV_QUERY_RESULT_CALLBACK, pContext: ?*c_void, phDevQuery: ?*?*HDEVQUERY__, ) callconv(@import("std").os.windows.WINAPI) HRESULT; pub extern "api-ms-win-devices-query-l1-1-0" fn DevCloseObjectQuery( hDevQuery: ?*HDEVQUERY__, ) callconv(@import("std").os.windows.WINAPI) void; pub extern "api-ms-win-devices-query-l1-1-0" fn DevGetObjects( ObjectType: DEV_OBJECT_TYPE, QueryFlags: u32, cRequestedProperties: u32, pRequestedProperties: ?[*]const DEVPROPCOMPKEY, cFilterExpressionCount: u32, pFilter: ?[*]const DEVPROP_FILTER_EXPRESSION, pcObjectCount: ?*u32, ppObjects: ?*const ?*DEV_OBJECT, ) callconv(@import("std").os.windows.WINAPI) HRESULT; pub extern "api-ms-win-devices-query-l1-1-1" fn DevGetObjectsEx( ObjectType: DEV_OBJECT_TYPE, QueryFlags: u32, cRequestedProperties: u32, pRequestedProperties: ?[*]const DEVPROPCOMPKEY, cFilterExpressionCount: u32, pFilter: ?[*]const DEVPROP_FILTER_EXPRESSION, cExtendedParameterCount: u32, pExtendedParameters: ?[*]const DEV_QUERY_PARAMETER, pcObjectCount: ?*u32, ppObjects: ?*const ?*DEV_OBJECT, ) callconv(@import("std").os.windows.WINAPI) HRESULT; pub extern "api-ms-win-devices-query-l1-1-0" fn DevFreeObjects( cObjectCount: u32, pObjects: [*]const DEV_OBJECT, ) callconv(@import("std").os.windows.WINAPI) void; pub extern "api-ms-win-devices-query-l1-1-0" fn DevGetObjectProperties( ObjectType: DEV_OBJECT_TYPE, pszObjectId: ?[*:0]const u16, QueryFlags: u32, cRequestedProperties: u32, pRequestedProperties: [*]const DEVPROPCOMPKEY, pcPropertyCount: ?*u32, ppProperties: ?*const ?*DEVPROPERTY, ) callconv(@import("std").os.windows.WINAPI) HRESULT; pub extern "api-ms-win-devices-query-l1-1-1" fn DevGetObjectPropertiesEx( ObjectType: DEV_OBJECT_TYPE, pszObjectId: ?[*:0]const u16, QueryFlags: u32, cRequestedProperties: u32, pRequestedProperties: [*]const DEVPROPCOMPKEY, cExtendedParameterCount: u32, pExtendedParameters: ?[*]const DEV_QUERY_PARAMETER, pcPropertyCount: ?*u32, ppProperties: ?*const ?*DEVPROPERTY, ) callconv(@import("std").os.windows.WINAPI) HRESULT; pub extern "api-ms-win-devices-query-l1-1-0" fn DevFreeObjectProperties( cPropertyCount: u32, pProperties: [*]const DEVPROPERTY, ) callconv(@import("std").os.windows.WINAPI) void; pub extern "api-ms-win-devices-query-l1-1-0" fn DevFindProperty( pKey: ?*const DEVPROPKEY, Store: DEVPROPSTORE, pszLocaleName: ?[*:0]const u16, cProperties: u32, pProperties: ?[*]const DEVPROPERTY, ) callconv(@import("std").os.windows.WINAPI) ?*DEVPROPERTY; //-------------------------------------------------------------------------------- // 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 (6) //-------------------------------------------------------------------------------- const DEVPROPCOMPKEY = @import("../system/system_services.zig").DEVPROPCOMPKEY; const DEVPROPERTY = @import("../system/system_services.zig").DEVPROPERTY; const DEVPROPKEY = @import("../system/system_services.zig").DEVPROPKEY; const DEVPROPSTORE = @import("../system/system_services.zig").DEVPROPSTORE; const HRESULT = @import("../foundation.zig").HRESULT; const PWSTR = @import("../foundation.zig").PWSTR; test { // The following '_ = <FuncPtrType>' lines are a workaround for https://github.com/ziglang/zig/issues/4476 if (@hasDecl(@This(), "PDEV_QUERY_RESULT_CALLBACK")) { _ = PDEV_QUERY_RESULT_CALLBACK; } @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/devices/device_query.zig
const std = @import("std"); const assert = std.debug.assert; const log = std.log.scoped(.clock); const fmt = std.fmt; const config = @import("../config.zig"); const clock_offset_tolerance_max: u64 = config.clock_offset_tolerance_max_ms * std.time.ns_per_ms; const epoch_max: u64 = config.clock_epoch_max_ms * std.time.ns_per_ms; const window_min: u64 = config.clock_synchronization_window_min_ms * std.time.ns_per_ms; const window_max: u64 = config.clock_synchronization_window_max_ms * std.time.ns_per_ms; const Marzullo = @import("marzullo.zig").Marzullo; pub fn Clock(comptime Time: type) type { return struct { const Self = @This(); const Sample = struct { /// The relative difference between our wall clock reading and that of the remote clock source. clock_offset: i64, one_way_delay: u64, }; const Epoch = struct { /// The best clock offset sample per remote clock source (with minimum one way delay) collected /// over the course of a window period of several seconds. sources: []?Sample, /// The total number of samples learned while synchronizing this epoch. samples: usize, /// The monotonic clock timestamp when this epoch began. We use this to measure elapsed time. monotonic: u64, /// The wall clock timestamp when this epoch began. We add the elapsed monotonic time to this /// plus the synchronized clock offset to arrive at a synchronized realtime timestamp. We /// capture this realtime when starting the epoch, before we take any samples, to guard against /// any jumps in the system's realtime clock from impacting our measurements. realtime: i64, /// Once we have enough source clock offset samples in agreement, the epoch is synchronized. /// We then have lower and upper bounds on the true cluster time, and can install this epoch for /// subsequent clock readings. This epoch is then valid for several seconds, while clock drift /// has not had enough time to accumulate into any significant clock skew, and while we collect /// samples for the next epoch to refresh and replace this one. synchronized: ?Marzullo.Interval, /// A guard to prevent synchronizing too often without having learned any new samples. learned: bool = false, fn elapsed(epoch: *Epoch, clock: *Self) u64 { return clock.monotonic() - epoch.monotonic; } fn reset(epoch: *Epoch, clock: *Self) void { std.mem.set(?Sample, epoch.sources, null); // A replica always has zero clock offset and network delay to its own system time reading: epoch.sources[clock.replica] = Sample{ .clock_offset = 0, .one_way_delay = 0, }; epoch.samples = 1; epoch.monotonic = clock.monotonic(); epoch.realtime = clock.realtime(); epoch.synchronized = null; epoch.learned = false; } fn sources_sampled(epoch: *Epoch) usize { var count: usize = 0; for (epoch.sources) |sampled| { if (sampled != null) count += 1; } return count; } }; /// The index of the replica using this clock to provide synchronized time. replica: u8, /// The underlying time source for this clock (system time or deterministic time). time: *Time, /// An epoch from which the clock can read synchronized clock timestamps within safe bounds. /// At least `config.clock_synchronization_window_min_ms` is needed for this to be ready to use. epoch: Epoch, /// The next epoch (collecting samples and being synchronized) to replace the current epoch. window: Epoch, /// A static allocation to convert window samples into tuple bounds for Marzullo's algorithm. marzullo_tuples: []Marzullo.Tuple, /// A kill switch to revert to unsynchronized realtime. synchronization_disabled: bool, pub fn init( allocator: std.mem.Allocator, /// The size of the cluster, i.e. the number of clock sources (including this replica). replica_count: u8, replica: u8, time: *Time, ) !Self { assert(replica_count > 0); assert(replica < replica_count); var epoch: Epoch = undefined; epoch.sources = try allocator.alloc(?Sample, replica_count); errdefer allocator.free(epoch.sources); var window: Epoch = undefined; window.sources = try allocator.alloc(?Sample, replica_count); errdefer allocator.free(window.sources); // There are two Marzullo tuple bounds (lower and upper) per source clock offset sample: var marzullo_tuples = try allocator.alloc(Marzullo.Tuple, replica_count * 2); errdefer allocator.free(marzullo_tuples); var self = Self{ .replica = replica, .time = time, .epoch = epoch, .window = window, .marzullo_tuples = marzullo_tuples, .synchronization_disabled = replica_count == 1, // A cluster of one cannot synchronize. }; // Reset the current epoch to be unsynchronized, self.epoch.reset(&self); // and open a new epoch window to start collecting samples... self.window.reset(&self); return self; } pub fn deinit(self: *Self, allocator: std.mem.Allocator) void { allocator.free(self.epoch.sources); allocator.free(self.window.sources); allocator.free(self.marzullo_tuples); } /// Called by `Replica.on_pong()` with: /// * the index of the `replica` that has replied to our ping with a pong, /// * our monotonic timestamp `m0` embedded in the ping we sent, carried over into this pong, /// * the remote replica's `realtime()` timestamp `t1`, and /// * our monotonic timestamp `m2` as captured by our `Replica.on_pong()` handler. pub fn learn(self: *Self, replica: u8, m0: u64, t1: i64, m2: u64) void { if (self.synchronization_disabled) return; // A network routing fault must have replayed one of our outbound messages back against us: if (replica == self.replica) { log.warn("{}: learn: replica == self.replica", .{self.replica}); return; } // Our m0 and m2 readings should always be monotonically increasing if not equal. // Crucially, it is possible for a very fast network to have m0 == m2, especially where // `config.tick_ms` is at a more course granularity. We must therefore tolerate RTT=0 or // otherwise we would have a liveness bug simply because we would be throwing away // perfectly good clock samples. // This condition should never be true. Reject this as a bad sample: if (m0 > m2) { log.warn("{}: learn: m0={} > m2={}", .{ self.replica, m0, m2 }); return; } // We may receive delayed packets after a reboot, in which case m0/m2 may be invalid: if (m0 < self.window.monotonic) { log.warn("{}: learn: m0={} < window.monotonic={}", .{ self.replica, m0, self.window.monotonic, }); return; } if (m2 < self.window.monotonic) { log.warn("{}: learn: m2={} < window.monotonic={}", .{ self.replica, m2, self.window.monotonic, }); return; } const elapsed: u64 = m2 - self.window.monotonic; if (elapsed > window_max) { log.warn("{}: learn: elapsed={} > window_max={}", .{ self.replica, elapsed, window_max, }); return; } const round_trip_time: u64 = m2 - m0; const one_way_delay: u64 = round_trip_time / 2; const t2: i64 = self.window.realtime + @intCast(i64, elapsed); const clock_offset: i64 = t1 + @intCast(i64, one_way_delay) - t2; const asymmetric_delay = self.estimate_asymmetric_delay( replica, one_way_delay, clock_offset, ); const clock_offset_corrected = clock_offset + asymmetric_delay; log.debug("{}: learn: replica={} m0={} t1={} m2={} t2={} one_way_delay={} " ++ "asymmetric_delay={} clock_offset={}", .{ self.replica, replica, m0, t1, m2, t2, one_way_delay, asymmetric_delay, clock_offset_corrected, }); // The less network delay, the more likely we have an accurante clock offset measurement: self.window.sources[replica] = minimum_one_way_delay( self.window.sources[replica], Sample{ .clock_offset = clock_offset_corrected, .one_way_delay = one_way_delay, }, ); self.window.samples += 1; // We decouple calls to `synchronize()` so that it's not triggered by these network events. // Otherwise, excessive duplicate network packets would burn the CPU. self.window.learned = true; } /// Called by `Replica.on_ping_timeout()` to provide `m0` when we decide to send a ping. /// Called by `Replica.on_pong()` to provide `m2` when we receive a pong. pub fn monotonic(self: *Self) u64 { return self.time.monotonic(); } /// Called by `Replica.on_ping()` when responding to a ping with a pong. /// This should never be used by the state machine, only for measuring clock offsets. pub fn realtime(self: *Self) i64 { return self.time.realtime(); } /// Called by `StateMachine.prepare_timestamp()` when the leader wants to timestamp a batch. /// If the leader's clock is not synchronized with the cluster, it must wait until it is. /// Returns the system time clamped to be within our synchronized lower and upper bounds. /// This is complementary to NTP and allows clusters with very accurate time to make use of it, /// while providing guard rails for when NTP is partitioned or unable to correct quickly enough. pub fn realtime_synchronized(self: *Self) ?i64 { if (self.synchronization_disabled) { return self.realtime(); } else if (self.epoch.synchronized) |interval| { const elapsed = @intCast(i64, self.epoch.elapsed(self)); return std.math.clamp( self.realtime(), self.epoch.realtime + elapsed + interval.lower_bound, self.epoch.realtime + elapsed + interval.upper_bound, ); } else { return null; } } pub fn tick(self: *Self) void { self.time.tick(); if (self.synchronization_disabled) return; self.synchronize(); // Expire the current epoch if successive windows failed to synchronize: // Gradual clock drift prevents us from using an epoch for more than a few seconds. if (self.epoch.elapsed(self) >= epoch_max) { log.err( "{}: no agreement on cluster time (partitioned or too many clock faults)", .{self.replica}, ); self.epoch.reset(self); } } /// Estimates the asymmetric delay for a sample compared to the previous window, according to /// Algorithm 1 from Section 4.2, "A System for Clock Synchronization in an Internet of Things". fn estimate_asymmetric_delay( self: *Self, replica: u8, one_way_delay: u64, clock_offset: i64, ) i64 { // Note that `one_way_delay` may be 0 for very fast networks. const error_margin = 10 * std.time.ns_per_ms; if (self.epoch.sources[replica]) |epoch| { if (one_way_delay <= epoch.one_way_delay) { return 0; } else if (clock_offset > epoch.clock_offset + error_margin) { // The asymmetric error is on the forward network path. return 0 - @intCast(i64, one_way_delay - epoch.one_way_delay); } else if (clock_offset < epoch.clock_offset - error_margin) { // The asymmetric error is on the reverse network path. return 0 + @intCast(i64, one_way_delay - epoch.one_way_delay); } else { return 0; } } else { return 0; } } fn synchronize(self: *Self) void { assert(self.window.synchronized == null); // Wait until the window has enough accurate samples: const elapsed = self.window.elapsed(self); if (elapsed < window_min) return; if (elapsed >= window_max) { // We took too long to synchronize the window, expire stale samples... const sources_sampled = self.window.sources_sampled(); if (sources_sampled <= @divTrunc(self.window.sources.len, 2)) { log.err("{}: synchronization failed, partitioned (sources={} samples={})", .{ self.replica, sources_sampled, self.window.samples, }); } else { log.err("{}: synchronization failed, no agreement (sources={} samples={})", .{ self.replica, sources_sampled, self.window.samples, }); } self.window.reset(self); return; } if (!self.window.learned) return; // Do not reset `learned` any earlier than this (before we have attempted to synchronize). self.window.learned = false; // Starting with the most clock offset tolerance, while we have a majority, find the best // smallest interval with the least clock offset tolerance, reducing tolerance at each step: var tolerance: u64 = clock_offset_tolerance_max; var terminate = false; var rounds: usize = 0; // Do at least one round if tolerance=0 and cap the number of rounds to avoid runaway loops. while (!terminate and rounds < 64) : (tolerance /= 2) { if (tolerance == 0) terminate = true; rounds += 1; const interval = Marzullo.smallest_interval(self.window_tuples(tolerance)); const majority = interval.sources_true > @divTrunc(self.window.sources.len, 2); if (!majority) break; // The new interval may reduce the number of `sources_true` while also decreasing error. // In other words, provided we maintain a majority, we prefer tighter tolerance bounds. self.window.synchronized = interval; } // Wait for more accurate samples or until we timeout the window for lack of majority: if (self.window.synchronized == null) return; var new_window = self.epoch; new_window.reset(self); self.epoch = self.window; self.window = new_window; self.after_synchronization(); } fn after_synchronization(self: *Self) void { const new_interval = self.epoch.synchronized.?; log.debug("{}: synchronized: truechimers={}/{} clock_offset={}..{} accuracy={}", .{ self.replica, new_interval.sources_true, self.epoch.sources.len, fmt.fmtDurationSigned(new_interval.lower_bound), fmt.fmtDurationSigned(new_interval.upper_bound), fmt.fmtDurationSigned(new_interval.upper_bound - new_interval.lower_bound), }); const elapsed = @intCast(i64, self.epoch.elapsed(self)); const system = self.realtime(); const lower = self.epoch.realtime + elapsed + new_interval.lower_bound; const upper = self.epoch.realtime + elapsed + new_interval.upper_bound; const cluster = std.math.clamp(system, lower, upper); if (system == cluster) {} else if (system < lower) { const delta = lower - system; if (delta < std.time.ns_per_ms) { log.info("{}: system time is {} behind", .{ self.replica, fmt.fmtDurationSigned(delta), }); } else { log.err("{}: system time is {} behind, clamping system time to cluster time", .{ self.replica, fmt.fmtDurationSigned(delta), }); } } else { const delta = system - upper; if (delta < std.time.ns_per_ms) { log.info("{}: system time is {} ahead", .{ self.replica, fmt.fmtDurationSigned(delta), }); } else { log.err("{}: system time is {} ahead, clamping system time to cluster time", .{ self.replica, fmt.fmtDurationSigned(delta), }); } } } fn window_tuples(self: *Self, tolerance: u64) []Marzullo.Tuple { assert(self.window.sources[self.replica].?.clock_offset == 0); assert(self.window.sources[self.replica].?.one_way_delay == 0); var count: usize = 0; for (self.window.sources) |sampled, source| { if (sampled) |sample| { self.marzullo_tuples[count] = Marzullo.Tuple{ .source = @intCast(u8, source), .offset = sample.clock_offset - @intCast(i64, sample.one_way_delay + tolerance), .bound = .lower, }; count += 1; self.marzullo_tuples[count] = Marzullo.Tuple{ .source = @intCast(u8, source), .offset = sample.clock_offset + @intCast(i64, sample.one_way_delay + tolerance), .bound = .upper, }; count += 1; } } return self.marzullo_tuples[0..count]; } fn minimum_one_way_delay(a: ?Sample, b: ?Sample) ?Sample { if (a == null) return b; if (b == null) return a; if (a.?.one_way_delay < b.?.one_way_delay) return a; // Choose B if B's one way delay is less or the same (we assume B is the newer sample): return b; } }; } const testing = std.testing; const OffsetType = @import("../test/time.zig").OffsetType; const DeterministicTime = @import("../test/time.zig").Time; const DeterministicClock = Clock(DeterministicTime); const ClockUnitTestContainer = struct { const Self = @This(); clock: DeterministicClock, rtt: u64 = 300 * std.time.ns_per_ms, owd: u64 = 150 * std.time.ns_per_ms, learn_interval: u64 = 5, pub fn init( allocator: std.mem.Allocator, offset_type: OffsetType, offset_coefficient_A: i64, offset_coefficient_B: i64, ) !Self { const time: DeterministicTime = .{ .resolution = std.time.ns_per_s / 2, .offset_type = offset_type, .offset_coefficient_A = offset_coefficient_A, .offset_coefficient_B = offset_coefficient_B, }; const self: Self = .{ .clock = try DeterministicClock.init(allocator, 3, 0, time), }; return self; } pub fn run_till_tick(self: *Self, tick: u64) void { while (self.clock.time.ticks < tick) { self.clock.time.tick(); if (@mod(self.clock.time.ticks, self.learn_interval) == 0) { const on_pong_time = self.clock.monotonic(); const m0 = on_pong_time - self.rtt; const t1 = @intCast(i64, on_pong_time - self.owd); self.clock.learn(1, m0, t1, on_pong_time); self.clock.learn(2, m0, t1, on_pong_time); } self.clock.synchronize(); } } const AssertionPoint = struct { tick: u64, expected_offset: i64, }; pub fn ticks_to_perform_assertions(self: *Self) [3]AssertionPoint { var ret: [3]AssertionPoint = undefined; switch (self.clock.time.offset_type) { .linear => { // For the first (OWD/drift per tick) ticks, the offset < OWD. This means that the // Marzullo interval is [0,0] (the offset and OWD are 0 for a replica w.r.t. itself). // Therefore the offset of `clock.realtime_synchronised` will be the analytically prescribed // offset at the start of the window. // Beyond this, the offset > OWD and the Marzullo interval will be from replica 1 and // replica 2. The `clock.realtime_synchronized` will be clamped to the lower bound. // Therefore the `clock.realtime_synchronized` will be offset by the OWD. var threshold = self.owd / @intCast(u64, self.clock.time.offset_coefficient_A); ret[0] = .{ .tick = threshold, .expected_offset = self.clock.time.offset(threshold - self.learn_interval), }; ret[1] = .{ .tick = threshold + 100, .expected_offset = @intCast(i64, self.owd), }; ret[2] = .{ .tick = threshold + 200, .expected_offset = @intCast(i64, self.owd), }; }, .periodic => { ret[0] = .{ .tick = @intCast(u64, @divTrunc(self.clock.time.offset_coefficient_B, 4)), .expected_offset = @intCast(i64, self.owd), }; ret[1] = .{ .tick = @intCast(u64, @divTrunc(self.clock.time.offset_coefficient_B, 2)), .expected_offset = 0, }; ret[2] = .{ .tick = @intCast(u64, @divTrunc(self.clock.time.offset_coefficient_B * 3, 4)), .expected_offset = -@intCast(i64, self.owd), }; }, .step => { ret[0] = .{ .tick = @intCast(u64, self.clock.time.offset_coefficient_B - 10), .expected_offset = 0, }; ret[1] = .{ .tick = @intCast(u64, self.clock.time.offset_coefficient_B + 10), .expected_offset = -@intCast(i64, self.owd), }; ret[2] = .{ .tick = @intCast(u64, self.clock.time.offset_coefficient_B + 10), .expected_offset = -@intCast(i64, self.owd), }; }, .non_ideal => unreachable, // use ideal clocks for the unit tests } return ret; } }; test "ideal clocks get clamped to cluster time" { std.testing.log_level = .err; var arena = std.heap.ArenaAllocator.init(std.heap.page_allocator); defer arena.deinit(); const allocator = &arena.allocator; var ideal_constant_drift_clock = try ClockUnitTestContainer.init( allocator, OffsetType.linear, std.time.ns_per_ms, // loses 1ms per tick 0, ); var linear_clock_assertion_points = ideal_constant_drift_clock.ticks_to_perform_assertions(); for (linear_clock_assertion_points) |point| { ideal_constant_drift_clock.run_till_tick(point.tick); try testing.expectEqual( point.expected_offset, @intCast(i64, ideal_constant_drift_clock.clock.monotonic()) - ideal_constant_drift_clock.clock.realtime_synchronized().?, ); } var ideal_periodic_drift_clock = try ClockUnitTestContainer.init( allocator, OffsetType.periodic, std.time.ns_per_s, // loses up to 1s 200, // period of 200 ticks ); var ideal_periodic_drift_clock_assertion_points = ideal_periodic_drift_clock.ticks_to_perform_assertions(); for (ideal_periodic_drift_clock_assertion_points) |point| { ideal_periodic_drift_clock.run_till_tick(point.tick); try testing.expectEqual( point.expected_offset, @intCast(i64, ideal_periodic_drift_clock.clock.monotonic()) - ideal_periodic_drift_clock.clock.realtime_synchronized().?, ); } var ideal_jumping_clock = try ClockUnitTestContainer.init( allocator, OffsetType.step, -5 * std.time.ns_per_day, // jumps 5 days ahead. 49, // after 49 ticks ); var ideal_jumping_clock_assertion_points = ideal_jumping_clock.ticks_to_perform_assertions(); for (ideal_jumping_clock_assertion_points) |point| { ideal_jumping_clock.run_till_tick(point.tick); try testing.expectEqual( point.expected_offset, @intCast(i64, ideal_jumping_clock.clock.monotonic()) - ideal_jumping_clock.clock.realtime_synchronized().?, ); } } const PacketSimulatorOptions = @import("../test/packet_simulator.zig").PacketSimulatorOptions; const PacketSimulator = @import("../test/packet_simulator.zig").PacketSimulator; const Path = @import("../test/packet_simulator.zig").Path; const ClockSimulator = struct { const Packet = struct { m0: u64, t1: ?i64, clock_simulator: *ClockSimulator, /// PacketSimulator requires this function, but we don't actually have anything to deinit. pub fn deinit(packet: *const Packet, path: Path) void { _ = packet; _ = path; } }; const Options = struct { ping_timeout: u32, clock_count: u8, network_options: PacketSimulatorOptions, }; allocator: std.mem.Allocator, options: Options, ticks: u64 = 0, network: PacketSimulator(Packet), clocks: []DeterministicClock, prng: std.rand.DefaultPrng, pub fn init(allocator: std.mem.Allocator, options: Options) !ClockSimulator { var self = ClockSimulator{ .allocator = allocator, .options = options, .network = try PacketSimulator(Packet).init(allocator, options.network_options), .clocks = try allocator.alloc(DeterministicClock, options.clock_count), .prng = std.rand.DefaultPrng.init(options.network_options.seed), }; for (self.clocks) |*clock, index| { clock.* = try self.create_clock(@intCast(u8, index)); } return self; } fn create_clock(self: *ClockSimulator, replica: u8) !DeterministicClock { const amplitude = self.prng.random.intRangeAtMost(i64, -10, 10) * std.time.ns_per_s; const phase = self.prng.random.intRangeAtMost(i64, 100, 1000) + @floatToInt(i64, self.prng.random.floatNorm(f64) * 50); const time: DeterministicTime = .{ .resolution = std.time.ns_per_s / 2, // delta_t = 0.5s .offset_type = OffsetType.non_ideal, .offset_coefficient_A = amplitude, .offset_coefficient_B = phase, .offset_coefficient_C = 10, }; return try DeterministicClock.init(self.allocator, self.options.clock_count, replica, time); } pub fn tick(self: *ClockSimulator) void { self.ticks += 1; self.network.tick(); for (self.clocks) |*clock| { clock.tick(); } for (self.clocks) |*clock| { if (clock.time.ticks % self.options.ping_timeout == 0) { const m0 = clock.monotonic(); for (self.clocks) |_, target| { if (target != clock.replica) { self.network.submit_packet( .{ .m0 = m0, .t1 = null, .clock_simulator = self, }, ClockSimulator.handle_packet, .{ .source = clock.replica, .target = @intCast(u8, target), }, ); } } } } } fn handle_packet(packet: Packet, path: Path) void { const self = packet.clock_simulator; const target = &self.clocks[path.target]; if (packet.t1) |t1| { target.learn( path.source, packet.m0, t1, target.monotonic(), ); } else { self.network.submit_packet( .{ .m0 = packet.m0, .t1 = target.realtime(), .clock_simulator = self, }, ClockSimulator.handle_packet, .{ // send the packet back to where it came from. .source = path.target, .target = path.source, }, ); } } }; test "fuzz test" { std.testing.log_level = .err; // silence all clock logs var arena_allocator = std.heap.ArenaAllocator.init(std.heap.page_allocator); defer arena_allocator.deinit(); const allocator = &arena_allocator.allocator; const ticks_max: u64 = 1_000_000; const clock_count: u8 = 3; const SystemTime = @import("../test/time.zig").Time; var system_time = SystemTime{}; var seed = @intCast(u64, system_time.realtime()); var min_sync_error: u64 = 1_000_000_000; var max_sync_error: u64 = 0; var max_clock_offset: u64 = 0; var min_clock_offset: u64 = 1_000_000_000; var simulator = try ClockSimulator.init(allocator, .{ .network_options = .{ .node_count = clock_count, .seed = seed, .one_way_delay_mean = 25, .one_way_delay_min = 10, .packet_loss_probability = 10, .path_maximum_capacity = 20, .path_clog_duration_mean = 200, .path_clog_probability = 2, .packet_replay_probability = 2, }, .clock_count = clock_count, .ping_timeout = 20, }); var clock_ticks_without_synchronization = [_]u32{0} ** clock_count; while (simulator.ticks < ticks_max) { simulator.tick(); for (simulator.clocks) |*clock, index| { var offset = clock.time.offset(simulator.ticks); var abs_offset = if (offset >= 0) @intCast(u64, offset) else @intCast(u64, -offset); max_clock_offset = if (abs_offset > max_clock_offset) abs_offset else max_clock_offset; min_clock_offset = if (abs_offset < min_clock_offset) abs_offset else min_clock_offset; var synced_time = clock.realtime_synchronized() orelse { clock_ticks_without_synchronization[index] += 1; continue; }; for (simulator.clocks) |*other_clock, other_clock_index| { if (index == other_clock_index) continue; var other_clock_sync_time = other_clock.realtime_synchronized() orelse { continue; }; var err: i64 = synced_time - other_clock_sync_time; var abs_err: u64 = if (err >= 0) @intCast(u64, err) else @intCast(u64, -err); max_sync_error = if (abs_err > max_sync_error) abs_err else max_sync_error; min_sync_error = if (abs_err < min_sync_error) abs_err else min_sync_error; } } } std.debug.print("seed={}, max ticks={}, clock count={}\n", .{ seed, ticks_max, clock_count, }); std.debug.print("absolute clock offsets with respect to test time:\n", .{}); std.debug.print("maximum={}\n", .{fmt.fmtDurationSigned(@intCast(i64, max_clock_offset))}); std.debug.print("minimum={}\n", .{fmt.fmtDurationSigned(@intCast(i64, min_clock_offset))}); std.debug.print("\nabsolute synchronization errors between clocks:\n", .{}); std.debug.print("maximum={}\n", .{fmt.fmtDurationSigned(@intCast(i64, max_sync_error))}); std.debug.print("minimum={}\n", .{fmt.fmtDurationSigned(@intCast(i64, min_sync_error))}); std.debug.print("clock ticks without synchronization={d}\n", .{ clock_ticks_without_synchronization, }); }
src/vsr/clock.zig
const std = @import("std"); const io = std.io; const process = std.process; const Allocator = std.mem.Allocator; const Chunk = @import("./chunk.zig").Chunk; const VM = @import("./vm.zig").VM; const ExternalWriter = @import("./writer.zig").ExternalWriter; var general_purpose_allocator = std.heap.GeneralPurposeAllocator(.{}){}; const allocator = &general_purpose_allocator.allocator; // These functions are expected to be passed in as part of the WASM environment extern fn writeOut(ptr: usize, len: usize) void; extern fn writeErr(ptr: usize, len: usize) void; fn writeOutSlice(bytes: []const u8) void { writeOut(@ptrToInt(bytes.ptr), bytes.len); } fn writeErrSlice(bytes: []const u8) void { writeErr(@ptrToInt(bytes.ptr), bytes.len); } fn createVMPtr() !*VM { // Note, important that outWriter holds ExternalWriter instance by // value, and not by reference, since a reference to the external // writer would be invalidated when this function exits. That // mistake caught me out earlier. const outWriter = ExternalWriter.init(writeOutSlice).writer(); const errWriter = ExternalWriter.init(writeErrSlice).writer(); var vm = try allocator.create(VM); vm.* = VM.create(); try vm.init(allocator, outWriter, errWriter); return vm; } export fn createVM() usize { var vm = createVMPtr() catch return 0; return @ptrToInt(vm); } export fn destroyVM(vm: *VM) void { vm.deinit(); allocator.destroy(vm); } export fn interpret(vm: *VM, input_ptr: [*]const u8, input_len: usize) usize { const source = input_ptr[0..input_len]; vm.interpret(source) catch |err| switch (err) { error.CompileError => return 65, error.RuntimeError => return 70, else => return 71, }; return 0; } export fn run(input_ptr: [*]const u8, input_len: usize) usize { var vm = createVMPtr() catch return 71; defer destroyVM(vm); return interpret(vm, input_ptr, input_len); } pub export fn alloc(len: usize) usize { var buf = allocator.alloc(u8, len) catch return 0; return @ptrToInt(buf.ptr); } pub export fn dealloc(ptr: [*]const u8, len: usize) void { allocator.free(ptr[0..len]); }
src/wasm-lib.zig
const std = @import("std"); pub fn Fixbuf(comptime max_len: usize) type { return struct { data: [max_len]u8 = undefined, len: usize = 0, pub fn copyFrom(self: *@This(), data: []const u8) void { std.mem.copy(u8, &self.data, data); self.len = data.len; } pub fn slice(self: @This()) []const u8 { return self.data[0..self.len]; } pub fn append(self: *@This(), char: u8) !void { if (self.len >= max_len) { return error.NoSpaceLeft; } self.data[self.len] = char; self.len += 1; } pub fn last(self: @This()) ?u8 { if (self.len > 0) { return self.data[self.len - 1]; } else { return null; } } pub fn pop(self: *@This()) !u8 { return self.last() orelse error.Empty; } }; } pub fn errSetContains(comptime ErrorSet: type, err: anytype) bool { inline for (comptime std.meta.fields(ErrorSet)) |e| { if (err == @field(ErrorSet, e.name)) { return true; } } return false; } pub fn ReturnOf(comptime func: anytype) type { return switch (@typeInfo(@TypeOf(func))) { .Fn, .BoundFn => |fn_info| fn_info.return_type.?, else => unreachable, }; } pub fn ErrorOf(comptime func: anytype) type { const return_type = ReturnOf(func); return switch (@typeInfo(return_type)) { .ErrorUnion => |eu_info| eu_info.error_set, else => unreachable, }; } pub fn Mailbox(comptime T: type) type { if (!std.Thread.use_pthreads) { @compileError("zCord currently requires pthreads. Please recompile with -lpthread enabled"); } return struct { const Self = @This(); value: ?T = null, cond: std.Thread.Condition = .{}, mutex: std.Thread.Mutex = .{}, pub fn get(self: *Self) T { const held = self.mutex.acquire(); defer held.release(); if (self.value) |value| { self.value = null; return value; } else { self.cond.wait(&self.mutex); defer self.value = null; return self.value.?; } } pub fn getWithTimeout(self: *Self, timeout_ns: u64) ?T { const held = self.mutex.acquire(); defer held.release(); if (self.value) |value| { self.value = null; return value; } else { const future_ns = std.time.nanoTimestamp() + timeout_ns; var future: std.os.timespec = undefined; future.tv_sec = @intCast(@TypeOf(future.tv_sec), @divFloor(future_ns, std.time.ns_per_s)); future.tv_nsec = @intCast(@TypeOf(future.tv_nsec), @mod(future_ns, std.time.ns_per_s)); const rc = std.os.system.pthread_cond_timedwait(&self.cond.impl.cond, &self.mutex.impl.pthread_mutex, &future); std.debug.assert(rc == 0 or rc == std.os.system.ETIMEDOUT); defer self.value = null; return self.value; } } pub fn putOverwrite(self: *Self, value: T) void { self.value = value; self.cond.impl.signal(); } }; }
src/util.zig
const std = @import("std"); const Allocator = std.mem.Allocator; const ArrayList = std.ArrayList; const c = @import("c.zig"); const gfx = @import("gfx.zig"); //; pub const ButtonState = enum { const Self = @This(); Pressed, Held, Released, Off, pub fn initFromActions(now: Action, last: Action) Self { if (now != last) { return switch (now) { .Press => .Pressed, .Repeat => .Held, .Release => .Released, }; } else { return switch (now) { // note: two presses in a row sounds unlikely .Press => .Held, .Repeat => .Held, .Release => .Off, }; } } }; pub const Action = enum(u8) { const Self = @This(); Press, Repeat, Release, pub fn init(raw_action: c_int) Self { return switch (raw_action) { c.GLFW_PRESS => Self.Press, c.GLFW_REPEAT => Self.Repeat, c.GLFW_RELEASE => Self.Release, else => unreachable, }; } }; pub const Mods = packed struct { const Self = @This(); shift: bool, control: bool, alt: bool, super: bool, caps_lock: bool, num_lock: bool, pub fn init(raw_mods: c_int) Self { return .{ .shift = (raw_mods & c.GLFW_MOD_SHIFT) != 0, .control = (raw_mods & c.GLFW_MOD_CONTROL) != 0, .alt = (raw_mods & c.GLFW_MOD_ALT) != 0, .super = (raw_mods & c.GLFW_MOD_SUPER) != 0, .caps_lock = (raw_mods & c.GLFW_MOD_CAPS_LOCK) != 0, .num_lock = (raw_mods & c.GLFW_MOD_NUM_LOCK) != 0, }; } }; pub const KeyEvent = struct { const Self = @This(); pub const Key = enum(i16) { Unknown = -1, Space = 32, Apostrophe = 39, Comma = 44, Minus = 45, Period = 46, Slash = 47, KB_0 = 48, KB_1 = 49, KB_2 = 50, KB_3 = 51, KB_4 = 52, KB_5 = 53, KB_6 = 54, KB_7 = 55, KB_8 = 56, KB_9 = 57, Semicolon = 59, Equal = 61, A = 65, B = 66, C = 67, D = 68, E = 69, F = 70, G = 71, H = 72, I = 73, J = 74, K = 75, L = 76, M = 77, N = 78, O = 79, P = 80, Q = 81, R = 82, S = 83, T = 84, U = 85, V = 86, W = 87, X = 88, Y = 89, Z = 90, LeftBracket = 91, Backslash = 92, RightBracket = 93, GraveAccent = 96, World1 = 161, World2 = 162, Escape = 256, Enter = 257, Tab = 258, Backspace = 259, Insert = 260, Delete = 261, Right = 262, Left = 263, Down = 264, Up = 265, PageUp = 266, PageDown = 267, Home = 268, End = 269, CapsLock = 280, ScrollLock = 281, NumLock = 282, PrintScreen = 283, Pause = 284, F1 = 290, F2 = 291, F3 = 292, F4 = 293, F5 = 294, F6 = 295, F7 = 296, F8 = 297, F9 = 298, F10 = 299, F11 = 300, F12 = 301, F13 = 302, F14 = 303, F15 = 304, F16 = 305, F17 = 306, F18 = 307, F19 = 308, F20 = 309, F21 = 310, F22 = 311, F23 = 312, F24 = 313, F25 = 314, KP_0 = 320, KP_1 = 321, KP_2 = 322, KP_3 = 323, KP_4 = 324, KP_5 = 325, KP_6 = 326, KP_7 = 327, KP_8 = 328, KP_9 = 329, KP_Decimal = 330, KP_Divide = 331, KP_Multiply = 332, KP_Subtract = 333, KP_Add = 334, KP_Enter = 335, KP_Equal = 336, LeftShift = 340, LeftControl = 341, LeftAlt = 342, LeftSuper = 343, RightShift = 344, RightControl = 345, RightAlt = 346, RightSuper = 347, Menu = 348, }; key: Key, scancode: ?u32, action: Action, mods: Mods, fn init(key: c_int, scancode: c_int, action: c_int, mods: c_int) Self { return .{ .key = @intToEnum(Key, @intCast(i16, key)), .scancode = if (scancode < 0) null else @intCast(u32, scancode), .action = Action.init(action), .mods = Mods.init(mods), }; } }; pub const CharEvent = struct { const Self = @This(); buf: [4]u8, len: u3, fn init(raw_codepoint: c_uint) Self { var ret: Self = undefined; ret.len = std.unicode.utf8Encode(@intCast(u21, raw_codepoint), &ret.buf) catch 0; return ret; } pub fn slice(self: Self) []const u8 { var ret: []const u8 = &self.buf; ret.len = self.len; return ret; } }; pub const MouseEvent = union(enum) { const Self = @This(); pub const MoveEvent = struct { x: f64, y: f64, }; pub const ButtonEvent = struct { pub const Button = enum(u8) { Left, Right, Middle, MB_4, MB_5, MB_6, MB_7, MB_8, }; button: Button, action: Action, mods: Mods, pub fn init(button: c_int, action: c_int, mods: c_int) ButtonEvent { return .{ .button = @intToEnum(Button, @intCast(u8, button)), .action = Action.init(action), .mods = Mods.init(mods), }; } }; pub const EnterEvent = struct { entered: bool, }; pub const ScrollEvent = struct { x: f64, y: f64, }; Move: MoveEvent, Button: ButtonEvent, Enter: EnterEvent, Scroll: ScrollEvent, }; pub const JoystickEvent = struct { id: u8, is_connected: bool, }; pub const GamepadData = struct { const button_ct = @typeInfo(Button).Enum.fields.len; const axis_ct = @typeInfo(Axis).Enum.fields.len; pub const Button = enum(usize) { A, B, X, Y, LeftBumper, RightBumper, Back, Start, Guide, LeftThumb, RightThumb, DPadUp, DPadRight, DPadDown, DPadLeft, }; pub const Axis = enum(usize) { LeftX, LeftY, RightX, RightY, LeftTrigger, RightTrigger, }; is_connected: bool, buttons: [button_ct]ButtonState, glfw_buttons_last: [button_ct]Action, glfw_buttons: [button_ct]Action, axes: [axis_ct]f32, pub fn getButtonState(self: Self, button: Button) Action { return self.buttons[@enumToInt(button)]; } pub fn getAxisState(self: Self, axis: Axis) f32 { return self.axes[@enumToInt(axis)]; } }; // pub const GamepadEvent = union(enum) { // const ButtonEvent = struct { // id: u8, // button: GamepadData.Button, // action: Action, // }; // // const AxisEvent = struct { // id: u8, // axis: GamepadData.Axis, // delta: f32, // position: f32, // }; // // const ConnectionEvent = struct { // id: u8, // is_connected: bool, // }; // // Connection: ConnectionEvent, // Button: ButtonEvent, // Axis: AxisEvent, // }; // // pub const Event = union(enum) { // Key: KeyEvent, // Char: CharEvent, // Mouse: MouseEvent, // Joystick: JoystickEvent, // GamepadEvent: GamepadEvent, // }; // TODO // gamepad // update mappings // allow player to put in thier own mappings if they need to // look into how calibration works // note: // by not using one array for events, // info is lost what order the events come in across different types // probably not a huge problem pub const EventHandler = struct { const Self = @This(); key_events: ArrayList(KeyEvent), char_events: ArrayList(CharEvent), mouse_events: ArrayList(MouseEvent), joystick_events: ArrayList(JoystickEvent), gamepads: [c.GLFW_JOYSTICK_LAST + 1]GamepadData, pub fn init(allocator: *Allocator, window: *c.GLFWwindow) Self { _ = c.glfwSetKeyCallback(window, keyCallback); _ = c.glfwSetCharCallback(window, charCallback); _ = c.glfwSetCursorPosCallback(window, cursorPosCallback); _ = c.glfwSetCursorEnterCallback(window, cursorEnterCallback); _ = c.glfwSetMouseButtonCallback(window, mouseButtonCallback); _ = c.glfwSetScrollCallback(window, scrollCallback); _ = c.glfwSetJoystickCallback(joystickCallback); var ret = Self{ .key_events = ArrayList(KeyEvent).init(allocator), .char_events = ArrayList(CharEvent).init(allocator), .mouse_events = ArrayList(MouseEvent).init(allocator), .joystick_events = ArrayList(JoystickEvent).init(allocator), .gamepads = undefined, }; // TODO handle notifying if gmae boots with joystick connected // cant just push to joystick_events, cuz its cleared on poll // TODO no code duplication var id: c_int = 0; while (id < c.GLFW_JOYSTICK_LAST) : (id += 1) { if (c.glfwJoystickPresent(id) == c.GLFW_TRUE) { if (c.glfwJoystickIsGamepad(id) == c.GLFW_TRUE) { // TODO could poll gamepad state here, just for completeness ret.gamepads[@intCast(usize, id)] = .{ .is_connected = true, .buttons = [_]ButtonState{.Off} ** GamepadData.button_ct, .glfw_buttons = [_]Action{.Release} ** GamepadData.button_ct, .glfw_buttons_last = [_]Action{.Release} ** GamepadData.button_ct, .axes = [_]f32{0} ** GamepadData.axis_ct, }; } else { // TODO // joysticks not supported } } else { ret.gamepads[@intCast(usize, id)].is_connected = false; } } return ret; } pub fn deinit(self: *Self) void { self.joystick_events.deinit(); self.mouse_events.deinit(); self.char_events.deinit(); self.key_events.deinit(); } // TODO have callback report an error somehow, // then this can return the error pub fn poll(self: *Self) void { self.key_events.items.len = 0; self.char_events.items.len = 0; self.mouse_events.items.len = 0; self.joystick_events.items.len = 0; c.glfwPollEvents(); // update gamepad data // by this time, all gamepads in self.gamepads must be: // currently connected // not joysticks for (self.gamepads) |*gpd, id| { if (gpd.is_connected) { var state: c.GLFWgamepadstate = undefined; // TODO assert this returns true? // technically should be // means that it is connected and is a gamepad _ = c.glfwGetGamepadState(@intCast(c_int, id), &state); { var i: usize = 0; while (i < GamepadData.button_ct) : (i += 1) { gpd.glfw_buttons_last[i] = gpd.glfw_buttons[i]; gpd.glfw_buttons[i] = Action.init(state.buttons[i]); gpd.buttons[i] = ButtonState.initFromActions(gpd.glfw_buttons[i], gpd.glfw_buttons_last[i]); } } for (state.axes) |val, i| { gpd.axes[i] = val; } } } } //; fn keyCallback( win: ?*c.GLFWwindow, key: c_int, scancode: c_int, action: c_int, mods: c_int, ) callconv(.C) void { var ctx = gfx.Context.getFromGLFW_WindowPtr(win); var evs = &ctx.event_handler.?; // TODO do something on allocator fail // just do nothing? evs.key_events.append(KeyEvent.init(key, scancode, action, mods)) catch unreachable; } fn charCallback( win: ?*c.GLFWwindow, codepoint: c_uint, ) callconv(.C) void { var ctx = gfx.Context.getFromGLFW_WindowPtr(win); var evs = &ctx.event_handler.?; evs.char_events.append(CharEvent.init(codepoint)) catch unreachable; } fn cursorPosCallback( win: ?*c.GLFWwindow, x: f64, y: f64, ) callconv(.C) void { var ctx = gfx.Context.getFromGLFW_WindowPtr(win); var evs = &ctx.event_handler.?; evs.mouse_events.append(.{ .Move = .{ .x = x, .y = y, }, }) catch unreachable; } fn cursorEnterCallback( win: ?*c.GLFWwindow, entered: c_int, ) callconv(.C) void { var ctx = gfx.Context.getFromGLFW_WindowPtr(win); var evs = &ctx.event_handler.?; evs.mouse_events.append(.{ .Enter = .{ .entered = entered == c.GLFW_TRUE, }, }) catch unreachable; } fn mouseButtonCallback( win: ?*c.GLFWwindow, button: c_int, action: c_int, mods: c_int, ) callconv(.C) void { var ctx = gfx.Context.getFromGLFW_WindowPtr(win); var evs = &ctx.event_handler.?; evs.mouse_events.append(.{ .Button = MouseEvent.ButtonEvent.init(button, action, mods), }) catch unreachable; } fn scrollCallback( win: ?*c.GLFWwindow, x: f64, y: f64, ) callconv(.C) void { var ctx = gfx.Context.getFromGLFW_WindowPtr(win); var evs = &ctx.event_handler.?; evs.mouse_events.append(.{ .Scroll = .{ .x = x, .y = y, }, }) catch unreachable; } fn joystickCallback( id: c_int, event: c_int, ) callconv(.C) void { if (gfx.joystick_ctx_reference) |ctx| { var evs = &ctx.event_handler.?; if (event == c.GLFW_CONNECTED) { if (c.glfwJoystickIsGamepad(id) == c.GLFW_TRUE) { evs.gamepads[@intCast(usize, id)].is_connected = true; evs.joystick_events.append(.{ .id = @intCast(u8, id), .is_connected = true, }) catch unreachable; } else { // TODO error or something, joysticks that arent gamepads arent supported } } else if (event == c.GLFW_DISCONNECTED) { evs.gamepads[@intCast(usize, id)].is_connected = false; evs.joystick_events.append(.{ .id = @intCast(u8, id), .is_connected = false, }) catch unreachable; } } } };
src/events.zig
const std = @import("std"); const ray = @import("translate-c/raylib_all.zig"); pub fn getRandomValue(comptime T: type, min: i32, max: i32) T { const re = ray.GetRandomValue(min, max); switch (@typeInfo(T)) { .Int => return @intCast(T, re), .Float => return @intToFloat(T, re), else => unreachable, } } pub fn main() anyerror!void { // Initialization //-------------------------------------------------------------------------------------- const screenWidth = 800; const screenHeight = 450; ray.InitWindow(screenWidth, screenHeight, "raylib [core] example - 3d camera first person"); defer ray.CloseWindow(); // Define the camera to look into our 3d world var camera = ray.Camera3D{ .position = ray.Vector3{ .x = 4, .y = 2, .z = 4 }, .target = ray.Vector3{ .x = 0, .y = 1.8, .z = 0 }, .up = ray.Vector3{ .x = 0, .y = 1, .z = 0 }, .fovy = 60, .projection = ray.CAMERA_PERSPECTIVE, }; // Generates some random columns const max_columns = 20; var heights = [_]f32{0} ** max_columns; var positions = [_]ray.Vector3{ray.Vector3{ .x = 0, .y = 0, .z = 0 }} ** max_columns; var colors = [_]ray.Color{ray.Color{ .r = 0, .g = 0, .b = 0, .a = 0 }} ** max_columns; { var i: usize = 0; while (i < max_columns) : (i += 1) { heights[i] = getRandomValue(f32, 1, 12); positions[i] = ray.Vector3{ .x = getRandomValue(f32, -15, 15), .y = heights[i] / 2, .z = getRandomValue(f32, -15, 15), }; colors[i] = ray.Color{ .r = getRandomValue(u8, 20, 255), .g = getRandomValue(u8, 10, 55), .b = 30, .a = 255, }; } } ray.SetCameraMode(camera, ray.CAMERA_FIRST_PERSON); // Set a first person camera mode ray.SetTargetFPS(60); //-------------------------------------------------------------------------------------- // Main game loop while (!ray.WindowShouldClose()) { // Update //---------------------------------------------------------------------------------- // const deltaTime = ray.GetFrameTime(); ray.UpdateCamera(&camera); // Draw //---------------------------------------------------------------------------------- ray.BeginDrawing(); ray.ClearBackground(ray.RAYWHITE); ray.BeginMode3D(camera); ray.DrawPlane(ray.Vector3{ .x = 0, .y = 0, .z = 0 }, ray.Vector2{ .x = 32, .y = 32 }, ray.LIGHTGRAY); // Draw ground ray.DrawCube(ray.Vector3{ .x = -16, .y = 2, .z = 0 }, 1, 5, 32, ray.BLUE); // Draw a blue wall ray.DrawCube(ray.Vector3{ .x = 16, .y = 2, .z = 0 }, 1, 5, 32, ray.LIME); // Draw a green wall ray.DrawCube(ray.Vector3{ .x = 0, .y = 2, .z = 16 }, 32, 5, 1, ray.GOLD); // Draw a yellow wall // Draw some cubes around var i: usize = 0; while (i < max_columns) : (i += 1) { ray.DrawCube(positions[i], 2, heights[i], 2, colors[i]); ray.DrawCubeWires(positions[i], 2, heights[i], 2, ray.MAROON); } ray.EndMode3D(); ray.DrawRectangle(10, 10, 220, 70, ray.Fade(ray.SKYBLUE, 0)); ray.DrawRectangleLines(10, 10, 220, 70, ray.BLUE); ray.DrawText("First person camera default controls:", 20, 20, 10, ray.BLACK); ray.DrawText("- Move with keys: W, A, S, D", 40, 40, 10, ray.DARKGRAY); ray.DrawText("- Mouse move to look around", 40, 60, 10, ray.DARKGRAY); ray.EndDrawing(); } }
src/examples/fps_camera.zig
const std = @import("std"); const expect = std.testing.expect; const test_allocator = std.testing.allocator; test "createFile, write, seekTo, read" { const file = try std.fs.cwd().createFile("junk_file.txt", std.fs.File.CreateFlags{ .read = true }); defer file.close(); try file.writeAll("Hello File!"); var buffer: [100]u8 = undefined; try file.seekTo(0); const bytes_read = try file.readAll(&buffer); try expect(std.mem.eql(u8, buffer[0..bytes_read], "Hello File!")); } test "file stat" { const file = try std.fs.cwd().createFile( "junk_file2.txt", .{}, ); defer file.close(); const stat = try file.stat(); try expect(stat.size == 0); try expect(stat.kind == .File); try expect(stat.ctime <= std.time.nanoTimestamp()); try expect(stat.mtime <= std.time.nanoTimestamp()); try expect(stat.atime <= std.time.nanoTimestamp()); } test "make dir" { try std.fs.cwd().deleteTree("test-tmp"); try std.fs.cwd().makeDir("test-tmp"); const dir = try std.fs.cwd().openDir("test-tmp", .{ .iterate = true }); defer { std.fs.cwd().deleteTree("test-tmp") catch unreachable; } _ = try dir.createFile("x", .{}); _ = try dir.createFile("y", .{}); _ = try dir.createFile("z", .{}); var file_count: usize = 0; var iter = dir.iterate(); while (try iter.next()) |entry| { if (entry.kind == .File) file_count += 1; } try expect(file_count == 3); } test "io writer usage" { var list = std.ArrayList(u8).init(test_allocator); defer list.deinit(); const writer = list.writer(); const bytes_written = try writer.write("Hello World!"); try expect(bytes_written == 12); try expect(std.mem.eql(u8, list.items, "Hello World!")); } test "io reader usage" { const message = "Hello File!"; const file = try std.fs.cwd().createFile("junk_file2.txt", .{ .read = true }); defer file.close(); try file.writeAll(message); try file.seekTo(0); const contents = try file.reader().readAllAlloc(test_allocator, message.len); defer test_allocator.free(contents); try expect(std.mem.eql(u8, contents, message)); } fn nextLine(reader: anytype, buffer: []u8) !?[]const u8 { var line = (try reader.readUntilDelimiterOrEof(buffer, '\n')) orelse return null; // trim annoying windows-only carriage return character if (std.builtin.os.tag == .windows) { line = std.mem.trimRight(u8, line, "\r"); } return line; } test "read until next line" { const stdout = std.io.getStdOut(); const stdin = std.io.getStdIn(); try stdout.writeAll( \\ Enter your name: ); var buffer: [100]u8 = undefined; const input = (try nextLine(stdin.reader(), &buffer)).?; try stdout.writer.print("Your name is: \"{s}\"\n", .{input}); }
zig/learn/fs_test.zig
const builtin = @import("builtin"); const TypeInfo = builtin.TypeInfo; const TypeId = builtin.TypeId; const std = @import("std"); const math = std.math; const meta = std.meta; const assert = std.debug.assert; const warn = std.debug.warn; pub fn Matrix(comptime T: type, comptime m: usize, comptime n: usize) type { return struct.{ const Self = @This(); const row_cnt = m; const col_cnt = n; pub data: [m][n]T, /// Initialize Matrix to a value pub fn init() Self { return Self.{ .data = undefined }; } /// Initialize Matrix to a value pub fn initVal(val: T) Self { var self = Self.init(); for (self.data) |row, i| { for (row) |_, j| { self.data[i][j] = val; } } return self; } /// Return true of pSelf.data == pOther.data pub fn eql(pSelf: *const Self, pOther: *const Self) bool { for (pSelf.data) |row, i| { for (row) |val, j| { if (val != pOther.data[i][j]) return false; } } return true; } /// Print the Matrix pub fn print(pSelf: *const Self, s: []const u8) void { warn("{}", s); for (pSelf.data) |row, i| { warn("{}: []{}.{{ ", i, @typeName(T)); for (row) |val, j| { warn("{.7}{}", val, if (j < (row.len - 1)) ", " else " "); } warn("}},\n"); } } }; } /// Returns a struct.mul function that multiplies m1 by m2 pub fn MatrixMultiplier(comptime m1: type, comptime m2: type) type { const m1_DataType = @typeInfo(@typeInfo(meta.fieldInfo(m1, "data").field_type).Array.child).Array.child; const m2_DataType = @typeInfo(@typeInfo(meta.fieldInfo(m2, "data").field_type).Array.child).Array.child; // What other validations should I check if (m1_DataType != m2_DataType) { @compileError("m1:" ++ @typeName(m1_DataType) ++ " != m2:" ++ @typeName(m2_DataType)); } if (m1.col_cnt != m2.row_cnt) { @compileError("m1.col_cnt: m1.col_cnt != m2.row_cnt"); } const DataType = m1_DataType; const row_cnt = m1.row_cnt; const col_cnt = m2.col_cnt; return struct.{ pub fn mul(mt1: *const m1, mt2: *const m2) Matrix(DataType, row_cnt, col_cnt) { var r = Matrix(DataType, row_cnt, col_cnt).init(); comptime var i: usize = 0; inline while (i < row_cnt) : (i += 1) { //warn("mul {}:\n", i); comptime var j: usize = 0; inline while (j < col_cnt) : (j += 1) { //warn(" ({}:", j); comptime var k: usize = 0; // The inner loop is m1.col_cnt or m2.row_cnt, which are equal inline while (k < m1.col_cnt) : (k += 1) { var val = mt1.data[i][k] * mt2.data[k][j]; if (k == 0) { r.data[i][j] = val; //warn(" {}:{}={} * {}", k, val, mt1.data[i][k], mt2.data[k][j]); } else { r.data[i][j] += val; //warn(" {}:{}={} * {}", k, val, mt1.data[i][k], mt2.data[k][j]); } } //warn(" {})\n", r.data[i][j]); } } return r; } }; } test "matrix.init" { warn("\n"); var m1 = Matrix(f32, 1, 1).init(); m1.data = [][1]f32.{ []f32.{ 2 }, }; m1.print("matrix.1x1*1x1 m1:\n"); assert(m1.data[0][0] == 2); const mf32 = Matrix(f32, 4, 4).initVal(1); mf32.print("mf32: init(1)\n"); for (mf32.data) |row| { for (row) |val| { assert(val == 1); } } } test "matrix.eql" { warn("\n"); const m0 = Matrix(f32, 4, 4).initVal(0); for (m0.data) |row| { for (row) |val| { assert(val == 0); } } var o0 = Matrix(f32, 4, 4).initVal(0); assert(m0.eql(&o0)); // Modify last value and verify !eql o0.data[3][3] = 1; o0.print("data.eql: o0\n"); assert(!m0.eql(&o0)); // Modify first value and verify !eql o0.data[0][0] = 1; o0.print("data.eql: o0\n"); assert(!m0.eql(&o0)); // Restore back to 0 and verify eql o0.data[3][3] = 0; o0.data[0][0] = 0; o0.print("data.eql: o0\n"); assert(m0.eql(&o0)); } test "matrix.1x1*1x1" { warn("\n"); const m1 = Matrix(f32, 1, 1).initVal(2); m1.print("matrix.1x1*1x1 m1:\n"); const m2 = Matrix(f32, 1, 1).initVal(3); m2.print("matrix.1x1*1x1 m2:\n"); const m3 = MatrixMultiplier(@typeOf(m1), @typeOf(m2)).mul(&m1, &m2); m3.print("matrix.1x1*1x1 m3:\n"); var expected = Matrix(f32, 1, 1).init(); expected.data = [][1]f32.{ []f32.{ (m1.data[0][0] * m2.data[0][0]), }, }; expected.print("matrix.1x1*1x1 expected:\n"); assert(m3.eql(&expected)); } test "matrix.2x2*2x2" { warn("\n"); var m1 = Matrix(f32, 2, 2).init(); m1.data = [][2]f32.{ []f32.{ 1, 2 }, []f32.{ 3, 4 }, }; m1.print("matrix.2x2*2x2 m1:\n"); var m2 = Matrix(f32, 2, 2).init(); m2.data = [][2]f32.{ []f32.{ 5, 6 }, []f32.{ 7, 8 }, }; m2.print("matrix.2x2*2x2 m2:\n"); const m3 = MatrixMultiplier(@typeOf(m1), @typeOf(m2)).mul(&m1, &m2); m3.print("matrix.2x2*2x2 m3:\n"); var expected = Matrix(f32, 2, 2).init(); expected.data = [][2]f32.{ []f32.{ (m1.data[0][0] * m2.data[0][0]) + (m1.data[0][1] * m2.data[1][0]), (m1.data[0][0] * m2.data[0][1]) + (m1.data[0][1] * m2.data[1][1]), }, []f32.{ (m1.data[1][0] * m2.data[0][0]) + (m1.data[1][1] * m2.data[1][0]), (m1.data[1][0] * m2.data[0][1]) + (m1.data[1][1] * m2.data[1][1]), }, }; expected.print("matrix.2x2*2x2 expected:\n"); assert(m3.eql(&expected)); } test "matrix.1x2*2x1" { warn("\n"); var m1 = Matrix(f32, 1, 2).init(); m1.data = [][2]f32.{ []f32.{ 3, 4 }, }; m1.print("matrix.1x2*2x1 m1:\n"); var m2 = Matrix(f32, 2, 1).init(); m2.data = [][1]f32.{ []f32.{ 5 }, []f32.{ 7 }, }; m2.print("matrix.1x2*2x1 m2:\n"); const m3 = MatrixMultiplier(@typeOf(m1), @typeOf(m2)).mul(&m1, &m2); m3.print("matrix.1x2*2x1 m3:\n"); var expected = Matrix(f32, 1, 1).init(); expected.data = [][1]f32.{ []f32.{ (m1.data[0][0] * m2.data[0][0]) + (m1.data[0][1] * m2.data[1][0]), }, }; expected.print("matrix.1x2*2x1 expected:\n"); assert(m3.eql(&expected)); }
matrix/matrix.zig
const vm = @import("vecmath_j.zig"); const std = @import("std"); const math = std.math; const Vec3 = vm.Vec3; const material = @import("material.zig"); const Material = material.Material; const Random = std.rand.DefaultPrng; const util = @import("utils.zig"); pub const Ray = struct { orig : Vec3, dir : Vec3, pub inline fn at( ray: Ray, t: f32 ) Vec3 { var result : Vec3 = Vec3.add( ray.orig ,Vec3.mul_s( ray.dir, t ) ); return result; } }; pub const HitRecord = struct { point : Vec3, normal : Vec3, t : f32, front_face : bool, mtl : *const Material, }; pub const Camera = struct { const Self = @This(); origin : Vec3, lower_left_corner : Vec3, horizontal : Vec3, vertical : Vec3, u : Vec3, v : Vec3, w : Vec3, lens_radius : f32, pub fn init( lookfrom : Vec3, lookat : Vec3, up : Vec3, vertical_fov : f32, aspect_ratio : f32, aperture : f32, focus_dist : f32 ) Camera { //const aspect_ratio : f32 = 16.0 / 9.0; const theta = vertical_fov * (math.pi / 180.0); const h = math.tan( theta / 2.0 ); const viewport_height : f32 = h; const viewport_width : f32 = aspect_ratio * viewport_height; //const focal_length : f32 = 1.0; const w = Vec3.normalize( Vec3.sub( lookfrom, lookat )); const u = Vec3.normalize( Vec3.cross( up, w )); const v = Vec3.cross( w, u ); const origin = lookfrom; const horizontal = Vec3.mul_s( u, viewport_width * focus_dist ); const vertical = Vec3.mul_s( v, viewport_height * focus_dist ); const half_h : Vec3 = Vec3.mul_s( horizontal, 0.5 ); const half_v : Vec3 = Vec3.mul_s( vertical, 0.5 ); const o_minus_h = Vec3.sub( origin, half_h ); const omh_minus_v = Vec3.sub( o_minus_h, half_v ); const lower_left_corner : Vec3 = Vec3.sub( omh_minus_v, Vec3.mul_s( w, focus_dist) ); return .{ .origin = origin, .horizontal = horizontal, .vertical = vertical, .lower_left_corner = lower_left_corner, .u = u, .v = v, .w = w, .lens_radius = (aperture / 2.0), }; } pub fn genRay( self: Self, rng: *Random, u : f32, v : f32 ) Ray { const rd = Vec3.mul_s( util.randomInUnitDisc( rng ), self.lens_radius ); const offs = Vec3.add( Vec3.mul_s( self.u, rd.v[0] ), Vec3.mul_s( self.v, rd.v[1] ) ); var rdir : Vec3 = Vec3.add( self.lower_left_corner, Vec3.mul_s( self.horizontal, u ) ); rdir = Vec3.add( rdir, Vec3.mul_s( self.vertical, v ) ); rdir = Vec3.sub( rdir, Vec3.add( self.origin, offs ) ); const r : Ray = .{ .orig = Vec3.add( self.origin, offs ), .dir = rdir }; return r; } };
src/camera.zig
const std = @import("std"); const builtin = @import("builtin"); const Builder = std.build.Builder; fn maybeLinkSnappy(obj: *std.build.LibExeObjStep, with_snappy: bool) void { obj.addBuildOption(bool, "with_snappy", with_snappy); if (!with_snappy) return; linkSnappy(obj); } fn linkSnappy(obj: *std.build.LibExeObjStep) void { obj.linkLibC(); obj.linkSystemLibrary("snappy"); } pub fn build(b: *Builder) !void { var target = b.standardTargetOptions(.{}); const mode = b.standardReleaseOptions(); // Define options const with_snappy = b.option(bool, "with_snappy", "Enable Snappy compression") orelse false; const with_cassandra = b.option([]const u8, "with_cassandra", "Run tests which need a Cassandra node running to work.") orelse null; // LZ4 // // To make cross compiling easier we embed the lz4 source code which is small enough and is easily compiled // with Zig's C compiling abilities. const lz4 = b.addStaticLibrary("lz4", null); lz4.linkLibC(); // lz4 is broken with -fsanitize=pointer-overflow which is added automatically by Zig with -fsanitize=undefined. // See here what this flag does: https://clang.llvm.org/docs/UndefinedBehaviorSanitizer.html lz4.addCSourceFile("src/lz4.c", &[_][]const u8{ "-std=c99", "-fno-sanitize=pointer-overflow" }); lz4.setTarget(target); lz4.setBuildMode(mode); lz4.addIncludeDir("src"); var lz4_tests = b.addTest("src/lz4.zig"); lz4_tests.linkLibrary(lz4); lz4_tests.setTarget(target); lz4_tests.setBuildMode(mode); lz4_tests.addIncludeDir("src"); const lz4_test_step = b.step("lz4-test", "Run the lz4 tests"); lz4_test_step.dependOn(&lz4_tests.step); // Snappy if (with_snappy) { var snappy_tests = b.addTest("src/snappy.zig"); linkSnappy(snappy_tests); snappy_tests.setTarget(target); snappy_tests.setBuildMode(mode); const snappy_test_step = b.step("snappy-test", "Run the snappy tests"); snappy_test_step.dependOn(&snappy_tests.step); } // Build library // const lib = b.addStaticLibrary("zig-cassandra", "src/lib.zig"); lib.linkLibrary(lz4); lib.setTarget(target); lib.setBuildMode(mode); lib.addIncludeDir("src"); maybeLinkSnappy(lib, with_snappy); lib.install(); // Add the main tests for the library. // var main_tests = b.addTest("src/lib.zig"); main_tests.linkLibrary(lz4); main_tests.setTarget(target); main_tests.setBuildMode(mode); main_tests.addIncludeDir("src"); maybeLinkSnappy(main_tests, with_snappy); main_tests.addBuildOption(?[]const u8, "with_cassandra", with_cassandra); const test_step = b.step("test", "Run library tests"); test_step.dependOn(&main_tests.step); // Add the example // const example = b.addExecutable("example", "src/example.zig"); example.linkLibrary(lz4); example.setTarget(target); example.setBuildMode(mode); example.install(); example.addIncludeDir("src"); maybeLinkSnappy(example, with_snappy); }
build.zig
const std = @import("std"); const event = std.event; const fs = std.fs; const heap = std.heap; const log = std.log; const mem = std.mem; const Message = @import("../message.zig").Message; pub fn mail(channel: *event.Channel(Message), home_dir: fs.Dir) void { const loop = event.Loop.instance.?; // TODO: Currently we just count the mails every so often. In an ideal world, // we wait for file system events, but it seems that Zigs `fs.Watch` haven't been // worked on for a while, so I'm not gonna try using it. while (true) : (loop.sleep(std.time.ns_per_s * 10)) { var mail_dir = home_dir.openDir(".local/share/mail", .{ .iterate = true }) catch |err| { return log.err("Failed to open .local/share/mail: {}", .{err}); }; defer mail_dir.close(); const res = count(mail_dir) catch |err| { log.warn("Failed to count mail: {}", .{err}); continue; }; channel.put(.{ .mail = .{ .read = res.read, .unread = res.unread, }, }); } } pub const Mail = struct { unread: usize, read: usize, }; fn count(root: fs.Dir) !Mail { var buf: [1024 * 1024]u8 = undefined; const fba = &heap.FixedBufferAllocator.init(&buf).allocator; var stack = std.ArrayList(fs.Dir).init(fba); var res = Mail{ .unread = 0, .read = 0 }; try stack.append(root); // Never close root dir errdefer for (stack.items) |*dir| if (dir.fd != root.fd) dir.close(); while (stack.popOrNull()) |*dir| { defer if (dir.fd != root.fd) dir.close(); var it = dir.iterate(); while (try it.next()) |entry| { switch (entry.kind) { .Directory => { const sub_dir = try dir.openDir(entry.name, .{ .iterate = true }); try stack.append(sub_dir); }, else => { res.unread += @boolToInt(mem.endsWith(u8, entry.name, ",")); res.read += @boolToInt(mem.endsWith(u8, entry.name, "S")); }, } } } return res; }
src/producer/mail.zig
const std = @import("std"); const glfw = @import("glfw"); const gpu = @import("gpu"); const App = @import("app"); const Engine = @import("Engine.zig"); const structs = @import("structs.zig"); const enums = @import("enums.zig"); const util = @import("util.zig"); const c = @import("c.zig").c; pub const CoreGlfw = struct { window: glfw.Window, backend_type: gpu.Adapter.BackendType, user_ptr: UserPtr = undefined, const UserPtr = struct { app: *App, engine: *Engine, }; pub fn init(allocator: std.mem.Allocator, engine: *Engine) !CoreGlfw { const options = engine.options; const backend_type = try util.detectBackendType(allocator); glfw.setErrorCallback(CoreGlfw.errorCallback); try glfw.init(.{}); // Create the test window and discover adapters using it (esp. for OpenGL) var hints = util.glfwWindowHintsForBackend(backend_type); hints.cocoa_retina_framebuffer = true; const window = try glfw.Window.create( options.width, options.height, options.title, null, null, hints, ); return CoreGlfw{ .window = window, .backend_type = backend_type, }; } fn initCallback(self: *CoreGlfw, app: *App, engine: *Engine) void { self.user_ptr = UserPtr{ .app = app, .engine = engine, }; self.window.setUserPointer(&self.user_ptr); } pub fn setShouldClose(self: *CoreGlfw, value: bool) void { self.window.setShouldClose(value); } pub fn getFramebufferSize(self: *CoreGlfw) !structs.Size { const size = try self.window.getFramebufferSize(); return @bitCast(structs.Size, size); } pub fn setSizeLimits(self: *CoreGlfw, min: structs.SizeOptional, max: structs.SizeOptional) !void { try self.window.setSizeLimits( @bitCast(glfw.Window.SizeOptional, min), @bitCast(glfw.Window.SizeOptional, max), ); } pub fn setKeyCallback(self: *CoreGlfw, comptime cb: fn (app: *App, engine: *Engine, key: enums.Key, action: enums.Action) void) void { const callback = struct { fn callback(window: glfw.Window, key: glfw.Key, scancode: i32, action: glfw.Action, mods: glfw.Mods) void { const usrptr = window.getUserPointer(UserPtr) orelse unreachable; cb(usrptr.app, usrptr.engine, CoreGlfw.toMachKey(key), CoreGlfw.toMachAction(action)); _ = scancode; _ = mods; } }.callback; self.window.setKeyCallback(callback); } fn toMachAction(action: glfw.Action) enums.Action { return switch (action) { .press => .press, .release => .release, .repeat => .repeat, }; } fn toMachKey(key: glfw.Key) enums.Key { return switch (key) { .a => .a, .b => .b, .c => .c, .d => .d, .e => .e, .f => .f, .g => .g, .h => .h, .i => .i, .j => .j, .k => .k, .l => .l, .m => .m, .n => .n, .o => .o, .p => .p, .q => .q, .r => .r, .s => .s, .t => .t, .u => .u, .v => .v, .w => .w, .x => .x, .y => .y, .z => .z, .zero => .zero, .one => .one, .two => .two, .three => .three, .four => .four, .five => .five, .six => .six, .seven => .seven, .eight => .eight, .nine => .nine, .F1 => .f1, .F2 => .f2, .F3 => .f3, .F4 => .f4, .F5 => .f5, .F6 => .f6, .F7 => .f7, .F8 => .f8, .F9 => .f9, .F10 => .f10, .F11 => .f11, .F12 => .f12, .F13 => .f13, .F14 => .f14, .F15 => .f15, .F16 => .f16, .F17 => .f17, .F18 => .f18, .F19 => .f19, .F20 => .f20, .F21 => .f21, .F22 => .f22, .F23 => .f23, .F24 => .f24, .F25 => .f25, .kp_divide => .kp_divide, .kp_multiply => .kp_multiply, .kp_subtract => .kp_subtract, .kp_add => .kp_add, .kp_0 => .kp_0, .kp_1 => .kp_1, .kp_2 => .kp_2, .kp_3 => .kp_3, .kp_4 => .kp_4, .kp_5 => .kp_5, .kp_6 => .kp_6, .kp_7 => .kp_7, .kp_8 => .kp_8, .kp_9 => .kp_9, .kp_decimal => .kp_decimal, .kp_equal => .kp_equal, .kp_enter => .kp_enter, .enter => .enter, .escape => .escape, .tab => .tab, .left_shift => .left_shift, .right_shift => .right_shift, .left_control => .left_control, .right_control => .right_control, .left_alt => .left_alt, .right_alt => .right_alt, .left_super => .left_super, .right_super => .right_super, .menu => .menu, .num_lock => .num_lock, .caps_lock => .caps_lock, .print_screen => .print, .scroll_lock => .scroll_lock, .pause => .pause, .delete => .delete, .home => .home, .end => .end, .page_up => .page_up, .page_down => .page_down, .insert => .insert, .left => .left, .right => .right, .up => .up, .down => .down, .backspace => .backspace, .space => .space, .minus => .minus, .equal => .equal, .left_bracket => .left_bracket, .right_bracket => .right_bracket, .backslash => .backslash, .semicolon => .semicolon, .apostrophe => .apostrophe, .comma => .comma, .period => .period, .slash => .slash, .grave_accent => .grave, .world_1 => .unknown, .world_2 => .unknown, .unknown => .unknown, }; } /// Default GLFW error handling callback fn errorCallback(error_code: glfw.Error, description: [:0]const u8) void { std.debug.print("glfw: {}: {s}\n", .{ error_code, description }); } }; pub const GpuDriverNative = struct { native_instance: gpu.NativeInstance, pub fn init(_: std.mem.Allocator, engine: *Engine) !GpuDriverNative { const options = engine.options; const window = engine.core.internal.window; const backend_type = engine.core.internal.backend_type; const backend_procs = c.machDawnNativeGetProcs(); c.dawnProcSetProcs(backend_procs); const instance = c.machDawnNativeInstance_init(); var native_instance = gpu.NativeInstance.wrap(c.machDawnNativeInstance_get(instance).?); // Discover e.g. OpenGL adapters. try util.discoverAdapters(instance, window, backend_type); // Request an adapter. // // TODO: It would be nice if we could use gpu_interface.waitForAdapter here, however the webgpu.h // API does not yet have a way to specify what type of backend you want (vulkan, opengl, etc.) // In theory, I suppose we shouldn't need to and Dawn should just pick the best adapter - but in // practice if Vulkan is not supported today waitForAdapter/requestAdapter merely generates an error. // // const gpu_interface = native_instance.interface(); // const backend_adapter = switch (gpu_interface.waitForAdapter(&.{ // .power_preference = .high_performance, // })) { // .adapter => |v| v, // .err => |err| { // std.debug.print("mach: failed to get adapter: error={} {s}\n", .{ err.code, err.message }); // std.process.exit(1); // }, // }; const adapters = c.machDawnNativeInstance_getAdapters(instance); var dawn_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); const found_backend_type = @intToEnum(gpu.Adapter.BackendType, c.machDawnNativeAdapterProperties_getBackendType(properties)); if (found_backend_type == backend_type) { dawn_adapter = adapter; break; } } if (dawn_adapter == null) { std.debug.print("mach: no matching adapter found for {s}", .{@tagName(backend_type)}); std.debug.print("-> maybe try GPU_BACKEND=opengl ?\n", .{}); std.process.exit(1); } std.debug.assert(dawn_adapter != null); const backend_adapter = gpu.NativeInstance.fromWGPUAdapter(c.machDawnNativeAdapter_get(dawn_adapter.?).?); // Print which adapter we are going to use. const props = backend_adapter.properties; std.debug.print("mach: found {s} backend on {s} adapter: {s}, {s}\n", .{ gpu.Adapter.backendTypeName(props.backend_type), gpu.Adapter.typeName(props.adapter_type), props.name, props.driver_description, }); const device = switch (backend_adapter.waitForDevice(&.{ .required_features = options.required_features, .required_limits = options.required_limits, })) { .device => |v| v, .err => |err| { // TODO: return a proper error type std.debug.print("mach: failed to get device: error={} {s}\n", .{ err.code, err.message }); std.process.exit(1); }, }; var framebuffer_size = try window.getFramebufferSize(); // If targeting OpenGL, we can't use the newer WGPUSurface API. Instead, we need to use the // older Dawn-specific API. https://bugs.chromium.org/p/dawn/issues/detail?id=269&q=surface&can=2 const use_legacy_api = backend_type == .opengl or backend_type == .opengles; var descriptor: gpu.SwapChain.Descriptor = undefined; var swap_chain: ?gpu.SwapChain = null; var swap_chain_format: gpu.Texture.Format = undefined; var surface: ?gpu.Surface = null; if (!use_legacy_api) { swap_chain_format = .bgra8_unorm; descriptor = .{ .label = "basic swap chain", .usage = .{ .render_attachment = true }, .format = swap_chain_format, .width = framebuffer_size.width, .height = framebuffer_size.height, .present_mode = switch (options.vsync) { .none => .immediate, .double => .fifo, .triple => .mailbox, }, .implementation = 0, }; surface = util.createSurfaceForWindow( &native_instance, window, comptime util.detectGLFWOptions(), ); } else { const binding = c.machUtilsCreateBinding(@enumToInt(backend_type), @ptrCast(*c.GLFWwindow, window.handle), @ptrCast(c.WGPUDevice, device.ptr)); if (binding == null) { @panic("failed to create Dawn backend binding"); } descriptor = std.mem.zeroes(gpu.SwapChain.Descriptor); descriptor.implementation = c.machUtilsBackendBinding_getSwapChainImplementation(binding); swap_chain = device.nativeCreateSwapChain(null, &descriptor); swap_chain_format = @intToEnum(gpu.Texture.Format, @intCast(u32, c.machUtilsBackendBinding_getPreferredSwapChainTextureFormat(binding))); swap_chain.?.configure( swap_chain_format, .{ .render_attachment = true }, framebuffer_size.width, framebuffer_size.height, ); } device.setUncapturedErrorCallback(&util.printUnhandledErrorCallback); engine.gpu_driver.device = device; engine.gpu_driver.backend_type = backend_type; engine.gpu_driver.surface = surface; engine.gpu_driver.swap_chain = swap_chain; engine.gpu_driver.swap_chain_format = swap_chain_format; engine.gpu_driver.current_desc = descriptor; engine.gpu_driver.target_desc = descriptor; return GpuDriverNative{ .native_instance = native_instance, }; } }; // TODO: check signatures comptime { if (!@hasDecl(App, "init")) @compileError("App must export 'pub fn init(app: *App, engine: *mach.Engine) !void'"); if (!@hasDecl(App, "deinit")) @compileError("App must export 'pub fn deinit(app: *App, engine: *mach.Engine) void'"); if (!@hasDecl(App, "update")) @compileError("App must export 'pub fn update(app: *App, engine: *mach.Engine) !bool'"); } pub fn main() !void { var gpa = std.heap.GeneralPurposeAllocator(.{}){}; const allocator = gpa.allocator(); const options = if (@hasDecl(App, "options")) App.options else structs.Options{}; var engine = try Engine.init(allocator, options); var app: App = undefined; try app.init(&engine); defer app.deinit(&engine); // Glfw specific: initialize the user pointer used in callbacks engine.core.internal.initCallback(&app, &engine); const window = engine.core.internal.window; while (!window.shouldClose()) { try glfw.pollEvents(); engine.delta_time_ns = engine.timer.lap(); engine.delta_time = @intToFloat(f64, engine.delta_time_ns) / @intToFloat(f64, std.time.ns_per_s); var framebuffer_size = try window.getFramebufferSize(); engine.gpu_driver.target_desc.width = framebuffer_size.width; engine.gpu_driver.target_desc.height = framebuffer_size.height; if (engine.gpu_driver.swap_chain == null or !engine.gpu_driver.current_desc.equal(&engine.gpu_driver.target_desc)) { const use_legacy_api = engine.gpu_driver.surface == null; if (!use_legacy_api) { engine.gpu_driver.swap_chain = engine.gpu_driver.device.nativeCreateSwapChain(engine.gpu_driver.surface, &engine.gpu_driver.target_desc); } else engine.gpu_driver.swap_chain.?.configure( engine.gpu_driver.swap_chain_format, .{ .render_attachment = true }, engine.gpu_driver.target_desc.width, engine.gpu_driver.target_desc.height, ); if (@hasDecl(App, "resize")) { try app.resize(&engine, engine.gpu_driver.target_desc.width, engine.gpu_driver.target_desc.height); } engine.gpu_driver.current_desc = engine.gpu_driver.target_desc; } const success = try app.update(&engine); if (!success) break; } }
src/native.zig
usingnamespace std.build; const std = @import("std"); const ssl = @import(pkgs.ssl.path); const pkgs = @import("deps.zig").pkgs; const clap = .{ .name = "clap", .path = "libs/zig-clap/clap.zig", }; const version = .{ .name = "version", .path = "libs/version/src/main.zig", .dependencies = &[_]Pkg{ .{ .name = "mecha", .path = "libs/mecha/mecha.zig", }, }, }; const tar = .{ .name = "tar", .path = "libs/tar/src/main.zig", }; const zzz = .{ .name = "zzz", .path = "libs/zzz/src/main.zig", }; const glob = .{ .name = "glob", .path = "libs/glob/src/main.zig", }; const hzzp = .{ .name = "hzzp", .path = "libs/hzzp/src/main.zig", }; const zfetch = .{ .name = "zfetch", .path = "libs/zfetch/src/main.zig", .dependencies = &[_]std.build.Pkg{ hzzp, uri, .{ .name = "network", .path = "libs/zig-network/network.zig", }, .{ .name = "iguanaTLS", .path = "libs/iguanaTLS/src/main.zig", }, }, }; const uri = .{ .name = "uri", .path = "libs/zig-uri/uri.zig", }; const known_folders = .{ .name = "known-folders", .path = "libs/known-folders/known-folders.zig", }; fn addAllPkgs(lib: *LibExeObjStep) void { lib.addPackage(clap); lib.addPackage(version); lib.addPackage(tar); lib.addPackage(zzz); lib.addPackage(glob); lib.addPackage(zfetch); lib.addPackage(uri); lib.addPackage(known_folders); } pub fn build(b: *Builder) !void { var target = b.standardTargetOptions(.{}); if (target.abi == null) { target.abi = switch (std.builtin.os.tag) { .windows => .gnu, else => .musl, }; } const mode = b.standardReleaseOptions(); const bootstrap = b.option(bool, "bootstrap", "bootstrapping with just the zig compiler"); const repository = b.option([]const u8, "repo", "default package index (default is astrolabe.pm)"); const gyro = b.addExecutable("gyro", "src/main.zig"); gyro.setTarget(target); gyro.setBuildMode(mode); if (bootstrap) |bs| { if (bs) { addAllPkgs(gyro); } else { pkgs.addAllTo(gyro); } } else { pkgs.addAllTo(gyro); } gyro.addBuildOption([]const u8, "default_repo", repository orelse "astrolabe.pm"); gyro.install(); const tests = b.addTest("src/main.zig"); tests.setBuildMode(mode); addAllPkgs(tests); tests.addBuildOption([]const u8, "default_repo", repository orelse "astrolabe.pm"); tests.step.dependOn(b.getInstallStep()); const test_step = b.step("test", "Run tests"); test_step.dependOn(&tests.step); }
build.zig
const std = @import("std.zig"); const builtin = @import("builtin"); const root = @import("root"); const c = std.c; const math = std.math; const assert = std.debug.assert; const os = std.os; const fs = std.fs; const mem = std.mem; const meta = std.meta; const trait = meta.trait; const File = std.fs.File; pub const Mode = enum { /// I/O operates normally, waiting for the operating system syscalls to complete. blocking, /// I/O functions are generated async and rely on a global event loop. Event-based I/O. evented, }; /// The application's chosen I/O mode. This defaults to `Mode.blocking` but can be overridden /// by `root.event_loop`. pub const mode: Mode = if (@hasDecl(root, "io_mode")) root.io_mode else if (@hasDecl(root, "event_loop")) Mode.evented else Mode.blocking; pub const is_async = mode != .blocking; fn getStdOutHandle() os.fd_t { if (builtin.os.tag == .windows) { return os.windows.peb().ProcessParameters.hStdOutput; } if (@hasDecl(root, "os") and @hasDecl(root.os, "io") and @hasDecl(root.os.io, "getStdOutHandle")) { return root.os.io.getStdOutHandle(); } return os.STDOUT_FILENO; } pub fn getStdOut() File { return File{ .handle = getStdOutHandle(), .io_mode = .blocking, }; } fn getStdErrHandle() os.fd_t { if (builtin.os.tag == .windows) { return os.windows.peb().ProcessParameters.hStdError; } if (@hasDecl(root, "os") and @hasDecl(root.os, "io") and @hasDecl(root.os.io, "getStdErrHandle")) { return root.os.io.getStdErrHandle(); } return os.STDERR_FILENO; } pub fn getStdErr() File { return File{ .handle = getStdErrHandle(), .io_mode = .blocking, .async_block_allowed = File.async_block_allowed_yes, }; } fn getStdInHandle() os.fd_t { if (builtin.os.tag == .windows) { return os.windows.peb().ProcessParameters.hStdInput; } if (@hasDecl(root, "os") and @hasDecl(root.os, "io") and @hasDecl(root.os.io, "getStdInHandle")) { return root.os.io.getStdInHandle(); } return os.STDIN_FILENO; } pub fn getStdIn() File { return File{ .handle = getStdInHandle(), .io_mode = .blocking, }; } pub const InStream = @import("io/in_stream.zig").InStream; pub const OutStream = @import("io/out_stream.zig").OutStream; pub const SeekableStream = @import("io/seekable_stream.zig").SeekableStream; pub const BufferedOutStream = @import("io/buffered_out_stream.zig").BufferedOutStream; pub const bufferedOutStream = @import("io/buffered_out_stream.zig").bufferedOutStream; pub const BufferedInStream = @import("io/buffered_in_stream.zig").BufferedInStream; pub const bufferedInStream = @import("io/buffered_in_stream.zig").bufferedInStream; pub const PeekStream = @import("io/peek_stream.zig").PeekStream; pub const peekStream = @import("io/peek_stream.zig").peekStream; pub const FixedBufferStream = @import("io/fixed_buffer_stream.zig").FixedBufferStream; pub const fixedBufferStream = @import("io/fixed_buffer_stream.zig").fixedBufferStream; pub const COutStream = @import("io/c_out_stream.zig").COutStream; pub const cOutStream = @import("io/c_out_stream.zig").cOutStream; pub const CountingOutStream = @import("io/counting_out_stream.zig").CountingOutStream; pub const countingOutStream = @import("io/counting_out_stream.zig").countingOutStream; pub const BitInStream = @import("io/bit_in_stream.zig").BitInStream; pub const bitInStream = @import("io/bit_in_stream.zig").bitInStream; pub const BitOutStream = @import("io/bit_out_stream.zig").BitOutStream; pub const bitOutStream = @import("io/bit_out_stream.zig").bitOutStream; pub const Packing = @import("io/serialization.zig").Packing; pub const Serializer = @import("io/serialization.zig").Serializer; pub const serializer = @import("io/serialization.zig").serializer; pub const Deserializer = @import("io/serialization.zig").Deserializer; pub const deserializer = @import("io/serialization.zig").deserializer; pub const BufferedAtomicFile = @import("io/buffered_atomic_file.zig").BufferedAtomicFile; pub const StreamSource = @import("io/stream_source.zig").StreamSource; /// An OutStream that doesn't write to anything. pub const null_out_stream = @as(NullOutStream, .{ .context = {} }); const NullOutStream = OutStream(void, error{}, dummyWrite); fn dummyWrite(context: void, data: []const u8) error{}!usize { return data.len; } test "null_out_stream" { null_out_stream.writeAll("yay" ** 10) catch |err| switch (err) {}; } test "" { _ = @import("io/bit_in_stream.zig"); _ = @import("io/bit_out_stream.zig"); _ = @import("io/buffered_atomic_file.zig"); _ = @import("io/buffered_in_stream.zig"); _ = @import("io/buffered_out_stream.zig"); _ = @import("io/c_out_stream.zig"); _ = @import("io/counting_out_stream.zig"); _ = @import("io/fixed_buffer_stream.zig"); _ = @import("io/in_stream.zig"); _ = @import("io/out_stream.zig"); _ = @import("io/peek_stream.zig"); _ = @import("io/seekable_stream.zig"); _ = @import("io/serialization.zig"); _ = @import("io/stream_source.zig"); _ = @import("io/test.zig"); } pub const writeFile = @compileError("deprecated: use std.fs.Dir.writeFile with math.maxInt(usize)"); pub const readFileAlloc = @compileError("deprecated: use std.fs.Dir.readFileAlloc");
lib/std/io.zig
const std = @import("std"); const io = std.io; const builtin = @import("builtin"); pub const io_mode: io.Mode = builtin.test_io_mode; var log_err_count: usize = 0; pub fn main() anyerror!void { const test_fn_list = builtin.test_functions; var ok_count: usize = 0; var skip_count: usize = 0; var progress = std.Progress{}; const root_node = progress.start("Test", test_fn_list.len) catch |err| switch (err) { // TODO still run tests in this case error.TimerUnsupported => @panic("timer unsupported"), }; var async_frame_buffer: []align(std.Target.stack_align) u8 = undefined; // TODO this is on the next line (using `undefined` above) because otherwise zig incorrectly // ignores the alignment of the slice. async_frame_buffer = &[_]u8{}; var leaks: usize = 0; for (test_fn_list) |test_fn, i| { std.testing.allocator_instance = .{}; defer { if (std.testing.allocator_instance.deinit()) { leaks += 1; } } std.testing.log_level = .warn; var test_node = root_node.start(test_fn.name, null); test_node.activate(); progress.refresh(); if (progress.terminal == null) { std.debug.print("{}/{} {}... ", .{ i + 1, test_fn_list.len, test_fn.name }); } const result = if (test_fn.async_frame_size) |size| switch (io_mode) { .evented => blk: { if (async_frame_buffer.len < size) { std.heap.page_allocator.free(async_frame_buffer); async_frame_buffer = try std.heap.page_allocator.alignedAlloc(u8, std.Target.stack_align, size); } const casted_fn = @ptrCast(fn () callconv(.Async) anyerror!void, test_fn.func); break :blk await @asyncCall(async_frame_buffer, {}, casted_fn, .{}); }, .blocking => { skip_count += 1; test_node.end(); progress.log("{}...SKIP (async test)\n", .{test_fn.name}); if (progress.terminal == null) std.debug.print("SKIP (async test)\n", .{}); continue; }, } else test_fn.func(); if (result) |_| { ok_count += 1; test_node.end(); if (progress.terminal == null) std.debug.print("OK\n", .{}); } else |err| switch (err) { error.SkipZigTest => { skip_count += 1; test_node.end(); progress.log("{}...SKIP\n", .{test_fn.name}); if (progress.terminal == null) std.debug.print("SKIP\n", .{}); }, else => { progress.log("", .{}); return err; }, } } root_node.end(); if (ok_count == test_fn_list.len) { std.debug.print("All {} tests passed.\n", .{ok_count}); } else { std.debug.print("{} passed; {} skipped.\n", .{ ok_count, skip_count }); } if (log_err_count != 0) { std.debug.print("{} errors were logged.\n", .{log_err_count}); } if (leaks != 0) { std.debug.print("{} tests leaked memory.\n", .{ok_count}); } if (leaks != 0 or log_err_count != 0) { std.process.exit(1); } } pub fn log( comptime message_level: std.log.Level, comptime scope: @Type(.EnumLiteral), comptime format: []const u8, args: anytype, ) void { if (@enumToInt(message_level) <= @enumToInt(std.log.Level.err)) { log_err_count += 1; } if (@enumToInt(message_level) <= @enumToInt(std.testing.log_level)) { std.debug.print("[{}] ({}): " ++ format, .{ @tagName(scope), @tagName(message_level) } ++ args); } }
lib/std/special/test_runner.zig
const std = @import("std"); const debug = std.debug; const math = std.math; const mem = std.mem; const testing = std.testing; /// Tests that an iterator returns all the items in the `expected` /// slice, and no more. pub fn test_it(_it: anytype, hint: LengthHint, expected: anytype) void { if (@hasDecl(@TypeOf(_it), "len_hint")) testing.expectEqual(hint, _it.len_hint()); var it = _it; for (expected) |item| testing.expectEqual(item, it.next().?); testing.expect(it.next() == null); } fn ReturnType(comptime F: type) type { return @typeInfo(F).Fn.return_type.?; } fn ReturnTypeOpt(comptime F: type) type { return @typeInfo(ReturnType(F)).Optional.child; } /// Get the type of the items an iterator iterates over. pub fn Result(comptime It: type) type { return ReturnTypeOpt(@TypeOf(It.next)); } pub const LengthHint = struct { min: usize = 0, max: ?usize = null, pub fn len(hint: LengthHint) ?usize { const max = hint.max orelse return null; return if (hint.min == max) max else null; } pub fn add(a: LengthHint, b: LengthHint) LengthHint { return .{ .min = a.min + b.min, .max = blk: { const a_max = a.max orelse break :blk null; const b_max = b.max orelse break :blk null; break :blk a_max + b_max; }, }; } }; /// You see, we don't have ufc and an iterator interface using free functions /// is kinda painful and hard to read: /// ``` /// const it = filter(span("aaa"), fn(a:u8){ return a == 0: }); /// ``` /// This is an attempt at emulating ufc by having all iterators have one function called /// `call`. With that function, you could build iterators like this: /// ``` /// const it = span("aaa") /// .call(filter, .{ fn(a: u8){ return a == 0; } }); /// ``` pub fn call_method( it: anytype, func: anytype, args: anytype, ) @TypeOf(@call(.{}, func, .{@TypeOf(it.*){}} ++ @as(@TypeOf(args), undefined))) { return @call(.{}, func, .{it.*} ++ args); } ////////////////////////////////////////////////////////// // The functions creates iterators from other iterators // ////////////////////////////////////////////////////////// pub fn Chain(comptime First: type, comptime Second: type) type { return struct { first: First = First{}, second: Second = Second{}, pub fn next(it: *@This()) ?Result(First) { return it.first.next() orelse it.second.next(); } pub fn len_hint(it: @This()) LengthHint { if (!@hasDecl(First, "len_hint") or !@hasDecl(Second, "len_hint")) return .{}; return LengthHint.add( it.first.len_hint(), it.second.len_hint(), ); } pub const call = call_method; }; } /// Creates an iterator that first iterates over all items in `first` after /// which it iterates over all elements in `second`. pub fn chain(first: anytype, second: anytype) Chain(@TypeOf(first), @TypeOf(second)) { return .{ .first = first, .second = second }; } test "chain" { const abc = span("abc"); const def = span("def"); const non = span(""); test_it(chain(abc, def), .{ .min = 6, .max = 6 }, "abcdef"); test_it(chain(non, def), .{ .min = 3, .max = 3 }, "def"); test_it(chain(abc, non), .{ .min = 3, .max = 3 }, "abc"); test_it(chain(non, non), .{ .min = 0, .max = 0 }, ""); } pub fn Deref(comptime Child: type) type { return Map(void, Child, @typeInfo(Result(Child)).Pointer.child); } /// Creates an iterator which derefs all of the items it iterates over. pub fn deref(it: anytype) Deref(@TypeOf(it)) { const It = @TypeOf(it); return map(it, struct { fn transform(ptr: Result(It)) Result(Deref(It)) { return ptr.*; } }.transform); } test "deref" { test_it(span_by_ref("abcd").call(deref, .{}), .{ .min = 4, .max = 4 }, "abcd"); } pub fn Enumerate(comptime I: type, comptime Child: type) type { return struct { index: I = 0, child: Child = Child{}, pub const Res = struct { index: I, item: Result(Child), }; pub fn next(it: *@This()) ?Res { const item = it.child.next() orelse return null; const index = it.index; it.index += 1; return Res{ .index = index, .item = item }; } pub fn len_hint(it: @This()) LengthHint { if (!@hasDecl(Child, "len_hint")) return .{}; return it.child.len_hint(); } pub const call = call_method; }; } /// Same as `enumerate_ex` but with `usize` passed as the second parameter. pub fn enumerate(it: anytype) Enumerate(usize, @TypeOf(it)) { return enumerate_ex(it, usize); } /// Creates an iterator that gives the item index as well as the item. pub fn enumerate_ex(it: anytype, comptime I: type) Enumerate(I, @TypeOf(it)) { return .{ .child = it }; } test "enumerate" { var it = span("ab") // .call(enumerate, .{}); testing.expectEqual(LengthHint{ .min = 2, .max = 2 }, it.len_hint()); var i: usize = 0; while (it.next()) |item| : (i += 1) { testing.expectEqual(@as(usize, i), item.index); testing.expectEqual(@as(u8, "ab"[i]), item.item); } } pub fn ErrInner(comptime Child: type) type { const err_union = @typeInfo(ReturnType(@TypeOf(Child.next))).ErrorUnion; const Error = err_union.error_set; const Res = @typeInfo(err_union.payload).Optional.child; return struct { child: Child = Child{}, pub fn next(it: *@This()) ?(Error!Res) { const res = it.child.next() catch |err| return err; return res orelse return null; } pub fn len_hint(it: @This()) LengthHint { if (!@hasDecl(Child, "len_hint")) return .{}; return it.child.len_hint(); } pub const call = call_method; }; } /// Takes an iterator that returns `Error!?T` and makes it into an iterator /// take returns `?(Error!T)`. pub fn err_inner(it: anytype) ErrInner(@TypeOf(it)) { return .{ .child = it }; } test "err_inner" { const Dummy = struct { const Error = error{A}; num: usize = 0, fn next(it: *@This()) Error!?u8 { defer it.num += 1; switch (it.num) { 0 => return 0, 1 => return error.A, else => return null, } } }; const i = err_inner(Dummy{}); test_it(i, .{}, &[_](Dummy.Error!u8){ 0, error.A }); } pub fn FilterMap(comptime Context: type, comptime Child: type, comptime T: type) type { return struct { child: Child = Child{}, ctx: Context = undefined, transform: fn (Context, Result(Child)) ?T = undefined, pub fn next(it: *@This()) ?T { while (it.child.next()) |item| { if (it.transform(it.ctx, item)) |res| return res; } return null; } pub fn len_hint(it: @This()) LengthHint { if (!@hasDecl(Child, "len_hint")) return .{}; return .{ .min = 0, .max = it.child.len_hint().max }; } pub const call = call_method; }; } /// Same as `filter_map_ex` but requires no context. pub fn filter_map( it: anytype, transform: anytype, ) FilterMap(void, @TypeOf(it), ReturnTypeOpt(@TypeOf(transform))) { const Expect = fn (Result(@TypeOf(it))) ReturnType(@TypeOf(transform)); const Transform = fn (void, Result(@TypeOf(it))) ReturnType(@TypeOf(transform)); return filter_map_ex(it, {}, @ptrCast(Transform, @as(Expect, transform))); } /// Creates an iterator that transforms and filters out items the `transform` function. pub fn filter_map_ex( it: anytype, ctx: anytype, transform: anytype, ) FilterMap(@TypeOf(ctx), @TypeOf(it), ReturnTypeOpt(@TypeOf(transform))) { return .{ .child = it, .ctx = ctx, .transform = transform }; } test "filter_map" { const F = struct { fn even_double(i: u8) ?u16 { if (i % 2 != 0) return null; return i * 2; } }; const i = range(u8, 0, 10) // .call(filter_map, .{F.even_double}); test_it(i, .{ .min = 0, .max = 10 }, &[_]u16{ 0, 4, 8, 12, 16 }); } pub fn Filter(comptime Context: type, comptime Child: type) type { return struct { child: Child = Child{}, ctx: Context = undefined, pred: fn (Context, Result(Child)) bool = undefined, pub fn next(it: *@This()) ?Result(Child) { while (it.child.next()) |item| { if (it.pred(it.ctx, item)) return item; } return null; } pub fn len_hint(it: @This()) LengthHint { if (!@hasDecl(Child, "len_hint")) return .{}; return .{ .min = 0, .max = it.child.len_hint().max }; } pub const call = call_method; }; } /// Same as `filter_ex` but requires no context. pub fn filter( it: anytype, pred: fn (Result(@TypeOf(it))) bool, ) Filter(void, @TypeOf(it)) { return filter_ex(it, {}, @ptrCast(fn (void, Result(@TypeOf(it))) bool, pred)); } /// Creates an iterator that filters out items that does not match /// the predicate `pred`. pub fn filter_ex( it: anytype, ctx: anytype, pred: fn (@TypeOf(ctx), Result(@TypeOf(it))) bool, ) Filter(@TypeOf(ctx), @TypeOf(it)) { return .{ .child = it, .ctx = ctx, .pred = pred }; } test "filter" { const s1 = span("a1b2"); const s2 = span("aaabb"); test_it(s1.call(filter, .{std.ascii.isDigit}), .{ .min = 0, .max = 4 }, "12"); test_it(s1.call(filter, .{std.ascii.isAlpha}), .{ .min = 0, .max = 4 }, "ab"); test_it(s2.call(filter, .{std.ascii.isDigit}), .{ .min = 0, .max = 5 }, ""); } pub fn InterLeave(comptime First: type, comptime Second: type) type { return struct { first: First = First{}, second: Second = Second{}, flag: enum { first, second } = .first, pub fn next(it: *@This()) ?Result(First) { defer it.flag = if (it.flag == .first) .second else .first; return switch (it.flag) { .first => it.first.next() orelse it.second.next(), .second => it.second.next() orelse it.first.next(), }; } pub fn len_hint(it: @This()) LengthHint { if (!@hasDecl(First, "len_hint") or !@hasDecl(Second, "len_hint")) return .{}; return LengthHint.add( it.first.len_hint(), it.second.len_hint(), ); } pub const call = call_method; }; } /// Creates an iterator switches between calling `first.next` and `second.next`. pub fn interleave( first: anytype, second: anytype, ) InterLeave(@TypeOf(first), @TypeOf(second)) { return .{ .first = first, .second = second }; } test "interleave" { const abc = span("abc"); const def = span("def"); const non = span(""); test_it(interleave(abc, def), .{ .min = 6, .max = 6 }, "adbecf"); test_it(interleave(non, def), .{ .min = 3, .max = 3 }, "def"); test_it(interleave(abc, non), .{ .min = 3, .max = 3 }, "abc"); test_it(interleave(non, non), .{ .min = 0, .max = 0 }, ""); } pub fn Map(comptime Context: type, comptime Child: type, comptime T: type) type { return struct { child: Child = Child{}, ctx: Context = undefined, transform: fn (Context, Result(Child)) T = undefined, pub fn next(it: *@This()) ?T { return it.transform(it.ctx, it.child.next() orelse return null); } pub fn len_hint(it: @This()) LengthHint { if (!@hasDecl(Child, "len_hint")) return .{}; return it.child.len_hint(); } pub const call = call_method; }; } /// Same as `map_ex` but requires no context. pub fn map( it: anytype, transform: anytype, ) Map(void, @TypeOf(it), ReturnType(@TypeOf(transform))) { const Expect = fn (Result(@TypeOf(it))) ReturnType(@TypeOf(transform)); const Transform = fn (void, Result(@TypeOf(it))) ReturnType(@TypeOf(transform)); return map_ex(it, {}, @ptrCast(Transform, @as(Expect, transform))); } /// Creates an iterator that transforms all items using the `transform` function. pub fn map_ex( it: anytype, ctx: anytype, transform: anytype, ) Map(@TypeOf(ctx), @TypeOf(it), ReturnType(@TypeOf(transform))) { return .{ .child = it, .ctx = ctx, .transform = transform }; } test "map" { const m1 = span("abcd") // .call(map, .{std.ascii.toUpper}); test_it(m1, .{ .min = 4, .max = 4 }, "ABCD"); const m2 = span("") // .call(map, .{std.ascii.toUpper}); test_it(m2, .{ .min = 0, .max = 0 }, ""); } pub fn SlidingWindow(comptime Child: type, comptime window: usize) type { return struct { prev: ?[window]T = null, child: Child = Child{}, const T = Result(Child); pub fn next(it: *@This()) ?[window]T { if (it.prev) |*prev| { mem.copy(T, prev, prev[1..]); prev[window - 1] = it.child.next() orelse return null; return it.prev; } else { it.prev = [_]Result(Child){undefined} ** window; for (it.prev.?) |*item| item.* = it.child.next() orelse return null; return it.prev; } } pub fn len_hint(it: @This()) LengthHint { if (!@hasDecl(Child, "len_hint")) return .{}; const child = it.child.len_hint(); return .{ .min = math.sub(usize, child.min, window - 1) catch 0, .max = blk: { const max = child.max orelse break :blk null; break :blk math.sub(usize, max, window - 1) catch 0; }, }; } pub const call = call_method; }; } /// Creates an iterator that iterates over the provided iterator and /// returns a window into the elements of the iterator, and slides /// that window along: /// ``` /// span("abcde") /// .call(sliding_window, {3}) = "abc" /// "bcd" /// "cde" /// ``` pub fn sliding_window(it: anytype, comptime window: usize) SlidingWindow(@TypeOf(it), window) { return .{ .child = it }; } test "sliding_window" { const s1 = span("abcd") // .call(sliding_window, .{2}); test_it(s1, .{ .min = 3, .max = 3 }, [_][2]u8{ "ab".*, "bc".*, "cd".* }); const s2 = span("abcd") // .call(sliding_window, .{3}); test_it(s2, .{ .min = 2, .max = 2 }, [_][3]u8{ "abc".*, "bcd".* }); } pub fn Range(comptime T: type) type { return struct { start: T = 0, end: T = 0, step: T = 1, pub fn next(it: *@This()) ?T { if (it.end <= it.start) return null; defer it.start += it.step; return it.start; } pub fn len_hint(it: @This()) LengthHint { const diff = math.sub(T, it.end, it.start) catch 0; const len = diff / it.step + @boolToInt(diff % it.step != 0); return .{ .min = len, .max = len }; } pub const call = call_method; }; } /// Same as `range_ex` with 1 passed to the `step` paramter. pub fn range(comptime T: type, start: T, end: T) Range(T) { return range_ex(T, start, end, 1); } /// Creates an iterator that iterates from `start` to `end` exclusively /// with a step size of `step`. pub fn range_ex(comptime T: type, start: T, end: T, step: T) Range(T) { debug.assert(start <= end and step != 0); return .{ .start = start, .end = end, .step = step }; } test "range" { test_it(range(u8, 'a', 'd'), .{ .min = 3, .max = 3 }, "abc"); test_it(range_ex(u8, 'a', 'd', 2), .{ .min = 2, .max = 2 }, "ac"); test_it(range_ex(u8, 'a', 'd', 3), .{ .min = 1, .max = 1 }, "a"); } pub fn Repeat(comptime Child: type) type { return struct { reset: Child = Child{}, curr: Child = Child{}, pub fn next(it: *@This()) ?Result(Child) { if (it.curr.next()) |res| return res; it.curr = it.reset; return it.curr.next(); } pub fn len_hint(it: @This()) LengthHint { if (!@hasDecl(Child, "len_hint")) return .{}; const child = it.reset.len_hint(); const min = child.min; const max = child.max orelse std.math.maxInt(usize); return .{ .min = min, .max = if (min == 0 and max == 0) 0 else null, }; } pub const call = call_method; }; } /// Creates an iterator that keeps repeating the items returned from the /// child iterator, never returning `null` unless the child iterator returns /// no items, in which case `repeat` always returns `null`. pub fn repeat(_it: anytype) Repeat(@TypeOf(_it)) { return .{ .reset = _it, .curr = _it }; } test "repeat" { var it = span("ab") // .call(repeat, .{}); testing.expectEqual(LengthHint{ .min = 2, .max = null }, it.len_hint()); testing.expect(it.next().? == 'a'); testing.expect(it.next().? == 'b'); testing.expect(it.next().? == 'a'); testing.expect(it.next().? == 'b'); testing.expect(it.next().? == 'a'); testing.expect(it.next().? == 'b'); } pub fn Span(comptime S: type) type { const Array = @Type(.{ .Array = .{ .child = @typeInfo(S).Pointer.child, .sentinel = @typeInfo(S).Pointer.sentinel, .len = 0, }, }); return struct { span: S = &Array{}, // HACK: Cannot use &it.span[0] here // --------------------------------vvvvvvvvvvvvvvvvvvvvvvvvv pub fn next(it: *@This()) ?@TypeOf(&@intToPtr(*S, 0x10).*[0]) { if (it.span.len == 0) return null; defer it.span = it.span[1..]; return &it.span[0]; } pub fn len_hint(it: @This()) LengthHint { return .{ .min = it.span.len, .max = it.span.len }; } pub const call = call_method; }; } /// Creates an iterator that iterates over all the items of an array or slice. pub fn span(s: anytype) Deref(Span(mem.Span(@TypeOf(s)))) { return deref(span_by_ref(s)); } test "span" { const items = "abcd"; test_it(span(items[0..]), .{ .min = 4, .max = 4 }, items[0..]); test_it(span(items[1..]), .{ .min = 3, .max = 3 }, items[1..]); test_it(span(items[2..]), .{ .min = 2, .max = 2 }, items[2..]); test_it(span(items[3..]), .{ .min = 1, .max = 1 }, items[3..]); test_it(span(items[4..]), .{ .min = 0, .max = 0 }, items[4..]); } /// Creates an iterator that iterates over all the items of an array or slice /// by reference. pub fn span_by_ref(s: anytype) Span(mem.Span(@TypeOf(s))) { return .{ .span = mem.span(s) }; } comptime { const c = "a".*; var v = "a".*; var sc = span_by_ref(&c); var sv = span_by_ref(&v); debug.assert(@TypeOf(sc.next()) == ?*const u8); debug.assert(@TypeOf(sv.next()) == ?*u8); } test "span_by_ref" { const items = "abcd"; const refs = &[_]*const u8{ &items[0], &items[1], &items[2], &items[3] }; test_it(span_by_ref(items[0..]), .{ .min = 4, .max = 4 }, refs[0..]); test_it(span_by_ref(items[1..]), .{ .min = 3, .max = 3 }, refs[1..]); test_it(span_by_ref(items[2..]), .{ .min = 2, .max = 2 }, refs[2..]); test_it(span_by_ref(items[3..]), .{ .min = 1, .max = 1 }, refs[3..]); test_it(span_by_ref(items[4..]), .{ .min = 0, .max = 0 }, refs[4..]); } /// Skips `n` iterations of `it` and return it. pub fn skip(_it: anytype, _n: usize) @TypeOf(_it) { var n = _n; var it = _it; while (n != 0) : (n -= 1) _ = it.next(); return it; } test "skip" { const i = span("abcd") // .call(skip, .{2}); test_it(i, .{ .min = 2, .max = 2 }, "cd"); } pub fn TakeWhile(comptime Context: type, comptime Child: type) type { return struct { child: Child = Child{}, ctx: Context = undefined, pred: fn (Context, Result(Child)) bool = undefined, pub fn next(it: *@This()) ?Result(Child) { const item = it.child.next() orelse return null; return if (it.pred(it.ctx, item)) item else null; } pub fn len_hint(it: @This()) LengthHint { if (!@hasDecl(Child, "len_hint")) return .{}; return .{ .min = 0, .max = it.child.len_hint().max }; } }; } /// Same as `take_while` but requires no context. pub fn take_while( it: anytype, pred: fn (Result(@TypeOf(it))) bool, ) TakeWhile(void, @TypeOf(it)) { const F = fn (void, Result(@TypeOf(it))) bool; return take_while_ex(it, {}, @ptrCast(F, pred)); } /// Creates an iterator that takes values from the child iterator so long /// as they matches the predicate `pred`. When the predicate is no longer /// satisfied, the iterator will return null. pub fn take_while_ex( it: anytype, ctx: anytype, pred: fn (@TypeOf(ctx), Result(@TypeOf(it))) bool, ) TakeWhile(@TypeOf(ctx), @TypeOf(it)) { return .{ .child = it, .ctx = ctx, .pred = pred }; } test "take_while" { const tw = span("abCD") // .call(take_while, .{std.ascii.isLower}); test_it(tw, .{ .min = 0, .max = 4 }, "ab"); } pub fn Take(comptime Child: type) type { return struct { child: Child = Child{}, n: usize, pub fn next(it: *@This()) ?Result(Child) { if (it.n == 0) return null; defer it.n -= 1; return it.child.next(); } pub fn len_hint(it: @This()) LengthHint { if (!@hasDecl(Child, "len_hint")) return .{ .max = it.n }; return .{ .min = math.min(it.n, it.child.len_hint().min), .max = it.n }; } }; } /// Creates an iterator that takes at most `n` items from the child iterator. pub fn take(it: anytype, n: usize) Take(@TypeOf(it)) { return .{ .child = it, .n = n }; } test "take" { const abCD = span("abCD"); test_it(abCD.call(take, .{1}), .{ .min = 1, .max = 1 }, "a"); test_it(abCD.call(take, .{2}), .{ .min = 2, .max = 2 }, "ab"); test_it(abCD.call(take, .{3}), .{ .min = 3, .max = 3 }, "abC"); } pub fn Unwrap(comptime Child: type) type { const err_union = @typeInfo(Result(Child)).ErrorUnion; const Error = err_union.error_set; const Res = err_union.payload; return struct { child: Child = Child{}, last_err: Error!void = {}, pub fn next(it: *@This()) ?Res { const errun = it.child.next() orelse return null; return errun catch |err| { it.last_err = err; return null; }; } pub fn len_hint(it: @This()) LengthHint { if (!@hasDecl(Child, "len_hint")) return .{}; return it.child.len_hint(); } }; } /// Creates an iterator that returns `null` on the first error returned /// from the child iterator. The child iterator is expected to return /// `?(Error!T)`. The error returned will be stored in a field called /// `last_err`. pub fn unwrap(it: anytype) Unwrap(@TypeOf(it)) { return .{ .child = it }; } test "unwrap" { const Dummy = struct { const Error = error{A}; num: usize = 0, fn next(it: *@This()) ?(Error!u8) { defer it.num += 1; switch (it.num) { // Without all these `@as` we get: // broken LLVM module found: Operand is null // call fastcc void @__zig_return_error(<null operand!>), !dbg !6394 0 => return @as(?(Error!u8), @as(Error!u8, 0)), 1 => return @as(?(Error!u8), @as(Error!u8, error.A)), else => return null, } } }; var i = unwrap(Dummy{}); testing.expectEqual(@as(?u8, 0), i.next()); testing.expectEqual(@as(?u8, null), i.next()); testing.expectEqual(@as(Dummy.Error!void, error.A), i.last_err); } ///////////////////////////////////////////////////////////////// // The functions below iterates over iterators to get a result // ///////////////////////////////////////////////////////////////// /// Same as `all_ex` but requires no context. pub fn all(it: anytype, pred: fn (Result(@TypeOf(it))) bool) bool { const F = fn (void, Result(@TypeOf(it))) bool; return all_ex(it, {}, @ptrCast(F, pred)); } /// Check that all items in an iterator matches a predicate. pub fn all_ex( _it: anytype, ctx: anytype, pred: fn (@TypeOf(ctx), Result(@TypeOf(_it))) bool, ) bool { var it = _it; while (it.next()) |item| { if (!pred(ctx, item)) return false; } return true; } test "all" { testing.expect(span("aaa").call(all, .{std.ascii.isLower})); testing.expect(!span("Aaa").call(all, .{std.ascii.isLower})); } /// Same as `any_ex` but requires no context. pub fn any(it: anytype, pred: fn (Result(@TypeOf(it))) bool) bool { const F = fn (void, Result(@TypeOf(it))) bool; return any_ex(it, {}, @ptrCast(F, pred)); } /// Check that any items in an iterator matches a predicate. pub fn any_ex( it: anytype, ctx: anytype, pred: fn (@TypeOf(ctx), Result(@TypeOf(it))) bool, ) bool { return find_ex(it, ctx, pred) != null; } test "any" { testing.expect(span("aAA").call(any, .{std.ascii.isLower})); testing.expect(!span("AAA").call(any, .{std.ascii.isLower})); } pub fn collect( _it: anytype, allocator: *mem.Allocator, ) mem.Allocator.Error![]Result(@TypeOf(_it)) { var res = std.ArrayList(Result(@TypeOf(_it))).init(allocator); errdefer res.deinit(); if (@hasDecl(@TypeOf(_it), "len_hint")) try res.ensureCapacity(_it.len_hint().min); var it = _it; while (it.next()) |item| try res.append(item); return res.items; } test "collect" { const collected = try span("abcd") // .call(collect, .{testing.allocator}); defer testing.allocator.free(collected); testing.expectEqualSlices(u8, "abcd", collected); const collected_range = try range(usize, 0, 5) // .call(collect, .{testing.allocator}); defer testing.allocator.free(collected_range); testing.expectEqualSlices(usize, &[_]usize{ 0, 1, 2, 3, 4 }, collected_range); } /// Counts the number of iterations before an iterator returns `null`. pub fn count(_it: anytype) usize { if (@hasDecl(@TypeOf(_it), "len_hint")) { if (_it.len_hint().len()) |len| return len; } var res: usize = 0; var it = _it; while (it.next()) |_| res += 1; return res; } test "count" { testing.expectEqual(@as(usize, 0), span("").call(count, .{})); testing.expectEqual(@as(usize, 1), span("a").call(count, .{})); testing.expectEqual(@as(usize, 2), span("aa").call(count, .{})); } /// Same as `find_ex` but requires no context. pub fn find(it: anytype, pred: fn (Result(@TypeOf(it))) bool) ?Result(@TypeOf(it)) { const F = fn (void, Result(@TypeOf(it))) bool; return find_ex(it, {}, @ptrCast(F, pred)); } /// Gets the first item in an iterator that satiesfies the predicate. pub fn find_ex( _it: anytype, ctx: anytype, pred: fn (@TypeOf(ctx), Result(@TypeOf(_it))) bool, ) ?Result(@TypeOf(_it)) { var it = _it; while (it.next()) |item| { if (pred(ctx, item)) return item; } return null; } test "find" { const aAA = span("aAA"); const AAA = span("AAA"); testing.expect(aAA.call(find, .{std.ascii.isLower}).? == 'a'); testing.expect(AAA.call(find, .{std.ascii.isLower}) == null); } /// Same as `fold_ex` but requires no context. pub fn fold( it: anytype, init: anytype, f: fn (@TypeOf(init), Result(@TypeOf(it))) @TypeOf(init), ) @TypeOf(init) { const F = fn (void, @TypeOf(init), Result(@TypeOf(it))) @TypeOf(init); return fold_ex(it, init, {}, @ptrCast(F, f)); } /// Iterates over an iterator to get a single resulting value. This result is aquired /// by starting with the value of `init` and calling the function `f` on all result + /// item pairs, reassing the result to the return value of `f` on each iteration. Once /// all items have been iterated over the result is returned. pub fn fold_ex( _it: anytype, init: anytype, ctx: anytype, f: fn (@TypeOf(ctx), @TypeOf(init), Result(@TypeOf(_it))) @TypeOf(init), ) @TypeOf(init) { var res = init; var it = _it; while (it.next()) |item| res = f(ctx, res, item); return res; } test "fold" { const add = struct { fn add(a: u8, b: u8) u8 { return a + b; } }.add; const r1 = range_ex(u8, 2, 8, 2); const r2 = range(u8, 0, 0); testing.expectEqual(@as(u8, 12), r1.call(fold, .{ @as(u8, 0), add })); testing.expectEqual(@as(u8, 0), r2.call(fold, .{ @as(u8, 0), add })); }
ziter.zig
pub const Input = [_]usize{ 19, 30, 13, 31, 42, 41, 44, 34, 39, 6, 47, 50, 36, 33, 32, 15, 43, 8, 26, 24, 48, 5, 3, 10, 1, 20, 4, 7, 9, 22, 11, 12, 16, 13, 14, 17, 6, 28, 57, 18, 19, 15, 21, 8, 23, 24, 25, 5, 26, 10, 27, 20, 29, 30, 33, 22, 43, 78, 31, 32, 41, 11, 13, 16, 56, 28, 37, 40, 15, 35, 18, 38, 21, 23, 24, 70, 34, 26, 45, 27, 102, 29, 33, 36, 108, 31, 32, 39, 41, 42, 46, 78, 50, 56, 44, 47, 48, 152, 104, 84, 64, 68, 53, 58, 136, 60, 61, 67, 106, 71, 63, 73, 80, 88, 108, 90, 97, 114, 148, 143, 118, 198, 133, 111, 121, 117, 113, 161, 124, 123, 131, 256, 130, 134, 136, 222, 153, 185, 178, 233, 203, 208, 232, 234, 245, 224, 237, 228, 274, 244, 230, 236, 276, 267, 253, 398, 264, 266, 356, 289, 397, 661, 436, 381, 411, 440, 609, 452, 458, 525, 889, 496, 464, 666, 466, 565, 500, 517, 520, 519, 530, 553, 702, 686, 893, 792, 894, 957, 1132, 851, 892, 1453, 982, 1478, 1409, 985, 930, 964, 1422, 966, 1017, 1019, 1036, 1221, 1818, 1232, 1239, 2053, 1537, 1643, 1684, 1912, 1743, 1781, 1815, 1822, 1894, 2249, 1947, 3065, 1896, 1930, 2036, 2460, 2779, 2923, 2471, 4513, 2453, 2769, 2882, 3020, 3590, 3427, 5018, 3728, 3524, 3558, 3596, 4924, 3966, 4699, 4720, 8223, 4918, 11951, 6043, 4496, 4913, 5232, 8147, 5222, 5335, 8471, 5651, 8054, 6447, 6951, 14918, 7082, 13398, 10145, 8462, 7562, 9414, 8665, 9195, 9638, 10150, 9409, 9718, 9728, 9831, 10567, 10454, 10557, 10873, 10986, 16033, 12098, 19142, 17200, 16024, 17860, 14644, 18916, 16227, 16757, 25864, 18074, 19549, 18833, 19047, 19559, 19127, 20285, 29483, 21430, 21011, 28855, 54719, 36318, 31647, 31014, 50789, 51299, 36987, 30668, 31401, 35060, 32984, 34301, 34831, 36907, 37121, 37880, 56713, 38174, 40989, 81803, 41296, 42441, 49866, 69527, 63048, 61682, 62415, 62661, 65499, 62069, 63652, 65702, 64385, 67285, 70105, 78417, 69132, 71738, 94593, 75001, 76054, 100243, 131793, 83430, 105681, 83737, 104123, 111548, 142286, 128117, 123751, 142069, 124730, 125721, 126454, 130087, 131670, 195489, 136417, 139237, 217287, 170647, 155168, 151055, 158431, 260168, 167167, 211547, 187553, 187860, 258124, 234210, 236278, 248481, 249472, 303584, 250451, 285255, 252175, 286838, 266504, 268087, 474698, 294848, 329078, 306223, 419342, 318222, 309486, 378714, 535706, 354720, 375413, 421763, 422070, 470488, 519465, 484759, 497953, 551759, 539013, 516955, 575990, 534591, 649568, 954704, 577573, 601071, 604334, 615709, 624445, 733434, 627708, 664206, 839479, 976484, 776483, 797176, 1090772, 892558, 1331767, 1144663, 982712, 1014908, 1215965, 1404191, 1334505, 1110581, 1380817, 1178644, 1181907, 2346675, 1803089, 1220043, 1573659, 1252153, 1291914, 2583920, 1615962, 1887064, 2192449, 2350142, 1689734, 2947752, 1875270, 2159571, 1997620, 3303030, 2125489, 2289225, 3291255, 4594944, 2292488, 3127423, 2360551, 4233739, 2825812, 4045855, 2511957, 6522964, 2544067, 2907876, 3305696, 4669556, 9825994, 3565004, 3687354, 3815223, 4290108, 3872890, 4123109, 4649776, 4414714, 4417977, 6635066, 4653039, 4872508, 10450289, 4904618, 5056024, 5337769, 5369879, 5451943, 5419833, 5849763, 6109071, 7197984, 7178586, 8621028, 11301695, 7252358, 8525929, 8995617, 8777508, 7995999, 8537823, 12070492, 8832691, 16617027, 9525547, 11831625, 10324451, 9960642, 22726098, 10393793, 14447560, 10789712, 10871776, 16502864, 11958834, 13361429, 15873386, 17576809, 16521928, 15248357, 15778287, 16533822, 17315331, 16773507, 16828690, 20664316, 18358238, 18793333, 19486189, 24772011, 20285093, 30609544, 20354435, 21183505, 21265569, 42568378, 27563219, 27207191, 29883357, 32021864, 28609786, 31026644, 31770285, 31782179, 32077047, 32312109, 33307329, 45955516, 39771282, 36314879, 40058902, 39147768, 51508053, 39840624, 60413337, 69775569, 41537940, 67757554, 42449074, 53577678, 62195466, 54770410, 55816977, 58493143, 59636430, 60380071, 62796929, 63552464, 72135949, 64389156, 88077739, 72455097, 82270395, 78763953, 97640911, 78988392, 158054248, 81378564, 82289698, 117966834, 83987014, 130554483, 141906825, 173003557, 108348088, 121290072, 185718650, 114310120, 118129573, 160213688, 255273952, 126349393, 164560093, 136525105, 136844253, 151219050, 154744795, 195688684, 157752345, 160366956, 161278090, 163668262, 196599818, 208639091, 192335102, 198297134, 226477661, 234697481, 222658208, 232439693, 416552042, 250835225, 387360330, 244478966, 262874498, 314887312, 263193646, 273369358, 321645046, 288063303, 567771092, 451731565, 402231311, 318119301, 324035218, 485851854, 356003364, 388934920, 406936225, 556342527, 420955342, 449135869, 510721511, 467137174, 495314191, 507353464, 764023181, 393911906, 532542269, 526068144, 578080958, 561432661, 591488659, 909584775, 676998223, 642154519, 674122665, 680038582, 739074643, 1036789655, 912345891, 805139233, 814867248, 919980050, 1446048194, 1404898966, 1684003231, 1355511840, 1068786125, 2760410806, 1036066425, 926454175, 1070910129, 1255079181, 1087500805, 2035550422, 1727213139, 2715589004, 1316277184, 1678220944, 1322193101, 1586468556, 2657378685, 1544213876, 1620006481, 1717485124, 2106976554, 1734847298, 1962520600, 2242731359, 2385063309, 3926734590, 3697367898, 2546460656, 1997364304, 2248647276, 2013954980, 2631714681, 2707507286, 2403777989, 2866406977, 3617370785, 3559008543, 2638470285, 2908661657, 3057040399, 4601254275, 3164220357, 7176379328, 3337491605, 3976475580, 3732211602, 3748802278, 3959884904, 5406951716, 4246011580, 5556372847, 4262602256, 4011319284, 4401142293, 6643033965, 4417732969, 5035492670, 5923447376, 5042248274, 6246153262, 5547131942, 11470579318, 5695510684, 5965702056, 6221260756, 7086293883, 6501711962, 7313967185, 9298094926, 8791050552, 16612062111, 9436634963, 9516257751, 8412461577, 8257330864, 8273921540, 8429052253, 14394754309, 8818875262, 9453225639, 9459981243, 10077740944, 25910157037, 10589380216, 11242642626, 11512833998, 13815679147, 11661212740, 19935134280, 16702973793, 13588005845, 15292762514, 18351662484, 21590574942, 16531252404, 17790179291, 27788297447, 24943713981, 16686383117, 17076206126, 17727147179, 35987897981, 18272100901, 18278856505, 27804888123, 25249218585, 20667121160, 27275763333, 21832022842, 22755476624, 34882914888, 28364186533, 29933313641, 46156550607, 30290979638, 31860106746, 31824014918, 33217635521, 33607458530, 34258399583, 54266754486, 33762589243, 34958484018, 44881094249, 55639949866, 40110879347, 36550957406, 38939222061, 41034333129, 61038352576, 42499144002, 43422597784, 89149669374, 68565942548, 65254620626, 84991973596, 58297500174, 60224293279, 75069363365, 62114994556, 69216883601, 97073478574, 90817711892, 70313546649, 68721073261, 101054216617, 71509441424, 95996836594, 115180242712, 75490179467, 76661836753, 77585290535, 79973555190, 112143671045, 85921741786, 101720097958, 162328099200, 118521793453, 170791267082, 120412494730, 122339287835, 127018573435, 146975383402, 137937956862, 131331878157, 139034619910, 140230514685, 173582127129, 141822988073, 169775289878, 211177079306, 146999620891, 152152016220, 154247127288, 153075470002, 239162244480, 157558845725, 307322597290, 187641839744, 204443535239, 233051976115, 238934288183, 253671165992, 259447114640, 329464827817, 284407348159, 518499676596, 270366498067, 406634103244, 509528742547, 279265134595, 293305984687, 288822608964, 327334135603, 476464448708, 299151637111, 300075090893, 305227486222, 552753099327, 310634315727, 443605779719, 390610821840, 392085374983, 509671021461, 437495511354, 526357960802, 492605454175, 513118280632, 529813612707, 569518135178, 610709406620, 575593984289, 549631632662, 568087743559, 604379123333, 671350509578, 598533470909, 587974246075, 1026096081370, 599226728004, 791757091286, 1079189156639, 996464498316, 754240095446, 748129827081, 782696196823, 828106333194, 829580886337, 930100965529, 987127144016, 1105407596996, 1022419066882, 1111651751541, 1079445245369, 1137605878737, 1117719376221, 1166621214468, 1148165103571, 1370670442898, 1186507716984, 1187200974079, 1584438744391, 1342214341521, 1347356555085, 1353466823450, 1545997186732, 1502369922527, 1530826023904, 2300771408427, 2243013475733, 1610802530017, 2495521658656, 1816708030353, 1917228109545, 2009546210898, 3827452220124, 2160024945619, 2581815167896, 2648545400125, 2255325254958, 2518835546469, 2314786318039, 2334672820555, 2373708691063, 2528722058505, 2529415315600, 2689570896606, 2700823378535, 3319077952880, 2899464010182, 3911573938444, 3033195946431, 3347534054257, 3427510560370, 3528030639562, 3620348740915, 3733936139898, 3926774320443, 4077253055164, 4169571156517, 4415350200577, 5015609696574, 4570111572997, 4833621864508, 8481685511441, 4649459138594, 6261447140998, 4708381511618, 7733085874690, 5932659956613, 5218986212206, 11171256408047, 5600287388717, 6427494649744, 11810338929854, 6380730000688, 6460706506801, 6775044614627, 7161446700268, 8496885893440, 8567558004406, 9723991208192, 8004027375607, 8246824211681, 9064809339171, 13315307375949, 9219570711591, 9278493084615, 9357840650212, 9927367723824, 9868445350800, 17925398654618, 10308668900335, 10819273600923, 13155774615315, 11599716212894, 11981017389405, 15021868826308, 16381017411859, 12841436507489, 20819286924485, 17466394923272, 13936491314895, 19002484292807, 25536207527789, 16250851587288, 20032660108527, 17068836714778, 17311633550852, 25136792004720, 18498063796206, 24245160215230, 19285208374036, 21338858039617, 23975048216238, 22418989813817, 23660710108412, 21127942501258, 22800290990328, 24755490828209, 28668552927672, 27002886215713, 26777927822384, 32631868999147, 29092288094777, 30187342902183, 39869127705106, 31005328029673, 49124948203304, };
day9/src/input.zig
const dos = @import("DOtherSide.zig"); //TODO: add rest of supported types pub const QVariant = struct { vptr: ?*dos.dos_type.DosQVariant, pub fn create(value: anytype) QVariant { var vptr = switch (@typeInfo(@TypeOf(value))) { .Null => dos.dos_qvariant_create(), .Pointer => dos.dos_qvariant_create_string(value), .Int => dos.dos_qvariant_create_int(@intCast(c_int, value)), .Float => |float| switch (float.bits) { 32 => dos.dos_qvariant_create_float(value), 64 => dos.dos_qvariant_create_double(value), else => @compileError("Unsupported type '" ++ @typeName(value) ++ "'"), }, .Bool => dos.dos_qvariant_create_bool(value), @typeInfo(QVariant) => dos.dos_qvariant_create_qvariant(value.vptr), else => @compileError("Unsupported type '" ++ @typeName(value) ++ "'"), }; return QVariant{ .vptr = vptr }; } pub fn wrap(vptr: ?*dos.DosQVariant) QVariant { return QVariant{ .vptr = vptr }; } pub fn delete(self: QVariant) void { dos.dos_qvariant_delete(self.vptr); } pub fn setValue(self: QVariant, value: anytype) void { switch (@typeInfo(@TypeOf(value))) { .Null => @compileError("Cannot set variant to null"), .Pointer => dos.dos_qvariant_setString(self.vptr, value), .Int => dos.dos_qvariant_setInt(self.vptr, @intCast(c_int, value)), .Float => |float| switch (float.bits) { 32 => dos.dos_qvariant_setFloat(value), 64 => dos.dos_qvariant_setDouble(value), else => @compileError("Unsupported type '" ++ @typeName(value) ++ "'"), }, .Bool => dos.dos_qvariant_setBool(self.vptr, value), else => @compileError("Unsupported type '" ++ @typeName(value) ++ "'"), } } pub fn getValue(self: QVariant, comptime T: type) T { return switch (@typeInfo(T)) { .Null => @compileError("Use isNull"), .Pointer => dos.dos_qvariant_toString(self.vptr), .Int => @intCast(T, dos.dos_qvariant_toInt(self.vptr)), .Bool => dos.dos_qvariant_toBool(self.vptr), .Float => |float| switch (float.bits) { 32 => dos.dos_qvariant_toFloat(self.vptr), 64 => dos.dos_qvariant_toDouble(self.vptr), else => @compileError("Unsupported type '" ++ @typeName(T) ++ "'"), }, else => @compileError("Unsupported type '" ++ @typeName(T) ++ "'"), }; } pub fn isNull(self: QVariant) bool { return dos.dos_qvariant_isnull(self.vptr); } }; const expect = @import("std").testing.expect; const TEST_TYPES = .{ true, @as(u32, 1), @as(f32, 2.37), @as(f64, 3.48), }; test "QVariant initialization" { inline for (TEST_TYPES) |t| { var variant = QVariant.create(t); defer variant.delete(); expect(variant.getValue(@TypeOf(t)) == t); } var nullVariant = QVariant.create(null); expect(nullVariant.isNull()); } test "QVariant initialization from different QVariant" { inline for (TEST_TYPES) |t| { var variant = QVariant.create(t); defer variant.delete(); var variantCopy = QVariant.create(variant); defer variantCopy.delete(); expect(variantCopy.getValue(@TypeOf(t)) == t); } }
src/QVariant.zig
pub fn toUpper(cp: u21) u21 { return switch (cp) { 0x61 => 0x41, 0x62 => 0x42, 0x63 => 0x43, 0x64 => 0x44, 0x65 => 0x45, 0x66 => 0x46, 0x67 => 0x47, 0x68 => 0x48, 0x69 => 0x49, 0x6A => 0x4A, 0x6B => 0x4B, 0x6C => 0x4C, 0x6D => 0x4D, 0x6E => 0x4E, 0x6F => 0x4F, 0x70 => 0x50, 0x71 => 0x51, 0x72 => 0x52, 0x73 => 0x53, 0x74 => 0x54, 0x75 => 0x55, 0x76 => 0x56, 0x77 => 0x57, 0x78 => 0x58, 0x79 => 0x59, 0x7A => 0x5A, 0xB5 => 0x39C, 0xE0 => 0xC0, 0xE1 => 0xC1, 0xE2 => 0xC2, 0xE3 => 0xC3, 0xE4 => 0xC4, 0xE5 => 0xC5, 0xE6 => 0xC6, 0xE7 => 0xC7, 0xE8 => 0xC8, 0xE9 => 0xC9, 0xEA => 0xCA, 0xEB => 0xCB, 0xEC => 0xCC, 0xED => 0xCD, 0xEE => 0xCE, 0xEF => 0xCF, 0xF0 => 0xD0, 0xF1 => 0xD1, 0xF2 => 0xD2, 0xF3 => 0xD3, 0xF4 => 0xD4, 0xF5 => 0xD5, 0xF6 => 0xD6, 0xF8 => 0xD8, 0xF9 => 0xD9, 0xFA => 0xDA, 0xFB => 0xDB, 0xFC => 0xDC, 0xFD => 0xDD, 0xFE => 0xDE, 0xFF => 0x178, 0x101 => 0x100, 0x103 => 0x102, 0x105 => 0x104, 0x107 => 0x106, 0x109 => 0x108, 0x10B => 0x10A, 0x10D => 0x10C, 0x10F => 0x10E, 0x111 => 0x110, 0x113 => 0x112, 0x115 => 0x114, 0x117 => 0x116, 0x119 => 0x118, 0x11B => 0x11A, 0x11D => 0x11C, 0x11F => 0x11E, 0x121 => 0x120, 0x123 => 0x122, 0x125 => 0x124, 0x127 => 0x126, 0x129 => 0x128, 0x12B => 0x12A, 0x12D => 0x12C, 0x12F => 0x12E, 0x131 => 0x49, 0x133 => 0x132, 0x135 => 0x134, 0x137 => 0x136, 0x13A => 0x139, 0x13C => 0x13B, 0x13E => 0x13D, 0x140 => 0x13F, 0x142 => 0x141, 0x144 => 0x143, 0x146 => 0x145, 0x148 => 0x147, 0x14B => 0x14A, 0x14D => 0x14C, 0x14F => 0x14E, 0x151 => 0x150, 0x153 => 0x152, 0x155 => 0x154, 0x157 => 0x156, 0x159 => 0x158, 0x15B => 0x15A, 0x15D => 0x15C, 0x15F => 0x15E, 0x161 => 0x160, 0x163 => 0x162, 0x165 => 0x164, 0x167 => 0x166, 0x169 => 0x168, 0x16B => 0x16A, 0x16D => 0x16C, 0x16F => 0x16E, 0x171 => 0x170, 0x173 => 0x172, 0x175 => 0x174, 0x177 => 0x176, 0x17A => 0x179, 0x17C => 0x17B, 0x17E => 0x17D, 0x17F => 0x53, 0x180 => 0x243, 0x183 => 0x182, 0x185 => 0x184, 0x188 => 0x187, 0x18C => 0x18B, 0x192 => 0x191, 0x195 => 0x1F6, 0x199 => 0x198, 0x19A => 0x23D, 0x19E => 0x220, 0x1A1 => 0x1A0, 0x1A3 => 0x1A2, 0x1A5 => 0x1A4, 0x1A8 => 0x1A7, 0x1AD => 0x1AC, 0x1B0 => 0x1AF, 0x1B4 => 0x1B3, 0x1B6 => 0x1B5, 0x1B9 => 0x1B8, 0x1BD => 0x1BC, 0x1BF => 0x1F7, 0x1C5 => 0x1C4, 0x1C6 => 0x1C4, 0x1C8 => 0x1C7, 0x1C9 => 0x1C7, 0x1CB => 0x1CA, 0x1CC => 0x1CA, 0x1CE => 0x1CD, 0x1D0 => 0x1CF, 0x1D2 => 0x1D1, 0x1D4 => 0x1D3, 0x1D6 => 0x1D5, 0x1D8 => 0x1D7, 0x1DA => 0x1D9, 0x1DC => 0x1DB, 0x1DD => 0x18E, 0x1DF => 0x1DE, 0x1E1 => 0x1E0, 0x1E3 => 0x1E2, 0x1E5 => 0x1E4, 0x1E7 => 0x1E6, 0x1E9 => 0x1E8, 0x1EB => 0x1EA, 0x1ED => 0x1EC, 0x1EF => 0x1EE, 0x1F2 => 0x1F1, 0x1F3 => 0x1F1, 0x1F5 => 0x1F4, 0x1F9 => 0x1F8, 0x1FB => 0x1FA, 0x1FD => 0x1FC, 0x1FF => 0x1FE, 0x201 => 0x200, 0x203 => 0x202, 0x205 => 0x204, 0x207 => 0x206, 0x209 => 0x208, 0x20B => 0x20A, 0x20D => 0x20C, 0x20F => 0x20E, 0x211 => 0x210, 0x213 => 0x212, 0x215 => 0x214, 0x217 => 0x216, 0x219 => 0x218, 0x21B => 0x21A, 0x21D => 0x21C, 0x21F => 0x21E, 0x223 => 0x222, 0x225 => 0x224, 0x227 => 0x226, 0x229 => 0x228, 0x22B => 0x22A, 0x22D => 0x22C, 0x22F => 0x22E, 0x231 => 0x230, 0x233 => 0x232, 0x23C => 0x23B, 0x23F => 0x2C7E, 0x240 => 0x2C7F, 0x242 => 0x241, 0x247 => 0x246, 0x249 => 0x248, 0x24B => 0x24A, 0x24D => 0x24C, 0x24F => 0x24E, 0x250 => 0x2C6F, 0x251 => 0x2C6D, 0x252 => 0x2C70, 0x253 => 0x181, 0x254 => 0x186, 0x256 => 0x189, 0x257 => 0x18A, 0x259 => 0x18F, 0x25B => 0x190, 0x25C => 0xA7AB, 0x260 => 0x193, 0x261 => 0xA7AC, 0x263 => 0x194, 0x265 => 0xA78D, 0x266 => 0xA7AA, 0x268 => 0x197, 0x269 => 0x196, 0x26A => 0xA7AE, 0x26B => 0x2C62, 0x26C => 0xA7AD, 0x26F => 0x19C, 0x271 => 0x2C6E, 0x272 => 0x19D, 0x275 => 0x19F, 0x27D => 0x2C64, 0x280 => 0x1A6, 0x282 => 0xA7C5, 0x283 => 0x1A9, 0x287 => 0xA7B1, 0x288 => 0x1AE, 0x289 => 0x244, 0x28A => 0x1B1, 0x28B => 0x1B2, 0x28C => 0x245, 0x292 => 0x1B7, 0x29D => 0xA7B2, 0x29E => 0xA7B0, 0x345 => 0x399, 0x371 => 0x370, 0x373 => 0x372, 0x377 => 0x376, 0x37B => 0x3FD, 0x37C => 0x3FE, 0x37D => 0x3FF, 0x3AC => 0x386, 0x3AD => 0x388, 0x3AE => 0x389, 0x3AF => 0x38A, 0x3B1 => 0x391, 0x3B2 => 0x392, 0x3B3 => 0x393, 0x3B4 => 0x394, 0x3B5 => 0x395, 0x3B6 => 0x396, 0x3B7 => 0x397, 0x3B8 => 0x398, 0x3B9 => 0x399, 0x3BA => 0x39A, 0x3BB => 0x39B, 0x3BC => 0x39C, 0x3BD => 0x39D, 0x3BE => 0x39E, 0x3BF => 0x39F, 0x3C0 => 0x3A0, 0x3C1 => 0x3A1, 0x3C2 => 0x3A3, 0x3C3 => 0x3A3, 0x3C4 => 0x3A4, 0x3C5 => 0x3A5, 0x3C6 => 0x3A6, 0x3C7 => 0x3A7, 0x3C8 => 0x3A8, 0x3C9 => 0x3A9, 0x3CA => 0x3AA, 0x3CB => 0x3AB, 0x3CC => 0x38C, 0x3CD => 0x38E, 0x3CE => 0x38F, 0x3D0 => 0x392, 0x3D1 => 0x398, 0x3D5 => 0x3A6, 0x3D6 => 0x3A0, 0x3D7 => 0x3CF, 0x3D9 => 0x3D8, 0x3DB => 0x3DA, 0x3DD => 0x3DC, 0x3DF => 0x3DE, 0x3E1 => 0x3E0, 0x3E3 => 0x3E2, 0x3E5 => 0x3E4, 0x3E7 => 0x3E6, 0x3E9 => 0x3E8, 0x3EB => 0x3EA, 0x3ED => 0x3EC, 0x3EF => 0x3EE, 0x3F0 => 0x39A, 0x3F1 => 0x3A1, 0x3F2 => 0x3F9, 0x3F3 => 0x37F, 0x3F5 => 0x395, 0x3F8 => 0x3F7, 0x3FB => 0x3FA, 0x430 => 0x410, 0x431 => 0x411, 0x432 => 0x412, 0x433 => 0x413, 0x434 => 0x414, 0x435 => 0x415, 0x436 => 0x416, 0x437 => 0x417, 0x438 => 0x418, 0x439 => 0x419, 0x43A => 0x41A, 0x43B => 0x41B, 0x43C => 0x41C, 0x43D => 0x41D, 0x43E => 0x41E, 0x43F => 0x41F, 0x440 => 0x420, 0x441 => 0x421, 0x442 => 0x422, 0x443 => 0x423, 0x444 => 0x424, 0x445 => 0x425, 0x446 => 0x426, 0x447 => 0x427, 0x448 => 0x428, 0x449 => 0x429, 0x44A => 0x42A, 0x44B => 0x42B, 0x44C => 0x42C, 0x44D => 0x42D, 0x44E => 0x42E, 0x44F => 0x42F, 0x450 => 0x400, 0x451 => 0x401, 0x452 => 0x402, 0x453 => 0x403, 0x454 => 0x404, 0x455 => 0x405, 0x456 => 0x406, 0x457 => 0x407, 0x458 => 0x408, 0x459 => 0x409, 0x45A => 0x40A, 0x45B => 0x40B, 0x45C => 0x40C, 0x45D => 0x40D, 0x45E => 0x40E, 0x45F => 0x40F, 0x461 => 0x460, 0x463 => 0x462, 0x465 => 0x464, 0x467 => 0x466, 0x469 => 0x468, 0x46B => 0x46A, 0x46D => 0x46C, 0x46F => 0x46E, 0x471 => 0x470, 0x473 => 0x472, 0x475 => 0x474, 0x477 => 0x476, 0x479 => 0x478, 0x47B => 0x47A, 0x47D => 0x47C, 0x47F => 0x47E, 0x481 => 0x480, 0x48B => 0x48A, 0x48D => 0x48C, 0x48F => 0x48E, 0x491 => 0x490, 0x493 => 0x492, 0x495 => 0x494, 0x497 => 0x496, 0x499 => 0x498, 0x49B => 0x49A, 0x49D => 0x49C, 0x49F => 0x49E, 0x4A1 => 0x4A0, 0x4A3 => 0x4A2, 0x4A5 => 0x4A4, 0x4A7 => 0x4A6, 0x4A9 => 0x4A8, 0x4AB => 0x4AA, 0x4AD => 0x4AC, 0x4AF => 0x4AE, 0x4B1 => 0x4B0, 0x4B3 => 0x4B2, 0x4B5 => 0x4B4, 0x4B7 => 0x4B6, 0x4B9 => 0x4B8, 0x4BB => 0x4BA, 0x4BD => 0x4BC, 0x4BF => 0x4BE, 0x4C2 => 0x4C1, 0x4C4 => 0x4C3, 0x4C6 => 0x4C5, 0x4C8 => 0x4C7, 0x4CA => 0x4C9, 0x4CC => 0x4CB, 0x4CE => 0x4CD, 0x4CF => 0x4C0, 0x4D1 => 0x4D0, 0x4D3 => 0x4D2, 0x4D5 => 0x4D4, 0x4D7 => 0x4D6, 0x4D9 => 0x4D8, 0x4DB => 0x4DA, 0x4DD => 0x4DC, 0x4DF => 0x4DE, 0x4E1 => 0x4E0, 0x4E3 => 0x4E2, 0x4E5 => 0x4E4, 0x4E7 => 0x4E6, 0x4E9 => 0x4E8, 0x4EB => 0x4EA, 0x4ED => 0x4EC, 0x4EF => 0x4EE, 0x4F1 => 0x4F0, 0x4F3 => 0x4F2, 0x4F5 => 0x4F4, 0x4F7 => 0x4F6, 0x4F9 => 0x4F8, 0x4FB => 0x4FA, 0x4FD => 0x4FC, 0x4FF => 0x4FE, 0x501 => 0x500, 0x503 => 0x502, 0x505 => 0x504, 0x507 => 0x506, 0x509 => 0x508, 0x50B => 0x50A, 0x50D => 0x50C, 0x50F => 0x50E, 0x511 => 0x510, 0x513 => 0x512, 0x515 => 0x514, 0x517 => 0x516, 0x519 => 0x518, 0x51B => 0x51A, 0x51D => 0x51C, 0x51F => 0x51E, 0x521 => 0x520, 0x523 => 0x522, 0x525 => 0x524, 0x527 => 0x526, 0x529 => 0x528, 0x52B => 0x52A, 0x52D => 0x52C, 0x52F => 0x52E, 0x561 => 0x531, 0x562 => 0x532, 0x563 => 0x533, 0x564 => 0x534, 0x565 => 0x535, 0x566 => 0x536, 0x567 => 0x537, 0x568 => 0x538, 0x569 => 0x539, 0x56A => 0x53A, 0x56B => 0x53B, 0x56C => 0x53C, 0x56D => 0x53D, 0x56E => 0x53E, 0x56F => 0x53F, 0x570 => 0x540, 0x571 => 0x541, 0x572 => 0x542, 0x573 => 0x543, 0x574 => 0x544, 0x575 => 0x545, 0x576 => 0x546, 0x577 => 0x547, 0x578 => 0x548, 0x579 => 0x549, 0x57A => 0x54A, 0x57B => 0x54B, 0x57C => 0x54C, 0x57D => 0x54D, 0x57E => 0x54E, 0x57F => 0x54F, 0x580 => 0x550, 0x581 => 0x551, 0x582 => 0x552, 0x583 => 0x553, 0x584 => 0x554, 0x585 => 0x555, 0x586 => 0x556, 0x10D0 => 0x1C90, 0x10D1 => 0x1C91, 0x10D2 => 0x1C92, 0x10D3 => 0x1C93, 0x10D4 => 0x1C94, 0x10D5 => 0x1C95, 0x10D6 => 0x1C96, 0x10D7 => 0x1C97, 0x10D8 => 0x1C98, 0x10D9 => 0x1C99, 0x10DA => 0x1C9A, 0x10DB => 0x1C9B, 0x10DC => 0x1C9C, 0x10DD => 0x1C9D, 0x10DE => 0x1C9E, 0x10DF => 0x1C9F, 0x10E0 => 0x1CA0, 0x10E1 => 0x1CA1, 0x10E2 => 0x1CA2, 0x10E3 => 0x1CA3, 0x10E4 => 0x1CA4, 0x10E5 => 0x1CA5, 0x10E6 => 0x1CA6, 0x10E7 => 0x1CA7, 0x10E8 => 0x1CA8, 0x10E9 => 0x1CA9, 0x10EA => 0x1CAA, 0x10EB => 0x1CAB, 0x10EC => 0x1CAC, 0x10ED => 0x1CAD, 0x10EE => 0x1CAE, 0x10EF => 0x1CAF, 0x10F0 => 0x1CB0, 0x10F1 => 0x1CB1, 0x10F2 => 0x1CB2, 0x10F3 => 0x1CB3, 0x10F4 => 0x1CB4, 0x10F5 => 0x1CB5, 0x10F6 => 0x1CB6, 0x10F7 => 0x1CB7, 0x10F8 => 0x1CB8, 0x10F9 => 0x1CB9, 0x10FA => 0x1CBA, 0x10FD => 0x1CBD, 0x10FE => 0x1CBE, 0x10FF => 0x1CBF, 0x13F8 => 0x13F0, 0x13F9 => 0x13F1, 0x13FA => 0x13F2, 0x13FB => 0x13F3, 0x13FC => 0x13F4, 0x13FD => 0x13F5, 0x1C80 => 0x412, 0x1C81 => 0x414, 0x1C82 => 0x41E, 0x1C83 => 0x421, 0x1C84 => 0x422, 0x1C85 => 0x422, 0x1C86 => 0x42A, 0x1C87 => 0x462, 0x1C88 => 0xA64A, 0x1D79 => 0xA77D, 0x1D7D => 0x2C63, 0x1D8E => 0xA7C6, 0x1E01 => 0x1E00, 0x1E03 => 0x1E02, 0x1E05 => 0x1E04, 0x1E07 => 0x1E06, 0x1E09 => 0x1E08, 0x1E0B => 0x1E0A, 0x1E0D => 0x1E0C, 0x1E0F => 0x1E0E, 0x1E11 => 0x1E10, 0x1E13 => 0x1E12, 0x1E15 => 0x1E14, 0x1E17 => 0x1E16, 0x1E19 => 0x1E18, 0x1E1B => 0x1E1A, 0x1E1D => 0x1E1C, 0x1E1F => 0x1E1E, 0x1E21 => 0x1E20, 0x1E23 => 0x1E22, 0x1E25 => 0x1E24, 0x1E27 => 0x1E26, 0x1E29 => 0x1E28, 0x1E2B => 0x1E2A, 0x1E2D => 0x1E2C, 0x1E2F => 0x1E2E, 0x1E31 => 0x1E30, 0x1E33 => 0x1E32, 0x1E35 => 0x1E34, 0x1E37 => 0x1E36, 0x1E39 => 0x1E38, 0x1E3B => 0x1E3A, 0x1E3D => 0x1E3C, 0x1E3F => 0x1E3E, 0x1E41 => 0x1E40, 0x1E43 => 0x1E42, 0x1E45 => 0x1E44, 0x1E47 => 0x1E46, 0x1E49 => 0x1E48, 0x1E4B => 0x1E4A, 0x1E4D => 0x1E4C, 0x1E4F => 0x1E4E, 0x1E51 => 0x1E50, 0x1E53 => 0x1E52, 0x1E55 => 0x1E54, 0x1E57 => 0x1E56, 0x1E59 => 0x1E58, 0x1E5B => 0x1E5A, 0x1E5D => 0x1E5C, 0x1E5F => 0x1E5E, 0x1E61 => 0x1E60, 0x1E63 => 0x1E62, 0x1E65 => 0x1E64, 0x1E67 => 0x1E66, 0x1E69 => 0x1E68, 0x1E6B => 0x1E6A, 0x1E6D => 0x1E6C, 0x1E6F => 0x1E6E, 0x1E71 => 0x1E70, 0x1E73 => 0x1E72, 0x1E75 => 0x1E74, 0x1E77 => 0x1E76, 0x1E79 => 0x1E78, 0x1E7B => 0x1E7A, 0x1E7D => 0x1E7C, 0x1E7F => 0x1E7E, 0x1E81 => 0x1E80, 0x1E83 => 0x1E82, 0x1E85 => 0x1E84, 0x1E87 => 0x1E86, 0x1E89 => 0x1E88, 0x1E8B => 0x1E8A, 0x1E8D => 0x1E8C, 0x1E8F => 0x1E8E, 0x1E91 => 0x1E90, 0x1E93 => 0x1E92, 0x1E95 => 0x1E94, 0x1E9B => 0x1E60, 0x1EA1 => 0x1EA0, 0x1EA3 => 0x1EA2, 0x1EA5 => 0x1EA4, 0x1EA7 => 0x1EA6, 0x1EA9 => 0x1EA8, 0x1EAB => 0x1EAA, 0x1EAD => 0x1EAC, 0x1EAF => 0x1EAE, 0x1EB1 => 0x1EB0, 0x1EB3 => 0x1EB2, 0x1EB5 => 0x1EB4, 0x1EB7 => 0x1EB6, 0x1EB9 => 0x1EB8, 0x1EBB => 0x1EBA, 0x1EBD => 0x1EBC, 0x1EBF => 0x1EBE, 0x1EC1 => 0x1EC0, 0x1EC3 => 0x1EC2, 0x1EC5 => 0x1EC4, 0x1EC7 => 0x1EC6, 0x1EC9 => 0x1EC8, 0x1ECB => 0x1ECA, 0x1ECD => 0x1ECC, 0x1ECF => 0x1ECE, 0x1ED1 => 0x1ED0, 0x1ED3 => 0x1ED2, 0x1ED5 => 0x1ED4, 0x1ED7 => 0x1ED6, 0x1ED9 => 0x1ED8, 0x1EDB => 0x1EDA, 0x1EDD => 0x1EDC, 0x1EDF => 0x1EDE, 0x1EE1 => 0x1EE0, 0x1EE3 => 0x1EE2, 0x1EE5 => 0x1EE4, 0x1EE7 => 0x1EE6, 0x1EE9 => 0x1EE8, 0x1EEB => 0x1EEA, 0x1EED => 0x1EEC, 0x1EEF => 0x1EEE, 0x1EF1 => 0x1EF0, 0x1EF3 => 0x1EF2, 0x1EF5 => 0x1EF4, 0x1EF7 => 0x1EF6, 0x1EF9 => 0x1EF8, 0x1EFB => 0x1EFA, 0x1EFD => 0x1EFC, 0x1EFF => 0x1EFE, 0x1F00 => 0x1F08, 0x1F01 => 0x1F09, 0x1F02 => 0x1F0A, 0x1F03 => 0x1F0B, 0x1F04 => 0x1F0C, 0x1F05 => 0x1F0D, 0x1F06 => 0x1F0E, 0x1F07 => 0x1F0F, 0x1F10 => 0x1F18, 0x1F11 => 0x1F19, 0x1F12 => 0x1F1A, 0x1F13 => 0x1F1B, 0x1F14 => 0x1F1C, 0x1F15 => 0x1F1D, 0x1F20 => 0x1F28, 0x1F21 => 0x1F29, 0x1F22 => 0x1F2A, 0x1F23 => 0x1F2B, 0x1F24 => 0x1F2C, 0x1F25 => 0x1F2D, 0x1F26 => 0x1F2E, 0x1F27 => 0x1F2F, 0x1F30 => 0x1F38, 0x1F31 => 0x1F39, 0x1F32 => 0x1F3A, 0x1F33 => 0x1F3B, 0x1F34 => 0x1F3C, 0x1F35 => 0x1F3D, 0x1F36 => 0x1F3E, 0x1F37 => 0x1F3F, 0x1F40 => 0x1F48, 0x1F41 => 0x1F49, 0x1F42 => 0x1F4A, 0x1F43 => 0x1F4B, 0x1F44 => 0x1F4C, 0x1F45 => 0x1F4D, 0x1F51 => 0x1F59, 0x1F53 => 0x1F5B, 0x1F55 => 0x1F5D, 0x1F57 => 0x1F5F, 0x1F60 => 0x1F68, 0x1F61 => 0x1F69, 0x1F62 => 0x1F6A, 0x1F63 => 0x1F6B, 0x1F64 => 0x1F6C, 0x1F65 => 0x1F6D, 0x1F66 => 0x1F6E, 0x1F67 => 0x1F6F, 0x1F70 => 0x1FBA, 0x1F71 => 0x1FBB, 0x1F72 => 0x1FC8, 0x1F73 => 0x1FC9, 0x1F74 => 0x1FCA, 0x1F75 => 0x1FCB, 0x1F76 => 0x1FDA, 0x1F77 => 0x1FDB, 0x1F78 => 0x1FF8, 0x1F79 => 0x1FF9, 0x1F7A => 0x1FEA, 0x1F7B => 0x1FEB, 0x1F7C => 0x1FFA, 0x1F7D => 0x1FFB, 0x1F80 => 0x1F88, 0x1F81 => 0x1F89, 0x1F82 => 0x1F8A, 0x1F83 => 0x1F8B, 0x1F84 => 0x1F8C, 0x1F85 => 0x1F8D, 0x1F86 => 0x1F8E, 0x1F87 => 0x1F8F, 0x1F90 => 0x1F98, 0x1F91 => 0x1F99, 0x1F92 => 0x1F9A, 0x1F93 => 0x1F9B, 0x1F94 => 0x1F9C, 0x1F95 => 0x1F9D, 0x1F96 => 0x1F9E, 0x1F97 => 0x1F9F, 0x1FA0 => 0x1FA8, 0x1FA1 => 0x1FA9, 0x1FA2 => 0x1FAA, 0x1FA3 => 0x1FAB, 0x1FA4 => 0x1FAC, 0x1FA5 => 0x1FAD, 0x1FA6 => 0x1FAE, 0x1FA7 => 0x1FAF, 0x1FB0 => 0x1FB8, 0x1FB1 => 0x1FB9, 0x1FB3 => 0x1FBC, 0x1FBE => 0x399, 0x1FC3 => 0x1FCC, 0x1FD0 => 0x1FD8, 0x1FD1 => 0x1FD9, 0x1FE0 => 0x1FE8, 0x1FE1 => 0x1FE9, 0x1FE5 => 0x1FEC, 0x1FF3 => 0x1FFC, 0x214E => 0x2132, 0x2170 => 0x2160, 0x2171 => 0x2161, 0x2172 => 0x2162, 0x2173 => 0x2163, 0x2174 => 0x2164, 0x2175 => 0x2165, 0x2176 => 0x2166, 0x2177 => 0x2167, 0x2178 => 0x2168, 0x2179 => 0x2169, 0x217A => 0x216A, 0x217B => 0x216B, 0x217C => 0x216C, 0x217D => 0x216D, 0x217E => 0x216E, 0x217F => 0x216F, 0x2184 => 0x2183, 0x24D0 => 0x24B6, 0x24D1 => 0x24B7, 0x24D2 => 0x24B8, 0x24D3 => 0x24B9, 0x24D4 => 0x24BA, 0x24D5 => 0x24BB, 0x24D6 => 0x24BC, 0x24D7 => 0x24BD, 0x24D8 => 0x24BE, 0x24D9 => 0x24BF, 0x24DA => 0x24C0, 0x24DB => 0x24C1, 0x24DC => 0x24C2, 0x24DD => 0x24C3, 0x24DE => 0x24C4, 0x24DF => 0x24C5, 0x24E0 => 0x24C6, 0x24E1 => 0x24C7, 0x24E2 => 0x24C8, 0x24E3 => 0x24C9, 0x24E4 => 0x24CA, 0x24E5 => 0x24CB, 0x24E6 => 0x24CC, 0x24E7 => 0x24CD, 0x24E8 => 0x24CE, 0x24E9 => 0x24CF, 0x2C30 => 0x2C00, 0x2C31 => 0x2C01, 0x2C32 => 0x2C02, 0x2C33 => 0x2C03, 0x2C34 => 0x2C04, 0x2C35 => 0x2C05, 0x2C36 => 0x2C06, 0x2C37 => 0x2C07, 0x2C38 => 0x2C08, 0x2C39 => 0x2C09, 0x2C3A => 0x2C0A, 0x2C3B => 0x2C0B, 0x2C3C => 0x2C0C, 0x2C3D => 0x2C0D, 0x2C3E => 0x2C0E, 0x2C3F => 0x2C0F, 0x2C40 => 0x2C10, 0x2C41 => 0x2C11, 0x2C42 => 0x2C12, 0x2C43 => 0x2C13, 0x2C44 => 0x2C14, 0x2C45 => 0x2C15, 0x2C46 => 0x2C16, 0x2C47 => 0x2C17, 0x2C48 => 0x2C18, 0x2C49 => 0x2C19, 0x2C4A => 0x2C1A, 0x2C4B => 0x2C1B, 0x2C4C => 0x2C1C, 0x2C4D => 0x2C1D, 0x2C4E => 0x2C1E, 0x2C4F => 0x2C1F, 0x2C50 => 0x2C20, 0x2C51 => 0x2C21, 0x2C52 => 0x2C22, 0x2C53 => 0x2C23, 0x2C54 => 0x2C24, 0x2C55 => 0x2C25, 0x2C56 => 0x2C26, 0x2C57 => 0x2C27, 0x2C58 => 0x2C28, 0x2C59 => 0x2C29, 0x2C5A => 0x2C2A, 0x2C5B => 0x2C2B, 0x2C5C => 0x2C2C, 0x2C5D => 0x2C2D, 0x2C5E => 0x2C2E, 0x2C5F => 0x2C2F, 0x2C61 => 0x2C60, 0x2C65 => 0x23A, 0x2C66 => 0x23E, 0x2C68 => 0x2C67, 0x2C6A => 0x2C69, 0x2C6C => 0x2C6B, 0x2C73 => 0x2C72, 0x2C76 => 0x2C75, 0x2C81 => 0x2C80, 0x2C83 => 0x2C82, 0x2C85 => 0x2C84, 0x2C87 => 0x2C86, 0x2C89 => 0x2C88, 0x2C8B => 0x2C8A, 0x2C8D => 0x2C8C, 0x2C8F => 0x2C8E, 0x2C91 => 0x2C90, 0x2C93 => 0x2C92, 0x2C95 => 0x2C94, 0x2C97 => 0x2C96, 0x2C99 => 0x2C98, 0x2C9B => 0x2C9A, 0x2C9D => 0x2C9C, 0x2C9F => 0x2C9E, 0x2CA1 => 0x2CA0, 0x2CA3 => 0x2CA2, 0x2CA5 => 0x2CA4, 0x2CA7 => 0x2CA6, 0x2CA9 => 0x2CA8, 0x2CAB => 0x2CAA, 0x2CAD => 0x2CAC, 0x2CAF => 0x2CAE, 0x2CB1 => 0x2CB0, 0x2CB3 => 0x2CB2, 0x2CB5 => 0x2CB4, 0x2CB7 => 0x2CB6, 0x2CB9 => 0x2CB8, 0x2CBB => 0x2CBA, 0x2CBD => 0x2CBC, 0x2CBF => 0x2CBE, 0x2CC1 => 0x2CC0, 0x2CC3 => 0x2CC2, 0x2CC5 => 0x2CC4, 0x2CC7 => 0x2CC6, 0x2CC9 => 0x2CC8, 0x2CCB => 0x2CCA, 0x2CCD => 0x2CCC, 0x2CCF => 0x2CCE, 0x2CD1 => 0x2CD0, 0x2CD3 => 0x2CD2, 0x2CD5 => 0x2CD4, 0x2CD7 => 0x2CD6, 0x2CD9 => 0x2CD8, 0x2CDB => 0x2CDA, 0x2CDD => 0x2CDC, 0x2CDF => 0x2CDE, 0x2CE1 => 0x2CE0, 0x2CE3 => 0x2CE2, 0x2CEC => 0x2CEB, 0x2CEE => 0x2CED, 0x2CF3 => 0x2CF2, 0x2D00 => 0x10A0, 0x2D01 => 0x10A1, 0x2D02 => 0x10A2, 0x2D03 => 0x10A3, 0x2D04 => 0x10A4, 0x2D05 => 0x10A5, 0x2D06 => 0x10A6, 0x2D07 => 0x10A7, 0x2D08 => 0x10A8, 0x2D09 => 0x10A9, 0x2D0A => 0x10AA, 0x2D0B => 0x10AB, 0x2D0C => 0x10AC, 0x2D0D => 0x10AD, 0x2D0E => 0x10AE, 0x2D0F => 0x10AF, 0x2D10 => 0x10B0, 0x2D11 => 0x10B1, 0x2D12 => 0x10B2, 0x2D13 => 0x10B3, 0x2D14 => 0x10B4, 0x2D15 => 0x10B5, 0x2D16 => 0x10B6, 0x2D17 => 0x10B7, 0x2D18 => 0x10B8, 0x2D19 => 0x10B9, 0x2D1A => 0x10BA, 0x2D1B => 0x10BB, 0x2D1C => 0x10BC, 0x2D1D => 0x10BD, 0x2D1E => 0x10BE, 0x2D1F => 0x10BF, 0x2D20 => 0x10C0, 0x2D21 => 0x10C1, 0x2D22 => 0x10C2, 0x2D23 => 0x10C3, 0x2D24 => 0x10C4, 0x2D25 => 0x10C5, 0x2D27 => 0x10C7, 0x2D2D => 0x10CD, 0xA641 => 0xA640, 0xA643 => 0xA642, 0xA645 => 0xA644, 0xA647 => 0xA646, 0xA649 => 0xA648, 0xA64B => 0xA64A, 0xA64D => 0xA64C, 0xA64F => 0xA64E, 0xA651 => 0xA650, 0xA653 => 0xA652, 0xA655 => 0xA654, 0xA657 => 0xA656, 0xA659 => 0xA658, 0xA65B => 0xA65A, 0xA65D => 0xA65C, 0xA65F => 0xA65E, 0xA661 => 0xA660, 0xA663 => 0xA662, 0xA665 => 0xA664, 0xA667 => 0xA666, 0xA669 => 0xA668, 0xA66B => 0xA66A, 0xA66D => 0xA66C, 0xA681 => 0xA680, 0xA683 => 0xA682, 0xA685 => 0xA684, 0xA687 => 0xA686, 0xA689 => 0xA688, 0xA68B => 0xA68A, 0xA68D => 0xA68C, 0xA68F => 0xA68E, 0xA691 => 0xA690, 0xA693 => 0xA692, 0xA695 => 0xA694, 0xA697 => 0xA696, 0xA699 => 0xA698, 0xA69B => 0xA69A, 0xA723 => 0xA722, 0xA725 => 0xA724, 0xA727 => 0xA726, 0xA729 => 0xA728, 0xA72B => 0xA72A, 0xA72D => 0xA72C, 0xA72F => 0xA72E, 0xA733 => 0xA732, 0xA735 => 0xA734, 0xA737 => 0xA736, 0xA739 => 0xA738, 0xA73B => 0xA73A, 0xA73D => 0xA73C, 0xA73F => 0xA73E, 0xA741 => 0xA740, 0xA743 => 0xA742, 0xA745 => 0xA744, 0xA747 => 0xA746, 0xA749 => 0xA748, 0xA74B => 0xA74A, 0xA74D => 0xA74C, 0xA74F => 0xA74E, 0xA751 => 0xA750, 0xA753 => 0xA752, 0xA755 => 0xA754, 0xA757 => 0xA756, 0xA759 => 0xA758, 0xA75B => 0xA75A, 0xA75D => 0xA75C, 0xA75F => 0xA75E, 0xA761 => 0xA760, 0xA763 => 0xA762, 0xA765 => 0xA764, 0xA767 => 0xA766, 0xA769 => 0xA768, 0xA76B => 0xA76A, 0xA76D => 0xA76C, 0xA76F => 0xA76E, 0xA77A => 0xA779, 0xA77C => 0xA77B, 0xA77F => 0xA77E, 0xA781 => 0xA780, 0xA783 => 0xA782, 0xA785 => 0xA784, 0xA787 => 0xA786, 0xA78C => 0xA78B, 0xA791 => 0xA790, 0xA793 => 0xA792, 0xA794 => 0xA7C4, 0xA797 => 0xA796, 0xA799 => 0xA798, 0xA79B => 0xA79A, 0xA79D => 0xA79C, 0xA79F => 0xA79E, 0xA7A1 => 0xA7A0, 0xA7A3 => 0xA7A2, 0xA7A5 => 0xA7A4, 0xA7A7 => 0xA7A6, 0xA7A9 => 0xA7A8, 0xA7B5 => 0xA7B4, 0xA7B7 => 0xA7B6, 0xA7B9 => 0xA7B8, 0xA7BB => 0xA7BA, 0xA7BD => 0xA7BC, 0xA7BF => 0xA7BE, 0xA7C1 => 0xA7C0, 0xA7C3 => 0xA7C2, 0xA7C8 => 0xA7C7, 0xA7CA => 0xA7C9, 0xA7D1 => 0xA7D0, 0xA7D7 => 0xA7D6, 0xA7D9 => 0xA7D8, 0xA7F6 => 0xA7F5, 0xAB53 => 0xA7B3, 0xAB70 => 0x13A0, 0xAB71 => 0x13A1, 0xAB72 => 0x13A2, 0xAB73 => 0x13A3, 0xAB74 => 0x13A4, 0xAB75 => 0x13A5, 0xAB76 => 0x13A6, 0xAB77 => 0x13A7, 0xAB78 => 0x13A8, 0xAB79 => 0x13A9, 0xAB7A => 0x13AA, 0xAB7B => 0x13AB, 0xAB7C => 0x13AC, 0xAB7D => 0x13AD, 0xAB7E => 0x13AE, 0xAB7F => 0x13AF, 0xAB80 => 0x13B0, 0xAB81 => 0x13B1, 0xAB82 => 0x13B2, 0xAB83 => 0x13B3, 0xAB84 => 0x13B4, 0xAB85 => 0x13B5, 0xAB86 => 0x13B6, 0xAB87 => 0x13B7, 0xAB88 => 0x13B8, 0xAB89 => 0x13B9, 0xAB8A => 0x13BA, 0xAB8B => 0x13BB, 0xAB8C => 0x13BC, 0xAB8D => 0x13BD, 0xAB8E => 0x13BE, 0xAB8F => 0x13BF, 0xAB90 => 0x13C0, 0xAB91 => 0x13C1, 0xAB92 => 0x13C2, 0xAB93 => 0x13C3, 0xAB94 => 0x13C4, 0xAB95 => 0x13C5, 0xAB96 => 0x13C6, 0xAB97 => 0x13C7, 0xAB98 => 0x13C8, 0xAB99 => 0x13C9, 0xAB9A => 0x13CA, 0xAB9B => 0x13CB, 0xAB9C => 0x13CC, 0xAB9D => 0x13CD, 0xAB9E => 0x13CE, 0xAB9F => 0x13CF, 0xABA0 => 0x13D0, 0xABA1 => 0x13D1, 0xABA2 => 0x13D2, 0xABA3 => 0x13D3, 0xABA4 => 0x13D4, 0xABA5 => 0x13D5, 0xABA6 => 0x13D6, 0xABA7 => 0x13D7, 0xABA8 => 0x13D8, 0xABA9 => 0x13D9, 0xABAA => 0x13DA, 0xABAB => 0x13DB, 0xABAC => 0x13DC, 0xABAD => 0x13DD, 0xABAE => 0x13DE, 0xABAF => 0x13DF, 0xABB0 => 0x13E0, 0xABB1 => 0x13E1, 0xABB2 => 0x13E2, 0xABB3 => 0x13E3, 0xABB4 => 0x13E4, 0xABB5 => 0x13E5, 0xABB6 => 0x13E6, 0xABB7 => 0x13E7, 0xABB8 => 0x13E8, 0xABB9 => 0x13E9, 0xABBA => 0x13EA, 0xABBB => 0x13EB, 0xABBC => 0x13EC, 0xABBD => 0x13ED, 0xABBE => 0x13EE, 0xABBF => 0x13EF, 0xFF41 => 0xFF21, 0xFF42 => 0xFF22, 0xFF43 => 0xFF23, 0xFF44 => 0xFF24, 0xFF45 => 0xFF25, 0xFF46 => 0xFF26, 0xFF47 => 0xFF27, 0xFF48 => 0xFF28, 0xFF49 => 0xFF29, 0xFF4A => 0xFF2A, 0xFF4B => 0xFF2B, 0xFF4C => 0xFF2C, 0xFF4D => 0xFF2D, 0xFF4E => 0xFF2E, 0xFF4F => 0xFF2F, 0xFF50 => 0xFF30, 0xFF51 => 0xFF31, 0xFF52 => 0xFF32, 0xFF53 => 0xFF33, 0xFF54 => 0xFF34, 0xFF55 => 0xFF35, 0xFF56 => 0xFF36, 0xFF57 => 0xFF37, 0xFF58 => 0xFF38, 0xFF59 => 0xFF39, 0xFF5A => 0xFF3A, 0x10428 => 0x10400, 0x10429 => 0x10401, 0x1042A => 0x10402, 0x1042B => 0x10403, 0x1042C => 0x10404, 0x1042D => 0x10405, 0x1042E => 0x10406, 0x1042F => 0x10407, 0x10430 => 0x10408, 0x10431 => 0x10409, 0x10432 => 0x1040A, 0x10433 => 0x1040B, 0x10434 => 0x1040C, 0x10435 => 0x1040D, 0x10436 => 0x1040E, 0x10437 => 0x1040F, 0x10438 => 0x10410, 0x10439 => 0x10411, 0x1043A => 0x10412, 0x1043B => 0x10413, 0x1043C => 0x10414, 0x1043D => 0x10415, 0x1043E => 0x10416, 0x1043F => 0x10417, 0x10440 => 0x10418, 0x10441 => 0x10419, 0x10442 => 0x1041A, 0x10443 => 0x1041B, 0x10444 => 0x1041C, 0x10445 => 0x1041D, 0x10446 => 0x1041E, 0x10447 => 0x1041F, 0x10448 => 0x10420, 0x10449 => 0x10421, 0x1044A => 0x10422, 0x1044B => 0x10423, 0x1044C => 0x10424, 0x1044D => 0x10425, 0x1044E => 0x10426, 0x1044F => 0x10427, 0x104D8 => 0x104B0, 0x104D9 => 0x104B1, 0x104DA => 0x104B2, 0x104DB => 0x104B3, 0x104DC => 0x104B4, 0x104DD => 0x104B5, 0x104DE => 0x104B6, 0x104DF => 0x104B7, 0x104E0 => 0x104B8, 0x104E1 => 0x104B9, 0x104E2 => 0x104BA, 0x104E3 => 0x104BB, 0x104E4 => 0x104BC, 0x104E5 => 0x104BD, 0x104E6 => 0x104BE, 0x104E7 => 0x104BF, 0x104E8 => 0x104C0, 0x104E9 => 0x104C1, 0x104EA => 0x104C2, 0x104EB => 0x104C3, 0x104EC => 0x104C4, 0x104ED => 0x104C5, 0x104EE => 0x104C6, 0x104EF => 0x104C7, 0x104F0 => 0x104C8, 0x104F1 => 0x104C9, 0x104F2 => 0x104CA, 0x104F3 => 0x104CB, 0x104F4 => 0x104CC, 0x104F5 => 0x104CD, 0x104F6 => 0x104CE, 0x104F7 => 0x104CF, 0x104F8 => 0x104D0, 0x104F9 => 0x104D1, 0x104FA => 0x104D2, 0x104FB => 0x104D3, 0x10597 => 0x10570, 0x10598 => 0x10571, 0x10599 => 0x10572, 0x1059A => 0x10573, 0x1059B => 0x10574, 0x1059C => 0x10575, 0x1059D => 0x10576, 0x1059E => 0x10577, 0x1059F => 0x10578, 0x105A0 => 0x10579, 0x105A1 => 0x1057A, 0x105A3 => 0x1057C, 0x105A4 => 0x1057D, 0x105A5 => 0x1057E, 0x105A6 => 0x1057F, 0x105A7 => 0x10580, 0x105A8 => 0x10581, 0x105A9 => 0x10582, 0x105AA => 0x10583, 0x105AB => 0x10584, 0x105AC => 0x10585, 0x105AD => 0x10586, 0x105AE => 0x10587, 0x105AF => 0x10588, 0x105B0 => 0x10589, 0x105B1 => 0x1058A, 0x105B3 => 0x1058C, 0x105B4 => 0x1058D, 0x105B5 => 0x1058E, 0x105B6 => 0x1058F, 0x105B7 => 0x10590, 0x105B8 => 0x10591, 0x105B9 => 0x10592, 0x105BB => 0x10594, 0x105BC => 0x10595, 0x10CC0 => 0x10C80, 0x10CC1 => 0x10C81, 0x10CC2 => 0x10C82, 0x10CC3 => 0x10C83, 0x10CC4 => 0x10C84, 0x10CC5 => 0x10C85, 0x10CC6 => 0x10C86, 0x10CC7 => 0x10C87, 0x10CC8 => 0x10C88, 0x10CC9 => 0x10C89, 0x10CCA => 0x10C8A, 0x10CCB => 0x10C8B, 0x10CCC => 0x10C8C, 0x10CCD => 0x10C8D, 0x10CCE => 0x10C8E, 0x10CCF => 0x10C8F, 0x10CD0 => 0x10C90, 0x10CD1 => 0x10C91, 0x10CD2 => 0x10C92, 0x10CD3 => 0x10C93, 0x10CD4 => 0x10C94, 0x10CD5 => 0x10C95, 0x10CD6 => 0x10C96, 0x10CD7 => 0x10C97, 0x10CD8 => 0x10C98, 0x10CD9 => 0x10C99, 0x10CDA => 0x10C9A, 0x10CDB => 0x10C9B, 0x10CDC => 0x10C9C, 0x10CDD => 0x10C9D, 0x10CDE => 0x10C9E, 0x10CDF => 0x10C9F, 0x10CE0 => 0x10CA0, 0x10CE1 => 0x10CA1, 0x10CE2 => 0x10CA2, 0x10CE3 => 0x10CA3, 0x10CE4 => 0x10CA4, 0x10CE5 => 0x10CA5, 0x10CE6 => 0x10CA6, 0x10CE7 => 0x10CA7, 0x10CE8 => 0x10CA8, 0x10CE9 => 0x10CA9, 0x10CEA => 0x10CAA, 0x10CEB => 0x10CAB, 0x10CEC => 0x10CAC, 0x10CED => 0x10CAD, 0x10CEE => 0x10CAE, 0x10CEF => 0x10CAF, 0x10CF0 => 0x10CB0, 0x10CF1 => 0x10CB1, 0x10CF2 => 0x10CB2, 0x118C0 => 0x118A0, 0x118C1 => 0x118A1, 0x118C2 => 0x118A2, 0x118C3 => 0x118A3, 0x118C4 => 0x118A4, 0x118C5 => 0x118A5, 0x118C6 => 0x118A6, 0x118C7 => 0x118A7, 0x118C8 => 0x118A8, 0x118C9 => 0x118A9, 0x118CA => 0x118AA, 0x118CB => 0x118AB, 0x118CC => 0x118AC, 0x118CD => 0x118AD, 0x118CE => 0x118AE, 0x118CF => 0x118AF, 0x118D0 => 0x118B0, 0x118D1 => 0x118B1, 0x118D2 => 0x118B2, 0x118D3 => 0x118B3, 0x118D4 => 0x118B4, 0x118D5 => 0x118B5, 0x118D6 => 0x118B6, 0x118D7 => 0x118B7, 0x118D8 => 0x118B8, 0x118D9 => 0x118B9, 0x118DA => 0x118BA, 0x118DB => 0x118BB, 0x118DC => 0x118BC, 0x118DD => 0x118BD, 0x118DE => 0x118BE, 0x118DF => 0x118BF, 0x16E60 => 0x16E40, 0x16E61 => 0x16E41, 0x16E62 => 0x16E42, 0x16E63 => 0x16E43, 0x16E64 => 0x16E44, 0x16E65 => 0x16E45, 0x16E66 => 0x16E46, 0x16E67 => 0x16E47, 0x16E68 => 0x16E48, 0x16E69 => 0x16E49, 0x16E6A => 0x16E4A, 0x16E6B => 0x16E4B, 0x16E6C => 0x16E4C, 0x16E6D => 0x16E4D, 0x16E6E => 0x16E4E, 0x16E6F => 0x16E4F, 0x16E70 => 0x16E50, 0x16E71 => 0x16E51, 0x16E72 => 0x16E52, 0x16E73 => 0x16E53, 0x16E74 => 0x16E54, 0x16E75 => 0x16E55, 0x16E76 => 0x16E56, 0x16E77 => 0x16E57, 0x16E78 => 0x16E58, 0x16E79 => 0x16E59, 0x16E7A => 0x16E5A, 0x16E7B => 0x16E5B, 0x16E7C => 0x16E5C, 0x16E7D => 0x16E5D, 0x16E7E => 0x16E5E, 0x16E7F => 0x16E5F, 0x1E922 => 0x1E900, 0x1E923 => 0x1E901, 0x1E924 => 0x1E902, 0x1E925 => 0x1E903, 0x1E926 => 0x1E904, 0x1E927 => 0x1E905, 0x1E928 => 0x1E906, 0x1E929 => 0x1E907, 0x1E92A => 0x1E908, 0x1E92B => 0x1E909, 0x1E92C => 0x1E90A, 0x1E92D => 0x1E90B, 0x1E92E => 0x1E90C, 0x1E92F => 0x1E90D, 0x1E930 => 0x1E90E, 0x1E931 => 0x1E90F, 0x1E932 => 0x1E910, 0x1E933 => 0x1E911, 0x1E934 => 0x1E912, 0x1E935 => 0x1E913, 0x1E936 => 0x1E914, 0x1E937 => 0x1E915, 0x1E938 => 0x1E916, 0x1E939 => 0x1E917, 0x1E93A => 0x1E918, 0x1E93B => 0x1E919, 0x1E93C => 0x1E91A, 0x1E93D => 0x1E91B, 0x1E93E => 0x1E91C, 0x1E93F => 0x1E91D, 0x1E940 => 0x1E91E, 0x1E941 => 0x1E91F, 0x1E942 => 0x1E920, 0x1E943 => 0x1E921, else => cp, }; }
src/components/autogen/UpperMap.zig
const std = @import("std"); const zlaap = @import("zlaap"); /// A single namespace unit. Can fit 5 or 6 characters of a limited character set. pub const Namespace = struct { /// The most significant bit determines which character encoding is used. bits: u31, /// Alphabetic encoding encodes exactly 6 characters matching [a-z _.-]. /// Alphanumeric encoding encodes 1 to 5 characters matching [a-z0-9 _.-]. pub const Encoding = enum(u1) { alphabetic = 0, alphanumeric = 1, }; /// Return which encoding is used by this namespace. pub fn encoding(self: Namespace) Encoding { const alphanumeric = self.bits & (0b1 << 30) != 0; return @intToEnum(Encoding, @boolToInt(alphanumeric)); } /// Encode up to 6 characters from the given slice, returning an error if /// any of the bytes are not part of the valid character set. Caller asserts /// that the input slice has at least one character in it. pub fn encode(input: []const u8) error{InvalidEncoding}!Namespace { var slice = input; return (try encodeNext(&slice)) orelse error.InvalidEncoding; } /// Encode up to 6 characters from the given slice, returning null if the /// slice is empty, or an error if any of the bytes are not part of the /// valid character set. The input slice will be updated automatically, /// allowing this function to be called repeatedly in a `while` loop. pub fn encodeNext(input: *[]const u8) error{InvalidEncoding}!?Namespace { // Initialize the slice of characters we are to encode. var slice = switch (input.len) { 0 => return null, 1...5 => input.*, else => input.*[0..6], }; // Encode each character in the input string. var alphanumeric = slice.len < 6; var buf = [_]u8{0} ** 6; for (slice) |c, i| switch (c) { // Encode alphabetic characters into the range 1...26. 'A'...'Z' => buf[i] = c - 'A' + 1, 'a'...'z' => buf[i] = c - 'a' + 1, // Encode numeric characters into the range 31...40. '0'...'9' => { buf[i] = c - '0' + 31; alphanumeric = true; }, // Encode special characters into the range 27...30. ' ' => buf[i] = 27, '_' => buf[i] = 28, '-' => buf[i] = 29, '.' => buf[i] = 30, // Return an error if the character doesn't fit in this encoding. else => return error.InvalidEncoding, }; // Pack the encoded characters into an unsigned 31 bit integer. if (alphanumeric) { var bits: u32 = buf[0]; for (buf[1..5]) |c| { bits <<= 6; bits |= c; } bits |= 0b1 << 30; input.* = input.*[std.math.min(5, slice.len)..]; return Namespace{ .bits = @intCast(u31, bits) }; } else { var bits: u32 = buf[0]; for (buf[1..6]) |c| { bits <<= 5; bits |= c; } input.* = input.*[6..]; return Namespace{ .bits = @intCast(u31, bits) }; } } /// Decode a namespace into the target slice. Return an error if the bits /// could not have possibly been generated by this encoder. pub fn decode( self: Namespace, output: *[6]u8, ) error{InvalidEncoding}![]u8 { if (self.encoding() == .alphanumeric) { var i: usize = 5; var bits = @truncate(u30, self.bits); while (@truncate(u6, bits) == 0) { if (i == 1) return error.InvalidEncoding; i -= 1; bits >>= 6; } const result = output[0..i]; while (i > 0) { i -= 1; result[i] = switch (@truncate(u6, bits)) { 1...26 => |x| @as(u8, x - 1) + 'a', 31...40 => |x| @as(u8, x - 31) + '0', 27 => ' ', 28 => '_', 29 => '-', 30 => '.', else => return error.InvalidEncoding, }; bits >>= 6; } return result; } else { var bits = @intCast(u30, self.bits); var i: usize = 6; while (i > 0) { i -= 1; output[i] = switch (@truncate(u5, bits)) { 1...26 => |x| @as(u8, x - 1) + 'a', 27 => ' ', 28 => '_', 29 => '-', 30 => '.', else => return error.InvalidEncoding, }; bits >>= 5; } return output; } } /// Create a TextView into the Namespace. The iteration functionality of /// a TextView is unlikely to be useful, but the TextView also implements /// formatting APIs, making it trivial to use `std.log` and `writer.print`. pub fn textView(self: *const Namespace) TextView(true) { const as_array: *const [1]Namespace = self; return .{ .items = as_array, .buf = undefined, }; } /// Format the namespace value into a translation string. /// Best used via 'printer' APIs such as `writer.print` and `std.log`. pub fn format( self: Namespace, comptime fmt: []const u8, options: std.fmt.FormatOptions, writer: anytype, ) !void { try writer.print("%{}$s", .{self.bits}); } /// Parse a translation string back into a namespace. The provided slice must /// have exactly one translation string. Use `parseNext` for more flexibility. pub fn parse(string: []const u8) error{InvalidEncoding}!Namespace { return parseInternal(Mode.one, string); } /// Read a translation string into a namespace, then advance the /// pointer past the text. Returns null if the string is empty. pub fn parseNext(string: *[]const u8) error{InvalidEncoding}!?Namespace { return parseInternal(Mode.next, string); } /// Read a translation strings into a namespace, ignoring any characters that /// are clearly not translation strings. Returns null if the string is empty. pub fn parseLossy(string: *[]const u8) error{InvalidEncoding}!?Namespace { return parseInternal(Mode.lossy, string); } /// Underlying implementation for `parse`, `parseNext`, and `parseLossy`. const Mode = enum { one, next, lossy }; fn parseInternal( comptime mode: Mode, string: if (mode == .one) []const u8 else *[]const u8, ) error{InvalidEncoding}!(if (mode == .one) Namespace else ?Namespace) { var slice = if (mode == .one) string else string.*; outer: while (slice.len >= 4) : (slice = slice[1..]) { // Each translation string starts with a `%` character. if (slice[0] != '%') { if (mode == .lossy) continue :outer; return error.InvalidEncoding; } // Initialize our bits value by reading the first digit. var bits: u31 = switch (slice[1]) { '1'...'9' => |x| @intCast(u31, x - '0'), else => if (mode == .lossy) continue :outer else break :outer, }; // Parse the rest of the translation string into the namespace. slice = slice[2..]; while (slice.len > 0) : (slice = slice[1..]) { switch (slice[0]) { '0'...'9' => |x| { // We treat integer overflow as a hard error even in lossy mode. // It's clear even in lossy mode that this is supposed to be a // translation string, but the integer was too large. This is an // error we need to report instead silently ignoring. const n = @intCast(u31, x - '0'); bits = std.math.mul(u31, bits, 10) catch break; bits = std.math.add(u31, bits, n) catch break; }, '$' => { // `.one` is for exact matches, so we reject any trailing characters // in that mode. In other modes, trailing characters are irrelevant. const badlen = if (mode == .one) slice.len != 2 else slice.len < 2; // Toss out this translation string if it's missing the `s` or is // an incorrect length for the selected mode. if (badlen or slice[1] != 's') { if (mode != .lossy) break; continue :outer; } // Update the slice we're iterating and return the namespace unit. if (mode != .one) string.* = slice[2..]; return Namespace{ .bits = bits }; }, else => { if (mode != .lossy) break; continue :outer; }, } } return error.InvalidEncoding; } // This codepath is reached if no value was found. Each mode handles this // case differently (this is, in fact, why the modes exist). switch (mode) { .lossy => string.* = slice[slice.len..], .next => if (string.len > 0) return error.InvalidEncoding, .one => return error.InvalidEncoding, } return null; } }; /// A string of namespace units; used as an intermediary between raw text and /// series of translation strings. Convenient for conversion between raw argument /// strings provided by the OS and useful values that can be formatted or decoded. pub const NamespaceString = struct { /// Iteration and modification of this field is permitted. items: []Namespace, /// ArrayList used in the initialization process. const List = std.ArrayListUnmanaged(Namespace); /// Create a NamespaceString by parsing a string formed of characters /// conforming to the regex [A-Za-z0-9 _.-]. This function will allocate /// memory (likely a smaller amount than the input string consumes). /// Caller is responsible for calling `deinit` to deallocate the string. pub fn encodeAll( allocator: *std.mem.Allocator, string: []const u8, ) error{ OutOfMemory, InvalidEncoding }!NamespaceString { // Initialize a buffer with the capacity to hold the full namespace string. const capacity = std.math.divCeil(usize, string.len, 5) catch unreachable; var buf = try List.initCapacity(allocator, capacity); errdefer buf.deinit(allocator); // Convert the text we were passed into a namespace string. var slice = string; while (try Namespace.encodeNext(&slice)) |n| buf.appendAssumeCapacity(n); return NamespaceString{ .items = buf.toOwnedSlice(allocator) }; } /// Create a NamespaceString by parsing a string formed of translated strings /// obtained by previously formatting a Namespace or NamespaceString. This then /// facilitates the retrieval of the original text used to create the namespace. /// Caller is responsible for calling `deinit` to deallocate the string. pub fn parseAll( allocator: *std.mem.Allocator, string: []const u8, ) error{ OutOfMemory, InvalidEncoding }!NamespaceString { return parseInternal(allocator, string, Namespace.parseNext); } /// Create a NamespaceString by parsing a string formed of translated strings /// obtained by previously formatting a Namespace or NamespaceString. Any /// characters that are clearly not part of a translation string are ignored. /// Caller is responsible for calling `deinit` to deallocate the string. pub fn parseLossy( allocator: *std.mem.Allocator, string: []const u8, ) error{ OutOfMemory, InvalidEncoding }!NamespaceString { return parseInternal(allocator, string, Namespace.parseLossy); } /// Underlying implementation for `parseAll` and `parseLossy`. fn parseInternal( allocator: *std.mem.Allocator, string: []const u8, comptime next: anytype, ) error{ OutOfMemory, InvalidEncoding }!NamespaceString { // Initialize a buffer to hold the decoded namepsace string. var buf = List{}; errdefer buf.deinit(allocator); // Convert the translation strings we were passed into a namespace string. var slice = string; while (try next(&slice)) |n| try buf.append(allocator, n); return NamespaceString{ .items = buf.toOwnedSlice(allocator) }; } /// Free memory allocated by `fromText` or `fromTranslationString`. pub fn deinit(self: NamespaceString, allocator: *std.mem.Allocator) void { allocator.free(self.items); } /// Create a TextView into the NamespaceString. TextViews serve as iterators /// over decoded fragments of the NamespaceString, but they also implement /// the formatting APIs, making conversion into textual form very simple. /// /// If `strict` is true, `.next()` and `.format()` will return an error upon /// encountering a value that is impossible to `.decode()`. If `strict` is /// false, any such values will simply be skipped. A value of false is useful /// to skip over "real" substitution strings such as `%1$s`; instead only /// printing the subsitution strings that form an encoded namespace. pub fn textView(self: NamespaceString, comptime strict: bool) TextView(strict) { return .{ .items = self.items, .buf = undefined, }; } /// Format the namespace string into a series of translation strings. /// Best used via 'printer' APIs such as `writer.print` and `std.log`. pub fn format( self: NamespaceString, comptime fmt: []const u8, options: std.fmt.FormatOptions, writer: anytype, ) !void { for (self.items) |item| try writer.print("%{}$s", .{item.bits}); } }; /// An iterator over a series of namespaces in decoded text form. Strings returned /// via iteration will be short (between 1 and 6 characters). To make this type a /// bit more useful, it also implements the stdlib formatting API, meaning that /// utilities like `std.log`, `writer.print`, and `bufPrint` all work on TextView. /// /// To create a TextView, call `textView` on a Namespace or NamespaceString. The /// TextView does not allocate or own memory; its lifetime is tied to the Namespace /// or NamespaceString used to construct it. This allows convenient usage such as: /// /// ``` /// std.log.info("{}", .{namespace.textView(true)}); /// ``` pub fn TextView(comptime strict: bool) type { return struct { /// The set of namespace strings to iterate over. items: []const Namespace, /// Temporary buffer for the decoded text. buf: [6]u8, /// In strict mode, errors are propagated through the writer and iterator. /// Otherwise, iteration simply skips them; this is useful for skipping the /// initial `%1$s` commonly seen in practical usage of the namespace trick. const Next = if (strict) error{InvalidEncoding}!?[]u8 else ?[]u8; const Next2 = if (strict) Next else error{}!Next; /// Decode the text of the next namespace string, or return null if no namespace /// strings remain to decode. The return value is only valid until a subsequent /// call to `next`. Use `allocator.dupe` to save the text for longer. pub fn next(self: *@This()) Next { while (self.items.len > 0) { defer self.items = self.items[1..]; return self.items[0].decode(&self.buf) catch |err| { if (strict) return err else continue; }; } else return null; } /// Format the namespace string into its original, textual form. /// Best used via "printer" APIs such as `writer.print` and `std.log`. pub fn format( self: @This(), comptime fmt: []const u8, options: std.fmt.FormatOptions, writer: anytype, ) !void { var copy = self; while (try @as(Next2, copy.next())) |text| try writer.writeAll(text); } }; } const Arguments = struct { state: State, fn init(allocator: *std.mem.Allocator) !Arguments { return Arguments{ .state = try State.init(allocator) }; } fn next(self: *Arguments) ?[]const u8 { if (std.builtin.os.tag == .windows) { if (self.state.iterator.decodeNext(.wtf8, self.state.buf[self.state.buf_idx..]) catch unreachable) |result| { self.state.buf_idx += result.len; return result; } else return null; } return self.state.iterator.next() orelse return null; } const State = switch (std.builtin.os.tag) { .windows => struct { iterator: zlaap.WindowsArgIterator, buf_idx: usize = 0, buf: [98304]u8 = undefined, fn init(_: *std.mem.Allocator) !@This() { return @This(){ .iterator = zlaap.WindowsArgIterator.init() }; } }, .wasi => struct { iterator: zlaap.ArgvIterator, buf: zlaap.WasiArgs, fn init(allocator: *std.mem.Allocator) !@This() { var buf = zlaap.WasiArgs{}; const iterator = try buf.iterator(allocator); return @This(){ .iterator = iterator, .buf = buf, }; } }, else => struct { iterator: zlaap.ArgvIterator, fn init(_: *std.mem.Allocator) !@This() { return @This(){ .iterator = zlaap.ArgvIterator.init() }; } }, }; }; fn printUsage(exe: []const u8, status: u8) !void { const stdout = std.io.getStdOut().writer(); try stdout.print( \\transpace - Minecraft Translate Namespace Encoder \\ \\Usage: {} [options] [string] \\Options: \\ -h, --help Print this help and exit \\ -V, --version Print the version number and exit \\ --encode Encode namespace into translation string \\ --decode Decode translation string into namespace \\ , .{exe}); std.process.exit(status); } fn behaviorAlreadySet(exe: []const u8, behavior: []const u8) void { std.log.err( \\behavior already set to `{}` \\See `{} --help` for detailed usage information , .{ behavior, exe }); std.process.exit(1); } pub fn main() !void { var arena = std.heap.ArenaAllocator.init(std.heap.page_allocator); const allocator = &arena.allocator; defer arena.deinit(); // Initialize argv iterator and retrieve executable name. var argv = try Arguments.init(allocator); const exe = argv.next() orelse "transpace"; // Process the list of command line arguments. var end_mark = false; var args: usize = 0; var string: []const u8 = undefined; var behavior: ?enum { encode, decode } = null; var any_args_exist: bool = false; while (argv.next()) |arg| { any_args_exist = true; if (!end_mark and std.mem.startsWith(u8, arg, "-")) { if (std.mem.eql(u8, arg, "-h") or std.mem.eql(u8, arg, "--help")) { try printUsage(exe, 0); } else if (std.mem.eql(u8, arg, "-V") or std.mem.eql(u8, arg, "--version")) { const stdout = std.io.getStdOut(); try stdout.writeAll("0.1.1\n"); std.process.exit(0); } else if (std.mem.eql(u8, arg, "--encode")) { if (behavior) |b| { behaviorAlreadySet(exe, @tagName(b)); } else behavior = .encode; } else if (std.mem.eql(u8, arg, "--decode")) { if (behavior) |b| { behaviorAlreadySet(exe, @tagName(b)); } else behavior = .decode; } else if (std.mem.eql(u8, arg, "--")) { end_mark = true; } else { std.log.err( \\unknown option: {} \\See `{} --help` for detailed usage information , .{ arg, exe }); std.process.exit(1); } } else { string = arg; args += 1; } } else if (!any_args_exist) try printUsage(exe, 1); // Validate the passed arguments. if (args != 1) { std.log.err( \\expected 1 positional argument, found {} \\See `{} --help` for detailed usage information , .{ args, exe }); std.process.exit(1); } if (string.len == 0) std.process.exit(0); if (behavior == null) { behavior = if (string[0] != '%') .encode else .decode; } // Perform the requested operation. switch (behavior.?) { .encode => { // Encode the provided string into a translation namespace. const namespace = NamespaceString.encodeAll(allocator, string) catch |err| switch (err) { error.InvalidEncoding => { std.log.err( \\namespace contains characters outside of [A-Za-z0-9 _.-] \\See `{} --help` for detailed usage information , .{exe}); std.process.exit(1); }, else => return err, }; defer namespace.deinit(allocator); // Print the namespaced translation string. const stdout = std.io.getStdOut().writer(); try stdout.print("%1$s{}\n", .{namespace}); }, .decode => { // Decode the translation string into a translation namespace. const namespace = NamespaceString.parseLossy(allocator, string) catch |err| switch (err) { error.InvalidEncoding => { std.log.err( \\translation string contains too large of an integer \\See `{} --help` for detailed usage information , .{exe}); std.process.exit(1); }, else => return err, }; defer namespace.deinit(allocator); // Print the initial text used to create the translation namespace. const stdout = std.io.getStdOut().writer(); try stdout.print("{}\n", .{namespace.textView(false)}); }, } }
src/main.zig
const wlr = @import("../wlroots.zig"); const wayland = @import("wayland"); const wl = wayland.server.wl; const xkb = @import("xkbcommon"); pub const Keyboard = extern struct { pub const led = struct { pub const num_lock = 1 << 0; pub const caps_lock = 1 << 1; pub const scroll_lock = 1 << 2; }; pub const ModifierMask = packed struct { shift: bool = false, caps: bool = false, ctrl: bool = false, alt: bool = false, mod2: bool = false, mod3: bool = false, logo: bool = false, mod5: bool = false, }; pub const Modifiers = extern struct { depressed: xkb.ModMask, latched: xkb.ModMask, locked: xkb.ModMask, group: xkb.ModMask, }; pub const event = struct { pub const Key = extern struct { time_msec: u32, keycode: u32, update_state: bool, state: wl.Keyboard.KeyState, }; }; const Impl = opaque {}; impl: *const Impl, group: ?*wlr.KeyboardGroup, keymap_string: [*:0]u8, keymap_size: usize, keymap: ?*xkb.Keymap, xkb_state: ?*xkb.State, led_indexes: [3]xkb.LED_Index, mod_indexes: [8]xkb.ModIndex, keycodes: [32]u32, num_keycodes: usize, modifiers: Modifiers, repeat_info: extern struct { rate: i32, delay: i32, }, events: extern struct { key: wl.Signal(*event.Key), modifiers: wl.Signal(*Keyboard), keymap: wl.Signal(*Keyboard), repeat_info: wl.Signal(*Keyboard), destroy: wl.Signal(*Keyboard), }, data: usize, extern fn wlr_keyboard_set_keymap(kb: *Keyboard, keymap: *xkb.Keymap) bool; pub const setKeymap = wlr_keyboard_set_keymap; extern fn wlr_keyboard_keymaps_match(km1: ?*xkb.Keymap, km2: ?*xkb.Keymap) bool; pub const keymapsMatch = wlr_keyboard_keymaps_match; extern fn wlr_keyboard_set_repeat_info(kb: *Keyboard, rate: i32, delay: i32) void; pub const setRepeatInfo = wlr_keyboard_set_repeat_info; extern fn wlr_keyboard_led_update(keyboard: *Keyboard, leds: u32) void; pub const ledUpdate = wlr_keyboard_led_update; extern fn wlr_keyboard_get_modifiers(keyboard: *Keyboard) u32; pub fn getModifiers(keyboard: *Keyboard) ModifierMask { return @bitCast(ModifierMask, @intCast(u8, wlr_keyboard_get_modifiers(keyboard))); } };
src/types/keyboard.zig
// helper function to convert "anything" to a Range struct pub fn asRange(val: anytype) Range { const type_info = @typeInfo(@TypeOf(val)); switch (type_info) { .Pointer => { switch (type_info.Pointer.size) { .One => return .{ .ptr = val, .size = @sizeOf(type_info.Pointer.child) }, .Slice => return .{ .ptr = val.ptr, .size = @sizeOf(type_info.Pointer.child) * val.len }, else => @compileError("FIXME: Pointer type!"), } }, .Struct, .Array => { return .{ .ptr = &val, .size = @sizeOf(@TypeOf(val)) }; }, else => { @compileError("Cannot convert to range!"); } } } pub const Buffer = extern struct { id: u32 = 0, }; pub const Image = extern struct { id: u32 = 0, }; pub const Shader = extern struct { id: u32 = 0, }; pub const Pipeline = extern struct { id: u32 = 0, }; pub const Pass = extern struct { id: u32 = 0, }; pub const Context = extern struct { id: u32 = 0, }; pub const Range = extern struct { ptr: ?*const c_void = null, size: usize = 0, }; pub const invalid_id = 0; pub const num_shader_stages = 2; pub const num_inflight_frames = 2; pub const max_color_attachments = 4; pub const max_shaderstage_buffers = 8; pub const max_shaderstage_images = 12; pub const max_shaderstage_ubs = 4; pub const max_ub_members = 16; pub const max_vertex_attributes = 16; pub const max_mipmaps = 16; pub const max_texturearray_layers = 128; pub const Color = extern struct { r: f32 = 0.0, g: f32 = 0.0, b: f32 = 0.0, a: f32 = 0.0, }; pub const Backend = extern enum(i32) { GLCORE33, GLES2, GLES3, D3D11, METAL_IOS, METAL_MACOS, METAL_SIMULATOR, WGPU, DUMMY, }; pub const PixelFormat = extern enum(i32) { DEFAULT, NONE, R8, R8SN, R8UI, R8SI, R16, R16SN, R16UI, R16SI, R16F, RG8, RG8SN, RG8UI, RG8SI, R32UI, R32SI, R32F, RG16, RG16SN, RG16UI, RG16SI, RG16F, RGBA8, RGBA8SN, RGBA8UI, RGBA8SI, BGRA8, RGB10A2, RG11B10F, RG32UI, RG32SI, RG32F, RGBA16, RGBA16SN, RGBA16UI, RGBA16SI, RGBA16F, RGBA32UI, RGBA32SI, RGBA32F, DEPTH, DEPTH_STENCIL, BC1_RGBA, BC2_RGBA, BC3_RGBA, BC4_R, BC4_RSN, BC5_RG, BC5_RGSN, BC6H_RGBF, BC6H_RGBUF, BC7_RGBA, PVRTC_RGB_2BPP, PVRTC_RGB_4BPP, PVRTC_RGBA_2BPP, PVRTC_RGBA_4BPP, ETC2_RGB8, ETC2_RGB8A1, ETC2_RGBA8, ETC2_RG11, ETC2_RG11SN, NUM, }; pub const PixelformatInfo = extern struct { sample: bool = false, filter: bool = false, render: bool = false, blend: bool = false, msaa: bool = false, depth: bool = false, __pad: [3]u32 = [_]u32{0} ** 3, }; pub const Features = extern struct { instancing: bool = false, origin_top_left: bool = false, multiple_render_targets: bool = false, msaa_render_targets: bool = false, imagetype_3d: bool = false, imagetype_array: bool = false, image_clamp_to_border: bool = false, mrt_independent_blend_state: bool = false, mrt_independent_write_mask: bool = false, __pad: [3]u32 = [_]u32{0} ** 3, }; pub const Limits = extern struct { max_image_size_2d: u32 = 0, max_image_size_cube: u32 = 0, max_image_size_3d: u32 = 0, max_image_size_array: u32 = 0, max_image_array_layers: u32 = 0, max_vertex_attrs: u32 = 0, }; pub const ResourceState = extern enum(i32) { INITIAL, ALLOC, VALID, FAILED, INVALID, }; pub const Usage = extern enum(i32) { DEFAULT, IMMUTABLE, DYNAMIC, STREAM, NUM, }; pub const BufferType = extern enum(i32) { DEFAULT, VERTEXBUFFER, INDEXBUFFER, NUM, }; pub const IndexType = extern enum(i32) { DEFAULT, NONE, UINT16, UINT32, NUM, }; pub const ImageType = extern enum(i32) { DEFAULT, _2D, CUBE, _3D, ARRAY, NUM, }; pub const SamplerType = extern enum(i32) { DEFAULT, FLOAT, SINT, UINT, }; pub const CubeFace = extern enum(i32) { POS_X, NEG_X, POS_Y, NEG_Y, POS_Z, NEG_Z, NUM, }; pub const ShaderStage = extern enum(i32) { VS, FS, }; pub const PrimitiveType = extern enum(i32) { DEFAULT, POINTS, LINES, LINE_STRIP, TRIANGLES, TRIANGLE_STRIP, NUM, }; pub const Filter = extern enum(i32) { DEFAULT, NEAREST, LINEAR, NEAREST_MIPMAP_NEAREST, NEAREST_MIPMAP_LINEAR, LINEAR_MIPMAP_NEAREST, LINEAR_MIPMAP_LINEAR, NUM, }; pub const Wrap = extern enum(i32) { DEFAULT, REPEAT, CLAMP_TO_EDGE, CLAMP_TO_BORDER, MIRRORED_REPEAT, NUM, }; pub const BorderColor = extern enum(i32) { DEFAULT, TRANSPARENT_BLACK, OPAQUE_BLACK, OPAQUE_WHITE, NUM, }; pub const VertexFormat = extern enum(i32) { INVALID, FLOAT, FLOAT2, FLOAT3, FLOAT4, BYTE4, BYTE4N, UBYTE4, UBYTE4N, SHORT2, SHORT2N, USHORT2N, SHORT4, SHORT4N, USHORT4N, UINT10_N2, NUM, }; pub const VertexStep = extern enum(i32) { DEFAULT, PER_VERTEX, PER_INSTANCE, NUM, }; pub const UniformType = extern enum(i32) { INVALID, FLOAT, FLOAT2, FLOAT3, FLOAT4, MAT4, NUM, }; pub const CullMode = extern enum(i32) { DEFAULT, NONE, FRONT, BACK, NUM, }; pub const FaceWinding = extern enum(i32) { DEFAULT, CCW, CW, NUM, }; pub const CompareFunc = extern enum(i32) { DEFAULT, NEVER, LESS, EQUAL, LESS_EQUAL, GREATER, NOT_EQUAL, GREATER_EQUAL, ALWAYS, NUM, }; pub const StencilOp = extern enum(i32) { DEFAULT, KEEP, ZERO, REPLACE, INCR_CLAMP, DECR_CLAMP, INVERT, INCR_WRAP, DECR_WRAP, NUM, }; pub const BlendFactor = extern enum(i32) { DEFAULT, ZERO, ONE, SRC_COLOR, ONE_MINUS_SRC_COLOR, SRC_ALPHA, ONE_MINUS_SRC_ALPHA, DST_COLOR, ONE_MINUS_DST_COLOR, DST_ALPHA, ONE_MINUS_DST_ALPHA, SRC_ALPHA_SATURATED, BLEND_COLOR, ONE_MINUS_BLEND_COLOR, BLEND_ALPHA, ONE_MINUS_BLEND_ALPHA, NUM, }; pub const BlendOp = extern enum(i32) { DEFAULT, ADD, SUBTRACT, REVERSE_SUBTRACT, NUM, }; pub const ColorMask = extern enum(i32) { DEFAULT = 0, NONE = 16, R = 1, G = 2, RG = 3, B = 4, RB = 5, GB = 6, RGB = 7, A = 8, RA = 9, GA = 10, RGA = 11, BA = 12, RBA = 13, GBA = 14, RGBA = 15, }; pub const Action = extern enum(i32) { DEFAULT, CLEAR, LOAD, DONTCARE, NUM, }; pub const ColorAttachmentAction = extern struct { action: Action = .DEFAULT, value: Color = .{ }, }; pub const DepthAttachmentAction = extern struct { action: Action = .DEFAULT, value: f32 = 0.0, }; pub const StencilAttachmentAction = extern struct { action: Action = .DEFAULT, value: u8 = 0, }; pub const PassAction = extern struct { _start_canary: u32 = 0, colors: [4]ColorAttachmentAction = [_]ColorAttachmentAction{.{}} ** 4, depth: DepthAttachmentAction = .{ }, stencil: StencilAttachmentAction = .{ }, _end_canary: u32 = 0, }; pub const Bindings = extern struct { _start_canary: u32 = 0, vertex_buffers: [8]Buffer = [_]Buffer{.{}} ** 8, vertex_buffer_offsets: [8]i32 = [_]i32{0} ** 8, index_buffer: Buffer = .{ }, index_buffer_offset: i32 = 0, vs_images: [12]Image = [_]Image{.{}} ** 12, fs_images: [12]Image = [_]Image{.{}} ** 12, _end_canary: u32 = 0, }; pub const BufferDesc = extern struct { _start_canary: u32 = 0, size: usize = 0, type: BufferType = .DEFAULT, usage: Usage = .DEFAULT, data: Range = .{ }, label: [*c]const u8 = null, gl_buffers: [2]u32 = [_]u32{0} ** 2, mtl_buffers: [2]?*const c_void = [_]?*const c_void { null } ** 2, d3d11_buffer: ?*const c_void = null, wgpu_buffer: ?*const c_void = null, _end_canary: u32 = 0, }; pub const ImageData = extern struct { subimage: [6][16]Range = [_][16]Range{[_]Range{ .{ } }**16}**6, }; pub const ImageDesc = extern struct { _start_canary: u32 = 0, type: ImageType = .DEFAULT, render_target: bool = false, width: i32 = 0, height: i32 = 0, num_slices: i32 = 0, num_mipmaps: i32 = 0, usage: Usage = .DEFAULT, pixel_format: PixelFormat = .DEFAULT, sample_count: i32 = 0, min_filter: Filter = .DEFAULT, mag_filter: Filter = .DEFAULT, wrap_u: Wrap = .DEFAULT, wrap_v: Wrap = .DEFAULT, wrap_w: Wrap = .DEFAULT, border_color: BorderColor = .DEFAULT, max_anisotropy: u32 = 0, min_lod: f32 = 0.0, max_lod: f32 = 0.0, data: ImageData = .{ }, label: [*c]const u8 = null, gl_textures: [2]u32 = [_]u32{0} ** 2, gl_texture_target: u32 = 0, mtl_textures: [2]?*const c_void = [_]?*const c_void { null } ** 2, d3d11_texture: ?*const c_void = null, d3d11_shader_resource_view: ?*const c_void = null, wgpu_texture: ?*const c_void = null, _end_canary: u32 = 0, }; pub const ShaderAttrDesc = extern struct { name: [*c]const u8 = null, sem_name: [*c]const u8 = null, sem_index: i32 = 0, }; pub const ShaderUniformDesc = extern struct { name: [*c]const u8 = null, type: UniformType = .INVALID, array_count: i32 = 0, }; pub const ShaderUniformBlockDesc = extern struct { size: usize = 0, uniforms: [16]ShaderUniformDesc = [_]ShaderUniformDesc{.{}} ** 16, }; pub const ShaderImageDesc = extern struct { name: [*c]const u8 = null, type: ImageType = .DEFAULT, sampler_type: SamplerType = .DEFAULT, }; pub const ShaderStageDesc = extern struct { source: [*c]const u8 = null, bytecode: Range = .{ }, entry: [*c]const u8 = null, d3d11_target: [*c]const u8 = null, uniform_blocks: [4]ShaderUniformBlockDesc = [_]ShaderUniformBlockDesc{.{}} ** 4, images: [12]ShaderImageDesc = [_]ShaderImageDesc{.{}} ** 12, }; pub const ShaderDesc = extern struct { _start_canary: u32 = 0, attrs: [16]ShaderAttrDesc = [_]ShaderAttrDesc{.{}} ** 16, vs: ShaderStageDesc = .{ }, fs: ShaderStageDesc = .{ }, label: [*c]const u8 = null, _end_canary: u32 = 0, }; pub const BufferLayoutDesc = extern struct { stride: i32 = 0, step_func: VertexStep = .DEFAULT, step_rate: i32 = 0, __pad: [2]u32 = [_]u32{0} ** 2, }; pub const VertexAttrDesc = extern struct { buffer_index: i32 = 0, offset: i32 = 0, format: VertexFormat = .INVALID, __pad: [2]u32 = [_]u32{0} ** 2, }; pub const LayoutDesc = extern struct { buffers: [8]BufferLayoutDesc = [_]BufferLayoutDesc{.{}} ** 8, attrs: [16]VertexAttrDesc = [_]VertexAttrDesc{.{}} ** 16, }; pub const StencilFaceState = extern struct { compare: CompareFunc = .DEFAULT, fail_op: StencilOp = .DEFAULT, depth_fail_op: StencilOp = .DEFAULT, pass_op: StencilOp = .DEFAULT, }; pub const StencilState = extern struct { enabled: bool = false, front: StencilFaceState = .{ }, back: StencilFaceState = .{ }, read_mask: u8 = 0, write_mask: u8 = 0, ref: u8 = 0, }; pub const DepthState = extern struct { pixel_format: PixelFormat = .DEFAULT, compare: CompareFunc = .DEFAULT, write_enabled: bool = false, bias: f32 = 0.0, bias_slope_scale: f32 = 0.0, bias_clamp: f32 = 0.0, }; pub const BlendState = extern struct { enabled: bool = false, src_factor_rgb: BlendFactor = .DEFAULT, dst_factor_rgb: BlendFactor = .DEFAULT, op_rgb: BlendOp = .DEFAULT, src_factor_alpha: BlendFactor = .DEFAULT, dst_factor_alpha: BlendFactor = .DEFAULT, op_alpha: BlendOp = .DEFAULT, }; pub const ColorState = extern struct { pixel_format: PixelFormat = .DEFAULT, write_mask: ColorMask = .DEFAULT, blend: BlendState = .{ }, }; pub const PipelineDesc = extern struct { _start_canary: u32 = 0, shader: Shader = .{ }, layout: LayoutDesc = .{ }, depth: DepthState = .{ }, stencil: StencilState = .{ }, color_count: u32 = 0, colors: [4]ColorState = [_]ColorState{.{}} ** 4, primitive_type: PrimitiveType = .DEFAULT, index_type: IndexType = .DEFAULT, cull_mode: CullMode = .DEFAULT, face_winding: FaceWinding = .DEFAULT, sample_count: i32 = 0, blend_color: Color = .{ }, alpha_to_coverage_enabled: bool = false, label: [*c]const u8 = null, _end_canary: u32 = 0, }; pub const PassAttachmentDesc = extern struct { image: Image = .{ }, mip_level: i32 = 0, slice: i32 = 0, }; pub const PassDesc = extern struct { _start_canary: u32 = 0, color_attachments: [4]PassAttachmentDesc = [_]PassAttachmentDesc{.{}} ** 4, depth_stencil_attachment: PassAttachmentDesc = .{ }, label: [*c]const u8 = null, _end_canary: u32 = 0, }; pub const TraceHooks = extern struct { user_data: ?*c_void = null, reset_state_cache: ?fn(?*c_void) callconv(.C) void = null, make_buffer: ?fn([*c]const BufferDesc, Buffer, ?*c_void) callconv(.C) void = null, make_image: ?fn([*c]const ImageDesc, Image, ?*c_void) callconv(.C) void = null, make_shader: ?fn([*c]const ShaderDesc, Shader, ?*c_void) callconv(.C) void = null, make_pipeline: ?fn([*c]const PipelineDesc, Pipeline, ?*c_void) callconv(.C) void = null, make_pass: ?fn([*c]const PassDesc, Pass, ?*c_void) callconv(.C) void = null, destroy_buffer: ?fn(Buffer, ?*c_void) callconv(.C) void = null, destroy_image: ?fn(Image, ?*c_void) callconv(.C) void = null, destroy_shader: ?fn(Shader, ?*c_void) callconv(.C) void = null, destroy_pipeline: ?fn(Pipeline, ?*c_void) callconv(.C) void = null, destroy_pass: ?fn(Pass, ?*c_void) callconv(.C) void = null, update_buffer: ?fn(Buffer, [*c]const Range, ?*c_void) callconv(.C) void = null, update_image: ?fn(Image, [*c]const ImageData, ?*c_void) callconv(.C) void = null, append_buffer: ?fn(Buffer, [*c]const Range, u32, ?*c_void) callconv(.C) void = null, begin_default_pass: ?fn([*c]const PassAction, i32, i32, ?*c_void) callconv(.C) void = null, begin_pass: ?fn(Pass, [*c]const PassAction, ?*c_void) callconv(.C) void = null, apply_viewport: ?fn(i32, i32, i32, i32, bool, ?*c_void) callconv(.C) void = null, apply_scissor_rect: ?fn(i32, i32, i32, i32, bool, ?*c_void) callconv(.C) void = null, apply_pipeline: ?fn(Pipeline, ?*c_void) callconv(.C) void = null, apply_bindings: ?fn([*c]const Bindings, ?*c_void) callconv(.C) void = null, apply_uniforms: ?fn(ShaderStage, u32, [*c]const Range, ?*c_void) callconv(.C) void = null, draw: ?fn(u32, u32, u32, ?*c_void) callconv(.C) void = null, end_pass: ?fn(?*c_void) callconv(.C) void = null, commit: ?fn(?*c_void) callconv(.C) void = null, alloc_buffer: ?fn(Buffer, ?*c_void) callconv(.C) void = null, alloc_image: ?fn(Image, ?*c_void) callconv(.C) void = null, alloc_shader: ?fn(Shader, ?*c_void) callconv(.C) void = null, alloc_pipeline: ?fn(Pipeline, ?*c_void) callconv(.C) void = null, alloc_pass: ?fn(Pass, ?*c_void) callconv(.C) void = null, dealloc_buffer: ?fn(Buffer, ?*c_void) callconv(.C) void = null, dealloc_image: ?fn(Image, ?*c_void) callconv(.C) void = null, dealloc_shader: ?fn(Shader, ?*c_void) callconv(.C) void = null, dealloc_pipeline: ?fn(Pipeline, ?*c_void) callconv(.C) void = null, dealloc_pass: ?fn(Pass, ?*c_void) callconv(.C) void = null, init_buffer: ?fn(Buffer, [*c]const BufferDesc, ?*c_void) callconv(.C) void = null, init_image: ?fn(Image, [*c]const ImageDesc, ?*c_void) callconv(.C) void = null, init_shader: ?fn(Shader, [*c]const ShaderDesc, ?*c_void) callconv(.C) void = null, init_pipeline: ?fn(Pipeline, [*c]const PipelineDesc, ?*c_void) callconv(.C) void = null, init_pass: ?fn(Pass, [*c]const PassDesc, ?*c_void) callconv(.C) void = null, uninit_buffer: ?fn(Buffer, ?*c_void) callconv(.C) void = null, uninit_image: ?fn(Image, ?*c_void) callconv(.C) void = null, uninit_shader: ?fn(Shader, ?*c_void) callconv(.C) void = null, uninit_pipeline: ?fn(Pipeline, ?*c_void) callconv(.C) void = null, uninit_pass: ?fn(Pass, ?*c_void) callconv(.C) void = null, fail_buffer: ?fn(Buffer, ?*c_void) callconv(.C) void = null, fail_image: ?fn(Image, ?*c_void) callconv(.C) void = null, fail_shader: ?fn(Shader, ?*c_void) callconv(.C) void = null, fail_pipeline: ?fn(Pipeline, ?*c_void) callconv(.C) void = null, fail_pass: ?fn(Pass, ?*c_void) callconv(.C) void = null, push_debug_group: ?fn([*c]const u8, ?*c_void) callconv(.C) void = null, pop_debug_group: ?fn(?*c_void) callconv(.C) void = null, err_buffer_pool_exhausted: ?fn(?*c_void) callconv(.C) void = null, err_image_pool_exhausted: ?fn(?*c_void) callconv(.C) void = null, err_shader_pool_exhausted: ?fn(?*c_void) callconv(.C) void = null, err_pipeline_pool_exhausted: ?fn(?*c_void) callconv(.C) void = null, err_pass_pool_exhausted: ?fn(?*c_void) callconv(.C) void = null, err_context_mismatch: ?fn(?*c_void) callconv(.C) void = null, err_pass_invalid: ?fn(?*c_void) callconv(.C) void = null, err_draw_invalid: ?fn(?*c_void) callconv(.C) void = null, err_bindings_invalid: ?fn(?*c_void) callconv(.C) void = null, }; pub const SlotInfo = extern struct { state: ResourceState = .INITIAL, res_id: u32 = 0, ctx_id: u32 = 0, }; pub const BufferInfo = extern struct { slot: SlotInfo = .{ }, update_frame_index: u32 = 0, append_frame_index: u32 = 0, append_pos: u32 = 0, append_overflow: bool = false, num_slots: i32 = 0, active_slot: i32 = 0, }; pub const ImageInfo = extern struct { slot: SlotInfo = .{ }, upd_frame_index: u32 = 0, num_slots: i32 = 0, active_slot: i32 = 0, width: i32 = 0, height: i32 = 0, }; pub const ShaderInfo = extern struct { slot: SlotInfo = .{ }, }; pub const PipelineInfo = extern struct { slot: SlotInfo = .{ }, }; pub const PassInfo = extern struct { slot: SlotInfo = .{ }, }; pub const GlContextDesc = extern struct { force_gles2: bool = false, }; pub const MetalContextDesc = extern struct { device: ?*const c_void = null, renderpass_descriptor_cb: ?fn() callconv(.C) ?*const c_void = null, renderpass_descriptor_userdata_cb: ?fn(?*c_void) callconv(.C) ?*const c_void = null, drawable_cb: ?fn() callconv(.C) ?*const c_void = null, drawable_userdata_cb: ?fn(?*c_void) callconv(.C) ?*const c_void = null, user_data: ?*c_void = null, }; pub const D3d11ContextDesc = extern struct { device: ?*const c_void = null, device_context: ?*const c_void = null, render_target_view_cb: ?fn() callconv(.C) ?*const c_void = null, render_target_view_userdata_cb: ?fn(?*c_void) callconv(.C) ?*const c_void = null, depth_stencil_view_cb: ?fn() callconv(.C) ?*const c_void = null, depth_stencil_view_userdata_cb: ?fn(?*c_void) callconv(.C) ?*const c_void = null, user_data: ?*c_void = null, }; pub const WgpuContextDesc = extern struct { device: ?*const c_void = null, render_view_cb: ?fn() callconv(.C) ?*const c_void = null, render_view_userdata_cb: ?fn(?*c_void) callconv(.C) ?*const c_void = null, resolve_view_cb: ?fn() callconv(.C) ?*const c_void = null, resolve_view_userdata_cb: ?fn(?*c_void) callconv(.C) ?*const c_void = null, depth_stencil_view_cb: ?fn() callconv(.C) ?*const c_void = null, depth_stencil_view_userdata_cb: ?fn(?*c_void) callconv(.C) ?*const c_void = null, user_data: ?*c_void = null, }; pub const ContextDesc = extern struct { color_format: i32 = 0, depth_format: i32 = 0, sample_count: i32 = 0, gl: GlContextDesc = .{ }, metal: MetalContextDesc = .{ }, d3d11: D3d11ContextDesc = .{ }, wgpu: WgpuContextDesc = .{ }, }; pub const Desc = extern struct { _start_canary: u32 = 0, buffer_pool_size: i32 = 0, image_pool_size: i32 = 0, shader_pool_size: i32 = 0, pipeline_pool_size: i32 = 0, pass_pool_size: i32 = 0, context_pool_size: i32 = 0, uniform_buffer_size: i32 = 0, staging_buffer_size: i32 = 0, sampler_cache_size: i32 = 0, context: ContextDesc = .{ }, _end_canary: u32 = 0, }; pub extern fn sg_setup([*c]const Desc) void; pub inline fn setup(desc: Desc) void { sg_setup(&desc); } pub extern fn sg_shutdown() void; pub inline fn shutdown() void { sg_shutdown(); } pub extern fn sg_isvalid() bool; pub inline fn isvalid() bool { return sg_isvalid(); } pub extern fn sg_reset_state_cache() void; pub inline fn resetStateCache() void { sg_reset_state_cache(); } pub extern fn sg_install_trace_hooks([*c]const TraceHooks) TraceHooks; pub inline fn installTraceHooks(trace_hooks: TraceHooks) TraceHooks { return sg_install_trace_hooks(&trace_hooks); } pub extern fn sg_push_debug_group([*c]const u8) void; pub inline fn pushDebugGroup(name: [:0]const u8) void { sg_push_debug_group(@ptrCast([*c]const u8,name)); } pub extern fn sg_pop_debug_group() void; pub inline fn popDebugGroup() void { sg_pop_debug_group(); } pub extern fn sg_make_buffer([*c]const BufferDesc) Buffer; pub inline fn makeBuffer(desc: BufferDesc) Buffer { return sg_make_buffer(&desc); } pub extern fn sg_make_image([*c]const ImageDesc) Image; pub inline fn makeImage(desc: ImageDesc) Image { return sg_make_image(&desc); } pub extern fn sg_make_shader([*c]const ShaderDesc) Shader; pub inline fn makeShader(desc: ShaderDesc) Shader { return sg_make_shader(&desc); } pub extern fn sg_make_pipeline([*c]const PipelineDesc) Pipeline; pub inline fn makePipeline(desc: PipelineDesc) Pipeline { return sg_make_pipeline(&desc); } pub extern fn sg_make_pass([*c]const PassDesc) Pass; pub inline fn makePass(desc: PassDesc) Pass { return sg_make_pass(&desc); } pub extern fn sg_destroy_buffer(Buffer) void; pub inline fn destroyBuffer(buf: Buffer) void { sg_destroy_buffer(buf); } pub extern fn sg_destroy_image(Image) void; pub inline fn destroyImage(img: Image) void { sg_destroy_image(img); } pub extern fn sg_destroy_shader(Shader) void; pub inline fn destroyShader(shd: Shader) void { sg_destroy_shader(shd); } pub extern fn sg_destroy_pipeline(Pipeline) void; pub inline fn destroyPipeline(pip: Pipeline) void { sg_destroy_pipeline(pip); } pub extern fn sg_destroy_pass(Pass) void; pub inline fn destroyPass(pass: Pass) void { sg_destroy_pass(pass); } pub extern fn sg_update_buffer(Buffer, [*c]const Range) void; pub inline fn updateBuffer(buf: Buffer, data: Range) void { sg_update_buffer(buf, &data); } pub extern fn sg_update_image(Image, [*c]const ImageData) void; pub inline fn updateImage(img: Image, data: ImageData) void { sg_update_image(img, &data); } pub extern fn sg_append_buffer(Buffer, [*c]const Range) u32; pub inline fn appendBuffer(buf: Buffer, data: Range) u32 { return sg_append_buffer(buf, &data); } pub extern fn sg_query_buffer_overflow(Buffer) bool; pub inline fn queryBufferOverflow(buf: Buffer) bool { return sg_query_buffer_overflow(buf); } pub extern fn sg_begin_default_pass([*c]const PassAction, i32, i32) void; pub inline fn beginDefaultPass(pass_action: PassAction, width: i32, height: i32) void { sg_begin_default_pass(&pass_action, width, height); } pub extern fn sg_begin_default_passf([*c]const PassAction, f32, f32) void; pub inline fn beginDefaultPassf(pass_action: PassAction, width: f32, height: f32) void { sg_begin_default_passf(&pass_action, width, height); } pub extern fn sg_begin_pass(Pass, [*c]const PassAction) void; pub inline fn beginPass(pass: Pass, pass_action: PassAction) void { sg_begin_pass(pass, &pass_action); } pub extern fn sg_apply_viewport(i32, i32, i32, i32, bool) void; pub inline fn applyViewport(x: i32, y: i32, width: i32, height: i32, origin_top_left: bool) void { sg_apply_viewport(x, y, width, height, origin_top_left); } pub extern fn sg_apply_viewportf(f32, f32, f32, f32, bool) void; pub inline fn applyViewportf(x: f32, y: f32, width: f32, height: f32, origin_top_left: bool) void { sg_apply_viewportf(x, y, width, height, origin_top_left); } pub extern fn sg_apply_scissor_rect(i32, i32, i32, i32, bool) void; pub inline fn applyScissorRect(x: i32, y: i32, width: i32, height: i32, origin_top_left: bool) void { sg_apply_scissor_rect(x, y, width, height, origin_top_left); } pub extern fn sg_apply_scissor_rectf(f32, f32, f32, f32, bool) void; pub inline fn applyScissorRectf(x: f32, y: f32, width: f32, height: f32, origin_top_left: bool) void { sg_apply_scissor_rectf(x, y, width, height, origin_top_left); } pub extern fn sg_apply_pipeline(Pipeline) void; pub inline fn applyPipeline(pip: Pipeline) void { sg_apply_pipeline(pip); } pub extern fn sg_apply_bindings([*c]const Bindings) void; pub inline fn applyBindings(bindings: Bindings) void { sg_apply_bindings(&bindings); } pub extern fn sg_apply_uniforms(ShaderStage, u32, [*c]const Range) void; pub inline fn applyUniforms(stage: ShaderStage, ub_index: u32, data: Range) void { sg_apply_uniforms(stage, ub_index, &data); } pub extern fn sg_draw(u32, u32, u32) void; pub inline fn draw(base_element: u32, num_elements: u32, num_instances: u32) void { sg_draw(base_element, num_elements, num_instances); } pub extern fn sg_end_pass() void; pub inline fn endPass() void { sg_end_pass(); } pub extern fn sg_commit() void; pub inline fn commit() void { sg_commit(); } pub extern fn sg_query_desc() Desc; pub inline fn queryDesc() Desc { return sg_query_desc(); } pub extern fn sg_query_backend() Backend; pub inline fn queryBackend() Backend { return sg_query_backend(); } pub extern fn sg_query_features() Features; pub inline fn queryFeatures() Features { return sg_query_features(); } pub extern fn sg_query_limits() Limits; pub inline fn queryLimits() Limits { return sg_query_limits(); } pub extern fn sg_query_pixelformat(PixelFormat) PixelformatInfo; pub inline fn queryPixelformat(fmt: PixelFormat) PixelformatInfo { return sg_query_pixelformat(fmt); } pub extern fn sg_query_buffer_state(Buffer) ResourceState; pub inline fn queryBufferState(buf: Buffer) ResourceState { return sg_query_buffer_state(buf); } pub extern fn sg_query_image_state(Image) ResourceState; pub inline fn queryImageState(img: Image) ResourceState { return sg_query_image_state(img); } pub extern fn sg_query_shader_state(Shader) ResourceState; pub inline fn queryShaderState(shd: Shader) ResourceState { return sg_query_shader_state(shd); } pub extern fn sg_query_pipeline_state(Pipeline) ResourceState; pub inline fn queryPipelineState(pip: Pipeline) ResourceState { return sg_query_pipeline_state(pip); } pub extern fn sg_query_pass_state(Pass) ResourceState; pub inline fn queryPassState(pass: Pass) ResourceState { return sg_query_pass_state(pass); } pub extern fn sg_query_buffer_info(Buffer) BufferInfo; pub inline fn queryBufferInfo(buf: Buffer) BufferInfo { return sg_query_buffer_info(buf); } pub extern fn sg_query_image_info(Image) ImageInfo; pub inline fn queryImageInfo(img: Image) ImageInfo { return sg_query_image_info(img); } pub extern fn sg_query_shader_info(Shader) ShaderInfo; pub inline fn queryShaderInfo(shd: Shader) ShaderInfo { return sg_query_shader_info(shd); } pub extern fn sg_query_pipeline_info(Pipeline) PipelineInfo; pub inline fn queryPipelineInfo(pip: Pipeline) PipelineInfo { return sg_query_pipeline_info(pip); } pub extern fn sg_query_pass_info(Pass) PassInfo; pub inline fn queryPassInfo(pass: Pass) PassInfo { return sg_query_pass_info(pass); } pub extern fn sg_query_buffer_defaults([*c]const BufferDesc) BufferDesc; pub inline fn queryBufferDefaults(desc: BufferDesc) BufferDesc { return sg_query_buffer_defaults(&desc); } pub extern fn sg_query_image_defaults([*c]const ImageDesc) ImageDesc; pub inline fn queryImageDefaults(desc: ImageDesc) ImageDesc { return sg_query_image_defaults(&desc); } pub extern fn sg_query_shader_defaults([*c]const ShaderDesc) ShaderDesc; pub inline fn queryShaderDefaults(desc: ShaderDesc) ShaderDesc { return sg_query_shader_defaults(&desc); } pub extern fn sg_query_pipeline_defaults([*c]const PipelineDesc) PipelineDesc; pub inline fn queryPipelineDefaults(desc: PipelineDesc) PipelineDesc { return sg_query_pipeline_defaults(&desc); } pub extern fn sg_query_pass_defaults([*c]const PassDesc) PassDesc; pub inline fn queryPassDefaults(desc: PassDesc) PassDesc { return sg_query_pass_defaults(&desc); } pub extern fn sg_alloc_buffer() Buffer; pub inline fn allocBuffer() Buffer { return sg_alloc_buffer(); } pub extern fn sg_alloc_image() Image; pub inline fn allocImage() Image { return sg_alloc_image(); } pub extern fn sg_alloc_shader() Shader; pub inline fn allocShader() Shader { return sg_alloc_shader(); } pub extern fn sg_alloc_pipeline() Pipeline; pub inline fn allocPipeline() Pipeline { return sg_alloc_pipeline(); } pub extern fn sg_alloc_pass() Pass; pub inline fn allocPass() Pass { return sg_alloc_pass(); } pub extern fn sg_dealloc_buffer(Buffer) void; pub inline fn deallocBuffer(buf_id: Buffer) void { sg_dealloc_buffer(buf_id); } pub extern fn sg_dealloc_image(Image) void; pub inline fn deallocImage(img_id: Image) void { sg_dealloc_image(img_id); } pub extern fn sg_dealloc_shader(Shader) void; pub inline fn deallocShader(shd_id: Shader) void { sg_dealloc_shader(shd_id); } pub extern fn sg_dealloc_pipeline(Pipeline) void; pub inline fn deallocPipeline(pip_id: Pipeline) void { sg_dealloc_pipeline(pip_id); } pub extern fn sg_dealloc_pass(Pass) void; pub inline fn deallocPass(pass_id: Pass) void { sg_dealloc_pass(pass_id); } pub extern fn sg_init_buffer(Buffer, [*c]const BufferDesc) void; pub inline fn initBuffer(buf_id: Buffer, desc: BufferDesc) void { sg_init_buffer(buf_id, &desc); } pub extern fn sg_init_image(Image, [*c]const ImageDesc) void; pub inline fn initImage(img_id: Image, desc: ImageDesc) void { sg_init_image(img_id, &desc); } pub extern fn sg_init_shader(Shader, [*c]const ShaderDesc) void; pub inline fn initShader(shd_id: Shader, desc: ShaderDesc) void { sg_init_shader(shd_id, &desc); } pub extern fn sg_init_pipeline(Pipeline, [*c]const PipelineDesc) void; pub inline fn initPipeline(pip_id: Pipeline, desc: PipelineDesc) void { sg_init_pipeline(pip_id, &desc); } pub extern fn sg_init_pass(Pass, [*c]const PassDesc) void; pub inline fn initPass(pass_id: Pass, desc: PassDesc) void { sg_init_pass(pass_id, &desc); } pub extern fn sg_uninit_buffer(Buffer) bool; pub inline fn uninitBuffer(buf_id: Buffer) bool { return sg_uninit_buffer(buf_id); } pub extern fn sg_uninit_image(Image) bool; pub inline fn uninitImage(img_id: Image) bool { return sg_uninit_image(img_id); } pub extern fn sg_uninit_shader(Shader) bool; pub inline fn uninitShader(shd_id: Shader) bool { return sg_uninit_shader(shd_id); } pub extern fn sg_uninit_pipeline(Pipeline) bool; pub inline fn uninitPipeline(pip_id: Pipeline) bool { return sg_uninit_pipeline(pip_id); } pub extern fn sg_uninit_pass(Pass) bool; pub inline fn uninitPass(pass_id: Pass) bool { return sg_uninit_pass(pass_id); } pub extern fn sg_fail_buffer(Buffer) void; pub inline fn failBuffer(buf_id: Buffer) void { sg_fail_buffer(buf_id); } pub extern fn sg_fail_image(Image) void; pub inline fn failImage(img_id: Image) void { sg_fail_image(img_id); } pub extern fn sg_fail_shader(Shader) void; pub inline fn failShader(shd_id: Shader) void { sg_fail_shader(shd_id); } pub extern fn sg_fail_pipeline(Pipeline) void; pub inline fn failPipeline(pip_id: Pipeline) void { sg_fail_pipeline(pip_id); } pub extern fn sg_fail_pass(Pass) void; pub inline fn failPass(pass_id: Pass) void { sg_fail_pass(pass_id); } pub extern fn sg_setup_context() Context; pub inline fn setupContext() Context { return sg_setup_context(); } pub extern fn sg_activate_context(Context) void; pub inline fn activateContext(ctx_id: Context) void { sg_activate_context(ctx_id); } pub extern fn sg_discard_context(Context) void; pub inline fn discardContext(ctx_id: Context) void { sg_discard_context(ctx_id); } pub extern fn sg_d3d11_device() ?*const c_void; pub inline fn d3d11Device() ?*const c_void { return sg_d3d11_device(); } pub extern fn sg_mtl_device() ?*const c_void; pub inline fn mtlDevice() ?*const c_void { return sg_mtl_device(); } pub extern fn sg_mtl_render_command_encoder() ?*const c_void; pub inline fn mtlRenderCommandEncoder() ?*const c_void { return sg_mtl_render_command_encoder(); }
src/sokol/gfx.zig
const std = @import("std"); const with_trace = true; const assert = std.debug.assert; fn trace(comptime fmt: []const u8, args: anytype) void { if (with_trace) std.debug.print(fmt, args); } const Interraction = struct { name: []const u8, nextname: []const u8, cost: i32, }; fn parse_line(line: []const u8) Interraction { //"{name} would {gain|lose} {val} happiness units by sitting next to {nextname}." var slice = line; var sep = std.mem.indexOf(u8, slice, " would "); const name = slice[0..sep.?]; slice = slice[sep.? + 7 ..]; sep = std.mem.indexOf(u8, slice, " "); const sign = slice[0..sep.?]; slice = slice[sep.? + 1 ..]; sep = std.mem.indexOf(u8, slice, " happiness units by sitting next to "); const number = slice[0..sep.?]; slice = slice[sep.? + 36 ..]; sep = std.mem.indexOf(u8, slice, "."); const nextname = slice[0..sep.?]; var val = std.fmt.parseInt(i32, number, 10) catch unreachable; if (std.mem.eql(u8, sign, "lose")) val = -val; return Interraction{ .name = name, .nextname = nextname, .cost = val }; } fn findoradd(table: [][]const u8, nb: *u32, name: []const u8) u32 { var i: u32 = 0; while (i < nb.*) : (i += 1) { const c = table[i]; if (std.mem.eql(u8, c, name)) return i; } table[nb.*] = name; nb.* += 1; return nb.* - 1; } fn swap(a: *u32, b: *u32) void { const t = a.*; a.* = b.*; b.* = t; } pub fn main() anyerror!void { var arena = std.heap.ArenaAllocator.init(std.heap.page_allocator); defer arena.deinit(); const allocator = arena.allocator(); const limit = 1 * 1024 * 1024 * 1024; const text = try std.fs.cwd().readFileAlloc(allocator, "day13.txt", limit); const maxpeople = 10; var people: [maxpeople][]const u8 = undefined; var popu: u32 = 0; var links: [maxpeople * maxpeople]?i32 = [1]?i32{null} ** (maxpeople * maxpeople); var it = std.mem.tokenize(u8, text, "\n"); while (it.next()) |line| { const inter = parse_line(line); //trace("{}\n", inter); const n1 = findoradd(&people, &popu, inter.name); const n2 = findoradd(&people, &popu, inter.nextname); links[n1 * maxpeople + n2] = inter.cost; } if (true) { const me = findoradd(&people, &popu, "me"); var i: u32 = 0; while (i < popu - 1) : (i += 1) { links[me * maxpeople + i] = 0; links[i * maxpeople + me] = 0; } } var permutations_mem: [maxpeople]u32 = undefined; const perm = permutations_mem[0..popu]; var permuts: usize = 1; for (perm) |p, i| { permuts *= (i + 1); } var best_total: i32 = 0; var j: u32 = 0; while (j < permuts) : (j += 1) { for (perm) |*p, i| { p.* = @intCast(u32, i); } var mod = popu; var k = j; for (perm) |*p, i| { swap(p, &perm[i + k % mod]); k /= mod; mod -= 1; } var total: i32 = 0; for (perm) |p, i| { const n = if (i + 1 < perm.len) perm[i + 1] else perm[0]; const link = links[p * maxpeople + n]; const revlink = links[n * maxpeople + p]; if (link) |l| { total += l; } else { unreachable; } if (revlink) |l| { total += l; } else { unreachable; } } if (total > best_total) best_total = total; } const out = std.io.getStdOut().writer(); try out.print("pass = {}\n", best_total); // return error.SolutionNotFound; }
2015/day13.zig
pub const SIDESHOW_ENDPOINT_SIMPLE_CONTENT_FORMAT = Guid.initString("a9a5353f-2d4b-47ce-93ee-759f3a7dda4f"); pub const SIDESHOW_ENDPOINT_ICAL = Guid.initString("4dff36b5-9dde-4f76-9a2a-96435047063d"); pub const SIDESHOW_CAPABILITY_DEVICE_PROPERTIES = Guid.initString("8abc88a8-857b-4ad7-a35a-b5942f492b99"); pub const GUID_DEVINTERFACE_SIDESHOW = Guid.initString("152e5811-feb9-4b00-90f4-d32947ae1681"); pub const SIDESHOW_CONTENT_MISSING_EVENT = Guid.initString("5007fba8-d313-439f-bea2-a50201d3e9a8"); pub const SIDESHOW_APPLICATION_EVENT = Guid.initString("4cb572fa-1d3b-49b3-a17a-2e6bff052854"); pub const SIDESHOW_USER_CHANGE_REQUEST_EVENT = Guid.initString("5009673c-3f7d-4c7e-9971-eaa2e91f1575"); pub const SIDESHOW_NEW_EVENT_DATA_AVAILABLE = Guid.initString("57813854-2fc1-411c-a59f-f24927608804"); pub const CONTENT_ID_GLANCE = @as(u32, 0); pub const SIDESHOW_EVENTID_APPLICATION_ENTER = @as(u32, 4294901760); pub const SIDESHOW_EVENTID_APPLICATION_EXIT = @as(u32, 4294901761); pub const CONTENT_ID_HOME = @as(u32, 1); pub const VERSION_1_WINDOWS_7 = @as(u32, 0); //-------------------------------------------------------------------------------- // Section: Types (28) //-------------------------------------------------------------------------------- const CLSID_SideShowSession_Value = @import("../zig.zig").Guid.initString("e20543b9-f785-4ea2-981e-c4ffa76bbc7c"); pub const CLSID_SideShowSession = &CLSID_SideShowSession_Value; const CLSID_SideShowNotification_Value = @import("../zig.zig").Guid.initString("0ce3e86f-d5cd-4525-a766-1abab1a752f5"); pub const CLSID_SideShowNotification = &CLSID_SideShowNotification_Value; const CLSID_SideShowKeyCollection_Value = @import("../zig.zig").Guid.initString("<KEY>"); pub const CLSID_SideShowKeyCollection = &CLSID_SideShowKeyCollection_Value; const CLSID_SideShowPropVariantCollection_Value = @import("../zig.zig").Guid.initString("e640f415-539e-4923-96cd-5f093bc250cd"); pub const CLSID_SideShowPropVariantCollection = &CLSID_SideShowPropVariantCollection_Value; const IID_ISideShowSession_Value = @import("../zig.zig").Guid.initString("e22331ee-9e7d-4922-9fc2-ab7aa41ce491"); pub const IID_ISideShowSession = &IID_ISideShowSession_Value; pub const ISideShowSession = extern struct { pub const VTable = extern struct { base: IUnknown.VTable, RegisterContent: fn( self: *const ISideShowSession, in_applicationId: ?*Guid, in_endpointId: ?*Guid, out_ppIContent: ?*?*ISideShowContentManager, ) callconv(@import("std").os.windows.WINAPI) HRESULT, RegisterNotifications: fn( self: *const ISideShowSession, in_applicationId: ?*Guid, out_ppINotification: ?*?*ISideShowNotificationManager, ) 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 ISideShowSession_RegisterContent(self: *const T, in_applicationId: ?*Guid, in_endpointId: ?*Guid, out_ppIContent: ?*?*ISideShowContentManager) callconv(.Inline) HRESULT { return @ptrCast(*const ISideShowSession.VTable, self.vtable).RegisterContent(@ptrCast(*const ISideShowSession, self), in_applicationId, in_endpointId, out_ppIContent); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn ISideShowSession_RegisterNotifications(self: *const T, in_applicationId: ?*Guid, out_ppINotification: ?*?*ISideShowNotificationManager) callconv(.Inline) HRESULT { return @ptrCast(*const ISideShowSession.VTable, self.vtable).RegisterNotifications(@ptrCast(*const ISideShowSession, self), in_applicationId, out_ppINotification); } };} pub usingnamespace MethodMixin(@This()); }; const IID_ISideShowNotificationManager_Value = @import("../zig.zig").Guid.initString("63cea909-f2b9-4302-b5e1-c68e6d9ab833"); pub const IID_ISideShowNotificationManager = &IID_ISideShowNotificationManager_Value; pub const ISideShowNotificationManager = extern struct { pub const VTable = extern struct { base: IUnknown.VTable, Show: fn( self: *const ISideShowNotificationManager, in_pINotification: ?*ISideShowNotification, ) callconv(@import("std").os.windows.WINAPI) HRESULT, Revoke: fn( self: *const ISideShowNotificationManager, in_notificationId: u32, ) callconv(@import("std").os.windows.WINAPI) HRESULT, RevokeAll: fn( self: *const ISideShowNotificationManager, ) 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 ISideShowNotificationManager_Show(self: *const T, in_pINotification: ?*ISideShowNotification) callconv(.Inline) HRESULT { return @ptrCast(*const ISideShowNotificationManager.VTable, self.vtable).Show(@ptrCast(*const ISideShowNotificationManager, self), in_pINotification); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn ISideShowNotificationManager_Revoke(self: *const T, in_notificationId: u32) callconv(.Inline) HRESULT { return @ptrCast(*const ISideShowNotificationManager.VTable, self.vtable).Revoke(@ptrCast(*const ISideShowNotificationManager, self), in_notificationId); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn ISideShowNotificationManager_RevokeAll(self: *const T) callconv(.Inline) HRESULT { return @ptrCast(*const ISideShowNotificationManager.VTable, self.vtable).RevokeAll(@ptrCast(*const ISideShowNotificationManager, self)); } };} pub usingnamespace MethodMixin(@This()); }; const IID_ISideShowNotification_Value = @import("../zig.zig").Guid.initString("03c93300-8ab2-41c5-9b79-46127a30e148"); pub const IID_ISideShowNotification = &IID_ISideShowNotification_Value; pub const ISideShowNotification = extern struct { pub const VTable = extern struct { base: IUnknown.VTable, // TODO: this function has a "SpecialName", should Zig do anything with this? get_NotificationId: fn( self: *const ISideShowNotification, out_pNotificationId: ?*u32, ) callconv(@import("std").os.windows.WINAPI) HRESULT, // TODO: this function has a "SpecialName", should Zig do anything with this? put_NotificationId: fn( self: *const ISideShowNotification, in_notificationId: u32, ) callconv(@import("std").os.windows.WINAPI) HRESULT, // TODO: this function has a "SpecialName", should Zig do anything with this? get_Title: fn( self: *const ISideShowNotification, out_ppwszTitle: ?*?PWSTR, ) callconv(@import("std").os.windows.WINAPI) HRESULT, // TODO: this function has a "SpecialName", should Zig do anything with this? put_Title: fn( self: *const ISideShowNotification, in_pwszTitle: ?PWSTR, ) callconv(@import("std").os.windows.WINAPI) HRESULT, // TODO: this function has a "SpecialName", should Zig do anything with this? get_Message: fn( self: *const ISideShowNotification, out_ppwszMessage: ?*?PWSTR, ) callconv(@import("std").os.windows.WINAPI) HRESULT, // TODO: this function has a "SpecialName", should Zig do anything with this? put_Message: fn( self: *const ISideShowNotification, in_pwszMessage: ?PWSTR, ) callconv(@import("std").os.windows.WINAPI) HRESULT, // TODO: this function has a "SpecialName", should Zig do anything with this? get_Image: fn( self: *const ISideShowNotification, out_phIcon: ?*?HICON, ) callconv(@import("std").os.windows.WINAPI) HRESULT, // TODO: this function has a "SpecialName", should Zig do anything with this? put_Image: fn( self: *const ISideShowNotification, in_hIcon: ?HICON, ) callconv(@import("std").os.windows.WINAPI) HRESULT, // TODO: this function has a "SpecialName", should Zig do anything with this? get_ExpirationTime: fn( self: *const ISideShowNotification, out_pTime: ?*SYSTEMTIME, ) callconv(@import("std").os.windows.WINAPI) HRESULT, // TODO: this function has a "SpecialName", should Zig do anything with this? put_ExpirationTime: fn( self: *const ISideShowNotification, in_pTime: ?*SYSTEMTIME, ) 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 ISideShowNotification_get_NotificationId(self: *const T, out_pNotificationId: ?*u32) callconv(.Inline) HRESULT { return @ptrCast(*const ISideShowNotification.VTable, self.vtable).get_NotificationId(@ptrCast(*const ISideShowNotification, self), out_pNotificationId); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn ISideShowNotification_put_NotificationId(self: *const T, in_notificationId: u32) callconv(.Inline) HRESULT { return @ptrCast(*const ISideShowNotification.VTable, self.vtable).put_NotificationId(@ptrCast(*const ISideShowNotification, self), in_notificationId); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn ISideShowNotification_get_Title(self: *const T, out_ppwszTitle: ?*?PWSTR) callconv(.Inline) HRESULT { return @ptrCast(*const ISideShowNotification.VTable, self.vtable).get_Title(@ptrCast(*const ISideShowNotification, self), out_ppwszTitle); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn ISideShowNotification_put_Title(self: *const T, in_pwszTitle: ?PWSTR) callconv(.Inline) HRESULT { return @ptrCast(*const ISideShowNotification.VTable, self.vtable).put_Title(@ptrCast(*const ISideShowNotification, self), in_pwszTitle); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn ISideShowNotification_get_Message(self: *const T, out_ppwszMessage: ?*?PWSTR) callconv(.Inline) HRESULT { return @ptrCast(*const ISideShowNotification.VTable, self.vtable).get_Message(@ptrCast(*const ISideShowNotification, self), out_ppwszMessage); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn ISideShowNotification_put_Message(self: *const T, in_pwszMessage: ?PWSTR) callconv(.Inline) HRESULT { return @ptrCast(*const ISideShowNotification.VTable, self.vtable).put_Message(@ptrCast(*const ISideShowNotification, self), in_pwszMessage); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn ISideShowNotification_get_Image(self: *const T, out_phIcon: ?*?HICON) callconv(.Inline) HRESULT { return @ptrCast(*const ISideShowNotification.VTable, self.vtable).get_Image(@ptrCast(*const ISideShowNotification, self), out_phIcon); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn ISideShowNotification_put_Image(self: *const T, in_hIcon: ?HICON) callconv(.Inline) HRESULT { return @ptrCast(*const ISideShowNotification.VTable, self.vtable).put_Image(@ptrCast(*const ISideShowNotification, self), in_hIcon); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn ISideShowNotification_get_ExpirationTime(self: *const T, out_pTime: ?*SYSTEMTIME) callconv(.Inline) HRESULT { return @ptrCast(*const ISideShowNotification.VTable, self.vtable).get_ExpirationTime(@ptrCast(*const ISideShowNotification, self), out_pTime); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn ISideShowNotification_put_ExpirationTime(self: *const T, in_pTime: ?*SYSTEMTIME) callconv(.Inline) HRESULT { return @ptrCast(*const ISideShowNotification.VTable, self.vtable).put_ExpirationTime(@ptrCast(*const ISideShowNotification, self), in_pTime); } };} pub usingnamespace MethodMixin(@This()); }; const IID_ISideShowContentManager_Value = @import("../zig.zig").Guid.initString("a5d5b66b-eef9-41db-8d7e-e17c33ab10b0"); pub const IID_ISideShowContentManager = &IID_ISideShowContentManager_Value; pub const ISideShowContentManager = extern struct { pub const VTable = extern struct { base: IUnknown.VTable, Add: fn( self: *const ISideShowContentManager, in_pIContent: ?*ISideShowContent, ) callconv(@import("std").os.windows.WINAPI) HRESULT, Remove: fn( self: *const ISideShowContentManager, in_contentId: u32, ) callconv(@import("std").os.windows.WINAPI) HRESULT, RemoveAll: fn( self: *const ISideShowContentManager, ) callconv(@import("std").os.windows.WINAPI) HRESULT, SetEventSink: fn( self: *const ISideShowContentManager, in_pIEvents: ?*ISideShowEvents, ) callconv(@import("std").os.windows.WINAPI) HRESULT, GetDeviceCapabilities: fn( self: *const ISideShowContentManager, out_ppCollection: ?*?*ISideShowCapabilitiesCollection, ) 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 ISideShowContentManager_Add(self: *const T, in_pIContent: ?*ISideShowContent) callconv(.Inline) HRESULT { return @ptrCast(*const ISideShowContentManager.VTable, self.vtable).Add(@ptrCast(*const ISideShowContentManager, self), in_pIContent); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn ISideShowContentManager_Remove(self: *const T, in_contentId: u32) callconv(.Inline) HRESULT { return @ptrCast(*const ISideShowContentManager.VTable, self.vtable).Remove(@ptrCast(*const ISideShowContentManager, self), in_contentId); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn ISideShowContentManager_RemoveAll(self: *const T) callconv(.Inline) HRESULT { return @ptrCast(*const ISideShowContentManager.VTable, self.vtable).RemoveAll(@ptrCast(*const ISideShowContentManager, self)); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn ISideShowContentManager_SetEventSink(self: *const T, in_pIEvents: ?*ISideShowEvents) callconv(.Inline) HRESULT { return @ptrCast(*const ISideShowContentManager.VTable, self.vtable).SetEventSink(@ptrCast(*const ISideShowContentManager, self), in_pIEvents); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn ISideShowContentManager_GetDeviceCapabilities(self: *const T, out_ppCollection: ?*?*ISideShowCapabilitiesCollection) callconv(.Inline) HRESULT { return @ptrCast(*const ISideShowContentManager.VTable, self.vtable).GetDeviceCapabilities(@ptrCast(*const ISideShowContentManager, self), out_ppCollection); } };} pub usingnamespace MethodMixin(@This()); }; const IID_ISideShowContent_Value = @import("../zig.zig").Guid.initString("c18552ed-74ff-4fec-be07-4cfed29d4887"); pub const IID_ISideShowContent = &IID_ISideShowContent_Value; pub const ISideShowContent = extern struct { pub const VTable = extern struct { base: IUnknown.VTable, GetContent: fn( self: *const ISideShowContent, in_pICapabilities: ?*ISideShowCapabilities, out_pdwSize: ?*u32, out_ppbData: ?[*]?*u8, ) callconv(@import("std").os.windows.WINAPI) HRESULT, // TODO: this function has a "SpecialName", should Zig do anything with this? get_ContentId: fn( self: *const ISideShowContent, out_pcontentId: ?*u32, ) callconv(@import("std").os.windows.WINAPI) HRESULT, // TODO: this function has a "SpecialName", should Zig do anything with this? get_DifferentiateContent: fn( self: *const ISideShowContent, out_pfDifferentiateContent: ?*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 ISideShowContent_GetContent(self: *const T, in_pICapabilities: ?*ISideShowCapabilities, out_pdwSize: ?*u32, out_ppbData: ?[*]?*u8) callconv(.Inline) HRESULT { return @ptrCast(*const ISideShowContent.VTable, self.vtable).GetContent(@ptrCast(*const ISideShowContent, self), in_pICapabilities, out_pdwSize, out_ppbData); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn ISideShowContent_get_ContentId(self: *const T, out_pcontentId: ?*u32) callconv(.Inline) HRESULT { return @ptrCast(*const ISideShowContent.VTable, self.vtable).get_ContentId(@ptrCast(*const ISideShowContent, self), out_pcontentId); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn ISideShowContent_get_DifferentiateContent(self: *const T, out_pfDifferentiateContent: ?*BOOL) callconv(.Inline) HRESULT { return @ptrCast(*const ISideShowContent.VTable, self.vtable).get_DifferentiateContent(@ptrCast(*const ISideShowContent, self), out_pfDifferentiateContent); } };} pub usingnamespace MethodMixin(@This()); }; const IID_ISideShowEvents_Value = @import("../zig.zig").Guid.initString("61feca4c-deb4-4a7e-8d75-51f1132d615b"); pub const IID_ISideShowEvents = &IID_ISideShowEvents_Value; pub const ISideShowEvents = extern struct { pub const VTable = extern struct { base: IUnknown.VTable, ContentMissing: fn( self: *const ISideShowEvents, in_contentId: u32, out_ppIContent: ?*?*ISideShowContent, ) callconv(@import("std").os.windows.WINAPI) HRESULT, ApplicationEvent: fn( self: *const ISideShowEvents, in_pICapabilities: ?*ISideShowCapabilities, in_dwEventId: u32, in_dwEventSize: u32, in_pbEventData: ?[*:0]const u8, ) callconv(@import("std").os.windows.WINAPI) HRESULT, DeviceAdded: fn( self: *const ISideShowEvents, in_pIDevice: ?*ISideShowCapabilities, ) callconv(@import("std").os.windows.WINAPI) HRESULT, DeviceRemoved: fn( self: *const ISideShowEvents, in_pIDevice: ?*ISideShowCapabilities, ) 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 ISideShowEvents_ContentMissing(self: *const T, in_contentId: u32, out_ppIContent: ?*?*ISideShowContent) callconv(.Inline) HRESULT { return @ptrCast(*const ISideShowEvents.VTable, self.vtable).ContentMissing(@ptrCast(*const ISideShowEvents, self), in_contentId, out_ppIContent); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn ISideShowEvents_ApplicationEvent(self: *const T, in_pICapabilities: ?*ISideShowCapabilities, in_dwEventId: u32, in_dwEventSize: u32, in_pbEventData: ?[*:0]const u8) callconv(.Inline) HRESULT { return @ptrCast(*const ISideShowEvents.VTable, self.vtable).ApplicationEvent(@ptrCast(*const ISideShowEvents, self), in_pICapabilities, in_dwEventId, in_dwEventSize, in_pbEventData); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn ISideShowEvents_DeviceAdded(self: *const T, in_pIDevice: ?*ISideShowCapabilities) callconv(.Inline) HRESULT { return @ptrCast(*const ISideShowEvents.VTable, self.vtable).DeviceAdded(@ptrCast(*const ISideShowEvents, self), in_pIDevice); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn ISideShowEvents_DeviceRemoved(self: *const T, in_pIDevice: ?*ISideShowCapabilities) callconv(.Inline) HRESULT { return @ptrCast(*const ISideShowEvents.VTable, self.vtable).DeviceRemoved(@ptrCast(*const ISideShowEvents, self), in_pIDevice); } };} pub usingnamespace MethodMixin(@This()); }; const IID_ISideShowCapabilities_Value = @import("../zig.zig").Guid.initString("535e1379-c09e-4a54-a511-597bab3a72b8"); pub const IID_ISideShowCapabilities = &IID_ISideShowCapabilities_Value; pub const ISideShowCapabilities = extern struct { pub const VTable = extern struct { base: IUnknown.VTable, GetCapability: fn( self: *const ISideShowCapabilities, in_keyCapability: ?*const PROPERTYKEY, inout_pValue: ?*PROPVARIANT, ) 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 ISideShowCapabilities_GetCapability(self: *const T, in_keyCapability: ?*const PROPERTYKEY, inout_pValue: ?*PROPVARIANT) callconv(.Inline) HRESULT { return @ptrCast(*const ISideShowCapabilities.VTable, self.vtable).GetCapability(@ptrCast(*const ISideShowCapabilities, self), in_keyCapability, inout_pValue); } };} pub usingnamespace MethodMixin(@This()); }; const IID_ISideShowCapabilitiesCollection_Value = @import("../zig.zig").Guid.initString("50305597-5e0d-4ff7-b3af-33d0d9bd52dd"); pub const IID_ISideShowCapabilitiesCollection = &IID_ISideShowCapabilitiesCollection_Value; pub const ISideShowCapabilitiesCollection = extern struct { pub const VTable = extern struct { base: IUnknown.VTable, GetCount: fn( self: *const ISideShowCapabilitiesCollection, out_pdwCount: ?*u32, ) callconv(@import("std").os.windows.WINAPI) HRESULT, GetAt: fn( self: *const ISideShowCapabilitiesCollection, in_dwIndex: u32, out_ppCapabilities: ?*?*ISideShowCapabilities, ) 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 ISideShowCapabilitiesCollection_GetCount(self: *const T, out_pdwCount: ?*u32) callconv(.Inline) HRESULT { return @ptrCast(*const ISideShowCapabilitiesCollection.VTable, self.vtable).GetCount(@ptrCast(*const ISideShowCapabilitiesCollection, self), out_pdwCount); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn ISideShowCapabilitiesCollection_GetAt(self: *const T, in_dwIndex: u32, out_ppCapabilities: ?*?*ISideShowCapabilities) callconv(.Inline) HRESULT { return @ptrCast(*const ISideShowCapabilitiesCollection.VTable, self.vtable).GetAt(@ptrCast(*const ISideShowCapabilitiesCollection, self), in_dwIndex, out_ppCapabilities); } };} pub usingnamespace MethodMixin(@This()); }; const IID_ISideShowBulkCapabilities_Value = @import("../zig.zig").Guid.initString("3a2b7fbc-3ad5-48bd-bbf1-0e6cfbd10807"); pub const IID_ISideShowBulkCapabilities = &IID_ISideShowBulkCapabilities_Value; pub const ISideShowBulkCapabilities = extern struct { pub const VTable = extern struct { base: ISideShowCapabilities.VTable, GetCapabilities: fn( self: *const ISideShowBulkCapabilities, in_keyCollection: ?*ISideShowKeyCollection, inout_pValues: ?*?*ISideShowPropVariantCollection, ) callconv(@import("std").os.windows.WINAPI) HRESULT, }; vtable: *const VTable, pub fn MethodMixin(comptime T: type) type { return struct { pub usingnamespace ISideShowCapabilities.MethodMixin(T); // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn ISideShowBulkCapabilities_GetCapabilities(self: *const T, in_keyCollection: ?*ISideShowKeyCollection, inout_pValues: ?*?*ISideShowPropVariantCollection) callconv(.Inline) HRESULT { return @ptrCast(*const ISideShowBulkCapabilities.VTable, self.vtable).GetCapabilities(@ptrCast(*const ISideShowBulkCapabilities, self), in_keyCollection, inout_pValues); } };} pub usingnamespace MethodMixin(@This()); }; const IID_ISideShowKeyCollection_Value = @import("../zig.zig").Guid.initString("045473bc-a37b-4957-b144-68105411ed8e"); pub const IID_ISideShowKeyCollection = &IID_ISideShowKeyCollection_Value; pub const ISideShowKeyCollection = extern struct { pub const VTable = extern struct { base: IUnknown.VTable, Add: fn( self: *const ISideShowKeyCollection, Key: ?*const PROPERTYKEY, ) callconv(@import("std").os.windows.WINAPI) HRESULT, Clear: fn( self: *const ISideShowKeyCollection, ) callconv(@import("std").os.windows.WINAPI) HRESULT, GetAt: fn( self: *const ISideShowKeyCollection, dwIndex: u32, pKey: ?*PROPERTYKEY, ) callconv(@import("std").os.windows.WINAPI) HRESULT, GetCount: fn( self: *const ISideShowKeyCollection, pcElems: ?*u32, ) callconv(@import("std").os.windows.WINAPI) HRESULT, RemoveAt: fn( self: *const ISideShowKeyCollection, dwIndex: 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 ISideShowKeyCollection_Add(self: *const T, Key: ?*const PROPERTYKEY) callconv(.Inline) HRESULT { return @ptrCast(*const ISideShowKeyCollection.VTable, self.vtable).Add(@ptrCast(*const ISideShowKeyCollection, self), Key); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn ISideShowKeyCollection_Clear(self: *const T) callconv(.Inline) HRESULT { return @ptrCast(*const ISideShowKeyCollection.VTable, self.vtable).Clear(@ptrCast(*const ISideShowKeyCollection, self)); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn ISideShowKeyCollection_GetAt(self: *const T, dwIndex: u32, pKey: ?*PROPERTYKEY) callconv(.Inline) HRESULT { return @ptrCast(*const ISideShowKeyCollection.VTable, self.vtable).GetAt(@ptrCast(*const ISideShowKeyCollection, self), dwIndex, pKey); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn ISideShowKeyCollection_GetCount(self: *const T, pcElems: ?*u32) callconv(.Inline) HRESULT { return @ptrCast(*const ISideShowKeyCollection.VTable, self.vtable).GetCount(@ptrCast(*const ISideShowKeyCollection, self), pcElems); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn ISideShowKeyCollection_RemoveAt(self: *const T, dwIndex: u32) callconv(.Inline) HRESULT { return @ptrCast(*const ISideShowKeyCollection.VTable, self.vtable).RemoveAt(@ptrCast(*const ISideShowKeyCollection, self), dwIndex); } };} pub usingnamespace MethodMixin(@This()); }; const IID_ISideShowPropVariantCollection_Value = @import("../zig.zig").Guid.initString("2ea7a549-7bff-4aae-bab0-22d43111de49"); pub const IID_ISideShowPropVariantCollection = &IID_ISideShowPropVariantCollection_Value; pub const ISideShowPropVariantCollection = extern struct { pub const VTable = extern struct { base: IUnknown.VTable, Add: fn( self: *const ISideShowPropVariantCollection, pValue: ?*const PROPVARIANT, ) callconv(@import("std").os.windows.WINAPI) HRESULT, Clear: fn( self: *const ISideShowPropVariantCollection, ) callconv(@import("std").os.windows.WINAPI) HRESULT, GetAt: fn( self: *const ISideShowPropVariantCollection, dwIndex: u32, pValue: ?*PROPVARIANT, ) callconv(@import("std").os.windows.WINAPI) HRESULT, GetCount: fn( self: *const ISideShowPropVariantCollection, pcElems: ?*u32, ) callconv(@import("std").os.windows.WINAPI) HRESULT, RemoveAt: fn( self: *const ISideShowPropVariantCollection, dwIndex: 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 ISideShowPropVariantCollection_Add(self: *const T, pValue: ?*const PROPVARIANT) callconv(.Inline) HRESULT { return @ptrCast(*const ISideShowPropVariantCollection.VTable, self.vtable).Add(@ptrCast(*const ISideShowPropVariantCollection, self), pValue); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn ISideShowPropVariantCollection_Clear(self: *const T) callconv(.Inline) HRESULT { return @ptrCast(*const ISideShowPropVariantCollection.VTable, self.vtable).Clear(@ptrCast(*const ISideShowPropVariantCollection, self)); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn ISideShowPropVariantCollection_GetAt(self: *const T, dwIndex: u32, pValue: ?*PROPVARIANT) callconv(.Inline) HRESULT { return @ptrCast(*const ISideShowPropVariantCollection.VTable, self.vtable).GetAt(@ptrCast(*const ISideShowPropVariantCollection, self), dwIndex, pValue); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn ISideShowPropVariantCollection_GetCount(self: *const T, pcElems: ?*u32) callconv(.Inline) HRESULT { return @ptrCast(*const ISideShowPropVariantCollection.VTable, self.vtable).GetCount(@ptrCast(*const ISideShowPropVariantCollection, self), pcElems); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn ISideShowPropVariantCollection_RemoveAt(self: *const T, dwIndex: u32) callconv(.Inline) HRESULT { return @ptrCast(*const ISideShowPropVariantCollection.VTable, self.vtable).RemoveAt(@ptrCast(*const ISideShowPropVariantCollection, self), dwIndex); } };} pub usingnamespace MethodMixin(@This()); }; pub const SIDESHOW_SCREEN_TYPE = enum(i32) { BITMAP = 0, TEXT = 1, }; pub const SIDESHOW_SCREEN_TYPE_BITMAP = SIDESHOW_SCREEN_TYPE.BITMAP; pub const SIDESHOW_SCREEN_TYPE_TEXT = SIDESHOW_SCREEN_TYPE.TEXT; pub const SIDESHOW_COLOR_TYPE = enum(i32) { COLOR = 0, GREYSCALE = 1, BLACK_AND_WHITE = 2, }; pub const SIDESHOW_COLOR_TYPE_COLOR = SIDESHOW_COLOR_TYPE.COLOR; pub const SIDESHOW_COLOR_TYPE_GREYSCALE = SIDESHOW_COLOR_TYPE.GREYSCALE; pub const SIDESHOW_COLOR_TYPE_BLACK_AND_WHITE = SIDESHOW_COLOR_TYPE.BLACK_AND_WHITE; pub const SCF_EVENT_IDS = enum(i32) { NAVIGATION = 1, MENUACTION = 2, CONTEXTMENU = 3, }; pub const SCF_EVENT_NAVIGATION = SCF_EVENT_IDS.NAVIGATION; pub const SCF_EVENT_MENUACTION = SCF_EVENT_IDS.MENUACTION; pub const SCF_EVENT_CONTEXTMENU = SCF_EVENT_IDS.CONTEXTMENU; pub const SCF_BUTTON_IDS = enum(i32) { MENU = 1, SELECT = 2, UP = 3, DOWN = 4, LEFT = 5, RIGHT = 6, PLAY = 7, PAUSE = 8, FASTFORWARD = 9, REWIND = 10, STOP = 11, BACK = 65280, }; pub const SCF_BUTTON_MENU = SCF_BUTTON_IDS.MENU; pub const SCF_BUTTON_SELECT = SCF_BUTTON_IDS.SELECT; pub const SCF_BUTTON_UP = SCF_BUTTON_IDS.UP; pub const SCF_BUTTON_DOWN = SCF_BUTTON_IDS.DOWN; pub const SCF_BUTTON_LEFT = SCF_BUTTON_IDS.LEFT; pub const SCF_BUTTON_RIGHT = SCF_BUTTON_IDS.RIGHT; pub const SCF_BUTTON_PLAY = SCF_BUTTON_IDS.PLAY; pub const SCF_BUTTON_PAUSE = SCF_BUTTON_IDS.PAUSE; pub const SCF_BUTTON_FASTFORWARD = SCF_BUTTON_IDS.FASTFORWARD; pub const SCF_BUTTON_REWIND = SCF_BUTTON_IDS.REWIND; pub const SCF_BUTTON_STOP = SCF_BUTTON_IDS.STOP; pub const SCF_BUTTON_BACK = SCF_BUTTON_IDS.BACK; pub const SCF_EVENT_HEADER = extern struct { PreviousPage: u32, TargetPage: u32, }; pub const SCF_NAVIGATION_EVENT = extern struct { PreviousPage: u32, TargetPage: u32, Button: u32, }; pub const SCF_MENUACTION_EVENT = extern struct { PreviousPage: u32, TargetPage: u32, Button: u32, ItemId: u32, }; pub const SCF_CONTEXTMENU_EVENT = extern struct { PreviousPage: u32, TargetPage: u32, PreviousItemId: u32, MenuPage: u32, MenuItemId: u32, }; pub const CONTENT_MISSING_EVENT_DATA = packed struct { cbContentMissingEventData: u32, ApplicationId: Guid, EndpointId: Guid, ContentId: u32, }; pub const APPLICATION_EVENT_DATA = packed struct { cbApplicationEventData: u32, ApplicationId: Guid, EndpointId: Guid, dwEventId: u32, cbEventData: u32, bEventData: [1]u8, }; pub const DEVICE_USER_CHANGE_EVENT_DATA = packed struct { cbDeviceUserChangeEventData: u32, wszUser: u16, }; pub const NEW_EVENT_DATA_AVAILABLE = packed struct { cbNewEventDataAvailable: u32, dwVersion: u32, }; pub const EVENT_DATA_HEADER = packed struct { cbEventDataHeader: u32, guidEventType: Guid, dwVersion: u32, cbEventDataSid: u32, }; //-------------------------------------------------------------------------------- // 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 (9) //-------------------------------------------------------------------------------- const Guid = @import("../zig.zig").Guid; const BOOL = @import("../foundation.zig").BOOL; const HICON = @import("../ui/windows_and_messaging.zig").HICON; const HRESULT = @import("../foundation.zig").HRESULT; const IUnknown = @import("../system/com.zig").IUnknown; const PROPERTYKEY = @import("../ui/shell/properties_system.zig").PROPERTYKEY; const PROPVARIANT = @import("../system/com/structured_storage.zig").PROPVARIANT; const PWSTR = @import("../foundation.zig").PWSTR; const SYSTEMTIME = @import("../foundation.zig").SYSTEMTIME; 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/system/side_show.zig
const std = @import("std"); const io = std.io; const fs = std.fs; const testing = std.testing; const mem = std.mem; const deflate = std.compress.deflate; pub fn ZlibStream(comptime ReaderType: type) type { return struct { const Self = @This(); pub const Error = ReaderType.Error || deflate.Decompressor(ReaderType).Error || error{ WrongChecksum, Unsupported }; pub const Reader = io.Reader(*Self, Error, read); allocator: mem.Allocator, inflater: deflate.Decompressor(ReaderType), in_reader: ReaderType, hasher: std.hash.Adler32, fn init(allocator: mem.Allocator, source: ReaderType) !Self { // Zlib header format is specified in RFC1950 const header = try source.readBytesNoEof(2); const CM = @truncate(u4, header[0]); const CINFO = @truncate(u4, header[0] >> 4); const FCHECK = @truncate(u5, header[1]); _ = FCHECK; const FDICT = @truncate(u1, header[1] >> 5); if ((@as(u16, header[0]) << 8 | header[1]) % 31 != 0) return error.BadHeader; // The CM field must be 8 to indicate the use of DEFLATE if (CM != 8) return error.InvalidCompression; // CINFO is the base-2 logarithm of the LZ77 window size, minus 8. // Values above 7 are unspecified and therefore rejected. if (CINFO > 7) return error.InvalidWindowSize; const dictionary = null; // TODO: Support this case if (FDICT != 0) return error.Unsupported; return Self{ .allocator = allocator, .inflater = try deflate.decompressor(allocator, source, dictionary), .in_reader = source, .hasher = std.hash.Adler32.init(), }; } pub fn deinit(self: *Self) void { self.inflater.deinit(); } // Implements the io.Reader interface pub fn read(self: *Self, buffer: []u8) Error!usize { if (buffer.len == 0) return 0; // Read from the compressed stream and update the computed checksum const r = try self.inflater.read(buffer); if (r != 0) { self.hasher.update(buffer[0..r]); return r; } // We've reached the end of stream, check if the checksum matches const hash = try self.in_reader.readIntBig(u32); if (hash != self.hasher.final()) return error.WrongChecksum; return 0; } pub fn reader(self: *Self) Reader { return .{ .context = self }; } }; } pub fn zlibStream(allocator: mem.Allocator, reader: anytype) !ZlibStream(@TypeOf(reader)) { return ZlibStream(@TypeOf(reader)).init(allocator, reader); } fn testReader(data: []const u8, expected: []const u8) !void { var in_stream = io.fixedBufferStream(data); var zlib_stream = try zlibStream(testing.allocator, in_stream.reader()); defer zlib_stream.deinit(); // Read and decompress the whole file const buf = try zlib_stream.reader().readAllAlloc(testing.allocator, std.math.maxInt(usize)); defer testing.allocator.free(buf); // Check against the reference try testing.expectEqualSlices(u8, buf, expected); } // All the test cases are obtained by compressing the RFC1951 text // // https://tools.ietf.org/rfc/rfc1951.txt length=36944 bytes // SHA256=5ebf4b5b7fe1c3a0c0ab9aa3ac8c0f3853a7dc484905e76e03b0b0f301350009 test "compressed data" { const rfc1951_txt = @embedFile("rfc1951.txt"); // Compressed with compression level = 0 try testReader( @embedFile("rfc1951.txt.z.0"), rfc1951_txt, ); // Compressed with compression level = 9 try testReader( @embedFile("rfc1951.txt.z.9"), rfc1951_txt, ); // Compressed with compression level = 9 and fixed Huffman codes try testReader( @embedFile("rfc1951.txt.fixed.z.9"), rfc1951_txt, ); } test "don't read past deflate stream's end" { try testReader(&[_]u8{ 0x08, 0xd7, 0x63, 0xf8, 0xcf, 0xc0, 0xc0, 0x00, 0xc1, 0xff, 0xff, 0x43, 0x30, 0x03, 0x03, 0xc3, 0xff, 0xff, 0xff, 0x01, 0x83, 0x95, 0x0b, 0xf5, }, &[_]u8{ 0x00, 0xff, 0x00, 0x00, 0x00, 0xff, 0x00, 0x00, 0x00, 0xff, 0x00, 0xff, 0xff, 0xff, 0x00, 0xff, 0xff, 0xff, 0x00, 0x00, 0x00, 0x00, 0xff, 0xff, 0xff, }); } test "sanity checks" { // Truncated header try testing.expectError( error.EndOfStream, testReader(&[_]u8{0x78}, ""), ); // Failed FCHECK check try testing.expectError( error.BadHeader, testReader(&[_]u8{ 0x78, 0x9D }, ""), ); // Wrong CM try testing.expectError( error.InvalidCompression, testReader(&[_]u8{ 0x79, 0x94 }, ""), ); // Wrong CINFO try testing.expectError( error.InvalidWindowSize, testReader(&[_]u8{ 0x88, 0x98 }, ""), ); // Wrong checksum try testing.expectError( error.WrongChecksum, testReader(&[_]u8{ 0x78, 0xda, 0x03, 0x00, 0x00, 0x00, 0x00, 0x00 }, ""), ); // Truncated checksum try testing.expectError( error.EndOfStream, testReader(&[_]u8{ 0x78, 0xda, 0x03, 0x00, 0x00 }, ""), ); }
lib/std/compress/zlib.zig
const std = @import("std"); const warn = std.debug.warn; const assert = std.debug.assert; const File = std.fs.File; const ASCII = std.ASCII; const TypeId = @import("builtin").TypeId; const TypeInfo = @import("builtin").TypeInfo; fn clamp(comptime T: type, v: T, min: T, max: T) T { if (v < min) { return min; } else { if (v > max) { return max; } else { return v; } } } fn lerp(a: f32, b: f32, f: f32) f32 { return (1.0 - f) * a + f * b; } fn Color(comptime T: type) type { return packed struct { const Self = @This(); const Component = T; const black = Self{ .R = 0, .G = 0, .B = 0 }; const white = Self{ .R = 1, .G = 1, .B = 1 }; R: Component, G: Component, B: Component, fn gray(v: T) Self { return Self{ .R = v, .G = v, .B = v }; } fn rgb(r: T, g: T, b: T) Self { return Self{ .R = r, .G = g, .B = b, }; } fn equals(self: Self, b: Self) bool { return self.R == b.R and self.G == b.G and self.B == b.B; } fn mix(a: Self, b: Self, f: f32) Self { return Self{ .R = lerp(a.R, b.R, f), .G = lerp(a.G, b.G, f), .B = lerp(a.B, b.B, f), }; } fn applyGamma(a: Self, gamma: f32) Self { return Self{ .R = std.math.pow(f32, a.R, gamma), .G = std.math.pow(f32, a.G, gamma), .B = std.math.pow(f32, a.B, gamma), }; } fn toSRGB(self: Self) Self { return self.applyGamma(1.0 / 2.2); } fn toLinear(self: Self) Self { return self.applyGamma(2.2); } }; } fn isInteger(comptime T: type) bool { return @typeInfo(T) == TypeId.Int; } fn isFloat(comptime T: type) bool { return @typeInfo(T) == TypeId.Float; } fn map_to_uniform(value: var) f64 { const T = @typeOf(value); switch (@typeInfo(T)) { TypeId.Int => |t| { if (t.is_signed) { const min = @intToFloat(f64, -(1 << (t.bits - 1))); const max = @intToFloat(f64, (1 << (t.bits - 1))); return (@intToFloat(f64, value) - min) / (max - min); } else { const max = @intToFloat(f64, (1 << t.bits) - 1); return @intToFloat(f64, value) / max; } }, TypeId.Float => |t| { return f64(value); }, else => @compileError(@typeName(@typeOf(value)) ++ " is neither integer nor float!"), } } fn map_from_uniform(comptime T: type, value: f64) T { switch (@typeInfo(T)) { TypeId.Int => |t| { if (t.is_signed) { const min = @intToFloat(f64, -(1 << (t.bits - 1))); const max = @intToFloat(f64, (1 << (t.bits - 1))); return @floatToInt(T, std.math.floor((max - min) * value + min)); } else { const max = @intToFloat(f64, (1 << t.bits) - 1); return @floatToInt(T, std.math.floor(max * value)); } }, TypeId.Float => |t| { return @floatCast(T, value); }, else => @panic("Unsupported type " ++ @typeName(T)), } } fn mapColor(comptime TOut: type, c: var) TOut { const TIn = @typeOf(c); if (TIn == TOut) return c; var r = map_to_uniform(c.R); var g = map_to_uniform(c.G); var b = map_to_uniform(c.B); r = clamp(f64, r, 0.0, 1.0); g = clamp(f64, g, 0.0, 1.0); b = clamp(f64, b, 0.0, 1.0); return TOut{ .R = map_from_uniform(TOut.Component, r), .G = map_from_uniform(TOut.Component, g), .B = map_from_uniform(TOut.Component, b), }; } test "mapColor" { comptime { var c_u8 = Color(u8){ .R = 0xFF, .G = 0x00, .B = 0x00 }; var c_f32 = Color(f32){ .R = 1.0, .G = 0.0, .B = 0.0 }; assert(mapColor(@typeOf(c_f32), c_u8).equals(c_f32)); assert(mapColor(@typeOf(c_u8), c_f32).equals(c_u8)); } } fn RGB(comptime hexspec: [7]u8) error{InvalidCharacter}!Color(u8) { if (hexspec[0] != '#') return error.InvalidCharacter; return Color(u8){ .R = ((try std.fmt.charToDigit(hexspec[1], 16)) << 4) | (try std.fmt.charToDigit(hexspec[2], 16)), .G = ((try std.fmt.charToDigit(hexspec[3], 16)) << 4) | (try std.fmt.charToDigit(hexspec[4], 16)), .B = ((try std.fmt.charToDigit(hexspec[5], 16)) << 4) | (try std.fmt.charToDigit(hexspec[6], 16)), }; } const RED = RGB("#FF0000"); const GREEN = RGB("#00FF00"); const BLUE = RGB("#0000FF"); test "RGB" { // assert(compareColors(try RGB("#123456"), Color { .R = 0x12, .G = 0x34, .B = 0x56 })); assert((try RGB("#123456")).equals(Color(u8){ .R = 0x12, .G = 0x34, .B = 0x56 })); assert(if (RGB("!000000")) |c| false else |err| err == error.InvalidCharacter); assert(if (RGB("#X00000")) |c| false else |err| err == error.InvalidCharacter); } fn Bitmap(comptime TColor: type, comptime width: comptime_int, comptime height: comptime_int) type { return struct { const Self = @This(); const MyColor = TColor; pixels: [width * height]MyColor, fn create() Self { return Self{ .pixels = undefined }; } fn get_width(_: Self) usize { return width; } fn get_height(_: Self) usize { return height; } fn get(self: Self, x: usize, y: usize) error{OutOfRange}!MyColor { if (x >= width or y >= height) { return error.OutOfRange; } else { return self.pixels[y * width + x]; } } fn set(self: *Self, x: usize, y: usize, color: MyColor) error{OutOfRange}!void { if (x >= width or y >= height) { return error.OutOfRange; } else { self.pixels[y * width + x] = color; } } }; } fn Times(comptime len: comptime_int) [len]void { const val: [len]void = undefined; return val; } const float = f32; const Vec2 = struct { x: float, y: float, }; const Vec3 = struct { const zero = Vec3{ .x = 0, .y = 0, .z = 0 }; const up = Vec3{ .x = 0, .y = 1, .z = 0 }; const forward = Vec3{ .x = 0, .y = 0, .z = -1 }; const right = Vec3{ .x = 1, .y = 0, .z = 0 }; x: float, y: float, z: float, fn length(self: Vec3) float { return std.math.sqrt(self.x * self.x + self.y * self.y + self.z * self.z); } fn add(self: Vec3, other: Vec3) Vec3 { return Vec3{ .x = self.x + other.x, .y = self.y + other.y, .z = self.z + other.z, }; } fn sub(self: Vec3, other: Vec3) Vec3 { return Vec3{ .x = self.x - other.x, .y = self.y - other.y, .z = self.z - other.z, }; } fn scale(self: Vec3, f: float) Vec3 { return Vec3{ .x = self.x * f, .y = self.y * f, .z = self.z * f, }; } fn normalize(self: Vec3) Vec3 { return self.scale(1.0 / self.length()); } fn dot(self: Vec3, other: Vec3) float { return self.x * other.x + self.y * other.y + self.z * other.z; } fn cross(a: Vec3, b: Vec3) Vec3 { return Vec3{ .x = a.y * b.z - a.z * b.y, .y = a.z * b.x - a.x * b.z, .z = a.x * b.y - a.y * b.x, }; } fn distance(a: Vec3, b: Vec3) float { return a.sub(b).length(); } }; fn vec3(x: float, y: float, z: float) Vec3 { return Vec3{ .x = x, .y = y, .z = z, }; } const Plane = struct { origin: Vec3, normal: Vec3, fn toGeometry(self: @This()) Geometry { return Geometry{ .plane = self }; } }; const Sphere = struct { origin: Vec3, radius: f32, fn toGeometry(self: @This()) Geometry { return Geometry{ .sphere = self }; } }; const Geometry = union(enum) { plane: Plane, sphere: Sphere, }; const Material = struct { albedo: Color(f32), roughness: float, metalness: float, }; const Object = struct { geometry: Geometry, material: Material, }; const Ray = struct { origin: Vec3, direction: Vec3, const Hit = struct { position: Vec3, normal: Vec3, distance: float, }; fn intersect(ray: Ray, obj: Geometry) ?Hit { switch (obj) { Geometry.plane => |plane| { const denom = plane.normal.dot(ray.direction); if (denom < -1e-6) { const p0l0 = plane.origin.sub(ray.origin); const t = p0l0.dot(plane.normal) / denom; if (t >= 0) { return Hit{ .distance = t, .position = ray.origin.add(ray.direction.scale(t)), .normal = plane.normal, }; } } return null; }, Geometry.sphere => |sphere| { // geometric solution const L = sphere.origin.sub(ray.origin); var tca = L.dot(ray.direction); // if (tca < 0) return false; var d2 = L.dot(L) - tca * tca; if (d2 > sphere.radius * sphere.radius) { return null; } const thc = std.math.sqrt(sphere.radius * sphere.radius - d2); const t0 = tca - thc; const t1 = tca + thc; const d = std.math.min(t0, t1); if (d >= 0) { return Hit{ .distance = d, .position = ray.origin.add(ray.direction.scale(d)), .normal = ray.origin.add(ray.direction.scale(d)).sub(sphere.origin).normalize(), }; } }, } return null; } }; const Camera = struct { origin: Vec3, forward: Vec3, up: Vec3, right: Vec3, focalLength: float, fn lookAt(origin: Vec3, target: Vec3, up: Vec3, focalLength: float) Camera { var cam = Camera{ .origin = origin, .forward = target.sub(origin).normalize(), .up = undefined, .right = undefined, .focalLength = focalLength, }; cam.right = up.cross(cam.forward).normalize(); cam.up = cam.forward.cross(cam.right).normalize(); return cam; } fn constructRay(self: Camera, uv: Vec2) Ray { return Ray{ .origin = self.origin, .direction = self.forward.scale(self.focalLength).add(self.right.scale(uv.x)).add(self.up.scale(uv.y)).normalize(), }; } }; const scene = [_]Object{ Object{ .geometry = (Plane{ .origin = Vec3.zero, .normal = Vec3.up, }).toGeometry(), .material = Material{ .albedo = Color(f32).gray(0.8), .roughness = 1.0, .metalness = 0.0, }, }, Object{ .geometry = (Sphere{ .origin = vec3(0, 0, 5), .radius = 1.0, }).toGeometry(), .material = Material{ .albedo = Color(f32).rgb(1.0, 0.0, 0.0), .roughness = 1.0, .metalness = 0.0, }, }, Object{ .geometry = (Sphere{ .origin = vec3(5, 0, 5), .radius = 1.0, }).toGeometry(), .material = Material{ .albedo = Color(f32).rgb(0.0, 1.0, 0.0), .roughness = 1.0, .metalness = 0.0, }, }, Object{ .geometry = (Sphere{ .origin = vec3(5, 4, 5), .radius = 1.0, }).toGeometry(), .material = Material{ .albedo = Color(f32).rgb(0.0, 0.0, 1.0), .roughness = 1.0, .metalness = 0.0, }, }, }; const camera = Camera.lookAt(vec3(0, 2, 0), vec3(0, 2, 100), Vec3.up, 1.0); const HitTestResult = struct { geom: Ray.Hit, obj: *const Object, }; fn hitTest(ray: Ray) ?HitTestResult { var hit: ?HitTestResult = null; for (scene) |*obj| { if (ray.intersect(obj.geometry)) |pt| { const hit_obj = HitTestResult{ .geom = pt, .obj = obj, }; if (hit) |*h2| { if (h2.geom.distance > pt.distance) { h2.* = hit_obj; } } else { hit = hit_obj; } } } return hit; } fn render(uv: Vec2) Color(f32) { const ray = camera.constructRay(uv); const maybe_hit = hitTest(ray); if (maybe_hit) |hit| { var col = hit.obj.material.albedo; if (hitTest(Ray{ .origin = hit.geom.position.add(hit.geom.normal.scale(1e-5)), .direction = vec3(0.7, 1, -0.5).normalize(), })) |_| { col.R *= 0.5; col.G *= 0.5; col.B *= 0.5; } return col.toSRGB(); } else { return Color(f32){ .R = 0.8, .G = 0.8, .B = 1.0 }; } } var ms_rng = std.rand.DefaultPrng.init(0); fn render_multisample(uv: Vec2, sampleCount: usize, sampleRadius: Vec2) Color(f32) { var result = Color(f32).black; if (sampleCount <= 1) { result = render(uv); } else { var i: usize = 0; while (i < sampleCount) : (i += 1) { var dx = ms_rng.random.float(f32); var dy = ms_rng.random.float(f32); var c = render(Vec2{ .x = uv.x + 0.5 * sampleRadius.x * (dx - 0.5), .y = uv.y + 0.5 * sampleRadius.y * (dy - 0.5), }); result.R += c.R; result.G += c.G; result.B += c.B; } } return Color(f32).mix(Color(f32).black, result, 1.0 / @intToFloat(f32, sampleCount)); } const pic = struct { var bmp = Bitmap(Color(u8), 320, 240).create(); }; pub fn main() !void { var bmp = &pic.bmp; const image_size = Vec2{ .x = @intToFloat(float, bmp.get_width()), .y = @intToFloat(float, bmp.get_height()), }; const aspect: float = image_size.x / image_size.y; const pixel_scale = Vec2{ .x = 1.0 / (image_size.x - 1), .y = 1.0 / (image_size.y - 1), }; var y: usize = 0; while (y < bmp.get_height()) : (y += 1) { var x: usize = 0; while (x < bmp.get_width()) : (x += 1) { const uv = Vec2{ .x = aspect * (2.0 * @intToFloat(float, x) * pixel_scale.x - 1.0), .y = 1.0 - 2.0 * @intToFloat(float, y) * pixel_scale.y, }; const val = render_multisample(uv, 1, Vec2{ .x = aspect * pixel_scale.x, .y = pixel_scale.y }); const mapped = mapColor(Color(u8), val); try bmp.set(x, y, mapped); } if ((y % 10) == 9) { warn("\rrender process: {} % ", @floatToInt(i32, std.math.ceil(100.0 * @intToFloat(f32, y + 1) / image_size.y))); } } warn("\ndone!\n"); try savePGM(bmp, "result.pgm"); } fn savePGM(bmp: var, file: []const u8) !void { assert(@typeOf(bmp.*).MyColor.Component == u8); var f = try File.openWrite("result.pgm"); defer f.close(); var buf: [64]u8 = undefined; try f.write(try std.fmt.bufPrint(buf[0..], "P6 {} {} 255\n", bmp.get_width(), bmp.get_height())); try f.write(@sliceToBytes(bmp.pixels[0..])); }
tracer.zig
const std = @import("std"); const zig = std.zig; const Node = zig.ast.Node; const Tree = zig.ast.Tree; const mem = std.mem; const eql = mem.eql; /// null if cannot be determined pub fn isType(tree: *Tree, node: *Node) ?bool { switch (node.id) { .ErrorType, .AnyFrameType, .ErrorSetDecl, .VarType => return true, .ContainerDecl => { // TODO check for namespace return true; }, .BuiltinCall => { const builtin = @fieldParentPtr(Node.BuiltinCall, "base", node); const name = tree.tokenSlice(builtin.builtin_token); if (eql(u8, name, "@import")) return null; return eql(u8, name, "@TypeOf") or eql(u8, name, "@Vector") or eql(u8, name, "@Frame") or eql(u8, name, "@OpaqueType") or eql(u8, name, "@TagType") or eql(u8, name, "@This") or eql(u8, name, "@Type") or eql(u8, name, "@typeInfo"); }, .InfixOp => { const infix = @fieldParentPtr(Node.InfixOp, "base", node); if (infix.op == .Period) return null; return infix.op == .ErrorUnion or infix.op == .MergeErrorSets; }, .PrefixOp => { const prefix = @fieldParentPtr(Node.PrefixOp, "base", node); switch (prefix.op) { .ArrayType, .OptionalType, .PtrType, .SliceType, => return true, else => return false, } }, .SuffixOp => { const suffix = @fieldParentPtr(Node.SuffixOp, "base", node); if (suffix.op == .Call) return null; return false; }, .FnProto => { const proto = @fieldParentPtr(Node.FnProto, "base", node); return proto.body_node == null; }, .GroupedExpression => { const group = @fieldParentPtr(Node.GroupedExpression, "base", node); return isType(tree, group.expr); }, .Identifier => { const ident = @fieldParentPtr(Node.Identifier, "base", node); const name = tree.tokenSlice(ident.token); if (name.len > 1 and (name[0] == 'u' or name[0] == 'i')) { for (name[1..]) |c| { switch (c) { '0'...'9' => {}, else => return false, } } return true; } if (eql(u8, name, "void") or eql(u8, name, "comptime_float") or eql(u8, name, "comptime_int") or eql(u8, name, "bool") or eql(u8, name, "isize") or eql(u8, name, "usize") or eql(u8, name, "f16") or eql(u8, name, "f32") or eql(u8, name, "f64") or eql(u8, name, "f128") or eql(u8, name, "c_longdouble") or eql(u8, name, "noreturn") or eql(u8, name, "type") or eql(u8, name, "anyerror") or eql(u8, name, "c_short") or eql(u8, name, "c_ushort") or eql(u8, name, "c_int") or eql(u8, name, "c_uint") or eql(u8, name, "c_long") or eql(u8, name, "c_ulong") or eql(u8, name, "c_longlong") or eql(u8, name, "c_ulonglong")) return true; return null; }, else => return false, } } pub fn isSnakeCase(name: []const u8) bool { std.debug.assert(name.len != 0); var i: usize = 0; while (i < name.len) : (i += 1) { switch (name[i]) { 'a'...'z', '0'...'9' => {}, '_' => { if (i == 0 or i == name.len - 1) return false; }, else => return false, } } return true; } pub fn isCamelCase(name: []const u8) bool { std.debug.assert(name.len != 0); switch (name[0]) { 'a'...'z' => {}, else => return false, } var i: usize = 0; while (i < name.len) : (i += 1) { switch (name[i]) { 'a'...'z', '0'...'9', 'A'...'Z' => {}, else => return false, } } return true; } pub fn isTitleCase(name: []const u8) bool { std.debug.assert(name.len != 0); switch (name[0]) { 'A'...'Z' => {}, else => return false, } var i: usize = 0; while (i < name.len) : (i += 1) { switch (name[i]) { 'a'...'z', '0'...'9', 'A'...'Z' => {}, else => return false, } } return true; }
src/utils.zig
const std = @import("std"); const Allocator = std.mem.Allocator; const odbc = @import("odbc"); const Statement = odbc.Statement; const Connection = odbc.Connection; const sql_parameter = @import("parameter.zig"); const ParameterBucket = sql_parameter.ParameterBucket; const ResultSet = @import("result_set.zig").ResultSet; const catalog_types = @import("catalog.zig"); const Column = catalog_types.Column; const Table = catalog_types.Table; const TablePrivileges = catalog_types.TablePrivileges; pub const Cursor = struct { parameters: ?ParameterBucket = null, connection: Connection, statement: Statement, allocator: Allocator, pub fn init(allocator: Allocator, connection: Connection) !Cursor { return Cursor{ .allocator = allocator, .connection = connection, .statement = try Statement.init(connection), }; } pub fn deinit(self: *Cursor) !void { try self.close(); try self.statement.deinit(); self.clearParameters(); } /// Close the current cursor. If the cursor is not open, does nothing and does not return an error. pub fn close(self: *Cursor) !void { self.statement.closeCursor() catch |err| { var errors = try self.statement.getErrors(self.allocator); for (errors) |e| { // InvalidCursorState just means that no cursor was open on the statement. Here, we just want to // ignore this error and pretend everything succeeded. if (e == .InvalidCursorState) return; } return err; }; } /// Execute a SQL statement and return the result set. SQL query parameters can be passed with the `parameters` argument. /// This is the fastest way to execute a SQL statement once. pub fn executeDirect(self: *Cursor, comptime ResultType: type, parameters: anytype, sql_statement: []const u8) !ResultSet(ResultType) { var num_params: usize = 0; for (sql_statement) |c| { if (c == '?') num_params += 1; } if (num_params != parameters.len) return error.InvalidNumParams; self.clearParameters(); self.parameters = try ParameterBucket.init(self.allocator, num_params); defer { self.parameters.?.deinit(); self.parameters = null; } inline for (parameters) |param, index| { const stored_param = try self.parameters.?.addParameter(index, param); const sql_param = sql_parameter.default(param); try self.statement.bindParameter( @intCast(u16, index + 1), .Input, sql_param.c_type, sql_param.sql_type, stored_param.param, sql_param.precision, stored_param.indicator, ); } _ = try self.statement.executeDirect(sql_statement); return try ResultSet(ResultType).init(self.allocator, self.statement, 10); } /// Execute a statement and return the result set. A statement must have been prepared previously /// using `Cursor.prepare()`. pub fn execute(self: *Cursor, comptime ResultType: type) !ResultSet(ResultType) { _ = try self.statement.execute(); return try ResultSet(ResultType).init(self.allocator, self.statement, 10); } /// Prepare a SQL statement for execution. If you want to execute a statement multiple times, /// preparing it first is much faster because you only have to compile and load the statement /// once on the driver/DBMS. Use `Cursor.execute()` to get the results. pub fn prepare(self: *Cursor, parameters: anytype, sql_statement: []const u8) !void { try self.bindParameters(parameters); try self.statement.prepare(sql_statement); } pub fn insert(self: *Cursor, comptime DataType: type, comptime table_name: []const u8, values: []const DataType) !usize { // @todo Try using arrays of parameters for bulk ops const num_fields = comptime std.meta.fields(DataType).len; const insert_statement = comptime blk: { var statement: []const u8 = "INSERT INTO " ++ table_name ++ " ("; var statement_end: []const u8 = "VALUES ("; for (std.meta.fields(DataType)) |field, index| { statement_end = statement_end ++ "?"; var column_name: []const u8 = &[_]u8{}; for (field.name) |c| { column_name = column_name ++ [_]u8{std.ascii.toLower(c)}; } statement = statement ++ column_name; if (index < num_fields - 1) { statement = statement ++ ", "; statement_end = statement_end ++ ", "; } } statement = statement ++ ") " ++ statement_end ++ ")"; break :blk statement; }; try self.prepare(.{}, insert_statement); self.parameters = try ParameterBucket.init(self.allocator, num_fields); var num_rows_inserted: usize = 0; for (values) |value| { inline for (std.meta.fields(DataType)) |field, index| { try self.bindParameter(index + 1, @field(value, field.name)); } _ = try self.statement.execute(); num_rows_inserted += try self.statement.rowCount(); } // @todo manual-commit mode return num_rows_inserted; } /// When in manual-commit mode, use this to commit a transaction. **Important!:** This will /// commit *all open cursors allocated on this connection*. Be mindful of that before using /// this, if in a situation where you are using multiple cursors simultaneously. pub fn commit(self: *Cursor) !void { try self.connection.endTransaction(.commit); } /// When in manual-commit mode, use this to rollback a transaction. **Important!:** This will /// rollback *all open cursors allocated on this connection*. Be mindful of that before using /// this, if in a situation where you are using multiple cursors simultaneously. pub fn rollback(self: *Cursor) !void { try self.connection.endTransaction(.rollback); } pub fn columns(self: *Cursor, catalog_name: ?[]const u8, schema_name: ?[]const u8, table_name: []const u8) ![]Column { var result_set = try ResultSet(Column).init(self.allocator, self.statement, 10); defer result_set.deinit(); try self.statement.columns(catalog_name, schema_name, table_name, null); return try result_set.getAllRows(); } pub fn tables(self: *Cursor, catalog_name: ?[]const u8, schema_name: ?[]const u8) ![]Table { var result_set = try ResultSet(Table).init(self.allocator, self.statement, 10); defer result_set.deinit(); try self.statement.tables(catalog_name, schema_name, null, null); return try result_set.getAllRows(); } pub fn tablePrivileges(self: *Cursor, catalog_name: ?[]const u8, schema_name: ?[]const u8, table_name: []const u8) ![]TablePrivileges { var result_set = try ResultSet(TablePrivileges).init(self.allocator, self.statement, 10); defer result_set.deinit(); try self.statement.tablePrivileges(catalog_name, schema_name, table_name); return try result_set.getAllRows(); } /// Bind a single value to a SQL parameter. If `self.parameters` is `null`, this does nothing /// and does not return an error. Parameter indices start at 1. pub fn bindParameter(self: *Cursor, index: usize, parameter: anytype) !void { if (self.parameters) |*params| { const stored_param = try params.addParameter(index - 1, parameter); const sql_param = sql_parameter.default(parameter); try self.statement.bindParameter( @intCast(u16, index), .Input, sql_param.c_type, sql_param.sql_type, stored_param.param, sql_param.precision, stored_param.indicator, ); } } /// Bind a list of parameters to SQL parameters. The first item in the list will be bound /// to the parameter at index 1, the second to index 2, etc. /// /// Calling this function clears all existing parameters, and if an empty list is passed in /// will not re-initialize them. pub fn bindParameters(self: *Cursor, parameters: anytype) !void { self.clearParameters(); if (parameters.len > 0) { self.parameters = try ParameterBucket.init(self.allocator, parameters.len); } inline for (parameters) |param, index| { try self.bindParameter(index + 1, param); } } /// Deinitialize any parameters allocated on this statement (if any), and reset `self.parameters` to null. fn clearParameters(self: *Cursor) void { if (self.parameters) |*p| p.deinit(); self.parameters = null; } pub fn getErrors(self: *Cursor) []odbc.Error.DiagnosticRecord { return self.statement.getDiagnosticRecords() catch return &[_]odbc.Error.DiagnosticRecord{}; } };
src/cursor.zig
const std = @import("std"); const log = std.log.scoped(.egl); pub const c = @import("c.zig"); const android = @import("android-support.zig"); pub const Version = enum { gles2, gles3, }; pub const EGLContext = struct { const Self = @This(); display: c.EGLDisplay, surface: c.EGLSurface, context: c.EGLContext, pub fn init(window: *android.ANativeWindow, version: Version) !Self { const EGLint = c.EGLint; var egl_display = c.eglGetDisplay(null); if (egl_display == null) { log.err("Error: No display found!\n", .{}); return error.FailedToInitializeEGL; } var egl_major: EGLint = undefined; var egl_minor: EGLint = undefined; if (c.eglInitialize(egl_display, &egl_major, &egl_minor) == 0) { log.err("Error: eglInitialise failed!\n", .{}); return error.FailedToInitializeEGL; } log.info( \\EGL Version: {s} \\EGL Vendor: {s} \\EGL Extensions: {s} \\ , .{ std.mem.span(c.eglQueryString(egl_display, c.EGL_VERSION)), std.mem.span(c.eglQueryString(egl_display, c.EGL_VENDOR)), std.mem.span(c.eglQueryString(egl_display, c.EGL_EXTENSIONS)), }); const config_attribute_list = [_]EGLint{ c.EGL_RED_SIZE, 8, c.EGL_GREEN_SIZE, 8, c.EGL_BLUE_SIZE, 8, c.EGL_ALPHA_SIZE, 8, c.EGL_BUFFER_SIZE, 32, c.EGL_STENCIL_SIZE, 0, c.EGL_DEPTH_SIZE, 16, // c.EGL_SAMPLES, 1, c.EGL_RENDERABLE_TYPE, switch (version) { .gles3 => c.EGL_OPENGL_ES3_BIT, .gles2 => c.EGL_OPENGL_ES2_BIT, }, c.EGL_NONE, }; var config: c.EGLConfig = undefined; var num_config: c.EGLint = undefined; if (c.eglChooseConfig(egl_display, &config_attribute_list, &config, 1, &num_config) == c.EGL_FALSE) { log.err("Error: eglChooseConfig failed: 0x{X:0>4}\n", .{c.eglGetError()}); return error.FailedToInitializeEGL; } log.info("Config: {}\n", .{num_config}); const context_attribute_list = [_]EGLint{ c.EGL_CONTEXT_CLIENT_VERSION, 2, c.EGL_NONE }; var context = c.eglCreateContext(egl_display, config, null, &context_attribute_list); if (context == null) { log.err("Error: eglCreateContext failed: 0x{X:0>4}\n", .{c.eglGetError()}); return error.FailedToInitializeEGL; } errdefer _ = c.eglDestroyContext(egl_display, context); log.info("Context created: {}\n", .{context}); var native_window: c.EGLNativeWindowType = @ptrCast(c.EGLNativeWindowType, window); // this is safe, just a C import problem const android_width = android.ANativeWindow_getWidth(window); const android_height = android.ANativeWindow_getHeight(window); log.info("Screen Resolution: {}x{}\n", .{ android_width, android_height }); const window_attribute_list = [_]EGLint{c.EGL_NONE}; const egl_surface = c.eglCreateWindowSurface(egl_display, config, native_window, &window_attribute_list); log.info("Got Surface: {}\n", .{egl_surface}); if (egl_surface == null) { log.err("Error: eglCreateWindowSurface failed: 0x{X:0>4}\n", .{c.eglGetError()}); return error.FailedToInitializeEGL; } errdefer _ = c.eglDestroySurface(egl_display, context); return Self{ .display = egl_display, .surface = egl_surface, .context = context, }; } pub fn deinit(self: *Self) void { _ = c.eglDestroySurface(self.display, self.surface); _ = c.eglDestroyContext(self.display, self.context); self.* = undefined; } pub fn swapBuffers(self: Self) !void { if (c.eglSwapBuffers(self.display, self.surface) == c.EGL_FALSE) { log.err("Error: eglMakeCurrent failed: 0x{X:0>4}\n", .{c.eglGetError()}); return error.EglFailure; } } pub fn makeCurrent(self: Self) !void { if (c.eglMakeCurrent(self.display, self.surface, self.surface, self.context) == c.EGL_FALSE) { log.err("Error: eglMakeCurrent failed: 0x{X:0>4}\n", .{c.eglGetError()}); return error.EglFailure; } } pub fn release(self: Self) void { if (c.eglMakeCurrent(self.display, self.surface, self.surface, null) == c.EGL_FALSE) { log.err("Error: eglMakeCurrent failed: 0x{X:0>4}\n", .{c.eglGetError()}); } } };
src/egl.zig
const c = @cImport({ @cInclude("EGL/egl.h"); }); const std = @import("std"); const GBM = @import("gbm.zig").GBM; const default_config_attributes = [_]i32{ c.EGL_RED_SIZE, 8, c.EGL_GREEN_SIZE, 8, c.EGL_BLUE_SIZE, 8, c.EGL_NONE, }; const default_context_attributes = [_]i32{ c.EGL_CONTEXT_MAJOR_VERSION, 3, c.EGL_CONTEXT_MINOR_VERSION, 3, c.EGL_NONE, }; pub const EGL = struct { display: *c_void, context: *c_void, surface: *c_void, pub fn init(gbm: *GBM) !EGL { glEGLImageTargetTexture2DOES = @ptrCast(?fn(i32, *c_void) callconv(.C) void, c.eglGetProcAddress("glEGLImageTargetTexture2DOES")); var display = c.eglGetDisplay(@ptrCast(*c.struct__XDisplay, gbm.device)); if (display == null) { return error.EGLGetDisplayError; } var major: i32 = 0; var minor: i32 = 0; var x = c.eglInitialize(display.?, &major, &minor); std.debug.warn("EGL version: {}.{}\n", .{major, minor}); var config: c.EGLConfig = undefined; var num_config: i32 = 0; if (c.eglChooseConfig(display.?, &default_config_attributes[0], &config, 1, &num_config) == c.EGL_FALSE) { return error.EGLChooseConfigFailed; } if (c.eglBindAPI(c.EGL_OPENGL_API) == c.EGL_FALSE) { return error.EGLBindAPIFailed; } var context = c.eglCreateContext(display.?, config, null, &default_context_attributes[0]); if (context == null) { return error.EGLCreateContextFailed; } var surface = c.eglCreateWindowSurface(display.?, config, @ptrToInt(gbm.surface), null); if (surface == null) { return error.EGLCreateWindowSurfaceFailed; } var width: i32 = 0; var height: i32 = 0; _ = c.eglQuerySurface(display.?, surface.?, c.EGL_WIDTH, &width); _ = c.eglQuerySurface(display.?, surface.?, c.EGL_HEIGHT, &height); std.debug.warn("egl wxh: {}x{}\n", .{width, height}); _ = c.eglMakeCurrent(display.?, surface.?, surface.?, context.?); return EGL { .display = display.?, .context = context.?, .surface = surface.?, }; } pub fn deinit(self: EGL) void { const ds = c.eglDestroySurface(self.display, self.surface); _ = c.eglDestroyContext(self.display, self.context); _ = c.eglTerminate(self.display); std.debug.warn("EGL deinit: {}\n", .{ds}); } pub fn swapBuffers(self: EGL) void { _ = c.eglSwapBuffers(self.display, self.surface); } }; pub var glEGLImageTargetTexture2DOES: ?fn(i32, *c_void) callconv(.C) void = undefined;
src/backend/drm/egl.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 Str = []const u8; const util = @import("util.zig"); const gpa = util.gpa; const data = @embedFile("../data/day01.txt"); // const data = @embedFile("../data/day01-tst.txt"); pub fn main() !void { var list = List(u32).init(gpa); defer list.deinit(); var it = tokenize(u8, data, "\r\n"); while (it.next()) |num| { try list.append(try parseInt(u32, num, 10)); } var i: usize = 0; var j: usize = 0; while (i < list.items.len - 1) : (i += 1) { j = i + 1; while (j < list.items.len) : (j += 1) { if (list.items[i] + list.items[j] == 2020) { print("{}\n", .{list.items[i] * list.items[j]}); } } } i = 0; var k: usize = 0; while (i < list.items.len - 2) : (i += 1) { const n1 = list.items[i]; j = i + 1; while (j < list.items.len - 1) : (j += 1) { const n2 = list.items[j]; k = j + 1; while (k < list.items.len) : (k += 1) { const n3 = list.items[k]; if (n1 + n2 + n3 == 2020) { print("{}\n", .{n1 * n2 * n3}); } } } } } // 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/day01.zig
const std = @import("std"); pub const Elf = @import("utils/elf.zig"); pub const Paging = @import("utils/paging.zig"); const ATA = @import("io.zig").ATA; const Serial = @import("io.zig").Serial; const SFL = @import("utils/sfl.zig"); pub fn ataboot(allocator: *std.mem.Allocator, kernel_offset: usize) ![]u8 { var dev = try ATA.PIODevice(.Primary, .Master).init(); if (kernel_offset > dev.block_count * 512) { return error.Abort; } // Read `kernel` const size = @truncate(usize, dev.block_count * 512 - kernel_offset); var buf = try allocator.allocAdvanced(u8, 16, size, .at_least); errdefer allocator.free(buf); var block: u64 = kernel_offset / 512; var total: usize = 0; while (total < size) { try dev.read(block, buf[total..total+512]); block += 1; total += 512; } return buf; } pub fn serialboot(allocator: *std.mem.Allocator, port: usize) ![]u8 { // Disable interrupts for serial const serial_irq = try Serial.get_irq(port); try Serial.set_irq(port, 0); defer Serial.set_irq(port, serial_irq) catch unreachable; // Send "magic" request to Host for (SFL.magic_req) |c| { try Serial.write(port, c); } try SFL.checkAck(port); var total: usize = 0; var buf: ?[]u8 = null; var done = false; errdefer if (buf != null) allocator.free(buf.?); errdefer SFL.clean(port) catch unreachable; while (true) { const sfl = try SFL.receive(port); switch (@intToEnum(SFL.Commands, sfl.cmd)) { .abort => { try Serial.write(port, SFL.ack_success); return SFL.Error.Abort; }, .load => { // first 4 bytes is address const size = sfl.payload_length - 4; const payload = @ptrCast([*]const u8, &sfl.payload); buf = if (buf == null) try allocator.allocAdvanced(u8, 16, size, .at_least) else try allocator.realloc(buf.?, total + size); std.mem.copy(u8, buf.?[total..total+size], payload[4..size+4]); total += size; try Serial.write(port, SFL.ack_success); }, .jump => { try Serial.write(port, SFL.ack_success); done = true; break; }, else => { try Serial.write(port, SFL.ack_unknown); break; }, } } return if (buf == null or !done) SFL.Error.Abort else buf.?; } pub fn dump(out: anytype, data: []const u8) !void { var i: usize = 0; while (i < data.len) : (i += 1) { if (i % 16 == 0 and i != 0) { try out.print("\n", .{}); } else if (i % 8 == 0 and i != 0) { try out.print(" ", .{}); } try out.print("{X:0>2} ", .{data[i]}); } try out.print("\n", .{}); }
src/utils.zig
const std = @import("std"); const tvg = @import("tvg.zig"); const parsing = tvg.parsing; const Point = tvg.Point; const Rectangle = tvg.Rectangle; const Color = tvg.Color; const Style = tvg.parsing.Style; // TODO: Make these configurable const circle_divs = 100; const bezier_divs = 16; pub fn isFramebuffer(comptime T: type) bool { const Framebuffer = if (@typeInfo(T) == .Pointer) std.meta.Child(T) else T; // @compileLog( // T, // Framebuffer, // std.meta.trait.hasFn("setPixel")(Framebuffer), // std.meta.trait.hasField("width")(Framebuffer), // std.meta.trait.hasField("height")(Framebuffer), // ); return std.meta.trait.hasFn("setPixel")(Framebuffer) and std.meta.trait.hasField("width")(Framebuffer) and std.meta.trait.hasField("height")(Framebuffer); } /// Renders a command for TVG icon. pub fn render( /// A struct that exports a single function `setPixel(x: isize, y: isize, color: [4]u8) void` as well as two fields width and height framebuffer: anytype, /// The parsed header of a TVG header: parsing.Header, /// The color lookup table color_table: []const tvg.Color, /// The command that should be executed. cmd: parsing.DrawCommand, ) !void { if (!comptime isFramebuffer(@TypeOf(framebuffer))) @compileError("framebuffer needs fields width, height and function setPixel!"); const fb_width = @intToFloat(f32, framebuffer.width); const fb_height = @intToFloat(f32, framebuffer.height); // std.debug.print("render {}\n", .{cmd}); var painter = Painter{ .scale_x = fb_width / header.width, .scale_y = fb_height / header.height, }; switch (cmd) { .fill_polygon => |data| { painter.fillPolygon(framebuffer, color_table, data.style, data.vertices); }, .fill_rectangles => |data| { for (data.rectangles) |rect| { painter.fillRectangle(framebuffer, rect.x, rect.y, rect.width, rect.height, color_table, data.style); } }, .fill_path => |data| { var point_store = FixedBufferList(Point, 256){}; try renderPath(&point_store, data.start, data.path); painter.fillPolygon(framebuffer, color_table, data.style, point_store.items()); }, .draw_lines => |data| { for (data.lines) |line| { painter.drawLine(framebuffer, color_table, data.style, data.line_width, data.line_width, line); } }, .draw_line_strip => |data| { for (data.vertices[1..]) |end, i| { const start = data.vertices[i]; // is actually [i-1], but we access the slice off-by-one! painter.drawLine(framebuffer, color_table, data.style, data.line_width, data.line_width, .{ .start = start, .end = end, }); } }, .draw_line_loop => |data| { var start_index: usize = data.vertices.len - 1; for (data.vertices) |end, end_index| { const start = data.vertices[start_index]; painter.drawLine(framebuffer, color_table, data.style, data.line_width, data.line_width, .{ .start = start, .end = end, }); start_index = end_index; } }, .draw_line_path => |data| { var point_store = FixedBufferList(Point, 256){}; try renderPath(&point_store, data.start, data.path); const vertices = point_store.items(); for (vertices[1..]) |end, i| { const start = vertices[i]; // is actually [i-1], but we access the slice off-by-one! painter.drawLine(framebuffer, color_table, data.style, data.line_width, data.line_width, .{ .start = start, .end = end, }); } }, .outline_fill_polygon => |data| { @panic("outline_fill_polygon not implemented yet!"); }, .outline_fill_rectangles => |data| { for (data.rectangles) |rect| { painter.fillRectangle(framebuffer, rect.x, rect.y, rect.width, rect.height, color_table, data.fill_style); var tl = Point{ .x = rect.x, .y = rect.y }; var tr = Point{ .x = rect.x + rect.width, .y = rect.y }; var bl = Point{ .x = rect.x, .y = rect.y + rect.height }; var br = Point{ .x = rect.x + rect.width, .y = rect.y + rect.height }; painter.drawLine(framebuffer, color_table, data.line_style, data.line_width, data.line_width, .{ .start = tl, .end = tr }); painter.drawLine(framebuffer, color_table, data.line_style, data.line_width, data.line_width, .{ .start = tr, .end = br }); painter.drawLine(framebuffer, color_table, data.line_style, data.line_width, data.line_width, .{ .start = br, .end = bl }); painter.drawLine(framebuffer, color_table, data.line_style, data.line_width, data.line_width, .{ .start = bl, .end = tl }); } }, .outline_fill_path => |data| { @panic("outline_fill_path not implemented yet!"); }, } } pub fn renderPath(point_list: anytype, start: Point, nodes: []const tvg.parsing.PathNode) !void { const Helper = struct { list: @TypeOf(point_list), last: Point, fn append(self: *@This(), pt: Point) !void { // Discard when point is in the vicinity of the last point (same pixel) const delta = 0.25; if (std.math.approxEqAbs(f32, pt.x, self.last.x, delta) and std.math.approxEqAbs(f32, pt.y, self.last.y, delta)) return; try self.list.append(pt); self.last = pt; } fn back(self: @This()) Point { return self.last; } }; var point_store = Helper{ .list = point_list, .last = undefined, }; try point_store.append(start); for (nodes) |node, node_index| { switch (node) { .line => |pt| try point_store.append(pt.data), .horiz => |x| try point_store.append(Point{ .x = x.data, .y = point_store.back().y }), .vert => |y| try point_store.append(Point{ .x = point_store.back().x, .y = y.data }), .bezier => |bezier| { var previous = point_store.back(); const oct0_x = [4]f32{ previous.x, bezier.data.c0.x, bezier.data.c1.x, bezier.data.p1.x }; const oct0_y = [4]f32{ previous.y, bezier.data.c0.y, bezier.data.c1.y, bezier.data.p1.y }; var i: usize = 1; while (i < bezier_divs) : (i += 1) { const f = @intToFloat(f32, i) / @intToFloat(f32, bezier_divs); const x = lerpAndReduceToOne(4, oct0_x, f); const y = lerpAndReduceToOne(4, oct0_y, f); try point_store.append(Point{ .x = x, .y = y }); } try point_store.append(bezier.data.p1); }, // /home/felix/projects/forks/svg-curve-lib/src/js/svg-curve-lib.js .arc_circle => |circle| { try renderCircle( &point_store, point_store.back(), circle.data.target, circle.data.radius, circle.data.large_arc, circle.data.sweep, ); }, .arc_ellipse => |ellipse| { try renderEllipse( &point_store, point_store.back(), ellipse.data.target, ellipse.data.radius_x, ellipse.data.radius_y, ellipse.data.rotation, ellipse.data.large_arc, ellipse.data.sweep, ); }, .close => { if (node_index != (nodes.len - 1)) { // .close must be last! return error.InvalidData; } try point_store.append(start); }, } } } fn toRadians(a: f32) f32 { return std.math.pi / 180.0 * a; } const cos = std.math.cos; const sin = std.math.sin; const sqrt = std.math.sqrt; const abs = std.math.fabs; pub fn renderEllipse( point_list: anytype, p0: Point, p1: Point, radius_x: f32, radius_y: f32, rotation: f32, large_arc: bool, turn_left: bool, ) !void { const ratio = radius_x / radius_y; const rot = rotationMat(toRadians(rotation-90)); const transform = [2][2]f32{ rot[0], .{ rot[1][0] * ratio, rot[1][1] * ratio } }; const transform_back = [2][2]f32{ .{ rot[1][1], -rot[0][1] / ratio }, .{ -rot[1][0], rot[0][0] / ratio }, }; var tmp = FixedBufferList(Point, circle_divs){}; renderCircle(&tmp, applyMat(transform, p0), applyMat(transform, p1), radius_x, large_arc, turn_left) catch unreachable; // buffer is correctly sized for (tmp.buffer) |p| { try point_list.append(applyMat(transform_back, p)); } } fn renderCircle( point_list: anytype, p0: Point, p1: Point, r: f32, large_arc: bool, turn_left: bool, ) !void { // Whether the center should be to the left of the vector from p0 to p1 const left_side = (turn_left and large_arc) or (!turn_left and !large_arc); const delta = scale(sub(p1, p0), 0.5); const midpoint = add(p0, delta); // Vector from midpoint to center, but incorrect length const radius_vec = if (left_side) Point{ .x = -delta.y, .y = delta.x } else Point{ .x = delta.y, .y = -delta.x }; const len_squared = length2(radius_vec); if (len_squared > r*r or r < 0) return error.InvalidRadius; const to_center = scale(radius_vec, sqrt(r*r / len_squared - 1)); const center = add(midpoint, to_center); const angle = std.math.asin(sqrt(len_squared) / r) * 2; const arc = if (large_arc) (std.math.tau - angle) else angle; const step_mat = rotationMat((if (turn_left) -arc else arc) / circle_divs); var pos = sub(p0, center); var i: usize = 0; while (i < circle_divs - 1) : (i += 1) { pos = applyMat(step_mat, pos); const point = add(pos, center); try point_list.append(point); } try point_list.append(p1); } fn rotationMat(angle: f32) [2][2]f32 { const s = sin(angle); const c = cos(angle); return .{ .{ c, -s }, .{ s, c } }; } fn applyMat(mat: [2][2]f32, p: Point) Point { return .{ .x = p.x * mat[0][0] + p.y * mat[0][1], .y = p.x * mat[1][0] + p.y * mat[1][1], }; } fn pointFromInts(x: i16, y: i16) Point { return Point{ .x = @intToFloat(f32, x) + 0.5, .y = @intToFloat(f32, y) + 0.5 }; } fn pointToInts(point: Point) struct { x: i16, y: i16 } { return .{ .x = @floatToInt(i16, std.math.round(point.x)), .y = @floatToInt(i16, std.math.round(point.y)), }; } fn xy(x: f32, y: f32) Point { return Point{ .x = x, .y = y }; } test "point conversion" { const TestData = struct { point: Point, x: i16, y: i16 }; const pt2int = [_]TestData{ .{ .point = xy(0, 0), .x = 0, .y = 0 }, .{ .point = xy(1, 0), .x = 1, .y = 0 }, .{ .point = xy(2, 0), .x = 2, .y = 0 }, .{ .point = xy(0, 1), .x = 0, .y = 1 }, .{ .point = xy(0, 2), .x = 0, .y = 2 }, .{ .point = xy(1, 3), .x = 1, .y = 3 }, .{ .point = xy(2, 4), .x = 2, .y = 4 }, }; const int2pt = [_]TestData{ .{ .point = xy(0, 0), .x = 0, .y = 0 }, .{ .point = xy(1, 0), .x = 1, .y = 0 }, .{ .point = xy(2, 0), .x = 2, .y = 0 }, .{ .point = xy(0, 1), .x = 0, .y = 1 }, .{ .point = xy(0, 2), .x = 0, .y = 2 }, .{ .point = xy(1, 3), .x = 1, .y = 3 }, .{ .point = xy(2, 4), .x = 2, .y = 4 }, }; for (pt2int) |data| { const ints = pointToInts(data.point); //std.debug.print("{d} {d} => {d} {d}\n", .{ // data.point.x, data.point.y, // ints.x, ints.y, //}); std.testing.expectEqual(data.x, ints.x); std.testing.expectEqual(data.y, ints.y); } for (int2pt) |data| { const pt = pointFromInts(data.x, data.y); std.testing.expectApproxEqAbs(@as(f32, 0.0), distance(pt, data.point), sqrt(2.0) / 2.0); } } fn add(a: Point, b: Point) Point { return .{ .x = a.x+b.x, .y = a.y+b.y }; } fn sub(p1: Point, p2: Point) Point { return Point{ .x = p1.x - p2.x, .y = p1.y - p2.y }; } fn dot(p1: Point, p2: Point) f32 { return p1.x * p2.x + p1.y * p2.y; } fn scale(a: Point, s: f32) Point { return .{ .x = a.x*s, .y = a.y*s }; } fn length2(p: Point) f32 { return dot(p, p); } fn length(p: Point) f32 { return sqrt(length2(p)); } fn distance(p1: Point, p2: Point) f32 { return length(sub(p1, p2)); } fn getProjectedPointOnLine(v1: Point, v2: Point, p: Point) Point { var l1 = sub(v2, v1); var l2 = sub(p, v1); var proj = dot(l1, l2) / length2(l1); return add(v1, scale(l1, proj)); } fn sampleStlye(color_table: []const Color, style: Style, x: i16, y: i16) Color { return switch (style) { .flat => |index| color_table[index], .linear => |grad| blk: { const c0 = color_table[grad.color_0]; const c1 = color_table[grad.color_1]; const p0 = grad.point_0; const p1 = grad.point_1; const pt = pointFromInts(x, y); const direction = sub(p1, p0); const delta_pt = sub(pt, p0); const dot_0 = dot(direction, delta_pt); if (dot_0 <= 0.0) break :blk c0; const dot_1 = dot(direction, sub(pt, p1)); if (dot_1 >= 0.0) break :blk c1; const len_grad = length(direction); const pos_grad = length(getProjectedPointOnLine( Point{ .x = 0, .y = 0 }, direction, delta_pt, )); break :blk lerp_sRGB(c0, c1, pos_grad / len_grad); }, .radial => |grad| blk: { const dist_max = distance(grad.point_0, grad.point_1); const dist_is = distance(grad.point_0, pointFromInts(x, y)); const c0 = color_table[grad.color_0]; const c1 = color_table[grad.color_1]; break :blk lerp_sRGB(c0, c1, dist_is / dist_max); }, }; } const Painter = struct { scale_x: f32, scale_y: f32, fn fillPolygon(self: Painter, framebuffer: anytype, color_table: []const Color, style: Style, points: []const Point) void { std.debug.assert(points.len >= 3); var min_x: i16 = std.math.maxInt(i16); var min_y: i16 = std.math.maxInt(i16); var max_x: i16 = std.math.minInt(i16); var max_y: i16 = std.math.minInt(i16); for (points) |pt| { min_x = std.math.min(min_x, @floatToInt(i16, std.math.floor(self.scale_x * pt.x))); min_y = std.math.min(min_y, @floatToInt(i16, std.math.floor(self.scale_y * pt.y))); max_x = std.math.max(max_x, @floatToInt(i16, std.math.ceil(self.scale_x * pt.x))); max_y = std.math.max(max_y, @floatToInt(i16, std.math.ceil(self.scale_y * pt.y))); } // limit to valid screen area min_x = std.math.max(min_x, 0); min_y = std.math.max(min_y, 0); max_x = std.math.min(max_x, @intCast(i16, framebuffer.width - 1)); max_y = std.math.min(max_y, @intCast(i16, framebuffer.height - 1)); var y: i16 = min_y; while (y <= max_y) : (y += 1) { var x: i16 = min_x; while (x <= max_x) : (x += 1) { var inside = false; // compute "center" of the pixel var p = pointFromInts(x, y); p.x /= self.scale_x; p.y /= self.scale_y; // free after https://stackoverflow.com/a/17490923 var j = points.len - 1; for (points) |p0, i| { defer j = i; const p1 = points[j]; if ((p0.y > p.y) != (p1.y > p.y) and p.x < (p1.x - p0.x) * (p.y - p0.y) / (p1.y - p0.y) + p0.x) { inside = !inside; } } if (inside) { framebuffer.setPixel(x, y, sampleStlye(color_table, style, x, y).toArray()); } } } } fn fillRectangle(self: Painter, framebuffer: anytype, x: f32, y: f32, width: f32, height: f32, color_table: []const Color, style: Style) void { const xlimit = @floatToInt(i16, std.math.ceil(self.scale_x * (x + width))); const ylimit = @floatToInt(i16, std.math.ceil(self.scale_y * (y + height))); var py = @floatToInt(i16, std.math.floor(self.scale_y * y)); while (py < ylimit) : (py += 1) { var px = @floatToInt(i16, std.math.floor(self.scale_x * x)); while (px < xlimit) : (px += 1) { framebuffer.setPixel(px, py, sampleStlye(color_table, style, px, py).toArray()); } } } fn drawLine(self: Painter, framebuffer: anytype, color_table: []const Color, style: Style, width_start: f32, width_end: f32, line: tvg.Line) void { const len_fract = distance(line.start, line.end); const num_dots = @floatToInt(usize, std.math.ceil(len_fract)); if (num_dots == 0) return; var i: usize = 0; while (i <= num_dots) : (i += 1) { const f = @intToFloat(f32, i) / @intToFloat(f32, num_dots); const pos = Point{ .x = lerp(line.start.x, line.end.x, f), .y = lerp(line.start.y, line.end.y, f), }; const width = lerp(width_start, width_end, f); self.drawCircle( framebuffer, color_table, style, pos, width / 2.0, // circle uses radius, we use width/diameter ); } } fn drawCircle(self: Painter, framebuffer: anytype, color_table: []const Color, style: Style, location: Point, radius: f32) void { if (radius < 0) return; const left = @floatToInt(i16, std.math.floor(self.scale_x * (location.x - radius) - 0.5)); const right = @floatToInt(i16, std.math.ceil(self.scale_y * (location.x + radius) + 0.5)); const top = @floatToInt(i16, std.math.floor(self.scale_x * (location.y - radius) - 0.5)); const bottom = @floatToInt(i16, std.math.ceil(self.scale_y * (location.y + radius) + 0.5)); const r2 = radius * radius; if (r2 > 0.77) { var y: i16 = top; while (y <= bottom) : (y += 1) { var x: i16 = left; while (x <= right) : (x += 1) { const pt = pointFromInts(x, y); var delta = sub(pt, location); delta.x /= self.scale_x; delta.y /= self.scale_y; const dist = length2(delta); if (dist <= r2) framebuffer.setPixel(x, y, sampleStlye(color_table, style, x, y).toArray()); } } } else { const pt = pointToInts(location); framebuffer.setPixel(pt.x, pt.y, sampleStlye(color_table, style, pt.x, pt.y).toArray()); } } }; const sRGB_gamma = 2.2; fn gamma2linear(v: f32) u8 { std.debug.assert(v >= 0 and v <= 1); return @floatToInt(u8, 255.0 * std.math.pow(f32, v, 1.0 / sRGB_gamma)); } fn linear2gamma(v: u8) f32 { return std.math.pow(f32, @intToFloat(f32, v) / 255.0, sRGB_gamma); } fn lerp_sRGB(c0: Color, c1: Color, f_unchecked: f32) Color { const f = std.math.clamp(f_unchecked, 0, 1); return Color{ .r = gamma2linear(lerp(linear2gamma(c0.r), linear2gamma(c1.r), f)), .g = gamma2linear(lerp(linear2gamma(c0.g), linear2gamma(c1.g), f)), .b = gamma2linear(lerp(linear2gamma(c0.b), linear2gamma(c1.b), f)), .a = @floatToInt(u8, lerp(@intToFloat(f32, c0.a), @intToFloat(f32, c0.a), f)), }; } fn lerp(a: f32, b: f32, x: f32) f32 { return a + (b - a) * x; } fn lerpAndReduce(comptime n: comptime_int, vals: [n]f32, f: f32) [n - 1]f32 { var result: [n - 1]f32 = undefined; for (result) |*r, i| { r.* = lerp(vals[i + 0], vals[i + 1], f); } return result; } fn lerpAndReduceToOne(comptime n: comptime_int, vals: [n]f32, f: f32) f32 { if (n == 1) { return vals[0]; } else { return lerpAndReduceToOne(n - 1, lerpAndReduce(n, vals, f), f); } } pub fn FixedBufferList(comptime T: type, comptime N: usize) type { return struct { const Self = @This(); buffer: [N]T = undefined, length: usize = 0, pub fn append(self: *Self, value: T) !void { if (self.length == N) return error.OutOfMemory; self.buffer[self.length] = value; self.length += 1; } pub fn popBack(self: Self) ?T { if (self.length == 0) return null; self.length -= 1; return self.buffer[self.length]; } pub fn itemsMut(self: *Self) []T { return self.buffer[0..self.length]; } pub fn items(self: Self) []const T { return self.buffer[0..self.length]; } pub fn front(self: Self) ?T { if (self.length == 0) return null; return self.buffer[0]; } pub fn back(self: Self) ?T { if (self.length == 0) return null; return self.buffer[self.length - 1]; } }; }
src/lib/rendering.zig
pub const EPERM = 1; pub const ENOENT = 2; pub const ESRCH = 3; pub const EINTR = 4; pub const EIO = 5; pub const ENXIO = 6; pub const E2BIG = 7; pub const ENOEXEC = 8; pub const EBADF = 9; pub const ECHILD = 10; pub const EAGAIN = 11; pub const ENOMEM = 12; pub const EACCES = 13; pub const EFAULT = 14; pub const ENOTBLK = 15; pub const EBUSY = 16; pub const EEXIST = 17; pub const EXDEV = 18; pub const ENODEV = 19; pub const ENOTDIR = 20; pub const EISDIR = 21; pub const EINVAL = 22; pub const ENFILE = 23; pub const EMFILE = 24; pub const ENOTTY = 25; pub const ETXTBSY = 26; pub const EFBIG = 27; pub const ENOSPC = 28; pub const ESPIPE = 29; pub const EROFS = 30; pub const EMLINK = 31; pub const EPIPE = 32; pub const EDOM = 33; pub const ERANGE = 34; pub const ENOMSG = 35; pub const EIDRM = 36; pub const ECHRNG = 37; pub const EL2NSYNC = 38; pub const EL3HLT = 39; pub const EL3RST = 40; pub const ELNRNG = 41; pub const EUNATCH = 42; pub const ENOCSI = 43; pub const EL2HLT = 44; pub const EDEADLK = 45; pub const ENOLCK = 46; pub const EBADE = 50; pub const EBADR = 51; pub const EXFULL = 52; pub const ENOANO = 53; pub const EBADRQC = 54; pub const EBADSLT = 55; pub const EDEADLOCK = 56; pub const EBFONT = 59; pub const ENOSTR = 60; pub const ENODATA = 61; pub const ETIME = 62; pub const ENOSR = 63; pub const ENONET = 64; pub const ENOPKG = 65; pub const EREMOTE = 66; pub const ENOLINK = 67; pub const EADV = 68; pub const ESRMNT = 69; pub const ECOMM = 70; pub const EPROTO = 71; pub const EDOTDOT = 73; pub const EMULTIHOP = 74; pub const EBADMSG = 77; pub const ENAMETOOLONG = 78; pub const EOVERFLOW = 79; pub const ENOTUNIQ = 80; pub const EBADFD = 81; pub const EREMCHG = 82; pub const ELIBACC = 83; pub const ELIBBAD = 84; pub const ELIBSCN = 85; pub const ELIBMAX = 86; pub const ELIBEXEC = 87; pub const EILSEQ = 88; pub const ENOSYS = 89; pub const ELOOP = 90; pub const ERESTART = 91; pub const ESTRPIPE = 92; pub const ENOTEMPTY = 93; pub const EUSERS = 94; pub const ENOTSOCK = 95; pub const EDESTADDRREQ = 96; pub const EMSGSIZE = 97; pub const EPROTOTYPE = 98; pub const ENOPROTOOPT = 99; pub const EPROTONOSUPPORT = 120; pub const ESOCKTNOSUPPORT = 121; pub const EOPNOTSUPP = 122; pub const ENOTSUP = EOPNOTSUPP; pub const EPFNOSUPPORT = 123; pub const EAFNOSUPPORT = 124; pub const EADDRINUSE = 125; pub const EADDRNOTAVAIL = 126; pub const ENETDOWN = 127; pub const ENETUNREACH = 128; pub const ENETRESET = 129; pub const ECONNABORTED = 130; pub const ECONNRESET = 131; pub const ENOBUFS = 132; pub const EISCONN = 133; pub const ENOTCONN = 134; pub const EUCLEAN = 135; pub const ENOTNAM = 137; pub const ENAVAIL = 138; pub const EISNAM = 139; pub const EREMOTEIO = 140; pub const ESHUTDOWN = 143; pub const ETOOMANYREFS = 144; pub const ETIMEDOUT = 145; pub const ECONNREFUSED = 146; pub const EHOSTDOWN = 147; pub const EHOSTUNREACH = 148; pub const EWOULDBLOCK = EAGAIN; pub const EALREADY = 149; pub const EINPROGRESS = 150; pub const ESTALE = 151; pub const ECANCELED = 158; pub const ENOMEDIUM = 159; pub const EMEDIUMTYPE = 160; pub const ENOKEY = 161; pub const EKEYEXPIRED = 162; pub const EKEYREVOKED = 163; pub const EKEYREJECTED = 164; pub const EOWNERDEAD = 165; pub const ENOTRECOVERABLE = 166; pub const ERFKILL = 167; pub const EHWPOISON = 168; pub const EDQUOT = 1133;
lib/std/os/bits/linux/errno-mips.zig
const std = @import("std"); const logger = std.log.scoped(.qoi); pub const EncodeError = error{}; pub const DecodeError = error{ OutOfMemory, InvalidData, EndOfStream }; /// Returns a raw qoi stream decoder that will fetch color runs from the qoi stream. pub fn decoder(reader: anytype) Decoder(@TypeOf(reader)) { return .{ .reader = reader }; } /// Returns a raw qoi stream encoder that will receive pixel colors and write out bytes to a writer. This stream does not create a qoi header! pub fn encoder(writer: anytype) Encoder(@TypeOf(writer)) { return .{ .writer = writer }; } /// A run of several pixels of the same color. pub const ColorRun = struct { color: Color, /// Is always greater than 0. length: usize, }; pub const Color = extern struct { r: u8, g: u8, b: u8, a: u8 = 0xFF, fn hash(c: Color) u6 { return @truncate(u6, c.r *% 3 +% c.g *% 5 +% c.b *% 7 +% c.a *% 11); } pub fn eql(a: Color, b: Color) bool { return std.meta.eql(a, b); } }; /// A QOI image with RGBA pixels. pub const Image = struct { width: u32, height: u32, pixels: []Color, colorspace: Colorspace, pub fn asConst(self: Image) ConstImage { return ConstImage{ .width = self.width, .height = self.height, .pixels = self.pixels, .colorspace = self.colorspace, }; } pub fn deinit(self: *Image, allocator: std.mem.Allocator) void { allocator.free(self.pixels); self.* = undefined; } }; /// A QOI image with RGBA pixels. pub const ConstImage = struct { width: u32, height: u32, pixels: []const Color, colorspace: Colorspace, }; /// Returns true if `bytes` appear to contain a valid QOI image from the header. This does not a in-depth analysis. pub fn isQOI(bytes: []const u8) bool { if (bytes.len < Header.size) return false; const header = Header.decode(bytes[0..Header.size].*) catch return false; return (bytes.len >= Header.size + header.size); } /// Decodes a buffer containing a QOI image and returns the decoded image. pub fn decodeBuffer(allocator: std.mem.Allocator, buffer: []const u8) DecodeError!Image { if (buffer.len < Header.size) return error.InvalidData; var stream = std.io.fixedBufferStream(buffer); return try decodeStream(allocator, stream.reader()); } /// Decodes a QOI stream and returns the decoded image. pub fn decodeStream(allocator: std.mem.Allocator, reader: anytype) (DecodeError || @TypeOf(reader).Error)!Image { var header_data: [Header.size]u8 = undefined; try reader.readNoEof(&header_data); const header = Header.decode(header_data) catch return error.InvalidData; const size_raw = @as(u64, header.width) * @as(u64, header.height); const size = std.math.cast(usize, size_raw) catch return error.OutOfMemory; var img = Image{ .width = header.width, .height = header.height, .pixels = try allocator.alloc(Color, size), .colorspace = header.colorspace, }; errdefer allocator.free(img.pixels); var dec = decoder(reader); var index: usize = 0; while (index < img.pixels.len) { var run = try dec.fetch(); // this will happen when a file has an invalid run length // and we would decode more pixels than there are in the image. if (index + run.length > img.pixels.len) { return error.InvalidData; } while (run.length > 0) { run.length -= 1; img.pixels[index] = run.color; index += 1; } } return img; } /// Encodes a given `image` into a QOI buffer. pub fn encodeBuffer(allocator: std.mem.Allocator, image: ConstImage) (std.mem.Allocator.Error || EncodeError)![]u8 { var destination_buffer = std.ArrayList(u8).init(allocator); defer destination_buffer.deinit(); try encodeStream(image, destination_buffer.writer()); return destination_buffer.toOwnedSlice(); } /// Encodes a given `image` into a QOI buffer. pub fn encodeStream(image: ConstImage, writer: anytype) (EncodeError || @TypeOf(writer).Error)!void { var format = for (image.pixels) |pix| { if (pix.a != 0xFF) break Format.rgba; } else Format.rgb; var header = Header{ .width = image.width, .height = image.height, .format = format, .colorspace = .sRGB, }; try writer.writeAll(&header.encode()); var enc = encoder(writer); for (image.pixels) |pixel| { try enc.push(pixel); } try enc.flush(); try writer.writeAll(&[8]u8{ 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x01, }); } /// Returns a raw qoi stream encoder that will receive pixel colors and write out bytes to a writer. This stream does not create a qoi header! /// - `Writer` is the type of that writer pub fn Encoder(comptime Writer: type) type { return struct { const Self = @This(); pub const Error = Writer.Error || EncodeError; // Set this to your writer: writer: Writer, // privates: color_lut: [64]Color = std.mem.zeroes([64]Color), previous_pixel: Color = .{ .r = 0, .g = 0, .b = 0, .a = 0xFF }, run_length: usize = 0, fn flushRun(self: *Self) !void { // QOI_OP_RUN std.debug.assert(self.run_length >= 1 and self.run_length <= 62); try self.writer.writeByte(0b1100_0000 | @truncate(u8, self.run_length - 1)); self.run_length = 0; } /// Resets the stream so it will start encoding from a clean slate. pub fn reset(self: *Self) void { var writer = self.writer; self.* = Self{ .writer = writer }; } /// Flushes any left runs to the stream and will leave the stream in a "clean" state where a stream is terminated. /// Does not reset the stream for a clean slate. pub fn flush(self: *Self) (EncodeError || Writer.Error)!void { if (self.run_length > 0) { try self.flushRun(); } std.debug.assert(self.run_length == 0); } /// Pushes a pixel into the stream. Might not write data if the pixel can be encoded as a run. /// Call `flush` after encoding all pixels to make sure the stream is terminated properly. pub fn push(self: *Self, pixel: Color) (EncodeError || Writer.Error)!void { defer self.previous_pixel = pixel; const previous_pixel = self.previous_pixel; const same_pixel = pixel.eql(self.previous_pixel); if (same_pixel) { self.run_length += 1; } if (self.run_length > 0 and (self.run_length == 62 or !same_pixel)) { try self.flushRun(); } if (same_pixel) { return; } const hash = pixel.hash(); if (self.color_lut[hash].eql(pixel)) { // QOI_OP_INDEX try self.writer.writeByte(0b0000_0000 | hash); } else { self.color_lut[hash] = pixel; const diff_r = @as(i16, pixel.r) - @as(i16, previous_pixel.r); const diff_g = @as(i16, pixel.g) - @as(i16, previous_pixel.g); const diff_b = @as(i16, pixel.b) - @as(i16, previous_pixel.b); const diff_a = @as(i16, pixel.a) - @as(i16, previous_pixel.a); const diff_rg = diff_r - diff_g; const diff_rb = diff_b - diff_g; if (diff_a == 0 and inRange2(diff_r) and inRange2(diff_g) and inRange2(diff_b)) { // QOI_OP_DIFF const byte = 0b0100_0000 | (mapRange2(diff_r) << 4) | (mapRange2(diff_g) << 2) | (mapRange2(diff_b) << 0); try self.writer.writeByte(byte); } else if (diff_a == 0 and inRange6(diff_g) and inRange4(diff_rg) and inRange4(diff_rb)) { // QOI_OP_LUMA try self.writer.writeAll(&[2]u8{ 0b1000_0000 | mapRange6(diff_g), (mapRange4(diff_rg) << 4) | (mapRange4(diff_rb) << 0), }); } else if (diff_a == 0) { // QOI_OP_RGB try self.writer.writeAll(&[4]u8{ 0b1111_1110, pixel.r, pixel.g, pixel.b, }); } else { // QOI_OP_RGBA try self.writer.writeAll(&[5]u8{ 0b1111_1111, pixel.r, pixel.g, pixel.b, pixel.a, }); } } } }; } /// A raw stream decoder for Qoi data streams. Will not decode file headers. pub fn Decoder(comptime Reader: type) type { return struct { const Self = @This(); reader: Reader, // private api: current_color: Color = .{ .r = 0, .g = 0, .b = 0, .a = 0xFF }, color_lut: [64]Color = std.mem.zeroes([64]Color), /// Decodes the next `ColorRun` from the stream. For non-run commands, will return a run with length 1. pub fn fetch(self: *Self) (Reader.Error || error{EndOfStream})!ColorRun { var byte = try self.reader.readByte(); var new_color = self.current_color; var count: usize = 1; if (byte == 0b11111110) { // QOI_OP_RGB new_color.r = try self.reader.readByte(); new_color.g = try self.reader.readByte(); new_color.b = try self.reader.readByte(); } else if (byte == 0b11111111) { // QOI_OP_RGBA new_color.r = try self.reader.readByte(); new_color.g = try self.reader.readByte(); new_color.b = try self.reader.readByte(); new_color.a = try self.reader.readByte(); } else if (hasPrefix(byte, u2, 0b00)) { // QOI_OP_INDEX const color_index = @truncate(u6, byte); new_color = self.color_lut[color_index]; } else if (hasPrefix(byte, u2, 0b01)) { // QOI_OP_DIFF const diff_r = unmapRange2(byte >> 4); const diff_g = unmapRange2(byte >> 2); const diff_b = unmapRange2(byte >> 0); add8(&new_color.r, diff_r); add8(&new_color.g, diff_g); add8(&new_color.b, diff_b); } else if (hasPrefix(byte, u2, 0b10)) { // QOI_OP_LUMA const diff_rg_rb = try self.reader.readByte(); const diff_rg = unmapRange4(diff_rg_rb >> 4); const diff_rb = unmapRange4(diff_rg_rb >> 0); const diff_g = unmapRange6(byte); const diff_r = @as(i8, diff_g) + diff_rg; const diff_b = @as(i8, diff_g) + diff_rb; add8(&new_color.r, diff_r); add8(&new_color.g, diff_g); add8(&new_color.b, diff_b); } else if (hasPrefix(byte, u2, 0b11)) { // QOI_OP_RUN count = @as(usize, @truncate(u6, byte)) + 1; std.debug.assert(count >= 1 and count <= 62); } else { // we have covered all possibilities. unreachable; } self.color_lut[new_color.hash()] = new_color; self.current_color = new_color; return ColorRun{ .color = new_color, .length = count }; } }; } fn mapRange2(val: i16) u8 { return @intCast(u2, val + 2); } fn mapRange4(val: i16) u8 { return @intCast(u4, val + 8); } fn mapRange6(val: i16) u8 { return @intCast(u6, val + 32); } fn unmapRange2(val: u32) i2 { return @intCast(i2, @as(i8, @truncate(u2, val)) - 2); } fn unmapRange4(val: u32) i4 { return @intCast(i4, @as(i8, @truncate(u4, val)) - 8); } fn unmapRange6(val: u32) i6 { return @intCast(i6, @as(i8, @truncate(u6, val)) - 32); } fn inRange2(val: i16) bool { return (val >= -2) and (val <= 1); } fn inRange4(val: i16) bool { return (val >= -8) and (val <= 7); } fn inRange6(val: i16) bool { return (val >= -32) and (val <= 31); } fn add8(dst: *u8, diff: i8) void { dst.* +%= @bitCast(u8, diff); } fn hasPrefix(value: u8, comptime T: type, prefix: T) bool { return (@truncate(T, value >> (8 - @bitSizeOf(T))) == prefix); } pub const Header = struct { const size = 14; const correct_magic = [4]u8{ 'q', 'o', 'i', 'f' }; width: u32, height: u32, format: Format, colorspace: Colorspace, fn decode(buffer: [size]u8) !Header { if (!std.mem.eql(u8, buffer[0..4], &correct_magic)) return error.InvalidMagic; return Header{ .width = std.mem.readIntBig(u32, buffer[4..8]), .height = std.mem.readIntBig(u32, buffer[8..12]), .format = try std.meta.intToEnum(Format, buffer[12]), .colorspace = try std.meta.intToEnum(Colorspace, buffer[13]), }; } fn encode(header: Header) [size]u8 { var result: [size]u8 = undefined; std.mem.copy(u8, result[0..4], &correct_magic); std.mem.writeIntBig(u32, result[4..8], header.width); std.mem.writeIntBig(u32, result[8..12], header.height); result[12] = @enumToInt(header.format); result[13] = @enumToInt(header.colorspace); return result; } }; pub const Colorspace = enum(u8) { /// sRGB color, linear alpha sRGB = 0, /// Every channel is linear linear = 1, }; pub const Format = enum(u8) { rgb = 3, rgba = 4, }; test "decode qoi" { const src_data = @embedFile("../data/zero.qoi"); var image = try decodeBuffer(std.testing.allocator, src_data); defer image.deinit(std.testing.allocator); try std.testing.expectEqual(@as(u32, 512), image.width); try std.testing.expectEqual(@as(u32, 512), image.height); try std.testing.expectEqual(@as(usize, 512 * 512), image.pixels.len); const dst_data = @embedFile("../data/zero.raw"); try std.testing.expectEqualSlices(u8, dst_data, std.mem.sliceAsBytes(image.pixels)); } test "decode qoi file" { var file = try std.fs.cwd().openFile("data/zero.qoi", .{}); defer file.close(); var image = try decodeStream(std.testing.allocator, file.reader()); defer image.deinit(std.testing.allocator); try std.testing.expectEqual(@as(u32, 512), image.width); try std.testing.expectEqual(@as(u32, 512), image.height); try std.testing.expectEqual(@as(usize, 512 * 512), image.pixels.len); const dst_data = @embedFile("../data/zero.raw"); try std.testing.expectEqualSlices(u8, dst_data, std.mem.sliceAsBytes(image.pixels)); } test "encode qoi" { const src_data = @embedFile("../data/zero.raw"); var dst_data = try encodeBuffer(std.testing.allocator, ConstImage{ .width = 512, .height = 512, .pixels = std.mem.bytesAsSlice(Color, src_data), .colorspace = .sRGB, }); defer std.testing.allocator.free(dst_data); const ref_data = @embedFile("../data/zero.qoi"); try std.testing.expectEqualSlices(u8, ref_data, dst_data); } test "random encode/decode" { var rng_engine = std.rand.DefaultPrng.init(0x1337); const rng = rng_engine.random(); const width = 251; const height = 49; var rounds: usize = 512; while (rounds > 0) { rounds -= 1; var input_buffer: [width * height]Color = undefined; rng.bytes(std.mem.sliceAsBytes(&input_buffer)); var encoded_data = try encodeBuffer(std.testing.allocator, ConstImage{ .width = width, .height = height, .pixels = &input_buffer, .colorspace = if (rng.boolean()) Colorspace.sRGB else Colorspace.linear, }); defer std.testing.allocator.free(encoded_data); var image = try decodeBuffer(std.testing.allocator, encoded_data); defer image.deinit(std.testing.allocator); try std.testing.expectEqual(@as(u32, width), image.width); try std.testing.expectEqual(@as(u32, height), image.height); try std.testing.expectEqualSlices(Color, &input_buffer, image.pixels); } } test "input fuzzer. plz do not crash" { var rng_engine = std.rand.DefaultPrng.init(0x1337); const rng = rng_engine.random(); var rounds: usize = 32; while (rounds > 0) { rounds -= 1; var input_buffer: [1 << 20]u8 = undefined; // perform on a 1 MB buffer rng.bytes(&input_buffer); if ((rounds % 4) != 0) { // 25% is fully random 75% has a correct looking header std.mem.copy(u8, &input_buffer, &(Header{ .width = rng.int(u16), .height = rng.int(u16), .format = rng.enumValue(Format), .colorspace = rng.enumValue(Colorspace), }).encode()); } var stream = std.io.fixedBufferStream(&input_buffer); if (decodeStream(std.testing.allocator, stream.reader())) |*image| { defer image.deinit(std.testing.allocator); } else |err| { // error is also okay, just no crashes plz err catch {}; } } }
src/qoi.zig
usingnamespace @import("psptypes.zig"); usingnamespace @import("pspgu.zig"); //Internal var gum_current_mode: u8 = 0; var gum_matrix_update: [4]u8 = [_]u8{0} ** 4; var gum_current_matrix_update: u8 = 0; var gum_current_matrix: *ScePspFMatrix4 = @ptrCast(*ScePspFMatrix4, &gum_matrix_stack[0]); var gum_stack_depth: [4][*]ScePspFMatrix4 = [_][*]ScePspFMatrix4{ @ptrCast([*]ScePspFMatrix4, &gum_matrix_stack[0]), @ptrCast([*]ScePspFMatrix4, &gum_matrix_stack[1]), @ptrCast([*]ScePspFMatrix4, &gum_matrix_stack[2]), @ptrCast([*]ScePspFMatrix4, &gum_matrix_stack[3]) }; var gum_matrix_stack: [4][32]ScePspFMatrix4 = undefined; pub fn sceGumDrawArray(prim: GuPrimitive, vtype: c_int, count: c_int, indices: ?*const c_void, vertices: ?*const c_void) void { sceGumUpdateMatrix(); sceGuDrawArray(prim, vtype, count, indices, vertices); } pub fn sceGumDrawArrayN(prim: c_int, vtype: c_int, count: c_int, a3: c_int, indices: ?*const c_void, vertices: ?*const c_void) void { sceGumUpdateMatrix(); sceGuDrawArrayN(prim, vtype, count, a3, indices, vertices); } pub fn sceGumDrawBezier(vtype: c_int, ucount: c_int, vcount: c_int, indices: ?*const c_void, vertices: ?*const c_void) void { sceGumUpdateMatrix(); sceGuDrawBezier(vtype, ucount, vcount, indices, vertices); } pub fn sceGumDrawSpline(vtype: c_int, ucount: c_int, vcount: c_int, uedge: c_int, vedge: c_int, indices: ?*const c_void, vertices: ?*const c_void) void { sceGumUpdateMatrix(); sceGuDrawSpline(vtype, ucount, vcount, uedge, vedge, indices, vertices); } extern fn memset(ptr: [*]u8, value: u32, num: usize) [*]u8; extern fn memcpy(dst: [*]u8, src: [*]const u8, num: isize) [*]u8; extern fn memcmp(ptr1: [*]u8, ptr2: [*]u8, num: isize) i32; pub fn sceGumLoadIdentity() void { _ = memset(@ptrCast([*]u8, gum_current_matrix), 0, @sizeOf(ScePspFMatrix4)); var i: usize = 0; while (i < 4) : (i += 1) { @ptrCast([*]f32, gum_current_matrix)[(i << 2) + i] = 1.0; } gum_current_matrix_update = 1; } pub fn sceGumLoadMatrix(m: [*c]ScePspFMatrix4) void { _ = memcpy(@ptrCast([*]u8, gum_current_matrix), @ptrCast([*]u8, m), @sizeOf(ScePspFMatrix4)); gum_current_matrix_update = 1; } pub fn sceGumUpdateMatrix() void { gum_stack_depth[gum_current_mode] = @ptrCast([*]ScePspFMatrix4, gum_current_matrix); gum_matrix_update[gum_current_mode] = gum_current_matrix_update; gum_current_matrix_update = 0; var i: usize = 0; while (i < 4) : (i += 1) { if (gum_matrix_update[i] != 0) { sceGuSetMatrix(@intCast(c_int, i), gum_stack_depth[i]); gum_matrix_update[i] = 0; } } } pub fn sceGumPopMatrix() void { var t = @ptrCast([*]ScePspFMatrix4, gum_current_matrix); t -= 1; gum_current_matrix = @ptrCast(*ScePspFMatrix4, t); gum_current_matrix_update = 1; } pub fn sceGumPushMatrix() void { _ = memcpy(@ptrCast([*]u8, @ptrCast([*]ScePspFMatrix4, gum_current_matrix) + 1), @ptrCast([*]u8, @ptrCast([*]ScePspFMatrix4, gum_current_matrix)), @sizeOf(ScePspFMatrix4)); var t = @ptrCast([*]ScePspFMatrix4, gum_current_matrix); t += 1; gum_current_matrix = @ptrCast(*ScePspFMatrix4, t); } pub fn sceGumRotateXYZ(v: *ScePspFVector3) void { sceGumRotateX(v.x); sceGumRotateY(v.y); sceGumRotateZ(v.z); } pub fn sceGumRotateZYX(v: *ScePspFVector3) void { sceGumRotateZ(v.z); sceGumRotateY(v.y); sceGumRotateX(v.x); } pub fn sceGumStoreMatrix(m: [*c]ScePspFMatrix4) void { _ = memcpy(@ptrCast([*]u8, m), @ptrCast([*]u8, gum_current_matrix), @sizeOf(ScePspFMatrix4)); } const std = @import("std"); pub fn sceGumRotateX(angle: f32) void { var t: ScePspFMatrix4 = undefined; _ = memset(@ptrCast([*]u8, &t), 0, @sizeOf(ScePspFMatrix4)); var i: usize = 0; while (i < 4) : (i += 1) { @ptrCast([*]f32, &t)[(i << 2) + i] = 1.0; } var c: f32 = @import("cos.zig").cos(angle); var s: f32 = @import("sin.zig").sin(angle); t.y.y = c; t.y.z = s; t.z.y = -s; t.z.z = c; gumMultMatrix(gum_current_matrix, gum_current_matrix, &t); } pub fn sceGumRotateY(angle: f32) void { var t: ScePspFMatrix4 = undefined; _ = memset(@ptrCast([*]u8, &t), 0, @sizeOf(ScePspFMatrix4)); var i: usize = 0; while (i < 4) : (i += 1) { @ptrCast([*]f32, &t)[(i << 2) + i] = 1.0; } var c: f32 = @import("cos.zig").cos(angle); var s: f32 = @import("sin.zig").sin(angle); t.x.x = c; t.x.z = -s; t.z.x = s; t.z.z = c; gumMultMatrix(gum_current_matrix, gum_current_matrix, &t); } pub fn sceGumRotateZ(angle: f32) void { var t: ScePspFMatrix4 = undefined; _ = memset(@ptrCast([*]u8, &t), 0, @sizeOf(ScePspFMatrix4)); var i: usize = 0; while (i < 4) : (i += 1) { @ptrCast([*]f32, &t)[(i << 2) + i] = 1.0; } var c: f32 = @import("cos.zig").cos(angle); var s: f32 = @import("sin.zig").sin(angle); t.x.x = c; t.x.y = s; t.y.x = -s; t.y.y = c; gumMultMatrix(gum_current_matrix, gum_current_matrix, &t); } fn gumMultMatrix(result: [*c]ScePspFMatrix4, a: [*c]const ScePspFMatrix4, b: [*c]const ScePspFMatrix4) void { var t: ScePspFMatrix4 = undefined; const ma: [*]const f32 = @ptrCast([*]const f32, a); const mb: [*]const f32 = @ptrCast([*]const f32, b); var mr: [*]f32 = @ptrCast([*]f32, &t); var i: usize = 0; while (i < 4) : (i += 1) { var j: usize = 0; while (j < 4) : (j += 1) { var v: f32 = 0.0; var k: usize = 0; while (k < 4) : (k += 1) { v += ma[(k << 2) + j] * mb[(i << 2) + k]; mr[(i << 2) + j] = v; } } } _ = memcpy(@ptrCast([*]u8, result), @ptrCast([*]u8, &t), @sizeOf(ScePspFMatrix4)); } pub fn sceGumMatrixMode(mm: MatrixMode) void { @setRuntimeSafety(false); var mode: c_int = @enumToInt(mm); gum_matrix_update[gum_current_mode] = gum_current_matrix_update; gum_stack_depth[gum_current_mode] = @ptrCast([*]ScePspFMatrix4, gum_current_matrix); var t = @ptrCast([*]ScePspFMatrix4, gum_current_matrix); t = gum_stack_depth[@intCast(usize, mode)]; gum_current_matrix = @ptrCast(*ScePspFMatrix4, t); gum_current_mode = @intCast(u8, mode); gum_current_matrix_update = gum_matrix_update[gum_current_mode]; } pub fn sceGumMultMatrix(m: [*c]const ScePspFMatrix4) void { gumMultMatrix(gum_current_matrix, gum_current_matrix, m); gum_current_matrix_update = 1; } pub fn sceGumScale(v: *const ScePspFVector3) void { var x: f32 = 0; var y: f32 = 0; var z: f32 = 0; x = v.x; y = v.y; z = v.z; gum_current_matrix.x.x *= x; gum_current_matrix.x.y *= x; gum_current_matrix.x.z *= x; gum_current_matrix.y.x *= y; gum_current_matrix.y.y *= y; gum_current_matrix.y.z *= y; gum_current_matrix.z.x *= z; gum_current_matrix.z.y *= z; gum_current_matrix.z.z *= z; gum_current_matrix_update = 1; } pub fn sceGumTranslate(v: *const ScePspFVector3) void { var t: ScePspFMatrix4 = undefined; _ = memset(@ptrCast([*]u8, &t), 0, @sizeOf(ScePspFMatrix4)); var i: usize = 0; while (i < 4) : (i += 1) { @ptrCast([*]f32, &t)[(i << 2) + i] = 1.0; } t.w.x = v.x; t.w.y = v.y; t.w.z = v.z; gumMultMatrix(gum_current_matrix, gum_current_matrix, &t); gum_current_matrix_update = 1; } pub fn sceGumOrtho(left: f32, right: f32, bottom: f32, top: f32, near: f32, far: f32) void { var dx: f32 = right - left; var dy: f32 = top - bottom; var dz: f32 = far - near; var t: ScePspFMatrix4 = undefined; _ = memset(@ptrCast([*]u8, &t), 0, @sizeOf(ScePspFMatrix4)); t.x.x = 2.0 / dx; t.w.x = -(right + left) / dx; t.y.y = 2.0 / dy; t.w.y = -(top + bottom) / dy; t.z.z = -2.0 / dz; t.w.z = -(far + near) / dz; t.w.w = 1.0; sceGumMultMatrix(&t); } pub fn sceGumPerspective(fovy: f32, aspect: f32, near: f32, far: f32) void { var angle: f32 = (fovy / 2) * (3.14159 / 180.0); var cotangent: f32 = std.math.cos(angle) / std.math.sin(angle); var delta_z: f32 = near - far; var t: ScePspFMatrix4 = undefined; _ = memset(@ptrCast([*]u8, &t), 0, @sizeOf(ScePspFMatrix4)); t.x.x = cotangent / aspect; t.y.y = cotangent; t.z.z = (far + near) / delta_z; // -(far + near) / delta_z t.w.z = 2.0 * (far * near) / delta_z; // -2 * (far * near) / delta_z t.z.w = -1.0; t.w.w = 0.0; sceGumMultMatrix(&t); } //Maybe... I kinda just hate this function... it's pointless in most apps //Feel free to make a PR //pub fn sceGumLookAt(eye: *ScePspFVector3, center: *ScePspFVector3, up: *ScePspFVector3) void{ // // var forward : ScePspFVector3 = undefined; // forward.x = center.x - eye.x; // forward.y = center.y - eye.y; // forward.z = center.z - eye.z; // // var l : f32 = std.math.sqrt((forward.x*forward.x) + (forward.y*forward.y) + (forward.z*forward.z)); // if (l > 0.00001) // { // var il : f32 = 1.0 / l; // forward.x *= il; forward.y *= il; forward.z *= il; // } // // var side : ScePspFVector3 = undefined; // var lup : ScePspFVector3 = undefined; // var ieye : ScePspFVector3 = undefined; // var t : ScePspFMatrix4 = undefined; // // gumCrossProduct(&side,&forward,up); // gumNormalize(&side); // // gumCrossProduct(&lup,&side,&forward); // gumLoadIdentity(&t); // // t.x.x = side.x; // t.y.x = side.y; // t.z.x = side.z; // // t.x.y = lup.x; // t.y.y = lup.y; // t.z.y = lup.z; // // t.x.z = -forward.x; // t.y.z = -forward.y; // t.z.z = -forward.z; // // ieye.x = -eye.x; ieye.y = -eye.y; ieye.z = -eye.z; // // gumMultMatrix(gum_current_matrix,gum_current_matrix,&t); // gumTranslate(gum_current_matrix,&ieye); // // gum_current_matrix_update = 1; //} pub fn sceGumFullInverse() void { var t: ScePspFMatrix4 = undefined; var d0: f32 = 0; var d1: f32 = 0; var d2: f32 = 0; var d3: f32 = 0; var d: f32 = 0; d0 = gum_current_matrix.y.y * gum_current_matrix.z.z * gum_current_matrix.w.w + gum_current_matrix.y.z * gum_current_matrix.z.w * gum_current_matrix.w.y + gum_current_matrix.y.w * gum_current_matrix.z.y * gum_current_matrix.w.z - gum_current_matrix.w.y * gum_current_matrix.z.z * gum_current_matrix.y.w - gum_current_matrix.w.z * gum_current_matrix.z.w * gum_current_matrix.y.y - gum_current_matrix.w.w * gum_current_matrix.z.y * gum_current_matrix.y.z; d1 = gum_current_matrix.y.x * gum_current_matrix.z.z * gum_current_matrix.w.w + gum_current_matrix.y.z * gum_current_matrix.z.w * gum_current_matrix.w.x + gum_current_matrix.y.w * gum_current_matrix.z.x * gum_current_matrix.w.z - gum_current_matrix.w.x * gum_current_matrix.z.z * gum_current_matrix.y.w - gum_current_matrix.w.z * gum_current_matrix.z.w * gum_current_matrix.y.x - gum_current_matrix.w.w * gum_current_matrix.z.x * gum_current_matrix.y.z; d2 = gum_current_matrix.y.x * gum_current_matrix.z.y * gum_current_matrix.w.w + gum_current_matrix.y.y * gum_current_matrix.z.w * gum_current_matrix.w.x + gum_current_matrix.y.w * gum_current_matrix.z.x * gum_current_matrix.w.y - gum_current_matrix.w.x * gum_current_matrix.z.y * gum_current_matrix.y.w - gum_current_matrix.w.y * gum_current_matrix.z.w * gum_current_matrix.y.x - gum_current_matrix.w.w * gum_current_matrix.z.x * gum_current_matrix.y.y; d3 = gum_current_matrix.y.x * gum_current_matrix.z.y * gum_current_matrix.w.z + gum_current_matrix.y.y * gum_current_matrix.z.z * gum_current_matrix.w.x + gum_current_matrix.y.z * gum_current_matrix.z.x * gum_current_matrix.w.y - gum_current_matrix.w.x * gum_current_matrix.z.y * gum_current_matrix.y.z - gum_current_matrix.w.y * gum_current_matrix.z.z * gum_current_matrix.y.x - gum_current_matrix.w.z * gum_current_matrix.z.x * gum_current_matrix.y.y; d = gum_current_matrix.x.x * d0 - gum_current_matrix.x.y * d1 + gum_current_matrix.x.z * d2 - gum_current_matrix.x.w * d3; if (std.math.fabs(d) < 0.000001) { _ = memset(@ptrCast([*]u8, gum_current_matrix), 0, @sizeOf(ScePspFMatrix4)); var i: usize = 0; while (i < 4) : (i += 1) { @ptrCast([*]f32, gum_current_matrix)[(i << 2) + i] = 1.0; } return; } d = 1.0 / d; t.x.x = d * d0; t.x.y = -d * (gum_current_matrix.x.y * gum_current_matrix.z.z * gum_current_matrix.w.w + gum_current_matrix.x.z * gum_current_matrix.z.w * gum_current_matrix.w.y + gum_current_matrix.x.w * gum_current_matrix.z.y * gum_current_matrix.w.z - gum_current_matrix.w.y * gum_current_matrix.z.z * gum_current_matrix.x.w - gum_current_matrix.w.z * gum_current_matrix.z.w * gum_current_matrix.x.y - gum_current_matrix.w.w * gum_current_matrix.z.y * gum_current_matrix.x.z); t.x.z = d * (gum_current_matrix.x.y * gum_current_matrix.y.z * gum_current_matrix.w.w + gum_current_matrix.x.z * gum_current_matrix.y.w * gum_current_matrix.w.y + gum_current_matrix.x.w * gum_current_matrix.y.y * gum_current_matrix.w.z - gum_current_matrix.w.y * gum_current_matrix.y.z * gum_current_matrix.x.w - gum_current_matrix.w.z * gum_current_matrix.y.w * gum_current_matrix.x.y - gum_current_matrix.w.w * gum_current_matrix.y.y * gum_current_matrix.x.z); t.x.w = -d * (gum_current_matrix.x.y * gum_current_matrix.y.z * gum_current_matrix.z.w + gum_current_matrix.x.z * gum_current_matrix.y.w * gum_current_matrix.z.y + gum_current_matrix.x.w * gum_current_matrix.y.y * gum_current_matrix.z.z - gum_current_matrix.z.y * gum_current_matrix.y.z * gum_current_matrix.x.w - gum_current_matrix.z.z * gum_current_matrix.y.w * gum_current_matrix.x.y - gum_current_matrix.z.w * gum_current_matrix.y.y * gum_current_matrix.x.z); t.y.x = -d * d1; t.y.y = d * (gum_current_matrix.x.x * gum_current_matrix.z.z * gum_current_matrix.w.w + gum_current_matrix.x.z * gum_current_matrix.z.w * gum_current_matrix.w.x + gum_current_matrix.x.w * gum_current_matrix.z.x * gum_current_matrix.w.z - gum_current_matrix.w.x * gum_current_matrix.z.z * gum_current_matrix.x.w - gum_current_matrix.w.z * gum_current_matrix.z.w * gum_current_matrix.x.x - gum_current_matrix.w.w * gum_current_matrix.z.x * gum_current_matrix.x.z); t.y.z = -d * (gum_current_matrix.x.x * gum_current_matrix.y.z * gum_current_matrix.w.w + gum_current_matrix.x.z * gum_current_matrix.y.w * gum_current_matrix.w.x + gum_current_matrix.x.w * gum_current_matrix.y.x * gum_current_matrix.w.z - gum_current_matrix.w.x * gum_current_matrix.y.z * gum_current_matrix.x.w - gum_current_matrix.w.z * gum_current_matrix.y.w * gum_current_matrix.x.x - gum_current_matrix.w.w * gum_current_matrix.y.x * gum_current_matrix.x.z); t.y.w = d * (gum_current_matrix.x.x * gum_current_matrix.y.z * gum_current_matrix.z.w + gum_current_matrix.x.z * gum_current_matrix.y.w * gum_current_matrix.z.x + gum_current_matrix.x.w * gum_current_matrix.y.x * gum_current_matrix.z.z - gum_current_matrix.z.x * gum_current_matrix.y.z * gum_current_matrix.x.w - gum_current_matrix.z.z * gum_current_matrix.y.w * gum_current_matrix.x.x - gum_current_matrix.z.w * gum_current_matrix.y.x * gum_current_matrix.x.z); t.z.x = d * d2; t.z.y = -d * (gum_current_matrix.x.x * gum_current_matrix.z.y * gum_current_matrix.w.w + gum_current_matrix.x.y * gum_current_matrix.z.w * gum_current_matrix.w.x + gum_current_matrix.x.w * gum_current_matrix.z.x * gum_current_matrix.w.y - gum_current_matrix.w.x * gum_current_matrix.z.y * gum_current_matrix.x.w - gum_current_matrix.w.y * gum_current_matrix.z.w * gum_current_matrix.x.x - gum_current_matrix.w.w * gum_current_matrix.z.x * gum_current_matrix.x.y); t.z.z = d * (gum_current_matrix.x.x * gum_current_matrix.y.y * gum_current_matrix.w.w + gum_current_matrix.x.y * gum_current_matrix.y.w * gum_current_matrix.w.x + gum_current_matrix.x.w * gum_current_matrix.y.x * gum_current_matrix.w.y - gum_current_matrix.w.x * gum_current_matrix.y.y * gum_current_matrix.x.w - gum_current_matrix.w.y * gum_current_matrix.y.w * gum_current_matrix.x.x - gum_current_matrix.w.w * gum_current_matrix.y.x * gum_current_matrix.x.y); t.z.w = -d * (gum_current_matrix.x.x * gum_current_matrix.y.y * gum_current_matrix.z.w + gum_current_matrix.x.y * gum_current_matrix.y.w * gum_current_matrix.z.x + gum_current_matrix.x.w * gum_current_matrix.y.x * gum_current_matrix.z.y - gum_current_matrix.z.x * gum_current_matrix.y.y * gum_current_matrix.x.w - gum_current_matrix.z.y * gum_current_matrix.y.w * gum_current_matrix.x.x - gum_current_matrix.z.w * gum_current_matrix.y.x * gum_current_matrix.x.y); t.w.x = -d * d3; t.w.y = d * (gum_current_matrix.x.x * gum_current_matrix.z.y * gum_current_matrix.w.z + gum_current_matrix.x.y * gum_current_matrix.z.z * gum_current_matrix.w.x + gum_current_matrix.x.z * gum_current_matrix.z.x * gum_current_matrix.w.y - gum_current_matrix.w.x * gum_current_matrix.z.y * gum_current_matrix.x.z - gum_current_matrix.w.y * gum_current_matrix.z.z * gum_current_matrix.x.x - gum_current_matrix.w.z * gum_current_matrix.z.x * gum_current_matrix.x.y); t.w.z = -d * (gum_current_matrix.x.x * gum_current_matrix.y.y * gum_current_matrix.w.z + gum_current_matrix.x.y * gum_current_matrix.y.z * gum_current_matrix.w.x + gum_current_matrix.x.z * gum_current_matrix.y.x * gum_current_matrix.w.y - gum_current_matrix.w.x * gum_current_matrix.y.y * gum_current_matrix.x.z - gum_current_matrix.w.y * gum_current_matrix.y.z * gum_current_matrix.x.x - gum_current_matrix.w.z * gum_current_matrix.y.x * gum_current_matrix.x.y); t.w.w = d * (gum_current_matrix.x.x * gum_current_matrix.y.y * gum_current_matrix.z.z + gum_current_matrix.x.y * gum_current_matrix.y.z * gum_current_matrix.z.x + gum_current_matrix.x.z * gum_current_matrix.y.x * gum_current_matrix.z.y - gum_current_matrix.z.x * gum_current_matrix.y.y * gum_current_matrix.x.z - gum_current_matrix.z.y * gum_current_matrix.y.z * gum_current_matrix.x.x - gum_current_matrix.z.z * gum_current_matrix.y.x * gum_current_matrix.x.y); _ = memcpy(@ptrCast([*]u8, gum_current_matrix), @ptrCast([*]u8, &t), @sizeOf(ScePspFMatrix4)); gum_current_matrix_update = 1; } fn gumDotProduct(a: *ScePspFVector3, b: *ScePspFVector3) f32 { return (a.x * b.x) + (a.y * b.y) + (a.z * b.z); } pub fn sceGumFastInverse() void { var t: ScePspFMatrix4 = undefined; var negPos: ScePspFVector3 = ScePspFVector3{ .x = -gum_current_matrix.w.x, .y = -gum_current_matrix.w.y, .z = -gum_current_matrix.w.z }; // transpose rotation t.x.x = gum_current_matrix.x.x; t.x.y = gum_current_matrix.y.x; t.x.z = gum_current_matrix.z.x; t.x.w = 0; t.y.x = gum_current_matrix.x.y; t.y.y = gum_current_matrix.y.y; t.y.z = gum_current_matrix.z.y; t.y.w = 0; t.z.x = gum_current_matrix.x.z; t.z.y = gum_current_matrix.y.z; t.z.z = gum_current_matrix.z.z; t.z.w = 0; // compute inverse position t.w.x = gumDotProduct(&negPos, @ptrCast(*ScePspFVector3, &gum_current_matrix.x)); t.w.y = gumDotProduct(&negPos, @ptrCast(*ScePspFVector3, &gum_current_matrix.y)); t.w.z = gumDotProduct(&negPos, @ptrCast(*ScePspFVector3, &gum_current_matrix.z)); t.w.w = 1; _ = memcpy(@ptrCast([*]u8, gum_current_matrix), @ptrCast([*]u8, &t), @sizeOf(ScePspFMatrix4)); gum_current_matrix_update = 1; }
src/psp/sdk/pspgumimpl.zig
const std = @import("std"); const api = @import("./buzz_api.zig"); const utils = @import("../src/utils.zig"); export fn getStdIn(vm: *api.VM) c_int { vm.bz_pushNum(@intToFloat(f64, std.io.getStdIn().handle)); return 1; } export fn getStdOut(vm: *api.VM) c_int { vm.bz_pushNum(@intToFloat(f64, std.io.getStdOut().handle)); return 1; } export fn getStdErr(vm: *api.VM) c_int { vm.bz_pushNum(@intToFloat(f64, std.io.getStdErr().handle)); return 1; } export fn FileOpen(vm: *api.VM) c_int { const mode: u8 = @floatToInt(u8, api.Value.bz_valueToNumber(vm.bz_peek(0))); const filename: []const u8 = std.mem.sliceTo(api.Value.bz_valueToString(vm.bz_peek(1)) orelse "", 0); var file: std.fs.File = if (std.fs.path.isAbsolute(filename)) switch (mode) { 0 => std.fs.openFileAbsolute(filename, .{ .mode = .read_only }) catch { vm.bz_throwString("Could not open file"); return -1; }, else => std.fs.createFileAbsolute(filename, .{ .read = mode != 1 }) catch { vm.bz_throwString("Could not open file"); return -1; }, } else switch (mode) { 0 => std.fs.cwd().openFile(filename, .{ .mode = .read_only }) catch { vm.bz_throwString("Could not open file"); return -1; }, else => std.fs.cwd().createFile(filename, .{ .read = mode != 1 }) catch { vm.bz_throwString("Could not open file"); return -1; }, }; vm.bz_pushNum(@intToFloat(f64, file.handle)); return 1; } export fn FileClose(vm: *api.VM) c_int { const handle: std.fs.File.Handle = @floatToInt( std.fs.File.Handle, api.Value.bz_valueToNumber(vm.bz_peek(0)), ); const file: std.fs.File = std.fs.File{ .handle = handle }; file.close(); return 0; } export fn FileReadAll(vm: *api.VM) c_int { const handle: std.fs.File.Handle = @floatToInt( std.fs.File.Handle, api.Value.bz_valueToNumber(vm.bz_peek(0)), ); const file: std.fs.File = std.fs.File{ .handle = handle }; const content: [*:0]u8 = file.readToEndAllocOptions(api.VM.allocator, 10240, null, @alignOf(u8), 0) catch { vm.bz_throwString("Could not read file"); return -1; }; vm.bz_pushString(api.ObjString.bz_string(vm, content) orelse { vm.bz_throwString("Could not read file"); return -1; }); return 1; } export fn FileReadLine(vm: *api.VM) c_int { const handle: std.fs.File.Handle = @floatToInt( std.fs.File.Handle, api.Value.bz_valueToNumber(vm.bz_peek(0)), ); const file: std.fs.File = std.fs.File{ .handle = handle }; const reader = file.reader(); var buffer = std.ArrayList(u8).init(api.VM.allocator); var i: usize = 0; while (i < 16 * 8 * 64) : (i += 1) { const read: ?u8 = reader.readByte() catch null; if (read == null) { break; } buffer.append(read.?) catch { vm.bz_throwString("Could not read file"); return -1; }; if (read.? == '\n') { break; } } // EOF? if (buffer.items.len == 0) { vm.bz_pushNull(); } else { vm.bz_pushString(api.ObjString.bz_string(vm, utils.toCString(api.VM.allocator, buffer.items) orelse { vm.bz_throwString("Could not read file"); return -1; }) orelse { vm.bz_throwString("Could not read file"); return -1; }); } return 1; } export fn FileRead(vm: *api.VM) c_int { const n: u64 = @floatToInt(u64, api.Value.bz_valueToNumber(vm.bz_peek(0))); const handle: std.fs.File.Handle = @floatToInt( std.fs.File.Handle, api.Value.bz_valueToNumber(vm.bz_peek(1)), ); const file: std.fs.File = std.fs.File{ .handle = handle }; const reader = file.reader(); var buffer = std.ArrayList(u8).initCapacity(api.VM.allocator, n) catch { vm.bz_throwString("Could not read file"); return -1; }; buffer.expandToCapacity(); const read = reader.read(buffer.items) catch { vm.bz_throwString("Could not read file"); return -1; }; if (read == 0) { vm.bz_pushNull(); } else { vm.bz_pushString(api.ObjString.bz_string(vm, utils.toCString(api.VM.allocator, buffer.items) orelse { vm.bz_throwString("Could not read file"); return -1; }) orelse { vm.bz_throwString("Could not read file"); return -1; }); } return 1; } // extern fun File_write(num fd, [num] bytes) > void; export fn FileWrite(vm: *api.VM) c_int { const handle: std.fs.File.Handle = @floatToInt( std.fs.File.Handle, api.Value.bz_valueToNumber(vm.bz_peek(1)), ); const file: std.fs.File = std.fs.File{ .handle = handle }; _ = file.write(std.mem.sliceTo(vm.bz_peek(0).bz_valueToString().?, 0)) catch { vm.bz_throwString("Could not read file"); return -1; }; return 0; }
lib/buzz_io.zig
const std = @import("std"); const Allocator = std.mem.Allocator; const ArenaAllocator = std.heap.ArenaAllocator; const testing = std.testing; const assert = std.debug.assert; const mustache = @import("../mustache.zig"); const ParseError = mustache.ParseError; const TemplateOptions = mustache.options.TemplateOptions; const TemplateLoadMode = mustache.options.TemplateLoadMode; const ref_counter = @import("ref_counter.zig"); const parsing = @import("parsing.zig"); const PartType = parsing.PartType; const DelimiterType = parsing.DelimiterType; const Delimiters = parsing.Delimiters; const IndexBookmark = parsing.IndexBookmark; pub fn TextScanner(comptime Node: type, comptime options: TemplateOptions) type { const RefCounter = ref_counter.RefCounter(options); const TrimmingIndex = parsing.TrimmingIndex(options); const FileReader = parsing.FileReader(options); const allow_lambdas = options.features.lambdas == .Enabled; return struct { const Self = @This(); const TextPart = Node.TextPart; const Trimmer = parsing.Trimmer(Self, TrimmingIndex); const Pos = struct { lin: u32 = 1, col: u32 = 1, }; const State = union(enum) { matching_open: DelimiterIndex, matching_close: MatchingCloseState, produce_open: void, produce_close: PartType, eos: void, const DelimiterIndex = u16; const MatchingCloseState = struct { delimiter_index: DelimiterIndex = 0, part_type: PartType, }; }; content: []const u8, index: u32 = 0, block_index: u32 = 0, state: State = .{ .matching_open = 0 }, start_pos: Pos = .{}, current_pos: Pos = .{}, delimiter_max_size: u32 = 0, delimiters: Delimiters = undefined, nodes: *const Node.List = undefined, stream: switch (options.source) { .Stream => struct { reader: FileReader, ref_counter: RefCounter = .{}, preserve_bookmark: ?u32 = null, }, .String => void, } = undefined, bookmark: if (allow_lambdas) struct { node_index: ?u32 = null, last_starting_mark: u32 = 0, } else void = if (allow_lambdas) .{} else {}, pub const ComptimeCounter = struct { /// Quantity of nodes present on the template text nodes: usize = 0, /// Max path lengh present on the template text path: usize = 0, pub fn count() @This() { comptime { const comptime_loaded = switch (options.load_mode) { .comptime_loaded => |payload| payload, .runtime_loaded => @compileError("Cannot count a runtime loaded template"), }; @setEvalBranchQuota(999999); const allocator: Allocator = undefined; var scanner = Self.init(comptime_loaded.template_text) catch unreachable; scanner.setDelimiters(comptime_loaded.default_delimiters) catch { // TODO unreachable; }; var ret: @This() = .{}; while (scanner.next(allocator) catch unreachable) |*part| { ret.nodes += 1; const len: usize = switch (part.part_type) { .interpolation, .section, .inverted_section, .unescaped_interpolation, .triple_mustache, => std.mem.count(u8, part.content.slice, ".") + 1, .delimiters => { const delimiter = part.parseDelimiters() orelse continue; scanner.setDelimiters(delimiter) catch { // TODO unreachable; }; continue; }, else => continue, }; if (len > ret.path) ret.path = len; } return ret; } } }; /// Should be the template content if source == .String /// or the absolute path if source == .File pub fn init(template: []const u8) if (options.source == .String) error{}!Self else FileReader.OpenError!Self { return switch (options.source) { .String => Self{ .content = template, }, .Stream => Self{ .content = &.{}, .stream = .{ .reader = try FileReader.init(template), }, }, }; } pub fn deinit(self: *Self, allocator: Allocator) void { if (comptime options.source == .Stream) { self.stream.ref_counter.unRef(allocator); self.stream.reader.deinit(); } } pub fn setDelimiters(self: *Self, delimiters: Delimiters) ParseError!void { if (delimiters.starting_delimiter.len == 0) return ParseError.InvalidDelimiters; if (delimiters.ending_delimiter.len == 0) return ParseError.InvalidDelimiters; self.delimiter_max_size = @intCast(u32, std.math.max(delimiters.starting_delimiter.len, delimiters.ending_delimiter.len) + 1); self.delimiters = delimiters; } fn requestContent(self: *Self, allocator: Allocator) !void { if (comptime options.source == .Stream) { if (!self.stream.reader.finished()) { // // Requesting a new buffer must preserve some parts of the current slice that are still needed const adjust: struct { off_set: u32, preserve: ?u32 } = adjust: { // block_index: initial index of the current TextBlock, the minimum part needed // bookmark.last_starting_mark: index of the last starting mark '{{', used to determine the inner_text between two tags const last_index = if (self.bookmark.node_index == null) self.block_index else std.math.min(self.block_index, self.bookmark.last_starting_mark); if (self.stream.preserve_bookmark) |preserve| { // Only when reading from Stream // stream.preserve_bookmark: is the index of the pending bookmark if (preserve < last_index) { break :adjust .{ .off_set = preserve, .preserve = 0, }; } else { break :adjust .{ .off_set = last_index, .preserve = preserve - last_index, }; } } else { break :adjust .{ .off_set = last_index, .preserve = null, }; } }; const prepend = self.content[adjust.off_set..]; const read = try self.stream.reader.read(allocator, prepend); errdefer read.ref_counter.unRef(allocator); self.stream.ref_counter.unRef(allocator); self.stream.ref_counter = read.ref_counter; self.content = read.slice; self.index -= adjust.off_set; self.block_index -= adjust.off_set; if (allow_lambdas) { if (self.bookmark.node_index != null) { self.adjustBookmarkOffset(self.bookmark.node_index, adjust.off_set); self.bookmark.last_starting_mark -= adjust.off_set; } self.stream.preserve_bookmark = adjust.preserve; } } } } pub fn next(self: *Self, allocator: Allocator) !?TextPart { if (self.state == .eos) return null; self.index = self.block_index; var trimmer = Trimmer.init(self); while (self.index < self.content.len or (options.source == .Stream and !self.stream.reader.finished())) : (self.index += 1) { if (comptime options.source == .Stream) { // Request a new slice if near to the end const look_ahead = self.index + self.delimiter_max_size + 1; if (look_ahead >= self.content.len) { try self.requestContent(allocator); } } const char = self.content[self.index]; switch (self.state) { .matching_open => |delimiter_index| { const delimiter_char = self.delimiters.starting_delimiter[delimiter_index]; if (char == delimiter_char) { const next_index = delimiter_index + 1; if (self.delimiters.starting_delimiter.len == next_index) { self.state = .produce_open; } else { self.state.matching_open = next_index; } } else { self.state.matching_open = 0; trimmer.move(); } self.moveLineCounter(char); }, .matching_close => |*close_state| { const delimiter_char = self.delimiters.ending_delimiter[close_state.delimiter_index]; if (char == delimiter_char) { const next_index = close_state.delimiter_index + 1; if (self.delimiters.ending_delimiter.len == next_index) { self.state = .{ .produce_close = close_state.part_type }; } else { close_state.delimiter_index = next_index; } } else { close_state.delimiter_index = 0; } self.moveLineCounter(char); }, .produce_open => { return self.produceOpen(trimmer, char) orelse continue; }, .produce_close => { return self.produceClose(trimmer, char); }, .eos => return null, } } return self.produceEos(trimmer); } inline fn moveLineCounter(self: *Self, char: u8) void { if (char == '\n') { self.current_pos.lin += 1; self.current_pos.col = 1; } else { self.current_pos.col += 1; } } fn produceOpen(self: *Self, trimmer: Trimmer, char: u8) ?TextPart { const skip_current = switch (char) { @enumToInt(PartType.comments), @enumToInt(PartType.section), @enumToInt(PartType.inverted_section), @enumToInt(PartType.close_section), @enumToInt(PartType.partial), @enumToInt(PartType.parent), @enumToInt(PartType.block), @enumToInt(PartType.unescaped_interpolation), @enumToInt(PartType.delimiters), @enumToInt(PartType.triple_mustache), => true, else => false, }; const delimiter_len = @intCast(u32, self.delimiters.starting_delimiter.len); defer { self.start_pos = .{ .lin = self.current_pos.lin, .col = self.current_pos.col - delimiter_len, }; if (skip_current) { // Skips the current char on the next iteration if it is part of the tag, like '#' is part of '{{#' self.block_index = self.index + 1; self.moveLineCounter(char); // Sets the next state self.state = .{ .matching_close = .{ .delimiter_index = 0, .part_type = @intToEnum(PartType, char), }, }; } else { // If the current char is not part of the tag, it must be processed again on the next iteration self.block_index = self.index; // Sets the next state self.state = .{ .matching_close = .{ .delimiter_index = 0, .part_type = .interpolation, }, }; } } const last_pos = self.index - delimiter_len; if (allow_lambdas) self.bookmark.last_starting_mark = last_pos; const tail = self.content[self.block_index..last_pos]; return if (tail.len > 0) TextPart{ .part_type = .static_text, .is_stand_alone = PartType.canBeStandAlone(.static_text), .content = .{ .slice = tail, .ref_counter = if (options.source == .Stream) self.stream.ref_counter.ref() else .{}, }, .source = .{ .lin = self.start_pos.lin, .col = self.start_pos.col, }, .trimming = .{ .left = trimmer.getLeftTrimmingIndex(), .right = trimmer.getRightTrimmingIndex(), }, } else null; } fn produceClose(self: *Self, trimmer: Trimmer, char: u8) TextPart { const triple_mustache_close = '}'; const Mark = struct { block_index: u32, skip_current: bool }; const mark: Mark = mark: { switch (char) { triple_mustache_close => { defer self.block_index = self.index + 1; break :mark .{ .block_index = self.block_index, .skip_current = true }; }, else => { defer self.block_index = self.index; break :mark .{ .block_index = self.block_index, .skip_current = false }; }, } }; defer { self.state = .{ .matching_open = 0 }; if (mark.skip_current) self.moveLineCounter(char); self.start_pos = .{ .lin = self.current_pos.lin, .col = self.current_pos.col, }; } const last_pos = self.index - self.delimiters.ending_delimiter.len; const tail = self.content[mark.block_index..last_pos]; return TextPart{ .part_type = self.state.produce_close, .is_stand_alone = PartType.canBeStandAlone(self.state.produce_close), .content = .{ .slice = tail, .ref_counter = if (options.source == .Stream) self.stream.ref_counter.ref() else .{}, }, .source = .{ .lin = self.start_pos.lin, .col = self.start_pos.col, }, .trimming = .{ .left = trimmer.getLeftTrimmingIndex(), .right = trimmer.getRightTrimmingIndex(), }, }; } fn produceEos(self: *Self, trimmer: Trimmer) ?TextPart { defer self.state = .eos; switch (self.state) { .produce_close => |part_type| { const last_pos = self.content.len - self.delimiters.ending_delimiter.len; const tail = self.content[self.block_index..last_pos]; return TextPart{ .part_type = part_type, .is_stand_alone = part_type.canBeStandAlone(), .content = .{ .slice = tail, .ref_counter = if (options.source == .Stream) self.stream.ref_counter.ref() else .{}, }, .source = .{ .lin = self.start_pos.lin, .col = self.start_pos.col, }, .trimming = .{ .left = trimmer.getLeftTrimmingIndex(), .right = trimmer.getRightTrimmingIndex(), }, }; }, else => { const tail = self.content[self.block_index..]; return if (tail.len > 0) TextPart{ .part_type = .static_text, .is_stand_alone = PartType.canBeStandAlone(.static_text), .content = .{ .slice = tail, .ref_counter = if (options.source == .Stream) self.stream.ref_counter.ref() else .{}, }, .source = .{ .lin = self.start_pos.lin, .col = self.start_pos.col, }, .trimming = .{ .left = trimmer.getLeftTrimmingIndex(), .right = trimmer.getRightTrimmingIndex(), }, } else null; }, } } pub fn beginBookmark(self: *Self, node: *Node) Allocator.Error!void { if (allow_lambdas) { assert(node.inner_text.bookmark == null); node.inner_text.bookmark = IndexBookmark{ .prev_node_index = self.bookmark.node_index, .text_index = self.index, }; self.bookmark.node_index = node.index; if (options.source == .Stream) { if (self.stream.preserve_bookmark) |preserve| { assert(preserve <= self.index); } else { self.stream.preserve_bookmark = self.index; } } } } pub fn endBookmark(self: *Self, list: *Node.List) Allocator.Error!?[]const u8 { if (allow_lambdas) { if (self.bookmark.node_index) |node_index| { const current = &list.items[node_index]; const bookmark = if (current.inner_text.bookmark) |*value| value else unreachable; defer { self.bookmark.node_index = bookmark.prev_node_index; if (options.source == .Stream and bookmark.prev_node_index == null) { self.stream.preserve_bookmark = null; } } assert(bookmark.text_index < self.content.len); assert(bookmark.text_index <= self.bookmark.last_starting_mark); assert(self.bookmark.last_starting_mark < self.content.len); return self.content[bookmark.text_index..self.bookmark.last_starting_mark]; } } return null; } fn adjustBookmarkOffset(self: *Self, node_index: ?u32, off_set: u32) void { if (allow_lambdas) { if (node_index) |index| { var current = &self.nodes.items[index]; var bookmark = if (current.inner_text.bookmark) |*value| value else unreachable; assert(bookmark.text_index >= off_set); bookmark.text_index -= off_set; self.adjustBookmarkOffset(bookmark.prev_node_index, off_set); } } } }; } const testing_options = TemplateOptions{ .source = .{ .String = .{} }, .output = .Render, }; const TestingNode = parsing.Node(testing_options); const TestingTextScanner = parsing.TextScanner(TestingNode, testing_options); const TestingTrimmingIndex = parsing.TrimmingIndex(testing_options); test "basic tests" { const content = \\Hello{{tag1}} \\World{{{ tag2 }}}Until eof ; const allocator = testing.allocator; var reader = try TestingTextScanner.init(content); defer reader.deinit(allocator); try reader.setDelimiters(.{}); var part_1 = try reader.next(allocator); try expectTag(.static_text, "Hello", part_1, 1, 1); defer part_1.?.unRef(allocator); var part_2 = try reader.next(allocator); try expectTag(.interpolation, "tag1", part_2, 1, 6); defer part_2.?.unRef(allocator); var part_3 = try reader.next(allocator); try expectTag(.static_text, "\nWorld", part_3, 1, 14); defer part_3.?.unRef(allocator); var part_4 = try reader.next(allocator); try expectTag(.triple_mustache, " tag2 ", part_4, 2, 6); defer part_4.?.unRef(allocator); var part_5 = try reader.next(allocator); try expectTag(.static_text, "Until eof", part_5, 2, 18); defer part_5.?.unRef(allocator); var part_6 = try reader.next(allocator); try testing.expect(part_6 == null); } test "custom tags" { const content = \\Hello[tag1] \\World[ tag2 ]Until eof ; const allocator = testing.allocator; var reader = try TestingTextScanner.init(content); defer reader.deinit(allocator); try reader.setDelimiters(.{ .starting_delimiter = "[", .ending_delimiter = "]" }); var part_1 = try reader.next(allocator); try expectTag(.static_text, "Hello", part_1, 1, 1); defer part_1.?.unRef(allocator); var part_2 = try reader.next(allocator); try expectTag(.interpolation, "tag1", part_2, 1, 6); defer part_2.?.unRef(allocator); var part_3 = try reader.next(allocator); try expectTag(.static_text, "\nWorld", part_3, 1, 12); defer part_3.?.unRef(allocator); var part_4 = try reader.next(allocator); try expectTag(.interpolation, " tag2 ", part_4, 2, 6); defer part_4.?.unRef(allocator); var part_5 = try reader.next(allocator); try expectTag(.static_text, "Until eof", part_5, 2, 14); defer part_5.?.unRef(allocator); var part_6 = try reader.next(allocator); try testing.expect(part_6 == null); } test "EOF" { const content = "{{tag1}}"; const allocator = testing.allocator; var reader = try TestingTextScanner.init(content); defer reader.deinit(allocator); try reader.setDelimiters(.{}); var part_1 = try reader.next(allocator); try expectTag(.interpolation, "tag1", part_1, 1, 1); defer part_1.?.unRef(allocator); var part_2 = try reader.next(allocator); try testing.expect(part_2 == null); } test "EOF custom tags" { const content = "[tag1]"; const allocator = testing.allocator; var reader = try TestingTextScanner.init(content); defer reader.deinit(allocator); try reader.setDelimiters(.{ .starting_delimiter = "[", .ending_delimiter = "]" }); var part_1 = try reader.next(allocator); try expectTag(.interpolation, "tag1", part_1, 1, 1); defer part_1.?.unRef(allocator); var part_2 = try reader.next(allocator); try testing.expect(part_2 == null); } test "bookmarks" { // 1 2 3 4 5 6 7 8 // 1234567890123456789012345678901234567890123456789012345678901234567890123456789012345 // ↓ ↓ ↓ ↓ ↓ ↓ ↓ const content = "{{#section1}}begin_content1{{#section2}}content2{{/section2}}end_content1{{/section1}}"; const allocator = testing.allocator; var nodes: TestingNode.List = .{}; defer nodes.deinit(allocator); var reader = try TestingTextScanner.init(content); defer reader.deinit(allocator); try reader.setDelimiters(.{}); var token_1 = try reader.next(allocator); try expectTag(.section, "section1", token_1, 1, 1); defer token_1.?.unRef(allocator); try nodes.append(allocator, TestingNode{ .index = 0, .identifier = undefined, .text_part = token_1.? }); try reader.beginBookmark(&nodes.items[0]); var token_2 = try reader.next(allocator); try expectTag(.static_text, "begin_content1", token_2, 1, 14); defer token_2.?.unRef(allocator); var token_3 = try reader.next(allocator); try expectTag(.section, "section2", token_3, 1, 28); defer token_3.?.unRef(allocator); try nodes.append(allocator, TestingNode{ .index = 1, .identifier = undefined, .text_part = token_3.? }); try reader.beginBookmark(&nodes.items[1]); var token_4 = try reader.next(allocator); try expectTag(.static_text, "content2", token_4, 1, 41); defer token_4.?.unRef(allocator); var token_5 = try reader.next(allocator); try expectTag(.close_section, "section2", token_5, 1, 49); defer token_5.?.unRef(allocator); if (try reader.endBookmark(&nodes)) |bookmark_1| { try testing.expectEqualStrings("content2", bookmark_1); } else { try testing.expect(false); } var token_6 = try reader.next(allocator); try expectTag(.static_text, "end_content1", token_6, 1, 62); defer token_6.?.unRef(allocator); var token_7 = try reader.next(allocator); try expectTag(.close_section, "section1", token_7, 1, 74); defer token_7.?.unRef(allocator); if (try reader.endBookmark(&nodes)) |bookmark_2| { try testing.expectEqualStrings("begin_content1{{#section2}}content2{{/section2}}end_content1", bookmark_2); } else { try testing.expect(false); } var part_8 = try reader.next(allocator); try testing.expect(part_8 == null); } fn expectTag(part_type: PartType, content: []const u8, value: anytype, lin: u32, col: u32) !void { if (value) |part| { try testing.expectEqual(part_type, part.part_type); try testing.expectEqualStrings(content, part.content.slice); try testing.expectEqual(lin, part.source.lin); try testing.expectEqual(col, part.source.col); } else { try testing.expect(false); } }
src/parsing/text_scanner.zig
const std = @import("std"); const Builder = std.build.Builder; const FileSource = std.build.FileSource; const LibExeObjStep = std.build.LibExeObjStep; const print = std.debug.print; const builtin = @import("builtin"); const Pkg = std.build.Pkg; const log = std.log.scoped(.build); const stdx = @import("stdx/lib.zig"); const platform = @import("platform/lib.zig"); const graphics = @import("graphics/lib.zig"); const ui = @import("ui/lib.zig"); const parser = @import("parser/lib.zig"); const runtime = @import("runtime/lib.zig"); const sdl = @import("lib/sdl/lib.zig"); const ssl = @import("lib/openssl/lib.zig"); const zlib = @import("lib/zlib/lib.zig"); const http2 = @import("lib/nghttp2/lib.zig"); const curl = @import("lib/curl/lib.zig"); const uv = @import("lib/uv/lib.zig"); const h2o = @import("lib/h2o/lib.zig"); const stb = @import("lib/stb/lib.zig"); const freetype = @import("lib/freetype2/lib.zig"); const gl = @import("lib/gl/lib.zig"); const vk = @import("lib/vk/lib.zig"); const lyon = @import("lib/clyon/lib.zig"); const tess2 = @import("lib/tess2/lib.zig"); const maudio = @import("lib/miniaudio/lib.zig"); const mingw = @import("lib/mingw/lib.zig"); const backend = @import("platform/backend.zig"); const cgltf = @import("lib/cgltf/lib.zig"); const GitRepoStep = @import("GitRepoStep.zig"); const VersionName = "v0.1"; const EXTRAS_REPO_SHA = "5c31d18797ccb0c71adaf6a31beab53a8c070b5c"; const ZIG_V8_BRANCH = "9.9.115.9"; const ZIG_V8_SHA = "8e6837d6d517134fcef0527ed7e933efeb1ee9db"; // Debugging: // Set to true to show generated build-lib and other commands created from execFromStep. const PrintCommands = false; // Useful in dev to see descrepancies between zig and normal builds. const LibV8Path: ?[]const u8 = null; const LibSdlPath: ?[]const u8 = null; const LibSslPath: ?[]const u8 = null; const LibCryptoPath: ?[]const u8 = null; const LibCurlPath: ?[]const u8 = null; const LibUvPath: ?[]const u8 = null; const LibH2oPath: ?[]const u8 = null; // To enable tracy profiling, append -Dtracy and ./lib/tracy must point to their main src tree. pub fn build(b: *Builder) !void { // Options. const path = b.option([]const u8, "path", "Path to main file, for: build, run, test-file") orelse ""; const filter = b.option([]const u8, "filter", "For tests") orelse ""; const tracy = b.option(bool, "tracy", "Enable tracy profiling.") orelse false; const link_graphics = b.option(bool, "graphics", "Link graphics libs") orelse false; const add_runtime = b.option(bool, "runtime", "Add the runtime package") orelse false; const audio = b.option(bool, "audio", "Link audio libs") orelse false; const v8 = b.option(bool, "v8", "Link v8 lib") orelse false; const net = b.option(bool, "net", "Link net libs") orelse false; const args = b.option([]const []const u8, "arg", "Append an arg into run step.") orelse &[_][]const u8{}; const extras_sha = b.option([]const u8, "deps-rev", "Override the extras repo sha.") orelse EXTRAS_REPO_SHA; const is_official_build = b.option(bool, "is-official-build", "Whether the build should be an official build.") orelse false; const target = b.standardTargetOptions(.{}); const mode = b.standardReleaseOptions(); const wsl = b.option(bool, "wsl", "Whether this running in wsl.") orelse false; const link_lyon = b.option(bool, "lyon", "Link lyon graphics for testing.") orelse false; const link_tess2 = b.option(bool, "tess2", "Link libtess2 for testing.") orelse false; b.verbose = PrintCommands; if (builtin.os.tag == .macos and target.getOsTag() == .macos) { if (target.isNative()) { // NOTE: builder.sysroot or --sysroot <path> should not be set for a native build; // zig will use getDarwinSDK by default and not use it's own libc headers (meant for cross compilation) // with one small caveat: the lib/exe must be linking with system library or framework. See Compilation.zig. // There are lib.linkFramework("CoreServices") in places where we want to force it to use native headers. // The target must be: <cpu>-native-gnu } else { // Targeting mac but not native. eg. targeting macos with a minimum version. // Set sysroot with sdk path and use these setups as needed for libs: // lib.addFrameworkDir("/System/Library/Frameworks"); // lib.addSystemIncludeDir("/usr/include"); // Don't use zig's libc, since it might not be up to date with the latest SDK which we need for frameworks. // lib.setLibCFile(std.build.FileSource.relative("./lib/macos.libc")); if (std.zig.system.darwin.getDarwinSDK(b.allocator, builtin.target)) |sdk| { b.sysroot = sdk.path; } } } // Default build context. var ctx = BuilderContext{ .builder = b, .enable_tracy = tracy, .link_graphics = link_graphics, .link_audio = audio, .add_v8_pkg = v8, .add_runtime_pkg = add_runtime, .link_v8 = v8, .link_net = net, .link_lyon = link_lyon, .link_tess2 = link_tess2, .link_mock = false, .path = path, .filter = filter, .mode = mode, .target = target, .wsl = wsl, }; // Contains optional prebuilt lyon lib as well as windows crypto/ssl prebuilt libs. // TODO: Remove this dependency once windows can build crypto/ssl. const extras_repo = GitRepoStep.create(b, .{ .url = "https://github.com/fubark/cosmic-deps", .branch = "master", .sha = extras_sha, .path = srcPath() ++ "/lib/extras", }); { // Like extras_repo step but with auto-fetch enabled. const extras_repo_fetch = GitRepoStep.create(b, .{ .url = "https://github.com/fubark/cosmic-deps", .branch = "master", .sha = extras_sha, .path = srcPath() ++ "/lib/extras", .fetch_enabled = true, }); b.step("get-extras", "Clone/pull the extras repo.").dependOn(&extras_repo_fetch.step); } const get_v8_lib = createGetV8LibStep(b, target); b.step("get-v8-lib", "Fetches prebuilt static lib. Use -Dtarget to indicate target platform").dependOn(&get_v8_lib.step); const build_lyon = lyon.BuildStep.create(b, ctx.target); b.step("lyon", "Builds rust lib with cargo and copies to lib/extras/prebuilt").dependOn(&build_lyon.step); { const step = b.addLog("", .{}); if (builtin.os.tag == .macos and target.getOsTag() == .macos and !target.isNativeOs()) { const gen_mac_libc = GenMacLibCStep.create(b, target); step.step.dependOn(&gen_mac_libc.step); } const test_exe = ctx.createTestExeStep(); step.step.dependOn(&test_exe.step); const test_install = ctx.addInstallArtifact(test_exe); step.step.dependOn(&test_install.step); b.step("test-exe", "Creates the test exe.").dependOn(&step.step); } { const step = b.addLog("", .{}); if (builtin.os.tag == .macos and target.getOsTag() == .macos and !target.isNativeOs()) { const gen_mac_libc = GenMacLibCStep.create(b, target); step.step.dependOn(&gen_mac_libc.step); } var ctx_ = ctx; ctx_.add_v8_pkg = true; ctx_.add_runtime_pkg = true; const test_exe = ctx_.createTestExeStep(); const run_test = test_exe.run(); step.step.dependOn(&run_test.step); b.step("test", "Run tests").dependOn(&step.step); } { var ctx_ = ctx; ctx_.link_net = true; ctx_.link_graphics = true; ctx_.link_audio = true; ctx_.link_v8 = true; const step = b.addLog("", .{}); if (builtin.os.tag == .macos and target.getOsTag() == .macos and !target.isNativeOs()) { const gen_mac_libc = GenMacLibCStep.create(b, target); step.step.dependOn(&gen_mac_libc.step); } step.step.dependOn(&extras_repo.step); const build_options = ctx_.createDefaultBuildOptions(); build_options.addOption([]const u8, "VersionName", VersionName); const test_exe = ctx_.createTestFileStep("test/behavior_test.zig", build_options); // Set filter so it doesn't run other unit tests (which assume to be linked with lib_mock.zig) test_exe.setFilter("behavior:"); step.step.dependOn(&test_exe.step); b.step("test-behavior", "Run behavior tests").dependOn(&step.step); } const test_file = ctx.createTestFileStep(ctx.path, null); b.step("test-file", "Test file with -Dpath").dependOn(&test_file.step); { const step = b.addLog("", .{}); const build_exe = ctx.createBuildExeStep(null); step.step.dependOn(&build_exe.step); step.step.dependOn(&ctx.addInstallArtifact(build_exe).step); b.step("exe", "Build exe with main file at -Dpath").dependOn(&step.step); } { const step = b.addLog("", .{}); const build_exe = ctx.createBuildExeStep(null); step.step.dependOn(&build_exe.step); step.step.dependOn(&ctx.addInstallArtifact(build_exe).step); const run_exe = build_exe.run(); run_exe.addArgs(args); step.step.dependOn(&run_exe.step); b.step("run", "Run with main file at -Dpath").dependOn(&step.step); } const build_lib = ctx.createBuildLibStep(); b.step("lib", "Build lib with main file at -Dpath").dependOn(&build_lib.step); { const step = b.step("openssl", "Build openssl."); const crypto = try ssl.createCrypto(b, target, mode); step.dependOn(&ctx.addInstallArtifact(crypto).step); const ssl_ = try ssl.createSsl(b, target, mode); step.dependOn(&ctx.addInstallArtifact(ssl_).step); } { var ctx_ = ctx; ctx_.target = .{ .cpu_arch = .wasm32, .os_tag = .freestanding, .abi = .musl, }; const build_wasm = ctx_.createBuildWasmBundleStep(ctx_.path); b.step("wasm", "Build wasm bundle with main file at -Dpath").dependOn(&build_wasm.step); } { const step = b.addLog("", .{}); var ctx_ = ctx; ctx_.target = .{ .cpu_arch = .wasm32, .os_tag = .freestanding, .abi = .musl, }; const counter = ctx_.createBuildWasmBundleStep("ui/examples/counter.zig"); step.step.dependOn(&counter.step); const converter = ctx_.createBuildWasmBundleStep("ui/examples/converter.zig"); step.step.dependOn(&converter.step); const timer = ctx_.createBuildWasmBundleStep("ui/examples/timer.zig"); step.step.dependOn(&timer.step); const crud = ctx_.createBuildWasmBundleStep("ui/examples/crud.zig"); step.step.dependOn(&crud.step); b.step("wasm-examples", "Builds all the wasm examples.").dependOn(&step.step); } const get_version = b.addLog("{s}", .{getVersionString(is_official_build)}); b.step("version", "Get the build version.").dependOn(&get_version.step); { var ctx_ = ctx; ctx_.link_net = false; ctx_.link_graphics = false; ctx_.link_lyon = false; ctx_.link_audio = false; ctx_.add_v8_pkg = true; ctx_.link_v8 = false; ctx_.link_mock = true; ctx_.path = "tools/gen.zig"; const build_options = ctx.createDefaultBuildOptions(); build_options.addOption([]const u8, "VersionName", VersionName); build_options.addOption([]const u8, "BuildRoot", b.build_root); const exe = ctx_.createBuildExeStep(build_options); ctx_.buildLinkMock(exe); const run = exe.run(); run.addArgs(args); b.step("gen", "Generate tool.").dependOn(&run.step); } { var ctx_ = ctx; ctx_.link_net = true; ctx_.link_graphics = true; ctx_.link_audio = true; ctx_.link_v8 = true; ctx_.path = "runtime/main.zig"; const step = b.addLog("", .{}); if (builtin.os.tag == .macos and target.getOsTag() == .macos and !target.isNativeOs()) { const gen_mac_libc = GenMacLibCStep.create(b, target); step.step.dependOn(&gen_mac_libc.step); } step.step.dependOn(&extras_repo.step); const build_options = ctx_.createDefaultBuildOptions(); build_options.addOption([]const u8, "VersionName", VersionName); const run = ctx_.createBuildExeStep(build_options).run(); run.addArgs(&.{ "test", "test/js/test.js" }); // run.addArgs(&.{ "test", "test/load-test/cs-https-request-test.js" }); step.step.dependOn(&run.step); b.step("test-cosmic-js", "Test cosmic js").dependOn(&step.step); } var build_cosmic = b.addLog("", .{}); { const build_options = ctx.createDefaultBuildOptions(); build_options.addOption([]const u8, "VersionName", getVersionString(is_official_build)); var ctx_ = ctx; ctx_.link_net = true; ctx_.link_graphics = true; ctx_.link_audio = true; ctx_.link_v8 = true; ctx_.add_runtime_pkg = true; ctx_.path = "runtime/main.zig"; const step = build_cosmic; if (builtin.os.tag == .macos and target.getOsTag() == .macos and !target.isNativeOs()) { const gen_mac_libc = GenMacLibCStep.create(b, target); step.step.dependOn(&gen_mac_libc.step); } step.step.dependOn(&extras_repo.step); const exe = ctx_.createBuildExeStep(build_options); const exe_install = ctx_.addInstallArtifact(exe); step.step.dependOn(&exe_install.step); b.step("cosmic", "Build cosmic.").dependOn(&step.step); } { var step = b.addLog("", .{}); var ctx_ = ctx; ctx_.link_net = true; ctx_.link_graphics = true; ctx_.link_audio = true; ctx_.link_v8 = true; ctx_.path = "runtime/main.zig"; if (builtin.os.tag == .macos and target.getOsTag() == .macos and !target.isNativeOs()) { const gen_mac_libc = GenMacLibCStep.create(b, target); step.step.dependOn(&gen_mac_libc.step); } step.step.dependOn(&extras_repo.step); const exe = ctx_.createBuildExeStep(null); const exe_install = ctx_.addInstallArtifact(exe); step.step.dependOn(&exe_install.step); const run = exe.run(); run.addArgs(&.{ "shell" }); step.step.dependOn(&run.step); b.step("cosmic-shell", "Run cosmic in shell mode.").dependOn(&step.step); } // Whitelist test is useful for running tests that were manually included with an INCLUDE prefix. const whitelist_test = ctx.createTestExeStep(); whitelist_test.setFilter("INCLUDE"); b.step("whitelist-test", "Tests with INCLUDE in name").dependOn(&whitelist_test.run().step); // b.default_step.dependOn(&build_cosmic.step); } const BuilderContext = struct { const Self = @This(); builder: *std.build.Builder, path: []const u8, filter: []const u8, enable_tracy: bool, link_graphics: bool, // For testing, benchmarks. link_lyon: bool, link_tess2: bool = false, link_audio: bool, add_v8_pkg: bool = false, add_runtime_pkg: bool = false, link_v8: bool, link_net: bool, link_mock: bool, mode: std.builtin.Mode, target: std.zig.CrossTarget, // This is only used to detect running a linux binary in WSL. wsl: bool = false, fn fromRoot(self: *Self, path: []const u8) []const u8 { return self.builder.pathFromRoot(path); } fn setOutputDir(self: *Self, obj: *LibExeObjStep, name: []const u8) void { const output_dir = self.fromRoot(self.builder.fmt("zig-out/{s}", .{ name })); obj.setOutputDir(output_dir); } fn createBuildLibStep(self: *Self) *LibExeObjStep { const basename = std.fs.path.basename(self.path); const i = std.mem.indexOf(u8, basename, ".zig") orelse basename.len; const name = basename[0..i]; const step = self.builder.addSharedLibrary(name, self.path, .unversioned); self.setBuildMode(step); self.setTarget(step); self.setOutputDir(step, name); self.addDeps(step) catch unreachable; return step; } /// Similar to createBuildLibStep except we also copy over index.html and required js libs. fn createBuildWasmBundleStep(self: *Self, path: []const u8) *LibExeObjStep { const basename = std.fs.path.basename(path); const i = std.mem.indexOf(u8, basename, ".zig") orelse basename.len; const name = basename[0..i]; const step = self.builder.addSharedLibrary(name, path, .unversioned); // const step = self.builder.addStaticLibrary(name, path); self.setBuildMode(step); self.setTarget(step); self.addDeps(step) catch unreachable; _ = self.addInstallArtifact(step); // This is needed for wasm builds or the main .wasm file won't output to the custom directory. self.setOutputDir(step, step.install_step.?.dest_dir.custom); self.copyAssets(step); // Create copy of index.html. var cp = CopyFileStep.create(self.builder, self.fromRoot("./lib/wasm-js/index.html"), self.fromRoot("./lib/wasm-js/gen-index.html")); step.step.dependOn(&cp.step); // Replace wasm file name in gen-index.html const index_path = self.fromRoot("./lib/wasm-js/gen-index.html"); const new_str = std.mem.concat(self.builder.allocator, u8, &.{ "wasmFile = '", name, ".wasm'" }) catch unreachable; const replace = ReplaceInFileStep.create(self.builder, index_path, "wasmFile = 'demo.wasm'", new_str); step.step.dependOn(&replace.step); // Install gen-index.html const install_index = self.addStepInstallFile(step, srcPath() ++ "/lib/wasm-js/gen-index.html", "index.html"); step.step.dependOn(&install_index.step); // graphics.js // const install_graphics = self.addStepInstallFile(step, srcPath() ++ "/lib/wasm-js/graphics-canvas.js", "graphics.js"); const install_graphics = self.addStepInstallFile(step, srcPath() ++ "/lib/wasm-js/graphics-webgl2.js", "graphics.js"); step.step.dependOn(&install_graphics.step); // stdx.js const install_stdx = self.addStepInstallFile(step, srcPath() ++ "/lib/wasm-js/stdx.js", "stdx.js"); step.step.dependOn(&install_stdx.step); return step; } /// dst_rel_path is relative to the step's custom dest directory. fn addStepInstallFile(self: *Self, step: *LibExeObjStep, src_path: []const u8, dst_rel_path: []const u8) *std.build.InstallFileStep { return self.builder.addInstallFile(.{ .path = src_path }, self.builder.fmt("{s}/{s}", .{step.install_step.?.dest_dir.custom, dst_rel_path})); } fn copyAssets(self: *Self, step: *LibExeObjStep) void { if (self.path.len == 0) { return; } if (!std.mem.endsWith(u8, self.path, ".zig")) { return; } const assets_file = self.builder.fmt("{s}_assets.txt", .{self.path[0..self.path.len-4]}); const assets = std.fs.cwd().readFileAlloc(self.builder.allocator, assets_file, 1e12) catch return; var iter = std.mem.tokenize(u8, assets, "\n"); while (iter.next()) |path| { const basename = std.fs.path.basename(path); const src_path = self.builder.fmt("{s}{s}", .{srcPath(), path}); const install_file = self.addStepInstallFile(step, src_path, basename); step.step.dependOn(&install_file.step); } } fn joinResolvePath(self: *Self, paths: []const []const u8) []const u8 { return std.fs.path.join(self.builder.allocator, paths) catch unreachable; } fn getSimpleTriple(b: *Builder, target: std.zig.CrossTarget) []const u8 { return target.toTarget().linuxTriple(b.allocator) catch unreachable; } fn addInstallArtifact(self: *Self, artifact: *LibExeObjStep) *std.build.InstallArtifactStep { const triple = getSimpleTriple(self.builder, artifact.target); if (artifact.kind == .exe or artifact.kind == .test_exe) { const basename = std.fs.path.basename(artifact.root_src.?.path); const i = std.mem.indexOf(u8, basename, ".zig") orelse basename.len; const name = basename[0..i]; const path = self.builder.fmt("{s}/{s}", .{ triple, name }); artifact.override_dest_dir = .{ .custom = path }; } else if (artifact.kind == .lib) { const path = self.builder.fmt("{s}/{s}", .{ triple, artifact.name }); artifact.override_dest_dir = .{ .custom = path }; } return self.builder.addInstallArtifact(artifact); } fn createBuildExeStep(self: *Self, options_step: ?*std.build.OptionsStep) *LibExeObjStep { const basename = std.fs.path.basename(self.path); const i = std.mem.indexOf(u8, basename, ".zig") orelse basename.len; const name = basename[0..i]; const exe = self.builder.addExecutable(name, self.path); self.setBuildMode(exe); self.setTarget(exe); exe.setMainPkgPath("."); const opts_step = options_step orelse self.createDefaultBuildOptions(); const pkg = opts_step.getPackage("build_options"); exe.addPackage(pkg); const graphics_backend = backend.getGraphicsBackend(exe); opts_step.addOption(backend.GraphicsBackend, "GraphicsBackend", graphics_backend); self.addDeps(exe) catch unreachable; if (self.enable_tracy) { self.linkTracy(exe); } _ = self.addInstallArtifact(exe); self.copyAssets(exe); return exe; } fn createTestFileStep(self: *Self, path: []const u8, build_options: ?*std.build.OptionsStep) *std.build.LibExeObjStep { const step = self.builder.addTest(path); self.setBuildMode(step); self.setTarget(step); step.setMainPkgPath("."); self.addDeps(step) catch unreachable; const build_opts = build_options orelse self.createDefaultBuildOptions(); step.addPackage(build_opts.getPackage("build_options")); build_opts.addOption(backend.GraphicsBackend, "GraphicsBackend", .Test); self.postStep(step); return step; } fn createTestExeStep(self: *Self) *std.build.LibExeObjStep { const step = self.builder.addTestExe("main_test", "./test/main_test.zig"); self.setBuildMode(step); self.setTarget(step); // This fixes test files that import above, eg. @import("../foo") step.setMainPkgPath("."); // Add external lib headers but link with mock lib. self.addDeps(step) catch unreachable; self.buildLinkMock(step); // Add build_options at root since the main test file references src paths instead of package names. const build_opts = self.createDefaultBuildOptions(); build_opts.addOption(backend.GraphicsBackend, "GraphicsBackend", .Test); build_opts.addOption([]const u8, "VersionName", VersionName); step.addPackage(build_opts.getPackage("build_options")); self.postStep(step); return step; } fn postStep(self: *Self, step: *std.build.LibExeObjStep) void { if (self.enable_tracy) { self.linkTracy(step); } if (self.filter.len > 0) { step.setFilter(self.filter); } } fn isWasmTarget(self: Self) bool { return self.target.getCpuArch() == .wasm32 or self.target.getCpuArch() == .wasm64; } fn addDeps(self: *Self, step: *LibExeObjStep) !void { const graphics_backend = backend.getGraphicsBackend(step); stdx.addPackage(step, .{ .enable_tracy = self.enable_tracy, }); platform.addPackage(step, .{ .graphics_backend = graphics_backend, .add_dep_pkgs = false, }); curl.addPackage(step); uv.addPackage(step); h2o.addPackage(step); ssl.addPackage(step); if (self.link_net) { ssl.buildAndLinkCrypto(step, .{ .lib_path = LibCryptoPath }); ssl.buildAndLinkSsl(step, .{ .lib_path = LibSslPath }); curl.buildAndLink(step, .{ .lib_path = LibCurlPath }); http2.buildAndLink(step); zlib.buildAndLink(step); uv.buildAndLink(step, .{ .lib_path = LibUvPath }); h2o.buildAndLink(step, .{ .lib_path = LibH2oPath }); } sdl.addPackage(step); stb.addStbttPackage(step); stb.addStbiPackage(step); freetype.addPackage(step); gl.addPackage(step); vk.addPackage(step); maudio.addPackage(step); lyon.addPackage(step, self.link_lyon); tess2.addPackage(step, self.link_tess2); if (self.target.getOsTag() == .macos) { self.buildLinkMacSys(step); } if (self.target.getOsTag() == .windows and self.target.getAbi() == .gnu) { mingw.buildExtra(step); mingw.buildAndLinkWinPosix(step); mingw.buildAndLinkWinPthreads(step); } ui.addPackage(step, .{ .graphics_backend = graphics_backend, .add_dep_pkgs = false, }); const graphics_opts = graphics.Options{ .graphics_backend = graphics_backend, .enable_tracy = self.enable_tracy, .link_lyon = self.link_lyon, .link_tess2 = self.link_tess2, .sdl_lib_path = LibSdlPath, .add_dep_pkgs = false, }; cgltf.addPackage(step); graphics.addPackage(step, graphics_opts); if (self.link_graphics) { graphics.buildAndLink(step, graphics_opts); } if (self.link_audio) { maudio.buildAndLink(step); } if (self.add_v8_pkg or self.link_v8) { // Only add zig-v8 package when this flag is set to let unrelated builds continue. eg. graphics/ui examples. // Must dependOn before adding the zig-v8 package. const zig_v8_repo = GitRepoStep.create(self.builder, .{ .url = "https://github.com/fubark/zig-v8", .branch = ZIG_V8_BRANCH, .sha = ZIG_V8_SHA, .path = srcPath() ++ "/lib/zig-v8", }); step.step.dependOn(&zig_v8_repo.step); addZigV8(step); } if (self.add_runtime_pkg) { runtime.addPackage(step, .{ .graphics_backend = graphics_backend, .link_lyon = self.link_lyon, .link_tess2 = self.link_tess2, .add_dep_pkgs = false, }); } if (self.link_v8) { self.linkZigV8(step); } if (self.link_mock) { self.buildLinkMock(step); } } fn setBuildMode(self: *Self, step: *std.build.LibExeObjStep) void { step.setBuildMode(self.mode); if (self.mode == .ReleaseSafe) { step.strip = true; } } fn setTarget(self: *Self, step: *std.build.LibExeObjStep) void { var target = self.target; if (target.os_tag == null) { // Native if (builtin.target.os.tag == .linux and self.enable_tracy) { // tracy seems to require glibc 2.18, only override if less. target = std.zig.CrossTarget.fromTarget(builtin.target); const min_ver = std.zig.CrossTarget.SemVer.parse("2.18") catch unreachable; if (std.zig.CrossTarget.SemVer.order(target.glibc_version.?, min_ver) == .lt) { target.glibc_version = min_ver; } } } step.setTarget(target); } fn createDefaultBuildOptions(self: Self) *std.build.OptionsStep { const build_options = self.builder.addOptions(); build_options.addOption(bool, "enable_tracy", self.enable_tracy); build_options.addOption(bool, "has_lyon", self.link_lyon); build_options.addOption(bool, "has_tess2", self.link_tess2); return build_options; } fn linkTracy(self: *Self, step: *std.build.LibExeObjStep) void { const path = "lib/tracy"; const client_cpp = std.fs.path.join( self.builder.allocator, &[_][]const u8{ path, "TracyClient.cpp" }, ) catch unreachable; const tracy_c_flags: []const []const u8 = &[_][]const u8{ "-DTRACY_ENABLE=1", "-fno-sanitize=undefined", // "-DTRACY_NO_EXIT=1" }; step.addIncludeDir(path); step.addCSourceFile(client_cpp, tracy_c_flags); step.linkSystemLibraryName("c++"); step.linkLibC(); // if (target.isWindows()) { // step.linkSystemLibrary("dbghelp"); // step.linkSystemLibrary("ws2_32"); // } } fn buildLinkMacSys(self: *Self, step: *LibExeObjStep) void { const lib = self.builder.addStaticLibrary("mac_sys", null); lib.setTarget(self.target); lib.setBuildMode(self.mode); lib.addCSourceFile("./lib/sys/mac_sys.c", &.{}); if (self.target.isNativeOs()) { // Force using native headers or it'll compile with ___darwin_check_fd_set_overflow references. lib.linkFramework("CoreServices"); } else { lib.setLibCFile(std.build.FileSource.relative("./lib/macos.libc")); } step.linkLibrary(lib); } fn addCSourceFileFmt(self: *Self, lib: *LibExeObjStep, comptime format: []const u8, args: anytype, c_flags: []const []const u8) void { const path = std.fmt.allocPrint(self.builder.allocator, format, args) catch unreachable; lib.addCSourceFile(self.fromRoot(path), c_flags); } fn linkZigV8(self: *Self, step: *LibExeObjStep) void { const path = getV8_StaticLibPath(self.builder, step.target); step.addAssemblyFile(path); step.linkLibCpp(); step.linkLibC(); if (self.target.getOsTag() == .linux) { step.linkSystemLibrary("unwind"); } else if (self.target.getOsTag() == .windows and self.target.getAbi() == .gnu) { step.linkSystemLibrary("winmm"); step.linkSystemLibrary("dbghelp"); } } fn buildLinkMock(self: *Self, step: *LibExeObjStep) void { const lib = self.builder.addStaticLibrary("mock", self.fromRoot("./test/lib_mock.zig")); lib.setTarget(self.target); lib.setBuildMode(self.mode); stdx.addPackage(lib, .{ .enable_tracy = self.enable_tracy, }); gl.addPackage(lib); uv.addPackage(lib); addZigV8(lib); maudio.addPackage(lib); step.linkLibrary(lib); } }; pub const zig_v8_pkg = Pkg{ .name = "v8", .source = FileSource.relative("./lib/zig-v8/src/v8.zig"), }; fn addZigV8(step: *LibExeObjStep) void { step.addPackage(zig_v8_pkg); step.linkLibC(); step.addIncludeDir("./lib/zig-v8/src"); } const GenMacLibCStep = struct { const Self = @This(); step: std.build.Step, b: *Builder, target: std.zig.CrossTarget, fn create(b: *Builder, target: std.zig.CrossTarget) *Self { const new = b.allocator.create(Self) catch unreachable; new.* = .{ .step = std.build.Step.init(.custom, b.fmt("gen-mac-libc", .{}), b.allocator, make), .b = b, .target = target, }; return new; } fn make(step: *std.build.Step) anyerror!void { const self = @fieldParentPtr(Self, "step", step); const path = try std.fs.path.resolve(self.b.allocator, &.{ self.b.sysroot.?, "usr/include"}); const libc_file = self.b.fmt( \\include_dir={s} \\sys_include_dir={s} \\crt_dir= \\msvc_lib_dir= \\kernel32_lib_dir= \\gcc_dir= , .{ path, path }, ); try std.fs.cwd().writeFile("./lib/macos.libc", libc_file); } }; const MakePathStep = struct { const Self = @This(); step: std.build.Step, b: *Builder, path: []const u8, fn create(b: *Builder, root_path: []const u8) *Self { const new = b.allocator.create(Self) catch unreachable; new.* = .{ .step = std.build.Step.init(.custom, b.fmt("make-path", .{}), b.allocator, make), .b = b, .path = root_path, }; return new; } fn make(step: *std.build.Step) anyerror!void { const self = @fieldParentPtr(Self, "step", step); std.fs.cwd().access(self.path, .{ .mode = .read_only }) catch |err| switch (err) { error.FileNotFound => { try self.b.makePath(self.path); }, else => {}, }; } }; const CopyFileStep = struct { const Self = @This(); step: std.build.Step, b: *Builder, src_path: []const u8, dst_path: []const u8, fn create(b: *Builder, src_path: []const u8, dst_path: []const u8) *Self { const new = b.allocator.create(Self) catch unreachable; new.* = .{ .step = std.build.Step.init(.custom, b.fmt("cp", .{}), b.allocator, make), .b = b, .src_path = src_path, .dst_path = dst_path, }; return new; } fn make(step: *std.build.Step) anyerror!void { const self = @fieldParentPtr(Self, "step", step); try std.fs.copyFileAbsolute(self.src_path, self.dst_path, .{}); } }; const ReplaceInFileStep = struct { const Self = @This(); step: std.build.Step, b: *Builder, path: []const u8, old_str: []const u8, new_str: []const u8, fn create(b: *Builder, path: []const u8, old_str: []const u8, new_str: []const u8) *Self { const new = b.allocator.create(Self) catch unreachable; new.* = .{ .step = std.build.Step.init(.custom, b.fmt("replace_in_file", .{}), b.allocator, make), .b = b, .path = path, .old_str = old_str, .new_str = new_str, }; return new; } fn make(step: *std.build.Step) anyerror!void { const self = @fieldParentPtr(Self, "step", step); const file = std.fs.openFileAbsolute(self.path, .{ .mode = .read_only }) catch unreachable; errdefer file.close(); const source = file.readToEndAllocOptions(self.b.allocator, 1024 * 1000 * 10, null, @alignOf(u8), 0) catch unreachable; defer self.b.allocator.free(source); const new_source = std.mem.replaceOwned(u8, self.b.allocator, source, self.old_str, self.new_str) catch unreachable; file.close(); const write = std.fs.openFileAbsolute(self.path, .{ .mode = .write_only }) catch unreachable; defer write.close(); write.writeAll(new_source) catch unreachable; } }; fn createGetV8LibStep(b: *Builder, target: std.zig.CrossTarget) *std.build.LogStep { const step = b.addLog("Get V8 Lib\n", .{}); const url = getV8_StaticLibGithubUrl(b.allocator, ZIG_V8_BRANCH, target); // log.debug("Url: {s}", .{url}); const lib_path = getV8_StaticLibPath(b, target); if (builtin.os.tag == .windows) { var sub_step = b.addSystemCommand(&.{ "powershell", "Invoke-WebRequest", "-Uri", url, "-OutFile", lib_path }); step.step.dependOn(&sub_step.step); } else { var sub_step = b.addSystemCommand(&.{ "curl", "-L", url, "-o", lib_path }); step.step.dependOn(&sub_step.step); } return step; } fn getV8_StaticLibGithubUrl(alloc: std.mem.Allocator, tag: []const u8, target: std.zig.CrossTarget) []const u8 { const lib_name: []const u8 = if (target.getOsTag() == .windows) "c_v8" else "libc_v8"; const lib_ext: []const u8 = if (target.getOsTag() == .windows) "lib" else "a"; if (target.getCpuArch() == .aarch64 and target.getOsTag() == .macos) { return std.fmt.allocPrint(alloc, "https://github.com/fubark/zig-v8/releases/download/{s}/{s}_{s}-{s}-gnu_{s}_{s}.{s}", .{ tag, lib_name, @tagName(target.getCpuArch()), @tagName(target.getOsTag()), "release", tag, lib_ext, }) catch unreachable; } else if (target.getOsTag() == .windows) { return std.fmt.allocPrint(alloc, "https://github.com/fubark/zig-v8/releases/download/{s}/{s}_{s}-{s}-gnu_{s}_{s}.{s}", .{ tag, lib_name, @tagName(target.getCpuArch()), @tagName(target.getOsTag()), "release", tag, lib_ext, }) catch unreachable; } else { return std.fmt.allocPrint(alloc, "https://github.com/fubark/zig-v8/releases/download/{s}/{s}_{s}-{s}-gnu_{s}_{s}.{s}", .{ tag, lib_name, @tagName(target.getCpuArch()), @tagName(target.getOsTag()), "release", tag, lib_ext, }) catch unreachable; } } fn getV8_StaticLibPath(b: *Builder, target: std.zig.CrossTarget) []const u8 { if (LibV8Path) |path| { return path; } const lib_name: []const u8 = if (target.getOsTag() == .windows) "c_v8" else "libc_v8"; const lib_ext: []const u8 = if (target.getOsTag() == .windows) "lib" else "a"; const triple = BuilderContext.getSimpleTriple(b, target); const path = std.fmt.allocPrint(b.allocator, "./lib/{s}-{s}.{s}", .{ lib_name, triple, lib_ext }) catch unreachable; return b.pathFromRoot(path); } fn syncRepo(b: *Builder, step: *std.build.Step, rel_path: []const u8, remote_url: []const u8, revision: []const u8, is_tag: bool) !void { const repo_path = b.pathFromRoot(rel_path); if ((try statPath(repo_path)) == .NotExist) { _ = try b.execFromStep(&.{ "git", "clone", remote_url, repo_path }, step); _ = try b.execFromStep(&.{ "git", "-C", repo_path, "checkout", revision }, step); } else { var cur_revision: []const u8 = undefined; if (is_tag) { cur_revision = try b.execFromStep(&.{ "git", "-C", repo_path, "describe", "--tags" }, step); } else { cur_revision = try b.execFromStep(&.{ "git", "-C", repo_path, "rev-parse", "HEAD" }, step); } if (cur_revision.len < revision.len or !std.mem.eql(u8, cur_revision[0..revision.len], revision)) { // Fetch and checkout. // Need -f or it will fail if the remote tag now points to a different revision. _ = try b.execFromStep(&.{ "git", "-C", repo_path, "fetch", "--tags", "-f" }, step); _ = try b.execFromStep(&.{ "git", "-C", repo_path, "checkout", revision }, step); } } } const PathStat = enum { NotExist, Directory, File, SymLink, Unknown, }; fn statPath(path_abs: []const u8) !PathStat { const file = std.fs.openFileAbsolute(path_abs, .{ .mode = .read_only }) catch |err| { if (err == error.FileNotFound) { return .NotExist; } else if (err == error.IsDir) { return .Directory; } else { return err; } }; defer file.close(); const stat = try file.stat(); switch (stat.kind) { .SymLink => return .SymLink, .Directory => return .Directory, .File => return .File, else => return .Unknown, } } fn getVersionString(is_official_build: bool) []const u8 { if (is_official_build) { return VersionName; } else { return VersionName ++ "-Dev"; } } fn srcPath() []const u8 { return (std.fs.path.dirname(@src().file) orelse unreachable); } fn fromRoot(b: *std.build.Builder, rel_path: []const u8) []const u8 { return std.fs.path.resolve(b.allocator, &.{ srcPath(), rel_path }) catch unreachable; }
build.zig