Unnamed: 0
int64 0
0
| repo_id
stringlengths 5
186
| file_path
stringlengths 15
223
| content
stringlengths 1
32.8M
⌀ |
---|---|---|---|
0 | repos/vite-plugin-zig/examples | repos/vite-plugin-zig/examples/vite-zig-project/dynamic_import_instantiate.js | const { exports, instance, module } = await import(
'./src/main.zig?instantiate'
);
// call exported functions from the exports object
console.log(exports.add(5, 37)); // 42
console.debug({ exports, instance, module });
|
0 | repos/vite-plugin-zig/examples | repos/vite-plugin-zig/examples/vite-zig-project/package.json | {
"name": "vite-zig-project",
"private": true,
"version": "0.0.0",
"type": "module",
"scripts": {
"dev": "vite",
"build": "vite build",
"preview": "vite preview"
},
"devDependencies": {
"vite": "^5.2.0",
"vite-plugin-inspect": "^0.8.4",
"vite-plugin-zig": "workspace:*"
}
}
|
0 | repos/vite-plugin-zig/examples | repos/vite-plugin-zig/examples/vite-zig-project/static_import.js | import { instantiate, module } from './src/main.zig';
// pass any custom importObject here, functions should be declared
// as extern in the Zig file
const importObject = {
// ...
};
// instantiate the compiled WebAssembly module, can also be moved
// to a Worker for instantiation in another thread
const { exports, instance } = await instantiate(importObject);
// call exported functions from the exports object
console.log(exports.add(5, 37)); // 42
console.debug({ exports, instance, module });
|
0 | repos/vite-plugin-zig/examples | repos/vite-plugin-zig/examples/vite-zig-project/style.css | :root {
font-family: Inter, system-ui, Avenir, Helvetica, Arial, sans-serif;
line-height: 1.5;
font-weight: 400;
color-scheme: light dark;
color: rgba(255, 255, 255, 0.87);
background-color: #242424;
font-synthesis: none;
text-rendering: optimizeLegibility;
-webkit-font-smoothing: antialiased;
-moz-osx-font-smoothing: grayscale;
}
a {
font-weight: 500;
color: #646cff;
text-decoration: inherit;
}
a:hover {
color: #535bf2;
}
body {
margin: 0;
display: flex;
place-items: center;
min-width: 320px;
min-height: 100vh;
}
h1 {
font-size: 3.2em;
line-height: 1.1;
}
#app {
max-width: 1280px;
margin: 0 auto;
padding: 2rem;
text-align: center;
}
.logo {
height: 6em;
padding: 1.5em;
will-change: filter;
transition: filter 300ms;
}
.logo:hover {
filter: drop-shadow(0 0 2em #646cffaa);
}
.logo.vanilla:hover {
filter: drop-shadow(0 0 2em #f7df1eaa);
}
.card {
padding: 2em;
}
.read-the-docs {
color: #888;
}
button {
border-radius: 8px;
border: 1px solid transparent;
padding: 0.6em 1.2em;
font-size: 1em;
font-weight: 500;
font-family: inherit;
background-color: #1a1a1a;
cursor: pointer;
transition: border-color 0.25s;
}
button:hover {
border-color: #646cff;
}
button:focus,
button:focus-visible {
outline: 4px auto -webkit-focus-ring-color;
}
@media (prefers-color-scheme: light) {
:root {
color: #213547;
background-color: #ffffff;
}
a:hover {
color: #747bff;
}
button {
background-color: #f9f9f9;
}
}
|
0 | repos/vite-plugin-zig/examples | repos/vite-plugin-zig/examples/vite-zig-project/static_import_instantiate.js | import { exports, instance, module } from './src/main.zig?instantiate';
// call exported functions from the exports object
console.log(exports.add(5, 37)); // 42
console.debug({ exports, instance, module });
|
0 | repos/vite-plugin-zig/examples | repos/vite-plugin-zig/examples/vite-zig-project/module.js | export const add = a => b => a + b;
|
0 | repos/vite-plugin-zig/examples | repos/vite-plugin-zig/examples/vite-zig-project/counter.js | export function setupCounter(element) {
let counter = 0
const setCounter = (count) => {
counter = count
element.innerHTML = `count is ${counter}`
}
element.addEventListener('click', () => setCounter(counter + 1))
setCounter(0)
}
|
0 | repos/vite-plugin-zig/examples | repos/vite-plugin-zig/examples/vite-zig-project/main.js | import './style.css';
import javascriptLogo from './javascript.svg';
import viteLogo from '/vite.svg';
import { setupCounter } from './counter.js';
document.querySelector('#app').innerHTML = `
<div>
<a href="https://vitejs.dev" target="_blank">
<img src="${viteLogo}" class="logo" alt="Vite logo" />
</a>
<a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript" target="_blank">
<img src="${javascriptLogo}" class="logo vanilla" alt="JavaScript logo" />
</a>
<h1>Hello Vite!</h1>
<div class="card">
<button id="counter" type="button"></button>
</div>
<p class="read-the-docs">
Click on the Vite logo to learn more
</p>
</div>
`;
setupCounter(document.querySelector('#counter'));
const { add } = await import('./module.js');
console.log(add(5)(37));
// test cases
import './static_import';
import './static_import_instantiate';
import './dynamic_import';
import './dynamic_import_instantiate';
|
0 | repos/vite-plugin-zig/examples | repos/vite-plugin-zig/examples/vite-zig-project/vite.config.js | import inspect from 'vite-plugin-inspect';
import zig from 'vite-plugin-zig';
/** @type {import('vite').UserConfig} */
export default {
plugins: [zig(), inspect()],
build: { target: 'esnext' },
};
|
0 | repos/vite-plugin-zig/examples | repos/vite-plugin-zig/examples/vite-zig-project/index.html | <!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<link rel="icon" type="image/svg+xml" href="/vite.svg" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Vite App</title>
</head>
<body>
<div id="app"></div>
<script type="module" src="/main.js"></script>
</body>
</html>
|
0 | repos/vite-plugin-zig/examples | repos/vite-plugin-zig/examples/vite-zig-project/dynamic_import.js | const { instantiate, module } = await import('./src/main.zig');
// pass any custom importObject here, functions should be declared
// as extern in the Zig file
const importObject = {
// ...
};
// instantiate the compiled WebAssembly module, can also be moved
// to a Worker for instantiation in another thread
const { exports, instance } = await instantiate(importObject);
// call exported functions from the exports object
console.log(exports.add(5, 37)); // 42
console.debug({ exports, instance, module });
|
0 | repos/vite-plugin-zig/examples/vite-zig-project | repos/vite-plugin-zig/examples/vite-zig-project/src/main.zig | const std = @import("std");
const testing = std.testing;
export fn add(a: i32, b: i32) i32 {
return a + b;
}
test "basic add functionality" {
try testing.expect(add(3, 7) == 10);
}
|
0 | repos/vite-plugin-zig/examples | repos/vite-plugin-zig/examples/svelte-kit-zig-project/package.json | {
"name": "svelte-kit-zig-project",
"version": "0.0.1",
"private": true,
"scripts": {
"dev": "vite dev",
"build": "vite build",
"preview": "vite preview"
},
"devDependencies": {
"@sveltejs/adapter-static": "^3.0.2",
"@sveltejs/kit": "^2.0.0",
"@sveltejs/vite-plugin-svelte": "^3.0.0",
"svelte": "^4.2.7",
"vite": "^5.0.3",
"vite-plugin-zig": "workspace:*"
},
"type": "module"
}
|
0 | repos/vite-plugin-zig/examples | repos/vite-plugin-zig/examples/svelte-kit-zig-project/README.md | # svelte-kit-zig-project
Everything you need to build a Svelte project, powered by [`create-svelte`](https://github.com/sveltejs/kit/tree/main/packages/create-svelte).
## Creating a project
If you're seeing this, you've probably already done this step. Congrats!
```bash
# create a new project in the current directory
npm create svelte@latest
# create a new project in my-app
npm create svelte@latest my-app
```
## Developing
Once you've created a project and installed dependencies with `npm install` (or `pnpm install` or `yarn`), start a development server:
```bash
npm run dev
# or start the server and open the app in a new browser tab
npm run dev -- --open
```
## Building
To create a production version of your app:
```bash
npm run build
```
You can preview the production build with `npm run preview`.
> To deploy your app, you may need to install an [adapter](https://kit.svelte.dev/docs/adapters) for your target environment.
|
0 | repos/vite-plugin-zig/examples | repos/vite-plugin-zig/examples/svelte-kit-zig-project/vite.config.js | import { sveltekit } from '@sveltejs/kit/vite';
import { defineConfig } from 'vite';
import zig from 'vite-plugin-zig';
export default defineConfig({
plugins: [sveltekit(), zig()],
});
|
0 | repos/vite-plugin-zig/examples | repos/vite-plugin-zig/examples/svelte-kit-zig-project/svelte.config.js | import adapter from '@sveltejs/adapter-static';
/** @type {import('@sveltejs/kit').Config} */
const config = {
kit: {
// See https://kit.svelte.dev/docs/adapters for more information about adapters.
adapter: adapter(),
},
};
export default config;
|
0 | repos/vite-plugin-zig/examples/svelte-kit-zig-project | repos/vite-plugin-zig/examples/svelte-kit-zig-project/src/app.html | <!doctype html>
<html lang="en">
<head>
<meta charset="utf-8" />
<link rel="icon" href="%sveltekit.assets%/favicon.png" />
<meta name="viewport" content="width=device-width, initial-scale=1" />
%sveltekit.head%
</head>
<body data-sveltekit-preload-data="hover">
<div style="display: contents">%sveltekit.body%</div>
</body>
</html>
|
0 | repos/vite-plugin-zig/examples/svelte-kit-zig-project/src | repos/vite-plugin-zig/examples/svelte-kit-zig-project/src/lib/main.zig | const std = @import("std");
const testing = std.testing;
export fn add(a: i32, b: i32) i32 {
return a + b;
}
test "basic add functionality" {
try testing.expect(add(3, 7) == 10);
}
|
0 | repos/vite-plugin-zig/examples/svelte-kit-zig-project/src | repos/vite-plugin-zig/examples/svelte-kit-zig-project/src/routes/+page.svelte | <script>
import { onMount } from 'svelte';
onMount(async () => {
const wasm = await import('$lib/main.zig?instantiate');
await wasm.instantiated;
console.log(wasm.exports.add(5, 37)); // 42
});
</script>
<h1>Welcome to SvelteKit</h1>
<p>Visit <a href="https://kit.svelte.dev">kit.svelte.dev</a> to read the documentation</p>
|
0 | repos/vite-plugin-zig/examples/svelte-kit-zig-project/src | repos/vite-plugin-zig/examples/svelte-kit-zig-project/src/routes/+layout.js | export const prerender = true;
|
0 | repos | repos/mach-glfw/README.md | <a href="https://machengine.org/pkg/mach-glfw">
<picture>
<source media="(prefers-color-scheme: dark)" srcset="https://machengine.org/assets/mach/glfw-full-dark.svg">
<img alt="mach-glfw" src="https://machengine.org/assets/mach/glfw-full-light.svg" height="150px">
</picture>
</a>
Perfected GLFW bindings for Zig
## Features
* Zero-fuss installation, cross-compilation at the flip of a switch, and broad platform support.
* 100% API coverage. Every function, type, constant, etc. has been exposed in a ziggified API.
See also: [What does a ziggified GLFW API offer?](https://machengine.org/pkg/mach-glfw/)
## Community maintained
The [Mach engine](https://machengine.org/) project no longer uses GLFW, and so this project is now community-maintained. Pull requests are welcome and will be reviewed. The project will still target [nominated Zig versions](https://machengine.org/about/zig-version/) but may not see regular updates as it is no longer a Mach project (see [hexops/mach#1166](https://github.com/hexops/mach/issues/1166)).
Note: [hexops/glfw]()
Some old documentation is available at https://machengine.org/v0.4/pkg/mach-glfw/
|
0 | repos | repos/mach-glfw/build.zig.zon | .{
.name = "mach-glfw",
.version = "0.2.0",
.paths = .{
"src/",
"build.zig",
"build.zig.zon",
"LICENSE",
"LICENSE-APACHE",
"LICENSE-MIT",
"README.md",
},
.dependencies = .{
.glfw = .{
.url = "https://pkg.machengine.org/glfw/e6f377baed70a7bef9fa08d808f40b64c5136bf6.tar.gz",
.hash = "1220c15e66c13f9633fcfd50b5ed265f74f2950c98b1f1defd66298fa027765e0190",
},
},
}
|
0 | repos | repos/mach-glfw/build.zig | const builtin = @import("builtin");
const std = @import("std");
pub fn build(b: *std.Build) !void {
const optimize = b.standardOptimizeOption(.{});
const target = b.standardTargetOptions(.{});
var module = b.addModule("mach-glfw", .{
.target = target,
.optimize = optimize,
.root_source_file = b.path("src/main.zig"),
});
const test_step = b.step("test", "Run library tests");
const main_tests = b.addTest(.{
.name = "glfw-tests",
.root_source_file = b.path("src/main.zig"),
.target = target,
.optimize = optimize,
});
b.installArtifact(main_tests);
test_step.dependOn(&b.addRunArtifact(main_tests).step);
if (b.lazyDependency("glfw", .{
.target = target,
.optimize = optimize,
})) |dep| {
module.linkLibrary(dep.artifact("glfw"));
@import("glfw").addPaths(module);
main_tests.linkLibrary(dep.artifact("glfw"));
@import("glfw").addPaths(&main_tests.root_module);
}
}
comptime {
const supported_zig = std.SemanticVersion.parse("0.13.0-dev.351+64ef45eb0") catch unreachable;
if (builtin.zig_version.order(supported_zig) != .eq) {
@compileError(std.fmt.comptimePrint("unsupported Zig version ({}). Required Zig version 2024.5.0-mach: https://machengine.org/about/nominated-zig/#202450-mach", .{builtin.zig_version}));
}
}
|
0 | repos/mach-glfw | repos/mach-glfw/src/native.zig | //! Native access functions
const std = @import("std");
const Window = @import("Window.zig");
const Monitor = @import("Monitor.zig");
const internal_debug = @import("internal_debug.zig");
pub const BackendOptions = struct {
win32: bool = false,
wgl: bool = false,
cocoa: bool = false,
nsgl: bool = false,
x11: bool = false,
glx: bool = false,
wayland: bool = false,
egl: bool = false,
osmesa: bool = false,
};
/// This function returns a type which allows provides an interface to access
/// the native handles based on backends selected.
///
/// The available window API options are:
/// * win32
/// * cocoa
/// * x11
/// * wayland
///
/// The available context API options are:
///
/// * wgl
/// * nsgl
/// * glx
/// * egl
/// * osmesa
///
/// The chosen backends must match those the library was compiled for. Failure to do so
/// will cause a link-time error.
pub fn Native(comptime options: BackendOptions) type {
const native = @cImport({
@cDefine("GLFW_INCLUDE_VULKAN", "1");
@cDefine("GLFW_INCLUDE_NONE", "1");
if (options.win32) @cDefine("GLFW_EXPOSE_NATIVE_WIN32", "1");
if (options.wgl) @cDefine("GLFW_EXPOSE_NATIVE_WGL", "1");
if (options.cocoa) @cDefine("GLFW_EXPOSE_NATIVE_COCOA", "1");
if (options.nsgl) @cDefine("GLFW_EXPOSE_NATIVE_NGSL", "1");
if (options.x11) @cDefine("GLFW_EXPOSE_NATIVE_X11", "1");
if (options.glx) @cDefine("GLFW_EXPOSE_NATIVE_GLX", "1");
if (options.wayland) @cDefine("GLFW_EXPOSE_NATIVE_WAYLAND", "1");
if (options.egl) @cDefine("GLFW_EXPOSE_NATIVE_EGL", "1");
if (options.osmesa) @cDefine("GLFW_EXPOSE_NATIVE_OSMESA", "1");
@cDefine("__kernel_ptr_semantics", "");
@cInclude("GLFW/glfw3.h");
@cInclude("GLFW/glfw3native.h");
});
return struct {
/// Returns the adapter device name of the specified monitor.
///
/// return: The UTF-8 encoded adapter device name (for example `\\.\DISPLAY1`) of the
/// specified monitor.
///
/// thread_safety: This function may be called from any thread. Access is not synchronized.
pub fn getWin32Adapter(monitor: Monitor) [*:0]const u8 {
internal_debug.assertInitialized();
if (native.glfwGetWin32Adapter(@as(*native.GLFWmonitor, @ptrCast(monitor.handle)))) |adapter| return adapter;
// `glfwGetWin32Adapter` returns `null` only for errors
// but the only potential error is unreachable (NotInitialized)
unreachable;
}
/// Returns the display device name of the specified monitor.
///
/// return: The UTF-8 encoded display device name (for example `\\.\DISPLAY1\Monitor0`)
/// of the specified monitor.
///
/// thread_safety: This function may be called from any thread. Access is not synchronized.
pub fn getWin32Monitor(monitor: Monitor) [*:0]const u8 {
internal_debug.assertInitialized();
if (native.glfwGetWin32Monitor(@as(*native.GLFWmonitor, @ptrCast(monitor.handle)))) |mon| return mon;
// `glfwGetWin32Monitor` returns `null` only for errors
// but the only potential error is unreachable (NotInitialized)
unreachable;
}
/// Returns the `HWND` of the specified window.
///
/// The `HDC` associated with the window can be queried with the
/// [GetDC](https://docs.microsoft.com/en-us/windows/win32/api/winuser/nf-winuser-getdc)
/// function.
/// ```
/// const dc = std.os.windows.user32.GetDC(native.getWin32Window(window));
/// ```
/// This DC is private and does not need to be released.
///
/// thread_safety: This function may be called from any thread. Access is not synchronized.
pub fn getWin32Window(window: Window) std.os.windows.HWND {
internal_debug.assertInitialized();
if (native.glfwGetWin32Window(@as(*native.GLFWwindow, @ptrCast(window.handle)))) |win|
return @as(std.os.windows.HWND, @ptrCast(win));
// `glfwGetWin32Window` returns `null` only for errors
// but the only potential error is unreachable (NotInitialized)
unreachable;
}
/// Returns the `HGLRC` of the specified window.
///
/// The `HDC` associated with the window can be queried with the
/// [GetDC](https://docs.microsoft.com/en-us/windows/win32/api/winuser/nf-winuser-getdc)
/// function.
/// ```
/// const dc = std.os.windows.user32.GetDC(native.getWin32Window(window));
/// ```
/// This DC is private and does not need to be released.
///
/// Possible errors include glfw.ErrorCode.NoWindowContext
/// null is returned in the event of an error.
///
/// thread_safety: This function may be called from any thread. Access is not synchronized.
pub fn getWGLContext(window: Window) ?std.os.windows.HGLRC {
internal_debug.assertInitialized();
if (native.glfwGetWGLContext(@as(*native.GLFWwindow, @ptrCast(window.handle)))) |context| return context;
return null;
}
/// Returns the `CGDirectDisplayID` of the specified monitor.
///
/// thread_safety: This function may be called from any thread. Access is not synchronized.
pub fn getCocoaMonitor(monitor: Monitor) u32 {
internal_debug.assertInitialized();
const mon = native.glfwGetCocoaMonitor(@as(*native.GLFWmonitor, @ptrCast(monitor.handle)));
if (mon != native.kCGNullDirectDisplay) return mon;
// `glfwGetCocoaMonitor` returns `kCGNullDirectDisplay` only for errors
// but the only potential error is unreachable (NotInitialized)
unreachable;
}
/// Returns the `NSWindow` of the specified window.
///
/// thread_safety: This function may be called from any thread. Access is not synchronized.
pub fn getCocoaWindow(window: Window) ?*anyopaque {
internal_debug.assertInitialized();
return native.glfwGetCocoaWindow(@as(*native.GLFWwindow, @ptrCast(window.handle)));
}
/// Returns the `NSWindow` of the specified window.
///
/// Possible errors include glfw.ErrorCode.NoWindowContext.
///
/// thread_safety: This function may be called from any thread. Access is not synchronized.
pub fn getNSGLContext(window: Window) u32 {
internal_debug.assertInitialized();
return native.glfwGetNSGLContext(@as(*native.GLFWwindow, @ptrCast(window.handle)));
}
/// Returns the `Display` used by GLFW.
///
/// thread_safety: This function may be called from any thread. Access is not synchronized.
pub fn getX11Display() *anyopaque {
internal_debug.assertInitialized();
if (native.glfwGetX11Display()) |display| return @as(*anyopaque, @ptrCast(display));
// `glfwGetX11Display` returns `null` only for errors
// but the only potential error is unreachable (NotInitialized)
unreachable;
}
/// Returns the `RRCrtc` of the specified monitor.
///
/// thread_safety: This function may be called from any thread. Access is not synchronized.
pub fn getX11Adapter(monitor: Monitor) u32 {
internal_debug.assertInitialized();
const adapter = native.glfwGetX11Adapter(@as(*native.GLFWMonitor, @ptrCast(monitor.handle)));
if (adapter != 0) return adapter;
// `glfwGetX11Adapter` returns `0` only for errors
// but the only potential error is unreachable (NotInitialized)
unreachable;
}
/// Returns the `RROutput` of the specified monitor.
///
/// thread_safety: This function may be called from any thread. Access is not synchronized.
pub fn getX11Monitor(monitor: Monitor) u32 {
internal_debug.assertInitialized();
const mon = native.glfwGetX11Monitor(@as(*native.GLFWmonitor, @ptrCast(monitor.handle)));
if (mon != 0) return mon;
// `glfwGetX11Monitor` returns `0` only for errors
// but the only potential error is unreachable (NotInitialized)
unreachable;
}
/// Returns the `Window` of the specified window.
///
/// thread_safety: This function may be called from any thread. Access is not synchronized.
pub fn getX11Window(window: Window) u32 {
internal_debug.assertInitialized();
const win = native.glfwGetX11Window(@as(*native.GLFWwindow, @ptrCast(window.handle)));
if (win != 0) return @as(u32, @intCast(win));
// `glfwGetX11Window` returns `0` only for errors
// but the only potential error is unreachable (NotInitialized)
unreachable;
}
/// Sets the current primary selection to the specified string.
///
/// Possible errors include glfw.ErrorCode.PlatformError.
///
/// The specified string is copied before this function returns.
///
/// thread_safety: This function must only be called from the main thread.
pub fn setX11SelectionString(string: [*:0]const u8) void {
internal_debug.assertInitialized();
native.glfwSetX11SelectionString(string);
}
/// Returns the contents of the current primary selection as a string.
///
/// Possible errors include glfw.ErrorCode.PlatformError.
/// Returns null in the event of an error.
///
/// The returned string is allocated and freed by GLFW. You should not free it
/// yourself. It is valid until the next call to getX11SelectionString or
/// setX11SelectionString, or until the library is terminated.
///
/// thread_safety: This function must only be called from the main thread.
pub fn getX11SelectionString() ?[*:0]const u8 {
internal_debug.assertInitialized();
if (native.glfwGetX11SelectionString()) |str| return str;
return null;
}
/// Returns the `GLXContext` of the specified window.
///
/// Possible errors include glfw.ErrorCode.NoWindowContext.
/// Returns null in the event of an error.
///
/// thread_safety: This function may be called from any thread. Access is not synchronized.
pub fn getGLXContext(window: Window) ?*anyopaque {
internal_debug.assertInitialized();
if (native.glfwGetGLXContext(@as(*native.GLFWwindow, @ptrCast(window.handle)))) |context| return @as(*anyopaque, @ptrCast(context));
return null;
}
/// Returns the `GLXWindow` of the specified window.
///
/// Possible errors include glfw.ErrorCode.NoWindowContext.
/// Returns null in the event of an error.
///
/// thread_safety: This function may be called from any thread. Access is not synchronized.
pub fn getGLXWindow(window: Window) ?*anyopaque {
internal_debug.assertInitialized();
const win = native.glfwGetGLXWindow(@as(*native.GLFWwindow, @ptrCast(window.handle)));
if (win != 0) return @as(*anyopaque, @ptrCast(win));
return null;
}
/// Returns the `*wl_display` used by GLFW.
///
/// thread_safety: This function may be called from any thread. Access is not synchronized.
pub fn getWaylandDisplay() *anyopaque {
internal_debug.assertInitialized();
if (native.glfwGetWaylandDisplay()) |display| return @as(*anyopaque, @ptrCast(display));
// `glfwGetWaylandDisplay` returns `null` only for errors
// but the only potential error is unreachable (NotInitialized)
unreachable;
}
/// Returns the `*wl_output` of the specified monitor.
///
/// thread_safety: This function may be called from any thread. Access is not synchronized.
pub fn getWaylandMonitor(monitor: Monitor) *anyopaque {
internal_debug.assertInitialized();
if (native.glfwGetWaylandMonitor(@as(*native.GLFWmonitor, @ptrCast(monitor.handle)))) |mon| return @as(*anyopaque, @ptrCast(mon));
// `glfwGetWaylandMonitor` returns `null` only for errors
// but the only potential error is unreachable (NotInitialized)
unreachable;
}
/// Returns the `*wl_surface` of the specified window.
///
/// thread_safety: This function may be called from any thread. Access is not synchronized.
pub fn getWaylandWindow(window: Window) *anyopaque {
internal_debug.assertInitialized();
if (native.glfwGetWaylandWindow(@as(*native.GLFWwindow, @ptrCast(window.handle)))) |win| return @as(*anyopaque, @ptrCast(win));
// `glfwGetWaylandWindow` returns `null` only for errors
// but the only potential error is unreachable (NotInitialized)
unreachable;
}
/// Returns the `EGLDisplay` used by GLFW.
///
/// remark: Because EGL is initialized on demand, this function will return `EGL_NO_DISPLAY`
/// until the first context has been created via EGL.
///
/// thread_safety: This function may be called from any thread. Access is not synchronized.
pub fn getEGLDisplay() *anyopaque {
internal_debug.assertInitialized();
const display = native.glfwGetEGLDisplay();
if (display != native.EGL_NO_DISPLAY) return @as(*anyopaque, @ptrCast(display));
// `glfwGetEGLDisplay` returns `EGL_NO_DISPLAY` only for errors
// but the only potential error is unreachable (NotInitialized)
unreachable;
}
/// Returns the `EGLContext` of the specified window.
///
/// Possible errors include glfw.ErrorCode.NoWindowContext.
/// Returns null in the event of an error.
///
/// thread_safety This function may be called from any thread. Access is not synchronized.
pub fn getEGLContext(window: Window) ?*anyopaque {
internal_debug.assertInitialized();
const context = native.glfwGetEGLContext(@as(*native.GLFWwindow, @ptrCast(window.handle)));
if (context != native.EGL_NO_CONTEXT) return @as(*anyopaque, @ptrCast(context));
return null;
}
/// Returns the `EGLSurface` of the specified window.
///
/// Possible errors include glfw.ErrorCode.NotInitalized and glfw.ErrorCode.NoWindowContext.
///
/// thread_safety This function may be called from any thread. Access is not synchronized.
pub fn getEGLSurface(window: Window) ?*anyopaque {
internal_debug.assertInitialized();
const surface = native.glfwGetEGLSurface(@as(*native.GLFWwindow, @ptrCast(window.handle)));
if (surface != native.EGL_NO_SURFACE) return @as(*anyopaque, @ptrCast(surface));
return null;
}
pub const OSMesaColorBuffer = struct {
width: c_int,
height: c_int,
format: c_int,
buffer: *anyopaque,
};
/// Retrieves the color buffer associated with the specified window.
///
/// Possible errors include glfw.ErrorCode.NoWindowContext and glfw.ErrorCode.PlatformError.
/// Returns null in the event of an error.
///
/// thread_safety: This function may be called from any thread. Access is not synchronized.
pub fn getOSMesaColorBuffer(window: Window) ?OSMesaColorBuffer {
internal_debug.assertInitialized();
var buf: OSMesaColorBuffer = undefined;
if (native.glfwGetOSMesaColorBuffer(
@as(*native.GLFWwindow, @ptrCast(window.handle)),
&buf.width,
&buf.height,
&buf.format,
&buf.buffer,
) == native.GLFW_TRUE) return buf;
return null;
}
pub const OSMesaDepthBuffer = struct {
width: c_int,
height: c_int,
bytes_per_value: c_int,
buffer: *anyopaque,
};
/// Retrieves the depth buffer associated with the specified window.
///
/// Possible errors include glfw.ErrorCode.NoWindowContext and glfw.ErrorCode.PlatformError.
/// Returns null in the event of an error.
///
/// thread_safety: This function may be called from any thread. Access is not synchronized.
pub fn getOSMesaDepthBuffer(window: Window) ?OSMesaDepthBuffer {
internal_debug.assertInitialized();
var buf: OSMesaDepthBuffer = undefined;
if (native.glfwGetOSMesaDepthBuffer(
@as(*native.GLFWwindow, @ptrCast(window.handle)),
&buf.width,
&buf.height,
&buf.bytes_per_value,
&buf.buffer,
) == native.GLFW_TRUE) return buf;
return null;
}
/// Returns the 'OSMesaContext' of the specified window.
///
/// Possible errors include glfw.ErrorCode.NoWindowContext.
///
/// thread_safety: This function may be called from any thread. Access is not synchronized.
pub fn getOSMesaContext(window: Window) ?*anyopaque {
internal_debug.assertInitialized();
if (native.glfwGetOSMesaContext(@as(*native.GLFWwindow, @ptrCast(window.handle)))) |context| return @as(*anyopaque, @ptrCast(context));
return null;
}
};
}
|
0 | repos/mach-glfw | repos/mach-glfw/src/gamepad_axis.zig | const c = @import("c.zig").c;
/// Gamepad axes.
///
/// See glfw.getGamepadState for how these are used.
pub const GamepadAxis = enum(c_int) {
left_x = c.GLFW_GAMEPAD_AXIS_LEFT_X,
left_y = c.GLFW_GAMEPAD_AXIS_LEFT_Y,
right_x = c.GLFW_GAMEPAD_AXIS_RIGHT_X,
right_y = c.GLFW_GAMEPAD_AXIS_RIGHT_Y,
left_trigger = c.GLFW_GAMEPAD_AXIS_LEFT_TRIGGER,
right_trigger = c.GLFW_GAMEPAD_AXIS_RIGHT_TRIGGER,
};
/// Not in the GamepadAxis enumeration as it is a duplicate value which is forbidden.
pub const last = GamepadAxis.right_trigger;
|
0 | repos/mach-glfw | repos/mach-glfw/src/key.zig | //! Keyboard key IDs.
//!
//! See glfw.setKeyCallback for how these are used.
//!
//! These key codes are inspired by the _USB HID Usage Tables v1.12_ (p. 53-60), but re-arranged to
//! map to 7-bit ASCII for printable keys (function keys are put in the 256+ range).
//!
//! The naming of the key codes follow these rules:
//!
//! - The US keyboard layout is used
//! - Names of printable alphanumeric characters are used (e.g. "a", "r", "three", etc.)
//! - For non-alphanumeric characters, Unicode:ish names are used (e.g. "comma", "left_bracket",
//! etc.). Note that some names do not correspond to the Unicode standard (usually for brevity)
//! - Keys that lack a clear US mapping are named "world_x"
//! - For non-printable keys, custom names are used (e.g. "F4", "backspace", etc.)
const std = @import("std");
const cc = @import("c.zig").c;
const internal_debug = @import("internal_debug.zig");
/// enum containing all glfw keys
pub const Key = enum(c_int) {
/// The unknown key
unknown = cc.GLFW_KEY_UNKNOWN,
/// Printable keys
space = cc.GLFW_KEY_SPACE,
apostrophe = cc.GLFW_KEY_APOSTROPHE,
comma = cc.GLFW_KEY_COMMA,
minus = cc.GLFW_KEY_MINUS,
period = cc.GLFW_KEY_PERIOD,
slash = cc.GLFW_KEY_SLASH,
zero = cc.GLFW_KEY_0,
one = cc.GLFW_KEY_1,
two = cc.GLFW_KEY_2,
three = cc.GLFW_KEY_3,
four = cc.GLFW_KEY_4,
five = cc.GLFW_KEY_5,
six = cc.GLFW_KEY_6,
seven = cc.GLFW_KEY_7,
eight = cc.GLFW_KEY_8,
nine = cc.GLFW_KEY_9,
semicolon = cc.GLFW_KEY_SEMICOLON,
equal = cc.GLFW_KEY_EQUAL,
a = cc.GLFW_KEY_A,
b = cc.GLFW_KEY_B,
c = cc.GLFW_KEY_C,
d = cc.GLFW_KEY_D,
e = cc.GLFW_KEY_E,
f = cc.GLFW_KEY_F,
g = cc.GLFW_KEY_G,
h = cc.GLFW_KEY_H,
i = cc.GLFW_KEY_I,
j = cc.GLFW_KEY_J,
k = cc.GLFW_KEY_K,
l = cc.GLFW_KEY_L,
m = cc.GLFW_KEY_M,
n = cc.GLFW_KEY_N,
o = cc.GLFW_KEY_O,
p = cc.GLFW_KEY_P,
q = cc.GLFW_KEY_Q,
r = cc.GLFW_KEY_R,
s = cc.GLFW_KEY_S,
t = cc.GLFW_KEY_T,
u = cc.GLFW_KEY_U,
v = cc.GLFW_KEY_V,
w = cc.GLFW_KEY_W,
x = cc.GLFW_KEY_X,
y = cc.GLFW_KEY_Y,
z = cc.GLFW_KEY_Z,
left_bracket = cc.GLFW_KEY_LEFT_BRACKET,
backslash = cc.GLFW_KEY_BACKSLASH,
right_bracket = cc.GLFW_KEY_RIGHT_BRACKET,
grave_accent = cc.GLFW_KEY_GRAVE_ACCENT,
world_1 = cc.GLFW_KEY_WORLD_1, // non-US #1
world_2 = cc.GLFW_KEY_WORLD_2, // non-US #2
// Function keys
escape = cc.GLFW_KEY_ESCAPE,
enter = cc.GLFW_KEY_ENTER,
tab = cc.GLFW_KEY_TAB,
backspace = cc.GLFW_KEY_BACKSPACE,
insert = cc.GLFW_KEY_INSERT,
delete = cc.GLFW_KEY_DELETE,
right = cc.GLFW_KEY_RIGHT,
left = cc.GLFW_KEY_LEFT,
down = cc.GLFW_KEY_DOWN,
up = cc.GLFW_KEY_UP,
page_up = cc.GLFW_KEY_PAGE_UP,
page_down = cc.GLFW_KEY_PAGE_DOWN,
home = cc.GLFW_KEY_HOME,
end = cc.GLFW_KEY_END,
caps_lock = cc.GLFW_KEY_CAPS_LOCK,
scroll_lock = cc.GLFW_KEY_SCROLL_LOCK,
num_lock = cc.GLFW_KEY_NUM_LOCK,
print_screen = cc.GLFW_KEY_PRINT_SCREEN,
pause = cc.GLFW_KEY_PAUSE,
F1 = cc.GLFW_KEY_F1,
F2 = cc.GLFW_KEY_F2,
F3 = cc.GLFW_KEY_F3,
F4 = cc.GLFW_KEY_F4,
F5 = cc.GLFW_KEY_F5,
F6 = cc.GLFW_KEY_F6,
F7 = cc.GLFW_KEY_F7,
F8 = cc.GLFW_KEY_F8,
F9 = cc.GLFW_KEY_F9,
F10 = cc.GLFW_KEY_F10,
F11 = cc.GLFW_KEY_F11,
F12 = cc.GLFW_KEY_F12,
F13 = cc.GLFW_KEY_F13,
F14 = cc.GLFW_KEY_F14,
F15 = cc.GLFW_KEY_F15,
F16 = cc.GLFW_KEY_F16,
F17 = cc.GLFW_KEY_F17,
F18 = cc.GLFW_KEY_F18,
F19 = cc.GLFW_KEY_F19,
F20 = cc.GLFW_KEY_F20,
F21 = cc.GLFW_KEY_F21,
F22 = cc.GLFW_KEY_F22,
F23 = cc.GLFW_KEY_F23,
F24 = cc.GLFW_KEY_F24,
F25 = cc.GLFW_KEY_F25,
kp_0 = cc.GLFW_KEY_KP_0,
kp_1 = cc.GLFW_KEY_KP_1,
kp_2 = cc.GLFW_KEY_KP_2,
kp_3 = cc.GLFW_KEY_KP_3,
kp_4 = cc.GLFW_KEY_KP_4,
kp_5 = cc.GLFW_KEY_KP_5,
kp_6 = cc.GLFW_KEY_KP_6,
kp_7 = cc.GLFW_KEY_KP_7,
kp_8 = cc.GLFW_KEY_KP_8,
kp_9 = cc.GLFW_KEY_KP_9,
kp_decimal = cc.GLFW_KEY_KP_DECIMAL,
kp_divide = cc.GLFW_KEY_KP_DIVIDE,
kp_multiply = cc.GLFW_KEY_KP_MULTIPLY,
kp_subtract = cc.GLFW_KEY_KP_SUBTRACT,
kp_add = cc.GLFW_KEY_KP_ADD,
kp_enter = cc.GLFW_KEY_KP_ENTER,
kp_equal = cc.GLFW_KEY_KP_EQUAL,
left_shift = cc.GLFW_KEY_LEFT_SHIFT,
left_control = cc.GLFW_KEY_LEFT_CONTROL,
left_alt = cc.GLFW_KEY_LEFT_ALT,
left_super = cc.GLFW_KEY_LEFT_SUPER,
right_shift = cc.GLFW_KEY_RIGHT_SHIFT,
right_control = cc.GLFW_KEY_RIGHT_CONTROL,
right_alt = cc.GLFW_KEY_RIGHT_ALT,
right_super = cc.GLFW_KEY_RIGHT_SUPER,
menu = cc.GLFW_KEY_MENU,
pub inline fn last() Key {
return @as(Key, @enumFromInt(cc.GLFW_KEY_LAST));
}
/// Returns the layout-specific name of the specified printable key.
///
/// This function returns the name of the specified printable key, encoded as UTF-8. This is
/// typically the character that key would produce without any modifier keys, intended for
/// displaying key bindings to the user. For dead keys, it is typically the diacritic it would add
/// to a character.
///
/// __Do not use this function__ for text input (see input_char). You will break text input for many
/// languages even if it happens to work for yours.
///
/// If the key is `glfw.key.unknown`, the scancode is used to identify the key, otherwise the
/// scancode is ignored. If you specify a non-printable key, or `glfw.key.unknown` and a scancode
/// that maps to a non-printable key, this function returns null but does not emit an error.
///
/// This behavior allows you to always pass in the arguments in the key callback (see input_key)
/// without modification.
///
/// The printable keys are:
///
/// - `glfw.Key.apostrophe`
/// - `glfw.Key.comma`
/// - `glfw.Key.minus`
/// - `glfw.Key.period`
/// - `glfw.Key.slash`
/// - `glfw.Key.semicolon`
/// - `glfw.Key.equal`
/// - `glfw.Key.left_bracket`
/// - `glfw.Key.right_bracket`
/// - `glfw.Key.backslash`
/// - `glfw.Key.world_1`
/// - `glfw.Key.world_2`
/// - `glfw.Key.0` to `glfw.key.9`
/// - `glfw.Key.a` to `glfw.key.z`
/// - `glfw.Key.kp_0` to `glfw.key.kp_9`
/// - `glfw.Key.kp_decimal`
/// - `glfw.Key.kp_divide`
/// - `glfw.Key.kp_multiply`
/// - `glfw.Key.kp_subtract`
/// - `glfw.Key.kp_add`
/// - `glfw.Key.kp_equal`
///
/// Names for printable keys depend on keyboard layout, while names for non-printable keys are the
/// same across layouts but depend on the application language and should be localized along with
/// other user interface text.
///
/// @param[in] key The key to query, or `glfw.key.unknown`.
/// @param[in] scancode The scancode of the key to query.
/// @return The UTF-8 encoded, layout-specific name of the key, or null.
///
/// Possible errors include glfw.ErrorCode.PlatformError.
/// Also returns null in the event of an error.
///
/// The contents of the returned string may change when a keyboard layout change event is received.
///
/// @pointer_lifetime The returned string is allocated and freed by GLFW. You should not free it
/// yourself. It is valid until the library is terminated.
///
/// @thread_safety This function must only be called from the main thread.
///
/// see also: input_key_name
pub inline fn getName(self: Key, scancode: i32) ?[:0]const u8 {
internal_debug.assertInitialized();
const name_opt = cc.glfwGetKeyName(@intFromEnum(self), @as(c_int, @intCast(scancode)));
return if (name_opt) |name|
std.mem.span(@as([*:0]const u8, @ptrCast(name)))
else
null;
}
/// Returns the platform-specific scancode of the specified key.
///
/// This function returns the platform-specific scancode of the specified key.
///
/// If the key is `glfw.key.UNKNOWN` or does not exist on the keyboard this method will return `-1`.
///
/// @param[in] key Any named key (see keys).
/// @return The platform-specific scancode for the key.
///
/// Possible errors include glfw.ErrorCode.InvalidEnum and glfw.ErrorCode.PlatformError.
/// Additionally returns -1 in the event of an error.
///
/// @thread_safety This function may be called from any thread.
pub inline fn getScancode(self: Key) i32 {
internal_debug.assertInitialized();
return cc.glfwGetKeyScancode(@intFromEnum(self));
}
};
test "getName" {
const glfw = @import("main.zig");
defer glfw.clearError(); // clear any error we generate
if (!glfw.init(.{})) {
std.log.err("failed to initialize GLFW: {?s}", .{glfw.getErrorString()});
std.process.exit(1);
}
defer glfw.terminate();
_ = glfw.Key.a.getName(0);
}
test "getScancode" {
const glfw = @import("main.zig");
defer glfw.clearError(); // clear any error we generate
if (!glfw.init(.{})) {
std.log.err("failed to initialize GLFW: {?s}", .{glfw.getErrorString()});
std.process.exit(1);
}
defer glfw.terminate();
_ = glfw.Key.a.getScancode();
}
|
0 | repos/mach-glfw | repos/mach-glfw/src/VideoMode.zig | //! Monitor video modes and related functions
//!
//! see also: glfw.Monitor.getVideoMode
const std = @import("std");
const c = @import("c.zig").c;
const VideoMode = @This();
handle: c.GLFWvidmode,
/// Returns the width of the video mode, in screen coordinates.
pub inline fn getWidth(self: VideoMode) u32 {
return @as(u32, @intCast(self.handle.width));
}
/// Returns the height of the video mode, in screen coordinates.
pub inline fn getHeight(self: VideoMode) u32 {
return @as(u32, @intCast(self.handle.height));
}
/// Returns the bit depth of the red channel of the video mode.
pub inline fn getRedBits(self: VideoMode) u32 {
return @as(u32, @intCast(self.handle.redBits));
}
/// Returns the bit depth of the green channel of the video mode.
pub inline fn getGreenBits(self: VideoMode) u32 {
return @as(u32, @intCast(self.handle.greenBits));
}
/// Returns the bit depth of the blue channel of the video mode.
pub inline fn getBlueBits(self: VideoMode) u32 {
return @as(u32, @intCast(self.handle.blueBits));
}
/// Returns the refresh rate of the video mode, in Hz.
pub inline fn getRefreshRate(self: VideoMode) u32 {
return @as(u32, @intCast(self.handle.refreshRate));
}
test "getters" {
const x = std.mem.zeroes(VideoMode);
_ = x.getWidth();
_ = x.getHeight();
_ = x.getRedBits();
_ = x.getGreenBits();
_ = x.getBlueBits();
_ = x.getRefreshRate();
}
|
0 | repos/mach-glfw | repos/mach-glfw/src/Window.zig | //! Window type and related functions
const std = @import("std");
const testing = std.testing;
const mem = std.mem;
const c = @import("c.zig").c;
const glfw = @import("main.zig");
const Image = @import("Image.zig");
const Monitor = @import("Monitor.zig");
const Cursor = @import("Cursor.zig");
const Key = @import("key.zig").Key;
const Action = @import("action.zig").Action;
const Mods = @import("mod.zig").Mods;
const MouseButton = @import("mouse_button.zig").MouseButton;
const internal_debug = @import("internal_debug.zig");
const Window = @This();
handle: *c.GLFWwindow,
/// Returns a Zig GLFW window from an underlying C GLFW window handle.
pub inline fn from(handle: *anyopaque) Window {
return Window{ .handle = @as(*c.GLFWwindow, @ptrCast(@alignCast(handle))) };
}
/// Resets all window hints to their default values.
///
/// This function resets all window hints to their default values.
///
/// @thread_safety This function must only be called from the main thread.
///
/// see also: window_hints, glfw.Window.hint, glfw.Window.hintString
pub inline fn defaultHints() void {
internal_debug.assertInitialized();
c.glfwDefaultWindowHints();
}
/// Window hints
const Hint = enum(c_int) {
resizable = c.GLFW_RESIZABLE,
visible = c.GLFW_VISIBLE,
decorated = c.GLFW_DECORATED,
focused = c.GLFW_FOCUSED,
auto_iconify = c.GLFW_AUTO_ICONIFY,
floating = c.GLFW_FLOATING,
maximized = c.GLFW_MAXIMIZED,
center_cursor = c.GLFW_CENTER_CURSOR,
transparent_framebuffer = c.GLFW_TRANSPARENT_FRAMEBUFFER,
focus_on_show = c.GLFW_FOCUS_ON_SHOW,
mouse_passthrough = c.GLFW_MOUSE_PASSTHROUGH,
position_x = c.GLFW_POSITION_X,
position_y = c.GLFW_POSITION_Y,
scale_to_monitor = c.GLFW_SCALE_TO_MONITOR,
/// Framebuffer hints
red_bits = c.GLFW_RED_BITS,
green_bits = c.GLFW_GREEN_BITS,
blue_bits = c.GLFW_BLUE_BITS,
alpha_bits = c.GLFW_ALPHA_BITS,
depth_bits = c.GLFW_DEPTH_BITS,
stencil_bits = c.GLFW_STENCIL_BITS,
accum_red_bits = c.GLFW_ACCUM_RED_BITS,
accum_green_bits = c.GLFW_ACCUM_GREEN_BITS,
accum_blue_bits = c.GLFW_ACCUM_BLUE_BITS,
accum_alpha_bits = c.GLFW_ACCUM_ALPHA_BITS,
aux_buffers = c.GLFW_AUX_BUFFERS,
/// Framebuffer MSAA samples
samples = c.GLFW_SAMPLES,
/// Monitor refresh rate
refresh_rate = c.GLFW_REFRESH_RATE,
/// OpenGL stereoscopic rendering
stereo = c.GLFW_STEREO,
/// Framebuffer sRGB
srgb_capable = c.GLFW_SRGB_CAPABLE,
/// Framebuffer double buffering
doublebuffer = c.GLFW_DOUBLEBUFFER,
client_api = c.GLFW_CLIENT_API,
context_creation_api = c.GLFW_CONTEXT_CREATION_API,
context_version_major = c.GLFW_CONTEXT_VERSION_MAJOR,
context_version_minor = c.GLFW_CONTEXT_VERSION_MINOR,
context_robustness = c.GLFW_CONTEXT_ROBUSTNESS,
context_release_behavior = c.GLFW_CONTEXT_RELEASE_BEHAVIOR,
context_no_error = c.GLFW_CONTEXT_NO_ERROR,
// NOTE: This supersedes opengl_debug_context / GLFW_OPENGL_DEBUG_CONTEXT
context_debug = c.GLFW_CONTEXT_DEBUG,
opengl_forward_compat = c.GLFW_OPENGL_FORWARD_COMPAT,
opengl_profile = c.GLFW_OPENGL_PROFILE,
/// macOS specific
cocoa_retina_framebuffer = c.GLFW_COCOA_RETINA_FRAMEBUFFER,
/// macOS specific
cocoa_frame_name = c.GLFW_COCOA_FRAME_NAME,
/// macOS specific
cocoa_graphics_switching = c.GLFW_COCOA_GRAPHICS_SWITCHING,
/// X11 specific
x11_class_name = c.GLFW_X11_CLASS_NAME,
/// X11 specific
x11_instance_name = c.GLFW_X11_INSTANCE_NAME,
/// Windows specific
win32_keyboard_menu = c.GLFW_WIN32_KEYBOARD_MENU,
/// Allows specification of the Wayland app_id.
wayland_app_id = c.GLFW_WAYLAND_APP_ID,
};
/// Window hints
pub const Hints = struct {
// Note: The defaults here are directly from the GLFW source of the glfwDefaultWindowHints function
resizable: bool = true,
visible: bool = true,
decorated: bool = true,
focused: bool = true,
auto_iconify: bool = true,
floating: bool = false,
maximized: bool = false,
center_cursor: bool = true,
transparent_framebuffer: bool = false,
focus_on_show: bool = true,
mouse_passthrough: bool = false,
position_x: c_int = @intFromEnum(Position.any),
position_y: c_int = @intFromEnum(Position.any),
scale_to_monitor: bool = false,
/// Framebuffer hints
red_bits: ?PositiveCInt = 8,
green_bits: ?PositiveCInt = 8,
blue_bits: ?PositiveCInt = 8,
alpha_bits: ?PositiveCInt = 8,
depth_bits: ?PositiveCInt = 24,
stencil_bits: ?PositiveCInt = 8,
accum_red_bits: ?PositiveCInt = 0,
accum_green_bits: ?PositiveCInt = 0,
accum_blue_bits: ?PositiveCInt = 0,
accum_alpha_bits: ?PositiveCInt = 0,
aux_buffers: ?PositiveCInt = 0,
/// Framebuffer MSAA samples
samples: ?PositiveCInt = 0,
/// Monitor refresh rate
refresh_rate: ?PositiveCInt = null,
/// OpenGL stereoscopic rendering
stereo: bool = false,
/// Framebuffer sRGB
srgb_capable: bool = false,
/// Framebuffer double buffering
doublebuffer: bool = true,
client_api: ClientAPI = .opengl_api,
context_creation_api: ContextCreationAPI = .native_context_api,
context_version_major: c_int = 1,
context_version_minor: c_int = 0,
context_robustness: ContextRobustness = .no_robustness,
context_release_behavior: ContextReleaseBehavior = .any_release_behavior,
/// Note: disables the context creating errors,
/// instead turning them into undefined behavior.
context_no_error: bool = false,
context_debug: bool = false,
opengl_forward_compat: bool = false,
opengl_profile: OpenGLProfile = .opengl_any_profile,
/// macOS specific
cocoa_retina_framebuffer: bool = true,
/// macOS specific
cocoa_frame_name: [:0]const u8 = "",
/// macOS specific
cocoa_graphics_switching: bool = false,
/// X11 specific
x11_class_name: [:0]const u8 = "",
/// X11 specific
x11_instance_name: [:0]const u8 = "",
/// Windows specific
win32_keyboard_menu: bool = false,
/// Allows specification of the Wayland app_id.
wayland_app_id: [:0]const u8 = "",
pub const PositiveCInt = std.math.IntFittingRange(0, std.math.maxInt(c_int));
pub const ClientAPI = enum(c_int) {
opengl_api = c.GLFW_OPENGL_API,
opengl_es_api = c.GLFW_OPENGL_ES_API,
no_api = c.GLFW_NO_API,
};
pub const ContextCreationAPI = enum(c_int) {
native_context_api = c.GLFW_NATIVE_CONTEXT_API,
egl_context_api = c.GLFW_EGL_CONTEXT_API,
osmesa_context_api = c.GLFW_OSMESA_CONTEXT_API,
};
pub const ContextRobustness = enum(c_int) {
no_robustness = c.GLFW_NO_ROBUSTNESS,
no_reset_notification = c.GLFW_NO_RESET_NOTIFICATION,
lose_context_on_reset = c.GLFW_LOSE_CONTEXT_ON_RESET,
};
pub const ContextReleaseBehavior = enum(c_int) {
any_release_behavior = c.GLFW_ANY_RELEASE_BEHAVIOR,
release_behavior_flush = c.GLFW_RELEASE_BEHAVIOR_FLUSH,
release_behavior_none = c.GLFW_RELEASE_BEHAVIOR_NONE,
};
pub const OpenGLProfile = enum(c_int) {
opengl_any_profile = c.GLFW_OPENGL_ANY_PROFILE,
opengl_compat_profile = c.GLFW_OPENGL_COMPAT_PROFILE,
opengl_core_profile = c.GLFW_OPENGL_CORE_PROFILE,
};
pub const Position = enum(c_int) {
/// By default, newly created windows use the placement recommended by the window system,
///
/// To create the window at a specific position, make it initially invisible using the
/// Window.Hint.visible hint, set its Window.Hint.position and then Window.hide() it.
///
/// To create the window at a specific position, set the Window.Hint.position_x and
/// Window.Hint.position_y hints before creation. To restore the default behavior, set
/// either or both hints back to Window.Hints.Position.any
any = @bitCast(c.GLFW_ANY_POSITION),
};
fn set(hints: Hints) void {
internal_debug.assertInitialized();
inline for (comptime std.meta.fieldNames(Hint)) |field_name| {
const hint_tag = @intFromEnum(@field(Hint, field_name));
const hint_value = @field(hints, field_name);
switch (@TypeOf(hint_value)) {
bool => c.glfwWindowHint(hint_tag, @intFromBool(hint_value)),
?PositiveCInt => c.glfwWindowHint(hint_tag, if (hint_value) |unwrapped| unwrapped else glfw.dont_care),
c_int => c.glfwWindowHint(hint_tag, hint_value),
ClientAPI,
ContextCreationAPI,
ContextRobustness,
ContextReleaseBehavior,
OpenGLProfile,
Position,
=> c.glfwWindowHint(hint_tag, @intFromEnum(hint_value)),
[:0]const u8 => c.glfwWindowHintString(hint_tag, hint_value.ptr),
else => unreachable,
}
}
}
};
/// Creates a window and its associated context.
///
/// This function creates a window and its associated OpenGL or OpenGL ES context. Most of the
/// options controlling how the window and its context should be created are specified with window
/// hints using `glfw.Window.hint`.
///
/// Successful creation does not change which context is current. Before you can use the newly
/// created context, you need to make it current using `glfw.makeContextCurrent`. For
/// information about the `share` parameter, see context_sharing.
///
/// The created window, framebuffer and context may differ from what you requested, as not all
/// parameters and hints are hard constraints. This includes the size of the window, especially for
/// full screen windows. To query the actual attributes of the created window, framebuffer and
/// context, see glfw.Window.getAttrib, glfw.Window.getSize and glfw.window.getFramebufferSize.
///
/// To create a full screen window, you need to specify the monitor the window will cover. If no
/// monitor is specified, the window will be windowed mode. Unless you have a way for the user to
/// choose a specific monitor, it is recommended that you pick the primary monitor. For more
/// information on how to query connected monitors, see @ref monitor_monitors.
///
/// For full screen windows, the specified size becomes the resolution of the window's _desired
/// video mode_. As long as a full screen window is not iconified, the supported video mode most
/// closely matching the desired video mode is set for the specified monitor. For more information
/// about full screen windows, including the creation of so called _windowed full screen_ or
/// _borderless full screen_ windows, see window_windowed_full_screen.
///
/// Once you have created the window, you can switch it between windowed and full screen mode with
/// glfw.Window.setMonitor. This will not affect its OpenGL or OpenGL ES context.
///
/// By default, newly created windows use the placement recommended by the window system. To create
/// the window at a specific position, make it initially invisible using the `visible` window
/// hint, set its position and then show it.
///
/// As long as at least one full screen window is not iconified, the screensaver is prohibited from
/// starting.
///
/// Window systems put limits on window sizes. Very large or very small window dimensions may be
/// overridden by the window system on creation. Check the actual size after creation.
///
/// The swap interval is not set during window creation and the initial value may vary depending on
/// driver settings and defaults.
///
/// Possible errors include glfw.ErrorCode.InvalidEnum, glfw.ErrorCode.InvalidValue,
/// glfw.ErrorCode.APIUnavailable, glfw.ErrorCode.VersionUnavailable, glfw.ErrorCode.FormatUnavailable and
/// glfw.ErrorCode.PlatformError.
/// Returns null in the event of an error.
///
/// Parameters are as follows:
///
/// * `width` The desired width, in screen coordinates, of the window.
/// * `height` The desired height, in screen coordinates, of the window.
/// * `title` The initial, UTF-8 encoded window title.
/// * `monitor` The monitor to use for full screen mode, or `null` for windowed mode.
/// * `share` The window whose context to share resources with, or `null` to not share resources.
///
/// win32: Window creation will fail if the Microsoft GDI software OpenGL implementation is the
/// only one available.
///
/// win32: If the executable has an icon resource named `GLFW_ICON`, it will be set as the initial
/// icon for the window. If no such icon is present, the `IDI_APPLICATION` icon will be used
/// instead. To set a different icon, see glfw.Window.setIcon.
///
/// win32: The context to share resources with must not be current on any other thread.
///
/// macos: The OS only supports forward-compatible core profile contexts for OpenGL versions 3.2
/// and later. Before creating an OpenGL context of version 3.2 or later you must set the
/// `glfw.opengl_forward_compat` and `glfw.opengl_profile` hints accordingly. OpenGL 3.0 and 3.1
/// contexts are not supported at all on macOS.
///
/// macos: The OS only supports core profile contexts for OpenGL versions 3.2 and later. Before
/// creating an OpenGL context of version 3.2 or later you must set the `glfw.opengl_profile` hint
/// accordingly. OpenGL 3.0 and 3.1 contexts are not supported at all on macOS.
///
/// macos: The GLFW window has no icon, as it is not a document window, but the dock icon will be
/// the same as the application bundle's icon. For more information on bundles, see the
/// [Bundle Programming Guide](https://developer.apple.com/library/mac/documentation/CoreFoundation/Conceptual/CFBundles/)
/// in the Mac Developer Library.
///
/// macos: On OS X 10.10 and later the window frame will not be rendered at full resolution on
/// Retina displays unless the glfw.cocoa_retina_framebuffer hint is true (1) and the `NSHighResolutionCapable`
/// key is enabled in the application bundle's `Info.plist`. For more information, see
/// [High Resolution Guidelines for OS X](https://developer.apple.com/library/mac/documentation/GraphicsAnimation/Conceptual/HighResolutionOSX/Explained/Explained.html)
/// in the Mac Developer Library. The GLFW test and example programs use a custom `Info.plist`
/// template for this, which can be found as `CMake/Info.plist.in` in the source tree.
///
/// macos: When activating frame autosaving with glfw.cocoa_frame_name, the specified window size
/// and position may be overridden by previously saved values.
///
/// x11: Some window managers will not respect the placement of initially hidden windows.
///
/// x11: Due to the asynchronous nature of X11, it may take a moment for a window to reach its
/// requested state. This means you may not be able to query the final size, position or other
/// attributes directly after window creation.
///
/// x11: The class part of the `WM_CLASS` window property will by default be set to the window title
/// passed to this function. The instance part will use the contents of the `RESOURCE_NAME`
/// environment variable, if present and not empty, or fall back to the window title. Set the glfw.x11_class_name
/// and glfw.x11_instance_name window hints to override this.
///
/// wayland: Compositors should implement the xdg-decoration protocol for GLFW to decorate the
/// window properly. If this protocol isn't supported, or if the compositor prefers client-side
/// decorations, a very simple fallback frame will be drawn using the wp_viewporter protocol. A
/// compositor can still emit close, maximize or fullscreen events, using for instance a keybind
/// mechanism. If neither of these protocols is supported, the window won't be decorated.
///
/// wayland: A full screen window will not attempt to change the mode, no matter what the
/// requested size or refresh rate.
///
/// wayland: Screensaver inhibition requires the idle-inhibit protocol to be implemented in the
/// user's compositor.
///
/// @thread_safety This function must only be called from the main thread.
///
/// see also: window_creation, glfw.Window.destroy
pub inline fn create(
width: u32,
height: u32,
title: [*:0]const u8,
monitor: ?Monitor,
share: ?Window,
hints: Hints,
) ?Window {
internal_debug.assertInitialized();
const ignore_hints_struct = if (comptime @import("builtin").is_test) testing_ignore_window_hints_struct else false;
if (!ignore_hints_struct) hints.set();
if (c.glfwCreateWindow(
@as(c_int, @intCast(width)),
@as(c_int, @intCast(height)),
&title[0],
if (monitor) |m| m.handle else null,
if (share) |w| w.handle else null,
)) |handle| return from(handle);
return null;
}
var testing_ignore_window_hints_struct = if (@import("builtin").is_test) false else @as(void, {});
/// Destroys the specified window and its context.
///
/// This function destroys the specified window and its context. On calling this function, no
/// further callbacks will be called for that window.
///
/// If the context of the specified window is current on the main thread, it is detached before
/// being destroyed.
///
/// note: The context of the specified window must not be current on any other thread when this
/// function is called.
///
/// Possible errors include glfw.ErrorCode.PlatformError.
///
/// @reentrancy This function must not be called from a callback.
///
/// @thread_safety This function must only be called from the main thread.
///
/// see also: window_creation, glfw.Window.create
pub inline fn destroy(self: Window) void {
internal_debug.assertInitialized();
c.glfwDestroyWindow(self.handle);
}
/// Checks the close flag of the specified window.
///
/// This function returns the value of the close flag of the specified window.
///
/// @thread_safety This function may be called from any thread. Access is not synchronized.
///
/// see also: window_close
pub inline fn shouldClose(self: Window) bool {
internal_debug.assertInitialized();
return c.glfwWindowShouldClose(self.handle) == c.GLFW_TRUE;
}
/// Sets the close flag of the specified window.
///
/// This function sets the value of the close flag of the specified window. This can be used to
/// override the user's attempt to close the window, or to signal that it should be closed.
///
/// @thread_safety This function may be called from any thread. Access is not
/// synchronized.
///
/// see also: window_close
pub inline fn setShouldClose(self: Window, value: bool) void {
internal_debug.assertInitialized();
const boolean = if (value) c.GLFW_TRUE else c.GLFW_FALSE;
c.glfwSetWindowShouldClose(self.handle, boolean);
}
/// Sets the UTF-8 encoded title of the specified window.
///
/// This function sets the window title, encoded as UTF-8, of the specified window.
///
/// Possible errors include glfw.ErrorCode.PlatformError.
///
/// macos: The window title will not be updated until the next time you process events.
///
/// @thread_safety This function must only be called from the main thread.
///
/// see also: window_title
pub inline fn setTitle(self: Window, title: [*:0]const u8) void {
internal_debug.assertInitialized();
c.glfwSetWindowTitle(self.handle, title);
}
/// Sets the icon for the specified window.
///
/// This function sets the icon of the specified window. If passed an array of candidate images,
/// those of or closest to the sizes desired by the system are selected. If no images are
/// specified, the window reverts to its default icon.
///
/// The pixels are 32-bit, little-endian, non-premultiplied RGBA, i.e. eight bits per channel with
/// the red channel first. They are arranged canonically as packed sequential rows, starting from
/// the top-left corner.
///
/// The desired image sizes varies depending on platform and system settings. The selected images
/// will be rescaled as needed. Good sizes include 16x16, 32x32 and 48x48.
///
/// @pointer_lifetime The specified image data is copied before this function returns.
///
/// macos: Regular windows do not have icons on macOS. This function will emit FeatureUnavailable.
/// The dock icon will be the same as the application bundle's icon. For more information on
/// bundles, see the [Bundle Programming Guide](https://developer.apple.com/library/mac/documentation/CoreFoundation/Conceptual/CFBundles/)
/// in the Mac Developer Library.
///
/// wayland: There is no existing protocol to change an icon, the window will thus inherit the one
/// defined in the application's desktop file. This function will emit glfw.ErrorCode.FeatureUnavailable.
///
/// Possible errors include glfw.ErrorCode.InvalidValue, glfw.ErrorCode.FeatureUnavailable
///
/// @thread_safety This function must only be called from the main thread.
///
/// see also: window_icon
pub inline fn setIcon(self: Window, allocator: mem.Allocator, images: ?[]const Image) mem.Allocator.Error!void {
internal_debug.assertInitialized();
if (images) |im| {
const tmp = try allocator.alloc(c.GLFWimage, im.len);
defer allocator.free(tmp);
for (im, 0..) |img, index| tmp[index] = img.toC();
c.glfwSetWindowIcon(self.handle, @as(c_int, @intCast(im.len)), &tmp[0]);
} else c.glfwSetWindowIcon(self.handle, 0, null);
}
pub const Pos = struct {
x: i64,
y: i64,
};
/// Retrieves the position of the content area of the specified window.
///
/// This function retrieves the position, in screen coordinates, of the upper-left corner of the
/// content area of the specified window.
///
/// Possible errors include glfw.ErrorCode.FeatureUnavailable.
/// Additionally returns a zero value in the event of an error.
///
/// wayland: There is no way for an application to retrieve the global position of its windows,
/// this function will always emit glfw.ErrorCode.FeatureUnavailable.
///
/// @thread_safety This function must only be called from the main thread.
///
/// see also: window_pos glfw.Window.setPos
pub inline fn getPos(self: Window) Pos {
internal_debug.assertInitialized();
var x: c_int = 0;
var y: c_int = 0;
c.glfwGetWindowPos(self.handle, &x, &y);
return Pos{ .x = @as(i64, @intCast(x)), .y = @as(i64, @intCast(y)) };
}
/// Sets the position of the content area of the specified window.
///
/// This function sets the position, in screen coordinates, of the upper-left corner of the content
/// area of the specified windowed mode window. If the window is a full screen window, this
/// function does nothing.
///
/// __Do not use this function__ to move an already visible window unless you have very good
/// reasons for doing so, as it will confuse and annoy the user.
///
/// The window manager may put limits on what positions are allowed. GLFW cannot and should not
/// override these limits.
///
/// Possible errors include glfw.ErrorCode.FeatureUnavailable.
///
/// wayland: There is no way for an application to set the global position of its windows, this
/// function will always emit glfw.ErrorCode.FeatureUnavailable.
///
/// @thread_safety This function must only be called from the main thread.
///
/// see also: window_pos, glfw.Window.getPos
pub inline fn setPos(self: Window, pos: Pos) void {
internal_debug.assertInitialized();
c.glfwSetWindowPos(self.handle, @as(c_int, @intCast(pos.x)), @as(c_int, @intCast(pos.y)));
}
pub const Size = struct {
width: u32,
height: u32,
};
/// Retrieves the size of the content area of the specified window.
///
/// This function retrieves the size, in screen coordinates, of the content area of the specified
/// window. If you wish to retrieve the size of the framebuffer of the window in pixels, see
/// glfw.Window.getFramebufferSize.
///
/// Possible errors include glfw.ErrorCode.PlatformError.
/// Additionally returns a zero value in the event of an error.
///
/// @thread_safety This function must only be called from the main thread.
///
/// see also: window_size, glfw.Window.setSize
pub inline fn getSize(self: Window) Size {
internal_debug.assertInitialized();
var width: c_int = 0;
var height: c_int = 0;
c.glfwGetWindowSize(self.handle, &width, &height);
return Size{ .width = @as(u32, @intCast(width)), .height = @as(u32, @intCast(height)) };
}
/// Sets the size of the content area of the specified window.
///
/// This function sets the size, in screen coordinates, of the content area of the specified window.
///
/// For full screen windows, this function updates the resolution of its desired video mode and
/// switches to the video mode closest to it, without affecting the window's context. As the
/// context is unaffected, the bit depths of the framebuffer remain unchanged.
///
/// If you wish to update the refresh rate of the desired video mode in addition to its resolution,
/// see glfw.Window.setMonitor.
///
/// The window manager may put limits on what sizes are allowed. GLFW cannot and should not
/// override these limits.
///
/// Possible errors include glfw.ErrorCode.PlatformError.
///
/// wayland: A full screen window will not attempt to change the mode, no matter what the requested
/// size.
///
/// @thread_safety This function must only be called from the main thread.
///
/// see also: window_size, glfw.Window.getSize, glfw.Window.SetMonitor
pub inline fn setSize(self: Window, size: Size) void {
internal_debug.assertInitialized();
c.glfwSetWindowSize(self.handle, @as(c_int, @intCast(size.width)), @as(c_int, @intCast(size.height)));
}
/// A size with option width/height, used to represent e.g. constraints on a windows size while
/// allowing specific axis to be unconstrained (null) if desired.
pub const SizeOptional = struct {
width: ?u32 = null,
height: ?u32 = null,
};
/// Sets the size limits of the specified window's content area.
///
/// This function sets the size limits of the content area of the specified window. If the window
/// is full screen, the size limits only take effect/ once it is made windowed. If the window is not
/// resizable, this function does nothing.
///
/// The size limits are applied immediately to a windowed mode window and may cause it to be resized.
///
/// The maximum dimensions must be greater than or equal to the minimum dimensions. glfw.dont_care
/// may be used for any width/height parameter.
///
/// Possible errors include glfw.ErrorCode.InvalidValue and glfw.ErrorCode.PlatformError.
///
/// If you set size limits and an aspect ratio that conflict, the results are undefined.
///
/// wayland: The size limits will not be applied until the window is actually resized, either by
/// the user or by the compositor.
///
/// @thread_safety This function must only be called from the main thread.
///
/// see also: window_sizelimits, glfw.Window.setAspectRatio
pub inline fn setSizeLimits(self: Window, min: SizeOptional, max: SizeOptional) void {
internal_debug.assertInitialized();
if (min.width != null and max.width != null) {
std.debug.assert(min.width.? <= max.width.?);
}
if (min.height != null and max.height != null) {
std.debug.assert(min.height.? <= max.height.?);
}
c.glfwSetWindowSizeLimits(
self.handle,
if (min.width) |min_width| @as(c_int, @intCast(min_width)) else glfw.dont_care,
if (min.height) |min_height| @as(c_int, @intCast(min_height)) else glfw.dont_care,
if (max.width) |max_width| @as(c_int, @intCast(max_width)) else glfw.dont_care,
if (max.height) |max_height| @as(c_int, @intCast(max_height)) else glfw.dont_care,
);
}
/// Sets the aspect ratio of the specified window.
///
/// This function sets the required aspect ratio of the content area of the specified window. If
/// the window is full screen, the aspect ratio only takes effect once it is made windowed. If the
/// window is not resizable, this function does nothing.
///
/// The aspect ratio is specified as a numerator and a denominator and both values must be greater
/// than zero. For example, the common 16:9 aspect ratio is specified as 16 and 9, respectively.
///
/// If the numerator AND denominator is set to `glfw.dont_care` then the aspect ratio limit is
/// disabled.
///
/// The aspect ratio is applied immediately to a windowed mode window and may cause it to be
/// resized.
///
/// Possible errors include glfw.ErrorCode.InvalidValue and glfw.ErrorCode.PlatformError.
///
/// If you set size limits and an aspect ratio that conflict, the results are undefined.
///
/// wayland: The aspect ratio will not be applied until the window is actually resized, either by
/// the user or by the compositor.
///
/// @thread_safety This function must only be called from the main thread.
///
/// see also: window_sizelimits, glfw.Window.setSizeLimits
///
/// WARNING: on wayland it will return glfw.ErrorCode.FeatureUnimplemented
pub inline fn setAspectRatio(self: Window, numerator: ?u32, denominator: ?u32) void {
internal_debug.assertInitialized();
if (numerator != null and denominator != null) {
std.debug.assert(numerator.? > 0);
std.debug.assert(denominator.? > 0);
}
c.glfwSetWindowAspectRatio(
self.handle,
if (numerator) |numerator_unwrapped| @as(c_int, @intCast(numerator_unwrapped)) else glfw.dont_care,
if (denominator) |denominator_unwrapped| @as(c_int, @intCast(denominator_unwrapped)) else glfw.dont_care,
);
}
/// Retrieves the size of the framebuffer of the specified window.
///
/// This function retrieves the size, in pixels, of the framebuffer of the specified window. If you
/// wish to retrieve the size of the window in screen coordinates, see @ref glfwGetWindowSize.
///
/// Possible errors include glfw.ErrorCode.PlatformError.
/// Additionally returns a zero value in the event of an error.
///
/// @thread_safety This function must only be called from the main thread.
///
/// see also: window_fbsize, glfwWindow.setFramebufferSizeCallback
pub inline fn getFramebufferSize(self: Window) Size {
internal_debug.assertInitialized();
var width: c_int = 0;
var height: c_int = 0;
c.glfwGetFramebufferSize(self.handle, &width, &height);
return Size{ .width = @as(u32, @intCast(width)), .height = @as(u32, @intCast(height)) };
}
pub const FrameSize = struct {
left: u32,
top: u32,
right: u32,
bottom: u32,
};
/// Retrieves the size of the frame of the window.
///
/// This function retrieves the size, in screen coordinates, of each edge of the frame of the
/// specified window. This size includes the title bar, if the window has one. The size of the
/// frame may vary depending on the window-related hints used to create it.
///
/// Because this function retrieves the size of each window frame edge and not the offset along a
/// particular coordinate axis, the retrieved values will always be zero or positive.
///
/// Possible errors include glfw.ErrorCode.PlatformError.
/// Additionally returns a zero value in the event of an error.
///
/// @thread_safety This function must only be called from the main thread.
///
/// see also: window_size
pub inline fn getFrameSize(self: Window) FrameSize {
internal_debug.assertInitialized();
var left: c_int = 0;
var top: c_int = 0;
var right: c_int = 0;
var bottom: c_int = 0;
c.glfwGetWindowFrameSize(self.handle, &left, &top, &right, &bottom);
return FrameSize{
.left = @as(u32, @intCast(left)),
.top = @as(u32, @intCast(top)),
.right = @as(u32, @intCast(right)),
.bottom = @as(u32, @intCast(bottom)),
};
}
pub const ContentScale = struct {
x_scale: f32,
y_scale: f32,
};
/// Retrieves the content scale for the specified window.
///
/// This function retrieves the content scale for the specified window. The content scale is the
/// ratio between the current DPI and the platform's default DPI. This is especially important for
/// text and any UI elements. If the pixel dimensions of your UI scaled by this look appropriate on
/// your machine then it should appear at a reasonable size on other machines regardless of their
/// DPI and scaling settings. This relies on the system DPI and scaling settings being somewhat
/// correct.
///
/// On platforms where each monitors can have its own content scale, the window content scale will
/// depend on which monitor the system considers the window to be on.
///
/// Possible errors include glfw.ErrorCode.PlatformError.
/// Additionally returns a zero value in the event of an error.
///
/// @thread_safety This function must only be called from the main thread.
///
/// see also: window_scale, glfwSetWindowContentScaleCallback, glfwGetMonitorContentScale
pub inline fn getContentScale(self: Window) ContentScale {
internal_debug.assertInitialized();
var x_scale: f32 = 0;
var y_scale: f32 = 0;
c.glfwGetWindowContentScale(self.handle, &x_scale, &y_scale);
return ContentScale{ .x_scale = x_scale, .y_scale = y_scale };
}
/// Returns the opacity of the whole window.
///
/// This function returns the opacity of the window, including any decorations.
///
/// The opacity (or alpha) value is a positive finite number between zero and one, where zero is
/// fully transparent and one is fully opaque. If the system does not support whole window
/// transparency, this function always returns one.
///
/// The initial opacity value for newly created windows is one.
///
/// Possible errors include glfw.ErrorCode.PlatformError.
/// Additionally returns a zero value in the event of an error.
///
/// @thread_safety This function must only be called from the main thread.
///
/// see also: window_transparency, glfw.Window.setOpacity
pub inline fn getOpacity(self: Window) f32 {
internal_debug.assertInitialized();
const opacity = c.glfwGetWindowOpacity(self.handle);
return opacity;
}
/// Sets the opacity of the whole window.
///
/// This function sets the opacity of the window, including any decorations.
///
/// The opacity (or alpha) value is a positive finite number between zero and one, where zero is
/// fully transparent and one is fully opaque.
///
/// The initial opacity value for newly created windows is one.
///
/// A window created with framebuffer transparency may not use whole window transparency. The
/// results of doing this are undefined.
///
/// @thread_safety This function must only be called from the main thread.
///
/// see also: window_transparency, glfw.Window.getOpacity
pub inline fn setOpacity(self: Window, opacity: f32) void {
internal_debug.assertInitialized();
c.glfwSetWindowOpacity(self.handle, opacity);
}
/// Iconifies the specified window.
///
/// This function iconifies (minimizes) the specified window if it was previously restored. If the
/// window is already iconified, this function does nothing.
///
/// If the specified window is a full screen window, GLFW restores the original video mode of the
/// monitor. The window's desired video mode is set again when the window is restored.
///
/// Possible errors include glfw.ErrorCode.PlatformError.
///
/// wayland: Once a window is iconified, glfw.Window.restorebe able to restore it. This is a design
/// decision of the xdg-shell protocol.
///
/// @thread_safety This function must only be called from the main thread.
///
/// see also: window_iconify, glfw.Window.restore, glfw.Window.maximize
pub inline fn iconify(self: Window) void {
internal_debug.assertInitialized();
c.glfwIconifyWindow(self.handle);
}
/// Restores the specified window.
///
/// This function restores the specified window if it was previously iconified (minimized) or
/// maximized. If the window is already restored, this function does nothing.
///
/// If the specified window is an iconified full screen window, its desired video mode is set
/// again for its monitor when the window is restored.
///
/// Possible errors include glfw.ErrorCode.PlatformError.
///
/// @thread_safety This function must only be called from the main thread.
///
/// see also: window_iconify, glfw.Window.iconify, glfw.Window.maximize
pub inline fn restore(self: Window) void {
internal_debug.assertInitialized();
c.glfwRestoreWindow(self.handle);
}
/// Maximizes the specified window.
///
/// This function maximizes the specified window if it was previously not maximized. If the window
/// is already maximized, this function does nothing.
///
/// If the specified window is a full screen window, this function does nothing.
///
/// Possible errors include glfw.ErrorCode.PlatformError.
///
/// @thread_safety This function must only be called from the main thread.
///
/// see also: window_iconify, glfw.Window.iconify, glfw.Window.restore
pub inline fn maximize(self: Window) void {
internal_debug.assertInitialized();
c.glfwMaximizeWindow(self.handle);
}
/// Makes the specified window visible.
///
/// This function makes the specified window visible if it was previously hidden. If the window is
/// already visible or is in full screen mode, this function does nothing.
///
/// By default, windowed mode windows are focused when shown Set the glfw.focus_on_show window hint
/// to change this behavior for all newly created windows, or change the
/// behavior for an existing window with glfw.Window.setAttrib.
///
/// wayland: Because Wayland wants every frame of the desktop to be complete, this function does
/// not immediately make the window visible. Instead it will become visible the next time the window
/// framebuffer is updated after this call.
///
/// @thread_safety This function must only be called from the main thread.
///
/// see also: window_hide, glfw.Window.hide
///
/// WARNING: on wayland it will return glfw.ErrorCode.FeatureUnavailable
pub inline fn show(self: Window) void {
internal_debug.assertInitialized();
c.glfwShowWindow(self.handle);
}
/// Hides the specified window.
///
/// This function hides the specified window if it was previously visible. If the window is already
/// hidden or is in full screen mode, this function does nothing.
///
/// Possible errors include glfw.ErrorCode.PlatformError.
///
/// @thread_safety This function must only be called from the main thread.
///
/// see also: window_hide, glfw.Window.show
pub inline fn hide(self: Window) void {
internal_debug.assertInitialized();
c.glfwHideWindow(self.handle);
}
/// Brings the specified window to front and sets input focus.
///
/// This function brings the specified window to front and sets input focus. The window should
/// already be visible and not iconified.
///
/// By default, both windowed and full screen mode windows are focused when initially created. Set
/// the glfw.focused to disable this behavior.
///
/// Also by default, windowed mode windows are focused when shown with glfw.Window.show. Set the
/// glfw.focus_on_show to disable this behavior.
///
/// __Do not use this function__ to steal focus from other applications unless you are certain that
/// is what the user wants. Focus stealing can be extremely disruptive.
///
/// For a less disruptive way of getting the user's attention, see [attention requests (window_attention).
///
/// wayland It is not possible for an application to set the input focus. This function will emit
/// glfw.ErrorCode.FeatureUnavailable.
///
/// @thread_safety This function must only be called from the main thread.
///
/// see also: window_focus, window_attention
pub inline fn focus(self: Window) void {
internal_debug.assertInitialized();
c.glfwFocusWindow(self.handle);
}
/// Requests user attention to the specified window.
///
/// This function requests user attention to the specified window. On platforms where this is not
/// supported, attention is requested to the application as a whole.
///
/// Once the user has given attention, usually by focusing the window or application, the system will end the request automatically.
///
/// Possible errors include glfw.ErrorCode.PlatformError.
///
/// macos: Attention is requested to the application as a whole, not the
/// specific window.
///
/// @thread_safety This function must only be called from the main thread.
///
/// see also: window_attention
///
/// WARNING: on wayland it will return glfw.ErrorCode.FeatureUnimplemented
pub inline fn requestAttention(self: Window) void {
internal_debug.assertInitialized();
c.glfwRequestWindowAttention(self.handle);
}
/// Swaps the front and back buffers of the specified window.
///
/// This function swaps the front and back buffers of the specified window when rendering with
/// OpenGL or OpenGL ES. If the swap interval is greater than zero, the GPU driver waits the
/// specified number of screen updates before swapping the buffers.
///
/// The specified window must have an OpenGL or OpenGL ES context. Specifying a window without a
/// context will generate glfw.ErrorCode.NoWindowContext.
///
/// This function does not apply to Vulkan. If you are rendering with Vulkan, see `vkQueuePresentKHR`
/// instead.
///
/// @param[in] window The window whose buffers to swap.
///
/// Possible errors include glfw.ErrorCode.NoWindowContext and glfw.ErrorCode.PlatformError.
///
/// __EGL:__ The context of the specified window must be current on the calling thread.
///
/// @thread_safety This function may be called from any thread.
///
/// see also: buffer_swap, glfwSwapInterval
pub inline fn swapBuffers(self: Window) void {
internal_debug.assertInitialized();
c.glfwSwapBuffers(self.handle);
}
/// Returns the monitor that the window uses for full screen mode.
///
/// This function returns the handle of the monitor that the specified window is in full screen on.
///
/// @return The monitor, or null if the window is in windowed mode.
///
/// @thread_safety This function must only be called from the main thread.
///
/// see also: window_monitor, glfw.Window.setMonitor
pub inline fn getMonitor(self: Window) ?Monitor {
internal_debug.assertInitialized();
if (c.glfwGetWindowMonitor(self.handle)) |monitor| return Monitor{ .handle = monitor };
return null;
}
/// Sets the mode, monitor, video mode and placement of a window.
///
/// This function sets the monitor that the window uses for full screen mode or, if the monitor is
/// null, makes it windowed mode.
///
/// When setting a monitor, this function updates the width, height and refresh rate of the desired
/// video mode and switches to the video mode closest to it. The window position is ignored when
/// setting a monitor.
///
/// When the monitor is null, the position, width and height are used to place the window content
/// area. The refresh rate is ignored when no monitor is specified.
///
/// If you only wish to update the resolution of a full screen window or the size of a windowed
/// mode window, see @ref glfwSetWindowSize.
///
/// When a window transitions from full screen to windowed mode, this function restores any
/// previous window settings such as whether it is decorated, floating, resizable, has size or
/// aspect ratio limits, etc.
///
/// @param[in] window The window whose monitor, size or video mode to set.
/// @param[in] monitor The desired monitor, or null to set windowed mode.
/// @param[in] xpos The desired x-coordinate of the upper-left corner of the content area.
/// @param[in] ypos The desired y-coordinate of the upper-left corner of the content area.
/// @param[in] width The desired with, in screen coordinates, of the content area or video mode.
/// @param[in] height The desired height, in screen coordinates, of the content area or video mode.
/// @param[in] refreshRate The desired refresh rate, in Hz, of the video mode, or `glfw.dont_care`.
///
/// Possible errors include glfw.ErrorCode.PlatformError.
///
/// The OpenGL or OpenGL ES context will not be destroyed or otherwise affected by any resizing or
/// mode switching, although you may need to update your viewport if the framebuffer size has
/// changed.
///
/// wayland: The desired window position is ignored, as there is no way for an application to set
/// this property.
///
/// wayland: Setting the window to full screen will not attempt to change the mode, no matter what
/// the requested size or refresh rate.
///
/// @thread_safety This function must only be called from the main thread.
///
/// see also: window_monitor, window_full_screen, glfw.Window.getMonitor, glfw.Window.setSize
pub inline fn setMonitor(self: Window, monitor: ?Monitor, xpos: i32, ypos: i32, width: u32, height: u32, refresh_rate: ?u32) void {
internal_debug.assertInitialized();
c.glfwSetWindowMonitor(
self.handle,
if (monitor) |m| m.handle else null,
@as(c_int, @intCast(xpos)),
@as(c_int, @intCast(ypos)),
@as(c_int, @intCast(width)),
@as(c_int, @intCast(height)),
if (refresh_rate) |refresh_rate_unwrapped| @as(c_int, @intCast(refresh_rate_unwrapped)) else glfw.dont_care,
);
}
/// Window attributes
pub const Attrib = enum(c_int) {
iconified = c.GLFW_ICONIFIED,
resizable = c.GLFW_RESIZABLE,
visible = c.GLFW_VISIBLE,
decorated = c.GLFW_DECORATED,
focused = c.GLFW_FOCUSED,
auto_iconify = c.GLFW_AUTO_ICONIFY,
floating = c.GLFW_FLOATING,
maximized = c.GLFW_MAXIMIZED,
transparent_framebuffer = c.GLFW_TRANSPARENT_FRAMEBUFFER,
hovered = c.GLFW_HOVERED,
focus_on_show = c.GLFW_FOCUS_ON_SHOW,
mouse_passthrough = c.GLFW_MOUSE_PASSTHROUGH,
doublebuffer = c.GLFW_DOUBLEBUFFER,
client_api = c.GLFW_CLIENT_API,
context_creation_api = c.GLFW_CONTEXT_CREATION_API,
context_version_major = c.GLFW_CONTEXT_VERSION_MAJOR,
context_version_minor = c.GLFW_CONTEXT_VERSION_MINOR,
context_revision = c.GLFW_CONTEXT_REVISION,
context_robustness = c.GLFW_CONTEXT_ROBUSTNESS,
context_release_behavior = c.GLFW_CONTEXT_RELEASE_BEHAVIOR,
context_no_error = c.GLFW_CONTEXT_NO_ERROR,
context_debug = c.GLFW_CONTEXT_DEBUG,
opengl_forward_compat = c.GLFW_OPENGL_FORWARD_COMPAT,
opengl_profile = c.GLFW_OPENGL_PROFILE,
};
/// Returns an attribute of the specified window.
///
/// This function returns the value of an attribute of the specified window or its OpenGL or OpenGL
/// ES context.
///
/// @param[in] attrib The window attribute (see window_attribs) whose value to return.
/// @return The value of the attribute, or zero if an error occurred.
///
/// Possible errors include glfw.ErrorCode.InvalidEnum and glfw.ErrorCode.PlatformError.
/// Additionally returns a zero value in the event of an error.
///
/// Framebuffer related hints are not window attributes. See window_attribs_fb for more information.
///
/// Zero is a valid value for many window and context related attributes so you cannot use a return
/// value of zero as an indication of errors. However, this function should not fail as long as it
/// is passed valid arguments and the library has been initialized.
///
/// @thread_safety This function must only be called from the main thread.
///
/// wayland: The Wayland protocol provides no way to check whether a window is iconified, so
/// glfw.Window.Attrib.iconified always returns `false`.
///
/// see also: window_attribs, glfw.Window.setAttrib
pub inline fn getAttrib(self: Window, attrib: Attrib) i32 {
internal_debug.assertInitialized();
return c.glfwGetWindowAttrib(self.handle, @intFromEnum(attrib));
}
/// Sets an attribute of the specified window.
///
/// This function sets the value of an attribute of the specified window.
///
/// The supported attributes are glfw.decorated, glfw.resizable, glfw.floating, glfw.auto_iconify,
/// glfw.focus_on_show.
///
/// Some of these attributes are ignored for full screen windows. The new value will take effect
/// if the window is later made windowed.
///
/// Some of these attributes are ignored for windowed mode windows. The new value will take effect
/// if the window is later made full screen.
///
/// @param[in] attrib A supported window attribute.
///
/// Possible errors include glfw.ErrorCode.InvalidEnum, glfw.ErrorCode.InvalidValue,
/// glfw.ErrorCode.PlatformError, glfw.ErrorCode.FeatureUnavailable
///
/// Calling glfw.Window.getAttrib will always return the latest
/// value, even if that value is ignored by the current mode of the window.
///
/// @thread_safety This function must only be called from the main thread.
///
/// see also: window_attribs, glfw.Window.getAttrib
///
pub inline fn setAttrib(self: Window, attrib: Attrib, value: bool) void {
internal_debug.assertInitialized();
std.debug.assert(switch (attrib) {
.decorated,
.resizable,
.floating,
.auto_iconify,
.focus_on_show,
.mouse_passthrough,
.doublebuffer,
=> true,
else => false,
});
c.glfwSetWindowAttrib(self.handle, @intFromEnum(attrib), if (value) c.GLFW_TRUE else c.GLFW_FALSE);
}
/// Sets the user pointer of the specified window.
///
/// This function sets the user-defined pointer of the specified window. The current value is
/// retained until the window is destroyed. The initial value is null.
///
/// @thread_safety This function may be called from any thread. Access is not synchronized.
///
/// see also: window_userptr, glfw.Window.getUserPointer
pub inline fn setUserPointer(self: Window, pointer: ?*anyopaque) void {
internal_debug.assertInitialized();
c.glfwSetWindowUserPointer(self.handle, pointer);
}
/// Returns the user pointer of the specified window.
///
/// This function returns the current value of the user-defined pointer of the specified window.
/// The initial value is null.
///
/// @thread_safety This function may be called from any thread. Access is not synchronized.
///
/// see also: window_userptr, glfw.Window.setUserPointer
pub inline fn getUserPointer(self: Window, comptime T: type) ?*T {
internal_debug.assertInitialized();
if (c.glfwGetWindowUserPointer(self.handle)) |user_pointer| return @as(?*T, @ptrCast(@alignCast(user_pointer)));
return null;
}
/// Sets the position callback for the specified window.
///
/// This function sets the position callback of the specified window, which is called when the
/// window is moved. The callback is provided with the position, in screen coordinates, of the
/// upper-left corner of the content area of the window.
///
/// @param[in] callback The new callback, or null to remove the currently set callback.
///
/// @callback_param `window` the window that moved.
/// @callback_param `xpos` the new x-coordinate, in screen coordinates, of the upper-left corner of
/// the content area of the window.
/// @callback_param `ypos` the new y-coordinate, in screen coordinates, of the upper-left corner of
/// the content area of the window.
///
/// wayland: This callback will never be called, as there is no way for an application to know its
/// global position.
///
/// @thread_safety This function must only be called from the main thread.
///
/// see also: window_pos
pub inline fn setPosCallback(self: Window, comptime callback: ?fn (window: Window, xpos: i32, ypos: i32) void) void {
internal_debug.assertInitialized();
if (callback) |user_callback| {
const CWrapper = struct {
pub fn posCallbackWrapper(handle: ?*c.GLFWwindow, xpos: c_int, ypos: c_int) callconv(.C) void {
@call(.always_inline, user_callback, .{
from(handle.?),
@as(i32, @intCast(xpos)),
@as(i32, @intCast(ypos)),
});
}
};
if (c.glfwSetWindowPosCallback(self.handle, CWrapper.posCallbackWrapper) != null) return;
} else {
if (c.glfwSetWindowPosCallback(self.handle, null) != null) return;
}
}
/// Sets the size callback for the specified window.
///
/// This function sets the size callback of the specified window, which is called when the window
/// is resized. The callback is provided with the size, in screen coordinates, of the content area
/// of the window.
///
/// @callback_param `window` the window that was resized.
/// @callback_param `width` the new width, in screen coordinates, of the window.
/// @callback_param `height` the new height, in screen coordinates, of the window.
///
/// @thread_safety This function must only be called from the main thread.
///
/// see also: window_size
pub inline fn setSizeCallback(self: Window, comptime callback: ?fn (window: Window, width: i32, height: i32) void) void {
internal_debug.assertInitialized();
if (callback) |user_callback| {
const CWrapper = struct {
pub fn sizeCallbackWrapper(handle: ?*c.GLFWwindow, width: c_int, height: c_int) callconv(.C) void {
@call(.always_inline, user_callback, .{
from(handle.?),
@as(i32, @intCast(width)),
@as(i32, @intCast(height)),
});
}
};
if (c.glfwSetWindowSizeCallback(self.handle, CWrapper.sizeCallbackWrapper) != null) return;
} else {
if (c.glfwSetWindowSizeCallback(self.handle, null) != null) return;
}
}
/// Sets the close callback for the specified window.
///
/// This function sets the close callback of the specified window, which is called when the user
/// attempts to close the window, for example by clicking the close widget in the title bar.
///
/// The close flag is set before this callback is called, but you can modify it at any time with
/// glfw.Window.setShouldClose.
///
/// The close callback is not triggered by glfw.Window.destroy.
///
/// @param[in] window The window whose callback to set.
/// @param[in] callback The new callback, or null to remove the currently set callback.
///
/// @callback_param `window` the window that the user attempted to close.
///
/// macos: Selecting Quit from the application menu will trigger the close callback for all
/// windows.
///
/// @thread_safety This function must only be called from the main thread.
///
/// see also: window_close
pub inline fn setCloseCallback(self: Window, comptime callback: ?fn (window: Window) void) void {
internal_debug.assertInitialized();
if (callback) |user_callback| {
const CWrapper = struct {
pub fn closeCallbackWrapper(handle: ?*c.GLFWwindow) callconv(.C) void {
@call(.always_inline, user_callback, .{
from(handle.?),
});
}
};
if (c.glfwSetWindowCloseCallback(self.handle, CWrapper.closeCallbackWrapper) != null) return;
} else {
if (c.glfwSetWindowCloseCallback(self.handle, null) != null) return;
}
}
/// Sets the refresh callback for the specified window.
///
/// This function sets the refresh callback of the specified window, which is
/// called when the content area of the window needs to be redrawn, for example
/// if the window has been exposed after having been covered by another window.
///
/// On compositing window systems such as Aero, Compiz, Aqua or Wayland, where
/// the window contents are saved off-screen, this callback may be called only
/// very infrequently or never at all.
///
/// @param[in] window The window whose callback to set.
/// @param[in] callback The new callback, or null to remove the currently set
/// callback.
///
/// @callback_param `window` the window whose content needs to be refreshed.
///
/// @thread_safety This function must only be called from the main thread.
///
/// see also: window_refresh
pub inline fn setRefreshCallback(self: Window, comptime callback: ?fn (window: Window) void) void {
internal_debug.assertInitialized();
if (callback) |user_callback| {
const CWrapper = struct {
pub fn refreshCallbackWrapper(handle: ?*c.GLFWwindow) callconv(.C) void {
@call(.always_inline, user_callback, .{
from(handle.?),
});
}
};
if (c.glfwSetWindowRefreshCallback(self.handle, CWrapper.refreshCallbackWrapper) != null) return;
} else {
if (c.glfwSetWindowRefreshCallback(self.handle, null) != null) return;
}
}
/// Sets the focus callback for the specified window.
///
/// This function sets the focus callback of the specified window, which is
/// called when the window gains or loses input focus.
///
/// After the focus callback is called for a window that lost input focus,
/// synthetic key and mouse button release events will be generated for all such
/// that had been pressed. For more information, see @ref glfwSetKeyCallback
/// and @ref glfwSetMouseButtonCallback.
///
/// @param[in] window The window whose callback to set.
/// @param[in] callback The new callback, or null to remove the currently set
/// callback.
///
/// @callback_param `window` the window whose input focus has changed.
/// @callback_param `focused` `true` if the window was given input focus, or `false` if it lost it.
///
/// @thread_safety This function must only be called from the main thread.
///
/// see also: window_focus
pub inline fn setFocusCallback(self: Window, comptime callback: ?fn (window: Window, focused: bool) void) void {
internal_debug.assertInitialized();
if (callback) |user_callback| {
const CWrapper = struct {
pub fn focusCallbackWrapper(handle: ?*c.GLFWwindow, focused: c_int) callconv(.C) void {
@call(.always_inline, user_callback, .{
from(handle.?),
focused == c.GLFW_TRUE,
});
}
};
if (c.glfwSetWindowFocusCallback(self.handle, CWrapper.focusCallbackWrapper) != null) return;
} else {
if (c.glfwSetWindowFocusCallback(self.handle, null) != null) return;
}
}
/// Sets the iconify callback for the specified window.
///
/// This function sets the iconification callback of the specified window, which
/// is called when the window is iconified or restored.
///
/// @param[in] window The window whose callback to set.
/// @param[in] callback The new callback, or null to remove the currently set
/// callback.
///
/// @callback_param `window` the window which was iconified or restored.
/// @callback_param `iconified` `true` if the window was iconified, or `false` if it was restored.
///
/// @thread_safety This function must only be called from the main thread.
///
/// see also: window_iconify
pub inline fn setIconifyCallback(self: Window, comptime callback: ?fn (window: Window, iconified: bool) void) void {
internal_debug.assertInitialized();
if (callback) |user_callback| {
const CWrapper = struct {
pub fn iconifyCallbackWrapper(handle: ?*c.GLFWwindow, iconified: c_int) callconv(.C) void {
@call(.always_inline, user_callback, .{
from(handle.?),
iconified == c.GLFW_TRUE,
});
}
};
if (c.glfwSetWindowIconifyCallback(self.handle, CWrapper.iconifyCallbackWrapper) != null) return;
} else {
if (c.glfwSetWindowIconifyCallback(self.handle, null) != null) return;
}
}
/// Sets the maximize callback for the specified window.
///
/// This function sets the maximization callback of the specified window, which
/// is called when the window is maximized or restored.
///
/// @param[in] window The window whose callback to set.
/// @param[in] callback The new callback, or null to remove the currently set
/// callback.
///
/// @callback_param `window` the window which was maximized or restored.
/// @callback_param `maximized` `true` if the window was maximized, or `false` if it was restored.
///
/// @thread_safety This function must only be called from the main thread.
///
/// see also: window_maximize
// GLFWAPI GLFWwindowmaximizefun glfwSetWindowMaximizeCallback(GLFWwindow* window, GLFWwindowmaximizefun callback);
pub inline fn setMaximizeCallback(self: Window, comptime callback: ?fn (window: Window, maximized: bool) void) void {
internal_debug.assertInitialized();
if (callback) |user_callback| {
const CWrapper = struct {
pub fn maximizeCallbackWrapper(handle: ?*c.GLFWwindow, maximized: c_int) callconv(.C) void {
@call(.always_inline, user_callback, .{
from(handle.?),
maximized == c.GLFW_TRUE,
});
}
};
if (c.glfwSetWindowMaximizeCallback(self.handle, CWrapper.maximizeCallbackWrapper) != null) return;
} else {
if (c.glfwSetWindowMaximizeCallback(self.handle, null) != null) return;
}
}
/// Sets the framebuffer resize callback for the specified window.
///
/// This function sets the framebuffer resize callback of the specified window,
/// which is called when the framebuffer of the specified window is resized.
///
/// @param[in] window The window whose callback to set.
/// @param[in] callback The new callback, or null to remove the currently set
/// callback.
///
/// @callback_param `window` the window whose framebuffer was resized.
/// @callback_param `width` the new width, in pixels, of the framebuffer.
/// @callback_param `height` the new height, in pixels, of the framebuffer.
///
/// @thread_safety This function must only be called from the main thread.
///
/// see also: window_fbsize
pub inline fn setFramebufferSizeCallback(self: Window, comptime callback: ?fn (window: Window, width: u32, height: u32) void) void {
internal_debug.assertInitialized();
if (callback) |user_callback| {
const CWrapper = struct {
pub fn framebufferSizeCallbackWrapper(handle: ?*c.GLFWwindow, width: c_int, height: c_int) callconv(.C) void {
@call(.always_inline, user_callback, .{
from(handle.?),
@as(u32, @intCast(width)),
@as(u32, @intCast(height)),
});
}
};
if (c.glfwSetFramebufferSizeCallback(self.handle, CWrapper.framebufferSizeCallbackWrapper) != null) return;
} else {
if (c.glfwSetFramebufferSizeCallback(self.handle, null) != null) return;
}
}
/// Sets the window content scale callback for the specified window.
///
/// This function sets the window content scale callback of the specified window,
/// which is called when the content scale of the specified window changes.
///
/// @param[in] window The window whose callback to set.
/// @param[in] callback The new callback, or null to remove the currently set
/// callback.
///
/// @callback_param `window` the window whose content scale changed.
/// @callback_param `xscale` the new x-axis content scale of the window.
/// @callback_param `yscale` the new y-axis content scale of the window.
///
/// @thread_safety This function must only be called from the main thread.
///
/// see also: window_scale, glfw.Window.getContentScale
pub inline fn setContentScaleCallback(self: Window, comptime callback: ?fn (window: Window, xscale: f32, yscale: f32) void) void {
internal_debug.assertInitialized();
if (callback) |user_callback| {
const CWrapper = struct {
pub fn windowScaleCallbackWrapper(handle: ?*c.GLFWwindow, xscale: f32, yscale: f32) callconv(.C) void {
@call(.always_inline, user_callback, .{
from(handle.?),
xscale,
yscale,
});
}
};
if (c.glfwSetWindowContentScaleCallback(self.handle, CWrapper.windowScaleCallbackWrapper) != null) return;
} else {
if (c.glfwSetWindowContentScaleCallback(self.handle, null) != null) return;
}
}
pub const InputMode = enum(c_int) {
cursor = c.GLFW_CURSOR,
sticky_keys = c.GLFW_STICKY_KEYS,
sticky_mouse_buttons = c.GLFW_STICKY_MOUSE_BUTTONS,
lock_key_mods = c.GLFW_LOCK_KEY_MODS,
raw_mouse_motion = c.GLFW_RAW_MOUSE_MOTION,
};
/// A cursor input mode to be supplied to `glfw.Window.setInputModeCursor`
pub const InputModeCursor = enum(c_int) {
/// Makes the cursor visible and behaving normally.
normal = c.GLFW_CURSOR_NORMAL,
/// Makes the cursor invisible when it is over the content area of the window but does not
/// restrict it from leaving.
hidden = c.GLFW_CURSOR_HIDDEN,
/// Hides and grabs the cursor, providing virtual and unlimited cursor movement. This is useful
/// for implementing for example 3D camera controls.
disabled = c.GLFW_CURSOR_DISABLED,
/// Makes the cursor visible but confines it to the content area of the window.
captured = c.GLFW_CURSOR_CAPTURED,
};
/// Sets the input mode of the cursor, whether it should behave normally, be hidden, or grabbed.
pub inline fn setInputModeCursor(self: Window, value: InputModeCursor) void {
if (value == .disabled) {
self.setInputMode(.cursor, value);
return self.setInputMode(.raw_mouse_motion, true);
}
self.setInputMode(.cursor, value);
return self.setInputMode(.raw_mouse_motion, false);
}
/// Gets the current input mode of the cursor.
pub inline fn getInputModeCursor(self: Window) InputModeCursor {
return @as(InputModeCursor, @enumFromInt(self.getInputMode(InputMode.cursor)));
}
/// Sets the input mode of sticky keys, if enabled a key press will ensure that `glfw.Window.getKey`
/// return `.press` the next time it is called even if the key had been released before the call.
///
/// This is useful when you are only interested in whether keys have been pressed but not when or
/// in which order.
pub inline fn setInputModeStickyKeys(self: Window, enabled: bool) void {
return self.setInputMode(InputMode.sticky_keys, enabled);
}
/// Tells if the sticky keys input mode is enabled.
pub inline fn getInputModeStickyKeys(self: Window) bool {
return self.getInputMode(InputMode.sticky_keys) == 1;
}
/// Sets the input mode of sticky mouse buttons, if enabled a mouse button press will ensure that
/// `glfw.Window.getMouseButton` return `.press` the next time it is called even if the button had
/// been released before the call.
///
/// This is useful when you are only interested in whether buttons have been pressed but not when
/// or in which order.
pub inline fn setInputModeStickyMouseButtons(self: Window, enabled: bool) void {
return self.setInputMode(InputMode.sticky_mouse_buttons, enabled);
}
/// Tells if the sticky mouse buttons input mode is enabled.
pub inline fn getInputModeStickyMouseButtons(self: Window) bool {
return self.getInputMode(InputMode.sticky_mouse_buttons) == 1;
}
/// Sets the input mode of locking key modifiers, if enabled callbacks that receive modifier bits
/// will also have the glfw.mod.caps_lock bit set when the event was generated with Caps Lock on,
/// and the glfw.mod.num_lock bit when Num Lock was on.
pub inline fn setInputModeLockKeyMods(self: Window, enabled: bool) void {
return self.setInputMode(InputMode.lock_key_mods, enabled);
}
/// Tells if the locking key modifiers input mode is enabled.
pub inline fn getInputModeLockKeyMods(self: Window) bool {
return self.getInputMode(InputMode.lock_key_mods) == 1;
}
/// Sets whether the raw mouse motion input mode is enabled, if enabled unscaled and unaccelerated
/// mouse motion events will be sent, otherwise standard mouse motion events respecting the user's
/// OS settings will be sent.
///
/// If raw motion is not supported, attempting to set this will emit glfw.ErrorCode.FeatureUnavailable.
/// Call glfw.rawMouseMotionSupported to check for support.
pub inline fn setInputModeRawMouseMotion(self: Window, enabled: bool) void {
return self.setInputMode(InputMode.raw_mouse_motion, enabled);
}
/// Tells if the raw mouse motion input mode is enabled.
pub inline fn getInputModeRawMouseMotion(self: Window) bool {
return self.getInputMode(InputMode.raw_mouse_motion) == 1;
}
/// Returns the value of an input option for the specified window.
///
/// Consider using one of the following variants instead, if applicable, as they'll give you a
/// typed return value:
///
/// * `glfw.Window.getInputModeCursor`
/// * `glfw.Window.getInputModeStickyKeys`
/// * `glfw.Window.getInputModeStickyMouseButtons`
/// * `glfw.Window.getInputModeLockKeyMods`
/// * `glfw.Window.getInputModeRawMouseMotion`
///
/// This function returns the value of an input option for the specified window. The mode must be
/// one of the `glfw.Window.InputMode` enumerations.
///
/// Boolean values, such as for `glfw.Window.InputMode.raw_mouse_motion`, are returned as integers.
/// You may convert to a boolean using `== 1`.
///
/// @thread_safety This function must only be called from the main thread.
///
/// see also: glfw.Window.setInputMode
pub inline fn getInputMode(self: Window, mode: InputMode) i32 {
internal_debug.assertInitialized();
const value = c.glfwGetInputMode(self.handle, @intFromEnum(mode));
return @as(i32, @intCast(value));
}
/// Sets an input option for the specified window.
///
/// Consider using one of the following variants instead, if applicable, as they'll guide you to
/// the right input value via enumerations:
///
/// * `glfw.Window.setInputModeCursor`
/// * `glfw.Window.setInputModeStickyKeys`
/// * `glfw.Window.setInputModeStickyMouseButtons`
/// * `glfw.Window.setInputModeLockKeyMods`
/// * `glfw.Window.setInputModeRawMouseMotion`
///
/// @param[in] mode One of the `glfw.Window.InputMode` enumerations.
/// @param[in] value The new value of the specified input mode.
///
/// @thread_safety This function must only be called from the main thread.
///
/// see also: glfw.Window.getInputMode
pub inline fn setInputMode(self: Window, mode: InputMode, value: anytype) void {
internal_debug.assertInitialized();
const T = @TypeOf(value);
std.debug.assert(switch (mode) {
.cursor => switch (@typeInfo(T)) {
.Enum => T == InputModeCursor,
.EnumLiteral => @hasField(InputModeCursor, @tagName(value)),
else => false,
},
.sticky_keys => T == bool,
.sticky_mouse_buttons => T == bool,
.lock_key_mods => T == bool,
.raw_mouse_motion => T == bool,
});
const int_value: c_int = switch (@typeInfo(T)) {
.Enum,
.EnumLiteral,
=> @intFromEnum(@as(InputModeCursor, value)),
else => @intFromBool(value),
};
c.glfwSetInputMode(self.handle, @intFromEnum(mode), int_value);
}
/// Returns the last reported press state of a keyboard key for the specified window.
///
/// This function returns the last press state reported for the specified key to the specified
/// window. The returned state is one of `true` (pressed) or `false` (released).
///
/// * `glfw.Action.repeat` is only reported to the key callback.
///
/// If the `glfw.sticky_keys` input mode is enabled, this function returns `glfw.Action.press` the
/// first time you call it for a key that was pressed, even if that key has already been released.
///
/// The key functions deal with physical keys, with key tokens (see keys) named after their use on
/// the standard US keyboard layout. If you want to input text, use the Unicode character callback
/// instead.
///
/// The modifier key bit masks (see mods) are not key tokens and cannot be used with this function.
///
/// __Do not use this function__ to implement text input, use glfw.Window.setCharCallback instead.
///
/// @param[in] window The desired window.
/// @param[in] key The desired keyboard key (see keys). `glfw.key.unknown` is not a valid key for
/// this function.
///
/// @thread_safety This function must only be called from the main thread.
///
/// see also: input_key
pub inline fn getKey(self: Window, key: Key) Action {
internal_debug.assertInitialized();
const state = c.glfwGetKey(self.handle, @intFromEnum(key));
return @as(Action, @enumFromInt(state));
}
/// Returns the last reported state of a mouse button for the specified window.
///
/// This function returns whether the specified mouse button is pressed or not.
///
/// If the glfw.sticky_mouse_buttons input mode is enabled, this function returns `true` the first
/// time you call it for a mouse button that was pressed, even if that mouse button has already been
/// released.
///
/// @param[in] button The desired mouse button.
/// @return One of `true` (if pressed) or `false` (if released)
///
/// Possible errors include glfw.ErrorCode.InvalidEnum.
///
/// @thread_safety This function must only be called from the main thread.
///
/// see also: input_mouse_button
pub inline fn getMouseButton(self: Window, button: MouseButton) Action {
internal_debug.assertInitialized();
const state = c.glfwGetMouseButton(self.handle, @intFromEnum(button));
return @as(Action, @enumFromInt(state));
}
pub const CursorPos = struct {
xpos: f64,
ypos: f64,
};
/// Retrieves the position of the cursor relative to the content area of the window.
///
/// This function returns the position of the cursor, in screen coordinates, relative to the
/// upper-left corner of the content area of the specified window.
///
/// If the cursor is disabled (with `glfw.cursor_disabled`) then the cursor position is unbounded
/// and limited only by the minimum and maximum values of a `f64`.
///
/// The coordinate can be converted to their integer equivalents with the `floor` function. Casting
/// directly to an integer type works for positive coordinates, but fails for negative ones.
///
/// Any or all of the position arguments may be null. If an error occurs, all non-null position
/// arguments will be set to zero.
///
/// @param[in] window The desired window.
/// @param[out] xpos Where to store the cursor x-coordinate, relative to the left edge of the
/// content area, or null.
/// @param[out] ypos Where to store the cursor y-coordinate, relative to the to top edge of the
/// content area, or null.
///
/// Possible errors include glfw.ErrorCode.PlatformError.
/// Additionally returns a zero value in the event of an error.
///
/// @thread_safety This function must only be called from the main thread.
///
/// see also: cursor_pos, glfw.Window.setCursorPos
pub inline fn getCursorPos(self: Window) CursorPos {
internal_debug.assertInitialized();
var pos: CursorPos = undefined;
c.glfwGetCursorPos(self.handle, &pos.xpos, &pos.ypos);
return pos;
}
/// Sets the position of the cursor, relative to the content area of the window.
///
/// This function sets the position, in screen coordinates, of the cursor relative to the upper-left
/// corner of the content area of the specified window. The window must have input focus. If the
/// window does not have input focus when this function is called, it fails silently.
///
/// __Do not use this function__ to implement things like camera controls. GLFW already provides the
/// `glfw.cursor_disabled` cursor mode that hides the cursor, transparently re-centers it and
/// provides unconstrained cursor motion. See glfw.Window.setInputMode for more information.
///
/// If the cursor mode is `glfw.cursor_disabled` then the cursor position is unconstrained and
/// limited only by the minimum and maximum values of a `double`.
///
/// @param[in] window The desired window.
/// @param[in] xpos The desired x-coordinate, relative to the left edge of the content area.
/// @param[in] ypos The desired y-coordinate, relative to the top edge of the content area.
///
/// Possible errors include glfw.ErrorCode.PlatformError, glfw.ErrorCode.FeatureUnavailable.
///
/// wayland: This function will only work when the cursor mode is `glfw.cursor_disabled`, otherwise
/// it will do nothing.
///
/// @thread_safety This function must only be called from the main thread.
///
/// see also: cursor_pos, glfw.Window.getCursorPos
pub inline fn setCursorPos(self: Window, xpos: f64, ypos: f64) void {
internal_debug.assertInitialized();
c.glfwSetCursorPos(self.handle, xpos, ypos);
}
/// Sets the cursor for the window.
///
/// This function sets the cursor image to be used when the cursor is over the content area of the
/// specified window. The set cursor will only be visible when the cursor mode (see cursor_mode) of
/// the window is `glfw.Cursor.normal`.
///
/// On some platforms, the set cursor may not be visible unless the window also has input focus.
///
/// @param[in] cursor The cursor to set, or null to switch back to the default arrow cursor.
///
/// Possible errors include glfw.ErrorCode.PlatformError.
///
/// @thread_safety This function must only be called from the main thread.
///
/// see also: cursor_object
pub inline fn setCursor(self: Window, cursor: ?Cursor) void {
internal_debug.assertInitialized();
c.glfwSetCursor(self.handle, if (cursor) |cs| cs.ptr else null);
}
/// Sets the key callback.
///
/// This function sets the key callback of the specified window, which is called when a key is
/// pressed, repeated or released.
///
/// The key functions deal with physical keys, with layout independent key tokens (see keys) named
/// after their values in the standard US keyboard layout. If you want to input text, use the
/// character callback (see glfw.Window.setCharCallback) instead.
///
/// When a window loses input focus, it will generate synthetic key release events for all pressed
/// keys. You can tell these events from user-generated events by the fact that the synthetic ones
/// are generated after the focus loss event has been processed, i.e. after the window focus
/// callback (see glfw.Window.setFocusCallback) has been called.
///
/// The scancode of a key is specific to that platform or sometimes even to that machine. Scancodes
/// are intended to allow users to bind keys that don't have a GLFW key token. Such keys have `key`
/// set to `glfw.key.unknown`, their state is not saved and so it cannot be queried with
/// glfw.Window.getKey.
///
/// Sometimes GLFW needs to generate synthetic key events, in which case the scancode may be zero.
///
/// @param[in] window The window whose callback to set.
/// @param[in] callback The new key callback, or null to remove the currently set callback.
///
/// @callback_param[in] window The window that received the event.
/// @callback_param[in] key The keyboard key (see keys) that was pressed or released.
/// @callback_param[in] scancode The platform-specific scancode of the key.
/// @callback_param[in] action `glfw.Action.press`, `glfw.Action.release` or `glfw.Action.repeat`.
/// Future releases may add more actions.
/// @callback_param[in] mods Bit field describing which modifier keys (see mods) were held down.
///
/// @thread_safety This function must only be called from the main thread.
///
/// see also: input_key
pub inline fn setKeyCallback(self: Window, comptime callback: ?fn (window: Window, key: Key, scancode: i32, action: Action, mods: Mods) void) void {
internal_debug.assertInitialized();
if (callback) |user_callback| {
const CWrapper = struct {
pub fn keyCallbackWrapper(handle: ?*c.GLFWwindow, key: c_int, scancode: c_int, action: c_int, mods: c_int) callconv(.C) void {
@call(.always_inline, user_callback, .{
from(handle.?),
@as(Key, @enumFromInt(key)),
@as(i32, @intCast(scancode)),
@as(Action, @enumFromInt(action)),
Mods.fromInt(mods),
});
}
};
if (c.glfwSetKeyCallback(self.handle, CWrapper.keyCallbackWrapper) != null) return;
} else {
if (c.glfwSetKeyCallback(self.handle, null) != null) return;
}
}
/// Sets the Unicode character callback.
///
/// This function sets the character callback of the specified window, which is called when a
/// Unicode character is input.
///
/// The character callback is intended for Unicode text input. As it deals with characters, it is
/// keyboard layout dependent, whereas the key callback (see glfw.Window.setKeyCallback) is not.
/// Characters do not map 1:1 to physical keys, as a key may produce zero, one or more characters.
/// If you want to know whether a specific physical key was pressed or released, see the key
/// callback instead.
///
/// The character callback behaves as system text input normally does and will not be called if
/// modifier keys are held down that would prevent normal text input on that platform, for example a
/// Super (Command) key on macOS or Alt key on Windows.
///
/// @param[in] window The window whose callback to set.
/// @param[in] callback The new callback, or null to remove the currently set callback.
///
/// @callback_param[in] window The window that received the event.
/// @callback_param[in] codepoint The Unicode code point of the character.
///
/// @thread_safety This function must only be called from the main thread.
///
/// see also: input_char
pub inline fn setCharCallback(self: Window, comptime callback: ?fn (window: Window, codepoint: u21) void) void {
internal_debug.assertInitialized();
if (callback) |user_callback| {
const CWrapper = struct {
pub fn charCallbackWrapper(handle: ?*c.GLFWwindow, codepoint: c_uint) callconv(.C) void {
@call(.always_inline, user_callback, .{
from(handle.?),
@as(u21, @intCast(codepoint)),
});
}
};
if (c.glfwSetCharCallback(self.handle, CWrapper.charCallbackWrapper) != null) return;
} else {
if (c.glfwSetCharCallback(self.handle, null) != null) return;
}
}
/// Sets the mouse button callback.
///
/// This function sets the mouse button callback of the specified window, which is called when a
/// mouse button is pressed or released.
///
/// When a window loses input focus, it will generate synthetic mouse button release events for all
/// pressed mouse buttons. You can tell these events from user-generated events by the fact that the
/// synthetic ones are generated after the focus loss event has been processed, i.e. after the
/// window focus callback (see glfw.Window.setFocusCallback) has been called.
///
/// @param[in] window The window whose callback to set.
/// @param[in] callback The new callback, or null to remove the currently set callback.
///
/// @callback_param[in] window The window that received the event.
/// @callback_param[in] button The mouse button that was pressed or released.
/// @callback_param[in] action One of `glfw.Action.press` or `glfw.Action.release`. Future releases
/// may add more actions.
/// @callback_param[in] mods Bit field describing which modifier keys (see mods) were held down.
///
/// @thread_safety This function must only be called from the main thread.
///
/// see also: input_mouse_button
pub inline fn setMouseButtonCallback(self: Window, comptime callback: ?fn (window: Window, button: MouseButton, action: Action, mods: Mods) void) void {
internal_debug.assertInitialized();
if (callback) |user_callback| {
const CWrapper = struct {
pub fn mouseButtonCallbackWrapper(handle: ?*c.GLFWwindow, button: c_int, action: c_int, mods: c_int) callconv(.C) void {
@call(.always_inline, user_callback, .{
from(handle.?),
@as(MouseButton, @enumFromInt(button)),
@as(Action, @enumFromInt(action)),
Mods.fromInt(mods),
});
}
};
if (c.glfwSetMouseButtonCallback(self.handle, CWrapper.mouseButtonCallbackWrapper) != null) return;
} else {
if (c.glfwSetMouseButtonCallback(self.handle, null) != null) return;
}
}
/// Sets the cursor position callback.
///
/// This function sets the cursor position callback of the specified window, which is called when
/// the cursor is moved. The callback is provided with the position, in screen coordinates, relative
/// to the upper-left corner of the content area of the window.
///
/// @param[in] callback The new callback, or null to remove the currently set callback.
///
/// @callback_param[in] window The window that received the event.
/// @callback_param[in] xpos The new cursor x-coordinate, relative to the left edge of the content
/// area.
/// callback_@param[in] ypos The new cursor y-coordinate, relative to the top edge of the content
/// area.
///
/// @thread_safety This function must only be called from the main thread.
///
/// see also: cursor_pos
pub inline fn setCursorPosCallback(self: Window, comptime callback: ?fn (window: Window, xpos: f64, ypos: f64) void) void {
internal_debug.assertInitialized();
if (callback) |user_callback| {
const CWrapper = struct {
pub fn cursorPosCallbackWrapper(handle: ?*c.GLFWwindow, xpos: f64, ypos: f64) callconv(.C) void {
@call(.always_inline, user_callback, .{
from(handle.?),
xpos,
ypos,
});
}
};
if (c.glfwSetCursorPosCallback(self.handle, CWrapper.cursorPosCallbackWrapper) != null) return;
} else {
if (c.glfwSetCursorPosCallback(self.handle, null) != null) return;
}
}
/// Sets the cursor enter/leave callback.
///
/// This function sets the cursor boundary crossing callback of the specified window, which is
/// called when the cursor enters or leaves the content area of the window.
///
/// @param[in] callback The new callback, or null to remove the currently set callback.
///
/// @callback_param[in] window The window that received the event.
/// @callback_param[in] entered `true` if the cursor entered the window's content area, or `false`
/// if it left it.
///
/// @thread_safety This function must only be called from the main thread.
///
/// see also: cursor_enter
pub inline fn setCursorEnterCallback(self: Window, comptime callback: ?fn (window: Window, entered: bool) void) void {
internal_debug.assertInitialized();
if (callback) |user_callback| {
const CWrapper = struct {
pub fn cursorEnterCallbackWrapper(handle: ?*c.GLFWwindow, entered: c_int) callconv(.C) void {
@call(.always_inline, user_callback, .{
from(handle.?),
entered == c.GLFW_TRUE,
});
}
};
if (c.glfwSetCursorEnterCallback(self.handle, CWrapper.cursorEnterCallbackWrapper) != null) return;
} else {
if (c.glfwSetCursorEnterCallback(self.handle, null) != null) return;
}
}
/// Sets the scroll callback.
///
/// This function sets the scroll callback of the specified window, which is called when a scrolling
/// device is used, such as a mouse wheel or scrolling area of a touchpad.
///
/// The scroll callback receives all scrolling input, like that from a mouse wheel or a touchpad
/// scrolling area.
///
/// @param[in] window The window whose callback to set.
/// @param[in] callback The new scroll callback, or null to remove the currently set callback.
///
/// @callback_param[in] window The window that received the event.
/// @callback_param[in] xoffset The scroll offset along the x-axis.
/// @callback_param[in] yoffset The scroll offset along the y-axis.
///
/// @thread_safety This function must only be called from the main thread.
///
/// see also: scrolling
pub inline fn setScrollCallback(self: Window, comptime callback: ?fn (window: Window, xoffset: f64, yoffset: f64) void) void {
internal_debug.assertInitialized();
if (callback) |user_callback| {
const CWrapper = struct {
pub fn scrollCallbackWrapper(handle: ?*c.GLFWwindow, xoffset: f64, yoffset: f64) callconv(.C) void {
@call(.always_inline, user_callback, .{
from(handle.?),
xoffset,
yoffset,
});
}
};
if (c.glfwSetScrollCallback(self.handle, CWrapper.scrollCallbackWrapper) != null) return;
} else {
if (c.glfwSetScrollCallback(self.handle, null) != null) return;
}
}
/// Sets the path drop callback.
///
/// This function sets the path drop callback of the specified window, which is called when one or
/// more dragged paths are dropped on the window.
///
/// Because the path array and its strings may have been generated specifically for that event, they
/// are not guaranteed to be valid after the callback has returned. If you wish to use them after
/// the callback returns, you need to make a deep copy.
///
/// @param[in] callback The new file drop callback, or null to remove the currently set callback.
///
/// @callback_param[in] window The window that received the event.
/// @callback_param[in] path_count The number of dropped paths.
/// @callback_param[in] paths The UTF-8 encoded file and/or directory path names.
///
/// @callback_pointer_lifetime The path array and its strings are valid until the callback function
/// returns.
///
/// wayland: File drop is currently unimplemented.
///
/// @thread_safety This function must only be called from the main thread.
///
/// see also: path_drop
pub inline fn setDropCallback(self: Window, comptime callback: ?fn (window: Window, paths: [][*:0]const u8) void) void {
internal_debug.assertInitialized();
if (callback) |user_callback| {
const CWrapper = struct {
pub fn dropCallbackWrapper(handle: ?*c.GLFWwindow, path_count: c_int, paths: [*c][*c]const u8) callconv(.C) void {
@call(.always_inline, user_callback, .{
from(handle.?),
@as([*][*:0]const u8, @ptrCast(paths))[0..@as(u32, @intCast(path_count))],
});
}
};
if (c.glfwSetDropCallback(self.handle, CWrapper.dropCallbackWrapper) != null) return;
} else {
if (c.glfwSetDropCallback(self.handle, null) != null) return;
}
}
/// For testing purposes only; see glfw.Window.Hints and glfw.Window.create for the public API.
/// Sets the specified window hint to the desired value.
///
/// This function sets hints for the next call to glfw.Window.create. The hints, once set, retain
/// their values until changed by a call to this function or glfw.window.defaultHints, or until the
/// library is terminated.
///
/// This function does not check whether the specified hint values are valid. If you set hints to
/// invalid values this will instead be reported by the next call to glfw.createWindow.
///
/// Some hints are platform specific. These may be set on any platform but they will only affect
/// their specific platform. Other platforms will ignore them.
///
/// Possible errors include glfw.ErrorCode.InvalidEnum.
///
/// @pointer_lifetime in the event that value is of a str type, the specified string is copied before this function returns.
///
/// @thread_safety This function must only be called from the main thread.
///
/// see also: window_hints, glfw.Window.defaultHints
inline fn hint(h: Hint, value: anytype) void {
internal_debug.assertInitialized();
const value_type = @TypeOf(value);
const value_type_info: std.builtin.Type = @typeInfo(value_type);
switch (value_type_info) {
.Int, .ComptimeInt => {
c.glfwWindowHint(@intFromEnum(h), @as(c_int, @intCast(value)));
},
.Bool => {
const int_value = @intFromBool(value);
c.glfwWindowHint(@intFromEnum(h), @as(c_int, @intCast(int_value)));
},
.Enum => {
const int_value = @intFromEnum(value);
c.glfwWindowHint(@intFromEnum(h), @as(c_int, @intCast(int_value)));
},
.Array => |arr_type| {
if (arr_type.child != u8) {
@compileError("expected array of u8, got " ++ @typeName(arr_type));
}
c.glfwWindowHintString(@intFromEnum(h), &value[0]);
},
.Pointer => |pointer_info| {
const pointed_type = @typeInfo(pointer_info.child);
switch (pointed_type) {
.Array => |arr_type| {
if (arr_type.child != u8) {
@compileError("expected pointer to array of u8, got " ++ @typeName(arr_type));
}
},
else => @compileError("expected pointer to array, got " ++ @typeName(pointed_type)),
}
c.glfwWindowHintString(@intFromEnum(h), &value[0]);
},
else => {
@compileError("expected a int, bool, enum, array, or pointer, got " ++ @typeName(value_type));
},
}
}
test "defaultHints" {
defer glfw.clearError(); // clear any error we generate
if (!glfw.init(.{})) {
std.log.err("failed to initialize GLFW: {?s}", .{glfw.getErrorString()});
std.process.exit(1);
}
defer glfw.terminate();
defaultHints();
}
test "hint comptime int" {
defer glfw.clearError(); // clear any error we generate
if (!glfw.init(.{})) {
std.log.err("failed to initialize GLFW: {?s}", .{glfw.getErrorString()});
std.process.exit(1);
}
defer glfw.terminate();
hint(.focused, 1);
defaultHints();
}
test "hint int" {
defer glfw.clearError(); // clear any error we generate
if (!glfw.init(.{})) {
std.log.err("failed to initialize GLFW: {?s}", .{glfw.getErrorString()});
std.process.exit(1);
}
defer glfw.terminate();
const focused: i32 = 1;
hint(.focused, focused);
defaultHints();
}
test "hint bool" {
defer glfw.clearError(); // clear any error we generate
if (!glfw.init(.{})) {
std.log.err("failed to initialize GLFW: {?s}", .{glfw.getErrorString()});
std.process.exit(1);
}
defer glfw.terminate();
hint(.focused, true);
defaultHints();
}
test "hint enum(u1)" {
defer glfw.clearError(); // clear any error we generate
if (!glfw.init(.{})) {
std.log.err("failed to initialize GLFW: {?s}", .{glfw.getErrorString()});
std.process.exit(1);
}
defer glfw.terminate();
const MyEnum = enum(u1) {
true = 1,
false = 0,
};
hint(.focused, MyEnum.true);
defaultHints();
}
test "hint enum(i32)" {
defer glfw.clearError(); // clear any error we generate
if (!glfw.init(.{})) {
std.log.err("failed to initialize GLFW: {?s}", .{glfw.getErrorString()});
std.process.exit(1);
}
defer glfw.terminate();
const MyEnum = enum(i32) {
true = 1,
false = 0,
};
hint(.focused, MyEnum.true);
defaultHints();
}
test "hint array str" {
defer glfw.clearError(); // clear any error we generate
if (!glfw.init(.{})) {
std.log.err("failed to initialize GLFW: {?s}", .{glfw.getErrorString()});
std.process.exit(1);
}
defer glfw.terminate();
const str_arr = [_]u8{ 'm', 'y', 'c', 'l', 'a', 's', 's' };
hint(.x11_class_name, str_arr);
defaultHints();
}
test "hint pointer str" {
defer glfw.clearError(); // clear any error we generate
if (!glfw.init(.{})) {
std.log.err("failed to initialize GLFW: {?s}", .{glfw.getErrorString()});
std.process.exit(1);
}
defer glfw.terminate();
hint(.x11_class_name, "myclass");
}
test "createWindow" {
defer glfw.clearError(); // clear any error we generate
if (!glfw.init(.{})) {
std.log.err("failed to initialize GLFW: {?s}", .{glfw.getErrorString()});
std.process.exit(1);
}
defer glfw.terminate();
const window = Window.create(640, 480, "GLFW example", null, null, .{}) orelse {
std.log.warn("failed to create window: {?s}", .{glfw.getErrorString()});
return error.SkipZigTest; // note: we don't exit(1) here because our CI can't open windows
};
defer window.destroy();
}
test "setShouldClose" {
defer glfw.clearError(); // clear any error we generate
if (!glfw.init(.{})) {
std.log.err("failed to initialize GLFW: {?s}", .{glfw.getErrorString()});
std.process.exit(1);
}
defer glfw.terminate();
const window = Window.create(640, 480, "GLFW example", null, null, .{}) orelse {
std.log.warn("failed to create window: {?s}", .{glfw.getErrorString()});
return error.SkipZigTest; // note: we don't exit(1) here because our CI can't open windows
};
window.setShouldClose(true);
defer window.destroy();
}
test "setTitle" {
defer glfw.clearError(); // clear any error we generate
if (!glfw.init(.{})) {
std.log.err("failed to initialize GLFW: {?s}", .{glfw.getErrorString()});
std.process.exit(1);
}
defer glfw.terminate();
const window = Window.create(640, 480, "GLFW example", null, null, .{}) orelse {
std.log.warn("failed to create window: {?s}", .{glfw.getErrorString()});
return error.SkipZigTest; // note: we don't exit(1) here because our CI can't open windows
};
defer window.destroy();
window.setTitle("Updated title!");
}
test "setIcon" {
const allocator = testing.allocator;
defer glfw.clearError(); // clear any error we generate
if (!glfw.init(.{})) {
std.log.err("failed to initialize GLFW: {?s}", .{glfw.getErrorString()});
std.process.exit(1);
}
defer glfw.terminate();
const window = Window.create(640, 480, "GLFW example", null, null, .{}) orelse {
std.log.warn("failed to create window: {?s}", .{glfw.getErrorString()});
return error.SkipZigTest; // note: we don't exit(1) here because our CI can't open windows
};
defer window.destroy();
// Create an all-red icon image.
const width: u32 = 48;
const height: u32 = 48;
const icon = try Image.init(allocator, width, height, width * height * 4);
var x: u32 = 0;
var y: u32 = 0;
while (y <= height) : (y += 1) {
while (x <= width) : (x += 1) {
icon.pixels[(x * y * 4) + 0] = 255; // red
icon.pixels[(x * y * 4) + 1] = 0; // green
icon.pixels[(x * y * 4) + 2] = 0; // blue
icon.pixels[(x * y * 4) + 3] = 255; // alpha
}
}
try window.setIcon(allocator, &[_]Image{icon});
icon.deinit(allocator); // glfw copies it.
}
test "getPos" {
defer glfw.clearError(); // clear any error we generate
if (!glfw.init(.{})) {
std.log.err("failed to initialize GLFW: {?s}", .{glfw.getErrorString()});
std.process.exit(1);
}
defer glfw.terminate();
const window = Window.create(640, 480, "GLFW example", null, null, .{}) orelse {
std.log.warn("failed to create window: {?s}", .{glfw.getErrorString()});
return error.SkipZigTest; // note: we don't exit(1) here because our CI can't open windows
};
defer window.destroy();
_ = window.getPos();
}
test "setPos" {
defer glfw.clearError(); // clear any error we generate
if (!glfw.init(.{})) {
std.log.err("failed to initialize GLFW: {?s}", .{glfw.getErrorString()});
std.process.exit(1);
}
defer glfw.terminate();
const window = Window.create(640, 480, "GLFW example", null, null, .{}) orelse {
std.log.warn("failed to create window: {?s}", .{glfw.getErrorString()});
return error.SkipZigTest; // note: we don't exit(1) here because our CI can't open windows
};
defer window.destroy();
_ = window.setPos(.{ .x = 0, .y = 0 });
}
test "getSize" {
defer glfw.clearError(); // clear any error we generate
if (!glfw.init(.{})) {
std.log.err("failed to initialize GLFW: {?s}", .{glfw.getErrorString()});
std.process.exit(1);
}
defer glfw.terminate();
const window = Window.create(640, 480, "GLFW example", null, null, .{}) orelse {
std.log.warn("failed to create window: {?s}", .{glfw.getErrorString()});
return error.SkipZigTest; // note: we don't exit(1) here because our CI can't open windows
};
defer window.destroy();
_ = window.getSize();
}
test "setSize" {
defer glfw.clearError(); // clear any error we generate
if (!glfw.init(.{})) {
std.log.err("failed to initialize GLFW: {?s}", .{glfw.getErrorString()});
std.process.exit(1);
}
defer glfw.terminate();
const window = Window.create(640, 480, "GLFW example", null, null, .{}) orelse {
std.log.warn("failed to create window: {?s}", .{glfw.getErrorString()});
return error.SkipZigTest; // note: we don't exit(1) here because our CI can't open windows
};
defer window.destroy();
_ = window.setSize(.{ .width = 640, .height = 480 });
}
test "setSizeLimits" {
defer glfw.clearError(); // clear any error we generate
if (!glfw.init(.{})) {
std.log.err("failed to initialize GLFW: {?s}", .{glfw.getErrorString()});
std.process.exit(1);
}
defer glfw.terminate();
const window = Window.create(640, 480, "GLFW example", null, null, .{}) orelse {
std.log.warn("failed to create window: {?s}", .{glfw.getErrorString()});
return error.SkipZigTest; // note: we don't exit(1) here because our CI can't open windows
};
defer window.destroy();
window.setSizeLimits(
.{ .width = 720, .height = 480 },
.{ .width = 1080, .height = 1920 },
);
}
test "setAspectRatio" {
defer glfw.clearError(); // clear any error we generate
if (!glfw.init(.{})) {
std.log.err("failed to initialize GLFW: {?s}", .{glfw.getErrorString()});
std.process.exit(1);
}
defer glfw.terminate();
const window = Window.create(640, 480, "GLFW example", null, null, .{}) orelse {
std.log.warn("failed to create window: {?s}", .{glfw.getErrorString()});
return error.SkipZigTest; // note: we don't exit(1) here because our CI can't open windows
};
defer window.destroy();
window.setAspectRatio(4, 3);
}
test "getFramebufferSize" {
defer glfw.clearError(); // clear any error we generate
if (!glfw.init(.{})) {
std.log.err("failed to initialize GLFW: {?s}", .{glfw.getErrorString()});
std.process.exit(1);
}
defer glfw.terminate();
const window = Window.create(640, 480, "GLFW example", null, null, .{}) orelse {
std.log.warn("failed to create window: {?s}", .{glfw.getErrorString()});
return error.SkipZigTest; // note: we don't exit(1) here because our CI can't open windows
};
defer window.destroy();
_ = window.getFramebufferSize();
}
test "getFrameSize" {
defer glfw.clearError(); // clear any error we generate
if (!glfw.init(.{})) {
std.log.err("failed to initialize GLFW: {?s}", .{glfw.getErrorString()});
std.process.exit(1);
}
defer glfw.terminate();
const window = Window.create(640, 480, "GLFW example", null, null, .{}) orelse {
std.log.warn("failed to create window: {?s}", .{glfw.getErrorString()});
return error.SkipZigTest; // note: we don't exit(1) here because our CI can't open windows
};
defer window.destroy();
_ = window.getFrameSize();
}
test "getContentScale" {
defer glfw.clearError(); // clear any error we generate
if (!glfw.init(.{})) {
std.log.err("failed to initialize GLFW: {?s}", .{glfw.getErrorString()});
std.process.exit(1);
}
defer glfw.terminate();
const window = Window.create(640, 480, "GLFW example", null, null, .{}) orelse {
std.log.warn("failed to create window: {?s}", .{glfw.getErrorString()});
return error.SkipZigTest; // note: we don't exit(1) here because our CI can't open windows
};
defer window.destroy();
_ = window.getContentScale();
}
test "getOpacity" {
defer glfw.clearError(); // clear any error we generate
if (!glfw.init(.{})) {
std.log.err("failed to initialize GLFW: {?s}", .{glfw.getErrorString()});
std.process.exit(1);
}
defer glfw.terminate();
const window = Window.create(640, 480, "GLFW example", null, null, .{}) orelse {
std.log.warn("failed to create window: {?s}", .{glfw.getErrorString()});
return error.SkipZigTest; // note: we don't exit(1) here because our CI can't open windows
};
defer window.destroy();
_ = window.getOpacity();
}
test "iconify" {
defer glfw.clearError(); // clear any error we generate
if (!glfw.init(.{})) {
std.log.err("failed to initialize GLFW: {?s}", .{glfw.getErrorString()});
std.process.exit(1);
}
defer glfw.terminate();
const window = Window.create(640, 480, "GLFW example", null, null, .{}) orelse {
std.log.warn("failed to create window: {?s}", .{glfw.getErrorString()});
return error.SkipZigTest; // note: we don't exit(1) here because our CI can't open windows
};
defer window.destroy();
_ = window.iconify();
}
test "restore" {
defer glfw.clearError(); // clear any error we generate
if (!glfw.init(.{})) {
std.log.err("failed to initialize GLFW: {?s}", .{glfw.getErrorString()});
std.process.exit(1);
}
defer glfw.terminate();
const window = Window.create(640, 480, "GLFW example", null, null, .{}) orelse {
std.log.warn("failed to create window: {?s}", .{glfw.getErrorString()});
return error.SkipZigTest; // note: we don't exit(1) here because our CI can't open windows
};
defer window.destroy();
_ = window.restore();
}
test "maximize" {
defer glfw.clearError(); // clear any error we generate
if (!glfw.init(.{})) {
std.log.err("failed to initialize GLFW: {?s}", .{glfw.getErrorString()});
std.process.exit(1);
}
defer glfw.terminate();
const window = Window.create(640, 480, "GLFW example", null, null, .{}) orelse {
std.log.warn("failed to create window: {?s}", .{glfw.getErrorString()});
return error.SkipZigTest; // note: we don't exit(1) here because our CI can't open windows
};
defer window.destroy();
_ = window.maximize();
}
test "show" {
defer glfw.clearError(); // clear any error we generate
if (!glfw.init(.{})) {
std.log.err("failed to initialize GLFW: {?s}", .{glfw.getErrorString()});
std.process.exit(1);
}
defer glfw.terminate();
const window = Window.create(640, 480, "GLFW example", null, null, .{}) orelse {
std.log.warn("failed to create window: {?s}", .{glfw.getErrorString()});
return error.SkipZigTest; // note: we don't exit(1) here because our CI can't open windows
};
defer window.destroy();
_ = window.show();
}
test "hide" {
defer glfw.clearError(); // clear any error we generate
if (!glfw.init(.{})) {
std.log.err("failed to initialize GLFW: {?s}", .{glfw.getErrorString()});
std.process.exit(1);
}
defer glfw.terminate();
const window = Window.create(640, 480, "GLFW example", null, null, .{}) orelse {
std.log.warn("failed to create window: {?s}", .{glfw.getErrorString()});
return error.SkipZigTest; // note: we don't exit(1) here because our CI can't open windows
};
defer window.destroy();
_ = window.hide();
}
test "focus" {
defer glfw.clearError(); // clear any error we generate
if (!glfw.init(.{})) {
std.log.err("failed to initialize GLFW: {?s}", .{glfw.getErrorString()});
std.process.exit(1);
}
defer glfw.terminate();
const window = Window.create(640, 480, "GLFW example", null, null, .{}) orelse {
std.log.warn("failed to create window: {?s}", .{glfw.getErrorString()});
return error.SkipZigTest; // note: we don't exit(1) here because our CI can't open windows
};
defer window.destroy();
_ = window.focus();
}
test "requestAttention" {
defer glfw.clearError(); // clear any error we generate
if (!glfw.init(.{})) {
std.log.err("failed to initialize GLFW: {?s}", .{glfw.getErrorString()});
std.process.exit(1);
}
defer glfw.terminate();
const window = Window.create(640, 480, "GLFW example", null, null, .{}) orelse {
std.log.warn("failed to create window: {?s}", .{glfw.getErrorString()});
return error.SkipZigTest; // note: we don't exit(1) here because our CI can't open windows
};
defer window.destroy();
_ = window.requestAttention();
}
test "swapBuffers" {
defer glfw.clearError(); // clear any error we generate
if (!glfw.init(.{})) {
std.log.err("failed to initialize GLFW: {?s}", .{glfw.getErrorString()});
std.process.exit(1);
}
defer glfw.terminate();
const window = Window.create(640, 480, "GLFW example", null, null, .{}) orelse {
std.log.warn("failed to create window: {?s}", .{glfw.getErrorString()});
return error.SkipZigTest; // note: we don't exit(1) here because our CI can't open windows
};
defer window.destroy();
_ = window.swapBuffers();
}
test "getMonitor" {
defer glfw.clearError(); // clear any error we generate
if (!glfw.init(.{})) {
std.log.err("failed to initialize GLFW: {?s}", .{glfw.getErrorString()});
std.process.exit(1);
}
defer glfw.terminate();
const window = Window.create(640, 480, "GLFW example", null, null, .{}) orelse {
std.log.warn("failed to create window: {?s}", .{glfw.getErrorString()});
return error.SkipZigTest; // note: we don't exit(1) here because our CI can't open windows
};
defer window.destroy();
_ = window.getMonitor();
}
test "setMonitor" {
defer glfw.clearError(); // clear any error we generate
if (!glfw.init(.{})) {
std.log.err("failed to initialize GLFW: {?s}", .{glfw.getErrorString()});
std.process.exit(1);
}
defer glfw.terminate();
const window = Window.create(640, 480, "GLFW example", null, null, .{}) orelse {
std.log.warn("failed to create window: {?s}", .{glfw.getErrorString()});
return error.SkipZigTest; // note: we don't exit(1) here because our CI can't open windows
};
defer window.destroy();
window.setMonitor(null, 10, 10, 640, 480, 60);
}
test "getAttrib" {
defer glfw.clearError(); // clear any error we generate
if (!glfw.init(.{})) {
std.log.err("failed to initialize GLFW: {?s}", .{glfw.getErrorString()});
std.process.exit(1);
}
defer glfw.terminate();
const window = Window.create(640, 480, "GLFW example", null, null, .{}) orelse {
std.log.warn("failed to create window: {?s}", .{glfw.getErrorString()});
return error.SkipZigTest; // note: we don't exit(1) here because our CI can't open windows
};
defer window.destroy();
_ = window.getAttrib(.focused);
}
test "setAttrib" {
defer glfw.clearError(); // clear any error we generate
if (!glfw.init(.{})) {
std.log.err("failed to initialize GLFW: {?s}", .{glfw.getErrorString()});
std.process.exit(1);
}
defer glfw.terminate();
const window = Window.create(640, 480, "GLFW example", null, null, .{}) orelse {
std.log.warn("failed to create window: {?s}", .{glfw.getErrorString()});
return error.SkipZigTest; // note: we don't exit(1) here because our CI can't open windows
};
defer window.destroy();
window.setAttrib(.decorated, false);
}
test "setUserPointer" {
defer glfw.clearError(); // clear any error we generate
if (!glfw.init(.{})) {
std.log.err("failed to initialize GLFW: {?s}", .{glfw.getErrorString()});
std.process.exit(1);
}
defer glfw.terminate();
const window = Window.create(640, 480, "GLFW example", null, null, .{}) orelse {
std.log.warn("failed to create window: {?s}", .{glfw.getErrorString()});
return error.SkipZigTest; // note: we don't exit(1) here because our CI can't open windows
};
defer window.destroy();
const T = struct { name: []const u8 };
var my_value = T{ .name = "my window!" };
window.setUserPointer(&my_value);
}
test "getUserPointer" {
defer glfw.clearError(); // clear any error we generate
if (!glfw.init(.{})) {
std.log.err("failed to initialize GLFW: {?s}", .{glfw.getErrorString()});
std.process.exit(1);
}
defer glfw.terminate();
const window = Window.create(640, 480, "GLFW example", null, null, .{}) orelse {
std.log.warn("failed to create window: {?s}", .{glfw.getErrorString()});
return error.SkipZigTest; // note: we don't exit(1) here because our CI can't open windows
};
defer window.destroy();
const T = struct { name: []const u8 };
var my_value = T{ .name = "my window!" };
window.setUserPointer(&my_value);
const got = window.getUserPointer(T);
std.debug.assert(&my_value == got);
}
test "setPosCallback" {
defer glfw.clearError(); // clear any error we generate
if (!glfw.init(.{})) {
std.log.err("failed to initialize GLFW: {?s}", .{glfw.getErrorString()});
std.process.exit(1);
}
defer glfw.terminate();
const window = Window.create(640, 480, "GLFW example", null, null, .{}) orelse {
std.log.warn("failed to create window: {?s}", .{glfw.getErrorString()});
return error.SkipZigTest; // note: we don't exit(1) here because our CI can't open windows
};
defer window.destroy();
window.setPosCallback((struct {
fn callback(_window: Window, xpos: i32, ypos: i32) void {
_ = _window;
_ = xpos;
_ = ypos;
}
}).callback);
}
test "setSizeCallback" {
defer glfw.clearError(); // clear any error we generate
if (!glfw.init(.{})) {
std.log.err("failed to initialize GLFW: {?s}", .{glfw.getErrorString()});
std.process.exit(1);
}
defer glfw.terminate();
const window = Window.create(640, 480, "GLFW example", null, null, .{}) orelse {
std.log.warn("failed to create window: {?s}", .{glfw.getErrorString()});
return error.SkipZigTest; // note: we don't exit(1) here because our CI can't open windows
};
defer window.destroy();
window.setSizeCallback((struct {
fn callback(_window: Window, width: i32, height: i32) void {
_ = _window;
_ = width;
_ = height;
}
}).callback);
}
test "setCloseCallback" {
defer glfw.clearError(); // clear any error we generate
if (!glfw.init(.{})) {
std.log.err("failed to initialize GLFW: {?s}", .{glfw.getErrorString()});
std.process.exit(1);
}
defer glfw.terminate();
const window = Window.create(640, 480, "GLFW example", null, null, .{}) orelse {
std.log.warn("failed to create window: {?s}", .{glfw.getErrorString()});
return error.SkipZigTest; // note: we don't exit(1) here because our CI can't open windows
};
defer window.destroy();
window.setCloseCallback((struct {
fn callback(_window: Window) void {
_ = _window;
}
}).callback);
}
test "setRefreshCallback" {
defer glfw.clearError(); // clear any error we generate
if (!glfw.init(.{})) {
std.log.err("failed to initialize GLFW: {?s}", .{glfw.getErrorString()});
std.process.exit(1);
}
defer glfw.terminate();
const window = Window.create(640, 480, "GLFW example", null, null, .{}) orelse {
std.log.warn("failed to create window: {?s}", .{glfw.getErrorString()});
return error.SkipZigTest; // note: we don't exit(1) here because our CI can't open windows
};
defer window.destroy();
window.setRefreshCallback((struct {
fn callback(_window: Window) void {
_ = _window;
}
}).callback);
}
test "setFocusCallback" {
defer glfw.clearError(); // clear any error we generate
if (!glfw.init(.{})) {
std.log.err("failed to initialize GLFW: {?s}", .{glfw.getErrorString()});
std.process.exit(1);
}
defer glfw.terminate();
const window = Window.create(640, 480, "GLFW example", null, null, .{}) orelse {
std.log.warn("failed to create window: {?s}", .{glfw.getErrorString()});
return error.SkipZigTest; // note: we don't exit(1) here because our CI can't open windows
};
defer window.destroy();
window.setFocusCallback((struct {
fn callback(_window: Window, focused: bool) void {
_ = _window;
_ = focused;
}
}).callback);
}
test "setIconifyCallback" {
defer glfw.clearError(); // clear any error we generate
if (!glfw.init(.{})) {
std.log.err("failed to initialize GLFW: {?s}", .{glfw.getErrorString()});
std.process.exit(1);
}
defer glfw.terminate();
const window = Window.create(640, 480, "GLFW example", null, null, .{}) orelse {
std.log.warn("failed to create window: {?s}", .{glfw.getErrorString()});
return error.SkipZigTest; // note: we don't exit(1) here because our CI can't open windows
};
defer window.destroy();
window.setIconifyCallback((struct {
fn callback(_window: Window, iconified: bool) void {
_ = _window;
_ = iconified;
}
}).callback);
}
test "setMaximizeCallback" {
defer glfw.clearError(); // clear any error we generate
if (!glfw.init(.{})) {
std.log.err("failed to initialize GLFW: {?s}", .{glfw.getErrorString()});
std.process.exit(1);
}
defer glfw.terminate();
const window = Window.create(640, 480, "GLFW example", null, null, .{}) orelse {
std.log.warn("failed to create window: {?s}", .{glfw.getErrorString()});
return error.SkipZigTest; // note: we don't exit(1) here because our CI can't open windows
};
defer window.destroy();
window.setMaximizeCallback((struct {
fn callback(_window: Window, maximized: bool) void {
_ = _window;
_ = maximized;
}
}).callback);
}
test "setFramebufferSizeCallback" {
defer glfw.clearError(); // clear any error we generate
if (!glfw.init(.{})) {
std.log.err("failed to initialize GLFW: {?s}", .{glfw.getErrorString()});
std.process.exit(1);
}
defer glfw.terminate();
const window = Window.create(640, 480, "GLFW example", null, null, .{}) orelse {
std.log.warn("failed to create window: {?s}", .{glfw.getErrorString()});
return error.SkipZigTest; // note: we don't exit(1) here because our CI can't open windows
};
defer window.destroy();
window.setFramebufferSizeCallback((struct {
fn callback(_window: Window, width: u32, height: u32) void {
_ = _window;
_ = width;
_ = height;
}
}).callback);
}
test "setContentScaleCallback" {
defer glfw.clearError(); // clear any error we generate
if (!glfw.init(.{})) {
std.log.err("failed to initialize GLFW: {?s}", .{glfw.getErrorString()});
std.process.exit(1);
}
defer glfw.terminate();
const window = Window.create(640, 480, "GLFW example", null, null, .{}) orelse {
std.log.warn("failed to create window: {?s}", .{glfw.getErrorString()});
return error.SkipZigTest; // note: we don't exit(1) here because our CI can't open windows
};
defer window.destroy();
window.setContentScaleCallback((struct {
fn callback(_window: Window, xscale: f32, yscale: f32) void {
_ = _window;
_ = xscale;
_ = yscale;
}
}).callback);
}
test "setDropCallback" {
defer glfw.clearError(); // clear any error we generate
if (!glfw.init(.{})) {
std.log.err("failed to initialize GLFW: {?s}", .{glfw.getErrorString()});
std.process.exit(1);
}
defer glfw.terminate();
const window = Window.create(640, 480, "GLFW example", null, null, .{}) orelse {
std.log.warn("failed to create window: {?s}", .{glfw.getErrorString()});
return error.SkipZigTest; // note: we don't exit(1) here because our CI can't open windows
};
defer window.destroy();
window.setDropCallback((struct {
fn callback(_window: Window, paths: [][*:0]const u8) void {
_ = _window;
_ = paths;
}
}).callback);
}
test "getInputModeCursor" {
defer glfw.clearError(); // clear any error we generate
if (!glfw.init(.{})) {
std.log.err("failed to initialize GLFW: {?s}", .{glfw.getErrorString()});
std.process.exit(1);
}
defer glfw.terminate();
const window = Window.create(640, 480, "GLFW example", null, null, .{}) orelse {
std.log.warn("failed to create window: {?s}", .{glfw.getErrorString()});
return error.SkipZigTest; // note: we don't exit(1) here because our CI can't open windows
};
defer window.destroy();
_ = window.getInputModeCursor();
}
test "setInputModeCursor" {
defer glfw.clearError(); // clear any error we generate
if (!glfw.init(.{})) {
std.log.err("failed to initialize GLFW: {?s}", .{glfw.getErrorString()});
std.process.exit(1);
}
defer glfw.terminate();
const window = Window.create(640, 480, "GLFW example", null, null, .{}) orelse {
std.log.warn("failed to create window: {?s}", .{glfw.getErrorString()});
return error.SkipZigTest; // note: we don't exit(1) here because our CI can't open windows
};
defer window.destroy();
window.setInputModeCursor(.hidden);
}
test "getInputModeStickyKeys" {
defer glfw.clearError(); // clear any error we generate
if (!glfw.init(.{})) {
std.log.err("failed to initialize GLFW: {?s}", .{glfw.getErrorString()});
std.process.exit(1);
}
defer glfw.terminate();
const window = Window.create(640, 480, "GLFW example", null, null, .{}) orelse {
std.log.warn("failed to create window: {?s}", .{glfw.getErrorString()});
return error.SkipZigTest; // note: we don't exit(1) here because our CI can't open windows
};
defer window.destroy();
_ = window.getInputModeStickyKeys();
}
test "setInputModeStickyKeys" {
defer glfw.clearError(); // clear any error we generate
if (!glfw.init(.{})) {
std.log.err("failed to initialize GLFW: {?s}", .{glfw.getErrorString()});
std.process.exit(1);
}
defer glfw.terminate();
const window = Window.create(640, 480, "GLFW example", null, null, .{}) orelse {
std.log.warn("failed to create window: {?s}", .{glfw.getErrorString()});
return error.SkipZigTest; // note: we don't exit(1) here because our CI can't open windows
};
defer window.destroy();
window.setInputModeStickyKeys(false);
}
test "getInputModeStickyMouseButtons" {
defer glfw.clearError(); // clear any error we generate
if (!glfw.init(.{})) {
std.log.err("failed to initialize GLFW: {?s}", .{glfw.getErrorString()});
std.process.exit(1);
}
defer glfw.terminate();
const window = Window.create(640, 480, "GLFW example", null, null, .{}) orelse {
std.log.warn("failed to create window: {?s}", .{glfw.getErrorString()});
return error.SkipZigTest; // note: we don't exit(1) here because our CI can't open windows
};
defer window.destroy();
_ = window.getInputModeStickyMouseButtons();
}
test "setInputModeStickyMouseButtons" {
defer glfw.clearError(); // clear any error we generate
if (!glfw.init(.{})) {
std.log.err("failed to initialize GLFW: {?s}", .{glfw.getErrorString()});
std.process.exit(1);
}
defer glfw.terminate();
const window = Window.create(640, 480, "GLFW example", null, null, .{}) orelse {
std.log.warn("failed to create window: {?s}", .{glfw.getErrorString()});
return error.SkipZigTest; // note: we don't exit(1) here because our CI can't open windows
};
defer window.destroy();
window.setInputModeStickyMouseButtons(false);
}
test "getInputModeLockKeyMods" {
defer glfw.clearError(); // clear any error we generate
if (!glfw.init(.{})) {
std.log.err("failed to initialize GLFW: {?s}", .{glfw.getErrorString()});
std.process.exit(1);
}
defer glfw.terminate();
const window = Window.create(640, 480, "GLFW example", null, null, .{}) orelse {
std.log.warn("failed to create window: {?s}", .{glfw.getErrorString()});
return error.SkipZigTest; // note: we don't exit(1) here because our CI can't open windows
};
defer window.destroy();
_ = window.getInputModeLockKeyMods();
}
test "setInputModeLockKeyMods" {
defer glfw.clearError(); // clear any error we generate
if (!glfw.init(.{})) {
std.log.err("failed to initialize GLFW: {?s}", .{glfw.getErrorString()});
std.process.exit(1);
}
defer glfw.terminate();
const window = Window.create(640, 480, "GLFW example", null, null, .{}) orelse {
std.log.warn("failed to create window: {?s}", .{glfw.getErrorString()});
return error.SkipZigTest; // note: we don't exit(1) here because our CI can't open windows
};
defer window.destroy();
window.setInputModeLockKeyMods(false);
}
test "getInputModeRawMouseMotion" {
defer glfw.clearError(); // clear any error we generate
if (!glfw.init(.{})) {
std.log.err("failed to initialize GLFW: {?s}", .{glfw.getErrorString()});
std.process.exit(1);
}
defer glfw.terminate();
const window = Window.create(640, 480, "GLFW example", null, null, .{}) orelse {
std.log.warn("failed to create window: {?s}", .{glfw.getErrorString()});
return error.SkipZigTest; // note: we don't exit(1) here because our CI can't open windows
};
defer window.destroy();
_ = window.getInputModeRawMouseMotion();
}
test "setInputModeRawMouseMotion" {
defer glfw.clearError(); // clear any error we generate
if (!glfw.init(.{})) {
std.log.err("failed to initialize GLFW: {?s}", .{glfw.getErrorString()});
std.process.exit(1);
}
defer glfw.terminate();
const window = Window.create(640, 480, "GLFW example", null, null, .{}) orelse {
std.log.warn("failed to create window: {?s}", .{glfw.getErrorString()});
return error.SkipZigTest; // note: we don't exit(1) here because our CI can't open windows
};
defer window.destroy();
window.setInputModeRawMouseMotion(false);
}
test "getInputMode" {
defer glfw.clearError(); // clear any error we generate
if (!glfw.init(.{})) {
std.log.err("failed to initialize GLFW: {?s}", .{glfw.getErrorString()});
std.process.exit(1);
}
defer glfw.terminate();
const window = Window.create(640, 480, "GLFW example", null, null, .{}) orelse {
std.log.warn("failed to create window: {?s}", .{glfw.getErrorString()});
return error.SkipZigTest; // note: we don't exit(1) here because our CI can't open windows
};
defer window.destroy();
_ = window.getInputMode(glfw.Window.InputMode.raw_mouse_motion) == 1;
}
test "setInputMode" {
defer glfw.clearError(); // clear any error we generate
if (!glfw.init(.{})) {
std.log.err("failed to initialize GLFW: {?s}", .{glfw.getErrorString()});
std.process.exit(1);
}
defer glfw.terminate();
const window = Window.create(640, 480, "GLFW example", null, null, .{}) orelse {
std.log.warn("failed to create window: {?s}", .{glfw.getErrorString()});
return error.SkipZigTest; // note: we don't exit(1) here because our CI can't open windows
};
defer window.destroy();
// Boolean values.
window.setInputMode(glfw.Window.InputMode.sticky_mouse_buttons, true);
// Integer values.
window.setInputMode(glfw.Window.InputMode.cursor, glfw.Window.InputModeCursor.hidden);
}
test "getKey" {
defer glfw.clearError(); // clear any error we generate
if (!glfw.init(.{})) {
std.log.err("failed to initialize GLFW: {?s}", .{glfw.getErrorString()});
std.process.exit(1);
}
defer glfw.terminate();
const window = Window.create(640, 480, "GLFW example", null, null, .{}) orelse {
std.log.warn("failed to create window: {?s}", .{glfw.getErrorString()});
return error.SkipZigTest; // note: we don't exit(1) here because our CI can't open windows
};
defer window.destroy();
_ = window.getKey(glfw.Key.escape);
}
test "getMouseButton" {
defer glfw.clearError(); // clear any error we generate
if (!glfw.init(.{})) {
std.log.err("failed to initialize GLFW: {?s}", .{glfw.getErrorString()});
std.process.exit(1);
}
defer glfw.terminate();
const window = Window.create(640, 480, "GLFW example", null, null, .{}) orelse {
std.log.warn("failed to create window: {?s}", .{glfw.getErrorString()});
return error.SkipZigTest; // note: we don't exit(1) here because our CI can't open windows
};
defer window.destroy();
_ = window.getMouseButton(.left);
}
test "getCursorPos" {
defer glfw.clearError(); // clear any error we generate
if (!glfw.init(.{})) {
std.log.err("failed to initialize GLFW: {?s}", .{glfw.getErrorString()});
std.process.exit(1);
}
defer glfw.terminate();
const window = Window.create(640, 480, "GLFW example", null, null, .{}) orelse {
std.log.warn("failed to create window: {?s}", .{glfw.getErrorString()});
return error.SkipZigTest; // note: we don't exit(1) here because our CI can't open windows
};
defer window.destroy();
_ = window.getCursorPos();
}
test "setCursorPos" {
defer glfw.clearError(); // clear any error we generate
if (!glfw.init(.{})) {
std.log.err("failed to initialize GLFW: {?s}", .{glfw.getErrorString()});
std.process.exit(1);
}
defer glfw.terminate();
const window = Window.create(640, 480, "GLFW example", null, null, .{}) orelse {
std.log.warn("failed to create window: {?s}", .{glfw.getErrorString()});
return error.SkipZigTest; // note: we don't exit(1) here because our CI can't open windows
};
defer window.destroy();
window.setCursorPos(0, 0);
}
test "setCursor" {
defer glfw.clearError(); // clear any error we generate
if (!glfw.init(.{})) {
std.log.err("failed to initialize GLFW: {?s}", .{glfw.getErrorString()});
std.process.exit(1);
}
defer glfw.terminate();
const window = Window.create(640, 480, "GLFW example", null, null, .{}) orelse {
std.log.warn("failed to create window: {?s}", .{glfw.getErrorString()});
return error.SkipZigTest; // note: we don't exit(1) here because our CI can't open windows
};
defer window.destroy();
const cursor = glfw.Cursor.createStandard(.ibeam);
if (cursor) |cur| {
window.setCursor(cur);
defer cur.destroy();
}
}
test "setKeyCallback" {
defer glfw.clearError(); // clear any error we generate
if (!glfw.init(.{})) {
std.log.err("failed to initialize GLFW: {?s}", .{glfw.getErrorString()});
std.process.exit(1);
}
defer glfw.terminate();
const window = Window.create(640, 480, "GLFW example", null, null, .{}) orelse {
std.log.warn("failed to create window: {?s}", .{glfw.getErrorString()});
return error.SkipZigTest; // note: we don't exit(1) here because our CI can't open windows
};
defer window.destroy();
window.setKeyCallback((struct {
fn callback(_window: Window, key: Key, scancode: i32, action: Action, mods: Mods) void {
_ = _window;
_ = key;
_ = scancode;
_ = action;
_ = mods;
}
}).callback);
}
test "setCharCallback" {
defer glfw.clearError(); // clear any error we generate
if (!glfw.init(.{})) {
std.log.err("failed to initialize GLFW: {?s}", .{glfw.getErrorString()});
std.process.exit(1);
}
defer glfw.terminate();
const window = Window.create(640, 480, "GLFW example", null, null, .{}) orelse {
std.log.warn("failed to create window: {?s}", .{glfw.getErrorString()});
return error.SkipZigTest; // note: we don't exit(1) here because our CI can't open windows
};
defer window.destroy();
window.setCharCallback((struct {
fn callback(_window: Window, codepoint: u21) void {
_ = _window;
_ = codepoint;
}
}).callback);
}
test "setMouseButtonCallback" {
defer glfw.clearError(); // clear any error we generate
if (!glfw.init(.{})) {
std.log.err("failed to initialize GLFW: {?s}", .{glfw.getErrorString()});
std.process.exit(1);
}
defer glfw.terminate();
const window = Window.create(640, 480, "GLFW example", null, null, .{}) orelse {
std.log.warn("failed to create window: {?s}", .{glfw.getErrorString()});
return error.SkipZigTest; // note: we don't exit(1) here because our CI can't open windows
};
defer window.destroy();
window.setMouseButtonCallback((struct {
fn callback(_window: Window, button: MouseButton, action: Action, mods: Mods) void {
_ = _window;
_ = button;
_ = action;
_ = mods;
}
}).callback);
}
test "setCursorPosCallback" {
defer glfw.clearError(); // clear any error we generate
if (!glfw.init(.{})) {
std.log.err("failed to initialize GLFW: {?s}", .{glfw.getErrorString()});
std.process.exit(1);
}
defer glfw.terminate();
const window = Window.create(640, 480, "GLFW example", null, null, .{}) orelse {
std.log.warn("failed to create window: {?s}", .{glfw.getErrorString()});
return error.SkipZigTest; // note: we don't exit(1) here because our CI can't open windows
};
defer window.destroy();
window.setCursorPosCallback((struct {
fn callback(_window: Window, xpos: f64, ypos: f64) void {
_ = _window;
_ = xpos;
_ = ypos;
}
}).callback);
}
test "setCursorEnterCallback" {
defer glfw.clearError(); // clear any error we generate
if (!glfw.init(.{})) {
std.log.err("failed to initialize GLFW: {?s}", .{glfw.getErrorString()});
std.process.exit(1);
}
defer glfw.terminate();
const window = Window.create(640, 480, "GLFW example", null, null, .{}) orelse {
std.log.warn("failed to create window: {?s}", .{glfw.getErrorString()});
return error.SkipZigTest; // note: we don't exit(1) here because our CI can't open windows
};
defer window.destroy();
window.setCursorEnterCallback((struct {
fn callback(_window: Window, entered: bool) void {
_ = _window;
_ = entered;
}
}).callback);
}
test "setScrollCallback" {
defer glfw.clearError(); // clear any error we generate
if (!glfw.init(.{})) {
std.log.err("failed to initialize GLFW: {?s}", .{glfw.getErrorString()});
std.process.exit(1);
}
defer glfw.terminate();
const window = Window.create(640, 480, "GLFW example", null, null, .{}) orelse {
std.log.warn("failed to create window: {?s}", .{glfw.getErrorString()});
return error.SkipZigTest; // note: we don't exit(1) here because our CI can't open windows
};
defer window.destroy();
window.setScrollCallback((struct {
fn callback(_window: Window, xoffset: f64, yoffset: f64) void {
_ = _window;
_ = xoffset;
_ = yoffset;
}
}).callback);
}
test "hint-attribute default value parity" {
defer glfw.clearError(); // clear any error we generate
if (!glfw.init(.{})) {
std.log.err("failed to initialize GLFW: {?s}", .{glfw.getErrorString()});
std.process.exit(1);
}
defer glfw.terminate();
testing_ignore_window_hints_struct = true;
const window_a = Window.create(640, 480, "GLFW example", null, null, .{}) orelse {
std.log.warn("failed to create window_a: {?s}", .{glfw.getErrorString()});
return error.SkipZigTest; // note: we don't exit(1) here because our CI can't open windows
};
defer window_a.destroy();
testing_ignore_window_hints_struct = false;
const window_b = Window.create(640, 480, "GLFW example", null, null, .{}) orelse {
std.log.warn("failed to create window_b: {?s}", .{glfw.getErrorString()});
return error.SkipZigTest; // note: we don't exit(1) here because our CI can't open windows
};
defer window_b.destroy();
inline for (comptime std.enums.values(Window.Hint)) |hint_tag| {
if (@hasField(Window.Attrib, @tagName(hint_tag))) {
const attrib_tag = @field(Window.Attrib, @tagName(hint_tag));
switch (attrib_tag) {
.resizable,
.visible,
.decorated,
.auto_iconify,
.floating,
.maximized,
.transparent_framebuffer,
.focus_on_show,
.mouse_passthrough,
.doublebuffer,
.client_api,
.context_creation_api,
.context_version_major,
.context_version_minor,
.context_robustness,
.context_release_behavior,
.context_no_error, // Note: at the time of writing this, GLFW does not list the default value for this hint in the documentation
.context_debug,
.opengl_forward_compat,
.opengl_profile,
=> {
const expected = window_a.getAttrib(attrib_tag);
const actual = window_b.getAttrib(attrib_tag);
testing.expectEqual(expected, actual) catch |err| {
std.debug.print("On attribute '{}'.\n", .{hint_tag});
return err;
};
},
// This attribute is based on a check for which window is currently in focus,
// and the default value, as of writing this comment, is 'true', which means
// that first window_a takes focus, and then window_b takes focus, meaning
// that we can't actually test for the default value.
.focused => continue,
.iconified,
.hovered,
.context_revision,
=> unreachable,
}
}
// Future: we could consider hint values that can't be retrieved via attributes:
// center_cursor
// mouse_passthrough
// scale_to_monitor
// red_bits
// green_bits
// blue_bits
// alpha_bits
// depth_bits
// stencil_bits
// accum_red_bits
// accum_green_bits
// accum_blue_bits
// accum_alpha_bits
// aux_buffers
// samples
// refresh_rate
// stereo
// srgb_capable
// doublebuffer
// platform specific, and thus not considered:
// cocoa_retina_framebuffer
// cocoa_frame_name
// cocoa_graphics_switching
}
}
|
0 | repos/mach-glfw | repos/mach-glfw/src/mod.zig | //! Modifier key flags
//!
//! See glfw.setKeyCallback for how these are used.
const c = @import("c.zig").c;
// must be in sync with GLFW C constants in modifier group, search for "@defgroup mods Modifier key flags"
/// A bitmask of all key modifiers
pub const Mods = packed struct(u8) {
shift: bool = false,
control: bool = false,
alt: bool = false,
super: bool = false,
caps_lock: bool = false,
num_lock: bool = false,
_padding: u2 = 0,
inline fn verifyIntType(comptime IntType: type) void {
comptime {
switch (@typeInfo(IntType)) {
.Int => {},
else => @compileError("Int was not of int type"),
}
}
}
pub inline fn toInt(self: Mods, comptime IntType: type) IntType {
verifyIntType(IntType);
return @as(IntType, @intCast(@as(u8, @bitCast(self))));
}
pub inline fn fromInt(flags: anytype) Mods {
verifyIntType(@TypeOf(flags));
return @as(Mods, @bitCast(@as(u8, @intCast(flags))));
}
};
/// Holds all GLFW mod values in their raw form.
pub const RawMods = struct {
/// If this bit is set one or more Shift keys were held down.
pub const shift = c.GLFW_MOD_SHIFT;
/// If this bit is set one or more Control keys were held down.
pub const control = c.GLFW_MOD_CONTROL;
/// If this bit is set one or more Alt keys were held down.
pub const alt = c.GLFW_MOD_ALT;
/// If this bit is set one or more Super keys were held down.
pub const super = c.GLFW_MOD_SUPER;
/// If this bit is set the Caps Lock key is enabled and the glfw.lock_key_mods input mode is set.
pub const caps_lock = c.GLFW_MOD_CAPS_LOCK;
/// If this bit is set the Num Lock key is enabled and the glfw.lock_key_mods input mode is set.
pub const num_lock = c.GLFW_MOD_NUM_LOCK;
};
test "shift int to bitmask" {
const std = @import("std");
const int_mod = RawMods.shift;
const mod = Mods.fromInt(int_mod);
try std.testing.expect(mod.shift == true);
try std.testing.expect(mod.control == false);
try std.testing.expect(mod.alt == false);
try std.testing.expect(mod.super == false);
try std.testing.expect(mod.caps_lock == false);
try std.testing.expect(mod.num_lock == false);
}
test "shift int and alt to bitmask" {
const std = @import("std");
const int_mod = RawMods.shift | RawMods.alt;
const mod = Mods.fromInt(int_mod);
try std.testing.expect(mod.shift == true);
try std.testing.expect(mod.control == false);
try std.testing.expect(mod.alt == true);
try std.testing.expect(mod.super == false);
try std.testing.expect(mod.caps_lock == false);
try std.testing.expect(mod.num_lock == false);
}
test "super int to bitmask" {
const std = @import("std");
const int_mod = RawMods.super;
const mod = Mods.fromInt(int_mod);
try std.testing.expect(mod.shift == false);
try std.testing.expect(mod.control == false);
try std.testing.expect(mod.alt == false);
try std.testing.expect(mod.super == true);
try std.testing.expect(mod.caps_lock == false);
try std.testing.expect(mod.num_lock == false);
}
test "num lock int to bitmask" {
const std = @import("std");
const int_mod = RawMods.num_lock;
const mod = Mods.fromInt(int_mod);
try std.testing.expect(mod.shift == false);
try std.testing.expect(mod.control == false);
try std.testing.expect(mod.alt == false);
try std.testing.expect(mod.super == false);
try std.testing.expect(mod.caps_lock == false);
try std.testing.expect(mod.num_lock == true);
}
test "all int to bitmask" {
const std = @import("std");
const int_mod = RawMods.shift | RawMods.control |
RawMods.alt | RawMods.super |
RawMods.caps_lock | RawMods.num_lock;
const mod = Mods.fromInt(int_mod);
try std.testing.expect(mod.shift == true);
try std.testing.expect(mod.control == true);
try std.testing.expect(mod.alt == true);
try std.testing.expect(mod.super == true);
try std.testing.expect(mod.caps_lock == true);
try std.testing.expect(mod.num_lock == true);
}
test "shift bitmask to int" {
const std = @import("std");
const mod = Mods{ .shift = true };
const int_mod = mod.toInt(c_int);
try std.testing.expectEqual(int_mod, RawMods.shift);
}
test "shift and alt bitmask to int" {
const std = @import("std");
const mod = Mods{ .shift = true, .alt = true };
const int_mod = mod.toInt(c_int);
try std.testing.expectEqual(int_mod, RawMods.shift | RawMods.alt);
}
test "all bitmask to int" {
const std = @import("std");
const mod = Mods{
.shift = true,
.control = true,
.alt = true,
.super = true,
.caps_lock = true,
.num_lock = true,
};
const int_mod = mod.toInt(c_int);
const expected = RawMods.shift | RawMods.control |
RawMods.alt | RawMods.super |
RawMods.caps_lock | RawMods.num_lock;
try std.testing.expectEqual(int_mod, expected);
}
|
0 | repos/mach-glfw | repos/mach-glfw/src/c.zig | pub const c = @cImport({
@cDefine("GLFW_INCLUDE_VULKAN", "1");
@cDefine("GLFW_INCLUDE_NONE", "1");
@cInclude("GLFW/glfw3.h");
});
|
0 | repos/mach-glfw | repos/mach-glfw/src/main.zig | const std = @import("std");
const testing = std.testing;
const c = @import("c.zig").c;
const key = @import("key.zig");
const errors = @import("errors.zig");
/// Possible value for various window hints, etc.
pub const dont_care = c.GLFW_DONT_CARE;
pub const getError = errors.getError;
pub const mustGetError = errors.mustGetError;
pub const getErrorCode = errors.getErrorCode;
pub const mustGetErrorCode = errors.mustGetErrorCode;
pub const getErrorString = errors.getErrorString;
pub const mustGetErrorString = errors.mustGetErrorString;
pub const setErrorCallback = errors.setErrorCallback;
pub const clearError = errors.clearError;
pub const ErrorCode = errors.ErrorCode;
pub const Error = errors.Error;
pub const Action = @import("action.zig").Action;
pub const GamepadAxis = @import("gamepad_axis.zig").GamepadAxis;
pub const GamepadButton = @import("gamepad_button.zig").GamepadButton;
pub const gamepad_axis = @import("gamepad_axis.zig");
pub const gamepad_button = @import("gamepad_button.zig");
pub const GammaRamp = @import("GammaRamp.zig");
pub const Image = @import("Image.zig");
pub const Joystick = @import("Joystick.zig");
pub const Monitor = @import("Monitor.zig");
pub const mouse_button = @import("mouse_button.zig");
pub const MouseButton = mouse_button.MouseButton;
pub const version = @import("version.zig");
pub const VideoMode = @import("VideoMode.zig");
pub const Window = @import("Window.zig");
pub const Cursor = @import("Cursor.zig");
pub const Native = @import("native.zig").Native;
pub const BackendOptions = @import("native.zig").BackendOptions;
pub const Key = key.Key;
pub const setClipboardString = @import("clipboard.zig").setClipboardString;
pub const getClipboardString = @import("clipboard.zig").getClipboardString;
pub const makeContextCurrent = @import("opengl.zig").makeContextCurrent;
pub const getCurrentContext = @import("opengl.zig").getCurrentContext;
pub const swapInterval = @import("opengl.zig").swapInterval;
pub const extensionSupported = @import("opengl.zig").extensionSupported;
pub const GLProc = @import("opengl.zig").GLProc;
pub const getProcAddress = @import("opengl.zig").getProcAddress;
pub const initVulkanLoader = @import("vulkan.zig").initVulkanLoader;
pub const VKGetInstanceProcAddr = @import("vulkan.zig").VKGetInstanceProcAddr;
pub const vulkanSupported = @import("vulkan.zig").vulkanSupported;
pub const getRequiredInstanceExtensions = @import("vulkan.zig").getRequiredInstanceExtensions;
pub const VKProc = @import("vulkan.zig").VKProc;
pub const getInstanceProcAddress = @import("vulkan.zig").getInstanceProcAddress;
pub const getPhysicalDevicePresentationSupport = @import("vulkan.zig").getPhysicalDevicePresentationSupport;
pub const createWindowSurface = @import("vulkan.zig").createWindowSurface;
pub const getTime = @import("time.zig").getTime;
pub const setTime = @import("time.zig").setTime;
pub const getTimerValue = @import("time.zig").getTimerValue;
pub const getTimerFrequency = @import("time.zig").getTimerFrequency;
pub const Hat = @import("hat.zig").Hat;
pub const RawHat = @import("hat.zig").RawHat;
pub const Mods = @import("mod.zig").Mods;
pub const RawMods = @import("mod.zig").RawMods;
const internal_debug = @import("internal_debug.zig");
/// If GLFW was already initialized in your program, e.g. you are embedding Zig code into an existing
/// program that has already called glfwInit via the C API for you - then you need to tell mach/glfw
/// that it has in fact been initialized already, otherwise when you call other methods mach/glfw
/// would panic thinking glfw.init has not been called yet.
pub fn assumeInitialized() void {
internal_debug.assumeInitialized();
}
/// Initializes the GLFW library.
///
/// This function initializes the GLFW library. Before most GLFW functions can be used, GLFW must
/// be initialized, and before an application terminates GLFW should be terminated in order to free
/// any resources allocated during or after initialization.
///
/// If this function fails, it calls glfw.Terminate before returning. If it succeeds, you should
/// call glfw.Terminate before the application exits.
///
/// Additional calls to this function after successful initialization but before termination will
/// return immediately with no error.
///
/// The glfw.InitHint.platform init hint controls which platforms are considered during
/// initialization. This also depends on which platforms the library was compiled to support.
///
/// macos: This function will change the current directory of the application to the
/// `Contents/Resources` subdirectory of the application's bundle, if present. This can be disabled
/// with `glfw.InitHint.cocoa_chdir_resources`.
///
/// macos: This function will create the main menu and dock icon for the application. If GLFW finds
/// a `MainMenu.nib` it is loaded and assumed to contain a menu bar. Otherwise a minimal menu bar is
/// created manually with common commands like Hide, Quit and About. The About entry opens a minimal
/// about dialog with information from the application's bundle. The menu bar and dock icon can be
/// disabled entirely with `glfw.InitHint.cocoa_menubar`.
///
/// x11: This function will set the `LC_CTYPE` category of the application locale according to the
/// current environment if that category is still "C". This is because the "C" locale breaks
/// Unicode text input.
///
/// Possible errors include glfw.ErrorCode.PlatformUnavailable, glfw.ErrorCode.PlatformError.
/// Returns a bool indicating success.
///
/// @thread_safety This function must only be called from the main thread.
pub inline fn init(hints: InitHints) bool {
internal_debug.toggleInitialized();
internal_debug.assertInitialized();
errdefer {
internal_debug.assertInitialized();
internal_debug.toggleInitialized();
}
inline for (comptime std.meta.fieldNames(InitHints)) |field_name| {
const init_hint = @field(InitHint, field_name);
const init_value = @field(hints, field_name);
if (@TypeOf(init_value) == PlatformType) {
initHint(init_hint, @intFromEnum(init_value));
} else {
initHint(init_hint, init_value);
}
}
return c.glfwInit() == c.GLFW_TRUE;
}
// TODO: implement custom allocator support
//
// /*! @brief Sets the init allocator to the desired value.
// *
// * To use the default allocator, call this function with a `NULL` argument.
// *
// * If you specify an allocator struct, every member must be a valid function
// * pointer. If any member is `NULL`, this function emits @ref
// * GLFW_INVALID_VALUE and the init allocator is unchanged.
// *
// * @param[in] allocator The allocator to use at the next initialization, or
// * `NULL` to use the default one.
// *
// * @errors Possible errors include @ref GLFW_INVALID_VALUE.
// *
// * @pointer_lifetime The specified allocator is copied before this function
// * returns.
// *
// * @thread_safety This function must only be called from the main thread.
// *
// * @sa @ref init_allocator
// * @sa @ref glfwInit
// *
// * @since Added in version 3.4.
// *
// * @ingroup init
// */
// GLFWAPI void glfwInitAllocator(const GLFWallocator* allocator);
/// Terminates the GLFW library.
///
/// This function destroys all remaining windows and cursors, restores any modified gamma ramps
/// and frees any other allocated resources. Once this function is called, you must again call
/// glfw.init successfully before you will be able to use most GLFW functions.
///
/// If GLFW has been successfully initialized, this function should be called before the
/// application exits. If initialization fails, there is no need to call this function, as it is
/// called by glfw.init before it returns failure.
///
/// This function has no effect if GLFW is not initialized.
///
/// Possible errors include glfw.ErrorCode.PlatformError.
///
/// warning: The contexts of any remaining windows must not be current on any other thread when
/// this function is called.
///
/// reentrancy: This function must not be called from a callback.
///
/// thread_safety: This function must only be called from the main thread.
pub inline fn terminate() void {
internal_debug.assertInitialized();
internal_debug.toggleInitialized();
c.glfwTerminate();
}
/// Initialization hints for passing into glfw.init
pub const InitHints = struct {
/// Specifies whether to also expose joystick hats as buttons, for compatibility with earlier
/// versions of GLFW that did not have glfwGetJoystickHats.
joystick_hat_buttons: bool = true,
/// macOS specific init hint. Ignored on other platforms.
///
/// Specifies whether to set the current directory to the application to the Contents/Resources
/// subdirectory of the application's bundle, if present.
cocoa_chdir_resources: bool = true,
/// macOS specific init hint. Ignored on other platforms.
///
/// specifies whether to create a basic menu bar, either from a nib or manually, when the first
/// window is created, which is when AppKit is initialized.
cocoa_menubar: bool = true,
/// Platform selection init hint.
///
/// Possible values are `PlatformType` enums.
platform: PlatformType = .any,
};
/// Initialization hints for passing into glfw.initHint
const InitHint = enum(c_int) {
/// Specifies whether to also expose joystick hats as buttons, for compatibility with earlier
/// versions of GLFW that did not have glfwGetJoystickHats.
///
/// Possible values are `true` and `false`.
joystick_hat_buttons = c.GLFW_JOYSTICK_HAT_BUTTONS,
/// ANGLE rendering backend init hint.
///
/// Possible values are `AnglePlatformType` enums.
angle_platform_type = c.GLFW_ANGLE_PLATFORM_TYPE,
/// Platform selection init hint.
///
/// Possible values are `PlatformType` enums.
platform = c.GLFW_PLATFORM,
/// macOS specific init hint. Ignored on other platforms.
///
/// Specifies whether to set the current directory to the application to the Contents/Resources
/// subdirectory of the application's bundle, if present.
///
/// Possible values are `true` and `false`.
cocoa_chdir_resources = c.GLFW_COCOA_CHDIR_RESOURCES,
/// macOS specific init hint. Ignored on other platforms.
///
/// specifies whether to create a basic menu bar, either from a nib or manually, when the first
/// window is created, which is when AppKit is initialized.
///
/// Possible values are `true` and `false`.
cocoa_menubar = c.GLFW_COCOA_MENUBAR,
/// X11 specific init hint.
x11_xcb_vulkan_surface = c.GLFW_X11_XCB_VULKAN_SURFACE,
/// Wayland specific init hint.
///
/// Possible values are `WaylandLibdecorInitHint` enums.
wayland_libdecor = c.GLFW_WAYLAND_LIBDECOR,
};
/// Angle platform type hints for glfw.InitHint.angle_platform_type
pub const AnglePlatformType = enum(c_int) {
none = c.GLFW_ANGLE_PLATFORM_TYPE_NONE,
opengl = c.GLFW_ANGLE_PLATFORM_TYPE_OPENGL,
opengles = c.GLFW_ANGLE_PLATFORM_TYPE_OPENGLES,
d3d9 = c.GLFW_ANGLE_PLATFORM_TYPE_D3D9,
d3d11 = c.GLFW_ANGLE_PLATFORM_TYPE_D3D11,
vulkan = c.GLFW_ANGLE_PLATFORM_TYPE_VULKAN,
metal = c.GLFW_ANGLE_PLATFORM_TYPE_METAL,
};
/// Wayland libdecor hints for glfw.InitHint.wayland_libdecor
///
/// libdecor is important for GNOME, since GNOME does not implement server side decorations on
/// wayland. libdecor is loaded dynamically at runtime, so in general enabling it is always
/// safe to do. It is enabled by default.
pub const WaylandLibdecorInitHint = enum(c_int) {
wayland_prefer_libdecor = c.GLFW_WAYLAND_PREFER_LIBDECOR,
wayland_disable_libdecor = c.GLFW_WAYLAND_DISABLE_LIBDECOR,
};
/// Platform type hints for glfw.InitHint.platform
pub const PlatformType = enum(c_int) {
/// Enables automatic platform detection.
/// Will default to X11 on wayland.
any = c.GLFW_ANY_PLATFORM,
win32 = c.GLFW_PLATFORM_WIN32,
cocoa = c.GLFW_PLATFORM_COCOA,
wayland = c.GLFW_PLATFORM_WAYLAND,
x11 = c.GLFW_PLATFORM_X11,
null = c.GLFW_PLATFORM_NULL,
};
/// Sets the specified init hint to the desired value.
///
/// This function sets hints for the next initialization of GLFW.
///
/// The values you set hints to are never reset by GLFW, but they only take effect during
/// initialization. Once GLFW has been initialized, any values you set will be ignored until the
/// library is terminated and initialized again.
///
/// Some hints are platform specific. These may be set on any platform but they will only affect
/// their specific platform. Other platforms will ignore them. Setting these hints requires no
/// platform specific headers or functions.
///
/// @param hint: The init hint to set.
/// @param value: The new value of the init hint.
///
/// Possible errors include glfw.ErrorCode.InvalidEnum and glfw.ErrorCode.InvalidValue.
///
/// @remarks This function may be called before glfw.init.
///
/// @thread_safety This function must only be called from the main thread.
fn initHint(hint: InitHint, value: anytype) void {
switch (@typeInfo(@TypeOf(value))) {
.Int, .ComptimeInt => {
c.glfwInitHint(@intFromEnum(hint), @as(c_int, @intCast(value)));
},
.Bool => c.glfwInitHint(@intFromEnum(hint), @as(c_int, @intCast(@intFromBool(value)))),
else => @compileError("expected a int or bool, got " ++ @typeName(@TypeOf(value))),
}
}
/// Returns a string describing the compile-time configuration.
///
/// This function returns the compile-time generated version string of the GLFW library binary. It
/// describes the version, platform, compiler and any platform or operating system specific
/// compile-time options. It should not be confused with the OpenGL or OpenGL ES version string,
/// queried with `glGetString`.
///
/// __Do not use the version string__ to parse the GLFW library version. Use the glfw.version
/// constants instead.
///
/// __Do not use the version string__ to parse what platforms are supported. The
/// `glfw.platformSupported` function lets you query platform support.
///
/// returns: The ASCII encoded GLFW version string.
///
/// remark: This function may be called before @ref glfw.Init.
///
/// pointer_lifetime: The returned string is static and compile-time generated.
///
/// thread_safety: This function may be called from any thread.
pub inline fn getVersionString() [:0]const u8 {
return std.mem.span(@as([*:0]const u8, @ptrCast(c.glfwGetVersionString())));
}
/// Returns the currently selected platform.
///
/// This function returns the platform that was selected during initialization. The returned value
/// will be one of `glfw.PlatformType.win32`, `glfw.PlatformType.cocoa`,
/// `glfw.PlatformType.wayland`, `glfw.PlatformType.x11` or `glfw.PlatformType.null`.
///
/// thread_safety: This function may be called from any thread.
pub fn getPlatform() PlatformType {
internal_debug.assertInitialized();
return @as(PlatformType, @enumFromInt(c.glfwGetPlatform()));
}
/// Returns whether the library includes support for the specified platform.
///
/// This function returns whether the library was compiled with support for the specified platform.
/// The platform must be one of `glfw.PlatformType.win32`, `glfw.PlatformType.cocoa`,
/// `glfw.PlatformType.wayland`, `glfw.PlatformType.x11` or `glfw.PlatformType.null`.
///
/// remark: This function may be called before glfw.Init.
///
/// thread_safety: This function may be called from any thread.
pub fn platformSupported(platform: PlatformType) bool {
internal_debug.assertInitialized();
return c.glfwPlatformSupported(@intFromEnum(platform)) == c.GLFW_TRUE;
}
/// Processes all pending events.
///
/// This function processes only those events that are already in the event queue and then returns
/// immediately. Processing events will cause the window and input callbacks associated with those
/// events to be called.
///
/// On some platforms, a window move, resize or menu operation will cause event processing to
/// block. This is due to how event processing is designed on those platforms. You can use the
/// window refresh callback (see window_refresh) to redraw the contents of your window when
/// necessary during such operations.
///
/// Do not assume that callbacks you set will _only_ be called in response to event processing
/// functions like this one. While it is necessary to poll for events, window systems that require
/// GLFW to register callbacks of its own can pass events to GLFW in response to many window system
/// function calls. GLFW will pass those events on to the application callbacks before returning.
///
/// Event processing is not required for joystick input to work.
///
/// Possible errors include glfw.ErrorCode.PlatformError.
///
/// @reentrancy This function must not be called from a callback.
///
/// @thread_safety This function must only be called from the main thread.
///
/// see also: events, glfw.waitEvents, glfw.waitEventsTimeout
pub inline fn pollEvents() void {
internal_debug.assertInitialized();
c.glfwPollEvents();
}
/// Waits until events are queued and processes them.
///
/// This function puts the calling thread to sleep until at least one event is available in the
/// event queue. Once one or more events are available, it behaves exactly like glfw.pollEvents,
/// i.e. the events in the queue are processed and the function then returns immediately.
/// Processing events will cause the window and input callbacks associated with those events to be
/// called.
///
/// Since not all events are associated with callbacks, this function may return without a callback
/// having been called even if you are monitoring all callbacks.
///
/// On some platforms, a window move, resize or menu operation will cause event processing to
/// block. This is due to how event processing is designed on those platforms. You can use the
/// window refresh callback (see window_refresh) to redraw the contents of your window when
/// necessary during such operations.
///
/// Do not assume that callbacks you set will _only_ be called in response to event processing
/// functions like this one. While it is necessary to poll for events, window systems that require
/// GLFW to register callbacks of its own can pass events to GLFW in response to many window system
/// function calls. GLFW will pass those events on to the application callbacks before returning.
///
/// Event processing is not required for joystick input to work.
///
/// Possible errors include glfw.ErrorCode.PlatformError.
///
/// @reentrancy This function must not be called from a callback.
///
/// @thread_safety This function must only be called from the main thread.
///
/// see also: events, glfw.pollEvents, glfw.waitEventsTimeout
pub inline fn waitEvents() void {
internal_debug.assertInitialized();
c.glfwWaitEvents();
}
/// Waits with timeout until events are queued and processes them.
///
/// This function puts the calling thread to sleep until at least one event is available in the
/// event queue, or until the specified timeout is reached. If one or more events are available, it
/// behaves exactly like glfw.pollEvents, i.e. the events in the queue are processed and the
/// function then returns immediately. Processing events will cause the window and input callbacks
/// associated with those events to be called.
///
/// The timeout value must be a positive finite number.
///
/// Since not all events are associated with callbacks, this function may return without a callback
/// having been called even if you are monitoring all callbacks.
///
/// On some platforms, a window move, resize or menu operation will cause event processing to
/// block. This is due to how event processing is designed on those platforms. You can use the
/// window refresh callback (see window_refresh) to redraw the contents of your window when
/// necessary during such operations.
///
/// Do not assume that callbacks you set will _only_ be called in response to event processing
/// functions like this one. While it is necessary to poll for events, window systems that require
/// GLFW to register callbacks of its own can pass events to GLFW in response to many window system
/// function calls. GLFW will pass those events on to the application callbacks before returning.
///
/// Event processing is not required for joystick input to work.
///
/// @param[in] timeout The maximum amount of time, in seconds, to wait.
///
/// Possible errors include glfw.ErrorCode.InvalidValue and glfw.ErrorCode.PlatformError.
///
/// @reentrancy This function must not be called from a callback.
///
/// @thread_safety This function must only be called from the main thread.
///
/// see also: events, glfw.pollEvents, glfw.waitEvents
pub inline fn waitEventsTimeout(timeout: f64) void {
internal_debug.assertInitialized();
std.debug.assert(!std.math.isNan(timeout));
std.debug.assert(timeout >= 0);
std.debug.assert(timeout <= std.math.floatMax(f64));
c.glfwWaitEventsTimeout(timeout);
}
/// Posts an empty event to the event queue.
///
/// This function posts an empty event from the current thread to the event queue, causing
/// glfw.waitEvents or glfw.waitEventsTimeout to return.
///
/// Possible errors include glfw.ErrorCode.PlatformError.
///
/// @thread_safety This function may be called from any thread.
///
/// see also: events, glfw.waitEvents, glfw.waitEventsTimeout
pub inline fn postEmptyEvent() void {
internal_debug.assertInitialized();
c.glfwPostEmptyEvent();
}
/// Returns whether raw mouse motion is supported.
///
/// This function returns whether raw mouse motion is supported on the current system. This status
/// does not change after GLFW has been initialized so you only need to check this once. If you
/// attempt to enable raw motion on a system that does not support it, glfw.ErrorCode.PlatformError
/// will be emitted.
///
/// Raw mouse motion is closer to the actual motion of the mouse across a surface. It is not
/// affected by the scaling and acceleration applied to the motion of the desktop cursor. That
/// processing is suitable for a cursor while raw motion is better for controlling for example a 3D
/// camera. Because of this, raw mouse motion is only provided when the cursor is disabled.
///
/// @return `true` if raw mouse motion is supported on the current machine, or `false` otherwise.
///
/// @thread_safety This function must only be called from the main thread.
///
/// see also: raw_mouse_motion, glfw.setInputMode
pub inline fn rawMouseMotionSupported() bool {
internal_debug.assertInitialized();
return c.glfwRawMouseMotionSupported() == c.GLFW_TRUE;
}
pub fn basicTest() !void {
defer clearError(); // clear any error we generate
if (!init(.{})) {
std.log.err("failed to initialize GLFW: {?s}", .{getErrorString()});
std.process.exit(1);
}
defer terminate();
const window = Window.create(640, 480, "GLFW example", null, null, .{}) orelse {
std.log.warn("failed to create window: {?s}", .{getErrorString()});
return error.SkipZigTest; // note: we don't exit(1) here because our CI can't open windows
};
defer window.destroy();
const start = std.time.milliTimestamp();
while (std.time.milliTimestamp() < start + 1000 and !window.shouldClose()) {
c.glfwPollEvents();
}
}
test {
std.testing.refAllDeclsRecursive(@This());
}
test "getVersionString" {
std.debug.print("\nGLFW version v{}.{}.{}\n", .{ version.major, version.minor, version.revision });
std.debug.print("\nstring: {s}\n", .{getVersionString()});
}
test "init" {
_ = init(.{ .cocoa_chdir_resources = true });
if (getErrorString()) |err| {
std.log.err("failed to initialize GLFW: {?s}", .{err});
std.process.exit(1);
}
defer terminate();
}
test "pollEvents" {
defer clearError(); // clear any error we generate
if (!init(.{})) {
std.log.err("failed to initialize GLFW: {?s}", .{getErrorString()});
std.process.exit(1);
}
defer terminate();
pollEvents();
}
test "waitEventsTimeout" {
defer clearError(); // clear any error we generate
if (!init(.{})) {
std.log.err("failed to initialize GLFW: {?s}", .{getErrorString()});
std.process.exit(1);
}
defer terminate();
waitEventsTimeout(0.25);
}
test "postEmptyEvent_and_waitEvents" {
defer clearError(); // clear any error we generate
if (!init(.{})) {
std.log.err("failed to initialize GLFW: {?s}", .{getErrorString()});
std.process.exit(1);
}
defer terminate();
postEmptyEvent();
waitEvents();
}
test "rawMouseMotionSupported" {
defer clearError(); // clear any error we generate
if (!init(.{})) {
std.log.err("failed to initialize GLFW: {?s}", .{getErrorString()});
std.process.exit(1);
}
defer terminate();
_ = rawMouseMotionSupported();
}
test "basic" {
try basicTest();
}
|
0 | repos/mach-glfw | repos/mach-glfw/src/Image.zig | //! Image data
//!
//!
//! This describes a single 2D image. See the documentation for each related function what the
//! expected pixel format is.
//!
//! see also: cursor_custom, window_icon
//!
//! It may be .owned (e.g. in the case of an image initialized by you for passing into glfw) or not
//! .owned (e.g. in the case of one gotten via glfw) If it is .owned, deinit should be called to
//! free the memory. It is safe to call deinit even if not .owned.
const std = @import("std");
const testing = std.testing;
const mem = std.mem;
const c = @import("c.zig").c;
const Image = @This();
/// The width of this image, in pixels.
width: u32,
/// The height of this image, in pixels.
height: u32,
/// The pixel data of this image, arranged left-to-right, top-to-bottom.
pixels: []u8,
/// Whether or not the pixels data is owned by you (true) or GLFW (false).
owned: bool,
/// Initializes a new owned image with the given size and pixel_data_len of undefined .pixel values.
pub inline fn init(allocator: mem.Allocator, width: u32, height: u32, pixel_data_len: usize) !Image {
const buf = try allocator.alloc(u8, pixel_data_len);
return Image{
.width = width,
.height = height,
.pixels = buf,
.owned = true,
};
}
/// Turns a GLFW / C image into the nicer Zig type, and sets `.owned = false`.
///
/// The length of pixel data must be supplied, as GLFW's image type does not itself describe the
/// number of bytes required per pixel / the length of the pixel data array.
///
/// The returned memory is valid for as long as the GLFW C memory is valid.
pub inline fn fromC(native: c.GLFWimage, pixel_data_len: usize) Image {
return Image{
.width = @as(u32, @intCast(native.width)),
.height = @as(u32, @intCast(native.height)),
.pixels = native.pixels[0..pixel_data_len],
.owned = false,
};
}
/// Turns the nicer Zig type into a GLFW / C image, for passing into GLFW C functions.
///
/// The returned memory is valid for as long as the Zig memory is valid.
pub inline fn toC(self: Image) c.GLFWimage {
return c.GLFWimage{
.width = @as(c_int, @intCast(self.width)),
.height = @as(c_int, @intCast(self.height)),
.pixels = &self.pixels[0],
};
}
/// Deinitializes the memory using the allocator iff `.owned = true`.
pub inline fn deinit(self: Image, allocator: mem.Allocator) void {
if (self.owned) allocator.free(self.pixels);
}
test "conversion" {
const allocator = testing.allocator;
const image = try Image.init(allocator, 256, 256, 256 * 256 * 4);
defer image.deinit(allocator);
const glfw = image.toC();
_ = Image.fromC(glfw, image.width * image.height * 4);
}
|
0 | repos/mach-glfw | repos/mach-glfw/src/GammaRamp.zig | //! Gamma ramp for monitors and related functions.
//!
//! It may be .owned (e.g. in the case of a gamma ramp initialized by you for passing into
//! glfw.Monitor.setGammaRamp) or not .owned (e.g. in the case of one gotten via
//! glfw.Monitor.getGammaRamp.) If it is .owned, deinit should be called to free the memory. It is
//! safe to call deinit even if not .owned.
//!
//! see also: monitor_gamma, glfw.Monitor.getGammaRamp
const std = @import("std");
const testing = std.testing;
const mem = std.mem;
const c = @import("c.zig").c;
const GammaRamp = @This();
red: []u16,
green: []u16,
blue: []u16,
owned: ?[]u16,
/// Initializes a new owned gamma ramp with the given array size and undefined values.
///
/// see also: glfw.Monitor.getGammaRamp
pub inline fn init(allocator: mem.Allocator, size: usize) !GammaRamp {
const buf = try allocator.alloc(u16, size * 3);
return GammaRamp{
.red = buf[size * 0 .. (size * 0) + size],
.green = buf[size * 1 .. (size * 1) + size],
.blue = buf[size * 2 .. (size * 2) + size],
.owned = buf,
};
}
/// Turns a GLFW / C gamma ramp into the nicer Zig type, and sets `.owned = false`.
///
/// The returned memory is valid for as long as the GLFW C memory is valid.
pub inline fn fromC(native: c.GLFWgammaramp) GammaRamp {
return GammaRamp{
.red = native.red[0..native.size],
.green = native.green[0..native.size],
.blue = native.blue[0..native.size],
.owned = null,
};
}
/// Turns the nicer Zig type into a GLFW / C gamma ramp, for passing into GLFW C functions.
///
/// The returned memory is valid for as long as the Zig memory is valid.
pub inline fn toC(self: GammaRamp) c.GLFWgammaramp {
std.debug.assert(self.red.len == self.green.len);
std.debug.assert(self.red.len == self.blue.len);
return c.GLFWgammaramp{
.red = &self.red[0],
.green = &self.green[0],
.blue = &self.blue[0],
.size = @as(c_uint, @intCast(self.red.len)),
};
}
/// Deinitializes the memory using the allocator iff `.owned = true`.
pub inline fn deinit(self: GammaRamp, allocator: mem.Allocator) void {
if (self.owned) |buf| allocator.free(buf);
}
test "conversion" {
const allocator = testing.allocator;
const ramp = try GammaRamp.init(allocator, 256);
defer ramp.deinit(allocator);
const glfw = ramp.toC();
_ = GammaRamp.fromC(glfw);
}
|
0 | repos/mach-glfw | repos/mach-glfw/src/clipboard.zig | const std = @import("std");
const c = @import("c.zig").c;
const internal_debug = @import("internal_debug.zig");
/// Sets the clipboard to the specified string.
///
/// This function sets the system clipboard to the specified, UTF-8 encoded string.
///
/// @param[in] string A UTF-8 encoded string.
///
/// Possible errors include glfw.ErrorCode.PlatformError.
///
/// @pointer_lifetime The specified string is copied before this function returns.
///
/// @thread_safety This function must only be called from the main thread.
///
/// see also: clipboard, glfwGetClipboardString
pub inline fn setClipboardString(value: [*:0]const u8) void {
internal_debug.assertInitialized();
c.glfwSetClipboardString(null, value);
}
/// Returns the contents of the clipboard as a string.
///
/// This function returns the contents of the system clipboard, if it contains or is convertible to
/// a UTF-8 encoded string. If the clipboard is empty or if its contents cannot be converted,
/// glfw.ErrorCode.FormatUnavailable is returned.
///
/// @return The contents of the clipboard as a UTF-8 encoded string.
///
/// Possible errors include glfw.ErrorCode.FormatUnavailable and glfw.ErrorCode.PlatformError.
/// null is returned in the event of an error.
///
/// @pointer_lifetime The returned string is allocated and freed by GLFW. You should not free it
/// yourself. It is valid until the next call to glfw.getClipboardString or glfw.setClipboardString
/// or until the library is terminated.
///
/// @thread_safety This function must only be called from the main thread.
///
/// see also: clipboard, glfwSetClipboardString
pub inline fn getClipboardString() ?[:0]const u8 {
internal_debug.assertInitialized();
if (c.glfwGetClipboardString(null)) |c_str| return std.mem.span(@as([*:0]const u8, @ptrCast(c_str)));
return null;
}
test "setClipboardString" {
const glfw = @import("main.zig");
defer glfw.clearError(); // clear any error we generate
if (!glfw.init(.{})) {
std.log.err("failed to initialize GLFW: {?s}", .{glfw.getErrorString()});
std.process.exit(1);
}
defer glfw.terminate();
glfw.setClipboardString("hello mach");
}
test "getClipboardString" {
const glfw = @import("main.zig");
defer glfw.clearError(); // clear any error we generate
if (!glfw.init(.{})) {
std.log.err("failed to initialize GLFW: {?s}", .{glfw.getErrorString()});
std.process.exit(1);
}
defer glfw.terminate();
_ = glfw.getClipboardString();
}
|
0 | repos/mach-glfw | repos/mach-glfw/src/errors.zig | //! Errors
const testing = @import("std").testing;
const mem = @import("std").mem;
const c = @import("c.zig").c;
/// Errors that GLFW can produce.
pub const ErrorCode = error{
/// GLFW has not been initialized.
///
/// This occurs if a GLFW function was called that must not be called unless the library is
/// initialized.
NotInitialized,
/// No context is current for this thread.
///
/// This occurs if a GLFW function was called that needs and operates on the current OpenGL or
/// OpenGL ES context but no context is current on the calling thread. One such function is
/// glfw.SwapInterval.
NoCurrentContext,
/// One of the arguments to the function was an invalid enum value.
///
/// One of the arguments to the function was an invalid enum value, for example requesting
/// glfw.red_bits with glfw.getWindowAttrib.
InvalidEnum,
/// One of the arguments to the function was an invalid value.
///
/// One of the arguments to the function was an invalid value, for example requesting a
/// non-existent OpenGL or OpenGL ES version like 2.7.
///
/// Requesting a valid but unavailable OpenGL or OpenGL ES version will instead result in a
/// glfw.ErrorCode.VersionUnavailable error.
InvalidValue,
/// A memory allocation failed.
OutOfMemory,
/// GLFW could not find support for the requested API on the system.
///
/// The installed graphics driver does not support the requested API, or does not support it
/// via the chosen context creation API. Below are a few examples.
///
/// Some pre-installed Windows graphics drivers do not support OpenGL. AMD only supports
/// OpenGL ES via EGL, while Nvidia and Intel only support it via a WGL or GLX extension. macOS
/// does not provide OpenGL ES at all. The Mesa EGL, OpenGL and OpenGL ES libraries do not
/// interface with the Nvidia binary driver. Older graphics drivers do not support Vulkan.
APIUnavailable,
/// The requested OpenGL or OpenGL ES version (including any requested context or framebuffer
/// hints) is not available on this machine.
///
/// The machine does not support your requirements. If your application is sufficiently
/// flexible, downgrade your requirements and try again. Otherwise, inform the user that their
/// machine does not match your requirements.
///
/// Future invalid OpenGL and OpenGL ES versions, for example OpenGL 4.8 if 5.0 comes out
/// before the 4.x series gets that far, also fail with this error and not glfw.ErrorCode.InvalidValue,
/// because GLFW cannot know what future versions will exist.
VersionUnavailable,
/// A platform-specific error occurred that does not match any of the more specific categories.
///
/// A bug or configuration error in GLFW, the underlying operating system or its drivers, or a
/// lack of required resources. Report the issue to our [issue tracker](https://github.com/glfw/glfw/issues).
PlatformError,
/// The requested format is not supported or available.
///
/// If emitted during window creation, the requested pixel format is not supported.
///
/// If emitted when querying the clipboard, the contents of the clipboard could not be
/// converted to the requested format.
///
/// If emitted during window creation, one or more hard constraints did not match any of the
/// available pixel formats. If your application is sufficiently flexible, downgrade your
/// requirements and try again. Otherwise, inform the user that their machine does not match
/// your requirements.
///
/// If emitted when querying the clipboard, ignore the error or report it to the user, as
/// appropriate.
FormatUnavailable,
/// The specified window does not have an OpenGL or OpenGL ES context.
///
/// A window that does not have an OpenGL or OpenGL ES context was passed to a function that
/// requires it to have one.
NoWindowContext,
/// The specified cursor shape is not available.
///
/// The specified standard cursor shape is not available, either because the
/// current platform cursor theme does not provide it or because it is not
/// available on the platform.
///
/// analysis: Platform or system settings limitation. Pick another standard cursor shape or
/// create a custom cursor.
CursorUnavailable,
/// The requested feature is not provided by the platform.
///
/// The requested feature is not provided by the platform, so GLFW is unable to
/// implement it. The documentation for each function notes if it could emit
/// this error.
///
/// analysis: Platform or platform version limitation. The error can be ignored
/// unless the feature is critical to the application.
///
/// A function call that emits this error has no effect other than the error and
/// updating any existing out parameters.
///
FeatureUnavailable,
/// The requested feature is not implemented for the platform.
///
/// The requested feature has not yet been implemented in GLFW for this platform.
///
/// analysis: An incomplete implementation of GLFW for this platform, hopefully
/// fixed in a future release. The error can be ignored unless the feature is
/// critical to the application.
///
/// A function call that emits this error has no effect other than the error and
/// updating any existing out parameters.
///
FeatureUnimplemented,
/// Platform unavailable or no matching platform was found.
///
/// If emitted during initialization, no matching platform was found. If glfw.InitHint.platform
/// is set to `.any_platform`, GLFW could not detect any of the platforms supported by this
/// library binary, except for the Null platform. If set to a specific platform, it is either
/// not supported by this library binary or GLFW was not able to detect it.
///
/// If emitted by a native access function, GLFW was initialized for a different platform
/// than the function is for.
///
/// analysis: Failure to detect any platform usually only happens on non-macOS Unix
/// systems, either when no window system is running or the program was run from
/// a terminal that does not have the necessary environment variables. Fall back to
/// a different platform if possible or notify the user that no usable platform was
/// detected.
///
/// Failure to detect a specific platform may have the same cause as above or be because
/// support for that platform was not compiled in. Call glfw.platformSupported to
/// check whether a specific platform is supported by a library binary.
///
PlatformUnavailable,
};
/// An error produced by GLFW and the description associated with it.
pub const Error = struct {
error_code: ErrorCode,
description: [:0]const u8,
};
fn convertError(e: c_int) ErrorCode!void {
return switch (e) {
c.GLFW_NO_ERROR => {},
c.GLFW_NOT_INITIALIZED => ErrorCode.NotInitialized,
c.GLFW_NO_CURRENT_CONTEXT => ErrorCode.NoCurrentContext,
c.GLFW_INVALID_ENUM => ErrorCode.InvalidEnum,
c.GLFW_INVALID_VALUE => ErrorCode.InvalidValue,
c.GLFW_OUT_OF_MEMORY => ErrorCode.OutOfMemory,
c.GLFW_API_UNAVAILABLE => ErrorCode.APIUnavailable,
c.GLFW_VERSION_UNAVAILABLE => ErrorCode.VersionUnavailable,
c.GLFW_PLATFORM_ERROR => ErrorCode.PlatformError,
c.GLFW_FORMAT_UNAVAILABLE => ErrorCode.FormatUnavailable,
c.GLFW_NO_WINDOW_CONTEXT => ErrorCode.NoWindowContext,
c.GLFW_CURSOR_UNAVAILABLE => ErrorCode.CursorUnavailable,
c.GLFW_FEATURE_UNAVAILABLE => ErrorCode.FeatureUnavailable,
c.GLFW_FEATURE_UNIMPLEMENTED => ErrorCode.FeatureUnimplemented,
c.GLFW_PLATFORM_UNAVAILABLE => ErrorCode.PlatformUnavailable,
else => unreachable,
};
}
/// Clears the last error and the error description pointer for the calling thread. Does nothing if
/// no error has occurred since the last call.
///
/// @remark This function may be called before @ref glfwInit.
///
/// @thread_safety This function may be called from any thread.
pub inline fn clearError() void {
_ = c.glfwGetError(null);
}
/// Returns and clears the last error for the calling thread.
///
/// This function returns and clears the error code of the last error that occurred on the calling
/// thread, along with a UTF-8 encoded human-readable description of it. If no error has occurred
/// since the last call, it returns GLFW_NO_ERROR (zero) and the description pointer is set to
/// `NULL`.
///
/// @pointer_lifetime The returned string is allocated and freed by GLFW. You should not free it
/// yourself. It is guaranteed to be valid only until the next error occurs or the library is
/// terminated.
///
/// @remark This function may be called before @ref glfwInit.
///
/// @thread_safety This function may be called from any thread.
pub inline fn getError() ?Error {
var desc: [*c]const u8 = null;
convertError(c.glfwGetError(&desc)) catch |error_code| {
return .{
.error_code = error_code,
.description = mem.sliceTo(desc, 0),
};
};
return null;
}
pub inline fn mustGetError() Error {
return getError() orelse {
@panic("glfw: mustGetError called but no error is present");
};
}
/// Returns and clears the last error for the calling thread.
///
/// This function returns and clears the error code of the last error that occurred on the calling
/// thread. If no error has occurred since the last call, it returns GLFW_NO_ERROR (zero).
///
/// @return The last error code for the calling thread, or @ref GLFW_NO_ERROR (zero).
///
/// @remark This function may be called before @ref glfwInit.
///
/// @thread_safety This function may be called from any thread.
pub inline fn getErrorCode() ErrorCode!void {
return convertError(c.glfwGetError(null));
}
/// Returns and clears the last error code for the calling thread. If no error is present, this
/// function panics.
pub inline fn mustGetErrorCode() ErrorCode {
try getErrorCode();
@panic("glfw: mustGetErrorCode called but no error is present");
}
/// Returns and clears the last error description for the calling thread.
///
/// This function returns a UTF-8 encoded human-readable description of the last error that occured
/// on the calling thread. If no error has occurred since the last call, it returns null.
///
/// @pointer_lifetime The returned string is allocated and freed by GLFW. You should not free it
/// yourself. It is guaranteed to be valid only until the next error occurs or the library is
/// terminated.
///
/// @remark This function may be called before @ref glfwInit.
///
/// @thread_safety This function may be called from any thread.
pub inline fn getErrorString() ?[:0]const u8 {
var desc: [*c]const u8 = null;
const error_code = c.glfwGetError(&desc);
if (error_code != c.GLFW_NO_ERROR) {
return mem.sliceTo(desc, 0);
}
return null;
}
/// Returns and clears the last error description for the calling thread. If no error is present,
/// this function panics.
pub inline fn mustGetErrorString() [:0]const u8 {
return getErrorString() orelse {
@panic("glfw: mustGetErrorString called but no error is present");
};
}
/// Sets the error callback.
///
/// This function sets the error callback, which is called with an error code
/// and a human-readable description each time a GLFW error occurs.
///
/// The error code is set before the callback is called. Calling @ref
/// glfwGetError from the error callback will return the same value as the error
/// code argument.
///
/// The error callback is called on the thread where the error occurred. If you
/// are using GLFW from multiple threads, your error callback needs to be
/// written accordingly.
///
/// Because the description string may have been generated specifically for that
/// error, it is not guaranteed to be valid after the callback has returned. If
/// you wish to use it after the callback returns, you need to make a copy.
///
/// Once set, the error callback remains set even after the library has been
/// terminated.
///
/// @param[in] callback The new callback, or `NULL` to remove the currently set
/// callback.
///
/// @callback_param `error_code` An error code. Future releases may add more error codes.
/// @callback_param `description` A UTF-8 encoded string describing the error.
///
/// @errors None.
///
/// @remark This function may be called before @ref glfwInit.
///
/// @thread_safety This function must only be called from the main thread.
pub fn setErrorCallback(comptime callback: ?fn (error_code: ErrorCode, description: [:0]const u8) void) void {
if (callback) |user_callback| {
const CWrapper = struct {
pub fn errorCallbackWrapper(err_int: c_int, c_description: [*c]const u8) callconv(.C) void {
convertError(err_int) catch |error_code| {
user_callback(error_code, mem.sliceTo(c_description, 0));
};
}
};
_ = c.glfwSetErrorCallback(CWrapper.errorCallbackWrapper);
return;
}
_ = c.glfwSetErrorCallback(null);
}
test "set error callback" {
const TestStruct = struct {
pub fn callback(_: ErrorCode, _: [:0]const u8) void {}
};
setErrorCallback(TestStruct.callback);
}
test "error string" {
try testing.expect(getErrorString() == null);
}
test "error code" {
try getErrorCode();
}
test "error code and string" {
try testing.expect(getError() == null);
}
test "clear error" {
clearError();
}
|
0 | repos/mach-glfw | repos/mach-glfw/src/internal_debug.zig | const std = @import("std");
const builtin = @import("builtin");
const is_debug = builtin.mode == .Debug;
var glfw_initialized = if (is_debug) false else @as(void, {});
pub inline fn toggleInitialized() void {
if (is_debug) glfw_initialized = !glfw_initialized;
}
pub inline fn assertInitialized() void {
if (is_debug) std.debug.assert(glfw_initialized);
}
pub inline fn assumeInitialized() void {
glfw_initialized = true;
}
|
0 | repos/mach-glfw | repos/mach-glfw/src/vulkan.zig | const std = @import("std");
const builtin = @import("builtin");
const c = @import("c.zig").c;
const Window = @import("Window.zig");
const internal_debug = @import("internal_debug.zig");
/// Sets the desired Vulkan `vkGetInstanceProcAddr` function.
///
/// This function sets the `vkGetInstanceProcAddr` function that GLFW will use for all
/// Vulkan related entry point queries.
///
/// This feature is mostly useful on macOS, if your copy of the Vulkan loader is in
/// a location where GLFW cannot find it through dynamic loading, or if you are still
/// using the static library version of the loader.
///
/// If set to `NULL`, GLFW will try to load the Vulkan loader dynamically by its standard
/// name and get this function from there. This is the default behavior.
///
/// The standard name of the loader is `vulkan-1.dll` on Windows, `libvulkan.so.1` on
/// Linux and other Unix-like systems and `libvulkan.1.dylib` on macOS. If your code is
/// also loading it via these names then you probably don't need to use this function.
///
/// The function address you set is never reset by GLFW, but it only takes effect during
/// initialization. Once GLFW has been initialized, any updates will be ignored until the
/// library is terminated and initialized again.
///
/// remark: This function may be called before glfw.Init.
///
/// thread_safety: This function must only be called from the main thread.
pub fn initVulkanLoader(loader_function: ?VKGetInstanceProcAddr) void {
c.glfwInitVulkanLoader(loader_function orelse null);
}
pub const VKGetInstanceProcAddr = *const fn (vk_instance: c.VkInstance, name: [*c]const u8) callconv(.C) ?VKProc;
/// Returns whether the Vulkan loader and an ICD have been found.
///
/// This function returns whether the Vulkan loader and any minimally functional ICD have been
/// found.
///
/// The availability of a Vulkan loader and even an ICD does not by itself guarantee that surface
/// creation or even instance creation is possible. Call glfw.getRequiredInstanceExtensions
/// to check whether the extensions necessary for Vulkan surface creation are available and
/// glfw.getPhysicalDevicePresentationSupport to check whether a queue family of a physical device
/// supports image presentation.
///
/// @return `true` if Vulkan is minimally available, or `false` otherwise.
///
/// @thread_safety This function may be called from any thread.
pub inline fn vulkanSupported() bool {
internal_debug.assertInitialized();
const supported = c.glfwVulkanSupported();
return supported == c.GLFW_TRUE;
}
/// Returns the Vulkan instance extensions required by GLFW.
///
/// This function returns an array of names of Vulkan instance extensions required by GLFW for
/// creating Vulkan surfaces for GLFW windows. If successful, the list will always contain
/// `VK_KHR_surface`, so if you don't require any additional extensions you can pass this list
/// directly to the `VkInstanceCreateInfo` struct.
///
/// If Vulkan is not available on the machine, this function returns null and generates a
/// glfw.ErrorCode.APIUnavailable error. Call glfw.vulkanSupported to check whether Vulkan is at
/// least minimally available.
///
/// If Vulkan is available but no set of extensions allowing window surface creation was found,
/// this function returns null. You may still use Vulkan for off-screen rendering and compute work.
///
/// Possible errors include glfw.ErrorCode.APIUnavailable.
/// Returns null in the event of an error.
///
/// Additional extensions may be required by future versions of GLFW. You should check if any
/// extensions you wish to enable are already in the returned array, as it is an error to specify
/// an extension more than once in the `VkInstanceCreateInfo` struct.
///
/// @pointer_lifetime The returned array is allocated and freed by GLFW. You should not free it
/// yourself. It is guaranteed to be valid only until the library is terminated.
///
/// @thread_safety This function may be called from any thread.
///
/// see also: vulkan_ext, glfwCreateWindowSurface
pub inline fn getRequiredInstanceExtensions() ?[][*:0]const u8 {
internal_debug.assertInitialized();
var count: u32 = 0;
if (c.glfwGetRequiredInstanceExtensions(&count)) |extensions| return @as([*][*:0]const u8, @ptrCast(extensions))[0..count];
return null;
}
/// Vulkan API function pointer type.
///
/// Generic function pointer used for returning Vulkan API function pointers.
///
/// see also: vulkan_proc, glfw.getInstanceProcAddress
pub const VKProc = *const fn () callconv(if (builtin.os.tag == .windows and builtin.cpu.arch == .x86) .Stdcall else .C) void;
/// Returns the address of the specified Vulkan instance function.
///
/// This function returns the address of the specified Vulkan core or extension function for the
/// specified instance. If instance is set to null it can return any function exported from the
/// Vulkan loader, including at least the following functions:
///
/// - `vkEnumerateInstanceExtensionProperties`
/// - `vkEnumerateInstanceLayerProperties`
/// - `vkCreateInstance`
/// - `vkGetInstanceProcAddr`
///
/// If Vulkan is not available on the machine, this function returns null and generates a
/// glfw.ErrorCode.APIUnavailable error. Call glfw.vulkanSupported to check whether Vulkan is at
/// least minimally available.
///
/// This function is equivalent to calling `vkGetInstanceProcAddr` with a platform-specific query
/// of the Vulkan loader as a fallback.
///
/// @param[in] instance The Vulkan instance to query, or null to retrieve functions related to
/// instance creation.
/// @param[in] procname The ASCII encoded name of the function.
/// @return The address of the function, or null if an error occurred.
///
/// To maintain ABI compatability with the C glfwGetInstanceProcAddress, as it is commonly passed
/// into libraries expecting that exact ABI, this function does not return an error. Instead, if
/// glfw.ErrorCode.NotInitialized or glfw.ErrorCode.APIUnavailable would occur this function will panic.
/// You may check glfw.vulkanSupported prior to invoking this function.
///
/// @pointer_lifetime The returned function pointer is valid until the library is terminated.
///
/// @thread_safety This function may be called from any thread.
pub fn getInstanceProcAddress(vk_instance: ?*anyopaque, proc_name: [*:0]const u8) callconv(.C) ?VKProc {
internal_debug.assertInitialized();
if (c.glfwGetInstanceProcAddress(if (vk_instance) |v| @as(c.VkInstance, @ptrCast(v)) else null, proc_name)) |proc_address| return proc_address;
return null;
}
/// Returns whether the specified queue family can present images.
///
/// This function returns whether the specified queue family of the specified physical device
/// supports presentation to the platform GLFW was built for.
///
/// If Vulkan or the required window surface creation instance extensions are not available on the
/// machine, or if the specified instance was not created with the required extensions, this
/// function returns `GLFW_FALSE` and generates a glfw.ErrorCode.APIUnavailable error. Call
/// glfw.vulkanSupported to check whether Vulkan is at least minimally available and
/// glfw.getRequiredInstanceExtensions to check what instance extensions are required.
///
/// @param[in] instance The instance that the physical device belongs to.
/// @param[in] device The physical device that the queue family belongs to.
/// @param[in] queuefamily The index of the queue family to query.
/// @return `true` if the queue family supports presentation, or `false` otherwise.
///
/// Possible errors include glfw.ErrorCode.APIUnavailable and glfw.ErrorCode.PlatformError.
/// Returns false in the event of an error.
///
/// macos: This function currently always returns `true`, as the `VK_MVK_macos_surface` and
/// 'VK_EXT_metal_surface' extension does not provide a `vkGetPhysicalDevice*PresentationSupport` type function.
///
/// @thread_safety This function may be called from any thread. For synchronization details of
/// Vulkan objects, see the Vulkan specification.
///
/// see also: vulkan_present
pub inline fn getPhysicalDevicePresentationSupport(
vk_instance: *anyopaque,
vk_physical_device: *anyopaque,
queue_family: u32,
) bool {
internal_debug.assertInitialized();
return c.glfwGetPhysicalDevicePresentationSupport(
@as(c.VkInstance, @ptrCast(vk_instance)),
@as(c.VkPhysicalDevice, @ptrCast(vk_physical_device)),
queue_family,
) == c.GLFW_TRUE;
}
/// Creates a Vulkan surface for the specified window.
///
/// This function creates a Vulkan surface for the specified window.
///
/// If the Vulkan loader or at least one minimally functional ICD were not found, this function
/// returns `VK_ERROR_INITIALIZATION_FAILED` and generates a glfw.ErrorCode.APIUnavailable error. Call
/// glfw.vulkanSupported to check whether Vulkan is at least minimally available.
///
/// If the required window surface creation instance extensions are not available or if the
/// specified instance was not created with these extensions enabled, this function returns `VK_ERROR_EXTENSION_NOT_PRESENT`
/// and generates a glfw.ErrorCode.APIUnavailable error. Call glfw.getRequiredInstanceExtensions to
/// check what instance extensions are required.
///
/// The window surface cannot be shared with another API so the window must have been created with
/// the client api hint set to `GLFW_NO_API` otherwise it generates a glfw.ErrorCode.InvalidValue error
/// and returns `VK_ERROR_NATIVE_WINDOW_IN_USE_KHR`.
///
/// The window surface must be destroyed before the specified Vulkan instance. It is the
/// responsibility of the caller to destroy the window surface. GLFW does not destroy it for you.
/// Call `vkDestroySurfaceKHR` to destroy the surface.
///
/// @param[in] vk_instance The Vulkan instance to create the surface in.
/// @param[in] window The window to create the surface for.
/// @param[in] vk_allocation_callbacks The allocator to use, or null to use the default
/// allocator.
/// @param[out] surface Where to store the handle of the surface. This is set
/// to `VK_NULL_HANDLE` if an error occurred.
/// @return `VkResult` type, `VK_SUCCESS` if successful, or a Vulkan error code if an
/// error occurred.
///
/// Possible errors include glfw.ErrorCode.APIUnavailable, glfw.ErrorCode.PlatformError and glfw.ErrorCode.InvalidValue
/// Returns a bool indicating success.
///
/// If an error occurs before the creation call is made, GLFW returns the Vulkan error code most
/// appropriate for the error. Appropriate use of glfw.vulkanSupported and glfw.getRequiredInstanceExtensions
/// should eliminate almost all occurrences of these errors.
///
/// macos: GLFW prefers the `VK_EXT_metal_surface` extension, with the `VK_MVK_macos_surface`
/// extension as a fallback. The name of the selected extension, if any, is included in the array
/// returned by glfw.getRequiredInstanceExtensions.
///
/// macos: This function currently only supports the `VK_MVK_macos_surface` extension from MoltenVK.
///
/// macos: This function creates and sets a `CAMetalLayer` instance for the window content view,
/// which is required for MoltenVK to function.
///
/// x11: By default GLFW prefers the `VK_KHR_xcb_surface` extension, with the `VK_KHR_xlib_surface`
/// extension as a fallback. You can make `VK_KHR_xlib_surface` the preferred extension by setting
/// glfw.InitHints.x11_xcb_vulkan_surface. The name of the selected extension, if any, is included
/// in the array returned by glfw.getRequiredInstanceExtensions.
///
/// @thread_safety This function may be called from any thread. For synchronization details of
/// Vulkan objects, see the Vulkan specification.
///
/// see also: vulkan_surface, glfw.getRequiredInstanceExtensions
pub inline fn createWindowSurface(vk_instance: anytype, window: Window, vk_allocation_callbacks: anytype, vk_surface_khr: anytype) i32 {
internal_debug.assertInitialized();
// zig-vulkan uses enums to represent opaque pointers:
// pub const Instance = enum(usize) { null_handle = 0, _ };
const instance: c.VkInstance = switch (@typeInfo(@TypeOf(vk_instance))) {
.Enum => @as(c.VkInstance, @ptrFromInt(@intFromEnum(vk_instance))),
else => @as(c.VkInstance, @ptrCast(vk_instance)),
};
return c.glfwCreateWindowSurface(
instance,
window.handle,
if (vk_allocation_callbacks == null) null else @as(*const c.VkAllocationCallbacks, @ptrCast(@alignCast(vk_allocation_callbacks))),
@as(*c.VkSurfaceKHR, @ptrCast(@alignCast(vk_surface_khr))),
);
}
test "vulkanSupported" {
const glfw = @import("main.zig");
defer glfw.clearError(); // clear any error we generate
if (!glfw.init(.{})) {
std.log.err("failed to initialize GLFW: {?s}", .{glfw.getErrorString()});
std.process.exit(1);
}
defer glfw.terminate();
_ = glfw.vulkanSupported();
}
test "getRequiredInstanceExtensions" {
const glfw = @import("main.zig");
defer glfw.clearError(); // clear any error we generate
if (!glfw.init(.{})) {
std.log.err("failed to initialize GLFW: {?s}", .{glfw.getErrorString()});
std.process.exit(1);
}
defer glfw.terminate();
_ = glfw.getRequiredInstanceExtensions();
}
test "getInstanceProcAddress" {
const glfw = @import("main.zig");
defer glfw.clearError(); // clear any error we generate
if (!glfw.init(.{})) {
std.log.err("failed to initialize GLFW: {?s}", .{glfw.getErrorString()});
std.process.exit(1);
}
defer glfw.terminate();
// syntax check only, we don't have a real vulkan instance and so this function would panic.
_ = glfw.getInstanceProcAddress;
}
test "syntax" {
// Best we can do for these two functions in terms of testing in lieu of an actual Vulkan
// context.
_ = getPhysicalDevicePresentationSupport;
_ = createWindowSurface;
_ = initVulkanLoader;
}
|
0 | repos/mach-glfw | repos/mach-glfw/src/gamepad_button.zig | const c = @import("c.zig").c;
/// Gamepad buttons.
///
/// See glfw.getGamepadState for how these are used.
pub const GamepadButton = enum(c_int) {
a = c.GLFW_GAMEPAD_BUTTON_A,
b = c.GLFW_GAMEPAD_BUTTON_B,
x = c.GLFW_GAMEPAD_BUTTON_X,
y = c.GLFW_GAMEPAD_BUTTON_Y,
left_bumper = c.GLFW_GAMEPAD_BUTTON_LEFT_BUMPER,
right_bumper = c.GLFW_GAMEPAD_BUTTON_RIGHT_BUMPER,
back = c.GLFW_GAMEPAD_BUTTON_BACK,
start = c.GLFW_GAMEPAD_BUTTON_START,
guide = c.GLFW_GAMEPAD_BUTTON_GUIDE,
left_thumb = c.GLFW_GAMEPAD_BUTTON_LEFT_THUMB,
right_thumb = c.GLFW_GAMEPAD_BUTTON_RIGHT_THUMB,
dpad_up = c.GLFW_GAMEPAD_BUTTON_DPAD_UP,
dpad_right = c.GLFW_GAMEPAD_BUTTON_DPAD_RIGHT,
dpad_down = c.GLFW_GAMEPAD_BUTTON_DPAD_DOWN,
dpad_left = c.GLFW_GAMEPAD_BUTTON_DPAD_LEFT,
};
/// Not in the GamepadAxis enumeration as it is a duplicate value which is forbidden.
pub const last = GamepadButton.dpad_left;
/// Not in the GamepadAxis enumeration as it is a duplicate value which is forbidden.
pub const cross = GamepadButton.a;
/// Not in the GamepadAxis enumeration as it is a duplicate value which is forbidden.
pub const circle = GamepadButton.b;
/// Not in the GamepadAxis enumeration as it is a duplicate value which is forbidden.
pub const square = GamepadButton.x;
/// Not in the GamepadAxis enumeration as it is a duplicate value which is forbidden.
pub const triangle = GamepadButton.y;
|
0 | repos/mach-glfw | repos/mach-glfw/src/allocator.zig | // TODO: implement custom allocator support
// /*! @brief
// *
// * @sa @ref init_allocator
// * @sa @ref glfwInitAllocator
// *
// * @since Added in version 3.4.
// *
// * @ingroup init
// */
// typedef struct GLFWallocator
// {
// GLFWallocatefun allocate;
// GLFWreallocatefun reallocate;
// GLFWdeallocatefun deallocate;
// void* user;
// } GLFWallocator;
// /*! @brief The function pointer type for memory allocation callbacks.
// *
// * This is the function pointer type for memory allocation callbacks. A memory
// * allocation callback function has the following signature:
// * @code
// * void* function_name(size_t size, void* user)
// * @endcode
// *
// * This function must return either a memory block at least `size` bytes long,
// * or `NULL` if allocation failed. Note that not all parts of GLFW handle allocation
// * failures gracefully yet.
// *
// * This function may be called during @ref glfwInit but before the library is
// * flagged as initialized, as well as during @ref glfwTerminate after the
// * library is no longer flagged as initialized.
// *
// * Any memory allocated by this function will be deallocated during library
// * termination or earlier.
// *
// * The size will always be greater than zero. Allocations of size zero are filtered out
// * before reaching the custom allocator.
// *
// * @param[in] size The minimum size, in bytes, of the memory block.
// * @param[in] user The user-defined pointer from the allocator.
// * @return The address of the newly allocated memory block, or `NULL` if an
// * error occurred.
// *
// * @pointer_lifetime The returned memory block must be valid at least until it
// * is deallocated.
// *
// * @reentrancy This function should not call any GLFW function.
// *
// * @thread_safety This function may be called from any thread that calls GLFW functions.
// *
// * @sa @ref init_allocator
// * @sa @ref GLFWallocator
// *
// * @since Added in version 3.4.
// *
// * @ingroup init
// */
// typedef void* (* GLFWallocatefun)(size_t size, void* user);
// /*! @brief The function pointer type for memory reallocation callbacks.
// *
// * This is the function pointer type for memory reallocation callbacks.
// * A memory reallocation callback function has the following signature:
// * @code
// * void* function_name(void* block, size_t size, void* user)
// * @endcode
// *
// * This function must return a memory block at least `size` bytes long, or
// * `NULL` if allocation failed. Note that not all parts of GLFW handle allocation
// * failures gracefully yet.
// *
// * This function may be called during @ref glfwInit but before the library is
// * flagged as initialized, as well as during @ref glfwTerminate after the
// * library is no longer flagged as initialized.
// *
// * Any memory allocated by this function will be deallocated during library
// * termination or earlier.
// *
// * The block address will never be `NULL` and the size will always be greater than zero.
// * Reallocations of a block to size zero are converted into deallocations. Reallocations
// * of `NULL` to a non-zero size are converted into regular allocations.
// *
// * @param[in] block The address of the memory block to reallocate.
// * @param[in] size The new minimum size, in bytes, of the memory block.
// * @param[in] user The user-defined pointer from the allocator.
// * @return The address of the newly allocated or resized memory block, or
// * `NULL` if an error occurred.
// *
// * @pointer_lifetime The returned memory block must be valid at least until it
// * is deallocated.
// *
// * @reentrancy This function should not call any GLFW function.
// *
// * @thread_safety This function may be called from any thread that calls GLFW functions.
// *
// * @sa @ref init_allocator
// * @sa @ref GLFWallocator
// *
// * @since Added in version 3.4.
// *
// * @ingroup init
// */
// typedef void* (* GLFWreallocatefun)(void* block, size_t size, void* user);
// /*! @brief The function pointer type for memory deallocation callbacks.
// *
// * This is the function pointer type for memory deallocation callbacks.
// * A memory deallocation callback function has the following signature:
// * @code
// * void function_name(void* block, void* user)
// * @endcode
// *
// * This function may deallocate the specified memory block. This memory block
// * will have been allocated with the same allocator.
// *
// * This function may be called during @ref glfwInit but before the library is
// * flagged as initialized, as well as during @ref glfwTerminate after the
// * library is no longer flagged as initialized.
// *
// * The block address will never be `NULL`. Deallocations of `NULL` are filtered out
// * before reaching the custom allocator.
// *
// * @param[in] block The address of the memory block to deallocate.
// * @param[in] user The user-defined pointer from the allocator.
// *
// * @pointer_lifetime The specified memory block will not be accessed by GLFW
// * after this function is called.
// *
// * @reentrancy This function should not call any GLFW function.
// *
// * @thread_safety This function may be called from any thread that calls GLFW functions.
// *
// * @sa @ref init_allocator
// * @sa @ref GLFWallocator
// *
// * @since Added in version 3.4.
// *
// * @ingroup init
// */
// typedef void (* GLFWdeallocatefun)(void* block, void* user);
|
0 | repos/mach-glfw | repos/mach-glfw/src/Monitor.zig | //! Monitor type and related functions
const std = @import("std");
const mem = std.mem;
const testing = std.testing;
const c = @import("c.zig").c;
const GammaRamp = @import("GammaRamp.zig");
const VideoMode = @import("VideoMode.zig");
const internal_debug = @import("internal_debug.zig");
const Monitor = @This();
handle: *c.GLFWmonitor,
/// A monitor position, in screen coordinates, of the upper left corner of the monitor on the
/// virtual screen.
const Pos = struct {
/// The x coordinate.
x: u32,
/// The y coordinate.
y: u32,
};
/// Returns the position of the monitor's viewport on the virtual screen.
///
/// Possible errors include glfw.ErrorCode.PlatformError.
///
/// @thread_safety This function must only be called from the main thread.
///
/// see also: monitor_properties
pub inline fn getPos(self: Monitor) Pos {
internal_debug.assertInitialized();
var xpos: c_int = 0;
var ypos: c_int = 0;
c.glfwGetMonitorPos(self.handle, &xpos, &ypos);
return Pos{ .x = @as(u32, @intCast(xpos)), .y = @as(u32, @intCast(ypos)) };
}
/// The monitor workarea, in screen coordinates.
///
/// This is the position of the upper-left corner of the work area of the monitor, along with the
/// work area size. The work area is defined as the area of the monitor not occluded by the
/// window system task bar where present. If no task bar exists then the work area is the
/// monitor resolution in screen coordinates.
const Workarea = struct {
x: u32,
y: u32,
width: u32,
height: u32,
};
/// Retrieves the work area of the monitor.
///
/// Possible errors include glfw.ErrorCode.PlatformError.
/// A zero value is returned in the event of an error.
///
/// @thread_safety This function must only be called from the main thread.
///
/// see also: monitor_workarea
pub inline fn getWorkarea(self: Monitor) Workarea {
internal_debug.assertInitialized();
var xpos: c_int = 0;
var ypos: c_int = 0;
var width: c_int = 0;
var height: c_int = 0;
c.glfwGetMonitorWorkarea(self.handle, &xpos, &ypos, &width, &height);
return Workarea{ .x = @as(u32, @intCast(xpos)), .y = @as(u32, @intCast(ypos)), .width = @as(u32, @intCast(width)), .height = @as(u32, @intCast(height)) };
}
/// The physical size, in millimetres, of the display area of a monitor.
const PhysicalSize = struct {
width_mm: u32,
height_mm: u32,
};
/// Returns the physical size of the monitor.
///
/// Some platforms do not provide accurate monitor size information, either because the monitor
/// [EDID](https://en.wikipedia.org/wiki/Extended_display_identification_data)
/// data is incorrect or because the driver does not report it accurately.
///
/// win32: On Windows 8 and earlier the physical size is calculated from
/// the current resolution and system DPI instead of querying the monitor EDID data
/// @thread_safety This function must only be called from the main thread.
///
/// see also: monitor_properties
pub inline fn getPhysicalSize(self: Monitor) PhysicalSize {
internal_debug.assertInitialized();
var width_mm: c_int = 0;
var height_mm: c_int = 0;
c.glfwGetMonitorPhysicalSize(self.handle, &width_mm, &height_mm);
return PhysicalSize{ .width_mm = @as(u32, @intCast(width_mm)), .height_mm = @as(u32, @intCast(height_mm)) };
}
/// The content scale for a monitor.
///
/// This is the ratio between the current DPI and the platform's default DPI. This is especially
/// important for text and any UI elements. If the pixel dimensions of your UI scaled by this look
/// appropriate on your machine then it should appear at a reasonable size on other machines
/// regardless of their DPI and scaling settings. This relies on the system DPI and scaling
/// settings being somewhat correct.
///
/// The content scale may depend on both the monitor resolution and pixel density and on users
/// settings. It may be very different from the raw DPI calculated from the physical size and
/// current resolution.
const ContentScale = struct {
x_scale: f32,
y_scale: f32,
};
/// Returns the content scale for the monitor.
///
/// Possible errors include glfw.ErrorCode.PlatformError.
/// A zero value is returned in the event of an error.
///
/// @thread_safety This function must only be called from the main thread.
///
/// see also: monitor_scale, glfw.Window.getContentScale
pub inline fn getContentScale(self: Monitor) ContentScale {
internal_debug.assertInitialized();
var x_scale: f32 = 0;
var y_scale: f32 = 0;
c.glfwGetMonitorContentScale(self.handle, &x_scale, &y_scale);
return ContentScale{ .x_scale = @as(f32, @floatCast(x_scale)), .y_scale = @as(f32, @floatCast(y_scale)) };
}
/// Returns the name of the specified monitor.
///
/// This function returns a human-readable name, encoded as UTF-8, of the specified monitor. The
/// name typically reflects the make and model of the monitor and is not guaranteed to be unique
/// among the connected monitors.
///
/// @pointer_lifetime The returned string is allocated and freed by GLFW. You should not free it
/// yourself. It is valid until the specified monitor is disconnected or the library is terminated.
///
/// @thread_safety This function must only be called from the main thread.
///
/// see also: monitor_properties
pub inline fn getName(self: Monitor) [*:0]const u8 {
internal_debug.assertInitialized();
if (c.glfwGetMonitorName(self.handle)) |name| return @as([*:0]const u8, @ptrCast(name));
// `glfwGetMonitorName` returns `null` only for errors, but the only error is unreachable
// (NotInitialized)
unreachable;
}
/// Sets the user pointer of the specified monitor.
///
/// This function sets the user-defined pointer of the specified monitor. The current value is
/// retained until the monitor is disconnected.
///
/// This function may be called from the monitor callback, even for a monitor that is being
/// disconnected.
///
/// @thread_safety This function may be called from any thread. Access is not synchronized.
///
/// see also: monitor_userptr, glfw.Monitor.getUserPointer
pub inline fn setUserPointer(self: Monitor, comptime T: type, ptr: *T) void {
internal_debug.assertInitialized();
c.glfwSetMonitorUserPointer(self.handle, ptr);
}
/// Returns the user pointer of the specified monitor.
///
/// This function returns the current value of the user-defined pointer of the specified monitor.
///
/// This function may be called from the monitor callback, even for a monitor that is being
/// disconnected.
///
/// @thread_safety This function may be called from any thread. Access is not synchronized.
///
/// see also: monitor_userptr, glfw.Monitor.setUserPointer
pub inline fn getUserPointer(self: Monitor, comptime T: type) ?*T {
internal_debug.assertInitialized();
const ptr = c.glfwGetMonitorUserPointer(self.handle);
if (ptr == null) return null;
return @as(*T, @ptrCast(@alignCast(ptr.?)));
}
/// Returns the available video modes for the specified monitor.
///
/// This function returns an array of all video modes supported by the monitor. The returned slice
/// is sorted in ascending order, first by color bit depth (the sum of all channel depths) and
/// then by resolution area (the product of width and height), then resolution width and finally
/// by refresh rate.
///
/// Possible errors include glfw.ErrorCode.PlatformError, glfw.ErrorCode.FeatureUnavailable.
/// Returns null in the event of an error.
///
/// The returned slice memory is owned by the caller.
///
/// @thread_safety This function must only be called from the main thread.
///
/// see also: monitor_modes, glfw.Monitor.getVideoMode
///
/// wayland: Gamma handling is privileged protocol, this function will thus never be implemented and
/// emits glfw.ErrorCode.FeatureUnavailable
///
/// TODO(glfw): rewrite this to not require any allocation.
pub inline fn getVideoModes(self: Monitor, allocator: mem.Allocator) mem.Allocator.Error!?[]VideoMode {
internal_debug.assertInitialized();
var count: c_int = 0;
if (c.glfwGetVideoModes(self.handle, &count)) |modes| {
const slice = try allocator.alloc(VideoMode, @as(u32, @intCast(count)));
var i: u32 = 0;
while (i < count) : (i += 1) {
slice[i] = VideoMode{ .handle = @as([*c]const c.GLFWvidmode, @ptrCast(modes))[i] };
}
return slice;
}
return null;
}
/// Returns the current mode of the specified monitor.
///
/// This function returns the current video mode of the specified monitor. If you have created a
/// full screen window for that monitor, the return value will depend on whether that window is
/// iconified.
///
/// Possible errors include glfw.ErrorCode.PlatformError, glfw.ErrorCode.FeatureUnavailable.
/// Additionally returns null in the event of an error.
///
/// @thread_safety This function must only be called from the main thread.
///
/// wayland: Gamma handling is a privileged protocol, this function will thus never be implemented
/// and will thus never be implemented and emits glfw.ErrorCode.FeatureUnavailable
///
/// see also: monitor_modes, glfw.Monitor.getVideoModes
pub inline fn getVideoMode(self: Monitor) ?VideoMode {
internal_debug.assertInitialized();
if (c.glfwGetVideoMode(self.handle)) |mode| return VideoMode{ .handle = mode.* };
return null;
}
/// Generates a gamma ramp and sets it for the specified monitor.
///
/// This function generates an appropriately sized gamma ramp from the specified exponent and then
/// calls glfw.Monitor.setGammaRamp with it. The value must be a finite number greater than zero.
///
/// The software controlled gamma ramp is applied _in addition_ to the hardware gamma correction,
/// which today is usually an approximation of sRGB gamma. This means that setting a perfectly
/// linear ramp, or gamma 1.0, will produce the default (usually sRGB-like) behavior.
///
/// For gamma correct rendering with OpenGL or OpenGL ES, see the glfw.srgb_capable hint.
///
/// Possible errors include glfw.ErrorCode.PlatformError, glfw.ErrorCode.FeatureUnavailable.
///
/// wayland: Gamma handling is privileged protocol, this function will thus never be implemented and
/// emits glfw.ErrorCode.FeatureUnavailable
///
/// @thread_safety This function must only be called from the main thread.
///
/// see also: monitor_gamma
pub inline fn setGamma(self: Monitor, gamma: f32) void {
internal_debug.assertInitialized();
std.debug.assert(!std.math.isNan(gamma));
std.debug.assert(gamma >= 0);
std.debug.assert(gamma <= std.math.f32_max);
c.glfwSetGamma(self.handle, gamma);
}
/// Returns the current gamma ramp for the specified monitor.
///
/// This function returns the current gamma ramp of the specified monitor.
///
/// Possible errors include glfw.ErrorCode.PlatformError.
/// Additionally returns null in the event of an error.
///
/// wayland: Gamma handling is a privileged protocol, this function will thus never be implemented
/// and returns glfw.ErrorCode.FeatureUnavailable.
///
/// The returned gamma ramp is `.owned = true` by GLFW, and is valid until the monitor is
/// disconnected, this function is called again, or `glfw.terminate()` is called.
///
/// @thread_safety This function must only be called from the main thread.
///
/// see also: monitor_gamma
pub inline fn getGammaRamp(self: Monitor) ?GammaRamp {
internal_debug.assertInitialized();
if (c.glfwGetGammaRamp(self.handle)) |ramp| return GammaRamp.fromC(ramp.*);
return null;
}
/// Sets the current gamma ramp for the specified monitor.
///
/// This function sets the current gamma ramp for the specified monitor. The original gamma ramp
/// for that monitor is saved by GLFW the first time this function is called and is restored by
/// `glfw.terminate()`.
///
/// The software controlled gamma ramp is applied _in addition_ to the hardware gamma correction,
/// which today is usually an approximation of sRGB gamma. This means that setting a perfectly
/// linear ramp, or gamma 1.0, will produce the default (usually sRGB-like) behavior.
///
/// For gamma correct rendering with OpenGL or OpenGL ES, see the glfw.srgb_capable hint.
///
/// Possible errors include glfw.ErrorCode.PlatformError, glfw.ErrorCode.FeatureUnavailable.
///
/// The size of the specified gamma ramp should match the size of the current ramp for that
/// monitor. On win32, the gamma ramp size must be 256.
///
/// wayland: Gamma handling is a privileged protocol, this function will thus never be implemented
/// and returns glfw.ErrorCode.FeatureUnavailable.
///
/// @pointer_lifetime The specified gamma ramp is copied before this function returns.
///
/// @thread_safety This function must only be called from the main thread.
///
/// see also: monitor_gamma
pub inline fn setGammaRamp(self: Monitor, ramp: GammaRamp) void {
internal_debug.assertInitialized();
c.glfwSetGammaRamp(self.handle, &ramp.toC());
}
/// Returns the currently connected monitors.
///
/// This function returns a slice of all currently connected monitors. The primary monitor is
/// always first. If no monitors were found, this function returns an empty slice.
///
/// The returned slice memory is owned by the caller. The underlying handles are owned by GLFW, and
/// are valid until the monitor configuration changes or `glfw.terminate` is called.
///
/// @thread_safety This function must only be called from the main thread.
///
/// see also: monitor_monitors, monitor_event, glfw.monitor.getPrimary
pub inline fn getAll(allocator: mem.Allocator) mem.Allocator.Error![]Monitor {
internal_debug.assertInitialized();
var count: c_int = 0;
if (c.glfwGetMonitors(&count)) |monitors| {
const slice = try allocator.alloc(Monitor, @as(u32, @intCast(count)));
var i: u32 = 0;
while (i < count) : (i += 1) {
slice[i] = Monitor{ .handle = @as([*c]const ?*c.GLFWmonitor, @ptrCast(monitors))[i].? };
}
return slice;
}
// `glfwGetMonitors` returning null can be either an error or no monitors, but the only error is
// unreachable (NotInitialized)
return &[_]Monitor{};
}
/// Returns the primary monitor.
///
/// This function returns the primary monitor. This is usually the monitor where elements like
/// the task bar or global menu bar are located.
///
/// @thread_safety This function must only be called from the main thread.
///
/// see also: monitor_monitors, glfw.monitors.getAll
pub inline fn getPrimary() ?Monitor {
internal_debug.assertInitialized();
if (c.glfwGetPrimaryMonitor()) |handle| return Monitor{ .handle = handle };
return null;
}
/// Describes an event relating to a monitor.
pub const Event = enum(c_int) {
/// The device was connected.
connected = c.GLFW_CONNECTED,
/// The device was disconnected.
disconnected = c.GLFW_DISCONNECTED,
};
/// Sets the monitor configuration callback.
///
/// This function sets the monitor configuration callback, or removes the currently set callback.
/// This is called when a monitor is connected to or disconnected from the system. Example:
///
/// ```
/// fn monitorCallback(monitor: glfw.Monitor, event: glfw.Monitor.Event, data: *MyData) void {
/// // data is the pointer you passed into setCallback.
/// // event is one of .connected or .disconnected
/// }
/// ...
/// glfw.Monitor.setCallback(MyData, &myData, monitorCallback)
/// ```
///
/// `event` may be one of .connected or .disconnected. More events may be added in the future.
///
/// @thread_safety This function must only be called from the main thread.
///
/// see also: monitor_event
pub inline fn setCallback(comptime callback: ?fn (monitor: Monitor, event: Event) void) void {
internal_debug.assertInitialized();
if (callback) |user_callback| {
const CWrapper = struct {
pub fn monitorCallbackWrapper(monitor: ?*c.GLFWmonitor, event: c_int) callconv(.C) void {
@call(.always_inline, user_callback, .{
Monitor{ .handle = monitor.? },
@as(Event, @enumFromInt(event)),
});
}
};
if (c.glfwSetMonitorCallback(CWrapper.monitorCallbackWrapper) != null) return;
} else {
if (c.glfwSetMonitorCallback(null) != null) return;
}
}
test "getAll" {
const glfw = @import("main.zig");
defer glfw.clearError(); // clear any error we generate
if (!glfw.init(.{})) {
std.log.err("failed to initialize GLFW: {?s}", .{glfw.getErrorString()});
std.process.exit(1);
}
defer glfw.terminate();
const allocator = testing.allocator;
const monitors = try getAll(allocator);
defer allocator.free(monitors);
}
test "getPrimary" {
const glfw = @import("main.zig");
defer glfw.clearError(); // clear any error we generate
if (!glfw.init(.{})) {
std.log.err("failed to initialize GLFW: {?s}", .{glfw.getErrorString()});
std.process.exit(1);
}
defer glfw.terminate();
_ = getPrimary();
}
test "getPos" {
const glfw = @import("main.zig");
defer glfw.clearError(); // clear any error we generate
if (!glfw.init(.{})) {
std.log.err("failed to initialize GLFW: {?s}", .{glfw.getErrorString()});
std.process.exit(1);
}
defer glfw.terminate();
const monitor = getPrimary();
if (monitor) |m| {
_ = m.getPos();
}
}
test "getWorkarea" {
const glfw = @import("main.zig");
defer glfw.clearError(); // clear any error we generate
if (!glfw.init(.{})) {
std.log.err("failed to initialize GLFW: {?s}", .{glfw.getErrorString()});
std.process.exit(1);
}
defer glfw.terminate();
const monitor = getPrimary();
if (monitor) |m| {
_ = m.getWorkarea();
}
}
test "getPhysicalSize" {
const glfw = @import("main.zig");
defer glfw.clearError(); // clear any error we generate
if (!glfw.init(.{})) {
std.log.err("failed to initialize GLFW: {?s}", .{glfw.getErrorString()});
std.process.exit(1);
}
defer glfw.terminate();
const monitor = getPrimary();
if (monitor) |m| {
_ = m.getPhysicalSize();
}
}
test "getContentScale" {
const glfw = @import("main.zig");
defer glfw.clearError(); // clear any error we generate
if (!glfw.init(.{})) {
std.log.err("failed to initialize GLFW: {?s}", .{glfw.getErrorString()});
std.process.exit(1);
}
defer glfw.terminate();
const monitor = getPrimary();
if (monitor) |m| {
_ = m.getContentScale();
}
}
test "getName" {
const glfw = @import("main.zig");
defer glfw.clearError(); // clear any error we generate
if (!glfw.init(.{})) {
std.log.err("failed to initialize GLFW: {?s}", .{glfw.getErrorString()});
std.process.exit(1);
}
defer glfw.terminate();
const monitor = getPrimary();
if (monitor) |m| {
_ = m.getName();
}
}
test "userPointer" {
const glfw = @import("main.zig");
defer glfw.clearError(); // clear any error we generate
if (!glfw.init(.{})) {
std.log.err("failed to initialize GLFW: {?s}", .{glfw.getErrorString()});
std.process.exit(1);
}
defer glfw.terminate();
const monitor = getPrimary();
if (monitor) |m| {
var p = m.getUserPointer(u32);
try testing.expect(p == null);
var x: u32 = 5;
m.setUserPointer(u32, &x);
p = m.getUserPointer(u32);
try testing.expectEqual(p.?.*, 5);
}
}
test "setCallback" {
const glfw = @import("main.zig");
defer glfw.clearError(); // clear any error we generate
if (!glfw.init(.{})) {
std.log.err("failed to initialize GLFW: {?s}", .{glfw.getErrorString()});
std.process.exit(1);
}
defer glfw.terminate();
setCallback(struct {
fn callback(monitor: Monitor, event: Event) void {
_ = monitor;
_ = event;
}
}.callback);
}
test "getVideoModes" {
const glfw = @import("main.zig");
defer glfw.clearError(); // clear any error we generate
if (!glfw.init(.{})) {
std.log.err("failed to initialize GLFW: {?s}", .{glfw.getErrorString()});
std.process.exit(1);
}
defer glfw.terminate();
const monitor = getPrimary();
if (monitor) |m| {
const allocator = testing.allocator;
const modes_maybe = try m.getVideoModes(allocator);
if (modes_maybe) |modes| {
defer allocator.free(modes);
}
}
}
test "getVideoMode" {
const glfw = @import("main.zig");
defer glfw.clearError(); // clear any error we generate
if (!glfw.init(.{})) {
std.log.err("failed to initialize GLFW: {?s}", .{glfw.getErrorString()});
std.process.exit(1);
}
defer glfw.terminate();
const monitor = getPrimary();
if (monitor) |m| {
_ = m.getVideoMode();
}
}
test "set_getGammaRamp" {
const allocator = testing.allocator;
const glfw = @import("main.zig");
defer glfw.clearError(); // clear any error we generate
if (!glfw.init(.{})) {
std.log.err("failed to initialize GLFW: {?s}", .{glfw.getErrorString()});
std.process.exit(1);
}
defer glfw.terminate();
const monitor = getPrimary();
if (monitor) |m| {
if (m.getGammaRamp()) |ramp| {
// Set it to the exact same value; if we do otherwise an our tests fail it wouldn't call
// terminate and our made-up gamma ramp would get stuck.
m.setGammaRamp(ramp);
// technically not needed here / noop because GLFW owns this gamma ramp.
defer ramp.deinit(allocator);
}
}
}
|
0 | repos/mach-glfw | repos/mach-glfw/src/time.zig | const std = @import("std");
const c = @import("c.zig").c;
const internal_debug = @import("internal_debug.zig");
/// Returns the GLFW time.
///
/// This function returns the current GLFW time, in seconds. Unless the time
/// has been set using @ref glfwSetTime it measures time elapsed since GLFW was
/// initialized.
///
/// This function and @ref glfwSetTime are helper functions on top of glfw.getTimerFrequency
/// and glfw.getTimerValue.
///
/// The resolution of the timer is system dependent, but is usually on the order
/// of a few micro- or nanoseconds. It uses the highest-resolution monotonic
/// time source on each supported operating system.
///
/// @return The current time, in seconds, or zero if an
/// error occurred.
///
/// @thread_safety This function may be called from any thread. Reading and
/// writing of the internal base time is not atomic, so it needs to be
/// externally synchronized with calls to @ref glfwSetTime.
///
/// see also: time
pub inline fn getTime() f64 {
internal_debug.assertInitialized();
const time = c.glfwGetTime();
if (time != 0) return time;
// `glfwGetTime` returns `0` only for errors
// but the only potential error is unreachable (NotInitialized)
unreachable;
}
/// Sets the GLFW time.
///
/// This function sets the current GLFW time, in seconds. The value must be a positive finite
/// number less than or equal to 18446744073.0, which is approximately 584.5 years.
///
/// This function and @ref glfwGetTime are helper functions on top of glfw.getTimerFrequency and
/// glfw.getTimerValue.
///
/// @param[in] time The new value, in seconds.
///
/// Possible errors include glfw.ErrorCode.InvalidValue.
///
/// The upper limit of GLFW time is calculated as `floor((2^64 - 1) / 10^9)` and is due to
/// implementations storing nanoseconds in 64 bits. The limit may be increased in the future.
///
/// @thread_safety This function may be called from any thread. Reading and writing of the internal
/// base time is not atomic, so it needs to be externally synchronized with calls to glfw.getTime.
///
/// see also: time
pub inline fn setTime(time: f64) void {
internal_debug.assertInitialized();
std.debug.assert(!std.math.isNan(time));
std.debug.assert(time >= 0);
// assert time is lteq to largest number of seconds representable by u64 with nanosecond precision
std.debug.assert(time <= max_time: {
const @"2^64" = std.math.maxInt(u64);
break :max_time @divTrunc(@"2^64", std.time.ns_per_s);
});
c.glfwSetTime(time);
}
/// Returns the current value of the raw timer.
///
/// This function returns the current value of the raw timer, measured in `1/frequency` seconds. To
/// get the frequency, call glfw.getTimerFrequency.
///
/// @return The value of the timer, or zero if an error occurred.
///
/// @thread_safety This function may be called from any thread.
///
/// see also: time, glfw.getTimerFrequency
pub inline fn getTimerValue() u64 {
internal_debug.assertInitialized();
const value = c.glfwGetTimerValue();
if (value != 0) return value;
// `glfwGetTimerValue` returns `0` only for errors
// but the only potential error is unreachable (NotInitialized)
unreachable;
}
/// Returns the frequency, in Hz, of the raw timer.
///
/// This function returns the frequency, in Hz, of the raw timer.
///
/// @return The frequency of the timer, in Hz, or zero if an error occurred.
///
/// @thread_safety This function may be called from any thread.
///
/// see also: time, glfw.getTimerValue
pub inline fn getTimerFrequency() u64 {
internal_debug.assertInitialized();
const frequency = c.glfwGetTimerFrequency();
if (frequency != 0) return frequency;
// `glfwGetTimerFrequency` returns `0` only for errors
// but the only potential error is unreachable (NotInitialized)
unreachable;
}
test "getTime" {
const glfw = @import("main.zig");
defer glfw.clearError(); // clear any error we generate
if (!glfw.init(.{})) {
std.log.err("failed to initialize GLFW: {?s}", .{glfw.getErrorString()});
std.process.exit(1);
}
defer glfw.terminate();
_ = getTime();
}
test "setTime" {
const glfw = @import("main.zig");
defer glfw.clearError(); // clear any error we generate
if (!glfw.init(.{})) {
std.log.err("failed to initialize GLFW: {?s}", .{glfw.getErrorString()});
std.process.exit(1);
}
defer glfw.terminate();
_ = glfw.setTime(1234);
}
test "getTimerValue" {
const glfw = @import("main.zig");
defer glfw.clearError(); // clear any error we generate
if (!glfw.init(.{})) {
std.log.err("failed to initialize GLFW: {?s}", .{glfw.getErrorString()});
std.process.exit(1);
}
defer glfw.terminate();
_ = glfw.getTimerValue();
}
test "getTimerFrequency" {
const glfw = @import("main.zig");
defer glfw.clearError(); // clear any error we generate
if (!glfw.init(.{})) {
std.log.err("failed to initialize GLFW: {?s}", .{glfw.getErrorString()});
std.process.exit(1);
}
defer glfw.terminate();
_ = glfw.getTimerFrequency();
}
|
0 | repos/mach-glfw | repos/mach-glfw/src/hat.zig | const c = @import("c.zig").c;
// must be in sync with GLFW C constants in hat state group, search for "@defgroup hat_state Joystick hat states"
/// A bitmask of all Joystick hat states
///
/// See glfw.Joystick.getHats for how these are used.
pub const Hat = packed struct(u8) {
up: bool = false,
right: bool = false,
down: bool = false,
left: bool = false,
_padding: u4 = 0,
pub inline fn centered(self: Hat) bool {
return self.up == false and self.right == false and self.down == false and self.left == false;
}
inline fn verifyIntType(comptime IntType: type) void {
comptime {
switch (@typeInfo(IntType)) {
.Int => {},
else => @compileError("Int was not of int type"),
}
}
}
pub inline fn toInt(self: Hat, comptime IntType: type) IntType {
verifyIntType(IntType);
return @as(IntType, @intCast(@as(u8, @bitCast(self))));
}
pub inline fn fromInt(flags: anytype) Hat {
verifyIntType(@TypeOf(flags));
return @as(Hat, @bitCast(@as(u8, @intCast(flags))));
}
};
/// Holds all GLFW hat values in their raw form.
pub const RawHat = struct {
pub const centered = c.GLFW_HAT_CENTERED;
pub const up = c.GLFW_HAT_UP;
pub const right = c.GLFW_HAT_RIGHT;
pub const down = c.GLFW_HAT_DOWN;
pub const left = c.GLFW_HAT_LEFT;
pub const right_up = right | up;
pub const right_down = right | down;
pub const left_up = left | up;
pub const left_down = left | down;
};
test "from int, single" {
const std = @import("std");
try std.testing.expectEqual(Hat{
.up = true,
.right = false,
.down = false,
.left = false,
._padding = 0,
}, Hat.fromInt(RawHat.up));
}
test "from int, multi" {
const std = @import("std");
try std.testing.expectEqual(Hat{
.up = true,
.right = false,
.down = true,
.left = true,
._padding = 0,
}, Hat.fromInt(RawHat.up | RawHat.down | RawHat.left));
}
test "to int, single" {
const std = @import("std");
var v = Hat{
.up = true,
.right = false,
.down = false,
.left = false,
._padding = 0,
};
try std.testing.expectEqual(v.toInt(c_int), RawHat.up);
}
test "to int, multi" {
const std = @import("std");
var v = Hat{
.up = true,
.right = false,
.down = true,
.left = true,
._padding = 0,
};
try std.testing.expectEqual(v.toInt(c_int), RawHat.up | RawHat.down | RawHat.left);
}
|
0 | repos/mach-glfw | repos/mach-glfw/src/Cursor.zig | //! Represents a cursor and provides facilities for setting cursor images.
const std = @import("std");
const testing = std.testing;
const c = @import("c.zig").c;
const Image = @import("Image.zig");
const internal_debug = @import("internal_debug.zig");
const Cursor = @This();
ptr: *c.GLFWcursor,
/// Standard system cursor shapes.
///
/// These are the standard cursor shapes that can be requested from the platform (window system).
pub const Shape = enum(i32) {
/// The regular arrow cursor shape.
arrow = c.GLFW_ARROW_CURSOR,
/// The text input I-beam cursor shape.
ibeam = c.GLFW_IBEAM_CURSOR,
/// The crosshair cursor shape.
crosshair = c.GLFW_CROSSHAIR_CURSOR,
/// The pointing hand cursor shape.
///
/// NOTE: This supersedes the old `hand` enum.
pointing_hand = c.GLFW_POINTING_HAND_CURSOR,
/// The horizontal resize/move arrow shape.
///
/// The horizontal resize/move arrow shape. This is usually a horizontal double-headed arrow.
//
// NOTE: This supersedes the old `hresize` enum.
resize_ew = c.GLFW_RESIZE_EW_CURSOR,
/// The vertical resize/move arrow shape.
///
/// The vertical resize/move shape. This is usually a vertical double-headed arrow.
///
/// NOTE: This supersedes the old `vresize` enum.
resize_ns = c.GLFW_RESIZE_NS_CURSOR,
/// The top-left to bottom-right diagonal resize/move arrow shape.
///
/// The top-left to bottom-right diagonal resize/move shape. This is usually a diagonal
/// double-headed arrow.
///
/// macos: This shape is provided by a private system API and may fail CursorUnavailable in the
/// future.
///
/// x11: This shape is provided by a newer standard not supported by all cursor themes.
///
/// wayland: This shape is provided by a newer standard not supported by all cursor themes.
resize_nwse = c.GLFW_RESIZE_NWSE_CURSOR,
/// The top-right to bottom-left diagonal resize/move arrow shape.
///
/// The top-right to bottom-left diagonal resize/move shape. This is usually a diagonal
/// double-headed arrow.
///
/// macos: This shape is provided by a private system API and may fail with CursorUnavailable
/// in the future.
///
/// x11: This shape is provided by a newer standard not supported by all cursor themes.
///
/// wayland: This shape is provided by a newer standard not supported by all cursor themes.
resize_nesw = c.GLFW_RESIZE_NESW_CURSOR,
/// The omni-directional resize/move cursor shape.
///
/// The omni-directional resize cursor/move shape. This is usually either a combined horizontal
/// and vertical double-headed arrow or a grabbing hand.
resize_all = c.GLFW_RESIZE_ALL_CURSOR,
/// The operation-not-allowed shape.
///
/// The operation-not-allowed shape. This is usually a circle with a diagonal line through it.
///
/// x11: This shape is provided by a newer standard not supported by all cursor themes.
///
/// wayland: This shape is provided by a newer standard not supported by all cursor themes.
not_allowed = c.GLFW_NOT_ALLOWED_CURSOR,
};
/// Creates a custom cursor.
///
/// Creates a new custom cursor image that can be set for a window with glfw.Cursor.set. The cursor
/// can be destroyed with glfwCursor.destroy. Any remaining cursors are destroyed by glfw.terminate.
///
/// The pixels are 32-bit, little-endian, non-premultiplied RGBA, i.e. eight bits per channel with
/// the red channel first. They are arranged canonically as packed sequential rows, starting from
/// the top-left corner.
///
/// The cursor hotspot is specified in pixels, relative to the upper-left corner of the cursor
/// image. Like all other coordinate systems in GLFW, the X-axis points to the right and the Y-axis
/// points down.
///
/// @param[in] image The desired cursor image.
/// @param[in] xhot The desired x-coordinate, in pixels, of the cursor hotspot.
/// @param[in] yhot The desired y-coordinate, in pixels, of the cursor hotspot.
/// @return The handle of the created cursor.
///
/// Possible errors include glfw.ErrorCode.PlatformError and glfw.ErrorCode.InvalidValue
/// null is returned in the event of an error.
///
/// @pointer_lifetime The specified image data is copied before this function returns.
///
/// @thread_safety This function must only be called from the main thread.
///
/// see also: cursor_object, glfw.Cursor.destroy, glfw.Cursor.createStandard
pub inline fn create(image: Image, xhot: i32, yhot: i32) ?Cursor {
internal_debug.assertInitialized();
const img = image.toC();
if (c.glfwCreateCursor(&img, @as(c_int, @intCast(xhot)), @as(c_int, @intCast(yhot)))) |cursor| return Cursor{ .ptr = cursor };
return null;
}
/// Creates a cursor with a standard shape.
///
/// Returns a cursor with a standard shape, that can be set for a window with glfw.Window.setCursor.
/// The images for these cursors come from the system cursor theme and their exact appearance will
/// vary between platforms.
///
/// Most of these shapes are guaranteed to exist on every supported platform but a few may not be
/// present. See the table below for details.
///
/// | Cursor shape | Windows | macOS | X11 | Wayland |
/// |------------------|---------|-----------------|-------------------|-------------------|
/// | `.arrow` | Yes | Yes | Yes | Yes |
/// | `.ibeam` | Yes | Yes | Yes | Yes |
/// | `.crosshair` | Yes | Yes | Yes | Yes |
/// | `.pointing_hand` | Yes | Yes | Yes | Yes |
/// | `.resize_ew` | Yes | Yes | Yes | Yes |
/// | `.resize_ns` | Yes | Yes | Yes | Yes |
/// | `.resize_nwse` | Yes | Yes<sup>1</sup> | Maybe<sup>2</sup> | Maybe<sup>2</sup> |
/// | `.resize_nesw` | Yes | Yes<sup>1</sup> | Maybe<sup>2</sup> | Maybe<sup>2</sup> |
/// | `.resize_all` | Yes | Yes | Yes | Yes |
/// | `.not_allowed` | Yes | Yes | Maybe<sup>2</sup> | Maybe<sup>2</sup> |
///
/// 1. This uses a private system API and may fail in the future.
/// 2. This uses a newer standard that not all cursor themes support.
///
/// If the requested shape is not available, this function emits a CursorUnavailable error
/// Possible errors include glfw.ErrorCode.PlatformError and glfw.ErrorCode.CursorUnavailable.
/// null is returned in the event of an error.
///
/// thread_safety: This function must only be called from the main thread.
///
/// see also: cursor_object, glfwCreateCursor
pub inline fn createStandard(shape: Shape) ?Cursor {
internal_debug.assertInitialized();
if (c.glfwCreateStandardCursor(@as(c_int, @intCast(@intFromEnum(shape))))) |cursor| return Cursor{ .ptr = cursor };
return null;
}
/// Destroys a cursor.
///
/// This function destroys a cursor previously created with glfw.Cursor.create. Any remaining
/// cursors will be destroyed by glfw.terminate.
///
/// If the specified cursor is current for any window, that window will be reverted to the default
/// cursor. This does not affect the cursor mode.
///
/// Possible errors include glfw.ErrorCode.PlatformError.
///
/// @reentrancy This function must not be called from a callback.
///
/// @thread_safety This function must only be called from the main thread.
///
/// see also: cursor_object, glfw.createCursor
pub inline fn destroy(self: Cursor) void {
internal_debug.assertInitialized();
c.glfwDestroyCursor(self.ptr);
}
test "create" {
const allocator = testing.allocator;
const glfw = @import("main.zig");
defer glfw.clearError(); // clear any error we generate
if (!glfw.init(.{})) {
std.log.err("failed to initialize GLFW: {?s}", .{glfw.getErrorString()});
std.process.exit(1);
}
defer glfw.terminate();
const image = try Image.init(allocator, 32, 32, 32 * 32 * 4);
defer image.deinit(allocator);
const cursor = glfw.Cursor.create(image, 0, 0);
if (cursor) |cur| cur.destroy();
}
test "createStandard" {
const glfw = @import("main.zig");
defer glfw.clearError(); // clear any error we generate
if (!glfw.init(.{})) {
std.log.err("failed to initialize GLFW: {?s}", .{glfw.getErrorString()});
std.process.exit(1);
}
defer glfw.terminate();
const cursor = glfw.Cursor.createStandard(.ibeam);
if (cursor) |cur| cur.destroy();
}
|
0 | repos/mach-glfw | repos/mach-glfw/src/opengl.zig | const std = @import("std");
const builtin = @import("builtin");
const c = @import("c.zig").c;
const Window = @import("Window.zig");
const internal_debug = @import("internal_debug.zig");
/// Makes the context of the specified window current for the calling thread.
///
/// This function makes the OpenGL or OpenGL ES context of the specified window current on the
/// calling thread. A context must only be made current on a single thread at a time and each
/// thread can have only a single current context at a time.
///
/// When moving a context between threads, you must make it non-current on the old thread before
/// making it current on the new one.
///
/// By default, making a context non-current implicitly forces a pipeline flush. On machines that
/// support `GL_KHR_context_flush_control`, you can control whether a context performs this flush
/// by setting the glfw.context_release_behavior hint.
///
/// The specified window must have an OpenGL or OpenGL ES context. Specifying a window without a
/// context will generate glfw.ErrorCode.NoWindowContext.
///
/// @param[in] window The window whose context to make current, or null to
/// detach the current context.
///
/// Possible errors include glfw.ErrorCode.NoWindowContext and glfw.ErrorCode.PlatformError.
///
/// @thread_safety This function may be called from any thread.
///
/// see also: context_current, glfwGetCurrentContext
pub inline fn makeContextCurrent(window: ?Window) void {
internal_debug.assertInitialized();
if (window) |w| c.glfwMakeContextCurrent(w.handle) else c.glfwMakeContextCurrent(null);
}
/// Returns the window whose context is current on the calling thread.
///
/// This function returns the window whose OpenGL or OpenGL ES context is current on the calling
/// thread.
///
/// Returns he window whose context is current, or null if no window's context is current.
///
/// @thread_safety This function may be called from any thread.
///
/// see also: context_current, glfwMakeContextCurrent
pub inline fn getCurrentContext() ?Window {
internal_debug.assertInitialized();
if (c.glfwGetCurrentContext()) |handle| return Window.from(handle);
return null;
}
/// Sets the swap interval for the current context.
///
/// This function sets the swap interval for the current OpenGL or OpenGL ES context, i.e. the
/// number of screen updates to wait from the time glfw.SwapBuffers was called before swapping the
/// buffers and returning. This is sometimes called _vertical synchronization_, _vertical retrace
/// synchronization_ or just _vsync_.
///
/// A context that supports either of the `WGL_EXT_swap_control_tear` and `GLX_EXT_swap_control_tear`
/// extensions also accepts _negative_ swap intervals, which allows the driver to swap immediately
/// even if a frame arrives a little bit late. You can check for these extensions with glfw.extensionSupported.
///
/// A context must be current on the calling thread. Calling this function without a current context
/// will cause glfw.ErrorCode.NoCurrentContext.
///
/// This function does not apply to Vulkan. If you are rendering with Vulkan, see the present mode
/// of your swapchain instead.
///
/// @param[in] interval The minimum number of screen updates to wait for until the buffers are
/// swapped by glfw.swapBuffers.
///
/// Possible errors include glfw.ErrorCode.NoCurrentContext and glfw.ErrorCode.PlatformError.
///
/// This function is not called during context creation, leaving the swap interval set to whatever
/// is the default for that API. This is done because some swap interval extensions used by
/// GLFW do not allow the swap interval to be reset to zero once it has been set to a non-zero
/// value.
///
/// Some GPU drivers do not honor the requested swap interval, either because of a user setting
/// that overrides the application's request or due to bugs in the driver.
///
/// @thread_safety This function may be called from any thread.
///
/// see also: buffer_swap, glfwSwapBuffers
pub inline fn swapInterval(interval: i32) void {
internal_debug.assertInitialized();
c.glfwSwapInterval(@as(c_int, @intCast(interval)));
}
/// Returns whether the specified extension is available.
///
/// This function returns whether the specified API extension (see context_glext) is supported by
/// the current OpenGL or OpenGL ES context. It searches both for client API extension and context
/// creation API extensions.
///
/// A context must be current on the calling thread. Calling this function without a current
/// context will cause glfw.ErrorCode.NoCurrentContext.
///
/// As this functions retrieves and searches one or more extension strings each call, it is
/// recommended that you cache its results if it is going to be used frequently. The extension
/// strings will not change during the lifetime of a context, so there is no danger in doing this.
///
/// This function does not apply to Vulkan. If you are using Vulkan, see glfw.getRequiredInstanceExtensions,
/// `vkEnumerateInstanceExtensionProperties` and `vkEnumerateDeviceExtensionProperties` instead.
///
/// @param[in] extension The ASCII encoded name of the extension.
/// @return `true` if the extension is available, or `false` otherwise.
///
/// Possible errors include glfw.ErrorCode.NoCurrentContext, glfw.ErrorCode.InvalidValue
/// and glfw.ErrorCode.PlatformError.
///
/// @thread_safety This function may be called from any thread.
///
/// see also: context_glext, glfw.getProcAddress
pub inline fn extensionSupported(extension: [:0]const u8) bool {
internal_debug.assertInitialized();
std.debug.assert(extension.len != 0);
std.debug.assert(extension[0] != 0);
return c.glfwExtensionSupported(extension.ptr) == c.GLFW_TRUE;
}
/// Client API function pointer type.
///
/// Generic function pointer used for returning client API function pointers.
///
/// see also: context_glext, glfwGetProcAddress
pub const GLProc = *const fn () callconv(if (builtin.os.tag == .windows and builtin.cpu.arch == .x86) .Stdcall else .C) void;
/// Returns the address of the specified function for the current context.
///
/// This function returns the address of the specified OpenGL or OpenGL ES core or extension
/// function (see context_glext), if it is supported by the current context.
///
/// A context must be current on the calling thread. Calling this function without a current
/// context will cause glfw.ErrorCode.NoCurrentContext.
///
/// This function does not apply to Vulkan. If you are rendering with Vulkan, see glfw.getInstanceProcAddress,
/// `vkGetInstanceProcAddr` and `vkGetDeviceProcAddr` instead.
///
/// @param[in] procname The ASCII encoded name of the function.
/// @return The address of the function, or null if an error occurred.
///
/// To maintain ABI compatability with the C glfwGetProcAddress, as it is commonly passed into
/// libraries expecting that exact ABI, this function does not return an error. Instead, if
/// glfw.ErrorCode.NotInitialized, glfw.ErrorCode.NoCurrentContext, or glfw.ErrorCode.PlatformError
/// would occur this function will panic. You should ensure a valid OpenGL context exists and the
/// GLFW is initialized before calling this function.
///
/// The address of a given function is not guaranteed to be the same between contexts.
///
/// This function may return a non-null address despite the associated version or extension
/// not being available. Always check the context version or extension string first.
///
/// @pointer_lifetime The returned function pointer is valid until the context is destroyed or the
/// library is terminated.
///
/// @thread_safety This function may be called from any thread.
///
/// see also: context_glext, glfwExtensionSupported
pub fn getProcAddress(proc_name: [*:0]const u8) callconv(.C) ?GLProc {
internal_debug.assertInitialized();
if (c.glfwGetProcAddress(proc_name)) |proc_address| return proc_address;
return null;
}
test "makeContextCurrent" {
const glfw = @import("main.zig");
defer glfw.clearError(); // clear any error we generate
if (!glfw.init(.{})) {
std.log.err("failed to initialize GLFW: {?s}", .{glfw.getErrorString()});
std.process.exit(1);
}
defer glfw.terminate();
const window = Window.create(640, 480, "Hello, Zig!", null, null, .{}) orelse {
std.log.warn("failed to create window: {?s}", .{glfw.getErrorString()});
return error.SkipZigTest; // note: we don't exit(1) here because our CI can't open windows
};
defer window.destroy();
glfw.makeContextCurrent(window);
}
test "getCurrentContext" {
const glfw = @import("main.zig");
defer glfw.clearError(); // clear any error we generate
if (!glfw.init(.{})) {
std.log.err("failed to initialize GLFW: {?s}", .{glfw.getErrorString()});
std.process.exit(1);
}
defer glfw.terminate();
const current_context = glfw.getCurrentContext();
std.debug.assert(current_context == null);
}
test "swapInterval" {
const glfw = @import("main.zig");
defer glfw.clearError(); // clear any error we generate
if (!glfw.init(.{})) {
std.log.err("failed to initialize GLFW: {?s}", .{glfw.getErrorString()});
std.process.exit(1);
}
defer glfw.terminate();
const window = Window.create(640, 480, "Hello, Zig!", null, null, .{}) orelse {
std.log.warn("failed to create window: {?s}", .{glfw.getErrorString()});
return error.SkipZigTest; // note: we don't exit(1) here because our CI can't open windows
};
defer window.destroy();
glfw.makeContextCurrent(window);
glfw.swapInterval(1);
}
test "getProcAddress" {
const glfw = @import("main.zig");
defer glfw.clearError(); // clear any error we generate
if (!glfw.init(.{})) {
std.log.err("failed to initialize GLFW: {?s}", .{glfw.getErrorString()});
std.process.exit(1);
}
defer glfw.terminate();
const window = Window.create(640, 480, "Hello, Zig!", null, null, .{}) orelse {
std.log.warn("failed to create window: {?s}", .{glfw.getErrorString()});
return error.SkipZigTest; // note: we don't exit(1) here because our CI can't open windows
};
defer window.destroy();
glfw.makeContextCurrent(window);
_ = glfw.getProcAddress("foobar");
}
test "extensionSupported" {
const glfw = @import("main.zig");
defer glfw.clearError(); // clear any error we generate
if (!glfw.init(.{})) {
std.log.err("failed to initialize GLFW: {?s}", .{glfw.getErrorString()});
std.process.exit(1);
}
defer glfw.terminate();
const window = Window.create(640, 480, "Hello, Zig!", null, null, .{}) orelse {
std.log.warn("failed to create window: {?s}", .{glfw.getErrorString()});
return error.SkipZigTest; // note: we don't exit(1) here because our CI can't open windows
};
defer window.destroy();
glfw.makeContextCurrent(window);
_ = glfw.extensionSupported("foobar");
}
|
0 | repos/mach-glfw | repos/mach-glfw/src/Joystick.zig | //! Represents a Joystick or gamepad
//!
//! It can be manually crafted via e.g. `glfw.Joystick{.jid = .one}`, but more
//! typically you'll want to discover the joystick using `glfw.Joystick.setCallback`.
const std = @import("std");
const c = @import("c.zig").c;
const Window = @import("Window.zig");
const Action = @import("action.zig").Action;
const GamepadAxis = @import("gamepad_axis.zig").GamepadAxis;
const GamepadButton = @import("gamepad_button.zig").GamepadButton;
const Hat = @import("hat.zig").Hat;
const internal_debug = @import("internal_debug.zig");
const Joystick = @This();
/// The GLFW joystick ID.
jid: Id,
/// Joystick IDs.
///
/// See glfw.Joystick.setCallback for how these are used.
pub const Id = enum(c_int) {
one = c.GLFW_JOYSTICK_1,
two = c.GLFW_JOYSTICK_2,
three = c.GLFW_JOYSTICK_3,
four = c.GLFW_JOYSTICK_4,
five = c.GLFW_JOYSTICK_5,
six = c.GLFW_JOYSTICK_6,
seven = c.GLFW_JOYSTICK_7,
eight = c.GLFW_JOYSTICK_8,
nine = c.GLFW_JOYSTICK_9,
ten = c.GLFW_JOYSTICK_10,
eleven = c.GLFW_JOYSTICK_11,
twelve = c.GLFW_JOYSTICK_12,
thirteen = c.GLFW_JOYSTICK_13,
fourteen = c.GLFW_JOYSTICK_14,
fifteen = c.GLFW_JOYSTICK_15,
sixteen = c.GLFW_JOYSTICK_16,
pub const last = @as(@This(), @enumFromInt(c.GLFW_JOYSTICK_LAST));
};
/// Gamepad input state
///
/// This describes the input state of a gamepad.
///
/// see also: gamepad, glfwGetGamepadState
const GamepadState = extern struct {
/// The states of each gamepad button (see gamepad_buttons), `glfw.Action.press` or `glfw.Action.release`.
///
/// Use the enumeration helper e.g. `.getButton(.dpad_up)` to access these indices.
buttons: [15]u8,
/// The states of each gamepad axis (see gamepad_axes), in the range -1.0 to 1.0 inclusive.
///
/// Use the enumeration helper e.g. `.getAxis(.left_x)` to access these indices.
axes: [6]f32,
/// Returns the state of the specified gamepad button.
pub fn getButton(self: @This(), which: GamepadButton) Action {
return @as(Action, @enumFromInt(self.buttons[@as(u32, @intCast(@intFromEnum(which)))]));
}
/// Returns the status of the specified gamepad axis, in the range -1.0 to 1.0 inclusive.
pub fn getAxis(self: @This(), which: GamepadAxis) f32 {
return self.axes[@as(u32, @intCast(@intFromEnum(which)))];
}
};
/// Returns whether the specified joystick is present.
///
/// This function returns whether the specified joystick is present.
///
/// There is no need to call this function before other functions that accept a joystick ID, as
/// they all check for presence before performing any other work.
///
/// @return `true` if the joystick is present, or `false` otherwise.
///
/// Possible errors include glfw.ErrorCode.InvalidEnum and glfw.ErrorCode.PlatformError.
///
/// @thread_safety This function must only be called from the main thread.
///
/// see also: joystick
pub inline fn present(self: Joystick) bool {
internal_debug.assertInitialized();
const is_present = c.glfwJoystickPresent(@intFromEnum(self.jid));
return is_present == c.GLFW_TRUE;
}
/// Returns the values of all axes of the specified joystick.
///
/// This function returns the values of all axes of the specified joystick. Each element in the
/// array is a value between -1.0 and 1.0.
///
/// If the specified joystick is not present this function will return null but will not generate
/// an error. This can be used instead of first calling glfw.Joystick.present.
///
/// @return An array of axis values, or null if the joystick is not present.
///
/// Possible errors include glfw.ErrorCode.InvalidEnum and glfw.ErrorCode.PlatformError.
/// null is additionally returned in the event of an error.
///
/// @pointer_lifetime The returned array is allocated and freed by GLFW. You should not free it
/// yourself. It is valid until the specified joystick is disconnected or the library is
/// terminated.
///
/// @thread_safety This function must only be called from the main thread.
///
/// see also: joystick_axis
/// Replaces `glfwGetJoystickPos`.
pub inline fn getAxes(self: Joystick) ?[]const f32 {
internal_debug.assertInitialized();
var count: c_int = undefined;
const axes = c.glfwGetJoystickAxes(@intFromEnum(self.jid), &count);
if (axes == null) return null;
return axes[0..@as(u32, @intCast(count))];
}
/// Returns the state of all buttons of the specified joystick.
///
/// This function returns the state of all buttons of the specified joystick. Each element in the
/// array is either `glfw.Action.press` or `glfw.Action.release`.
///
/// For backward compatibility with earlier versions that did not have glfw.Joystick.getHats, the
/// button array also includes all hats, each represented as four buttons. The hats are in the same
/// order as returned by glfw.Joystick.getHats and are in the order _up_, _right_, _down_ and
/// _left_. To disable these extra buttons, set the glfw.joystick_hat_buttons init hint before
/// initialization.
///
/// If the specified joystick is not present this function will return null but will not generate an
/// error. This can be used instead of first calling glfw.Joystick.present.
///
/// @return An array of button states, or null if the joystick is not present.
///
/// Possible errors include glfw.ErrorCode.InvalidEnum and glfw.ErrorCode.PlatformError.
/// null is additionally returned in the event of an error.
///
/// @pointer_lifetime The returned array is allocated and freed by GLFW. You should not free it
/// yourself. It is valid until the specified joystick is disconnected or the library is terminated.
///
/// @thread_safety This function must only be called from the main thread.
///
/// see also: joystick_button
pub inline fn getButtons(self: Joystick) ?[]const u8 {
internal_debug.assertInitialized();
var count: c_int = undefined;
const buttons = c.glfwGetJoystickButtons(@intFromEnum(self.jid), &count);
if (buttons == null) return null;
return buttons[0..@as(u32, @intCast(count))];
}
/// Returns the state of all hats of the specified joystick.
///
/// This function returns the state of all hats of the specified joystick. Each element in the array
/// is one of the following values:
///
/// | Name | Value |
/// |---------------------------|---------------------------------------------|
/// | `glfw.RawHats.centered` | 0 |
/// | `glfw.RawHats.up` | 1 |
/// | `glfw.RawHats.right` | 2 |
/// | `glfw.RawHats.down` | 4 |
/// | `glfw.RawHats.left` | 8 |
/// | `glfw.RawHats.right_up` | `glfw.RawHats.right` \| `glfw.RawHats.up` |
/// | `glfw.RawHats.right_down` | `glfw.RawHats.right` \| `glfw.RawHats.down` |
/// | `glfw.RawHats.left_up` | `glfw.RawHats.left` \| `glfw.RawHats.up` |
/// | `glfw.RawHats.left_down` | `glfw.RawHats.left` \| `glfw.RawHats.down` |
///
/// The diagonal directions are bitwise combinations of the primary (up, right, down and left)
/// directions, since the Zig GLFW wrapper returns a packed struct it is trivial to test for these:
///
/// ```
/// if (hats.up and hats.right) {
/// // up-right!
/// }
/// ```
///
/// If the specified joystick is not present this function will return null but will not generate an
/// error. This can be used instead of first calling glfw.Joystick.present.
///
/// @return An array of hat states, or null if the joystick is not present.
///
/// Possible errors include glfw.ErrorCode.InvalidEnum and glfw.ErrorCode.PlatformError.
/// null is additionally returned in the event of an error.
///
/// @pointer_lifetime The returned array is allocated and freed by GLFW. You should not free it
/// yourself. It is valid until the specified joystick is disconnected, this function is called
/// again for that joystick or the library is terminated.
///
/// @thread_safety This function must only be called from the main thread.
///
/// see also: joystick_hat
pub inline fn getHats(self: Joystick) ?[]const Hat {
internal_debug.assertInitialized();
var count: c_int = undefined;
const hats = c.glfwGetJoystickHats(@intFromEnum(self.jid), &count);
if (hats == null) return null;
const slice = hats[0..@as(u32, @intCast(count))];
return @as(*const []const Hat, @ptrCast(&slice)).*;
}
/// Returns the name of the specified joystick.
///
/// This function returns the name, encoded as UTF-8, of the specified joystick. The returned string
/// is allocated and freed by GLFW. You should not free it yourself.
///
/// If the specified joystick is not present this function will return null but will not generate an
/// error. This can be used instead of first calling glfw.Joystick.present.
///
/// @return The UTF-8 encoded name of the joystick, or null if the joystick is not present or an
/// error occurred.
///
/// Possible errors include glfw.ErrorCode.InvalidEnum and glfw.ErrorCode.PlatformError.
/// null is additionally returned in the event of an error.
///
/// @pointer_lifetime The returned string is allocated and freed by GLFW. You should not free it
/// yourself. It is valid until the specified joystick is disconnected or the library is terminated.
///
/// @thread_safety This function must only be called from the main thread.
///
/// see also: joystick_name
pub inline fn getName(self: Joystick) ?[:0]const u8 {
internal_debug.assertInitialized();
const name_opt = c.glfwGetJoystickName(@intFromEnum(self.jid));
return if (name_opt) |name|
std.mem.span(@as([*:0]const u8, @ptrCast(name)))
else
null;
}
/// Returns the SDL compatible GUID of the specified joystick.
///
/// This function returns the SDL compatible GUID, as a UTF-8 encoded hexadecimal string, of the
/// specified joystick. The returned string is allocated and freed by GLFW. You should not free it
/// yourself.
///
/// The GUID is what connects a joystick to a gamepad mapping. A connected joystick will always have
/// a GUID even if there is no gamepad mapping assigned to it.
///
/// If the specified joystick is not present this function will return null but will not generate an
/// error. This can be used instead of first calling glfw.Joystick.present.
///
/// The GUID uses the format introduced in SDL 2.0.5. This GUID tries to uniquely identify the make
/// and model of a joystick but does not identify a specific unit, e.g. all wired Xbox 360
/// controllers will have the same GUID on that platform. The GUID for a unit may vary between
/// platforms depending on what hardware information the platform specific APIs provide.
///
/// @return The UTF-8 encoded GUID of the joystick, or null if the joystick is not present.
///
/// Possible errors include glfw.ErrorCode.InvalidEnum and glfw.ErrorCode.PlatformError.
/// null is additionally returned in the event of an error.
///
/// @pointer_lifetime The returned string is allocated and freed by GLFW. You should not free it
/// yourself. It is valid until the specified joystick is disconnected or the library is terminated.
///
/// @thread_safety This function must only be called from the main thread.
///
/// see also: gamepad
pub inline fn getGUID(self: Joystick) ?[:0]const u8 {
internal_debug.assertInitialized();
const guid_opt = c.glfwGetJoystickGUID(@intFromEnum(self.jid));
return if (guid_opt) |guid|
std.mem.span(@as([*:0]const u8, @ptrCast(guid)))
else
null;
}
/// Sets the user pointer of the specified joystick.
///
/// This function sets the user-defined pointer of the specified joystick. The current value is
/// retained until the joystick is disconnected. The initial value is null.
///
/// This function may be called from the joystick callback, even for a joystick that is being disconnected.
///
/// @thread_safety This function may be called from any thread. Access is not synchronized.
///
/// see also: joystick_userptr, glfw.Joystick.getUserPointer
pub inline fn setUserPointer(self: Joystick, comptime T: type, pointer: *T) void {
internal_debug.assertInitialized();
c.glfwSetJoystickUserPointer(@intFromEnum(self.jid), @as(*anyopaque, @ptrCast(pointer)));
}
/// Returns the user pointer of the specified joystick.
///
/// This function returns the current value of the user-defined pointer of the specified joystick.
/// The initial value is null.
///
/// This function may be called from the joystick callback, even for a joystick that is being
/// disconnected.
///
/// @thread_safety This function may be called from any thread. Access is not synchronized.
///
/// see also: joystick_userptr, glfw.Joystick.setUserPointer
pub inline fn getUserPointer(self: Joystick, comptime PointerType: type) ?PointerType {
internal_debug.assertInitialized();
const ptr = c.glfwGetJoystickUserPointer(@intFromEnum(self.jid));
if (ptr) |p| return @as(PointerType, @ptrCast(@alignCast(p)));
return null;
}
/// Describes an event relating to a joystick.
pub const Event = enum(c_int) {
/// The device was connected.
connected = c.GLFW_CONNECTED,
/// The device was disconnected.
disconnected = c.GLFW_DISCONNECTED,
};
/// Sets the joystick configuration callback.
///
/// This function sets the joystick configuration callback, or removes the currently set callback.
/// This is called when a joystick is connected to or disconnected from the system.
///
/// For joystick connection and disconnection events to be delivered on all platforms, you need to
/// call one of the event processing (see events) functions. Joystick disconnection may also be
/// detected and the callback called by joystick functions. The function will then return whatever
/// it returns if the joystick is not present.
///
/// @param[in] callback The new callback, or null to remove the currently set callback.
///
/// @callback_param `jid` The joystick that was connected or disconnected.
/// @callback_param `event` One of `.connected` or `.disconnected`. Future releases may add
/// more events.
///
/// @thread_safety This function must only be called from the main thread.
///
/// see also: joystick_event
pub inline fn setCallback(comptime callback: ?fn (joystick: Joystick, event: Event) void) void {
internal_debug.assertInitialized();
if (callback) |user_callback| {
const CWrapper = struct {
pub fn joystickCallbackWrapper(jid: c_int, event: c_int) callconv(.C) void {
@call(.always_inline, user_callback, .{
Joystick{ .jid = @as(Joystick.Id, @enumFromInt(jid)) },
@as(Event, @enumFromInt(event)),
});
}
};
if (c.glfwSetJoystickCallback(CWrapper.joystickCallbackWrapper) != null) return;
} else {
if (c.glfwSetJoystickCallback(null) != null) return;
}
}
/// Adds the specified SDL_GameControllerDB gamepad mappings.
///
/// This function parses the specified ASCII encoded string and updates the internal list with any
/// gamepad mappings it finds. This string may contain either a single gamepad mapping or many
/// mappings separated by newlines. The parser supports the full format of the `gamecontrollerdb.txt`
/// source file including empty lines and comments.
///
/// See gamepad_mapping for a description of the format.
///
/// If there is already a gamepad mapping for a given GUID in the internal list, it will be
/// replaced by the one passed to this function. If the library is terminated and re-initialized
/// the internal list will revert to the built-in default.
///
/// @param[in] string The string containing the gamepad mappings.
///
/// Possible errors include glfw.ErrorCode.InvalidValue.
/// Returns a boolean indicating success.
///
/// @thread_safety This function must only be called from the main thread.
///
/// see also: gamepad, glfw.Joystick.isGamepad, glfwGetGamepadName
///
///
/// @ingroup input
pub inline fn updateGamepadMappings(gamepad_mappings: [*:0]const u8) bool {
internal_debug.assertInitialized();
return c.glfwUpdateGamepadMappings(gamepad_mappings) == c.GLFW_TRUE;
}
/// Returns whether the specified joystick has a gamepad mapping.
///
/// This function returns whether the specified joystick is both present and has a gamepad mapping.
///
/// If the specified joystick is present but does not have a gamepad mapping this function will
/// return `false` but will not generate an error. Call glfw.Joystick.present to check if a
/// joystick is present regardless of whether it has a mapping.
///
/// @return `true` if a joystick is both present and has a gamepad mapping, or `false` otherwise.
///
/// Possible errors include glfw.ErrorCode.InvalidEnum.
/// Additionally returns false in the event of an error.
///
/// @thread_safety This function must only be called from the main thread.
///
/// see also: gamepad, glfw.Joystick.getGamepadState
pub inline fn isGamepad(self: Joystick) bool {
internal_debug.assertInitialized();
const is_gamepad = c.glfwJoystickIsGamepad(@intFromEnum(self.jid));
return is_gamepad == c.GLFW_TRUE;
}
/// Returns the human-readable gamepad name for the specified joystick.
///
/// This function returns the human-readable name of the gamepad from the gamepad mapping assigned
/// to the specified joystick.
///
/// If the specified joystick is not present or does not have a gamepad mapping this function will
/// return null, not an error. Call glfw.Joystick.present to check whether it is
/// present regardless of whether it has a mapping.
///
/// @return The UTF-8 encoded name of the gamepad, or null if the joystick is not present or does
/// not have a mapping.
///
/// Possible errors include glfw.ErrorCode.InvalidEnum.
/// Additionally returns null in the event of an error.
///
/// @pointer_lifetime The returned string is allocated and freed by GLFW. You should not free it
/// yourself. It is valid until the specified joystick is disconnected, the gamepad mappings are
/// updated or the library is terminated.
///
/// @thread_safety This function must only be called from the main thread.
///
/// see also: gamepad, glfw.Joystick.isGamepad
pub inline fn getGamepadName(self: Joystick) ?[:0]const u8 {
internal_debug.assertInitialized();
const name_opt = c.glfwGetGamepadName(@intFromEnum(self.jid));
return if (name_opt) |name|
std.mem.span(@as([*:0]const u8, @ptrCast(name)))
else
null;
}
/// Retrieves the state of the joystick remapped as a gamepad.
///
/// This function retrieves the state of the joystick remapped to an Xbox-like gamepad.
///
/// If the specified joystick is not present or does not have a gamepad mapping this function will
/// return `false`. Call glfw.joystickPresent to check whether it is present regardless of whether
/// it has a mapping.
///
/// The Guide button may not be available for input as it is often hooked by the system or the
/// Steam client.
///
/// Not all devices have all the buttons or axes provided by GamepadState. Unavailable buttons
/// and axes will always report `glfw.Action.release` and 0.0 respectively.
///
/// @param[in] jid The joystick (see joysticks) to query.
/// @param[out] state The gamepad input state of the joystick.
/// @return the gamepad input state if successful, or null if no joystick is connected or it has no
/// gamepad mapping.
///
/// Possible errors include glfw.ErrorCode.InvalidEnum.
/// Returns null in the event of an error.
///
/// @thread_safety This function must only be called from the main thread.
///
/// see also: gamepad, glfw.UpdateGamepadMappings, glfw.Joystick.isGamepad
pub inline fn getGamepadState(self: Joystick) ?GamepadState {
internal_debug.assertInitialized();
var state: GamepadState = undefined;
const success = c.glfwGetGamepadState(@intFromEnum(self.jid), @as(*c.GLFWgamepadstate, @ptrCast(&state)));
return if (success == c.GLFW_TRUE) state else null;
}
test "present" {
const glfw = @import("main.zig");
defer glfw.clearError(); // clear any error we generate
if (!glfw.init(.{})) {
std.log.err("failed to initialize GLFW: {?s}", .{glfw.getErrorString()});
std.process.exit(1);
}
defer glfw.terminate();
const joystick = glfw.Joystick{ .jid = .one };
_ = joystick.present();
}
test "getAxes" {
const glfw = @import("main.zig");
defer glfw.clearError(); // clear any error we generate
if (!glfw.init(.{})) {
std.log.err("failed to initialize GLFW: {?s}", .{glfw.getErrorString()});
std.process.exit(1);
}
defer glfw.terminate();
const joystick = glfw.Joystick{ .jid = .one };
_ = joystick.getAxes();
}
test "getButtons" {
const glfw = @import("main.zig");
defer glfw.clearError(); // clear any error we generate
if (!glfw.init(.{})) {
std.log.err("failed to initialize GLFW: {?s}", .{glfw.getErrorString()});
std.process.exit(1);
}
defer glfw.terminate();
const joystick = glfw.Joystick{ .jid = .one };
_ = joystick.getButtons();
}
test "getHats" {
const glfw = @import("main.zig");
defer glfw.clearError(); // clear any error we generate
if (!glfw.init(.{})) {
std.log.err("failed to initialize GLFW: {?s}", .{glfw.getErrorString()});
std.process.exit(1);
}
defer glfw.terminate();
const joystick = glfw.Joystick{ .jid = .one };
if (joystick.getHats()) |hats| {
for (hats) |hat| {
if (hat.down and hat.up) {
// down-up!
}
}
}
}
test "getName" {
const glfw = @import("main.zig");
defer glfw.clearError(); // clear any error we generate
if (!glfw.init(.{})) {
std.log.err("failed to initialize GLFW: {?s}", .{glfw.getErrorString()});
std.process.exit(1);
}
defer glfw.terminate();
const joystick = glfw.Joystick{ .jid = .one };
_ = joystick.getName();
}
test "getGUID" {
const glfw = @import("main.zig");
defer glfw.clearError(); // clear any error we generate
if (!glfw.init(.{})) {
std.log.err("failed to initialize GLFW: {?s}", .{glfw.getErrorString()});
std.process.exit(1);
}
defer glfw.terminate();
const joystick = glfw.Joystick{ .jid = .one };
_ = joystick.getGUID();
}
test "setUserPointer_syntax" {
const glfw = @import("main.zig");
defer glfw.clearError(); // clear any error we generate
if (!glfw.init(.{})) {
std.log.err("failed to initialize GLFW: {?s}", .{glfw.getErrorString()});
std.process.exit(1);
}
defer glfw.terminate();
const joystick = glfw.Joystick{ .jid = .one };
// Must be called from joystick callback, we cannot test it.
_ = joystick;
_ = setUserPointer;
}
test "getUserPointer_syntax" {
const glfw = @import("main.zig");
defer glfw.clearError(); // clear any error we generate
if (!glfw.init(.{})) {
std.log.err("failed to initialize GLFW: {?s}", .{glfw.getErrorString()});
std.process.exit(1);
}
defer glfw.terminate();
const joystick = glfw.Joystick{ .jid = .one };
// Must be called from joystick callback, we cannot test it.
_ = joystick;
_ = getUserPointer;
}
test "setCallback" {
const glfw = @import("main.zig");
defer glfw.clearError(); // clear any error we generate
if (!glfw.init(.{})) {
std.log.err("failed to initialize GLFW: {?s}", .{glfw.getErrorString()});
std.process.exit(1);
}
defer glfw.terminate();
glfw.Joystick.setCallback((struct {
pub fn callback(joystick: Joystick, event: Event) void {
_ = joystick;
_ = event;
}
}).callback);
}
test "updateGamepadMappings_syntax" {
// We don't have a gamepad mapping to test with, just confirm the syntax is good.
_ = updateGamepadMappings;
}
test "isGamepad" {
const glfw = @import("main.zig");
defer glfw.clearError(); // clear any error we generate
if (!glfw.init(.{})) {
std.log.err("failed to initialize GLFW: {?s}", .{glfw.getErrorString()});
std.process.exit(1);
}
defer glfw.terminate();
const joystick = glfw.Joystick{ .jid = .one };
_ = joystick.isGamepad();
}
test "getGamepadName" {
const glfw = @import("main.zig");
defer glfw.clearError(); // clear any error we generate
if (!glfw.init(.{})) {
std.log.err("failed to initialize GLFW: {?s}", .{glfw.getErrorString()});
std.process.exit(1);
}
defer glfw.terminate();
const joystick = glfw.Joystick{ .jid = .one };
_ = joystick.getGamepadName();
}
test "getGamepadState" {
const glfw = @import("main.zig");
defer glfw.clearError(); // clear any error we generate
if (!glfw.init(.{})) {
std.log.err("failed to initialize GLFW: {?s}", .{glfw.getErrorString()});
std.process.exit(1);
}
defer glfw.terminate();
const joystick = glfw.Joystick{ .jid = .one };
_ = joystick.getGamepadState();
_ = (std.mem.zeroes(GamepadState)).getAxis(.left_x);
_ = (std.mem.zeroes(GamepadState)).getButton(.dpad_up);
}
|
0 | repos/mach-glfw | repos/mach-glfw/src/version.zig | //! GLFW version info
const c = @import("c.zig").c;
/// The major version number of the GLFW library.
///
/// This is incremented when the API is changed in non-compatible ways.
pub const major = c.GLFW_VERSION_MAJOR;
/// The minor version number of the GLFW library.
///
/// This is incremented when features are added to the API but it remains backward-compatible.
pub const minor = c.GLFW_VERSION_MINOR;
/// The revision number of the GLFW library.
///
/// This is incremented when a bug fix release is made that does not contain any API changes.
pub const revision = c.GLFW_VERSION_REVISION;
|
0 | repos/mach-glfw | repos/mach-glfw/src/mouse_button.zig | const c = @import("c.zig").c;
/// Mouse button IDs.
///
/// See glfw.setMouseButtonCallback for how these are used.
pub const MouseButton = enum(c_int) {
// We use left/right/middle aliases here because those are more common and we cannot have
// duplicate values in a Zig enum.
left = c.GLFW_MOUSE_BUTTON_1,
right = c.GLFW_MOUSE_BUTTON_2,
middle = c.GLFW_MOUSE_BUTTON_3,
four = c.GLFW_MOUSE_BUTTON_4,
five = c.GLFW_MOUSE_BUTTON_5,
six = c.GLFW_MOUSE_BUTTON_6,
seven = c.GLFW_MOUSE_BUTTON_7,
eight = c.GLFW_MOUSE_BUTTON_8,
};
/// Not in the MouseButton enumeration as it is a duplicate value which is forbidden.
pub const last = MouseButton.eight;
pub const one = MouseButton.left;
pub const two = MouseButton.right;
pub const three = MouseButton.middle;
|
0 | repos/mach-glfw | repos/mach-glfw/src/action.zig | const c = @import("c.zig").c;
/// Key and button actions
pub const Action = enum(c_int) {
/// The key or mouse button was released.
release = c.GLFW_RELEASE,
/// The key or mouse button was pressed.
press = c.GLFW_PRESS,
/// The key was held down until it repeated.
repeat = c.GLFW_REPEAT,
};
|
0 | repos/mach-glfw/src | repos/mach-glfw/src/cimport/c_normal_native.zig | pub fn import(comptime options: anytype) type {
return @cImport({
@cDefine("GLFW_INCLUDE_VULKAN", "1");
@cInclude("GLFW/glfw3.h");
if (options.win32) @cDefine("GLFW_EXPOSE_NATIVE_WIN32", "1");
if (options.wgl) @cDefine("GLFW_EXPOSE_NATIVE_WGL", "1");
if (options.cocoa) @cDefine("GLFW_EXPOSE_NATIVE_COCOA", "1");
if (options.nsgl) @cDefine("GLFW_EXPOSE_NATIVE_NGSL", "1");
if (options.x11) @cDefine("GLFW_EXPOSE_NATIVE_X11", "1");
if (options.glx) @cDefine("GLFW_EXPOSE_NATIVE_GLX", "1");
if (options.wayland) @cDefine("GLFW_EXPOSE_NATIVE_WAYLAND", "1");
if (options.egl) @cDefine("GLFW_EXPOSE_NATIVE_EGL", "1");
if (options.osmesa) @cDefine("GLFW_EXPOSE_NATIVE_OSMESA", "1");
@cInclude("GLFW/glfw3native.h");
});
}
|
0 | repos | repos/Ziguana-Game-System/README.md | # Ziguana Game System
This is a fake/virtual console which is work in progress.

## Info
A small virtual console programmed in [LoLa](https://lola.random-projects.net/). Create low-resolution pixel art games with an ease!
## Specs
- 120×90 pixel resolution
- 16 color fixed palette
- programmed in [LoLa](https://lola.random-projects.net/)
- (planned) crossplatform support for
- Windows
- Linux
- Android
- x86 freestanding (ZGS as an OS)
### APIs
The console provides APIs for saving/loading game states, accessing resource data, drawing simple graphics, interface with the text mode, do audio playback, and read inputs.
For a full documentation of the API, see [documentation/api-design.md](documentation/api-design.md).
### Palette
Uses [Dawnbringers 16](https://lospec.com/palette-list/dawnbringer-16) palette:
| Index | Hexcode | Name | Preview |
| ----- | --------- | ----------- | --------------------------------------------------------------- |
| 0 | `#140c1c` | black |  |
| 1 | `#442434` | dark purple |  |
| 2 | `#30346d` | dark blue |  |
| 3 | `#4e4a4e` | dark gray |  |
| 4 | `#854c30` | brown |  |
| 5 | `#346524` | dark green |  |
| 6 | `#d04648` | red |  |
| 7 | `#757161` | gray |  |
| 8 | `#597dce` | blue |  |
| 9 | `#d27d2c` | orange |  |
| A | `#8595a1` | light gray |  |
| B | `#6daa2c` | green |  |
| C | `#d2aa99` | skin |  |
| D | `#6dc2ca` | dim cyan |  |
| E | `#dad45e` | yellow |  |
| F | `#deeed6` | white |  |
|
0 | repos | repos/Ziguana-Game-System/build.zig | const std = @import("std");
const is_windows_host = (std.builtin.os.tag == .windows);
const pkgs = struct {
const painterz = std.build.Pkg{
.name = "painterz",
.path = "extern/painterz/painterz.zig",
};
const interface = std.build.Pkg{
.name = "interface",
.path = "extern/interface/interface.zig",
};
const args = std.build.Pkg{
.name = "args",
.path = "extern/args/args.zig",
};
const lola = std.build.Pkg{
.name = "lola",
.path = "extern/lola/src/library/main.zig",
.dependencies = &[_]std.build.Pkg{
interface,
},
};
const sdl2 = std.build.Pkg{
.name = "sdl2",
.path = "extern/sdl2/src/lib.zig",
};
const zgs = std.build.Pkg{
.name = "zgs",
.path = "src/core/zgs.zig",
.dependencies = &[_]std.build.Pkg{
lola, painterz,
},
};
};
pub fn build(b: *std.build.Builder) !void {
try std.fs.cwd().makePath("zig-cache/bin");
const pc_exe = b.addExecutable("zgs.pc", "src/pc/main.zig");
pc_exe.linkLibC();
pc_exe.linkSystemLibrary("sdl2");
pc_exe.addPackage(pkgs.sdl2);
pc_exe.addPackage(pkgs.zgs);
pc_exe.addPackage(pkgs.lola);
pc_exe.addPackage(pkgs.args);
pc_exe.install();
const run_step = pc_exe.run();
run_step.addArg("--directory");
run_step.addArg("examples/bouncy");
b.step("run", "Starts the game system").dependOn(&run_step.step);
const resources_step = b.step("resources", "Regenerates the resource files");
{
const compile_mkbitmap = b.addSystemCommand(&[_][]const u8{
if (is_windows_host) "C:\\Windows\\Microsoft.NET\\Framework\\v.4.0.30319\\csc" else "mcs",
"src/tools/mkbitmap.cs",
"/r:System.Drawing.dll",
"/out:zig-cache/bin/mkbitmap.exe",
});
const build_font = b.addSystemCommand(if (is_windows_host)
&[_][]const u8{
"zig-cache\\bin\\mkbitmap.exe",
"res/dos_8x8_font_white.png",
"src/core/res/font.dat",
}
else
&[_][]const u8{
"mono",
"zig-cache\\bin\\mkbitmap.exe",
"res/dos_8x8_font_white.png",
"src/core/res/font.dat",
});
build_font.step.dependOn(&compile_mkbitmap.step);
resources_step.dependOn(&build_font.step);
}
}
|
0 | repos/Ziguana-Game-System/src | repos/Ziguana-Game-System/src/pc/main.zig | const std = @import("std");
const zgs = @import("zgs");
const lola = @import("lola");
const sdl = @import("sdl2");
const args_parser = @import("args");
var gpa_state = std.heap.GeneralPurposeAllocator(.{}){};
const gpa = &gpa_state.allocator;
const CliArgs = struct {
directory: ?[]const u8 = null,
game: ?[]const u8 = null,
};
pub fn main() !u8 {
defer _ = gpa_state.deinit();
var cli_args = try args_parser.parseForCurrentProcess(CliArgs, gpa);
defer cli_args.deinit();
if (cli_args.options.directory != null and cli_args.options.game != null) {
@panic("print usage message and error");
// return 1;
}
try sdl.init(.{
.video = true,
.audio = true,
.events = true,
});
defer sdl.quit();
const scale = 6;
var window = try sdl.createWindow(
"Ziguana Game System",
.centered,
.centered,
scale * zgs.Screen.total_width,
scale * zgs.Screen.total_height,
.{},
);
defer window.destroy();
var renderer = try sdl.createRenderer(
window,
null,
.{
.accelerated = true,
.present_vsync = true,
},
);
defer renderer.destroy();
var screen_buffer = try sdl.createTexture(
renderer,
.abgr8888,
.streaming,
zgs.Screen.total_width,
zgs.Screen.total_height,
);
defer screen_buffer.destroy();
var game_system = try zgs.init(gpa);
defer game_system.deinit();
var game: ?zgs.GameROM = null;
if (cli_args.options.directory) |directory_path| {
var dir = try std.fs.cwd().openDir(directory_path, .{});
defer dir.close();
game = try createROMFromDirectory(dir);
}
defer if (game) |*g| deinitROM(g);
if (game) |*g|
try game_system.loadGame(g);
var system_timer = try std.time.Timer.start();
main_loop: while (true) {
while (sdl.pollEvent()) |event| {
switch (event) {
.quit => break :main_loop,
.key_down => |key| {
switch (key.keysym.scancode) {
else => {},
}
},
.key_up => |key| {
switch (key.keysym.scancode) {
else => {},
}
},
else => {},
}
}
var keyboard = sdl.getKeyboardState();
{
var joystick_state = zgs.JoystickState{
.x = 0,
.y = 0,
.a = false,
.b = false,
.menu = false,
.go = false,
};
if (keyboard.isPressed(.SDL_SCANCODE_LEFT))
joystick_state.x -= 1;
if (keyboard.isPressed(.SDL_SCANCODE_RIGHT))
joystick_state.x += 1;
if (keyboard.isPressed(.SDL_SCANCODE_UP))
joystick_state.y -= 1;
if (keyboard.isPressed(.SDL_SCANCODE_DOWN))
joystick_state.y += 1;
joystick_state.a = keyboard.isPressed(.SDL_SCANCODE_Y) or keyboard.isPressed(.SDL_SCANCODE_Z); // be friendly to germans as well
joystick_state.b = keyboard.isPressed(.SDL_SCANCODE_X);
joystick_state.menu = keyboard.isPressed(.SDL_SCANCODE_ESCAPE);
joystick_state.go = keyboard.isPressed(.SDL_SCANCODE_RETURN);
game_system.setJoystick(joystick_state);
}
switch (try game_system.update()) {
.yield => {},
.quit => break :main_loop,
.render => {
const screen_content = game_system.virtual_screen.render();
try screen_buffer.update(std.mem.sliceAsBytes(&screen_content), @sizeOf(zgs.Screen.RGBA) * screen_content[0].len, null);
try renderer.copy(screen_buffer, null, null);
renderer.present();
},
}
}
return 0;
}
fn createROMFromDirectory(dir: std.fs.Dir) !zgs.GameROM {
var game = zgs.GameROM{
.id = undefined,
.name = undefined,
.icon = undefined,
.code = undefined,
.data = undefined,
};
game.id = blk: {
var file = try dir.openFile("game.id", .{});
defer file.close();
break :blk try file.readToEndAlloc(gpa, 128);
};
errdefer gpa.free(game.id);
game.name = blk: {
var file = try dir.openFile("game.name", .{});
defer file.close();
break :blk try file.readToEndAlloc(gpa, 64);
};
errdefer gpa.free(game.name);
blk: {
var file = dir.openFile("game.ico", .{}) catch |err| switch (err) {
// when file not there, just leave the default icon
error.FileNotFound => break :blk,
else => |e| return e,
};
defer file.close();
try file.reader().readNoEof(std.mem.asBytes(&game.icon));
}
game.code = if (dir.openFile("game.lola", .{})) |file| blk: {
defer file.close();
const source = try file.readToEndAlloc(gpa, 1 << 20); // 1 MB of source is a lot
defer gpa.free(source);
var diagnostics = lola.compiler.Diagnostics.init(gpa);
defer diagnostics.deinit();
var module_or_null = try lola.compiler.compile(
gpa,
&diagnostics,
"game.lola",
source,
);
for (diagnostics.messages.items) |msg| {
std.debug.print("{}\n", .{msg});
}
break :blk module_or_null orelse return error.InvalidSource;
} else |err| blk: {
if (err != error.FileNotFound)
return err;
var file = try dir.openFile("game.lola.lm", .{});
defer file.close();
break :blk try lola.CompileUnit.loadFromStream(gpa, file.reader());
};
errdefer game.code.deinit();
game.data = std.StringHashMap([]const u8).init(gpa);
errdefer game.data.deinit();
var data_directory = dir.openDir("data", .{
.iterate = true,
.no_follow = true,
}) catch |err| switch (err) {
// No data directory, we are done
error.FileNotFound => return game,
else => |e| return e,
};
defer data_directory.close();
// TODO: Iterate recursively through all subfolders
var iterator = data_directory.iterate();
while (try iterator.next()) |entry| {
switch (entry.kind) {
.File => {
var file = try data_directory.openFile(entry.name, .{});
defer file.close();
const name = try gpa.dupe(u8, entry.name);
errdefer gpa.free(name);
const contents = try file.readToEndAlloc(gpa, 16 << 20); // 16 MB
errdefer gpa.free(contents);
try game.data.put(name, contents);
},
.Directory => @panic("TODO: Directory recursion not implemented yet!"),
else => {},
}
}
return game;
}
fn deinitROM(rom: *zgs.GameROM) void {
var iter = rom.data.iterator();
while (iter.next()) |kv| {
gpa.free(kv.key);
gpa.free(kv.value);
}
gpa.free(rom.name);
gpa.free(rom.id);
rom.code.deinit();
rom.data.deinit();
rom.* = undefined;
}
|
0 | repos/Ziguana-Game-System/src | repos/Ziguana-Game-System/src/core/zgs.zig | const std = @import("std");
const lola = @import("lola");
const painterz = @import("painterz");
pub const ObjectPool = lola.runtime.ObjectPool(.{});
fn parsePixelValue(value: ?u8) ?u4 {
if (value == null)
return null;
return switch (value.?) {
0...15 => @truncate(u4, value.?),
'0'...'9' => @truncate(u4, value.? - '0'),
'a'...'f' => @truncate(u4, value.? - 'a' + 10),
'A'...'F' => @truncate(u4, value.? - 'A' + 10),
else => null,
};
}
pub const Color = struct {
const black = 0x0;
const dark_purple = 0x1;
const dark_blue = 0x2;
const dark_gray = 0x3;
const brown = 0x4;
const dark_green = 0x5;
const red = 0x6;
const gray = 0x7;
const blue = 0x8;
const orange = 0x9;
const light_gray = 0xA;
const green = 0xB;
const skin = 0xC;
const dim_cyan = 0xD;
const yellow = 0xE;
const white = 0xF;
};
comptime {
if (Screen.width % TextTerminal.width != 0)
@compileError("TextTerminal.width is not a integer divisor of Screen.width!");
if (Screen.height % TextTerminal.height != 0)
@compileError("TextTerminal.height is not a integer divisor of Screen.height!");
if ((Screen.width / TextTerminal.width) != (Screen.height / TextTerminal.height))
@compileError("TextTerminal does not have square tiles!");
}
pub const TextTerminal = struct {
const Self = @This();
const raw_font = @as([tile_size * 256]u8, @embedFile("res/font.dat").*);
const CursorPosition = struct {
x: usize,
y: usize,
};
const Char = struct {
data: u8,
color: ?u4,
const empty = @This(){
.data = ' ',
.color = null,
};
};
pub const width = 20;
pub const height = 15;
pub const tile_size = Screen.width / width;
comptime {
if (tile_size < 1 or tile_size > 8) {
@compileError("TextTerminal.tile_size must be less or equal than 8 pixel large!");
}
}
const empty_row = [1]Char{Char.empty} ** width;
const empty_screen = [1][20]Char{empty_row} ** height;
content: [height][width]Char = empty_screen,
cursor_visible: bool = true,
cursor_position: CursorPosition = CursorPosition{ .x = 0, .y = 0 },
bg_color: ?u4 = 0,
fg_color: ?u4 = 15,
const Glyph = struct {
bits: [tile_size]u8,
fn get(self: @This(), x: u3, y: u3) callconv(.Inline) bool {
return (self.bits[y] & (@as(u8, 1) << x)) != 0;
}
};
pub fn getGlyph(char: u8) Glyph {
return Glyph{ .bits = raw_font[tile_size * @as(usize, char) ..][0..tile_size].* };
}
pub fn render(self: Self, screen: *Screen, cursor_blink_active: bool) void {
for (self.content) |line, row| {
for (line) |char, column| {
const glyph = getGlyph(char.data);
var y: usize = 0;
while (y < tile_size) : (y += 1) {
// unroll 6 pixel-set operations
comptime var x = 0;
inline while (x < tile_size) : (x += 1) {
screen.pixels[tile_size * row + y][tile_size * column + x] = if ((glyph.get(x, @truncate(u3, y))))
char.color orelse @as(u8, 0xFF)
else
self.bg_color orelse @as(u8, 0xFF);
}
}
}
}
if (self.cursor_visible and cursor_blink_active) {
var y: usize = 0;
while (y < tile_size) : (y += 1) {
var x: usize = 0;
while (x < tile_size) : (x += 1) {
screen.pixels[tile_size * self.cursor_position.y + y][tile_size * self.cursor_position.x + x] = self.fg_color orelse 0xFF;
}
}
}
}
pub fn clear(self: *Self) void {
self.content = empty_screen;
self.cursor_position = CursorPosition{
.x = 0,
.y = 0,
};
}
pub fn scroll(self: *Self, amount: u32) void {
if (amount > self.content.len) {
self.content = empty_screen;
} else {
var r: usize = 1;
while (r < self.content.len) : (r += 1) {
self.content[r - 1] = self.content[r];
}
self.content[self.content.len - 1] = empty_row;
}
}
pub fn put(self: *Self, char: u8) void {
switch (char) {
'\r' => self.cursor_position.x = 0,
'\n' => self.cursor_position.y += 1,
else => {
self.content[self.cursor_position.y][self.cursor_position.x] = Char{
.data = char,
.color = self.fg_color,
};
self.cursor_position.x += 1;
},
}
if (self.cursor_position.x >= self.content[0].len) {
self.cursor_position.x = 0;
self.cursor_position.y += 1;
}
if (self.cursor_position.y >= self.content.len) {
self.scroll(1);
self.cursor_position.y -= 1;
}
}
pub fn write(self: *Self, string: []const u8) void {
for (string) |c| {
self.put(c);
}
}
const Writer = std.io.Writer(*Self, error{}, struct {
fn write(self: *Self, buffer: []const u8) error{}!usize {
self.write(buffer);
return buffer.len;
}
}.write);
pub fn writer(self: *Self) Writer {
return Writer{ .context = self };
}
};
pub const Screen = struct {
const Self = @This();
pub const RGBA = extern struct {
r: u8,
g: u8,
b: u8,
a: u8 = 0xFF,
};
pub const border_size = 16;
pub const width = 160;
pub const height = 120;
pub const total_width = 2 * border_size + width;
pub const total_height = 2 * border_size + height;
border_color: u8 = 2, // dim blue
pixels: [height][width]u8 = [1][width]u8{[1]u8{0} ** width} ** height,
pixel_rng: std.rand.DefaultPrng = std.rand.DefaultPrng.init(1337), // can always be the same sequence, shouldn't matter
palette: [16]RGBA = [16]RGBA{
// Using the Dawnbringer 16 palette by default.
// https://lospec.com/palette-list/dawnbringer-16
RGBA{ .r = 0x14, .g = 0x0c, .b = 0x1c }, // 0 #140c1c black
RGBA{ .r = 0x44, .g = 0x24, .b = 0x34 }, // 1 #442434 dark purple
RGBA{ .r = 0x30, .g = 0x34, .b = 0x6d }, // 2 #30346d dark blue
RGBA{ .r = 0x4e, .g = 0x4a, .b = 0x4e }, // 3 #4e4a4e dark gray
RGBA{ .r = 0x85, .g = 0x4c, .b = 0x30 }, // 4 #854c30 brown
RGBA{ .r = 0x34, .g = 0x65, .b = 0x24 }, // 5 #346524 dark green
RGBA{ .r = 0xd0, .g = 0x46, .b = 0x48 }, // 6 #d04648 red
RGBA{ .r = 0x75, .g = 0x71, .b = 0x61 }, // 7 #757161 gray
RGBA{ .r = 0x59, .g = 0x7d, .b = 0xce }, // 8 #597dce blue
RGBA{ .r = 0xd2, .g = 0x7d, .b = 0x2c }, // 9 #d27d2c orange
RGBA{ .r = 0x85, .g = 0x95, .b = 0xa1 }, // A #8595a1 light gray
RGBA{ .r = 0x6d, .g = 0xaa, .b = 0x2c }, // B #6daa2c green
RGBA{ .r = 0xd2, .g = 0xaa, .b = 0x99 }, // C #d2aa99 skin
RGBA{ .r = 0x6d, .g = 0xc2, .b = 0xca }, // D #6dc2ca dim cyan
RGBA{ .r = 0xda, .g = 0xd4, .b = 0x5e }, // E #dad45e yellow
RGBA{ .r = 0xde, .g = 0xee, .b = 0xd6 }, // F #deeed6 white
},
fn translateColor(self: *Self, color: u8) RGBA {
const index = std.math.cast(u4, color) catch self.pixel_rng.random.int(u4);
return self.palette[index];
}
pub fn set(self: *Self, x: isize, y: isize, color: u8) void {
const px = std.math.cast(usize, x) catch return;
const py = std.math.cast(usize, y) catch return;
if (px >= width) return;
if (py >= height) return;
self.pixels[py][px] = color;
}
pub fn get(self: Self, x: isize, y: isize) u8 {
const px = std.math.cast(usize, x) catch return 0xFF;
const py = std.math.cast(usize, y) catch return 0xFF;
if (px >= width) return 0xFF;
if (py >= height) return 0xFF;
return self.pixels[py][px];
}
pub fn render(self: *Self) [total_height][total_width]RGBA {
var buffer: [total_height][total_width]RGBA = undefined;
for (buffer) |*row| {
for (row) |*color| {
color.* = self.translateColor(self.border_color);
}
}
for (self.pixels) |row, y| {
for (row) |color, x| {
buffer[border_size + y][border_size + x] = self.translateColor(color);
}
}
return buffer;
}
fn clear(self: *Self, color: u8) void {
for (self.pixels) |*row| {
for (row) |*pixel| {
pixel.* = color;
}
}
}
fn scroll(self: *Self, src_dx: i32, src_dy: i32) void {
const srcbuf = self.pixels;
const dx: u32 = @intCast(u32, @mod(-src_dx, Screen.width));
const dy: u32 = @intCast(u32, @mod(-src_dy, Screen.height));
if (dx == 0 and dy == 0)
return;
const H = struct {
fn wrapAdd(a: usize, b: u32, comptime limit: comptime_int) u32 {
return (@intCast(u32, a) + b) % limit;
}
};
for (self.pixels) |*row, y| {
for (row) |*pixel, x| {
pixel.* = srcbuf[H.wrapAdd(y, dy, Screen.height)][H.wrapAdd(x, dx, Screen.width)];
}
}
}
fn blitBuffer(self: *Self, dst_x: i32, dst_y: i32, buffer_width: u31, pixel_buffer: []const u8) void {
if (buffer_width == 0)
return;
var index: usize = 0;
var dy: u31 = 0;
while (true) : (dy += 1) {
var dx: u31 = 0;
while (dx < buffer_width) : (dx += 1) {
const pixel = pixel_buffer[index];
if (parsePixelValue(pixel)) |color| {
self.set(
dst_x + @as(i32, dx),
dst_y + @as(i32, dy),
color,
);
}
index += 1;
if (index >= pixel_buffer.len)
return;
}
}
}
fn drawText(self: *Self, x: i32, y: i32, color: ?u8, text: []const u8) void {
var dx = x;
var dy = y;
for (text) |char| {
const glyph = TextTerminal.getGlyph(char);
var iy: u4 = 0;
while (iy < TextTerminal.tile_size) : (iy += 1) {
comptime var ix: u4 = 0;
inline while (ix < TextTerminal.tile_size) : (ix += 1) {
if (glyph.get(@truncate(u3, ix), @truncate(u3, iy))) {
self.set(
dx + @as(i32, ix),
dy + @as(i32, iy),
color orelse 0xFF,
);
}
}
}
dx += TextTerminal.tile_size;
}
}
};
pub const JoystickButton = struct {
const Self = @This();
is_pressed: bool = false,
press_state: bool = false,
release_state: bool = false,
pub fn wasHit(self: *Self) bool {
defer self.press_state = self.is_pressed;
return if (self.is_pressed)
!self.press_state
else
false;
}
pub fn wasReleased(self: *Self) bool {
defer self.release_state = self.is_pressed;
return if (!self.is_pressed)
self.release_state
else
false;
}
/// Syncs the event states so no cached event might be happening
fn resetEvent(self: *Self) void {
self.press_state = self.is_pressed;
self.release_state = self.is_pressed;
}
};
pub const JoystickState = struct {
x: f64,
y: f64,
a: bool,
b: bool,
go: bool,
menu: bool,
};
const Joystick = struct {
const Self = @This();
x: f64 = 0,
y: f64 = 0,
up: JoystickButton = JoystickButton{},
down: JoystickButton = JoystickButton{},
left: JoystickButton = JoystickButton{},
right: JoystickButton = JoystickButton{},
a: JoystickButton = JoystickButton{},
b: JoystickButton = JoystickButton{},
go: JoystickButton = JoystickButton{},
menu: JoystickButton = JoystickButton{},
fn update(self: *Self, state: JoystickState) void {
self.x = state.x;
self.y = state.y;
self.up.is_pressed = self.y < -0.1;
self.down.is_pressed = self.y > 0.1;
self.left.is_pressed = self.x < -0.1;
self.right.is_pressed = self.x > 0.1;
self.a.is_pressed = state.a;
self.b.is_pressed = state.b;
self.go.is_pressed = state.go;
self.menu.is_pressed = state.menu;
}
fn resetEvents(self: *Self) void {
self.a.resetEvent();
self.b.resetEvent();
self.go.resetEvent();
self.menu.resetEvent();
}
};
/// Initialize a new game system.
/// The system is allocated by allocator to ensure the returned value is a pinned pointer as
/// System stores internal references.
pub fn init(allocator: *std.mem.Allocator) !*System {
var system = try allocator.create(System);
errdefer allocator.destroy(system);
system.* = System{
.allocator = allocator,
.game = null,
};
return system;
}
pub const System = struct {
const Self = @This();
const Event = union(enum) {
/// The game system is done, shut down the emulator
quit,
/// Flush System.virtual_screen to the actual screen.
render,
/// The system is stale and requires either more events to be pushed
/// or enough time has passed and control should return to the caller
/// again (required for WASM and other systems)
yield,
};
const State = union(enum) {
// Either running the game (if any) or show a broken screen
default,
shutdown,
save_dialog: *SaveGameCall,
load_dialog: *LoadGameCall,
pause_dialog: *PauseGameCall,
};
const GraphicsMode = enum { text, graphics };
allocator: *std.mem.Allocator,
virtual_screen: Screen = Screen{},
virtual_terminal: TextTerminal = TextTerminal{},
state: State = .default,
game: ?Game = null,
is_finished: bool = false,
graphics_mode: GraphicsMode = .text,
gpu_auto_flush: bool = true,
gpu_flush: bool = false,
is_joystick_normalized: bool = false,
joystick: Joystick = Joystick{},
/// Loads the given game, unloading any currently loaded game.
/// Note that the system keeps the pointer to `game` until the system is closed. Don't free game
/// before the system is deinitialized.
pub fn loadGame(self: *Self, rom: *const GameROM) !void {
self.unloadGame();
self.game = @as(Game, undefined); // makes self.game non-null
try Game.init(&self.game.?, self, rom);
errdefer game = null;
}
/// Unloads the current game and resumes the home position.
pub fn unloadGame(self: *Self) void {
// switch (self.state) {
// .default => {},
// }
if (self.game) |*game| {
game.deinit();
}
self.game = null;
self.state = .default;
self.resetScreen();
}
pub fn update(self: *Self) !Event {
defer self.gpu_flush = false;
const loop_event: Event = switch (self.state) {
.shutdown => return .quit,
.default => blk: {
if (self.game) |*game| {
const result = game.vm.execute(10_000) catch |err| {
if (err == error.PoweroffSignal) {
self.state = .shutdown;
break :blk .yield;
} else {
// TODO: Print stack trace here
std.debug.print("failed with {s}\n", .{@errorName(err)});
try game.vm.printStackTrace(std.io.getStdOut().writer());
}
self.unloadGame();
break :blk Event.render;
};
switch (result) {
.completed => {
self.unloadGame();
break :blk Event.yield;
},
.exhausted, .paused => break :blk if (self.gpu_auto_flush or self.gpu_flush)
Event.render
else
Event.yield,
}
} else {
self.virtual_screen.clear(0xFF);
// what to do here?
break :blk Event.render;
}
},
.save_dialog => |call| {
std.debug.assert(self.game != null);
if (self.joystick.menu.wasHit()) {
call.result = false;
return self.closeDialog(&call.dialog);
}
if (self.joystick.b.wasHit()) {
call.result = true;
return self.closeDialog(&call.dialog);
}
if (self.joystick.up.wasHit() and call.selected_slot > 0) {
call.selected_slot -= 1;
}
if (self.joystick.down.wasHit() and call.selected_slot < 2) {
call.selected_slot += 1;
}
self.virtual_screen.clear(Color.light_gray);
self.virtual_screen.drawText(28, 2, Color.dark_purple, "<<SAVE GAME>>");
self.virtual_screen.drawText(0, 12, Color.white, "Chose your game file");
self.virtual_screen.drawText(0, 24, Color.white, "[ ] <empty>");
self.virtual_screen.drawText(0, 32, Color.white, "[ ] <empty>");
self.virtual_screen.drawText(0, 40, Color.white, "[ ] <empty>");
self.virtual_screen.drawText(8, 24 + 8 * call.selected_slot, Color.red, "X");
return .render;
},
.load_dialog => |call| {
std.debug.assert(self.game != null);
if (self.joystick.menu.wasHit()) {
call.data = null;
return self.closeDialog(&call.dialog);
}
if (self.joystick.b.wasHit()) {
call.data = switch (call.selected_slot) {
0 => try self.allocator.dupe(u8, "1"),
1 => try self.allocator.dupe(u8, "2"),
2 => try self.allocator.dupe(u8, "3"),
else => unreachable,
};
return self.closeDialog(&call.dialog);
}
if (self.joystick.up.wasHit() and call.selected_slot > 0) {
call.selected_slot -= 1;
}
if (self.joystick.down.wasHit() and call.selected_slot < 2) {
call.selected_slot += 1;
}
self.virtual_screen.clear(Color.light_gray);
self.virtual_screen.drawText(28, 2, Color.dark_purple, "<<LOAD GAME>>");
self.virtual_screen.drawText(0, 12, Color.white, "Chose your game file");
self.virtual_screen.drawText(0, 24, Color.white, "[ ] <empty>");
self.virtual_screen.drawText(0, 32, Color.white, "[ ] <empty>");
self.virtual_screen.drawText(0, 40, Color.white, "[ ] <empty>");
self.virtual_screen.drawText(8, 24 + 8 * call.selected_slot, Color.red, "X");
return .render;
},
.pause_dialog => |call| {
std.debug.assert(self.game != null);
if (self.joystick.menu.wasHit()) {
return self.closeDialog(&call.dialog);
}
self.virtual_screen.clear(Color.light_gray);
self.virtual_screen.drawText(6, 6, Color.white, "The game is paused");
self.virtual_screen.blitBuffer(48, 33, 24, std.mem.asBytes(&self.game.?.rom.icon));
return .render;
},
};
if (self.graphics_mode == .text and (loop_event == .render or loop_event == .yield)) {
self.virtual_terminal.render(
&self.virtual_screen,
@mod(std.time.milliTimestamp(), 1000) >= 500,
);
return .render;
}
return loop_event;
}
fn closeDialog(self: *Self, dialog: *Dialog) Event {
dialog.completed = true;
self.state = .default;
self.virtual_screen.pixels = dialog.screen_backup;
return .render;
}
pub fn deinit(self: *Self) void {
self.unloadGame();
self.allocator.destroy(self);
}
pub fn setJoystick(self: *Self, joy: JoystickState) void {
if (self.is_joystick_normalized) {
var joybuf = joy;
const len2 = joy.x * joy.x + joy.y * joy.y;
if (len2 > 1.0) {
const len = std.math.sqrt(len2);
joybuf.x /= len;
joybuf.y /= len;
}
self.joystick.update(joybuf);
} else {
self.joystick.update(joy);
}
}
fn resetScreen(self: *Self) void {
self.virtual_screen = Screen{};
}
const Canvas = painterz.Canvas(*Screen, u8, Screen.set);
fn canvas(self: *Self) Canvas {
return Canvas.init(&self.virtual_screen);
}
};
pub const GameROM = struct {
id: []const u8,
name: []const u8,
icon: [24][24]u8,
code: lola.CompileUnit,
data: std.StringHashMap([]const u8),
};
const Game = struct {
const Self = @This();
system: *System,
rom: *const GameROM,
pool: ObjectPool,
environment: lola.runtime.Environment,
vm: lola.runtime.VM,
fn init(game: *Self, system: *System, rom: *const GameROM) !void {
game.* = Self{
.system = system,
.rom = rom,
.pool = undefined,
.environment = undefined,
.vm = undefined,
};
game.pool = ObjectPool.init(system.allocator);
errdefer game.pool.deinit();
game.environment = try lola.runtime.Environment.init(system.allocator, &rom.code, game.pool.interface());
errdefer game.environment.deinit();
try lola.libs.std.install(&game.environment, system.allocator);
inline for (std.meta.declarations(api)) |decl| {
const function = @field(api, decl.name);
const Type = @TypeOf(function);
const lola_fn = if (Type == lola.runtime.UserFunctionCall)
lola.runtime.Function{
.syncUser = .{
.context = lola.runtime.Context.init(Game, game),
.call = function,
.destructor = null,
},
}
else if (Type == lola.runtime.AsyncUserFunctionCall)
lola.runtime.Function{
.asyncUser = .{
.context = lola.runtime.Context.init(Game, game),
.call = function,
.destructor = null,
},
}
else
lola.runtime.Function.wrapWithContext(
function,
game,
);
try game.environment.installFunction(decl.name, lola_fn);
}
game.vm = try lola.runtime.VM.init(system.allocator, &game.environment);
errdefer game.vm.deinit();
}
pub fn deinit(self: *Self) void {
self.vm.deinit();
self.environment.deinit();
self.pool.deinit();
self.* = undefined;
}
fn initDialog(self: *Self) Dialog {
self.system.joystick.resetEvents();
return Dialog{
.game = self,
.screen_backup = self.system.virtual_screen.pixels,
.completed = false,
};
}
const api = struct {
// System Control
fn Poweroff(game: *Game) error{PoweroffSignal} {
std.debug.assert(game.system.state == .default);
game.system.state = .shutdown;
return error.PoweroffSignal;
}
fn SaveGame(
environment: *lola.runtime.Environment,
call_context: lola.runtime.Context,
args: []const lola.runtime.Value,
) anyerror!lola.runtime.AsyncFunctionCall {
const game = call_context.get(Game);
if (args.len != 1)
return error.InvalidArgs;
const original_data = try args[0].toString();
const data = try game.system.allocator.dupe(u8, original_data);
errdefer game.system.allocator.free(data);
const call = try game.system.allocator.create(SaveGameCall);
errdefer game.system.allocator.destroy(call);
call.* = SaveGameCall{
.data = data,
.dialog = game.initDialog(),
};
game.system.state = System.State{
.save_dialog = call,
};
return lola.runtime.AsyncFunctionCall{
.context = lola.runtime.Context.init(SaveGameCall, call),
.execute = SaveGameCall.execute,
.destructor = SaveGameCall.destroy,
};
}
fn LoadGame(
environment: *lola.runtime.Environment,
call_context: lola.runtime.Context,
args: []const lola.runtime.Value,
) anyerror!lola.runtime.AsyncFunctionCall {
const game = call_context.get(Game);
if (args.len != 0)
return error.InvalidArgs;
const call = try game.system.allocator.create(LoadGameCall);
errdefer game.system.allocator.destroy(call);
call.* = LoadGameCall{
.dialog = game.initDialog(),
};
game.system.state = System.State{
.load_dialog = call,
};
return lola.runtime.AsyncFunctionCall{
.context = lola.runtime.Context.init(LoadGameCall, call),
.execute = LoadGameCall.execute,
.destructor = LoadGameCall.destroy,
};
}
fn Pause(
environment: *lola.runtime.Environment,
call_context: lola.runtime.Context,
args: []const lola.runtime.Value,
) anyerror!lola.runtime.AsyncFunctionCall {
const game = call_context.get(Game);
if (args.len != 0)
return error.InvalidArgs;
const call = try game.system.allocator.create(PauseGameCall);
errdefer game.system.allocator.destroy(call);
call.* = PauseGameCall{
.dialog = game.initDialog(),
};
game.system.state = System.State{
.pause_dialog = call,
};
return lola.runtime.AsyncFunctionCall{
.context = lola.runtime.Context.init(PauseGameCall, call),
.execute = PauseGameCall.execute,
.destructor = PauseGameCall.destroy,
};
}
// Resource Management
fn LoadData(game: *Game, path: []const u8) !?lola.runtime.String {
if (game.rom.data.get(path)) |data| {
return try lola.runtime.String.init(game.system.allocator, data);
} else {
return null;
}
}
// Text Mode
fn Print(
environment: *lola.runtime.Environment,
context: lola.runtime.Context,
args: []const lola.runtime.Value,
) anyerror!lola.runtime.Value {
const game = context.get(Game);
const output = game.system.virtual_terminal.writer();
for (args) |arg| {
if (arg == .string) {
try output.print("{s}", .{arg.toString() catch unreachable});
} else {
try output.print("{}", .{arg});
}
}
try output.writeAll("\r\n");
return .void;
}
fn Input(game: *Game, prompt: ?[]const u8) ?lola.runtime.String {
// TODO: Implement Input
return null;
}
fn TxtClear(game: *Game) void {
game.system.virtual_terminal.clear();
}
fn TxtSetBackground(game: *Game, color: ?u8) void {
game.system.virtual_terminal.bg_color = parsePixelValue(color);
}
fn TxtSetForeground(game: *Game, color: ?u8) void {
game.system.virtual_terminal.fg_color = parsePixelValue(color);
}
fn TxtWrite(
environment: *lola.runtime.Environment,
context: lola.runtime.Context,
args: []const lola.runtime.Value,
) anyerror!lola.runtime.Value {
const game = context.get(Game);
const output = game.system.virtual_terminal.writer();
for (args) |arg| {
if (arg == .string) {
try output.print("{s}", .{arg.toString() catch unreachable});
} else {
try output.print("{}", .{arg});
}
}
// TODO: Return number of chars written
return .void;
}
fn TxtRead(game: *Game) !lola.runtime.String {
@panic("TODO: Implement TxtRead!");
}
fn TxtReadLine(game: *Game) !?lola.runtime.String {
@panic("TODO: Implement TxtReadLine!");
}
fn TxtEnableCursor(game: *Game, enabled: bool) void {
game.system.virtual_terminal.cursor_visible = enabled;
}
fn TxtSetCursor(game: *Game, x: i32, y: i32) void {
if (x < 0 or x >= TextTerminal.width)
return;
if (y < 0 or y >= TextTerminal.height)
return;
game.system.virtual_terminal.cursor_position.x = @intCast(u5, x);
game.system.virtual_terminal.cursor_position.y = @intCast(u5, y);
}
fn TxtScroll(game: *Game, lines: u32) void {
game.system.virtual_terminal.scroll(lines);
}
// Graphics Mode
fn SetGraphicsMode(game: *Game, enabled: bool) void {
game.system.graphics_mode = if (enabled) .graphics else .text;
}
fn GpuSetPixel(game: *Game, x: i32, y: i32, color: ?u8) !void {
game.system.virtual_screen.set(x, y, color orelse 0xFF);
}
fn GpuGetPixel(game: *Game, x: i32, y: i32) !?u8 {
const color = game.system.virtual_screen.get(x, y);
if (color >= 16)
return null;
return color;
}
fn GpuGetFramebuffer(game: *Game) !lola.runtime.String {
return try lola.runtime.String.init(
game.system.allocator,
std.mem.sliceAsBytes(&game.system.virtual_screen.pixels),
);
}
fn GpuSetFramebuffer(game: *Game, buffer: []const u8) void {
var pixels = std.mem.sliceAsBytes(&game.system.virtual_screen.pixels);
std.mem.copy(
u8,
pixels[0..std.math.min(pixels.len, buffer.len)],
buffer[0..std.math.min(pixels.len, buffer.len)],
);
}
fn GpuBlitBuffer(game: *Game, dst_x: i32, dst_y: i32, width: u31, pixel_buffer: []const u8) void {
game.system.virtual_screen.blitBuffer(dst_x, dst_y, width, pixel_buffer);
}
fn GpuDrawLine(game: *Game, x0: i32, y0: i32, x1: i32, y1: i32, color: ?u8) void {
game.system.canvas().drawLine(x0, y0, x1, y1, color orelse 0xFF);
}
fn GpuDrawRect(game: *Game, x: i32, y: i32, w: u32, h: u32, color: ?u8) void {
game.system.canvas().drawRectangle(x, y, w, h, color orelse 0xFF);
}
fn GpuFillRect(game: *Game, x: i32, y: i32, w: u31, h: u31, color: ?u8) void {
game.system.canvas().fillRectangle(x, y, w, h, color orelse 0xFF);
}
fn GpuDrawText(game: *Game, x: i32, y: i32, color: ?u8, text: []const u8) void {
game.system.virtual_screen.drawText(x, y, color, text);
}
fn GpuScroll(game: *Game, dx: i32, dy: i32) void {
game.system.virtual_screen.scroll(dx, dy);
}
fn GpuSetBorder(game: *Game, color: ?u8) void {
game.system.virtual_screen.border_color = color orelse 0xFF;
}
fn GpuFlush(
environment: *lola.runtime.Environment,
call_context: lola.runtime.Context,
args: []const lola.runtime.Value,
) anyerror!lola.runtime.AsyncFunctionCall {
if (args.len != 0)
return error.TypeMismatch;
const Impl = struct {
fn execute(context: lola.runtime.Context) !?lola.runtime.Value {
const game = context.get(Game);
game.system.gpu_flush = true;
return .void;
}
};
return lola.runtime.AsyncFunctionCall{
.context = call_context,
.execute = Impl.execute,
.destructor = null,
};
}
fn GpuEnableAutoFlush(game: *Game, enabled: bool) void {
game.system.gpu_auto_flush = enabled;
}
// Keyboard
fn KbdIsDown(game: *Game, key: []const u8) bool {
@panic("implement");
}
fn KbdIsUp(game: *Game, key: []const u8) bool {
@panic("implement");
}
// Joystick
fn JoyEnableNormalization(game: *Game, enabled: bool) void {
game.system.is_joystick_normalized = enabled;
}
fn JoyGetX(game: *Game) f64 {
return game.system.joystick.x;
}
fn JoyGetY(game: *Game) f64 {
return game.system.joystick.y;
}
fn JoyGetA(game: *Game) bool {
return game.system.joystick.a.is_pressed;
}
fn JoyGetB(game: *Game) bool {
return game.system.joystick.b.is_pressed;
}
fn JoyGetGo(game: *Game) bool {
return game.system.joystick.go.is_pressed;
}
fn JoyGetMenu(game: *Game) bool {
return game.system.joystick.menu.is_pressed;
}
fn JoyHitA(game: *Game) bool {
return game.system.joystick.a.wasHit();
}
fn JoyHitB(game: *Game) bool {
return game.system.joystick.b.wasHit();
}
fn JoyHitGo(game: *Game) bool {
return game.system.joystick.go.wasHit();
}
fn JoyHitMenu(game: *Game) bool {
return game.system.joystick.menu.wasHit();
}
fn JoyReleaseA(game: *Game) bool {
return game.system.joystick.a.wasReleased();
}
fn JoyReleaseB(game: *Game) bool {
return game.system.joystick.b.wasReleased();
}
fn JoyReleaseGo(game: *Game) bool {
return game.system.joystick.go.wasReleased();
}
fn JoyReleaseMenu(game: *Game) bool {
return game.system.joystick.menu.wasReleased();
}
};
};
const Dialog = struct {
game: *Game,
screen_backup: [Screen.height][Screen.width]u8,
completed: bool,
};
const SaveGameCall = struct {
const Self = @This();
dialog: Dialog,
data: []const u8,
result: ?bool = null,
selected_slot: u8 = 0,
fn execute(context: lola.runtime.Context) !?lola.runtime.Value {
const self = context.get(Self);
if (self.dialog.completed)
return lola.runtime.Value.initBoolean(self.result orelse @panic("call.result wasn't set before calling closeDialog!"));
return null;
}
fn destroy(context: lola.runtime.Context) void {
const self = context.get(Self);
self.dialog.game.system.allocator.free(self.data);
self.dialog.game.system.allocator.destroy(self);
}
};
const LoadGameCall = struct {
const Self = @This();
dialog: Dialog,
data: ?[]const u8 = null,
selected_slot: u8 = 0,
fn execute(context: lola.runtime.Context) !?lola.runtime.Value {
const self = context.get(Self);
if (self.dialog.completed) {
if (self.data) |data| {
return try lola.runtime.Value.initString(self.dialog.game.system.allocator, data);
}
return .void;
}
return null;
}
fn destroy(context: lola.runtime.Context) void {
const self = context.get(Self);
if (self.data) |data|
self.dialog.game.system.allocator.free(data);
self.dialog.game.system.allocator.destroy(self);
}
};
const PauseGameCall = struct {
const Self = @This();
dialog: Dialog,
fn execute(context: lola.runtime.Context) !?lola.runtime.Value {
const self = context.get(Self);
if (self.dialog.completed) {
return .void;
} else {
return null;
}
}
fn destroy(context: lola.runtime.Context) void {
const self = context.get(Self);
self.dialog.game.system.allocator.destroy(self);
}
};
|
0 | repos/Ziguana-Game-System/src | repos/Ziguana-Game-System/src/tools/mkbitmap.cs | using System;
using System.Drawing;
using System.IO;
class Program
{
const int tile_size = 8;
static int Main(string[] args)
{
int margin = 1;
int padding = 1;
var result = new byte[256 * tile_size];
using (var bmp = new Bitmap(args[0]))
{
if (bmp.Width != 16 * tile_size + 2 * margin + 15 * padding)
return Error("Invalid image width: {0}", bmp.Width);
if (bmp.Height != 16 * tile_size + 2 * margin + 15 * padding)
return Error("Invalid image height: {0}", bmp.Height);
var chroma_key = bmp.GetPixel(margin, margin);
for (int c = 0; c < 256; c++)
{
int rx = margin + (tile_size + padding) * (c % 16);
int ry = margin + (tile_size + padding) * (c / 16);
int offset = tile_size * c;
for (int y = 0; y < tile_size; y++)
{
result[offset + y] = 0x00;
for (int x = 0; x < tile_size; x++)
{
if (bmp.GetPixel(rx + x, ry + y) != chroma_key)
result[offset + y] += (byte)(1 << x);
}
}
}
File.WriteAllBytes(args[1], result);
}
return 0;
}
static int Error(string text)
{
Console.Error.WriteLine(text);
return 1;
}
static int Error(string text, params object[] args)
{
Console.Error.WriteLine(text, args);
return 1;
}
} |
0 | repos/Ziguana-Game-System | repos/Ziguana-Game-System/documentation/project-structure.md | # ZPAK Game ROM
This file is a [GNU TAR](https://www.gnu.org/software/tar/manual/html_node/Standard.html) file which contains all relevant parts of a game.
The file follows this rough structure:
```
.
├── game.lm
├── game.ico
├── game.name
├── game.id
└── data/
├── some_file.dat
└── other_file.icon
```
- `game.lm` is the game source code, a LoLa compile unit.
- `game.ico` is a 24×24 pixel icon file, encoded in the usual [bitmap format](bitmap-format.md). If this file is not given, a default icon is shown.
- `game.name` is a file containing the display name of the game which will be shown in the game discovery.
- `game.id` is a unique game identifier. This follows the java package conventions and is the creators domain backwards. If this file is not given, the user is not able to save/load files. Example: `net.random-projects.zgs.example`
- `data/` is a folder containing embedded resources of the game. These files can be load with the `LoadData()` API.
|
0 | repos/Ziguana-Game-System | repos/Ziguana-Game-System/documentation/bitmap-format.md | # ZGS Bitmap Format
The bitmap format is pretty simple:
Each pixel is encoded by a single byte, pixels are encoded either in binary (value `0`…`15`) or as hexadecimal characters (`'0'`…`'9'`, `'a'`…`'f'`, `'A'`…`'F'`). Values outside this range will be considered *broken* and are either displayed as a flimmering pixel or will be considered transparent.
Pixels are encoded row-major, so pixels will be in order left-to-right, then top-to-bottom.
Example for a 8×8 texture encoding a two-colored 'A' character:
```
..0000..
.0....1.
.0....1.
.000111.
.0....1.
.0....1.
.1....1.
........
```
(note that the LF displayed here is only for visualization and should not be included in the final file)
The size of the bitmaps is not encoded in the file format itself. |
0 | repos/Ziguana-Game-System | repos/Ziguana-Game-System/documentation/api-design.md | # Ziguana Game System API
## System Control
### `Poweroff() noreturn`
Will shut down the console and exit.
### `SaveGame(data: string) bool`
Opens a prompt for the user to save the game. The user can then select one of three save games to save the game or cancel the saving process.
Returns `true` when the game was successfully saved, otherwise `false`.
### `LoadGame() string|void`
Opens a prompt for the user to load a previously saved game. The user can then select one of the save games or cancel the loading.
When the user selected a save game, the data is returned as a `string`, if the user cancelled the saving, `void` is returned.
### `Pause() void`
Opens the pause screen of the console. The user can then decide to resume the game at any time.
## Resource Management
### `LoadData(path: string) string|void`
Will load a resource located at `"data/" + path`
## Text Mode
This is the default mode of the system. It displays a primitive text terminal with 20×15 characters of size and a small 8×8 pixel font.
### `Print(…): void`
Prints all arguments followed by a new line.
### `Input(prompt: string|void) string|void`
Asks the user for a value accepted by _Return_ or cancelled by _Escape_. If _Return_ is pressed, the user accepted the input and a string is returned, if _Escape_ was pressed, the user cancelled the input and `void` is returned.
The function will go into a new line if not already and will print `prompt` if given. If not, `? ` is printed as a prompt.
### `TxtClear(): void`
Clears the screen and resets the cursor to the top-left.
### `TxtSetBackground(color: number) void`
Sets the background color of the screen. The color parameter is explained in [Graphics Mode](#Graphics_Mode).
### `TxtSetForeground(color: number) void`
Sets the text color. All new text is written in that color. The color parameter is explained in [Graphics Mode](#Graphics_Mode).
### `TxtWrite(…): number`
Writes the arguments to the text console and returns the number of characters written.
### `TxtRead(): string`
Reads all available text from the keyboard buffer. Returns `""` when nothing is in the buffer.
### `TxtReadLine(): string|void`
Reads a line of text entered by the user. As soon as the user presses _Return_, the text is returned. If `""` is returned, the user pressed _Return_, but didn't enter text. If `void` is returned, the user cancelled the input by pressing _Escape_.
### `TxtEnableCursor(enabled: bool) void`
Enables or disables the text cursor. The text cursor will always be one digit behind the last printed character and will blink.
### `TxtSetCursor(x: number, y: number) void`
Moves the cursor on the screen. New text will be inserted at the cursor position, even if the cursor is not visible.
### `TxtScroll(lines: number) void`
Scrolls the text screen by the given number of lines.
## Graphics Mode
The system also provides a bitmap mode with a resolution of 160×120 pixels and 4 bit color depth and a fixed palette.
Pixels are encoded as bytes in a string, where each byte encodes a color between 0 and 15. If the byte value is larger than 15, the pixel is considered _broken_ and will display a randomly changing color from the palette.
### `SetGraphicsMode(enabled: bool) void`
If `enabled == true`, the system will enable graphics mode, otherwise it will enable text mode.
### `GpuSetPixel(x: number, y: number, color: number|void) void`
Sets the pixel at (`x`, `y`) to `c` where `c` is a number between `0` and `15` or `void` for a broken pixel.
### `GpuGetPixel(x: number, y: number) number|void`
Returns the color index of a pixel at (`x`, `y`) or `void` if the pixel is broken.
### `GpuGetFramebuffer(): string`
Returns a string of length 19200 where each byte corresponds to a pixel on the screen. Valid pixels are encoded as values `0` … `15`, broken pixels are encoded as `255`.
### `GpuSetFramebuffer(fb: string) void`
Sets the frame buffer to the given string. Each byte is considered a pixel value. Excess bytes (more than 19200) are cut off, missing bytes (less than 19200) are filled with _broken_ pixels. Each byte may have a integer value between `0` and `15` or be a valid hexadecimal digit (`'0'`…`'9'`, `'a'`…`'f'`, `'A'`…`'F'`), all other values are considered _broken_.
### `GpuBlitBuffer(x: number, y: number, width: number, data: string) void`
Copies pixels from `data` onto the screen. The rules for the pixel format are the same as in `GpuSetFramebuffer`, except that _broken_ pixels are ignored and will not be blitted into the framebuffer.
Pixels are copied starting at point (`x`, `y`), where both coordinates may be negative. Pixels are then copied to the right for `width` pixels, then advance one row and continue copying. Pixels that are out-of-screen are discarded, no wrap-around is performed.
This routine allows simple sprite or tile graphics to be done.
### `GpuDrawLine(x0, y0, x1, y1, c)`
Draws a Line from (`x0`, `y0`) to (`x1`, `y1`) with color `c`.
### `GpuDrawRect(x, y, w, h, c)`s
Draws the rectangle outline between the points (`x`, `y`) and (`x+w-1`,`y+h-1`) with color `c`.
### `GpuFillRect(x, y, w, h, c)`
Fills the rectangle between the points (`x`, `y`) and (`x+w-1`,`y+h-1`) with color `c`.
### `GpuDrawText(x: number, y: number, color: number, text: string) void`
Draws a string `text ` starting at (`x`, `y`). The font size is 6×6 pixels, which gives a maximum text density of 20×15 characters.
### `GpuScroll(dx, dy)`
Scrolls the screen content by the given amount into x and y direction. Contents that get shifted out of the screen will be shifted in on the opposite site again. This rolls the screen content.
This is helpful for scrolling backgrounds and similar.
### `GpuSetBorder(color: number) void`
Sets the background color of the border around the screen.
### `GpuFlush() void`
Will flush the current framebuffer to the screen and wait for vsync.
### `GpuEnableAutoFlush(enabled: bool) void`
If `enabled` is true, the graphics functions will always draw directly to the screen and when vsync comes, the result will be presented.
## Keyboard
### Key Map
> To be done
### `KbdIsDown(key: string) bool`
Returns `true` when the `key` is pressed.
### `KbdIsUp(key: string) bool`
Returns `true` when the `key` is not pressed.
## Joystick
Input API for a connected joystick. The joystick has a analogue stick and two buttons _A_ and _B_.
### `JoyEnableNormalization(enabled: bool) void`
If `enabled` is true, the values returned by `JoyGetX` and `JoyGetY` will always have a euclidean length of `<= 1.0`. Otherwise, the axis will be separated and both have the full range.
### `JoyGetX(): number`
Returns a value between `-1.0` and `1.0` that reflects the horizontal position of the joystick. Negative values go left, positive values go right.
### `JoyGetY(): number`
Returns a value between `-1.0` and `1.0` that reflects the vertical position of the joystick. Negative values are upwards, positive values go downwards.
### `JoyGet{A,B,Go,Menu}(): bool`
Returns `true` when the {_A_,_B_,_Go_,_Menu_} button is pressed.
### `JoyHit{A,B,Go,Menu}(): bool`
Returns `true` when the {_A_,_B_,_Go_,_Menu_} button was pressed since the last call to this function.
### `JoyRelease{A,B,Go,Menu}(): bool`
Returns `true` when the {_A_,_B_,_Go_,_Menu_} button was released since the last call to this function.
## Audio System
### `PlaySound(name: string, volume: number) void`
Plays a sound called `name` with the given `volume` (between `0.0` and `1.0`).
### `LoopSound(name: string, volume: number) object`
Plays a sound in a loop and returns a handle to the playing sound. The loop can be controlled via this handle:
#### `SoundHandle.Stop() void`
Will stop the loop from playing and will make the sound handle invalid (destroys the object).
#### `SoundHandle.Pause() void`
Will stop the loop from playing at the current position.
#### `SoundHandle.Resume() void`
Lets a paused loop continue to play
#### `SoundHandle.SetVolume(volume: number) void`
Will change the volume of the loop.
### `PlayMusic(music: string, fade_time: number) void`
Starts playing the track `music`, stopping all previously played music.
The tracks will smoothly fade one into the other over `fade_time` seconds. If `fade_time` is not given, 0.5 seconds will be used to fade the tracks.
|
0 | repos/Ziguana-Game-System | repos/Ziguana-Game-System/old-version/README.md | # Ziguana Game System
A project that aims to create a fake/virtual console similar
to the PICO-8, LIKO-12 or TIC-80.
## Concept
- The user can program the console via builtin tools
- Projects/Games can be saved/loaded
- A project can be up to 1440 KiB large
- Projects can be saved/loaded to/from an extern floppy disk
- Projects can be stored on an ATA hard disk
- Uses partition tables!
- Uses "slots": Every slot contains a full floppy disk image
- User can program its projects via [GASM](#GASM) language
## Specifications
- Screen: 320×200 pixels, 256 colors, choosable palette
- Audio: *to be defined...*
- RAM: 16 MB
- "Cartridges": Floppy Disks, 1440K
- Input: Keyboard & mouse
## Minimum Hardware Requirements
To run this on *real* hardware, you need to meet the following
hardware requirements:
- VGA compatible graphics card (so: pretty much *any* card will work)
- At least 20 MB of RAM
- i486 compatible CPU (at least in theory, was tested on a Pentium III)
- PS/2 compatible keyboard
- Floppy disk drive
## GASM
The *Game Assembly* language is a fake assembly language that
behaves similar to x86 asm. It supports not only generic
instructions to manipulate memory, but also has special
instructions for the fake console to make programming games
easier.
```asm
init:
mov r0, 0
mov [running], 1
Loops r0 until it is 200
.loop:
cmp r0, 200
jiz stop
add r0, 1
cmp counter
jmp .loop
stop:
mov [running], 0
jmp stop
running:
.dw 0
```
### Syntax and Semantics
Register Names (32 bit):
- `r0` … `r15`
#### Flags
- `C`: Carry, set when an instruction overflows
- `Z`: Zero, set when an instruction results in zero.
#### Operand Format
- `r0` … `r15` are register names
- decimal or hexadecimal numbers are used as literals
- label names can be used instead of literals for the address of the label
- `[…]` is an indirection and stores/loads from the memory address `…` instead of using `…` as an immediate value. `…` can be any other non-indirect operand.
- `[…+n]` is an indirection similar to `[…]`, but it will offset the address in … by n bytes.
#### Instructions:
Note: `*x` means that `x` may be modified.
| Instruction | Description |
|-----------------|-------------|
| `mov *dst, src` | copies src to dst |
| `add *dst, val` | adds val to dst |
| `sub *dst, val` | subtracts val from dst |
| `cmp a, b` | compares a to b and stores result in | flags. Z is set when a==b, C is set when a < b |
| `jmp dst` | jumps execution to address dst |
| `jnz dst` | jumps execution to address dst when Z is set |
| `jlz dst` | jumps execution to address dst when C is set |
| `jgz dst` | jumps execution to address dst when both Z and C are not set |
| `jiz dst` | jumps execution to address dst when Z is not set |
| `shl *dst, cnt` | shifts dst cnt bits to the left |
| `shr *dst, cnt` | shifts dst cnt bits to the right |
| `gettime *dst` | stores the current system time in ms into dst |
| `setpix x,y,c` | sets pixel (x,y) to color c |
| `getpix *c,x,y` | gets pixel (x,y) into c |
#### Directives
| Syntax | Description |
|--------|-------------|
| `.def NAME, value` | creates new constant `NAME` that will be replaced with `value` from this line on. `value` can be any number, identifier or register name. |
| `.undef NAME` | removes a previously defined constant. |
| `.dw a,…` | stores literal 32bit word a, … at the current position |
| `.align v` | aligns the current position with v bytes |
#### Labels
- `name:` defines a global label "name"
- `.name:` defines a local label "name" that can only be used/references between to global labels.
## Screenshots
**Rendering text in VGA 256 color mode:**

**Playing a nice game of snake:**

## Building
Install the latest [zig](https://ziglang.org/) master build (at least 0.6.0+d07383689) and run
```sh
# This compile the project
zig build
# This will run qemu with the system (you need qemu installed ^^)
zig build run
``` |
0 | repos/Ziguana-Game-System | repos/Ziguana-Game-System/old-version/build.zig | const std = @import("std");
const builtin = @import("builtin");
const Builder = @import("std").build.Builder;
const lola_cfg = @import("./libs/lola/build.zig");
pub fn build(b: *Builder) void {
const mode = b.standardReleaseOptions();
const kernel = b.addExecutable("kernel", "kernel/src/main.zig");
kernel.setBuildMode(mode);
kernel.setLinkerScriptPath("kernel/src/linker.ld");
kernel.setTarget(std.zig.CrossTarget{
.cpu_arch = .i386,
.cpu_model = .{
.explicit = &std.Target.x86.cpu._i386,
},
// workaround for LLVM bugs :(
// without cmov, the code won't compile
.cpu_features_add = blk: {
var features = std.Target.Cpu.Feature.Set.empty;
features.addFeature(@enumToInt(std.Target.x86.Feature.cmov));
break :blk features;
},
.os_tag = .freestanding,
.abi = .eabi,
});
kernel.addPackage(lola_cfg.createPackage("libs/lola"));
kernel.install();
kernel.single_threaded = true;
const verbose_debug = b.option(bool, "verbose-qemu", "Enable verbose debug output for QEMU") orelse false;
const qemu_debug_mode: []const u8 = if (verbose_debug)
"guest_errors,int,cpu_reset"
else
"guest_errors,cpu_reset";
const run_qemu = b.addSystemCommand(&[_][]const u8{
"qemu-system-i386",
"-no-shutdown", // don't shutdown the VM on halt
"-no-reboot", // don't reset the machine on errors
"-serial",
"stdio", // using the stdout as our serial console
"-device",
"sb16", // add soundblaster 16
"-device",
"ac97", // add ac97
"-device",
"intel-hda",
"-device",
"hda-duplex", // add intel HD audio
"-m",
"64M", // 64 MB RAM
"-d",
qemu_debug_mode, // debug output will yield all interrupts and resets
// "-drive",
// "format=raw,if=ide,file=kernel/boot.img",
// "-drive",
// "format=raw,if=floppy,file=kernel/cartridge.img", // attach floppy cartridge
});
{ // don't use the system image, boot the kernel directly
run_qemu.addArg("-kernel");
run_qemu.addArtifactArg(kernel);
}
const run_step = b.step("run", "Runs qemu with emulation");
run_step.dependOn(&run_qemu.step);
}
|
0 | repos/Ziguana-Game-System/old-version | repos/Ziguana-Game-System/old-version/data/kbd_ger_std.txt | # Scancodes for german layout
# Scancode Enum (lower)ASCII (upper)ASCII
1 Escape \1B
2 One 1 !
3 Two 2 " ²
4 Three 3 § ³
5 Four 4 $
6 Five 5 %
7 Six 6 &
8 Seven 7 / {
9 Eight 8 ( [
10 Nine 9 ) ]
11 Zero 0 = }
12 SZ ß ? \
13 Tick ´ `
14 Backspace \08
15 Tabulator \09
16 Q q Q @
17 W w W
18 E e E €
19 R r R
20 T t T
21 Z z Z
22 U u U
23 I i I
24 O o O
25 P p P
26 UmlU ü Ü
27 Plus + * ~
28 Enter \0A
29 LeftControl
30 A a A
31 S s S
32 D d D
33 F f F
34 G g G
35 H h H
36 J j J
37 K k K
38 L l L
39 UmlO ö Ö
40 UmlA ä Ä
41 Circumflex ^ °
42 LeftShift
43 Hash # '
44 Y y Y
45 X x X
46 C c C
47 V v V
48 B b B
49 N n N
50 M m M µ
51 Comma , ;
52 Dot . :
53 Minus - _
# 54
55 NumpadMul * *
56 LeftAlt
# WARNING: THIS IS SPACE CHARACTER!
57 Space
# WARNING: END OF SPACE CHARACTER!
58 CapsLock
59 F1
60 F2
61 F3
62 F4
63 F5
64 F6
65 F7
66 F8
67 F9
68 F10
69 NumpadLock
71 Numpad7 7 7
72 Numpad8 8 8
73 Numpad9 9 9
74 NumpadMinus - -
75 Numpad4 4 4
76 Numpad5 5 5
77 Numpad6 6 6
78 NumpadPlus + +
79 Numpad1 1 1
80 Numpad2 2 2
81 Numpad3 3 3
82 Numpad0 0 0
83 NumpadDot . .
86 < > |
87 F11
88 F12
|
0 | repos/Ziguana-Game-System/old-version/kernel | repos/Ziguana-Game-System/old-version/kernel/aux/mkbitmap.cs | using System;
using System.IO;
using System.Drawing;
class Program
{
static int Main(string[] args)
{
using(var fs = File.Open(args[1], FileMode.Create, FileAccess.Write))
{
using(var bmp = new Bitmap(args[0]))
{
fs.Write(BitConverter.GetBytes(bmp.Width), 0, 4);
fs.Write(BitConverter.GetBytes(bmp.Height), 0, 4);
var stride = (bmp.Width + 7) / 8;
for(int y = 0; y < bmp.Height; y++)
{
var line = new byte[stride];
for(int x = 0; x < bmp.Width; x++)
{
if(bmp.GetPixel(x, y).R == 0xFF)
line[x / 8] |= (byte)(1<<(x%8));
}
fs.Write(line, 0, line.Length);
}
}
}
return 0;
}
}
|
0 | repos/Ziguana-Game-System/old-version/kernel | repos/Ziguana-Game-System/old-version/kernel/aux/fontconv.cs | using System;
using System.IO;
using System.Drawing;
class Program
{
static int Main(string[] args)
{
using(var fs = File.Open(args[1], FileMode.Create, FileAccess.Write))
{
using(var bmp = new Bitmap(args[0]))
{
for(int i = 0; i < 128; i++)
{
var pixels = new byte[8];
int sx = 6 * (i % 16);
int sy = 8 * (i / 16);
for(int y = 0; y < 8; y++)
{
byte b = 0;
for(int x = 0; x < 6; x++)
{
if(bmp.GetPixel(sx + x, sy + y).R == 0xFF)
b |= (byte)(1<<x);
}
pixels[y] = b;
}
fs.Write(pixels, 0, 8);
}
}
}
return 0;
}
}
|
0 | repos/Ziguana-Game-System/old-version/kernel | repos/Ziguana-Game-System/old-version/kernel/aux/mkkeymap.cs | using System;
using System.IO;
using System.Text;
class Program
{
static byte KeyToByte(string val)
{
if(val.Length > 1 && val[0] == '\\') {
return Convert.ToByte(val.Substring(1), 16);
}
var x = Encoding.ASCII.GetBytes(val);
if(x.Length != 1)
throw new InvalidOperationException(val);
return x[0];
}
static int Main(string[] args)
{
var keymap = new byte[4 * 128];
using(var sr = new StreamReader(args[0], Encoding.UTF8))
{
while(!sr.EndOfStream)
{
var line = sr.ReadLine();
if(line.StartsWith("#"))
continue;
if(line.Length == 0)
continue;
var parts = line.Split('\t');
if(parts.Length < 2 || parts.Length > 5)
throw new InvalidOperationException("Kaputt: " + line);
if(parts.Length > 2)
{
var index = int.Parse(parts[0]);
var lower = parts[2];
var upper = (parts.Length >= 4) ? parts[3] : lower;
var graph = (parts.Length >= 5) ? parts[4] : lower;
keymap[4 * index + 1] = KeyToByte(lower);
keymap[4 * index + 2] = KeyToByte(upper);
keymap[4 * index + 3] = KeyToByte(graph);
}
}
}
using(var fs = File.Open(args[1], FileMode.Create, FileAccess.Write))
{
fs.Write(keymap, 0, keymap.Length);
}
return 0;
}
}
|
0 | repos/Ziguana-Game-System/old-version/kernel | repos/Ziguana-Game-System/old-version/kernel/aux/stacktrace_to_line.sh | #!/bin/bash
while IFS= read -r line
do
printf '%s\n' "$line"
if echo $line | grep -q 'Stack:'; then
addr2line -e zig-cache/bin/kernel $(echo $line | cut -d ':' -f 2)
fi
done < "${1:-/dev/stdin}"
|
0 | repos/Ziguana-Game-System/old-version/kernel | repos/Ziguana-Game-System/old-version/kernel/src/interrupts.zig | const std = @import("std");
const io = @import("io.zig");
const Terminal = @import("text-terminal.zig");
pub const InterruptHandler = fn (*CpuState) *CpuState;
var irqHandlers = [_]?InterruptHandler{null} ** 32;
pub fn setIRQHandler(irq: u4, handler: ?InterruptHandler) void {
irqHandlers[irq] = handler;
}
export fn handle_interrupt(_cpu: *CpuState) *CpuState {
const Root = @import("root");
var cpu = _cpu;
switch (cpu.interrupt) {
0x00...0x1F => {
// Exception
Terminal.setColors(.white, .magenta);
Terminal.println("Unhandled exception: {}\r\n", .{@as([]const u8, switch (cpu.interrupt) {
0x00 => "Divide By Zero",
0x01 => "Debug",
0x02 => "Non Maskable Interrupt",
0x03 => "Breakpoint",
0x04 => "Overflow",
0x05 => "Bound Range",
0x06 => "Invalid Opcode",
0x07 => "Device Not Available",
0x08 => "Double Fault",
0x09 => "Coprocessor Segment Overrun",
0x0A => "Invalid TSS",
0x0B => "Segment not Present",
0x0C => "Stack Fault",
0x0D => "General Protection Fault",
0x0E => "Page Fault",
0x0F => "Reserved",
0x10 => "x87 Floating Point",
0x11 => "Alignment Check",
0x12 => "Machine Check",
0x13 => "SIMD Floating Point",
0x14...0x1D => "Reserved",
0x1E => "Security-sensitive event in Host",
0x1F => "Reserved",
else => "Unknown",
})});
Terminal.println("{}", .{cpu});
if (cpu.interrupt == 0x0E) {
const cr2 = asm volatile ("mov %%cr2, %[cr]"
: [cr] "=r" (-> usize)
);
const cr3 = asm volatile ("mov %%cr3, %[cr]"
: [cr] "=r" (-> usize)
);
Terminal.println("Page Fault when {1} address 0x{0X} from {3}: {2}", .{
cr2,
if ((cpu.errorcode & 2) != 0) @as([]const u8, "writing") else @as([]const u8, "reading"),
if ((cpu.errorcode & 1) != 0) @as([]const u8, "access denied") else @as([]const u8, "page unmapped"),
if ((cpu.errorcode & 4) != 0) @as([]const u8, "userspace") else @as([]const u8, "kernelspace"),
});
}
if (@import("root").currentAssemblerLine) |line| {
Terminal.println("Assembler Line: {}", .{line});
}
Terminal.resetColors();
while (true) {
asm volatile (
\\ cli
\\ hlt
);
}
},
0x20...0x2F => {
// IRQ
if (irqHandlers[cpu.interrupt - 0x20]) |handler| {
cpu = handler(cpu);
} else {
Terminal.println("Unhandled IRQ{}:\r\n{}", .{ cpu.interrupt - 0x20, cpu });
}
if (cpu.interrupt >= 0x28) {
io.out(u8, 0xA0, 0x20); // ACK slave PIC
}
io.out(u8, 0x20, 0x20); // ACK master PIC
},
0x30 => {
// assembler debug call
Root.debugCall(cpu);
},
0x40 => return Root.switchTask(.shell),
0x41 => return Root.switchTask(.codeEditor),
0x42 => return Root.switchTask(.spriteEditor),
0x43 => return Root.switchTask(.tilemapEditor),
0x44 => return Root.switchTask(.codeRunner),
0x45 => return Root.switchTask(.splash),
else => {
Terminal.println("Unhandled interrupt:\r\n{}", .{cpu});
while (true) {
asm volatile (
\\ cli
\\ hlt
);
}
},
}
return cpu;
}
export var idt: [256]Descriptor align(16) = undefined;
pub fn init() void {
comptime var i: usize = 0;
inline while (i < idt.len) : (i += 1) {
idt[i] = Descriptor.init(getInterruptStub(i), 0x08, .interruptGate, .bits32, 0, true);
}
asm volatile ("lidt idtp");
// Master-PIC initialisieren
io.out(u8, 0x20, 0x11); // Initialisierungsbefehl fuer den PIC
io.out(u8, 0x21, 0x20); // Interruptnummer fuer IRQ 0
io.out(u8, 0x21, 0x04); // An IRQ 2 haengt der Slave
io.out(u8, 0x21, 0x01); // ICW 4
// Slave-PIC initialisieren
io.out(u8, 0xa0, 0x11); // Initialisierungsbefehl fuer den PIC
io.out(u8, 0xa1, 0x28); // Interruptnummer fuer IRQ 8
io.out(u8, 0xa1, 0x02); // An IRQ 2 haengt der Slave
io.out(u8, 0xa1, 0x01); // ICW 4
}
pub fn fireInterrupt(comptime intr: u32) void {
asm volatile ("int %[i]"
:
: [i] "n" (intr)
);
}
pub fn enableIRQ(irqNum: u4) void {
switch (irqNum) {
0...7 => {
io.out(u8, 0x21, io.in(u8, 0x21) & ~(@as(u8, 1) << @intCast(u3, irqNum)));
},
8...15 => {
io.out(u8, 0x21, io.in(u8, 0x21) & ~(@as(u8, 1) << @intCast(u3, irqNum - 8)));
},
}
}
pub fn disableIRQ(irqNum: u4) void {
switch (irqNum) {
0...7 => {
io.out(u8, 0x21, io.in(u8, 0x21) | (@as(u8, 1) << @intCast(u3, irqNum)));
},
8...15 => {
io.out(u8, 0x21, io.in(u8, 0x21) | (@as(u8, 1) << @intCast(u3, irqNum - 8)));
},
}
}
pub fn enableAllIRQs() void {
// Alle IRQs aktivieren (demaskieren)
io.out(u8, 0x21, 0x0);
io.out(u8, 0xa1, 0x0);
}
pub fn disableAllIRQs() void {
// Alle IRQs aktivieren (demaskieren)
io.out(u8, 0x21, 0xFF);
io.out(u8, 0xa1, 0xFF);
}
pub fn enableExternalInterrupts() void {
asm volatile ("sti");
}
pub fn disableExternalInterrupts() void {
asm volatile ("cli");
}
pub const CpuState = packed struct {
// Von Hand gesicherte Register
eax: u32,
ebx: u32,
ecx: u32,
edx: u32,
esi: u32,
edi: u32,
ebp: u32,
interrupt: u32,
errorcode: u32,
// Von der CPU gesichert
eip: u32,
cs: u32,
eflags: u32,
esp: u32,
ss: u32,
pub fn format(cpu: CpuState, comptime fmt: []const u8, options: std.fmt.FormatOptions, writer: anytype) !void {
try writer.print(" EAX={X:0>8} EBX={X:0>8} ECX={X:0>8} EDX={X:0>8}\r\n", .{ cpu.eax, cpu.ebx, cpu.ecx, cpu.edx });
try writer.print(" ESI={X:0>8} EDI={X:0>8} EBP={X:0>8} EIP={X:0>8}\r\n", .{ cpu.esi, cpu.edi, cpu.ebp, cpu.eip });
try writer.print(" INT={X:0>2} ERR={X:0>8} CS={X:0>8} FLG={X:0>8}\r\n", .{ cpu.interrupt, cpu.errorcode, cpu.cs, cpu.eflags });
try writer.print(" ESP={X:0>8} SS={X:0>8}\r\n", .{ cpu.esp, cpu.ss });
}
};
const InterruptType = enum(u3) {
interruptGate = 0b110,
trapGate = 0b111,
taskGate = 0b101,
};
const InterruptBits = enum(u1) {
bits32 = 1,
bits16 = 0,
};
const Descriptor = packed struct {
offset0: u16, // 0-15 Offset 0-15 Gibt das Offset des ISR innerhalb des Segments an. Wenn der entsprechende Interrupt auftritt, wird eip auf diesen Wert gesetzt.
selector: u16, // 16-31 Selector Gibt den Selector des Codesegments an, in das beim Auftreten des Interrupts gewechselt werden soll. Im Allgemeinen ist dies das Kernel-Codesegment (Ring 0).
ist: u3 = 0, // 32-34 000 / IST Gibt im LM den Index in die IST an, ansonsten 0!
_0: u5 = 0, // 35-39 Reserviert Wird ignoriert
type: InterruptType, // 40-42 Typ Gibt die Art des Interrupts an
bits: InterruptBits, // 43 D Gibt an, ob es sich um ein 32bit- (1) oder um ein 16bit-Segment (0) handelt.
// Im LM: Für 64-Bit LDT 0, ansonsten 1
_1: u1 = 0, // 44 0
privilege: u2, // 45-46 DPL Gibt das Descriptor Privilege Level an, das man braucht um diesen Interrupt aufrufen zu dürfen.
enabled: bool, // 47 P Gibt an, ob dieser Eintrag benutzt wird.
offset1: u16, // 48-63 Offset 16-31
pub fn init(offset: ?fn () callconv(.Naked) void, selector: u16, _type: InterruptType, bits: InterruptBits, privilege: u2, enabled: bool) Descriptor {
const offset_val = @ptrToInt(offset);
return Descriptor{
.offset0 = @truncate(u16, offset_val & 0xFFFF),
.offset1 = @truncate(u16, (offset_val >> 16) & 0xFFFF),
.selector = selector,
.type = _type,
.bits = bits,
.privilege = privilege,
.enabled = enabled,
};
}
};
comptime {
std.debug.assert(@sizeOf(Descriptor) == 8);
}
const InterruptTable = packed struct {
limit: u16,
table: [*]Descriptor,
};
export const idtp = InterruptTable{
.table = &idt,
.limit = @sizeOf(@TypeOf(idt)) - 1,
};
export fn common_isr_handler() callconv(.Naked) void {
asm volatile (
\\ push %%ebp
\\ push %%edi
\\ push %%esi
\\ push %%edx
\\ push %%ecx
\\ push %%ebx
\\ push %%eax
\\
\\ // Handler aufrufen
\\ push %%esp
\\ call handle_interrupt
\\ mov %%eax, %%esp
\\
\\ // CPU-Zustand wiederherstellen
\\ pop %%eax
\\ pop %%ebx
\\ pop %%ecx
\\ pop %%edx
\\ pop %%esi
\\ pop %%edi
\\ pop %%ebp
\\
\\ // Fehlercode und Interruptnummer vom Stack nehmen
\\ add $8, %%esp
\\
\\ // Ruecksprung zum unterbrochenen Code
\\ iret
);
}
fn getInterruptStub(comptime i: u32) fn () callconv(.Naked) void {
const Wrapper = struct {
fn stub_with_zero() callconv(.Naked) void {
asm volatile (
\\ pushl $0
\\ pushl %[nr]
\\ jmp common_isr_handler
:
: [nr] "n" (i)
);
}
fn stub_with_errorcode() callconv(.Naked) void {
asm volatile (
\\ pushl %[nr]
\\ jmp common_isr_handler
:
: [nr] "n" (i)
);
}
};
return switch (i) {
8, 10...14, 17 => Wrapper.stub_with_errorcode,
else => Wrapper.stub_with_zero,
};
}
|
0 | repos/Ziguana-Game-System/old-version/kernel | repos/Ziguana-Game-System/old-version/kernel/src/mbr.zig | const std = @import("std");
pub const CHS = packed struct {
head: u8,
sector: u6,
cylinder: u10,
};
pub const Partition = struct {
const PackedData = [16]u8;
flags: u8, // if 0x80 is set, it's bootable
start: CHS,
id: u8, // system id
end: CHS,
lba: u32,
size: u32,
fn unpack(data: Partition.PackedData) Partition {
return Partition{
.flags = data[0],
.start = @bitCast(CHS, data[1..4].*),
.id = data[4],
.end = @bitCast(CHS, data[5..8].*),
.lba = @bitCast(u32, data[8..12].*),
.size = @bitCast(u32, data[12..16].*),
};
}
};
pub const BootSector = packed struct {
bootloader: [440]u8,
driveSignature: u32, // since win2000
zero: u16,
partitions: [4]Partition.PackedData,
signature: u16 = signature,
pub fn getPartition(self: @This(), index: u2) Partition {
return Partition.unpack(self.partitions[index]);
}
pub fn isValid(hdr: BootSector) bool {
return hdr.signature == signature;
}
};
pub const signature = 0xAA55;
comptime {
// @compileLog(
// @sizeOf(CHS),
// @sizeOf(Partition),
// @sizeOf(BootSector),
// );
std.debug.assert(@sizeOf(CHS) == 3);
std.debug.assert(@sizeOf(Partition) == 16);
std.debug.assert(@sizeOf(BootSector) == 512);
}
|
0 | repos/Ziguana-Game-System/old-version/kernel | repos/Ziguana-Game-System/old-version/kernel/src/assembler.zig | const std = @import("std");
const warn = if (std.builtin.os.tag == .freestanding)
@import("text-terminal.zig").print
else
std.debug.warn;
const Operand = union(enum) {
direct: Direct,
indirect: Indirect,
fn print(this: Operand) void {
switch (this) {
.direct => |o| o.print(),
.indirect => |o| o.print(),
}
}
const Direct = union(enum) {
register: u4,
label: []const u8,
immediate: u32,
// fn print(this: Direct) void {
// switch (this) {
// .register => |r| std.debug.warn("r{}", r),
// .label => |r| std.debug.warn("{}", r),
// .immediate => |r| std.debug.warn("{}", r),
// }
// }
};
const Indirect = struct {
source: Direct,
offset: ?i32,
// fn print(this: Indirect) void {
// std.debug.warn("[");
// this.source.print();
// if (this.offset) |offset| {
// if (offset < 0) {
// std.debug.warn("{}", offset);
// } else {
// std.debug.warn("+{}", offset);
// }
// }
// std.debug.warn("]");
// }
};
};
const Instruction = struct {
mnemonic: []const u8,
operands: [3]Operand,
operandCount: usize,
fn new(mn: []const u8) Instruction {
return Instruction{
.mnemonic = mn,
.operandCount = 0,
.operands = undefined,
};
}
fn addOperand(this: *Instruction, oper: Operand) !void {
if (this.operandCount >= this.operands.len)
return error.TooManyOperands;
this.operands[this.operandCount] = oper;
this.operandCount += 1;
}
};
const Element = union(enum) {
instruction: Instruction,
label: []const u8,
data8: u8,
data16: u16,
data32: u32,
alignment: u32,
};
const Parser = struct {
allocator: *std.mem.Allocator,
source: []const u8,
offset: usize,
lineNumber: u32 = 0,
constants: std.StringHashMap(Token),
state: State = .default,
fn init(allocator: *std.mem.Allocator, source: []const u8) Parser {
return Parser{
.allocator = allocator,
.source = source,
.offset = 0,
.constants = std.StringHashMap(Token).init(allocator),
};
}
fn deinit(this: *Parser) void {
this.constants.deinit();
}
const TokenType = enum {
hexnum, // 0x10
decnum, // 10
registerName, // r0 … r15
label, // either 'bla:' or '.bla:'
comma, // ,
beginIndirection, // [
endIndirection, // ]
identifier, // [A-Za-z][A-Za-z0-9]+
directiveOrLabel, // .foo
lineBreak, // '\n'
positiveOffset, // '+'
negativeOffset, // '-'
endOfText,
};
const Token = struct {
type: TokenType,
value: []const u8,
};
fn isWordCharacter(c: u8) bool {
return switch (c) {
'0'...'9' => true,
'a'...'z' => true,
'A'...'Z' => true,
'_' => true,
else => false,
};
}
fn isDigit(c: u8) bool {
return switch (c) {
'0'...'9' => true,
else => false,
};
}
fn isHexDigit(c: u8) bool {
return switch (c) {
'0'...'9' => true,
'a'...'f' => true,
'A'...'F' => true,
else => false,
};
}
fn readToken(this: *Parser) !?Token {
// const token = this.readTokenNoDebug();
// std.debug.warn("token: {}\n", token);
// return token;
// }
// fn readTokenNoDebug(this: *Parser) !?Token {
if (this.offset >= this.source.len)
return null;
// skip to next start of "meaningful"
while (true) {
const c = this.source[this.offset];
if (c == '#') { // read line comment
this.offset += 1;
if (this.offset >= this.source.len)
return null;
while (this.source[this.offset] != '\n') {
this.offset += 1;
if (this.offset >= this.source.len)
return null;
}
// don't eat the delimiting newline, otherwise trailing comments will fail
} else if (c == ' ' or c == '\t') {
this.offset += 1;
} else {
break;
}
}
if (this.source[this.offset] == '\n') {
this.lineNumber += 1;
}
switch (this.source[this.offset]) {
// is single-char item
'\n', ',', '[', ']', '-', '+' => {
this.offset += 1;
return Token{
.type = switch (this.source[this.offset - 1]) {
'\n' => .lineBreak,
',' => .comma,
'[' => .beginIndirection,
']' => .endIndirection,
'-' => .negativeOffset,
'+' => .positiveOffset,
else => unreachable,
},
.value = this.source[this.offset - 1 .. this.offset],
};
},
// is either .label or .directiveOrLabel
'.' => {
const start = this.offset;
var end = start + 1;
if (end >= this.source.len)
return error.UnexpectedEndOfText;
while (isWordCharacter(this.source[end])) {
end += 1;
if (end >= this.source.len)
return error.UnexpectedEndOfText;
}
this.offset = end;
if (this.source[end] == ':') {
this.offset += 1;
return Token{
.type = .label,
.value = this.source[start..end],
};
} else {
return Token{
.type = .directiveOrLabel,
.value = this.source[start..end],
};
}
},
// identifier:
'A'...'Z', 'a'...'z', '_' => {
const start = this.offset;
var end = start + 1;
if (end >= this.source.len)
return error.UnexpectedEndOfText;
while (isWordCharacter(this.source[end])) {
end += 1;
if (end >= this.source.len)
return error.UnexpectedEndOfText;
}
this.offset = end;
if (this.source[end] == ':') {
this.offset += 1;
return Token{
.type = .label,
.value = this.source[start..end],
};
} else {
const text = this.source[start..end];
comptime var i = 0;
inline while (i < 16) : (i += 1) {
comptime var registerName: [3]u8 = "r??".*;
comptime var len = std.fmt.formatIntBuf(registerName[1..], @as(usize, i), 10, false, std.fmt.FormatOptions{});
// @compileLog(i, registerName[0 .. 1 + len]);
if (std.mem.eql(u8, text, registerName[0 .. 1 + len])) {
return Token{
.type = .registerName,
.value = text,
};
}
}
if (this.constants.get(text)) |kv| {
// return stored token from .def
return kv;
}
return Token{
.type = .identifier,
.value = text,
};
}
},
// numbers:
'0'...'9' => {
const start = this.offset;
var end = start + 1;
if (end >= this.source.len)
return error.UnexpectedEndOfText;
while (isHexDigit(this.source[end]) or this.source[end] == 'x') {
end += 1;
if (end >= this.source.len)
return error.UnexpectedEndOfText;
}
this.offset = end;
const text = this.source[start..end];
if (text.len >= 2 and text[0] == '0' and text[1] == 'x') {
if (text.len == 2)
return error.InvalidHexLiteral;
return Token{
.type = .hexnum,
.value = this.source[start..end],
};
}
return Token{
.type = .decnum,
.value = this.source[start..end],
};
},
else => return error.UnexpectedCharacter,
}
return null;
}
fn readExpectedToken(this: *Parser, comptime _type: TokenType) ![]const u8 {
const token = (try this.readToken()) orelse return error.UnexpectedEndOfText;
if (token.type != _type)
return error.UnexpectedToken;
return token.value;
}
fn readAnyExpectedToken(this: *Parser, allowedTypes: []const TokenType) !Token {
const token = (try this.readToken()) orelse return error.UnexpectedEndOfText;
for (allowedTypes) |val| {
if (token.type == val)
return token;
}
return error.UnexpectedToken;
}
fn convertTokenToNumber(token: Token) !u32 {
return switch (token.type) {
.hexnum => try std.fmt.parseInt(u32, token.value[2..], 16),
.decnum => try std.fmt.parseInt(u32, token.value, 10),
else => return error.UnexpectedToken,
};
}
fn convertTokenToDirectOperand(token: Token) !Operand.Direct {
return switch (token.type) {
.registerName => Operand.Direct{
.register = try std.fmt.parseInt(u4, token.value[1..], 10),
},
.identifier, .directiveOrLabel => Operand.Direct{
.label = token.value,
},
.hexnum, .decnum => Operand.Direct{
.immediate = try convertTokenToNumber(token),
},
else => return error.UnexpectedToken,
};
}
fn readNumberToken(this: *Parser) !u32 {
return try convertTokenToNumber(try this.readAnyExpectedToken(([_]TokenType{ .decnum, .hexnum })[0..]));
}
const TokenizeError = error{
UnexpectedEndOfText,
InvalidHexLiteral,
UnexpectedCharacter,
UnexpectedToken,
OutOfMemory,
Overflow,
InvalidCharacter,
UnknownDirective,
TooManyOperands,
NotImplementedYet,
};
fn readNext(this: *Parser) TokenizeError!?Element {
// loop until we return
while (true) {
var token = (try this.readToken()) orelse return null;
if (token.type == .lineBreak) {
// line breaks will stop any special processing from directives
this.state = .default;
continue;
}
switch (this.state) {
.default => {
switch (token.type) {
.directiveOrLabel => {
if (std.mem.eql(u8, token.value, ".def")) {
const name = try this.readExpectedToken(.identifier);
_ = try this.readExpectedToken(.comma);
const value = (try this.readToken()) orelse return error.UnexpectedEndOfText;
switch (value.type) {
.identifier, .hexnum, .decnum, .registerName => {
_ = try this.constants.put(name, value);
},
else => return error.UnexpectedToken,
}
} else if (std.mem.eql(u8, token.value, ".undef")) {
const name = try this.readExpectedToken(.identifier);
_ = this.constants.remove(name);
} else if (std.mem.eql(u8, token.value, ".d8")) {
this.state = .readsD8;
} else if (std.mem.eql(u8, token.value, ".d16")) {
this.state = .readsD16;
} else if (std.mem.eql(u8, token.value, ".d32") or std.mem.eql(u8, token.value, ".dw")) {
this.state = .readsD32;
} else if (std.mem.eql(u8, token.value, ".align")) {
const al = try this.readNumberToken();
return @as(?Element, Element{
.alignment = al,
});
} else {
return error.UnknownDirective;
}
},
.label => {
return Element{
.label = token.value,
};
},
// is a mnemonic/instruction
.identifier => {
var instruction = Instruction.new(token.value);
// read operands
var readDelimiterNext = false;
var isFirst = true;
while (true) {
const subtok = (try this.readToken()) orelse return error.UnexpectedEndOfText;
if (isFirst and subtok.type == .lineBreak)
break;
isFirst = false;
if (readDelimiterNext) {
// is either comma for another operand or lineBreak for "end of operands"
switch (subtok.type) {
.lineBreak => break,
.comma => {},
else => return error.UnexpectedToken,
}
readDelimiterNext = false;
} else {
// is an operand value
switch (subtok.type) {
.identifier, .hexnum, .decnum, .directiveOrLabel, .registerName => {
try instruction.addOperand(Operand{
.direct = try convertTokenToDirectOperand(subtok),
});
},
.beginIndirection => {
const directOperand = try convertTokenToDirectOperand((try this.readToken()) orelse return error.UnexpectedEndOfText);
const something = try this.readAnyExpectedToken(([_]TokenType{ .endIndirection, .positiveOffset, .negativeOffset })[0..]);
const result = switch (something.type) {
.endIndirection => Operand.Indirect{
.source = directOperand,
.offset = null,
},
.positiveOffset => blk: {
const num = try this.readNumberToken();
_ = try this.readExpectedToken(.endIndirection);
break :blk Operand.Indirect{
.source = directOperand,
.offset = @intCast(i32, num),
};
},
.negativeOffset => blk: {
const num = try this.readNumberToken();
_ = try this.readExpectedToken(.endIndirection);
break :blk Operand.Indirect{
.source = directOperand,
.offset = -@intCast(i32, num),
};
},
else => return error.UnexpectedToken,
};
try instruction.addOperand(Operand{
.indirect = result,
});
},
else => return error.UnexpectedToken,
}
readDelimiterNext = true;
}
}
return Element{ .instruction = instruction };
},
else => return error.UnexpectedToken,
}
},
.readsD8, .readsD16, .readsD32 => {
switch (token.type) {
.decnum, .hexnum => {
const num = try convertTokenToNumber(token);
return switch (this.state) {
.readsD8 => Element{
.data8 = @intCast(u8, num),
},
.readsD16 => Element{
.data16 = @intCast(u16, num),
},
.readsD32 => Element{
.data32 = num,
},
else => unreachable,
};
},
.identifier => {
// TODO: Support definitions and labels here
return error.NotImplementedYet;
},
.comma => {},
else => return error.UnexpectedToken,
}
},
}
}
}
const State = enum {
default,
readsD8,
readsD16,
readsD32,
};
};
fn getRegisterAddress(register: u4) u32 {
const root = @import("root");
if (@hasDecl(root, "getRegisterAddress")) {
return root.getRegisterAddress(register);
} else {
// label addresses are hardcoded on page 0, address 0x00 … 0x40
return 4 * u32(register);
}
}
fn convertOperandToArg(comptime T: type, operand: Operand, labels: Labels) error{InvalidOperand}!T {
switch (operand) {
.direct => |opdir| switch (opdir) {
.register => |reg| return T{
.indirection = Indirection{
.address = ImmediateOrLabel.initImm(getRegisterAddress(reg)),
.offset = 0,
},
},
.label => |lbl| if (comptime T == InstrInput) {
return T{
.immediate = ImmediateOrLabel.initLbl(labels.get(lbl)),
};
} else {
return error.InvalidOperand;
},
.immediate => |imm| if (comptime T == InstrInput) {
return T{
.immediate = ImmediateOrLabel.initImm(imm),
};
} else {
return error.InvalidOperand;
},
},
.indirect => |indirect| {
switch (indirect.source) {
.register => |reg| return T{
.doubleIndirection = Indirection{
.address = ImmediateOrLabel.initImm(getRegisterAddress(reg)),
.offset = indirect.offset orelse 0,
},
},
.label => |lbl| return T{
.indirection = Indirection{
.address = ImmediateOrLabel.initLbl(labels.get(lbl)),
.offset = indirect.offset orelse 0,
},
},
.immediate => |imm| return T{
.indirection = Indirection{
.address = ImmediateOrLabel.initImm(imm),
.offset = indirect.offset orelse 0,
},
},
}
},
}
}
const Labels = struct {
local: std.StringHashMap(u32),
global: std.StringHashMap(u32),
fn get(this: Labels, name: []const u8) LabelRef {
var ref = if (name[0] == '.') this.local.getEntry(name) else this.global.getEntry(name);
if (ref) |lbl| {
return LabelRef{
.label = lbl.key,
.offset = lbl.value,
};
} else {
return LabelRef{
.label = name,
.offset = null,
};
}
}
};
pub fn assemble(allocator: *std.mem.Allocator, source: []const u8, target: []u8, offset: ?u32) !void {
var arena = std.heap.ArenaAllocator.init(allocator);
defer arena.deinit();
var parser = Parser.init(&arena.allocator, source);
defer parser.deinit();
var labels = Labels{
.local = std.StringHashMap(u32).init(&arena.allocator),
.global = std.StringHashMap(u32).init(&arena.allocator),
};
defer labels.local.deinit();
defer labels.global.deinit();
var writer = Writer.init(allocator, target);
writer.deinit();
// used for offsetting labels to "link" the code to the
// right position
const absoffset = offset orelse @intCast(u32, @ptrToInt(target.ptr));
// std.debug.warn("offset = {} ({})\n", offset, absoffset);
var i: usize = 0;
warn("start parsing...\r\n", .{});
while (try parser.readNext()) |label_or_instruction| {
i += 1;
switch (label_or_instruction) {
.label => |lbl| {
// std.debug.warn("{}: # 0x{X:0>8}\n", lbl, writer.offset);
if (lbl[0] == '.') {
// is local
_ = try labels.local.put(lbl, absoffset + writer.offset);
} else {
// we need to patch all previous code here as
// we will lose all local label references in this step.
try writer.applyPatches(labels, .onlyLocals);
// erase all local labels as soon as we encounter a global label
labels.local.clearAndFree();
_ = try labels.global.put(lbl, absoffset + writer.offset);
}
},
.instruction => |instr| {
// insert debug tracers
// CD30 int 0x30
// enable this for line callback :)
if (@hasDecl(@import("root"), "enable_assembler_tracing")) {
if (@import("root").enable_assembler_tracing) {
try writer.write(@as(u8, 0xCD));
try writer.write(@as(u8, 0x30));
try writer.write(parser.lineNumber);
}
}
// std.debug.warn("\t{}", instr.mnemonic);
// var i: usize = 0;
// while (i < instr.operandCount) : (i += 1) {
// if (i > 0) {
// std.debug.warn(", ");
// } else {
// std.debug.warn(" ");
// }
// instr.operands[i].print();
// }
// std.debug.warn("\n");
var foundAny = false;
inline for (@typeInfo(InstructionCore).Struct.decls) |executor| {
comptime std.debug.assert(executor.data == .Fn);
if (std.mem.eql(u8, executor.name, instr.mnemonic)) {
const FunType = @typeInfo(executor.data.Fn.fn_type).Fn;
if (FunType.args.len != instr.operandCount + 1) {
// ("operand count mismatch for {}. Expected {}, got {}!\n", instr.mnemonic, FunType.args.len - 1, instr.operandCount);
return error.OperandMismatch;
}
inline for (FunType.args) |arg| {
comptime std.debug.assert(arg.arg_type != null);
}
switch (FunType.args.len) {
1 => {
try @field(InstructionCore, executor.name)(&writer);
},
2 => {
var arg0 = try convertOperandToArg(FunType.args[1].arg_type.?, instr.operands[0], labels);
try @field(InstructionCore, executor.name)(&writer, arg0);
},
3 => {
var arg0 = try convertOperandToArg(FunType.args[1].arg_type.?, instr.operands[0], labels);
var arg1 = try convertOperandToArg(FunType.args[2].arg_type.?, instr.operands[1], labels);
try @field(InstructionCore, executor.name)(&writer, arg0, arg1);
},
4 => {
// warn("assemble {}\r\n", executor.name);
var arg0 = try convertOperandToArg(FunType.args[1].arg_type.?, instr.operands[0], labels);
var arg1 = try convertOperandToArg(FunType.args[2].arg_type.?, instr.operands[1], labels);
var arg2 = try convertOperandToArg(FunType.args[3].arg_type.?, instr.operands[2], labels);
try @field(InstructionCore, executor.name)(&writer, arg0, arg1, arg2);
},
else => @panic("unsupported operand count!"),
}
// std.debug.warn("found instruction: {}\n", instr.mnemonic);
foundAny = true;
break;
}
}
if (!foundAny) {
// std.debug.warn("unknown instruction: {}\n", instr.mnemonic);
return error.UnknownMnemonic;
}
},
.data8 => |data| {
// std.debug.warn(".d8 0x{X:0>2}\n", data);
try writer.write(data);
},
.data16 => |data| {
// std.debug.warn(".d16 0x{X:0>4}\n", data);
try writer.write(data);
},
.data32 => |data| {
// std.debug.warn(".d32 0x{X:0>8}\n", data);
try writer.write(data);
},
.alignment => |al| {
// std.debug.warn(".align {}\n", al);
std.debug.assert((al & (al - 1)) == 0);
writer.offset = (writer.offset + al - 1) & ~(al - 1);
},
}
}
try InstructionCore.exit(&writer);
// debug output:
// {
// std.debug.warn("Labels:\n");
// var iter = labels.global.iterator();
// while (iter.next()) |lbl| {
// std.debug.warn("\t{}\n", lbl);
// }
// }
// {
// std.debug.warn("Constants:\n");
// var iter = parser.constants.iterator();
// while (iter.next()) |lbl| {
// std.debug.warn("\t{}\n", lbl);
// }
// }
// {
// std.debug.warn("Global Patches:\n");
// var iter = writer.globalPatchlist.iterator();
// while (iter.next()) |lbl| {
// std.debug.warn("\t{}\n", lbl);
// }
// }
try writer.applyPatches(labels, .all);
}
/// A reference to a named label.
/// May contain the offset of the label for faster assembly.
const LabelRef = struct {
label: []const u8,
offset: ?u32,
};
/// A literal value that is noted by either a label reference or an immediate (written) number.
const ImmediateOrLabel = union(enum) {
immediate: u32,
label: LabelRef,
fn initImm(val: u32) ImmediateOrLabel {
return ImmediateOrLabel{
.immediate = val,
};
}
fn initLbl(val: LabelRef) ImmediateOrLabel {
return ImmediateOrLabel{
.label = val,
};
}
pub fn format(value: ImmediateOrLabel, comptime fmt: []const u8, options: std.fmt.FormatOptions, context: anytype, comptime Errors: type, output: fn (@typeOf(context), []const u8) Errors!void) Errors!void {
switch (value) {
.immediate => |imm| try std.fmt.format(context, Errors, output, "0x{X:0>8}", imm),
.label => |ref| {
if (ref.offset) |off| {
try std.fmt.format(context, Errors, output, "0x{X:0>8}", off);
} else {
try std.fmt.format(context, Errors, output, "{}", ref.label);
}
},
}
}
};
const WriterError = error{
NotEnoughSpace,
OutOfMemory,
};
/// simple wrapper around a slice that allows
/// sequential writing to that slice
const Writer = struct {
target: []u8,
offset: u32,
localPatchlist: std.ArrayList(Patch),
globalPatchlist: std.ArrayList(Patch),
const PatchBatch = enum {
all,
onlyLocals,
};
/// a patch that will be applied later.
/// Patches are required when labels are referenced but the offset of
/// the label is not yet known.
const Patch = struct {
/// Offset in the `target` field of the `Writer` struct.
offset_to_binary: u32,
/// Required when the label is referenced in an indirectoin via `[label+offset]`.
offset_to_value: i32,
/// The name of the label.
label: []const u8,
};
fn init(allocator: *std.mem.Allocator, target: []u8) Writer {
return Writer{
.target = target,
.offset = 0,
.localPatchlist = std.ArrayList(Patch).init(allocator),
.globalPatchlist = std.ArrayList(Patch).init(allocator),
};
}
fn deinit(this: Writer) void {
this.localPatchlist.deinit();
this.globalPatchlist.deinit();
}
fn applyPatchesTo(this: *Writer, labels: Labels, patchlist: *std.ArrayList(Patch)) !void {
// on deinit, we will flush our patchlist and apply all patches:
for (patchlist.items) |patch| {
const lbl = labels.get(patch.label);
// std.debug.warn("Patching {} to {}\n", patch, lbl);
if (lbl.offset) |local_offset| {
const off = local_offset + @bitCast(u32, patch.offset_to_value);
std.mem.copy(u8, this.target[patch.offset_to_binary .. patch.offset_to_binary + 4], std.mem.asBytes(&off));
} else {
return error.UnknownLabel;
}
}
patchlist.shrink(0);
}
fn applyPatches(this: *Writer, labels: Labels, batchMode: PatchBatch) !void {
if (batchMode == .all) {
try this.applyPatchesTo(labels, &this.globalPatchlist);
}
try this.applyPatchesTo(labels, &this.localPatchlist);
}
fn ensureSpace(this: *Writer, size: usize) WriterError!void {
if (this.offset + size > this.target.len)
return error.NotEnoughSpace;
}
/// emits `count` undefined bytes to the stream.
/// these must be patched by hand!
fn emit(this: *Writer, count: u32) WriterError!usize {
try this.ensureSpace(count);
std.mem.set(u8, this.target[this.offset .. this.offset + count], 0x90);
const off = this.offset;
this.offset += count;
return @as(usize, off);
}
/// writes a value.
/// if the value is a LabelRef and the ref is not valid yet, it will
/// be added to the patchlist.
fn write(this: *Writer, value: anytype) WriterError!void {
try this.writeWithOffset(value, 0);
}
/// writes a value with a certain offset added to it.
/// if the value is a LabelRef and the ref is not valid yet, it will
/// be added to the patchlist.
fn writeWithOffset(this: *Writer, value: anytype, offset: i32) WriterError!void {
const T = @TypeOf(value);
switch (T) {
u8, u16, u32, u64, i8, i16, i32, i64 => {
var val = value + @intCast(T, offset);
try this.ensureSpace(@sizeOf(T));
std.mem.copy(u8, this.target[this.offset .. this.offset + @sizeOf(T)], std.mem.asBytes(&val));
this.offset += @sizeOf(T);
},
LabelRef => {
try this.ensureSpace(4);
if (value.offset) |local_offset| {
// this assumes twos complement
const off = local_offset + @bitCast(u32, offset);
std.mem.copy(u8, this.target[this.offset .. this.offset + 4], std.mem.asBytes(&off));
} else {
const patch = Patch{
.label = value.label,
.offset_to_binary = this.offset,
.offset_to_value = offset,
};
if (value.label[0] == '.') {
try this.localPatchlist.append(patch);
} else {
try this.globalPatchlist.append(patch);
}
}
this.offset += 4;
},
ImmediateOrLabel => switch (value) {
.immediate => |v| try this.writeWithOffset(v, offset),
.label => |v| try this.writeWithOffset(v, offset),
},
else => @compileError(@typeName(@TypeOf(value)) ++ " is not supported by writer!"),
}
}
};
/// First or second level indirection. second level indirection is required for
/// fake registers as they are implemented by indirection as well.
const Indirection = struct {
address: ImmediateOrLabel,
offset: i32,
};
/// An operand to an instruction that may be modified by the instruction.
/// Must must either be a register name or a "regular" indirection.
const InstrOutput = union(enum) {
indirection: Indirection,
doubleIndirection: Indirection,
pub fn format(value: InstrOutput, comptime fmt: []const u8, options: std.fmt.FormatOptions, context: anytype, comptime Errors: type, output: fn (@typeOf(context), []const u8) Errors!void) Errors!void {
switch (value) {
.indirection => |ind| if (ind.offset == 0)
try std.fmt.format(context, Errors, output, "*[{}]", ind.address)
else
try std.fmt.format(context, Errors, output, "*[{}+{}]", ind.address, ind.offset),
.doubleIndirection => |dind| if (dind.offset == 0)
try std.fmt.format(context, Errors, output, "*[[{}]]", dind.address)
else
try std.fmt.format(context, Errors, output, "*[[{}]+{}]", dind.address, dind.offset),
}
}
/// Loads the operands value into EAX.
/// Does not modify anything except EAX.
pub fn loadToEAX(this: InstrOutput, writer: *Writer) !void {
switch (this) {
.indirection => |ind| {
// A144332211 mov eax,[0x11223344]
try writer.write(@as(u8, 0xA1));
try writer.writeWithOffset(ind.address, ind.offset);
},
// actually only required when someone does `[reg]`
.doubleIndirection => |ind| {
// A144332211 mov eax,[0x11223344]
try writer.write(@as(u8, 0xA1));
try writer.write(ind.address);
if (ind.offset != 0) {
// 8B8044332211 mov eax,[eax+0x11223344]
try writer.write(@as(u8, 0x8B));
try writer.write(@as(u8, 0x80));
try writer.write(ind.offset);
} else {
// 8B00 mov eax,[eax]
try writer.write(@as(u8, 0x8B));
try writer.write(@as(u8, 0x00));
}
},
}
}
/// Saves EAX into the operands location. Clobbers EBX
pub fn saveFromEAX(this: InstrOutput, writer: *Writer) !void {
switch (this) {
.indirection => |ind| {
// A344332211 mov [0x11223344],eax
try writer.write(@as(u8, 0xA3));
try writer.writeWithOffset(ind.address, ind.offset);
},
// actually only required when someone does `[reg]`
.doubleIndirection => |ind| {
// 8B 1D 44332211 mov ebx,[dword 0x11223344]
try writer.write(@as(u8, 0x8B));
try writer.write(@as(u8, 0x1D));
try writer.write(ind.address);
if (ind.offset != 0) {
// 898344332211 mov [ebx+0x11223344],eax
try writer.write(@as(u8, 0x89));
try writer.write(@as(u8, 0x83));
try writer.write(ind.offset);
} else {
// 8903 mov [ebx],eax
try writer.write(@as(u8, 0x89));
try writer.write(@as(u8, 0x03));
}
},
}
}
};
/// An operand to an instruction that is only read by the instruction.
const InstrInput = union(enum) {
immediate: ImmediateOrLabel,
indirection: Indirection,
doubleIndirection: Indirection,
pub fn format(value: InstrInput, comptime fmt: []const u8, options: std.fmt.FormatOptions, context: anytype, comptime Errors: type, output: fn (@typeOf(context), []const u8) Errors!void) Errors!void {
switch (value) {
.immediate => |imm| try std.fmt.format(context, Errors, output, "{}", imm),
.indirection => |ind| if (ind.offset == 0)
try std.fmt.format(context, Errors, output, "[{}]", ind.address)
else
try std.fmt.format(context, Errors, output, "[{}+{}]", ind.address, ind.offset),
.doubleIndirection => |dind| if (dind.offset == 0)
try std.fmt.format(context, Errors, output, "[[{}]]", dind.address)
else
try std.fmt.format(context, Errors, output, "[[{}]+{}]", dind.address, dind.offset),
}
}
/// Loads the operands value into EAX.
/// Does not modify anything except EAX.
pub fn loadToEAX(this: InstrInput, writer: *Writer) !void {
switch (this) {
.immediate => |imm| {
// B844332211 mov eax,0x11223344
try writer.write(@as(u8, 0xB8));
try writer.write(imm);
},
.indirection => |ind| {
// A144332211 mov eax,[0x11223344]
try writer.write(@as(u8, 0xA1));
try writer.writeWithOffset(ind.address, ind.offset);
},
// actually only required when someone does `[reg]`
.doubleIndirection => |ind| {
// A144332211 mov eax,[0x11223344]
try writer.write(@as(u8, 0xA1));
try writer.write(ind.address);
if (ind.offset != 0) {
// 8B8044332211 mov eax,[eax+0x11223344]
try writer.write(@as(u8, 0x8B));
try writer.write(@as(u8, 0x80));
try writer.write(ind.offset);
} else {
// 8B00 mov eax,[eax]
try writer.write(@as(u8, 0x8B));
try writer.write(@as(u8, 0x00));
}
},
}
}
};
const API = @import("root").assembler_api;
fn emitConditionalJump(writer: *Writer, dst: InstrInput, jumpCode: u8) WriterError!void {
// make inverse jump mechanic:
// jump over the unconditional jump as
// conditional jumps are always short jumps and cannot
// use indirection
try writer.write(jumpCode); // emit NOP for debugging reference
const offset = try writer.emit(1);
const start = writer.offset;
try InstructionCore.jmp(writer, dst);
const end = writer.offset;
writer.target[offset] = @intCast(u8, end - start);
}
fn emitMovEbxToEax(writer: *Writer) WriterError!void {
// 89C3 mov ebx,eax
try writer.write(@as(u8, 0x89));
try writer.write(@as(u8, 0xC3));
}
/// Contains emitter functions for every possible instructions.
const InstructionCore = struct {
/// moves src to dst.
fn mov(writer: *Writer, dst: InstrOutput, src: InstrInput) WriterError!void {
try src.loadToEAX(writer);
try dst.saveFromEAX(writer);
}
/// adds src to dst
fn add(writer: *Writer, dst: InstrOutput, src: InstrInput) WriterError!void {
try src.loadToEAX(writer);
try emitMovEbxToEax(writer);
try dst.loadToEAX(writer);
// 01D8 add eax,ebx
try writer.write(@as(u8, 0x01));
try writer.write(@as(u8, 0xD8));
try dst.saveFromEAX(writer);
}
// subtracts src from dst
fn sub(writer: *Writer, dst: InstrOutput, src: InstrInput) WriterError!void {
try src.loadToEAX(writer);
try emitMovEbxToEax(writer);
try dst.loadToEAX(writer);
// 29D8 sub eax,ebx
try writer.write(@as(u8, 0x29));
try writer.write(@as(u8, 0xD8));
try dst.saveFromEAX(writer);
}
fn cmp(writer: *Writer, lhs: InstrInput, rhs: InstrInput) WriterError!void {
try rhs.loadToEAX(writer);
try emitMovEbxToEax(writer);
try lhs.loadToEAX(writer);
// 39D8 cmp eax,ebx
try writer.write(@as(u8, 0x39));
try writer.write(@as(u8, 0xD8));
}
fn jmp(writer: *Writer, pos: InstrInput) WriterError!void {
switch (pos) {
.immediate => |imm| {
// B844332211 mov eax,0x11223344
try writer.write(@as(u8, 0xB8));
try writer.write(imm);
// FFE0 jmp eax
try writer.write(@as(u8, 0xFF));
try writer.write(@as(u8, 0xE0));
},
.indirection => |ind| {
// FF2544332211 jmp [dword 0x11223344]
try writer.write(@as(u8, 0xFF));
try writer.write(@as(u8, 0x25));
try writer.writeWithOffset(ind.address, ind.offset);
},
// actually only required when someone does `[reg]`
.doubleIndirection => |ind| {
// A144332211 mov eax,[0x11223344]
try writer.write(@as(u8, 0xA1));
try writer.write(ind.address);
if (ind.offset != 0) {
// FFA044332211 jmp [eax+0x11223344]
try writer.write(@as(u8, 0xFF));
try writer.write(@as(u8, 0xA0));
try writer.write(ind.offset);
} else {
// FF20 jmp [eax]
try writer.write(@as(u8, 0xFF));
try writer.write(@as(u8, 0x20));
}
},
}
}
fn jnz(writer: *Writer, pos: InstrInput) WriterError!void {
// 7404 jz +4
try emitConditionalJump(writer, pos, 0x74);
}
fn jiz(writer: *Writer, pos: InstrInput) WriterError!void {
// 7504 jnz +4
try emitConditionalJump(writer, pos, 0x75);
}
fn jlz(writer: *Writer, pos: InstrInput) WriterError!void {
// 7D06 jnl 0x4d # jump not less
try emitConditionalJump(writer, pos, 0x7D);
}
fn jgz(writer: *Writer, pos: InstrInput) WriterError!void {
// 7E04 jng 0x4d # jump not greater
try emitConditionalJump(writer, pos, 0x7E);
}
fn mul(writer: *Writer, dst: InstrOutput, src: InstrInput) WriterError!void {
try src.loadToEAX(writer);
try emitMovEbxToEax(writer);
try dst.loadToEAX(writer);
// F7E3 mul ebx
// clobbers EDX with higher part
try writer.write(@as(u8, 0xF7));
try writer.write(@as(u8, 0xE3));
try dst.saveFromEAX(writer);
}
fn div(writer: *Writer, dst: InstrOutput, src: InstrInput) WriterError!void {
try src.loadToEAX(writer);
try emitMovEbxToEax(writer);
try dst.loadToEAX(writer);
// F7F3 div ebx
// clobbers EDX with remainder part
try writer.write(@as(u8, 0xF7));
try writer.write(@as(u8, 0xF3));
try dst.saveFromEAX(writer);
}
fn mod(writer: *Writer, dst: InstrOutput, src: InstrInput) WriterError!void {
try src.loadToEAX(writer);
try emitMovEbxToEax(writer);
try dst.loadToEAX(writer);
// F7F3 div ebx
// clobbers EDX with remainder part
try writer.write(@as(u8, 0xF7));
try writer.write(@as(u8, 0xF3));
// 89D0 mov eax,edx
try writer.write(@as(u8, 0x89));
try writer.write(@as(u8, 0xD0));
try dst.saveFromEAX(writer);
}
fn gettime(writer: *Writer, dst: InstrOutput) WriterError!void {
// extern fn () u32
// B844332211 mov eax,0x11223344
try writer.write(@as(u8, 0xB8));
try writer.write(@intCast(u32, @ptrToInt(API.gettime)));
// FFD0 call eax
try writer.write(@as(u8, 0xFF));
try writer.write(@as(u8, 0xD0));
try dst.saveFromEAX(writer);
}
fn getkey(writer: *Writer, dst: InstrOutput) WriterError!void {
// extern fn () u32
// B844332211 mov eax,0x11223344
try writer.write(@as(u8, 0xB8));
try writer.write(@intCast(u32, @ptrToInt(API.getkey)));
// FFD0 call eax
try writer.write(@as(u8, 0xFF));
try writer.write(@as(u8, 0xD0));
try dst.saveFromEAX(writer);
}
fn @"and"(writer: *Writer, dst: InstrOutput, src: InstrInput) WriterError!void {
try src.loadToEAX(writer);
try emitMovEbxToEax(writer);
try dst.loadToEAX(writer);
// 21D8 and eax,ebx
try writer.write(@as(u8, 0x21));
try writer.write(@as(u8, 0xD8));
try dst.saveFromEAX(writer);
}
fn @"or"(writer: *Writer, dst: InstrOutput, src: InstrInput) WriterError!void {
try src.loadToEAX(writer);
try emitMovEbxToEax(writer);
try dst.loadToEAX(writer);
// 09D8 or eax,ebx
try writer.write(@as(u8, 0x09));
try writer.write(@as(u8, 0xD8));
try dst.saveFromEAX(writer);
}
fn @"xor"(writer: *Writer, dst: InstrOutput, src: InstrInput) WriterError!void {
try src.loadToEAX(writer);
try emitMovEbxToEax(writer);
try dst.loadToEAX(writer);
// 31D8 xor eax,ebx
try writer.write(@as(u8, 0x31));
try writer.write(@as(u8, 0xD8));
try dst.saveFromEAX(writer);
}
fn @"not"(writer: *Writer, dst: InstrOutput) WriterError!void {
try dst.loadToEAX(writer);
// F7D0 not eax
try writer.write(@as(u8, 0xF7));
try writer.write(@as(u8, 0xD0));
try dst.saveFromEAX(writer);
}
fn @"neg"(writer: *Writer, dst: InstrOutput) WriterError!void {
try dst.loadToEAX(writer);
// F7D8 neg eax
try writer.write(@as(u8, 0xF7));
try writer.write(@as(u8, 0xD8));
try dst.saveFromEAX(writer);
}
fn setpix(writer: *Writer, x: InstrInput, y: InstrInput, col: InstrInput) WriterError!void {
// extern fn (x: u32, y: u32, col: u32) void
try col.loadToEAX(writer);
// 50 push eax
try writer.write(@as(u8, 0x50));
try y.loadToEAX(writer);
// 50 push eax
try writer.write(@as(u8, 0x50));
try x.loadToEAX(writer);
// 50 push eax
try writer.write(@as(u8, 0x50));
// B844332211 mov eax,0x11223344
try writer.write(@as(u8, 0xB8));
try writer.write(@intCast(u32, @ptrToInt(API.setpix)));
// FFD0 call eax
try writer.write(@as(u8, 0xFF));
try writer.write(@as(u8, 0xD0));
// 83C444 add esp,byte +0x44
// pop*3
try writer.write(@as(u8, 0x83));
try writer.write(@as(u8, 0xC4));
try writer.write(@as(u8, 0x0C)); // pop 3 args
}
fn getpix(writer: *Writer, col: InstrOutput, x: InstrInput, y: InstrInput) WriterError!void {
// extern fn (x: u32, y: u32) u32
try y.loadToEAX(writer);
// 50 push eax
try writer.write(@as(u8, 0x50));
try x.loadToEAX(writer);
// 50 push eax
try writer.write(@as(u8, 0x50));
// B844332211 mov eax,0x11223344
try writer.write(@as(u8, 0xB8));
try writer.write(@intCast(u32, @ptrToInt(API.getpix)));
// FFD0 call eax
try writer.write(@as(u8, 0xFF));
try writer.write(@as(u8, 0xD0));
// 83C455 add esp,byte +0x55
try writer.write(@as(u8, 0x83));
try writer.write(@as(u8, 0xC4));
try writer.write(@as(u8, 0x08)); // pop 2 args
try col.saveFromEAX(writer);
}
fn flushpix(writer: *Writer) WriterError!void {
// extern fn () void
// B844332211 mov eax,0x11223344
try writer.write(@as(u8, 0xB8));
try writer.write(@intCast(u32, @ptrToInt(API.flushpix)));
// FFD0 call eax
try writer.write(@as(u8, 0xFF));
try writer.write(@as(u8, 0xD0));
}
fn trace(writer: *Writer, on: InstrInput) WriterError!void {
// extern fn (x: u32, y: u32, col: u32) void
try on.loadToEAX(writer);
// 50 push eax
try writer.write(@as(u8, 0x50));
// B844332211 mov eax,0x11223344
try writer.write(@as(u8, 0xB8));
try writer.write(@intCast(u32, @ptrToInt(API.trace)));
// FFD0 call eax
try writer.write(@as(u8, 0xFF));
try writer.write(@as(u8, 0xD0));
// 83C444 add esp,byte +0x04
try writer.write(@as(u8, 0x83));
try writer.write(@as(u8, 0xC4));
try writer.write(@as(u8, 0x04)); // pop 1 args
}
fn exit(writer: *Writer) WriterError!void {
// B844332211 mov eax,0x11223344
try writer.write(@as(u8, 0xB8));
try writer.write(@intCast(u32, @ptrToInt(API.exit)));
// FFE0 jmp eax
try writer.write(@as(u8, 0xFF));
try writer.write(@as(u8, 0xE0));
}
};
|
0 | repos/Ziguana-Game-System/old-version/kernel | repos/Ziguana-Game-System/old-version/kernel/src/enum-array.zig | pub fn EnumArray(comptime TKey: type, comptime TValue: type) type {
const KeyInfo = @typeInfo(TKey).Enum;
return struct {
const This = @This();
fields: [KeyInfo.fields.len]TValue,
fn keyToIndex(key: TKey) usize {
inline for (KeyInfo.fields) |fld, i| {
if (@intToEnum(TKey, fld.value) == key)
return i;
}
unreachable;
}
pub fn init(comptime value: TValue) This {
return This{
.fields = [_]TValue{value} ** KeyInfo.fields.len,
};
}
pub fn initDefault() This {
return This{
.fields = [_]TValue{TValue{}} ** KeyInfo.fields.len,
};
}
pub const KV = struct {
key: TKey,
value: TValue,
};
pub fn initMap(comptime initSet: []const KV) This {
var array = This{ .fields = undefined };
if (initSet.len != KeyInfo.fields.len)
@compileError("Initializer map must have exact one entry per enum entry!");
comptime var fields_inited = [_]bool{false} ** KeyInfo.fields.len;
inline for (initSet) |kv| {
const i = comptime keyToIndex(kv.key);
if (fields_inited[i])
@compileError("Initializer map must have exact one entry per enum entry!");
fields_inited[i] = true;
array.fields[i] = kv.value;
}
return array;
}
pub fn at(this: This, index: TKey) TValue {
return this.fields[keyToIndex(index)];
}
pub fn atMut(this: *This, index: TKey) *TValue {
return &this.fields[keyToIndex(index)];
}
pub fn set(this: *This, index: TKey, val: TValue) void {
this.fields[keyToIndex(index)] = val;
}
};
}
const std = @import("std");
test "EnumArray.init" {
const E = enum {
a,
b,
};
const T = EnumArray(E, i32);
var list = T.init(42);
std.debug.assert(list.at(.a) == 42);
std.debug.assert(list.at(.b) == 42);
}
test "EnumArray" {
const E = enum {
a,
b,
};
const T = EnumArray(E, i32);
// _ = T.initDefault();
var list = T.initMap(([_]T.KV{
T.KV{
.key = .a,
.value = 1,
}, T.KV{
.key = .b,
.value = 2,
},
})[0..]);
std.debug.assert(list.at(.a) == 1);
std.debug.assert(list.at(.b) == 2);
}
|
0 | repos/Ziguana-Game-System/old-version/kernel | repos/Ziguana-Game-System/old-version/kernel/src/text-painter.zig | const VGA = @import("vga.zig");
const Glyph = packed struct {
const This = @This();
rows: [8]u8,
fn getPixel(this: This, x: u3, y: u3) u1 {
return @truncate(u1, (this.rows[y] >> x) & 1);
}
};
const stdfont = @bitCast([128]Glyph, @as([1024]u8, @embedFile("stdfont.bin").*));
pub fn drawChar(x: isize, y: isize, char: u8, color: VGA.Color) void {
if (x <= -6 or y <= -6 or x >= VGA.width or y >= VGA.height)
return;
const safe_c = if (char < 128) char else 0x1F;
var dy: u3 = 0;
while (dy < 7) : (dy += 1) {
var dx: u3 = 0;
while (dx < 6) : (dx += 1) {
if (VGA.isInBounds(x + @as(isize, dx), y + @as(isize, dy))) {
if (stdfont[safe_c].getPixel(dx, dy) == 1) {
VGA.setPixel(@intCast(usize, x) + dx, @intCast(usize, y) + dy, color);
}
}
}
}
}
pub const PaintOptions = struct {
color: VGA.Color = 1,
horizontalAlignment: enum {
left,
middle,
right,
} = .left,
verticalAlignment: enum {
top,
middle,
bottom,
} = .top,
};
/// Draws a string with formatting (alignment)
pub fn drawString(x: isize, y: isize, text: []const u8, options: PaintOptions) void {
const startX = switch (options.horizontalAlignment) {
.left => x,
.middle => x - @intCast(isize, 6 * text.len / 2),
.right => x - @intCast(isize, 6 * text.len),
};
const startY = switch (options.verticalAlignment) {
.top => y,
.middle => y + 4,
.bottom => y + 8,
};
for (text) |c, i| {
const left = startX + @intCast(isize, 6 * i);
if (left <= -6)
continue;
const top = startY;
drawChar(left, top, c, options.color);
}
}
|
0 | repos/Ziguana-Game-System/old-version/kernel | repos/Ziguana-Game-System/old-version/kernel/src/chs.zig | const Error = error{AddressNotOnDevice};
pub const DriveLayout = struct {
headCount: usize,
cylinderCount: usize,
sectorCount: usize,
};
pub const CHS = struct {
cylinder: usize, // starts at 0
head: usize, // starts at 0
sector: usize, // starts at 1
};
pub fn lba2chs(layout: DriveLayout, lba: usize) Error!CHS {
if (lba >= layout.headCount * layout.cylinderCount * layout.sectorCount)
return error.AddressNotOnDevice;
return CHS{
.cylinder = lba / (layout.headCount * layout.sectorCount),
.head = ((lba % (layout.headCount * layout.sectorCount)) / layout.sectorCount),
.sector = ((lba % (layout.headCount * layout.sectorCount)) % layout.sectorCount + 1),
};
}
pub fn chs2lba(layout: DriveLayout, chs: CHS) Error!usize {
if (chs.sector < 1 or chs.sector > layout.sectorCount)
return error.AddressNotOnDevice;
if (chs.head >= layout.headCount)
return error.AddressNotOnDevice;
if (chs.cylinder >= layout.cylinderCount)
return error.AddressNotOnDevice;
return layout.sectorCount * layout.headCount * chs.cylinder + layout.sectorCount * chs.head + chs.sector - 1;
}
const std = @import("std");
test "lba2chs" {
const layout = DriveLayout{
.headCount = 2,
.cylinderCount = 3,
.sectorCount = 5,
};
std.debug.assert(std.meta.eql(try lba2chs(layout, 0), CHS{ .cylinder = 0, .head = 0, .sector = 1 }));
std.debug.assert(std.meta.eql(try lba2chs(layout, 4), CHS{ .cylinder = 0, .head = 0, .sector = 5 }));
std.debug.assert(std.meta.eql(try lba2chs(layout, 5), CHS{ .cylinder = 0, .head = 1, .sector = 1 }));
std.debug.assert(std.meta.eql(try lba2chs(layout, 10), CHS{ .cylinder = 1, .head = 0, .sector = 1 }));
std.debug.assert(std.meta.eql(try lba2chs(layout, 3), CHS{ .cylinder = 0, .head = 0, .sector = 4 }));
std.debug.assert(std.meta.eql(try lba2chs(layout, 7), CHS{ .cylinder = 0, .head = 1, .sector = 3 }));
std.debug.assert(std.meta.eql(try lba2chs(layout, 19), CHS{ .cylinder = 1, .head = 1, .sector = 5 }));
}
test "chs2lba" {
const layout = DriveLayout{
.headCount = 2,
.cylinderCount = 3,
.sectorCount = 5,
};
std.debug.assert((try chs2lba(layout, CHS{ .cylinder = 0, .head = 0, .sector = 5 })) == 4);
std.debug.assert((try chs2lba(layout, CHS{ .cylinder = 0, .head = 1, .sector = 1 })) == 5);
std.debug.assert((try chs2lba(layout, CHS{ .cylinder = 1, .head = 0, .sector = 1 })) == 10);
std.debug.assert((try chs2lba(layout, CHS{ .cylinder = 0, .head = 0, .sector = 4 })) == 3);
std.debug.assert((try chs2lba(layout, CHS{ .cylinder = 0, .head = 1, .sector = 3 })) == 7);
std.debug.assert((try chs2lba(layout, CHS{ .cylinder = 1, .head = 1, .sector = 5 })) == 19);
}
|
0 | repos/Ziguana-Game-System/old-version/kernel | repos/Ziguana-Game-System/old-version/kernel/src/keyboard.zig | const io = @import("io.zig");
const Interrupts = @import("interrupts.zig");
const Terminal = @import("text-terminal.zig");
fn sendCommand(cmd: u8) void {
// Warten bis die Tastatur bereit ist, und der Befehlspuffer leer ist
while ((io.in(u8, 0x64) & 0x2) != 0) {}
io.out(u8, 0x60, cmd);
}
pub fn init() void {
// IRQ-Handler fuer Tastatur-IRQ(1) registrieren
Interrupts.setIRQHandler(1, kbdIrqHandler);
// Interrupts.setkbdIrqHandler(12, mouseIrqHandler);
// Tastaturpuffer leeren
while ((io.in(u8, 0x64) & 0x1) != 0) {
_ = io.in(u8, 0x60);
}
// Tastatur aktivieren
sendCommand(0xF4);
Interrupts.enableIRQ(1);
}
pub const KeyEvent = struct {
set: ScancodeSet,
scancode: u16,
char: ?u8,
};
var foo: u32 = 0;
var lastKeyPress: ?KeyEvent = null;
pub fn getKey() ?KeyEvent {
_ = @atomicLoad(u32, &foo, .SeqCst);
var copy = lastKeyPress;
lastKeyPress = null;
return copy;
}
const ScancodeSet = enum {
default,
extended0,
extended1,
};
const ScancodeInfo = packed struct {
unused: u8,
lowerCase: u8,
upperCase: u8,
graphCase: u8,
};
const scancodeTableDefault = @bitCast([128]ScancodeInfo, @as([512]u8, @embedFile("stdkbd_default.bin").*));
var isShiftPressed = false;
var isAltPressed = false;
var isControlPressed = false;
var isGraphPressed = false;
fn pushScancode(set: ScancodeSet, scancode: u16, isRelease: bool) void {
if (set == .default) {
switch (scancode) {
29 => isControlPressed = !isRelease,
42 => isShiftPressed = !isRelease,
56 => isAltPressed = !isRelease,
else => {},
}
} else if (set == .extended0) {
switch (scancode) {
56 => isGraphPressed = !isRelease,
else => {},
}
}
if (!isRelease) {
var keyinfo = if (scancode < 128 and set == .default) scancodeTableDefault[scancode] else ScancodeInfo{
.unused = undefined,
.lowerCase = 0,
.upperCase = 0,
.graphCase = 0,
};
var chr = if (isGraphPressed) keyinfo.graphCase else if (isShiftPressed) keyinfo.upperCase else keyinfo.lowerCase;
lastKeyPress = KeyEvent{
.set = set,
.scancode = scancode,
.char = if (chr != 0) chr else null,
};
}
// Zum Testen sollte folgendes verwendet werden:
// Terminal.println("[kbd:{}/{}/{}]", set, scancode, if (isRelease) "R" else "P");
}
pub const FKey = enum {
F1,
F2,
F3,
F4,
F5,
F6,
F7,
F8,
F9,
F10,
F11,
F12,
};
const IrqState = enum {
default,
receiveE0,
receiveE1_Byte0,
receiveE1_Byte1,
};
var irqState: IrqState = .default;
var e1Byte0: u8 = undefined;
fn kbdIrqHandler(cpu: *Interrupts.CpuState) *Interrupts.CpuState {
var newCpu = cpu;
const inputData = io.in(u8, 0x60);
irqState = switch (irqState) {
.default => switch (inputData) {
0xE0 => IrqState.receiveE0,
0xE1 => IrqState.receiveE1_Byte0,
else => blk: {
const scancode = inputData & 0x7F;
const isRelease = (inputData & 0x80 != 0);
switch (scancode) {
59...68, 87, 88 => {
if (isRelease)
return cpu;
return @import("root").handleFKey(cpu, switch (scancode) {
59 => FKey.F1,
60 => FKey.F2,
61 => FKey.F3,
62 => FKey.F4,
63 => FKey.F5,
64 => FKey.F6,
65 => FKey.F7,
66 => FKey.F8,
67 => FKey.F9,
68 => FKey.F10,
87 => FKey.F11,
88 => FKey.F12,
else => unreachable,
});
},
else => pushScancode(.default, scancode, isRelease),
}
break :blk IrqState.default;
},
},
.receiveE0 => switch (inputData) {
// these are "fake shifts"
0x2A, 0x36 => IrqState.default,
else => blk: {
pushScancode(.extended0, inputData & 0x7F, (inputData & 0x80 != 0));
break :blk IrqState.default;
},
},
.receiveE1_Byte0 => blk: {
e1Byte0 = inputData;
break :blk .receiveE1_Byte1;
},
.receiveE1_Byte1 => blk: {
const scancode = (@as(u16, inputData) << 8) | e1Byte0;
pushScancode(.extended1, scancode, (inputData & 0x80) != 0);
break :blk .default;
},
};
return newCpu;
}
fn mouseIrqHandler(cpu: *Interrupts.CpuState) *Interrupts.CpuState {
@panic("EEK, A MOUSE!");
}
|
0 | repos/Ziguana-Game-System/old-version/kernel | repos/Ziguana-Game-System/old-version/kernel/src/pci.zig | const std = @import("std");
const IO = @import("io.zig");
const Terminal = @import("text-terminal.zig");
const PCI_CONFIG_DATA = 0x0CFC;
const PCI_CONFIG_ADDRESS = 0x0CF8;
fn pci_read(bus: u8, device: u5, function: u3, register: u8) u32 {
const address = 0x80000000 | (@as(u32, bus) << 16) | (@as(u32, device) << 11) | (@as(u32, function) << 8) | (register & 0xFC);
IO.out(u32, PCI_CONFIG_ADDRESS, address);
return IO.in(u32, PCI_CONFIG_DATA);
}
fn pci_write(bus: u8, device: u5, function: u3, register: u8, value: u32) void {
const address = 0x80000000 | (@as(u32, bus) << 16) | (@as(u32, device) << 11) | (@as(u32, function) << 8) | (register & 0xFC);
IO.out(u32, PCI_CONFIG_ADDRESS, address);
IO.out(u32, PCI_CONFIG_DATA, value);
}
pub fn init() void {
var bus: u8 = 0;
while (bus < 10) {
var device: u5 = 0;
while (true) {
var function: u3 = 0;
while (true) {
const vendorId_deviceId = pci_read(bus, device, function, 0x00);
const vendorId = @truncate(u16, vendorId_deviceId & 0xFFFF);
const deviceId = @truncate(u16, vendorId_deviceId >> 16);
// skip when 0, 1 or FFFF
switch (vendorId) {
0x0000, 0x0001, 0xFFFF => {
if (@addWithOverflow(u3, function, 1, &function))
break;
continue;
},
else => {},
}
Terminal.print("{:0>2}:{:0>2}.{:0>2}: {X:0>4}:{X:0>4}", .{ bus, device, function, vendorId, deviceId });
const HeaderInfo = packed struct {
command: u16,
status: u16,
revision: u8,
classcode: u24,
cacheLineSize: u8,
latencyTimer: u8,
headerType: u7,
isMultifunction: bool,
bist: u8,
};
var infopack = [_]u32{
pci_read(bus, device, function, 0x04),
pci_read(bus, device, function, 0x08),
pci_read(bus, device, function, 0x0C),
};
const header = @bitCast(HeaderInfo, infopack);
Terminal.print(" [{X:0>6}]", .{header.classcode});
const cc = ClassCodeDescription.lookUp(header.classcode);
if (cc.class != null) {
Terminal.print(" {}", .{cc.programmingInterface orelse cc.subclass orelse cc.class});
}
Terminal.println("", .{});
const desc = DeviceDescription.lookUp(vendorId, deviceId);
if (desc.vendor != null) {
Terminal.println(" {}", .{desc.device orelse desc.vendor});
}
if (!header.isMultifunction)
break;
if (@addWithOverflow(u3, function, 1, &function))
break;
}
if (@addWithOverflow(u5, device, 1, &device))
break;
}
if (@addWithOverflow(u8, bus, 1, &bus))
break;
}
}
const pci_device_database = @embedFile("../../data/devices.dat");
const pci_classcode_database = @embedFile("../../data/classes.dat");
const DeviceDescription = struct {
vendor: ?[]const u8,
device: ?[]const u8,
pub fn lookUp(vendorId: u16, deviceId: u16) DeviceDescription {
var iterator = std.mem.tokenize(pci_device_database, "\n");
var desc = DeviceDescription{
.vendor = null,
.device = null,
};
var vendorIdStrBuf = " ".*;
const vendorIdStr = std.fmt.bufPrint(vendorIdStrBuf[0..], "{x:0>4}", .{vendorId}) catch unreachable;
var deviceIdStrBuf = " ".*;
const deviceIdStr = std.fmt.bufPrint(deviceIdStrBuf[0..], "{x:0>4}", .{deviceId}) catch unreachable;
while (iterator.next()) |line| {
if (desc.vendor != null) {
// search device
if (line[0] != '\t') // found another vendor, don't have a matching device!
return desc;
if (std.mem.startsWith(u8, line[1..], deviceIdStr)) {
desc.device = line[7..];
return desc;
}
} else {
// search vendor
if (std.mem.startsWith(u8, line, vendorIdStr)) {
desc.vendor = line[6..];
}
}
}
return desc;
}
};
const ClassCodeDescription = struct {
class: ?[]const u8,
subclass: ?[]const u8,
programmingInterface: ?[]const u8,
pub fn lookUp(classcode: u24) ClassCodeDescription {
var iterator = std.mem.tokenize(pci_classcode_database, "\n");
var desc = ClassCodeDescription{
.class = null,
.subclass = null,
.programmingInterface = null,
};
var classCodeStrBuf = " ".*;
const classCodeStr = std.fmt.bufPrint(classCodeStrBuf[0..], "{x:0>6}", .{classcode}) catch unreachable;
while (iterator.next()) |line| {
if (desc.subclass != null) {
// search programmingInterface
if (line[0] != '\t') // found another class, don't have a matching classcode!
return desc;
if (line[1] != '\t') // found another subclass, don't have a matching classcode!
return desc;
if (std.mem.startsWith(u8, line[1..], classCodeStr[4..6])) {
desc.programmingInterface = line[5..];
return desc;
}
} else if (desc.class != null) {
// search subclass
if (line[0] != '\t') // found another class, don't have a matching classcode!
return desc;
if (std.mem.startsWith(u8, line[1..], classCodeStr[2..4])) {
desc.subclass = line[5..];
}
} else {
// search class
if (std.mem.startsWith(u8, line, classCodeStr[0..2])) {
desc.class = line[4..];
}
}
}
return desc;
}
};
|
0 | repos/Ziguana-Game-System/old-version/kernel | repos/Ziguana-Game-System/old-version/kernel/src/io.zig | /// Implements the `out` instruction for an x86 processor.
/// `type` must be one of `u8`, `u16`, `u32`, `port` is the
/// port number and `value` will be sent to that port.
pub fn out(comptime T: type, port: u16, value: T) void {
switch (T) {
u8 => return outb(port, value),
u16 => return outw(port, value),
u32 => return outl(port, value),
else => @compileError("Only u8, u16 or u32 are allowed for port I/O!"),
}
}
/// Implements the `in` instruction for an x86 processor.
/// `type` must be one of `u8`, `u16`, `u32`, `port` is the
/// port number and the value received from that port will be returned.
pub fn in(comptime T: type, port: u16) T {
switch (T) {
u8 => return inb(port),
u16 => return inw(port),
u32 => return inl(port),
else => @compileError("Only u8, u16 or u32 are allowed for port I/O!"),
}
}
fn outb(port: u16, data: u8) void {
asm volatile ("outb %[data], %[port]"
:
: [port] "{dx}" (port),
[data] "{al}" (data)
);
}
fn outw(port: u16, data: u16) void {
asm volatile ("outw %[data], %[port]"
:
: [port] "{dx}" (port),
[data] "{ax}" (data)
);
}
fn outl(port: u16, data: u32) void {
asm volatile ("outl %[data], %[port]"
:
: [port] "{dx}" (port),
[data] "{eax}" (data)
);
}
fn inb(port: u16) u8 {
return asm volatile ("inb %[port], %[ret]"
: [ret] "={al}" (-> u8)
: [port] "{dx}" (port)
);
}
fn inw(port: u16) u16 {
return asm volatile ("inw %[port], %[ret]"
: [ret] "={ax}" (-> u16)
: [port] "{dx}" (port)
);
}
fn inl(port: u16) u32 {
return asm volatile ("inl %[port], %[ret]"
: [ret] "={eax}" (-> u32)
: [port] "{dx}" (port)
);
}
|
0 | repos/Ziguana-Game-System/old-version/kernel | repos/Ziguana-Game-System/old-version/kernel/src/block-allocator.zig | const Bitmap = @import("bitmap.zig").Bitmap;
pub fn BlockAllocator(comptime T: type, comptime blockCount: usize) type {
return struct {
const This = @This();
const Element = T;
const BlockCount = blockCount;
bitmap: Bitmap(BlockCount),
elements: [BlockCount]T,
pub fn init() This {
var this = This{
.bitmap = Bitmap(BlockCount).init(.free),
.elements = undefined,
};
return this;
}
/// free all objects
pub fn reset(this: *This) void {
this.bitmap = Bitmap(BlockCount).init(.free);
}
/// allocate single object
pub fn alloc(this: *This) !*T {
const idx = this.bitmap.alloc() orelse return error.OutOfMemory;
return &this.elements[idx];
}
/// free previously allocated object
pub fn free(this: *This, obj: *T) void {
const obj_p = @ptrCast([*]T, obj);
const root = @ptrCast([*]T, &this.elements);
if (@ptrToInt(obj_p) < @ptrToInt(root) or @ptrToInt(obj_p) >= @ptrToInt(root + BlockCount))
@panic("Object was not allocated with this allocator!");
const idx = (@ptrToInt(obj_p) - @ptrToInt(root)) / @sizeOf(T);
this.bitmap.free(idx);
}
};
}
|
0 | repos/Ziguana-Game-System/old-version/kernel | repos/Ziguana-Game-System/old-version/kernel/src/main.zig | const std = @import("std");
const lola = @import("lola");
const Terminal = @import("text-terminal.zig");
const Multiboot = @import("multiboot.zig");
const VGA = @import("vga.zig");
const GDT = @import("gdt.zig");
const Interrupts = @import("interrupts.zig");
const Keyboard = @import("keyboard.zig");
const SerialPort = @import("serial-port.zig");
const CodeEditor = @import("code-editor.zig");
const Timer = @import("timer.zig");
const SplashScreen = @import("splashscreen.zig");
const Assembler = @import("assembler.zig");
const EnumArray = @import("enum-array.zig").EnumArray;
const PCI = @import("pci.zig");
const CMOS = @import("cmos.zig");
const FDC = @import("floppy-disk-controller.zig");
const Heap = @import("heap.zig");
const PMM = @import("pmm.zig");
const VMM = @import("vmm.zig");
const ATA = @import("ata.zig");
const ZGSFS = @import("zgs-fs.zig");
usingnamespace @import("block-device.zig");
export var multibootHeader align(4) linksection(".multiboot") = Multiboot.Header.init();
var usercodeValid: bool = false;
var registers: [16]u32 = [_]u32{0} ** 16;
pub fn getRegisterAddress(register: u4) u32 {
return @ptrToInt(®isters[register]);
}
var enable_live_tracing = false;
pub fn milliTimestamp() u64 {
return Timer.ticks;
}
pub const assembler_api = struct {
pub fn flushpix() callconv(.C) void {
switch (vgaApi) {
.buffered => VGA.swapBuffers(),
else => {},
}
}
pub fn trace(value: u32) callconv(.C) void {
switch (value) {
0, 1 => {
enable_live_tracing = (value != 0);
},
2 => vgaApi = .immediate,
3 => vgaApi = .buffered,
else => {
Terminal.println("trace({})", .{value});
},
}
}
pub fn setpix(x: u32, y: u32, col: u32) callconv(.C) void {
// Terminal.println("setpix({},{},{})", x, y, col);
if (vgaApi == .immediate) {
VGA.setPixelDirect(x, y, @truncate(u4, col));
}
VGA.setPixel(x, y, @truncate(u4, col));
}
pub fn getpix(x: u32, y: u32) callconv(.C) u32 {
// Terminal.println("getpix({},{})", x, y);
return VGA.getPixel(x, y);
}
pub fn gettime() callconv(.C) u32 {
// systemTicks is in 0.1 sec steps, but we want ms
const time = Timer.ticks;
// Terminal.println("gettime() = {}", time);
return time;
}
pub fn getkey() callconv(.C) u32 {
const keycode = if (Keyboard.getKey()) |key|
key.scancode | switch (key.set) {
.default => @as(u32, 0),
.extended0 => @as(u32, 0x10000),
.extended1 => @as(u32, 0x20000),
}
else
@as(u32, 0);
// Terminal.println("getkey() = 0x{X:0>5}", keycode);
return keycode;
}
pub fn exit() callconv(.C) noreturn {
Terminal.println("User code finished!", .{});
haltForever();
}
};
const VgaApi = enum {
buffered,
immediate,
};
var vgaApi: VgaApi = .immediate;
pub const enable_assembler_tracing = false;
pub var currentAssemblerLine: ?usize = null;
pub fn debugCall(cpu: *Interrupts.CpuState) void {
if (!enable_live_tracing)
return;
currentAssemblerLine = @intToPtr(*u32, cpu.eip).*;
// Terminal.println("-----------------------------");
// Terminal.println("Line: {}", currentAssemblerLine);
// Terminal.println("CPU:\r\n{}", cpu);
// Terminal.println("Registers:");
// for (registers) |reg, i| {
// Terminal.println("r{} = {}", i, reg);
// }
// skip 4 bytes after interrupt. this is the assembler line number!
cpu.eip += 4;
}
// const developSource = @embedFile("../../gasm/concept.asm");
const Task = struct {
entryPoint: fn () callconv(.C) noreturn = undefined,
};
pub const TaskId = enum {
splash,
shell,
codeEditor,
spriteEditor,
tilemapEditor,
codeRunner,
};
fn editorNotImplementedYet() callconv(.C) noreturn {
Terminal.println("This editor is not implemented yet!", .{});
while (true) {
// wait for interrupt
asm volatile ("hlt");
}
}
const ObjectPool = lola.runtime.ObjectPool(.{});
fn compileAndRunLolaSource() !void {
var arena = std.heap.ArenaAllocator.init(Heap.allocator);
defer arena.deinit();
var buffer = std.ArrayList(u8).init(&arena.allocator);
defer buffer.deinit();
try CodeEditor.saveTo(buffer.writer());
const allocator = &arena.allocator;
var diagnostics = lola.compiler.Diagnostics.init(allocator);
defer diagnostics.deinit();
Terminal.println("Compiling code...", .{});
var compile_unit = (try lola.compiler.compile(allocator, &diagnostics, "code", buffer.items)) orelse {
for (diagnostics.messages.items) |msg| {
Terminal.println("{}", .{msg});
}
return;
};
defer compile_unit.deinit();
Terminal.println("Initializing runtime...", .{});
var pool = ObjectPool.init(allocator);
defer pool.deinit();
var env = try lola.runtime.Environment.init(allocator, &compile_unit, pool.interface());
defer env.deinit();
try lola.libs.std.install(&env, allocator);
try env.installFunction("Print", lola.runtime.Function.initSimpleUser(struct {
fn invoke(environment: *const lola.runtime.Environment, context: lola.runtime.Context, args: []const lola.runtime.Value) anyerror!lola.runtime.Value {
for (args) |value, i| {
switch (value) {
.string => |str| Terminal.write(str.contents),
else => Terminal.print("{}", .{value}),
}
}
Terminal.println("", .{});
return .void;
}
}.invoke));
try env.installFunction("Clear", lola.runtime.Function.wrap(VGA.clear));
try env.installFunction("GetPixel", lola.runtime.Function.wrap(VGA.getPixel));
try env.installFunction("SetPixel", lola.runtime.Function.wrap(VGA.setPixel));
try env.installFunction("SwapBuffers", lola.runtime.Function.wrap(VGA.swapBuffers));
Terminal.println("Start execution...", .{});
var vm = try lola.runtime.VM.init(allocator, &env);
defer vm.deinit();
while (true) {
var result = vm.execute(100_000) catch |err| {
Terminal.println("LoLa panic: {}", .{@errorName(err)});
return;
};
pool.clearUsageCounters();
try pool.walkEnvironment(env);
try pool.walkVM(vm);
pool.collectGarbage();
switch (result) {
.completed => break,
.exhausted => continue,
.paused => continue,
}
}
Terminal.println("User code execution finished.", .{});
}
fn executeUsercode() callconv(.C) noreturn {
compileAndRunLolaSource() catch |err| {
Terminal.println("Failed to save user code: {}", .{err});
};
while (true) {
// wait for interrupt
asm volatile ("hlt");
}
// if (Assembler.assemble(&arena.allocator, buffer.items, VMM.getUserSpace(), null)) {
// arena.deinit();
// Terminal.println("Assembled code successfully!", .{});
// // Terminal.println("Memory required: {} bytes!", fba.end_index);
// Terminal.println("Setup graphics...", .{});
// // Load dawnbringers 16 color palette
// // see: https://lospec.com/palette-list/dawnbringer-16
// VGA.loadPalette(&comptime [_]VGA.RGB{
// VGA.RGB.parse("#140c1c") catch unreachable, // 0 = black
// VGA.RGB.parse("#442434") catch unreachable, // 1 = dark purple-brown
// VGA.RGB.parse("#30346d") catch unreachable, // 2 = blue
// VGA.RGB.parse("#4e4a4e") catch unreachable, // 3 = gray
// VGA.RGB.parse("#854c30") catch unreachable, // 4 = brown
// VGA.RGB.parse("#346524") catch unreachable, // 5 = green
// VGA.RGB.parse("#d04648") catch unreachable, // 6 = salmon
// VGA.RGB.parse("#757161") catch unreachable, // 7 = khaki
// VGA.RGB.parse("#597dce") catch unreachable, // 8 = baby blue
// VGA.RGB.parse("#d27d2c") catch unreachable, // 9 = orange
// VGA.RGB.parse("#8595a1") catch unreachable, // 10 = light gray
// VGA.RGB.parse("#6daa2c") catch unreachable, // 11 = grass green
// VGA.RGB.parse("#d2aa99") catch unreachable, // 12 = skin
// VGA.RGB.parse("#6dc2ca") catch unreachable, // 13 = bright blue
// VGA.RGB.parse("#dad45e") catch unreachable, // 14 = yellow
// VGA.RGB.parse("#deeed6") catch unreachable, // 15 = white
// });
// Terminal.println("Start user code...", .{});
// asm volatile ("jmp 0x40000000");
// unreachable;
// } else |err| {
// arena.deinit();
// buffer.deinit();
// Terminal.println("Failed to assemble user code: {}", .{err});
// while (true) {
// // wait for interrupt
// asm volatile ("hlt");
// }
// }
}
fn executeTilemapEditor() callconv(.C) noreturn {
var time: usize = 0;
var color: VGA.Color = 1;
while (true) : (time += 1) {
if (Keyboard.getKey()) |key| {
if (key.set == .default and key.scancode == 57) {
// space
if (@addWithOverflow(VGA.Color, color, 1, &color)) {
color = 1;
}
}
}
var y: usize = 0;
while (y < VGA.height) : (y += 1) {
var x: usize = 0;
while (x < VGA.width) : (x += 1) {
// c = @truncate(u4, (x + offset_x + dx) / 32 + (y + offset_y + dy) / 32);
const c = if (y > ((Timer.ticks / 10) % 200)) color else 0;
VGA.setPixel(x, y, c);
}
}
VGA.swapBuffers();
}
}
const TaskList = EnumArray(TaskId, Task);
const taskList = TaskList.initMap(&([_]TaskList.KV{
TaskList.KV{
.key = .splash,
.value = Task{
.entryPoint = SplashScreen.run,
},
},
TaskList.KV{
.key = .shell,
.value = Task{
.entryPoint = editorNotImplementedYet,
},
},
TaskList.KV{
.key = .codeEditor,
.value = Task{
.entryPoint = CodeEditor.run,
},
},
TaskList.KV{
.key = .spriteEditor,
.value = Task{
.entryPoint = editorNotImplementedYet,
},
},
TaskList.KV{
.key = .tilemapEditor,
.value = Task{
.entryPoint = executeTilemapEditor,
},
},
TaskList.KV{
.key = .codeRunner,
.value = Task{
.entryPoint = executeUsercode,
},
},
}));
var userStack: [8192]u8 align(16) = undefined;
pub fn handleFKey(cpu: *Interrupts.CpuState, key: Keyboard.FKey) *Interrupts.CpuState {
return switch (key) {
.F1 => switchTask(.shell),
.F2 => switchTask(.codeEditor),
.F3 => switchTask(.spriteEditor),
.F4 => switchTask(.tilemapEditor),
.F5 => switchTask(.codeRunner),
.F12 => blk: {
if (Terminal.enable_serial) {
Terminal.println("Disable serial... Press F12 to enable serial again!", .{});
Terminal.enable_serial = false;
} else {
Terminal.enable_serial = true;
Terminal.println("Serial output enabled!", .{});
}
break :blk cpu;
},
else => cpu,
};
}
pub fn switchTask(task: TaskId) *Interrupts.CpuState {
const Helper = struct {
fn createTask(stack: []u8, id: TaskId) *Interrupts.CpuState {
var newCpu = @ptrCast(*Interrupts.CpuState, stack.ptr + stack.len - @sizeOf(Interrupts.CpuState));
newCpu.* = Interrupts.CpuState{
.eax = 0,
.ebx = 0,
.ecx = 0,
.edx = 0,
.esi = 0,
.edi = 0,
.ebp = 0,
.eip = @ptrToInt(taskList.at(id).entryPoint),
.cs = 0x08,
.eflags = 0x202,
.interrupt = 0,
.errorcode = 0,
.esp = 0,
.ss = 0,
};
return newCpu;
}
};
var stack = userStack[0..];
return Helper.createTask(stack, task);
}
extern const __start: u8;
extern const __end: u8;
pub fn main() anyerror!void {
// HACK: this fixes some weird behaviour with "code running into userStack"
_ = userStack;
SerialPort.init(SerialPort.COM1, 9600, .none, .eight);
Terminal.clear();
Terminal.println("Kernel Range: {X:0>8} - {X:0>8}", .{ @ptrToInt(&__start), @ptrToInt(&__end) });
Terminal.println("Stack Size: {}", .{@as(u32, @sizeOf(@TypeOf(kernelStack)))});
// Terminal.println("User Stack: {X:0>8}", @ptrToInt(&userStack));
Terminal.println("Kernel Stack: {X:0>8}", .{@ptrToInt(&kernelStack)});
const flags = @ptrCast(*Multiboot.Structure.Flags, &multiboot.flags).*;
//const flags = @bitCast(Multiboot.Structure.Flags, multiboot.flags);
Terminal.print("Multiboot Structure: {*}\r\n", .{multiboot});
inline for (@typeInfo(Multiboot.Structure).Struct.fields) |fld| {
if (comptime !std.mem.eql(u8, comptime fld.name, "flags")) {
if (@field(flags, fld.name)) {
Terminal.print("\t{}\t= {}\r\n", .{ fld.name, @field(multiboot, fld.name) });
}
}
}
// Init PMM
// mark everything in the "memmap" as free
if (multiboot.flags != 0) {
var iter = multiboot.mmap.iterator();
while (iter.next()) |entry| {
if (entry.baseAddress + entry.length > 0xFFFFFFFF)
continue; // out of range
Terminal.println("mmap = {}", .{entry});
var start = std.mem.alignForward(@intCast(usize, entry.baseAddress), 4096); // only allocate full pages
var length = entry.length - (start - entry.baseAddress); // remove padded bytes
while (start < entry.baseAddress + length) : (start += 4096) {
PMM.mark(@intCast(usize, start), switch (entry.type) {
.available => PMM.Marker.free,
else => PMM.Marker.allocated,
});
}
}
}
Terminal.println("total memory: {} pages, {Bi}", .{ PMM.getFreePageCount(), PMM.getFreeMemory() });
// mark "ourself" used
{
var pos = @ptrToInt(&__start);
std.debug.assert(std.mem.isAligned(pos, 4096));
while (pos < @ptrToInt(&__end)) : (pos += 4096) {
PMM.mark(pos, .allocated);
}
}
// Mark MMIO area as allocated
{
var i: usize = 0x0000;
while (i < 0x10000) : (i += 0x1000) {
PMM.mark(i, .allocated);
}
}
{
Terminal.print("[ ] Initialize gdt...\r", .{});
GDT.init();
Terminal.println("[X", .{});
}
var pageDirectory = try VMM.init();
// map ourself into memory
{
var pos = @ptrToInt(&__start);
std.debug.assert(std.mem.isAligned(pos, 0x1000));
while (pos < @ptrToInt(&__end)) : (pos += 0x1000) {
try pageDirectory.mapPage(pos, pos, .readOnly);
}
}
// map VGA memory
{
var i: usize = 0xA0000;
while (i < 0xC0000) : (i += 0x1000) {
try pageDirectory.mapPage(i, i, .readWrite);
}
}
Terminal.print("[ ] Map user space memory...\r", .{});
try VMM.createUserspace(pageDirectory);
Terminal.println("[X", .{});
Terminal.print("[ ] Map heap memory...\r", .{});
try VMM.createHeap(pageDirectory);
Terminal.println("[X", .{});
Terminal.println("free memory: {} pages, {Bi}", .{ PMM.getFreePageCount(), PMM.getFreeMemory() });
Terminal.print("[ ] Enable paging...\r", .{});
VMM.enablePaging();
Terminal.println("[X", .{});
Terminal.print("[ ] Initialize heap memory...\r", .{});
Heap.init();
Terminal.println("[X", .{});
{
Terminal.print("[ ] Initialize idt...\r", .{});
Interrupts.init();
Terminal.println("[X", .{});
Terminal.print("[ ] Enable IRQs...\r", .{});
Interrupts.disableAllIRQs();
Interrupts.enableExternalInterrupts();
Terminal.println("[X", .{});
}
Terminal.print("[ ] Enable Keyboard...\r", .{});
Keyboard.init();
Terminal.println("[X", .{});
Terminal.print("[ ] Enable Timer...\r", .{});
Timer.init();
Terminal.println("[X", .{});
Terminal.print("[ ] Initialize CMOS...\r", .{});
CMOS.init();
Terminal.println("[X", .{});
CMOS.printInfo();
var drives = std.ArrayList(*BlockDevice).init(Heap.allocator);
Terminal.print("[ ] Initialize FDC...\r", .{});
for (try FDC.init()) |drive| {
try drives.append(drive);
}
Terminal.println("[X", .{});
Terminal.print("[ ] Initialize ATA...\r", .{});
for (try ATA.init()) |drive| {
try drives.append(drive);
}
Terminal.println("[X", .{});
Terminal.print("[ ] Scan drives...\n", .{});
{
const MBR = @import("mbr.zig");
var i: usize = 0;
for (drives.items) |drive| {
// if(drive.blockSize != 512)
// continue; // currently unsupported
var buf: [512]u8 = undefined;
try drive.read(drive, 0, buf[0..]);
// Check if the first block marks a "ZGS Partition"
const fsHeader = @ptrCast(*const ZGSFS.FSHeader, &buf);
if (fsHeader.isValid()) {
// yay! \o/
Terminal.println("found ZGSFS: {}", .{drive});
continue;
}
// Check if the first block contains a partition table
const mbrHeader = @ptrCast(*const MBR.BootSector, &buf);
if (mbrHeader.isValid()) {
// yay! \o/
Terminal.println("found MBR header: {}", .{drive});
var index: usize = 0;
while (index < 4) : (index += 1) {
const part = mbrHeader.getPartition(@truncate(u2, index));
if (part.id != 0) {
Terminal.println("Partition[{}] = {}", .{ index, part });
}
}
continue;
}
// Block device is useless to us :(
}
}
// Terminal.println("[X");
drives.deinit();
// Terminal.print("[ ] Initialize PCI...\r", .{});
// PCI.init();
// Terminal.println("[X", .{});
Terminal.print("Initialize text editor...\r\n", .{});
CodeEditor.init();
try CodeEditor.load("// Get ready to code!");
// Terminal.print("Press 'space' to start system...\r\n");
// while (true) {
// if (Keyboard.getKey()) |key| {
// if (key.char) |c|
// if (c == ' ')
// break;
// }
// }
Terminal.print("[ ] Initialize VGA...\r", .{});
// prevent the terminal to write data into the video memory
Terminal.enable_video = false;
VGA.init();
Terminal.println("[X", .{});
Terminal.println("[x] Disable serial debugging for better performance...", .{});
Terminal.println(" Press F12 to re-enable serial debugging!", .{});
// Terminal.enable_serial = false;
asm volatile ("int $0x45");
unreachable;
}
fn kmain() noreturn {
if (multibootMagic != 0x2BADB002) {
@panic("System was not bootet with multiboot!");
}
main() catch |err| {
Terminal.enable_serial = true;
Terminal.setColors(.white, .red);
Terminal.println("\r\n\r\nmain() returned {}!", .{err});
if (@errorReturnTrace()) |trace| {
for (trace.instruction_addresses) |addr, i| {
if (i >= trace.index)
break;
Terminal.println("Stack: {x: >8}", .{addr});
}
}
};
Terminal.enable_serial = true;
Terminal.println("system haltet, shut down now!", .{});
while (true) {
Interrupts.disableExternalInterrupts();
asm volatile ("hlt");
}
}
var kernelStack: [4096]u8 align(16) = undefined;
var multiboot: *Multiboot.Structure = undefined;
var multibootMagic: u32 = undefined;
export fn _start() callconv(.Naked) noreturn {
// DO NOT INSERT CODE BEFORE HERE
// WE MUST NOT MODIFY THE REGISTER CONTENTS
// BEFORE SAVING THEM TO MEMORY
multiboot = asm volatile (""
: [_] "={ebx}" (-> *Multiboot.Structure)
);
multibootMagic = asm volatile (""
: [_] "={eax}" (-> u32)
);
// FROM HERE ON WE ARE SAVE
const eos = @ptrToInt(&kernelStack) + @sizeOf(u8) * kernelStack.len;
asm volatile (""
:
: [stack] "{esp}" (eos)
);
kmain();
}
pub fn panic(msg: []const u8, error_return_trace: ?*std.builtin.StackTrace) noreturn {
@setCold(true);
Terminal.enable_serial = true;
Interrupts.disableExternalInterrupts();
Terminal.setColors(.white, .red);
Terminal.println("\r\n\r\nKERNEL PANIC: {}\r\n", .{msg});
// Terminal.println("Registers:");
// for (registers) |reg, i| {
// Terminal.println("r{} = {}", i, reg);
// }
const first_trace_addr = @returnAddress();
// const dwarf_info: ?*std.debug.DwarfInfo = getSelfDebugInfo() catch |err| blk: {
// Terminal.println("unable to get debug info: {}\n", @errorName(err));
// break :blk null;
// };
var it = std.debug.StackIterator.init(first_trace_addr, null);
while (it.next()) |return_address| {
Terminal.println("Stack: {x}", .{return_address});
// if (dwarf_info) |di| {
// std.debug.printSourceAtAddressDwarf(
// di,
// serial_out_stream,
// return_address,
// true, // tty color on
// printLineFromFile,
// ) catch |err| {
// Terminal.println("missed a stack frame: {}\n", @errorName(err));
// continue;
// };
// }
}
haltForever();
}
fn haltForever() noreturn {
while (true) {
Interrupts.disableExternalInterrupts();
asm volatile ("hlt");
}
}
|
0 | repos/Ziguana-Game-System/old-version/kernel | repos/Ziguana-Game-System/old-version/kernel/src/timer.zig | const Interrupts = @import("interrupts.zig");
const IO = @import("io.zig");
pub const freq = 1000; // 1 kHz
pub var ticks: usize = 0;
// right now roughly 100ms
fn handleTimerIRQ(cpu: *Interrupts.CpuState) *Interrupts.CpuState {
_ = @atomicRmw(usize, &ticks, .Add, 1, .Release);
return cpu;
}
pub fn wait(cnt: usize) void {
const dst = @atomicLoad(usize, &ticks, .Acquire) + cnt;
while (@atomicLoad(usize, &ticks, .Acquire) < dst) {
asm volatile ("hlt");
}
}
pub fn init() void {
const timer_limit = 1193182 / freq;
ticks = 0;
IO.out(u8, 0x43, 0x34); // Binary, Mode 2, LSB first, Channel 0
IO.out(u8, 0x40, @truncate(u8, timer_limit & 0xFF));
IO.out(u8, 0x40, @truncate(u8, timer_limit >> 8));
Interrupts.setIRQHandler(0, handleTimerIRQ);
Interrupts.enableIRQ(0);
}
|
0 | repos/Ziguana-Game-System/old-version/kernel | repos/Ziguana-Game-System/old-version/kernel/src/block-iterator.zig | const std = @import("std");
pub const IteratorKind = enum {
mutable,
constant,
};
pub fn BlockIterator(kind: IteratorKind) type {
return struct {
const This = @This();
const Slice = switch (kind) {
.mutable => []u8,
.constant => []const u8,
};
slice: Slice,
offset: usize,
blockSize: usize,
block: usize,
pub fn init(block: usize, buffer: Slice, blockSize: usize) !This {
if (!std.math.isPowerOfTwo(blockSize))
return error.BlockSizeMustBePowerOfTwo;
if (!std.mem.isAligned(buffer.len, blockSize))
return error.BufferLengthMustBeMultipleOfBlockSize;
return This{
.slice = buffer,
.offset = 0,
.blockSize = blockSize,
.block = block,
};
}
pub fn next(this: *This) ?Block {
if (this.offset >= this.slice.len)
return null;
var block = Block{
.block = this.block,
.slice = this.slice[this.offset .. this.offset + this.blockSize],
};
this.offset += this.blockSize;
this.block += 1;
return block;
}
pub const Block = struct {
slice: Slice,
block: usize,
};
};
}
|
0 | repos/Ziguana-Game-System/old-version/kernel | repos/Ziguana-Game-System/old-version/kernel/src/ata.zig | const std = @import("std");
const IO = @import("io.zig");
const TextTerminal = @import("text-terminal.zig");
const Interrupts = @import("interrupts.zig");
const Timer = @import("timer.zig");
const CHS = @import("chs.zig");
const BlockIterator = @import("block-iterator.zig").BlockIterator;
usingnamespace @import("block-device.zig");
fn wait400NS(port: u16) void {
_ = IO.in(u8, port);
_ = IO.in(u8, port);
_ = IO.in(u8, port);
_ = IO.in(u8, port);
}
const Device = struct {
const This = @This();
device: BlockDevice,
blockSize: usize,
isMaster: bool,
baseport: u16,
ports: Ports,
present: bool,
const Ports = struct {
data: u16,
@"error": u16,
sectors: u16,
lbaLow: u16,
lbaMid: u16,
lbaHigh: u16,
devSelect: u16,
status: u16,
cmd: u16,
control: u16,
};
const Status = packed struct {
/// Indicates an error occurred. Send a new command to clear it (or nuke it with a Software Reset).
hasError: bool,
/// Index. Always set to zero.
index: u1 = 0,
/// Corrected data. Always set to zero.
correctedData: bool = 0,
/// Set when the drive has PIO data to transfer, or is ready to accept PIO data.
dataRequest: bool,
/// Overlapped Mode Service Request.
serviceRequest: bool,
/// Drive Fault Error (does not set ERR).
driveFault: bool,
/// Bit is clear when drive is spun down, or after an error. Set otherwise.
ready: bool,
/// Indicates the drive is preparing to send/receive data (wait for it to clear). In case of 'hang' (it never clears), do a software reset.
busy: bool,
};
comptime {
std.debug.assert(@sizeOf(Status) == 1);
}
fn status(device: This) Status {
wait400NS(device.ports.status);
return @bitCast(Status, IO.in(u8, device.ports.status));
}
fn isFloating(device: This) bool {
return IO.in(u8, device.ports.status) == 0xFF;
}
fn initialize(device: *This) bool {
if (device.isFloating())
return false;
const ports = device.ports;
// To use the IDENTIFY command, select a target drive by sending
// 0xA0 for the master drive, or
// 0xB0 for the slave, to the "drive select" IO port.
if (device.isMaster) {
IO.out(u8, ports.devSelect, 0xA0); // Select Master
} else {
IO.out(u8, ports.devSelect, 0xB0); // Select Slave
}
// Then set the Sectorcount, LBAlo, LBAmid, and LBAhi IO ports to 0
IO.out(u8, ports.sectors, 0);
IO.out(u8, ports.lbaLow, 0);
IO.out(u8, ports.lbaMid, 0);
IO.out(u8, ports.lbaHigh, 0);
// Then send the IDENTIFY command (0xEC) to the Command IO port.
IO.out(u8, ports.cmd, 0xEC);
// Then read the Status port again. If the value read is 0, the drive does not
// exist.
const statusByte = IO.in(u8, device.ports.status);
if (statusByte == 0x00) {
// hal_debug("IDENTIFY failed with STATUS = 0.\n");
return false;
}
// For any other value: poll the Status port (0x1F7) until bit 7 (BSY, value = 0x80)
// clears. Because of some ATAPI drives that do not follow spec, at this point you
// need to check the LBAmid and LBAhi ports (0x1F4 and 0x1F5) to see if they are
// non-zero. If so, the drive is not ATA, and you should stop polling. Otherwise,
// continue polling one of the Status ports until bit 3 (DRQ, value = 8) sets,
// or until bit 0 (ERR, value = 1) sets.
while (device.status().busy) {
// hal_debug("devbusy\n");
}
if ((IO.in(u8, ports.lbaMid) != 0) or (IO.in(u8, ports.lbaHigh) != 0)) {
// hal_debug("%d, %d\n", IO.in(u8, ports.lbaMid), IO.in(u8, ports.lbaHigh));
// hal_debug("IDENTIFY failed with INVALID ATA DEVICE.\n");
return false;
}
device.waitForErrOrReady(150) catch return false;
// At that point, if ERR is clear, the data is ready to read from the Data port
// (0x1F0).
// Read 256 16-bit values, and store them.
var ataData: [256]u16 = undefined;
for (ataData) |*w| {
w.* = IO.in(u16, ports.data);
}
device.device.blockCount = ((@as(u32, ataData[61]) << 16) | ataData[60]);
return true;
}
const Error = error{
DeviceError,
Timeout,
};
fn waitForErrOrReady(device: Device, timeout: usize) Error!void {
const end = Timer.ticks + timeout;
while (Timer.ticks < end) {
const stat = device.status();
if (stat.hasError)
return error.DeviceError;
if (stat.ready)
return;
}
return error.Timeout;
}
fn setupParameters(device: Device, lba: u24, blockCount: u8) void {
if (device.isMaster) {
IO.out(u8, device.ports.devSelect, 0xE0);
} else {
IO.out(u8, device.ports.devSelect, 0xF0);
}
IO.out(u8, device.ports.sectors, blockCount);
IO.out(u8, device.ports.lbaLow, @truncate(u8, lba));
IO.out(u8, device.ports.lbaMid, @truncate(u8, lba >> 8));
IO.out(u8, device.ports.lbaHigh, @truncate(u8, lba >> 16));
}
};
var devs: [8]Device = undefined;
var blockdevs: [8]*BlockDevice = undefined;
pub fn init() error{}![]*BlockDevice {
const PortConfig = struct {
port: u16,
isMaster: bool,
};
const baseports = [_]PortConfig{
.{ .port = 0x1F0, .isMaster = true },
.{ .port = 0x1F0, .isMaster = false },
.{ .port = 0x170, .isMaster = true },
.{ .port = 0x170, .isMaster = false },
.{ .port = 0x1E8, .isMaster = true },
.{ .port = 0x1E8, .isMaster = false },
.{ .port = 0x168, .isMaster = true },
.{ .port = 0x168, .isMaster = false },
};
var deviceCount: usize = 0;
for (baseports) |cfg, i| {
devs[i] = Device{
.device = BlockDevice{
.icon = .hdd,
.read = read,
.write = write,
.blockCount = undefined,
},
.blockSize = 512,
.baseport = cfg.port,
.isMaster = cfg.isMaster,
.ports = Device.Ports{
.data = devs[i].baseport + 0,
.@"error" = devs[i].baseport + 1,
.sectors = devs[i].baseport + 2,
.lbaLow = devs[i].baseport + 3,
.lbaMid = devs[i].baseport + 4,
.lbaHigh = devs[i].baseport + 5,
.devSelect = devs[i].baseport + 6,
.status = devs[i].baseport + 7,
.cmd = devs[i].baseport + 7,
.control = devs[i].baseport + 518,
},
.present = false,
};
devs[i].present = devs[i].initialize();
if (devs[i].present) {
blockdevs[deviceCount] = &devs[i].device;
deviceCount += 1;
}
}
return blockdevs[0..deviceCount];
}
pub fn read(dev: *BlockDevice, lba: usize, buffer: []u8) BlockDevice.Error!void {
const parent = @fieldParentPtr(Device, "device", dev);
return readBlocks(parent.*, @intCast(u24, lba), buffer);
}
fn readBlocks(device: Device, lba: u24, buffer: []u8) BlockDevice.Error!void {
if (!device.present)
return error.DeviceNotPresent;
if (!std.mem.isAligned(buffer.len, device.blockSize))
return error.DataIsNotAligned;
const ports = device.ports;
const blockCount = @intCast(u8, buffer.len / device.blockSize);
if (lba + blockCount > device.device.blockCount)
return error.AddressNotOnDevice;
device.setupParameters(lba, blockCount);
IO.out(u8, ports.cmd, 0x20);
var block: usize = 0;
while (block < blockCount) : (block += 1) {
try device.waitForErrOrReady(150);
var words: [256]u16 = undefined;
for (words) |*w| {
w.* = IO.in(u16, ports.data);
// WHY?!
asm volatile ("nop");
asm volatile ("nop");
asm volatile ("nop");
asm volatile ("nop");
}
std.mem.copy(u8, buffer[device.blockSize * block ..], std.mem.sliceAsBytes(&words)[0..device.blockSize]);
}
}
pub fn write(dev: *BlockDevice, lba: usize, buffer: []const u8) BlockDevice.Error!void {
const parent = @fieldParentPtr(Device, "device", dev);
return writeBlocks(parent.*, @intCast(u24, lba), buffer);
}
fn writeBlocks(device: Device, lba: u24, buffer: []const u8) BlockDevice.Error!void {
if (!device.present)
return error.DeviceNotPresent;
if (!std.mem.isAligned(buffer.len, device.blockSize))
return error.DataIsNotAligned;
const ports = device.ports;
const blockCount = @intCast(u8, buffer.len / device.blockSize);
if (lba + blockCount > device.device.blockCount)
return error.AddressNotOnDevice;
device.setupParameters(lba, blockCount);
IO.out(u8, ports.cmd, 0x30);
var block: usize = 0;
while (block < blockCount) : (block += 1) {
try device.waitForErrOrReady(150);
var words: [256]u16 = undefined;
std.mem.copy(u8, std.mem.sliceAsBytes(&words), buffer[device.blockSize * block ..][0..device.blockSize]);
for (words) |w| {
IO.out(u16, ports.data, w);
// WHY?!
asm volatile ("nop");
asm volatile ("nop");
asm volatile ("nop");
asm volatile ("nop");
}
IO.out(u8, ports.cmd, 0xE7); // Flush
try device.waitForErrOrReady(150);
}
}
|
0 | repos/Ziguana-Game-System/old-version/kernel | repos/Ziguana-Game-System/old-version/kernel/src/linker.ld | ENTRY(_start)
SECTIONS
{
. = 1M; /* Load to 1 MB */
__start = .;
/* Multiboot-Header into first 8 kB */
.text : {
KEEP(*(.multiboot));
*(.text)
}
.data ALIGN(4096) : {
*(.data)
}
.rodata ALIGN(4096) : {
*(.rodata)
/*
__debug_info_start = .;
KEEP(*(.debug_info))
__debug_info_end = .;
__debug_abbrev_start = .;
KEEP(*(.debug_abbrev))
__debug_abbrev_end = .;
__debug_str_start = .;
KEEP(*(.debug_str))
__debug_str_end = .;
__debug_line_start = .;
KEEP(*(.debug_line))
__debug_line_end = .;
__debug_ranges_start = .;
KEEP(*(.debug_ranges))
__debug_ranges_end = .;
*/
__debug_info_start = .;
__debug_info_end = .;
__debug_abbrev_start = .;
__debug_abbrev_end = .;
__debug_str_start = .;
__debug_str_end = .;
__debug_line_start = .;
__debug_line_end = .;
__debug_ranges_start = .;
__debug_ranges_end = .;
}
.bss ALIGN(4096) : {
*(.bss)
}
. = ALIGN(4096);
__end = .;
}
|
0 | repos/Ziguana-Game-System/old-version/kernel | repos/Ziguana-Game-System/old-version/kernel/src/bitmap.zig | const std = @import("std");
pub const Marker = enum {
free,
allocated,
};
pub fn Bitmap(comptime BitCount: comptime_int) type {
return struct {
const This = @This();
const BitPerWord = @typeInfo(usize).Int.bits;
const WordCount = (BitCount + BitPerWord - 1) / BitPerWord;
/// one bit for each page in RAM.
/// If the bit is set, the corresponding page is free.
bitmap: [WordCount]usize,
pub fn init(marker: Marker) This {
return This{
// everything is allocated
.bitmap = switch (marker) {
.free => [_]usize{std.math.maxInt(usize)} ** WordCount,
.allocated => [_]usize{0} ** WordCount,
},
};
}
pub fn alloc(this: *This) ?usize {
for (this.bitmap) |*bits, i| {
if (bits.* == 0)
continue;
comptime var b = 0;
inline while (b < BitPerWord) : (b += 1) {
const bitmask = (1 << b);
if ((bits.* & bitmask) != 0) {
bits.* &= ~@as(usize, bitmask);
return (BitPerWord * i + b);
}
}
unreachable;
}
return null;
}
pub fn mark(this: *This, bit: usize, marker: Marker) void {
const i = bit / BitPerWord;
const b = @truncate(u5, bit % BitPerWord);
switch (marker) {
.allocated => this.bitmap[i] &= ~(@as(usize, 1) << b),
.free => this.bitmap[i] |= (@as(usize, 1) << b),
}
}
pub fn free(this: *This, bit: usize) void {
this.mark(bit, .free);
}
pub fn getFreeCount(this: This) usize {
var count: usize = 0;
for (this.bitmap) |bits, i| {
count += @popCount(usize, bits);
}
return count;
}
};
}
test "Bitmap" {
// fails horribly with 63. compiler bug!
var allocator = Bitmap(64).init();
std.debug.assert(allocator.bitmap.len == 2);
std.debug.assert(allocator.alloc() == null);
std.debug.assert(allocator.alloc() == null);
std.debug.assert(allocator.alloc() == null);
}
test "Bitmap.tight" {
var allocator = Bitmap(64).init();
allocator.mark(0, .free);
allocator.mark(1, .free);
std.debug.assert(allocator.getFreeCount() == 2);
std.debug.assert(allocator.alloc().? == 0);
std.debug.assert(allocator.getFreeCount() == 1);
std.debug.assert(allocator.alloc().? == 1);
std.debug.assert(allocator.getFreeCount() == 0);
allocator.free(1);
std.debug.assert(allocator.getFreeCount() == 1);
std.debug.assert(allocator.alloc().? == 1);
std.debug.assert(allocator.getFreeCount() == 0);
std.debug.assert(allocator.alloc() == null);
std.debug.assert(allocator.getFreeCount() == 0);
}
test "Bitmap.sparse" {
var allocator = Bitmap(64).init();
allocator.mark(0x04, .free);
allocator.mark(0x24, .free);
std.debug.assert(allocator.alloc().? == 0x04);
std.debug.assert(allocator.alloc().? == 0x24);
std.debug.assert(allocator.alloc() == null);
}
test "Bitmap.heavy" {
var allocator = Bitmap(64).init();
comptime var i = 0;
inline while (i < 64) : (i += 1) {
allocator.mark(i, .free);
}
std.debug.assert(allocator.getFreeCount() == 64);
comptime i = 0;
inline while (i < 64) : (i += 1) {
std.debug.assert(allocator.alloc().? == i);
}
std.debug.assert(allocator.alloc() == null);
}
|
0 | repos/Ziguana-Game-System/old-version/kernel | repos/Ziguana-Game-System/old-version/kernel/src/text-terminal.zig | const std = @import("std");
const serial = @import("serial-port.zig");
pub const Color = enum(u4) {
black = 0,
blue = 1,
green = 2,
cyan = 3,
red = 4,
magenta = 5,
brown = 6,
lightGray = 7,
gray = 8,
lightBlue = 9,
lightGreen = 10,
lightCyan = 11,
lightRed = 12,
lightMagenta = 13,
yellow = 14,
white = 15,
};
pub const Char = packed struct {
char: u8,
foreground: Color,
background: Color,
};
pub const WIDTH = 80;
pub const HEIGHT = 25;
var videoBuffer = @intToPtr(*[HEIGHT][WIDTH]Char, 0xB8000);
var currentForeground: Color = .lightGray;
var currentBackground: Color = .black;
var cursorX: u16 = 0;
var cursorY: u16 = 0;
pub var enable_serial = true;
pub var enable_video = true;
pub fn clear() void {
cursorX = 0;
cursorY = 0;
for (videoBuffer) |*line| {
for (line) |*char| {
char.* = Char{
.char = ' ',
.foreground = currentForeground,
.background = currentBackground,
};
}
}
}
pub fn resetColors() void {
currentForeground = .lightGray;
currentBackground = .black;
}
pub fn setForegroundColor(color: Color) void {
currentForeground = color;
}
pub fn setBackgroundColor(color: Color) void {
currentBackground = color;
}
pub fn setColors(foreground: Color, background: Color) void {
currentBackground = background;
currentForeground = foreground;
}
pub fn scroll(lineCount: usize) void {
var i: usize = 0;
while (i < lineCount) : (i += 1) {
var y: usize = 0;
while (y < HEIGHT - 1) : (y += 1) {
videoBuffer.*[y] = videoBuffer.*[y + 1];
}
videoBuffer.*[HEIGHT - 1] = [1]Char{Char{
.background = .black,
.foreground = .black,
.char = ' ',
}} ** WIDTH;
}
cursorY -= 1;
}
fn newline() void {
cursorY += 1;
if (cursorY >= HEIGHT) {
scroll(1);
}
}
fn put_raw(c: u8) void {
if (!enable_video) return;
videoBuffer[cursorY][cursorX] = Char{
.char = c,
.foreground = currentForeground,
.background = currentBackground,
};
cursorX += 1;
if (cursorX >= WIDTH) {
cursorX = 0;
newline();
}
}
pub fn put(c: u8) void {
if (enable_serial)
serial.put(c);
switch (c) {
'\r' => cursorX = 0,
'\n' => newline(),
'\t' => {
const oldpos = cursorX;
cursorX = (cursorX & ~@as(u16, 3)) + 4;
// std.mem.set(Char, videoBuffer[cursorY][oldpos..cursorX], Char{
// .char = ' ',
// .foreground = currentForeground,
// .background = currentBackground,
// });
if (cursorX >= WIDTH)
newline();
},
else => put_raw(c),
}
}
fn write_raw(raw: []const u8) void {
for (raw) |c| {
put_raw(c);
}
}
pub fn write(text: []const u8) void {
for (text) |c| {
put(c);
}
}
fn writerImpl(_: void, text: []const u8) error{}!usize {
write(text);
return text.len;
}
pub fn print(comptime fmt: []const u8, params: anytype) void {
var writer = std.io.Writer(void, error{}, writerImpl){
.context = {},
};
std.fmt.format(writer, fmt, params) catch unreachable;
}
pub fn println(comptime fmt: []const u8, params: anytype) void {
print(fmt, params);
write("\r\n");
}
|
0 | repos/Ziguana-Game-System/old-version/kernel | repos/Ziguana-Game-System/old-version/kernel/src/standalone-assembler.zig | const std = @import("std");
const Assembler = @import("assembler.zig");
var scratchpad: [4096]u8 align(16) = undefined;
pub const assembler_api = struct {
pub const setpix = @intToPtr(fn (x: u32, y: u32, col: u32) callconv(.C) void, 0x100000);
pub const getpix = @intToPtr(fn (x: u32, y: u32) callconv(.C) u32, 0x100004);
pub const gettime = @intToPtr(fn () callconv(.C) u32, 0x100008);
pub const getkey = @intToPtr(fn () callconv(.C) u32, 0x10000C);
pub const flushpix = @intToPtr(fn () callconv(.C) void, 0x100010);
pub const trace = @intToPtr(fn (on: u32) callconv(.C) void, 0x100014);
pub const exit = @intToPtr(fn () callconv(.C) noreturn, 0x100016);
};
pub fn getRegisterAddress(register: u4) u32 {
return 0x1000 + 4 * @as(u32, register);
}
pub fn main() !void {
var contents = try std.fs.cwd().readFileAlloc(std.heap.page_allocator, "../gasm/concept.asm", 1 << 20);
try Assembler.assemble(std.heap.page_allocator, contents, scratchpad[0..], 0x200000);
std.debug.print("assembled code successfully!\n", .{});
try std.fs.cwd().writeFile("/tmp/develop.bin", scratchpad[0..]);
}
|
0 | repos/Ziguana-Game-System/old-version/kernel | repos/Ziguana-Game-System/old-version/kernel/src/code-editor.zig | const std = @import("std");
const Keyboard = @import("keyboard.zig");
const VGA = @import("vga.zig");
const TextTerminal = @import("text-terminal.zig");
const BlockAllocator = @import("block-allocator.zig").BlockAllocator;
const Timer = @import("timer.zig");
const TextPainter = @import("text-painter.zig");
const Heap = @import("heap.zig");
const ColorScheme = struct {
background: VGA.Color,
text: VGA.Color,
comment: VGA.Color,
mnemonic: VGA.Color,
indirection: VGA.Color,
register: VGA.Color,
label: VGA.Color,
directive: VGA.Color,
cursor: VGA.Color,
};
pub var colorScheme = ColorScheme{
.background = 0,
.text = 1,
.comment = 2,
.mnemonic = 3,
.indirection = 4,
.register = 5,
.label = 6,
.directive = 7,
.cursor = 8,
};
const TextLine = struct {
previous: ?*TextLine,
next: ?*TextLine,
text: [120]u8,
length: usize,
};
// var lines: BlockAllocator(TextLine, 4096) = undefined;
var lines = Heap.allocator;
var firstLine: ?*TextLine = null;
var cursorX: usize = 0;
var cursorY: ?*TextLine = null;
pub fn init() void {
// lines = BlockAllocator(TextLine, 4096).init();
}
/// Saves all text lines to the given slice.
/// Returns the portion of the slice actually written.
pub fn saveTo(stream: anytype) !void {
var start = firstLine;
while (start) |s| {
if (s.previous != null) {
start = s.previous;
} else {
break;
}
}
while (start) |node| : (start = node.next) {
try stream.writeAll(node.text[0..node.length]);
try stream.writeAll("\n");
}
}
pub fn load(source: []const u8) !void {
// lines.reset();
firstLine = null;
var it = std.mem.split(source, "\n");
var previousLine: ?*TextLine = null;
while (it.next()) |line| {
var tl = try lines.create(TextLine);
std.mem.copy(u8, tl.text[0..], line);
tl.length = line.len;
tl.next = null;
tl.previous = previousLine;
if (previousLine) |prev| {
prev.next = tl;
}
previousLine = tl;
if (firstLine == null) {
firstLine = tl;
}
}
cursorY = firstLine;
cursorX = 0;
}
fn paint() void {
VGA.clear(colorScheme.background);
var row: usize = 0;
var line_iterator = firstLine;
while (line_iterator) |line| : ({
line_iterator = line.next;
row += 1;
}) {
if (row >= 25)
break;
var line_text = line.text[0..line.length];
var label_pos = std.mem.indexOf(u8, line_text, ":");
const TextType = enum {
background,
text,
comment,
mnemonic,
indirection,
register,
label,
directive,
};
var highlighting: TextType = .text;
var resetHighlighting = false;
var hadMnemonic = false;
var pal: VGA.Color = 0;
var col: usize = 0;
var cursorCol: usize = 0;
for (line_text) |c, i| {
if (col >= 53) // maximum line length
break;
if (i <= cursorX) {
cursorCol = col;
}
std.debug.assert(c != '\n');
if (c == '\t') {
col = (col + 4) & 0xFFFFC;
continue;
}
if (highlighting != .comment) {
if (resetHighlighting) {
highlighting = .text;
}
if (c == '#') {
highlighting = .comment;
} else if (c == ' ') {
if (highlighting == .mnemonic) {
hadMnemonic = true;
}
highlighting = .text;
} else {
if (label_pos) |pos| {
if (i <= pos) {
highlighting = .label;
}
}
if (c == '[' or c == ']') {
highlighting = .indirection;
resetHighlighting = true;
} else if (c == '.') {
highlighting = .directive;
hadMnemonic = true; // prevent mnemonic highlighting
} else if (highlighting == .text and !hadMnemonic and ((c >= 'a' and c <= 'z') or (c >= 'A' and c <= 'Z'))) {
highlighting = .mnemonic;
}
}
}
TextPainter.drawChar(@intCast(isize, 1 + 6 * col), @intCast(isize, 8 * row), c, switch (highlighting) {
.background => colorScheme.background,
.text => colorScheme.text,
.comment => colorScheme.comment,
.mnemonic => colorScheme.mnemonic,
.indirection => colorScheme.indirection,
.register => colorScheme.register,
.label => colorScheme.label,
.directive => colorScheme.directive,
// else => colorScheme.text,
});
col += 1;
}
if (cursorX == line_text.len and line_text.len > 0) {
// adjust "end of line"
cursorCol += 1;
}
if (line == cursorY and (Timer.ticks % 1000 > 500)) {
var y: u3 = 0;
while (y < 7) : (y += 1) {
VGA.setPixel(6 * cursorCol, 8 * row + y, colorScheme.cursor);
}
}
}
VGA.swapBuffers();
}
pub fn run() callconv(.C) noreturn {
// .background = 0,
// .text = 1,
// .comment = 2,
// .mnemonic = 3,
// .indirection = 4,
// .register = 5,
// .label = 6,
// .directive = 7,
// .cursor = 8,
VGA.loadPalette(&comptime [_]VGA.RGB{
VGA.RGB.parse("#000000") catch unreachable, // 0
VGA.RGB.parse("#CCCCCC") catch unreachable, // 1
VGA.RGB.parse("#346524") catch unreachable, // 2
VGA.RGB.parse("#d27d2c") catch unreachable, // 3
VGA.RGB.parse("#d27d2c") catch unreachable, // 4
VGA.RGB.parse("#30346d") catch unreachable, // 5
VGA.RGB.parse("#d04648") catch unreachable, // 6
VGA.RGB.parse("#597dce") catch unreachable, // 7
VGA.RGB.parse("#ffffff") catch unreachable, // 8
});
paint();
while (true) {
if (Keyboard.getKey()) |key| {
const Helper = struct {
fn navigateUp() void {
if (cursorY) |cursor| {
if (cursor.previous) |prev| {
if (cursorY == firstLine)
firstLine = prev;
cursorY = prev;
cursorX = std.math.min(cursorX, cursorY.?.length);
}
}
}
fn navigateDown() void {
var lastLine = firstLine;
var i: usize = 0;
while (i < 24 and lastLine != null) : (i += 1) {
lastLine = lastLine.?.next;
}
if (cursorY) |cursor| {
if (cursor.next) |next| {
if (cursorY == lastLine)
firstLine = firstLine.?.next;
cursorY = next;
cursorX = std.math.min(cursorX, cursorY.?.length);
}
}
}
fn navigateLeft() void {
if (cursorY) |cursor| {
if (cursorX > 0) {
cursorX -= 1;
} else if (cursor.previous != null) {
cursorX = std.math.maxInt(usize);
navigateUp();
}
}
}
fn navigateRight() void {
if (cursorY) |cursor| {
if (cursorX < cursor.length) {
cursorX += 1;
} else if (cursor.next != null) {
cursorX = 0;
navigateDown();
}
}
}
};
if (key.set == .extended0 and key.scancode == 0x48) { // ↑
Helper.navigateUp();
} else if (key.set == .extended0 and key.scancode == 0x50) { // ↓
Helper.navigateDown();
} else if (key.set == .extended0 and key.scancode == 0x4B) { // ←
Helper.navigateLeft();
} else if (key.set == .extended0 and key.scancode == 0x4D) { // →
Helper.navigateRight();
} else if (key.set == .default and key.scancode == 14) { // backspace
if (cursorY) |cursor| {
if (cursorX > 0) {
std.mem.copy(u8, cursor.text[cursorX - 1 ..], cursor.text[cursorX..]);
cursor.length -= 1;
cursorX -= 1;
} else {
if (cursor.previous) |prev| {
// merge lines here
std.mem.copy(u8, prev.text[prev.length..], cursor.text[0..cursor.length]);
cursorX = prev.length;
prev.length += cursor.length;
prev.next = cursor.next;
if (cursor.next) |nx| {
nx.previous = prev;
}
// ZIG BUG!
lines.destroy(cursor);
cursorY = prev;
if (firstLine == cursor) {
firstLine = prev;
}
} else {
// nothing to delete
}
}
}
} else if (key.set == .default and key.scancode == 28) { // Return
if (cursorY) |cursor| {
var cursor_set_pos: enum {
tl,
cursor,
} = undefined;
var tl = lines.create(TextLine) catch @panic("out of memory!");
if (cursorX == 0) {
// trivial case: front insert
tl.previous = cursor.previous;
tl.next = cursor;
tl.length = 0;
if (firstLine == cursor) {
firstLine = tl;
}
} else if (cursorX == cursor.length) {
// trivial case: back insert
tl.previous = cursor;
tl.next = cursor.next;
tl.length = 0;
cursor_set_pos = .tl;
} else {
// complex case: middle insert
tl.previous = cursor;
tl.next = cursor.next;
tl.length = cursor.length - cursorX;
cursor.length = cursorX;
std.mem.copy(u8, tl.text[0..], cursor.text[cursorX..]);
cursor_set_pos = .tl;
}
if (tl.previous) |prev| {
prev.next = tl;
}
if (tl.next) |next| {
next.previous = tl;
}
switch (cursor_set_pos) {
.tl => {
cursorY = tl;
},
.cursor => {
cursorY = cursor;
},
}
cursorX = 0;
}
} else if (key.set == .extended0 and key.scancode == 71) { // Home
cursorX = 0;
} else if (key.set == .extended0 and key.scancode == 79) { // End
if (cursorY) |c| {
cursorX = c.length;
}
} else if (key.set == .extended0 and key.scancode == 83) { // Del
if (cursorY) |cursor| {
if (cursorX == cursor.length) {
// merge two lines
if (cursor.next) |next| {
std.mem.copy(u8, cursor.text[cursor.length..], next.text[0..next.length]);
cursor.length += next.length;
if (next.next) |nxt| {
nxt.previous = cursor;
}
// BAH, FOOTGUNS
lines.destroy(next);
// BAH, MORE FOOTGUNS
cursor.next = next.next;
}
} else {
// erase character
std.mem.copy(u8, cursor.text[cursorX .. cursor.length - 1], cursor.text[cursorX + 1 .. cursor.length]);
cursor.length -= 1;
}
}
}
// [kbd:ScancodeSet.extended0/82/P] Ins
// [kbd:ScancodeSet.extended0/73/P] PgUp
// [kbd:ScancodeSet.extended0/81/P] PgDown
else if (key.char) |chr| {
std.debug.assert(chr != '\n');
if (cursorY) |cursor| {
cursor.length += 1;
if (cursorX < cursor.length) {
std.mem.copyBackwards(u8, cursor.text[cursorX + 1 .. cursor.length], cursor.text[cursorX .. cursor.length - 1]);
}
cursor.text[cursorX] = chr;
cursorX += 1;
}
}
}
// Sleep and wait for interrupt
asm volatile ("hlt");
paint();
}
}
|
0 | repos/Ziguana-Game-System/old-version/kernel | repos/Ziguana-Game-System/old-version/kernel/src/splashscreen.zig | const std = @import("std");
const Keyboard = @import("keyboard.zig");
const VGA = @import("vga.zig");
const Timer = @import("timer.zig");
const TextPainter = @import("text-painter.zig");
const Point = struct {
x: usize,
y: usize,
speed: usize,
};
var stars: [256]Point = undefined;
fn Bitmap2D(comptime _width: usize, comptime _height: usize) type {
const T = struct {
pub const stride = (width + 7) / 8;
pub const width = _width;
pub const height = _height;
bits: [height * stride]u8,
fn getPixel(this: @This(), x: usize, y: usize) u1 {
return @truncate(u1, this.bits[stride * y + x / 8] >> @truncate(u3, x % 8));
}
};
// this is currently broken
// @compileLog(@sizeOf(T), ((_width + 7) / 8) * _height);
// std.debug.assert(@sizeOf(T) == ((_width + 7) / 8) * _height);
return T;
}
fn mkBitmapType(comptime bitmapData: []const u8) type {
const W = std.mem.readIntLittle(usize, @ptrCast(*const [4]u8, &bitmapData[0]));
const H = std.mem.readIntLittle(usize, @ptrCast(*const [4]u8, &bitmapData[4]));
return Bitmap2D(W, H);
}
fn loadBitmap(comptime bitmapData: []const u8) mkBitmapType(bitmapData) {
@setEvalBranchQuota(bitmapData.len);
const T = mkBitmapType(bitmapData);
// this is dirty, but maybe it works
var bitmap = T{
.bits = undefined,
};
std.mem.copy(u8, bitmap.bits[0..], bitmapData[8..]);
return bitmap;
}
const logoData = loadBitmap(@embedFile("splashscreen.bin"));
pub fn run() callconv(.C) noreturn {
const oversampling = 4;
var rng = std.rand.DefaultPrng.init(1);
VGA.loadPalette(&[_]VGA.RGB{
VGA.RGB.init(0x00, 0x00, 0x00), // 0
VGA.RGB.init(0x33, 0x33, 0x33), // 1
VGA.RGB.init(0x66, 0x66, 0x66), // 2
VGA.RGB.init(0x99, 0x99, 0x99), // 3
VGA.RGB.init(0xCC, 0xCC, 0xCC), // 4
VGA.RGB.init(0xFF, 0xFF, 0xFF), // 5
VGA.RGB.init(0xFF, 0xFF, 0xFF), // 6
});
for (stars) |*star| {
star.x = rng.random.intRangeLessThan(usize, 0, oversampling * VGA.width);
star.y = rng.random.intRangeLessThan(usize, 0, oversampling * VGA.height);
star.speed = rng.random.intRangeAtMost(usize, 0, 3);
}
var floop: u8 = 0;
while (true) {
VGA.clear(0);
for (stars) |*star| {
VGA.setPixel(star.x / oversampling, star.y / oversampling, @truncate(u4, 1 + star.speed));
star.x += oversampling * VGA.width;
star.x -= star.speed;
star.x %= oversampling * VGA.width;
}
{
var y: usize = 0;
while (y < @TypeOf(logoData).height) : (y += 1) {
var x: usize = 0;
while (x < @TypeOf(logoData).width) : (x += 1) {
var bit = logoData.getPixel(x, y);
if (bit == 1) {
const offset_x = (VGA.width - @TypeOf(logoData).width) / 2;
const offset_y = (VGA.height - @TypeOf(logoData).height) / 2;
VGA.setPixel(offset_x + x, offset_y + y, 6);
VGA.setPixel(offset_x + x + 1, offset_y + y + 1, 3);
}
}
}
}
if (Timer.ticks % 1500 > 750) {
TextPainter.drawString(VGA.width / 2, VGA.height - 32, "[ Press Space ]", TextPainter.PaintOptions{
.color = 6,
.horizontalAlignment = .middle,
});
}
VGA.waitForVSync();
VGA.swapBuffers();
Timer.wait(10);
if (Keyboard.getKey()) |key| {
if (key.set == .default and key.scancode == 57) {
asm volatile ("int $0x40");
unreachable;
}
}
}
}
|
0 | repos/Ziguana-Game-System/old-version/kernel | repos/Ziguana-Game-System/old-version/kernel/src/isa-dma.zig | const IO = @import("io.zig");
pub const Error = error{
AlreadyInProgress,
InvalidAddress,
EmptyData,
DataTooLarge,
InvalidChannel,
DataCrosses64kBoundary,
};
const TransferMode = packed struct {
/// which channel to configure
channel: u2,
direction: TransferDirection,
autoInit: bool,
count: AddressOperation,
mode: Mode,
const TransferDirection = enum(u2) {
verify = 0b00,
/// this means "RAM to device" (so: CPU *writes* data)
/// this bitfield is usually described as *read*, as the device reads from
/// RAM, but i find this more confusing then helping, so i flipped those.
/// We implement code for a CPU here, not a for the FDC!
write = 0b10,
/// this means "device to RAM" (so: CPU *reads* data)
read = 0b01,
};
const AddressOperation = enum(u1) {
// increment address
increment = 0,
// decrement address
decrement = 1,
};
const Mode = enum(u2) {
demand = 0b00,
single = 0b01,
block = 0b10,
cascade = 0b11,
};
};
const DmaStatus = struct {
transferComplete: [4]bool,
transferRequested: [4]bool,
};
const DmaController = struct {
start: [4]u16,
counter: [4]u16,
currentAddress: [4]u16,
currentCounter: [4]u16,
page: [4]u16,
// Liefert Statusinformationen zum DMA-Controller (siehe dazu unten).
status: u16,
// Befehle, die der Controller ausführen soll, werden hierein geschrieben (für eine Liste der Befehle siehe unten).
command: u16,
// Durch Schreiben in dieses Register wird ein Reset des entsprechenden Controllers durchgeführt.
resetPort: u16,
// Dieses Register ist nötig, um mit 8-Bit-Zugriffen, die 16-Bit-Register zu verwenden.
// Vor dem Zugriff auf ein 16-Bit-Register sollte eine Null an dieses Register gesendet werden.
// Dadurch wird der Flip-Flop des Controllers zurückgesetzt und es wird beim anschließenden
// Zugriff auf ein 16-Bit-Register das Low-Byte adressiert.
// Der Controller wird das Flip-Flop-Register danach selbstständig auf Eins setzen, wodurch der
// nächste Zugriff das High-Byte adressiert. Dies ist sowohl beim Lesen als auch beim Schreiben
// aus bzw. in 16-Bit-Register nötig.
flipflop: u16,
// Über dieses Register kann der Übertragungsmodus für einen Channel und einige weitere ergänzende Details zum Befehl,
// der an das Befehlsregister gesendet wird, festgelegt werden (Für eine genaue Beschreibung siehe unten).
transferMode: u16,
// Hierüber kann ein einzelner Channel maskiert, also deaktiviert, werden.
// Dies sollte immer(!) getan werden, wenn der Controller auf einen Transfer
// vorbereitet wird, um gleichzeitige Zugriffe von mehreren Programmen zu
// unterbinden. Die Bits 0 und 1 enthalten dabei die Nummer des Channels,
// dessen Status geändert werden soll. In Bit 2 wird angegeben, ob der
// gewählte Channel aktiviert (0) oder deaktiviert (1) werden soll.
channelMask: u16,
// Dieses Register hat die gleiche Funktion wie das Maskierungsregister oben, aber mit dem
// Unterschied, dass mit Hilfe dieses Registers der Zustand meherer Channel gleichzeitig
// geändert werden kann. Bit 0 bis 3 geben dabei an, ob der entsprechende Channel (0 … 3)
// aktiviert (0) oder deaktiviert (1) werden soll. Hierbei ist zu beachten, dass nicht aus
// Versehen ein Channel irrtümlicherweise (de)aktiviert wird, dessen Status eigentlich unverändert bleiben soll.
multiMask: u16,
// Dieses Register ermöglicht es, einen Transfer mittels Software auszulösen. Für den Aufbau des zu sendenen Bytes siehe unten.
request: u16,
pub fn setTransferMode(dma: DmaController, transferMode: TransferMode) void {
IO.out(u8, dma.transferMode, @bitCast(u8, transferMode));
}
pub fn enable(dma: DmaController, enabled: bool) void {
IO.out(u8, dma.command, if (enabled) @as(u8, 0b00000100) else 0);
}
pub fn maskChannel(dma: DmaController, channel: u2, masked: bool) void {
IO.out(u8, dma.channelMask, @as(u8, channel) | if (masked) @as(u8, 0b100) else 0);
}
pub fn reset(dma: DmaController) void {
IO.out(u8, dma.resetPort, 0xFF);
}
fn resetFlipFlop(dma: DmaController) void {
IO.out(u8, dma.flipflop, 0xFF);
}
pub fn setStartAddress(dma: DmaController, channel: u2, address: u16) void {
dma.resetFlipFlop();
IO.out(u8, dma.start[channel], @truncate(u8, address));
IO.out(u8, dma.start[channel], @truncate(u8, address >> 8));
}
pub fn setCounter(dma: DmaController, channel: u2, count: u16) void {
dma.resetFlipFlop();
IO.out(u8, dma.counter[channel], @truncate(u8, count));
IO.out(u8, dma.counter[channel], @truncate(u8, count >> 8));
}
pub fn getCurrentAddress(dma: DmaController, channel: u2) u16 {
dma.resetFlipFlop();
var value: u16 = 0;
value |= @as(u16, IO.in(u8, dma.currentAddress[channel]));
value |= @as(u16, IO.in(u8, dma.currentAddress[channel])) << 16;
return value;
}
pub fn getCurrentCounter(dma: DmaController, channel: u2) u16 {
dma.resetFlipFlop();
var value: u16 = 0;
value |= @as(u16, IO.in(u8, dma.currentCounter[channel]));
value |= @as(u16, IO.in(u8, dma.currentCounter[channel])) << 16;
return value;
}
pub fn setPage(dma: DmaController, channel: u2, page: u8) void {
return IO.out(u8, dma.page[channel], page);
}
pub fn getPage(dma: DmaController, channel: u2) u8 {
return IO.in(u8, dma.page[channel]);
}
/// Reading this register will clear the TC bits!!!!
pub fn getStatus(dma: DmaController) DmaStatus {
const word = IO.in(u8, dma.status);
return DmaStatus{
.transferComplete = [4]bool{
(word & 0b00000001) != 0,
(word & 0b00000010) != 0,
(word & 0b00000100) != 0,
(word & 0b00001000) != 0,
},
.transferRequested = [4]bool{
(word & 0b00010000) != 0,
(word & 0b00100000) != 0,
(word & 0b01000000) != 0,
(word & 0b10000000) != 0,
},
};
}
};
const dmaMaster = DmaController{
.start = [_]u16{ 0x00, 0x02, 0x04, 0x06 },
.counter = [_]u16{ 0x01, 0x03, 0x05, 0x07 },
.currentAddress = [_]u16{ 0x00, 0x02, 0x04, 0x06 },
.currentCounter = [_]u16{ 0x01, 0x03, 0x05, 0x07 },
.page = [_]u16{ 0x87, 0x83, 0x81, 0x82 },
.status = 0x08,
.command = 0x08,
.resetPort = 0x0D,
.flipflop = 0x0C,
.transferMode = 0x0B,
.channelMask = 0x0A,
.multiMask = 0x0F,
.request = 0x09,
};
const dmaSlave = DmaController{
.start = [_]u16{ 0xC0, 0xC2, 0xC4, 0xC6 },
.counter = [_]u16{ 0xC1, 0xC3, 0xC5, 0xC7 },
.currentAddress = [_]u16{ 0xC0, 0xC2, 0xC4, 0xC6 },
.currentCounter = [_]u16{ 0xC1, 0xC3, 0xC5, 0xC7 },
.page = [_]u16{ 0x8F, 0x8B, 0x89, 0x8A },
.status = 0xD0,
.command = 0xD0,
.resetPort = 0xDA,
.flipflop = 0xD8,
.transferMode = 0xD6,
.channelMask = 0xD4,
.multiMask = 0xDE,
.request = 0xD2,
};
const Handle = struct {
dma: *const DmaController,
channel: u2,
pub fn isComplete(handle: Handle) bool {
return handle.dma.getStatus().transferComplete[handle.channel];
}
pub fn close(handle: Handle) void {}
};
/// starts a new DMA transfer
fn begin(channel: u3, source_ptr: usize, source_len: usize, mode: TransferMode.Mode, dir: TransferMode.TransferDirection) Error!Handle {
const handle = Handle{
.dma = if ((channel & 0b100) != 0) &dmaSlave else &dmaMaster,
.channel = @truncate(u2, channel),
};
if (channel == 0 or channel == 4)
return error.InvalidChannel;
if (source_ptr >= 0x1000000)
return error.InvalidAddress;
if (source_len == 0)
return error.EmptyData;
if (source_len >= 0x10000)
return error.DataTooLarge;
if ((source_ptr & 0xFF0000) != ((source_ptr + source_len - 1) & 0xFF0000))
return error.DataCrosses64kBoundary;
// We modify the channel, make sure it doesn't do DMA stuff in time
handle.dma.maskChannel(handle.channel, true);
handle.dma.setStartAddress(handle.channel, @truncate(u16, source_ptr));
handle.dma.setCounter(handle.channel, @truncate(u16, source_len - 1));
handle.dma.setPage(handle.channel, @truncate(u8, source_ptr >> 16));
handle.dma.setTransferMode(TransferMode{
.channel = handle.channel,
.direction = dir,
.autoInit = false,
.count = .increment,
.mode = mode,
});
// We have configured our channel, let's go!
handle.dma.maskChannel(handle.channel, false);
return handle;
}
/// starts a new DMA transfer
pub fn beginRead(channel: u3, buffer: []u8, mode: TransferMode.Mode) Error!Handle {
const source_ptr = @ptrToInt(buffer.ptr);
const source_len = buffer.len;
return begin(channel, source_ptr, source_len, mode, .read);
}
/// starts a new DMA transfer
pub fn beginWrite(channel: u3, buffer: []const u8, mode: TransferMode.Mode) Error!Handle {
const source_ptr = @ptrToInt(buffer.ptr);
const source_len = buffer.len;
return begin(channel, source_ptr, source_len, mode, .write);
}
|
0 | repos/Ziguana-Game-System/old-version/kernel | repos/Ziguana-Game-System/old-version/kernel/src/cmos.zig | const IO = @import("io.zig");
const TextTerminal = @import("text-terminal.zig");
const std = @import("std");
// 0x00 Sekunde (BCD)
// 0x01 Alarmsekunde (BCD)
// 0x02 Minute (BCD)
// 0x03 Alarmminute (BCD)
// 0x04 Stunde (BCD)
// 0x05 Alarmstunde (BCD)
// 0x06 Wochentag (BCD)
// 0x07 Tag des Monats (BCD)
// 0x08 Monat (BCD)
// 0x09 Jahr (letzten zwei Stellen) (BCD)
// 0x0A Statusregister A
// 0x0B Statusregister B
// 0x0C Statusregister C (schreibgeschützt)
// 0x0D Statusregister D (schreibgeschützt)
// 0x0E POST-Diagnosestatusbyte
// 0x0F Shutdown-Statusbyte
// 0x10 Typ der Diskettenlaufwerke
// 0x11 reserviert
// 0x12 Typ der Festplattenlaufwerke
// 0x13 reserviert
// 0x14 Gerätebyte
// 0x15 Größe des Basisspeichers in kB (niederwertiges Byte)
// 0x16 Größe des Basisspeichers in kB (höherwertiges Byte)
// 0x17 Größe des Erweiterungsspeichers in kB (niederwertiges Byte)
// 0x18 Größe des Erweiterungsspeichers in kB (höherwertiges Byte)
// 0x19 Erweiterungsbyte 1. Festplatte
// 0x1A Erweiterungsbyte 2. Festplatte
// 0x1B - 0x2D Reserviert / vom BIOS abhängig
// 0x2E CMOS-Prüfsumme (höherwertiges Byte)
// 0x2F CMOS-Prüfsumme (niederwertiges Byte)
// 0x30 Erweiterter Speicher (niederwertiges Byte)
// 0x31 Erweiterter Speicher (höherwertiges Byte)
// 0x32 Jahrhundert (BCD)
// 0x33 - 0x3F Reserviert / vom BIOS abhängig
fn bcdDecode(val: u8) [2]u8 {
return [2]u8{
'0' + (val >> 4),
'0' + (val & 0xF),
};
}
pub fn init() void {}
pub fn printInfo() void {
TextTerminal.println("Clock: {}:{}:{}", .{
bcdDecode(read(0x04)),
bcdDecode(read(0x02)),
bcdDecode(read(0x00)),
});
const floppyDrives = read(0x10);
var buf = (" " ** 64).*;
const floppy_a_type: []const u8 = switch ((floppyDrives >> 4) & 0xF) {
0b0000 => "none",
0b0001 => "5 1/4 - 360 kB",
0b0010 => "5 1/4 - 1.2 MB",
0b0011 => "3 1/2 - 720 kB",
0b0100 => "3 1/2 - 1.44 MB",
else => std.fmt.bufPrint(buf[0..], "unknown ({b:0>4})", .{(floppyDrives >> 4) & 0xF}) catch unreachable,
};
const floppy_b_type: []const u8 = switch ((floppyDrives >> 0) & 0xF) {
0b0000 => "none",
0b0001 => "5 1/4 - 360 kB",
0b0010 => "5 1/4 - 1.2 MB",
0b0011 => "3 1/2 - 720 kB",
0b0100 => "3 1/2 - 1.44 MB",
else => std.fmt.bufPrint(buf[0..], "unknown ({b:0>4})", .{(floppyDrives >> 0) & 0xF}) catch unreachable,
};
TextTerminal.println("Floppy A: {}", .{floppy_a_type});
TextTerminal.println("Floppy B: {}", .{floppy_b_type});
}
pub const FloppyType = enum(u4) {
miniDD = 0b0001, // 5¼, 360 kB
miniHD = 0b0010, // 5¼, 1200 kB
microDD = 0b0011, // 3½, 720 kB
microHD = 0b0100, // 3½, 1440 kB
unknown = 0b1111,
};
pub const FloppyDrives = struct {
A: ?FloppyType,
B: ?FloppyType,
};
pub fn getFloppyDrives() FloppyDrives {
const drivespec = read(0x10);
return FloppyDrives{
.A = switch ((drivespec >> 4) & 0xF) {
0b0000 => null,
0b0001 => FloppyType.miniDD,
0b0010 => FloppyType.miniHD,
0b0011 => FloppyType.microDD,
0b0100 => FloppyType.microHD,
else => FloppyType.unknown,
},
.B = switch ((drivespec >> 0) & 0xF) {
0b0000 => null,
0b0001 => FloppyType.miniDD,
0b0010 => FloppyType.miniHD,
0b0011 => FloppyType.microDD,
0b0100 => FloppyType.microHD,
else => FloppyType.unknown,
},
};
}
const CMOS_PORT_ADDRESS = 0x70;
const CMOS_PORT_DATA = 0x71;
fn read(offset: u7) u8 {
const tmp = IO.in(u8, CMOS_PORT_ADDRESS);
IO.out(u8, CMOS_PORT_ADDRESS, (tmp & 0x80) | (offset & 0x7F));
return IO.in(u8, CMOS_PORT_DATA);
}
fn write(offset: u7, val: u8) void {
const tmp = IO.in(u8, CMOS_PORT_ADDRESS);
IO.out(u8, CMOS_PORT_ADDRESS, (tmp & 0x80) | (offset & 0x7F));
IO.out(u8, CMOS_PORT_DATA, val);
}
|
0 | repos/Ziguana-Game-System/old-version/kernel | repos/Ziguana-Game-System/old-version/kernel/src/vmm.zig | const std = @import("std");
const PMM = @import("pmm.zig");
// WARNING: Change assembler jmp according to this!
pub const startOfUserspace = 0x40000000; // 1 GB into virtual memory
pub const sizeOfUserspace = 16 * 1024 * 1024; // 16 MB RAM
pub const endOfUserspace = startOfUserspace + sizeOfUserspace;
pub const startOfHeap = 0x80000000; // 2 GB into virtual memory
pub const sizeOfHeap = 1 * 1024 * 1024; // 1 MB
pub const endOfHeap = startOfHeap + sizeOfHeap;
pub fn getUserSpace() []u8 {
return @intToPtr([*]u8, startOfUserspace)[0..sizeOfUserspace];
}
pub fn getHeap() []u8 {
return @intToPtr([*]u8, startOfHeap)[0..sizeOfHeap];
}
pub fn init() !*PageDirectory {
var directory = @intToPtr(*PageDirectory, try PMM.alloc());
@memset(@ptrCast([*]u8, directory), 0, 4096);
asm volatile ("mov %[ptr], %%cr3"
:
: [ptr] "r" (directory)
);
return directory;
}
pub fn createUserspace(directory: *PageDirectory) !void {
var pointer = @as(u32, startOfUserspace);
while (pointer < endOfUserspace) : (pointer += PMM.pageSize) {
try directory.mapPage(pointer, try PMM.alloc(), .readWrite);
}
}
pub fn createHeap(directory: *PageDirectory) !void {
var pointer = @as(u32, startOfHeap);
while (pointer < endOfHeap) : (pointer += PMM.pageSize) {
try directory.mapPage(pointer, try PMM.alloc(), .readWrite);
}
}
pub fn enablePaging() void {
var cr0 = asm volatile ("mov %%cr0, %[cr]"
: [cr] "={eax}" (-> u32)
);
cr0 |= (1 << 31);
asm volatile ("mov %[cr], %%cr0"
:
: [cr] "{eax}" (cr0)
);
}
pub const PageDirectory = extern struct {
entries: [1024]Entry,
pub fn mapPage(directory: *PageDirectory, virtualAddress: usize, physicalAddress: usize, access: WriteProtection) error{
AlreadyMapped,
OutOfMemory,
}!void {
const loc = addrToLocation(virtualAddress);
var dirEntry = &directory.entries[loc.directoryIndex];
if (!dirEntry.isMapped) {
var tbl = @intToPtr(*allowzero PageTable, try PMM.alloc());
@memset(@ptrCast([*]u8, tbl), 0, 4096);
dirEntry.* = Entry{
.isMapped = true,
.writeProtection = .readWrite,
.access = .ring0,
.enableWriteThroughCaching = false,
.disableCaching = false,
.wasAccessed = false,
.wasWritten = false,
.size = .fourKilo,
.dontRefreshTLB = false,
.userBits = 0,
// Hack to workaround #2627
.pointer0 = @truncate(u4, (@ptrToInt(tbl) >> 12)),
.pointer1 = @intCast(u16, (@ptrToInt(tbl) >> 16)),
};
std.debug.assert(@ptrToInt(tbl) == (@bitCast(usize, dirEntry.*) & 0xFFFFF000));
}
var table = @intToPtr(*allowzero PageTable, ((@as(usize, dirEntry.pointer1) << 4) | @as(usize, dirEntry.pointer0)) << 12);
var tblEntry = &table.entries[loc.tableIndex];
if (tblEntry.isMapped) {
// Terminal.println("Mapping is at {} is {X}: {}", loc, @bitCast(u32, tblEntry.*), tblEntry);
return error.AlreadyMapped;
}
tblEntry.* = Entry{
.isMapped = true,
.writeProtection = access,
.access = .ring0,
.enableWriteThroughCaching = false,
.disableCaching = false,
.wasAccessed = false,
.wasWritten = false,
.size = .fourKilo,
.dontRefreshTLB = false,
.userBits = 0,
// Hack to workaround #2627
.pointer0 = @truncate(u4, (physicalAddress >> 12)),
.pointer1 = @intCast(u16, (physicalAddress >> 16)),
};
std.debug.assert(physicalAddress == (@bitCast(usize, tblEntry.*) & 0xFFFFF000));
asm volatile ("invlpg %[ptr]"
:
: [ptr] "m" (virtualAddress)
);
}
};
const PageTable = extern struct {
entries: [1024]Entry,
};
const PageLocation = struct {
directoryIndex: u10,
tableIndex: u10,
};
fn addrToLocation(addr: usize) PageLocation {
const idx = addr / 4096;
return PageLocation{
.directoryIndex = @truncate(u10, idx / 1024),
.tableIndex = @truncate(u10, idx & 0x3FF),
};
}
const WriteProtection = enum(u1) {
readOnly = 0,
readWrite = 1,
};
const PageAccess = enum(u1) {
ring0 = 0,
all = 1,
};
const PageSize = enum(u1) {
fourKilo = 0,
fourMegas = 1,
};
const Entry = packed struct {
isMapped: bool,
writeProtection: WriteProtection,
access: PageAccess,
enableWriteThroughCaching: bool,
disableCaching: bool,
wasAccessed: bool,
wasWritten: bool,
size: PageSize,
dontRefreshTLB: bool,
userBits: u3 = 0,
// magic bug fix for #2627
pointer0: u4,
pointer1: u16,
};
comptime {
std.debug.assert(@sizeOf(Entry) == 4);
std.debug.assert(@sizeOf(PageDirectory) == 4096);
std.debug.assert(@sizeOf(PageTable) == 4096);
}
|
0 | repos/Ziguana-Game-System/old-version/kernel | repos/Ziguana-Game-System/old-version/kernel/src/block-device.zig | /// An interface for block devices. use @fieldParentPtr for accessing the implementation.
pub const BlockDevice = struct {
pub const Error = error{
DeviceNotPresent,
DataIsNotAligned,
AddressNotOnDevice,
Timeout,
DeviceError,
BlockSizeMustBePowerOfTwo,
BufferLengthMustBeMultipleOfBlockSize,
};
pub const Icon = enum {
generic,
floppy,
hdd,
};
/// The icon that will be displayed in the UI.
icon: Icon,
/// The number of blocks available on this device.
blockCount: usize,
/// Function to read a stream of blocks from the device.
read: fn (device: *BlockDevice, startingBlock: usize, data: []u8) Error!void,
/// Function to write a stream of blocks to the device.
write: fn write(device: *BlockDevice, startingBlock: usize, data: []const u8) Error!void,
};
|
0 | repos/Ziguana-Game-System/old-version/kernel | repos/Ziguana-Game-System/old-version/kernel/src/zgs-fs.zig | const std = @import("std");
pub const FSHeader = packed struct {
magic: u32 = 0x56ac65d5, // 0x56ac65d5
version: u32 = 1,
name: [32]u8, // zero-terminated or full
saveGameSize: u32,
pub fn isValid(hdr: FSHeader) bool {
return (hdr.magic == 0x56AC65D5) and (hdr.version == 1);
}
pub fn getName(hdr: FSHeader) []const u8 {
return hdr.name[0 .. std.mem.indexOf(u8, hdr.name, "\x00") orelse hdr.name.len];
}
pub fn supportsSaveGames(hdr: FSHeader) bool {
return hdr.saveGameSize != 0;
}
};
comptime {
std.debug.assert(@sizeOf(FSHeader) <= 512);
}
|
0 | repos/Ziguana-Game-System/old-version/kernel | repos/Ziguana-Game-System/old-version/kernel/src/serial-port.zig | const io = @import("io.zig");
pub const IER = 1;
pub const IIR = 2;
pub const FCR = 2;
pub const LCR = 3;
pub const MCR = 4;
pub const LSR = 5;
pub const MSR = 6;
pub const COM1 = 0x3F8;
pub const COM2 = 0x2F8;
pub const COM3 = 0x3E8;
pub const COM4 = 0x2E8;
// Prüft, ob man bereits schreiben kann
pub fn is_transmit_empty(base: u16) bool {
return (io.in(u8, base + LSR) & 0x20) != 0;
}
// Byte senden
fn write_com(base: u16, chr: u8) void {
while (!is_transmit_empty(base)) {}
io.out(u8, base, chr);
}
pub fn put(c: u8) void {
write_com(COM1, c);
}
pub fn write(message: []u8) void {
for (message) |c| {
put(c);
}
}
pub const Parity = enum(u3) {
none = 0,
odd = 0b100,
even = 0b110,
mark = 0b101,
zero = 0b111,
};
pub const BitCount = enum(u4) {
five = 5,
six = 6,
seven = 7,
eight = 8,
};
// Funktion zum initialisieren eines COM-Ports
pub fn init(base: u16, baud: usize, parity: Parity, bits: BitCount) void {
// Teiler berechnen
const baudSplits = @bitCast([2]u8, @intCast(u16, 115200 / baud));
// Interrupt ausschalten
io.out(u8, base + IER, 0x00);
// DLAB-Bit setzen
io.out(u8, base + LCR, 0x80);
// Teiler (low) setzen
io.out(u8, base + 0, baudSplits[0]);
// Teiler (high) setzen
io.out(u8, base + 1, baudSplits[1]);
// Anzahl Bits, Parität, usw setzen (DLAB zurücksetzen)
io.out(u8, base + LCR, (@as(u8, @enumToInt(parity) & 0x7) << 3) | ((@enumToInt(bits) - 5) & 0x3));
// Initialisierung abschließen
io.out(u8, base + FCR, 0xC7);
io.out(u8, base + MCR, 0x0B);
}
|
0 | repos/Ziguana-Game-System/old-version/kernel | repos/Ziguana-Game-System/old-version/kernel/src/pmm.zig | const Bitmap = @import("bitmap.zig").Bitmap;
pub const pageSize = 0x1000;
pub const totalPageCount = (1 << 32) / pageSize;
// 1 MBit for 4 GB @ 4096 pages
var pmm_bitmap = Bitmap(totalPageCount).init(.allocated);
pub fn alloc() !usize {
return pageSize * (pmm_bitmap.alloc() orelse return error.OutOfMemory);
}
pub fn free(ptr: usize) void {
pmm_bitmap.free(ptr / pageSize);
}
pub const Marker = @import("bitmap.zig").Marker;
pub fn mark(ptr: usize, marker: Marker) void {
pmm_bitmap.mark(ptr / pageSize, marker);
}
pub fn getFreePageCount() usize {
return pmm_bitmap.getFreeCount();
}
pub fn getFreeMemory() usize {
return pageSize * pmm_bitmap.getFreeCount();
}
|
0 | repos/Ziguana-Game-System/old-version/kernel | repos/Ziguana-Game-System/old-version/kernel/src/floppy-disk-controller.zig | const std = @import("std");
const IO = @import("io.zig");
const TextTerminal = @import("text-terminal.zig");
const CMOS = @import("cmos.zig");
const ISA_DMA = @import("isa-dma.zig");
const Interrupts = @import("interrupts.zig");
const Timer = @import("timer.zig");
const CHS = @import("chs.zig");
const BlockIterator = @import("block-iterator.zig").BlockIterator;
usingnamespace @import("block-device.zig");
const defaultRetryCount = 5;
const disableReadWriteRetries = false;
const FloppyError = BlockDevice.Error || error{
InvalidFifoOperation,
NoDriveSelected,
ControllerIsBusy,
ExpectedValueWasNotTwo,
AlreadyInProgress,
InvalidAddress,
EmptyData,
DataTooLarge,
InvalidChannel,
DataCrosses64kBoundary,
SenseInterruptFailure,
};
pub const microHDFloppyLayout = CHS.DriveLayout{
.headCount = 2,
.cylinderCount = 80,
.sectorCount = 18,
};
// this file follows roughly the following links:
// https://wiki.osdev.org/FDC
// https://www.lowlevel.eu/wiki/Floppy_Disk_Controller
pub const DriveName = enum(u2) {
A = 0,
B = 1,
C = 2,
D = 3,
};
const IoMode = enum {
portIO,
dma,
};
const Drive = struct {
device: BlockDevice,
available: bool,
id: u2,
ioMode: IoMode,
};
var allDrives: [4]Drive = undefined;
var blockDevices: [4]*BlockDevice = undefined;
var currentDrive: ?*Drive = null;
fn getCurrentDrive() FloppyError!*Drive {
const drive = currentDrive orelse return error.NoDriveSelected;
if (!drive.available)
return error.DeviceNotPresent;
return drive;
}
/// discovers and initializes all floppy drives
pub fn init() ![]*BlockDevice {
Interrupts.setIRQHandler(6, handleIRQ6);
Interrupts.enableIRQ(6);
const drives = CMOS.getFloppyDrives();
for (allDrives) |*drive, i| {
drive.* = Drive{
.device = BlockDevice{
.icon = .floppy,
.read = read,
.write = write,
.blockCount = 2880, // this is fixed
},
.available = switch (i) {
0 => if (drives.A) |d| d == .microHD else false,
1 => if (drives.B) |d| d == .microHD else false,
2 => false,
3 => false,
else => unreachable,
},
.id = @intCast(u2, i),
.ioMode = .dma,
};
}
// The bottom 2 bits specify the data transfer rate to/from the drive.
// You want both bits set to zero for a 1.44MB or 1.2MB floppy drive.
// So generally, you want to set CCR to zero just once, after bootup
// (because the BIOS may not have done it, unless it booted a floppy disk).
writeRegister(.datarateSelectRegister, 0x00);
if ((try execVersion()) != 0x90) {
// controller isn't a 82077AA
return error.ControllerNotSupported;
}
// Reset the controller
try resetController();
// Implied seek, fifo enabled, polling disabled, 8 byte threshold, manufacturer precompensation
try execConfigure(true, false, true, 8, 0);
// Lock down configuration over controller resets
try execLock(true);
var driveCount: usize = 0;
for (allDrives) |*drive| {
if (!drive.available)
continue;
blockDevices[driveCount] = &drive.device;
driveCount += 1;
try selectDrive(drive);
try setMotorPower(.on);
// wait for the motor to spin up
Timer.wait(200);
try execRecalibrate();
try setMotorPower(.off);
}
return blockDevices[0..driveCount];
}
fn read(blockdev: *BlockDevice, startingBlock: usize, data: []u8) BlockDevice.Error!void {
return read_NoErrorMapping(blockdev, startingBlock, data) catch |err| return mapFloppyError(err);
}
/// reads blocks from drive `name`, starting at block `startingBlock`.
fn read_NoErrorMapping(blockdev: *BlockDevice, startingBlock: usize, data: []u8) FloppyError!void {
try selectDrive(@fieldParentPtr(Drive, "device", blockdev));
var drive = try getCurrentDrive();
try setMotorPower(.on);
// turn motor off after successful or failed operation
defer setMotorPower(.off) catch unreachable; // error is only when getCurrentDrive() fails and we called that already :)
Timer.wait(200); // Let motor spin up a bit
var iterator = try BlockIterator(.mutable).init(startingBlock, data, 512);
while (iterator.next()) |block| {
var retries: usize = 5;
var lastError: FloppyError = undefined;
while (retries > 0) : (retries -= 1) {
if (disableReadWriteRetries) {
try readBlock(block.block, block.slice);
} else {
readBlock(block.block, block.slice) catch |err| {
lastError = err;
continue;
};
}
break;
}
if (retries == 0)
return lastError;
}
}
/// writes blocks from drive `name`, starting at block `startingBlock`.
fn write(blockdev: *BlockDevice, startingBlock: usize, data: []const u8) BlockDevice.Error!void {
return write_NoErrorMapping(blockdev, startingBlock, data) catch |err| return mapFloppyError(err);
}
fn write_NoErrorMapping(blockdev: *BlockDevice, startingBlock: usize, data: []const u8) FloppyError!void {
try selectDrive(@fieldParentPtr(Drive, "device", blockdev));
var drive = try getCurrentDrive();
try setMotorPower(.on);
// turn motor off after successful or failed operation
defer setMotorPower(.off) catch unreachable; // error is only when getCurrentDrive() fails and we called that already :)
Timer.wait(200); // Let motor spin up a bit
var iterator = try BlockIterator(.constant).init(startingBlock, data, 512);
while (iterator.next()) |block| {
var retries: usize = defaultRetryCount;
var lastError: FloppyError = undefined;
while (retries > 0) : (retries -= 1) {
if (disableReadWriteRetries) {
try writeBlock(block.block, block.slice);
} else {
writeBlock(block.block, block.slice) catch |err| {
lastError = err;
continue;
};
}
break;
}
if (retries == 0)
return lastError;
}
}
fn readBlock(block: u32, buffer: []u8) !void {
const chs = try CHS.lba2chs(microHDFloppyLayout, block);
execSeek(@intCast(u8, chs.cylinder), @intCast(u8, chs.head), 1000) catch {
try execRecalibrate();
try execSeek(@intCast(u8, chs.cylinder), @intCast(u8, chs.head), 1000);
};
try execRead(chs, buffer);
}
fn writeBlock(block: u32, buffer: []const u8) !void {
const chs = try CHS.lba2chs(microHDFloppyLayout, block);
execSeek(@intCast(u8, chs.cylinder), @intCast(u8, chs.head), 1000) catch {
try execRecalibrate();
try execSeek(@intCast(u8, chs.cylinder), @intCast(u8, chs.head), 1000);
};
try execWrite(chs, buffer);
}
fn resetController() !void {
var dor = @bitCast(DigitalOutputRegister, readRegister(.digitalOutputRegister));
dor.disableReset = false;
dor.irqEnabled = true;
resetIrqCounter();
writeRegister(.digitalOutputRegister, 0x00);
dor.disableReset = true;
writeRegister(.digitalOutputRegister, @bitCast(u8, dor));
try waitForInterrupt(250);
}
const MotorPower = enum(u1) {
off = 0,
on = 1,
};
fn setMotorPower(power: MotorPower) !void {
var drive = try getCurrentDrive();
var dor = @bitCast(DigitalOutputRegister, readRegister(.digitalOutputRegister));
switch (drive.id) {
0 => dor.motorA = (power == .on),
1 => dor.motorB = (power == .on),
2 => dor.motorC = (power == .on),
3 => dor.motorD = (power == .on),
}
writeRegister(.digitalOutputRegister, @bitCast(u8, dor));
}
fn selectDrive(drive: *Drive) !void {
if (!drive.available)
return error.DeviceNotPresent;
var dor = @bitCast(DigitalOutputRegister, readRegister(.digitalOutputRegister));
dor.driveSelect = drive.id;
writeRegister(.digitalOutputRegister, @bitCast(u8, dor));
currentDrive = drive;
// set 500kbit/s
writeRegister(.datarateSelectRegister, 0x00);
// SRT = "Step Rate Time" = time the controller should wait for the head assembly
// to move between successive cylinders. A reasonable amount of time
// to allow for this is 3ms for modern 3.5 inch floppy drives. A very safe amount would be 6 to 8ms.
// To calculate the value for the SRT setting from the given time, use
// "SRT_value = 16 - (milliseconds * data_rate / 500000)".
// For a 1.44 MB floppy and 8ms delay this gives "SRT_value = 16 - (8 * 500000 / 500000)" or a parameter value of 8.
// HLT = "Head Load Time" = time the controller should wait between activating a head and actually performing a read/write.
// A reasonable value for this is around 10ms. A very safe amount would be 30ms.
// To calculate the value for the HLT setting from the given time, use
// "HLT_value = milliseconds * data_rate / 1000000".
// For a 1.44 MB floppy and a 10ms delay this gives "HLT_value = 10 * 500000 / 1000000" or 5.
// HUT = "Head Unload Time" = time the controller should wait before deactivating the head.
// To calculate the value for the HUT setting from a given time, use
// "HUT_value = milliseconds * data_rate / 8000000".
// For a 1.44 MB floppy and a 240 mS delay this gives "HUT_value = 24 * 500000 / 8000000" or 15.
// However, it seems likely that the smartest thing to do is just to set the value to 0 (which is the maximum in any mode).
try execSpecify(drive.ioMode == .dma, 8, 5, 0);
// Bugfix: Somehow specify deletes the DMA enabled bit!
dor = @bitCast(DigitalOutputRegister, readRegister(.digitalOutputRegister));
dor.irqEnabled = true;
writeRegister(.digitalOutputRegister, @bitCast(u8, dor));
}
fn execSeek(cylinder: u8, head: u8, timeout: usize) !void {
var drive = try getCurrentDrive();
try startCommand(.seek, false, false, false);
try writeFifo(head << 2 | drive.id);
try writeFifo(cylinder);
try waitForInterrupt(5000); // wait a long time for the seek to happen
try execSenseInterrupt(false);
const end = Timer.ticks + timeout;
while (Timer.ticks < end) {
const msr = @bitCast(MainStatusRegister, readRegister(.mainStatusRegister));
const isSeeking = switch (drive.id) {
0 => msr.driveAseeking,
1 => msr.driveBseeking,
2 => msr.driveCseeking,
3 => msr.driveDseeking,
};
if (!isSeeking and !msr.commandBusy)
return; // yay, we're done!
}
return error.Timeout;
}
fn execRead(address: CHS.CHS, buffer: []u8) !void {
const drive = try getCurrentDrive();
var handle = if (drive.ioMode == .dma) try ISA_DMA.beginRead(2, buffer, .single) else undefined;
defer if (drive.ioMode == .dma) handle.close();
return execReadOrWriteTransfer(address, .readData);
}
fn execWrite(address: CHS.CHS, buffer: []const u8) !void {
const drive = try getCurrentDrive();
var handle = if (drive.ioMode == .dma) try ISA_DMA.beginWrite(2, buffer, .single) else undefined;
defer if (drive.ioMode == .dma) handle.close();
return execReadOrWriteTransfer(address, .writeData);
}
fn execReadOrWriteTransfer(address: CHS.CHS, cmd: FloppyCommand) !void {
const drive = try getCurrentDrive();
std.debug.assert(switch (cmd) {
.readData, .writeData => true,
else => false,
});
std.debug.assert(drive.ioMode == .dma); // .portIO is not supported yet!
// if (drive.ioMode == .portIO) {
// var dor = @bitCast(DigitalOutputRegister, readRegister(.digitalOutputRegister));
// dor.irqEnabled = false;
// writeRegister(.digitalOutputRegister, @bitCast(u8, dor));
// }
// defer if (drive.ioMode == .portIO) {
// var dor = @bitCast(DigitalOutputRegister, readRegister(.digitalOutputRegister));
// dor.irqEnabled = true;
// writeRegister(.digitalOutputRegister, @bitCast(u8, dor));
// };
try startCommand(cmd, false, true, false);
try writeFifo(@intCast(u8, (address.head << 2) | drive.id));
try writeFifo(@intCast(u8, address.cylinder));
try writeFifo(@intCast(u8, address.head));
try writeFifo(@intCast(u8, address.sector));
try writeFifo(0x02); // (all floppy drives use 512bytes per sector))
try writeFifo(microHDFloppyLayout.sectorCount); // END OF TRACK (end of track, the last sector number on the track)
try writeFifo(0x1B); // GAP 1
try writeFifo(0xFF); // (all floppy drives use 512bytes per sector)
// If !DMA, then
// read via PIO here!
if (drive.ioMode == .portIO) {
// for (buffer) |*b, i| {
// const msr = @bitCast(MainStatusRegister, readRegister(.mainStatusRegister));
// std.debug.assert(msr.nonDma);
// b.* = try readFifo();
// }
try waitForInterrupt(100);
} else {
// while (handle.isComplete() == false) {
// Timer.wait(100);
// }
try waitForInterrupt(100);
}
// {
// const msr = @bitCast(MainStatusRegister, readRegister(.mainStatusRegister));
// std.debug.assert(!msr.nonDma);
// }
const st0 = try readFifo(); // First result byte = st0 status register
const st1 = try readFifo(); // Second result byte = st1 status register
const st2 = try readFifo(); // Third result byte = st2 status register
const cylinder = try readFifo(); // Fourth result byte = cylinder number
const endHead = try readFifo(); // Fifth result byte = ending head number
const endSector = try readFifo(); // Sixth result byte = ending sector number
const mb2 = try readFifo(); // Seventh result byte = 2
// TextTerminal.println("result: {} / {X} {X} {X} {} {} {} {}", buffer.len, st0, st1, st2, cylinder, endHead, endSector, mb2);
if (mb2 != 2)
return error.ExpectedValueWasNotTwo; // this is ... cryptic.
}
fn execRecalibrate() !void {
var drive = try getCurrentDrive();
try startCommand(.recalibrate, false, false, false);
try writeFifo(drive.id);
try waitForInterrupt(5000);
try execSenseInterrupt(false);
}
fn execSenseInterrupt(postResetCondition: bool) !void {
var drive = try getCurrentDrive();
try startCommand(.senseInterrupt, false, false, false);
const st0 = try readFifo();
const cyl = try readFifo(); // this is probably wrong
// TextTerminal.println("sense returned: st0={X}, cyl={}", st0, cyl);
// The correct value of st0 after a reset should be 0xC0 | drive number (drive number = 0 to 3).
// After a Recalibrate/Seek it should be 0x20 | drive number.
if (postResetCondition) {
if ((st0 & 0xE0) != 0xC0 | @as(u8, drive.id))
return error.SenseInterruptFailure;
} else {
if ((st0 & 0xE0) != 0x20 | @as(u8, drive.id))
return error.SenseInterruptFailure;
}
}
fn execSpecify(enableDMA: bool, stepRateTime: u4, headLoadTime: u7, headUnloadTime: u4) !void {
try startCommand(.specify, false, false, false);
try writeFifo((@as(u8, stepRateTime) << 4) | headUnloadTime);
try writeFifo((@as(u8, headLoadTime) << 1) | (if (enableDMA) @as(u8, 0) else 1));
}
/// Returns one byte. If the value is 0x90, the floppy controller is a 82077AA.
fn execVersion() !u8 {
try startCommand(.version, false, false, false);
return try readFifo();
}
fn execConfigure(impliedSeek: bool, disableFifo: bool, disablePolling: bool, fifoIrqThreshold: u5, precompensation: u8) !void {
if (fifoIrqThreshold < 1 or fifoIrqThreshold > 16)
return error.ThresholdOutOfRange;
var data = @as(u8, @intCast(u4, fifoIrqThreshold - 1));
if (impliedSeek)
data |= (1 << 6);
if (disableFifo)
data |= (1 << 5);
if (!disablePolling)
data |= (1 << 4);
try startCommand(.configure, false, false, false);
try writeFifo(0x00);
try writeFifo(data);
try writeFifo(precompensation);
}
fn execLock(enableLock: bool) !void {
try startCommand(.lock, enableLock, false, false);
const result = try readFifo();
if (result != if (enableLock) @as(u8, 0x10) else 0x00)
return error.LockFailed;
}
fn startCommand(cmd: FloppyCommand, multiTrack: bool, mfmMode: bool, skipMode: bool) !void {
var msr = @bitCast(MainStatusRegister, readRegister(.mainStatusRegister));
if (msr.commandBusy)
return error.ControllerIsBusy;
var data = @as(u8, @enumToInt(cmd));
if (multiTrack)
data |= 0x80;
if (mfmMode)
data |= 0x40;
if (skipMode)
data |= 0x20;
// TextTerminal.println("startCommand({}, {}, {}, {})", cmd, multiTrack, mfmMode, skipMode);
try writeFifo(data);
}
const FifoDirection = enum {
fdcToHost,
hostToFdc,
};
fn waitForFifoReady() error{Timeout}!FifoDirection {
var count: usize = 0;
while (true) {
var msr = @bitCast(MainStatusRegister, readRegister(.mainStatusRegister));
if (msr.fifoReady)
return if (msr.fifoExpectsRead) return FifoDirection.fdcToHost else FifoDirection.hostToFdc;
Timer.wait(10);
count += 1;
if (count >= 10)
return error.Timeout;
}
}
fn writeFifo(value: u8) !void {
if ((try waitForFifoReady()) != .hostToFdc)
return error.InvalidFifoOperation;
writeRegister(.dataFifo, value);
}
fn readFifo() !u8 {
if ((try waitForFifoReady()) != .fdcToHost)
return error.InvalidFifoOperation;
return readRegister(.dataFifo);
}
fn writeRegister(reg: FloppyOutputRegisters, value: u8) void {
// TextTerminal.println("writeRegister({}, 0x{X})", reg, value);
IO.out(u8, @enumToInt(reg), value);
}
fn readRegister(reg: FloppyInputRegisters) u8 {
const value = IO.in(u8, @enumToInt(reg));
// TextTerminal.println("readRegister({}) = 0x{X}", reg, value);
return value;
}
var irqCounter: u32 = 0;
fn resetIrqCounter() void {
@atomicStore(u32, &irqCounter, 0, .Release);
}
fn handleIRQ6(cpu: *Interrupts.CpuState) *Interrupts.CpuState {
_ = @atomicRmw(u32, &irqCounter, .Add, 1, .SeqCst);
return cpu;
}
/// waits `timeout` ms for IRQ6
fn waitForInterrupt(timeout: usize) error{Timeout}!void {
var end = Timer.ticks + timeout;
while (Timer.ticks < end) {
if (@atomicRmw(u32, &irqCounter, .Xchg, 0, .SeqCst) > 0) {
return;
}
asm volatile ("hlt");
}
return error.Timeout;
}
fn mapFloppyError(err: FloppyError) BlockDevice.Error {
return switch (err) {
error.Timeout => error.Timeout,
error.DeviceNotPresent => error.DeviceNotPresent,
error.DataIsNotAligned => error.DataIsNotAligned,
error.AddressNotOnDevice => error.AddressNotOnDevice,
error.BlockSizeMustBePowerOfTwo => error.BlockSizeMustBePowerOfTwo,
error.BufferLengthMustBeMultipleOfBlockSize => error.BufferLengthMustBeMultipleOfBlockSize,
else => error.DeviceError,
};
}
const FloppyCommand = enum(u5) {
readTrack = 2, // generates irq6
specify = 3, // * set drive parameters
senseDriveStatus = 4,
writeData = 5, // * write to the disk
readData = 6, // * read from the disk
recalibrate = 7, // * seek to cylinder 0
senseInterrupt = 8, // * ack irq6, get status of last command
writeDeletedData = 9,
readId = 10, // generates irq6
readDeletedData = 12,
formatTrack = 13, // *
dumpRegisters = 14,
seek = 15, // * seek both heads to cylinder x
version = 16, // * used during initialization, once
scanEqual = 17,
perpendicularMode = 18, // * used during initialization, once, maybe
configure = 19, // * set controller parameters
lock = 20, // * protect controller params from a reset
verify = 22,
scanLowOrEqual = 25,
scanHighOrEqual = 29,
};
const FloppyOutputRegisters = enum(u16) {
digitalOutputRegister = 0x3f2,
tapeDriveRegister = 0x3f3,
datarateSelectRegister = 0x3f4,
dataFifo = 0x3f5,
configurationControlRegister = 0x3f7,
};
const FloppyInputRegisters = enum(u16) {
statusRegisterA = 0x3f0,
statusRegisterB = 0x3f1,
digitalOutputRegister = 0x3f2,
tapeDriveRegister = 0x3f3,
mainStatusRegister = 0x3f4,
dataFifo = 0x3f5,
digitalInputRegister = 0x3F7,
};
const DigitalOutputRegister = packed struct {
driveSelect: u2,
disableReset: bool,
irqEnabled: bool,
motorA: bool,
motorB: bool,
motorC: bool,
motorD: bool,
};
const MainStatusRegister = packed struct {
driveDseeking: bool,
driveCseeking: bool,
driveBseeking: bool,
driveAseeking: bool,
commandBusy: bool,
nonDma: bool,
fifoExpectsRead: bool,
fifoReady: bool,
};
comptime {
std.debug.assert(@sizeOf(DigitalOutputRegister) == 1);
std.debug.assert(@sizeOf(MainStatusRegister) == 1);
}
|
0 | repos/Ziguana-Game-System/old-version/kernel | repos/Ziguana-Game-System/old-version/kernel/src/heap.zig | const std = @import("std");
const VMM = @import("vmm.zig");
/// defines the minimum size of an allocation
const granularity = 16;
const HeapSegment = struct {
const This = @This();
next: ?*This,
size: usize,
isFree: bool,
};
comptime {
std.debug.assert(@alignOf(HeapSegment) <= granularity);
std.debug.assert(@sizeOf(HeapSegment) <= granularity);
std.debug.assert(std.mem.isAligned(VMM.startOfHeap, granularity));
std.debug.assert(std.mem.isAligned(VMM.endOfHeap, granularity));
}
var allocatorObject = std.mem.Allocator{
.allocFn = heapAlloc,
.resizeFn = heapResize,
};
pub const allocator = &allocatorObject;
var firstNode: ?*HeapSegment = null;
pub fn init() void {
firstNode = @intToPtr(*HeapSegment, VMM.startOfHeap);
firstNode.?.* = HeapSegment{
.next = null,
.size = VMM.sizeOfHeap,
.isFree = true,
};
}
fn malloc(len: usize) std.mem.Allocator.Error![]u8 {
var node = firstNode;
while (node) |it| : (node = it.next) {
if (!it.isFree)
continue;
if (it.size - granularity < len)
continue;
const address_of_node = @ptrToInt(it);
std.debug.assert(std.mem.isAligned(address_of_node, granularity)); // security check here
const address_of_data = address_of_node + granularity;
const new_size_of_node = std.mem.alignForward(len, granularity) + granularity;
// if we haven't allocated *all* memory in this node
if (it.size > new_size_of_node) {
const remaining_size = it.size - new_size_of_node;
it.size = new_size_of_node;
const address_of_next = address_of_node + new_size_of_node;
std.debug.assert(std.mem.isAligned(address_of_next, granularity)); // security check here
const next = @intToPtr(*HeapSegment, address_of_next);
next.* = HeapSegment{
.size = remaining_size,
.isFree = true,
.next = it.next,
};
it.next = next;
}
it.isFree = false;
return @intToPtr([*]u8, address_of_data)[0..len];
}
return error.OutOfMemory;
}
fn free(memory: []u8) void {
const address_of_data = @ptrToInt(memory.ptr);
std.debug.assert(std.mem.isAligned(address_of_data, granularity)); // security check here
const address_of_node = address_of_data - granularity;
const node = @intToPtr(*HeapSegment, address_of_node);
node.isFree = true;
if (node.next) |next| {
// sad, we cannot merge :(
if (!next.isFree)
return;
node.size += next.size;
// make sure this is the last access to "next",
// because: zig bug!
node.next = next.next;
}
}
fn printAllocationList() void {
// var node = firstNode;
// while (node) |it| : (node = it.next) {
// Terminal.println("{*} = {{ .size = {}, .isFree = {}, .next = {*} }}", it, it.size, it.isFree, it.next);
// }
}
fn heapAlloc(self: *std.mem.Allocator, len: usize, ptr_align: u29, len_align: u29, ret_addr: usize) std.mem.Allocator.Error![]u8 {
std.debug.assert(ptr_align <= @alignOf(c_longdouble));
return try malloc(len);
}
fn heapResize(
self: *std.mem.Allocator,
buf: []u8,
old_align: u29,
new_len: usize,
len_align: u29,
ret_addr: usize,
) std.mem.Allocator.Error!usize {
if (new_len == 0) {
free(buf);
return 0;
}
if (new_len <= buf.len) {
return std.mem.alignAllocLen(buf.len, new_len, len_align);
}
return error.OutOfMemory;
}
|
0 | repos/Ziguana-Game-System/old-version/kernel | repos/Ziguana-Game-System/old-version/kernel/src/gdt.zig | const std = @import("std");
const Granularity = enum(u1) {
byte = 0,
page = 1,
};
const SegmentSize = enum(u1) {
bits16 = 0,
bits32 = 1,
};
const Descriptor = packed struct {
pub const Access = packed struct {
accessed: bool = false,
writeable: bool,
direction: bool,
executable: bool,
segment: bool,
priviledge: u2,
present: bool,
};
pub const Flags = packed struct {
userbit: u1 = 0,
longmode: bool,
size: SegmentSize,
granularity: Granularity,
};
limit0: u16, // 0 Limit 0-7
// 1 Limit 8-15
base0: u24, // 2 Base 0-7
// 3 Base 8-15
// 4 Base 16-23
access: Access, // 5 Accessbyte 0-7 (vollständig)
limit1: u4, // 6 Limit 16-19
flags: Flags, // 6 Flags 0-3 (vollständig)
base1: u8, // 7 Base 24-31
pub fn init(base: u32, limit: u32, access: Access, flags: Flags) Descriptor {
return Descriptor{
.limit0 = @truncate(u16, limit & 0xFFFF),
.limit1 = @truncate(u4, (limit >> 16) & 0xF),
.base0 = @truncate(u24, base & 0xFFFFFF),
.base1 = @truncate(u8, (base >> 24) & 0xFF),
.access = access,
.flags = flags,
};
}
};
comptime {
if (comptime @sizeOf(Descriptor) != 8) {
@compileLog(@sizeOf(Descriptor));
}
}
var gdt: [3]Descriptor align(16) = [_]Descriptor{
// null descriptor
Descriptor.init(0, 0, Descriptor.Access{
.writeable = false,
.direction = false,
.executable = false,
.segment = false,
.priviledge = 0,
.present = false,
}, Descriptor.Flags{
.granularity = .byte,
.size = .bits16,
.longmode = false,
}),
// Kernel Code Segment
Descriptor.init(0, 0xfffff, Descriptor.Access{
.writeable = true,
.direction = false,
.executable = true,
.segment = true,
.priviledge = 0,
.present = true,
}, Descriptor.Flags{
.granularity = .page,
.size = .bits32,
.longmode = false,
}),
// Kernel Data Segment
Descriptor.init(0, 0xfffff, Descriptor.Access{
.writeable = true,
.direction = false,
.executable = false,
.segment = true,
.priviledge = 0,
.present = true,
}, Descriptor.Flags{
.granularity = .page,
.size = .bits32,
.longmode = false,
}),
};
const DescriptorTable = packed struct {
limit: u16,
table: [*]Descriptor,
};
export const gdtp = DescriptorTable{
.table = &gdt,
.limit = @sizeOf(@TypeOf(gdt)) - 1,
};
const Terminal = @import("text-terminal.zig");
fn load() void {
// TODO: This is kinda dirty, is this possible otherwise?
asm volatile ("lgdt gdtp");
asm volatile (
\\ mov $0x10, %%ax
\\ mov %%ax, %%ds
\\ mov %%ax, %%es
\\ mov %%ax, %%fs
\\ mov %%ax, %%gs
\\ mov %%ax, %%ss
\\ ljmp $0x8, $.reload
\\ .reload:
);
}
pub fn init() void {
// for (gdt) |descriptor| {
// Terminal.println("0x{X:0>16} = {}", @bitCast(u64, descriptor), descriptor);
// }
load();
}
|
0 | repos/Ziguana-Game-System/old-version/kernel | repos/Ziguana-Game-System/old-version/kernel/src/vga.zig | const std = @import("std");
const io = @import("io.zig");
const Terminal = @import("text-terminal.zig");
fn outportb(port: u16, val: u8) void {
io.out(u8, port, val);
}
fn inportb(port: u16) u8 {
return io.in(u8, port);
}
pub const VgaMode = enum {
mode320x200,
mode640x480,
};
pub const mode = if (@hasDecl(@import("root"), "vga_mode")) @import("root").vga_mode else VgaMode.mode320x200;
pub const Color = switch (mode) {
.mode320x200 => u8,
.mode640x480 => u4,
};
pub const width = switch (mode) {
.mode320x200 => 320,
.mode640x480 => 640,
};
pub const height = switch (mode) {
.mode320x200 => 200,
.mode640x480 => 480,
};
pub fn isInBounds(x: isize, y: isize) bool {
return x >= 0 and y >= 0 and x < width and y < height;
}
fn write_regs(regs: [61]u8) void {
var index: usize = 0;
var i: u8 = 0;
// write MISCELLANEOUS reg
outportb(VGA_MISC_WRITE, regs[index]);
index += 1;
// write SEQUENCER regs
i = 0;
while (i < VGA_NUM_SEQ_REGS) : (i += 1) {
outportb(VGA_SEQ_INDEX, i);
outportb(VGA_SEQ_DATA, regs[index]);
index += 1;
}
// unlock CRTC registers
outportb(VGA_CRTC_INDEX, 0x03);
outportb(VGA_CRTC_DATA, inportb(VGA_CRTC_DATA) | 0x80);
outportb(VGA_CRTC_INDEX, 0x11);
outportb(VGA_CRTC_DATA, inportb(VGA_CRTC_DATA) & ~@as(u8, 0x80));
// make sure they remain unlocked
// TODO: Reinsert again
// regs[0x03] |= 0x80;
// regs[0x11] &= ~0x80;
// write CRTC regs
i = 0;
while (i < VGA_NUM_CRTC_REGS) : (i += 1) {
outportb(VGA_CRTC_INDEX, i);
outportb(VGA_CRTC_DATA, regs[index]);
index += 1;
}
// write GRAPHICS CONTROLLER regs
i = 0;
while (i < VGA_NUM_GC_REGS) : (i += 1) {
outportb(VGA_GC_INDEX, i);
outportb(VGA_GC_DATA, regs[index]);
index += 1;
}
// write ATTRIBUTE CONTROLLER regs
i = 0;
while (i < VGA_NUM_AC_REGS) : (i += 1) {
_ = inportb(VGA_INSTAT_READ);
outportb(VGA_AC_INDEX, i);
outportb(VGA_AC_WRITE, regs[index]);
index += 1;
}
// lock 16-color palette and unblank display
_ = inportb(VGA_INSTAT_READ);
outportb(VGA_AC_INDEX, 0x20);
}
pub fn setPlane(plane: u2) void {
const pmask: u8 = u8(1) << plane;
// set read plane
outportb(VGA_GC_INDEX, 4);
outportb(VGA_GC_DATA, plane);
// set write plane
outportb(VGA_SEQ_INDEX, 2);
outportb(VGA_SEQ_DATA, pmask);
}
pub fn init() void {
switch (mode) {
.mode320x200 => write_regs(g_320x200x256),
.mode640x480 => write_regs(g_640x480x16),
}
// write_regs(g_320x200x256);
}
fn get_fb_seg() [*]volatile u8 {
outportb(VGA_GC_INDEX, 6);
const seg = (inportb(VGA_GC_DATA) >> 2) & 3;
return @intToPtr([*]volatile u8, switch (@truncate(u2, seg)) {
0, 1 => @as(u32, 0xA0000),
2 => @as(u32, 0xB0000),
3 => @as(u32, 0xB8000),
});
}
fn vpokeb(off: usize, val: u8) void {
get_fb_seg()[off] = val;
}
fn vpeekb(off: usize) u8 {
return get_fb_seg()[off];
}
pub fn setPixelDirect(x: usize, y: usize, c: Color) void {
switch (mode) {
.mode320x200 => {
// setPlane(@truncate(u2, 0));
var segment = get_fb_seg();
segment[320 * y + x] = c;
},
.mode640x480 => {
const wd_in_bytes = 640 / 8;
const off = wd_in_bytes * y + x / 8;
const px = @truncate(u3, x & 7);
var mask: u8 = u8(0x80) >> px;
var pmask: u8 = 1;
comptime var p: usize = 0;
inline while (p < 4) : (p += 1) {
setPlane(@truncate(u2, p));
var segment = get_fb_seg();
const src = segment[off];
segment[off] = if ((pmask & c) != 0) src | mask else src & ~mask;
pmask <<= 1;
}
},
}
}
var backbuffer: [height][width]Color = undefined;
pub fn clear(c: Color) void {
for (backbuffer) |*row| {
for (row) |*pixel| {
pixel.* = c;
}
}
}
pub fn setPixel(x: usize, y: usize, c: Color) void {
backbuffer[y][x] = c;
}
pub fn getPixel(x: usize, y: usize) Color {
return backbuffer[y][x];
}
pub fn swapBuffers() void {
@setRuntimeSafety(false);
@setCold(false);
switch (mode) {
.mode320x200 => {
@intToPtr(*[height][width]Color, 0xA0000).* = backbuffer;
},
.mode640x480 => {
// const bytes_per_line = 640 / 8;
var plane: usize = 0;
while (plane < 4) : (plane += 1) {
const plane_mask: u8 = u8(1) << @truncate(u3, plane);
setPlane(@truncate(u2, plane));
var segment = get_fb_seg();
var offset: usize = 0;
var y: usize = 0;
while (y < 480) : (y += 1) {
var x: usize = 0;
while (x < 640) : (x += 8) {
// const offset = bytes_per_line * y + (x / 8);
var bits: u8 = 0;
// unroll for maximum fastness
comptime var px: usize = 0;
inline while (px < 8) : (px += 1) {
const mask = u8(0x80) >> px;
const index = backbuffer[y][x + px];
if ((index & plane_mask) != 0) {
bits |= mask;
}
}
segment[offset] = bits;
offset += 1;
}
}
}
},
}
}
pub const RGB = struct {
r: u8,
g: u8,
b: u8,
pub fn init(r: u8, g: u8, b: u8) RGB {
return RGB{
.r = r,
.g = g,
.b = b,
};
}
pub fn parse(rgb: []const u8) !RGB {
if (rgb.len != 7) return error.InvalidLength;
if (rgb[0] != '#') return error.InvalidFormat;
return RGB{
.r = try std.fmt.parseInt(u8, rgb[1..3], 16),
.g = try std.fmt.parseInt(u8, rgb[3..5], 16),
.b = try std.fmt.parseInt(u8, rgb[5..7], 16),
};
}
};
const PALETTE_INDEX = 0x03c8;
const PALETTE_DATA = 0x03c9;
// see: http://www.brackeen.com/vga/source/bc31/palette.c.html
pub fn loadPalette(palette: []const RGB) void {
io.out(u8, PALETTE_INDEX, 0); // tell the VGA that palette data is coming.
for (palette) |rgb| {
io.out(u8, PALETTE_DATA, rgb.r >> 2); // write the data
io.out(u8, PALETTE_DATA, rgb.g >> 2);
io.out(u8, PALETTE_DATA, rgb.b >> 2);
}
}
pub fn setPaletteEntry(entry: u8, color: RGB) void {
io.out(u8, PALETTE_INDEX, entry); // tell the VGA that palette data is coming.
io.out(u8, PALETTE_DATA, color.r >> 2); // write the data
io.out(u8, PALETTE_DATA, color.g >> 2);
io.out(u8, PALETTE_DATA, color.b >> 2);
}
// see: http://www.brackeen.com/vga/source/bc31/palette.c.html
pub fn waitForVSync() void {
const INPUT_STATUS = 0x03da;
const VRETRACE = 0x08;
// wait until done with vertical retrace
while ((io.in(u8, INPUT_STATUS) & VRETRACE) != 0) {}
// wait until done refreshing
while ((io.in(u8, INPUT_STATUS) & VRETRACE) == 0) {}
}
const VGA_AC_INDEX = 0x3C0;
const VGA_AC_WRITE = 0x3C0;
const VGA_AC_READ = 0x3C1;
const VGA_MISC_WRITE = 0x3C2;
const VGA_SEQ_INDEX = 0x3C4;
const VGA_SEQ_DATA = 0x3C5;
const VGA_DAC_READ_INDEX = 0x3C7;
const VGA_DAC_WRITE_INDEX = 0x3C8;
const VGA_DAC_DATA = 0x3C9;
const VGA_MISC_READ = 0x3CC;
const VGA_GC_INDEX = 0x3CE;
const VGA_GC_DATA = 0x3CF;
// COLOR emulation MONO emulation
const VGA_CRTC_INDEX = 0x3D4; // 0x3B4
const VGA_CRTC_DATA = 0x3D5; // 0x3B5
const VGA_INSTAT_READ = 0x3DA;
const VGA_NUM_SEQ_REGS = 5;
const VGA_NUM_CRTC_REGS = 25;
const VGA_NUM_GC_REGS = 9;
const VGA_NUM_AC_REGS = 21;
const VGA_NUM_REGS = (1 + VGA_NUM_SEQ_REGS + VGA_NUM_CRTC_REGS + VGA_NUM_GC_REGS + VGA_NUM_AC_REGS);
const g_40x25_text = [_]u8{
// MISC
0x67,
// SEQ
0x03,
0x08,
0x03,
0x00,
0x02,
// CRTC
0x2D,
0x27,
0x28,
0x90,
0x2B,
0xA0,
0xBF,
0x1F,
0x00,
0x4F,
0x0D,
0x0E,
0x00,
0x00,
0x00,
0xA0,
0x9C,
0x8E,
0x8F,
0x14,
0x1F,
0x96,
0xB9,
0xA3,
0xFF,
// GC
0x00,
0x00,
0x00,
0x00,
0x00,
0x10,
0x0E,
0x00,
0xFF,
// AC
0x00,
0x01,
0x02,
0x03,
0x04,
0x05,
0x14,
0x07,
0x38,
0x39,
0x3A,
0x3B,
0x3C,
0x3D,
0x3E,
0x3F,
0x0C,
0x00,
0x0F,
0x08,
0x00,
};
const g_40x50_text = [_]u8{
// MISC
0x67,
// SEQ
0x03,
0x08,
0x03,
0x00,
0x02,
// CRTC
0x2D,
0x27,
0x28,
0x90,
0x2B,
0xA0,
0xBF,
0x1F,
0x00,
0x47,
0x06,
0x07,
0x00,
0x00,
0x04,
0x60,
0x9C,
0x8E,
0x8F,
0x14,
0x1F,
0x96,
0xB9,
0xA3,
0xFF,
// GC
0x00,
0x00,
0x00,
0x00,
0x00,
0x10,
0x0E,
0x00,
0xFF,
// AC
0x00,
0x01,
0x02,
0x03,
0x04,
0x05,
0x14,
0x07,
0x38,
0x39,
0x3A,
0x3B,
0x3C,
0x3D,
0x3E,
0x3F,
0x0C,
0x00,
0x0F,
0x08,
0x00,
};
const g_80x25_text = [_]u8{
// MISC
0x67,
// SEQ
0x03,
0x00,
0x03,
0x00,
0x02,
// CRTC
0x5F,
0x4F,
0x50,
0x82,
0x55,
0x81,
0xBF,
0x1F,
0x00,
0x4F,
0x0D,
0x0E,
0x00,
0x00,
0x00,
0x50,
0x9C,
0x0E,
0x8F,
0x28,
0x1F,
0x96,
0xB9,
0xA3,
0xFF,
// GC
0x00,
0x00,
0x00,
0x00,
0x00,
0x10,
0x0E,
0x00,
0xFF,
// AC
0x00,
0x01,
0x02,
0x03,
0x04,
0x05,
0x14,
0x07,
0x38,
0x39,
0x3A,
0x3B,
0x3C,
0x3D,
0x3E,
0x3F,
0x0C,
0x00,
0x0F,
0x08,
0x00,
};
const g_80x50_text = [_]u8{
// MISC
0x67,
// SEQ
0x03,
0x00,
0x03,
0x00,
0x02,
// CRTC
0x5F,
0x4F,
0x50,
0x82,
0x55,
0x81,
0xBF,
0x1F,
0x00,
0x47,
0x06,
0x07,
0x00,
0x00,
0x01,
0x40,
0x9C,
0x8E,
0x8F,
0x28,
0x1F,
0x96,
0xB9,
0xA3,
0xFF,
// GC
0x00,
0x00,
0x00,
0x00,
0x00,
0x10,
0x0E,
0x00,
0xFF,
// AC
0x00,
0x01,
0x02,
0x03,
0x04,
0x05,
0x14,
0x07,
0x38,
0x39,
0x3A,
0x3B,
0x3C,
0x3D,
0x3E,
0x3F,
0x0C,
0x00,
0x0F,
0x08,
0x00,
};
const g_90x30_text = [_]u8{
// MISC
0xE7,
// SEQ
0x03,
0x01,
0x03,
0x00,
0x02,
// CRTC
0x6B,
0x59,
0x5A,
0x82,
0x60,
0x8D,
0x0B,
0x3E,
0x00,
0x4F,
0x0D,
0x0E,
0x00,
0x00,
0x00,
0x00,
0xEA,
0x0C,
0xDF,
0x2D,
0x10,
0xE8,
0x05,
0xA3,
0xFF,
// GC
0x00,
0x00,
0x00,
0x00,
0x00,
0x10,
0x0E,
0x00,
0xFF,
// AC
0x00,
0x01,
0x02,
0x03,
0x04,
0x05,
0x14,
0x07,
0x38,
0x39,
0x3A,
0x3B,
0x3C,
0x3D,
0x3E,
0x3F,
0x0C,
0x00,
0x0F,
0x08,
0x00,
};
const g_90x60_text = [_]u8{
// MISC
0xE7,
// SEQ
0x03,
0x01,
0x03,
0x00,
0x02,
// CRTC
0x6B,
0x59,
0x5A,
0x82,
0x60,
0x8D,
0x0B,
0x3E,
0x00,
0x47,
0x06,
0x07,
0x00,
0x00,
0x00,
0x00,
0xEA,
0x0C,
0xDF,
0x2D,
0x08,
0xE8,
0x05,
0xA3,
0xFF,
// GC
0x00,
0x00,
0x00,
0x00,
0x00,
0x10,
0x0E,
0x00,
0xFF,
// AC
0x00,
0x01,
0x02,
0x03,
0x04,
0x05,
0x14,
0x07,
0x38,
0x39,
0x3A,
0x3B,
0x3C,
0x3D,
0x3E,
0x3F,
0x0C,
0x00,
0x0F,
0x08,
0x00,
};
// ****************************************************************************
// VGA REGISTER DUMPS FOR VARIOUS GRAPHICS MODES
// ****************************************************************************
const g_640x480x2 = [_]u8{
// MISC
0xE3,
// SEQ
0x03,
0x01,
0x0F,
0x00,
0x06,
// CRTC
0x5F,
0x4F,
0x50,
0x82,
0x54,
0x80,
0x0B,
0x3E,
0x00,
0x40,
0x00,
0x00,
0x00,
0x00,
0x00,
0x00,
0xEA,
0x0C,
0xDF,
0x28,
0x00,
0xE7,
0x04,
0xE3,
0xFF,
// GC
0x00,
0x00,
0x00,
0x00,
0x00,
0x00,
0x05,
0x0F,
0xFF,
// AC
0x00,
0x01,
0x02,
0x03,
0x04,
0x05,
0x14,
0x07,
0x38,
0x39,
0x3A,
0x3B,
0x3C,
0x3D,
0x3E,
0x3F,
0x01,
0x00,
0x0F,
0x00,
0x00,
};
//****************************************************************************
// *** NOTE: the mode described by g_320x200x4[]
// is different from BIOS mode 05h in two ways:
// - Framebuffer is at A000:0000 instead of B800:0000
// - Framebuffer is linear (no screwy line-by-line CGA addressing)
// ****************************************************************************
const g_320x200x4 = [_]u8{
// MISC
0x63,
// SEQ
0x03,
0x09,
0x03,
0x00,
0x02,
// CRTC
0x2D,
0x27,
0x28,
0x90,
0x2B,
0x80,
0xBF,
0x1F,
0x00,
0x41,
0x00,
0x00,
0x00,
0x00,
0x00,
0x00,
0x9C,
0x0E,
0x8F,
0x14,
0x00,
0x96,
0xB9,
0xA3,
0xFF,
// GC
0x00,
0x00,
0x00,
0x00,
0x00,
0x30,
0x02,
0x00,
0xFF,
// AC
0x00,
0x13,
0x15,
0x17,
0x02,
0x04,
0x06,
0x07,
0x10,
0x11,
0x12,
0x13,
0x14,
0x15,
0x16,
0x17,
0x01,
0x00,
0x03,
0x00,
0x00,
};
const g_640x480x16 = [_]u8{
// MISC
0xE3,
// SEQ
0x03,
0x01,
0x08,
0x00,
0x06,
// CRTC
0x5F,
0x4F,
0x50,
0x82,
0x54,
0x80,
0x0B,
0x3E,
0x00,
0x40,
0x00,
0x00,
0x00,
0x00,
0x00,
0x00,
0xEA,
0x0C,
0xDF,
0x28,
0x00,
0xE7,
0x04,
0xE3,
0xFF,
// GC
0x00,
0x00,
0x00,
0x00,
0x03,
0x00,
0x05,
0x0F,
0xFF,
// AC
0x00,
0x01,
0x02,
0x03,
0x04,
0x05,
0x14,
0x07,
0x38,
0x39,
0x3A,
0x3B,
0x3C,
0x3D,
0x3E,
0x3F,
0x01,
0x00,
0x0F,
0x00,
0x00,
};
const g_720x480x16 = [_]u8{
// MISC
0xE7,
// SEQ
0x03,
0x01,
0x08,
0x00,
0x06,
// CRTC
0x6B,
0x59,
0x5A,
0x82,
0x60,
0x8D,
0x0B,
0x3E,
0x00,
0x40,
0x06,
0x07,
0x00,
0x00,
0x00,
0x00,
0xEA,
0x0C,
0xDF,
0x2D,
0x08,
0xE8,
0x05,
0xE3,
0xFF,
// GC
0x00,
0x00,
0x00,
0x00,
0x03,
0x00,
0x05,
0x0F,
0xFF,
// AC
0x00,
0x01,
0x02,
0x03,
0x04,
0x05,
0x06,
0x07,
0x08,
0x09,
0x0A,
0x0B,
0x0C,
0x0D,
0x0E,
0x0F,
0x01,
0x00,
0x0F,
0x00,
0x00,
};
const g_320x200x256 = [_]u8{
// MISC
0x63,
// SEQ
0x03,
0x01,
0x0F,
0x00,
0x0E,
// CRTC
0x5F,
0x4F,
0x50,
0x82,
0x54,
0x80,
0xBF,
0x1F,
0x00,
0x41,
0x00,
0x00,
0x00,
0x00,
0x00,
0x00,
0x9C,
0x0E,
0x8F,
0x28,
0x40,
0x96,
0xB9,
0xA3,
0xFF,
// GC
0x00,
0x00,
0x00,
0x00,
0x00,
0x40,
0x05,
0x0F,
0xFF,
// AC
0x00,
0x01,
0x02,
0x03,
0x04,
0x05,
0x06,
0x07,
0x08,
0x09,
0x0A,
0x0B,
0x0C,
0x0D,
0x0E,
0x0F,
0x41,
0x00,
0x0F,
0x00,
0x00,
};
const g_320x200x256_modex = [_]u8{
// MISC
0x63,
// SEQ
0x03,
0x01,
0x0F,
0x00,
0x06,
// CRTC
0x5F,
0x4F,
0x50,
0x82,
0x54,
0x80,
0xBF,
0x1F,
0x00,
0x41,
0x00,
0x00,
0x00,
0x00,
0x00,
0x00,
0x9C,
0x0E,
0x8F,
0x28,
0x00,
0x96,
0xB9,
0xE3,
0xFF,
// GC
0x00,
0x00,
0x00,
0x00,
0x00,
0x40,
0x05,
0x0F,
0xFF,
// AC
0x00,
0x01,
0x02,
0x03,
0x04,
0x05,
0x06,
0x07,
0x08,
0x09,
0x0A,
0x0B,
0x0C,
0x0D,
0x0E,
0x0F,
0x41,
0x00,
0x0F,
0x00,
0x00,
};
|
0 | repos/Ziguana-Game-System/old-version/kernel | repos/Ziguana-Game-System/old-version/kernel/src/multiboot.zig | const std = @import("std");
pub const Header = packed struct {
magic: u32 = 0x1badb002,
flags: Flags = 0,
checksum: u32 = 0,
header_addr: u32 = 0,
load_addr: u32 = 0,
load_end_addr: u32 = 0,
bss_end_addr: u32 = 0,
entry_addr: u32 = 0,
mode_type: u32 = 0,
width: u32 = 0,
height: u32 = 0,
depth: u32 = 0,
const Flags = packed struct {
aligned: bool,
provideMmap: bool,
provideVideoMode: bool,
_0: u12 = 0,
overrideLoadAddress: bool,
_1: u16 = 0,
};
comptime {
std.debug.assert(@sizeOf(Flags) == 4);
}
pub fn init() Header {
var header = Header{
.flags = Flags{
.aligned = true,
.provideMmap = true,
.provideVideoMode = false,
.overrideLoadAddress = false,
},
};
header.checksum = calcChecksum(&header);
// // Validate header checksum
// var cs: u32 = 0;
// inline for (@typeInfo(@This()).Struct.fields) |fld| {
// _ = @addWithOverflow(u32, cs, @bitCast(u32, @field(header, fld.name)), &cs);
// }
// std.debug.assert(cs == 0);
return header;
}
fn calcChecksum(header: *Header) u32 {
var cs: u32 = 0;
// inline for (@typeInfo(@This()).Struct.fields) |fld| {
// if (!std.mem.eql(u8, fld.name, "checksum")) {
// _ = @subWithOverflow(u32, cs, @bitCast(u32, @field(header, fld.name)), &cs);
// }
// }
_ = @subWithOverflow(u32, cs, @bitCast(u32, header.flags), &cs);
_ = @subWithOverflow(u32, cs, @bitCast(u32, header.magic), &cs);
return cs;
}
};
pub const Structure = packed struct {
flags: u32,
mem: Memory,
boot_device: u32,
cmdline: [*]u8,
mods: Modules,
syms: [4]u32,
mmap: MemoryMap,
drives: Drives,
config_table: u32,
boot_loader_name: [*]u8,
apm_table: u32,
vbe: VesaBiosExtensions,
framebuffer: Framebuffer,
pub const Flags = packed struct {
mem: bool,
boot_device: bool,
cmdline: bool,
mods: bool,
syms: bool,
syms2: bool,
mmap: bool,
drives: bool,
config_table: bool,
boot_loader_name: bool,
apm_table: bool,
vbe: bool,
framebuffer: bool,
// WORKAROUND: This is a compiler bug, see
// https://github.com/ziglang/zig/issues/2627
_0: u3,
_1: u16,
};
pub const Modules = extern struct {
mods_count: u32,
mods_addr: u32,
};
pub const Memory = extern struct {
lower: u32,
upper: u32,
};
pub const MemoryMap = extern struct {
mmap_length: u32,
mmap_addr: u32,
const Type = enum(u32) {
available = 1,
reserved = 2,
acpi = 3,
reservedForHibernation = 4,
defectiveRAM = 5,
};
const Entry = packed struct {
size: u32,
baseAddress: u64,
length: u64,
type: Type,
};
const Iterator = struct {
end_pos: u32,
current_pos: u32,
pub fn next(this: *Iterator) ?*const Entry {
// official multiboot documentation is bad here :(
// this is the right way to iterate over the multiboot structure
if (this.current_pos >= this.end_pos) {
return null;
} else {
var current = @intToPtr(*const Entry, this.current_pos);
this.current_pos += (current.size + 0x04);
return current;
}
}
};
pub fn iterator(this: MemoryMap) Iterator {
return Iterator{
.end_pos = this.mmap_addr + this.mmap_length,
.current_pos = this.mmap_addr,
};
}
};
pub const Drives = extern struct {
drives_length: u32,
drives_addr: u32,
};
pub const VesaBiosExtensions = extern struct {
control_info: u32,
mode_info: u32,
mode: u16,
interface_seg: u16,
interface_off: u16,
interface_len: u16,
};
pub const Framebuffer = extern struct {
addr_low: u32,
addr_high: u32,
pitch: u32,
width: u32,
height: u32,
bpp: u8,
type: u8,
color_info: [5]u8,
};
comptime {
std.debug.assert(@byteOffsetOf(@This(), "mem") == 4);
std.debug.assert(@byteOffsetOf(@This(), "vbe") == 72);
std.debug.assert(@byteOffsetOf(@This(), "framebuffer") == 88);
}
};
|
0 | repos/Ziguana-Game-System/old-version/kernel | repos/Ziguana-Game-System/old-version/kernel/src/debug-info.zig | const std = @import("std");
const Terminal = @import("text-terminal.zig");
const SerialOutStream = struct {
const This = @This();
fn print(_: This, comptime fmt: []const u8, args: anytype) error{Never}!void {
Terminal.print(fmt, args);
}
fn write(_: This, text: []const u8) error{Never}!void {
Terminal.print("{}", text);
}
fn writeByte(_: This, byte: u8) error{Never}!void {
Terminal.print("{c}", byte);
}
};
const serial_out_stream = SerialOutStream{};
fn printLineFromFile(out_stream: anytype, line_info: std.debug.LineInfo) anyerror!void {
Terminal.println("TODO print line from the file\n");
}
var kernel_panic_allocator_bytes: [4 * 1024 * 1024]u8 = undefined;
var kernel_panic_allocator_state = std.heap.FixedBufferAllocator.init(kernel_panic_allocator_bytes[0..]);
const kernel_panic_allocator = &kernel_panic_allocator_state.allocator;
extern var __debug_info_start: u8;
extern var __debug_info_end: u8;
extern var __debug_abbrev_start: u8;
extern var __debug_abbrev_end: u8;
extern var __debug_str_start: u8;
extern var __debug_str_end: u8;
extern var __debug_line_start: u8;
extern var __debug_line_end: u8;
extern var __debug_ranges_start: u8;
extern var __debug_ranges_end: u8;
fn dwarfSectionFromSymbolAbs(start: *u8, end: *u8) std.debug.DwarfInfo.Section {
return std.debug.DwarfInfo.Section{
.offset = 0,
.size = @ptrToInt(end) - @ptrToInt(start),
};
}
fn dwarfSectionFromSymbol(start: *u8, end: *u8) std.debug.DwarfInfo.Section {
return std.debug.DwarfInfo.Section{
.offset = @ptrToInt(start),
.size = @ptrToInt(end) - @ptrToInt(start),
};
}
fn getSelfDebugInfo() !*std.debug.DwarfInfo {
const S = struct {
var have_self_debug_info = false;
var self_debug_info: std.debug.DwarfInfo = undefined;
var in_stream_state = std.io.InStream(anyerror){ .readFn = readFn };
var in_stream_pos: usize = 0;
const in_stream = &in_stream_state;
fn readFn(self: *std.io.InStream(anyerror), buffer: []u8) anyerror!usize {
const ptr = @intToPtr([*]const u8, in_stream_pos);
std.mem.copy(u8, buffer, ptr[0..buffer.len]);
in_stream_pos += buffer.len;
return buffer.len;
}
const SeekableStream = std.io.SeekableStream(anyerror, anyerror);
var seekable_stream_state = SeekableStream{
.seekToFn = seekToFn,
.seekByFn = seekForwardFn,
.getPosFn = getPosFn,
.getEndPosFn = getEndPosFn,
};
const seekable_stream = &seekable_stream_state;
fn seekToFn(self: *SeekableStream, pos: u64) anyerror!void {
in_stream_pos = @intCast(usize, pos);
}
fn seekForwardFn(self: *SeekableStream, pos: i64) anyerror!void {
in_stream_pos = @bitCast(usize, @bitCast(isize, in_stream_pos) +% @intCast(isize, pos));
}
fn getPosFn(self: *SeekableStream) anyerror!u64 {
return in_stream_pos;
}
fn getEndPosFn(self: *SeekableStream) anyerror!u64 {
return @ptrToInt(&__debug_ranges_end);
}
};
if (S.have_self_debug_info)
return &S.self_debug_info;
S.self_debug_info = std.debug.DwarfInfo{
.dwarf_seekable_stream = S.seekable_stream,
.dwarf_in_stream = S.in_stream,
.endian = builtin.Endian.Little,
.debug_info = dwarfSectionFromSymbol(&__debug_info_start, &__debug_info_end),
.debug_abbrev = dwarfSectionFromSymbolAbs(&__debug_abbrev_start, &__debug_abbrev_end),
.debug_str = dwarfSectionFromSymbolAbs(&__debug_str_start, &__debug_str_end),
.debug_line = dwarfSectionFromSymbol(&__debug_line_start, &__debug_line_end),
.debug_ranges = dwarfSectionFromSymbolAbs(&__debug_ranges_start, &__debug_ranges_end),
.abbrev_table_list = undefined,
.compile_unit_list = undefined,
.func_list = undefined,
};
try std.debug.openDwarfDebugInfo(&S.self_debug_info, kernel_panic_allocator);
return &S.self_debug_info;
}
|
0 | repos/Ziguana-Game-System/old-version | repos/Ziguana-Game-System/old-version/scratchpad/brainstorm.txt | Resourcentypen:
- Image / Sprite
- Freie Größe, 4bpp
- Hat eine "Standard-Palette" zugeordnet (für korrekte Darstellung)
- Dataset
- BLOB mit Datenformat
- 1D: Länge, 2D: Breite×Höhe
- Datenformat: U8, U16, U32
- Code File
- []u8
- Paletten
- 16 Einträge mit RGB666
- Audio
- soundhw sb16,adlib
- custom ADSR synth
- Save Games
- Spezielle Resource
- Max. 3 Stück
- Sind nur als "benötigen N byte" definiert
Daten liegen als "linked list" auf der Diskette,
vorne ist ein Header:
Header {
magic: u32, // 0x56ac65d5
version: u32, // 1
name: [32]u8, // zero-terminated or full
saveGameSize: u32,
}
Code {
length: u32,
data: []u8,
}
Resource {
type: u8,
length: u32,
name: []u8,
union {
EndOfList{},
Palette { [16]RGB }
Image {
w: u16,
h: u16,
pal: u8,
ptr: []u4
}
Save Game { [N]u8 },
Music { ??? },
SFX { ??? },
DataSet {
format: enum{u8,16,u32},
width: u32, // if ≤ 1 ⇒ 1D
height: u32
data: []u8
}
}
}
Mehr als eine Palette erlauben?
+ Pro: Bequemeres Palette wechseln
- Con: Höhere Komplexität, schwerer zu verwenden
=> Mehr als eine Palette erlauben
Vollfarb-Palette (256 einträge) erlauben?
+ Pro: Maximale Ausreizung
- Con: Wie soll die UI im Bildeditor aussehen? Nutzt ja selbe Palette
=> Nur 16 Farben pro Bilddatei
Mehr als ein Code File erlauben?
+ Pro: Bessere Strukturierung
- Con: Komplexere Implementierung, kein "Go To Definition"
=> Einzelnes Codestück
synth features:
- duty cycle / steepness
- frequency mixing (waveforms)
-
|
0 | repos/Ziguana-Game-System/old-version/prototypes | repos/Ziguana-Game-System/old-version/prototypes/wavesynth/build.zig | const Builder = @import("std").build.Builder;
pub fn build(b: *Builder) void {
const mode = b.standardReleaseOptions();
const exe = b.addExecutable("wavesynth", "src/main.zig");
exe.setBuildMode(mode);
exe.linkSystemLibrary("libpulse-simple");
exe.install();
const run_cmd = exe.run();
run_cmd.step.dependOn(b.getInstallStep());
const run_step = b.step("run", "Run the app");
run_step.dependOn(&run_cmd.step);
}
|
0 | repos/Ziguana-Game-System/old-version/prototypes/wavesynth | repos/Ziguana-Game-System/old-version/prototypes/wavesynth/src/main.zig | const std = @import("std");
const PA = @import("pa-simple.zig");
// 7 3 4 2
// N I V E
const song_text_form =
\\D-3 0
\\E-3
\\F-3
\\G-3
\\A-3
\\ =
\\A-3
\\ =
\\B-3
\\B-3
\\B-3
\\B-3
\\A-3
\\ =
\\
\\
\\G-3
\\G-3
\\G-3
\\G-3
\\F-3
\\ =
\\F-3
\\ =
\\A-3
\\A-3
\\A-3
\\A-3
\\D-3
\\
;
const song_drum_form =
\\A-4 3 4
\\
\\A-4 2
\\
\\A-4 3
\\
\\A-4 2
\\
\\A-4 3
\\
\\A-4 2
\\
\\A-4 3
\\
\\A-4 2
\\
\\A-4 3
\\
\\A-4 2
\\
\\A-4 3
\\
\\A-4 2
\\
\\A-4 3
\\
\\A-4 2
\\
\\A-4 3
\\
\\A-4 2
\\
;
const song_pad_form =
\\D-2 1 8
\\ =
\\ =
\\
\\C-2
\\ =
\\ =
\\
\\E-2
\\ =
\\ =
\\ =
\\ =
\\ =
\\ =
\\
\\C-2
\\ =
\\ =
\\
\\B-1
\\ =
\\ =
\\
\\C-2
\\ =
\\ =
\\
\\E-2
\\ =
\\ =
\\
;
pub fn loadChannelFromText(allocator: *std.mem.Allocator, source: []const u8) ![]Event {
var list = std.ArrayList(Event).init(allocator);
var iterator = std.mem.separate(source, "\n");
var lastInstr: u3 = 0;
var lastVolume: u4 = 0xC;
while (iterator.next()) |line| {
switch (line.len) {
0, 3, 5, 7, 9 => {},
else => return error.InvalidFormat,
}
if (line.len == 0) {
// note-off event
try list.append(Event.off);
continue;
}
var event = Event{
.note = if (std.mem.eql(u8, line[0..3], " = ")) Note.repeated else try Note.parse(line[0..3]),
.instr = if (line.len >= 5 and line[4] != ' ') try std.fmt.parseInt(u3, line[4..5], 16) else lastInstr,
.volume = if (line.len >= 7 and line[6] != ' ') try std.fmt.parseInt(u4, line[6..7], 16) else lastVolume,
.effect = if (line.len >= 9) try std.fmt.parseInt(u2, line[8..9], 16) else 0,
};
lastVolume = event.volume;
lastInstr = event.instr;
try list.append(event);
}
return list.toOwnedSlice();
}
const Event = struct {
note: Note,
instr: u3,
volume: u4 = 0xF,
effect: u2 = 0x0,
pub const off = @This(){ .note = Note{ .index = 0 }, .instr = 0, .volume = 0 };
};
/// A note on the piano keyboard.
/// Indexed "left to right", starting at C0
const Note = struct {
index: u7,
pub const repeated = @This(){ .index = 127 };
/// converts english note notation (A#1) to key index (14).
/// Lowest note is C0 (16.3516 Hz), highest note is C8 (4186,01 Hz).
pub fn parse(spec: []const u8) !Note {
if (spec.len < 2 or spec.len > 3)
return error.InvalidFormat;
var modifier: enum {
none,
sharp,
} = .none;
var noteName = spec[0];
if (spec.len == 3) {
modifier = switch (spec[1]) {
'#' => @typeOf(modifier).sharp,
'-' => .none,
else => return error.InvalidFormat,
};
}
// 0 ...
var index = try std.fmt.parseInt(u7, spec[spec.len - 1 ..], 10);
const allowsModifier = switch (noteName) {
'A', 'C', 'D', 'F', 'G' => true,
else => false,
};
if (!allowsModifier and modifier != .none)
return error.InvalidNote;
var note = 12 * index + switch (noteName) {
'C' => @as(u7, 0),
'D' => 2,
'E' => 4,
'F' => 5,
'G' => 7,
'A' => 9,
'B' => 11,
else => return error.InvalidNote,
};
note += switch (modifier) {
.sharp => @as(u7, 1),
.none => 0,
};
return Note{
.index = note,
};
}
// converts key index on keyboard (14) to frequency (58,2705 Hz)
pub fn toFreq(note: Note) f32 {
// freq(i)=440 hertz * (2^(1/12))^(i - 49)
// see: https://en.wikipedia.org/wiki/Piano_key_frequencies
return 440.0 * std.math.pow(f32, std.math.pow(f32, 2, 1.0 / 12.0), @intToFloat(f32, note.index) - 49.0 - 8.0); // 8.0 is the adjustment for "offset" index
}
pub fn format(value: Note, comptime fmt: []const u8, options: std.fmt.FormatOptions, context: var, comptime Errors: type, output: fn (@typeOf(context), []const u8) Errors!void) Errors!void {
const name = value.index % 12;
const offset = value.index / 12;
try std.fmt.format(context, Errors, output, "{}{}", switch (name) {
0 => "C",
1 => "C#",
2 => "D",
3 => "D#",
4 => "E",
5 => "F",
6 => "F#",
7 => "G",
8 => "G#",
9 => "A",
10 => "A#",
11 => "B",
else => unreachable,
}, offset);
}
};
test "Note.parse" {
std.debug.assert((try Note.parse("C0")).index == 0);
std.debug.assert((try Note.parse("C1")).index == 12);
std.debug.assert((try Note.parse("G5")).index == 67);
std.debug.assert((try Note.parse("A4")).index == 57);
std.debug.assert((try Note.parse("C-1")).index == 12);
std.debug.assert((try Note.parse("G-5")).index == 67);
std.debug.assert((try Note.parse("A-4")).index == 57);
std.debug.assert((try Note.parse("D#4")).index == 51);
std.debug.assert((try Note.parse("A#6")).index == 82);
}
test "Note.toFreq" {
const floatEq = struct {
fn floatEq(value: f32, comptime expected: f32) bool {
// maximum offset is 1‰
return std.math.fabs(value - expected) < std.math.fabs(expected) / 1000.0;
}
}.floatEq;
std.debug.assert(floatEq((Note{ .index = 57 }).toFreq(), 440.0)); // A4
std.debug.assert(floatEq((Note{ .index = 48 }).toFreq(), 261.626)); // C4
std.debug.assert(floatEq((Note{ .index = 30 }).toFreq(), 92.4986)); // F#2
std.debug.assert(floatEq((Note{ .index = 18 }).toFreq(), 46.2493)); // F#1
std.debug.assert(floatEq((Note{ .index = 9 }).toFreq(), 27.5)); // A0
}
test "Note.format" {
var buffer = " " ** 64;
std.debug.assert(std.mem.eql(u8, "A4", try std.fmt.bufPrint(buffer[0..], "{}", Note{ .index = 57 })));
std.debug.assert(std.mem.eql(u8, "C4", try std.fmt.bufPrint(buffer[0..], "{}", Note{ .index = 48 })));
std.debug.assert(std.mem.eql(u8, "F#2", try std.fmt.bufPrint(buffer[0..], "{}", Note{ .index = 30 })));
std.debug.assert(std.mem.eql(u8, "F#1", try std.fmt.bufPrint(buffer[0..], "{}", Note{ .index = 18 })));
std.debug.assert(std.mem.eql(u8, "A0", try std.fmt.bufPrint(buffer[0..], "{}", Note{ .index = 9 })));
}
pub fn bpmToSecondsPerBeat(bpm: f32) f32 {
return (60.0 / bpm);
}
const Instrument = struct {
const This = @This();
envelope: Envelope,
waveform: Waveform,
pub fn synthesize(this: Instrument, time: f32, note: Note, on_time: f32, off_time: ?f32) f32 {
const env = this.envelope.getAmplitude(time, on_time, off_time);
// 70ies synth ahoi!
return env * oscillate(time, note.toFreq(), this.waveform);
}
};
const instruments = [_]Instrument{
// "Piano"
Instrument{
.waveform = .triangle,
.envelope = Envelope{
.attackTime = 0.005,
.decayTime = 0.4,
.releaseTime = 0.0,
.sustainLevel = 0.0,
},
},
// "Pad"
Instrument{
.waveform = .sine,
.envelope = Envelope{
.attackTime = 0.3,
.decayTime = 0.3,
.releaseTime = 0.2,
.sustainLevel = 0.7,
},
},
// "Snare Drum"
Instrument{
.waveform = .noise,
.envelope = Envelope{
.attackTime = 0.0,
.decayTime = 0.1,
.releaseTime = 0.0,
.sustainLevel = 0.0,
},
},
// "Bass Drum"
Instrument{
.waveform = .noise,
.envelope = Envelope{
.attackTime = 0.05,
.decayTime = 0.1,
.releaseTime = 0.0,
.sustainLevel = 0.0,
},
},
};
const Channel = struct {
const This = @This();
events: []const Event,
instruments: []const Instrument,
const CurrentNote = struct {
note: Note,
on_time: f32,
off_time: ?f32,
instrument: u3,
};
currentNote: ?CurrentNote = null,
currentVolume: f32 = 1.0,
pub fn synthesize(this: *This, time: f32, tempo: f32) f32 {
if (time < 0)
return 0.0;
const time_per_beat = bpmToSecondsPerBeat(tempo);
const trackIndex = @floatToInt(usize, std.math.floor(time / time_per_beat));
const start_of_note = time_per_beat * @intToFloat(f32, trackIndex);
if (trackIndex < this.events.len) {
const event = this.events[trackIndex];
const is_on = (event.volume > 0);
if (is_on) {
if (event.note.index != Note.repeated.index) {
this.currentNote = CurrentNote{
.note = event.note,
.on_time = start_of_note,
.off_time = null,
.instrument = event.instr,
};
}
this.currentVolume = @intToFloat(f32, event.volume) / @intToFloat(f32, std.math.maxInt(@typeOf(event.volume)));
} else if (this.currentNote) |*cn| {
if (cn.off_time == null) {
std.debug.assert(start_of_note > cn.on_time);
cn.off_time = start_of_note;
}
}
} else {
if (this.currentNote) |*cn| {
if (cn.off_time == null) {
std.debug.assert(start_of_note > cn.on_time);
cn.off_time = start_of_note;
}
}
}
if (this.currentNote) |cn| {
const instrument = this.instruments[cn.instrument];
return this.currentVolume * instrument.synthesize(time, cn.note, cn.on_time, cn.off_time);
} else {
return 0.0;
}
}
};
pub fn main() anyerror!void {
const sampleSpec = PA.SampleSpecification{
.format = .float32le,
.channels = 2,
.rate = 44100,
};
var stream = try PA.Stream.openPlayback(null, // Use the default server.
c"Ziguana Game System", // Our application's name.
null, // Use the default device.
c"Wave Synth", // Description of our stream.
&sampleSpec, // Our sample format.
null, // Use default channel map
null // Use default buffering attributes.
);
defer stream.close();
std.debug.warn("Starting playback...\n");
// render ADSR
if (false) {
var t: f32 = 0.0;
const in = instruments[1]; // PAD
const spaces = " " ** 64;
var prevT: f32 = -1.0;
while (t <= 10.0) : (t += 0.1) {
var amp = in.envelope.getAmplitude(t, 1.0, 8.0);
if (std.math.floor(prevT) < std.math.floor(t)) {
std.debug.warn("{}", @floatToInt(usize, std.math.floor(t)));
}
std.debug.warn("\t|{}⏺\n", spaces[0..@floatToInt(usize, std.math.floor(48.0 * amp + 0.5))]);
prevT = t;
}
}
var channels = [_]Channel{ Channel{
.instruments = instruments,
.events = try loadChannelFromText(std.heap.direct_allocator, song_text_form),
}, Channel{
.instruments = instruments,
.events = try loadChannelFromText(std.heap.direct_allocator, song_drum_form),
}, Channel{
.instruments = instruments,
.events = try loadChannelFromText(std.heap.direct_allocator, song_pad_form),
} };
// Plays "Alle meine Entchen" at 120 BPM
// One Event is 1 eighth (1/8)
const tempo = 120.0; // 120 BPM
var buffer = [_]f32{0} ** 256;
var time: f32 = -2.0; // start in negative space, so "play two seconds of silence"
while (true) {
for (buffer) |*sample, i| {
const t = (time + @intToFloat(f32, i) / @as(f32, sampleSpec.rate));
if (t >= 0) {
sample.* = 0;
for (channels) |*channel| {
sample.* += channel.synthesize(t, tempo);
}
} else {
sample.* = 0.0;
}
// limiter:
const K = 1.0;
sample.* = std.math.copysign(f32, 1.0 + -std.math.pow(f32, std.math.e, -K * std.math.fabs(sample.*)), sample.*);
// sample.* *= 0.8;
}
time += @as(f32, buffer.len) / @as(f32, sampleSpec.rate);
try stream.write(@sliceToBytes(buffer[0..]));
if (time >= 1.0 + @intToFloat(f32, channels[0].events.len) * bpmToSecondsPerBeat(tempo))
break;
}
}
fn lerp(a: var, b: @typeOf(a), f: @typeOf(a)) @typeOf(a) {
return a * (1.0 - f) + b * f;
}
pub fn freqToAngleVelocity(freq: f32) f32 {
return freq * 2 * std.math.pi;
}
pub const Waveform = enum {
sine,
square,
sawtooth,
triangle,
noise,
};
var noiseRng = std.rand.DefaultPrng.init(1);
pub fn oscillate(time: f32, freq: f32, kind: Waveform) f32 {
const av = freqToAngleVelocity(freq);
return switch (kind) {
.sine => std.math.sin(av * time),
.square => if (std.math.sin(av * time) > 0.0) @as(f32, 1.0) else @as(f32, -1.0),
.triangle => (2.0 / std.math.pi) * std.math.asin(std.math.sin(av * time)),
.sawtooth => 2.0 * std.math.modf(freq * time).fpart - 1.0,
.noise => 2.0 * noiseRng.random.float(f32) - 1.0,
};
}
pub const Envelope = struct {
attackTime: f32,
decayTime: f32,
releaseTime: f32,
attackLevel: f32 = 1.0,
sustainLevel: f32,
pub fn getAmplitude(self: Envelope, time: f32, onTime: f32, offTime: ?f32) f32 {
const dt = time - onTime;
if (dt < 0.0) {
return 0.0;
} else if (dt < self.attackTime) {
return self.attackLevel * (dt / self.attackTime);
} else if (offTime) |off| {
if (time >= off) {
const offdt = time - off;
if (offdt < self.releaseTime) {
return lerp(self.sustainLevel, 0.0, offdt / self.releaseTime);
} else {
return 0;
}
}
}
if (dt < self.attackTime + self.decayTime) {
return lerp(self.attackLevel, self.sustainLevel, ((dt - self.attackTime) / self.decayTime));
} else {
return self.sustainLevel;
}
}
};
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.