<commit_before>#include "AnimationSet.h"
#include "Common.h"

#include <iostream>
#include <boost/property_tree/ptree.hpp>
#include <boost/property_tree/json_parser.hpp>

using boost::property_tree::ptree;
using boost::property_tree::read_json;

bool AnimationSet::loadFromFile(const std::string &filename)
{
    ptree pt;
    try
    {
        read_json(filename, pt);

        frameSize.x = pt.get<int>("frameWidth");
        frameSize.y = pt.get<int>("frameHeight");

        // Loop through listed animations
        for (const ptree::value_type& animVal : pt.get_child("animations"))
        {
            const std::string& name = animVal.first;
            const ptree& animTree = animVal.second;

            if (anims.find(name) != anims.end())
            {
                LOG(WARNING) << "Tried to add animation \"" + name + "\" more than once in " + filename + "! Ignoring...";
                continue;
            }

            Animation& anim = anims[name];

            // Basic animation properties
            float frameTime = animTree.get<float>("frameTime", 0.0);
            anim.frameTime = sf::seconds(frameTime);
            anim.looping = animTree.get<bool>("looping", false);

            // Frames of animation
            for (const ptree::value_type& framePair : animTree.get_child("frames"))
            {
                anim.frames.push_back(framePair.second.get_value<int>());
            }
        }
    }
    catch (boost::property_tree::ptree_error &e)
    {
        std::string msg = "";
        msg += "Failed to load animation from " + filename + ": " + e.what();

        throw std::runtime_error(msg);
    }

    return true;
}

const Animation& AnimationSet::getAnimation(const std::string& name) const
{
    auto it = anims.find(name);
    if (it == anims.end())
    {
        throw std::runtime_error("Couldn't find animation \"" + name + "\"");
    }

    return it->second;
}<commit_msg>Moved using statements inside the function<commit_after>#include "AnimationSet.h"
#include "Common.h"

#include <iostream>
#include <boost/property_tree/ptree.hpp>
#include <boost/property_tree/json_parser.hpp>

bool AnimationSet::loadFromFile(const std::string &filename)
{
    using boost::property_tree::ptree;
    using boost::property_tree::read_json;

    ptree pt;
    try
    {
        read_json(filename, pt);

        frameSize.x = pt.get<int>("frameWidth");
        frameSize.y = pt.get<int>("frameHeight");

        // Loop through listed animations
        for (const ptree::value_type& animVal : pt.get_child("animations"))
        {
            const std::string& name = animVal.first;
            const ptree& animTree = animVal.second;

            if (anims.find(name) != anims.end())
            {
                LOG(WARNING) << "Tried to add animation \"" + name + "\" more than once in " + filename + "! Ignoring...";
                continue;
            }

            Animation& anim = anims[name];

            // Basic animation properties
            float frameTime = animTree.get<float>("frameTime", 0.0);
            anim.frameTime = sf::seconds(frameTime);
            anim.looping = animTree.get<bool>("looping", false);

            // Frames of animation
            for (const ptree::value_type& framePair : animTree.get_child("frames"))
            {
                anim.frames.push_back(framePair.second.get_value<int>());
            }
        }
    }
    catch (boost::property_tree::ptree_error &e)
    {
        std::string msg = "";
        msg += "Failed to load animation from " + filename + ": " + e.what();

        throw std::runtime_error(msg);
    }

    return true;
}

const Animation& AnimationSet::getAnimation(const std::string& name) const
{
    auto it = anims.find(name);
    if (it == anims.end())
    {
        throw std::runtime_error("Couldn't find animation \"" + name + "\"");
    }

    return it->second;
}<|endoftext|>


<commit_before>/*
 * The Apache Software License, Version 1.1
 *
 *
 * Copyright (c) 1999 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(FACTORY_HEADER_GUARD_1357924680)
#define FACTORY_HEADER_GUARD_1357924680

// Base include file.  Must be first.
#include <PlatformSupport/PlatformSupportDefinitions.hpp>

#include <cassert>
#include <functional>

#include <PlatformSupport/Resettable.hpp>

class FactoryObject;

class XALAN_PLATFORMSUPPORT_EXPORT Factory : public Resettable
{
public:

	explicit
	Factory();

	virtual
	~Factory();

	// These interfaces are inherited from Resetable...

	/**
	 * Reset the instance.  This invalidates all existing FactoryObject
	 * instances created with this Factory.
	 */
	virtual void
	reset() = 0;

	// These interfaces are new...

	/**
	 * Return an object to the factory.
	 *
	 * @param theFactoryObject object to be returned
	 */

	bool
	returnObject(const FactoryObject*	theFactoryObject)
	{
		return doReturnObject(theFactoryObject);
	}

protected:

	/**
	 * Delete a FactoryObject instance.
	 */
	virtual bool
	deleteObject(const FactoryObject*	theFactoryObject) const;

	/**
	 * Return an object to the factory.
	 *
	 * @param theFactoryObject object to be returned
	 * @param fInReset true when called during reset().
	 */

	virtual bool
	doReturnObject(
			const FactoryObject*	theFactoryObject,
			bool					fInReset = false) = 0;

	/**
	 *
	 * A functor for use with stl algorithms.
	 *
	 */
	#if defined(XALAN_NO_NAMESPACES)
	struct DeleteFactoryObjectFunctor : public unary_function<const FactoryObject*, void>
	#else
	struct DeleteFactoryObjectFunctor : public std::unary_function<const FactoryObject*, void>
	#endif
	{
	public:

		DeleteFactoryObjectFunctor(
			Factory&		theFactoryInstance,
			bool			fInReset = false) :
			m_factoryInstance(theFactoryInstance),
			m_fInReset(fInReset)
		{
		}

		result_type
		operator()(argument_type	theFactoryObject) const
		{
			m_factoryInstance.doReturnObject(theFactoryObject,
											 m_fInReset);
		}

	private:

		Factory&	m_factoryInstance;

		const bool	m_fInReset;
	};

	friend struct DeleteFactoryObjectFunctor;

private:

	// Not implemented...
	Factory(const Factory&);

	Factory&
	operator=(const Factory&);

	bool
	operator==(const Factory&) const;
};

// auto_ptr-like class for FactoryObject instances (and it's derivatives).
template<class Type>
class FactoryObjectAutoPointer
{
public:

	// Construct a FactoryObjectAutoPointer.  Either both parameters should
	// be valid or pointers or they should both be 0.
	explicit
	FactoryObjectAutoPointer(
			Factory*	theFactory = 0,
			Type*		theObject = 0) :
		m_factory(theFactory),
		m_object(theObject)
	{
		assert(theFactory != 0 && theObject != 0 ||
			   theFactory == 0 && theObject == 0);

	}

	// Note that copy construction is not const for the source object.  Once
	// copied, the source object will no longer refer to a valid object!
#if defined(XALAN_MEMBER_TEMPLATES)
	template <class CompatibleType>
	FactoryObjectAutoPointer(FactoryObjectAutoPointer<CompatibleType>&	theRHS)
#else
	FactoryObjectAutoPointer(FactoryObjectAutoPointer<Type>&	theRHS)
#endif
	{
		adopt(theRHS);
	}

	~FactoryObjectAutoPointer()
	{
		returnObject();
	}

	Type*
	operator->() const
	{
		return m_object;
	}

	Type*
	get() const
	{
		return m_object;
	}

	void
	reset(Factory*	theFactory = 0,
		  Type*		theObject = 0)
	{
		assert(theFactory != 0 && theObject != 0 ||
			   theFactory == 0 && theObject == 0);

		returnObject();

		m_factory = theFactory;
		m_object = theObject;
	}

	Type*
	release()
	{
		Type* const		theTemp = m_object;

		m_object = 0;
		m_factory = 0;

		return theTemp;
	}

	bool
	returnObject()
	{
		bool fReturn = false;

		if (m_object != 0)
		{
			assert(m_factory != 0);

			fReturn = m_factory->returnObject(m_object);
		}

		m_object = 0;
		m_factory = 0;

		return fReturn;
	}

	// Note that assignment is not const for the source object.  Once
	// copied, the source object will no longer refer to a valid object!
#if defined(XALAN_MEMBER_TEMPLATES)
	template <class CompatibleType>
	FactoryObjectAutoPointer&
	operator=(FactoryObjectAutoPointer<CompatibleType&	theRHS)
#else
	FactoryObjectAutoPointer&
	operator=(FactoryObjectAutoPointer<Type>&	theRHS)
#endif
	{
		if (static_cast<void*>(this) != static_cast<void*>(&theRHS))
		{
			adopt(theRHS);
		}

		return *this;
	}

#if defined(XALAN_MEMBER_TEMPLATES)
	template <class CompatibleType>
	bool
	operator==(const FactoryObjectAutoPointer<CompatibleType&		theRHS) const
#else
	bool
	operator==(const FactoryObjectAutoPointer&) const
#endif
	{
		return m_object == theRHS.m_object ? true : false;
	}

private:

#if defined(XALAN_MEMBER_TEMPLATES)
	template <class CompatibleType>
	void
	adopt(FactoryObjectAutoPointer<CompatibleType&	theRHS)
#else
	void
	adopt(FactoryObjectAutoPointer<Type>&	theRHS)
#endif
	{
		if (m_object != theRHS.m_object)
		{
			// Return the object we're now pointing
			// to.
			returnObject();
		}

		// Adopt the object and factory of the source
		// object.
		m_factory = theRHS.m_factory;
		m_object = theRHS.m_object;

		// The source object will no longer refer
		// to the object.
		theRHS.m_object = 0;
		theRHS.m_factory = 0;
	}

	// Data members...
	Factory*	m_factory;
    Type*		m_object;
};

#endif	// FACTORY_HEADER_GUARD_1357924680
<commit_msg>Made a public version of the delete functor and changed the name of the protected one.<commit_after>/*
 * The Apache Software License, Version 1.1
 *
 *
 * Copyright (c) 1999 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(FACTORY_HEADER_GUARD_1357924680)
#define FACTORY_HEADER_GUARD_1357924680

// Base include file.  Must be first.
#include <PlatformSupport/PlatformSupportDefinitions.hpp>

#include <cassert>
#include <functional>

#include <PlatformSupport/Resettable.hpp>

class FactoryObject;

class XALAN_PLATFORMSUPPORT_EXPORT Factory : public Resettable
{
public:

	explicit
	Factory();

	virtual
	~Factory();

	// These interfaces are inherited from Resetable...

	/**
	 * Reset the instance.  This invalidates all existing FactoryObject
	 * instances created with this Factory.
	 */
	virtual void
	reset() = 0;

	// These interfaces are new...

	/**
	 * Return an object to the factory.
	 *
	 * @param theFactoryObject object to be returned
	 */

	bool
	returnObject(const FactoryObject*	theFactoryObject)
	{
		return doReturnObject(theFactoryObject);
	}

protected:

	/**
	 * Delete a FactoryObject instance.
	 */
	virtual bool
	deleteObject(const FactoryObject*	theFactoryObject) const;

	/**
	 * Return an object to the factory.
	 *
	 * @param theFactoryObject object to be returned
	 * @param fInReset true when called during reset().
	 */

	virtual bool
	doReturnObject(
			const FactoryObject*	theFactoryObject,
			bool					fInReset = false) = 0;

	/**
	 *
	 * A functor for use with stl algorithms.
	 *
	 */
	#if defined(XALAN_NO_NAMESPACES)
	struct ProtectedDeleteFactoryObjectFunctor : public unary_function<const FactoryObject*, void>
	#else
	struct ProtectedDeleteFactoryObjectFunctor : public std::unary_function<const FactoryObject*, void>
	#endif
	{
	public:

		ProtectedDeleteFactoryObjectFunctor(
			Factory&		theFactoryInstance,
			bool			fInReset) :
			m_factoryInstance(theFactoryInstance),
			m_fInReset(fInReset)
		{
		}

		result_type
		operator()(argument_type	theFactoryObject) const
		{
			m_factoryInstance.doReturnObject(theFactoryObject,
											 m_fInReset);
		}

	private:

		Factory&	m_factoryInstance;

		const bool	m_fInReset;
	};

	friend struct ProtectedDeleteFactoryObjectFunctor;

private:

	// Not implemented...
	Factory(const Factory&);

	Factory&
	operator=(const Factory&);

	bool
	operator==(const Factory&) const;
};

// auto_ptr-like class for FactoryObject instances (and it's derivatives).
template<class Type>
class FactoryObjectAutoPointer
{
public:

	// Construct a FactoryObjectAutoPointer.  Either both parameters should
	// be valid or pointers or they should both be 0.
	explicit
	FactoryObjectAutoPointer(
			Factory*	theFactory = 0,
			Type*		theObject = 0) :
		m_factory(theFactory),
		m_object(theObject)
	{
		assert(theFactory != 0 && theObject != 0 ||
			   theFactory == 0 && theObject == 0);

	}

	// Note that copy construction is not const for the source object.  Once
	// copied, the source object will no longer refer to a valid object!
#if defined(XALAN_MEMBER_TEMPLATES)
	template <class CompatibleType>
	FactoryObjectAutoPointer(FactoryObjectAutoPointer<CompatibleType>&	theRHS)
#else
	FactoryObjectAutoPointer(FactoryObjectAutoPointer<Type>&	theRHS)
#endif
	{
		adopt(theRHS);
	}

	~FactoryObjectAutoPointer()
	{
		returnObject();
	}

	Type*
	operator->() const
	{
		return m_object;
	}

	Type*
	get() const
	{
		return m_object;
	}

	void
	reset(Factory*	theFactory = 0,
		  Type*		theObject = 0)
	{
		assert(theFactory != 0 && theObject != 0 ||
			   theFactory == 0 && theObject == 0);

		returnObject();

		m_factory = theFactory;
		m_object = theObject;
	}

	Type*
	release()
	{
		Type* const		theTemp = m_object;

		m_object = 0;
		m_factory = 0;

		return theTemp;
	}

	bool
	returnObject()
	{
		bool fReturn = false;

		if (m_object != 0)
		{
			assert(m_factory != 0);

			fReturn = m_factory->returnObject(m_object);
		}

		m_object = 0;
		m_factory = 0;

		return fReturn;
	}

	// Note that assignment is not const for the source object.  Once
	// copied, the source object will no longer refer to a valid object!
#if defined(XALAN_MEMBER_TEMPLATES)
	template <class CompatibleType>
	FactoryObjectAutoPointer&
	operator=(FactoryObjectAutoPointer<CompatibleType&	theRHS)
#else
	FactoryObjectAutoPointer&
	operator=(FactoryObjectAutoPointer<Type>&	theRHS)
#endif
	{
		if (static_cast<void*>(this) != static_cast<void*>(&theRHS))
		{
			adopt(theRHS);
		}

		return *this;
	}

#if defined(XALAN_MEMBER_TEMPLATES)
	template <class CompatibleType>
	bool
	operator==(const FactoryObjectAutoPointer<CompatibleType&		theRHS) const
#else
	bool
	operator==(const FactoryObjectAutoPointer&) const
#endif
	{
		return m_object == theRHS.m_object ? true : false;
	}

private:

#if defined(XALAN_MEMBER_TEMPLATES)
	template <class CompatibleType>
	void
	adopt(FactoryObjectAutoPointer<CompatibleType&	theRHS)
#else
	void
	adopt(FactoryObjectAutoPointer<Type>&	theRHS)
#endif
	{
		if (m_object != theRHS.m_object)
		{
			// Return the object we're now pointing
			// to.
			returnObject();
		}

		// Adopt the object and factory of the source
		// object.
		m_factory = theRHS.m_factory;
		m_object = theRHS.m_object;

		// The source object will no longer refer
		// to the object.
		theRHS.m_object = 0;
		theRHS.m_factory = 0;
	}

	// Data members...
	Factory*	m_factory;
    Type*		m_object;
};

/**
 *
 * A public functor for use with stl algorithms.
 *
 */
#if defined(XALAN_NO_NAMESPACES)
struct DeleteFactoryObjectFunctor : public unary_function<const FactoryObject*, void>
#else
struct DeleteFactoryObjectFunctor : public std::unary_function<const FactoryObject*, void>
#endif
{
public:

	DeleteFactoryObjectFunctor(Factory&		theFactoryInstance) :
		m_factoryInstance(theFactoryInstance)
	{
	}

	result_type
	operator()(argument_type	theFactoryObject) const
	{
		m_factoryInstance.returnObject(theFactoryObject);
	}

private:

	Factory&	m_factoryInstance;
};

#endif	// FACTORY_HEADER_GUARD_1357924680
<|endoftext|>


<commit_before><commit_msg>fixed bug with bet reset<commit_after><|endoftext|>


<commit_before><commit_msg>Tuplaturbo (molemmat Control-näppäimet pohjaan yhtä aikaa).<commit_after><|endoftext|>


<commit_before>
#include <ostream>
#include <string>

#include <boost/filesystem.hpp>

#include <papyrus/parser/PapyrusParser.h>
#include <papyrus/PapyrusResolutionContext.h>
#include <papyrus/PapyrusScript.h>
#include <pex/PexWriter.h>

void compileScript(std::string filename) {
  printf("Compiling %s\n", filename.c_str());
  auto parser = new caprica::papyrus::parser::PapyrusParser(filename);
  auto a = parser->parseScript();
  delete parser;
  auto ctx = new caprica::papyrus::PapyrusResolutionContext();
  a->semantic(ctx);
  auto pex = a->buildPex();
  delete ctx;
  delete a;
  std::ofstream strm(boost::filesystem::basename(filename) + ".pex", std::ofstream::binary);
  caprica::pex::PexWriter wtr(strm);
  pex->write(wtr);
  delete pex;
}

int main(int argc, char* argv[])
{
  if (argc != 2) {
    printf("Invoke like: caprica.exe myFile.psc");
  }

  printf("Caprica Papyrus Compiler v0.0.2\n");

#ifdef NDEBUG
  try {
#endif
    std::string file = argv[1];
    if (boost::filesystem::is_directory(file)) {
      boost::system::error_code ec;
      for (auto e : boost::filesystem::directory_iterator(file, ec)) {
        if (boost::filesystem::extension(e.path()) == ".psc") {
          compileScript(e.path().string());
        }
      }
    } else {
      compileScript(file);
    }
#ifdef NDEBUG
  } catch (std::runtime_error err) {
    printf("%s", err.what());
    getchar();
  }
#endif

  return 0;
}

<commit_msg>Bump to version 0.0.3<commit_after>
#include <ostream>
#include <string>

#include <boost/filesystem.hpp>

#include <papyrus/parser/PapyrusParser.h>
#include <papyrus/PapyrusResolutionContext.h>
#include <papyrus/PapyrusScript.h>
#include <pex/PexWriter.h>

void compileScript(std::string filename) {
  printf("Compiling %s\n", filename.c_str());
  auto parser = new caprica::papyrus::parser::PapyrusParser(filename);
  auto a = parser->parseScript();
  delete parser;
  auto ctx = new caprica::papyrus::PapyrusResolutionContext();
  a->semantic(ctx);
  auto pex = a->buildPex();
  delete ctx;
  delete a;
  std::ofstream strm(boost::filesystem::basename(filename) + ".pex", std::ofstream::binary);
  caprica::pex::PexWriter wtr(strm);
  pex->write(wtr);
  delete pex;
}

int main(int argc, char* argv[])
{
  if (argc != 2) {
    printf("Invoke like: caprica.exe myFile.psc");
  }

  printf("Caprica Papyrus Compiler v0.0.3\n");

#ifdef NDEBUG
  try {
#endif
    std::string file = argv[1];
    if (boost::filesystem::is_directory(file)) {
      boost::system::error_code ec;
      for (auto e : boost::filesystem::directory_iterator(file, ec)) {
        if (boost::filesystem::extension(e.path()) == ".psc") {
          compileScript(e.path().string());
        }
      }
    } else {
      compileScript(file);
    }
#ifdef NDEBUG
  } catch (std::runtime_error err) {
    printf("%s", err.what());
    getchar();
  }
#endif

  return 0;
}

<|endoftext|>


<commit_before>/*************************************************************************
 *
 *  $RCSfile: xdictionary.cxx,v $
 *
 *  $Revision: 1.7 $
 *
 *  last change: $Author: vg $ $Date: 2003-05-27 11:27:22 $
 *
 *  The Contents of this file are made available subject to the terms of
 *  either of the following licenses
 *
 *         - GNU Lesser General Public License Version 2.1
 *         - Sun Industry Standards Source License Version 1.1
 *
 *  Sun Microsystems Inc., October, 2000
 *
 *  GNU Lesser General Public License Version 2.1
 *  =============================================
 *  Copyright 2000 by Sun Microsystems, Inc.
 *  901 San Antonio Road, Palo Alto, CA 94303, USA
 *
 *  This library is free software; you can redistribute it and/or
 *  modify it under the terms of the GNU Lesser General Public
 *  License version 2.1, as published by the Free Software Foundation.
 *
 *  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
 *
 *
 *  Sun Industry Standards Source License Version 1.1
 *  =================================================
 *  The contents of this file are subject to the Sun Industry Standards
 *  Source License Version 1.1 (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.openoffice.org/license.html.
 *
 *  Software provided under this License is provided on an "AS IS" basis,
 *  WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING,
 *  WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,
 *  MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.
 *  See the License for the specific provisions governing your rights and
 *  obligations concerning the Software.
 *
 *  The Initial Developer of the Original Code is: Sun Microsystems, Inc.
 *
 *  Copyright: 2000 by Sun Microsystems, Inc.
 *
 *  All Rights Reserved.
 *
 *  Contributor(s): _______________________________________
 *
 *
 ************************************************************************/

// xdictionary.cpp: implementation of the xdictionary class.
//
//////////////////////////////////////////////////////////////////////

#ifndef _RTL_USTRBUF_HXX_
#include <rtl/ustrbuf.hxx>
#endif

#include <com/sun/star/i18n/WordType.hpp>
#include <tools/string.hxx>
#include <xdictionary.hxx>
#include <i18nutil/unicode.hxx>
#include <string.h>

//////////////////////////////////////////////////////////////////////
// Construction/Destruction
//////////////////////////////////////////////////////////////////////

using namespace rtl;

namespace com { namespace sun { namespace star { namespace i18n {

xdictionary::xdictionary(sal_Char *lang)
{
#ifdef SAL_DLLPREFIX
    OUStringBuffer aBuf( strlen(lang) + 7 + 6 );    // mostly "lib*.so" (with * == dict_zh)
    aBuf.appendAscii( SAL_DLLPREFIX );
#else
    OUStringBuffer aBuf( strlen(lang) + 7 + 4 );    // mostly "*.dll" (with * == dict_zh)
#endif
    aBuf.appendAscii( "dict_" ).appendAscii( lang ).appendAscii( SAL_DLLEXTENSION );
        oslModule hModule = osl_loadModule( aBuf.makeStringAndClear().pData, SAL_LOADMODULE_DEFAULT );
        if( hModule ) {
            int (*func)();
            func = (int(*)()) osl_getSymbol( hModule, OUString::createFromAscii("getExistMark").pData );
            existMark = (sal_uInt8*) (*func)();
            func = (int(*)()) osl_getSymbol( hModule, OUString::createFromAscii("getIndex1").pData );
            index1 = (sal_Int16*) (*func)();
            func = (int(*)()) osl_getSymbol( hModule, OUString::createFromAscii("getIndex2").pData );
            index2 = (sal_Int32*) (*func)();
            func = (int(*)()) osl_getSymbol( hModule, OUString::createFromAscii("getLenArray").pData );
            lenArray = (sal_Int32*) (*func)();
            func = (int(*)()) osl_getSymbol( hModule, OUString::createFromAscii("getDataArea").pData );
            dataArea = (sal_Unicode*) (*func)();
        }
        else
            existMark = NULL;
        for (sal_Int32 i = 0; i < CACHE_MAX; i++)
            cache[i].size = 0;

        // for CTL breakiterator, which the word boundary should not inside cell.
        useCellBoundary = sal_False;
}

xdictionary::~xdictionary() {
        osl_unloadModule(hModule);
        for (sal_Int32 i = 0; i < CACHE_MAX; i++) {
            if (cache[i].size > 0) {
                delete cache[i].contents;
                delete cache[i].wordboundary;
            }
        }
}

sal_Bool xdictionary::exists(const sal_Unicode u) {
        return existMark ? ((existMark[u>>3] & (1<<(u&0x07))) != 0) : sal_False;
}

sal_Int32 SAL_CALL
xdictionary::getLongestMatch(const sal_Unicode* str, sal_Int32 sLen) {

        sal_Int16 idx = index1[str[0] >> 8];

        if (idx == 0xFF) return 1;

        idx = (idx<<8) | (str[0]&0xff);

        sal_uInt32 begin = index2[idx], end = index2[idx+1];

        if (begin == 0) return 1;

        str++; sLen--; // first character is not stored in the dictionary
        for (sal_uInt32 i = end; i > begin; i--) {
            sal_Int32 len = lenArray[i] - lenArray[i - 1];
            if (sLen >= len) {
                const sal_Unicode *dstr = dataArea + lenArray[i-1];
                sal_Int32 pos = 0;

                while (pos < len && dstr[pos] == str[pos]) { pos++; }

                if (pos == len)
                    return len + 1;
            }
        }
        return 1;
}

/*
 * Compare two unicode string,
 */

sal_Bool SAL_CALL WordBreakCache::equals(const sal_Unicode* str, Boundary& boundary) {
        // Different length, different string.
        if (length != boundary.endPos - boundary.startPos) return sal_False;

        for (sal_Int32 i = 0; i < length; i++)
            if (contents[i] != str[i + boundary.startPos]) return sal_False;

        return sal_True;
}

/*
 * Retrieve the segment containing the character at pos.
 * @param pos : Position of the given character.
 * @return true if CJK.
 */
sal_Bool SAL_CALL xdictionary::seekSegment(const sal_Unicode *text, sal_Int32 pos,
                sal_Int32 len, Boundary& boundary) {
        for (boundary.startPos = pos - 1;
            boundary.startPos >= 0 &&
                (unicode::isWhiteSpace(text[boundary.startPos]) || exists(text[boundary.startPos]));
            boundary.startPos--);
        boundary.startPos++;

        for (boundary.endPos = pos;
            boundary.endPos < len &&
                    (unicode::isWhiteSpace(text[boundary.endPos]) || exists(text[boundary.endPos]));
            boundary.endPos++);

        return boundary.endPos > boundary.startPos + 1;
}

WordBreakCache& SAL_CALL xdictionary::getCache(const sal_Unicode *text, Boundary& boundary)
{

        WordBreakCache& aCache = cache[text[0] & 0x1f];

        if (aCache.size != 0 && aCache.equals(text, boundary))
            return aCache;

        sal_Int32 len = boundary.endPos - boundary.startPos;

        if (aCache.size == 0 || len > aCache.size) {
            if (aCache.size != 0) {
                delete aCache.contents;
                delete aCache.wordboundary;
                aCache.size = len;
            }
            else
                aCache.size = len > DEFAULT_SIZE ? len : DEFAULT_SIZE;
            aCache.contents = new sal_Unicode[aCache.size + 1];
            aCache.wordboundary = new sal_Int32[aCache.size + 2];
        }
        aCache.length  = len;
        memcpy(aCache.contents, text + boundary.startPos, len * sizeof(sal_Unicode));
        *(aCache.contents + len) = 0x0000;
        // reset the wordboundary in cache
        memset(aCache.wordboundary, '\0', sizeof(sal_Int32)*(len + 2));

        sal_Int32 i = 0;        // loop variable
        while (aCache.wordboundary[i] < aCache.length) {
            len = 0;
            // look the continuous white space as one word and cashe it
            while (unicode::isWhiteSpace(text[boundary.startPos + aCache.wordboundary[i] + len]))
                len ++;

            if (len == 0)
                len = getLongestMatch(text + boundary.startPos + aCache.wordboundary[i],
                                            aCache.length - aCache.wordboundary[i]);

            aCache.wordboundary[i+1] = aCache.wordboundary[i] + len;
            i++;

            if (useCellBoundary) {
                sal_Int32 cBoundary = cellBoundary[aCache.wordboundary[i] + boundary.startPos - 1];
                if (cBoundary > 0)
                    aCache.wordboundary[i] = cBoundary - boundary.startPos;
            }
        }
        aCache.wordboundary[i + 1] = aCache.length + 1;

        return aCache;
}

Boundary SAL_CALL xdictionary::previousWord(const sal_Unicode *text, sal_Int32 anyPos, sal_Int32 len, sal_Int16 wordType)
{
        // looking for the first non-whitespace character from anyPos
        while (unicode::isWhiteSpace(text[anyPos - 1])) anyPos --;
        return getWordBoundary(text, anyPos - 1, len, wordType, true);
}

Boundary SAL_CALL xdictionary::nextWord(const sal_Unicode *text, sal_Int32 anyPos, sal_Int32 len, sal_Int16 wordType)
{
        boundary = getWordBoundary(text, anyPos, len, wordType, true);
        // looknig for the first non-whitespace character from anyPos
        anyPos = boundary.endPos;
        while (unicode::isWhiteSpace(text[anyPos])) anyPos ++;

        return getWordBoundary(text, anyPos, len, wordType, true);
}

Boundary SAL_CALL xdictionary::getWordBoundary(const sal_Unicode *text, sal_Int32 anyPos, sal_Int32 len, sal_Int16 wordType, sal_Bool bDirection)
{
        Boundary boundary;

        if (anyPos >= len || anyPos < 0) {
            boundary.startPos = boundary.endPos = anyPos < 0 ? 0 : len;
        } else if (seekSegment(text, anyPos, len, boundary)) {          // character in dict
            WordBreakCache& aCache = getCache(text, boundary);
            sal_Int32 i = 0;

            while (aCache.wordboundary[i] <= (sal_Int32)anyPos - boundary.startPos) i++;

            sal_Int32 startPos = aCache.wordboundary[i - 1];
            // if bDirection is false
            if (!bDirection && startPos > 0 && startPos == (anyPos - boundary.startPos) &&
                                                unicode::isWhiteSpace(text[anyPos - 1]))
                i--;
            boundary.endPos = aCache.wordboundary[i] + boundary.startPos;
            boundary.startPos += aCache.wordboundary[i - 1];
        } else {
            boundary.startPos = anyPos++;
            boundary.endPos = anyPos < len ? anyPos : len;
        }
        if (wordType == WordType::WORD_COUNT) {
            // skip punctuation for word count.
            while (boundary.endPos < len && unicode::isPunctuation(text[boundary.endPos]))
                boundary.endPos++;
        }

        return boundary;
}

void SAL_CALL xdictionary::setCellBoundary(sal_Int32* cellArray)
{
        useCellBoundary = sal_True;
        cellBoundary = cellArray;
}

} } } }
<commit_msg>INTEGRATION: CWS sw016 (1.6.18); FILE MERGED 2003/06/06 10:59:23 hbrinkm 1.6.18.2: RESYNC: (1.6-1.7); FILE MERGED 2003/06/05 21:39:06 khong 1.6.18.1: #109813# make CJK word breakiterator falls back to default icu breakiterator on non-CJK text<commit_after>/*************************************************************************
 *
 *  $RCSfile: xdictionary.cxx,v $
 *
 *  $Revision: 1.8 $
 *
 *  last change: $Author: rt $ $Date: 2003-06-12 07:34:07 $
 *
 *  The Contents of this file are made available subject to the terms of
 *  either of the following licenses
 *
 *         - GNU Lesser General Public License Version 2.1
 *         - Sun Industry Standards Source License Version 1.1
 *
 *  Sun Microsystems Inc., October, 2000
 *
 *  GNU Lesser General Public License Version 2.1
 *  =============================================
 *  Copyright 2000 by Sun Microsystems, Inc.
 *  901 San Antonio Road, Palo Alto, CA 94303, USA
 *
 *  This library is free software; you can redistribute it and/or
 *  modify it under the terms of the GNU Lesser General Public
 *  License version 2.1, as published by the Free Software Foundation.
 *
 *  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
 *
 *
 *  Sun Industry Standards Source License Version 1.1
 *  =================================================
 *  The contents of this file are subject to the Sun Industry Standards
 *  Source License Version 1.1 (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.openoffice.org/license.html.
 *
 *  Software provided under this License is provided on an "AS IS" basis,
 *  WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING,
 *  WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,
 *  MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.
 *  See the License for the specific provisions governing your rights and
 *  obligations concerning the Software.
 *
 *  The Initial Developer of the Original Code is: Sun Microsystems, Inc.
 *
 *  Copyright: 2000 by Sun Microsystems, Inc.
 *
 *  All Rights Reserved.
 *
 *  Contributor(s): _______________________________________
 *
 *
 ************************************************************************/

// xdictionary.cpp: implementation of the xdictionary class.
//
//////////////////////////////////////////////////////////////////////

#ifndef _RTL_USTRBUF_HXX_
#include <rtl/ustrbuf.hxx>
#endif

#include <com/sun/star/i18n/WordType.hpp>
#include <tools/string.hxx>
#include <xdictionary.hxx>
#include <i18nutil/unicode.hxx>
#include <string.h>

//////////////////////////////////////////////////////////////////////
// Construction/Destruction
//////////////////////////////////////////////////////////////////////

using namespace rtl;

namespace com { namespace sun { namespace star { namespace i18n {

xdictionary::xdictionary(sal_Char *lang)
{
#ifdef SAL_DLLPREFIX
    OUStringBuffer aBuf( strlen(lang) + 7 + 6 );    // mostly "lib*.so" (with * == dict_zh)
    aBuf.appendAscii( SAL_DLLPREFIX );
#else
    OUStringBuffer aBuf( strlen(lang) + 7 + 4 );    // mostly "*.dll" (with * == dict_zh)
#endif
    aBuf.appendAscii( "dict_" ).appendAscii( lang ).appendAscii( SAL_DLLEXTENSION );
    hModule = osl_loadModule( aBuf.makeStringAndClear().pData, SAL_LOADMODULE_DEFAULT );
    if( hModule ) {
        int (*func)();
        func = (int(*)()) osl_getSymbol( hModule, OUString::createFromAscii("getExistMark").pData );
        existMark = (sal_uInt8*) (*func)();
        func = (int(*)()) osl_getSymbol( hModule, OUString::createFromAscii("getIndex1").pData );
        index1 = (sal_Int16*) (*func)();
        func = (int(*)()) osl_getSymbol( hModule, OUString::createFromAscii("getIndex2").pData );
        index2 = (sal_Int32*) (*func)();
        func = (int(*)()) osl_getSymbol( hModule, OUString::createFromAscii("getLenArray").pData );
        lenArray = (sal_Int32*) (*func)();
        func = (int(*)()) osl_getSymbol( hModule, OUString::createFromAscii("getDataArea").pData );
        dataArea = (sal_Unicode*) (*func)();
    }
    else
        existMark = NULL;
    for (sal_Int32 i = 0; i < CACHE_MAX; i++)
        cache[i].size = 0;

        // for CTL breakiterator, which the word boundary should not inside cell.
        useCellBoundary = sal_False;
}

xdictionary::~xdictionary() {
        osl_unloadModule(hModule);
        for (sal_Int32 i = 0; i < CACHE_MAX; i++) {
            if (cache[i].size > 0) {
                delete cache[i].contents;
                delete cache[i].wordboundary;
            }
        }
}

sal_Bool xdictionary::exists(const sal_Unicode u) {
        return existMark ? ((existMark[u>>3] & (1<<(u&0x07))) != 0) : sal_False;
}

sal_Int32 SAL_CALL
xdictionary::getLongestMatch(const sal_Unicode* str, sal_Int32 sLen) {

        sal_Int16 idx = index1[str[0] >> 8];

        if (idx == 0xFF) return 1;

        idx = (idx<<8) | (str[0]&0xff);

        sal_uInt32 begin = index2[idx], end = index2[idx+1];

        if (begin == 0) return 1;

        str++; sLen--; // first character is not stored in the dictionary
        for (sal_uInt32 i = end; i > begin; i--) {
            sal_Int32 len = lenArray[i] - lenArray[i - 1];
            if (sLen >= len) {
                const sal_Unicode *dstr = dataArea + lenArray[i-1];
                sal_Int32 pos = 0;

                while (pos < len && dstr[pos] == str[pos]) { pos++; }

                if (pos == len)
                    return len + 1;
            }
        }
        return 1;
}

/*
 * Compare two unicode string,
 */

sal_Bool SAL_CALL WordBreakCache::equals(const sal_Unicode* str, Boundary& boundary) {
        // Different length, different string.
        if (length != boundary.endPos - boundary.startPos) return sal_False;

        for (sal_Int32 i = 0; i < length; i++)
            if (contents[i] != str[i + boundary.startPos]) return sal_False;

        return sal_True;
}

/*
 * Retrieve the segment containing the character at pos.
 * @param pos : Position of the given character.
 * @return true if CJK.
 */
sal_Bool SAL_CALL xdictionary::seekSegment(const sal_Unicode *text, sal_Int32 pos,
                sal_Int32 len, Boundary& boundary) {
        for (boundary.startPos = pos - 1;
            boundary.startPos >= 0 &&
                (unicode::isWhiteSpace(text[boundary.startPos]) || exists(text[boundary.startPos]));
            boundary.startPos--);
        boundary.startPos++;

        for (boundary.endPos = pos;
            boundary.endPos < len &&
                    (unicode::isWhiteSpace(text[boundary.endPos]) || exists(text[boundary.endPos]));
            boundary.endPos++);

        return boundary.endPos > boundary.startPos + 1;
}

WordBreakCache& SAL_CALL xdictionary::getCache(const sal_Unicode *text, Boundary& boundary)
{

        WordBreakCache& aCache = cache[text[0] & 0x1f];

        if (aCache.size != 0 && aCache.equals(text, boundary))
            return aCache;

        sal_Int32 len = boundary.endPos - boundary.startPos;

        if (aCache.size == 0 || len > aCache.size) {
            if (aCache.size != 0) {
                delete aCache.contents;
                delete aCache.wordboundary;
                aCache.size = len;
            }
            else
                aCache.size = len > DEFAULT_SIZE ? len : DEFAULT_SIZE;
            aCache.contents = new sal_Unicode[aCache.size + 1];
            aCache.wordboundary = new sal_Int32[aCache.size + 2];
        }
        aCache.length  = len;
        memcpy(aCache.contents, text + boundary.startPos, len * sizeof(sal_Unicode));
        *(aCache.contents + len) = 0x0000;
        // reset the wordboundary in cache
        memset(aCache.wordboundary, '\0', sizeof(sal_Int32)*(len + 2));

        sal_Int32 i = 0;        // loop variable
        while (aCache.wordboundary[i] < aCache.length) {
            len = 0;
            // look the continuous white space as one word and cashe it
            while (unicode::isWhiteSpace(text[boundary.startPos + aCache.wordboundary[i] + len]))
                len ++;

            if (len == 0)
                len = getLongestMatch(text + boundary.startPos + aCache.wordboundary[i],
                                            aCache.length - aCache.wordboundary[i]);

            aCache.wordboundary[i+1] = aCache.wordboundary[i] + len;
            i++;

            if (useCellBoundary) {
                sal_Int32 cBoundary = cellBoundary[aCache.wordboundary[i] + boundary.startPos - 1];
                if (cBoundary > 0)
                    aCache.wordboundary[i] = cBoundary - boundary.startPos;
            }
        }
        aCache.wordboundary[i + 1] = aCache.length + 1;

        return aCache;
}

Boundary SAL_CALL xdictionary::previousWord(const sal_Unicode *text, sal_Int32 anyPos, sal_Int32 len, sal_Int16 wordType)
{
        // looking for the first non-whitespace character from anyPos
        while (unicode::isWhiteSpace(text[anyPos - 1])) anyPos --;
        return getWordBoundary(text, anyPos - 1, len, wordType, true);
}

Boundary SAL_CALL xdictionary::nextWord(const sal_Unicode *text, sal_Int32 anyPos, sal_Int32 len, sal_Int16 wordType)
{
        boundary = getWordBoundary(text, anyPos, len, wordType, true);
        // looknig for the first non-whitespace character from anyPos
        anyPos = boundary.endPos;
        while (unicode::isWhiteSpace(text[anyPos])) anyPos ++;

        return getWordBoundary(text, anyPos, len, wordType, true);
}

Boundary SAL_CALL xdictionary::getWordBoundary(const sal_Unicode *text, sal_Int32 anyPos, sal_Int32 len, sal_Int16 wordType, sal_Bool bDirection)
{
        Boundary boundary;

        if (anyPos >= len || anyPos < 0) {
            boundary.startPos = boundary.endPos = anyPos < 0 ? 0 : len;
        } else if (seekSegment(text, anyPos, len, boundary)) {          // character in dict
            WordBreakCache& aCache = getCache(text, boundary);
            sal_Int32 i = 0;

            while (aCache.wordboundary[i] <= (sal_Int32)anyPos - boundary.startPos) i++;

            sal_Int32 startPos = aCache.wordboundary[i - 1];
            // if bDirection is false
            if (!bDirection && startPos > 0 && startPos == (anyPos - boundary.startPos) &&
                                                unicode::isWhiteSpace(text[anyPos - 1]))
                i--;
            boundary.endPos = aCache.wordboundary[i] + boundary.startPos;
            boundary.startPos += aCache.wordboundary[i - 1];
        } else {
            boundary.startPos = anyPos++;
            boundary.endPos = anyPos < len ? anyPos : len;
        }
        if (wordType == WordType::WORD_COUNT) {
            // skip punctuation for word count.
            while (boundary.endPos < len && unicode::isPunctuation(text[boundary.endPos]))
                boundary.endPos++;
        }

        return boundary;
}

void SAL_CALL xdictionary::setCellBoundary(sal_Int32* cellArray)
{
        useCellBoundary = sal_True;
        cellBoundary = cellArray;
}

} } } }
<|endoftext|>


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

#include "customnatives.h"
#include <assert.h>
#include <sampgdk/sampgdk.h>
#include <mono/metadata/appdomain.h>
#include <mono/metadata/exception.h>
#include "monohelper.h"

#define MAX_NATIVE_ARGS                 (32)
#define MAX_NATIVE_ARG_FORMAT_LEN       (8)
#define ERR_EXCEPTION                   (-1)

//
// native functions
bool native_exists(MonoString *name_string) {
    char *name;

    if (!name_string) {
        mono_raise_exception(mono_get_exception_invalid_operation(
            "name cannot be null"));
        return ERR_EXCEPTION;
    }

    name = mono_string_to_utf8(name_string);

    AMX_NATIVE native = sampgdk::FindNative(name);

    return !!native;
}
int call_native_array(MonoString *name_string, MonoString *format_string,
    MonoArray *args_array, MonoArray *sizes_array) {
    char *name;
    char *format;
    char amx_format[MAX_NATIVE_ARGS * MAX_NATIVE_ARG_FORMAT_LEN] = "";
    void *params[MAX_NATIVE_ARGS];
    int param_size[MAX_NATIVE_ARGS];
    int args_count = 0;
    int size_idx = 0;

    if (!name_string) {
        mono_raise_exception(mono_get_exception_invalid_operation(
            "name cannot be null"));
        return ERR_EXCEPTION;
    }

    name = mono_string_to_utf8(name_string);
    format = !format_string ? "" : mono_string_to_utf8(format_string);

    args_count = !args_array ? 0 : mono_array_length(args_array);

    if (args_count > MAX_NATIVE_ARGS) {
        mono_raise_exception(mono_get_exception_invalid_operation(
            "too many arguments"));
        return ERR_EXCEPTION;
    }

    AMX_NATIVE native = sampgdk::FindNative(name);
    if (!native) {
        mono_raise_exception(mono_get_exception_invalid_operation(
            "native not found"));
        return ERR_EXCEPTION;
    }

    for (int i = 0; i < args_count; i++) {
        switch (format[i]) {
        case 'd': /* integer */
        case 'b': /* boolean */
            params[i] = mono_object_unbox(
                mono_array_get(args_array, MonoObject *, i));
            sprintf(amx_format, "%sd", amx_format);
            break;
        case 'f': /* floating-point */
            params[i] = &amx_ftoc(*(float *)mono_object_unbox(
                mono_array_get(args_array, MonoObject *, i)));
            sprintf(amx_format, "%sf", amx_format);
            break;
        case 's': { /* const string */
            params[i] = monostring_to_string(
                mono_array_get(args_array, MonoString *, i));
            sprintf(amx_format, "%ss", amx_format);
            break;
        }
        case 'a': { /* array of integers */
            MonoArray *values_array =
                mono_array_get(args_array, MonoArray *, i);

            if (!sizes_array) {
                mono_raise_exception(mono_get_exception_invalid_operation(
                    "sizes cannot be null when an array or string "
                    "reference type is passed as parameter."));
                return ERR_EXCEPTION;
            }

            int size_info = mono_array_get(sizes_array, int, size_idx++);
            param_size[i] = size_info < 0 ? -size_info
                : *(int *)mono_object_unbox(
                mono_array_get(args_array, MonoObject *, size_info));

            cell *value = new cell[param_size[i]];
            for (int j = 0; j < param_size[i]; j++) {
                value[j] = mono_array_get(values_array, int, j);
            }
            params[i] = value;

            sprintf(amx_format, "%sa[%d]", amx_format, param_size[i]);
            break;
        }
        case 'v': { /* array of floats */
            MonoArray *values_array =
                mono_array_get(args_array, MonoArray *, i);

            if (!sizes_array) {
                mono_raise_exception(mono_get_exception_invalid_operation(
                    "sizes cannot be null when an array or string "
                    "reference type is passed as parameter."));
                return ERR_EXCEPTION;
            }

            int size_info = mono_array_get(sizes_array, int, size_idx++);
            param_size[i] = size_info < 0 ? -size_info
                : *(int *)mono_object_unbox(
                mono_array_get(args_array, MonoObject *, size_info));

            cell *value = new cell[param_size[i]];
            for (int j = 0; j<param_size[i]; j++) {
                value[j] = amx_ftoc(mono_array_get(values_array, float, j));
            }
            params[i] = value;

            sprintf(amx_format, "%sa[%d]", amx_format, param_size[i]);
            break;
        }
        case 'D': /* integer reference */
            params[i] = *(int **)mono_object_unbox(
                mono_array_get(args_array, MonoObject *, i));
            sprintf(amx_format, "%sR", amx_format);
            break;
        case 'F': /* floating-point reference */
            params[i] = &amx_ftoc(**(float **)mono_object_unbox(
                mono_array_get(args_array, MonoObject *, i)));
            sprintf(amx_format, "%sR", amx_format);
            break;
        case 'S': /* non-const string (writeable) */ {
            if (!sizes_array) {
                mono_raise_exception(mono_get_exception_invalid_operation(
                    "sizes cannot be null when an array or string "
                    "reference type is passed as parameter."));
                return ERR_EXCEPTION;
            }

            int size_info = mono_array_get(sizes_array, int, size_idx++);
            param_size[i] = size_info < 0 ? -size_info
                : *(int *)mono_object_unbox(
                mono_array_get(args_array, MonoObject *, size_info));

            params[i] = new cell[param_size[i] + 1] {'\0'};

            assert(params[i]);

            sprintf(amx_format, "%sS[%d]", amx_format, param_size[i]);
            break;
        }
        case 'A': { /* array of integers reference */
            if (!sizes_array) {
                mono_raise_exception(mono_get_exception_invalid_operation(
                    "sizes cannot be null when an array or string "
                    "reference type is passed as parameter."));
                return ERR_EXCEPTION;
            }

            int size_info = mono_array_get(sizes_array, int, size_idx++);
            param_size[i] = size_info < 0 ? -size_info
                : *(int *)mono_object_unbox(
                mono_array_get(args_array, MonoObject *, size_info));

            cell *value = new cell[param_size[i]];
            for (int j = 0; j < param_size[i]; j++) {
                /* Set default value to int.MinValue */
                value[j] = -2147483648;
            }
            params[i] = value;

            sprintf(amx_format, "%sA[%d]", amx_format, param_size[i]);
            break;
        }
        case 'V': { /* array of floating-points reference */
            if (!sizes_array) {
                mono_raise_exception(mono_get_exception_invalid_operation(
                    "sizes cannot be null when an array or string "
                    "reference type is passed as parameter."));
                return ERR_EXCEPTION;
            }

            int size_info = mono_array_get(sizes_array, int, size_idx++);
            param_size[i] = size_info < 0 ? -size_info
                : *(int *)mono_object_unbox(
                mono_array_get(args_array, MonoObject *, size_info));

            params[i] = new cell[param_size[i]];

            sprintf(amx_format, "%sR[%d]", amx_format, param_size[i]);
            break;
        }
        default:
            mono_raise_exception(mono_get_exception_invalid_operation(
                "invalid format type"));
            return ERR_EXCEPTION;
            break;
        }

    }

    int return_value = sampgdk::InvokeNativeArray(native, amx_format, params);

    for (int i = 0; i < args_count; i++) {
        switch (format[i]) {
        case 's': /* const string */
        case 'a': /* array of integers */
        case 'v': /* array of floats */
            delete[] params[i];
            break;
        case 'D': /* integer reference */
            **(int **)mono_object_unbox(
                mono_array_get(args_array, MonoObject *, i)) =
                *(int *)params[i];
            break;
        case 'F': /* floating-point reference */
            **(float **)mono_object_unbox(
                mono_array_get(args_array, MonoObject *, i)) =
                amx_ctof(*(cell *)params[i]);
            break;
        case 'S': /* non-const string (writeable) */
            *mono_array_get(args_array, MonoString **, i) =
                string_to_monostring((char *)params[i], param_size[i]);

            delete[] params[i];
            break;
        case 'A': { /* array of integers reference */
            cell *param_array = (cell *)params[i];
            MonoArray *arr = mono_array_new(mono_domain_get(),
                mono_get_int32_class(), param_size[i]);
            for (int j = 0; j < param_size[i]; j++) {
                mono_array_set(arr, int, j, param_array[j]);
            }
            *mono_array_get(args_array, MonoArray **, i) = arr;

            delete[] params[i];
            break;
        }
        case 'V': { /* array of floating-points reference */
            cell *param_array = (cell *)params[i];

            MonoArray *arr = mono_array_new(mono_domain_get(),
                mono_get_single_class(), param_size[i]);
            for (int j = 0; j<param_size[i]; j++) {
                mono_array_set(arr, float, j, amx_ctof(param_array[j]));
            }
            *mono_array_get(args_array, MonoArray **, i) = arr;

            delete[] params[i];
            break;
        }
        }
    }

    return return_value;
}
<commit_msg>Fixed an issue where CallNativeArray spits out sampgdk errors when passing an out float[] argument<commit_after>// SampSharp
// Copyright 2015 Tim Potze
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//     http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

#include "customnatives.h"
#include <assert.h>
#include <sampgdk/sampgdk.h>
#include <mono/metadata/appdomain.h>
#include <mono/metadata/exception.h>
#include "monohelper.h"

#define MAX_NATIVE_ARGS                 (32)
#define MAX_NATIVE_ARG_FORMAT_LEN       (8)
#define ERR_EXCEPTION                   (-1)

//
// native functions
bool native_exists(MonoString *name_string) {
    char *name;

    if (!name_string) {
        mono_raise_exception(mono_get_exception_invalid_operation(
            "name cannot be null"));
        return ERR_EXCEPTION;
    }

    name = mono_string_to_utf8(name_string);

    AMX_NATIVE native = sampgdk::FindNative(name);

    return !!native;
}
int call_native_array(MonoString *name_string, MonoString *format_string,
    MonoArray *args_array, MonoArray *sizes_array) {
    char *name;
    char *format;
    char amx_format[MAX_NATIVE_ARGS * MAX_NATIVE_ARG_FORMAT_LEN] = "";
    void *params[MAX_NATIVE_ARGS];
    int param_size[MAX_NATIVE_ARGS];
    int args_count = 0;
    int size_idx = 0;

    if (!name_string) {
        mono_raise_exception(mono_get_exception_invalid_operation(
            "name cannot be null"));
        return ERR_EXCEPTION;
    }

    name = mono_string_to_utf8(name_string);
    format = !format_string ? "" : mono_string_to_utf8(format_string);

    args_count = !args_array ? 0 : mono_array_length(args_array);

    if (args_count > MAX_NATIVE_ARGS) {
        mono_raise_exception(mono_get_exception_invalid_operation(
            "too many arguments"));
        return ERR_EXCEPTION;
    }

    AMX_NATIVE native = sampgdk::FindNative(name);
    if (!native) {
        mono_raise_exception(mono_get_exception_invalid_operation(
            "native not found"));
        return ERR_EXCEPTION;
    }

    for (int i = 0; i < args_count; i++) {
        switch (format[i]) {
        case 'd': /* integer */
        case 'b': /* boolean */
            params[i] = mono_object_unbox(
                mono_array_get(args_array, MonoObject *, i));
            sprintf(amx_format, "%sd", amx_format);
            break;
        case 'f': /* floating-point */
            params[i] = &amx_ftoc(*(float *)mono_object_unbox(
                mono_array_get(args_array, MonoObject *, i)));
            sprintf(amx_format, "%sf", amx_format);
            break;
        case 's': { /* const string */
            params[i] = monostring_to_string(
                mono_array_get(args_array, MonoString *, i));
            sprintf(amx_format, "%ss", amx_format);
            break;
        }
        case 'a': { /* array of integers */
            MonoArray *values_array =
                mono_array_get(args_array, MonoArray *, i);

            if (!sizes_array) {
                mono_raise_exception(mono_get_exception_invalid_operation(
                    "sizes cannot be null when an array or string "
                    "reference type is passed as parameter."));
                return ERR_EXCEPTION;
            }

            int size_info = mono_array_get(sizes_array, int, size_idx++);
            param_size[i] = size_info < 0 ? -size_info
                : *(int *)mono_object_unbox(
                mono_array_get(args_array, MonoObject *, size_info));

            cell *value = new cell[param_size[i]];
            for (int j = 0; j < param_size[i]; j++) {
                value[j] = mono_array_get(values_array, int, j);
            }
            params[i] = value;

            sprintf(amx_format, "%sa[%d]", amx_format, param_size[i]);
            break;
        }
        case 'v': { /* array of floats */
            MonoArray *values_array =
                mono_array_get(args_array, MonoArray *, i);

            if (!sizes_array) {
                mono_raise_exception(mono_get_exception_invalid_operation(
                    "sizes cannot be null when an array or string "
                    "reference type is passed as parameter."));
                return ERR_EXCEPTION;
            }

            int size_info = mono_array_get(sizes_array, int, size_idx++);
            param_size[i] = size_info < 0 ? -size_info
                : *(int *)mono_object_unbox(
                mono_array_get(args_array, MonoObject *, size_info));

            cell *value = new cell[param_size[i]];
            for (int j = 0; j<param_size[i]; j++) {
                value[j] = amx_ftoc(mono_array_get(values_array, float, j));
            }
            params[i] = value;

            sprintf(amx_format, "%sa[%d]", amx_format, param_size[i]);
            break;
        }
        case 'D': /* integer reference */
            params[i] = *(int **)mono_object_unbox(
                mono_array_get(args_array, MonoObject *, i));
            sprintf(amx_format, "%sR", amx_format);
            break;
        case 'F': /* floating-point reference */
            params[i] = &amx_ftoc(**(float **)mono_object_unbox(
                mono_array_get(args_array, MonoObject *, i)));
            sprintf(amx_format, "%sR", amx_format);
            break;
        case 'S': /* non-const string (writeable) */ {
            if (!sizes_array) {
                mono_raise_exception(mono_get_exception_invalid_operation(
                    "sizes cannot be null when an array or string "
                    "reference type is passed as parameter."));
                return ERR_EXCEPTION;
            }

            int size_info = mono_array_get(sizes_array, int, size_idx++);
            param_size[i] = size_info < 0 ? -size_info
                : *(int *)mono_object_unbox(
                mono_array_get(args_array, MonoObject *, size_info));

            params[i] = new cell[param_size[i] + 1] {'\0'};

            assert(params[i]);

            sprintf(amx_format, "%sS[%d]", amx_format, param_size[i]);
            break;
        }
        case 'A': { /* array of integers reference */
            if (!sizes_array) {
                mono_raise_exception(mono_get_exception_invalid_operation(
                    "sizes cannot be null when an array or string "
                    "reference type is passed as parameter."));
                return ERR_EXCEPTION;
            }

            int size_info = mono_array_get(sizes_array, int, size_idx++);
            param_size[i] = size_info < 0 ? -size_info
                : *(int *)mono_object_unbox(
                mono_array_get(args_array, MonoObject *, size_info));

            cell *value = new cell[param_size[i]];
            for (int j = 0; j < param_size[i]; j++) {
                /* Set default value to int.MinValue */
                value[j] = -2147483648;
            }
            params[i] = value;

            sprintf(amx_format, "%sA[%d]", amx_format, param_size[i]);
            break;
        }
        case 'V': { /* array of floating-points reference */
            if (!sizes_array) {
                mono_raise_exception(mono_get_exception_invalid_operation(
                    "sizes cannot be null when an array or string "
                    "reference type is passed as parameter."));
                return ERR_EXCEPTION;
            }

            int size_info = mono_array_get(sizes_array, int, size_idx++);
            param_size[i] = size_info < 0 ? -size_info
                : *(int *)mono_object_unbox(
                mono_array_get(args_array, MonoObject *, size_info));

            params[i] = new cell[param_size[i]];

            sprintf(amx_format, "%sA[%d]", amx_format, param_size[i]);
            break;
        }
        default:
            mono_raise_exception(mono_get_exception_invalid_operation(
                "invalid format type"));
            return ERR_EXCEPTION;
            break;
        }

    }

    int return_value = sampgdk::InvokeNativeArray(native, amx_format, params);

    for (int i = 0; i < args_count; i++) {
        switch (format[i]) {
        case 's': /* const string */
        case 'a': /* array of integers */
        case 'v': /* array of floats */
            delete[] params[i];
            break;
        case 'D': /* integer reference */
            **(int **)mono_object_unbox(
                mono_array_get(args_array, MonoObject *, i)) =
                *(int *)params[i];
            break;
        case 'F': /* floating-point reference */
            **(float **)mono_object_unbox(
                mono_array_get(args_array, MonoObject *, i)) =
                amx_ctof(*(cell *)params[i]);
            break;
        case 'S': /* non-const string (writeable) */
            *mono_array_get(args_array, MonoString **, i) =
                string_to_monostring((char *)params[i], param_size[i]);

            delete[] params[i];
            break;
        case 'A': { /* array of integers reference */
            cell *param_array = (cell *)params[i];
            MonoArray *arr = mono_array_new(mono_domain_get(),
                mono_get_int32_class(), param_size[i]);
            for (int j = 0; j < param_size[i]; j++) {
                mono_array_set(arr, int, j, param_array[j]);
            }
            *mono_array_get(args_array, MonoArray **, i) = arr;

            delete[] params[i];
            break;
        }
        case 'V': { /* array of floating-points reference */
            cell *param_array = (cell *)params[i];

            MonoArray *arr = mono_array_new(mono_domain_get(),
                mono_get_single_class(), param_size[i]);
            for (int j = 0; j<param_size[i]; j++) {
                mono_array_set(arr, float, j, amx_ctof(param_array[j]));
            }
            *mono_array_get(args_array, MonoArray **, i) = arr;

            delete[] params[i];
            break;
        }
        }
    }

    return return_value;
}
<|endoftext|>


<commit_before>#include <ros/ros.h>
#include <sensor_msgs/Image.h>
#include <sensor_msgs/image_encodings.h>
#include <cv_bridge/cv_bridge.h>
#include <opencv2/opencv.hpp>
#include <opencv2/core/mat.hpp>
#include <fstream>
#include <iostream>
#include <igvc_utils/NodeUtils.hpp>

ros::Publisher img_pub_lines;
ros::Publisher img_pub_barrels;
sensor_msgs::Image outmsg_lines;
sensor_msgs::Image outmsg_barrels;

/*
 * Responsible for detecting the lines (currently set to a purple color) and
 * illuminating them as white (and setting all other pixels to black).
 */
void handle_image_lines(const sensor_msgs::ImageConstPtr& msg) {

  cv_bridge::CvImagePtr cv_ptr;
  cv::Mat frame;

  try {
    cv_ptr = cv_bridge::toCvCopy(msg, "bgr8");
  } catch (cv_bridge::Exception& e) {
    ROS_ERROR("CV-Bridge error: %s", e.what());
    return;
  }

  frame = cv_ptr->image;
  cv::Mat output(frame.rows, frame.cols, CV_8UC1, cv::Scalar::all(0));

  // Set color ranges (8 bit BGR) for line detection
  const int min_b = 120;
  const int max_b = 140;
  const int min_g = 0;
  const int max_g = 20;
  const int min_r = 70;
  const int max_r = 85;

  const int white_color = 255;
  const int black_color = 0;

  for(int rowCount=0; rowCount<frame.rows; ++rowCount) {
    for(int columnCount=0; columnCount<frame.cols; ++columnCount)  {

      cv::Vec3b color = frame.at<cv::Vec3b>(cv::Point(columnCount,rowCount));

      if (int(color.val[0]) > min_b && int(color.val[0]) < max_b && int(color.val[1]) >= min_g && int(color.val[1]) < max_g && int(color.val[2]) > min_r && int(color.val[2]) < max_r) {
        output.at<uchar>(cv::Point(columnCount, rowCount)) = white_color;
      } else {
        output.at<uchar>(cv::Point(columnCount, rowCount)) = black_color;
      }
    }
  }

  sensor_msgs::Image outmsg;
  outmsg.header = msg->header;
  cv_ptr->image = output;
  cv_ptr->encoding = "mono8";
  cv_ptr->toImageMsg(outmsg);
  outmsg_lines = outmsg;
}

/*
 * Responsible for detecting the barrels (white and orange components) and
 * illuminating them as white (and setting all other pixels to black).
 */
void handle_image_barrels(const sensor_msgs::ImageConstPtr& msg) {

  cv_bridge::CvImagePtr cv_ptr;
  cv::Mat frame;

  try {
    cv_ptr = cv_bridge::toCvCopy(msg, "bgr8");
  } catch (cv_bridge::Exception& e) {
    ROS_ERROR("CV-Bridge error: %s", e.what());
    return;
  }

  frame = cv_ptr->image;
  cv::Mat output(frame.rows, frame.cols, CV_8UC1, cv::Scalar::all(0));

  // Set color ranges (8 bit BGR) for barrel detection
  // Detects the black base of the barrel
  const int max_b_obstacle_black = 45;
  const int max_g_obstacle_black = 45;
  const int max_r_obstacle_black = 45;

  // Detects the orange parts of the barrel
  const int max_g_obstacle_orange = 160;
  const int min_r_obstacle_orange = 240;

  // Detects the white parts of the barrel
  const int min_b_obstacle_white = 230;
  const int min_g_obstacle_white = 230;
  const int min_r_obstacle_white = 230;

  const int white_color = 255;
  const int black_color = 0;

  for(int rowCount=0; rowCount<frame.rows; ++rowCount) {
    for(int columnCount=0; columnCount<frame.cols; ++columnCount)  {

      cv::Vec3b color = frame.at<cv::Vec3b>(cv::Point(columnCount,rowCount));

      if (int(color.val[0]) < max_b_obstacle_black && int(color.val[1]) < max_g_obstacle_black && int(color.val[2]) < max_r_obstacle_black) {
        output.at<uchar>(cv::Point(columnCount, rowCount)) = white_color;
      } else if (int(color.val[1]) < max_g_obstacle_orange && int(color.val[2]) > min_r_obstacle_orange) {
        output.at<uchar>(cv::Point(columnCount, rowCount)) = white_color;
      } else if (int(color.val[0]) > min_b_obstacle_white && int(color.val[1]) > min_g_obstacle_white && int(color.val[2]) > min_r_obstacle_white) {
        output.at<uchar>(cv::Point(columnCount, rowCount)) = white_color;
      } else {
        output.at<uchar>(cv::Point(columnCount, rowCount)) = black_color;
      }
    }
  }

  sensor_msgs::Image outmsg;
  outmsg.header = msg->header;
  cv_ptr->image = output;
  cv_ptr->encoding = "mono8";
  cv_ptr->toImageMsg(outmsg);
  outmsg_barrels = outmsg;
}

/*
 * Takes the most recent messages from the handle_image_lines and
 * handle_image_barrels functions and publishes them once triggered
 * by a a ros::Timer
 */
void publish(const ros::TimerEvent&)
{
  img_pub_barrels.publish(outmsg_barrels);
  img_pub_lines.publish(outmsg_lines);
}

/*
 * Responsible for setting up the publishers and triggering the functions to
 * update the detected black-and-white images
 */
int main(int argc, char** argv) {

  ros::init(argc, argv, "sim_color_detector");

  // LINES

  ros::NodeHandle nh_lines;
  ros::NodeHandle pNh_lines("~");

  std::string topic_name_lines;

  igvc::param(pNh_lines, "image_topic", topic_name_lines, std::string("/center_cam/image_raw"));

  img_pub_lines = nh_lines.advertise<sensor_msgs::Image>("/usb_cam_center/detected_lines", 1);

  ros::Subscriber img_sub_lines = nh_lines.subscribe(topic_name_lines, 1, handle_image_lines);

  // BARRELS

  ros::NodeHandle nh_barrels;
  ros::NodeHandle pNh_barrels("~");

  std::string topic_name_barrels;

  igvc::param(pNh_barrels, "image_topic", topic_name_barrels, std::string("/center_cam/image_raw"));

  img_pub_barrels = nh_barrels.advertise<sensor_msgs::Image>("/usb_cam_center/detected_barrels", 1);

  ros::Subscriber img_sub_barrels = nh_barrels.subscribe(topic_name_barrels, 1, handle_image_barrels);

  ros::NodeHandle nh;

  // Will call publish to update the published topics -> Set the publishing rate here
  ros::Timer timer = nh.createTimer(ros::Duration(1.0/30), publish);

  ros::spin();

  return 0;
}
<commit_msg>Added additional documentation requested by Alejandro.<commit_after>/*
 * Node responsible for (color) detecting the lines and barrels in the Gazebo
 * simulator. Receives the raw image and publishes two different B&W images
 * (one for line detection, one for barrel detection) that each highlight
 * their respective features in white. Integrated with a ros::Timer to publish at
 * a specified rate.
 */

#include <ros/ros.h>
#include <sensor_msgs/Image.h>
#include <sensor_msgs/image_encodings.h>
#include <cv_bridge/cv_bridge.h>
#include <opencv2/opencv.hpp>
#include <opencv2/core/mat.hpp>
#include <fstream>
#include <iostream>
#include <igvc_utils/NodeUtils.hpp>

ros::Publisher img_pub_lines;
ros::Publisher img_pub_barrels;
sensor_msgs::Image outmsg_lines;
sensor_msgs::Image outmsg_barrels;

/*
 * Responsible for detecting the lines (currently set to a purple color) and
 * illuminating them as white (and setting all other pixels to black).
 */
void handle_image_lines(const sensor_msgs::ImageConstPtr& msg) {

  cv_bridge::CvImagePtr cv_ptr;
  cv::Mat frame;

  try {
    cv_ptr = cv_bridge::toCvCopy(msg, "bgr8");
  } catch (cv_bridge::Exception& e) {
    ROS_ERROR("CV-Bridge error: %s", e.what());
    return;
  }

  frame = cv_ptr->image; // Input image
  cv::Mat output(frame.rows, frame.cols, CV_8UC1, cv::Scalar::all(0)); // Ouput image (B&W)

  // Set color ranges (8 bit BGR) for line detection -> looking for purple
  const int min_b = 120;
  const int max_b = 140;
  const int min_g = 0;
  const int max_g = 20;
  const int min_r = 70;
  const int max_r = 85;

  const int white_color = 255;
  const int black_color = 0;

  for(int rowCount=0; rowCount<frame.rows; ++rowCount) {
    for(int columnCount=0; columnCount<frame.cols; ++columnCount)  {

      cv::Vec3b color = frame.at<cv::Vec3b>(cv::Point(columnCount,rowCount));

      if (int(color.val[0]) > min_b && int(color.val[0]) < max_b && int(color.val[1]) >= min_g && int(color.val[1]) < max_g && int(color.val[2]) > min_r && int(color.val[2]) < max_r) {
        output.at<uchar>(cv::Point(columnCount, rowCount)) = white_color;
      } else {
        output.at<uchar>(cv::Point(columnCount, rowCount)) = black_color;
      }
    }
  }

  sensor_msgs::Image outmsg;
  outmsg.header = msg->header;
  cv_ptr->image = output;
  cv_ptr->encoding = "mono8";
  cv_ptr->toImageMsg(outmsg);
  outmsg_lines = outmsg;
}

/*
 * Responsible for detecting the barrels (white and orange components) and
 * illuminating them as white (and setting all other pixels to black).
 */
void handle_image_barrels(const sensor_msgs::ImageConstPtr& msg) {

  cv_bridge::CvImagePtr cv_ptr;
  cv::Mat frame;

  try {
    cv_ptr = cv_bridge::toCvCopy(msg, "bgr8");
  } catch (cv_bridge::Exception& e) {
    ROS_ERROR("CV-Bridge error: %s", e.what());
    return;
  }

  frame = cv_ptr->image; // Input image
  cv::Mat output(frame.rows, frame.cols, CV_8UC1, cv::Scalar::all(0)); // Ouput image (B&W)

  // Set color ranges (8 bit BGR) for barrel detection
  // Detects the black base of the barrel
  const int max_b_obstacle_black = 45;
  const int max_g_obstacle_black = 45;
  const int max_r_obstacle_black = 45;

  // Detects the orange parts of the barrel
  const int max_g_obstacle_orange = 160;
  const int min_r_obstacle_orange = 240;

  // Detects the white parts of the barrel
  const int min_b_obstacle_white = 230;
  const int min_g_obstacle_white = 230;
  const int min_r_obstacle_white = 230;

  const int white_color = 255;
  const int black_color = 0;

  for(int rowCount=0; rowCount<frame.rows; ++rowCount) {
    for(int columnCount=0; columnCount<frame.cols; ++columnCount)  {

      cv::Vec3b color = frame.at<cv::Vec3b>(cv::Point(columnCount,rowCount));

      if (int(color.val[0]) < max_b_obstacle_black && int(color.val[1]) < max_g_obstacle_black && int(color.val[2]) < max_r_obstacle_black) {
        output.at<uchar>(cv::Point(columnCount, rowCount)) = white_color;
      } else if (int(color.val[1]) < max_g_obstacle_orange && int(color.val[2]) > min_r_obstacle_orange) {
        output.at<uchar>(cv::Point(columnCount, rowCount)) = white_color;
      } else if (int(color.val[0]) > min_b_obstacle_white && int(color.val[1]) > min_g_obstacle_white && int(color.val[2]) > min_r_obstacle_white) {
        output.at<uchar>(cv::Point(columnCount, rowCount)) = white_color;
      } else {
        output.at<uchar>(cv::Point(columnCount, rowCount)) = black_color;
      }
    }
  }

  sensor_msgs::Image outmsg;
  outmsg.header = msg->header;
  cv_ptr->image = output;
  cv_ptr->encoding = "mono8";
  cv_ptr->toImageMsg(outmsg);
  outmsg_barrels = outmsg;
}

/*
 * Takes the most recent messages from the handle_image_lines and
 * handle_image_barrels functions and publishes them once triggered
 * by a a ros::Timer
 */
void publish(const ros::TimerEvent&)
{
  img_pub_barrels.publish(outmsg_barrels);
  img_pub_lines.publish(outmsg_lines);
}

/*
 * Responsible for setting up the publishers and triggering the functions to
 * update the detected black-and-white images
 */
int main(int argc, char** argv) {

  ros::init(argc, argv, "sim_color_detector");

  // LINES

  ros::NodeHandle nh_lines;
  ros::NodeHandle pNh_lines("~");

  std::string topic_name_lines;

  igvc::param(pNh_lines, "image_topic", topic_name_lines, std::string("/center_cam/image_raw"));

  img_pub_lines = nh_lines.advertise<sensor_msgs::Image>("/usb_cam_center/detected_lines", 1);

  ros::Subscriber img_sub_lines = nh_lines.subscribe(topic_name_lines, 1, handle_image_lines);

  // BARRELS

  ros::NodeHandle nh_barrels;
  ros::NodeHandle pNh_barrels("~");

  std::string topic_name_barrels;

  igvc::param(pNh_barrels, "image_topic", topic_name_barrels, std::string("/center_cam/image_raw"));

  img_pub_barrels = nh_barrels.advertise<sensor_msgs::Image>("/usb_cam_center/detected_barrels", 1);

  ros::Subscriber img_sub_barrels = nh_barrels.subscribe(topic_name_barrels, 1, handle_image_barrels);

  ros::NodeHandle nh;

  // Will call publish to update the published topics -> Set the publishing rate here
  ros::Timer timer = nh.createTimer(ros::Duration(1.0/30), publish);

  ros::spin();

  return 0;
}
<|endoftext|>


<commit_before>/**
 * @file ZooKeeperEevent.hpp
 * @author Zhongxia Li
 * @date Sep 7, 2011
 * @brief
 */
#ifndef ZOO_KEEPER_EVENT_HPP_
#define ZOO_KEEPER_EVENT_HPP_

#include <3rdparty/zookeeper/zookeeper.h>

namespace zookeeper{

class ZooKeeperEvent
{
public:
    int type_;
    int state_;
    std::string path_;

public:
    ZooKeeperEvent()
    : type_(0), state_(0), path_()
    {
    }

    ZooKeeperEvent(int type, int state, const std::string path)
    : type_(type), state_(state), path_(path)
    {
    }

    static std::string state2String(int state)
    {
        if (state == 0) {
            return "ZOO_CLOSED_STATE";
        }
        else if (state == ZOO_CONNECTING_STATE) {
            return "ZOO_CONNECTING_STATE";
        }
        else if (state == ZOO_ASSOCIATING_STATE) {
            return "ZOO_ASSOCIATING_STATE";
        }
        else if (state == ZOO_EXPIRED_SESSION_STATE) {
            return "ZOO_EXPIRED_SESSION_STATE";
        }
        else if (state == ZOO_AUTH_FAILED_STATE) {
            return "ZOO_AUTH_FAILED_STATE";
        }
        return "INVALID_STATE";
    }

    static std::string watcherEvent2String(int ev)
    {
        if (ev == 0) {
            return "ZOO_ERROR_EVENT";
        }
        else if (ev == ZOO_CREATED_EVENT) {
            return "ZOO_CREATED_EVENT";
        }
        else if (ev == ZOO_DELETED_EVENT) {
            return "ZOO_DELETED_EVENT";
        }
        else if (ev == ZOO_CHANGED_EVENT) {
            return "ZOO_CHANGED_EVENT";
        }
        else if (ev == ZOO_CHILD_EVENT) {
            return "ZOO_CHILD_EVENT";
        }
        else if (ev == ZOO_SESSION_EVENT) {
            return "ZOO_SESSION_EVENT";
        }
        else if (ev == ZOO_NOTWATCHING_EVENT) {
            return "ZOO_NOTWATCHING_EVENT";
        }
        return "INVALID_EVENT";
    }
};

class ZooKeeperEventHandler
{
public:
    ZooKeeperEventHandler() {}
    virtual ~ZooKeeperEventHandler() {}

public:
    /// will be called on any event.
    virtual void process(ZooKeeperEvent& zkEvent) {}

    virtual void onNodeCreated(const std::string& path) {}
    virtual void onNodeDeleted(const std::string& path) {}
    virtual void onDataChanged(const std::string& path) {}
    virtual void onChildrenChanged(const std::string& path) {}

    virtual void onSessionClosed() {}
    virtual void onSessionConnected() {}
    virtual void onSessionExpired() {}
    virtual void onAuthFailed() {}
};

}

#endif /* ZOO_KEEPER_EVENT_HPP_ */
<commit_msg>add help function for zookeeper.<commit_after>/**
 * @file ZooKeeperEevent.hpp
 * @author Zhongxia Li
 * @date Sep 7, 2011
 * @brief
 */
#ifndef ZOO_KEEPER_EVENT_HPP_
#define ZOO_KEEPER_EVENT_HPP_

#include <3rdparty/zookeeper/zookeeper.h>
#include <sstream>

namespace zookeeper{

class ZooKeeperEvent
{
public:
    int type_;
    int state_;
    std::string path_;

public:
    ZooKeeperEvent()
    : type_(0), state_(0), path_()
    {
    }

    ZooKeeperEvent(int type, int state, const std::string path)
    : type_(type), state_(state), path_(path)
    {
    }

    std::string toString()
    {
        std::stringstream ss;
        ss << "[ZooKeeperEvent] "<<path_<<" - "<<watcherEvent2String(type_)<<" - "<<state2String(state_)<<std::endl;
        return ss.str();
    }

    static std::string state2String(int state)
    {
        if (state == 0) {
            return "ZOO_CLOSED_STATE";
        }
        else if (state == ZOO_CONNECTING_STATE) {
            return "ZOO_CONNECTING_STATE";
        }
        else if (state == ZOO_ASSOCIATING_STATE) {
            return "ZOO_ASSOCIATING_STATE";
        }
        else if (state == ZOO_EXPIRED_SESSION_STATE) {
            return "ZOO_EXPIRED_SESSION_STATE";
        }
        else if (state == ZOO_AUTH_FAILED_STATE) {
            return "ZOO_AUTH_FAILED_STATE";
        }
        return "INVALID_STATE";
    }

    static std::string watcherEvent2String(int ev)
    {
        if (ev == 0) {
            return "ZOO_ERROR_EVENT";
        }
        else if (ev == ZOO_CREATED_EVENT) {
            return "ZOO_CREATED_EVENT";
        }
        else if (ev == ZOO_DELETED_EVENT) {
            return "ZOO_DELETED_EVENT";
        }
        else if (ev == ZOO_CHANGED_EVENT) {
            return "ZOO_CHANGED_EVENT";
        }
        else if (ev == ZOO_CHILD_EVENT) {
            return "ZOO_CHILD_EVENT";
        }
        else if (ev == ZOO_SESSION_EVENT) {
            return "ZOO_SESSION_EVENT";
        }
        else if (ev == ZOO_NOTWATCHING_EVENT) {
            return "ZOO_NOTWATCHING_EVENT";
        }
        return "INVALID_EVENT";
    }
};

class ZooKeeperEventHandler
{
public:
    ZooKeeperEventHandler() {}
    virtual ~ZooKeeperEventHandler() {}

public:
    /// will be called on any event.
    virtual void process(ZooKeeperEvent& zkEvent) {}

    virtual void onNodeCreated(const std::string& path) {}
    virtual void onNodeDeleted(const std::string& path) {}
    virtual void onDataChanged(const std::string& path) {}
    virtual void onChildrenChanged(const std::string& path) {}

    virtual void onSessionClosed() {}
    virtual void onSessionConnected() {}
    virtual void onSessionExpired() {}
    virtual void onAuthFailed() {}
};

}

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


<commit_before>#include <Riostream.h>
#include "TVirtualMCApplication.h"
#include "TVirtualMCStack.h"
#include "TFluka.h"
// Fluka include
#include "Fdimpar.h"  //(DIMPAR) fluka include
#include "Fdblprc.h"  //(DBLPRC) fluka common
#include "Ftrackr.h"  //(TRACKR) fluka common

#ifndef WIN32
# define mgdraw mgdraw_
#else
# define mgdraw MGDRAW
#endif

extern "C" {
void mgdraw(Int_t& icode, Int_t& mreg)
{
    TFluka* fluka =  (TFluka*) gMC;
    Int_t verbosityLevel = fluka->GetVerbosityLevel();
//
//  Make sure that stack has currrent track Id
    Int_t trackId = TRACKR.ispusr[mkbmx2-1];
    TVirtualMCStack* cppstack = fluka->GetStack();
    cppstack->SetCurrentTrack(trackId);
//
//
    Int_t oldreg = ((TFluka*) gMC)->GetMreg();
    if (oldreg != mreg) {
//
//  Boundary Crossing
//
	fluka->SetNewreg(mreg);
	if (oldreg == -1) fluka->SetMreg(mreg);
	if (verbosityLevel >= 3)
	    printf("Boundary Crossing %d %d \n", oldreg, mreg);
    } else {
	fluka->SetMreg(mreg);
	fluka->SetNewreg(mreg);
	if (verbosityLevel >= 3)
	    printf("Normal step %d %d \n", oldreg, mreg);
    }
    fluka->SetIcode(icode);

    cout << endl << " !!! I am in mgdraw - calling Stepping()" << endl;
    cout << endl << " Track Id =" << trackId << endl;

    fluka->FutoTest();

    if (oldreg != mreg) {
//
//  Double step for boundary crossing
//
	fluka->SetTrackIsExiting();
	(TVirtualMCApplication::Instance())->Stepping();
	fluka->SetMreg(mreg);
	fluka->SetTrackIsEntering();
	(TVirtualMCApplication::Instance())->Stepping();
	fluka->SetTrackIsInside();
    } else {
	(TVirtualMCApplication::Instance())->Stepping();
    }
} // end of mgdraw
} // end of extern "C"

<commit_msg>Introduce verbosity level.<commit_after>#include <Riostream.h>
#include "TVirtualMCApplication.h"
#include "TVirtualMCStack.h"
#include "TFluka.h"
// Fluka include
#include "Fdimpar.h"  //(DIMPAR) fluka include
#include "Fdblprc.h"  //(DBLPRC) fluka common
#include "Ftrackr.h"  //(TRACKR) fluka common

#ifndef WIN32
# define mgdraw mgdraw_
#else
# define mgdraw MGDRAW
#endif

extern "C" {
void mgdraw(Int_t& icode, Int_t& mreg)
{
    TFluka* fluka =  (TFluka*) gMC;
    Int_t verbosityLevel = fluka->GetVerbosityLevel();
//
//  Make sure that stack has currrent track Id
    Int_t trackId = TRACKR.ispusr[mkbmx2-1];
    TVirtualMCStack* cppstack = fluka->GetStack();
    cppstack->SetCurrentTrack(trackId);
//
//
    Int_t oldreg = ((TFluka*) gMC)->GetMreg();
    if (oldreg != mreg) {
//
//  Boundary Crossing
//
	fluka->SetNewreg(mreg);
	if (oldreg == -1) fluka->SetMreg(mreg);
	if (verbosityLevel >= 3)
	    printf("Boundary Crossing %d %d \n", oldreg, mreg);
    } else {
	fluka->SetMreg(mreg);
	fluka->SetNewreg(mreg);
	if (verbosityLevel >= 3)
	    printf("Normal step %d %d \n", oldreg, mreg);
    }
    fluka->SetIcode(icode);
    if (verbosityLevel >= 3) {
	cout << endl << " !!! I am in mgdraw - calling Stepping()" << endl;
	cout << endl << " Track Id =" << trackId << endl;
    }

    fluka->FutoTest();

    if (oldreg != mreg) {
//
//  Double step for boundary crossing
//
	fluka->SetTrackIsExiting();
	(TVirtualMCApplication::Instance())->Stepping();
	fluka->SetMreg(mreg);
	fluka->SetTrackIsEntering();
	(TVirtualMCApplication::Instance())->Stepping();
	fluka->SetTrackIsInside();
    } else {
	(TVirtualMCApplication::Instance())->Stepping();
    }
} // end of mgdraw
} // end of extern "C"

<|endoftext|>


<commit_before><commit_msg>Added a header file<commit_after><|endoftext|>


<commit_before>/*
 * This is part of the FL library, a C++ Bayesian filtering library
 * (https://github.com/filtering-library)
 *
 * Copyright (c) 2014 Jan Issac (jan.issac@gmail.com)
 * Copyright (c) 2014 Manuel Wuthrich (manuel.wuthrich@gmail.com)
 *
 * Max-Planck Institute for Intelligent Systems, AMD Lab
 * University of Southern California, CLMC Lab
 *
 * This Source Code Form is subject to the terms of the MIT License (MIT).
 * A copy of the license can be found in the LICENSE file distributed with this
 * source code.
 */

/**
 * \file moments.hpp
 * \date May 2014
 * \author Manuel Wuthrich (manuel.wuthrich@gmail.com)
 * \author Jan Issac (jan.issac@gmail.com)
 */

#ifndef FL__DISTRIBUTION__INTERFACE__MOMENTS_HPP
#define FL__DISTRIBUTION__INTERFACE__MOMENTS_HPP

#include <fl/distribution/interface/approximate_moments.hpp>

namespace fl
{

/**
 * \interface Moments
 * \ingroup distribution_interfaces
 *
 * \brief Moments is the interface providing the first two moments
 *
 * \tparam Variate        Random variable type. This is equivalent to the first
 *                        moment type.
 * \tparam SecondMoment   Second moment type. The second moment is either
 *                        the second uncentered moment \f$Var(X) + X^2\f$ or
 *                        simply the second central moment, the variance or
 *                        covariance \f$Var(X) = Cov(X, X)\f$. Both have the
 *                        same type \c SecondMoment.
 *
 *
 * The Moments interface provides access to the exact first moments of
 * a distribution. The moments represent a subset of the approximate moments.
 */
template <typename Variate, typename SecondMoment>
class Moments:
    public ApproximateMoments<Variate, SecondMoment>
{
public:
    /**
     * \brief Overridable default destructor
     */
    virtual ~Moments() { }

    /**
     * \return First moment of the underlying distribution, the mean
     *
     * \f$ \mu = \sum\limits_i x_i p(x_i)\f$
     */
    virtual Variate mean() const = 0;

    /**
     * \return Second centered moment of the underlying distribution,
     *         the covariance
     *
     * \f$ \Sigma =
     *     \sum\limits_i (x_i - \mu)(x_i - \mu)^T \f$
     */
    virtual SecondMoment covariance() const = 0;

    /**
     * \copydoc ApproximateMoments::approximate_mean
     */
    virtual Variate approximate_mean() const
    {
        return mean();
    }

    /**
     * \copydoc ApproximateMoments::approximate_covariance
     */
    virtual SecondMoment approximate_covariance() const
    {
        return covariance();
    }
};

}

#endif
<commit_msg>Moments moments interface can now be entirely defined in terms of the Variate type and fl::Real.<commit_after>/*
 * This is part of the FL library, a C++ Bayesian filtering library
 * (https://github.com/filtering-library)
 *
 * Copyright (c) 2014 Jan Issac (jan.issac@gmail.com)
 * Copyright (c) 2014 Manuel Wuthrich (manuel.wuthrich@gmail.com)
 *
 * Max-Planck Institute for Intelligent Systems, AMD Lab
 * University of Southern California, CLMC Lab
 *
 * This Source Code Form is subject to the terms of the MIT License (MIT).
 * A copy of the license can be found in the LICENSE file distributed with this
 * source code.
 */

/**
 * \file moments.hpp
 * \date May 2014
 * \author Manuel Wuthrich (manuel.wuthrich@gmail.com)
 * \author Jan Issac (jan.issac@gmail.com)
 */

#ifndef FL__DISTRIBUTION__INTERFACE__MOMENTS_HPP
#define FL__DISTRIBUTION__INTERFACE__MOMENTS_HPP

#include <fl/util/types.hpp>
#include <fl/util/traits.hpp>
#include <fl/distribution/interface/approximate_moments.hpp>

namespace fl
{

// Forward declaration
template <typename...> class Moments;

/**
 * \ingroup distribution_interfaces
 *
 * \brief Represents the interface providing the first two moments
 *
 * \tparam Variate        Random variable type. This is equivalent to the first
 *                        moment type.
 * \tparam SecondMoment   Second moment type. The second moment is either
 *                        the second uncentered moment \f$Var(X) + X^2\f$ or
 *                        simply the second central moment, the variance or
 *                        covariance \f$Var(X) = Cov(X, X)\f$. Both have the
 *                        same type \c SecondMoment.
 *
 *
 * The Moments interface provides access to the exact first moments of
 * a distribution. The moments represent a subset of the approximate moments.
 */
template <typename Variate_, typename SecondMoment_>
class Moments<Variate_, SecondMoment_>
    : public ApproximateMoments<Variate_, SecondMoment_>
{
public:
    /**
     * \brief Variate Random variable type. This is equivalent to the first
     *        moment type.
     */
    typedef Variate_ Variate;

    /**
     * \brief Second central moment type (e.g. Variance or the Covariance)
     */
    typedef SecondMoment_ SecondMoment;

    /**
     * \brief Overridable default destructor
     */
    virtual ~Moments() { }

    /**
     * \return First moment of the underlying distribution, the mean
     *
     * \f$ \mu = \sum\limits_i x_i p(x_i)\f$
     */
    virtual Variate mean() const = 0;

    /**
     * \return Second centered moment of the underlying distribution,
     *         the covariance
     *
     * \f$ \Sigma =
     *     \sum\limits_i (x_i - \mu)(x_i - \mu)^T \f$
     */
    virtual SecondMoment covariance() const = 0;

    /**
     * \copydoc ApproximateMoments::approximate_mean
     */
    virtual Variate approximate_mean() const
    {
        return mean();
    }

    /**
     * \copydoc ApproximateMoments::approximate_covariance
     */
    virtual SecondMoment approximate_covariance() const
    {
        return covariance();
    }
};

/**
 * \ingroup distribution_interfaces
 */
template <typename Variate>
class Moments<Variate>
    : public Moments<Variate, typename SecondMomentOf<Variate>::Type>
{
public:
    /**
     * \brief Overridable default destructor
     */
    virtual ~Moments() { }
};

/**
 * \ingroup distribution_interfaces
 */
template <>
class Moments<Real>
    : public Moments<Real, Real>
{
public:
    /**
     * \brief Overridable default destructor
     */
    virtual ~Moments() { }
};

}

#endif
<|endoftext|>