forked from NatronGitHub/Natron
-
Notifications
You must be signed in to change notification settings - Fork 0
/
EffectInstanceRenderRoI.cpp
2058 lines (1803 loc) · 102 KB
/
EffectInstanceRenderRoI.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
/* ***** BEGIN LICENSE BLOCK *****
* This file is part of Natron <https://natrongithub.github.io/>,
* (C) 2018-2021 The Natron developers
* (C) 2013-2018 INRIA and Alexandre Gauthier-Foichat
*
* Natron is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* Natron 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 Natron. If not, see <http://www.gnu.org/licenses/gpl-2.0.html>
* ***** END LICENSE BLOCK ***** */
// ***** BEGIN PYTHON BLOCK *****
// from <https://docs.python.org/3/c-api/intro.html#include-files>:
// "Since Python may define some pre-processor definitions which affect the standard headers on some systems, you must include Python.h before any standard headers are included."
#include <Python.h>
// ***** END PYTHON BLOCK *****
#include "EffectInstance.h"
#include "EffectInstancePrivate.h"
#include <map>
#include <sstream>
#include <algorithm> // min, max
#include <fstream>
#include <cassert>
#include <stdexcept>
#include <sstream> // stringstream
#include <boost/scoped_ptr.hpp>
#include <QtCore/QThreadPool>
#include <QtCore/QReadWriteLock>
#include <QtCore/QCoreApplication>
#include <QtConcurrentMap> // QtCore on Qt4, QtConcurrent on Qt5
#include <QtConcurrentRun> // QtCore on Qt4, QtConcurrent on Qt5
#if !defined(SBK_RUN) && !defined(Q_MOC_RUN)
GCC_DIAG_UNUSED_LOCAL_TYPEDEFS_OFF
// /usr/local/include/boost/bind/arg.hpp:37:9: warning: unused typedef 'boost_static_assert_typedef_37' [-Wunused-local-typedef]
#include <boost/bind/bind.hpp>
GCC_DIAG_UNUSED_LOCAL_TYPEDEFS_ON
#endif
#include "Global/QtCompat.h"
#include "Engine/AppInstance.h"
#include "Engine/AppManager.h"
#include "Engine/BlockingBackgroundRender.h"
#include "Engine/DiskCacheNode.h"
#include "Engine/Cache.h"
#include "Engine/Image.h"
#include "Engine/ImageParams.h"
#include "Engine/KnobFile.h"
#include "Engine/KnobTypes.h"
#include "Engine/Log.h"
#include "Engine/Node.h"
#include "Engine/OfxEffectInstance.h"
#include "Engine/OfxEffectInstance.h"
#include "Engine/OfxImageEffectInstance.h"
#include "Engine/OutputSchedulerThread.h"
#include "Engine/OSGLContext.h"
#include "Engine/GPUContextPool.h"
#include "Engine/PluginMemory.h"
#include "Engine/Project.h"
#include "Engine/RenderStats.h"
#include "Engine/RotoContext.h"
#include "Engine/RotoDrawableItem.h"
#include "Engine/Settings.h"
#include "Engine/Timer.h"
#include "Engine/Transform.h"
#include "Engine/ThreadPool.h"
#include "Engine/ViewIdx.h"
#include "Engine/ViewerInstance.h"
//#define NATRON_ALWAYS_ALLOCATE_FULL_IMAGE_BOUNDS
using namespace boost::placeholders;
NATRON_NAMESPACE_ENTER
/*
* @brief Split all rects to render in smaller rects and check if each one of them is identity.
* For identity rectangles, we just call renderRoI again on the identity input in the tiledRenderingFunctor.
* For non-identity rectangles, compute the bounding box of them and render it
*/
static void
optimizeRectsToRender(EffectInstance* self,
const RectI & inputsRoDIntersection,
const std::list<RectI> & rectsToRender,
const double time,
const ViewIdx view,
const RenderScale & renderMappedScale,
std::list<EffectInstance::RectToRender>* finalRectsToRender)
{
for (std::list<RectI>::const_iterator it = rectsToRender.begin(); it != rectsToRender.end(); ++it) {
std::vector<RectI> splits = it->splitIntoSmallerRects(0);
EffectInstance::RectToRender nonIdentityRect;
nonIdentityRect.isIdentity = false;
nonIdentityRect.identityTime = 0;
nonIdentityRect.rect.x1 = INT_MAX;
nonIdentityRect.rect.x2 = INT_MIN;
nonIdentityRect.rect.y1 = INT_MAX;
nonIdentityRect.rect.y2 = INT_MIN;
bool nonIdentityRectSet = false;
for (std::size_t i = 0; i < splits.size(); ++i) {
double identityInputTime = 0.;
int identityInputNb = -1;
bool identity = false;
ViewIdx inputIdentityView(view);
if ( !splits[i].intersects(inputsRoDIntersection) ) {
identity = self->isIdentity_public(false, 0, time, renderMappedScale, splits[i], view, &identityInputTime, &inputIdentityView, &identityInputNb);
} else {
identity = false;
}
if (identity) {
EffectInstance::RectToRender r;
r.isIdentity = true;
// Walk along the identity branch until we find the non identity input, or NULL in we case we will
// just render black and transparent
EffectInstancePtr identityInput = self->getInput(identityInputNb);
if (identityInput) {
for (;; ) {
identity = identityInput->isIdentity_public(false, 0, time, renderMappedScale, splits[i], view, &identityInputTime, &inputIdentityView, &identityInputNb);
if ( !identity || (identityInputNb == -2) ) {
break;
}
EffectInstancePtr subIdentityInput = identityInput->getInput(identityInputNb);
if (subIdentityInput == identityInput) {
break;
}
identityInput = subIdentityInput;
if (!subIdentityInput) {
break;
}
}
}
r.identityInput = identityInput;
r.identityTime = identityInputTime;
r.identityView = inputIdentityView;
r.rect = splits[i];
finalRectsToRender->push_back(r);
} else {
nonIdentityRectSet = true;
nonIdentityRect.rect.x1 = std::min(splits[i].x1, nonIdentityRect.rect.x1);
nonIdentityRect.rect.x2 = std::max(splits[i].x2, nonIdentityRect.rect.x2);
nonIdentityRect.rect.y1 = std::min(splits[i].y1, nonIdentityRect.rect.y1);
nonIdentityRect.rect.y2 = std::max(splits[i].y2, nonIdentityRect.rect.y2);
}
}
if (nonIdentityRectSet) {
finalRectsToRender->push_back(nonIdentityRect);
}
}
} // optimizeRectsToRender
ImagePtr
EffectInstance::convertPlanesFormatsIfNeeded(const AppInstancePtr& app,
const ImagePtr& inputImage,
const RectI& roi,
const ImagePlaneDesc& targetComponents,
ImageBitDepthEnum targetDepth,
bool useAlpha0ForRGBToRGBAConversion,
ImagePremultiplicationEnum outputPremult,
int channelForAlpha)
{
// Do not do any conversion for OpenGL textures, OpenGL is managing it for us.
if (inputImage->getStorageMode() == eStorageModeGLTex) {
return inputImage;
}
bool imageConversionNeeded = ( /*!targetIsMultiPlanar &&*/ targetComponents.getNumComponents() != inputImage->getComponents().getNumComponents() ) || targetDepth != inputImage->getBitDepth();
if (!imageConversionNeeded) {
return inputImage;
} else {
/**
* Lock the downscaled image so it cannot be resized while creating the temp image and calling convertToFormat.
**/
Image::ReadAccess acc = inputImage->getReadRights();
RectI bounds = inputImage->getBounds();
#if 0 //def BOOST_NO_CXX11_VARIADIC_TEMPLATES
ImagePtr tmp( new Image(targetComponents,
inputImage->getRoD(),
bounds,
inputImage->getMipMapLevel(),
inputImage->getPixelAspectRatio(),
targetDepth,
inputImage->getPremultiplication(),
inputImage->getFieldingOrder(),
false) );
#else
ImagePtr tmp = boost::make_shared<Image>(targetComponents,
inputImage->getRoD(),
bounds,
inputImage->getMipMapLevel(),
inputImage->getPixelAspectRatio(),
targetDepth,
inputImage->getPremultiplication(),
inputImage->getFieldingOrder(),
false);
#endif
tmp->setKey(inputImage->getKey());
RectI clippedRoi;
roi.intersect(bounds, &clippedRoi);
bool unPremultIfNeeded = outputPremult == eImagePremultiplicationPremultiplied && inputImage->getComponentsCount() == 4 && tmp->getComponentsCount() == 3;
if (useAlpha0ForRGBToRGBAConversion) {
inputImage->convertToFormatAlpha0( clippedRoi,
app->getDefaultColorSpaceForBitDepth( inputImage->getBitDepth() ),
app->getDefaultColorSpaceForBitDepth(targetDepth),
channelForAlpha, false, unPremultIfNeeded, tmp.get() );
} else {
inputImage->convertToFormat( clippedRoi,
app->getDefaultColorSpaceForBitDepth( inputImage->getBitDepth() ),
app->getDefaultColorSpaceForBitDepth(targetDepth),
channelForAlpha, false, unPremultIfNeeded, tmp.get() );
}
return tmp;
}
}
#if NATRON_ENABLE_TRIMAP
class ImageBitMapMarker_RAII
{
std::map<ImagePlaneDesc, EffectInstance::PlaneToRender> _image;
RectI _roi;
EffectInstance* _effect;
std::list<RectI> _rectsToRender;
bool _isBeingRenderedElseWhere;
bool _isValid;
bool _renderFullScale;
public:
ImageBitMapMarker_RAII(const std::map<ImagePlaneDesc, EffectInstance::PlaneToRender>& image,
bool renderFullScale,
const RectI& roi,
EffectInstance* effect)
: _image(image)
, _roi(roi)
, _effect(effect)
, _rectsToRender()
, _isBeingRenderedElseWhere(false)
, _isValid(true)
, _renderFullScale(renderFullScale)
{
for (std::map<ImagePlaneDesc,EffectInstance::PlaneToRender>::const_iterator it = _image.begin(); it != _image.end(); ++it) {
ImagePtr cacheImage;
if (!renderFullScale) {
cacheImage = it->second.downscaleImage;
} else {
cacheImage = it->second.fullscaleImage;
}
if (cacheImage && cacheImage->usesBitMap()) {
_effect->_imp->markImageAsBeingRendered(cacheImage, roi, &_rectsToRender, &_isBeingRenderedElseWhere);
}
}
}
const std::list<RectI>& getRectsToRender() const
{
return _rectsToRender;
}
void invalidate()
{
_isValid = false;
}
void waitForPendingRegions()
{
if (!_isBeingRenderedElseWhere || !_isValid) {
return;
}
for (std::map<ImagePlaneDesc,EffectInstance::PlaneToRender>::const_iterator it = _image.begin(); it != _image.end(); ++it) {
ImagePtr cacheImage;
if (!_renderFullScale) {
cacheImage = it->second.downscaleImage;
} else {
cacheImage = it->second.fullscaleImage;
}
if (cacheImage && cacheImage->usesBitMap()) {
if (!_effect->_imp->waitForImageBeingRenderedElsewhere(_roi, cacheImage)) {
_isValid = false;
}
}
}
}
~ImageBitMapMarker_RAII()
{
for (std::map<ImagePlaneDesc,EffectInstance::PlaneToRender>::const_iterator it = _image.begin(); it != _image.end(); ++it) {
ImagePtr cacheImage;
if (!_renderFullScale) {
cacheImage = it->second.downscaleImage;
} else {
cacheImage = it->second.fullscaleImage;
}
if (cacheImage && cacheImage->usesBitMap()) {
_effect->_imp->unmarkImageAsBeingRendered(cacheImage, _rectsToRender, !_isValid);
}
}
}
};
#endif // #if NATRON_ENABLE_TRIMAP
EffectInstance::RenderRoIRetCode
EffectInstance::renderRoI(const RenderRoIArgs & args,
std::map<ImagePlaneDesc, ImagePtr>* outputPlanes)
{
//Do nothing if no components were requested
if ( args.components.empty() ) {
qDebug() << getScriptName_mt_safe().c_str() << "renderRoi: Early bail-out components requested empty";
return eRenderRoIRetCodeOk;
}
if ( args.roi.isNull() ) {
qDebug() << getScriptName_mt_safe().c_str() << "renderRoi: Early bail-out ROI requested empty ";
return eRenderRoIRetCodeOk;
}
// Make sure this call is not made recursively from getImage on a render clone on which we are already calling renderRoI.
// If so, forward the call to the main instance
if (_imp->mainInstance) {
return _imp->mainInstance->renderRoI(args, outputPlanes);
}
//Create the TLS data for this node if it did not exist yet
EffectTLSDataPtr tls = _imp->tlsData->getOrCreateTLSData();
assert(tls);
OSGLContextPtr glContext;
AbortableRenderInfoPtr abortInfo;
ParallelRenderArgsPtr frameArgs;
if ( tls->frameArgs.empty() ) {
qDebug() << QThread::currentThread() << "[BUG]:" << getScriptName_mt_safe().c_str() << "Thread-storage for the render of the frame was not set.";
frameArgs = boost::make_shared<ParallelRenderArgs>();
{
NodesWList outputs;
getNode()->getOutputs_mt_safe(outputs);
frameArgs->visitsCount = (int)outputs.size();
}
frameArgs->time = args.time;
frameArgs->nodeHash = getHash();
frameArgs->view = args.view;
frameArgs->isSequentialRender = false;
frameArgs->isRenderResponseToUserInteraction = true;
tls->frameArgs.push_back(frameArgs);
} else {
//The hash must not have changed if we did a pre-pass.
frameArgs = tls->frameArgs.back();
glContext = frameArgs->openGLContext.lock();
abortInfo = frameArgs->abortInfo.lock();
if (!abortInfo) {
// If we don't have info to identify the render, we cannot manage the OpenGL context properly, so don't try to render with OpenGL.
glContext.reset();
}
assert(!frameArgs->request || frameArgs->nodeHash == frameArgs->request->nodeHash);
}
///For writer we never want to cache otherwise the next time we want to render it will skip writing the image on disk!
bool byPassCache = args.byPassCache;
///Use the hash at this time, and then copy it to the clips in the thread-local storage to use the same value
///through all the rendering of this frame.
U64 nodeHash = frameArgs->nodeHash;
const double par = getAspectRatio(-1);
const ImageFieldingOrderEnum fieldingOrder = getFieldingOrder();
const ImagePremultiplicationEnum thisEffectOutputPremult = getPremult();
const unsigned int mipMapLevel = args.mipMapLevel;
SupportsEnum supportsRS = supportsRenderScaleMaybe();
///This flag is relevant only when the mipMapLevel is different than 0. We use it to determine
///whether the plug-in should render in the full scale image, and then we downscale afterwards or
///if the plug-in can just use the downscaled image to render.
bool renderFullScaleThenDownscale = (supportsRS == eSupportsNo && mipMapLevel != 0);
unsigned int renderMappedMipMapLevel;
if (renderFullScaleThenDownscale) {
renderMappedMipMapLevel = 0;
} else {
renderMappedMipMapLevel = args.mipMapLevel;
}
RenderScale renderMappedScale( Image::getScaleFromMipMapLevel(renderMappedMipMapLevel) );
assert( !( (supportsRS == eSupportsNo) && !(renderMappedScale.x == 1. && renderMappedScale.y == 1.) ) );
const FrameViewRequest* requestPassData = 0;
if (frameArgs->request) {
requestPassData = frameArgs->request->getFrameViewRequest(args.time, args.view);
}
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
////////////////////////////// Get the RoD ///////////////////////////////////////////////////////////////
RectD rod; //!< rod is in canonical coordinates
bool isProjectFormat = false;
{
///if the rod is already passed as parameter, just use it and don't call getRegionOfDefinition
if ( !args.preComputedRoD.isNull() ) {
rod = args.preComputedRoD;
} else {
///Check if the pre-pass already has the RoD
if (requestPassData) {
rod = requestPassData->globalData.rod;
isProjectFormat = requestPassData->globalData.isProjectFormat;
} else {
assert( !( (supportsRS == eSupportsNo) && !(renderMappedScale.x == 1. && renderMappedScale.y == 1.) ) );
StatusEnum stat = getRegionOfDefinition_public(nodeHash, args.time, renderMappedScale, args.view, &rod, &isProjectFormat);
///The rod might be NULL for a roto that has no beziers and no input
if (stat == eStatusFailed) {
///if getRoD fails, this might be because the RoD is null after all (e.g: an empty Roto node), we don't want the render to fail
return eRenderRoIRetCodeOk;
} else if ( rod.isNull() ) {
//Nothing to render
return eRenderRoIRetCodeOk;
}
if ( (supportsRS == eSupportsMaybe) && (renderMappedMipMapLevel != 0) ) {
// supportsRenderScaleMaybe may have changed, update it
supportsRS = supportsRenderScaleMaybe();
renderFullScaleThenDownscale = (supportsRS == eSupportsNo && mipMapLevel != 0);
if (renderFullScaleThenDownscale) {
renderMappedScale.x = renderMappedScale.y = 1.;
renderMappedMipMapLevel = 0;
}
}
}
}
}
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
////////////////////////////// End get RoD ///////////////////////////////////////////////////////////////
RectI roi;
{
if (renderFullScaleThenDownscale) {
//We cache 'image', hence the RoI should be expressed in its coordinates
//renderRoIInternal should check the bitmap of 'image' and not downscaledImage!
RectD canonicalRoI;
args.roi.toCanonical(args.mipMapLevel, par, rod, &canonicalRoI);
canonicalRoI.toPixelEnclosing(0, par, &roi);
} else {
roi = args.roi;
}
}
///Determine needed planes
ComponentsNeededMapPtr neededComps = boost::make_shared<ComponentsNeededMap>();
ComponentsNeededMap::iterator foundOutputNeededComps;
std::bitset<4> processChannels;
std::list<ImagePlaneDesc> passThroughPlanes;
int ptInputNb;
double ptTime;
int ptView;
{
bool processAllComponentsRequested;
{
getComponentsNeededAndProduced_public(nodeHash, args.time, args.view, neededComps.get(), &passThroughPlanes, &processAllComponentsRequested, &ptTime, &ptView, &processChannels, &ptInputNb);
foundOutputNeededComps = neededComps->find(-1);
if ( foundOutputNeededComps == neededComps->end() ) {
return eRenderRoIRetCodeOk;
}
}
if (processAllComponentsRequested) {
std::list<ImagePlaneDesc> compVec;
for (std::list<ImagePlaneDesc>::const_iterator it = args.components.begin(); it != args.components.end(); ++it) {
bool found = false;
//Change all needed comps in output to the requested components
for (std::list<ImagePlaneDesc>::const_iterator it2 = foundOutputNeededComps->second.begin(); it2 != foundOutputNeededComps->second.end(); ++it2) {
if ( ( it2->isColorPlane() && it->isColorPlane() ) ) {
compVec.push_back(*it2);
found = true;
break;
}
}
if (!found) {
compVec.push_back(*it);
}
}
for (ComponentsNeededMap::iterator it = neededComps->begin(); it != neededComps->end(); ++it) {
it->second = compVec;
}
}
}
const std::list<ImagePlaneDesc> & outputComponents = foundOutputNeededComps->second;
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
////////////////////////////// Handle pass-through for planes //////////////////////////////////////////////////////////
std::list<ImagePlaneDesc> requestedComponents;
{
{
EffectInstancePtr passThroughInput = getInput(ptInputNb);
/*
* For all requested planes, check which components can be produced in output by this node.
* If the components are from the color plane, if another set of components of the color plane is present
* we try to render with those instead.
*/
for (std::list<ImagePlaneDesc>::const_iterator it = args.components.begin(); it != args.components.end(); ++it) {
// We may not request paired layers
assert(it->getNumComponents() > 0);
std::list<ImagePlaneDesc>::const_iterator foundInOutputComps = ImagePlaneDesc::findEquivalentLayer(*it, outputComponents.begin(), outputComponents.end());
if (foundInOutputComps != outputComponents.end()) {
requestedComponents.push_back(*foundInOutputComps);
} else {
std::list<ImagePlaneDesc>::iterator foundEquivalent = ImagePlaneDesc::findEquivalentLayer(*it, passThroughPlanes.begin(), passThroughPlanes.end());
// If the requested component is not present, then it will just return black and transparent to the plug-in.
if (foundEquivalent != passThroughPlanes.end()) {
boost::scoped_ptr<RenderRoIArgs> inArgs ( new RenderRoIArgs(args) );
inArgs->preComputedRoD.clear();
inArgs->components.clear();
inArgs->components.push_back(*foundEquivalent);
inArgs->time = ptTime;
inArgs->view = ViewIdx(ptView);
if (!passThroughInput) {
return eRenderRoIRetCodeFailed;
}
std::map<ImagePlaneDesc, ImagePtr> inputPlanes;
RenderRoIRetCode inputRetCode = passThroughInput->renderRoI(*inArgs, &inputPlanes);
assert( inputPlanes.size() == 1 || inputPlanes.empty() );
if ( (inputRetCode == eRenderRoIRetCodeAborted) || (inputRetCode == eRenderRoIRetCodeFailed) || inputPlanes.empty() ) {
return inputRetCode;
}
outputPlanes->insert( std::make_pair(*it, inputPlanes.begin()->second) );
}
}
}
}
///There might be only planes to render that were fetched from upstream
if ( requestedComponents.empty() ) {
return eRenderRoIRetCodeOk;
}
}
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
////////////////////////////// End pass-through for planes //////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
////////////////////////////// Check if effect is identity ///////////////////////////////////////////////////////////////
{
double inputTimeIdentity = 0.;
int inputNbIdentity;
ViewIdx inputIdentityView(args.view);
assert( !( (supportsRS == eSupportsNo) && !(renderMappedScale.x == 1. && renderMappedScale.y == 1.) ) );
bool identity;
RectI pixelRod;
rod.toPixelEnclosing(args.mipMapLevel, par, &pixelRod);
ViewInvarianceLevel viewInvariance = isViewInvariant();
if ( (args.view != 0) && (viewInvariance == eViewInvarianceAllViewsInvariant) ) {
identity = true;
inputNbIdentity = -2;
inputTimeIdentity = args.time;
} else {
try {
if (requestPassData) {
inputTimeIdentity = requestPassData->globalData.inputIdentityTime;
inputNbIdentity = requestPassData->globalData.identityInputNb;
identity = requestPassData->globalData.isIdentity;
inputIdentityView = requestPassData->globalData.identityView;
} else {
identity = isIdentity_public(true, nodeHash, args.time, renderMappedScale, pixelRod, args.view, &inputTimeIdentity, &inputIdentityView, &inputNbIdentity);
}
} catch (...) {
return eRenderRoIRetCodeFailed;
}
}
if ( (supportsRS == eSupportsMaybe) && (mipMapLevel != 0) ) {
// supportsRenderScaleMaybe may have changed, update it
renderFullScaleThenDownscale = true;
renderMappedScale.x = renderMappedScale.y = 1.;
renderMappedMipMapLevel = 0;
}
if (identity) {
///The effect is an identity but it has no inputs
if (inputNbIdentity == -1) {
return eRenderRoIRetCodeOk;
} else if (inputNbIdentity == -2) {
// there was at least one crash if you set the first frame to a negative value
assert(inputTimeIdentity != args.time || viewInvariance == eViewInvarianceAllViewsInvariant);
// be safe in release mode otherwise we hit an infinite recursion
if ( (inputTimeIdentity != args.time) || (viewInvariance == eViewInvarianceAllViewsInvariant) ) {
///This special value of -2 indicates that the plugin is identity of itself at another time
boost::scoped_ptr<RenderRoIArgs> argCpy ( new RenderRoIArgs(args) );
argCpy->time = inputTimeIdentity;
if (viewInvariance == eViewInvarianceAllViewsInvariant) {
argCpy->view = ViewIdx(0);
} else {
argCpy->view = inputIdentityView;
}
argCpy->preComputedRoD.clear(); //< clear as the RoD of the identity input might not be the same (reproducible with Blur)
return renderRoI(*argCpy, outputPlanes);
}
}
double firstFrame, lastFrame;
getFrameRange_public(nodeHash, &firstFrame, &lastFrame);
RectD canonicalRoI;
///WRONG! We can't clip against the RoD of *this* effect. We should clip against the RoD of the input effect, but this is done
///later on for us already.
//args.roi.toCanonical(args.mipMapLevel, rod, &canonicalRoI);
args.roi.toCanonical_noClipping(args.mipMapLevel, par, &canonicalRoI);
EffectInstancePtr inputEffectIdentity = getInput(inputNbIdentity);
if (inputEffectIdentity) {
if ( frameArgs->stats && frameArgs->stats->isInDepthProfilingEnabled() ) {
frameArgs->stats->setNodeIdentity( getNode(), inputEffectIdentity->getNode() );
}
boost::scoped_ptr<RenderRoIArgs> inputArgs ( new RenderRoIArgs(args) );
inputArgs->time = inputTimeIdentity;
inputArgs->view = inputIdentityView;
// Make sure we do not hold the RoD for this effect
inputArgs->preComputedRoD.clear();
/*
When the effect is identity, we can make 2 different requests upstream:
A) If they do not exist upstream, then this will result in a black image
B) If instead we request what this node (the identity node) has set to the corresponding layer
selector for the identity input, we may end-up with something different.
So we have to use option B), but for some cases it requires behaviour A), e.g:
1 - A Dot node does not have any channel selector and is expected to be a pass-through for layers.
2 - A node's Output Layer choice set on All is expected to act as a Dot (because it is identity).
This second case is already covered above in the code when choice is All, so we only have to worry
about case 1
*/
bool fetchUserSelectedComponentsUpstream = getNode()->getChannelSelectorKnob(inputNbIdentity).get() != 0;
if (fetchUserSelectedComponentsUpstream) {
/// This corresponds to choice B)
EffectInstance::ComponentsNeededMap::const_iterator foundCompsNeeded = neededComps->find(inputNbIdentity);
if ( foundCompsNeeded != neededComps->end() ) {
inputArgs->components.clear();
for (std::list<ImagePlaneDesc>::const_iterator it = foundCompsNeeded->second.begin(); it != foundCompsNeeded->second.end(); ++it) {
if (it->getNumComponents() != 0) {
inputArgs->components.push_back(*it);
}
}
}
} else {
/// This corresponds to choice A)
inputArgs->components = requestedComponents;
}
std::map<ImagePlaneDesc, ImagePtr> identityPlanes;
RenderRoIRetCode ret = inputEffectIdentity->renderRoI(*inputArgs, &identityPlanes);
if (ret == eRenderRoIRetCodeOk) {
outputPlanes->insert( identityPlanes.begin(), identityPlanes.end() );
if (fetchUserSelectedComponentsUpstream) {
// We fetched potentially different components, so convert them to the format requested
std::map<ImagePlaneDesc, ImagePtr> convertedPlanes;
AppInstancePtr app = getApp();
bool useAlpha0ForRGBToRGBAConversion = args.caller ? args.caller->getNode()->usesAlpha0ToConvertFromRGBToRGBA() : false;
std::list<ImagePlaneDesc>::const_iterator compIt = args.components.begin();
for (std::map<ImagePlaneDesc, ImagePtr>::iterator it = outputPlanes->begin(); it != outputPlanes->end(); ++it, ++compIt) {
ImagePremultiplicationEnum premult;
const ImagePlaneDesc & outComp = outputComponents.front();
if ( outComp.isColorPlane() ) {
premult = thisEffectOutputPremult;
} else {
premult = eImagePremultiplicationOpaque;
}
ImagePtr tmp = convertPlanesFormatsIfNeeded(app, it->second, args.roi, *compIt, inputArgs->bitdepth, useAlpha0ForRGBToRGBAConversion, premult, -1);
assert(tmp);
convertedPlanes[it->first] = tmp;
}
*outputPlanes = convertedPlanes;
}
} else {
return ret;
}
} else {
assert( outputPlanes->empty() );
}
return eRenderRoIRetCodeOk;
} // if (identity)
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
////////////////////////////// End identity check ///////////////////////////////////////////////////////////////
// At this point, if only the pass through planes are view variant and the rendered view is different than 0,
// just call renderRoI again for the components left to render on the view 0.
if ( (args.view != 0) && (viewInvariance == eViewInvarianceOnlyPassThroughPlanesVariant) ) {
boost::scoped_ptr<RenderRoIArgs> argCpy( new RenderRoIArgs(args) );
argCpy->view = ViewIdx(0);
argCpy->preComputedRoD.clear();
return renderRoI(*argCpy, outputPlanes);
}
}
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
////////////////////////////// Transform concatenations ///////////////////////////////////////////////////////////////
///Try to concatenate transform effects
bool useTransforms;
if (requestPassData) {
tls->currentRenderArgs.transformRedirections = requestPassData->globalData.transforms;
useTransforms = tls->currentRenderArgs.transformRedirections && !tls->currentRenderArgs.transformRedirections->empty();
} else {
SettingsPtr settings = appPTR->getCurrentSettings();
useTransforms = settings && settings->isTransformConcatenationEnabled();
if (useTransforms) {
tls->currentRenderArgs.transformRedirections = boost::make_shared<InputMatrixMap>();
tryConcatenateTransforms( args.time, frameArgs->draftMode, args.view, args.scale, tls->currentRenderArgs.transformRedirections.get() );
}
}
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
/////////////////////////////////End transform concatenations//////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
////////////////////////////// Compute RoI depending on render scale ///////////////////////////////////////////////////
RectI downscaledImageBoundsNc;
RectI upscaledImageBoundsNc;
{
rod.toPixelEnclosing(args.mipMapLevel, par, &downscaledImageBoundsNc);
rod.toPixelEnclosing(0, par, &upscaledImageBoundsNc);
///Make sure the RoI falls within the image bounds
///Intersection will be in pixel coordinates
if (frameArgs->tilesSupported) {
if (renderFullScaleThenDownscale) {
if ( !roi.intersect(upscaledImageBoundsNc, &roi) ) {
return eRenderRoIRetCodeOk;
}
assert(roi.x1 >= upscaledImageBoundsNc.x1 && roi.y1 >= upscaledImageBoundsNc.y1 &&
roi.x2 <= upscaledImageBoundsNc.x2 && roi.y2 <= upscaledImageBoundsNc.y2);
} else {
if ( !roi.intersect(downscaledImageBoundsNc, &roi) ) {
return eRenderRoIRetCodeOk;
}
assert(roi.x1 >= downscaledImageBoundsNc.x1 && roi.y1 >= downscaledImageBoundsNc.y1 &&
roi.x2 <= downscaledImageBoundsNc.x2 && roi.y2 <= downscaledImageBoundsNc.y2);
}
#ifndef NATRON_ALWAYS_ALLOCATE_FULL_IMAGE_BOUNDS
///just allocate the roi
upscaledImageBoundsNc.intersect(roi, &upscaledImageBoundsNc);
downscaledImageBoundsNc.intersect(args.roi, &downscaledImageBoundsNc);
#endif
}
}
/*
* Keep in memory what the user as requested, and change the roi to the full bounds if the effect doesn't support tiles
*/
const RectI originalRoI = roi;
if (!frameArgs->tilesSupported) {
roi = renderFullScaleThenDownscale ? upscaledImageBoundsNc : downscaledImageBoundsNc;
}
const RectI & downscaledImageBounds = downscaledImageBoundsNc;
const RectI & upscaledImageBounds = upscaledImageBoundsNc;
RectD canonicalRoI;
{
if (renderFullScaleThenDownscale) {
roi.toCanonical(0, par, rod, &canonicalRoI);
} else {
roi.toCanonical(args.mipMapLevel, par, rod, &canonicalRoI);
}
}
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
////////////////////////////// End Compute RoI /////////////////////////////////////////////////////////////////////////
const PluginOpenGLRenderSupport openGLSupport = frameArgs->currentOpenglSupport;
StorageModeEnum storage = eStorageModeRAM;
OSGLContextAttacherPtr glContextLocker;
if ( dynamic_cast<DiskCacheNode*>(this) ) {
storage = eStorageModeDisk;
} else if ( glContext && ( (openGLSupport == ePluginOpenGLRenderSupportNeeded) ||
( ( openGLSupport == ePluginOpenGLRenderSupportYes) && args.allowGPURendering) ) ) {
// Enable GPU render if the plug-in cannot render another way or if all conditions are met
if (openGLSupport == ePluginOpenGLRenderSupportNeeded && !getNode()->getPlugin()->isOpenGLEnabled()) {
QString message = tr("OpenGL render is required for %1 but was disabled in the Preferences for this plug-in, please enable it and restart %2").arg(QString::fromUtf8(getNode()->getLabel().c_str())).arg(QString::fromUtf8(NATRON_APPLICATION_NAME));
setPersistentMessage(eMessageTypeError, message.toStdString());
return eRenderRoIRetCodeFailed;
}
/*
We only render using OpenGL if this effect is the preferred input of the calling node (to avoid recursions in the graph
since we do not use the cache for textures)
*/
// Make the OpenGL context current to this thread
glContextLocker = boost::make_shared<OSGLContextAttacher>(glContext, abortInfo
#ifdef DEBUG
, frameArgs->time
#endif
);
storage = eStorageModeGLTex;
// If the plug-in knows how to render on CPU, check if we actually should not render on CPU instead.
if (openGLSupport == ePluginOpenGLRenderSupportYes) {
// User want to force caching of this node but we cannot cache OpenGL renders, so fallback on CPU.
if ( getNode()->isForceCachingEnabled() ) {
storage = eStorageModeRAM;
glContextLocker.reset();
}
// If a node has multiple outputs, do not render it on OpenGL since we do not use the cache. We could end-up with this render being executed multiple times.
// Also, if the render time is different from the caller render time, don't render using OpenGL otherwise we could computed this render multiple times.
if (storage == eStorageModeGLTex) {
if ( (frameArgs->visitsCount > 1) ||
( args.time != args.callerRenderTime) ) {
storage = eStorageModeRAM;
glContextLocker.reset();
}
}
// Ensure that the texture will be at least smaller than the maximum OpenGL texture size
if (storage == eStorageModeGLTex) {
int maxTextureSize = appPTR->getGPUContextPool()->getCurrentOpenGLRendererMaxTextureSize();
if ( (roi.width() >= maxTextureSize) ||
( roi.height() >= maxTextureSize) ) {
// Fallback on CPU rendering since the image is larger than the maximum allowed OpenGL texture size
storage = eStorageModeRAM;
glContextLocker.reset();
}
}
}
if (storage == eStorageModeGLTex) {
// OpenGL renders always support render scale...
if (renderFullScaleThenDownscale) {
renderFullScaleThenDownscale = false;
renderMappedMipMapLevel = args.mipMapLevel;
renderMappedScale.x = renderMappedScale.y = Image::getScaleFromMipMapLevel(renderMappedMipMapLevel);
if (frameArgs->tilesSupported) {
roi = args.roi;
if ( !roi.intersect(downscaledImageBoundsNc, &roi) ) {
return eRenderRoIRetCodeOk;
}
} else {
roi = downscaledImageBoundsNc;
}
}
}
}
const bool draftModeSupported = getNode()->isDraftModeUsed();
const bool isFrameVaryingOrAnimated = isFrameVaryingOrAnimated_Recursive();
bool createInCache;
// Do not use the cache for OpenGL rendering
if (storage == eStorageModeGLTex) {
createInCache = false;
} else {
// in Analysis, the node upstream of the analysis node should always cache
createInCache = (frameArgs->isAnalysis && frameArgs->treeRoot->getEffectInstance().get() == args.caller) ? true : shouldCacheOutput(isFrameVaryingOrAnimated, args.time, args.view, frameArgs->visitsCount);
}
///Do we want to render the graph upstream at scale 1 or at the requested render scale ? (user setting)
bool renderScaleOneUpstreamIfRenderScaleSupportDisabled = getNode()->useScaleOneImagesWhenRenderScaleSupportIsDisabled();
///For multi-resolution we want input images with exactly the same size as the output image
if ( !renderScaleOneUpstreamIfRenderScaleSupportDisabled && !supportsMultiResolution() ) {
renderScaleOneUpstreamIfRenderScaleSupportDisabled = true;
}
boost::scoped_ptr<ImageKey> key( new ImageKey(getNode().get(),
nodeHash,
isFrameVaryingOrAnimated,
args.time,
args.view,
1.,
draftModeSupported && frameArgs->draftMode,
renderMappedMipMapLevel == 0 && !renderScaleOneUpstreamIfRenderScaleSupportDisabled) );
boost::scoped_ptr<ImageKey> nonDraftKey( new ImageKey(getNode().get(),
nodeHash,
isFrameVaryingOrAnimated,
args.time,
args.view,
1.,
false,
renderMappedMipMapLevel == 0 && !renderScaleOneUpstreamIfRenderScaleSupportDisabled) );
bool isDuringPaintStroke = isDuringPaintStrokeCreationThreadLocal();
/*
* Get the bitdepth and output components that the plug-in expects to render. The cached image does not necesserarily has the bitdepth
* that the plug-in expects.
*/
ImageBitDepthEnum outputDepth = getBitDepth(-1);
ImagePlaneDesc outputClipPrefComps, outputClipPrefCompsPaired;
getMetadataComponents(-1, &outputClipPrefComps, &outputClipPrefCompsPaired);
ImagePlanesToRenderPtr planesToRender = boost::make_shared<ImagePlanesToRender>();
planesToRender->useOpenGL = storage == eStorageModeGLTex;
FramesNeededMapPtr framesNeeded = boost::make_shared<FramesNeededMap>();
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
////////////////////////////// Look-up the cache ///////////////////////////////////////////////////////////////
{
//If one plane is missing from cache, we will have to render it all. For all other planes, either they have nothing
//left to render, otherwise we render them for all the roi again.
bool missingPlane = false;
for (std::list<ImagePlaneDesc>::iterator it = requestedComponents.begin(); it != requestedComponents.end(); ++it) {
EffectInstance::PlaneToRender plane;
/*
* If the plane is the color plane, we might have to convert between components, hence we always
* try to find in the cache the "preferred" components of this node for the color plane.
* For all other planes, just consider this set of components, we do not allow conversion.
*/
const ImagePlaneDesc* components = 0;
if ( !it->isColorPlane() ) {
components = &(*it);
} else {
for (std::list<ImagePlaneDesc>::const_iterator it2 = outputComponents.begin(); it2 != outputComponents.end(); ++it2) {
if ( it2->isColorPlane() ) {
components = &(*it2);
break;
}
}
}
assert(components);
if (!components) {
continue;
}
//For writers, we always want to call the render action when doing a sequential render, but we still want to use the cache for nodes upstream
bool doCacheLookup = !isWriter() || !frameArgs->isSequentialRender;
if (doCacheLookup) {
int nLookups = draftModeSupported && frameArgs->draftMode ? 2 : 1;
// If the node doesn't support render scale, first lookup the cache with requested level, if not cached then lookup
// with full scale
unsigned int lookupMipMapLevel = (renderMappedMipMapLevel != mipMapLevel && !isDuringPaintStroke)? mipMapLevel : renderMappedMipMapLevel;
for (int n = 0; n < nLookups; ++n) {
getImageFromCacheAndConvertIfNeeded(createInCache, storage, args.returnStorage, n == 0 ? *nonDraftKey : *key, lookupMipMapLevel,
&downscaledImageBounds,
&rod, args.roi,
args.bitdepth, *it,
args.inputImagesList,
frameArgs->stats,
glContextLocker,
&plane.fullscaleImage);
if (plane.fullscaleImage) {
if (byPassCache) {
if (plane.fullscaleImage) {
appPTR->removeFromNodeCache( key->getHash() );
plane.fullscaleImage.reset();
}
} else if (renderMappedMipMapLevel != mipMapLevel) {
// Only keep the cached image if it covers the roi
std::list<RectI> restToRender;
plane.fullscaleImage->getRestToRender(args.roi, restToRender);
if ( !restToRender.empty() ) {
plane.fullscaleImage.reset();
} else {
renderFullScaleThenDownscale = false;
renderMappedMipMapLevel = mipMapLevel;
roi = args.roi;
}
}
break;