<commit_before>#include "Bumblebee2.h"
#include <stdio.h>
#include "sensors/camera3D/imgUtils.h"
#include <opencv2/highgui/highgui.hpp>
#include "sensors/camera3D/imgUtils.h"
#include <unistd.h>

using namespace FlyCapture2;
using namespace cv;

Bumblebee2::Bumblebee2(): _running(true), _images(), _cam()
{
    StartCamera();
}

int Bumblebee2::StartCamera()
{
    const Mode k_fmt7Mode = MODE_3;
    const PixelFormat k_fmt7PixFmt = PIXEL_FORMAT_RAW16;
    Error error;

    BusManager busMgr;
    unsigned int numCameras;
    error = busMgr.GetNumOfCameras(&numCameras);
    printf("Number of cameras detected: %u\n", numCameras);
    if (error != PGRERROR_OK)
    {
        PrintError( error );
        return -1;
    }

    if ( numCameras < 1 )
    {
        printf( "Insufficient number of cameras... exiting\n" );
        return -1;
    }

    PGRGuid guid;
    error = busMgr.GetCameraFromIndex(0, &guid);
    if (error != PGRERROR_OK)
    {
        PrintError( error );
        return -1;
    }

    // Connect to a camera
    error = _cam.Connect(&guid);
    if (error != PGRERROR_OK)
    {
        PrintError( error );
        return -1;
    }

    // Query for available Format 7 modes
    Format7Info fmt7Info;
    bool supported;
    fmt7Info.mode = k_fmt7Mode;
    error = _cam.GetFormat7Info( &fmt7Info, &supported );
    if (error != PGRERROR_OK)
    {
        PrintError( error );
        return -1;
    }

    Format7ImageSettings fmt7ImageSettings;
    fmt7ImageSettings.mode = k_fmt7Mode;
    fmt7ImageSettings.offsetX = 0;
    fmt7ImageSettings.offsetY = 0;
    fmt7ImageSettings.width = fmt7Info.maxWidth;
    fmt7ImageSettings.height = fmt7Info.maxHeight;
    fmt7ImageSettings.pixelFormat = k_fmt7PixFmt;

    bool valid;
    Format7PacketInfo fmt7PacketInfo;

    // Validate the settings to make sure that they are valid
    error = _cam.ValidateFormat7Settings(
        &fmt7ImageSettings,
        &valid,
        &fmt7PacketInfo );
    if (error != PGRERROR_OK)
    {
        PrintError( error );
        return -1;
    }

    if ( !valid )
    {
        // Settings are not valid
		printf("Format7 settings are not valid\n");
        return -1;
    }

    // Set the settings to the camera

    error = _cam.SetFormat7Configuration(
        &fmt7ImageSettings,
        fmt7PacketInfo.recommendedBytesPerPacket );
    if (error != PGRERROR_OK)
    {
        PrintError( error );
        return -1;
    }

    // Start capturing images
    error = _cam.StartCapture(&ProcessFrame, this);
    if (error != PGRERROR_OK)
    {
        PrintError( error );
        return -1;
    }

/*
    error = _cam.SetCallback(&ProcessFrame, this);
    if (error != PGRERROR_OK)
    {
        PrintError( error );
        return -1;
    }
*/
}

/*
void Bumblebee2::ProcessFrame(Image* rawImage, const void* otherThings)
{
        Image savedRaw;
        Error error;
        Mat right, left;
        error = savedRaw.DeepCopy((const Image*) &rawImage);
        if (error != PGRERROR_OK)
        {
            PrintError( error );
            return;
        }

        // Get the raw image dimensions
        PixelFormat pixFormat;
        unsigned int rows, cols, stride;
        savedRaw.GetDimensions( &rows, &cols, &stride, &pixFormat );

	// Create a converted image
        Image convertedImage;

        // Convert the raw image
        error = savedRaw.Convert( PIXEL_FORMAT_BGR, &convertedImage );
        if (error != PGRERROR_OK)
        {
            PrintError( error );
            return;
        }

        ptgrey2opencv(convertedImage,right);

		unsigned char* data = savedRaw.GetData();
		for(int i = 1; i < savedRaw.GetDataSize(); i += 2)
		{
            char tmp = data[i];
			data[i] = data[i-1];
			data[i-1] = tmp;
		}

        error = savedRaw.Convert( PIXEL_FORMAT_BGR, &convertedImage );
        if (error != PGRERROR_OK)
        {
            PrintError( error );
            return;
        }

        ptgrey2opencv(convertedImage, left);
        return;

}
*/

int Bumblebee2::Run()
{
    Mat left;
    Mat right;
    Error error;

    // Retrieve frame rate property
    Property frmRate;
    frmRate.type = FRAME_RATE;
    error = _cam.GetProperty( &frmRate );
    if (error != PGRERROR_OK)
    {
        PrintError( error );
        return -1;
    }

    //printf( "Frame rate is %3.2f fps\n", frmRate.absValue );

    Image rawImage;
    Image savedRaw;
    namedWindow( "leftDisp", CV_WINDOW_AUTOSIZE );
    namedWindow( "rightDisp", CV_WINDOW_AUTOSIZE );
    //trash first frame
    error = _cam.RetrieveBuffer((FlyCapture2::Image*) &rawImage);

    while(1)
    {
        // Retrieve an image
        error = _cam.RetrieveBuffer((FlyCapture2::Image*) &rawImage);
        if (error != PGRERROR_OK)
        {
            PrintError( error );
            continue;
        }
        error = savedRaw.DeepCopy((const Image*) &rawImage);
        if (error != PGRERROR_OK)
        {
            PrintError( error );
            continue;
        }

        // Get the raw image dimensions
        PixelFormat pixFormat;
        unsigned int rows, cols, stride;
        savedRaw.GetDimensions( &rows, &cols, &stride, &pixFormat );

	// Create a converted image
        Image convertedImage;

        // Convert the raw image
        error = savedRaw.Convert( PIXEL_FORMAT_BGR, &convertedImage );
        if (error != PGRERROR_OK)
        {
            PrintError( error );
            return -1;
        }

        ptgrey2opencv(convertedImage,right);

		unsigned char* data = savedRaw.GetData();
		for(int i = 1; i < savedRaw.GetDataSize(); i += 2)
		{
            char tmp = data[i];
			data[i] = data[i-1];
			data[i-1] = tmp;
		}

        error = savedRaw.Convert( PIXEL_FORMAT_BGR, &convertedImage );
        if (error != PGRERROR_OK)
        {
            PrintError( error );
            return -1;
        }

        ptgrey2opencv(convertedImage, left);
        //convertedImage.Save("/home/robojackets/Desktop/pgright.png");
        imshow( "leftDisp", left);
        imshow( "rightDisp", right);
        //imwrite("/home/robojackets/Desktop/right.png",right);
        //imwrite("/home/robojackets/Desktop/left.png",left);
        if(waitKey(30) >= 0) break;
    }

    CloseCamera();

	return 0;
}

int Bumblebee2::CloseCamera()
{
    Error error;
    // Stop capturing images
    error = _cam.StopCapture();
    if (error != PGRERROR_OK)
    {
        PrintError( error );
        return -1;
    }

    // Disconnect the camera
    error = _cam.Disconnect();
    if (error != PGRERROR_OK)
    {
        PrintError( error );
        return -1;
    }
}

void Bumblebee2::ptgrey2opencv(FlyCapture2::Image& img, cv::Mat& mat)
{
    Mat newMat = cv::Mat(img.GetRows(), img.GetCols(), CV_8UC3, img.GetData(), cv::Mat::AUTO_STEP);
    mat = newMat.clone();
    return;
}

void Bumblebee2::Running(bool newState)
{
    _running = newState;
}

bool Bumblebee2::Running(void)
{
    return _running;
}

Mat& Bumblebee2::Left()
{
    return _images.RightImage();
}

Mat& Bumblebee2::Right()
{
    return _images.LeftImage();
}

void Bumblebee2::LockImages()
{
    _imagesLock.lock();
}

void Bumblebee2::UnlockImages()
{
    _imagesLock.unlock();
}

StereoPair Bumblebee2::Images()
{
    return _images;
}

Bumblebee2::~Bumblebee2()
{
    //dtor
}

void ProcessFrame(Image* rawImage, const void* that)
{

    Bumblebee2&  thisHere= *((Bumblebee2*)that);
    Image savedRaw;
    Error error;
    Mat right, left;
    error = savedRaw.DeepCopy((const Image*) &rawImage);
    if (error != PGRERROR_OK)
    {
        PrintError( error );
        return;
    }

    // Get the raw image dimensions
    PixelFormat pixFormat;
    unsigned int rows, cols, stride;
    savedRaw.GetDimensions( &rows, &cols, &stride, &pixFormat );

// Create a converted image
    Image convertedImage;

    // Convert the raw image
    error = savedRaw.Convert( PIXEL_FORMAT_BGR, &convertedImage );
    if (error != PGRERROR_OK)
    {
        PrintError( error );
        return;
    }

    Bumblebee2::ptgrey2opencv(convertedImage,right);

    unsigned char* data = savedRaw.GetData();
    for(int i = 1; i < savedRaw.GetDataSize(); i += 2)
    {
        char tmp = data[i];
        data[i] = data[i-1];
        data[i-1] = tmp;
    }

    error = savedRaw.Convert( PIXEL_FORMAT_BGR, &convertedImage );
    if (error != PGRERROR_OK)
    {
        PrintError( error );
        return;
    }

    Bumblebee2::ptgrey2opencv(convertedImage, left);

    thisHere.LockImages();
    thisHere.Left() = left.clone();
    thisHere.Right() = right.clone();
    thisHere.UnlockImages();
    thisHere.onNewData(thisHere.Images());

    return;

}

void PrintError( FlyCapture2::Error error )
{
    error.PrintErrorTrace();
}
<commit_msg>finally fixed stuff<commit_after>#include "Bumblebee2.h"
#include <stdio.h>
#include "sensors/camera3D/imgUtils.h"
#include <opencv2/highgui/highgui.hpp>
#include "sensors/camera3D/imgUtils.h"
#include <unistd.h>

using namespace FlyCapture2;
using namespace cv;

Bumblebee2::Bumblebee2(): _running(true), _images(), _cam()
{
    StartCamera();
}

int Bumblebee2::StartCamera()
{
    const Mode k_fmt7Mode = MODE_3;
    const PixelFormat k_fmt7PixFmt = PIXEL_FORMAT_RAW16;
    Error error;

    BusManager busMgr;
    unsigned int numCameras;
    error = busMgr.GetNumOfCameras(&numCameras);
    printf("Number of cameras detected: %u\n", numCameras);
    if (error != PGRERROR_OK)
    {
        PrintError( error );
        return -1;
    }

    if ( numCameras < 1 )
    {
        printf( "Insufficient number of cameras... exiting\n" );
        return -1;
    }

    PGRGuid guid;
    error = busMgr.GetCameraFromIndex(0, &guid);
    if (error != PGRERROR_OK)
    {
        PrintError( error );
        return -1;
    }

    // Connect to a camera
    error = _cam.Connect(&guid);
    if (error != PGRERROR_OK)
    {
        PrintError( error );
        return -1;
    }

    // Query for available Format 7 modes
    Format7Info fmt7Info;
    bool supported;
    fmt7Info.mode = k_fmt7Mode;
    error = _cam.GetFormat7Info( &fmt7Info, &supported );
    if (error != PGRERROR_OK)
    {
        PrintError( error );
        return -1;
    }

    Format7ImageSettings fmt7ImageSettings;
    fmt7ImageSettings.mode = k_fmt7Mode;
    fmt7ImageSettings.offsetX = 0;
    fmt7ImageSettings.offsetY = 0;
    fmt7ImageSettings.width = fmt7Info.maxWidth;
    fmt7ImageSettings.height = fmt7Info.maxHeight;
    fmt7ImageSettings.pixelFormat = k_fmt7PixFmt;

    bool valid;
    Format7PacketInfo fmt7PacketInfo;

    // Validate the settings to make sure that they are valid
    error = _cam.ValidateFormat7Settings(
        &fmt7ImageSettings,
        &valid,
        &fmt7PacketInfo );
    if (error != PGRERROR_OK)
    {
        PrintError( error );
        return -1;
    }

    if ( !valid )
    {
        // Settings are not valid
		printf("Format7 settings are not valid\n");
        return -1;
    }

    // Set the settings to the camera

    error = _cam.SetFormat7Configuration(
        &fmt7ImageSettings,
        fmt7PacketInfo.recommendedBytesPerPacket );
    if (error != PGRERROR_OK)
    {
        PrintError( error );
        return -1;
    }

    // Start capturing images
    error = _cam.StartCapture(&ProcessFrame, this);
    if (error != PGRERROR_OK)
    {
        PrintError( error );
        return -1;
    }

/*
    error = _cam.SetCallback(&ProcessFrame, this);
    if (error != PGRERROR_OK)
    {
        PrintError( error );
        return -1;
    }
*/
}

/*
void Bumblebee2::ProcessFrame(Image* rawImage, const void* otherThings)
{
        Image savedRaw;
        Error error;
        Mat right, left;
        error = savedRaw.DeepCopy((const Image*) &rawImage);
        if (error != PGRERROR_OK)
        {
            PrintError( error );
            return;
        }

        // Get the raw image dimensions
        PixelFormat pixFormat;
        unsigned int rows, cols, stride;
        savedRaw.GetDimensions( &rows, &cols, &stride, &pixFormat );

	// Create a converted image
        Image convertedImage;

        // Convert the raw image
        error = savedRaw.Convert( PIXEL_FORMAT_BGR, &convertedImage );
        if (error != PGRERROR_OK)
        {
            PrintError( error );
            return;
        }

        ptgrey2opencv(convertedImage,right);

		unsigned char* data = savedRaw.GetData();
		for(int i = 1; i < savedRaw.GetDataSize(); i += 2)
		{
            char tmp = data[i];
			data[i] = data[i-1];
			data[i-1] = tmp;
		}

        error = savedRaw.Convert( PIXEL_FORMAT_BGR, &convertedImage );
        if (error != PGRERROR_OK)
        {
            PrintError( error );
            return;
        }

        ptgrey2opencv(convertedImage, left);
        return;

}
*/

/*

int Bumblebee2::Run()
{
    Mat left;
    Mat right;
    Error error;

    // Retrieve frame rate property
    Property frmRate;
    frmRate.type = FRAME_RATE;
    error = _cam.GetProperty( &frmRate );
    if (error != PGRERROR_OK)
    {
        PrintError( error );
        return -1;
    }

    //printf( "Frame rate is %3.2f fps\n", frmRate.absValue );

    Image rawImage;
    Image savedRaw;
    namedWindow( "leftDisp", CV_WINDOW_AUTOSIZE );
    namedWindow( "rightDisp", CV_WINDOW_AUTOSIZE );
    //trash first frame
    error = _cam.RetrieveBuffer((FlyCapture2::Image*) &rawImage);

    while(1)
    {
        // Retrieve an image
        error = _cam.RetrieveBuffer((FlyCapture2::Image*) &rawImage);
        if (error != PGRERROR_OK)
        {
            PrintError( error );
            continue;
        }
        error = savedRaw.DeepCopy((const Image*) &rawImage);
        if (error != PGRERROR_OK)
        {
            PrintError( error );
            continue;
        }

        // Get the raw image dimensions
        PixelFormat pixFormat;
        unsigned int rows, cols, stride;
        savedRaw.GetDimensions( &rows, &cols, &stride, &pixFormat );

	// Create a converted image
        Image convertedImage;

        // Convert the raw image
        error = savedRaw.Convert( PIXEL_FORMAT_BGR, &convertedImage );
        if (error != PGRERROR_OK)
        {
            PrintError( error );
            return -1;
        }

        ptgrey2opencv(convertedImage,right);

		unsigned char* data = savedRaw.GetData();
		for(int i = 1; i < savedRaw.GetDataSize(); i += 2)
		{
            char tmp = data[i];
			data[i] = data[i-1];
			data[i-1] = tmp;
		}

        error = savedRaw.Convert( PIXEL_FORMAT_BGR, &convertedImage );
        if (error != PGRERROR_OK)
        {
            PrintError( error );
            return -1;
        }

        ptgrey2opencv(convertedImage, left);
        //convertedImage.Save("/home/robojackets/Desktop/pgright.png");
        imshow( "leftDisp", left);
        imshow( "rightDisp", right);
        //imwrite("/home/robojackets/Desktop/right.png",right);
        //imwrite("/home/robojackets/Desktop/left.png",left);
        if(waitKey(30) >= 0) break;
    }

    CloseCamera();

	return 0;
}
*/
int Bumblebee2::CloseCamera()
{
    Error error;
    // Stop capturing images
    error = _cam.StopCapture();
    if (error != PGRERROR_OK)
    {
        PrintError( error );
        return -1;
    }

    // Disconnect the camera
    error = _cam.Disconnect();
    if (error != PGRERROR_OK)
    {
        PrintError( error );
        return -1;
    }
}

void Bumblebee2::ptgrey2opencv(FlyCapture2::Image& img, cv::Mat& mat)
{
    Mat newMat = cv::Mat(img.GetRows(), img.GetCols(), CV_8UC3, img.GetData(), cv::Mat::AUTO_STEP);
    mat = newMat.clone();
    return;
}

void Bumblebee2::Running(bool newState)
{
    _running = newState;
}

bool Bumblebee2::Running(void)
{
    return _running;
}

Mat& Bumblebee2::Left()
{
    return _images.RightImage();
}

Mat& Bumblebee2::Right()
{
    return _images.LeftImage();
}

void Bumblebee2::LockImages()
{
    _imagesLock.lock();
}

void Bumblebee2::UnlockImages()
{
    _imagesLock.unlock();
}

StereoPair Bumblebee2::Images()
{
    return _images;
}

Bumblebee2::~Bumblebee2()
{
    //dtor
}

void ProcessFrame(Image* rawImage, const void* that)
{
    Bumblebee2&  thisHere= *((Bumblebee2*)that);
    Image savedRaw;
    Error error;
    Mat right, left;
    error = savedRaw.DeepCopy((const Image*) rawImage);
    if (error != PGRERROR_OK)
    {
        PrintError( error );
        return;
    }

    // Get the raw image dimensions
    PixelFormat pixFormat;
    unsigned int rows, cols, stride;
    savedRaw.GetDimensions( &rows, &cols, &stride, &pixFormat );

// Create a converted image
    Image convertedImage;

    // Convert the raw image
    error = savedRaw.Convert( PIXEL_FORMAT_BGR, &convertedImage );
    if (error != PGRERROR_OK)
    {
        PrintError( error );
        return;
    }

    Bumblebee2::ptgrey2opencv(convertedImage,right);

    unsigned char* data = savedRaw.GetData();
    for(int i = 1; i < savedRaw.GetDataSize(); i += 2)
    {
        char tmp = data[i];
        data[i] = data[i-1];
        data[i-1] = tmp;
    }

    error = savedRaw.Convert( PIXEL_FORMAT_BGR, &convertedImage );
    if (error != PGRERROR_OK)
    {
        PrintError( error );
        return;
    }

    Bumblebee2::ptgrey2opencv(convertedImage, left);

    thisHere.LockImages();
    thisHere.Left() = left.clone();
    thisHere.Right() = right.clone();
    thisHere.UnlockImages();
    thisHere.onNewData(thisHere.Images());

    return;

}

void PrintError( FlyCapture2::Error error )
{
    error.PrintErrorTrace();
}
<|endoftext|>


<commit_before>//
// Copyright (c) 2010 Advanced Micro Devices, Inc. All rights reserved.
//

#ifndef VERSIONS_HPP_
#define VERSIONS_HPP_

#include "utils/macros.hpp"

#ifndef AMD_PLATFORM_NAME
#define AMD_PLATFORM_NAME "AMD Accelerated Parallel Processing"
#endif  // AMD_PLATFORM_NAME

#ifndef AMD_PLATFORM_BUILD_NUMBER
#define AMD_PLATFORM_BUILD_NUMBER 2436
#endif  // AMD_PLATFORM_BUILD_NUMBER

#ifndef AMD_PLATFORM_REVISION_NUMBER
#define AMD_PLATFORM_REVISION_NUMBER 0
#endif  // AMD_PLATFORM_REVISION_NUMBER

#ifndef AMD_PLATFORM_RELEASE_INFO
#define AMD_PLATFORM_RELEASE_INFO
#endif  // AMD_PLATFORM_RELEASE_INFO

#define AMD_BUILD_STRING                                                                           \
  XSTR(AMD_PLATFORM_BUILD_NUMBER)                                                                  \
  "." XSTR(AMD_PLATFORM_REVISION_NUMBER)

#ifndef AMD_PLATFORM_INFO
#define AMD_PLATFORM_INFO                                                                          \
  "AMD-APP" AMD_PLATFORM_RELEASE_INFO DEBUG_ONLY(                                                  \
      "." IF(IS_OPTIMIZED, "opt", "dbg")) " (" AMD_BUILD_STRING ")"
#endif  // ATI_PLATFORM_INFO

#endif  // VERSIONS_HPP_
<commit_msg>P4 to Git Change 1419768 by johtaylo@johtaylo-jtincrementor-increment on 2017/06/08 03:00:05<commit_after>//
// Copyright (c) 2010 Advanced Micro Devices, Inc. All rights reserved.
//

#ifndef VERSIONS_HPP_
#define VERSIONS_HPP_

#include "utils/macros.hpp"

#ifndef AMD_PLATFORM_NAME
#define AMD_PLATFORM_NAME "AMD Accelerated Parallel Processing"
#endif  // AMD_PLATFORM_NAME

#ifndef AMD_PLATFORM_BUILD_NUMBER
#define AMD_PLATFORM_BUILD_NUMBER 2437
#endif  // AMD_PLATFORM_BUILD_NUMBER

#ifndef AMD_PLATFORM_REVISION_NUMBER
#define AMD_PLATFORM_REVISION_NUMBER 0
#endif  // AMD_PLATFORM_REVISION_NUMBER

#ifndef AMD_PLATFORM_RELEASE_INFO
#define AMD_PLATFORM_RELEASE_INFO
#endif  // AMD_PLATFORM_RELEASE_INFO

#define AMD_BUILD_STRING                                                                           \
  XSTR(AMD_PLATFORM_BUILD_NUMBER)                                                                  \
  "." XSTR(AMD_PLATFORM_REVISION_NUMBER)

#ifndef AMD_PLATFORM_INFO
#define AMD_PLATFORM_INFO                                                                          \
  "AMD-APP" AMD_PLATFORM_RELEASE_INFO DEBUG_ONLY(                                                  \
      "." IF(IS_OPTIMIZED, "opt", "dbg")) " (" AMD_BUILD_STRING ")"
#endif  // ATI_PLATFORM_INFO

#endif  // VERSIONS_HPP_
<|endoftext|>


<commit_before>//
// Copyright (c) 2010 Advanced Micro Devices, Inc. All rights reserved.
//

#ifndef VERSIONS_HPP_
#define VERSIONS_HPP_

#include "utils/macros.hpp"

#ifndef AMD_PLATFORM_NAME
# define AMD_PLATFORM_NAME "AMD Accelerated Parallel Processing"
#endif // AMD_PLATFORM_NAME

#ifndef AMD_PLATFORM_BUILD_NUMBER
# define AMD_PLATFORM_BUILD_NUMBER 2233
#endif // AMD_PLATFORM_BUILD_NUMBER

#ifndef AMD_PLATFORM_REVISION_NUMBER
# define AMD_PLATFORM_REVISION_NUMBER 0
#endif // AMD_PLATFORM_REVISION_NUMBER

#ifndef AMD_PLATFORM_RELEASE_INFO
# define AMD_PLATFORM_RELEASE_INFO
#endif // AMD_PLATFORM_RELEASE_INFO

#define AMD_BUILD_STRING XSTR(AMD_PLATFORM_BUILD_NUMBER) \
    "." XSTR(AMD_PLATFORM_REVISION_NUMBER)

#ifndef AMD_PLATFORM_INFO
# define AMD_PLATFORM_INFO "AMD-APP" AMD_PLATFORM_RELEASE_INFO \
    DEBUG_ONLY("." IF(IS_OPTIMIZED,"opt","dbg")) " (" AMD_BUILD_STRING ")"
#endif // ATI_PLATFORM_INFO

#endif // VERSIONS_HPP_
<commit_msg>P4 to Git Change 1322095 by johtaylo@johtaylo-jtincrementor-increment on 2016/10/04 03:00:04<commit_after>//
// Copyright (c) 2010 Advanced Micro Devices, Inc. All rights reserved.
//

#ifndef VERSIONS_HPP_
#define VERSIONS_HPP_

#include "utils/macros.hpp"

#ifndef AMD_PLATFORM_NAME
# define AMD_PLATFORM_NAME "AMD Accelerated Parallel Processing"
#endif // AMD_PLATFORM_NAME

#ifndef AMD_PLATFORM_BUILD_NUMBER
# define AMD_PLATFORM_BUILD_NUMBER 2234
#endif // AMD_PLATFORM_BUILD_NUMBER

#ifndef AMD_PLATFORM_REVISION_NUMBER
# define AMD_PLATFORM_REVISION_NUMBER 0
#endif // AMD_PLATFORM_REVISION_NUMBER

#ifndef AMD_PLATFORM_RELEASE_INFO
# define AMD_PLATFORM_RELEASE_INFO
#endif // AMD_PLATFORM_RELEASE_INFO

#define AMD_BUILD_STRING XSTR(AMD_PLATFORM_BUILD_NUMBER) \
    "." XSTR(AMD_PLATFORM_REVISION_NUMBER)

#ifndef AMD_PLATFORM_INFO
# define AMD_PLATFORM_INFO "AMD-APP" AMD_PLATFORM_RELEASE_INFO \
    DEBUG_ONLY("." IF(IS_OPTIMIZED,"opt","dbg")) " (" AMD_BUILD_STRING ")"
#endif // ATI_PLATFORM_INFO

#endif // VERSIONS_HPP_
<|endoftext|>


<commit_before>//
// Copyright (c) 2010 Advanced Micro Devices, Inc. All rights reserved.
//

#ifndef VERSIONS_HPP_
#define VERSIONS_HPP_

#include "utils/macros.hpp"

#ifndef AMD_PLATFORM_NAME
# define AMD_PLATFORM_NAME "AMD Accelerated Parallel Processing"
#endif // AMD_PLATFORM_NAME

#ifndef AMD_PLATFORM_BUILD_NUMBER
# define AMD_PLATFORM_BUILD_NUMBER 1889
#endif // AMD_PLATFORM_BUILD_NUMBER

#ifndef AMD_PLATFORM_REVISION_NUMBER
# define AMD_PLATFORM_REVISION_NUMBER 0
#endif // AMD_PLATFORM_REVISION_NUMBER

#ifndef AMD_PLATFORM_RELEASE_INFO
# define AMD_PLATFORM_RELEASE_INFO
#endif // AMD_PLATFORM_RELEASE_INFO

#define AMD_BUILD_STRING XSTR(AMD_PLATFORM_BUILD_NUMBER) \
    "." XSTR(AMD_PLATFORM_REVISION_NUMBER)

#ifndef AMD_PLATFORM_INFO
# define AMD_PLATFORM_INFO "AMD-APP" AMD_PLATFORM_RELEASE_INFO \
    DEBUG_ONLY("." IF(IS_OPTIMIZED,"opt","dbg")) " (" AMD_BUILD_STRING ")"
#endif // ATI_PLATFORM_INFO

#endif // VERSIONS_HPP_
<commit_msg>P4 to Git Change 1189005 by johtaylo@johtaylo-JTBUILDER03-increment on 2015/09/09 03:00:13<commit_after>//
// Copyright (c) 2010 Advanced Micro Devices, Inc. All rights reserved.
//

#ifndef VERSIONS_HPP_
#define VERSIONS_HPP_

#include "utils/macros.hpp"

#ifndef AMD_PLATFORM_NAME
# define AMD_PLATFORM_NAME "AMD Accelerated Parallel Processing"
#endif // AMD_PLATFORM_NAME

#ifndef AMD_PLATFORM_BUILD_NUMBER
# define AMD_PLATFORM_BUILD_NUMBER 1890
#endif // AMD_PLATFORM_BUILD_NUMBER

#ifndef AMD_PLATFORM_REVISION_NUMBER
# define AMD_PLATFORM_REVISION_NUMBER 0
#endif // AMD_PLATFORM_REVISION_NUMBER

#ifndef AMD_PLATFORM_RELEASE_INFO
# define AMD_PLATFORM_RELEASE_INFO
#endif // AMD_PLATFORM_RELEASE_INFO

#define AMD_BUILD_STRING XSTR(AMD_PLATFORM_BUILD_NUMBER) \
    "." XSTR(AMD_PLATFORM_REVISION_NUMBER)

#ifndef AMD_PLATFORM_INFO
# define AMD_PLATFORM_INFO "AMD-APP" AMD_PLATFORM_RELEASE_INFO \
    DEBUG_ONLY("." IF(IS_OPTIMIZED,"opt","dbg")) " (" AMD_BUILD_STRING ")"
#endif // ATI_PLATFORM_INFO

#endif // VERSIONS_HPP_
<|endoftext|>


<commit_before>//
// Copyright (c) 2010 Advanced Micro Devices, Inc. All rights reserved.
//

#ifndef VERSIONS_HPP_
#define VERSIONS_HPP_

#include "utils/macros.hpp"

#ifndef AMD_PLATFORM_NAME
#define AMD_PLATFORM_NAME "AMD Accelerated Parallel Processing"
#endif  // AMD_PLATFORM_NAME

#ifndef AMD_PLATFORM_BUILD_NUMBER
#define AMD_PLATFORM_BUILD_NUMBER 3065
#endif  // AMD_PLATFORM_BUILD_NUMBER

#ifndef AMD_PLATFORM_REVISION_NUMBER
#define AMD_PLATFORM_REVISION_NUMBER 0
#endif  // AMD_PLATFORM_REVISION_NUMBER

#ifndef AMD_PLATFORM_RELEASE_INFO
#define AMD_PLATFORM_RELEASE_INFO
#endif  // AMD_PLATFORM_RELEASE_INFO

#define AMD_BUILD_STRING                                                                           \
  XSTR(AMD_PLATFORM_BUILD_NUMBER)                                                                  \
  "." XSTR(AMD_PLATFORM_REVISION_NUMBER)

#ifndef AMD_PLATFORM_INFO
#define AMD_PLATFORM_INFO                                                                          \
  "AMD-APP" AMD_PLATFORM_RELEASE_INFO DEBUG_ONLY(                                                  \
      "." IF(IS_OPTIMIZED, "opt", "dbg")) " (" AMD_BUILD_STRING ")"
#endif  // ATI_PLATFORM_INFO

#endif  // VERSIONS_HPP_
<commit_msg>P4 to Git Change 2049013 by chui@ocl-promo-incrementor on 2019/12/20 03:00:07<commit_after>//
// Copyright (c) 2010 Advanced Micro Devices, Inc. All rights reserved.
//

#ifndef VERSIONS_HPP_
#define VERSIONS_HPP_

#include "utils/macros.hpp"

#ifndef AMD_PLATFORM_NAME
#define AMD_PLATFORM_NAME "AMD Accelerated Parallel Processing"
#endif  // AMD_PLATFORM_NAME

#ifndef AMD_PLATFORM_BUILD_NUMBER
#define AMD_PLATFORM_BUILD_NUMBER 3066
#endif  // AMD_PLATFORM_BUILD_NUMBER

#ifndef AMD_PLATFORM_REVISION_NUMBER
#define AMD_PLATFORM_REVISION_NUMBER 0
#endif  // AMD_PLATFORM_REVISION_NUMBER

#ifndef AMD_PLATFORM_RELEASE_INFO
#define AMD_PLATFORM_RELEASE_INFO
#endif  // AMD_PLATFORM_RELEASE_INFO

#define AMD_BUILD_STRING                                                                           \
  XSTR(AMD_PLATFORM_BUILD_NUMBER)                                                                  \
  "." XSTR(AMD_PLATFORM_REVISION_NUMBER)

#ifndef AMD_PLATFORM_INFO
#define AMD_PLATFORM_INFO                                                                          \
  "AMD-APP" AMD_PLATFORM_RELEASE_INFO DEBUG_ONLY(                                                  \
      "." IF(IS_OPTIMIZED, "opt", "dbg")) " (" AMD_BUILD_STRING ")"
#endif  // ATI_PLATFORM_INFO

#endif  // VERSIONS_HPP_
<|endoftext|>


<commit_before>// Ylikuutio - A 3D game and simulation engine.
//
// Copyright (C) 2015-2019 Antti Nuortimo.
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU Affero General Public License as
// published by the Free Software Foundation, either version 3 of the
// License, or (at your option) any later version.
//
// This program 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 Affero General Public License for more details.
//
// You should have received a copy of the GNU Affero General Public License
// along with this program.  If not, see <https://www.gnu.org/licenses/>.

#ifndef PI
#define PI 3.14159265359f
#endif

#ifndef GLM_FORCE_RADIANS
#define GLM_FORCE_RADIANS
#define DEGREES_TO_RADIANS(x) (x * PI / 180.0f)
#endif

#include "scene.hpp"
#include "world.hpp"
#include "ground_level.hpp"
#include "shader.hpp"
#include "camera.hpp"
#include "render_templates.hpp"
#include "family_templates.hpp"
#include "code/ylikuutio/hierarchy/hierarchy_templates.hpp"
#include "code/ylikuutio/common/pi.hpp"

// Include standard headers
#include <cmath>         // NAN, std::isnan, std::pow
#include <cstddef>       // std::size_t
#include <iostream>      // std::cout, std::cin, std::cerr
#include <unordered_map> // std::unordered_map

namespace yli
{
    namespace ontology
    {
        class Species;

        void Scene::bind_shader(yli::ontology::Shader* const shader)
        {
            // get `childID` from `Scene` and set pointer to `shader`.
            yli::hierarchy::bind_child_to_parent<yli::ontology::Shader*>(
                    shader,
                    this->shader_pointer_vector,
                    this->free_shaderID_queue,
                    this->number_of_shaders);

            // `shader` needs to be added to the priority queue as well.
            this->shader_priority_queue.push(shader);
        }

        void Scene::bind_camera(yli::ontology::Camera* const camera)
        {
            // get `childID` from `Scene` and set pointer to `camera`.
            yli::hierarchy::bind_child_to_parent<yli::ontology::Camera*>(
                    camera,
                    this->camera_pointer_vector,
                    this->free_cameraID_queue,
                    this->number_of_cameras);
        }

        void Scene::unbind_shader(const std::size_t childID)
        {
            // `shader` needs to be removed from the priority queue as well.
            this->shader_priority_queue.remove(childID);

            yli::hierarchy::unbind_child_from_parent(
                    childID,
                    this->shader_pointer_vector,
                    this->free_shaderID_queue,
                    this->number_of_shaders);
        }

        void Scene::unbind_camera(const std::size_t childID)
        {
            yli::hierarchy::unbind_child_from_parent(
                    childID,
                    this->camera_pointer_vector,
                    this->free_cameraID_queue,
                    this->number_of_cameras);
        }

        void Scene::bind_to_parent()
        {
            // requirements:
            // `this->parent` must not be `nullptr`.
            yli::ontology::World* const world = this->parent;

            if (world == nullptr)
            {
                std::cerr << "ERROR: `Scene::bind_to_parent`: `world` is `nullptr`!\n";
                return;
            }

            // get `childID` from the `World` and set pointer to this `Scene`.
            world->bind_scene(this);
        }

        Scene::~Scene()
        {
            // destructor.
            std::cout << "Scene with childID " << std::dec << this->childID << " will be destroyed.\n";

            // destroy all `Shader`s of this `Scene`.
            std::cout << "All shaders of this scene will be destroyed.\n";
            yli::hierarchy::delete_children<yli::ontology::Shader*>(this->shader_pointer_vector, this->number_of_shaders);

            // destroy all `Camera`s of this `Scene`.
            std::cout << "All cameras of this scene will be destroyed.\n";
            yli::hierarchy::delete_children<yli::ontology::Camera*>(this->camera_pointer_vector, this->number_of_cameras);

            // requirements for further actions:
            // `this->parent` must not be `nullptr`.

            yli::ontology::World* const world = this->parent;

            if (world == nullptr)
            {
                std::cerr << "ERROR: `Scene::~Scene`: `world` is `nullptr`!\n";
                return;
            }

            if (world->get_active_scene() == this)
            {
                // Make this `Scene` no more the active `Scene`.
                this->parent->set_active_scene(nullptr);
            }

            // set pointer to this `Scene` to `nullptr`.
            world->unbind_scene(this->childID);
        }

        void Scene::render()
        {
            if (this->should_be_rendered)
            {
                this->prerender();

                // render this `Scene` by calling `render()` function of each `Shader`.
                yli::ontology::render_children<yli::ontology::Shader*>(this->shader_pointer_vector);

                this->postrender();
            }
        }

        yli::ontology::Camera* Scene::get_active_camera() const
        {
            return this->active_camera;
        }

        void Scene::set_active_camera(yli::ontology::Camera* camera)
        {
            yli::ontology::Camera* const old_active_camera = this->active_camera;

            if (this->universe != nullptr &&
                    old_active_camera != nullptr &&
                    !old_active_camera->get_is_static_view())
            {
                // OK, there is an old active `Camera`, and it is not a static view `Camera`.
                // Copy the coordinates and angles from the `Universe` to the old active `Camera`.
                old_active_camera->set_cartesian_coordinates(this->universe->current_camera_cartesian_coordinates);
                old_active_camera->set_horizontal_angle(this->universe->current_camera_horizontal_angle);
                old_active_camera->set_vertical_angle(this->universe->current_camera_vertical_angle);
            }

            // It is OK to disactivate the active camera by setting `active_camera` to `nullptr`.
            this->active_camera = camera;

            // requirements for further actions:
            // `this->universe` must not be `nullptr`.
            // `this->parent` must not be `nullptr`.

            if (this->universe == nullptr || this->parent == nullptr)
            {
                return;
            }

            yli::ontology::World* const active_world = this->universe->get_active_world();

            if (active_world == nullptr)
            {
                return;
            }

            yli::ontology::Scene* const active_scene = active_world->get_active_scene();

            if (active_scene == nullptr)
            {
                return;
            }

            if (active_scene == this)
            {
                if (this->active_camera != nullptr)
                {
                    this->universe->current_camera_cartesian_coordinates = camera->get_cartesian_coordinates();
                    this->universe->current_camera_horizontal_angle = camera->get_horizontal_angle();
                    this->universe->current_camera_vertical_angle = camera->get_vertical_angle();
                }
            }
        }

        yli::ontology::Entity* Scene::get_parent() const
        {
            return this->parent;
        }

        std::size_t Scene::get_number_of_children() const
        {
            return this->number_of_shaders + this->number_of_cameras;
        }

        std::size_t Scene::get_number_of_descendants() const
        {
            return yli::ontology::get_number_of_descendants(this->shader_pointer_vector) +
                yli::ontology::get_number_of_descendants(this->camera_pointer_vector);
        }

        // this method returns a pointer to an `Entity` using the name as key.
        yli::ontology::Entity* Scene::get_entity(const std::string name) const
        {
            if (this->name_map.count(name) != 1)
            {
                return nullptr;
            }

            return this->name_map.at(name);
        }

        float Scene::get_turbo_factor() const
        {
            if (this->parent != nullptr &&
                    this->universe != nullptr &&
                    this->parent == this->universe->get_active_world() &&
                    this == this->parent->get_active_scene())
            {
                return this->universe->turbo_factor;
            }

            return NAN;
        }

        void Scene::set_turbo_factor(float turbo_factor)
        {
            this->turbo_factor = turbo_factor;

            if (this->parent != nullptr &&
                    this->universe != nullptr &&
                    this->parent == this->universe->get_active_world() &&
                    this == this->parent->get_active_scene())
            {
                this->universe->turbo_factor = this->turbo_factor;
            }
        }

        float Scene::get_twin_turbo_factor() const
        {
            if (this->parent != nullptr &&
                    this->universe != nullptr &&
                    this->parent == this->universe->get_active_world() &&
                    this == this->parent->get_active_scene())
            {
                return this->universe->twin_turbo_factor;
            }

            return NAN;
        }

        void Scene::set_twin_turbo_factor(float twin_turbo_factor)
        {
            this->twin_turbo_factor = twin_turbo_factor;

            if (this->parent != nullptr &&
                    this->universe != nullptr &&
                    this->parent == this->universe->get_active_world() &&
                    this == this->parent->get_active_scene())
            {
                this->universe->twin_turbo_factor = this->twin_turbo_factor;
            }
        }

        yli::ontology::Species* Scene::get_terrain_species() const
        {
            if (this->parent != nullptr &&
                    this->universe != nullptr &&
                    this->parent == this->universe->get_active_world() &&
                    this == this->parent->get_active_scene())
            {
                return this->terrain_species;
            }

            return nullptr;
        }

        void Scene::set_terrain_species(yli::ontology::Species* const terrain_species)
        {
            this->terrain_species = terrain_species;

            if (this->parent != nullptr &&
                    this->universe != nullptr &&
                    this->parent == this->universe->get_active_world() &&
                    this == this->parent->get_active_scene())
            {
                this->universe->set_terrain_species(this->terrain_species);
            }
        }

        yli::ontology::World* Scene::get_world_parent() const
        {
            return this->parent;
        }

        float Scene::get_water_level() const
        {
            return this->water_level;
        }
    }
}
<commit_msg>`Scene::set_active_camera`: cleaning up code, and added comments.<commit_after>// Ylikuutio - A 3D game and simulation engine.
//
// Copyright (C) 2015-2019 Antti Nuortimo.
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU Affero General Public License as
// published by the Free Software Foundation, either version 3 of the
// License, or (at your option) any later version.
//
// This program 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 Affero General Public License for more details.
//
// You should have received a copy of the GNU Affero General Public License
// along with this program.  If not, see <https://www.gnu.org/licenses/>.

#ifndef PI
#define PI 3.14159265359f
#endif

#ifndef GLM_FORCE_RADIANS
#define GLM_FORCE_RADIANS
#define DEGREES_TO_RADIANS(x) (x * PI / 180.0f)
#endif

#include "scene.hpp"
#include "world.hpp"
#include "ground_level.hpp"
#include "shader.hpp"
#include "camera.hpp"
#include "render_templates.hpp"
#include "family_templates.hpp"
#include "code/ylikuutio/hierarchy/hierarchy_templates.hpp"
#include "code/ylikuutio/common/pi.hpp"

// Include standard headers
#include <cmath>         // NAN, std::isnan, std::pow
#include <cstddef>       // std::size_t
#include <iostream>      // std::cout, std::cin, std::cerr
#include <unordered_map> // std::unordered_map

namespace yli
{
    namespace ontology
    {
        class Species;

        void Scene::bind_shader(yli::ontology::Shader* const shader)
        {
            // get `childID` from `Scene` and set pointer to `shader`.
            yli::hierarchy::bind_child_to_parent<yli::ontology::Shader*>(
                    shader,
                    this->shader_pointer_vector,
                    this->free_shaderID_queue,
                    this->number_of_shaders);

            // `shader` needs to be added to the priority queue as well.
            this->shader_priority_queue.push(shader);
        }

        void Scene::bind_camera(yli::ontology::Camera* const camera)
        {
            // get `childID` from `Scene` and set pointer to `camera`.
            yli::hierarchy::bind_child_to_parent<yli::ontology::Camera*>(
                    camera,
                    this->camera_pointer_vector,
                    this->free_cameraID_queue,
                    this->number_of_cameras);
        }

        void Scene::unbind_shader(const std::size_t childID)
        {
            // `shader` needs to be removed from the priority queue as well.
            this->shader_priority_queue.remove(childID);

            yli::hierarchy::unbind_child_from_parent(
                    childID,
                    this->shader_pointer_vector,
                    this->free_shaderID_queue,
                    this->number_of_shaders);
        }

        void Scene::unbind_camera(const std::size_t childID)
        {
            yli::hierarchy::unbind_child_from_parent(
                    childID,
                    this->camera_pointer_vector,
                    this->free_cameraID_queue,
                    this->number_of_cameras);
        }

        void Scene::bind_to_parent()
        {
            // requirements:
            // `this->parent` must not be `nullptr`.
            yli::ontology::World* const world = this->parent;

            if (world == nullptr)
            {
                std::cerr << "ERROR: `Scene::bind_to_parent`: `world` is `nullptr`!\n";
                return;
            }

            // get `childID` from the `World` and set pointer to this `Scene`.
            world->bind_scene(this);
        }

        Scene::~Scene()
        {
            // destructor.
            std::cout << "Scene with childID " << std::dec << this->childID << " will be destroyed.\n";

            // destroy all `Shader`s of this `Scene`.
            std::cout << "All shaders of this scene will be destroyed.\n";
            yli::hierarchy::delete_children<yli::ontology::Shader*>(this->shader_pointer_vector, this->number_of_shaders);

            // destroy all `Camera`s of this `Scene`.
            std::cout << "All cameras of this scene will be destroyed.\n";
            yli::hierarchy::delete_children<yli::ontology::Camera*>(this->camera_pointer_vector, this->number_of_cameras);

            // requirements for further actions:
            // `this->parent` must not be `nullptr`.

            yli::ontology::World* const world = this->parent;

            if (world == nullptr)
            {
                std::cerr << "ERROR: `Scene::~Scene`: `world` is `nullptr`!\n";
                return;
            }

            if (world->get_active_scene() == this)
            {
                // Make this `Scene` no more the active `Scene`.
                this->parent->set_active_scene(nullptr);
            }

            // set pointer to this `Scene` to `nullptr`.
            world->unbind_scene(this->childID);
        }

        void Scene::render()
        {
            if (this->should_be_rendered)
            {
                this->prerender();

                // render this `Scene` by calling `render()` function of each `Shader`.
                yli::ontology::render_children<yli::ontology::Shader*>(this->shader_pointer_vector);

                this->postrender();
            }
        }

        yli::ontology::Camera* Scene::get_active_camera() const
        {
            return this->active_camera;
        }

        void Scene::set_active_camera(yli::ontology::Camera* camera)
        {
            yli::ontology::Camera* const old_active_camera = this->active_camera;

            if (this->universe != nullptr &&
                    old_active_camera != nullptr &&
                    !old_active_camera->get_is_static_view())
            {
                // OK, there is an old active `Camera`, and it is not a static view `Camera`.
                // Copy the coordinates and angles from the `Universe` to the old active `Camera`.
                old_active_camera->set_cartesian_coordinates(this->universe->current_camera_cartesian_coordinates);
                old_active_camera->set_horizontal_angle(this->universe->current_camera_horizontal_angle);
                old_active_camera->set_vertical_angle(this->universe->current_camera_vertical_angle);
            }

            // It is OK to disactivate the active camera by setting `active_camera` to `nullptr`.
            this->active_camera = camera;

            // requirements for further actions:
            // `this->universe` must not be `nullptr`.
            // `this->parent` must not be `nullptr`.

            if (this->universe == nullptr || this->parent == nullptr)
            {
                return;
            }

            yli::ontology::World* const active_world = this->universe->get_active_world();

            if (active_world == nullptr)
            {
                return;
            }

            yli::ontology::Scene* const active_scene = active_world->get_active_scene();

            if (active_scene == nullptr)
            {
                return;
            }

            if (active_scene == this && camera != nullptr)
            {
                // OK, the newly activated `Camera` is not `nullptr`,
                // and this is the active `Scene` in the active `World`.
                // Copy `Camera`'s coordinates and angles to the `Universe`.
                this->universe->current_camera_cartesian_coordinates = camera->get_cartesian_coordinates();
                this->universe->current_camera_horizontal_angle = camera->get_horizontal_angle();
                this->universe->current_camera_vertical_angle = camera->get_vertical_angle();
            }
        }

        yli::ontology::Entity* Scene::get_parent() const
        {
            return this->parent;
        }

        std::size_t Scene::get_number_of_children() const
        {
            return this->number_of_shaders + this->number_of_cameras;
        }

        std::size_t Scene::get_number_of_descendants() const
        {
            return yli::ontology::get_number_of_descendants(this->shader_pointer_vector) +
                yli::ontology::get_number_of_descendants(this->camera_pointer_vector);
        }

        // this method returns a pointer to an `Entity` using the name as key.
        yli::ontology::Entity* Scene::get_entity(const std::string name) const
        {
            if (this->name_map.count(name) != 1)
            {
                return nullptr;
            }

            return this->name_map.at(name);
        }

        float Scene::get_turbo_factor() const
        {
            if (this->parent != nullptr &&
                    this->universe != nullptr &&
                    this->parent == this->universe->get_active_world() &&
                    this == this->parent->get_active_scene())
            {
                return this->universe->turbo_factor;
            }

            return NAN;
        }

        void Scene::set_turbo_factor(float turbo_factor)
        {
            this->turbo_factor = turbo_factor;

            if (this->parent != nullptr &&
                    this->universe != nullptr &&
                    this->parent == this->universe->get_active_world() &&
                    this == this->parent->get_active_scene())
            {
                this->universe->turbo_factor = this->turbo_factor;
            }
        }

        float Scene::get_twin_turbo_factor() const
        {
            if (this->parent != nullptr &&
                    this->universe != nullptr &&
                    this->parent == this->universe->get_active_world() &&
                    this == this->parent->get_active_scene())
            {
                return this->universe->twin_turbo_factor;
            }

            return NAN;
        }

        void Scene::set_twin_turbo_factor(float twin_turbo_factor)
        {
            this->twin_turbo_factor = twin_turbo_factor;

            if (this->parent != nullptr &&
                    this->universe != nullptr &&
                    this->parent == this->universe->get_active_world() &&
                    this == this->parent->get_active_scene())
            {
                this->universe->twin_turbo_factor = this->twin_turbo_factor;
            }
        }

        yli::ontology::Species* Scene::get_terrain_species() const
        {
            if (this->parent != nullptr &&
                    this->universe != nullptr &&
                    this->parent == this->universe->get_active_world() &&
                    this == this->parent->get_active_scene())
            {
                return this->terrain_species;
            }

            return nullptr;
        }

        void Scene::set_terrain_species(yli::ontology::Species* const terrain_species)
        {
            this->terrain_species = terrain_species;

            if (this->parent != nullptr &&
                    this->universe != nullptr &&
                    this->parent == this->universe->get_active_world() &&
                    this == this->parent->get_active_scene())
            {
                this->universe->set_terrain_species(this->terrain_species);
            }
        }

        yli::ontology::World* Scene::get_world_parent() const
        {
            return this->parent;
        }

        float Scene::get_water_level() const
        {
            return this->water_level;
        }
    }
}
<|endoftext|>


<commit_before>//
// Copyright (c) 2010 Advanced Micro Devices, Inc. All rights reserved.
//

#ifndef VERSIONS_HPP_
#define VERSIONS_HPP_

#include "utils/macros.hpp"

#ifndef AMD_PLATFORM_NAME
# define AMD_PLATFORM_NAME "AMD Accelerated Parallel Processing"
#endif // AMD_PLATFORM_NAME

#ifndef AMD_PLATFORM_BUILD_NUMBER
# define AMD_PLATFORM_BUILD_NUMBER 1641
#endif // AMD_PLATFORM_BUILD_NUMBER

#ifndef AMD_PLATFORM_REVISION_NUMBER
# define AMD_PLATFORM_REVISION_NUMBER 0
#endif // AMD_PLATFORM_REVISION_NUMBER

#ifndef AMD_PLATFORM_RELEASE_INFO
# define AMD_PLATFORM_RELEASE_INFO
#endif // AMD_PLATFORM_RELEASE_INFO

#define AMD_BUILD_STRING XSTR(AMD_PLATFORM_BUILD_NUMBER) \
    "." XSTR(AMD_PLATFORM_REVISION_NUMBER)

#ifndef AMD_PLATFORM_INFO
# define AMD_PLATFORM_INFO "AMD-APP" AMD_PLATFORM_RELEASE_INFO \
    DEBUG_ONLY("." IF(IS_OPTIMIZED,"opt","dbg")) " (" AMD_BUILD_STRING ")"
#endif // ATI_PLATFORM_INFO

#endif // VERSIONS_HPP_
<commit_msg>P4 to Git Change 1079692 by johtaylo@johtaylo-JTBUILDER03-increment on 2014/09/23 03:00:11<commit_after>//
// Copyright (c) 2010 Advanced Micro Devices, Inc. All rights reserved.
//

#ifndef VERSIONS_HPP_
#define VERSIONS_HPP_

#include "utils/macros.hpp"

#ifndef AMD_PLATFORM_NAME
# define AMD_PLATFORM_NAME "AMD Accelerated Parallel Processing"
#endif // AMD_PLATFORM_NAME

#ifndef AMD_PLATFORM_BUILD_NUMBER
# define AMD_PLATFORM_BUILD_NUMBER 1642
#endif // AMD_PLATFORM_BUILD_NUMBER

#ifndef AMD_PLATFORM_REVISION_NUMBER
# define AMD_PLATFORM_REVISION_NUMBER 0
#endif // AMD_PLATFORM_REVISION_NUMBER

#ifndef AMD_PLATFORM_RELEASE_INFO
# define AMD_PLATFORM_RELEASE_INFO
#endif // AMD_PLATFORM_RELEASE_INFO

#define AMD_BUILD_STRING XSTR(AMD_PLATFORM_BUILD_NUMBER) \
    "." XSTR(AMD_PLATFORM_REVISION_NUMBER)

#ifndef AMD_PLATFORM_INFO
# define AMD_PLATFORM_INFO "AMD-APP" AMD_PLATFORM_RELEASE_INFO \
    DEBUG_ONLY("." IF(IS_OPTIMIZED,"opt","dbg")) " (" AMD_BUILD_STRING ")"
#endif // ATI_PLATFORM_INFO

#endif // VERSIONS_HPP_
<|endoftext|>


<commit_before>//
// Copyright (c) 2010 Advanced Micro Devices, Inc. All rights reserved.
//

#ifndef VERSIONS_HPP_
#define VERSIONS_HPP_

#include "utils/macros.hpp"

#ifndef AMD_PLATFORM_NAME
#define AMD_PLATFORM_NAME "AMD Accelerated Parallel Processing"
#endif  // AMD_PLATFORM_NAME

#ifndef AMD_PLATFORM_BUILD_NUMBER
#define AMD_PLATFORM_BUILD_NUMBER 2478
#endif  // AMD_PLATFORM_BUILD_NUMBER

#ifndef AMD_PLATFORM_REVISION_NUMBER
#define AMD_PLATFORM_REVISION_NUMBER 0
#endif  // AMD_PLATFORM_REVISION_NUMBER

#ifndef AMD_PLATFORM_RELEASE_INFO
#define AMD_PLATFORM_RELEASE_INFO
#endif  // AMD_PLATFORM_RELEASE_INFO

#define AMD_BUILD_STRING                                                                           \
  XSTR(AMD_PLATFORM_BUILD_NUMBER)                                                                  \
  "." XSTR(AMD_PLATFORM_REVISION_NUMBER)

#ifndef AMD_PLATFORM_INFO
#define AMD_PLATFORM_INFO                                                                          \
  "AMD-APP" AMD_PLATFORM_RELEASE_INFO DEBUG_ONLY(                                                  \
      "." IF(IS_OPTIMIZED, "opt", "dbg")) " (" AMD_BUILD_STRING ")"
#endif  // ATI_PLATFORM_INFO

#endif  // VERSIONS_HPP_
<commit_msg>P4 to Git Change 1448306 by johtaylo@johtaylo-jtincrementor-increment on 2017/08/17 03:00:05<commit_after>//
// Copyright (c) 2010 Advanced Micro Devices, Inc. All rights reserved.
//

#ifndef VERSIONS_HPP_
#define VERSIONS_HPP_

#include "utils/macros.hpp"

#ifndef AMD_PLATFORM_NAME
#define AMD_PLATFORM_NAME "AMD Accelerated Parallel Processing"
#endif  // AMD_PLATFORM_NAME

#ifndef AMD_PLATFORM_BUILD_NUMBER
#define AMD_PLATFORM_BUILD_NUMBER 2479
#endif  // AMD_PLATFORM_BUILD_NUMBER

#ifndef AMD_PLATFORM_REVISION_NUMBER
#define AMD_PLATFORM_REVISION_NUMBER 0
#endif  // AMD_PLATFORM_REVISION_NUMBER

#ifndef AMD_PLATFORM_RELEASE_INFO
#define AMD_PLATFORM_RELEASE_INFO
#endif  // AMD_PLATFORM_RELEASE_INFO

#define AMD_BUILD_STRING                                                                           \
  XSTR(AMD_PLATFORM_BUILD_NUMBER)                                                                  \
  "." XSTR(AMD_PLATFORM_REVISION_NUMBER)

#ifndef AMD_PLATFORM_INFO
#define AMD_PLATFORM_INFO                                                                          \
  "AMD-APP" AMD_PLATFORM_RELEASE_INFO DEBUG_ONLY(                                                  \
      "." IF(IS_OPTIMIZED, "opt", "dbg")) " (" AMD_BUILD_STRING ")"
#endif  // ATI_PLATFORM_INFO

#endif  // VERSIONS_HPP_
<|endoftext|>


<commit_before>//
// Copyright (c) 2010 Advanced Micro Devices, Inc. All rights reserved.
//

#ifndef VERSIONS_HPP_
#define VERSIONS_HPP_

#include "utils/macros.hpp"

#ifndef AMD_PLATFORM_NAME
#define AMD_PLATFORM_NAME "AMD Accelerated Parallel Processing"
#endif  // AMD_PLATFORM_NAME

#ifndef AMD_PLATFORM_BUILD_NUMBER
#define AMD_PLATFORM_BUILD_NUMBER 2896
#endif  // AMD_PLATFORM_BUILD_NUMBER

#ifndef AMD_PLATFORM_REVISION_NUMBER
#define AMD_PLATFORM_REVISION_NUMBER 0
#endif  // AMD_PLATFORM_REVISION_NUMBER

#ifndef AMD_PLATFORM_RELEASE_INFO
#define AMD_PLATFORM_RELEASE_INFO
#endif  // AMD_PLATFORM_RELEASE_INFO

#define AMD_BUILD_STRING                                                                           \
  XSTR(AMD_PLATFORM_BUILD_NUMBER)                                                                  \
  "." XSTR(AMD_PLATFORM_REVISION_NUMBER)

#ifndef AMD_PLATFORM_INFO
#define AMD_PLATFORM_INFO                                                                          \
  "AMD-APP" AMD_PLATFORM_RELEASE_INFO DEBUG_ONLY(                                                  \
      "." IF(IS_OPTIMIZED, "opt", "dbg")) " (" AMD_BUILD_STRING ")"
#endif  // ATI_PLATFORM_INFO

#endif  // VERSIONS_HPP_
<commit_msg>P4 to Git Change 1781707 by chui@ocl-promo-incrementor on 2019/05/12 03:00:04<commit_after>//
// Copyright (c) 2010 Advanced Micro Devices, Inc. All rights reserved.
//

#ifndef VERSIONS_HPP_
#define VERSIONS_HPP_

#include "utils/macros.hpp"

#ifndef AMD_PLATFORM_NAME
#define AMD_PLATFORM_NAME "AMD Accelerated Parallel Processing"
#endif  // AMD_PLATFORM_NAME

#ifndef AMD_PLATFORM_BUILD_NUMBER
#define AMD_PLATFORM_BUILD_NUMBER 2897
#endif  // AMD_PLATFORM_BUILD_NUMBER

#ifndef AMD_PLATFORM_REVISION_NUMBER
#define AMD_PLATFORM_REVISION_NUMBER 0
#endif  // AMD_PLATFORM_REVISION_NUMBER

#ifndef AMD_PLATFORM_RELEASE_INFO
#define AMD_PLATFORM_RELEASE_INFO
#endif  // AMD_PLATFORM_RELEASE_INFO

#define AMD_BUILD_STRING                                                                           \
  XSTR(AMD_PLATFORM_BUILD_NUMBER)                                                                  \
  "." XSTR(AMD_PLATFORM_REVISION_NUMBER)

#ifndef AMD_PLATFORM_INFO
#define AMD_PLATFORM_INFO                                                                          \
  "AMD-APP" AMD_PLATFORM_RELEASE_INFO DEBUG_ONLY(                                                  \
      "." IF(IS_OPTIMIZED, "opt", "dbg")) " (" AMD_BUILD_STRING ")"
#endif  // ATI_PLATFORM_INFO

#endif  // VERSIONS_HPP_
<|endoftext|>


<commit_before>/*
    RawSpeed - RAW file decoder.

    Copyright (C) 2009-2014 Klaus Post

    This library is free software; you can redistribute it and/or
    modify it under the terms of the GNU Lesser General Public
    License as published by the Free Software Foundation; either
    version 2 of the License, or (at your option) any later version.

    This library 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
    Lesser General Public License for more details.

    You should have received a copy of the GNU Lesser General Public
    License along with this library; if not, write to the Free Software
    Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*/

#include "metadata/CameraMetaData.h"
#include "common/Common.h"                    // for uint32_t, trimSpaces
#include "metadata/Camera.h"                  // for Camera
#include "metadata/CameraMetadataException.h" // for ThrowCME
#include <algorithm>                          // for find_if
#include <map>                                // for _Rb_tree_iterator, map
#include <string>                             // for string, operator==
#include <utility>                            // for pair
#include <vector>                             // for vector

#ifdef HAVE_PUGIXML
#include <pugixml.hpp> // for xml_document, xml_pars...
using pugi::xml_node;
using pugi::xml_document;
using pugi::xml_parse_result;
#endif

namespace rawspeed {

#ifdef HAVE_PUGIXML
CameraMetaData::CameraMetaData(const char *docname) {
  xml_document doc;

  if (xml_parse_result result =
#if defined(__unix__) || defined(__APPLE__)
          doc.load_file(docname)
#else
          doc.load_file(pugi::as_wide(docname).c_str())
#endif
          ;
      !result) {
    ThrowCME("XML Document \"%s\" could not be parsed successfully. Error was: "
             "%s in %s",
             docname, result.description(),
             doc.child("node").attribute("attr").value());
  }

  for (xml_node camera : doc.child("Cameras").children("Camera")) {
    const auto* cam = addCamera(std::make_unique<Camera>(camera));

    if (cam == nullptr)
      continue;

    // Create cameras for aliases.
    for (auto i = 0UL; i < cam->aliases.size(); i++) {
      addCamera(std::make_unique<Camera>(cam, i));
    }
  }
}
#endif

static inline CameraId getId(const std::string& make, const std::string& model,
                             const std::string& mode) {
  CameraId id;
  id.make = trimSpaces(make);
  id.model = trimSpaces(model);
  id.mode = trimSpaces(mode);

  return id;
}

const Camera* CameraMetaData::getCamera(const std::string& make,
                                        const std::string& model,
                                        const std::string& mode) const {
  auto camera = cameras.find(getId(make, model, mode));
  return camera == cameras.end() ? nullptr : camera->second.get();
}

const Camera* CameraMetaData::getCamera(const std::string& make,
                                        const std::string& model) const {
  auto id = getId(make, model, "");

  auto iter = find_if(cameras.cbegin(), cameras.cend(),
                      [&id](decltype(*cameras.cbegin())& i) {
                        const auto& cid = i.first;
                        return tie(id.make, id.model) ==
                               tie(cid.make, cid.model);
                      });

  if (iter == cameras.end())
    return nullptr;

  return iter->second.get();
}

bool CameraMetaData::hasCamera(const std::string& make,
                               const std::string& model,
                               const std::string& mode) const {
  return getCamera(make, model, mode);
}

const Camera* __attribute__((pure))
CameraMetaData::getChdkCamera(uint32_t filesize) const {
  auto camera = chdkCameras.find(filesize);
  return camera == chdkCameras.end() ? nullptr : camera->second;
}

bool __attribute__((pure))
CameraMetaData::hasChdkCamera(uint32_t filesize) const {
  return chdkCameras.end() != chdkCameras.find(filesize);
}

const Camera* CameraMetaData::addCamera(std::unique_ptr<Camera> cam) {
  auto id = getId(cam->make, cam->model, cam->mode);
  if (cameras.end() != cameras.find(id)) {
    writeLog(
        DEBUG_PRIO::WARNING,
        "CameraMetaData: Duplicate entry found for camera: %s %s, Skipping!",
        cam->make.c_str(), cam->model.c_str());
    return nullptr;
  }
  cameras[id] = std::move(cam);

  if (std::string::npos != cameras[id]->mode.find("chdk")) {
    auto filesize_hint = cameras[id]->hints.get("filesize", std::string());
    if (filesize_hint.empty()) {
      writeLog(DEBUG_PRIO::WARNING,
               "CameraMetaData: CHDK camera: %s %s, no \"filesize\" hint set!",
               cameras[id]->make.c_str(), cameras[id]->model.c_str());
    } else {
      chdkCameras[stoi(filesize_hint)] = cameras[id].get();
      // writeLog(DEBUG_PRIO::WARNING, "CHDK camera: %s %s size:%u",
      // cameras[id]->make.c_str(), cameras[id]->model.c_str(), size);
    }
  }
  return cameras[id].get();
}

void CameraMetaData::disableMake(std::string_view make) const {
  for (const auto& [key, value] : cameras) {
    if (value->make == make)
      value->supported = false;
  }
}

void CameraMetaData::disableCamera(std::string_view make,
                                   std::string_view model) const {
  for (const auto& [key, value] : cameras) {
    if (value->make == make && value->model == model)
      value->supported = false;
  }
}

} // namespace rawspeed
<commit_msg>Revert "CameraMetaData: use structured bindings"<commit_after>/*
    RawSpeed - RAW file decoder.

    Copyright (C) 2009-2014 Klaus Post

    This library is free software; you can redistribute it and/or
    modify it under the terms of the GNU Lesser General Public
    License as published by the Free Software Foundation; either
    version 2 of the License, or (at your option) any later version.

    This library 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
    Lesser General Public License for more details.

    You should have received a copy of the GNU Lesser General Public
    License along with this library; if not, write to the Free Software
    Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*/

#include "metadata/CameraMetaData.h"
#include "common/Common.h"                    // for uint32_t, trimSpaces
#include "metadata/Camera.h"                  // for Camera
#include "metadata/CameraMetadataException.h" // for ThrowCME
#include <algorithm>                          // for find_if
#include <map>                                // for _Rb_tree_iterator, map
#include <string>                             // for string, operator==
#include <utility>                            // for pair
#include <vector>                             // for vector

#ifdef HAVE_PUGIXML
#include <pugixml.hpp> // for xml_document, xml_pars...
using pugi::xml_node;
using pugi::xml_document;
using pugi::xml_parse_result;
#endif

namespace rawspeed {

#ifdef HAVE_PUGIXML
CameraMetaData::CameraMetaData(const char *docname) {
  xml_document doc;

  if (xml_parse_result result =
#if defined(__unix__) || defined(__APPLE__)
          doc.load_file(docname)
#else
          doc.load_file(pugi::as_wide(docname).c_str())
#endif
          ;
      !result) {
    ThrowCME("XML Document \"%s\" could not be parsed successfully. Error was: "
             "%s in %s",
             docname, result.description(),
             doc.child("node").attribute("attr").value());
  }

  for (xml_node camera : doc.child("Cameras").children("Camera")) {
    const auto* cam = addCamera(std::make_unique<Camera>(camera));

    if (cam == nullptr)
      continue;

    // Create cameras for aliases.
    for (auto i = 0UL; i < cam->aliases.size(); i++) {
      addCamera(std::make_unique<Camera>(cam, i));
    }
  }
}
#endif

static inline CameraId getId(const std::string& make, const std::string& model,
                             const std::string& mode) {
  CameraId id;
  id.make = trimSpaces(make);
  id.model = trimSpaces(model);
  id.mode = trimSpaces(mode);

  return id;
}

const Camera* CameraMetaData::getCamera(const std::string& make,
                                        const std::string& model,
                                        const std::string& mode) const {
  auto camera = cameras.find(getId(make, model, mode));
  return camera == cameras.end() ? nullptr : camera->second.get();
}

const Camera* CameraMetaData::getCamera(const std::string& make,
                                        const std::string& model) const {
  auto id = getId(make, model, "");

  auto iter = find_if(cameras.cbegin(), cameras.cend(),
                      [&id](decltype(*cameras.cbegin())& i) {
                        const auto& cid = i.first;
                        return tie(id.make, id.model) ==
                               tie(cid.make, cid.model);
                      });

  if (iter == cameras.end())
    return nullptr;

  return iter->second.get();
}

bool CameraMetaData::hasCamera(const std::string& make,
                               const std::string& model,
                               const std::string& mode) const {
  return getCamera(make, model, mode);
}

const Camera* __attribute__((pure))
CameraMetaData::getChdkCamera(uint32_t filesize) const {
  auto camera = chdkCameras.find(filesize);
  return camera == chdkCameras.end() ? nullptr : camera->second;
}

bool __attribute__((pure))
CameraMetaData::hasChdkCamera(uint32_t filesize) const {
  return chdkCameras.end() != chdkCameras.find(filesize);
}

const Camera* CameraMetaData::addCamera(std::unique_ptr<Camera> cam) {
  auto id = getId(cam->make, cam->model, cam->mode);
  if (cameras.end() != cameras.find(id)) {
    writeLog(
        DEBUG_PRIO::WARNING,
        "CameraMetaData: Duplicate entry found for camera: %s %s, Skipping!",
        cam->make.c_str(), cam->model.c_str());
    return nullptr;
  }
  cameras[id] = std::move(cam);

  if (std::string::npos != cameras[id]->mode.find("chdk")) {
    auto filesize_hint = cameras[id]->hints.get("filesize", std::string());
    if (filesize_hint.empty()) {
      writeLog(DEBUG_PRIO::WARNING,
               "CameraMetaData: CHDK camera: %s %s, no \"filesize\" hint set!",
               cameras[id]->make.c_str(), cameras[id]->model.c_str());
    } else {
      chdkCameras[stoi(filesize_hint)] = cameras[id].get();
      // writeLog(DEBUG_PRIO::WARNING, "CHDK camera: %s %s size:%u",
      // cameras[id]->make.c_str(), cameras[id]->model.c_str(), size);
    }
  }
  return cameras[id].get();
}

void CameraMetaData::disableMake(std::string_view make) const {
  for (const auto& cam : cameras) {
    if (cam.second->make == make)
      cam.second->supported = false;
  }
}

void CameraMetaData::disableCamera(std::string_view make,
                                   std::string_view model) const {
  for (const auto& cam : cameras) {
    if (cam.second->make == make && cam.second->model == model)
      cam.second->supported = false;
  }
}

} // namespace rawspeed
<|endoftext|>


<commit_before>//===- TestDialect.cpp - MLIR Dialect for Testing -------------------------===//
//
// Copyright 2019 The MLIR Authors.
//
// 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
//
// 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.
// =============================================================================

#include "TestDialect.h"
#include "mlir/IR/PatternMatch.h"
#include "mlir/IR/TypeUtilities.h"
#include "mlir/Transforms/FoldUtils.h"
#include "mlir/Transforms/InliningUtils.h"

using namespace mlir;

//===----------------------------------------------------------------------===//
// TestDialect Interfaces
//===----------------------------------------------------------------------===//

namespace {
struct TestOpFolderDialectInterface : public OpFolderDialectInterface {
  using OpFolderDialectInterface::OpFolderDialectInterface;

  /// Registered hook to check if the given region, which is attached to an
  /// operation that is *not* isolated from above, should be used when
  /// materializing constants.
  virtual bool shouldMaterializeInto(Region *region) const {
    // If this is a one region operation, then insert into it.
    return isa<OneRegionOp>(region->getParentOp());
  }
};

/// This class defines the interface for handling inlining with standard
/// operations.
struct TestInlinerInterface : public DialectInlinerInterface {
  using DialectInlinerInterface::DialectInlinerInterface;

  //===--------------------------------------------------------------------===//
  // Analysis Hooks
  //===--------------------------------------------------------------------===//

  bool isLegalToInline(Operation *, Region *,
                       BlockAndValueMapping &) const final {
    return true;
  }

  bool shouldAnalyzeRecursively(Operation *op) const {
    // Analyze recursively if this is not a functional region operation, it
    // froms a separate functional scope.
    return !isa<FunctionalRegionOp>(op);
  }

  //===--------------------------------------------------------------------===//
  // Transformation Hooks
  //===--------------------------------------------------------------------===//

  /// Handle the given inlined terminator by replacing it with a new operation
  /// as necessary.
  void handleTerminator(Operation *op,
                        ArrayRef<Value *> valuesToRepl) const final {
    // Only handle "test.return" here.
    auto returnOp = dyn_cast<TestReturnOp>(op);
    if (!returnOp)
      return;

    // Replace the values directly with the return operands.
    assert(returnOp.getNumOperands() == valuesToRepl.size());
    for (const auto &it : llvm::enumerate(returnOp.getOperands()))
      valuesToRepl[it.index()]->replaceAllUsesWith(it.value());
  }
};
} // end anonymous namespace

//===----------------------------------------------------------------------===//
// TestDialect
//===----------------------------------------------------------------------===//

TestDialect::TestDialect(MLIRContext *context)
    : Dialect(getDialectName(), context) {
  addOperations<
#define GET_OP_LIST
#include "TestOps.cpp.inc"
      >();
  addInterfaces<TestOpFolderDialectInterface, TestInlinerInterface>();
  allowUnknownOperations();
}

//===----------------------------------------------------------------------===//
// Test IsolatedRegionOp - parse passthrough region arguments.
//===----------------------------------------------------------------------===//

static ParseResult parseIsolatedRegionOp(OpAsmParser *parser,
                                         OperationState *result) {
  OpAsmParser::OperandType argInfo;
  Type argType = parser->getBuilder().getIndexType();

  // Parse the input operand.
  if (parser->parseOperand(argInfo) ||
      parser->resolveOperand(argInfo, argType, result->operands))
    return failure();

  // Parse the body region, and reuse the operand info as the argument info.
  Region *body = result->addRegion();
  return parser->parseRegion(*body, argInfo, argType,
                             /*enableNameShadowing=*/true);
}

static void print(OpAsmPrinter *p, IsolatedRegionOp op) {
  *p << "test.isolated_region ";
  p->printOperand(op.getOperand());
  p->shadowRegionArgs(op.region(), op.getOperand());
  p->printRegion(op.region(), /*printEntryBlockArgs=*/false);
}

//===----------------------------------------------------------------------===//
// Test PolyForOp - parse list of region arguments.
//===----------------------------------------------------------------------===//
static ParseResult parsePolyForOp(OpAsmParser *parser, OperationState *result) {
  SmallVector<OpAsmParser::OperandType, 4> ivsInfo;
  // Parse list of region arguments without a delimiter.
  if (parser->parseRegionArgumentList(ivsInfo))
    return failure();

  // Parse the body region.
  Region *body = result->addRegion();
  auto &builder = parser->getBuilder();
  SmallVector<Type, 4> argTypes(ivsInfo.size(), builder.getIndexType());
  return parser->parseRegion(*body, ivsInfo, argTypes);
}

//===----------------------------------------------------------------------===//
// Test removing op with inner ops.
//===----------------------------------------------------------------------===//

namespace {
struct TestRemoveOpWithInnerOps
    : public OpRewritePattern<TestOpWithRegionPattern> {
  using OpRewritePattern<TestOpWithRegionPattern>::OpRewritePattern;

  PatternMatchResult matchAndRewrite(TestOpWithRegionPattern op,
                                     PatternRewriter &rewriter) const override {
    rewriter.replaceOp(op, llvm::None);
    return matchSuccess();
  }
};
} // end anonymous namespace

void TestOpWithRegionPattern::getCanonicalizationPatterns(
    OwningRewritePatternList &results, MLIRContext *context) {
  results.insert<TestRemoveOpWithInnerOps>(context);
}

OpFoldResult TestOpWithRegionFold::fold(ArrayRef<Attribute> operands) {
  return operand();
}

// Static initialization for Test dialect registration.
static mlir::DialectRegistration<mlir::TestDialect> testDialect;

#define GET_OP_CLASSES
#include "TestOps.cpp.inc"
<commit_msg>Use "final" instead of marking method virtual in override (NFC)<commit_after>//===- TestDialect.cpp - MLIR Dialect for Testing -------------------------===//
//
// Copyright 2019 The MLIR Authors.
//
// 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
//
// 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.
// =============================================================================

#include "TestDialect.h"
#include "mlir/IR/PatternMatch.h"
#include "mlir/IR/TypeUtilities.h"
#include "mlir/Transforms/FoldUtils.h"
#include "mlir/Transforms/InliningUtils.h"

using namespace mlir;

//===----------------------------------------------------------------------===//
// TestDialect Interfaces
//===----------------------------------------------------------------------===//

namespace {
struct TestOpFolderDialectInterface : public OpFolderDialectInterface {
  using OpFolderDialectInterface::OpFolderDialectInterface;

  /// Registered hook to check if the given region, which is attached to an
  /// operation that is *not* isolated from above, should be used when
  /// materializing constants.
  bool shouldMaterializeInto(Region *region) const final {
    // If this is a one region operation, then insert into it.
    return isa<OneRegionOp>(region->getParentOp());
  }
};

/// This class defines the interface for handling inlining with standard
/// operations.
struct TestInlinerInterface : public DialectInlinerInterface {
  using DialectInlinerInterface::DialectInlinerInterface;

  //===--------------------------------------------------------------------===//
  // Analysis Hooks
  //===--------------------------------------------------------------------===//

  bool isLegalToInline(Operation *, Region *,
                       BlockAndValueMapping &) const final {
    return true;
  }

  bool shouldAnalyzeRecursively(Operation *op) const {
    // Analyze recursively if this is not a functional region operation, it
    // froms a separate functional scope.
    return !isa<FunctionalRegionOp>(op);
  }

  //===--------------------------------------------------------------------===//
  // Transformation Hooks
  //===--------------------------------------------------------------------===//

  /// Handle the given inlined terminator by replacing it with a new operation
  /// as necessary.
  void handleTerminator(Operation *op,
                        ArrayRef<Value *> valuesToRepl) const final {
    // Only handle "test.return" here.
    auto returnOp = dyn_cast<TestReturnOp>(op);
    if (!returnOp)
      return;

    // Replace the values directly with the return operands.
    assert(returnOp.getNumOperands() == valuesToRepl.size());
    for (const auto &it : llvm::enumerate(returnOp.getOperands()))
      valuesToRepl[it.index()]->replaceAllUsesWith(it.value());
  }
};
} // end anonymous namespace

//===----------------------------------------------------------------------===//
// TestDialect
//===----------------------------------------------------------------------===//

TestDialect::TestDialect(MLIRContext *context)
    : Dialect(getDialectName(), context) {
  addOperations<
#define GET_OP_LIST
#include "TestOps.cpp.inc"
      >();
  addInterfaces<TestOpFolderDialectInterface, TestInlinerInterface>();
  allowUnknownOperations();
}

//===----------------------------------------------------------------------===//
// Test IsolatedRegionOp - parse passthrough region arguments.
//===----------------------------------------------------------------------===//

static ParseResult parseIsolatedRegionOp(OpAsmParser *parser,
                                         OperationState *result) {
  OpAsmParser::OperandType argInfo;
  Type argType = parser->getBuilder().getIndexType();

  // Parse the input operand.
  if (parser->parseOperand(argInfo) ||
      parser->resolveOperand(argInfo, argType, result->operands))
    return failure();

  // Parse the body region, and reuse the operand info as the argument info.
  Region *body = result->addRegion();
  return parser->parseRegion(*body, argInfo, argType,
                             /*enableNameShadowing=*/true);
}

static void print(OpAsmPrinter *p, IsolatedRegionOp op) {
  *p << "test.isolated_region ";
  p->printOperand(op.getOperand());
  p->shadowRegionArgs(op.region(), op.getOperand());
  p->printRegion(op.region(), /*printEntryBlockArgs=*/false);
}

//===----------------------------------------------------------------------===//
// Test PolyForOp - parse list of region arguments.
//===----------------------------------------------------------------------===//
static ParseResult parsePolyForOp(OpAsmParser *parser, OperationState *result) {
  SmallVector<OpAsmParser::OperandType, 4> ivsInfo;
  // Parse list of region arguments without a delimiter.
  if (parser->parseRegionArgumentList(ivsInfo))
    return failure();

  // Parse the body region.
  Region *body = result->addRegion();
  auto &builder = parser->getBuilder();
  SmallVector<Type, 4> argTypes(ivsInfo.size(), builder.getIndexType());
  return parser->parseRegion(*body, ivsInfo, argTypes);
}

//===----------------------------------------------------------------------===//
// Test removing op with inner ops.
//===----------------------------------------------------------------------===//

namespace {
struct TestRemoveOpWithInnerOps
    : public OpRewritePattern<TestOpWithRegionPattern> {
  using OpRewritePattern<TestOpWithRegionPattern>::OpRewritePattern;

  PatternMatchResult matchAndRewrite(TestOpWithRegionPattern op,
                                     PatternRewriter &rewriter) const override {
    rewriter.replaceOp(op, llvm::None);
    return matchSuccess();
  }
};
} // end anonymous namespace

void TestOpWithRegionPattern::getCanonicalizationPatterns(
    OwningRewritePatternList &results, MLIRContext *context) {
  results.insert<TestRemoveOpWithInnerOps>(context);
}

OpFoldResult TestOpWithRegionFold::fold(ArrayRef<Attribute> operands) {
  return operand();
}

// Static initialization for Test dialect registration.
static mlir::DialectRegistration<mlir::TestDialect> testDialect;

#define GET_OP_CLASSES
#include "TestOps.cpp.inc"
<|endoftext|>