-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathProcessing.cpp
More file actions
4304 lines (3998 loc) · 177 KB
/
Processing.cpp
File metadata and controls
4304 lines (3998 loc) · 177 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
#include "Processing.h"
#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
// #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.
#if __has_include("stb_truetype.h")
# define STB_TRUETYPE_IMPLEMENTATION
# include "stb_truetype.h"
# define PROCESSING_HAS_STB_TRUETYPE 1
#else
# define PROCESSING_HAS_STB_TRUETYPE 0
#endif
namespace Processing {
// =============================================================================
// STATE
// =============================================================================
// Window / canvas size
int winWidth = 640, winHeight = 480; // current window size (updated by size())
int logicalW = 640, logicalH = 480; // sketch's coordinate space (from size())
static int fbW = 640, fbH = 480; // actual framebuffer (may be 2× on HiDPI)
int displayWidth = 0, displayHeight = 0;
int pixelWidth = 0, pixelHeight = 0;
int pixelDensityValue = 1;
bool isResizable = false;
bool focused = false;
// Mouse state
float mouseX = 0, mouseY = 0, pmouseX = 0, pmouseY = 0;
bool mouseInWindow = false; // true once cursor has entered the window
bool _mousePressed = false;
int mouseButton = -1;
// Keyboard state
bool _keyPressed = false;
int keyCode = 0;
char key = 0;
// Frame timing
int frameCount = 1;
float currentFrameRate = 60.0f;
bool looping = true;
static bool redrawOnce = false;
float measuredFrameRate = 0.0f;
static double targetFrameTime = 1.0 / 60.0;
// Current draw style
float fillR = 1, fillG = 1, fillB = 1, fillA = 1;
float strokeR = 0, strokeG = 0, strokeB = 0, strokeA = 1;
float strokeW = 1;
bool doFill = true, doStroke = true, smoothing = true;
int currentRectMode = CORNER;
int currentEllipseMode = CENTER;
int currentImageMode = CORNER;
float tintR = 1, tintG = 1, tintB = 1, tintA = 1;
bool doTint = false;
// Lighting state
static float pendingSpecR = 0, pendingSpecG = 0, pendingSpecB = 0; // from lightSpecular()
static float lightConcentration[8] = { 0, 0, 0, 0, 0, 0, 0, 0 }; // spotlight exponent
static float lightCutoffCos[8] = { -1, -1, -1, -1, -1, -1, -1, -1 }; // cos(cutoff), -1 = no cone
// Color mode
int colorModeVal = RGB;
float colorMaxH = 255.f, colorMaxS = 255.f, colorMaxB = 255.f, colorMaxA = 255.f;
std::vector<unsigned int> pixels;
// 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;
std::function<void()> _onWindowResized;
// 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.
void (*_wireCallbacksFn)() = nullptr;
void (*_staticSketchSetup)() = nullptr; // set by static sketches for i3 redraw
static GLFWwindow* gWindow=nullptr;
static bool is3DMode=false;
static int sphereRes=48;
static int curveDetailVal=20;
static float curveTightnessVal=0.0f;
static int bezierDetailVal=60;
static bool lightsEnabled=false;
static int lightIndex=0;
// Shape state
static int shapeKind=-1;
static bool inShape=false,inContour=false;
static bool shape3D=false;
static std::vector<std::pair<float,float>> shapeVerts; // 2D projections (for stroke outlines)
static std::vector<std::array<float,3>> shapeVerts3D; // full 3D positions (for fill)
static std::vector<std::pair<float,float>> contourVerts;
// Style stack
struct Style {
float fillR, fillG, fillB, fillA;
float strokeR, strokeG, strokeB, strokeA, strokeW;
bool doFill, doStroke;
int rectMode, ellipseMode, imageMode;
float tintR, tintG, tintB, tintA;
bool doTint;
int colorMode;
float cmH, cmS, cmB, cmA;
};
static std::vector<Style> styleStack;
// =============================================================================
// 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.
// =============================================================================
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;
static int noiseOctaves = 4;
static float noiseFalloff = 0.5f;
static float perlinTable[PERLIN_SIZE + 1];
static bool perlinInit = false;
static void 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 noiseSeed(int s) { initPerlin((unsigned int)s); }
void 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 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 noise(float x) { return noise(x, 0.0f, 0.0f); }
float noise(float x, float y) { return noise(x, y, 0.0f); }
// Seeded random -- Mersenne Twister for reproducibility matching Java Processing
static std::mt19937 _rng(std::mt19937::default_seed);
static std::uniform_real_distribution<float> _rngDist(0.0f, 1.0f);
void randomSeed(long s) {
_rng.seed(static_cast<uint32_t>(s));
_rngDist.reset();
}
float random(float lo, float hi) {
return lo + _rngDist(_rng) * (hi - lo);
}
float random(float hi) { return random(0.f, hi); }
float 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
// =============================================================================
static void 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 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 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
// =============================================================================
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(int r, int g, int b) { value = makeColor((float)r,(float)g,(float)b,colorMaxA).value; }
color::color(int r,int g,int b,int a){ value = makeColor((float)r,(float)g,(float)b,(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 colorMode(int mode, float mx) { colorModeVal=mode; colorMaxH=colorMaxS=colorMaxB=colorMaxA=mx; }
void 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 red(color c) { unsigned int v=c.value; return (v>>16&0xFF)/255.0f*colorMaxH; }
float green(color c) { unsigned int v=c.value; return (v>>8&0xFF)/255.0f*colorMaxS; }
float blue(color c) { unsigned int v=c.value; return (v&0xFF)/255.0f*colorMaxB; }
float alpha(color c) { unsigned int v=c.value; return (v>>24&0xFF)/255.0f*colorMaxA; }
float 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 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 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 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
// =============================================================================
static void 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.
static void 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.
static void 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);
}
}
static GLuint persistFBO=0, persistTex=0;
static void 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
static void 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
static void 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);
}
static void _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);
}
static void 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);
}
static void drawEllipseGeom(float cx,float cy,float rx,float ry,
float sa=0,float ea=TWO_PI,int segs=-1){
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();
}
}
static void 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;}
}
static void 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;}
}
static void 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;
}
static void 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
// =============================================================================
static bool defaultP3D = false;
static void applyDefaultCamera(); // forward decl for use in size()
void 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 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 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 frameRate(int fps){currentFrameRate=fps;targetFrameTime=1.0/fps;}
void settings(){}
void noLoop(){looping=false;}
void loop() {looping=true;}
void redraw(){redrawOnce=true;}
void exit_sketch(){if(gWindow)glfwSetWindowShouldClose(gWindow,GLFW_TRUE);}
void windowTitle(const std::string& t){if(gWindow)glfwSetWindowTitle(gWindow,t.c_str());}
void windowMove(int x,int y){if(gWindow)glfwSetWindowPos(gWindow,x,y);}
void windowResize(int w,int h){size(w,h);}
void windowResizable(bool r){isResizable=r;if(gWindow)glfwSetWindowAttrib(gWindow,GLFW_RESIZABLE,r?GLFW_TRUE:GLFW_FALSE);}
// ---------------------------------------------------------------------------
// Clipboard
// ---------------------------------------------------------------------------
void setClipboard(const std::string& s) {
if (s.empty()) return;
if (gWindow) glfwSetClipboardString(gWindow, s.c_str());
}
std::string getClipboard() {
if (!gWindow) return "";
const char* cb = glfwGetClipboardString(gWindow);
return cb ? std::string(cb) : "";
}
// ---------------------------------------------------------------------------
// Window icon
// ---------------------------------------------------------------------------
void 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
// ---------------------------------------------------------------------------
static int g_currentMods = 0; // GLFW modifier bitmask, set in key/mouse callbacks
bool 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 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 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 windowRatio(int w,int h){if(gWindow)glfwSetWindowAspectRatio(gWindow,w,h);}
void pixelDensity(int d){pixelDensityValue=d;}
void smooth() {smoothing=true; 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 noSmooth(){smoothing=false;glDisable(GL_LINE_SMOOTH);glDisable(GL_POLYGON_SMOOTH);glDisable(GL_POINT_SMOOTH);glDisable(GL_MULTISAMPLE);}
void 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 cursor() {if(gWindow)glfwSetInputMode(gWindow,GLFW_CURSOR,GLFW_CURSOR_NORMAL);}
void cursor(int type){if(!gWindow)return;GLFWcursor* c=glfwCreateStandardCursor(type);if(c)glfwSetCursor(gWindow,c);}
void 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 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 releaseMouse(){if(gWindow){glfwSetInputMode(gWindow,GLFW_CURSOR,GLFW_CURSOR_NORMAL);
glfwSetInputMode(gWindow,GLFW_RAW_MOUSE_MOTION,GLFW_FALSE);}}
// =============================================================================
// STYLE STACK
// =============================================================================
static void 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 };
}
static void 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 pushStyle() {
Style s;
captureStyle(s);
styleStack.push_back(s);
}
void popStyle() {
if (!styleStack.empty()) {
restoreStyle(styleStack.back());
styleStack.pop_back();
}
}
void push() { glPushMatrix(); pushStyle(); }
void pop() { glPopMatrix(); popStyle(); }
void pushMatrix() { glPushMatrix(); }
void popMatrix() { glPopMatrix(); }
// =============================================================================
// BACKGROUND / CLEAR
// =============================================================================
static float bgR=0.8f,bgG=0.8f,bgB=0.8f,bgA=1; // Java Processing default grey // last background() color
static void 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 background(float gray) {background(gray, colorMaxA);}
void background(float gray, float a) {
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 background(float r, float g, float b, float a) {
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 background(color c) {
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);
}
static void drawImageRect(PImage& img,float x,float y,float w,float h); // fwd for background(PImage)
void background(const PImage& img) {
// 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 clear(){glClearColor(0,0,0,0);glClear(GL_COLOR_BUFFER_BIT);}
// =============================================================================
// FILL / STROKE
// =============================================================================
void fill(float gray,float a) {setFillFromColor(makeColor(gray,a));}
void fill(float gray) {setFillFromColor(makeColor(gray,colorMaxA));}
void fill(float r,float g,float b,float a) {setFillFromColor(makeColor(r,g,b,a));}
void fill(float r,float g,float b) {setFillFromColor(makeColor(r,g,b,colorMaxA));}
void fill(color c) {setFillFromColor(c);}
void 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 noFill() {doFill=false;}
void stroke(float gray,float a) {setStrokeFromColor(makeColor(gray,a));}
void stroke(float gray) {setStrokeFromColor(makeColor(gray,colorMaxA));}
void stroke(float r,float g,float b,float a){setStrokeFromColor(makeColor(r,g,b,a));}
void stroke(float r,float g,float b) {setStrokeFromColor(makeColor(r,g,b,colorMaxA));}
void stroke(color c) {setStrokeFromColor(c);}
void noStroke() {doStroke=false;}
void strokeWeight(float w) {strokeW=w;}
void strokeCap(int) {}
void strokeJoin(int) {}
// =============================================================================
// PCOLOR CONVENIENCE OVERLOADS
// =============================================================================
void fill(const PColor& c) { fill(c.r, c.g, c.b, c.a); }
void stroke(const PColor& c) { stroke(c.r, c.g, c.b, c.a); }
void background(const PColor& c){ background(c.r, c.g, c.b, c.a); }
void tint(const PColor& c) { tint(c.r, c.g, c.b, c.a); }
void rectMode(int m) {currentRectMode=m;}
void ellipseMode(int m) {currentEllipseMode=m;}
// =============================================================================
// 2D PRIMITIVES
// =============================================================================
static void flushPoints(){} // no-op, points drawn immediately now
void 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 point(float x, float y, float z) {
if (!doStroke) return;
applyStroke();
glPointSize(strokeW);
glBegin(GL_POINTS); glVertex3f(x, y, z); glEnd();
restoreLighting();
}
void line(float x1, float y1, float x2, float y2) {
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 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 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 circle(float cx, float cy, float diameter) {
ellipse(cx, cy, diameter, diameter);
}
void 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 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 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) {
// Expand stroke outward by half strokeWeight so it sits outside the fill
float half = strokeW * 0.5f;
applyStroke();
glLineWidth(strokeW);
glBegin(GL_LINE_LOOP);
glVertex2f(x - half, y - half );
glVertex2f(x + w + half, y - half );
glVertex2f(x + w + half, y + h + half);
glVertex2f(x - half, y + h + half);
glEnd();
restoreLighting();
}
}
void 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) {