Clone of mesa.
Nevar pievienot vairāk kā 25 tēmas Tēmai ir jāsākas ar burtu vai ciparu, tā var saturēt domu zīmes ('-') un var būt līdz 35 simboliem gara.

dinoshade.c 25KB

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