-
Notifications
You must be signed in to change notification settings - Fork 0
/
asst8.cpp
1644 lines (1370 loc) · 49.4 KB
/
asst8.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
////////////////////////////////////////////////////////////////////////
//
// Harvard University
// CS175 : Computer Graphics
// Professor Steven Gortler
//
////////////////////////////////////////////////////////////////////////
#include <stdio.h>
#include <cstddef>
#include <vector>
#include <math.h>
#include <string>
#include <memory>
#include <stdexcept>
#include <list>
#if __GNUG__
# include <tr1/memory>
#endif
#ifdef __MAC__
# include <OpenGL/gl3.h>
# include <GLUT/glut.h>
#else
# include <GL/glew.h>
# include <GL/glut.h>
#endif
#include "ppm.h"
#include "cvec.h"
#include "matrix4.h"
#include "rigtform.h"
#include "glsupport.h"
#include "geometrymaker.h"
#include "arcball.h"
#include "scenegraph.h"
#include "asstcommon.h"
#include "drawer.h"
#include "picker.h"
#include "sgutils.h"
#include "geometry.h"
#include "mesh.h"
using namespace std;
using namespace tr1;
#define KF_UNDEF -1
// G L O B A L S ///////////////////////////////////////////////////
// --------- IMPORTANT --------------------------------------------------------
// Before you start working on this assignment, set the following variable
// properly to indicate whether you want to use OpenGL 2.x with GLSL 1.0 or
// OpenGL 3.x+ with GLSL 1.5.
//
// Set g_Gl2Compatible = true to use GLSL 1.0 and g_Gl2Compatible = false to
// use GLSL 1.5. Use GLSL 1.5 unless your system does not support it.
//
// If g_Gl2Compatible=true, shaders with -gl2 suffix will be loaded.
// If g_Gl2Compatible=false, shaders with -gl3 suffix will be loaded.
// To complete the assignment you only need to edit the shader files that get
// loaded
// ----------------------------------------------------------------------------
#ifdef __MAC__
const bool g_Gl2Compatible = false;
#else
const bool g_Gl2Compatible = true;
#endif
static const float g_frustMinFov = 60.0; // A minimal of 60 degree field of view
static float g_frustFovY = g_frustMinFov; // FOV in y direction (updated by updateFrustFovY)
static const float g_frustNear = -0.1; // near plane
static const float g_frustFar = -50.0; // far plane
static const float g_groundY = -2.0; // y coordinate of the ground
static const float g_groundSize = 10.0; // half the ground length
static const int g_divcap = 6;
enum SkyMode {WORLD_SKY=0, SKY_SKY=1};
static double g_horiz_scale = 4.0;
static int g_div_level = 0;
static int g_windowWidth = 512;
static int g_windowHeight = 512;
static bool g_mouseClickDown = false; // is the mouse button pressed
static bool g_mouseLClickButton, g_mouseRClickButton, g_mouseMClickButton;
static bool g_spaceDown = false; // space state, for middle mouse emulation
static bool g_flat = false; // smooth vs flat shading
static int g_mouseClickX, g_mouseClickY; // coordinates for mouse click event
static int g_activeShader = 0;
static Mesh cubeMesh;
static vector<double> vertex_speeds;
static vector<vector<int> > vertex_signs;
static bool meshLoaded = false;
static SkyMode g_activeCameraFrame = WORLD_SKY;
static bool g_displayArcball = true;
static double g_arcballScreenRadius = 100; // number of pixels
static double g_arcballScale = 1;
static bool g_pickingMode = false;
// -------- Shaders
static shared_ptr<Material> g_redDiffuseMat,
g_blueDiffuseMat,
g_bumpFloorMat,
g_arcballMat,
g_pickingMat,
g_lightMat,
g_specular,
g_bunnyMat;
shared_ptr<Material> g_overridingMaterial;
static vector<shared_ptr<Material> > g_bunnyShellMats; // for bunny shells
// New Geometry
static const int g_numShells = 32; // constants defining how many layers of shells
static double g_furHeight = 0.21;
static double g_hairyness = 0.7;
static shared_ptr<SimpleGeometryPN> g_bunnyGeometry;
static vector<shared_ptr<SimpleGeometryPNX> > g_bunnyShellGeometries;
static Mesh g_bunnyMesh;
// New Scene node
static shared_ptr<SgRbtNode> g_bunnyNode;
// linked list of frame vectors
static list<vector<RigTForm> > key_frames;
static int cur_frame = -1;
// --------- Geometry
typedef SgGeometryShapeNode MyShapeNode;
// Vertex buffer and index buffer associated with the ground and cube geometry
static shared_ptr<Geometry> g_ground, g_cube, g_sphere;
static shared_ptr<SimpleGeometryPN> g_cubeGeometryPN;
// --------- Scene
static const Cvec3 g_light1(2.0, 3.0, 14.0), g_light2(-2, 3.0, -14.0); // define two lights positions in world space
static shared_ptr<SgTransformNode> g_light1Node, g_light2Node;
static shared_ptr<SgRootNode> g_world;
static shared_ptr<SgRbtNode> g_skyNode, g_groundNode, g_mesh_cube, g_robot1Node, g_robot2Node;
static shared_ptr<SgRbtNode> g_currentCameraNode;
static shared_ptr<SgRbtNode> g_currentPickedRbtNode;
static int g_msBetweenKeyFrames = 2000;
static int g_animateFramesPerSecond = 60;
static bool animating = false;
static const Cvec3 g_gravity(0, -0.5, 0); // gavity vector
static double g_timeStep = 0.02;
static double g_numStepsPerFrame = 10;
static double g_damping = 0.96;
static double g_stiffness = 4;
static int g_simulationsPerSecond = 60;
static bool g_shellNeedsUpdate = false;
static RigTForm bunnyTransform;
static std::vector<Cvec3> g_tipStartPos;
static std::vector<Cvec3> g_tipPos, // should be hair tip pos in world-space coordinates
g_tipVelocity; // should be hair tip velocity in world-space coordinates
static bool bunnyTransformSet = false;
///////////////// END OF G L O B A L S //////////////////////////////////////////////////
Cvec3 bunny2world(Cvec3 bunnyVec) {
return Cvec3(bunnyTransform * Cvec4(bunnyVec, 1));
}
Cvec3 world2bunny(Cvec3 worldVec) {
return Cvec3(inv(bunnyTransform) * Cvec4(worldVec, 1));
}
static void updateShellGeometry() {
float xs[] = {0, g_hairyness, 0};
float ys[] = {0, 0, g_hairyness};
vector<Cvec3> prevPos;
prevPos.resize(g_bunnyMesh.getNumFaces() * 3);
for (int level = 0; level < g_numShells; ++level) {
int counter = 0;
vector<VertexPNX> verts;
for (int i = 0; i < g_bunnyMesh.getNumFaces(); ++i) {
const Mesh::Face f = g_bunnyMesh.getFace(i);
for (int j = 0; j < f.getNumVertices(); ++j) {
const Mesh::Vertex v = f.getVertex(j);
int index = v.getIndex();
Cvec3 pos = v.getPosition();
Cvec3 normal = v.getNormal();
Cvec2 c = Cvec2(xs[j], ys[j]);
Cvec3 n = normal * g_furHeight / g_numShells;
Cvec3 s = pos + (n * g_numShells);
Cvec3 t = world2bunny(g_tipPos[index]);
Cvec3 d = (t - s) / ((g_numShells + 1) * g_numShells / 2);
/* Cvec3 d = (world2bunny(g_tipPos[index]) - (normal * g_furHeight)) / (g_numShells - 1); */
if (level == 0) {
prevPos[counter] = pos;
verts.push_back(VertexPNX(pos, n, c));
}
else {
Cvec3 new_position = prevPos[counter] + n + (d * level);
verts.push_back(VertexPNX(new_position, new_position - prevPos[counter], c));
prevPos[counter] = new_position;
}
++counter;
}
}
int numVertices = verts.size();
g_bunnyShellGeometries[level]->upload(&verts[0], numVertices);
verts.clear();
}
}
static void hairsSimulationCallback(int dontCare) {
g_shellNeedsUpdate = true;
bunnyTransformSet = true;
bunnyTransform = getPathAccumRbt(g_world, g_bunnyNode);
for (int q = 0; q < g_numStepsPerFrame; ++q) {
for (int i = 0; i < g_bunnyMesh.getNumVertices(); ++i) {
Cvec3 pos = bunny2world(g_bunnyMesh.getVertex(i).getPosition());
Cvec3 spring = (g_tipStartPos[i] - g_tipPos[i]) * g_stiffness;
Cvec3 force = g_gravity + spring;
g_tipPos[i] += g_tipVelocity[i] * g_timeStep;
g_tipPos[i] = pos + (normalize(g_tipPos[i] - pos) * g_furHeight);
g_tipVelocity[i] = (g_tipVelocity[i] + (force * g_timeStep)) * g_damping;
}
}
// schedule this to get called again
glutTimerFunc(1000/g_simulationsPerSecond, hairsSimulationCallback, 0);
/* glutPostRedisplay(); // signal redisplaying */
}
// New function that initialize the dynamics simulation
static void initSimulation() {
bunnyTransformSet = true;
bunnyTransform = (getPathAccumRbt(g_world, g_bunnyNode));
g_tipPos.resize(g_bunnyMesh.getNumVertices(), Cvec3(0));
g_tipStartPos.resize(g_bunnyMesh.getNumVertices(), Cvec3(0));
g_tipVelocity = g_tipPos;
// TASK 1 TODO: initialize g_tipPos to "at-rest" hair tips in world coordinates
for (int i = 0; i < g_bunnyMesh.getNumVertices(); ++i) {
const Mesh::Vertex v = g_bunnyMesh.getVertex(i);
Cvec3 pos = v.getPosition();
Cvec3 normal = v.getNormal();
g_tipPos[i] = bunny2world(pos + normal * g_furHeight);
g_tipStartPos[i] = bunny2world(pos + normal * g_furHeight);
}
// Starts hair tip simulation
hairsSimulationCallback(0);
}
static void make_frame() {
vector<shared_ptr<SgRbtNode> > graph_vector;
dumpSgRbtNodes(g_world, graph_vector);
vector<RigTForm> new_frame;
for (int i = 0; i < graph_vector.size(); ++i) {
new_frame.push_back(graph_vector[i]->getRbt());
}
if (cur_frame == KF_UNDEF || cur_frame == key_frames.size() - 1) {
// undef is -1, so adding one sets the position to 0
key_frames.push_back(new_frame);
++cur_frame;
}
else {
list<vector<RigTForm> >::iterator it = key_frames.begin();
advance(it, cur_frame);
key_frames.insert(it, new_frame);
++cur_frame;
}
return;
}
static void next_frame() {
if (cur_frame == KF_UNDEF || cur_frame == key_frames.size() - 1) {
cout << "can't advance frame" << endl;
return;
}
++cur_frame;
list<vector<RigTForm> >::iterator it = key_frames.begin();
advance(it, cur_frame);
// this linked list of arrays is getting the previous vectors stacked on top of each other
fillSgRbtNodes(g_world, *it);
return;
}
static void prev_frame() {
if (cur_frame < 1) {
cout << "can't rewind frame "<< endl;
return;
}
--cur_frame;
list<vector<RigTForm> >::iterator it = key_frames.begin();
advance(it, cur_frame);
fillSgRbtNodes(g_world, *it);
return;
}
static void delete_frame() {
if (cur_frame == KF_UNDEF) {
return;
}
list<vector<RigTForm> >::iterator it = key_frames.begin();
advance(it, cur_frame);
key_frames.erase(it);
if (key_frames.empty()) {
cur_frame = KF_UNDEF;
return;
}
else if (cur_frame != 0) {
--cur_frame;
}
fillSgRbtNodes(g_world, *it);
return;
}
static void write_frame() {
list<vector<RigTForm> >::iterator it = key_frames.begin();
FILE* output = fopen("animation.txt", "w");
int n = (*it).size();
fprintf(output, "%d %d\n", key_frames.size(), n);
while (it != key_frames.end()) {
vector<RigTForm> frame = *it;
for (int i = 0; i < frame.size(); ++i) {
RigTForm r = frame[i];
Cvec3 transFact = r.getTranslation();
Quat linFact = r.getRotation();
fprintf(output, "%.3f %.3f %.3f %.3f %.3f %.3f %.3f\n",
transFact[0], transFact[1], transFact[2],
linFact[0], linFact[1], linFact[2], linFact[3]
);
}
++it;
}
fclose(output);
}
static void read_frame() {
FILE* input = fopen("animation.txt", "r");
if (input == NULL) {
return;
}
int nFrames;
int nRbts;
fscanf(input, "%d %d\n", &nFrames, &nRbts);
key_frames.clear();
for (int i = 0; i < nFrames; ++i) {
vector<RigTForm> frame;
for (int j = 0; j < nRbts; ++j) {
Cvec3 transFact;
Quat linFact;
fscanf(input, "%lf %lf %lf %lf %lf %lf %lf\n",
&transFact[0], &transFact[1], &transFact[2],
&linFact[0], &linFact[1], &linFact[2], &linFact[3]
);
RigTForm r = RigTForm(transFact, linFact);
frame.push_back(r);
}
key_frames.push_back(frame);
}
cur_frame = 0;
fillSgRbtNodes(g_world, key_frames.front());
fclose(input);
}
static Quat slerp(Quat src, Quat dest, float alpha);
static Cvec3 lerp(Cvec3 src, Cvec3 dest, float alpha);
static Quat cond_neg(Quat q);
static Quat qpow(Quat q, float alpha);
Cvec3 getDTrans(Cvec3 c_i_1, Cvec3 c_i_neg_1, Cvec3 c_i) {
return (c_i_1 - c_i_neg_1)/6 + c_i;
}
Cvec3 getETrans(Cvec3 c_i_2, Cvec3 c_i_1, Cvec3 c_i) {
return (c_i_2 - c_i)/-6 + c_i_1;
}
Cvec3 bezierTrans(Cvec3 c_i_neg_1, Cvec3 c_i, Cvec3 c_i_1, Cvec3 c_i_2, int i, float t) {
Cvec3 d = getDTrans(c_i_1, c_i_neg_1, c_i);
Cvec3 e = getETrans(c_i_2, c_i_1, c_i);
Cvec3 f = c_i*(1 - t + i) + d*(t - i);
Cvec3 g = d*(1 - t + i) + e*(t - i);
Cvec3 h = e*(1 - t + i) + c_i_1*(t - i);
Cvec3 m = f*(1 - t + i) + g*(t - i);
Cvec3 n = g*(1 - t + i) + h*(t - i);
return m*(1 - t + i) + n*(t - i);
}
Quat getDRot(Quat c_i_1, Quat c_i_neg_1, Quat c_i) {
return qpow(cond_neg(c_i_1 * inv(c_i_neg_1)), 1.0/6.0) * c_i;
}
Quat getERot(Quat c_i_2, Quat c_i_1, Quat c_i) {
return qpow(cond_neg(c_i_2 * inv(c_i)), -1.0/6.0) * c_i_1;
}
Quat bezierRot(Quat c_i_neg_1, Quat c_i, Quat c_i_1, Quat c_i_2, int i, float t) {
Quat d = getDRot(c_i_1, c_i_neg_1, c_i);
Quat e = getERot(c_i_2, c_i_1, c_i);
Quat f = slerp(c_i, d, t -i);
Quat g = slerp(d, e, t - i);
Quat h = slerp(e, c_i_1, t - i);
Quat m = slerp(f, g, t - i);
Quat n = slerp(g, h, t - i);
return slerp(m, n, t - i);
}
bool interpolateAndDisplay(float t) {
list<vector<RigTForm> >::iterator it = key_frames.begin();
advance(it, (int) t);
++it;
vector<RigTForm> frame_1 = *it;
++it;
vector<RigTForm> frame_2 = *it;
++it;
if (it == key_frames.end()) {
return true;
}
vector<RigTForm> post_frame = *it;
// minus operator not overloaded for iterators. sad face.
--it; --it; --it;
vector<RigTForm> pre_frame = *it;
// d ci ci+1 e
float alpha = t - (int) t;
vector<RigTForm> frame;
int n = frame_1.size();
for (int i = 0; i < n; ++i) {
Cvec3 c_i_neg_1 = pre_frame[i].getTranslation();
Cvec3 c_i = frame_1[i].getTranslation();
Cvec3 c_i_1 = frame_2[i].getTranslation();
Cvec3 c_i_2 = post_frame[i].getTranslation();
Quat c_i_neg_1_r = pre_frame[i].getRotation();
Quat c_i_r = frame_1[i].getRotation();
Quat c_i_1_r = frame_2[i].getRotation();
Quat c_i_2_r = post_frame[i].getRotation();
Cvec3 trans = bezierTrans(c_i_neg_1, c_i, c_i_1, c_i_2, (int) t, t);
Quat rot = bezierRot(c_i_neg_1_r, c_i_r, c_i_1_r, c_i_2_r, (int) t, t);
frame.push_back(RigTForm(trans, rot));
}
fillSgRbtNodes(g_world, frame);
glutPostRedisplay();
return false;
}
static void animateTimerCallback(int ms) {
float t = (float) ms / (float) g_msBetweenKeyFrames;
bool endReached = interpolateAndDisplay(t);
if (!endReached) {
glutTimerFunc(1000/g_animateFramesPerSecond,
animateTimerCallback,
ms + 1000/g_animateFramesPerSecond);
}
else {
animating = false;
cur_frame = key_frames.size() - 2;
glutPostRedisplay();
}
}
static Cvec3 getFaceVertex(vector<Cvec3> & verts) {
// pass in the n vertices surrounding a face
float m_f = (float(1)/verts.size());
Cvec3 out = Cvec3 (0,0,0);
for (int i = 0; i < verts.size(); ++i) {
out += verts[i];
}
out *= m_f;
return out;
}
static Cvec3 getEdgeVertex(vector<Cvec3> & verts) {
// pass in two vertices on an edge, and the two face vertices of the
// faces they have in common
return getFaceVertex(verts);
}
static Cvec3 getVertexVertex(Cvec3 v, vector<Cvec3> & verts, vector<Cvec3> & faceverts) {
// pass in a vertex v, adjacent vertices verts, and
// the vertices of all adjacent faces faceverts.
Cvec3 out = Cvec3(0,0,0);
int n_v = verts.size();
out += v * (float(n_v - 2) / n_v);
Cvec3 out2 = Cvec3(0,0,0);
for (int i = 0; i < n_v; ++i) {
out2 += verts[i] + faceverts[i];
}
return out + (out2 * (float(1)/(n_v * n_v)));
}
static bool first_run = true;
Cvec3 get_T(Cvec3 p, Cvec3 n_hat) {
if (first_run) {
// return S if first run
first_run = false;
return p + ((n_hat) * g_furHeight);
}
}
static void simpleShadeCube(Mesh& mesh);
static void shadeCube(Mesh& mesh);
static void initBunnyMeshes() {
g_bunnyMesh.load("bunny.mesh");
// TODO: Init the per vertex normal of g_bunnyMesh, using codes from asst7
// ...
shadeCube(g_bunnyMesh);
// cout << "Finished shading bunny" << endl;
// TODO: Initialize g_bunnyGeometry from g_bunnyMesh, similar to
vector<VertexPN> verts;
for (int i = 0; i < g_bunnyMesh.getNumFaces(); ++i) {
const Mesh::Face f = g_bunnyMesh.getFace(i);
Cvec3 pos;
Cvec3 normal;
if (g_flat)
normal = f.getNormal();
for (int j = 0; j < f.getNumVertices(); ++j) {
const Mesh::Vertex v = f.getVertex(j);
pos = v.getPosition();
if (!g_flat)
normal = v.getNormal();
verts.push_back(VertexPN(pos, normal));
}
}
// add vertices to bunny geometry
int numVertices = verts.size();
g_bunnyGeometry.reset(new SimpleGeometryPN());
g_bunnyGeometry->upload(&verts[0], numVertices);
// Now allocate array of SimpleGeometryPNX to for shells, one per layer
g_bunnyShellGeometries.resize(g_numShells);
for (int i = 0; i < g_numShells; ++i) {
g_bunnyShellGeometries[i].reset(new SimpleGeometryPNX());
}
}
static void initGround() {
int ibLen, vbLen;
getPlaneVbIbLen(vbLen, ibLen);
// Temporary storage for cube Geometry
vector<VertexPNTBX> vtx(vbLen);
vector<unsigned short> idx(ibLen);
makePlane(g_groundSize*2, vtx.begin(), idx.begin());
g_ground.reset(new SimpleIndexedGeometryPNTBX(&vtx[0], &idx[0], vbLen, ibLen));
}
static void simpleShadeCube(Mesh& mesh) {
Cvec3 normal = Cvec3(0, 1, 0);
for (int i = 0; i < mesh.getNumFaces(); ++i) {
const Mesh::Face f = mesh.getFace(i);
Cvec3 facenorm = f.getNormal();
for (int j = 0; j < f.getNumVertices(); ++j) {
const Mesh::Vertex v = f.getVertex(j);
v.setNormal(facenorm);
}
}
}
static void shadeCube(Mesh& mesh) {
Cvec3 normal = Cvec3(0, 0, 0);
for (int i = 0; i < mesh.getNumVertices(); ++i) {
mesh.getVertex(i).setNormal(normal);
}
for (int i = 0; i < mesh.getNumFaces(); ++i) {
const Mesh::Face f = mesh.getFace(i);
Cvec3 facenorm = f.getNormal();
for (int j = 0; j < f.getNumVertices(); ++j) {
const Mesh::Vertex v = f.getVertex(j);
v.setNormal(facenorm + v.getNormal());
}
}
for (int i = 0; i < mesh.getNumVertices(); ++i) {
const Mesh::Vertex v = mesh.getVertex(i);
if (norm2(v.getNormal()) > .001) {
v.setNormal(normalize(v.getNormal()));
}
}
}
void collectEdgeVertices(Mesh& m);
void collectFaceVertices(Mesh& m);
void collectVertexVertices(Mesh& m);
static void initCubeMesh() {
if (!meshLoaded) {
cubeMesh.load("./cube.mesh");
meshLoaded = true;
}
// set normals
shadeCube(cubeMesh);
// collect vertices from each face and map quads to triangles
vector<VertexPN> verts;
for (int i = 0; i < cubeMesh.getNumFaces(); ++i) {
const Mesh::Face f = cubeMesh.getFace(i);
Cvec3 pos;
Cvec3 normal;
if (g_flat)
normal = f.getNormal();
for (int j = 0; j < f.getNumVertices(); ++j) {
const Mesh::Vertex v = f.getVertex(j);
pos = v.getPosition();
if (!g_flat)
normal = v.getNormal();
verts.push_back(VertexPN(pos, normal));
if (j == 2) {
verts.push_back(VertexPN(pos, normal));
}
}
const Mesh::Vertex v = f.getVertex(0);
pos = v.getPosition();
if (!g_flat)
normal = v.getNormal();
verts.push_back(VertexPN(pos, normal));
}
// add vertices to cube geometry
int numVertices = verts.size();
if (!g_cubeGeometryPN) {
g_cubeGeometryPN.reset(new SimpleGeometryPN());
}
g_cubeGeometryPN->upload(&verts[0], numVertices);
}
static void initCubeAnimation() {
// set the speeds of each vertex
srand(time(NULL));
for (int i = 0; i < cubeMesh.getNumVertices(); ++i) {
// create random speed
vertex_speeds.push_back((double) rand() / RAND_MAX);
Cvec3 pos = cubeMesh.getVertex(i).getPosition();
// store sign
int xSign = (pos[0] < 0) ? -1 : 1;
int ySign = (pos[1] < 0) ? -1 : 1;
int zSign = (pos[2] < 0) ? -1 : 1;
vector<int> signs;
signs.push_back(xSign);
signs.push_back(ySign);
signs.push_back(zSign);
vertex_signs.push_back(signs);
}
}
static void initCubes() {
int ibLen, vbLen;
getCubeVbIbLen(vbLen, ibLen);
// Temporary storage for cube Geometry
vector<VertexPNTBX> vtx(vbLen);
vector<unsigned short> idx(ibLen);
makeCube(1, vtx.begin(), idx.begin());
g_cube.reset(new SimpleIndexedGeometryPNTBX(&vtx[0], &idx[0], vbLen, ibLen));
}
static void initSphere() {
int ibLen, vbLen;
getSphereVbIbLen(20, 10, vbLen, ibLen);
// Temporary storage for sphere Geometry
vector<VertexPNTBX> vtx(vbLen);
vector<unsigned short> idx(ibLen);
makeSphere(1, 20, 10, vtx.begin(), idx.begin());
g_sphere.reset(new SimpleIndexedGeometryPNTBX(&vtx[0], &idx[0], vtx.size(), idx.size()));
}
static void initRobots() {
// Init whatever geometry needed for the robots
}
// takes a projection matrix and send to the the shaders
inline void sendProjectionMatrix(Uniforms& uniforms, const Matrix4& projMatrix) {
uniforms.put("uProjMatrix", projMatrix);
}
// update g_frustFovY from g_frustMinFov, g_windowWidth, and g_windowHeight
static void updateFrustFovY() {
if (g_windowWidth >= g_windowHeight)
g_frustFovY = g_frustMinFov;
else {
const double RAD_PER_DEG = 0.5 * CS175_PI/180;
g_frustFovY = atan2(sin(g_frustMinFov * RAD_PER_DEG) * g_windowHeight / g_windowWidth, cos(g_frustMinFov * RAD_PER_DEG)) / RAD_PER_DEG;
}
}
static void animateCube(int ms) {
float t = (float) ms / (float) g_msBetweenKeyFrames;
// scale all vertices in cube
for (int i = 0; i < cubeMesh.getNumVertices(); ++i) {
const Mesh::Vertex v = cubeMesh.getVertex(i);
Cvec3 pos = v.getPosition();
double factor = (1 + (float(g_div_level)/10)) * ((-1 * sin((double) (g_horiz_scale * ms) / (1000 * (vertex_speeds[i] + .5))) + 1) / 2 + .5);
pos[0] = vertex_signs[i][0] * (factor / sqrt(3));
pos[1] = vertex_signs[i][1] * (factor / sqrt(3));
pos[2] = vertex_signs[i][2] * (factor / sqrt(3));
v.setPosition(pos);
}
// copy mesh to temporary mesh for rendering
Mesh renderMesh = cubeMesh;
// subdivision
for (int i = 0; i < g_div_level; ++i) {
collectFaceVertices(renderMesh);
collectEdgeVertices(renderMesh);
collectVertexVertices(renderMesh);
renderMesh.subdivide();
}
// set normals
shadeCube(renderMesh);
// collect vertices for each face
vector<VertexPN> verts;
int q = 0;
for (int i = 0; i < renderMesh.getNumFaces(); ++i) {
const Mesh::Face f = renderMesh.getFace(i);
Cvec3 pos;
Cvec3 normal;
for (int j = 0; j < f.getNumVertices(); ++j) {
const Mesh::Vertex v = f.getVertex(j);
pos = v.getPosition();
if (!g_flat)
normal = v.getNormal();
else
normal = f.getNormal();
verts.push_back(VertexPN(pos, normal));
if (j == 2) {
verts.push_back(VertexPN(pos, normal));
}
}
const Mesh::Vertex v = f.getVertex(0);
pos = v.getPosition();
if (!g_flat)
normal = v.getNormal();
else
normal = f.getNormal();
verts.push_back(VertexPN(pos, normal));
}
// dump into geometry
int numVertices = verts.size();
g_cubeGeometryPN->upload(&verts[0], numVertices);
glutPostRedisplay();
glutTimerFunc(1000/g_animateFramesPerSecond,
animateCube,
ms + 1000/g_animateFramesPerSecond);
}
void collectFaceVertices(Mesh& m) {
for (int i = 0; i < m.getNumFaces(); ++i) {
Mesh::Face f = m.getFace(i);
vector<Cvec3> vertices;
for (int j = 0; j < f.getNumVertices(); ++j) {
vertices.push_back(f.getVertex(j).getPosition());
}
m.setNewFaceVertex(f, getFaceVertex(vertices));
}
}
void collectEdgeVertices(Mesh& m) {
for (int i = 0; i < m.getNumEdges(); ++i) {
Mesh::Edge e = m.getEdge(i);
// get faces adjacent to edges
Cvec3 f0 = m.getNewFaceVertex(e.getFace(0));
Cvec3 f1 = m.getNewFaceVertex(e.getFace(1));
Cvec3 pos0 = e.getVertex(0).getPosition();
Cvec3 pos1 = e.getVertex(1).getPosition();
vector<Cvec3> vertices;
vertices.push_back(f0);
vertices.push_back(f1);
vertices.push_back(pos0);
vertices.push_back(pos1);
Cvec3 newEdge = getEdgeVertex(vertices);
m.setNewEdgeVertex(e, newEdge);
}
}
void collectVertexVertices(Mesh& m) {
vector<vector<Cvec3> > vertexVertices;
for (int i = 0; i < m.getNumVertices(); ++i) {
const Mesh::Vertex v = m.getVertex(i);
Mesh::VertexIterator it(v.getIterator()), it0(it);
vector<Cvec3> vertices;
vector<Cvec3> faces;
do {
vertices.push_back(it.getVertex().getPosition());
faces.push_back(m.getNewFaceVertex(it.getFace()));
}
while (++it != it0); // go around once the 1ring
Cvec3 vertex = getVertexVertex(v.getPosition(), vertices, faces);
m.setNewVertexVertex(v, vertex);
}
}
static Cvec3 lerp(Cvec3 src, Cvec3 dest, float alpha) {
assert(0 <= alpha && alpha <= 1.0);
float xout = ((1-alpha) * src[0]) + (alpha * dest[0]);
float yout = ((1-alpha) * src[1]) + (alpha * dest[1]);
float zout = ((1-alpha) * src[2]) + (alpha * dest[2]);
return Cvec3(xout, yout, zout);
}
static Quat cond_neg(Quat q) {
if (q[0] < 0) {
return Quat(-q[0], -q[1], -q[2], -q[3]);
}
return q;
}
static Quat qpow(Quat q, float alpha) {
Cvec3 axis = Cvec3(q[1], q[2], q[3]);
float theta = atan2(sqrt(norm2(axis)), q[0]);
if (norm2(axis) <= .001) {
return Quat();
}
axis = normalize(axis);
float q_outw = cos(alpha * theta);
float q_outx = axis[0] * sin(alpha * theta);
float q_outy = axis[1] * sin(alpha * theta);
float q_outz = axis[2] * sin(alpha * theta);
return normalize(Quat(q_outw, q_outx, q_outy, q_outz));
}
static Quat slerp(Quat src, Quat dest, float alpha) {
assert(0 <= alpha && alpha <= 1.0);
return normalize(qpow(cond_neg(dest * inv(src)), alpha) * src);
}
static Matrix4 makeProjectionMatrix() {
return Matrix4::makeProjection(
g_frustFovY, g_windowWidth / static_cast <double> (g_windowHeight),
g_frustNear, g_frustFar);
}
enum ManipMode {
ARCBALL_ON_PICKED,
ARCBALL_ON_SKY,
EGO_MOTION
};
static ManipMode getManipMode() {
// if nothing is picked or the picked transform is the transfrom we are viewing from
if (g_currentPickedRbtNode == NULL || g_currentPickedRbtNode == g_currentCameraNode) {
if (g_currentCameraNode == g_skyNode && g_activeCameraFrame == WORLD_SKY)
return ARCBALL_ON_SKY;
else
return EGO_MOTION;
}
else
return ARCBALL_ON_PICKED;
}
static bool shouldUseArcball() {
return getManipMode() != EGO_MOTION;
}
// The translation part of the aux frame either comes from the current
// active object, or is the identity matrix when
static RigTForm getArcballRbt() {
switch (getManipMode()) {
case ARCBALL_ON_PICKED:
return getPathAccumRbt(g_world, g_currentPickedRbtNode);
case ARCBALL_ON_SKY:
return RigTForm();
case EGO_MOTION:
return getPathAccumRbt(g_world, g_currentCameraNode);
default:
throw runtime_error("Invalid ManipMode");
}
}
static void updateArcballScale() {
RigTForm arcballEye = inv(getPathAccumRbt(g_world, g_currentCameraNode)) * getArcballRbt();
double depth = arcballEye.getTranslation()[2];
if (depth > -CS175_EPS)
g_arcballScale = 0.02;
else
g_arcballScale = getScreenToEyeScale(depth, g_frustFovY, g_windowHeight);
}
static void drawArcBall(Uniforms& uniforms) {
// switch to wire frame mode
glPolygonMode(GL_FRONT_AND_BACK, GL_LINE);
RigTForm arcballEye = inv(getPathAccumRbt(g_world, g_currentCameraNode)) * getArcballRbt();
Matrix4 MVM = rigTFormToMatrix(arcballEye) * Matrix4::makeScale(Cvec3(1, 1, 1) * g_arcballScale * g_arcballScreenRadius);
sendModelViewNormalMatrix(uniforms, MVM, normalMatrix(MVM));
uniforms.put("uColor", Cvec3 (0.27, 0.82, 0.35));
// switch back to solid mode
g_arcballMat->draw(*g_sphere, uniforms);
}
static void drawStuff(bool picking) {
Uniforms uniforms;
// if we are not translating, update arcball scale
if (!(g_mouseMClickButton || (g_mouseLClickButton && g_mouseRClickButton) || (g_mouseLClickButton && !g_mouseRClickButton && g_spaceDown)))
updateArcballScale();
// build & send proj. matrix to vshader
const Matrix4 projmat = makeProjectionMatrix();
sendProjectionMatrix(uniforms, projmat);
const RigTForm eyeRbt = getPathAccumRbt(g_world, g_currentCameraNode);
const RigTForm invEyeRbt = inv(eyeRbt);
// const Cvec3 eyeLight1 = Cvec3(invEyeRbt * Cvec4(g_light1, 1));
// const Cvec3 eyeLight2 = Cvec3(invEyeRbt * Cvec4(g_light2, 1));
const Cvec3 eyeLight1 = getPathAccumRbt(g_world, g_light1Node).getTranslation();
const Cvec3 eyeLight2 = getPathAccumRbt(g_world, g_light2Node).getTranslation();
uniforms.put("uLight", (Cvec3) (invEyeRbt * Cvec4(eyeLight1,1)));
uniforms.put("uLight2", (Cvec3) (invEyeRbt * Cvec4(eyeLight2,1)));