<commit_before>#include <Geometry.h>

namespace Data
{
	Geometry::Geometry(std::vector<std::vector<double>> basis_i, const std::vector<std::vector<double>> translation_vectors_i,
		const std::vector<int> n_cells_i, const int n_spins_basic_domain_i, const std::vector<double> spin_pos_i) :
		basis(basis_i), translation_vectors(translation_vectors_i),
		n_cells(n_cells_i), n_spins_basic_domain(n_spins_basic_domain_i),
		spin_pos(spin_pos_i), nos( n_spins_basic_domain_i * n_cells_i[0] * n_cells_i[1] * n_cells_i[2])
	{
		// Calculate Bounds of the System
		this->bounds_min = std::vector<double>(3);
		this->bounds_max = std::vector<double>(3);
		this->center = std::vector<double>(3);

		for (int dim = 0; dim < 3; ++dim)
		{
			for (int iatom = 0; iatom < nos; ++iatom)
			{
				if (this->spin_pos[dim*nos + iatom] < this->bounds_min[dim]) this->bounds_min[dim] = spin_pos[dim*nos + iatom];
				if (this->spin_pos[dim*nos + iatom] > this->bounds_max[dim]) this->bounds_max[dim] = spin_pos[dim*nos + iatom];
			}
		}

		// Calculate Center of the System
		for (int dim = 0; dim < 3; ++dim)
		{
			this->center[dim] = (this->bounds_min[dim] + this->bounds_max[dim]) / 2.0;
		}
	}
}<commit_msg>Added delaunay decomposition function<commit_after>#include <Geometry.h>

namespace Data
{
	Geometry::Geometry(std::vector<std::vector<double>> basis_i, const std::vector<std::vector<double>> translation_vectors_i,
		const std::vector<int> n_cells_i, const int n_spins_basic_domain_i, const std::vector<double> spin_pos_i) :
		basis(basis_i), translation_vectors(translation_vectors_i),
		n_cells(n_cells_i), n_spins_basic_domain(n_spins_basic_domain_i),
		spin_pos(spin_pos_i), nos( n_spins_basic_domain_i * n_cells_i[0] * n_cells_i[1] * n_cells_i[2])
	{
		// Calculate Bounds of the System
		this->bounds_min = std::vector<double>(3);
		this->bounds_max = std::vector<double>(3);
		this->center = std::vector<double>(3);

		for (int dim = 0; dim < 3; ++dim)
		{
			for (int iatom = 0; iatom < nos; ++iatom)
			{
				if (this->spin_pos[dim*nos + iatom] < this->bounds_min[dim]) this->bounds_min[dim] = spin_pos[dim*nos + iatom];
				if (this->spin_pos[dim*nos + iatom] > this->bounds_max[dim]) this->bounds_max[dim] = spin_pos[dim*nos + iatom];
			}
		}

		// Calculate Center of the System
		for (int dim = 0; dim < 3; ++dim)
		{
			this->center[dim] = (this->bounds_min[dim] + this->bounds_max[dim]) / 2.0;
		}
	}
}

void do_delaunay(int npoints, const double *x, const double *y, int *ntri, int **triangles) {
    coordT *points = NULL;
    facetT *facet;
    vertexT *vertex, **vertexp;
    int i, max_facet_id;
    int *tri_indices = NULL;
    int indices[3], *indicesp;
    int curlong, totlong;
    const int ndim = 2;
    int *tri = NULL;

    *ntri = 0;
    *triangles = NULL;

    points = (coordT *) malloc(npoints * ndim * sizeof(coordT));
    if (points != NULL) {

        for (i = 0; i < npoints; ++i) {
            points[2*i  ] = x[i];
            points[2*i+1] = y[i];
        }

        /* Perform Delaunay triangulation */
        if (qh_new_qhull(ndim, npoints, points, False, "qhull d Qt QbB Qz", NULL, stderr) == qh_ERRnone) {
            /* Split facets so that they only have 3 points each */
            qh_triangulate();

            /* Determine ntri and max_facet_id */
            FORALLfacets {
                if (!facet->upperdelaunay)
                    (*ntri)++;
            }

            max_facet_id = qh facet_id - 1;

            /* Create array to map facet id to triangle index */
            tri_indices = (int *) malloc((max_facet_id+1) * sizeof(int));
            if (tri_indices != NULL) {

                tri = (int *) malloc(*ntri * 3 * sizeof(int));
                if (tri != NULL) {
                    *triangles = tri;

                    /* Determine triangles array and set tri_indices array */
                    i = 0;
                    FORALLfacets {
                        if (!facet->upperdelaunay) {
                            tri_indices[facet->id] = i++;

                            indicesp = indices;
                            FOREACHvertex_(facet->vertices)
                                *indicesp++ = qh_pointid(vertex->point);

                            *tri++ = (facet->toporient ? indices[0] : indices[2]);
                            *tri++ = indices[1];
                            *tri++ = (facet->toporient ? indices[2] : indices[0]);
                        }
                        else
                            tri_indices[facet->id] = -1;
                    }

                    /*
                     * xp = x;
                     * yp = y;
                     * qsort(*triangles, *ntri, 3 * sizeof(int), compar);
                     */
                }
                else
                    fprintf(stderr, "Could not allocate triangle array\n");

                free(tri_indices);
            }
            else
                fprintf(stderr, "Could not allocate triangle map\n");
        }
        else
            fprintf(stderr, "Error in Delaunay triangulation calculation\n");

        qh_freeqhull(!qh_ALL);
        qh_memfreeshort(&curlong, &totlong);
        if (curlong || totlong)
            fprintf(stderr, "Could not free all allocated memory\n");

        free(points);
    }
    else
        fprintf(stderr, "Could not allocate point array\n");
}
<|endoftext|>


<commit_before>#include "jobQueue.h"

namespace Tangram {

JobQueue::~JobQueue() {

    if (!m_jobs.empty()) {
        runJobs();
    }

}

void JobQueue::add(Job job) {

    std::lock_guard<std::mutex> lock(m_mutex);
    m_jobs.push_back(job);

}

void JobQueue::runJobs() {

    auto it = m_jobs.begin();
    auto end = m_jobs.end();
    while (it != end) {
        Job job;
        {
            std::lock_guard<std::mutex> lock(m_mutex);
            job.swap(*it);
            ++it;
        }
        job();
    }
    m_jobs.clear();

}

} //namespace Tangram
<commit_msg>fix: invalid iterator<commit_after>#include "jobQueue.h"

namespace Tangram {

JobQueue::~JobQueue() {

    if (!m_jobs.empty()) {
        runJobs();
    }

}

void JobQueue::add(Job job) {

    std::lock_guard<std::mutex> lock(m_mutex);
    m_jobs.push_back(job);

}

void JobQueue::runJobs() {

    for (size_t i = 0; i < m_jobs.size(); i++) {
        Job job;
        {
            std::lock_guard<std::mutex> lock(m_mutex);
            job.swap(m_jobs[i]);
        }
        job();
    }
    m_jobs.clear();

}

} //namespace Tangram
<|endoftext|>


<commit_before>#include <catch.hpp>
#include <Spirit/State.h>
#include <Spirit/Configurations.h>
#include <Spirit/Transitions.h>
#include <Spirit/Parameters_LLG.h>
#include <Spirit/Parameters_GNEB.h>
#include <Spirit/Geometry.h>
#include <Spirit/Simulation.h>
#include <Spirit/System.h>
#include <Spirit/Chain.h>
#include <Spirit/Quantities.h>
#include <iostream>

TEST_CASE( "Solvers testing", "[solvers]" )
{
    // Input file
    auto inputfile = "core/test/input/solvers.cfg";

    // State
    auto state = std::shared_ptr<State>( State_Setup( inputfile ), State_Delete );

    // Solvers to be tested
    std::vector<int>  solvers { Solver_VP, Solver_Heun, Solver_SIB, Solver_Depondt, Solver_RungeKutta4 };

    // Expected values
    float energy_expected = -5849.69140625f;
    std::vector<float> magnetization_expected{ 0, 0, 0.79977f };

    // Result values
    scalar energy;
    std::vector<float> magnetization{ 0, 0, 0 };

    // Calculate energy and magnetization for every solvers
    for ( auto solver : solvers )
    {
        // Put a skyrmion in the center of the space
        Configuration_PlusZ( state.get() );
        Configuration_Skyrmion( state.get(), 5, 1, -90, false, false, false);

        // Do simulation
        Simulation_LLG_Start( state.get(), solver );

        // Save energy and magnetization
        energy = System_Get_Energy( state.get() );
        Quantity_Get_Magnetization( state.get(), magnetization.data() );

        // Log the name of the solvers
        INFO( "LLG using " << solver << " solver" );

        // Check the values of energy and magnetization
        REQUIRE( energy == Approx( energy_expected ) );
        for (int dim=0; dim<3; dim++)
            REQUIRE( magnetization[dim] == Approx( magnetization_expected[dim] ) );
    }

    // Calculate energy and magnetization for every solvers with direct minimization
    Parameters_LLG_Set_Direct_Minimization( state.get(), true );
    for ( auto solver : solvers )
    {
        // Put a skyrmion in the center of the space
        Configuration_PlusZ( state.get() );
        Configuration_Skyrmion( state.get(), 5, 1, -90, false, false, false);

        // Do simulation
        Simulation_LLG_Start( state.get(), solver );

        // Save energy and magnetization
        energy = System_Get_Energy( state.get() );
        Quantity_Get_Magnetization( state.get(), magnetization.data() );

        // Log the name of the solvers
        INFO( "LLG using " << solver << " solver (direct)" );

        // Check the values of energy and magnetization
        REQUIRE( energy == Approx( energy_expected ) );
        for (int dim=0; dim<3; dim++)
            REQUIRE( magnetization[dim] == Approx( magnetization_expected[dim] ) );
    }

    Chain_Image_to_Clipboard(state.get());
    int noi = 4;

    for (int i=1; i<noi; ++i)
      Chain_Insert_Image_After(state.get());

    // Solvers to be tested
    solvers = { Solver_VP, Solver_Heun, Solver_Depondt };

    // Expected values
    float energy_sp_expected = -5811.5244140625f;
    std::vector<float> magnetization_sp_expected{ 0, 0, 0.96657f };

    // Result values
    scalar energy_sp;
    std::vector<float> magnetization_sp{ 0, 0, 0 };

    // Calculate energy and magnetization at saddle point for every solver
    for ( auto solver : solvers )
    {
        // Create a skyrmion collapse transition
        Chain_Replace_Image(state.get(), 0);
        Chain_Jump_To_Image(state.get(), noi-1);
        Configuration_PlusZ(state.get());
        Chain_Jump_To_Image(state.get(), 0);
        Transition_Homogeneous(state.get(), 0, noi-1);

        // Do simulation
        Simulation_GNEB_Start( state.get(), solver, 2e4 );
        Parameters_GNEB_Set_Image_Type_Automatically( state.get() );
        Simulation_GNEB_Start( state.get(), solver );

        // Get saddle point index
        int i_max = 1;
        float E_max = System_Get_Energy(state.get(), 0);

        for (int i=1; i<noi-1; ++i)
            if (System_Get_Energy(state.get(), i) > E_max) i_max = i;

        // Save energy and magnetization
        energy_sp = System_Get_Energy( state.get(), i_max );
        Quantity_Get_Magnetization( state.get(), magnetization_sp.data(), i_max );

        // Log the name of the solver
        INFO( "GNEB using " << solver << " solver" );

        // Check the values of energy and magnetization
        REQUIRE( energy_sp == Approx( energy_sp_expected ) );
        for (int dim=0; dim<3; dim++)
            REQUIRE( magnetization_sp[dim] == Approx( magnetization_sp_expected[dim] ) );
    }

}<commit_msg>Corrected test_solver unit test and added LBFGS_OSO to it.<commit_after>#include <catch.hpp>
#include <Spirit/State.h>
#include <Spirit/Configurations.h>
#include <Spirit/Transitions.h>
#include <Spirit/Parameters_LLG.h>
#include <Spirit/Parameters_GNEB.h>
#include <Spirit/Geometry.h>
#include <Spirit/Simulation.h>
#include <Spirit/System.h>
#include <Spirit/Chain.h>
#include <Spirit/Quantities.h>
#include <iostream>

TEST_CASE( "Solvers testing", "[solvers]" )
{
    // Input file
    auto inputfile = "core/test/input/solvers.cfg";

    // State
    auto state = std::shared_ptr<State>( State_Setup( inputfile ), State_Delete );

    // Solvers to be tested
    std::vector<int>  solvers { Solver_LBFGS_OSO, Solver_VP, Solver_Heun, Solver_SIB, Solver_Depondt, Solver_RungeKutta4 };

    // Expected values
    float energy_expected = -5849.69140625f;
    std::vector<float> magnetization_expected{ 0, 0, 0.79977f };

    // Result values
    scalar energy;
    std::vector<float> magnetization{ 0, 0, 0 };

    // Calculate energy and magnetization for every solvers
    for ( auto solver : solvers )
    {
        // Put a skyrmion in the center of the space
        Configuration_PlusZ( state.get() );
        Configuration_Skyrmion( state.get(), 5, 1, -90, false, false, false);

        // Do simulation
        Simulation_LLG_Start( state.get(), solver );

        // Save energy and magnetization
        energy = System_Get_Energy( state.get() );
        Quantity_Get_Magnetization( state.get(), magnetization.data() );

        // Log the name of the solvers
        INFO( "LLG using " << solver << " solver" );

        // Check the values of energy and magnetization
        REQUIRE( energy == Approx( energy_expected ) );
        for (int dim=0; dim<3; dim++)
            REQUIRE( magnetization[dim] == Approx( magnetization_expected[dim] ) );
    }

    // Calculate energy and magnetization for every solvers with direct minimization
    Parameters_LLG_Set_Direct_Minimization( state.get(), true );
    for ( auto solver : solvers )
    {
        // Put a skyrmion in the center of the space
        Configuration_PlusZ( state.get() );
        Configuration_Skyrmion( state.get(), 5, 1, -90, false, false, false);

        // Do simulation
        Simulation_LLG_Start( state.get(), solver );

        // Save energy and magnetization
        energy = System_Get_Energy( state.get() );
        Quantity_Get_Magnetization( state.get(), magnetization.data() );

        // Log the name of the solvers
        INFO( "LLG using " << solver << " solver (direct)" );

        // Check the values of energy and magnetization
        REQUIRE( energy == Approx( energy_expected ) );
        for (int dim=0; dim<3; dim++)
            REQUIRE( magnetization[dim] == Approx( magnetization_expected[dim] ) );
    }

    Chain_Image_to_Clipboard(state.get());
    int noi = 9;

    for (int i=1; i<noi; ++i)
      Chain_Insert_Image_After(state.get());

    // Solvers to be tested
    solvers = { Solver_LBFGS_OSO, Solver_VP, Solver_Heun, Solver_Depondt };

    // Expected values
    float energy_sp_expected = -5811.5244140625f;
    std::vector<float> magnetization_sp_expected{ 0, 0, 0.96657f };

    // Result values
    scalar energy_sp;
    std::vector<float> magnetization_sp{ 0, 0, 0 };

    // Calculate energy and magnetization at saddle point for every solver
    for ( auto solver : solvers )
    {
        // Create a skyrmion collapse transition
        Chain_Replace_Image(state.get(), 0);
        Chain_Jump_To_Image(state.get(), noi-1);
        Configuration_PlusZ(state.get());
        Chain_Jump_To_Image(state.get(), 0);
        Transition_Homogeneous(state.get(), 0, noi-1);

        // Do simulation
        Simulation_GNEB_Start( state.get(), solver, 2e4 );
        Parameters_GNEB_Set_Image_Type_Automatically( state.get() );
        Simulation_GNEB_Start( state.get(), solver );

        // Get saddle point index
        int i_max = 1;
        float E_max = System_Get_Energy(state.get(), 0);

        float E_temp = 0;
        for (int i=1; i<noi-1; ++i)
        {
            E_temp = System_Get_Energy(state.get(), i);
            if (E_temp > E_max)
            {
                i_max = i;
                E_max = E_temp;
            }
        }

        // Save energy and magnetization
        energy_sp = E_max;
        Quantity_Get_Magnetization( state.get(), magnetization_sp.data(), i_max );

        // Log the name of the solver
        INFO( "GNEB using " << solver << " solver" );

        // Check the values of energy and magnetization
        REQUIRE( energy_sp == Approx( energy_sp_expected ) );
        for (int dim=0; dim<3; dim++)
            REQUIRE( magnetization_sp[dim] == Approx( magnetization_sp_expected[dim] ) );
    }

}<|endoftext|>


<commit_before>/*
 * copyright: (c) RDO-Team, 2009
 * filename : rdo_type_param.cpp
 * author   :
 * date     : 12.02.2010
 * bref     :
 * indent   : 4T
 */

// ====================================================================== PCH
#include "rdo_lib/rdo_parser/pch.h"
// ====================================================================== INCLUDES
// ====================================================================== SYNOPSIS
#include "rdo_lib/rdo_parser/rdo_type_param.h"
#include "rdo_lib/rdo_parser/rdoparser.h"
// ===============================================================================

OPEN_RDO_PARSER_NAMESPACE

// ----------------------------------------------------------------------------
// ---------- RDOTypeParam
// ----------------------------------------------------------------------------
RDOTypeParam::RDOTypeParam(CREF(LPRDOType) type, CREF(RDOValue) default, CREF(RDOParserSrcInfo) src_info)
	: RDOParserSrcInfo(src_info)
	, m_type          (type    )
	, m_default       (default )
{
	ASSERT(m_type);
	if (m_default.defined())
	{
		m_type->type_cast(m_default.type(), m_default.src_info(), src_info, m_default.src_info());
		m_default = m_type->value_cast(m_default, src_info, m_default.src_info());
	}
	switch (m_type->type().typeID())
	{
	case rdoRuntime::RDOType::t_enum :
	case rdoRuntime::RDOType::t_fuzzy: RDOParser::s_parser()->insertPreCastType(this); break;
	}
}

RDOTypeParam::~RDOTypeParam()
{}

LPRDOType RDOTypeParam::type() const
{
	return m_type;
}

void RDOTypeParam::writeModelStructure(REF(std::ostream) stream) const
{
	m_type->writeModelStructure(stream);
}

RDOValue RDOTypeParam::value_cast(CREF(RDOValue) value) const
{
	return m_type->value_cast(value, src_info(), value.src_info());
}

CREF(RDOValue) RDOTypeParam::default() const
{
	return m_default;
}

CLOSE_RDO_PARSER_NAMESPACE
<commit_msg> - формирование src_text для RDOTypeParam<commit_after>/*
 * copyright: (c) RDO-Team, 2009
 * filename : rdo_type_param.cpp
 * author   :
 * date     : 12.02.2010
 * bref     :
 * indent   : 4T
 */

// ====================================================================== PCH
#include "rdo_lib/rdo_parser/pch.h"
// ====================================================================== INCLUDES
// ====================================================================== SYNOPSIS
#include "rdo_lib/rdo_parser/rdo_type_param.h"
#include "rdo_lib/rdo_parser/rdoparser.h"
// ===============================================================================

OPEN_RDO_PARSER_NAMESPACE

// ----------------------------------------------------------------------------
// ---------- RDOTypeParam
// ----------------------------------------------------------------------------
RDOTypeParam::RDOTypeParam(CREF(LPRDOType) type, CREF(RDOValue) default, CREF(RDOParserSrcInfo) src_info)
	: RDOParserSrcInfo(src_info)
	, m_type          (type    )
	, m_default       (default )
{
	ASSERT(m_type);
	setSrcText(m_type->name());

	if (m_default.defined())
	{
		m_type->type_cast(m_default.type(), m_default.src_info(), src_info, m_default.src_info());
		m_default = m_type->value_cast(m_default, src_info, m_default.src_info());
		setSrcText(rdo::format(_T("%s = %s"), src_text().c_str(), m_default.src_text().c_str()));
	}
	switch (m_type->type().typeID())
	{
	case rdoRuntime::RDOType::t_enum :
	case rdoRuntime::RDOType::t_fuzzy: RDOParser::s_parser()->insertPreCastType(this); break;
	}
}

RDOTypeParam::~RDOTypeParam()
{}

LPRDOType RDOTypeParam::type() const
{
	return m_type;
}

void RDOTypeParam::writeModelStructure(REF(std::ostream) stream) const
{
	m_type->writeModelStructure(stream);
}

RDOValue RDOTypeParam::value_cast(CREF(RDOValue) value) const
{
	return m_type->value_cast(value, src_info(), value.src_info());
}

CREF(RDOValue) RDOTypeParam::default() const
{
	return m_default;
}

CLOSE_RDO_PARSER_NAMESPACE
<|endoftext|>


<commit_before>#include "command.h"
#include "memory.h"
#include "progressbar.h"
#include "image/threaded_loop.h"
#include "image/buffer.h"
#include "image/buffer_preload.h"
#include "image/voxel.h"
#include "dwi/gradient.h"
#include "dwi/shells.h"
#include "dwi/sdeconv/constrained.h"

using namespace MR;
using namespace App;

void usage ()
{
  DESCRIPTION
    + "perform non-negativity constrained spherical deconvolution."

    + "Note that this program makes use of implied symmetries in the diffusion "
    "profile. First, the fact the signal attenuation profile is real implies "
    "that it has conjugate symmetry, i.e. Y(l,-m) = Y(l,m)* (where * denotes "
    "the complex conjugate). Second, the diffusion profile should be "
    "antipodally symmetric (i.e. S(x) = S(-x)), implying that all odd l "
    "components should be zero. Therefore, this program only computes the even "
    "elements."

    + "Note that the spherical harmonics equations used here differ slightly "
    "from those conventionally used, in that the (-1)^m factor has been "
    "omitted. This should be taken into account in all subsequent calculations."

    + Math::SH::encoding_description;

  REFERENCES
   + "Tournier, J.-D.; Calamante, F. & Connelly, A. "
   "Robust determination of the fibre orientation distribution in diffusion MRI: "
   "Non-negativity constrained super-resolved spherical deconvolution. "
   "NeuroImage, 2007, 35, 1459-1472";

  ARGUMENTS
    + Argument ("dwi",
        "the input diffusion-weighted image.").type_image_in()
    + Argument ("response",
        "a text file containing the diffusion-weighted signal response function "
        "coefficients for a single fibre population, ").type_file_in()
    + Argument ("SH",
        "the output spherical harmonics coefficients image.").type_image_out();

  OPTIONS
    + DWI::GradImportOptions()
    + DWI::ShellOption
    + DWI::CSD_options
    + Image::Stride::StrideOption;
}

typedef float value_type;
typedef double cost_value_type;
typedef Image::BufferPreload<value_type> InputBufferType;
typedef Image::Buffer<value_type> OutputBufferType;
typedef Image::Buffer<bool> MaskBufferType;

class Processor
{
  public:
    Processor (InputBufferType::voxel_type& DWI_vox,
        OutputBufferType::voxel_type& FOD_vox,
        copy_ptr<MaskBufferType::voxel_type>& mask_vox,
        const DWI::CSDeconv<value_type>::Shared& shared) :
      dwi (DWI_vox),
      fod (FOD_vox),
      mask (mask_vox),
      sdeconv (shared),
      data (shared.dwis.size()) {
        if (mask)
          Image::check_dimensions (*mask, dwi, 0, 3);
      }

    void operator () (const Image::Iterator& pos) {
      if (!load_data (pos))
        return;

      sdeconv.set (data);

      size_t n;
      for (n = 0; n < sdeconv.shared.niter; n++)
        if (sdeconv.iterate())
          break;

      if (n >= sdeconv.shared.niter)
        INFO ("voxel [ " + str (pos[0]) + " " + str (pos[1]) + " " + str (pos[2]) +
            " ] did not reach full convergence");

      write_back (pos);
    }

  private:
    InputBufferType::voxel_type dwi;
    OutputBufferType::voxel_type fod;
    copy_ptr<MaskBufferType::voxel_type> mask;
    DWI::CSDeconv<value_type> sdeconv;
    Math::Vector<value_type> data;

    bool load_data (const Image::Iterator& pos) {
      if (mask) {
        Image::voxel_assign (*mask, pos);
        if (!mask->value())
          return false;
      }

      Image::voxel_assign (dwi, pos);

      for (size_t n = 0; n < sdeconv.shared.dwis.size(); n++) {
        dwi[3] = sdeconv.shared.dwis[n];
        data[n] = dwi.value();
        if (!std::isfinite (data[n]))
          return false;
        if (data[n] < 0.0)
          data[n] = 0.0;
      }

      return true;
    }

    void write_back (const Image::Iterator& pos) {
      Image::voxel_assign (fod, pos);
      for (fod[3] = 0; fod[3] < fod.dim (3); ++fod[3])
        fod.value() = sdeconv.FOD() [fod[3]];
    }

};

void run ()
{
  InputBufferType dwi_buffer (argument[0], Image::Stride::contiguous_along_axis(3));

  copy_ptr<MaskBufferType> mask_data;
  copy_ptr<MaskBufferType::voxel_type> mask_vox;
  Options opt = get_options ("mask");
  if (opt.size()) {
    mask_data.reset (new MaskBufferType (opt[0][0]));
    mask_vox.reset (new MaskBufferType::voxel_type (*mask_data));
  }

  DWI::CSDeconv<value_type>::Shared shared (dwi_buffer);
  shared.parse_cmdline_options();
  shared.set_response (argument[1]);
  shared.init();

  Image::Header header (dwi_buffer);
  header.dim(3) = shared.nSH();
  header.datatype() = DataType::Float32;
  Image::Stride::set_from_command_line (header);
  OutputBufferType FOD_buffer (argument[2], header);

  auto dwi_vox = dwi_buffer.voxel();
  auto FOD_vox = FOD_buffer.voxel();

  Processor processor (dwi_vox, FOD_vox, mask_vox, shared);
  Image::ThreadedLoop loop ("performing constrained spherical deconvolution...", dwi_vox, 0, 3);
  loop.run (processor);
}

<commit_msg>Small fix to dwi2fod to ensure non-masks voxel are initalised to zero<commit_after>#include "command.h"
#include "memory.h"
#include "progressbar.h"
#include "image/threaded_loop.h"
#include "image/buffer.h"
#include "image/buffer_preload.h"
#include "image/voxel.h"
#include "dwi/gradient.h"
#include "dwi/shells.h"
#include "dwi/sdeconv/constrained.h"

using namespace MR;
using namespace App;

void usage ()
{
  DESCRIPTION
    + "perform non-negativity constrained spherical deconvolution."

    + "Note that this program makes use of implied symmetries in the diffusion "
    "profile. First, the fact the signal attenuation profile is real implies "
    "that it has conjugate symmetry, i.e. Y(l,-m) = Y(l,m)* (where * denotes "
    "the complex conjugate). Second, the diffusion profile should be "
    "antipodally symmetric (i.e. S(x) = S(-x)), implying that all odd l "
    "components should be zero. Therefore, this program only computes the even "
    "elements."

    + "Note that the spherical harmonics equations used here differ slightly "
    "from those conventionally used, in that the (-1)^m factor has been "
    "omitted. This should be taken into account in all subsequent calculations."

    + Math::SH::encoding_description;

  REFERENCES
   + "Tournier, J.-D.; Calamante, F. & Connelly, A. "
   "Robust determination of the fibre orientation distribution in diffusion MRI: "
   "Non-negativity constrained super-resolved spherical deconvolution. "
   "NeuroImage, 2007, 35, 1459-1472";

  ARGUMENTS
    + Argument ("dwi",
        "the input diffusion-weighted image.").type_image_in()
    + Argument ("response",
        "a text file containing the diffusion-weighted signal response function "
        "coefficients for a single fibre population, ").type_file_in()
    + Argument ("SH",
        "the output spherical harmonics coefficients image.").type_image_out();

  OPTIONS
    + DWI::GradImportOptions()
    + DWI::ShellOption
    + DWI::CSD_options
    + Image::Stride::StrideOption;
}

typedef float value_type;
typedef double cost_value_type;
typedef Image::BufferPreload<value_type> InputBufferType;
typedef Image::Buffer<value_type> OutputBufferType;
typedef Image::Buffer<bool> MaskBufferType;

class Processor
{
  public:
    Processor (InputBufferType::voxel_type& DWI_vox,
        OutputBufferType::voxel_type& FOD_vox,
        copy_ptr<MaskBufferType::voxel_type>& mask_vox,
        const DWI::CSDeconv<value_type>::Shared& shared) :
      dwi (DWI_vox),
      fod (FOD_vox),
      mask (mask_vox),
      sdeconv (shared),
      data (shared.dwis.size()) {
        if (mask)
          Image::check_dimensions (*mask, dwi, 0, 3);
      }

    void operator () (const Image::Iterator& pos) {
      if (!load_data (pos))
        return;

      sdeconv.set (data);

      size_t n;
      for (n = 0; n < sdeconv.shared.niter; n++)
        if (sdeconv.iterate())
          break;

      if (n >= sdeconv.shared.niter)
        INFO ("voxel [ " + str (pos[0]) + " " + str (pos[1]) + " " + str (pos[2]) +
            " ] did not reach full convergence");

      write_back (pos);
    }

  private:
    InputBufferType::voxel_type dwi;
    OutputBufferType::voxel_type fod;
    copy_ptr<MaskBufferType::voxel_type> mask;
    DWI::CSDeconv<value_type> sdeconv;
    Math::Vector<value_type> data;

    bool load_data (const Image::Iterator& pos) {
      if (mask) {
        Image::voxel_assign (*mask, pos);
        if (!mask->value()) {
          Image::voxel_assign (fod, pos);
          for (auto l = Image::Loop (3) (fod); l; ++l)
            fod.value() = 0.0;
          return false;
        }
      }

      Image::voxel_assign (dwi, pos);

      for (size_t n = 0; n < sdeconv.shared.dwis.size(); n++) {
        dwi[3] = sdeconv.shared.dwis[n];
        data[n] = dwi.value();
        if (!std::isfinite (data[n]))
          return false;
        if (data[n] < 0.0)
          data[n] = 0.0;
      }

      return true;
    }

    void write_back (const Image::Iterator& pos) {
      Image::voxel_assign (fod, pos);
      for (fod[3] = 0; fod[3] < fod.dim (3); ++fod[3])
        fod.value() = sdeconv.FOD() [fod[3]];
    }

};

void run ()
{
  InputBufferType dwi_buffer (argument[0], Image::Stride::contiguous_along_axis(3));

  copy_ptr<MaskBufferType> mask_data;
  copy_ptr<MaskBufferType::voxel_type> mask_vox;
  Options opt = get_options ("mask");
  if (opt.size()) {
    mask_data.reset (new MaskBufferType (opt[0][0]));
    mask_vox.reset (new MaskBufferType::voxel_type (*mask_data));
  }

  DWI::CSDeconv<value_type>::Shared shared (dwi_buffer);
  shared.parse_cmdline_options();
  shared.set_response (argument[1]);
  shared.init();

  Image::Header header (dwi_buffer);
  header.dim(3) = shared.nSH();
  header.datatype() = DataType::Float32;
  Image::Stride::set_from_command_line (header);
  OutputBufferType FOD_buffer (argument[2], header);

  auto dwi_vox = dwi_buffer.voxel();
  auto FOD_vox = FOD_buffer.voxel();

  Processor processor (dwi_vox, FOD_vox, mask_vox, shared);
  Image::ThreadedLoop loop ("performing constrained spherical deconvolution...", dwi_vox, 0, 3);
  loop.run (processor);
}

<|endoftext|>


<commit_before>//===-- ResetMachineFunctionPass.cpp - Reset Machine Function ----*- C++ -*-==//
//
//                     The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
/// \file
/// This file implements a pass that will conditionally reset a machine
/// function as if it was just created. This is used to provide a fallback
/// mechanism when GlobalISel fails, thus the condition for the reset to
/// happen is that the MachineFunction has the FailedISel property.
//===----------------------------------------------------------------------===//

#include "llvm/ADT/Statistic.h"
#include "llvm/CodeGen/MachineFunction.h"
#include "llvm/CodeGen/MachineFunctionPass.h"
#include "llvm/CodeGen/Passes.h"
#include "llvm/IR/DiagnosticInfo.h"
#include "llvm/Support/Debug.h"
using namespace llvm;

#define DEBUG_TYPE "reset-machine-function"

STATISTIC(NumFunctionsReset, "Number of functions reset");

namespace {
  class ResetMachineFunction : public MachineFunctionPass {
    /// Tells whether or not this pass should emit a fallback
    /// diagnostic when it resets a function.
    bool EmitFallbackDiag;
    /// Whether we should abort immediately instead of resetting the function.
    bool AbortOnFailedISel;

  public:
    static char ID; // Pass identification, replacement for typeid
    ResetMachineFunction(bool EmitFallbackDiag = false,
                         bool AbortOnFailedISel = false)
        : MachineFunctionPass(ID), EmitFallbackDiag(EmitFallbackDiag),
          AbortOnFailedISel(AbortOnFailedISel) {}

    StringRef getPassName() const override { return "ResetMachineFunction"; }

    bool runOnMachineFunction(MachineFunction &MF) override {
      if (MF.getProperties().hasProperty(
              MachineFunctionProperties::Property::FailedISel)) {
        if (AbortOnFailedISel)
          report_fatal_error("Instruction selection failed");
        DEBUG(dbgs() << "Reseting: " << MF.getName() << '\n');
        ++NumFunctionsReset;
        MF.reset();
        if (EmitFallbackDiag) {
          const Function &F = MF.getFunction();
          DiagnosticInfoISelFallback DiagFallback(F);
          F.getContext().diagnose(DiagFallback);
        }
        return true;
      }
      return false;
    }

  };
} // end anonymous namespace

char ResetMachineFunction::ID = 0;
INITIALIZE_PASS(ResetMachineFunction, DEBUG_TYPE,
                "reset machine function if ISel failed", false, false)

MachineFunctionPass *
llvm::createResetMachineFunctionPass(bool EmitFallbackDiag = false,
                                     bool AbortOnFailedISel = false) {
  return new ResetMachineFunction(EmitFallbackDiag, AbortOnFailedISel);
}
<commit_msg>Fix debug spelling in ResetMachineFunction pass.<commit_after>//===-- ResetMachineFunctionPass.cpp - Reset Machine Function ----*- C++ -*-==//
//
//                     The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
/// \file
/// This file implements a pass that will conditionally reset a machine
/// function as if it was just created. This is used to provide a fallback
/// mechanism when GlobalISel fails, thus the condition for the reset to
/// happen is that the MachineFunction has the FailedISel property.
//===----------------------------------------------------------------------===//

#include "llvm/ADT/Statistic.h"
#include "llvm/CodeGen/MachineFunction.h"
#include "llvm/CodeGen/MachineFunctionPass.h"
#include "llvm/CodeGen/Passes.h"
#include "llvm/IR/DiagnosticInfo.h"
#include "llvm/Support/Debug.h"
using namespace llvm;

#define DEBUG_TYPE "reset-machine-function"

STATISTIC(NumFunctionsReset, "Number of functions reset");

namespace {
  class ResetMachineFunction : public MachineFunctionPass {
    /// Tells whether or not this pass should emit a fallback
    /// diagnostic when it resets a function.
    bool EmitFallbackDiag;
    /// Whether we should abort immediately instead of resetting the function.
    bool AbortOnFailedISel;

  public:
    static char ID; // Pass identification, replacement for typeid
    ResetMachineFunction(bool EmitFallbackDiag = false,
                         bool AbortOnFailedISel = false)
        : MachineFunctionPass(ID), EmitFallbackDiag(EmitFallbackDiag),
          AbortOnFailedISel(AbortOnFailedISel) {}

    StringRef getPassName() const override { return "ResetMachineFunction"; }

    bool runOnMachineFunction(MachineFunction &MF) override {
      if (MF.getProperties().hasProperty(
              MachineFunctionProperties::Property::FailedISel)) {
        if (AbortOnFailedISel)
          report_fatal_error("Instruction selection failed");
        DEBUG(dbgs() << "Resetting: " << MF.getName() << '\n');
        ++NumFunctionsReset;
        MF.reset();
        if (EmitFallbackDiag) {
          const Function &F = MF.getFunction();
          DiagnosticInfoISelFallback DiagFallback(F);
          F.getContext().diagnose(DiagFallback);
        }
        return true;
      }
      return false;
    }

  };
} // end anonymous namespace

char ResetMachineFunction::ID = 0;
INITIALIZE_PASS(ResetMachineFunction, DEBUG_TYPE,
                "Reset machine function if ISel failed", false, false)

MachineFunctionPass *
llvm::createResetMachineFunctionPass(bool EmitFallbackDiag = false,
                                     bool AbortOnFailedISel = false) {
  return new ResetMachineFunction(EmitFallbackDiag, AbortOnFailedISel);
}
<|endoftext|>


<commit_before>// Copyright (2015) Gustav

#include "ride/projectsettingsdlg.h"

#include <wx/editlbox.h>
#include <wx/fontenum.h>
#include <wx/textdlg.h>

#include <string>

#include "ride/generated/ui.h"

#include "ride/resources/commonimages.h"

#include "ride/cargo.h"
#include "ride/enabledisable.h"
#include "ride/form.h"
#include "ride/mainwindow.h"
#include "ride/project.h"
#include "ride/wxutils.h"

class ProjectSettingsDlg : public ui::ProjectSettings {
 public:
  ProjectSettingsDlg(wxWindow* parent, MainWindow* mainwindow,
                     Project* project);

 protected:
  void OnApply(wxCommandEvent& event);
  void OnCancel(wxCommandEvent& event);
  void OnOk(wxCommandEvent& event);

 protected:
  bool Apply();
  void AllToGui(bool togui);
  void CargoToGui(bool togui);
  void EditorToGui(bool togui);
  void BuildToGui(bool togui);
  ride::BuildSetting* GetSelectedBuildSetting();

 protected:
  void OnlyAllowNumberChars(wxKeyEvent& event);
  void OnTabWdithChanged(wxCommandEvent& event);
  void OnEditorUseTabsClicked(wxCommandEvent& event);

  void OnBuildConfiguration(wxCommandEvent& event);
  void OnBuildConfigurationModify(wxCommandEvent& event);
  void OnBuildCheckbox(wxCommandEvent& event);
  void OnBuildText(wxCommandEvent& event);
  void OnBuildTargetHelp(wxCommandEvent& event);
  void OnBuildCustomArgHelp(wxCommandEvent& event);

  void OnBuildFeatureAdd(wxCommandEvent& event);
  void OnBuildFeatureEdit(wxCommandEvent& event);
  void OnBuildFeatureRemove(wxCommandEvent& event);
  void OnBuildFeatureUp(wxCommandEvent& event);
  void OnBuildFeatureDown(wxCommandEvent& event);

 protected:
  Cargo cargo_;

 private:
  MainWindow* main_window_;
  Project* project_;
  ride::Project project_backup_;
  bool allow_editor_to_gui_;
  bool allow_build_to_gui_;
};

void DoProjectSettingsDlg(wxWindow* parent, MainWindow* mainwindow,
                          Project* project) {
  ProjectSettingsDlg dlg(parent, mainwindow, project);
  dlg.ShowModal();
}

bool LoadCargoFile(const wxString& cargo_file, Cargo* cargo,
                   wxStaticText* error_display) {
  if (cargo_file.IsEmpty()) {
    error_display->SetLabelText("No project loaded");
    return false;
  }
  const auto result = cargo->Load(cargo_file);
  if (result.IsOk()) {
    error_display->SetLabelText("");
    return true;
  }

  error_display->SetLabelText(result.message());
  return false;
}

ProjectSettingsDlg::ProjectSettingsDlg(wxWindow* parent, MainWindow* mainwindow,
                                       Project* project)
    : ::ui::ProjectSettings(parent, wxID_ANY),
      main_window_(mainwindow),
      project_(project),
      project_backup_(project->project()),
      allow_editor_to_gui_(true),
      allow_build_to_gui_(true) {
  LoadCargoFile(project_->GetCargoFile(), &cargo_, uiCargoLoadError);

  AllToGui(true);

  // disable all cargo related gui as we can't save toml files yet
  EnableDisable(false) << uiCargoName << uiCargoVersion;
  // we can't select or scroll in disabled listboxes
  // so lets keep them enabled since we can't really do anything in them
  // << uiCargoAuthors
  // << uiCargoDependencies

  SetImageAndRemoveText(uiBuildConfigurationTargetHelp, wxART_HELP);
  SetImageAndRemoveText(uiBuildConfigurationCustomArgsHelp, wxART_TIP);
  SetImageAndRemoveText(uiBuildFeatureAdd, wxART_NEW);
  SetImageAndRemoveText(uiBuildFeatureRemove, wxART_DELETE);
  SetImageAndRemoveText(uiBuildFeatureEdit, image::edit_xpm);
  SetImageAndRemoveText(uiBuildFeatureUp, wxART_GO_UP);
  SetImageAndRemoveText(uiBuildFeatureDown, wxART_GO_DOWN);
}

void ProjectSettingsDlg::OnApply(wxCommandEvent& event) { Apply(); }

void ProjectSettingsDlg::OnCancel(wxCommandEvent& event) {
  project_->set_project(project_backup_);
  EditorToGui(true);
  EndModal(wxCANCEL);
}

void ProjectSettingsDlg::OnOk(wxCommandEvent& event) {
  if (Apply()) {
    EndModal(wxOK);
  }
}

void ProjectSettingsDlg::AllToGui(bool togui) {
  CargoToGui(togui);
  EditorToGui(togui);
  BuildToGui(togui);
}

//////////////////////////////////////////////////////////////////////////

bool ProjectSettingsDlg::Apply() {
  AllToGui(false);
  project_backup_ = project_->project();

  return true;
}

//////////////////////////////////////////////////////////////////////////

void ProjectSettingsDlg::CargoToGui(bool togui) {
  DIALOG_DATA(cargo_, name, uiCargoName, _Str);
  DIALOG_DATA(cargo_, version, uiCargoVersion, _Str);
  DIALOG_DATA(cargo_, authors, uiCargoAuthors, _Content);
  DIALOG_DATA(cargo_, dependencies, uiCargoDependencies, _Content);
  DIALOG_DATA(cargo_, features, uiCargoFeatures, _Content);
}

//////////////////////////////////////////////////////////////////////////

void ProjectSettingsDlg::EditorToGui(bool togui) {
  if (allow_editor_to_gui_ == false) return;
  allow_editor_to_gui_ = false;
  ride::Project& project = *project_->project_ptr();
  DIALOG_DATA(project, tabwidth, uiEditorTabWidth, _I32);
  DIALOG_DATA(project, usetabs, uiEditorUseTabs, );

  if (togui == false) {
    main_window_->ProjectSettingsHasChanged();
    main_window_->ProjectSettingsHasChanged();
  }
  allow_editor_to_gui_ = true;
}

void ProjectSettingsDlg::OnlyAllowNumberChars(wxKeyEvent& event) {
  ::OnlyAllowNumberChars(event);
}
void ProjectSettingsDlg::OnTabWdithChanged(wxCommandEvent& event) {
  EditorToGui(false);
}
void ProjectSettingsDlg::OnEditorUseTabsClicked(wxCommandEvent& event) {
  EditorToGui(false);
}

//////////////////////////////////////////////////////////////////////////

void ProjectSettingsDlg::OnBuildConfiguration(wxCommandEvent& event) {
  BuildToGui(true);
}

void ProjectSettingsDlg::OnBuildConfigurationModify(wxCommandEvent& event) {
  // todo
}

void ProjectSettingsDlg::OnBuildCheckbox(wxCommandEvent& event) {
  BuildToGui(false);
}

void ProjectSettingsDlg::OnBuildText(wxCommandEvent& event) {
  BuildToGui(false);
}

void ProjectSettingsDlg::OnBuildTargetHelp(wxCommandEvent& event) {
  ShowInfo(this, "this is a build target info", "info");
}

void ProjectSettingsDlg::OnBuildCustomArgHelp(wxCommandEvent& event) {
  ShowInfo(this, "this is a custom argument info", "info");
}

void ProjectSettingsDlg::BuildToGui(bool togui) {
  if (togui && static_cast<wxItemContainer*>(uiBuildConfiguration)->IsEmpty()) {
    for (int i = 0; i < project_->project().build_settings_size(); ++i) {
      ride::BuildSetting* bs =
          project_->project_ptr()->mutable_build_settings(i);
      uiBuildConfiguration->Append(bs->name().c_str(),
                                   reinterpret_cast<void*>(bs));
    }
  }

  ride::BuildSetting* setting_ptr = GetSelectedBuildSetting();
  EnableDisable(setting_ptr != NULL)
      << uiBuildConfigurationRelease << uiBuildConfigurationDefaultFeatures
      << uiBuildConfigurationVerbose << uiBuildConfigurationTarget
      << uiBuildConfigurationTargetHelp << uiBuildConfigurationCustomArgs
      << uiBuildConfigurationCustomArgsHelp << uiBuildFeatures
      << uiBuildFeatureAdd << uiBuildFeatureRemove << uiBuildFeatureUp
      << uiBuildFeatureDown << uiBuildFeatureEdit;

  if (setting_ptr == NULL) return;

  ride::BuildSetting& setting = *setting_ptr;

  DIALOG_DATA(setting, release, uiBuildConfigurationRelease, );
  DIALOG_DATA(setting, default_features, uiBuildConfigurationDefaultFeatures, );
  DIALOG_DATA(setting, verbose, uiBuildConfigurationVerbose, );

  DIALOG_DATA(setting, target, uiBuildConfigurationTarget, _Str);
  DIALOG_DATA(setting, custom_arguments, uiBuildConfigurationCustomArgs, _Str);

  if (togui) {
    int selection = uiBuildFeatures->GetSelection();
    uiBuildFeatures->Clear();
    for (int i = 0; i < setting.features_size(); ++i) {
      uiBuildFeatures->AppendString(setting.features(i));
    }
    if (setting.features_size() > 0) {
      uiBuildFeatures->SetSelection(selection);
    }
  }
}

ride::BuildSetting* ProjectSettingsDlg::GetSelectedBuildSetting() {
  const int selection = uiBuildConfiguration->GetSelection();
  const bool found = selection != wxNOT_FOUND;

  if (!found) return NULL;
  void* d = uiBuildConfiguration->GetClientData(selection);
  ride::BuildSetting* setting = reinterpret_cast<ride::BuildSetting*>(d);

  return setting;
}

void ProjectSettingsDlg::OnBuildFeatureAdd(wxCommandEvent& event) {
  ride::BuildSetting* build = GetSelectedBuildSetting();
  if (build == NULL) return;
  wxTextEntryDialog entry(this, "Feature name");
  if (entry.ShowModal() != wxID_OK) return;
  std::string* new_feature = build->add_features();
  *new_feature = entry.GetValue().c_str();
  BuildToGui(true);
}

void ProjectSettingsDlg::OnBuildFeatureEdit(wxCommandEvent& event) {
  ride::BuildSetting* build = GetSelectedBuildSetting();
  if (build == NULL) return;

  const int selection = uiBuildFeatures->GetSelection();
  if (selection == -1) return;

  wxTextEntryDialog entry(this, "New feature name");
  entry.SetValue(build->features(selection));
  if (entry.ShowModal() != wxID_OK) return;
  build->set_features(selection, entry.GetValue().c_str());
  BuildToGui(true);
}

void ProjectSettingsDlg::OnBuildFeatureRemove(wxCommandEvent& event) {
  ride::BuildSetting* build = GetSelectedBuildSetting();
  if (build == NULL) return;

  const int selection = uiBuildFeatures->GetSelection();
  if (selection == -1) return;

  build->mutable_features()->DeleteSubrange(selection, 1);

  // move back one
  int new_selection = selection - 1;
  // if there aren't a selection and there are more items, select the first one
  if (new_selection == -1 && build->features_size() > 0) new_selection = 0;
  uiBuildFeatures->SetSelection(new_selection);

  BuildToGui(true);
}

void ProjectSettingsDlg::OnBuildFeatureUp(wxCommandEvent& event) {
  event.Skip();
}

void ProjectSettingsDlg::OnBuildFeatureDown(wxCommandEvent& event) {
  event.Skip();
}
<commit_msg>added move featiue up and move feature down actions<commit_after>// Copyright (2015) Gustav

#include "ride/projectsettingsdlg.h"

#include <wx/editlbox.h>
#include <wx/fontenum.h>
#include <wx/textdlg.h>

#include <algorithm>
#include <string>

#include "ride/generated/ui.h"

#include "ride/resources/commonimages.h"

#include "ride/cargo.h"
#include "ride/enabledisable.h"
#include "ride/form.h"
#include "ride/mainwindow.h"
#include "ride/project.h"
#include "ride/wxutils.h"

class ProjectSettingsDlg : public ui::ProjectSettings {
 public:
  ProjectSettingsDlg(wxWindow* parent, MainWindow* mainwindow,
                     Project* project);

 protected:
  void OnApply(wxCommandEvent& event);
  void OnCancel(wxCommandEvent& event);
  void OnOk(wxCommandEvent& event);

 protected:
  bool Apply();
  void AllToGui(bool togui);
  void CargoToGui(bool togui);
  void EditorToGui(bool togui);
  void BuildToGui(bool togui);
  ride::BuildSetting* GetSelectedBuildSetting();

 protected:
  void OnlyAllowNumberChars(wxKeyEvent& event);
  void OnTabWdithChanged(wxCommandEvent& event);
  void OnEditorUseTabsClicked(wxCommandEvent& event);

  void OnBuildConfiguration(wxCommandEvent& event);
  void OnBuildConfigurationModify(wxCommandEvent& event);
  void OnBuildCheckbox(wxCommandEvent& event);
  void OnBuildText(wxCommandEvent& event);
  void OnBuildTargetHelp(wxCommandEvent& event);
  void OnBuildCustomArgHelp(wxCommandEvent& event);

  void OnBuildFeatureAdd(wxCommandEvent& event);
  void OnBuildFeatureEdit(wxCommandEvent& event);
  void OnBuildFeatureRemove(wxCommandEvent& event);
  void OnBuildFeatureUp(wxCommandEvent& event);
  void OnBuildFeatureDown(wxCommandEvent& event);

 protected:
  Cargo cargo_;

 private:
  MainWindow* main_window_;
  Project* project_;
  ride::Project project_backup_;
  bool allow_editor_to_gui_;
  bool allow_build_to_gui_;
};

void DoProjectSettingsDlg(wxWindow* parent, MainWindow* mainwindow,
                          Project* project) {
  ProjectSettingsDlg dlg(parent, mainwindow, project);
  dlg.ShowModal();
}

bool LoadCargoFile(const wxString& cargo_file, Cargo* cargo,
                   wxStaticText* error_display) {
  if (cargo_file.IsEmpty()) {
    error_display->SetLabelText("No project loaded");
    return false;
  }
  const auto result = cargo->Load(cargo_file);
  if (result.IsOk()) {
    error_display->SetLabelText("");
    return true;
  }

  error_display->SetLabelText(result.message());
  return false;
}

ProjectSettingsDlg::ProjectSettingsDlg(wxWindow* parent, MainWindow* mainwindow,
                                       Project* project)
    : ::ui::ProjectSettings(parent, wxID_ANY),
      main_window_(mainwindow),
      project_(project),
      project_backup_(project->project()),
      allow_editor_to_gui_(true),
      allow_build_to_gui_(true) {
  LoadCargoFile(project_->GetCargoFile(), &cargo_, uiCargoLoadError);

  AllToGui(true);

  // disable all cargo related gui as we can't save toml files yet
  EnableDisable(false) << uiCargoName << uiCargoVersion;
  // we can't select or scroll in disabled listboxes
  // so lets keep them enabled since we can't really do anything in them
  // << uiCargoAuthors
  // << uiCargoDependencies

  SetImageAndRemoveText(uiBuildConfigurationTargetHelp, wxART_HELP);
  SetImageAndRemoveText(uiBuildConfigurationCustomArgsHelp, wxART_TIP);
  SetImageAndRemoveText(uiBuildFeatureAdd, wxART_NEW);
  SetImageAndRemoveText(uiBuildFeatureRemove, wxART_DELETE);
  SetImageAndRemoveText(uiBuildFeatureEdit, image::edit_xpm);
  SetImageAndRemoveText(uiBuildFeatureUp, wxART_GO_UP);
  SetImageAndRemoveText(uiBuildFeatureDown, wxART_GO_DOWN);
}

void ProjectSettingsDlg::OnApply(wxCommandEvent& event) { Apply(); }

void ProjectSettingsDlg::OnCancel(wxCommandEvent& event) {
  project_->set_project(project_backup_);
  EditorToGui(true);
  EndModal(wxCANCEL);
}

void ProjectSettingsDlg::OnOk(wxCommandEvent& event) {
  if (Apply()) {
    EndModal(wxOK);
  }
}

void ProjectSettingsDlg::AllToGui(bool togui) {
  CargoToGui(togui);
  EditorToGui(togui);
  BuildToGui(togui);
}

//////////////////////////////////////////////////////////////////////////

bool ProjectSettingsDlg::Apply() {
  AllToGui(false);
  project_backup_ = project_->project();

  return true;
}

//////////////////////////////////////////////////////////////////////////

void ProjectSettingsDlg::CargoToGui(bool togui) {
  DIALOG_DATA(cargo_, name, uiCargoName, _Str);
  DIALOG_DATA(cargo_, version, uiCargoVersion, _Str);
  DIALOG_DATA(cargo_, authors, uiCargoAuthors, _Content);
  DIALOG_DATA(cargo_, dependencies, uiCargoDependencies, _Content);
  DIALOG_DATA(cargo_, features, uiCargoFeatures, _Content);
}

//////////////////////////////////////////////////////////////////////////

void ProjectSettingsDlg::EditorToGui(bool togui) {
  if (allow_editor_to_gui_ == false) return;
  allow_editor_to_gui_ = false;
  ride::Project& project = *project_->project_ptr();
  DIALOG_DATA(project, tabwidth, uiEditorTabWidth, _I32);
  DIALOG_DATA(project, usetabs, uiEditorUseTabs, );

  if (togui == false) {
    main_window_->ProjectSettingsHasChanged();
    main_window_->ProjectSettingsHasChanged();
  }
  allow_editor_to_gui_ = true;
}

void ProjectSettingsDlg::OnlyAllowNumberChars(wxKeyEvent& event) {
  ::OnlyAllowNumberChars(event);
}
void ProjectSettingsDlg::OnTabWdithChanged(wxCommandEvent& event) {
  EditorToGui(false);
}
void ProjectSettingsDlg::OnEditorUseTabsClicked(wxCommandEvent& event) {
  EditorToGui(false);
}

//////////////////////////////////////////////////////////////////////////

void ProjectSettingsDlg::OnBuildConfiguration(wxCommandEvent& event) {
  BuildToGui(true);
}

void ProjectSettingsDlg::OnBuildConfigurationModify(wxCommandEvent& event) {
  // todo
}

void ProjectSettingsDlg::OnBuildCheckbox(wxCommandEvent& event) {
  BuildToGui(false);
}

void ProjectSettingsDlg::OnBuildText(wxCommandEvent& event) {
  BuildToGui(false);
}

void ProjectSettingsDlg::OnBuildTargetHelp(wxCommandEvent& event) {
  ShowInfo(this, "this is a build target info", "info");
}

void ProjectSettingsDlg::OnBuildCustomArgHelp(wxCommandEvent& event) {
  ShowInfo(this, "this is a custom argument info", "info");
}

void ProjectSettingsDlg::BuildToGui(bool togui) {
  if (togui && static_cast<wxItemContainer*>(uiBuildConfiguration)->IsEmpty()) {
    for (int i = 0; i < project_->project().build_settings_size(); ++i) {
      ride::BuildSetting* bs =
          project_->project_ptr()->mutable_build_settings(i);
      uiBuildConfiguration->Append(bs->name().c_str(),
                                   reinterpret_cast<void*>(bs));
    }
  }

  ride::BuildSetting* setting_ptr = GetSelectedBuildSetting();
  EnableDisable(setting_ptr != NULL)
      << uiBuildConfigurationRelease << uiBuildConfigurationDefaultFeatures
      << uiBuildConfigurationVerbose << uiBuildConfigurationTarget
      << uiBuildConfigurationTargetHelp << uiBuildConfigurationCustomArgs
      << uiBuildConfigurationCustomArgsHelp << uiBuildFeatures
      << uiBuildFeatureAdd << uiBuildFeatureRemove << uiBuildFeatureUp
      << uiBuildFeatureDown << uiBuildFeatureEdit;

  if (setting_ptr == NULL) return;

  ride::BuildSetting& setting = *setting_ptr;

  DIALOG_DATA(setting, release, uiBuildConfigurationRelease, );
  DIALOG_DATA(setting, default_features, uiBuildConfigurationDefaultFeatures, );
  DIALOG_DATA(setting, verbose, uiBuildConfigurationVerbose, );

  DIALOG_DATA(setting, target, uiBuildConfigurationTarget, _Str);
  DIALOG_DATA(setting, custom_arguments, uiBuildConfigurationCustomArgs, _Str);

  if (togui) {
    int selection = uiBuildFeatures->GetSelection();
    uiBuildFeatures->Clear();
    for (int i = 0; i < setting.features_size(); ++i) {
      uiBuildFeatures->AppendString(setting.features(i));
    }
    if (setting.features_size() > 0) {
      uiBuildFeatures->SetSelection(selection);
    }
  }
}

ride::BuildSetting* ProjectSettingsDlg::GetSelectedBuildSetting() {
  const int selection = uiBuildConfiguration->GetSelection();
  const bool found = selection != wxNOT_FOUND;

  if (!found) return NULL;
  void* d = uiBuildConfiguration->GetClientData(selection);
  ride::BuildSetting* setting = reinterpret_cast<ride::BuildSetting*>(d);

  return setting;
}

void ProjectSettingsDlg::OnBuildFeatureAdd(wxCommandEvent& event) {
  ride::BuildSetting* build = GetSelectedBuildSetting();
  if (build == NULL) return;
  wxTextEntryDialog entry(this, "Feature name");
  if (entry.ShowModal() != wxID_OK) return;
  std::string* new_feature = build->add_features();
  *new_feature = entry.GetValue().c_str();
  BuildToGui(true);
}

void ProjectSettingsDlg::OnBuildFeatureEdit(wxCommandEvent& event) {
  ride::BuildSetting* build = GetSelectedBuildSetting();
  if (build == NULL) return;

  const int selection = uiBuildFeatures->GetSelection();
  if (selection == -1) return;

  wxTextEntryDialog entry(this, "New feature name");
  entry.SetValue(build->features(selection));
  if (entry.ShowModal() != wxID_OK) return;
  build->set_features(selection, entry.GetValue().c_str());
  BuildToGui(true);
}

void ProjectSettingsDlg::OnBuildFeatureRemove(wxCommandEvent& event) {
  ride::BuildSetting* build = GetSelectedBuildSetting();
  if (build == NULL) return;

  const int selection = uiBuildFeatures->GetSelection();
  if (selection == -1) return;

  build->mutable_features()->DeleteSubrange(selection, 1);

  // move back one
  int new_selection = selection - 1;
  // if there aren't a selection and there are more items, select the first one
  if (new_selection == -1 && build->features_size() > 0) new_selection = 0;
  uiBuildFeatures->SetSelection(new_selection);

  BuildToGui(true);
}

void ProjectSettingsDlg::OnBuildFeatureUp(wxCommandEvent& event) {
  ride::BuildSetting* build = GetSelectedBuildSetting();
  if (build == NULL) return;

  const int selection = uiBuildFeatures->GetSelection();
  if (selection == -1) return;

  const int next_index = selection - 1;
  if (next_index == -1) return;

  std::swap(*build->mutable_features(selection),
            *build->mutable_features(next_index));
  uiBuildFeatures->SetSelection(next_index);
  BuildToGui(true);
}

void ProjectSettingsDlg::OnBuildFeatureDown(wxCommandEvent& event) {
  ride::BuildSetting* build = GetSelectedBuildSetting();
  if (build == NULL) return;

  const int selection = uiBuildFeatures->GetSelection();
  if (selection == -1) return;

  const int next_index = selection + 1;
  if (next_index >= build->features_size()) return;

  std::swap(*build->mutable_features(selection),
            *build->mutable_features(next_index));
  uiBuildFeatures->SetSelection(next_index);
  BuildToGui(true);
}
<|endoftext|>


<commit_before>#include <curses.h>
#include <stdio.h>
#include "debugC.h"
#include "machine.h"

using namespace std;

debugC::debugC(machine* BFM){
	localMachine = BFM;
}

debugC::~debugC(){
	delete this;
}

void debugC::setupDebugger(){
	initscr();
	raw();
	noecho();
	start_color();
	curs_set(0);

	init_pair(1, COLOR_WHITE, COLOR_GREEN);
	attron(A_BOLD);

	printw("\t\t\tBr**nfuck Curses Debugger");

	stackWindow = subwin(stdscr, 18, 7, 1, 0);
	wborder(stackWindow, '|', '|', '-', '-', '|', '|', 'x', 'x');
	mvwprintw(stackWindow, 0, 1, "Stack");

	tapeWindow = subwin(stdscr, 5, 72, 1, 8);
	wborder(tapeWindow, '|', '|', '-', '-', 'x', 'x', 'x', 'x');
	mvwprintw(tapeWindow, 0, 2, "Tape");

	inputWindow = subwin(stdscr, 5, 20, 14, 8);
	wborder(inputWindow, '|', '|', '-', '-', 'x', 'x', 'x', 'x');
	mvwprintw(inputWindow, 0, 2, "Input");

	outputWindow = subwin(stdscr, 5, 20, 14, 29);
	wborder(outputWindow, '|', '|', '-', '-', 'x', 'x', 'x', 'x');
	mvwprintw(outputWindow, 0, 2, "Output");

	codeWindow = subwin(stdscr, 8, 72, 6, 8);
	wborder(codeWindow, '|', '|', '-', '-', 'x', 'x', 'x', 'x');
	mvwprintw(codeWindow, 0, 2, "Source code");
}

void debugC::tearDown(){
	endwin();
}

void debugC::redrawStackWindow(int stackHeight){
	//stack is only redrawn when it changes, don't waste time changing every iteration
	int top = localMachine->getStackTop();
	int* stack = localMachine->getStack();

	for(int y = 0; y < 16; y++){
		mvwprintw(stackWindow, 16-y, 1, "   ");
		if(y <= top){
			char* currentElement;
			sprintf(currentElement, "%i", stack[y]);
			mvwprintw(stackWindow, 16-y, 1, currentElement);
		}
	}

	wrefresh(stackWindow);
}

void debugC::redrawTapeWindow(){
	char* tmp = (char*)malloc(20);
	int n = 1;
	for(int i = 0; i < 17; i++){
		sprintf(tmp, "%d", localMachine->getTapeAt(i));

		if(i == localMachine->getDataPointer())
			wattron(tapeWindow, COLOR_PAIR(1) | A_BOLD);

		mvwprintw(tapeWindow, 2, n, tmp);
		wprintw(tapeWindow, "|");
		wattroff(tapeWindow, COLOR_PAIR(1));
		n+=4;
	}
	wrefresh(tapeWindow);
}

void debugC::redrawCodeWindow(){
	string sourceToDraw = localMachine->getSource();

	wmove(codeWindow, 1, 1); int n = 0, tmpY, tmpX;
	while(n < localMachine->getSource().length()){
		if(n == localMachine->getSourceIterator())
			wattron(codeWindow, COLOR_PAIR(1) | A_BOLD);
		waddch(codeWindow, sourceToDraw[n]);
		wattroff(codeWindow, COLOR_PAIR(1));

		//When moving to a new line, start at x=1 instead of 0
		getyx(codeWindow, tmpY, tmpX);
		if(tmpX == 0)
			wmove(codeWindow, tmpY, 1);
		n++;
	}

	wborder(codeWindow, '|', '|', '-', '-', 'x', 'x', 'x', 'x');
	mvwprintw(codeWindow, 0, 2, "Source code");
	wrefresh(codeWindow);
}

void debugC::redrawOutputWindow(){
	int returnedOutput = localMachine->NAO();
	char* output; sprintf(output, "%i", returnedOutput);
	mvwprintw(outputWindow, 1, 1, "   ");
	mvwprintw(outputWindow, 1, 1, output);
	wrefresh(outputWindow);
}

void debugC::updateScreen(){
	redrawCodeWindow();
	redrawTapeWindow();

	refresh();
}

void debugC::step(int mod){
	char retOperator = localMachine->processChar(mod);

	switch(retOperator){
		case '.':
			redrawOutputWindow();
			break;
	}
}

//begin debugger, create window with curses
void debugC::start(string source){
	setupDebugger();
	updateScreen();

	int stackHeight = -1;
	int input;
	while((input = getch()) != '!'){ //Exit debugger on !
		updateScreen();

		//need to start working on over/underflow protection/wrapping now that I think about it
		if(input == '>')
			step(1);
		if(input == '<')
			step(-1); //for the love of god this probably won't work for a while

		//Only update the stack window if it actually changes
		if(stackHeight != localMachine->getStackTop()){
			stackHeight = localMachine->getStackTop();
			redrawStackWindow(stackHeight);
		}
	}

	tearDown();
};
<commit_msg>working on output again. display updates are more in-sync with operations<commit_after>#include <curses.h>
#include <stdio.h>
#include "debugC.h"
#include "machine.h"

using namespace std;

debugC::debugC(machine* BFM){
	localMachine = BFM;
}

debugC::~debugC(){
	delete this;
}

void debugC::setupDebugger(){
	initscr();
	raw();
	noecho();
	start_color();
	curs_set(0);

	init_pair(1, COLOR_WHITE, COLOR_GREEN);
	attron(A_BOLD);

	printw("\t\t\tBr**nfuck Curses Debugger");

	stackWindow = subwin(stdscr, 18, 7, 1, 0);
	wborder(stackWindow, '|', '|', '-', '-', '|', '|', 'x', 'x');
	mvwprintw(stackWindow, 0, 1, "Stack");

	tapeWindow = subwin(stdscr, 5, 72, 1, 8);
	wborder(tapeWindow, '|', '|', '-', '-', 'x', 'x', 'x', 'x');
	mvwprintw(tapeWindow, 0, 2, "Tape");

	inputWindow = subwin(stdscr, 5, 20, 14, 8);
	wborder(inputWindow, '|', '|', '-', '-', 'x', 'x', 'x', 'x');
	mvwprintw(inputWindow, 0, 2, "Input");

	outputWindow = subwin(stdscr, 5, 20, 14, 29);
	wborder(outputWindow, '|', '|', '-', '-', 'x', 'x', 'x', 'x');
	mvwprintw(outputWindow, 0, 2, "Output");

	codeWindow = subwin(stdscr, 8, 72, 6, 8);
	wborder(codeWindow, '|', '|', '-', '-', 'x', 'x', 'x', 'x');
	mvwprintw(codeWindow, 0, 2, "Source code");
}

void debugC::tearDown(){
	endwin();
}

void debugC::redrawStackWindow(int stackHeight){
	//stack is only redrawn when it changes, don't waste time changing every iteration
	int top = localMachine->getStackTop();
	int* stack = localMachine->getStack();

	for(int y = 0; y < 16; y++){
		mvwprintw(stackWindow, 16-y, 1, "   ");
		if(y <= top){
			char* currentElement;
			sprintf(currentElement, "%i", stack[y]);
			mvwprintw(stackWindow, 16-y, 1, currentElement);
		}
	}

	wrefresh(stackWindow);
}

void debugC::redrawTapeWindow(){
	char* tmp = (char*)malloc(20);
	int n = 1;
	for(int i = 0; i < 17; i++){
		sprintf(tmp, "%d", localMachine->getTapeAt(i));

		if(i == localMachine->getDataPointer())
			wattron(tapeWindow, COLOR_PAIR(1) | A_BOLD);

		mvwprintw(tapeWindow, 2, n, tmp);
		wprintw(tapeWindow, "|");
		wattroff(tapeWindow, COLOR_PAIR(1));
		n+=4;
	}
	wrefresh(tapeWindow);
}

void debugC::redrawCodeWindow(){
	string sourceToDraw = localMachine->getSource();

	wmove(codeWindow, 1, 1); int n = 0, tmpY, tmpX;
	while(n < localMachine->getSource().length()){
		if(n == localMachine->getSourceIterator())
			wattron(codeWindow, COLOR_PAIR(1) | A_BOLD);
		waddch(codeWindow, sourceToDraw[n]);
		wattroff(codeWindow, COLOR_PAIR(1));

		//When moving to a new line, start at x=1 instead of 0
		getyx(codeWindow, tmpY, tmpX);
		if(tmpX == 0)
			wmove(codeWindow, tmpY, 1);
		n++;
	}

	wborder(codeWindow, '|', '|', '-', '-', 'x', 'x', 'x', 'x');
	mvwprintw(codeWindow, 0, 2, "Source code");
	wrefresh(codeWindow);
}

void debugC::redrawOutputWindow(){
	int returnedOutput = localMachine->NAO();
	char* output; sprintf(output, "%i", returnedOutput);
	mvwprintw(outputWindow, 1, 1, "   ");
	mvwprintw(outputWindow, 1, 1, output);
	wrefresh(outputWindow);
}

void debugC::updateScreen(){
	redrawCodeWindow();
	redrawTapeWindow();

	refresh();
}

void debugC::step(int mod){
	char retOperator = localMachine->processChar(mod);

	switch(retOperator){
		case '.':
			redrawOutputWindow();
			break;
	}
}

//begin debugger, create window with curses
void debugC::start(string source){
	setupDebugger();
	updateScreen();

	int stackHeight = -1;
	int input;
	while((input = getch()) != '!'){ //Exit debugger on !
		//need to start working on over/underflow protection/wrapping now that I think about it
		if(input == '>')
			step(1);
		if(input == '<')
			step(-1); //for the love of god this probably won't work for a while

		//Only update the stack window if it actually changes
		if(stackHeight != localMachine->getStackTop()){
			stackHeight = localMachine->getStackTop();
			redrawStackWindow(stackHeight);
		}
		updateScreen();
	}

	tearDown();
};
<|endoftext|>


<commit_before>/*
 *  Copyright (c) 2014 The WebRTC project authors. All Rights Reserved.
 *
 *  Use of this source code is governed by a BSD-style license
 *  that can be found in the LICENSE file in the root of the source
 *  tree. An additional intellectual property rights grant can be found
 *  in the file PATENTS.  All contributing project authors may
 *  be found in the AUTHORS file in the root of the source tree.
 */

#include "webrtc/modules/audio_coding/codecs/ilbc/interface/audio_encoder_ilbc.h"

#include <cstring>
#include <limits>
#include "webrtc/base/checks.h"
#include "webrtc/modules/audio_coding/codecs/ilbc/interface/ilbc.h"

namespace webrtc {

namespace {

const int kSampleRateHz = 8000;

}  // namespace

AudioEncoderIlbc::AudioEncoderIlbc(const Config& config)
    : payload_type_(config.payload_type),
      num_10ms_frames_per_packet_(config.frame_size_ms / 10),
      num_10ms_frames_buffered_(0) {
  CHECK(config.frame_size_ms == 20 || config.frame_size_ms == 30)
      << "Frame size must be 20 or 30 ms.";
  DCHECK_LE(kSampleRateHz / 100 * num_10ms_frames_per_packet_,
            kMaxSamplesPerPacket);
  CHECK_EQ(0, WebRtcIlbcfix_EncoderCreate(&encoder_));
  CHECK_EQ(0, WebRtcIlbcfix_EncoderInit(encoder_, config.frame_size_ms));
}

AudioEncoderIlbc::~AudioEncoderIlbc() {
  CHECK_EQ(0, WebRtcIlbcfix_EncoderFree(encoder_));
}

int AudioEncoderIlbc::sample_rate_hz() const {
  return kSampleRateHz;
}
int AudioEncoderIlbc::num_channels() const {
  return 1;
}
int AudioEncoderIlbc::Num10MsFramesInNextPacket() const {
  return num_10ms_frames_per_packet_;
}

bool AudioEncoderIlbc::EncodeInternal(uint32_t timestamp,
                                      const int16_t* audio,
                                      size_t max_encoded_bytes,
                                      uint8_t* encoded,
                                      size_t* encoded_bytes,
                                      EncodedInfo* info) {
  const size_t expected_output_len ATTRIBUTE_UNUSED =
      num_10ms_frames_per_packet_ == 2 ? 38 : 50;
  DCHECK_GE(max_encoded_bytes, expected_output_len);

  // Save timestamp if starting a new packet.
  if (num_10ms_frames_buffered_ == 0)
    first_timestamp_in_buffer_ = timestamp;

  // Buffer input.
  std::memcpy(input_buffer_ + kSampleRateHz / 100 * num_10ms_frames_buffered_,
              audio,
              kSampleRateHz / 100 * sizeof(audio[0]));

  // If we don't yet have enough buffered input for a whole packet, we're done
  // for now.
  if (++num_10ms_frames_buffered_ < num_10ms_frames_per_packet_) {
    *encoded_bytes = 0;
    return true;
  }

  // Encode buffered input.
  DCHECK_EQ(num_10ms_frames_buffered_, num_10ms_frames_per_packet_);
  num_10ms_frames_buffered_ = 0;
  const int output_len = WebRtcIlbcfix_Encode(
      encoder_,
      input_buffer_,
      kSampleRateHz / 100 * num_10ms_frames_per_packet_,
      encoded);
  if (output_len == -1)
    return false;  // Encoding error.
  DCHECK_EQ(output_len, static_cast<int>(expected_output_len));
  *encoded_bytes = output_len;
  info->encoded_timestamp = first_timestamp_in_buffer_;
  info->payload_type = payload_type_;
  return true;
}

}  // namespace webrtc
<commit_msg>ATTRIBUTE_UNUSED expanded to empty on MSVS, so be sure to use the variable.<commit_after>/*
 *  Copyright (c) 2014 The WebRTC project authors. All Rights Reserved.
 *
 *  Use of this source code is governed by a BSD-style license
 *  that can be found in the LICENSE file in the root of the source
 *  tree. An additional intellectual property rights grant can be found
 *  in the file PATENTS.  All contributing project authors may
 *  be found in the AUTHORS file in the root of the source tree.
 */

#include "webrtc/modules/audio_coding/codecs/ilbc/interface/audio_encoder_ilbc.h"

#include <cstring>
#include <limits>
#include "webrtc/base/checks.h"
#include "webrtc/modules/audio_coding/codecs/ilbc/interface/ilbc.h"

namespace webrtc {

namespace {

const int kSampleRateHz = 8000;

}  // namespace

AudioEncoderIlbc::AudioEncoderIlbc(const Config& config)
    : payload_type_(config.payload_type),
      num_10ms_frames_per_packet_(config.frame_size_ms / 10),
      num_10ms_frames_buffered_(0) {
  CHECK(config.frame_size_ms == 20 || config.frame_size_ms == 30)
      << "Frame size must be 20 or 30 ms.";
  DCHECK_LE(kSampleRateHz / 100 * num_10ms_frames_per_packet_,
            kMaxSamplesPerPacket);
  CHECK_EQ(0, WebRtcIlbcfix_EncoderCreate(&encoder_));
  CHECK_EQ(0, WebRtcIlbcfix_EncoderInit(encoder_, config.frame_size_ms));
}

AudioEncoderIlbc::~AudioEncoderIlbc() {
  CHECK_EQ(0, WebRtcIlbcfix_EncoderFree(encoder_));
}

int AudioEncoderIlbc::sample_rate_hz() const {
  return kSampleRateHz;
}
int AudioEncoderIlbc::num_channels() const {
  return 1;
}
int AudioEncoderIlbc::Num10MsFramesInNextPacket() const {
  return num_10ms_frames_per_packet_;
}

bool AudioEncoderIlbc::EncodeInternal(uint32_t timestamp,
                                      const int16_t* audio,
                                      size_t max_encoded_bytes,
                                      uint8_t* encoded,
                                      size_t* encoded_bytes,
                                      EncodedInfo* info) {
  const size_t expected_output_len =
      num_10ms_frames_per_packet_ == 2 ? 38 : 50;
  CHECK_GE(max_encoded_bytes, expected_output_len);

  // Save timestamp if starting a new packet.
  if (num_10ms_frames_buffered_ == 0)
    first_timestamp_in_buffer_ = timestamp;

  // Buffer input.
  std::memcpy(input_buffer_ + kSampleRateHz / 100 * num_10ms_frames_buffered_,
              audio,
              kSampleRateHz / 100 * sizeof(audio[0]));

  // If we don't yet have enough buffered input for a whole packet, we're done
  // for now.
  if (++num_10ms_frames_buffered_ < num_10ms_frames_per_packet_) {
    *encoded_bytes = 0;
    return true;
  }

  // Encode buffered input.
  DCHECK_EQ(num_10ms_frames_buffered_, num_10ms_frames_per_packet_);
  num_10ms_frames_buffered_ = 0;
  const int output_len = WebRtcIlbcfix_Encode(
      encoder_,
      input_buffer_,
      kSampleRateHz / 100 * num_10ms_frames_per_packet_,
      encoded);
  if (output_len == -1)
    return false;  // Encoding error.
  DCHECK_EQ(output_len, static_cast<int>(expected_output_len));
  *encoded_bytes = output_len;
  info->encoded_timestamp = first_timestamp_in_buffer_;
  info->payload_type = payload_type_;
  return true;
}

}  // namespace webrtc
<|endoftext|>


<commit_before>#include "pairwise_index.h"

using namespace Pairwise;

Index::Index(qint32 x, qint32 y):
   _x(x),
   _y(y)
{
   // make sure pairwise index is valid
   if ( x < 1 || y < 0 || x <= y )
   {
      E_MAKE_EXCEPTION(e);
      e.setTitle(QObject::tr("Gene Pair Index Error"));
      e.setDetails(QObject::tr("Cannot initialize pairwise index (%1, %2).").arg(x).arg(y));
      throw e;
   }
}

Index::Index(qint64 index):
   _x(1),
   _y(0)
{
   // make sure index is valid
   if ( index < 0 )
   {
      E_MAKE_EXCEPTION(e);
      e.setTitle(QObject::tr("Gene Pair Index Error"));
      e.setDetails(QObject::tr("Cannot initialize pairwise index from %1.").arg(index));
      throw e;
   }

   // compute pairwise index from scalar index
   qint64 pos {0};
   while ( pos <= index )
   {
      ++_x;
      pos = _x * (_x - 1) / 2;
   }

   --_x;
   pos = _x * (_x - 1) / 2;

   _y = index - pos;
}

qint64 Index::indent(qint8 cluster) const
{
   // make sure cluster given is valid
   if ( cluster < 0 || cluster >= MAX_CLUSTER_SIZE )
   {
      E_MAKE_EXCEPTION(e);
      e.setTitle(QObject::tr("Gene Pair Index Error"));
      e.setDetails(QObject::tr("Cluster %1 is outside limits.").arg(cluster));
      throw e;
   }

   // compute indent with given cluster and return it
   qint64 index {_x * (_x - 1) / 2 + _y};
   return index * MAX_CLUSTER_SIZE + cluster;
}

void Index::operator++()
{
   // increment gene y and check if it reaches gene x
   if ( ++_y >= _x )
   {
      // reset gene y to 0 and increment gene x
      _y = 0;
      ++_x;
   }
}

Index Index::operator++(int)
{
   // save index value, increment it, and return previous value
   Index ret {*this};
   ++(*this);
   return ret;
}
<commit_msg>Fixed integer overflow in Pairwise::Index::indent()<commit_after>#include "pairwise_index.h"

using namespace Pairwise;

Index::Index(qint32 x, qint32 y):
   _x(x),
   _y(y)
{
   // make sure pairwise index is valid
   if ( x < 1 || y < 0 || x <= y )
   {
      E_MAKE_EXCEPTION(e);
      e.setTitle(QObject::tr("Gene Pair Index Error"));
      e.setDetails(QObject::tr("Cannot initialize pairwise index (%1, %2).").arg(x).arg(y));
      throw e;
   }
}

Index::Index(qint64 index):
   _x(1),
   _y(0)
{
   // make sure index is valid
   if ( index < 0 )
   {
      E_MAKE_EXCEPTION(e);
      e.setTitle(QObject::tr("Gene Pair Index Error"));
      e.setDetails(QObject::tr("Cannot initialize pairwise index from %1.").arg(index));
      throw e;
   }

   // compute pairwise index from scalar index
   qint64 pos {0};
   while ( pos <= index )
   {
      ++_x;
      pos = _x * (_x - 1) / 2;
   }

   --_x;
   pos = _x * (_x - 1) / 2;

   _y = index - pos;
}

qint64 Index::indent(qint8 cluster) const
{
   // make sure cluster given is valid
   if ( cluster < 0 || cluster >= MAX_CLUSTER_SIZE )
   {
      E_MAKE_EXCEPTION(e);
      e.setTitle(QObject::tr("Gene Pair Index Error"));
      e.setDetails(QObject::tr("Cluster %1 is outside limits.").arg(cluster));
      throw e;
   }

   // compute indent with given cluster and return it
   qint64 index {(qint64)_x * (_x - 1) / 2 + _y};
   return index * MAX_CLUSTER_SIZE + cluster;
}

void Index::operator++()
{
   // increment gene y and check if it reaches gene x
   if ( ++_y >= _x )
   {
      // reset gene y to 0 and increment gene x
      _y = 0;
      ++_x;
   }
}

Index Index::operator++(int)
{
   // save index value, increment it, and return previous value
   Index ret {*this};
   ++(*this);
   return ret;
}
<|endoftext|>


<commit_before>/*
 * Copyright 2016 Google Inc.
 *
 * Use of this source code is governed by a BSD-style license that can be
 * found in the LICENSE file.
 */

#include "GrTextureProxy.h"
#include "GrTextureProxyPriv.h"

#include "GrContext.h"
#include "GrContextPriv.h"
#include "GrDeferredProxyUploader.h"
#include "GrProxyProvider.h"
#include "GrTexturePriv.h"

// Deferred version
GrTextureProxy::GrTextureProxy(const GrSurfaceDesc& srcDesc, SkBackingFit fit, SkBudgeted budgeted,
                               const void* srcData, size_t /*rowBytes*/, uint32_t flags)
        : INHERITED(srcDesc, fit, budgeted, flags)
        , fMipMapped(GrMipMapped::kNo)
        , fMipColorMode(SkDestinationSurfaceColorMode::kLegacy)
        , fProxyProvider(nullptr)
        , fDeferredUploader(nullptr) {
    SkASSERT(!srcData);  // currently handled in Make()
}

// Lazy-callback version
GrTextureProxy::GrTextureProxy(LazyInstantiateCallback&& callback, LazyInstantiationType lazyType,
                               const GrSurfaceDesc& desc, GrMipMapped mipMapped, SkBackingFit fit,
                               SkBudgeted budgeted, uint32_t flags)
        : INHERITED(std::move(callback), lazyType, desc, fit, budgeted, flags)
        , fMipMapped(mipMapped)
        , fMipColorMode(SkDestinationSurfaceColorMode::kLegacy)
        , fProxyProvider(nullptr)
        , fDeferredUploader(nullptr) {
}

// Wrapped version
GrTextureProxy::GrTextureProxy(sk_sp<GrSurface> surf, GrSurfaceOrigin origin)
        : INHERITED(std::move(surf), origin, SkBackingFit::kExact)
        , fMipMapped(fTarget->asTexture()->texturePriv().mipMapped())
        , fMipColorMode(fTarget->asTexture()->texturePriv().mipColorMode())
        , fProxyProvider(nullptr)
        , fDeferredUploader(nullptr) {
    if (fTarget->getUniqueKey().isValid()) {
        fProxyProvider = fTarget->asTexture()->getContext()->contextPriv().proxyProvider();
        fProxyProvider->adoptUniqueKeyFromSurface(this, fTarget);
    }
}

GrTextureProxy::~GrTextureProxy() {
    // Due to the order of cleanup the GrSurface this proxy may have wrapped may have gone away
    // at this point. Zero out the pointer so the cache invalidation code doesn't try to use it.
    fTarget = nullptr;
    if (fUniqueKey.isValid()) {
        fProxyProvider->processInvalidProxyUniqueKey(fUniqueKey, this, false);
    } else {
        SkASSERT(!fProxyProvider);
    }
}

bool GrTextureProxy::instantiate(GrResourceProvider* resourceProvider) {
    if (LazyState::kNot != this->lazyInstantiationState()) {
        return false;
    }
    if (!this->instantiateImpl(resourceProvider, 1, /* needsStencil = */ false,
                               kNone_GrSurfaceFlags, fMipMapped, fMipColorMode,
                               fUniqueKey.isValid() ? &fUniqueKey : nullptr)) {
        return false;
    }

    SkASSERT(!fTarget->asRenderTarget());
    SkASSERT(fTarget->asTexture());
    return true;
}

sk_sp<GrSurface> GrTextureProxy::createSurface(GrResourceProvider* resourceProvider) const {
    sk_sp<GrSurface> surface= this->createSurfaceImpl(resourceProvider, 1,
                                                      /* needsStencil = */ false,
                                                      kNone_GrSurfaceFlags,
                                                      fMipMapped, fMipColorMode);
    if (!surface) {
        return nullptr;
    }

    SkASSERT(!surface->asRenderTarget());
    SkASSERT(surface->asTexture());
    return surface;
}

void GrTextureProxyPriv::setDeferredUploader(std::unique_ptr<GrDeferredProxyUploader> uploader) {
    SkASSERT(!fTextureProxy->fDeferredUploader);
    fTextureProxy->fDeferredUploader = std::move(uploader);
}

void GrTextureProxyPriv::scheduleUpload(GrOpFlushState* flushState) {
    // The texture proxy's contents may already have been uploaded or instantiation may have failed
    if (fTextureProxy->fDeferredUploader && fTextureProxy->fTarget) {
        fTextureProxy->fDeferredUploader->scheduleUpload(flushState, fTextureProxy);
    }
}

void GrTextureProxyPriv::resetDeferredUploader() {
    SkASSERT(fTextureProxy->fDeferredUploader);
    fTextureProxy->fDeferredUploader.reset();
}

// This method parallels the highest_filter_mode functions in GrGLTexture & GrVkTexture.
GrSamplerState::Filter GrTextureProxy::highestFilterMode() const {
    if (fTarget) {
        return fTarget->asTexture()->texturePriv().highestFilterMode();
    }

    // In OpenGL, GR_GL_TEXTURE_RECTANGLE and GR_GL_TEXTURE_EXTERNAL (which have a highest filter
    // mode of bilerp) can only be created via wrapping.

    return GrSamplerState::Filter::kMipMap;
}

size_t GrTextureProxy::onUninstantiatedGpuMemorySize() const {
    return GrSurface::ComputeSize(this->config(), this->width(), this->height(), 1,
                                  this->mipMapped(), !this->priv().isExact());
}

void GrTextureProxy::setUniqueKey(GrProxyProvider* proxyProvider, const GrUniqueKey& key) {
    SkASSERT(key.isValid());
    SkASSERT(!fUniqueKey.isValid()); // proxies can only ever get one uniqueKey

    if (fTarget) {
        if (!fTarget->getUniqueKey().isValid()) {
            fTarget->resourcePriv().setUniqueKey(key);
        }
        SkASSERT(fTarget->getUniqueKey() == key);
    }

    fUniqueKey = key;
    fProxyProvider = proxyProvider;
}

void GrTextureProxy::clearUniqueKey() {
    fUniqueKey.reset();
    fProxyProvider = nullptr;
}

#ifdef SK_DEBUG
void GrTextureProxy::validateLazySurface(const GrSurface* surface) {
    SkASSERT(!surface->asRenderTarget());

    // Anything that is checked here should be duplicated in GrTextureRenderTargetProxy's version
    SkASSERT(surface->asTexture());
    SkASSERT(surface->asTexture()->texturePriv().mipMapped() == this->mipMapped());
}
#endif

<commit_msg>Fix assert in GrTextureProxy.cpp<commit_after>/*
 * Copyright 2016 Google Inc.
 *
 * Use of this source code is governed by a BSD-style license that can be
 * found in the LICENSE file.
 */

#include "GrTextureProxy.h"
#include "GrTextureProxyPriv.h"

#include "GrContext.h"
#include "GrContextPriv.h"
#include "GrDeferredProxyUploader.h"
#include "GrProxyProvider.h"
#include "GrTexturePriv.h"

// Deferred version
GrTextureProxy::GrTextureProxy(const GrSurfaceDesc& srcDesc, SkBackingFit fit, SkBudgeted budgeted,
                               const void* srcData, size_t /*rowBytes*/, uint32_t flags)
        : INHERITED(srcDesc, fit, budgeted, flags)
        , fMipMapped(GrMipMapped::kNo)
        , fMipColorMode(SkDestinationSurfaceColorMode::kLegacy)
        , fProxyProvider(nullptr)
        , fDeferredUploader(nullptr) {
    SkASSERT(!srcData);  // currently handled in Make()
}

// Lazy-callback version
GrTextureProxy::GrTextureProxy(LazyInstantiateCallback&& callback, LazyInstantiationType lazyType,
                               const GrSurfaceDesc& desc, GrMipMapped mipMapped, SkBackingFit fit,
                               SkBudgeted budgeted, uint32_t flags)
        : INHERITED(std::move(callback), lazyType, desc, fit, budgeted, flags)
        , fMipMapped(mipMapped)
        , fMipColorMode(SkDestinationSurfaceColorMode::kLegacy)
        , fProxyProvider(nullptr)
        , fDeferredUploader(nullptr) {
}

// Wrapped version
GrTextureProxy::GrTextureProxy(sk_sp<GrSurface> surf, GrSurfaceOrigin origin)
        : INHERITED(std::move(surf), origin, SkBackingFit::kExact)
        , fMipMapped(fTarget->asTexture()->texturePriv().mipMapped())
        , fMipColorMode(fTarget->asTexture()->texturePriv().mipColorMode())
        , fProxyProvider(nullptr)
        , fDeferredUploader(nullptr) {
    if (fTarget->getUniqueKey().isValid()) {
        fProxyProvider = fTarget->asTexture()->getContext()->contextPriv().proxyProvider();
        fProxyProvider->adoptUniqueKeyFromSurface(this, fTarget);
    }
}

GrTextureProxy::~GrTextureProxy() {
    // Due to the order of cleanup the GrSurface this proxy may have wrapped may have gone away
    // at this point. Zero out the pointer so the cache invalidation code doesn't try to use it.
    fTarget = nullptr;
    if (fUniqueKey.isValid()) {
        fProxyProvider->processInvalidProxyUniqueKey(fUniqueKey, this, false);
    } else {
        SkASSERT(!fProxyProvider);
    }
}

bool GrTextureProxy::instantiate(GrResourceProvider* resourceProvider) {
    if (LazyState::kNot != this->lazyInstantiationState()) {
        return false;
    }
    if (!this->instantiateImpl(resourceProvider, 1, /* needsStencil = */ false,
                               kNone_GrSurfaceFlags, fMipMapped, fMipColorMode,
                               fUniqueKey.isValid() ? &fUniqueKey : nullptr)) {
        return false;
    }

    SkASSERT(!fTarget->asRenderTarget());
    SkASSERT(fTarget->asTexture());
    return true;
}

sk_sp<GrSurface> GrTextureProxy::createSurface(GrResourceProvider* resourceProvider) const {
    sk_sp<GrSurface> surface= this->createSurfaceImpl(resourceProvider, 1,
                                                      /* needsStencil = */ false,
                                                      kNone_GrSurfaceFlags,
                                                      fMipMapped, fMipColorMode);
    if (!surface) {
        return nullptr;
    }

    SkASSERT(!surface->asRenderTarget());
    SkASSERT(surface->asTexture());
    return surface;
}

void GrTextureProxyPriv::setDeferredUploader(std::unique_ptr<GrDeferredProxyUploader> uploader) {
    SkASSERT(!fTextureProxy->fDeferredUploader);
    fTextureProxy->fDeferredUploader = std::move(uploader);
}

void GrTextureProxyPriv::scheduleUpload(GrOpFlushState* flushState) {
    // The texture proxy's contents may already have been uploaded or instantiation may have failed
    if (fTextureProxy->fDeferredUploader && fTextureProxy->fTarget) {
        fTextureProxy->fDeferredUploader->scheduleUpload(flushState, fTextureProxy);
    }
}

void GrTextureProxyPriv::resetDeferredUploader() {
    SkASSERT(fTextureProxy->fDeferredUploader);
    fTextureProxy->fDeferredUploader.reset();
}

// This method parallels the highest_filter_mode functions in GrGLTexture & GrVkTexture.
GrSamplerState::Filter GrTextureProxy::highestFilterMode() const {
    if (fTarget) {
        return fTarget->asTexture()->texturePriv().highestFilterMode();
    }

    // In OpenGL, GR_GL_TEXTURE_RECTANGLE and GR_GL_TEXTURE_EXTERNAL (which have a highest filter
    // mode of bilerp) can only be created via wrapping.

    return GrSamplerState::Filter::kMipMap;
}

size_t GrTextureProxy::onUninstantiatedGpuMemorySize() const {
    return GrSurface::ComputeSize(this->config(), this->width(), this->height(), 1,
                                  this->mipMapped(), !this->priv().isExact());
}

void GrTextureProxy::setUniqueKey(GrProxyProvider* proxyProvider, const GrUniqueKey& key) {
    SkASSERT(key.isValid());
    SkASSERT(!fUniqueKey.isValid()); // proxies can only ever get one uniqueKey

    if (fTarget) {
        if (!fTarget->getUniqueKey().isValid()) {
            fTarget->resourcePriv().setUniqueKey(key);
        }
        SkASSERT(fTarget->getUniqueKey() == key);
    }

    fUniqueKey = key;
    fProxyProvider = proxyProvider;
}

void GrTextureProxy::clearUniqueKey() {
    fUniqueKey.reset();
    fProxyProvider = nullptr;
}

#ifdef SK_DEBUG
void GrTextureProxy::validateLazySurface(const GrSurface* surface) {
    SkASSERT(!surface->asRenderTarget());

    // Anything that is checked here should be duplicated in GrTextureRenderTargetProxy's version
    SkASSERT(surface->asTexture());
    SkASSERT(GrMipMapped::kNo == this->mipMapped() ||
             GrMipMapped::kYes == surface->asTexture()->texturePriv().mipMapped());
}
#endif

<|endoftext|>


<commit_before>//
//  libavg - Media Playback Engine.
//  Copyright (C) 2003-2011 Ulrich von Zadow
//
//  This library is free software; you can redistribute it and/or
//  modify it under the terms of the GNU Lesser General Public
//  License as published by the Free Software Foundation; either
//  version 2 of the License, or (at your option) any later version.
//
//  This library is distributed in the hope that it will be useful,
//  but WITHOUT ANY WARRANTY; without even the implied warranty of
//  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
//  Lesser General Public License for more details.
//
//  You should have received a copy of the GNU Lesser General Public
//  License along with this library; if not, write to the Free Software
//  Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
//
//  Current versions can be found at www.libavg.de
//

#include "OGLShader.h"
#include "ShaderRegistry.h"

#include "../base/Logger.h"
#include "../base/Exception.h"
#include "../base/OSHelper.h"

#include "../graphics/VertexArray.h"

#include <iostream>
#include <sstream>

using namespace std;

namespace avg {

OGLShader::OGLShader(const string& sName, const string& sVertProgram,
        const string& sFragProgram, const string& sVertPrefix, const string& sFragPrefix)
    : m_sName(sName),
      m_sVertProgram(sVertProgram),
      m_sFragProgram(sFragProgram)
{
    m_hProgram = glproc::CreateProgram();
    if (sVertProgram == "") {
        m_hVertexShader = 0;
    } else {
        glproc::BindAttribLocation(m_hProgram, VertexArray::TEX_INDEX, "a_TexCoord");
        glproc::BindAttribLocation(m_hProgram, VertexArray::COLOR_INDEX, "a_Color");
        glproc::BindAttribLocation(m_hProgram, VertexArray::POS_INDEX, "a_Pos");
        m_hVertexShader = compileShader(GL_VERTEX_SHADER, sVertProgram, sVertPrefix);
        glproc::AttachShader(m_hProgram, m_hVertexShader);
    }
    m_hFragmentShader = compileShader(GL_FRAGMENT_SHADER, sFragProgram, sFragPrefix);

    glproc::AttachShader(m_hProgram, m_hFragmentShader);
    glproc::LinkProgram(m_hProgram);
    GLContext::checkError("OGLShader::OGLShader: glLinkProgram()");

    GLint bLinked;
    glproc::GetProgramiv(m_hProgram, GL_LINK_STATUS, &bLinked);
    if (!bLinked) {
        AVG_LOG_ERROR("Linking shader program '"+sName+"' failed. Aborting.");
        dumpInfoLog(m_hVertexShader, Logger::severity::ERROR);
        dumpInfoLog(m_hFragmentShader, Logger::severity::ERROR);
        dumpInfoLog(m_hProgram, Logger::severity::ERROR, true);
        exit(-1);
    } else {
        AVG_TRACE(Logger::category::SHADER, Logger::severity::INFO,
                "Linking shader program '"+sName+"'.");
        dumpInfoLog(m_hVertexShader, Logger::severity::INFO);
        dumpInfoLog(m_hFragmentShader, Logger::severity::INFO);
        dumpInfoLog(m_hProgram, Logger::severity::INFO, true);
    }
    m_pShaderRegistry = &*ShaderRegistry::get();
    if (m_hVertexShader) {
        m_pTransformParam = getParam<glm::mat4>("transform");
    }
}

OGLShader::~OGLShader()
{
}

bool isMountainLion()
{
#ifdef __APPLE__
    return getOSXMajorVersion() == 12;
#else
    return false;
#endif
}

void OGLShader::activate()
{
    // If we're running on OS X mountain lion, we need to disable shader activation
    // caching (See bug #355).
    OGLShaderPtr pCurShader = m_pShaderRegistry->getCurShader();
    if (isMountainLion() || !pCurShader || &*pCurShader != this) {
        glproc::UseProgram(m_hProgram);
        m_pShaderRegistry->setCurShader(m_sName);
        GLContext::checkError("OGLShader::activate: glUseProgram()");
    }
}

GLuint OGLShader::getProgram()
{
    return m_hProgram;
}

const std::string OGLShader::getName() const
{
    return m_sName;
}

void OGLShader::setTransform(const glm::mat4& transform)
{
    if (m_hVertexShader) {
        m_pTransformParam->set(transform);
    } else {
#ifdef AVG_ENABLE_EGL
        // No fixed-function vertex shader in gles
        AVG_ASSERT(false);
#else
        glLoadMatrixf(glm::value_ptr(transform));
#endif
    }
}

GLuint OGLShader::compileShader(GLenum shaderType, const std::string& sProgram,
        const std::string& sPrefix)
{
    const char * pProgramStrs[2];
    pProgramStrs[0] = sPrefix.c_str();
    pProgramStrs[1] = sProgram.c_str();
    GLuint hShader = glproc::CreateShader(shaderType);
    glproc::ShaderSource(hShader, 2, pProgramStrs, 0);
    glproc::CompileShader(hShader);
    GLContext::checkError("OGLShader::compileShader()");
    return hShader;
}

bool OGLShader::findParam(const std::string& sName, unsigned& pos)
{
    GLShaderParamPtr pParam;
    bool bFound = false;
    pos = 0;
    while (!bFound && pos<m_pParams.size() && m_pParams[pos]->getName() <= sName) {
        if (m_pParams[pos]->getName() == sName) {
            bFound = true;
        } else {
            ++pos;
        }
    }
    return bFound;
}

void OGLShader::dumpInfoLog(GLuint hObj, long level, bool bIsProgram)
{
    int infoLogLength;
    GLchar * pInfoLog;

    if (!hObj) {
        return;
    }

    if (bIsProgram) {
        glproc::GetProgramiv(hObj, GL_INFO_LOG_LENGTH, &infoLogLength);
    } else {
        glproc::GetShaderiv(hObj, GL_INFO_LOG_LENGTH, &infoLogLength);
    }
    GLContext::checkError("OGLShader::dumpInfoLog: glGetShaderiv()");
    if (infoLogLength > 1) {
        pInfoLog = (GLchar*)malloc(infoLogLength);
        int charsWritten;
        if (bIsProgram) {
            glproc::GetProgramInfoLog(hObj, infoLogLength, &charsWritten, pInfoLog);
        } else {
            glproc::GetShaderInfoLog(hObj, infoLogLength, &charsWritten, pInfoLog);
        }
        string sLog = removeATIInfoLogSpam(pInfoLog);
        GLContext::checkError("OGLShader::dumpInfoLog: glGetShaderInfoLog()");
        if (sLog.size() > 3) {
            AVG_TRACE(Logger::category::SHADER, level, sLog);
        }
        free(pInfoLog);
    }
}

string OGLShader::removeATIInfoLogSpam(const string& sOrigLog)
{
    istringstream stream(sOrigLog);
    string sLog;
    string sCurLine;
    while(getline(stream, sCurLine)) {
        bool bLineBroken = (sCurLine.find(
                "shader was successfully compiled to run on hardware.") != string::npos)
                || (sCurLine.find("shader(s) linked.") != string::npos);
        if (!bLineBroken) {
            sLog.append(sCurLine+"\n");
        }
    }
    return sLog;
}

}
<commit_msg>Removed workaround for mountain lion bug - OS/Driver bug seems to have been fixed.<commit_after>//
//  libavg - Media Playback Engine.
//  Copyright (C) 2003-2011 Ulrich von Zadow
//
//  This library is free software; you can redistribute it and/or
//  modify it under the terms of the GNU Lesser General Public
//  License as published by the Free Software Foundation; either
//  version 2 of the License, or (at your option) any later version.
//
//  This library is distributed in the hope that it will be useful,
//  but WITHOUT ANY WARRANTY; without even the implied warranty of
//  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
//  Lesser General Public License for more details.
//
//  You should have received a copy of the GNU Lesser General Public
//  License along with this library; if not, write to the Free Software
//  Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
//
//  Current versions can be found at www.libavg.de
//

#include "OGLShader.h"
#include "ShaderRegistry.h"

#include "../base/Logger.h"
#include "../base/Exception.h"
#include "../base/OSHelper.h"

#include "../graphics/VertexArray.h"

#include <iostream>
#include <sstream>

using namespace std;

namespace avg {

OGLShader::OGLShader(const string& sName, const string& sVertProgram,
        const string& sFragProgram, const string& sVertPrefix, const string& sFragPrefix)
    : m_sName(sName),
      m_sVertProgram(sVertProgram),
      m_sFragProgram(sFragProgram)
{
    m_hProgram = glproc::CreateProgram();
    if (sVertProgram == "") {
        m_hVertexShader = 0;
    } else {
        glproc::BindAttribLocation(m_hProgram, VertexArray::TEX_INDEX, "a_TexCoord");
        glproc::BindAttribLocation(m_hProgram, VertexArray::COLOR_INDEX, "a_Color");
        glproc::BindAttribLocation(m_hProgram, VertexArray::POS_INDEX, "a_Pos");
        m_hVertexShader = compileShader(GL_VERTEX_SHADER, sVertProgram, sVertPrefix);
        glproc::AttachShader(m_hProgram, m_hVertexShader);
    }
    m_hFragmentShader = compileShader(GL_FRAGMENT_SHADER, sFragProgram, sFragPrefix);

    glproc::AttachShader(m_hProgram, m_hFragmentShader);
    glproc::LinkProgram(m_hProgram);
    GLContext::checkError("OGLShader::OGLShader: glLinkProgram()");

    GLint bLinked;
    glproc::GetProgramiv(m_hProgram, GL_LINK_STATUS, &bLinked);
    if (!bLinked) {
        AVG_LOG_ERROR("Linking shader program '"+sName+"' failed. Aborting.");
        dumpInfoLog(m_hVertexShader, Logger::severity::ERROR);
        dumpInfoLog(m_hFragmentShader, Logger::severity::ERROR);
        dumpInfoLog(m_hProgram, Logger::severity::ERROR, true);
        exit(-1);
    } else {
        AVG_TRACE(Logger::category::SHADER, Logger::severity::INFO,
                "Linking shader program '"+sName+"'.");
        dumpInfoLog(m_hVertexShader, Logger::severity::INFO);
        dumpInfoLog(m_hFragmentShader, Logger::severity::INFO);
        dumpInfoLog(m_hProgram, Logger::severity::INFO, true);
    }
    m_pShaderRegistry = &*ShaderRegistry::get();
    if (m_hVertexShader) {
        m_pTransformParam = getParam<glm::mat4>("transform");
    }
}

OGLShader::~OGLShader()
{
}

void OGLShader::activate()
{
    OGLShaderPtr pCurShader = m_pShaderRegistry->getCurShader();
    if (!pCurShader || &*pCurShader != this) {
        glproc::UseProgram(m_hProgram);
        m_pShaderRegistry->setCurShader(m_sName);
        GLContext::checkError("OGLShader::activate: glUseProgram()");
    }
}

GLuint OGLShader::getProgram()
{
    return m_hProgram;
}

const std::string OGLShader::getName() const
{
    return m_sName;
}

void OGLShader::setTransform(const glm::mat4& transform)
{
    if (m_hVertexShader) {
        m_pTransformParam->set(transform);
    } else {
#ifdef AVG_ENABLE_EGL
        // No fixed-function vertex shader in gles
        AVG_ASSERT(false);
#else
        glLoadMatrixf(glm::value_ptr(transform));
#endif
    }
}

GLuint OGLShader::compileShader(GLenum shaderType, const std::string& sProgram,
        const std::string& sPrefix)
{
    const char * pProgramStrs[2];
    pProgramStrs[0] = sPrefix.c_str();
    pProgramStrs[1] = sProgram.c_str();
    GLuint hShader = glproc::CreateShader(shaderType);
    glproc::ShaderSource(hShader, 2, pProgramStrs, 0);
    glproc::CompileShader(hShader);
    GLContext::checkError("OGLShader::compileShader()");
    return hShader;
}

bool OGLShader::findParam(const std::string& sName, unsigned& pos)
{
    GLShaderParamPtr pParam;
    bool bFound = false;
    pos = 0;
    while (!bFound && pos<m_pParams.size() && m_pParams[pos]->getName() <= sName) {
        if (m_pParams[pos]->getName() == sName) {
            bFound = true;
        } else {
            ++pos;
        }
    }
    return bFound;
}

void OGLShader::dumpInfoLog(GLuint hObj, long level, bool bIsProgram)
{
    int infoLogLength;
    GLchar * pInfoLog;

    if (!hObj) {
        return;
    }

    if (bIsProgram) {
        glproc::GetProgramiv(hObj, GL_INFO_LOG_LENGTH, &infoLogLength);
    } else {
        glproc::GetShaderiv(hObj, GL_INFO_LOG_LENGTH, &infoLogLength);
    }
    GLContext::checkError("OGLShader::dumpInfoLog: glGetShaderiv()");
    if (infoLogLength > 1) {
        pInfoLog = (GLchar*)malloc(infoLogLength);
        int charsWritten;
        if (bIsProgram) {
            glproc::GetProgramInfoLog(hObj, infoLogLength, &charsWritten, pInfoLog);
        } else {
            glproc::GetShaderInfoLog(hObj, infoLogLength, &charsWritten, pInfoLog);
        }
        string sLog = removeATIInfoLogSpam(pInfoLog);
        GLContext::checkError("OGLShader::dumpInfoLog: glGetShaderInfoLog()");
        if (sLog.size() > 3) {
            AVG_TRACE(Logger::category::SHADER, level, sLog);
        }
        free(pInfoLog);
    }
}

string OGLShader::removeATIInfoLogSpam(const string& sOrigLog)
{
    istringstream stream(sOrigLog);
    string sLog;
    string sCurLine;
    while(getline(stream, sCurLine)) {
        bool bLineBroken = (sCurLine.find(
                "shader was successfully compiled to run on hardware.") != string::npos)
                || (sCurLine.find("shader(s) linked.") != string::npos);
        if (!bLineBroken) {
            sLog.append(sCurLine+"\n");
        }
    }
    return sLog;
}

}
<|endoftext|>