-
Notifications
You must be signed in to change notification settings - Fork 14
/
Copy pathzigglgen.zig
1280 lines (1227 loc) · 45.1 KB
/
zigglgen.zig
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// © 2024 Carl Åstholm
// SPDX-License-Identifier: MIT
const std = @import("std");
const builtin = @import("builtin");
const Options = @import("GeneratorOptions.zig");
const registry = @import("api_registry.zig");
const shims = @import("shims.zig");
/// Usage: `zigglen <api>-<version>[-<profile>] [<extension> ...]`
pub fn main() !void {
var arena_state = std.heap.ArenaAllocator.init(std.heap.page_allocator);
defer arena_state.deinit();
const arena = arena_state.allocator();
var arg_it = try std.process.argsWithAllocator(arena);
const exe_name = arg_it.next() orelse "zigglen";
const raw_triple = arg_it.next() orelse printUsageAndExit(exe_name);
const triple = ApiVersionProfile.parse(raw_triple) catch |err|
return handleApiVersionProfileUserErrorAndExit(err, raw_triple);
const api, const version, const profile = .{ triple.api, triple.version, triple.profile };
var extensions: ResolvedExtensions = .{};
var resolve_everything = false;
while (arg_it.next()) |raw_extension| {
if (std.mem.eql(u8, raw_extension, "ZIGGLGEN_everything")) { // For internal testing.
resolve_everything = true;
continue;
}
const extension = parseExtension(raw_extension, api) catch |err|
return handleExtensionUserErrorAndExit(err, raw_extension, api, version, profile);
extensions.put(extension, .{});
}
var types: ResolvedTypes = .{};
var constants: ResolvedConstants = .{};
var commands: ResolvedCommands = .{};
if (resolve_everything)
resolveEverything(&extensions, &types, &constants, &commands)
else
resolveQuery(api, version, profile, &extensions, &types, &constants, &commands);
var stdout_state = std.io.bufferedWriter(std.io.getStdOut().writer());
const stdout = stdout_state.writer();
try renderCode(stdout, api, version, profile, &extensions, &types, &constants, &commands);
try stdout_state.flush();
}
const ApiVersionProfile = struct {
api: registry.Api.Name,
version: [2]u8,
profile: ?registry.ProfileName,
fn parse(raw: []const u8) ParseError!ApiVersionProfile {
var raw_it = std.mem.splitScalar(u8, raw, '-');
const raw_api = raw_it.next().?;
const raw_version = raw_it.next() orelse return error.MissingVersion;
const maybe_raw_profile = raw_it.next();
if (raw_it.next() != null) return error.UnknownExtraField;
var api: registry.Api.Name = switch (inline for (shims.typeInfo(Options.Api).@"enum".fields) |field| {
if (std.mem.eql(u8, raw_api, field.name)) break @field(Options.Api, field.name);
} else return error.InvalidApi) {
.gl => .gl,
.gles => .gles2,
.glsc => .glsc2,
};
const version: [2]u8 = inline for (shims.typeInfo(Options.Version).@"enum".fields) |field| {
if (std.mem.eql(u8, raw_version, field.name)) {
const dot = std.mem.indexOfScalar(u8, raw_version, '.').?;
break .{
std.fmt.parseUnsigned(u8, raw_version[0..dot], 10) catch unreachable,
std.fmt.parseUnsigned(u8, raw_version[(dot + 1)..], 10) catch unreachable,
};
}
} else return error.InvalidVersion;
var maybe_profile: ?registry.ProfileName = if (maybe_raw_profile) |raw_profile|
switch (inline for (shims.typeInfo(Options.Profile).@"enum".fields) |field| {
if (std.mem.eql(u8, raw_profile, field.name)) break @field(Options.Profile, field.name);
} else return error.InvalidProfile) {
.core => .core,
.compatibility => .compatibility,
.common => .common,
.common_lite => .common_lite,
}
else
null;
// Fix up API
if (api == .gles2 and version[0] < 2) {
api = .gles1;
}
// Validate version
if (api == .gles1) {
// GL ES 1.0/1.1 is an odd special case; the API Registry defines the feature set under
// 1.0, but it includes features added in 1.1. Therefore, we only accept 1.1, even
// though it's 1.0 in the registry.
if (version[0] != 1 or version[1] != 1) return error.UnsupportedVersion;
} else for (registry.apis) |reg_api| {
if (reg_api.name == api and reg_api.version[0] == version[0] and reg_api.version[1] == version[1]) break;
} else return error.UnsupportedVersion;
// Validate/fix up profile
switch (api) {
.gl => {
// The Core/Compatibility profiles were introduced in GL 3.2.
if (version[0] < 3 or version[0] == 3 and version[1] < 2) {
if (maybe_profile != null) return error.UnsupportedProfile;
} else if (maybe_profile) |profile| switch (profile) {
.core, .compatibility => {},
else => return error.UnsupportedProfile,
} else {
maybe_profile = .core;
}
},
.gles1 => {
// The Common/Common-Lite profiles were introduced in GL ES 1.0.
if (maybe_profile) |profile| switch (profile) {
.common, .common_lite => {},
else => return error.UnsupportedProfile,
} else {
maybe_profile = .common;
}
},
// The Common/Common-Lite profiles were dropped in GL ES 2.0 (and GL SC never had any).
else => if (maybe_profile != null) return error.UnsupportedProfile,
}
return .{ .api = api, .version = version, .profile = maybe_profile };
}
const ParseError = error{
InvalidApi,
MissingVersion,
InvalidVersion,
UnsupportedVersion,
InvalidProfile,
UnsupportedProfile,
UnknownExtraField,
};
};
fn parseExtension(raw: []const u8, api: registry.Api.Name) ParseExtensionError!registry.Extension.Name {
// Statically assert that 'api_registry.zig' and 'GeneratorOptions.zig' are in sync.
comptime {
@setEvalBranchQuota(100_000);
for (shims.typeInfo(registry.Extension.Name).@"enum".fields, shims.typeInfo(Options.Extension).@"enum".fields) |a, b| {
std.debug.assert(std.mem.eql(u8, a.name, b.name));
}
}
const extension: registry.Extension.Name = inline for (shims.typeInfo(registry.Extension.Name).@"enum".fields) |field| {
if (std.mem.eql(u8, raw, field.name)) break @field(registry.Extension.Name, field.name);
} else return error.InvalidExtension;
// Validate extension
const reg_extension = for (registry.extensions) |reg_extension| {
if (reg_extension.name == extension) break reg_extension;
} else return error.UnsupportedExtension;
if (std.mem.indexOfScalar(registry.Api.Name, reg_extension.apis, api) == null) return error.UnsupportedExtension;
return extension;
}
const ParseExtensionError = error{
InvalidExtension,
UnsupportedExtension,
};
fn printUsageAndExit(exe_name: []const u8) noreturn {
std.debug.print("Usage: {s} <api>-<version>[-<profile>] [<extension> ...]", .{std.fs.path.basename(exe_name)});
std.process.exit(1);
}
fn handleApiVersionProfileUserErrorAndExit(
err: ApiVersionProfile.ParseError,
raw_triple: []const u8,
) noreturn {
var raw_it = std.mem.splitScalar(u8, raw_triple, '-');
const raw_api = raw_it.next().?;
const raw_version = raw_it.next();
const raw_profile = raw_it.next();
const raw_extra = raw_it.next();
switch (err) {
error.InvalidApi,
=> std.log.err("API '{s}' is not a supported API", .{raw_api}),
error.MissingVersion,
=> std.log.err("missing version field after API field", .{}),
error.InvalidVersion,
error.UnsupportedVersion,
=> std.log.err("version '{s}' is not a supported version of '{s}'", .{ raw_version.?, raw_api }),
error.InvalidProfile,
error.UnsupportedProfile,
=> std.log.err("profile '{s}' is not a supported profile of '{s}-{s}'", .{ raw_profile.?, raw_api, raw_version.? }),
error.UnknownExtraField,
=> std.log.err("unknown extra value '{s}' after profile field", .{raw_extra.?}),
}
std.process.exit(1);
}
fn handleExtensionUserErrorAndExit(
err: ParseExtensionError,
raw_extension: []const u8,
api: registry.Api.Name,
version: [2]u8,
profile: ?registry.ProfileName,
) noreturn {
switch (err) {
error.InvalidExtension,
error.UnsupportedExtension,
=> std.log.err("extension '{s}' is not a supported extension of '{s}-{}.{}{s}{s}'", .{
raw_extension,
@tagName(api),
version[0],
version[1],
if (profile != null) "-" else "",
if (profile) |x| @tagName(x) else "",
}),
}
std.process.exit(1);
}
comptime {
@setEvalBranchQuota(100_000);
_ = std.enums.EnumIndexer(registry.Extension.Name);
_ = std.enums.EnumIndexer(registry.Type.Name);
_ = std.enums.EnumIndexer(registry.Constant.Name);
_ = std.enums.EnumIndexer(registry.Command.Name);
}
const ResolvedExtensions = std.EnumMap(registry.Extension.Name, struct {
commands: std.EnumSet(registry.Command.Name) = .{},
});
const ResolvedTypes = std.EnumMap(registry.Type.Name, struct {
requires: ?registry.Type.Name = null,
});
const ResolvedConstants = std.EnumMap(registry.Constant.Name, struct {
value: i128,
});
const ResolvedCommands = std.EnumMap(registry.Command.Name, struct {
params: []const registry.Command.Param,
return_type_expr: []const registry.Command.Token,
required: bool = false,
});
fn resolveQuery(
api: registry.Api.Name,
version: [2]u8,
profile: ?registry.ProfileName,
extensions: *ResolvedExtensions,
types: *ResolvedTypes,
constants: *ResolvedConstants,
commands: *ResolvedCommands,
) void {
// Add API features
for (registry.apis) |reg_api| {
if (reg_api.name != api) continue;
if (reg_api.version[0] > version[0] or reg_api.version[0] == version[0] and reg_api.version[1] > version[1]) continue;
for (reg_api.add) |feature| {
std.debug.assert(feature.api == null);
if (feature.profile != null and feature.profile != profile) continue;
switch (feature.name) {
.type => |name| _ = tryPutType(types, name),
.constant => |name| _ = tryPutConstant(constants, name, api),
.command => |name| _ = tryPutCommand(commands, name, true),
}
}
}
// Remove API features
for (registry.apis) |reg_api| {
if (reg_api.name != api) continue;
if (reg_api.version[0] > version[0] or reg_api.version[0] == version[0] and reg_api.version[1] > version[1]) continue;
for (reg_api.remove) |feature| {
std.debug.assert(feature.api == null);
if (feature.profile != null and feature.profile != profile) continue;
switch (feature.name) {
.type => |name| types.remove(name),
.constant => |name| constants.remove(name),
.command => |name| commands.remove(name),
}
}
}
// Add extension features
var extension_it = extensions.iterator();
while (extension_it.next()) |extension| {
for (registry.extensions) |reg_extension| {
if (reg_extension.name != extension.key) continue;
std.debug.assert(std.mem.indexOfScalar(registry.Api.Name, reg_extension.apis, api) != null);
for (reg_extension.add) |feature| {
if (feature.api != null and feature.api != api) continue;
if (feature.profile != null and feature.profile != profile) continue;
switch (feature.name) {
.type => |name| _ = tryPutType(types, name),
.constant => |name| _ = tryPutConstant(constants, name, api),
.command => |name| {
_ = tryPutCommand(commands, name, false);
extension.value.commands.insert(name);
},
}
}
break;
}
}
// Add command type dependencies
var command_it = commands.iterator();
while (command_it.next()) |command| {
for (command.value.params) |param| for (param.type_expr) |token| switch (token) {
.type => |name| _ = tryPutType(types, name),
else => {},
};
for (command.value.return_type_expr) |token| switch (token) {
.type => |name| _ = tryPutType(types, name),
else => {},
};
}
// Add type type dependencies
while (true) {
var mutated = false;
var type_it = types.iterator();
while (type_it.next()) |@"type"| {
if (@"type".value.requires) |requires| if (tryPutType(types, requires)) {
mutated = true;
};
}
if (!mutated) break;
}
}
fn tryPutType(types: *ResolvedTypes, name: registry.Type.Name) bool {
if (types.contains(name)) return false;
for (registry.types) |reg_type| {
if (reg_type.name != name) continue;
types.put(name, .{ .requires = reg_type.requires });
return true;
}
unreachable;
}
fn tryPutConstant(constants: *ResolvedConstants, name: registry.Constant.Name, api: registry.Api.Name) bool {
if (constants.contains(name)) return false;
for (registry.constants) |reg_constant| {
if (reg_constant.name != name) continue;
if (reg_constant.api != null and reg_constant.api != api) continue;
constants.put(name, .{ .value = reg_constant.value });
return true;
}
unreachable;
}
fn tryPutCommand(commands: *ResolvedCommands, name: registry.Command.Name, required: bool) bool {
if (commands.contains(name)) return false;
for (registry.commands) |reg_command| {
if (reg_command.name != name) continue;
commands.put(name, .{
.params = reg_command.params,
.return_type_expr = reg_command.return_type_expr,
.required = required,
});
return true;
}
unreachable;
}
fn resolveEverything(
extensions: *ResolvedExtensions,
types: *ResolvedTypes,
constants: *ResolvedConstants,
commands: *ResolvedCommands,
) void {
@setEvalBranchQuota(100_000);
for (std.enums.values(registry.Extension.Name)) |name| extensions.put(name, .{});
for (std.enums.values(registry.Type.Name)) |name| _ = tryPutType(types, name);
for (std.enums.values(registry.Constant.Name)) |name| _ = tryPutConstant(constants, name, .gl);
for (std.enums.values(registry.Command.Name)) |name| _ = tryPutCommand(commands, name, false);
}
fn renderCode(
writer: anytype,
api: registry.Api.Name,
version: [2]u8,
profile: ?registry.ProfileName,
extensions: *ResolvedExtensions,
types: *ResolvedTypes,
constants: *ResolvedConstants,
commands: *ResolvedCommands,
) !void {
const any_extensions = extensions.count() != 0;
try writer.print("" ++
// REUSE-IgnoreStart
\\// © 2013-2020 The Khronos Group Inc.
\\// © 2024 Carl Åstholm
\\// SPDX-License-Identifier: Apache-2.0 AND MIT
// REUSE-IgnoreEnd
\\
\\//! Bindings for {[api_pretty]s} {[version_major]d}.{[version_minor]d}{[sp_profile_pretty]s} generated by zigglgen.
\\
\\// OpenGL XML API Registry revision: {[registry_revision]s}
\\// zigglgen version: 0.3.0
\\
\\// Example usage:
\\//
\\// const windowing = @import(...);
\\// const gl = @import("gl");
\\//
\\// // Procedure table that will hold OpenGL functions loaded at runtime.
\\// var procs: gl.ProcTable = undefined;
\\//
\\// pub fn main() !void {{
\\// // Create an OpenGL context using a windowing system of your choice.
\\// const context = windowing.createContext(...);
\\// defer context.destroy();
\\//
\\// // Make the OpenGL context current on the calling thread.
\\// windowing.makeContextCurrent(context);
\\// defer windowing.makeContextCurrent(null);
\\//
\\// // Initialize the procedure table.
\\// if (!procs.init(windowing.getProcAddress)) return error.InitFailed;
\\//
\\// // Make the procedure table current on the calling thread.
\\// gl.makeProcTableCurrent(&procs);
\\// defer gl.makeProcTableCurrent(null);
\\//
\\// // Issue OpenGL commands to your heart's content!
\\// const alpha: gl.{[clear_color_type]s} = 1;
\\// gl.{[clear_color_fn]s}(1, 1, 1, alpha);
\\// gl.Clear(gl.COLOR_BUFFER_BIT);
\\// }}
\\//
\\
\\const std = @import("std");
\\const builtin = @import("builtin");
\\
\\/// Information about this set of OpenGL bindings.
\\pub const info = struct {{
\\ pub const api: Api = {[api]s};
\\ pub const version_major = {[version_major]d};
\\ pub const version_minor = {[version_minor]d};
\\ pub const profile: ?Profile = {[profile]s};
\\
\\ pub const Api = enum {{ gl, gles, glsc }};
\\ pub const Profile = enum {{ core, compatibility, common, common_lite }};
\\}};
\\
, .{
.registry_revision = registry.revision,
.api_pretty = switch (api) {
.gl => "OpenGL",
.gles1, .gles2 => "OpenGL ES",
.glsc2 => "OpenGL SC",
},
.api = switch (api) {
.gl => ".gl",
.gles1, .gles2 => ".gles",
.glsc2 => ".glsc",
},
.version_major = version[0],
.version_minor = version[1],
.sp_profile_pretty = if (profile) |x| switch (x) {
.core => " (Core profile)",
.compatibility => " (Compatibility profile)",
.common => " (Common profile)",
.common_lite => " (Common-Lite profile)",
} else "",
.profile = if (profile) |x| switch (x) {
.core => ".core",
.compatibility => ".compatibility",
.common => ".common",
.common_lite => ".common_lite",
} else "null",
.clear_color_type = if (profile == .common_lite) "fixed" else "float",
.clear_color_fn = if (profile == .common_lite) "ClearColorx" else "ClearColor",
});
try writer.writeAll(
\\
\\/// Makes the specified procedure table current on the calling thread.
\\///
\\/// A valid procedure table must be made current on a thread before issuing any OpenGL commands from
\\/// that same thread.
\\pub fn makeProcTableCurrent(procs: ?*const ProcTable) void {
\\ ProcTable.current = procs;
\\}
\\
\\/// Returns the procedure table that is current on the calling thread.
\\pub fn getCurrentProcTable() ?*const ProcTable {
\\ return ProcTable.current;
\\}
\\
);
if (any_extensions) {
try writer.writeAll(
\\
\\/// Returns `true` if the specified OpenGL extension is supported by the procedure table that is
\\/// current on the calling thread, `false` otherwise.
\\pub fn extensionSupported(comptime extension: Extension) bool {
\\ return @field(ProcTable.current orelse return false, @tagName(extension));
\\}
\\
\\/// OpenGL extension.
\\pub const Extension = enum {
\\
);
var extension_it = extensions.iterator();
while (extension_it.next()) |extension| {
try writer.print(
\\ {p},
\\
, .{std.zig.fmtId(@tagName(extension.key))});
}
try writer.writeAll(
\\};
\\
);
}
try writer.writeAll(
\\
\\pub const APIENTRY = if (builtin.os.tag == .windows and builtin.cpu.arch == .x86) std.builtin.CallingConvention.Stdcall else std.builtin.CallingConvention.C;
\\pub const PROC = *align(@alignOf(fn () callconv(APIENTRY) void)) const anyopaque;
\\
\\//#region Types
\\
);
var type_it = types.iterator();
while (type_it.next()) |@"type"| {
switch (@"type".key) {
.khrplatform, .void => continue,
else => {},
}
try writer.print(
\\pub const {} = {s};
\\
, .{ std.zig.fmtId(@tagName(@"type".key)), getTypeValue(@"type".key) });
}
try writer.writeAll(
\\//#endregion Types
\\
\\//#region Constants
\\
);
var constant_it = constants.iterator();
while (constant_it.next()) |constant| {
try writer.print(
\\pub const {} = {s}0x{X};
\\
, .{ std.zig.fmtId(@tagName(constant.key)), if (constant.value.value < 0) "-" else "", @abs(constant.value.value) });
}
try writer.writeAll(
\\//#endregion Constants
\\
\\//#region Commands
\\
);
var command_it = commands.iterator();
while (command_it.next()) |command| {
try writer.print("pub fn {}(", .{std.zig.fmtId(@tagName(command.key))});
try renderParams(writer, command, false);
try writer.writeAll(") callconv(APIENTRY) ");
try renderReturnType(writer, command);
try writer.print(" {{\n return ProcTable.current.?.{p_}", .{std.zig.fmtId(@tagName(command.key))});
if (!command.value.required) try writer.writeAll(".?");
try writer.writeAll("(");
try renderParams(writer, command, true);
try writer.writeAll(");\n}\n");
}
try writer.writeAll(
\\//#endregion Commands
\\
\\/// Holds OpenGL features loaded at runtime.
\\///
\\/// This struct is very large; avoid storing instances of it on the stack.
\\pub const ProcTable = struct {
\\ threadlocal var current: ?*const ProcTable = null;
\\
\\ //#region Fields
\\
);
if (any_extensions) {
var extension_it = extensions.iterator();
while (extension_it.next()) |extension| {
try writer.print(
\\ {p_}: bool,
\\
, .{std.zig.fmtId(@tagName(extension.key))});
}
}
command_it = commands.iterator();
while (command_it.next()) |command| {
try writer.print(" {p_}: ", .{std.zig.fmtId(@tagName(command.key))});
if (!command.value.required) try writer.writeAll("?");
try writer.writeAll("*const fn (");
try renderParams(writer, command, false);
try writer.writeAll(") callconv(APIENTRY) ");
try renderReturnType(writer, command);
try writer.writeAll(",\n");
}
try writer.writeAll(
\\ //#endregion Fields
\\
\\ /// Initializes the specified procedure table and returns `true` if successful,
\\ /// `false` otherwise.
\\ ///
\\ /// A procedure table must be successfully initialized before passing it to
\\ /// `makeProcTableCurrent` or accessing any of its fields.
\\ ///
\\ /// `loader` is duck-typed. Given the prefixed name of an OpenGL command (e.g. `"glClear"`), it
\\ /// should return a pointer to the corresponding function. It should be able to be used in one
\\ /// of the following two ways:
\\ ///
\\ /// - `@as(?PROC, loader(@as([*:0]const u8, prefixed_name)))`
\\ /// - `@as(?PROC, loader.getProcAddress(@as([*:0]const u8, prefixed_name)))`
\\ ///
\\ /// If your windowing system has a "get procedure address" function, it is usually enough to
\\ /// simply pass that function as the `loader` argument.
\\ ///
\\ /// No references to `loader` are retained after this function returns.
\\ ///
\\ /// There is no corresponding `deinit` function.
\\ pub fn init(procs: *ProcTable, loader: anytype) bool {
\\ @setEvalBranchQuota(1_000_000);
\\ var success: u1 = 1;
\\ inline for (shims.typeInfo(ProcTable).@"struct".fields) |field_info| {
\\ switch (shims.typeInfo(field_info.type)) {
\\ .pointer => |ptr_info| switch (shims.typeInfo(ptr_info.child)) {
\\ .@"fn" => {
\\ success &= @intFromBool(procs.initCommand(loader, field_info.name));
\\ },
\\ else => comptime unreachable,
\\ },
\\
);
if (any_extensions) {
try writer.writeAll(
\\ .optional => |opt_info| switch (shims.typeInfo(opt_info.child)) {
\\ .pointer => |ptr_info| switch (shims.typeInfo(ptr_info.child)) {
\\ .@"fn" => {
\\ @field(procs, field_info.name) = null;
\\ },
\\ else => comptime unreachable,
\\ },
\\ else => comptime unreachable,
\\ },
\\ .bool => {
\\ @field(procs, field_info.name) = false;
\\ },
\\
);
}
try writer.writeAll(
\\ else => comptime unreachable,
\\ }
\\ }
\\
);
if (any_extensions) {
try writer.writeAll(
\\ if (success == 0) return false;
\\
);
var extension_it = extensions.iterator();
while (extension_it.next()) |extension| {
if (extension.value.commands.count() != 0) {
try writer.print(
\\ if (procs.initExtension("{s}")) {{
\\
, .{@tagName(extension.key)});
var extension_command_it = extension.value.commands.iterator();
while (extension_command_it.next()) |extension_command| {
try writer.print(
\\ _ = procs.initCommand(loader, "{s}");
\\
, .{@tagName(extension_command)});
}
try writer.writeAll(
\\ }
\\
);
} else {
try writer.print(
\\ _ = procs.initExtension("{s}");
\\
, .{@tagName(extension.key)});
}
}
try writer.writeAll(
\\ return true;
\\
);
} else {
try writer.writeAll(
\\ return success != 0;
\\
);
}
try writer.writeAll(
\\ }
\\
\\ fn initCommand(procs: *ProcTable, loader: anytype, comptime name: [:0]const u8) bool {
\\ if (getProcAddress(loader, "gl" ++ name)) |proc| {
\\ @field(procs, name) = @ptrCast(proc);
\\ return true;
\\ } else {
\\ return shims.typeInfo(@TypeOf(@field(procs, name))) == .optional;
\\ }
\\ }
\\
\\ fn getProcAddress(loader: anytype, prefixed_name: [:0]const u8) ?PROC {
\\ const loader_info = shims.typeInfo(@TypeOf(loader));
\\ const loader_is_fn =
\\ loader_info == .@"fn" or
\\ loader_info == .pointer and shims.typeInfo(loader_info.pointer.child) == .@"fn";
\\ if (loader_is_fn) {
\\ return @as(?PROC, loader(@as([*:0]const u8, prefixed_name)));
\\ } else {
\\ return @as(?PROC, loader.getProcAddress(@as([*:0]const u8, prefixed_name)));
\\ }
\\ }
\\
);
if (any_extensions) {
try writer.writeAll(
\\
\\ fn initExtension(procs: *ProcTable, comptime name: [:0]const u8) bool {
\\
);
if (version[0] >= 3) {
// GL 3.0 and GL ES 3.0 both introduced querying extensions by index via 'GetStringi'.
// Starting with GL 3.2, querying extensions via 'GetString' is no longer supported
// under the Core profile.
try writer.writeAll(
\\ var count: c_int = 0;
\\ procs.GetIntegerv(NUM_EXTENSIONS, (&count)[0..1]);
\\ if (count < 0) return false;
\\ var i: c_uint = 0;
\\ while (i < @as(c_uint, @intCast(count))) : (i += 1) {
\\ const prefixed_name = procs.GetStringi(EXTENSIONS, i) orelse return false;
\\ if (std.mem.orderZ(u8, prefixed_name, "GL_" ++ name) == .eq) {
\\
);
} else {
try writer.writeAll(
\\ const prefixed_names = procs.GetString(EXTENSIONS) orelse return false;
\\ var it = std.mem.tokenizeScalar(u8, std.mem.span(prefixed_names), ' ');
\\ while (it.next()) |prefixed_name| {
\\ if (std.mem.eql(u8, prefixed_name, "GL_" ++ name)) {
\\
);
}
try writer.writeAll(
\\ @field(procs, name) = true;
\\ return true;
\\ }
\\ }
\\ return false;
\\ }
\\
);
}
try writer.writeAll(
\\};
\\
\\const shims = struct {
);
var shims_lines_it = std.mem.splitScalar(u8, @embedFile("shims.zig"), '\n');
while (shims_lines_it.next()) |line| {
try writer.writeAll("\n");
if (line.len != 0) {
try writer.writeAll(" ");
try writer.writeAll(line);
}
}
try writer.writeAll(
\\};
\\
\\test {
\\ @setEvalBranchQuota(1_000_000);
\\ std.testing.refAllDeclsRecursive(@This());
\\}
\\
);
}
fn fmtTypeExpr(type_expr: []const registry.Command.Token) std.fmt.Formatter(formatTypeExpr) {
return .{ .data = type_expr };
}
fn formatTypeExpr(
type_expr: []const registry.Command.Token,
comptime _: []const u8,
_: std.fmt.FormatOptions,
writer: anytype,
) !void {
if (type_expr.len == 1 and type_expr[0] == .void) {
return writer.writeAll("void");
}
for (type_expr, 0..) |token, token_index| switch (token) {
.void => try writer.writeAll("anyopaque"),
.@"*" => {
try writer.writeAll(
if (type_expr[type_expr.len - 1] == .void and for (type_expr[(token_index + 1)..]) |future_token| {
if (future_token == .@"*") break false;
} else true)
"?*"
else
"[*c]",
);
},
.@"const" => try writer.writeAll("const "),
.type => |@"type"| try writer.print("{}", .{std.zig.fmtId(@tagName(@"type"))}),
};
}
fn getTypeValue(@"type": registry.Type.Name) []const u8 {
return switch (@"type") {
.DEBUGPROC,
.DEBUGPROCARB,
.DEBUGPROCKHR,
=> "*const fn (source: @\"enum\", @\"type\": @\"enum\", id: uint, severity: @\"enum\", length: sizei, message: [*:0]const char, userParam: ?*const anyopaque) callconv(APIENTRY) void",
.DEBUGPROCAMD,
=> "*const fn (id: uint, category: @\"enum\", severity: @\"enum\", length: sizei, message: [*:0]const char, userParam: ?*anyopaque) callconv(APIENTRY) void",
.VULKANPROCNV,
=> "*const fn () callconv(APIENTRY) void",
.bitfield,
.@"enum",
.uint,
=> "c_uint",
.boolean,
.char,
.charARB,
.ubyte,
=> "u8",
.byte,
=> "i8",
.cl_context,
.cl_event,
.eglClientBufferEXT,
.eglImageOES,
.sync,
=> "*opaque {}",
.clampd,
.double,
=> "f64",
.clampf,
.float,
=> "f32",
.clampx,
.fixed,
=> "i32",
.half,
.halfARB,
.ushort,
=> "u16",
.halfNV,
=> "c_ushort",
.handleARB,
=> "if (builtin.os.tag.isDarwin()) *allowzero anyopaque else u32",
.int,
.sizei,
=> "c_int",
.int64,
.int64EXT,
=> "i64",
.intptr,
.intptrARB,
.sizeiptr,
.sizeiptrARB,
=> "isize",
.short,
=> "i16",
.uint64,
.uint64EXT,
=> "u64",
.vdpauSurfaceNV,
=> "intptr",
.khrplatform,
.void,
=> unreachable,
};
}
fn renderParams(writer: anytype, command: ResolvedCommands.Entry, comptime name_only: bool) !void {
for (command.value.params, 0..) |param, param_index| {
if (param_index != 0) try writer.writeAll(", ");
if (paramOverride(command.key, param_index)) |override| {
try writer.print("{}", .{std.zig.fmtId(override.name)});
if (!name_only) {
try writer.print(": {s}", .{override.type_expr});
}
} else {
try writer.print("{}", .{std.zig.fmtId(param.name)});
if (!name_only) {
try writer.print(": {}", .{fmtTypeExpr(param.type_expr)});
}
}
}
}
fn paramOverride(command: registry.Command.Name, param_index: usize) ?struct {
name: []const u8,
type_expr: []const u8,
} {
return switch (command) {
.BufferData,
.BufferDataARB,
=> switch (param_index) {
2 => .{ .name = "data", .type_expr = "?*const anyopaque" },
else => null,
},
.BufferStorageExternalEXT,
.NamedBufferStorageExternalEXT,
=> switch (param_index) {
3 => .{ .name = "clientBuffer", .type_expr = "eglClientBufferEXT" },
else => null,
},
inline .ClearBufferfv,
.ClearBufferiv,
.ClearBufferuiv,
=> |tag| switch (param_index) {
2 => .{
.name = "values",
.type_expr = "[*]const " ++ switch (tag) {
.ClearBufferfv => "float",
.ClearBufferiv => "int",
.ClearBufferuiv => "uint",
else => comptime unreachable,
},
},
else => null,
},
inline .ClearNamedFramebufferfv,
.ClearNamedFramebufferiv,
.ClearNamedFramebufferuiv,
=> |tag| switch (param_index) {
3 => .{
.name = "values",
.type_expr = "[*]const " ++ switch (tag) {
.ClearNamedFramebufferfv => "float",
.ClearNamedFramebufferiv => "int",
.ClearNamedFramebufferuiv => "uint",
else => comptime unreachable,
},
},
else => null,
},
.ClientWaitSync,
.ClientWaitSyncAPPLE,
.GetSynciv,
.GetSyncivAPPLE,
.WaitSync,
.WaitSyncAPPLE,
=> switch (param_index) {
0 => .{ .name = "sync_", .type_expr = "sync" },
else => null,
},
.CreateSyncFromCLeventARB,
=> switch (param_index) {
0 => .{ .name = "context", .type_expr = "cl_context" },
1 => .{ .name = "event", .type_expr = "cl_event" },
else => null,
},
inline .DebugMessageCallback,
.DebugMessageCallbackAMD,
.DebugMessageCallbackARB,
.DebugMessageCallbackKHR,
=> |tag| switch (param_index) {
0 => .{
.name = "callback",
.type_expr = "?" ++ switch (tag) {
.DebugMessageCallbackAMD => "DEBUGPROCAMD",
.DebugMessageCallbackARB => "DEBUGPROCARB",
.DebugMessageCallbackKHR => "DEBUGPROCKHR",
else => "DEBUGPROC",
},
},
else => null,
},
.DeleteBuffers,
.DeleteBuffersARB,
.GenBuffers,
.GenBuffersARB,
=> switch (param_index) {
1 => .{ .name = "buffers", .type_expr = "[*]uint" },
else => null,
},