forked from NatronGitHub/Natron
-
Notifications
You must be signed in to change notification settings - Fork 0
/
EffectInstance.cpp
5992 lines (5091 loc) · 233 KB
/
EffectInstance.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> // stringstream
#include <algorithm> // min, max
#include <fstream>
#include <bitset>
#include <cassert>
#include <stdexcept>
#include <sstream> // stringstream
#if !defined(SBK_RUN) && !defined(Q_MOC_RUN)
GCC_DIAG_UNUSED_LOCAL_TYPEDEFS_OFF
#include <boost/algorithm/string/predicate.hpp>
#include <boost/scoped_ptr.hpp>
#include <boost/make_shared.hpp>
GCC_DIAG_UNUSED_LOCAL_TYPEDEFS_ON
#endif
#include <QtCore/QReadWriteLock>
#include <QtCore/QCoreApplication>
#include <QtConcurrentMap> // QtCore on Qt4, QtConcurrent on Qt5
#include <QtConcurrentRun> // QtCore on Qt4, QtConcurrent on Qt5
#include "Global/QtCompat.h"
#include "Engine/AbortableRenderInfo.h"
#include "Engine/AppInstance.h"
#include "Engine/AppManager.h"
#include "Engine/BlockingBackgroundRender.h"
#include "Engine/DiskCacheNode.h"
#include "Engine/Image.h"
#include "Engine/ImageParams.h"
#include "Engine/KnobFile.h"
#include "Engine/KnobTypes.h"
#include "Engine/Log.h"
#include "Engine/MemoryInfo.h" // printAsRAM
#include "Engine/Node.h"
#include "Engine/OfxEffectInstance.h"
#include "Engine/OfxOverlayInteract.h"
#include "Engine/OfxImageEffectInstance.h"
#include "Engine/GPUContextPool.h"
#include "Engine/OSGLContext.h"
#include "Engine/OutputSchedulerThread.h"
#include "Engine/PluginMemory.h"
#include "Engine/Project.h"
#include "Engine/RenderStats.h"
#include "Engine/RotoContext.h"
#include "Engine/RotoDrawableItem.h"
#include "Engine/ReadNode.h"
#include "Engine/Settings.h"
#include "Engine/Timer.h"
#include "Engine/Transform.h"
#include "Engine/UndoCommand.h"
#include "Engine/ViewIdx.h"
#include "Engine/ViewerInstance.h"
//#define NATRON_ALWAYS_ALLOCATE_FULL_IMAGE_BOUNDS
NATRON_NAMESPACE_ENTER
class KnobFile;
class KnobOutputFile;
void
EffectInstance::addThreadLocalInputImageTempPointer(int inputNb,
const ImagePtr & img)
{
_imp->addInputImageTempPointer(inputNb, img);
}
EffectInstance::EffectInstance(NodePtr node)
: NamedKnobHolder( node ? node->getApp() : AppInstancePtr() )
, _node(node)
, _imp( new Implementation(this) )
{
if (node) {
if ( !node->isRenderScaleSupportEnabledForPlugin() ) {
setSupportsRenderScaleMaybe(eSupportsNo);
}
}
}
EffectInstance::EffectInstance(const EffectInstance& other)
: NamedKnobHolder(other)
, LockManagerI<Image>()
, boost::enable_shared_from_this<EffectInstance>()
, _node( other.getNode() )
, _imp( new Implementation(*other._imp) )
{
_imp->_publicInterface = this;
}
EffectInstance::~EffectInstance()
{
}
void
EffectInstance::lock(const ImagePtr & entry)
{
NodePtr n = _node.lock();
n->lock(entry);
}
bool
EffectInstance::tryLock(const ImagePtr & entry)
{
NodePtr n = _node.lock();
return n->tryLock(entry);
}
void
EffectInstance::unlock(const ImagePtr & entry)
{
NodePtr n = _node.lock();
n->unlock(entry);
}
/**
* @brief Add the layers from the inputList to the toList if they do not already exist in the list.
* For the color plane, if it already existed in toList it is replaced by the value in inputList
**/
static void mergeLayersList(const std::list<ImagePlaneDesc>& inputList,
std::list<ImagePlaneDesc>* toList)
{
for (std::list<ImagePlaneDesc>::const_iterator it = inputList.begin(); it != inputList.end(); ++it) {
std::list<ImagePlaneDesc>::iterator foundMatch = ImagePlaneDesc::findEquivalentLayer(*it, toList->begin(), toList->end());
// If we found the color plane, replace it by this color plane which may have changed (e.g: input was Color.RGB but this node Color.RGBA)
if (foundMatch != toList->end()) {
toList->erase(foundMatch);
}
toList->push_back(*it);
} // for each input components
} // mergeLayersList
/**
* @brief Remove any layer from the toRemove list from toList.
**/
static void removeFromLayersList(const std::list<ImagePlaneDesc>& toRemove,
std::list<ImagePlaneDesc>* toList)
{
for (std::list<ImagePlaneDesc>::const_iterator it = toRemove.begin(); it != toRemove.end(); ++it) {
std::list<ImagePlaneDesc>::iterator foundMatch = ImagePlaneDesc::findEquivalentLayer<std::list<ImagePlaneDesc>::iterator>(*it, toList->begin(), toList->end());
if (foundMatch != toList->end()) {
toList->erase(foundMatch);
}
} // for each input components
} // removeFromLayersList
const std::vector<std::string>&
EffectInstance::getUserPlanes() const
{
EffectTLSDataPtr tls = _imp->tlsData->getOrCreateTLSData();
assert(tls);
tls->userPlaneStrings.clear();
std::list<ImagePlaneDesc> projectLayers = getApp()->getProject()->getProjectDefaultLayers();
std::list<ImagePlaneDesc> userCreatedLayers;
getNode()->getUserCreatedComponents(&userCreatedLayers);
mergeLayersList(userCreatedLayers, &projectLayers);
for (std::list<ImagePlaneDesc>::iterator it = projectLayers.begin(); it != projectLayers.end(); ++it) {
std::string ofxPlane = ImagePlaneDesc::mapPlaneToOFXPlaneString(*it);
tls->userPlaneStrings.push_back(ofxPlane);
}
return tls->userPlaneStrings;
}
void
EffectInstance::clearPluginMemoryChunks()
{
// This will remove the mem from the pluginMemoryChunks list
QMutexLocker l(&_imp->pluginMemoryChunksMutex);
for (std::list<PluginMemoryWPtr>::iterator it = _imp->pluginMemoryChunks.begin(); it!=_imp->pluginMemoryChunks.end(); ++it) {
PluginMemoryPtr mem = it->lock();
if (!mem) {
continue;
}
mem->setUnregisterOnDestructor(false);
}
_imp->pluginMemoryChunks.clear();
}
#ifdef DEBUG
void
EffectInstance::setCanSetValue(bool can)
{
_imp->tlsData->getOrCreateTLSData()->canSetValue.push_back(can);
}
void
EffectInstance::invalidateCanSetValueFlag()
{
EffectTLSDataPtr tls = _imp->tlsData->getTLSData();
assert(tls);
assert( !tls->canSetValue.empty() );
tls->canSetValue.pop_back();
}
bool
EffectInstance::isDuringActionThatCanSetValue() const
{
EffectTLSDataPtr tls = _imp->tlsData->getTLSData();
if (!tls) {
return true;
}
if ( tls->canSetValue.empty() ) {
return true;
}
return tls->canSetValue.back();
}
#endif //DEBUG
void
EffectInstance::setNodeRequestThreadLocal(const NodeFrameRequestPtr & nodeRequest)
{
EffectTLSDataPtr tls = _imp->tlsData->getTLSData();
if (!tls) {
assert(false);
return;
}
std::list<ParallelRenderArgsPtr>& argsList = tls->frameArgs;
if ( argsList.empty() ) {
return;
}
argsList.back()->request = nodeRequest;
}
void
EffectInstance::setParallelRenderArgsTLS(double time,
ViewIdx view,
bool isRenderUserInteraction,
bool isSequential,
U64 nodeHash,
const AbortableRenderInfoPtr& abortInfo,
const NodePtr & treeRoot,
int visitsCount,
const NodeFrameRequestPtr & nodeRequest,
const OSGLContextPtr& glContext,
int textureIndex,
const TimeLine* timeline,
bool isAnalysis,
bool isDuringPaintStrokeCreation,
const NodesList & rotoPaintNodes,
RenderSafetyEnum currentThreadSafety,
PluginOpenGLRenderSupport currentOpenGLSupport,
bool doNanHandling,
bool draftMode,
const RenderStatsPtr & stats)
{
EffectTLSDataPtr tls = _imp->tlsData->getOrCreateTLSData();
std::list<ParallelRenderArgsPtr>& argsList = tls->frameArgs;
ParallelRenderArgsPtr args = boost::make_shared<ParallelRenderArgs>();
args->time = time;
args->timeline = timeline;
args->view = view;
args->isRenderResponseToUserInteraction = isRenderUserInteraction;
args->isSequentialRender = isSequential;
args->request = nodeRequest;
if (nodeRequest) {
args->nodeHash = nodeRequest->nodeHash;
} else {
args->nodeHash = nodeHash;
}
assert(abortInfo);
args->abortInfo = abortInfo;
args->treeRoot = treeRoot;
args->visitsCount = visitsCount;
args->textureIndex = textureIndex;
args->isAnalysis = isAnalysis;
args->isDuringPaintStrokeCreation = isDuringPaintStrokeCreation;
args->currentThreadSafety = currentThreadSafety;
args->currentOpenglSupport = currentOpenGLSupport;
args->rotoPaintNodes = rotoPaintNodes;
args->doNansHandling = isAnalysis ? false : doNanHandling;
args->draftMode = draftMode;
args->tilesSupported = getNode()->getCurrentSupportTiles();
args->stats = stats;
args->openGLContext = glContext;
argsList.push_back(args);
}
bool
EffectInstance::getThreadLocalRotoPaintTreeNodes(NodesList* nodes) const
{
EffectTLSDataPtr tls = _imp->tlsData->getTLSData();
if (!tls) {
return false;
}
if ( tls->frameArgs.empty() ) {
return false;
}
*nodes = tls->frameArgs.back()->rotoPaintNodes;
return true;
}
void
EffectInstance::setDuringPaintStrokeCreationThreadLocal(bool duringPaintStroke)
{
EffectTLSDataPtr tls = _imp->tlsData->getOrCreateTLSData();
tls->frameArgs.back()->isDuringPaintStrokeCreation = duringPaintStroke;
}
void
EffectInstance::setParallelRenderArgsTLS(const ParallelRenderArgsPtr & args)
{
EffectTLSDataPtr tls = _imp->tlsData->getOrCreateTLSData();
assert( args->abortInfo.lock() );
tls->frameArgs.push_back(args);
}
void
EffectInstance::invalidateParallelRenderArgsTLS()
{
EffectTLSDataPtr tls = _imp->tlsData->getTLSData();
if (!tls) {
return;
}
assert( !tls->frameArgs.empty() );
const ParallelRenderArgsPtr& back = tls->frameArgs.back();
for (NodesList::iterator it = back->rotoPaintNodes.begin(); it != back->rotoPaintNodes.end(); ++it) {
(*it)->getEffectInstance()->invalidateParallelRenderArgsTLS();
}
tls->frameArgs.pop_back();
}
ParallelRenderArgsPtr
EffectInstance::getParallelRenderArgsTLS() const
{
EffectTLSDataPtr tls = _imp->tlsData->getTLSData();
if ( !tls || tls->frameArgs.empty() ) {
return ParallelRenderArgsPtr();
}
return tls->frameArgs.back();
}
U64
EffectInstance::getHash() const
{
NodePtr n = _node.lock();
return n->getHashValue();
}
U64
EffectInstance::getRenderHash() const
{
EffectTLSDataPtr tls = _imp->tlsData->getTLSData();
if ( !tls || tls->frameArgs.empty() ) {
//No tls: get the GUI hash
return getHash();
}
const ParallelRenderArgsPtr &args = tls->frameArgs.back();
if (args->request) {
//A request pass was made, Hash for this thread was already computed, use it
return args->request->nodeHash;
}
//Use the hash that was computed when we set the ParallelRenderArgs TLS
return args->nodeHash;
}
bool
EffectInstance::Implementation::aborted(bool isRenderResponseToUserInteraction,
const AbortableRenderInfoPtr& abortInfo,
const EffectInstancePtr& treeRoot)
{
if (!isRenderResponseToUserInteraction) {
// Rendering is playback or render on disk
// If we have abort info, e just peek the atomic int inside the abort info, this is very fast
if ( abortInfo && abortInfo->isAborted() ) {
return true;
}
// Fallback on the flag set on the node that requested the render in OutputSchedulerThread
if (treeRoot) {
OutputEffectInstance* effect = dynamic_cast<OutputEffectInstance*>( treeRoot.get() );
assert(effect);
if (effect) {
return effect->isSequentialRenderBeingAborted();
}
}
// We have no other means to know if abort was called
return false;
} else {
// This is a render issued to refresh the image on the Viewer
if ( !abortInfo || !abortInfo->canAbort() ) {
// We do not have any abortInfo set or this render is not abortable. This should be avoided as much as possible!
return false;
}
// This is very fast, we just peek the atomic int inside the abort info
if ( (int)abortInfo->isAborted() ) {
return true;
}
// If this node can start sequential renders (e.g: start playback like on the viewer or render on disk) and it is already doing a sequential render, abort
// this render
OutputEffectInstance* isRenderEffect = dynamic_cast<OutputEffectInstance*>( treeRoot.get() );
if (isRenderEffect) {
if ( isRenderEffect->isDoingSequentialRender() ) {
return true;
}
}
// The render was not aborted
return false;
}
}
bool
EffectInstance::aborted() const
{
QThread* thisThread = QThread::currentThread();
/* If this thread is an AbortableThread, this function will be extremely fast*/
AbortableThread* isAbortableThread = dynamic_cast<AbortableThread*>(thisThread);
/**
The solution here is to store per-render info on the thread that we retrieve.
These info contain an atomic integer determining whether this particular render was aborted or not.
If this thread does not have abort info yet on it, we retrieve them from the thread-local storage of this node
and set it.
Threads that start a render generally already have the AbortableThread::setAbortInfo function called on them, but
threads spawned from the thread pool may not.
**/
bool isRenderUserInteraction;
AbortableRenderInfoPtr abortInfo;
EffectInstancePtr treeRoot;
if ( !isAbortableThread || !isAbortableThread->getAbortInfo(&isRenderUserInteraction, &abortInfo, &treeRoot) ) {
// If this thread is not abortable or we did not set the abort info for this render yet, retrieve them from the TLS of this node.
EffectTLSDataPtr tls = _imp->tlsData->getTLSData();
if (!tls) {
return false;
}
if ( tls->frameArgs.empty() ) {
return false;
}
const ParallelRenderArgsPtr & args = tls->frameArgs.back();
isRenderUserInteraction = args->isRenderResponseToUserInteraction;
abortInfo = args->abortInfo.lock();
if (args->treeRoot) {
treeRoot = args->treeRoot->getEffectInstance();
}
if (isAbortableThread) {
isAbortableThread->setAbortInfo(isRenderUserInteraction, abortInfo, treeRoot);
}
}
// The internal function that given a AbortableRenderInfoPtr determines if a render was aborted or not
return Implementation::aborted(isRenderUserInteraction,
abortInfo,
treeRoot);
} // EffectInstance::aborted
bool
EffectInstance::shouldCacheOutput(bool isFrameVaryingOrAnimated,
double time,
ViewIdx view,
int visitsCount) const
{
NodePtr n = _node.lock();
return n->shouldCacheOutput(isFrameVaryingOrAnimated, time, view, visitsCount);
}
U64
EffectInstance::getKnobsAge() const
{
return getNode()->getKnobsAge();
}
void
EffectInstance::setKnobsAge(U64 age)
{
getNode()->setKnobsAge(age);
}
const std::string &
EffectInstance::getScriptName() const
{
return getNode()->getScriptName();
}
std::string
EffectInstance::getScriptName_mt_safe() const
{
return getNode()->getScriptName_mt_safe();
}
std::string
EffectInstance::getFullyQualifiedName() const
{
return getNode()->getFullyQualifiedName();
}
int
EffectInstance::getRenderViewsCount() const
{
return getApp()->getProject()->getProjectViewsCount();
}
bool
EffectInstance::hasOutputConnected() const
{
return getNode()->hasOutputConnected();
}
EffectInstancePtr
EffectInstance::getInput(int n) const
{
NodePtr inputNode = getNode()->getInput(n);
if (inputNode) {
return inputNode->getEffectInstance();
}
return EffectInstancePtr();
}
std::string
EffectInstance::getInputLabel(int inputNb) const
{
std::string out;
out.append( 1, (char)(inputNb + 65) );
return out;
}
std::string
EffectInstance::getInputHint(int /*inputNb*/) const
{
return std::string();
}
bool
EffectInstance::retrieveGetImageDataUponFailure(const double time,
const ViewIdx view,
const RenderScale & scale,
const RectD* optionalBoundsParam,
U64* nodeHash_p,
bool* isIdentity_p,
EffectInstancePtr* identityInput_p,
bool* duringPaintStroke_p,
RectD* rod_p,
RoIMap* inputRois_p, //!< output, only set if optionalBoundsParam != NULL
RectD* optionalBounds_p) //!< output, only set if optionalBoundsParam != NULL
{
/////Update 09/02/14
/// We now AUTHORIZE GetRegionOfDefinition and isIdentity and getRegionsOfInterest to be called recursively.
/// It didn't make much sense to forbid them from being recursive.
//#ifdef DEBUG
// if (QThread::currentThread() != qApp->thread()) {
// ///This is a bad plug-in
// qDebug() << getNode()->getScriptName_mt_safe().c_str() << " is trying to call clipGetImage during an unauthorized time. "
// "Developers of that plug-in should fix it. \n Reminder from the OpenFX spec: \n "
// "Images may be fetched from an attached clip in the following situations... \n"
// "- in the kOfxImageEffectActionRender action\n"
// "- in the kOfxActionInstanceChanged and kOfxActionEndInstanceChanged actions with a kOfxPropChangeReason or kOfxChangeUserEdited";
// }
//#endif
///Try to compensate for the mistake
*nodeHash_p = getHash();
*duringPaintStroke_p = getNode()->isDuringPaintStrokeCreation();
const U64 & nodeHash = *nodeHash_p;
{
RECURSIVE_ACTION();
StatusEnum stat = getRegionOfDefinition(nodeHash, time, scale, view, rod_p);
if (stat == eStatusFailed) {
return false;
}
}
const RectD & rod = *rod_p;
///OptionalBoundsParam is the optional rectangle passed to getImage which may be NULL, in which case we use the RoD.
if (!optionalBoundsParam) {
///// We cannot recover the RoI, we just assume the plug-in wants to render the full RoD.
*optionalBounds_p = rod;
ifInfiniteApplyHeuristic(nodeHash, time, scale, view, optionalBounds_p);
const RectD & optionalBounds = *optionalBounds_p;
/// If the region parameter is not set to NULL, then it will be clipped to the clip's
/// Region of Definition for the given time. The returned image will be m at m least as big as this region.
/// If the region parameter is not set, then the region fetched will be at least the Region of Interest
/// the effect has previously specified, clipped the clip's Region of Definition.
/// (renderRoI will do the clipping for us).
///// This code is wrong but executed ONLY IF THE PLUG-IN DOESN'T RESPECT THE SPECIFICATIONS. Recursive actions
///// should never happen.
getRegionsOfInterest(time, scale, optionalBounds, optionalBounds, ViewIdx(0), inputRois_p);
}
assert( !( (supportsRenderScaleMaybe() == eSupportsNo) && !(scale.x == 1. && scale.y == 1.) ) );
RectI pixelRod;
rod.toPixelEnclosing(scale, getAspectRatio(-1), &pixelRod);
try {
int identityInputNb;
double identityTime;
ViewIdx identityView;
*isIdentity_p = isIdentity_public(true, nodeHash, time, scale, pixelRod, view, &identityTime, &identityView, &identityInputNb);
if (*isIdentity_p) {
if (identityInputNb >= 0) {
*identityInput_p = getInput(identityInputNb);
} else if (identityInputNb == -2) {
*identityInput_p = shared_from_this();
}
}
} catch (...) {
return false;
}
return true;
} // EffectInstance::retrieveGetImageDataUponFailure
void
EffectInstance::getThreadLocalInputImages(InputImagesMap* images) const
{
EffectTLSDataPtr tls = _imp->tlsData->getTLSData();
if (!tls) {
return;
}
*images = tls->currentRenderArgs.inputImages;
}
bool
EffectInstance::getThreadLocalRegionsOfInterests(RoIMap & roiMap) const
{
EffectTLSDataPtr tls = _imp->tlsData->getTLSData();
if (!tls) {
return false;
}
roiMap = tls->currentRenderArgs.regionOfInterestResults;
return true;
}
OSGLContextPtr
EffectInstance::getThreadLocalOpenGLContext() const
{
EffectTLSDataPtr tls = _imp->tlsData->getTLSData();
if ( !tls || tls->frameArgs.empty() ) {
return OSGLContextPtr();
}
return tls->frameArgs.back()->openGLContext.lock();
}
ImagePtr
EffectInstance::getImage(int inputNb,
const double time,
const RenderScale & scale,
const ViewIdx view,
const RectD *optionalBoundsParam, //!< optional region in canonical coordinates
const ImagePlaneDesc* layer,
const bool mapToClipPrefs,
const bool dontUpscale,
const StorageModeEnum returnStorage,
const ImageBitDepthEnum* /*textureDepth*/, // < ignore requested texture depth because internally we use 32bit fp textures, so we offer the highest possible quality anyway.
RectI* roiPixel,
Transform::Matrix3x3Ptr* transform)
{
if (time != time) {
// time is NaN
return ImagePtr();
}
///The input we want the image from
EffectInstancePtr inputEffect;
//Check for transform redirections
InputMatrixMapPtr transformRedirections;
EffectTLSDataPtr tls = _imp->tlsData->getTLSData();
if (tls && tls->currentRenderArgs.validArgs) {
transformRedirections = tls->currentRenderArgs.transformRedirections;
if (transformRedirections) {
InputMatrixMap::const_iterator foundRedirection = transformRedirections->find(inputNb);
if ( ( foundRedirection != transformRedirections->end() ) && foundRedirection->second.newInputEffect ) {
inputEffect = foundRedirection->second.newInputEffect->getInput(foundRedirection->second.newInputNbToFetchFrom);
if (transform) {
*transform = foundRedirection->second.cat;
}
}
}
}
NodePtr node = getNode();
if (!inputEffect) {
inputEffect = getInput(inputNb);
}
///Is this input a mask or not
bool isMask = isInputMask(inputNb);
///If the input is a mask, this is the channel index in the layer of the mask channel
int channelForMask = -1;
///Is this node a roto node or not. If so, find out if this input is the roto-brush
RotoContextPtr roto;
RotoDrawableItemPtr attachedStroke = node->getAttachedRotoItem();
if (attachedStroke) {
roto = attachedStroke->getContext();
}
bool useRotoInput = false;
bool inputIsRotoBrush = roto && isInputRotoBrush(inputNb);
bool supportsOnlyAlpha = node->isInputOnlyAlpha(inputNb);
if (roto) {
useRotoInput = isMask || inputIsRotoBrush;
}
///This is the actual layer that we are fetching in input
ImagePlaneDesc maskComps;
if ( !isMaskEnabled(inputNb) ) {
return ImagePtr();
}
///If this is a mask, fetch the image from the effect indicated by the mask channel
if (isMask || supportsOnlyAlpha) {
if (!useRotoInput) {
std::list<ImagePlaneDesc> availableLayers;
getAvailableLayers(time, view, inputNb, &availableLayers);
channelForMask = getMaskChannel(inputNb, availableLayers, &maskComps);
} else {
channelForMask = 3; // default to alpha channel
maskComps = ImagePlaneDesc::getAlphaComponents();
}
}
//Invalid mask
if ( isMask && ( (channelForMask == -1) || (maskComps.getNumComponents() == 0) ) ) {
return ImagePtr();
}
if ( ( !roto || (roto && !useRotoInput) ) && !inputEffect ) {
//Disconnected input
return ImagePtr();
}
///If optionalBounds have been set, use this for the RoI instead of the data int the TLS
RectD optionalBounds;
if (optionalBoundsParam) {
optionalBounds = *optionalBoundsParam;
}
/*
* These are the data fields stored in the TLS from the on-going render action or instance changed action
*/
unsigned int mipMapLevel = Image::getLevelFromScale(scale.x);
RoIMap inputsRoI;
bool isIdentity = false;
EffectInstancePtr identityInput;
U64 nodeHash;
bool duringPaintStroke;
/// Never by-pass the cache here because we already computed the image in renderRoI and by-passing the cache again can lead to
/// re-computing of the same image many many times
bool byPassCache = false;
///The caller thread MUST be a thread owned by Natron. It cannot be a thread from the multi-thread suite.
///A call to getImage is forbidden outside an action running in a thread launched by Natron.
/// From http://openfx.sourceforge.net/Documentation/1.3/ofxProgrammingReference.html#ImageEffectsImagesAndClipsUsingClips
// Images may be fetched from an attached clip in the following situations...
// in the kOfxImageEffectActionRender action
// in the kOfxActionInstanceChanged and kOfxActionEndInstanceChanged actions with a kOfxPropChangeReason of kOfxChangeUserEdited
RectD roi;
bool roiWasInRequestPass = false;
bool isAnalysisPass = false;
RectD thisRod;
double thisEffectRenderTime = time;
///Try to find in the input images thread-local storage if we already pre-computed the image
EffectInstance::InputImagesMap inputImagesThreadLocal;
OSGLContextPtr glContext;
AbortableRenderInfoPtr renderInfo;
if ( !tls || ( !tls->currentRenderArgs.validArgs && tls->frameArgs.empty() ) ) {
/*
This is either a huge bug or an unknown thread that called clipGetImage from the OpenFX plug-in.
Make-up some reasonable arguments
*/
if ( !retrieveGetImageDataUponFailure(time, view, scale, optionalBoundsParam, &nodeHash, &isIdentity, &identityInput, &duringPaintStroke, &thisRod, &inputsRoI, &optionalBounds) ) {
return ImagePtr();
}
} else {
assert( tls->currentRenderArgs.validArgs || !tls->frameArgs.empty() );
if (inputEffect) {
//When analysing we do not compute a request pass so we do not enter this condition
ParallelRenderArgsPtr inputFrameArgs = inputEffect->getParallelRenderArgsTLS();
const FrameViewRequest* request = 0;
if (inputFrameArgs && inputFrameArgs->request) {
request = inputFrameArgs->request->getFrameViewRequest(time, view);
}
if (request) {
roiWasInRequestPass = true;
roi = request->finalData.finalRoi;
}
}
if ( !tls->frameArgs.empty() ) {
const ParallelRenderArgsPtr& frameRenderArgs = tls->frameArgs.back();
nodeHash = frameRenderArgs->nodeHash;
duringPaintStroke = frameRenderArgs->isDuringPaintStrokeCreation;
isAnalysisPass = frameRenderArgs->isAnalysis;
glContext = frameRenderArgs->openGLContext.lock();
renderInfo = frameRenderArgs->abortInfo.lock();
} else {
//This is a bug, when entering here, frameArgs TLS should always have been set, except for unknown threads.
nodeHash = getHash();
duringPaintStroke = false;
}
if (tls->currentRenderArgs.validArgs) {
//This will only be valid for render pass, not analysis
const RenderArgs& renderArgs = tls->currentRenderArgs;
if (!roiWasInRequestPass) {
inputsRoI = renderArgs.regionOfInterestResults;
}
thisEffectRenderTime = renderArgs.time;
isIdentity = renderArgs.isIdentity;
identityInput = renderArgs.identityInput;
inputImagesThreadLocal = renderArgs.inputImages;
thisRod = renderArgs.rod;
}
}
if ( (!glContext || !renderInfo) && returnStorage == eStorageModeGLTex ) {
qDebug() << "[BUG]: " << getScriptName_mt_safe().c_str() << "is doing an OpenGL render but no context is bound to the current render.";
return ImagePtr();
}
RectD inputRoD;
bool inputRoDSet = false;
if (optionalBoundsParam) {
//Set the RoI from the parameters given to clipGetImage
roi = optionalBounds;
} else if (!roiWasInRequestPass) {
//We did not have a request pass, use if possible the result of getRegionsOfInterest found in the TLS
//If not, fallback on input RoD
EffectInstancePtr inputToFind;
if (useRotoInput) {
if ( node->getRotoContext() ) {
inputToFind = shared_from_this();
} else {
assert(attachedStroke);
inputToFind = attachedStroke->getContext()->getNode()->getEffectInstance();
}
} else {
inputToFind = inputEffect;
}
RoIMap::iterator found = inputsRoI.find(inputToFind);
if ( found != inputsRoI.end() ) {
///RoI is in canonical coordinates since the results of getRegionsOfInterest is in canonical coords.
roi = found->second;
} else {
///Oops, we didn't find the roi in the thread-storage... use the RoD instead...
if (inputEffect && !isAnalysisPass) {
qDebug() << QThread::currentThread() << getScriptName_mt_safe().c_str() << "[Bug] RoI not found in TLS...falling back on RoD when calling getImage() on" <<
inputEffect->getScriptName_mt_safe().c_str();
}
//We are either in analysis or in an unknown thread
//do not set identity flags, request for RoI the full RoD of the input
if (useRotoInput) {
assert( !thisRod.isNull() );
roi = thisRod;
} else {
if (inputEffect) {
StatusEnum stat = inputEffect->getRegionOfDefinition_public(inputEffect->getRenderHash(), time, scale, view, &inputRoD, 0);
if (stat != eStatusFailed) {
inputRoDSet = true;
}
}
roi = inputRoD;
}
}
}
if ( roi.isNull() ) {
return ImagePtr();
}
if (isIdentity) {
assert(identityInput.get() != this);
///If the effect is an identity but it didn't ask for the effect's image of which it is identity
///return a null image (only when non analysis)
if ( (identityInput != inputEffect) && !isAnalysisPass ) {
return ImagePtr();
}
}
///Does this node supports images at a scale different than 1
bool renderFullScaleThenDownscale = (!supportsRenderScale() && mipMapLevel != 0 && returnStorage == eStorageModeRAM);
///Do we want to render the graph upstream at scale 1 or at the requested render scale ? (user setting)
bool renderScaleOneUpstreamIfRenderScaleSupportDisabled = false;
unsigned int renderMappedMipMapLevel = mipMapLevel;
if (renderFullScaleThenDownscale) {
renderScaleOneUpstreamIfRenderScaleSupportDisabled = node->useScaleOneImagesWhenRenderScaleSupportIsDisabled();
if (renderScaleOneUpstreamIfRenderScaleSupportDisabled) {
renderMappedMipMapLevel = 0;
}
}
///Both the result of getRegionsOfInterest and optionalBounds are in canonical coordinates, we have to convert in both cases
///Convert to pixel coordinates
const double par = getAspectRatio(inputNb);
ImageBitDepthEnum depth = getBitDepth(inputNb);
ImagePlaneDesc components;
ImagePlaneDesc clipPrefComps, clipPrefMappedComps;
getMetadataComponents(inputNb, &clipPrefComps, &clipPrefMappedComps);
if (layer) {
components = *layer;
} else {
components = clipPrefComps;
}