<commit_before>#include <tudocomp_driver/Registry.hpp>

#include <tudocomp/ChainCompressor.hpp>
#include <tudocomp/NoopCompressor.hpp>
#include <tudocomp/InnerNullCompressor.hpp>
#include <tudocomp/LiteralEncoder.hpp>

//compressors
#include <tudocomp/compressors/ESACompressor.hpp>
#include <tudocomp/compressors/LZ78Compressor.hpp>
#include <tudocomp/compressors/LZSSLCPCompressor.hpp>
#include <tudocomp/compressors/LZSSSlidingWindowCompressor.hpp>
#include <tudocomp/compressors/LZWCompressor.hpp>
#include <tudocomp/compressors/RePairCompressor.hpp>
#include <tudocomp/compressors/RunLengthEncoder.hpp>
#include <tudocomp/compressors/EasyRLECompressor.hpp>
#include <tudocomp/compressors/MTFCompressor.hpp>
#include <tudocomp/compressors/BWTCompressor.hpp>

//coders
#include <tudocomp/coders/ASCIICoder.hpp>
#include <tudocomp/coders/ByteCoder.hpp>
#include <tudocomp/coders/BitOptimalCoder.hpp>
#include <tudocomp/coders/Code2Coder.hpp>
#include <tudocomp/coders/VariantCoder.hpp>
#include <tudocomp/coders/HuffmanCoder.hpp>

namespace tdc_algorithms {

using namespace tdc;

void register_algorithms(Registry& r);

// One global instance for the registry
Registry REGISTRY = Registry::with_all_from(register_algorithms);

// All compression and encoding algorithms exposed by the command
// line interface.
void register_algorithms(Registry& r) {
    // Define which implementations to use for each combination.
    //
    // Because the tudocomp_driver has to select the algorithm
    // at runtime, we need to explicitly register all possible
    // template instances

    r.register_compressor<RePairCompressor<ASCIICoder>>();
    r.register_compressor<RePairCompressor<ByteCoder>>();
    r.register_compressor<RePairCompressor<BitOptimalCoder>>();
    r.register_compressor<RePairCompressor<HuffmanCoder>>();

    r.register_compressor<LiteralEncoder<ASCIICoder>>();
    r.register_compressor<LiteralEncoder<ByteCoder>>();
    r.register_compressor<LiteralEncoder<BitOptimalCoder>>();
    r.register_compressor<LiteralEncoder<Code2Coder>>();
    r.register_compressor<LiteralEncoder<HuffmanCoder>>();

    r.register_compressor<ESACompressor<esacomp::ESACompMaxLCP, ASCIICoder>>();
    r.register_compressor<ESACompressor<esacomp::ESACompMaxLCP, ByteCoder>>();
    r.register_compressor<ESACompressor<esacomp::ESACompMaxLCP, BitOptimalCoder>>();
    r.register_compressor<ESACompressor<esacomp::ESACompMaxLCP, Code2Coder>>();
    r.register_compressor<ESACompressor<esacomp::ESACompMaxLCP, HuffmanCoder>>();

    r.register_compressor<ESACompressor<esacomp::ESACompBulldozer, ASCIICoder>>();
    r.register_compressor<ESACompressor<esacomp::ESACompBulldozer, ByteCoder>>();
    r.register_compressor<ESACompressor<esacomp::ESACompBulldozer, BitOptimalCoder>>();
    r.register_compressor<ESACompressor<esacomp::ESACompBulldozer, HuffmanCoder>>();

    r.register_compressor<ESACompressor<esacomp::ESACompNaive, ASCIICoder>>();
    r.register_compressor<ESACompressor<esacomp::ESACompNaive, ByteCoder>>();
    r.register_compressor<ESACompressor<esacomp::ESACompNaive, BitOptimalCoder>>();
    r.register_compressor<ESACompressor<esacomp::ESACompNaive, HuffmanCoder>>();

    r.register_compressor<LZ78Compressor<ASCIICoder>>();
    r.register_compressor<LZ78Compressor<ByteCoder>>();
    r.register_compressor<LZ78Compressor<BitOptimalCoder>>();
    r.register_compressor<LZ78Compressor<HuffmanCoder>>();

    r.register_compressor<LZWCompressor<ASCIICoder>>();
    r.register_compressor<LZWCompressor<ByteCoder>>();
    r.register_compressor<LZWCompressor<BitOptimalCoder>>();
    r.register_compressor<LZWCompressor<HuffmanCoder>>();

    r.register_compressor<LZSSLCPCompressor<ASCIICoder>>();
    r.register_compressor<LZSSLCPCompressor<ByteCoder>>();
    r.register_compressor<LZSSLCPCompressor<BitOptimalCoder>>();
    r.register_compressor<LZSSLCPCompressor<HuffmanCoder>>();

    // [!] causes infinite loop in tdc::Registry::all_algorithms_with_static
    // r.register_compressor<LZSSLCPCompressor<VariantCoder<ASCIICoder, ByteCoder>>>();

    r.register_compressor<LZSSSlidingWindowCompressor<ASCIICoder>>();
    r.register_compressor<LZSSSlidingWindowCompressor<ByteCoder>>();
    r.register_compressor<LZSSSlidingWindowCompressor<BitOptimalCoder>>();
    r.register_compressor<LZSSSlidingWindowCompressor<HuffmanCoder>>();

    r.register_compressor<RunLengthEncoder<ASCIICoder>>();
    r.register_compressor<RunLengthEncoder<ByteCoder>>();
    r.register_compressor<RunLengthEncoder<BitOptimalCoder>>();
    r.register_compressor<RunLengthEncoder<HuffmanCoder>>();

    r.register_compressor< EasyRLECompressor>();
    r.register_compressor< MTFCompressor>();
    r.register_compressor< BWTCompressor>();

    r.register_compressor< ChainCompressor >();
    r.register_compressor< NoopCompressor >();
}

}
<commit_msg>Register code2 with compatible compressors<commit_after>#include <tudocomp_driver/Registry.hpp>

#include <tudocomp/ChainCompressor.hpp>
#include <tudocomp/NoopCompressor.hpp>
#include <tudocomp/InnerNullCompressor.hpp>
#include <tudocomp/LiteralEncoder.hpp>

//compressors
#include <tudocomp/compressors/ESACompressor.hpp>
#include <tudocomp/compressors/LZ78Compressor.hpp>
#include <tudocomp/compressors/LZSSLCPCompressor.hpp>
#include <tudocomp/compressors/LZSSSlidingWindowCompressor.hpp>
#include <tudocomp/compressors/LZWCompressor.hpp>
#include <tudocomp/compressors/RePairCompressor.hpp>
#include <tudocomp/compressors/RunLengthEncoder.hpp>
#include <tudocomp/compressors/EasyRLECompressor.hpp>
#include <tudocomp/compressors/MTFCompressor.hpp>
#include <tudocomp/compressors/BWTCompressor.hpp>

//coders
#include <tudocomp/coders/ASCIICoder.hpp>
#include <tudocomp/coders/ByteCoder.hpp>
#include <tudocomp/coders/BitOptimalCoder.hpp>
#include <tudocomp/coders/Code2Coder.hpp>
#include <tudocomp/coders/VariantCoder.hpp>
#include <tudocomp/coders/HuffmanCoder.hpp>

namespace tdc_algorithms {

using namespace tdc;

void register_algorithms(Registry& r);

// One global instance for the registry
Registry REGISTRY = Registry::with_all_from(register_algorithms);

// All compression and encoding algorithms exposed by the command
// line interface.
void register_algorithms(Registry& r) {
    // Define which implementations to use for each combination.
    //
    // Because the tudocomp_driver has to select the algorithm
    // at runtime, we need to explicitly register all possible
    // template instances

    r.register_compressor<RePairCompressor<ASCIICoder>>();
    r.register_compressor<RePairCompressor<ByteCoder>>();
    r.register_compressor<RePairCompressor<BitOptimalCoder>>();
    r.register_compressor<RePairCompressor<Code2Coder>>();
    r.register_compressor<RePairCompressor<HuffmanCoder>>();

    r.register_compressor<LiteralEncoder<ASCIICoder>>();
    r.register_compressor<LiteralEncoder<ByteCoder>>();
    r.register_compressor<LiteralEncoder<BitOptimalCoder>>();
    r.register_compressor<LiteralEncoder<Code2Coder>>();
    r.register_compressor<LiteralEncoder<HuffmanCoder>>();

    r.register_compressor<ESACompressor<esacomp::ESACompMaxLCP, ASCIICoder>>();
    r.register_compressor<ESACompressor<esacomp::ESACompMaxLCP, ByteCoder>>();
    r.register_compressor<ESACompressor<esacomp::ESACompMaxLCP, BitOptimalCoder>>();
    r.register_compressor<ESACompressor<esacomp::ESACompMaxLCP, Code2Coder>>();
    r.register_compressor<ESACompressor<esacomp::ESACompMaxLCP, HuffmanCoder>>();

    r.register_compressor<ESACompressor<esacomp::ESACompBulldozer, ASCIICoder>>();
    r.register_compressor<ESACompressor<esacomp::ESACompBulldozer, ByteCoder>>();
    r.register_compressor<ESACompressor<esacomp::ESACompBulldozer, BitOptimalCoder>>();
    r.register_compressor<ESACompressor<esacomp::ESACompBulldozer, Code2Coder>>();
    r.register_compressor<ESACompressor<esacomp::ESACompBulldozer, HuffmanCoder>>();

    r.register_compressor<ESACompressor<esacomp::ESACompNaive, ASCIICoder>>();
    r.register_compressor<ESACompressor<esacomp::ESACompNaive, ByteCoder>>();
    r.register_compressor<ESACompressor<esacomp::ESACompNaive, BitOptimalCoder>>();
    r.register_compressor<ESACompressor<esacomp::ESACompNaive, Code2Coder>>();
    r.register_compressor<ESACompressor<esacomp::ESACompNaive, HuffmanCoder>>();

    r.register_compressor<LZ78Compressor<ASCIICoder>>();
    r.register_compressor<LZ78Compressor<ByteCoder>>();
    r.register_compressor<LZ78Compressor<BitOptimalCoder>>();

    r.register_compressor<LZWCompressor<ASCIICoder>>();
    r.register_compressor<LZWCompressor<ByteCoder>>();
    r.register_compressor<LZWCompressor<BitOptimalCoder>>();

    r.register_compressor<LZSSLCPCompressor<ASCIICoder>>();
    r.register_compressor<LZSSLCPCompressor<ByteCoder>>();
    r.register_compressor<LZSSLCPCompressor<BitOptimalCoder>>();
    r.register_compressor<LZSSLCPCompressor<Code2Coder>>();
    r.register_compressor<LZSSLCPCompressor<HuffmanCoder>>();

    // [!] causes infinite loop in tdc::Registry::all_algorithms_with_static
    // r.register_compressor<LZSSLCPCompressor<VariantCoder<ASCIICoder, ByteCoder>>>();

    r.register_compressor<LZSSSlidingWindowCompressor<ASCIICoder>>();
    r.register_compressor<LZSSSlidingWindowCompressor<ByteCoder>>();
    r.register_compressor<LZSSSlidingWindowCompressor<BitOptimalCoder>>();

    r.register_compressor<RunLengthEncoder<ASCIICoder>>();
    r.register_compressor<RunLengthEncoder<ByteCoder>>();
    r.register_compressor<RunLengthEncoder<BitOptimalCoder>>();

    r.register_compressor< EasyRLECompressor>();
    r.register_compressor< MTFCompressor>();
    r.register_compressor< BWTCompressor>();

    r.register_compressor< ChainCompressor >();
    r.register_compressor< NoopCompressor >();
}

}
<|endoftext|>


<commit_before>// Copyright 2022 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//      http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
<commit_msg>Remove empty cwisstable.cc<commit_after><|endoftext|>


<commit_before>// Copyright (C) by Josh Blum. See LICENSE.txt for licensing information.

#ifndef INCLUDED_APOLOGY_WORKER_HPP
#define INCLUDED_APOLOGY_WORKER_HPP

#include <Apology/Config.hpp>
#include <Apology/Port.hpp>
#include <Theron/Actor.h>
#include <vector>

#ifdef _MSC_VER //remove some template export warnings
APOLOGY_EXTERN template class APOLOGY_API std::vector<Apology::Worker *>;
APOLOGY_EXTERN template class APOLOGY_API std::vector<std::vector<Apology::Port> >;
#endif

namespace Apology
{

/*!
 * A derived worker should register a message handler
 * for this message to get an update about topology.
 */
struct APOLOGY_API WorkerTopologyMessage
{
    //empty
};

/*!
 * A worker represents a unit of computation.
 * A worker contains an actor.
 * As part of being in a topology:
 * Arbitrary messages may be accepted from upstream ports
 * and arbitrary messages may be posted to downstream ports.
 */
struct APOLOGY_API Worker : Base
{
    //! Create a new worker
    Worker(void);

    //! Destroy the worker
    virtual ~Worker(void);

    //! Set the active actor
    void set_actor(Theron::Actor *actor);

    //! Get the active actor
    Theron::Actor *get_actor(void) const;

    //! Get the number of input ports
    size_t get_num_inputs(void) const;

    //! Get the number of output ports
    size_t get_num_outputs(void) const;

    /*!
     * Send a message to all downstream blocks on this output port.
     * \param index the output port index
     * \msg the message (must have index member)
     */
    template <typename Message>
    void post_downstream(const size_t index, const Message &msg) const;

    /*!
     * Send a message to all upstream blocks on this input port.
     * \param index the input port index
     * \msg the message (must have index member)
     */
    template <typename Message>
    void post_upstream(const size_t index, const Message &msg) const;

    std::vector<std::vector<Port> > _inputs;
    std::vector<std::vector<Port> > _outputs;
    Theron::Actor *_actor;
};

THERON_FORCEINLINE Theron::Actor *Worker::get_actor(void) const
{
    return _actor;
}

THERON_FORCEINLINE size_t Worker::get_num_inputs(void) const
{
    return _inputs.size();
}

THERON_FORCEINLINE size_t Worker::get_num_outputs(void) const
{
    return _outputs.size();
}

template <typename Message>
THERON_FORCEINLINE void Worker::post_downstream(const size_t index, const Message &msg) const
{
    Theron::Actor *actor = this->get_actor();
    Message message = msg;
    for (size_t i = 0; i < _outputs[index].size(); i++)
    {
        const Port &port = _outputs[index][i];
        message.index = port.index;
        Theron::Actor *dest = reinterpret_cast<Worker *>(port.elem)->get_actor();
        actor->GetFramework().Send(message, actor->GetAddress(), dest->GetAddress());
    }
}

template <typename Message>
THERON_FORCEINLINE void Worker::post_upstream(const size_t index, const Message &msg) const
{
    Theron::Actor *actor = this->get_actor();
    Message message = msg;
    for (size_t i = 0; i < _inputs[index].size(); i++)
    {
        const Port &port = _inputs[index][i];
        message.index = port.index;
        Theron::Actor *dest = reinterpret_cast<Worker *>(port.elem)->get_actor();
        actor->GetFramework().Send(message, actor->GetAddress(), dest->GetAddress());
    }
}

} //namespace Apology

#include <Theron/Register.h>

THERON_DECLARE_REGISTERED_MESSAGE(Apology::WorkerTopologyMessage);

#endif /*INCLUDED_APOLOGY_WORKER_HPP*/
<commit_msg>Apology: null addrs for posting from worker<commit_after>// Copyright (C) by Josh Blum. See LICENSE.txt for licensing information.

#ifndef INCLUDED_APOLOGY_WORKER_HPP
#define INCLUDED_APOLOGY_WORKER_HPP

#include <Apology/Config.hpp>
#include <Apology/Port.hpp>
#include <Theron/Actor.h>
#include <vector>

#ifdef _MSC_VER //remove some template export warnings
APOLOGY_EXTERN template class APOLOGY_API std::vector<Apology::Worker *>;
APOLOGY_EXTERN template class APOLOGY_API std::vector<std::vector<Apology::Port> >;
#endif

namespace Apology
{

/*!
 * A derived worker should register a message handler
 * for this message to get an update about topology.
 */
struct APOLOGY_API WorkerTopologyMessage
{
    //empty
};

/*!
 * A worker represents a unit of computation.
 * A worker contains an actor.
 * As part of being in a topology:
 * Arbitrary messages may be accepted from upstream ports
 * and arbitrary messages may be posted to downstream ports.
 */
struct APOLOGY_API Worker : Base
{
    //! Create a new worker
    Worker(void);

    //! Destroy the worker
    virtual ~Worker(void);

    //! Set the active actor
    void set_actor(Theron::Actor *actor);

    //! Get the active actor
    Theron::Actor *get_actor(void) const;

    //! Get the number of input ports
    size_t get_num_inputs(void) const;

    //! Get the number of output ports
    size_t get_num_outputs(void) const;

    /*!
     * Send a message to all downstream blocks on this output port.
     * \param index the output port index
     * \msg the message (must have index member)
     */
    template <typename Message>
    void post_downstream(const size_t index, const Message &msg) const;

    /*!
     * Send a message to all upstream blocks on this input port.
     * \param index the input port index
     * \msg the message (must have index member)
     */
    template <typename Message>
    void post_upstream(const size_t index, const Message &msg) const;

    std::vector<std::vector<Port> > _inputs;
    std::vector<std::vector<Port> > _outputs;
    Theron::Actor *_actor;
};

THERON_FORCEINLINE Theron::Actor *Worker::get_actor(void) const
{
    return _actor;
}

THERON_FORCEINLINE size_t Worker::get_num_inputs(void) const
{
    return _inputs.size();
}

THERON_FORCEINLINE size_t Worker::get_num_outputs(void) const
{
    return _outputs.size();
}

template <typename Message>
THERON_FORCEINLINE void Worker::post_downstream(const size_t index, const Message &msg) const
{
    Message message = msg;
    for (size_t i = 0; i < _outputs[index].size(); i++)
    {
        const Port &port = _outputs[index][i];
        message.index = port.index;
        Theron::Actor *actor = reinterpret_cast<Worker *>(port.elem)->get_actor();
        actor->GetFramework().Send(message, Theron::Address::Null(), actor->GetAddress());
    }
}

template <typename Message>
THERON_FORCEINLINE void Worker::post_upstream(const size_t index, const Message &msg) const
{
    Message message = msg;
    for (size_t i = 0; i < _inputs[index].size(); i++)
    {
        const Port &port = _inputs[index][i];
        message.index = port.index;
        Theron::Actor *actor = reinterpret_cast<Worker *>(port.elem)->get_actor();
        actor->GetFramework().Send(message, Theron::Address::Null(), actor->GetAddress());
    }
}

} //namespace Apology

#include <Theron/Register.h>

THERON_DECLARE_REGISTERED_MESSAGE(Apology::WorkerTopologyMessage);

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


<commit_before>#include "type.h"
#include "pt_data.h"
#include <iostream>
#include <boost/assign.hpp>
#include "utils/functions.h"

namespace navitia { namespace type {

bool ValidityPattern::is_valid(int duration) const {
    if(duration < 0){

        std::cerr << "La date est avant le début de période(" << beginning_date << ")" << std::endl;
        return false;
    }
    else if(duration > 366){
        std::cerr << "La date dépasse la fin de période " << duration << " " << std::endl;
        return false;
    }
    return true;
}

int ValidityPattern::slide(boost::gregorian::date day) const {
    return (day - beginning_date).days();
}

void ValidityPattern::add(boost::gregorian::date day){
    long duration = slide(day);
    add(duration);
}

void ValidityPattern::add(int duration){
    if(is_valid(duration))
        days[duration] = true;
}

void ValidityPattern::remove(boost::gregorian::date date){
    long duration = slide(date);
    remove(duration);
}

void ValidityPattern::remove(int day){
    if(is_valid(day))
        days[day] = false;
}

std::string ValidityPattern::str() const {
    return days.to_string();
}

bool ValidityPattern::check(boost::gregorian::date day) const {
    long duration = slide(day);
    return ValidityPattern::check(duration);
}

bool ValidityPattern::check(unsigned int day) const {
//    BOOST_ASSERT(is_valid(day));
    return days[day];
}

bool ValidityPattern::check2(unsigned int day) const {
//    BOOST_ASSERT(is_valid(day));
    if(day == 0)
        return days[day] || days[day+1];
    else
        return days[day-1] || days[day] || days[day+1];
}

bool ValidityPattern::uncheck2(unsigned int day) const {
//    BOOST_ASSERT(is_valid(day));
    if(day == 0)
        return !days[day] && !days[day+1];
    else
        return !days[day-1] && !days[day] && !days[day+1];
}

double GeographicalCoord::distance_to(const GeographicalCoord &other) const{
    static const double EARTH_RADIUS_IN_METERS = 6372797.560856;
    double longitudeArc = (this->lon() - other.lon()) * DEG_TO_RAD;
    double latitudeArc  = (this->lat() - other.lat()) * DEG_TO_RAD;
    double latitudeH = sin(latitudeArc * 0.5);
    latitudeH *= latitudeH;
    double lontitudeH = sin(longitudeArc * 0.5);
    lontitudeH *= lontitudeH;
    double tmp = cos(this->lat()*DEG_TO_RAD) * cos(other.lat()*DEG_TO_RAD);
    return EARTH_RADIUS_IN_METERS * 2.0 * asin(sqrt(latitudeH + tmp*lontitudeH));
}

bool operator==(const GeographicalCoord & a, const GeographicalCoord & b){
    return a.distance_to(b) < 0.1; // soit 0.1m
}

std::pair<GeographicalCoord, float> GeographicalCoord::project(GeographicalCoord segment_start, GeographicalCoord segment_end) const{
    std::pair<GeographicalCoord, float> result;

    double dlon = segment_end._lon - segment_start._lon;
    double dlat = segment_end._lat - segment_start._lat;
    double length = ::sqrt(dlon * dlon + dlat * dlat);
    double u;

    // On gère le cas où le segment est particulièrement court, et donc ça peut poser des problèmes (à cause de la division par length²)
    if(length < 1.0){ // moins de un, on projette sur une extrémité
        if(this->distance_to(segment_start) < this->distance_to(segment_end))
            u = 0;
        else
            u = 1;
    } else {
        u = ((this->_lon - segment_start._lon)*dlon + (this->_lat - segment_start._lat)*dlat )/
                (length * length);
    }

    // Les deux cas où le projeté tombe en dehors
    if(u < 0)
        result = std::make_pair(segment_start, this->distance_to(segment_start));
    else if(u > 1)
        result = std::make_pair(segment_end, this->distance_to(segment_end));
    else {
        result.first._lon = segment_start._lon + u * (segment_end._lon - segment_start._lon);
        result.first._lat = segment_start._lat + u * (segment_end._lat - segment_start._lat);
        result.second = this->distance_to(result.first);
    }

    pj_free(pj_dest);
    pj_free(pj_src);
    return GeographicalCoord(x, y);
}

std::ostream & operator<<(std::ostream & os, const GeographicalCoord & coord){
    os << coord.lon() << ";" << coord.lat();
    return os;
}

static_data * static_data::instance = 0;
static_data * static_data::get() {
    if (instance == 0) {
        static_data* temp = new static_data();

        boost::assign::insert(temp->types_string)
                (Type_e::eValidityPattern, "validity_pattern")
                (Type_e::eLine, "line")
                (Type_e::eRoute, "route")
                (Type_e::eVehicleJourney, "vehicle_journey")
                (Type_e::eStopPoint, "stop_point")
                (Type_e::eStopArea, "stop_area")
                (Type_e::eStopTime, "stop_time")
                (Type_e::eNetwork, "network")
                (Type_e::eMode, "mode")
                (Type_e::eModeType, "mode_type")
                (Type_e::eCity, "city")
                (Type_e::eConnection, "connection")
                (Type_e::eRoutePoint, "route_point")
                (Type_e::eDistrict, "district")
                (Type_e::eDepartment, "department")
                (Type_e::eCompany, "company")
                (Type_e::eVehicle, "vehicle")
                (Type_e::eCountry, "country")
                (Type_e::eWay, "way")
                (Type_e::eCoord, "coord")
                (Type_e::eAddress, "address");

        instance = temp;

    }
    return instance;
}

std::string static_data::getListNameByType(Type_e type){
    return instance->types_string.left.at(type) + "_list";
}

Type_e static_data::typeByCaption(const std::string & type_str) {
    return instance->types_string.right.at(type_str);
}

std::string static_data::captionByType(Type_e type){
    return instance->types_string.left.at(type);
}

std::vector<idx_t> Country::get(Type_e type, const PT_Data &)  const {
    std::vector<idx_t> result;
    switch(type) {
    case Type_e::eDistrict: return district_list; break;
    default: break;
    }
    return result;
}

std::vector<idx_t> City::get(Type_e type, const PT_Data &) const {
    std::vector<idx_t> result;
    switch(type) {
    case Type_e::eStopArea: return stop_area_list; break;
    case Type_e::eDepartment: result.push_back(department_idx); break;
    default: break;
    }
    return result;
}

std::vector<idx_t> StopArea::get(Type_e type, const PT_Data &) const {
    std::vector<idx_t> result;
    switch(type) {
    case Type_e::eStopPoint: return this->stop_point_list; break;
    case Type_e::eCity: result.push_back(city_idx); break;
    default: break;
    }
    return result;
}

std::vector<idx_t> Network::get(Type_e type, const PT_Data &) const {
    std::vector<idx_t> result;
    switch(type) {
    case Type_e::eLine: return line_list; break;
    default: break;
    }
    return result;
}

std::vector<idx_t> Company::get(Type_e type, const PT_Data &) const {
    std::vector<idx_t> result;
    switch(type) {
    case Type_e::eLine: return line_list; break;
    default: break;
    }
    return result;
}

std::vector<idx_t> ModeType::get(Type_e type, const PT_Data &) const {
    std::vector<idx_t> result;
    switch(type) {
    case Type_e::eLine: return line_list; break;
    case Type_e::eMode: return mode_list; break;
    default: break;
    }
    return result;
}

std::vector<idx_t> Mode::get(Type_e type, const PT_Data &) const {
    std::vector<idx_t> result;
    switch(type) {
    case Type_e::eModeType: result.push_back(mode_type_idx); break;
    default: break;
    }
    return result;
}

std::vector<idx_t> Line::get(Type_e type, const PT_Data & data) const {
    std::vector<idx_t> result;
    switch(type) {
    case Type_e::eModeType: result.push_back(mode_type_idx); break;
    case Type_e::eMode: return mode_list; break;
    case Type_e::eCompany: return company_list; break;
    case Type_e::eNetwork: result.push_back(network_idx); break;
    case Type_e::eRoute: for(const Route & route : data.routes) {
            if(route.line_idx == idx)
                result.push_back(route.idx);
        }
        break;
    default: break;
    }
    return result;
}

std::vector<idx_t> Route::get(Type_e type, const PT_Data &) const {
    std::vector<idx_t> result;
    switch(type) {
    case Type_e::eLine: result.push_back(line_idx); break;
    case Type_e::eModeType: result.push_back(mode_type_idx); break;
    case Type_e::eRoutePoint: return route_point_list; break;
    case Type_e::eVehicleJourney: return vehicle_journey_list; break;
    default: break;
    }
    return result;
}

std::vector<idx_t> VehicleJourney::get(Type_e type, const PT_Data &) const {
    std::vector<idx_t> result;
    switch(type) {
    case Type_e::eRoute: result.push_back(route_idx); break;
    case Type_e::eCompany: result.push_back(company_idx); break;
    case Type_e::eMode: result.push_back(mode_idx); break;
    case Type_e::eVehicle: result.push_back(vehicle_idx); break;
    case Type_e::eValidityPattern: result.push_back(validity_pattern_idx); break;
    default: break;
    }
    return result;
}

std::vector<idx_t> RoutePoint::get(Type_e type, const PT_Data &) const {
    std::vector<idx_t> result;
    switch(type) {
    case Type_e::eRoute: result.push_back(route_idx); break;
    case Type_e::eStopPoint: result.push_back(stop_point_idx); break;
    default: break;
    }
    return result;
}

std::vector<idx_t> StopPoint::get(Type_e type, const PT_Data &) const {
    std::vector<idx_t> result;
    switch(type) {
    case Type_e::eStopArea: result.push_back(stop_area_idx); break;
    case Type_e::eCity: result.push_back(city_idx); break;
    case Type_e::eMode: result.push_back(mode_idx); break;
    case Type_e::eNetwork: result.push_back(network_idx); break;
    case Type_e::eRoutePoint: return route_point_list; break;
    default: break;
    }
    return result;
}

EntryPoint::EntryPoint(const std::string &uri) : external_code(uri) {
       size_t pos = uri.find(":");
       if(pos == std::string::npos)
           type = Type_e::eUnknown;
       else {
           type = static_data::get()->typeByCaption(uri.substr(0,pos));
       }

       // Gestion des adresses
       if (type == Type_e::eAddress){
           std::vector<std::string> vect;
           vect = split_string(uri, ":");
           this->external_code = vect[0] + ":" + vect[1];
           this->house_number = str_to_int(vect[2]);
       }

       if(type == Type_e::eCoord){
           size_t pos2 = uri.find(":", pos+1);
           try{
               if(pos2 != std::string::npos) {
                   this->coordinates.set_lon(boost::lexical_cast<double>(uri.substr(pos+1, pos2 - pos - 1)));
                   this->coordinates.set_lat(boost::lexical_cast<double>(uri.substr(pos2+1)));
               }
           }catch(boost::bad_lexical_cast){
               this->coordinates.set_lon(0);
               this->coordinates.set_lat(0);
           }
       }
   }
}} //namespace navitia::type
<commit_msg>EntryPoint : évite le plantage si extcode invalide<commit_after>#include "type.h"
#include "pt_data.h"
#include <iostream>
#include <boost/assign.hpp>
#include "utils/functions.h"

namespace navitia { namespace type {

bool ValidityPattern::is_valid(int duration) const {
    if(duration < 0){

        std::cerr << "La date est avant le début de période(" << beginning_date << ")" << std::endl;
        return false;
    }
    else if(duration > 366){
        std::cerr << "La date dépasse la fin de période " << duration << " " << std::endl;
        return false;
    }
    return true;
}

int ValidityPattern::slide(boost::gregorian::date day) const {
    return (day - beginning_date).days();
}

void ValidityPattern::add(boost::gregorian::date day){
    long duration = slide(day);
    add(duration);
}

void ValidityPattern::add(int duration){
    if(is_valid(duration))
        days[duration] = true;
}

void ValidityPattern::remove(boost::gregorian::date date){
    long duration = slide(date);
    remove(duration);
}

void ValidityPattern::remove(int day){
    if(is_valid(day))
        days[day] = false;
}

std::string ValidityPattern::str() const {
    return days.to_string();
}

bool ValidityPattern::check(boost::gregorian::date day) const {
    long duration = slide(day);
    return ValidityPattern::check(duration);
}

bool ValidityPattern::check(unsigned int day) const {
//    BOOST_ASSERT(is_valid(day));
    return days[day];
}

bool ValidityPattern::check2(unsigned int day) const {
//    BOOST_ASSERT(is_valid(day));
    if(day == 0)
        return days[day] || days[day+1];
    else
        return days[day-1] || days[day] || days[day+1];
}

bool ValidityPattern::uncheck2(unsigned int day) const {
//    BOOST_ASSERT(is_valid(day));
    if(day == 0)
        return !days[day] && !days[day+1];
    else
        return !days[day-1] && !days[day] && !days[day+1];
}

double GeographicalCoord::distance_to(const GeographicalCoord &other) const{
    static const double EARTH_RADIUS_IN_METERS = 6372797.560856;
    double longitudeArc = (this->lon() - other.lon()) * DEG_TO_RAD;
    double latitudeArc  = (this->lat() - other.lat()) * DEG_TO_RAD;
    double latitudeH = sin(latitudeArc * 0.5);
    latitudeH *= latitudeH;
    double lontitudeH = sin(longitudeArc * 0.5);
    lontitudeH *= lontitudeH;
    double tmp = cos(this->lat()*DEG_TO_RAD) * cos(other.lat()*DEG_TO_RAD);
    return EARTH_RADIUS_IN_METERS * 2.0 * asin(sqrt(latitudeH + tmp*lontitudeH));
}

bool operator==(const GeographicalCoord & a, const GeographicalCoord & b){
    return a.distance_to(b) < 0.1; // soit 0.1m
}

std::pair<GeographicalCoord, float> GeographicalCoord::project(GeographicalCoord segment_start, GeographicalCoord segment_end) const{
    std::pair<GeographicalCoord, float> result;

    double dlon = segment_end._lon - segment_start._lon;
    double dlat = segment_end._lat - segment_start._lat;
    double length = ::sqrt(dlon * dlon + dlat * dlat);
    double u;

    // On gère le cas où le segment est particulièrement court, et donc ça peut poser des problèmes (à cause de la division par length²)
    if(length < 1.0){ // moins de un, on projette sur une extrémité
        if(this->distance_to(segment_start) < this->distance_to(segment_end))
            u = 0;
        else
            u = 1;
    } else {
        u = ((this->_lon - segment_start._lon)*dlon + (this->_lat - segment_start._lat)*dlat )/
                (length * length);
    }

    // Les deux cas où le projeté tombe en dehors
    if(u < 0)
        result = std::make_pair(segment_start, this->distance_to(segment_start));
    else if(u > 1)
        result = std::make_pair(segment_end, this->distance_to(segment_end));
    else {
        result.first._lon = segment_start._lon + u * (segment_end._lon - segment_start._lon);
        result.first._lat = segment_start._lat + u * (segment_end._lat - segment_start._lat);
        result.second = this->distance_to(result.first);
    }

    return result;
}

std::ostream & operator<<(std::ostream & os, const GeographicalCoord & coord){
    os << coord.lon() << ";" << coord.lat();
    return os;
}

static_data * static_data::instance = 0;
static_data * static_data::get() {
    if (instance == 0) {
        static_data* temp = new static_data();

        boost::assign::insert(temp->types_string)
                (Type_e::eValidityPattern, "validity_pattern")
                (Type_e::eLine, "line")
                (Type_e::eRoute, "route")
                (Type_e::eVehicleJourney, "vehicle_journey")
                (Type_e::eStopPoint, "stop_point")
                (Type_e::eStopArea, "stop_area")
                (Type_e::eStopTime, "stop_time")
                (Type_e::eNetwork, "network")
                (Type_e::eMode, "mode")
                (Type_e::eModeType, "mode_type")
                (Type_e::eCity, "city")
                (Type_e::eConnection, "connection")
                (Type_e::eRoutePoint, "route_point")
                (Type_e::eDistrict, "district")
                (Type_e::eDepartment, "department")
                (Type_e::eCompany, "company")
                (Type_e::eVehicle, "vehicle")
                (Type_e::eCountry, "country")
                (Type_e::eWay, "way")
                (Type_e::eCoord, "coord")
                (Type_e::eAddress, "address");

        instance = temp;

    }
    return instance;
}

std::string static_data::getListNameByType(Type_e type){
    return instance->types_string.left.at(type) + "_list";
}

Type_e static_data::typeByCaption(const std::string & type_str) {
    return instance->types_string.right.at(type_str);
}

std::string static_data::captionByType(Type_e type){
    return instance->types_string.left.at(type);
}

std::vector<idx_t> Country::get(Type_e type, const PT_Data &)  const {
    std::vector<idx_t> result;
    switch(type) {
    case Type_e::eDistrict: return district_list; break;
    default: break;
    }
    return result;
}

std::vector<idx_t> City::get(Type_e type, const PT_Data &) const {
    std::vector<idx_t> result;
    switch(type) {
    case Type_e::eStopArea: return stop_area_list; break;
    case Type_e::eDepartment: result.push_back(department_idx); break;
    default: break;
    }
    return result;
}

std::vector<idx_t> StopArea::get(Type_e type, const PT_Data &) const {
    std::vector<idx_t> result;
    switch(type) {
    case Type_e::eStopPoint: return this->stop_point_list; break;
    case Type_e::eCity: result.push_back(city_idx); break;
    default: break;
    }
    return result;
}

std::vector<idx_t> Network::get(Type_e type, const PT_Data &) const {
    std::vector<idx_t> result;
    switch(type) {
    case Type_e::eLine: return line_list; break;
    default: break;
    }
    return result;
}

std::vector<idx_t> Company::get(Type_e type, const PT_Data &) const {
    std::vector<idx_t> result;
    switch(type) {
    case Type_e::eLine: return line_list; break;
    default: break;
    }
    return result;
}

std::vector<idx_t> ModeType::get(Type_e type, const PT_Data &) const {
    std::vector<idx_t> result;
    switch(type) {
    case Type_e::eLine: return line_list; break;
    case Type_e::eMode: return mode_list; break;
    default: break;
    }
    return result;
}

std::vector<idx_t> Mode::get(Type_e type, const PT_Data &) const {
    std::vector<idx_t> result;
    switch(type) {
    case Type_e::eModeType: result.push_back(mode_type_idx); break;
    default: break;
    }
    return result;
}

std::vector<idx_t> Line::get(Type_e type, const PT_Data & data) const {
    std::vector<idx_t> result;
    switch(type) {
    case Type_e::eModeType: result.push_back(mode_type_idx); break;
    case Type_e::eMode: return mode_list; break;
    case Type_e::eCompany: return company_list; break;
    case Type_e::eNetwork: result.push_back(network_idx); break;
    case Type_e::eRoute: for(const Route & route : data.routes) {
            if(route.line_idx == idx)
                result.push_back(route.idx);
        }
        break;
    default: break;
    }
    return result;
}

std::vector<idx_t> Route::get(Type_e type, const PT_Data &) const {
    std::vector<idx_t> result;
    switch(type) {
    case Type_e::eLine: result.push_back(line_idx); break;
    case Type_e::eModeType: result.push_back(mode_type_idx); break;
    case Type_e::eRoutePoint: return route_point_list; break;
    case Type_e::eVehicleJourney: return vehicle_journey_list; break;
    default: break;
    }
    return result;
}

std::vector<idx_t> VehicleJourney::get(Type_e type, const PT_Data &) const {
    std::vector<idx_t> result;
    switch(type) {
    case Type_e::eRoute: result.push_back(route_idx); break;
    case Type_e::eCompany: result.push_back(company_idx); break;
    case Type_e::eMode: result.push_back(mode_idx); break;
    case Type_e::eVehicle: result.push_back(vehicle_idx); break;
    case Type_e::eValidityPattern: result.push_back(validity_pattern_idx); break;
    default: break;
    }
    return result;
}

std::vector<idx_t> RoutePoint::get(Type_e type, const PT_Data &) const {
    std::vector<idx_t> result;
    switch(type) {
    case Type_e::eRoute: result.push_back(route_idx); break;
    case Type_e::eStopPoint: result.push_back(stop_point_idx); break;
    default: break;
    }
    return result;
}

std::vector<idx_t> StopPoint::get(Type_e type, const PT_Data &) const {
    std::vector<idx_t> result;
    switch(type) {
    case Type_e::eStopArea: result.push_back(stop_area_idx); break;
    case Type_e::eCity: result.push_back(city_idx); break;
    case Type_e::eMode: result.push_back(mode_idx); break;
    case Type_e::eNetwork: result.push_back(network_idx); break;
    case Type_e::eRoutePoint: return route_point_list; break;
    default: break;
    }
    return result;
}

EntryPoint::EntryPoint(const std::string &uri) : external_code(uri) {
       size_t pos = uri.find(":");
       if(pos == std::string::npos)
           type = Type_e::eUnknown;
       else {
           type = static_data::get()->typeByCaption(uri.substr(0,pos));
       }

       // Gestion des adresses
       if (type == Type_e::eAddress){
           std::vector<std::string> vect;
           vect = split_string(uri, ":");
           if(vect.size() == 3){
               this->external_code = vect[0] + ":" + vect[1];
               this->house_number = str_to_int(vect[2]);
           }
       }

       if(type == Type_e::eCoord){
           size_t pos2 = uri.find(":", pos+1);
           try{
               if(pos2 != std::string::npos) {
                   this->coordinates.set_lon(boost::lexical_cast<double>(uri.substr(pos+1, pos2 - pos - 1)));
                   this->coordinates.set_lat(boost::lexical_cast<double>(uri.substr(pos2+1)));
               }
           }catch(boost::bad_lexical_cast){
               this->coordinates.set_lon(0);
               this->coordinates.set_lat(0);
           }
       }
   }
}} //namespace navitia::type
<|endoftext|>


<commit_before>#include <GL/glew.h>
#include <GL/glut.h>
#include <stdio.h>
#include <stdint.h>
#include <stdlib.h>
#include <unistd.h>

const char* vertexSource = "\
#version 130\r\n\
\r\n\
 \r\n\
in vec4 position;\r\n\
uniform vec2 windowSize;\r\n\
uniform vec2 plotCorner;\r\n\
 \r\n\
out vec2 plotCoord;\r\n\
 \r\n\
void main()                                                                             \r\n\
{                                                                                \r\n\
gl_Position = vec4((position.xy / windowSize)*vec2(2.0,-2.0)+vec2(-1.0,1.0), 0.0, 1.0); \r\n\
plotCoord = vec2(position.x - plotCorner.x, plotCorner.y - position.y);                 \r\n\
}                                                                                \r\n\
";

const char* fragmentSource = "\
#version 130\r\n\
#define M_PI 3.141596\r\n\
\r\n\
out vec4 fragColor;\r\n\
in  vec2 plotCoord;\r\n\
uniform sampler2D datass;\r\n\
\r\n\
void main()\r\n\
{\r\n\
    if (plotCoord.x < 0 || plotCoord.y < 0) {\
  fragColor = vec4(0.0, 0.0, 0.2, 1.0);\
} else {\
//fragColor = vec4(0.0, 1.0, 0.0, 0.0);\r\n\
fragColor = texture2D(datass, vec2(0.5, 0.5)); \r\n\
//    fragColor = texelFetch(datass, ivec2(1,1), 0);\r\n\
//vec4 texel = vec4(1.0, 0.0, 0.0, 0.0);\r\n\
  //  fragColor = vec4(sin(plotCoord.x*2.03*M_PI)/2.0+0.5, cos(plotCoord.y*2.03*M_PI)/2.0+0.5, 0.0, 1.0) * vec4(texel.rrr, 1.0);\r\n\
} \
}\r\n\
";

static int vs, fs, p;
static int uWindowSize;
static int uPlotCorner;
static int uData;
static GLuint texData;
static GLuint sampler;

static uint8_t datums[4096*4];

static void glCompileShaderWithCheck(int shader) {
  glCompileShader(shader);
  GLint status;
  glGetShaderiv(shader, GL_COMPILE_STATUS, &status);
  if (status == GL_TRUE) {
    printf("Compile successful.\r\n");
    return;
  }
  char buf[2000];
  GLsizei len;
  glGetShaderInfoLog(shader, 1999, &len, buf);
  printf("Compile failed:\r\n\r\n%s\r\n\r\n", buf);
  exit(1);
}

void setupShaders(void) {
  vs = glCreateShader(GL_VERTEX_SHADER);
  fs = glCreateShader(GL_FRAGMENT_SHADER);

  glShaderSource(vs, 1, &vertexSource, NULL);
  glShaderSource(fs, 1, &fragmentSource, NULL);

  glCompileShaderWithCheck(vs);
  glCompileShaderWithCheck(fs);

  p = glCreateProgram();
  glAttachShader(p, vs);
  glAttachShader(p, fs);
  glLinkProgram(p);
  glUseProgram(p);
  uWindowSize = glGetUniformLocation(p, "windowSize");
  uPlotCorner = glGetUniformLocation(p, "plotCorner");
  uData = glGetUniformLocation(p, "datass");

  glGenTextures(1, &texData);
  glGenSamplers(1, &sampler);

  int i;
  for (i=0; i < 4096*4; i++) {
    datums[i] = 0x7f;
  }
}

void displayMe(void) {
  int windowHeight = glutGet(GLUT_WINDOW_HEIGHT);
  int windowWidth = glutGet(GLUT_WINDOW_WIDTH);

  glGetError();

  glUniform2f(uWindowSize, windowWidth, windowHeight);
  glUniform2f(uPlotCorner, 50, windowHeight - 50);

  glBindTexture(GL_TEXTURE_2D, texData);
  glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, 32, 32, 0, GL_RGBA, GL_UNSIGNED_BYTE, datums);
  glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);
  glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);
  glBindTexture(GL_TEXTURE_2D, 0);

  glActiveTexture(GL_TEXTURE0);
  glBindTexture(GL_TEXTURE_2D, texData);
  glUniform1i(uData, 0);

  //glBindSampler(3, sampler) ;
  printf("Error: %d, btw %d\r\n", glGetError(), uData);

  // ------------------ onResize above

  glMatrixMode(GL_PROJECTION);
  glLoadIdentity();
  glOrtho(0.0f, windowWidth, windowHeight, 0.0f, -1.0f, 1.0f);

  glMatrixMode(GL_MODELVIEW);
  glLoadIdentity();
  glTranslatef(100.45, 100.45, 0);

  glClear(GL_COLOR_BUFFER_BIT);
  glBegin(GL_POLYGON);
  glVertex3f(0.0, 0.0, 0.0);
  glVertex3f(windowWidth, 0.0, 0.0);
  glVertex3f(windowWidth, windowHeight, 0.0);
  glVertex3f(0.0, windowHeight, 0.0);
  glEnd();
  glBegin(GL_POLYGON);
  //  glVertex3f(0.0, 0.0, 1.0);
  // glVertex3f(-0.9, 0.0, 1.0);
  //glVertex3f(-0.9, -0.9, 1.0);
  //glVertex3f(0.0, -0.9, 1.0);
  glEnd();
  glFlush();
  glutSwapBuffers();
}

int main(int argc, char** argv) {
  glutInit(&argc, argv);
    glutInitDisplayMode(GLUT_RGBA | GLUT_DOUBLE);
    glutInitWindowSize(1000, 700);
    glutInitWindowPosition(0, 0);
    glutCreateWindow("Teh awesomes");
  glewInit();

   if (glewIsSupported("GL_VERSION_3_3"))
        printf("Ready for OpenGL 3.3\n");
    else {
        printf("OpenGL 3.3 not supported\n");
        //exit(1);
    }
	if (GLEW_ARB_fragment_shader)
		printf("Ready for GLSL\n");
	else {
		printf("Not totally ready :( \n");
		exit(1);
	}

	if (glewIsSupported("GL_VERSION_2_0"))
		printf("Ready for OpenGL 2.0\n");
	else {
		printf("OpenGL 2.0 not supported\n");
		exit(1);
	}

    glutDisplayFunc(displayMe);
printf("%s\r\n", glGetString(GL_VENDOR));
printf("%s\r\n", glGetString(GL_RENDERER));
printf("%s\r\n", glGetString(GL_VERSION));
printf("%s\r\n", glGetString(GL_SHADING_LANGUAGE_VERSION));
  printf("%s\r\n", glGetString(GL_EXTENSIONS));

    usleep(50000);
    system("wmctrl -r :ACTIVE: -b add,maximized_vert,maximized_horz");

    setupShaders();

    glutMainLoop();
    return 0;
}

<commit_msg>Fix texture bug?<commit_after>#include <GL/glew.h>
#include <GL/glut.h>
#include <stdio.h>
#include <stdint.h>
#include <stdlib.h>
#include <unistd.h>

const char* vertexSource = "\
#version 130\r\n\
\r\n\
 \r\n\
in vec4 position;\r\n\
uniform vec2 windowSize;\r\n\
uniform vec2 plotCorner;\r\n\
 \r\n\
out vec2 plotCoord;\r\n\
 \r\n\
void main()                                                                             \r\n\
{                                                                                \r\n\
gl_Position = vec4((position.xy / windowSize)*vec2(2.0,-2.0)+vec2(-1.0,1.0), 0.0, 1.0); \r\n\
plotCoord = vec2(position.x - plotCorner.x, plotCorner.y - position.y);                 \r\n\
}                                                                                \r\n\
";

const char* fragmentSource = "\
#version 130\r\n\
#define M_PI 3.141596\r\n\
\r\n\
out vec4 fragColor;\r\n\
in  vec2 plotCoord;\r\n\
uniform sampler2D datass;\r\n\
\r\n\
void main()\r\n\
{\r\n\
    if (plotCoord.x < 0 || plotCoord.y < 0) {\
  fragColor = vec4(0.0, 0.0, 0.2, 1.0);\
} else {\
//fragColor = vec4(0.0, 1.0, 0.0, 0.0);\r\n\
fragColor = texture2D(datass, vec2(0.5, 0.5)); \r\n\
//    fragColor = texelFetch(datass, ivec2(1,1), 0);\r\n\
//vec4 texel = vec4(1.0, 0.0, 0.0, 0.0);\r\n\
  //  fragColor = vec4(sin(plotCoord.x*2.03*M_PI)/2.0+0.5, cos(plotCoord.y*2.03*M_PI)/2.0+0.5, 0.0, 1.0) * vec4(texel.rrr, 1.0);\r\n\
} \
}\r\n\
";

static int vs, fs, p;
static int uWindowSize;
static int uPlotCorner;
static int uData;
static GLuint texData;
static GLuint sampler;

static uint8_t datums[4096*4];

static void glCompileShaderWithCheck(int shader) {
  glCompileShader(shader);
  GLint status;
  glGetShaderiv(shader, GL_COMPILE_STATUS, &status);
  if (status == GL_TRUE) {
    printf("Compile successful.\r\n");
    return;
  }
  char buf[2000];
  GLsizei len;
  glGetShaderInfoLog(shader, 1999, &len, buf);
  printf("Compile failed:\r\n\r\n%s\r\n\r\n", buf);
  exit(1);
}

void setupShaders(void) {
  vs = glCreateShader(GL_VERTEX_SHADER);
  fs = glCreateShader(GL_FRAGMENT_SHADER);

  glShaderSource(vs, 1, &vertexSource, NULL);
  glShaderSource(fs, 1, &fragmentSource, NULL);

  glCompileShaderWithCheck(vs);
  glCompileShaderWithCheck(fs);

  p = glCreateProgram();
  glAttachShader(p, vs);
  glAttachShader(p, fs);
  glLinkProgram(p);
  glUseProgram(p);
  uWindowSize = glGetUniformLocation(p, "windowSize");
  uPlotCorner = glGetUniformLocation(p, "plotCorner");
  uData = glGetUniformLocation(p, "datass");

  glGenTextures(1, &texData);
  glGenSamplers(1, &sampler);

  int i;
  for (i=0; i < 4096*4; i++) {
    datums[i] = 0x7f;
  }
}

void displayMe(void) {
  int windowHeight = glutGet(GLUT_WINDOW_HEIGHT);
  int windowWidth = glutGet(GLUT_WINDOW_WIDTH);

  glGetError();

  glUniform2f(uWindowSize, windowWidth, windowHeight);
  glUniform2f(uPlotCorner, 50, windowHeight - 50);

  glBindTexture(GL_TEXTURE_2D, texData);
  glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, 32, 32, 0, GL_RGBA, GL_UNSIGNED_BYTE, datums);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
  glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);
  glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);
  glBindTexture(GL_TEXTURE_2D, 0);

  glActiveTexture(GL_TEXTURE0);
  glBindTexture(GL_TEXTURE_2D, texData);
  glUniform1i(uData, 0);

  //glBindSampler(3, sampler) ;
  printf("Error: %d, btw %d\r\n", glGetError(), uData);

  // ------------------ onResize above

  glMatrixMode(GL_PROJECTION);
  glLoadIdentity();
  glOrtho(0.0f, windowWidth, windowHeight, 0.0f, -1.0f, 1.0f);

  glMatrixMode(GL_MODELVIEW);
  glLoadIdentity();
  glTranslatef(100.45, 100.45, 0);

  glClear(GL_COLOR_BUFFER_BIT);
  glBegin(GL_POLYGON);
  glVertex3f(0.0, 0.0, 0.0);
  glVertex3f(windowWidth, 0.0, 0.0);
  glVertex3f(windowWidth, windowHeight, 0.0);
  glVertex3f(0.0, windowHeight, 0.0);
  glEnd();
  glBegin(GL_POLYGON);
  //  glVertex3f(0.0, 0.0, 1.0);
  // glVertex3f(-0.9, 0.0, 1.0);
  //glVertex3f(-0.9, -0.9, 1.0);
  //glVertex3f(0.0, -0.9, 1.0);
  glEnd();
  glFlush();
  glutSwapBuffers();
}

int main(int argc, char** argv) {
  glutInit(&argc, argv);
    glutInitDisplayMode(GLUT_RGBA | GLUT_DOUBLE);
    glutInitWindowSize(1000, 700);
    glutInitWindowPosition(0, 0);
    glutCreateWindow("Teh awesomes");
  glewInit();

   if (glewIsSupported("GL_VERSION_3_3"))
        printf("Ready for OpenGL 3.3\n");
    else {
        printf("OpenGL 3.3 not supported\n");
        //exit(1);
    }
	if (GLEW_ARB_fragment_shader)
		printf("Ready for GLSL\n");
	else {
		printf("Not totally ready :( \n");
		exit(1);
	}

	if (glewIsSupported("GL_VERSION_2_0"))
		printf("Ready for OpenGL 2.0\n");
	else {
		printf("OpenGL 2.0 not supported\n");
		exit(1);
	}

    glutDisplayFunc(displayMe);
printf("%s\r\n", glGetString(GL_VENDOR));
printf("%s\r\n", glGetString(GL_RENDERER));
printf("%s\r\n", glGetString(GL_VERSION));
printf("%s\r\n", glGetString(GL_SHADING_LANGUAGE_VERSION));
  printf("%s\r\n", glGetString(GL_EXTENSIONS));

    usleep(50000);
    system("wmctrl -r :ACTIVE: -b add,maximized_vert,maximized_horz");

    setupShaders();

    glutMainLoop();
    return 0;
}

<|endoftext|>


<commit_before>/** \file
 * File for the image resource.
 *
 * @author Nathan Samson
*/

#include <algorithm>
#include <sstream>

#include "SDL.h"
#include "SDL_image.h"
#include "SDL_rotozoom.h"

#include "resources/resourcemanager.h"
#include "resources/imageresource.h"

namespace Zabbr {

	/**
	 * Constructor.
	 *
	 * @param name The name of the image.
	 * @param surface The surface of the image.
	*/
	ImageResource::ImageResource(std::string name, SDL_Surface* surface)
	              : SDLSurfaceResource(name, surface) {
	}

	/**
	 * Destructor.
	*/
	ImageResource::~ImageResource() {
	}

	/**
	 * Opens an image.
	 *
	 * @param name the filename of the image.
	 *
	 * @throw ResourceNotLoadedException.
	*/
	ImageResource* ImageResource::open(std::string name) {
		SDL_Surface* temp;
		SDL_Surface* image;

		temp = IMG_Load((ResourceManager::fgDataPath+name).c_str());
		if (temp == 0) {
			throw ResourceNotLoadedException(name, IMG_GetError());
		}

		image = SDL_DisplayFormatAlpha(temp);
		SDL_FreeSurface(temp);
		return new ImageResource(createID(name), image);
	}

	/**
	 * Scale and rotate the image.
	 *
	 * @param w The maximum width of the new image.
	 * @param h The maximul height of the new image.
	 * @param keepRatio True if the result shoul be the same ratio as the original.
	 * @param angle The angle of the rotation (in degrees).
	*/
	ImageResource* ImageResource::scaleAndRotate(int w, int h, bool keepRatio, int angle) {
		SDL_Surface* surf;
		if (keepRatio) {
			surf = rotozoomSurface(fSurface, angle, std::min(w*1.0/fSurface->w, h*1.0/fSurface->h), SMOOTHING_ON);
		} else {
			SDL_Surface* t;
			t = zoomSurface(fSurface, w*1.0/fSurface->w, h*1.0/fSurface->h, SMOOTHING_ON);
			surf = rotozoomSurface(fSurface, angle, 1, SMOOTHING_ON);
			delete t;

		}
		return new ImageResource(createID(getName(), w, h, keepRatio, angle), surf);
	}

	/**
	 * Generates an ID for an Image resource.
	 *
	 * @param name The file name of the image.
	*/
	std::string ImageResource::createID(std::string name) {
		return name;
	}

	/**
	 * Generates an ID for an Image resource.
	 *
	 * @param name The ID of the original image
	 * @param w The width of the image.
	 * @param h The height of the image
	 * @param keepRatio value to keep the ratio.
	 * @param angle The angle of the rotation
	*/
	std::string ImageResource::createID(std::string name, int w, int h, bool keepRatio, int angle) {
		std::stringstream ssID;
		ssID  << "_" << w << "_"<< h;
		if (keepRatio) {
			ssID << "_KR";
		}
		ssID << "_" << angle;
		std::string id;
		ssID >> id;
		return name + id;
	}
}
<commit_msg>Fix image scaling with non-fixed resolution<commit_after>/** \file
 * File for the image resource.
 *
 * @author Nathan Samson
*/

#include <algorithm>
#include <sstream>

#include "SDL.h"
#include "SDL_image.h"
#include "SDL_rotozoom.h"

#include "resources/resourcemanager.h"
#include "resources/imageresource.h"

namespace Zabbr {

	/**
	 * Constructor.
	 *
	 * @param name The name of the image.
	 * @param surface The surface of the image.
	*/
	ImageResource::ImageResource(std::string name, SDL_Surface* surface)
	              : SDLSurfaceResource(name, surface) {
	}

	/**
	 * Destructor.
	*/
	ImageResource::~ImageResource() {
	}

	/**
	 * Opens an image.
	 *
	 * @param name the filename of the image.
	 *
	 * @throw ResourceNotLoadedException.
	*/
	ImageResource* ImageResource::open(std::string name) {
		SDL_Surface* temp;
		SDL_Surface* image;

		temp = IMG_Load((ResourceManager::fgDataPath+name).c_str());
		if (temp == 0) {
			throw ResourceNotLoadedException(name, IMG_GetError());
		}

		image = SDL_DisplayFormatAlpha(temp);
		SDL_FreeSurface(temp);
		return new ImageResource(createID(name), image);
	}

	/**
	 * Scale and rotate the image.
	 *
	 * @param w The maximum width of the new image.
	 * @param h The maximul height of the new image.
	 * @param keepRatio True if the result shoul be the same ratio as the original.
	 * @param angle The angle of the rotation (in degrees).
	*/
	ImageResource* ImageResource::scaleAndRotate(int w, int h, bool keepRatio, int angle) {
		SDL_Surface* surf;
		if (keepRatio) {
			surf = rotozoomSurface(fSurface, angle, std::min(w*1.0/fSurface->w, h*1.0/fSurface->h), SMOOTHING_ON);
		} else {
			SDL_Surface* t;
			t = zoomSurface(fSurface, w*1.0/fSurface->w, h*1.0/fSurface->h, SMOOTHING_ON);
			surf = rotozoomSurface(t, angle, 1, SMOOTHING_ON);
			SDL_FreeSurface(t);

		}
		return new ImageResource(createID(getName(), w, h, keepRatio, angle), surf);
	}

	/**
	 * Generates an ID for an Image resource.
	 *
	 * @param name The file name of the image.
	*/
	std::string ImageResource::createID(std::string name) {
		return name;
	}

	/**
	 * Generates an ID for an Image resource.
	 *
	 * @param name The ID of the original image
	 * @param w The width of the image.
	 * @param h The height of the image
	 * @param keepRatio value to keep the ratio.
	 * @param angle The angle of the rotation
	*/
	std::string ImageResource::createID(std::string name, int w, int h, bool keepRatio, int angle) {
		std::stringstream ssID;
		ssID  << "_" << w << "_"<< h;
		if (keepRatio) {
			ssID << "_KR";
		}
		ssID << "_" << angle;
		std::string id;
		ssID >> id;
		return name + id;
	}
}
<|endoftext|>


<commit_before><commit_msg>Bugfix (i'm an idiot)<commit_after><|endoftext|>


<commit_before>//    Copyright 2015 Christina Teflioudi
//
//    Licensed under the Apache License, Version 2.0 (the "License");
//    you may not use this file except in compliance with the License.
//    You may obtain a copy of the License at
//
//        http://www.apache.org/licenses/LICENSE-2.0
//
//    Unless required by applicable law or agreed to in writing, software
//    distributed under the License is distributed on an "AS IS" BASIS,
//    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
//    See the License for the specific language governing permissions and
//    limitations under the License.

#include <iostream>
#include <mips/mips.h>

#include <sys/time.h>
#include <fstream>
#include <climits>
#include <cmath>
#include <algorithm>

using namespace std;
using namespace mips;
using namespace rg;

// EXAMPLE OF LEMP
int main() {

    // first we have to define the input arguments for the algorithm
    InputArguments args;
//    args.theta = 0.035;//0.035; // theta for the Above-theta problem (will be used when running .runAboveTheta())
    args.k = 10; // k for the Row-Top-k problem (will be used when running .runTopK())
    args.threads = 1; // number of threads the algorithm will use for execution
    args.logFile = "../../results/log.txt"; // log file which will contain the timings

    // LEMP will also need some special arguments
    LEMP_Method method = LEMP_LI; // choose one of the methods LEMP provides (LEMP_X where X: L, LI, LC, I, C, TA, TREE, AP, LSH)
    int cacheSizeinKB = 2048; // specify your cache size per core (important since LEMP tries to optimize for cache utilization)
    double R = 0.60; // recall parameter for LEMP_LSH
    bool isTARR = true; // relevant for LEMP_TA (true will use ROUND ROBIN, false will use a MAX HEAP)
    double epsilon = 0.3; // epsilon value for LEMP_LI with absolute or relative approximation

    // we will need some input matrices for the algorithm (create them like (1), (2) or (3))
    VectorMatrix leftMatrix, rightMatrix;

    // (1) create a VectorMatrix by using .mma files
//    string queryFile = "../../dataset/w-gnmf-sample.mma";
//    string probeFile = "../../dataset/h-gnmf-sample.mma";
//    string queryFile = "/home/chteflio/chteflioInMPI/data/ta-data/w-50-gnmf-zero.mma";
//    string probeFile = "/home/chteflio/chteflioInMPI/data/ta-data/h-50-gnmf-zero.mma";
    string queryFile = "/home/chteflio/chteflioInMPI/data/ta-data/w50-net-noav.mma";
    string probeFile = "/home/chteflio/chteflioInMPI/data/ta-data/h50-net-noav.mma";

    leftMatrix.readFromFile(queryFile, 0,0, true);
    rightMatrix.readFromFile(probeFile, 0,0, false);

    // (2) create a VectorMatrix by using .csv files
//    int r = 50; // dimensionality of vectors
//    int m = 1000; // number of query-vectors
//    int n = 1000; // number of probe-vectors
//    string queryFile = "../../dataset/w-gnmf-sample.csv";
//    string probeFile = "../../dataset/h-gnmf-sample.csv";
//    leftMatrix.readFromFile(queryFile, r, m, true);
//    rightMatrix.readFromFile(probeFile, r, n, false);

    // (3) create a VectorMatrix by using several vectors of double values
//    std::vector<std::vector<double>> m(1); // a matrix containing only 1 vector
//    m[0].resize(50); // this vector will have dimensionality 50
//    std::iota(m[0].begin(), m[0].end(), 0); // we will just fill in some values as an example
//    VectorMatrix leftMatrixStreaming(m);

    // create an instance of the algorithm you wish to use
    mips::Lemp algo(args, cacheSizeinKB, method, isTARR, R, epsilon);

    // initialize the algorithm with a probe matrix (algorithm will store a copy of it inside)
    algo.initialize(rightMatrix);

    // create a structure for storing the results
    Results results;

    // decide between the Row-Top-k problem or the Above-theta problem
    if (args.k > 0) { // Row-Top-k

        // solves the Row-Top-k problem and stores the results in the specified results structure
        algo.runTopK(leftMatrix, results);

    } else { // Above-theta

        // solves the Above-theta problem and stores the results in the specified results structure
        algo.runAboveTheta(leftMatrix, results);

//        algo.setTheta(1.68); // we might also change the theta if we want so
//        algo.setMethod(LEMP_LSH); // we might also change the method if we want so
//        results.clear();
//
//        // we might also run another matrix which will append the results to the specified results structure (otherwise you will have to create another results instance)
//        algo.runAboveTheta(leftMatrixStreaming, results);

    }

    // write the results to a file
    string resultsFile = "../../results/output.data";
    results.writeToFile(resultsFile);

    return 0;

}
<commit_msg>examples ok<commit_after>//    Copyright 2015 Christina Teflioudi
//
//    Licensed under the Apache License, Version 2.0 (the "License");
//    you may not use this file except in compliance with the License.
//    You may obtain a copy of the License at
//
//        http://www.apache.org/licenses/LICENSE-2.0
//
//    Unless required by applicable law or agreed to in writing, software
//    distributed under the License is distributed on an "AS IS" BASIS,
//    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
//    See the License for the specific language governing permissions and
//    limitations under the License.

#include <iostream>
#include <mips/mips.h>

#include <sys/time.h>
#include <fstream>
#include <climits>
#include <cmath>
#include <algorithm>

using namespace std;
using namespace mips;
using namespace rg;

// EXAMPLE OF LEMP
int main() {

    // first we have to define the input arguments for the algorithm
    InputArguments args;
//    args.theta = 0.035;//0.035; // theta for the Above-theta problem (will be used when running .runAboveTheta())
    args.k = 10; // k for the Row-Top-k problem (will be used when running .runTopK())
    args.threads = 1; // number of threads the algorithm will use for execution
    args.logFile = "../../results/log.txt"; // log file which will contain the timings

    // LEMP will also need some special arguments
    LEMP_Method method = LEMP_LI; // choose one of the methods LEMP provides (LEMP_X where X: L, LI, LC, I, C, TA, TREE, AP, LSH)
    int cacheSizeinKB = 2048; // specify your cache size per core (important since LEMP tries to optimize for cache utilization)
    double R = 0.60; // recall parameter for LEMP_LSH
    bool isTARR = true; // relevant for LEMP_TA (true will use ROUND ROBIN, false will use a MAX HEAP)
    double epsilon = 0.3; // epsilon value for LEMP_LI with absolute or relative approximation

    // we will need some input matrices for the algorithm (create them like (1), (2) or (3))
    VectorMatrix leftMatrix, rightMatrix;

    // (1) create a VectorMatrix by using .mma files
   string queryFile = "../../dataset/w-gnmf-sample.mma";
   string probeFile = "../../dataset/h-gnmf-sample.mma";

    leftMatrix.readFromFile(queryFile, 0,0, true);
    rightMatrix.readFromFile(probeFile, 0,0, false);

    // (2) create a VectorMatrix by using .csv files
//    int r = 50; // dimensionality of vectors
//    int m = 1000; // number of query-vectors
//    int n = 1000; // number of probe-vectors
//    string queryFile = "../../dataset/w-gnmf-sample.csv";
//    string probeFile = "../../dataset/h-gnmf-sample.csv";
//    leftMatrix.readFromFile(queryFile, r, m, true);
//    rightMatrix.readFromFile(probeFile, r, n, false);

    // (3) create a VectorMatrix by using several vectors of double values
//    std::vector<std::vector<double>> m(1); // a matrix containing only 1 vector
//    m[0].resize(50); // this vector will have dimensionality 50
//    std::iota(m[0].begin(), m[0].end(), 0); // we will just fill in some values as an example
//    VectorMatrix leftMatrixStreaming(m);

    // create an instance of the algorithm you wish to use
    mips::Lemp algo(args, cacheSizeinKB, method, isTARR, R, epsilon);

    // initialize the algorithm with a probe matrix (algorithm will store a copy of it inside)
    algo.initialize(rightMatrix);

    // create a structure for storing the results
    Results results;

    // decide between the Row-Top-k problem or the Above-theta problem
    if (args.k > 0) { // Row-Top-k

        // solves the Row-Top-k problem and stores the results in the specified results structure
        algo.runTopK(leftMatrix, results);

    } else { // Above-theta

        // solves the Above-theta problem and stores the results in the specified results structure
        algo.runAboveTheta(leftMatrix, results);

//        algo.setTheta(1.68); // we might also change the theta if we want so
//        algo.setMethod(LEMP_LSH); // we might also change the method if we want so
//        results.clear();
//
//        // we might also run another matrix which will append the results to the specified results structure (otherwise you will have to create another results instance)
//        algo.runAboveTheta(leftMatrixStreaming, results);

    }

    // write the results to a file
    string resultsFile = "../../results/output.data";
    results.writeToFile(resultsFile);

    return 0;

}
<|endoftext|>


<commit_before>/******************************************************************************
* BRICS_3D - 3D Perception and Modeling Library
* Copyright (c) 2015, KU Leuven
*
* Author: Sebastian Blumenthal
*
*
* This software is published under a dual-license: GNU Lesser General Public
* License LGPL 2.1 and Modified BSD license. The dual-license implies that
* users of this code may choose which terms they prefer.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License LGPL and the BSD license for
* more details.
*
******************************************************************************/

/*
 * This example shows the usage of the json parser tools.
 */

#include <brics_3d/core/Logger.h>
#include <brics_3d/worldModel/WorldModel.h>

#include <Variant/Variant.h>
#include <stdio.h>

// Import Variant from libvariant
using libvariant::Variant;

using brics_3d::Logger;
using namespace brics_3d;

bool handleGraphPrimitive(Variant& atom, rsg::Id parentId);
bool handleNode(Variant& node, rsg::Id parentId);
bool handleGroup(Variant& group, rsg::Id parentId);
brics_3d::rsg::Id getId(Variant& node, string idTag);
std::vector<rsg::Attribute> getAttributes (Variant& node);

int main(int argc, char **argv) {

	Logger::setMinLoglevel(Logger::LOGDEBUG);
	LOG(INFO) << " JSON parser test.";

	if (argc != 2) {
		printf("Usage: %s input_file\n", *argv);
		return 1;
	}

	const char *fileName = argv[1];
    Variant model = libvariant::DeserializeJSONFile(fileName);

	// Pretty print to stdout
	libvariant::SerializeJSON(stdout, model, true);

	if(model.Contains("type")) {
		LOG(INFO) << "Top level model type exists.";
	}

	handleGraphPrimitive(model, 0);

	return 0;
}

/**
 * Inferes the type and calls the respecive handleXY
 * @param atom
 * @param parentId
 * @return
 */
bool handleGraphPrimitive(Variant& atom, rsg::Id parentId) {
	if(atom.Contains("type")) {
		LOG(DEBUG) << "Atom has type identifier";
		string type = atom.Get("type").AsString();
		LOG(DEBUG) << "\t type = " << type;

		if(type.compare("Node") == 0) {
			handleNode(atom, parentId);
		} else if (type.compare("Group") == 0) {
			handleGroup(atom, parentId);
		} else { // ...
			LOG(WARNING) << "Unknown atom type. Skippping it.";
		}
	} else {
		LOG(ERROR) << "Atom has no type identifier";
		return false;
	}

	return true;
}

bool handleNode(Variant& node, rsg::Id parentId) {
	LOG(DEBUG) << "handleNode: type is" << node.Get("type").AsString();

	/* Id */
	rsg::Id id = getId(node, "id");
	assert(!id.isNil());

	/* attributes */
	std::vector<rsg::Attribute> attributes = getAttributes(node);

	/* create it */

	return true;
}

/**
 * Handle paring of a "group" primitive.
 * @param group The JSON version of a group
 * @param parentId For recursion we need to pass the parent Id as extracted from the group on the "upper" level
 *        in the graph.
 * @return true on success
 */
bool handleGroup(Variant& group, rsg::Id parentId) {
	LOG(DEBUG) << "handleGroup: type is" << group.Get("type").AsString();

	/* Id */
	rsg::Id id = getId(group, "id");
	assert(!id.isNil());

	/* attributes */
	std::vector<rsg::Attribute> attributes = getAttributes(group);

	/* childs (recursion) */
	if(group.Contains("childs")) {
		LOG(DEBUG) << "Group has the following childs:";

		Variant attributeList = group.Get("childs");
		if (attributeList.IsList()) {
			for (Variant::ListIterator i(attributeList.ListBegin()), e(attributeList.ListEnd()); i!=e; ++i) {
				assert(i->Contains("type"));
				string childType = i->Get("type").AsString();
				LOG(DEBUG) << " type = " << childType;

				if(childType.compare("Child") == 0) {
					Variant child = i->Get("child");
					handleGraphPrimitive(child, id);
				} else if (childType.compare("ChildId") == 0) {
					// TODO stamps
					assert(i->Contains("childId"));
					rsg::Id childId = getId(*i, "childId");
					LOG(DEBUG) << "Adding parent -> child relation: " << id << " -> " << childId;
					// add parent
				}
			}
		}
	}
	return true;
}

brics_3d::rsg::Id getId(Variant& node, string idTag) {
	rsg::Id id = 0; //NiL

	if(node.Contains(idTag)) { // required
		id.fromString(node.Get(idTag).AsString());
		assert(!id.isNil());
		LOG(DEBUG) << "Id " << idTag << " is = " << id;
	} else {
		LOG(ERROR) << "Can not parse model. No node Id " << idTag << " specified.";
	}

	return id;
}

std::vector<rsg::Attribute> getAttributes (Variant& node) {
	std::vector<rsg::Attribute> attributes;
	attributes.clear();

	if(node.Contains("attributes")) {
		LOG(DEBUG) << "Node has the following attributes:";

		Variant attributeList = node.Get("attributes");
		if (attributeList.IsList()) {
			for (Variant::ListIterator i(attributeList.ListBegin()), e(attributeList.ListEnd()); i!=e; ++i) {
				assert(i->Contains("key"));
				assert(i->Contains("value"));
				LOG(DEBUG) << "\t( " << i->Get("key").AsString() << ", " << i->Get("value").AsString() << " )";
				attributes.push_back(rsg::Attribute(i->Get("key").AsString(), i->Get("value").AsString()));
			}
		}
	}

	return attributes;
}
<commit_msg>Added guessing option for deserialization.<commit_after>/******************************************************************************
* BRICS_3D - 3D Perception and Modeling Library
* Copyright (c) 2015, KU Leuven
*
* Author: Sebastian Blumenthal
*
*
* This software is published under a dual-license: GNU Lesser General Public
* License LGPL 2.1 and Modified BSD license. The dual-license implies that
* users of this code may choose which terms they prefer.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License LGPL and the BSD license for
* more details.
*
******************************************************************************/

/*
 * This example shows the usage of the json parser tools.
 */

#include <brics_3d/core/Logger.h>
#include <brics_3d/worldModel/WorldModel.h>

#include <Variant/Variant.h>
#include <Variant/Schema.h>
#include <Variant/Payload.h>
#include <stdio.h>
#include <fstream>
#include <sstream>

// Import Variant from libvariant
using libvariant::Variant;

using brics_3d::Logger;
using namespace brics_3d;

bool handleGraphPrimitive(Variant& atom, rsg::Id parentId);
bool handleNode(Variant& node, rsg::Id parentId);
bool handleGroup(Variant& group, rsg::Id parentId);
brics_3d::rsg::Id getId(Variant& node, string idTag);
std::vector<rsg::Attribute> getAttributes (Variant& node);

int main(int argc, char **argv) {

	Logger::setMinLoglevel(Logger::LOGDEBUG);
	LOG(INFO) << " JSON parser test.";

	if (argc != 2) {
		printf("Usage: %s input_file\n", *argv);
		return 1;
	}

	const char *fileName = argv[1];
	std::ifstream inputFile;
	inputFile.open (fileName, std::ifstream::in);
	std::stringstream serializedModel;
	serializedModel << inputFile.rdbuf();

	LOG(DEBUG) << "Input = " << std::endl << serializedModel.str();
    Variant model = libvariant:: Deserialize(serializedModel.str(), libvariant::SERIALIZE_GUESS); // GUESS seems to be more permissive with parsing than JSON

	// Pretty print to stdout
    LOG(INFO) << "---";
	libvariant::SerializeJSON(stdout, model, true);
    LOG(INFO) << "---";

    // Start to parse it
	if(model.Contains("type")) {
		LOG(INFO) << "Top level model type exists.";
	}

	handleGraphPrimitive(model, 0);

	return 0;
}

/**
 * Inferes the type and calls the respecive handleXY
 * @param atom
 * @param parentId
 * @return
 */
bool handleGraphPrimitive(Variant& atom, rsg::Id parentId) {
	if(atom.Contains("type")) {
		LOG(DEBUG) << "Atom has type identifier";
		string type = atom.Get("type").AsString();
		LOG(DEBUG) << "\t type = " << type;

		if(type.compare("Node") == 0) {
			handleNode(atom, parentId);
		} else if (type.compare("Group") == 0) {
			handleGroup(atom, parentId);
		} else { // ...
			LOG(WARNING) << "Unknown atom type. Skippping it.";
		}
	} else {
		LOG(ERROR) << "Atom has no type identifier";
		return false;
	}

	return true;
}

bool handleNode(Variant& node, rsg::Id parentId) {
	LOG(DEBUG) << "handleNode: type is" << node.Get("type").AsString();

	/* Id */
	rsg::Id id = getId(node, "id");
	assert(!id.isNil());

	/* attributes */
	std::vector<rsg::Attribute> attributes = getAttributes(node);

	/* create it */

	return true;
}

/**
 * Handle paring of a "group" primitive.
 * @param group The JSON version of a group
 * @param parentId For recursion we need to pass the parent Id as extracted from the group on the "upper" level
 *        in the graph.
 * @return true on success
 */
bool handleGroup(Variant& group, rsg::Id parentId) {
	LOG(DEBUG) << "handleGroup: type is" << group.Get("type").AsString();

	/* Id */
	rsg::Id id = getId(group, "id");
	assert(!id.isNil());

	/* attributes */
	std::vector<rsg::Attribute> attributes = getAttributes(group);

	/* childs (recursion) */
	if(group.Contains("childs")) {
		LOG(DEBUG) << "Group has the following childs:";

		Variant attributeList = group.Get("childs");
		if (attributeList.IsList()) {
			for (Variant::ListIterator i(attributeList.ListBegin()), e(attributeList.ListEnd()); i!=e; ++i) {
				assert(i->Contains("type"));
				string childType = i->Get("type").AsString();
				LOG(DEBUG) << " type = " << childType;

				if(childType.compare("Child") == 0) {
					Variant child = i->Get("child");
					handleGraphPrimitive(child, id);
				} else if (childType.compare("ChildId") == 0) {
					// TODO stamps
					assert(i->Contains("childId"));
					rsg::Id childId = getId(*i, "childId");
					LOG(DEBUG) << "Adding parent -> child relation: " << id << " -> " << childId;
					// add parent
				}
			}
		}
	}
	return true;
}

brics_3d::rsg::Id getId(Variant& node, string idTag) {
	rsg::Id id = 0; //NiL

	if(node.Contains(idTag)) { // required
		id.fromString(node.Get(idTag).AsString());
		assert(!id.isNil());
		LOG(DEBUG) << "Id " << idTag << " is = " << id;
	} else {
		LOG(ERROR) << "Can not parse model. No node Id " << idTag << " specified.";
	}

	return id;
}

std::vector<rsg::Attribute> getAttributes (Variant& node) {
	std::vector<rsg::Attribute> attributes;
	attributes.clear();

	if(node.Contains("attributes")) {
		LOG(DEBUG) << "Node has the following attributes:";

		Variant attributeList = node.Get("attributes");
		if (attributeList.IsList()) {
			for (Variant::ListIterator i(attributeList.ListBegin()), e(attributeList.ListEnd()); i!=e; ++i) {
				assert(i->Contains("key"));
				assert(i->Contains("value"));
				LOG(DEBUG) << "\t( " << i->Get("key").AsString() << ", " << i->Get("value").AsString() << " )";
				attributes.push_back(rsg::Attribute(i->Get("key").AsString(), i->Get("value").AsString()));
			}
		}
	}

	return attributes;
}
<|endoftext|>


<commit_before>/*****************************************************************************
Copyright (C) 2011 Elliot Laster

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

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

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

// Rice
#include <rice/Data_Type.hpp>
#include <rice/Constructor.hpp>
#include <rice/Class.hpp>
#include <rice/Enum.hpp>

// Mapnik
#include <mapnik/layer.hpp>

template<>
Rice::Object to_ruby<std::vector<std::string> >(std::vector<std::string> const & x)
{
  return Rice::Array(x.begin(), x.end());
}

std::vector<std::string> & (mapnik::layer::*_styles_)() = &mapnik::layer::styles;

void register_layer(Rice::Module rb_mapnik){
  /*
    @@Module_var rb_mapnik = Mapnik
  */
  Rice::Data_Type< mapnik::layer > rb_clayer = Rice::define_class_under< mapnik::layer >(rb_mapnik, "Layer");

  /*
  * Document-method: new
  * call-seq:
  *   new(name, srs)
  * @param [String] name
  * @param [String] srs
  * @return [Mapnik::Layer] a new layer object
  */
  rb_clayer.define_constructor(Rice::Constructor< mapnik::layer, std::string, std::string >(), (Rice::Arg("name"), Rice::Arg("srs") = (std::string)"+proj=longlat +ellps=WGS84 +datum=WGS84 +no_defs"));

  /*
  * Document-method: datasource
  * @return [Mapnik::Datasource] the layer's datasource
  */
  rb_clayer.define_method("datasource", &mapnik::layer::datasource);

  /*
  * Document-method: datasource=
  * call-seq:
  *   datasource=(new_datasource)
  * @param [Mapnik::Datasource]
  * @return [nil]
  */
  rb_clayer.define_method("datasource=", &mapnik::layer::set_datasource, Rice::Arg("new_datasource"));

  /*
  * Document-method: envelope
  * @return [Mapnik::Envelope] The layer's envelope
  * Should correspond to the layer's datasource envelope.
  */
  rb_clayer.define_method("envelope", &mapnik::layer::envelope);

  /*
  * Document-method: name
  * @return [String] The layer's name
  */
  rb_clayer.define_method("name", &mapnik::layer::name);

  /*
  * Document-method: name=
  * call-seq:
  *   name=(new_name)
  * @param [String]
  * @return [nil]
  */
  rb_clayer.define_method("name=", &mapnik::layer::set_name, Rice::Arg("new_name"));

  /*
  * Document-method: srs
  * @return [String] the layer's srs
  */
  rb_clayer.define_method("srs", &mapnik::layer::srs);

  /*
  * Document-method: srs=
  * call-seq:
  *   srs=(new_srs)
  * @param [String]
  */
  rb_clayer.define_method("srs=", &mapnik::layer::set_srs, Rice::Arg("new_srs"));

  /*
  * Document-method: min_zoom
  * @return [Integer] the layer's minimum zoom factor
  */
  rb_clayer.define_method("min_zoom", &mapnik::layer::getMinZoom);

  /*
  * Document-method: min_zoom=
  * call-seq:
  *   min_zoom=(min_zoom)
  * @return [nil]
  */
  rb_clayer.define_method("min_zoom=", &mapnik::layer::setMinZoom, Rice::Arg("new_min_zoom"));

  /*
  * Document-method: max_zoom
  * @return [Integer] the layer's maximum zoom factor
  */
  rb_clayer.define_method("max_zoom", &mapnik::layer::getMaxZoom);

  /*
  * Document-method: max_zoom=
  * call-seq:
  *   min_zoom=(min_zoom)
  * @return [nil]
  */
  rb_clayer.define_method("max_zoom=", &mapnik::layer::setMaxZoom, Rice::Arg("new_max_zoom"));

  /*
  * Document-method: visible_at_scale?
  * @return [Boolean]
  */
  rb_clayer.define_method("visible_at_scale?", &mapnik::layer::isVisible, Rice::Arg("scale"));

  /*
  * Document-method: active?
  * @return [Boolean]
  */
  rb_clayer.define_method("active?", &mapnik::layer::isActive);

  /*
  * Document-method: active=
  * call-seq:
  *   active=(new_active_value)
  * @return [nil]
  */
  rb_clayer.define_method("active=", &mapnik::layer::setActive, Rice::Arg("new_active_value"));

  /*
  * Document-method: queryable?
  * @return [Boolean]
  */
  rb_clayer.define_method("queryable?", &mapnik::layer::isQueryable);

  /*
  * Document-method: queryable=
  * call-seq:
  *   queryable=(new_queryable_value)
  * @return [nil]
  */
  rb_clayer.define_method("queryable=", &mapnik::layer::setQueryable, Rice::Arg("new_queryable_value"));

  /*
  * Document-method: cache_features?
  * @return [Boolean]
  */
  rb_clayer.define_method("cache_features?", &mapnik::layer::cache_features);

  /*
  * Document-method: cache_features=
  * call-seq:
  *   cache_features=(new_cache_features_value)
  * @return [nil]
  */
  rb_clayer.define_method("cache_features=", &mapnik::layer::set_cache_features, Rice::Arg("new_cache_features_value"));

  /*
  * Document-method: clear_label_cache?
  * @return [Boolean]
  */
  rb_clayer.define_method("clear_label_cache?", &mapnik::layer::clear_label_cache);

  /*
  * Document-method: clear_label_cache=
  * call-seq:
  *   clear_label_cache=(new_clear_label_cache_value)
  * @return [nil]
  */
  rb_clayer.define_method("clear_label_cache=", &mapnik::layer::set_clear_label_cache, Rice::Arg("new_clear_label_cache_value"));

  /*
  * Dont-Document-method: __style_list__
  */
  rb_clayer.define_method("__style_list__", _styles_);

  /*
  * Dont-Document-method: __append_style__
  */
  rb_clayer.define_method("__append_style__", &mapnik::layer::add_style, Rice::Arg("new_style"));
}<commit_msg>Fix method names in mapnik::layer (according to https://github.com/mapnik/mapnik/commit/207ecfd597d70a9fcc1b3c8e768049658e4085fc)<commit_after>/*****************************************************************************
Copyright (C) 2011 Elliot Laster

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

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

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

// Rice
#include <rice/Data_Type.hpp>
#include <rice/Constructor.hpp>
#include <rice/Class.hpp>
#include <rice/Enum.hpp>

// Mapnik
#include <mapnik/layer.hpp>

template<>
Rice::Object to_ruby<std::vector<std::string> >(std::vector<std::string> const & x)
{
  return Rice::Array(x.begin(), x.end());
}

std::vector<std::string> & (mapnik::layer::*_styles_)() = &mapnik::layer::styles;

void register_layer(Rice::Module rb_mapnik){
  /*
    @@Module_var rb_mapnik = Mapnik
  */
  Rice::Data_Type< mapnik::layer > rb_clayer = Rice::define_class_under< mapnik::layer >(rb_mapnik, "Layer");

  /*
  * Document-method: new
  * call-seq:
  *   new(name, srs)
  * @param [String] name
  * @param [String] srs
  * @return [Mapnik::Layer] a new layer object
  */
  rb_clayer.define_constructor(Rice::Constructor< mapnik::layer, std::string, std::string >(), (Rice::Arg("name"), Rice::Arg("srs") = (std::string)"+proj=longlat +ellps=WGS84 +datum=WGS84 +no_defs"));

  /*
  * Document-method: datasource
  * @return [Mapnik::Datasource] the layer's datasource
  */
  rb_clayer.define_method("datasource", &mapnik::layer::datasource);

  /*
  * Document-method: datasource=
  * call-seq:
  *   datasource=(new_datasource)
  * @param [Mapnik::Datasource]
  * @return [nil]
  */
  rb_clayer.define_method("datasource=", &mapnik::layer::set_datasource, Rice::Arg("new_datasource"));

  /*
  * Document-method: envelope
  * @return [Mapnik::Envelope] The layer's envelope
  * Should correspond to the layer's datasource envelope.
  */
  rb_clayer.define_method("envelope", &mapnik::layer::envelope);

  /*
  * Document-method: name
  * @return [String] The layer's name
  */
  rb_clayer.define_method("name", &mapnik::layer::name);

  /*
  * Document-method: name=
  * call-seq:
  *   name=(new_name)
  * @param [String]
  * @return [nil]
  */
  rb_clayer.define_method("name=", &mapnik::layer::set_name, Rice::Arg("new_name"));

  /*
  * Document-method: srs
  * @return [String] the layer's srs
  */
  rb_clayer.define_method("srs", &mapnik::layer::srs);

  /*
  * Document-method: srs=
  * call-seq:
  *   srs=(new_srs)
  * @param [String]
  */
  rb_clayer.define_method("srs=", &mapnik::layer::set_srs, Rice::Arg("new_srs"));

  /*
  * Document-method: min_zoom
  * @return [Integer] the layer's minimum zoom factor
  */
  rb_clayer.define_method("min_zoom", &mapnik::layer::min_zoom);

  /*
  * Document-method: min_zoom=
  * call-seq:
  *   min_zoom=(min_zoom)
  * @return [nil]
  */
  rb_clayer.define_method("min_zoom=", &mapnik::layer::set_min_zoom, Rice::Arg("new_min_zoom"));

  /*
  * Document-method: max_zoom
  * @return [Integer] the layer's maximum zoom factor
  */
  rb_clayer.define_method("max_zoom", &mapnik::layer::max_zoom);

  /*
  * Document-method: max_zoom=
  * call-seq:
  *   min_zoom=(min_zoom)
  * @return [nil]
  */
  rb_clayer.define_method("max_zoom=", &mapnik::layer::set_max_zoom, Rice::Arg("new_max_zoom"));

  /*
  * Document-method: visible_at_scale?
  * @return [Boolean]
  */
  rb_clayer.define_method("visible_at_scale?", &mapnik::layer::visible, Rice::Arg("scale"));

  /*
  * Document-method: active?
  * @return [Boolean]
  */
  rb_clayer.define_method("active?", &mapnik::layer::active);

  /*
  * Document-method: active=
  * call-seq:
  *   active=(new_active_value)
  * @return [nil]
  */
  rb_clayer.define_method("active=", &mapnik::layer::set_active, Rice::Arg("new_active_value"));

  /*
  * Document-method: queryable?
  * @return [Boolean]
  */
  rb_clayer.define_method("queryable?", &mapnik::layer::queryable);

  /*
  * Document-method: queryable=
  * call-seq:
  *   queryable=(new_queryable_value)
  * @return [nil]
  */
  rb_clayer.define_method("queryable=", &mapnik::layer::set_queryable, Rice::Arg("new_queryable_value"));

  /*
  * Document-method: cache_features?
  * @return [Boolean]
  */
  rb_clayer.define_method("cache_features?", &mapnik::layer::cache_features);

  /*
  * Document-method: cache_features=
  * call-seq:
  *   cache_features=(new_cache_features_value)
  * @return [nil]
  */
  rb_clayer.define_method("cache_features=", &mapnik::layer::set_cache_features, Rice::Arg("new_cache_features_value"));

  /*
  * Document-method: clear_label_cache?
  * @return [Boolean]
  */
  rb_clayer.define_method("clear_label_cache?", &mapnik::layer::clear_label_cache);

  /*
  * Document-method: clear_label_cache=
  * call-seq:
  *   clear_label_cache=(new_clear_label_cache_value)
  * @return [nil]
  */
  rb_clayer.define_method("clear_label_cache=", &mapnik::layer::set_clear_label_cache, Rice::Arg("new_clear_label_cache_value"));

  /*
  * Dont-Document-method: __style_list__
  */
  rb_clayer.define_method("__style_list__", _styles_);

  /*
  * Dont-Document-method: __append_style__
  */
  rb_clayer.define_method("__append_style__", &mapnik::layer::add_style, Rice::Arg("new_style"));
}<|endoftext|>