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.

shadowtex.c 28KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003
  1. /*
  2. * Shadow demo using the GL_ARB_depth_texture, GL_ARB_shadow and
  3. * GL_ARB_shadow_ambient extensions.
  4. *
  5. * Brian Paul
  6. * 19 Feb 2001
  7. *
  8. * Added GL_EXT_shadow_funcs support on 23 March 2002
  9. * Added GL_EXT_packed_depth_stencil support on 15 March 2006.
  10. * Added GL_EXT_framebuffer_object support on 27 March 2006.
  11. * Removed old SGIX extension support on 5 April 2006.
  12. * Added vertex / fragment program support on 7 June 2007 (Ian Romanick).
  13. *
  14. * Copyright (C) 1999-2006 Brian Paul All Rights Reserved.
  15. *
  16. * Permission is hereby granted, free of charge, to any person obtaining a
  17. * copy of this software and associated documentation files (the "Software"),
  18. * to deal in the Software without restriction, including without limitation
  19. * the rights to use, copy, modify, merge, publish, distribute, sublicense,
  20. * and/or sell copies of the Software, and to permit persons to whom the
  21. * Software is furnished to do so, subject to the following conditions:
  22. *
  23. * The above copyright notice and this permission notice shall be included
  24. * in all copies or substantial portions of the Software.
  25. *
  26. * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
  27. * OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  28. * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
  29. * BRIAN PAUL BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN
  30. * AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
  31. * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
  32. */
  33. #define GL_GLEXT_PROTOTYPES
  34. #include <assert.h>
  35. #include <stdio.h>
  36. #include <stdlib.h>
  37. #include <string.h>
  38. #include <math.h>
  39. #include <GL/glut.h>
  40. #include "showbuffer.h"
  41. #define DEG_TO_RAD (3.14159 / 180.0)
  42. static GLint WindowWidth = 450, WindowHeight = 300;
  43. static GLfloat Xrot = 15, Yrot = 0, Zrot = 0;
  44. static GLfloat Red[4] = {1, 0, 0, 1};
  45. static GLfloat Green[4] = {0, 1, 0, 1};
  46. static GLfloat Blue[4] = {0, 0, 1, 1};
  47. static GLfloat Yellow[4] = {1, 1, 0, 1};
  48. static GLfloat LightDist = 10;
  49. static GLfloat LightLatitude = 45.0;
  50. static GLfloat LightLongitude = 45.0;
  51. static GLfloat LightPos[4];
  52. static GLfloat SpotDir[3];
  53. static GLfloat SpotAngle = 40.0 * DEG_TO_RAD;
  54. static GLfloat ShadowNear = 4.0, ShadowFar = 24.0;
  55. static GLint ShadowTexWidth = 256, ShadowTexHeight = 256;
  56. static GLboolean LinearFilter = GL_FALSE;
  57. static GLfloat Bias = -0.06;
  58. static GLboolean Anim = GL_TRUE;
  59. static GLboolean NeedNewShadowMap = GL_FALSE;
  60. static GLuint ShadowTexture, GrayTexture;
  61. static GLuint ShadowFBO;
  62. static GLfloat lightModelview[16];
  63. static GLfloat lightProjection[16];
  64. static GLuint vert_prog;
  65. static GLuint frag_progs[3];
  66. static GLuint curr_frag = 0;
  67. static GLuint max_frag = 1;
  68. #define NUM_FRAG_MODES 3
  69. static const char *FragProgNames[] = {
  70. "fixed-function",
  71. "program without \"OPTION ARB_fragment_program_shadow\"",
  72. "program with \"OPTION ARB_fragment_program_shadow\"",
  73. };
  74. static GLboolean HaveFBO = GL_FALSE;
  75. static GLboolean UseFBO = GL_FALSE;
  76. static GLboolean HaveVP = GL_FALSE;
  77. static GLboolean HaveFP = GL_FALSE;
  78. static GLboolean HaveFP_Shadow = GL_FALSE;
  79. static GLboolean UseVP = GL_FALSE;
  80. static GLboolean HavePackedDepthStencil = GL_FALSE;
  81. static GLboolean UsePackedDepthStencil = GL_FALSE;
  82. static GLboolean HaveEXTshadowFuncs = GL_FALSE;
  83. static GLboolean HaveShadowAmbient = GL_FALSE;
  84. static GLint Operator = 0;
  85. static const GLenum OperatorFunc[8] = {
  86. GL_LEQUAL, GL_LESS, GL_GEQUAL, GL_GREATER,
  87. GL_EQUAL, GL_NOTEQUAL, GL_ALWAYS, GL_NEVER };
  88. static const char *OperatorName[8] = {
  89. "GL_LEQUAL", "GL_LESS", "GL_GEQUAL", "GL_GREATER",
  90. "GL_EQUAL", "GL_NOTEQUAL", "GL_ALWAYS", "GL_NEVER" };
  91. static GLuint DisplayMode;
  92. #define SHOW_SHADOWS 0
  93. #define SHOW_DEPTH_IMAGE 1
  94. #define SHOW_DEPTH_MAPPING 2
  95. #define SHOW_DISTANCE 3
  96. #define MAT4_MUL(dest_vec, src_mat, src_vec) \
  97. "DP4 " dest_vec ".x, " src_mat "[0], " src_vec ";\n" \
  98. "DP4 " dest_vec ".y, " src_mat "[1], " src_vec ";\n" \
  99. "DP4 " dest_vec ".z, " src_mat "[2], " src_vec ";\n" \
  100. "DP4 " dest_vec ".w, " src_mat "[3], " src_vec ";\n"
  101. #define MAT3_MUL(dest_vec, src_mat, src_vec) \
  102. "DP3 " dest_vec ".x, " src_mat "[0], " src_vec ";\n" \
  103. "DP3 " dest_vec ".y, " src_mat "[1], " src_vec ";\n" \
  104. "DP3 " dest_vec ".z, " src_mat "[2], " src_vec ";\n"
  105. #define NORMALIZE(dest, src) \
  106. "DP3 " dest ".w, " src ", " src ";\n" \
  107. "RSQ " dest ".w, " dest ".w;\n" \
  108. "MUL " dest ", " src ", " dest ".w;\n"
  109. /**
  110. * Vertex program for shadow mapping.
  111. */
  112. static const char vert_code[] =
  113. "!!ARBvp1.0\n"
  114. "ATTRIB iPos = vertex.position;\n"
  115. "ATTRIB iNorm = vertex.normal;\n"
  116. "PARAM mvinv[4] = { state.matrix.modelview.invtrans };\n"
  117. "PARAM mvp[4] = { state.matrix.mvp };\n"
  118. "PARAM mv[4] = { state.matrix.modelview };\n"
  119. "PARAM texmat[4] = { state.matrix.texture[0] };\n"
  120. "PARAM lightPos = state.light[0].position;\n"
  121. "PARAM ambientCol = state.lightprod[0].ambient;\n"
  122. "PARAM diffuseCol = state.lightprod[0].diffuse;\n"
  123. "TEMP n, lightVec;\n"
  124. "ALIAS V = lightVec;\n"
  125. "ALIAS NdotL = n;\n"
  126. "OUTPUT oPos = result.position;\n"
  127. "OUTPUT oColor = result.color;\n"
  128. "OUTPUT oTex = result.texcoord[0];\n"
  129. /* Transform the vertex to clip coordinates. */
  130. MAT4_MUL("oPos", "mvp", "iPos")
  131. /* Transform the vertex to eye coordinates. */
  132. MAT4_MUL("V", "mv", "iPos")
  133. /* Transform the vertex to projected light coordinates. */
  134. MAT4_MUL("oTex", "texmat", "iPos")
  135. /* Transform the normal to eye coordinates. */
  136. MAT3_MUL("n", "mvinv", "iNorm")
  137. /* Calculate the vector from the vertex to the light in eye
  138. * coordinates.
  139. */
  140. "SUB lightVec, lightPos, V;\n"
  141. NORMALIZE("lightVec", "lightVec")
  142. /* Compute diffuse lighting coefficient.
  143. */
  144. "DP3 NdotL.x, n, lightVec;\n"
  145. "MAX NdotL.x, NdotL.x, {0.0};\n"
  146. "MIN NdotL.x, NdotL.x, {1.0};\n"
  147. /* Accumulate color contributions.
  148. */
  149. "MOV oColor, diffuseCol;\n"
  150. "MAD oColor.xyz, NdotL.x, diffuseCol, ambientCol;\n"
  151. "END\n"
  152. ;
  153. static const char frag_code[] =
  154. "!!ARBfp1.0\n"
  155. "TEMP shadow, temp;\n"
  156. "TXP shadow, fragment.texcoord[0], texture[0], 2D;\n"
  157. "RCP temp.x, fragment.texcoord[0].w;\n"
  158. "MUL temp.x, temp.x, fragment.texcoord[0].z;\n"
  159. "SGE shadow, shadow.x, temp.x;\n"
  160. "MUL result.color.rgb, fragment.color, shadow.x;\n"
  161. "MOV result.color.a, fragment.color;\n"
  162. "END\n"
  163. ;
  164. static const char frag_shadow_code[] =
  165. "!!ARBfp1.0\n"
  166. "OPTION ARB_fragment_program_shadow;\n"
  167. "TEMP shadow;\n"
  168. "TXP shadow, fragment.texcoord[0], texture[0], SHADOW2D;\n"
  169. "MUL result.color.rgb, fragment.color, shadow.x;\n"
  170. "MOV result.color.a, fragment.color.a;\n"
  171. "END\n"
  172. ;
  173. static void
  174. DrawScene(void)
  175. {
  176. GLfloat k = 6;
  177. /* sphere */
  178. glPushMatrix();
  179. glTranslatef(1.6, 2.2, 2.7);
  180. glMaterialfv(GL_FRONT_AND_BACK, GL_AMBIENT_AND_DIFFUSE, Green);
  181. glColor4fv(Green);
  182. glutSolidSphere(1.5, 15, 15);
  183. glPopMatrix();
  184. /* dodecahedron */
  185. glPushMatrix();
  186. glTranslatef(-2.0, 1.2, 2.1);
  187. glMaterialfv(GL_FRONT_AND_BACK, GL_AMBIENT_AND_DIFFUSE, Red);
  188. glColor4fv(Red);
  189. glutSolidDodecahedron();
  190. glPopMatrix();
  191. /* icosahedron */
  192. glPushMatrix();
  193. glTranslatef(-0.6, 1.3, -0.5);
  194. glScalef(1.5, 1.5, 1.5);
  195. glMaterialfv(GL_FRONT_AND_BACK, GL_AMBIENT_AND_DIFFUSE, Yellow);
  196. glColor4fv(Red);
  197. glutSolidIcosahedron();
  198. glPopMatrix();
  199. /* a plane */
  200. glPushMatrix();
  201. glTranslatef(0, -1.1, 0);
  202. glMaterialfv(GL_FRONT_AND_BACK, GL_AMBIENT_AND_DIFFUSE, Blue);
  203. glColor4fv(Blue);
  204. glNormal3f(0, 1, 0);
  205. glBegin(GL_POLYGON);
  206. glVertex3f(-k, 0, -k);
  207. glVertex3f( k, 0, -k);
  208. glVertex3f( k, 0, k);
  209. glVertex3f(-k, 0, k);
  210. glEnd();
  211. glPopMatrix();
  212. }
  213. /**
  214. * Calculate modelview and project matrices for the light
  215. *
  216. * Stores the results in \c lightProjection (projection matrix) and
  217. * \c lightModelview (modelview matrix).
  218. */
  219. static void
  220. MakeShadowMatrix(const GLfloat lightPos[4], const GLfloat spotDir[3],
  221. GLfloat spotAngle, GLfloat shadowNear, GLfloat shadowFar)
  222. {
  223. /* compute frustum to enclose spot light cone */
  224. const GLfloat d = shadowNear * tan(spotAngle);
  225. glMatrixMode(GL_PROJECTION);
  226. glPushMatrix();
  227. glLoadIdentity();
  228. glFrustum(-d, d, -d, d, shadowNear, shadowFar);
  229. glGetFloatv(GL_PROJECTION_MATRIX, lightProjection);
  230. glPopMatrix();
  231. glMatrixMode(GL_MODELVIEW);
  232. glPushMatrix();
  233. glLoadIdentity();
  234. gluLookAt(lightPos[0], lightPos[1], lightPos[2],
  235. lightPos[0] + spotDir[0],
  236. lightPos[1] + spotDir[1],
  237. lightPos[2] + spotDir[2],
  238. 0.0, 1.0, 0.0);
  239. glGetFloatv(GL_MODELVIEW_MATRIX, lightModelview);
  240. glPopMatrix();
  241. }
  242. /**
  243. * Load \c GL_TEXTURE matrix with light's MVP matrix.
  244. */
  245. static void SetShadowTextureMatrix(void)
  246. {
  247. static const GLfloat biasMatrix[16] = {
  248. 0.5, 0.0, 0.0, 0.0,
  249. 0.0, 0.5, 0.0, 0.0,
  250. 0.0, 0.0, 0.5, 0.0,
  251. 0.5, 0.5, 0.5, 1.0,
  252. };
  253. glMatrixMode(GL_TEXTURE);
  254. glLoadMatrixf(biasMatrix);
  255. glTranslatef(0.0, 0.0, Bias);
  256. glMultMatrixf(lightProjection);
  257. glMultMatrixf(lightModelview);
  258. glMatrixMode(GL_MODELVIEW);
  259. }
  260. static void
  261. EnableIdentityTexgen(void)
  262. {
  263. /* texgen so that texcoord = vertex coord */
  264. static GLfloat sPlane[4] = { 1, 0, 0, 0 };
  265. static GLfloat tPlane[4] = { 0, 1, 0, 0 };
  266. static GLfloat rPlane[4] = { 0, 0, 1, 0 };
  267. static GLfloat qPlane[4] = { 0, 0, 0, 1 };
  268. glTexGenfv(GL_S, GL_EYE_PLANE, sPlane);
  269. glTexGenfv(GL_T, GL_EYE_PLANE, tPlane);
  270. glTexGenfv(GL_R, GL_EYE_PLANE, rPlane);
  271. glTexGenfv(GL_Q, GL_EYE_PLANE, qPlane);
  272. glTexGeni(GL_S, GL_TEXTURE_GEN_MODE, GL_EYE_LINEAR);
  273. glTexGeni(GL_T, GL_TEXTURE_GEN_MODE, GL_EYE_LINEAR);
  274. glTexGeni(GL_R, GL_TEXTURE_GEN_MODE, GL_EYE_LINEAR);
  275. glTexGeni(GL_Q, GL_TEXTURE_GEN_MODE, GL_EYE_LINEAR);
  276. glEnable(GL_TEXTURE_GEN_S);
  277. glEnable(GL_TEXTURE_GEN_T);
  278. glEnable(GL_TEXTURE_GEN_R);
  279. glEnable(GL_TEXTURE_GEN_Q);
  280. }
  281. /*
  282. * Setup 1-D texgen so that the distance from the light source, between
  283. * the near and far planes maps to s=0 and s=1. When we draw the scene,
  284. * the grayness will indicate the fragment's distance from the light
  285. * source.
  286. */
  287. static void
  288. EnableDistanceTexgen(const GLfloat lightPos[4], const GLfloat lightDir[3],
  289. GLfloat lightNear, GLfloat lightFar)
  290. {
  291. GLfloat m, d;
  292. GLfloat sPlane[4];
  293. GLfloat nearPoint[3];
  294. m = sqrt(lightDir[0] * lightDir[0] +
  295. lightDir[1] * lightDir[1] +
  296. lightDir[2] * lightDir[2]);
  297. d = lightFar - lightNear;
  298. /* nearPoint = point on light direction vector which intersects the
  299. * near plane of the light frustum.
  300. */
  301. nearPoint[0] = lightPos[0] + lightDir[0] / m * lightNear;
  302. nearPoint[1] = lightPos[1] + lightDir[1] / m * lightNear;
  303. nearPoint[2] = lightPos[2] + lightDir[2] / m * lightNear;
  304. sPlane[0] = lightDir[0] / d / m;
  305. sPlane[1] = lightDir[1] / d / m;
  306. sPlane[2] = lightDir[2] / d / m;
  307. sPlane[3] = -(sPlane[0] * nearPoint[0]
  308. + sPlane[1] * nearPoint[1]
  309. + sPlane[2] * nearPoint[2]);
  310. glTexGenfv(GL_S, GL_EYE_PLANE, sPlane);
  311. glTexGeni(GL_S, GL_TEXTURE_GEN_MODE, GL_EYE_LINEAR);
  312. glEnable(GL_TEXTURE_GEN_S);
  313. }
  314. static void
  315. DisableTexgen(void)
  316. {
  317. glDisable(GL_TEXTURE_GEN_S);
  318. glDisable(GL_TEXTURE_GEN_T);
  319. glDisable(GL_TEXTURE_GEN_R);
  320. glDisable(GL_TEXTURE_GEN_Q);
  321. }
  322. static void
  323. ComputeLightPos(GLfloat dist, GLfloat latitude, GLfloat longitude,
  324. GLfloat pos[4], GLfloat dir[3])
  325. {
  326. pos[0] = dist * sin(longitude * DEG_TO_RAD);
  327. pos[1] = dist * sin(latitude * DEG_TO_RAD);
  328. pos[2] = dist * cos(latitude * DEG_TO_RAD) * cos(longitude * DEG_TO_RAD);
  329. pos[3] = 1;
  330. dir[0] = -pos[0];
  331. dir[1] = -pos[1];
  332. dir[2] = -pos[2];
  333. }
  334. /**
  335. * Render the shadow map / depth texture.
  336. * The result will be in the texture object named ShadowTexture.
  337. */
  338. static void
  339. RenderShadowMap(void)
  340. {
  341. GLenum depthFormat; /* GL_DEPTH_COMPONENT or GL_DEPTH_STENCIL_EXT */
  342. GLenum depthType; /* GL_UNSIGNED_INT_24_8_EXT or GL_UNSIGNED_INT */
  343. if (WindowWidth >= 1024 && WindowHeight >= 1024) {
  344. ShadowTexWidth = ShadowTexHeight = 1024;
  345. }
  346. else if (WindowWidth >= 512 && WindowHeight >= 512) {
  347. ShadowTexWidth = ShadowTexHeight = 512;
  348. }
  349. else if (WindowWidth >= 256 && WindowHeight >= 256) {
  350. ShadowTexWidth = ShadowTexHeight = 256;
  351. }
  352. else {
  353. ShadowTexWidth = ShadowTexHeight = 128;
  354. }
  355. printf("Rendering %d x %d depth texture\n", ShadowTexWidth, ShadowTexHeight);
  356. if (UsePackedDepthStencil) {
  357. depthFormat = GL_DEPTH_STENCIL_EXT;
  358. depthType = GL_UNSIGNED_INT_24_8_EXT;
  359. }
  360. else {
  361. depthFormat = GL_DEPTH_COMPONENT;
  362. depthType = GL_UNSIGNED_INT;
  363. }
  364. glMatrixMode(GL_PROJECTION);
  365. glLoadMatrixf(lightProjection);
  366. glMatrixMode(GL_MODELVIEW);
  367. glLoadMatrixf(lightModelview);
  368. if (UseFBO) {
  369. GLenum fbo_status;
  370. glTexImage2D(GL_TEXTURE_2D, 0, depthFormat,
  371. ShadowTexWidth, ShadowTexHeight, 0,
  372. depthFormat, depthType, NULL);
  373. /* Set the filter mode so that the texture is texture-complete.
  374. * Otherwise it will cause the framebuffer to fail the framebuffer
  375. * completeness test.
  376. */
  377. glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST);
  378. glBindFramebufferEXT(GL_FRAMEBUFFER_EXT, ShadowFBO);
  379. glDrawBuffer(GL_NONE);
  380. glReadBuffer(GL_NONE);
  381. fbo_status = glCheckFramebufferStatusEXT(GL_FRAMEBUFFER_EXT);
  382. if (fbo_status != GL_FRAMEBUFFER_COMPLETE_EXT) {
  383. fprintf(stderr, "FBO not complete! status = 0x%04x\n", fbo_status);
  384. assert(fbo_status == GL_FRAMEBUFFER_COMPLETE_EXT);
  385. }
  386. }
  387. assert(!glIsEnabled(GL_TEXTURE_1D));
  388. assert(!glIsEnabled(GL_TEXTURE_2D));
  389. glViewport(0, 0, ShadowTexWidth, ShadowTexHeight);
  390. glClear(GL_DEPTH_BUFFER_BIT);
  391. glEnable(GL_DEPTH_TEST);
  392. DrawScene();
  393. if (UseFBO) {
  394. /* all done! */
  395. glBindFramebufferEXT(GL_FRAMEBUFFER_EXT, 0);
  396. }
  397. else {
  398. /*
  399. * copy depth buffer into the texture map
  400. */
  401. if (DisplayMode == SHOW_DEPTH_MAPPING) {
  402. /* load depth image as gray-scale luminance texture */
  403. GLuint *depth = (GLuint *)
  404. malloc(ShadowTexWidth * ShadowTexHeight * sizeof(GLuint));
  405. assert(depth);
  406. glReadPixels(0, 0, ShadowTexWidth, ShadowTexHeight,
  407. depthFormat, depthType, depth);
  408. glTexImage2D(GL_TEXTURE_2D, 0, GL_LUMINANCE,
  409. ShadowTexWidth, ShadowTexHeight, 0,
  410. GL_LUMINANCE, GL_UNSIGNED_INT, depth);
  411. free(depth);
  412. }
  413. else {
  414. /* The normal shadow case - a real depth texture */
  415. glCopyTexImage2D(GL_TEXTURE_2D, 0, depthFormat,
  416. 0, 0, ShadowTexWidth, ShadowTexHeight, 0);
  417. if (UsePackedDepthStencil) {
  418. /* debug check */
  419. GLint intFormat;
  420. glGetTexLevelParameteriv(GL_TEXTURE_2D, 0,
  421. GL_TEXTURE_INTERNAL_FORMAT, &intFormat);
  422. assert(intFormat == GL_DEPTH_STENCIL_EXT);
  423. }
  424. }
  425. }
  426. }
  427. /**
  428. * Show the shadow map as a grayscale image.
  429. */
  430. static void
  431. ShowShadowMap(void)
  432. {
  433. glClear(GL_COLOR_BUFFER_BIT);
  434. glMatrixMode(GL_TEXTURE);
  435. glLoadIdentity();
  436. glMatrixMode(GL_PROJECTION);
  437. glLoadIdentity();
  438. glOrtho(0, WindowWidth, 0, WindowHeight, -1, 1);
  439. glMatrixMode(GL_MODELVIEW);
  440. glLoadIdentity();
  441. glDisable(GL_DEPTH_TEST);
  442. glDisable(GL_LIGHTING);
  443. glEnable(GL_TEXTURE_2D);
  444. DisableTexgen();
  445. /* interpret texture's depth values as luminance values */
  446. glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_COMPARE_MODE_ARB, GL_NONE);
  447. glTexParameteri(GL_TEXTURE_2D, GL_DEPTH_TEXTURE_MODE_ARB, GL_LUMINANCE);
  448. glTexEnvi(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_REPLACE);
  449. glBegin(GL_POLYGON);
  450. glTexCoord2f(0, 0); glVertex2f(0, 0);
  451. glTexCoord2f(1, 0); glVertex2f(ShadowTexWidth, 0);
  452. glTexCoord2f(1, 1); glVertex2f(ShadowTexWidth, ShadowTexHeight);
  453. glTexCoord2f(0, 1); glVertex2f(0, ShadowTexHeight);
  454. glEnd();
  455. glDisable(GL_TEXTURE_2D);
  456. glEnable(GL_DEPTH_TEST);
  457. glEnable(GL_LIGHTING);
  458. }
  459. /**
  460. * Redraw window image
  461. */
  462. static void
  463. Display(void)
  464. {
  465. GLenum error;
  466. ComputeLightPos(LightDist, LightLatitude, LightLongitude,
  467. LightPos, SpotDir);
  468. if (NeedNewShadowMap) {
  469. MakeShadowMatrix(LightPos, SpotDir, SpotAngle, ShadowNear, ShadowFar);
  470. RenderShadowMap();
  471. NeedNewShadowMap = GL_FALSE;
  472. }
  473. glViewport(0, 0, WindowWidth, WindowHeight);
  474. if (DisplayMode == SHOW_DEPTH_IMAGE) {
  475. ShowShadowMap();
  476. }
  477. else {
  478. /* prepare to draw scene from camera's view */
  479. const GLfloat ar = (GLfloat) WindowWidth / (GLfloat) WindowHeight;
  480. glMatrixMode(GL_PROJECTION);
  481. glLoadIdentity();
  482. glFrustum(-ar, ar, -1.0, 1.0, 4.0, 50.0);
  483. glMatrixMode(GL_MODELVIEW);
  484. glLoadIdentity();
  485. glTranslatef(0.0, 0.0, -22.0);
  486. glRotatef(Xrot, 1, 0, 0);
  487. glRotatef(Yrot, 0, 1, 0);
  488. glRotatef(Zrot, 0, 0, 1);
  489. glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
  490. glLightfv(GL_LIGHT0, GL_POSITION, LightPos);
  491. if (LinearFilter) {
  492. glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
  493. glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
  494. }
  495. else {
  496. glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST);
  497. glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST);
  498. }
  499. if (DisplayMode == SHOW_DEPTH_MAPPING) {
  500. glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_COMPARE_MODE_ARB, GL_NONE);
  501. glTexEnvi(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_REPLACE);
  502. glEnable(GL_TEXTURE_2D);
  503. SetShadowTextureMatrix();
  504. EnableIdentityTexgen();
  505. }
  506. else if (DisplayMode == SHOW_DISTANCE) {
  507. glMatrixMode(GL_TEXTURE);
  508. glLoadIdentity();
  509. glMatrixMode(GL_MODELVIEW);
  510. EnableDistanceTexgen(LightPos, SpotDir, ShadowNear+Bias, ShadowFar);
  511. glTexEnvi(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_REPLACE);
  512. glEnable(GL_TEXTURE_1D);
  513. assert(!glIsEnabled(GL_TEXTURE_2D));
  514. }
  515. else {
  516. assert(DisplayMode == SHOW_SHADOWS);
  517. glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_COMPARE_MODE_ARB,
  518. GL_COMPARE_R_TO_TEXTURE_ARB);
  519. if (curr_frag > 0) {
  520. glEnable(GL_FRAGMENT_PROGRAM_ARB);
  521. }
  522. else {
  523. glTexEnvi(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_MODULATE);
  524. }
  525. glEnable(GL_TEXTURE_2D);
  526. SetShadowTextureMatrix();
  527. if (UseVP) {
  528. glEnable(GL_VERTEX_PROGRAM_ARB);
  529. }
  530. else {
  531. glEnable(GL_LIGHTING);
  532. EnableIdentityTexgen();
  533. }
  534. }
  535. DrawScene();
  536. if (UseVP) {
  537. glDisable(GL_VERTEX_PROGRAM_ARB);
  538. }
  539. else {
  540. DisableTexgen();
  541. glDisable(GL_LIGHTING);
  542. }
  543. if (curr_frag > 0) {
  544. glDisable(GL_FRAGMENT_PROGRAM_ARB);
  545. }
  546. glDisable(GL_TEXTURE_1D);
  547. glDisable(GL_TEXTURE_2D);
  548. }
  549. glutSwapBuffers();
  550. error = glGetError();
  551. if (error) {
  552. printf("GL Error: %s\n", (char *) gluErrorString(error));
  553. }
  554. }
  555. static void
  556. Reshape(int width, int height)
  557. {
  558. WindowWidth = width;
  559. WindowHeight = height;
  560. NeedNewShadowMap = GL_TRUE;
  561. }
  562. static void
  563. Idle(void)
  564. {
  565. static double t0 = -1.;
  566. double dt, t = glutGet(GLUT_ELAPSED_TIME) / 1000.0;
  567. if (t0 < 0.0)
  568. t0 = t;
  569. dt = t - t0;
  570. t0 = t;
  571. Yrot += 75.0 * dt;
  572. /*LightLongitude -= 5.0;*/
  573. glutPostRedisplay();
  574. }
  575. static void
  576. Key(unsigned char key, int x, int y)
  577. {
  578. const GLfloat step = 3.0;
  579. (void) x;
  580. (void) y;
  581. switch (key) {
  582. case 'a':
  583. Anim = !Anim;
  584. if (Anim)
  585. glutIdleFunc(Idle);
  586. else
  587. glutIdleFunc(NULL);
  588. break;
  589. case 'b':
  590. Bias -= 0.01;
  591. printf("Bias %g\n", Bias);
  592. break;
  593. case 'B':
  594. Bias += 0.01;
  595. printf("Bias %g\n", Bias);
  596. break;
  597. case 'd':
  598. DisplayMode = SHOW_DISTANCE;
  599. break;
  600. case 'f':
  601. LinearFilter = !LinearFilter;
  602. printf("%s filtering\n", LinearFilter ? "Bilinear" : "Nearest");
  603. break;
  604. case 'i':
  605. DisplayMode = SHOW_DEPTH_IMAGE;
  606. break;
  607. case 'm':
  608. DisplayMode = SHOW_DEPTH_MAPPING;
  609. break;
  610. case 'M':
  611. curr_frag = (1 + curr_frag) % max_frag;
  612. printf("Using fragment %s\n", FragProgNames[curr_frag]);
  613. if (HaveFP) {
  614. glBindProgramARB(GL_FRAGMENT_PROGRAM_ARB, frag_progs[curr_frag]);
  615. }
  616. break;
  617. case 'n':
  618. case 's':
  619. case ' ':
  620. DisplayMode = SHOW_SHADOWS;
  621. break;
  622. case 'o':
  623. if (HaveEXTshadowFuncs) {
  624. Operator++;
  625. if (Operator >= 8)
  626. Operator = 0;
  627. printf("Operator: %s\n", OperatorName[Operator]);
  628. glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_COMPARE_FUNC_ARB,
  629. OperatorFunc[Operator]);
  630. }
  631. break;
  632. case 'p':
  633. UsePackedDepthStencil = !UsePackedDepthStencil;
  634. if (UsePackedDepthStencil && !HavePackedDepthStencil) {
  635. printf("Sorry, GL_EXT_packed_depth_stencil not supported\n");
  636. UsePackedDepthStencil = GL_FALSE;
  637. }
  638. else {
  639. printf("Use GL_DEPTH_STENCIL_EXT: %d\n", UsePackedDepthStencil);
  640. /* Don't really need to regenerate shadow map texture, but do so
  641. * to exercise more code more often.
  642. */
  643. NeedNewShadowMap = GL_TRUE;
  644. }
  645. break;
  646. case 'v':
  647. UseVP = !UseVP && HaveVP;
  648. printf("Using vertex %s mode.\n",
  649. UseVP ? "program" : "fixed-function");
  650. break;
  651. case 'z':
  652. Zrot -= step;
  653. break;
  654. case 'Z':
  655. Zrot += step;
  656. break;
  657. case 27:
  658. exit(0);
  659. break;
  660. }
  661. glutPostRedisplay();
  662. }
  663. static void
  664. SpecialKey(int key, int x, int y)
  665. {
  666. const GLfloat step = 3.0;
  667. const int mod = glutGetModifiers();
  668. (void) x;
  669. (void) y;
  670. switch (key) {
  671. case GLUT_KEY_UP:
  672. if (mod)
  673. LightLatitude += step;
  674. else
  675. Xrot += step;
  676. break;
  677. case GLUT_KEY_DOWN:
  678. if (mod)
  679. LightLatitude -= step;
  680. else
  681. Xrot -= step;
  682. break;
  683. case GLUT_KEY_LEFT:
  684. if (mod)
  685. LightLongitude += step;
  686. else
  687. Yrot += step;
  688. break;
  689. case GLUT_KEY_RIGHT:
  690. if (mod)
  691. LightLongitude -= step;
  692. else
  693. Yrot -= step;
  694. break;
  695. }
  696. if (mod)
  697. NeedNewShadowMap = GL_TRUE;
  698. glutPostRedisplay();
  699. }
  700. /* A helper for finding errors in program strings */
  701. static int FindLine( const char *program, int position )
  702. {
  703. int i, line = 1;
  704. for (i = 0; i < position; i++) {
  705. if (program[i] == '\n')
  706. line++;
  707. }
  708. return line;
  709. }
  710. static GLuint
  711. compile_program(GLenum target, const char *code)
  712. {
  713. GLuint p;
  714. GLint errorPos;
  715. glGenProgramsARB(1, & p);
  716. glBindProgramARB(target, p);
  717. glProgramStringARB(target, GL_PROGRAM_FORMAT_ASCII_ARB,
  718. strlen(code), code);
  719. glGetIntegerv(GL_PROGRAM_ERROR_POSITION_ARB, &errorPos);
  720. if (glGetError() != GL_NO_ERROR || errorPos != -1) {
  721. int l = FindLine(code, errorPos);
  722. printf("Fragment Program Error (pos=%d line=%d): %s\n", errorPos, l,
  723. (char *) glGetString(GL_PROGRAM_ERROR_STRING_ARB));
  724. exit(0);
  725. }
  726. glBindProgramARB(target, 0);
  727. return p;
  728. }
  729. static void
  730. Init(void)
  731. {
  732. static const GLfloat borderColor[4] = {1.0, 0.0, 0.0, 0.0};
  733. if (!glutExtensionSupported("GL_ARB_depth_texture") ||
  734. !glutExtensionSupported("GL_ARB_shadow")) {
  735. printf("Sorry, this demo requires the GL_ARB_depth_texture and GL_ARB_shadow extensions\n");
  736. exit(1);
  737. }
  738. printf("Using GL_ARB_depth_texture and GL_ARB_shadow\n");
  739. HaveVP = glutExtensionSupported("GL_ARB_vertex_program");
  740. HaveFP = glutExtensionSupported("GL_ARB_fragment_program");
  741. HaveFP_Shadow = glutExtensionSupported("GL_ARB_fragment_program_shadow");
  742. HaveShadowAmbient = glutExtensionSupported("GL_ARB_shadow_ambient");
  743. if (HaveShadowAmbient) {
  744. printf("and GL_ARB_shadow_ambient\n");
  745. }
  746. HaveEXTshadowFuncs = glutExtensionSupported("GL_EXT_shadow_funcs");
  747. HavePackedDepthStencil = glutExtensionSupported("GL_EXT_packed_depth_stencil");
  748. UsePackedDepthStencil = HavePackedDepthStencil;
  749. #if defined(GL_EXT_framebuffer_object)
  750. HaveFBO = glutExtensionSupported("GL_EXT_framebuffer_object");
  751. UseFBO = HaveFBO;
  752. if (UseFBO) {
  753. printf("Using GL_EXT_framebuffer_object\n");
  754. }
  755. #endif
  756. /*
  757. * Set up the 2D shadow map texture
  758. */
  759. glGenTextures(1, &ShadowTexture);
  760. glBindTexture(GL_TEXTURE_2D, ShadowTexture);
  761. glTexParameterfv(GL_TEXTURE_2D, GL_TEXTURE_BORDER_COLOR, borderColor);
  762. glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP);
  763. glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP);
  764. glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_COMPARE_MODE_ARB,
  765. GL_COMPARE_R_TO_TEXTURE_ARB);
  766. glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_COMPARE_FUNC_ARB, GL_LEQUAL);
  767. if (HaveShadowAmbient) {
  768. glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_COMPARE_FAIL_VALUE_ARB, 0.3);
  769. }
  770. #if defined(GL_EXT_framebuffer_object)
  771. if (UseFBO) {
  772. glGenFramebuffersEXT(1, &ShadowFBO);
  773. glBindFramebufferEXT(GL_FRAMEBUFFER_EXT, ShadowFBO);
  774. glFramebufferRenderbufferEXT(GL_FRAMEBUFFER_EXT,
  775. GL_COLOR_ATTACHMENT0_EXT,
  776. GL_RENDERBUFFER_EXT, 0);
  777. glFramebufferTexture2DEXT(GL_FRAMEBUFFER_EXT, GL_DEPTH_ATTACHMENT_EXT,
  778. GL_TEXTURE_2D, ShadowTexture, 0);
  779. glBindFramebufferEXT(GL_FRAMEBUFFER_EXT, 0);
  780. }
  781. #endif
  782. /*
  783. * Setup 1-D grayscale texture image for SHOW_DISTANCE mode
  784. */
  785. glGenTextures(1, &GrayTexture);
  786. glBindTexture(GL_TEXTURE_1D, GrayTexture);
  787. glTexParameteri(GL_TEXTURE_1D, GL_TEXTURE_WRAP_S, GL_CLAMP);
  788. glTexParameteri(GL_TEXTURE_1D, GL_TEXTURE_WRAP_T, GL_CLAMP);
  789. glTexParameteri(GL_TEXTURE_1D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
  790. glTexParameteri(GL_TEXTURE_1D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
  791. {
  792. GLuint i;
  793. GLubyte image[256];
  794. for (i = 0; i < 256; i++)
  795. image[i] = i;
  796. glTexImage1D(GL_TEXTURE_1D, 0, GL_LUMINANCE,
  797. 256, 0, GL_LUMINANCE, GL_UNSIGNED_BYTE, image);
  798. }
  799. if (HaveVP) {
  800. vert_prog = compile_program(GL_VERTEX_PROGRAM_ARB, vert_code);
  801. glBindProgramARB(GL_VERTEX_PROGRAM_ARB, vert_prog);
  802. }
  803. max_frag = 1;
  804. frag_progs[0] = 0;
  805. if (HaveFP) {
  806. frag_progs[1] = compile_program(GL_FRAGMENT_PROGRAM_ARB, frag_code);
  807. max_frag = 2;
  808. }
  809. if (HaveFP && HaveFP_Shadow) {
  810. frag_progs[2] = compile_program(GL_FRAGMENT_PROGRAM_ARB,
  811. frag_shadow_code);
  812. max_frag = 3;
  813. }
  814. glEnable(GL_DEPTH_TEST);
  815. glEnable(GL_LIGHTING);
  816. glEnable(GL_LIGHT0);
  817. }
  818. static void
  819. PrintHelp(void)
  820. {
  821. printf("Keys:\n");
  822. printf(" a = toggle animation\n");
  823. printf(" i = show depth texture image\n");
  824. printf(" m = show depth texture mapping\n");
  825. printf(" d = show fragment distance from light source\n");
  826. printf(" n = show normal, shadowed image\n");
  827. printf(" f = toggle nearest/bilinear texture filtering\n");
  828. printf(" b/B = decrease/increase shadow map Z bias\n");
  829. printf(" p = toggle use of packed depth/stencil\n");
  830. printf(" M = cycle through fragment program modes\n");
  831. printf(" v = toggle vertex program modes\n");
  832. printf(" cursor keys = rotate scene\n");
  833. printf(" <shift> + cursor keys = rotate light source\n");
  834. if (HaveEXTshadowFuncs)
  835. printf(" o = cycle through comparison modes\n");
  836. }
  837. int
  838. main(int argc, char *argv[])
  839. {
  840. glutInit(&argc, argv);
  841. glutInitWindowPosition(0, 0);
  842. glutInitWindowSize(WindowWidth, WindowHeight);
  843. glutInitDisplayMode(GLUT_RGB | GLUT_DOUBLE | GLUT_DEPTH | GLUT_STENCIL);
  844. glutCreateWindow(argv[0]);
  845. glutReshapeFunc(Reshape);
  846. glutKeyboardFunc(Key);
  847. glutSpecialFunc(SpecialKey);
  848. glutDisplayFunc(Display);
  849. if (Anim)
  850. glutIdleFunc(Idle);
  851. Init();
  852. PrintHelp();
  853. glutMainLoop();
  854. return 0;
  855. }