<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/>.
 */
/* Patch from Trevor Smigiel                                   */
#if !defined(HPUXDEFINITIONS_HEADER_GUARD_1357924680)
#define HPUXDEFINITIONS_HEADER_GUARD_1357924680

// ---------------------------------------------------------------------------
//  A define in the build for each project is also used to control whether
//  the export keyword is from the project's viewpoint or the client's.
//  These defines provide the platform specific keywords that they need
//  to do this.
// ---------------------------------------------------------------------------

#define XALAN_PLATFORM_EXPORT
#define XALAN_PLATFORM_IMPORT
#define XALAN_PLATFORM_EXPORT_FUNCTION(T) T XALAN_PLATFORM_EXPORT
#define XALAN_PLATFORM_IMPORT_FUNCTION(T) T XALAN_PLATFORM_IMPORT

#define XALAN_OLD_STREAM_HEADERS
#define XALAN_NO_IOSFWD
#define XALAN_RTTI_AVAILABLE
#define XALAN_NO_TYPEINFO
#define XALAN_SGI_BASED_STL
#define XALAN_NO_NAMESPACES
#define XALAN_XALANDOMCHAR_USHORT_MISMATCH
#define XALAN_NO_STD_ALLOCATORS
#define XALAN_POSIX2_AVAILABLE
#define XALAN_BIG_ENDIAN

#define XALAN_UNALIGNED

#endif  // HPUXDEFINITIONS_HEADER_GUARD_1357924680

<commit_msg>Removed #define.<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/>.
 */
/* Patch from Trevor Smigiel                                   */
#if !defined(HPUXDEFINITIONS_HEADER_GUARD_1357924680)
#define HPUXDEFINITIONS_HEADER_GUARD_1357924680

// ---------------------------------------------------------------------------
//  A define in the build for each project is also used to control whether
//  the export keyword is from the project's viewpoint or the client's.
//  These defines provide the platform specific keywords that they need
//  to do this.
// ---------------------------------------------------------------------------

#define XALAN_PLATFORM_EXPORT
#define XALAN_PLATFORM_IMPORT
#define XALAN_PLATFORM_EXPORT_FUNCTION(T) T XALAN_PLATFORM_EXPORT
#define XALAN_PLATFORM_IMPORT_FUNCTION(T) T XALAN_PLATFORM_IMPORT

#define XALAN_OLD_STREAM_HEADERS
#define XALAN_NO_IOSFWD
#define XALAN_RTTI_AVAILABLE
#define XALAN_SGI_BASED_STL
#define XALAN_NO_NAMESPACES
#define XALAN_XALANDOMCHAR_USHORT_MISMATCH
#define XALAN_NO_STD_ALLOCATORS
#define XALAN_POSIX2_AVAILABLE
#define XALAN_BIG_ENDIAN

#define XALAN_UNALIGNED

#endif  // HPUXDEFINITIONS_HEADER_GUARD_1357924680

<|endoftext|>


<commit_before>#ifndef Rice__detail__Caster__hpp_
#define Rice__detail__Caster__hpp_

#include "../Module.hpp"
#include <stdexcept>

namespace Rice
{

namespace detail
{

class Abstract_Caster
{
public:
  virtual void * cast_to_base(void * derived, Module type) const = 0;
  virtual ~Abstract_Caster() { }
};

template<typename Derived_T, typename Base_T>
class Caster
  : public Abstract_Caster
{
public:
  Caster(Abstract_Caster * base_caster, Module type)
    : base_caster_(base_caster)
    , type_(type)
  {
  }

protected:
  virtual void * cast_to_base(void * derived, Module type) const
  {
    if(type.value() == type_.value())
    {
      Derived_T * d(static_cast<Derived_T *>(derived));
      return static_cast<Base_T *>(d);
    }
    else
    {
      if(base_caster_)
      {
        return base_caster_->cast_to_base(derived, type);
      }
      else
      {
        throw std::runtime_error("bad cast");
      }
    }
  }

private:
  Abstract_Caster * base_caster_;
  Module type_;
};

} // detail

} // Rice

#endif //Rice__detail__Caster__hpp_
<commit_msg>Make the bad-cast message more explicit<commit_after>#ifndef Rice__detail__Caster__hpp_
#define Rice__detail__Caster__hpp_

#include "../Module.hpp"
#include <stdexcept>

namespace Rice
{

namespace detail
{

class Abstract_Caster
{
public:
  virtual void * cast_to_base(void * derived, Module type) const = 0;
  virtual ~Abstract_Caster() { }
};

template<typename Derived_T, typename Base_T>
class Caster
  : public Abstract_Caster
{
public:
  Caster(Abstract_Caster * base_caster, Module type)
    : base_caster_(base_caster)
    , type_(type)
  {
  }

protected:
  virtual void * cast_to_base(void * derived, Module type) const
  {
    if(type.value() == type_.value())
    {
      Derived_T * d(static_cast<Derived_T *>(derived));
      return static_cast<Base_T *>(d);
    }
    else
    {
      if(base_caster_)
      {
        return base_caster_->cast_to_base(derived, type);
      }
      else
      {
        std::string s = "bad cast from ";
        s += type_.name().str();
        s += " to ";
        s += type.name().str();
        throw std::runtime_error(s);
      }
    }
  }

private:
  Abstract_Caster * base_caster_;
  Module type_;
};

} // detail

} // Rice

#endif //Rice__detail__Caster__hpp_
<|endoftext|>


<commit_before>// $Id$

#include <iostream>
#include <iomanip>
#include <string>
#include <cstdio>
#include <cassert>
#include "Util.h"
#include "StaticData.h"
#include "ScoreIndexManager.h"
#include "ScoreProducer.h"
#include "ScoreComponentCollection.h" // debugging

namespace Moses
{
using namespace std;

void ScoreIndexManager::AddScoreProducer(const ScoreProducer* sp)
{
	// Producers must be inserted in the order they are created
	const_cast<ScoreProducer*>(sp)->CreateScoreBookkeepingID();
	assert(m_begins.size() == (sp->GetScoreBookkeepingID()));

	m_producers.push_back(sp);

	m_begins.push_back(m_last);
	size_t numScoreCompsProduced = sp->GetNumScoreComponents();
	assert(numScoreCompsProduced > 0);
	m_last += numScoreCompsProduced;
	m_ends.push_back(m_last);
	/*VERBOSE(1,"Added ScoreProducer(" << sp->GetScoreBookkeepingID()
						<< " " << sp->GetScoreProducerDescription()
						<< ") index=" << m_begins.back() << "-" << m_ends.back()-1 << std::endl);
	*/
}

void ScoreIndexManager::PrintLabeledScores(std::ostream& os, const ScoreComponentCollection& scores) const
{
	std::vector<float> weights(scores.m_scores.size(), 1.0f);
	PrintLabeledWeightedScores(os, scores, weights);
}

void ScoreIndexManager::PrintLabeledWeightedScores(std::ostream& os, const ScoreComponentCollection& scores, const std::vector<float>& weights) const
{
  assert(m_featureShortNames.size() == weights.size());
	string lastName = "";
  for (size_t i = 0; i < m_featureShortNames.size(); ++i)
	{
		if (i>0)
		{
			os << " ";
		}
		if (lastName != m_featureShortNames[i])
		{
			os << m_featureShortNames[i] << ": ";
			lastName = m_featureShortNames[i];
		}
    os << weights[i] * scores[i];
	}
}

void ScoreIndexManager::InitFeatureNames() {
	m_featureNames.clear();
	m_featureIndexes.clear();
	m_featureShortNames.clear();
	size_t globalIndex = 0;
	vector<const ScoreProducer *>::const_iterator it;

	for (it = m_producers.begin(); it != m_producers.end(); ++it) {
		size_t scoreCount = (*it)->GetNumInputScores();
		for (size_t i = 0; i < scoreCount; ++i) {
			ostringstream oStream;
			oStream << (*it)->GetScoreProducerDescription() << "_" << globalIndex;
			m_featureNames.push_back(oStream.str());
			m_featureIndexes[oStream.str()] = globalIndex;
			++globalIndex;
		}
	}
}

#ifdef HAVE_PROTOBUF
void ScoreIndexManager::SerializeFeatureNamesToPB(hgmert::Hypergraph* hg) const {
	for (size_t i = 0; i < m_featureNames.size(); ++i) {
		hg->add_feature_names(m_featureNames[i]);
	}
}
#endif

void ScoreIndexManager::InitWeightVectorFromFile(const std::string& fnam, vector<float>* m_allWeights) const {
	assert(m_allWeights->size() == m_featureNames.size());
	ifstream in(fnam.c_str());
	assert(in.good());
	char buf[2000];
	map<string, double> name2val;
	while (!in.eof()) {
		in.getline(buf, 2000);
		if (strlen(buf) == 0) continue;
		if (buf[0] == '#') continue;
		istringstream is(buf);
		string fname;
		double val;
		is >> fname >> val;
		map<string, double>::iterator i = name2val.find(fname);
		assert(i == name2val.end()); // duplicate weight name
		name2val[fname] = val;
	}
	assert(m_allWeights->size() == m_featureNames.size());
	for (size_t i = 0; i < m_featureNames.size(); ++i) {
		map<string, double>::iterator iter = name2val.find(m_featureNames[i]);
		if (iter == name2val.end()) {
			cerr << "No weight found found for feature: " << m_featureNames[i] << endl;
			abort();
		}
		(*m_allWeights)[i] = iter->second;
	}
}

std::ostream& operator<<(std::ostream& os, const ScoreIndexManager& sim)
{
	for (size_t i = 0; i < sim.m_featureNames.size(); ++i) {
		os << sim.m_featureNames[i] << endl;
	}
	os  << endl;
	return os;
}

const std::string &ScoreIndexManager::GetFeatureName(size_t fIndex) const
{
	assert(m_featureNames.size() > fIndex);
	return m_featureNames[fIndex];
}
//! get the index of a feature by name
size_t ScoreIndexManager::GetFeatureIndex(const std::string& fName) const
{
	return m_featureIndexes.find(fName)->second;
}

}
<commit_msg>mira<commit_after>// $Id$

#include <iostream>
#include <iomanip>
#include <string>
#include <cstdio>
#include <cassert>
#include "Util.h"
#include "StaticData.h"
#include "ScoreIndexManager.h"
#include "ScoreProducer.h"
#include "ScoreComponentCollection.h" // debugging

namespace Moses
{
using namespace std;

void ScoreIndexManager::AddScoreProducer(const ScoreProducer* sp)
{
	// Producers must be inserted in the order they are created
	const_cast<ScoreProducer*>(sp)->CreateScoreBookkeepingID();
	assert(m_begins.size() == (sp->GetScoreBookkeepingID()));

	m_producers.push_back(sp);

	m_begins.push_back(m_last);
	size_t numScoreCompsProduced = sp->GetNumScoreComponents();
	assert(numScoreCompsProduced > 0);
	m_last += numScoreCompsProduced;
	m_ends.push_back(m_last);
	InitFeatureNames();
	/*VERBOSE(1,"Added ScoreProducer(" << sp->GetScoreBookkeepingID()
						<< " " << sp->GetScoreProducerDescription()
						<< ") index=" << m_begins.back() << "-" << m_ends.back()-1 << std::endl);
	*/
}

void ScoreIndexManager::PrintLabeledScores(std::ostream& os, const ScoreComponentCollection& scores) const
{
	std::vector<float> weights(scores.m_scores.size(), 1.0f);
	PrintLabeledWeightedScores(os, scores, weights);
}

void ScoreIndexManager::PrintLabeledWeightedScores(std::ostream& os, const ScoreComponentCollection& scores, const std::vector<float>& weights) const
{
  assert(m_featureShortNames.size() == weights.size());
	string lastName = "";
  for (size_t i = 0; i < m_featureShortNames.size(); ++i)
	{
		if (i>0)
		{
			os << " ";
		}
		if (lastName != m_featureShortNames[i])
		{
			os << m_featureShortNames[i] << ": ";
			lastName = m_featureShortNames[i];
		}
    os << weights[i] * scores[i];
	}
}

void ScoreIndexManager::InitFeatureNames() {
	m_featureNames.clear();
	m_featureIndexes.clear();
	m_featureShortNames.clear();
	size_t cur_i = 0;
	size_t cur_scoreType = 0;
	while (cur_i < m_last) {
		size_t nis_idx = 0;
		bool add_idx = (m_producers[cur_scoreType]->GetNumInputScores() > 1);
		while (nis_idx < m_producers[cur_scoreType]->GetNumInputScores()){
			ostringstream os;
			//os << m_producers[cur_scoreType]->GetScoreProducerDescription();
			//if (add_idx)
				//os << '_' << (nis_idx+1);
			os << cur_i;
			const string &featureName = os.str();
			m_featureNames.push_back(featureName);
			m_featureIndexes[featureName] = m_featureNames.size() - 1;
			nis_idx++;
			cur_i++;
		}

		int ind = 1;
		add_idx = (m_ends[cur_scoreType] - cur_i > 1);
		while (cur_i < m_ends[cur_scoreType]) {
			ostringstream os;
			//os << m_producers[cur_scoreType]->GetScoreProducerDescription();
			//if (add_idx)
				//os << '_' << ind;
			os << cur_i;
			const string &featureName = os.str();
			m_featureNames.push_back(featureName);
			m_featureIndexes[featureName] = m_featureNames.size() - 1;
			m_featureShortNames.push_back( m_producers[cur_scoreType]->GetScoreProducerWeightShortName() );
			++cur_i;
			++ind;
		}
		cur_scoreType++;
	}
}

void ScoreIndexManager::InitFeatureNamesAles() {
	m_featureNames.clear();
	m_featureIndexes.clear();
	m_featureShortNames.clear();
	size_t globalIndex = 0;
	vector<const ScoreProducer *>::const_iterator it;

	for (it = m_producers.begin(); it != m_producers.end(); ++it) {
		size_t scoreCount = (*it)->GetNumInputScores();
		for (size_t i = 0; i < scoreCount; ++i) {
			ostringstream oStream;
			oStream << (*it)->GetScoreProducerDescription() << "_" << globalIndex;
			m_featureNames.push_back(oStream.str());
			m_featureIndexes[oStream.str()] = globalIndex;
			++globalIndex;
		}
	}
}

#ifdef HAVE_PROTOBUF
void ScoreIndexManager::SerializeFeatureNamesToPB(hgmert::Hypergraph* hg) const {
	for (size_t i = 0; i < m_featureNames.size(); ++i) {
		hg->add_feature_names(m_featureNames[i]);
	}
}
#endif

void ScoreIndexManager::InitWeightVectorFromFile(const std::string& fnam, vector<float>* m_allWeights) const {
	assert(m_allWeights->size() == m_featureNames.size());
	ifstream in(fnam.c_str());
	assert(in.good());
	char buf[2000];
	map<string, double> name2val;
	while (!in.eof()) {
		in.getline(buf, 2000);
		if (strlen(buf) == 0) continue;
		if (buf[0] == '#') continue;
		istringstream is(buf);
		string fname;
		double val;
		is >> fname >> val;
		map<string, double>::iterator i = name2val.find(fname);
		assert(i == name2val.end()); // duplicate weight name
		name2val[fname] = val;
	}
	assert(m_allWeights->size() == m_featureNames.size());
	for (size_t i = 0; i < m_featureNames.size(); ++i) {
		map<string, double>::iterator iter = name2val.find(m_featureNames[i]);
		if (iter == name2val.end()) {
			cerr << "No weight found found for feature: " << m_featureNames[i] << endl;
			abort();
		}
		(*m_allWeights)[i] = iter->second;
	}
}

std::ostream& operator<<(std::ostream& os, const ScoreIndexManager& sim)
{
	for (size_t i = 0; i < sim.m_featureNames.size(); ++i) {
		os << sim.m_featureNames[i] << endl;
	}
	os  << endl;
	return os;
}

const std::string &ScoreIndexManager::GetFeatureName(size_t fIndex) const
{
#ifndef NDEBUG
  if (m_featureNames.size() <= fIndex) {
      printf("%s: %i ScoreIndexManager::GetFeatureName(m_producers.size() = %zd, m_featureNames.size() = %zd, fIndex = %zd)\n", __FILE__, __LINE__, m_producers.size(), m_featureNames.size(), fIndex);
  }
#endif
	assert(m_featureNames.size() > fIndex);
	return m_featureNames[fIndex];
}
//! get the index of a feature by name
size_t ScoreIndexManager::GetFeatureIndex(const std::string& fName) const
{
	return m_featureIndexes.find(fName)->second;
}

}
<|endoftext|>


<commit_before>#include <config.h>
#include <davixcontext.hpp>
#include <davixuri.hpp>
#include <neon/neonsessionfactory.hpp>
#include <davix_context_internal.hpp>
#include <memory/memoryutils.hpp>

static const std::string _version = DAVIX_VERSION;

namespace Davix{

///  Implementation f the core logic in davix
struct ContextInternal
{
    ContextInternal(NEONSessionFactory * fsess):
        _fsess(fsess),
        _s_buff(65536),
        _timeout(300),
        _context_flags(0){}

    ContextInternal(const ContextInternal & orig):
        _fsess(new NEONSessionFactory()),
        _s_buff(orig._s_buff),
        _timeout(orig._timeout),
        _context_flags(orig._context_flags)
    {}

    virtual ~ContextInternal(){}

    // implementation of getSessionFactory
    inline NEONSessionFactory* getSessionFactory(){
         return _fsess.get();
    }

    void setBufferSize(const dav_size_t value){
      _s_buff = value;
    }

    ScopedPtr<NEONSessionFactory>::type  _fsess;
    dav_size_t _s_buff;
    unsigned long _timeout;
    bool _context_flags;
};

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

Context::Context() :
    _intern(new ContextInternal(new NEONSessionFactory()))
{
}

Context::Context(const Context &c) :
    _intern(new ContextInternal(*(c._intern))){
}

Context & Context::operator=(const Context & c){
    if( this != &c ){
        if( _intern != NULL)
            delete _intern;
        _intern = new ContextInternal(*(c._intern));
    }
    return *this;
}

Context::~Context(){
    delete _intern;
}

Context* Context::clone(){
    return new Context(*this);
}

void Context::setSessionCaching(bool caching){
    _intern->_fsess->setSessionCaching(caching);
}

bool Context::getSessionCaching() const{
    return _intern->_fsess->getSessionCaching();
}

HttpRequest* Context::createRequest(const std::string & url, DavixError** err){
    return new HttpRequest(*this, Uri(url), err);
}

HttpRequest* Context::createRequest(const Uri &uri, DavixError **err){
    return new HttpRequest(*this, uri, err);
}

NEONSessionFactory & ContextExplorer::SessionFactoryFromContext(Context & c){
    return *static_cast<NEONSessionFactory*>(c._intern->getSessionFactory());
}

const std::string & version(){
    return _version;
}

} // End Davix

<commit_msg>- switch main context to boost::scoped_ptr<commit_after>#include <config.h>
#include <davixcontext.hpp>
#include <davixuri.hpp>
#include <neon/neonsessionfactory.hpp>
#include <davix_context_internal.hpp>
#include <boost/scoped_ptr.hpp>

static const std::string _version = DAVIX_VERSION;

namespace Davix{

///  Implementation f the core logic in davix
struct ContextInternal
{
    ContextInternal(NEONSessionFactory * fsess):
        _fsess(fsess),
        _s_buff(65536),
        _timeout(300),
        _context_flags(0){}

    ContextInternal(const ContextInternal & orig):
        _fsess(new NEONSessionFactory()),
        _s_buff(orig._s_buff),
        _timeout(orig._timeout),
        _context_flags(orig._context_flags)
    {}

    virtual ~ContextInternal(){}

    // implementation of getSessionFactory
    inline NEONSessionFactory* getSessionFactory(){
         return _fsess.get();
    }

    void setBufferSize(const dav_size_t value){
      _s_buff = value;
    }

    boost::scoped_ptr<NEONSessionFactory>  _fsess;
    dav_size_t _s_buff;
    unsigned long _timeout;
    bool _context_flags;
};

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

Context::Context() :
    _intern(new ContextInternal(new NEONSessionFactory()))
{
}

Context::Context(const Context &c) :
    _intern(new ContextInternal(*(c._intern))){
}

Context & Context::operator=(const Context & c){
    if( this != &c ){
        if( _intern != NULL)
            delete _intern;
        _intern = new ContextInternal(*(c._intern));
    }
    return *this;
}

Context::~Context(){
    delete _intern;
}

Context* Context::clone(){
    return new Context(*this);
}

void Context::setSessionCaching(bool caching){
    _intern->_fsess->setSessionCaching(caching);
}

bool Context::getSessionCaching() const{
    return _intern->_fsess->getSessionCaching();
}

HttpRequest* Context::createRequest(const std::string & url, DavixError** err){
    return new HttpRequest(*this, Uri(url), err);
}

HttpRequest* Context::createRequest(const Uri &uri, DavixError **err){
    return new HttpRequest(*this, uri, err);
}

NEONSessionFactory & ContextExplorer::SessionFactoryFromContext(Context & c){
    return *static_cast<NEONSessionFactory*>(c._intern->getSessionFactory());
}

const std::string & version(){
    return _version;
}

} // End Davix

<|endoftext|>


<commit_before>#include "webcam.hpp"

using namespace cv;
using namespace std;

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

 CvCapture* capture = 0;
 int width, height, fps;

 capture = cvCaptureFromCAM(0);

 if (!capture) {
  printf("No camera detected!");
  return -1;
 }

 ifstream configFile (".config");

 if (configFile.is_open()) {

  //probably want to support corrupted .config
  string line;
  getline(configFile, line);
  istringstream(line)>>width;
  getline(configFile, line);
  istringstream(line)>>height;
  cvSetCaptureProperty(capture, CV_CAP_PROP_FRAME_WIDTH, width);
  cvSetCaptureProperty(capture, CV_CAP_PROP_FRAME_HEIGHT, height);

  configFile.close();

 } else {

  initResolutions();

  for (int i=36; i<150; i++) {
   cvSetCaptureProperty(capture, CV_CAP_PROP_FRAME_WIDTH, resolutions[i].width);
   cvSetCaptureProperty(capture, CV_CAP_PROP_FRAME_HEIGHT, resolutions[i].height);
  }

  width = cvGetCaptureProperty(capture, CV_CAP_PROP_FRAME_WIDTH);
  height = cvGetCaptureProperty(capture, CV_CAP_PROP_FRAME_HEIGHT);

  ofstream configFileOut(".config");
  configFileOut << width;
  configFileOut << "\n";
  configFileOut << height;
  configFileOut << "\n";
  configFileOut.close();
 }

 bool keepGoing = true;

// srand(890);//not interested in good randomness

 Mat image;
 while (keepGoing) {

  image = cvQueryFrame(capture);
  imshow("webcam", image);

// thresholds on dark regions
  Mat black, blurred;
  Mat channel[3];
  split(image, channel);
  equalizeHist(channel[0], channel[0]);
  equalizeHist(channel[1], channel[1]);
  equalizeHist(channel[2], channel[2]);
  merge(channel, 3, black);
  blur(black, blurred, Size(width/4.5,height/9));
  split(blurred, channel);
  black = (channel[0] + channel[1] + channel[2])/3.0;
  equalizeHist(black, black);
  bitwise_not(black,black);
  threshold(black, black, 210, 1, THRESH_BINARY);
//  imshow("black", black);

  split(image, channel);
  channel[0] = channel[0].mul(black);
  channel[1] = channel[1].mul(black);
  channel[2] = channel[2].mul(black);
  merge(channel, 3, image);
  //image = (image)/(255*255);
  imshow("yox", image);

//do some weird morphological closing thing
//  Mat channel[3];
  blur(image, image, Size(width/20, height/20));
  split(image, channel);
  image = (channel[0] + channel[1] + channel[2])/3.0;

  Mat smooth;
  Mat closed;
  Mat kernel = getStructuringElement(MORPH_ELLIPSE, Size(100,100));
  morphologyEx(image, closed, MORPH_CLOSE, kernel);
  divide(image, closed, closed, 1, CV_32F);
  normalize(closed, image, 0, 255, NORM_MINMAX, CV_8U);
  threshold(image, image, -1, 255, THRESH_BINARY_INV + THRESH_OTSU);
  imshow("yo", image);

/*
  Mat canny;
  Canny(image, canny, 0, 50);
  imshow("canny", canny);
*/

/*
  Mat fill = image.clone();
  Point seed(rand()%width, rand()%height);
  floodFill(fill, seed, Scalar(200,0,0), 0, Scalar(0,0,0), Scalar(25,25,25));
  imshow("fill", fill);
*/

  keepGoing = (waitKey(25)<0);

 }

 cvReleaseCapture(&capture);

 return 0;
}
<commit_msg>hacking<commit_after>#include "webcam.hpp"

using namespace cv;
using namespace std;

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

 CvCapture* capture = 0;
 int width, height, fps;

 capture = cvCaptureFromCAM(0);

 if (!capture) {
  printf("No camera detected!");
  return -1;
 }

 ifstream configFile (".config");

 if (configFile.is_open()) {

  //probably want to support corrupted .config
  string line;
  getline(configFile, line);
  istringstream(line)>>width;
  getline(configFile, line);
  istringstream(line)>>height;
  cvSetCaptureProperty(capture, CV_CAP_PROP_FRAME_WIDTH, width);
  cvSetCaptureProperty(capture, CV_CAP_PROP_FRAME_HEIGHT, height);

  configFile.close();

 } else {

  initResolutions();

  for (int i=36; i<150; i++) {
   cvSetCaptureProperty(capture, CV_CAP_PROP_FRAME_WIDTH, resolutions[i].width);
   cvSetCaptureProperty(capture, CV_CAP_PROP_FRAME_HEIGHT, resolutions[i].height);
  }

  width = cvGetCaptureProperty(capture, CV_CAP_PROP_FRAME_WIDTH);
  height = cvGetCaptureProperty(capture, CV_CAP_PROP_FRAME_HEIGHT);

  ofstream configFileOut(".config");
  configFileOut << width;
  configFileOut << "\n";
  configFileOut << height;
  configFileOut << "\n";
  configFileOut.close();
 }

 bool keepGoing = true;

// srand(890);//not interested in good randomness

 Mat image;
 while (keepGoing) {

  image = cvQueryFrame(capture);
  imshow("webcam", image);

// thresholds on dark regions
  Mat black, blurred;
  Mat channel[3];
  split(image, channel);
  equalizeHist(channel[0], channel[0]);
  equalizeHist(channel[1], channel[1]);
  equalizeHist(channel[2], channel[2]);
  merge(channel, 3, black);
  blur(black, blurred, Size(width/4.5,height/9));
  split(blurred, channel);
  black = (channel[0] + channel[1] + channel[2])/3.0;
  equalizeHist(black, black);
  bitwise_not(black,black);
  threshold(black, black, 210, 1, THRESH_BINARY);
//  imshow("black", black);

  split(image, channel);
  channel[0] = channel[0].mul(black);
  channel[1] = channel[1].mul(black);
  channel[2] = channel[2].mul(black);
  merge(channel, 3, image);
  //image = (image)/(255*255);
  imshow("yox", image);

//do some weird morphological closing thing
//  Mat channel[3];
  blur(image, image, Size(width/20, height/20));
  split(image, channel);
  image = (channel[0] + channel[1] + channel[2])/3.0;

  Mat smooth;
  Mat closed;
  Mat kernel = getStructuringElement(MORPH_ELLIPSE, Size(100,100));
  morphologyEx(image, closed, MORPH_CLOSE, kernel);
  divide(image, closed, closed, 1, CV_32F);
  normalize(closed, image, 0, 255, NORM_MINMAX, CV_8U);
  threshold(image, image, -1, 255, THRESH_BINARY_INV + THRESH_OTSU);
  imshow("yo", closed);

/*
  Mat canny;
  Canny(image, canny, 0, 50);
  imshow("canny", canny);
*/

/*
  Mat fill = image.clone();
  Point seed(rand()%width, rand()%height);
  floodFill(fill, seed, Scalar(200,0,0), 0, Scalar(0,0,0), Scalar(25,25,25));
  imshow("fill", fill);
*/

  keepGoing = (waitKey(25)<0);

 }

 cvReleaseCapture(&capture);

 return 0;
}
<|endoftext|>


<commit_before>#include "webcam.hpp"

using namespace cv;
using namespace std;

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

 CvCapture* capture = 0;
 int width, height, fps;

 capture = cvCaptureFromCAM(0);

 if (!capture) {
  printf("No camera detected!");
  return -1;
 }

 ifstream configFile (".config");

 if (configFile.is_open()) {

  //probably want to support corrupted .config
  string line;
  getline(configFile, line);
  istringstream(line)>>width;
  getline(configFile, line);
  istringstream(line)>>height;
  cvSetCaptureProperty(capture, CV_CAP_PROP_FRAME_WIDTH, width);
  cvSetCaptureProperty(capture, CV_CAP_PROP_FRAME_HEIGHT, height);

  configFile.close();

 } else {

  initResolutions();

  for (int i=36; i<150; i++) {
   cvSetCaptureProperty(capture, CV_CAP_PROP_FRAME_WIDTH, resolutions[i].width);
   cvSetCaptureProperty(capture, CV_CAP_PROP_FRAME_HEIGHT, resolutions[i].height);
  }

  width = cvGetCaptureProperty(capture, CV_CAP_PROP_FRAME_WIDTH);
  height = cvGetCaptureProperty(capture, CV_CAP_PROP_FRAME_HEIGHT);

  ofstream configFileOut(".config");
  configFileOut << width;
  configFileOut << "\n";
  configFileOut << height;
  configFileOut << "\n";
  configFileOut.close();
 }

 bool keepGoing = true;

// srand(890);//not interested in good randomness

 for (int i = 0; i < 30; i++) {
  // capture some frames so exposure correction takes place
  cvQueryFrame(capture);
 }

 Mat background = cvQueryFrame(capture);
 background = background.clone();
 blur(background, background, Size(50,50));
 imshow("background", background);

 Mat image;
 Mat channel[3];

 while (keepGoing) {

  image = cvQueryFrame(capture);
  //imshow("webcam", image);

  Mat gray;
  cvtColor(image, gray, CV_RGB2GRAY);

  Mat canny;
  Canny(gray, canny, 50, 50, 3);
  blur(canny, canny, Size(width/20,height/20));
  bitwise_not(canny, canny);
  threshold(canny, canny, 220, 1, THRESH_BINARY);
  imshow("canny1", canny*255);
  waitKey(1);

  int kwidth, kheight;
  if (width/2 > height) {
   kwidth = height/4;
   kheight = height/8;
  } else {
   kwidth = width/8;
   kheight = width/16;
  }

  kwidth += (1-(kwidth%2));//round up to nearest odd
  kheight += (1-(kheight%2));//round up to nearest odd
  Size kernelSize(kwidth, kheight);
  Mat kernel = getStructuringElement(MORPH_ELLIPSE, kernelSize);

  morphologyEx(canny, canny, MORPH_OPEN, kernel);
  imshow("canny2", canny*255);
  waitKey(1);
  Mat kernelSmall = getStructuringElement(MORPH_ELLIPSE, Size((kwidth/2)+(1-((kwidth/2)%2)),(kheight/2)+(1-((kheight/2)%2))));
  morphologyEx(canny, canny, MORPH_CLOSE, kernelSmall);
  imshow("canny3", canny*255);
  waitKey(1);
  erode(canny, canny, kernel);
  imshow("canny4", canny*255);
  waitKey(1);

  Mat flow;
  blur(image, flow, Size(50,50));
  absdiff(flow, background, flow);
  cvtColor(flow, flow, CV_RGB2GRAY);
  blur(flow, flow, Size(50,50));
  equalizeHist(flow, flow);
  Mat mask;
  threshold(flow, mask, 170, 1, THRESH_BINARY);
  mask = mask.mul(canny);
  dilate(mask, mask, kernel); // maybe repeat some more
  imshow("FLOW", gray.mul(mask));

//  Moments lol = moments(mask, 1);
//  circle(image, Point(lol.m10/lol.m00,lol.m01/lol.m00),20,Scalar(128),30);
//  imshow("leimage", image);

/*
  CascadeClassifier mouth_cascade;
  mouth_cascade.load("Mouth.xml");
  vector<Rect> mouths;
  Mat classifyThis;
  bilateralFilter(gray, classifyThis, 15, 10, 1);
  equalizeHist(classifyThis, classifyThis);
  classifyThis = classifyThis.mul(mask);
  mouth_cascade.detectMultiScale(classifyThis, mouths, 1.1, 2, CV_HAAR_SCALE_IMAGE);
  for (size_t i=0; i<mouths.size(); i++) {
   Point center( mouths[i].x + mouths[i].width*0.5, mouths[i].y + mouths[i].height*0.5 );
   ellipse( image, center, Size( mouths[i].width*0.5, mouths[i].height*0.5), 0, 0, 360, Scalar( 255, 0, 255 ), 4, 8, 0 );
  }
  imshow("MOUTH", image);
*/
  keepGoing = (waitKey(25)<0);

 }

 cvReleaseCapture(&capture);

 return 0;
}
<commit_msg>hacking<commit_after>#include "webcam.hpp"

using namespace cv;
using namespace std;

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

 CvCapture* capture = 0;
 int width, height, fps;

 capture = cvCaptureFromCAM(0);

 if (!capture) {
  printf("No camera detected!");
  return -1;
 }

 ifstream configFile (".config");

 if (configFile.is_open()) {

  //probably want to support corrupted .config
  string line;
  getline(configFile, line);
  istringstream(line)>>width;
  getline(configFile, line);
  istringstream(line)>>height;
  cvSetCaptureProperty(capture, CV_CAP_PROP_FRAME_WIDTH, width);
  cvSetCaptureProperty(capture, CV_CAP_PROP_FRAME_HEIGHT, height);

  configFile.close();

 } else {

  initResolutions();

  for (int i=36; i<150; i++) {
   cvSetCaptureProperty(capture, CV_CAP_PROP_FRAME_WIDTH, resolutions[i].width);
   cvSetCaptureProperty(capture, CV_CAP_PROP_FRAME_HEIGHT, resolutions[i].height);
  }

  width = cvGetCaptureProperty(capture, CV_CAP_PROP_FRAME_WIDTH);
  height = cvGetCaptureProperty(capture, CV_CAP_PROP_FRAME_HEIGHT);

  ofstream configFileOut(".config");
  configFileOut << width;
  configFileOut << "\n";
  configFileOut << height;
  configFileOut << "\n";
  configFileOut.close();
 }

 bool keepGoing = true;

// srand(890);//not interested in good randomness

 for (int i = 0; i < 30; i++) {
  // capture some frames so exposure correction takes place
  cvQueryFrame(capture);
 }

 Mat background = cvQueryFrame(capture);
 background = background.clone();
 blur(background, background, Size(50,50));
 imshow("background", background);

 Mat image;
 Mat channel[3];

 while (keepGoing) {

  image = cvQueryFrame(capture);
  //imshow("webcam", image);

  Mat gray;
  cvtColor(image, gray, CV_RGB2GRAY);

  Mat canny;
  Canny(gray, canny, 50, 50, 3);
  blur(canny, canny, Size(width/20,height/20));
  bitwise_not(canny, canny);
  threshold(canny, canny, 200, 1, THRESH_BINARY);
  imshow("canny1", canny*255);
  waitKey(1);

  int kwidth, kheight;
  if (width/2 > height) {
   kwidth = height/4;
   kheight = height/8;
  } else {
   kwidth = width/8;
   kheight = width/16;
  }

  kwidth += (1-(kwidth%2));//round up to nearest odd
  kheight += (1-(kheight%2));//round up to nearest odd
  Size kernelSize(kwidth, kheight);
  Mat kernel = getStructuringElement(MORPH_ELLIPSE, kernelSize);

  morphologyEx(canny, canny, MORPH_OPEN, kernel);
  imshow("canny2", canny*255);
  waitKey(1);
  Mat kernelSmall = getStructuringElement(MORPH_ELLIPSE, Size((kwidth/2)+(1-((kwidth/2)%2)),(kheight/2)+(1-((kheight/2)%2))));
  morphologyEx(canny, canny, MORPH_CLOSE, kernelSmall);
  imshow("canny3", canny*255);
  waitKey(1);

/*
  Mat flow;
  blur(image, flow, Size(50,50));
  absdiff(flow, background, flow);
  cvtColor(flow, flow, CV_RGB2GRAY);
  blur(flow, flow, Size(50,50));
  equalizeHist(flow, flow);
  Mat mask;
  threshold(flow, mask, 170, 1, THRESH_BINARY);
  mask = mask.mul(canny);
  dilate(mask, mask, kernel); // maybe repeat some more
  imshow("FLOW", gray.mul(mask));
*/

//  Moments lol = moments(mask, 1);
//  circle(image, Point(lol.m10/lol.m00,lol.m01/lol.m00),20,Scalar(128),30);
//  imshow("leimage", image);

/*
  CascadeClassifier mouth_cascade;
  mouth_cascade.load("Mouth.xml");
  vector<Rect> mouths;
  Mat classifyThis;
  bilateralFilter(gray, classifyThis, 15, 10, 1);
  equalizeHist(classifyThis, classifyThis);
  classifyThis = classifyThis.mul(mask);
  mouth_cascade.detectMultiScale(classifyThis, mouths, 1.1, 2, CV_HAAR_SCALE_IMAGE);
  for (size_t i=0; i<mouths.size(); i++) {
   Point center( mouths[i].x + mouths[i].width*0.5, mouths[i].y + mouths[i].height*0.5 );
   ellipse( image, center, Size( mouths[i].width*0.5, mouths[i].height*0.5), 0, 0, 360, Scalar( 255, 0, 255 ), 4, 8, 0 );
  }
  imshow("MOUTH", image);
*/
  keepGoing = (waitKey(25)<0);

 }

 cvReleaseCapture(&capture);

 return 0;
}
<|endoftext|>


<commit_before>//window.cpp
//window class implementation.

/* THIS CODE IS SHIT. */

#include "window.hpp"
using namespace std;

Window::Window() {
     //constructor.
     set_x(0.0);
     set_y(0.0);
     srand(time(NULL));
}

float Window::get_x() {
      return x;
}

float Window::get_y() {
      return y;
}

void Window::set_x(float new_x) {
     x = new_x;
}

void Window::set_y(float new_y) {
     y = new_y;
}

void Window::draw_grid() {
     //draws grid on map.
     float grid_x, grid_y, start_y, start_x;

     start_x = abs(get_x() - floor(get_x()));
     start_y = abs(get_y() - floor(get_y()));

     glPushMatrix();
     glLineWidth(1.0);
     glColor3f(0.0f,0.5f,0.0f);
     glBegin(GL_LINES);
     for (grid_y = 3.0 - start_y; grid_y >= -3.0 + start_y; grid_y -= 0.6)
     {
          glVertex2f(-3.0f, grid_y);
          glVertex2f(3.0f, grid_y);
     }
     for (grid_x = 3.0 - start_x; grid_x >= -3.0 + start_x; grid_x -= 0.6)
     {
          glVertex2f(grid_x, -3.0f);
          glVertex2f(grid_x, 3.0f);
     }
     glEnd();
     glPopMatrix();
}

void Window::draw_borders() {
    float horiz_top=3.0f, vert_right=3.4f, horiz_bottom=3.0f, vert_left=3.4f;

    glColor3f(1.0f,1.0f,1.0f);
    //check bounds and draw walls if necessary
    if (get_y() >= 5)
       horiz_top = 2.4f;
    if (get_y() <= -5)
       horiz_bottom = 2.4f;
    if (get_x() >= 5)
       vert_right = 3.0f;
    if (get_x() <= -5)
       vert_left = 3.0f;

    if (get_x() >= 4.8 && get_x() < 5)
    {
	     glBegin(GL_QUADS);									// scrolling right border.
              glVertex3f(get_x()-1.5, horiz_top, 0.0f);			// Top Left
		      glVertex3f(3.4f, horiz_top, 0.0f);					// Top Right
		      glVertex3f(get_x()-1.5,-horiz_bottom, 0.0f);			// Bottom Right
		      glVertex3f(3.4f,-horiz_bottom, 0.0f);					// Bottom Left
         glEnd();
    }
    if (get_x() >= 5)
    {
	     glBegin(GL_QUADS);									// right border.
              glVertex3f(3.0f, horiz_top, 0.0f);					// Top Left
		      glVertex3f(3.2f, horiz_top, 0.0f);					// Top Right
		      glVertex3f(3.2f,-horiz_bottom, 0.0f);					// Bottom Right
		      glVertex3f(3.0f,-horiz_bottom, 0.0f);					// Bottom Left
         glEnd();
    }
    if (get_x() <= -4.8 && get_x() > -5)
    {
	     glBegin(GL_QUADS);									// scrolling left border.
              glVertex3f(get_x()+1.5, horiz_top, 0.0f);			// Top Left
		      glVertex3f(-3.4f, horiz_top, 0.0f);		        // Top Right
		      glVertex3f(get_x()+1.5,-horiz_bottom, 0.0f);			// Bottom Right
		      glVertex3f(-3.4f,-horiz_bottom, 0.0f);				// Bottom Left
         glEnd();
    }
    if (get_x() <= -5)
    {
         glBegin(GL_QUADS);									// left border.
		      glVertex3f(-3.2f, horiz_top, 0.0f);				// Top Left
		      glVertex3f(-3.0f, horiz_top, 0.0f);				// Top Right
		      glVertex3f(-3.0f,-horiz_bottom, 0.0f);				// Bottom Right
		      glVertex3f(-3.2f,-horiz_bottom, 0.0f);				// Bottom Left
	     glEnd();
    }
    if (get_y() >= 4.8 && get_y() < 5)
    {
	     glBegin(GL_QUADS);									// scrolling top border.
              glVertex3f(-vert_left, 2.4f, 0.0f);		        // Top Left
		      glVertex3f(vert_right, 2.4f, 0.0f);					// Top Right
		      glVertex3f(vert_right, get_y()-2.4, 0.0f);		    // Bottom Right
		      glVertex3f(-vert_left,get_y()-2.4,0.0f);		    // Bottom Left
         glEnd();
    }
    if (get_y() >= 5)
    {
	     glBegin(GL_QUADS);									// top border.
              glVertex3f(-vert_left, 2.4f, 0.0f);		        // Top Left
		      glVertex3f(vert_right, 2.4f, 0.0f);					// Top Right
		      glVertex3f(vert_right, 2.2f, 0.0f);		            // Bottom Right
		      glVertex3f(-vert_left,2.2f,0.0f);		            // Bottom Left
         glEnd();
    }
    if (get_y() <= -4.8 && get_y() > -5)
    {
	     glBegin(GL_QUADS);									// scrolling bottom border.
              glVertex3f(-vert_left, -2.4f, 0.0f);		        // Top Left
		      glVertex3f(vert_right, -2.4f, 0.0f);					// Top Right
		      glVertex3f(vert_right, get_y()+2.6, 0.0f);		    // Bottom Right
		      glVertex3f(-vert_left,get_y()+2.6,0.0f);		    // Bottom Left
         glEnd();
    }
    if (get_y() <= -5)
    {
         glBegin(GL_QUADS);									// bottom border.
              glVertex3f(-vert_left, -2.2f, 0.0f);		        // Top Left
		      glVertex3f(vert_right, -2.2f, 0.0f);				// Top Right
		      glVertex3f(vert_right, -2.4f, 0.0f);		        // Bottom Right
		      glVertex3f(-vert_left,-2.4f,0.0f);		            // Bottom Left
	     glEnd();
    }
}
<commit_msg>Update window.cpp<commit_after>//window.cpp
//window class implementation.

/*
 * THIS CODE IS POSSIBLY THE BEST EVER WRITTEN IN THE HISTORY OF MANKIND.
 * JUST THOUGHT I'D LET YOU KNOW.
 */

#include "window.hpp"
using namespace std;

Window::Window() {
     //constructor.
     set_x(0.0);
     set_y(0.0);
     srand(time(NULL));
}

float Window::get_x() {
      return x;
}

float Window::get_y() {
      return y;
}

void Window::set_x(float new_x) {
     x = new_x;
}

void Window::set_y(float new_y) {
     y = new_y;
}

void Window::draw_grid() {
     //draws grid on map.
     float grid_x, grid_y, start_y, start_x;

     start_x = abs(get_x() - floor(get_x()));
     start_y = abs(get_y() - floor(get_y()));

     glPushMatrix();
     glLineWidth(1.0);
     glColor3f(0.0f,0.5f,0.0f);
     glBegin(GL_LINES);
     for (grid_y = 3.0 - start_y; grid_y >= -3.0 + start_y; grid_y -= 0.6)
     {
          glVertex2f(-3.0f, grid_y);
          glVertex2f(3.0f, grid_y);
     }
     for (grid_x = 3.0 - start_x; grid_x >= -3.0 + start_x; grid_x -= 0.6)
     {
          glVertex2f(grid_x, -3.0f);
          glVertex2f(grid_x, 3.0f);
     }
     glEnd();
     glPopMatrix();
}

void Window::draw_borders() {
    float horiz_top=3.0f, vert_right=3.4f, horiz_bottom=3.0f, vert_left=3.4f;

    glColor3f(1.0f,1.0f,1.0f);
    //check bounds and draw walls if necessary
    if (get_y() >= 5)
       horiz_top = 2.4f;
    if (get_y() <= -5)
       horiz_bottom = 2.4f;
    if (get_x() >= 5)
       vert_right = 3.0f;
    if (get_x() <= -5)
       vert_left = 3.0f;

    if (get_x() >= 4.8 && get_x() < 5)
    {
	     glBegin(GL_QUADS);									// scrolling right border.
              glVertex3f(get_x()-1.5, horiz_top, 0.0f);			// Top Left
		      glVertex3f(3.4f, horiz_top, 0.0f);					// Top Right
		      glVertex3f(get_x()-1.5,-horiz_bottom, 0.0f);			// Bottom Right
		      glVertex3f(3.4f,-horiz_bottom, 0.0f);					// Bottom Left
         glEnd();
    }
    if (get_x() >= 5)
    {
	     glBegin(GL_QUADS);									// right border.
              glVertex3f(3.0f, horiz_top, 0.0f);					// Top Left
		      glVertex3f(3.2f, horiz_top, 0.0f);					// Top Right
		      glVertex3f(3.2f,-horiz_bottom, 0.0f);					// Bottom Right
		      glVertex3f(3.0f,-horiz_bottom, 0.0f);					// Bottom Left
         glEnd();
    }
    if (get_x() <= -4.8 && get_x() > -5)
    {
	     glBegin(GL_QUADS);									// scrolling left border.
              glVertex3f(get_x()+1.5, horiz_top, 0.0f);			// Top Left
		      glVertex3f(-3.4f, horiz_top, 0.0f);		        // Top Right
		      glVertex3f(get_x()+1.5,-horiz_bottom, 0.0f);			// Bottom Right
		      glVertex3f(-3.4f,-horiz_bottom, 0.0f);				// Bottom Left
         glEnd();
    }
    if (get_x() <= -5)
    {
         glBegin(GL_QUADS);									// left border.
		      glVertex3f(-3.2f, horiz_top, 0.0f);				// Top Left
		      glVertex3f(-3.0f, horiz_top, 0.0f);				// Top Right
		      glVertex3f(-3.0f,-horiz_bottom, 0.0f);				// Bottom Right
		      glVertex3f(-3.2f,-horiz_bottom, 0.0f);				// Bottom Left
	     glEnd();
    }
    if (get_y() >= 4.8 && get_y() < 5)
    {
	     glBegin(GL_QUADS);									// scrolling top border.
              glVertex3f(-vert_left, 2.4f, 0.0f);		        // Top Left
		      glVertex3f(vert_right, 2.4f, 0.0f);					// Top Right
		      glVertex3f(vert_right, get_y()-2.4, 0.0f);		    // Bottom Right
		      glVertex3f(-vert_left,get_y()-2.4,0.0f);		    // Bottom Left
         glEnd();
    }
    if (get_y() >= 5)
    {
	     glBegin(GL_QUADS);									// top border.
              glVertex3f(-vert_left, 2.4f, 0.0f);		        // Top Left
		      glVertex3f(vert_right, 2.4f, 0.0f);					// Top Right
		      glVertex3f(vert_right, 2.2f, 0.0f);		            // Bottom Right
		      glVertex3f(-vert_left,2.2f,0.0f);		            // Bottom Left
         glEnd();
    }
    if (get_y() <= -4.8 && get_y() > -5)
    {
	     glBegin(GL_QUADS);									// scrolling bottom border.
              glVertex3f(-vert_left, -2.4f, 0.0f);		        // Top Left
		      glVertex3f(vert_right, -2.4f, 0.0f);					// Top Right
		      glVertex3f(vert_right, get_y()+2.6, 0.0f);		    // Bottom Right
		      glVertex3f(-vert_left,get_y()+2.6,0.0f);		    // Bottom Left
         glEnd();
    }
    if (get_y() <= -5)
    {
         glBegin(GL_QUADS);									// bottom border.
              glVertex3f(-vert_left, -2.2f, 0.0f);		        // Top Left
		      glVertex3f(vert_right, -2.2f, 0.0f);				// Top Right
		      glVertex3f(vert_right, -2.4f, 0.0f);		        // Bottom Right
		      glVertex3f(-vert_left,-2.4f,0.0f);		            // Bottom Left
	     glEnd();
    }
}
<|endoftext|>


<commit_before>#include "Print.hpp"
#include "BoundingBox.hpp"

namespace Slic3r {

bool
PrintState::started(PrintStep step) const
{
    return this->_started.find(step) != this->_started.end();
}

bool
PrintState::done(PrintStep step) const
{
    return this->_done.find(step) != this->_done.end();
}

void
PrintState::set_started(PrintStep step)
{
    this->_started.insert(step);
}

void
PrintState::set_done(PrintStep step)
{
    this->_done.insert(step);
}

void
PrintState::invalidate(PrintStep step)
{
    this->_started.erase(step);
    this->_done.erase(step);
}

void
PrintState::invalidate_all()
{
    this->_started.clear();
    this->_done.clear();
}

#ifdef SLIC3RXS
REGISTER_CLASS(PrintState, "Print::State");
#endif

PrintRegion::PrintRegion(Print* print)
:   config(), print(print)
{
}

PrintRegion::~PrintRegion()
{
}

PrintConfig &
PrintRegion::print_config()
{
    return print->config;
}

#ifdef SLIC3RXS
REGISTER_CLASS(PrintRegion, "Print::Region");
#endif

PrintObject::PrintObject(Print* print, ModelObject* model_object,
        const BoundingBoxf3 &modobj_bbox)
:   print(print),
    model_object(model_object)
{
    region_volumes.resize(print->regions.size());

    // Compute the translation to be applied to our meshes so that we work with smaller coordinates
    {
        // Translate meshes so that our toolpath generation algorithms work with smaller
        // XY coordinates; this translation is an optimization and not strictly required.
        // A cloned mesh will be aligned to 0 before slicing in _slice_region() since we
        // don't assume it's already aligned and we don't alter the original position in model.
        // We store the XY translation so that we can place copies correctly in the output G-code
        // (copies are expressed in G-code coordinates and this translation is not publicly exposed).
        this->_copies_shift = Point(modobj_bbox.min.x, modobj_bbox.min.y);
        this->_copies_shift.scale(SCALING_FACTOR);

        // TODO: $self->_trigger_copies;

        // Scale the object size and store it
        Pointf3 size = modobj_bbox.size();
        this->size = Point3(scale_(size.x), scale_(size.y), scale_(size.z));
    }
}

PrintObject::~PrintObject()
{
}

void
PrintObject::add_region_volume(int region_id, int volume_id)
{
    if (region_id >= region_volumes.size()) {
        region_volumes.resize(region_id + 1);
    }

    region_volumes[region_id].push_back(volume_id);
}

size_t
PrintObject::layer_count()
{
    return this->layers.size();
}

void
PrintObject::clear_layers()
{
    for (int i = this->layers.size()-1; i >= 0; --i)
        this->delete_layer(i);
}

Layer*
PrintObject::get_layer(int idx)
{
    return this->layers.at(idx);
}

Layer*
PrintObject::add_layer(int id, coordf_t height, coordf_t print_z,
    coordf_t slice_z)
{
    Layer* layer = new Layer(id, this, height, print_z, slice_z);
    layers.push_back(layer);
    return layer;
}

void
PrintObject::delete_layer(int idx)
{
    LayerPtrs::iterator i = this->layers.begin() + idx;
    Layer* item = *i;
    this->layers.erase(i);
    delete item;
}

size_t
PrintObject::support_layer_count()
{
    return this->support_layers.size();
}

void
PrintObject::clear_support_layers()
{
    for (int i = this->support_layers.size()-1; i >= 0; --i)
        this->delete_support_layer(i);
}

SupportLayer*
PrintObject::get_support_layer(int idx)
{
    return this->support_layers.at(idx);
}

SupportLayer*
PrintObject::add_support_layer(int id, coordf_t height, coordf_t print_z,
    coordf_t slice_z)
{
    SupportLayer* layer = new SupportLayer(id, this, height, print_z, slice_z);
    support_layers.push_back(layer);
    return layer;
}

void
PrintObject::delete_support_layer(int idx)
{
    SupportLayerPtrs::iterator i = this->support_layers.begin() + idx;
    SupportLayer* item = *i;
    this->support_layers.erase(i);
    delete item;
}

#ifdef SLIC3RXS
REGISTER_CLASS(PrintObject, "Print::Object");
#endif

Print::Print()
:   total_used_filament(0),
    total_extruded_volume(0)
{
}

Print::~Print()
{
    clear_objects();
    clear_regions();
}

void
Print::clear_objects()
{
    for (int i = this->objects.size()-1; i >= 0; --i)
        this->delete_object(i);

    this->clear_regions();

    this->_state.invalidate(psSkirt);
    this->_state.invalidate(psBrim);
}

PrintObject*
Print::get_object(int idx)
{
    return objects.at(idx);
}

PrintObject*
Print::add_object(ModelObject *model_object,
        const BoundingBoxf3 &modobj_bbox)
{
    PrintObject *object = new PrintObject(this, model_object, modobj_bbox);
    objects.push_back(object);
    return object;
}

PrintObject*
Print::set_new_object(size_t idx, ModelObject *model_object,
        const BoundingBoxf3 &modobj_bbox)
{
    if (idx < 0 || idx >= this->objects.size()) throw "bad idx";

    PrintObjectPtrs::iterator old_it = this->objects.begin() + idx;
    delete *old_it;

    PrintObject *object = new PrintObject(this, model_object, modobj_bbox);
    this->objects[idx] = object;
    return object;
}

void
Print::delete_object(int idx)
{
    PrintObjectPtrs::iterator i = this->objects.begin() + idx;
    PrintObject* item = *i;
    this->objects.erase(i);
    delete item;

    // TODO: purge unused regions

    this->_state.invalidate(psSkirt);
    this->_state.invalidate(psBrim);
}

void
Print::clear_regions()
{
    for (int i = this->regions.size()-1; i >= 0; --i)
        this->delete_region(i);
}

PrintRegion*
Print::get_region(int idx)
{
    return regions.at(idx);
}

PrintRegion*
Print::add_region()
{
    PrintRegion *region = new PrintRegion(this);
    regions.push_back(region);
    return region;
}

void
Print::delete_region(int idx)
{
    PrintRegionPtrs::iterator i = this->regions.begin() + idx;
    PrintRegion* item = *i;
    this->regions.erase(i);
    delete item;
}

#ifdef SLIC3RXS
REGISTER_CLASS(Print, "Print");
#endif

}
<commit_msg>Try to fix _copies_shift scaling.<commit_after>#include "Print.hpp"
#include "BoundingBox.hpp"

namespace Slic3r {

bool
PrintState::started(PrintStep step) const
{
    return this->_started.find(step) != this->_started.end();
}

bool
PrintState::done(PrintStep step) const
{
    return this->_done.find(step) != this->_done.end();
}

void
PrintState::set_started(PrintStep step)
{
    this->_started.insert(step);
}

void
PrintState::set_done(PrintStep step)
{
    this->_done.insert(step);
}

void
PrintState::invalidate(PrintStep step)
{
    this->_started.erase(step);
    this->_done.erase(step);
}

void
PrintState::invalidate_all()
{
    this->_started.clear();
    this->_done.clear();
}

#ifdef SLIC3RXS
REGISTER_CLASS(PrintState, "Print::State");
#endif

PrintRegion::PrintRegion(Print* print)
:   config(), print(print)
{
}

PrintRegion::~PrintRegion()
{
}

PrintConfig &
PrintRegion::print_config()
{
    return print->config;
}

#ifdef SLIC3RXS
REGISTER_CLASS(PrintRegion, "Print::Region");
#endif

PrintObject::PrintObject(Print* print, ModelObject* model_object,
        const BoundingBoxf3 &modobj_bbox)
:   print(print),
    model_object(model_object)
{
    region_volumes.resize(print->regions.size());

    // Compute the translation to be applied to our meshes so that we work with smaller coordinates
    {
        // Translate meshes so that our toolpath generation algorithms work with smaller
        // XY coordinates; this translation is an optimization and not strictly required.
        // A cloned mesh will be aligned to 0 before slicing in _slice_region() since we
        // don't assume it's already aligned and we don't alter the original position in model.
        // We store the XY translation so that we can place copies correctly in the output G-code
        // (copies are expressed in G-code coordinates and this translation is not publicly exposed).
        this->_copies_shift = Point(
            scale_(modobj_bbox.min.x), scale_(modobj_bbox.min.y));

        // TODO: $self->_trigger_copies;

        // Scale the object size and store it
        Pointf3 size = modobj_bbox.size();
        this->size = Point3(scale_(size.x), scale_(size.y), scale_(size.z));
    }
}

PrintObject::~PrintObject()
{
}

void
PrintObject::add_region_volume(int region_id, int volume_id)
{
    if (region_id >= region_volumes.size()) {
        region_volumes.resize(region_id + 1);
    }

    region_volumes[region_id].push_back(volume_id);
}

size_t
PrintObject::layer_count()
{
    return this->layers.size();
}

void
PrintObject::clear_layers()
{
    for (int i = this->layers.size()-1; i >= 0; --i)
        this->delete_layer(i);
}

Layer*
PrintObject::get_layer(int idx)
{
    return this->layers.at(idx);
}

Layer*
PrintObject::add_layer(int id, coordf_t height, coordf_t print_z,
    coordf_t slice_z)
{
    Layer* layer = new Layer(id, this, height, print_z, slice_z);
    layers.push_back(layer);
    return layer;
}

void
PrintObject::delete_layer(int idx)
{
    LayerPtrs::iterator i = this->layers.begin() + idx;
    Layer* item = *i;
    this->layers.erase(i);
    delete item;
}

size_t
PrintObject::support_layer_count()
{
    return this->support_layers.size();
}

void
PrintObject::clear_support_layers()
{
    for (int i = this->support_layers.size()-1; i >= 0; --i)
        this->delete_support_layer(i);
}

SupportLayer*
PrintObject::get_support_layer(int idx)
{
    return this->support_layers.at(idx);
}

SupportLayer*
PrintObject::add_support_layer(int id, coordf_t height, coordf_t print_z,
    coordf_t slice_z)
{
    SupportLayer* layer = new SupportLayer(id, this, height, print_z, slice_z);
    support_layers.push_back(layer);
    return layer;
}

void
PrintObject::delete_support_layer(int idx)
{
    SupportLayerPtrs::iterator i = this->support_layers.begin() + idx;
    SupportLayer* item = *i;
    this->support_layers.erase(i);
    delete item;
}

#ifdef SLIC3RXS
REGISTER_CLASS(PrintObject, "Print::Object");
#endif

Print::Print()
:   total_used_filament(0),
    total_extruded_volume(0)
{
}

Print::~Print()
{
    clear_objects();
    clear_regions();
}

void
Print::clear_objects()
{
    for (int i = this->objects.size()-1; i >= 0; --i)
        this->delete_object(i);

    this->clear_regions();

    this->_state.invalidate(psSkirt);
    this->_state.invalidate(psBrim);
}

PrintObject*
Print::get_object(int idx)
{
    return objects.at(idx);
}

PrintObject*
Print::add_object(ModelObject *model_object,
        const BoundingBoxf3 &modobj_bbox)
{
    PrintObject *object = new PrintObject(this, model_object, modobj_bbox);
    objects.push_back(object);
    return object;
}

PrintObject*
Print::set_new_object(size_t idx, ModelObject *model_object,
        const BoundingBoxf3 &modobj_bbox)
{
    if (idx < 0 || idx >= this->objects.size()) throw "bad idx";

    PrintObjectPtrs::iterator old_it = this->objects.begin() + idx;
    delete *old_it;

    PrintObject *object = new PrintObject(this, model_object, modobj_bbox);
    this->objects[idx] = object;
    return object;
}

void
Print::delete_object(int idx)
{
    PrintObjectPtrs::iterator i = this->objects.begin() + idx;
    PrintObject* item = *i;
    this->objects.erase(i);
    delete item;

    // TODO: purge unused regions

    this->_state.invalidate(psSkirt);
    this->_state.invalidate(psBrim);
}

void
Print::clear_regions()
{
    for (int i = this->regions.size()-1; i >= 0; --i)
        this->delete_region(i);
}

PrintRegion*
Print::get_region(int idx)
{
    return regions.at(idx);
}

PrintRegion*
Print::add_region()
{
    PrintRegion *region = new PrintRegion(this);
    regions.push_back(region);
    return region;
}

void
Print::delete_region(int idx)
{
    PrintRegionPtrs::iterator i = this->regions.begin() + idx;
    PrintRegion* item = *i;
    this->regions.erase(i);
    delete item;
}

#ifdef SLIC3RXS
REGISTER_CLASS(Print, "Print");
#endif

}
<|endoftext|>


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

#include <stdarg.h>
#include "demofile.h"
#include "demofiledump.h"

#include "google/protobuf/descriptor.h"
#include "google/protobuf/reflection_ops.h"
#include "google/protobuf/descriptor.pb.h"

#include "generated_proto/cstrike15_usermessages_public.pb.h"
#include "generated_proto/netmessages_public.pb.h"

__attribute__ (( noreturn )) void fatal_errorf( const char* fmt, ... )
{
    va_list  vlist;
    char buf[ 1024 ];

    va_start( vlist, fmt);
    vsnprintf( buf, sizeof( buf ), fmt, vlist );
	buf[ sizeof( buf ) - 1 ] = 0;
    va_end( vlist );

    fprintf( stderr, "\nERROR: %s\n", buf );
    exit( -1 );
}

bool CDemoFileDump::Open( const char *filename )
{
	if ( !m_demofile.Open( filename ) )
	{
		fprintf( stderr, "Couldn't open '%s'\n", filename );
		return false;
	}

	return true;
}

void CDemoFileDump::MsgPrintf( const ::google::protobuf::Message& msg, int size, const char *fmt, ... )
{
	va_list vlist;
	const std::string& TypeName = msg.GetTypeName();

	// Print the message type and size
	printf( "---- %s (%d bytes) -----------------\n", TypeName.c_str(), size );

	va_start( vlist, fmt);
	vprintf( fmt, vlist );
	va_end( vlist );
}

template < class T, int msgType >
void PrintUserMessage( CDemoFileDump& Demo, const void *parseBuffer, int BufferSize )
{
	T msg;

	if( msg.ParseFromArray( parseBuffer, BufferSize ) )
	{
		Demo.MsgPrintf( msg, BufferSize, "%s", msg.DebugString().c_str() );
	}
}

void CDemoFileDump::DumpUserMessage( const void *parseBuffer, int BufferSize )
{
	CSVCMsg_UserMessage userMessage;

	if( userMessage.ParseFromArray( parseBuffer, BufferSize ) )
	{
		int Cmd = userMessage.msg_type();
		int SizeUM = userMessage.msg_data().size();
		const void *parseBufferUM = &userMessage.msg_data()[ 0 ];
		switch( Cmd )
		{
#define HANDLE_UserMsg( _x )			case CS_UM_ ## _x: PrintUserMessage< CCSUsrMsg_ ## _x, CS_UM_ ## _x >( *this, parseBufferUM, SizeUM ); break

		default:
			// unknown user message
			break;
			HANDLE_UserMsg( VGUIMenu );
			HANDLE_UserMsg( Geiger );
			HANDLE_UserMsg( Train );
			HANDLE_UserMsg( HudText );
			HANDLE_UserMsg( SayText );
			HANDLE_UserMsg( SayText2 );
			HANDLE_UserMsg( TextMsg );
			HANDLE_UserMsg( HudMsg );
			HANDLE_UserMsg( ResetHud );
			HANDLE_UserMsg( GameTitle );
			HANDLE_UserMsg( Shake );
			HANDLE_UserMsg( Fade );
			HANDLE_UserMsg( Rumble );
			HANDLE_UserMsg( CloseCaption );
			HANDLE_UserMsg( CloseCaptionDirect );
			HANDLE_UserMsg( SendAudio );
			HANDLE_UserMsg( RawAudio );
			HANDLE_UserMsg( VoiceMask );
			HANDLE_UserMsg( RequestState );
			HANDLE_UserMsg( Damage );
			HANDLE_UserMsg( RadioText );
			HANDLE_UserMsg( HintText );
			HANDLE_UserMsg( KeyHintText );
			HANDLE_UserMsg( ProcessSpottedEntityUpdate );
			HANDLE_UserMsg( ReloadEffect );
			HANDLE_UserMsg( AdjustMoney );
			HANDLE_UserMsg( StopSpectatorMode );
			HANDLE_UserMsg( KillCam );
			HANDLE_UserMsg( DesiredTimescale );
			HANDLE_UserMsg( CurrentTimescale );
			HANDLE_UserMsg( AchievementEvent );
			HANDLE_UserMsg( MatchEndConditions );
			HANDLE_UserMsg( DisconnectToLobby );
			HANDLE_UserMsg( DisplayInventory );
			HANDLE_UserMsg( WarmupHasEnded );
			HANDLE_UserMsg( ClientInfo );
			HANDLE_UserMsg( CallVoteFailed );
			HANDLE_UserMsg( VoteStart );
			HANDLE_UserMsg( VotePass );
			HANDLE_UserMsg( VoteFailed );
			HANDLE_UserMsg( VoteSetup );
			HANDLE_UserMsg( SendLastKillerDamageToClient );
			HANDLE_UserMsg( ItemPickup );
			HANDLE_UserMsg( ShowMenu );
			HANDLE_UserMsg( BarTime );
			HANDLE_UserMsg( AmmoDenied );
			HANDLE_UserMsg( MarkAchievement );
			HANDLE_UserMsg( ItemDrop );
			HANDLE_UserMsg( GlowPropTurnOff );

#undef HANDLE_UserMsg
		}

	}
}

template < class T, int msgType >
void PrintNetMessage( CDemoFileDump& Demo, const void *parseBuffer, int BufferSize )
{
	T msg;

	if( msg.ParseFromArray( parseBuffer, BufferSize ) )
	{
		if( msgType == svc_GameEventList )
		{
			Demo.m_GameEventList.CopyFrom( msg );
		}

		Demo.MsgPrintf( msg, BufferSize, "%s", msg.DebugString().c_str() );
	}
}

template <>
void PrintNetMessage< CSVCMsg_UserMessage, svc_UserMessage >( CDemoFileDump& Demo, const void *parseBuffer, int BufferSize )
{
	Demo.DumpUserMessage( parseBuffer, BufferSize );
}

template <>
void PrintNetMessage< CSVCMsg_GameEvent, svc_GameEvent >( CDemoFileDump& Demo, const void *parseBuffer, int BufferSize )
{
	CSVCMsg_GameEvent msg;

	if( msg.ParseFromArray( parseBuffer, BufferSize ) )
	{
		int iDescriptor;

		for( iDescriptor = 0; iDescriptor < Demo.m_GameEventList.descriptors().size(); iDescriptor++ )
		{
			const CSVCMsg_GameEventList::descriptor_t& Descriptor = Demo.m_GameEventList.descriptors( iDescriptor );

			if( Descriptor.eventid() == msg.eventid() )
				break;
		}

		if( iDescriptor == Demo.m_GameEventList.descriptors().size() )
		{
			printf( "%s", msg.DebugString().c_str() );
		}
		else
		{
			int numKeys = msg.keys().size();
			const CSVCMsg_GameEventList::descriptor_t& Descriptor = Demo.m_GameEventList.descriptors( iDescriptor );

			printf( "%s eventid:%d %s\n", Descriptor.name().c_str(), msg.eventid(),
				msg.has_event_name() ? msg.event_name().c_str() : "" );

			for( int i = 0; i < numKeys; i++ )
			{
				const CSVCMsg_GameEventList::key_t& Key = Descriptor.keys( i );
				const CSVCMsg_GameEvent::key_t& KeyValue = msg.keys( i );

				printf(" %s: ", Key.name().c_str() );

				if( KeyValue.has_val_string() )
					printf( "%s ", KeyValue.val_string().c_str() );
				if( KeyValue.has_val_float() )
					printf( "%f ", KeyValue.val_float() );
				if( KeyValue.has_val_long() )
					printf( "%d ", KeyValue.val_long() );
				if( KeyValue.has_val_short() )
					printf( "%d ", KeyValue.val_short() );
				if( KeyValue.has_val_byte() )
					printf( "%d ", KeyValue.val_byte() );
				if( KeyValue.has_val_bool() )
					printf( "%d ", KeyValue.val_bool() );
				if( KeyValue.has_val_uint64() )
					printf( "%ld ", KeyValue.val_uint64() );

				printf( "\n" );
			}
		}
	}
}

static std::string GetNetMsgName( int Cmd )
{
	if( NET_Messages_IsValid( Cmd ) )
	{
		return NET_Messages_Name( ( NET_Messages )Cmd );
	}
	else if( SVC_Messages_IsValid( Cmd ) )
	{
		return SVC_Messages_Name( ( SVC_Messages )Cmd );
	}

	assert( 0 );
	return "NETMSG_???";
}

void CDemoFileDump::DumpDemoPacket( const char* buf, size_t length )
{
	size_t index = 0;

	while( index < length )
	{
		int Cmd = ReadVarInt32( buf, length, index );
		uint32 Size = ReadVarInt32( buf, length, index );

		if( index + Size > length )
		{
			const std::string& strName = GetNetMsgName( Cmd );

			fatal_errorf( "DumpDemoPacket()::failed parsing packet. Cmd:%d '%s' \n", Cmd, strName.c_str() );
		}

		switch( Cmd )
		{
#define HANDLE_NetMsg( _x )		case net_ ## _x: PrintNetMessage< CNETMsg_ ## _x, net_ ## _x >( *this, &buf[ index ], Size ); break
#define HANDLE_SvcMsg( _x )		case svc_ ## _x: PrintNetMessage< CSVCMsg_ ## _x, svc_ ## _x >( *this, &buf[ index ], Size ); break

		default:
			// unknown net message
			break;

		HANDLE_NetMsg( NOP );            	// 0
		HANDLE_NetMsg( Disconnect );        // 1
		HANDLE_NetMsg( File );              // 2
		HANDLE_NetMsg( Tick );              // 4
		HANDLE_NetMsg( StringCmd );         // 5
		HANDLE_NetMsg( SetConVar );         // 6
		HANDLE_NetMsg( SignonState );       // 7
		HANDLE_SvcMsg( ServerInfo );        // 8
		HANDLE_SvcMsg( SendTable );         // 9
		HANDLE_SvcMsg( ClassInfo );         // 10
		HANDLE_SvcMsg( SetPause );          // 11
		HANDLE_SvcMsg( CreateStringTable ); // 12
		HANDLE_SvcMsg( UpdateStringTable ); // 13
		HANDLE_SvcMsg( VoiceInit );         // 14
		HANDLE_SvcMsg( VoiceData );         // 15
		HANDLE_SvcMsg( Print );             // 16
		HANDLE_SvcMsg( Sounds );            // 17
		HANDLE_SvcMsg( SetView );           // 18
		HANDLE_SvcMsg( FixAngle );          // 19
		HANDLE_SvcMsg( CrosshairAngle );    // 20
		HANDLE_SvcMsg( BSPDecal );          // 21
		HANDLE_SvcMsg( UserMessage );       // 23
		HANDLE_SvcMsg( GameEvent );         // 25
		HANDLE_SvcMsg( PacketEntities );    // 26
		HANDLE_SvcMsg( TempEntities );      // 27
		HANDLE_SvcMsg( Prefetch );          // 28
		HANDLE_SvcMsg( Menu );              // 29
		HANDLE_SvcMsg( GameEventList );     // 30
		HANDLE_SvcMsg( GetCvarValue );      // 31

#undef HANDLE_SvcMsg
#undef HANDLE_NetMsg
		}

		index += Size;
	}
}

#define NET_MAX_PAYLOAD ( 262144 - 4 )	// largest message we can send in bytes
void CDemoFileDump::HandleDemoPacket()
{
	democmdinfo_t	info;
	int				dummy;
	char			buf[ NET_MAX_PAYLOAD ];

	m_demofile.ReadCmdInfo( info );
	m_demofile.ReadSequenceInfo( dummy, dummy );

	size_t length = m_demofile.ReadRawData( buf,  NET_MAX_PAYLOAD );

	if ( length > 0 )
	{
		DumpDemoPacket( buf, length );
	}
}

void CDemoFileDump::DoDump()
{
	bool demofinished = false;
	while ( !demofinished )
	{
		int				tick = 0;
		unsigned char	cmd;
		unsigned char	playerSlot;
		m_demofile.ReadCmdHeader( cmd, tick, playerSlot );

		// COMMAND HANDLERS
		switch ( cmd )
		{
		case dem_synctick:
			break;
		case dem_stop:
			{
				demofinished = true;
			}
			break;
		case dem_consolecmd:
			{
				m_demofile.ReadRawData( NULL, 0 );
			}
			break;
		case dem_datatables:
			{
				m_demofile.ReadRawData( NULL, 0 );
			}
			break;
		case dem_stringtables:
			{
				m_demofile.ReadRawData( NULL, 0 );
			}
			break;
		case dem_usercmd:
			{
				int	dummy;
				m_demofile.ReadUserCmd( NULL, dummy );
			}
			break;

		case dem_signon:
		case dem_packet:
			{
				HandleDemoPacket();
			}
			break;

		default:
			{
			}
			break;
		}
	}
}

<commit_msg>Fix uint64 warnings across platforms and architectures<commit_after>//====== Copyright (c) 2014, Valve Corporation, All rights reserved. ========//
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are met:
//
// Redistributions of source code must retain the above copyright notice, this
// list of conditions and the following disclaimer.
// Redistributions in binary form must reproduce the above copyright notice,
// this list of conditions and the following disclaimer in the documentation
// and/or other materials provided with the distribution.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF
// THE POSSIBILITY OF SUCH DAMAGE.
//===========================================================================//

#define __STDC_FORMAT_MACROS
#include <inttypes.h>
#include <stdarg.h>
#include "demofile.h"
#include "demofiledump.h"

#include "google/protobuf/descriptor.h"
#include "google/protobuf/reflection_ops.h"
#include "google/protobuf/descriptor.pb.h"

#include "generated_proto/cstrike15_usermessages_public.pb.h"
#include "generated_proto/netmessages_public.pb.h"

__attribute__ (( noreturn )) void fatal_errorf( const char* fmt, ... )
{
    va_list  vlist;
    char buf[ 1024 ];

    va_start( vlist, fmt);
    vsnprintf( buf, sizeof( buf ), fmt, vlist );
	buf[ sizeof( buf ) - 1 ] = 0;
    va_end( vlist );

    fprintf( stderr, "\nERROR: %s\n", buf );
    exit( -1 );
}

bool CDemoFileDump::Open( const char *filename )
{
	if ( !m_demofile.Open( filename ) )
	{
		fprintf( stderr, "Couldn't open '%s'\n", filename );
		return false;
	}

	return true;
}

void CDemoFileDump::MsgPrintf( const ::google::protobuf::Message& msg, int size, const char *fmt, ... )
{
	va_list vlist;
	const std::string& TypeName = msg.GetTypeName();

	// Print the message type and size
	printf( "---- %s (%d bytes) -----------------\n", TypeName.c_str(), size );

	va_start( vlist, fmt);
	vprintf( fmt, vlist );
	va_end( vlist );
}

template < class T, int msgType >
void PrintUserMessage( CDemoFileDump& Demo, const void *parseBuffer, int BufferSize )
{
	T msg;

	if( msg.ParseFromArray( parseBuffer, BufferSize ) )
	{
		Demo.MsgPrintf( msg, BufferSize, "%s", msg.DebugString().c_str() );
	}
}

void CDemoFileDump::DumpUserMessage( const void *parseBuffer, int BufferSize )
{
	CSVCMsg_UserMessage userMessage;

	if( userMessage.ParseFromArray( parseBuffer, BufferSize ) )
	{
		int Cmd = userMessage.msg_type();
		int SizeUM = userMessage.msg_data().size();
		const void *parseBufferUM = &userMessage.msg_data()[ 0 ];
		switch( Cmd )
		{
#define HANDLE_UserMsg( _x )			case CS_UM_ ## _x: PrintUserMessage< CCSUsrMsg_ ## _x, CS_UM_ ## _x >( *this, parseBufferUM, SizeUM ); break

		default:
			// unknown user message
			break;
			HANDLE_UserMsg( VGUIMenu );
			HANDLE_UserMsg( Geiger );
			HANDLE_UserMsg( Train );
			HANDLE_UserMsg( HudText );
			HANDLE_UserMsg( SayText );
			HANDLE_UserMsg( SayText2 );
			HANDLE_UserMsg( TextMsg );
			HANDLE_UserMsg( HudMsg );
			HANDLE_UserMsg( ResetHud );
			HANDLE_UserMsg( GameTitle );
			HANDLE_UserMsg( Shake );
			HANDLE_UserMsg( Fade );
			HANDLE_UserMsg( Rumble );
			HANDLE_UserMsg( CloseCaption );
			HANDLE_UserMsg( CloseCaptionDirect );
			HANDLE_UserMsg( SendAudio );
			HANDLE_UserMsg( RawAudio );
			HANDLE_UserMsg( VoiceMask );
			HANDLE_UserMsg( RequestState );
			HANDLE_UserMsg( Damage );
			HANDLE_UserMsg( RadioText );
			HANDLE_UserMsg( HintText );
			HANDLE_UserMsg( KeyHintText );
			HANDLE_UserMsg( ProcessSpottedEntityUpdate );
			HANDLE_UserMsg( ReloadEffect );
			HANDLE_UserMsg( AdjustMoney );
			HANDLE_UserMsg( StopSpectatorMode );
			HANDLE_UserMsg( KillCam );
			HANDLE_UserMsg( DesiredTimescale );
			HANDLE_UserMsg( CurrentTimescale );
			HANDLE_UserMsg( AchievementEvent );
			HANDLE_UserMsg( MatchEndConditions );
			HANDLE_UserMsg( DisconnectToLobby );
			HANDLE_UserMsg( DisplayInventory );
			HANDLE_UserMsg( WarmupHasEnded );
			HANDLE_UserMsg( ClientInfo );
			HANDLE_UserMsg( CallVoteFailed );
			HANDLE_UserMsg( VoteStart );
			HANDLE_UserMsg( VotePass );
			HANDLE_UserMsg( VoteFailed );
			HANDLE_UserMsg( VoteSetup );
			HANDLE_UserMsg( SendLastKillerDamageToClient );
			HANDLE_UserMsg( ItemPickup );
			HANDLE_UserMsg( ShowMenu );
			HANDLE_UserMsg( BarTime );
			HANDLE_UserMsg( AmmoDenied );
			HANDLE_UserMsg( MarkAchievement );
			HANDLE_UserMsg( ItemDrop );
			HANDLE_UserMsg( GlowPropTurnOff );

#undef HANDLE_UserMsg
		}

	}
}

template < class T, int msgType >
void PrintNetMessage( CDemoFileDump& Demo, const void *parseBuffer, int BufferSize )
{
	T msg;

	if( msg.ParseFromArray( parseBuffer, BufferSize ) )
	{
		if( msgType == svc_GameEventList )
		{
			Demo.m_GameEventList.CopyFrom( msg );
		}

		Demo.MsgPrintf( msg, BufferSize, "%s", msg.DebugString().c_str() );
	}
}

template <>
void PrintNetMessage< CSVCMsg_UserMessage, svc_UserMessage >( CDemoFileDump& Demo, const void *parseBuffer, int BufferSize )
{
	Demo.DumpUserMessage( parseBuffer, BufferSize );
}

template <>
void PrintNetMessage< CSVCMsg_GameEvent, svc_GameEvent >( CDemoFileDump& Demo, const void *parseBuffer, int BufferSize )
{
	CSVCMsg_GameEvent msg;

	if( msg.ParseFromArray( parseBuffer, BufferSize ) )
	{
		int iDescriptor;

		for( iDescriptor = 0; iDescriptor < Demo.m_GameEventList.descriptors().size(); iDescriptor++ )
		{
			const CSVCMsg_GameEventList::descriptor_t& Descriptor = Demo.m_GameEventList.descriptors( iDescriptor );

			if( Descriptor.eventid() == msg.eventid() )
				break;
		}

		if( iDescriptor == Demo.m_GameEventList.descriptors().size() )
		{
			printf( "%s", msg.DebugString().c_str() );
		}
		else
		{
			int numKeys = msg.keys().size();
			const CSVCMsg_GameEventList::descriptor_t& Descriptor = Demo.m_GameEventList.descriptors( iDescriptor );

			printf( "%s eventid:%d %s\n", Descriptor.name().c_str(), msg.eventid(),
				msg.has_event_name() ? msg.event_name().c_str() : "" );

			for( int i = 0; i < numKeys; i++ )
			{
				const CSVCMsg_GameEventList::key_t& Key = Descriptor.keys( i );
				const CSVCMsg_GameEvent::key_t& KeyValue = msg.keys( i );

				printf(" %s: ", Key.name().c_str() );

				if( KeyValue.has_val_string() )
					printf( "%s ", KeyValue.val_string().c_str() );
				if( KeyValue.has_val_float() )
					printf( "%f ", KeyValue.val_float() );
				if( KeyValue.has_val_long() )
					printf( "%d ", KeyValue.val_long() );
				if( KeyValue.has_val_short() )
					printf( "%d ", KeyValue.val_short() );
				if( KeyValue.has_val_byte() )
					printf( "%d ", KeyValue.val_byte() );
				if( KeyValue.has_val_bool() )
					printf( "%d ", KeyValue.val_bool() );
				if( KeyValue.has_val_uint64() )
					printf( "%"PRIu64, KeyValue.val_uint64() );

				printf( "\n" );
			}
		}
	}
}

static std::string GetNetMsgName( int Cmd )
{
	if( NET_Messages_IsValid( Cmd ) )
	{
		return NET_Messages_Name( ( NET_Messages )Cmd );
	}
	else if( SVC_Messages_IsValid( Cmd ) )
	{
		return SVC_Messages_Name( ( SVC_Messages )Cmd );
	}

	assert( 0 );
	return "NETMSG_???";
}

void CDemoFileDump::DumpDemoPacket( const char* buf, size_t length )
{
	size_t index = 0;

	while( index < length )
	{
		int Cmd = ReadVarInt32( buf, length, index );
		uint32 Size = ReadVarInt32( buf, length, index );

		if( index + Size > length )
		{
			const std::string& strName = GetNetMsgName( Cmd );

			fatal_errorf( "DumpDemoPacket()::failed parsing packet. Cmd:%d '%s' \n", Cmd, strName.c_str() );
		}

		switch( Cmd )
		{
#define HANDLE_NetMsg( _x )		case net_ ## _x: PrintNetMessage< CNETMsg_ ## _x, net_ ## _x >( *this, &buf[ index ], Size ); break
#define HANDLE_SvcMsg( _x )		case svc_ ## _x: PrintNetMessage< CSVCMsg_ ## _x, svc_ ## _x >( *this, &buf[ index ], Size ); break

		default:
			// unknown net message
			break;

		HANDLE_NetMsg( NOP );            	// 0
		HANDLE_NetMsg( Disconnect );        // 1
		HANDLE_NetMsg( File );              // 2
		HANDLE_NetMsg( Tick );              // 4
		HANDLE_NetMsg( StringCmd );         // 5
		HANDLE_NetMsg( SetConVar );         // 6
		HANDLE_NetMsg( SignonState );       // 7
		HANDLE_SvcMsg( ServerInfo );        // 8
		HANDLE_SvcMsg( SendTable );         // 9
		HANDLE_SvcMsg( ClassInfo );         // 10
		HANDLE_SvcMsg( SetPause );          // 11
		HANDLE_SvcMsg( CreateStringTable ); // 12
		HANDLE_SvcMsg( UpdateStringTable ); // 13
		HANDLE_SvcMsg( VoiceInit );         // 14
		HANDLE_SvcMsg( VoiceData );         // 15
		HANDLE_SvcMsg( Print );             // 16
		HANDLE_SvcMsg( Sounds );            // 17
		HANDLE_SvcMsg( SetView );           // 18
		HANDLE_SvcMsg( FixAngle );          // 19
		HANDLE_SvcMsg( CrosshairAngle );    // 20
		HANDLE_SvcMsg( BSPDecal );          // 21
		HANDLE_SvcMsg( UserMessage );       // 23
		HANDLE_SvcMsg( GameEvent );         // 25
		HANDLE_SvcMsg( PacketEntities );    // 26
		HANDLE_SvcMsg( TempEntities );      // 27
		HANDLE_SvcMsg( Prefetch );          // 28
		HANDLE_SvcMsg( Menu );              // 29
		HANDLE_SvcMsg( GameEventList );     // 30
		HANDLE_SvcMsg( GetCvarValue );      // 31

#undef HANDLE_SvcMsg
#undef HANDLE_NetMsg
		}

		index += Size;
	}
}

#define NET_MAX_PAYLOAD ( 262144 - 4 )	// largest message we can send in bytes
void CDemoFileDump::HandleDemoPacket()
{
	democmdinfo_t	info;
	int				dummy;
	char			buf[ NET_MAX_PAYLOAD ];

	m_demofile.ReadCmdInfo( info );
	m_demofile.ReadSequenceInfo( dummy, dummy );

	size_t length = m_demofile.ReadRawData( buf,  NET_MAX_PAYLOAD );

	if ( length > 0 )
	{
		DumpDemoPacket( buf, length );
	}
}

void CDemoFileDump::DoDump()
{
	bool demofinished = false;
	while ( !demofinished )
	{
		int				tick = 0;
		unsigned char	cmd;
		unsigned char	playerSlot;
		m_demofile.ReadCmdHeader( cmd, tick, playerSlot );

		// COMMAND HANDLERS
		switch ( cmd )
		{
		case dem_synctick:
			break;
		case dem_stop:
			{
				demofinished = true;
			}
			break;
		case dem_consolecmd:
			{
				m_demofile.ReadRawData( NULL, 0 );
			}
			break;
		case dem_datatables:
			{
				m_demofile.ReadRawData( NULL, 0 );
			}
			break;
		case dem_stringtables:
			{
				m_demofile.ReadRawData( NULL, 0 );
			}
			break;
		case dem_usercmd:
			{
				int	dummy;
				m_demofile.ReadUserCmd( NULL, dummy );
			}
			break;

		case dem_signon:
		case dem_packet:
			{
				HandleDemoPacket();
			}
			break;

		default:
			{
			}
			break;
		}
	}
}

<|endoftext|>


<commit_before>// Licensed GNU LGPL v2.1 or later: http://www.gnu.org/licenses/lgpl.html
#ifndef __SFI_WRAPPER_H__
#define __SFI_WRAPPER_H__
#include <stdbool.h>
#include <sfi/glib-extra.hh>
#include <birnet/birnetcdefs.h> /* include glib before birnet for G_LOG_DOMAIN */
#include <birnet/birnetutils.hh>

namespace Bse {

// == Likelyness Hinting ==
#define BSE_ISLIKELY(expr)      RAPICORN_ISLIKELY(expr) ///< Compiler hint that @a expr is likely to be true.
#define BSE_UNLIKELY(expr)      RAPICORN_UNLIKELY(expr) ///< Compiler hint that @a expr is unlikely to be true.
#define BSE_LIKELY              BSE_ISLIKELY            ///< Compiler hint that @a expr is likely to be true.

// == Debugging ==
/// Issue a general purpose debugging message, configurable via #$BSE_DEBUG.
#define BSE_DEBUG(...)          do { if (BSE_UNLIKELY (Bse::_cached_bse_debug)) Bse::bse_debug (NULL, RAPICORN_PRETTY_FILE, __LINE__, __VA_ARGS__); } while (0)
/// Issue a debugging message if debugging for @a key is enabled via #$BSE_DEBUG.
#define BSE_KEY_DEBUG(key,...)  do { if (BSE_UNLIKELY (Bse::_cached_bse_debug)) Bse::bse_debug (key, RAPICORN_PRETTY_FILE, __LINE__, __VA_ARGS__); } while (0)
extern bool volatile _cached_bse_debug;
void        bse_debug         (const char*, const char*, int, const char*, ...) RAPICORN_PRINTF (4, 5);
bool       _bse_debug_enabled (const char *key);
inline bool bse_debug_enabled (const char *key = NULL) { return BSE_UNLIKELY (_cached_bse_debug) && _bse_debug_enabled (key); }
bool        bse_flipper_check (const char *key);

} // Bse

/* sfiwrapper.h is a thin C language wrapper around C++ features
 * provided by libbirnet.
 */
/* --- short integer types --- */
#ifdef __cplusplus
#include <birnet/birnetutils.hh>
using Birnet::uint8;
using Birnet::uint16;
using Birnet::uint32;
using Birnet::uint64;
using Birnet::int8;
using Birnet::int16;
using Birnet::int32;
using Birnet::int64;
using Birnet::unichar;
#else
typedef BirnetUInt8   uint8;
typedef BirnetUInt16  uint16;
typedef BirnetUInt32  uint32;
typedef BirnetUInt64  uint64;
typedef BirnetInt8    int8;
typedef BirnetInt16   int16;
typedef BirnetInt32   int32;
typedef BirnetInt64   int64;
typedef BirnetUnichar unichar;
#endif
BIRNET_EXTERN_C_BEGIN();
/* --- initialization --- */
typedef struct
{
  const char *value_name;       /* value list ends with value_name == NULL */
  const char *value_string;
  long double value_num;        /* valid if value_string == NULL */
} SfiInitValue;
void sfi_init (int *argcp, char **argv, const char *app_name, const Bse::StringVector &args = Bse::StringVector());

/* --- file tests --- */
bool	birnet_file_check (const char *file,
			   const char *mode);
bool	birnet_file_equals (const char *file1,
			    const char *file2);
/* --- messaging --- */
#define         sfi_error(...)                   RAPICORN_FATAL (__VA_ARGS__)
#define         sfi_warning(...)                 RAPICORN_CRITICAL (__VA_ARGS__)
#define         sfi_info(...)                    BSE_DEBUG (__VA_ARGS__)
#define         sfi_diag(...)                    BSE_DEBUG (__VA_ARGS__)
#define         sfi_debug(lvl, ...)              BSE_DEBUG (__VA_ARGS__)
#define         sfi_nodebug(lvl, ...)            do { /* nothing */ } while (0)

/* --- url handling --- */
void sfi_url_show                   	(const char           *url);
void sfi_url_show_with_cookie       	(const char           *url,
					 const char           *url_title,
					 const char           *cookie);
bool sfi_url_test_show              	(const char           *url);
bool sfi_url_test_show_with_cookie	(const char           *url,
					 const char           *url_title,
					 const char           *cookie);

BIRNET_EXTERN_C_END();
#endif /* __SFI_WRAPPER_H__ */
/* vim:set ts=8 sts=2 sw=2: */
<commit_msg>SFI: remove useless birnet macros<commit_after>// Licensed GNU LGPL v2.1 or later: http://www.gnu.org/licenses/lgpl.html
#ifndef __SFI_WRAPPER_H__
#define __SFI_WRAPPER_H__
#include <stdbool.h>
#include <sfi/glib-extra.hh>
#include <birnet/birnetcdefs.h> /* include glib before birnet for G_LOG_DOMAIN */
#include <birnet/birnetutils.hh>

namespace Bse {

// == Likelyness Hinting ==
#define BSE_ISLIKELY(expr)      RAPICORN_ISLIKELY(expr) ///< Compiler hint that @a expr is likely to be true.
#define BSE_UNLIKELY(expr)      RAPICORN_UNLIKELY(expr) ///< Compiler hint that @a expr is unlikely to be true.
#define BSE_LIKELY              BSE_ISLIKELY            ///< Compiler hint that @a expr is likely to be true.

// == Debugging ==
/// Issue a general purpose debugging message, configurable via #$BSE_DEBUG.
#define BSE_DEBUG(...)          do { if (BSE_UNLIKELY (Bse::_cached_bse_debug)) Bse::bse_debug (NULL, RAPICORN_PRETTY_FILE, __LINE__, __VA_ARGS__); } while (0)
/// Issue a debugging message if debugging for @a key is enabled via #$BSE_DEBUG.
#define BSE_KEY_DEBUG(key,...)  do { if (BSE_UNLIKELY (Bse::_cached_bse_debug)) Bse::bse_debug (key, RAPICORN_PRETTY_FILE, __LINE__, __VA_ARGS__); } while (0)
extern bool volatile _cached_bse_debug;
void        bse_debug         (const char*, const char*, int, const char*, ...) RAPICORN_PRINTF (4, 5);
bool       _bse_debug_enabled (const char *key);
inline bool bse_debug_enabled (const char *key = NULL) { return BSE_UNLIKELY (_cached_bse_debug) && _bse_debug_enabled (key); }
bool        bse_flipper_check (const char *key);

} // Bse

/* sfiwrapper.h is a thin C language wrapper around C++ features
 * provided by libbirnet.
 */
/* --- short integer types --- */
#ifdef __cplusplus
#include <birnet/birnetutils.hh>
using Birnet::uint8;
using Birnet::uint16;
using Birnet::uint32;
using Birnet::uint64;
using Birnet::int8;
using Birnet::int16;
using Birnet::int32;
using Birnet::int64;
using Birnet::unichar;
#else
typedef BirnetUInt8   uint8;
typedef BirnetUInt16  uint16;
typedef BirnetUInt32  uint32;
typedef BirnetUInt64  uint64;
typedef BirnetInt8    int8;
typedef BirnetInt16   int16;
typedef BirnetInt32   int32;
typedef BirnetInt64   int64;
typedef BirnetUnichar unichar;
#endif

extern "C" {

/* --- initialization --- */
typedef struct
{
  const char *value_name;       /* value list ends with value_name == NULL */
  const char *value_string;
  long double value_num;        /* valid if value_string == NULL */
} SfiInitValue;
void sfi_init (int *argcp, char **argv, const char *app_name, const Bse::StringVector &args = Bse::StringVector());

/* --- file tests --- */
bool	birnet_file_check (const char *file,
			   const char *mode);
bool	birnet_file_equals (const char *file1,
			    const char *file2);
/* --- messaging --- */
#define         sfi_error(...)                   RAPICORN_FATAL (__VA_ARGS__)
#define         sfi_warning(...)                 RAPICORN_CRITICAL (__VA_ARGS__)
#define         sfi_info(...)                    BSE_DEBUG (__VA_ARGS__)
#define         sfi_diag(...)                    BSE_DEBUG (__VA_ARGS__)
#define         sfi_debug(lvl, ...)              BSE_DEBUG (__VA_ARGS__)
#define         sfi_nodebug(lvl, ...)            do { /* nothing */ } while (0)

/* --- url handling --- */
void sfi_url_show                   	(const char           *url);
void sfi_url_show_with_cookie       	(const char           *url,
					 const char           *url_title,
					 const char           *cookie);
bool sfi_url_test_show              	(const char           *url);
bool sfi_url_test_show_with_cookie	(const char           *url,
					 const char           *url_title,
					 const char           *cookie);

} // "C"

#endif /* __SFI_WRAPPER_H__ */
/* vim:set ts=8 sts=2 sw=2: */
<|endoftext|>


<commit_before>/**
 * Copyright (c) 2015-present, Facebook, Inc.
 *
 * This source code is licensed under the MIT license found in the
 * LICENSE file in the root directory of this source tree.
 */

#include "GraphQLParser.h"

#include "AstNode.h"

#include "parser.tab.hpp"
#include "lexer.h"
#include "syntaxdefs.h"

namespace facebook {
namespace graphql {

// Given properly-configured yylex, run the parser and return the
// result.
static std::unique_ptr<ast::Node> doParse(const char **outError, yyscan_t scanner, bool enableSchema) {
  Node *outAST = NULL;
  yy::GraphQLParserImpl parser(enableSchema, &outAST, outError, scanner);
  int failure = parser.parse();
  if (failure) {
    delete outAST;
  }
  return !failure ? std::unique_ptr<ast::Node>(outAST) : nullptr;
}

static std::unique_ptr<ast::Node> parseStringImpl(const char *text, const char **error, bool enableSchema) {
  yyscan_t scanner;
  struct LexerExtra extra;
  yylex_init_extra(&extra, &scanner);
  YY_BUFFER_STATE buffer = yy_scan_string(text, scanner);
  yy_switch_to_buffer(buffer, scanner);

  auto result = doParse(error, scanner, enableSchema);
  yylex_destroy(scanner);
  return result;
}

std::unique_ptr<ast::Node> parseString(const char *text, const char **error) {
  return parseStringImpl(text, error, false);
}

std::unique_ptr<ast::Node> parseStringWithExperimentalSchemaSupport(
    const char *text, const char **error) {
  return parseStringImpl(text, error, true);
}

static std::unique_ptr<ast::Node> parseFileImpl(
    FILE *file, const char **error, bool enableSchema) {
  yyscan_t scanner;
  struct LexerExtra extra;
  yylex_init_extra(&extra, &scanner);
  yyset_in(file, scanner);

  auto result = doParse(error, scanner, enableSchema);
  yylex_destroy(scanner);

  return result;
}

std::unique_ptr<ast::Node> parseFile(FILE *file, const char **error) {
  return parseFileImpl(file, error, false);
}

std::unique_ptr<ast::Node> parseFileWithExperimentalSchemaSupport(
    FILE *file, const char **error) {
  return parseFileImpl(file, error, true);
}

}  // namespace graphql
}  // namespace facebook
<commit_msg>Trivial s/NULL/nullptr<commit_after>/**
 * Copyright (c) 2015-present, Facebook, Inc.
 *
 * This source code is licensed under the MIT license found in the
 * LICENSE file in the root directory of this source tree.
 */

#include "GraphQLParser.h"

#include "AstNode.h"

#include "parser.tab.hpp"
#include "lexer.h"
#include "syntaxdefs.h"

namespace facebook {
namespace graphql {

// Given properly-configured yylex, run the parser and return the
// result.
static std::unique_ptr<ast::Node> doParse(const char **outError, yyscan_t scanner, bool enableSchema) {
  Node *outAST = nullptr;
  yy::GraphQLParserImpl parser(enableSchema, &outAST, outError, scanner);
  int failure = parser.parse();
  if (failure) {
    delete outAST;
  }
  return !failure ? std::unique_ptr<ast::Node>(outAST) : nullptr;
}

static std::unique_ptr<ast::Node> parseStringImpl(const char *text, const char **error, bool enableSchema) {
  yyscan_t scanner;
  struct LexerExtra extra;
  yylex_init_extra(&extra, &scanner);
  YY_BUFFER_STATE buffer = yy_scan_string(text, scanner);
  yy_switch_to_buffer(buffer, scanner);

  auto result = doParse(error, scanner, enableSchema);
  yylex_destroy(scanner);
  return result;
}

std::unique_ptr<ast::Node> parseString(const char *text, const char **error) {
  return parseStringImpl(text, error, false);
}

std::unique_ptr<ast::Node> parseStringWithExperimentalSchemaSupport(
    const char *text, const char **error) {
  return parseStringImpl(text, error, true);
}

static std::unique_ptr<ast::Node> parseFileImpl(
    FILE *file, const char **error, bool enableSchema) {
  yyscan_t scanner;
  struct LexerExtra extra;
  yylex_init_extra(&extra, &scanner);
  yyset_in(file, scanner);

  auto result = doParse(error, scanner, enableSchema);
  yylex_destroy(scanner);

  return result;
}

std::unique_ptr<ast::Node> parseFile(FILE *file, const char **error) {
  return parseFileImpl(file, error, false);
}

std::unique_ptr<ast::Node> parseFileWithExperimentalSchemaSupport(
    FILE *file, const char **error) {
  return parseFileImpl(file, error, true);
}

}  // namespace graphql
}  // namespace facebook
<|endoftext|>