-
Notifications
You must be signed in to change notification settings - Fork 1
/
scene-start.cpp
857 lines (685 loc) · 32 KB
/
scene-start.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
#include "Angel.h"
#include <stdlib.h>
#include <dirent.h>
#include <time.h>
// Open Asset Importer header files (in ../../assimp--3.0.1270/include)
// This is a standard open source library for loading meshes, see gnatidread.h
#include <assimp/cimport.h>
#include <assimp/scene.h>
#include <assimp/postprocess.h>
GLint windowHeight=640, windowWidth=960;
// gnatidread.cpp is the CITS3003 "Graphics n Animation Tool Interface & Data
// Reader" code. This file contains parts of the code that you shouldn't need
// to modify (but, you can).
#include "gnatidread.h"
#include "gnatidread2.h" // PART 2D.B. Include the additional gnatidread file
using namespace std; // Import the C++ standard functions (e.g., min)
// IDs for the GLSL program and GLSL variables.
GLuint shaderProgram; // The number identifying the GLSL shader program
GLuint vPosition, vNormal, vTexCoord; // IDs for vshader input vars (from glGetAttribLocation)
GLuint projectionU, modelViewU; // IDs for uniform variables (from glGetUniformLocation)
// PART 2D.3. Additional globsl variables
GLuint vBoneIDs, vBoneWeights; // IDs for vshader input vars (from glGetAttribLocation)
GLuint boneTransformsU; // IDs for uniform variables (from glGetUniformLocation)
static float viewDist = 1.5; // Distance from the camera to the centre of the scene
static float camRotSidewaysDeg=0; // rotates the camera sideways around the centre
static float camRotUpAndOverDeg=20; // rotates the camera up and over the centre.
mat4 projection; // Projection matrix - set in the reshape function
mat4 view; // View matrix - set in the display function.
// These are used to set the window title
char lab[] = "Project1";
char *programName = NULL; // Set in main
int numDisplayCalls = 0; // Used to calculate the number of frames per second
//------Meshes----------------------------------------------------------------
// Uses the type aiMesh from ../../assimp--3.0.1270/include/assimp/mesh.h
// (numMeshes is defined in gnatidread.h)
aiMesh* meshes[numMeshes]; // For each mesh we have a pointer to the mesh to draw
GLuint vaoIDs[numMeshes]; // and a corresponding VAO ID from glGenVertexArrays
const aiScene* scenes[numMeshes]; // PART 2D.4. Stores extra scene related info for each loaded mesh
// -----Textures--------------------------------------------------------------
// (numTextures is defined in gnatidread.h)
texture* textures[numTextures]; // An array of texture pointers - see gnatidread.h
GLuint textureIDs[numTextures]; // Stores the IDs returned by glGenTextures
//------Scene Objects---------------------------------------------------------
//
// For each object in a scene we store the following
// Note: the following is exactly what the sample solution uses, you can do things differently if you want.
typedef struct {
vec4 loc;
float scale;
float angles[3]; // rotations around X, Y and Z axes.
float diffuse, specular, ambient; // Amount of each light component
float shine;
vec3 rgb;
float brightness; // Multiplies all colours
int meshId;
int texId;
float texScale;
// PART 2D. Animation variables
bool hasAnim; // If the obj has animation
int frames; // The number of frames
} SceneObject;
const int maxObjects = 1024; // Scenes with more than 1024 objects seem unlikely
SceneObject sceneObjs[maxObjects]; // An array storing the objects currently in the scene.
int nObjects = 0; // How many objects are currenly in the scene.
int currObject = -1; // The current object
int toolObj = -1; // The object currently being modified
int delObjects = 0; // How many deleted objects
// PART 2D. Global animation variables
float POSE_TIME = 0.0;
float ANIM_SPEED = 1; // Speed of animation from 0 to 10
bool ANIM_PAUSED = false;
static void makeMenu(); // PART J.2. Selection menu update. Prevent compilation erorr
//----------------------------------------------------------------------------
//
// Loads a texture by number, and binds it for later use.
void loadTextureIfNotAlreadyLoaded(int i) {
if (textures[i] != NULL) return; // The texture is already loaded.
textures[i] = loadTextureNum(i); CheckError();
glActiveTexture(GL_TEXTURE0); CheckError();
// Based on: http://www.opengl.org/wiki/Common_Mistakes
glBindTexture(GL_TEXTURE_2D, textureIDs[i]); CheckError();
glTexImage2D(GL_TEXTURE_2D, 0, GL_RGB, textures[i]->width, textures[i]->height,
0, GL_RGB, GL_UNSIGNED_BYTE, textures[i]->rgbData); CheckError();
glGenerateMipmap(GL_TEXTURE_2D); CheckError();
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT); CheckError();
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT); CheckError();
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR); CheckError();
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR_MIPMAP_LINEAR); CheckError();
glBindTexture(GL_TEXTURE_2D, 0); CheckError(); // Back to default texture
}
//------Mesh loading----------------------------------------------------------
//
// The following uses the Open Asset Importer library via loadMesh in
// gnatidread.h to load models in .x format, including vertex positions,
// normals, and texture coordinates.
// You shouldn't need to modify this - it's called from drawMesh below.
void loadMeshIfNotAlreadyLoaded(int meshNumber)
{
if (meshNumber>=numMeshes || meshNumber < 0) {
printf("Error - no such model number");
exit(1);
}
if (meshes[meshNumber] != NULL)
return; // Already loaded
// PART 2D.5. Stores the scene for the mesh
const aiScene* scene = loadScene(meshNumber);
scenes[meshNumber] = scene;
aiMesh* mesh = scene->mMeshes[0];
meshes[meshNumber] = mesh;
glBindVertexArrayAPPLE(vaoIDs[meshNumber]);
// Create and initialize a buffer object for positions and texture coordinates, initially empty.
// mesh->mTextureCoords[0] has space for up to 3 dimensions, but we only need 2.
GLuint buffer[1];
glGenBuffers(1, buffer);
glBindBuffer(GL_ARRAY_BUFFER, buffer[0]);
glBufferData(GL_ARRAY_BUFFER, sizeof(float)*(3+3+3)*mesh->mNumVertices, NULL, GL_STATIC_DRAW);
int nVerts = mesh->mNumVertices;
// Next, we load the position and texCoord data in parts.
glBufferSubData(GL_ARRAY_BUFFER, 0, sizeof(float)*3*nVerts, mesh->mVertices);
glBufferSubData(GL_ARRAY_BUFFER, sizeof(float)*3*nVerts, sizeof(float)*3*nVerts, mesh->mTextureCoords[0]);
glBufferSubData(GL_ARRAY_BUFFER, sizeof(float)*6*nVerts, sizeof(float)*3*nVerts, mesh->mNormals);
// Load the element index data
GLuint elements[mesh->mNumFaces*3];
for (GLuint i=0; i < mesh->mNumFaces; i++) {
elements[i*3] = mesh->mFaces[i].mIndices[0];
elements[i*3+1] = mesh->mFaces[i].mIndices[1];
elements[i*3+2] = mesh->mFaces[i].mIndices[2];
}
GLuint elementBufferId[1];
glGenBuffers(1, elementBufferId);
glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, elementBufferId[0]);
glBufferData(GL_ELEMENT_ARRAY_BUFFER, sizeof(GLuint) * mesh->mNumFaces * 3, elements, GL_STATIC_DRAW);
// vPosition it actually 4D - the conversion sets the fourth dimension (i.e. w) to 1.0
glVertexAttribPointer(vPosition, 3, GL_FLOAT, GL_FALSE, 0, BUFFER_OFFSET(0));
glEnableVertexAttribArray(vPosition);
// vTexCoord is actually 2D - the third dimension is ignored (it's always 0.0)
glVertexAttribPointer(vTexCoord, 3, GL_FLOAT, GL_FALSE, 0, BUFFER_OFFSET(sizeof(float)*3*mesh->mNumVertices));
glEnableVertexAttribArray(vTexCoord);
glVertexAttribPointer(vNormal, 3, GL_FLOAT, GL_FALSE, 0, BUFFER_OFFSET(sizeof(float)*6*mesh->mNumVertices));
glEnableVertexAttribArray(vNormal);
CheckError();
// PART 2D.6. Get boneIDs and boneWeights for each vertex from the imported mesh data
GLint boneIDs[mesh->mNumVertices][4];
GLfloat boneWeights[mesh->mNumVertices][4];
getBonesAffectingEachVertex(mesh, boneIDs, boneWeights);
GLuint buffers[2];
glGenBuffers(2, buffers); // Add two VBOs
glBindBuffer(GL_ARRAY_BUFFER, buffers[0]); CheckError();
glBufferData(GL_ARRAY_BUFFER, sizeof(int) * 4 * mesh->mNumVertices, boneIDs, GL_STATIC_DRAW); CheckError();
glVertexAttribPointer(vBoneIDs, 4, GL_INT, GL_FALSE, 0, BUFFER_OFFSET(0)); CheckError();
glEnableVertexAttribArray(vBoneIDs); CheckError();
glBindBuffer(GL_ARRAY_BUFFER, buffers[1]);
glBufferData(GL_ARRAY_BUFFER, sizeof(float) * 4 * mesh->mNumVertices, boneWeights, GL_STATIC_DRAW);
glVertexAttribPointer(vBoneWeights, 4, GL_FLOAT, GL_FALSE, 0, BUFFER_OFFSET(0));
glEnableVertexAttribArray(vBoneWeights); CheckError();
}
//----------------------------------------------------------------------------
static void mouseClickOrScroll(int button, int state, int x, int y)
{
if (button==GLUT_LEFT_BUTTON && state == GLUT_DOWN) {
if (glutGetModifiers()!=GLUT_ACTIVE_SHIFT) activateTool(button);
else activateTool(GLUT_LEFT_BUTTON);
}
else if (button==GLUT_LEFT_BUTTON && state == GLUT_UP) deactivateTool();
else if (button==GLUT_MIDDLE_BUTTON && state==GLUT_DOWN) { activateTool(button); }
else if (button==GLUT_MIDDLE_BUTTON && state==GLUT_UP) deactivateTool();
else if (button == 3) { // scroll up
viewDist = (viewDist < 0.0 ? viewDist : viewDist*0.8) - 0.05;
}
else if (button == 4) { // scroll down
viewDist = (viewDist < 0.0 ? viewDist : viewDist*1.25) + 0.05;
}
}
//----------------------------------------------------------------------------
static void mousePassiveMotion(int x, int y)
{
mouseX=x;
mouseY=y;
}
//----------------------------------------------------------------------------
mat2 camRotZ()
{
return rotZ(-camRotSidewaysDeg) * mat2(10.0, 0, 0, -10.0);
}
//------callback functions for doRotate below and later-----------------------
static void adjustCamrotsideViewdist(vec2 cv)
{
cout << cv << endl;
camRotSidewaysDeg+=cv[0]; viewDist+=cv[1];
}
static void adjustcamSideUp(vec2 su)
{
camRotSidewaysDeg+=su[0]; camRotUpAndOverDeg+=su[1];
}
static void adjustLocXZ(vec2 xz)
{
sceneObjs[toolObj].loc[0]+=xz[0]; sceneObjs[toolObj].loc[2]+=xz[1];
}
static void adjustScaleY(vec2 sy)
{
sceneObjs[toolObj].scale+=sy[0]; sceneObjs[toolObj].loc[1]+=sy[1];
}
//----------------------------------------------------------------------------
//------Set the mouse buttons to rotate the camera----------------------------
//------around the centre of the scene.---------------------------------------
//----------------------------------------------------------------------------
static void doRotate()
{
setToolCallbacks(adjustCamrotsideViewdist, mat2(400,0,0,-2),
adjustcamSideUp, mat2(400, 0, 0,-90));
}
//------Add an object to the scene--------------------------------------------
static void addObject(int id) {
if (nObjects >= maxObjects) return; // Potential fix to the Fatal Error: Out of Memory
vec2 currPos = currMouseXYworld(camRotSidewaysDeg);
sceneObjs[nObjects].loc[0] = currPos[0];
sceneObjs[nObjects].loc[1] = 0.0;
sceneObjs[nObjects].loc[2] = currPos[1];
sceneObjs[nObjects].loc[3] = 1.0;
sceneObjs[nObjects].frames = 1;
sceneObjs[nObjects].hasAnim = false;
if (id != 0 && id != 55)
sceneObjs[nObjects].scale = 0.005;
if (id == 56) {
sceneObjs[nObjects].scale *= 10; // PART 2C. Scale the human models by 10
sceneObjs[nObjects].frames = 300;
sceneObjs[nObjects].hasAnim = true;
}
if (id >= 57) {
sceneObjs[nObjects].scale *= 12; // Custom scaling for more reasonable sizing
sceneObjs[nObjects].frames = 250; // Custom frame rate
sceneObjs[nObjects].hasAnim = true;
}
sceneObjs[nObjects].rgb[0] = 0.7; sceneObjs[nObjects].rgb[1] = 0.7;
sceneObjs[nObjects].rgb[2] = 0.7; sceneObjs[nObjects].brightness = 1.0;
sceneObjs[nObjects].diffuse = 1.0; sceneObjs[nObjects].specular = 0.5;
sceneObjs[nObjects].ambient = 0.7; sceneObjs[nObjects].shine = 10.0;
sceneObjs[nObjects].angles[0] = 0.0;
sceneObjs[nObjects].angles[1] = 180.0;
sceneObjs[nObjects].angles[2] = 0.0;
sceneObjs[nObjects].meshId = id;
sceneObjs[nObjects].texId = rand() % numTextures;
sceneObjs[nObjects].texScale = 2.0;
toolObj = currObject = nObjects++;
setToolCallbacks(adjustLocXZ, camRotZ(),
adjustScaleY, mat2(0.05, 0, 0, 10.0));
glutPostRedisplay();
makeMenu(); // PART J.2. Object selection sub-menu needs to be updated
}
// PART J.3. Duplicate object
static void duplicateObject(int id) {
if (nObjects == maxObjects) {
return;
}
sceneObjs[nObjects] = sceneObjs[id];
toolObj = currObject = nObjects++;
setToolCallbacks(adjustLocXZ, camRotZ(),
adjustScaleY, mat2(0.05, 0, 0, 10.0));
glutPostRedisplay();
makeMenu(); // PART J.2. Required for object selection sub-menu
}
// PART J.4. Delete object
static void deleteObject(int id) {
sceneObjs[currObject].meshId = NULL;
currObject = -1;
delObjects++;
makeMenu(); // PART J.2. Update object selection sub-menu
}
//------The init function-----------------------------------------------------
void init(void) {
srand (time(NULL)); /* initialize random seed - so the starting scene varies */
aiInit();
// for (int i=0; i < numMeshes; i++)
// meshes[i] = NULL;
glGenVertexArraysAPPLE(numMeshes, vaoIDs); CheckError(); // Allocate vertex array objects for meshes
glGenTextures(numTextures, textureIDs); CheckError(); // Allocate texture objects
// Load shaders and use the resulting shader program
shaderProgram = InitShader("vStart.glsl", "fStart.glsl");
glUseProgram(shaderProgram); CheckError();
// Initialize the vertex position attribute from the vertex shader
vPosition = glGetAttribLocation(shaderProgram, "vPosition");
vNormal = glGetAttribLocation(shaderProgram, "vNormal"); CheckError();
// PART 2D.3. Initialize additional variables
vBoneIDs = glGetAttribLocation(shaderProgram, "boneIDs"); CheckError();
vBoneWeights = glGetAttribLocation(shaderProgram, "boneWeights"); CheckError();
// Likewise, initialize the vertex texture coordinates attribute.
vTexCoord = glGetAttribLocation(shaderProgram, "vTexCoord"); CheckError();
projectionU = glGetUniformLocation(shaderProgram, "Projection");
modelViewU = glGetUniformLocation(shaderProgram, "ModelView");
// PART 2D.3. Initialize additional variable
boneTransformsU = glGetUniformLocation(shaderProgram, "boneTransforms");
// Objects 0, 1 and 2 are the ground, first light and second light.
addObject(0); // Square for the ground
sceneObjs[0].loc = vec4(0.0, 0.0, 0.0, 1.0);
sceneObjs[0].scale = 10.0;
sceneObjs[0].angles[0] = 90.0; // Rotate it.
sceneObjs[0].texScale = 5.0; // Repeat the texture.
addObject(55); // Sphere for the first light
sceneObjs[1].loc = vec4(2.0, 1.0, 1.0, 1.0);
sceneObjs[1].scale = 0.1;
sceneObjs[1].texId = 0; // Plain texture
sceneObjs[1].brightness = 0.2; // The light's brightness is 5 times this (below).
// Second light
addObject(55); // Sphere for the second light
sceneObjs[2].loc = vec4(-2.0, 1.0, 1.0, 1.0);
sceneObjs[2].scale = 0.2;
sceneObjs[2].texId = 0; // Plain texture
sceneObjs[2].brightness = 0.2; // The light's brightness is 5 times this (below).
addObject(rand() % numMeshes); // A test mesh
// We need to enable the depth test to discard fragments that
// are behind previously drawn fragments for the same pixel.
glEnable(GL_DEPTH_TEST);
doRotate(); // Start in camera rotate mode.
glClearColor(0.0, 0.0, 0.0, 1.0); /* black background */
}
//----------------------------------------------------------------------------
void drawMesh(SceneObject sceneObj) {
// Activate a texture, loading if needed.
loadTextureIfNotAlreadyLoaded(sceneObj.texId);
glActiveTexture(GL_TEXTURE0);
glBindTexture(GL_TEXTURE_2D, textureIDs[sceneObj.texId]);
// Texture 0 is the only texture type in this program, and is for the rgb
// colour of the surface but there could be separate types for, e.g.,
// specularity and normals.
glUniform1i(glGetUniformLocation(shaderProgram, "texture"), 0);
// Set the texture scale for the shaders
glUniform1f(glGetUniformLocation(shaderProgram, "texScale"), sceneObj.texScale);
// Set the projection matrix for the shaders
glUniformMatrix4fv(projectionU, 1, GL_TRUE, projection);
// Set the model matrix - this should combine translation, rotation and scaling based on what's
// in the sceneObj structure (see near the top of the program).
// PART B. Object rotation
mat4 rotate = RotateX(-sceneObj.angles[0]) * RotateY(sceneObj.angles[1]) * RotateZ(sceneObj.angles[2]);
mat4 model = Translate(sceneObj.loc) * Scale(sceneObj.scale) * rotate;
// Set the model-view matrix for the shaders
glUniformMatrix4fv(modelViewU, 1, GL_TRUE, view * model);
// Activate the VAO for a mesh, loading if needed.
loadMeshIfNotAlreadyLoaded(sceneObj.meshId); CheckError();
glBindVertexArrayAPPLE(vaoIDs[sceneObj.meshId]); CheckError();
// PART 2D. Calculate animation frame
float poseTime = 0.0;
if (sceneObj.hasAnim) {
poseTime = (int) POSE_TIME % sceneObj.frames;
}
// PART 2D.7. Set the new uniform shader variable (pulled from addingAnimation.txt)
int nBones = meshes[sceneObj.meshId]->mNumBones;
if (nBones == 0) nBones = 1; // If no bones, just a single identity matrix is used
// Get boneTransforms for the first (0th) animation at the given time (a float measured in frames)
mat4 boneTransforms[nBones]; // was: mat4 boneTransforms[mesh->mNumBones];
calculateAnimPose(meshes[sceneObj.meshId], scenes[sceneObj.meshId], 0, poseTime, boneTransforms);
glUniformMatrix4fv(boneTransformsU, nBones, GL_TRUE, (const GLfloat *)boneTransforms);
// Set bounds for the animation Speed
if (ANIM_SPEED > 10) ANIM_SPEED = 10;
if (ANIM_SPEED < 0.1) ANIM_SPEED = 0.1;
if (!ANIM_PAUSED) {
POSE_TIME += ANIM_SPEED/10;
}
glDrawElements(GL_TRIANGLES, meshes[sceneObj.meshId]->mNumFaces * 3, GL_UNSIGNED_INT, NULL); CheckError();
}
//----------------------------------------------------------------------------
void display(void) {
numDisplayCalls++;
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
CheckError(); // May report a harmless GL_INVALID_OPERATION with GLEW on the first frame
// PART A. Set the view matrix
mat4 rotate = RotateX(camRotUpAndOverDeg) * RotateY(camRotSidewaysDeg);
view = Translate(0.0, 0.0, -viewDist) * rotate;
SceneObject lightObj1 = sceneObjs[1];
vec4 lightPosition = view * lightObj1.loc;
// PART I. Second light
SceneObject lightObj2 = sceneObjs[2];
vec4 lightPosition2 = rotate * lightObj2.loc;
glUniform4fv(glGetUniformLocation(shaderProgram, "LightPosition"), 1, lightPosition); CheckError();
glUniform4fv(glGetUniformLocation(shaderProgram, "LightPosition2"), 1, lightPosition2); CheckError();
// PART J.1. Passing the light locations
glUniform4fv(glGetUniformLocation(shaderProgram, "LightObj"), 1, lightObj1.loc); CheckError();
glUniform4fv(glGetUniformLocation(shaderProgram, "LightObj2"), 1, lightObj2.loc); CheckError();
glUniform3fv(glGetUniformLocation(shaderProgram, "LightColor"), 1, lightObj1.rgb); CheckError();
glUniform3fv(glGetUniformLocation(shaderProgram, "LightColor2"), 1, lightObj2.rgb); CheckError();
// PART H. Shine requires brightness to be passed
glUniform1f(glGetUniformLocation(shaderProgram, "LightBrightness"), lightObj1.brightness); CheckError();
glUniform1f(glGetUniformLocation(shaderProgram, "LightBrightness2"), lightObj2.brightness); CheckError();
for (int i=0; i < nObjects; i++) {
SceneObject so = sceneObjs[i];
vec3 rgb = so.rgb * so.brightness * 4.0; // Increased base brightness, mentioned in the Overview section
glUniform3fv(glGetUniformLocation(shaderProgram, "AmbientProduct"), 1, so.ambient * rgb); CheckError();
glUniform3fv(glGetUniformLocation(shaderProgram, "DiffuseProduct"), 1, so.diffuse * rgb);
glUniform3fv(glGetUniformLocation(shaderProgram, "SpecularProduct"), 1, so.specular * rgb);
glUniform1f(glGetUniformLocation(shaderProgram, "Shininess"), so.shine); CheckError();
drawMesh(sceneObjs[i]);
}
glutSwapBuffers();
}
//----------------------------------------------------------------------------
//------Menus-----------------------------------------------------------------
//----------------------------------------------------------------------------
static void objectMenu(int id) {
deactivateTool();
addObject(id);
}
static void texMenu(int id) {
deactivateTool();
if (currObject>=0) {
sceneObjs[currObject].texId = id;
glutPostRedisplay();
}
makeMenu(); // [Part J] Object selection name update
}
static void groundMenu(int id) {
deactivateTool();
sceneObjs[0].texId = id;
glutPostRedisplay();
}
// PART C. Adjusts the amounts of ambient and diffuse
static void adjustAmbientDiffuse(vec2 am_df) {
sceneObjs[toolObj].ambient += am_df[0];
sceneObjs[toolObj].diffuse += am_df[1];
}
static void adjustBrightnessY(vec2 by) {
sceneObjs[toolObj].brightness+=by[0];
sceneObjs[toolObj].loc[1]+=by[1];
}
static void adjustRedGreen(vec2 rg) {
sceneObjs[toolObj].rgb[0]+=rg[0];
sceneObjs[toolObj].rgb[1]+=rg[1];
}
static void adjustBlueBrightness(vec2 bl_br) {
sceneObjs[toolObj].rgb[2]+=bl_br[0];
sceneObjs[toolObj].brightness+=bl_br[1];
}
// PART C. Adjusts the amounts of specular light and shine
static void adjustSpecularShine(vec2 sp_sh) {
sceneObjs[toolObj].specular += sp_sh[0];
sceneObjs[toolObj].shine += sp_sh[1];
}
// PART 2D. Adjust animation speed
static void adjustAnimSpeed(vec2 an_sp) {
ANIM_SPEED += an_sp[0];
}
static void lightMenu(int id) {
deactivateTool();
if (id == 70) {
toolObj = 1;
setToolCallbacks(adjustLocXZ, camRotZ(),
adjustBrightnessY, mat2(1.0, 0.0, 0.0, 10.0));
} else if (id >= 71 && id <= 74) {
toolObj = 1;
setToolCallbacks(adjustRedGreen, mat2(1.0, 0, 0, 1.0),
adjustBlueBrightness, mat2(1.0, 0, 0, 1.0));
} else if (id == 80) { // Move Light 2
toolObj = 2;
setToolCallbacks(adjustLocXZ, camRotZ(),
adjustBrightnessY, mat2(1.0, 0.0, 0.0, 10.0));
} else if (id >= 81 && id <= 84) { // R/G/B/ALL Light 2
toolObj = 2;
setToolCallbacks(adjustRedGreen, mat2(1.0, 0, 0, 1.0),
adjustBlueBrightness, mat2(1.0, 0, 0, 1.0));
} else {
printf("Error in lightMenu\n");
exit(1);
}
}
static int createArrayMenu(int size, const char menuEntries[][128], void(*menuFn)(int)) {
int nSubMenus = (size-1)/10 + 1;
int subMenus[nSubMenus];
for (int i=0; i < nSubMenus; i++) {
subMenus[i] = glutCreateMenu(menuFn);
for (int j = i*10+1; j <= min(i*10+10, size); j++)
glutAddMenuEntry(menuEntries[j-1] , j);
CheckError();
}
int menuId = glutCreateMenu(menuFn);
for (int i=0; i < nSubMenus; i++) {
char num[6];
sprintf(num, "%d-%d", i*10+1, min(i*10+10, size));
glutAddSubMenu(num,subMenus[i]);
CheckError();
}
return menuId;
}
static void materialMenu(int id) {
deactivateTool();
if (currObject < 0) return;
if (id==10) {
toolObj = currObject;
setToolCallbacks(adjustRedGreen, mat2(1, 0, 0, 1),
adjustBlueBrightness, mat2(1, 0, 0, 1));
} else if (id == 20) { // PART C. Ambient/Diffuse/Specilar/Shine
setToolCallbacks(adjustAmbientDiffuse, mat2(1, 0, 0, 1),
adjustSpecularShine, mat2(1, 0, 0, 1));
}
else {
printf("Error in materialMenu\n");
}
}
// PART J.2. Object selection menu
static void selectObjectMenu(int id) {
int objectId = id - 100; // Object's actual index
toolObj = objectId;
currObject = objectId;
makeMenu();
}
// PART 2D. Animation menu
static void animationMenu(int id) {
if (id == 60) { // Animation resume
ANIM_PAUSED = false;
makeMenu();
}
if (id == 61) { // Animation pause
ANIM_PAUSED = true;
makeMenu();
}
if (id == 62) { // Animation speed
setToolCallbacks(adjustAnimSpeed, mat2(1, 0, 0, 10),
adjustAnimSpeed, mat2(1, 0, 0, 10));
}
}
static void adjustAngleYX(vec2 angle_yx) {
sceneObjs[currObject].angles[1]+=angle_yx[0];
sceneObjs[currObject].angles[0]+=angle_yx[1];
}
static void adjustAngleZTexscale(vec2 az_ts) {
sceneObjs[currObject].angles[2]+=az_ts[0];
sceneObjs[currObject].texScale+=az_ts[1];
}
static void mainmenu(int id) {
deactivateTool();
if (id == 41 && currObject>=0) {
toolObj=currObject;
setToolCallbacks(adjustLocXZ, camRotZ(),
adjustScaleY, mat2(0.05, 0, 0, 10));
}
if (id == 50) {
doRotate();
}
if (id == 51 && currObject >= 0) {
duplicateObject(currObject);
}
if (id == 52 && currObject >= 0) {
deleteObject(currObject);
}
if (id == 55 && currObject>=0) {
setToolCallbacks(adjustAngleYX, mat2(400, 0, 0, -400),
adjustAngleZTexscale, mat2(400, 0, 0, 15));
}
if (id == 99) exit(0);
}
static void makeMenu() {
int objectId = createArrayMenu(numMeshes, objectMenuEntries, objectMenu);
int materialMenuId = glutCreateMenu(materialMenu);
glutAddMenuEntry("R/G/B/All",10);
glutAddMenuEntry("Ambient/Diffuse/Specular/Shine",20);
int texMenuId = createArrayMenu(numTextures, textureMenuEntries, texMenu);
int groundMenuId = createArrayMenu(numTextures, textureMenuEntries, groundMenu);
int lightMenuId = glutCreateMenu(lightMenu);
glutAddMenuEntry("Move Light 1",70);
glutAddMenuEntry("R/G/B/All Light 1",71);
glutAddMenuEntry("Move Light 2",80);
glutAddMenuEntry("R/G/B/All Light 2",81);
// PART J.2. Selection of objects using a sub-menu
int selectObjMenuId = glutCreateMenu(selectObjectMenu);
for (int i = 3; i < nObjects; i++) { // Exclude ground, lightObj1 and lightObj2
char objectName[128]; // Same size used in gnatidread.h
if (sceneObjs[i].meshId != NULL) {
int objectId = 100 + i;
strcpy(objectName, objectMenuEntries[sceneObjs[i].meshId - 1]);
strcat(objectName, " (");
strcat(objectName, textureMenuEntries[sceneObjs[i].texId - 1]);
strcat(objectName, ")");
if (currObject == i) { // Indicate currently selected object
strcat(objectName, " *");
}
glutAddMenuEntry(objectName, objectId);
}
}
// PART 2D. Animation control using a sub-menu
int animationMenuId = glutCreateMenu(animationMenu);
if (ANIM_PAUSED) {
glutAddMenuEntry("Resume Animation", 60);
} else {
glutAddMenuEntry("Pause Animation", 61);
}
glutAddMenuEntry("Animation Speed", 62);
glutCreateMenu(mainmenu);
glutAddMenuEntry("Rotate/Move Camera", 50);
glutAddSubMenu("Add Object", objectId);
// PART J.5. Show sub-menu if an object exists (excluding the ground and lights)
if (nObjects - delObjects - 3 > 0) {
glutAddSubMenu("Select Object", selectObjMenuId);
}
if (currObject != -1) { // PART J.5. Show only when an object is selected
glutAddMenuEntry("Duplicate Object", 51);
glutAddMenuEntry("Delete Object", 52);
glutAddMenuEntry("Position/Scale", 41);
glutAddMenuEntry("Rotation/Texture Scale", 55);
glutAddSubMenu("Material", materialMenuId);
glutAddSubMenu("Texture", texMenuId);
}
glutAddSubMenu("Animation", animationMenuId);
glutAddSubMenu("Ground Texture", groundMenuId);
glutAddSubMenu("Lights", lightMenuId);
glutAddMenuEntry("EXIT", 99);
glutAttachMenu(GLUT_RIGHT_BUTTON);
}
//----------------------------------------------------------------------------
void keyboard(unsigned char key, int x, int y) {
switch (key) {
case 033:
exit(EXIT_SUCCESS);
break;
}
}
//----------------------------------------------------------------------------
void idle(void) {
glutPostRedisplay();
}
//----------------------------------------------------------------------------
void reshape(int width, int height) {
windowWidth = width;
windowHeight = height;
glViewport(0, 0, width, height);
GLfloat nearDist = 0.01; // PART D. Close-up clipping
// PART E. Window reshaping
if (width < height) { // Ensure visibility is unchanged when width < height
projection = Frustum(-nearDist, nearDist, -nearDist*(float)height/(float)width, nearDist*(float)height/(float)width, nearDist, 100.0);
} else {
projection = Frustum(-nearDist*(float)width/(float)height, nearDist*(float)width/(float)height, -nearDist, nearDist, nearDist, 100.0);
}
}
//----------------------------------------------------------------------------
void timer(int unused) {
char title[256];
sprintf(title, "%s %s: %d Frames Per Second @ %d x %d",
lab, programName, numDisplayCalls, windowWidth, windowHeight);
glutSetWindowTitle(title);
numDisplayCalls = 0;
glutTimerFunc(1000, timer, 1);
}
//----------------------------------------------------------------------------
char dirDefault1[] = "models-textures";
char dirDefault3[] = "/tmp/models-textures";
char dirDefault4[] = "/d/models-textures";
char dirDefault2[] = "/cslinux/examples/CITS3003/project-files/models-textures";
void fileErr(char* fileName) {
printf("Error reading file: %s\n", fileName);
printf("When not in the CSSE labs, you will need to include the directory containing\n");
printf("the models on the command line, or put it in the same folder as the exectutable.");
exit(1);
}
//----------------------------------------------------------------------------
int main(int argc, char* argv[]) {
// Get the program name, excluding the directory, for the window title
programName = argv[0];
for (char *cpointer = argv[0]; *cpointer != 0; cpointer++)
if (*cpointer == '/' || *cpointer == '\\') programName = cpointer+1;
// Set the models-textures directory, via the first argument or some handy defaults.
if (argc > 1)
strcpy(dataDir, argv[1]);
else if (opendir(dirDefault1)) strcpy(dataDir, dirDefault1);
else if (opendir(dirDefault2)) strcpy(dataDir, dirDefault2);
else if (opendir(dirDefault3)) strcpy(dataDir, dirDefault3);
else if (opendir(dirDefault4)) strcpy(dataDir, dirDefault4);
else fileErr(dirDefault1);
glutInit(&argc, argv);
glutInitDisplayMode(GLUT_RGBA | GLUT_DOUBLE | GLUT_DEPTH);
glutInitWindowSize(windowWidth, windowHeight);
glutCreateWindow("Initialising...");
// glewInit(); // With some old hardware yields GL_INVALID_ENUM, if so use glewExperimental.
CheckError(); // This bug is explained at: http://www.opengl.org/wiki/OpenGL_Loading_Library
init();
CheckError();
glutDisplayFunc(display);
glutKeyboardFunc(keyboard);
glutIdleFunc(idle);
glutMouseFunc(mouseClickOrScroll);
glutPassiveMotionFunc(mousePassiveMotion);
glutMotionFunc(doToolUpdateXY);
glutReshapeFunc(reshape);
glutTimerFunc(1000, timer, 1);
CheckError();
makeMenu();
CheckError();
glutMainLoop();
return 0;
}