-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathgraphic3.cpp
1137 lines (981 loc) · 44.7 KB
/
graphic3.cpp
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 <graphics.h>
#include <math.h>
#include <windows.h>
#include <iostream>
#include <fstream>
#include <strstream>
#include <list>
#include <string>
#include <vector>
#include <chrono>
using namespace std;
struct vec2d // to store texture information of triangles, but here we don't actually apply texture, we use this to compute z buffer
{
float u = 0;
float v = 0;
float w = 1;
};
struct vec3d // to store triangle vertex information
{
float x = 0;
float y = 0;
float z = 0;
float w = 1;
};
struct triangle // triangle struct represents a triangle, which contains vertex of triangles as p and vertex of texture as t, whereas col refers to colour of the triangles, which in this project is black or light gray or dark gray
{
vec3d p[3];
vec2d t[3];
short col;
};
struct mesh // mesh is basically vector of all triangles of an object extracted from an object file. Exterior of car is a mesh and interior of car is another mesh
{
vector<triangle> tris;
bool LoadFromObjectFile(string sFilename, bool bHasTexture = false) // it is function to read and store triangles from obj file to mesh.
{
ifstream f(sFilename);
if (!f.is_open())
return false;
// Local cache of verts
vector<vec3d> verts;
vector<vec2d> texs;
while (!f.eof())
{
char line[128];
f.getline(line, 128);
strstream s;
s << line;
char junk;
if (line[0] == 'v') // v can be just 'v' or 'vt'. v is vertex of triangle and vt is vertex of texture
{
if (line[1] == 't') // condition for vt
{
vec2d v;
s >> junk >> junk >> v.u >> v.v;
texs.push_back(v);
}
else // condition for v only
{
vec3d v;
s >> junk >> v.x >> v.y >> v.z;
verts.push_back(v);
}
}
if (!bHasTexture) // is define this bool when we define mesh, here in this project we make it true, though we don't really apply texture, but we calculate zbuffer using it
{
if (line[0] == 'f') // f for face. face is set of 3 vertex that define a triangle
{
int f[3];
s >> junk >> f[0] >> f[1] >> f[2];
tris.push_back({verts[f[0] - 1], verts[f[1] - 1], verts[f[2] - 1]});
}
}
else // this condition doesn't really come in our project because we keep bHasTexture always true
{
if (line[0] == 'f')
{
s >> junk;
string tokens[6];
int nTokenCount = -1;
while (!s.eof())
{
char c = s.get();
if (c == ' ' || c == '/')
nTokenCount++;
else
tokens[nTokenCount].append(1, c);
}
tokens[nTokenCount].pop_back();
tris.push_back({verts[stoi(tokens[0]) - 1], verts[stoi(tokens[2]) - 1], verts[stoi(tokens[4]) - 1],
texs[stoi(tokens[1]) - 1], texs[stoi(tokens[3]) - 1], texs[stoi(tokens[5]) - 1]});
}
}
}
return true;
}
};
struct mat4x4 // 4 dimensional matrix for transformations
{
float m[4][4] = {0};
};
class renderer // this class contains basically everything that is needed for the rendering
{
private:
DWORD screenWidth;
DWORD screenHeight;
string objName;
mat4x4 matProj, matRotX, matRotY; // projection matrix , and rotation matrices
mesh meshObj; // this mesh is what we render on the screen
mesh meshObj2; // this mesh is swaped with meshobj when we switch between interior and exterior
vec3d vLookDir; // unit vector that travels along the direction that we want the camera to point
vec3d vCamera; // position of camera
POINT cursorPos; // position of mouse cursor
float fYaw = 0.0f; // for rotation of camera in horizontal direction using left and right arrow keys
// float fZaw = 0.0f;
// float fXaw = 0.0f;
float fThetaX = 0.0f; // angle of rotation
float fThetaY = 0.0f;
int page = 0; // for double buffer implementation
int c = 0; // for toggle interior and exterior models
float *pDepthBuffer = nullptr; // z-buffer calculation
mat4x4 matCameraRot; // rotation matrix
std::chrono::time_point<std::chrono::system_clock> m_tp1, m_tp2; // for elapsed time calculation that results in uniform movement w.r.t time
float prevXM; // previous x position of mouse for mouse cursor position detection
float prevYM; // previous y position of mouse
float differenceX; // difference between current and previous x position of mouse
float differenceY;
bool leftButtonHold = false; // for knowing when left mouse button is left
public:
// constructor
renderer(string objName, string objName2, DWORD screenWidth, DWORD screenHeight, int xOffset, int yOffset) // constructor of class, runs only once when program is run
{
initwindow(screenWidth, screenHeight, "", xOffset, yOffset);
this->objName = objName;
this->screenWidth = screenWidth;
this->screenHeight = screenHeight;
// Projection Matrix
matProj = Matrix_MakeProjection(90.0f, (float)screenHeight / (float)screenWidth, 0.1f, 1000.0f); // precalculated value assigned. 90 is angle of vision, 0.1f is near plane distance from camera, 1000.0f is far plane distance from camera
meshObj.LoadFromObjectFile(objName, true); // exterior of car read and loaded
meshObj2.LoadFromObjectFile(objName2, true); // interior of car read and loaded
pDepthBuffer = new float[screenWidth * screenHeight]; // for z-buffer calculation
// meshObj.tris = {
// // SOUTH
// { 0.0f, 0.0f, 0.0f, 1.0f, 0.0f, 1.0f, 0.0f, 1.0f, 1.0f, 1.0f, 0.0f, 1.0f, 0.0f, 1.0f, 1.0f, 0.0f, 0.0f, 1.0f, 1.0f, 0.0f, 1.0f,},
// { 0.0f, 0.0f, 0.0f, 1.0f, 1.0f, 1.0f, 0.0f, 1.0f, 1.0f, 0.0f, 0.0f, 1.0f, 0.0f, 1.0f, 1.0f, 1.0f, 0.0f, 1.0f, 1.0f, 1.0f, 1.0f,},
// // EAST
// { 1.0f, 0.0f, 0.0f, 1.0f, 1.0f, 1.0f, 0.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 0.0f, 1.0f, 1.0f, 0.0f, 0.0f, 1.0f, 1.0f, 0.0f, 1.0f,},
// { 1.0f, 0.0f, 0.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 0.0f, 1.0f, 1.0f, 0.0f, 1.0f, 1.0f, 1.0f, 0.0f, 1.0f, 1.0f, 1.0f, 1.0f,},
// // NORTH
// { 1.0f, 0.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 0.0f, 1.0f, 1.0f, 1.0f, 0.0f, 1.0f, 1.0f, 0.0f, 0.0f, 1.0f, 1.0f, 0.0f, 1.0f,},
// { 1.0f, 0.0f, 1.0f, 1.0f, 0.0f, 1.0f, 1.0f, 1.0f, 0.0f, 0.0f, 1.0f, 1.0f, 0.0f, 1.0f, 1.0f, 1.0f, 0.0f, 1.0f, 1.0f, 1.0f, 1.0f,},
// // WEST
// { 0.0f, 0.0f, 1.0f, 1.0f, 0.0f, 1.0f, 1.0f, 1.0f, 0.0f, 1.0f, 0.0f, 1.0f, 0.0f, 1.0f, 1.0f, 0.0f, 0.0f, 1.0f, 1.0f, 0.0f, 1.0f,},
// { 0.0f, 0.0f, 1.0f, 1.0f, 0.0f, 1.0f, 0.0f, 1.0f, 0.0f, 0.0f, 0.0f, 1.0f, 0.0f, 1.0f, 1.0f, 1.0f, 0.0f, 1.0f, 1.0f, 1.0f, 1.0f,},
// // TOP
// { 0.0f, 1.0f, 0.0f, 1.0f, 0.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 0.0f, 1.0f, 1.0f, 0.0f, 0.0f, 1.0f, 1.0f, 0.0f, 1.0f,},
// { 0.0f, 1.0f, 0.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 0.0f, 1.0f, 0.0f, 1.0f, 1.0f, 1.0f, 0.0f, 1.0f, 1.0f, 1.0f, 1.0f,},
// // BOTTOM
// { 1.0f, 0.0f, 1.0f, 1.0f, 0.0f, 0.0f, 1.0f, 1.0f, 0.0f, 0.0f, 0.0f, 1.0f, 0.0f, 1.0f, 1.0f, 0.0f, 0.0f, 1.0f, 1.0f, 0.0f, 1.0f,},
// { 1.0f, 0.0f, 1.0f, 1.0f, 0.0f, 0.0f, 0.0f, 1.0f, 1.0f, 0.0f, 0.0f, 1.0f, 0.0f, 1.0f, 1.0f, 1.0f, 0.0f, 1.0f, 1.0f, 1.0f, 1.0f,},
// };
vCamera.x = 0.0f; // defining intial camera position
vCamera.y = 0.0f;
vCamera.z = 0.0f;
// initialization of rotation matrices
// rotation y
matRotY = Matrix_MakeRotationY(fThetaY); // rotation w.r.t y axis
// rotation x
matRotX = Matrix_MakeRotationX(fThetaX); // rotation w.r.t x axis
m_tp1 = std::chrono::system_clock::now();
m_tp2 = std::chrono::system_clock::now();
}
void mainLoop()
{
m_tp2 = std::chrono::system_clock::now();
std::chrono::duration<float> fElapsedTime = m_tp2 - m_tp1;
m_tp1 = m_tp2;
// std::cout<<elapsedTime.count()<<std::endl;
float elapsedTime = fElapsedTime.count(); // time elapsed in each frame
// rotation y
matRotY = Matrix_MakeRotationY(fThetaY); // updating rotation matrices
// rotation x
matRotX = Matrix_MakeRotationX(fThetaX);
setactivepage(page); // double buffer method
setvisualpage(1 - page);
if (GetAsyncKeyState(0x26) != 0) // up key held
{
vCamera.y += 8.0f * elapsedTime;
}
if (GetAsyncKeyState(0x28) != 0) // down key held
{
vCamera.y -= 8.0f * elapsedTime;
}
if (GetAsyncKeyState(0x41) != 0) // a key held
{
vCamera.x += 8.0f * elapsedTime;
}
if (GetAsyncKeyState(0x44) != 0) // d key held
{
vCamera.x -= 8.0f * elapsedTime;
}
vec3d vForward = Vector_Mul(vLookDir, 8.0f * elapsedTime);
if (GetAsyncKeyState(0x57) != 0) // w key held
{
vCamera = Vector_Add(vCamera, vForward);
}
if (GetAsyncKeyState(0x53) != 0) // s key held
{
vCamera = Vector_Sub(vCamera, vForward);
}
if (GetAsyncKeyState(0x25) != 0) // left key held
{
fYaw -= 2.0f * elapsedTime;
}
if (GetAsyncKeyState(0x27) != 0) // right key held
{
fYaw += 2.0f * elapsedTime;
}
if (GetAsyncKeyState(0x20) != 0) // space key pressed
{
c++;
if (c == 1)
{
mesh tempObj = meshObj;
meshObj = meshObj2;
meshObj2 = tempObj;
}
}
else
{
c = 0;
}
// when left click is hold
if ((GetAsyncKeyState(VK_LBUTTON) & 0x8000) != 0)
{
GetCursorPos(&cursorPos);
if (leftButtonHold == false)
{
prevXM = cursorPos.x;
prevYM = cursorPos.y;
leftButtonHold = true;
}
differenceX = prevXM - cursorPos.x;
differenceY = prevYM - cursorPos.y;
fThetaX += differenceY * 0.01; // dragging mouse in y direction give means rotating wrt to x axis
fThetaY += differenceX * 0.01;
prevXM = cursorPos.x;
prevYM = cursorPos.y;
}
else
{
leftButtonHold = false;
}
cleardevice(); // clears the screen
for (int i = 0; i < screenWidth * screenHeight; i++) // depth buffer stuffs
{
pDepthBuffer[i] = 0.0f;
}
// manipulation of triangles started
vector<triangle> vecTrianglesToRaster; // is used to store projected and clipped triangles after
// matrix translation
mat4x4 matTrans;
matTrans = Matrix_MakeTranslation(0.0f, 0.0f, 5.0f); // translating by 5.0f in z direction , otherwise camera would be inside objection
mat4x4 matWorld; // this transformation matrix translates and rotates everything and gives illusion of camera is moving, even though, the world is actually moving
matWorld = Matrix_MakeIdentity(); // Form World Matrix
matWorld = Matrix_MultiplyMatrix(matRotY, matRotX); // Transform by rotation
// matWorld = Matrix_MultiplyMatrix(matRotZ, matRotX);
matWorld = Matrix_MultiplyMatrix(matWorld, matTrans); // Transform by translation
// maybe for initial condition //ends
vec3d vUp = {0, 1, 0}; // up vector, which is perpendicular to forward vector
vec3d vTarget = {0, 0, 1}; // forward vector, initially, is towards z direction
matCameraRot = Matrix_MakeRotationY(fYaw); // camera rotation matrix // uses left and right key to update fYaw which rotates the camera
vLookDir = Matrix_MultiplyVector(matCameraRot, vTarget); // unit vector points towards the direction we want the camera to point
vTarget = Vector_Add(vCamera, vLookDir); // vTarget is vector along which we move when we press w
mat4x4 matCamera = Matrix_PointAt(vCamera, vTarget, vUp); // transformation matrix of camera
// make view matrix from camera
mat4x4 matView = Matrix_QuickInverse(matCamera); // inverse because, we aren't transforming the camera, but instead the whole world
for (auto tri : meshObj.tris) // going through all the triangles of the object
{
triangle triProjected, triTransformed, triViewed; // triTransformed has all the transformed triangles of an object that has been transformed by matWorld matrix // triviewed has all
vec3d normal, line1, line2; // line 1 is one edge of a triangle, line2 is another edge of the triangle and normal is normal vector to the surface of the triangle
// world matrix transform
triTransformed.p[0] = Matrix_MultiplyVector(matWorld, tri.p[0]); // for point data // transformed the whole world/object ( in 3d space )
triTransformed.p[1] = Matrix_MultiplyVector(matWorld, tri.p[1]);
triTransformed.p[2] = Matrix_MultiplyVector(matWorld, tri.p[2]);
triTransformed.t[0] = tri.t[0]; // for texture data
triTransformed.t[1] = tri.t[1];
triTransformed.t[2] = tri.t[2];
// Get lines either side of triangle
line1 = Vector_Sub(triTransformed.p[1], triTransformed.p[0]);
line2 = Vector_Sub(triTransformed.p[2], triTransformed.p[0]);
// Take cross product of lines to get normal to triangle surface
normal = Vector_CrossProduct(line1, line2);
// You normally need to normalise a normal!
normal = Vector_Normalise(normal);
// Get Ray from triangle to camera
vec3d vCameraRay = Vector_Sub(triTransformed.p[0], vCamera);
if (Vector_DotProduct(normal, vCameraRay) < 0.0f) // partial visible surface detection, only includes those triangles whose normal points towards the camera
{
// Convert world space to view space
// Illumination
vec3d light_direction = {1.0f, 1.0f, -1.0f};
light_direction = Vector_Normalise(light_direction);
// How "aligned" are light direction and triangle surface normal?
float dp = max(0.1f, Vector_DotProduct(light_direction, normal));
// Choose console colours as required
int c = GetColour(dp);
triTransformed.col = c;
triViewed.p[0] = Matrix_MultiplyVector(matView, triTransformed.p[0]); // changed co-ordinates(by rotation) of the triangles w.r.t camera manipulation ( in 3d space)
triViewed.p[1] = Matrix_MultiplyVector(matView, triTransformed.p[1]);
triViewed.p[2] = Matrix_MultiplyVector(matView, triTransformed.p[2]);
triViewed.col = triTransformed.col;
triViewed.t[0] = triTransformed.t[0]; // for texture
triViewed.t[1] = triTransformed.t[1];
triViewed.t[2] = triTransformed.t[2];
int nClippedTriangles = 0; // number of triangles formed of 1 triangles when clipped against window
triangle clipped[2];
nClippedTriangles = Triangle_ClipAgainstPlane({0.0f, 0.0f, 0.1f}, {0.0f, 0.0f, 1.0f}, triViewed, clipped[0], clipped[1]); // passing clipped by reference, so changes occur in clipped
for (int n = 0; n < nClippedTriangles; n++)
{
// Project triangles from 3D --> 2D
triProjected.p[0] = Matrix_MultiplyVector(matProj, clipped[n].p[0]); // projects from 3d space to 2d space
triProjected.p[1] = Matrix_MultiplyVector(matProj, clipped[n].p[1]);
triProjected.p[2] = Matrix_MultiplyVector(matProj, clipped[n].p[2]);
triProjected.col = clipped[n].col;
triProjected.t[0] = clipped[n].t[0]; // clipped triangles
triProjected.t[1] = clipped[n].t[1];
triProjected.t[2] = clipped[n].t[2];
triProjected.t[0].u = triProjected.t[0].u / triProjected.p[0].w; // texture projection affected by projection of triangles
triProjected.t[1].u = triProjected.t[1].u / triProjected.p[1].w;
triProjected.t[2].u = triProjected.t[2].u / triProjected.p[2].w;
triProjected.t[0].v = triProjected.t[0].v / triProjected.p[0].w;
triProjected.t[1].v = triProjected.t[1].v / triProjected.p[1].w;
triProjected.t[2].v = triProjected.t[2].v / triProjected.p[2].w;
triProjected.t[0].w = 1.0f / triProjected.p[0].w;
triProjected.t[1].w = 1.0f / triProjected.p[1].w;
triProjected.t[2].w = 1.0f / triProjected.p[2].w;
// Scale into view, we moved the normalising into cartesian space
// out of the matrix.vector function
triProjected.p[0] = Vector_Div(triProjected.p[0], triProjected.p[0].w);
triProjected.p[1] = Vector_Div(triProjected.p[1], triProjected.p[1].w);
triProjected.p[2] = Vector_Div(triProjected.p[2], triProjected.p[2].w);
// X/Y are inverted so putting them back
triProjected.p[0].x *= -1.0f;
triProjected.p[1].x *= -1.0f;
triProjected.p[2].x *= -1.0f;
triProjected.p[0].y *= -1.0f;
triProjected.p[1].y *= -1.0f;
triProjected.p[2].y *= -1.0f;
vec3d vOffsetView = {1, 1, 0}; // since we export file from blender and blender co ordinate system has negative values, but our screen only has positive scales, from (0,0) to (1920, 1080), so, we offset in x and y to make it appear on screen, otherwise, negative part wouldn't be visible
triProjected.p[0] = Vector_Add(triProjected.p[0], vOffsetView);
triProjected.p[1] = Vector_Add(triProjected.p[1], vOffsetView);
triProjected.p[2] = Vector_Add(triProjected.p[2], vOffsetView);
// scaling it wrt to screen size //we scale half the total length to make the object appear on center
triProjected.p[0].x *= 0.5f * (float)screenWidth; // scaling in x direction is bigger because width is bigger than height, but it's cancelled out by aspect ratio( h/w), so at the end, it is just perfect
triProjected.p[0].y *= 0.5f * (float)screenHeight;
triProjected.p[1].x *= 0.5f * (float)screenWidth;
triProjected.p[1].y *= 0.5f * (float)screenHeight;
triProjected.p[2].x *= 0.5f * (float)screenWidth;
triProjected.p[2].y *= 0.5f * (float)screenHeight;
// drawTriangle(triProjected.p[0].x, triProjected.p[0].y, triProjected.p[1].x, triProjected.p[1].y, triProjected.p[2].x, triProjected.p[2].y);
vecTrianglesToRaster.push_back(triProjected);
}
}
//}
}
// sort triangles from back to front
// sort(vecTrianglesToRaster.begin(), vecTrianglesToRaster.end(), [](triangle &t1, triangle &t2)
// {
// float z1 = (t1.p[0].z +t1.p[1].z +t1.p[2].z)/3.0f;
// float z2 = (t2.p[0].z +t2.p[1].z +t2.p[2].z)/3.0f;
// return z1>z2; });
for (auto &triToRaster : vecTrianglesToRaster) // triangles to raster
{
triangle clipped[2];
list<triangle> listTriangles;
listTriangles.push_back(triToRaster);
int nNewTriangles = 1;
for (int p = 0; p < 4; p++)
{
int nTrisToAdd = 0;
while (nNewTriangles > 0)
{
// Take triangle from front of queue
triangle test = listTriangles.front();
listTriangles.pop_front();
nNewTriangles--;
// Clip it against a plane. We only need to test each
// subsequent plane, against subsequent new triangles
// as all triangles after a plane clip are guaranteed
// to lie on the inside of the plane.
switch (p)
{
case 0:
nTrisToAdd = Triangle_ClipAgainstPlane({0.0f, 0.0f, 0.0f}, {0.0f, 1.0f, 0.0f}, test, clipped[0], clipped[1]);
break;
case 1:
nTrisToAdd = Triangle_ClipAgainstPlane({0.0f, (float)screenHeight - 1, 0.0f}, {0.0f, -1.0f, 0.0f}, test, clipped[0], clipped[1]);
break;
case 2:
nTrisToAdd = Triangle_ClipAgainstPlane({0.0f, 0.0f, 0.0f}, {1.0f, 0.0f, 0.0f}, test, clipped[0], clipped[1]);
break;
case 3:
nTrisToAdd = Triangle_ClipAgainstPlane({(float)screenWidth - 1, 0.0f, 0.0f}, {-1.0f, 0.0f, 0.0f}, test, clipped[0], clipped[1]);
break;
}
// Clipping may yield a variable number of triangles, so
// add these new ones to the back of the queue for subsequent
// clipping against next planes
for (int w = 0; w < nTrisToAdd; w++)
listTriangles.push_back(clipped[w]);
}
nNewTriangles = listTriangles.size();
}
// Draw the transformed, viewed, clipped, projected, sorted, clipped triangles
for (auto &t : listTriangles) // triangles to be drawn
{
// drawTriangle(t.p[0].x, t.p[0].y, t.p[1].x, t.p[1].y, t.p[2].x, t.p[2].y);
TexturedTriangle(t.p[0].x, t.p[0].y, t.t[0].u, t.t[0].v, t.t[0].w,
t.p[1].x, t.p[1].y, t.t[1].u, t.t[1].v, t.t[1].w,
t.p[2].x, t.p[2].y, t.t[2].u, t.t[2].v, t.t[2].w, t.col);
}
}
page = 1 - page; // double buffer method
}
private:
vec3d Vector_Add(vec3d &v1, vec3d &v2)
{
return {v1.x + v2.x, v1.y + v2.y, v1.z + v2.z};
}
vec3d Vector_Sub(vec3d &v1, vec3d &v2)
{
return {v1.x - v2.x, v1.y - v2.y, v1.z - v2.z};
}
vec3d Vector_Mul(vec3d &v1, float k)
{
return {v1.x * k, v1.y * k, v1.z * k};
}
vec3d Vector_Div(vec3d &v1, float k)
{
return {v1.x / k, v1.y / k, v1.z / k};
}
float Vector_DotProduct(vec3d &v1, vec3d &v2)
{
return v1.x * v2.x + v1.y * v2.y + v1.z * v2.z;
}
float Vector_Length(vec3d &v)
{
return sqrtf(Vector_DotProduct(v, v));
}
vec3d Vector_Normalise(vec3d &v)
{
float l = Vector_Length(v);
return {v.x / l, v.y / l, v.z / l};
}
vec3d Vector_CrossProduct(vec3d &v1, vec3d &v2)
{
vec3d v;
v.x = v1.y * v2.z - v1.z * v2.y;
v.y = v1.z * v2.x - v1.x * v2.z;
v.z = v1.x * v2.y - v1.y * v2.x;
return v;
}
vec3d Matrix_MultiplyVector(mat4x4 &m, vec3d &i)
{
vec3d v;
v.x = i.x * m.m[0][0] + i.y * m.m[1][0] + i.z * m.m[2][0] + i.w * m.m[3][0];
v.y = i.x * m.m[0][1] + i.y * m.m[1][1] + i.z * m.m[2][1] + i.w * m.m[3][1];
v.z = i.x * m.m[0][2] + i.y * m.m[1][2] + i.z * m.m[2][2] + i.w * m.m[3][2];
v.w = i.x * m.m[0][3] + i.y * m.m[1][3] + i.z * m.m[2][3] + i.w * m.m[3][3];
return v;
}
void MultiplyMatrixVector(vec3d &i, vec3d &o, mat4x4 &m)
{ // pass by reference
o.x = i.x * m.m[0][0] + i.y * m.m[1][0] + i.z * m.m[2][0] + m.m[3][0];
o.y = i.x * m.m[0][1] + i.y * m.m[1][1] + i.z * m.m[2][1] + m.m[3][1];
o.z = i.x * m.m[0][2] + i.y * m.m[1][2] + i.z * m.m[2][2] + m.m[3][2];
float w = i.x * m.m[0][3] + i.y * m.m[1][3] + i.z * m.m[2][3] + m.m[3][3];
if (w != 0.0f)
{
o.x /= w;
o.y /= w;
o.z /= w;
}
}
mat4x4 Matrix_MakeIdentity()
{
mat4x4 matrix;
matrix.m[0][0] = 1.0f;
matrix.m[1][1] = 1.0f;
matrix.m[2][2] = 1.0f;
matrix.m[3][3] = 1.0f;
return matrix;
}
mat4x4 Matrix_Adder(mat4x4 mat1, mat4x4 mat2)
{
mat4x4 mat3;
for (int i = 0; i < 4; i++)
{
for (int j = 0; j < 4; j++)
{
mat3.m[i][j] = mat1.m[i][j] + mat2.m[i][j];
}
}
return mat3;
}
mat4x4 Matrix_MakeRotationX(float fAngleRad)
{
mat4x4 matrix;
matrix.m[0][0] = 1.0f;
matrix.m[1][1] = cosf(fAngleRad);
matrix.m[1][2] = sinf(fAngleRad);
matrix.m[2][1] = -sinf(fAngleRad);
matrix.m[2][2] = cosf(fAngleRad);
matrix.m[3][3] = 1.0f;
return matrix;
}
mat4x4 Matrix_MakeRotationY(float fAngleRad)
{
mat4x4 matrix;
matrix.m[0][0] = cosf(fAngleRad);
matrix.m[0][2] = sinf(fAngleRad);
matrix.m[2][0] = -sinf(fAngleRad);
matrix.m[1][1] = 1.0f;
matrix.m[2][2] = cosf(fAngleRad);
matrix.m[3][3] = 1.0f;
return matrix;
}
mat4x4 Matrix_MakeRotationZ(float fAngleRad)
{
mat4x4 matrix;
matrix.m[0][0] = cosf(fAngleRad);
matrix.m[0][1] = sinf(fAngleRad);
matrix.m[1][0] = -sinf(fAngleRad);
matrix.m[1][1] = cosf(fAngleRad);
matrix.m[2][2] = 1.0f;
matrix.m[3][3] = 1.0f;
return matrix;
}
mat4x4 Matrix_MakeTranslation(float x, float y, float z)
{
mat4x4 matrix;
matrix.m[0][0] = 1.0f;
matrix.m[1][1] = 1.0f;
matrix.m[2][2] = 1.0f;
matrix.m[3][3] = 1.0f;
matrix.m[3][0] = x;
matrix.m[3][1] = y;
matrix.m[3][2] = z;
return matrix;
}
mat4x4 Matrix_MakeProjection(float fFovDegrees, float fAspectRatio, float fNear, float fFar)
{
float fFovRad = 1.0f / tanf(fFovDegrees * 0.5f / 180.0f * 3.14159f);
mat4x4 matrix;
matrix.m[0][0] = fAspectRatio * fFovRad;
matrix.m[1][1] = fFovRad;
matrix.m[2][2] = fFar / (fFar - fNear);
matrix.m[3][2] = (-fFar * fNear) / (fFar - fNear);
matrix.m[2][3] = 1.0f;
matrix.m[3][3] = 0.0f;
return matrix;
}
mat4x4 Matrix_MultiplyMatrix(mat4x4 &m1, mat4x4 &m2)
{
mat4x4 matrix;
for (int c = 0; c < 4; c++)
for (int r = 0; r < 4; r++)
matrix.m[r][c] = m1.m[r][0] * m2.m[0][c] + m1.m[r][1] * m2.m[1][c] + m1.m[r][2] * m2.m[2][c] + m1.m[r][3] * m2.m[3][c];
return matrix;
}
mat4x4 Matrix_PointAt(vec3d &pos, vec3d &target, vec3d &up)
{
// calculate new forward direction
vec3d newForward = Vector_Sub(target, pos);
newForward = Vector_Normalise(newForward);
// calculate new up direction
vec3d a = Vector_Mul(newForward, Vector_DotProduct(up, newForward));
vec3d newUp = Vector_Sub(up, a);
newUp = Vector_Normalise(newUp);
// new right direction
vec3d newRight = Vector_CrossProduct(newUp, newForward);
// construct dimensioning and translation matrix
mat4x4 matrix;
matrix.m[0][0] = newRight.x;
matrix.m[0][1] = newRight.y;
matrix.m[0][2] = newRight.z;
matrix.m[0][3] = 0.0f;
matrix.m[1][0] = newUp.x;
matrix.m[1][1] = newUp.y;
matrix.m[1][2] = newUp.z;
matrix.m[1][3] = 0.0f;
matrix.m[2][0] = newForward.x;
matrix.m[2][1] = newForward.y;
matrix.m[2][2] = newForward.z;
matrix.m[2][3] = 0.0f;
matrix.m[3][0] = pos.x;
matrix.m[3][1] = pos.y;
matrix.m[3][2] = pos.z;
matrix.m[3][3] = 1.0f;
return matrix;
}
mat4x4 Matrix_QuickInverse(mat4x4 &m) // Only for Rotation/Translation Matrices
{
mat4x4 matrix;
matrix.m[0][0] = m.m[0][0];
matrix.m[0][1] = m.m[1][0];
matrix.m[0][2] = m.m[2][0];
matrix.m[0][3] = 0.0f;
matrix.m[1][0] = m.m[0][1];
matrix.m[1][1] = m.m[1][1];
matrix.m[1][2] = m.m[2][1];
matrix.m[1][3] = 0.0f;
matrix.m[2][0] = m.m[0][2];
matrix.m[2][1] = m.m[1][2];
matrix.m[2][2] = m.m[2][2];
matrix.m[2][3] = 0.0f;
matrix.m[3][0] = -(m.m[3][0] * matrix.m[0][0] + m.m[3][1] * matrix.m[1][0] + m.m[3][2] * matrix.m[2][0]);
matrix.m[3][1] = -(m.m[3][0] * matrix.m[0][1] + m.m[3][1] * matrix.m[1][1] + m.m[3][2] * matrix.m[2][1]);
matrix.m[3][2] = -(m.m[3][0] * matrix.m[0][2] + m.m[3][1] * matrix.m[1][2] + m.m[3][2] * matrix.m[2][2]);
matrix.m[3][3] = 1.0f;
return matrix;
}
vec3d Vector_IntersectPlane(vec3d &plane_p, vec3d &plane_n, vec3d &lineStart, vec3d &lineEnd, float &t) // returns the point where a line interesects a plane
{
plane_n = Vector_Normalise(plane_n);
float plane_d = -Vector_DotProduct(plane_n, plane_p);
float ad = Vector_DotProduct(lineStart, plane_n);
float bd = Vector_DotProduct(lineEnd, plane_n);
t = (-plane_d - ad) / (bd - ad);
vec3d lineStartToEnd = Vector_Sub(lineEnd, lineStart);
vec3d lineToIntersect = Vector_Mul(lineStartToEnd, t);
return Vector_Add(lineStart, lineToIntersect);
}
int Triangle_ClipAgainstPlane(vec3d plane_p, vec3d plane_n, triangle &in_tri, triangle &out_tri1, triangle &out_tri2) // returns number of triangle that has been clipped from a single triangle , as well as return by reference the actual clipped triangles
{
// Make sure plane normal is indeed normal
plane_n = Vector_Normalise(plane_n);
// Return signed shortest distance from point to plane, plane normal must be normalised
auto dist = [&](vec3d &p)
{
vec3d n = Vector_Normalise(p);
return (plane_n.x * p.x + plane_n.y * p.y + plane_n.z * p.z - Vector_DotProduct(plane_n, plane_p));
};
// Create two temporary storage arrays to classify points either side of plane
// If distance sign is positive, point lies on "inside" of plane
vec3d *inside_points[3];
int nInsidePointCount = 0;
vec3d *outside_points[3];
int nOutsidePointCount = 0;
vec2d *inside_tex[3];
int nInsideTexCount = 0;
vec2d *outside_tex[3];
int nOutsideTexCount = 0;
// Get signed distance of each point in triangle to plane
float d0 = dist(in_tri.p[0]);
float d1 = dist(in_tri.p[1]);
float d2 = dist(in_tri.p[2]);
if (d0 >= 0)
{
inside_points[nInsidePointCount++] = &in_tri.p[0];
inside_tex[nInsideTexCount++] = &in_tri.t[0];
}
else
{
outside_points[nOutsidePointCount++] = &in_tri.p[0];
outside_tex[nOutsideTexCount++] = &in_tri.t[0];
}
if (d1 >= 0)
{
inside_points[nInsidePointCount++] = &in_tri.p[1];
inside_tex[nInsideTexCount++] = &in_tri.t[1];
}
else
{
outside_points[nOutsidePointCount++] = &in_tri.p[1];
outside_tex[nOutsideTexCount++] = &in_tri.t[1];
}
if (d2 >= 0)
{
inside_points[nInsidePointCount++] = &in_tri.p[2];
inside_tex[nInsideTexCount++] = &in_tri.t[2];
}
else
{
outside_points[nOutsidePointCount++] = &in_tri.p[2];
outside_tex[nOutsideTexCount++] = &in_tri.t[2];
}
// Now classify triangle points, and break the input triangle into
// smaller output triangles if required. There are four possible
// outcomes...
if (nInsidePointCount == 0)
{
// All points lie on the outside of plane, so clip whole triangle
// It ceases to exist
return 0; // No returned triangles are valid
}
if (nInsidePointCount == 3)
{
// All points lie on the inside of plane, so do nothing
// and allow the triangle to simply pass through
out_tri1 = in_tri;
return 1; // Just the one returned original triangle is valid
}
if (nInsidePointCount == 1 && nOutsidePointCount == 2)
{
// Triangle should be clipped. As two points lie outside
// the plane, the triangle simply becomes a smaller triangle
// Copy appearance info to new triangle
out_tri1.col = in_tri.col;
// The inside point is valid, so keep that...
out_tri1.p[0] = *inside_points[0];
out_tri1.t[0] = *inside_tex[0];
// but the two new points are at the locations where the
// original sides of the triangle (lines) intersect with the plane
float t;
out_tri1.p[1] = Vector_IntersectPlane(plane_p, plane_n, *inside_points[0], *outside_points[0], t);
out_tri1.t[1].u = t * (outside_tex[0]->u - inside_tex[0]->u) + inside_tex[0]->u;
out_tri1.t[1].v = t * (outside_tex[0]->v - inside_tex[0]->v) + inside_tex[0]->v;
out_tri1.t[1].w = t * (outside_tex[0]->w - inside_tex[0]->w) + inside_tex[0]->w;
out_tri1.p[2] = Vector_IntersectPlane(plane_p, plane_n, *inside_points[0], *outside_points[1], t);
out_tri1.t[2].u = t * (outside_tex[1]->u - inside_tex[0]->u) + inside_tex[0]->u;
out_tri1.t[2].v = t * (outside_tex[1]->v - inside_tex[0]->v) + inside_tex[0]->v;
out_tri1.t[2].w = t * (outside_tex[1]->w - inside_tex[0]->w) + inside_tex[0]->w;
return 1; // Return the newly formed single triangle
}
if (nInsidePointCount == 2 && nOutsidePointCount == 1)
{
// Triangle should be clipped. As two points lie inside the plane,
// the clipped triangle becomes a "quad". Fortunately, we can
// represent a quad with two new triangles
// Copy appearance info to new triangles
out_tri1.col = in_tri.col;
out_tri2.col = in_tri.col;
// The first triangle consists of the two inside points and a new
// point determined by the location where one side of the triangle
// intersects with the plane
out_tri1.p[0] = *inside_points[0];
out_tri1.p[1] = *inside_points[1];
out_tri1.t[0] = *inside_tex[0];
out_tri1.t[1] = *inside_tex[1];
float t;
out_tri1.p[2] = Vector_IntersectPlane(plane_p, plane_n, *inside_points[0], *outside_points[0], t);
out_tri1.t[2].u = t * (outside_tex[0]->u - inside_tex[0]->u) + inside_tex[0]->u;
out_tri1.t[2].v = t * (outside_tex[0]->v - inside_tex[0]->v) + inside_tex[0]->v;
out_tri1.t[2].w = t * (outside_tex[0]->w - inside_tex[0]->w) + inside_tex[0]->w;
// The second triangle is composed of one of he inside points, a
// new point determined by the intersection of the other side of the
// triangle and the plane, and the newly created point above
out_tri2.p[0] = *inside_points[1];
out_tri2.t[0] = *inside_tex[1];
out_tri2.p[1] = out_tri1.p[2];
out_tri2.t[1] = out_tri1.t[2];
out_tri2.p[2] = Vector_IntersectPlane(plane_p, plane_n, *inside_points[1], *outside_points[0], t);
out_tri2.t[2].u = t * (outside_tex[0]->u - inside_tex[1]->u) + inside_tex[1]->u;
out_tri2.t[2].v = t * (outside_tex[0]->v - inside_tex[1]->v) + inside_tex[1]->v;
out_tri2.t[2].w = t * (outside_tex[0]->w - inside_tex[1]->w) + inside_tex[1]->w;
return 2; // Return two newly formed triangles which form a quad
}
}
int GetColour(float lum) //get color of triangle considering the illumnation configuration( angle at which light incidents the surface of triangle)
{
int bg_col;
int pixel_bw = (int)(13.0f * lum);
switch (pixel_bw)
{
case 0:
bg_col = BLACK;
break;
case 1:
bg_col = BLACK;
break;
case 2:
bg_col = BLACK;
break;
case 3:
bg_col = BLACK;
break;
case 4:
bg_col = BLACK;
break;
case 5:
bg_col = DARKGRAY;
break;
case 6:
bg_col = DARKGRAY;
break;
case 7:
bg_col = DARKGRAY;
break;
case 8:
bg_col = DARKGRAY;
break;
case 9:
bg_col = LIGHTGRAY;
break;
case 10:
bg_col = LIGHTGRAY;
break;
case 11:
bg_col = LIGHTGRAY;
break;
case 12:
bg_col = LIGHTGRAY;
break;
default:
bg_col = BLACK;
}
return bg_col;
}
void TexturedTriangle(int x1, int y1, float u1, float v1, float w1, // function of fill a triangle with a corresponding color
int x2, int y2, float u2, float v2, float w2,
int x3, int y3, float u3, float v3, float w3,
short col)
{
if (y2 < y1)
{
swap(y1, y2);
swap(x1, x2);
swap(u1, u2);
swap(v1, v2);
swap(w1, w2);
}
if (y3 < y1)
{
swap(y1, y3);
swap(x1, x3);
swap(u1, u3);
swap(v1, v3);
swap(w1, w3);
}
if (y3 < y2)
{
swap(y2, y3);
swap(x2, x3);
swap(u2, u3);
swap(v2, v3);
swap(w2, w3);
}
int dy1 = y2 - y1;
int dx1 = x2 - x1;
float dv1 = v2 - v1;
float du1 = u2 - u1;
float dw1 = w2 - w1;
int dy2 = y3 - y1;
int dx2 = x3 - x1;
float dv2 = v3 - v1;
float du2 = u3 - u1;
float dw2 = w3 - w1;
float tex_u, tex_v, tex_w;
float dax_step = 0, dbx_step = 0,
du1_step = 0, dv1_step = 0,
du2_step = 0, dv2_step = 0,
dw1_step = 0, dw2_step = 0;
if (dy1)
dax_step = dx1 / (float)abs(dy1);
if (dy2)
dbx_step = dx2 / (float)abs(dy2);
if (dy1)
du1_step = du1 / (float)abs(dy1);
if (dy1)
dv1_step = dv1 / (float)abs(dy1);
if (dy1)
dw1_step = dw1 / (float)abs(dy1);
if (dy2)