home *** CD-ROM | disk | FTP | other *** search
/ Usenet 1994 October / usenetsourcesnewsgroupsinfomagicoctober1994disk2.iso / misc / volume21 / rayshade / part13 (.txt) < prev    next >
LaTeX Document  |  1991-07-21  |  47KB  |  1,245 lines

  1. Newsgroups: comp.sources.misc
  2. From: Rayshade Construction Co. <rayshade@weedeater.math.YALE.EDU>
  3. Subject:  v21i016:  rayshade - A raytracing package for UNIX, Part13/19
  4. Message-ID: <1991Jul21.033819.29294@sparky.IMD.Sterling.COM>
  5. X-Md4-Signature: 53f3ff77cd6fa10e38fc8bd025d16e01
  6. Date: Sun, 21 Jul 1991 03:38:19 GMT
  7. Approved: kent@sparky.imd.sterling.com
  8. Submitted-by: Rayshade Construction Co. <rayshade@weedeater.math.YALE.EDU>
  9. Posting-number: Volume 21, Issue 16
  10. Archive-name: rayshade/part13
  11. Environment: UNIX, !16BIT
  12. #! /bin/sh
  13. # This is a shell archive.  Remove anything before this line, then unpack
  14. # it by saving it into a file and typing "sh file".  To overwrite existing
  15. # files, type "sh file -c".  You can also feed this as standard input via
  16. # unshar, or by typing "sh <file", e.g..  If this archive is complete, you
  17. # will see the following message at the end:
  18. #        "End of archive 13 (of 19)."
  19. # Contents:  Doc/Guide/surfaces.tex libray/libcommon/transform.c
  20. #   libray/libobj/csg.c libshade/shade.c
  21. # Wrapped by kolb@woody on Wed Jul 17 17:56:52 1991
  22. PATH=/bin:/usr/bin:/usr/ucb ; export PATH
  23. if test -f 'Doc/Guide/surfaces.tex' -a "${1}" != "-c" ; then 
  24.   echo shar: Will not clobber existing file \"'Doc/Guide/surfaces.tex'\"
  25. echo shar: Extracting \"'Doc/Guide/surfaces.tex'\" \(10193 characters\)
  26. sed "s/^X//" >'Doc/Guide/surfaces.tex' <<'END_OF_FILE'
  27. X\chapter{Surfaces and Atmospheric Effects}
  28. XSurfaces are used to control the interaction between light sources and
  29. Xobjects.  A surface specification consists of information
  30. Xabout how the light interacts with both the exterior and
  31. Xinterior of an object .
  32. XFor non-closed objects, such as polygons,
  33. Xthe ``interior'' of an object is the ``other side'' of the object's surface
  34. Xrelative to the origin of a ray.
  35. XRayshade usually ensures that a primitive's surface normal is pointing
  36. Xtowards the origin of the incident ray when performing shading
  37. Xcalculations.  Exceptions to this rule are transparent primitives, for
  38. Xwhich rayshade uses the direction of the surface normal to determine if
  39. Xthe incident ray is entering or exiting the object.
  40. XAll non-transparent primitives will, in effect, be double-sided.
  41. X\section{Surface Description}
  42. XA surface definition consists of a number of component keywords, each
  43. Xof which is usually followed by either a single number or a red-green-blue
  44. Xcolor triple.   Each of the values in the color triple are normalized,
  45. Xwith zero indicating zero intensity, and one indicating full intensity.
  46. XIf any surface component is left unspecified, its value defaults to zero,
  47. Xwith the exception of the index of refraction, which is assigned the
  48. Xdefault index of refraction (normally 1.0).
  49. XSurface descriptions are used in rayshade to compute the color of a ray
  50. Xthat strikes the surface at a point \evec{P}. The normal to the surface
  51. Xat \evec{P}, \evec{N}, is also computed.
  52. X\begin{defkey}{ambient}{\evec{color}}
  53. X    Use the given {\em color} to approximate those surface-surface 
  54. X    interactions (e.g., diffuse interreflection) not modeled by the
  55. X    ray tracing process.
  56. X\end{defkey}
  57. XA surface's ambient color is always applied to a ray.  The color
  58. Xapplied is computed by multiplying the ambient color by the intensity
  59. Xof the ambient light source.
  60. XIf \evec{P} is in shadow with respect to a given light source,
  61. Xthat light source makes no contribution to the shading of \evec{P}.
  62. X\begin{defkey}{diffuse}{\evec{color}}
  63. X    Specifies the diffuse color.
  64. X\end{defkey}
  65. XThe diffuse contribution from each non-shadowed light source at \evec{P}
  66. Xis equal to the diffuse color of the surface scaled by the cosine of
  67. Xthe angle between \evec{N}
  68. Xand the vector from \evec{P} to the light source.
  69. X\begin{defkey}{specular}{\evec{color}}
  70. X    Specifies the base color of specular reflections.
  71. X\end{defkey}
  72. X\begin{defkey}{specpow}{{\em exponent}}
  73. X    Specifies the specular highlight) exponent.
  74. X\end{defkey}
  75. XThe intensity of specular highlights from light sources are
  76. Xscaled by the specular color of the surface.
  77. X\begin{defkey}{reflect}{{\em reflectivity}}
  78. X    Specifies the specular reflectivity of the surface.  If non-zero,
  79. X    reflected rays will be spawned.
  80. X\end{defkey}
  81. XThe intensity of specularly reflected rays will be proportional to
  82. Xthe specular color of the surface scaled by the reflectivity.
  83. X\begin{defkey}{transp}{{\em transparency}}
  84. X    Specifies the specular transmissivity of the surface.  If
  85. X    non-zero,
  86. X    transmitted (refracted) rays will be spawned.
  87. X\end{defkey}
  88. X\begin{defkey}{body}{\evec{color}}
  89. X    Specifies the body color of the object.  The body color
  90. X    affects the color of rays that are transmitted through the
  91. X    object.
  92. X\end{defkey}
  93. X\begin{defkey}{extinct}{{\em coefficient}}
  94. X    Specifies the extinction coefficient of the interior
  95. X    of the object.
  96. X\end{defkey}
  97. XThe extinction coefficient is raised to a power equal to the distance
  98. Xthe transmitted ray travels through the object.
  99. XThe overall intensity of specularly transmitted rays will be proportional to
  100. Xthis factor multiplied by the surface's body color
  101. Xmultiplied by the transparency of the object.
  102. X\begin{defkey}{index}{{\em N}}
  103. X    Specifies the index of refraction.  The default value is equal
  104. X    to the index of refraction of the atmosphere surrounding the eye.
  105. X\end{defkey}
  106. X\begin{defkey}{translucency}{{\em translu} \evec{color} {\em stexp}}
  107. X    Specifies the translucency, diffusely transmitted color,
  108. X    and Phong exponent for transmitted specular highlights.
  109. X\end{defkey}
  110. XIf a light source illuminates a translucent surface from the side opposite
  111. Xthat from which a ray approaches, illumination computations are performed,
  112. Xusing the given color as the surface's diffuse color, and the given
  113. Xexponent as the Phong highlight exponent.  The resulting color is then
  114. Xscaled by the surface's translucency.
  115. X\section{Atmospheric Effects}
  116. XAny number of atmospheric effects may also be associated with a surface.
  117. XThese effects will be applied to those rays that are transmitted through
  118. Xthe surface.  Applying atmospheric effects to opaque objects is a waste
  119. Xof input file.
  120. X\begin{defkey}{fog}{\evec{color} \evec{thinness}}
  121. XAdd exponential fog with the specified {\em thinness} and {\em color}.
  122. X\end{defkey}
  123. XFog is simulated by blending the color of the fog with the color of
  124. Xeach ray.  The amount of fog color blended into a ray color is an exponential
  125. Xfunction of the distance from the ray origin to the point of intersection
  126. Xdivided by the specified {\em thinness} for each color channel.
  127. XIf the distance is equal to {\em thinness},
  128. Xa ray's new color will be half of the fog color plus half its
  129. Xoriginal color.
  130. X\begin{defkey}{mist}{\evec{color} \evec{thinness} {\em zero scale}}
  131. XAdd global low-altitude mist of the specified color.  The color of
  132. Xa ray is modulated by a fog with density that varies linearly with
  133. Xthe difference in $z$ coordinate (altitude) between the ray origin and
  134. Xthe point of intersection.  The thinness values specify the transmissivity
  135. Xof the fog for each color channel.
  136. XThe base altitude of the
  137. Xmist is given by {\em zero}, and the apparent height of the mist can
  138. Xbe modulated using {\em scale}, which scales the difference in
  139. Xaltitude used to compute the fog.
  140. X\end{defkey}
  141. X\section {The Default Medium}
  142. XThe default medium is the medium which surrounds and encompasses
  143. Xall of the objects in the scene; it is the ``air'' through which eye
  144. Xrays usually travel before hitting an object.  The properties of
  145. Xthe default medium may be modified through the use of the {\tt atmosphere}
  146. Xkeyword.
  147. X\begin{defkey}{atmosphere}{[{\em N\/}] [{\em atmospheric effects}]}
  148. XIf given, {\em N} specifies the index of refraction of the default
  149. Xmedium.  The default is 1.0.  Any atmospheric effects listed are applied
  150. Xto rays that are exterior to every object in the scene (e.g., rays
  151. Xemanating from the camera).
  152. X\end{defkey}
  153. X\begin{verbatim}
  154. X    /*
  155. X     * Red sphere on a grey plane, with fog.
  156. X     */
  157. X    eyep 0. -10. 2.
  158. X    atmosphere fog  .8 .8 .8 14. 14. 14.
  159. X    plane 0 0 0  0 0 1
  160. X    sphere diffuse 0.8 0 0   1.5  0 0 1.5
  161. X\end{verbatim}
  162. X\section {Surface Specification}
  163. X{\em Rayshade} provides a number of ways to define surfaces and to
  164. Xbind these surfaces to objects.  The most straight-forward method
  165. Xof surface specification is to simply list the surface properties to
  166. Xbe used.
  167. XAlternatively, one may associate a name with a given surface.
  168. XThis name may subsequently be used to refer to that surface.
  169. X\begin{defkey}{surface}{{\em name\/} $<${\em Surface Definition}$>$}
  170. X    Associate the given collection of surface attributes with the
  171. X    given name.
  172. X\end{defkey}
  173. XThe binding of a collection of surface properties to a given object
  174. Xis accomplished in a bottom-up manner; the surface that ``closest''
  175. Xin the modeling tree to the primitive being rendered is the one that
  176. Xis used to give the primitive its appearance.
  177. XAn object that has no surface bound to it is assigned a default surface
  178. Xthat give an object the appearance of white plastic.
  179. XThe first
  180. Xand most direct way to bind a surface to a primitive
  181. Xis by specifying the surface to be bound to
  182. Xthe primitive when it is instantiated.
  183. XThis is accomplished
  184. Xby inserting a list of surface attributes or a surface name after
  185. Xthe primitive's type keyword and before the actual primitive data.
  186. X\begin{verbatim}
  187. X    /*
  188. X     * A red 'mud' colored sphere reseting on a
  189. X     * white sphere. To the right is a sphere with
  190. X     * default surface attributes.
  191. X     */
  192. X    surface mud ambient .03 0. 0.  diffuse .7 .3 0.
  193. X    sphere  ambient .05 .05 .05 diffuse .7 .7 .7   1. 0 0 0
  194. X    sphere mud  1. 0 0 2
  195. X    sphere 1. 1.5 0 0
  196. X\end{verbatim}
  197. XHere, we define a red surface named ``mud''.  We then instantiate
  198. Xa sphere, which has a diffuse white surface bound to it.  The
  199. Xnext line instantiates a sphere with the defined ``mud'' surface bound
  200. Xto it.  The last line instantiates a sphere with no surface bound to it;
  201. Xit is assigned the default surface by {\em rayshade}.
  202. XThe {\tt applysurf} keyword may be used to set the default surface
  203. Xcharacteristics for the aggregate object currently being defined.
  204. X\begin{defkey}{applysurf}{$<${\em Surface Specification}$>$}
  205. XThe specified surface is applied to all following
  206. Xinstantiated objects that do not have surfaces associated with them.
  207. XThe scope of this keyword is limited to the aggregate currently
  208. Xbeing defined.
  209. X\end{defkey}
  210. X\begin{verbatim}
  211. X    /*
  212. X     * Mirrored ball and cylinder sitting on 'default' plane.
  213. X     */
  214. X    surface mirror .01 .01 .01  diffuse .05 .05 .05
  215. X            specular .8 .8 .8 speccoef 20  reflect 0.95
  216. X    plane 0 0 0  0 0 1
  217. X    applysurf mirror
  218. X    sphere 1 0 0 0
  219. X    cylinder 1  3 0 0  3 0 3
  220. X\end{verbatim}
  221. XFor convenience, the name {\tt cursurf} may be used to refer to the
  222. Xcurrent default surface.
  223. XThe utility of bottom-up binding of surfaces lies in the fact that
  224. Xone may be as adamant or as noncommittal about
  225. Xsurface binding as one sees fit when defining objects.  For example,
  226. Xone could define a king chess piece consisting of triangles that have no
  227. Xsurface bound to them, save for the cross on top, which has
  228. Xa gold-colored surface associated with it.  One may then instantiate
  229. Xthe king twice, once applying a black surface, and once applying
  230. Xa white surface.  The result:  a black king and a white king, each
  231. Xadorned with a golden cross.
  232. X\begin{verbatim}
  233. X    surface white ...
  234. X    surface black ...
  235. X    surface gold  ...
  236. X    ...
  237. X    define cross
  238. X            box x y z  x y z
  239. X            ...
  240. X    defend
  241. X    define king
  242. X            triangle x y z  x y z  x y z
  243. X            ...
  244. X            object gold cross
  245. X    defend
  246. X    object white king translate 1. 0 0
  247. X    object black king
  248. X\end{verbatim}
  249. END_OF_FILE
  250. if test 10193 -ne `wc -c <'Doc/Guide/surfaces.tex'`; then
  251.     echo shar: \"'Doc/Guide/surfaces.tex'\" unpacked with wrong size!
  252. # end of 'Doc/Guide/surfaces.tex'
  253. if test -f 'libray/libcommon/transform.c' -a "${1}" != "-c" ; then 
  254.   echo shar: Will not clobber existing file \"'libray/libcommon/transform.c'\"
  255. echo shar: Extracting \"'libray/libcommon/transform.c'\" \(10691 characters\)
  256. sed "s/^X//" >'libray/libcommon/transform.c' <<'END_OF_FILE'
  257. X * transform.c
  258. X * Copyright (C) 1989, 1991, Craig E. Kolb
  259. X * All rights reserved.
  260. X * This software may be freely copied, modified, and redistributed
  261. X * provided that this copyright notice is preserved on all copies.
  262. X * You may not distribute this software, in whole or in part, as part of
  263. X * any commercial product without the express consent of the authors.
  264. X * There is no warranty or other guarantee of fitness of this software
  265. X * for any purpose.  It is provided solely "as is".
  266. X * $Id: transform.c,v 4.0 91/07/17 14:32:25 kolb Exp Locker: kolb $
  267. X * $Log:    transform.c,v $
  268. X * Revision 4.0  91/07/17  14:32:25  kolb
  269. X * Initial version.
  270. X#include "common.h"
  271. X * Matrices are indexed row-first; that is:
  272. X * matrix[ROW][COLUMN]
  273. X * Allocate new structure that holds both object-to-world and
  274. X * world-to-object space transformation structures.  It probably
  275. X * should hold pointers to these structures.
  276. XTrans *
  277. XTransCreate(tr, meth)
  278. XTransRef tr;
  279. XTransMethods *meth;
  280. X    Trans *res;
  281. X    res = (Trans *)share_malloc(sizeof(Trans));
  282. X    res->tr = tr;
  283. X    res->methods = meth;
  284. X    res->animated = FALSE;
  285. X    res->assoc = (ExprAssoc *)NULL;
  286. X    res->prev = res->next = (Trans *)NULL;
  287. X    MatrixInit(&res->trans);
  288. X    MatrixInit(&res->itrans);
  289. X    return res;
  290. Xvoid
  291. XTransFree(trans)
  292. XTrans *trans;
  293. X    if (trans->tr)
  294. X        free((voidstar)trans->tr);
  295. X    free((voidstar)trans);
  296. Xvoid
  297. XTransAssoc(trans, ptr, expr)
  298. XTrans *trans;
  299. XFloat *ptr;
  300. XExpr *expr;
  301. X    ExprAssoc *assoc;
  302. X    if (expr->timevary) {
  303. X        /*
  304. X         * Gotta store the sucker.
  305. X         */
  306. X        trans->assoc = AssocCreate(ptr, expr, trans->assoc);
  307. X        trans->animated = TRUE;
  308. X    } else {
  309. X        *ptr = expr->value;
  310. X    fflush(stderr);
  311. X * Allocate new transformation 'matrix'.
  312. XRSMatrix *
  313. XMatrixCreate()
  314. X    RSMatrix *res;
  315. X    res = (RSMatrix *)share_malloc(sizeof(RSMatrix));
  316. X    MatrixInit(res);
  317. X    return res;
  318. X * Multiply m1 and m2, copy result into "res".
  319. Xvoid
  320. XMatrixMult(t1, t2, res)
  321. XRSMatrix *t1, *t2, *res;
  322. X    register int i;
  323. X    RSMatrix tmp;
  324. X    for (i = 0; i < 3; i++) {
  325. X        tmp.matrix[i][0] = t1->matrix[i][0] * t2->matrix[0][0] +
  326. X                     t1->matrix[i][1] * t2->matrix[1][0] +
  327. X                     t1->matrix[i][2] * t2->matrix[2][0];
  328. X        tmp.matrix[i][1] = t1->matrix[i][0] * t2->matrix[0][1] +
  329. X                     t1->matrix[i][1] * t2->matrix[1][1] +
  330. X                     t1->matrix[i][2] * t2->matrix[2][1];
  331. X        tmp.matrix[i][2] = t1->matrix[i][0] * t2->matrix[0][2] +
  332. X                     t1->matrix[i][1] * t2->matrix[1][2] +
  333. X                     t1->matrix[i][2] * t2->matrix[2][2];
  334. X    tmp.translate.x = t1->translate.x * t2->matrix[0][0] +
  335. X              t1->translate.y * t2->matrix[1][0] +
  336. X              t1->translate.z * t2->matrix[2][0] + t2->translate.x;
  337. X    tmp.translate.y = t1->translate.x * t2->matrix[0][1] +
  338. X              t1->translate.y * t2->matrix[1][1] +
  339. X              t1->translate.z * t2->matrix[2][1] + t2->translate.y;
  340. X    tmp.translate.z = t1->translate.x * t2->matrix[0][2] +
  341. X              t1->translate.y * t2->matrix[1][2] +
  342. X              t1->translate.z * t2->matrix[2][2] + t2->translate.z;
  343. X    MatrixCopy(&tmp, res);
  344. X * Return transformation information to map the "coordinate system"
  345. X * with the given origin, "up" vector, radius, and up axis lengths to
  346. X * one in which the "up" vector is the Z axis and the x/y/up axes
  347. X * have unit length.  This is useful for transforming a general
  348. X * form of a primitive into a canonical, Z-axis aligned, unit size
  349. X * primitive, facilitating intersection testing.
  350. Xvoid
  351. XCoordSysTransform(origin, up, r, len, trans)
  352. XVector *origin, *up;
  353. XFloat r, len;
  354. XTrans *trans;
  355. X    RSMatrix tmp;
  356. X    Vector atmp;
  357. X    ScaleMatrix(r, r, len, &trans->trans);
  358. X    if (fabs(up->z) == 1.) {
  359. X        atmp.x = 1.;
  360. X        atmp.y = atmp.z = 0.;
  361. X    } else {
  362. X        atmp.x = up->y;
  363. X        atmp.y = -up->x;
  364. X        atmp.z= 0.;
  365. X     * Might want to make sure that |up->z| is < 1.
  366. X     */
  367. X    RotationMatrix(atmp.x, atmp.y, atmp.z, -acos(up->z), &tmp);
  368. X    MatrixMult(&trans->trans, &tmp, &trans->trans);
  369. X    TranslationMatrix(origin->x, origin->y, origin->z, &tmp);
  370. X    MatrixMult(&trans->trans, &tmp, &trans->trans);
  371. X    MatrixInvert(&trans->trans, &trans->itrans);
  372. Xvoid
  373. XTransCopy(from, into)
  374. XTrans *into, *from;
  375. X    MatrixCopy(&from->trans, &into->trans);
  376. X    MatrixCopy(&from->itrans, &into->itrans);
  377. Xvoid
  378. XTransInvert(from, into)
  379. XTrans *into, *from;
  380. X    RSMatrix ttmp;
  381. X     * In case into == from...
  382. X     */
  383. X    if (from == into) {
  384. X        ttmp = from->trans;
  385. X        into->trans = from->itrans;
  386. X        into->itrans = ttmp;
  387. X    } else {
  388. X        into->trans = from->itrans;
  389. X        into->itrans = from->trans;
  390. X * Copy a given transformation structure.
  391. Xvoid
  392. XMatrixCopy(from, into)
  393. XRSMatrix *into, *from;
  394. X    into->matrix[0][0] = from->matrix[0][0];
  395. X    into->matrix[0][1] = from->matrix[0][1];
  396. X    into->matrix[0][2] = from->matrix[0][2];
  397. X    into->matrix[1][0] = from->matrix[1][0];
  398. X    into->matrix[1][1] = from->matrix[1][1];
  399. X    into->matrix[1][2] = from->matrix[1][2];
  400. X    into->matrix[2][0] = from->matrix[2][0];
  401. X    into->matrix[2][1] = from->matrix[2][1];
  402. X    into->matrix[2][2] = from->matrix[2][2];
  403. X    into->translate = from->translate;
  404. Xvoid
  405. XTransInit(trans)
  406. XTrans *trans;
  407. X    MatrixInit(&trans->trans);
  408. X    MatrixInit(&trans->itrans);
  409. Xvoid
  410. XTransCompose(t1, t2, res)
  411. XTrans *t1, *t2, *res;
  412. X    MatrixMult(&t1->trans, &t2->trans, &res->trans);
  413. X    MatrixMult(&t2->itrans, &t1->itrans, &res->itrans);
  414. X * Initialize transformation structure.
  415. Xvoid
  416. XMatrixInit(trans)
  417. XRSMatrix *trans;
  418. X    trans->matrix[0][0] = trans->matrix[1][1] = trans->matrix[2][2] = 1.;
  419. X    trans->matrix[0][1] = trans->matrix[0][2] = trans->matrix[1][0] =
  420. X    trans->matrix[1][2] = trans->matrix[2][0] = trans->matrix[2][1] = 0.;
  421. X    trans->translate.x = trans->translate.y = trans->translate.z = 0.;
  422. X * Calculate inverse of the given transformation structure.
  423. Xvoid
  424. XMatrixInvert(trans, inverse)
  425. XRSMatrix *inverse, *trans;
  426. X    RSMatrix ttmp;
  427. X    int i;
  428. X    Float d;
  429. X    extern int yylineno;
  430. X    ttmp.matrix[0][0] = trans->matrix[1][1]*trans->matrix[2][2] -
  431. X                trans->matrix[1][2]*trans->matrix[2][1];
  432. X    ttmp.matrix[1][0] = trans->matrix[1][0]*trans->matrix[2][2] -
  433. X                trans->matrix[1][2]*trans->matrix[2][0];
  434. X    ttmp.matrix[2][0] = trans->matrix[1][0]*trans->matrix[2][1] -
  435. X                trans->matrix[1][1]*trans->matrix[2][0];
  436. X    ttmp.matrix[0][1] = trans->matrix[0][1]*trans->matrix[2][2] -
  437. X                trans->matrix[0][2]*trans->matrix[2][1];
  438. X    ttmp.matrix[1][1] = trans->matrix[0][0]*trans->matrix[2][2] -
  439. X                trans->matrix[0][2]*trans->matrix[2][0];
  440. X    ttmp.matrix[2][1] = trans->matrix[0][0]*trans->matrix[2][1] -
  441. X                trans->matrix[0][1]*trans->matrix[2][0];
  442. X    ttmp.matrix[0][2] = trans->matrix[0][1]*trans->matrix[1][2] -
  443. X                trans->matrix[0][2]*trans->matrix[1][1];
  444. X    ttmp.matrix[1][2] = trans->matrix[0][0]*trans->matrix[1][2] -
  445. X                trans->matrix[0][2]*trans->matrix[1][0];
  446. X    ttmp.matrix[2][2] = trans->matrix[0][0]*trans->matrix[1][1] -
  447. X                trans->matrix[0][1]*trans->matrix[1][0];
  448. X    d = trans->matrix[0][0]*ttmp.matrix[0][0] -
  449. X        trans->matrix[0][1]*ttmp.matrix[1][0] +
  450. X        trans->matrix[0][2]*ttmp.matrix[2][0];
  451. X    if (fabs(d) < EPSILON*EPSILON)
  452. X        RLerror(RL_PANIC, "Singular matrix.\n",yylineno);
  453. X    ttmp.matrix[0][0] /= d;
  454. X    ttmp.matrix[0][2] /= d;
  455. X    ttmp.matrix[1][1] /= d;
  456. X    ttmp.matrix[2][0] /= d;
  457. X    ttmp.matrix[2][2] /= d;
  458. X    d = -d;
  459. X    ttmp.matrix[0][1] /= d;
  460. X    ttmp.matrix[1][0] /= d;
  461. X    ttmp.matrix[1][2] /= d;
  462. X    ttmp.matrix[2][1] /= d;
  463. X    ttmp.translate.x = -(ttmp.matrix[0][0]*trans->translate.x +
  464. X                 ttmp.matrix[1][0]*trans->translate.y +
  465. X                 ttmp.matrix[2][0]*trans->translate.z);
  466. X    ttmp.translate.y = -(ttmp.matrix[0][1]*trans->translate.x +
  467. X                 ttmp.matrix[1][1]*trans->translate.y +
  468. X                 ttmp.matrix[2][1]*trans->translate.z);
  469. X    ttmp.translate.z = -(ttmp.matrix[0][2]*trans->translate.x +
  470. X                 ttmp.matrix[1][2]*trans->translate.y +
  471. X                 ttmp.matrix[2][2]*trans->translate.z);
  472. X    MatrixCopy(&ttmp, inverse);
  473. X * Apply a transformation to a point (translation affects the point).
  474. Xvoid
  475. XPointTransform(vec, trans)
  476. XVector *vec;
  477. XRSMatrix *trans;
  478. X    Vector tmp;
  479. X    tmp.x = vec->x * trans->matrix[0][0] + vec->y * trans->matrix[1][0] +
  480. X            vec->z * trans->matrix[2][0] + trans->translate.x;
  481. X    tmp.y = vec->x * trans->matrix[0][1] + vec->y * trans->matrix[1][1] +
  482. X            vec->z * trans->matrix[2][1] + trans->translate.y;
  483. X    tmp.z = vec->x * trans->matrix[0][2] + vec->y * trans->matrix[1][2] +
  484. X            vec->z * trans->matrix[2][2] + trans->translate.z;
  485. X    *vec = tmp;
  486. X * 'c1x' is the X (0th) component of the first column, and so on.
  487. Xvoid
  488. XArbitraryMatrix(c1x, c2x, c3x, c1y, c2y, c3y, c1z, c2z, c3z, tx, ty, tz, trans)
  489. XFloat c1x, c1y, c1z, c2x, c2y, c2z, c3x, c3y, c3z, tx, ty, tz;
  490. XRSMatrix *trans;
  491. X    trans->matrix[0][0] = c1x;
  492. X    trans->matrix[1][0] = c1y;
  493. X    trans->matrix[2][0] = c1z;
  494. X    trans->matrix[0][1] = c2x;
  495. X    trans->matrix[1][1] = c2y;
  496. X    trans->matrix[2][1] = c2z;
  497. X    trans->matrix[0][2] = c3x;
  498. X    trans->matrix[1][2] = c3y;
  499. X    trans->matrix[2][2] = c3z;
  500. X    trans->translate.x = tx;
  501. X    trans->translate.y = ty;
  502. X    trans->translate.z = tz;
  503. X * Apply transformation to a vector (translations have no effect).
  504. Xvoid
  505. XVecTransform(vec, trans)
  506. XVector *vec;
  507. XRSMatrix *trans;
  508. X    Vector tmp;
  509. X    tmp.x = vec->x*trans->matrix[0][0] +
  510. X        vec->y*trans->matrix[1][0] + vec->z*trans->matrix[2][0];
  511. X    tmp.y = vec->x*trans->matrix[0][1] +
  512. X        vec->y*trans->matrix[1][1] + vec->z*trans->matrix[2][1];
  513. X    tmp.z = vec->x*trans->matrix[0][2] +
  514. X        vec->y*trans->matrix[1][2] + vec->z*trans->matrix[2][2];
  515. X    *vec = tmp;
  516. X * Transform normal -- multiply by the transpose of the given
  517. X * matrix (which is the inverse of the 'desired' transformation).
  518. Xvoid
  519. XNormalTransform(norm, it)
  520. XVector *norm;
  521. XRSMatrix *it;
  522. X    Vector onorm;
  523. X    onorm = *norm;
  524. X    norm->x = onorm.x*it->matrix[0][0] + onorm.y*it->matrix[0][1] +
  525. X                onorm.z*it->matrix[0][2];
  526. X    norm->y = onorm.x*it->matrix[1][0] + onorm.y*it->matrix[1][1] +
  527. X                onorm.z*it->matrix[1][2];
  528. X    norm->z = onorm.x*it->matrix[2][0] + onorm.y*it->matrix[2][1] +
  529. X                onorm.z*it->matrix[2][2];
  530. X    (void)VecNormalize(norm);
  531. X * Transform "ray" by transforming the origin point and direction vector.
  532. XFloat
  533. XRayTransform(ray, trans)
  534. XRay *ray;
  535. XRSMatrix *trans;
  536. X    PointTransform(&ray->pos, trans);
  537. X    VecTransform(&ray->dir, trans);
  538. X    return VecNormalize(&ray->dir);
  539. Xvoid
  540. XTransPropagate(trans)
  541. XTrans *trans;
  542. X    (*trans->methods->propagate)(trans->tr, &trans->trans, &trans->itrans);
  543. Xvoid
  544. XTransResolveAssoc(trans)
  545. XTrans *trans;
  546. X    Trans *curtrans;
  547. X    ExprAssoc *curassoc;
  548. X    for (curtrans = trans; curtrans; curtrans = curtrans->next) {
  549. X        for (curassoc = curtrans->assoc; curassoc; curassoc = curassoc->next) {
  550. X            *curassoc->lhs = ExprEval(curassoc->expr);
  551. X        if (curtrans->assoc)
  552. X            TransPropagate(curtrans);
  553. Xvoid
  554. XTransComposeList(list, result)
  555. XTrans *list, *result;
  556. X    TransCopy(list, result);
  557. X    for (list = list->next; list; list = list->next)
  558. X        TransCompose(list, result, result);
  559. END_OF_FILE
  560. if test 10691 -ne `wc -c <'libray/libcommon/transform.c'`; then
  561.     echo shar: \"'libray/libcommon/transform.c'\" unpacked with wrong size!
  562. # end of 'libray/libcommon/transform.c'
  563. if test -f 'libray/libobj/csg.c' -a "${1}" != "-c" ; then 
  564.   echo shar: Will not clobber existing file \"'libray/libobj/csg.c'\"
  565. echo shar: Extracting \"'libray/libobj/csg.c'\" \(10585 characters\)
  566. sed "s/^X//" >'libray/libobj/csg.c' <<'END_OF_FILE'
  567. X * csg.c
  568. X * Copyright (C) 1991, Rod G. Bogart, Craig E. Kolb
  569. X * All rights reserved.
  570. X * This software may be freely copied, modified, and redistributed
  571. X * provided that this copyright notice is preserved on all copies.
  572. X * You may not distribute this software, in whole or in part, as part of
  573. X * any commercial product without the express consent of the authors.
  574. X * There is no warranty or other guarantee of fitness of this software
  575. X * for any purpose.  It is provided solely "as is".
  576. X * $Id: csg.c,v 4.0 91/07/17 14:37:00 kolb Exp Locker: kolb $
  577. X * $Log:    csg.c,v $
  578. X * Revision 4.0  91/07/17  14:37:00  kolb
  579. X * Initial version.
  580. X#include "geom.h"
  581. X#include "csg.h"
  582. X#define csg_set_enter(l, f) ((l)->data[0].enter = (f) + 1)
  583. Xstatic Methods *iCsgMethods = NULL;
  584. Xstatic char csgName[] = "csg";
  585. Xstatic int    CsgUnionInt(), CsgDifferenceInt(),
  586. X        CsgIntersectInt();
  587. Xstatic void    CsgHitlistCopy(), CsgSetBounds();
  588. XCsg *
  589. XCsgCreate(op)
  590. Xint op;
  591. X    Csg *csg;
  592. X    csg = (Csg *)share_malloc(sizeof(Csg));
  593. X    csg->operator = op;
  594. X    csg->obj1 = csg->obj2 = (Geom *)NULL;
  595. X    switch(op) {
  596. X        case CSG_UNION:
  597. X            csg->intmeth = CsgUnionInt;
  598. X            break;
  599. X        case CSG_INTERSECT:
  600. X            csg->intmeth = CsgIntersectInt;
  601. X            break;
  602. X        case CSG_DIFFERENCE:
  603. X            csg->intmeth = CsgDifferenceInt;
  604. X            break;
  605. X        default:
  606. X            RLerror(RL_ABORT, "Unknown csg op type %d?\n",op);
  607. X    return csg;
  608. XMethods *
  609. XCsgMethods()
  610. X    if (iCsgMethods== (Methods *)NULL) {
  611. X        iCsgMethods = MethodsCreate();
  612. X        iCsgMethods->create = (GeomCreateFunc *)CsgCreate;
  613. X        iCsgMethods->convert = CsgConvert;
  614. X        iCsgMethods->methods = CsgMethods;
  615. X        iCsgMethods->name = CsgName;
  616. X        iCsgMethods->intersect = CsgIntersect;
  617. X        iCsgMethods->bounds = CsgBounds;
  618. X        iCsgMethods->checkbounds = FALSE;
  619. X        iCsgMethods->closed = TRUE;
  620. X    return iCsgMethods;
  621. Xchar *
  622. XCsgName()
  623. X    return csgName;
  624. Xcsg_intersect_objs(csg, ray, hit1, hit2, mindist, dist1, dist2)
  625. XCsg *csg;
  626. XRay *ray;
  627. XHitList *hit1, *hit2;
  628. XFloat mindist, *dist1, *dist2;
  629. X    int operator;
  630. X    hit1->nodes = 0;
  631. X    hit2->nodes = 0;
  632. X    *dist1 = FAR_AWAY;
  633. X    *dist2 = FAR_AWAY;
  634. X    operator = csg->operator;
  635. X    if (!intersect(csg->obj1, ray, hit1, mindist, dist1) &&
  636. X        ((operator == CSG_INTERSECT) || (operator == CSG_DIFFERENCE))) {
  637. X        /*
  638. X         * Intersection and Difference cases: if you miss the first
  639. X         * object, you missed the whole thing.
  640. X         */
  641. X        return FALSE;
  642. X    if (!intersect(csg->obj2, ray, hit2, mindist, dist2) &&
  643. X        ((operator == CSG_INTERSECT) ||
  644. X         (hit1->nodes == 0) && (operator == CSG_UNION))) {
  645. X        /*
  646. X         * Intersect case:  if you miss either object, you miss whole
  647. X         * Union case: if you miss both object, you miss whole
  648. X         */
  649. X        return FALSE;
  650. X    return TRUE;
  651. Xcsg_enter_obj(hitp)
  652. XHitList *hitp;
  653. X    if (hitp->data[0].enter)
  654. X        return hitp->data[0].enter - 1;
  655. X    return PrimEnter(hitp->data[0].obj, &hitp->data[0].ray,
  656. X            hitp->data[0].mindist, hitp->data[0].dist);
  657. Xstatic int
  658. XCsgUnionInt(ray, hit1p, hit2p, dist1, dist2, hitclose, distclose)
  659. XRay *ray;
  660. XHitList *hit1p, *hit2p, **hitclose;
  661. XFloat dist1, dist2, *distclose;
  662. X    Float distnext;
  663. X    HitList hitnext, *hittmp;
  664. X    while (TRUE) {
  665. X        if (hit2p->nodes == 0 ||
  666. X            csg_enter_obj(hit2p)) {
  667. X            /* return hit1 */
  668. X            *hitclose = hit1p;
  669. X            *distclose = dist1;
  670. X            csg_set_enter(hit1p, csg_enter_obj(hit1p));
  671. X            return TRUE;
  672. X        } else {
  673. X            distnext = FAR_AWAY;
  674. X            hitnext.nodes = 0;
  675. X            if (!intersect(hit1p->data[hit1p->nodes-1].obj,
  676. X                ray, &hitnext, dist2+EPSILON, &distnext)) {
  677. X                /*
  678. X                 * None of obj1 beyond, return hit2 (leaving)
  679. X                 */
  680. X                *hitclose = hit2p;
  681. X                *distclose = dist2;
  682. X                csg_set_enter(hit2p, FALSE);
  683. X                return TRUE;
  684. X            } else {
  685. X                /*
  686. X                 * Since hit1 is supposed to be the close one,
  687. X                 * swap them and copy hitnext into hit2.
  688. X                      */
  689. X                hittmp = hit1p;
  690. X                hit1p = hit2p;
  691. X                hit2p = hittmp;
  692. X                dist1 = dist2;
  693. X                CsgHitlistCopy(&hitnext, hit2p);
  694. X                dist2 = distnext;
  695. X                /* and continue */
  696. X            }
  697. Xstatic int
  698. XCsgIntersectInt(ray, hit1p, hit2p, dist1, dist2, hitclose, distclose)
  699. XRay *ray;
  700. XHitList *hit1p, *hit2p, **hitclose;
  701. XFloat dist1, dist2, *distclose;
  702. X    HitList *hittmp, hitnext;
  703. X    Float distnext;
  704. X    while (TRUE) {
  705. X        if (!csg_enter_obj(hit2p)) {
  706. X            /* Ray is leaving obj2 */
  707. X            /* Return hit1 info */
  708. X            *hitclose = hit1p;
  709. X            *distclose = dist1;
  710. X            csg_set_enter(hit1p, csg_enter_obj(hit1p));
  711. X            return TRUE;
  712. X        } else {
  713. X            distnext = FAR_AWAY;
  714. X            hitnext.nodes = 0;
  715. X            if (!intersect(hit1p->data[hit1p->nodes-1].obj,
  716. X                ray, &hitnext, dist2+EPSILON, &distnext)) {
  717. X                /*
  718. X                 * None of obj1 beyond, so return miss
  719. X                 */
  720. X                return FALSE;
  721. X            } else {
  722. X                /*
  723. X                 * Since hit1 is supposed to be the
  724. X                 * close one, swap them and copy
  725. X                 * hitnext into hit2.
  726. X                 */
  727. X                hittmp = hit1p;
  728. X                hit1p = hit2p;
  729. X                hit2p = hittmp;
  730. X                dist1 = dist2;
  731. X                CsgHitlistCopy(&hitnext, hit2p);
  732. X                dist2 = distnext;
  733. X                /* and continue */
  734. X            }
  735. Xstatic int
  736. XCsgDifferenceInt(ray, hit1p, hit2p, dist1, dist2, hitclose, distclose)
  737. XRay *ray;
  738. XHitList *hit1p, *hit2p, **hitclose;
  739. XFloat dist1, dist2, *distclose;
  740. X    Float distnext;
  741. X    HitList hitnext;
  742. X    while (TRUE) {
  743. X        if (dist1 < dist2) {
  744. X            if (hit2p->nodes == 0 ||
  745. X                csg_enter_obj(hit2p)) {
  746. X                /* return hit1 */
  747. X                *hitclose = hit1p;
  748. X                *distclose = dist1;
  749. X                csg_set_enter(hit1p, csg_enter_obj(hit1p));
  750. X                return TRUE;
  751. X            } else {
  752. X                distnext = FAR_AWAY;
  753. X                hitnext.nodes = 0;
  754. X                if (!intersect(hit1p->data[hit1p->nodes-1].obj,
  755. X                    ray, &hitnext, dist2+EPSILON, &distnext)) {
  756. X                    /*
  757. X                     * None of obj1 beyond, so
  758. X                     * return miss
  759. X                     */
  760. X                    return FALSE;
  761. X                } else {
  762. X                    dist1 = distnext;
  763. X                    CsgHitlistCopy(&hitnext, hit1p);
  764. X                    /* and continue */
  765. X                }
  766. X            }
  767. X        } else { /* dist1 <= dist2 */
  768. X            if (hit1p->nodes == 0) {
  769. X                /* return a miss */
  770. X                return FALSE;
  771. X            }
  772. X            if (!csg_enter_obj(hit1p)) {
  773. X                /*
  774. X                 * return hit2, but invert hit2
  775. X                 * Enter/Leave flag
  776. X                 */
  777. X                *hitclose = hit2p;
  778. X                *distclose = dist2;
  779. X                csg_set_enter(hit2p, !csg_enter_obj(hit2p));
  780. X                return TRUE;
  781. X            } else {
  782. X                distnext = FAR_AWAY;
  783. X                hitnext.nodes = 0;
  784. X                if (!intersect(hit2p->data[hit2p->nodes-1].obj,
  785. X                    ray, &hitnext, dist1+EPSILON, &distnext)) {
  786. X                    /*
  787. X                     * None of obj2 beyond, so
  788. X                     * return hit1
  789. X                     */
  790. X                    *hitclose = hit1p;
  791. X                    *distclose = dist1;
  792. X                    /* we know we're entering obj1 */
  793. X                    csg_set_enter(hit1p, TRUE);
  794. X                    return TRUE;
  795. X                } else {
  796. X                    dist2 = distnext;
  797. X                    CsgHitlistCopy(&hitnext, hit2p);
  798. X                    /* and continue */
  799. X                }
  800. X            }
  801. XCsgIntersect(csg, ray, hitlist, mindist, maxdist)
  802. XCsg *csg;
  803. XRay *ray;
  804. XHitList *hitlist;
  805. XFloat mindist, *maxdist;
  806. X    Float dist1, dist2, disttmp, distclose;
  807. X    HitList hit1, hit2, *hit1p, *hit2p, *hitclose;
  808. X    hit1p = &hit1;
  809. X    hit2p = &hit2;
  810. X    if (!csg_intersect_objs(csg, ray, hit1p, hit2p, mindist,
  811. X        &dist1, &dist2)) {
  812. X        /* missed the csg object */
  813. X        return FALSE;
  814. X    if ((dist1 > dist2) &&
  815. X        (csg->operator == CSG_UNION || csg->operator == CSG_INTERSECT)) {
  816. X        /* swap so 1 is closest (except in difference case) */
  817. X        disttmp = dist2;  
  818. X        dist2 = dist1;  
  819. X        dist1 = disttmp;
  820. X        hit1p = &hit2;  
  821. X        hit2p = &hit1;
  822. X     * Call appropriate intersection method.  If FALSE is return,
  823. X     * no hit of any kind was found.
  824. X     */
  825. X    if (!(*csg->intmeth)(ray, hit1p, hit2p, dist1, dist2,
  826. X        &hitclose, &distclose))
  827. X        return FALSE;
  828. X     * At this time, the closest hit is in hitclose and
  829. X     * distclose.
  830. X     */
  831. X    if (distclose < mindist || distclose > *maxdist)
  832. X        return FALSE;
  833. X    CsgHitlistCopy(hitclose, hitlist);
  834. X    *maxdist = distclose;
  835. X    return TRUE;
  836. Xstatic void
  837. XCsgHitlistCopy(from, to)
  838. XHitList *from, *to;
  839. X    int i;
  840. X    to->nodes = from->nodes;
  841. X    for (i = 0; i < from->nodes; i++)
  842. X        to->data[i] = from->data[i];
  843. Xstatic void
  844. XCsgSetBounds(csg, bounds)
  845. XCsg *csg;
  846. XFloat bounds[2][3];
  847. X    GeomComputeBounds(csg->obj1);
  848. X    GeomComputeBounds(csg->obj2);
  849. X    switch (csg->operator) {
  850. X    case CSG_UNION:
  851. X        bounds[LOW][X] = min(csg->obj1->bounds[LOW][X], csg->obj2->bounds[LOW][X]);
  852. X        bounds[HIGH][X] = max(csg->obj1->bounds[HIGH][X], csg->obj2->bounds[HIGH][X]);
  853. X        bounds[LOW][Y] = min(csg->obj1->bounds[LOW][Y], csg->obj2->bounds[LOW][Y]);
  854. X        bounds[HIGH][Y] = max(csg->obj1->bounds[HIGH][Y], csg->obj2->bounds[HIGH][Y]);
  855. X        bounds[LOW][Z] = min(csg->obj1->bounds[LOW][Z], csg->obj2->bounds[LOW][Z]);
  856. X        bounds[HIGH][Z] = max(csg->obj1->bounds[HIGH][Z], csg->obj2->bounds[HIGH][Z]);
  857. X        break;
  858. X    case CSG_INTERSECT:
  859. X        bounds[LOW][X] = max(csg->obj1->bounds[LOW][X], csg->obj2->bounds[LOW][X]);
  860. X        bounds[HIGH][X] = min(csg->obj1->bounds[HIGH][X], csg->obj2->bounds[HIGH][X]);
  861. X        bounds[LOW][Y] = max(csg->obj1->bounds[LOW][Y], csg->obj2->bounds[LOW][Y]);
  862. X        bounds[HIGH][Y] = min(csg->obj1->bounds[HIGH][Y], csg->obj2->bounds[HIGH][Y]);
  863. X        bounds[LOW][Z] = max(csg->obj1->bounds[LOW][Z], csg->obj2->bounds[LOW][Z]);
  864. X        bounds[HIGH][Z] = min(csg->obj1->bounds[HIGH][Z], csg->obj2->bounds[HIGH][Z]);
  865. X        break;
  866. X    case CSG_DIFFERENCE:
  867. X        bounds[LOW][X] = csg->obj1->bounds[LOW][X];
  868. X        bounds[HIGH][X] = csg->obj1->bounds[HIGH][X];
  869. X        bounds[LOW][Y] = csg->obj1->bounds[LOW][Y];
  870. X        bounds[HIGH][Y] = csg->obj1->bounds[HIGH][Y];
  871. X        bounds[LOW][Z] = csg->obj1->bounds[LOW][Z];
  872. X        bounds[HIGH][Z] = csg->obj1->bounds[HIGH][Z];
  873. X        break;
  874. X    default:
  875. X        RLerror(RL_ABORT, "Unknown csg operator type %d?\n",
  876. X            csg->operator);
  877. X * Return index of hitlist node closest to the leaf and not below any
  878. X * CSG object.
  879. XFirstCSGGeom(hitlist)
  880. XHitList *hitlist;
  881. X    int i;
  882. X     * UUUUGLY -- detect if obj is a CsgGeom by comparing
  883. X     * methods with iCsgMethods.
  884. X     */
  885. X    for (i = hitlist->nodes -1; i; i--)
  886. X        if (hitlist->data[i].obj->methods == iCsgMethods)
  887. X            return i;
  888. X    return 0;
  889. Xvoid
  890. XCsgBounds(csg, bounds)
  891. XCsg *csg;
  892. XFloat bounds[2][3];
  893. X    CsgSetBounds(csg, csg->bounds);
  894. X    BoundsCopy(csg->bounds, bounds);
  895. XCsgConvert(csg, list)
  896. XCsg *csg;
  897. XGeom *list;
  898. X    static int OpenAdvised = FALSE;
  899. X     * Currently, this only handles two objects.
  900. X     * Will be fixed in the future.
  901. X     * No really we promise.
  902. X     */
  903. X    if (!list || !list->next) {
  904. X        RLerror(RL_WARN, "CSG needs at least two objects.\n");
  905. X        return 0;
  906. X    if (list->next->next) {
  907. X        RLerror(RL_WARN, "Currently, CSG only handles two objects.\n");
  908. X        return 0;
  909. X     * Things are put into lists backwards....
  910. X     */
  911. X    csg->obj2 = list;
  912. X    csg->obj1 = list->next;
  913. X    if ((!csg->obj1->methods->closed || !csg->obj2->methods->closed) &&
  914. X        !OpenAdvised) {
  915. X        RLerror(RL_ADVISE,
  916. X            "Performing CSG with non-closed object(s).\n");
  917. X        OpenAdvised = TRUE;
  918. X    return csg->obj1->prims + csg->obj2->prims;
  919. Xvoid
  920. XCsgMethodRegister(meth)
  921. XUserMethodType meth;
  922. X    if (iCsgMethods)
  923. X        iCsgMethods->user = meth;
  924. END_OF_FILE
  925. if test 10585 -ne `wc -c <'libray/libobj/csg.c'`; then
  926.     echo shar: \"'libray/libobj/csg.c'\" unpacked with wrong size!
  927. # end of 'libray/libobj/csg.c'
  928. if test -f 'libshade/shade.c' -a "${1}" != "-c" ; then 
  929.   echo shar: Will not clobber existing file \"'libshade/shade.c'\"
  930. echo shar: Extracting \"'libshade/shade.c'\" \(10451 characters\)
  931. sed "s/^X//" >'libshade/shade.c' <<'END_OF_FILE'
  932. X * shade.c
  933. X * Copyright (C) 1989, 1991, Craig E. Kolb
  934. X * All rights reserved.
  935. X * This software may be freely copied, modified, and redistributed
  936. X * provided that this copyright notice is preserved on all copies.
  937. X * You may not distribute this software, in whole or in part, as part of
  938. X * any commercial product without the express consent of the authors.
  939. X * There is no warranty or other guarantee of fitness of this software
  940. X * for any purpose.  It is provided solely "as is".
  941. X * $Id: shade.c,v 4.0 91/07/17 14:47:36 kolb Exp Locker: kolb $
  942. X * $Log:    shade.c,v $
  943. X * Revision 4.0  91/07/17  14:47:36  kolb
  944. X * Initial version.
  945. X#include "rayshade.h"
  946. X#include "libtext/texture.h"
  947. X#include "libsurf/surface.h"
  948. X#include "liblight/light.h"
  949. X#include "libsurf/atmosphere.h"
  950. X#include "options.h"
  951. X#include "stats.h"
  952. XMedium    TopMedium;
  953. XAtmosphere *AtmosEffects;
  954. Xstatic void shade(), LightRay(), Lighting(), ReflectRay();
  955. Xstatic int TransmitRay();
  956. X * Calculate color of ray.
  957. Xvoid
  958. XShadeRay(hitlist, ray, dist, back, color, contrib)
  959. XHitList *hitlist;        /* Information about point of intersection. */
  960. XRay *ray;            /* Direction and origin of ray. */
  961. XFloat dist;            /* Distance from origin of intersection. */
  962. XColor    *back,            /* "Background" color */
  963. X    *color,            /* Color to assign current ray. */
  964. X    *contrib;        /* Contribution of this ray to final color */
  965. X    Vector norm, gnorm, pos; /* surface normal, point of intersection */
  966. X    Surface surf, *stmp;    /* surface properties */
  967. X    int enter, smooth;    /* entering ?, gnorm != snorm ?*/
  968. X    if (hitlist->nodes == 0) {
  969. X        /*
  970. X         * No valid intersection.  Set distance for atmospheric
  971. X         * effects and set color of ray to background.
  972. X         */
  973. X        *color = *back;
  974. X        VecAddScaled(ray->pos, FAR_AWAY, ray->dir, &pos);
  975. X        if (!ray->media && AtmosEffects)
  976. X            Atmospherics(AtmosEffects, ray, FAR_AWAY, &pos, color);
  977. X        return;
  978. X     * Compute normal, surface properties, etc.
  979. X     */
  980. X    stmp = GetShadingSurf(hitlist);
  981. X    surf = *stmp;
  982. X    enter = ComputeSurfProps(hitlist, ray, &pos, &norm, &gnorm, &surf,
  983. X            &smooth);
  984. X    Stats.HitRays++;
  985. X     * Calculate ray color.
  986. X     */
  987. X    shade(&pos, ray, &norm, &gnorm, smooth, enter, &surf, back, color,
  988. X            contrib);
  989. X    if (!ray->media && AtmosEffects)
  990. X        Atmospherics(AtmosEffects, ray, dist, &pos, color);
  991. X * Perform lighting calculations based on surface normal & other properties,
  992. X * incident ray direction and position, and light source properties.
  993. X * Spawn any necessary reflected and transmitted rays.
  994. Xstatic void
  995. Xshade(pos, ray, nrm, gnrm, smooth, enter, surf, back, color, contrib)
  996. XVector *pos, *nrm, *gnrm;    /* hit pos, shade normal, geo normal */
  997. Xint smooth;            /* true if shading norm and geo norm differ */
  998. Xint enter;            /* TRUE if entering surface */
  999. XRay *ray;            /* indicent ray */
  1000. XSurface *surf;            /* properties of hit surface */
  1001. XColor *back, *color;        /* background color, computed color */
  1002. XColor *contrib;            /* contribution to final pixel value */
  1003. X    Float    k;        /* -ray . normal */
  1004. X    Color    newcontrib;
  1005. X    Vector    refl;        /* reflected direction */
  1006. X    Color    reflectivity,    /* effective surface reflectivity */
  1007. X        intens;        /* reflected/transmitted intensity */
  1008. X    Light *lp;        /* current light source */
  1009. X    extern Light *Lights;    /* list of defined sources */
  1010. X     * Ambient color is always included.
  1011. X     */
  1012. X    ColorMultiply(surf->amb, Options.ambient, color);
  1013. X     * Calculate direction of reflected ray.
  1014. X     */
  1015. X    k = -dotp(&ray->dir, nrm);
  1016. X    VecAddScaled(ray->dir, 2.*k, *nrm, &refl);
  1017. X     * Calculate intensity contributed by each light source.
  1018. X     */
  1019. X    for (lp = Lights; lp; lp = lp->next)
  1020. X        LightRay(lp, pos, nrm, gnrm, smooth, &refl, surf,
  1021. X                ray->depth, ray->sample, ray->time, color);
  1022. X    if (ray->depth >= Options.maxdepth)
  1023. X        /*
  1024. X         * Don't spawn any transmitted/reflected rays.
  1025. X         */
  1026. X        return;
  1027. X     * Specular transmission (refraction).
  1028. X     */
  1029. X    ColorScale(surf->reflect, surf->spec, &reflectivity);
  1030. X    if (surf->transp > EPSILON) {
  1031. X        ColorScale(surf->transp, surf->body, &intens);
  1032. X        ColorMultiply(intens, *contrib, &newcontrib);
  1033. X        if (newcontrib.r > Options.cutoff.r ||
  1034. X            newcontrib.g > Options.cutoff.g ||
  1035. X            newcontrib.b > Options.cutoff.b)
  1036. X            /*
  1037. X             * Transmit ray.  If TIR occurs, add transmitted
  1038. X             * component to reflected component.  Kinda strange, but...
  1039. X             */
  1040. X            if (TransmitRay(ray, pos, nrm, k, surf->index,
  1041. X                surf->statten, enter, back, &newcontrib, &intens, color))
  1042. X                ColorAdd(reflectivity, intens, &reflectivity);
  1043. X    if (reflectivity.r > EPSILON ||
  1044. X        reflectivity.g > EPSILON ||
  1045. X        reflectivity.b > EPSILON) {
  1046. X        ColorMultiply(reflectivity, *contrib, &newcontrib);
  1047. X        if (newcontrib.r > Options.cutoff.r ||
  1048. X            newcontrib.g > Options.cutoff.g ||
  1049. X            newcontrib.b > Options.cutoff.b)
  1050. X            ReflectRay(ray, pos, &refl, back, &reflectivity,
  1051. X                &newcontrib, color);
  1052. X * Lighting calculations
  1053. Xstatic void
  1054. XLightRay(lp, pos, norm, gnorm, smooth, reflect, surf, depth, samp, time, color)
  1055. XLight *lp;            /* Light source */
  1056. XVector *pos, *norm, *gnorm;    /* hit pos, shade norm, geo norm */
  1057. Xint smooth;            /* true if shade and geo norm differ */
  1058. XVector *reflect;        /* reflection direction */
  1059. XSurface *surf;            /* surface characteristics */
  1060. Xint depth, samp;        /* ray depth, sample # */
  1061. XFloat time;
  1062. XColor *color;            /* resulting color */
  1063. X    Color lcolor;
  1064. X    Ray newray;
  1065. X    Float costheta, cosalpha, dist;
  1066. X    newray.pos = *pos;
  1067. X    newray.depth = depth;
  1068. X    newray.sample = samp;
  1069. X    newray.time = time; 
  1070. X    newray.media = (Medium *)NULL;    
  1071. X    LightDirection(lp, pos, &newray.dir, &dist);
  1072. X    costheta = dotp(&newray.dir, norm);
  1073. X    if (smooth) {
  1074. X        cosalpha = dotp(&newray.dir, gnorm); 
  1075. X        /*
  1076. X         * If shading normal indicates self-shadowing
  1077. X         * and geom normal indicates no self-shadowing,
  1078. X         * trust the geom normal.
  1079. X         */
  1080. X        if (costheta <= 0. && cosalpha > 0.)
  1081. X            costheta = cosalpha;
  1082. X        /*
  1083. X         * If geom normal indicates self-shadowing and
  1084. X         * geom normal doesn't, then have to do something
  1085. X         * clever ala Snyder & Barr.
  1086. X         */
  1087. X    if (costheta <= 0.) {
  1088. X        /*
  1089. X         * Light source is on opposite side of surface,
  1090. X         * hence light must be transmitted through...
  1091. X         */
  1092. X        if (surf->translucency < EPSILON)
  1093. X            return;
  1094. X        if (!LightIntens(lp, &newray, dist,
  1095. X            (int)surf->noshadow, &lcolor))
  1096. X            return;
  1097. X        cosalpha = -dotp(reflect, &newray.dir);
  1098. X        Lighting(-costheta, cosalpha, &lcolor, &surf->translu,
  1099. X                &surf->body, surf->stexp, color);
  1100. X        ColorScale(surf->translucency, *color, color);
  1101. X    } else {
  1102. X        if (!LightIntens(lp, &newray, dist,
  1103. X            (int)surf->noshadow, &lcolor))
  1104. X            return;  /* prim is in shadow w.r.t light source */
  1105. X        cosalpha = dotp(reflect, &newray.dir);
  1106. X        Lighting(costheta, cosalpha, &lcolor, &surf->diff,
  1107. X                &surf->spec, surf->srexp, color);
  1108. X * Compute shading function (diffuse reflection and specular highlight)
  1109. X * This function *adds* the computed color to "color".
  1110. Xstatic void
  1111. XLighting(costheta, cosalpha, lcolor, diff, spec, coef, color)
  1112. XFloat costheta, cosalpha, coef;
  1113. XColor *diff, *spec, *color, *lcolor;
  1114. X    Float intens;
  1115. X     * Diffuse reflection.
  1116. X     * Falls off as the cosine of the angle between
  1117. X     * the normal and the ray to the light (costheta).
  1118. X     */
  1119. X    color->r += diff->r * costheta * lcolor->r;
  1120. X    color->g += diff->g * costheta * lcolor->g;
  1121. X    color->b += diff->b * costheta * lcolor->b;
  1122. X     * Specularly reflected highlights.
  1123. X     * Fall off as the cosine of the angle
  1124. X     * between the reflected ray and the ray to the light source.
  1125. X     */
  1126. X    if (coef < EPSILON || cosalpha <= 0.)
  1127. X        return;
  1128. X     * Specular highlight = cosine of the angle raised to the
  1129. X     * appropriate power.
  1130. X     */
  1131. X    intens = pow(cosalpha, coef);
  1132. X    color->r += spec->r * intens * lcolor->r;
  1133. X    color->g += spec->g * intens * lcolor->g;
  1134. X    color->b += spec->b * intens * lcolor->b;
  1135. X * Spawn a transmitted ray.  Returns TRUE if total internal reflection
  1136. X * occurs, FALSE otherwise.
  1137. Xstatic int
  1138. XTransmitRay(ray, pos, norm, k, index, statten, enter, back, contrib, intens, color)
  1139. XRay *ray;
  1140. XVector *pos, *norm;
  1141. XFloat k, index, statten;
  1142. Xint enter;
  1143. XColor *back, *contrib, *intens, *color;
  1144. X    int total_int_refl = FALSE;
  1145. X    Ray NewRay;
  1146. X    Float dist;
  1147. X    Color newcol;
  1148. X    HitList hittmp;        /* Geom intersection record */
  1149. X    NewRay.pos = *pos;        /* Origin == hit point */
  1150. X    NewRay.media = ray->media;    /* Media == old media */
  1151. X    NewRay.sample = ray->sample;
  1152. X    NewRay.time = ray->time;
  1153. X    NewRay.depth = ray->depth + 1;
  1154. X    if (enter) {
  1155. X        /*
  1156. X         * Entering surface.
  1157. X         */
  1158. X        if (Refract(&NewRay.dir,
  1159. X            NewRay.media ? NewRay.media->index :
  1160. X            TopMedium.index, index, &ray->dir, norm, k)) {
  1161. X            total_int_refl = TRUE;
  1162. X        } else {
  1163. X            /*
  1164. X             * Push information for new medium.
  1165. X             */
  1166. X            NewRay.media = MediumPush(index, statten, NewRay.media);
  1167. X    } else {
  1168. X        /*
  1169. X         * Exiting surface
  1170. X         * Pop medium from stack.
  1171. X         */
  1172. X        if (NewRay.media != (Medium *)0)
  1173. X            NewRay.media = NewRay.media->next;
  1174. X        if (Refract(&NewRay.dir, index,
  1175. X            NewRay.media ? NewRay.media->index :
  1176. X            TopMedium.index, &ray->dir, norm, k)) {
  1177. X            total_int_refl = TRUE;
  1178. X     * At this point, NewRay.media is the medium into which
  1179. X     * the new ray is entering.
  1180. X     */
  1181. X    if (!total_int_refl) {
  1182. X        Stats.RefractRays++;
  1183. X        hittmp.nodes = 0;
  1184. X        dist = FAR_AWAY;
  1185. X        TraceRay(&NewRay, &hittmp, EPSILON, &dist);
  1186. X        ShadeRay(&hittmp, &NewRay, dist, back, &newcol, contrib);
  1187. X        ColorMultiply(newcol, *intens, &newcol);
  1188. X        /*
  1189. X         * Attenuate transmitted color.  Note that
  1190. X         * if the transmitted ray hit nothing, we still
  1191. X         * perform this computation, as it's possible
  1192. X         * that 'air' has a non-unit statten.
  1193. X         */
  1194. X        statten = NewRay.media ? NewRay.media->statten :
  1195. X            TopMedium.statten;
  1196. X        if (statten != 1.0) {
  1197. X            statten = pow(statten, dist);
  1198. X            ColorScale(statten, newcol, &newcol);
  1199. X        ColorAdd(*color, newcol, color);
  1200. X        /* Free pushed medium */
  1201. X        if (enter)
  1202. X            free((voidstar)NewRay.media);
  1203. X    return total_int_refl;
  1204. Xstatic void
  1205. XReflectRay(ray, pos, dir, back, intens, contrib, color)
  1206. XRay *ray;
  1207. XVector *pos, *dir;
  1208. XColor *back, *intens, *contrib, *color;
  1209. X    Ray NewRay;
  1210. X    HitList hittmp;        /* Geom intersection record */
  1211. X    Color newcol;
  1212. X    Float dist;
  1213. X    NewRay.pos = *pos;        /* Origin == hit point */
  1214. X    NewRay.dir = *dir;        /* Direction == reflection */
  1215. X    NewRay.media = ray->media;    /* Medium == old medium */
  1216. X    NewRay.sample = ray->sample;
  1217. X    NewRay.time = ray->time;
  1218. X    NewRay.depth = ray->depth + 1;
  1219. X    Stats.ReflectRays++;
  1220. X    hittmp.nodes = 0;
  1221. X    dist = FAR_AWAY;
  1222. X    (void)TraceRay(&NewRay, &hittmp, EPSILON, &dist);
  1223. X    ShadeRay(&hittmp, &NewRay, dist, back, &newcol, contrib);
  1224. X    ColorMultiply(newcol, *intens, &newcol);
  1225. X    ColorAdd(*color, newcol, color);
  1226. END_OF_FILE
  1227. if test 10451 -ne `wc -c <'libshade/shade.c'`; then
  1228.     echo shar: \"'libshade/shade.c'\" unpacked with wrong size!
  1229. # end of 'libshade/shade.c'
  1230. echo shar: End of archive 13 \(of 19\).
  1231. cp /dev/null ark13isdone
  1232. MISSING=""
  1233. for I in 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 ; do
  1234.     if test ! -f ark${I}isdone ; then
  1235.     MISSING="${MISSING} ${I}"
  1236.     fi
  1237. if test "${MISSING}" = "" ; then
  1238.     echo You have unpacked all 19 archives.
  1239.     rm -f ark[1-9]isdone ark[1-9][0-9]isdone
  1240.     echo You still need to unpack the following archives:
  1241.     echo "        " ${MISSING}
  1242. ##  End of shell archive.
  1243. exit 0
  1244. exit 0 # Just in case...
  1245.