213 Commits

Author SHA1 Message Date
Robin Voetter
5559cccea6 add missing vulkan video type in ref_all_decls.zig 2024-11-24 21:00:45 +01:00
Robin Voetter
84b9622f92 Merge pull request #165 from moomba42/master
Bring zig-0.13-compat branch up to date with main
2024-10-12 21:28:44 +02:00
Aleksander Długosz
a6e228cd9f Update ref_all_decls.zig 2024-10-12 02:07:38 +02:00
Aleksander Długosz
fc700b44c0 Update render.zig 2024-10-12 02:06:48 +02:00
Robin Voetter
06dae6c920 yeet usingnamespace
Fixes #161
2024-09-17 20:45:09 +02:00
Robin Voetter
efad55ba0d Merge pull request #159 from poconn/increase_branch_quota
Increase eval branch quota
2024-09-13 00:06:07 +02:00
Patrick O'Connell
0e29c7b70f Increase eval branch quota 2024-09-09 06:19:13 -07:00
Robin Voetter
9bfa67682f mention shader_compiler in the readme 2024-09-04 23:56:41 +02:00
Robin Voetter
981b20c395 remove deprecated VkGenerateStep 2024-09-04 23:56:40 +02:00
Robin Voetter
9ee4cf349f get rid of ShaderCompileStep
Use addSystemCommand to run glslc now. See the example.
2024-09-04 23:56:40 +02:00
Robin Voetter
976dbfbcca example: use addSystemCommand instead of shader compile step 2024-09-04 23:56:38 +02:00
Robin Voetter
f7b21d034f Merge pull request #157 from andrewrk/master
update for latest zig
2024-09-01 08:29:11 +02:00
Andrew Kelley
28c14dcf37 update in response to std.builtin.Type field renames 2024-08-31 20:47:06 -07:00
Andrew Kelley
d03459819c add build.zig.zon file
Integrate with tooling and makes the package size smaller.
2024-08-30 19:52:09 -07:00
Robin Voetter
18f38ef2b7 increase more branch quotas 2024-08-23 23:47:14 +02:00
Robin Voetter
492521b50d increase branch quota in ref_all_decls.zig 2024-08-23 23:19:43 +02:00
Robin Voetter
54ab76b667 Merge pull request #155 from MilkywayPirate/patch-1
Update README.md
2024-08-12 09:44:44 +02:00
Emil Lai
543381c7dc Update README.md
Substitute `.addImport(..)` with `.root_module.addImport(..)` as the former seems to be gone.
2024-08-09 23:24:37 +02:00
Robin Voetter
d7ad51c9b8 Merge pull request #150 from antlilja/lazy-path-compile-command
Add ability to pass a LazyPath as compile command to the ShaderCompileStep
2024-08-08 22:41:58 +02:00
Robin Voetter
9f6e6177b1 Merge pull request #152 from alichraghi/master
update to latest zig
2024-07-16 09:17:12 +02:00
Ali Cheraghi
0125bcc466 update to latest zig 2024-07-16 09:56:19 +03:30
antlilja
c2e755d934 Add ability to pass a LazyPath to ShaderCompileStep
Allows for executables generated by the
build system to be used as shader compilers.
2024-07-09 12:35:00 +02:00
Robin Voetter
66b7b773bb Merge pull request #147 from flut2/master
Log command name when loading fails
2024-07-06 20:57:56 +02:00
flut2
982178e027 Merge branch 'Snektron:master' into master 2024-07-06 20:35:38 +02:00
Robin Voetter
51c5566f92 Merge pull request #146 from poconn/alloc_wrappers
Array function wrappers
2024-07-01 00:00:16 +02:00
Patrick O'Connell
a2167a79d5 Author suffix last for alloc functions 2024-06-30 13:37:51 -07:00
Patrick O'Connell
b3eb45d6a4 Add more "enumerate" functions to list 2024-06-30 13:18:05 -07:00
Patrick O'Connell
4707aca68d Use *Alloc() functions in example 2024-06-29 17:13:06 -07:00
Patrick O'Connell
7a6986faba Proxy wrappers for slice functions 2024-06-29 16:53:30 -07:00
Patrick O'Connell
a2b49336d1 Add *Alloc() wrappers 2024-06-29 15:47:55 -07:00
flut2
062357916c log command name when loading fails 2024-06-24 20:08:20 +02:00
Patrick O'Connell
e9199a0abc Extract some helper functions 2024-06-23 10:22:24 -07:00
Robin Voetter
ff4cff5f64 Merge pull request #144 from Squamto/master
update to 0.14.0-dev.91+a154d8da8
2024-06-20 23:28:54 +02:00
Squamto
3c8f827322 update to 0.14.0-dev.91+a154d8da8 2024-06-20 21:01:31 +02:00
Robin Voetter
f637a0d252 Merge pull request #143 from flut2/master
Update to 0.14.0-dev.43+96501d338
2024-06-17 21:17:17 +02:00
flut2
c79bbd86e8 update to 0.14.0-dev.43+96501d338 2024-06-17 18:53:57 +02:00
Robin Voetter
f537d09955 ci: switch to mlugg/setup-zig 2024-06-12 21:16:52 +02:00
Robin Voetter
a44d86899b Merge pull request #142 from vali-pnt/master
Update to zig 0.13.0
2024-06-11 07:49:11 +02:00
vali-pnt
4321b8bff9 update to zig 0.13.0 2024-06-11 02:48:42 +03:00
Robin Voetter
f2c2e0ff80 Merge pull request #141 from slimsag/master
always provide default opaque{} external type implementations
2024-06-02 23:25:51 +02:00
Stephen Gutekanst
cfaf58a4de always provide default opaque{} external type implementations
Signed-off-by: Stephen Gutekanst <stephen@hexops.com>
2024-06-02 12:20:00 -07:00
Robin Voetter
ac5ad34a95 update to latest zig: update to new progress api 2024-06-01 11:58:42 +02:00
Robin Voetter
8bd83cad43 Merge pull request #140 from antlilja/fix-build
Fix broken build
2024-05-16 19:22:02 +02:00
antlilja
794239076b Use cwd_relative for override registry 2024-05-16 18:04:23 +02:00
Robin Voetter
35f69b4ea6 Merge pull request #139 from antlilja/update-build
Update to zig master
2024-05-16 14:00:52 +02:00
antlilja
949de7684e Update to zig master 2024-05-16 13:59:45 +02:00
Robin Voetter
aa3808940e update to zig master 2024-05-08 00:05:34 +02:00
Robin Voetter
2115516b9b Merge pull request #136 from Snektron/proxy
Proxy
2024-04-29 23:36:53 +02:00
Robin Voetter
cb7873e8e4 add proxying wrappers description to readme 2024-04-29 21:37:50 +02:00
Robin Voetter
defc4c53d3 update example with new proxying wrappers 2024-04-29 21:37:36 +02:00
Robin Voetter
8694a69697 proxy wrappers: strip queue and cmd from QueueProxy and CommandBufferProxy functions 2024-04-29 21:14:47 +02:00
Robin Voetter
1260c86f60 generate proxying wrappers
Adds InstanceProxy, DeviceProxy, QueueProxy, CommandBufferProxy.
These act similar to the wrapper types, except that they
store and implicitly pass their respective handles.
2024-04-29 19:33:18 +02:00
Robin Voetter
fe036177e9 add --debug flag to aid debugging renerated source 2024-04-29 18:33:33 +02:00
Robin Voetter
a71c58bc65 Merge pull request #135 from Snektron/meta-ii
unified command info ii
2024-04-29 00:03:20 +02:00
Robin Voetter
c408e57d6d unified command info ii
This unifies command info even more, by making the user first construct
a list of `ApiInfo` to represent the api that they want to use. This
allows for much easier composition of different extensions and features.
2024-04-28 23:59:26 +02:00
Robin Voetter
66c2a743ba remove example vk.xml
This file is now fetched using the package manager.
2024-04-28 22:55:59 +02:00
Robin Voetter
143b506553 Merge pull request #134 from Snektron/build-improvements
Build improvements
2024-04-28 22:47:55 +02:00
Robin Voetter
65f1b0252b ci: build example separate and fix tests
Apparently the tests werent executing for some reason??
2024-04-28 22:44:21 +02:00
Robin Voetter
883ab2c2c4 update and fix README
Updates and fixes the explanations for how to use vulkan-zig so that they
are up-to-date in general, and up-to-date with the recent changes to
building the example.
2024-04-28 22:22:47 +02:00
Robin Voetter
7ac69f90ef use a separate build.zig for the example
This gives a more concrete example of how to use vulkan-zig, including
build commands as how a downstream user would use vulkan-zig.
2024-04-28 22:22:01 +02:00
Robin Voetter
1fdb930ae3 build example using tool instead of custom step
We are about to get rid of the custom build steps, so build
the example in a similar way that the downstream user would.
2024-04-28 14:20:12 +02:00
Robin Voetter
c5725dfb2e rename 'generator' binary to 'vulkan-zig-generator'
This changes the name of the generator binary from something
very generic to something a little more descriptive. If using
the package manager method to use the generator, this will
require updating to the new name.
2024-04-28 11:33:58 +02:00
Robin Voetter
e1f290399e move generator/ to src/
A long time ago there was the idea to use src/ for something else,
but that is no longer relevant. Its nice to switch to a more
conventional repo layout.
2024-04-28 11:27:49 +02:00
Robin Voetter
c3c9333d73 Remove zig.mod
Seems this is not really relevant anymore with the new build system
2024-04-28 11:26:44 +02:00
Robin Voetter
c212653f20 Merge pull request #133 from Snektron/ci-fmt
ci: format check
2024-04-28 11:00:56 +02:00
Robin Voetter
82ca63bce8 ci: update step versions 2024-04-28 10:56:23 +02:00
Robin Voetter
f811e5b926 ci: format check 2024-04-28 10:49:43 +02:00
Robin Voetter
2ac60ff7cd Merge pull request #127 from bluesillybeard/master
Add extension function metadata for #112
2024-04-28 10:38:34 +02:00
bluesillybeard
d19313ba75 Run zig fmt 2024-04-27 21:27:43 -06:00
bluesillybeard
110d836854 Refactor example to use extension info and feature info for functions 2024-04-26 22:15:08 -06:00
bluesillybeard
e4d6c50b55 Increase branch quota for command flags 2024-04-26 22:14:26 -06:00
bluesillybeard
9479fe480a Add feature info 2024-04-26 21:56:38 -06:00
bluesillybeard
d4a04e0bea Implement initial suggestions on PR 2024-04-26 20:44:40 -06:00
dan
500d7cc3e8 fix: change ComptimeStringMap to StaticStringMap
reflect changes made in 8af59d1f98
2024-04-26 20:44:40 -06:00
Robin Voetter
571cecdda6 actually run the tests 2024-04-26 20:44:40 -06:00
Robin Voetter
2047f7e7f2 Merge pull request #129 from igaryhe/update-comptimestringmap
fix: change ComptimeStringMap to StaticStringMap
2024-04-26 20:35:51 +02:00
dan
bab8f1883d fix: change ComptimeStringMap to StaticStringMap
reflect changes made in 8af59d1f98
2024-04-24 11:16:43 +08:00
Robin Voetter
8391911683 actually run the tests 2024-04-13 23:18:44 +02:00
bluesillybeard
9c45afca2e Add extension function metadata for #112 2024-04-10 17:06:43 -06:00
Robin Voetter
e60869528c Merge pull request #126 from igaryhe/fix-fieldparentptr
Fix broken @fieldParentPtr
2024-04-01 17:03:38 +02:00
dan
e840119290 Fix broken @fieldParentPtr 2024-03-31 19:42:56 +08:00
Robin Voetter
ac4103a733 Merge pull request #123 from igaryhe/fix-container-layout
make ContainerLayout field lowercase
2024-03-14 06:07:27 +01:00
dan
b7ef4e7a76 make ContainerLayout field lowercase
sync changes with zig master branch
099f3c4039d5702b073639ef8b55881973b71c80.
2024-03-13 23:29:53 +08:00
Robin Voetter
7f161ce0ed Merge pull request #121 from Mikastiv/master
remove no longer used error from set
2024-02-27 08:48:29 +01:00
Mikastiv
d1e6ebf931 remove no longer used error from set 2024-02-27 00:43:06 -05:00
Robin Voetter
b1f3820d08 Merge pull request #119 from Mikastiv/master
Fix compile error for the generator
2024-02-18 01:30:33 +01:00
Mikastiv
85532cf243 fix compile error 2024-02-17 15:20:57 -05:00
Robin Voetter
d0897a14da fix parsing issues with vk 1.3.278
This change introduced len/optional attributes for
arrays. Previously, we assumed that these would only
occur on pointers, but now, this information is also
available for arrays.

This adapts the registery and parsing code to also
parse these properly. No modifications are made to the
rendering part as of yet, since these partially filled
arrays cannot be cleanly represented in Zig.
2024-02-17 16:13:37 +01:00
Robin Voetter
cebfcc6045 improve error handling of generator tool
This now also prints more detailed error messages,
similar to the build step.
2024-02-17 15:33:22 +01:00
Robin Voetter
2b6d7691f1 Merge pull request #118 from Sirius902/zig-master
Compile on Zig master
2024-02-06 20:29:11 +01:00
Sirius902
be2ebfbff4 Compile on Zig master 2024-02-06 10:35:37 -08:00
Robin Voetter
62e981ad4e Merge pull request #117 from Sirius902/minimize-fix
[Triangle Example] Fix crash when minimizing window
2024-01-24 09:31:20 +01:00
Sirius902
e3bc661349 Fix crash when minimizing window
Wait for the device to be idle before exiting
2024-01-23 23:34:36 -08:00
Robin Voetter
d5e577f3f0 Merge pull request #116 from antlilja/fix-casts
Fix old style casts in generated vk.zig
2024-01-18 16:32:07 +01:00
antlilja
e72a6bb2d0 Fix old casts (rename and remove type) in vk.zig 2024-01-18 16:21:32 +01:00
Robin Voetter
290aaca5b8 Merge pull request #113 from SammyJames/new_modules
fixing up vulkan-zig for new build sys
2024-01-05 10:22:22 +01:00
sammy j
57ad4d5e16 fixing up vulkan-zig for new build design 2024-01-02 18:28:11 -08:00
Robin Voetter
27d9b028eb fix invalid use of var 2023-11-21 19:56:00 +01:00
Robin Voetter
6d46195c99 make pointers which do not have an 'optional' attribute optional
Closes #109
2023-10-21 11:02:48 +02:00
Robin Voetter
1e4e90ffb1 wrap readme 2023-09-25 21:51:52 +02:00
Robin Voetter
14259cc6f5 Merge pull request #108 from timoffex/fix-shader-comp-example
Update "Shader compilation" in README
2023-09-25 21:51:19 +02:00
Timofey Peshin
9fbfa26046 Update "Shader compilation" in README 2023-09-24 23:44:05 -07:00
Robin Voetter
348ac5d35a Merge pull request #106 from nolanderc/format-flags
Format flags
2023-08-23 22:33:55 +02:00
Christofer Nolander
190a4a054d add leading dot for bit flags format 2023-08-23 22:17:05 +02:00
Christofer Nolander
2287412536 use format mixin for bit-flags 2023-08-23 22:12:17 +02:00
Christofer Nolander
5b99c4992a format bit flags as set
This changes to format output from:

    MyFlagType{ .first_bit = true, second_bit = false, _reserved_bit_0 = false, _reserved_bit_1 = false }

to the following:

    MyFlagType{ first_bit }

That is, we only show bits which are `true`.
2023-08-23 20:01:44 +02:00
Robin Voetter
ed9401c72e Merge pull request #105 from tiawl/master
Add logs for std.zig.Ast.parse() failure
2023-08-09 22:20:58 +02:00
tiawl
4bc0666679 Add logs for std.zig.Ast.parse() failure 2023-08-09 21:23:07 +02:00
Robin Voetter
510c6b836b remove is_pub usage from builtin.Type.Declararion
This field was removed, see
3c08fe931a
2023-08-04 23:29:41 +02:00
Robin Voetter
391998e535 Merge pull request #102 from CodesOtakuYT/patch-3
Provide more info about vk.xml path and fix generator path in README
2023-07-26 18:27:42 +02:00
Codotaku
a5aac7ad14 Provide more info about vk.xml path 2023-07-26 16:39:20 +01:00
Codotaku
e014248b3b Provide more info about vk.xml path 2023-07-26 15:36:21 +01:00
Robin Voetter
4156f738f0 Merge pull request #101 from lefp/fix_optional_conflict
Fix `optional` detection conflict
2023-07-24 10:39:09 +02:00
Peter Lef
f172cbbd7d Minor readability change
To be consistent with the naming style in the previous loop.
2023-07-24 00:18:56 -04:00
Peter Lef
69402977bc Fix overwriting of pointer optionality 2023-07-24 00:18:16 -04:00
Robin Voetter
9743c9b1d3 Merge pull request #99 from lefp/optional-pointer-params
Nullable pointer parameters
2023-07-12 10:57:33 +02:00
Peter Lef
c7d3723710 Nullable pointer parameters
For procedure parameters which are of pointer type: if the associated
`count` parameter is marked `optional` in the XML, this commit makes the
parameter pointer type nullable.
2023-07-10 10:59:11 -04:00
Robin Voetter
086276bd05 Merge pull request #98 from antlilja/builtin-rework
Remove type param from cast builtins (Update to master)
2023-06-27 14:36:57 +02:00
antlilja
6c9133bc24 Remove type param from cast builtins 2023-06-27 13:09:34 +02:00
Robin Voetter
4f15927ba2 Merge pull request #97 from antlilja/master-update
Update intToFloat builtin to floatFromInt
2023-06-22 01:27:57 +02:00
antlilja
8a0be4f5de Update intToFloat builtin to floatFromInt 2023-06-22 00:32:12 +02:00
Robin Voetter
ab10325893 Merge pull request #96 from ttyyls/master
fix-readme-links
2023-06-21 09:12:13 +02:00
ttyyls
a4eb8399e0 fix-readme-links 2023-06-21 00:53:05 +01:00
Robin Voetter
03da126bc0 Merge pull request #95 from davidgm94/fix-readme-compile-error
Fix README compile error.
2023-06-19 21:03:28 +02:00
Robin Voetter
308dd180f0 Merge pull request #94 from davidgm94/master-update
keep up with master breaking changes
2023-06-19 20:52:58 +02:00
David Gonzalez Martin
0f757bfa34 Fix README compile error.
The byte slice required to be constant and it was giving a compile
error.
2023-06-19 12:51:03 -06:00
David Gonzalez Martin
c75e71333d keep up with master breaking changes 2023-06-19 12:32:52 -06:00
Robin Voetter
f6c751cdd3 Merge pull request #93 from Henrik-N/patch-1
Updated example "Manual generation with the package manager from buil…
2023-06-12 19:20:57 +02:00
Henrik Nilsson
3d98b8a273 Updated example "Manual generation with the package manager from build.zig" 2023-06-12 18:55:32 +02:00
Robin Voetter
ff48aa1581 Merge pull request #92 from CodesOtakuYT/master
use std.mem.sliceTo instead of indexOfScalar
2023-06-07 18:10:15 +02:00
CodesOtakuYT
de4ec3efa3 use std.mem.sliceTo instead of indexOfScalar 2023-06-07 17:08:27 +01:00
Robin Voetter
bbf9c886de Merge pull request #90 from CodesOtakuYT/patch-2
load the instance proc addr from vkb instead of the loader
2023-06-04 13:34:41 +02:00
Codotaku
21383ef259 load the instance proc addr from vkb instead of the loader
Am honestly not sure if this is objectively better, but I can imagine that it's cleaner to rely on GLFW proc only to load the vkb. then rely on the vkb for everything else after that.
Feedback is appreciated!
2023-06-03 23:46:05 +01:00
Robin Voetter
a795a6d5cf Merge pull request #89 from CodesOtakuYT/patch-1
Fix outdated README "generation from build.zig" instructions
2023-06-02 10:40:32 +02:00
Codotaku
97f5da4da6 Fix outdated README generation from build.zig instructions 2023-06-02 09:02:16 +01:00
Robin Voetter
7b0e3d5a9d Merge pull request #88 from Avokadoen/bool-to-u32
explicitly cast boolToInt in Wrapper
2023-05-26 19:24:43 +02:00
avokadoen
3094dc5e27 explicitly cast boolToInt in Wrapper
This resolves compile error with master zig
2023-05-26 13:17:57 +02:00
Robin Voetter
9ab420e0d7 Merge pull request #87 from Avokadoen/store-hash
Expose shader hash
2023-05-23 23:33:34 +02:00
avokadoen
9bb8e7b1f7 expose shader hash in Shader struct 2023-05-23 21:16:22 +02:00
Robin Voetter
d59005bab6 ci: update vk.zig artifact path 2023-04-17 22:15:59 +02:00
Robin Voetter
55e7dcf270 install vk.zig to prefix/src/ by default 2023-04-17 22:12:48 +02:00
Robin Voetter
303d06b3d8 Merge pull request #84 from d0miKuras/master
Fixed deprecated install step
2023-04-17 20:14:40 +02:00
Robin Voetter
8b452b9edd generate wrapper for command aliases
Instead of generating a Zig alias for aliased commands, actual wrappers
are now generated. This should make sure that extension commands, such as
vkCmdBeginRenderingKHR, can still be used on older Vulkan implementations.
2023-04-17 20:09:30 +02:00
Dominik Kurasbediani
17366388db Fixed deprecated install step 2023-04-15 18:14:28 +02:00
Robin Voetter
02939ff026 Merge pull request #82 from praschke/refresh-build
Update for zig build changes
2023-03-18 16:11:12 +01:00
praschke
2a796113e8 Update for zig build changes
- Step now holds the builder and some manifest/cache helpers
- cleaned up proxy names and remaining uses of `std.build`
- removed vicious lie from README
2023-03-18 12:26:59 +00:00
praschke
b4f7ead7e6 removed unnecessary run condition 2023-03-18 12:04:24 +00:00
Robin Voetter
40a7b871be Merge pull request #81 from antlilja/pub-vkgen
Export ShaderCompileStep and VkGenerateStep
2023-03-15 09:23:19 +01:00
antlilja
ab12ecc5d4 Remove ShaderStage from generator/index.zig
ShaderStage no longer exists but zig does not produce any compile error
because it isn't used anywhere.
2023-03-09 20:32:44 +01:00
antlilja
a893f0d880 Export shader and generate steps in build.zig
Export ShaderCompileStep and VkGenerateStep in build.zig in order to
support importing the build.zig file from other build.zig files using
vulkan-zig.
2023-03-09 20:29:19 +01:00
Robin Voetter
04105c3bb0 Merge pull request #80 from antlilja/addModule
Use new module API
2023-03-06 23:17:04 +01:00
antlilja
d8cfd033b1 Use new module API
The new module API now returns the created module as well as taking some
different parameters.
2023-03-06 23:15:16 +01:00
Robin Voetter
070500f5e5 Update parser for VulkanSC changes
The update that added the VulkanSC changes to vk.xml broke vulkan-zig previously.
2023-03-04 01:24:30 +01:00
Robin Voetter
c801ac0d2e Revert "fix workflow"
This reverts commit ac035d5ebe.

vk.xml is the correct xml file, its the one from the vulkan repository.
2023-03-03 23:45:41 +01:00
Robin Voetter
075e29c8a1 Merge pull request #78 from antlilja/multi-for
Fixed code to conform to new multi-for syntax
2023-02-23 09:27:15 +01:00
antlilja
07b13e976f Made vulkan-zig conform to new multi for syntax 2023-02-22 22:34:49 +01:00
Robin Voetter
e83a035210 Merge pull request #79 from antlilja/shader-path
Fixed bug in shader output path
2023-02-20 20:49:28 +01:00
antlilja
27c38931db Fixed bug in shader output path
The build root and cache root paths were being concatanated which
resulted in the wrong path being calculated for the shaders.
2023-02-20 15:18:44 +01:00
Robin Voetter
c887a0fcc4 Merge pull request #77 from InKryption/master
build system updates
2023-02-19 00:24:07 +01:00
InKryption
ac035d5ebe fix workflow 2023-02-18 02:29:25 +01:00
InKryption
9a4b43e15d Update README 2023-02-18 02:26:23 +01:00
InKryption
886b75272f improve option description 2023-02-18 02:00:12 +01:00
InKryption
71403a013b remove configurable file name from GenerateStep & don't use path as part of cache hash 2023-02-18 01:59:40 +01:00
InKryption
c294b849d2 make build.zig friendly to the zig package manager 2023-02-16 03:09:56 +01:00
InKryption
ef75aa0fd6 Update to latest build system changes; use caching API in GenerateStep 2023-02-16 02:21:28 +01:00
Robin Voetter
09565850a9 Explicitly pass null to p_wait_dst_stage_mask in SubmitInfo
It seems that the optional-ness of this field was changed in a recent-ish
vk.xml update.
2023-02-11 13:06:42 +01:00
Robin Voetter
1070100e2e CI: Update to ubuntu 22.04 2023-02-11 09:58:37 +01:00
Robin Voetter
3829d2eb99 CI: Always use latest Vulkan SDK 2023-02-11 09:58:06 +01:00
Robin Voetter
010160107e CI: Bump setup-zig to 2.0.1 2023-02-11 09:54:53 +01:00
Robin Voetter
c203897352 Merge pull request #76 from Avokadoen/fix-build
update build to use new build API
2023-02-08 20:28:40 +01:00
avokadoen
b09e14a649 update build to use new build API 2023-02-08 20:23:21 +01:00
Robin Voetter
782d75ac4c Merge pull request #73 from ashpil/more-defaults
More defaults for struct fields
2023-02-05 20:33:16 +01:00
ashpil
9d1ffe0fb3 no longer explicitly initialize fields which have defaults in example 2023-02-05 13:33:18 -05:00
ashpil
0873a35392 provide defaults for struct fields vulkan considers optional 2023-02-05 13:33:13 -05:00
Robin Voetter
ddc4ae1938 Merge pull request #74 from Cold-Bytes-Games/update-to-build-system-changes
Update to build system changes
2023-02-04 22:58:36 +01:00
mlarouche
e9e4e0d77f Update to latest std lib changes regarding Zig parsing 2023-02-04 16:54:15 -05:00
mlarouche
dee86a06cb Update build script to latest Build 2023-02-04 16:53:52 -05:00
Robin Voetter
2a631c4695 also generate command aliases (fixes #71) 2023-01-29 23:54:16 +01:00
Robin Voetter
16b4524166 Merge pull request #72 from ashpil/additional-watched-files
Allow specifying additional watches files for shader compilation caching
2023-01-22 11:23:22 +01:00
ashpil
737cc52908 allow specifying additional watches files for shader compilation caching 2023-01-21 19:21:32 -05:00
Robin Voetter
72959e3b11 Merge pull request #69 from ashpil/arbitrary-shader-compiler
Remove a couple glslc specific assumptions to allow an arbitrary shader compiler
2023-01-21 13:05:59 +01:00
ashpil
235edc8c67 remove a couple glslc specific assumptions 2023-01-20 22:52:41 -05:00
Robin Voetter
08dc9f508c standardize names for step creation and obtaining packages
stdlib style is to use `create` for step creation and `getPackage`/`getSource`
to provide generated sources as package/file.
2022-12-30 00:43:29 +01:00
Robin Voetter
f7a4e4346e Improve ShaderCreateStep to work around cache issues 2022-12-30 00:31:48 +01:00
Robin Voetter
d9377c4c70 use addShaderBase64 in build.zig for now 2022-12-23 00:10:44 +01:00
Robin Voetter
8c4cb60b3f Merge pull request #66 from a-day-old-bagel/base64
Added option to add shaders as base64 instead of embedding file
2022-12-23 00:07:49 +01:00
Robin Voetter
6527b04aaa Merge pull request #62 from clickingbuttons/master
Copy src path in ShaderCompileStep.add
2022-12-22 23:14:21 +01:00
Robin Voetter
ee22921bb6 Merge pull request #64 from Avokadoen/update-zig
rename StructField field_type to type
2022-12-22 23:13:35 +01:00
a-day-old-bagel
e798643829 Added option to add shaders as base64 instead of embedding file 2022-12-22 15:00:22 -07:00
Aksel Hjerpbakk
2ef2905c3d rename StructField field_type to type
breaking zig commit: aac2d6b56f
2022-12-22 15:57:25 +01:00
Robin Voetter
a56d6e31a8 allocgate 2.0 2022-12-03 02:35:40 +01:00
thesmartwon
8db9029286 Copy src 2022-12-02 19:21:28 -05:00
Robin Voetter
be59386118 change pointer size fallback to many 2022-11-27 23:24:37 +01:00
Robin Voetter
3f89cdcb80 Merge pull request #60 from a-day-old-bagel/master
updated platform enumeration for 0.11.0
2022-11-27 23:19:44 +01:00
a-day-old-bagel
5a64a8e0af updated platform enumeration for 0.11.0 2022-11-27 15:10:00 -07:00
Robin Voetter
d1ddf52e82 test that refs all decls 2022-10-07 01:37:38 +02:00
Robin Voetter
75aa7e5556 Explicitly default pNext fields again
This undoes #5, as there are still some structs which do not properly
set this value.
2022-10-07 01:36:34 +02:00
Robin Voetter
cc95608912 add missing default foreign types, fix SECURITY_ATTRIBUTES foreign type 2022-10-07 01:36:21 +02:00
Robin Voetter
135fc51b3b make basetypes with no clear type foreign
This allows the user to override them to the proper type
2022-10-07 01:35:26 +02:00
Robin Voetter
a21db9e2b5 dont write default structure type if there is none 2022-10-07 01:34:49 +02:00
Robin Voetter
08a72b582d decay arrays to pointers in parameters (fixes #54) 2022-10-07 01:33:25 +02:00
Robin Voetter
db198fb4fa bump vk.xml version 2022-10-07 00:21:15 +02:00
Robin Voetter
09d2de4fb6 Add special cases for bit packed structs
This commit adds special cases for AccelerationStructureInstanceKHR and
VkAccelerationStructureSRTMotionInstanceNV. These types use bit-packed
fields which are not representable in the current version of the zig
stage 2 compiler. This might change when
https://github.com/ziglang/zig/issues/13009 is resolved.

Fixes #56
2022-10-07 00:21:15 +02:00
Robin Voetter
80a201f89a fix alignment for shader binary 2022-09-24 00:40:17 +02:00
Robin Voetter
9e85717471 CI: Bump Vulkan SDK version 2022-09-24 00:36:41 +02:00
Robin Voetter
977b4ca5f4 remove unused unused variables 2022-09-24 00:34:46 +02:00
Robin Voetter
5b5b7d047f update generator out path in readme 2022-08-20 12:28:19 +02:00
Robin Voetter
77885af37e clean up ShaderCompileStep.make 2022-08-20 12:20:45 +02:00
Robin Voetter
5c7b6e06bb Merge pull request #50 from viviicat/multi-entrypoints
Add support for multiple entrypoints, specifying stage, and a custom output file for shader compilation
2022-08-20 12:13:44 +02:00
Robin Voetter
837893c637 clean up flags using new zig features 2022-08-20 12:10:56 +02:00
Robin Voetter
d7a608d520 elaborate on self-hosted compatibility 2022-08-20 11:41:26 +02:00
Robin Voetter
5af6ffe864 zig stage 2 compatibility 2022-08-20 11:31:36 +02:00
Vivianne Langdon
d96e32eb6e Add support for multiple entrypoints and a custom output file 2022-07-20 22:05:24 -07:00
26 changed files with 2108 additions and 17670 deletions

View File

@@ -2,45 +2,49 @@ name: Build
on:
push:
branches: [ zig-stage1-compat ]
branches: [ master ]
pull_request:
branches: [ zig-stage1-compat ]
branches: [ master ]
schedule:
- cron: '0 6 * * *'
jobs:
build:
runs-on: ubuntu-20.04
runs-on: ubuntu-22.04
steps:
- uses: actions/checkout@v2
- uses: actions/checkout@v4
- name: Setup Zig
uses: goto-bus-stop/setup-zig@v1.3.0
uses: mlugg/setup-zig@v1
with:
version: master
- name: Test
run: |
zig build -fstage1 test
- name: Check formatting
run: zig fmt --check .
- name: Fetch Vulkan SDK
- name: Fetch latest Vulkan SDK
run: |
wget -qO - https://packages.lunarg.com/lunarg-signing-key-pub.asc | sudo apt-key add -
sudo wget -qO /etc/apt/sources.list.d/lunarg-vulkan-1.3.224-focal.list https://packages.lunarg.com/vulkan/1.3.224/lunarg-vulkan-1.3.224-focal.list
sudo wget -qO /etc/apt/sources.list.d/lunarg-vulkan-jammy.list https://packages.lunarg.com/vulkan/lunarg-vulkan-jammy.list
sudo apt update
sudo apt install shaderc libglfw3 libglfw3-dev
- name: Fetch latest vk.xml
run: |
wget https://raw.githubusercontent.com/KhronosGroup/Vulkan-Docs/main/xml/vk.xml
run: wget https://raw.githubusercontent.com/KhronosGroup/Vulkan-Docs/main/xml/vk.xml
- name: Build with latest zig & vk.xml
run: |
zig build -fstage1 -Dvulkan-registry=./vk.xml
- name: Test and install with latest zig & latest vk.xml
run: zig build test install -Dregistry=$(pwd)/vk.xml
- name: Archive vk.xml
uses: actions/upload-artifact@v2
- name: Build example with latest zig & vk.xml from dependency
run: zig build --build-file $(pwd)/examples/build.zig
- name: Build example with latest zig & latest vk.xml
run: zig build --build-file $(pwd)/examples/build.zig -Doverride-registry=$(pwd)/vk.xml
- name: Archive vk.zig
uses: actions/upload-artifact@v4
with:
name: vk.zig
path: zig-cache/vk.zig
path: zig-out/src/vk.zig
if-no-files-found: error

3
.gitignore vendored
View File

@@ -1,2 +1,5 @@
zig-cache/
zig-out/
.vscode/.zig-cache/
.zig-cache/
examples/.zig-cache

177
README.md
View File

@@ -10,39 +10,92 @@ vulkan-zig attempts to provide a better experience to programming Vulkan applica
vulkan-zig is automatically tested daily against the latest vk.xml and zig, and supports vk.xml from version 1.x.163.
## Example
A partial implementation of https://vulkan-tutorial.com is implemented in [examples/triangle.zig](examples/triangle.zig). This example can be ran by executing `zig build --build-file $(pwd)/examples/build.zig run-triangle` in vulkan-zig's root. See in particular the [build file](examples/build.zig), which contains a concrete example of how to use vulkan-zig as a dependency.
### Zig versions
vulkan-zig aims to be always compatible with the ever-changing Zig master branch (however, development may lag a few days behind). Sometimes, the Zig master branch breaks a bunch of functionality however, which may make the latest version vulkan-zig incompatible with older releases of Zig. This repository aims to have a version compatible for both the latest Zig master, and the latest Zig release. The `master` branch is compatible with the `master` branch of Zig, and versions for older versions of Zig are maintained in the `zig-<version>-compat` branch.
This branch (zig-stage1-compat) is compatible with the Zig stage 1 compiler.
`master` is compatible and tested with the Zig self-hosted compiler. The `zig-stage1-compat` branch contains a version which is compatible with the Zig stage 1 compiler.
## Features
### CLI-interface
A CLI-interface is provided to generate vk.zig from the [Vulkan XML registry](https://github.com/KhronosGroup/Vulkan-Docs/blob/main/xml), which is built by default when invoking `zig build` in the project root. To generate vk.zig, simply invoke the program as follows:
```
$ zig-out/bin/vulkan-zig-generator path/to/vk.xml output/path/to/vk.zig
```
This reads the xml file, parses its contents, renders the Vulkan bindings, and formats file, before writing the result to the output path. While the intended usage of vulkan-zig is through direct generation from build.zig (see below), the CLI-interface can be used for one-off generation and vendoring the result.
### Generation from build.zig
Vulkan bindings can be generated from the Vulkan XML registry at compile time with build.zig, by using the provided Vulkan generation step:
`path/to/vk.xml` can be obtained from several sources:
- From the LunarG Vulkan SDK. This can either be obtained from [LunarG](https://www.lunarg.com/vulkan-sdk) or usually using the package manager. The registry can then be found at `$VULKAN_SDK/share/vulkan/registry/vk.xml`.
- Directly from the [Vulkan-Headers GitHub repository](https://github.com/KhronosGroup/Vulkan-Headers/blob/main/registry/vk.xml).
### Generation with the package manager from build.zig
There is also support for adding this project as a dependency through zig package manager in its current form. In order to do this, add this repo as a dependency in your build.zig.zon:
```zig
const vkgen = @import("vulkan-zig/generator/index.zig");
pub fn build(b: *Builder) void {
...
const exe = b.addExecutable("my-executable", "src/main.zig");
// Create a step that generates vk.zig (stored in zig-cache) from the provided vulkan registry.
const gen = vkgen.VkGenerateStep.init(b, "path/to/vk.xml", "vk.zig");
// Add the generated file as package to the final executable
exe.addPackage(gen.package);
.{
// -- snip --
.dependencies = .{
// -- snip --
.vulkan_zig = .{
.url = "https://github.com/Snektron/vulkan-zig/archive/<commit SHA>.tar.gz",
.hash = "<dependency hash>",
},
},
}
```
This reads vk.xml, parses its contents, and renders the Vulkan bindings to "vk.zig", which is then formatted and placed in `zig-cache`. The resulting file can then be added to an executable by using `addPackage`, after which the bindings will be made available to the executable under the name `vulkan`.
And then in your build.zig file, you'll need to add a line like this to your build function:
```zig
const vkzig_dep = b.dependency("vulkan_zig", .{
.registry = @as([]const u8, b.pathFromRoot("path/to/vk.xml")),
});
const vkzig_bindings = vkzig_dep.module("vulkan-zig");
exe.root_module.addImport("vulkan", vkzig_bindings);
```
That will allow you to `@import("vulkan")` in your executable's source.
### Manual generation with the package manager from build.zig
Bindings can also be generated by invoking the generator directly. This may be useful is some special cases, for example, it integrates particularly well with fetching the registry via the package manager. This can be done by adding the Vulkan-Headers repository to your dependencies, and then passing the `vk.xml` inside it to vulkan-zig-generator:
```zig
.{
// -- snip --
.depdendencies = .{
// -- snip --
.vulkan_headers = .{
.url = "https://github.com/KhronosGroup/Vulkan-Headers/archive/<commit SHA>.tar.gz",
.hash = "<dependency hash>",
},
},
}
```
And then pass `vk.xml` to vulkan-zig-generator as follows:
```zig
// Get the (lazy) path to vk.xml:
const registry = b.dependency("vulkan_headers", .{}).path("registry/vk.xml");
// Get generator executable reference
const vk_gen = b.dependency("vulkan_zig", .{}).artifact("vulkan-zig-generator");
// Set up a run step to generate the bindings
const vk_generate_cmd = b.addRunArtifact(vk_gen);
// Pass the registry to the generator
generate_cmd.addArg(registry);
// Create a module from the generator's output...
const vulkan_zig = b.addModule("vulkan-zig", .{
.root_source_file = vk_generate_cmd.addOutputFileArg("vk.zig"),
});
// ... and pass it as a module to your executable's build command
exe.root_module.addImport("vulkan", vulkan_zig);
```
See [examples/build.zig](examples/build.zig) and [examples/build.zig.zon](examples/build.zig.zon) for a concrete example.
### Function & field renaming
Functions and fields are renamed to be more or less in line with [Zig's standard library style](https://ziglang.org/documentation/master/#Style-Guide):
* The vk prefix is removed everywhere
* Structs like `VkInstanceCreateInfo` are renamed to `InstanceCreateInfo`.
@@ -54,6 +107,7 @@ Functions and fields are renamed to be more or less in line with [Zig's standard
* Any name which is either an illegal Zig name or a reserved identifier is rendered using `@"name"` syntax. For example, `VK_IMAGE_TYPE_2D` is translated to `@"2d"`.
### Function pointers & Wrappers
vulkan-zig provides no integration for statically linking libvulkan, and these symbols are not generated at all. Instead, vulkan functions are to be loaded dynamically. For each Vulkan function, a function pointer type is generated using the exact parameters and return types as defined by the Vulkan specification:
```zig
pub const PfnCreateInstance = fn (
@@ -68,12 +122,27 @@ For each function, a wrapper is generated into one of three structs:
* InstanceWrapper. This contains wrappers for functions which are otherwise loaded by `vkGetInstanceProcAddr`.
* DeviceWrapper. This contains wrappers for functions which are loaded by `vkGetDeviceProcAddr`.
Each wrapper struct can be called with an array of the appropriate enums:
To create a wrapper type, an "api specification" should be passed to it. This is a list of `ApiInfo` structs, which allows one to specify the functions that should be made available. An `ApiInfo` structure is initialized 3 optional fields, `base_commands`, `instance_commands`, and `device_commands`. Each of these takes a set of the vulkan functions that should be made available for that category, for example, setting `.createInstance = true` in `base_commands` makes the `createInstance` function available (loaded from `vkCreateInstance`). An entire feature level or extension can be pulled in at once too, for example, `vk.features.version_1_0` contains all functions for Vulkan 1.0. `vk.extensions.khr_surface` contains all functions for the `VK_KHR_surface` extension.
```zig
const vk = @import("vulkan");
const BaseDispatch = vk.BaseWrapper(.{
.createInstance = true,
});
/// To construct base, instance and device wrappers for vulkan-zig, you need to pass a list of 'apis' to it.
const apis: []const vk.ApiInfo = &.{
// You can either add invidiual functions by manually creating an 'api'
.{
.base_commands = .{
.createInstance = true,
},
.instance_commands = .{
.createDevice = true,
},
},
// Or you can add entire feature sets or extensions
vk.features.version_1_0,
vk.extensions.khr_surface,
vk.extensions.khr_swapchain,
};
const BaseDispatch = vk.BaseWrapper(apis);
```
The wrapper struct then provides wrapper functions for each function pointer in the dispatch struct:
```zig
@@ -157,7 +226,25 @@ By default, wrapper `load` functions return `error.CommandLoadFailure` if a call
One can access the underlying unwrapped C functions by doing `wrapper.dispatch.vkFuncYouWant(..)`.
#### Proxying Wrappers
Proxying wrappers wrap a wrapper and a pointer to the associated handle in a single struct, and automatically passes this handle to commands as appropriate. Besides the proxying wrappers for instances and devices, there are also proxying wrappers for queues and command buffers. Proxying wrapper type are constructed in the same way as a regular wrapper, by passing an api specification to them. To initialize a proxying wrapper, it must be passed a handle and a pointer to an appropriate wrapper. For queue and command buffer proxying wrappers, a pointer to a device wrapper must be passed.
```zig
// Create the dispatch tables
const InstanceDispatch = vk.InstanceWrapper(apis);
const Instance = vk.InstanceProxy(apis);
const instance_handle = try vkb.createInstance(...);
const vki = try InstanceDispatch.load(instance_handle, vkb.vkGetInstanceProcAddr);
const instance = Instance.load(instance_handle, &vki);
defer instance.destroyInstance(null);
```
For queue and command buffer proxying wrappers, the `queue` and `cmd` prefix is removed for functions where appropriate. Note that the device proxying wrappers also have the queue and command buffer functions made available for convenience, but there the prefix is not stripped.
### Bitflags
Packed structs of bools are used for bit flags in vulkan-zig, instead of both a `FlagBits` and `Flags` variant. Places where either of these variants are used are both replaced by this packed struct instead. This means that even in places where just one flag would normally be accepted, the packed struct is accepted. The programmer is responsible for only enabling a single bit.
Each bit is defaulted to `false`, and the first `bool` is aligned to guarantee the overal alignment
@@ -206,6 +293,7 @@ pub fn FlagsMixin(comptime FlagsType: type) type {
```
### Handles
Handles are generated to a non-exhaustive enum, backed by a `u64` for non-dispatchable handles and `usize` for dispatchable ones:
```zig
const Instance = extern enum(usize) { null_handle = 0, _ };
@@ -213,6 +301,7 @@ const Instance = extern enum(usize) { null_handle = 0, _ };
This means that handles are type-safe even when compiling for a 32-bit target.
### Struct defaults
Defaults are generated for certain fields of structs:
* sType is defaulted to the appropriate value.
* pNext is defaulted to `null`.
@@ -227,6 +316,7 @@ pub const InstanceCreateInfo = extern struct {
```
### Pointer types
Pointer types in both commands (wrapped and function pointers) and struct fields are augmented with the following information, where available in the registry:
* Pointer optional-ness.
* Pointer const-ness.
@@ -235,45 +325,50 @@ Pointer types in both commands (wrapped and function pointers) and struct fields
Note that this information is not everywhere as useful in the registry, leading to places where optional-ness is not correct. Most notably, CreateInfo type structures which take a slice often have the item count marked as optional, but the pointer itself not. As of yet, this is not fixed in vulkan-zig. If drivers properly follow the Vulkan specification, these can be initialized to `undefined`, however, [that is not always the case](https://zeux.io/2019/07/17/serializing-pipeline-cache/).
### Platform types
Defaults with the same ABI layout are generated for most platform-defined types. These can either by bitcasted to, or overridden by defining them in the project root:
```zig
pub const xcb_connection_t = if (@hasDecl(root, "xcb_connection_t")) root.xcb_connection_t else @Type(.Opaque);
pub const xcb_connection_t = if (@hasDecl(root, "xcb_connection_t")) root.xcb_connection_t else opaque{};
```
For some times (such as those from Google Games Platform) no default is known. Usage of these without providing a concrete type in the project root generates a compile error.
For some times (such as those from Google Games Platform) no default is known, but an `opaque{}` will be used by default. Usage of these without providing a concrete type in the project root is likely an error.
### Shader compilation
vulkan-zig provides functionality to help compiling shaders using glslc. It can be used from build.zig as follows:
Shaders should be compiled by invoking a shader compiler via the build system. For example:
```zig
const vkgen = @import("vulkan-zig/generator/index.zig");
pub fn build(b: *Builder) void {
...
const exe = b.addExecutable("my-executable", "src/main.zig");
const gen = vkgen.VkGenerateStep(b, "path/to/vk.xml", "vk.zig");
exe.addPackage(gen.package);
const shader_comp = vkgen.ShaderCompileStep.init(
builder,
&[_][]const u8{"glslc", "--target-env=vulkan1.2"}, // Path to glslc and additional parameters
);
exe.step.dependOn(&shader_comp.step);
const spv_path = shader_comp.addShader("path/to/shader.frag");
const vert_cmd = b.addSystemCommand(&.{
"glslc",
"--target-env=vulkan1.2",
"-o"
});
const vert_spv = vert_cmd.addOutputFileArg("vert.spv");
vert_cmd.addFileArg(b.path("shaders/triangle.vert"));
exe.root_module.addAnonymousImport("vertex_shader", .{
.root_source_file = vert_spv
});
...
}
```
Upon compilation, glslc is then invoked to compile each shader, and the result is placed within `zig-cache`. `addShader` returns the full path to the compiled shader code. This file can then be included in the project, as is done in [build.zig for the example](build.zig) by generating an additional file which uses `@embedFile`.
Note that SPIR-V must be 32-bit aligned when fed to Vulkan. The easiest way to do this is to dereference the shader's bytecode and manually align it as follows:
```zig
const vert_spv align(@alignOf(u32)) = @embedFile("vertex_shader").*;
```
See [examples/build.zig](examples/build.zig) for a working example.
For more advanced shader compiler usage, one may consider a library such as [shader_compiler](https://github.com/Games-by-Mason/shader_compiler).
## Limitations
* Currently, the self-hosted version of Zig's cache-hash API is not yet ready for usage, which means that the bindings are regenerated every time an executable is built.
* vulkan-zig has as of yet no functionality for selecting feature levels and extensions when generating bindings. This is because when an extension is promoted to Vulkan core, its fields and commands are renamed to lose the extensions author tag (for example, VkSemaphoreWaitFlagsKHR was renamed to VkSemaphoreWaitFlags when it was promoted from an extension to Vulkan 1.2 core). This leads to inconsistencies when only items from up to a certain feature level is included, as these promoted items then need to re-gain a tag.
## Example
A partial implementation of https://vulkan-tutorial.org is implemented in [examples/triangle.zig](examples/triangle.zig). This example can be ran by executing `zig build run-triangle` in vulkan-zig's root.
## See also
* Implementation of https://vulkan-tutorial.org using `@cImport`'ed bindings: https://github.com/andrewrk/zig-vulkan-triangle.
* Implementation of https://vulkan-tutorial.com using `@cImport`'ed bindings: https://github.com/andrewrk/zig-vulkan-triangle.
* Alternative binding generator: https://github.com/SpexGuy/Zig-Vulkan-Headers
* Zig bindings for GLFW: https://github.com/hexops/mach-glfw
* With vulkan-zig integration example: https://github.com/hexops/mach-glfw-vulkan-example
* Advanced shader compilation: https://github.com/Games-by-Mason/shader_compiler

146
build.zig
View File

@@ -1,110 +1,56 @@
const std = @import("std");
const vkgen = @import("generator/index.zig");
const Step = std.build.Step;
const Builder = std.build.Builder;
pub const ResourceGenStep = struct {
step: Step,
shader_step: *vkgen.ShaderCompileStep,
builder: *Builder,
package: std.build.Pkg,
output_file: std.build.GeneratedFile,
resources: std.ArrayList(u8),
pub fn init(builder: *Builder, out: []const u8) *ResourceGenStep {
const self = builder.allocator.create(ResourceGenStep) catch unreachable;
const full_out_path = std.fs.path.join(builder.allocator, &[_][]const u8{
builder.build_root,
builder.cache_root,
out,
}) catch unreachable;
self.* = .{
.step = Step.init(.custom, "resources", builder.allocator, make),
.shader_step = vkgen.ShaderCompileStep.init(builder, &[_][]const u8{ "glslc", "--target-env=vulkan1.2" }, "shaders"),
.builder = builder,
.package = .{
.name = "resources",
.source = .{ .generated = &self.output_file },
.dependencies = null,
},
.output_file = .{
.step = &self.step,
.path = full_out_path,
},
.resources = std.ArrayList(u8).init(builder.allocator),
};
self.step.dependOn(&self.shader_step.step);
return self;
}
fn renderPath(path: []const u8, writer: anytype) void {
const separators = &[_]u8{ std.fs.path.sep_windows, std.fs.path.sep_posix };
var i: usize = 0;
while (std.mem.indexOfAnyPos(u8, path, i, separators)) |j| {
writer.writeAll(path[i..j]) catch unreachable;
switch (std.fs.path.sep) {
std.fs.path.sep_windows => writer.writeAll("\\\\") catch unreachable,
std.fs.path.sep_posix => writer.writeByte(std.fs.path.sep_posix) catch unreachable,
else => unreachable,
}
i = j + 1;
}
writer.writeAll(path[i..]) catch unreachable;
}
pub fn addShader(self: *ResourceGenStep, name: []const u8, source: []const u8) void {
const shader_out_path = self.shader_step.add(source, .{});
var writer = self.resources.writer();
writer.print("pub const {s} align(@alignOf(u32)) = @embedFile(\"", .{name}) catch unreachable;
renderPath(shader_out_path, writer);
writer.writeAll("\").*;\n") catch unreachable;
}
fn make(step: *Step) !void {
const self = @fieldParentPtr(ResourceGenStep, "step", step);
const cwd = std.fs.cwd();
const dir = std.fs.path.dirname(self.output_file.path.?).?;
try cwd.makePath(dir);
try cwd.writeFile(self.output_file.path.?, self.resources.items);
}
};
pub fn build(b: *Builder) void {
var test_step = b.step("test", "Run all the tests");
test_step.dependOn(&b.addTest("generator/index.zig").step);
pub fn build(b: *std.Build) void {
const target = b.standardTargetOptions(.{});
const mode = b.standardReleaseOptions();
const optimize = b.standardOptimizeOption(.{});
const maybe_registry: ?[]const u8 = b.option([]const u8, "registry", "Set the path to the Vulkan registry (vk.xml)");
const test_step = b.step("test", "Run all the tests");
const generator_exe = b.addExecutable("vulkan-zig-generator", "generator/main.zig");
generator_exe.setTarget(target);
generator_exe.setBuildMode(mode);
generator_exe.install();
// Using the package manager, this artifact can be obtained by the user
// through `b.dependency(<name in build.zig.zon>, .{}).artifact("vulkan-zig-generator")`.
// with that, the user need only `.addArg("path/to/vk.xml")`, and then obtain
// a file source to the generated code with `.addOutputArg("vk.zig")`
const generator_exe = b.addExecutable(.{
.name = "vulkan-zig-generator",
.root_source_file = b.path("src/main.zig"),
.target = target,
.optimize = optimize,
});
b.installArtifact(generator_exe);
const triangle_exe = b.addExecutable("triangle", "examples/triangle.zig");
triangle_exe.setTarget(target);
triangle_exe.setBuildMode(mode);
triangle_exe.install();
triangle_exe.linkLibC();
triangle_exe.linkSystemLibrary("glfw");
// Or they can skip all that, and just make sure to pass `.registry = "path/to/vk.xml"` to `b.dependency`,
// and then obtain the module directly via `.module("vulkan-zig")`.
if (maybe_registry) |registry| {
const vk_generate_cmd = b.addRunArtifact(generator_exe);
const vk_xml_path = b.option([]const u8, "vulkan-registry", "Override the path to the Vulkan registry") orelse "examples/vk.xml";
vk_generate_cmd.addArg(registry);
const gen = vkgen.VkGenerateStep.init(b, vk_xml_path, "vk.zig");
triangle_exe.addPackage(gen.package);
const vk_zig = vk_generate_cmd.addOutputFileArg("vk.zig");
const vk_zig_module = b.addModule("vulkan-zig", .{
.root_source_file = vk_zig,
});
const res = ResourceGenStep.init(b, "resources.zig");
res.addShader("triangle_vert", "examples/shaders/triangle.vert");
res.addShader("triangle_frag", "examples/shaders/triangle.frag");
triangle_exe.addPackage(res.package);
// Also install vk.zig, if passed.
const triangle_run_cmd = triangle_exe.run();
triangle_run_cmd.step.dependOn(b.getInstallStep());
const triangle_run_step = b.step("run-triangle", "Run the triangle example");
triangle_run_step.dependOn(&triangle_run_cmd.step);
const vk_zig_install_step = b.addInstallFile(vk_zig, "src/vk.zig");
b.getInstallStep().dependOn(&vk_zig_install_step.step);
// And run tests on this vk.zig too.
// This test needs to be an object so that vulkan-zig can import types from the root.
// It does not need to run anyway.
const ref_all_decls_test = b.addObject(.{
.name = "ref-all-decls-test",
.root_source_file = b.path("test/ref_all_decls.zig"),
.target = target,
.optimize = optimize,
});
ref_all_decls_test.root_module.addImport("vulkan", vk_zig_module);
test_step.dependOn(&ref_all_decls_test.step);
}
const test_target = b.addTest(.{
.root_source_file = b.path("src/main.zig"),
});
test_step.dependOn(&b.addRunArtifact(test_target).step);
}

11
build.zig.zon Normal file
View File

@@ -0,0 +1,11 @@
.{
.name = "vulkan",
.version = "0.0.0",
.minimum_zig_version = "0.14.0-dev.1359+e9a00ba7f",
.paths = .{
"build.zig",
"LICENSE",
"README.md",
"src",
},
}

62
examples/build.zig Normal file
View File

@@ -0,0 +1,62 @@
const std = @import("std");
const vkgen = @import("vulkan_zig");
pub fn build(b: *std.Build) void {
const target = b.standardTargetOptions(.{});
const optimize = b.standardOptimizeOption(.{});
const maybe_override_registry = b.option([]const u8, "override-registry", "Override the path to the Vulkan registry used for the examples");
const registry = b.dependency("vulkan_headers", .{}).path("registry/vk.xml");
const triangle_exe = b.addExecutable(.{
.name = "triangle",
.root_source_file = b.path("triangle.zig"),
.target = target,
.link_libc = true,
.optimize = optimize,
});
b.installArtifact(triangle_exe);
triangle_exe.linkSystemLibrary("glfw");
const vk_gen = b.dependency("vulkan_zig", .{}).artifact("vulkan-zig-generator");
const vk_generate_cmd = b.addRunArtifact(vk_gen);
if (maybe_override_registry) |override_registry| {
vk_generate_cmd.addFileArg(.{ .cwd_relative = override_registry });
} else {
vk_generate_cmd.addFileArg(registry);
}
triangle_exe.root_module.addAnonymousImport("vulkan", .{
.root_source_file = vk_generate_cmd.addOutputFileArg("vk.zig"),
});
const vert_cmd = b.addSystemCommand(&.{
"glslc",
"--target-env=vulkan1.2",
"-o",
});
const vert_spv = vert_cmd.addOutputFileArg("vert.spv");
vert_cmd.addFileArg(b.path("shaders/triangle.vert"));
triangle_exe.root_module.addAnonymousImport("vertex_shader", .{
.root_source_file = vert_spv,
});
const frag_cmd = b.addSystemCommand(&.{
"glslc",
"--target-env=vulkan1.2",
"-o",
});
const frag_spv = frag_cmd.addOutputFileArg("frag.spv");
frag_cmd.addFileArg(b.path("shaders/triangle.frag"));
triangle_exe.root_module.addAnonymousImport("fragment_shader", .{
.root_source_file = frag_spv,
});
const triangle_run_cmd = b.addRunArtifact(triangle_exe);
triangle_run_cmd.step.dependOn(b.getInstallStep());
const triangle_run_step = b.step("run-triangle", "Run the triangle example");
triangle_run_step.dependOn(&triangle_run_cmd.step);
}

14
examples/build.zig.zon Normal file
View File

@@ -0,0 +1,14 @@
.{
.name = "vulkan-zig-examples",
.version = "0.1.0",
.dependencies = .{
.vulkan_zig = .{
.path = "..",
},
.vulkan_headers = .{
.url = "https://github.com/KhronosGroup/Vulkan-Headers/archive/v1.3.283.tar.gz",
.hash = "1220a7e73d72a0d56bc2a65f9d8999a7c019e42260a0744c408d1cded111bc205e10",
},
},
.paths = .{""},
}

View File

@@ -1,14 +1,32 @@
pub usingnamespace @cImport({
const c = @cImport({
@cDefine("GLFW_INCLUDE_NONE", {});
@cInclude("GLFW/glfw3.h");
});
const vk = @import("vulkan");
const c = @This();
// Re-export the GLFW things that we need
pub const GLFW_TRUE = c.GLFW_TRUE;
pub const GLFW_FALSE = c.GLFW_FALSE;
pub const GLFW_CLIENT_API = c.GLFW_CLIENT_API;
pub const GLFW_NO_API = c.GLFW_NO_API;
pub const GLFWwindow = c.GLFWwindow;
pub const glfwInit = c.glfwInit;
pub const glfwTerminate = c.glfwTerminate;
pub const glfwVulkanSupported = c.glfwVulkanSupported;
pub const glfwWindowHint = c.glfwWindowHint;
pub const glfwCreateWindow = c.glfwCreateWindow;
pub const glfwDestroyWindow = c.glfwDestroyWindow;
pub const glfwWindowShouldClose = c.glfwWindowShouldClose;
pub const glfwGetRequiredInstanceExtensions = c.glfwGetRequiredInstanceExtensions;
pub const glfwGetFramebufferSize = c.glfwGetFramebufferSize;
pub const glfwPollEvents = c.glfwPollEvents;
// usually the GLFW vulkan functions are exported if Vulkan is included,
// but since thats not the case here, they are manually imported.
// but since thats not the case here, they are manually imported.
pub extern fn glfwGetInstanceProcAddress(instance: vk.Instance, procname: [*:0]const u8) vk.PfnVoidFunction;
pub extern fn glfwGetPhysicalDevicePresentationSupport(instance: vk.Instance, pdev: vk.PhysicalDevice, queuefamily: u32) c_int;
pub extern fn glfwCreateWindowSurface(instance: vk.Instance, window: *c.GLFWwindow, allocation_callbacks: ?*const vk.AllocationCallbacks, surface: *vk.SurfaceKHR) vk.Result;
pub extern fn glfwCreateWindowSurface(instance: vk.Instance, window: *GLFWwindow, allocation_callbacks: ?*const vk.AllocationCallbacks, surface: *vk.SurfaceKHR) vk.Result;

View File

@@ -3,98 +3,54 @@ const vk = @import("vulkan");
const c = @import("c.zig");
const Allocator = std.mem.Allocator;
const required_device_extensions = [_][*:0]const u8{vk.extension_info.khr_swapchain.name};
const required_device_extensions = [_][*:0]const u8{vk.extensions.khr_swapchain.name};
const BaseDispatch = vk.BaseWrapper(.{
.createInstance = true,
});
/// To construct base, instance and device wrappers for vulkan-zig, you need to pass a list of 'apis' to it.
const apis: []const vk.ApiInfo = &.{
// You can either add invidiual functions by manually creating an 'api'
.{
.base_commands = .{
.createInstance = true,
},
.instance_commands = .{
.createDevice = true,
},
},
// Or you can add entire feature sets or extensions
vk.features.version_1_0,
vk.extensions.khr_surface,
vk.extensions.khr_swapchain,
};
const InstanceDispatch = vk.InstanceWrapper(.{
.destroyInstance = true,
.createDevice = true,
.destroySurfaceKHR = true,
.enumeratePhysicalDevices = true,
.getPhysicalDeviceProperties = true,
.enumerateDeviceExtensionProperties = true,
.getPhysicalDeviceSurfaceFormatsKHR = true,
.getPhysicalDeviceSurfacePresentModesKHR = true,
.getPhysicalDeviceSurfaceCapabilitiesKHR = true,
.getPhysicalDeviceQueueFamilyProperties = true,
.getPhysicalDeviceSurfaceSupportKHR = true,
.getPhysicalDeviceMemoryProperties = true,
.getDeviceProcAddr = true,
});
/// Next, pass the `apis` to the wrappers to create dispatch tables.
const BaseDispatch = vk.BaseWrapper(apis);
const InstanceDispatch = vk.InstanceWrapper(apis);
const DeviceDispatch = vk.DeviceWrapper(apis);
const DeviceDispatch = vk.DeviceWrapper(.{
.destroyDevice = true,
.getDeviceQueue = true,
.createSemaphore = true,
.createFence = true,
.createImageView = true,
.destroyImageView = true,
.destroySemaphore = true,
.destroyFence = true,
.getSwapchainImagesKHR = true,
.createSwapchainKHR = true,
.destroySwapchainKHR = true,
.acquireNextImageKHR = true,
.deviceWaitIdle = true,
.waitForFences = true,
.resetFences = true,
.queueSubmit = true,
.queuePresentKHR = true,
.createCommandPool = true,
.destroyCommandPool = true,
.allocateCommandBuffers = true,
.freeCommandBuffers = true,
.queueWaitIdle = true,
.createShaderModule = true,
.destroyShaderModule = true,
.createPipelineLayout = true,
.destroyPipelineLayout = true,
.createRenderPass = true,
.destroyRenderPass = true,
.createGraphicsPipelines = true,
.destroyPipeline = true,
.createFramebuffer = true,
.destroyFramebuffer = true,
.beginCommandBuffer = true,
.endCommandBuffer = true,
.allocateMemory = true,
.freeMemory = true,
.createBuffer = true,
.destroyBuffer = true,
.getBufferMemoryRequirements = true,
.mapMemory = true,
.unmapMemory = true,
.bindBufferMemory = true,
.cmdBeginRenderPass = true,
.cmdEndRenderPass = true,
.cmdBindPipeline = true,
.cmdDraw = true,
.cmdSetViewport = true,
.cmdSetScissor = true,
.cmdBindVertexBuffers = true,
.cmdCopyBuffer = true,
});
// Also create some proxying wrappers, which also have the respective handles
const Instance = vk.InstanceProxy(apis);
const Device = vk.DeviceProxy(apis);
pub const GraphicsContext = struct {
vkb: BaseDispatch,
vki: InstanceDispatch,
vkd: DeviceDispatch,
pub const CommandBuffer = vk.CommandBufferProxy(apis);
instance: vk.Instance,
allocator: Allocator,
vkb: BaseDispatch,
instance: Instance,
surface: vk.SurfaceKHR,
pdev: vk.PhysicalDevice,
props: vk.PhysicalDeviceProperties,
mem_props: vk.PhysicalDeviceMemoryProperties,
dev: vk.Device,
dev: Device,
graphics_queue: Queue,
present_queue: Queue,
pub fn init(allocator: Allocator, app_name: [*:0]const u8, window: *c.GLFWwindow) !GraphicsContext {
var self: GraphicsContext = undefined;
self.allocator = allocator;
self.vkb = try BaseDispatch.load(c.glfwGetInstanceProcAddress);
var glfw_exts_count: u32 = 0;
@@ -108,51 +64,59 @@ pub const GraphicsContext = struct {
.api_version = vk.API_VERSION_1_2,
};
self.instance = try self.vkb.createInstance(&.{
.flags = .{},
const instance = try self.vkb.createInstance(&.{
.p_application_info = &app_info,
.enabled_layer_count = 0,
.pp_enabled_layer_names = undefined,
.enabled_extension_count = glfw_exts_count,
.pp_enabled_extension_names = @ptrCast([*]const [*:0]const u8, glfw_exts),
.pp_enabled_extension_names = @ptrCast(glfw_exts),
}, null);
self.vki = try InstanceDispatch.load(self.instance, c.glfwGetInstanceProcAddress);
errdefer self.vki.destroyInstance(self.instance, null);
const vki = try allocator.create(InstanceDispatch);
errdefer allocator.destroy(vki);
vki.* = try InstanceDispatch.load(instance, self.vkb.dispatch.vkGetInstanceProcAddr);
self.instance = Instance.init(instance, vki);
errdefer self.instance.destroyInstance(null);
self.surface = try createSurface(self.instance, window);
errdefer self.vki.destroySurfaceKHR(self.instance, self.surface, null);
errdefer self.instance.destroySurfaceKHR(self.surface, null);
const candidate = try pickPhysicalDevice(self.vki, self.instance, allocator, self.surface);
const candidate = try pickPhysicalDevice(self.instance, allocator, self.surface);
self.pdev = candidate.pdev;
self.props = candidate.props;
self.dev = try initializeCandidate(self.vki, candidate);
self.vkd = try DeviceDispatch.load(self.dev, self.vki.dispatch.vkGetDeviceProcAddr);
errdefer self.vkd.destroyDevice(self.dev, null);
self.graphics_queue = Queue.init(self.vkd, self.dev, candidate.queues.graphics_family);
self.present_queue = Queue.init(self.vkd, self.dev, candidate.queues.present_family);
const dev = try initializeCandidate(self.instance, candidate);
self.mem_props = self.vki.getPhysicalDeviceMemoryProperties(self.pdev);
const vkd = try allocator.create(DeviceDispatch);
errdefer allocator.destroy(vkd);
vkd.* = try DeviceDispatch.load(dev, self.instance.wrapper.dispatch.vkGetDeviceProcAddr);
self.dev = Device.init(dev, vkd);
errdefer self.dev.destroyDevice(null);
self.graphics_queue = Queue.init(self.dev, candidate.queues.graphics_family);
self.present_queue = Queue.init(self.dev, candidate.queues.present_family);
self.mem_props = self.instance.getPhysicalDeviceMemoryProperties(self.pdev);
return self;
}
pub fn deinit(self: GraphicsContext) void {
self.vkd.destroyDevice(self.dev, null);
self.vki.destroySurfaceKHR(self.instance, self.surface, null);
self.vki.destroyInstance(self.instance, null);
self.dev.destroyDevice(null);
self.instance.destroySurfaceKHR(self.surface, null);
self.instance.destroyInstance(null);
// Don't forget to free the tables to prevent a memory leak.
self.allocator.destroy(self.dev.wrapper);
self.allocator.destroy(self.instance.wrapper);
}
pub fn deviceName(self: *const GraphicsContext) []const u8 {
const len = std.mem.indexOfScalar(u8, &self.props.device_name, 0).?;
return self.props.device_name[0..len];
return std.mem.sliceTo(&self.props.device_name, 0);
}
pub fn findMemoryTypeIndex(self: GraphicsContext, memory_type_bits: u32, flags: vk.MemoryPropertyFlags) !u32 {
for (self.mem_props.memory_types[0..self.mem_props.memory_type_count]) |mem_type, i| {
if (memory_type_bits & (@as(u32, 1) << @truncate(u5, i)) != 0 and mem_type.property_flags.contains(flags)) {
return @truncate(u32, i);
for (self.mem_props.memory_types[0..self.mem_props.memory_type_count], 0..) |mem_type, i| {
if (memory_type_bits & (@as(u32, 1) << @truncate(i)) != 0 and mem_type.property_flags.contains(flags)) {
return @truncate(i);
}
}
@@ -160,7 +124,7 @@ pub const GraphicsContext = struct {
}
pub fn allocate(self: GraphicsContext, requirements: vk.MemoryRequirements, flags: vk.MemoryPropertyFlags) !vk.DeviceMemory {
return try self.vkd.allocateMemory(self.dev, &.{
return try self.dev.allocateMemory(&.{
.allocation_size = requirements.size,
.memory_type_index = try self.findMemoryTypeIndex(requirements.memory_type_bits, flags),
}, null);
@@ -171,34 +135,32 @@ pub const Queue = struct {
handle: vk.Queue,
family: u32,
fn init(vkd: DeviceDispatch, dev: vk.Device, family: u32) Queue {
fn init(device: Device, family: u32) Queue {
return .{
.handle = vkd.getDeviceQueue(dev, family, 0),
.handle = device.getDeviceQueue(family, 0),
.family = family,
};
}
};
fn createSurface(instance: vk.Instance, window: *c.GLFWwindow) !vk.SurfaceKHR {
fn createSurface(instance: Instance, window: *c.GLFWwindow) !vk.SurfaceKHR {
var surface: vk.SurfaceKHR = undefined;
if (c.glfwCreateWindowSurface(instance, window, null, &surface) != .success) {
if (c.glfwCreateWindowSurface(instance.handle, window, null, &surface) != .success) {
return error.SurfaceInitFailed;
}
return surface;
}
fn initializeCandidate(vki: InstanceDispatch, candidate: DeviceCandidate) !vk.Device {
fn initializeCandidate(instance: Instance, candidate: DeviceCandidate) !vk.Device {
const priority = [_]f32{1};
const qci = [_]vk.DeviceQueueCreateInfo{
.{
.flags = .{},
.queue_family_index = candidate.queues.graphics_family,
.queue_count = 1,
.p_queue_priorities = &priority,
},
.{
.flags = .{},
.queue_family_index = candidate.queues.present_family,
.queue_count = 1,
.p_queue_priorities = &priority,
@@ -210,15 +172,11 @@ fn initializeCandidate(vki: InstanceDispatch, candidate: DeviceCandidate) !vk.De
else
2;
return try vki.createDevice(candidate.pdev, &.{
.flags = .{},
return try instance.createDevice(candidate.pdev, &.{
.queue_create_info_count = queue_count,
.p_queue_create_infos = &qci,
.enabled_layer_count = 0,
.pp_enabled_layer_names = undefined,
.enabled_extension_count = required_device_extensions.len,
.pp_enabled_extension_names = @ptrCast([*]const [*:0]const u8, &required_device_extensions),
.p_enabled_features = null,
.pp_enabled_extension_names = @ptrCast(&required_device_extensions),
}, null);
}
@@ -234,21 +192,15 @@ const QueueAllocation = struct {
};
fn pickPhysicalDevice(
vki: InstanceDispatch,
instance: vk.Instance,
instance: Instance,
allocator: Allocator,
surface: vk.SurfaceKHR,
) !DeviceCandidate {
var device_count: u32 = undefined;
_ = try vki.enumeratePhysicalDevices(instance, &device_count, null);
const pdevs = try allocator.alloc(vk.PhysicalDevice, device_count);
const pdevs = try instance.enumeratePhysicalDevicesAlloc(allocator);
defer allocator.free(pdevs);
_ = try vki.enumeratePhysicalDevices(instance, &device_count, pdevs.ptr);
for (pdevs) |pdev| {
if (try checkSuitable(vki, pdev, allocator, surface)) |candidate| {
if (try checkSuitable(instance, pdev, allocator, surface)) |candidate| {
return candidate;
}
}
@@ -257,22 +209,21 @@ fn pickPhysicalDevice(
}
fn checkSuitable(
vki: InstanceDispatch,
instance: Instance,
pdev: vk.PhysicalDevice,
allocator: Allocator,
surface: vk.SurfaceKHR,
) !?DeviceCandidate {
const props = vki.getPhysicalDeviceProperties(pdev);
if (!try checkExtensionSupport(vki, pdev, allocator)) {
if (!try checkExtensionSupport(instance, pdev, allocator)) {
return null;
}
if (!try checkSurfaceSupport(vki, pdev, surface)) {
if (!try checkSurfaceSupport(instance, pdev, surface)) {
return null;
}
if (try allocateQueues(vki, pdev, allocator, surface)) |allocation| {
if (try allocateQueues(instance, pdev, allocator, surface)) |allocation| {
const props = instance.getPhysicalDeviceProperties(pdev);
return DeviceCandidate{
.pdev = pdev,
.props = props,
@@ -283,25 +234,21 @@ fn checkSuitable(
return null;
}
fn allocateQueues(vki: InstanceDispatch, pdev: vk.PhysicalDevice, allocator: Allocator, surface: vk.SurfaceKHR) !?QueueAllocation {
var family_count: u32 = undefined;
vki.getPhysicalDeviceQueueFamilyProperties(pdev, &family_count, null);
const families = try allocator.alloc(vk.QueueFamilyProperties, family_count);
fn allocateQueues(instance: Instance, pdev: vk.PhysicalDevice, allocator: Allocator, surface: vk.SurfaceKHR) !?QueueAllocation {
const families = try instance.getPhysicalDeviceQueueFamilyPropertiesAlloc(pdev, allocator);
defer allocator.free(families);
vki.getPhysicalDeviceQueueFamilyProperties(pdev, &family_count, families.ptr);
var graphics_family: ?u32 = null;
var present_family: ?u32 = null;
for (families) |properties, i| {
const family = @intCast(u32, i);
for (families, 0..) |properties, i| {
const family: u32 = @intCast(i);
if (graphics_family == null and properties.queue_flags.graphics_bit) {
graphics_family = family;
}
if (present_family == null and (try vki.getPhysicalDeviceSurfaceSupportKHR(pdev, family, surface)) == vk.TRUE) {
if (present_family == null and (try instance.getPhysicalDeviceSurfaceSupportKHR(pdev, family, surface)) == vk.TRUE) {
present_family = family;
}
}
@@ -316,34 +263,27 @@ fn allocateQueues(vki: InstanceDispatch, pdev: vk.PhysicalDevice, allocator: All
return null;
}
fn checkSurfaceSupport(vki: InstanceDispatch, pdev: vk.PhysicalDevice, surface: vk.SurfaceKHR) !bool {
fn checkSurfaceSupport(instance: Instance, pdev: vk.PhysicalDevice, surface: vk.SurfaceKHR) !bool {
var format_count: u32 = undefined;
_ = try vki.getPhysicalDeviceSurfaceFormatsKHR(pdev, surface, &format_count, null);
_ = try instance.getPhysicalDeviceSurfaceFormatsKHR(pdev, surface, &format_count, null);
var present_mode_count: u32 = undefined;
_ = try vki.getPhysicalDeviceSurfacePresentModesKHR(pdev, surface, &present_mode_count, null);
_ = try instance.getPhysicalDeviceSurfacePresentModesKHR(pdev, surface, &present_mode_count, null);
return format_count > 0 and present_mode_count > 0;
}
fn checkExtensionSupport(
vki: InstanceDispatch,
instance: Instance,
pdev: vk.PhysicalDevice,
allocator: Allocator,
) !bool {
var count: u32 = undefined;
_ = try vki.enumerateDeviceExtensionProperties(pdev, null, &count, null);
const propsv = try allocator.alloc(vk.ExtensionProperties, count);
const propsv = try instance.enumerateDeviceExtensionPropertiesAlloc(pdev, null, allocator);
defer allocator.free(propsv);
_ = try vki.enumerateDeviceExtensionProperties(pdev, null, &count, propsv.ptr);
for (required_device_extensions) |ext| {
for (propsv) |props| {
const len = std.mem.indexOfScalar(u8, &props.extension_name, 0).?;
const prop_ext_name = props.extension_name[0..len];
if (std.mem.eql(u8, std.mem.span(ext), prop_ext_name)) {
if (std.mem.eql(u8, std.mem.span(ext), std.mem.sliceTo(&props.extension_name, 0))) {
break;
}
} else {

View File

@@ -26,7 +26,7 @@ pub const Swapchain = struct {
}
pub fn initRecycle(gc: *const GraphicsContext, allocator: Allocator, extent: vk.Extent2D, old_handle: vk.SwapchainKHR) !Swapchain {
const caps = try gc.vki.getPhysicalDeviceSurfaceCapabilitiesKHR(gc.pdev, gc.surface);
const caps = try gc.instance.getPhysicalDeviceSurfaceCapabilitiesKHR(gc.pdev, gc.surface);
const actual_extent = findActualExtent(caps, extent);
if (actual_extent.width == 0 or actual_extent.height == 0) {
return error.InvalidSurfaceDimensions;
@@ -37,7 +37,7 @@ pub const Swapchain = struct {
var image_count = caps.min_image_count + 1;
if (caps.max_image_count > 0) {
image_count = std.math.min(image_count, caps.max_image_count);
image_count = @min(image_count, caps.max_image_count);
}
const qfi = [_]u32{ gc.graphics_queue.family, gc.present_queue.family };
@@ -46,8 +46,7 @@ pub const Swapchain = struct {
else
.exclusive;
const handle = try gc.vkd.createSwapchainKHR(gc.dev, &.{
.flags = .{},
const handle = try gc.dev.createSwapchainKHR(&.{
.surface = gc.surface,
.min_image_count = image_count,
.image_format = surface_format.format,
@@ -64,11 +63,11 @@ pub const Swapchain = struct {
.clipped = vk.TRUE,
.old_swapchain = old_handle,
}, null);
errdefer gc.vkd.destroySwapchainKHR(gc.dev, handle, null);
errdefer gc.dev.destroySwapchainKHR(handle, null);
if (old_handle != .null_handle) {
// Apparently, the old swapchain handle still needs to be destroyed after recreating.
gc.vkd.destroySwapchainKHR(gc.dev, old_handle, null);
gc.dev.destroySwapchainKHR(old_handle, null);
}
const swap_images = try initSwapchainImages(gc, handle, surface_format.format, allocator);
@@ -77,10 +76,10 @@ pub const Swapchain = struct {
allocator.free(swap_images);
}
var next_image_acquired = try gc.vkd.createSemaphore(gc.dev, &.{ .flags = .{} }, null);
errdefer gc.vkd.destroySemaphore(gc.dev, next_image_acquired, null);
var next_image_acquired = try gc.dev.createSemaphore(&.{}, null);
errdefer gc.dev.destroySemaphore(next_image_acquired, null);
const result = try gc.vkd.acquireNextImageKHR(gc.dev, handle, std.math.maxInt(u64), next_image_acquired, .null_handle);
const result = try gc.dev.acquireNextImageKHR(handle, std.math.maxInt(u64), next_image_acquired, .null_handle);
if (result.result != .success) {
return error.ImageAcquireFailed;
}
@@ -102,7 +101,7 @@ pub const Swapchain = struct {
fn deinitExceptSwapchain(self: Swapchain) void {
for (self.swap_images) |si| si.deinit(self.gc);
self.allocator.free(self.swap_images);
self.gc.vkd.destroySemaphore(self.gc.dev, self.next_image_acquired, null);
self.gc.dev.destroySemaphore(self.next_image_acquired, null);
}
pub fn waitForAllFences(self: Swapchain) !void {
@@ -111,7 +110,7 @@ pub const Swapchain = struct {
pub fn deinit(self: Swapchain) void {
self.deinitExceptSwapchain();
self.gc.vkd.destroySwapchainKHR(self.gc.dev, self.handle, null);
self.gc.dev.destroySwapchainKHR(self.handle, null);
}
pub fn recreate(self: *Swapchain, new_extent: vk.Extent2D) !void {
@@ -151,33 +150,31 @@ pub const Swapchain = struct {
// Step 1: Make sure the current frame has finished rendering
const current = self.currentSwapImage();
try current.waitForFence(self.gc);
try self.gc.vkd.resetFences(self.gc.dev, 1, @ptrCast([*]const vk.Fence, &current.frame_fence));
try self.gc.dev.resetFences(1, @ptrCast(&current.frame_fence));
// Step 2: Submit the command buffer
const wait_stage = [_]vk.PipelineStageFlags{.{ .top_of_pipe_bit = true }};
try self.gc.vkd.queueSubmit(self.gc.graphics_queue.handle, 1, &[_]vk.SubmitInfo{.{
try self.gc.dev.queueSubmit(self.gc.graphics_queue.handle, 1, &[_]vk.SubmitInfo{.{
.wait_semaphore_count = 1,
.p_wait_semaphores = @ptrCast([*]const vk.Semaphore, &current.image_acquired),
.p_wait_semaphores = @ptrCast(&current.image_acquired),
.p_wait_dst_stage_mask = &wait_stage,
.command_buffer_count = 1,
.p_command_buffers = @ptrCast([*]const vk.CommandBuffer, &cmdbuf),
.p_command_buffers = @ptrCast(&cmdbuf),
.signal_semaphore_count = 1,
.p_signal_semaphores = @ptrCast([*]const vk.Semaphore, &current.render_finished),
.p_signal_semaphores = @ptrCast(&current.render_finished),
}}, current.frame_fence);
// Step 3: Present the current frame
_ = try self.gc.vkd.queuePresentKHR(self.gc.present_queue.handle, &.{
_ = try self.gc.dev.queuePresentKHR(self.gc.present_queue.handle, &.{
.wait_semaphore_count = 1,
.p_wait_semaphores = @ptrCast([*]const vk.Semaphore, &current.render_finished),
.p_wait_semaphores = @ptrCast(&current.render_finished),
.swapchain_count = 1,
.p_swapchains = @ptrCast([*]const vk.SwapchainKHR, &self.handle),
.p_image_indices = @ptrCast([*]const u32, &self.image_index),
.p_results = null,
.p_swapchains = @ptrCast(&self.handle),
.p_image_indices = @ptrCast(&self.image_index),
});
// Step 4: Acquire next frame
const result = try self.gc.vkd.acquireNextImageKHR(
self.gc.dev,
const result = try self.gc.dev.acquireNextImageKHR(
self.handle,
std.math.maxInt(u64),
self.next_image_acquired,
@@ -203,8 +200,7 @@ const SwapImage = struct {
frame_fence: vk.Fence,
fn init(gc: *const GraphicsContext, image: vk.Image, format: vk.Format) !SwapImage {
const view = try gc.vkd.createImageView(gc.dev, &.{
.flags = .{},
const view = try gc.dev.createImageView(&.{
.image = image,
.view_type = .@"2d",
.format = format,
@@ -217,16 +213,16 @@ const SwapImage = struct {
.layer_count = 1,
},
}, null);
errdefer gc.vkd.destroyImageView(gc.dev, view, null);
errdefer gc.dev.destroyImageView(view, null);
const image_acquired = try gc.vkd.createSemaphore(gc.dev, &.{ .flags = .{} }, null);
errdefer gc.vkd.destroySemaphore(gc.dev, image_acquired, null);
const image_acquired = try gc.dev.createSemaphore(&.{}, null);
errdefer gc.dev.destroySemaphore(image_acquired, null);
const render_finished = try gc.vkd.createSemaphore(gc.dev, &.{ .flags = .{} }, null);
errdefer gc.vkd.destroySemaphore(gc.dev, render_finished, null);
const render_finished = try gc.dev.createSemaphore(&.{}, null);
errdefer gc.dev.destroySemaphore(render_finished, null);
const frame_fence = try gc.vkd.createFence(gc.dev, &.{ .flags = .{ .signaled_bit = true } }, null);
errdefer gc.vkd.destroyFence(gc.dev, frame_fence, null);
const frame_fence = try gc.dev.createFence(&.{ .flags = .{ .signaled_bit = true } }, null);
errdefer gc.dev.destroyFence(frame_fence, null);
return SwapImage{
.image = image,
@@ -239,25 +235,22 @@ const SwapImage = struct {
fn deinit(self: SwapImage, gc: *const GraphicsContext) void {
self.waitForFence(gc) catch return;
gc.vkd.destroyImageView(gc.dev, self.view, null);
gc.vkd.destroySemaphore(gc.dev, self.image_acquired, null);
gc.vkd.destroySemaphore(gc.dev, self.render_finished, null);
gc.vkd.destroyFence(gc.dev, self.frame_fence, null);
gc.dev.destroyImageView(self.view, null);
gc.dev.destroySemaphore(self.image_acquired, null);
gc.dev.destroySemaphore(self.render_finished, null);
gc.dev.destroyFence(self.frame_fence, null);
}
fn waitForFence(self: SwapImage, gc: *const GraphicsContext) !void {
_ = try gc.vkd.waitForFences(gc.dev, 1, @ptrCast([*]const vk.Fence, &self.frame_fence), vk.TRUE, std.math.maxInt(u64));
_ = try gc.dev.waitForFences(1, @ptrCast(&self.frame_fence), vk.TRUE, std.math.maxInt(u64));
}
};
fn initSwapchainImages(gc: *const GraphicsContext, swapchain: vk.SwapchainKHR, format: vk.Format, allocator: Allocator) ![]SwapImage {
var count: u32 = undefined;
_ = try gc.vkd.getSwapchainImagesKHR(gc.dev, swapchain, &count, null);
const images = try allocator.alloc(vk.Image, count);
const images = try gc.dev.getSwapchainImagesAllocKHR(swapchain, allocator);
defer allocator.free(images);
_ = try gc.vkd.getSwapchainImagesKHR(gc.dev, swapchain, &count, images.ptr);
const swap_images = try allocator.alloc(SwapImage, count);
const swap_images = try allocator.alloc(SwapImage, images.len);
errdefer allocator.free(swap_images);
var i: usize = 0;
@@ -277,11 +270,8 @@ fn findSurfaceFormat(gc: *const GraphicsContext, allocator: Allocator) !vk.Surfa
.color_space = .srgb_nonlinear_khr,
};
var count: u32 = undefined;
_ = try gc.vki.getPhysicalDeviceSurfaceFormatsKHR(gc.pdev, gc.surface, &count, null);
const surface_formats = try allocator.alloc(vk.SurfaceFormatKHR, count);
const surface_formats = try gc.instance.getPhysicalDeviceSurfaceFormatsAllocKHR(gc.pdev, gc.surface, allocator);
defer allocator.free(surface_formats);
_ = try gc.vki.getPhysicalDeviceSurfaceFormatsKHR(gc.pdev, gc.surface, &count, surface_formats.ptr);
for (surface_formats) |sfmt| {
if (std.meta.eql(sfmt, preferred)) {
@@ -293,11 +283,8 @@ fn findSurfaceFormat(gc: *const GraphicsContext, allocator: Allocator) !vk.Surfa
}
fn findPresentMode(gc: *const GraphicsContext, allocator: Allocator) !vk.PresentModeKHR {
var count: u32 = undefined;
_ = try gc.vki.getPhysicalDeviceSurfacePresentModesKHR(gc.pdev, gc.surface, &count, null);
const present_modes = try allocator.alloc(vk.PresentModeKHR, count);
const present_modes = try gc.instance.getPhysicalDeviceSurfacePresentModesAllocKHR(gc.pdev, gc.surface, allocator);
defer allocator.free(present_modes);
_ = try gc.vki.getPhysicalDeviceSurfacePresentModesKHR(gc.pdev, gc.surface, &count, present_modes.ptr);
const preferred = [_]vk.PresentModeKHR{
.mailbox_khr,

View File

@@ -1,11 +1,13 @@
const std = @import("std");
const vk = @import("vulkan");
const c = @import("c.zig");
const resources = @import("resources");
const GraphicsContext = @import("graphics_context.zig").GraphicsContext;
const Swapchain = @import("swapchain.zig").Swapchain;
const Allocator = std.mem.Allocator;
const vert_spv align(@alignOf(u32)) = @embedFile("vertex_shader").*;
const frag_spv align(@alignOf(u32)) = @embedFile("fragment_shader").*;
const app_name = "vulkan-zig triangle example";
const Vertex = struct {
@@ -44,12 +46,17 @@ pub fn main() !void {
if (c.glfwInit() != c.GLFW_TRUE) return error.GlfwInitFailed;
defer c.glfwTerminate();
if (c.glfwVulkanSupported() != c.GLFW_TRUE) {
std.log.err("GLFW could not find libvulkan", .{});
return error.NoVulkan;
}
var extent = vk.Extent2D{ .width = 800, .height = 600 };
c.glfwWindowHint(c.GLFW_CLIENT_API, c.GLFW_NO_API);
const window = c.glfwCreateWindow(
@intCast(c_int, extent.width),
@intCast(c_int, extent.height),
@intCast(extent.width),
@intCast(extent.height),
app_name,
null,
null,
@@ -63,48 +70,44 @@ pub fn main() !void {
const gc = try GraphicsContext.init(allocator, app_name, window);
defer gc.deinit();
std.debug.print("Using device: {s}\n", .{gc.deviceName()});
std.log.debug("Using device: {s}", .{gc.deviceName()});
var swapchain = try Swapchain.init(&gc, allocator, extent);
defer swapchain.deinit();
const pipeline_layout = try gc.vkd.createPipelineLayout(gc.dev, &.{
const pipeline_layout = try gc.dev.createPipelineLayout(&.{
.flags = .{},
.set_layout_count = 0,
.p_set_layouts = undefined,
.push_constant_range_count = 0,
.p_push_constant_ranges = undefined,
}, null);
defer gc.vkd.destroyPipelineLayout(gc.dev, pipeline_layout, null);
defer gc.dev.destroyPipelineLayout(pipeline_layout, null);
const render_pass = try createRenderPass(&gc, swapchain);
defer gc.vkd.destroyRenderPass(gc.dev, render_pass, null);
defer gc.dev.destroyRenderPass(render_pass, null);
var pipeline = try createPipeline(&gc, pipeline_layout, render_pass);
defer gc.vkd.destroyPipeline(gc.dev, pipeline, null);
const pipeline = try createPipeline(&gc, pipeline_layout, render_pass);
defer gc.dev.destroyPipeline(pipeline, null);
var framebuffers = try createFramebuffers(&gc, allocator, render_pass, swapchain);
defer destroyFramebuffers(&gc, allocator, framebuffers);
const pool = try gc.vkd.createCommandPool(gc.dev, &.{
.flags = .{},
const pool = try gc.dev.createCommandPool(&.{
.queue_family_index = gc.graphics_queue.family,
}, null);
defer gc.vkd.destroyCommandPool(gc.dev, pool, null);
defer gc.dev.destroyCommandPool(pool, null);
const buffer = try gc.vkd.createBuffer(gc.dev, &.{
.flags = .{},
const buffer = try gc.dev.createBuffer(&.{
.size = @sizeOf(@TypeOf(vertices)),
.usage = .{ .transfer_dst_bit = true, .vertex_buffer_bit = true },
.sharing_mode = .exclusive,
.queue_family_index_count = 0,
.p_queue_family_indices = undefined,
}, null);
defer gc.vkd.destroyBuffer(gc.dev, buffer, null);
const mem_reqs = gc.vkd.getBufferMemoryRequirements(gc.dev, buffer);
defer gc.dev.destroyBuffer(buffer, null);
const mem_reqs = gc.dev.getBufferMemoryRequirements(buffer);
const memory = try gc.allocate(mem_reqs, .{ .device_local_bit = true });
defer gc.vkd.freeMemory(gc.dev, memory, null);
try gc.vkd.bindBufferMemory(gc.dev, buffer, memory, 0);
defer gc.dev.freeMemory(memory, null);
try gc.dev.bindBufferMemory(buffer, memory, 0);
try uploadVertices(&gc, pool, buffer);
@@ -121,6 +124,16 @@ pub fn main() !void {
defer destroyCommandBuffers(&gc, pool, allocator, cmdbufs);
while (c.glfwWindowShouldClose(window) == c.GLFW_FALSE) {
var w: c_int = undefined;
var h: c_int = undefined;
c.glfwGetFramebufferSize(window, &w, &h);
// Don't present or resize swapchain while the window is minimized
if (w == 0 or h == 0) {
c.glfwPollEvents();
continue;
}
const cmdbuf = cmdbufs[swapchain.image_index];
const state = swapchain.present(cmdbuf) catch |err| switch (err) {
@@ -128,13 +141,9 @@ pub fn main() !void {
else => |narrow| return narrow,
};
var w: c_int = undefined;
var h: c_int = undefined;
c.glfwGetWindowSize(window, &w, &h);
if (state == .suboptimal or extent.width != @intCast(u32, w) or extent.height != @intCast(u32, h)) {
extent.width = @intCast(u32, w);
extent.height = @intCast(u32, h);
if (state == .suboptimal or extent.width != @as(u32, @intCast(w)) or extent.height != @as(u32, @intCast(h))) {
extent.width = @intCast(w);
extent.height = @intCast(h);
try swapchain.recreate(extent);
destroyFramebuffers(&gc, allocator, framebuffers);
@@ -157,48 +166,45 @@ pub fn main() !void {
}
try swapchain.waitForAllFences();
try gc.dev.deviceWaitIdle();
}
fn uploadVertices(gc: *const GraphicsContext, pool: vk.CommandPool, buffer: vk.Buffer) !void {
const staging_buffer = try gc.vkd.createBuffer(gc.dev, &.{
.flags = .{},
const staging_buffer = try gc.dev.createBuffer(&.{
.size = @sizeOf(@TypeOf(vertices)),
.usage = .{ .transfer_src_bit = true },
.sharing_mode = .exclusive,
.queue_family_index_count = 0,
.p_queue_family_indices = undefined,
}, null);
defer gc.vkd.destroyBuffer(gc.dev, staging_buffer, null);
const mem_reqs = gc.vkd.getBufferMemoryRequirements(gc.dev, staging_buffer);
defer gc.dev.destroyBuffer(staging_buffer, null);
const mem_reqs = gc.dev.getBufferMemoryRequirements(staging_buffer);
const staging_memory = try gc.allocate(mem_reqs, .{ .host_visible_bit = true, .host_coherent_bit = true });
defer gc.vkd.freeMemory(gc.dev, staging_memory, null);
try gc.vkd.bindBufferMemory(gc.dev, staging_buffer, staging_memory, 0);
defer gc.dev.freeMemory(staging_memory, null);
try gc.dev.bindBufferMemory(staging_buffer, staging_memory, 0);
{
const data = try gc.vkd.mapMemory(gc.dev, staging_memory, 0, vk.WHOLE_SIZE, .{});
defer gc.vkd.unmapMemory(gc.dev, staging_memory);
const data = try gc.dev.mapMemory(staging_memory, 0, vk.WHOLE_SIZE, .{});
defer gc.dev.unmapMemory(staging_memory);
const gpu_vertices = @ptrCast([*]Vertex, @alignCast(@alignOf(Vertex), data));
for (vertices) |vertex, i| {
gpu_vertices[i] = vertex;
}
const gpu_vertices: [*]Vertex = @ptrCast(@alignCast(data));
@memcpy(gpu_vertices, vertices[0..]);
}
try copyBuffer(gc, pool, buffer, staging_buffer, @sizeOf(@TypeOf(vertices)));
}
fn copyBuffer(gc: *const GraphicsContext, pool: vk.CommandPool, dst: vk.Buffer, src: vk.Buffer, size: vk.DeviceSize) !void {
var cmdbuf: vk.CommandBuffer = undefined;
try gc.vkd.allocateCommandBuffers(gc.dev, &.{
var cmdbuf_handle: vk.CommandBuffer = undefined;
try gc.dev.allocateCommandBuffers(&.{
.command_pool = pool,
.level = .primary,
.command_buffer_count = 1,
}, @ptrCast([*]vk.CommandBuffer, &cmdbuf));
defer gc.vkd.freeCommandBuffers(gc.dev, pool, 1, @ptrCast([*]const vk.CommandBuffer, &cmdbuf));
}, @ptrCast(&cmdbuf_handle));
defer gc.dev.freeCommandBuffers(pool, 1, @ptrCast(&cmdbuf_handle));
try gc.vkd.beginCommandBuffer(cmdbuf, &.{
const cmdbuf = GraphicsContext.CommandBuffer.init(cmdbuf_handle, gc.dev.wrapper);
try cmdbuf.beginCommandBuffer(&.{
.flags = .{ .one_time_submit_bit = true },
.p_inheritance_info = null,
});
const region = vk.BufferCopy{
@@ -206,21 +212,17 @@ fn copyBuffer(gc: *const GraphicsContext, pool: vk.CommandPool, dst: vk.Buffer,
.dst_offset = 0,
.size = size,
};
gc.vkd.cmdCopyBuffer(cmdbuf, src, dst, 1, @ptrCast([*]const vk.BufferCopy, &region));
cmdbuf.copyBuffer(src, dst, 1, @ptrCast(&region));
try gc.vkd.endCommandBuffer(cmdbuf);
try cmdbuf.endCommandBuffer();
const si = vk.SubmitInfo{
.wait_semaphore_count = 0,
.p_wait_semaphores = undefined,
.p_wait_dst_stage_mask = undefined,
.command_buffer_count = 1,
.p_command_buffers = @ptrCast([*]const vk.CommandBuffer, &cmdbuf),
.signal_semaphore_count = 0,
.p_signal_semaphores = undefined,
.p_command_buffers = (&cmdbuf.handle)[0..1],
.p_wait_dst_stage_mask = undefined,
};
try gc.vkd.queueSubmit(gc.graphics_queue.handle, 1, @ptrCast([*]const vk.SubmitInfo, &si), .null_handle);
try gc.vkd.queueWaitIdle(gc.graphics_queue.handle);
try gc.dev.queueSubmit(gc.graphics_queue.handle, 1, @ptrCast(&si), .null_handle);
try gc.dev.queueWaitIdle(gc.graphics_queue.handle);
}
fn createCommandBuffers(
@@ -236,12 +238,12 @@ fn createCommandBuffers(
const cmdbufs = try allocator.alloc(vk.CommandBuffer, framebuffers.len);
errdefer allocator.free(cmdbufs);
try gc.vkd.allocateCommandBuffers(gc.dev, &.{
try gc.dev.allocateCommandBuffers(&.{
.command_pool = pool,
.level = .primary,
.command_buffer_count = @truncate(u32, cmdbufs.len),
.command_buffer_count = @intCast(cmdbufs.len),
}, cmdbufs.ptr);
errdefer gc.vkd.freeCommandBuffers(gc.dev, pool, @truncate(u32, cmdbufs.len), cmdbufs.ptr);
errdefer gc.dev.freeCommandBuffers(pool, @intCast(cmdbufs.len), cmdbufs.ptr);
const clear = vk.ClearValue{
.color = .{ .float_32 = .{ 0, 0, 0, 1 } },
@@ -250,8 +252,8 @@ fn createCommandBuffers(
const viewport = vk.Viewport{
.x = 0,
.y = 0,
.width = @intToFloat(f32, extent.width),
.height = @intToFloat(f32, extent.height),
.width = @floatFromInt(extent.width),
.height = @floatFromInt(extent.height),
.min_depth = 0,
.max_depth = 1,
};
@@ -261,14 +263,11 @@ fn createCommandBuffers(
.extent = extent,
};
for (cmdbufs) |cmdbuf, i| {
try gc.vkd.beginCommandBuffer(cmdbuf, &.{
.flags = .{},
.p_inheritance_info = null,
});
for (cmdbufs, framebuffers) |cmdbuf, framebuffer| {
try gc.dev.beginCommandBuffer(cmdbuf, &.{});
gc.vkd.cmdSetViewport(cmdbuf, 0, 1, @ptrCast([*]const vk.Viewport, &viewport));
gc.vkd.cmdSetScissor(cmdbuf, 0, 1, @ptrCast([*]const vk.Rect2D, &scissor));
gc.dev.cmdSetViewport(cmdbuf, 0, 1, @ptrCast(&viewport));
gc.dev.cmdSetScissor(cmdbuf, 0, 1, @ptrCast(&scissor));
// This needs to be a separate definition - see https://github.com/ziglang/zig/issues/7627.
const render_area = vk.Rect2D{
@@ -276,28 +275,28 @@ fn createCommandBuffers(
.extent = extent,
};
gc.vkd.cmdBeginRenderPass(cmdbuf, &.{
gc.dev.cmdBeginRenderPass(cmdbuf, &.{
.render_pass = render_pass,
.framebuffer = framebuffers[i],
.framebuffer = framebuffer,
.render_area = render_area,
.clear_value_count = 1,
.p_clear_values = @ptrCast([*]const vk.ClearValue, &clear),
.p_clear_values = @ptrCast(&clear),
}, .@"inline");
gc.vkd.cmdBindPipeline(cmdbuf, .graphics, pipeline);
gc.dev.cmdBindPipeline(cmdbuf, .graphics, pipeline);
const offset = [_]vk.DeviceSize{0};
gc.vkd.cmdBindVertexBuffers(cmdbuf, 0, 1, @ptrCast([*]const vk.Buffer, &buffer), &offset);
gc.vkd.cmdDraw(cmdbuf, vertices.len, 1, 0, 0);
gc.dev.cmdBindVertexBuffers(cmdbuf, 0, 1, @ptrCast(&buffer), &offset);
gc.dev.cmdDraw(cmdbuf, vertices.len, 1, 0, 0);
gc.vkd.cmdEndRenderPass(cmdbuf);
try gc.vkd.endCommandBuffer(cmdbuf);
gc.dev.cmdEndRenderPass(cmdbuf);
try gc.dev.endCommandBuffer(cmdbuf);
}
return cmdbufs;
}
fn destroyCommandBuffers(gc: *const GraphicsContext, pool: vk.CommandPool, allocator: Allocator, cmdbufs: []vk.CommandBuffer) void {
gc.vkd.freeCommandBuffers(gc.dev, pool, @truncate(u32, cmdbufs.len), cmdbufs.ptr);
gc.dev.freeCommandBuffers(pool, @truncate(cmdbufs.len), cmdbufs.ptr);
allocator.free(cmdbufs);
}
@@ -306,14 +305,13 @@ fn createFramebuffers(gc: *const GraphicsContext, allocator: Allocator, render_p
errdefer allocator.free(framebuffers);
var i: usize = 0;
errdefer for (framebuffers[0..i]) |fb| gc.vkd.destroyFramebuffer(gc.dev, fb, null);
errdefer for (framebuffers[0..i]) |fb| gc.dev.destroyFramebuffer(fb, null);
for (framebuffers) |*fb| {
fb.* = try gc.vkd.createFramebuffer(gc.dev, &.{
.flags = .{},
fb.* = try gc.dev.createFramebuffer(&.{
.render_pass = render_pass,
.attachment_count = 1,
.p_attachments = @ptrCast([*]const vk.ImageView, &swapchain.swap_images[i].view),
.p_attachments = @ptrCast(&swapchain.swap_images[i].view),
.width = swapchain.extent.width,
.height = swapchain.extent.height,
.layers = 1,
@@ -325,20 +323,19 @@ fn createFramebuffers(gc: *const GraphicsContext, allocator: Allocator, render_p
}
fn destroyFramebuffers(gc: *const GraphicsContext, allocator: Allocator, framebuffers: []const vk.Framebuffer) void {
for (framebuffers) |fb| gc.vkd.destroyFramebuffer(gc.dev, fb, null);
for (framebuffers) |fb| gc.dev.destroyFramebuffer(fb, null);
allocator.free(framebuffers);
}
fn createRenderPass(gc: *const GraphicsContext, swapchain: Swapchain) !vk.RenderPass {
const color_attachment = vk.AttachmentDescription{
.flags = .{},
.format = swapchain.surface_format.format,
.samples = .{ .@"1_bit" = true },
.load_op = .clear,
.store_op = .store,
.stencil_load_op = .dont_care,
.stencil_store_op = .dont_care,
.initial_layout = .@"undefined",
.initial_layout = .undefined,
.final_layout = .present_src_khr,
};
@@ -348,26 +345,16 @@ fn createRenderPass(gc: *const GraphicsContext, swapchain: Swapchain) !vk.Render
};
const subpass = vk.SubpassDescription{
.flags = .{},
.pipeline_bind_point = .graphics,
.input_attachment_count = 0,
.p_input_attachments = undefined,
.color_attachment_count = 1,
.p_color_attachments = @ptrCast([*]const vk.AttachmentReference, &color_attachment_ref),
.p_resolve_attachments = null,
.p_depth_stencil_attachment = null,
.preserve_attachment_count = 0,
.p_preserve_attachments = undefined,
.p_color_attachments = @ptrCast(&color_attachment_ref),
};
return try gc.vkd.createRenderPass(gc.dev, &.{
.flags = .{},
return try gc.dev.createRenderPass(&.{
.attachment_count = 1,
.p_attachments = @ptrCast([*]const vk.AttachmentDescription, &color_attachment),
.p_attachments = @ptrCast(&color_attachment),
.subpass_count = 1,
.p_subpasses = @ptrCast([*]const vk.SubpassDescription, &subpass),
.dependency_count = 0,
.p_dependencies = undefined,
.p_subpasses = @ptrCast(&subpass),
}, null);
}
@@ -376,53 +363,44 @@ fn createPipeline(
layout: vk.PipelineLayout,
render_pass: vk.RenderPass,
) !vk.Pipeline {
const vert = try gc.vkd.createShaderModule(gc.dev, &.{
.flags = .{},
.code_size = resources.triangle_vert.len,
.p_code = @ptrCast([*]const u32, &resources.triangle_vert),
const vert = try gc.dev.createShaderModule(&.{
.code_size = vert_spv.len,
.p_code = @ptrCast(&vert_spv),
}, null);
defer gc.vkd.destroyShaderModule(gc.dev, vert, null);
defer gc.dev.destroyShaderModule(vert, null);
const frag = try gc.vkd.createShaderModule(gc.dev, &.{
.flags = .{},
.code_size = resources.triangle_frag.len,
.p_code = @ptrCast([*]const u32, &resources.triangle_frag),
const frag = try gc.dev.createShaderModule(&.{
.code_size = frag_spv.len,
.p_code = @ptrCast(&frag_spv),
}, null);
defer gc.vkd.destroyShaderModule(gc.dev, frag, null);
defer gc.dev.destroyShaderModule(frag, null);
const pssci = [_]vk.PipelineShaderStageCreateInfo{
.{
.flags = .{},
.stage = .{ .vertex_bit = true },
.module = vert,
.p_name = "main",
.p_specialization_info = null,
},
.{
.flags = .{},
.stage = .{ .fragment_bit = true },
.module = frag,
.p_name = "main",
.p_specialization_info = null,
},
};
const pvisci = vk.PipelineVertexInputStateCreateInfo{
.flags = .{},
.vertex_binding_description_count = 1,
.p_vertex_binding_descriptions = @ptrCast([*]const vk.VertexInputBindingDescription, &Vertex.binding_description),
.p_vertex_binding_descriptions = @ptrCast(&Vertex.binding_description),
.vertex_attribute_description_count = Vertex.attribute_description.len,
.p_vertex_attribute_descriptions = &Vertex.attribute_description,
};
const piasci = vk.PipelineInputAssemblyStateCreateInfo{
.flags = .{},
.topology = .triangle_list,
.primitive_restart_enable = vk.FALSE,
};
const pvsci = vk.PipelineViewportStateCreateInfo{
.flags = .{},
.viewport_count = 1,
.p_viewports = undefined, // set in createCommandBuffers with cmdSetViewport
.scissor_count = 1,
@@ -430,7 +408,6 @@ fn createPipeline(
};
const prsci = vk.PipelineRasterizationStateCreateInfo{
.flags = .{},
.depth_clamp_enable = vk.FALSE,
.rasterizer_discard_enable = vk.FALSE,
.polygon_mode = .fill,
@@ -444,11 +421,9 @@ fn createPipeline(
};
const pmsci = vk.PipelineMultisampleStateCreateInfo{
.flags = .{},
.rasterization_samples = .{ .@"1_bit" = true },
.sample_shading_enable = vk.FALSE,
.min_sample_shading = 1,
.p_sample_mask = null,
.alpha_to_coverage_enable = vk.FALSE,
.alpha_to_one_enable = vk.FALSE,
};
@@ -465,11 +440,10 @@ fn createPipeline(
};
const pcbsci = vk.PipelineColorBlendStateCreateInfo{
.flags = .{},
.logic_op_enable = vk.FALSE,
.logic_op = .copy,
.attachment_count = 1,
.p_attachments = @ptrCast([*]const vk.PipelineColorBlendAttachmentState, &pcbas),
.p_attachments = @ptrCast(&pcbas),
.blend_constants = [_]f32{ 0, 0, 0, 0 },
};
@@ -501,13 +475,12 @@ fn createPipeline(
};
var pipeline: vk.Pipeline = undefined;
_ = try gc.vkd.createGraphicsPipelines(
gc.dev,
_ = try gc.dev.createGraphicsPipelines(
.null_handle,
1,
@ptrCast([*]const vk.GraphicsPipelineCreateInfo, &gpci),
@ptrCast(&gpci),
null,
@ptrCast([*]vk.Pipeline, &pipeline),
@ptrCast(&pipeline),
);
return pipeline;
}

File diff suppressed because it is too large Load Diff

View File

@@ -1,111 +0,0 @@
const std = @import("std");
const path = std.fs.path;
const Builder = std.build.Builder;
const Step = std.build.Step;
/// Stage the shader should be built for. This is passed to the -fshader-stage
/// argument when invoking glslc.
pub const ShaderStage = enum {
vertex,
fragment,
tesscontrol,
tesseval,
geometry,
compute,
};
/// Utility functionality to help with compiling shaders from build.zig.
/// Invokes glslc (or another shader compiler passed to `init`) for each shader
/// added via `addShader`.
pub const ShaderCompileStep = struct {
const AddFileParams = struct {
entry_point: ?[]const u8 = null,
stage: ?ShaderStage = null,
output_filename: ?[]const u8 = null,
};
/// Structure representing a shader to be compiled.
const Shader = struct {
/// The path to the shader, relative to the current build root.
source_path: []const u8,
/// The full output path where the compiled shader binary is placed.
full_out_path: []const u8,
/// The entry point to use when compiling the shader.
entry_point: ?[]const u8,
/// The stage to use when building. If not null, this is passed to
/// the -fshader-stage argument.
stage: ?ShaderStage,
};
step: Step,
builder: *Builder,
/// The command and optional arguments used to invoke the shader compiler.
glslc_cmd: []const []const u8,
/// The directory within `zig-cache/` that the compiled shaders are placed in.
output_dir: []const u8,
/// List of shaders that are to be compiled.
shaders: std.ArrayList(Shader),
/// Create a ShaderCompilerStep for `builder`. When this step is invoked by the build
/// system, `<glcl_cmd...> <shader_source> -o <dst_addr>` is invoked for each shader.
pub fn init(builder: *Builder, glslc_cmd: []const []const u8, output_dir: []const u8) *ShaderCompileStep {
const self = builder.allocator.create(ShaderCompileStep) catch unreachable;
self.* = .{
.step = Step.init(.custom, "shader-compile", builder.allocator, make),
.builder = builder,
.output_dir = output_dir,
.glslc_cmd = builder.dupeStrings(glslc_cmd),
.shaders = std.ArrayList(Shader).init(builder.allocator),
};
return self;
}
/// Add a shader to be compiled. `src` is shader source path, relative to the project root.
/// Returns the full path where the compiled binary will be stored upon successful compilation.
/// This path can then be used to include the binary into an executable, for example by passing it
/// to @embedFile via an additional generated file. `entry_point` is the entry point to pass to the compiler.
/// `stage` is an optional shader stage to pass to the compiler with the flag `-fshader-stage` when building the shader.
pub fn add(self: *ShaderCompileStep, src: []const u8, params: AddFileParams) []const u8 {
const full_out_path = path.join(self.builder.allocator, &[_][]const u8{
self.builder.build_root,
self.builder.cache_root,
if (params.output_filename) |out| out else std.fmt.allocPrint(self.builder.allocator, "{s}.spv", .{src}) catch unreachable,
}) catch unreachable;
self.shaders.append(.{ .source_path = src, .full_out_path = full_out_path, .entry_point = params.entry_point, .stage = params.stage }) catch unreachable;
return full_out_path;
}
/// Internal build function.
fn make(step: *Step) !void {
const self = @fieldParentPtr(ShaderCompileStep, "step", step);
const cwd = std.fs.cwd();
var cmd = std.ArrayList([]const u8).init(self.builder.allocator);
try cmd.appendSlice(self.glslc_cmd);
const base_cmd_len = cmd.items.len;
for (self.shaders.items) |shader| {
cmd.items.len = base_cmd_len;
if (shader.entry_point) |entry_point| {
try cmd.append(try std.fmt.allocPrint(self.builder.allocator, "-fentry-point={s}", .{entry_point}));
}
if (shader.stage) |stage| {
try cmd.append(try std.fmt.allocPrint(self.builder.allocator, "-fshader-stage={s}", .{@tagName(stage)}));
}
const dir = path.dirname(shader.full_out_path).?;
try cwd.makePath(dir);
try cmd.appendSlice(&.{shader.source_path, "-o", shader.full_out_path});
try self.builder.spawnChild(cmd.items);
}
}
};

View File

@@ -1,9 +0,0 @@
pub const generateVk = @import("vulkan/generator.zig").generate;
pub const VkGenerateStep = @import("vulkan/build_integration.zig").GenerateStep;
pub const ShaderStage = @import("build_integration.zig").ShaderStage;
pub const ShaderCompileStep = @import("build_integration.zig").ShaderCompileStep;
test "main" {
_ = @import("xml.zig");
_ = @import("vulkan/c_parse.zig");
}

View File

@@ -1,80 +0,0 @@
const std = @import("std");
const generate = @import("vulkan/generator.zig").generate;
const usage = "Usage: {s} [-h|--help] <spec xml path> <output zig source>\n";
pub fn main() !void {
const stderr = std.io.getStdErr();
var arena = std.heap.ArenaAllocator.init(std.heap.page_allocator);
defer arena.deinit();
const allocator = arena.allocator();
var args = try std.process.argsWithAllocator(allocator);
const prog_name = args.next() orelse return error.ExecutableNameMissing;
var maybe_xml_path: ?[]const u8 = null;
var maybe_out_path: ?[]const u8 = null;
while (args.next()) |arg| {
if (std.mem.eql(u8, arg, "--help") or std.mem.eql(u8, arg, "-h")) {
@setEvalBranchQuota(2000);
try stderr.writer().print(
\\Utility to generate a Zig binding from the Vulkan XML API registry.
\\
\\The most recent Vulkan XML API registry can be obtained from
\\https://github.com/KhronosGroup/Vulkan-Docs/blob/master/xml/vk.xml,
\\and the most recent LunarG Vulkan SDK version can be found at
\\$VULKAN_SDK/x86_64/share/vulkan/registry/vk.xml.
\\
\\
++ usage,
.{prog_name},
);
return;
} else if (maybe_xml_path == null) {
maybe_xml_path = arg;
} else if (maybe_out_path == null) {
maybe_out_path = arg;
} else {
try stderr.writer().print("Error: Superficial argument '{s}'\n", .{arg});
}
}
const xml_path = maybe_xml_path orelse {
try stderr.writer().print("Error: Missing required argument <spec xml path>\n" ++ usage, .{prog_name});
return;
};
const out_path = maybe_out_path orelse {
try stderr.writer().print("Error: Missing required argument <output zig source>\n" ++ usage, .{prog_name});
return;
};
const cwd = std.fs.cwd();
const xml_src = cwd.readFileAlloc(allocator, xml_path, std.math.maxInt(usize)) catch |err| {
try stderr.writer().print("Error: Failed to open input file '{s}' ({s})\n", .{ xml_path, @errorName(err) });
return;
};
var out_buffer = std.ArrayList(u8).init(allocator);
try generate(allocator, xml_src, out_buffer.writer());
try out_buffer.append(0);
const src = out_buffer.items[0 .. out_buffer.items.len - 1 :0];
const tree = try std.zig.parse(allocator, src);
const formatted = try tree.render(allocator);
defer allocator.free(formatted);
if (std.fs.path.dirname(out_path)) |dir| {
cwd.makePath(dir) catch |err| {
try stderr.writer().print("Error: Failed to create output directory '{s}' ({s})\n", .{ dir, @errorName(err) });
return;
};
}
cwd.writeFile(out_path, formatted) catch |err| {
try stderr.writer().print("Error: Failed to write to output file '{s}' ({s})\n", .{ out_path, @errorName(err) });
return;
};
}

View File

@@ -1,91 +0,0 @@
const std = @import("std");
const generate = @import("generator.zig").generate;
const path = std.fs.path;
const Builder = std.build.Builder;
const Step = std.build.Step;
/// build.zig integration for Vulkan binding generation. This step can be used to generate
/// Vulkan bindings at compiletime from vk.xml, by providing the path to vk.xml and the output
/// path relative to zig-cache. The final package can then be obtained by `package()`, the result
/// of which can be added to the project using `std.build.Builder.addPackage`.
pub const GenerateStep = struct {
step: Step,
builder: *Builder,
/// The path to vk.xml
spec_path: []const u8,
/// The package representing the generated bindings. The generated bindings will be placed
/// in `package.path`. When using this step, this member should be passed to
/// `std.build.Builder.addPackage`, which causes the bindings to become available under the
/// name `vulkan`.
package: std.build.Pkg,
output_file: std.build.GeneratedFile,
/// Initialize a Vulkan generation step, for `builder`. `spec_path` is the path to
/// vk.xml, relative to the project root. The generated bindings will be placed at
/// `out_path`, which is relative to the zig-cache directory.
pub fn init(builder: *Builder, spec_path: []const u8, out_path: []const u8) *GenerateStep {
const self = builder.allocator.create(GenerateStep) catch unreachable;
const full_out_path = path.join(builder.allocator, &[_][]const u8{
builder.build_root,
builder.cache_root,
out_path,
}) catch unreachable;
self.* = .{
.step = Step.init(.custom, "vulkan-generate", builder.allocator, make),
.builder = builder,
.spec_path = spec_path,
.package = .{
.name = "vulkan",
.source = .{ .generated = &self.output_file },
.dependencies = null,
},
.output_file = .{
.step = &self.step,
.path = full_out_path,
},
};
return self;
}
/// Initialize a Vulkan generation step for `builder`, by extracting vk.xml from the LunarG installation
/// root. Typically, the location of the LunarG SDK root can be retrieved by querying for the VULKAN_SDK
/// environment variable, set by activating the environment setup script located in the SDK root.
/// `builder` and `out_path` are used in the same manner as `init`.
pub fn initFromSdk(builder: *Builder, sdk_path: []const u8, out_path: []const u8) *GenerateStep {
const spec_path = std.fs.path.join(
builder.allocator,
&[_][]const u8{ sdk_path, "share/vulkan/registry/vk.xml" },
) catch unreachable;
return init(builder, spec_path, out_path);
}
/// Internal build function. This reads `vk.xml`, and passes it to `generate`, which then generates
/// the final bindings. The resulting generated bindings are not formatted, which is why an ArrayList
/// writer is passed instead of a file writer. This is then formatted into standard formatting
/// by parsing it and rendering with `std.zig.parse` and `std.zig.render` respectively.
fn make(step: *Step) !void {
const self = @fieldParentPtr(GenerateStep, "step", step);
const cwd = std.fs.cwd();
const spec = try cwd.readFileAlloc(self.builder.allocator, self.spec_path, std.math.maxInt(usize));
var out_buffer = std.ArrayList(u8).init(self.builder.allocator);
try generate(self.builder.allocator, spec, out_buffer.writer());
try out_buffer.append(0);
const src = out_buffer.items[0 .. out_buffer.items.len - 1 :0];
const tree = try std.zig.parse(self.builder.allocator, src);
std.debug.assert(tree.errors.len == 0); // If this triggers, vulkan-zig produced invalid code.
var formatted = try tree.render(self.builder.allocator);
const dir = path.dirname(self.output_file.path.?).?;
try cwd.makePath(dir);
try cwd.writeFile(self.output_file.path.?, formatted);
}
};

View File

@@ -139,10 +139,9 @@ pub const IdRenderer = struct {
self.text_cache.deinit();
}
fn renderSnake(self: *IdRenderer, comptime screaming: bool, id: []const u8, tag: ?[]const u8) !void {
fn renderSnake(self: *IdRenderer, screaming: bool, id: []const u8, tag: ?[]const u8) !void {
var it = SegmentIterator.init(id);
var first = true;
const transform = if (screaming) std.ascii.toUpper else std.ascii.toLower;
while (it.next()) |segment| {
if (first) {
@@ -152,7 +151,7 @@ pub const IdRenderer = struct {
}
for (segment) |c| {
try self.text_cache.append(transform(c));
try self.text_cache.append(if (screaming) std.ascii.toUpper(c) else std.ascii.toLower(c));
}
}
@@ -160,7 +159,7 @@ pub const IdRenderer = struct {
try self.text_cache.append('_');
for (name) |c| {
try self.text_cache.append(transform(c));
try self.text_cache.append(if (screaming) std.ascii.toUpper(c) else std.ascii.toLower(c));
}
}
}

162
src/main.zig Normal file
View File

@@ -0,0 +1,162 @@
const std = @import("std");
const generator = @import("vulkan/generator.zig");
fn invalidUsage(prog_name: []const u8, comptime fmt: []const u8, args: anytype) noreturn {
std.log.err(fmt, args);
std.log.err("see {s} --help for usage", .{prog_name});
std.process.exit(1);
}
fn reportParseErrors(tree: std.zig.Ast) !void {
const stderr = std.io.getStdErr().writer();
for (tree.errors) |err| {
const loc = tree.tokenLocation(0, err.token);
try stderr.print("(vulkan-zig error):{}:{}: error: ", .{ loc.line + 1, loc.column + 1 });
try tree.renderError(err, stderr);
try stderr.print("\n{s}\n", .{tree.source[loc.line_start..loc.line_end]});
for (0..loc.column) |_| {
try stderr.writeAll(" ");
}
try stderr.writeAll("^\n");
}
}
pub fn main() void {
var arena = std.heap.ArenaAllocator.init(std.heap.page_allocator);
defer arena.deinit();
const allocator = arena.allocator();
var args = std.process.argsWithAllocator(allocator) catch |err| switch (err) {
error.OutOfMemory => @panic("OOM"),
};
const prog_name = args.next() orelse "vulkan-zig-generator";
var maybe_xml_path: ?[]const u8 = null;
var maybe_out_path: ?[]const u8 = null;
var debug: bool = false;
var api = generator.Api.vulkan;
while (args.next()) |arg| {
if (std.mem.eql(u8, arg, "--help") or std.mem.eql(u8, arg, "-h")) {
@setEvalBranchQuota(2000);
std.io.getStdOut().writer().print(
\\Utility to generate a Zig binding from the Vulkan XML API registry.
\\
\\The most recent Vulkan XML API registry can be obtained from
\\https://github.com/KhronosGroup/Vulkan-Docs/blob/master/xml/vk.xml,
\\and the most recent LunarG Vulkan SDK version can be found at
\\$VULKAN_SDK/x86_64/share/vulkan/registry/vk.xml.
\\
\\Usage: {s} [options] <spec xml path> <output zig source>
\\Options:
\\-h --help show this message and exit.
\\-a --api <api> Generate API for 'vulkan' or 'vulkansc'. Defaults to 'vulkan'.
\\--debug Write out unformatted source if does not parse correctly.
\\
,
.{prog_name},
) catch |err| {
std.log.err("failed to write to stdout: {s}", .{@errorName(err)});
std.process.exit(1);
};
return;
} else if (std.mem.eql(u8, arg, "-a") or std.mem.eql(u8, arg, "--api")) {
const api_str = args.next() orelse {
invalidUsage(prog_name, "{s} expects argument <api>", .{arg});
};
api = std.meta.stringToEnum(generator.Api, api_str) orelse {
invalidUsage(prog_name, "invalid api '{s}'", .{api_str});
};
} else if (maybe_xml_path == null) {
maybe_xml_path = arg;
} else if (maybe_out_path == null) {
maybe_out_path = arg;
} else if (std.mem.eql(u8, arg, "--debug")) {
debug = true;
} else {
invalidUsage(prog_name, "superficial argument '{s}'", .{arg});
}
}
const xml_path = maybe_xml_path orelse {
invalidUsage(prog_name, "missing required argument <spec xml path>", .{});
};
const out_path = maybe_out_path orelse {
invalidUsage(prog_name, "missing required argument <output zig source>", .{});
};
const cwd = std.fs.cwd();
const xml_src = cwd.readFileAlloc(allocator, xml_path, std.math.maxInt(usize)) catch |err| {
std.log.err("failed to open input file '{s}' ({s})", .{ xml_path, @errorName(err) });
std.process.exit(1);
};
var out_buffer = std.ArrayList(u8).init(allocator);
generator.generate(allocator, api, xml_src, out_buffer.writer()) catch |err| switch (err) {
error.InvalidXml => {
std.log.err("invalid vulkan registry - invalid xml", .{});
std.log.err("please check that the correct vk.xml file is passed", .{});
std.process.exit(1);
},
error.InvalidRegistry => {
std.log.err("invalid vulkan registry - registry is valid xml but contents are invalid", .{});
std.log.err("please check that the correct vk.xml file is passed", .{});
std.process.exit(1);
},
error.UnhandledBitfieldStruct => {
std.log.err("unhandled struct with bit fields detected in vk.xml", .{});
std.log.err("this is a bug in vulkan-zig", .{});
std.log.err("please make a bug report at https://github.com/Snektron/vulkan-zig/issues/", .{});
std.process.exit(1);
},
error.OutOfMemory => @panic("oom"),
};
out_buffer.append(0) catch @panic("oom");
const src = out_buffer.items[0 .. out_buffer.items.len - 1 :0];
const tree = std.zig.Ast.parse(allocator, src, .zig) catch |err| switch (err) {
error.OutOfMemory => @panic("oom"),
};
const formatted = if (tree.errors.len > 0) blk: {
std.log.err("generated invalid zig code", .{});
std.log.err("this is a bug in vulkan-zig", .{});
std.log.err("please make a bug report at https://github.com/Snektron/vulkan-zig/issues/", .{});
std.log.err("or run with --debug to write out unformatted source", .{});
reportParseErrors(tree) catch |err| {
std.log.err("failed to dump ast errors: {s}", .{@errorName(err)});
std.process.exit(1);
};
if (debug) {
break :blk src;
}
std.process.exit(1);
} else tree.render(allocator) catch |err| switch (err) {
error.OutOfMemory => @panic("oom"),
};
if (std.fs.path.dirname(out_path)) |dir| {
cwd.makePath(dir) catch |err| {
std.log.err("failed to create output directory '{s}' ({s})", .{ dir, @errorName(err) });
std.process.exit(1);
};
}
cwd.writeFile(.{
.sub_path = out_path,
.data = formatted,
}) catch |err| {
std.log.err("failed to write to output file '{s}' ({s})", .{ out_path, @errorName(err) });
std.process.exit(1);
};
}
test "main" {
_ = @import("xml.zig");
_ = @import("vulkan/c_parse.zig");
}

View File

@@ -263,6 +263,7 @@ pub fn parseMember(allocator: Allocator, xctok: *XmlCTokenizer, ptrs_optional: b
.field_type = decl.decl_type,
.bits = null,
.is_buffer_len = false,
.is_optional = false,
};
if (try xctok.peek()) |tok| {
@@ -285,10 +286,29 @@ pub fn parseMember(allocator: Allocator, xctok: *XmlCTokenizer, ptrs_optional: b
}
pub fn parseParamOrProto(allocator: Allocator, xctok: *XmlCTokenizer, ptrs_optional: bool) !registry.Declaration {
const decl = try parseDeclaration(allocator, xctok, ptrs_optional);
var decl = try parseDeclaration(allocator, xctok, ptrs_optional);
if (try xctok.peek()) |_| {
return error.InvalidSyntax;
}
// Decay pointers
switch (decl.decl_type) {
.array => {
const child = try allocator.create(TypeInfo);
child.* = decl.decl_type;
decl.decl_type = .{
.pointer = .{
.is_const = decl.is_const,
.is_optional = false,
.size = .one,
.child = child,
},
};
},
else => {},
}
return registry.Declaration{
.name = decl.name orelse return error.MissingTypeIdentifier,
.decl_type = .{ .typedef = decl.decl_type },
@@ -298,6 +318,7 @@ pub fn parseParamOrProto(allocator: Allocator, xctok: *XmlCTokenizer, ptrs_optio
pub const Declaration = struct {
name: ?[]const u8, // Parameter names may be optional, especially in case of func(void)
decl_type: TypeInfo,
is_const: bool,
};
pub const ParseError = error{
@@ -338,7 +359,11 @@ fn parseDeclaration(allocator: Allocator, xctok: *XmlCTokenizer, ptrs_optional:
// Parse name / fn ptr
if (try parseFnPtrSuffix(allocator, xctok, type_info, ptrs_optional)) |decl| {
return decl;
return Declaration{
.name = decl.name,
.decl_type = decl.decl_type,
.is_const = inner_is_const,
};
}
const name = blk: {
@@ -361,6 +386,8 @@ fn parseDeclaration(allocator: Allocator, xctok: *XmlCTokenizer, ptrs_optional:
inner_type.* = .{
.array = .{
.size = array_size,
.valid_size = .all, // Refined later
.is_optional = true,
.child = child,
},
};
@@ -373,6 +400,7 @@ fn parseDeclaration(allocator: Allocator, xctok: *XmlCTokenizer, ptrs_optional:
return Declaration{
.name = name,
.decl_type = type_info,
.is_const = inner_is_const,
};
}
@@ -402,6 +430,7 @@ fn parseFnPtrSuffix(allocator: Allocator, xctok: *XmlCTokenizer, return_type: Ty
.error_codes = &[_][]const u8{},
},
},
.is_const = false,
};
const first_param = try parseDeclaration(allocator, xctok, ptrs_optional);
@@ -422,6 +451,7 @@ fn parseFnPtrSuffix(allocator: Allocator, xctok: *XmlCTokenizer, return_type: Ty
.name = first_param.name.?,
.param_type = first_param.decl_type,
.is_buffer_len = false,
.is_optional = false,
});
while (true) {
@@ -436,11 +466,12 @@ fn parseFnPtrSuffix(allocator: Allocator, xctok: *XmlCTokenizer, return_type: Ty
.name = decl.name orelse return error.MissingTypeIdentifier,
.param_type = decl.decl_type,
.is_buffer_len = false,
.is_optional = false,
});
}
_ = try xctok.nextNoEof();
command_ptr.decl_type.command_ptr.params = params.toOwnedSlice();
command_ptr.decl_type.command_ptr.params = try params.toOwnedSlice();
return command_ptr;
}
@@ -522,7 +553,7 @@ pub fn parseVersion(xctok: *XmlCTokenizer) ![4][]const u8 {
_ = try xctok.expect(.lparen);
var version: [4][]const u8 = undefined;
for (version) |*part, i| {
for (&version, 0..) |*part, i| {
if (i != 0) {
_ = try xctok.expect(.comma);
}

View File

@@ -72,7 +72,7 @@ const EnumFieldMerger = struct {
// Existing base_enum.fields was allocated by `self.arena`, so
// it gets cleaned up whenever that is deinited.
base_enum.fields = self.arena.shrink(new_fields, i);
base_enum.fields = new_fields[0..i];
}
fn merge(self: *EnumFieldMerger) !void {
@@ -99,11 +99,11 @@ pub const Generator = struct {
registry: reg.Registry,
id_renderer: IdRenderer,
fn init(allocator: Allocator, spec: *xml.Element) !Generator {
const result = try parseXml(allocator, spec);
fn init(allocator: Allocator, spec: *xml.Element, api: reg.Api) !Generator {
const result = try parseXml(allocator, spec, api);
const tags = try allocator.alloc([]const u8, result.registry.tags.len);
for (tags) |*tag, i| tag.* = result.registry.tags[i].name;
for (tags, result.registry.tags) |*tag, registry_tag| tag.* = registry_tag.name;
return Generator{
.arena = result.arena,
@@ -170,18 +170,58 @@ pub const Generator = struct {
}
};
/// The vulkan registry contains the specification for multiple APIs: Vulkan and VulkanSC. This enum
/// describes applicable APIs.
pub const Api = reg.Api;
/// Main function for generating the Vulkan bindings. vk.xml is to be provided via `spec_xml`,
/// and the resulting binding is written to `writer`. `allocator` will be used to allocate temporary
/// internal datastructures - mostly via an ArenaAllocator, but sometimes a hashmap uses this allocator
/// directly.
pub fn generate(allocator: Allocator, spec_xml: []const u8, writer: anytype) !void {
const spec = try xml.parse(allocator, spec_xml);
/// directly. `api` is the API to generate the bindings for, usually `.vulkan`.
pub fn generate(allocator: Allocator, api: Api, spec_xml: []const u8, writer: anytype) !void {
const spec = xml.parse(allocator, spec_xml) catch |err| switch (err) {
error.InvalidDocument,
error.UnexpectedEof,
error.UnexpectedCharacter,
error.IllegalCharacter,
error.InvalidEntity,
error.InvalidName,
error.InvalidStandaloneValue,
error.NonMatchingClosingTag,
error.UnclosedComment,
error.UnclosedValue,
=> return error.InvalidXml,
error.OutOfMemory => return error.OutOfMemory,
};
defer spec.deinit();
var gen = try Generator.init(allocator, spec.root);
var gen = Generator.init(allocator, spec.root, api) catch |err| switch (err) {
error.InvalidXml,
error.InvalidCharacter,
error.Overflow,
error.InvalidFeatureLevel,
error.InvalidSyntax,
error.InvalidTag,
error.MissingTypeIdentifier,
error.UnexpectedCharacter,
error.UnexpectedEof,
error.UnexpectedToken,
error.InvalidRegistry,
=> return error.InvalidRegistry,
error.OutOfMemory => return error.OutOfMemory,
};
defer gen.deinit();
try gen.mergeEnumFields();
try gen.fixupBitFlags();
try gen.render(writer);
gen.render(writer) catch |err| switch (err) {
error.InvalidApiConstant,
error.InvalidConstantExpr,
error.InvalidRegistry,
error.UnexpectedCharacter,
error.InvalidCharacter,
error.Overflow,
=> return error.InvalidRegistry,
else => |others| return others,
};
}

View File

@@ -17,18 +17,18 @@ pub const ParseResult = struct {
}
};
pub fn parseXml(backing_allocator: Allocator, root: *xml.Element) !ParseResult {
pub fn parseXml(backing_allocator: Allocator, root: *xml.Element, api: registry.Api) !ParseResult {
var arena = ArenaAllocator.init(backing_allocator);
errdefer arena.deinit();
const allocator = arena.allocator();
var reg = registry.Registry{
.decls = try parseDeclarations(allocator, root),
.api_constants = try parseApiConstants(allocator, root),
const reg = registry.Registry{
.decls = try parseDeclarations(allocator, root, api),
.api_constants = try parseApiConstants(allocator, root, api),
.tags = try parseTags(allocator, root),
.features = try parseFeatures(allocator, root),
.extensions = try parseExtensions(allocator, root),
.features = try parseFeatures(allocator, root, api),
.extensions = try parseExtensions(allocator, root, api),
};
return ParseResult{
@@ -37,25 +37,28 @@ pub fn parseXml(backing_allocator: Allocator, root: *xml.Element) !ParseResult {
};
}
fn parseDeclarations(allocator: Allocator, root: *xml.Element) ![]registry.Declaration {
var types_elem = root.findChildByTag("types") orelse return error.InvalidRegistry;
var commands_elem = root.findChildByTag("commands") orelse return error.InvalidRegistry;
fn parseDeclarations(allocator: Allocator, root: *xml.Element, api: registry.Api) ![]registry.Declaration {
const types_elem = root.findChildByTag("types") orelse return error.InvalidRegistry;
const commands_elem = root.findChildByTag("commands") orelse return error.InvalidRegistry;
const decl_upper_bound = types_elem.children.len + commands_elem.children.len;
const decls = try allocator.alloc(registry.Declaration, decl_upper_bound);
var count: usize = 0;
count += try parseTypes(allocator, decls, types_elem);
count += try parseEnums(allocator, decls[count..], root);
count += try parseCommands(allocator, decls[count..], commands_elem);
return allocator.shrink(decls, count);
count += try parseTypes(allocator, decls, types_elem, api);
count += try parseEnums(allocator, decls[count..], root, api);
count += try parseCommands(allocator, decls[count..], commands_elem, api);
return decls[0..count];
}
fn parseTypes(allocator: Allocator, out: []registry.Declaration, types_elem: *xml.Element) !usize {
fn parseTypes(allocator: Allocator, out: []registry.Declaration, types_elem: *xml.Element, api: registry.Api) !usize {
var i: usize = 0;
var it = types_elem.findChildrenByTag("type");
while (it.next()) |ty| {
out[i] = blk: {
if (!requiredByApi(ty, api))
continue;
const category = ty.getAttribute("category") orelse {
break :blk try parseForeigntype(ty);
};
@@ -67,9 +70,9 @@ fn parseTypes(allocator: Allocator, out: []registry.Declaration, types_elem: *xm
} else if (mem.eql(u8, category, "basetype")) {
break :blk try parseBaseType(allocator, ty);
} else if (mem.eql(u8, category, "struct")) {
break :blk try parseContainer(allocator, ty, false);
break :blk try parseContainer(allocator, ty, false, api);
} else if (mem.eql(u8, category, "union")) {
break :blk try parseContainer(allocator, ty, true);
break :blk try parseContainer(allocator, ty, true, api);
} else if (mem.eql(u8, category, "funcpointer")) {
break :blk try parseFuncPointer(allocator, ty);
} else if (mem.eql(u8, category, "enum")) {
@@ -168,12 +171,12 @@ fn parseBaseType(allocator: Allocator, ty: *xml.Element) !registry.Declaration {
// macros, which is why this part is not built into the xml/c parser.
return registry.Declaration{
.name = name,
.decl_type = .{ .external = {} },
.decl_type = .{ .foreign = .{ .depends = &.{} } },
};
}
}
fn parseContainer(allocator: Allocator, ty: *xml.Element, is_union: bool) !registry.Declaration {
fn parseContainer(allocator: Allocator, ty: *xml.Element, is_union: bool, api: registry.Api) !registry.Declaration {
const name = ty.getAttribute("name") orelse return error.InvalidRegistry;
if (ty.getAttribute("alias")) |alias| {
@@ -191,6 +194,9 @@ fn parseContainer(allocator: Allocator, ty: *xml.Element, is_union: bool) !regis
var it = ty.findChildrenByTag("member");
var maybe_stype: ?[]const u8 = null;
while (it.next()) |member| {
if (!requiredByApi(member, api))
continue;
var xctok = cparse.XmlCTokenizer.init(member);
members[i] = try cparse.parseMember(allocator, &xctok, false);
if (mem.eql(u8, members[i].name, "sType")) {
@@ -199,16 +205,25 @@ fn parseContainer(allocator: Allocator, ty: *xml.Element, is_union: bool) !regis
}
}
if (member.getAttribute("optional")) |optionals| {
var optional_it = mem.splitScalar(u8, optionals, ',');
if (optional_it.next()) |first_optional| {
members[i].is_optional = mem.eql(u8, first_optional, "true");
} else {
// Optional is empty, probably incorrect.
return error.InvalidRegistry;
}
}
i += 1;
}
members = allocator.shrink(members, i);
members = members[0..i];
var maybe_extends: ?[][]const u8 = null;
if (ty.getAttribute("structextends")) |extends| {
const n_structs = std.mem.count(u8, extends, ",") + 1;
maybe_extends = try allocator.alloc([]const u8, n_structs);
var struct_extends = std.mem.split(u8, extends, ",");
var struct_extends = std.mem.splitScalar(u8, extends, ',');
var j: usize = 0;
while (struct_extends.next()) |struct_extend| {
maybe_extends.?[j] = struct_extend;
@@ -218,8 +233,16 @@ fn parseContainer(allocator: Allocator, ty: *xml.Element, is_union: bool) !regis
it = ty.findChildrenByTag("member");
for (members) |*member| {
const member_elem = it.next().?;
const member_elem = while (it.next()) |elem| {
if (requiredByApi(elem, api)) break elem;
} else unreachable;
try parsePointerMeta(.{ .container = members }, &member.field_type, member_elem);
// pNext isn't always properly marked as optional, so just manually override it,
if (mem.eql(u8, member.name, "pNext")) {
member.field_type.pointer.is_optional = true;
}
}
return registry.Declaration{
@@ -240,7 +263,7 @@ fn parseFuncPointer(allocator: Allocator, ty: *xml.Element) !registry.Declaratio
return try cparse.parseTypedef(allocator, &xctok, true);
}
// For some reason, the DeclarationType cannot be passed to lenToPointerSize, as
// For some reason, the DeclarationType cannot be passed to lenToPointer, as
// that causes the Zig compiler to generate invalid code for the function. Using a
// dedicated enum fixes the issue...
const Fields = union(enum) {
@@ -248,13 +271,14 @@ const Fields = union(enum) {
container: []registry.Container.Field,
};
fn lenToPointerSize(fields: Fields, len: []const u8) registry.Pointer.PointerSize {
// returns .{ size, nullable }
fn lenToPointer(fields: Fields, len: []const u8) std.meta.Tuple(&.{ registry.Pointer.PointerSize, bool }) {
switch (fields) {
.command => |params| {
for (params) |*param| {
if (mem.eql(u8, param.name, len)) {
param.is_buffer_len = true;
return .{ .other_field = param.name };
return .{ .{ .other_field = param.name }, param.is_optional };
}
}
},
@@ -262,50 +286,91 @@ fn lenToPointerSize(fields: Fields, len: []const u8) registry.Pointer.PointerSiz
for (members) |*member| {
if (mem.eql(u8, member.name, len)) {
member.is_buffer_len = true;
return .{ .other_field = member.name };
return .{ .{ .other_field = member.name }, member.is_optional };
}
}
},
}
if (mem.eql(u8, len, "null-terminated")) {
return .zero_terminated;
return .{ .zero_terminated, false };
} else {
return .many;
return .{ .many, false };
}
}
fn parsePointerMeta(fields: Fields, type_info: *registry.TypeInfo, elem: *xml.Element) !void {
var len_attribute_depth: usize = 0;
if (elem.getAttribute("len")) |lens| {
var it = mem.split(u8, lens, ",");
var it = mem.splitScalar(u8, lens, ',');
var current_type_info = type_info;
while (current_type_info.* == .pointer) {
// TODO: Check altlen
const size = if (it.next()) |len_str| lenToPointerSize(fields, len_str) else .one;
current_type_info.pointer.size = size;
current_type_info = current_type_info.pointer.child;
}
while (true) switch (current_type_info.*) {
.pointer => |*ptr| {
if (it.next()) |len_str| {
ptr.size, ptr.is_optional = lenToPointer(fields, len_str);
} else {
ptr.size = .many;
}
current_type_info = ptr.child;
len_attribute_depth += 1;
},
.array => |*arr| {
if (it.next()) |len_str| {
const size, _ = lenToPointer(fields, len_str);
arr.valid_size = switch (size) {
.one => .all,
.many => .many,
.other_field => |field| .{ .other_field = field },
.zero_terminated => .zero_terminated,
};
} else {
arr.valid_size = .all;
}
current_type_info = arr.child;
len_attribute_depth += 1;
},
else => break,
};
if (it.next()) |_| {
// There are more elements in the `len` attribute than there are pointers
// Something probably went wrong
std.log.err("len: {s}", .{lens});
return error.InvalidRegistry;
}
}
if (elem.getAttribute("optional")) |optionals| {
var it = mem.split(u8, optionals, ",");
var current_type_info = type_info;
while (current_type_info.* == .pointer) {
if (it.next()) |current_optional| {
current_type_info.pointer.is_optional = mem.eql(u8, current_optional, "true");
} else {
// There is no information for this pointer, probably incorrect.
return error.InvalidRegistry;
}
var current_depth: usize = 0;
current_type_info = current_type_info.pointer.child;
}
if (elem.getAttribute("optional")) |optionals| {
var it = mem.splitScalar(u8, optionals, ',');
var current_type_info = type_info;
while (true) switch (current_type_info.*) {
inline .pointer, .array => |*info| {
if (it.next()) |optional_str| {
// The pointer may have already been marked as optional due to its `len` attribute.
const is_already_optional = current_depth < len_attribute_depth and info.is_optional;
info.is_optional = is_already_optional or mem.eql(u8, optional_str, "true");
} else {
// There is no information for this pointer, probably incorrect.
// Currently there is one definition where this is the case, VkCudaLaunchInfoNV.
// We work around these by assuming that they are optional, so that in the case
// that they are, we can assign null to them.
// See https://github.com/Snektron/vulkan-zig/issues/109
info.is_optional = true;
}
current_type_info = info.child;
current_depth += 1;
},
else => break,
};
}
}
@@ -323,18 +388,18 @@ fn parseEnumAlias(elem: *xml.Element) !?registry.Declaration {
return null;
}
fn parseEnums(allocator: Allocator, out: []registry.Declaration, root: *xml.Element) !usize {
fn parseEnums(allocator: Allocator, out: []registry.Declaration, root: *xml.Element, api: registry.Api) !usize {
var i: usize = 0;
var it = root.findChildrenByTag("enums");
while (it.next()) |enums| {
const name = enums.getAttribute("name") orelse return error.InvalidRegistry;
if (mem.eql(u8, name, api_constants_name)) {
if (mem.eql(u8, name, api_constants_name) or !requiredByApi(enums, api)) {
continue;
}
out[i] = .{
.name = name,
.decl_type = .{ .enumeration = try parseEnumFields(allocator, enums) },
.decl_type = .{ .enumeration = try parseEnumFields(allocator, enums, api) },
};
i += 1;
}
@@ -342,7 +407,7 @@ fn parseEnums(allocator: Allocator, out: []registry.Declaration, root: *xml.Elem
return i;
}
fn parseEnumFields(allocator: Allocator, elem: *xml.Element) !registry.Enum {
fn parseEnumFields(allocator: Allocator, elem: *xml.Element, api: registry.Api) !registry.Enum {
// TODO: `type` was added recently, fall back to checking endswith FlagBits for older versions?
const enum_type = elem.getAttribute("type") orelse return error.InvalidRegistry;
const is_bitmask = mem.eql(u8, enum_type, "bitmask");
@@ -360,12 +425,15 @@ fn parseEnumFields(allocator: Allocator, elem: *xml.Element) !registry.Enum {
var i: usize = 0;
var it = elem.findChildrenByTag("enum");
while (it.next()) |field| {
if (!requiredByApi(field, api))
continue;
fields[i] = try parseEnumField(field);
i += 1;
}
return registry.Enum{
.fields = allocator.shrink(fields, i),
.fields = fields[0..i],
.bitwidth = bitwidth,
.is_bitmask = is_bitmask,
};
@@ -409,11 +477,14 @@ fn parseEnumField(field: *xml.Element) !registry.Enum.Field {
};
}
fn parseCommands(allocator: Allocator, out: []registry.Declaration, commands_elem: *xml.Element) !usize {
fn parseCommands(allocator: Allocator, out: []registry.Declaration, commands_elem: *xml.Element, api: registry.Api) !usize {
var i: usize = 0;
var it = commands_elem.findChildrenByTag("command");
while (it.next()) |elem| {
out[i] = try parseCommand(allocator, elem);
if (!requiredByApi(elem, api))
continue;
out[i] = try parseCommand(allocator, elem, api);
i += 1;
}
@@ -427,7 +498,7 @@ fn splitCommaAlloc(allocator: Allocator, text: []const u8) ![][]const u8 {
}
const codes = try allocator.alloc([]const u8, n_codes);
var it = mem.split(u8, text, ",");
var it = mem.splitScalar(u8, text, ',');
for (codes) |*code| {
code.* = it.next().?;
}
@@ -435,7 +506,7 @@ fn splitCommaAlloc(allocator: Allocator, text: []const u8) ![][]const u8 {
return codes;
}
fn parseCommand(allocator: Allocator, elem: *xml.Element) !registry.Declaration {
fn parseCommand(allocator: Allocator, elem: *xml.Element, api: registry.Api) !registry.Declaration {
if (elem.getAttribute("alias")) |alias| {
const name = elem.getAttribute("name") orelse return error.InvalidRegistry;
return registry.Declaration{
@@ -455,34 +526,51 @@ fn parseCommand(allocator: Allocator, elem: *xml.Element) !registry.Declaration
var i: usize = 0;
var it = elem.findChildrenByTag("param");
while (it.next()) |param| {
if (!requiredByApi(param, api))
continue;
var xctok = cparse.XmlCTokenizer.init(param);
const decl = try cparse.parseParamOrProto(allocator, &xctok, false);
params[i] = .{
.name = decl.name,
.param_type = decl.decl_type.typedef,
.is_buffer_len = false,
.is_optional = false,
};
if (param.getAttribute("optional")) |optionals| {
var optional_it = mem.splitScalar(u8, optionals, ',');
if (optional_it.next()) |first_optional| {
params[i].is_optional = mem.eql(u8, first_optional, "true");
} else {
// Optional is empty, probably incorrect.
return error.InvalidRegistry;
}
}
i += 1;
}
const return_type = try allocator.create(registry.TypeInfo);
return_type.* = command_decl.decl_type.typedef;
const success_codes: [][]const u8 = if (elem.getAttribute("successcodes")) |codes|
const success_codes = if (elem.getAttribute("successcodes")) |codes|
try splitCommaAlloc(allocator, codes)
else
&[_][]const u8{};
const error_codes: [][]const u8 = if (elem.getAttribute("errorcodes")) |codes|
const error_codes = if (elem.getAttribute("errorcodes")) |codes|
try splitCommaAlloc(allocator, codes)
else
&[_][]const u8{};
params = allocator.shrink(params, i);
params = params[0..i];
it = elem.findChildrenByTag("param");
for (params) |*param| {
const param_elem = it.next().?;
const param_elem = while (it.next()) |param_elem| {
if (requiredByApi(param_elem, api)) break param_elem;
} else unreachable;
try parsePointerMeta(.{ .command = params }, &param.param_type, param_elem);
}
@@ -499,7 +587,7 @@ fn parseCommand(allocator: Allocator, elem: *xml.Element) !registry.Declaration
};
}
fn parseApiConstants(allocator: Allocator, root: *xml.Element) ![]registry.ApiConstant {
fn parseApiConstants(allocator: Allocator, root: *xml.Element, api: registry.Api) ![]registry.ApiConstant {
var enums = blk: {
var it = root.findChildrenByTag("enums");
while (it.next()) |child| {
@@ -531,6 +619,9 @@ fn parseApiConstants(allocator: Allocator, root: *xml.Element) ![]registry.ApiCo
var i: usize = 0;
var it = enums.findChildrenByTag("enum");
while (it.next()) |constant| {
if (!requiredByApi(constant, api))
continue;
const expr = if (constant.getAttribute("value")) |expr|
expr
else if (constant.getAttribute("alias")) |alias|
@@ -546,21 +637,24 @@ fn parseApiConstants(allocator: Allocator, root: *xml.Element) ![]registry.ApiCo
i += 1;
}
i += try parseDefines(types, constants[i..]);
return allocator.shrink(constants, i);
i += try parseDefines(types, constants[i..], api);
return constants[0..i];
}
fn parseDefines(types: *xml.Element, out: []registry.ApiConstant) !usize {
fn parseDefines(types: *xml.Element, out: []registry.ApiConstant, api: registry.Api) !usize {
var i: usize = 0;
var it = types.findChildrenByTag("type");
while (it.next()) |ty| {
if (!requiredByApi(ty, api))
continue;
const category = ty.getAttribute("category") orelse continue;
if (!mem.eql(u8, category, "define")) {
continue;
}
const name = ty.getCharData("name") orelse continue;
if (mem.eql(u8, name, "VK_HEADER_VERSION")) {
if (mem.eql(u8, name, "VK_HEADER_VERSION") or mem.eql(u8, name, "VKSC_API_VARIANT")) {
out[i] = .{
.name = name,
.value = .{ .expr = mem.trim(u8, ty.children[2].char_data, " ") },
@@ -593,10 +687,10 @@ fn parseTags(allocator: Allocator, root: *xml.Element) ![]registry.Tag {
i += 1;
}
return allocator.shrink(tags, i);
return tags[0..i];
}
fn parseFeatures(allocator: Allocator, root: *xml.Element) ![]registry.Feature {
fn parseFeatures(allocator: Allocator, root: *xml.Element, api: registry.Api) ![]registry.Feature {
var it = root.findChildrenByTag("feature");
var count: usize = 0;
while (it.next()) |_| count += 1;
@@ -605,14 +699,17 @@ fn parseFeatures(allocator: Allocator, root: *xml.Element) ![]registry.Feature {
var i: usize = 0;
it = root.findChildrenByTag("feature");
while (it.next()) |feature| {
features[i] = try parseFeature(allocator, feature);
if (!requiredByApi(feature, api))
continue;
features[i] = try parseFeature(allocator, feature, api);
i += 1;
}
return features;
return features[0..i];
}
fn parseFeature(allocator: Allocator, feature: *xml.Element) !registry.Feature {
fn parseFeature(allocator: Allocator, feature: *xml.Element, api: registry.Api) !registry.Feature {
const name = feature.getAttribute("name") orelse return error.InvalidRegistry;
const feature_level = blk: {
const number = feature.getAttribute("number") orelse return error.InvalidRegistry;
@@ -623,14 +720,17 @@ fn parseFeature(allocator: Allocator, feature: *xml.Element) !registry.Feature {
var i: usize = 0;
var it = feature.findChildrenByTag("require");
while (it.next()) |require| {
requires[i] = try parseRequire(allocator, require, null);
if (!requiredByApi(require, api))
continue;
requires[i] = try parseRequire(allocator, require, null, api);
i += 1;
}
return registry.Feature{
.name = name,
.level = feature_level,
.requires = allocator.shrink(requires, i),
.requires = requires[0..i],
};
}
@@ -683,7 +783,7 @@ fn enumExtOffsetToValue(extnumber: u31, offset: u31) u31 {
return extension_value_base + (extnumber - 1) * extension_block + offset;
}
fn parseRequire(allocator: Allocator, require: *xml.Element, extnumber: ?u31) !registry.Require {
fn parseRequire(allocator: Allocator, require: *xml.Element, extnumber: ?u31, api: registry.Api) !registry.Require {
var n_extends: usize = 0;
var n_types: usize = 0;
var n_commands: usize = 0;
@@ -709,6 +809,9 @@ fn parseRequire(allocator: Allocator, require: *xml.Element, extnumber: ?u31) !r
it = require.elements();
while (it.next()) |elem| {
if (!requiredByApi(elem, api))
continue;
if (mem.eql(u8, elem.tag, "enum")) {
if (try parseEnumExtension(elem, extnumber)) |ext| {
extends[i_extends] = ext;
@@ -733,21 +836,23 @@ fn parseRequire(allocator: Allocator, require: *xml.Element, extnumber: ?u31) !r
};
return registry.Require{
.extends = allocator.shrink(extends, i_extends),
.types = types,
.commands = commands,
.extends = extends[0..i_extends],
.types = types[0..i_types],
.commands = commands[0..i_commands],
.required_feature_level = required_feature_level,
.required_extension = require.getAttribute("extension"),
};
}
fn parseExtensions(allocator: Allocator, root: *xml.Element) ![]registry.Extension {
fn parseExtensions(allocator: Allocator, root: *xml.Element, api: registry.Api) ![]registry.Extension {
const extensions_elem = root.findChildByTag("extensions") orelse return error.InvalidRegistry;
const extensions = try allocator.alloc(registry.Extension, extensions_elem.children.len);
var i: usize = 0;
var it = extensions_elem.findChildrenByTag("extension");
while (it.next()) |extension| {
if (!requiredByApi(extension, api))
continue;
// Some extensions (in particular 94) are disabled, so just skip them
if (extension.getAttribute("supported")) |supported| {
if (mem.eql(u8, supported, "disabled")) {
@@ -755,11 +860,11 @@ fn parseExtensions(allocator: Allocator, root: *xml.Element) ![]registry.Extensi
}
}
extensions[i] = try parseExtension(allocator, extension);
extensions[i] = try parseExtension(allocator, extension, api);
i += 1;
}
return allocator.shrink(extensions, i);
return extensions[0..i];
}
fn findExtVersion(extension: *xml.Element) !u32 {
@@ -778,7 +883,7 @@ fn findExtVersion(extension: *xml.Element) !u32 {
return error.InvalidRegistry;
}
fn parseExtension(allocator: Allocator, extension: *xml.Element) !registry.Extension {
fn parseExtension(allocator: Allocator, extension: *xml.Element, api: registry.Api) !registry.Extension {
const name = extension.getAttribute("name") orelse return error.InvalidRegistry;
const platform = extension.getAttribute("platform");
const version = try findExtVersion(extension);
@@ -826,7 +931,9 @@ fn parseExtension(allocator: Allocator, extension: *xml.Element) !registry.Exten
var i: usize = 0;
var it = extension.findChildrenByTag("require");
while (it.next()) |require| {
requires[i] = try parseRequire(allocator, require, number);
if (!requiredByApi(require, api))
continue;
requires[i] = try parseRequire(allocator, require, number, api);
i += 1;
}
@@ -839,12 +946,12 @@ fn parseExtension(allocator: Allocator, extension: *xml.Element) !registry.Exten
.promoted_to = promoted_to,
.platform = platform,
.required_feature_level = requires_core,
.requires = allocator.shrink(requires, i),
.requires = requires[0..i],
};
}
fn splitFeatureLevel(ver: []const u8, split: []const u8) !registry.FeatureLevel {
var it = mem.split(u8, ver, split);
var it = mem.splitSequence(u8, ver, split);
const major = it.next() orelse return error.InvalidFeatureLevel;
const minor = it.next() orelse return error.InvalidFeatureLevel;
@@ -857,3 +964,14 @@ fn splitFeatureLevel(ver: []const u8, split: []const u8) !registry.FeatureLevel
.minor = try std.fmt.parseInt(u32, minor, 10),
};
}
fn requiredByApi(elem: *xml.Element, api: registry.Api) bool {
const apis = elem.getAttribute("api") orelse return true; // If the 'api' element is not present, assume required.
var it = mem.splitScalar(u8, apis, ',');
while (it.next()) |required_by_api| {
if (std.mem.eql(u8, @tagName(api), required_by_api)) return true;
}
return false;
}

View File

@@ -1,3 +1,8 @@
pub const Api = enum {
vulkan,
vulkansc,
};
pub const Registry = struct {
decls: []Declaration,
api_constants: []ApiConstant,
@@ -61,6 +66,7 @@ pub const Container = struct {
field_type: TypeInfo,
bits: ?usize,
is_buffer_len: bool,
is_optional: bool,
};
stype: ?[]const u8,
@@ -105,19 +111,22 @@ pub const Command = struct {
name: []const u8,
param_type: TypeInfo,
is_buffer_len: bool,
is_optional: bool,
};
params: []Param,
return_type: *TypeInfo,
success_codes: [][]const u8,
error_codes: [][]const u8,
success_codes: []const []const u8,
error_codes: []const []const u8,
};
pub const Pointer = struct {
pub const PointerSize = union(enum) {
one,
many, // The length is given by some complex expression, possibly involving another field
other_field: []const u8, // The length is given by some other field or parameter
/// The length is given by some complex expression, possibly involving another field
many,
/// The length is given by some other field or parameter
other_field: []const u8,
zero_terminated,
};
@@ -133,7 +142,26 @@ pub const Array = struct {
alias: []const u8, // Field size is given by an api constant
};
pub const ArrayValidSize = union(enum) {
/// All elements are valid.
all,
/// The length is given by some complex expression, possibly involving another field
many,
/// The length is given by some complex expression, possibly involving another field
other_field: []const u8,
/// The valid elements are terminated by a 0, or by the bounds of the array.
zero_terminated,
};
/// This is the total size of the array
size: ArraySize,
/// The number of items that are actually filled with valid values
valid_size: ArrayValidSize,
/// Some members may indicate than an array is optional. This happens with
/// VkPhysicalDeviceHostImageCopyPropertiesEXT::optimalTilingLayoutUUID for example.
/// The spec is not entirely clear about what this means, but presumably it should
/// be filled with all zeroes.
is_optional: bool,
child: *TypeInfo,
};

File diff suppressed because it is too large Load Diff

View File

@@ -56,8 +56,8 @@ pub const Element = struct {
}
pub fn findChildByTag(self: Element, tag: []const u8) ?*Element {
var children = self.findChildrenByTag(tag);
return children.next();
var it = self.findChildrenByTag(tag);
return it.next();
}
pub fn findChildrenByTag(self: Element, tag: []const u8) FindChildrenByTagIterator {
@@ -232,7 +232,7 @@ const Parser = struct {
begin = prev_nl + 1;
}
var end = mem.indexOfScalarPos(u8, self.source, self.offset, '\n') orelse self.source.len;
const end = mem.indexOfScalarPos(u8, self.source, self.offset, '\n') orelse self.source.len;
return self.source[begin..end];
}
};
@@ -481,8 +481,8 @@ fn parseElement(parser: *Parser, alloc: Allocator, comptime kind: ElementKind) !
const element = try alloc.create(Element);
element.* = .{
.tag = try alloc.dupe(u8, tag),
.attributes = attributes.toOwnedSlice(),
.children = children.toOwnedSlice(),
.attributes = try attributes.toOwnedSlice(),
.children = try children.toOwnedSlice(),
};
return element;
}

122
test/ref_all_decls.zig Normal file
View File

@@ -0,0 +1,122 @@
const std = @import("std");
const vk = @import("vulkan");
// Provide bogus defaults for unknown platform types
// The actual type does not really matter here...
pub const GgpStreamDescriptor = u32;
pub const GgpFrameToken = u32;
pub const _screen_buffer = u32;
pub const NvSciSyncAttrList = u32;
pub const NvSciSyncObj = u32;
pub const NvSciSyncFence = u32;
pub const NvSciBufAttrList = u32;
pub const NvSciBufObj = u32;
pub const ANativeWindow = u32;
pub const AHardwareBuffer = u32;
pub const CAMetalLayer = u32;
pub const MTLDevice_id = u32;
pub const MTLCommandQueue_id = u32;
pub const MTLBuffer_id = u32;
pub const MTLTexture_id = u32;
pub const MTLSharedEvent_id = u32;
pub const IOSurfaceRef = u32;
// For some reason these types are exported in a different header, and not described in vk.xml.
pub const StdVideoH264ProfileIdc = u32;
pub const StdVideoH264LevelIdc = u32;
pub const StdVideoH264ChromaFormatIdc = u32;
pub const StdVideoH264PocType = u32;
pub const StdVideoH264SpsFlags = u32;
pub const StdVideoH264ScalingLists = u32;
pub const StdVideoH264SequenceParameterSetVui = u32;
pub const StdVideoH264AspectRatioIdc = u32;
pub const StdVideoH264HrdParameters = u32;
pub const StdVideoH264SpsVuiFlags = u32;
pub const StdVideoH264WeightedBipredIdc = u32;
pub const StdVideoH264PpsFlags = u32;
pub const StdVideoH264SliceType = u32;
pub const StdVideoH264CabacInitIdc = u32;
pub const StdVideoH264DisableDeblockingFilterIdc = u32;
pub const StdVideoH264PictureType = u32;
pub const StdVideoH264ModificationOfPicNumsIdc = u32;
pub const StdVideoH264MemMgmtControlOp = u32;
pub const StdVideoDecodeH264PictureInfo = u32;
pub const StdVideoDecodeH264ReferenceInfo = u32;
pub const StdVideoDecodeH264PictureInfoFlags = u32;
pub const StdVideoDecodeH264ReferenceInfoFlags = u32;
pub const StdVideoH264SequenceParameterSet = u32;
pub const StdVideoH264PictureParameterSet = u32;
pub const StdVideoH265ProfileIdc = u32;
pub const StdVideoH265VideoParameterSet = u32;
pub const StdVideoH265SequenceParameterSet = u32;
pub const StdVideoH265PictureParameterSet = u32;
pub const StdVideoH265DecPicBufMgr = u32;
pub const StdVideoH265HrdParameters = u32;
pub const StdVideoH265VpsFlags = u32;
pub const StdVideoH265LevelIdc = u32;
pub const StdVideoH265SpsFlags = u32;
pub const StdVideoH265ScalingLists = u32;
pub const StdVideoH265SequenceParameterSetVui = u32;
pub const StdVideoH265PredictorPaletteEntries = u32;
pub const StdVideoH265PpsFlags = u32;
pub const StdVideoH265SubLayerHrdParameters = u32;
pub const StdVideoH265HrdFlags = u32;
pub const StdVideoH265SpsVuiFlags = u32;
pub const StdVideoH265SliceType = u32;
pub const StdVideoH265PictureType = u32;
pub const StdVideoDecodeH265PictureInfo = u32;
pub const StdVideoDecodeH265ReferenceInfo = u32;
pub const StdVideoDecodeH265PictureInfoFlags = u32;
pub const StdVideoDecodeH265ReferenceInfoFlags = u32;
pub const StdVideoAV1Profile = u32;
pub const StdVideoAV1Level = u32;
pub const StdVideoAV1SequenceHeader = u32;
pub const StdVideoDecodeAV1PictureInfo = u32;
pub const StdVideoDecodeAV1ReferenceInfo = u32;
pub const StdVideoEncodeH264SliceHeader = u32;
pub const StdVideoEncodeH264PictureInfo = u32;
pub const StdVideoEncodeH264ReferenceInfo = u32;
pub const StdVideoEncodeH264SliceHeaderFlags = u32;
pub const StdVideoEncodeH264ReferenceListsInfo = u32;
pub const StdVideoEncodeH264PictureInfoFlags = u32;
pub const StdVideoEncodeH264ReferenceInfoFlags = u32;
pub const StdVideoEncodeH264RefMgmtFlags = u32;
pub const StdVideoEncodeH264RefListModEntry = u32;
pub const StdVideoEncodeH264RefPicMarkingEntry = u32;
pub const StdVideoEncodeH265PictureInfoFlags = u32;
pub const StdVideoEncodeH265PictureInfo = u32;
pub const StdVideoEncodeH265SliceSegmentHeader = u32;
pub const StdVideoEncodeH265ReferenceInfo = u32;
pub const StdVideoEncodeH265ReferenceListsInfo = u32;
pub const StdVideoEncodeH265SliceSegmentHeaderFlags = u32;
pub const StdVideoEncodeH265ReferenceInfoFlags = u32;
pub const StdVideoEncodeH265ReferenceModificationFlags = u32;
pub const StdVideoEncodeAV1OperatingPointInfo = u32;
comptime {
@setEvalBranchQuota(1000000);
reallyRefAllDecls(vk);
}
fn reallyRefAllDecls(comptime T: type) void {
switch (@typeInfo(T)) {
.Struct, .Union => {
reallyRefAllContainerDecls(T);
inline for (std.meta.fields(T)) |field| {
reallyRefAllDecls(field.type);
}
},
.Enum, .Opaque => {
reallyRefAllContainerDecls(T);
},
else => {},
}
}
fn reallyRefAllContainerDecls(comptime T: type) void {
inline for (comptime std.meta.declarations(T)) |decl| {
if (@TypeOf(@field(T, decl.name)) == type) {
reallyRefAllDecls(@field(T, decl.name));
}
}
}

View File

@@ -1,6 +0,0 @@
id: uxw7q1ovyv4z3t7fi28agxovmhbrobglw7mwtl5p3pnsc1gu
name: vulkan-zig
main: generator/index.zig
license: MIT
description: Vulkan binding generator for Zig
dependencies: