<commit_before>/**
 * gdal_image.cpp -- Load GIS data into OpenCV Containers using the Geospatial Data Abstraction Library
*/

/// OpenCV Headers
#include "opencv2/core/core.hpp"
#include "opencv2/imgproc/imgproc.hpp"
#include "opencv2/highgui/highgui.hpp"

/// C++ Standard Libraries
#include <cmath>
#include <iostream>
#include <stdexcept>
#include <vector>

using namespace std;

/// define the corner points
///    Note that GDAL can natively determine this
cv::Point2d tl( -122.441017, 37.815664 );
cv::Point2d tr( -122.370919, 37.815311 );
cv::Point2d bl( -122.441533, 37.747167 );
cv::Point2d br( -122.3715,   37.746814 );

/// determine dem corners
cv::Point2d dem_bl( -122.0, 38);
cv::Point2d dem_tr( -123.0, 37);

/// range of the heat map colors
std::vector<std::pair<cv::Vec3b,double> > color_range;

/**
 * Linear Interpolation
 * p1 - Point 1
 * p2 - Point 2
 * t  - Ratio from Point 1 to Point 2
*/
cv::Point2d lerp( cv::Point2d const& p1, cv::Point2d const& p2, const double& t ){
    return cv::Point2d( ((1-t)*p1.x) + (t*p2.x),
                        ((1-t)*p1.y) + (t*p2.y));
}

/**
 * Interpolate Colors
*/
template <typename DATATYPE, int N>
cv::Vec<DATATYPE,N> lerp( cv::Vec<DATATYPE,N> const& minColor,
                          cv::Vec<DATATYPE,N> const& maxColor,
                          double const& t ){

    cv::Vec<DATATYPE,N> output;
    for( int i=0; i<N; i++ ){
        output[i] = ((1-t)*minColor[i]) + (t * maxColor[i]);
    }
    return output;
}

/**
 * Compute the dem color
*/
cv::Vec3b get_dem_color( const double& elevation ){

    // if the elevation is below the minimum, return the minimum
    if( elevation < color_range[0].second ){
        return color_range[0].first;
    }
    // if the elevation is above the maximum, return the maximum
    if( elevation > color_range.back().second ){
        return color_range.back().first;
    }

    // otherwise, find the proper starting index
    int idx=0;
    double t = 0;
    for( int x=0; x<color_range.size()-1; x++ ){

        // if the current elevation is below the next item, then use the current
        // two colors as our range
        if( elevation < color_range[x+1].second ){
            idx=x;
            t = (color_range[x+1].second - elevation)/
                (color_range[x+1].second - color_range[x].second);

            break;
        }
    }

    // interpolate the color
    return lerp( color_range[idx].first, color_range[idx+1].first, t);
}

/**
 * Given a pixel coordinate and the size of the input image, compute the pixel location
 * on the DEM image.
*/
cv::Point2d world2dem( cv::Point2d const& coordinate, const cv::Size& dem_size   ){

    // relate this to the dem points
    // ASSUMING THAT DEM DATA IS ORTHORECTIFIED
    double demRatioX = ((dem_tr.x - coordinate.x)/(dem_tr.x - dem_bl.x));
    double demRatioY = 1-((dem_tr.y - coordinate.y)/(dem_tr.y - dem_bl.y));

    cv::Point2d output;
    output.x = demRatioX * dem_size.width;
    output.y = demRatioY * dem_size.height;

    return output;
}

/**
 * Convert a pixel coordinate to world coordinates
*/
cv::Point2d pixel2world( const int& x, const int& y, const cv::Size& size ){

    // compute the ratio of the pixel location to its dimension
    double rx = (double)x / size.width;
    double ry = (double)y / size.height;

    // compute LERP of each coordinate
    cv::Point2d rightSide = lerp(tr, br, ry);
    cv::Point2d leftSide  = lerp(tl, bl, ry);

    // compute the actual Lat/Lon coordinate of the interpolated coordinate
    return lerp( leftSide, rightSide, rx );
}

/**
 * Add color to a specific pixel color value
*/
void add_color( cv::Vec3b& pix, const uchar& b, const uchar& g, const uchar& r ){

    if( pix[0] + b < 255 && pix[0] + b >= 0 ){ pix[0] += b; }
    if( pix[1] + g < 255 && pix[1] + g >= 0 ){ pix[1] += g; }
    if( pix[2] + r < 255 && pix[2] + r >= 0 ){ pix[2] += r; }
}

/**
 * Main Function
*/
int main( int argc, char* argv[] ){

    /**
     * Check input arguments
    */
    if( argc < 3 ){
        cout << "usage: " << argv[0] << " <image> <dem>" << endl;
        return 1;
    }

    /// load the image (note that we don't have the projection information.  You will
    /// need to load that yourself or use the full GDAL driver.  The values are pre-defined
    /// at the top of this file
    cv::Mat image = cv::imread(argv[1], cv::IMREAD_LOAD_GDAL | cv::IMREAD_COLOR );

    /// load the dem model
    cv::Mat dem = cv::imread(argv[2], cv::IMREAD_LOAD_GDAL | cv::IMREAD_ANYDEPTH );

    /// create our output products
    cv::Mat output_dem(   image.size(), CV_8UC3 );
    cv::Mat output_dem_flood(   image.size(), CV_8UC3 );

    /// for sanity sake, make sure GDAL Loads it as a signed short
    if( dem.type() != CV_16SC1 ){ throw std::runtime_error("DEM image type must be CV_16SC1"); }

    /// define the color range to create our output DEM heat map
    //  Pair format ( Color, elevation );  Push from low to high
    //  Note:  This would be perfect for a configuration file, but is here for a working demo.
    color_range.push_back( std::pair<cv::Vec3b,double>(cv::Vec3b( 188, 154,  46),   -1));
    color_range.push_back( std::pair<cv::Vec3b,double>(cv::Vec3b( 110, 220, 110), 0.25));
    color_range.push_back( std::pair<cv::Vec3b,double>(cv::Vec3b( 150, 250, 230),   20));
    color_range.push_back( std::pair<cv::Vec3b,double>(cv::Vec3b( 160, 220, 200),   75));
    color_range.push_back( std::pair<cv::Vec3b,double>(cv::Vec3b( 220, 190, 170),  100));
    color_range.push_back( std::pair<cv::Vec3b,double>(cv::Vec3b( 250, 180, 140),  200));

    // define a minimum elevation
    double minElevation = -10;

    // iterate over each pixel in the image, computing the dem point
    for( int y=0; y<image.rows; y++ ){
    for( int x=0; x<image.cols; x++ ){

        // convert the pixel coordinate to lat/lon coordinates
        cv::Point2d coordinate = pixel2world( x, y, image.size() );

        // compute the dem image pixel coordinate from lat/lon
        cv::Point2d dem_coordinate = world2dem( coordinate, dem.size() );

        // extract the elevation
        double dz;
        if( dem_coordinate.x >=    0    && dem_coordinate.y >=    0     &&
            dem_coordinate.x < dem.cols && dem_coordinate.y < dem.rows ){
            dz = dem.at<short>(dem_coordinate);
        }else{
            dz = minElevation;
        }

        // write the pixel value to the file
        output_dem_flood.at<cv::Vec3b>(y,x) = image.at<cv::Vec3b>(y,x);

        // compute the color for the heat map output
        cv::Vec3b actualColor = get_dem_color(dz);
        output_dem.at<cv::Vec3b>(y,x) = actualColor;

        // show effect of a 10 meter increase in ocean levels
        if( dz < 10 ){
            add_color( output_dem_flood.at<cv::Vec3b>(y,x), 90, 0, 0 );
        }
        // show effect of a 50 meter increase in ocean levels
        else if( dz < 50 ){
            add_color( output_dem_flood.at<cv::Vec3b>(y,x), 0, 90, 0 );
        }
        // show effect of a 100 meter increase in ocean levels
        else if( dz < 100 ){
            add_color( output_dem_flood.at<cv::Vec3b>(y,x), 0, 0, 90 );
        }

    }}

    // print our heat map
    cv::imwrite( "heat-map.jpg"   ,  output_dem );

    // print the flooding effect image
    cv::imwrite( "flooded.jpg",  output_dem_flood);

    return 0;
}
<commit_msg>Fixed the compiler warnings for the demo program.<commit_after>/**
 * gdal_image.cpp -- Load GIS data into OpenCV Containers using the Geospatial Data Abstraction Library
*/

/// OpenCV Headers
#include "opencv2/core/core.hpp"
#include "opencv2/imgproc/imgproc.hpp"
#include "opencv2/highgui/highgui.hpp"

/// C++ Standard Libraries
#include <cmath>
#include <iostream>
#include <stdexcept>
#include <vector>

using namespace std;

/// define the corner points
///    Note that GDAL can natively determine this
cv::Point2d tl( -122.441017, 37.815664 );
cv::Point2d tr( -122.370919, 37.815311 );
cv::Point2d bl( -122.441533, 37.747167 );
cv::Point2d br( -122.3715,   37.746814 );

/// determine dem corners
cv::Point2d dem_bl( -122.0, 38);
cv::Point2d dem_tr( -123.0, 37);

/// range of the heat map colors
std::vector<std::pair<cv::Vec3b,double> > color_range;

/// List of all function prototypes
cv::Point2d lerp( const cv::Point2d&, const cv::Point2d&, const double& );

cv::Vec3b get_dem_color( const double& );

cv::Point2d world2dem( const cv::Point2d&, const cv::Size&);

cv::Point2d pixel2world( const int&, const int&, const cv::Size& );

void add_color( cv::Vec3b& pix, const uchar& b, const uchar& g, const uchar& r );

/**
 * Linear Interpolation
 * p1 - Point 1
 * p2 - Point 2
 * t  - Ratio from Point 1 to Point 2
*/
cv::Point2d lerp( cv::Point2d const& p1, cv::Point2d const& p2, const double& t ){
    return cv::Point2d( ((1-t)*p1.x) + (t*p2.x),
                        ((1-t)*p1.y) + (t*p2.y));
}

/**
 * Interpolate Colors
*/
template <typename DATATYPE, int N>
cv::Vec<DATATYPE,N> lerp( cv::Vec<DATATYPE,N> const& minColor,
                          cv::Vec<DATATYPE,N> const& maxColor,
                          double const& t ){

    cv::Vec<DATATYPE,N> output;
    for( int i=0; i<N; i++ ){
        output[i] = ((1-t)*minColor[i]) + (t * maxColor[i]);
    }
    return output;
}

/**
 * Compute the dem color
*/
cv::Vec3b get_dem_color( const double& elevation ){

    // if the elevation is below the minimum, return the minimum
    if( elevation < color_range[0].second ){
        return color_range[0].first;
    }
    // if the elevation is above the maximum, return the maximum
    if( elevation > color_range.back().second ){
        return color_range.back().first;
    }

    // otherwise, find the proper starting index
    int idx=0;
    double t = 0;
    for( int x=0; x<(int)(color_range.size()-1); x++ ){

        // if the current elevation is below the next item, then use the current
        // two colors as our range
        if( elevation < color_range[x+1].second ){
            idx=x;
            t = (color_range[x+1].second - elevation)/
                (color_range[x+1].second - color_range[x].second);

            break;
        }
    }

    // interpolate the color
    return lerp( color_range[idx].first, color_range[idx+1].first, t);
}

/**
 * Given a pixel coordinate and the size of the input image, compute the pixel location
 * on the DEM image.
*/
cv::Point2d world2dem( cv::Point2d const& coordinate, const cv::Size& dem_size   ){

    // relate this to the dem points
    // ASSUMING THAT DEM DATA IS ORTHORECTIFIED
    double demRatioX = ((dem_tr.x - coordinate.x)/(dem_tr.x - dem_bl.x));
    double demRatioY = 1-((dem_tr.y - coordinate.y)/(dem_tr.y - dem_bl.y));

    cv::Point2d output;
    output.x = demRatioX * dem_size.width;
    output.y = demRatioY * dem_size.height;

    return output;
}

/**
 * Convert a pixel coordinate to world coordinates
*/
cv::Point2d pixel2world( const int& x, const int& y, const cv::Size& size ){

    // compute the ratio of the pixel location to its dimension
    double rx = (double)x / size.width;
    double ry = (double)y / size.height;

    // compute LERP of each coordinate
    cv::Point2d rightSide = lerp(tr, br, ry);
    cv::Point2d leftSide  = lerp(tl, bl, ry);

    // compute the actual Lat/Lon coordinate of the interpolated coordinate
    return lerp( leftSide, rightSide, rx );
}

/**
 * Add color to a specific pixel color value
*/
void add_color( cv::Vec3b& pix, const uchar& b, const uchar& g, const uchar& r ){

    if( pix[0] + b < 255 && pix[0] + b >= 0 ){ pix[0] += b; }
    if( pix[1] + g < 255 && pix[1] + g >= 0 ){ pix[1] += g; }
    if( pix[2] + r < 255 && pix[2] + r >= 0 ){ pix[2] += r; }
}

/**
 * Main Function
*/
int main( int argc, char* argv[] ){

    /**
     * Check input arguments
    */
    if( argc < 3 ){
        cout << "usage: " << argv[0] << " <image> <dem>" << endl;
        return 1;
    }

    /// load the image (note that we don't have the projection information.  You will
    /// need to load that yourself or use the full GDAL driver.  The values are pre-defined
    /// at the top of this file
    cv::Mat image = cv::imread(argv[1], cv::IMREAD_LOAD_GDAL | cv::IMREAD_COLOR );

    /// load the dem model
    cv::Mat dem = cv::imread(argv[2], cv::IMREAD_LOAD_GDAL | cv::IMREAD_ANYDEPTH );

    /// create our output products
    cv::Mat output_dem(   image.size(), CV_8UC3 );
    cv::Mat output_dem_flood(   image.size(), CV_8UC3 );

    /// for sanity sake, make sure GDAL Loads it as a signed short
    if( dem.type() != CV_16SC1 ){ throw std::runtime_error("DEM image type must be CV_16SC1"); }

    /// define the color range to create our output DEM heat map
    //  Pair format ( Color, elevation );  Push from low to high
    //  Note:  This would be perfect for a configuration file, but is here for a working demo.
    color_range.push_back( std::pair<cv::Vec3b,double>(cv::Vec3b( 188, 154,  46),   -1));
    color_range.push_back( std::pair<cv::Vec3b,double>(cv::Vec3b( 110, 220, 110), 0.25));
    color_range.push_back( std::pair<cv::Vec3b,double>(cv::Vec3b( 150, 250, 230),   20));
    color_range.push_back( std::pair<cv::Vec3b,double>(cv::Vec3b( 160, 220, 200),   75));
    color_range.push_back( std::pair<cv::Vec3b,double>(cv::Vec3b( 220, 190, 170),  100));
    color_range.push_back( std::pair<cv::Vec3b,double>(cv::Vec3b( 250, 180, 140),  200));

    // define a minimum elevation
    double minElevation = -10;

    // iterate over each pixel in the image, computing the dem point
    for( int y=0; y<image.rows; y++ ){
    for( int x=0; x<image.cols; x++ ){

        // convert the pixel coordinate to lat/lon coordinates
        cv::Point2d coordinate = pixel2world( x, y, image.size() );

        // compute the dem image pixel coordinate from lat/lon
        cv::Point2d dem_coordinate = world2dem( coordinate, dem.size() );

        // extract the elevation
        double dz;
        if( dem_coordinate.x >=    0    && dem_coordinate.y >=    0     &&
            dem_coordinate.x < dem.cols && dem_coordinate.y < dem.rows ){
            dz = dem.at<short>(dem_coordinate);
        }else{
            dz = minElevation;
        }

        // write the pixel value to the file
        output_dem_flood.at<cv::Vec3b>(y,x) = image.at<cv::Vec3b>(y,x);

        // compute the color for the heat map output
        cv::Vec3b actualColor = get_dem_color(dz);
        output_dem.at<cv::Vec3b>(y,x) = actualColor;

        // show effect of a 10 meter increase in ocean levels
        if( dz < 10 ){
            add_color( output_dem_flood.at<cv::Vec3b>(y,x), 90, 0, 0 );
        }
        // show effect of a 50 meter increase in ocean levels
        else if( dz < 50 ){
            add_color( output_dem_flood.at<cv::Vec3b>(y,x), 0, 90, 0 );
        }
        // show effect of a 100 meter increase in ocean levels
        else if( dz < 100 ){
            add_color( output_dem_flood.at<cv::Vec3b>(y,x), 0, 0, 90 );
        }

    }}

    // print our heat map
    cv::imwrite( "heat-map.jpg"   ,  output_dem );

    // print the flooding effect image
    cv::imwrite( "flooded.jpg",  output_dem_flood);

    return 0;
}
<|endoftext|>


<commit_before>#ifndef HAXOR_COMMON_HAXOR_HH
#define HAXOR_COMMON_HAXOR_HH

#include <cstdint>
#include <stdexcept>
#include <string>

namespace haxor {
  typedef int64_t word_t;

  const int64_t magic = 0x7265887982;
  const int64_t major = 0;
  const int64_t minor = 6;
  const int64_t patch = 0;
  constexpr int64_t version = (major << 16) | (minor << 8) | patch;

  const uint64_t ivt_num = 128;
  constexpr uint64_t ivt_size = sizeof(word_t) * ivt_num;

  class haxe_open_error : public std::exception {
    virtual const char* what() const throw() {
      return "Cannot open specified file. Check path and try again.";
    }
  };

  class hdr_magic_error : public std::exception {
    virtual const char* what() const throw() {
      return "Incorrect magic number. You are probably trying to run incorrect file.";
    }
  };

  class hdr_version_error : public std::exception {
    virtual const char* what() const throw() {
      return "Incorrect version number. Program was compiled for different version of Haxor.";
    }
  };

  class regs_range_error : public std::exception {};
  class mem_misalign_error : public std::exception {};
  class mem_range_error : public std::exception {};
}

#endif
<commit_msg>version 0.6.1<commit_after>#ifndef HAXOR_COMMON_HAXOR_HH
#define HAXOR_COMMON_HAXOR_HH

#include <cstdint>
#include <stdexcept>
#include <string>

namespace haxor {
  typedef int64_t word_t;

  const int64_t magic = 0x7265887982;
  const int64_t major = 0;
  const int64_t minor = 6;
  const int64_t patch = 1;
  constexpr int64_t version = (major << 16) | (minor << 8) | patch;

  const uint64_t ivt_num = 128;
  constexpr uint64_t ivt_size = sizeof(word_t) * ivt_num;

  class haxe_open_error : public std::exception {
    virtual const char* what() const throw() {
      return "Cannot open specified file. Check path and try again.";
    }
  };

  class hdr_magic_error : public std::exception {
    virtual const char* what() const throw() {
      return "Incorrect magic number. You are probably trying to run incorrect file.";
    }
  };

  class hdr_version_error : public std::exception {
    virtual const char* what() const throw() {
      return "Incorrect version number. Program was compiled for different version of Haxor.";
    }
  };

  class regs_range_error : public std::exception {};
  class mem_misalign_error : public std::exception {};
  class mem_range_error : public std::exception {};
}

#endif
<|endoftext|>


<commit_before>#include <graphics/pipeline/commandbuffer.h>
#include <core/log/log.h>

namespace fd {
namespace graphics {
namespace pipeline {

using namespace core;
using namespace log;

CommandBufferArray::CommandBufferArray(VkCommandPool pool, CommandBufferType type, uint32 count) : commandBuffers(count), count(count) {

	FD_ASSERT(count != 0);

	for (uint32 i = 0; i < count; i++) {
		commandBuffers.Emaplace_back(pool, type);
	}
}

CommandBufferArray::~CommandBufferArray() {

}

void CommandBufferArray::Begin(CommandBufferUsage usage) {
	for (uint32 i = 0; i < count; i++) {
		commandBuffers[i].Begin(usage);
	}
}

void CommandBufferArray::End() {
	for (uint32 i = 0; i < count; i++) {
		commandBuffers[i].End();
	}
}

void CommandBufferArray::ExecuteCommandBuffer(const CommandBuffer* const buffer) {
	for (uint32 i = 0; i < count; i++) {
		commandBuffers[i].ExecuteCommandBuffer(buffer);
	}
}

void CommandBufferArray::BeginRenderPass(const RenderPass* const renderPass) {
	for (uint32 i = 0; i < count; i++) {
		commandBuffers[i].BeginRenderPass(renderPass, i);
	}
}

void CommandBufferArray::EndRenderPass() {
	for (uint32 i = 0; i < count; i++) {
		commandBuffers[i].EndRenderPass();
	}
}

void CommandBufferArray::BindPipeline(const Pipeline* const pipeline) {
	for (uint32 i = 0; i < count; i++) {
		commandBuffers[i].BindPipeline(pipeline);
	}
}

void CommandBufferArray::BindPipelineLayout(const PipelineLayout* const pipelineLayout) {
	for (uint32 i = 0; i < count; i++) {
		commandBuffers[i].BindPipelineLayout(pipelineLayout);
	}
}

void CommandBufferArray::Bind(const buffer::VertexBuffer* const vertexBuffer) {
	for (uint32 i = 0; i < count; i++) {
		commandBuffers[i].Bind(vertexBuffer);
	}
}

void CommandBufferArray::Bind(const buffer::IndexBuffer* const indexBuffer) {
	for (uint32 i = 0; i < count; i++) {
		commandBuffers[i].Bind(indexBuffer);
	}
}

void CommandBufferArray::DrawIndexed(uint32 count) {
	for (uint32 i = 0; i < count; i++) {
		commandBuffers[i].DrawIndexed(count);
	}
}

}
}
}<commit_msg>Stopped using stuff that I removed that ain't working<commit_after>#include <graphics/pipeline/commandbuffer.h>
#include <core/log/log.h>

namespace fd {
namespace graphics {
namespace pipeline {

using namespace core;
using namespace log;

CommandBufferArray::CommandBufferArray(VkCommandPool pool, CommandBufferType type, uint32 count) : commandBuffers(count), count(count) {

	FD_ASSERT(count != 0);

	for (uint32 i = 0; i < count; i++) {
		commandBuffers.Push_back(CommandBuffer(pool, type));
	}
}

CommandBufferArray::~CommandBufferArray() {

}

void CommandBufferArray::Begin(CommandBufferUsage usage) {
	for (uint32 i = 0; i < count; i++) {
		commandBuffers[i].Begin(usage);
	}
}

void CommandBufferArray::End() {
	for (uint32 i = 0; i < count; i++) {
		commandBuffers[i].End();
	}
}

void CommandBufferArray::ExecuteCommandBuffer(const CommandBuffer* const buffer) {
	for (uint32 i = 0; i < count; i++) {
		commandBuffers[i].ExecuteCommandBuffer(buffer);
	}
}

void CommandBufferArray::BeginRenderPass(const RenderPass* const renderPass) {
	for (uint32 i = 0; i < count; i++) {
		commandBuffers[i].BeginRenderPass(renderPass, i);
	}
}

void CommandBufferArray::EndRenderPass() {
	for (uint32 i = 0; i < count; i++) {
		commandBuffers[i].EndRenderPass();
	}
}

void CommandBufferArray::BindPipeline(const Pipeline* const pipeline) {
	for (uint32 i = 0; i < count; i++) {
		commandBuffers[i].BindPipeline(pipeline);
	}
}

void CommandBufferArray::BindPipelineLayout(const PipelineLayout* const pipelineLayout) {
	for (uint32 i = 0; i < count; i++) {
		commandBuffers[i].BindPipelineLayout(pipelineLayout);
	}
}

void CommandBufferArray::Bind(const buffer::VertexBuffer* const vertexBuffer) {
	for (uint32 i = 0; i < count; i++) {
		commandBuffers[i].Bind(vertexBuffer);
	}
}

void CommandBufferArray::Bind(const buffer::IndexBuffer* const indexBuffer) {
	for (uint32 i = 0; i < count; i++) {
		commandBuffers[i].Bind(indexBuffer);
	}
}

void CommandBufferArray::DrawIndexed(uint32 count) {
	for (uint32 i = 0; i < count; i++) {
		commandBuffers[i].DrawIndexed(count);
	}
}

}
}
}<|endoftext|>


<commit_before>/*
   For more information, please see: http://software.sci.utah.edu

   The MIT License

   Copyright (c) 2009 Scientific Computing and Imaging Institute,
   University of Utah.

   Permission is hereby granted, free of charge, to any person obtaining a
   copy of this software and associated documentation files (the "Software"),
   to deal in the Software without restriction, including without limitation
   the rights to use, copy, modify, merge, publish, distribute, sublicense,
   and/or sell copies of the Software, and to permit persons to whom the
   Software is furnished to do so, subject to the following conditions:

   The above copyright notice and this permission notice shall be included
   in all copies or substantial portions of the Software.

   THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
   OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
   FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
   THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
   LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
   FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
   DEALINGS IN THE SOFTWARE.
*/

#include <Core/Algorithms/Legacy/Fields/FieldData/SetFieldDataToConstantValue.h>

#include <Modules/Legacy/Fields/SetFieldDataToConstantValue.h>
#include <Core/Datatypes/Legacy/Field/Field.h>

using namespace SCIRun;
using namespace SCIRun::Modules::Fields;
using namespace SCIRun::Dataflow::Networks;
using namespace SCIRun::Core::Datatypes;

ModuleLookupInfo SetFieldDataToConstantValue::staticInfo_("SetFieldDataToConstantValue", "ChangeFieldData", "SCIRun");

/// @class SetFieldDataToConstantValue
/// @brief Sets field data to a given scalar value on a new output field based
/// on the input field geometry.
//
//class SetFieldDataToConstantValue : public Module {
//  public:
//    SetFieldDataToConstantValue(GuiContext*);
//    virtual ~SetFieldDataToConstantValue() {}
//
//    virtual void execute();
//
//  private:
//    GuiString gui_data_type_;
//    GuiString gui_basis_order_;
//    GuiDouble gui_value_;
//
//    SCIRunAlgo::SetFieldDataToConstantValueAlgo algo_;
//};

SetFieldDataToConstantValue::SetFieldDataToConstantValue(GuiContext* ctx) :
  Module("SetFieldDataToConstantValue", ctx, Source, "ChangeFieldData", "SCIRun"),
    gui_data_type_(ctx->subVar("data-type"),"same as input"),
    gui_basis_order_(ctx->subVar("basis-order"),"same as input"),
    gui_value_(ctx->subVar("value"),0.0)
{
  algo_.set_progress_reporter(this);
}

void
SetFieldDataToConstantValue::execute()
{
  FieldHandle input, output;

  get_input_handle("Field",input,true);

  if ( inputs_changed_ || gui_data_type_.changed() ||
       gui_basis_order_.changed() || gui_value_.changed() ||
      !oport_cached("Field"))
  {
    update_state(Executing);

    algo_.set_option("data_type",gui_data_type_.get());
    algo_.set_option("basis_order",gui_basis_order_.get());
    algo_.set_scalar("value",gui_value_.get());
    if(!(algo_.run(input,output))) return;

    send_output_handle("Field",output,true);
  }

}
<commit_msg>Constructor changes<commit_after>/*
   For more information, please see: http://software.sci.utah.edu

   The MIT License

   Copyright (c) 2009 Scientific Computing and Imaging Institute,
   University of Utah.

   Permission is hereby granted, free of charge, to any person obtaining a
   copy of this software and associated documentation files (the "Software"),
   to deal in the Software without restriction, including without limitation
   the rights to use, copy, modify, merge, publish, distribute, sublicense,
   and/or sell copies of the Software, and to permit persons to whom the
   Software is furnished to do so, subject to the following conditions:

   The above copyright notice and this permission notice shall be included
   in all copies or substantial portions of the Software.

   THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
   OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
   FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
   THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
   LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
   FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
   DEALINGS IN THE SOFTWARE.
*/

#include <Core/Algorithms/Legacy/Fields/FieldData/SetFieldDataToConstantValue.h>

#include <Modules/Legacy/Fields/SetFieldDataToConstantValue.h>
#include <Core/Datatypes/Legacy/Field/Field.h>

using namespace SCIRun;
using namespace SCIRun::Modules::Fields;
using namespace SCIRun::Dataflow::Networks;
using namespace SCIRun::Core::Datatypes;

const ModuleLookupInfo SetFieldDataToConstantValue::staticInfo_("SetFieldDataToConstantValue", "ChangeFieldData", "SCIRun");

/// @class SetFieldDataToConstantValue
/// @brief Sets field data to a given scalar value on a new output field based
/// on the input field geometry.
//
//class SetFieldDataToConstantValue : public Module {
//  public:
//    SetFieldDataToConstantValue(GuiContext*);
//    virtual ~SetFieldDataToConstantValue() {}
//
//    virtual void execute();
//
//  private:
//    GuiString gui_data_type_;
//    GuiString gui_basis_order_;
//    GuiDouble gui_value_;
//
//    SCIRunAlgo::SetFieldDataToConstantValueAlgo algo_;
//};

SetFieldDataToConstantValue::SetFieldDataToConstantValue() :
  Module(staticInfo_)
//     gui_data_type_(ctx->subVar("data-type"),"same as input"),
//     gui_basis_order_(ctx->subVar("basis-order"),"same as input"),
//     gui_value_(ctx->subVar("value"),0.0)
{
}

void
SetFieldDataToConstantValue::execute()
{
  FieldHandle input, output;

  get_input_handle("Field",input,true);

  if ( inputs_changed_ || gui_data_type_.changed() ||
       gui_basis_order_.changed() || gui_value_.changed() ||
      !oport_cached("Field"))
  {
    update_state(Executing);

    algo_.set_option("data_type",gui_data_type_.get());
    algo_.set_option("basis_order",gui_basis_order_.get());
    algo_.set_scalar("value",gui_value_.get());
    if(!(algo_.run(input,output))) return;

    send_output_handle("Field",output,true);
  }

}
<|endoftext|>


<commit_before>// Copyright eeGeo Ltd (2012-2015), All Rights Reserved

#include "NavWidgetRouteDrawingHandler.h"

namespace ExampleApp
{
    namespace NavRouting
    {
        namespace SdkModel
        {
            NavWidgetRouteDrawingHandler::NavWidgetRouteDrawingHandler(INavRoutingModel& navRoutingModel,
                                                                       TurnByTurn::INavTurnByTurnModel& navTurnByTurnModel,
                                                                       INavRouteDrawingController& routeDrawingController)
                    : m_navRoutingModel(navRoutingModel)
                    , m_navTurnByTurnModel(navTurnByTurnModel)
                    , m_routeDrawingController(routeDrawingController)
                    , m_routeColor(0.f, 0.588f, 1.f, 1.0f)
                    , m_routeCurrentStepColor(0, 1.f, 0.588f, 1.0f)
                    , m_routePreviousStepColor(0.f, 0.588f, 1.f, 1.0f)
                    , m_currentRouteStep(-1)
                    , m_routeSetCallback(this, &NavWidgetRouteDrawingHandler::OnRouteSet)
                    , m_routeClearedCallback(this, &NavWidgetRouteDrawingHandler::OnRouteCleared)
                    , m_currentDirectionSetCallback(this, &NavWidgetRouteDrawingHandler::OnCurrentDirectionSet)
                    , m_turnByTurnStartedCallback(this, &NavWidgetRouteDrawingHandler::OnTurnByTurnStarted)
                    , m_turnByTurnStoppedCallback(this, &NavWidgetRouteDrawingHandler::OnTurnByTurnStopped)
                    , m_turnByTurnUpdatedCallback(this, &NavWidgetRouteDrawingHandler::OnTurnByTurnUpdated)
            {
                m_navRoutingModel.InsertRouteSetCallback(m_routeSetCallback);
                m_navRoutingModel.InsertRouteClearedCallback(m_routeClearedCallback);
                m_navRoutingModel.InsertCurrentDirectionSetCallback(m_currentDirectionSetCallback);
                m_navTurnByTurnModel.InsertStartedCallback(m_turnByTurnStartedCallback);
                m_navTurnByTurnModel.InsertStoppedCallback(m_turnByTurnStoppedCallback);
                m_navTurnByTurnModel.InsertUpdatedCallback(m_turnByTurnUpdatedCallback);
            }

            NavWidgetRouteDrawingHandler::~NavWidgetRouteDrawingHandler()
            {
                m_navTurnByTurnModel.RemoveUpdatedCallback(m_turnByTurnUpdatedCallback);
                m_navTurnByTurnModel.RemoveStoppedCallback(m_turnByTurnStoppedCallback);
                m_navTurnByTurnModel.RemoveStartedCallback(m_turnByTurnStartedCallback);
                m_navRoutingModel.RemoveCurrentDirectionSetCallback(m_currentDirectionSetCallback);
                m_navRoutingModel.RemoveRouteClearedCallback(m_routeClearedCallback);
                m_navRoutingModel.RemoveRouteSetCallback(m_routeSetCallback);
            }

            void NavWidgetRouteDrawingHandler::OnRouteSet(const NavRoutingRouteModel& routeModel)
            {
                m_routeDrawingController.DrawRoute(m_routeColor);
            }

            void NavWidgetRouteDrawingHandler::OnRouteCleared()
            {
                m_routeDrawingController.ClearRoute();
            }

            void NavWidgetRouteDrawingHandler::OnCurrentDirectionSet(const int& directionIndex)
            {
                if (m_currentRouteStep != -1 && directionIndex != m_currentRouteStep)
                {
                    m_routeDrawingController.SetRouteStepColor(m_currentRouteStep, m_routePreviousStepColor);
                }

                m_currentRouteStep = directionIndex;
            }

            void NavWidgetRouteDrawingHandler::OnTurnByTurnStarted()
            {
                m_currentRouteStep = m_navTurnByTurnModel.GetCurrentStepIndex();
            }

            void NavWidgetRouteDrawingHandler::OnTurnByTurnStopped()
            {
                Eegeo_ASSERT(m_currentRouteStep >= 0, "Invalid route step index");
                m_routeDrawingController.SetRouteStepColor(m_currentRouteStep, m_routePreviousStepColor);
                m_currentRouteStep = -1;
            }

            void NavWidgetRouteDrawingHandler::OnTurnByTurnUpdated()
            {
                Eegeo_ASSERT(m_currentRouteStep >= 0, "Invalid route step index");
                m_routeDrawingController.UpdateRouteStepProgress(m_currentRouteStep,
                                                                 m_routePreviousStepColor,
                                                                 m_routeCurrentStepColor,
                                                                 m_navTurnByTurnModel.GetIndexOfPathSegmentStartVertex(),
                                                                 m_navTurnByTurnModel.GetClosestPointOnRoute());
            }
        }
    }
}
<commit_msg>Changed an assert to a validation check in route drawing. Buddy: Malcolm B<commit_after>// Copyright eeGeo Ltd (2012-2015), All Rights Reserved

#include "NavWidgetRouteDrawingHandler.h"

namespace ExampleApp
{
    namespace NavRouting
    {
        namespace SdkModel
        {
            NavWidgetRouteDrawingHandler::NavWidgetRouteDrawingHandler(INavRoutingModel& navRoutingModel,
                                                                       TurnByTurn::INavTurnByTurnModel& navTurnByTurnModel,
                                                                       INavRouteDrawingController& routeDrawingController)
                    : m_navRoutingModel(navRoutingModel)
                    , m_navTurnByTurnModel(navTurnByTurnModel)
                    , m_routeDrawingController(routeDrawingController)
                    , m_routeColor(0.f, 0.588f, 1.f, 1.0f)
                    , m_routeCurrentStepColor(0, 1.f, 0.588f, 1.0f)
                    , m_routePreviousStepColor(0.f, 0.588f, 1.f, 1.0f)
                    , m_currentRouteStep(-1)
                    , m_routeSetCallback(this, &NavWidgetRouteDrawingHandler::OnRouteSet)
                    , m_routeClearedCallback(this, &NavWidgetRouteDrawingHandler::OnRouteCleared)
                    , m_currentDirectionSetCallback(this, &NavWidgetRouteDrawingHandler::OnCurrentDirectionSet)
                    , m_turnByTurnStartedCallback(this, &NavWidgetRouteDrawingHandler::OnTurnByTurnStarted)
                    , m_turnByTurnStoppedCallback(this, &NavWidgetRouteDrawingHandler::OnTurnByTurnStopped)
                    , m_turnByTurnUpdatedCallback(this, &NavWidgetRouteDrawingHandler::OnTurnByTurnUpdated)
            {
                m_navRoutingModel.InsertRouteSetCallback(m_routeSetCallback);
                m_navRoutingModel.InsertRouteClearedCallback(m_routeClearedCallback);
                m_navRoutingModel.InsertCurrentDirectionSetCallback(m_currentDirectionSetCallback);
                m_navTurnByTurnModel.InsertStartedCallback(m_turnByTurnStartedCallback);
                m_navTurnByTurnModel.InsertStoppedCallback(m_turnByTurnStoppedCallback);
                m_navTurnByTurnModel.InsertUpdatedCallback(m_turnByTurnUpdatedCallback);
            }

            NavWidgetRouteDrawingHandler::~NavWidgetRouteDrawingHandler()
            {
                m_navTurnByTurnModel.RemoveUpdatedCallback(m_turnByTurnUpdatedCallback);
                m_navTurnByTurnModel.RemoveStoppedCallback(m_turnByTurnStoppedCallback);
                m_navTurnByTurnModel.RemoveStartedCallback(m_turnByTurnStartedCallback);
                m_navRoutingModel.RemoveCurrentDirectionSetCallback(m_currentDirectionSetCallback);
                m_navRoutingModel.RemoveRouteClearedCallback(m_routeClearedCallback);
                m_navRoutingModel.RemoveRouteSetCallback(m_routeSetCallback);
            }

            void NavWidgetRouteDrawingHandler::OnRouteSet(const NavRoutingRouteModel& routeModel)
            {
                m_routeDrawingController.DrawRoute(m_routeColor);
            }

            void NavWidgetRouteDrawingHandler::OnRouteCleared()
            {
                m_routeDrawingController.ClearRoute();
            }

            void NavWidgetRouteDrawingHandler::OnCurrentDirectionSet(const int& directionIndex)
            {
                if (m_currentRouteStep != -1 && directionIndex != m_currentRouteStep)
                {
                    m_routeDrawingController.SetRouteStepColor(m_currentRouteStep, m_routePreviousStepColor);
                }

                m_currentRouteStep = directionIndex;
            }

            void NavWidgetRouteDrawingHandler::OnTurnByTurnStarted()
            {
                m_currentRouteStep = m_navTurnByTurnModel.GetCurrentStepIndex();
            }

            void NavWidgetRouteDrawingHandler::OnTurnByTurnStopped()
            {
                Eegeo_ASSERT(m_currentRouteStep >= 0, "Invalid route step index");
                m_routeDrawingController.SetRouteStepColor(m_currentRouteStep, m_routePreviousStepColor);
                m_currentRouteStep = -1;
            }

            void NavWidgetRouteDrawingHandler::OnTurnByTurnUpdated()
            {
                if (m_currentRouteStep >= 0)
                {
                    m_routeDrawingController.UpdateRouteStepProgress(m_currentRouteStep,
                                                                     m_routePreviousStepColor,
                                                                     m_routeCurrentStepColor,
                                                                     m_navTurnByTurnModel.GetIndexOfPathSegmentStartVertex(),
                                                                     m_navTurnByTurnModel.GetClosestPointOnRoute());
                }
            }
        }
    }
}
<|endoftext|>


<commit_before>/*
 *  cpptest       libcaca++ rendering test
 *  Copyright (c) 2006 Jean-Yves Lamoureux <jylam@lnxscene.org>
 *                All Rights Reserved
 *
 *  $Id$
 *
 *  This program is free software; you can redistribute it and/or
 *  modify it under the terms of the Do What The Fuck You Want To
 *  Public License, Version 2, as published by Sam Hocevar. See
 *  http://sam.zoy.org/wtfpl/COPYING for more details.
 */

#include "config.h"

#include <iostream>

#include <cucul++.h>
#include <caca++.h>

using namespace std;

static char const pigstring[] =
    "                                   \n"
    "                             _     \n"
    "    _._ _..._ .-',     _.._(`))    \n"
    "   '-. `     '  /-._.-'    ',/     \n"
    "      )         \\            '.    \n"
    "     / _    _    |             \\   \n"
    "    |  a    a    /              |  \n"
    "    \\   .-.                     ;  \n"
    "     '-('' ).-'       ,'       ;   \n"
    "        '-;           |      .'    \n"
    "           \\           \\    /      \n"
    "           | 7  .__  _.-\\   \\      \n"
    "           | |  |  ``/  /`  /      \n"
    "      jgs /,_|  |   /,_/   /       \n"
    "             /,_/      '`-'        \n";

int main(int argc, char *argv[])
{
    Cucul *qq, *pig;
    Caca  *kk;
    Event ev;

    int x = 0, y = 0, ix = 1, iy = 1;

    try {
        qq = new Cucul();
    }
    catch (int e) {
        cerr << "Error while initializing cucul (" << e << ")" << endl;
        return -1;
    }

    try {
        kk = new Caca(qq);
    }
    catch(int e) {
        cerr << "Error while attaching cucul to caca (" << e << ")" << endl;
        return -1;
    }

    try {
        // Import buffer into a canvas
        Buffer *buf = new Buffer();
        buf->loadMemory((void *)pigstring, strlen(pigstring));
        pig = new Cucul(buf, "text");
        delete buf;
        // Change colour to magenta
        pig->setColorANSI(CUCUL_LIGHTMAGENTA, CUCUL_TRANSPARENT);
        for(int y = 0; y < pig->getHeight(); y++)
            for(int x = 0; x < pig->getWidth(); x++)
                pig->putChar(x, y, pig->getChar(x, y));
    }
    catch(int e) {
        cerr << "Error while importing image (" << e << ")" << endl;
        return -1;
    }

    kk->setDisplayTime(20000);

    while(!kk->getEvent(ev.CACA_EVENT_KEY_PRESS, &ev, 0)) {

        qq->Clear();

        /* Draw pig */
        qq->Blit(x, y, pig, NULL);

        /* printf works */
        qq->setColorANSI(CUCUL_LIGHTBLUE, CUCUL_BLACK);
        qq->Printf(qq->getWidth() / 2 - 10, qq->getHeight() / 2,
                   "Powered by libcaca %s", VERSION);

        /* Blit */
        kk->Display();

        x += ix;
        y += iy;

        if(x + pig->getWidth() >= qq->getWidth() || x < 0 )
            ix = -ix;
        if(y + pig->getHeight() >= qq->getHeight() || y < 0 )
            iy = -iy;
    }

    delete kk;
    delete qq;

    return 0;
}
<commit_msg> * Fixed behaviour of the pig while resizing window<commit_after>/*
 *  cpptest       libcaca++ rendering test
 *  Copyright (c) 2006 Jean-Yves Lamoureux <jylam@lnxscene.org>
 *                All Rights Reserved
 *
 *  $Id$
 *
 *  This program is free software; you can redistribute it and/or
 *  modify it under the terms of the Do What The Fuck You Want To
 *  Public License, Version 2, as published by Sam Hocevar. See
 *  http://sam.zoy.org/wtfpl/COPYING for more details.
 */

#include "config.h"

#include <iostream>

#include <cucul++.h>
#include <caca++.h>

using namespace std;

static char const pigstring[] =
    "                                   \n"
    "                             _     \n"
    "    _._ _..._ .-',     _.._(`))    \n"
    "   '-. `     '  /-._.-'    ',/     \n"
    "      )         \\            '.    \n"
    "     / _    _    |             \\   \n"
    "    |  a    a    /              |  \n"
    "    \\   .-.                     ;  \n"
    "     '-('' ).-'       ,'       ;   \n"
    "        '-;           |      .'    \n"
    "           \\           \\    /      \n"
    "           | 7  .__  _.-\\   \\      \n"
    "           | |  |  ``/  /`  /      \n"
    "      jgs /,_|  |   /,_/   /       \n"
    "             /,_/      '`-'        \n";

int main(int argc, char *argv[])
{
    Cucul *qq, *pig;
    Caca  *kk;
    Event ev;

    int x = 0, y = 0, ix = 1, iy = 1;

    try {
        qq = new Cucul();
    }
    catch (int e) {
        cerr << "Error while initializing cucul (" << e << ")" << endl;
        return -1;
    }

    try {
        kk = new Caca(qq);
    }
    catch(int e) {
        cerr << "Error while attaching cucul to caca (" << e << ")" << endl;
        return -1;
    }

    try {
        // Import buffer into a canvas
        Buffer *buf = new Buffer();
        buf->loadMemory((void *)pigstring, strlen(pigstring));
        pig = new Cucul(buf, "text");
        delete buf;
        // Change colour to magenta
        pig->setColorANSI(CUCUL_LIGHTMAGENTA, CUCUL_TRANSPARENT);
        for(int y = 0; y < pig->getHeight(); y++)
            for(int x = 0; x < pig->getWidth(); x++)
                pig->putChar(x, y, pig->getChar(x, y));
    }
    catch(int e) {
        cerr << "Error while importing image (" << e << ")" << endl;
        return -1;
    }

    kk->setDisplayTime(20000);

    while(!kk->getEvent(ev.CACA_EVENT_KEY_PRESS, &ev, 0)) {

        /* In case of resize ...*/
        if((x + pig->getWidth())-1 >= qq->getWidth() || x < 0 )
            x = 0;
        if((y + pig->getHeight())-1 >= qq->getHeight() || y < 0 )
            y = 0;

        qq->Clear();

        /* Draw pig */
        qq->Blit(x, y, pig, NULL);

        /* printf works */
        qq->setColorANSI(CUCUL_LIGHTBLUE, CUCUL_BLACK);
        qq->Printf(qq->getWidth() / 2 - 10, qq->getHeight() / 2,
                   "Powered by libcaca %s", VERSION);

        /* Blit */
        kk->Display();

        x += ix;
        y += iy;

        if(x + pig->getWidth() >= qq->getWidth() || x < 0 )
            ix = -ix;
        if(y + pig->getHeight() >= qq->getHeight() || y < 0 )
            iy = -iy;

    }

    delete kk;
    delete qq;

    return 0;
}
<|endoftext|>


<commit_before>
#include <basic-painters/cubescape/CubeScape.h>

#include <array>

#include <glm/glm.hpp>
#include <glm/gtc/matrix_transform.hpp>
#include <glm/gtc/type_ptr.hpp>

#include <glbinding/gl/enum.h>
#include <glbinding/gl/bitfield.h>

#include <globjects/globjects.h>
#include <globjects/logging.h>
#include <globjects/DebugMessage.h>
#include <globjects/VertexAttributeBinding.h>

#include <gloperate/resources/RawFile.h>

#include <gloperate/Camera.h>
#include <gloperate/capabilities/TargetFramebufferCapability.h>
#include <gloperate/capabilities/ViewportCapability.h>
#include <gloperate/capabilities/PerspectiveProjectionCapability.h>
#include <gloperate/capabilities/CameraCapability.h>
#include <gloperate/capabilities/TypedRenderTargetCapability.h>
#include <gloperate/capabilities/CoordinateProviderCapability.h>
#include <gloperate/capabilities/VirtualTimeCapability.h>

using namespace gl;
using namespace glm;
using namespace globjects;

CubeScape::CubeScape(gloperate::ResourceManager & resourceManager)
: Painter(resourceManager)
, m_numCubes(25)
, m_animation(true)
, m_targetFramebufferCapability(new gloperate::TargetFramebufferCapability)
, m_viewportCapability(new gloperate::ViewportCapability)
, m_projectionCapability(new gloperate::PerspectiveProjectionCapability(m_viewportCapability))
, m_typedRenderTargetCapability(new gloperate::TypedRenderTargetCapability())
, m_cameraCapability(new gloperate::CameraCapability())
, m_coordProviderCapability(new gloperate::CoordinateProviderCapability(m_cameraCapability, m_projectionCapability, m_viewportCapability, m_typedRenderTargetCapability))
, m_timeCapability(new gloperate::VirtualTimeCapability)
, a_vertex(-1)
, u_transform(-1)
, u_time(-1)
, u_numcubes(-1)
{
    m_timeCapability->setLoopDuration(20.0f * pi<float>());

    addCapability(m_targetFramebufferCapability);
    addCapability(m_viewportCapability);
    addCapability(m_projectionCapability);
    addCapability(m_cameraCapability);
    addCapability(m_timeCapability);
}

CubeScape::~CubeScape()
{
}

void CubeScape::setupProjection()
{
    m_projectionCapability->setZNear(1.f);
    m_projectionCapability->setZFar(4.f);
    m_projectionCapability->setFovy(radians(50.f));
}

void CubeScape::onInitialize()
{
    // create program

    globjects::init();

#ifdef MAC_OS
    Shader::clearGlobalReplacements();
    Shader::globalReplace("#version 140", "#version 150");

    debug() << "Using global OS X shader replacement '#version 140' -> '#version 150'" << std::endl;
#endif

    m_program = new globjects::Program;
    m_program->attach(
        globjects::Shader::fromFile(GL_VERTEX_SHADER, "data/cubescape/cubescape.vert"),
        globjects::Shader::fromFile(GL_GEOMETRY_SHADER, "data/cubescape/cubescape.geom"),
        globjects::Shader::fromFile(GL_FRAGMENT_SHADER, "data/cubescape/cubescape.frag")
    );

    // create textures

    m_textures[0] = new globjects::Texture;
    m_textures[1] = new globjects::Texture;

    for (int i=0; i < 2; ++i)
    {
        m_textures[i]->setParameter(GL_TEXTURE_WRAP_S, GL_REPEAT);
        m_textures[i]->setParameter(GL_TEXTURE_WRAP_T, GL_REPEAT);

        m_textures[i]->setParameter(GL_TEXTURE_MIN_FILTER, GL_LINEAR);
        m_textures[i]->setParameter(GL_TEXTURE_MAG_FILTER, GL_LINEAR);
    }

    {
        gloperate::RawFile terrain("data/cubescape/terrain.512.512.r.ub.raw");
        if (!terrain.isValid())
            std::cout << "warning: loading texture from " << terrain.filePath() << " failed.";

        m_textures[0]->image2D(0, GL_RED_NV, 512, 512, 0, GL_RED, GL_UNSIGNED_BYTE, terrain.data());
    }

    {
        gloperate::RawFile patches("data/cubescape/patches.64.16.rgb.ub.raw");
        if (!patches.isValid())
            std::cout << "warning: loading texture from " << patches.filePath() << " failed.";

        m_textures[1]->image2D(0, GL_RGB8, 64, 16, 0, GL_RGB, GL_UNSIGNED_BYTE, patches.data());
    }

    m_vao = new globjects::VertexArray;
    m_vao->bind();

    m_vertices = new globjects::Buffer;
    m_indices = new globjects::Buffer;

    const std::array<vec3, 8> vertices =
    {
        vec3(-1.f, -1.f, -1.f ), // 0
        vec3(-1.f, -1.f,  1.f ), // 1
        vec3(-1.f,  1.f, -1.f ), // 2
        vec3(-1.f,  1.f,  1.f ), // 3
        vec3( 1.f, -1.f, -1.f ), // 4
        vec3( 1.f, -1.f,  1.f ), // 5
        vec3( 1.f,  1.f, -1.f ), // 6
        vec3( 1.f,  1.f,  1.f )  // 7
    };

    m_vertices->setData(vertices, GL_STATIC_DRAW);

    const std::array<unsigned char, 18> indices =
        { 2, 3, 6, 0, 1, 2, 1, 5, 3, 5, 4, 7, 4, 0, 6, 5, 1, 4 };

    m_indices->setData(indices, GL_STATIC_DRAW);
    m_indices->bind(GL_ELEMENT_ARRAY_BUFFER);

    // setup uniforms

    a_vertex = m_program->getAttributeLocation("a_vertex");

    m_vao->binding(0)->setAttribute(a_vertex);
    m_vao->binding(0)->setBuffer(m_vertices, 0, sizeof(vec3));
    m_vao->binding(0)->setFormat(3, GL_FLOAT, GL_FALSE, 0);

    m_vao->enable(a_vertex);

    u_transform = m_program->getUniformLocation("modelViewProjection");
    u_time = m_program->getUniformLocation("time");
    u_numcubes = m_program->getUniformLocation("numcubes");

    GLint terrain = m_program->getUniformLocation("terrain");
    GLint patches = m_program->getUniformLocation("patches");

    // since only single program and single data is used, bind only once

    glClearColor(0.f, 0.f, 0.f, 1.0f);

    m_program->setUniform(terrain, 0);
    m_program->setUniform(patches, 1);

    setupProjection();
}

void CubeScape::onPaint()
{
    if (m_viewportCapability->hasChanged())
    {
        glViewport(m_viewportCapability->x(), m_viewportCapability->y(), m_viewportCapability->width(), m_viewportCapability->height());

        m_viewportCapability->setChanged(false);
    }

    globjects::Framebuffer * fbo = m_targetFramebufferCapability->framebuffer();

    if (!fbo)
    {
        fbo = globjects::Framebuffer::defaultFBO();
    }

    fbo->bind(GL_FRAMEBUFFER);

    glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);

    glEnable(GL_DEPTH_TEST);

    mat4 transform = m_projectionCapability->projection() * m_cameraCapability->view() * rotate(mat4(), m_timeCapability->time() * 0.1f, vec3(0.f, 1.f, 0.f));

    m_vao->bind();

    m_indices->bind(GL_ELEMENT_ARRAY_BUFFER);

    m_program->use();

    m_program->setUniform(u_transform, transform);
    m_program->setUniform(u_time, m_timeCapability->time());
    m_program->setUniform(u_numcubes, m_numCubes);

    m_textures[0]->bindActive(GL_TEXTURE0);
    m_textures[1]->bindActive(GL_TEXTURE1);

    m_vao->drawElementsInstanced(GL_TRIANGLES, 18, GL_UNSIGNED_BYTE, nullptr, m_numCubes * m_numCubes);

    m_program->release();
    m_vao->unbind();

    globjects::Framebuffer::unbind(GL_FRAMEBUFFER);
}

int CubeScape::numberOfCubes() const
{
    return m_numCubes;
}

void CubeScape::setNumberOfCubes(const int & number)
{
    m_numCubes = number;
}

bool CubeScape::animation() const
{
    return m_animation;
}

void CubeScape::setAnimation(const bool & enabled)
{
    m_animation = enabled;

    m_timeCapability->setEnabled(m_animation);
}
<commit_msg>add addCapability of coordProviderCapability and typedRenderTargetCapability<commit_after>
#include <basic-painters/cubescape/CubeScape.h>

#include <array>

#include <glm/glm.hpp>
#include <glm/gtc/matrix_transform.hpp>
#include <glm/gtc/type_ptr.hpp>

#include <glbinding/gl/enum.h>
#include <glbinding/gl/bitfield.h>

#include <globjects/globjects.h>
#include <globjects/logging.h>
#include <globjects/DebugMessage.h>
#include <globjects/VertexAttributeBinding.h>

#include <gloperate/resources/RawFile.h>

#include <gloperate/Camera.h>
#include <gloperate/capabilities/TargetFramebufferCapability.h>
#include <gloperate/capabilities/ViewportCapability.h>
#include <gloperate/capabilities/PerspectiveProjectionCapability.h>
#include <gloperate/capabilities/CameraCapability.h>
#include <gloperate/capabilities/TypedRenderTargetCapability.h>
#include <gloperate/capabilities/CoordinateProviderCapability.h>
#include <gloperate/capabilities/VirtualTimeCapability.h>

using namespace gl;
using namespace glm;
using namespace globjects;

CubeScape::CubeScape(gloperate::ResourceManager & resourceManager)
: Painter(resourceManager)
, m_numCubes(25)
, m_animation(true)
, m_targetFramebufferCapability(new gloperate::TargetFramebufferCapability)
, m_viewportCapability(new gloperate::ViewportCapability)
, m_projectionCapability(new gloperate::PerspectiveProjectionCapability(m_viewportCapability))
, m_typedRenderTargetCapability(new gloperate::TypedRenderTargetCapability())
, m_cameraCapability(new gloperate::CameraCapability())
, m_coordProviderCapability(new gloperate::CoordinateProviderCapability(m_cameraCapability, m_projectionCapability, m_viewportCapability, m_typedRenderTargetCapability))
, m_timeCapability(new gloperate::VirtualTimeCapability)
, a_vertex(-1)
, u_transform(-1)
, u_time(-1)
, u_numcubes(-1)
{
    m_timeCapability->setLoopDuration(20.0f * pi<float>());

    addCapability(m_targetFramebufferCapability);
    addCapability(m_viewportCapability);
    addCapability(m_projectionCapability);
    addCapability(m_cameraCapability);
    addCapability(m_timeCapability);
    addCapability(m_coordProviderCapability);
    addCapability(m_typedRenderTargetCapability);
}

CubeScape::~CubeScape()
{
}

void CubeScape::setupProjection()
{
    m_projectionCapability->setZNear(1.f);
    m_projectionCapability->setZFar(4.f);
    m_projectionCapability->setFovy(radians(50.f));
}

void CubeScape::onInitialize()
{
    // create program

    globjects::init();

#ifdef MAC_OS
    Shader::clearGlobalReplacements();
    Shader::globalReplace("#version 140", "#version 150");

    debug() << "Using global OS X shader replacement '#version 140' -> '#version 150'" << std::endl;
#endif

    m_program = new globjects::Program;
    m_program->attach(
        globjects::Shader::fromFile(GL_VERTEX_SHADER, "data/cubescape/cubescape.vert"),
        globjects::Shader::fromFile(GL_GEOMETRY_SHADER, "data/cubescape/cubescape.geom"),
        globjects::Shader::fromFile(GL_FRAGMENT_SHADER, "data/cubescape/cubescape.frag")
    );

    // create textures

    m_textures[0] = new globjects::Texture;
    m_textures[1] = new globjects::Texture;

    for (int i=0; i < 2; ++i)
    {
        m_textures[i]->setParameter(GL_TEXTURE_WRAP_S, GL_REPEAT);
        m_textures[i]->setParameter(GL_TEXTURE_WRAP_T, GL_REPEAT);

        m_textures[i]->setParameter(GL_TEXTURE_MIN_FILTER, GL_LINEAR);
        m_textures[i]->setParameter(GL_TEXTURE_MAG_FILTER, GL_LINEAR);
    }

    {
        gloperate::RawFile terrain("data/cubescape/terrain.512.512.r.ub.raw");
        if (!terrain.isValid())
            std::cout << "warning: loading texture from " << terrain.filePath() << " failed.";

        m_textures[0]->image2D(0, GL_RED_NV, 512, 512, 0, GL_RED, GL_UNSIGNED_BYTE, terrain.data());
    }

    {
        gloperate::RawFile patches("data/cubescape/patches.64.16.rgb.ub.raw");
        if (!patches.isValid())
            std::cout << "warning: loading texture from " << patches.filePath() << " failed.";

        m_textures[1]->image2D(0, GL_RGB8, 64, 16, 0, GL_RGB, GL_UNSIGNED_BYTE, patches.data());
    }

    m_vao = new globjects::VertexArray;
    m_vao->bind();

    m_vertices = new globjects::Buffer;
    m_indices = new globjects::Buffer;

    const std::array<vec3, 8> vertices =
    {
        vec3(-1.f, -1.f, -1.f ), // 0
        vec3(-1.f, -1.f,  1.f ), // 1
        vec3(-1.f,  1.f, -1.f ), // 2
        vec3(-1.f,  1.f,  1.f ), // 3
        vec3( 1.f, -1.f, -1.f ), // 4
        vec3( 1.f, -1.f,  1.f ), // 5
        vec3( 1.f,  1.f, -1.f ), // 6
        vec3( 1.f,  1.f,  1.f )  // 7
    };

    m_vertices->setData(vertices, GL_STATIC_DRAW);

    const std::array<unsigned char, 18> indices =
        { 2, 3, 6, 0, 1, 2, 1, 5, 3, 5, 4, 7, 4, 0, 6, 5, 1, 4 };

    m_indices->setData(indices, GL_STATIC_DRAW);
    m_indices->bind(GL_ELEMENT_ARRAY_BUFFER);

    // setup uniforms

    a_vertex = m_program->getAttributeLocation("a_vertex");

    m_vao->binding(0)->setAttribute(a_vertex);
    m_vao->binding(0)->setBuffer(m_vertices, 0, sizeof(vec3));
    m_vao->binding(0)->setFormat(3, GL_FLOAT, GL_FALSE, 0);

    m_vao->enable(a_vertex);

    u_transform = m_program->getUniformLocation("modelViewProjection");
    u_time = m_program->getUniformLocation("time");
    u_numcubes = m_program->getUniformLocation("numcubes");

    GLint terrain = m_program->getUniformLocation("terrain");
    GLint patches = m_program->getUniformLocation("patches");

    // since only single program and single data is used, bind only once

    glClearColor(0.f, 0.f, 0.f, 1.0f);

    m_program->setUniform(terrain, 0);
    m_program->setUniform(patches, 1);

    setupProjection();
}

void CubeScape::onPaint()
{
    if (m_viewportCapability->hasChanged())
    {
        glViewport(m_viewportCapability->x(), m_viewportCapability->y(), m_viewportCapability->width(), m_viewportCapability->height());

        m_viewportCapability->setChanged(false);
    }

    globjects::Framebuffer * fbo = m_targetFramebufferCapability->framebuffer();

    if (!fbo)
    {
        fbo = globjects::Framebuffer::defaultFBO();
    }

    fbo->bind(GL_FRAMEBUFFER);

    glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);

    glEnable(GL_DEPTH_TEST);

    mat4 transform = m_projectionCapability->projection() * m_cameraCapability->view() * rotate(mat4(), m_timeCapability->time() * 0.1f, vec3(0.f, 1.f, 0.f));

    m_vao->bind();

    m_indices->bind(GL_ELEMENT_ARRAY_BUFFER);

    m_program->use();

    m_program->setUniform(u_transform, transform);
    m_program->setUniform(u_time, m_timeCapability->time());
    m_program->setUniform(u_numcubes, m_numCubes);

    m_textures[0]->bindActive(GL_TEXTURE0);
    m_textures[1]->bindActive(GL_TEXTURE1);

    m_vao->drawElementsInstanced(GL_TRIANGLES, 18, GL_UNSIGNED_BYTE, nullptr, m_numCubes * m_numCubes);

    m_program->release();
    m_vao->unbind();

    globjects::Framebuffer::unbind(GL_FRAMEBUFFER);
}

int CubeScape::numberOfCubes() const
{
    return m_numCubes;
}

void CubeScape::setNumberOfCubes(const int & number)
{
    m_numCubes = number;
}

bool CubeScape::animation() const
{
    return m_animation;
}

void CubeScape::setAnimation(const bool & enabled)
{
    m_animation = enabled;

    m_timeCapability->setEnabled(m_animation);
}
<|endoftext|>


<commit_before>/****************************************************************************
**
** Copyright (C) 2013 Digia Plc and/or its subsidiary(-ies).
** Contact: http://www.qt-project.org/legal
**
** This file is part of Qt Creator.
**
** Commercial License Usage
** Licensees holding valid commercial Qt licenses may use this file in
** accordance with the commercial license agreement provided with the
** Software or, alternatively, in accordance with the terms contained in
** a written agreement between you and Digia.  For licensing terms and
** conditions see http://qt.digia.com/licensing.  For further information
** use the contact form at http://qt.digia.com/contact-us.
**
** GNU Lesser General Public License Usage
** Alternatively, this file may be used under the terms of the GNU Lesser
** General Public License version 2.1 as published by the Free Software
** Foundation and appearing in the file LICENSE.LGPL included in the
** packaging of this file.  Please review the following information to
** ensure the GNU Lesser General Public License version 2.1 requirements
** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
**
** In addition, as a special exception, Digia gives you certain additional
** rights.  These rights are described in the Digia Qt LGPL Exception
** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
**
****************************************************************************/

#include "designeractionmanager.h"
#include "modelnodecontextmenu_helper.h"
#include "modelnodeoperations.h"
#include "componentcore_constants.h"
#include <nodeproperty.h>

#include <QMenu>

namespace QmlDesigner {

static inline QString captionForModelNode(const ModelNode &modelNode)
{
    if (modelNode.id().isEmpty())
        return modelNode.simplifiedTypeName();

    return modelNode.id();
}

static inline bool contains(const QmlItemNode &node, const QPoint &position)
{
    return node.isValid() && node.instanceSceneTransform().mapRect(node.instanceBoundingRect()).contains(position);
}

namespace Internal {

class DesignerActionManagerView : public QmlModelView
{
public:
    DesignerActionManagerView() : QmlModelView(0), m_isInRewriterTransaction(false), m_setupContextDirty(false)
    {}

    void modelAttached(Model *model) QTC_OVERRIDE
    {
        QmlModelView::modelAttached(model);
        setupContext();
    }

    void modelAboutToBeDetached(Model *model) QTC_OVERRIDE
    {
        QmlModelView::modelAboutToBeDetached(model);
        setupContext();
    }

    virtual void nodeCreated(const ModelNode &) QTC_OVERRIDE
    {
        setupContext();
    }

    virtual void nodeAboutToBeRemoved(const ModelNode &) QTC_OVERRIDE
    {}

    virtual void nodeRemoved(const ModelNode &, const NodeAbstractProperty &, PropertyChangeFlags) QTC_OVERRIDE
    {
        setupContext();
    }

    virtual void nodeAboutToBeReparented(const ModelNode &,
                                         const NodeAbstractProperty &,
                                         const NodeAbstractProperty &,
                                         AbstractView::PropertyChangeFlags ) QTC_OVERRIDE
    {
        setupContext();
    }

    virtual void nodeReparented(const ModelNode &, const NodeAbstractProperty &,
                                const NodeAbstractProperty &,
                                AbstractView::PropertyChangeFlags) QTC_OVERRIDE
    {
        setupContext();
    }

    virtual void nodeIdChanged(const ModelNode&, const QString&, const QString&) QTC_OVERRIDE
    {}

    virtual void propertiesAboutToBeRemoved(const QList<AbstractProperty>&) QTC_OVERRIDE
    {}

    virtual void propertiesRemoved(const QList<AbstractProperty>&) QTC_OVERRIDE
    {
        setupContext();
    }

    virtual void variantPropertiesChanged(const QList<VariantProperty>&, PropertyChangeFlags) QTC_OVERRIDE
    {}

    virtual void bindingPropertiesChanged(const QList<BindingProperty>&, PropertyChangeFlags) QTC_OVERRIDE
    {}

    virtual void rootNodeTypeChanged(const QString &, int , int ) QTC_OVERRIDE
    {
        setupContext();
    }

    virtual void instancePropertyChange(const QList<QPair<ModelNode, PropertyName> > &) QTC_OVERRIDE
    {}

    virtual void instancesCompleted(const QVector<ModelNode> &) QTC_OVERRIDE
    {}

    virtual void instanceInformationsChange(const QMultiHash<ModelNode, InformationName> &) QTC_OVERRIDE
    {}

    virtual void instancesRenderImageChanged(const QVector<ModelNode> &) QTC_OVERRIDE
    {}

    virtual void instancesPreviewImageChanged(const QVector<ModelNode> &) QTC_OVERRIDE
    {}

    virtual void instancesChildrenChanged(const QVector<ModelNode> &) QTC_OVERRIDE
    {}

    virtual void instancesToken(const QString &, int , const QVector<ModelNode> &) QTC_OVERRIDE
    {}

    virtual void nodeSourceChanged(const ModelNode &, const QString &) QTC_OVERRIDE
    {}

    virtual void rewriterBeginTransaction() QTC_OVERRIDE
    {
        m_isInRewriterTransaction = true;
    }

    virtual void rewriterEndTransaction() QTC_OVERRIDE
    {
        m_isInRewriterTransaction = false;

        if (m_setupContextDirty)
            setupContext();
    }

    virtual void actualStateChanged(const ModelNode &) QTC_OVERRIDE
    {
        setupContext();
    }

    virtual void selectedNodesChanged(const QList<ModelNode> &,
                                      const QList<ModelNode> &) QTC_OVERRIDE
    {
        setupContext();
    }

    virtual void nodeOrderChanged(const NodeListProperty &, const ModelNode &, int ) QTC_OVERRIDE
    {
        setupContext();
    }

    virtual void importsChanged(const QList<Import> &, const QList<Import> &) QTC_OVERRIDE
    {
        setupContext();
    }

    virtual void scriptFunctionsChanged(const ModelNode &, const QStringList &) QTC_OVERRIDE
    {}

    void setDesignerActionList(const QList<AbstractDesignerAction* > &designerActionList)
    {
        m_designerActionList = designerActionList;
    }

protected:
    void setupContext()
    {
        if (m_isInRewriterTransaction) {
            m_setupContextDirty = true;
            return;
        }
        SelectionContext selectionContext(this);
        foreach (AbstractDesignerAction* action, m_designerActionList) {
            action->currentContextChanged(selectionContext);
        }
        m_setupContextDirty = false;
    }

    QList<AbstractDesignerAction* > m_designerActionList;
    bool m_isInRewriterTransaction;
    bool m_setupContextDirty;
};

} //Internal

DesignerActionManager *DesignerActionManager::m_instance = 0;

void DesignerActionManager::addDesignerAction(AbstractDesignerAction *newAction)
{
    instance()->addDesignerActionInternal(newAction);
}

QList<AbstractDesignerAction* > DesignerActionManager::designerActions()
{
    return instance()->factoriesInternal();
}

QmlModelView *DesignerActionManager::view()
{
    return instance()->m_view;
}

class VisiblityModelNodeAction : public ModelNodeAction
{
public:
    VisiblityModelNodeAction(const QString &description, const QByteArray &category, int priority,
            ModelNodeOperations::SelectionAction action,
            SelectionContextFunction enabled = &SelectionContextFunctors::always,
            SelectionContextFunction visibility = &SelectionContextFunctors::always) :
        ModelNodeAction(description, category, priority, action, enabled, visibility)
    {}
    virtual void updateContext()
    {
        defaultAction()->setSelectionContext(selectionContext());
        if (selectionContext().isValid()) {
            defaultAction()->setEnabled(isEnabled(selectionContext()));
            defaultAction()->setVisible(isVisible(selectionContext()));

            defaultAction()->setCheckable(true);
            QmlItemNode itemNode = QmlItemNode(selectionContext().currentSingleSelectedNode());
            if (itemNode.isValid())
                defaultAction()->setChecked(itemNode.instanceValue("visible").toBool());
            else
                defaultAction()->setEnabled(false);
        }
    }
};

class SelectionModelNodeAction : public MenuDesignerAction
{
public:
    SelectionModelNodeAction(const QString &displayName, const QByteArray &menuId, int priority) :
        MenuDesignerAction(displayName, menuId, priority,
                           &SelectionContextFunctors::always, &SelectionContextFunctors::selectionEnabled)

    {}

    virtual void updateContext()
    {
        m_menu->clear();
        if (m_selectionContext.isValid()) {
            m_action->setEnabled(isEnabled(m_selectionContext));
            m_action->setVisible(isVisible(m_selectionContext));
        } else {
            return;
        }
        if (m_action->isEnabled()) {
            ModelNode parentNode;
            if (m_selectionContext.singleNodeIsSelected() && !m_selectionContext.currentSingleSelectedNode().isRootNode()) {
                ActionTemplate *selectionAction = new ActionTemplate(QString(), &ModelNodeOperations::select);
                selectionAction->setParent(m_menu.data());

                parentNode = m_selectionContext.currentSingleSelectedNode().parentProperty().parentModelNode();
                m_selectionContext.setTargetNode(parentNode);
                selectionAction->setText(QString(QT_TRANSLATE_NOOP("QmlDesignerContextMenu", "Select parent: %1")).arg(
                                             captionForModelNode(parentNode)));
                selectionAction->setSelectionContext(m_selectionContext);

                m_menu->addAction(selectionAction);
            }
            foreach (const ModelNode &node, m_selectionContext.qmlModelView()->allModelNodes()) {
                if (node != m_selectionContext.currentSingleSelectedNode()
                        && node != parentNode
                        && contains(node, m_selectionContext.scenePos())
                        && !node.isRootNode()) {
                    m_selectionContext.setTargetNode(node);
                    QString what = QString(QT_TRANSLATE_NOOP("QmlDesignerContextMenu", "Select: %1")).arg(captionForModelNode(node));
                    ActionTemplate *selectionAction = new ActionTemplate(what, &ModelNodeOperations::select);
                    selectionAction->setSelectionContext(m_selectionContext);

                    m_menu->addAction(selectionAction);
                }
            }
        }
    }
};

char xProperty[] = "x";
char yProperty[] = "y";
char zProperty[] = "z";
char widthProperty[] = "width";
char heightProperty[] = "height";

using namespace SelectionContextFunctors;

bool multiSelection(const SelectionContext &context)
{
    return !singleSelection(context) && selectionNotEmpty(context);
}

bool singleSelectionAndInBaseState(const SelectionContext &context)
{
    return singleSelection(context) && inBaseState(context);
}

bool multiSelectionAndInBaseState(const SelectionContext &context)
{
    return multiSelection(context) && inBaseState(context);
}

bool selectionHasProperty1or2(const SelectionContext &context, const char *x, const char *y)
{
    return selectionHasProperty(context, x) || selectionHasProperty(context, y);
}

bool selectionHasSameParentAndInBaseState(const SelectionContext &context)
{
    return selectionHasSameParent(context) && inBaseState(context);
}

bool selectionCanBeLayouted(const SelectionContext &context)
{
    return selectionHasSameParentAndInBaseState(context) && inBaseState(context);
}

bool selectionNotEmptyAndHasZProperty(const SelectionContext &context)
{
    return selectionNotEmpty(context) && selectionHasProperty(context, zProperty);
}

bool selectionNotEmptyAndHasWidthOrHeightProperty(const SelectionContext &context)
{
    return selectionNotEmpty(context)
        && selectionHasProperty1or2(context, widthProperty, heightProperty);
}

bool selectionNotEmptyAndHasXorYProperty(const SelectionContext &context)
{
    return selectionNotEmpty(context)
        && selectionHasProperty1or2(context, xProperty, yProperty);
}

void DesignerActionManager::createDefaultDesignerActions()
{
    using namespace SelectionContextFunctors;
    using namespace ComponentCoreConstants;
    using namespace ModelNodeOperations;

    addDesignerAction(new SelectionModelNodeAction(selectionCategoryDisplayName, selectionCategory, prioritySelectionCategory));

    addDesignerAction(new MenuDesignerAction(stackCategoryDisplayName, stackCategory, priorityStackCategory, &always));
        addDesignerAction(new ModelNodeAction
                   (toFrontDisplayName, stackCategory, 200, &toFront, &singleSelection));
        addDesignerAction(new ModelNodeAction
                   (toBackDisplayName, stackCategory, 180, &toBack, &singleSelection));
        addDesignerAction(new ModelNodeAction
                   (raiseDisplayName, stackCategory, 160, &raise, &selectionNotEmpty));
        addDesignerAction(new ModelNodeAction
                   (lowerDisplayName, stackCategory, 140, &lower, &selectionNotEmpty));
        addDesignerAction(new SeperatorDesignerAction(stackCategory, 120));
        addDesignerAction(new ModelNodeAction
                   (resetZDisplayName, stackCategory, 100, &resetZ, &selectionNotEmptyAndHasZProperty));

    addDesignerAction(new MenuDesignerAction(editCategoryDisplayName, editCategory, priorityEditCategory, &selectionNotEmpty));
        addDesignerAction(new ModelNodeAction
                   (resetPositionDisplayName, editCategory, 200, &resetPosition, &selectionNotEmptyAndHasXorYProperty));
        addDesignerAction(new ModelNodeAction
                   (resetSizeDisplayName, editCategory, 180, &resetSize, &selectionNotEmptyAndHasWidthOrHeightProperty));
        addDesignerAction(new VisiblityModelNodeAction
                   (visibilityDisplayName, editCategory, 160, &setVisible, &singleSelectedItem));

    addDesignerAction(new MenuDesignerAction(anchorsCategoryDisplayName, anchorsCategory,
                    priorityAnchorsCategory, &singleSelectionAndInBaseState));
        addDesignerAction(new ModelNodeAction
                   (anchorsFillDisplayName, anchorsCategory, 200, &anchorsFill, &singleSelectionItemIsNotAnchored));
        addDesignerAction(new ModelNodeAction
                   (anchorsResetDisplayName, anchorsCategory, 180, &anchorsReset, &singleSelectionItemIsAnchored));

    addDesignerAction(new MenuDesignerAction(layoutCategoryDisplayName, layoutCategory,
                    priorityLayoutCategory, &multiSelectionAndInBaseState));
        addDesignerAction(new ModelNodeAction
                   (layoutRowDisplayName, layoutCategory, 200, &layoutRow, &selectionCanBeLayouted));
        addDesignerAction(new ModelNodeAction
                   (layoutColumnDisplayName, layoutCategory, 180, &layoutColumn, &selectionCanBeLayouted));
        addDesignerAction(new ModelNodeAction
                   (layoutGridDisplayName, layoutCategory, 160, &layoutGrid, &selectionCanBeLayouted));
        addDesignerAction(new ModelNodeAction
                   (layoutFlowDisplayName, layoutCategory, 140, &layoutFlow, &selectionCanBeLayouted));

    addDesignerAction(new SeperatorDesignerAction(rootCategory, priorityTopLevelSeperator));
    addDesignerAction(new ModelNodeAction
               (goIntoComponentDisplayName, rootCategory, priorityGoIntoComponent, &goIntoComponent, &selectionIsComponent));
}

DesignerActionManager *DesignerActionManager::instance()
{
    if (!m_instance) {
        m_instance = new DesignerActionManager;
        createDefaultDesignerActions();
    }

    return m_instance;
}

void DesignerActionManager::addDesignerActionInternal(AbstractDesignerAction *newAction)
{
    m_designerActions.append(QSharedPointer<AbstractDesignerAction>(newAction));
    m_view->setDesignerActionList(designerActions());
}

QList<AbstractDesignerAction* > DesignerActionManager::factoriesInternal() const
{
    QList<AbstractDesignerAction* > list;
    foreach (const QSharedPointer<AbstractDesignerAction> &pointer, m_designerActions) {
        list.append(pointer.data());
    }

    return list;
}

DesignerActionManager::DesignerActionManager() : m_view(new Internal::DesignerActionManagerView)
{
}

DesignerActionManager::~DesignerActionManager()
{
    delete m_view;
}

} //QmlDesigner
<commit_msg>QmlDesigner: Multiselection should be not empty<commit_after>/****************************************************************************
**
** Copyright (C) 2013 Digia Plc and/or its subsidiary(-ies).
** Contact: http://www.qt-project.org/legal
**
** This file is part of Qt Creator.
**
** Commercial License Usage
** Licensees holding valid commercial Qt licenses may use this file in
** accordance with the commercial license agreement provided with the
** Software or, alternatively, in accordance with the terms contained in
** a written agreement between you and Digia.  For licensing terms and
** conditions see http://qt.digia.com/licensing.  For further information
** use the contact form at http://qt.digia.com/contact-us.
**
** GNU Lesser General Public License Usage
** Alternatively, this file may be used under the terms of the GNU Lesser
** General Public License version 2.1 as published by the Free Software
** Foundation and appearing in the file LICENSE.LGPL included in the
** packaging of this file.  Please review the following information to
** ensure the GNU Lesser General Public License version 2.1 requirements
** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
**
** In addition, as a special exception, Digia gives you certain additional
** rights.  These rights are described in the Digia Qt LGPL Exception
** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
**
****************************************************************************/

#include "designeractionmanager.h"
#include "modelnodecontextmenu_helper.h"
#include "modelnodeoperations.h"
#include "componentcore_constants.h"
#include <nodeproperty.h>

#include <QMenu>

namespace QmlDesigner {

static inline QString captionForModelNode(const ModelNode &modelNode)
{
    if (modelNode.id().isEmpty())
        return modelNode.simplifiedTypeName();

    return modelNode.id();
}

static inline bool contains(const QmlItemNode &node, const QPoint &position)
{
    return node.isValid() && node.instanceSceneTransform().mapRect(node.instanceBoundingRect()).contains(position);
}

namespace Internal {

class DesignerActionManagerView : public QmlModelView
{
public:
    DesignerActionManagerView() : QmlModelView(0), m_isInRewriterTransaction(false), m_setupContextDirty(false)
    {}

    void modelAttached(Model *model) QTC_OVERRIDE
    {
        QmlModelView::modelAttached(model);
        setupContext();
    }

    void modelAboutToBeDetached(Model *model) QTC_OVERRIDE
    {
        QmlModelView::modelAboutToBeDetached(model);
        setupContext();
    }

    virtual void nodeCreated(const ModelNode &) QTC_OVERRIDE
    {
        setupContext();
    }

    virtual void nodeAboutToBeRemoved(const ModelNode &) QTC_OVERRIDE
    {}

    virtual void nodeRemoved(const ModelNode &, const NodeAbstractProperty &, PropertyChangeFlags) QTC_OVERRIDE
    {
        setupContext();
    }

    virtual void nodeAboutToBeReparented(const ModelNode &,
                                         const NodeAbstractProperty &,
                                         const NodeAbstractProperty &,
                                         AbstractView::PropertyChangeFlags ) QTC_OVERRIDE
    {
        setupContext();
    }

    virtual void nodeReparented(const ModelNode &, const NodeAbstractProperty &,
                                const NodeAbstractProperty &,
                                AbstractView::PropertyChangeFlags) QTC_OVERRIDE
    {
        setupContext();
    }

    virtual void nodeIdChanged(const ModelNode&, const QString&, const QString&) QTC_OVERRIDE
    {}

    virtual void propertiesAboutToBeRemoved(const QList<AbstractProperty>&) QTC_OVERRIDE
    {}

    virtual void propertiesRemoved(const QList<AbstractProperty>&) QTC_OVERRIDE
    {
        setupContext();
    }

    virtual void variantPropertiesChanged(const QList<VariantProperty>&, PropertyChangeFlags) QTC_OVERRIDE
    {}

    virtual void bindingPropertiesChanged(const QList<BindingProperty>&, PropertyChangeFlags) QTC_OVERRIDE
    {}

    virtual void rootNodeTypeChanged(const QString &, int , int ) QTC_OVERRIDE
    {
        setupContext();
    }

    virtual void instancePropertyChange(const QList<QPair<ModelNode, PropertyName> > &) QTC_OVERRIDE
    {}

    virtual void instancesCompleted(const QVector<ModelNode> &) QTC_OVERRIDE
    {}

    virtual void instanceInformationsChange(const QMultiHash<ModelNode, InformationName> &) QTC_OVERRIDE
    {}

    virtual void instancesRenderImageChanged(const QVector<ModelNode> &) QTC_OVERRIDE
    {}

    virtual void instancesPreviewImageChanged(const QVector<ModelNode> &) QTC_OVERRIDE
    {}

    virtual void instancesChildrenChanged(const QVector<ModelNode> &) QTC_OVERRIDE
    {}

    virtual void instancesToken(const QString &, int , const QVector<ModelNode> &) QTC_OVERRIDE
    {}

    virtual void nodeSourceChanged(const ModelNode &, const QString &) QTC_OVERRIDE
    {}

    virtual void rewriterBeginTransaction() QTC_OVERRIDE
    {
        m_isInRewriterTransaction = true;
    }

    virtual void rewriterEndTransaction() QTC_OVERRIDE
    {
        m_isInRewriterTransaction = false;

        if (m_setupContextDirty)
            setupContext();
    }

    virtual void actualStateChanged(const ModelNode &) QTC_OVERRIDE
    {
        setupContext();
    }

    virtual void selectedNodesChanged(const QList<ModelNode> &,
                                      const QList<ModelNode> &) QTC_OVERRIDE
    {
        setupContext();
    }

    virtual void nodeOrderChanged(const NodeListProperty &, const ModelNode &, int ) QTC_OVERRIDE
    {
        setupContext();
    }

    virtual void importsChanged(const QList<Import> &, const QList<Import> &) QTC_OVERRIDE
    {
        setupContext();
    }

    virtual void scriptFunctionsChanged(const ModelNode &, const QStringList &) QTC_OVERRIDE
    {}

    void setDesignerActionList(const QList<AbstractDesignerAction* > &designerActionList)
    {
        m_designerActionList = designerActionList;
    }

protected:
    void setupContext()
    {
        if (m_isInRewriterTransaction) {
            m_setupContextDirty = true;
            return;
        }
        SelectionContext selectionContext(this);
        foreach (AbstractDesignerAction* action, m_designerActionList) {
            action->currentContextChanged(selectionContext);
        }
        m_setupContextDirty = false;
    }

    QList<AbstractDesignerAction* > m_designerActionList;
    bool m_isInRewriterTransaction;
    bool m_setupContextDirty;
};

} //Internal

DesignerActionManager *DesignerActionManager::m_instance = 0;

void DesignerActionManager::addDesignerAction(AbstractDesignerAction *newAction)
{
    instance()->addDesignerActionInternal(newAction);
}

QList<AbstractDesignerAction* > DesignerActionManager::designerActions()
{
    return instance()->factoriesInternal();
}

QmlModelView *DesignerActionManager::view()
{
    return instance()->m_view;
}

class VisiblityModelNodeAction : public ModelNodeAction
{
public:
    VisiblityModelNodeAction(const QString &description, const QByteArray &category, int priority,
            ModelNodeOperations::SelectionAction action,
            SelectionContextFunction enabled = &SelectionContextFunctors::always,
            SelectionContextFunction visibility = &SelectionContextFunctors::always) :
        ModelNodeAction(description, category, priority, action, enabled, visibility)
    {}
    virtual void updateContext()
    {
        defaultAction()->setSelectionContext(selectionContext());
        if (selectionContext().isValid()) {
            defaultAction()->setEnabled(isEnabled(selectionContext()));
            defaultAction()->setVisible(isVisible(selectionContext()));

            defaultAction()->setCheckable(true);
            QmlItemNode itemNode = QmlItemNode(selectionContext().currentSingleSelectedNode());
            if (itemNode.isValid())
                defaultAction()->setChecked(itemNode.instanceValue("visible").toBool());
            else
                defaultAction()->setEnabled(false);
        }
    }
};

class SelectionModelNodeAction : public MenuDesignerAction
{
public:
    SelectionModelNodeAction(const QString &displayName, const QByteArray &menuId, int priority) :
        MenuDesignerAction(displayName, menuId, priority,
                           &SelectionContextFunctors::always, &SelectionContextFunctors::selectionEnabled)

    {}

    virtual void updateContext()
    {
        m_menu->clear();
        if (m_selectionContext.isValid()) {
            m_action->setEnabled(isEnabled(m_selectionContext));
            m_action->setVisible(isVisible(m_selectionContext));
        } else {
            return;
        }
        if (m_action->isEnabled()) {
            ModelNode parentNode;
            if (m_selectionContext.singleNodeIsSelected() && !m_selectionContext.currentSingleSelectedNode().isRootNode()) {
                ActionTemplate *selectionAction = new ActionTemplate(QString(), &ModelNodeOperations::select);
                selectionAction->setParent(m_menu.data());

                parentNode = m_selectionContext.currentSingleSelectedNode().parentProperty().parentModelNode();
                m_selectionContext.setTargetNode(parentNode);
                selectionAction->setText(QString(QT_TRANSLATE_NOOP("QmlDesignerContextMenu", "Select parent: %1")).arg(
                                             captionForModelNode(parentNode)));
                selectionAction->setSelectionContext(m_selectionContext);

                m_menu->addAction(selectionAction);
            }
            foreach (const ModelNode &node, m_selectionContext.qmlModelView()->allModelNodes()) {
                if (node != m_selectionContext.currentSingleSelectedNode()
                        && node != parentNode
                        && contains(node, m_selectionContext.scenePos())
                        && !node.isRootNode()) {
                    m_selectionContext.setTargetNode(node);
                    QString what = QString(QT_TRANSLATE_NOOP("QmlDesignerContextMenu", "Select: %1")).arg(captionForModelNode(node));
                    ActionTemplate *selectionAction = new ActionTemplate(what, &ModelNodeOperations::select);
                    selectionAction->setSelectionContext(m_selectionContext);

                    m_menu->addAction(selectionAction);
                }
            }
        }
    }
};

char xProperty[] = "x";
char yProperty[] = "y";
char zProperty[] = "z";
char widthProperty[] = "width";
char heightProperty[] = "height";

using namespace SelectionContextFunctors;

bool multiSelection(const SelectionContext &context)
{
    return !singleSelection(context) && selectionNotEmpty(context);
}

bool singleSelectionAndInBaseState(const SelectionContext &context)
{
    return singleSelection(context) && inBaseState(context);
}

bool multiSelectionAndInBaseState(const SelectionContext &context)
{
    return multiSelection(context) && inBaseState(context);
}

bool selectionHasProperty1or2(const SelectionContext &context, const char *x, const char *y)
{
    return selectionHasProperty(context, x) || selectionHasProperty(context, y);
}

bool selectionHasSameParentAndInBaseState(const SelectionContext &context)
{
    return selectionHasSameParent(context) && inBaseState(context);
}

bool selectionCanBeLayouted(const SelectionContext &context)
{
    return selectionHasSameParentAndInBaseState(context) && inBaseState(context);
}

bool selectionNotEmptyAndHasZProperty(const SelectionContext &context)
{
    return selectionNotEmpty(context) && selectionHasProperty(context, zProperty);
}

bool selectionNotEmptyAndHasWidthOrHeightProperty(const SelectionContext &context)
{
    return selectionNotEmpty(context)
        && selectionHasProperty1or2(context, widthProperty, heightProperty);
}

bool selectionNotEmptyAndHasXorYProperty(const SelectionContext &context)
{
    return selectionNotEmpty(context)
        && selectionHasProperty1or2(context, xProperty, yProperty);
}

void DesignerActionManager::createDefaultDesignerActions()
{
    using namespace SelectionContextFunctors;
    using namespace ComponentCoreConstants;
    using namespace ModelNodeOperations;

    addDesignerAction(new SelectionModelNodeAction(selectionCategoryDisplayName, selectionCategory, prioritySelectionCategory));

    addDesignerAction(new MenuDesignerAction(stackCategoryDisplayName, stackCategory, priorityStackCategory, &selectionNotEmpty));
        addDesignerAction(new ModelNodeAction
                   (toFrontDisplayName, stackCategory, 200, &toFront, &singleSelection));
        addDesignerAction(new ModelNodeAction
                   (toBackDisplayName, stackCategory, 180, &toBack, &singleSelection));
        addDesignerAction(new ModelNodeAction
                   (raiseDisplayName, stackCategory, 160, &raise, &selectionNotEmpty));
        addDesignerAction(new ModelNodeAction
                   (lowerDisplayName, stackCategory, 140, &lower, &selectionNotEmpty));
        addDesignerAction(new SeperatorDesignerAction(stackCategory, 120));
        addDesignerAction(new ModelNodeAction
                   (resetZDisplayName, stackCategory, 100, &resetZ, &selectionNotEmptyAndHasZProperty));

    addDesignerAction(new MenuDesignerAction(editCategoryDisplayName, editCategory, priorityEditCategory, &selectionNotEmpty));
        addDesignerAction(new ModelNodeAction
                   (resetPositionDisplayName, editCategory, 200, &resetPosition, &selectionNotEmptyAndHasXorYProperty));
        addDesignerAction(new ModelNodeAction
                   (resetSizeDisplayName, editCategory, 180, &resetSize, &selectionNotEmptyAndHasWidthOrHeightProperty));
        addDesignerAction(new VisiblityModelNodeAction
                   (visibilityDisplayName, editCategory, 160, &setVisible, &singleSelectedItem));

    addDesignerAction(new MenuDesignerAction(anchorsCategoryDisplayName, anchorsCategory,
                    priorityAnchorsCategory, &singleSelectionAndInBaseState));
        addDesignerAction(new ModelNodeAction
                   (anchorsFillDisplayName, anchorsCategory, 200, &anchorsFill, &singleSelectionItemIsNotAnchored));
        addDesignerAction(new ModelNodeAction
                   (anchorsResetDisplayName, anchorsCategory, 180, &anchorsReset, &singleSelectionItemIsAnchored));

    addDesignerAction(new MenuDesignerAction(layoutCategoryDisplayName, layoutCategory,
                    priorityLayoutCategory, &multiSelectionAndInBaseState));
        addDesignerAction(new ModelNodeAction
                   (layoutRowDisplayName, layoutCategory, 200, &layoutRow, &selectionCanBeLayouted));
        addDesignerAction(new ModelNodeAction
                   (layoutColumnDisplayName, layoutCategory, 180, &layoutColumn, &selectionCanBeLayouted));
        addDesignerAction(new ModelNodeAction
                   (layoutGridDisplayName, layoutCategory, 160, &layoutGrid, &selectionCanBeLayouted));
        addDesignerAction(new ModelNodeAction
                   (layoutFlowDisplayName, layoutCategory, 140, &layoutFlow, &selectionCanBeLayouted));

    addDesignerAction(new SeperatorDesignerAction(rootCategory, priorityTopLevelSeperator));
    addDesignerAction(new ModelNodeAction
               (goIntoComponentDisplayName, rootCategory, priorityGoIntoComponent, &goIntoComponent, &selectionIsComponent));
}

DesignerActionManager *DesignerActionManager::instance()
{
    if (!m_instance) {
        m_instance = new DesignerActionManager;
        createDefaultDesignerActions();
    }

    return m_instance;
}

void DesignerActionManager::addDesignerActionInternal(AbstractDesignerAction *newAction)
{
    m_designerActions.append(QSharedPointer<AbstractDesignerAction>(newAction));
    m_view->setDesignerActionList(designerActions());
}

QList<AbstractDesignerAction* > DesignerActionManager::factoriesInternal() const
{
    QList<AbstractDesignerAction* > list;
    foreach (const QSharedPointer<AbstractDesignerAction> &pointer, m_designerActions) {
        list.append(pointer.data());
    }

    return list;
}

DesignerActionManager::DesignerActionManager() : m_view(new Internal::DesignerActionManagerView)
{
}

DesignerActionManager::~DesignerActionManager()
{
    delete m_view;
}

} //QmlDesigner
<|endoftext|>