Starting from 2021-07-01, all LRZ GitLab users will be required to explicitly accept the GitLab Terms of Service. Please see the detailed information at https://doku.lrz.de/display/PUBLIC/GitLab and make sure that your projects conform to the requirements.

abstractprocessor.h 16.3 KB
Newer Older
1 2
// ================================================================================================
// 
schultezub's avatar
schultezub committed
3
// This file is part of the CAMPVis Software Framework.
4
// 
5
// If not explicitly stated otherwise: Copyright (C) 2012-2015, all rights reserved,
schultezub's avatar
schultezub committed
6
//      Christian Schulte zu Berge <christian.szb@in.tum.de>
7
//      Chair for Computer Aided Medical Procedures
8 9
//      Technische Universitaet Muenchen
//      Boltzmannstr. 3, 85748 Garching b. Muenchen, Germany
10
// 
schultezub's avatar
schultezub committed
11
// For a full list of authors and contributors, please refer to the file "AUTHORS.txt".
12
// 
13 14 15 16
// Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file 
// except in compliance with the License. You may obtain a copy of the License at
// 
// http://www.apache.org/licenses/LICENSE-2.0
17
// 
18 19 20 21
// Unless required by applicable law or agreed to in writing, software distributed under the 
// License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, 
// either express or implied. See the License for the specific language governing permissions 
// and limitations under the License.
22 23 24
// 
// ================================================================================================

schultezub's avatar
schultezub committed
25 26 27
#ifndef PROCESSOR_H__
#define PROCESSOR_H__

28 29
#include <tbb/atomic.h>
#include <tbb/concurrent_queue.h>
30 31 32
#include <tbb/spin_rw_mutex.h>

#include "sigslot/sigslot.h"
33
#include "cgt/logmanager.h"
34 35

#include "core/coreapi.h"
schultezub's avatar
schultezub committed
36
#include "core/datastructures/datacontainer.h"
schultezub's avatar
schultezub committed
37 38
#include "core/properties/propertycollection.h"

39
#include <chrono>
40
#include <unordered_map>
schultezub's avatar
schultezub committed
41 42
#include <string>
#include <vector>
schultezub's avatar
schultezub committed
43

schultezub's avatar
schultezub committed
44
namespace campvis {
schultezub's avatar
schultezub committed
45 46
    class AbstractProperty;

schultezub's avatar
schultezub committed
47
    /**
schultezub's avatar
schultezub committed
48
     * Abstract base class for CAMPVis Processors.
49 50 51 52 53 54 55 56
     * A processor implements a specific task, which it performs on the DataCollection passed
     * during process(). Properties provide a transparent layer for adjusting the processor's 
     * behaviour.
     * Once a processor has finished it sets it should set its invalidation level to valid. As
     * soon as one of its properties changes, the processor will be notified and possibliy
     * change its invalidation level. Observing pipelines will be notified of this and can
     * and have to decide which part of the pipeline has to be re-evaluated wrt. the processor's
     * invalidation level.
schultezub's avatar
schultezub committed
57 58 59
     * 
     * \sa AbstractPipeline
     */
60
    class CAMPVIS_CORE_API AbstractProcessor : public HasPropertyCollection {
schultezub's avatar
schultezub committed
61
    public:
62 63 64 65 66 67 68 69 70
        /**
         * Scoped lock of an AbstractProcessor that automatically unlocks the processor on destruction.
         * Useful for exception safety.
         */
        struct CAMPVIS_CORE_API ScopedLock {
            /**
             * Constructs a new Scoped lock, locking \a p and unlocking \a p on destruction.
             * \param   p                   Processor to lock
             */
71
            explicit ScopedLock(AbstractProcessor* p) 
72 73 74 75
                : _p(p)
            {
                _p->lockProcessor();
            };
76 77

            /// Destructor, unlocks the processor
78 79 80
            ~ScopedLock() {
                _p->unlockProcessor();    
            };
81 82 83

            AbstractProcessor* _p;      ///< The processor to lock
        };
84
        
85

86 87 88 89
        /**
         * Available invalidation levels
         */
        enum InvalidationLevel {
90 91 92 93
            VALID               = 0,        ///< Valid, no need to run the process() method
            INVALID_RESULT      = 1 << 0,   ///< Need to run the updateResult() method
            INVALID_SHADER      = 1 << 1,   ///< Need to run the updateShader() method (e.g. to recompile the shader)
            INVALID_PROPERTIES  = 1 << 2,   ///< Need to run the updateProperties() method (e.g. to adjust property ranges)
94
            FIRST_FREE_TO_USE_INVALIDATION_LEVEL = 1 << 3
95
        };
96

97 98 99 100 101 102 103
        /// Current state of a processor in terms of stability.
        enum ProcessorState {
            EXPERIMENTAL,
            TESTING,
            STABLE
        };

schultezub's avatar
schultezub committed
104 105 106 107 108 109 110 111 112 113 114
        /**
         * Creates a AbstractProcessor.
         */
        AbstractProcessor();

        /**
         * Virtual Destructor
         **/
        virtual ~AbstractProcessor();


schultezub's avatar
schultezub committed
115
        /**
116 117 118
         * Initializes the processor.
         * Everything that requires a valid OpenGL context or is otherwise expensive gets in here.
         * 
schultezub's avatar
schultezub committed
119 120 121
         * \note    When overwriting this method, make sure to call the base class version first.
         */
        virtual void init();
122 123
        
        /**
schultezub's avatar
schultezub committed
124
         * Deinitializes this processor.
125
         * \note    When overwriting this method, make sure to call the base class version at the end.
126 127
         */
        virtual void deinit();
schultezub's avatar
schultezub committed
128

129 130 131 132 133 134
        /**
         * Gets the name of this very processor. To be defined by every subclass.
         * \return  The name of this processor.
         */
        virtual const std::string getName() const = 0;

135 136 137 138 139 140
        /**
         * Gets a description of this processor. To be defined by every subclass.
         * \return  A description what this processor does.
         */
        virtual const std::string getDescription() const = 0;

141 142 143 144 145 146 147 148 149 150
        /**
         * Gets the name of the author of this processor. Can be handy if you have questions on how to do XYZ with this processor.
         * \return  The name of the author of this processor.
         */
        virtual const std::string getAuthor() const = 0;

        /**
         * Gets the current processor state in terms of stability. To be defined by every subclass.
         * \return  The current processor state in terms of stability.
         */
151
        virtual ProcessorState getProcessorState() const = 0;
152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174

        /**
         * Gets the name of the instance, to be used to disambiguate several instances of the same
         * processor.
         * \return _instanceName
         */
        std::string getInstanceName() const {
            return _instanceName;
        };

        /**
         * Sets the name of the instance.
         */
        void setInstanceName(const std::string& name) {
            _instanceName = name;
            s_instanceNameChanged.emitSignal();
        }

        /**
         * Signals when the instance name has changed. Useful for updating the GUI
         */
        sigslot::signal0 s_instanceNameChanged;

175 176 177 178 179 180 181 182
        /**
         * Registers \a prop as property with the provided invalidation level. Registered properties 
         * can be accessed from the outside, e.g. via getProperty(), and will automatically invalidate
         * this processor on change. An already existing property with the same name will be replaced.
         *
         * \param   prop                Property to add
         * \param   invalidationLevel   Invalidation level of this property
         */
183
        void addProperty(AbstractProperty& prop, int invalidationLevel = INVALID_RESULT);
184 185 186 187 188 189 190 191 192

        /**
         * Sets the property invalidation level to the specified value.
         *
         * \param   prop                Property whose invalidation level is to change.
         * \param   invalidationLevel   New invalidation level of this property
         */
        void setPropertyInvalidationLevel(AbstractProperty& prop, int invalidationLevel);

193 194 195 196 197 198 199
        /**
         * Execute this processor.
         * Locks the processor and calls updateShader(), updateProperties() and/or updateResult() 
         * with respect to the current invalidation level.
         * 
         * \param   data                DataContainer to work on.
         **/
200
        void process(DataContainer& data);
201

202 203 204 205 206 207 208 209 210 211
        /**
         * Forces the execution of this processor according to the given invalidation level and 
         * independent of its current invalidation level. Sets this processor's invalidation level
         * to \a invalidationLevel and then calles process().
         * 
         * \param   dataContainer       DataContainer to work on
         * \param   invalidationLevel   Invalidation level to enforce prior to calling process.
         */
        void forceProcess(DataContainer& dataContainer, int invalidationLevel);

212 213 214 215 216 217 218 219 220 221 222
        /**
         * Gets the flag whether this processor is currently enabled.
         * \return _enabled
         */
        bool getEnabled() const;

        /**
         * Sets the flag whether this processor is currently enabled.
         * \param   enabled     New flag whether this processor is currently enabled.
         */
        void setEnabled(bool enabled);
223 224 225 226 227 228 229 230 231 232 233 234

        /**
         * Returns whether to measure the execution time of this processor.
         * \return  _clockExecutionTime
         */
        bool getClockExecutionTime() const;

        /**
         * Sets whether to measure the execution time of this processor.
         * \param   value   The new flag vlaue whether to measure the execution time of this processor.
         */
        void setClockExecutionTime(bool value);
235

236 237 238 239 240 241 242 243 244 245
        /**
         *  Returns the absolute time of the last (timed) execution
         */
        std::chrono::high_resolution_clock::time_point getLastExecutionTime();

        /**
         *  Sets the absolute time of the last execution
         */
        void setLastExeuctionTime(const std::chrono::high_resolution_clock::time_point& executionTime);

246 247 248 249 250 251
        /**
         * Returns the current lockProcessor status of this processor.
         * If a processor is locked, all of its properties are locked and its process method must not be called.
         * \return  _locked != 0
         */
        bool isLocked();
252

253 254 255 256 257 258 259 260 261 262 263
// = Invalidation Level related stuff =============================================================

        /**
         * Returns the current invalidation level.
         * \return _level
         */
        int getInvalidationLevel() const {
            return _level;
        }

        /**
264
         * Returns whether the invalidation level is valid (i.e. no invalid flag is set).
265 266 267 268 269 270 271
         * \return _level == VALID
         */
        bool isValid() const {
            return _level == static_cast<int>(VALID);
        }

        /**
272
         * Returns whether the the INVALID_RESULT flag is set.
273 274 275 276 277 278 279
         * \return _level & INVALID_RESULT
         */
        bool hasInvalidResult() const {
            return (_level & static_cast<int>(INVALID_RESULT)) != 0;
        }

        /**
280
         * Returns whether the the INVALID_SHADER flag is set.
281 282 283 284 285 286 287
         * \return _level & INVALID_SHADER
         */
        bool hasInvalidShader() const {
            return (_level & static_cast<int>(INVALID_SHADER)) != 0;
        }

        /**
288
         * Returns whether the the INVALID_PROPERTIES flag is set.
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
         * \return _level & INVALID_PROPERTIES
         */
        bool hasInvalidProperties() const {
            return (_level & static_cast<int>(INVALID_PROPERTIES)) != 0;
        }

        /**
         * Sets the invalidation level to valid (i.e. clears all invalidation flags).
         */
        void setValid() {
            _level = static_cast<int>(VALID);
        }

        /**
         * Sets all invalidation flags specified in \a level.
         * \param   level   Flags to set to invalid.
         */
        void invalidate(int level);

        /**
         * Sets all invalidation flags specified in \a il's level.
         * \param   il  Flags to set to invalid.
         */
        void invalidate(InvalidationLevel il) {
            invalidate(static_cast<int>(il));
        }

        /**
         * Clears all invalidation flags specified in \a level.
         * \param   level   Flags to set to valid.
         */
        void validate(int level);

        /**
         * Clears all invalidation flags specified in \a il's level.
         * \param   il  Flags to set to valid.
         */
        void validate(InvalidationLevel il) {
            validate(static_cast<int>(il));
        }

330 331 332 333 334 335 336 337 338 339 340 341
        /**
         * Sets that incoming change signals from properties are ignored.
         * \see observePropertyChanges()
         */
        void ignorePropertyChanges();

        /**
         * Sets that incoming signals from properties are no longer ignored.
         * \see ignorePropertyChanges()
         */
        void observePropertyChanges();

schultezub's avatar
schultezub committed
342
        /// Signal emitted when the processor has been invalidated.
343
        sigslot::signal1<AbstractProcessor*> s_invalidated;
schultezub's avatar
schultezub committed
344

345 346 347
        /// Signal emitted when the processor has been validated.
        sigslot::signal1<AbstractProcessor*> s_validated;

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
    protected:
        /**
         * Gets called from default process() method when having an invalidation level of INVALID_SHADER.
         * 
         * Override this method for your needs, for instance if you need to recompile your shaders.
         * The default implementation only validates the INVALID_SHADER level again.
         */
        virtual void updateShader();

        /**
         * Gets called from default process() method when having an invalidation level of INVALID_PROPERTIES.
         * 
         * Override this method for your needs, for instance if you need to adjust your properties
         * to incoming data or other properties' settings. The default implementation only 
         * validates the INVALID_PROPERTIES level again.
         * 
         * \param   dc  DataContainer   The DataContainer of the calling pipeline.
         */
        virtual void updateProperties(DataContainer& dataContainer);

        /**
         * Implement this method to your needs to compute the result/output of your processor.
         * This method is considered to contain the actual algorithm each processor realizes. It 
         * gets called from default process() method when having an invalidation level of 
         * INVALID_RESULT.
         * 
         * \note    The default implementation only validates the INVALID_SHADER level again.
         * \param   dataContainer   The DataContainer to work on.
         */
        virtual void updateResult(DataContainer& dataContainer) = 0;
378
        
379 380 381 382 383 384 385 386 387 388 389 390 391
        /**
         * 
         * Locks all properties in the processor's PropertyCollection and marks them as "in use".
         * \sa  AbstractProcessor::unlockProcessor
         */
        void lockProcessor();

        /**
         * Unlocks all properties in the processor's PropertyCollection and marks them as "not in use".
         * \sa  AbstractProcessor::lockProcessor
         */
        void unlockProcessor();

392 393
// = Slots ========================================================================================

schultezub's avatar
schultezub committed
394 395 396 397 398 399
        /**
         * Slot getting called when one of the observed properties changed and notifies its observers.
         * \param   prop    Property that emitted the signal
         */
        virtual void onPropertyChanged(const AbstractProperty* prop);

400
        tbb::atomic<bool> _enabled;                 ///< flag whether this processor is currently enabled
401
        tbb::atomic<bool> _clockExecutionTime;      ///< flag whether to measure the execution time of this processor
402
        std::chrono::high_resolution_clock::time_point _lastExecutionTime; ///< time of last execution
403
        tbb::atomic<int> _ignorePropertyChanges;    ///< flag whether signals from properties shall be ignored
404 405 406 407

        /// Flag whether this processor is currently locked
        /// (This implies, that all properties are locked and it is not valid to call process())
        tbb::atomic<bool> _locked;
schultezub's avatar
schultezub committed
408

409 410 411 412
        tbb::spin_rw_mutex _mtxInvalidationMap;     ///< Mutex protecting _invalidationMap
        /// Hash map storing the invalidation levels for each registered property
        std::unordered_map<const AbstractProperty*, int> _invalidationMap;

413
    private:
414 415
        tbb::atomic<int> _level;            ///< current invalidation level
        tbb::concurrent_queue<int> _queuedInvalidations;
416

417 418
        std::string _instanceName; ///< instance name displayed in the GUI

Jakob Weiss's avatar
Jakob Weiss committed
419 420 421 422 423
#ifdef _DEBUG
        bool _baseInitWasCalled; ///< This is used for debug checks to make sure subclasses call init/deinit
        bool _baseDeinitWasCalled; ///< This is used for debug checks to make sure subclasses call init/deinit
#endif

424
        static const std::string loggerCat_;
schultezub's avatar
schultezub committed
425 426 427 428 429
    };

}

#endif // PROCESSOR_H__