-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathProcessing.cpp
More file actions
4637 lines (4339 loc) · 199 KB
/
Copy pathProcessing.cpp
File metadata and controls
4637 lines (4339 loc) · 199 KB
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
#if __has_include("stb_truetype.h")
# define PROCESSING_HAS_STB_TRUETYPE 1
# define STB_TRUETYPE_IMPLEMENTATION
# include "stb_truetype.h"
#else
# define PROCESSING_HAS_STB_TRUETYPE 0
#endif
#include "Processing.h"
#include <csignal>
#include <cstdlib>
#include <cmath>
#include <sys/stat.h>
#include <iostream>
#include <iomanip>
#include <sstream>
#include <fstream>
#include <thread>
#include <chrono>
#include <vector>
#include <array>
#include <string>
#include <functional>
#include <unordered_map>
#include <unordered_set>
#include <random>
#include <memory>
// stb_image.h must be in the src/ folder for loadImage() to work.
// Download from: https://github.com/nothings/stb/blob/master/stb_image.h
#ifdef PROCESSING_HAS_STB_IMAGE
#define STB_IMAGE_IMPLEMENTATION
#include "stb_image.h"
#endif
// Uncomment + drop stb_image_write.h to enable saveFrame()/save():
// #define STB_IMAGE_WRITE_IMPLEMENTATION
#define STB_IMAGE_WRITE_IMPLEMENTATION
#include "stb_image_write.h"
// ── Manual glu replacements (no GLU header needed) ───────────────────────────
static void _gluPerspective(double fovY_deg, double aspect, double zNear, double zFar) {
// Identical to gluPerspective -- sets up a perspective projection matrix
double f = 1.0 / std::tan(fovY_deg * M_PI / 360.0);
double m[16] = {0};
m[0] = f / aspect;
m[5] = f;
m[10] = (zFar + zNear) / (zNear - zFar);
m[11] = -1.0;
m[14] = (2.0 * zFar * zNear) / (zNear - zFar);
glMultMatrixd(m);
}
static void _gluLookAt(double ex,double ey,double ez,
double cx,double cy,double cz,
double ux,double uy,double uz) {
// Identical to gluLookAt
double fx=cx-ex, fy=cy-ey, fz=cz-ez;
double len=std::sqrt(fx*fx+fy*fy+fz*fz); fx/=len;fy/=len;fz/=len;
double rx=fy*uz-fz*uy, ry=fz*ux-fx*uz, rz=fx*uy-fy*ux;
len=std::sqrt(rx*rx+ry*ry+rz*rz); rx/=len;ry/=len;rz/=len;
double upx=ry*fz-rz*fy, upy=rz*fx-rx*fz, upz=rx*fy-ry*fx;
double m[16]={
rx, upx, -fx, 0,
ry, upy, -fy, 0,
rz, upz, -fz, 0,
0, 0, 0, 1
};
glMultMatrixd(m);
glTranslated(-ex,-ey,-ez);
}
// stb_truetype -- drop stb_truetype.h next to this file for TTF font rendering.
// default.ttf in the project root is loaded automatically as the default font.
// =============================================================================
// STATE
// =============================================================================
// Window / canvas size
static int fbW = 640, fbH = 480; // actual framebuffer (may be 2× on HiDPI)
// Mouse state
// Keyboard state
// Frame timing
// Current draw style
// Lighting state
// Color mode
// User event callbacks
std::function<void()> _onKeyPressed;
std::function<void()> _onKeyReleased;
std::function<void()> _onKeyTyped;
std::function<void()> _onMousePressed;
std::function<void()> _onMouseReleased;
std::function<void()> _onMouseClicked;
std::function<void()> _onMouseMoved;
std::function<void()> _onMouseDragged;
std::function<void(int)> _onMouseWheel;
std::function<void()> _onWindowMoved;
// On Windows: IDE.cpp stores a raw function pointer here before static init
// of Processing.cpp completes. Raw function pointers are POD -- zero-initialized
// at program start before ANY constructor runs, so this is always safe to write.
// Shape state
// =============================================================================
// NOISE - exact Java Processing implementation (PApplet.java)
// Uses a 4096-entry float lookup table with cosine interpolation.
// This matches Processing Java's noise() output exactly.
// =============================================================================
namespace Processing {
static void _doEnableDebugConsole() {
#ifdef _WIN32
if (AllocConsole()) {
FILE* f;
freopen_s(&f, "CONOUT$", "w", stdout);
freopen_s(&f, "CONOUT$", "w", stderr);
freopen_s(&f, "CONIN$", "r", stdin);
fprintf(stderr, "[debug] processing-cpp debug console enabled\n");
}
#endif
}
void enableDebugConsole() { _doEnableDebugConsole(); }
static std::string _s_objDir; // OBJ loader scratch
static const int PERLIN_YWRAPB = 4;
static const int PERLIN_YWRAP = 1 << PERLIN_YWRAPB; // 16
static const int PERLIN_ZWRAPB = 8;
static const int PERLIN_ZWRAP = 1 << PERLIN_ZWRAPB; // 256
static const int PERLIN_SIZE = 4095;
void PApplet::initPerlin(unsigned int seed) {
// Java Processing seeds with a simple LCG and fills with rand values in [0,1)
// It uses its own random to not disturb the sketch's random()
uint32_t s = seed;
auto jrand = [&]() -> float {
s = s * 1664525u + 1013904223u; // LCG like Java's Random
return (s >> 8) / (float)(1 << 24);
};
for (int i = 0; i < PERLIN_SIZE + 1; i++)
perlinTable[i] = jrand();
perlinInit = true;
}
void PApplet::noiseSeed(int s) { initPerlin((unsigned int)s); }
void PApplet::noiseDetail(int o, float f) { noiseOctaves = o; noiseFalloff = f; }
// Cosine interpolation curve -- Java Processing's noise_fsc()
static inline float noise_fsc(float i) {
return 0.5f * (1.0f - std::cos(i * PI));
}
float PApplet::noise(float x, float y, float z) {
if (!perlinInit) initPerlin(0); // default seed 0 like Java
if (x < 0) x = -x;
if (y < 0) y = -y;
if (z < 0) z = -z;
int xi = (int)x, yi = (int)y, zi = (int)z;
float xf = x - xi, yf = y - yi, zf = z - zi;
float r = 0.0f, ampl = 0.5f;
for (int oct = 0; oct < noiseOctaves; oct++) {
int of = xi + (yi << PERLIN_YWRAPB) + (zi << PERLIN_ZWRAPB);
float rxf = noise_fsc(xf), ryf = noise_fsc(yf);
float n1 = perlinTable[of & PERLIN_SIZE];
n1 += rxf * (perlinTable[(of+1) & PERLIN_SIZE] - n1);
float n2 = perlinTable[(of + PERLIN_YWRAP) & PERLIN_SIZE];
n2 += rxf * (perlinTable[(of + PERLIN_YWRAP + 1) & PERLIN_SIZE] - n2);
n1 += ryf * (n2 - n1);
of += PERLIN_ZWRAP;
n2 = perlinTable[of & PERLIN_SIZE];
n2 += rxf * (perlinTable[(of+1) & PERLIN_SIZE] - n2);
float n3 = perlinTable[(of + PERLIN_YWRAP) & PERLIN_SIZE];
n3 += rxf * (perlinTable[(of + PERLIN_YWRAP + 1) & PERLIN_SIZE] - n3);
n2 += ryf * (n3 - n2);
n1 += noise_fsc(zf) * (n2 - n1);
r += n1 * ampl;
ampl *= noiseFalloff;
// Double frequency each octave
xi <<= 1; xf *= 2.0f; if (xf >= 1.0f) { xi++; xf--; }
yi <<= 1; yf *= 2.0f; if (yf >= 1.0f) { yi++; yf--; }
zi <<= 1; zf *= 2.0f; if (zf >= 1.0f) { zi++; zf--; }
}
return r;
}
float PApplet::noise(float x) { return noise(x, 0.0f, 0.0f); }
float PApplet::noise(float x, float y) { return noise(x, y, 0.0f); }
// Seeded random -- Mersenne Twister for reproducibility matching Java Processing
void PApplet::randomSeed(long s) {
_rng.seed(static_cast<uint32_t>(s));
_rngDist.reset();
}
float PApplet::random(float lo, float hi) {
return lo + _rngDist(_rng) * (hi - lo);
}
float PApplet::random(float hi) { return random(0.f, hi); }
float PApplet::randomGaussian(){
static float spare; static bool has=false;
if(has){has=false;return spare;}
float u,v,s;
do{u=_rngDist(_rng)*2-1;v=_rngDist(_rng)*2-1;s=u*u+v*v;}while(s>=1||s==0);
s=std::sqrt(-2*std::log(s)/s);spare=v*s;has=true;return u*s;
}
// =============================================================================
// COLOR MODE & HELPERS
// =============================================================================
void PApplet::hsbToRgb(float h, float s, float b, float& outR, float& outG, float& outB) {
// Normalise each channel to [0, 1]
h /= colorMaxH;
s /= colorMaxS;
b /= colorMaxB;
if (s == 0.0f) {
// Achromatic (grey): all channels equal brightness
outR = outG = outB = b;
return;
}
float sector = h * 6.0f; // which 60-degree sector of the hue wheel
int i = (int)sector;
float frac = sector - i; // fractional part within sector
float p = b * (1.0f - s);
float q = b * (1.0f - s * frac);
float t = b * (1.0f - s * (1.0f - frac));
switch (i % 6) {
case 0: outR = b; outG = t; outB = p; break;
case 1: outR = q; outG = b; outB = p; break;
case 2: outR = p; outG = b; outB = t; break;
case 3: outR = p; outG = q; outB = b; break;
case 4: outR = t; outG = p; outB = b; break;
default: outR = b; outG = p; outB = q; break;
}
}
color PApplet::makeColor(float a, float b, float c, float d) {
float r = 0, g = 0, bv = 0, aa = 0;
if (colorModeVal == HSB) {
hsbToRgb(a, b, c, r, g, bv);
aa = d / colorMaxA;
} else {
r = a / colorMaxH;
g = b / colorMaxS;
bv = c / colorMaxB;
aa = d / colorMaxA;
}
return colorVal((int)(r*255), (int)(g*255), (int)(bv*255), (int)(aa*255));
}
color PApplet::makeColor(float gray,float alpha){
// In HSB mode, a single-value gray maps to brightness only (hue=0, sat=0)
// matching Processing Java behavior -- background(v) in HSB gives gray
if(colorModeVal==HSB){
float br=gray/colorMaxB;
br=std::fmax(0.f,std::fmin(1.f,br));
int v=(int)(br*255);
unsigned int a=std::fmax(0.f,std::fmin(1.f,alpha/colorMaxA))*255;
return colorVal(v,v,v,(int)a);
}
return makeColor(gray,gray,gray,alpha);
}
// =============================================================================
// color STRUCT CONSTRUCTORS
// =============================================================================
// File-scope shims so color:: constructors can call makeColor
static color _makeColor(float a,float b,float c,float d=255){
if(PApplet::g_papplet) return PApplet::g_papplet->makeColor(a,b,c,d);
return colorVal((int)a,(int)b,(int)c,(int)d);
}
static color _makeColor(float gray,float alpha=255){
if(PApplet::g_papplet) return PApplet::g_papplet->makeColor(gray,alpha);
return colorVal((int)gray,(int)gray,(int)gray,(int)alpha);
}
static float _colorMaxA(){
return PApplet::g_papplet ? PApplet::g_papplet->colorMaxA : 255.f;
}
color::color(int gray) { value = _makeColor((float)gray, _colorMaxA()).value; }
color::color(int gray, int a) { value = _makeColor((float)gray, (float)a).value; }
color::color(float gray) { value = _makeColor(gray, _colorMaxA()).value; }
color::color(float gray, float a) { value = _makeColor(gray, a).value; }
color::color(float r,float g,float b){ value = _makeColor(r,g,b,_colorMaxA()).value; }
color::color(float r,float g,float b,float a){ value = _makeColor(r,g,b,a).value; }
void PApplet::colorMode(int mode, float mx) { colorModeVal=mode; colorMaxH=colorMaxS=colorMaxB=colorMaxA=mx; }
void PApplet::colorMode(int mode, float mH, float mS, float mB, float mA) { colorModeVal=mode; colorMaxH=mH; colorMaxS=mS; colorMaxB=mB; colorMaxA=mA; }
// Color channel accessors -- scaled to current colorMode range
float PApplet::red(color c) { unsigned int v=c.value; return (v>>16&0xFF)/255.0f*colorMaxH; }
float PApplet::green(color c) { unsigned int v=c.value; return (v>>8&0xFF)/255.0f*colorMaxS; }
float PApplet::blue(color c) { unsigned int v=c.value; return (v&0xFF)/255.0f*colorMaxB; }
float PApplet::alpha(color c) { unsigned int v=c.value; return (v>>24&0xFF)/255.0f*colorMaxA; }
float PApplet::brightness(color c) {
unsigned int v=c.value;
float r=(v>>16&0xFF)/255.f, g=(v>>8&0xFF)/255.f, b=(v&0xFF)/255.f;
return max(r, max(g, b)) * colorMaxB;
}
float PApplet::saturation(color c) {
unsigned int v = c.value;
float r = (v >> 16 & 0xFF) / 255.f;
float g = (v >> 8 & 0xFF) / 255.f;
float b = (v & 0xFF) / 255.f;
float mx = max(r, max(g, b));
float mn = min(r, min(g, b));
return (mx == 0 ? 0 : (mx - mn) / mx) * colorMaxS;
}
float PApplet::hue(color c){
unsigned int v=c.value;
float r=(v>>16&0xFF)/255.f,g=(v>>8&0xFF)/255.f,b=(v&0xFF)/255.f;
float mx=max(r,max(g,b)),mn=min(r,min(g,b)),d=mx-mn;
if(d==0)return 0;
float h=(mx==r)?(g-b)/d:(mx==g)?2+(b-r)/d:4+(r-g)/d;
h*=60;if(h<0)h+=360;return h/360.0f*colorMaxH;
}
color PApplet::lerpColor(color c1, color c2, float t) {
unsigned int v1 = c1.value;
unsigned int v2 = c2.value;
int r1 = (v1 >> 16) & 0xFF, r2 = (v2 >> 16) & 0xFF;
int g1 = (v1 >> 8) & 0xFF, g2 = (v2 >> 8) & 0xFF;
int b1 = v1 & 0xFF, b2 = v2 & 0xFF;
int a1 = (v1 >> 24) & 0xFF, a2 = (v2 >> 24) & 0xFF;
return colorVal(
(int)(r1 + t * (r2 - r1)),
(int)(g1 + t * (g2 - g1)),
(int)(b1 + t * (b2 - b1)),
(int)(a1 + t * (a2 - a1))
);
}
// =============================================================================
// INTERNAL HELPERS
// =============================================================================
void PApplet::applyFill() {
glColor4f(fillR, fillG, fillB, fillA);
// Always enable blend -- shapes with alpha need it, opaque shapes don't hurt
glEnable(GL_BLEND);
glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
}
// Temporarily suspend lighting so stroke lines/points render with their exact
// colour. Processing Java does the same -- strokes are never affected by lights.
void PApplet::applyStroke() {
if (lightsEnabled) {
glDisable(GL_LIGHTING);
glDisable(GL_COLOR_MATERIAL);
}
glColor4f(strokeR, strokeG, strokeB, strokeA);
glEnable(GL_BLEND);
glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
}
// Restore lighting after a stroke draw call.
void PApplet::restoreLighting() {
if (lightsEnabled) {
glEnable(GL_LIGHTING);
glEnable(GL_COLOR_MATERIAL);
glColorMaterial(GL_FRONT_AND_BACK, GL_DIFFUSE);
// Reapply fill colour so the next lit shape uses the right material
glColor4f(fillR, fillG, fillB, fillA);
}
}
void PApplet::initPersistFBO(){
if(persistFBO){glDeleteFramebuffers(1,&persistFBO);glDeleteTextures(1,&persistTex);persistFBO=0;}
glGenFramebuffers(1,&persistFBO);
glGenTextures(1,&persistTex);
glBindTexture(GL_TEXTURE_2D,persistTex);
glTexImage2D(GL_TEXTURE_2D,0,GL_RGBA,fbW,fbH,0,GL_RGBA,GL_UNSIGNED_BYTE,nullptr);
glTexParameteri(GL_TEXTURE_2D,GL_TEXTURE_MIN_FILTER,GL_NEAREST);
glTexParameteri(GL_TEXTURE_2D,GL_TEXTURE_MAG_FILTER,GL_NEAREST);
glBindTexture(GL_TEXTURE_2D,0);
glBindFramebuffer(GL_FRAMEBUFFER,persistFBO);
glFramebufferTexture2D(GL_FRAMEBUFFER,GL_COLOR_ATTACHMENT0,GL_TEXTURE_2D,persistTex,0);
glBindFramebuffer(GL_FRAMEBUFFER,0);
}
// Copy current back buffer into persist FBO
void PApplet::saveToPersist(){
if(!persistFBO) initPersistFBO();
// Blit back buffer -> persist FBO
glBindFramebuffer(GL_READ_FRAMEBUFFER,0);
glBindFramebuffer(GL_DRAW_FRAMEBUFFER,persistFBO);
glBlitFramebuffer(0,0,fbW,fbH,0,0,fbW,fbH,GL_COLOR_BUFFER_BIT,GL_NEAREST);
glBindFramebuffer(GL_FRAMEBUFFER,0);
}
// Restore persist FBO into back buffer
void PApplet::restoreFromPersist(){
if(!persistFBO) return;
glBindFramebuffer(GL_READ_FRAMEBUFFER,persistFBO);
glBindFramebuffer(GL_DRAW_FRAMEBUFFER,0);
glBlitFramebuffer(0,0,fbW,fbH,0,0,fbW,fbH,GL_COLOR_BUFFER_BIT,GL_NEAREST);
glBindFramebuffer(GL_FRAMEBUFFER,0);
}
void PApplet::_restoreMainCanvas(){
// Restore main window viewport and projection after PGraphics endDraw()
glViewport(0,0,fbW,fbH);
glMatrixMode(GL_PROJECTION);glLoadIdentity();
glOrtho(0,logicalW,logicalH,0,-1,1);
glMatrixMode(GL_MODELVIEW);glLoadIdentity();
glDisable(GL_DEPTH_TEST);
glDisable(GL_LIGHTING);
}
void PApplet::setProjection(int,int){
// Viewport = actual framebuffer size (handles HiDPI where fb > logical).
// Ortho = logical sketch size (coordinates always match what size() set).
if (gWindow) {
int fw=logicalW, fh=logicalH;
glfwGetFramebufferSize(gWindow, &fw, &fh);
if (fw > 0) fbW = fw;
if (fh > 0) fbH = fh;
}
glViewport(0, 0, fbW, fbH);
glMatrixMode(GL_PROJECTION);glLoadIdentity();
glOrtho(0, logicalW, logicalH, 0, -1, 1);
glMatrixMode(GL_MODELVIEW);glLoadIdentity();
glDisable(GL_DEPTH_TEST);
glDisable(GL_LIGHTING);
}
void PApplet::drawEllipseGeom(float cx,float cy,float rx,float ry,
float sa,float ea,int segs){
if(segs < 0){
float maxR = rx > ry ? rx : ry;
segs = (int)(maxR * 2.5f);
if(segs < 64) segs = 64;
if(segs > 512) segs = 512;
}
float range=ea-sa;
bool isFullCircle = (std::fabs(range) >= TWO_PI - 0.001f);
if(doFill){
applyFill();
glBegin(GL_TRIANGLE_FAN);
glVertex2f(cx,cy); // center
for(int i=0;i<=segs;i++){
float a=sa+range*i/segs;
glVertex2f(cx+rx*std::cos(a),cy+ry*std::sin(a));
}
if(isFullCircle){
// close the circle back to the first arc point
glVertex2f(cx+rx*std::cos(sa),cy+ry*std::sin(sa));
}
glEnd();
}
if(doStroke){
applyStroke();glLineWidth(strokeW);
if(isFullCircle){
glBegin(GL_LINE_LOOP);
} else {
glBegin(GL_LINE_STRIP);
}
for(int i=0;i<=segs;i++){
float a=sa+range*i/segs;
glVertex2f(cx+rx*std::cos(a),cy+ry*std::sin(a));
}
glEnd();
}
}
void PApplet::resolveRect(float& x,float& y,float& w,float& h){
if(currentRectMode==CENTER){x-=w*0.5f;y-=h*0.5f;}
else if(currentRectMode==RADIUS){x-=w;y-=h;w*=2;h*=2;}
else if(currentRectMode==CORNERS){w=w-x;h=h-y;}
}
void PApplet::resolveEllipse(float& cx,float& cy,float& rx,float& ry){
if(currentEllipseMode==CORNER){cx+=rx;cy+=ry;}
else if(currentEllipseMode==CORNERS){float ex=rx,ey=ry;rx=(ex-cx)*0.5f;ry=(ey-cy)*0.5f;cx=(cx+ex)*0.5f;cy=(cy+ey)*0.5f;}
else if(currentEllipseMode==CENTER){rx*=0.5f;ry*=0.5f;}
}
void PApplet::setFillFromColor(color c) {
unsigned int v = c.value;
fillR = (v >> 16 & 0xFF) / 255.f;
fillG = (v >> 8 & 0xFF) / 255.f;
fillB = (v & 0xFF) / 255.f;
fillA = (v >> 24 & 0xFF) / 255.f;
doFill = true;
}
void PApplet::setStrokeFromColor(color c) {
unsigned int v = c.value;
strokeR = (v >> 16 & 0xFF) / 255.f;
strokeG = (v >> 8 & 0xFF) / 255.f;
strokeB = (v & 0xFF) / 255.f;
strokeA = (v >> 24 & 0xFF) / 255.f;
doStroke = true;
}
// =============================================================================
// ENVIRONMENT
// =============================================================================
void PApplet::size(int w,int h){
winWidth=w;winHeight=h;
logicalW=w;logicalH=h; // remember what the sketch requested
pixelWidth=w;pixelHeight=h;
if(gWindow){
glfwSetWindowSize(gWindow,w,h);
// Poll until the framebuffer is actually the requested size.
// glfwSetWindowSize is async; without this the window stays 100x100
// when setup() calls background() or draws anything.
// Poll until the window is actually resized (or timeout after 500ms)
for(int _wait=0; _wait<500; _wait++){
glfwPollEvents();
int fw=0,fh=0;
glfwGetFramebufferSize(gWindow,&fw,&fh);
// Accept exact match or close match (HiDPI scaling)
if(fw>0 && fh>0){
pixelWidth=fw; pixelHeight=fh;
// Check if the logical window size matches what we requested
int lw=0,lh=0;
glfwGetWindowSize(gWindow,&lw,&lh);
if(lw==w && lh==h) break; // exact match
}
if(_wait>=50){ // after 50ms, accept whatever we have
int fw2=0,fh2=0;
glfwGetFramebufferSize(gWindow,&fw2,&fh2);
if(fw2>0&&fh2>0){ pixelWidth=fw2; pixelHeight=fh2; }
break;
}
#ifdef _WIN32
Sleep(1);
#else
usleep(1000);
#endif
}
// Force coordinate system to requested size regardless of WM.
// logicalW/H are the sketch's coordinate space; viewport uses actual size.
logicalW = w; logicalH = h;
winWidth = w; winHeight = h;
setProjection(w,h);
}
}
void PApplet::size(int w,int h,int renderer){
defaultP3D=(renderer==P3D);
size(w,h);
// For P3D mode: set up depth test and apply default camera/perspective
// immediately so setup() draws with the correct projection.
if(defaultP3D && gWindow){
{int fw=logicalW,fh=logicalH;if(gWindow)glfwGetFramebufferSize(gWindow,&fw,&fh);if(fw>0)fbW=fw;if(fh>0)fbH=fh;}
glViewport(0,0,fbW,fbH);
glEnable(GL_DEPTH_TEST);
glDepthFunc(GL_LESS);
glDisable(GL_CULL_FACE);
glFrontFace(GL_CW);
glEnable(GL_NORMALIZE);
glClearColor(0.8f,0.8f,0.8f,1); // Java Processing default grey (204,204,204)
glClear(GL_COLOR_BUFFER_BIT|GL_DEPTH_BUFFER_BIT);
applyDefaultCamera();
}
}
void PApplet::fullScreen() {
if (!gWindow) {
winWidth = displayWidth;
winHeight = displayHeight;
} else {
GLFWmonitor* m = glfwGetPrimaryMonitor();
const GLFWvidmode* v = glfwGetVideoMode(m);
glfwSetWindowMonitor(gWindow, m, 0, 0, v->width, v->height, v->refreshRate);
}
}
void PApplet::frameRate(int fps){currentFrameRate=fps;targetFrameTime=1.0/fps;}
void PApplet::vsync(bool on){if(gWindow) glfwSwapInterval(on?1:0);}
void PApplet::noLoop(){looping=false;}
void PApplet::loop() {looping=true;}
void PApplet::redraw(){redrawOnce=true;}
void PApplet::exit_sketch(){if(gWindow)glfwSetWindowShouldClose(gWindow,GLFW_TRUE);}
void PApplet::windowTitle(const std::string& t){if(gWindow)glfwSetWindowTitle(gWindow,t.c_str());}
void PApplet::windowMove(int x,int y){if(gWindow)glfwSetWindowPos(gWindow,x,y);}
void PApplet::windowResize(int w,int h){size(w,h);}
void PApplet::windowResizable(bool r){isResizable=r;if(gWindow)glfwSetWindowAttrib(gWindow,GLFW_RESIZABLE,r?GLFW_TRUE:GLFW_FALSE);}
// ---------------------------------------------------------------------------
// Clipboard
// ---------------------------------------------------------------------------
void PApplet::setClipboard(const std::string& s) {
if (s.empty()) return;
if (gWindow) glfwSetClipboardString(gWindow, s.c_str());
}
std::string PApplet::getClipboard() {
if (!gWindow) return "";
const char* cb = glfwGetClipboardString(gWindow);
return cb ? std::string(cb) : "";
}
// ---------------------------------------------------------------------------
// Window icon
// ---------------------------------------------------------------------------
void PApplet::setWindowIcon(PImage* img) {
if (!img || !gWindow) return;
// Convert ARGB pixels (Processing internal) to RGBA (GLFW wants RGBA)
std::vector<unsigned char> rgba(img->width * img->height * 4);
for (int p = 0; p < img->width * img->height; p++) {
unsigned int px = img->pixels[p];
rgba[p*4+0] = (px >> 16) & 0xFF; // R
rgba[p*4+1] = (px >> 8) & 0xFF; // G
rgba[p*4+2] = (px ) & 0xFF; // B
rgba[p*4+3] = (px >> 24) & 0xFF; // A
}
GLFWimage gi;
gi.width = img->width;
gi.height = img->height;
gi.pixels = rgba.data();
glfwSetWindowIcon(gWindow, 1, &gi);
}
// ---------------------------------------------------------------------------
// Modifier key state
// ---------------------------------------------------------------------------
bool PApplet::isCtrlDown() {
// Use GLFW mods bitmask (reliable from callbacks) OR glfwGetKey (for polling)
if (g_currentMods & GLFW_MOD_CONTROL) return true;
if (!gWindow) return false;
return glfwGetKey(gWindow, GLFW_KEY_LEFT_CONTROL) == GLFW_PRESS
|| glfwGetKey(gWindow, GLFW_KEY_RIGHT_CONTROL) == GLFW_PRESS;
}
bool PApplet::isShiftDown() {
if (g_currentMods & GLFW_MOD_SHIFT) return true;
if (!gWindow) return false;
return glfwGetKey(gWindow, GLFW_KEY_LEFT_SHIFT) == GLFW_PRESS
|| glfwGetKey(gWindow, GLFW_KEY_RIGHT_SHIFT) == GLFW_PRESS;
}
bool PApplet::isAltDown() {
if (g_currentMods & GLFW_MOD_ALT) return true;
if (!gWindow) return false;
return glfwGetKey(gWindow, GLFW_KEY_LEFT_ALT) == GLFW_PRESS
|| glfwGetKey(gWindow, GLFW_KEY_RIGHT_ALT) == GLFW_PRESS;
}
void PApplet::windowRatio(int w,int h){if(gWindow)glfwSetWindowAspectRatio(gWindow,w,h);}
void PApplet::pixelDensity(int d){pixelDensityValue=d;}
void PApplet::smooth(int level) {
// The MAIN window's actual MSAA sample count is fixed at window-creation
// time (GLFW_SAMPLES is a window hint, can't change after the window
// exists) -- so smooth(level) can't retroactively change the main
// canvas's hardware sample count the way real Processing's P2D/P3D
// renderers can. What we CAN do: store the requested level (used by
// PGraphics buffers below, which DO get to choose their own sample
// count fresh at creation time), and toggle the same smoothing flags
// smooth() always has, regardless of which level was requested.
smoothing = true;
smoothLevel = level;
glEnable(GL_LINE_SMOOTH);glHint(GL_LINE_SMOOTH_HINT,GL_NICEST);
glEnable(GL_POINT_SMOOTH);glHint(GL_POINT_SMOOTH_HINT,GL_NICEST);
glEnable(GL_MULTISAMPLE);
}
void PApplet::noSmooth(){smoothing=false;glDisable(GL_LINE_SMOOTH);glDisable(GL_POLYGON_SMOOTH);glDisable(GL_POINT_SMOOTH);glDisable(GL_MULTISAMPLE);}
void PApplet::hint(int which){
switch(which){
case ENABLE_DEPTH_TEST: glEnable(GL_DEPTH_TEST); break;
case DISABLE_DEPTH_TEST: glDisable(GL_DEPTH_TEST); break;
case ENABLE_DEPTH_SORT: glEnable(GL_DEPTH_TEST);glDepthFunc(GL_LEQUAL); break;
case DISABLE_DEPTH_SORT: glDepthFunc(GL_LESS); break;
default: break;
}
}
void PApplet::cursor() {if(gWindow)glfwSetInputMode(gWindow,GLFW_CURSOR,GLFW_CURSOR_NORMAL);}
void PApplet::cursor(int type){if(!gWindow)return;GLFWcursor* c=glfwCreateStandardCursor(type);if(c)glfwSetCursor(gWindow,c);}
void PApplet::noCursor() {if(gWindow)glfwSetInputMode(gWindow,GLFW_CURSOR,GLFW_CURSOR_HIDDEN);}
// captureMouse(): locks cursor to window and provides unlimited delta movement.
// Use releaseMouse() or press ESC to free it.
void PApplet::captureMouse() {if(gWindow){glfwSetInputMode(gWindow,GLFW_CURSOR,GLFW_CURSOR_DISABLED);
// Enable raw motion if supported (removes OS acceleration)
if(glfwRawMouseMotionSupported())
glfwSetInputMode(gWindow,GLFW_RAW_MOUSE_MOTION,GLFW_TRUE);}}
void PApplet::releaseMouse(){if(gWindow){glfwSetInputMode(gWindow,GLFW_CURSOR,GLFW_CURSOR_NORMAL);
glfwSetInputMode(gWindow,GLFW_RAW_MOUSE_MOTION,GLFW_FALSE);}}
// =============================================================================
// STYLE STACK
// =============================================================================
void PApplet::captureStyle(Style& s) {
s = { fillR, fillG, fillB, fillA,
strokeR, strokeG, strokeB, strokeA, strokeW,
doFill, doStroke,
currentRectMode, currentEllipseMode, currentImageMode,
tintR, tintG, tintB, tintA, doTint,
colorModeVal, colorMaxH, colorMaxS, colorMaxB, colorMaxA };
}
void PApplet::restoreStyle(const Style& s) {
fillR = s.fillR; fillG = s.fillG; fillB = s.fillB; fillA = s.fillA;
strokeR = s.strokeR; strokeG = s.strokeG; strokeB = s.strokeB;
strokeA = s.strokeA; strokeW = s.strokeW;
doFill = s.doFill; doStroke = s.doStroke;
currentRectMode = s.rectMode;
currentEllipseMode = s.ellipseMode;
currentImageMode = s.imageMode;
tintR = s.tintR; tintG = s.tintG; tintB = s.tintB; tintA = s.tintA;
doTint = s.doTint;
colorModeVal = s.colorMode;
colorMaxH = s.cmH; colorMaxS = s.cmS; colorMaxB = s.cmB; colorMaxA = s.cmA;
}
void PApplet::pushStyle() {
Style s;
captureStyle(s);
styleStack.push_back(s);
}
void PApplet::popStyle() {
if (!styleStack.empty()) {
restoreStyle(styleStack.back());
styleStack.pop_back();
}
}
void PApplet::push() { glPushMatrix(); pushStyle(); }
void PApplet::pop() { glPopMatrix(); popStyle(); }
void PApplet::pushMatrix() { glPushMatrix(); }
void PApplet::popMatrix() { glPopMatrix(); }
// =============================================================================
// BACKGROUND / CLEAR
// =============================================================================
void PApplet::setBg(float r,float g,float b,float a){
bgR=r;bgG=g;bgB=b;bgA=a;
glClearColor(r,g,b,a);
glClear(GL_COLOR_BUFFER_BIT|GL_DEPTH_BUFFER_BIT);
}
void PApplet::background(float gray, float a) {
_backgroundCalledThisFrame = true;
color c = makeColor(gray, a);
unsigned int v = c.value;
setBg((v>>16&0xFF)/255.f, (v>>8&0xFF)/255.f, (v&0xFF)/255.f, (v>>24&0xFF)/255.f);
}
void PApplet::background(float r, float g, float b, float a) {
_backgroundCalledThisFrame = true;
color c = makeColor(r, g, b, a);
unsigned int v = c.value;
setBg((v>>16&0xFF)/255.f, (v>>8&0xFF)/255.f, (v&0xFF)/255.f, (v>>24&0xFF)/255.f);
}
void PApplet::background(color c) {
_backgroundCalledThisFrame = true;
unsigned int v = c.value;
setBg((v>>16&0xFF)/255.f, (v>>8&0xFF)/255.f, (v&0xFF)/255.f, (v>>24&0xFF)/255.f);
}
void PApplet::background(const PImage& img) {
_backgroundCalledThisFrame = true;
// Draw image as full-canvas background
if (img.width == 0 || img.height == 0) return;
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
glMatrixMode(GL_PROJECTION); glPushMatrix(); glLoadIdentity();
glOrtho(0, logicalW, logicalH, 0, -1, 1);
glMatrixMode(GL_MODELVIEW); glPushMatrix(); glLoadIdentity();
glDisable(GL_DEPTH_TEST);
drawImageRect(const_cast<PImage&>(img), 0, 0, (float)logicalW, (float)logicalH);
glMatrixMode(GL_PROJECTION); glPopMatrix();
glMatrixMode(GL_MODELVIEW); glPopMatrix();
if (defaultP3D) glEnable(GL_DEPTH_TEST);
}
void PApplet::clear(){glClearColor(0,0,0,0);glClear(GL_COLOR_BUFFER_BIT);}
// =============================================================================
// FILL / STROKE
// =============================================================================
void PApplet::fill(float gray,float a) {setFillFromColor(makeColor(gray,a));}
void PApplet::fill(float gray) {setFillFromColor(makeColor(gray,colorMaxA));}
void PApplet::fill(float r,float g,float b,float a) {setFillFromColor(makeColor(r,g,b,a));}
void PApplet::fill(float r,float g,float b) {setFillFromColor(makeColor(r,g,b,colorMaxA));}
void PApplet::fill(color c) {setFillFromColor(c);}
void PApplet::fill(color c, float a) {
unsigned int v = c.value;
fillR = (v>>16&0xFF)/255.f;
fillG = (v>>8 &0xFF)/255.f;
fillB = (v &0xFF)/255.f;
fillA = std::min(255.f, std::max(0.f, a)) / 255.f;
doFill = true;
}
void PApplet::noFill() {doFill=false;}
void PApplet::stroke(float gray,float a) {setStrokeFromColor(makeColor(gray,a));}
void PApplet::stroke(float gray) {setStrokeFromColor(makeColor(gray,colorMaxA));}
void PApplet::stroke(float r,float g,float b,float a){setStrokeFromColor(makeColor(r,g,b,a));}
void PApplet::stroke(float r,float g,float b) {setStrokeFromColor(makeColor(r,g,b,colorMaxA));}
void PApplet::stroke(color c) {setStrokeFromColor(c);}
void PApplet::noStroke() {doStroke=false;}
void PApplet::strokeWeight(float w) {strokeW=w;}
void PApplet::strokeCap(int) {}
void PApplet::strokeJoin(int) {}
// =============================================================================
// PCOLOR CONVENIENCE OVERLOADS
// =============================================================================
void PApplet::fill(const PColor& c) { fill(c.r, c.g, c.b, c.a); }
void PApplet::stroke(const PColor& c) { stroke(c.r, c.g, c.b, c.a); }
void PApplet::background(const PColor& c){ background(c.r, c.g, c.b, c.a); }
void PApplet::tint(const PColor& c) { tint(c.r, c.g, c.b, c.a); }
void PApplet::rectMode(int m) {currentRectMode=m;}
void PApplet::ellipseMode(int m) {currentEllipseMode=m;}
// =============================================================================
// 2D PRIMITIVES
// =============================================================================
static void flushPoints(){} // no-op, points drawn immediately now
void PApplet::point(float x, float y) {
if (!doStroke) return;
applyStroke();
if (!smoothing && strokeW <= 1.0f) {
glPointSize(1.0f);
glBegin(GL_POINTS); glVertex2f(std::floor(x)+0.5f, std::floor(y)+0.5f); glEnd();
} else {
glPointSize(strokeW);
glBegin(GL_POINTS); glVertex2f(x, y); glEnd();
}
restoreLighting();
}
void PApplet::point(float x, float y, float z) {
if (!doStroke) return;
applyStroke();
glPointSize(strokeW);
glBegin(GL_POINTS); glVertex3f(x, y, z); glEnd();
restoreLighting();
}
void PApplet::line(float x1, float y1, float x2, float y2) {
{
GLint mvDepth=0, projDepth=0;
glGetIntegerv(GL_MODELVIEW_STACK_DEPTH, &mvDepth);
glGetIntegerv(GL_PROJECTION_STACK_DEPTH, &projDepth);
double mv[16], proj[16];
glGetDoublev(GL_MODELVIEW_MATRIX, mv);
glGetDoublev(GL_PROJECTION_MATRIX, proj);
GLint vp[4]; glGetIntegerv(GL_VIEWPORT, vp);
GLint curFbo=0; glGetIntegerv(GL_FRAMEBUFFER_BINDING, &curFbo);
PDEBUG("PApplet::line(%.1f,%.1f,%.1f,%.1f) ENTRY: mvDepth=%d projDepth=%d curFbo=%d viewport=(%d,%d,%d,%d)\n",
x1,y1,x2,y2, mvDepth, projDepth, curFbo, vp[0],vp[1],vp[2],vp[3]);
PDEBUG(" mv[0]=%.3f mv[5]=%.3f mv[12]=%.3f mv[13]=%.3f\n", mv[0],mv[5],mv[12],mv[13]);
PDEBUG(" proj[0]=%.6f proj[5]=%.6f proj[12]=%.6f proj[13]=%.6f\n", proj[0],proj[5],proj[12],proj[13]);
}
if (!doStroke) return;
applyStroke();
float w = strokeW;
if (w <= 1.0f) {
// Thin lines: use GL_LINES
glLineWidth(1.0f);
glBegin(GL_LINES); glVertex2f(x1,y1); glVertex2f(x2,y2); glEnd();
restoreLighting();
return;
}
// Thick line: quad body + round caps using stencil to prevent double-blend
float dx = x2-x1, dy = y2-y1;
float len = std::sqrt(dx*dx+dy*dy);
if(len < 0.0001f){ restoreLighting(); return; }
float ux = dx/len, uy = dy/len;
float r = w*0.5f;
float px2 = -uy*r, py2 = ux*r; // perpendicular
int segs = std::max(16, (int)(r*4.0f));
// Use stencil to draw all geometry, then fill once -- prevents double-blend
glEnable(GL_STENCIL_TEST);
glClearStencil(0);
glClear(GL_STENCIL_BUFFER_BIT);
glStencilFunc(GL_ALWAYS, 1, 0xFF);
glStencilOp(GL_KEEP, GL_KEEP, GL_REPLACE);
glColorMask(GL_FALSE,GL_FALSE,GL_FALSE,GL_FALSE);
// Draw body into stencil
glBegin(GL_QUADS);
glVertex2f(x1+px2,y1+py2); glVertex2f(x2+px2,y2+py2);
glVertex2f(x2-px2,y2-py2); glVertex2f(x1-px2,y1-py2);
glEnd();
// Draw end caps into stencil
for(int ep=0;ep<2;ep++){
float cx2=ep?x2:x1, cy2=ep?y2:y1;
glBegin(GL_TRIANGLE_FAN);
glVertex2f(cx2,cy2);
for(int s=0;s<=segs;s++){
float a=s*TWO_PI/segs;
glVertex2f(cx2+std::cos(a)*r, cy2+std::sin(a)*r);
}
glEnd();
}
// Now draw color only where stencil=1
glColorMask(GL_TRUE,GL_TRUE,GL_TRUE,GL_TRUE);
glStencilFunc(GL_EQUAL, 1, 0xFF);
glStencilOp(GL_KEEP,GL_KEEP,GL_KEEP);
glEnable(GL_BLEND);
glBlendFunc(GL_SRC_ALPHA,GL_ONE_MINUS_SRC_ALPHA);
// Fill bounding box with stroke color
float minx=std::min(x1,x2)-r, maxx=std::max(x1,x2)+r;
float miny=std::min(y1,y2)-r, maxy=std::max(y1,y2)+r;
glBegin(GL_QUADS);
glVertex2f(minx,miny); glVertex2f(maxx,miny);
glVertex2f(maxx,maxy); glVertex2f(minx,maxy);
glEnd();
glDisable(GL_STENCIL_TEST);
restoreLighting();
}
void PApplet::line(float x1, float y1, float z1, float x2, float y2, float z2) {
if (!doStroke) return;
applyStroke();
glLineWidth(strokeW);
glBegin(GL_LINES); glVertex3f(x1,y1,z1); glVertex3f(x2,y2,z2); glEnd();
restoreLighting();
}
void PApplet::ellipse(float cx, float cy, float w, float h) {
float rx = w, ry = h;
resolveEllipse(cx, cy, rx, ry);
drawEllipseGeom(cx, cy, rx, ry);
}
void PApplet::circle(float cx, float cy, float diameter) {
ellipse(cx, cy, diameter, diameter);
}
void PApplet::arc(float cx, float cy, float w, float h, float startAngle, float endAngle) {
float rx = w, ry = h;
resolveEllipse(cx, cy, rx, ry);
drawEllipseGeom(cx, cy, rx, ry, startAngle, endAngle);
}
void PApplet::arc(float cx, float cy, float w, float h, float startAngle, float endAngle, int /*mode*/) {
// mode = OPEN / CHORD / PIE -- basic implementation uses OPEN
arc(cx, cy, w, h, startAngle, endAngle);
}
void PApplet::rect(float x, float y, float w, float h) {
resolveRect(x, y, w, h);
if (doFill) {
applyFill();
glBegin(GL_QUADS);
glVertex2f(x, y );
glVertex2f(x + w, y );
glVertex2f(x + w, y + h);
glVertex2f(x, y + h);
glEnd();
}
if (doStroke) {
// Real Processing centers the stroke ON the rectangle's boundary
// (half the weight extends inward over the fill, half extends
// outward) -- NOT entirely outside it. The previous version drew
// the stroke loop expanded fully outward, which meant increasing
// strokeWeight never visually shrank the filled interior (it
// does in real Processing, since the inward half of a thick
// stroke covers part of the fill), and glLineWidth-rendered
// GL_LINE_LOOP gives flat, unmitered corners at large widths
// (visible gaps/seams at corners instead of a clean joined
// outline). Drawing the stroke as actual filled quad geometry --
// matching real Processing's approach -- fixes both: correct
// centering AND clean mitered corners via overlapping quads.
applyStroke();
float half = strokeW * 0.5f;
float xo = x - half, yo = y - half; // outer edge
float xi = x + half, yi = y + half; // inner edge (top-left side)
float xow = x + w + half, yoh = y + h + half; // outer edge (bottom-right side)
float xiw = x + w - half, yih = y + h - half; // inner edge (bottom-right side)
glBegin(GL_QUADS);
// Top edge
glVertex2f(xo, yo); glVertex2f(xow, yo); glVertex2f(xow, yi); glVertex2f(xo, yi);
// Bottom edge
glVertex2f(xo, yih); glVertex2f(xow, yih); glVertex2f(xow, yoh); glVertex2f(xo, yoh);
// Left edge (between top and bottom strips already drawn)
glVertex2f(xo, yi); glVertex2f(xi, yi); glVertex2f(xi, yih); glVertex2f(xo, yih);
// Right edge
glVertex2f(xiw, yi); glVertex2f(xow, yi); glVertex2f(xow, yih); glVertex2f(xiw, yih);
glEnd();
restoreLighting();
}
}
void PApplet::rect(float x, float y, float w, float h, float r) {
resolveRect(x, y, w, h);
// Clamp radius so it never exceeds half the shortest side
r = min(r, min(w, h) * 0.5f);
const int cornerSegs = 8; // segments per 90-degree corner arc
// Emit a corner arc: center (cx,cy), from angle sa to ea
auto corner = [&](float cx, float cy, float sa, float ea) {
for (int i = 0; i <= cornerSegs; i++) {
float a = sa + (ea - sa) * i / cornerSegs;
glVertex2f(cx + r * std::cos(a), cy + r * std::sin(a));
}
};
if (doFill) {
applyFill();
glBegin(GL_TRIANGLE_FAN);
// Fan center at rect midpoint
glVertex2f(x + w * 0.5f, y + h * 0.5f);
// Four corners in CCW order, closing back to the first arc point
corner(x + r, y + r, PI, PI + HALF_PI); // top-left