RADIOSIT.C 32 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039
  1. /****************************************************************************
  2. * radiosit.c
  3. *
  4. * This module contains all radiosity calculation functions.
  5. *
  6. * This file was written by Jim McElhiney.
  7. *
  8. * from Persistence of Vision(tm) Ray Tracer
  9. * Copyright 1996,1999 Persistence of Vision Team
  10. *---------------------------------------------------------------------------
  11. * NOTICE: This source code file is provided so that users may experiment
  12. * with enhancements to POV-Ray and to port the software to platforms other
  13. * than those supported by the POV-Ray Team. There are strict rules under
  14. * which you are permitted to use this file. The rules are in the file
  15. * named POVLEGAL.DOC which should be distributed with this file.
  16. * If POVLEGAL.DOC is not available or for more info please contact the POV-Ray
  17. * Team Coordinator by email to team-coord@povray.org or visit us on the web at
  18. * http://www.povray.org. The latest version of POV-Ray may be found at this site.
  19. *
  20. * This program is based on the popular DKB raytracer version 2.12.
  21. * DKBTrace was originally written by David K. Buck.
  22. * DKBTrace Ver 2.0-2.12 were written by David K. Buck & Aaron A. Collins.
  23. *
  24. *****************************************************************************/
  25. /************************************************************************
  26. * Radiosity calculation routies.
  27. *
  28. * (This does not work the way that most radiosity programs do, but it accomplishes
  29. * the diffuse interreflection integral the hard way and produces similar results. It
  30. * is called radiosity here to avoid confusion with ambient and diffuse, which
  31. * already have well established meanings within POV).
  32. * Inspired by the paper "A Ray Tracing Solution for Diffuse Interreflection"
  33. * by Ward, Rubinstein, and Clear, in Siggraph '88 proceedings.
  34. *
  35. * Basic Idea: Never use a constant ambient term. Instead,
  36. * - For first pixel, cast a whole bunch of rays in different directions
  37. * from the object intersection point to see what the diffuse illumination
  38. * really is. Save this value, after estimating its
  39. * degree of reusability. (Method 1)
  40. * - For second and subsequent pixels,
  41. * - If there are one or more nearby values already computed,
  42. * average them and use the result (Method 2), else
  43. * - Use method 1.
  44. *
  45. * Implemented by and (c) 1994-6 Jim McElhiney, mcelhiney@acm.org or 71201,1326
  46. * All standard POV distribution rights granted. All other rights reserved.
  47. *************************************************************************/
  48. #include "string.h"
  49. #include "frame.h"
  50. #include "lighting.h"
  51. #include "vector.h"
  52. #include "povray.h"
  53. #include "optin.h"
  54. #include "povproto.h"
  55. #include "render.h"
  56. #include "texture.h"
  57. #include "octree.h"
  58. #include "radiosit.h"
  59. #include "ray.h"
  60. /*****************************************************************************
  61. * Local preprocessor defines
  62. ******************************************************************************/
  63. #define RAD_GRADIENT 1
  64. #define SAW_METHOD 1
  65. /* #define SIGMOID_METHOD 1 */
  66. /* #define SHOW_SAMPLE_SPOTS 1 */ /* try this! bright spots at sample pts */
  67. /*****************************************************************************
  68. * Local typedefs
  69. ******************************************************************************/
  70. /*****************************************************************************
  71. * Local variables
  72. ******************************************************************************/
  73. long ra_reuse_count = 0;
  74. long ra_gather_count = 0;
  75. int Radiosity_Trace_Level = 1;
  76. COLOUR Radiosity_Gather_Total;
  77. long Radiosity_Gather_Total_Count;
  78. COLOUR Radiosity_Setting_Total;
  79. long Radiosity_Setting_Total_Count;
  80. #ifdef RADSTATS
  81. extern long ot_blockcount;
  82. long ot_seenodecount = 0;
  83. long ot_seeblockcount = 0;
  84. long ot_doblockcount = 0;
  85. long ot_dotokcount = 0;
  86. long ot_lastcount = 0;
  87. long ot_lowerrorcount = 0;
  88. #endif
  89. OT_NODE *ot_root = NULL;
  90. /* This (and all other changing globals) should really be in an execution
  91. * context structure passed down the execution call tree as a parameter to
  92. * each function. This would allow for a multiprocessor/multithreaded version.
  93. */
  94. FILE *ot_fd = NULL;
  95. /*****************************************************************************
  96. * Static functions
  97. ******************************************************************************/
  98. static long ra_reuse (VECTOR IPoint, VECTOR Normal, COLOUR Illuminance);
  99. static long ra_average_near (OT_BLOCK *block, void *void_info);
  100. static void ra_gather (VECTOR IPoint, VECTOR Normal, COLOUR Illuminance, DBL Weight);
  101. static void VUnpack (VECTOR dest_vec, BYTE_XYZ *pack);
  102. /*****************************************************************************
  103. *
  104. * FUNCTION
  105. *
  106. * Compute_Ambient
  107. *
  108. * INPUT
  109. *
  110. * OUTPUT
  111. *
  112. * RETURNS
  113. *
  114. * AUTHOUR
  115. *
  116. * Jim McElhiney
  117. *
  118. * DESCRIPTION
  119. *
  120. * Main entry point for calculated diffuse illumination
  121. *
  122. * CHANGES
  123. *
  124. * --- 1994 : Creation.
  125. *
  126. ******************************************************************************/
  127. /* the colour to be calculated */
  128. /* maximum possible contribution to pixel colour */
  129. int Compute_Ambient(VECTOR IPoint, VECTOR S_Normal, COLOUR Ambient_Colour, DBL Weight)
  130. {
  131. int retval, reuse;
  132. DBL grey, save_bound;
  133. save_bound = opts.Radiosity_Error_Bound;
  134. if ( Weight < .25 )
  135. {
  136. opts.Radiosity_Error_Bound += (.25 - Weight);
  137. }
  138. reuse = ra_reuse(IPoint, S_Normal, Ambient_Colour);
  139. opts.Radiosity_Error_Bound = save_bound;
  140. if ( reuse )
  141. {
  142. ra_reuse_count++;
  143. retval = 0;
  144. }
  145. else
  146. {
  147. ra_gather(IPoint, S_Normal, Ambient_Colour, Weight);
  148. ra_gather_count++; /* keep a running count */
  149. retval = 1;
  150. }
  151. if ( Radiosity_Trace_Level == 1 )
  152. {
  153. grey = (Ambient_Colour[RED] + Ambient_Colour[GREEN] + Ambient_Colour[BLUE]) / 3.;
  154. /* note grey spelling: american options structure with worldbeat calculations! */
  155. Ambient_Colour[RED] = opts.Radiosity_Gray * grey + Ambient_Colour[RED] * (1.-opts.Radiosity_Gray);
  156. Ambient_Colour[GREEN] = opts.Radiosity_Gray * grey + Ambient_Colour[GREEN] * (1.-opts.Radiosity_Gray);
  157. Ambient_Colour[BLUE] = opts.Radiosity_Gray * grey + Ambient_Colour[BLUE] * (1.-opts.Radiosity_Gray);
  158. /* Scale up by current brightness factor prior to return */
  159. VScale(Ambient_Colour, Ambient_Colour, opts.Radiosity_Brightness);
  160. }
  161. return(retval);
  162. }
  163. /*****************************************************************************
  164. *
  165. * FUNCTION
  166. *
  167. * ra_reuse
  168. *
  169. * INPUT
  170. *
  171. * OUTPUT
  172. *
  173. * RETURNS
  174. *
  175. * AUTHOUR
  176. *
  177. * Jim McElhiney
  178. *
  179. * DESCRIPTION
  180. *
  181. * Returns whether or not there were some prestored values close enough to
  182. * reuse.
  183. *
  184. * CHANGES
  185. *
  186. * --- 1994 : Creation.
  187. *
  188. ******************************************************************************/
  189. static long ra_reuse/* return value */(VECTOR IPoint, VECTOR S_Normal, COLOUR Illuminance)
  190. {
  191. long i;
  192. WT_AVG gather;
  193. if (ot_root != NULL)
  194. {
  195. Make_Colour(gather.Weights_Times_Illuminances, 0.0, 0.0, 0.0);
  196. gather.Weights = 0.0;
  197. Assign_Vector(gather.P, IPoint);
  198. Assign_Vector(gather.N, S_Normal);
  199. gather.Weights_Count = 0;
  200. gather.Good_Count = 0;
  201. gather.Close_Count = 0;
  202. gather.Current_Error_Bound = opts.Radiosity_Error_Bound;
  203. for (i = 1; i < Radiosity_Trace_Level; i++)
  204. {
  205. gather.Current_Error_Bound *= 1.4;
  206. }
  207. /*
  208. * Go through the tree calculating a weighted average of all of the
  209. * usable points near this one
  210. */
  211. ot_dist_traverse(ot_root, IPoint, Radiosity_Trace_Level,
  212. ra_average_near, (void *)&gather);
  213. /* Did we get any nearby points we could reuse? */
  214. if (gather.Good_Count > 0)
  215. {
  216. Make_Colour(gather.Weights_Times_Illuminances, 0.0, 0.0, 0.0);
  217. gather.Weights = 0.0;
  218. for (i = 0; i < gather.Close_Count; i++)
  219. {
  220. VAddEq(gather.Weights_Times_Illuminances, gather.Weight_Times_Illuminance[i]);
  221. gather.Weights += gather.Weight[i];
  222. }
  223. VInverseScale(Illuminance, gather.Weights_Times_Illuminances, gather.Weights);
  224. }
  225. }
  226. else
  227. {
  228. gather.Good_Count = 0; /* No tree, so no reused values */
  229. }
  230. return(gather.Good_Count);
  231. }
  232. /*****************************************************************************
  233. *
  234. * FUNCTION
  235. *
  236. * ra_average_near
  237. *
  238. * INPUT
  239. *
  240. * OUTPUT
  241. *
  242. * RETURNS
  243. *
  244. * AUTHOUR
  245. *
  246. * Jim McElhiney
  247. *
  248. * DESCRIPTION
  249. *
  250. * Tree traversal function used by ra_reuse()
  251. * Calculate the weight of this cached value, taking into account how far
  252. * it is from our test point, and the difference in surface normal angles.
  253. *
  254. * Given a node with an old cached value, check to see if it is reusable, and
  255. * aggregate its info into the weighted average being built during the tree
  256. * traversal. block contains Point, Normal, Illuminance,
  257. * Harmonic_Mean_Distance
  258. *
  259. * CHANGES
  260. *
  261. * --- 1994 : Creation.
  262. *
  263. ******************************************************************************/
  264. static long ra_average_near(OT_BLOCK *block, void *void_info)
  265. {
  266. long ind, i;
  267. WT_AVG *info = (WT_AVG *) void_info;
  268. VECTOR half, delta, delta_unit;
  269. COLOUR tc, prediction;
  270. DBL ri, error_reuse, dir_diff, in_front, dist, weight, square_dist, dr, dg, db;
  271. DBL error_reuse_rotate, error_reuse_translate, inverse_dist, cos_diff_from_nearest;
  272. DBL quickcheck_rad;
  273. #ifdef RADSTATS
  274. ot_doblockcount++;
  275. #endif
  276. VSub(delta, info->P, block->Point); /* a = b - c, which is test p minus old pt */
  277. square_dist = VSumSqr(delta);
  278. quickcheck_rad = (DBL)block->Harmonic_Mean_Distance * info->Current_Error_Bound;
  279. /* first we do a tuning test--this func gets called a LOT */
  280. if (square_dist < quickcheck_rad * quickcheck_rad)
  281. {
  282. dist = sqrt(square_dist);
  283. ri = (DBL)block->Harmonic_Mean_Distance;
  284. if ( dist > .000001 )
  285. {
  286. inverse_dist = 1./dist;
  287. VScale(delta_unit, delta, inverse_dist); /* this is a normalization */
  288. /* This block reduces the radius of influence when it points near the nearest
  289. surface found during sampling. */
  290. VDot( cos_diff_from_nearest, block->To_Nearest_Surface, delta_unit);
  291. if ( cos_diff_from_nearest > 0. )
  292. {
  293. ri = cos_diff_from_nearest * (DBL)block->Nearest_Distance +
  294. (1.-cos_diff_from_nearest) * ri;
  295. }
  296. }
  297. if (dist < ri * info->Current_Error_Bound)
  298. {
  299. VDot(dir_diff, info->N, block->S_Normal);
  300. /* NB error_reuse varies from 0 to 3.82 (1+ 2 root 2) */
  301. error_reuse_translate = dist / ri;
  302. error_reuse_rotate = 2.0 * sqrt(fabs(1.0 - dir_diff));
  303. error_reuse = error_reuse_translate + error_reuse_rotate;
  304. /* is this old point within a reasonable error distance? */
  305. if (error_reuse < info->Current_Error_Bound)
  306. {
  307. #ifdef RADSTATS
  308. ot_lowerrorcount++;
  309. #endif
  310. if (dist > 0.000001)
  311. {
  312. /*
  313. * Make sure that the old point is not in front of this point, the
  314. * old surface might shadow this point and make the result
  315. * meaningless
  316. */
  317. VHalf(half, info->N, block->S_Normal);
  318. VNormalizeEq(half); /* needed so check can be to constant */
  319. VDot(in_front, delta_unit, half);
  320. }
  321. else
  322. {
  323. in_front = 1.0;
  324. }
  325. /*
  326. * Theory: eliminate the use of old points well in front of our
  327. * new point we are calculating, but not ones which are just a little
  328. * tiny bit in front. This (usually) avoids eliminating points on the
  329. * same surface by accident.
  330. */
  331. if (in_front > (-0.05))
  332. {
  333. #ifdef RADSTATS
  334. ot_dotokcount++;
  335. #endif
  336. #ifdef SIGMOID_METHOD
  337. weight = error_reuse / info->Current_Error_Bound; /* 0 < t < 1 */
  338. weight = (cos(weight * M_PI) + 1.0) * 0.5; /* 0 < w < 1 */
  339. #endif
  340. #ifdef SAW_METHOD
  341. weight = 1.0 - (error_reuse / info->Current_Error_Bound); /* 0 < t < 1 */
  342. #endif
  343. if ( weight > 0.001 )
  344. { /* avoid floating point oddities near zero */
  345. /* This is the block where we use the gradient to improve the prediction */
  346. dr = delta[X] * block->drdx + delta[Y] * block->drdy + delta[Z] * block->drdz;
  347. dg = delta[X] * block->dgdx + delta[Y] * block->dgdy + delta[Z] * block->dgdz;
  348. db = delta[X] * block->dbdx + delta[Y] * block->dbdy + delta[Z] * block->dbdz;
  349. #ifndef RAD_GRADIENT
  350. dr = dg = db = 0.;
  351. #endif
  352. #if 0
  353. /* Ensure that the total change in colour is a reasonable magnitude */
  354. if ( dr > .1 ) dr = .1; else if ( dr < -.1 ) dr = -.1;
  355. if ( dg > .1 ) dg = .1; else if ( dg < -.1 ) dg = -.1;
  356. if ( db > .1 ) db = .1; else if ( db < -.1 ) db = -.1;
  357. #endif
  358. prediction[RED] = block->Illuminance[RED] + dr;
  359. prediction[RED] = min(max(prediction[RED], 0.), 1.);
  360. prediction[GREEN] = block->Illuminance[GREEN] + dg;
  361. prediction[GREEN] = min(max(prediction[GREEN],0.), 1.);
  362. prediction[BLUE] = block->Illuminance[BLUE] + db;
  363. prediction[BLUE] = min(max(prediction[BLUE], 0.), 1.);
  364. #ifdef SHOW_SAMPLE_SPOTS
  365. if ( dist < opts.Radiosity_Dist_Max * .015 ) {
  366. prediction[RED] = prediction[GREEN] = prediction[BLUE] = 3.;
  367. }
  368. #endif
  369. /* The predicted colour is an extrapolation based on the old value */
  370. VScale(tc, prediction, weight);
  371. VAddEq(info->Weights_Times_Illuminances, tc);
  372. info->Weights += weight;
  373. info->Weights_Count++;
  374. info->Good_Count++;
  375. ind = -1;
  376. if (info->Close_Count < opts.Radiosity_Nearest_Count)
  377. {
  378. ind = info->Close_Count++;
  379. }
  380. else
  381. {
  382. for (i = 0; i < info->Close_Count; i++)
  383. {
  384. if (dist < info->Distance[i])
  385. {
  386. ind = i;
  387. i = opts.Radiosity_Nearest_Count;
  388. }
  389. }
  390. }
  391. if (ind != -1)
  392. {
  393. info->Distance[ind] = dist;
  394. info->Weight[ind] = weight;
  395. VScale(info->Weight_Times_Illuminance[ind], prediction, weight);
  396. }
  397. }
  398. }
  399. }
  400. }
  401. }
  402. return(1);
  403. }
  404. /*****************************************************************************
  405. *
  406. * FUNCTION
  407. *
  408. * ra_gather
  409. *
  410. * INPUT
  411. * IPoint - a point at which the illumination is needed
  412. * S_Normal - the surface normal (not perturbed by the current layer) at that point
  413. * Illuminance - a place to put the return result
  414. * Weight - the weight of this point in final output, to drive ADC_Bailout
  415. *
  416. * OUTPUT
  417. * The average colour of light of objects visible from the specified point.
  418. * The colour is returned in the Illuminance parameter.
  419. *
  420. *
  421. * RETURNS
  422. *
  423. * AUTHOUR
  424. *
  425. * Jim McElhiney
  426. *
  427. * DESCRIPTION
  428. * Gather up the incident light and average it.
  429. * Return the results in Illuminance, and also cache them for later.
  430. * Note that last parameter is similar to weight parameter used
  431. * to control ADC_Bailout as a parameter to Trace(), but it also
  432. * takes into account that this subsystem calculates only ambient
  433. * values. Therefore, coming in at the top level, the value might
  434. * be 0.3 if the first object hit had an ambient of 0.3, whereas
  435. * Trace() would have been passed a parameter of 1.0 (since it
  436. * calculates the whole pixel value).
  437. *
  438. * CHANGES
  439. *
  440. * --- 1994 : Creation.
  441. *
  442. ******************************************************************************/
  443. static void ra_gather(VECTOR IPoint, VECTOR S_Normal, COLOUR Illuminance, DBL Weight)
  444. {
  445. extern FRAME Frame;
  446. long i, hit, Current_Radiosity_Count;
  447. unsigned long Save_Quality_Flags, Save_Options;
  448. VECTOR random_vec, direction, n2, n3, up, min_dist_vec;
  449. int save_Max_Trace_Level;
  450. DBL Inverse_Distance_Sum, depth, mean_dist, weight, save_min_reuse,
  451. drdxs, dgdxs, dbdxs, drdys, dgdys, dbdys, drdzs, dgdzs, dbdzs,
  452. depth_weight_for_this_gradient, dxsquared, dysquared, dzsquared,
  453. constant_term, deemed_depth, min_dist, reuse_dist_min, to_eye,
  454. sum_of_inverse_dist, sum_of_dist, average_dist, gradient_count;
  455. COLOUR Colour_Sums, Temp_Colour;
  456. RAY New_Ray;
  457. OT_BLOCK *block;
  458. OT_ID id;
  459. /*
  460. * A bit of theory: The goal is to create a set of "random" direction rays
  461. * so that the probability of close-to-normal versus close-to-tangent rolls
  462. * off in a cos-theta curve, where theta is the deviation from normal.
  463. * That is, lots of rays close to normal, and very few close to tangent.
  464. * You also want to have all of the rays be evenly spread, no matter how
  465. * many you want to use. The lookup array has an array of points carefully
  466. * chosen to meet all of these criteria.
  467. */
  468. /* The number of rays to trace varies with our recursion depth */
  469. Current_Radiosity_Count = opts.Radiosity_Count;
  470. save_min_reuse = opts.Radiosity_Min_Reuse;
  471. for ( i=1; i<Radiosity_Trace_Level; i++ )
  472. {
  473. Current_Radiosity_Count /= 3;
  474. opts.Radiosity_Min_Reuse *= 2.;
  475. }
  476. /* Save some global stuff which we have to change for now */
  477. save_Max_Trace_Level = Max_Trace_Level;
  478. /* Since we'll be calculating averages, zero the accumulators */
  479. Make_Colour(Colour_Sums, 0., 0., 0.);
  480. Inverse_Distance_Sum = 0.;
  481. min_dist = BOUND_HUGE;
  482. if ( fabs(fabs(S_Normal[Z])- 1.) < .1 ) {
  483. /* too close to vertical for comfort, so use cross product with horizon */
  484. up[X] = 0.; up[Y] = 1.; up[Z] = 0.;
  485. }
  486. else
  487. {
  488. up[X] = 0.; up[Y] = 0.; up[Z] = 1.;
  489. }
  490. VCross(n2, S_Normal, up); VNormalizeEq(n2);
  491. VCross(n3, S_Normal, n2); VNormalizeEq(n3);
  492. /* Note that this max() forces at least one ray to be shot.
  493. Otherwise, the loop does nothing, since every call to
  494. Trace() just bails out immediately! */
  495. weight = max(ADC_Bailout, Weight/(DBL)Current_Radiosity_Count);
  496. /* Initialized the accumulators for the integrals which will be come the rad gradient */
  497. drdxs = dgdxs = dbdxs = drdys = dgdys = dbdys = drdzs = dgdzs = dbdzs = 0.;
  498. sum_of_inverse_dist = sum_of_dist = gradient_count = 0.;
  499. for (i = hit = 0; i < Current_Radiosity_Count; i++)
  500. {
  501. /* pick a random direction with the right statistical skew */
  502. VUnpack(random_vec, &rad_samples[i]);
  503. if ( fabs(S_Normal[Z] - 1.) < .001 ) /* pretty well straight Z, folks */
  504. {
  505. /* we are within 1/20 degree of pointing in the Z axis. */
  506. /* use all vectors as is--they're precomputed this way */
  507. Assign_Vector(direction, random_vec);
  508. }
  509. else
  510. {
  511. direction[X] = n2[X]*random_vec[X] + n3[X]*random_vec[Y] + S_Normal[X]*random_vec[Z];
  512. direction[Y] = n2[Y]*random_vec[X] + n3[Y]*random_vec[Y] + S_Normal[Y]*random_vec[Z];
  513. direction[Z] = n2[Z]*random_vec[X] + n3[Z]*random_vec[Y] + S_Normal[Z]*random_vec[Z];
  514. }
  515. /* Build a ray pointing in the chosen direction */
  516. Make_Colour(Temp_Colour, 0.0, 0.0, 0.0);
  517. Initialize_Ray_Containers(&New_Ray);
  518. Assign_Vector(New_Ray.Initial, IPoint);
  519. Assign_Vector(New_Ray.Direction, direction);
  520. /* save some flags that must be set to a different value during the trace() */
  521. Save_Quality_Flags = opts.Quality_Flags;
  522. Save_Options = opts.Options;
  523. opts.Radiosity_Quality = 6;
  524. #ifdef SAFE_BUT_SLOW
  525. opts.Quality_Flags = Quality_Values[opts.Radiosity_Quality];
  526. #else
  527. /* Set up a custom quality level, like Q=5, without area lights, with radiosity */
  528. opts.Quality_Flags = Q_SHADOW;
  529. opts.Options &= ~USE_LIGHT_BUFFER;
  530. #endif
  531. /* Go down in recursion, trace the result, and come back up */
  532. Trace_Level++;
  533. Radiosity_Trace_Level++;
  534. depth = Trace(&New_Ray, Temp_Colour, weight);
  535. Radiosity_Trace_Level--;
  536. Trace_Level--;
  537. /* Add into illumination gradient integrals */
  538. deemed_depth = depth;
  539. if (deemed_depth < opts.Radiosity_Dist_Max * 10.)
  540. {
  541. depth_weight_for_this_gradient = 1. / deemed_depth;
  542. sum_of_inverse_dist += 1. / deemed_depth;
  543. sum_of_dist += deemed_depth;
  544. gradient_count++;
  545. dxsquared = direction[X] * direction[X]; if (direction[X] < 0.) dxsquared = -dxsquared;
  546. dysquared = direction[Y] * direction[Y]; if (direction[Y] < 0.) dysquared = -dysquared;
  547. dzsquared = direction[Z] * direction[Z]; if (direction[Z] < 0.) dzsquared = -dzsquared;
  548. drdxs += dxsquared * Temp_Colour[RED] * depth_weight_for_this_gradient;
  549. dgdxs += dxsquared * Temp_Colour[GREEN] * depth_weight_for_this_gradient;
  550. dbdxs += dxsquared * Temp_Colour[BLUE] * depth_weight_for_this_gradient;
  551. drdys += dysquared * Temp_Colour[RED] * depth_weight_for_this_gradient;
  552. dgdys += dysquared * Temp_Colour[GREEN] * depth_weight_for_this_gradient;
  553. dbdys += dysquared * Temp_Colour[BLUE] * depth_weight_for_this_gradient;
  554. drdzs += dzsquared * Temp_Colour[RED] * depth_weight_for_this_gradient;
  555. dgdzs += dzsquared * Temp_Colour[GREEN] * depth_weight_for_this_gradient;
  556. dbdzs += dzsquared * Temp_Colour[BLUE] * depth_weight_for_this_gradient;
  557. }
  558. if (depth > opts.Radiosity_Dist_Max)
  559. {
  560. depth = opts.Radiosity_Dist_Max;
  561. }
  562. else
  563. {
  564. #ifdef RADSTATS
  565. hit++;
  566. #endif
  567. }
  568. if (depth < min_dist)
  569. {
  570. min_dist = depth;
  571. Assign_Vector(min_dist_vec, direction);
  572. }
  573. opts.Quality_Flags = Save_Quality_Flags;
  574. opts.Options = Save_Options;
  575. /* Add into total illumination integral */
  576. VAddEq(Colour_Sums, Temp_Colour);
  577. Inverse_Distance_Sum += 1.0 / depth;
  578. } /* end ray sampling loop */
  579. /*
  580. * Use the accumulated values to calculate the averages needed. The sphere
  581. * of influence of this primary-method sample point is based on the
  582. * harmonic mean distance to the points encountered. (An harmonic mean is
  583. * the inverse of the mean of the inverses).
  584. */
  585. mean_dist = 1.0 / (Inverse_Distance_Sum / (DBL) Current_Radiosity_Count);
  586. VInverseScale(Illuminance, Colour_Sums, (DBL) Current_Radiosity_Count);
  587. /* Keep a running total of the final Illuminances we calculated */
  588. if ( Radiosity_Trace_Level == 1.) {
  589. VAddEq(Radiosity_Gather_Total, Illuminance);
  590. Radiosity_Gather_Total_Count++;
  591. }
  592. /* We want to cached this block for later reuse. But,
  593. * if ground units not big enough, meaning that the value has very
  594. * limited reuse potential, forget it.
  595. */
  596. if (mean_dist > (opts.Radiosity_Dist_Max * 0.0001))
  597. {
  598. /*
  599. * Theory: we don't want to calculate a primary method ray loop at every
  600. * point along the inside edges, so a minimum effectivity is practical.
  601. * It is expressed as a fraction of the distance to the eyepoint. 1/2%
  602. * is a good number. This enhancement was Greg Ward's idea, but the use
  603. * of % units is my idea. [JDM]
  604. */
  605. VDist(to_eye, Frame.Camera->Location, IPoint);
  606. reuse_dist_min = to_eye * opts.Radiosity_Min_Reuse;
  607. if (mean_dist < reuse_dist_min)
  608. {
  609. mean_dist = reuse_dist_min;
  610. }
  611. /* figure out the block id */
  612. ot_index_sphere(IPoint, mean_dist * opts.Radiosity_Error_Bound, &id);
  613. #ifdef RADSTATS
  614. ot_blockcount++;
  615. #endif
  616. /* After end of ray loop, we've decided that this point is worth storing */
  617. /* Allocate a block, and fill it with values for reuse in cacheing later */
  618. block = (OT_BLOCK *)POV_MALLOC(sizeof(OT_BLOCK), "octree block");
  619. memset(block, 0, sizeof(OT_BLOCK));
  620. /* beta */
  621. if ( gradient_count > 10.)
  622. {
  623. average_dist = sum_of_dist / gradient_count;
  624. constant_term = 1.00 / (sum_of_inverse_dist * average_dist );
  625. block->drdx = (float)(drdxs * constant_term);
  626. block->dgdx = (float)(dgdxs * constant_term);
  627. block->dbdx = (float)(dbdxs * constant_term);
  628. block->drdy = (float)(drdys * constant_term);
  629. block->dgdy = (float)(dgdys * constant_term);
  630. block->dbdy = (float)(dbdys * constant_term);
  631. block->drdz = (float)(drdzs * constant_term);
  632. block->dgdz = (float)(dgdzs * constant_term);
  633. block->dbdz = (float)(dbdzs * constant_term);
  634. }
  635. /* Fill up the values in the octree (ot_) cache block */
  636. Assign_Vector(block->Illuminance, Illuminance);
  637. Assign_Vector(block->To_Nearest_Surface, min_dist_vec);
  638. block->Harmonic_Mean_Distance = (float)mean_dist;
  639. block->Nearest_Distance = (float)min_dist;
  640. block->Bounce_Depth = (short)Radiosity_Trace_Level;
  641. Assign_Vector(block->Point, IPoint);
  642. Assign_Vector(block->S_Normal, S_Normal);
  643. block->next = NULL;
  644. /* store the info block in the oct tree */
  645. ot_ins(&ot_root, block, &id);
  646. /* In case the rendering is suspended, save the cache tree values to a file */
  647. if ( opts.Radiosity_File_SaveWhileRendering && (ot_fd != NULL) ) {
  648. ot_write_block(block, ot_fd);
  649. }
  650. }
  651. /* Put things back where they were in recursion depth */
  652. Max_Trace_Level = save_Max_Trace_Level;
  653. opts.Radiosity_Min_Reuse = save_min_reuse;
  654. }
  655. /*****************************************************************************
  656. *
  657. * FUNCTION VUnpack() - Unpacks "pack_vec" into "dest_vec" and normalizes it.
  658. *
  659. * INPUT
  660. *
  661. * OUTPUT
  662. *
  663. * RETURNS Nothing
  664. *
  665. * AUTHOUR Jim McElhiney
  666. *
  667. * DESCRIPTION
  668. *
  669. * The precomputed radiosity rays are packed into a lookup array with one byte
  670. * for each of dx, dy, and dz. dx and dy are scaled from the range (-1. to 1.),
  671. * and dz is scaled from the range (0. to 1.), and both are stored in the range
  672. * 0 to 255.
  673. *
  674. * The reason for this function is that it saves a bit of memory. There are 2000
  675. * entries in the table, and packing them saves 21 bytes each, or 42KB.
  676. *
  677. * CHANGES
  678. *
  679. * --- Jan 1996 : Creation.
  680. *
  681. ******************************************************************************/
  682. static void VUnpack(VECTOR dest_vec, BYTE_XYZ * pack_vec)
  683. {
  684. dest_vec[X] = ((double)pack_vec->x * (1./ 255.))*2.-1.;
  685. dest_vec[Y] = ((double)pack_vec->y * (1./ 255.))*2.-1.;
  686. dest_vec[Z] = ((double)pack_vec->z * (1./ 255.));
  687. VNormalizeEq(dest_vec); /* already good to about 1%, but we can do better */
  688. }
  689. /*****************************************************************************
  690. *
  691. * FUNCTION Initialize_Radiosity_Code
  692. *
  693. * INPUT Nothing.
  694. *
  695. * OUTPUT Sets various global states used by radiosity. Notably,
  696. * ot_fd - the file identifier of the file used to save radiosity values
  697. *
  698. * RETURNS 1 for Success, 0 for failure (e.g., could not open cache file)
  699. *
  700. * AUTHOUR Jim McElhiney
  701. *
  702. * DESCRIPTION
  703. *
  704. * CHANGES
  705. *
  706. * --- Jan 1996 : Creation.
  707. *
  708. ******************************************************************************/
  709. long
  710. Initialize_Radiosity_Code()
  711. {
  712. long retval, used_existing_file;
  713. FILE *fd;
  714. char *modes, rad_cache_filename[256];
  715. retval = 1; /* assume the best */
  716. if ( opts.Options & RADIOSITY )
  717. {
  718. opts.Radiosity_Preview_Done = 0;
  719. ra_gather_count = 0;
  720. ra_reuse_count = 0;
  721. if ( opts.Radiosity_Dist_Max == 0. )
  722. {
  723. /* User hasn't picked a radiosity dist max, so pick one automatically. */
  724. VDist(opts.Radiosity_Dist_Max, Frame.Camera->Location,
  725. Frame.Camera->Look_At);
  726. opts.Radiosity_Dist_Max *= 0.2;
  727. }
  728. #ifdef RADSTATS
  729. ot_seenodecount = 0;
  730. ot_seeblockcount = 0;
  731. ot_doblockcount = 0;
  732. ot_dotokcount = 0;
  733. ot_lowerrorcount = 0;
  734. ot_lastcount = 0;
  735. #endif
  736. if ( ot_fd != NULL ) /* if already open for some unknown reason, close it */
  737. {
  738. fclose(ot_fd);
  739. ot_fd = 0;
  740. }
  741. /* build the file name for the radiosity cache file */
  742. strcpy(rad_cache_filename, opts.Scene_Name);
  743. strcat(rad_cache_filename, RADIOSITY_CACHE_EXTENSION);
  744. used_existing_file = 0;
  745. if ( ((opts.Options & CONTINUE_TRACE) && opts.Radiosity_File_ReadOnContinue) ||
  746. opts.Radiosity_File_AlwaysReadAtStart )
  747. {
  748. fd = fopen(rad_cache_filename, READ_BINFILE_STRING); /* "myname.rca" */
  749. if ( fd != NULL) {
  750. used_existing_file = ot_read_file(fd);
  751. retval &= used_existing_file;
  752. fclose(fd);
  753. }
  754. }
  755. else
  756. {
  757. DELETE_FILE(rad_cache_filename); /* default case, force a clean start */
  758. }
  759. if ( opts.Radiosity_File_SaveWhileRendering )
  760. {
  761. /* If we are writing a file, but not using what's there, we truncate,
  762. since we conclude that what is there is bad.
  763. But, if we are also using what's there, then it must be good, so
  764. we just append to it.
  765. */
  766. modes = used_existing_file ? APPEND_BINFILE_STRING : WRITE_BINFILE_STRING;
  767. ot_fd = fopen(rad_cache_filename, modes);
  768. retval &= (ot_fd != NULL);
  769. }
  770. }
  771. return retval;
  772. }
  773. /*****************************************************************************
  774. *
  775. * FUNCTION Deinitialize_Radiosity_Code()
  776. *
  777. * INPUT Nothing.
  778. *
  779. * OUTPUT Sets various global states used by radiosity. Notably,
  780. * ot_fd - the file identifier of the file used to save radiosity values
  781. *
  782. * RETURNS 1 for total success, 0 otherwise (e.g., could not save cache tree)
  783. *
  784. * AUTHOUR Jim McElhiney
  785. *
  786. * DESCRIPTION
  787. * Wrap up and free any radiosity-specific features.
  788. * Note that this function is safe to call even if radiosity was not on.
  789. *
  790. * CHANGES
  791. *
  792. * --- Jan 1996 : Creation.
  793. *
  794. ******************************************************************************/
  795. long
  796. Deinitialize_Radiosity_Code()
  797. {
  798. long retval;
  799. char rad_cache_filename[256];
  800. FILE *fd;
  801. retval = 1; /* assume the best */
  802. if ( opts.Options & RADIOSITY )
  803. {
  804. /* if the global file identifier is set, close it */
  805. if ( ot_fd != NULL ) {
  806. fclose(ot_fd);
  807. ot_fd = NULL;
  808. }
  809. /* build the file name for the radiosity cache file */
  810. strcpy(rad_cache_filename, opts.Scene_Name);
  811. strcat(rad_cache_filename, RADIOSITY_CACHE_EXTENSION);
  812. /* If user has not asked us to save the radiosity cache file, delete it */
  813. if ( opts.Radiosity_File_SaveWhileRendering &&
  814. !(opts.Radiosity_File_KeepAlways || (Stop_Flag && opts.Radiosity_File_KeepOnAbort) ) )
  815. {
  816. DELETE_FILE(rad_cache_filename);
  817. }
  818. /* after-the-fact version. This is an alternative to putting a call to
  819. ot_write_node after the call to ot_ins in ra_gather().
  820. The on-the-fly version (all of the code which uses ot_fd) is superior
  821. in that you will get partial results if you restart your rendering
  822. with a different resolution or camera angle. This version is superior
  823. in that your rendering goes a lot quicker.
  824. */
  825. if (!(opts.Radiosity_File_KeepAlways || (Stop_Flag && opts.Radiosity_File_KeepOnAbort)) &&
  826. !opts.Radiosity_File_SaveWhileRendering && ot_root != NULL )
  827. {
  828. fd = fopen(rad_cache_filename, WRITE_BINFILE_STRING);
  829. if ( fd != NULL ) {
  830. retval &= ot_save_tree(ot_root, fd);
  831. fclose(fd);
  832. }
  833. else
  834. {
  835. retval = 0;
  836. }
  837. }
  838. /* Note that multiframe animations should call this free function if they have
  839. moving objects and want correct results.
  840. They should NOT call this function if they have no moving objects (like
  841. fly-throughs) and want speed
  842. */
  843. if ( ot_root != NULL ) {
  844. retval &= ot_free_tree(&ot_root); /* this zeroes the root pointer */
  845. }
  846. }
  847. return retval;
  848. }