scene.C 12.5 KB
Newer Older
1 2 3 4
/*---------------------------------------------------------------------------*\
  =========                 |
  \\      /  F ield         | OpenFOAM: The Open Source CFD Toolbox
   \\    /   O peration     |
5
    \\  /    A nd           | Copyright (C) 2015-2016 OpenCFD Ltd.
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
     \\/     M anipulation  |
-------------------------------------------------------------------------------
License
    This file is part of OpenFOAM.

    OpenFOAM 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 3 of the License, or
    (at your option) any later version.

    OpenFOAM 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 OpenFOAM.  If not, see <http://www.gnu.org/licenses/>.

\*---------------------------------------------------------------------------*/

// OpenFOAM includes
#include "scene.H"
#include "Constant.H"

// VTK includes
#include "vtkCamera.h"
#include "vtkCubeSource.h"
#include "vtkLightKit.h"
#include "vtkPolyDataMapper.h"
#include "vtkPNGWriter.h"
#include "vtkRenderer.h"
#include "vtkRendererCollection.h"
#include "vtkRenderWindow.h"
#include "vtkWindowToImageFilter.h"

// * * * * * * * * * * * * Static Member Functions * * * * * * * * * * * * * //

namespace Foam
{
    template<>
46 47 48 49 50
    const char* NamedEnum
    <
        functionObjects::runTimePostPro::scene::modeType,
        2
    >::names[] =
51 52 53 54 55 56
    {
        "static",
        "flightPath"
    };
}

57 58 59 60 61
const Foam::NamedEnum
<
    Foam::functionObjects::runTimePostPro::scene::modeType,
    2
> modeTypeNames_;
62 63 64 65


// * * * * * * * * * * * * * Private Member Functions  * * * * * * * * * * * //

66 67 68 69
void Foam::functionObjects::runTimePostPro::scene::readCamera
(
    const dictionary& dict
)
70 71 72 73 74
{
    if (dict.readIfPresent("nFrameTotal", nFrameTotal_))
    {
        if (nFrameTotal_ < 1)
        {
75 76
            FatalIOErrorInFunction(dict)
                << "nFrameTotal must be 1 or greater"
77 78 79 80
                << exit(FatalIOError);
        }
    }

81
    if (dict.readIfPresent("startPosition", startPosition_))
82
    {
83
        if ((startPosition_ < 0) || (startPosition_ > 1))
84
        {
85 86
            FatalIOErrorInFunction(dict)
                << "startPosition must be in the range 0-1"
87 88
                << exit(FatalIOError);
        }
89 90 91 92
        else
        {
            position_ = startPosition_;
        }
93 94 95 96 97 98 99 100 101 102
    }


    dict.lookup("parallelProjection") >> parallelProjection_;

    if (nFrameTotal_ > 1)
    {
        scalar endPosition = dict.lookupOrDefault<scalar>("endPosition", 1);
        if ((endPosition < 0) || (endPosition > 1))
        {
103 104
            FatalIOErrorInFunction(dict)
                << "endPosition must be in the range 0-1"
105 106
                << exit(FatalIOError);
        }
107
        dPosition_ = (endPosition - startPosition_)/scalar(nFrameTotal_ - 1);
108 109 110 111 112 113 114 115 116 117 118 119 120
    }

    mode_ = modeTypeNames_.read(dict.lookup("mode"));

    word coeffsName = modeTypeNames_[mode_] + word("Coeffs");
    const dictionary& coeffs = dict.subDict(coeffsName);

    switch (mode_)
    {
        case mtStatic:
        {
            clipBox_ = boundBox(coeffs.lookup("clipBox"));
            const vector lookDir(vector(coeffs.lookup("lookDir")));
121 122 123 124
            cameraPosition_.reset
            (
                new Function1Types::Constant<point>("position", -lookDir)
            );
125 126 127
            const vector focalPoint(coeffs.lookup("focalPoint"));
            cameraFocalPoint_.reset
            (
128
                new Function1Types::Constant<point>("focalPoint", focalPoint)
129 130
            );
            const vector up(coeffs.lookup("up"));
131
            cameraUp_.reset(new Function1Types::Constant<point>("up", up));
132 133 134 135 136 137
            if (nFrameTotal_ > 1)
            {
                WarningInFunction
                    << "Static mode with nFrames > 1 - please check your setup"
                    << endl;
            }
138 139 140 141 142 143
            break;
        }
        case mtFlightPath:
        {
            cameraPosition_.reset
            (
144
                Function1<vector>::New("position", coeffs).ptr()
145 146 147
            );
            cameraFocalPoint_.reset
            (
148
                Function1<point>::New("focalPoint", coeffs).ptr()
149
            );
150
            cameraUp_.reset(Function1<vector>::New("up", coeffs).ptr());
151 152 153 154
            break;
        }
        default:
        {
155
            FatalErrorInFunction
156 157 158 159 160 161 162
                << "Unhandled enumeration " << modeTypeNames_[mode_]
                << abort(FatalError);
        }
    }

    if (dict.found("zoom"))
    {
163
        cameraZoom_.reset(Function1<scalar>::New("zoom", dict).ptr());
164 165 166
    }
    else
    {
167
        cameraZoom_.reset(new Function1Types::Constant<scalar>("zoom", 1.0));
168 169 170 171
    }

    if (dict.found("viewAngle"))
    {
172
        cameraViewAngle_.reset(Function1<scalar>::New("viewAngle", dict).ptr());
173 174 175
    }
    else
    {
176 177 178 179
        cameraViewAngle_.reset
        (
            new Function1Types::Constant<scalar>("viewAngle", 35.0)
        );
180 181 182 183
    }
}


184 185 186 187
void Foam::functionObjects::runTimePostPro::scene::readColours
(
    const dictionary& dict
)
188 189 190 191 192
{
    const wordList colours = dict.toc();
    forAll(colours, i)
    {
        const word& c = colours[i];
193
        colours_.insert(c, Function1<vector>::New(c, dict).ptr());
194 195 196 197
    }
}


198 199 200 201 202
void Foam::functionObjects::runTimePostPro::scene::initialise
(
    vtkRenderer* renderer,
    const word& outputName
)
203 204
{
    currentFrameI_ = 0;
205
    position_ = startPosition_;
206 207 208 209

    outputName_ = outputName;

    // Set the background
210
    const vector backgroundColour = colours_["background"]->value(position_);
211 212 213 214 215 216 217 218 219 220 221
    renderer->SetBackground
    (
        backgroundColour.x(),
        backgroundColour.y(),
        backgroundColour.z()
    );

    // Apply gradient background if "background2" defined
    if (colours_.found("background2"))
    {
        renderer->GradientBackgroundOn();
222
        vector backgroundColour2 = colours_["background2"]->value(position_);
223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242

        renderer->SetBackground2
        (
            backgroundColour2.x(),
            backgroundColour2.y(),
            backgroundColour2.z()
        );
    }

    // Depth peeling
    renderer->SetUseDepthPeeling(true);
    renderer->SetMaximumNumberOfPeels(4);
    renderer->SetOcclusionRatio(0);

    // Set the camera
    vtkSmartPointer<vtkCamera> camera = vtkSmartPointer<vtkCamera>::New();
    camera->SetParallelProjection(parallelProjection_);
    renderer->SetActiveCamera(camera);


243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259
    // Initialise the camera
    const vector up = cameraUp_->value(position_);
    const vector pos = cameraPosition_->value(position_);
    const point focalPoint = cameraFocalPoint_->value(position_);

    camera->SetViewUp(up.x(), up.y(), up.z());
    camera->SetPosition(pos.x(), pos.y(), pos.z());
    camera->SetFocalPoint(focalPoint.x(), focalPoint.y(), focalPoint.z());
    camera->Modified();


    // Add the lights
    vtkSmartPointer<vtkLightKit> lightKit = vtkSmartPointer<vtkLightKit>::New();
    lightKit->AddLightsToRenderer(renderer);


    // For static mode initialise the clip box
260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280
    if (mode_ == mtStatic)
    {
        const point& min = clipBox_.min();
        const point& max = clipBox_.max();
        vtkSmartPointer<vtkCubeSource> clipBox =
            vtkSmartPointer<vtkCubeSource>::New();
        clipBox->SetXLength(max.x() - min.x());
        clipBox->SetYLength(max.y() - min.y());
        clipBox->SetZLength(max.z() - min.z());
        clipBox->SetCenter
        (
            min.x() + 0.5*(max.x() - min.x()),
            min.y() + 0.5*(max.y() - min.y()),
            min.z() + 0.5*(max.z() - min.z())
        );
        vtkSmartPointer<vtkPolyDataMapper> clipMapper =
            vtkSmartPointer<vtkPolyDataMapper>::New();
        clipMapper->SetInputConnection(clipBox->GetOutputPort());

        vtkSmartPointer<vtkActor> clipActor = vtkSmartPointer<vtkActor>::New();
        clipActor->SetMapper(clipMapper);
281
        clipActor->VisibilityOff();
282 283
        renderer->AddActor(clipActor);

284 285
        // Call resetCamera to fit clip box in view
        clipActor->VisibilityOn();
286 287 288 289 290 291
        renderer->ResetCamera();
        clipActor->VisibilityOff();
    }
}


292 293 294 295
void Foam::functionObjects::runTimePostPro::scene::setCamera
(
    vtkRenderer* renderer
) const
296
{
297
    if (mode_ == mtFlightPath)
298
    {
299 300 301
        const vector up = cameraUp_->value(position_);
        const vector pos = cameraPosition_->value(position_);
        const point focalPoint = cameraFocalPoint_->value(position_);
302

303
        vtkCamera* camera = renderer->GetActiveCamera();
304 305 306 307
        camera->SetViewUp(up.x(), up.y(), up.z());
        camera->SetPosition(pos.x(), pos.y(), pos.z());
        camera->SetFocalPoint(focalPoint.x(), focalPoint.y(), focalPoint.z());
        camera->Modified();
308
    }
309

310 311 312 313 314 315
    if (!parallelProjection_)
    {
        // Restore viewAngle (it might be reset by clipping)
        vtkCamera* camera = renderer->GetActiveCamera();
        camera->SetViewAngle(cameraViewAngle_->value(position_));
        camera->Modified();
316 317 318 319
    }
}


320 321
Foam::string
Foam::functionObjects::runTimePostPro::scene::frameIndexStr() const
322 323 324 325 326 327 328 329 330 331
{
    string str = Foam::name(currentFrameI_);
    str.insert(0, 4 - str.length(), '0');

    return str;
}


// * * * * * * * * * * * * * * * * Constructors  * * * * * * * * * * * * * * //

332 333 334 335 336
Foam::functionObjects::runTimePostPro::scene::scene
(
    const objectRegistry& obr,
    const word& name
)
337 338 339 340 341 342 343 344 345 346 347 348
:
    obr_(obr),
    name_(name),
    colours_(),
    mode_(mtStatic),
    cameraPosition_(NULL),
    cameraFocalPoint_(NULL),
    cameraUp_(NULL),
    cameraViewAngle_(NULL),
    clipBox_(),
    parallelProjection_(true),
    nFrameTotal_(1),
349
    startPosition_(0),
350 351 352 353 354 355 356 357 358
    position_(0),
    dPosition_(0),
    currentFrameI_(0),
    outputName_("unknown")
{}


// * * * * * * * * * * * * * * * * Destructor  * * * * * * * * * * * * * * * //

359
Foam::functionObjects::runTimePostPro::scene::~scene()
360 361 362 363 364
{}


// * * * * * * * * * * * * * * * Member Functions  * * * * * * * * * * * * * //

365
const Foam::HashPtrTable<Foam::Function1<Foam::vector>, Foam::word>&
366
Foam::functionObjects::runTimePostPro::scene::colours() const
367 368 369 370 371
{
    return colours_;
}


372
Foam::label Foam::functionObjects::runTimePostPro::scene::frameIndex() const
373 374 375 376 377
{
    return currentFrameI_;
}


378
Foam::scalar Foam::functionObjects::runTimePostPro::scene::position() const
379 380 381 382 383
{
    return position_;
}


384
void Foam::functionObjects::runTimePostPro::scene::read(const dictionary& dict)
385 386 387 388 389 390
{
    readCamera(dict.subDict("camera"));
    readColours(dict.subDict("colours"));
}


391
bool Foam::functionObjects::runTimePostPro::scene::loop(vtkRenderer* renderer)
392 393
{
    static bool initialised = false;
394
    setCamera(renderer);
395 396 397 398 399 400 401

    if (!initialised)
    {
        initialised = true;
        return true;
    }

402 403 404 405
    // Ensure that all objects can be seen without clipping
    // Note: can only be done after all objects have been added!
    renderer->ResetCameraClippingRange();

406 407 408 409 410
    // Save image from last iteration
    saveImage(renderer->GetRenderWindow());

    currentFrameI_++;

411
    position_ = startPosition_ + currentFrameI_*dPosition_;
412

413 414 415 416 417 418
    if (currentFrameI_ < nFrameTotal_)
    {
        return true;
    }
    else
    {
419
        initialised = false;
420 421 422 423 424
        return false;
    }
}


425 426 427 428
void Foam::functionObjects::runTimePostPro::scene::saveImage
(
    vtkRenderWindow* renderWindow
) const
429 430 431 432 433 434
{
    if (!renderWindow)
    {
        return;
    }

435 436 437 438 439 440
    const Time& runTime = obr_.time();

    fileName prefix(Pstream::parRun() ?
        runTime.path()/".."/"postProcessing"/name_/obr_.time().timeName() :
        runTime.path()/"postProcessing"/name_/obr_.time().timeName());

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
    mkDir(prefix);

    renderWindow->Render();

    // Set up off-screen rendering
    vtkSmartPointer<vtkWindowToImageFilter> windowToImageFilter =
        vtkSmartPointer<vtkWindowToImageFilter>::New();

    windowToImageFilter->SetInput(renderWindow);

    //// Add alpha channel for transparency
    // windowToImageFilter->SetInputBufferTypeToRGBA();
    windowToImageFilter->SetInputBufferTypeToRGB();

//    windowToImageFilter->ReadFrontBufferOff();
    windowToImageFilter->Update();

    // Save the image
    vtkSmartPointer<vtkPNGWriter> writer = vtkSmartPointer<vtkPNGWriter>::New();
    fileName fName(prefix/outputName_ + '.' + frameIndexStr() + ".png");
    writer->SetFileName(fName.c_str());
    writer->SetInputConnection(windowToImageFilter->GetOutputPort());

    Info<< "    Generating image: " << fName << endl;

    writer->Write();
}


// ************************************************************************* //