-
Notifications
You must be signed in to change notification settings - Fork 21
/
internal.zig
2282 lines (1949 loc) · 80 KB
/
internal.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
const std = @import("std");
const Allocator = std.mem.Allocator;
const ArrayList = std.ArrayList;
const c = @cImport({
@cDefine("FONS_NO_STDIO", "1");
@cInclude("fontstash.h");
@cDefine("STBI_NO_STDIO", "1");
@cInclude("stb_image.h");
});
const nvg = @import("nanovg.zig");
const Color = nvg.Color;
const Paint = nvg.Paint;
const Image = nvg.Image;
const ImageFlags = nvg.ImageFlags;
const Font = nvg.Font;
const init_fontimage_size = 512;
const max_fontimage_size = 2048;
// Length proportional to radius of a cubic bezier handle for 90deg arcs.
const kappa90 = 4.0 * (@sqrt(2.0) - 1.0) / 3.0; // 0.5522847493
pub const Context = struct {
allocator: Allocator,
params: Params,
commands: ArrayList(f32),
commandx: f32 = 0,
commandy: f32 = 0,
states: ArrayList(State),
cache: PathCache,
tess_tol: f32,
dist_tol: f32,
device_px_ratio: f32 = 1,
fs: ?*c.FONScontext = null,
font_images: [4]i32 = [_]i32{0} ** 4,
font_image_idx: u32 = 0,
draw_call_count: u32 = 0,
fill_tri_count: u32 = 0,
stroke_tri_count: u32 = 0,
text_tri_count: u32 = 0,
pub fn init(allocator: Allocator, params: Params) !*Context {
var ctx = try allocator.create(Context);
ctx.* = Context{
.allocator = allocator,
.params = params,
.commands = ArrayList(f32).init(allocator),
.states = ArrayList(State).init(allocator),
.cache = try PathCache.init(allocator),
.tess_tol = undefined,
.dist_tol = undefined,
.device_px_ratio = undefined,
};
errdefer ctx.deinit();
try ctx.commands.ensureTotalCapacity(256);
try ctx.states.ensureTotalCapacity(32);
ctx.save();
ctx.reset();
ctx.setDevicePixelRatio(1);
try ctx.params.renderCreate(ctx.params.user_ptr);
var font_params = std.mem.zeroes(c.FONSparams);
font_params.width = init_fontimage_size;
font_params.height = init_fontimage_size;
font_params.flags = c.FONS_ZERO_TOPLEFT;
font_params.renderCreate = null;
font_params.renderUpdate = null;
font_params.renderDraw = null;
font_params.renderDelete = null;
font_params.userPtr = null;
ctx.fs = c.fonsCreateInternal(&font_params) orelse return error.CreateFontstashFailed;
// Create font texture
ctx.font_images[0] = try ctx.params.renderCreateTexture(ctx.params.user_ptr, .alpha, @intCast(font_params.width), @intCast(font_params.height), .{}, null);
ctx.font_image_idx = 0;
return ctx;
}
pub fn deinit(ctx: *Context) void {
ctx.commands.deinit();
ctx.states.deinit();
ctx.cache.deinit();
if (ctx.fs != null) {
c.fonsDeleteInternal(ctx.fs);
}
for (&ctx.font_images) |*font_image| {
if (font_image.* != 0) {
ctx.deleteImage(font_image.*);
font_image.* = 0;
}
}
_ = ctx.params.renderDelete(ctx.params.user_ptr);
ctx.allocator.destroy(ctx);
}
fn setDevicePixelRatio(ctx: *Context, ratio: f32) void {
ctx.tess_tol = 0.25 / ratio;
ctx.dist_tol = 0.01 / ratio;
ctx.device_px_ratio = ratio;
}
pub fn getState(ctx: *Context) *State {
return &ctx.states.items[ctx.states.items.len - 1];
}
pub fn save(ctx: *Context) void {
const state = ctx.states.addOne() catch return;
if (ctx.states.items.len > 1) {
state.* = ctx.states.items[ctx.states.items.len - 2];
}
}
pub fn restore(ctx: *Context) void {
_ = ctx.states.popOrNull();
}
pub fn reset(ctx: *Context) void {
var state = ctx.getState();
state.* = std.mem.zeroes(State);
setPaintColor(&state.fill, nvg.rgbaf(1, 1, 1, 1));
setPaintColor(&state.stroke, nvg.rgbaf(0, 0, 0, 1));
state.composite_operation = nvg.CompositeOperationState.initOperation(.source_over);
state.stroke_width = 1;
state.miter_limit = 10;
state.line_cap = .butt;
state.line_join = .miter;
state.alpha = 1;
nvg.transformIdentity(&state.xform);
state.scissor.extent[0] = -1;
state.scissor.extent[1] = -1;
state.font_size = 16;
state.letter_spacing = 0;
state.line_height = 1;
state.font_blur = 0;
state.text_align.horizontal = .left;
state.text_align.vertical = .baseline;
state.font_id = c.FONS_INVALID;
}
pub fn shapeAntiAlias(ctx: *Context, enabled: bool) void {
ctx.getState().shape_antialias = enabled;
}
pub fn strokeWidth(ctx: *Context, width: f32) void {
ctx.getState().stroke_width = width;
}
pub fn miterLimit(ctx: *Context, limit: f32) void {
ctx.getState().miter_limit = limit;
}
pub fn lineCap(ctx: *Context, cap: nvg.LineCap) void {
ctx.getState().line_cap = cap;
}
pub fn lineJoin(ctx: *Context, join: nvg.LineJoin) void {
ctx.getState().line_join = join;
}
pub fn globalAlpha(ctx: *Context, alpha: f32) void {
ctx.getState().alpha = alpha;
}
pub fn transform(ctx: *Context, a: f32, b: f32, _c: f32, d: f32, e: f32, f: f32) void {
const state = ctx.getState();
var t: [6]f32 = .{ a, b, _c, d, e, f };
nvg.transformPremultiply(&state.xform, &t);
}
pub fn resetTransform(ctx: *Context) void {
const state = ctx.getState();
nvg.transformIdentity(&state.xform);
}
pub fn translate(ctx: *Context, x: f32, y: f32) void {
const state = ctx.getState();
var t: [6]f32 = undefined;
nvg.transformTranslate(&t, x, y);
nvg.transformPremultiply(&state.xform, &t);
}
pub fn rotate(ctx: *Context, angle: f32) void {
const state = ctx.getState();
var t: [6]f32 = undefined;
nvg.transformRotate(&t, angle);
nvg.transformPremultiply(&state.xform, &t);
}
pub fn skewX(ctx: *Context, angle: f32) void {
const state = ctx.getState();
var t: [6]f32 = undefined;
nvg.transformSkewX(&t, angle);
nvg.transformPremultiply(&state.xform, &t);
}
pub fn skewY(ctx: *Context, angle: f32) void {
const state = ctx.getState();
var t: [6]f32 = undefined;
nvg.transformSkewY(&t, angle);
nvg.transformPremultiply(&state.xform, &t);
}
pub fn scale(ctx: *Context, x: f32, y: f32) void {
const state = ctx.getState();
var t: [6]f32 = undefined;
nvg.transformScale(&t, x, y);
nvg.transformPremultiply(&state.xform, &t);
}
pub fn currentTransform(ctx: *Context, xform: *[6]f32) void {
const state = ctx.getState();
@memcpy(xform, &state.xform);
}
pub fn strokeColor(ctx: *Context, color: Color) void {
const state = ctx.getState();
setPaintColor(&state.stroke, color);
}
pub fn strokePaint(ctx: *Context, paint: Paint) void {
const state = ctx.getState();
state.stroke = paint;
nvg.transformMultiply(&state.stroke.xform, &state.xform);
}
pub fn fillColor(ctx: *Context, color: Color) void {
const state = ctx.getState();
setPaintColor(&state.fill, color);
}
pub fn fillPaint(ctx: *Context, paint: Paint) void {
const state = ctx.getState();
state.fill = paint;
nvg.transformMultiply(&state.fill.xform, &state.xform);
}
pub fn createImageMem(ctx: *Context, data: []const u8, flags: ImageFlags) Image {
var w: c_int = undefined;
var h: c_int = undefined;
var n: c_int = undefined;
const maybe_img = c.stbi_load_from_memory(data.ptr, @intCast(data.len), &w, &h, &n, 4);
if (maybe_img) |img| {
defer c.stbi_image_free(img);
const size: usize = @intCast(w * h * 4);
return ctx.createImageRGBA(@intCast(w), @intCast(h), flags, img[0..size]);
}
return .{ .handle = 0 };
}
pub fn createImageRGBA(ctx: *Context, w: u32, h: u32, flags: ImageFlags, data: ?[]const u8) Image {
return Image{ .handle = ctx.params.renderCreateTexture(ctx.params.user_ptr, .rgba, @intCast(w), @intCast(h), flags, data) catch 0 };
}
pub fn createImageAlpha(ctx: *Context, w: u32, h: u32, flags: ImageFlags, data: []const u8) Image {
return Image{ .handle = ctx.params.renderCreateTexture(ctx.params.user_ptr, .alpha, @intCast(w), @intCast(h), flags, data) catch 0 };
}
pub fn updateImage(ctx: *Context, image: Image, data: []const u8) void {
var w: u32 = undefined;
var h: u32 = undefined;
_ = ctx.params.renderGetTextureSize(ctx.params.user_ptr, image.handle, &w, &h);
_ = ctx.params.renderUpdateTexture(ctx.params.user_ptr, image.handle, 0, 0, w, h, data);
}
pub fn beginFrame(ctx: *Context, window_width: f32, window_height: f32, device_pixel_ratio: f32) void {
ctx.states.clearRetainingCapacity();
ctx.save();
ctx.reset();
ctx.setDevicePixelRatio(device_pixel_ratio);
ctx.params.renderViewport(ctx.params.user_ptr, window_width, window_height, device_pixel_ratio);
ctx.draw_call_count = 0;
ctx.fill_tri_count = 0;
ctx.stroke_tri_count = 0;
ctx.text_tri_count = 0;
}
pub fn cancelFrame(ctx: *Context) void {
ctx.params.renderCancel(ctx.params.user_ptr);
}
pub fn endFrame(ctx: *Context) void {
ctx.params.renderFlush(ctx.params.user_ptr);
if (ctx.font_image_idx != 0) {
const font_image = ctx.font_images[ctx.font_image_idx];
// delete images that are smaller than current one
if (font_image == 0)
return;
var iw: u32 = undefined;
var ih: u32 = undefined;
ctx.imageSize(font_image, &iw, &ih);
var i: u32 = 0;
var j: u32 = 0;
while (i < ctx.font_image_idx) : (i += 1) {
if (ctx.font_images[i] != 0) {
var nw: u32 = undefined;
var nh: u32 = undefined;
const image = ctx.font_images[i];
ctx.font_images[i] = 0;
ctx.imageSize(image, &nw, &nh);
if (nw < iw or nh < ih) {
ctx.deleteImage(image);
} else {
ctx.font_images[j] = image;
j += 1;
}
}
}
// make current font image to first
ctx.font_images[ctx.font_image_idx] = 0;
ctx.font_images[j] = ctx.font_images[0];
ctx.font_images[0] = font_image;
ctx.font_image_idx = 0;
}
}
fn appendCommands(ctx: *Context, vals_src: anytype) void {
var vals: [vals_src.len]f32 = vals_src;
const state = ctx.getState();
ctx.commands.ensureUnusedCapacity(vals.len) catch return;
if (vals_src.len >= 3) {
ctx.commandx = vals[vals.len - 2];
ctx.commandy = vals[vals.len - 1];
}
// transform commands
var i: u32 = 0;
while (i < vals.len) {
switch (Command.fromValue(vals[i])) {
.move_to => {
transformPoint(&vals[i + 1], &vals[i + 2], state.xform, vals[i + 1], vals[i + 2]);
i += 3;
},
.line_to => {
transformPoint(&vals[i + 1], &vals[i + 2], state.xform, vals[i + 1], vals[i + 2]);
i += 3;
},
.bezier_to => {
transformPoint(&vals[i + 1], &vals[i + 2], state.xform, vals[i + 1], vals[i + 2]);
transformPoint(&vals[i + 3], &vals[i + 4], state.xform, vals[i + 3], vals[i + 4]);
transformPoint(&vals[i + 5], &vals[i + 6], state.xform, vals[i + 5], vals[i + 6]);
i += 7;
},
.winding => i += 2,
.close, .clip => i += 1,
}
}
ctx.commands.appendSliceAssumeCapacity(&vals);
ctx.cache.clear();
}
fn tesselateBezier(ctx: *Context, x1: f32, y1: f32, x2: f32, y2: f32, x3: f32, y3: f32, x4: f32, y4: f32, level: u8, cornerType: PointFlags) void {
if (level > 10) return;
const x12 = (x1 + x2) * 0.5;
const y12 = (y1 + y2) * 0.5;
const x23 = (x2 + x3) * 0.5;
const y23 = (y2 + y3) * 0.5;
const x34 = (x3 + x4) * 0.5;
const y34 = (y3 + y4) * 0.5;
const x123 = (x12 + x23) * 0.5;
const y123 = (y12 + y23) * 0.5;
const dx = x4 - x1;
const dy = y4 - y1;
const d2 = @abs(((x2 - x4) * dy - (y2 - y4) * dx));
const d3 = @abs(((x3 - x4) * dy - (y3 - y4) * dx));
if ((d2 + d3) * (d2 + d3) < ctx.tess_tol * (dx * dx + dy * dy)) {
ctx.cache.addPoint(x4, y4, cornerType, ctx.dist_tol);
return;
}
const x234 = (x23 + x34) * 0.5;
const y234 = (y23 + y34) * 0.5;
const x1234 = (x123 + x234) * 0.5;
const y1234 = (y123 + y234) * 0.5;
ctx.tesselateBezier(x1, y1, x12, y12, x123, y123, x1234, y1234, level + 1, .{});
ctx.tesselateBezier(x1234, y1234, x234, y234, x34, y34, x4, y4, level + 1, cornerType);
}
fn flattenPaths(ctx: *Context) void {
const cache = &ctx.cache;
if (cache.paths.items.len > 0)
return;
// Flatten
var i: u32 = 0;
while (i < ctx.commands.items.len) {
switch (Command.fromValue(ctx.commands.items[i])) {
.move_to => {
cache.addPath();
const p = ctx.commands.items[i + 1 ..];
cache.addPoint(p[0], p[1], .{ .corner = true }, ctx.dist_tol);
i += 3;
},
.line_to => {
const p = ctx.commands.items[i + 1 ..];
cache.addPoint(p[0], p[1], .{ .corner = true }, ctx.dist_tol);
i += 3;
},
.bezier_to => {
if (cache.lastPoint()) |last| {
const cp1 = ctx.commands.items[i + 1 ..];
const cp2 = ctx.commands.items[i + 3 ..];
const p = ctx.commands.items[i + 5 ..];
ctx.tesselateBezier(last.x, last.y, cp1[0], cp1[1], cp2[0], cp2[1], p[0], p[1], 0, .{ .corner = true });
}
i += 7;
},
.close => {
cache.closePath();
i += 1;
},
.winding => {
cache.pathWinding(@enumFromInt(@as(u2, @intFromFloat(ctx.commands.items[i + 1]))));
i += 2;
},
.clip => {
cache.clip();
i += 1;
},
}
}
cache.bounds[0] = 1e6;
cache.bounds[1] = 1e6;
cache.bounds[2] = -1e6;
cache.bounds[3] = -1e6;
// Calculate the direction and length of line segments.
for (cache.paths.items) |*path| {
var pts = cache.points.items[path.first..][0..path.count];
// If the first and last points are the same, remove the last, mark as closed path.
var p0 = &pts[pts.len - 1];
if (ptEquals(p0.x, p0.y, pts[0].x, pts[0].y, ctx.dist_tol)) {
path.count -= 1;
if (path.count == 0) continue;
pts.len -= 1;
path.closed = true;
}
// Enforce winding.
if (path.count > 2) {
const area = polyArea(pts);
if (path.winding == .ccw and area < 0.0)
polyReverse(pts);
if (path.winding == .cw and area > 0.0)
polyReverse(pts);
}
p0 = &pts[pts.len - 1];
for (pts) |*p1| {
defer p0 = p1;
// Calculate segment direction and length
p0.dx = p1.x - p0.x;
p0.dy = p1.y - p0.y;
p0.len = normalize(&p0.dx, &p0.dy);
// Update bounds
cache.bounds[0] = @min(cache.bounds[0], p0.x);
cache.bounds[1] = @min(cache.bounds[1], p0.y);
cache.bounds[2] = @max(cache.bounds[2], p0.x);
cache.bounds[3] = @max(cache.bounds[3], p0.y);
}
}
}
fn calculateJoins(ctx: *Context, line_join: nvg.LineJoin, miter_limit: f32) void {
const cache = &ctx.cache;
// Calculate which joins needs extra vertices to append, and gather vertex count.
for (cache.paths.items) |*path| {
if (path.count == 0) continue;
const pts = cache.points.items[path.first..][0..path.count];
var nleft: u32 = 0;
path.nbevel = 0;
var p0 = &pts[pts.len - 1];
for (pts) |*p1| {
defer p0 = p1;
const dlx0 = p0.dy;
const dly0 = -p0.dx;
const dlx1 = p1.dy;
const dly1 = -p1.dx;
// Calculate extrusions
p1.dmx = (dlx0 + dlx1) * 0.5;
p1.dmy = (dly0 + dly1) * 0.5;
const dmr2 = p1.dmx * p1.dmx + p1.dmy * p1.dmy;
if (dmr2 > 0.000001) {
var s = 1.0 / dmr2;
if (s > 600) s = 600;
p1.dmx *= s;
p1.dmy *= s;
}
// Clear flags, but keep the corner.
p1.flags = .{ .corner = p1.flags.corner };
// Keep track of left turns.
if (cross(p0.dx, p0.dy, p1.dx, p1.dy) > 0.0) {
nleft += 1;
p1.flags.left = true;
}
// Calculate if we should use bevel or miter for inner join.
const limit = 1.01;
if ((dmr2 * limit * limit) < 1.0)
p1.flags.innerbevel = true;
// Check to see if the corner needs to be beveled.
if (p1.flags.corner) {
if ((dmr2 * miter_limit * miter_limit) < 1.0 or line_join == .bevel or line_join == .round) {
p1.flags.bevel = true;
}
}
if (p1.flags.bevel or p1.flags.innerbevel)
path.nbevel += 1;
}
path.convex = (nleft == path.count);
}
}
fn expandFill(ctx: *Context, line_join: nvg.LineJoin, miter_limit: f32) !void {
const cache = &ctx.cache;
ctx.calculateJoins(line_join, miter_limit);
// Calculate max vertex usage.
var cverts: u32 = 0;
for (cache.paths.items) |path| {
cverts += path.count + path.nbevel + 1;
}
var verts = try cache.allocTempVerts(cverts);
for (cache.paths.items) |*path| {
if (path.count == 0) continue;
const pts = cache.points.items[path.first..][0..path.count];
// Calculate shape vertices.
var dst = ArrayList(Vertex).fromOwnedSlice(ctx.allocator, verts);
dst.clearRetainingCapacity();
for (pts) |p| {
dst.addOneAssumeCapacity().set(p.x, p.y, 0.5, 1);
}
path.fill = dst.items;
path.stroke = &.{};
verts = verts[dst.items.len..verts.len];
}
}
pub fn expandStroke(ctx: *Context, width: f32, line_cap: nvg.LineCap, line_join: nvg.LineJoin, miter_limit: f32) !void {
const cache = &ctx.cache;
const @"u0": f32 = 0.5;
const @"u1": f32 = 0.5;
const w = width;
const ncap = curveDivs(w, std.math.pi, ctx.tess_tol); // Calculate divisions per half circle.
ctx.calculateJoins(line_join, miter_limit);
// Calculate max vertex usage.
var cverts: u32 = 0;
for (cache.paths.items) |path| {
const loop = path.closed;
if (line_join == .round) {
cverts += (path.count + path.nbevel * (ncap + 2) + 1) * 2; // plus one for loop
} else {
cverts += (path.count + path.nbevel * 5 + 1) * 2; // plus one for loop
}
if (!loop) {
// space for caps
if (line_cap == .round) {
cverts += (ncap * 2 + 2) * 2;
} else {
cverts += (3 + 3) * 2;
}
}
}
var verts = try cache.allocTempVerts(cverts);
for (cache.paths.items) |*path| {
if (path.count == 0) continue;
const pts = cache.points.items[path.first..][0..path.count];
// Calculate fringe or stroke
const loop = path.closed;
var dst = ArrayList(Vertex).fromOwnedSlice(ctx.allocator, verts);
dst.clearRetainingCapacity();
if (path.clip) {
for (pts) |p| {
dst.addOneAssumeCapacity().set(p.x, p.y, 0.5, 1);
}
path.fill = dst.items;
path.stroke = &.{};
} else {
// Looping
var p0 = &pts[path.count - 1];
var p1 = &pts[0];
var s: u32 = 0;
var e = path.count;
if (!loop) {
p0 = &pts[0];
p1 = &pts[1];
s = 1;
e = path.count - 1;
// Add cap
var dx = p1.x - p0.x;
var dy = p1.y - p0.y;
_ = normalize(&dx, &dy);
switch (line_cap) {
.butt => buttCapStart(&dst, p0.*, dx, dy, w, 0, @"u0", @"u1"),
.square => buttCapStart(&dst, p0.*, dx, dy, w, w, @"u0", @"u1"),
.round => roundCapStart(&dst, p0.*, dx, dy, w, ncap, @"u0", @"u1"),
}
}
var j: u32 = s;
while (j < e) : (j += 1) {
p1 = &pts[j];
defer p0 = p1;
if (p1.flags.bevel or p1.flags.innerbevel) {
if (line_join == .round) {
roundJoin(&dst, p0.*, p1.*, w, w, @"u0", @"u1", ncap);
} else {
bevelJoin(&dst, p0.*, p1.*, w, w, @"u0", @"u1");
}
} else {
dst.addOneAssumeCapacity().set(p1.x + (p1.dmx * w), p1.y + (p1.dmy * w), @"u0", 1);
dst.addOneAssumeCapacity().set(p1.x - (p1.dmx * w), p1.y - (p1.dmy * w), @"u1", 1);
}
}
if (loop) {
// Loop it
dst.addOneAssumeCapacity().set(verts[0].x, verts[0].y, @"u0", 1);
dst.addOneAssumeCapacity().set(verts[1].x, verts[1].y, @"u1", 1);
} else {
p1 = &pts[j];
// Add cap
var dx = p1.x - p0.x;
var dy = p1.y - p0.y;
_ = normalize(&dx, &dy);
switch (line_cap) {
.butt => buttCapEnd(&dst, p1.*, dx, dy, w, 0, @"u0", @"u1"),
.square => buttCapEnd(&dst, p1.*, dx, dy, w, w, @"u0", @"u1"),
.round => roundCapEnd(&dst, p1.*, dx, dy, w, ncap, @"u0", @"u1"),
}
}
path.fill = &.{};
path.stroke = dst.items;
}
verts = verts[dst.items.len..verts.len];
}
}
pub fn addPath(ctx: *Context, path: nvg.Path) void {
var i: usize = 0;
for (path.verbs) |verb| {
switch (verb) {
.move => {
ctx.moveTo(path.points[i + 0], path.points[i + 1]);
i += 2;
},
.line => {
ctx.lineTo(path.points[i + 0], path.points[i + 1]);
i += 2;
},
.quad => {
ctx.quadTo(
path.points[i + 0],
path.points[i + 1],
path.points[i + 2],
path.points[i + 3],
);
i += 4;
},
.bezier => {
ctx.bezierTo(
path.points[i + 0],
path.points[i + 1],
path.points[i + 2],
path.points[i + 3],
path.points[i + 4],
path.points[i + 5],
);
i += 6;
},
.close => ctx.closePath(),
}
}
}
pub fn beginPath(ctx: *Context) void {
ctx.commands.clearRetainingCapacity();
}
pub fn moveTo(ctx: *Context, x: f32, y: f32) void {
ctx.appendCommands(.{ Command.move_to.toValue(), x, y });
}
pub fn lineTo(ctx: *Context, x: f32, y: f32) void {
ctx.appendCommands(.{ Command.line_to.toValue(), x, y });
}
pub fn bezierTo(ctx: *Context, c1x: f32, c1y: f32, c2x: f32, c2y: f32, x: f32, y: f32) void {
ctx.appendCommands(.{ Command.bezier_to.toValue(), c1x, c1y, c2x, c2y, x, y });
}
pub fn quadTo(ctx: *Context, cx: f32, cy: f32, x: f32, y: f32) void {
const x0 = ctx.commandx;
const y0 = ctx.commandy;
// zig fmt: off
ctx.appendCommands(.{
Command.bezier_to.toValue(),
x0 + 2.0/3.0*(cx - x0), y0 + 2.0/3.0*(cy - y0),
x + 2.0/3.0*(cx - x), y + 2.0/3.0*(cy - y),
x, y
});
// zig fmt: on
}
pub fn arcTo(ctx: *Context, x1: f32, y1: f32, x2: f32, y2: f32, radius: f32) void {
const x0: f32 = ctx.commandx;
const y0: f32 = ctx.commandy;
if (ctx.commands.items.len == 0) {
return;
}
// Handle degenerate cases.
if (ptEquals(x0, y0, x1, y1, ctx.dist_tol) or
ptEquals(x1, y1, x2, y2, ctx.dist_tol) or
distPtSeg(x1, y1, x0, y0, x2, y2) < ctx.dist_tol * ctx.dist_tol or
radius < ctx.dist_tol)
{
ctx.lineTo(x1, y1);
return;
}
// Calculate tangential circle to lines (x0,y0)-(x1,y1) and (x1,y1)-(x2,y2).
var dx0 = x0 - x1;
var dy0 = y0 - y1;
var dx1 = x2 - x1;
var dy1 = y2 - y1;
_ = normalize(&dx0, &dy0);
_ = normalize(&dx1, &dy1);
const a = std.math.acos(dx0 * dx1 + dy0 * dy1);
const d = radius / @tan(a / 2.0);
if (d > 10000.0) {
ctx.lineTo(x1, y1);
return;
}
if (cross(dx0, dy0, dx1, dy1) > 0.0) {
ctx.arc(
x1 + dx0 * d + dy0 * radius,
y1 + dy0 * d + -dx0 * radius,
radius,
std.math.atan2(dx0, -dy0),
std.math.atan2(-dx1, dy1),
.cw,
);
} else {
ctx.arc(
x1 + dx0 * d + -dy0 * radius,
y1 + dy0 * d + dx0 * radius,
radius,
std.math.atan2(-dx0, dy0),
std.math.atan2(dx1, -dy1),
.ccw,
);
}
}
pub fn closePath(ctx: *Context) void {
ctx.appendCommands(.{Command.close.toValue()});
}
pub fn pathWinding(ctx: *Context, dir: nvg.Winding) void {
ctx.appendCommands(.{ Command.winding.toValue(), @as(f32, @floatFromInt(@intFromEnum(dir))) });
}
pub fn arc(ctx: *Context, cx: f32, cy: f32, r: f32, a0: f32, a1: f32, dir: nvg.Winding) void {
const move: Command = if (ctx.commands.items.len > 0) .line_to else .move_to;
// Clamp angles
var da = a1 - a0;
if (dir == .cw) {
if (@abs(da) >= std.math.pi * 2.0) {
da = std.math.pi * 2.0;
} else {
while (da < 0.0) da += std.math.pi * 2.0;
}
} else {
if (@abs(da) >= std.math.pi * 2.0) {
da = -std.math.pi * 2.0;
} else {
while (da > 0.0) da -= std.math.pi * 2.0;
}
}
// Split arc into max 90 degree segments.
const ndivs = std.math.clamp(@round(@abs(da) / (std.math.pi * 0.5)), 1, 5);
const hda = (da / ndivs) / 2.0;
var kappa = @abs(4.0 / 3.0 * (1.0 - @cos(hda)) / @sin(hda));
if (dir == .ccw)
kappa = -kappa;
var px: f32 = 0;
var py: f32 = 0;
var ptanx: f32 = 0;
var ptany: f32 = 0;
var i: f32 = 0;
while (i <= ndivs) : (i += 1) {
const a = a0 + da * (i / ndivs);
const dx = @cos(a);
const dy = @sin(a);
const x = cx + dx * r;
const y = cy + dy * r;
const tanx = -dy * r * kappa;
const tany = dx * r * kappa;
if (i == 0) {
ctx.appendCommands(.{ move.toValue(), x, y });
} else {
ctx.appendCommands(.{ Command.bezier_to.toValue(), px + ptanx, py + ptany, x - tanx, y - tany, x, y });
}
px = x;
py = y;
ptanx = tanx;
ptany = tany;
}
}
pub fn rect(ctx: *Context, x: f32, y: f32, w: f32, h: f32) void {
ctx.appendCommands(.{
Command.move_to.toValue(), x, y,
Command.line_to.toValue(), x, y + h,
Command.line_to.toValue(), x + w, y + h,
Command.line_to.toValue(), x + w, y,
Command.close.toValue(),
});
}
pub fn roundedRect(ctx: *Context, x: f32, y: f32, w: f32, h: f32, r: f32) void {
ctx.roundedRectVarying(x, y, w, h, r, r, r, r);
}
pub fn roundedRectVarying(ctx: *Context, x: f32, y: f32, w: f32, h: f32, radTopLeft: f32, radTopRight: f32, radBottomRight: f32, radBottomLeft: f32) void {
if (radTopLeft < 0.1 and radTopRight < 0.1 and radBottomRight < 0.1 and radBottomLeft < 0.1) {
ctx.rect(x, y, w, h);
} else {
const halfw = @abs(w) * 0.5;
const halfh = @abs(h) * 0.5;
const rxBL = @min(radBottomLeft, halfw) * sign(w);
const ryBL = @min(radBottomLeft, halfh) * sign(h);
const rxBR = @min(radBottomRight, halfw) * sign(w);
const ryBR = @min(radBottomRight, halfh) * sign(h);
const rxTR = @min(radTopRight, halfw) * sign(w);
const ryTR = @min(radTopRight, halfh) * sign(h);
const rxTL = @min(radTopLeft, halfw) * sign(w);
const ryTL = @min(radTopLeft, halfh) * sign(h);
// zig fmt: off
ctx.appendCommands(.{
Command.move_to.toValue(), x, y + ryTL,
Command.line_to.toValue(), x, y + h - ryBL,
Command.bezier_to.toValue(), x, y + h - ryBL*(1 - kappa90), x + rxBL*(1 - kappa90), y + h, x + rxBL, y + h,
Command.line_to.toValue(), x + w - rxBR, y + h,
Command.bezier_to.toValue(), x + w - rxBR*(1 - kappa90), y + h, x + w, y + h - ryBR*(1 - kappa90), x + w, y + h - ryBR,
Command.line_to.toValue(), x + w, y + ryTR,
Command.bezier_to.toValue(), x + w, y + ryTR*(1 - kappa90), x + w - rxTR*(1 - kappa90), y, x + w - rxTR, y,
Command.line_to.toValue(), x + rxTL, y,
Command.bezier_to.toValue(), x + rxTL*(1 - kappa90), y, x, y + ryTL*(1 - kappa90), x, y + ryTL,
Command.close.toValue(),
});
// zig fmt: on
}
}
pub fn ellipse(ctx: *Context, cx: f32, cy: f32, rx: f32, ry: f32) void {
// zig fmt: off
ctx.appendCommands(.{
Command.move_to.toValue(), cx-rx, cy,
Command.bezier_to.toValue(), cx-rx, cy+ry*kappa90, cx-rx*kappa90, cy+ry, cx, cy+ry,
Command.bezier_to.toValue(), cx+rx*kappa90, cy+ry, cx+rx, cy+ry*kappa90, cx+rx, cy,
Command.bezier_to.toValue(), cx+rx, cy-ry*kappa90, cx+rx*kappa90, cy-ry, cx, cy-ry,
Command.bezier_to.toValue(), cx-rx*kappa90, cy-ry, cx-rx, cy-ry*kappa90, cx-rx, cy,
Command.close.toValue(),
});
// zig fmt: on
}
pub fn clip(ctx: *Context) void {
ctx.appendCommands(.{Command.clip.toValue()});
}
pub fn imageSize(ctx: *Context, image: i32, w: *u32, h: *u32) void {
_ = ctx.params.renderGetTextureSize(ctx.params.user_ptr, image, w, h);
}
pub fn deleteImage(ctx: *Context, image: i32) void {
ctx.params.renderDeleteTexture(ctx.params.user_ptr, image);
}
pub fn linearGradient(ctx: *Context, sx: f32, sy: f32, ex: f32, ey: f32, icol: Color, ocol: Color) Paint {
_ = ctx;
var p = std.mem.zeroes(Paint);
const large = 1e5;
// Calculate transform aligned to the line
var dx = ex - sx;
var dy = ey - sy;
const d = @sqrt(dx * dx + dy * dy);
if (d > 0.0001) {
dx /= d;
dy /= d;
} else {
dx = 0;
dy = 1;
}
p.xform[0] = dy;
p.xform[1] = -dx;
p.xform[2] = dx;
p.xform[3] = dy;
p.xform[4] = sx - dx * large;
p.xform[5] = sy - dy * large;
p.extent[0] = large;
p.extent[1] = large + d * 0.5;
p.radius = 0;
p.feather = @max(1, d);
p.inner_color = icol;
p.outer_color = ocol;
return p;
}
pub fn radialGradient(ctx: *Context, cx: f32, cy: f32, inr: f32, outr: f32, icol: Color, ocol: Color) Paint {
_ = ctx;
const r = (inr + outr) * 0.5;
const f = (outr - inr);
var p = std.mem.zeroes(Paint);
nvg.transformIdentity(&p.xform);
p.xform[4] = cx;
p.xform[5] = cy;
p.extent[0] = r;
p.extent[1] = r;
p.radius = r;
p.feather = @max(1, f);
p.inner_color = icol;
p.outer_color = ocol;
return p;
}