all: move standalone libraries to libs/ subdirectory

The root dir of our repository has grown quite a lot the past few months.

I'd like to make it more clear where the bulk of the engine lives (`src/`) and
also make it more clear which Mach libraries are consumable as standalone projects.

As for the name of this directory, `libs` was my first choice but there's a bit of
a convention of that being external libraries in Zig projects _today_, while these
are libraries maintained as part of Mach in this repository - not external ones.

We will name this directory `libs`, and if we have a need for external libraries
we will use `external` or `deps` for that directory name. I considered other names
such as `components`, `systems`, `modules` (which are bad as they overlap with
major ECS / engine concepts), and it seems likely the official Zig package manager
will break the convention of using a `libs` dir anyway.

Performed via:

```sh
mkdir libs/
git mv freetype libs/
git mv basisu libs/
git mv gamemode libs/
git mv glfw libs/
git mv gpu libs/
git mv gpu-dawn libs/
git mv sysaudio libs/
git mv sysjs libs/
git mv ecs libs/
```

git-subtree-dir: glfw
git-subtree-mainline: 0d5b853443
git-subtree-split: 572d1144f11b353abdb64fff828b25a4f0fbb7ca

Signed-off-by: Stephen Gutekanst <stephen@hexops.com>

git mv ecs libs/

Signed-off-by: Stephen Gutekanst <stephen@hexops.com>
This commit is contained in:
Stephen Gutekanst 2022-08-26 13:29:04 -07:00 committed by Stephen Gutekanst
parent 79ec61396f
commit 0645429df9
240 changed files with 6 additions and 6 deletions

2
libs/basisu/.gitattributes vendored Normal file
View file

@ -0,0 +1,2 @@
* text=auto eol=lf
upstream/** linguist-vendored

1
libs/basisu/.github/FUNDING.yml vendored Normal file
View file

@ -0,0 +1 @@
github: slimsag

View file

@ -0,0 +1,5 @@
Please send your change to [the main repository](https://github.com/hexops/mach/tree/main/basisu) instead, sorry for the trouble!
This helps us avoid some complex merge conflicts we run into when changes are made to both repositories and history needs to be reconciled. Keeping PRs in just that repository enables us to use `git subtree` to trivially keep the two repositories in sync.
Once your PR is merged over there, it'll automatically sync to this repository.

46
libs/basisu/.github/workflows/ci.yml vendored Normal file
View file

@ -0,0 +1,46 @@
name: CI
on:
- push
- pull_request
jobs:
x86_64-linux:
runs-on: ubuntu-latest
steps:
- name: Checkout
uses: actions/checkout@v2
- name: Setup Zig
run: |
sudo apt install xz-utils
sudo sh -c 'wget -c https://ziglang.org/builds/zig-linux-x86_64-0.10.0-dev.3551+92568a009.tar.xz -O - | tar -xJ --strip-components=1 -C /usr/local/bin'
- name: x86_64-linux -> aarch64-macos
run: zig build test -Dtarget=aarch64-macos.12-none
- name: test
run: |
zig build test
x86_64-windows:
runs-on: windows-latest
steps:
- name: Checkout
uses: actions/checkout@v2
- name: Install Git
run: choco install git
- name: Setup Zig
run: |
$ProgressPreference = 'SilentlyContinue'
Invoke-WebRequest -Uri "https://ziglang.org/builds/zig-windows-x86_64-0.10.0-dev.3551+92568a009.zip" -OutFile "C:\zig.zip"
cd C:\
7z x zig.zip
Add-Content $env:GITHUB_PATH "C:\zig-windows-x86_64-0.10.0-dev.3551+92568a009\"
- name: test
run: zig build test
x86_64-macos:
runs-on: macos-latest
steps:
- name: Checkout
uses: actions/checkout@v2
- name: Setup Zig
run: |
brew install xz
sudo sh -c 'wget -c https://ziglang.org/builds/zig-macos-x86_64-0.10.0-dev.3551+92568a009.tar.xz -O - | tar -xJ --strip-components=1 -C /usr/local/bin'
- name: test
run: zig build test

18
libs/basisu/.gitignore vendored Normal file
View file

@ -0,0 +1,18 @@
# This file is for zig-specific build artifacts.
# If you have OS-specific or editor-specific files to ignore,
# such as *.swp or .DS_Store, put those in your global
# ~/.gitignore and put this in your ~/.gitconfig:
#
# [core]
# excludesfile = ~/.gitignore
#
# Cheers!
# -andrewrk
zig-cache/
zig-out/
/release/
/debug/
/build/
/build-*/
/docgen_tmp/

3
libs/basisu/.gitmodules vendored Normal file
View file

@ -0,0 +1,3 @@
[submodule "upstream"]
path = upstream
url = https://github.com/hexops/basisu

13
libs/basisu/LICENSE Normal file
View file

@ -0,0 +1,13 @@
Copyright 2021, Hexops Contributors (given via the Git commit history).
All documentation, image, sound, font, and 2D/3D model files are CC-BY-4.0 licensed unless
otherwise noted. You may get a copy of this license at https://creativecommons.org/licenses/by/4.0
Files in a directory with a separate LICENSE file may contain files under different license terms,
described within that LICENSE file.
All other files are licensed under the Apache License, Version 2.0 (see LICENSE-APACHE or http://www.apache.org/licenses/LICENSE-2.0)
or the MIT license (see LICENSE-MIT or http://opensource.org/licenses/MIT), at your option.
All files in the project without exclusions may not be copied, modified, or distributed except
according to the terms above.

202
libs/basisu/LICENSE-APACHE Normal file
View file

@ -0,0 +1,202 @@
Apache License
Version 2.0, January 2004
http://www.apache.org/licenses/
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
1. Definitions.
"License" shall mean the terms and conditions for use, reproduction,
and distribution as defined by Sections 1 through 9 of this document.
"Licensor" shall mean the copyright owner or entity authorized by
the copyright owner that is granting the License.
"Legal Entity" shall mean the union of the acting entity and all
other entities that control, are controlled by, or are under common
control with that entity. For the purposes of this definition,
"control" means (i) the power, direct or indirect, to cause the
direction or management of such entity, whether by contract or
otherwise, or (ii) ownership of fifty percent (50%) or more of the
outstanding shares, or (iii) beneficial ownership of such entity.
"You" (or "Your") shall mean an individual or Legal Entity
exercising permissions granted by this License.
"Source" form shall mean the preferred form for making modifications,
including but not limited to software source code, documentation
source, and configuration files.
"Object" form shall mean any form resulting from mechanical
transformation or translation of a Source form, including but
not limited to compiled object code, generated documentation,
and conversions to other media types.
"Work" shall mean the work of authorship, whether in Source or
Object form, made available under the License, as indicated by a
copyright notice that is included in or attached to the work
(an example is provided in the Appendix below).
"Derivative Works" shall mean any work, whether in Source or Object
form, that is based on (or derived from) the Work and for which the
editorial revisions, annotations, elaborations, or other modifications
represent, as a whole, an original work of authorship. For the purposes
of this License, Derivative Works shall not include works that remain
separable from, or merely link (or bind by name) to the interfaces of,
the Work and Derivative Works thereof.
"Contribution" shall mean any work of authorship, including
the original version of the Work and any modifications or additions
to that Work or Derivative Works thereof, that is intentionally
submitted to Licensor for inclusion in the Work by the copyright owner
or by an individual or Legal Entity authorized to submit on behalf of
the copyright owner. For the purposes of this definition, "submitted"
means any form of electronic, verbal, or written communication sent
to the Licensor or its representatives, including but not limited to
communication on electronic mailing lists, source code control systems,
and issue tracking systems that are managed by, or on behalf of, the
Licensor for the purpose of discussing and improving the Work, but
excluding communication that is conspicuously marked or otherwise
designated in writing by the copyright owner as "Not a Contribution."
"Contributor" shall mean Licensor and any individual or Legal Entity
on behalf of whom a Contribution has been received by Licensor and
subsequently incorporated within the Work.
2. Grant of Copyright License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
copyright license to reproduce, prepare Derivative Works of,
publicly display, publicly perform, sublicense, and distribute the
Work and such Derivative Works in Source or Object form.
3. Grant of Patent License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
(except as stated in this section) patent license to make, have made,
use, offer to sell, sell, import, and otherwise transfer the Work,
where such license applies only to those patent claims licensable
by such Contributor that are necessarily infringed by their
Contribution(s) alone or by combination of their Contribution(s)
with the Work to which such Contribution(s) was submitted. If You
institute patent litigation against any entity (including a
cross-claim or counterclaim in a lawsuit) alleging that the Work
or a Contribution incorporated within the Work constitutes direct
or contributory patent infringement, then any patent licenses
granted to You under this License for that Work shall terminate
as of the date such litigation is filed.
4. Redistribution. You may reproduce and distribute copies of the
Work or Derivative Works thereof in any medium, with or without
modifications, and in Source or Object form, provided that You
meet the following conditions:
(a) You must give any other recipients of the Work or
Derivative Works a copy of this License; and
(b) You must cause any modified files to carry prominent notices
stating that You changed the files; and
(c) You must retain, in the Source form of any Derivative Works
that You distribute, all copyright, patent, trademark, and
attribution notices from the Source form of the Work,
excluding those notices that do not pertain to any part of
the Derivative Works; and
(d) If the Work includes a "NOTICE" text file as part of its
distribution, then any Derivative Works that You distribute must
include a readable copy of the attribution notices contained
within such NOTICE file, excluding those notices that do not
pertain to any part of the Derivative Works, in at least one
of the following places: within a NOTICE text file distributed
as part of the Derivative Works; within the Source form or
documentation, if provided along with the Derivative Works; or,
within a display generated by the Derivative Works, if and
wherever such third-party notices normally appear. The contents
of the NOTICE file are for informational purposes only and
do not modify the License. You may add Your own attribution
notices within Derivative Works that You distribute, alongside
or as an addendum to the NOTICE text from the Work, provided
that such additional attribution notices cannot be construed
as modifying the License.
You may add Your own copyright statement to Your modifications and
may provide additional or different license terms and conditions
for use, reproduction, or distribution of Your modifications, or
for any such Derivative Works as a whole, provided Your use,
reproduction, and distribution of the Work otherwise complies with
the conditions stated in this License.
5. Submission of Contributions. Unless You explicitly state otherwise,
any Contribution intentionally submitted for inclusion in the Work
by You to the Licensor shall be under the terms and conditions of
this License, without any additional terms or conditions.
Notwithstanding the above, nothing herein shall supersede or modify
the terms of any separate license agreement you may have executed
with Licensor regarding such Contributions.
6. Trademarks. This License does not grant permission to use the trade
names, trademarks, service marks, or product names of the Licensor,
except as required for reasonable and customary use in describing the
origin of the Work and reproducing the content of the NOTICE file.
7. Disclaimer of Warranty. Unless required by applicable law or
agreed to in writing, Licensor provides the Work (and each
Contributor provides its Contributions) on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
implied, including, without limitation, any warranties or conditions
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
PARTICULAR PURPOSE. You are solely responsible for determining the
appropriateness of using or redistributing the Work and assume any
risks associated with Your exercise of permissions under this License.
8. Limitation of Liability. In no event and under no legal theory,
whether in tort (including negligence), contract, or otherwise,
unless required by applicable law (such as deliberate and grossly
negligent acts) or agreed to in writing, shall any Contributor be
liable to You for damages, including any direct, indirect, special,
incidental, or consequential damages of any character arising as a
result of this License or out of the use or inability to use the
Work (including but not limited to damages for loss of goodwill,
work stoppage, computer failure or malfunction, or any and all
other commercial damages or losses), even if such Contributor
has been advised of the possibility of such damages.
9. Accepting Warranty or Additional Liability. While redistributing
the Work or Derivative Works thereof, You may choose to offer,
and charge a fee for, acceptance of support, warranty, indemnity,
or other liability obligations and/or rights consistent with this
License. However, in accepting such obligations, You may act only
on Your own behalf and on Your sole responsibility, not on behalf
of any other Contributor, and only if You agree to indemnify,
defend, and hold each Contributor harmless for any liability
incurred by, or claims asserted against, such Contributor by reason
of your accepting any such warranty or additional liability.
END OF TERMS AND CONDITIONS
APPENDIX: How to apply the Apache License to your work.
To apply the Apache License to your work, attach the following
boilerplate notice, with the fields enclosed by brackets "[]"
replaced with your own identifying information. (Don't include
the brackets!) The text should be enclosed in the appropriate
comment syntax for the file format. We also recommend that a
file or class name and description of purpose be included on the
same "printed page" as the copyright notice for easier
identification within third-party archives.
Copyright [yyyy] [name of copyright owner]
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.

25
libs/basisu/LICENSE-MIT Normal file
View file

@ -0,0 +1,25 @@
Copyright (c) 2021 Hexops Contributors (given via the Git commit history).
Permission is hereby granted, free of charge, to any
person obtaining a copy of this software and associated
documentation files (the "Software"), to deal in the
Software without restriction, including without
limitation the rights to use, copy, modify, merge,
publish, distribute, sublicense, and/or sell copies of
the Software, and to permit persons to whom the Software
is furnished to do so, subject to the following
conditions:
The above copyright notice and this permission notice
shall be included in all copies or substantial portions
of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF
ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED
TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A
PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT
SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR
IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
DEALINGS IN THE SOFTWARE.

38
libs/basisu/README.md Normal file
View file

@ -0,0 +1,38 @@
# mach/basisu - basis universal (supercompressed textures) for Zig
This repository is a separate copy of the same library in the [main Mach repository](https://github.com/hexops/mach), and is automatically kept in sync, so that anyone can use this library in their own project if they like!
## Getting started
### Adding dependency
In a `libs` subdirectory of the root of your project:
```sh
git clone https://github.com/hexops/mach-basisu
```
Then in your `build.zig` add:
```zig
...
const basisu = @import("libs/mach-basisu/build.zig");
pub fn build(b: *Builder) void {
...
exe.addPackage(basisu.pkg);
basisu.link(b, exe, .{});
}
```
## Join the community
Join the Mach community [on Discord](https://discord.gg/XNG3NZgCqp) or [Matrix](https://matrix.to/#/#hexops:matrix.org) to discuss this project, ask questions, get help, etc.
## Issues
Issues are tracked in the [main Mach repository](https://github.com/hexops/mach/issues?q=is%3Aissue+is%3Aopen+label%3Abasisu).
## Contributing
Contributions are very welcome. Pull requests must be sent to [the main repository](https://github.com/hexops/mach/tree/main/basisu) to avoid some complex merge conflicts we'd get by accepting contributions in both repositories. Once the changes are merged there, they'll get sync'd to this repository automatically.

124
libs/basisu/build.zig Normal file
View file

@ -0,0 +1,124 @@
const std = @import("std");
const Builder = std.build.Builder;
const basisu_root = thisDir() ++ "/upstream/basisu";
pub const pkg = std.build.Pkg{
.name = "basisu",
.source = .{
.path = "src/main.zig",
},
};
pub fn build(b: *Builder) void {
const mode = b.standardReleaseOptions();
const target = b.standardTargetOptions(.{});
const test_step = b.step("test", "Run library tests");
test_step.dependOn(&testStep(b, mode, target).step);
}
pub fn testStep(b: *Builder, mode: std.builtin.Mode, target: std.zig.CrossTarget) *std.build.RunStep {
const main_tests = b.addTestExe("basisu-tests", comptime thisDir() ++ "/src/main.zig");
main_tests.setBuildMode(mode);
main_tests.setTarget(target);
main_tests.main_pkg_path = thisDir();
link(b, main_tests, .{
.encoder = true,
.transcoder = true,
});
main_tests.install();
return main_tests.run();
}
pub fn link(b: *Builder, step: *std.build.LibExeObjStep, options: Options) void {
if (options.encoder) {
step.linkLibrary(buildEncoder(b));
step.addCSourceFile(comptime thisDir() ++ "/src/encoder/wrapper.cpp", &.{});
step.addIncludeDir(basisu_root ++ "/encoder");
}
if (options.transcoder) {
step.linkLibrary(buildTranscoder(b));
step.addCSourceFile(comptime thisDir() ++ "/src/transcoder/wrapper.cpp", &.{});
step.addIncludeDir(basisu_root ++ "/transcoder");
}
}
pub fn buildEncoder(b: *Builder) *std.build.LibExeObjStep {
// TODO(build-system): https://github.com/hexops/mach/issues/229#issuecomment-1100958939
ensureDependencySubmodule(b.allocator, "upstream") catch unreachable;
const encoder = b.addStaticLibrary("basisu-encoder", null);
encoder.linkLibCpp();
encoder.addCSourceFiles(
encoder_sources,
&.{},
);
encoder.defineCMacro("BASISU_FORCE_DEVEL_MESSAGES", "0");
encoder.defineCMacro("BASISD_SUPPORT_KTX2_ZSTD", "0");
encoder.install();
return encoder;
}
pub fn buildTranscoder(b: *Builder) *std.build.LibExeObjStep {
// TODO(build-system): https://github.com/hexops/mach/issues/229#issuecomment-1100958939
ensureDependencySubmodule(b.allocator, "upstream") catch unreachable;
const transcoder = b.addStaticLibrary("basisu-transcoder", null);
transcoder.linkLibCpp();
transcoder.addCSourceFiles(
transcoder_sources,
&.{},
);
transcoder.defineCMacro("BASISU_FORCE_DEVEL_MESSAGES", "0");
transcoder.defineCMacro("BASISD_SUPPORT_KTX2_ZSTD", "0");
transcoder.install();
return transcoder;
}
pub const Options = struct {
encoder: bool,
transcoder: bool,
};
fn thisDir() []const u8 {
return std.fs.path.dirname(@src().file) orelse ".";
}
fn ensureDependencySubmodule(allocator: std.mem.Allocator, path: []const u8) !void {
if (std.process.getEnvVarOwned(allocator, "NO_ENSURE_SUBMODULES")) |no_ensure_submodules| {
if (std.mem.eql(u8, no_ensure_submodules, "true")) return;
} else |_| {}
var child = std.ChildProcess.init(&.{ "git", "submodule", "update", "--init", path }, allocator);
child.cwd = (comptime thisDir());
child.stderr = std.io.getStdErr();
child.stdout = std.io.getStdOut();
_ = try child.spawnAndWait();
}
const transcoder_sources = &[_][]const u8{
basisu_root ++ "/transcoder/basisu_transcoder.cpp",
};
const encoder_sources = &[_][]const u8{
basisu_root ++ "/encoder/basisu_backend.cpp",
basisu_root ++ "/encoder/basisu_basis_file.cpp",
basisu_root ++ "/encoder/basisu_bc7enc.cpp",
basisu_root ++ "/encoder/basisu_comp.cpp",
basisu_root ++ "/encoder/basisu_enc.cpp",
basisu_root ++ "/encoder/basisu_etc.cpp",
basisu_root ++ "/encoder/basisu_frontend.cpp",
basisu_root ++ "/encoder/basisu_gpu_texture.cpp",
basisu_root ++ "/encoder/basisu_kernels_sse.cpp",
basisu_root ++ "/encoder/basisu_opencl.cpp",
basisu_root ++ "/encoder/basisu_pvrtc1_4.cpp",
basisu_root ++ "/encoder/basisu_resample_filters.cpp",
basisu_root ++ "/encoder/basisu_resampler.cpp",
basisu_root ++ "/encoder/basisu_ssim.cpp",
basisu_root ++ "/encoder/basisu_uastc_enc.cpp",
basisu_root ++ "/encoder/jpgd.cpp",
basisu_root ++ "/encoder/pvpngreader.cpp",
};

259
libs/basisu/src/encoder.zig Normal file
View file

@ -0,0 +1,259 @@
const std = @import("std");
const b = @import("encoder/binding.zig");
const BasisTextureFormat = @import("main.zig").BasisTextureFormat;
const testing = std.testing;
/// Must be called before encoding anything
pub fn init_encoder() void {
b.basisu_encoder_init();
}
pub const Compressor = struct {
pub const Error = error{
InitializationFailed,
ValidationFailed,
EncodingUASTCFailed,
CannotReadSourceImages,
FrontendFault,
FrontendExtractionFailed,
BackendFault,
CannotCreateBasisFile,
CannotWriteOutput,
UASTCRDOPostProcessFailed,
CannotCreateKTX2File,
};
handle: *b.Compressor,
pub fn init(params: CompressorParams) error{Unknown}!Compressor {
return Compressor{
.handle = if (b.compressor_init(params.handle)) |v| v else return error.Unknown,
};
}
pub fn deinit(self: Compressor) void {
b.compressor_deinit(self.handle);
}
pub fn process(self: Compressor) Error!void {
return switch (b.compressor_process(self.handle)) {
0 => {},
1 => error.InitializationFailed,
2 => error.CannotReadSourceImages,
3 => error.ValidationFailed,
4 => error.EncodingUASTCFailed,
5 => error.FrontendFault,
6 => error.FrontendExtractionFailed,
7 => error.BackendFault,
8 => error.CannotCreateBasisFile,
9 => error.UASTCRDOPostProcessFailed,
10 => error.CannotCreateKTX2File,
else => unreachable,
};
}
/// output will be freed with `Compressor.deinit`
pub fn output(self: Compressor) []const u8 {
return b.compressor_get_output(self.handle)[0..b.compressor_get_output_size(self.handle)];
}
pub fn outputBitsPerTexel(self: Compressor) f64 {
return b.compressor_get_output_bits_per_texel(self.handle);
}
pub fn anyImageHasAlpha(self: Compressor) bool {
return b.compressor_get_any_source_image_has_alpha(self.handle);
}
};
pub const CompressorParams = struct {
handle: *b.CompressorParams,
pub fn init(threads_count: u32) CompressorParams {
const h = CompressorParams{ .handle = b.compressor_params_init() };
h.setStatusOutput(false);
b.compressor_params_set_thread_count(h.handle, threads_count);
return h;
}
pub fn deinit(self: CompressorParams) void {
b.compressor_params_deinit(self.handle);
}
pub fn clear(self: CompressorParams) void {
b.compressor_params_clear(self.handle);
}
pub fn setStatusOutput(self: CompressorParams, enable_output: bool) void {
b.compressor_params_set_status_output(self.handle, enable_output);
}
/// `level` ranges from [1, 255]
pub fn setQualityLevel(self: CompressorParams, level: u8) void {
b.compressor_params_set_quality_level(self.handle, level);
}
pub fn getPackUASTCFlags(self: CompressorParams) PackUASTCFlags {
return PackUASTCFlags.from(b.compressor_params_get_pack_uastc_flags(self.handle));
}
pub fn setPackUASTCFlags(self: CompressorParams, flags: PackUASTCFlags) void {
b.compressor_params_set_pack_uastc_flags(self.handle, flags.cast());
}
pub fn setBasisFormat(self: CompressorParams, format: BasisTextureFormat) void {
b.compressor_params_set_uastc(self.handle, switch (format) {
.etc1s => false,
.uastc4x4 => true,
});
}
pub fn setColorSpace(self: CompressorParams, color_space: ColorSpace) void {
b.compressor_params_set_perceptual(self.handle, switch (color_space) {
.linear => false,
.srgb => true,
});
}
pub fn setMipColorSpace(self: CompressorParams, color_space: ColorSpace) void {
b.compressor_params_set_mip_srgb(self.handle, switch (color_space) {
.linear => false,
.srgb => true,
});
}
/// Disable selector RDO, for faster compression but larger files.
/// Enabled by default
pub fn setSelectorRDO(self: CompressorParams, enable: bool) void {
b.compressor_params_set_no_selector_rdo(self.handle, !enable);
}
/// Enabled by default
pub fn setEndpointRDO(self: CompressorParams, enable: bool) void {
b.compressor_params_set_no_endpoint_rdo(self.handle, !enable);
}
pub fn setRDO_UASTC(self: CompressorParams, enable: bool) void {
b.compressor_params_set_rdo_uastc(self.handle, enable);
}
pub fn setRDO_UASTCQualityScalar(self: CompressorParams, quality: f32) void {
b.compressor_params_set_rdo_uastc_quality_scalar(self.handle, quality);
}
pub fn setGenerateMipMaps(self: CompressorParams, enable: bool) void {
b.compressor_params_set_generate_mipmaps(self.handle, enable);
}
pub fn setMipSmallestDimension(self: CompressorParams, smallest_dimension: i32) void {
b.compressor_params_set_mip_smallest_dimension(self.handle, smallest_dimension);
}
/// Resizes sources list and creates a new Image in case index is out of bounds
pub fn getImageSource(self: CompressorParams, index: u32) Image {
return .{ .handle = b.compressor_params_get_or_create_source_image(self.handle, index) };
}
pub fn resizeImageSource(self: CompressorParams, new_size: u32) void {
b.compressor_params_resize_source_image_list(self.handle, new_size);
}
pub fn clearImageSource(self: CompressorParams) void {
b.compressor_params_clear_source_image_list(self.handle);
}
};
pub const Image = struct {
handle: *b.Image,
pub fn fill(self: Image, data: []const u8, w: u32, h: u32, channels: u3) void {
b.compressor_image_fill(self.handle, data.ptr, w, h, channels);
}
pub fn resize(self: Image, w: u32, h: u32, p: ?u32) void {
b.compressor_image_resize(self.handle, w, h, p orelse std.math.maxInt(u32));
}
pub fn width(self: Image) u32 {
return b.compressor_image_get_width(self.handle);
}
pub fn height(self: Image) u32 {
return b.compressor_image_get_height(self.handle);
}
pub fn pitch(self: Image) u32 {
return b.compressor_image_get_pitch(self.handle);
}
pub fn totalPixels(self: Image) u32 {
return b.compressor_image_get_total_pixels(self.handle);
}
pub fn blockWidth(self: Image, w: u32) u32 {
return (self.width() + (w - 1)) / w;
}
pub fn blockHeight(self: Image, h: u32) u32 {
return (self.height() + (h - 1)) / h;
}
pub fn totalBlocks(self: Image, w: u32, h: u32) u32 {
return self.blockWidth(w) * self.blockHeight(h);
}
};
pub const PackUASTCFlags = packed struct {
fastest: bool = false,
faster: bool = false,
default: bool = false,
slower: bool = false,
verySlow: bool = false,
mask: bool = false,
favor_uastc_error: bool = false,
favor_bc7_error: bool = false,
etc1_faster_hints: bool = false,
etc1_fastest_hints: bool = false,
etc1_disable_flip_and_individual: bool = false,
favor_simpler_modes: bool = false,
pub const Flag = enum(u32) {
fastest = 0,
faster = 1,
default = 2,
slower = 3,
verySlow = 4,
mask = 0xF,
favor_uastc_error = 8,
favor_bc7_error = 16,
etc1_faster_hints = 64,
etc1_fastest_hints = 128,
etc1_disable_flip_and_individual = 256,
favor_simpler_modes = 512,
};
pub fn from(bits: u32) PackUASTCFlags {
var value = PackUASTCFlags{};
inline for (comptime std.meta.fieldNames(Flag)) |field_name| {
if (bits & (@enumToInt(@field(Flag, field_name))) != 0) {
@field(value, field_name) = true;
}
}
return value;
}
pub fn cast(self: PackUASTCFlags) u32 {
var value: u32 = 0;
inline for (comptime std.meta.fieldNames(Flag)) |field_name| {
if (@field(self, field_name)) {
value |= @enumToInt(@field(Flag, field_name));
}
}
return value;
}
};
pub const ColorSpace = enum {
linear,
srgb,
};

View file

@ -0,0 +1,42 @@
pub const Compressor = opaque {};
pub const CompressorParams = opaque {};
pub const Image = opaque {};
pub extern fn basisu_encoder_init() void;
pub extern fn compressor_params_init() *CompressorParams;
pub extern fn compressor_params_deinit(*CompressorParams) void;
pub extern fn compressor_params_clear(*CompressorParams) void;
pub extern fn compressor_params_set_status_output(*CompressorParams, bool) void;
pub extern fn compressor_params_set_thread_count(*CompressorParams, u32) void;
pub extern fn compressor_params_set_quality_level(*CompressorParams, c_int) void;
pub extern fn compressor_params_get_pack_uastc_flags(*CompressorParams) u32;
pub extern fn compressor_params_set_pack_uastc_flags(*CompressorParams, u32) void;
pub extern fn compressor_params_set_uastc(*CompressorParams, bool) void;
pub extern fn compressor_params_set_perceptual(*CompressorParams, bool) void;
pub extern fn compressor_params_set_mip_srgb(*CompressorParams, bool) void;
pub extern fn compressor_params_set_no_selector_rdo(*CompressorParams, bool) void;
pub extern fn compressor_params_set_no_endpoint_rdo(*CompressorParams, bool) void;
pub extern fn compressor_params_set_rdo_uastc(*CompressorParams, bool) void;
pub extern fn compressor_params_set_rdo_uastc_quality_scalar(*CompressorParams, f32) void;
pub extern fn compressor_params_set_generate_mipmaps(*CompressorParams, bool) void;
pub extern fn compressor_params_set_mip_smallest_dimension(*CompressorParams, c_int) void;
pub extern fn compressor_params_get_or_create_source_image(*CompressorParams, u32) *Image;
pub extern fn compressor_params_resize_source_image_list(*CompressorParams, usize) void;
pub extern fn compressor_params_clear_source_image_list(*CompressorParams) void;
pub extern fn compressor_image_fill(*Image, [*]const u8, u32, u32, u32) void;
pub extern fn compressor_image_resize(*Image, u32, u32, u32) void;
pub extern fn compressor_image_get_width(*Image) u32;
pub extern fn compressor_image_get_height(*Image) u32;
pub extern fn compressor_image_get_pitch(*Image) u32;
pub extern fn compressor_image_get_total_pixels(*Image) u32;
pub extern fn compressor_init(*CompressorParams) ?*Compressor;
pub extern fn compressor_deinit(*Compressor) void;
pub extern fn compressor_process(*Compressor) u32;
pub extern fn compressor_get_output(*Compressor) [*]const u8;
pub extern fn compressor_get_output_size(*Compressor) u32;
pub extern fn compressor_get_output_bits_per_texel(*Compressor) f64;
pub extern fn compressor_get_any_source_image_has_alpha(*Compressor) bool;

View file

@ -0,0 +1,176 @@
#include <basisu_comp.h>
#include <basisu_enc.h>
#include <cstdbool>
#include <cstdint>
extern "C" {
void basisu_encoder_init() { basisu::basisu_encoder_init(); }
basisu::basis_compressor_params *compressor_params_init() {
return new basisu::basis_compressor_params();
};
void compressor_params_deinit(basisu::basis_compressor_params *params) {
delete params;
}
void compressor_params_clear(basisu::basis_compressor_params *params) {
params->clear();
}
void compressor_params_set_status_output(
basisu::basis_compressor_params *params, bool status_output) {
params->m_status_output = status_output;
}
void compressor_params_set_thread_count(basisu::basis_compressor_params *params,
uint32_t thread_count) {
params->m_pJob_pool = new basisu::job_pool(thread_count);
}
void compressor_params_set_quality_level(
basisu::basis_compressor_params *params, uint8_t quality_level) {
params->m_quality_level = quality_level;
}
uint32_t compressor_params_get_pack_uastc_flags(
basisu::basis_compressor_params *params) {
return params->m_pack_uastc_flags;
}
void compressor_params_set_pack_uastc_flags(
basisu::basis_compressor_params *params, uint32_t pack_uastc_flags) {
params->m_pack_uastc_flags = pack_uastc_flags;
}
void compressor_params_set_uastc(basisu::basis_compressor_params *params,
bool is_uastc) {
params->m_uastc = is_uastc;
}
void compressor_params_set_perceptual(basisu::basis_compressor_params *params,
bool perceptual) {
params->m_perceptual = perceptual;
}
void compressor_params_set_mip_srgb(basisu::basis_compressor_params *params,
bool mip_srgb) {
params->m_mip_srgb = mip_srgb;
}
void compressor_params_set_no_selector_rdo(
basisu::basis_compressor_params *params, bool no_selector_rdo) {
params->m_no_selector_rdo = no_selector_rdo;
}
void compressor_params_set_no_endpoint_rdo(
basisu::basis_compressor_params *params, bool no_endpoint_rdo) {
params->m_no_endpoint_rdo = no_endpoint_rdo;
}
void compressor_params_set_rdo_uastc(basisu::basis_compressor_params *params,
bool rdo_uastc) {
params->m_rdo_uastc = rdo_uastc;
}
void compressor_params_set_generate_mipmaps(
basisu::basis_compressor_params *params, bool generate_mipmaps) {
params->m_mip_gen = generate_mipmaps;
}
void compressor_params_set_rdo_uastc_quality_scalar(
basisu::basis_compressor_params *params, float rdo_uastc_quality_scalar) {
params->m_rdo_uastc_quality_scalar = rdo_uastc_quality_scalar;
}
void compressor_params_set_mip_smallest_dimension(
basisu::basis_compressor_params *params, int mip_smallest_dimension) {
params->m_mip_smallest_dimension = mip_smallest_dimension;
}
basisu::image *compressor_params_get_or_create_source_image(
basisu::basis_compressor_params *params, uint32_t index) {
if (params->m_source_images.size() < index + 1) {
params->m_source_images.resize(index + 1);
}
return &params->m_source_images[index];
}
void compressor_params_resize_source_image_list(
basisu::basis_compressor_params *params, size_t size) {
params->m_source_images.resize(size);
}
void compressor_params_clear_source_image_list(
basisu::basis_compressor_params *params) {
params->clear();
}
///
void compressor_image_fill(basisu::image *image, const uint8_t *pData,
uint32_t width, uint32_t height, uint32_t comps) {
image->init(pData, width, height, comps);
}
void compressor_image_resize(basisu::image *image, uint32_t w, uint32_t h,
uint32_t p) {
image->resize(w, h, p);
}
uint32_t compressor_image_get_width(basisu::image *image) {
return image->get_width();
}
uint32_t compressor_image_get_height(basisu::image *image) {
return image->get_height();
}
uint32_t compressor_image_get_pitch(basisu::image *image) {
return image->get_pitch();
}
uint32_t compressor_image_get_total_pixels(basisu::image *image) {
return image->get_total_pixels();
}
///
basisu::basis_compressor *
compressor_init(basisu::basis_compressor_params *params) {
auto comp = new basisu::basis_compressor();
if (comp->init(*params))
return comp;
else
return nullptr;
}
void compressor_deinit(basisu::basis_compressor *compressor) {
delete compressor;
}
basisu::basis_compressor::error_code
compressor_process(basisu::basis_compressor *compressor) {
return compressor->process();
}
const uint8_t *compressor_get_output(basisu::basis_compressor *compressor) {
return compressor->get_output_basis_file().data();
}
uint32_t
compressor_get_output_size(const basisu::basis_compressor *compressor) {
return compressor->get_basis_file_size();
}
double compressor_get_output_bits_per_texel(
const basisu::basis_compressor *compressor) {
return compressor->get_basis_bits_per_texel();
}
bool compressor_get_any_source_image_has_alpha(
const basisu::basis_compressor *compressor) {
return compressor->get_any_source_image_has_alpha();
}
}

45
libs/basisu/src/main.zig Normal file
View file

@ -0,0 +1,45 @@
pub usingnamespace @import("encoder.zig");
pub usingnamespace @import("transcoder.zig");
pub const BasisTextureFormat = enum(u1) {
etc1s = 0,
uastc4x4 = 1,
};
// Test
const t = @import("transcoder.zig");
const e = @import("encoder.zig");
const testing = @import("std").testing;
test "reference decls" {
testing.refAllDeclsRecursive(t);
testing.refAllDeclsRecursive(e);
}
test "encode/transcode" {
// Encode
e.init_encoder();
const params = e.CompressorParams.init(1);
params.setGenerateMipMaps(true);
params.setBasisFormat(.uastc4x4);
params.setPackUASTCFlags(.{ .fastest = true });
defer params.deinit();
const image = params.getImageSource(0);
image.fill(@embedFile("../test/ziggy.png"), 379, 316, 4);
const comp = try e.Compressor.init(params);
try comp.process();
// Transcode
t.init_transcoder();
const trans = try t.Transcoder.init(comp.output());
defer trans.deinit();
var out_buf = try testing.allocator.alloc(u8, try trans.calcTranscodedSize(0, 0, .astc_4x4_rgba));
defer testing.allocator.free(out_buf);
try trans.transcode(out_buf, 0, 0, .astc_4x4_rgba, .{});
}

View file

@ -0,0 +1,229 @@
const std = @import("std");
const b = @import("transcoder/binding.zig");
const BasisTextureFormat = @import("main.zig").BasisTextureFormat;
const testing = std.testing;
/// Must be called before a `.basis` file can be transcoded.
/// NOTE: this function *isn't* thread safe.
pub fn init_transcoder() void {
b.basisu_transcoder_init();
}
/// Returns true if the specified format was enabled at compile time.
pub fn isFormatEnabled(self: BasisTextureFormat, transcoder_format: Transcoder.TextureFormat) bool {
return b.transcoder_is_format_supported(@enumToInt(self), @enumToInt(transcoder_format));
}
pub const Transcoder = struct {
handle: *b.BasisFile,
pub fn init(src: []const u8) error{Unknown}!Transcoder {
const h = b.transcoder_init(src.ptr, @intCast(u32, src.len));
return if (!b.transcoder_start_transcoding(h))
error.Unknown
else .{ .handle = h };
}
pub fn deinit(self: Transcoder) void {
if (!b.transcoder_stop_transcoding(self.handle))
unreachable;
b.transcoder_deinit(self.handle);
}
/// Returns the total number of images in the basis file (always 1 or more).
/// Note that the number of mipmap levels for each image may differ, and that images may have different resolutions.
pub fn getImageCount(self: Transcoder) u32 {
return b.transcoder_get_images_count(self.handle);
}
/// Returns the number of mipmap levels in an image.
pub fn getImageLevelCount(self: Transcoder, image_index: u32) u32 {
return b.transcoder_get_levels_count(self.handle, image_index);
}
/// Returns basic information about an image.
/// Note that orig_width/orig_height may not be a multiple of 4.
pub fn getImageLevelDescriptor(self: Transcoder, image_index: u32, level_index: u32) error{OutOfBoundsLevelIndex}!ImageLevelDescriptor {
var desc: ImageLevelDescriptor = undefined;
return if (b.transcoder_get_image_level_desc(
self.handle,
image_index,
level_index,
&desc.original_width,
&desc.original_height,
&desc.block_count,
))
desc
else
error.OutOfBoundsLevelIndex;
}
/// Returns the bytes neeeded to store output.
pub fn calcTranscodedSize(self: Transcoder, image_index: u32, level_index: u32, format: TextureFormat) error{OutOfBoundsLevelIndex}!u32 {
var size: u32 = undefined;
return if (b.transcoder_get_image_transcoded_size(self.handle, image_index, level_index, @enumToInt(format), &size))
size
else
error.OutOfBoundsLevelIndex;
}
pub const TranscodeParams = struct {
decode_flags: ?DecodeFlags = null,
/// Output row pitch in blocks or pixels.
/// Should be at least the image level's total_blocks (num_blocks_x * num_blocks_y),
/// or the total number of output pixels if fmt==cTFRGBA32.
output_row_pitch: ?u32 = null,
/// Output rows in pixels
/// Ignored unless fmt is uncompressed (cRGBA32, etc.).
/// The total number of output rows in the output buffer. If 0,
/// the transcoder assumes the slice's orig_height (NOT num_blocks_y * 4).
output_rows: ?u32 = null,
};
/// Decodes a single mipmap level from the .basis file to any of the supported output texture formats.
/// Currently, to decode to PVRTC1 the basis texture's dimensions in pixels must be a power of 2,
/// due to PVRTC1 format requirements.
/// NOTE:
/// - `transcoder_init()` must have been called first to initialize
/// the transcoder lookup tables before calling this function.
/// - This method assumes the output texture buffer is readable.
/// In some cases to handle alpha, the transcoder will write temporary data
/// to the output texture in a first pass, which will be read in a second pass.
pub fn transcode(
self: Transcoder,
out_buf: []u8,
image_index: u32,
level_index: u32,
format: TextureFormat,
params: TranscodeParams,
) error{Unknown}!void {
if (!b.transcoder_transcode(
self.handle,
out_buf.ptr,
@intCast(u32, out_buf.len),
image_index,
level_index,
@enumToInt(format),
if (params.decode_flags) |f| f.cast() else 0,
params.output_row_pitch orelse 0,
params.output_rows orelse 0,
)) return error.Unknown;
}
pub const ImageLevelDescriptor = struct {
original_width: u32,
original_height: u32,
block_count: u32,
};
pub const DecodeFlags = packed struct {
pvrtc_decode_to_next_pow_2: bool = false,
transcode_alpha_data_to_opaque_formats: bool = false,
bc1_forbid_three_color_blocks: bool = false,
output_has_alpha_indices: bool = false,
high_quality: bool = false,
pub const Flag = enum(u32) {
pvrtc_decode_to_next_pow_2 = 2,
transcode_alpha_data_to_opaque_formats = 4,
bc1_forbid_three_color_blocks = 8,
output_has_alpha_indices = 16,
high_quality = 32,
};
pub fn from(bits: u32) DecodeFlags {
var value = DecodeFlags{};
inline for (comptime std.meta.fieldNames(Flag)) |field_name| {
if (bits & (@enumToInt(@field(Flag, field_name))) != 0) {
@field(value, field_name) = true;
}
}
return value;
}
pub fn cast(self: DecodeFlags) u32 {
var value: u32 = 0;
inline for (comptime std.meta.fieldNames(Flag)) |field_name| {
if (@field(self, field_name)) {
value |= @enumToInt(@field(Flag, field_name));
}
}
return value;
}
};
pub const TextureFormat = enum(u5) {
etc1_rgb = 0,
etc2_rgba = 1,
bc1_rgb = 2,
bc3_rgba = 3,
bc4_r = 4,
bc5_rg = 5,
bc7_rgba = 6,
bc7_alt = 7,
pvrtc1_4_rgb = 8,
pvrtc1_4_rgba = 9,
astc_4x4_rgba = 10,
atc_rgb = 11,
atc_rgba = 12,
rgba32 = 13,
rgb565 = 14,
bgr565 = 15,
rgba4444 = 16,
fxt1_rgb = 17,
pvrtc2_4_rgb = 18,
pvrtc2_4_rgba = 19,
etc2_eac_r11 = 20,
etc2_eac_rg11 = 21,
pub fn isEnabled(
self: TextureFormat,
basis_texture_format: BasisTextureFormat,
) bool {
return isFormatEnabled(basis_texture_format, self);
}
pub fn bytesPerBlockOrPixel(self: TextureFormat) u5 {
return switch (self) {
.rgb565, .bgr565, .rgba4444 => return 2,
.rgba32 => return 4,
.etc1_rgb, .bc1_rgb, .bc4_r, .pvrtc1_4_rgb, .pvrtc1_4_rgba, .atc_rgb, .pvrtc2_4_rgb, .pvrtc2_4_rgba, .etc2_eac_r11 => 8,
.bc7_rgba, .bc7_alt, .etc2_rgba, .bc3_rgba, .bc5_rg, .astc_4x4_rgba, .atc_rgba, .fxt1_rgb, .etc2_eac_rg11 => return 16,
};
}
};
pub const BlockFormat = enum(u5) {
etc1 = 0,
etc2_rgba = 1,
bc1 = 2,
bc3 = 3,
bc4 = 4,
bc5 = 5,
pvrtc1_4_rgb = 6,
pvrtc1_4_rgba = 7,
bc7 = 8,
bc7_m5_color = 9,
bc7_m5_alpha = 10,
etc2_eac_a8 = 11,
astc_4x4 = 12,
atc_rgb = 13,
atc_rgba_interpolated_alpha = 14,
fxt1_rgb = 15,
pvrtc2_4_rgb = 16,
pvrtc2_4_rgba = 17,
etc2_eac_r11 = 18,
etc2_eac_rg11 = 19,
indices = 20,
rgb32 = 21,
rgba32 = 23,
a32 = 24,
rgb565 = 25,
bgr565 = 26,
rgba4444_color = 27,
rgba4444_alpha = 28,
rgba4444_color_opaque = 29,
rgba4444 = 30,
uastc_4x4 = 31,
};
};

View file

@ -0,0 +1,38 @@
pub const BasisFile = opaque {};
pub extern fn basisu_transcoder_init() void;
pub extern fn transcoder_is_format_supported(tex_type: u32, fmt: u32) bool;
pub extern fn transcoder_init([*]const u8, u32) *BasisFile;
pub extern fn transcoder_deinit(*BasisFile) void;
pub extern fn transcoder_get_images_count(*BasisFile) u32;
pub extern fn transcoder_get_levels_count(*BasisFile, image_index: u32) u32;
pub extern fn transcoder_get_image_level_desc(
*BasisFile,
image_index: u32,
level_index: u32,
orig_width: *u32,
orig_height: *u32,
total_block: *u32,
) bool;
pub extern fn transcoder_get_image_transcoded_size(
*BasisFile,
image_index: u32,
level_index: u32,
format: u32,
size: *u32,
) bool;
pub extern fn transcoder_start_transcoding(*BasisFile) bool;
pub extern fn transcoder_stop_transcoding(*BasisFile) bool;
pub extern fn transcoder_transcode(
*BasisFile,
out: [*]const u8,
out_size: u32,
image_index: u32,
level_index: u32,
format: u32,
decode_flags: u32,
output_row_pitch_in_blocks_or_pixels: u32,
output_rows_in_pixels: u32,
) bool;

View file

@ -0,0 +1,153 @@
#include <basisu_transcoder.h>
#include <cstdbool>
#include <cstdint>
extern "C" {
void basisu_transcoder_init();
bool transcoder_is_format_supported(uint32_t tex_type, uint32_t fmt);
void *transcoder_init(void *src, uint32_t src_size);
void transcoder_deinit(void *h);
uint32_t transcoder_get_images_count(void *h);
uint32_t transcoder_get_levels_count(void *h, uint32_t image_index);
bool transcoder_get_image_level_desc(void *h, uint32_t image_index,
uint32_t level_index, uint32_t &orig_width,
uint32_t &orig_height,
uint32_t &block_count);
bool transcoder_get_image_transcoded_size(void *h, uint32_t image_index,
uint32_t level_index, uint32_t format,
uint32_t &size);
bool transcoder_start_transcoding(void *h);
bool transcoder_stop_transcoding(void *h);
bool transcoder_transcode(void *h, void *out, uint32_t out_size,
uint32_t image_index, uint32_t level_index,
uint32_t format, uint32_t decode_flags,
uint32_t output_row_pitch_in_blocks_or_pixels,
uint32_t output_rows_in_pixels);
}
void basisu_transcoder_init() { basist::basisu_transcoder_init(); }
#define MAGIC 0xDEADBEE1
struct basis_file {
int m_magic;
basist::basisu_transcoder m_transcoder;
void *m_pFile;
uint32_t m_file_size;
basis_file() : m_transcoder() {}
};
// transcoder_texture_format, basis_tex_format
bool transcoder_is_format_supported(uint32_t tex_type, uint32_t fmt) {
return basist::basis_is_format_supported(
(basist::transcoder_texture_format)tex_type,
(basist::basis_tex_format)fmt);
}
// !null - success
// null - validation failure
void *transcoder_init(void *src, uint32_t src_size) {
auto f = new basis_file;
f->m_pFile = src;
f->m_file_size = src_size;
if (!f->m_transcoder.validate_header(f->m_pFile, f->m_file_size)) {
delete f;
return nullptr;
}
f->m_magic = MAGIC;
return f;
}
void transcoder_deinit(void *h) {
auto f = static_cast<basis_file *>(h);
delete f;
}
uint32_t transcoder_get_images_count(void *h) {
auto f = static_cast<basis_file *>(h);
return f->m_transcoder.get_total_images(f->m_pFile, f->m_file_size);
}
uint32_t transcoder_get_levels_count(void *h, uint32_t image_index) {
auto f = static_cast<basis_file *>(h);
return f->m_transcoder.get_total_image_levels(f->m_pFile, f->m_file_size,
image_index);
}
// true - success
// false - OutOfBoundsLevelIndex
bool transcoder_get_image_level_desc(void *h, uint32_t image_index,
uint32_t level_index, uint32_t &orig_width,
uint32_t &orig_height,
uint32_t &block_count) {
auto f = static_cast<basis_file *>(h);
return f->m_transcoder.get_image_level_desc(
f->m_pFile, f->m_file_size, image_index, level_index, orig_width,
orig_height, block_count);
}
// true - success
// false - OutOfBoundsLevelIndex
bool transcoder_get_image_transcoded_size(void *h, uint32_t image_index,
uint32_t level_index, uint32_t format,
uint32_t &size) {
auto f = static_cast<basis_file *>(h);
uint32_t orig_width, orig_height, total_blocks;
if (!f->m_transcoder.get_image_level_desc(
f->m_pFile, f->m_file_size, image_index, level_index, orig_width,
orig_height, total_blocks))
return false;
uint8_t bytes_per_block_or_pixel = basis_get_bytes_per_block_or_pixel(
(basist::transcoder_texture_format)format);
if (basis_transcoder_format_is_uncompressed(
(basist::transcoder_texture_format)format)) {
size = orig_width * orig_height * bytes_per_block_or_pixel;
} else {
size = total_blocks * bytes_per_block_or_pixel;
}
return true;
}
// true - success
// false - unknown
bool transcoder_start_transcoding(void *h) {
auto f = static_cast<basis_file *>(h);
return f->m_transcoder.start_transcoding(f->m_pFile, f->m_file_size);
}
// true - success
// false - unknown
bool transcoder_stop_transcoding(void *h) {
auto f = static_cast<basis_file *>(h);
return f->m_transcoder.stop_transcoding();
}
// true - success
// false - unknown
bool transcoder_transcode(void *h, void *out, uint32_t out_size,
uint32_t image_index, uint32_t level_index,
uint32_t format, uint32_t decode_flags,
uint32_t output_row_pitch_in_blocks_or_pixels,
uint32_t output_rows_in_pixels) {
auto f = static_cast<basis_file *>(h);
uint32_t bytes_per_block = basis_get_bytes_per_block_or_pixel(
(basist::transcoder_texture_format)format);
return f->m_transcoder.transcode_image_level(
f->m_pFile, f->m_file_size, image_index, level_index, out,
out_size / bytes_per_block, (basist::transcoder_texture_format)format,
decode_flags, output_row_pitch_in_blocks_or_pixels, nullptr,
output_rows_in_pixels);
}

BIN
libs/basisu/test/ziggy.png Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 31 KiB

1
libs/basisu/upstream Submodule

@ -0,0 +1 @@
Subproject commit d55a3f9f06adf9cc8c31f58e894d947cc6026da5

2
libs/ecs/.gitattributes vendored Normal file
View file

@ -0,0 +1,2 @@
* text=auto eol=lf
upstream/** linguist-vendored

1
libs/ecs/.github/FUNDING.yml vendored Normal file
View file

@ -0,0 +1 @@
github: slimsag

View file

@ -0,0 +1,5 @@
Please send your change to [the main repository](https://github.com/hexops/mach/tree/main/ecs) instead, sorry for the trouble!
This helps us avoid some complex merge conflicts we run into when changes are made to both repositories and history needs to be reconciled. Keeping PRs in just that repository enables us to use `git subtree` to trivially keep the two repositories in sync.
Once your PR is merged over there, it'll automatically sync to this repository.

18
libs/ecs/.gitignore vendored Normal file
View file

@ -0,0 +1,18 @@
# This file is for zig-specific build artifacts.
# If you have OS-specific or editor-specific files to ignore,
# such as *.swp or .DS_Store, put those in your global
# ~/.gitignore and put this in your ~/.gitconfig:
#
# [core]
# excludesfile = ~/.gitignore
#
# Cheers!
# -andrewrk
zig-cache/
zig-out/
/release/
/debug/
/build/
/build-*/
/docgen_tmp/

13
libs/ecs/LICENSE Normal file
View file

@ -0,0 +1,13 @@
Copyright 2021, Hexops Contributors (given via the Git commit history).
All documentation, image, sound, font, and 2D/3D model files are CC-BY-4.0 licensed unless
otherwise noted. You may get a copy of this license at https://creativecommons.org/licenses/by/4.0
Files in a directory with a separate LICENSE file may contain files under different license terms,
described within that LICENSE file.
All other files are licensed under the Apache License, Version 2.0 (see LICENSE-APACHE or http://www.apache.org/licenses/LICENSE-2.0)
or the MIT license (see LICENSE-MIT or http://opensource.org/licenses/MIT), at your option.
All files in the project without exclusions may not be copied, modified, or distributed except
according to the terms above.

202
libs/ecs/LICENSE-APACHE Normal file
View file

@ -0,0 +1,202 @@
Apache License
Version 2.0, January 2004
http://www.apache.org/licenses/
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
1. Definitions.
"License" shall mean the terms and conditions for use, reproduction,
and distribution as defined by Sections 1 through 9 of this document.
"Licensor" shall mean the copyright owner or entity authorized by
the copyright owner that is granting the License.
"Legal Entity" shall mean the union of the acting entity and all
other entities that control, are controlled by, or are under common
control with that entity. For the purposes of this definition,
"control" means (i) the power, direct or indirect, to cause the
direction or management of such entity, whether by contract or
otherwise, or (ii) ownership of fifty percent (50%) or more of the
outstanding shares, or (iii) beneficial ownership of such entity.
"You" (or "Your") shall mean an individual or Legal Entity
exercising permissions granted by this License.
"Source" form shall mean the preferred form for making modifications,
including but not limited to software source code, documentation
source, and configuration files.
"Object" form shall mean any form resulting from mechanical
transformation or translation of a Source form, including but
not limited to compiled object code, generated documentation,
and conversions to other media types.
"Work" shall mean the work of authorship, whether in Source or
Object form, made available under the License, as indicated by a
copyright notice that is included in or attached to the work
(an example is provided in the Appendix below).
"Derivative Works" shall mean any work, whether in Source or Object
form, that is based on (or derived from) the Work and for which the
editorial revisions, annotations, elaborations, or other modifications
represent, as a whole, an original work of authorship. For the purposes
of this License, Derivative Works shall not include works that remain
separable from, or merely link (or bind by name) to the interfaces of,
the Work and Derivative Works thereof.
"Contribution" shall mean any work of authorship, including
the original version of the Work and any modifications or additions
to that Work or Derivative Works thereof, that is intentionally
submitted to Licensor for inclusion in the Work by the copyright owner
or by an individual or Legal Entity authorized to submit on behalf of
the copyright owner. For the purposes of this definition, "submitted"
means any form of electronic, verbal, or written communication sent
to the Licensor or its representatives, including but not limited to
communication on electronic mailing lists, source code control systems,
and issue tracking systems that are managed by, or on behalf of, the
Licensor for the purpose of discussing and improving the Work, but
excluding communication that is conspicuously marked or otherwise
designated in writing by the copyright owner as "Not a Contribution."
"Contributor" shall mean Licensor and any individual or Legal Entity
on behalf of whom a Contribution has been received by Licensor and
subsequently incorporated within the Work.
2. Grant of Copyright License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
copyright license to reproduce, prepare Derivative Works of,
publicly display, publicly perform, sublicense, and distribute the
Work and such Derivative Works in Source or Object form.
3. Grant of Patent License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
(except as stated in this section) patent license to make, have made,
use, offer to sell, sell, import, and otherwise transfer the Work,
where such license applies only to those patent claims licensable
by such Contributor that are necessarily infringed by their
Contribution(s) alone or by combination of their Contribution(s)
with the Work to which such Contribution(s) was submitted. If You
institute patent litigation against any entity (including a
cross-claim or counterclaim in a lawsuit) alleging that the Work
or a Contribution incorporated within the Work constitutes direct
or contributory patent infringement, then any patent licenses
granted to You under this License for that Work shall terminate
as of the date such litigation is filed.
4. Redistribution. You may reproduce and distribute copies of the
Work or Derivative Works thereof in any medium, with or without
modifications, and in Source or Object form, provided that You
meet the following conditions:
(a) You must give any other recipients of the Work or
Derivative Works a copy of this License; and
(b) You must cause any modified files to carry prominent notices
stating that You changed the files; and
(c) You must retain, in the Source form of any Derivative Works
that You distribute, all copyright, patent, trademark, and
attribution notices from the Source form of the Work,
excluding those notices that do not pertain to any part of
the Derivative Works; and
(d) If the Work includes a "NOTICE" text file as part of its
distribution, then any Derivative Works that You distribute must
include a readable copy of the attribution notices contained
within such NOTICE file, excluding those notices that do not
pertain to any part of the Derivative Works, in at least one
of the following places: within a NOTICE text file distributed
as part of the Derivative Works; within the Source form or
documentation, if provided along with the Derivative Works; or,
within a display generated by the Derivative Works, if and
wherever such third-party notices normally appear. The contents
of the NOTICE file are for informational purposes only and
do not modify the License. You may add Your own attribution
notices within Derivative Works that You distribute, alongside
or as an addendum to the NOTICE text from the Work, provided
that such additional attribution notices cannot be construed
as modifying the License.
You may add Your own copyright statement to Your modifications and
may provide additional or different license terms and conditions
for use, reproduction, or distribution of Your modifications, or
for any such Derivative Works as a whole, provided Your use,
reproduction, and distribution of the Work otherwise complies with
the conditions stated in this License.
5. Submission of Contributions. Unless You explicitly state otherwise,
any Contribution intentionally submitted for inclusion in the Work
by You to the Licensor shall be under the terms and conditions of
this License, without any additional terms or conditions.
Notwithstanding the above, nothing herein shall supersede or modify
the terms of any separate license agreement you may have executed
with Licensor regarding such Contributions.
6. Trademarks. This License does not grant permission to use the trade
names, trademarks, service marks, or product names of the Licensor,
except as required for reasonable and customary use in describing the
origin of the Work and reproducing the content of the NOTICE file.
7. Disclaimer of Warranty. Unless required by applicable law or
agreed to in writing, Licensor provides the Work (and each
Contributor provides its Contributions) on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
implied, including, without limitation, any warranties or conditions
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
PARTICULAR PURPOSE. You are solely responsible for determining the
appropriateness of using or redistributing the Work and assume any
risks associated with Your exercise of permissions under this License.
8. Limitation of Liability. In no event and under no legal theory,
whether in tort (including negligence), contract, or otherwise,
unless required by applicable law (such as deliberate and grossly
negligent acts) or agreed to in writing, shall any Contributor be
liable to You for damages, including any direct, indirect, special,
incidental, or consequential damages of any character arising as a
result of this License or out of the use or inability to use the
Work (including but not limited to damages for loss of goodwill,
work stoppage, computer failure or malfunction, or any and all
other commercial damages or losses), even if such Contributor
has been advised of the possibility of such damages.
9. Accepting Warranty or Additional Liability. While redistributing
the Work or Derivative Works thereof, You may choose to offer,
and charge a fee for, acceptance of support, warranty, indemnity,
or other liability obligations and/or rights consistent with this
License. However, in accepting such obligations, You may act only
on Your own behalf and on Your sole responsibility, not on behalf
of any other Contributor, and only if You agree to indemnify,
defend, and hold each Contributor harmless for any liability
incurred by, or claims asserted against, such Contributor by reason
of your accepting any such warranty or additional liability.
END OF TERMS AND CONDITIONS
APPENDIX: How to apply the Apache License to your work.
To apply the Apache License to your work, attach the following
boilerplate notice, with the fields enclosed by brackets "[]"
replaced with your own identifying information. (Don't include
the brackets!) The text should be enclosed in the appropriate
comment syntax for the file format. We also recommend that a
file or class name and description of purpose be included on the
same "printed page" as the copyright notice for easier
identification within third-party archives.
Copyright [yyyy] [name of copyright owner]
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.

25
libs/ecs/LICENSE-MIT Normal file
View file

@ -0,0 +1,25 @@
Copyright (c) 2021 Hexops Contributors (given via the Git commit history).
Permission is hereby granted, free of charge, to any
person obtaining a copy of this software and associated
documentation files (the "Software"), to deal in the
Software without restriction, including without
limitation the rights to use, copy, modify, merge,
publish, distribute, sublicense, and/or sell copies of
the Software, and to permit persons to whom the Software
is furnished to do so, subject to the following
conditions:
The above copyright notice and this permission notice
shall be included in all copies or substantial portions
of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF
ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED
TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A
PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT
SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR
IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
DEALINGS IN THE SOFTWARE.

43
libs/ecs/README.md Normal file
View file

@ -0,0 +1,43 @@
# mach/ecs, an Entity Component System for Zig <a href="https://hexops.com"><img align="right" alt="Hexops logo" src="https://raw.githubusercontent.com/hexops/media/master/readme.svg"></img></a>
`mach/ecs` is an Entity Component System for Zig built from first-principles.
## Design principles:
* Clean-room implementation (author has not read any other ECS implementation code.)
* Solve the problems ECS solves, in a way that is natural to Zig and leverages Zig comptime.
* Avoid patent infringement upon Unity ECS patent claims.
* Fast. Optimal for CPU caches, multi-threaded, leverage comptime as much as is reasonable.
* Simple. Small API footprint, should be natural and fun - not like you're writing boilerplate.
* Enable other libraries to provide tracing, editors, visualizers, profilers, etc.
## ⚠️ in-development ⚠️
Under heavy development, not ready for use!
As development continues, we're publishing a blog series ["Let's build an Entity Component System from scatch"](https://devlog.hexops.com/categories/build-an-ecs/).
Join us in developing it, give us advice, etc. [on Matrix chat](https://matrix.to/#/#ecs:matrix.org) or [follow updates on Twitter](https://twitter.com/machengine).
## Known issues
There are plenty of known issues, and things that just aren't implemented yet. And certainly many unknown issues, too.
* Missing multi-threading!
* Currently only handles entity management, no world management or scheduling. No global data, etc.
* Lack of API documentation (see "example" test)
* Missing hooks that would enable visualizing memory usage, # of entities, components, etc. and otherwise enable integration of editors/visualizers/profilers/etc.
* We have dense and sparse data, but no shared data yet.
* If many entities are deleted, iteration becomes slower due to needing to skip over entities in the free_slots set, we should add a .compact() method that allows for remediating this.
* If *tons* of entities are deleted, even with .compact(), memory would not be free'd / returned to the OS by the underlying components arrays. We could add a .compactAndFree() method to correct this.
* It would be nicer if there were configuration options for performing .compactAndFree() automatically, e.g. if the number of free entity slots is particularly high or something.
* Currently we do not expose an API for pre-allocating entities (i.e. allocating capacity up front) but that's very important for perf and memory usage in the real world.
* When entity is deleted, maybe via systems / an event/callback, need a way to be notified of destruction. Same with updated maybe.
See also the numerous TODOs in main.zig.
## Copyright & patent mitigation
The initial implementation was a clean-room implementation by Stephen Gutekanst without having read other ECS implementations' code, but with speaking to people familiar with other ECS implementations. Contributions past the initial implementation may be made by individuals in non-clean-room settings (familiar with open source implementations only.)
Critically, this entity component system stores components for a classified archetype using independent arrays allocated per component as well as hashmaps for sparse component data as an optimization. This is a novel and fundamentally different process than what is described in Unity Software Inc's patent US 10,599,560. This is not legal advice.

26
libs/ecs/build.zig Normal file
View file

@ -0,0 +1,26 @@
const std = @import("std");
pub fn build(b: *std.build.Builder) void {
const mode = b.standardReleaseOptions();
const target = b.standardTargetOptions(.{});
const test_step = b.step("test", "Run library tests");
test_step.dependOn(&testStep(b, mode, target).step);
}
pub fn testStep(b: *std.build.Builder, mode: std.builtin.Mode, target: std.zig.CrossTarget) *std.build.RunStep {
const main_tests = b.addTestExe("ecs-tests", (comptime thisDir()) ++ "/src/main.zig");
main_tests.setBuildMode(mode);
main_tests.setTarget(target);
main_tests.install();
return main_tests.run();
}
pub const pkg = std.build.Pkg{
.name = "ecs",
.source = .{ .path = thisDir() ++ "/src/main.zig" },
.dependencies = &[_]std.build.Pkg{},
};
fn thisDir() []const u8 {
return std.fs.path.dirname(@src().file) orelse ".";
}

870
libs/ecs/src/entities.zig Normal file
View file

@ -0,0 +1,870 @@
const std = @import("std");
const mem = std.mem;
const Allocator = mem.Allocator;
const testing = std.testing;
const builtin = @import("builtin");
const assert = std.debug.assert;
const is_debug = builtin.mode == .Debug;
/// An entity ID uniquely identifies an entity globally within an Entities set.
pub const EntityID = u64;
const TypeId = enum(usize) { _ };
// typeId implementation by Felix "xq" Queißner
fn typeId(comptime T: type) TypeId {
_ = T;
return @intToEnum(TypeId, @ptrToInt(&struct {
var x: u8 = 0;
}.x));
}
const Column = struct {
name: []const u8,
typeId: TypeId,
size: u32,
alignment: u16,
offset: usize,
};
fn by_alignment_name(context: void, lhs: Column, rhs: Column) bool {
_ = context;
if (lhs.alignment < rhs.alignment) return true;
return std.mem.lessThan(u8, lhs.name, rhs.name);
}
/// Represents a single archetype, that is, entities which have the same exact set of component
/// types. When a component is added or removed from an entity, it's archetype changes.
///
/// Database equivalent: a table where rows are entities and columns are components (dense storage).
pub const ArchetypeStorage = struct {
allocator: Allocator,
/// The hash of every component name in this archetype, i.e. the name of this archetype.
hash: u64,
/// The length of the table (used number of rows.)
len: u32,
/// The capacity of the table (allocated number of rows.)
capacity: u32,
/// Describes the columns stored in the `block` of memory, sorted by the smallest alignment
/// value.
columns: []Column,
/// The block of memory where all entities of this archetype are actually stored. This memory is
/// laid out as contiguous column values (i.e. the same way MultiArrayList works, SoA style)
/// so `[col1_val1, col1_val2, col2_val1, col2_val2, ...]`. The number of rows is always
/// identical (the `ArchetypeStorage.capacity`), and an "id" column is always present (the
/// entity IDs stored in the table.) The value names, size, and alignments are described by the
/// `ArchetypeStorage.columns` slice.
///
/// When necessary, padding is added between the column value *arrays* in order to achieve
/// alignment.
block: []u8,
/// Calculates the storage.hash value. This is a hash of all the component names, and can
/// effectively be used to uniquely identify this table within the database.
pub fn calculateHash(storage: *ArchetypeStorage) void {
storage.hash = 0;
for (storage.columns) |column| {
storage.hash ^= std.hash_map.hashString(column.name);
}
}
pub fn deinit(storage: *ArchetypeStorage, gpa: Allocator) void {
gpa.free(storage.columns);
}
fn debugValidateRow(storage: *ArchetypeStorage, gpa: Allocator, row: anytype) void {
inline for (std.meta.fields(@TypeOf(row))) |field, index| {
const column = storage.columns[index];
if (typeId(field.field_type) != column.typeId) {
const msg = std.mem.concat(gpa, u8, &.{
"unexpected type: ",
@typeName(field.field_type),
" expected: ",
column.name,
}) catch |err| @panic(@errorName(err));
@panic(msg);
}
}
}
/// appends a new row to this table, with all undefined values.
pub fn appendUndefined(storage: *ArchetypeStorage, gpa: Allocator) !u32 {
try storage.ensureUnusedCapacity(gpa, 1);
assert(storage.len < storage.capacity);
const row_index = storage.len;
storage.len += 1;
return row_index;
}
pub fn append(storage: *ArchetypeStorage, gpa: Allocator, row: anytype) !u32 {
if (is_debug) storage.debugValidateRow(gpa, row);
try storage.ensureUnusedCapacity(gpa, 1);
assert(storage.len < storage.capacity);
storage.len += 1;
storage.setRow(gpa, storage.len - 1, row);
return storage.len;
}
pub fn undoAppend(storage: *ArchetypeStorage) void {
storage.len -= 1;
}
/// Ensures there is enough unused capacity to store `num_rows`.
pub fn ensureUnusedCapacity(storage: *ArchetypeStorage, gpa: Allocator, num_rows: usize) !void {
return storage.ensureTotalCapacity(gpa, storage.len + num_rows);
}
/// Ensures the total capacity is enough to store `new_capacity` rows total.
pub fn ensureTotalCapacity(storage: *ArchetypeStorage, gpa: Allocator, new_capacity: usize) !void {
var better_capacity = storage.capacity;
if (better_capacity >= new_capacity) return;
while (true) {
better_capacity += better_capacity / 2 + 8;
if (better_capacity >= new_capacity) break;
}
return storage.setCapacity(gpa, better_capacity);
}
/// Sets the capacity to exactly `new_capacity` rows total
///
/// Asserts `new_capacity >= storage.len`, if you want to shrink capacity then change the len
/// yourself first.
pub fn setCapacity(storage: *ArchetypeStorage, gpa: Allocator, new_capacity: usize) !void {
assert(storage.capacity >= storage.len);
// TODO: ensure columns are sorted by alignment
var new_capacity_bytes: usize = 0;
for (storage.columns) |*column| {
const max_padding = column.alignment - 1;
new_capacity_bytes += max_padding;
new_capacity_bytes += new_capacity * column.size;
}
const new_block = try gpa.alloc(u8, new_capacity_bytes);
var offset: usize = 0;
for (storage.columns) |*column| {
const addr = @ptrToInt(&new_block[offset]);
const aligned_addr = std.mem.alignForward(addr, column.alignment);
const padding = aligned_addr - addr;
offset += padding;
if (storage.capacity > 0) {
const slice = storage.block[column.offset .. column.offset + storage.capacity * column.size];
mem.copy(u8, new_block[offset..], slice);
}
column.offset = offset;
offset += new_capacity * column.size;
}
if (storage.capacity > 0) {
gpa.free(storage.block);
}
storage.block = new_block;
storage.capacity = @intCast(u32, new_capacity);
}
/// Sets the entire row's values in the table.
pub fn setRow(storage: *ArchetypeStorage, gpa: Allocator, row_index: u32, row: anytype) void {
if (is_debug) storage.debugValidateRow(gpa, row);
const fields = std.meta.fields(@TypeOf(row));
inline for (fields) |field, index| {
const ColumnType = field.field_type;
if (@sizeOf(ColumnType) == 0) continue;
const column = storage.columns[index];
const columnValues = @ptrCast([*]ColumnType, @alignCast(@alignOf(ColumnType), &storage.block[column.offset]));
columnValues[row_index] = @field(row, field.name);
}
}
/// Sets the value of the named components (columns) for the given row in the table.
pub fn set(storage: *ArchetypeStorage, gpa: Allocator, row_index: u32, name: []const u8, component: anytype) void {
const ColumnType = @TypeOf(component);
if (@sizeOf(ColumnType) == 0) return;
for (storage.columns) |column| {
if (!std.mem.eql(u8, column.name, name)) continue;
if (is_debug) {
if (typeId(ColumnType) != column.typeId) {
const msg = std.mem.concat(gpa, u8, &.{
"unexpected type: ",
@typeName(ColumnType),
" expected: ",
column.name,
}) catch |err| @panic(@errorName(err));
@panic(msg);
}
}
const columnValues = @ptrCast([*]ColumnType, @alignCast(@alignOf(ColumnType), &storage.block[column.offset]));
columnValues[row_index] = component;
return;
}
@panic("no such component");
}
pub fn get(storage: *ArchetypeStorage, gpa: Allocator, row_index: u32, name: []const u8, comptime ColumnType: type) ?ColumnType {
for (storage.columns) |column| {
if (!std.mem.eql(u8, column.name, name)) continue;
if (@sizeOf(ColumnType) == 0) return {};
if (is_debug) {
if (typeId(ColumnType) != column.typeId) {
const msg = std.mem.concat(gpa, u8, &.{
"unexpected type: ",
@typeName(ColumnType),
" expected: ",
column.name,
}) catch |err| @panic(@errorName(err));
@panic(msg);
}
}
const columnValues = @ptrCast([*]ColumnType, @alignCast(@alignOf(ColumnType), &storage.block[column.offset]));
return columnValues[row_index];
}
return null;
}
pub fn getRaw(storage: *ArchetypeStorage, row_index: u32, name: []const u8) []u8 {
for (storage.columns) |column| {
if (!std.mem.eql(u8, column.name, name)) continue;
const start = column.offset + (column.size * row_index);
return storage.block[start .. start + (column.size)];
}
@panic("no such component");
}
pub fn setRaw(storage: *ArchetypeStorage, row_index: u32, column: Column, component: []u8) !void {
if (is_debug) {
const ok = blk: {
for (storage.columns) |col| {
if (std.mem.eql(u8, col.name, column.name)) {
break :blk true;
}
}
break :blk false;
};
if (!ok) @panic("setRaw with non-matching column");
}
mem.copy(u8, storage.block[column.offset + (row_index * column.size) ..], component);
}
/// Swap-removes the specified row with the last row in the table.
pub fn remove(storage: *ArchetypeStorage, row_index: u32) void {
if (storage.len > 1) {
for (storage.columns) |column| {
const dstStart = column.offset + (column.size * row_index);
const dst = storage.block[dstStart .. dstStart + (column.size)];
const srcStart = column.offset + (column.size * (storage.len - 1));
const src = storage.block[srcStart .. srcStart + (column.size)];
std.mem.copy(u8, dst, src);
}
}
storage.len -= 1;
}
/// Tells if this archetype has every one of the given components.
pub fn hasComponents(storage: *ArchetypeStorage, components: []const []const u8) bool {
for (components) |component_name| {
if (!storage.hasComponent(component_name)) return false;
}
return true;
}
/// Tells if this archetype has a component with the specified name.
pub fn hasComponent(storage: *ArchetypeStorage, component: []const u8) bool {
for (storage.columns) |column| {
if (std.mem.eql(u8, column.name, component)) return true;
}
return false;
}
};
pub const void_archetype_hash = std.math.maxInt(u64);
/// A database of entities. For example, all player, monster, etc. entities in a game world.
///
/// ```
/// const world = Entities.init(allocator); // all entities in our world.
/// defer world.deinit();
///
/// const player1 = world.new(); // our first "player" entity
/// const player2 = world.new(); // our second "player" entity
/// ```
///
/// Entities are divided into archetypes for optimal, CPU cache efficient storage. For example, all
/// entities with two components `Location` and `Name` are stored in the same table dedicated to
/// densely storing `(Location, Name)` rows in contiguous memory. This not only ensures CPU cache
/// efficiency (leveraging data oriented design) which improves iteration speed over entities for
/// example, but makes queries like "find all entities with a Location component" ridiculously fast
/// because one need only find the tables which have a column for storing Location components and it
/// is then guaranteed every entity in the table has that component (entities do not need to be
/// checked one by one to determine if they have a Location component.)
///
/// Components can be added and removed to entities at runtime as you please:
///
/// ```
/// try player1.set("rotation", Rotation{ .degrees = 90 });
/// try player1.remove("rotation");
/// ```
///
/// When getting a component value, you must know it's type or undefined behavior will occur:
/// TODO: improve this!
///
/// ```
/// if (player1.get("rotation", Rotation)) |rotation| {
/// // player1 had a rotation component!
/// }
/// ```
///
/// When a component is added or removed from an entity, it's archetype is said to change. For
/// example player1 may have had the archetype `(Location, Name)` before, and after adding the
/// rotation component has the archetype `(Location, Name, Rotation)`. It will be automagically
/// "moved" from the table that stores entities with `(Location, Name)` components to the table that
/// stores `(Location, Name, Rotation)` components for you.
///
/// You can have 65,535 archetypes in total, and 4,294,967,295 entities total. Entities which are
/// deleted are merely marked as "unused" and recycled
///
/// Database equivalents:
/// * Entities is a database of tables, where each table represents a single archetype.
/// * ArchetypeStorage is a table, whose rows are entities and columns are components.
/// * EntityID is a mere 32-bit array index, pointing to a 16-bit archetype table index and 32-bit
/// row index, enabling entities to "move" from one archetype table to another seamlessly and
/// making lookup by entity ID a few cheap array indexing operations.
/// * ComponentStorage(T) is a column of data within a table for a single type of component `T`.
pub fn Entities(all_components: anytype) type {
// TODO: validate all_components is a namespaced component set in the form we expect
_ = all_components;
return struct {
allocator: Allocator,
/// TODO!
counter: EntityID = 0,
/// A mapping of entity IDs (array indices) to where an entity's component values are actually
/// stored.
entities: std.AutoHashMapUnmanaged(EntityID, Pointer) = .{},
/// A mapping of archetype hash to their storage.
///
/// Database equivalent: table name -> tables representing entities.
archetypes: std.AutoArrayHashMapUnmanaged(u64, ArchetypeStorage) = .{},
const Self = @This();
/// Points to where an entity is stored, specifically in which archetype table and in which row
/// of that table. That is, the entity's component values are stored at:
///
/// ```
/// Entities.archetypes[ptr.archetype_index].rows[ptr.row_index]
/// ```
///
pub const Pointer = struct {
archetype_index: u16,
row_index: u32,
};
pub const Query = Query: {
const namespaces = std.meta.fields(@TypeOf(all_components));
var fields: [namespaces.len]std.builtin.Type.UnionField = undefined;
inline for (namespaces) |namespace, i| {
const component_enum = std.meta.FieldEnum(namespace.field_type);
fields[i] = .{
.name = namespace.name,
.field_type = component_enum,
.alignment = @alignOf(component_enum),
};
}
// need type_info variable (rather than embedding in @Type() call)
// to work around stage 1 bug
const type_info = std.builtin.Type{
.Union = .{
.layout = .Auto,
.tag_type = std.meta.FieldEnum(@TypeOf(all_components)),
.fields = &fields,
.decls = &.{},
},
};
break :Query @Type(type_info);
};
fn fullComponentName(comptime q: Query) []const u8 {
return @tagName(q) ++ "." ++ @tagName(@field(q, @tagName(std.meta.activeTag(q))));
}
pub fn Iter(comptime components: []const Query) type {
return struct {
entities: *Self,
archetype_index: usize = 0,
row_index: u32 = 0,
const Iterator = @This();
pub const Entry = struct {
entity: EntityID,
pub fn unlock(e: Entry) void {
_ = e;
}
};
pub fn next(iter: *Iterator) ?Entry {
const entities = iter.entities;
// If the archetype table we're looking at does not contain the components we're
// querying for, keep searching through tables until we find one that does.
var archetype = entities.archetypes.entries.get(iter.archetype_index).value;
while (!hasComponents(archetype, components) or iter.row_index >= archetype.len) {
iter.archetype_index += 1;
iter.row_index = 0;
if (iter.archetype_index >= entities.archetypes.count()) {
return null;
}
archetype = entities.archetypes.entries.get(iter.archetype_index).value;
}
const row_entity_id = archetype.get(iter.entities.allocator, iter.row_index, "id", EntityID).?;
iter.row_index += 1;
return Entry{ .entity = row_entity_id };
}
};
}
fn hasComponents(storage: ArchetypeStorage, comptime components: []const Query) bool {
var archetype = storage;
if (components.len == 0) return false;
inline for (components) |component| {
if (!archetype.hasComponent(fullComponentName(component))) return false;
}
return true;
}
pub fn query(entities: *Self, comptime components: []const Query) Iter(components) {
return Iter(components){
.entities = entities,
};
}
pub fn init(allocator: Allocator) !Self {
var entities = Self{ .allocator = allocator };
const columns = try allocator.alloc(Column, 1);
columns[0] = .{
.name = "id",
.typeId = typeId(EntityID),
.size = @sizeOf(EntityID),
.alignment = @alignOf(EntityID),
.offset = undefined,
};
try entities.archetypes.put(allocator, void_archetype_hash, ArchetypeStorage{
.allocator = allocator,
.len = 0,
.capacity = 0,
.columns = columns,
.block = undefined,
.hash = void_archetype_hash,
});
return entities;
}
pub fn deinit(entities: *Self) void {
entities.entities.deinit(entities.allocator);
var iter = entities.archetypes.iterator();
while (iter.next()) |entry| {
entities.allocator.free(entry.value_ptr.block);
entry.value_ptr.deinit(entities.allocator);
}
entities.archetypes.deinit(entities.allocator);
}
/// Returns a new entity.
pub fn new(entities: *Self) !EntityID {
const new_id = entities.counter;
entities.counter += 1;
var void_archetype = entities.archetypes.getPtr(void_archetype_hash).?;
const new_row = try void_archetype.append(entities.allocator, .{ .id = new_id });
const void_pointer = Pointer{
.archetype_index = 0, // void archetype is guaranteed to be first index
.row_index = new_row,
};
entities.entities.put(entities.allocator, new_id, void_pointer) catch |err| {
void_archetype.undoAppend();
return err;
};
return new_id;
}
/// Removes an entity.
pub fn remove(entities: *Self, entity: EntityID) !void {
var archetype = entities.archetypeByID(entity);
const ptr = entities.entities.get(entity).?;
// A swap removal will be performed, update the entity stored in the last row of the
// archetype table to point to the row the entity we are removing is currently located.
if (archetype.len > 1) {
const last_row_entity_id = archetype.get(entities.allocator, archetype.len - 1, "id", EntityID).?;
try entities.entities.put(entities.allocator, last_row_entity_id, Pointer{
.archetype_index = ptr.archetype_index,
.row_index = ptr.row_index,
});
}
// Perform a swap removal to remove our entity from the archetype table.
archetype.remove(ptr.row_index);
_ = entities.entities.remove(entity);
}
/// Returns the archetype storage for the given entity.
pub inline fn archetypeByID(entities: *Self, entity: EntityID) *ArchetypeStorage {
const ptr = entities.entities.get(entity).?;
return &entities.archetypes.values()[ptr.archetype_index];
}
/// Sets the named component to the specified value for the given entity,
/// moving the entity from it's current archetype table to the new archetype
/// table if required.
pub fn setComponent(
entities: *Self,
entity: EntityID,
comptime namespace_name: std.meta.FieldEnum(@TypeOf(all_components)),
comptime component_name: std.meta.FieldEnum(@TypeOf(@field(all_components, @tagName(namespace_name)))),
component: @field(
@field(all_components, @tagName(namespace_name)),
@tagName(component_name),
),
) !void {
const name = @tagName(namespace_name) ++ "." ++ @tagName(component_name);
var archetype = entities.archetypeByID(entity);
// Determine the old hash for the archetype.
const old_hash = archetype.hash;
// Determine the new hash for the archetype + new component
var have_already = archetype.hasComponent(name);
const new_hash = if (have_already) old_hash else old_hash ^ std.hash_map.hashString(name);
// Find the archetype storage for this entity. Could be a new archetype storage table (if a
// new component was added), or the same archetype storage table (if just updating the
// value of a component.)
var archetype_entry = try entities.archetypes.getOrPut(entities.allocator, new_hash);
// getOrPut allocated, so the archetype we retrieved earlier may no longer be a valid
// pointer. Refresh it now:
archetype = entities.archetypeByID(entity);
if (!archetype_entry.found_existing) {
const columns = entities.allocator.alloc(Column, archetype.columns.len + 1) catch |err| {
assert(entities.archetypes.swapRemove(new_hash));
return err;
};
mem.copy(Column, columns, archetype.columns);
columns[columns.len - 1] = .{
.name = name,
.typeId = typeId(@TypeOf(component)),
.size = @sizeOf(@TypeOf(component)),
.alignment = if (@sizeOf(@TypeOf(component)) == 0) 1 else @alignOf(@TypeOf(component)),
.offset = undefined,
};
std.sort.sort(Column, columns, {}, by_alignment_name);
archetype_entry.value_ptr.* = ArchetypeStorage{
.allocator = entities.allocator,
.len = 0,
.capacity = 0,
.columns = columns,
.block = undefined,
.hash = undefined,
};
const new_archetype = archetype_entry.value_ptr;
new_archetype.calculateHash();
}
// Either new storage (if the entity moved between storage tables due to having a new
// component) or the prior storage (if the entity already had the component and it's value
// is merely being updated.)
var current_archetype_storage = archetype_entry.value_ptr;
if (new_hash == old_hash) {
// Update the value of the existing component of the entity.
const ptr = entities.entities.get(entity).?;
current_archetype_storage.set(entities.allocator, ptr.row_index, name, component);
return;
}
// Copy to all component values for our entity from the old archetype storage (archetype)
// to the new one (current_archetype_storage).
const new_row = try current_archetype_storage.appendUndefined(entities.allocator);
const old_ptr = entities.entities.get(entity).?;
// Update the storage/columns for all of the existing components on the entity.
current_archetype_storage.set(entities.allocator, new_row, "id", entity);
for (archetype.columns) |column| {
if (std.mem.eql(u8, column.name, "id")) continue;
for (current_archetype_storage.columns) |corresponding| {
if (std.mem.eql(u8, column.name, corresponding.name)) {
const old_value_raw = archetype.getRaw(old_ptr.row_index, column.name);
current_archetype_storage.setRaw(new_row, corresponding, old_value_raw) catch |err| {
current_archetype_storage.undoAppend();
return err;
};
break;
}
}
}
// Update the storage/column for the new component.
current_archetype_storage.set(entities.allocator, new_row, name, component);
archetype.remove(old_ptr.row_index);
const swapped_entity_id = archetype.get(entities.allocator, old_ptr.row_index, "id", EntityID).?;
// TODO: try is wrong here and below?
// if we removed the last entry from archetype, then swapped_entity_id == entity
// so the second entities.put will clobber this one
try entities.entities.put(entities.allocator, swapped_entity_id, old_ptr);
try entities.entities.put(entities.allocator, entity, Pointer{
.archetype_index = @intCast(u16, archetype_entry.index),
.row_index = new_row,
});
return;
}
/// gets the named component of the given type (which must be correct, otherwise undefined
/// behavior will occur). Returns null if the component does not exist on the entity.
pub fn getComponent(
entities: *Self,
entity: EntityID,
comptime namespace_name: std.meta.FieldEnum(@TypeOf(all_components)),
comptime component_name: std.meta.FieldEnum(@TypeOf(@field(all_components, @tagName(namespace_name)))),
) ?@field(
@field(all_components, @tagName(namespace_name)),
@tagName(component_name),
) {
const Component = comptime @field(
@field(all_components, @tagName(namespace_name)),
@tagName(component_name),
);
const name = @tagName(namespace_name) ++ "." ++ @tagName(component_name);
var archetype = entities.archetypeByID(entity);
const ptr = entities.entities.get(entity).?;
return archetype.get(entities.allocator, ptr.row_index, name, Component);
}
/// Removes the named component from the entity, or noop if it doesn't have such a component.
pub fn removeComponent(
entities: *Self,
entity: EntityID,
comptime namespace_name: std.meta.FieldEnum(@TypeOf(all_components)),
comptime component_name: std.meta.FieldEnum(@TypeOf(@field(all_components, @tagName(namespace_name)))),
) !void {
const name = @tagName(namespace_name) ++ "." ++ @tagName(component_name);
var archetype = entities.archetypeByID(entity);
if (!archetype.hasComponent(name)) return;
// Determine the old hash for the archetype.
const old_hash = archetype.hash;
// Determine the new hash for the archetype with the component removed
var new_hash: u64 = 0;
for (archetype.columns) |column| {
if (!std.mem.eql(u8, column.name, name)) new_hash ^= std.hash_map.hashString(column.name);
}
assert(new_hash != old_hash);
// Find the archetype storage this entity will move to. Note that although an entity with
// (A, B, C) components implies archetypes ((A), (A, B), (A, B, C)) exist there is no
// guarantee that archetype (A, C) exists - and so removing a component sometimes does
// require creating a new archetype table!
var archetype_entry = try entities.archetypes.getOrPut(entities.allocator, new_hash);
// getOrPut allocated, so the archetype we retrieved earlier may no longer be a valid
// pointer. Refresh it now:
archetype = entities.archetypeByID(entity);
if (!archetype_entry.found_existing) {
const columns = entities.allocator.alloc(Column, archetype.columns.len - 1) catch |err| {
assert(entities.archetypes.swapRemove(new_hash));
return err;
};
var i: usize = 0;
for (archetype.columns) |column| {
if (std.mem.eql(u8, column.name, name)) continue;
columns[i] = column;
i += 1;
}
archetype_entry.value_ptr.* = ArchetypeStorage{
.allocator = entities.allocator,
.len = 0,
.capacity = 0,
.columns = columns,
.block = undefined,
.hash = undefined,
};
const new_archetype = archetype_entry.value_ptr;
new_archetype.calculateHash();
}
var current_archetype_storage = archetype_entry.value_ptr;
// Copy to all component values for our entity from the old archetype storage (archetype)
// to the new one (current_archetype_storage).
const new_row = try current_archetype_storage.appendUndefined(entities.allocator);
const old_ptr = entities.entities.get(entity).?;
// Update the storage/columns for all of the existing components on the entity that exist in
// the new archetype table (i.e. excluding the component to remove.)
current_archetype_storage.set(entities.allocator, new_row, "id", entity);
for (current_archetype_storage.columns) |column| {
if (std.mem.eql(u8, column.name, "id")) continue;
for (archetype.columns) |corresponding| {
if (std.mem.eql(u8, column.name, corresponding.name)) {
const old_value_raw = archetype.getRaw(old_ptr.row_index, column.name);
current_archetype_storage.setRaw(new_row, column, old_value_raw) catch |err| {
current_archetype_storage.undoAppend();
return err;
};
break;
}
}
}
archetype.remove(old_ptr.row_index);
const swapped_entity_id = archetype.get(entities.allocator, old_ptr.row_index, "id", EntityID).?;
// TODO: try is wrong here and below?
// if we removed the last entry from archetype, then swapped_entity_id == entity
// so the second entities.put will clobber this one
try entities.entities.put(entities.allocator, swapped_entity_id, old_ptr);
try entities.entities.put(entities.allocator, entity, Pointer{
.archetype_index = @intCast(u16, archetype_entry.index),
.row_index = new_row,
});
}
// TODO: iteration over all entities
// TODO: iteration over all entities with components (U, V, ...)
// TODO: iteration over all entities with type T
// TODO: iteration over all entities with type T and components (U, V, ...)
// TODO: "indexes" - a few ideas we could express:
//
// * Graph relations index: e.g. parent-child entity relations for a DOM / UI / scene graph.
// * Spatial index: "give me all entities within 5 units distance from (x, y, z)"
// * Generic index: "give me all entities where arbitraryFunction(e) returns true"
//
// TODO: ability to remove archetype entirely, deleting all entities in it
// TODO: ability to remove archetypes with no entities (garbage collection)
};
}
test "entity ID size" {
try testing.expectEqual(8, @sizeOf(EntityID));
}
test "example" {
const allocator = testing.allocator;
const Location = struct {
x: f32 = 0,
y: f32 = 0,
z: f32 = 0,
};
const Rotation = struct { degrees: f32 };
const all_components = .{
.game = .{
.location = Location,
.name = []const u8,
.rotation = Rotation,
},
};
//-------------------------------------------------------------------------
// Create a world.
var world = try Entities(all_components).init(allocator);
defer world.deinit();
//-------------------------------------------------------------------------
// Create first player entity.
var player1 = try world.new();
try world.setComponent(player1, .game, .name, "jane"); // add Name component
try world.setComponent(player1, .game, .location, .{}); // add Location component
// Create second player entity.
var player2 = try world.new();
try testing.expect(world.getComponent(player2, .game, .location) == null);
try testing.expect(world.getComponent(player2, .game, .name) == null);
//-------------------------------------------------------------------------
// We can add new components at will.
try world.setComponent(player2, .game, .rotation, .{ .degrees = 90 });
try testing.expect(world.getComponent(player1, .game, .rotation) == null); // player1 has no rotation
//-------------------------------------------------------------------------
// Remove a component from any entity at will.
// TODO: add a way to "cleanup" truly unused archetypes
try world.removeComponent(player1, .game, .name);
try world.removeComponent(player1, .game, .location);
try world.removeComponent(player1, .game, .location); // doesn't exist? no problem.
//-------------------------------------------------------------------------
// Introspect things.
//
// Archetype IDs, these are our "table names" - they're just hashes of all the component names
// within the archetype table.
var archetypes = world.archetypes.keys();
try testing.expectEqual(@as(usize, 6), archetypes.len);
try testing.expectEqual(@as(u64, void_archetype_hash), archetypes[0]);
try testing.expectEqual(@as(u64, 10567852867187873021), archetypes[1]);
try testing.expectEqual(@as(u64, 14072552683119202344), archetypes[2]);
try testing.expectEqual(@as(u64, 17945105277702244199), archetypes[3]);
try testing.expectEqual(@as(u64, 12546098194442238762), archetypes[4]);
try testing.expectEqual(@as(u64, 4457032469566706731), archetypes[5]);
// Number of (living) entities stored in an archetype table.
try testing.expectEqual(@as(usize, 0), world.archetypes.get(archetypes[0]).?.len);
try testing.expectEqual(@as(usize, 0), world.archetypes.get(archetypes[1]).?.len);
try testing.expectEqual(@as(usize, 0), world.archetypes.get(archetypes[2]).?.len);
try testing.expectEqual(@as(usize, 1), world.archetypes.get(archetypes[3]).?.len);
try testing.expectEqual(@as(usize, 0), world.archetypes.get(archetypes[4]).?.len);
try testing.expectEqual(@as(usize, 1), world.archetypes.get(archetypes[5]).?.len);
// Components for a given archetype.
var columns = world.archetypes.get(archetypes[2]).?.columns;
try testing.expectEqual(@as(usize, 3), columns.len);
try testing.expectEqualStrings("game.location", columns[0].name);
try testing.expectEqualStrings("game.name", columns[1].name);
try testing.expectEqualStrings("id", columns[2].name);
// Archetype resolved via entity ID
var player2_archetype = world.archetypeByID(player2);
try testing.expectEqual(@as(u64, 4263961864502127795), player2_archetype.hash);
// TODO: iterating components an entity has not currently supported.
//-------------------------------------------------------------------------
// Remove an entity whenever you wish. Just be sure not to try and use it later!
try world.remove(player1);
}

99
libs/ecs/src/main.zig Normal file
View file

@ -0,0 +1,99 @@
//! mach/ecs is an Entity component system implementation.
//!
//! ## Design principles:
//!
//! * Clean-room implementation (author has not read any other ECS implementation code.)
//! * Solve the problems ECS solves, in a way that is natural to Zig and leverages Zig comptime.
//! * Avoid patent infringement upon Unity ECS patent claims.
//! * Fast. Optimal for CPU caches, multi-threaded, leverage comptime as much as is reasonable.
//! * Simple. Small API footprint, should be natural and fun - not like you're writing boilerplate.
//! * Enable other libraries to provide tracing, editors, visualizers, profilers, etc.
//!
//! ## Copyright & patent mitigation
//!
//! The initial implementation was a clean-room implementation by Stephen Gutekanst without having
//! read other ECS implementations' code, but with speaking to people familiar with other ECS
//! implementations. Contributions past the initial implementation may be made by individuals in
//! non-clean-room settings.
//!
//! Critically, this entity component system stores components for a classified archetype using
//! independent arrays allocated per component as well as hashmaps for sparse component data as an
//! optimization. This is a novel and fundamentally different process than what is described in
//! Unity Software Inc's patent US 10,599,560. This is not legal advice.
//!
const std = @import("std");
const testing = std.testing;
pub const EntityID = @import("entities.zig").EntityID;
pub const Entities = @import("entities.zig").Entities;
pub const Module = @import("systems.zig").Module;
pub const Modules = @import("systems.zig").Modules;
pub const Messages = @import("systems.zig").Messages;
pub const MessagesTag = @import("systems.zig").MessagesTag;
pub const World = @import("systems.zig").World;
// TODO:
// * Iteration
// * Querying
// * Multi threading
// * Multiple entities having one value
// * Sparse storage?
test "inclusion" {
std.testing.refAllDeclsRecursive(@This());
}
test "example" {
const allocator = testing.allocator;
const PhysicsMsg = Messages(.{
.tick = void,
});
const physicsUpdate = (struct {
pub fn physicsUpdate(msg: PhysicsMsg) void {
switch (msg) {
.tick => std.debug.print("\nphysics tick!\n", .{}),
}
}
}).physicsUpdate;
const modules = Modules(.{
.physics = Module(.{
.components = .{
.id = u32,
},
.globals = struct {
pointer: u8,
},
.messages = PhysicsMsg,
.update = physicsUpdate,
}),
.renderer = Module(.{
.components = .{
.id = u16,
},
}),
});
//-------------------------------------------------------------------------
// Create a world.
var world = try World(modules).init(allocator);
defer world.deinit();
// Initialize globals.
world.set(.physics, .pointer, 123);
_ = world.get(.physics, .pointer); // == 123
const player1 = try world.entities.new();
const player2 = try world.entities.new();
const player3 = try world.entities.new();
try world.entities.setComponent(player1, .physics, .id, 1234);
try world.entities.setComponent(player1, .renderer, .id, 1234);
try world.entities.setComponent(player2, .physics, .id, 1234);
try world.entities.setComponent(player3, .physics, .id, 1234);
world.tick();
}

291
libs/ecs/src/systems.zig Normal file
View file

@ -0,0 +1,291 @@
const std = @import("std");
const mem = std.mem;
const Allocator = mem.Allocator;
const testing = std.testing;
const math = std.math;
const StructField = std.builtin.Type.StructField;
const EnumField = std.builtin.Type.EnumField;
const UnionField = std.builtin.Type.UnionField;
const Entities = @import("entities.zig").Entities;
/// An ECS module can provide components, systems, and global values.
pub fn Module(comptime Params: anytype) @TypeOf(Params) {
// TODO: validate the type
return Params;
}
/// Describes a set of ECS modules, each of which can provide components, systems, and more.
pub fn Modules(modules: anytype) @TypeOf(modules) {
// TODO: validate the type
return modules;
}
/// Returns a tagged union representing the messages, turning this:
///
/// ```
/// .{ .tick = void, .foo = i32 }
/// ```
///
/// Into `T`:
///
/// ```
/// const T = union(MessagesTag(messages)) {
/// .tick = void,
/// .foo = i32,
/// };
/// ```
pub fn Messages(messages: anytype) type {
var fields: []const UnionField = &[0]UnionField{};
const message_fields = std.meta.fields(@TypeOf(messages));
inline for (message_fields) |message_field| {
const message_type = @field(messages, message_field.name);
fields = fields ++ [_]std.builtin.Type.UnionField{.{
.name = message_field.name,
.field_type = message_type,
.alignment = if (message_type == void) 0 else @alignOf(message_type),
}};
}
// Hack to workaround stage1 compiler bug. https://github.com/ziglang/zig/issues/8114
//
// return @Type(.{
// .Union = .{
// .layout = .Auto,
// .tag_type = MessagesTag(messages),
// .fields = fields,
// .decls = &[_]std.builtin.Type.Declaration{},
// },
// });
//
const Ref = union(enum) { temp };
var info = @typeInfo(Ref);
info.Union.tag_type = MessagesTag(messages);
info.Union.fields = fields;
return @Type(info);
}
/// Returns the tag enum for a tagged union representing the messages, turning this:
///
/// ```
/// .{ .tick = void, .foo = i32 }
/// ```
///
/// Into this:
///
/// ```
/// enum { .tick, .foo };
/// ```
pub fn MessagesTag(messages: anytype) type {
var fields: []const EnumField = &[0]EnumField{};
const message_fields = std.meta.fields(@TypeOf(messages));
inline for (message_fields) |message_field, index| {
fields = fields ++ [_]std.builtin.Type.EnumField{.{
.name = message_field.name,
.value = index,
}};
}
return @Type(.{
.Enum = .{
.layout = .Auto,
.tag_type = std.meta.Int(.unsigned, @floatToInt(u16, math.ceil(math.log2(@intToFloat(f64, message_fields.len))))),
.fields = fields,
.decls = &[_]std.builtin.Type.Declaration{},
.is_exhaustive = true,
},
});
}
/// Returns the namespaced components struct **type**.
//
/// Consult `namespacedComponents` for how a value of this type looks.
fn NamespacedComponents(comptime modules: anytype) type {
var fields: []const StructField = &[0]StructField{};
inline for (std.meta.fields(@TypeOf(modules))) |module_field| {
const module = @field(modules, module_field.name);
if (@hasField(@TypeOf(module), "components")) {
fields = fields ++ [_]std.builtin.Type.StructField{.{
.name = module_field.name,
.field_type = @TypeOf(module.components),
.default_value = null,
.is_comptime = false,
.alignment = @alignOf(@TypeOf(module.components)),
}};
}
}
return @Type(.{
.Struct = .{
.layout = .Auto,
.is_tuple = false,
.fields = fields,
.decls = &[_]std.builtin.Type.Declaration{},
},
});
}
/// Extracts namespaces components from modules like this:
///
/// ```
/// .{
/// .renderer = .{
/// .components = .{
/// .location = Vec3,
/// .rotation = Vec3,
/// },
/// ...
/// },
/// .physics2d = .{
/// .components = .{
/// .location = Vec2
/// .velocity = Vec2,
/// },
/// ...
/// },
/// }
/// ```
///
/// Returning a namespaced components value like this:
///
/// ```
/// .{
/// .renderer = .{
/// .location = Vec3,
/// .rotation = Vec3,
/// },
/// .physics2d = .{
/// .location = Vec2
/// .velocity = Vec2,
/// },
/// }
/// ```
///
fn namespacedComponents(comptime modules: anytype) NamespacedComponents(modules) {
var x: NamespacedComponents(modules) = undefined;
inline for (std.meta.fields(@TypeOf(modules))) |module_field| {
const module = @field(modules, module_field.name);
if (@hasField(@TypeOf(module), "components")) {
@field(x, module_field.name) = module.components;
}
}
return x;
}
/// Extracts namespaced globals from modules like this:
///
/// ```
/// .{
/// .renderer = .{
/// .globals = struct{
/// foo: *Bar,
/// baz: Bam,
/// },
/// ...
/// },
/// .physics2d = .{
/// .globals = struct{
/// foo: *Instance,
/// },
/// ...
/// },
/// }
/// ```
///
/// Into a namespaced global type like this:
///
/// ```
/// struct{
/// renderer: struct{
/// foo: *Bar,
/// baz: Bam,
/// },
/// physics2d: struct{
/// foo: *Instance,
/// },
/// }
/// ```
///
fn NamespacedGlobals(comptime modules: anytype) type {
var fields: []const StructField = &[0]StructField{};
inline for (std.meta.fields(@TypeOf(modules))) |module_field| {
const module = @field(modules, module_field.name);
if (@hasField(@TypeOf(module), "globals")) {
fields = fields ++ [_]std.builtin.Type.StructField{.{
.name = module_field.name,
.field_type = module.globals,
.default_value = null,
.is_comptime = false,
.alignment = @alignOf(module.globals),
}};
}
}
return @Type(.{
.Struct = .{
.layout = .Auto,
.is_tuple = false,
.fields = fields,
.decls = &[_]std.builtin.Type.Declaration{},
},
});
}
pub fn World(comptime modules: anytype) type {
const all_components = namespacedComponents(modules);
return struct {
allocator: Allocator,
entities: Entities(all_components),
globals: NamespacedGlobals(modules),
const Self = @This();
pub fn init(allocator: Allocator) !Self {
return Self{
.allocator = allocator,
.entities = try Entities(all_components).init(allocator),
.globals = undefined,
};
}
pub fn deinit(world: *Self) void {
world.entities.deinit();
}
/// Gets a global value called `.global_tag` from the module named `.module_tag`
pub fn get(world: *Self, module_tag: anytype, global_tag: anytype) @TypeOf(@field(
@field(world.globals, @tagName(module_tag)),
@tagName(global_tag),
)) {
return comptime @field(
@field(world.globals, @tagName(module_tag)),
@tagName(global_tag),
);
}
/// Sets a global value called `.global_tag` in the module named `.module_tag`
pub fn set(
world: *Self,
comptime module_tag: anytype,
comptime global_tag: anytype,
value: @TypeOf(@field(
@field(world.globals, @tagName(module_tag)),
@tagName(global_tag),
)),
) void {
comptime @field(
@field(world.globals, @tagName(module_tag)),
@tagName(global_tag),
) = value;
}
/// Tick sends the global 'tick' message to all modules that are subscribed to it.
pub fn tick(world: *Self) void {
_ = world;
inline for (std.meta.fields(@TypeOf(modules))) |module_field| {
const module = @field(modules, module_field.name);
if (@hasField(@TypeOf(module), "messages")) {
if (@hasField(module.messages, "tick")) module.update(.tick);
}
}
}
};
}

2
libs/freetype/.gitattributes vendored Normal file
View file

@ -0,0 +1,2 @@
* text=auto eol=lf
upstream/** linguist-vendored

1
libs/freetype/.github/FUNDING.yml vendored Normal file
View file

@ -0,0 +1 @@
github: slimsag

View file

@ -0,0 +1,5 @@
Please send your change to [the main repository](https://github.com/hexops/mach/tree/main/freetype) instead, sorry for the trouble!
This helps us avoid some complex merge conflicts we run into when changes are made to both repositories and history needs to be reconciled. Keeping PRs in just that repository enables us to use `git subtree` to trivially keep the two repositories in sync.
Once your PR is merged over there, it'll automatically sync to this repository.

46
libs/freetype/.github/workflows/ci.yml vendored Normal file
View file

@ -0,0 +1,46 @@
name: CI
on:
- push
- pull_request
jobs:
x86_64-linux:
runs-on: ubuntu-latest
steps:
- name: Checkout
uses: actions/checkout@v2
- name: Setup Zig
run: |
sudo apt install xz-utils
sudo sh -c 'wget -c https://ziglang.org/builds/zig-linux-x86_64-0.10.0-dev.3551+92568a009.tar.xz -O - | tar -xJ --strip-components=1 -C /usr/local/bin'
- name: x86_64-linux -> aarch64-macos
run: zig build test -Dtarget=aarch64-macos.12-none
- name: test
run: |
zig build test
x86_64-windows:
runs-on: windows-latest
steps:
- name: Checkout
uses: actions/checkout@v2
- name: Install Git
run: choco install git
- name: Setup Zig
run: |
$ProgressPreference = 'SilentlyContinue'
Invoke-WebRequest -Uri "https://ziglang.org/builds/zig-windows-x86_64-0.10.0-dev.3551+92568a009.zip" -OutFile "C:\zig.zip"
cd C:\
7z x zig.zip
Add-Content $env:GITHUB_PATH "C:\zig-windows-x86_64-0.10.0-dev.3551+92568a009\"
- name: test
run: zig build test
x86_64-macos:
runs-on: macos-latest
steps:
- name: Checkout
uses: actions/checkout@v2
- name: Setup Zig
run: |
brew install xz
sudo sh -c 'wget -c https://ziglang.org/builds/zig-macos-x86_64-0.10.0-dev.3551+92568a009.tar.xz -O - | tar -xJ --strip-components=1 -C /usr/local/bin'
- name: test
run: zig build test

18
libs/freetype/.gitignore vendored Normal file
View file

@ -0,0 +1,18 @@
# This file is for zig-specific build artifacts.
# If you have OS-specific or editor-specific files to ignore,
# such as *.swp or .DS_Store, put those in your global
# ~/.gitignore and put this in your ~/.gitconfig:
#
# [core]
# excludesfile = ~/.gitignore
#
# Cheers!
# -andrewrk
zig-cache/
zig-out/
/release/
/debug/
/build/
/build-*/
/docgen_tmp/

3
libs/freetype/.gitmodules vendored Normal file
View file

@ -0,0 +1,3 @@
[submodule "upstream"]
path = upstream
url = https://github.com/hexops/freetype

13
libs/freetype/LICENSE Normal file
View file

@ -0,0 +1,13 @@
Copyright 2021, Hexops Contributors (given via the Git commit history).
All documentation, image, sound, font, and 2D/3D model files are CC-BY-4.0 licensed unless
otherwise noted. You may get a copy of this license at https://creativecommons.org/licenses/by/4.0
Files in a directory with a separate LICENSE file may contain files under different license terms,
described within that LICENSE file.
All other files are licensed under the Apache License, Version 2.0 (see LICENSE-APACHE or http://www.apache.org/licenses/LICENSE-2.0)
or the MIT license (see LICENSE-MIT or http://opensource.org/licenses/MIT), at your option.
All files in the project without exclusions may not be copied, modified, or distributed except
according to the terms above.

View file

@ -0,0 +1,202 @@
Apache License
Version 2.0, January 2004
http://www.apache.org/licenses/
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
1. Definitions.
"License" shall mean the terms and conditions for use, reproduction,
and distribution as defined by Sections 1 through 9 of this document.
"Licensor" shall mean the copyright owner or entity authorized by
the copyright owner that is granting the License.
"Legal Entity" shall mean the union of the acting entity and all
other entities that control, are controlled by, or are under common
control with that entity. For the purposes of this definition,
"control" means (i) the power, direct or indirect, to cause the
direction or management of such entity, whether by contract or
otherwise, or (ii) ownership of fifty percent (50%) or more of the
outstanding shares, or (iii) beneficial ownership of such entity.
"You" (or "Your") shall mean an individual or Legal Entity
exercising permissions granted by this License.
"Source" form shall mean the preferred form for making modifications,
including but not limited to software source code, documentation
source, and configuration files.
"Object" form shall mean any form resulting from mechanical
transformation or translation of a Source form, including but
not limited to compiled object code, generated documentation,
and conversions to other media types.
"Work" shall mean the work of authorship, whether in Source or
Object form, made available under the License, as indicated by a
copyright notice that is included in or attached to the work
(an example is provided in the Appendix below).
"Derivative Works" shall mean any work, whether in Source or Object
form, that is based on (or derived from) the Work and for which the
editorial revisions, annotations, elaborations, or other modifications
represent, as a whole, an original work of authorship. For the purposes
of this License, Derivative Works shall not include works that remain
separable from, or merely link (or bind by name) to the interfaces of,
the Work and Derivative Works thereof.
"Contribution" shall mean any work of authorship, including
the original version of the Work and any modifications or additions
to that Work or Derivative Works thereof, that is intentionally
submitted to Licensor for inclusion in the Work by the copyright owner
or by an individual or Legal Entity authorized to submit on behalf of
the copyright owner. For the purposes of this definition, "submitted"
means any form of electronic, verbal, or written communication sent
to the Licensor or its representatives, including but not limited to
communication on electronic mailing lists, source code control systems,
and issue tracking systems that are managed by, or on behalf of, the
Licensor for the purpose of discussing and improving the Work, but
excluding communication that is conspicuously marked or otherwise
designated in writing by the copyright owner as "Not a Contribution."
"Contributor" shall mean Licensor and any individual or Legal Entity
on behalf of whom a Contribution has been received by Licensor and
subsequently incorporated within the Work.
2. Grant of Copyright License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
copyright license to reproduce, prepare Derivative Works of,
publicly display, publicly perform, sublicense, and distribute the
Work and such Derivative Works in Source or Object form.
3. Grant of Patent License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
(except as stated in this section) patent license to make, have made,
use, offer to sell, sell, import, and otherwise transfer the Work,
where such license applies only to those patent claims licensable
by such Contributor that are necessarily infringed by their
Contribution(s) alone or by combination of their Contribution(s)
with the Work to which such Contribution(s) was submitted. If You
institute patent litigation against any entity (including a
cross-claim or counterclaim in a lawsuit) alleging that the Work
or a Contribution incorporated within the Work constitutes direct
or contributory patent infringement, then any patent licenses
granted to You under this License for that Work shall terminate
as of the date such litigation is filed.
4. Redistribution. You may reproduce and distribute copies of the
Work or Derivative Works thereof in any medium, with or without
modifications, and in Source or Object form, provided that You
meet the following conditions:
(a) You must give any other recipients of the Work or
Derivative Works a copy of this License; and
(b) You must cause any modified files to carry prominent notices
stating that You changed the files; and
(c) You must retain, in the Source form of any Derivative Works
that You distribute, all copyright, patent, trademark, and
attribution notices from the Source form of the Work,
excluding those notices that do not pertain to any part of
the Derivative Works; and
(d) If the Work includes a "NOTICE" text file as part of its
distribution, then any Derivative Works that You distribute must
include a readable copy of the attribution notices contained
within such NOTICE file, excluding those notices that do not
pertain to any part of the Derivative Works, in at least one
of the following places: within a NOTICE text file distributed
as part of the Derivative Works; within the Source form or
documentation, if provided along with the Derivative Works; or,
within a display generated by the Derivative Works, if and
wherever such third-party notices normally appear. The contents
of the NOTICE file are for informational purposes only and
do not modify the License. You may add Your own attribution
notices within Derivative Works that You distribute, alongside
or as an addendum to the NOTICE text from the Work, provided
that such additional attribution notices cannot be construed
as modifying the License.
You may add Your own copyright statement to Your modifications and
may provide additional or different license terms and conditions
for use, reproduction, or distribution of Your modifications, or
for any such Derivative Works as a whole, provided Your use,
reproduction, and distribution of the Work otherwise complies with
the conditions stated in this License.
5. Submission of Contributions. Unless You explicitly state otherwise,
any Contribution intentionally submitted for inclusion in the Work
by You to the Licensor shall be under the terms and conditions of
this License, without any additional terms or conditions.
Notwithstanding the above, nothing herein shall supersede or modify
the terms of any separate license agreement you may have executed
with Licensor regarding such Contributions.
6. Trademarks. This License does not grant permission to use the trade
names, trademarks, service marks, or product names of the Licensor,
except as required for reasonable and customary use in describing the
origin of the Work and reproducing the content of the NOTICE file.
7. Disclaimer of Warranty. Unless required by applicable law or
agreed to in writing, Licensor provides the Work (and each
Contributor provides its Contributions) on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
implied, including, without limitation, any warranties or conditions
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
PARTICULAR PURPOSE. You are solely responsible for determining the
appropriateness of using or redistributing the Work and assume any
risks associated with Your exercise of permissions under this License.
8. Limitation of Liability. In no event and under no legal theory,
whether in tort (including negligence), contract, or otherwise,
unless required by applicable law (such as deliberate and grossly
negligent acts) or agreed to in writing, shall any Contributor be
liable to You for damages, including any direct, indirect, special,
incidental, or consequential damages of any character arising as a
result of this License or out of the use or inability to use the
Work (including but not limited to damages for loss of goodwill,
work stoppage, computer failure or malfunction, or any and all
other commercial damages or losses), even if such Contributor
has been advised of the possibility of such damages.
9. Accepting Warranty or Additional Liability. While redistributing
the Work or Derivative Works thereof, You may choose to offer,
and charge a fee for, acceptance of support, warranty, indemnity,
or other liability obligations and/or rights consistent with this
License. However, in accepting such obligations, You may act only
on Your own behalf and on Your sole responsibility, not on behalf
of any other Contributor, and only if You agree to indemnify,
defend, and hold each Contributor harmless for any liability
incurred by, or claims asserted against, such Contributor by reason
of your accepting any such warranty or additional liability.
END OF TERMS AND CONDITIONS
APPENDIX: How to apply the Apache License to your work.
To apply the Apache License to your work, attach the following
boilerplate notice, with the fields enclosed by brackets "[]"
replaced with your own identifying information. (Don't include
the brackets!) The text should be enclosed in the appropriate
comment syntax for the file format. We also recommend that a
file or class name and description of purpose be included on the
same "printed page" as the copyright notice for easier
identification within third-party archives.
Copyright [yyyy] [name of copyright owner]
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.

25
libs/freetype/LICENSE-MIT Normal file
View file

@ -0,0 +1,25 @@
Copyright (c) 2021 Hexops Contributors (given via the Git commit history).
Permission is hereby granted, free of charge, to any
person obtaining a copy of this software and associated
documentation files (the "Software"), to deal in the
Software without restriction, including without
limitation the rights to use, copy, modify, merge,
publish, distribute, sublicense, and/or sell copies of
the Software, and to permit persons to whom the Software
is furnished to do so, subject to the following
conditions:
The above copyright notice and this permission notice
shall be included in all copies or substantial portions
of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF
ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED
TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A
PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT
SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR
IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
DEALINGS IN THE SOFTWARE.

View file

@ -0,0 +1,42 @@
FREETYPE LICENSES
-----------------
The FreeType 2 font engine is copyrighted work and cannot be used
legally without a software license. In order to make this project
usable to a vast majority of developers, we distribute it under two
mutually exclusive open-source licenses.
This means that *you* must choose *one* of the two licenses described
below, then obey all its terms and conditions when using FreeType 2 in
any of your projects or products.
- The FreeType License, found in the file `docs/FTL.TXT`, which is
similar to the original BSD license *with* an advertising clause
that forces you to explicitly cite the FreeType project in your
product's documentation. All details are in the license file.
This license is suited to products which don't use the GNU General
Public License.
Note that this license is compatible to the GNU General Public
License version 3, but not version 2.
- The GNU General Public License version 2, found in
`docs/GPLv2.TXT` (any later version can be used also), for
programs which already use the GPL. Note that the FTL is
incompatible with GPLv2 due to its advertisement clause.
The contributed BDF and PCF drivers come with a license similar to
that of the X Window System. It is compatible to the above two
licenses (see files `src/bdf/README` and `src/pcf/README`). The same
holds for the source code files `src/base/fthash.c` and
`include/freetype/internal/fthash.h`; they wer part of the BDF driver
in earlier FreeType versions.
The gzip module uses the zlib license (see `src/gzip/zlib.h`) which
too is compatible to the above two licenses.
The MD5 checksum support (only used for debugging in development
builds) is in the public domain.
--- end of LICENSE.TXT ---

105
libs/freetype/README.md Normal file
View file

@ -0,0 +1,105 @@
# mach/freetype - Ziggified FreeType 2 bindings [![CI](https://github.com/hexops/mach-freetype/workflows/CI/badge.svg)](https://github.com/hexops/mach-freetype/actions) <a href="https://hexops.com"><img align="right" alt="Hexops logo" src="https://raw.githubusercontent.com/hexops/media/main/readme.svg"></img></a>
Ziggified FreeType 2 bindings that [Mach engine](https://github.com/hexops/mach) uses, with zero-fuss installation, cross compilation, and more.
This repository is a separate copy of the same library in the [main Mach repository](https://github.com/hexops/mach), and is automatically kept in sync, so that anyone can use this library in their own project / engine if they like!
## Zero fuss installation, cross compilation, and more
[Just as with Mach](https://github.com/hexops/mach#zero-fuss-installation--cross-compilation), you get zero fuss installation & cross compilation using these Freetype bindings. **only `zig` and `git` are needed to build from any OS and produce binaries for every OS.** No system dependencies at all.
## Usage
## Getting started
### Adding dependency (using Git)
In a `libs` subdirectory of the root of your project:
```sh
git clone https://github.com/hexops/mach-freetype
```
Then in your `build.zig` add:
```zig
...
const freetype = @import("libs/mach-freetype/build.zig");
pub fn build(b: *Builder) void {
...
exe.addPackage(freetype.pkg);
freetype.link(b, exe, .{});
}
```
and optionaly add harfbuzz:
```zig
exe.addPackage(freetype.harfbuzz_pkg);
freetype.link(b, exe, .{ .harfbuzz = .{} });
```
You can also optionally build brotli compression (for WOFF2 font support):
```zig
exe.addPackage(freetype.pkg);
freetype.link(b, exe, .{ .freetype = .{ .brotli = true } });
```
<details>
<description>Optional: Using Gyro dependency manager</description>
```sh
gyro add --src github hexops/mach-freetype --root src/main.zig --alias freetype
gyro add --build-dep --src github hexops/mach-freetype --root build.zig --alias build-freetype
```
Then in your `build.zig` add:
```zig
...
const pkgs = @import("deps.zig").pkgs;
const freetype = @import("build-freetype");
pub fn build(b: *Builder) void {
...
exe.addPackage(pkgs.freetype);
freetype.link(b, exe, .{});
}
```
**WARNING: You should use `gyro build` instead of `zig build` now!**
</details>
Now you can import in code:
```zig
const freetype = @import("freetype");
```
## Examples
See the `examples/` directory. for running each example do:
```sh
zig build run-example-<name> # e.g run-example-single-glyph
```
## Join the community
Join the Mach engine community [on Matrix chat](https://matrix.to/#/#hexops:matrix.org) to discuss this project, ask questions, get help, etc.
## Issues
Issues are tracked in the [main Mach repository](https://github.com/hexops/mach/issues?q=is%3Aissue+is%3Aopen+label%3Afreetype).
## Contributing
Contributions are very welcome. Pull requests must be sent to [the main repository](https://github.com/hexops/mach/tree/main/freetype) to avoid some complex merge conflicts we'd get by accepting contributions in both repositories. Once the changes are merged there, they'll get sync'd to this repository automatically.
# Thanks
Special thanks to [@alichraghi](https://github.com/alichraghi), original author of these bindings who contributed them to Mach!

278
libs/freetype/build.zig Normal file
View file

@ -0,0 +1,278 @@
const std = @import("std");
const Builder = std.build.Builder;
const ft_root = thisDir() ++ "/upstream/freetype";
const ft_include_path = ft_root ++ "/include";
const hb_root = thisDir() ++ "/upstream/harfbuzz";
const hb_include_path = hb_root ++ "/src";
const brotli_root = thisDir() ++ "/upstream/brotli";
const c_pkg = std.build.Pkg{
.name = "c",
.source = .{ .path = thisDir() ++ "/src/c.zig" },
};
const utils_pkg = std.build.Pkg{
.name = "utils",
.source = .{ .path = thisDir() ++ "/src/utils.zig" },
};
pub const pkg = std.build.Pkg{
.name = "freetype",
.source = .{ .path = thisDir() ++ "/src/main.zig" },
.dependencies = &.{ c_pkg, utils_pkg },
};
pub const harfbuzz_pkg = std.build.Pkg{
.name = "harfbuzz",
.source = .{ .path = thisDir() ++ "/src/harfbuzz/main.zig" },
.dependencies = &.{ c_pkg, utils_pkg, pkg },
};
pub const Options = struct {
freetype: FreetypeOptions = .{},
harfbuzz: ?HarfbuzzOptions = null,
};
pub const FreetypeOptions = struct {
/// the path you specify freetype options
/// via `ftoptions.h` and `ftmodule.h`
ft_config_path: ?[]const u8 = null,
brotli: bool = false,
};
pub const HarfbuzzOptions = struct {};
pub fn build(b: *std.build.Builder) !void {
const mode = b.standardReleaseOptions();
const target = b.standardTargetOptions(.{});
const test_app = b.addStaticLibrary("test_app", null);
test_app.setBuildMode(mode);
test_app.setTarget(target);
link(b, test_app, .{ .freetype = .{ .brotli = true } });
test_app.install();
const test_step = b.step("test", "Run library tests");
test_step.dependOn(&testStep(b, mode, target).step);
inline for ([_][]const u8{
"single-glyph",
"glyph-to-svg",
}) |example| {
const example_exe = b.addExecutable("example-" ++ example, "examples/" ++ example ++ ".zig");
example_exe.setBuildMode(mode);
example_exe.setTarget(target);
example_exe.addPackage(pkg);
// Remove once the stage2 compiler fixes pkg std not found
example_exe.addPackage(utils_pkg);
link(b, example_exe, .{});
const example_install = b.addInstallArtifact(example_exe);
var example_compile_step = b.step("example-" ++ example, "Compile '" ++ example ++ "' example");
example_compile_step.dependOn(&example_install.step);
const example_run_cmd = example_exe.run();
if (b.args) |args| {
example_run_cmd.addArgs(args);
}
const example_run_step = b.step("run-example-" ++ example, "Run '" ++ example ++ "' example");
example_run_step.dependOn(&example_run_cmd.step);
}
}
pub fn testStep(b: *Builder, mode: std.builtin.Mode, target: std.zig.CrossTarget) *std.build.RunStep {
const main_tests = b.addTestExe("freetype-tests", (comptime thisDir()) ++ "/src/main.zig");
main_tests.setBuildMode(mode);
main_tests.setTarget(target);
main_tests.addPackage(c_pkg);
// Remove once the stage2 compiler fixes pkg std not found
main_tests.addPackage(utils_pkg);
main_tests.addPackage(pkg);
link(b, main_tests, .{
.freetype = .{
.brotli = true,
},
.harfbuzz = .{},
});
main_tests.main_pkg_path = (comptime thisDir());
main_tests.install();
return main_tests.run();
}
pub fn link(b: *Builder, step: *std.build.LibExeObjStep, options: Options) void {
const ft_lib = buildFreetype(b, step, options.freetype);
step.linkLibrary(ft_lib);
step.addIncludePath(ft_include_path);
step.addIncludePath(hb_include_path);
if (options.harfbuzz) |hb_options| {
const hb_lib = buildHarfbuzz(b, step, hb_options);
step.linkLibrary(hb_lib);
}
}
pub fn buildFreetype(b: *Builder, step: *std.build.LibExeObjStep, options: FreetypeOptions) *std.build.LibExeObjStep {
// TODO(build-system): https://github.com/hexops/mach/issues/229#issuecomment-1100958939
ensureDependencySubmodule(b.allocator, "upstream") catch unreachable;
const main_abs = ft_root ++ "/src/base/ftbase.c";
const lib = b.addStaticLibrary("freetype", main_abs);
lib.defineCMacro("FT2_BUILD_LIBRARY", "1");
lib.setBuildMode(step.build_mode);
lib.setTarget(step.target);
lib.linkLibC();
lib.addIncludePath(ft_include_path);
if (options.ft_config_path) |path|
lib.addIncludePath(path);
if (options.brotli) {
const brotli_lib = buildBrotli(b, step);
step.linkLibrary(brotli_lib);
lib.defineCMacro("FT_REQUIRE_BROTLI", "1");
}
const target = (std.zig.system.NativeTargetInfo.detect(b.allocator, step.target) catch unreachable).target;
if (target.os.tag == .windows) {
lib.addCSourceFile(ft_root ++ "/builds/windows/ftsystem.c", &.{});
lib.addCSourceFile(ft_root ++ "/builds/windows/ftdebug.c", &.{});
} else {
lib.addCSourceFile(ft_root ++ "/src/base/ftsystem.c", &.{});
lib.addCSourceFile(ft_root ++ "/src/base/ftdebug.c", &.{});
}
if (target.os.tag.isBSD() or target.os.tag == .linux) {
lib.defineCMacro("HAVE_UNISTD_H", "1");
lib.defineCMacro("HAVE_FCNTL_H", "1");
lib.addCSourceFile(ft_root ++ "/builds/unix/ftsystem.c", &.{});
if (target.os.tag == .macos) {
lib.addCSourceFile(ft_root ++ "/src/base/ftmac.c", &.{});
}
}
lib.addCSourceFiles(freetype_base_sources, &.{});
lib.install();
return lib;
}
pub fn buildHarfbuzz(b: *Builder, step: *std.build.LibExeObjStep, options: HarfbuzzOptions) *std.build.LibExeObjStep {
_ = options;
const main_abs = hb_root ++ "/src/harfbuzz.cc";
const lib = b.addStaticLibrary("harfbuzz", main_abs);
lib.setBuildMode(step.build_mode);
lib.setTarget(step.target);
lib.linkLibCpp();
lib.addIncludePath(hb_include_path);
lib.addIncludePath(ft_include_path);
lib.defineCMacro("HAVE_FREETYPE", "1");
lib.install();
return lib;
}
pub fn buildBrotli(b: *Builder, step: *std.build.LibExeObjStep) *std.build.LibExeObjStep {
const main_abs = brotli_root ++ "/common/constants.c";
const lib = b.addStaticLibrary("brotli", main_abs);
lib.setBuildMode(step.build_mode);
lib.setTarget(step.target);
lib.linkLibC();
lib.addIncludePath(brotli_root ++ "/include");
lib.addCSourceFiles(brotli_base_sources, &.{});
lib.install();
return lib;
}
fn thisDir() []const u8 {
return std.fs.path.dirname(@src().file) orelse ".";
}
fn ensureDependencySubmodule(allocator: std.mem.Allocator, path: []const u8) !void {
if (std.process.getEnvVarOwned(allocator, "NO_ENSURE_SUBMODULES")) |no_ensure_submodules| {
if (std.mem.eql(u8, no_ensure_submodules, "true")) return;
} else |_| {}
var child = std.ChildProcess.init(&.{ "git", "submodule", "update", "--init", path }, allocator);
child.cwd = (comptime thisDir());
child.stderr = std.io.getStdErr();
child.stdout = std.io.getStdOut();
_ = try child.spawnAndWait();
}
const freetype_base_sources = &[_][]const u8{
ft_root ++ "/src/autofit/autofit.c",
ft_root ++ "/src/base/ftbbox.c",
ft_root ++ "/src/base/ftbdf.c",
ft_root ++ "/src/base/ftbitmap.c",
ft_root ++ "/src/base/ftcid.c",
ft_root ++ "/src/base/ftfstype.c",
ft_root ++ "/src/base/ftgasp.c",
ft_root ++ "/src/base/ftglyph.c",
ft_root ++ "/src/base/ftgxval.c",
ft_root ++ "/src/base/ftinit.c",
ft_root ++ "/src/base/ftmm.c",
ft_root ++ "/src/base/ftotval.c",
ft_root ++ "/src/base/ftpatent.c",
ft_root ++ "/src/base/ftpfr.c",
ft_root ++ "/src/base/ftstroke.c",
ft_root ++ "/src/base/ftsynth.c",
ft_root ++ "/src/base/fttype1.c",
ft_root ++ "/src/base/ftwinfnt.c",
ft_root ++ "/src/bdf/bdf.c",
ft_root ++ "/src/bzip2/ftbzip2.c",
ft_root ++ "/src/cache/ftcache.c",
ft_root ++ "/src/cff/cff.c",
ft_root ++ "/src/cid/type1cid.c",
ft_root ++ "/src/gzip/ftgzip.c",
ft_root ++ "/src/lzw/ftlzw.c",
ft_root ++ "/src/pcf/pcf.c",
ft_root ++ "/src/pfr/pfr.c",
ft_root ++ "/src/psaux/psaux.c",
ft_root ++ "/src/pshinter/pshinter.c",
ft_root ++ "/src/psnames/psnames.c",
ft_root ++ "/src/raster/raster.c",
ft_root ++ "/src/sdf/sdf.c",
ft_root ++ "/src/sfnt/sfnt.c",
ft_root ++ "/src/smooth/smooth.c",
ft_root ++ "/src/svg/svg.c",
ft_root ++ "/src/truetype/truetype.c",
ft_root ++ "/src/type1/type1.c",
ft_root ++ "/src/type42/type42.c",
ft_root ++ "/src/winfonts/winfnt.c",
};
const brotli_base_sources = &[_][]const u8{
brotli_root ++ "/enc/backward_references.c",
brotli_root ++ "/enc/fast_log.c",
brotli_root ++ "/enc/histogram.c",
brotli_root ++ "/enc/cluster.c",
brotli_root ++ "/enc/command.c",
brotli_root ++ "/enc/compress_fragment_two_pass.c",
brotli_root ++ "/enc/entropy_encode.c",
brotli_root ++ "/enc/bit_cost.c",
brotli_root ++ "/enc/memory.c",
brotli_root ++ "/enc/backward_references_hq.c",
brotli_root ++ "/enc/dictionary_hash.c",
brotli_root ++ "/enc/encoder_dict.c",
brotli_root ++ "/enc/block_splitter.c",
brotli_root ++ "/enc/compress_fragment.c",
brotli_root ++ "/enc/literal_cost.c",
brotli_root ++ "/enc/brotli_bit_stream.c",
brotli_root ++ "/enc/encode.c",
brotli_root ++ "/enc/static_dict.c",
brotli_root ++ "/enc/utf8_util.c",
brotli_root ++ "/enc/metablock.c",
brotli_root ++ "/dec/decode.c",
brotli_root ++ "/dec/bit_reader.c",
brotli_root ++ "/dec/huffman.c",
brotli_root ++ "/dec/state.c",
brotli_root ++ "/common/context.c",
brotli_root ++ "/common/dictionary.c",
brotli_root ++ "/common/transform.c",
brotli_root ++ "/common/platform.c",
};

View file

@ -0,0 +1,128 @@
const std = @import("std");
const freetype = @import("freetype");
// Remove once the stage2 compiler fixes pkg std not found
comptime {
_ = @import("utils");
}
const OutlinePrinter = struct {
library: freetype.Library,
face: freetype.Face,
output_file: std.fs.File,
path_stream: std.io.FixedBufferStream([]u8),
xMin: isize,
yMin: isize,
width: isize,
height: isize,
const Self = @This();
var buf = [_]u8{0} ** (1024 * 10);
pub fn init(file: std.fs.File) freetype.Error!Self {
var lib = try freetype.Library.init();
return Self{
.library = lib,
.face = try lib.createFace("upstream/assets/FiraSans-Regular.ttf", 0),
.output_file = file,
.path_stream = std.io.fixedBufferStream(&buf),
.xMin = 0,
.yMin = 0,
.width = 0,
.height = 0,
};
}
pub fn deinit(self: Self) void {
self.library.deinit();
}
pub fn outlineExists(self: Self) bool {
const outline = self.face.glyph().outline() orelse return false;
if (outline.numContours() <= 0 or outline.numPoints() <= 0)
return false;
outline.check() catch return false;
return true;
}
pub fn flipOutline(self: Self) void {
const multiplier = 65536;
const matrix = freetype.Matrix{
.xx = 1 * multiplier,
.xy = 0 * multiplier,
.yx = 0 * multiplier,
.yy = -1 * multiplier,
};
self.face.glyph().outline().?.transform(matrix);
}
pub fn extractOutline(self: *Self) !void {
try self.path_stream.writer().writeAll("<path d='");
var callbacks = freetype.Outline.Funcs(*Self){
.move_to = moveToFunction,
.line_to = lineToFunction,
.conic_to = conicToFunction,
.cubic_to = cubicToFunction,
.shift = 0,
.delta = 0,
};
try self.face.glyph().outline().?.decompose(self, callbacks);
try self.path_stream.writer().writeAll("' fill='#000'/>");
}
pub fn computeViewBox(self: *Self) !void {
const boundingBox = try self.face.glyph().outline().?.bbox();
self.xMin = boundingBox.xMin;
self.yMin = boundingBox.yMin;
self.width = boundingBox.xMax - boundingBox.xMin;
self.height = boundingBox.yMax - boundingBox.yMin;
}
pub fn printSVG(self: Self) !void {
try self.output_file.writer().print(
\\<svg xmlns='http://www.w3.org/2000/svg'
\\ xmlns:xlink='http://www.w3.org/1999/xlink'
\\ viewBox='{d} {d} {d} {d}'>
\\ {s}
\\</svg>
, .{ self.xMin, self.yMin, self.width, self.height, self.path_stream.getWritten() });
}
pub fn moveToFunction(self: *Self, to: freetype.Vector) freetype.Error!void {
self.path_stream.writer().print("M {d} {d}\t", .{ to.x, to.y }) catch unreachable;
}
pub fn lineToFunction(self: *Self, to: freetype.Vector) freetype.Error!void {
self.path_stream.writer().print("L {d} {d}\t", .{ to.x, to.y }) catch unreachable;
}
pub fn conicToFunction(self: *Self, control: freetype.Vector, to: freetype.Vector) freetype.Error!void {
self.path_stream.writer().print("Q {d} {d}, {d} {d}\t", .{ control.x, control.y, to.x, to.y }) catch unreachable;
}
pub fn cubicToFunction(self: *Self, control_0: freetype.Vector, control_1: freetype.Vector, to: freetype.Vector) freetype.Error!void {
self.path_stream.writer().print("C {d} {d}, {d} {d}, {d} {d}\t", .{ control_0.x, control_0.y, control_1.x, control_1.y, to.x, to.y }) catch unreachable;
}
pub fn run(self: *Self, symbol: u32) !void {
try self.face.loadChar(symbol, .{ .no_scale = true, .no_bitmap = true });
if (!self.outlineExists())
return error.OutlineDoesntExists;
self.flipOutline();
try self.extractOutline();
try self.computeViewBox();
try self.printSVG();
}
};
pub fn main() !void {
var file = try std.fs.cwd().createFile("out.svg", .{});
defer file.close();
var outline_printer = try OutlinePrinter.init(file);
defer outline_printer.deinit();
try outline_printer.run(@as(u32, 'ë'));
}

View file

@ -0,0 +1,38 @@
// zig build run-example-single-glyph -- B
const std = @import("std");
const freetype = @import("freetype");
// Remove once the stage2 compiler fixes pkg std not found
comptime {
_ = @import("utils");
}
pub fn main() !void {
var gpa = std.heap.GeneralPurposeAllocator(.{}){};
defer _ = gpa.deinit();
const allocator = gpa.allocator();
var args = try std.process.argsAlloc(allocator);
defer std.process.argsFree(allocator, args);
const lib = try freetype.Library.init();
defer lib.deinit();
const face = try lib.createFace("upstream/assets/FiraSans-Regular.ttf", 0);
try face.setCharSize(60 * 48, 0, 50, 0);
try face.loadChar(args[1][0], .{ .render = true });
const bitmap = face.glyph().bitmap();
var i: usize = 0;
while (i < bitmap.rows()) : (i += 1) {
var j: usize = 0;
while (j < bitmap.width()) : (j += 1) {
const char: u8 = switch (bitmap.buffer().?[i * bitmap.width() + j]) {
0 => ' ',
1...128 => ';',
else => '#',
};
std.debug.print("{c}", .{char});
}
std.debug.print("\n", .{});
}
}

419
libs/freetype/src/Face.zig Normal file
View file

@ -0,0 +1,419 @@
const std = @import("std");
const utils = @import("utils");
const c = @import("c");
const intToError = @import("error.zig").intToError;
const Error = @import("error.zig").Error;
const GlyphSlot = @import("freetype.zig").GlyphSlot;
const LoadFlags = @import("freetype.zig").LoadFlags;
const FaceFlags = @import("freetype.zig").FaceFlags;
const StyleFlags = @import("freetype.zig").StyleFlags;
const FSType = @import("freetype.zig").FSType;
const OpenArgs = @import("freetype.zig").OpenArgs;
const KerningMode = @import("freetype.zig").KerningMode;
const Encoding = @import("freetype.zig").Encoding;
const CharMap = @import("freetype.zig").CharMap;
const Size = @import("freetype.zig").Size;
const SizeRequest = @import("freetype.zig").SizeRequest;
const BitmapSize = @import("freetype.zig").BitmapSize;
const Matrix = @import("types.zig").Matrix;
const BBox = @import("types.zig").BBox;
const Vector = @import("image.zig").Vector;
const RootTransform = @import("color.zig").RootTransform;
const PaintFormat = @import("color.zig").PaintFormat;
const Color = @import("color.zig").Color;
const ClipBox = @import("color.zig").ClipBox;
const OpaquePaint = @import("color.zig").OpaquePaint;
const Paint = @import("color.zig").Paint;
const PaletteData = @import("color.zig").PaletteData;
const GlyphLayersIterator = @import("color.zig").GlyphLayersIterator;
pub const CharmapIterator = struct {
face: Face,
index: u32,
charcode: u32,
pub fn init(face: Face) CharmapIterator {
var i: u32 = 0;
const cc = c.FT_Get_First_Char(face.handle, &i);
return .{
.face = face,
.index = i,
.charcode = @intCast(u32, cc),
};
}
pub fn next(self: *CharmapIterator) ?u32 {
self.charcode = @intCast(u32, c.FT_Get_Next_Char(self.face.handle, self.charcode, &self.index));
return if (self.index != 0)
self.charcode
else
null;
}
};
const Face = @This();
handle: c.FT_Face,
pub fn deinit(self: Face) void {
_ = c.FT_Done_Face(self.handle);
}
pub fn attachFile(self: Face, path: []const u8) Error!void {
return self.attachStream(.{
.flags = .{ .path = true },
.data = .{ .path = path },
});
}
pub fn attachMemory(self: Face, bytes: []const u8) Error!void {
return self.attachStream(.{
.flags = .{ .memory = true },
.data = .{ .memory = bytes },
});
}
pub fn attachStream(self: Face, args: OpenArgs) Error!void {
return intToError(c.FT_Attach_Stream(self.handle, &args.cast()));
}
pub fn loadGlyph(self: Face, index: u32, flags: LoadFlags) Error!void {
return intToError(c.FT_Load_Glyph(self.handle, index, flags.cast()));
}
pub fn loadChar(self: Face, char: u32, flags: LoadFlags) Error!void {
return intToError(c.FT_Load_Char(self.handle, char, flags.cast()));
}
pub fn setCharSize(self: Face, pt_width: i32, pt_height: i32, horz_resolution: u16, vert_resolution: u16) Error!void {
return intToError(c.FT_Set_Char_Size(self.handle, pt_width, pt_height, horz_resolution, vert_resolution));
}
pub fn setPixelSizes(self: Face, pixel_width: u32, pixel_height: u32) Error!void {
return intToError(c.FT_Set_Pixel_Sizes(self.handle, pixel_width, pixel_height));
}
pub fn requestSize(self: Face, req: SizeRequest) Error!void {
var req_mut = req;
return intToError(c.FT_Request_Size(self.handle, &req_mut));
}
pub fn selectSize(self: Face, strike_index: i32) Error!void {
return intToError(c.FT_Select_Size(self.handle, strike_index));
}
pub fn setTransform(self: Face, matrix: ?Matrix, delta: ?Vector) Error!void {
var matrix_mut = matrix;
var delta_mut = delta;
return c.FT_Set_Transform(self.handle, if (matrix_mut) |*m| m else null, if (delta_mut) |*d| d else null);
}
pub fn getTransform(self: Face) std.meta.Tuple(&.{ Matrix, Vector }) {
var matrix: Matrix = undefined;
var delta: Vector = undefined;
c.FT_Get_Transform(self.handle, &matrix, &delta);
return .{ matrix, delta };
}
pub fn getCharIndex(self: Face, char: u32) ?u32 {
const i = c.FT_Get_Char_Index(self.handle, char);
return if (i == 0) null else i;
}
pub fn getNameIndex(self: Face, name: [:0]const u8) ?u32 {
const i = c.FT_Get_Name_Index(self.handle, name.ptr);
return if (i == 0) null else i;
}
pub fn getKerning(self: Face, left_char_index: u32, right_char_index: u32, mode: KerningMode) Error!Vector {
var kerning: Vector = undefined;
try intToError(c.FT_Get_Kerning(self.handle, left_char_index, right_char_index, @enumToInt(mode), &kerning));
return kerning;
}
pub fn getTrackKerning(self: Face, point_size: i32, degree: i32) Error!i32 {
var kerning: i32 = 0;
try intToError(c.FT_Get_Track_Kerning(self.handle, point_size, degree, &@intCast(c_long, kerning)));
return kerning;
}
pub fn getGlyphName(self: Face, index: u32, buf: []u8) Error!void {
try intToError(c.FT_Get_Glyph_Name(self.handle, index, buf.ptr, @intCast(c_uint, buf.len)));
}
pub fn getPostscriptName(self: Face) ?[:0]const u8 {
return if (c.FT_Get_Postscript_Name(self.handle)) |face_name|
std.mem.span(@ptrCast([*:0]const u8, face_name))
else
null;
}
pub fn iterateCharmap(self: Face) CharmapIterator {
return CharmapIterator.init(self);
}
pub fn selectCharmap(self: Face, encoding: Encoding) Error!void {
return intToError(c.FT_Select_Charmap(self.handle, @enumToInt(encoding)));
}
pub fn setCharmap(self: Face, char_map: *CharMap) Error!void {
return intToError(c.FT_Set_Charmap(self.handle, char_map));
}
pub fn getFSTypeFlags(self: Face) FSType {
return FSType.from(c.FT_Get_FSType_Flags(self.handle));
}
pub fn getCharVariantIndex(self: Face, char: u32, variant_selector: u32) ?u32 {
return switch (c.FT_Face_GetCharVariantIndex(self.handle, char, variant_selector)) {
0 => null,
else => |i| i,
};
}
pub fn getCharVariantIsDefault(self: Face, char: u32, variant_selector: u32) ?bool {
return switch (c.FT_Face_GetCharVariantIsDefault(self.handle, char, variant_selector)) {
-1 => null,
0 => false,
1 => true,
else => unreachable,
};
}
pub fn getVariantSelectors(self: Face) ?[]u32 {
return if (c.FT_Face_GetVariantSelectors(self.handle)) |chars|
@ptrCast([]u32, std.mem.sliceTo(@ptrCast([*:0]u32, chars), 0))
else
null;
}
pub fn getVariantsOfChar(self: Face, char: u32) ?[]u32 {
return if (c.FT_Face_GetVariantsOfChar(self.handle, char)) |variants|
@ptrCast([]u32, std.mem.sliceTo(@ptrCast([*:0]u32, variants), 0))
else
null;
}
pub fn getCharsOfVariant(self: Face, variant_selector: u32) ?[]u32 {
return if (c.FT_Face_GetCharsOfVariant(self.handle, variant_selector)) |chars|
@ptrCast([]u32, std.mem.sliceTo(@ptrCast([*:0]u32, chars), 0))
else
null;
}
pub fn getPaletteData(self: Face) Error!PaletteData {
var p: c.FT_Palette_Data = undefined;
try intToError(c.FT_Palette_Data_Get(self.handle, &p));
return PaletteData{ .handle = p };
}
fn selectPalette(self: Face, index: u16) Error!?[]const Color {
var color: [*:0]Color = undefined;
try intToError(c.FT_Palette_Select(self.handle, index, &color));
const pd = try getPaletteData();
return self.color[0..pd.numPaletteEntries()];
}
pub fn setPaletteForegroundColor(self: Face, color: Color) Error!void {
try intToError(c.FT_Palette_Set_Foreground_Color(self.handle, color));
}
pub fn getGlyphLayersIterator(self: Face, glyph_index: u32) GlyphLayersIterator {
return GlyphLayersIterator.init(self, glyph_index);
}
pub fn getColorGlyphPaint(self: Face, base_glyph: u32, root_transform: RootTransform) ?Paint {
var opaque_paint: OpaquePaint = undefined;
if (c.FT_Get_Color_Glyph_Paint(self.handle, base_glyph, @enumToInt(root_transform), &opaque_paint) == 0)
return null;
return self.getPaint(opaque_paint);
}
pub fn getColorGlyphClibBox(self: Face, base_glyph: u32) ?ClipBox {
var clib_box: ClipBox = undefined;
if (c.FT_Get_Color_Glyph_ClipBox(self.handle, base_glyph, &clib_box) == 0)
return null;
return clib_box;
}
pub fn getPaint(self: Face, opaque_paint: OpaquePaint) ?Paint {
var p: c.FT_COLR_Paint = undefined;
if (c.FT_Get_Paint(self.handle, opaque_paint, &p) == 0)
return null;
return switch (@intToEnum(PaintFormat, p.format)) {
.color_layers => Paint{ .color_layers = p.u.colr_layers },
.glyph => Paint{ .glyph = p.u.glyph },
.solid => Paint{ .solid = p.u.solid },
.linear_gradient => Paint{ .linear_gradient = p.u.linear_gradient },
.radial_gradient => Paint{ .radial_gradient = p.u.radial_gradient },
.sweep_gradient => Paint{ .sweep_gradient = p.u.sweep_gradient },
.transform => Paint{ .transform = p.u.transform },
.translate => Paint{ .translate = p.u.translate },
.scale => Paint{ .scale = p.u.scale },
.rotate => Paint{ .rotate = p.u.rotate },
.skew => Paint{ .skew = p.u.skew },
.composite => Paint{ .composite = p.u.composite },
.color_glyph => Paint{ .color_glyph = p.u.colr_glyph },
};
}
pub fn newSize(self: Face) Error!Size {
var s: c.FT_Size = undefined;
try intToError(c.FT_New_Size(self.handle, &s));
return Size{ .handle = s };
}
pub fn numFaces(self: Face) u32 {
return @intCast(u32, self.handle.*.num_faces);
}
pub fn faceIndex(self: Face) u32 {
return @intCast(u32, self.handle.*.face_index);
}
pub fn faceFlags(self: Face) FaceFlags {
return FaceFlags.from(self.handle.*.face_flags);
}
pub fn styleFlags(self: Face) StyleFlags {
return StyleFlags.from(self.handle.*.style_flags);
}
pub fn numGlyphs(self: Face) u32 {
return @intCast(u32, self.handle.*.num_glyphs);
}
pub fn familyName(self: Face) ?[:0]const u8 {
return if (self.handle.*.family_name) |family|
std.mem.span(@ptrCast([*:0]const u8, family))
else
null;
}
pub fn styleName(self: Face) ?[:0]const u8 {
return if (self.handle.*.style_name) |style_name|
std.mem.span(@ptrCast([*:0]const u8, style_name))
else
null;
}
pub fn numFixedSizes(self: Face) u32 {
return @intCast(u32, self.handle.*.num_fixed_sizes);
}
pub fn availableSizes(self: Face) ?BitmapSize {
return if (self.handle.*.available_sizes != null)
self.handle.*.available_sizes.*
else
null;
}
pub fn getAdvance(self: Face, glyph_index: u32, load_flags: LoadFlags) Error!i32 {
var a: i32 = 0;
try intToError(c.FT_Get_Advance(self.handle, glyph_index, load_flags.cast(), &@intCast(c_long, a)));
return a;
}
pub fn getAdvances(self: Face, start: u32, advances_out: []c_long, load_flags: LoadFlags) Error!void {
try intToError(c.FT_Get_Advances(self.handle, start, @intCast(c_uint, advances_out.len), load_flags.cast(), advances_out.ptr));
}
pub fn numCharmaps(self: Face) u32 {
return @intCast(u32, self.handle.*.num_charmaps);
}
pub fn charmaps(self: Face) []const CharMap {
return @ptrCast([*]const CharMap, self.handle.*.charmaps)[0..self.numCharmaps()];
}
pub fn bbox(self: Face) BBox {
return self.handle.*.bbox;
}
pub fn unitsPerEM(self: Face) u16 {
return self.handle.*.units_per_EM;
}
pub fn ascender(self: Face) i16 {
return self.handle.*.ascender;
}
pub fn descender(self: Face) i16 {
return self.handle.*.descender;
}
pub fn height(self: Face) i16 {
return self.handle.*.height;
}
pub fn maxAdvanceWidth(self: Face) i16 {
return self.handle.*.max_advance_width;
}
pub fn maxAdvanceHeight(self: Face) i16 {
return self.handle.*.max_advance_height;
}
pub fn underlinePosition(self: Face) i16 {
return self.handle.*.underline_position;
}
pub fn underlineThickness(self: Face) i16 {
return self.handle.*.underline_thickness;
}
pub fn glyph(self: Face) GlyphSlot {
return .{ .handle = self.handle.*.glyph };
}
pub fn size(self: Face) Size {
return Size{ .handle = self.handle.*.size };
}
pub fn charmap(self: Face) CharMap {
return self.handle.*.charmap.*;
}
pub fn hasHorizontal(self: Face) bool {
return c.FT_HAS_HORIZONTAL(self.handle);
}
pub fn hasVertical(self: Face) bool {
return c.FT_HAS_VERTICAL(self.handle);
}
pub fn hasKerning(self: Face) bool {
return c.FT_HAS_KERNING(self.handle);
}
pub fn hasFixedSizes(self: Face) bool {
return c.FT_HAS_FIXED_SIZES(self.handle);
}
pub fn hasGlyphNames(self: Face) bool {
return c.FT_HAS_GLYPH_NAMES(self.handle);
}
pub fn hasColor(self: Face) bool {
return c.FT_HAS_COLOR(self.handle);
}
pub fn isScalable(self: Face) bool {
return c.FT_IS_SCALABLE(self.handle);
}
pub fn isSfnt(self: Face) bool {
return c.FT_IS_SFNT(self.handle);
}
pub fn isFixedWidth(self: Face) bool {
return c.FT_IS_FIXED_WIDTH(self.handle);
}
pub fn isCidKeyed(self: Face) bool {
return c.FT_IS_CID_KEYED(self.handle);
}
pub fn isTricky(self: Face) bool {
return c.FT_IS_TRICKY(self.handle);
}

View file

@ -0,0 +1,105 @@
const c = @import("c");
const intToError = @import("error.zig").intToError;
const Error = @import("error.zig").Error;
const Glyph = @import("glyph.zig").Glyph;
const Library = @import("freetype.zig").Library;
const Face = @import("freetype.zig").Face;
const RenderMode = @import("freetype.zig").RenderMode;
const Matrix = @import("types.zig").Matrix;
const Outline = @import("image.zig").Outline;
const GlyphFormat = @import("image.zig").GlyphFormat;
const Vector = @import("image.zig").Vector;
const GlyphMetrics = @import("image.zig").GlyphMetrics;
const Bitmap = @import("image.zig").Bitmap;
const GlyphSlot = @This();
pub const SubGlyphInfo = struct {
index: i32,
flags: c_uint,
arg1: i32,
arg2: i32,
transform: Matrix,
};
handle: c.FT_GlyphSlot,
pub fn library(self: GlyphSlot) Library {
return .{ .handle = self.handle.*.library };
}
pub fn face(self: GlyphSlot) Face {
return .{ .handle = self.handle.*.face };
}
pub fn next(self: GlyphSlot) GlyphSlot {
return .{ .handle = self.handle.*.next };
}
pub fn glyphIndex(self: GlyphSlot) u32 {
return self.handle.*.glyph_index;
}
pub fn metrics(self: GlyphSlot) GlyphMetrics {
return self.handle.*.metrics;
}
pub fn linearHoriAdvance(self: GlyphSlot) i32 {
return @intCast(i32, self.handle.*.linearHoriAdvance);
}
pub fn linearVertAdvance(self: GlyphSlot) i32 {
return @intCast(i32, self.handle.*.linearVertAdvance);
}
pub fn advance(self: GlyphSlot) Vector {
return self.handle.*.advance;
}
pub fn format(self: GlyphSlot) GlyphFormat {
return @intToEnum(GlyphFormat, self.handle.*.format);
}
pub fn ownBitmap(self: GlyphSlot) Error!void {
try intToError(c.FT_GlyphSlot_Own_Bitmap(self.handle));
}
pub fn bitmap(self: GlyphSlot) Bitmap {
return .{ .handle = self.handle.*.bitmap };
}
pub fn bitmapLeft(self: GlyphSlot) i32 {
return self.handle.*.bitmap_left;
}
pub fn bitmapTop(self: GlyphSlot) i32 {
return self.handle.*.bitmap_top;
}
pub fn outline(self: GlyphSlot) ?Outline {
return if (self.format() == .outline) .{ .handle = &self.handle.*.outline } else null;
}
pub fn lsbDelta(self: GlyphSlot) i32 {
return @intCast(i32, self.handle.*.lsb_delta);
}
pub fn rsbDelta(self: GlyphSlot) i32 {
return @intCast(i32, self.handle.*.rsb_delta);
}
pub fn render(self: GlyphSlot, render_mode: RenderMode) Error!void {
return intToError(c.FT_Render_Glyph(self.handle, @enumToInt(render_mode)));
}
pub fn getSubGlyphInfo(self: GlyphSlot, sub_index: u32) Error!SubGlyphInfo {
var info: SubGlyphInfo = undefined;
try intToError(c.FT_Get_SubGlyph_Info(self.handle, sub_index, &info.index, &info.flags, &info.arg1, &info.arg2, &info.transform));
return info;
}
pub fn getGlyph(self: GlyphSlot) Error!Glyph {
var res: c.FT_Glyph = undefined;
try intToError(c.FT_Get_Glyph(self.handle, &res));
return Glyph{ .handle = res };
}

View file

@ -0,0 +1,82 @@
const std = @import("std");
const c = @import("c");
const intToError = @import("error.zig").intToError;
const Error = @import("error.zig").Error;
const Face = @import("freetype.zig").Face;
const Stroker = @import("stroke.zig").Stroker;
const OpenArgs = @import("freetype.zig").OpenArgs;
const Bitmap = @import("image.zig").Bitmap;
const Outline = @import("image.zig").Outline;
const RasterParams = @import("image.zig").RasterParams;
const LcdFilter = @import("lcdfilter.zig").LcdFilter;
const Library = @This();
pub const Version = struct {
major: i32,
minor: i32,
patch: i32,
};
handle: c.FT_Library,
pub fn init() Error!Library {
var lib = Library{ .handle = undefined };
try intToError(c.FT_Init_FreeType(&lib.handle));
return lib;
}
pub fn deinit(self: Library) void {
_ = c.FT_Done_FreeType(self.handle);
}
pub fn createFace(self: Library, path: []const u8, face_index: i32) Error!Face {
return self.openFace(.{
.flags = .{ .path = true },
.data = .{ .path = path },
}, face_index);
}
pub fn createFaceMemory(self: Library, bytes: []const u8, face_index: i32) Error!Face {
return self.openFace(.{
.flags = .{ .memory = true },
.data = .{ .memory = bytes },
}, face_index);
}
pub fn openFace(self: Library, args: OpenArgs, face_index: i32) Error!Face {
var f: c.FT_Face = undefined;
try intToError(c.FT_Open_Face(self.handle, &args.cast(), face_index, &f));
return Face{ .handle = f };
}
pub fn version(self: Library) Version {
var v: Version = undefined;
c.FT_Library_Version(
self.handle,
&v.major,
&v.minor,
&v.patch,
);
return v;
}
pub fn createStroker(self: Library) Error!Stroker {
var s: c.FT_Stroker = undefined;
try intToError(c.FT_Stroker_New(self.handle, &s));
return Stroker{ .handle = s };
}
pub fn createOutlineFromBitmap(self: Library, bitmap: Bitmap) Error!Outline {
var o: Outline = undefined;
try intToError(c.FT_Outline_Get_Bitmap(self.handle, o.handle, &bitmap.handle));
return o;
}
pub fn renderOutline(self: Library, outline: Outline, params: *RasterParams) Error!void {
try intToError(c.FT_Outline_Render(self.handle, outline.handle, params));
}
pub fn setLcdFilter(self: Library, lcd_filter: LcdFilter) Error!void {
return intToError(c.FT_Library_SetLcdFilter(self.handle, @enumToInt(lcd_filter)));
}

11
libs/freetype/src/c.zig Normal file
View file

@ -0,0 +1,11 @@
pub usingnamespace @cImport({
@cInclude("hb-ft.h");
@cInclude("freetype/ftadvanc.h");
@cInclude("freetype/ftbbox.h");
@cInclude("freetype/ftbitmap.h");
@cInclude("freetype/ftcolor.h");
@cInclude("freetype/ftlcdfil.h");
@cInclude("freetype/ftsizes.h");
@cInclude("freetype/ftstroke.h");
@cInclude("freetype/fttrigon.h");
});

176
libs/freetype/src/color.zig Normal file
View file

@ -0,0 +1,176 @@
const utils = @import("utils");
const c = @import("c");
const Face = @import("freetype.zig").Face;
pub const Color = c.FT_Color;
pub const LayerIterator = c.FT_LayerIterator;
pub const ColorStopIterator = c.FT_ColorStopIterator;
pub const ColorIndex = c.FT_ColorIndex;
pub const ColorStop = c.FT_ColorStop;
pub const ColorLine = c.FT_ColorLine;
pub const Affine23 = c.FT_Affine23;
pub const OpaquePaint = c.FT_OpaquePaint;
pub const PaintColrLayers = c.FT_PaintColrLayers;
pub const PaintSolid = c.FT_PaintSolid;
pub const PaintLinearGradient = c.FT_PaintLinearGradient;
pub const PaintRadialGradient = c.FT_PaintRadialGradient;
pub const PaintSweepGradient = c.FT_PaintSweepGradient;
pub const PaintGlyph = c.FT_PaintGlyph;
pub const PaintColrGlyph = c.FT_PaintColrGlyph;
pub const PaintTransform = c.FT_PaintTransform;
pub const PaintTranslate = c.FT_PaintTranslate;
pub const PaintScale = c.FT_PaintScale;
pub const PaintRotate = c.FT_PaintRotate;
pub const PaintSkew = c.FT_PaintSkew;
pub const PaintComposite = c.FT_PaintComposite;
pub const ClipBox = c.FT_ClipBox;
pub const RootTransform = enum(u1) {
include_root_transform = c.FT_COLOR_INCLUDE_ROOT_TRANSFORM,
no_root_transform = c.FT_COLOR_NO_ROOT_TRANSFORM,
};
pub const PaintExtend = enum(u2) {
pad = c.FT_COLR_PAINT_EXTEND_PAD,
repeat = c.FT_COLR_PAINT_EXTEND_REPEAT,
reflect = c.FT_COLR_PAINT_EXTEND_REFLECT,
};
pub const PaintFormat = enum(u8) {
color_layers = c.FT_COLR_PAINTFORMAT_COLR_LAYERS,
solid = c.FT_COLR_PAINTFORMAT_SOLID,
linear_gradient = c.FT_COLR_PAINTFORMAT_LINEAR_GRADIENT,
radial_gradient = c.FT_COLR_PAINTFORMAT_RADIAL_GRADIENT,
sweep_gradient = c.FT_COLR_PAINTFORMAT_SWEEP_GRADIENT,
glyph = c.FT_COLR_PAINTFORMAT_GLYPH,
color_glyph = c.FT_COLR_PAINTFORMAT_COLR_GLYPH,
transform = c.FT_COLR_PAINTFORMAT_TRANSFORM,
translate = c.FT_COLR_PAINTFORMAT_TRANSLATE,
scale = c.FT_COLR_PAINTFORMAT_SCALE,
rotate = c.FT_COLR_PAINTFORMAT_ROTATE,
skew = c.FT_COLR_PAINTFORMAT_SKEW,
composite = c.FT_COLR_PAINTFORMAT_COMPOSITE,
};
pub const CompositeMode = enum(u5) {
clear = c.FT_COLR_COMPOSITE_CLEAR,
src = c.FT_COLR_COMPOSITE_SRC,
dest = c.FT_COLR_COMPOSITE_DEST,
src_over = c.FT_COLR_COMPOSITE_SRC_OVER,
dest_over = c.FT_COLR_COMPOSITE_DEST_OVER,
src_in = c.FT_COLR_COMPOSITE_SRC_IN,
dest_in = c.FT_COLR_COMPOSITE_DEST_IN,
src_out = c.FT_COLR_COMPOSITE_SRC_OUT,
dest_out = c.FT_COLR_COMPOSITE_DEST_OUT,
src_atop = c.FT_COLR_COMPOSITE_SRC_ATOP,
dest_atop = c.FT_COLR_COMPOSITE_DEST_ATOP,
xor = c.FT_COLR_COMPOSITE_XOR,
plus = c.FT_COLR_COMPOSITE_PLUS,
screen = c.FT_COLR_COMPOSITE_SCREEN,
overlay = c.FT_COLR_COMPOSITE_OVERLAY,
darken = c.FT_COLR_COMPOSITE_DARKEN,
lighten = c.FT_COLR_COMPOSITE_LIGHTEN,
color_dodge = c.FT_COLR_COMPOSITE_COLOR_DODGE,
color_burn = c.FT_COLR_COMPOSITE_COLOR_BURN,
hard_light = c.FT_COLR_COMPOSITE_HARD_LIGHT,
soft_light = c.FT_COLR_COMPOSITE_SOFT_LIGHT,
difference = c.FT_COLR_COMPOSITE_DIFFERENCE,
exclusion = c.FT_COLR_COMPOSITE_EXCLUSION,
multiply = c.FT_COLR_COMPOSITE_MULTIPLY,
hsl_hue = c.FT_COLR_COMPOSITE_HSL_HUE,
hsl_saturation = c.FT_COLR_COMPOSITE_HSL_SATURATION,
hsl_color = c.FT_COLR_COMPOSITE_HSL_COLOR,
hsl_luminosity = c.FT_COLR_COMPOSITE_HSL_LUMINOSITY,
};
pub const Paint = union(PaintFormat) {
color_layers: PaintColrLayers,
glyph: PaintGlyph,
solid: PaintSolid,
linear_gradient: PaintLinearGradient,
radial_gradient: PaintRadialGradient,
sweep_gradient: PaintSweepGradient,
transform: PaintTransform,
translate: PaintTranslate,
scale: PaintScale,
rotate: PaintRotate,
skew: PaintSkew,
composite: PaintComposite,
color_glyph: PaintColrGlyph,
};
pub const PaletteData = struct {
handle: c.FT_Palette_Data,
pub fn numPalettes(self: PaletteData) u16 {
return self.handle.num_palettes;
}
pub fn paletteNameIDs(self: PaletteData) ?[]const u16 {
return self.handle.palette_name_ids[0..self.numPalettes()];
}
pub fn paletteFlags(self: PaletteData) ?[]const u16 {
return self.handle.palette_flags[0..self.numPalettes()];
}
pub fn paletteFlag(self: PaletteData, index: u32) PaletteFlags {
return PaletteFlags.from(self.handle.palette_flags[index]);
}
pub fn numPaletteEntries(self: PaletteData) u16 {
return self.handle.num_palette_entries;
}
pub fn paletteEntryNameIDs(self: PaletteData) ?[]const u16 {
return self.handle.palette_entry_name_ids[0..self.numPaletteEntries()];
}
};
pub const PaletteFlags = packed struct {
for_light_background: bool = false,
for_dark_background: bool = false,
pub const Flag = enum(u2) {
for_light_background = c.FT_PALETTE_FOR_LIGHT_BACKGROUND,
for_dark_background = c.FT_PALETTE_FOR_DARK_BACKGROUND,
};
pub fn from(bits: c_int) PaletteFlags {
return utils.bitFieldsToStruct(PaletteFlags, Flag, bits);
}
pub fn to(flags: PaletteFlags) c_int {
return utils.structToBitFields(c_int, Flag, flags);
}
};
pub const GlyphLayersIterator = struct {
face: Face,
glyph_index: u32,
layer_glyph_index: u32,
layer_color_index: u32,
iterator: LayerIterator,
pub fn init(face: Face, glyph_index: u32) GlyphLayersIterator {
var iterator: LayerIterator = undefined;
iterator.p = null;
return .{
.face = face,
.glyph_index = glyph_index,
.layer_glyph_index = 0,
.layer_color_index = 0,
.iterator = iterator,
};
}
pub fn next(self: *GlyphLayersIterator) bool {
return if (c.FT_Get_Color_Glyph_Layer(
self.face.handle,
self.glyph_index,
&self.layer_glyph_index,
&self.layer_color_index,
&self.iterator,
) == 0) false else true;
}
};

View file

@ -0,0 +1,71 @@
const _c = @import("c");
const intToError = @import("error.zig").intToError;
const Error = @import("error.zig").Error;
const Vector = @import("image.zig").Vector;
const Matrix = @import("types.zig").Matrix;
pub const angel_pi = _c.FT_ANGLE_PI;
pub const angel_2pi = _c.FT_ANGLE_2PI;
pub const angel_pi2 = _c.FT_ANGLE_PI2;
pub const angel_pi4 = _c.FT_ANGLE_PI4;
pub fn mulDiv(a: i32, b: i32, c: i32) i32 {
return @intCast(i32, _c.FT_MulDiv(a, b, c));
}
pub fn mulFix(a: i32, b: i32) i32 {
return @intCast(i32, _c.FT_MulFix(a, b));
}
pub fn divFix(a: i32, b: i32) i32 {
return @intCast(i32, _c.FT_DivFix(a, b));
}
pub fn roundFix(a: i32) i32 {
return @intCast(i32, _c.FT_RoundFix(a));
}
pub fn ceilFix(a: i32) i32 {
return @intCast(i32, _c.FT_CeilFix(a));
}
pub fn floorFix(a: i32) i32 {
return @intCast(i32, _c.FT_FloorFix(a));
}
pub fn vectorTransform(vec: *Vector, matrix: Matrix) void {
_c.FT_Vector_Transform(vec, &matrix);
}
pub fn matrixMul(a: Matrix, b: *Matrix) void {
_c.FT_Matrix_Multiply(&a, b);
}
pub fn matrixInvert(m: *Matrix) Error!void {
try intToError(_c.FT_Matrix_Invert(m));
}
pub fn angleDiff(a: i32, b: i32) i32 {
return @intCast(i32, _c.FT_Angle_Diff(a, b));
}
pub fn vectorUnit(vec: *Vector, angle: i32) void {
_c.FT_Vector_Unit(vec, angle);
}
pub fn vectorRotate(vec: *Vector, angle: i32) void {
_c.FT_Vector_Rotate(vec, angle);
}
pub fn vectorLength(vec: *Vector) i32 {
return @intCast(i32, _c.FT_Vector_Length(vec));
}
pub fn vectorPolarize(vec: *Vector, length: *i32, angle: *i32) void {
_c.FT_Vector_Polarize(vec, &@intCast(c_long, length.*), &@intCast(c_long, angle.*));
}
pub fn vectorFromPolar(vec: *Vector, length: i32, angle: i32) void {
_c.FT_Vector_From_Polar(vec, length, angle);
}

290
libs/freetype/src/error.zig Normal file
View file

@ -0,0 +1,290 @@
const c = @import("c");
pub const Error = error{
CannotOpenResource,
UnknownFileFormat,
InvalidFileFormat,
InvalidVersion,
LowerModuleVersion,
InvalidArgument,
UnimplementedFeature,
InvalidTable,
InvalidOffset,
ArrayTooLarge,
MissingModule,
MissingProperty,
InvalidGlyphIndex,
InvalidCharacterCode,
InvalidGlyphFormat,
CannotRenderGlyph,
InvalidOutline,
InvalidComposite,
TooManyHints,
InvalidPixelSize,
InvalidHandle,
InvalidLibraryHandle,
InvalidDriverHandle,
InvalidFaceHandle,
InvalidSizeHandle,
InvalidSlotHandle,
InvalidCharMapHandle,
InvalidCacheHandle,
InvalidStreamHandle,
TooManyDrivers,
TooManyExtensions,
OutOfMemory,
UnlistedObject,
CannotOpenStream,
InvalidStreamSeek,
InvalidStreamSkip,
InvalidStreamRead,
InvalidStreamOperation,
InvalidFrameOperation,
NestedFrameAccess,
InvalidFrameRead,
RasterUninitialized,
RasterCorrupted,
RasterOverflow,
RasterNegativeHeight,
TooManyCaches,
InvalidOpcode,
TooFewArguments,
StackOverflow,
CodeOverflow,
BadArgument,
DivideByZero,
InvalidReference,
DebugOpCode,
ENDFInExecStream,
NestedDEFS,
InvalidCodeRange,
ExecutionTooLong,
TooManyFunctionDefs,
TooManyInstructionDefs,
TableMissing,
HorizHeaderMissing,
LocationsMissing,
NameTableMissing,
CMapTableMissing,
HmtxTableMissing,
PostTableMissing,
InvalidHorizMetrics,
InvalidCharMapFormat,
InvalidPPem,
InvalidVertMetrics,
CouldNotFindContext,
InvalidPostTableFormat,
InvalidPostTable,
Syntax,
StackUnderflow,
Ignore,
NoUnicodeGlyphName,
MissingStartfontField,
MissingFontField,
MissingSizeField,
MissingFontboundingboxField,
MissingCharsField,
MissingStartcharField,
MissingEncodingField,
MissingBbxField,
BbxTooBig,
CorruptedFontHeader,
CorruptedFontGlyphs,
};
pub fn intToError(err: c_int) Error!void {
return switch (err) {
c.FT_Err_Ok => {},
c.FT_Err_Cannot_Open_Resource => Error.CannotOpenResource,
c.FT_Err_Unknown_File_Format => Error.UnknownFileFormat,
c.FT_Err_Invalid_File_Format => Error.InvalidFileFormat,
c.FT_Err_Invalid_Version => Error.InvalidVersion,
c.FT_Err_Lower_Module_Version => Error.LowerModuleVersion,
c.FT_Err_Invalid_Argument => Error.InvalidArgument,
c.FT_Err_Unimplemented_Feature => Error.UnimplementedFeature,
c.FT_Err_Invalid_Table => Error.InvalidTable,
c.FT_Err_Invalid_Offset => Error.InvalidOffset,
c.FT_Err_Array_Too_Large => Error.ArrayTooLarge,
c.FT_Err_Missing_Module => Error.MissingModule,
c.FT_Err_Missing_Property => Error.MissingProperty,
c.FT_Err_Invalid_Glyph_Index => Error.InvalidGlyphIndex,
c.FT_Err_Invalid_Character_Code => Error.InvalidCharacterCode,
c.FT_Err_Invalid_Glyph_Format => Error.InvalidGlyphFormat,
c.FT_Err_Cannot_Render_Glyph => Error.CannotRenderGlyph,
c.FT_Err_Invalid_Outline => Error.InvalidOutline,
c.FT_Err_Invalid_Composite => Error.InvalidComposite,
c.FT_Err_Too_Many_Hints => Error.TooManyHints,
c.FT_Err_Invalid_Pixel_Size => Error.InvalidPixelSize,
c.FT_Err_Invalid_Handle => Error.InvalidHandle,
c.FT_Err_Invalid_Library_Handle => Error.InvalidLibraryHandle,
c.FT_Err_Invalid_Driver_Handle => Error.InvalidDriverHandle,
c.FT_Err_Invalid_Face_Handle => Error.InvalidFaceHandle,
c.FT_Err_Invalid_Size_Handle => Error.InvalidSizeHandle,
c.FT_Err_Invalid_Slot_Handle => Error.InvalidSlotHandle,
c.FT_Err_Invalid_CharMap_Handle => Error.InvalidCharMapHandle,
c.FT_Err_Invalid_Cache_Handle => Error.InvalidCacheHandle,
c.FT_Err_Invalid_Stream_Handle => Error.InvalidStreamHandle,
c.FT_Err_Too_Many_Drivers => Error.TooManyDrivers,
c.FT_Err_Too_Many_Extensions => Error.TooManyExtensions,
c.FT_Err_Out_Of_Memory => Error.OutOfMemory,
c.FT_Err_Unlisted_Object => Error.UnlistedObject,
c.FT_Err_Cannot_Open_Stream => Error.CannotOpenStream,
c.FT_Err_Invalid_Stream_Seek => Error.InvalidStreamSeek,
c.FT_Err_Invalid_Stream_Skip => Error.InvalidStreamSkip,
c.FT_Err_Invalid_Stream_Read => Error.InvalidStreamRead,
c.FT_Err_Invalid_Stream_Operation => Error.InvalidStreamOperation,
c.FT_Err_Invalid_Frame_Operation => Error.InvalidFrameOperation,
c.FT_Err_Nested_Frame_Access => Error.NestedFrameAccess,
c.FT_Err_Invalid_Frame_Read => Error.InvalidFrameRead,
c.FT_Err_Raster_Uninitialized => Error.RasterUninitialized,
c.FT_Err_Raster_Corrupted => Error.RasterCorrupted,
c.FT_Err_Raster_Overflow => Error.RasterOverflow,
c.FT_Err_Raster_Negative_Height => Error.RasterNegativeHeight,
c.FT_Err_Too_Many_Caches => Error.TooManyCaches,
c.FT_Err_Invalid_Opcode => Error.InvalidOpcode,
c.FT_Err_Too_Few_Arguments => Error.TooFewArguments,
c.FT_Err_Stack_Overflow => Error.StackOverflow,
c.FT_Err_Code_Overflow => Error.CodeOverflow,
c.FT_Err_Bad_Argument => Error.BadArgument,
c.FT_Err_Divide_By_Zero => Error.DivideByZero,
c.FT_Err_Invalid_Reference => Error.InvalidReference,
c.FT_Err_Debug_OpCode => Error.DebugOpCode,
c.FT_Err_ENDF_In_Exec_Stream => Error.ENDFInExecStream,
c.FT_Err_Nested_DEFS => Error.NestedDEFS,
c.FT_Err_Invalid_CodeRange => Error.InvalidCodeRange,
c.FT_Err_Execution_Too_Long => Error.ExecutionTooLong,
c.FT_Err_Too_Many_Function_Defs => Error.TooManyFunctionDefs,
c.FT_Err_Too_Many_Instruction_Defs => Error.TooManyInstructionDefs,
c.FT_Err_Table_Missing => Error.TableMissing,
c.FT_Err_Horiz_Header_Missing => Error.HorizHeaderMissing,
c.FT_Err_Locations_Missing => Error.LocationsMissing,
c.FT_Err_Name_Table_Missing => Error.NameTableMissing,
c.FT_Err_CMap_Table_Missing => Error.CMapTableMissing,
c.FT_Err_Hmtx_Table_Missing => Error.HmtxTableMissing,
c.FT_Err_Post_Table_Missing => Error.PostTableMissing,
c.FT_Err_Invalid_Horiz_Metrics => Error.InvalidHorizMetrics,
c.FT_Err_Invalid_CharMap_Format => Error.InvalidCharMapFormat,
c.FT_Err_Invalid_PPem => Error.InvalidPPem,
c.FT_Err_Invalid_Vert_Metrics => Error.InvalidVertMetrics,
c.FT_Err_Could_Not_Find_Context => Error.CouldNotFindContext,
c.FT_Err_Invalid_Post_Table_Format => Error.InvalidPostTableFormat,
c.FT_Err_Invalid_Post_Table => Error.InvalidPostTable,
c.FT_Err_Syntax_Error => Error.Syntax,
c.FT_Err_Stack_Underflow => Error.StackUnderflow,
c.FT_Err_Ignore => Error.Ignore,
c.FT_Err_No_Unicode_Glyph_Name => Error.NoUnicodeGlyphName,
c.FT_Err_Missing_Startfont_Field => Error.MissingStartfontField,
c.FT_Err_Missing_Font_Field => Error.MissingFontField,
c.FT_Err_Missing_Size_Field => Error.MissingSizeField,
c.FT_Err_Missing_Fontboundingbox_Field => Error.MissingFontboundingboxField,
c.FT_Err_Missing_Chars_Field => Error.MissingCharsField,
c.FT_Err_Missing_Startchar_Field => Error.MissingStartcharField,
c.FT_Err_Missing_Encoding_Field => Error.MissingEncodingField,
c.FT_Err_Missing_Bbx_Field => Error.MissingBbxField,
c.FT_Err_Bbx_Too_Big => Error.BbxTooBig,
c.FT_Err_Corrupted_Font_Header => Error.CorruptedFontHeader,
c.FT_Err_Corrupted_Font_Glyphs => Error.CorruptedFontGlyphs,
else => unreachable,
};
}
pub fn errorToInt(err: Error) c_int {
return switch (err) {
Error.CannotOpenResource => c.FT_Err_Cannot_Open_Resource,
Error.UnknownFileFormat => c.FT_Err_Unknown_File_Format,
Error.InvalidFileFormat => c.FT_Err_Invalid_File_Format,
Error.InvalidVersion => c.FT_Err_Invalid_Version,
Error.LowerModuleVersion => c.FT_Err_Lower_Module_Version,
Error.InvalidArgument => c.FT_Err_Invalid_Argument,
Error.UnimplementedFeature => c.FT_Err_Unimplemented_Feature,
Error.InvalidTable => c.FT_Err_Invalid_Table,
Error.InvalidOffset => c.FT_Err_Invalid_Offset,
Error.ArrayTooLarge => c.FT_Err_Array_Too_Large,
Error.MissingModule => c.FT_Err_Missing_Module,
Error.MissingProperty => c.FT_Err_Missing_Property,
Error.InvalidGlyphIndex => c.FT_Err_Invalid_Glyph_Index,
Error.InvalidCharacterCode => c.FT_Err_Invalid_Character_Code,
Error.InvalidGlyphFormat => c.FT_Err_Invalid_Glyph_Format,
Error.CannotRenderGlyph => c.FT_Err_Cannot_Render_Glyph,
Error.InvalidOutline => c.FT_Err_Invalid_Outline,
Error.InvalidComposite => c.FT_Err_Invalid_Composite,
Error.TooManyHints => c.FT_Err_Too_Many_Hints,
Error.InvalidPixelSize => c.FT_Err_Invalid_Pixel_Size,
Error.InvalidHandle => c.FT_Err_Invalid_Handle,
Error.InvalidLibraryHandle => c.FT_Err_Invalid_Library_Handle,
Error.InvalidDriverHandle => c.FT_Err_Invalid_Driver_Handle,
Error.InvalidFaceHandle => c.FT_Err_Invalid_Face_Handle,
Error.InvalidSizeHandle => c.FT_Err_Invalid_Size_Handle,
Error.InvalidSlotHandle => c.FT_Err_Invalid_Slot_Handle,
Error.InvalidCharMapHandle => c.FT_Err_Invalid_CharMap_Handle,
Error.InvalidCacheHandle => c.FT_Err_Invalid_Cache_Handle,
Error.InvalidStreamHandle => c.FT_Err_Invalid_Stream_Handle,
Error.TooManyDrivers => c.FT_Err_Too_Many_Drivers,
Error.TooManyExtensions => c.FT_Err_Too_Many_Extensions,
Error.OutOfMemory => c.FT_Err_Out_Of_Memory,
Error.UnlistedObject => c.FT_Err_Unlisted_Object,
Error.CannotOpenStream => c.FT_Err_Cannot_Open_Stream,
Error.InvalidStreamSeek => c.FT_Err_Invalid_Stream_Seek,
Error.InvalidStreamSkip => c.FT_Err_Invalid_Stream_Skip,
Error.InvalidStreamRead => c.FT_Err_Invalid_Stream_Read,
Error.InvalidStreamOperation => c.FT_Err_Invalid_Stream_Operation,
Error.InvalidFrameOperation => c.FT_Err_Invalid_Frame_Operation,
Error.NestedFrameAccess => c.FT_Err_Nested_Frame_Access,
Error.InvalidFrameRead => c.FT_Err_Invalid_Frame_Read,
Error.RasterUninitialized => c.FT_Err_Raster_Uninitialized,
Error.RasterCorrupted => c.FT_Err_Raster_Corrupted,
Error.RasterOverflow => c.FT_Err_Raster_Overflow,
Error.RasterNegativeHeight => c.FT_Err_Raster_Negative_Height,
Error.TooManyCaches => c.FT_Err_Too_Many_Caches,
Error.InvalidOpcode => c.FT_Err_Invalid_Opcode,
Error.TooFewArguments => c.FT_Err_Too_Few_Arguments,
Error.StackOverflow => c.FT_Err_Stack_Overflow,
Error.CodeOverflow => c.FT_Err_Code_Overflow,
Error.BadArgument => c.FT_Err_Bad_Argument,
Error.DivideByZero => c.FT_Err_Divide_By_Zero,
Error.InvalidReference => c.FT_Err_Invalid_Reference,
Error.DebugOpCode => c.FT_Err_Debug_OpCode,
Error.ENDFInExecStream => c.FT_Err_ENDF_In_Exec_Stream,
Error.NestedDEFS => c.FT_Err_Nested_DEFS,
Error.InvalidCodeRange => c.FT_Err_Invalid_CodeRange,
Error.ExecutionTooLong => c.FT_Err_Execution_Too_Long,
Error.TooManyFunctionDefs => c.FT_Err_Too_Many_Function_Defs,
Error.TooManyInstructionDefs => c.FT_Err_Too_Many_Instruction_Defs,
Error.TableMissing => c.FT_Err_Table_Missing,
Error.HorizHeaderMissing => c.FT_Err_Horiz_Header_Missing,
Error.LocationsMissing => c.FT_Err_Locations_Missing,
Error.NameTableMissing => c.FT_Err_Name_Table_Missing,
Error.CMapTableMissing => c.FT_Err_CMap_Table_Missing,
Error.HmtxTableMissing => c.FT_Err_Hmtx_Table_Missing,
Error.PostTableMissing => c.FT_Err_Post_Table_Missing,
Error.InvalidHorizMetrics => c.FT_Err_Invalid_Horiz_Metrics,
Error.InvalidCharMapFormat => c.FT_Err_Invalid_CharMap_Format,
Error.InvalidPPem => c.FT_Err_Invalid_PPem,
Error.InvalidVertMetrics => c.FT_Err_Invalid_Vert_Metrics,
Error.CouldNotFindContext => c.FT_Err_Could_Not_Find_Context,
Error.InvalidPostTableFormat => c.FT_Err_Invalid_Post_Table_Format,
Error.InvalidPostTable => c.FT_Err_Invalid_Post_Table,
Error.Syntax => c.FT_Err_Syntax_Error,
Error.StackUnderflow => c.FT_Err_Stack_Underflow,
Error.Ignore => c.FT_Err_Ignore,
Error.NoUnicodeGlyphName => c.FT_Err_No_Unicode_Glyph_Name,
Error.MissingStartfontField => c.FT_Err_Missing_Startfont_Field,
Error.MissingFontField => c.FT_Err_Missing_Font_Field,
Error.MissingSizeField => c.FT_Err_Missing_Size_Field,
Error.MissingFontboundingboxField => c.FT_Err_Missing_Fontboundingbox_Field,
Error.MissingCharsField => c.FT_Err_Missing_Chars_Field,
Error.MissingStartcharField => c.FT_Err_Missing_Startchar_Field,
Error.MissingEncodingField => c.FT_Err_Missing_Encoding_Field,
Error.MissingBbxField => c.FT_Err_Missing_Bbx_Field,
Error.BbxTooBig => c.FT_Err_Bbx_Too_Big,
Error.CorruptedFontHeader => c.FT_Err_Corrupted_Font_Header,
Error.CorruptedFontGlyphs => c.FT_Err_Corrupted_Font_Glyphs,
};
}
test "error convertion" {
const expectError = @import("std").testing.expectError;
try intToError(c.FT_Err_Ok);
try expectError(Error.OutOfMemory, intToError(c.FT_Err_Out_Of_Memory));
}

View file

@ -0,0 +1,289 @@
const std = @import("std");
const utils = @import("utils");
const c = @import("c");
const intToError = @import("error.zig").intToError;
const Error = @import("error.zig").Error;
const Generic = @import("types.zig").Generic;
pub const Library = @import("Library.zig");
pub const Face = @import("Face.zig");
pub const GlyphSlot = @import("GlyphSlot.zig");
pub const SizeRequest = c.FT_Size_RequestRec;
pub const BitmapSize = c.FT_Bitmap_Size;
pub const CharMap = c.FT_CharMapRec;
pub const SizeMetrics = c.FT_Size_Metrics;
pub const KerningMode = enum(u2) {
default = c.FT_KERNING_DEFAULT,
unfitted = c.FT_KERNING_UNFITTED,
unscaled = c.FT_KERNING_UNSCALED,
};
pub const RenderMode = enum(u3) {
normal = c.FT_RENDER_MODE_NORMAL,
light = c.FT_RENDER_MODE_LIGHT,
mono = c.FT_RENDER_MODE_MONO,
lcd = c.FT_RENDER_MODE_LCD,
lcd_v = c.FT_RENDER_MODE_LCD_V,
sdf = c.FT_RENDER_MODE_SDF,
};
pub const SizeRequestType = enum(u3) {
nominal = c.FT_SIZE_REQUEST_TYPE_NOMINAL,
real_dim = c.FT_SIZE_REQUEST_TYPE_REAL_DIM,
bbox = c.FT_SIZE_REQUEST_TYPE_BBOX,
cell = c.FT_SIZE_REQUEST_TYPE_CELL,
scales = c.FT_SIZE_REQUEST_TYPE_SCALES,
max = c.FT_SIZE_REQUEST_TYPE_MAX,
};
pub const Encoding = enum(u31) {
none = c.FT_ENCODING_NONE,
ms_symbol = c.FT_ENCODING_MS_SYMBOL,
unicode = c.FT_ENCODING_UNICODE,
sjis = c.FT_ENCODING_SJIS,
prc = c.FT_ENCODING_PRC,
big5 = c.FT_ENCODING_BIG5,
wansung = c.FT_ENCODING_WANSUNG,
johab = c.FT_ENCODING_JOHAB,
adobe_standard = c.FT_ENCODING_ADOBE_STANDARD,
adobe_expert = c.FT_ENCODING_ADOBE_EXPERT,
adobe_custom = c.FT_ENCODING_ADOBE_CUSTOM,
adobe_latin_1 = c.FT_ENCODING_ADOBE_LATIN_1,
old_latin_2 = c.FT_ENCODING_OLD_LATIN_2,
apple_roman = c.FT_ENCODING_APPLE_ROMAN,
};
pub const Size = struct {
handle: c.FT_Size,
pub fn face(self: Size) Face {
return Face{ .handle = self.handle.*.face };
}
pub fn generic(self: Size) Generic {
return self.handle.*.generic;
}
pub fn metrics(self: Size) SizeMetrics {
return self.handle.*.metrics;
}
pub fn activate(self: Size) Error!void {
try intToError(c.FT_Activate_Size(self.handle));
}
pub fn deinit(self: Size) void {
intToError(c.FT_Done_Size(self.handle)) catch |err| {
std.log.err("mach/freetype: Failed to destroy Size: {}", .{err});
};
}
};
pub const LoadFlags = packed struct {
no_scale: bool = false,
no_hinting: bool = false,
render: bool = false,
no_bitmap: bool = false,
vertical_layout: bool = false,
force_autohint: bool = false,
crop_bitmap: bool = false,
pedantic: bool = false,
ignore_global_advance_with: bool = false,
no_recurse: bool = false,
ignore_transform: bool = false,
monochrome: bool = false,
linear_design: bool = false,
no_autohint: bool = false,
target_normal: bool = false,
target_light: bool = false,
target_mono: bool = false,
target_lcd: bool = false,
target_lcd_v: bool = false,
color: bool = false,
pub const Flag = enum(u21) {
no_scale = c.FT_LOAD_NO_SCALE,
no_hinting = c.FT_LOAD_NO_HINTING,
render = c.FT_LOAD_RENDER,
no_bitmap = c.FT_LOAD_NO_BITMAP,
vertical_layout = c.FT_LOAD_VERTICAL_LAYOUT,
force_autohint = c.FT_LOAD_FORCE_AUTOHINT,
crop_bitmap = c.FT_LOAD_CROP_BITMAP,
pedantic = c.FT_LOAD_PEDANTIC,
ignore_global_advance_with = c.FT_LOAD_IGNORE_GLOBAL_ADVANCE_WIDTH,
no_recurse = c.FT_LOAD_NO_RECURSE,
ignore_transform = c.FT_LOAD_IGNORE_TRANSFORM,
monochrome = c.FT_LOAD_MONOCHROME,
linear_design = c.FT_LOAD_LINEAR_DESIGN,
no_autohint = c.FT_LOAD_NO_AUTOHINT,
target_normal = c.FT_LOAD_TARGET_NORMAL,
target_light = c.FT_LOAD_TARGET_LIGHT,
target_mono = c.FT_LOAD_TARGET_MONO,
target_lcd = c.FT_LOAD_TARGET_LCD,
target_lcd_v = c.FT_LOAD_TARGET_LCD_V,
color = c.FT_LOAD_COLOR,
};
pub fn from(bits: c_int) LoadFlags {
return utils.bitFieldsToStruct(LoadFlags, Flag, bits);
}
pub fn cast(self: LoadFlags) c_int {
return utils.structToBitFields(c_int, Flag, self);
}
};
pub const FaceFlags = packed struct {
scalable: bool = false,
fixed_sizes: bool = false,
fixed_width: bool = false,
sfnt: bool = false,
horizontal: bool = false,
vertical: bool = false,
kerning: bool = false,
fast_glyphs: bool = false,
multiple_masters: bool = false,
glyph_names: bool = false,
external_stream: bool = false,
hinter: bool = false,
cid_keyed: bool = false,
tricky: bool = false,
color: bool = false,
variation: bool = false,
svg: bool = false,
sbix: bool = false,
sbix_overlay: bool = false,
pub const Flag = enum(u19) {
scalable = c.FT_FACE_FLAG_SCALABLE,
fixed_sizes = c.FT_FACE_FLAG_FIXED_SIZES,
fixed_width = c.FT_FACE_FLAG_FIXED_WIDTH,
sfnt = c.FT_FACE_FLAG_SFNT,
horizontal = c.FT_FACE_FLAG_HORIZONTAL,
vertical = c.FT_FACE_FLAG_VERTICAL,
kerning = c.FT_FACE_FLAG_KERNING,
fast_glyphs = c.FT_FACE_FLAG_FAST_GLYPHS,
multiple_masters = c.FT_FACE_FLAG_MULTIPLE_MASTERS,
glyph_names = c.FT_FACE_FLAG_GLYPH_NAMES,
external_stream = c.FT_FACE_FLAG_EXTERNAL_STREAM,
hinter = c.FT_FACE_FLAG_HINTER,
cid_keyed = c.FT_FACE_FLAG_CID_KEYED,
tricky = c.FT_FACE_FLAG_TRICKY,
color = c.FT_FACE_FLAG_COLOR,
variation = c.FT_FACE_FLAG_VARIATION,
svg = c.FT_FACE_FLAG_SVG,
sbix = c.FT_FACE_FLAG_SBIX,
sbix_overlay = c.FT_FACE_FLAG_SBIX_OVERLAY,
};
pub fn from(bits: c_long) FaceFlags {
return utils.bitFieldsToStruct(FaceFlags, Flag, bits);
}
pub fn cast(self: FaceFlags) c_long {
return utils.structToBitFields(c_long, Flag, self);
}
};
pub const FSType = packed struct {
installable_embedding: bool = false,
restriced_license_embedding: bool = false,
preview_and_print_embedding: bool = false,
editable_embedding: bool = false,
no_subsetting: bool = false,
bitmap_embedding_only: bool = false,
pub const Flag = enum(u10) {
installable_embedding = c.FT_FSTYPE_INSTALLABLE_EMBEDDING,
restriced_license_embedding = c.FT_FSTYPE_RESTRICTED_LICENSE_EMBEDDING,
preview_and_print_embedding = c.FT_FSTYPE_PREVIEW_AND_PRINT_EMBEDDING,
editable_embedding = c.FT_FSTYPE_EDITABLE_EMBEDDING,
no_subsetting = c.FT_FSTYPE_NO_SUBSETTING,
bitmap_embedding_only = c.FT_FSTYPE_BITMAP_EMBEDDING_ONLY,
};
pub fn from(bits: c_int) FSType {
return utils.bitFieldsToStruct(FSType, Flag, bits);
}
pub fn cast(self: FSType) c_int {
return utils.structToBitFields(c_int, Flag, self);
}
};
pub const StyleFlags = packed struct {
italic: bool = false,
bold: bool = false,
pub const Flag = enum(u2) {
italic = c.FT_STYLE_FLAG_ITALIC,
bold = c.FT_STYLE_FLAG_BOLD,
};
pub fn from(bits: c_long) StyleFlags {
return utils.bitFieldsToStruct(StyleFlags, Flag, bits);
}
pub fn cast(self: StyleFlags) c_long {
return utils.structToBitFields(c_long, Flag, self);
}
};
pub const OpenFlags = packed struct {
memory: bool = false,
stream: bool = false,
path: bool = false,
driver: bool = false,
params: bool = false,
pub const Flag = enum(u5) {
memory = c.FT_OPEN_MEMORY,
stream = c.FT_OPEN_STREAM,
path = c.FT_OPEN_PATHNAME,
driver = c.FT_OPEN_DRIVER,
params = c.FT_OPEN_PARAMS,
};
pub fn from(bits: c_uint) OpenFlags {
return utils.bitFieldsToStruct(OpenFlags, Flag, bits);
}
pub fn cast(flags: OpenFlags) c_uint {
return utils.structToBitFields(c_uint, Flag, flags);
}
};
pub const OpenArgs = struct {
flags: OpenFlags,
data: union(enum) {
memory: []const u8,
path: []const u8,
stream: c.FT_Stream,
driver: c.FT_Module,
params: []const c.FT_Parameter,
},
pub fn cast(self: OpenArgs) c.FT_Open_Args {
var oa: c.FT_Open_Args = undefined;
oa.flags = self.flags.cast();
switch (self.data) {
.memory => |d| {
oa.memory_base = d.ptr;
oa.memory_size = @intCast(u31, d.len);
},
.path => |*d| oa.pathname = @intToPtr(*u8, @ptrToInt(d.ptr)),
.stream => |d| oa.stream = d,
.driver => |d| oa.driver = d,
.params => |*d| {
oa.params = @intToPtr(*c.FT_Parameter, @ptrToInt(d.ptr));
oa.num_params = @intCast(u31, d.len);
},
}
return oa;
}
};
pub fn getCharmapIndex(self: [*c]CharMap) ?u32 {
const i = c.FT_Get_Charmap_Index(self);
return if (i == -1) null else @intCast(u32, i);
}

172
libs/freetype/src/glyph.zig Normal file
View file

@ -0,0 +1,172 @@
const std = @import("std");
const c = @import("c");
const intToError = @import("error.zig").intToError;
const Error = @import("error.zig").Error;
const Stroker = @import("stroke.zig").Stroker;
const Library = @import("freetype.zig").Library;
const RenderMode = @import("freetype.zig").RenderMode;
const SizeMetrics = @import("freetype.zig").SizeMetrics;
const Matrix = @import("types.zig").Matrix;
const BBox = @import("types.zig").BBox;
const Outline = @import("image.zig").Outline;
const GlyphFormat = @import("image.zig").GlyphFormat;
const Vector = @import("image.zig").Vector;
const Bitmap = @import("image.zig").Bitmap;
pub const BBoxMode = enum(u2) {
// https://freetype.org/freetype2/docs/reference/ft2-glyph_management.html#ft_glyph_bbox_mode
// both `unscaled` and `subpixel` are set to 0
unscaled_or_subpixels = c.FT_GLYPH_BBOX_UNSCALED,
gridfit = c.FT_GLYPH_BBOX_GRIDFIT,
truncate = c.FT_GLYPH_BBOX_TRUNCATE,
pixels = c.FT_GLYPH_BBOX_PIXELS,
};
pub const Glyph = struct {
handle: c.FT_Glyph,
pub fn deinit(self: Glyph) void {
c.FT_Done_Glyph(self.handle);
}
pub fn newGlyph(library: Library, glyph_format: GlyphFormat) Glyph {
var g: c.FT_Glyph = undefined;
return .{
.handle = c.FT_New_Glyph(library.handle, @enumToInt(glyph_format), &g),
};
}
pub fn copy(self: Glyph) Error!Glyph {
var g: c.FT_Glyph = undefined;
try intToError(c.FT_Glyph_Copy(self.handle, &g));
return Glyph{ .handle = g };
}
pub fn transform(self: Glyph, matrix: ?Matrix, delta: ?Vector) Error!void {
try intToError(c.FT_Glyph_Transform(self.handle, if (matrix) |m| &m else null, if (delta) |d| &d else null));
}
pub fn getCBox(self: Glyph, bbox_mode: BBoxMode) BBox {
var b: BBox = undefined;
c.FT_Glyph_Get_CBox(self.handle, @enumToInt(bbox_mode), &b);
return b;
}
pub fn toBitmapGlyph(self: *Glyph, render_mode: RenderMode, origin: ?Vector) Error!BitmapGlyph {
try intToError(c.FT_Glyph_To_Bitmap(&self.handle, @enumToInt(render_mode), if (origin) |o| &o else null, 1));
return BitmapGlyph{ .handle = @ptrCast(c.FT_BitmapGlyph, self.handle) };
}
pub fn copyBitmapGlyph(self: *Glyph, render_mode: RenderMode, origin: ?Vector) Error!BitmapGlyph {
try intToError(c.FT_Glyph_To_Bitmap(&self.handle, @enumToInt(render_mode), if (origin) |o| &o else null, 0));
return BitmapGlyph{ .handle = @ptrCast(c.FT_BitmapGlyph, self.handle) };
}
pub fn castBitmapGlyph(self: Glyph) Error!BitmapGlyph {
return BitmapGlyph{ .handle = @ptrCast(c.FT_BitmapGlyph, self.handle) };
}
pub fn castOutlineGlyph(self: Glyph) Error!OutlineGlyph {
return OutlineGlyph{ .handle = @ptrCast(c.FT_OutlineGlyph, self.handle) };
}
pub fn castSvgGlyph(self: Glyph) Error!SvgGlyph {
return SvgGlyph{ .handle = @ptrCast(c.FT_SvgGlyph, self.handle) };
}
pub fn stroke(self: *Glyph, stroker: Stroker) Error!void {
try intToError(c.FT_Glyph_Stroke(&self.handle, stroker.handle, 0));
}
pub fn strokeBorder(self: *Glyph, stroker: Stroker, inside: bool) Error!void {
try intToError(c.FT_Glyph_StrokeBorder(&self.handle, stroker.handle, if (inside) 1 else 0, 0));
}
pub fn format(self: Glyph) GlyphFormat {
return @intToEnum(GlyphFormat, self.handle.*.format);
}
pub fn advanceX(self: Glyph) isize {
return self.handle.*.advance.x;
}
pub fn advanceY(self: Glyph) isize {
return self.handle.*.advance.y;
}
};
const SvgGlyph = struct {
handle: c.FT_SvgGlyph,
pub fn deinit(self: SvgGlyph) void {
c.FT_Done_Glyph(@ptrCast(c.FT_Glyph, self.handle));
}
pub fn svgBuffer(self: SvgGlyph) []const u8 {
return self.handle.*.svg_document[0..self.svgBufferLen()];
}
pub fn svgBufferLen(self: SvgGlyph) u32 {
return self.handle.*.svg_document_length;
}
pub fn glyphIndex(self: SvgGlyph) u32 {
return self.handle.*.glyph_index;
}
pub fn metrics(self: SvgGlyph) SizeMetrics {
return self.handle.*.metrics;
}
pub fn unitsPerEM(self: SvgGlyph) u16 {
return self.handle.*.units_per_EM;
}
pub fn startGlyphID(self: SvgGlyph) u16 {
return self.handle.*.start_glyph_id;
}
pub fn endGlyphID(self: SvgGlyph) u16 {
return self.handle.*.end_glyph_id;
}
pub fn transform(self: SvgGlyph) Matrix {
return self.handle.*.transform;
}
pub fn delta(self: SvgGlyph) Vector {
return self.handle.*.delta;
}
};
pub const BitmapGlyph = struct {
handle: c.FT_BitmapGlyph,
pub fn deinit(self: BitmapGlyph) void {
c.FT_Done_Glyph(@ptrCast(c.FT_Glyph, self.handle));
}
pub fn left(self: BitmapGlyph) i32 {
return self.handle.*.left;
}
pub fn top(self: BitmapGlyph) i32 {
return self.handle.*.top;
}
pub fn bitmap(self: BitmapGlyph) Bitmap {
return .{ .handle = self.handle.*.bitmap };
}
};
pub const OutlineGlyph = struct {
handle: c.FT_OutlineGlyph,
pub fn deinit(self: OutlineGlyph) void {
c.FT_Done_Glyph(@ptrCast(c.FT_Glyph, self.handle));
}
pub fn outline(self: OutlineGlyph) Outline {
return .{ .handle = &self.handle.*.outline };
}
};

View file

@ -0,0 +1,95 @@
const std = @import("std");
const c = @import("c");
pub const MemoryMode = enum(u2) {
duplicate = c.HB_MEMORY_MODE_DUPLICATE,
readonly = c.HB_MEMORY_MODE_READONLY,
writable = c.HB_MEMORY_MODE_WRITABLE,
readonly_may_make_writable = c.HB_MEMORY_MODE_READONLY_MAY_MAKE_WRITABLE,
};
pub const Blob = struct {
handle: *c.hb_blob_t,
pub fn init(data: []u8, mode: MemoryMode) ?Blob {
return Blob{
.handle = c.hb_blob_create_or_fail(&data[0], @intCast(c_uint, data.len), @enumToInt(mode), null, null) orelse return null,
};
}
pub fn initOrEmpty(data: []u8, mode: MemoryMode) Blob {
return .{
.handle = c.hb_blob_create(&data[0], @intCast(c_uint, data.len), @enumToInt(mode), null, null).?,
};
}
pub fn initFromFile(path: [*:0]const u8) ?Blob {
return Blob{
.handle = c.hb_blob_create_from_file_or_fail(path) orelse return null,
};
}
pub fn initFromFileOrEmpty(path: [*:0]const u8) Blob {
return .{
.handle = c.hb_blob_create_from_file(path).?,
};
}
pub fn initEmpty() Blob {
return .{ .handle = c.hb_blob_get_empty().? };
}
pub fn createSubBlobOrEmpty(self: Blob, offset: u32, len: u32) Blob {
return .{
.handle = c.hb_blob_create_sub_blob(self.handle, offset, len).?,
};
}
pub fn copyWritable(self: Blob) ?Blob {
return Blob{
.handle = c.hb_blob_copy_writable_or_fail(self.handle) orelse return null,
};
}
pub fn deinit(self: Blob) void {
c.hb_blob_destroy(self.handle);
}
pub fn getData(self: Blob, len: ?u32) []const u8 {
var l = len;
const data = c.hb_blob_get_data(self.handle, if (l) |_| &l.? else null);
return if (l) |_|
data[0..l.?]
else
std.mem.sliceTo(data, 0);
}
pub fn getDataWritable(self: Blob, len: ?u32) ?[]const u8 {
var l = len;
const data = c.hb_blob_get_data(self.handle, if (l) |_| &l.? else null);
return if (data == null)
null
else if (l) |_|
data[0..l.?]
else
std.mem.sliceTo(data, 0);
}
pub fn getLength(self: Blob) u32 {
return c.hb_blob_get_length(self.handle);
}
pub fn isImmutable(self: Blob) bool {
return c.hb_blob_is_immutable(self.handle) > 0;
}
pub fn makeImmutable(self: Blob) void {
c.hb_blob_make_immutable(self.handle);
}
pub fn reference(self: Blob) Blob {
return .{
.handle = c.hb_blob_reference(self.handle).?,
};
}
};

View file

@ -0,0 +1,397 @@
const std = @import("std");
const utils = @import("utils");
const c = @import("c");
const Direction = @import("common.zig").Direction;
const Script = @import("common.zig").Script;
const Language = @import("common.zig").Language;
const Font = @import("font.zig").Font;
pub const ContentType = enum(u2) {
invalid = c.HB_BUFFER_CONTENT_TYPE_INVALID,
unicode = c.HB_BUFFER_CONTENT_TYPE_UNICODE,
glyphs = c.HB_BUFFER_CONTENT_TYPE_GLYPHS,
};
pub const ClusterLevel = enum(u2) {
monotone_graphemes = c.HB_BUFFER_CLUSTER_LEVEL_MONOTONE_GRAPHEMES,
monotone_characters = c.HB_BUFFER_CLUSTER_LEVEL_MONOTONE_CHARACTERS,
characters = c.HB_BUFFER_CLUSTER_LEVEL_CHARACTERS,
};
pub const SerializeFormat = enum(u31) {
text = c.HB_BUFFER_SERIALIZE_FORMAT_TEXT,
json = c.HB_BUFFER_SERIALIZE_FORMAT_JSON,
invalid = c.HB_BUFFER_SERIALIZE_FORMAT_INVALID,
};
pub const GlyphInfo = extern struct {
codepoint: u32,
mask: u32,
cluster: u32,
var1: u32,
var2: u32,
pub fn getFlags(self: GlyphInfo) GlyphFlags {
return GlyphFlags.from(hb_glyph_info_get_glyph_flags(&self));
}
};
pub const Position = extern struct {
x_advance: i32,
y_advance: i32,
x_offset: i32,
y_offset: i32,
};
pub const GlyphFlags = packed struct {
unsafe_to_break: bool = false,
unsafe_to_concat: bool = false,
pub const Flag = enum(u2) {
unsafe_to_break = c.HB_GLYPH_FLAG_UNSAFE_TO_BREAK,
unsafe_to_concat = c.HB_GLYPH_FLAG_UNSAFE_TO_CONCAT,
};
pub fn from(bits: c_uint) GlyphFlags {
return utils.bitFieldsToStruct(GlyphFlags, Flag, bits);
}
pub fn cast(self: GlyphFlags) c_uint {
return utils.structToBitFields(c_uint, Flag, self);
}
};
pub const SegmentProps = struct {
direction: Direction,
script: Script,
language: Language,
pub fn from(c_struct: c.hb_segment_properties_t) SegmentProps {
return .{
.direction = @intToEnum(Direction, c_struct.direction),
.script = @intToEnum(Script, c_struct.script),
.language = Language{ .handle = c_struct.language },
};
}
pub fn cast(self: SegmentProps) c.hb_segment_properties_t {
return .{
.reserved1 = undefined,
.reserved2 = undefined,
.direction = @enumToInt(self.direction),
.script = @enumToInt(self.script),
.language = self.language.handle,
};
}
pub fn compare(a: SegmentProps, b: SegmentProps) bool {
return c.hb_segment_properties_equal(&a.cast(), &b.cast()) > 0;
}
pub fn hash(self: SegmentProps) u32 {
return c.hb_segment_properties_hash(&self.cast());
}
pub fn overlay(self: SegmentProps, src: SegmentProps) void {
c.hb_segment_properties_overlay(&self.cast(), &src.cast());
}
};
pub const SerializeFlags = packed struct {
no_clusters: bool = false,
no_positions: bool = false,
no_glyph_names: bool = false,
glyph_extents: bool = false,
glyph_flags: bool = false,
no_advances: bool = false,
pub const Flag = enum(u6) {
no_clusters = c.HB_BUFFER_SERIALIZE_FLAG_NO_CLUSTERS,
no_positions = c.HB_BUFFER_SERIALIZE_FLAG_NO_POSITIONS,
no_glyph_names = c.HB_BUFFER_SERIALIZE_FLAG_NO_GLYPH_NAMES,
glyph_extents = c.HB_BUFFER_SERIALIZE_FLAG_GLYPH_EXTENTS,
glyph_flags = c.HB_BUFFER_SERIALIZE_FLAG_GLYPH_FLAGS,
no_advances = c.HB_BUFFER_SERIALIZE_FLAG_NO_ADVANCES,
};
pub fn from(bits: u6) SerializeFlags {
return utils.bitFieldsToStruct(SerializeFlags, Flag, bits);
}
pub fn cast(self: SerializeFlags) u6 {
return utils.structToBitFields(u6, Flag, self);
}
};
pub const DiffFlags = packed struct {
equal: bool = false,
content_type_mismatch: bool = false,
length_mismatch: bool = false,
notdef_present: bool = false,
dotted_circle_present: bool = false,
codepoint_mismatch: bool = false,
cluster_mismatch: bool = false,
glyph_flags_mismatch: bool = false,
position_mismatch: bool = false,
pub const Flag = enum(u8) {
equal = c.HB_BUFFER_DIFF_FLAG_EQUAL,
content_type_mismatch = c.HB_BUFFER_DIFF_FLAG_CONTENT_TYPE_MISMATCH,
length_mismatch = c.HB_BUFFER_DIFF_FLAG_LENGTH_MISMATCH,
notdef_present = c.HB_BUFFER_DIFF_FLAG_NOTDEF_PRESENT,
dotted_circle_present = c.HB_BUFFER_DIFF_FLAG_DOTTED_CIRCLE_PRESENT,
codepoint_mismatch = c.HB_BUFFER_DIFF_FLAG_CODEPOINT_MISMATCH,
cluster_mismatch = c.HB_BUFFER_DIFF_FLAG_CLUSTER_MISMATCH,
glyph_flags_mismatch = c.HB_BUFFER_DIFF_FLAG_GLYPH_FLAGS_MISMATCH,
position_mismatch = c.HB_BUFFER_DIFF_FLAG_POSITION_MISMATCH,
};
pub fn from(bits: c_uint) DiffFlags {
return utils.bitFieldsToStruct(DiffFlags, Flag, bits);
}
pub fn cast(self: DiffFlags) c_uint {
return utils.structToBitFields(c_uint, Flag, self);
}
};
pub const Buffer = struct {
pub const Flags = packed struct {
bot: bool = false,
eot: bool = false,
preserve_default_ignorables: bool = false,
remove_default_ignorables: bool = false,
do_not_insert_dotted_circle: bool = false,
verify: bool = false,
produce_unsafe_to_concat: bool = false,
pub const Flag = enum(u7) {
bot = c.HB_BUFFER_FLAG_BOT,
eot = c.HB_BUFFER_FLAG_EOT,
preserve_default_ignorables = c.HB_BUFFER_FLAG_PRESERVE_DEFAULT_IGNORABLES,
remove_default_ignorables = c.HB_BUFFER_FLAG_REMOVE_DEFAULT_IGNORABLES,
do_not_insert_dotted_circle = c.HB_BUFFER_FLAG_DO_NOT_INSERT_DOTTED_CIRCLE,
verify = c.HB_BUFFER_FLAG_VERIFY,
produce_unsafe_to_concat = c.HB_BUFFER_FLAG_PRODUCE_UNSAFE_TO_CONCAT,
};
pub fn from(bits: c_uint) Flags {
return utils.bitFieldsToStruct(Flags, Flag, bits);
}
pub fn cast(self: Flags) c_uint {
return utils.structToBitFields(c_uint, Flag, self);
}
};
handle: *c.hb_buffer_t,
pub fn init() ?Buffer {
var b = c.hb_buffer_create();
if (c.hb_buffer_allocation_successful(b) < 1)
return null;
return Buffer{ .handle = b.? };
}
pub fn initEmpty() Buffer {
return .{ .handle = c.hb_buffer_get_empty().? };
}
pub fn initSimilar(self: Buffer) ?Buffer {
var b = c.hb_buffer_create_similar(self.handle);
if (c.hb_buffer_allocation_successful(b) < 1)
return null;
return Buffer{ .handle = b.? };
}
pub fn reference(self: Buffer) Buffer {
return .{
.handle = c.hb_buffer_reference(self.handle).?,
};
}
pub fn deinit(self: Buffer) void {
c.hb_buffer_destroy(self.handle);
}
pub fn reset(self: Buffer) void {
c.hb_buffer_reset(self.handle);
}
pub fn clearContents(self: Buffer) void {
c.hb_buffer_clear_contents(self.handle);
}
pub fn preAllocate(self: Buffer, size: u32) error{OutOfMemory}!void {
if (c.hb_buffer_pre_allocate(self.handle, size) < 1)
return error.OutOfMemory;
}
pub fn allocationSuccessful(self: Buffer) bool {
return c.hb_buffer_allocation_successful(self.handle) > 0;
}
pub fn add(self: Buffer, codepoint: u32, cluster: u32) void {
c.hb_buffer_add(self.handle, codepoint, cluster);
}
pub fn addCodepoints(self: Buffer, text: []const u32, item_offset: u32, item_length: ?u31) void {
c.hb_buffer_add_codepoints(self.handle, &text[0], @intCast(c_int, text.len), item_offset, if (item_length) |l| l else @intCast(c_int, text.len));
}
pub fn addUTF32(self: Buffer, text: []const u32, item_offset: u32, item_length: ?u31) void {
c.hb_buffer_add_utf32(self.handle, &text[0], @intCast(c_int, text.len), item_offset, if (item_length) |l| l else @intCast(c_int, text.len));
}
pub fn addUTF16(self: Buffer, text: []const u16, item_offset: u32, item_length: ?u31) void {
c.hb_buffer_add_utf16(self.handle, &text[0], @intCast(c_int, text.len), item_offset, if (item_length) |l| l else @intCast(c_int, text.len));
}
pub fn addUTF8(self: Buffer, text: []const u8, item_offset: u32, item_length: ?u31) void {
c.hb_buffer_add_utf8(self.handle, &text[0], @intCast(c_int, text.len), item_offset, if (item_length) |l| l else @intCast(c_int, text.len));
}
pub fn addLatin1(self: Buffer, text: []const u8, item_offset: u32, item_length: ?u31) void {
c.hb_buffer_add_latin1(self.handle, &text[0], @intCast(c_int, text.len), item_offset, if (item_length) |l| l else @intCast(c_int, text.len));
}
pub fn append(self: Buffer, source: Buffer, start: u32, end: u32) void {
c.hb_buffer_append(self.handle, source.handle, start, end);
}
pub fn getContentType(self: Buffer) ContentType {
return @intToEnum(ContentType, c.hb_buffer_get_content_type(self.handle));
}
pub fn setContentType(self: Buffer, content_type: ContentType) void {
c.hb_buffer_set_content_type(self.handle, @enumToInt(content_type));
}
pub fn getDirection(self: Buffer) Direction {
return @intToEnum(Direction, c.hb_buffer_get_direction(self.handle));
}
pub fn setDirection(self: Buffer, direction: Direction) void {
c.hb_buffer_set_direction(self.handle, @enumToInt(direction));
}
pub fn getScript(self: Buffer) Script {
return @intToEnum(Script, c.hb_buffer_get_script(self.handle));
}
pub fn setScript(self: Buffer, script: Script) void {
c.hb_buffer_set_script(self.handle, @enumToInt(script));
}
pub fn getLanguage(self: Buffer) Language {
return Language{ .handle = c.hb_buffer_get_language(self.handle) };
}
pub fn setLanguage(self: Buffer, lang: Language) void {
c.hb_buffer_set_language(self.handle, lang.handle);
}
pub fn getFlags(self: Buffer) Flags {
return Flags.from(c.hb_buffer_get_flags(self.handle));
}
pub fn setFlags(self: Buffer, flags: Flags) void {
c.hb_buffer_set_flags(self.handle, flags.cast());
}
pub fn getClusterLevel(self: Buffer) ClusterLevel {
return @intToEnum(ClusterLevel, c.hb_buffer_get_cluster_level(self.handle));
}
pub fn setClusterLevel(self: Buffer, level: ClusterLevel) void {
c.hb_buffer_set_cluster_level(self.handle, @enumToInt(level));
}
pub fn getLength(self: Buffer) u32 {
return c.hb_buffer_get_length(self.handle);
}
pub fn setLength(self: Buffer, new_len: u32) error{OutOfMemory}!void {
if (c.hb_buffer_set_length(self.handle, new_len) < 1)
return error.OutOfMemory;
}
pub fn getSegmentProps(self: Buffer) SegmentProps {
var props: c.hb_segment_properties_t = undefined;
c.hb_buffer_get_segment_properties(self.handle, &props);
return SegmentProps.from(props);
}
pub fn setSegmentProps(self: Buffer, props: SegmentProps) void {
c.hb_buffer_set_segment_properties(self.handle, &props.cast());
}
pub fn guessSegmentProps(self: Buffer) void {
c.hb_buffer_guess_segment_properties(self.handle);
}
pub fn getGlyphInfos(self: Buffer) []GlyphInfo {
var length: u32 = 0;
return hb_buffer_get_glyph_infos(self.handle, &length)[0..length];
}
pub fn getGlyphPositions(self: Buffer) ?[]Position {
var length: u32 = 0;
return if (hb_buffer_get_glyph_positions(self.handle, &length)) |positions|
@ptrCast([*]Position, positions)[0..length]
else
null;
}
pub fn hasPositions(self: Buffer) bool {
return c.hb_buffer_has_positions(self.handle) > 0;
}
pub fn getInvisibleGlyph(self: Buffer) u32 {
return c.hb_buffer_get_invisible_glyph(self.handle);
}
pub fn setInvisibleGlyph(self: Buffer, codepoint: u32) void {
c.hb_buffer_set_invisible_glyph(self.handle, codepoint);
}
pub fn getGlyphNotFound(self: Buffer) u32 {
return c.hb_buffer_get_not_found_glyph(self.handle);
}
pub fn setGlyphNotFound(self: Buffer, codepoint: u32) void {
c.hb_buffer_set_not_found_glyph(self.handle, codepoint);
}
pub fn getReplacementCodepoint(self: Buffer) u32 {
return c.hb_buffer_get_replacement_codepoint(self.handle);
}
pub fn setReplacementCodepoint(self: Buffer, codepoint: u32) void {
c.hb_buffer_set_replacement_codepoint(self.handle, codepoint);
}
pub fn normalizeGlyphs(self: Buffer) void {
c.hb_buffer_normalize_glyphs(self.handle);
}
pub fn reverse(self: Buffer) void {
c.hb_buffer_reverse(self.handle);
}
pub fn reverseRange(self: Buffer, start: u32, end: u32) void {
c.hb_buffer_reverse_range(self.handle, start, end);
}
pub fn reverseClusters(self: Buffer) void {
c.hb_buffer_reverse_clusters(self.handle);
}
pub fn diff(self: Buffer, ref: Buffer, dottedcircle_glyph: u32, position_fuzz: u32) DiffFlags {
return DiffFlags.from(c.hb_buffer_diff(self.handle, ref.handle, dottedcircle_glyph, position_fuzz));
}
};
pub extern fn hb_glyph_info_get_glyph_flags(info: [*c]const GlyphInfo) c.hb_glyph_flags_t;
pub extern fn hb_buffer_get_glyph_infos(buffer: ?*c.hb_buffer_t, length: [*c]c_uint) [*c]GlyphInfo;
pub extern fn hb_buffer_get_glyph_positions(buffer: ?*c.hb_buffer_t, length: [*c]c_uint) [*c]Position;

View file

@ -0,0 +1,282 @@
const std = @import("std");
const c = @import("c");
pub const Direction = enum(u3) {
invalid = c.HB_DIRECTION_INVALID,
ltr = c.HB_DIRECTION_LTR,
rtl = c.HB_DIRECTION_RTL,
ttb = c.HB_DIRECTION_TTB,
bit = c.HB_DIRECTION_BTT,
pub fn fromString(str: []const u8) Direction {
return @intToEnum(Direction, c.hb_direction_from_string(str.ptr, @intCast(c_int, str.len)));
}
pub fn toString(self: Direction) [:0]const u8 {
return std.mem.span(@ptrCast([*:0]const u8, c.hb_direction_to_string(@enumToInt(self))));
}
};
pub const Script = enum(u31) {
common = c.HB_SCRIPT_COMMON,
inherited = c.HB_SCRIPT_INHERITED,
unknown = c.HB_SCRIPT_UNKNOWN,
arabic = c.HB_SCRIPT_ARABIC,
armenian = c.HB_SCRIPT_ARMENIAN,
bengali = c.HB_SCRIPT_BENGALI,
cyrillic = c.HB_SCRIPT_CYRILLIC,
devanagari = c.HB_SCRIPT_DEVANAGARI,
georgian = c.HB_SCRIPT_GEORGIAN,
greek = c.HB_SCRIPT_GREEK,
gujarati = c.HB_SCRIPT_GUJARATI,
gurmukhi = c.HB_SCRIPT_GURMUKHI,
hangul = c.HB_SCRIPT_HANGUL,
han = c.HB_SCRIPT_HAN,
hebrew = c.HB_SCRIPT_HEBREW,
hiragana = c.HB_SCRIPT_HIRAGANA,
kannada = c.HB_SCRIPT_KANNADA,
katakana = c.HB_SCRIPT_KATAKANA,
lao = c.HB_SCRIPT_LAO,
latin = c.HB_SCRIPT_LATIN,
malayalam = c.HB_SCRIPT_MALAYALAM,
oriya = c.HB_SCRIPT_ORIYA,
tamil = c.HB_SCRIPT_TAMIL,
telugu = c.HB_SCRIPT_TELUGU,
thai = c.HB_SCRIPT_THAI,
tibetan = c.HB_SCRIPT_TIBETAN,
bopomofo = c.HB_SCRIPT_BOPOMOFO,
braille = c.HB_SCRIPT_BRAILLE,
canadian_syllabics = c.HB_SCRIPT_CANADIAN_SYLLABICS,
cherokee = c.HB_SCRIPT_CHEROKEE,
ethiopic = c.HB_SCRIPT_ETHIOPIC,
khmer = c.HB_SCRIPT_KHMER,
mongolian = c.HB_SCRIPT_MONGOLIAN,
myanmar = c.HB_SCRIPT_MYANMAR,
ogham = c.HB_SCRIPT_OGHAM,
runic = c.HB_SCRIPT_RUNIC,
sinhala = c.HB_SCRIPT_SINHALA,
syriac = c.HB_SCRIPT_SYRIAC,
thaana = c.HB_SCRIPT_THAANA,
yi = c.HB_SCRIPT_YI,
deseret = c.HB_SCRIPT_DESERET,
gothic = c.HB_SCRIPT_GOTHIC,
old_italic = c.HB_SCRIPT_OLD_ITALIC,
buhid = c.HB_SCRIPT_BUHID,
hanunoo = c.HB_SCRIPT_HANUNOO,
tagalog = c.HB_SCRIPT_TAGALOG,
tagbanwa = c.HB_SCRIPT_TAGBANWA,
cypriot = c.HB_SCRIPT_CYPRIOT,
limbu = c.HB_SCRIPT_LIMBU,
linear_b = c.HB_SCRIPT_LINEAR_B,
osmanya = c.HB_SCRIPT_OSMANYA,
shavian = c.HB_SCRIPT_SHAVIAN,
tai_le = c.HB_SCRIPT_TAI_LE,
ugaritic = c.HB_SCRIPT_UGARITIC,
buginese = c.HB_SCRIPT_BUGINESE,
coptic = c.HB_SCRIPT_COPTIC,
glagolitic = c.HB_SCRIPT_GLAGOLITIC,
kharoshthi = c.HB_SCRIPT_KHAROSHTHI,
new_tai_lue = c.HB_SCRIPT_NEW_TAI_LUE,
old_persian = c.HB_SCRIPT_OLD_PERSIAN,
syloti_nagri = c.HB_SCRIPT_SYLOTI_NAGRI,
tifinagh = c.HB_SCRIPT_TIFINAGH,
balinese = c.HB_SCRIPT_BALINESE,
cuneiform = c.HB_SCRIPT_CUNEIFORM,
nko = c.HB_SCRIPT_NKO,
phags_pa = c.HB_SCRIPT_PHAGS_PA,
phoenician = c.HB_SCRIPT_PHOENICIAN,
carian = c.HB_SCRIPT_CARIAN,
cham = c.HB_SCRIPT_CHAM,
kayah_li = c.HB_SCRIPT_KAYAH_LI,
lepcha = c.HB_SCRIPT_LEPCHA,
lycian = c.HB_SCRIPT_LYCIAN,
lydian = c.HB_SCRIPT_LYDIAN,
ol_chiki = c.HB_SCRIPT_OL_CHIKI,
rejang = c.HB_SCRIPT_REJANG,
saurashtra = c.HB_SCRIPT_SAURASHTRA,
sundanese = c.HB_SCRIPT_SUNDANESE,
vai = c.HB_SCRIPT_VAI,
avestan = c.HB_SCRIPT_AVESTAN,
bamum = c.HB_SCRIPT_BAMUM,
egyptian_hieroglyphs = c.HB_SCRIPT_EGYPTIAN_HIEROGLYPHS,
imperial_aramaic = c.HB_SCRIPT_IMPERIAL_ARAMAIC,
inscriptional_pahlavi = c.HB_SCRIPT_INSCRIPTIONAL_PAHLAVI,
inscriptional_parthian = c.HB_SCRIPT_INSCRIPTIONAL_PARTHIAN,
javanese = c.HB_SCRIPT_JAVANESE,
kaithi = c.HB_SCRIPT_KAITHI,
lisu = c.HB_SCRIPT_LISU,
meetei_mayek = c.HB_SCRIPT_MEETEI_MAYEK,
old_south_arabian = c.HB_SCRIPT_OLD_SOUTH_ARABIAN,
old_turkic = c.HB_SCRIPT_OLD_TURKIC,
samaritan = c.HB_SCRIPT_SAMARITAN,
tai_tham = c.HB_SCRIPT_TAI_THAM,
tai_viet = c.HB_SCRIPT_TAI_VIET,
batak = c.HB_SCRIPT_BATAK,
brahmi = c.HB_SCRIPT_BRAHMI,
mandaic = c.HB_SCRIPT_MANDAIC,
chakma = c.HB_SCRIPT_CHAKMA,
meroitic_cursive = c.HB_SCRIPT_MEROITIC_CURSIVE,
meroitic_hieroglyphs = c.HB_SCRIPT_MEROITIC_HIEROGLYPHS,
miao = c.HB_SCRIPT_MIAO,
sharada = c.HB_SCRIPT_SHARADA,
sora_sompeng = c.HB_SCRIPT_SORA_SOMPENG,
takri = c.HB_SCRIPT_TAKRI,
bassa_vah = c.HB_SCRIPT_BASSA_VAH,
caucasian_albanian = c.HB_SCRIPT_CAUCASIAN_ALBANIAN,
duployan = c.HB_SCRIPT_DUPLOYAN,
elbasan = c.HB_SCRIPT_ELBASAN,
grantha = c.HB_SCRIPT_GRANTHA,
khojki = c.HB_SCRIPT_KHOJKI,
khudawadi = c.HB_SCRIPT_KHUDAWADI,
linear_a = c.HB_SCRIPT_LINEAR_A,
mahajani = c.HB_SCRIPT_MAHAJANI,
manichaean = c.HB_SCRIPT_MANICHAEAN,
mende_kikakui = c.HB_SCRIPT_MENDE_KIKAKUI,
modi = c.HB_SCRIPT_MODI,
mro = c.HB_SCRIPT_MRO,
nabataean = c.HB_SCRIPT_NABATAEAN,
old_north_arabian = c.HB_SCRIPT_OLD_NORTH_ARABIAN,
old_permic = c.HB_SCRIPT_OLD_PERMIC,
pahawh_hmong = c.HB_SCRIPT_PAHAWH_HMONG,
palmyrene = c.HB_SCRIPT_PALMYRENE,
pau_cin_hau = c.HB_SCRIPT_PAU_CIN_HAU,
psalter_pahlavi = c.HB_SCRIPT_PSALTER_PAHLAVI,
siddham = c.HB_SCRIPT_SIDDHAM,
tirhuta = c.HB_SCRIPT_TIRHUTA,
warang_citi = c.HB_SCRIPT_WARANG_CITI,
ahom = c.HB_SCRIPT_AHOM,
anatolian_hieroglyphs = c.HB_SCRIPT_ANATOLIAN_HIEROGLYPHS,
hatran = c.HB_SCRIPT_HATRAN,
multani = c.HB_SCRIPT_MULTANI,
old_hungarian = c.HB_SCRIPT_OLD_HUNGARIAN,
signwriting = c.HB_SCRIPT_SIGNWRITING,
adlam = c.HB_SCRIPT_ADLAM,
bhaiksuki = c.HB_SCRIPT_BHAIKSUKI,
marchen = c.HB_SCRIPT_MARCHEN,
osage = c.HB_SCRIPT_OSAGE,
tangut = c.HB_SCRIPT_TANGUT,
newa = c.HB_SCRIPT_NEWA,
masaram_gondi = c.HB_SCRIPT_MASARAM_GONDI,
nushu = c.HB_SCRIPT_NUSHU,
soyombo = c.HB_SCRIPT_SOYOMBO,
zanabazar_square = c.HB_SCRIPT_ZANABAZAR_SQUARE,
dogra = c.HB_SCRIPT_DOGRA,
gunjala_gondi = c.HB_SCRIPT_GUNJALA_GONDI,
hanifi_rohingya = c.HB_SCRIPT_HANIFI_ROHINGYA,
makasar = c.HB_SCRIPT_MAKASAR,
medefaidrin = c.HB_SCRIPT_MEDEFAIDRIN,
old_sogdian = c.HB_SCRIPT_OLD_SOGDIAN,
sogdian = c.HB_SCRIPT_SOGDIAN,
elymaic = c.HB_SCRIPT_ELYMAIC,
nandinagari = c.HB_SCRIPT_NANDINAGARI,
nyiakeng_puachue_hmong = c.HB_SCRIPT_NYIAKENG_PUACHUE_HMONG,
wancho = c.HB_SCRIPT_WANCHO,
chorasmian = c.HB_SCRIPT_CHORASMIAN,
dives_akuru = c.HB_SCRIPT_DIVES_AKURU,
khitan_small_script = c.HB_SCRIPT_KHITAN_SMALL_SCRIPT,
yezidi = c.HB_SCRIPT_YEZIDI,
cypro_minoan = c.HB_SCRIPT_CYPRO_MINOAN,
old_uyghur = c.HB_SCRIPT_OLD_UYGHUR,
tangsa = c.HB_SCRIPT_TANGSA,
toto = c.HB_SCRIPT_TOTO,
vithkuqi = c.HB_SCRIPT_VITHKUQI,
math = c.HB_SCRIPT_MATH,
invalid = c.HB_SCRIPT_INVALID,
pub fn fromISO15924Tag(tag: Tag) Script {
return @intToEnum(Script, c.hb_script_from_iso15924_tag(tag.handle));
}
pub fn fromString(str: []const u8) Script {
return @intToEnum(Script, c.hb_script_from_string(str.ptr, @intCast(c_int, str.len)));
}
pub fn toISO15924Tag(self: Script) Tag {
return .{ .handle = c.hb_script_to_iso15924_tag(@enumToInt(self)) };
}
pub fn getHorizontalDirection(self: Script) Direction {
return @intToEnum(Direction, c.hb_script_get_horizontal_direction(@enumToInt(self)));
}
};
pub const Language = struct {
handle: c.hb_language_t,
pub fn fromString(name: []const u8) Language {
return .{
.handle = c.hb_language_from_string(name.ptr, @intCast(c_int, name.len)),
};
}
pub fn toString(self: Language) [:0]const u8 {
return std.mem.span(@ptrCast([*:0]const u8, c.hb_language_to_string(self.handle)));
}
pub fn getDefault() Language {
return .{ .handle = c.hb_language_get_default() };
}
};
pub const Feature = extern struct {
tag: c.hb_tag_t,
value: u32,
start: c_uint,
end: c_uint,
pub fn fromString(str: []const u8) ?Feature {
var f: Feature = undefined;
return if (hb_feature_from_string(str.ptr, @intCast(c_int, str.len), &f) > 1)
f
else
null;
}
pub fn toString(self: *Feature, buf: []u8) void {
hb_feature_to_string(self, buf.ptr, @intCast(c_uint, buf.len));
}
};
pub const Variation = extern struct {
tag: u32,
value: f32,
pub fn fromString(str: []const u8) ?Variation {
var v: Variation = undefined;
return if (hb_variation_from_string(str.ptr, @intCast(c_int, str.len), &v) > 1)
v
else
null;
}
pub fn toString(self: *Variation, buf: []u8) void {
hb_variation_to_string(self, buf.ptr, @intCast(c_uint, buf.len));
}
pub fn tag(self: Variation) Tag {
return .{ .handle = self.tag };
}
pub fn value(self: Variation) f32 {
return self.value;
}
};
pub const Tag = struct {
handle: u32,
pub fn fromString(str: []const u8) Tag {
return .{ .handle = c.hb_tag_from_string(str.ptr, @intCast(c_int, str.len)) };
}
pub fn toString(self: Tag) []const u8 {
var str: [4]u8 = undefined;
c.hb_tag_to_string(self.handle, &str[0]);
return &str;
}
};
pub extern fn hb_feature_from_string(str: [*c]const u8, len: c_int, feature: [*c]Feature) u8;
pub extern fn hb_feature_to_string(feature: [*c]Feature, buf: [*c]u8, size: c_uint) void;
pub extern fn hb_variation_from_string(str: [*c]const u8, len: c_int, variation: [*c]Variation) u8;
pub extern fn hb_variation_to_string(variation: [*c]Variation, buf: [*c]u8, size: c_uint) void;

View file

@ -0,0 +1,80 @@
const freetype = @import("freetype");
const c = @import("c");
const Blob = @import("blob.zig").Blob;
pub const UnicodeIterator = struct {
set: *c.hb_set_t,
prev_codepoint: u32 = 0,
pub fn next(self: *UnicodeIterator) ?u32 {
var codepoint: u32 = c.HB_SET_VALUE_INVALID;
return if (c.hb_set_next(self.set, &codepoint) > 1) b: {
self.prev_codepoint = codepoint;
break :b codepoint;
} else null;
}
};
pub const Face = struct {
handle: *c.hb_face_t,
pub fn init(blob: Blob, index: u16) Face {
return .{ .handle = c.hb_face_create(blob.handle, index).? };
}
pub fn fromFtFace(face: freetype.Face) Face {
return .{ .handle = c.hb_ft_face_create_referenced(face.handle).? };
}
pub fn initEmpty() Face {
return .{ .handle = c.hb_face_get_empty().? };
}
pub fn getCount(blob: Blob) u32 {
return c.hb_face_count(blob.handle);
}
pub fn deinit(self: Face) void {
c.hb_face_destroy(self.handle);
}
pub fn getGlyphcount(self: Face) u32 {
return c.hb_face_get_glyph_count(self.handle);
}
pub fn setGlyphcount(self: Face, count: u32) void {
return c.hb_face_set_glyph_count(self.handle, count);
}
pub fn getUnitsPerEM(self: Face) u32 {
return c.hb_face_get_upem(self.handle);
}
pub fn setUnitsPerEM(self: Face, upem: u32) void {
return c.hb_face_set_upem(self.handle, upem);
}
pub fn setIndex(self: Face, index: u32) void {
return c.hb_face_set_index(self.handle, index);
}
pub fn isImmutable(self: Face) bool {
return c.hb_face_is_immutable(self.handle) > 0;
}
pub fn makeImmutable(self: Face) void {
c.hb_face_make_immutable(self.handle);
}
pub fn reference(self: Face) Face {
return .{
.handle = c.hb_face_reference(self.handle).?,
};
}
pub fn collectUnicodes(self: Face) UnicodeIterator {
var set: *c.hb_set_t = undefined;
c.hb_face_collect_unicodes(self.handle, set);
return .{ .set = set };
}
};

View file

@ -0,0 +1,100 @@
const freetype = @import("freetype");
const c = @import("c");
const Face = @import("face.zig").Face;
const Buffer = @import("buffer.zig").Buffer;
const Feature = @import("common.zig").Feature;
const SegmentProps = @import("buffer.zig").SegmentProps;
pub const Font = struct {
handle: *c.hb_font_t,
pub fn init(face: Face) Font {
return .{ .handle = c.hb_font_create(face.handle).? };
}
pub fn fromFtFace(face: freetype.Face) Font {
return .{ .handle = c.hb_ft_font_create_referenced(face.handle).? };
}
pub fn createSubFont(self: Font) Font {
return .{
.handle = c.hb_font_create_sub_font(self.handle).?,
};
}
pub fn deinit(self: Font) void {
c.hb_font_destroy(self.handle);
}
pub fn ftFaceChanged(self: Font) void {
c.hb_ft_font_changed(self.handle);
}
pub fn setFtLoadFlags(self: Font, flags: freetype.LoadFlags) void {
c.hb_ft_font_set_load_flags(self.handle, flags.cast());
}
pub fn getFace(self: Font) Face {
return .{ .handle = c.hb_font_get_face(self.handle).? };
}
pub fn getFreetypeFace(self: Font) freetype.Face {
return .{ .handle = c.hb_ft_font_get_face(self.handle) };
}
pub fn getGlyph(self: Font, unicode: u32, variation_selector: u32) ?u32 {
var g: u32 = 0;
return if (c.hb_font_get_glyph(self.handle, unicode, variation_selector, &g) > 0)
g
else
null;
}
pub fn getParent(self: Font) ?Font {
return Font{ .handle = c.hb_font_get_parent(self.handle) orelse return null };
}
pub fn getPPEM(self: Font) @Vector(2, u32) {
var x: u32 = 0;
var y: u32 = 0;
c.hb_font_get_ppem(self.handle, &@intCast(c_uint, x), &@intCast(c_uint, y));
return @Vector(2, u32){ x, y };
}
pub fn getPTEM(self: Font) f32 {
return c.hb_font_get_ptem(self.handle);
}
pub fn getScale(self: Font) @Vector(2, u32) {
var x: u32 = 0;
var y: u32 = 0;
c.hb_font_get_scale(self.handle, &@intCast(c_int, x), &@intCast(c_int, y));
return @Vector(2, u32){ x, y };
}
pub fn setFace(self: Font, face: Face) void {
return c.hb_font_set_face(self.handle, face.handle);
}
pub fn shape(self: Font, buf: Buffer, features: ?[]const Feature) void {
hb_shape(
self.handle,
buf.handle,
if (features) |f| f.ptr else null,
if (features) |f| @intCast(c_uint, f.len) else 0,
);
}
pub fn shapeFull(self: Font, buf: Buffer, features: ?[]const Feature, shapers: []const []const u8) error{ShapingFailed}!void {
if (hb_shape_full(
self.handle,
buf.handle,
if (features) |f| f.ptr else null,
if (features) |f| @intCast(c_uint, f.len) else 0,
@ptrCast([*c]const [*c]const u8, shapers),
) < 1) return error.ShapingFailed;
}
};
pub extern fn hb_shape(font: ?*c.hb_font_t, buffer: ?*c.hb_buffer_t, features: [*c]const Feature, num_features: c_uint) void;
pub extern fn hb_shape_full(font: ?*c.hb_font_t, buffer: ?*c.hb_buffer_t, features: [*c]const Feature, num_features: c_uint, shaper_list: [*c]const [*c]const u8) u8;

View file

@ -0,0 +1,14 @@
pub usingnamespace @import("blob.zig");
pub usingnamespace @import("buffer.zig");
pub usingnamespace @import("common.zig");
pub usingnamespace @import("face.zig");
pub usingnamespace @import("font.zig");
pub usingnamespace @import("shape.zig");
pub usingnamespace @import("shape_plan.zig");
const std = @import("std");
// Remove once the stage2 compiler fixes pkg std not found
comptime {
_ = @import("utils");
}

View file

@ -0,0 +1,19 @@
const std = @import("std");
const c = @import("c");
pub const ListShapers = struct {
index: usize,
list: [*c][*c]const u8,
pub fn init() ListShapers {
return .{ .index = 0, .list = c.hb_shape_list_shapers() };
}
pub fn next(self: *ListShapers) ?[:0]const u8 {
self.index += 1;
return std.mem.span(@ptrCast(
?[*:0]const u8,
self.list[self.index - 1] orelse return null,
));
}
};

View file

@ -0,0 +1,79 @@
const std = @import("std");
const c = @import("c");
const Buffer = @import("buffer.zig").Buffer;
const Font = @import("font.zig").Font;
const Face = @import("face.zig").Face;
const SegmentProps = @import("buffer.zig").SegmentProps;
const Feature = @import("common.zig").Feature;
pub const ShapePlan = struct {
handle: *c.hb_shape_plan_t,
pub fn init(face: Face, props: SegmentProps, features: ?[]const Feature, shapers: []const []const u8) ShapePlan {
return .{ .handle = hb_shape_plan_create(
face.handle,
&props.cast(),
if (features) |f| f.ptr else null,
if (features) |f| @intCast(c_uint, f.len) else 0,
@ptrCast([*c]const [*c]const u8, shapers),
).? };
}
pub fn initCached(face: Face, props: SegmentProps, features: ?[]const Feature, shapers: []const []const u8) ShapePlan {
return .{ .handle = hb_shape_plan_create_cached(
face.handle,
&props.cast(),
if (features) |f| f.ptr else null,
if (features) |f| @intCast(c_uint, f.len) else 0,
@ptrCast([*c]const [*c]const u8, shapers),
).? };
}
pub fn init2(face: Face, props: SegmentProps, features: ?[]const Feature, cords: []const i32, shapers: []const []const u8) ShapePlan {
return .{ .handle = hb_shape_plan_create2(
face.handle,
&props.cast(),
if (features) |f| f.ptr else null,
if (features) |f| @intCast(c_uint, f.len) else 0,
cords.ptr,
@intCast(c_uint, cords.len),
@ptrCast([*c]const [*c]const u8, shapers),
).? };
}
pub fn initCached2(face: Face, props: SegmentProps, features: ?[]const Feature, cords: []const i32, shapers: []const []const u8) ShapePlan {
return .{ .handle = hb_shape_plan_create_cached2(
face.handle,
&props.cast(),
if (features) |f| f.ptr else null,
if (features) |f| @intCast(c_uint, f.len) else 0,
cords.ptr,
@intCast(c_uint, cords.len),
@ptrCast([*c]const [*c]const u8, shapers),
).? };
}
pub fn deinit(self: ShapePlan) void {
c.hb_shape_plan_destroy(self.handle);
}
pub fn execute(self: ShapePlan, font: Font, buffer: Buffer, features: ?[]Feature) error{ShapingFailed}!void {
if (hb_shape_plan_execute(
self.handle,
font.handle,
buffer.handle,
if (features) |f| f.ptr else null,
if (features) |f| @intCast(c_uint, f.len) else 0,
) < 1) return error.ShapingFailed;
}
pub fn getShaper(self: ShapePlan) [:0]const u8 {
return std.mem.span(@ptrCast([*:0]const u8, c.hb_shape_plan_get_shaper(self.handle)));
}
};
pub extern fn hb_shape_plan_create(face: ?*c.hb_face_t, props: [*c]const c.hb_segment_properties_t, user_features: [*c]const Feature, num_user_features: c_uint, shaper_list: [*c]const [*c]const u8) ?*c.hb_shape_plan_t;
pub extern fn hb_shape_plan_create_cached(face: ?*c.hb_face_t, props: [*c]const c.hb_segment_properties_t, user_features: [*c]const Feature, num_user_features: c_uint, shaper_list: [*c]const [*c]const u8) ?*c.hb_shape_plan_t;
pub extern fn hb_shape_plan_create2(face: ?*c.hb_face_t, props: [*c]const c.hb_segment_properties_t, user_features: [*c]const Feature, num_user_features: c_uint, coords: [*c]const c_int, num_coords: c_uint, shaper_list: [*c]const [*c]const u8) ?*c.hb_shape_plan_t;
pub extern fn hb_shape_plan_create_cached2(face: ?*c.hb_face_t, props: [*c]const c.hb_segment_properties_t, user_features: [*c]const Feature, num_user_features: c_uint, coords: [*c]const c_int, num_coords: c_uint, shaper_list: [*c]const [*c]const u8) ?*c.hb_shape_plan_t;
pub extern fn hb_shape_plan_execute(shape_plan: ?*c.hb_shape_plan_t, font: ?*c.hb_font_t, buffer: ?*c.hb_buffer_t, features: [*c]const Feature, num_features: c_uint) u8;

309
libs/freetype/src/image.zig Normal file
View file

@ -0,0 +1,309 @@
const builtin = @import("builtin");
const std = @import("std");
const c = @import("c");
const utils = @import("utils.zig");
const intToError = @import("error.zig").intToError;
const errorToInt = @import("error.zig").errorToInt;
const Error = @import("error.zig").Error;
const Library = @import("freetype.zig").Library;
const Color = @import("color.zig").Color;
const Stroker = @import("stroke.zig").Stroker;
const Matrix = @import("types.zig").Matrix;
const BBox = @import("types.zig").BBox;
pub const Vector = c.FT_Vector;
pub const GlyphMetrics = c.FT_Glyph_Metrics;
pub const RasterParams = c.FT_Raster_Params_;
pub const PixelMode = enum(u3) {
none = c.FT_PIXEL_MODE_NONE,
mono = c.FT_PIXEL_MODE_MONO,
gray = c.FT_PIXEL_MODE_GRAY,
gray2 = c.FT_PIXEL_MODE_GRAY2,
gray4 = c.FT_PIXEL_MODE_GRAY4,
lcd = c.FT_PIXEL_MODE_LCD,
lcd_v = c.FT_PIXEL_MODE_LCD_V,
bgra = c.FT_PIXEL_MODE_BGRA,
};
pub const GlyphFormat = enum(u32) {
none = c.FT_GLYPH_FORMAT_NONE,
composite = c.FT_GLYPH_FORMAT_COMPOSITE,
bitmap = c.FT_GLYPH_FORMAT_BITMAP,
outline = c.FT_GLYPH_FORMAT_OUTLINE,
plotter = c.FT_GLYPH_FORMAT_PLOTTER,
svg = c.FT_GLYPH_FORMAT_SVG,
};
pub const Bitmap = struct {
handle: c.FT_Bitmap,
pub fn init() Bitmap {
var b: c.FT_Bitmap = undefined;
c.FT_Bitmap_Init(&b);
return .{ .handle = b };
}
pub fn deinit(self: *Bitmap, lib: Library) void {
_ = c.FT_Bitmap_Done(lib.handle, &self.handle);
}
pub fn copy(self: Bitmap, lib: Library) Error!Bitmap {
var b: c.FT_Bitmap = undefined;
try intToError(c.FT_Bitmap_Copy(lib.handle, &self.handle, &b));
return Bitmap{ .handle = b };
}
pub fn embolden(self: *Bitmap, lib: Library, x_strength: i32, y_strength: i32) Error!void {
try intToError(c.FT_Bitmap_Embolden(lib.handle, &self.handle, x_strength, y_strength));
}
pub fn convert(self: Bitmap, lib: Library, alignment: u29) Error!Bitmap {
var b: c.FT_Bitmap = undefined;
try intToError(c.FT_Bitmap_Convert(lib.handle, &self.handle, &b, alignment));
return Bitmap{ .handle = b };
}
pub fn blend(self: *Bitmap, lib: Library, source_offset: Vector, target_offset: *Vector, color: Color) Error!void {
var b: c.FT_Bitmap = undefined;
c.FT_Bitmap_Init(&b);
try intToError(c.FT_Bitmap_Blend(lib.handle, &self.handle, source_offset, &b, target_offset, color));
}
pub fn width(self: Bitmap) u32 {
return self.handle.width;
}
pub fn pitch(self: Bitmap) i32 {
return self.handle.pitch;
}
pub fn rows(self: Bitmap) u32 {
return self.handle.rows;
}
pub fn pixelMode(self: Bitmap) PixelMode {
return @intToEnum(PixelMode, self.handle.pixel_mode);
}
pub fn buffer(self: Bitmap) ?[]const u8 {
const buffer_size = std.math.absCast(self.pitch()) * self.rows();
return if (self.handle.buffer == null)
// freetype returns a null pointer for zero-length allocations
// https://github.com/hexops/freetype/blob/bbd80a52b7b749140ec87d24b6c767c5063be356/freetype/src/base/ftutil.c#L135
null
else
self.handle.buffer[0..buffer_size];
}
};
pub const Outline = struct {
pub const Orientation = enum(u2) {
truetype = c.FT_ORIENTATION_TRUETYPE,
postscript = c.FT_ORIENTATION_POSTSCRIPT,
none = c.FT_ORIENTATION_NONE,
};
handle: *c.FT_Outline,
pub fn numPoints(self: Outline) u15 {
return @intCast(u15, self.handle.*.n_points);
}
pub fn numContours(self: Outline) u15 {
return @intCast(u15, self.handle.*.n_contours);
}
pub fn points(self: Outline) []const Vector {
return self.handle.*.points[0..self.numPoints()];
}
pub fn tags(self: Outline) []const u8 {
return self.handle.tags[0..@intCast(u15, self.handle.n_points)];
}
pub fn contours(self: Outline) []const i16 {
return self.handle.*.contours[0..self.numContours()];
}
pub fn flags(self: Outline) OutlineFlags {
return OutlineFlags.from(self.handle.*.flags);
}
pub fn copy(self: Outline) Error!Outline {
var o: c.FT_Outline = undefined;
try intToError(c.FT_Outline_Copy(self.handle, &o));
return Outline{ .handle = &o };
}
pub fn translate(self: Outline, x_offset: i32, y_offset: i32) void {
c.FT_Outline_Translate(self.handle, x_offset, y_offset);
}
pub fn transform(self: Outline, matrix: ?Matrix) void {
c.FT_Outline_Transform(self.handle, if (matrix) |m| &m else null);
}
pub fn embolden(self: Outline, strength: i32) Error!void {
try intToError(c.FT_Outline_Embolden(self.handle, strength));
}
pub fn emboldenXY(self: Outline, x_strength: i32, y_strength: i32) Error!void {
try intToError(c.FT_Outline_EmboldenXY(self.handle, x_strength, y_strength));
}
pub fn reverse(self: Outline) void {
c.FT_Outline_Reverse(self.handle);
}
pub fn check(self: Outline) Error!void {
try intToError(c.FT_Outline_Check(self.handle));
}
pub fn cbox(self: Outline) BBox {
var b: BBox = undefined;
c.FT_Outline_Get_CBox(self.handle, &b);
return b;
}
pub fn bbox(self: Outline) Error!BBox {
var b: BBox = undefined;
try intToError(c.FT_Outline_Get_BBox(self.handle, &b));
return b;
}
pub fn orientation(self: Outline) Orientation {
return @intToEnum(Orientation, c.FT_Outline_Get_Orientation(self.handle));
}
pub fn getInsideBorder(self: Outline) Stroker.Border {
return @intToEnum(Stroker.Border, c.FT_Outline_GetInsideBorder(self.handle));
}
pub fn getOutsideBorder(self: Outline) Stroker.Border {
return @intToEnum(Stroker.Border, c.FT_Outline_GetOutsideBorder(self.handle));
}
pub fn Funcs(comptime Context: type) type {
return struct {
move_to: if (builtin.zig_backend == .stage1 or builtin.zig_backend == .other) fn (ctx: Context, to: Vector) Error!void else *const fn (ctx: Context, to: Vector) Error!void,
line_to: if (builtin.zig_backend == .stage1 or builtin.zig_backend == .other) fn (ctx: Context, to: Vector) Error!void else *const fn (ctx: Context, to: Vector) Error!void,
conic_to: if (builtin.zig_backend == .stage1 or builtin.zig_backend == .other) fn (ctx: Context, control: Vector, to: Vector) Error!void else *const fn (ctx: Context, control: Vector, to: Vector) Error!void,
cubic_to: if (builtin.zig_backend == .stage1 or builtin.zig_backend == .other) fn (ctx: Context, control_0: Vector, control_1: Vector, to: Vector) Error!void else *const fn (ctx: Context, control_0: Vector, control_1: Vector, to: Vector) Error!void,
shift: i32,
delta: i32,
};
}
fn FuncsWrapper(comptime Context: type) type {
return struct {
const Self = @This();
ctx: Context,
callbacks: Funcs(Context),
fn getSelf(ptr: ?*anyopaque) *Self {
return @ptrCast(*Self, @alignCast(@alignOf(Self), ptr));
}
pub fn move_to(to: [*c]const c.FT_Vector, ctx: ?*anyopaque) callconv(.C) c_int {
const self = getSelf(ctx);
return if (self.callbacks.move_to(self.ctx, to.*)) |_|
0
else |err|
errorToInt(err);
}
pub fn line_to(to: [*c]const c.FT_Vector, ctx: ?*anyopaque) callconv(.C) c_int {
const self = getSelf(ctx);
return if (self.callbacks.line_to(self.ctx, to.*)) |_|
0
else |err|
errorToInt(err);
}
pub fn conic_to(
control: [*c]const c.FT_Vector,
to: [*c]const c.FT_Vector,
ctx: ?*anyopaque,
) callconv(.C) c_int {
const self = getSelf(ctx);
return if (self.callbacks.conic_to(
self.ctx,
control.*,
to.*,
)) |_|
0
else |err|
errorToInt(err);
}
pub fn cubic_to(
control_0: [*c]const c.FT_Vector,
control_1: [*c]const c.FT_Vector,
to: [*c]const c.FT_Vector,
ctx: ?*anyopaque,
) callconv(.C) c_int {
const self = getSelf(ctx);
return if (self.callbacks.cubic_to(
self.ctx,
control_0.*,
control_1.*,
to.*,
)) |_|
0
else |err|
errorToInt(err);
}
};
}
pub fn decompose(self: Outline, ctx: anytype, callbacks: Funcs(@TypeOf(ctx))) Error!void {
var wrapper = FuncsWrapper(@TypeOf(ctx)){ .ctx = ctx, .callbacks = callbacks };
try intToError(c.FT_Outline_Decompose(
self.handle,
&c.FT_Outline_Funcs{
.move_to = @TypeOf(wrapper).move_to,
.line_to = @TypeOf(wrapper).line_to,
.conic_to = @TypeOf(wrapper).conic_to,
.cubic_to = @TypeOf(wrapper).cubic_to,
.shift = callbacks.shift,
.delta = callbacks.delta,
},
&wrapper,
));
}
};
pub const OutlineFlags = packed struct {
none: bool = false,
owner: bool = false,
even_odd_fill: bool = false,
reverse_fill: bool = false,
ignore_dropouts: bool = false,
smart_dropouts: bool = false,
include_stubs: bool = false,
overlap: bool = false,
high_precision: bool = false,
single_pass: bool = false,
pub const Flag = enum(u21) {
none = c.FT_OUTLINE_NONE,
owner = c.FT_OUTLINE_OWNER,
even_odd_fill = c.FT_OUTLINE_EVEN_ODD_FILL,
reverse_fill = c.FT_OUTLINE_REVERSE_FILL,
ignore_dropouts = c.FT_OUTLINE_IGNORE_DROPOUTS,
smart_dropouts = c.FT_OUTLINE_SMART_DROPOUTS,
include_stubs = c.FT_OUTLINE_INCLUDE_STUBS,
overlap = c.FT_OUTLINE_OVERLAP,
high_precision = c.FT_OUTLINE_HIGH_PRECISION,
single_pass = c.FT_OUTLINE_SINGLE_PASS,
};
pub fn from(bits: c_int) OutlineFlags {
return utils.bitFieldsToStruct(OutlineFlags, Flag, bits);
}
pub fn cast(self: OutlineFlags) c_int {
return utils.structToBitFields(c_int, Flag, self);
}
};

View file

@ -0,0 +1,8 @@
const c = @import("c");
pub const LcdFilter = enum(u5) {
none = c.FT_LCD_FILTER_NONE,
default = c.FT_LCD_FILTER_DEFAULT,
light = c.FT_LCD_FILTER_LIGHT,
legacy = c.FT_LCD_FILTER_LEGACY,
};

106
libs/freetype/src/main.zig Normal file
View file

@ -0,0 +1,106 @@
pub usingnamespace @import("color.zig");
pub usingnamespace @import("freetype.zig");
pub usingnamespace @import("glyph.zig");
pub usingnamespace @import("image.zig");
pub usingnamespace @import("lcdfilter.zig");
pub usingnamespace @import("stroke.zig");
pub usingnamespace @import("types.zig");
pub usingnamespace @import("computations.zig");
pub usingnamespace @import("error.zig");
pub const harfbuzz = @import("harfbuzz/main.zig");
pub const c = @import("c");
const std = @import("std");
const testing = std.testing;
const ft = @import("freetype.zig");
// Remove once the stage2 compiler fixes pkg std not found
comptime {
_ = @import("utils");
}
test {
std.testing.refAllDeclsRecursive(@import("color.zig"));
std.testing.refAllDeclsRecursive(@import("error.zig"));
std.testing.refAllDeclsRecursive(@import("freetype.zig"));
std.testing.refAllDeclsRecursive(@import("glyph.zig"));
std.testing.refAllDeclsRecursive(@import("image.zig"));
std.testing.refAllDeclsRecursive(@import("lcdfilter.zig"));
std.testing.refAllDeclsRecursive(@import("stroke.zig"));
std.testing.refAllDeclsRecursive(@import("types.zig"));
std.testing.refAllDeclsRecursive(@import("computations.zig"));
std.testing.refAllDeclsRecursive(harfbuzz);
}
const firasans_font_path = thisDir() ++ "/../upstream/assets/FiraSans-Regular.ttf";
const firasans_font_data = @embedFile(thisDir() ++ "/../upstream/assets/FiraSans-Regular.ttf");
fn thisDir() []const u8 {
return std.fs.path.dirname(@src().file) orelse ".";
}
test "create face from file" {
const lib = try ft.Library.init();
_ = try lib.createFace(firasans_font_path, 0);
}
test "create face from memory" {
const lib = try ft.Library.init();
_ = try lib.createFaceMemory(firasans_font_data, 0);
}
test "create stroker" {
const lib = try ft.Library.init();
_ = try lib.createStroker();
}
test "load glyph" {
const lib = try ft.Library.init();
const face = try lib.createFace(firasans_font_path, 0);
try face.setPixelSizes(100, 100);
try face.setCharSize(10 * 10, 0, 72, 0);
try face.loadGlyph(205, .{});
try face.loadChar('A', .{});
face.deinit();
}
test "attach file" {
const lib = try ft.Library.init();
const face = try lib.createFace(comptime thisDir() ++ "/../upstream/assets/DejaVuSans.pfb", 0);
try face.attachFile(comptime thisDir() ++ "/../upstream/assets/DejaVuSans.pfm");
}
test "attach from memory" {
const lib = try ft.Library.init();
const face = try lib.createFace(comptime thisDir() ++ "/../upstream/assets/DejaVuSans.pfb", 0);
const file = @embedFile(comptime thisDir() ++ "/../upstream/assets/DejaVuSans.pfm");
try face.attachMemory(file);
}
test "charmap iterator" {
const lib = try ft.Library.init();
const face = try lib.createFace(firasans_font_path, 0);
var iterator = face.iterateCharmap();
var old_char: u32 = 0;
while (iterator.next()) |char| {
try testing.expect(old_char != char);
old_char = char;
}
}
test "get name index" {
const lib = try ft.Library.init();
const face = try lib.createFace(firasans_font_path, 0);
try testing.expectEqual(@as(u32, 1120), face.getNameIndex("summation").?);
}
test "get index name" {
const lib = try ft.Library.init();
const face = try lib.createFace(firasans_font_path, 0);
var buf: [32]u8 = undefined;
try face.getGlyphName(1120, &buf);
try testing.expectEqualStrings(std.mem.sliceTo(&buf, 0), "summation");
}

View file

@ -0,0 +1,88 @@
const c = @import("c");
const intToError = @import("error.zig").intToError;
const Error = @import("error.zig").Error;
const Outline = @import("image.zig").Outline;
const Vector = @import("image.zig").Vector;
pub const LineCap = enum(u2) {
butt = c.FT_STROKER_LINECAP_BUTT,
round = c.FT_STROKER_LINECAP_ROUND,
square = c.FT_STROKER_LINECAP_SQUARE,
};
pub const LineJoin = enum(u2) {
round = c.FT_STROKER_LINEJOIN_ROUND,
bevel = c.FT_STROKER_LINEJOIN_BEVEL,
miter_variable = c.FT_STROKER_LINEJOIN_MITER_VARIABLE,
miter_fixed = c.FT_STROKER_LINEJOIN_MITER_FIXED,
};
pub const Stroker = struct {
pub const Border = enum(u1) {
left,
right,
};
pub const BorderCounts = struct {
points: u32,
contours: u32,
};
handle: c.FT_Stroker,
pub fn set(self: Stroker, radius: i32, line_cap: LineCap, line_join: LineJoin, miter_limit: i32) void {
c.FT_Stroker_Set(self.handle, radius, @enumToInt(line_cap), @enumToInt(line_join), miter_limit);
}
pub fn rewind(self: Stroker) void {
c.FT_Stroker_Rewind(self.handle);
}
pub fn parseOutline(self: Stroker, outline: Outline, opened: bool) Error!void {
try intToError(c.FT_Stroker_ParseOutline(self.handle, outline.handle, if (opened) 1 else 0));
}
pub fn beginSubPath(self: Stroker, to: *Vector, open: bool) Error!void {
try intToError(c.FT_Stroker_BeginSubPath(self.handle, to, if (open) 1 else 0));
}
pub fn endSubPath(self: Stroker) Error!void {
try intToError(c.FT_Stroker_EndSubPath(self.handle));
}
pub fn lineTo(self: Stroker, to: *Vector) Error!void {
try intToError(c.FT_Stroker_LineTo(self.handle, to));
}
pub fn conicTo(self: Stroker, control: *Vector, to: *Vector) Error!void {
try intToError(c.FT_Stroker_ConicTo(self.handle, control, to));
}
pub fn cubicTo(self: Stroker, control_0: *Vector, control_1: *Vector, to: *Vector) Error!void {
try intToError(c.FT_Stroker_CubicTo(self.handle, control_0, control_1, to));
}
pub fn getBorderCounts(self: Stroker, border: Border) Error!BorderCounts {
var counts: BorderCounts = undefined;
try intToError(c.FT_Stroker_GetBorderCounts(self.handle, @enumToInt(border), &counts.points, &counts.contours));
return counts;
}
pub fn exportBorder(self: Stroker, border: Border, outline: *Outline) void {
c.FT_Stroker_ExportBorder(self.handle, @enumToInt(border), outline.handle);
}
pub fn getCounts(self: Stroker) Error!BorderCounts {
var counts: BorderCounts = undefined;
try intToError(c.FT_Stroker_GetCounts(self.handle, &counts.points, &counts.contours));
return counts;
}
pub fn exportAll(self: Stroker, outline: *Outline) void {
c.FT_Stroker_Export(self.handle, outline.handle);
}
pub fn deinit(self: Stroker) void {
c.FT_Stroker_Done(self.handle);
}
};

View file

@ -0,0 +1,5 @@
const c = @import("c");
pub const Matrix = c.FT_Matrix;
pub const Generic = c.FT_Generic;
pub const BBox = c.FT_BBox;

View file

@ -0,0 +1,21 @@
const std = @import("std");
pub fn structToBitFields(comptime IntType: type, comptime EnumDataType: type, flags: anytype) IntType {
var value: IntType = 0;
inline for (comptime std.meta.fieldNames(EnumDataType)) |field_name| {
if (@field(flags, field_name)) {
value |= @enumToInt(@field(EnumDataType, field_name));
}
}
return value;
}
pub fn bitFieldsToStruct(comptime StructType: type, comptime EnumDataType: type, flags: anytype) StructType {
var value = std.mem.zeroes(StructType);
inline for (comptime std.meta.fieldNames(EnumDataType)) |field_name| {
if (flags & (@enumToInt(@field(EnumDataType, field_name))) != 0) {
@field(value, field_name) = true;
}
}
return value;
}

@ -0,0 +1 @@
Subproject commit a0403e32fd2ac02bc32daafb4b354e54d43b6c10

2
libs/gamemode/.gitattributes vendored Normal file
View file

@ -0,0 +1,2 @@
* text=auto eol=lf
upstream/** linguist-vendored

1
libs/gamemode/.github/FUNDING.yml vendored Normal file
View file

@ -0,0 +1 @@
github: slimsag

View file

@ -0,0 +1,5 @@
Please send your change to [the main repository](https://github.com/hexops/mach/tree/main/gamemode) instead, sorry for the trouble!
This helps us avoid some complex merge conflicts we run into when changes are made to both repositories and history needs to be reconciled. Keeping PRs in just that repository enables us to use `git subtree` to trivially keep the two repositories in sync.
Once your PR is merged over there, it'll automatically sync to this repository.

18
libs/gamemode/.gitignore vendored Normal file
View file

@ -0,0 +1,18 @@
# This file is for zig-specific build artifacts.
# If you have OS-specific or editor-specific files to ignore,
# such as *.swp or .DS_Store, put those in your global
# ~/.gitignore and put this in your ~/.gitconfig:
#
# [core]
# excludesfile = ~/.gitignore
#
# Cheers!
# -andrewrk
zig-cache/
zig-out/
/release/
/debug/
/build/
/build-*/
/docgen_tmp/

13
libs/gamemode/LICENSE Normal file
View file

@ -0,0 +1,13 @@
Copyright 2021, Hexops Contributors (given via the Git commit history).
All documentation, image, sound, font, and 2D/3D model files are CC-BY-4.0 licensed unless
otherwise noted. You may get a copy of this license at https://creativecommons.org/licenses/by/4.0
Files in a directory with a separate LICENSE file may contain files under different license terms,
described within that LICENSE file.
All other files are licensed under the Apache License, Version 2.0 (see LICENSE-APACHE or http://www.apache.org/licenses/LICENSE-2.0)
or the MIT license (see LICENSE-MIT or http://opensource.org/licenses/MIT), at your option.
All files in the project without exclusions may not be copied, modified, or distributed except
according to the terms above.

View file

@ -0,0 +1,202 @@
Apache License
Version 2.0, January 2004
http://www.apache.org/licenses/
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
1. Definitions.
"License" shall mean the terms and conditions for use, reproduction,
and distribution as defined by Sections 1 through 9 of this document.
"Licensor" shall mean the copyright owner or entity authorized by
the copyright owner that is granting the License.
"Legal Entity" shall mean the union of the acting entity and all
other entities that control, are controlled by, or are under common
control with that entity. For the purposes of this definition,
"control" means (i) the power, direct or indirect, to cause the
direction or management of such entity, whether by contract or
otherwise, or (ii) ownership of fifty percent (50%) or more of the
outstanding shares, or (iii) beneficial ownership of such entity.
"You" (or "Your") shall mean an individual or Legal Entity
exercising permissions granted by this License.
"Source" form shall mean the preferred form for making modifications,
including but not limited to software source code, documentation
source, and configuration files.
"Object" form shall mean any form resulting from mechanical
transformation or translation of a Source form, including but
not limited to compiled object code, generated documentation,
and conversions to other media types.
"Work" shall mean the work of authorship, whether in Source or
Object form, made available under the License, as indicated by a
copyright notice that is included in or attached to the work
(an example is provided in the Appendix below).
"Derivative Works" shall mean any work, whether in Source or Object
form, that is based on (or derived from) the Work and for which the
editorial revisions, annotations, elaborations, or other modifications
represent, as a whole, an original work of authorship. For the purposes
of this License, Derivative Works shall not include works that remain
separable from, or merely link (or bind by name) to the interfaces of,
the Work and Derivative Works thereof.
"Contribution" shall mean any work of authorship, including
the original version of the Work and any modifications or additions
to that Work or Derivative Works thereof, that is intentionally
submitted to Licensor for inclusion in the Work by the copyright owner
or by an individual or Legal Entity authorized to submit on behalf of
the copyright owner. For the purposes of this definition, "submitted"
means any form of electronic, verbal, or written communication sent
to the Licensor or its representatives, including but not limited to
communication on electronic mailing lists, source code control systems,
and issue tracking systems that are managed by, or on behalf of, the
Licensor for the purpose of discussing and improving the Work, but
excluding communication that is conspicuously marked or otherwise
designated in writing by the copyright owner as "Not a Contribution."
"Contributor" shall mean Licensor and any individual or Legal Entity
on behalf of whom a Contribution has been received by Licensor and
subsequently incorporated within the Work.
2. Grant of Copyright License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
copyright license to reproduce, prepare Derivative Works of,
publicly display, publicly perform, sublicense, and distribute the
Work and such Derivative Works in Source or Object form.
3. Grant of Patent License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
(except as stated in this section) patent license to make, have made,
use, offer to sell, sell, import, and otherwise transfer the Work,
where such license applies only to those patent claims licensable
by such Contributor that are necessarily infringed by their
Contribution(s) alone or by combination of their Contribution(s)
with the Work to which such Contribution(s) was submitted. If You
institute patent litigation against any entity (including a
cross-claim or counterclaim in a lawsuit) alleging that the Work
or a Contribution incorporated within the Work constitutes direct
or contributory patent infringement, then any patent licenses
granted to You under this License for that Work shall terminate
as of the date such litigation is filed.
4. Redistribution. You may reproduce and distribute copies of the
Work or Derivative Works thereof in any medium, with or without
modifications, and in Source or Object form, provided that You
meet the following conditions:
(a) You must give any other recipients of the Work or
Derivative Works a copy of this License; and
(b) You must cause any modified files to carry prominent notices
stating that You changed the files; and
(c) You must retain, in the Source form of any Derivative Works
that You distribute, all copyright, patent, trademark, and
attribution notices from the Source form of the Work,
excluding those notices that do not pertain to any part of
the Derivative Works; and
(d) If the Work includes a "NOTICE" text file as part of its
distribution, then any Derivative Works that You distribute must
include a readable copy of the attribution notices contained
within such NOTICE file, excluding those notices that do not
pertain to any part of the Derivative Works, in at least one
of the following places: within a NOTICE text file distributed
as part of the Derivative Works; within the Source form or
documentation, if provided along with the Derivative Works; or,
within a display generated by the Derivative Works, if and
wherever such third-party notices normally appear. The contents
of the NOTICE file are for informational purposes only and
do not modify the License. You may add Your own attribution
notices within Derivative Works that You distribute, alongside
or as an addendum to the NOTICE text from the Work, provided
that such additional attribution notices cannot be construed
as modifying the License.
You may add Your own copyright statement to Your modifications and
may provide additional or different license terms and conditions
for use, reproduction, or distribution of Your modifications, or
for any such Derivative Works as a whole, provided Your use,
reproduction, and distribution of the Work otherwise complies with
the conditions stated in this License.
5. Submission of Contributions. Unless You explicitly state otherwise,
any Contribution intentionally submitted for inclusion in the Work
by You to the Licensor shall be under the terms and conditions of
this License, without any additional terms or conditions.
Notwithstanding the above, nothing herein shall supersede or modify
the terms of any separate license agreement you may have executed
with Licensor regarding such Contributions.
6. Trademarks. This License does not grant permission to use the trade
names, trademarks, service marks, or product names of the Licensor,
except as required for reasonable and customary use in describing the
origin of the Work and reproducing the content of the NOTICE file.
7. Disclaimer of Warranty. Unless required by applicable law or
agreed to in writing, Licensor provides the Work (and each
Contributor provides its Contributions) on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
implied, including, without limitation, any warranties or conditions
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
PARTICULAR PURPOSE. You are solely responsible for determining the
appropriateness of using or redistributing the Work and assume any
risks associated with Your exercise of permissions under this License.
8. Limitation of Liability. In no event and under no legal theory,
whether in tort (including negligence), contract, or otherwise,
unless required by applicable law (such as deliberate and grossly
negligent acts) or agreed to in writing, shall any Contributor be
liable to You for damages, including any direct, indirect, special,
incidental, or consequential damages of any character arising as a
result of this License or out of the use or inability to use the
Work (including but not limited to damages for loss of goodwill,
work stoppage, computer failure or malfunction, or any and all
other commercial damages or losses), even if such Contributor
has been advised of the possibility of such damages.
9. Accepting Warranty or Additional Liability. While redistributing
the Work or Derivative Works thereof, You may choose to offer,
and charge a fee for, acceptance of support, warranty, indemnity,
or other liability obligations and/or rights consistent with this
License. However, in accepting such obligations, You may act only
on Your own behalf and on Your sole responsibility, not on behalf
of any other Contributor, and only if You agree to indemnify,
defend, and hold each Contributor harmless for any liability
incurred by, or claims asserted against, such Contributor by reason
of your accepting any such warranty or additional liability.
END OF TERMS AND CONDITIONS
APPENDIX: How to apply the Apache License to your work.
To apply the Apache License to your work, attach the following
boilerplate notice, with the fields enclosed by brackets "[]"
replaced with your own identifying information. (Don't include
the brackets!) The text should be enclosed in the appropriate
comment syntax for the file format. We also recommend that a
file or class name and description of purpose be included on the
same "printed page" as the copyright notice for easier
identification within third-party archives.
Copyright [yyyy] [name of copyright owner]
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.

25
libs/gamemode/LICENSE-MIT Normal file
View file

@ -0,0 +1,25 @@
Copyright (c) 2021 Hexops Contributors (given via the Git commit history).
Permission is hereby granted, free of charge, to any
person obtaining a copy of this software and associated
documentation files (the "Software"), to deal in the
Software without restriction, including without
limitation the rights to use, copy, modify, merge,
publish, distribute, sublicense, and/or sell copies of
the Software, and to permit persons to whom the Software
is furnished to do so, subject to the following
conditions:
The above copyright notice and this permission notice
shall be included in all copies or substantial portions
of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF
ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED
TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A
PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT
SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR
IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
DEALINGS IN THE SOFTWARE.

View file

@ -0,0 +1,6 @@
#!/usr/bin/env bash
rm ./gamemode/gamemode_client.h
wget --output-document ./gamemode/gamemode_client.h "https://github.com/FeralInteractive/gamemode/raw/master/lib/gamemode_client.h"
# The output from translate-c isn't perfect, so we need this fix
zig translate-c ./gamemode/gamemode_client.h -lc | sed "s#functor\(.*\)@alignCast\(.*\),\(.*\))#functor\1\3#" > ./gamemode_client.zig

View file

@ -0,0 +1,76 @@
//! Note: All the above requests can be blocking - dbus requests can and will block while the daemon
//! handles the request. It is not recommended to make these calls in performance critical code
pub const c = @import("gamemode_client.zig");
pub const GamemodeError = error{
RequestFailed,
RequestRejected,
QueryFailed,
};
pub const GamemodeStatus = enum(c_int) {
Inactive = 0,
Active = 1,
/// Gamemode is active and the client is registered
ActiveAndRegistered = 2,
};
/// Request gamemode starts
pub fn requestStart() GamemodeError!void {
if (c.gamemode_request_start() == -1)
return GamemodeError.RequestFailed;
}
/// Request gamemode ends
pub fn requestEnd() GamemodeError!void {
if (c.gamemode_request_end() == -1)
return GamemodeError.RequestFailed;
}
/// Query the current status of gamemode
pub fn queryStatus() GamemodeError!GamemodeStatus {
const status = c.gamemode_query_status();
if (status == -1)
return GamemodeError.QueryFailed;
return @intToEnum(GamemodeStatus, status);
}
/// Request gamemode starts for another process
pub fn requestStartFor(pid: c.pid_t) GamemodeError!void {
const res = c.gamemode_request_start_for(pid);
if (res == 0) {
return;
} else if (res == -1) {
return GamemodeError.RequestFailed;
} else if (res == -2) {
return GamemodeError.RequestRejected;
}
}
/// Request gamemode ends for another process
pub fn requestEndFor(pid: c.pid_t) GamemodeError!void {
const res = c.gamemode_request_end_for(pid);
if (res == 0) {
return;
} else if (res == -1) {
return GamemodeError.RequestFailed;
} else if (res == -2) {
return GamemodeError.RequestRejected;
}
}
/// Query the current status of gamemode for another process
pub fn queryStatusFor(pid: c.pid_t) GamemodeError!GamemodeStatus {
const status = c.gamemode_query_status_for(pid);
if (status == -1)
return GamemodeError.QueryFailed;
return @intToEnum(GamemodeStatus, status);
}
/// Get an error string
pub fn errorString() []const u8 {
return @import("std").mem.sliceTo(c.gamemode_error_string(), 0);
}

View file

@ -0,0 +1,26 @@
Copyright (c) 2017-2022, Feral Interactive
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
* Redistributions of source code must retain the above copyright notice,
this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in the
documentation and/or other materials provided with the distribution.
* Neither the name of Feral Interactive nor the names of its contributors
may be used to endorse or promote products derived from this software
without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
POSSIBILITY OF SUCH DAMAGE.

View file

@ -0,0 +1,376 @@
/*
Copyright (c) 2017-2019, Feral Interactive
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
* Redistributions of source code must retain the above copyright notice,
this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in the
documentation and/or other materials provided with the distribution.
* Neither the name of Feral Interactive nor the names of its contributors
may be used to endorse or promote products derived from this software
without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
POSSIBILITY OF SUCH DAMAGE.
*/
#ifndef CLIENT_GAMEMODE_H
#define CLIENT_GAMEMODE_H
/*
* GameMode supports the following client functions
* Requests are refcounted in the daemon
*
* int gamemode_request_start() - Request gamemode starts
* 0 if the request was sent successfully
* -1 if the request failed
*
* int gamemode_request_end() - Request gamemode ends
* 0 if the request was sent successfully
* -1 if the request failed
*
* GAMEMODE_AUTO can be defined to make the above two functions apply during static init and
* destruction, as appropriate. In this configuration, errors will be printed to stderr
*
* int gamemode_query_status() - Query the current status of gamemode
* 0 if gamemode is inactive
* 1 if gamemode is active
* 2 if gamemode is active and this client is registered
* -1 if the query failed
*
* int gamemode_request_start_for(pid_t pid) - Request gamemode starts for another process
* 0 if the request was sent successfully
* -1 if the request failed
* -2 if the request was rejected
*
* int gamemode_request_end_for(pid_t pid) - Request gamemode ends for another process
* 0 if the request was sent successfully
* -1 if the request failed
* -2 if the request was rejected
*
* int gamemode_query_status_for(pid_t pid) - Query status of gamemode for another process
* 0 if gamemode is inactive
* 1 if gamemode is active
* 2 if gamemode is active and this client is registered
* -1 if the query failed
*
* const char* gamemode_error_string() - Get an error string
* returns a string describing any of the above errors
*
* Note: All the above requests can be blocking - dbus requests can and will block while the daemon
* handles the request. It is not recommended to make these calls in performance critical code
*/
#include <stdbool.h>
#include <stdio.h>
#include <dlfcn.h>
#include <string.h>
#include <assert.h>
#include <sys/types.h>
static char internal_gamemode_client_error_string[512] = { 0 };
/**
* Load libgamemode dynamically to dislodge us from most dependencies.
* This allows clients to link and/or use this regardless of runtime.
* See SDL2 for an example of the reasoning behind this in terms of
* dynamic versioning as well.
*/
static volatile int internal_libgamemode_loaded = 1;
/* Typedefs for the functions to load */
typedef int (*api_call_return_int)(void);
typedef const char *(*api_call_return_cstring)(void);
typedef int (*api_call_pid_return_int)(pid_t);
/* Storage for functors */
static api_call_return_int REAL_internal_gamemode_request_start = NULL;
static api_call_return_int REAL_internal_gamemode_request_end = NULL;
static api_call_return_int REAL_internal_gamemode_query_status = NULL;
static api_call_return_cstring REAL_internal_gamemode_error_string = NULL;
static api_call_pid_return_int REAL_internal_gamemode_request_start_for = NULL;
static api_call_pid_return_int REAL_internal_gamemode_request_end_for = NULL;
static api_call_pid_return_int REAL_internal_gamemode_query_status_for = NULL;
/**
* Internal helper to perform the symbol binding safely.
*
* Returns 0 on success and -1 on failure
*/
__attribute__((always_inline)) static inline int internal_bind_libgamemode_symbol(
void *handle, const char *name, void **out_func, size_t func_size, bool required)
{
void *symbol_lookup = NULL;
char *dl_error = NULL;
/* Safely look up the symbol */
symbol_lookup = dlsym(handle, name);
dl_error = dlerror();
if (required && (dl_error || !symbol_lookup)) {
snprintf(internal_gamemode_client_error_string,
sizeof(internal_gamemode_client_error_string),
"dlsym failed - %s",
dl_error);
return -1;
}
/* Have the symbol correctly, copy it to make it usable */
memcpy(out_func, &symbol_lookup, func_size);
return 0;
}
/**
* Loads libgamemode and needed functions
*
* Returns 0 on success and -1 on failure
*/
__attribute__((always_inline)) static inline int internal_load_libgamemode(void)
{
/* We start at 1, 0 is a success and -1 is a fail */
if (internal_libgamemode_loaded != 1) {
return internal_libgamemode_loaded;
}
/* Anonymous struct type to define our bindings */
struct binding {
const char *name;
void **functor;
size_t func_size;
bool required;
} bindings[] = {
{ "real_gamemode_request_start",
(void **)&REAL_internal_gamemode_request_start,
sizeof(REAL_internal_gamemode_request_start),
true },
{ "real_gamemode_request_end",
(void **)&REAL_internal_gamemode_request_end,
sizeof(REAL_internal_gamemode_request_end),
true },
{ "real_gamemode_query_status",
(void **)&REAL_internal_gamemode_query_status,
sizeof(REAL_internal_gamemode_query_status),
false },
{ "real_gamemode_error_string",
(void **)&REAL_internal_gamemode_error_string,
sizeof(REAL_internal_gamemode_error_string),
true },
{ "real_gamemode_request_start_for",
(void **)&REAL_internal_gamemode_request_start_for,
sizeof(REAL_internal_gamemode_request_start_for),
false },
{ "real_gamemode_request_end_for",
(void **)&REAL_internal_gamemode_request_end_for,
sizeof(REAL_internal_gamemode_request_end_for),
false },
{ "real_gamemode_query_status_for",
(void **)&REAL_internal_gamemode_query_status_for,
sizeof(REAL_internal_gamemode_query_status_for),
false },
};
void *libgamemode = NULL;
/* Try and load libgamemode */
libgamemode = dlopen("libgamemode.so.0", RTLD_NOW);
if (!libgamemode) {
/* Attempt to load unversioned library for compatibility with older
* versions (as of writing, there are no ABI changes between the two -
* this may need to change if ever ABI-breaking changes are made) */
libgamemode = dlopen("libgamemode.so", RTLD_NOW);
if (!libgamemode) {
snprintf(internal_gamemode_client_error_string,
sizeof(internal_gamemode_client_error_string),
"dlopen failed - %s",
dlerror());
internal_libgamemode_loaded = -1;
return -1;
}
}
/* Attempt to bind all symbols */
for (size_t i = 0; i < sizeof(bindings) / sizeof(bindings[0]); i++) {
struct binding *binder = &bindings[i];
if (internal_bind_libgamemode_symbol(libgamemode,
binder->name,
binder->functor,
binder->func_size,
binder->required)) {
internal_libgamemode_loaded = -1;
return -1;
};
}
/* Success */
internal_libgamemode_loaded = 0;
return 0;
}
/**
* Redirect to the real libgamemode
*/
__attribute__((always_inline)) static inline const char *gamemode_error_string(void)
{
/* If we fail to load the system gamemode, or we have an error string already, return our error
* string instead of diverting to the system version */
if (internal_load_libgamemode() < 0 || internal_gamemode_client_error_string[0] != '\0') {
return internal_gamemode_client_error_string;
}
/* Assert for static analyser that the function is not NULL */
assert(REAL_internal_gamemode_error_string != NULL);
return REAL_internal_gamemode_error_string();
}
/**
* Redirect to the real libgamemode
* Allow automatically requesting game mode
* Also prints errors as they happen.
*/
#ifdef GAMEMODE_AUTO
__attribute__((constructor))
#else
__attribute__((always_inline)) static inline
#endif
int gamemode_request_start(void)
{
/* Need to load gamemode */
if (internal_load_libgamemode() < 0) {
#ifdef GAMEMODE_AUTO
fprintf(stderr, "gamemodeauto: %s\n", gamemode_error_string());
#endif
return -1;
}
/* Assert for static analyser that the function is not NULL */
assert(REAL_internal_gamemode_request_start != NULL);
if (REAL_internal_gamemode_request_start() < 0) {
#ifdef GAMEMODE_AUTO
fprintf(stderr, "gamemodeauto: %s\n", gamemode_error_string());
#endif
return -1;
}
return 0;
}
/* Redirect to the real libgamemode */
#ifdef GAMEMODE_AUTO
__attribute__((destructor))
#else
__attribute__((always_inline)) static inline
#endif
int gamemode_request_end(void)
{
/* Need to load gamemode */
if (internal_load_libgamemode() < 0) {
#ifdef GAMEMODE_AUTO
fprintf(stderr, "gamemodeauto: %s\n", gamemode_error_string());
#endif
return -1;
}
/* Assert for static analyser that the function is not NULL */
assert(REAL_internal_gamemode_request_end != NULL);
if (REAL_internal_gamemode_request_end() < 0) {
#ifdef GAMEMODE_AUTO
fprintf(stderr, "gamemodeauto: %s\n", gamemode_error_string());
#endif
return -1;
}
return 0;
}
/* Redirect to the real libgamemode */
__attribute__((always_inline)) static inline int gamemode_query_status(void)
{
/* Need to load gamemode */
if (internal_load_libgamemode() < 0) {
return -1;
}
if (REAL_internal_gamemode_query_status == NULL) {
snprintf(internal_gamemode_client_error_string,
sizeof(internal_gamemode_client_error_string),
"gamemode_query_status missing (older host?)");
return -1;
}
return REAL_internal_gamemode_query_status();
}
/* Redirect to the real libgamemode */
__attribute__((always_inline)) static inline int gamemode_request_start_for(pid_t pid)
{
/* Need to load gamemode */
if (internal_load_libgamemode() < 0) {
return -1;
}
if (REAL_internal_gamemode_request_start_for == NULL) {
snprintf(internal_gamemode_client_error_string,
sizeof(internal_gamemode_client_error_string),
"gamemode_request_start_for missing (older host?)");
return -1;
}
return REAL_internal_gamemode_request_start_for(pid);
}
/* Redirect to the real libgamemode */
__attribute__((always_inline)) static inline int gamemode_request_end_for(pid_t pid)
{
/* Need to load gamemode */
if (internal_load_libgamemode() < 0) {
return -1;
}
if (REAL_internal_gamemode_request_end_for == NULL) {
snprintf(internal_gamemode_client_error_string,
sizeof(internal_gamemode_client_error_string),
"gamemode_request_end_for missing (older host?)");
return -1;
}
return REAL_internal_gamemode_request_end_for(pid);
}
/* Redirect to the real libgamemode */
__attribute__((always_inline)) static inline int gamemode_query_status_for(pid_t pid)
{
/* Need to load gamemode */
if (internal_load_libgamemode() < 0) {
return -1;
}
if (REAL_internal_gamemode_query_status_for == NULL) {
snprintf(internal_gamemode_client_error_string,
sizeof(internal_gamemode_client_error_string),
"gamemode_query_status_for missing (older host?)");
return -1;
}
return REAL_internal_gamemode_query_status_for(pid);
}
#endif // CLIENT_GAMEMODE_H

File diff suppressed because it is too large Load diff

2
libs/glfw/.gitattributes vendored Normal file
View file

@ -0,0 +1,2 @@
* text=auto eol=lf
upstream/** linguist-vendored

1
libs/glfw/.github/FUNDING.yml vendored Normal file
View file

@ -0,0 +1 @@
github: slimsag

View file

@ -0,0 +1,5 @@
Please send your change to [the main repository](https://github.com/hexops/mach/tree/main/glfw) instead, sorry for the trouble!
This helps us avoid some complex merge conflicts we run into when changes are made to both repositories and history needs to be reconciled. Keeping PRs in just that repository enables us to use `git subtree` to trivially keep the two repositories in sync.
Once your PR is merged over there, it'll automatically sync to this repository.

91
libs/glfw/.github/workflows/ci.yml vendored Normal file
View file

@ -0,0 +1,91 @@
name: CI
on:
- push
- pull_request
jobs:
x86_64-linux:
runs-on: ubuntu-latest
# We want to run on external PRs, but not on our own internal PRs as they'll be run by the push
# to the branch.
if: github.event_name == 'push' || github.event.pull_request.head.repo.full_name != github.repository
env:
DISPLAY: ':99.0'
steps:
- name: Checkout
uses: actions/checkout@v2
- name: Setup Zig
run: |
sudo apt install xz-utils
sudo sh -c 'wget -c https://ziglang.org/builds/zig-linux-x86_64-0.10.0-dev.3551+92568a009.tar.xz -O - | tar -xJ --strip-components=1 -C /usr/local/bin'
- name: x86_64-linux -> x86_64-macos
run: zig build test -Dtarget=x86_64-macos
env:
AGREE: true
- name: x86_64-linux -> aarch64-macos
run: zig build test -Dtarget=aarch64-macos
env:
AGREE: true
- name: x86_64-linux -> x86_64-windows
run: zig build test -Dtarget=x86_64-windows
- name: launch xvfb
run: Xvfb :99 -screen 0 1680x720x24 > /dev/null 2>&1 &
- name: test
run: |
sudo add-apt-repository -y ppa:kisak/kisak-mesa
sudo apt-get update
sudo apt-get install mesa-utils mesa-utils-extra mesa-va-drivers mesa-vdpau-drivers mesa-vulkan-drivers xvfb
zig build test
x86_64-windows:
runs-on: windows-latest
# We want to run on external PRs, but not on our own internal PRs as they'll be run by the push
# to the branch.
if: github.event_name == 'push' || github.event.pull_request.head.repo.full_name != github.repository
steps:
- name: Checkout
uses: actions/checkout@v2
- name: Install Git
run: choco install git
- name: Setup Zig
run: |
$ProgressPreference = 'SilentlyContinue'
Invoke-WebRequest -Uri "https://ziglang.org/builds/zig-windows-x86_64-0.10.0-dev.3551+92568a009.zip" -OutFile "C:\zig.zip"
cd C:\
7z x zig.zip
Add-Content $env:GITHUB_PATH "C:\zig-windows-x86_64-0.10.0-dev.3551+92568a009\"
- name: x86_64-windows -> x86_64-macos
run: zig build test -Dtarget=x86_64-macos
env:
AGREE: true
- name: x86_64-windows -> aarch64-macos
run: zig build test -Dtarget=aarch64-macos
env:
AGREE: true
- name: x86_64-windows -> x86_64-linux
run: zig build test -Dtarget=x86_64-linux
- name: test
run: zig build test
x86_64-macos:
runs-on: macos-12
# We want to run on external PRs, but not on our own internal PRs as they'll be run by the push
# to the branch.
if: github.event_name == 'push' || github.event.pull_request.head.repo.full_name != github.repository
steps:
- name: Checkout
uses: actions/checkout@v2
- name: Setup Zig
run: |
brew uninstall --ignore-dependencies libx11 # https://github.com/ziglang/zig/issues/11066
brew install xz
sudo sh -c 'wget -c https://ziglang.org/builds/zig-macos-x86_64-0.10.0-dev.3551+92568a009.tar.xz -O - | tar -xJ --strip-components=1 -C /usr/local/bin'
- name: test
run: zig build test
env:
AGREE: true
- name: x86_64-macos -> aarch64-macos
run: zig build test -Dtarget=aarch64-macos
env:
AGREE: true
- name: x86_64-macos -> x86_64-windows
run: zig build test -Dtarget=x86_64-windows
- name: x86_64-macos -> x86_64-linux
run: zig build test -Dtarget=x86_64-linux

39
libs/glfw/.github/workflows/m1_ci.yml vendored Normal file
View file

@ -0,0 +1,39 @@
name: M1
on:
# SECURITY: This must be a push event only, otherwise our M1 mac runner would be compromised by
# third-party pull requests which could run arbitrary code. This way, we can restrict it to
# collaborators of the repository only.
#
# Whenever GitHub Actions gets official M1 support, we can use that for PRs and get rid of this
# self-hosted runner: https://github.com/actions/virtual-environments/issues/2187
- push
jobs:
aarch64-macos:
if: ${{ github.repository == 'hexops/mach-glfw' }}
runs-on: [self-hosted, macOS, ARM64]
defaults:
run:
shell: "/usr/bin/arch -arch arm64e /bin/bash --noprofile --norc -eo pipefail {0}"
steps:
- name: Clean repository submodules
# See https://github.com/actions/checkout/issues/385
run: |
rm -rf $GITHUB_WORKSPACE && mkdir $GITHUB_WORKSPACE
- name: Checkout
uses: actions/checkout@v2
- name: Setup Zig
run: |
sudo rm -rf /usr/local/bin/zig /usr/local/bin/lib/
sudo sh -c 'wget -c https://ziglang.org/builds/zig-macos-aarch64-0.10.0-dev.3551+92568a009.tar.xz -O - | tar -xJ --strip-components=1 -C /usr/local/bin'
- name: test
run: zig build test
env:
AGREE: true
- name: aarch64-macos -> x86_64-macos
run: zig build test -Dtarget=x86_64-macos
env:
AGREE: true
- name: aarch64-macos -> x86_64-windows
run: zig build test -Dtarget=x86_64-windows
- name: aarch64-macos -> x86_64-linux
run: zig build test -Dtarget=x86_64-linux

18
libs/glfw/.gitignore vendored Normal file
View file

@ -0,0 +1,18 @@
# This file is for zig-specific build artifacts.
# If you have OS-specific or editor-specific files to ignore,
# such as *.swp or .DS_Store, put those in your global
# ~/.gitignore and put this in your ~/.gitconfig:
#
# [core]
# excludesfile = ~/.gitignore
#
# Cheers!
# -andrewrk
zig-cache/
zig-out/
/release/
/debug/
/build/
/build-*/
/docgen_tmp/

4
libs/glfw/.gitmodules vendored Normal file
View file

@ -0,0 +1,4 @@
[submodule "upstream"]
path = upstream
url = https://github.com/hexops/glfw

13
libs/glfw/LICENSE Normal file
View file

@ -0,0 +1,13 @@
Copyright 2021, Hexops Contributors (given via the Git commit history).
All documentation, image, sound, font, and 2D/3D model files are CC-BY-4.0 licensed unless
otherwise noted. You may get a copy of this license at https://creativecommons.org/licenses/by/4.0
Files in a directory with a separate LICENSE file may contain files under different license terms,
described within that LICENSE file.
All other files are licensed under the Apache License, Version 2.0 (see LICENSE-APACHE or http://www.apache.org/licenses/LICENSE-2.0)
or the MIT license (see LICENSE-MIT or http://opensource.org/licenses/MIT), at your option.
All files in the project without exclusions may not be copied, modified, or distributed except
according to the terms above.

202
libs/glfw/LICENSE-APACHE Normal file
View file

@ -0,0 +1,202 @@
Apache License
Version 2.0, January 2004
http://www.apache.org/licenses/
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
1. Definitions.
"License" shall mean the terms and conditions for use, reproduction,
and distribution as defined by Sections 1 through 9 of this document.
"Licensor" shall mean the copyright owner or entity authorized by
the copyright owner that is granting the License.
"Legal Entity" shall mean the union of the acting entity and all
other entities that control, are controlled by, or are under common
control with that entity. For the purposes of this definition,
"control" means (i) the power, direct or indirect, to cause the
direction or management of such entity, whether by contract or
otherwise, or (ii) ownership of fifty percent (50%) or more of the
outstanding shares, or (iii) beneficial ownership of such entity.
"You" (or "Your") shall mean an individual or Legal Entity
exercising permissions granted by this License.
"Source" form shall mean the preferred form for making modifications,
including but not limited to software source code, documentation
source, and configuration files.
"Object" form shall mean any form resulting from mechanical
transformation or translation of a Source form, including but
not limited to compiled object code, generated documentation,
and conversions to other media types.
"Work" shall mean the work of authorship, whether in Source or
Object form, made available under the License, as indicated by a
copyright notice that is included in or attached to the work
(an example is provided in the Appendix below).
"Derivative Works" shall mean any work, whether in Source or Object
form, that is based on (or derived from) the Work and for which the
editorial revisions, annotations, elaborations, or other modifications
represent, as a whole, an original work of authorship. For the purposes
of this License, Derivative Works shall not include works that remain
separable from, or merely link (or bind by name) to the interfaces of,
the Work and Derivative Works thereof.
"Contribution" shall mean any work of authorship, including
the original version of the Work and any modifications or additions
to that Work or Derivative Works thereof, that is intentionally
submitted to Licensor for inclusion in the Work by the copyright owner
or by an individual or Legal Entity authorized to submit on behalf of
the copyright owner. For the purposes of this definition, "submitted"
means any form of electronic, verbal, or written communication sent
to the Licensor or its representatives, including but not limited to
communication on electronic mailing lists, source code control systems,
and issue tracking systems that are managed by, or on behalf of, the
Licensor for the purpose of discussing and improving the Work, but
excluding communication that is conspicuously marked or otherwise
designated in writing by the copyright owner as "Not a Contribution."
"Contributor" shall mean Licensor and any individual or Legal Entity
on behalf of whom a Contribution has been received by Licensor and
subsequently incorporated within the Work.
2. Grant of Copyright License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
copyright license to reproduce, prepare Derivative Works of,
publicly display, publicly perform, sublicense, and distribute the
Work and such Derivative Works in Source or Object form.
3. Grant of Patent License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
(except as stated in this section) patent license to make, have made,
use, offer to sell, sell, import, and otherwise transfer the Work,
where such license applies only to those patent claims licensable
by such Contributor that are necessarily infringed by their
Contribution(s) alone or by combination of their Contribution(s)
with the Work to which such Contribution(s) was submitted. If You
institute patent litigation against any entity (including a
cross-claim or counterclaim in a lawsuit) alleging that the Work
or a Contribution incorporated within the Work constitutes direct
or contributory patent infringement, then any patent licenses
granted to You under this License for that Work shall terminate
as of the date such litigation is filed.
4. Redistribution. You may reproduce and distribute copies of the
Work or Derivative Works thereof in any medium, with or without
modifications, and in Source or Object form, provided that You
meet the following conditions:
(a) You must give any other recipients of the Work or
Derivative Works a copy of this License; and
(b) You must cause any modified files to carry prominent notices
stating that You changed the files; and
(c) You must retain, in the Source form of any Derivative Works
that You distribute, all copyright, patent, trademark, and
attribution notices from the Source form of the Work,
excluding those notices that do not pertain to any part of
the Derivative Works; and
(d) If the Work includes a "NOTICE" text file as part of its
distribution, then any Derivative Works that You distribute must
include a readable copy of the attribution notices contained
within such NOTICE file, excluding those notices that do not
pertain to any part of the Derivative Works, in at least one
of the following places: within a NOTICE text file distributed
as part of the Derivative Works; within the Source form or
documentation, if provided along with the Derivative Works; or,
within a display generated by the Derivative Works, if and
wherever such third-party notices normally appear. The contents
of the NOTICE file are for informational purposes only and
do not modify the License. You may add Your own attribution
notices within Derivative Works that You distribute, alongside
or as an addendum to the NOTICE text from the Work, provided
that such additional attribution notices cannot be construed
as modifying the License.
You may add Your own copyright statement to Your modifications and
may provide additional or different license terms and conditions
for use, reproduction, or distribution of Your modifications, or
for any such Derivative Works as a whole, provided Your use,
reproduction, and distribution of the Work otherwise complies with
the conditions stated in this License.
5. Submission of Contributions. Unless You explicitly state otherwise,
any Contribution intentionally submitted for inclusion in the Work
by You to the Licensor shall be under the terms and conditions of
this License, without any additional terms or conditions.
Notwithstanding the above, nothing herein shall supersede or modify
the terms of any separate license agreement you may have executed
with Licensor regarding such Contributions.
6. Trademarks. This License does not grant permission to use the trade
names, trademarks, service marks, or product names of the Licensor,
except as required for reasonable and customary use in describing the
origin of the Work and reproducing the content of the NOTICE file.
7. Disclaimer of Warranty. Unless required by applicable law or
agreed to in writing, Licensor provides the Work (and each
Contributor provides its Contributions) on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
implied, including, without limitation, any warranties or conditions
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
PARTICULAR PURPOSE. You are solely responsible for determining the
appropriateness of using or redistributing the Work and assume any
risks associated with Your exercise of permissions under this License.
8. Limitation of Liability. In no event and under no legal theory,
whether in tort (including negligence), contract, or otherwise,
unless required by applicable law (such as deliberate and grossly
negligent acts) or agreed to in writing, shall any Contributor be
liable to You for damages, including any direct, indirect, special,
incidental, or consequential damages of any character arising as a
result of this License or out of the use or inability to use the
Work (including but not limited to damages for loss of goodwill,
work stoppage, computer failure or malfunction, or any and all
other commercial damages or losses), even if such Contributor
has been advised of the possibility of such damages.
9. Accepting Warranty or Additional Liability. While redistributing
the Work or Derivative Works thereof, You may choose to offer,
and charge a fee for, acceptance of support, warranty, indemnity,
or other liability obligations and/or rights consistent with this
License. However, in accepting such obligations, You may act only
on Your own behalf and on Your sole responsibility, not on behalf
of any other Contributor, and only if You agree to indemnify,
defend, and hold each Contributor harmless for any liability
incurred by, or claims asserted against, such Contributor by reason
of your accepting any such warranty or additional liability.
END OF TERMS AND CONDITIONS
APPENDIX: How to apply the Apache License to your work.
To apply the Apache License to your work, attach the following
boilerplate notice, with the fields enclosed by brackets "[]"
replaced with your own identifying information. (Don't include
the brackets!) The text should be enclosed in the appropriate
comment syntax for the file format. We also recommend that a
file or class name and description of purpose be included on the
same "printed page" as the copyright notice for easier
identification within third-party archives.
Copyright [yyyy] [name of copyright owner]
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.

25
libs/glfw/LICENSE-MIT Normal file
View file

@ -0,0 +1,25 @@
Copyright (c) 2021 Hexops Contributors (given via the Git commit history).
Permission is hereby granted, free of charge, to any
person obtaining a copy of this software and associated
documentation files (the "Software"), to deal in the
Software without restriction, including without
limitation the rights to use, copy, modify, merge,
publish, distribute, sublicense, and/or sell copies of
the Software, and to permit persons to whom the Software
is furnished to do so, subject to the following
conditions:
The above copyright notice and this permission notice
shall be included in all copies or substantial portions
of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF
ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED
TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A
PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT
SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR
IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
DEALINGS IN THE SOFTWARE.

155
libs/glfw/README.md Normal file
View file

@ -0,0 +1,155 @@
# mach/glfw - Ziggified GLFW bindings [![CI](https://github.com/hexops/mach-glfw/workflows/CI/badge.svg)](https://github.com/hexops/mach-glfw/actions) <a href="https://hexops.com"><img align="right" alt="Hexops logo" src="https://raw.githubusercontent.com/hexops/media/main/readme.svg"></img></a>
Ziggified GLFW bindings that [Mach engine](https://github.com/hexops/mach) uses, with 100% API coverage, zero-fuss installation, cross compilation, and more.
This repository is a separate copy of the same library in the [main Mach repository](https://github.com/hexops/mach), and is automatically kept in sync, so that anyone can use this library in their own project / engine if they like!
## Zero fuss installation, cross compilation, and more
[Just as with Mach](https://github.com/hexops/mach#zero-fuss-installation--cross-compilation), you get zero fuss installation & cross compilation using these GLFW bindings. **only `zig` and `git` are needed to build from any OS and produce binaries for every OS.** No system dependencies at all.
## 100% API coverage, 130+ tests, etc.
These bindings have 100% API coverage of GLFW v3.3.4. Every function, type, constant, etc. has been wrapped in a ziggified API.
There are 130+ tests, and CI tests on all major platforms as well as cross-compilation between platforms:
[platform support table](https://github.com/hexops/mach#supported-platforms)
## What does a ziggified GLFW API offer?
Why create a ziggified GLFW wrapper, instead of just using `@cImport` and interfacing with GLFW directly? You get:
* Errors as [zig errors](https://ziglang.org/documentation/master/#Errors) instead of via a callback function.
* `true` and `false` instead of `c.GLFW_TRUE` and `c.GLFW_FALSE` constants.
* Generics, so you can just use `window.hint` instead of `glfwWindowHint`, `glfwWindowHintString`, etc.
* **Enums**, always know what value a GLFW function can accept as everything is strictly typed. And use the nice Zig syntax to access enums, like `window.getKey(.escape)` instead of `c.glfwGetKey(window, c.GLFW_KEY_ESCAPE)`
* Slices instead of C pointers and lengths.
* [packed structs](https://ziglang.org/documentation/master/#packed-struct) represent bit masks, so you can use `if (joystick.down and joystick.right)` instead of `if (joystick & c.GLFW_HAT_DOWN and joystick & c.GLFW_HAT_RIGHT)`, etc.
* Methods, e.g. `my_window.hint(...)` instead of `glfwWindowHint(my_window, ...)`
## How do I use OpenGL, Vulkan, WebGPU, etc. with this?
You'll need to bring your own library for this. Some are:
* (Vulkan) https://github.com/Snektron/vulkan-zig (also see https://github.com/Avokadoen/zig_vulkan)
* (OpenGL) https://github.com/ziglibs/zgl
## Examples
A minimal Vulkan example can be found in the [mach-glfw-vulkan-example](https://github.com/hexops/mach-glfw-vulkan-example) repository:
<img width="912" alt="image" src="https://user-images.githubusercontent.com/3173176/139573985-d862f35a-e78e-40c2-bc0c-9c4fb68d6ecd.png">
## Getting started
### Adding dependency (using Git)
In a `libs` subdirectory of the root of your project:
```sh
git clone https://github.com/hexops/mach-glfw
```
Then in your `build.zig` add:
```zig
...
const glfw = @import("libs/mach-glfw/build.zig");
pub fn build(b: *Builder) void {
...
exe.addPackage(glfw.pkg);
glfw.link(b, exe, .{});
}
```
<details>
<summary>
### (optional) Adding dependency using Gyro
</summary>
```sh
gyro add --src github hexops/mach-glfw --root src/main.zig --alias glfw
gyro add --build_dep --src github hexops/mach-glfw --root build.zig --alias build-glfw
```
Then in your `build.zig` add:
```zig
...
const pkgs = @import("deps.zig").pkgs;
const glfw = @import("build-glfw");
pub fn build(b: *Builder) void {
...
exe.addPackage(pkgs.glfw);
glfw.link(b, exe, .{});
}
```
**Note: You should use `gyro build` instead of `zig build` to use gyro**
</details>
# Next steps
Now in your code you may import and use GLFW:
```zig
const glfw = @import("glfw");
pub fn main() !void {
try glfw.init(.{});
defer glfw.terminate();
// Create our window
const window = try glfw.Window.create(640, 480, "Hello, mach-glfw!", null, null, .{});
defer window.destroy();
// Wait for the user to close the window.
while (!window.shouldClose()) {
try glfw.pollEvents();
}
}
```
## A warning about error handling
Unless the action you're performing is truly critical to your application continuing further, you should avoid using `try`.
This is because GLFW unfortunately must return errors for _a large portion_ of its functionality on some platforms, but especially for Wayland - so ideally your application is resiliant to such errors and merely e.g. logs failures that are not critical.
Instead of `try window.getPos()` for example, you may use:
```zig
const pos = window.getPos() catch |err| {
std.log.err("failed to get window position: error={}\n", .{err});
return;
};
```
Here is a rough list of functionality Wayland does not support:
* `Window.setIcon`
* `Window.setPos`, `Window.getPos`
* `Window.iconify`, `Window.focus`
* `Monitor.setGamma`
* `Monitor.getGammaRamp`, `Monitor.setGammaRamp`
## Join the community
Join the Mach engine community [on Matrix chat](https://matrix.to/#/#hexops:matrix.org) to discuss this project, ask questions, get help, etc.
## Issues
Issues are tracked in the [main Mach repository](https://github.com/hexops/mach/issues?q=is%3Aissue+is%3Aopen+label%3Aglfw).
## Contributing
Contributions are very welcome. Pull requests must be sent to [the main repository](https://github.com/hexops/mach/tree/main/glfw) to avoid some complex merge conflicts we'd get by accepting contributions in both repositories. Once the changes are merged there, they'll get sync'd to this repository automatically.
For now mach/glfw tracks the latest `master` revision of GLFW, as recorded [in this file](https://github.com/hexops/glfw/blob/main/VERSION), as this version has critical undefined behavior fixes required for GLFW to work with Zig. We will switch to stable releases of GLFW once GLFW 3.4 is tagged.

212
libs/glfw/build.zig Normal file
View file

@ -0,0 +1,212 @@
const std = @import("std");
const Builder = std.build.Builder;
const system_sdk = @import("system_sdk.zig");
pub fn build(b: *Builder) void {
const mode = b.standardReleaseOptions();
const target = b.standardTargetOptions(.{});
const test_step = b.step("test", "Run library tests");
test_step.dependOn(&testStep(b, mode, target).step);
test_step.dependOn(&testStepShared(b, mode, target).step);
}
pub fn testStep(b: *Builder, mode: std.builtin.Mode, target: std.zig.CrossTarget) *std.build.RunStep {
const main_tests = b.addTestExe("glfw_tests", thisDir() ++ "/src/main.zig");
main_tests.setBuildMode(mode);
main_tests.setTarget(target);
link(b, main_tests, .{});
main_tests.install();
return main_tests.run();
}
fn testStepShared(b: *Builder, mode: std.builtin.Mode, target: std.zig.CrossTarget) *std.build.RunStep {
const main_tests = b.addTestExe("glfw_tests_shared", thisDir() ++ "/src/main.zig");
main_tests.setBuildMode(mode);
main_tests.setTarget(target);
link(b, main_tests, .{ .shared = true });
main_tests.install();
return main_tests.run();
}
pub const LinuxWindowManager = enum {
X11,
Wayland,
};
pub const Options = struct {
/// Not supported on macOS.
vulkan: bool = true,
/// Only respected on macOS.
metal: bool = true,
/// Deprecated on macOS.
opengl: bool = false,
/// Not supported on macOS. GLES v3.2 only, currently.
gles: bool = false,
/// Only respected on Linux.
x11: bool = true,
/// Only respected on Linux.
wayland: bool = true,
/// System SDK options.
system_sdk: system_sdk.Options = .{},
/// Build and link GLFW as a shared library.
shared: bool = false,
};
pub const pkg = std.build.Pkg{
.name = "glfw",
.source = .{ .path = thisDir() ++ "/src/main.zig" },
};
pub fn link(b: *Builder, step: *std.build.LibExeObjStep, options: Options) void {
const lib = buildLibrary(b, step, options);
step.linkLibrary(lib);
addGLFWIncludes(step);
if (!options.shared) linkGLFWDependencies(b, step, options);
if (options.shared) step.defineCMacro("GLFW_DLL", null);
}
fn buildLibrary(b: *Builder, step: *std.build.LibExeObjStep, options: Options) *std.build.LibExeObjStep {
// TODO(build-system): https://github.com/hexops/mach/issues/229#issuecomment-1100958939
ensureDependencySubmodule(b.allocator, "upstream") catch unreachable;
const main_abs = thisDir() ++ "/src/main.zig";
const lib = if (options.shared) b.addSharedLibrary("glfw", main_abs, .unversioned) else b.addStaticLibrary("glfw", main_abs);
lib.setBuildMode(step.build_mode);
lib.setTarget(step.target);
addGLFWIncludes(lib);
if (options.shared) {
lib.defineCMacro("_GLFW_BUILD_DLL", null);
lib.install();
}
addGLFWSources(b, step, lib, options);
linkGLFWDependencies(b, lib, options);
return lib;
}
fn addGLFWIncludes(step: *std.build.LibExeObjStep) void {
step.addIncludeDir(thisDir() ++ "/upstream/glfw/include");
step.addIncludeDir(thisDir() ++ "/upstream/vulkan_headers/include");
}
fn addGLFWSources(b: *Builder, step: *std.build.LibExeObjStep, lib: *std.build.LibExeObjStep, options: Options) void {
const target = (std.zig.system.NativeTargetInfo.detect(b.allocator, step.target) catch unreachable).target;
const include_glfw_src = "-I" ++ thisDir() ++ "/upstream/glfw/src";
switch (target.os.tag) {
.windows => lib.addCSourceFiles(&.{
thisDir() ++ "/src/sources_all.c",
thisDir() ++ "/src/sources_windows.c",
}, &.{ "-D_GLFW_WIN32", include_glfw_src }),
.macos => lib.addCSourceFiles(&.{
thisDir() ++ "/src/sources_all.c",
thisDir() ++ "/src/sources_macos.m",
thisDir() ++ "/src/sources_macos.c",
}, &.{ "-D_GLFW_COCOA", include_glfw_src }),
else => {
// TODO(future): for now, Linux must be built with glibc, not musl:
//
// ```
// ld.lld: error: cannot create a copy relocation for symbol stderr
// thread 2004762 panic: attempt to unwrap error: LLDReportedFailure
// ```
step.target.abi = .gnu;
lib.setTarget(step.target);
var sources = std.ArrayList([]const u8).init(b.allocator);
var flags = std.ArrayList([]const u8).init(b.allocator);
sources.append(thisDir() ++ "/src/sources_all.c") catch unreachable;
sources.append(thisDir() ++ "/src/sources_linux.c") catch unreachable;
if (options.x11) {
sources.append(thisDir() ++ "/src/sources_linux_x11.c") catch unreachable;
flags.append("-D_GLFW_X11") catch unreachable;
}
if (options.wayland) {
sources.append(thisDir() ++ "/src/sources_linux_wayland.c") catch unreachable;
flags.append("-D_GLFW_WAYLAND") catch unreachable;
}
flags.append("-I" ++ thisDir() ++ "/upstream/glfw/src") catch unreachable;
lib.addCSourceFiles(sources.items, flags.items);
},
}
}
fn ensureDependencySubmodule(allocator: std.mem.Allocator, path: []const u8) !void {
if (std.process.getEnvVarOwned(allocator, "NO_ENSURE_SUBMODULES")) |no_ensure_submodules| {
if (std.mem.eql(u8, no_ensure_submodules, "true")) return;
} else |_| {}
var child = std.ChildProcess.init(&.{ "git", "submodule", "update", "--init", path }, allocator);
child.cwd = thisDir();
child.stderr = std.io.getStdErr();
child.stdout = std.io.getStdOut();
_ = try child.spawnAndWait();
}
inline fn thisDir() []const u8 {
return comptime std.fs.path.dirname(@src().file) orelse ".";
}
fn linkGLFWDependencies(b: *Builder, step: *std.build.LibExeObjStep, options: Options) void {
step.linkLibC();
// TODO(build-system): pass system SDK options through
system_sdk.include(b, step, .{});
const target = (std.zig.system.NativeTargetInfo.detect(b.allocator, step.target) catch unreachable).target;
switch (target.os.tag) {
.windows => {
step.linkSystemLibraryName("gdi32");
step.linkSystemLibraryName("user32");
step.linkSystemLibraryName("shell32");
if (options.opengl) {
step.linkSystemLibraryName("opengl32");
}
if (options.gles) {
step.linkSystemLibraryName("GLESv3");
}
},
.macos => {
step.linkFramework("IOKit");
step.linkFramework("CoreFoundation");
if (options.metal) {
step.linkFramework("Metal");
}
if (options.opengl) {
step.linkFramework("OpenGL");
}
step.linkSystemLibraryName("objc");
step.linkFramework("AppKit");
step.linkFramework("CoreServices");
step.linkFramework("CoreGraphics");
step.linkFramework("Foundation");
},
else => {
// Assume Linux-like
if (options.wayland) {
step.defineCMacro("WL_MARSHAL_FLAG_DESTROY", null);
}
if (options.x11) {
step.linkSystemLibraryName("X11");
step.linkSystemLibraryName("xcb");
step.linkSystemLibraryName("Xau");
step.linkSystemLibraryName("Xdmcp");
}
// Note: no need to link against vulkan, GLFW finds it dynamically at runtime.
// https://www.glfw.org/docs/3.3/vulkan_guide.html#vulkan_loader
if (options.opengl) {
step.linkSystemLibraryName("GL");
}
if (options.gles) {
step.linkSystemLibraryName("GLESv3");
}
},
}
}

223
libs/glfw/src/Cursor.zig Normal file
View file

@ -0,0 +1,223 @@
//! 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 Error = @import("errors.zig").Error;
const getError = @import("errors.zig").getError;
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.
///
/// @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) error{ PlatformError, InvalidValue }!Cursor {
internal_debug.assertInitialized();
const img = image.toC();
if (c.glfwCreateCursor(&img, @intCast(c_int, xhot), @intCast(c_int, yhot))) |cursor| return Cursor{ .ptr = cursor };
getError() catch |err| return switch (err) {
Error.NotInitialized => unreachable,
Error.PlatformError => |e| e,
Error.InvalidValue => |e| e,
else => unreachable,
};
// `glfwCreateCursor` returns `null` only for errors
unreachable;
}
/// 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
///
/// thread_safety: This function must only be called from the main thread.
///
/// see also: cursor_object, glfwCreateCursor
pub inline fn createStandard(shape: Shape) error{ PlatformError, CursorUnavailable }!Cursor {
internal_debug.assertInitialized();
if (c.glfwCreateStandardCursor(@intCast(c_int, @enumToInt(shape)))) |cursor| return Cursor{ .ptr = cursor };
getError() catch |err| return switch (err) {
Error.NotInitialized => unreachable,
Error.InvalidEnum => unreachable,
Error.CursorUnavailable => |e| e,
Error.PlatformError => |e| e,
else => unreachable,
};
// `glfwCreateStandardCursor` returns `null` only for errors
unreachable;
}
/// 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.Error.NotInitialized and glfw.Error.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);
getError() catch |err| return switch (err) {
Error.PlatformError => std.log.err("mach/glfw: unable to destroy Cursor: {}\n", .{err}),
else => unreachable,
};
}
test "create" {
const allocator = testing.allocator;
const glfw = @import("main.zig");
try glfw.init(.{});
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) catch |err| {
std.debug.print("failed to create cursor, custom cursors not supported? error={}\n", .{err});
return;
};
cursor.destroy();
}
test "createStandard" {
const glfw = @import("main.zig");
try glfw.init(.{});
defer glfw.terminate();
const cursor = glfw.Cursor.createStandard(.ibeam) catch |err| {
std.debug.print("failed to create cursor, custom cursors not supported? error={}\n", .{err});
return;
};
cursor.destroy();
}

View file

@ -0,0 +1,74 @@
//! 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: bool,
/// 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 = true,
};
}
/// 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 = false,
};
}
/// 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 = @intCast(c_uint, 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) allocator.free(self.red);
}
test "conversion" {
const allocator = testing.allocator;
const ramp = try GammaRamp.init(allocator, 256);
defer ramp.deinit(allocator);
const glfw = ramp.toC();
_ = GammaRamp.fromC(glfw);
}

82
libs/glfw/src/Image.zig Normal file
View file

@ -0,0 +1,82 @@
//! 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 = @intCast(u32, native.width),
.height = @intCast(u32, 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 = @intCast(c_int, self.width),
.height = @intCast(c_int, 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);
}

667
libs/glfw/src/Joystick.zig Normal file
View file

@ -0,0 +1,667 @@
//! 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 Error = @import("errors.zig").Error;
const getError = @import("errors.zig").getError;
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 = @intToEnum(@This(), 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 {
_ = self;
return @intToEnum(Action, self.buttons[@intCast(u32, @enumToInt(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 {
_ = self;
return self.axes[@intCast(u32, @enumToInt(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.Error.NotInitialized, glfw.Error.InvalidEnum and glfw.Error.PlatformError.
///
/// @thread_safety This function must only be called from the main thread.
///
/// see also: joystick
pub inline fn present(self: Joystick) error{PlatformError}!bool {
internal_debug.assertInitialized();
const is_present = c.glfwJoystickPresent(@enumToInt(self.jid));
getError() catch |err| return switch (err) {
Error.NotInitialized => unreachable,
Error.InvalidEnum => unreachable,
Error.PlatformError => |e| e,
else => unreachable,
};
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.Error.NotInitialized, glfw.Error.InvalidEnum and glfw.Error.PlatformError.
///
/// @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) error{PlatformError}!?[]const f32 {
internal_debug.assertInitialized();
var count: c_int = undefined;
const axes = c.glfwGetJoystickAxes(@enumToInt(self.jid), &count);
getError() catch |err| return switch (err) {
Error.NotInitialized => unreachable,
Error.InvalidEnum => unreachable,
Error.PlatformError => |e| e,
else => unreachable,
};
if (axes == null) return null;
return axes[0..@intCast(u32, 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.Error.NotInitialized, glfw.Error.InvalidEnum and glfw.Error.PlatformError.
///
/// @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) error{PlatformError}!?[]const u8 {
internal_debug.assertInitialized();
var count: c_int = undefined;
const buttons = c.glfwGetJoystickButtons(@enumToInt(self.jid), &count);
getError() catch |err| return switch (err) {
Error.NotInitialized => unreachable,
Error.InvalidEnum => unreachable,
Error.PlatformError => |e| e,
else => unreachable,
};
if (buttons == null) return null;
return buttons[0..@intCast(u32, 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.Error.NotInitialized, glfw.Error.InvalidEnum and glfw.Error.PlatformError.
///
/// @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) error{PlatformError}!?[]const Hat {
internal_debug.assertInitialized();
var count: c_int = undefined;
const hats = c.glfwGetJoystickHats(@enumToInt(self.jid), &count);
getError() catch |err| return switch (err) {
Error.NotInitialized => unreachable,
Error.InvalidEnum => unreachable,
Error.PlatformError => |e| e,
else => unreachable,
};
if (hats == null) return null;
const slice = hats[0..@intCast(u32, count)];
return @ptrCast(*const []const Hat, &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.Error.NotInitialized, glfw.Error.InvalidEnum and glfw.Error.PlatformError.
///
/// @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) error{PlatformError}!?[:0]const u8 {
internal_debug.assertInitialized();
const name_opt = c.glfwGetJoystickName(@enumToInt(self.jid));
getError() catch |err| return switch (err) {
Error.NotInitialized => unreachable,
Error.InvalidEnum => unreachable,
Error.PlatformError => |e| e,
else => unreachable,
};
return if (name_opt) |name|
std.mem.span(@ptrCast([*:0]const u8, 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.Error.NotInitialized, glfw.Error.InvalidEnum and glfw.Error.PlatformError.
///
/// @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) error{PlatformError}!?[:0]const u8 {
internal_debug.assertInitialized();
const guid_opt = c.glfwGetJoystickGUID(@enumToInt(self.jid));
getError() catch |err| return switch (err) {
Error.NotInitialized => unreachable,
Error.InvalidEnum => unreachable,
Error.PlatformError => |e| e,
else => unreachable,
};
return if (guid_opt) |guid|
std.mem.span(@ptrCast([*:0]const u8, 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(@enumToInt(self.jid), @ptrCast(*anyopaque, pointer));
getError() catch |err| return switch (err) {
Error.NotInitialized => unreachable,
else => unreachable,
};
}
/// 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(@enumToInt(self.jid));
getError() catch |err| return switch (err) {
Error.NotInitialized => unreachable,
else => unreachable,
};
if (ptr) |p| return @ptrCast(PointerType, @alignCast(@alignOf(std.meta.Child(PointerType)), 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.
///
/// Possible errors include glfw.Error.NotInitialized.
///
/// @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(.{ .modifier = .always_inline }, user_callback, .{
Joystick{ .jid = @intToEnum(Joystick.Id, jid) },
@intToEnum(Event, event),
});
}
};
if (c.glfwSetJoystickCallback(CWrapper.joystickCallbackWrapper) != null) return;
} else {
if (c.glfwSetJoystickCallback(null) != null) return;
}
getError() catch |err| return switch (err) {
Error.NotInitialized => unreachable,
else => unreachable,
};
}
/// 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.Error.NotInitialized and glfw.Error.InvalidValue.
///
/// @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) error{InvalidValue}!void {
internal_debug.assertInitialized();
if (c.glfwUpdateGamepadMappings(gamepad_mappings) == c.GLFW_TRUE) return;
getError() catch |err| return switch (err) {
Error.NotInitialized => unreachable,
// TODO: Maybe return as 'ParseError' here?
// TODO: Look into upstream proposal for GLFW to publicize
// their Gamepad mappings parsing functions/interface
// for a better error message in debug.
Error.InvalidValue => |e| e,
else => unreachable,
};
}
/// 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.Error.NotInitialized and glfw.Error.InvalidEnum.
///
/// @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(@enumToInt(self.jid));
getError() catch |err| return switch (err) {
Error.NotInitialized => unreachable,
Error.InvalidEnum => unreachable,
else => unreachable,
};
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.Error.NotInitialized and glfw.Error.InvalidEnum.
///
/// @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(@enumToInt(self.jid));
getError() catch |err| return switch (err) {
Error.NotInitialized => unreachable,
Error.InvalidValue => unreachable,
else => unreachable,
};
return if (name_opt) |name|
std.mem.span(@ptrCast([*:0]const u8, 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.Error.NotInitialized and glfw.Error.InvalidEnum.
///
/// @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(@enumToInt(self.jid), @ptrCast(*c.GLFWgamepadstate, &state));
getError() catch |err| return switch (err) {
Error.NotInitialized => unreachable,
Error.InvalidEnum => unreachable,
else => unreachable,
};
return if (success == c.GLFW_TRUE) state else null;
}
test "present" {
const glfw = @import("main.zig");
try glfw.init(.{});
defer glfw.terminate();
const joystick = glfw.Joystick{ .jid = .one };
_ = joystick.present() catch |err| std.debug.print("failed to detect joystick, joysticks not supported? error={}\n", .{err});
}
test "getAxes" {
const glfw = @import("main.zig");
try glfw.init(.{});
defer glfw.terminate();
const joystick = glfw.Joystick{ .jid = .one };
_ = joystick.getAxes() catch |err| std.debug.print("failed to get joystick axes, joysticks not supported? error={}\n", .{err});
}
test "getButtons" {
const glfw = @import("main.zig");
try glfw.init(.{});
defer glfw.terminate();
const joystick = glfw.Joystick{ .jid = .one };
_ = joystick.getButtons() catch |err| std.debug.print("failed to get joystick buttons, joysticks not supported? error={}\n", .{err});
}
test "getHats" {
const glfw = @import("main.zig");
try glfw.init(.{});
defer glfw.terminate();
const joystick = glfw.Joystick{ .jid = .one };
_ = joystick.getHats() catch |err| std.debug.print("failed to get joystick hats, joysticks not supported? error={}\n", .{err});
const hats = std.mem.zeroes(Hat);
if (hats.down and hats.up) {
// down-up!
}
}
test "getName" {
const glfw = @import("main.zig");
try glfw.init(.{});
defer glfw.terminate();
const joystick = glfw.Joystick{ .jid = .one };
_ = joystick.getName() catch |err| std.debug.print("failed to get joystick name, joysticks not supported? error={}\n", .{err});
}
test "getGUID" {
const glfw = @import("main.zig");
try glfw.init(.{});
defer glfw.terminate();
const joystick = glfw.Joystick{ .jid = .one };
_ = joystick.getGUID() catch |err| std.debug.print("failed to get joystick GUID, joysticks not supported? error={}\n", .{err});
}
test "setUserPointer_syntax" {
const glfw = @import("main.zig");
try glfw.init(.{});
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");
try glfw.init(.{});
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");
try glfw.init(.{});
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");
try glfw.init(.{});
defer glfw.terminate();
const joystick = glfw.Joystick{ .jid = .one };
_ = joystick.isGamepad();
}
test "getGamepadName" {
const glfw = @import("main.zig");
try glfw.init(.{});
defer glfw.terminate();
const joystick = glfw.Joystick{ .jid = .one };
_ = joystick.getGamepadName();
}
test "getGamepadState" {
const glfw = @import("main.zig");
try glfw.init(.{});
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);
}

626
libs/glfw/src/Monitor.zig Normal file
View file

@ -0,0 +1,626 @@
//! Monitor type and related functions
const std = @import("std");
const mem = std.mem;
const testing = std.testing;
const c = @import("c.zig").c;
const Error = @import("errors.zig").Error;
const getError = @import("errors.zig").getError;
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.Error.NotInitialized and glfw.Error.PlatformError.
///
/// @thread_safety This function must only be called from the main thread.
///
/// see also: monitor_properties
pub inline fn getPos(self: Monitor) error{PlatformError}!Pos {
internal_debug.assertInitialized();
var xpos: c_int = 0;
var ypos: c_int = 0;
c.glfwGetMonitorPos(self.handle, &xpos, &ypos);
getError() catch |err| return switch (err) {
Error.NotInitialized => unreachable,
Error.PlatformError => |e| e,
else => unreachable,
};
return Pos{ .x = @intCast(u32, xpos), .y = @intCast(u32, 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.Error.NotInitialized and glfw.Error.PlatformError.
///
/// @thread_safety This function must only be called from the main thread.
///
/// see also: monitor_workarea
pub inline fn getWorkarea(self: Monitor) error{PlatformError}!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);
getError() catch |err| return switch (err) {
Error.NotInitialized => unreachable,
Error.PlatformError => |e| e,
else => unreachable,
};
return Workarea{ .x = @intCast(u32, xpos), .y = @intCast(u32, ypos), .width = @intCast(u32, width), .height = @intCast(u32, 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.
///
/// Possible errors include glfw.Error.NotInitialized.
///
///
/// 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);
getError() catch |err| return switch (err) {
Error.NotInitialized => unreachable,
else => unreachable,
};
return PhysicalSize{ .width_mm = @intCast(u32, width_mm), .height_mm = @intCast(u32, 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.Error.NotInitialized and glfw.Error.PlatformError.
///
/// @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) error{PlatformError}!ContentScale {
internal_debug.assertInitialized();
var x_scale: f32 = 0;
var y_scale: f32 = 0;
c.glfwGetMonitorContentScale(self.handle, &x_scale, &y_scale);
getError() catch |err| return switch (err) {
Error.NotInitialized => unreachable,
Error.PlatformError => |e| e,
else => unreachable,
};
return ContentScale{ .x_scale = @floatCast(f32, x_scale), .y_scale = @floatCast(f32, 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.
///
/// Possible errors include glfw.Error.NotInitialized.
///
/// @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 @ptrCast([*:0]const u8, name);
getError() catch |err| return switch (err) {
Error.NotInitialized => unreachable,
else => unreachable,
};
// `glfwGetMonitorName` returns `null` only for errors
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.
///
/// Possible errors include glfw.Error.NotInitialized.
///
/// @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);
getError() catch |err| return switch (err) {
Error.NotInitialized => unreachable,
else => unreachable,
};
}
/// 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.
///
/// Possible errors include glfw.Error.NotInitialized.
///
/// @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);
getError() catch |err| return switch (err) {
Error.NotInitialized => unreachable,
else => unreachable,
};
if (ptr == null) return null;
return @ptrCast(*T, @alignCast(@alignOf(T), 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.Error.NotInitialized and glfw.Error.PlatformError.
///
/// 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
pub inline fn getVideoModes(self: Monitor, allocator: mem.Allocator) (mem.Allocator.Error || error{PlatformError})![]VideoMode {
internal_debug.assertInitialized();
var count: c_int = 0;
if (c.glfwGetVideoModes(self.handle, &count)) |modes| {
const slice = try allocator.alloc(VideoMode, @intCast(u32, count));
var i: u32 = 0;
while (i < count) : (i += 1) {
slice[i] = VideoMode{ .handle = @ptrCast([*c]const c.GLFWvidmode, modes)[i] };
}
return slice;
}
getError() catch |err| return switch (err) {
Error.NotInitialized => unreachable,
Error.PlatformError => |e| e,
else => unreachable,
};
// `glfwGetVideoModes` returns `null` only for errors
unreachable;
}
/// 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.Error.NotInitialized and glfw.Error.PlatformError.
///
/// @thread_safety This function must only be called from the main thread.
///
/// see also: monitor_modes, glfw.Monitor.getVideoModes
pub inline fn getVideoMode(self: Monitor) error{PlatformError}!VideoMode {
internal_debug.assertInitialized();
if (c.glfwGetVideoMode(self.handle)) |mode| return VideoMode{ .handle = mode.* };
getError() catch |err| return switch (err) {
Error.NotInitialized => unreachable,
Error.PlatformError => |e| e,
else => unreachable,
};
// `glfwGetVideoMode` returns `null` only for errors
unreachable;
}
/// 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.Error.NotInitialized, glfw.Error.InvalidValue and glfw.Error.PlatformError.
///
/// wayland: Gamma handling is a privileged protocol, this function will thus never be implemented
/// and emits glfw.Error.PlatformError.
///
/// @thread_safety This function must only be called from the main thread.
///
/// see also: monitor_gamma
pub inline fn setGamma(self: Monitor, gamma: f32) error{PlatformError}!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);
getError() catch |err| return switch (err) {
Error.NotInitialized => unreachable,
Error.InvalidValue => unreachable,
Error.PlatformError => |e| e,
else => unreachable,
};
}
/// Returns the current gamma ramp for the specified monitor.
///
/// This function returns the current gamma ramp of the specified monitor.
///
/// Possible errors include glfw.Error.NotInitialized and glfw.Error.PlatformError.
///
/// wayland: Gamma handling is a privileged protocol, this function will thus never be implemented
/// and returns glfw.Error.PlatformError.
/// TODO: Is the documentation obsolete? On wayland the error returned is 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) error{ PlatformError, FeatureUnavailable }!GammaRamp {
internal_debug.assertInitialized();
if (c.glfwGetGammaRamp(self.handle)) |ramp| return GammaRamp.fromC(ramp.*);
getError() catch |err| return switch (err) {
Error.NotInitialized => unreachable,
Error.PlatformError, Error.FeatureUnavailable => |e| e,
else => unreachable,
};
// `glfwGetGammaRamp` returns `null` only for errors
unreachable;
}
/// 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.Error.NotInitialized and glfw.Error.PlatformError.
///
/// 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 emits glfw.Error.PlatformError.
///
/// @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) error{PlatformError}!void {
internal_debug.assertInitialized();
c.glfwSetGammaRamp(self.handle, &ramp.toC());
getError() catch |err| return switch (err) {
Error.NotInitialized => unreachable,
Error.PlatformError => |e| e,
else => unreachable,
};
}
/// 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, @intCast(u32, count));
var i: u32 = 0;
while (i < count) : (i += 1) {
slice[i] = Monitor{ .handle = @ptrCast([*c]const ?*c.GLFWmonitor, monitors)[i].? };
}
return slice;
}
getError() catch |err| return switch (err) {
Error.NotInitialized => unreachable,
else => unreachable,
};
// `glfwGetMonitors` returning null can be either an error or no monitors
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.
///
/// Possible errors include glfw.Error.NotInitialized.
///
/// @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 };
getError() catch |err| return switch (err) {
Error.NotInitialized => unreachable,
else => unreachable,
};
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.
///
/// Possible errors include glfw.Error.NotInitialized.
///
/// @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(.{ .modifier = .always_inline }, user_callback, .{
Monitor{ .handle = monitor.? },
@intToEnum(Event, event),
});
}
};
if (c.glfwSetMonitorCallback(CWrapper.monitorCallbackWrapper) != null) return;
} else {
if (c.glfwSetMonitorCallback(null) != null) return;
}
getError() catch |err| return switch (err) {
Error.NotInitialized => unreachable,
else => unreachable,
};
}
test "getAll" {
const glfw = @import("main.zig");
try glfw.init(.{});
defer glfw.terminate();
const allocator = testing.allocator;
const monitors = try getAll(allocator);
defer allocator.free(monitors);
}
test "getPrimary" {
const glfw = @import("main.zig");
try glfw.init(.{});
defer glfw.terminate();
_ = getPrimary();
}
test "getPos" {
const glfw = @import("main.zig");
try glfw.init(.{});
defer glfw.terminate();
const monitor = getPrimary();
if (monitor) |m| {
_ = try m.getPos();
}
}
test "getWorkarea" {
const glfw = @import("main.zig");
try glfw.init(.{});
defer glfw.terminate();
const monitor = getPrimary();
if (monitor) |m| {
_ = try m.getWorkarea();
}
}
test "getPhysicalSize" {
const glfw = @import("main.zig");
try glfw.init(.{});
defer glfw.terminate();
const monitor = getPrimary();
if (monitor) |m| {
_ = m.getPhysicalSize();
}
}
test "getContentScale" {
const glfw = @import("main.zig");
try glfw.init(.{});
defer glfw.terminate();
const monitor = getPrimary();
if (monitor) |m| {
_ = try m.getContentScale();
}
}
test "getName" {
const glfw = @import("main.zig");
try glfw.init(.{});
defer glfw.terminate();
const monitor = getPrimary();
if (monitor) |m| {
_ = m.getName();
}
}
test "userPointer" {
const glfw = @import("main.zig");
try glfw.init(.{});
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");
try glfw.init(.{});
defer glfw.terminate();
setCallback(struct {
fn callback(monitor: Monitor, event: Event) void {
_ = monitor;
_ = event;
}
}.callback);
}
test "getVideoModes" {
const glfw = @import("main.zig");
try glfw.init(.{});
defer glfw.terminate();
const monitor = getPrimary();
if (monitor) |m| {
const allocator = testing.allocator;
const modes = try m.getVideoModes(allocator);
defer allocator.free(modes);
}
}
test "getVideoMode" {
const glfw = @import("main.zig");
try glfw.init(.{});
defer glfw.terminate();
const monitor = getPrimary();
if (monitor) |m| {
_ = try m.getVideoMode();
}
}
test "set_getGammaRamp" {
const allocator = testing.allocator;
const glfw = @import("main.zig");
try glfw.init(.{});
defer glfw.terminate();
const monitor = getPrimary();
if (monitor) |m| {
const ramp = m.getGammaRamp() catch |err| {
std.debug.print("can't get window position, wayland maybe? error={}\n", .{err});
return;
};
// 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.
try m.setGammaRamp(ramp);
// technically not needed here / noop because GLFW owns this gamma ramp.
defer ramp.deinit(allocator);
}
}

View file

@ -0,0 +1,50 @@
//! 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 @intCast(u32, self.handle.width);
}
/// Returns the height of the video mode, in screen coordinates.
pub inline fn getHeight(self: VideoMode) u32 {
return @intCast(u32, self.handle.height);
}
/// Returns the bit depth of the red channel of the video mode.
pub inline fn getRedBits(self: VideoMode) u32 {
return @intCast(u32, self.handle.redBits);
}
/// Returns the bit depth of the green channel of the video mode.
pub inline fn getGreenBits(self: VideoMode) u32 {
return @intCast(u32, self.handle.greenBits);
}
/// Returns the bit depth of the blue channel of the video mode.
pub inline fn getBlueBits(self: VideoMode) u32 {
return @intCast(u32, self.handle.blueBits);
}
/// Returns the refresh rate of the video mode, in Hz.
pub inline fn getRefreshRate(self: VideoMode) u32 {
return @intCast(u32, self.handle.refreshRate);
}
test "getters" {
const x = std.mem.zeroes(VideoMode);
_ = x.getWidth();
_ = x.getHeight();
_ = x.getRedBits();
_ = x.getGreenBits();
_ = x.getBlueBits();
_ = x.getRefreshRate();
}

Some files were not shown because too many files have changed in this diff Show more