<commit_before>/*-----------------------------------------------------------------------------------------------
The MIT License (MIT)

Copyright (c) 2015-2018 OSRE ( Open Source Render Engine ) by Kim Kulling

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 <osre/Scene/MaterialBuilder.h>

namespace OSRE {
namespace Scene {

using namespace ::OSRE::RenderBackend;

static const String GLSLVersionString_330 =
    "#version 330 core\n";

static const String GLSLVersionString_400 =
    "#version 400 core\n";

static const String GLSLRenderVertexLayout =
	"// RenderVertex layout\n"
	"layout(location = 0) in vec3 position;	  // object space vertex position\n"
	"layout(location = 1) in vec3 normal;	  // object space vertex normal\n"
	"layout(location = 2) in vec3 color0;     // per-vertex diffuse colour\n"
	"layout(location = 3) in vec2 texcoord0;  // per-vertex tex coord, stage 0\n"
	"\n";

static const String CombinedMVPUniformSrc =
    "// uniform\n"
    "uniform mat4 MVP;	//combined modelview projection matrix\n";

static const String VsSrc =
    GLSLVersionString_400 +
    "\n"
    "layout(location = 0) in vec3 position;	      // object space vertex position\n"
    "layout(location = 1) in vec3 normal;	            // object space vertex normal\n"
    "layout(location = 2) in vec3 color0;  // per-vertex colour\n"
    "\n"
    "// output from the vertex shader\n"
    "smooth out vec4 vSmoothColor;		//smooth colour to fragment shader\n"
    "\n"
    + CombinedMVPUniformSrc +
    "\n"
    "void main() {\n"
    "    // assign the per-vertex color to vSmoothColor varying\n"
    "    vSmoothColor = vec4(color0,1);\n"
    "    // get the clip space position by multiplying the combined MVP matrix with the object space\n"
    "    // vertex position\n"
    "    gl_Position = MVP*vec4(position,1);\n"
    "}\n";

const String FsSrc =
    GLSLVersionString_400 +
    "\n"
    "layout(location=0) out vec4 vFragColor; //fragment shader output\n"
    "\n"
    "//input form the vertex shader\n"
    "smooth in vec4 vSmoothColor;		//interpolated colour to fragment shader\n"
    "\n"
    "void main() {\n"
    "    // set the interpolated color as the shader output\n"
    "    vFragColor = vSmoothColor;\n"
    "}\n";

const String VsSrcRV =
    GLSLVersionString_400 +
    "\n"
	+ GLSLRenderVertexLayout +
    "\n"
    "// output from the vertex shader\n"
    "smooth out vec4 vSmoothColor;		//smooth colour to fragment shader\n"
    "smooth out vec2 vUV;\n"
    "\n"
    + CombinedMVPUniformSrc +
    "\n"
    "void main()\n"
    "{\n"
    "    //assign the per-vertex color to vSmoothColor varying\n"
    "    vSmoothColor = vec4(color0,1);\n"
    "\n"
    "    //get the clip space position by multiplying the combined MVP matrix with the object space\n"
    "    //vertex position\n"
    "    gl_Position = MVP*vec4(position,1);\n"
    "    vSmoothColor = vec4( color0, 1 );\n"
    "    vUV = texcoord0;\n"
    "}\n";

const String FsSrcRV =
    GLSLVersionString_400 +
    "\n"
    "layout(location=0) out vec4 vFragColor; //fragment shader output\n"
    "\n"
    "//input form the vertex shader\n"
    "smooth in vec4 vSmoothColor;		//interpolated colour to fragment shader\n"
    "smooth in vec2 vUV;\n"
    "uniform sampler2D tex0;\n"
    "\n"
    "void main()\n"
    "{\n"
    "    // set the interpolated color as the shader output\n"
    "    vFragColor = texture( tex0, vUV );\n"
    //"    vec4 texColor = texture( tex0, vUV );\n"
	//"    vFragColor = texColor + vSmoothColor;\n"
    "}\n";

const String VsSrcUI =
    GLSLVersionString_400 +
    "\n"
    + GLSLRenderVertexLayout +
    "\n"
    "// fixed point light properties\n"
    "vec3 light_position_world = vec3 (0.0, 0.0, 2.0);\n"
    "vec3 Ls = vec3 (1.0, 1.0, 1.0); // white specular colour\n"
    "vec3 Ld = vec3 (0.7, 0.7, 0.7); // dull white diffuse light colour\n"
    "vec3 La = vec3 (0.2, 0.2, 0.2); // grey ambient colour\n"
    "\n"
    "// surface reflectance\n"
    "vec3 Ks = vec3 (1.0, 1.0, 1.0); // fully reflect specular light\n"
    "vec3 Kd = vec3 (1.0, 0.5, 0.0); // orange diffuse surface reflectance\n"
    "vec3 Ka = vec3 (1.0, 1.0, 1.0); // fully reflect ambient light\n"
    "float specular_exponent = 100.0; // specular 'power'\n"
    "\n"
    "// output from the vertex shader\n"
    "smooth out vec4 vSmoothColor;		//smooth colour to fragment shader\n"
    "smooth out vec2 vUV;\n"
    "\n"
    + CombinedMVPUniformSrc +
    "\n"
    "void main()\n"
    "{\n"
    "    //assign the per-vertex color to vSmoothColor varying\n"
    "    vSmoothColor = vec4(color0,1);\n"
    "\n"
    "    //get the clip space position by multiplying the combined MVP matrix with the object space\n"
    "    //vertex position\n"
    "    gl_Position = MVP*vec4(position,1);\n"
    "    vSmoothColor = vec4( color0, 1 );\n"
    "    vUV = texcoord0;\n"
    "}\n";

const String FsSrcUI =
    GLSLVersionString_400 +
    "\n"
    "layout(location=0) out vec4 vFragColor; //fragment shader output\n"
    "\n"
    "//input form the vertex shader\n"
    "smooth in vec4 vSmoothColor;		//interpolated colour to fragment shader\n"
    "smooth in vec2 vUV;\n"
    "uniform sampler2D tex0;\n"
    "\n"
    "void main()\n"
    "{\n"
    "    // set the interpolated color as the shader output\n"
    "    vFragColor = vSmoothColor;\n"
    "}\n";

static const String VSLightRenderVertexSrc =
    "";

static const String FSLightRenderVertexSrc =
    "";

static const String MaterialParameterStruct =
    "struct MaterialParameter {\n"
    "    vec3 ka;\n"
    "    vec3 kd;\n"
    "    vec3 ks;\n"
    "}\n";

MaterialBuilder::MaterialBuilder() {
    // empty
}

MaterialBuilder::~MaterialBuilder() {
    // empty
}

 Material *MaterialBuilder::createBuildinMaterial(VertexType type) {
    Material *mat = new Material( "shadermaterial", MaterialType::ShaderMaterial);

    String vs, fs;
    if ( type == VertexType::ColorVertex ) {
        vs = VsSrc;
        fs = FsSrc;
    } else if ( type == VertexType::RenderVertex ) {
        vs = VsSrcRV;
        fs = FsSrcRV;
    }

    if ( vs.empty() || fs.empty() ) {
        delete mat;
        return nullptr;
    }
    ShaderSourceArray arr;
    arr[ static_cast<ui32>( ShaderType::SH_VertexShaderType ) ] = vs;
    arr[ static_cast<ui32>( ShaderType::SH_FragmentShaderType ) ] = fs;
    mat->createShader(arr);

    // Setup shader attributes and variables
    if ( nullptr != mat->m_shader ) {
        if ( type == VertexType::ColorVertex ) {
            ui32 numAttribs( ColorVert::getNumAttributes() );
            const String *attribs( ColorVert::getAttributes() );
            mat->m_shader->m_attributes.add( attribs, numAttribs );
        } else if ( type == VertexType::RenderVertex ) {
            ui32 numAttribs( RenderVert::getNumAttributes() );
            const String *attribs( RenderVert::getAttributes() );
            mat->m_shader->m_attributes.add( attribs, numAttribs );
        }

        mat->m_shader->m_parameters.add( "MVP" );
    }

    return mat;
}

Material *MaterialBuilder::createBuildinUiMaterial() {
    Material *mat = new Material( "shadermaterial", MaterialType::ShaderMaterial );
    ShaderSourceArray arr;
    arr[static_cast<ui32>(ShaderType::SH_VertexShaderType)] = VsSrcUI;
    arr[static_cast<ui32>(ShaderType::SH_FragmentShaderType)] = FsSrcUI;
    mat->createShader(arr);

    // setup shader attributes and variables
    if ( nullptr != mat->m_shader ) {
        ui32 numAttribs( RenderVert::getNumAttributes() );
        const String *attribs( RenderVert::getAttributes() );
        mat->m_shader->m_attributes.add( attribs, numAttribs );
        mat->m_shader->m_parameters.add( "MVP" );
    }

    return mat;
}

} // Namespace Scene
} // namespace OSRE
<commit_msg>Scene: tag GLSL-shader with the prefix GLSL.<commit_after>/*-----------------------------------------------------------------------------------------------
The MIT License (MIT)

Copyright (c) 2015-2018 OSRE ( Open Source Render Engine ) by Kim Kulling

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 <osre/Scene/MaterialBuilder.h>

namespace OSRE {
namespace Scene {

using namespace ::OSRE::RenderBackend;

static const String GLSLVersionString_330 =
    "#version 330 core\n";

static const String GLSLVersionString_400 =
    "#version 400 core\n";

static const String GLSLRenderVertexLayout =
	"// RenderVertex layout\n"
	"layout(location = 0) in vec3 position;	  // object space vertex position\n"
	"layout(location = 1) in vec3 normal;	  // object space vertex normal\n"
	"layout(location = 2) in vec3 color0;     // per-vertex diffuse colour\n"
	"layout(location = 3) in vec2 texcoord0;  // per-vertex tex coord, stage 0\n"
	"\n";

static const String GLSLCombinedMVPUniformSrc =
    "// uniform\n"
    "uniform mat4 MVP;	//combined modelview projection matrix\n";

static const String GLSLVsSrc =
    GLSLVersionString_400 +
    "\n"
    "layout(location = 0) in vec3 position;	      // object space vertex position\n"
    "layout(location = 1) in vec3 normal;	            // object space vertex normal\n"
    "layout(location = 2) in vec3 color0;  // per-vertex colour\n"
    "\n"
    "// output from the vertex shader\n"
    "smooth out vec4 vSmoothColor;		//smooth colour to fragment shader\n"
    "\n"
    + GLSLCombinedMVPUniformSrc +
    "\n"
    "void main() {\n"
    "    // assign the per-vertex color to vSmoothColor varying\n"
    "    vSmoothColor = vec4(color0,1);\n"
    "    // get the clip space position by multiplying the combined MVP matrix with the object space\n"
    "    // vertex position\n"
    "    gl_Position = MVP*vec4(position,1);\n"
    "}\n";

const String GLSLFsSrc =
    GLSLVersionString_400 +
    "\n"
    "layout(location=0) out vec4 vFragColor; //fragment shader output\n"
    "\n"
    "//input form the vertex shader\n"
    "smooth in vec4 vSmoothColor;		//interpolated colour to fragment shader\n"
    "\n"
    "void main() {\n"
    "    // set the interpolated color as the shader output\n"
    "    vFragColor = vSmoothColor;\n"
    "}\n";

const String GLSLVsSrcRV =
    GLSLVersionString_400 +
    "\n"
	+ GLSLRenderVertexLayout +
    "\n"
    "// output from the vertex shader\n"
    "smooth out vec4 vSmoothColor;		//smooth colour to fragment shader\n"
    "smooth out vec2 vUV;\n"
    "\n"
    + GLSLCombinedMVPUniformSrc +
    "\n"
    "void main()\n"
    "{\n"
    "    //assign the per-vertex color to vSmoothColor varying\n"
    "    vSmoothColor = vec4(color0,1);\n"
    "\n"
    "    //get the clip space position by multiplying the combined MVP matrix with the object space\n"
    "    //vertex position\n"
    "    gl_Position = MVP*vec4(position,1);\n"
    "    vSmoothColor = vec4( color0, 1 );\n"
    "    vUV = texcoord0;\n"
    "}\n";

const String GLSLFsSrcRV =
    GLSLVersionString_400 +
    "\n"
    "layout(location=0) out vec4 vFragColor; //fragment shader output\n"
    "\n"
    "//input form the vertex shader\n"
    "smooth in vec4 vSmoothColor;		//interpolated colour to fragment shader\n"
    "smooth in vec2 vUV;\n"
    "uniform sampler2D tex0;\n"
    "\n"
    "void main()\n"
    "{\n"
    "    // set the interpolated color as the shader output\n"
    "    vFragColor = texture( tex0, vUV );\n"
    //"    vec4 texColor = texture( tex0, vUV );\n"
	//"    vFragColor = texColor + vSmoothColor;\n"
    "}\n";

const String GLSLVsSrcUI =
    GLSLVersionString_400 +
    "\n"
    + GLSLRenderVertexLayout +
    "\n"
    "// fixed point light properties\n"
    "vec3 light_position_world = vec3 (0.0, 0.0, 2.0);\n"
    "vec3 Ls = vec3 (1.0, 1.0, 1.0); // white specular colour\n"
    "vec3 Ld = vec3 (0.7, 0.7, 0.7); // dull white diffuse light colour\n"
    "vec3 La = vec3 (0.2, 0.2, 0.2); // grey ambient colour\n"
    "\n"
    "// surface reflectance\n"
    "vec3 Ks = vec3 (1.0, 1.0, 1.0); // fully reflect specular light\n"
    "vec3 Kd = vec3 (1.0, 0.5, 0.0); // orange diffuse surface reflectance\n"
    "vec3 Ka = vec3 (1.0, 1.0, 1.0); // fully reflect ambient light\n"
    "float specular_exponent = 100.0; // specular 'power'\n"
    "\n"
    "// output from the vertex shader\n"
    "smooth out vec4 vSmoothColor;		//smooth colour to fragment shader\n"
    "smooth out vec2 vUV;\n"
    "\n"
    + GLSLCombinedMVPUniformSrc +
    "\n"
    "void main()\n"
    "{\n"
    "    //assign the per-vertex color to vSmoothColor varying\n"
    "    vSmoothColor = vec4(color0,1);\n"
    "\n"
    "    //get the clip space position by multiplying the combined MVP matrix with the object space\n"
    "    //vertex position\n"
    "    gl_Position = MVP*vec4(position,1);\n"
    "    vSmoothColor = vec4( color0, 1 );\n"
    "    vUV = texcoord0;\n"
    "}\n";

const String GLSLFsSrcUI =
    GLSLVersionString_400 +
    "\n"
    "layout(location=0) out vec4 vFragColor; //fragment shader output\n"
    "\n"
    "//input form the vertex shader\n"
    "smooth in vec4 vSmoothColor;		//interpolated colour to fragment shader\n"
    "smooth in vec2 vUV;\n"
    "uniform sampler2D tex0;\n"
    "\n"
    "void main()\n"
    "{\n"
    "    // set the interpolated color as the shader output\n"
    "    vFragColor = vSmoothColor;\n"
    "}\n";

static const String GLSLVSLightRenderVertexSrc =
    "";

static const String GLSLFSLightRenderVertexSrc =
    "";

static const String GLSLMaterialParameterStruct =
    "struct MaterialParameter {\n"
    "    vec3 ka;\n"
    "    vec3 kd;\n"
    "    vec3 ks;\n"
    "}\n";

MaterialBuilder::MaterialBuilder() {
    // empty
}

MaterialBuilder::~MaterialBuilder() {
    // empty
}

 Material *MaterialBuilder::createBuildinMaterial(VertexType type) {
    Material *mat = new Material( "shadermaterial", MaterialType::ShaderMaterial);

    String vs, fs;
    if ( type == VertexType::ColorVertex ) {
        vs = GLSLVsSrc;
        fs = GLSLFsSrc;
    } else if ( type == VertexType::RenderVertex ) {
        vs = GLSLVsSrcRV;
        fs = GLSLFsSrcRV;
    }

    if ( vs.empty() || fs.empty() ) {
        delete mat;
        return nullptr;
    }
    ShaderSourceArray arr;
    arr[ static_cast<ui32>( ShaderType::SH_VertexShaderType ) ] = vs;
    arr[ static_cast<ui32>( ShaderType::SH_FragmentShaderType ) ] = fs;
    mat->createShader(arr);

    // Setup shader attributes and variables
    if ( nullptr != mat->m_shader ) {
        if ( type == VertexType::ColorVertex ) {
            ui32 numAttribs( ColorVert::getNumAttributes() );
            const String *attribs( ColorVert::getAttributes() );
            mat->m_shader->m_attributes.add( attribs, numAttribs );
        } else if ( type == VertexType::RenderVertex ) {
            ui32 numAttribs( RenderVert::getNumAttributes() );
            const String *attribs( RenderVert::getAttributes() );
            mat->m_shader->m_attributes.add( attribs, numAttribs );
        }

        mat->m_shader->m_parameters.add( "MVP" );
    }

    return mat;
}

Material *MaterialBuilder::createBuildinUiMaterial() {
    Material *mat = new Material( "shadermaterial", MaterialType::ShaderMaterial );
    ShaderSourceArray arr;
    arr[static_cast<ui32>(ShaderType::SH_VertexShaderType)] = GLSLVsSrcUI;
    arr[static_cast<ui32>(ShaderType::SH_FragmentShaderType)] = GLSLFsSrcUI;
    mat->createShader(arr);

    // setup shader attributes and variables
    if ( nullptr != mat->m_shader ) {
        ui32 numAttribs( RenderVert::getNumAttributes() );
        const String *attribs( RenderVert::getAttributes() );
        mat->m_shader->m_attributes.add( attribs, numAttribs );
        mat->m_shader->m_parameters.add( "MVP" );
    }

    return mat;
}

} // Namespace Scene
} // namespace OSRE
<|endoftext|>


<commit_before><commit_msg>title bar is now restored as well<commit_after><|endoftext|>


<commit_before>/**
 * @file network_traits.hpp
 * @author Marcus Edel
 *
 * NetworkTraits class, a template class to get information about various
 * networks.
 */
#ifndef __MLPACK_METHODS_ANN_NETWORK_TRAITS_HPP
#define __MLPACK_METHODS_ANN_NETWORK_TRAITS_HPP

namespace mlpack {
namespace ann {

/**
 * This is a template class that can provide information about various
 * networks. By default, this class will provide the weakest possible
 * assumptions on networks, and each network should override values as
 * necessary. If a network doesn't need to override a value, then there's no
 * need to write a NetworkTraits specialization for that class.
 */
template<typename NetworkType>
class NetworkTraits
{
 public:
  /**
   * This is true if the network is a feed forward neural network.
   */
  static const bool IsFNN = false;

  /**
   * This is true if the network is a recurrent neural network.
   */
  static const bool IsRNN = false;

  /**
   * This is true if the network is a convolutional neural network.
   */
  static const bool IsCNN = false;
};

} // namespace ann
} // namespace mlpack

#endif

<commit_msg>Add the sparse autoencoder to the network traits.<commit_after>/**
 * @file network_traits.hpp
 * @author Marcus Edel
 *
 * NetworkTraits class, a template class to get information about various
 * networks.
 */
#ifndef __MLPACK_METHODS_ANN_NETWORK_TRAITS_HPP
#define __MLPACK_METHODS_ANN_NETWORK_TRAITS_HPP

namespace mlpack {
namespace ann {

/**
 * This is a template class that can provide information about various
 * networks. By default, this class will provide the weakest possible
 * assumptions on networks, and each network should override values as
 * necessary. If a network doesn't need to override a value, then there's no
 * need to write a NetworkTraits specialization for that class.
 */
template<typename NetworkType>
class NetworkTraits
{
 public:
  /**
   * This is true if the network is a feed forward neural network.
   */
  static const bool IsFNN = false;

  /**
   * This is true if the network is a recurrent neural network.
   */
  static const bool IsRNN = false;

  /**
   * This is true if the network is a convolutional neural network.
   */
  static const bool IsCNN = false;

  /**
   * This is true if the network is a sparse autoencoder.
   */
  static const bool IsSAE = false;
};

} // namespace ann
} // namespace mlpack

#endif

<|endoftext|>


<commit_before>#pragma once

#include <vector>
#include <iostream>

#include <opencv2/opencv.hpp>

namespace openMVG{
namespace calibration{

enum Pattern
{
  CHESSBOARD = 0,
  CIRCLES_GRID,
  ASYMMETRIC_CIRCLES_GRID,
  ASYMMETRIC_CCTAG_GRID
};

/**
 * @brief Read pattern from console.
 *
 * @param[in,out] stream
 * @param[in] pattern
 * @return stream
 */
std::istream& operator>>(std::istream &stream, Pattern &pattern);

/**
 * @brief Write pattern to console.
 *
 * @param[out] stream
 * @param[in] pattern
 * @return stream
 */
std::ostream& operator<<(std::ostream &stream, const Pattern pattern);

/**
 * @brief This function detects the checkerboard in images
 *
 * @param[in] pattern The type of pattern used for the calibration.
 * @param[in] viewGray The image in gray level.
 * @param[in] boardSize The size of the calibration pattern.
 * @param[out] detectedId Id of the detected CCTags.
 * @param[out] pointbuf Coordinates of the 2D points in each image.
 * @return True if the pattern is found, otherwise false.
 */
bool findPattern(const Pattern& pattern, const cv::Mat& viewGray, const cv::Size& boardSize, std::vector<int>& detectedId, std::vector<cv::Point2f>& pointbuf);

/**
 * @brief This function computes the points' coordinates of the checkerboard.
 *
 * @param[out] corners Coordinates of the 2D points in each image.
 * @param[in] boardSize The size of the calibration pattern.
 * @param[in] squareSize The distance between two points of the calibration pattern.
 * @param[in] pattern The type of pattern used for the calibration.
 */
void calcChessboardCorners(std::vector<cv::Point3f>& corners, const cv::Size& boardSize,
                           const float squareSize, Pattern pattern);

/**
 * @brief This function creates an object which stores all the points of the images.
 *
 * @param[in] boardSize The size of the calibration pattern.
 * @param[in] pattern The type of pattern used for the calibration.
 * @param[in] squareSize The distance between two points of the calibration pattern.
 * @param[in] imagePoints Coordinates of the 2D points in each image of the sequence.
 * @param[out] objectPoints Coordinates of the 3D points in each image of the sequence.
 */
void computeObjectPoints(const cv::Size& boardSize, Pattern pattern, const float squareSize,
                         const std::vector<std::vector<cv::Point2f> >& imagePoints,
                         std::vector<std::vector<cv::Point3f> >& objectPoints);

}//namespace calibration
}//namespace openMVG

<commit_msg>[cctag] add missing ifdef<commit_after>#pragma once

#include <vector>
#include <iostream>

#include <opencv2/opencv.hpp>

namespace openMVG{
namespace calibration{

enum Pattern
{
  CHESSBOARD = 0,
  CIRCLES_GRID = 1,
  ASYMMETRIC_CIRCLES_GRID = 2
#ifdef HAVE_CCTAG
  , ASYMMETRIC_CCTAG_GRID = 4
#endif
};

/**
 * @brief Read pattern from console.
 *
 * @param[in,out] stream
 * @param[in] pattern
 * @return stream
 */
std::istream& operator>>(std::istream &stream, Pattern &pattern);

/**
 * @brief Write pattern to console.
 *
 * @param[out] stream
 * @param[in] pattern
 * @return stream
 */
std::ostream& operator<<(std::ostream &stream, const Pattern pattern);

/**
 * @brief This function detects the checkerboard in images
 *
 * @param[in] pattern The type of pattern used for the calibration.
 * @param[in] viewGray The image in gray level.
 * @param[in] boardSize The size of the calibration pattern.
 * @param[out] detectedId Id of the detected CCTags.
 * @param[out] pointbuf Coordinates of the 2D points in each image.
 * @return True if the pattern is found, otherwise false.
 */
bool findPattern(const Pattern& pattern, const cv::Mat& viewGray, const cv::Size& boardSize, std::vector<int>& detectedId, std::vector<cv::Point2f>& pointbuf);

/**
 * @brief This function computes the points' coordinates of the checkerboard.
 *
 * @param[out] corners Coordinates of the 2D points in each image.
 * @param[in] boardSize The size of the calibration pattern.
 * @param[in] squareSize The distance between two points of the calibration pattern.
 * @param[in] pattern The type of pattern used for the calibration.
 */
void calcChessboardCorners(std::vector<cv::Point3f>& corners, const cv::Size& boardSize,
                           const float squareSize, Pattern pattern);

/**
 * @brief This function creates an object which stores all the points of the images.
 *
 * @param[in] boardSize The size of the calibration pattern.
 * @param[in] pattern The type of pattern used for the calibration.
 * @param[in] squareSize The distance between two points of the calibration pattern.
 * @param[in] imagePoints Coordinates of the 2D points in each image of the sequence.
 * @param[out] objectPoints Coordinates of the 3D points in each image of the sequence.
 */
void computeObjectPoints(const cv::Size& boardSize, Pattern pattern, const float squareSize,
                         const std::vector<std::vector<cv::Point2f> >& imagePoints,
                         std::vector<std::vector<cv::Point3f> >& objectPoints);

}//namespace calibration
}//namespace openMVG

<|endoftext|>


<commit_before>/****************************************************************************
**
** Copyright (C) 2015 The Qt Company Ltd.
** Contact: http://www.qt.io/licensing
**
** 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 The Qt Company.  For licensing terms and
** conditions see http://www.qt.io/terms-conditions.  For further information
** use the contact form at http://www.qt.io/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 or version 3 as published by the Free
** Software Foundation and appearing in the file LICENSE.LGPLv21 and
** LICENSE.LGPLv3 included in the packaging of this file.  Please review the
** following information to ensure the GNU Lesser General Public License
** requirements will be met: https://www.gnu.org/licenses/lgpl.html and
** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
**
** In addition, as a special exception, The Qt Company gives you certain additional
** rights.  These rights are described in The Qt Company LGPL Exception
** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
**
****************************************************************************/

#include "iwizardfactory.h"

#include "actionmanager/actionmanager.h"
#include "documentmanager.h"
#include "icore.h"
#include "featureprovider.h"

#include <extensionsystem/pluginspec.h>
#include <extensionsystem/pluginmanager.h>

#include <utils/qtcassert.h>

#include <QAction>

/*!
    \class Core::IWizardFactory
    \mainclass

    \brief The class IWizardFactory is the base class for all wizard factories
    (for example shown in \gui {File | New}).

    The wizard interface is a very thin abstraction for the \gui{New...} wizards.
    Basically it defines what to show to the user in the wizard selection dialogs,
    and a hook that is called if the user selects the wizard.

    Wizards can then perform any operations they like, including showing dialogs and
    creating files. Often it is not necessary to create your own wizard from scratch,
    instead use one of the predefined wizards and adapt it to your needs.

    To make your wizard known to the system, add your IWizardFactory instance to the
    plugin manager's object pool in your plugin's initialize function:
    \code
        bool MyPlugin::initialize(const QStringList &arguments, QString *errorString)
        {
            // ... do setup
            addAutoReleasedObject(new MyWizardFactory);
            // ... do more setup
        }
    \endcode
    \sa Core::BaseFileWizard
    \sa Core::StandardFileWizard
*/

/*!
    \enum Core::IWizardFactory::WizardKind
    Used to specify what kind of objects the wizard creates. This information is used
    to show e.g. only wizards that create projects when selecting a \gui{New Project}
    menu item.
    \value FileWizard
        The wizard creates one or more files.
    \value ClassWizard
        The wizard creates a new class (e.g. source+header files).
    \value ProjectWizard
        The wizard creates a new project.
*/

/*!
    \fn IWizardFactory::IWizardFactory(QObject *parent)
    \internal
*/

/*!
    \fn IWizardFactory::~IWizardFactory()
    \internal
*/

/*!
    \fn Kind IWizardFactory::kind() const
    Returns what kind of objects are created by the wizard.
    \sa Kind
*/

/*!
    \fn QIcon IWizardFactory::icon() const
    Returns an icon to show in the wizard selection dialog.
*/

/*!
    \fn QString IWizardFactory::description() const
    Returns a translated description to show when this wizard is selected
    in the dialog.
*/

/*!
    \fn QString IWizardFactory::displayName() const
    Returns the translated name of the wizard, how it should appear in the
    dialog.
*/

/*!
    \fn QString IWizardFactory::id() const
    Returns an arbitrary id that is used for sorting within the category.
*/

/*!
    \fn QString IWizardFactory::category() const
    Returns a category ID to add the wizard to.
*/

/*!
    \fn QString IWizardFactory::displayCategory() const
    Returns the translated string of the category, how it should appear
    in the dialog.
*/

/*!
    \fn void IWizardFactory::runWizard(const QString &path,
                                      QWidget *parent,
                                      const QString &platform,
                                      const QVariantMap &variables)

    This function is executed when the wizard has been selected by the user
    for execution. Any dialogs the wizard opens should use the given \a parent.
    The \a path argument is a suggestion for the location where files should be
    created. The wizard should fill this in its path selection elements as a
    default path.
*/

using namespace Core;

namespace {
static QList<IFeatureProvider *> s_providerList;
QList<IWizardFactory *> s_allFactories;
QList<IWizardFactory::FactoryCreator> s_factoryCreators;
bool s_areFactoriesLoaded = false;
bool s_isWizardRunning = false;
}

/* A utility to find all wizards supporting a view mode and matching a predicate */
QList<IWizardFactory*> findWizardFactories(const std::function<bool(IWizardFactory*)> &predicate)
{
    const QList<IWizardFactory *> allFactories = IWizardFactory::allWizardFactories();
    QList<IWizardFactory *> rc;
    auto cend = allFactories.constEnd();
    for (auto it = allFactories.constBegin(); it != cend; ++it) {
        if (predicate(*it))
            rc.push_back(*it);
    }
    return rc;
}

static Id actionId(const IWizardFactory *factory)
{
    return factory->id().withPrefix("Wizard.Impl.");
}

QList<IWizardFactory*> IWizardFactory::allWizardFactories()
{
    if (!s_areFactoriesLoaded) {
        QTC_ASSERT(s_allFactories.isEmpty(), return s_allFactories);

        s_areFactoriesLoaded = true;

        QHash<Id, IWizardFactory *> sanityCheck;
        foreach (const FactoryCreator &fc, s_factoryCreators) {
            QList<IWizardFactory *> tmp = fc();
            foreach (IWizardFactory *newFactory, tmp) {
                QTC_ASSERT(newFactory, continue);
                IWizardFactory *existingFactory = sanityCheck.value(newFactory->id());

                QTC_ASSERT(existingFactory != newFactory, continue);
                if (existingFactory) {
                    qWarning("%s", qPrintable(tr("Factory with id=\"%1\" already registered. Deleting.")
                                              .arg(existingFactory->id().toString())));
                    delete newFactory;
                    continue;
                }

                QTC_ASSERT(!newFactory->m_action, continue);
                newFactory->m_action = new QAction(newFactory->displayName(), newFactory);
                ActionManager::registerAction(newFactory->m_action, actionId(newFactory));

                connect(newFactory->m_action, &QAction::triggered, newFactory, [newFactory]() {
                    QString path = newFactory->runPath(QString());
                    newFactory->runWizard(path, ICore::dialogParent(), QString(), QVariantMap());
                });

                sanityCheck.insert(newFactory->id(), newFactory);
                s_allFactories << newFactory;
            }
        }
    }

    return s_allFactories;
}

// Utility to find all registered wizards of a certain kind
QList<IWizardFactory*> IWizardFactory::wizardFactoriesOfKind(WizardKind kind)
{
    return findWizardFactories([kind](IWizardFactory *f) { return f->kind() == kind; });
}

QString IWizardFactory::runPath(const QString &defaultPath)
{
    QString path = defaultPath;
    if (path.isEmpty()) {
        switch (kind()) {
        case IWizardFactory::ProjectWizard:
            // Project wizards: Check for projects directory or
            // use last visited directory of file dialog. Never start
            // at current.
            path = DocumentManager::useProjectsDirectory() ?
                       DocumentManager::projectsDirectory() :
                       DocumentManager::fileDialogLastVisitedDirectory();
            break;
        default:
            path = DocumentManager::fileDialogInitialDirectory();
            break;
        }
    }
    return path;
}

void IWizardFactory::runWizard(const QString &path, QWidget *parent, const QString &platform, const QVariantMap &variables)
{
    s_isWizardRunning = true;
    ICore::validateNewDialogIsRunning();

    runWizardImpl(path, parent, platform, variables);

    s_isWizardRunning = false;
    ICore::validateNewDialogIsRunning();
}

bool IWizardFactory::isAvailable(const QString &platformName) const
{
    if (platformName.isEmpty())
        return true;

    return availableFeatures(platformName).contains(requiredFeatures());
}

QStringList IWizardFactory::supportedPlatforms() const
{
    QStringList stringList;

    foreach (const QString &platform, allAvailablePlatforms()) {
        if (isAvailable(platform))
            stringList.append(platform);
    }

    return stringList;
}

void IWizardFactory::registerFactoryCreator(const IWizardFactory::FactoryCreator &creator)
{
    s_factoryCreators << creator;
}

QStringList IWizardFactory::allAvailablePlatforms()
{
    QStringList platforms;

    foreach (const IFeatureProvider *featureManager, s_providerList)
        platforms.append(featureManager->availablePlatforms());

    return platforms;
}

QString IWizardFactory::displayNameForPlatform(const QString &string)
{
    foreach (const IFeatureProvider *featureManager, s_providerList) {
        QString displayName = featureManager->displayNameForPlatform(string);
        if (!displayName.isEmpty())
            return displayName;
    }
    return QString();
}

void IWizardFactory::registerFeatureProvider(IFeatureProvider *provider)
{
    QTC_ASSERT(!s_providerList.contains(provider), return);
    s_providerList.append(provider);
}

bool IWizardFactory::isWizardRunning()
{
    return s_isWizardRunning;
}

void IWizardFactory::destroyFeatureProvider()
{
    qDeleteAll(s_providerList);
    s_providerList.clear();
}

void IWizardFactory::clearWizardFactories()
{
    foreach (IWizardFactory *factory, s_allFactories)
        ActionManager::unregisterAction(factory->m_action, actionId(factory));

    qDeleteAll(s_allFactories);
    s_allFactories.clear();

    s_areFactoriesLoaded = false;
}

FeatureSet IWizardFactory::pluginFeatures() const
{
    static FeatureSet plugins;
    if (plugins.isEmpty()) {
        QStringList list;
        // Implicitly create a feature for each plugin loaded:
        foreach (ExtensionSystem::PluginSpec *s, ExtensionSystem::PluginManager::plugins()) {
            if (s->state() == ExtensionSystem::PluginSpec::Running)
                list.append(s->name());
        }
        plugins = FeatureSet::fromStringList(list);
    }
    return plugins;
}

FeatureSet IWizardFactory::availableFeatures(const QString &platformName) const
{
    FeatureSet availableFeatures;

    foreach (const IFeatureProvider *featureManager, s_providerList)
        availableFeatures |= featureManager->availableFeatures(platformName);

    return availableFeatures;
}

void IWizardFactory::initialize()
{
    connect(ICore::instance(), &ICore::coreAboutToClose, &IWizardFactory::clearWizardFactories);

    auto resetAction = new QAction(tr("Reload All Wizards"), ActionManager::instance());
    ActionManager::registerAction(resetAction, "Wizard.Factory.Reset");

    connect(resetAction, &QAction::triggered, &IWizardFactory::clearWizardFactories);
}
<commit_msg>Wizards: Block reloading of wizards while NewDialog is visible<commit_after>/****************************************************************************
**
** Copyright (C) 2015 The Qt Company Ltd.
** Contact: http://www.qt.io/licensing
**
** 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 The Qt Company.  For licensing terms and
** conditions see http://www.qt.io/terms-conditions.  For further information
** use the contact form at http://www.qt.io/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 or version 3 as published by the Free
** Software Foundation and appearing in the file LICENSE.LGPLv21 and
** LICENSE.LGPLv3 included in the packaging of this file.  Please review the
** following information to ensure the GNU Lesser General Public License
** requirements will be met: https://www.gnu.org/licenses/lgpl.html and
** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
**
** In addition, as a special exception, The Qt Company gives you certain additional
** rights.  These rights are described in The Qt Company LGPL Exception
** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
**
****************************************************************************/

#include "iwizardfactory.h"

#include "actionmanager/actionmanager.h"
#include "documentmanager.h"
#include "icore.h"
#include "featureprovider.h"

#include <extensionsystem/pluginspec.h>
#include <extensionsystem/pluginmanager.h>

#include <utils/qtcassert.h>

#include <QAction>

/*!
    \class Core::IWizardFactory
    \mainclass

    \brief The class IWizardFactory is the base class for all wizard factories
    (for example shown in \gui {File | New}).

    The wizard interface is a very thin abstraction for the \gui{New...} wizards.
    Basically it defines what to show to the user in the wizard selection dialogs,
    and a hook that is called if the user selects the wizard.

    Wizards can then perform any operations they like, including showing dialogs and
    creating files. Often it is not necessary to create your own wizard from scratch,
    instead use one of the predefined wizards and adapt it to your needs.

    To make your wizard known to the system, add your IWizardFactory instance to the
    plugin manager's object pool in your plugin's initialize function:
    \code
        bool MyPlugin::initialize(const QStringList &arguments, QString *errorString)
        {
            // ... do setup
            addAutoReleasedObject(new MyWizardFactory);
            // ... do more setup
        }
    \endcode
    \sa Core::BaseFileWizard
    \sa Core::StandardFileWizard
*/

/*!
    \enum Core::IWizardFactory::WizardKind
    Used to specify what kind of objects the wizard creates. This information is used
    to show e.g. only wizards that create projects when selecting a \gui{New Project}
    menu item.
    \value FileWizard
        The wizard creates one or more files.
    \value ClassWizard
        The wizard creates a new class (e.g. source+header files).
    \value ProjectWizard
        The wizard creates a new project.
*/

/*!
    \fn IWizardFactory::IWizardFactory(QObject *parent)
    \internal
*/

/*!
    \fn IWizardFactory::~IWizardFactory()
    \internal
*/

/*!
    \fn Kind IWizardFactory::kind() const
    Returns what kind of objects are created by the wizard.
    \sa Kind
*/

/*!
    \fn QIcon IWizardFactory::icon() const
    Returns an icon to show in the wizard selection dialog.
*/

/*!
    \fn QString IWizardFactory::description() const
    Returns a translated description to show when this wizard is selected
    in the dialog.
*/

/*!
    \fn QString IWizardFactory::displayName() const
    Returns the translated name of the wizard, how it should appear in the
    dialog.
*/

/*!
    \fn QString IWizardFactory::id() const
    Returns an arbitrary id that is used for sorting within the category.
*/

/*!
    \fn QString IWizardFactory::category() const
    Returns a category ID to add the wizard to.
*/

/*!
    \fn QString IWizardFactory::displayCategory() const
    Returns the translated string of the category, how it should appear
    in the dialog.
*/

/*!
    \fn void IWizardFactory::runWizard(const QString &path,
                                      QWidget *parent,
                                      const QString &platform,
                                      const QVariantMap &variables)

    This function is executed when the wizard has been selected by the user
    for execution. Any dialogs the wizard opens should use the given \a parent.
    The \a path argument is a suggestion for the location where files should be
    created. The wizard should fill this in its path selection elements as a
    default path.
*/

using namespace Core;

namespace {
static QList<IFeatureProvider *> s_providerList;
QList<IWizardFactory *> s_allFactories;
QList<IWizardFactory::FactoryCreator> s_factoryCreators;
bool s_areFactoriesLoaded = false;
bool s_isWizardRunning = false;
}

/* A utility to find all wizards supporting a view mode and matching a predicate */
QList<IWizardFactory*> findWizardFactories(const std::function<bool(IWizardFactory*)> &predicate)
{
    const QList<IWizardFactory *> allFactories = IWizardFactory::allWizardFactories();
    QList<IWizardFactory *> rc;
    auto cend = allFactories.constEnd();
    for (auto it = allFactories.constBegin(); it != cend; ++it) {
        if (predicate(*it))
            rc.push_back(*it);
    }
    return rc;
}

static Id actionId(const IWizardFactory *factory)
{
    return factory->id().withPrefix("Wizard.Impl.");
}

QList<IWizardFactory*> IWizardFactory::allWizardFactories()
{
    if (!s_areFactoriesLoaded) {
        QTC_ASSERT(s_allFactories.isEmpty(), return s_allFactories);

        s_areFactoriesLoaded = true;

        QHash<Id, IWizardFactory *> sanityCheck;
        foreach (const FactoryCreator &fc, s_factoryCreators) {
            QList<IWizardFactory *> tmp = fc();
            foreach (IWizardFactory *newFactory, tmp) {
                QTC_ASSERT(newFactory, continue);
                IWizardFactory *existingFactory = sanityCheck.value(newFactory->id());

                QTC_ASSERT(existingFactory != newFactory, continue);
                if (existingFactory) {
                    qWarning("%s", qPrintable(tr("Factory with id=\"%1\" already registered. Deleting.")
                                              .arg(existingFactory->id().toString())));
                    delete newFactory;
                    continue;
                }

                QTC_ASSERT(!newFactory->m_action, continue);
                newFactory->m_action = new QAction(newFactory->displayName(), newFactory);
                ActionManager::registerAction(newFactory->m_action, actionId(newFactory));

                connect(newFactory->m_action, &QAction::triggered, newFactory, [newFactory]() {
                    QString path = newFactory->runPath(QString());
                    newFactory->runWizard(path, ICore::dialogParent(), QString(), QVariantMap());
                });

                sanityCheck.insert(newFactory->id(), newFactory);
                s_allFactories << newFactory;
            }
        }
    }

    return s_allFactories;
}

// Utility to find all registered wizards of a certain kind
QList<IWizardFactory*> IWizardFactory::wizardFactoriesOfKind(WizardKind kind)
{
    return findWizardFactories([kind](IWizardFactory *f) { return f->kind() == kind; });
}

QString IWizardFactory::runPath(const QString &defaultPath)
{
    QString path = defaultPath;
    if (path.isEmpty()) {
        switch (kind()) {
        case IWizardFactory::ProjectWizard:
            // Project wizards: Check for projects directory or
            // use last visited directory of file dialog. Never start
            // at current.
            path = DocumentManager::useProjectsDirectory() ?
                       DocumentManager::projectsDirectory() :
                       DocumentManager::fileDialogLastVisitedDirectory();
            break;
        default:
            path = DocumentManager::fileDialogInitialDirectory();
            break;
        }
    }
    return path;
}

void IWizardFactory::runWizard(const QString &path, QWidget *parent, const QString &platform, const QVariantMap &variables)
{
    s_isWizardRunning = true;
    ICore::validateNewDialogIsRunning();

    runWizardImpl(path, parent, platform, variables);

    s_isWizardRunning = false;
    ICore::validateNewDialogIsRunning();
}

bool IWizardFactory::isAvailable(const QString &platformName) const
{
    if (platformName.isEmpty())
        return true;

    return availableFeatures(platformName).contains(requiredFeatures());
}

QStringList IWizardFactory::supportedPlatforms() const
{
    QStringList stringList;

    foreach (const QString &platform, allAvailablePlatforms()) {
        if (isAvailable(platform))
            stringList.append(platform);
    }

    return stringList;
}

void IWizardFactory::registerFactoryCreator(const IWizardFactory::FactoryCreator &creator)
{
    s_factoryCreators << creator;
}

QStringList IWizardFactory::allAvailablePlatforms()
{
    QStringList platforms;

    foreach (const IFeatureProvider *featureManager, s_providerList)
        platforms.append(featureManager->availablePlatforms());

    return platforms;
}

QString IWizardFactory::displayNameForPlatform(const QString &string)
{
    foreach (const IFeatureProvider *featureManager, s_providerList) {
        QString displayName = featureManager->displayNameForPlatform(string);
        if (!displayName.isEmpty())
            return displayName;
    }
    return QString();
}

void IWizardFactory::registerFeatureProvider(IFeatureProvider *provider)
{
    QTC_ASSERT(!s_providerList.contains(provider), return);
    s_providerList.append(provider);
}

bool IWizardFactory::isWizardRunning()
{
    return s_isWizardRunning;
}

void IWizardFactory::destroyFeatureProvider()
{
    qDeleteAll(s_providerList);
    s_providerList.clear();
}

void IWizardFactory::clearWizardFactories()
{
    QTC_ASSERT(!ICore::isNewItemDialogRunning(), return);

    foreach (IWizardFactory *factory, s_allFactories)
        ActionManager::unregisterAction(factory->m_action, actionId(factory));

    qDeleteAll(s_allFactories);
    s_allFactories.clear();

    s_areFactoriesLoaded = false;
}

FeatureSet IWizardFactory::pluginFeatures() const
{
    static FeatureSet plugins;
    if (plugins.isEmpty()) {
        QStringList list;
        // Implicitly create a feature for each plugin loaded:
        foreach (ExtensionSystem::PluginSpec *s, ExtensionSystem::PluginManager::plugins()) {
            if (s->state() == ExtensionSystem::PluginSpec::Running)
                list.append(s->name());
        }
        plugins = FeatureSet::fromStringList(list);
    }
    return plugins;
}

FeatureSet IWizardFactory::availableFeatures(const QString &platformName) const
{
    FeatureSet availableFeatures;

    foreach (const IFeatureProvider *featureManager, s_providerList)
        availableFeatures |= featureManager->availableFeatures(platformName);

    return availableFeatures;
}

void IWizardFactory::initialize()
{
    connect(ICore::instance(), &ICore::coreAboutToClose, &IWizardFactory::clearWizardFactories);

    auto resetAction = new QAction(tr("Reload All Wizards"), ActionManager::instance());
    ActionManager::registerAction(resetAction, "Wizard.Factory.Reset");

    connect(resetAction, &QAction::triggered, &IWizardFactory::clearWizardFactories);
    connect(ICore::instance(), &ICore::newItemDialogRunningChanged, resetAction,
            [resetAction]() { resetAction->setEnabled(!ICore::isNewItemDialogRunning()); });
}
<|endoftext|>


<commit_before>#include <iostream>

#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <fcntl.h>
#include <string.h>
#include <string>
#include <math.h>
#include <sys/stat.h>
#include <sys/types.h>

#include <config.h>
#include <libvisual/libvisual.h>
#include <libprojectM/BeatDetect.hpp>
#include <libprojectM/PCM.hpp>
#include <libprojectM/projectM.hpp>
#include <libprojectM/KeyHandler.hpp>
#include "lvtoprojectM.h"
#include "ConfigFile.h"

#define CONFIG_FILE "/share/projectM/config.inp"

std::string read_config();

int texsize=512;
int gx=32,gy=24;
int wvw=512,wvh=512;
int fvw=1024,fvh=768;
int fps=30, fullscreen=0;

/* Private context sensitive data goes here, */
typedef struct {
	projectM *PM;
} ProjectmPrivate;

extern "C" int lv_projectm_init (VisPluginData *plugin);
extern "C" int lv_projectm_cleanup (VisPluginData *plugin);
extern "C" int lv_projectm_requisition (VisPluginData *plugin, int *width, int *height);
extern "C" int lv_projectm_dimension (VisPluginData *plugin, VisVideo *video, int width, int height);
extern "C" int lv_projectm_events (VisPluginData *plugin, VisEventQueue *events);
extern "C" VisPalette *lv_projectm_palette (VisPluginData *plugin);
extern "C" int lv_projectm_render (VisPluginData *plugin, VisVideo *video, VisAudio *audio);

VISUAL_PLUGIN_API_VERSION_VALIDATOR

/* Main plugin stuff */
/* The get_plugin_info function provides the libvisual plugin registry, and plugin loader
 * with the very basic plugin information */
extern "C" const VisPluginInfo *get_plugin_info (int *count)
{
  /* Initialize the plugin specific data structure
   * with pointers to the functions that represent
   * the plugin interface it's implementation, more info:
   * http://libvisual.sourceforge.net/newdocs/docs/html/struct__VisActorPlugin.html */
  static VisActorPlugin actor[1];
  static VisPluginInfo info[1];

  actor[0].requisition = lv_projectm_requisition;
  actor[0].palette = lv_projectm_palette;
  actor[0].render = lv_projectm_render;
    actor[0].vidoptions.depth = VISUAL_VIDEO_DEPTH_GL; /* We want GL clearly */

    info[0].type = VISUAL_PLUGIN_TYPE_ACTOR;

    info[0].plugname = "projectM";
    info[0].name = "libvisual projectM";
    info[0].author = "Peter Sperl";
    info[0].version = "1.00";
    info[0].about = "projectM";
    info[0].help =  "";

    info[0].init = lv_projectm_init;
    info[0].cleanup = lv_projectm_cleanup;
    info[0].events = lv_projectm_events;

    info[0].plugin = VISUAL_OBJECT (&actor[0]);
    *count = sizeof (info) / sizeof (*info);

	VISUAL_VIDEO_ATTRIBUTE_OPTIONS_GL_ENTRY(actor[0].vidoptions, VISUAL_GL_ATTRIBUTE_ALPHA_SIZE, 8);
	VISUAL_VIDEO_ATTRIBUTE_OPTIONS_GL_ENTRY(actor[0].vidoptions, VISUAL_GL_ATTRIBUTE_DEPTH_SIZE, 16);
	VISUAL_VIDEO_ATTRIBUTE_OPTIONS_GL_ENTRY(actor[0].vidoptions, VISUAL_GL_ATTRIBUTE_DOUBLEBUFFER, 1);

	VISUAL_VIDEO_ATTRIBUTE_OPTIONS_GL_ENTRY(actor[0].vidoptions, VISUAL_GL_ATTRIBUTE_RED_SIZE, 8);
	VISUAL_VIDEO_ATTRIBUTE_OPTIONS_GL_ENTRY(actor[0].vidoptions, VISUAL_GL_ATTRIBUTE_GREEN_SIZE, 8);
	VISUAL_VIDEO_ATTRIBUTE_OPTIONS_GL_ENTRY(actor[0].vidoptions, VISUAL_GL_ATTRIBUTE_BLUE_SIZE, 8);
    return info;
}

/* This function is called before we really start rendering, it's the init function */
extern "C" int lv_projectm_init (VisPluginData *plugin)
{
        char projectM_data[1024];
	ProjectmPrivate *priv;
	 std::string config_file;
 config_file = read_config();

 ConfigFile config(config_file);
        wvw = config.read<int>( "Window Width", 512 );
  wvh = config.read<int>( "Window Height", 512 );
 fullscreen = 0;
	/* Allocate the projectm private data structure, and register it as a private */

	priv = new ProjectmPrivate;
	visual_mem_set (priv, 0, sizeof (ProjectmPrivate));

	//priv = visual_mem_new0 (ProjectmPrivate, 1);
	visual_object_set_private (VISUAL_OBJECT (plugin), priv);

	//FIXME
	priv->PM = new projectM(config_file);
	//globalPM = (projectM *)wipemalloc( sizeof( projectM ) );

	return 0;
}

extern "C" int lv_projectm_cleanup (VisPluginData *plugin)
{
	ProjectmPrivate *priv = (ProjectmPrivate*)visual_object_get_private (VISUAL_OBJECT (plugin));

	/* Cleanup, and thus also free our private */
	visual_mem_free (priv->PM);
	visual_mem_free (priv);
	return 0;
}

/* This is used to ask a plugin if it can handle a certain size, and if not, to
 * set the size it wants by putting a value in width, height that represents the
 * required size */
extern "C" int lv_projectm_requisition (VisPluginData *plugin, int *width, int *height)
{
	int reqw, reqh;

	/* Size negotiate with the window */
	reqw = *width;
	reqh = *height;

	if (reqw < 64)
		reqw = 64;

	if (reqh < 64)
		reqh = 64;

	*width = reqw;
	*height = reqh;

	return 0;
}

extern "C" int lv_projectm_dimension (VisPluginData *plugin, VisVideo *video, int width, int height)
{
	ProjectmPrivate *priv = (ProjectmPrivate*)visual_object_get_private (VISUAL_OBJECT (plugin));

	visual_video_set_dimension (video, width, height);

	priv->PM->projectM_resetGL( width, height );

	return 0;
}

/* This is the main event loop, where all kind of events can be handled, more information
 * regarding these can be found at:
 * http://libvisual.sourceforge.net/newdocs/docs/html/union__VisEvent.html
 */
extern "C" int lv_projectm_events (VisPluginData *plugin, VisEventQueue *events)
{
	ProjectmPrivate *priv = (ProjectmPrivate*)visual_object_get_private (VISUAL_OBJECT (plugin));
	VisEvent ev;
	VisParamEntry *param;

	projectMEvent evt;
        projectMKeycode key;
        projectMModifier mod;

	while (visual_event_queue_poll (events, &ev))
	  {
	    switch (ev.type)
	      {
	      case VISUAL_EVENT_KEYUP:

		evt = lv2pmEvent( ev.type );
		key = lv2pmKeycode( ev.event.keyboard.keysym.sym );
		mod = lv2pmModifier( ev.event.keyboard.keysym.mod );
		priv->PM->key_handler(PROJECTM_KEYDOWN, key,mod);

		break;
	      case VISUAL_EVENT_RESIZE:
		lv_projectm_dimension (plugin, ev.event.resize.video,
				       ev.event.resize.width, ev.event.resize.height);
		break;

	      default: /* to avoid warnings */
		break;
	      }
	}

	return 0;
}

/* Using this function we can update the palette when we're in 8bits mode, which
 * we aren't with projectm, so just ignore :) */
extern "C" VisPalette *lv_projectm_palette (VisPluginData *plugin)
{
	return NULL;
}

/* This is where the real rendering happens! This function is what we call, many times
 * a second to get our graphical frames. */
extern "C" int lv_projectm_render (VisPluginData *plugin, VisVideo *video, VisAudio *audio)
{
	ProjectmPrivate *priv = (ProjectmPrivate*)visual_object_get_private (VISUAL_OBJECT (plugin));
	VisBuffer pcmb;
	float pcm[2][512];
	//short pcms[2][512];
	int i;

	visual_buffer_set_data_pair (&pcmb, pcm[0], sizeof (pcm[0]));
	visual_audio_get_sample (audio, &pcmb, VISUAL_AUDIO_CHANNEL_LEFT);

	visual_buffer_set_data_pair (&pcmb, pcm[1], sizeof (pcm[1]));
	visual_audio_get_sample (audio, &pcmb, VISUAL_AUDIO_CHANNEL_RIGHT);

	/*
	for (i = 0; i < 512; i++) {
		pcms[0][i] = pcm[0][i] * 32768.0;
		pcms[1][i] = pcm[1][i] * 32768.0;
	}

	addPCM16Data(pcms,512);
	*/

	priv->PM->beatDetect->pcm->addPCMfloat(*pcm,512);

	priv->PM->renderFrame();

	return 0;
}

std::string read_config()
{

   int n;

   char num[512];
   FILE *in;
   FILE *out;

   char* home;
   char projectM_home[1024];
   char projectM_config[1024];

   strcpy(projectM_config, PROJECTM_DATADIR);
   strcpy(projectM_config+strlen(PROJECTM_DATADIR), CONFIG_FILE);
   projectM_config[strlen(PROJECTM_DATADIR)+strlen(CONFIG_FILE)]='\0';
   printf("dir:%s \n",projectM_config);
   home=getenv("HOME");
   strcpy(projectM_home, home);
   strcpy(projectM_home+strlen(home), "/.projectM/config.inp");
   projectM_home[strlen(home)+strlen("/.projectM/config.inp")]='\0';

 if ((in = fopen(projectM_home, "r")) != 0)
   {
     printf("reading ~/.projectM/config.inp \n");
     fclose(in);
     return std::string(projectM_home);
   }
 else
   {
     printf("trying to create ~/.projectM/config.inp \n");

     strcpy(projectM_home, home);
     strcpy(projectM_home+strlen(home), "/.projectM");
     projectM_home[strlen(home)+strlen("/.projectM")]='\0';
     mkdir(projectM_home,0755);

     strcpy(projectM_home, home);
     strcpy(projectM_home+strlen(home), "/.projectM/config.inp");
     projectM_home[strlen(home)+strlen("/.projectM/config.inp")]='\0';

     if((out = fopen(projectM_home,"w"))!=0)
       {

	 if ((in = fopen(projectM_config, "r")) != 0)
	   {

	     while(fgets(num,80,in)!=NULL)
	       {
		 fputs(num,out);
	       }
	     fclose(in);
	     fclose(out);

	     if ((in = fopen(projectM_home, "r")) != 0)
	       {
		 printf("created ~/.projectM/config.inp successfully\n");
		 fclose(in);
		 return std::string(projectM_home);
	       }
	     else{printf("This shouldn't happen, using implementation defualts\n");abort();}
	   }
	 else{printf("Cannot find projectM default config, using implementation defaults\n");abort();}
       }
     else
       {
	 printf("Cannot create ~/.projectM/config.inp, using default config file\n");
	 if ((in = fopen(projectM_config, "r")) != 0)
	   { printf("Successfully opened default config file\n");
	     fclose(in);
	     return std::string(projectM_config);}
	 else{ printf("Using implementation defaults, your system is really messed up, I'm suprised we even got this far\n");  abort();}

       }

   }

 /*
     fgets(num, 512, in);  fgets(num, 512, in);  fgets(num, 512, in);
     if(fgets(num, 512, in) != NULL) sscanf (num, "%d", &texsize);

     fgets(num, 512, in);
     if(fgets(num, 512, in) != NULL) sscanf (num, "%d", &gx);

     fgets(num, 512, in);
     if(fgets(num, 512, in) != NULL) sscanf (num, "%d", &gy);

     fgets(num, 512, in);
     if(fgets(num, 512, in) != NULL) sscanf (num, "%d", &wvw);

     fgets(num, 512, in);
     if(fgets(num, 512, in) != NULL) sscanf (num, "%d", &wvh);

     fgets(num, 512, in);
     if(fgets(num, 512, in) != NULL) sscanf (num, "%d", &fps);

     fgets(num, 512, in);
     if(fgets(num, 512, in) != NULL) sscanf (num, "%d", &fullscreen);
     fgets(num, 512, in);

     if(fgets(num, 512, in) != NULL)  strcpy(preset_dir, num);
     preset_dir[strlen(preset_dir)-1]='\0';
 */
     /*
     fgets(num, 80, in);
     fgets(num, 80, in);

     n=0;
     while (num[n]!=' ' && num[n]!='\n' && n < 80 && num[n]!=EOF)
       {
	 	 disp[n]=num[n];
		 n++;
       }
     disp[n]=0;

     // sprintf(disp,"%s",num );
      setenv("DISPLAY",disp,1);
      printf("%s %d\n", disp,strlen(disp));
      setenv("LD_PRELOAD", "/usr/lib/tls/libGL.so.1.0.4496", 1);
     */
 // fclose(in);

 abort();
}

<commit_msg>Libvisual config file crash fix from Frank<commit_after>#include <iostream>

#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <fcntl.h>
#include <string.h>
#include <string>
#include <math.h>
#include <sys/stat.h>
#include <sys/types.h>

#include <config.h>
#include <libvisual/libvisual.h>
#include <libprojectM/BeatDetect.hpp>
#include <libprojectM/PCM.hpp>
#include <libprojectM/projectM.hpp>
#include <libprojectM/KeyHandler.hpp>
#include "lvtoprojectM.h"
#include "ConfigFile.h"

#define CONFIG_FILE "/config.inp"

std::string read_config();

int texsize=512;
int gx=32,gy=24;
int wvw=512,wvh=512;
int fvw=1024,fvh=768;
int fps=30, fullscreen=0;

/* Private context sensitive data goes here, */
typedef struct {
	projectM *PM;
} ProjectmPrivate;

extern "C" int lv_projectm_init (VisPluginData *plugin);
extern "C" int lv_projectm_cleanup (VisPluginData *plugin);
extern "C" int lv_projectm_requisition (VisPluginData *plugin, int *width, int *height);
extern "C" int lv_projectm_dimension (VisPluginData *plugin, VisVideo *video, int width, int height);
extern "C" int lv_projectm_events (VisPluginData *plugin, VisEventQueue *events);
extern "C" VisPalette *lv_projectm_palette (VisPluginData *plugin);
extern "C" int lv_projectm_render (VisPluginData *plugin, VisVideo *video, VisAudio *audio);

VISUAL_PLUGIN_API_VERSION_VALIDATOR

/* Main plugin stuff */
/* The get_plugin_info function provides the libvisual plugin registry, and plugin loader
 * with the very basic plugin information */
extern "C" const VisPluginInfo *get_plugin_info (int *count)
{
  /* Initialize the plugin specific data structure
   * with pointers to the functions that represent
   * the plugin interface it's implementation, more info:
   * http://libvisual.sourceforge.net/newdocs/docs/html/struct__VisActorPlugin.html */
  static VisActorPlugin actor[1];
  static VisPluginInfo info[1];

  actor[0].requisition = lv_projectm_requisition;
  actor[0].palette = lv_projectm_palette;
  actor[0].render = lv_projectm_render;
    actor[0].vidoptions.depth = VISUAL_VIDEO_DEPTH_GL; /* We want GL clearly */

    info[0].type = VISUAL_PLUGIN_TYPE_ACTOR;

    info[0].plugname = "projectM";
    info[0].name = "libvisual projectM";
    info[0].author = "Peter Sperl";
    info[0].version = "1.00";
    info[0].about = "projectM";
    info[0].help =  "";

    info[0].init = lv_projectm_init;
    info[0].cleanup = lv_projectm_cleanup;
    info[0].events = lv_projectm_events;

    info[0].plugin = VISUAL_OBJECT (&actor[0]);
    *count = sizeof (info) / sizeof (*info);

	VISUAL_VIDEO_ATTRIBUTE_OPTIONS_GL_ENTRY(actor[0].vidoptions, VISUAL_GL_ATTRIBUTE_ALPHA_SIZE, 8);
	VISUAL_VIDEO_ATTRIBUTE_OPTIONS_GL_ENTRY(actor[0].vidoptions, VISUAL_GL_ATTRIBUTE_DEPTH_SIZE, 16);
	VISUAL_VIDEO_ATTRIBUTE_OPTIONS_GL_ENTRY(actor[0].vidoptions, VISUAL_GL_ATTRIBUTE_DOUBLEBUFFER, 1);

	VISUAL_VIDEO_ATTRIBUTE_OPTIONS_GL_ENTRY(actor[0].vidoptions, VISUAL_GL_ATTRIBUTE_RED_SIZE, 8);
	VISUAL_VIDEO_ATTRIBUTE_OPTIONS_GL_ENTRY(actor[0].vidoptions, VISUAL_GL_ATTRIBUTE_GREEN_SIZE, 8);
	VISUAL_VIDEO_ATTRIBUTE_OPTIONS_GL_ENTRY(actor[0].vidoptions, VISUAL_GL_ATTRIBUTE_BLUE_SIZE, 8);
    return info;
}

/* This function is called before we really start rendering, it's the init function */
extern "C" int lv_projectm_init (VisPluginData *plugin)
{
        char projectM_data[1024];
	ProjectmPrivate *priv;
	 std::string config_file;
 config_file = read_config();

 ConfigFile config(config_file);
        wvw = config.read<int>( "Window Width", 512 );
  wvh = config.read<int>( "Window Height", 512 );
 fullscreen = 0;
	/* Allocate the projectm private data structure, and register it as a private */

	priv = new ProjectmPrivate;
	visual_mem_set (priv, 0, sizeof (ProjectmPrivate));

	//priv = visual_mem_new0 (ProjectmPrivate, 1);
	visual_object_set_private (VISUAL_OBJECT (plugin), priv);

	//FIXME
	priv->PM = new projectM(config_file);
	//globalPM = (projectM *)wipemalloc( sizeof( projectM ) );

	return 0;
}

extern "C" int lv_projectm_cleanup (VisPluginData *plugin)
{
	ProjectmPrivate *priv = (ProjectmPrivate*)visual_object_get_private (VISUAL_OBJECT (plugin));

	/* Cleanup, and thus also free our private */
	visual_mem_free (priv->PM);
	visual_mem_free (priv);
	return 0;
}

/* This is used to ask a plugin if it can handle a certain size, and if not, to
 * set the size it wants by putting a value in width, height that represents the
 * required size */
extern "C" int lv_projectm_requisition (VisPluginData *plugin, int *width, int *height)
{
	int reqw, reqh;

	/* Size negotiate with the window */
	reqw = *width;
	reqh = *height;

	if (reqw < 64)
		reqw = 64;

	if (reqh < 64)
		reqh = 64;

	*width = reqw;
	*height = reqh;

	return 0;
}

extern "C" int lv_projectm_dimension (VisPluginData *plugin, VisVideo *video, int width, int height)
{
	ProjectmPrivate *priv = (ProjectmPrivate*)visual_object_get_private (VISUAL_OBJECT (plugin));

	visual_video_set_dimension (video, width, height);

	priv->PM->projectM_resetGL( width, height );

	return 0;
}

/* This is the main event loop, where all kind of events can be handled, more information
 * regarding these can be found at:
 * http://libvisual.sourceforge.net/newdocs/docs/html/union__VisEvent.html
 */
extern "C" int lv_projectm_events (VisPluginData *plugin, VisEventQueue *events)
{
	ProjectmPrivate *priv = (ProjectmPrivate*)visual_object_get_private (VISUAL_OBJECT (plugin));
	VisEvent ev;
	VisParamEntry *param;

	projectMEvent evt;
        projectMKeycode key;
        projectMModifier mod;

	while (visual_event_queue_poll (events, &ev))
	  {
	    switch (ev.type)
	      {
	      case VISUAL_EVENT_KEYUP:

		evt = lv2pmEvent( ev.type );
		key = lv2pmKeycode( ev.event.keyboard.keysym.sym );
		mod = lv2pmModifier( ev.event.keyboard.keysym.mod );
		priv->PM->key_handler(PROJECTM_KEYDOWN, key,mod);

		break;
	      case VISUAL_EVENT_RESIZE:
		lv_projectm_dimension (plugin, ev.event.resize.video,
				       ev.event.resize.width, ev.event.resize.height);
		break;

	      default: /* to avoid warnings */
		break;
	      }
	}

	return 0;
}

/* Using this function we can update the palette when we're in 8bits mode, which
 * we aren't with projectm, so just ignore :) */
extern "C" VisPalette *lv_projectm_palette (VisPluginData *plugin)
{
	return NULL;
}

/* This is where the real rendering happens! This function is what we call, many times
 * a second to get our graphical frames. */
extern "C" int lv_projectm_render (VisPluginData *plugin, VisVideo *video, VisAudio *audio)
{
	ProjectmPrivate *priv = (ProjectmPrivate*)visual_object_get_private (VISUAL_OBJECT (plugin));
	VisBuffer pcmb;
	float pcm[2][512];
	//short pcms[2][512];
	int i;

	visual_buffer_set_data_pair (&pcmb, pcm[0], sizeof (pcm[0]));
	visual_audio_get_sample (audio, &pcmb, VISUAL_AUDIO_CHANNEL_LEFT);

	visual_buffer_set_data_pair (&pcmb, pcm[1], sizeof (pcm[1]));
	visual_audio_get_sample (audio, &pcmb, VISUAL_AUDIO_CHANNEL_RIGHT);

	/*
	for (i = 0; i < 512; i++) {
		pcms[0][i] = pcm[0][i] * 32768.0;
		pcms[1][i] = pcm[1][i] * 32768.0;
	}

	addPCM16Data(pcms,512);
	*/

	priv->PM->beatDetect->pcm->addPCMfloat(*pcm,512);

	priv->PM->renderFrame();

	return 0;
}

std::string read_config()
{

   int n;

   char num[512];
   FILE *in;
   FILE *out;

   char* home;
   char projectM_home[1024];
   char projectM_config[1024];

   strcpy(projectM_config, PROJECTM_DATADIR);
   strcpy(projectM_config+strlen(PROJECTM_DATADIR), CONFIG_FILE);
   projectM_config[strlen(PROJECTM_DATADIR)+strlen(CONFIG_FILE)]='\0';
   printf("dir:%s \n",projectM_config);
   home=getenv("HOME");
   strcpy(projectM_home, home);
   strcpy(projectM_home+strlen(home), "/.projectM/config.inp");
   projectM_home[strlen(home)+strlen("/.projectM/config.inp")]='\0';

 if ((in = fopen(projectM_home, "r")) != 0)
   {
     printf("reading ~/.projectM/config.inp \n");
     fclose(in);
     return std::string(projectM_home);
   }
 else
   {
     printf("trying to create ~/.projectM/config.inp \n");

     strcpy(projectM_home, home);
     strcpy(projectM_home+strlen(home), "/.projectM");
     projectM_home[strlen(home)+strlen("/.projectM")]='\0';
     mkdir(projectM_home,0755);

     strcpy(projectM_home, home);
     strcpy(projectM_home+strlen(home), "/.projectM/config.inp");
     projectM_home[strlen(home)+strlen("/.projectM/config.inp")]='\0';

     if((out = fopen(projectM_home,"w"))!=0)
       {

	 if ((in = fopen(projectM_config, "r")) != 0)
	   {

	     while(fgets(num,80,in)!=NULL)
	       {
		 fputs(num,out);
	       }
	     fclose(in);
	     fclose(out);

	     if ((in = fopen(projectM_home, "r")) != 0)
	       {
		 printf("created ~/.projectM/config.inp successfully\n");
		 fclose(in);
		 return std::string(projectM_home);
	       }
	     else{printf("This shouldn't happen, using implementation defualts\n");abort();}
	   }
	 else{printf("Cannot find projectM default config, using implementation defaults\n");abort();}
       }
     else
       {
	 printf("Cannot create ~/.projectM/config.inp, using default config file\n");
	 if ((in = fopen(projectM_config, "r")) != 0)
	   { printf("Successfully opened default config file\n");
	     fclose(in);
	     return std::string(projectM_config);}
	 else{ printf("Using implementation defaults, your system is really messed up, I'm suprised we even got this far\n");  abort();}

       }

   }

 /*
     fgets(num, 512, in);  fgets(num, 512, in);  fgets(num, 512, in);
     if(fgets(num, 512, in) != NULL) sscanf (num, "%d", &texsize);

     fgets(num, 512, in);
     if(fgets(num, 512, in) != NULL) sscanf (num, "%d", &gx);

     fgets(num, 512, in);
     if(fgets(num, 512, in) != NULL) sscanf (num, "%d", &gy);

     fgets(num, 512, in);
     if(fgets(num, 512, in) != NULL) sscanf (num, "%d", &wvw);

     fgets(num, 512, in);
     if(fgets(num, 512, in) != NULL) sscanf (num, "%d", &wvh);

     fgets(num, 512, in);
     if(fgets(num, 512, in) != NULL) sscanf (num, "%d", &fps);

     fgets(num, 512, in);
     if(fgets(num, 512, in) != NULL) sscanf (num, "%d", &fullscreen);
     fgets(num, 512, in);

     if(fgets(num, 512, in) != NULL)  strcpy(preset_dir, num);
     preset_dir[strlen(preset_dir)-1]='\0';
 */
     /*
     fgets(num, 80, in);
     fgets(num, 80, in);

     n=0;
     while (num[n]!=' ' && num[n]!='\n' && n < 80 && num[n]!=EOF)
       {
	 	 disp[n]=num[n];
		 n++;
       }
     disp[n]=0;

     // sprintf(disp,"%s",num );
      setenv("DISPLAY",disp,1);
      printf("%s %d\n", disp,strlen(disp));
      setenv("LD_PRELOAD", "/usr/lib/tls/libGL.so.1.0.4496", 1);
     */
 // fclose(in);

 abort();
}

<|endoftext|>


<commit_before>/*
 * This program is free software; you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation; either version 3 of the License, or
 * (at your option) any later version.
 *
 * Written (W) 2013 Roman Votyakov
 * Written (W) 2013 Heiko Strathmann
 * Copyright (C) 2012 Jacob Walker
 * Copyright (C) 2013 Roman Votyakov
 */

#include <shogun/lib/config.h>

#ifdef HAVE_EIGEN3

#include <shogun/machine/gp/InferenceMethod.h>
#include <shogun/distributions/classical/GaussianDistribution.h>
#include <shogun/mathematics/Statistics.h>
#include <shogun/mathematics/Math.h>
#include <shogun/lib/Lock.h>

using namespace shogun;

#ifndef DOXYGEN_SHOULD_SKIP_THIS
struct GRADIENT_THREAD_PARAM
{
	CInferenceMethod* inf;
	CMap<TParameter*, SGVector<float64_t> >* grad;
	CSGObject* obj;
	TParameter* param;
	CLock* lock;
};
#endif /* DOXYGEN_SHOULD_SKIP_THIS */

CInferenceMethod::CInferenceMethod()
{
	init();
}

float64_t CInferenceMethod::get_scale() const
{
	return CMath::exp(m_log_scale);
}

void CInferenceMethod::set_scale(float64_t scale)
{
	REQUIRE(scale>0, "Scale (%f) must be positive", scale);
	m_log_scale=CMath::log(scale);
}

SGMatrix<float64_t> CInferenceMethod::get_multiclass_E()
{
	if (parameter_hash_changed())
		update();

	return SGMatrix<float64_t>(m_E);
}

CInferenceMethod::CInferenceMethod(CKernel* kernel, CFeatures* features,
	CMeanFunction* mean, CLabels* labels, CLikelihoodModel* model)
{
	init();

	set_kernel(kernel);
	set_features(features);
	set_labels(labels);
	set_model(model);
	set_mean(mean);
}

CInferenceMethod::~CInferenceMethod()
{
	SG_UNREF(m_kernel);
	SG_UNREF(m_features);
	SG_UNREF(m_labels);
	SG_UNREF(m_model);
	SG_UNREF(m_mean);
}

void CInferenceMethod::init()
{
	SG_ADD((CSGObject**)&m_kernel, "kernel", "Kernel", MS_AVAILABLE);
	SG_ADD(&m_log_scale, "log_scale", "Kernel log scale", MS_AVAILABLE, GRADIENT_AVAILABLE);
	SG_ADD((CSGObject**)&m_model, "likelihood_model", "Likelihood model",
		MS_AVAILABLE);
	SG_ADD((CSGObject**)&m_mean, "mean_function", "Mean function", MS_AVAILABLE);
	SG_ADD((CSGObject**)&m_labels, "labels", "Labels", MS_NOT_AVAILABLE);
	SG_ADD((CSGObject**)&m_features, "features", "Features", MS_NOT_AVAILABLE);

	m_kernel=NULL;
	m_model=NULL;
	m_labels=NULL;
	m_features=NULL;
	m_mean=NULL;
	m_log_scale=0.0;

	SG_ADD(&m_alpha, "alpha", "alpha vector used in process mean calculation", MS_NOT_AVAILABLE);
	SG_ADD(&m_L, "L", "upper triangular factor of Cholesky decomposition", MS_NOT_AVAILABLE);
	SG_ADD(&m_E, "E", "the matrix used for multi classification", MS_NOT_AVAILABLE);
}

float64_t CInferenceMethod::get_marginal_likelihood_estimate(
		int32_t num_importance_samples, float64_t ridge_size)
{
	/* sample from Gaussian approximation to q(f|y) */
	SGMatrix<float64_t> cov=get_posterior_covariance();

	/* add ridge */
	for (index_t i=0; i<cov.num_rows; ++i)
		cov(i,i)+=ridge_size;

	SGVector<float64_t> mean=get_posterior_mean();

	CGaussianDistribution* post_approx=new CGaussianDistribution(mean, cov);
	SGMatrix<float64_t> samples=post_approx->sample(num_importance_samples);

	/* evaluate q(f^i|y), p(f^i|\theta), p(y|f^i), i.e.,
	 * log pdf of approximation, prior and likelihood */

	/* log pdf q(f^i|y) */
	SGVector<float64_t> log_pdf_post_approx=post_approx->log_pdf_multiple(samples);

	/* dont need gaussian anymore, free memory */
	SG_UNREF(post_approx);
	post_approx=NULL;

	/* log pdf p(f^i|\theta) and free memory afterwise. Scale kernel before */
	SGMatrix<float64_t> scaled_kernel(m_ktrtr.num_rows, m_ktrtr.num_cols);
	memcpy(scaled_kernel.matrix, m_ktrtr.matrix,
			sizeof(float64_t)*m_ktrtr.num_rows*m_ktrtr.num_cols);
	for (index_t i=0; i<m_ktrtr.num_rows*m_ktrtr.num_cols; ++i)
		scaled_kernel.matrix[i]*=CMath::exp(m_log_scale*2.0);

	/* add ridge */
	for (index_t i=0; i<cov.num_rows; ++i)
		scaled_kernel(i,i)+=ridge_size;

	CGaussianDistribution* prior=new CGaussianDistribution(
			m_mean->get_mean_vector(m_features), scaled_kernel);
	SGVector<float64_t> log_pdf_prior=prior->log_pdf_multiple(samples);
	SG_UNREF(prior);
	prior=NULL;

	/* p(y|f^i) */
	SGVector<float64_t> log_likelihood=m_model->get_log_probability_fmatrix(
			m_labels, samples);

	/* combine probabilities */
	ASSERT(log_likelihood.vlen==num_importance_samples);
	ASSERT(log_likelihood.vlen==log_pdf_prior.vlen);
	ASSERT(log_likelihood.vlen==log_pdf_post_approx.vlen);
	SGVector<float64_t> sum(log_likelihood);
	for (index_t i=0; i<log_likelihood.vlen; ++i)
		sum[i]=log_likelihood[i]+log_pdf_prior[i]-log_pdf_post_approx[i];

	/* use log-sum-exp (in particular, log-mean-exp) trick to combine values */
	return CMath::log_mean_exp(sum);
}

CMap<TParameter*, SGVector<float64_t> >* CInferenceMethod::
get_negative_log_marginal_likelihood_derivatives(CMap<TParameter*, CSGObject*>* params)
{
	REQUIRE(params->get_num_elements(), "Number of parameters should be greater "
			"than zero\n")

	if (parameter_hash_changed())
		update();

	// get number of derivatives
	const index_t num_deriv=params->get_num_elements();

	// create map of derivatives
	CMap<TParameter*, SGVector<float64_t> >* result=
		new CMap<TParameter*, SGVector<float64_t> >(num_deriv, num_deriv);

	SG_REF(result);

	// create lock object
	CLock lock;

#ifdef HAVE_PTHREAD
	if (num_deriv<2)
	{
#endif /* HAVE_PTHREAD */
		for (index_t i=0; i<num_deriv; i++)
		{
			CMapNode<TParameter*, CSGObject*>* node=params->get_node_ptr(i);

			GRADIENT_THREAD_PARAM thread_params;

			thread_params.inf=this;
			thread_params.obj=node->data;
			thread_params.param=node->key;
			thread_params.grad=result;
			thread_params.lock=&lock;

			get_derivative_helper((void*) &thread_params);
		}
#ifdef HAVE_PTHREAD
	}
	else
	{
		pthread_t* threads=SG_MALLOC(pthread_t, num_deriv);
		GRADIENT_THREAD_PARAM* thread_params=SG_MALLOC(GRADIENT_THREAD_PARAM,
				num_deriv);

		for (index_t t=0; t<num_deriv; t++)
		{
			CMapNode<TParameter*, CSGObject*>* node=params->get_node_ptr(t);

			thread_params[t].inf=this;
			thread_params[t].obj=node->data;
			thread_params[t].param=node->key;
			thread_params[t].grad=result;
			thread_params[t].lock=&lock;

			pthread_create(&threads[t], NULL, CInferenceMethod::get_derivative_helper,
					(void*)&thread_params[t]);
		}

		for (index_t t=0; t<num_deriv; t++)
			pthread_join(threads[t], NULL);

		SG_FREE(thread_params);
		SG_FREE(threads);
	}
#endif /* HAVE_PTHREAD */

	return result;
}

void* CInferenceMethod::get_derivative_helper(void *p)
{
	GRADIENT_THREAD_PARAM* thread_param=(GRADIENT_THREAD_PARAM*)p;

	CInferenceMethod* inf=thread_param->inf;
	CSGObject* obj=thread_param->obj;
	CMap<TParameter*, SGVector<float64_t> >* grad=thread_param->grad;
	TParameter* param=thread_param->param;
	CLock* lock=thread_param->lock;

	REQUIRE(param, "Parameter should not be NULL\n");
	REQUIRE(obj, "Object of the parameter should not be NULL\n");

	SGVector<float64_t> gradient;

	if (obj==inf)
	{
		// try to find dervative wrt InferenceMethod.parameter
		gradient=inf->get_derivative_wrt_inference_method(param);
	}
	else if (obj==inf->m_model)
	{
		// try to find derivative wrt LikelihoodModel.parameter
		gradient=inf->get_derivative_wrt_likelihood_model(param);
	}
	else if (obj==inf->m_kernel)
	{
		// try to find derivative wrt Kernel.parameter
		gradient=inf->get_derivative_wrt_kernel(param);
	}
	else if (obj==inf->m_mean)
	{
		// try to find derivative wrt MeanFunction.parameter
		gradient=inf->get_derivative_wrt_mean(param);
	}
	else
	{
		SG_SERROR("Can't compute derivative of negative log marginal "
				"likelihood wrt %s.%s", obj->get_name(), param->m_name);
	}

	lock->lock();
	grad->add(param, gradient);
	lock->unlock();

	return NULL;
}

void CInferenceMethod::update()
{
	check_members();
	update_train_kernel();
}

void CInferenceMethod::check_members() const
{
	REQUIRE(m_features, "Training features should not be NULL\n")
	REQUIRE(m_features->get_num_vectors(),
			"Number of training features must be greater than zero\n")
	REQUIRE(m_labels, "Labels should not be NULL\n")
	REQUIRE(m_labels->get_num_labels(),
			"Number of labels must be greater than zero\n")
	REQUIRE(m_labels->get_num_labels()==m_features->get_num_vectors(),
			"Number of training vectors must match number of labels, which is "
			"%d, but number of training vectors is %d\n",
			m_labels->get_num_labels(), m_features->get_num_vectors())
	REQUIRE(m_kernel, "Kernel should not be NULL\n")
	REQUIRE(m_mean, "Mean function should not be NULL\n")
}

void CInferenceMethod::update_train_kernel()
{
	m_kernel->init(m_features, m_features);
	m_ktrtr=m_kernel->get_kernel_matrix();
}

#endif /* HAVE_EIGEN3 */
<commit_msg>update the comment<commit_after>/*
 * This program is free software; you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation; either version 3 of the License, or
 * (at your option) any later version.
 *
 * Written (W) 2013 Roman Votyakov
 * Written (W) 2013 Heiko Strathmann
 * Copyright (C) 2012 Jacob Walker
 * Copyright (C) 2013 Roman Votyakov
 */

#include <shogun/lib/config.h>

#ifdef HAVE_EIGEN3

#include <shogun/machine/gp/InferenceMethod.h>
#include <shogun/distributions/classical/GaussianDistribution.h>
#include <shogun/mathematics/Statistics.h>
#include <shogun/mathematics/Math.h>
#include <shogun/lib/Lock.h>

using namespace shogun;

#ifndef DOXYGEN_SHOULD_SKIP_THIS
struct GRADIENT_THREAD_PARAM
{
	CInferenceMethod* inf;
	CMap<TParameter*, SGVector<float64_t> >* grad;
	CSGObject* obj;
	TParameter* param;
	CLock* lock;
};
#endif /* DOXYGEN_SHOULD_SKIP_THIS */

CInferenceMethod::CInferenceMethod()
{
	init();
}

float64_t CInferenceMethod::get_scale() const
{
	return CMath::exp(m_log_scale);
}

void CInferenceMethod::set_scale(float64_t scale)
{
	REQUIRE(scale>0, "Scale (%f) must be positive", scale);
	m_log_scale=CMath::log(scale);
}

SGMatrix<float64_t> CInferenceMethod::get_multiclass_E()
{
	if (parameter_hash_changed())
		update();

	return SGMatrix<float64_t>(m_E);
}

CInferenceMethod::CInferenceMethod(CKernel* kernel, CFeatures* features,
	CMeanFunction* mean, CLabels* labels, CLikelihoodModel* model)
{
	init();

	set_kernel(kernel);
	set_features(features);
	set_labels(labels);
	set_model(model);
	set_mean(mean);
}

CInferenceMethod::~CInferenceMethod()
{
	SG_UNREF(m_kernel);
	SG_UNREF(m_features);
	SG_UNREF(m_labels);
	SG_UNREF(m_model);
	SG_UNREF(m_mean);
}

void CInferenceMethod::init()
{
	SG_ADD((CSGObject**)&m_kernel, "kernel", "Kernel", MS_AVAILABLE);
	SG_ADD(&m_log_scale, "log_scale", "Kernel log scale", MS_AVAILABLE, GRADIENT_AVAILABLE);
	SG_ADD((CSGObject**)&m_model, "likelihood_model", "Likelihood model",
		MS_AVAILABLE);
	SG_ADD((CSGObject**)&m_mean, "mean_function", "Mean function", MS_AVAILABLE);
	SG_ADD((CSGObject**)&m_labels, "labels", "Labels", MS_NOT_AVAILABLE);
	SG_ADD((CSGObject**)&m_features, "features", "Features", MS_NOT_AVAILABLE);

	m_kernel=NULL;
	m_model=NULL;
	m_labels=NULL;
	m_features=NULL;
	m_mean=NULL;
	m_log_scale=0.0;

	SG_ADD(&m_alpha, "alpha", "alpha vector used in process mean calculation", MS_NOT_AVAILABLE);
	SG_ADD(&m_L, "L", "upper triangular factor of Cholesky decomposition", MS_NOT_AVAILABLE);
	SG_ADD(&m_E, "E", "the matrix used for multi classification", MS_NOT_AVAILABLE);
}

float64_t CInferenceMethod::get_marginal_likelihood_estimate(
		int32_t num_importance_samples, float64_t ridge_size)
{
	/* sample from Gaussian approximation to q(f|y) */
	SGMatrix<float64_t> cov=get_posterior_covariance();

	/* add ridge */
	for (index_t i=0; i<cov.num_rows; ++i)
		cov(i,i)+=ridge_size;

	SGVector<float64_t> mean=get_posterior_mean();

	CGaussianDistribution* post_approx=new CGaussianDistribution(mean, cov);
	SGMatrix<float64_t> samples=post_approx->sample(num_importance_samples);

	/* evaluate q(f^i|y), p(f^i|\theta), p(y|f^i), i.e.,
	 * log pdf of approximation, prior and likelihood */

	/* log pdf q(f^i|y) */
	SGVector<float64_t> log_pdf_post_approx=post_approx->log_pdf_multiple(samples);

	/* dont need gaussian anymore, free memory */
	SG_UNREF(post_approx);
	post_approx=NULL;

	/* log pdf p(f^i|\theta) and free memory afterwise. Scale kernel before */
	SGMatrix<float64_t> scaled_kernel(m_ktrtr.num_rows, m_ktrtr.num_cols);
	memcpy(scaled_kernel.matrix, m_ktrtr.matrix,
			sizeof(float64_t)*m_ktrtr.num_rows*m_ktrtr.num_cols);
	for (index_t i=0; i<m_ktrtr.num_rows*m_ktrtr.num_cols; ++i)
		scaled_kernel.matrix[i]*=CMath::exp(m_log_scale*2.0);

	/* add ridge */
	for (index_t i=0; i<cov.num_rows; ++i)
		scaled_kernel(i,i)+=ridge_size;

	CGaussianDistribution* prior=new CGaussianDistribution(
			m_mean->get_mean_vector(m_features), scaled_kernel);
	SGVector<float64_t> log_pdf_prior=prior->log_pdf_multiple(samples);
	SG_UNREF(prior);
	prior=NULL;

	/* p(y|f^i) */
	SGVector<float64_t> log_likelihood=m_model->get_log_probability_fmatrix(
			m_labels, samples);

	/* combine probabilities */
	ASSERT(log_likelihood.vlen==num_importance_samples);
	ASSERT(log_likelihood.vlen==log_pdf_prior.vlen);
	ASSERT(log_likelihood.vlen==log_pdf_post_approx.vlen);
	SGVector<float64_t> sum(log_likelihood);
	for (index_t i=0; i<log_likelihood.vlen; ++i)
		sum[i]=log_likelihood[i]+log_pdf_prior[i]-log_pdf_post_approx[i];

	/* use log-sum-exp (in particular, log-mean-exp) trick to combine values */
	return CMath::log_mean_exp(sum);
}

CMap<TParameter*, SGVector<float64_t> >* CInferenceMethod::
get_negative_log_marginal_likelihood_derivatives(CMap<TParameter*, CSGObject*>* params)
{
	REQUIRE(params->get_num_elements(), "Number of parameters should be greater "
			"than zero\n")

	if (parameter_hash_changed())
		update();

	// get number of derivatives
	const index_t num_deriv=params->get_num_elements();

	// create map of derivatives
	CMap<TParameter*, SGVector<float64_t> >* result=
		new CMap<TParameter*, SGVector<float64_t> >(num_deriv, num_deriv);

	SG_REF(result);

	// create lock object
	CLock lock;

#ifdef HAVE_PTHREAD
	if (num_deriv<2)
	{
#endif /* HAVE_PTHREAD */
		for (index_t i=0; i<num_deriv; i++)
		{
			CMapNode<TParameter*, CSGObject*>* node=params->get_node_ptr(i);

			GRADIENT_THREAD_PARAM thread_params;

			thread_params.inf=this;
			thread_params.obj=node->data;
			thread_params.param=node->key;
			thread_params.grad=result;
			thread_params.lock=&lock;

			get_derivative_helper((void*) &thread_params);
		}
#ifdef HAVE_PTHREAD
	}
	else
	{
		pthread_t* threads=SG_MALLOC(pthread_t, num_deriv);
		GRADIENT_THREAD_PARAM* thread_params=SG_MALLOC(GRADIENT_THREAD_PARAM,
				num_deriv);

		for (index_t t=0; t<num_deriv; t++)
		{
			CMapNode<TParameter*, CSGObject*>* node=params->get_node_ptr(t);

			thread_params[t].inf=this;
			thread_params[t].obj=node->data;
			thread_params[t].param=node->key;
			thread_params[t].grad=result;
			thread_params[t].lock=&lock;

			pthread_create(&threads[t], NULL, CInferenceMethod::get_derivative_helper,
					(void*)&thread_params[t]);
		}

		for (index_t t=0; t<num_deriv; t++)
			pthread_join(threads[t], NULL);

		SG_FREE(thread_params);
		SG_FREE(threads);
	}
#endif /* HAVE_PTHREAD */

	return result;
}

void* CInferenceMethod::get_derivative_helper(void *p)
{
	GRADIENT_THREAD_PARAM* thread_param=(GRADIENT_THREAD_PARAM*)p;

	CInferenceMethod* inf=thread_param->inf;
	CSGObject* obj=thread_param->obj;
	CMap<TParameter*, SGVector<float64_t> >* grad=thread_param->grad;
	TParameter* param=thread_param->param;
	CLock* lock=thread_param->lock;

	REQUIRE(param, "Parameter should not be NULL\n");
	REQUIRE(obj, "Object of the parameter should not be NULL\n");

	SGVector<float64_t> gradient;

	if (obj==inf)
	{
		// try to find dervative wrt InferenceMethod.parameter
		gradient=inf->get_derivative_wrt_inference_method(param);
	}
	else if (obj==inf->m_model)
	{
		// try to find derivative wrt LikelihoodModel.parameter
		gradient=inf->get_derivative_wrt_likelihood_model(param);
	}
	else if (obj==inf->m_kernel)
	{
		// try to find derivative wrt Kernel.parameter
		gradient=inf->get_derivative_wrt_kernel(param);
	}
	else if (obj==inf->m_mean)
	{
		// try to find derivative wrt MeanFunction.parameter
		gradient=inf->get_derivative_wrt_mean(param);
	}
	else
	{
		SG_SERROR("Can't compute derivative of negative log marginal "
				"likelihood wrt %s.%s", obj->get_name(), param->m_name);
	}

	lock->lock();
	grad->add(param, gradient);
	lock->unlock();

	return NULL;
}

void CInferenceMethod::update()
{
	check_members();
	update_train_kernel();
}

void CInferenceMethod::check_members() const
{
	REQUIRE(m_features, "Training features should not be NULL\n")
	REQUIRE(m_features->get_num_vectors(),
			"Number of training features must be greater than zero\n")
	REQUIRE(m_labels, "Labels should not be NULL\n")
	REQUIRE(m_labels->get_num_labels(),
			"Number of labels must be greater than zero\n")
	REQUIRE(m_labels->get_num_labels()==m_features->get_num_vectors(),
			"Number of training vectors (%d) must match number of labels (%d)\n",
			m_labels->get_num_labels(), m_features->get_num_vectors())
	REQUIRE(m_kernel, "Kernel should not be NULL\n")
	REQUIRE(m_mean, "Mean function should not be NULL\n")
}

void CInferenceMethod::update_train_kernel()
{
	m_kernel->init(m_features, m_features);
	m_ktrtr=m_kernel->get_kernel_matrix();
}

#endif /* HAVE_EIGEN3 */
<|endoftext|>


<commit_before>// Licensed to the Apache Software Foundation (ASF) under one
// or more contributor license agreements.  See the NOTICE file
// distributed with this work for additional information
// regarding copyright ownership.  The ASF licenses this file
// to you 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.

#ifndef __CONTAINERIZER_HPP__
#define __CONTAINERIZER_HPP__

#include <map>

#include <mesos/mesos.hpp>
#include <mesos/resources.hpp>

#include <mesos/containerizer/containerizer.hpp>

#include <process/future.hpp>
#include <process/owned.hpp>
#include <process/process.hpp>

#include <stout/duration.hpp>
#include <stout/hashset.hpp>
#include <stout/option.hpp>
#include <stout/try.hpp>

#include "slave/containerizer/fetcher.hpp"

namespace mesos {
namespace internal {
namespace slave {

// Forward declaration.
class Slave;
class Flags;

namespace state {
// Forward declaration.
struct SlaveState;
} // namespace state {

// An abstraction of a Containerizer that will contain an executor and its
// tasks.
class Containerizer
{
public:
  // Attempts to create a containerizer as specified by 'isolation' in flags.
  static Try<Containerizer*> create(
      const Flags& flags,
      bool local,
      Fetcher* fetcher);

  // Determine slave resources from flags, probing the system or querying a
  // delegate.
  // TODO(idownes): Consider making this non-static and moving to containerizer
  // implementations to enable a containerizer to best determine the resources,
  // particularly if containerizeration is delegated.
  static Try<Resources> resources(const Flags& flags);

  virtual ~Containerizer() {}

  // Recover all containerized executors specified in state. Any containerized
  // executors present on the system but not included in state (or state is
  // None) will be terminated and cleaned up.
  virtual process::Future<Nothing> recover(
      const Option<state::SlaveState>& state) = 0;

  // Launch a containerized executor. Returns true if launching this
  // ExecutorInfo is supported and it has been launched, otherwise
  // false or a failure is something went wrong.
  virtual process::Future<bool> launch(
      const ContainerID& containerId,
      const ExecutorInfo& executorInfo,
      const std::string& directory,
      const Option<std::string>& user,
      const SlaveID& slaveId,
      const process::PID<Slave>& slavePid,
      bool checkpoint) = 0;

  // Launch a containerized task. Returns true if launching this
  // TaskInfo/ExecutorInfo is supported and it has been launched,
  // otherwise false or a failure is something went wrong.
  // TODO(nnielsen): Obsolete the executorInfo argument when the slave
  // doesn't require executors to run standalone tasks.
  virtual process::Future<bool> launch(
      const ContainerID& containerId,
      const TaskInfo& taskInfo,
      const ExecutorInfo& executorInfo,
      const std::string& directory,
      const Option<std::string>& user,
      const SlaveID& slaveId,
      const process::PID<Slave>& slavePid,
      bool checkpoint) = 0;

  // Update the resources for a container.
  virtual process::Future<Nothing> update(
      const ContainerID& containerId,
      const Resources& resources) = 0;

  // Get resource usage statistics on the container.
  virtual process::Future<ResourceStatistics> usage(
      const ContainerID& containerId) = 0;

  // Wait on the container's 'Termination'. If the executor terminates, the
  // containerizer should also destroy the containerized context. The future
  // may be failed if an error occurs during termination of the executor or
  // destruction of the container.
  virtual process::Future<containerizer::Termination> wait(
      const ContainerID& containerId) = 0;

  // Destroy a running container, killing all processes and releasing all
  // resources.
  // NOTE: You cannot wait() on containers that have been destroyed, so you
  // should always call wait() before destroy().
  virtual void destroy(const ContainerID& containerId) = 0;

  virtual process::Future<hashset<ContainerID>> containers() = 0;
};

/**
 * Returns a map of environment variables necessary in order to launch
 * an executor.
 *
 * @param executorInfo ExecutorInfo being launched.
 * @param directory Path to the sandbox directory.
 * @param slaveId SlaveID where this executor is being launched.
 * @param slavePid PID of the slave launching the executor.
 * @param checkpoint Whether or not the framework is checkpointing.
 * @param flags Flags used to launch the slave.
 *
 * @return Map of environment variables (name, value).
 */
std::map<std::string, std::string> executorEnvironment(
    const ExecutorInfo& executorInfo,
    const std::string& directory,
    const SlaveID& slaveId,
    const process::PID<Slave>& slavePid,
    bool checkpoint,
    const Flags& flags,
    bool includeOsEnvironment = true);

} // namespace slave {
} // namespace internal {
} // namespace mesos {

#endif // __CONTAINERIZER_HPP__
<commit_msg>Defined a virtual `status` method for Containerizer.<commit_after>// Licensed to the Apache Software Foundation (ASF) under one
// or more contributor license agreements.  See the NOTICE file
// distributed with this work for additional information
// regarding copyright ownership.  The ASF licenses this file
// to you 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.

#ifndef __CONTAINERIZER_HPP__
#define __CONTAINERIZER_HPP__

#include <map>

#include <mesos/mesos.hpp>
#include <mesos/resources.hpp>

#include <mesos/containerizer/containerizer.hpp>

#include <process/future.hpp>
#include <process/owned.hpp>
#include <process/process.hpp>

#include <stout/duration.hpp>
#include <stout/hashset.hpp>
#include <stout/option.hpp>
#include <stout/try.hpp>

#include "slave/containerizer/fetcher.hpp"

namespace mesos {
namespace internal {
namespace slave {

// Forward declaration.
class Slave;
class Flags;

namespace state {
// Forward declaration.
struct SlaveState;
} // namespace state {

// An abstraction of a Containerizer that will contain an executor and
// its tasks.
class Containerizer
{
public:
  // Attempts to create a containerizer as specified by 'isolation' in
  // flags.
  static Try<Containerizer*> create(
      const Flags& flags,
      bool local,
      Fetcher* fetcher);

  // Determine slave resources from flags, probing the system or
  // querying a delegate.
  // TODO(idownes): Consider making this non-static and moving to
  // containerizer implementations to enable a containerizer to best
  // determine the resources, particularly if containerizeration is
  // delegated.
  static Try<Resources> resources(const Flags& flags);

  virtual ~Containerizer() {}

  // Recover all containerized executors specified in state. Any
  // containerized executors present on the system but not included in
  // state (or state is None) will be terminated and cleaned up.
  virtual process::Future<Nothing> recover(
      const Option<state::SlaveState>& state) = 0;

  // Launch a containerized executor. Returns true if launching this
  // ExecutorInfo is supported and it has been launched, otherwise
  // false or a failure is something went wrong.
  virtual process::Future<bool> launch(
      const ContainerID& containerId,
      const ExecutorInfo& executorInfo,
      const std::string& directory,
      const Option<std::string>& user,
      const SlaveID& slaveId,
      const process::PID<Slave>& slavePid,
      bool checkpoint) = 0;

  // Launch a containerized task. Returns true if launching this
  // TaskInfo/ExecutorInfo is supported and it has been launched,
  // otherwise false or a failure is something went wrong.
  // TODO(nnielsen): Obsolete the executorInfo argument when the slave
  // doesn't require executors to run standalone tasks.
  virtual process::Future<bool> launch(
      const ContainerID& containerId,
      const TaskInfo& taskInfo,
      const ExecutorInfo& executorInfo,
      const std::string& directory,
      const Option<std::string>& user,
      const SlaveID& slaveId,
      const process::PID<Slave>& slavePid,
      bool checkpoint) = 0;

  // Update the resources for a container.
  virtual process::Future<Nothing> update(
      const ContainerID& containerId,
      const Resources& resources) = 0;

  // Get resource usage statistics on the container.
  virtual process::Future<ResourceStatistics> usage(
      const ContainerID& containerId) = 0;

  // Retrieve the run-time state of various isolator properties
  // associated with the container. Unlike other methods in this class
  // we are not making this pure virtual, since a `Containerizer`
  // doesn't necessarily need to return the status of a container.
  virtual process::Future<ContainerStatus> status(
      const ContainerID &containerId)
  {
    return ContainerStatus();
  }

  // Wait on the container's 'Termination'. If the executor
  // terminates, the containerizer should also destroy the
  // containerized context. The future may be failed if an error
  // occurs during termination of the executor or destruction of the
  // container.
  virtual process::Future<containerizer::Termination> wait(
      const ContainerID& containerId) = 0;

  // Destroy a running container, killing all processes and releasing
  // all resources.
  // NOTE: You cannot wait() on containers that have been destroyed,
  // so you should always call wait() before destroy().
  virtual void destroy(const ContainerID& containerId) = 0;

  virtual process::Future<hashset<ContainerID>> containers() = 0;
};

/**
 * Returns a map of environment variables necessary in order to launch
 * an executor.
 *
 * @param executorInfo ExecutorInfo being launched.
 * @param directory Path to the sandbox directory.
 * @param slaveId SlaveID where this executor is being launched.
 * @param slavePid PID of the slave launching the executor.
 * @param checkpoint Whether or not the framework is checkpointing.
 * @param flags Flags used to launch the slave.
 *
 * @return Map of environment variables (name, value).
 */
std::map<std::string, std::string> executorEnvironment(
    const ExecutorInfo& executorInfo,
    const std::string& directory,
    const SlaveID& slaveId,
    const process::PID<Slave>& slavePid,
    bool checkpoint,
    const Flags& flags,
    bool includeOsEnvironment = true);

} // namespace slave {
} // namespace internal {
} // namespace mesos {

#endif // __CONTAINERIZER_HPP__
<|endoftext|>