Clone of mesa.
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

dinoshade.c 25KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896
  1. /* Copyright (c) Mark J. Kilgard, 1994, 1997. */
  2. /* This program is freely distributable without licensing fees
  3. and is provided without guarantee or warrantee expressed or
  4. implied. This program is -not- in the public domain. */
  5. /* Example for PC game developers to show how to *combine* texturing,
  6. reflections, and projected shadows all in real-time with OpenGL.
  7. Robust reflections use stenciling. Robust projected shadows
  8. use both stenciling and polygon offset. PC game programmers
  9. should realize that neither stenciling nor polygon offset are
  10. supported by Direct3D, so these real-time rendering algorithms
  11. are only really viable with OpenGL.
  12. The program has modes for disabling the stenciling and polygon
  13. offset uses. It is worth running this example with these features
  14. toggled off so you can see the sort of artifacts that result.
  15. Notice that the floor texturing, reflections, and shadowing
  16. all co-exist properly. */
  17. /* When you run this program: Left mouse button controls the
  18. view. Middle mouse button controls light position (left &
  19. right rotates light around dino; up & down moves light
  20. position up and down). Right mouse button pops up menu. */
  21. /* Check out the comments in the "redraw" routine to see how the
  22. reflection blending and surface stenciling is done. You can
  23. also see in "redraw" how the projected shadows are rendered,
  24. including the use of stenciling and polygon offset. */
  25. /* This program is derived from glutdino.c */
  26. /* Compile: cc -o dinoshade dinoshade.c -lglut -lGLU -lGL -lXmu -lXext -lX11 -lm */
  27. #include <stdio.h>
  28. #include <stdlib.h>
  29. #include <string.h>
  30. #include <math.h> /* for cos(), sin(), and sqrt() */
  31. #include <malloc.h> /* for ptrdiff_t, referenced by GL.h when GL_GLEXT_LEGACY defined */
  32. #ifdef _WIN32
  33. #include <windows.h>
  34. #endif
  35. #define GL_GLEXT_LEGACY
  36. #include <GL/glut.h> /* OpenGL Utility Toolkit header */
  37. /* Some <math.h> files do not define M_PI... */
  38. #ifndef M_PI
  39. #define M_PI 3.14159265358979323846
  40. #endif
  41. /* Variable controlling various rendering modes. */
  42. static int stencilReflection = 1, stencilShadow = 1, offsetShadow = 1;
  43. static int renderShadow = 1, renderDinosaur = 1, renderReflection = 1;
  44. static int linearFiltering = 0, useMipmaps = 0, useTexture = 1;
  45. static int reportSpeed = 0;
  46. static int animation = 1;
  47. static GLboolean lightSwitch = GL_TRUE;
  48. static int directionalLight = 1;
  49. static int forceExtension = 0;
  50. /* Time varying or user-controled variables. */
  51. static float jump = 0.0;
  52. static float lightAngle = 0.0, lightHeight = 20;
  53. GLfloat angle = -150; /* in degrees */
  54. GLfloat angle2 = 30; /* in degrees */
  55. int moving, startx, starty;
  56. int lightMoving = 0, lightStartX, lightStartY;
  57. enum {
  58. MISSING, EXTENSION, ONE_DOT_ONE
  59. };
  60. int polygonOffsetVersion;
  61. static GLdouble bodyWidth = 3.0;
  62. /* *INDENT-OFF* */
  63. static GLfloat body[][2] = { {0, 3}, {1, 1}, {5, 1}, {8, 4}, {10, 4}, {11, 5},
  64. {11, 11.5}, {13, 12}, {13, 13}, {10, 13.5}, {13, 14}, {13, 15}, {11, 16},
  65. {8, 16}, {7, 15}, {7, 13}, {8, 12}, {7, 11}, {6, 6}, {4, 3}, {3, 2},
  66. {1, 2} };
  67. static GLfloat arm[][2] = { {8, 10}, {9, 9}, {10, 9}, {13, 8}, {14, 9}, {16, 9},
  68. {15, 9.5}, {16, 10}, {15, 10}, {15.5, 11}, {14.5, 10}, {14, 11}, {14, 10},
  69. {13, 9}, {11, 11}, {9, 11} };
  70. static GLfloat leg[][2] = { {8, 6}, {8, 4}, {9, 3}, {9, 2}, {8, 1}, {8, 0.5}, {9, 0},
  71. {12, 0}, {10, 1}, {10, 2}, {12, 4}, {11, 6}, {10, 7}, {9, 7} };
  72. static GLfloat eye[][2] = { {8.75, 15}, {9, 14.7}, {9.6, 14.7}, {10.1, 15},
  73. {9.6, 15.25}, {9, 15.25} };
  74. static GLfloat lightPosition[4];
  75. static GLfloat lightColor[] = {0.8, 1.0, 0.8, 1.0}; /* green-tinted */
  76. static GLfloat skinColor[] = {0.1, 1.0, 0.1, 1.0}, eyeColor[] = {1.0, 0.2, 0.2, 1.0};
  77. /* *INDENT-ON* */
  78. /* Nice floor texture tiling pattern. */
  79. static char *circles[] = {
  80. "....xxxx........",
  81. "..xxxxxxxx......",
  82. ".xxxxxxxxxx.....",
  83. ".xxx....xxx.....",
  84. "xxx......xxx....",
  85. "xxx......xxx....",
  86. "xxx......xxx....",
  87. "xxx......xxx....",
  88. ".xxx....xxx.....",
  89. ".xxxxxxxxxx.....",
  90. "..xxxxxxxx......",
  91. "....xxxx........",
  92. "................",
  93. "................",
  94. "................",
  95. "................",
  96. };
  97. static void
  98. makeFloorTexture(void)
  99. {
  100. GLubyte floorTexture[16][16][3];
  101. GLubyte *loc;
  102. int s, t;
  103. /* Setup RGB image for the texture. */
  104. loc = (GLubyte*) floorTexture;
  105. for (t = 0; t < 16; t++) {
  106. for (s = 0; s < 16; s++) {
  107. if (circles[t][s] == 'x') {
  108. /* Nice green. */
  109. loc[0] = 0x1f;
  110. loc[1] = 0x8f;
  111. loc[2] = 0x1f;
  112. } else {
  113. /* Light gray. */
  114. loc[0] = 0xaa;
  115. loc[1] = 0xaa;
  116. loc[2] = 0xaa;
  117. }
  118. loc += 3;
  119. }
  120. }
  121. glPixelStorei(GL_UNPACK_ALIGNMENT, 1);
  122. if (useMipmaps) {
  123. glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER,
  124. GL_LINEAR_MIPMAP_LINEAR);
  125. gluBuild2DMipmaps(GL_TEXTURE_2D, 3, 16, 16,
  126. GL_RGB, GL_UNSIGNED_BYTE, floorTexture);
  127. } else {
  128. if (linearFiltering) {
  129. glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
  130. } else {
  131. glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST);
  132. }
  133. glTexImage2D(GL_TEXTURE_2D, 0, 3, 16, 16, 0,
  134. GL_RGB, GL_UNSIGNED_BYTE, floorTexture);
  135. }
  136. }
  137. enum {
  138. X, Y, Z, W
  139. };
  140. enum {
  141. A, B, C, D
  142. };
  143. /* Create a matrix that will project the desired shadow. */
  144. void
  145. shadowMatrix(GLfloat shadowMat[4][4],
  146. GLfloat groundplane[4],
  147. GLfloat lightpos[4])
  148. {
  149. GLfloat dot;
  150. /* Find dot product between light position vector and ground plane normal. */
  151. dot = groundplane[X] * lightpos[X] +
  152. groundplane[Y] * lightpos[Y] +
  153. groundplane[Z] * lightpos[Z] +
  154. groundplane[W] * lightpos[W];
  155. shadowMat[0][0] = dot - lightpos[X] * groundplane[X];
  156. shadowMat[1][0] = 0.f - lightpos[X] * groundplane[Y];
  157. shadowMat[2][0] = 0.f - lightpos[X] * groundplane[Z];
  158. shadowMat[3][0] = 0.f - lightpos[X] * groundplane[W];
  159. shadowMat[X][1] = 0.f - lightpos[Y] * groundplane[X];
  160. shadowMat[1][1] = dot - lightpos[Y] * groundplane[Y];
  161. shadowMat[2][1] = 0.f - lightpos[Y] * groundplane[Z];
  162. shadowMat[3][1] = 0.f - lightpos[Y] * groundplane[W];
  163. shadowMat[X][2] = 0.f - lightpos[Z] * groundplane[X];
  164. shadowMat[1][2] = 0.f - lightpos[Z] * groundplane[Y];
  165. shadowMat[2][2] = dot - lightpos[Z] * groundplane[Z];
  166. shadowMat[3][2] = 0.f - lightpos[Z] * groundplane[W];
  167. shadowMat[X][3] = 0.f - lightpos[W] * groundplane[X];
  168. shadowMat[1][3] = 0.f - lightpos[W] * groundplane[Y];
  169. shadowMat[2][3] = 0.f - lightpos[W] * groundplane[Z];
  170. shadowMat[3][3] = dot - lightpos[W] * groundplane[W];
  171. }
  172. /* Find the plane equation given 3 points. */
  173. void
  174. findPlane(GLfloat plane[4],
  175. GLfloat v0[3], GLfloat v1[3], GLfloat v2[3])
  176. {
  177. GLfloat vec0[3], vec1[3];
  178. /* Need 2 vectors to find cross product. */
  179. vec0[X] = v1[X] - v0[X];
  180. vec0[Y] = v1[Y] - v0[Y];
  181. vec0[Z] = v1[Z] - v0[Z];
  182. vec1[X] = v2[X] - v0[X];
  183. vec1[Y] = v2[Y] - v0[Y];
  184. vec1[Z] = v2[Z] - v0[Z];
  185. /* find cross product to get A, B, and C of plane equation */
  186. plane[A] = vec0[Y] * vec1[Z] - vec0[Z] * vec1[Y];
  187. plane[B] = -(vec0[X] * vec1[Z] - vec0[Z] * vec1[X]);
  188. plane[C] = vec0[X] * vec1[Y] - vec0[Y] * vec1[X];
  189. plane[D] = -(plane[A] * v0[X] + plane[B] * v0[Y] + plane[C] * v0[Z]);
  190. }
  191. void
  192. extrudeSolidFromPolygon(GLfloat data[][2], unsigned int dataSize,
  193. GLdouble thickness, GLuint side, GLuint edge, GLuint whole)
  194. {
  195. static GLUtriangulatorObj *tobj = NULL;
  196. GLdouble vertex[3], dx, dy, len;
  197. int i;
  198. int count = (int) (dataSize / (2 * sizeof(GLfloat)));
  199. if (tobj == NULL) {
  200. tobj = gluNewTess(); /* create and initialize a GLU
  201. polygon tesselation object */
  202. gluTessCallback(tobj, GLU_BEGIN, glBegin);
  203. gluTessCallback(tobj, GLU_VERTEX, glVertex2fv); /* semi-tricky */
  204. gluTessCallback(tobj, GLU_END, glEnd);
  205. }
  206. glNewList(side, GL_COMPILE);
  207. glShadeModel(GL_SMOOTH); /* smooth minimizes seeing
  208. tessellation */
  209. gluBeginPolygon(tobj);
  210. for (i = 0; i < count; i++) {
  211. vertex[0] = data[i][0];
  212. vertex[1] = data[i][1];
  213. vertex[2] = 0;
  214. gluTessVertex(tobj, vertex, data[i]);
  215. }
  216. gluEndPolygon(tobj);
  217. glEndList();
  218. glNewList(edge, GL_COMPILE);
  219. glShadeModel(GL_FLAT); /* flat shade keeps angular hands
  220. from being "smoothed" */
  221. glBegin(GL_QUAD_STRIP);
  222. for (i = 0; i <= count; i++) {
  223. /* mod function handles closing the edge */
  224. glVertex3f(data[i % count][0], data[i % count][1], 0.0);
  225. glVertex3f(data[i % count][0], data[i % count][1], thickness);
  226. /* Calculate a unit normal by dividing by Euclidean
  227. distance. We * could be lazy and use
  228. glEnable(GL_NORMALIZE) so we could pass in * arbitrary
  229. normals for a very slight performance hit. */
  230. dx = data[(i + 1) % count][1] - data[i % count][1];
  231. dy = data[i % count][0] - data[(i + 1) % count][0];
  232. len = sqrt(dx * dx + dy * dy);
  233. glNormal3f(dx / len, dy / len, 0.0);
  234. }
  235. glEnd();
  236. glEndList();
  237. glNewList(whole, GL_COMPILE);
  238. glFrontFace(GL_CW);
  239. glCallList(edge);
  240. glNormal3f(0.0, 0.0, -1.0); /* constant normal for side */
  241. glCallList(side);
  242. glPushMatrix();
  243. glTranslatef(0.0, 0.0, thickness);
  244. glFrontFace(GL_CCW);
  245. glNormal3f(0.0, 0.0, 1.0); /* opposite normal for other side */
  246. glCallList(side);
  247. glPopMatrix();
  248. glEndList();
  249. }
  250. /* Enumerants for refering to display lists. */
  251. typedef enum {
  252. RESERVED, BODY_SIDE, BODY_EDGE, BODY_WHOLE, ARM_SIDE, ARM_EDGE, ARM_WHOLE,
  253. LEG_SIDE, LEG_EDGE, LEG_WHOLE, EYE_SIDE, EYE_EDGE, EYE_WHOLE
  254. } displayLists;
  255. static void
  256. makeDinosaur(void)
  257. {
  258. extrudeSolidFromPolygon(body, sizeof(body), bodyWidth,
  259. BODY_SIDE, BODY_EDGE, BODY_WHOLE);
  260. extrudeSolidFromPolygon(arm, sizeof(arm), bodyWidth / 4,
  261. ARM_SIDE, ARM_EDGE, ARM_WHOLE);
  262. extrudeSolidFromPolygon(leg, sizeof(leg), bodyWidth / 2,
  263. LEG_SIDE, LEG_EDGE, LEG_WHOLE);
  264. extrudeSolidFromPolygon(eye, sizeof(eye), bodyWidth + 0.2,
  265. EYE_SIDE, EYE_EDGE, EYE_WHOLE);
  266. }
  267. static void
  268. drawDinosaur(void)
  269. {
  270. glPushMatrix();
  271. /* Translate the dinosaur to be at (0,8,0). */
  272. glTranslatef(-8, 0, -bodyWidth / 2);
  273. glTranslatef(0.0, jump, 0.0);
  274. glMaterialfv(GL_FRONT, GL_DIFFUSE, skinColor);
  275. glCallList(BODY_WHOLE);
  276. glTranslatef(0.0, 0.0, bodyWidth);
  277. glCallList(ARM_WHOLE);
  278. glCallList(LEG_WHOLE);
  279. glTranslatef(0.0, 0.0, -bodyWidth - bodyWidth / 4);
  280. glCallList(ARM_WHOLE);
  281. glTranslatef(0.0, 0.0, -bodyWidth / 4);
  282. glCallList(LEG_WHOLE);
  283. glTranslatef(0.0, 0.0, bodyWidth / 2 - 0.1);
  284. glMaterialfv(GL_FRONT, GL_DIFFUSE, eyeColor);
  285. glCallList(EYE_WHOLE);
  286. glPopMatrix();
  287. }
  288. static GLfloat floorVertices[4][3] = {
  289. { -20.0, 0.0, 20.0 },
  290. { 20.0, 0.0, 20.0 },
  291. { 20.0, 0.0, -20.0 },
  292. { -20.0, 0.0, -20.0 },
  293. };
  294. /* Draw a floor (possibly textured). */
  295. static void
  296. drawFloor(void)
  297. {
  298. glDisable(GL_LIGHTING);
  299. if (useTexture) {
  300. glEnable(GL_TEXTURE_2D);
  301. }
  302. glBegin(GL_QUADS);
  303. glTexCoord2f(0.0, 0.0);
  304. glVertex3fv(floorVertices[0]);
  305. glTexCoord2f(0.0, 16.0);
  306. glVertex3fv(floorVertices[1]);
  307. glTexCoord2f(16.0, 16.0);
  308. glVertex3fv(floorVertices[2]);
  309. glTexCoord2f(16.0, 0.0);
  310. glVertex3fv(floorVertices[3]);
  311. glEnd();
  312. if (useTexture) {
  313. glDisable(GL_TEXTURE_2D);
  314. }
  315. glEnable(GL_LIGHTING);
  316. }
  317. static GLfloat floorPlane[4];
  318. static GLfloat floorShadow[4][4];
  319. static void
  320. redraw(void)
  321. {
  322. int start, end;
  323. if (reportSpeed) {
  324. start = glutGet(GLUT_ELAPSED_TIME);
  325. }
  326. /* Clear; default stencil clears to zero. */
  327. if ((stencilReflection && renderReflection) || (stencilShadow && renderShadow)) {
  328. glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT | GL_STENCIL_BUFFER_BIT);
  329. } else {
  330. /* Avoid clearing stencil when not using it. */
  331. glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
  332. }
  333. /* Reposition the light source. */
  334. lightPosition[0] = 12*cos(lightAngle);
  335. lightPosition[1] = lightHeight;
  336. lightPosition[2] = 12*sin(lightAngle);
  337. if (directionalLight) {
  338. lightPosition[3] = 0.0;
  339. } else {
  340. lightPosition[3] = 1.0;
  341. }
  342. shadowMatrix(floorShadow, floorPlane, lightPosition);
  343. glPushMatrix();
  344. /* Perform scene rotations based on user mouse input. */
  345. glRotatef(angle2, 1.0, 0.0, 0.0);
  346. glRotatef(angle, 0.0, 1.0, 0.0);
  347. /* Tell GL new light source position. */
  348. glLightfv(GL_LIGHT0, GL_POSITION, lightPosition);
  349. if (renderReflection) {
  350. if (stencilReflection) {
  351. /* We can eliminate the visual "artifact" of seeing the "flipped"
  352. dinosaur underneath the floor by using stencil. The idea is
  353. draw the floor without color or depth update but so that
  354. a stencil value of one is where the floor will be. Later when
  355. rendering the dinosaur reflection, we will only update pixels
  356. with a stencil value of 1 to make sure the reflection only
  357. lives on the floor, not below the floor. */
  358. /* Don't update color or depth. */
  359. glDisable(GL_DEPTH_TEST);
  360. glColorMask(GL_FALSE, GL_FALSE, GL_FALSE, GL_FALSE);
  361. /* Draw 1 into the stencil buffer. */
  362. glEnable(GL_STENCIL_TEST);
  363. glStencilOp(GL_REPLACE, GL_REPLACE, GL_REPLACE);
  364. glStencilFunc(GL_ALWAYS, 1, 0xffffffff);
  365. /* Now render floor; floor pixels just get their stencil set to 1. */
  366. drawFloor();
  367. /* Re-enable update of color and depth. */
  368. glColorMask(GL_TRUE, GL_TRUE, GL_TRUE, GL_TRUE);
  369. glEnable(GL_DEPTH_TEST);
  370. /* Now, only render where stencil is set to 1. */
  371. glStencilFunc(GL_EQUAL, 1, 0xffffffff); /* draw if ==1 */
  372. glStencilOp(GL_KEEP, GL_KEEP, GL_KEEP);
  373. }
  374. glPushMatrix();
  375. /* The critical reflection step: Reflect dinosaur through the floor
  376. (the Y=0 plane) to make a relection. */
  377. glScalef(1.0, -1.0, 1.0);
  378. /* Reflect the light position. */
  379. glLightfv(GL_LIGHT0, GL_POSITION, lightPosition);
  380. /* To avoid our normals getting reversed and hence botched lighting
  381. on the reflection, turn on normalize. */
  382. glEnable(GL_NORMALIZE);
  383. glCullFace(GL_FRONT);
  384. /* Draw the reflected dinosaur. */
  385. drawDinosaur();
  386. /* Disable noramlize again and re-enable back face culling. */
  387. glDisable(GL_NORMALIZE);
  388. glCullFace(GL_BACK);
  389. glPopMatrix();
  390. /* Switch back to the unreflected light position. */
  391. glLightfv(GL_LIGHT0, GL_POSITION, lightPosition);
  392. if (stencilReflection) {
  393. glDisable(GL_STENCIL_TEST);
  394. }
  395. }
  396. /* Back face culling will get used to only draw either the top or the
  397. bottom floor. This let's us get a floor with two distinct
  398. appearances. The top floor surface is reflective and kind of red.
  399. The bottom floor surface is not reflective and blue. */
  400. /* Draw "bottom" of floor in blue. */
  401. glFrontFace(GL_CW); /* Switch face orientation. */
  402. glColor4f(0.1, 0.1, 0.7, 1.0);
  403. drawFloor();
  404. glFrontFace(GL_CCW);
  405. if (renderShadow) {
  406. if (stencilShadow) {
  407. /* Draw the floor with stencil value 3. This helps us only
  408. draw the shadow once per floor pixel (and only on the
  409. floor pixels). */
  410. glEnable(GL_STENCIL_TEST);
  411. glStencilFunc(GL_ALWAYS, 3, 0xffffffff);
  412. glStencilOp(GL_KEEP, GL_KEEP, GL_REPLACE);
  413. }
  414. }
  415. /* Draw "top" of floor. Use blending to blend in reflection. */
  416. glEnable(GL_BLEND);
  417. glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
  418. glColor4f(0.7, 0.0, 0.0, 0.3);
  419. glColor4f(1.0, 1.0, 1.0, 0.3);
  420. drawFloor();
  421. glDisable(GL_BLEND);
  422. if (renderDinosaur) {
  423. /* Draw "actual" dinosaur, not its reflection. */
  424. drawDinosaur();
  425. }
  426. if (renderShadow) {
  427. /* Render the projected shadow. */
  428. if (stencilShadow) {
  429. /* Now, only render where stencil is set above 2 (ie, 3 where
  430. the top floor is). Update stencil with 2 where the shadow
  431. gets drawn so we don't redraw (and accidently reblend) the
  432. shadow). */
  433. glStencilFunc(GL_LESS, 2, 0xffffffff); /* draw if ==1 */
  434. glStencilOp(GL_REPLACE, GL_REPLACE, GL_REPLACE);
  435. }
  436. /* To eliminate depth buffer artifacts, we use polygon offset
  437. to raise the depth of the projected shadow slightly so
  438. that it does not depth buffer alias with the floor. */
  439. if (offsetShadow) {
  440. switch (polygonOffsetVersion) {
  441. case EXTENSION:
  442. #ifdef GL_EXT_polygon_offset
  443. glEnable(GL_POLYGON_OFFSET_EXT);
  444. break;
  445. #endif
  446. #ifdef GL_VERSION_1_1
  447. case ONE_DOT_ONE:
  448. glEnable(GL_POLYGON_OFFSET_FILL);
  449. break;
  450. #endif
  451. case MISSING:
  452. /* Oh well. */
  453. break;
  454. }
  455. }
  456. /* Render 50% black shadow color on top of whatever the
  457. floor appareance is. */
  458. glEnable(GL_BLEND);
  459. glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
  460. glDisable(GL_LIGHTING); /* Force the 50% black. */
  461. glColor4f(0.0, 0.0, 0.0, 0.5);
  462. glPushMatrix();
  463. /* Project the shadow. */
  464. glMultMatrixf((GLfloat *) floorShadow);
  465. drawDinosaur();
  466. glPopMatrix();
  467. glDisable(GL_BLEND);
  468. glEnable(GL_LIGHTING);
  469. if (offsetShadow) {
  470. switch (polygonOffsetVersion) {
  471. #ifdef GL_EXT_polygon_offset
  472. case EXTENSION:
  473. glDisable(GL_POLYGON_OFFSET_EXT);
  474. break;
  475. #endif
  476. #ifdef GL_VERSION_1_1
  477. case ONE_DOT_ONE:
  478. glDisable(GL_POLYGON_OFFSET_FILL);
  479. break;
  480. #endif
  481. case MISSING:
  482. /* Oh well. */
  483. break;
  484. }
  485. }
  486. if (stencilShadow) {
  487. glDisable(GL_STENCIL_TEST);
  488. }
  489. }
  490. glPushMatrix();
  491. glDisable(GL_LIGHTING);
  492. glColor3f(1.0, 1.0, 0.0);
  493. if (directionalLight) {
  494. /* Draw an arrowhead. */
  495. glDisable(GL_CULL_FACE);
  496. glTranslatef(lightPosition[0], lightPosition[1], lightPosition[2]);
  497. glRotatef(lightAngle * -180.0 / M_PI, 0, 1, 0);
  498. glRotatef(atan(lightHeight/12) * 180.0 / M_PI, 0, 0, 1);
  499. glBegin(GL_TRIANGLE_FAN);
  500. glVertex3f(0, 0, 0);
  501. glVertex3f(2, 1, 1);
  502. glVertex3f(2, -1, 1);
  503. glVertex3f(2, -1, -1);
  504. glVertex3f(2, 1, -1);
  505. glVertex3f(2, 1, 1);
  506. glEnd();
  507. /* Draw a white line from light direction. */
  508. glColor3f(1.0, 1.0, 1.0);
  509. glBegin(GL_LINES);
  510. glVertex3f(0, 0, 0);
  511. glVertex3f(5, 0, 0);
  512. glEnd();
  513. glEnable(GL_CULL_FACE);
  514. } else {
  515. /* Draw a yellow ball at the light source. */
  516. glTranslatef(lightPosition[0], lightPosition[1], lightPosition[2]);
  517. glutSolidSphere(1.0, 5, 5);
  518. }
  519. glEnable(GL_LIGHTING);
  520. glPopMatrix();
  521. glPopMatrix();
  522. if (reportSpeed) {
  523. glFinish();
  524. end = glutGet(GLUT_ELAPSED_TIME);
  525. printf("Speed %.3g frames/sec (%d ms)\n", 1000.0/(end-start), end-start);
  526. }
  527. glutSwapBuffers();
  528. }
  529. /* ARGSUSED2 */
  530. static void
  531. mouse(int button, int state, int x, int y)
  532. {
  533. if (button == GLUT_LEFT_BUTTON) {
  534. if (state == GLUT_DOWN) {
  535. moving = 1;
  536. startx = x;
  537. starty = y;
  538. }
  539. if (state == GLUT_UP) {
  540. moving = 0;
  541. }
  542. }
  543. if (button == GLUT_MIDDLE_BUTTON) {
  544. if (state == GLUT_DOWN) {
  545. lightMoving = 1;
  546. lightStartX = x;
  547. lightStartY = y;
  548. }
  549. if (state == GLUT_UP) {
  550. lightMoving = 0;
  551. }
  552. }
  553. }
  554. /* ARGSUSED1 */
  555. static void
  556. motion(int x, int y)
  557. {
  558. if (moving) {
  559. angle = angle + (x - startx);
  560. angle2 = angle2 + (y - starty);
  561. startx = x;
  562. starty = y;
  563. glutPostRedisplay();
  564. }
  565. if (lightMoving) {
  566. lightAngle += (x - lightStartX)/40.0;
  567. lightHeight += (lightStartY - y)/20.0;
  568. lightStartX = x;
  569. lightStartY = y;
  570. glutPostRedisplay();
  571. }
  572. }
  573. /* Advance time varying state when idle callback registered. */
  574. static void
  575. idle(void)
  576. {
  577. static float time = 0.0;
  578. time = glutGet(GLUT_ELAPSED_TIME) / 500.0;
  579. jump = 4.0 * fabs(sin(time)*0.5);
  580. if (!lightMoving) {
  581. lightAngle += 0.03;
  582. }
  583. glutPostRedisplay();
  584. }
  585. enum {
  586. M_NONE, M_MOTION, M_LIGHT, M_TEXTURE, M_SHADOWS, M_REFLECTION, M_DINOSAUR,
  587. M_STENCIL_REFLECTION, M_STENCIL_SHADOW, M_OFFSET_SHADOW,
  588. M_POSITIONAL, M_DIRECTIONAL, M_PERFORMANCE
  589. };
  590. static void
  591. controlLights(int value)
  592. {
  593. switch (value) {
  594. case M_NONE:
  595. return;
  596. case M_MOTION:
  597. animation = 1 - animation;
  598. if (animation) {
  599. glutIdleFunc(idle);
  600. } else {
  601. glutIdleFunc(NULL);
  602. }
  603. break;
  604. case M_LIGHT:
  605. lightSwitch = !lightSwitch;
  606. if (lightSwitch) {
  607. glEnable(GL_LIGHT0);
  608. } else {
  609. glDisable(GL_LIGHT0);
  610. }
  611. break;
  612. case M_TEXTURE:
  613. useTexture = !useTexture;
  614. break;
  615. case M_SHADOWS:
  616. renderShadow = 1 - renderShadow;
  617. break;
  618. case M_REFLECTION:
  619. renderReflection = 1 - renderReflection;
  620. break;
  621. case M_DINOSAUR:
  622. renderDinosaur = 1 - renderDinosaur;
  623. break;
  624. case M_STENCIL_REFLECTION:
  625. stencilReflection = 1 - stencilReflection;
  626. break;
  627. case M_STENCIL_SHADOW:
  628. stencilShadow = 1 - stencilShadow;
  629. break;
  630. case M_OFFSET_SHADOW:
  631. offsetShadow = 1 - offsetShadow;
  632. break;
  633. case M_POSITIONAL:
  634. directionalLight = 0;
  635. break;
  636. case M_DIRECTIONAL:
  637. directionalLight = 1;
  638. break;
  639. case M_PERFORMANCE:
  640. reportSpeed = 1 - reportSpeed;
  641. break;
  642. }
  643. glutPostRedisplay();
  644. }
  645. /* When not visible, stop animating. Restart when visible again. */
  646. static void
  647. visible(int vis)
  648. {
  649. if (vis == GLUT_VISIBLE) {
  650. if (animation)
  651. glutIdleFunc(idle);
  652. } else {
  653. if (!animation)
  654. glutIdleFunc(NULL);
  655. }
  656. }
  657. /* Press any key to redraw; good when motion stopped and
  658. performance reporting on. */
  659. /* ARGSUSED */
  660. static void
  661. key(unsigned char c, int x, int y)
  662. {
  663. if (c == 27) {
  664. exit(0); /* IRIS GLism, Escape quits. */
  665. }
  666. glutPostRedisplay();
  667. }
  668. /* Press any key to redraw; good when motion stopped and
  669. performance reporting on. */
  670. /* ARGSUSED */
  671. static void
  672. special(int k, int x, int y)
  673. {
  674. glutPostRedisplay();
  675. }
  676. static int
  677. supportsOneDotOne(void)
  678. {
  679. const char *version;
  680. int major, minor;
  681. version = (char *) glGetString(GL_VERSION);
  682. if (sscanf(version, "%d.%d", &major, &minor) == 2)
  683. return major >= 1 && minor >= 1;
  684. return 0; /* OpenGL version string malformed! */
  685. }
  686. int
  687. main(int argc, char **argv)
  688. {
  689. int i;
  690. glutInit(&argc, argv);
  691. for (i=1; i<argc; i++) {
  692. if (!strcmp("-linear", argv[i])) {
  693. linearFiltering = 1;
  694. } else if (!strcmp("-mipmap", argv[i])) {
  695. useMipmaps = 1;
  696. } else if (!strcmp("-ext", argv[i])) {
  697. forceExtension = 1;
  698. }
  699. }
  700. glutInitDisplayMode(GLUT_RGB | GLUT_DOUBLE | GLUT_DEPTH | GLUT_STENCIL);
  701. #if 0
  702. /* In GLUT 4.0, you'll be able to do this an be sure to
  703. get 2 bits of stencil if the machine has it for you. */
  704. glutInitDisplayString("samples stencil>=2 rgb double depth");
  705. #endif
  706. glutCreateWindow("Shadowy Leapin' Lizards");
  707. if (glutGet(GLUT_WINDOW_STENCIL_SIZE) <= 1) {
  708. printf("dinoshade: Sorry, I need at least 2 bits of stencil.\n");
  709. exit(1);
  710. }
  711. /* Register GLUT callbacks. */
  712. glutDisplayFunc(redraw);
  713. glutMouseFunc(mouse);
  714. glutMotionFunc(motion);
  715. glutVisibilityFunc(visible);
  716. glutKeyboardFunc(key);
  717. glutSpecialFunc(special);
  718. glutCreateMenu(controlLights);
  719. glutAddMenuEntry("Toggle motion", M_MOTION);
  720. glutAddMenuEntry("-----------------------", M_NONE);
  721. glutAddMenuEntry("Toggle light", M_LIGHT);
  722. glutAddMenuEntry("Toggle texture", M_TEXTURE);
  723. glutAddMenuEntry("Toggle shadows", M_SHADOWS);
  724. glutAddMenuEntry("Toggle reflection", M_REFLECTION);
  725. glutAddMenuEntry("Toggle dinosaur", M_DINOSAUR);
  726. glutAddMenuEntry("-----------------------", M_NONE);
  727. glutAddMenuEntry("Toggle reflection stenciling", M_STENCIL_REFLECTION);
  728. glutAddMenuEntry("Toggle shadow stenciling", M_STENCIL_SHADOW);
  729. glutAddMenuEntry("Toggle shadow offset", M_OFFSET_SHADOW);
  730. glutAddMenuEntry("----------------------", M_NONE);
  731. glutAddMenuEntry("Positional light", M_POSITIONAL);
  732. glutAddMenuEntry("Directional light", M_DIRECTIONAL);
  733. glutAddMenuEntry("-----------------------", M_NONE);
  734. glutAddMenuEntry("Toggle performance", M_PERFORMANCE);
  735. glutAttachMenu(GLUT_RIGHT_BUTTON);
  736. makeDinosaur();
  737. #ifdef GL_VERSION_1_1
  738. if (supportsOneDotOne() && !forceExtension) {
  739. polygonOffsetVersion = ONE_DOT_ONE;
  740. glPolygonOffset(-2.0, -9.0);
  741. } else
  742. #endif
  743. {
  744. #ifdef GL_EXT_polygon_offset
  745. /* check for the polygon offset extension */
  746. if (glutExtensionSupported("GL_EXT_polygon_offset")) {
  747. polygonOffsetVersion = EXTENSION;
  748. glPolygonOffsetEXT(-2.0, -0.002);
  749. } else
  750. #endif
  751. {
  752. polygonOffsetVersion = MISSING;
  753. printf("\ndinoshine: Missing polygon offset.\n");
  754. printf(" Expect shadow depth aliasing artifacts.\n\n");
  755. }
  756. }
  757. glEnable(GL_CULL_FACE);
  758. glEnable(GL_DEPTH_TEST);
  759. glEnable(GL_TEXTURE_2D);
  760. glLineWidth(3.0);
  761. glMatrixMode(GL_PROJECTION);
  762. gluPerspective( /* field of view in degree */ 40.0,
  763. /* aspect ratio */ 1.0,
  764. /* Z near */ 20.0, /* Z far */ 100.0);
  765. glMatrixMode(GL_MODELVIEW);
  766. gluLookAt(0.0, 8.0, 60.0, /* eye is at (0,8,60) */
  767. 0.0, 8.0, 0.0, /* center is at (0,8,0) */
  768. 0.0, 1.0, 0.); /* up is in postivie Y direction */
  769. glLightModeli(GL_LIGHT_MODEL_LOCAL_VIEWER, 1);
  770. glLightfv(GL_LIGHT0, GL_DIFFUSE, lightColor);
  771. glLightf(GL_LIGHT0, GL_CONSTANT_ATTENUATION, 0.1);
  772. glLightf(GL_LIGHT0, GL_LINEAR_ATTENUATION, 0.05);
  773. glEnable(GL_LIGHT0);
  774. glEnable(GL_LIGHTING);
  775. makeFloorTexture();
  776. /* Setup floor plane for projected shadow calculations. */
  777. findPlane(floorPlane, floorVertices[1], floorVertices[2], floorVertices[3]);
  778. glutMainLoop();
  779. return 0; /* ANSI C requires main to return int. */
  780. }