<commit_before>//******************************************************************
//
// Copyright 2014 Intel Mobile Communications GmbH All Rights Reserved.
//
//-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
//
// 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.
//
//-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=

// garageclient.cpp is the client program for garageserver.cpp, which
// uses different representation in OCRepresention.

#include <string>
#include <cstdlib>
#include <mutex>
#include <condition_variable>
#include "OCPlatform.h"
#include "OCApi.h"

using namespace OC;

const int SUCCESS_RESPONSE = 0;
std::shared_ptr<OCResource> curResource;
std::mutex curResourceLock;

static void printUsage()
{
    std::cout<<"Usage: garageclient <0|1> \n";
    std::cout<<"ConnectivityType: Default IP\n";
    std::cout<<"ConnectivityType 0: IP \n";
}

class Garage
{
public:

    bool m_state;
    std::string m_name;
    std::vector<bool> m_lightStates;
    std::vector<int> m_lightPowers;
    OCRepresentation m_lightRep;
    std::vector<OCRepresentation> m_reps;
    std::vector<std::vector<int>> m_hingeStates;

    Garage() : m_state(false), m_name("")
    {
    }
};

Garage myGarage;

void printRepresentation(const OCRepresentation& rep)
{

        // Check if attribute "name" exists, and then getValue
        if(rep.hasAttribute("name"))
        {
            myGarage.m_name = rep["name"];
        }
        std::cout << "\tname: " << myGarage.m_name << std::endl;

        // You can directly try to get the value. this function
        // return false if there is no attribute "state"
        if(!rep.getValue("state", myGarage.m_state))
        {
            std::cout << "Attribute state doesn't exist in the representation\n";
        }
        std::cout << "\tstate: " << myGarage.m_state << std::endl;

        OCRepresentation rep2 = rep;

        std::cout << "Number of attributes in rep2: "
                  << rep2.numberOfAttributes() << std::endl;

        if(rep2.erase("name"))
        {
            std::cout << "attribute: name, was removed successfully from rep2.\n";
        }

        std::cout << "Number of attributes in rep2: "
                  << rep2.numberOfAttributes() << std::endl;

        if(rep.isNULL("nullAttribute"))
        {
            std::cout << "\tnullAttribute is null." << std::endl;
        }
        else
        {
            std::cout << "\tnullAttribute is not null." << std::endl;
        }

        myGarage.m_lightRep = rep["light"];

        myGarage.m_lightStates = myGarage.m_lightRep["states"];
        myGarage.m_lightPowers = myGarage.m_lightRep["powers"];

        std::cout << "\tlightRep: states: ";

        int first = 1;
        for(auto state: myGarage.m_lightStates)
        {
            if(first)
            {
                std::cout << state;
                first = 0;
            }
            else
            {
                std::cout << "," << state;
            }
        }

        std::cout << std::endl;
        std::cout << "\tlightRep: powers: ";
        first = 1;
        for(auto power: myGarage.m_lightPowers)
        {
            if(first)
            {
                std::cout << power;
                first = 0;
            }
            else
            {
                std::cout << "," << power;
            }
        }
        std::cout << std::endl;

        // Get vector of representations
        myGarage.m_reps = rep["reps"];

        int ct = 0;
        for(auto& rep : myGarage.m_reps)
        {
            for(auto& attribute : rep)
            {
                std::cout<< "\treps["<<ct<<"]."<<attribute.attrname()<<":"
                    << attribute.type()<<" with value " <<attribute.getValueToString() <<std::endl;
            }
            ++ct;
        }

        std::cout << "\tjson: " << rep["json"] << std::endl;
        myGarage.m_hingeStates = rep["hinges"];

        std::cout<< "\tHinge parameter is type: " << rep["hinges"].type() << " with depth "<<
            rep["hinges"].depth() << " and a base type of "<< rep["hinges"].base_type()<<std::endl;

}
// callback handler on PUT request
void onPut(const HeaderOptions& /*headerOptions*/, const OCRepresentation& rep, const int eCode)
{
    if(eCode == SUCCESS_RESPONSE || eCode == OC_STACK_RESOURCE_CHANGED)
    {
        std::cout << "PUT request was successful" << std::endl;

        printRepresentation(rep);
    }
    else
    {
        std::cout << "onPut Response error: " << eCode << std::endl;
        std::exit(-1);
    }
}

// Local function to put a different state for this resource
void putLightRepresentation(std::shared_ptr<OCResource> resource)
{
    if(resource)
    {
        OCRepresentation rep;

        std::cout << "Putting light representation..."<<std::endl;

        myGarage.m_state = true;

        rep["state"] = myGarage.m_state;

        // Create QueryParameters Map and add query params (if any)
        QueryParamsMap queryParamsMap;

        // Invoke resource's pit API with rep, query map and the callback parameter
        resource->put(rep, queryParamsMap, &onPut);
    }
}

// Callback handler on GET request
void onGet(const HeaderOptions& /*headerOptions*/, const OCRepresentation& rep, const int eCode)
{
    if(eCode == SUCCESS_RESPONSE)
    {
        std::cout << "GET request was successful" << std::endl;
        std::cout << "Resource URI: " << rep.getUri() << std::endl;

        printRepresentation(rep);

        putLightRepresentation(curResource);
    }
    else
    {
        std::cout << "onGET Response error: " << eCode << std::endl;
        std::exit(-1);
    }
}

// Local function to get representation of light resource
void getLightRepresentation(std::shared_ptr<OCResource> resource)
{
    if(resource)
    {
        std::cout << "Getting Light Representation..."<<std::endl;
        // Invoke resource's get API with the callback parameter

        QueryParamsMap test;
        resource->get(test, &onGet);
    }
}

// Callback to found resources
void foundResource(std::shared_ptr<OCResource> resource)
{
    std::lock_guard<std::mutex> lock(curResourceLock);
    if(curResource)
    {
        std::cout << "Found another resource, ignoring"<<std::endl;
        return;
    }

    std::string resourceURI;
    std::string hostAddress;
    try
    {
        // Do some operations with resource object.
        if(resource)
        {
            std::cout<<"DISCOVERED Resource:"<<std::endl;
            // Get the resource URI
            resourceURI = resource->uri();
            std::cout << "\tURI of the resource: " << resourceURI << std::endl;

            // Get the resource host address
            hostAddress = resource->host();
            std::cout << "\tHost address of the resource: " << hostAddress << std::endl;

            // Get the resource types
            std::cout << "\tList of resource types: " << std::endl;
            for(auto &resourceTypes : resource->getResourceTypes())
            {
                std::cout << "\t\t" << resourceTypes << std::endl;
            }

            // Get the resource interfaces
            std::cout << "\tList of resource interfaces: " << std::endl;
            for(auto &resourceInterfaces : resource->getResourceInterfaces())
            {
                std::cout << "\t\t" << resourceInterfaces << std::endl;
            }

            if(resourceURI == "/a/garage")
            {
                curResource = resource;
                // Call a local function which will internally invoke
                // get API on the resource pointer
                getLightRepresentation(resource);
            }
        }
        else
        {
            // Resource is invalid
            std::cout << "Resource is invalid" << std::endl;
        }

    }
    catch(std::exception& e)
    {
        std::cerr << "Exception in foundResource: "<< e.what()<<std::endl;
    }
}

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

    std::ostringstream requestURI;

    OCConnectivityType connectivityType = CT_ADAPTER_IP;

    if(argc == 2)
    {
        try
        {
            std::size_t inputValLen;
            int optionSelected = std::stoi(argv[1], &inputValLen);

            if(inputValLen == strlen(argv[1]))
            {
                if(optionSelected == 0)
                {
                    std::cout << "Using IP."<< std::endl;
                    connectivityType = CT_ADAPTER_IP;
                }
                else
                {
                    std::cout << "Invalid connectivity type selected. Using default IP"
                        << std::endl;
                }
            }
            else
            {
                std::cout << "Invalid connectivity type selected. Using default IP" << std::endl;
            }
        }
        catch(std::exception&)
        {
            std::cout << "Invalid input argument. Using IP as connectivity type" << std::endl;
        }
    }
    else
    {
        printUsage();
        std::cout << "Invalid input argument. Using IP as connectivity type" << std::endl;
    }

    // Create PlatformConfig object
    PlatformConfig cfg {
        OC::ServiceType::InProc,
        OC::ModeType::Client,
        "0.0.0.0",
        0,
        OC::QualityOfService::LowQos
    };

    OCPlatform::Configure(cfg);
    try
    {
        // Find all resources
        requestURI << OC_RSRVD_WELL_KNOWN_URI << "?rt=core.garage";

        OCPlatform::findResource("", requestURI.str(),
                connectivityType, &foundResource);

        std::cout<< "Finding Resource... " <<std::endl;

        // A condition variable will free the mutex it is given, then do a non-
        // intensive block until 'notify' is called on it.  In this case, since we
        // don't ever call cv.notify, this should be a non-processor intensive version
        // of while(true);
        std::mutex blocker;
        std::condition_variable cv;
        std::unique_lock<std::mutex> lock(blocker);
        cv.wait(lock);
    }
    catch(OCException& e)
    {
        std::cerr << "Exception in GarageClient: "<<e.what();
    }

    return 0;
}

<commit_msg>Update garageclient status checking<commit_after>//******************************************************************
//
// Copyright 2014 Intel Mobile Communications GmbH All Rights Reserved.
//
//-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
//
// 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.
//
//-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=

// garageclient.cpp is the client program for garageserver.cpp, which
// uses different representation in OCRepresention.

#include <string>
#include <cstdlib>
#include <mutex>
#include <condition_variable>
#include "OCPlatform.h"
#include "OCApi.h"

using namespace OC;

std::shared_ptr<OCResource> curResource;
std::mutex curResourceLock;

static void printUsage()
{
    std::cout<<"Usage: garageclient <0|1> \n";
    std::cout<<"ConnectivityType: Default IP\n";
    std::cout<<"ConnectivityType 0: IP \n";
}

class Garage
{
public:

    bool m_state;
    std::string m_name;
    std::vector<bool> m_lightStates;
    std::vector<int> m_lightPowers;
    OCRepresentation m_lightRep;
    std::vector<OCRepresentation> m_reps;
    std::vector<std::vector<int>> m_hingeStates;

    Garage() : m_state(false), m_name("")
    {
    }
};

Garage myGarage;

void printRepresentation(const OCRepresentation& rep)
{

        // Check if attribute "name" exists, and then getValue
        if(rep.hasAttribute("name"))
        {
            myGarage.m_name = rep["name"];
        }
        std::cout << "\tname: " << myGarage.m_name << std::endl;

        // You can directly try to get the value. this function
        // return false if there is no attribute "state"
        if(!rep.getValue("state", myGarage.m_state))
        {
            std::cout << "Attribute state doesn't exist in the representation\n";
        }
        std::cout << "\tstate: " << myGarage.m_state << std::endl;

        OCRepresentation rep2 = rep;

        std::cout << "Number of attributes in rep2: "
                  << rep2.numberOfAttributes() << std::endl;

        if(rep2.erase("name"))
        {
            std::cout << "attribute: name, was removed successfully from rep2.\n";
        }

        std::cout << "Number of attributes in rep2: "
                  << rep2.numberOfAttributes() << std::endl;

        if(rep.isNULL("nullAttribute"))
        {
            std::cout << "\tnullAttribute is null." << std::endl;
        }
        else
        {
            std::cout << "\tnullAttribute is not null." << std::endl;
        }

        myGarage.m_lightRep = rep["light"];

        myGarage.m_lightStates = myGarage.m_lightRep["states"];
        myGarage.m_lightPowers = myGarage.m_lightRep["powers"];

        std::cout << "\tlightRep: states: ";

        int first = 1;
        for(auto state: myGarage.m_lightStates)
        {
            if(first)
            {
                std::cout << state;
                first = 0;
            }
            else
            {
                std::cout << "," << state;
            }
        }

        std::cout << std::endl;
        std::cout << "\tlightRep: powers: ";
        first = 1;
        for(auto power: myGarage.m_lightPowers)
        {
            if(first)
            {
                std::cout << power;
                first = 0;
            }
            else
            {
                std::cout << "," << power;
            }
        }
        std::cout << std::endl;

        // Get vector of representations
        myGarage.m_reps = rep["reps"];

        int ct = 0;
        for(auto& rep : myGarage.m_reps)
        {
            for(auto& attribute : rep)
            {
                std::cout<< "\treps["<<ct<<"]."<<attribute.attrname()<<":"
                    << attribute.type()<<" with value " <<attribute.getValueToString() <<std::endl;
            }
            ++ct;
        }

        std::cout << "\tjson: " << rep["json"] << std::endl;
        myGarage.m_hingeStates = rep["hinges"];

        std::cout<< "\tHinge parameter is type: " << rep["hinges"].type() << " with depth "<<
            rep["hinges"].depth() << " and a base type of "<< rep["hinges"].base_type()<<std::endl;

}
// callback handler on PUT request
void onPut(const HeaderOptions& /*headerOptions*/, const OCRepresentation& rep, const int eCode)
{
    if (eCode == OC_STACK_OK || eCode == OC_STACK_RESOURCE_CHANGED)
    {
        std::cout << "PUT request was successful" << std::endl;

        printRepresentation(rep);
    }
    else
    {
        std::cout << "onPut Response error: " << eCode << std::endl;
        std::exit(-1);
    }
}

// Local function to put a different state for this resource
void putLightRepresentation(std::shared_ptr<OCResource> resource)
{
    if(resource)
    {
        OCRepresentation rep;

        std::cout << "Putting light representation..."<<std::endl;

        myGarage.m_state = true;

        rep["state"] = myGarage.m_state;

        // Create QueryParameters Map and add query params (if any)
        QueryParamsMap queryParamsMap;

        // Invoke resource's pit API with rep, query map and the callback parameter
        resource->put(rep, queryParamsMap, &onPut);
    }
}

// Callback handler on GET request
void onGet(const HeaderOptions& /*headerOptions*/, const OCRepresentation& rep, const int eCode)
{
    if (eCode == OC_STACK_OK)
    {
        std::cout << "GET request was successful" << std::endl;
        std::cout << "Resource URI: " << rep.getUri() << std::endl;

        printRepresentation(rep);

        putLightRepresentation(curResource);
    }
    else
    {
        std::cout << "onGET Response error: " << eCode << std::endl;
        std::exit(-1);
    }
}

// Local function to get representation of light resource
void getLightRepresentation(std::shared_ptr<OCResource> resource)
{
    if(resource)
    {
        std::cout << "Getting Light Representation..."<<std::endl;
        // Invoke resource's get API with the callback parameter

        QueryParamsMap test;
        resource->get(test, &onGet);
    }
}

// Callback to found resources
void foundResource(std::shared_ptr<OCResource> resource)
{
    std::lock_guard<std::mutex> lock(curResourceLock);
    if(curResource)
    {
        std::cout << "Found another resource, ignoring"<<std::endl;
        return;
    }

    std::string resourceURI;
    std::string hostAddress;
    try
    {
        // Do some operations with resource object.
        if(resource)
        {
            std::cout<<"DISCOVERED Resource:"<<std::endl;
            // Get the resource URI
            resourceURI = resource->uri();
            std::cout << "\tURI of the resource: " << resourceURI << std::endl;

            // Get the resource host address
            hostAddress = resource->host();
            std::cout << "\tHost address of the resource: " << hostAddress << std::endl;

            // Get the resource types
            std::cout << "\tList of resource types: " << std::endl;
            for(auto &resourceTypes : resource->getResourceTypes())
            {
                std::cout << "\t\t" << resourceTypes << std::endl;
            }

            // Get the resource interfaces
            std::cout << "\tList of resource interfaces: " << std::endl;
            for(auto &resourceInterfaces : resource->getResourceInterfaces())
            {
                std::cout << "\t\t" << resourceInterfaces << std::endl;
            }

            if(resourceURI == "/a/garage")
            {
                curResource = resource;
                // Call a local function which will internally invoke
                // get API on the resource pointer
                getLightRepresentation(resource);
            }
        }
        else
        {
            // Resource is invalid
            std::cout << "Resource is invalid" << std::endl;
        }

    }
    catch(std::exception& e)
    {
        std::cerr << "Exception in foundResource: "<< e.what()<<std::endl;
    }
}

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

    std::ostringstream requestURI;

    OCConnectivityType connectivityType = CT_ADAPTER_IP;

    if(argc == 2)
    {
        try
        {
            std::size_t inputValLen;
            int optionSelected = std::stoi(argv[1], &inputValLen);

            if(inputValLen == strlen(argv[1]))
            {
                if(optionSelected == 0)
                {
                    std::cout << "Using IP."<< std::endl;
                    connectivityType = CT_ADAPTER_IP;
                }
                else
                {
                    std::cout << "Invalid connectivity type selected. Using default IP"
                        << std::endl;
                }
            }
            else
            {
                std::cout << "Invalid connectivity type selected. Using default IP" << std::endl;
            }
        }
        catch(std::exception&)
        {
            std::cout << "Invalid input argument. Using IP as connectivity type" << std::endl;
        }
    }
    else
    {
        printUsage();
        std::cout << "Invalid input argument. Using IP as connectivity type" << std::endl;
    }

    // Create PlatformConfig object
    PlatformConfig cfg {
        OC::ServiceType::InProc,
        OC::ModeType::Client,
        "0.0.0.0",
        0,
        OC::QualityOfService::LowQos
    };

    OCPlatform::Configure(cfg);
    try
    {
        // Find all resources
        requestURI << OC_RSRVD_WELL_KNOWN_URI << "?rt=core.garage";

        OCPlatform::findResource("", requestURI.str(),
                connectivityType, &foundResource);

        std::cout<< "Finding Resource... " <<std::endl;

        // A condition variable will free the mutex it is given, then do a non-
        // intensive block until 'notify' is called on it.  In this case, since we
        // don't ever call cv.notify, this should be a non-processor intensive version
        // of while(true);
        std::mutex blocker;
        std::condition_variable cv;
        std::unique_lock<std::mutex> lock(blocker);
        cv.wait(lock);
    }
    catch(OCException& e)
    {
        std::cerr << "Exception in GarageClient: "<<e.what();
    }

    return 0;
}

<|endoftext|>


<commit_before>#include "Ray.h"

void Ray::draw(sf::RenderTarget & target, sf::RenderStates states) const
{
	target.draw(m_sprite);
}

Ray::Ray(Side side)
	:m_side(side)
{

}

Ray::~Ray()
{
}

void Ray::SetAnimator(Animator & animator)
{
	m_animator = &animator;
	m_animator->SetSprite(m_sprite);
	m_animator->SetDelayBetweenFrames(0.1f);
	m_animator->ChangeActiveState("explosion");
}

int Ray::GetSide()
{
	return m_side;
}

void Ray::SetRaySpriteSize(unsigned short size)
{

	m_size = size;
	m_sprite.setTextureRect(sf::IntRect(0, 0, m_size*TILE_SIZE,TILE_SIZE));
	m_sprite.setOrigin(0, m_sprite.getGlobalBounds().height / 2.f);
	m_sprite.getTexture();
	switch (m_side)
	{
	case Ray::Up:
		m_sprite.setPosition(m_sprite.getPosition().x,m_sprite.getPosition().y - TILE_SIZE/2);
		m_sprite.setRotation(270);
		SetSize(TILE_SIZE, TILE_SIZE*size + TILE_SIZE);
		SetPositionY(static_cast<int>(GetPositionY() / TILE_SIZE) * TILE_SIZE);
		PhysicalBody::SetPositionY(GetPositionY()- ((TILE_SIZE*size) + TILE_SIZE)/2);
		break;
	case Ray::Down:
		SetPositionY(static_cast<int>(GetPositionY() / TILE_SIZE) * TILE_SIZE);
		m_sprite.setPosition(m_sprite.getPosition().x, m_sprite.getPosition().y + TILE_SIZE/2);
		m_sprite.setRotation(90);
		SetSize(TILE_SIZE, TILE_SIZE*size);
		PhysicalBody::SetPositionY(GetPositionY() + (TILE_SIZE*size) / 2 );
		break;
	case Ray::Left:
		SetPositionX(static_cast<int>(GetPositionX() / TILE_SIZE) * TILE_SIZE);
		m_sprite.setPosition(m_sprite.getPosition().x - TILE_SIZE/2, m_sprite.getPosition().y );
		m_sprite.setRotation(180);
		SetSize(TILE_SIZE*size, TILE_SIZE);
		PhysicalBody::SetPositionX(GetPositionX() - (TILE_SIZE*size) / 2);
		break;
	case Ray::Right:
		SetPositionX(static_cast<int>(GetPositionX() / TILE_SIZE) * TILE_SIZE);
		m_sprite.setPosition(m_sprite.getPosition().x + TILE_SIZE/2, m_sprite.getPosition().y);
		SetSize(TILE_SIZE*size, TILE_SIZE);
		PhysicalBody::SetPositionX(GetPositionX() + (TILE_SIZE*size) / 2);
		break;
	default:
		break;
	}

}

void Ray::SetPosition(float x, float y)
{
	m_sprite.setPosition(x,y);
	PhysicalBody::SetPositionX(x);
	PhysicalBody::SetPositionY(y);
}

void Ray::Update(const float & dt)
{
	//m_animator->Animate(dt);
}

<commit_msg>Please let it be the last fix to this bug<commit_after>#include "Ray.h"

void Ray::draw(sf::RenderTarget & target, sf::RenderStates states) const
{
	target.draw(m_sprite);
}

Ray::Ray(Side side)
	:m_side(side)
{

}

Ray::~Ray()
{
}

void Ray::SetAnimator(Animator & animator)
{
	m_animator = &animator;
	m_animator->SetSprite(m_sprite);
	m_animator->SetDelayBetweenFrames(0.1f);
	m_animator->ChangeActiveState("explosion");
}

int Ray::GetSide()
{
	return m_side;
}

void Ray::SetRaySpriteSize(unsigned short size)
{

	m_size = size;
	m_sprite.setTextureRect(sf::IntRect(0, 0, m_size*TILE_SIZE,TILE_SIZE));
	m_sprite.setOrigin(0, m_sprite.getGlobalBounds().height / 2.f);
	m_sprite.getTexture();
	switch (m_side)
	{
	case Ray::Up:
		m_sprite.setPosition(m_sprite.getPosition().x,m_sprite.getPosition().y - TILE_SIZE/2);
		m_sprite.setRotation(270);
		SetSize(TILE_SIZE, TILE_SIZE*size + TILE_SIZE);
		SetPositionY(static_cast<int>(GetPositionY() / TILE_SIZE) * TILE_SIZE);
		PhysicalBody::SetPositionY(GetPositionY()- ((TILE_SIZE*size) + TILE_SIZE)/2);
		break;
	case Ray::Down:
		SetPositionY(static_cast<int>(GetPositionY() / TILE_SIZE) * TILE_SIZE);
		m_sprite.setPosition(m_sprite.getPosition().x, m_sprite.getPosition().y + TILE_SIZE/2);
		m_sprite.setRotation(90);
		SetSize(TILE_SIZE, TILE_SIZE*size);
		PhysicalBody::SetPositionY(GetPositionY() +TILE_SIZE + (TILE_SIZE*size) / 2 );
		break;
	case Ray::Left:
		SetPositionX(static_cast<int>(GetPositionX() / TILE_SIZE) * TILE_SIZE);
		m_sprite.setPosition(m_sprite.getPosition().x - TILE_SIZE/2, m_sprite.getPosition().y );
		m_sprite.setRotation(180);
		SetSize(TILE_SIZE*size, TILE_SIZE);
		PhysicalBody::SetPositionX(GetPositionX() - (TILE_SIZE*size) / 2);
		break;
	case Ray::Right:
		SetPositionX(static_cast<int>(GetPositionX() / TILE_SIZE) * TILE_SIZE);
		m_sprite.setPosition(m_sprite.getPosition().x + TILE_SIZE/2, m_sprite.getPosition().y);
		SetSize(TILE_SIZE*size, TILE_SIZE);
		PhysicalBody::SetPositionX(GetPositionX() +TILE_SIZE + (TILE_SIZE*size) / 2);
		break;
	default:
		break;
	}

}

void Ray::SetPosition(float x, float y)
{
	m_sprite.setPosition(x,y);
	PhysicalBody::SetPositionX(x);
	PhysicalBody::SetPositionY(y);
}

void Ray::Update(const float & dt)
{

}

<|endoftext|>


<commit_before>// Copyright (c) 2008, Google Inc.
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are
// met:
//
//     * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
//     * Redistributions in binary form must reproduce the above
// copyright notice, this list of conditions and the following disclaimer
// in the documentation and/or other materials provided with the
// distribution.
//     * Neither the name of Google Inc. nor the names of its
// contributors may be used to endorse or promote products derived from
// this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.

// These functions are used by the javascript access to the
// netscape.plugins object.  See PluginInfoStore.h.
// They are also used by WebViewImpl to check if a plugin exists for a given
// MIME type.
//

#include "config.h"

#include "ChromiumBridge.h"
#include "PluginData.h"
#if COMPILER(MSVC)
__pragma(warning(push, 0))
#endif
#include "PluginInfoStore.h"
#if COMPILER(MSVC)
__pragma(warning(pop))
#endif
#undef LOG

namespace WebCore {

// We cache the plugins ourselves, since if we're getting them from the another
// process GetPlugins() will be expensive.
static bool g_loaded_plugins = false;
static Vector<PluginInfo*> g_plugins;

void LoadPlugins(bool refresh)
{
    if (g_loaded_plugins && !refresh)
        return;

    if (g_loaded_plugins) {
        for (size_t i = 0; i < g_plugins.size(); ++i)
            deleteAllValues(g_plugins[i]->mimes);
        deleteAllValues(g_plugins);
        g_plugins.clear();
    }

    g_loaded_plugins = true;
    // these are leaked at shutdown
    ChromiumBridge::plugins(refresh, &g_plugins);
}

// Returns a PluginInfo pointer.  Caller is responsible for
// deleting contents of the PluginInfo.
PluginInfo* PluginInfoStore::createPluginInfoForPluginAtIndex(unsigned int index)
{
    LoadPlugins(false);

    WebCore::PluginInfo* rv = new WebCore::PluginInfo();
    const WebCore::PluginInfo* plugin = g_plugins[index];
    rv->name = plugin->name;
    rv->desc = plugin->desc;
    rv->file = plugin->file;
    for (size_t j = 0; j < plugin->mimes.size(); ++j) {
        WebCore::MimeClassInfo* new_mime = new WebCore::MimeClassInfo();
        const WebCore::MimeClassInfo* mime_type = plugin->mimes[j];
        new_mime->type = mime_type->type;
        new_mime->desc = mime_type->desc;
        new_mime->suffixes = mime_type->suffixes;
        new_mime->plugin = rv;
        rv->mimes.append(new_mime);
    }

    return rv;
}

unsigned PluginInfoStore::pluginCount() const
{
    LoadPlugins(false);

    return g_plugins.size();
}

bool PluginInfoStore::supportsMIMEType(const WebCore::String &mime_type)
{
    LoadPlugins(false);

    for (size_t i = 0; i < g_plugins.size(); ++i) {
        for (size_t j = 0; j < g_plugins[i]->mimes.size(); ++j) {
            if (ChromiumBridge::matchesMIMEType(g_plugins[i]->mimes[j]->type,
                                                mime_type)) {
                // Don't allow wildcard matches here as this will result in
                // plugins being instantiated in cases where they should not.
                // For e.g. clicking on a link which causes a file to be
                // downloaded, special mime types like text/xml, etc. In any
                // case the webkit codepaths which invoke this function don't
                // expect wildcard plugin matches.
                if (g_plugins[i]->mimes[j]->type == "*")
                    continue;
                return true;
            }
        }
    }

    return false;
}

void refreshPlugins(bool)
{
    LoadPlugins(true);
}

String GetPluginMimeTypeFromExtension(const String& extension)
{
#if !defined(__linux__)
    // TODO(port): unstub once we have plugin support for Linux
    LoadPlugins(false);

    for (size_t i = 0; i < g_plugins.size(); ++i) {
        PluginInfo* plugin = g_plugins[i];
        for (size_t j = 0; j < plugin->mimes.size(); ++j) {
            MimeClassInfo* mime = plugin->mimes[j];
            Vector<String> extensions;
            mime->suffixes.split(",", extensions);
            for (size_t k = 0; k < extensions.size(); ++k) {
                if (extension == extensions[k])
                    return mime->type;
            }
        }
    }
#endif

    return String();
}

} // namespace WebCore
<commit_msg>fix a leak in the plugin cache BUG=http://code.google.com/p/chromium/issues/detail?id=4654<commit_after>// Copyright (c) 2008, Google Inc.
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are
// met:
//
//     * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
//     * Redistributions in binary form must reproduce the above
// copyright notice, this list of conditions and the following disclaimer
// in the documentation and/or other materials provided with the
// distribution.
//     * Neither the name of Google Inc. nor the names of its
// contributors may be used to endorse or promote products derived from
// this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.

// These functions are used by the javascript access to the
// netscape.plugins object.  See PluginInfoStore.h.
// They are also used by WebViewImpl to check if a plugin exists for a given
// MIME type.

#include "config.h"

#include "ChromiumBridge.h"
#include "PluginData.h"
#include "PluginInfoStore.h"

namespace WebCore {

class PluginCache {
public:
    PluginCache() : m_loaded(false) { }

    ~PluginCache()
    {
        clear();
    }

    void load(bool refresh)
    {
        if (m_loaded) {
            if (!refresh)
                return;
            clear();
        } else {
            m_loaded = true;
        }
        ChromiumBridge::plugins(refresh, &m_plugins);
    }

    void clear()
    {
        for (size_t i = 0; i < m_plugins.size(); ++i)
            deleteAllValues(m_plugins[i]->mimes);
        deleteAllValues(m_plugins);
        m_plugins.clear();
    }

    // Returns a PluginInfo pointer.  Caller is responsible for
    // deleting contents of the PluginInfo.
    PluginInfo* createPluginInfoForPluginAtIndex(unsigned int index)
    {
        load(false);

        WebCore::PluginInfo* rv = new WebCore::PluginInfo();
        const WebCore::PluginInfo* plugin = m_plugins[index];
        rv->name = plugin->name;
        rv->desc = plugin->desc;
        rv->file = plugin->file;
        for (size_t j = 0; j < plugin->mimes.size(); ++j) {
            WebCore::MimeClassInfo* newMime = new WebCore::MimeClassInfo();
            const WebCore::MimeClassInfo* mimeType = plugin->mimes[j];
            newMime->type = mimeType->type;
            newMime->desc = mimeType->desc;
            newMime->suffixes = mimeType->suffixes;
            newMime->plugin = rv;
            rv->mimes.append(newMime);
        }

        return rv;
    }

    unsigned pluginCount()
    {
        load(false);

        return m_plugins.size();
    }

    bool supportsMIMEType(const WebCore::String &mime_type)
    {
        load(false);

        for (size_t i = 0; i < m_plugins.size(); ++i) {
            for (size_t j = 0; j < m_plugins[i]->mimes.size(); ++j) {
                if (ChromiumBridge::matchesMIMEType(
                        m_plugins[i]->mimes[j]->type, mime_type)) {
                    // Don't allow wildcard matches here as this will result in
                    // plugins being instantiated in cases where they should
                    // not. For e.g. clicking on a link which causes a file to
                    // be downloaded, special mime types like text/xml, etc. In
                    // any case the webkit codepaths which invoke this function
                    // don't expect wildcard plugin matches.
                    if (m_plugins[i]->mimes[j]->type == "*")
                        continue;
                    return true;
                }
            }
        }

        return false;
    }

    String GetPluginMimeTypeFromExtension(const String& extension)
    {
#if !defined(__linux__)
        // TODO(port): unstub once we have plugin support for Linux

        load(false);

        for (size_t i = 0; i < m_plugins.size(); ++i) {
            PluginInfo* plugin = m_plugins[i];
            for (size_t j = 0; j < plugin->mimes.size(); ++j) {
                MimeClassInfo* mime = plugin->mimes[j];
                Vector<String> extensions;
                mime->suffixes.split(",", extensions);
                for (size_t k = 0; k < extensions.size(); ++k) {
                    if (extension == extensions[k])
                        return mime->type;
                }
            }
        }
#endif
        return String();
    }

private:
    bool m_loaded;
    Vector<PluginInfo*> m_plugins;
};

// We cache the plugins ourselves, since if we're getting them from the another
// process GetPlugins() will be expensive.
static PluginCache pluginCache;

PluginInfo* PluginInfoStore::createPluginInfoForPluginAtIndex(unsigned int index)
{
    return pluginCache.createPluginInfoForPluginAtIndex(index);
}

unsigned PluginInfoStore::pluginCount() const
{
    return pluginCache.pluginCount();
}

bool PluginInfoStore::supportsMIMEType(const WebCore::String &mime_type)
{
    return pluginCache.supportsMIMEType(mime_type);
}

void refreshPlugins(bool)
{
    pluginCache.load(true);
}

String GetPluginMimeTypeFromExtension(const String& extension)
{
    return pluginCache.GetPluginMimeTypeFromExtension(extension);
}

} // namespace WebCore
<|endoftext|>


<commit_before>//
//  StaticAnalyser.cpp
//  Clock Signal
//
//  Created by Thomas Harte on 25/11/2017.
//  Copyright © 2017 Thomas Harte. All rights reserved.
//

#include "StaticAnalyser.hpp"

#include "Tape.hpp"
#include "../Disassembler/Z80.hpp"
#include "../Disassembler/AddressMapper.hpp"

#include <algorithm>

/*
	Expected standard cartridge format:

		DEFB "AB" ; expansion ROM header
		DEFW initcode ; start of the init code, 0 if no initcode
		DEFW callstat; pointer to CALL statement handler, 0 if no such handler
		DEFW device; pointer to expansion device handler, 0 if no such handler
		DEFW basic ; pointer to the start of a tokenized basicprogram, 0 if no basicprogram
		DEFS 6,0 ; room reserved for future extensions
*/
static std::list<std::shared_ptr<Storage::Cartridge::Cartridge>>
		MSXCartridgesFrom(const std::list<std::shared_ptr<Storage::Cartridge::Cartridge>> &cartridges, StaticAnalyser::Target &target) {
	std::list<std::shared_ptr<Storage::Cartridge::Cartridge>> msx_cartridges;

	for(const auto &cartridge : cartridges) {
		const auto &segments = cartridge->get_segments();

		// Only one mapped item is allowed.
		if(segments.size() != 1) continue;

		// Which must be a multiple of 16 kb in size.
		Storage::Cartridge::Cartridge::Segment segment = segments.front();
		const size_t data_size = segment.data.size();
		if(data_size < 0x2000 || data_size & 0x3fff) continue;

		// Check for a ROM header at address 0; if it's not found then try 0x4000
		// and adjust the start address;
		uint16_t start_address = 0;
		bool found_start = false;
		if(segment.data[0] == 0x41 && segment.data[1] == 0x42) {
			start_address = 0x4000;
			found_start = true;
		} else if(segment.data.size() >= 0x8000 && segment.data[0x4000] == 0x41 && segment.data[0x4001] == 0x42) {
			start_address = 0;
			found_start = true;
		}

		// Reject cartridge if the ROM header wasn't found.
		if(!found_start) continue;

		uint16_t init_address = static_cast<uint16_t>(segment.data[2] | (segment.data[3] << 8));
		// TODO: check for a rational init address?

		// If this ROM is greater than 48kb in size then some sort of MegaROM scheme must
		// be at play; disassemble to try to figure it out.
		if(data_size > 0xc000) {
			std::vector<uint8_t> first_8k;
			first_8k.insert(first_8k.begin(), segment.data.begin(), segment.data.begin() + 8192);
			StaticAnalyser::Z80::Disassembly disassembly =
				StaticAnalyser::Z80::Disassemble(
					first_8k,
					StaticAnalyser::Disassembler::OffsetMapper(start_address),
					{ init_address }
				);

			// Look for LD (nnnn), A instructions, and collate those addresses.
			using Instruction = StaticAnalyser::Z80::Instruction;
			std::map<uint16_t, int> address_counts;
			for(const auto &instruction_pair : disassembly.instructions_by_address) {
				if(	instruction_pair.second.operation == Instruction::Operation::LD &&
					instruction_pair.second.destination == Instruction::Location::Operand_Indirect &&
					instruction_pair.second.source == Instruction::Location::A) {
					address_counts[static_cast<uint16_t>(instruction_pair.second.operand)]++;
				}
			}

			// Sort possible cartridge types.
			using Possibility = std::pair<StaticAnalyser::MSXCartridgeType, int>;
			std::vector<Possibility> possibilities;
			// Add to list in order of declining probability, so that stable_sort below prefers the more likely option
			// in a tie.
			possibilities.push_back(std::make_pair(StaticAnalyser::MSXCartridgeType::ASCII8kb, address_counts[0x6000] + address_counts[0x6800] + address_counts[0x7000] + address_counts[0x7800]));
			possibilities.push_back(std::make_pair(StaticAnalyser::MSXCartridgeType::Konami, address_counts[0x6000] + address_counts[0x8000] + address_counts[0xa000]));
			possibilities.push_back(std::make_pair(StaticAnalyser::MSXCartridgeType::KonamiWithSCC, address_counts[0x5000] + address_counts[0x7000] + address_counts[0x9000] + address_counts[0xb000]));
			possibilities.push_back(std::make_pair(StaticAnalyser::MSXCartridgeType::ASCII16kb, address_counts[0x6000] + address_counts[0x7000] + address_counts[0x77ff]));
			std::stable_sort(possibilities.begin(), possibilities.end(), [](const Possibility &a, const Possibility &b) {
				if(a.second != b.second) return a.second > b.second;
				return a.first > b.first;
			});

			target.msx.paging_model = possibilities[0].first;
		}

		// Apply the standard MSX start address.
		msx_cartridges.emplace_back(new Storage::Cartridge::Cartridge({
			Storage::Cartridge::Cartridge::Segment(start_address, segment.data)
		}));
	}

	return msx_cartridges;
}

void StaticAnalyser::MSX::AddTargets(const Media &media, std::list<Target> &destination) {
	Target target;

	// Obtain only those cartridges which it looks like an MSX would understand.
	target.media.cartridges = MSXCartridgesFrom(media.cartridges, target);

	// Check tapes for loadable files.
	for(const auto &tape : media.tapes) {
		std::vector<File> files_on_tape = GetFiles(tape);
		if(!files_on_tape.empty()) {
			switch(files_on_tape.front().type) {
				case File::Type::ASCII:				target.loading_command = "RUN\"CAS:\r";			break;
				case File::Type::TokenisedBASIC:	target.loading_command = "CLOAD\rRUN\r";		break;
				case File::Type::Binary:			target.loading_command = "BLOAD\"CAS:\",R\r";	break;
				default: break;
			}
			target.media.tapes.push_back(tape);
		}
	}

	if(!target.media.empty()) {
		target.machine = Target::MSX;
		target.probability = 1.0;
		destination.push_back(target);
	}
}
<commit_msg>Adds an attempt to catch LD (xx), A / [CALL/JP] pairs.<commit_after>//
//  StaticAnalyser.cpp
//  Clock Signal
//
//  Created by Thomas Harte on 25/11/2017.
//  Copyright © 2017 Thomas Harte. All rights reserved.
//

#include "StaticAnalyser.hpp"

#include "Tape.hpp"
#include "../Disassembler/Z80.hpp"
#include "../Disassembler/AddressMapper.hpp"

#include <algorithm>

/*
	Expected standard cartridge format:

		DEFB "AB" ; expansion ROM header
		DEFW initcode ; start of the init code, 0 if no initcode
		DEFW callstat; pointer to CALL statement handler, 0 if no such handler
		DEFW device; pointer to expansion device handler, 0 if no such handler
		DEFW basic ; pointer to the start of a tokenized basicprogram, 0 if no basicprogram
		DEFS 6,0 ; room reserved for future extensions
*/
static std::list<std::shared_ptr<Storage::Cartridge::Cartridge>>
		MSXCartridgesFrom(const std::list<std::shared_ptr<Storage::Cartridge::Cartridge>> &cartridges, StaticAnalyser::Target &target) {
	std::list<std::shared_ptr<Storage::Cartridge::Cartridge>> msx_cartridges;

	for(const auto &cartridge : cartridges) {
		const auto &segments = cartridge->get_segments();

		// Only one mapped item is allowed.
		if(segments.size() != 1) continue;

		// Which must be a multiple of 16 kb in size.
		Storage::Cartridge::Cartridge::Segment segment = segments.front();
		const size_t data_size = segment.data.size();
		if(data_size < 0x2000 || data_size & 0x3fff) continue;

		// Check for a ROM header at address 0; if it's not found then try 0x4000
		// and adjust the start address;
		uint16_t start_address = 0;
		bool found_start = false;
		if(segment.data[0] == 0x41 && segment.data[1] == 0x42) {
			start_address = 0x4000;
			found_start = true;
		} else if(segment.data.size() >= 0x8000 && segment.data[0x4000] == 0x41 && segment.data[0x4001] == 0x42) {
			start_address = 0;
			found_start = true;
		}

		// Reject cartridge if the ROM header wasn't found.
		if(!found_start) continue;

		uint16_t init_address = static_cast<uint16_t>(segment.data[2] | (segment.data[3] << 8));
		// TODO: check for a rational init address?

		// If this ROM is greater than 48kb in size then some sort of MegaROM scheme must
		// be at play; disassemble to try to figure it out.
		target.msx.paging_model = StaticAnalyser::MSXCartridgeType::None;
		if(data_size > 0xc000) {
			std::vector<uint8_t> first_16k;
			first_16k.insert(first_16k.begin(), segment.data.begin(), segment.data.begin() + 8192);
			StaticAnalyser::Z80::Disassembly disassembly =
				StaticAnalyser::Z80::Disassemble(
					first_16k,
					StaticAnalyser::Disassembler::OffsetMapper(start_address),
					{ init_address }
				);

			// Look for a indirect store followed by an unconditional JP or CALL into another
			// segment, that's a fairly explicit sign where found.
			using Instruction = StaticAnalyser::Z80::Instruction;
			std::map<uint16_t, Instruction> &instructions = disassembly.instructions_by_address;
			bool is_ascii = false;
			auto iterator = instructions.begin();
			while(iterator != instructions.end()) {
				auto next_iterator = iterator;
				next_iterator++;
				if(next_iterator == instructions.end()) break;

				if(	iterator->second.operation == Instruction::Operation::LD &&
					iterator->second.destination == Instruction::Location::Operand_Indirect &&
					(
						iterator->second.operand == 0x5000 ||
						iterator->second.operand == 0x6000 ||
						iterator->second.operand == 0x6800 ||
						iterator->second.operand == 0x7000 ||
						iterator->second.operand == 0x77ff ||
						iterator->second.operand == 0x7800 ||
						iterator->second.operand == 0x8000 ||
						iterator->second.operand == 0x9000 ||
						iterator->second.operand == 0xa000
					) &&
					(
						next_iterator->second.operation == Instruction::Operation::CALL ||
						next_iterator->second.operation == Instruction::Operation::JP
					) &&
					((next_iterator->second.operand >> 13) != (0x4000 >> 13))
				) {
					const uint16_t address = static_cast<uint16_t>(next_iterator->second.operand);
					switch(iterator->second.operand) {
						case 0x6000:
							if(address >= 0x6000 && address < 0x8000) {
								target.msx.paging_model = StaticAnalyser::MSXCartridgeType::KonamiWithSCC;
							}
						break;
						case 0x6800:
							if(address >= 0x6000 && address < 0x6800) {
								target.msx.paging_model = StaticAnalyser::MSXCartridgeType::ASCII8kb;
							}
						break;
						case 0x7000:
							if(address >= 0x6000 && address < 0x8000) {
								target.msx.paging_model = StaticAnalyser::MSXCartridgeType::KonamiWithSCC;
							}
							if(address >= 0x7000 && address < 0x7800) {
								is_ascii = true;
							}
						break;
						case 0x77ff:
							if(address >= 0x7000 && address < 0x7800) {
								target.msx.paging_model = StaticAnalyser::MSXCartridgeType::ASCII16kb;
							}
						break;
						case 0x7800:
							if(address >= 0xa000 && address < 0xc000) {
								target.msx.paging_model = StaticAnalyser::MSXCartridgeType::ASCII8kb;
							}
						break;
						case 0x8000:
							if(address >= 0x8000 && address < 0xa000) {
								target.msx.paging_model = StaticAnalyser::MSXCartridgeType::KonamiWithSCC;
							}
						break;
						case 0x9000:
							if(address >= 0x8000 && address < 0xa000) {
								target.msx.paging_model = StaticAnalyser::MSXCartridgeType::KonamiWithSCC;
							}
						break;
						case 0xa000:
							if(address >= 0xa000 && address < 0xc000) {
								target.msx.paging_model = StaticAnalyser::MSXCartridgeType::Konami;
							}
						break;
						case 0xb000:
							if(address >= 0xa000 && address < 0xc000) {
								target.msx.paging_model = StaticAnalyser::MSXCartridgeType::KonamiWithSCC;
							}
						break;
					}
				}

				iterator = next_iterator;
			}

			if(target.msx.paging_model == StaticAnalyser::MSXCartridgeType::None) {
				// Look for LD (nnnn), A instructions, and collate those addresses.
				std::map<uint16_t, int> address_counts;
				for(const auto &instruction_pair : instructions) {
					if(	instruction_pair.second.operation == Instruction::Operation::LD &&
						instruction_pair.second.destination == Instruction::Location::Operand_Indirect &&
						instruction_pair.second.source == Instruction::Location::A) {
						address_counts[static_cast<uint16_t>(instruction_pair.second.operand)]++;
					}
				}

				// Sort possible cartridge types.
				using Possibility = std::pair<StaticAnalyser::MSXCartridgeType, int>;
				std::vector<Possibility> possibilities;
				// Add to list in order of declining probability, so that stable_sort below prefers
				// the more likely option in a tie.
				possibilities.push_back(std::make_pair(StaticAnalyser::MSXCartridgeType::ASCII8kb, address_counts[0x6000] + address_counts[0x6800] + address_counts[0x7000] + address_counts[0x7800]));
				possibilities.push_back(std::make_pair(StaticAnalyser::MSXCartridgeType::ASCII16kb, address_counts[0x6000] + address_counts[0x7000] + address_counts[0x77ff]));
				if(!is_ascii) possibilities.push_back(std::make_pair(StaticAnalyser::MSXCartridgeType::Konami, address_counts[0x6000] + address_counts[0x8000] + address_counts[0xa000]));
				if(!is_ascii) possibilities.push_back(std::make_pair(StaticAnalyser::MSXCartridgeType::KonamiWithSCC, address_counts[0x5000] + address_counts[0x7000] + address_counts[0x9000] + address_counts[0xb000]));
				std::stable_sort(possibilities.begin(), possibilities.end(), [](const Possibility &a, const Possibility &b) {
					return a.second > b.second;
				});

				target.msx.paging_model = possibilities[0].first;
			}
		}

		// Apply the standard MSX start address.
		msx_cartridges.emplace_back(new Storage::Cartridge::Cartridge({
			Storage::Cartridge::Cartridge::Segment(start_address, segment.data)
		}));
	}

	return msx_cartridges;
}

void StaticAnalyser::MSX::AddTargets(const Media &media, std::list<Target> &destination) {
	Target target;

	// Obtain only those cartridges which it looks like an MSX would understand.
	target.media.cartridges = MSXCartridgesFrom(media.cartridges, target);

	// Check tapes for loadable files.
	for(const auto &tape : media.tapes) {
		std::vector<File> files_on_tape = GetFiles(tape);
		if(!files_on_tape.empty()) {
			switch(files_on_tape.front().type) {
				case File::Type::ASCII:				target.loading_command = "RUN\"CAS:\r";			break;
				case File::Type::TokenisedBASIC:	target.loading_command = "CLOAD\rRUN\r";		break;
				case File::Type::Binary:			target.loading_command = "BLOAD\"CAS:\",R\r";	break;
				default: break;
			}
			target.media.tapes.push_back(tape);
		}
	}

	if(!target.media.empty()) {
		target.machine = Target::MSX;
		target.probability = 1.0;
		destination.push_back(target);
	}
}
<|endoftext|>


<commit_before>/*
 * The Apache Software License, Version 1.1
 *
 *
 * Copyright (c) 1999-2002 The Apache Software Foundation.  All rights
 * reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions
 * are met:
 *
 * 1. Redistributions of source code must retain the above copyright
 *    notice, this list of conditions and the following disclaimer.
 *
 * 2. Redistributions in binary form must reproduce the above copyright
 *    notice, this list of conditions and the following disclaimer in
 *    the documentation and/or other materials provided with the
 *    distribution.
 *
 * 3. The end-user documentation included with the redistribution,
 *    if any, must include the following acknowledgment:
 *       "This product includes software developed by the
 *        Apache Software Foundation (http://www.apache.org/)."
 *    Alternately, this acknowledgment may appear in the software itself,
 *    if and wherever such third-party acknowledgments normally appear.
 *
 * 4. The names "Xalan" and "Apache Software Foundation" must
 *    not be used to endorse or promote products derived from this
 *    software without prior written permission. For written
 *    permission, please contact apache@apache.org.
 *
 * 5. Products derived from this software may not be called "Apache",
 *    nor may "Apache" appear in their name, without prior written
 *    permission of the Apache Software Foundation.
 *
 * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED
 * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
 * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
 * DISCLAIMED.  IN NO EVENT SHALL THE APACHE SOFTWARE FOUNDATION OR
 * ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
 * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
 * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF
 * USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
 * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
 * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
 * OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
 * SUCH DAMAGE.
 * ====================================================================
 *
 * This software consists of voluntary contributions made by many
 * individuals on behalf of the Apache Software Foundation and was
 * originally based on software copyright (c) 1999, International
 * Business Machines, Inc., http://www.ibm.com.  For more
 * information on the Apache Software Foundation, please see
 * <http://www.apache.org/>.
 */
#if !defined(FORMATTERSTRINGLENGTHCOUNTER_HEADER_GUARD_1357924680)
#define FORMATTERSTRINGLENGTHCOUNTER_HEADER_GUARD_1357924680

// Base include file.  Must be first.
#include <XPath/XPathDefinitions.hpp>

// Base class header file.
#include <PlatformSupport/FormatterListener.hpp>

XALAN_CPP_NAMESPACE_BEGIN

/**
 * This class takes SAX events (in addition to some extra events
 * that SAX doesn't handle yet) and produces counts the characters
 * sent to the characters event.
 */
class XALAN_XPATH_EXPORT FormatterStringLengthCounter : public FormatterListener
{
public:

	typedef unsigned long	size_type;

	/**
	 * FormatterStringLengthCounter instance constructor.
	 */
	explicit
	FormatterStringLengthCounter();

	virtual
	~FormatterStringLengthCounter();

	unsigned long
	getCount() const
	{
		return m_count;
	}

	// These methods are inherited from FormatterListener ...

	virtual void
	setDocumentLocator(const LocatorType* const		locator);

	virtual void
	startDocument();

	virtual void
	endDocument();

	virtual void
	startElement(
			const XMLCh* const	name,
			AttributeListType&	attrs);

    virtual void
	endElement(const XMLCh* const	name);

    virtual void
	characters(
			const XMLCh* const	chars,
			const unsigned int	length);

    virtual void
	charactersRaw(
			const XMLCh* const	chars,
			const unsigned int	length);

	virtual void
	entityReference(const XMLCh* const	name);

	virtual void
	ignorableWhitespace(
			const XMLCh* const	chars,
			const unsigned int	length);

	virtual void
	processingInstruction(
			const XMLCh* const	target,
			const XMLCh* const	data);

	virtual void
	resetDocument();

	virtual void
	comment(const XMLCh* const	data);

	virtual void
	cdata(
			const XMLCh* const	ch,
			const unsigned int 	length);

private:

	// These are not implemented.
	FormatterStringLengthCounter(const FormatterStringLengthCounter&);

	FormatterStringLengthCounter&
	operator=(const FormatterStringLengthCounter&);

	bool
	operator==(const FormatterStringLengthCounter&) const;

	// Data members...
	size_type	m_count;
};

XALAN_CPP_NAMESPACE_END

#endif	// FORMATTERSTRINGLENGTHCOUNTER_HEADER_GUARD_1357924680
<commit_msg>Use typedef.<commit_after>/*
 * The Apache Software License, Version 1.1
 *
 *
 * Copyright (c) 1999-2002 The Apache Software Foundation.  All rights
 * reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions
 * are met:
 *
 * 1. Redistributions of source code must retain the above copyright
 *    notice, this list of conditions and the following disclaimer.
 *
 * 2. Redistributions in binary form must reproduce the above copyright
 *    notice, this list of conditions and the following disclaimer in
 *    the documentation and/or other materials provided with the
 *    distribution.
 *
 * 3. The end-user documentation included with the redistribution,
 *    if any, must include the following acknowledgment:
 *       "This product includes software developed by the
 *        Apache Software Foundation (http://www.apache.org/)."
 *    Alternately, this acknowledgment may appear in the software itself,
 *    if and wherever such third-party acknowledgments normally appear.
 *
 * 4. The names "Xalan" and "Apache Software Foundation" must
 *    not be used to endorse or promote products derived from this
 *    software without prior written permission. For written
 *    permission, please contact apache@apache.org.
 *
 * 5. Products derived from this software may not be called "Apache",
 *    nor may "Apache" appear in their name, without prior written
 *    permission of the Apache Software Foundation.
 *
 * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED
 * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
 * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
 * DISCLAIMED.  IN NO EVENT SHALL THE APACHE SOFTWARE FOUNDATION OR
 * ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
 * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
 * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF
 * USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
 * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
 * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
 * OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
 * SUCH DAMAGE.
 * ====================================================================
 *
 * This software consists of voluntary contributions made by many
 * individuals on behalf of the Apache Software Foundation and was
 * originally based on software copyright (c) 1999, International
 * Business Machines, Inc., http://www.ibm.com.  For more
 * information on the Apache Software Foundation, please see
 * <http://www.apache.org/>.
 */
#if !defined(FORMATTERSTRINGLENGTHCOUNTER_HEADER_GUARD_1357924680)
#define FORMATTERSTRINGLENGTHCOUNTER_HEADER_GUARD_1357924680

// Base include file.  Must be first.
#include <XPath/XPathDefinitions.hpp>

// Base class header file.
#include <PlatformSupport/FormatterListener.hpp>

XALAN_CPP_NAMESPACE_BEGIN

/**
 * This class takes SAX events (in addition to some extra events
 * that SAX doesn't handle yet) and produces counts the characters
 * sent to the characters event.
 */
class XALAN_XPATH_EXPORT FormatterStringLengthCounter : public FormatterListener
{
public:

	typedef unsigned long	size_type;

	/**
	 * FormatterStringLengthCounter instance constructor.
	 */
	explicit
	FormatterStringLengthCounter();

	virtual
	~FormatterStringLengthCounter();

	size_type
	getCount() const
	{
		return m_count;
	}

	// These methods are inherited from FormatterListener ...

	virtual void
	setDocumentLocator(const LocatorType* const		locator);

	virtual void
	startDocument();

	virtual void
	endDocument();

	virtual void
	startElement(
			const XMLCh* const	name,
			AttributeListType&	attrs);

    virtual void
	endElement(const XMLCh* const	name);

    virtual void
	characters(
			const XMLCh* const	chars,
			const unsigned int	length);

    virtual void
	charactersRaw(
			const XMLCh* const	chars,
			const unsigned int	length);

	virtual void
	entityReference(const XMLCh* const	name);

	virtual void
	ignorableWhitespace(
			const XMLCh* const	chars,
			const unsigned int	length);

	virtual void
	processingInstruction(
			const XMLCh* const	target,
			const XMLCh* const	data);

	virtual void
	resetDocument();

	virtual void
	comment(const XMLCh* const	data);

	virtual void
	cdata(
			const XMLCh* const	ch,
			const unsigned int 	length);

private:

	// These are not implemented.
	FormatterStringLengthCounter(const FormatterStringLengthCounter&);

	FormatterStringLengthCounter&
	operator=(const FormatterStringLengthCounter&);

	bool
	operator==(const FormatterStringLengthCounter&) const;

	// Data members...
	size_type	m_count;
};

XALAN_CPP_NAMESPACE_END

#endif	// FORMATTERSTRINGLENGTHCOUNTER_HEADER_GUARD_1357924680
<|endoftext|>


<commit_before>// This file is part of the AliceVision project.
// Copyright (c) 2016 AliceVision contributors.
// Copyright (c) 2012 openMVG contributors.
// This Source Code Form is subject to the terms of the Mozilla Public License,
// v. 2.0. If a copy of the MPL was not distributed with this file,
// You can obtain one at https://mozilla.org/MPL/2.0/.

#pragma once

#include <aliceVision/numeric/numeric.hpp>
#include <aliceVision/feature/imageDescriberCommon.hpp>
#include <aliceVision/feature/Regions.hpp>
#include <aliceVision/image/Image.hpp>
#include <memory>

#include <string>
#include <iostream>

namespace aliceVision {
namespace feature {

/**
 * @brief The preset to control the number of detected regions
 */
enum class EImageDescriberPreset
{
  LOW = 0
  , MEDIUM
  , NORMAL
  , HIGH
  , ULTRA
};

/**
 * @brief It returns the preset from a string.
 * @param[in] imageDescriberPreset the input string.
 * @return the associated describer preset.
 */
EImageDescriberPreset EImageDescriberPreset_stringToEnum(const std::string& imageDescriberPreset);

/**
 * @brief It converts a preset to a string.
 * @param[in] imageDescriberPreset the describer preset enum to convert.
 * @return the string associated to the describer preset.
 */
std::string EImageDescriberPreset_enumToString(const EImageDescriberPreset imageDescriberPreset);

/**
 * @brief It write a describer preset into a stream by converting it to a string.
 * @param[in] os the stream where to write the preset.
 * @param[in] p the preset to write.
 * @return the modified stream.
 */
std::ostream& operator<<(std::ostream& os, EImageDescriberPreset p);

/**
 * @brief It read a describer preset from a stream.
 * @param[in] in the stream from which the preset is read.
 * @param[out] p the preset read from the stream.
 * @return the modified stream without the read preset.
 */
std::istream& operator>>(std::istream& in, EImageDescriberPreset& p);

/**
 * @brief A pure virtual class for image description computation
 */
class ImageDescriber
{
public:
  ImageDescriber() {}

  virtual ~ImageDescriber() {}

  /**
   * @brief Check if the image describer use CUDA
   * @return True if the image describer use CUDA
   */
  virtual bool useCuda() const = 0;

  /**
   * @brief Check if the image describer use float image
   * @return True if the image describer use float image
   */
  virtual bool useFloatImage() const = 0;

  /**
   * @brief Get the corresponding EImageDescriberType
   * @return EImageDescriberType
   */
  virtual EImageDescriberType getDescriberType() const = 0;

  /**
   * @brief Get the total amount of RAM needed for a
   * feature extraction of an image of the given dimension.
   * @param[in] width The image width
   * @param[in] height The image height
   * @return total amount of memory needed
   */
  virtual std::size_t getMemoryConsumption(std::size_t width, std::size_t height) const = 0;

  /**
   * @brief Set image describer always upRight
   * @param[in] upRight
   */
  virtual void setUpRight(bool upRight) {}

  /**
   * @brief Set if yes or no imageDescriber need to use cuda implementation
   * @param[in] useCuda
   */
  virtual void setUseCuda(bool useCuda) {}

  /**
   * @brief set the CUDA pipe
   * @param[in] pipe The CUDA pipe id
   */
  virtual void setCudaPipe(int pipe) {}

  /**
   * @brief Use a preset to control the number of detected regions
   * @param[in] preset The preset configuration
   */
  virtual void setConfigurationPreset(EImageDescriberPreset preset) = 0;

  /**
   * @brief Use a preset to control the number of detected regions
   * @param[in] preset The preset configuration string
   */
  void setConfigurationPreset(const std::string& preset)
  {
    setConfigurationPreset(EImageDescriberPreset_stringToEnum(preset));
  }

  /**
   * @brief Detect regions on the 8-bit image and compute their attributes (description)
   * @param[in] image Image.
   * @param[out] regions The detected regions and attributes
   * @param[in] mask 8-bit grayscale image for keypoint filtering (optional)
   * Non-zero values depict the region of interest.
   */
  virtual bool describe(const image::Image<unsigned char>& image,
                        std::unique_ptr<Regions>& regions,
                        const image::Image<unsigned char>* mask = nullptr)
  {
    throw std::logic_error("Can't use" + EImageDescriberType_enumToString(getDescriberType()) + " image describer with an 8-bit image.");
    return false;
  }

  /**
   * @brief Detect regions on the float image and compute their attributes (description)
   * @param[in] image Image.
   * @param[out] regions The detected regions and attributes
   * @param[in] mask 8-bit grayscale image for keypoint filtering (optional)
   * Non-zero values depict the region of interest.
   */
  virtual bool describe(const image::Image<float>& image,
                        std::unique_ptr<Regions>& regions,
                        const image::Image<unsigned char>* mask = nullptr)
  {
    throw std::logic_error("Can't use" + EImageDescriberType_enumToString(getDescriberType()) + " image describer with a float image.");
    return false;
  }

  /**
   * @brief Allocate Regions type depending of the ImageDescriber
   * @param[in,out] regions
   */
  virtual void allocate(std::unique_ptr<Regions>& regions) const = 0;

  // IO - one file for region features, one file for region descriptors

  void Load(Regions* regions,
    const std::string& sfileNameFeats,
    const std::string& sfileNameDescs) const
  {
    regions->Load(sfileNameFeats, sfileNameDescs);
  }

  void Save(const Regions* regions,
    const std::string& sfileNameFeats,
    const std::string& sfileNameDescs) const;

  void LoadFeatures(Regions* regions,
    const std::string& sfileNameFeats) const
  {
    regions->LoadFeatures(sfileNameFeats);
  }
};

/**
 * @brief Create the desired ImageDescriber method.
 * Don't use a factory, perform direct allocation.
 */
std::unique_ptr<ImageDescriber> createImageDescriber(EImageDescriberType imageDescriberType);

} // namespace feature
} // namespace aliceVision
<commit_msg>[feature] `ImageDescriber` fix exception message<commit_after>// This file is part of the AliceVision project.
// Copyright (c) 2016 AliceVision contributors.
// Copyright (c) 2012 openMVG contributors.
// This Source Code Form is subject to the terms of the Mozilla Public License,
// v. 2.0. If a copy of the MPL was not distributed with this file,
// You can obtain one at https://mozilla.org/MPL/2.0/.

#pragma once

#include <aliceVision/numeric/numeric.hpp>
#include <aliceVision/feature/imageDescriberCommon.hpp>
#include <aliceVision/feature/Regions.hpp>
#include <aliceVision/image/Image.hpp>
#include <memory>

#include <string>
#include <iostream>

namespace aliceVision {
namespace feature {

/**
 * @brief The preset to control the number of detected regions
 */
enum class EImageDescriberPreset
{
  LOW = 0
  , MEDIUM
  , NORMAL
  , HIGH
  , ULTRA
};

/**
 * @brief It returns the preset from a string.
 * @param[in] imageDescriberPreset the input string.
 * @return the associated describer preset.
 */
EImageDescriberPreset EImageDescriberPreset_stringToEnum(const std::string& imageDescriberPreset);

/**
 * @brief It converts a preset to a string.
 * @param[in] imageDescriberPreset the describer preset enum to convert.
 * @return the string associated to the describer preset.
 */
std::string EImageDescriberPreset_enumToString(const EImageDescriberPreset imageDescriberPreset);

/**
 * @brief It write a describer preset into a stream by converting it to a string.
 * @param[in] os the stream where to write the preset.
 * @param[in] p the preset to write.
 * @return the modified stream.
 */
std::ostream& operator<<(std::ostream& os, EImageDescriberPreset p);

/**
 * @brief It read a describer preset from a stream.
 * @param[in] in the stream from which the preset is read.
 * @param[out] p the preset read from the stream.
 * @return the modified stream without the read preset.
 */
std::istream& operator>>(std::istream& in, EImageDescriberPreset& p);

/**
 * @brief A pure virtual class for image description computation
 */
class ImageDescriber
{
public:
  ImageDescriber() {}

  virtual ~ImageDescriber() {}

  /**
   * @brief Check if the image describer use CUDA
   * @return True if the image describer use CUDA
   */
  virtual bool useCuda() const = 0;

  /**
   * @brief Check if the image describer use float image
   * @return True if the image describer use float image
   */
  virtual bool useFloatImage() const = 0;

  /**
   * @brief Get the corresponding EImageDescriberType
   * @return EImageDescriberType
   */
  virtual EImageDescriberType getDescriberType() const = 0;

  /**
   * @brief Get the total amount of RAM needed for a
   * feature extraction of an image of the given dimension.
   * @param[in] width The image width
   * @param[in] height The image height
   * @return total amount of memory needed
   */
  virtual std::size_t getMemoryConsumption(std::size_t width, std::size_t height) const = 0;

  /**
   * @brief Set image describer always upRight
   * @param[in] upRight
   */
  virtual void setUpRight(bool upRight) {}

  /**
   * @brief Set if yes or no imageDescriber need to use cuda implementation
   * @param[in] useCuda
   */
  virtual void setUseCuda(bool useCuda) {}

  /**
   * @brief set the CUDA pipe
   * @param[in] pipe The CUDA pipe id
   */
  virtual void setCudaPipe(int pipe) {}

  /**
   * @brief Use a preset to control the number of detected regions
   * @param[in] preset The preset configuration
   */
  virtual void setConfigurationPreset(EImageDescriberPreset preset) = 0;

  /**
   * @brief Use a preset to control the number of detected regions
   * @param[in] preset The preset configuration string
   */
  void setConfigurationPreset(const std::string& preset)
  {
    setConfigurationPreset(EImageDescriberPreset_stringToEnum(preset));
  }

  /**
   * @brief Detect regions on the 8-bit image and compute their attributes (description)
   * @param[in] image Image.
   * @param[out] regions The detected regions and attributes
   * @param[in] mask 8-bit grayscale image for keypoint filtering (optional)
   * Non-zero values depict the region of interest.
   */
  virtual bool describe(const image::Image<unsigned char>& image,
                        std::unique_ptr<Regions>& regions,
                        const image::Image<unsigned char>* mask = nullptr)
  {
    throw std::logic_error("Can't use " + EImageDescriberType_enumToString(getDescriberType()) + " image describer with an 8-bit image.");
    return false;
  }

  /**
   * @brief Detect regions on the float image and compute their attributes (description)
   * @param[in] image Image.
   * @param[out] regions The detected regions and attributes
   * @param[in] mask 8-bit grayscale image for keypoint filtering (optional)
   * Non-zero values depict the region of interest.
   */
  virtual bool describe(const image::Image<float>& image,
                        std::unique_ptr<Regions>& regions,
                        const image::Image<unsigned char>* mask = nullptr)
  {
    throw std::logic_error("Can't use " + EImageDescriberType_enumToString(getDescriberType()) + " image describer with a float image.");
    return false;
  }

  /**
   * @brief Allocate Regions type depending of the ImageDescriber
   * @param[in,out] regions
   */
  virtual void allocate(std::unique_ptr<Regions>& regions) const = 0;

  // IO - one file for region features, one file for region descriptors

  void Load(Regions* regions,
    const std::string& sfileNameFeats,
    const std::string& sfileNameDescs) const
  {
    regions->Load(sfileNameFeats, sfileNameDescs);
  }

  void Save(const Regions* regions,
    const std::string& sfileNameFeats,
    const std::string& sfileNameDescs) const;

  void LoadFeatures(Regions* regions,
    const std::string& sfileNameFeats) const
  {
    regions->LoadFeatures(sfileNameFeats);
  }
};

/**
 * @brief Create the desired ImageDescriber method.
 * Don't use a factory, perform direct allocation.
 */
std::unique_ptr<ImageDescriber> createImageDescriber(EImageDescriberType imageDescriberType);

} // namespace feature
} // namespace aliceVision
<|endoftext|>


<commit_before>/*
   (c) Copyright 2012-2013  DirectFB integrated media GmbH
   (c) Copyright 2001-2013  The world wide DirectFB Open Source Community (directfb.org)
   (c) Copyright 2000-2004  Convergence (integrated media) GmbH

   All rights reserved.

   Written by Denis Oliver Kropp <dok@directfb.org>,
              Andreas Hundt <andi@fischlustig.de>,
              Sven Neumann <neo@directfb.org>,
              Ville Syrjälä <syrjala@sci.fi> and
              Claudio Ciccani <klan@users.sf.net>.

   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.
*/

//#define DIRECT_ENABLE_DEBUG

#include <config.h>

extern "C" {
#include <direct/messages.h>
}

#include <direct/ToString.h>

#include "DIRECTFB_GetConfigAttribs.h"

D_LOG_DOMAIN( DFBEGL_GetConfigAttribs, "DFBEGL/GetConfigAttribs", "DirectFB EGL GetConfigAttribs extension" );

using namespace std::placeholders;

namespace DirectFB {

namespace EGL {

/**********************************************************************************************************************/

static GetConfigAttribs get_config_attribs;

/**********************************************************************************************************************/
/**********************************************************************************************************************/

GetConfigAttribs::GetConfigAttribs()
{
     D_DEBUG_AT( DFBEGL_GetConfigAttribs, "GetConfigAttribs::%s( %p )\n", __FUNCTION__, this );

     DirectFB::EGL::Display::Register< DirectFB::EGL::EGLExtension::GetNames >( "GetNames",
                                                                                [](){ return "EGL_DIRECTFB_get_config_attribs";},
                                                                                GetName() );

     DirectFB::EGL::Core::Register< DirectFB::EGL::Core::GetProcAddress >( "GetProcAddress",
                                                                           [](const char *){ return (void*) eglGetConfigAttribsDIRECTFB;},
                                                                           "eglGetConfigAttribsDIRECTFB" );

     DirectFB::EGL::Display::Register< GetConfigAttribsDIRECTFB >( "GetConfigAttribsDIRECTFB",
                                                                   std::bind( &GetConfigAttribs::eglGetConfigAttribs, this, _1, _2, _3, _4 ),
                                                                   "" );
}

GetConfigAttribs::~GetConfigAttribs()
{
     D_DEBUG_AT( DFBEGL_GetConfigAttribs, "GetConfigAttribs::%s( %p )\n", __FUNCTION__, this );
}

/**********************************************************************************************************************/

EGLBoolean
GetConfigAttribs::eglGetConfigAttribsDIRECTFB( EGLDisplay           dpy,
                                               EGLNativePixmapType  native,
                                               EGLint              *attribs,
                                               EGLint               max )
{
     D_DEBUG_AT( DFBEGL_GetConfigAttribs, "%s( display %p, native %p, attribs %p, max %d )\n", __FUNCTION__, dpy, native, attribs, max );

     DirectFB::EGL::TLS *tls = DirectFB::EGLTLS.Get();

     if (!dpy)
          DFB_EGL_RETURN (EGL_BAD_DISPLAY, EGL_FALSE);

     if (!attribs)
          DFB_EGL_RETURN (EGL_BAD_PARAMETER, EGL_FALSE);

     DirectFB::EGL::Display *display = (DirectFB::EGL::Display*) dpy;

     DFBResult ret = DirectFB::EGL::Display::Call< GetConfigAttribsDIRECTFB >( "GetConfigAttribsDIRECTFB", "" )( *display, native, attribs, max );

     if (ret)
          DFB_EGL_RETURN (EGL_BAD_PARAMETER, EGL_FALSE);

     DFB_EGL_RETURN (EGL_SUCCESS, EGL_TRUE);
}

DFBResult
GetConfigAttribs::eglGetConfigAttribs( EGL::Display        &display,
                                       EGLNativePixmapType  native,
                                       EGLint              *attribs,
                                       EGLint               max )
{
     D_DEBUG_AT( DFBEGL_GetConfigAttribs, "%s( display %p, native %p, attribs %p, max %d )\n", __FUNCTION__, &display, native, attribs, max );

     if (!attribs)
          return DFB_INVARG;

     DFB_EGL_ATTRIB_LIST_DEBUG_AT( DFBEGL_GetConfigAttribs, attribs );

     IDirectFBSurface *surface = (IDirectFBSurface *) native;

     for (EGLint *v=attribs; *v != EGL_NONE; v+=2) {
          if (max > 0 && v-attribs >= max) {
               D_DEBUG_AT( DFBEGL_GetConfigAttribs, "  -> max (%d) reached (%ld)\n", max, v-attribs );
               break;
          }

          EGLint                attribute = v[0];
          EGLint                value     = v[1];
          DFBSurfacePixelFormat format;
          DFBDimension          size;

          D_DEBUG_AT( DFBEGL_GetConfigAttribs, "  -> [%ld] 0x%04x '%s'  <- %d (0x%08x)\n", v-attribs, attribute, **EGLInt(attribute), value, value );

          switch (attribute) {
          case EGL_BUFFER_SIZE:
               surface->GetPixelFormat( surface, &format );
               value = DFB_COLOR_BITS_PER_PIXEL( format );
               break;

          case EGL_ALPHA_SIZE:
               surface->GetPixelFormat( surface, &format );
               value = DFB_ALPHA_BITS_PER_PIXEL( format );
               break;

          case EGL_BLUE_SIZE:
          case EGL_GREEN_SIZE:
          case EGL_RED_SIZE:
               surface->GetPixelFormat( surface, &format );
               value = DFB_COLOR_BITS_PER_PIXEL( format ) / 3;//FIXME
               break;

          //case EGL_DEPTH_SIZE:
          //case EGL_STENCIL_SIZE:
          //case EGL_RENDERABLE_TYPE:

          case EGL_SURFACE_TYPE:
               value = EGL_WINDOW_BIT;  // FIXME
               break;

          case EGL_WIDTH:     // keep? not a config attribute actually
               surface->GetSize( surface, &size.w, &size.h );
               value = size.w;
               break;

          case EGL_HEIGHT:    // keep? not a config attribute actually
               surface->GetSize( surface, &size.w, &size.h );
               value = size.h;
               break;

          default:
               D_DEBUG_AT( DFBEGL_GetConfigAttribs, "  -> UNRECOGNIZED!!!\n" );
               continue;
          }

          D_DEBUG_AT( DFBEGL_GetConfigAttribs, "            => %d (0x%08x)\n", value, value );

          v[1] = value;
     }

     D_DEBUG_AT( DFBEGL_GetConfigAttribs, " --> DONE -------------\n" );

     DFB_EGL_ATTRIB_LIST_DEBUG_AT( DFBEGL_GetConfigAttribs, attribs );

     return DFB_OK;
}

}

}

<commit_msg>libegl: fix warnings<commit_after>/*
   (c) Copyright 2012-2013  DirectFB integrated media GmbH
   (c) Copyright 2001-2013  The world wide DirectFB Open Source Community (directfb.org)
   (c) Copyright 2000-2004  Convergence (integrated media) GmbH

   All rights reserved.

   Written by Denis Oliver Kropp <dok@directfb.org>,
              Andreas Hundt <andi@fischlustig.de>,
              Sven Neumann <neo@directfb.org>,
              Ville Syrjälä <syrjala@sci.fi> and
              Claudio Ciccani <klan@users.sf.net>.

   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.
*/

//#define DIRECT_ENABLE_DEBUG

#include <config.h>

extern "C" {
#include <direct/messages.h>
}

#include <direct/ToString.h>

#include "DIRECTFB_GetConfigAttribs.h"

D_LOG_DOMAIN( DFBEGL_GetConfigAttribs, "DFBEGL/GetConfigAttribs", "DirectFB EGL GetConfigAttribs extension" );

using namespace std::placeholders;

namespace DirectFB {

namespace EGL {

/**********************************************************************************************************************/

static GetConfigAttribs get_config_attribs;

/**********************************************************************************************************************/
/**********************************************************************************************************************/

GetConfigAttribs::GetConfigAttribs()
{
     D_DEBUG_AT( DFBEGL_GetConfigAttribs, "GetConfigAttribs::%s( %p )\n", __FUNCTION__, this );

     DirectFB::EGL::Display::Register< DirectFB::EGL::EGLExtension::GetNames >( "GetNames",
                                                                                [](){ return "EGL_DIRECTFB_get_config_attribs";},
                                                                                GetName() );

     DirectFB::EGL::Core::Register< DirectFB::EGL::Core::GetProcAddress >( "GetProcAddress",
                                                                           [](const char *){ return (void*) eglGetConfigAttribsDIRECTFB;},
                                                                           "eglGetConfigAttribsDIRECTFB" );

     DirectFB::EGL::Display::Register< GetConfigAttribsDIRECTFB >( "GetConfigAttribsDIRECTFB",
                                                                   std::bind( &GetConfigAttribs::eglGetConfigAttribs, this, _1, _2, _3, _4 ),
                                                                   "" );
}

GetConfigAttribs::~GetConfigAttribs()
{
     D_DEBUG_AT( DFBEGL_GetConfigAttribs, "GetConfigAttribs::%s( %p )\n", __FUNCTION__, this );
}

/**********************************************************************************************************************/

EGLBoolean
GetConfigAttribs::eglGetConfigAttribsDIRECTFB( EGLDisplay           dpy,
                                               EGLNativePixmapType  native,
                                               EGLint              *attribs,
                                               EGLint               max )
{
     D_DEBUG_AT( DFBEGL_GetConfigAttribs, "%s( display %p, native %p, attribs %p, max %d )\n", __FUNCTION__, dpy, native, attribs, max );

     DirectFB::EGL::TLS *tls = DirectFB::EGLTLS.Get();

     if (!dpy)
          DFB_EGL_RETURN (EGL_BAD_DISPLAY, EGL_FALSE);

     if (!attribs)
          DFB_EGL_RETURN (EGL_BAD_PARAMETER, EGL_FALSE);

     DirectFB::EGL::Display *display = (DirectFB::EGL::Display*) dpy;

     DFBResult ret = DirectFB::EGL::Display::Call< GetConfigAttribsDIRECTFB >( "GetConfigAttribsDIRECTFB", "" )( *display, native, attribs, max );

     if (ret)
          DFB_EGL_RETURN (EGL_BAD_PARAMETER, EGL_FALSE);

     DFB_EGL_RETURN (EGL_SUCCESS, EGL_TRUE);
}

DFBResult
GetConfigAttribs::eglGetConfigAttribs( EGL::Display        &display,
                                       EGLNativePixmapType  native,
                                       EGLint              *attribs,
                                       EGLint               max )
{
     D_DEBUG_AT( DFBEGL_GetConfigAttribs, "%s( display %p, native %p, attribs %p, max %d )\n", __FUNCTION__, &display, native, attribs, max );

     if (!attribs)
          return DFB_INVARG;

     DFB_EGL_ATTRIB_LIST_DEBUG_AT( DFBEGL_GetConfigAttribs, attribs );

     IDirectFBSurface *surface = (IDirectFBSurface *) native;

     for (EGLint *v=attribs; *v != EGL_NONE; v+=2) {
          if (max > 0 && v-attribs >= max) {
               D_DEBUG_AT( DFBEGL_GetConfigAttribs, "  -> max (%d) reached (%zd)\n", max, v-attribs );
               break;
          }

          EGLint                attribute = v[0];
          EGLint                value     = v[1];
          DFBSurfacePixelFormat format;
          DFBDimension          size;

          D_DEBUG_AT( DFBEGL_GetConfigAttribs, "  -> [%zd] 0x%04x '%s'  <- %d (0x%08x)\n", v-attribs, attribute, **EGLInt(attribute), value, value );

          switch (attribute) {
          case EGL_BUFFER_SIZE:
               surface->GetPixelFormat( surface, &format );
               value = DFB_COLOR_BITS_PER_PIXEL( format );
               break;

          case EGL_ALPHA_SIZE:
               surface->GetPixelFormat( surface, &format );
               value = DFB_ALPHA_BITS_PER_PIXEL( format );
               break;

          case EGL_BLUE_SIZE:
          case EGL_GREEN_SIZE:
          case EGL_RED_SIZE:
               surface->GetPixelFormat( surface, &format );
               value = DFB_COLOR_BITS_PER_PIXEL( format ) / 3;//FIXME
               break;

          //case EGL_DEPTH_SIZE:
          //case EGL_STENCIL_SIZE:
          //case EGL_RENDERABLE_TYPE:

          case EGL_SURFACE_TYPE:
               value = EGL_WINDOW_BIT;  // FIXME
               break;

          case EGL_WIDTH:     // keep? not a config attribute actually
               surface->GetSize( surface, &size.w, &size.h );
               value = size.w;
               break;

          case EGL_HEIGHT:    // keep? not a config attribute actually
               surface->GetSize( surface, &size.w, &size.h );
               value = size.h;
               break;

          default:
               D_DEBUG_AT( DFBEGL_GetConfigAttribs, "  -> UNRECOGNIZED!!!\n" );
               continue;
          }

          D_DEBUG_AT( DFBEGL_GetConfigAttribs, "            => %d (0x%08x)\n", value, value );

          v[1] = value;
     }

     D_DEBUG_AT( DFBEGL_GetConfigAttribs, " --> DONE -------------\n" );

     DFB_EGL_ATTRIB_LIST_DEBUG_AT( DFBEGL_GetConfigAttribs, attribs );

     return DFB_OK;
}

}

}

<|endoftext|>


<commit_before>/*
 * This file is part of the OpenKinect Project. http://www.openkinect.org
 *
 * Copyright (c) 2011 individual OpenKinect contributors. See the CONTRIB file
 * for details.
 *
 * This code is licensed to you under the terms of the Apache License, version
 * 2.0, or, at your option, the terms of the GNU General Public License,
 * version 2.0. See the APACHE20 and GPL2 files for the text of the licenses,
 * or the following URLs:
 * http://www.apache.org/licenses/LICENSE-2.0
 * http://www.gnu.org/licenses/gpl-2.0.txt
 *
 * If you redistribute this file in source form, modified or unmodified, you
 * may:
 *   1) Leave this header intact and distribute it under the same terms,
 *      accompanying it with the APACHE20 and GPL20 files, or
 *   2) Delete the Apache 2.0 clause and accompany it with the GPL2 file, or
 *   3) Delete the GPL v2 clause and accompany it with the APACHE20 file
 * In all cases you must keep the copyright notice intact and include a copy
 * of the CONTRIB file.
 *
 * Binary distributions must follow the binary distribution requirements of
 * either License.
 */

/** @file Protonect.cpp Main application file. */

#include <iostream>
#include <cstdlib>
#include <signal.h>

/// [headers]
#include <libfreenect2/libfreenect2.hpp>
#include <libfreenect2/frame_listener_impl.h>
#include <libfreenect2/registration.h>
#include <libfreenect2/packet_pipeline.h>
#include <libfreenect2/logger.h>
/// [headers]
#ifdef EXAMPLES_WITH_OPENGL_SUPPORT
#include "viewer.h"
#endif

bool protonect_shutdown = false; ///< Whether the running application should shut down.

void sigint_handler(int s)
{
  protonect_shutdown = true;
}

bool protonect_paused = false;
libfreenect2::Freenect2Device *devtopause;

//Doing non-trivial things in signal handler is bad. If you want to pause,
//do it in another thread.
//Though libusb operations are generally thread safe, I cannot guarantee
//everything above is thread safe when calling start()/stop() while
//waitForNewFrame().
void sigusr1_handler(int s)
{
  if (devtopause == 0)
    return;
/// [pause]
  if (protonect_paused)
    devtopause->start();
  else
    devtopause->stop();
  protonect_paused = !protonect_paused;
/// [pause]
}

//The following demostrates how to create a custom logger
/// [logger]
#include <fstream>
#include <cstdlib>
class MyFileLogger: public libfreenect2::Logger
{
private:
  std::ofstream logfile_;
public:
  MyFileLogger(const char *filename)
  {
    if (filename)
      logfile_.open(filename);
    level_ = Debug;
  }
  bool good()
  {
    return logfile_.is_open() && logfile_.good();
  }
  virtual void log(Level level, const std::string &message)
  {
    logfile_ << "[" << libfreenect2::Logger::level2str(level) << "] " << message << std::endl;
  }
};
/// [logger]

/// [main]
/**
 * Main application entry point.
 *
 * Accepted argumemnts:
 * - cpu Perform depth processing with the CPU.
 * - gl  Perform depth processing with OpenGL.
 * - cl  Perform depth processing with OpenCL.
 * - <number> Serial number of the device to open.
 * - -noviewer Disable viewer window.
 */
int main(int argc, char *argv[])
/// [main]
{
  std::string program_path(argv[0]);
  std::cerr << "Version: " << LIBFREENECT2_VERSION << std::endl;
  std::cerr << "Environment variables: LOGFILE=<protonect.log>" << std::endl;
  std::cerr << "Usage: " << program_path << " [-gpu=<id>] [gl | cl | clkde | cuda | cudakde | cpu] [<device serial>]" << std::endl;
  std::cerr << "        [-noviewer] [-norgb | -nodepth] [-help] [-version]" << std::endl;
  std::cerr << "        [-frames <number of frames to process>]" << std::endl;
  std::cerr << "To pause and unpause: pkill -USR1 Protonect" << std::endl;
  size_t executable_name_idx = program_path.rfind("Protonect");

  std::string binpath = "/";

  if(executable_name_idx != std::string::npos)
  {
    binpath = program_path.substr(0, executable_name_idx);
  }

#if defined(WIN32) || defined(_WIN32) || defined(__WIN32__)
  // avoid flooing the very slow Windows console with debug messages
  libfreenect2::setGlobalLogger(libfreenect2::createConsoleLogger(libfreenect2::Logger::Info));
#else
  // create a console logger with debug level (default is console logger with info level)
/// [logging]
  libfreenect2::setGlobalLogger(libfreenect2::createConsoleLogger(libfreenect2::Logger::Debug));
/// [logging]
#endif
/// [file logging]
  MyFileLogger *filelogger = new MyFileLogger(getenv("LOGFILE"));
  if (filelogger->good())
    libfreenect2::setGlobalLogger(filelogger);
  else
    delete filelogger;
/// [file logging]

/// [context]
  libfreenect2::Freenect2 freenect2;
  libfreenect2::Freenect2Device *dev = 0;
  libfreenect2::PacketPipeline *pipeline = 0;
/// [context]

  std::string serial = "";

  bool viewer_enabled = true;
  bool enable_rgb = true;
  bool enable_depth = true;
  int deviceId = -1;
  size_t framemax = -1;

  for(int argI = 1; argI < argc; ++argI)
  {
    const std::string arg(argv[argI]);

    if(arg == "-help" || arg == "--help" || arg == "-h" || arg == "-v" || arg == "--version" || arg == "-version")
    {
      // Just let the initial lines display at the beginning of main
      return 0;
    }
    else if(arg.find("-gpu=") == 0)
    {
      if (pipeline)
      {
        std::cerr << "-gpu must be specified before pipeline argument" << std::endl;
        return -1;
      }
      deviceId = atoi(argv[argI] + 5);
    }
    else if(arg == "cpu")
    {
      if(!pipeline)
/// [pipeline]
        pipeline = new libfreenect2::CpuPacketPipeline();
/// [pipeline]
    }
    else if(arg == "gl")
    {
#ifdef LIBFREENECT2_WITH_OPENGL_SUPPORT
      if(!pipeline)
        pipeline = new libfreenect2::OpenGLPacketPipeline();
#else
      std::cout << "OpenGL pipeline is not supported!" << std::endl;
#endif
    }
    else if(arg == "cl")
    {
#ifdef LIBFREENECT2_WITH_OPENCL_SUPPORT
      if(!pipeline)
        pipeline = new libfreenect2::OpenCLPacketPipeline(deviceId);
#else
      std::cout << "OpenCL pipeline is not supported!" << std::endl;
#endif
    }
    else if(arg == "clkde")
    {
#ifdef LIBFREENECT2_WITH_OPENCL_SUPPORT
      if(!pipeline)
        pipeline = new libfreenect2::OpenCLKdePacketPipeline(deviceId);
#else
      std::cout << "OpenCL pipeline is not supported!" << std::endl;
#endif
    }
    else if(arg == "cuda")
    {
#ifdef LIBFREENECT2_WITH_CUDA_SUPPORT
      if(!pipeline)
        pipeline = new libfreenect2::CudaPacketPipeline(deviceId);
#else
      std::cout << "CUDA pipeline is not supported!" << std::endl;
#endif
    }
    else if(arg == "cudakde")
    {
#ifdef LIBFREENECT2_WITH_CUDA_SUPPORT
      if(!pipeline)
        pipeline = new libfreenect2::CudaKdePacketPipeline(deviceId);
#else
      std::cout << "CUDA pipeline is not supported!" << std::endl;
#endif
    }
    else if(arg.find_first_not_of("0123456789") == std::string::npos) //check if parameter could be a serial number
    {
      serial = arg;
    }
    else if(arg == "-noviewer" || arg == "--noviewer")
    {
      viewer_enabled = false;
    }
    else if(arg == "-norgb" || arg == "--norgb")
    {
      enable_rgb = false;
    }
    else if(arg == "-nodepth" || arg == "--nodepth")
    {
      enable_depth = false;
    }
    else if(arg == "-frames")
    {
      ++argI;
      framemax = strtol(argv[argI], NULL, 0);
      if (framemax == 0) {
        std::cerr << "invalid frame count '" << argv[argI] << "'" << std::endl;
        return -1;
      }
    }
    else
    {
      std::cout << "Unknown argument: " << arg << std::endl;
    }
  }

  if (!enable_rgb && !enable_depth)
  {
    std::cerr << "Disabling both streams is not allowed!" << std::endl;
    return -1;
  }

/// [discovery]
  if(freenect2.enumerateDevices() == 0)
  {
    std::cout << "no device connected!" << std::endl;
    return -1;
  }

  if (serial == "")
  {
    serial = freenect2.getDefaultDeviceSerialNumber();
  }
/// [discovery]

  if(pipeline)
  {
/// [open]
    dev = freenect2.openDevice(serial, pipeline);
/// [open]
  }
  else
  {
    dev = freenect2.openDevice(serial);
  }

  if(dev == 0)
  {
    std::cout << "failure opening device!" << std::endl;
    return -1;
  }

  devtopause = dev;

  signal(SIGINT,sigint_handler);
#ifdef SIGUSR1
  signal(SIGUSR1, sigusr1_handler);
#endif
  protonect_shutdown = false;

/// [listeners]
  int types = 0;
  if (enable_rgb)
    types |= libfreenect2::Frame::Color;
  if (enable_depth)
    types |= libfreenect2::Frame::Ir | libfreenect2::Frame::Depth;
  libfreenect2::SyncMultiFrameListener listener(types);
  libfreenect2::FrameMap frames;

  dev->setColorFrameListener(&listener);
  dev->setIrAndDepthFrameListener(&listener);
/// [listeners]

/// [start]
  if (enable_rgb && enable_depth)
  {
    if (!dev->start())
      return -1;
  }
  else
  {
    if (!dev->startStreams(enable_rgb, enable_depth))
      return -1;
  }

  std::cout << "device serial: " << dev->getSerialNumber() << std::endl;
  std::cout << "device firmware: " << dev->getFirmwareVersion() << std::endl;
/// [start]

/// [registration setup]
  libfreenect2::Registration* registration = new libfreenect2::Registration(dev->getIrCameraParams(), dev->getColorCameraParams());
  libfreenect2::Frame undistorted(512, 424, 4), registered(512, 424, 4);
/// [registration setup]

  size_t framecount = 0;
#ifdef EXAMPLES_WITH_OPENGL_SUPPORT
  Viewer viewer;
  if (viewer_enabled)
    viewer.initialize();
#else
  viewer_enabled = false;
#endif

/// [loop start]
  while(!protonect_shutdown && (framemax == (size_t)-1 || framecount < framemax))
  {
    if (!listener.waitForNewFrame(frames, 10*1000)) // 10 sconds
    {
      std::cout << "timeout!" << std::endl;
      return -1;
    }
    libfreenect2::Frame *rgb = frames[libfreenect2::Frame::Color];
    libfreenect2::Frame *ir = frames[libfreenect2::Frame::Ir];
    libfreenect2::Frame *depth = frames[libfreenect2::Frame::Depth];
/// [loop start]

    if (enable_rgb && enable_depth)
    {
/// [registration]
      registration->apply(rgb, depth, &undistorted, &registered);
/// [registration]
    }

    framecount++;
    if (!viewer_enabled)
    {
      if (framecount % 100 == 0)
        std::cout << "The viewer is turned off. Received " << framecount << " frames. Ctrl-C to stop." << std::endl;
      listener.release(frames);
      continue;
    }

#ifdef EXAMPLES_WITH_OPENGL_SUPPORT
    if (enable_rgb)
    {
      viewer.addFrame("RGB", rgb);
    }
    if (enable_depth)
    {
      viewer.addFrame("ir", ir);
      viewer.addFrame("depth", depth);
    }
    if (enable_rgb && enable_depth)
    {
      viewer.addFrame("registered", &registered);
    }

    protonect_shutdown = protonect_shutdown || viewer.render();
#endif

/// [loop end]
    listener.release(frames);
    /** libfreenect2::this_thread::sleep_for(libfreenect2::chrono::milliseconds(100)); */
  }
/// [loop end]

  // TODO: restarting ir stream doesn't work!
  // TODO: bad things will happen, if frame listeners are freed before dev->stop() :(
/// [stop]
  dev->stop();
  dev->close();
/// [stop]

  delete registration;

  return 0;
}
<commit_msg>Delete Protonect.cpp<commit_after><|endoftext|>