-
Notifications
You must be signed in to change notification settings - Fork 4
/
Copy pathrecursive_path.cpp
1586 lines (1276 loc) · 57.2 KB
/
recursive_path.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/*
This file is part of Mitsuba, a physically based rendering system.
Copyright (c) 2007-2014 by Wenzel Jakob and others.
Mitsuba is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License Version 3
as published by the Free Software Foundation.
Mitsuba is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include <OpenImageDenoise/oidn.hpp>
#include <mitsuba/render/renderproc.h>
#include <mitsuba/render/scene.h>
#include <mitsuba/core/plugin.h>
#include <mitsuba/core/statistics.h>
#include <array>
#include <atomic>
#include <chrono>
#include <fstream>
#include <functional>
#include <iomanip>
#include <sstream>
#include <mutex>
#include "octtree.h"
/// we support outputting several AOVs that can be helpful for research and debugging.
/// since they are computationally expensive, we disable them by default.
/// uncomment the following line to enable outputting AOVs:
//#define EARS_INCLUDE_AOVS
#include "recursive_path_aovs.h"
MTS_NAMESPACE_BEGIN
thread_local StatsRecursiveImageBlockCache *StatsRecursiveImageBlockCache::instance = nullptr;
thread_local StatsRecursiveDescriptorCache *StatsRecursiveDescriptorCache::instance = nullptr;
thread_local StatsRecursiveValuesCache *StatsRecursiveValuesCache::instance = nullptr;
/**
* Helper class to build averages that discared a given amount of outliers.
* Used for our image variance estimate.
*/
class OutlierRejectedAverage {
public:
struct Sample {
Spectrum secondMoment;
Float cost;
Sample()
: secondMoment(Spectrum(0.f)), cost(0) {}
Sample(const Spectrum &sm, Float cost)
: secondMoment(sm), cost(cost) {}
void operator+=(const Sample &other) {
secondMoment += other.secondMoment;
cost += other.cost;
}
void operator-=(const Sample &other) {
secondMoment -= other.secondMoment;
cost -= other.cost;
}
Sample operator-(const Sample &other) const {
Sample s = *this;
s -= other;
return s;
}
Sample operator/(Float weight) const {
return Sample {
secondMoment / weight,
cost / weight
};
}
bool operator>=(const Sample &other) const {
return secondMoment.average() >= other.secondMoment.average();
}
};
/**
* Resizes the history buffer to account for up to \c length outliers.
*/
void resize(int length) {
m_length = length;
m_history.resize(length);
reset();
}
/**
* Resets all statistics, including outlier history and current average.
*/
void reset() {
m_index = 0;
m_knownMinimum = Sample();
m_accumulation = Sample();
m_weight = 0;
m_outlierAccumulation = Sample();
m_outlierWeight = 0;
}
/**
* Returns whether a lower bound can be given on what will definitely not count as outlier.
*/
bool hasOutlierLowerBound() const {
return m_length > 0 && m_index >= m_length;
}
/**
* Returns the lower bound of what will definitely count as outlier.
* Useful if multiple \c OutlierRejectedAverage from different threads will be combined.
*/
Sample outlierLowerBound() const {
return m_history[m_index - 1];
}
/**
* Sets a manual lower bound of what will count as outlier.
* This avoids wasting time on adding samples to the outlier history that are known to be less significant
* than outliers that have already been collected by other instances of \c OutlierRejectedAverage that
* will eventually be merged.
*/
void setRemoteOutlierLowerBound(const Sample &minimum) {
m_knownMinimum = minimum;
}
/**
* Records one sample.
*/
void operator+=(Sample sample) {
m_weight += 1;
m_accumulation += sample;
if (m_knownMinimum >= sample) {
return;
}
int insertionPoint = m_index;
while (insertionPoint > 0 && sample >= m_history[insertionPoint - 1]) {
if (insertionPoint < m_length) {
m_history[insertionPoint] = m_history[insertionPoint - 1];
}
insertionPoint--;
}
if (insertionPoint < m_length) {
m_history[insertionPoint] = sample;
if (m_index < m_length) {
++m_index;
}
}
}
/**
* Merges the statistics of another \c OutlierRejectedAverage into this instance.
*/
void operator+=(const OutlierRejectedAverage &other) {
int m_writeIndex = m_index + other.m_index;
int m_readIndexLocal = m_index - 1;
int m_readIndexOther = other.m_index - 1;
while (m_writeIndex > 0) {
Sample sample;
if (m_readIndexOther < 0 || (m_readIndexLocal >= 0 && other.m_history[m_readIndexOther] >= m_history[m_readIndexLocal])) {
/// we take the local sample next
sample = m_history[m_readIndexLocal--];
} else {
/// we take the other sample next
sample = other.m_history[m_readIndexOther--];
}
if (--m_writeIndex < m_length) {
m_history[m_writeIndex] = sample;
}
}
m_index = std::min(m_index + other.m_index, m_length);
m_weight += other.m_weight;
m_accumulation += other.m_accumulation;
}
void dump() const {
std::cout << m_index << " vs " << m_length << std::endl;
for (int i = 0; i < m_index; ++i)
std::cout << m_history[i].secondMoment.average() << std::endl;
}
void computeOutlierContribution() {
for (int i = 0; i < m_index; ++i) {
m_outlierAccumulation += m_history[i];
}
m_outlierWeight += m_index;
/// reset ourselves
m_index = 0;
}
Sample average() const {
if (m_index > 0) {
SLog(EWarn, "There are some outliers that have not yet been removed. Did you forget to call computeOutlierContribution()?");
}
return (m_accumulation - m_outlierAccumulation) / (m_weight - m_outlierWeight);
}
Sample averageWithoutRejection() const {
return m_accumulation / m_weight;
}
long weight() const {
return m_weight;
}
private:
long m_weight;
int m_index;
int m_length;
Sample m_accumulation;
Sample m_knownMinimum;
std::vector<Sample> m_history;
Sample m_outlierAccumulation;
long m_outlierWeight;
};
/**
* Renders albedo and normals auxiliaries used for denoising the pixel estimate used by ADRRS and our method.
*/
class DenoisingAuxilariesIntegrator : public SamplingIntegrator {
public:
enum EField {
EShadingNormal,
EAlbedo,
};
DenoisingAuxilariesIntegrator()
: SamplingIntegrator(Properties()) {
}
Spectrum Li(const RayDifferential &ray, RadianceQueryRecord &rRec) const {
Spectrum result(0.f);
if (!rRec.rayIntersect(ray))
return result;
Intersection &its = rRec.its;
switch (m_field) {
case EShadingNormal:
result.fromLinearRGB(its.shFrame.n.x, its.shFrame.n.y, its.shFrame.n.z);
break;
case EAlbedo:
result = its.shape->getBSDF()->getDiffuseReflectance(its);
break;
default:
Log(EError, "Internal error!");
}
return result;
}
std::string toString() const {
return "DenoisingAuxilariesIntegrator[]";
}
EField m_field;
};
class MIRecursivePathTracer : public MonteCarloIntegrator {
private:
struct RRSMethod {
enum {
ENone,
EClassic,
EGWTW,
EADRRS,
EEARS,
} technique;
Float splittingMin;
Float splittingMax;
int rrDepth;
bool useAbsoluteThroughput;
RRSMethod() {
technique = ENone;
splittingMin = 1;
splittingMax = 1;
rrDepth = 1;
useAbsoluteThroughput = true;
}
RRSMethod(const Properties &props) {
/// parse parameters
splittingMin = props.getFloat("splittingMin", 0.05f);
splittingMax = props.getFloat("splittingMax", 20);
rrDepth = props.getInteger("rrDepth", 5);
/// parse desired modifiers
std::string rrsStr = props.getString("rrsStrategy", "noRR");
if ((useAbsoluteThroughput = rrsStr.back() == 'A')) {
rrsStr.pop_back();
}
if (rrsStr.back() == 'S') {
rrsStr.pop_back();
} else if (splittingMax > 1) {
Log(EWarn, "Changing maximum splitting factor to 1 since splitting was not explicitly allowed");
splittingMax = 1;
}
/// parse desired technique
if (rrsStr == "noRR") technique = ENone; else
if (rrsStr == "classicRR") technique = EClassic; else
if (rrsStr == "ADRR") technique = EADRRS; else
if (rrsStr == "EAR") technique = EEARS; else
if (rrsStr == "GWTWRR") technique = EGWTW; else {
Log(EError, "Invalid RRS technique specified: %s", rrsStr.c_str());
}
if (technique == EEARS && rrDepth != 1)
Log(EWarn, "EARS should ideally be used with rrDepth 1");
if (technique == EADRRS && rrDepth != 2)
Log(EWarn, "ADRRS should ideally be used with rrDepth 2");
}
static RRSMethod Classic() {
RRSMethod rrs;
rrs.technique = EClassic;
rrs.splittingMin = 0;
rrs.splittingMax = 0.95f;
rrs.rrDepth = 5;
rrs.useAbsoluteThroughput = true;
return rrs;
}
std::string getName() const {
std::string suffix = "";
if (splittingMax > 1) suffix += "S";
if (useAbsoluteThroughput) suffix += "A";
switch (technique) {
case ENone: return "noRR";
case EClassic: return "classicRR" + suffix;
case EGWTW: return "GWTWRR" + suffix;
case EADRRS: return "ADRR" + suffix;
case EEARS: return "EAR" + suffix;
default: return "ERROR";
}
}
Float evaluate(
const Octtree::SamplingNode *samplingNode,
Float imageEarsFactor,
const Spectrum &albedo,
const Spectrum &throughput,
Float shininess,
bool bsdfHasSmoothComponent,
int depth
) const {
if (depth < rrDepth) {
/// do not perform RR or splitting at this depth.
return 1;
}
switch (technique) {
case ENone: {
/// the simplest mode of all. perform no splitting and no RR.
return clamp(1);
}
case EClassic: {
/// Classic RR(S) based on throughput weight
if (albedo.isZero())
/// avoid bias for materials that might report their reflectance incorrectly
return clamp(0.1f);
return clamp((throughput * albedo).average());
}
case EGWTW: {
/// "Go with the Winners"
const Float Vr = 1.0;
const Float Vv = splittingMax * splittingMax - 1.0;
return clamp((throughput * albedo).average() * std::sqrt(Vr + Vv / std::pow(shininess + 1, 2)));
}
case EADRRS: {
/// "Adjoint-driven Russian Roulette and Splitting"
const Spectrum LiEstimate = samplingNode->lrEstimate;
if (bsdfHasSmoothComponent && LiEstimate.max() > 0) {
return clamp(weightWindow((throughput * LiEstimate).average()));
} else {
return clamp(1);
}
}
case EEARS: {
/// "Efficiency-Aware Russian Roulette and Splitting"
if (bsdfHasSmoothComponent) {
const Float splittingFactorS = std::sqrt( (throughput * throughput * samplingNode->earsFactorS).average() ) * imageEarsFactor;
const Float splittingFactorR = std::sqrt( (throughput * throughput * samplingNode->earsFactorR).average() ) * imageEarsFactor;
if (splittingFactorR > 1) {
if (splittingFactorS < 1) {
/// second moment and variance disagree on whether to split or RR, resort to doing nothing.
return clamp(1);
} else {
/// use variance only if both modes recommend splitting.
return clamp(splittingFactorS);
}
} else {
/// use second moment only if it recommends RR.
return clamp(splittingFactorR);
}
} else {
return clamp(1);
}
}
}
/// make gcc happy
return 0;
}
bool needsTrainingPhase() const {
switch (technique) {
case ENone: return false;
case EClassic: return false;
case EGWTW: return false;
case EADRRS: return true;
case EEARS: return true;
}
/// make gcc happy
return false;
}
bool performsInvVarWeighting() const {
return needsTrainingPhase();
}
bool needsPixelEstimate() const {
return useAbsoluteThroughput == false;
}
private:
Float clamp(Float splittingFactor) const {
/// not using std::clamp here since that's C++17
splittingFactor = std::min(splittingFactor, splittingMax);
splittingFactor = std::max(splittingFactor, splittingMin);
return splittingFactor;
}
Float weightWindow(Float splittingFactor, Float weightWindowSize = 5) const {
const float dminus = 2 / (1 + weightWindowSize);
const float dplus = dminus * weightWindowSize;
if (splittingFactor < dminus) {
/// russian roulette
return splittingFactor / dminus;
} else if (splittingFactor > dplus) {
/// splitting
return splittingFactor / dplus;
} else {
/// within weight window
return 1;
}
}
};
struct LiInput {
Spectrum weight;
Spectrum absoluteWeight; /// only relevant for AOVs
RayDifferential ray;
RadianceQueryRecord rRec;
bool scattered { false };
Float eta { 1.f };
};
struct LiOutput {
Spectrum reflected { 0.f };
Spectrum emitted { 0.f };
Float cost { 0.f };
int numSamples { 0 };
Float depthAcc { 0.f };
Float depthWeight { 0.f };
void markAsLeaf(int depth) {
depthAcc = depth;
depthWeight = 1;
}
Float averagePathLength() const {
return depthWeight > 0 ? depthAcc / depthWeight : 0;
}
Float numberOfPaths() const {
return depthWeight;
}
Spectrum totalContribution() const {
return reflected + emitted;
}
};
public:
/// the cost of ray tracing + direct illumination sample (in seconds)
static constexpr Float COST_NEE = 0.3e-7;
/// the cost of ray tracing + BSDF/camera sample (in seconds)
static constexpr Float COST_BSDF = 0.3e-7;
MIRecursivePathTracer(const Properties &props)
: MonteCarloIntegrator(props) {
m_oidnDevice = oidn::newDevice();
m_oidnDevice.commit();
cache.setMaximumMemory(long(24)*1024*1024); /// 24 MiB
m_renderingRRSMethod = RRSMethod(props);
m_budget = props.getFloat("budget", 30.0f);
m_useIncrementalTraining = props.getBoolean("useIncrementalTraining", true);
m_saveTrainingFrames = props.getBoolean("saveTrainingFrames", false);
m_outlierRejection = props.getInteger("outlierRejection", 10);
m_imageStatistics.setOutlierRejectionCount(m_outlierRejection);
for (const auto &name : props.getPropertyNames()) {
Log(EInfo, "%s: %s", name.c_str(), props.getAsString(name).c_str());
}
}
ref<BlockedRenderProcess> renderPass(Scene *scene,
RenderQueue *queue, const RenderJob *job,
int sceneResID, int sensorResID, int samplerResID, int integratorResID) {
/* This is a sampling-based integrator - parallelize */
ref<BlockedRenderProcess> proc = new BlockedRenderProcess(job,
queue, scene->getBlockSize());
proc->disableProgress();
proc->bindResource("integrator", integratorResID);
proc->bindResource("scene", sceneResID);
proc->bindResource("sensor", sensorResID);
proc->bindResource("sampler", samplerResID);
scene->bindUsedResources(proc);
bindUsedResources(proc);
return proc;
}
bool renderIterationTime(Float until, int &passesRenderedLocal, Scene *scene, RenderQueue *queue, const RenderJob *job,
int sceneResID, int sensorResID, int samplerResID, int integratorResID) {
ref<Scheduler> sched = Scheduler::getInstance();
ref<Sensor> sensor = static_cast<Sensor *>(sched->getResource(sensorResID));
ref<Film> film = sensor->getFilm();
Log(EInfo, "ITERATION %d, until %.1f seconds (%s)", m_iteration, until, m_currentRRSMethod.getName().c_str());
passesRenderedLocal = 0;
bool result = true;
while (true) {
ref<BlockedRenderProcess> process = renderPass(scene, queue, job, sceneResID, sensorResID, samplerResID, integratorResID);
sched->schedule(process);
sched->wait(process);
m_imageStatistics.applyOutlierRejection();
++passesRenderedLocal;
++m_passesRenderedGlobal;
const Float progress = computeElapsedSeconds(m_startTime);
m_progress->update(progress);
if (progress > until) {
break;
}
if (process->getReturnStatus() != ParallelProcess::ESuccess) {
result = false;
break;
}
}
Log(EInfo, " %.2f seconds elapsed, passes this iteration: %d, total passes: %d",
computeElapsedSeconds(m_startTime), passesRenderedLocal, m_passesRenderedGlobal);
return result;
}
static Float computeElapsedSeconds(std::chrono::steady_clock::time_point start) {
auto current = std::chrono::steady_clock::now();
auto ms = std::chrono::duration_cast<std::chrono::milliseconds>(current - start);
return (Float)ms.count() / 1000;
}
bool renderTime(Scene *scene, RenderQueue *queue, const RenderJob *job,
int sceneResID, int sensorResID, int samplerResID, int integratorResID) {
ref<Scheduler> sched = Scheduler::getInstance();
ref<Sensor> sensor = static_cast<Sensor *>(sched->getResource(sensorResID));
ref<Film> film = sensor->getFilm();
m_progress = std::unique_ptr<ProgressReporter>(new ProgressReporter("Rendering", (int)m_budget, job));
Float iterationTime = 1;
cache.configuration.leafDecay = m_useIncrementalTraining ? 1 : 0;
int spp;
Float until = 0;
for (m_iteration = 0;; m_iteration++) {
const Float timeBeforeIter = computeElapsedSeconds(m_startTime);
if (timeBeforeIter >= m_budget) {
/// note that we always do at least one sample per pixel per training iteration,
/// which can sometimes be significantly longer than the budget for that iteration.
/// this means we can exhaust the training budget before all iterations have finished
/// (typically due to excessive amounts of splitting)
break;
}
film->clear();
#ifdef EARS_INCLUDE_AOVS
m_statsImages->clear();
#endif
/// don't use learning based methods unless caches have somewhat converged
const bool isPretraining = m_iteration < 3;
m_currentRRSMethod = isPretraining ? RRSMethod::Classic() : m_renderingRRSMethod;
until += iterationTime;
if (until > m_budget - iterationTime) {
/// since the budget would be exhausted in the next iteration anyway, we exhaust it fully now.
/// this way we can avoid final iterations that are shorter than "iterationTime" and are not worth the overhead.
until = m_budget;
}
if (!renderIterationTime(until, spp, scene, queue, job, sceneResID, sensorResID, samplerResID, integratorResID)) {
return false;
}
updateCaches();
updateImageStatistics(computeElapsedSeconds(m_startTime) - timeBeforeIter);
const bool hasVarianceEstimate = m_iteration > 0 || !m_needsPixelEstimate;
m_finalImage.add(
film, spp,
m_renderingRRSMethod.performsInvVarWeighting() ?
(hasVarianceEstimate ? m_imageStatistics.squareError().average() : 0) :
1
);
computePixelEstimate(film);
if (m_iteration % 8 == 7) {
/// double the duration of a render pass every 8 passes.
iterationTime *= 2;
}
if (m_saveTrainingFrames) {
ref<Bitmap> bitmap = new Bitmap(Bitmap::ESpectrum, Bitmap::EFloat32, film->getSize());
m_finalImage.develop(bitmap);
fs::path path = scene->getDestinationFile();
path = path.parent_path() / (path.leaf().string() + "__train-" + std::to_string(m_iteration) + ".exr");
Log(EInfo, "Saving training frame to %s", path.c_str());
bitmap->write(path);
}
}
return true;
}
bool render(Scene *scene, RenderQueue *queue, const RenderJob *job,
int sceneResID, int sensorResID, int samplerResID) {
ref<Scheduler> sched = Scheduler::getInstance();
size_t nCores = sched->getCoreCount();
ref<Sensor> sensor = static_cast<Sensor *>(sched->getResource(sensorResID));
ref<Film> film = sensor->getFilm();
#ifdef EARS_INCLUDE_AOVS
auto properties = Properties("hdrfilm");
properties.setInteger("width", film->getSize().x);
properties.setInteger("height", film->getSize().y);
{
/// debug film with additional channels
StatsRecursiveDescriptor statsDesc;
auto properties = Properties(film->getProperties());
properties.setString("pixelFormat", statsDesc.types);
properties.setString("channelNames", statsDesc.names);
std::cout << properties.toString() << std::endl;
auto rfilter = film->getReconstructionFilter();
m_debugFilm = static_cast<Film*>(PluginManager::getInstance()->createObject(MTS_CLASS(Film), properties));
m_debugFilm->addChild(rfilter);
m_debugFilm->configure();
m_statsImages.reset(new StatsRecursiveImageBlocks([&]() {
return new ImageBlock(Bitmap::ESpectrumAlphaWeight, film->getCropSize());
}));
m_debugImage = new ImageBlock(Bitmap::EMultiSpectrumAlphaWeight, film->getCropSize(), NULL,
statsDesc.size * SPECTRUM_SAMPLES + 2
);
}
#endif
m_needsPixelEstimate = m_renderingRRSMethod.needsPixelEstimate();
m_needsCaches = m_renderingRRSMethod.needsTrainingPhase();
renderDenoisingAuxiliaries(scene, queue, job, sceneResID, sensorResID);
m_startTime = std::chrono::steady_clock::now();
Log(EInfo, "Starting render job (%ix%i, " SIZE_T_FMT " %s, " SSE_STR ") ..", film->getCropSize().x, film->getCropSize().y, nCores, nCores == 1 ? "core" : "cores");
Thread::initializeOpenMP(nCores);
int integratorResID = sched->registerResource(this);
bool result = true;
m_passesRenderedGlobal = 0;
m_finalImage.clear();
result = renderTime(scene, queue, job, sceneResID, sensorResID, samplerResID, integratorResID);
Vector2i size = film->getSize();
ref<Bitmap> image = new Bitmap(Bitmap::EPixelFormat::ESpectrum, Bitmap::EComponentFormat::EFloat32, size);
film->develop(Point2i(0, 0), size, Point2i(0, 0), image);
#ifdef EARS_INCLUDE_AOVS
auto statsBitmaps = m_statsImages->getBitmaps();
Float* debugImage = m_debugImage->getBitmap()->getFloatData();
for (int y = 0; y < size.y; ++y)
for (int x = 0; x < size.x; ++x) {
Point2i pos = Point2i(x, y);
Spectrum pixel = image->getPixel(pos);
/// write out debug channels
for (int i = 0; i < SPECTRUM_SAMPLES; ++i) *(debugImage++) = pixel[i];
for (auto &b : statsBitmaps) {
Spectrum v = b->getPixel(pos);
for (int i = 0; i < SPECTRUM_SAMPLES; ++i) *(debugImage++) = v[i];
}
*(debugImage++) = 1.0f;
*(debugImage++) = 1.0f;
}
m_debugFilm->setBitmap(m_debugImage->getBitmap());
{
/// output debug image
std::string suffix = "-dbg-" + m_renderingRRSMethod.getName() + "-" + std::to_string(m_passesRenderedGlobal) + "spp";
fs::path destPath = scene->getDestinationFile();
fs::path debugPath = destPath.parent_path() / (
destPath.leaf().string()
+ suffix
+ ".exr"
);
m_debugFilm->setDestinationFile(debugPath, 0);
m_debugFilm->develop(scene, 0.0f);
}
#endif
ref<Bitmap> finalBitmap = new Bitmap(Bitmap::EPixelFormat::ESpectrum, Bitmap::EComponentFormat::EFloat32, film->getSize());
m_finalImage.develop(finalBitmap.get());
film->setBitmap(finalBitmap);
sched->unregisterResource(integratorResID);
m_progress = nullptr;
return result;
}
void renderBlock(const Scene *scene, const Sensor *sensor,
Sampler *sampler, ImageBlock *block, const bool &stop,
const std::vector< TPoint2<uint8_t> > &points) const {
static thread_local OutlierRejectedAverage blockStatistics;
blockStatistics.resize(m_outlierRejection);
if (m_imageStatistics.hasOutlierLowerBound()) {
blockStatistics.setRemoteOutlierLowerBound(m_imageStatistics.outlierLowerBound());
}
bool needsApertureSample = sensor->needsApertureSample();
bool needsTimeSample = sensor->needsTimeSample();
RadianceQueryRecord rRec(scene, sampler);
Point2 apertureSample(0.5f);
Float timeSample = 0.5f;
RayDifferential sensorRay;
block->clear();
#ifdef EARS_INCLUDE_AOVS
static thread_local StatsRecursiveImageBlocks blocks([&]() {
auto b = new ImageBlock(block->getPixelFormat(), block->getSize(), block->getReconstructionFilter());
return b;
});
for (auto &b : blocks.blocks) {
b->setOffset(block->getOffset());
b->clear();
}
#endif
StatsRecursiveValues stats;
uint32_t queryType = RadianceQueryRecord::ESensorRay;
if (!sensor->getFilm()->hasAlpha()) // Don't compute an alpha channel if we don't have to
queryType &= ~RadianceQueryRecord::EOpacity;
Float depthAcc = 0;
Float depthWeight = 0;
Float primarySplit = 0;
Float samplesTaken = 0;
for (size_t i = 0; i < points.size(); ++i) {
Point2i offset = Point2i(points[i]) + Vector2i(block->getOffset());
//if (stop)
// break;
Spectrum pixelEstimate { 0.5f };
if (m_pixelEstimate.get()) {
pixelEstimate = m_pixelEstimate->getPixel(offset);
}
const Spectrum metricNorm = m_renderingRRSMethod.useAbsoluteThroughput ?
Spectrum { 1.f } :
pixelEstimate + Spectrum { 1e-2 };
const Spectrum expectedContribution = pixelEstimate / metricNorm;
constexpr int sppPerPass = 1;
for (int j = 0; j < sppPerPass; j++) {
stats.reset();
rRec.newQuery(queryType, sensor->getMedium());
Point2 samplePos(Point2(offset) + Vector2(rRec.nextSample2D()));
if (needsApertureSample)
apertureSample = rRec.nextSample2D();
if (needsTimeSample)
timeSample = rRec.nextSample1D();
Spectrum spec = sensor->sampleRayDifferential(
sensorRay, samplePos, apertureSample, timeSample);
LiInput input;
input.absoluteWeight = spec;
input.weight = spec;
input.ray = sensorRay;
input.rRec = rRec;
if (!m_currentRRSMethod.useAbsoluteThroughput)
input.weight /= pixelEstimate + Spectrum { 1e-2 };
LiOutput output = Li(input, stats);
block->put(samplePos, spec * output.totalContribution(), input.rRec.alpha);
sampler->advance();
const Spectrum pixelContribution = (spec / metricNorm) * output.totalContribution();
const Spectrum diff = pixelContribution - expectedContribution;
blockStatistics += OutlierRejectedAverage::Sample {
diff * diff,
output.cost
};
stats.pixelEstimate.add(pixelEstimate);
stats.avgPathLength.add(output.averagePathLength());
stats.numPaths.add(output.numberOfPaths());
stats.cost.add(1e+6 * output.cost);
#ifdef EARS_INCLUDE_AOVS
stats.put(blocks, samplePos, rRec.alpha);
#endif
depthAcc += output.depthAcc;
depthWeight += output.depthWeight;
primarySplit += output.numSamples;
samplesTaken += 1;
}
}
//if (!stop) {
#ifdef EARS_INCLUDE_AOVS
m_statsImages->put(blocks);
#endif
m_imageStatistics += blockStatistics;
m_imageStatistics.splatDepthAcc(depthAcc, depthWeight, primarySplit, samplesTaken);
//}
}
Vector3f mapPointToUnitCube(const Scene *scene, const Point3 &point) const {
AABB aabb = scene->getAABB();
Vector3f size = aabb.getExtents();
Vector3f result = point - aabb.min;
for (int i = 0; i < 3; ++i)
result[i] /= size[i];
return result;
}
Point2 dirToCanonical(const Vector& d) const {
if (!std::isfinite(d.x) || !std::isfinite(d.y) || !std::isfinite(d.z)) {
return {0, 0};
}
const Float cosTheta = std::min(std::max(d.z, -1.0f), 1.0f);
Float phi = std::atan2(d.y, d.x);
while (phi < 0)
phi += 2.0 * M_PI;
return {(cosTheta + 1) / 2, phi / (2 * M_PI)};
}
int mapOutgoingDirectionToHistogramBin(const Vector3f &wo) const {
const Point2 p = dirToCanonical(wo);
const int res = Octtree::HISTOGRAM_RESOLUTION;
const int result =
std::min(int(p.x * res), res - 1) +
std::min(int(p.y * res), res - 1) * res;
return result;
}
Spectrum Li(const RayDifferential &r, RadianceQueryRecord &rRec) const {
Assert(false);
return Spectrum { 0.f };
}
LiOutput Li(LiInput &input, StatsRecursiveValues &stats) const {
LiOutput output;
if (m_maxDepth >= 0 && input.rRec.depth > m_maxDepth) {
// maximum depth reached
output.markAsLeaf(input.rRec.depth);
return output;
}
/* Some aliases and local variables */
RadianceQueryRecord &rRec = input.rRec;
Intersection &its = rRec.its;
const Scene *scene = rRec.scene;
RayDifferential ray(input.ray);
/* Perform the first ray intersection (or ignore if the
intersection has already been provided). */
if (rRec.type & RadianceQueryRecord::EIntersection) {
rRec.rayIntersect(ray);
output.cost += COST_BSDF;
}
if (!its.isValid()) {
/* If no intersection could be found, potentially return
radiance from a environment luminaire if it exists */
if ((rRec.type & RadianceQueryRecord::EEmittedRadiance)
&& (!m_hideEmitters || input.scattered))
output.emitted += scene->evalEnvironment(ray);
stats.emitted.add(rRec.depth-1, input.absoluteWeight * output.emitted, 0);
output.markAsLeaf(rRec.depth);
return output;
}
const BSDF *bsdf = its.getBSDF();
const bool bsdfHasSmoothComponent = bsdf->getType() & BSDF::ESmooth;
/* Possibly include emitted radiance if requested */
if (its.isEmitter() && (rRec.type & RadianceQueryRecord::EEmittedRadiance)
&& (!m_hideEmitters || input.scattered))
output.emitted += its.Le(-ray.d);
/* Include radiance from a subsurface scattering model if requested */
if (its.hasSubsurface() && (rRec.type & RadianceQueryRecord::ESubsurfaceRadiance))
output.emitted += its.LoSub(scene, rRec.sampler, -ray.d, rRec.depth);