ViewVC Help
View File | Revision Log | Show Annotations | Download File | Root Listing
root/radiance/ray/src/rt/pmapcontrib.c
Revision: 2.6
Committed: Wed May 20 13:43:28 2015 UTC (9 years ago) by greg
Content type: text/plain
Branch: MAIN
Changes since 2.5: +42 -41 lines
Log Message:
Eliminated debug message

File Contents

# Content
1 /*
2 ==================================================================
3 Photon map support for light source contributions
4
5 Roland Schregle (roland.schregle@{hslu.ch, gmail.com})
6 (c) Lucerne University of Applied Sciences and Arts,
7 supported by the Swiss National Science Foundation (SNSF, #147053)
8 ==================================================================
9
10 $Id: pmapcontrib.c,v 2.5 2015/05/20 12:58:31 greg Exp $
11 */
12
13
14 #include "pmapcontrib.h"
15 #include "pmap.h"
16 #include "pmapmat.h"
17 #include "pmapsrc.h"
18 #include "pmaprand.h"
19 #include "pmapio.h"
20 #include "pmapdiag.h"
21 #include "rcontrib.h"
22 #include "otypes.h"
23
24
25
26 static void setPmapContribParams (PhotonMap *pmap, LUTAB *srcContrib)
27 /* Set parameters for light source contributions */
28 {
29 /* Set light source modifier list and appropriate callback to extract
30 * their contributions from the photon map */
31 if (pmap) {
32 pmap -> srcContrib = srcContrib;
33 pmap -> lookup = photonContrib;
34 /* Ensure we get all requested photon contribs during lookups */
35 pmap -> gatherTolerance = 1.0;
36 }
37 }
38
39
40
41 static void checkPmapContribs (const PhotonMap *pmap, LUTAB *srcContrib)
42 /* Check modifiers for light source contributions */
43 {
44 const PhotonPrimary *primary = pmap -> primary;
45 OBJREC *srcMod;
46 unsigned long i, found = 0;
47
48 /* Make sure at least one of the modifiers is actually in the pmap,
49 * otherwise findPhotons() winds up in an infinite loop! */
50 for (i = pmap -> primarySize; i; --i, ++primary) {
51 if (primary -> srcIdx < 0 || primary -> srcIdx >= nsources)
52 error(INTERNAL, "invalid light source index in photon map");
53
54 srcMod = objptr(source [primary -> srcIdx].so -> omod);
55 if ((MODCONT*)lu_find(srcContrib, srcMod -> oname) -> data)
56 ++found;
57 }
58
59 if (!found)
60 error(USER, "modifiers not in photon map");
61 }
62
63
64
65 void initPmapContrib (LUTAB *srcContrib, unsigned numSrcContrib)
66 {
67 unsigned t;
68
69 for (t = 0; t < NUM_PMAP_TYPES; t++)
70 if (photonMaps [t] && t != PMAP_TYPE_CONTRIB) {
71 sprintf(errmsg, "%s photon map does not support contributions",
72 pmapName [t]);
73 error(USER, errmsg);
74 }
75
76 /* Get params */
77 setPmapContribParams(contribPmap, srcContrib);
78
79 if (contribPhotonMapping) {
80 if (contribPmap -> maxGather < numSrcContrib) {
81 /* Adjust density estimate bandwidth if lower than modifier
82 * count, otherwise contributions are missing */
83 error(WARNING, "contrib density estimate bandwidth too low, "
84 "adjusting to modifier count");
85 contribPmap -> maxGather = numSrcContrib;
86 }
87
88 /* Sanity check */
89 checkPmapContribs(contribPmap, srcContrib);
90 }
91 }
92
93
94
95 void photonContrib (PhotonMap *pmap, RAY *ray, COLOR irrad)
96 /* Sum up light source contributions from photons in pmap->srcContrib */
97 {
98 unsigned i;
99 PhotonSQNode *sq;
100 float r, invArea;
101 RREAL rayCoeff [3];
102
103 setcolor(irrad, 0, 0, 0);
104
105 if (!pmap -> maxGather)
106 return;
107
108 /* Ignore sources */
109 if (ray -> ro)
110 if (islight(objptr(ray -> ro -> omod) -> otype))
111 return;
112
113 /* Get cumulative path
114 * coefficient up to photon lookup point */
115 raycontrib(rayCoeff, ray, PRIMARY);
116
117 /* Lookup photons */
118 pmap -> squeueEnd = 0;
119 findPhotons(pmap, ray);
120
121 /* Need at least 2 photons */
122 if (pmap -> squeueEnd < 2) {
123 #ifdef PMAP_NONEFOUND
124 sprintf(errmsg, "no photons found on %s at (%.3f, %.3f, %.3f)",
125 ray -> ro ? ray -> ro -> oname : "<null>",
126 ray -> rop [0], ray -> rop [1], ray -> rop [2]);
127 error(WARNING, errmsg);
128 #endif
129
130 return;
131 }
132
133 /* Average (squared) radius between furthest two photons to improve
134 * accuracy and get inverse search area 1 / (PI * r^2), with extra
135 * normalisation factor 1 / PI for ambient calculation */
136 sq = pmap -> squeue + 1;
137 r = max(sq -> dist, (sq + 1) -> dist);
138 r = 0.25 * (pmap -> maxDist + r + 2 * sqrt(pmap -> maxDist * r));
139 invArea = 1 / (PI * PI * r);
140
141 /* Skip the extra photon */
142 for (i = 1 ; i < pmap -> squeueEnd; i++, sq++) {
143 COLOR flux;
144
145 /* Get photon's contribution to density estimate */
146 getPhotonFlux(sq -> photon, flux);
147 scalecolor(flux, invArea);
148 #ifdef PMAP_EPANECHNIKOV
149 /* Apply Epanechnikov kernel to photon flux (dists are squared) */
150 scalecolor(flux, 2 * (1 - sq -> dist / r));
151 #endif
152 addcolor(irrad, flux);
153
154 if (pmap -> srcContrib) {
155 const PhotonPrimary *primary = pmap -> primary +
156 sq -> photon -> primary;
157 SRCREC *sp = &source[primary -> srcIdx];
158 OBJREC *srcMod = objptr(sp -> so -> omod);
159 MODCONT *srcContrib = (MODCONT*)lu_find(pmap -> srcContrib,
160 srcMod -> oname) -> data;
161 if (!srcContrib)
162 continue;
163
164 /* Photon's emitting light source has modifier whose
165 * contributions are sought */
166 double srcBinReal;
167 int srcBin;
168 RAY srcRay;
169
170 if (srcContrib -> binv -> type != NUM) {
171 /* Use intersection function to set shadow ray parameters
172 * if it's not simply a constant
173 */
174 rayorigin(&srcRay, SHADOW, NULL, NULL);
175 srcRay.rsrc = primary -> srcIdx;
176 VCOPY(srcRay.rorg, primary -> pos);
177 VCOPY(srcRay.rdir, primary -> dir);
178 if (!(source [primary -> srcIdx].sflags & SDISTANT ?
179 sourcehit(&srcRay) :
180 (*ofun[sp -> so -> otype].funp)(sp -> so, &srcRay)))
181 continue; /* XXX shouldn't happen! */
182 worldfunc(RCCONTEXT, &srcRay);
183 set_eparams((char *)srcContrib -> params);
184 }
185
186 if ((srcBinReal = evalue(srcContrib -> binv)) < -.5)
187 continue; /* silently ignore negative bins */
188
189 if ((srcBin = srcBinReal + .5) >= srcContrib -> nbins) {
190 error(WARNING, "bad bin number (ignored)");
191 continue;
192 }
193
194 if (!contrib) {
195 /* Ray coefficient mode; normalise by light source radiance
196 * after applying distrib pattern */
197 int j;
198 raytexture(ray, srcMod -> omod);
199 setcolor(ray -> rcol, srcMod -> oargs.farg [0],
200 srcMod -> oargs.farg [1], srcMod -> oargs.farg [2]);
201 multcolor(ray -> rcol, ray -> pcol);
202 for (j = 0; j < 3; j++)
203 flux [j] = ray -> rcol [j] ? flux [j] / ray -> rcol [j]
204 : 0;
205 }
206
207 multcolor(flux, rayCoeff);
208 addcolor(srcContrib -> cbin [srcBin], flux);
209 }
210 }
211
212 return;
213 }
214
215
216
217 void distribPhotonContrib (PhotonMap* pm)
218 {
219 EmissionMap emap;
220 char errmsg2 [128];
221 unsigned srcIdx;
222 double *srcFlux; /* Emitted flux per light source */
223 const double srcDistribTarget = /* Target photon count per source */
224 nsources ? (double)pm -> distribTarget / nsources : 0;
225
226 if (!pm)
227 error(USER, "no photon map defined");
228
229 if (!nsources)
230 error(USER, "no light sources");
231
232 /* Allocate photon flux per light source; this differs for every
233 * source as all sources contribute the same number of distributed
234 * photons (srcDistribTarget), hence the number of photons emitted per
235 * source does not correlate with its emitted flux. The resulting flux
236 * per photon is therefore adjusted individually for each source. */
237 if (!(srcFlux = calloc(nsources, sizeof(double))))
238 error(SYSTEM, "cannot allocate source flux");
239
240 /* ================================================================
241 * INITIALISASHUNN - Set up emisshunn and scattering funcs
242 * ================================================================ */
243 emap.samples = NULL;
244 emap.src = NULL;
245 emap.maxPartitions = MAXSPART;
246 emap.partitions = (unsigned char*)malloc(emap.maxPartitions >> 1);
247 if (!emap.partitions)
248 error(USER, "can't allocate source partitions");
249
250 initPhotonMap(pm, PMAP_TYPE_CONTRIB);
251 initPhotonEmissionFuncs();
252 initPhotonScatterFuncs();
253
254 /* Get photon ports if specified */
255 if (ambincl == 1)
256 getPhotonPorts();
257
258 /* Get photon sensor modifiers */
259 getPhotonSensors(photonSensorList);
260
261 /* Seed RNGs for photon distribution */
262 pmapSeed(randSeed, partState);
263 pmapSeed(randSeed, emitState);
264 pmapSeed(randSeed, cntState);
265 pmapSeed(randSeed, mediumState);
266 pmapSeed(randSeed, scatterState);
267 pmapSeed(randSeed, rouletteState);
268
269 /* Record start time and enable progress report signal handler */
270 repStartTime = time(NULL);
271 #ifdef SIGCONT
272 signal(SIGCONT, pmapDistribReport);
273 #endif
274
275 for (srcIdx = 0; srcIdx < nsources; srcIdx++) {
276 unsigned portCnt = 0, passCnt = 0, prePassCnt = 0;
277 double srcNumEmit = 0; /* # photons to emit from source */
278 unsigned long srcNumDistrib = pm -> heapEnd; /* # photons stored */
279
280 srcFlux [srcIdx] = repProgress = 0;
281 emap.src = source + srcIdx;
282
283 if (photonRepTime)
284 eputs("\n");
285
286 /* =============================================================
287 * FLUX INTEGRATION - Get total flux emitted from light source
288 * ============================================================= */
289 do {
290 emap.port = emap.src -> sflags & SDISTANT
291 ? photonPorts + portCnt : NULL;
292 photonPartition [emap.src -> so -> otype] (&emap);
293
294 if (photonRepTime) {
295 sprintf(errmsg, "Integrating flux from source %s (mod %s) ",
296 source [srcIdx].so -> oname,
297 objptr(source [srcIdx].so -> omod) -> oname);
298
299 if (emap.port) {
300 sprintf(errmsg2, "via port %s ",
301 photonPorts [portCnt].so -> oname);
302 strcat(errmsg, errmsg2);
303 }
304
305 sprintf(errmsg2, "(%lu partitions)...\n",
306 emap.numPartitions);
307 strcat(errmsg, errmsg2);
308 eputs(errmsg);
309 fflush(stderr);
310 }
311
312 for (emap.partitionCnt = 0;
313 emap.partitionCnt < emap.numPartitions;
314 emap.partitionCnt++) {
315 initPhotonEmission(&emap, pdfSamples);
316 srcFlux [srcIdx] += colorAvg(emap.partFlux);
317 }
318
319 portCnt++;
320 } while (portCnt < numPhotonPorts);
321
322 if (srcFlux [srcIdx] < FTINY) {
323 sprintf(errmsg, "source %s has zero emission",
324 source [srcIdx].so -> oname);
325 error(WARNING, errmsg);
326 }
327 else {
328 /* ==========================================================
329 * 2-PASS PHOTON DISTRIBUTION
330 * Pass 1 (pre): emit fraction of target photon count
331 * Pass 2 (main): based on outcome of pass 1, estimate
332 * remaining number of photons to emit to
333 * approximate target count
334 * ========================================================== */
335 do {
336 if (!passCnt) {
337 /* INIT PASS 1 */
338 if (++prePassCnt > maxPreDistrib) {
339 /* Warn if no photons contributed after sufficient
340 * iterations */
341 sprintf(errmsg, "too many prepasses, no photons "
342 "from source %s", source [srcIdx].so -> oname);
343 error(WARNING, errmsg);
344 break;
345 }
346
347 /* Num to emit is fraction of target count */
348 srcNumEmit = preDistrib * srcDistribTarget;
349 }
350
351 else {
352 /* INIT PASS 2 */
353 /* Based on the outcome of the predistribution we can now
354 * figure out how many more photons we have to emit from
355 * the current source to meet the target count,
356 * srcDistribTarget. This value is clamped to 0 in case
357 * the target has already been exceeded in pass 1.
358 * srcNumEmit and srcNumDistrib is the number of photons
359 * emitted and distributed (stored) from the current
360 * source in pass 1, respectively. */
361 srcNumDistrib = pm -> heapEnd - srcNumDistrib;
362 srcNumEmit *= srcNumDistrib
363 ? max(srcDistribTarget/srcNumDistrib, 1) - 1
364 : 0;
365
366 if (!srcNumEmit)
367 /* No photons left to distribute in main pass */
368 break;
369 }
370
371 /* Set completion count for progress report */
372 repComplete = srcNumEmit + repProgress;
373 portCnt = 0;
374
375 do {
376 emap.port = emap.src -> sflags & SDISTANT
377 ? photonPorts + portCnt : NULL;
378 photonPartition [emap.src -> so -> otype] (&emap);
379
380 if (photonRepTime) {
381 if (!passCnt)
382 sprintf(errmsg, "PREPASS %d on source %s (mod %s) ",
383 prePassCnt, source [srcIdx].so -> oname,
384 objptr(source[srcIdx].so->omod) -> oname);
385 else
386 sprintf(errmsg, "MAIN PASS on source %s (mod %s) ",
387 source [srcIdx].so -> oname,
388 objptr(source[srcIdx].so->omod) -> oname);
389
390 if (emap.port) {
391 sprintf(errmsg2, "via port %s ",
392 photonPorts [portCnt].so -> oname);
393 strcat(errmsg, errmsg2);
394 }
395
396 sprintf(errmsg2, "(%lu partitions)...\n",
397 emap.numPartitions);
398 strcat(errmsg, errmsg2);
399 eputs(errmsg);
400 fflush(stderr);
401 }
402
403 for (emap.partitionCnt = 0;
404 emap.partitionCnt < emap.numPartitions;
405 emap.partitionCnt++) {
406 double partNumEmit;
407 unsigned long partEmitCnt;
408
409 /* Get photon origin within current source partishunn
410 * and build emission map */
411 photonOrigin [emap.src -> so -> otype] (&emap);
412 initPhotonEmission(&emap, pdfSamples);
413
414 /* Number of photons to emit from ziss partishunn;
415 * scale according to its normalised contribushunn to
416 * the emitted source flux */
417 partNumEmit = srcNumEmit * colorAvg(emap.partFlux) /
418 srcFlux [srcIdx];
419 partEmitCnt = (unsigned long)partNumEmit;
420
421 /* Probabilistically account for fractional photons */
422 if (pmapRandom(cntState) < partNumEmit - partEmitCnt)
423 partEmitCnt++;
424
425 /* Integer counter avoids FP rounding errors */
426 while (partEmitCnt--) {
427 RAY photonRay;
428
429 /* Emit photon according to PDF (if any), allocate
430 * associated primary ray, and trace through scene
431 * until absorbed/leaked */
432 emitPhoton(&emap, &photonRay);
433 addPhotonPrimary(pm, &photonRay);
434 tracePhoton(&photonRay);
435
436 /* Record progress */
437 repProgress++;
438
439 if (photonRepTime > 0 &&
440 time(NULL) >= repLastTime + photonRepTime)
441 pmapDistribReport();
442 #ifdef SIGCONT
443 else signal(SIGCONT, pmapDistribReport);
444 #endif
445 }
446 }
447
448 portCnt++;
449 } while (portCnt < numPhotonPorts);
450
451 if (pm -> heapEnd == srcNumDistrib)
452 /* Double preDistrib in case no photons were stored
453 * for this source and redo pass 1 */
454 preDistrib *= 2;
455 else {
456 /* Now do pass 2 */
457 passCnt++;
458 if (photonRepTime)
459 eputs("\n");
460 }
461 } while (passCnt < 2);
462
463 /* Flux per photon emitted from this source; repProgress is the
464 * number of emitted photons after both passes */
465 srcFlux [srcIdx] = repProgress ? srcFlux [srcIdx] / repProgress
466 : 0;
467 }
468 }
469
470 /* ================================================================
471 * POST-DISTRIBUTION - Set photon flux and build kd-tree, etc.
472 * ================================================================ */
473 #ifdef SIGCONT
474 signal(SIGCONT, SIG_DFL);
475 #endif
476 free(emap.samples);
477
478 if (!pm -> heapEnd)
479 error(USER, "empty photon map");
480
481 /* Check for valid primary photon rays */
482 if (!pm -> primary)
483 error(INTERNAL, "no primary rays in contribution photon map");
484
485 if (pm -> primary [pm -> primaryEnd].srcIdx < 0)
486 /* Last primary ray is unused, so decrement counter */
487 pm -> primaryEnd--;
488
489 if (photonRepTime) {
490 eputs("\nBuilding contrib photon heap...\n");
491 fflush(stderr);
492 }
493
494 balancePhotons(pm, srcFlux);
495 }