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

#include <string.h>
#include <sys/stat.h>
#include <sys/types.h>
#if defined(_MSC_VER)
#include <io.h>
#define access _access
#define F_OK 0
#else
#include <unistd.h>
#endif

#include <string>

#include "base/file.h"
#include "base/logging.h"
#include "base/scoped_ptr.h"

namespace operations_research {

File::File(FILE* const f_des, const std::string& name)
  : f_(f_des), name_(name) {}

bool File::Delete(char* const name) {
  return remove(name) == 0;
}

bool File::Exists(char* const name) {
  return access(name, F_OK) == 0;
}

size_t File::Size() {
  struct stat f_stat;
  stat(name_.c_str(), &f_stat);
  return f_stat.st_size;
}

bool File::Flush() {
  return fflush(f_) == 0;
}

bool File::Close() {
  if (fclose(f_) == 0) {
    f_ = NULL;
    return true;
  } else {
    return false;
  }
}

void File::ReadOrDie(void* const buf, size_t size) {
  CHECK_EQ(fread(buf, 1, size, f_), size);
}

size_t File::Read(void* const buf, size_t size) {
  return fread(buf, 1, size, f_);
}

void File::WriteOrDie(const void* const buf, size_t size) {
  CHECK_EQ(fwrite(buf, 1, size, f_), size);
}
size_t File::Write(const void* const buf, size_t size) {
  return fwrite(buf, 1, size, f_);
}

File* File::OpenOrDie(const char* const name, const char* const flag) {
  FILE* const f_des = fopen(name, flag);
  if (f_des == NULL) {
    std::cerr << "Cannot open " << name;
    exit(1);
  }
  File* const f = new File(f_des, name);
  return f;
}

File* File::Open(const char* const name, const char* const flag) {
  FILE* const f_des = fopen(name, flag);
  if (f_des == NULL) return NULL;
  File* const f = new File(f_des, name);
  return f;
}

char* File::ReadLine(char* const output, uint64 max_length) {
  char* const result = fgets(output, max_length, f_);
  if (result == NULL) {
    return NULL;
  }
  // Chop the last linefeed if there.
  int len = strlen(result);
  if (len > 0 && result[len - 1] == 10) {  // Linefeed char.
      result[--len] = '\0';
    }
  if (len > 0 && result[len - 1] == 13) {  // Carriage return.
    result[--len] = '\0';
  }
}

int64 File::ReadToString(std::string* const output, uint64 max_length) {
  CHECK_NOTNULL(output);
  output->clear();

  if (max_length == 0) return 0;
  if (max_length < 0) return -1;

  int64 needed = max_length;
  int bufsize = (needed < (2 << 20) ? needed : (2 << 20));

  scoped_array<char> buf(new char[bufsize]);

  int64 nread = 0;
  while (needed > 0) {
    nread = Read(buf.get(), (bufsize < needed ? bufsize : needed));
    if (nread > 0) {
      output->append(buf.get(), nread);
      needed -= nread;
    } else {
      break;
    }
  }
  return (nread >= 0 ? static_cast<int64>(output->size()) : -1);
}

size_t File::WriteString(const std::string& line) {
  return Write(line.c_str(), line.size());
}

bool File::WriteLine(const std::string& line) {
  if (Write(line.c_str(), line.size()) != line.size()) return false;
  return Write("\n", 1) == 1;
}

std::string File::CreateFileName() const {
  return name_;
}

bool File::Open() const {
  return f_ != NULL;
}

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

#include <string.h>
#include <sys/stat.h>
#include <sys/types.h>
#if defined(_MSC_VER)
#include <io.h>
#define access _access
#define F_OK 0
#else
#include <unistd.h>
#endif

#include <string>

#include "base/file.h"
#include "base/logging.h"
#include "base/scoped_ptr.h"

namespace operations_research {

File::File(FILE* const f_des, const std::string& name)
  : f_(f_des), name_(name) {}

bool File::Delete(char* const name) {
  return remove(name) == 0;
}

bool File::Exists(char* const name) {
  return access(name, F_OK) == 0;
}

size_t File::Size() {
  struct stat f_stat;
  stat(name_.c_str(), &f_stat);
  return f_stat.st_size;
}

bool File::Flush() {
  return fflush(f_) == 0;
}

bool File::Close() {
  if (fclose(f_) == 0) {
    f_ = NULL;
    return true;
  } else {
    return false;
  }
}

void File::ReadOrDie(void* const buf, size_t size) {
  CHECK_EQ(fread(buf, 1, size, f_), size);
}

size_t File::Read(void* const buf, size_t size) {
  return fread(buf, 1, size, f_);
}

void File::WriteOrDie(const void* const buf, size_t size) {
  CHECK_EQ(fwrite(buf, 1, size, f_), size);
}
size_t File::Write(const void* const buf, size_t size) {
  return fwrite(buf, 1, size, f_);
}

File* File::OpenOrDie(const char* const name, const char* const flag) {
  FILE* const f_des = fopen(name, flag);
  if (f_des == NULL) {
    std::cerr << "Cannot open " << name;
    exit(1);
  }
  File* const f = new File(f_des, name);
  return f;
}

File* File::Open(const char* const name, const char* const flag) {
  FILE* const f_des = fopen(name, flag);
  if (f_des == NULL) return NULL;
  File* const f = new File(f_des, name);
  return f;
}

char* File::ReadLine(char* const output, uint64 max_length) {
  char* const result = fgets(output, max_length, f_);
  if (result == NULL) {
    return NULL;
  }
  // Chop the last linefeed if there.
  int len = strlen(result);
  if (len > 0 && result[len - 1] == 10) {  // Linefeed char.
      result[--len] = '\0';
    }
  if (len > 0 && result[len - 1] == 13) {  // Carriage return.
    result[--len] = '\0';
  }
  return result;
}

int64 File::ReadToString(std::string* const output, uint64 max_length) {
  CHECK_NOTNULL(output);
  output->clear();

  if (max_length == 0) return 0;
  if (max_length < 0) return -1;

  int64 needed = max_length;
  int bufsize = (needed < (2 << 20) ? needed : (2 << 20));

  scoped_array<char> buf(new char[bufsize]);

  int64 nread = 0;
  while (needed > 0) {
    nread = Read(buf.get(), (bufsize < needed ? bufsize : needed));
    if (nread > 0) {
      output->append(buf.get(), nread);
      needed -= nread;
    } else {
      break;
    }
  }
  return (nread >= 0 ? static_cast<int64>(output->size()) : -1);
}

size_t File::WriteString(const std::string& line) {
  return Write(line.c_str(), line.size());
}

bool File::WriteLine(const std::string& line) {
  if (Write(line.c_str(), line.size()) != line.size()) return false;
  return Write("\n", 1) == 1;
}

std::string File::CreateFileName() const {
  return name_;
}

bool File::Open() const {
  return f_ != NULL;
}

void File::Init() {}
}  // namespace operations_research
<|endoftext|>


<commit_before>#include "Layer.h"
#include "ShapesUD.h"
#include "BaseFileUD.h"

#include "view/LibraryPanel.h"

#include <easyshape.h>

namespace lr
{

Layer::Layer(int id, LibraryPanel* library)
	: m_id(id)
	, m_library(library)
	, m_editable(true)
	, m_visible(true)
	, m_next_id(0)
{
}

void Layer::TraverseSprite(d2d::IVisitor& visitor, bool order/* = true*/) const
{
	m_sprites.Traverse(visitor, order);
}

void Layer::TraverseSprite(d2d::IVisitor& visitor, d2d::DataTraverseType type, bool order) const
{
	m_sprites.Traverse(visitor, type, order);
}

bool Layer::RemoveSprite(Object* obj)
{
	d2d::ISprite* spr = static_cast<d2d::ISprite*>(obj);
	m_name_set.erase(spr->name);
	return m_sprites.Remove(spr);
}

bool Layer::InsertSprite(Object* obj, int idx)
{
	d2d::ISprite* spr = static_cast<d2d::ISprite*>(obj);
	CheckSpriteName(spr);
	return m_sprites.Insert(spr, idx);
}

bool Layer::ClearSprite()
{
	m_next_id = 0;
	m_name_set.clear();

	return m_sprites.Clear();
}

bool Layer::ResetOrderSprite(const Object* obj, bool up)
{
	return m_sprites.ResetOrder(static_cast<const d2d::ISprite*>(obj), up);
}

void Layer::TraverseShape(d2d::IVisitor& visitor, bool order) const
{
	m_shapes.Traverse(visitor, order);
}

bool Layer::RemoveShape(Object* obj)
{
	return m_shapes.Remove(static_cast<d2d::IShape*>(obj));
}

bool Layer::InsertShape(Object* obj)
{
	return m_shapes.Insert(static_cast<d2d::IShape*>(obj));
}

bool Layer::ClearShape()
{
	return m_shapes.Clear();
}

void Layer::LoadFromFile(const Json::Value& val, const std::string& dir, int layer_idx)
{
	m_name = val["name"].asString();
	m_editable = val["editable"].asBool();
	m_visible = val["visible"].asBool();

	if (!val["base filepath"].isNull()) {
		m_base_filepath = val["base filepath"].asString();
		LoadFromBaseFile(layer_idx, m_base_filepath, dir);
	}

	LoadSprites(val["sprite"], dir);
	LoadShapes(val["shape"], dir);
}

void Layer::StoreToFile(Json::Value& val, const std::string& dir) const
{
	val["name"] = m_name;
	val["visible"] = m_visible;
	val["editable"] = m_editable;
	if (!m_base_filepath.empty()) {
		val["base filepath"] = m_base_filepath;
	}

	std::vector<d2d::ISprite*> sprites;
	m_sprites.Traverse(d2d::FetchAllVisitor<d2d::ISprite>(sprites), d2d::DT_ALL);
	int count = 0;
	for (int i = 0, n = sprites.size(); i < n; ++i)
	{
		d2d::ISprite* spr = sprites[i];
		if (spr->GetUserData()) {
			UserData* ud = static_cast<UserData*>(spr->GetUserData());
			if (ud->type == UT_BASE_FILE) {
				return;
			}
		}

		if (!IsValidFloat(spr->GetPosition().x) ||
			!IsValidFloat(spr->GetPosition().y)) {
			continue;
		}

		Json::Value spr_val;
		spr_val["filepath"] = d2d::FilenameTools::getRelativePath(dir,
			spr->GetSymbol().GetFilepath()).ToStdString();
		spr->Store(spr_val);
		StoreShapesUD(spr, spr_val);

		val["sprite"][count++] = spr_val;
	}

	std::vector<d2d::IShape*> shapes;
	m_shapes.Traverse(d2d::FetchAllVisitor<d2d::IShape>(shapes), true);
	count = 0;
	for (int i = 0, n = shapes.size(); i < n; ++i) {
		d2d::IShape* shape = shapes[i];
		if (shape->GetUserData()) {
			UserData* ud = static_cast<UserData*>(shape->GetUserData());
			if (ud->type == UT_BASE_FILE) {
				return;
			}
		}
		shape->StoreToFile(val["shape"][count++], dir);
	}
}

bool Layer::Update(int version)
{
	bool ret = false;

	std::vector<d2d::ISprite*> sprites;
	TraverseSprite(d2d::FetchAllVisitor<d2d::ISprite>(sprites), true);
	for (int i = 0, n = sprites.size(); i < n; ++i) {
		bool dirty = sprites[i]->Update(version);
		if (dirty) {
			ret = true;
		}
	}

	if (!m_visible) {
		ret = false;
	}
	return ret;
}

d2d::ISprite* Layer::QuerySprite(const std::string& name) const
{
	QueryNameVisitor<d2d::ISprite> visitor(name);
	m_sprites.Traverse(visitor, true);
	return visitor.GetResult();
}

d2d::IShape* Layer::QueryShape(const std::string& name) const
{
	QueryNameVisitor<d2d::IShape> visitor(name);
	m_shapes.Traverse(visitor, true);
	return visitor.GetResult();
}

bool Layer::IsValidFloat(float f)
{
	return (f == f) && (f <= FLT_MAX && f >= -FLT_MAX);
}

void Layer::LoadSprites(const Json::Value& val, const std::string& dir,
						const std::string& base_path)
{
	int idx = 0;
	Json::Value spr_val = val[idx++];
	while (!spr_val.isNull())
	{
		std::string filepath = d2d::SymbolSearcher::GetSymbolPath(dir, spr_val);
		if (filepath.empty()) {
			std::string filepath = spr_val["filepath"].asString();
			throw d2d::Exception("filepath err: %s", filepath.c_str());
		}
		d2d::ISymbol* symbol = NULL;

		std::string shape_tag = d2d::FileNameParser::getFileTag(d2d::FileNameParser::e_shape);
		std::string shape_filepath = d2d::FilenameTools::getFilenameAddTag(filepath, shape_tag, "json");
		if (d2d::FilenameTools::IsFileExist(shape_filepath)) {
			symbol = d2d::SymbolMgr::Instance()->FetchSymbol(shape_filepath);
		} else {
			symbol = d2d::SymbolMgr::Instance()->FetchSymbol(filepath);
		}

		if (!symbol) {
			throw d2d::Exception("create symbol err: %s", filepath.c_str());
		}

		d2d::ISprite* sprite = d2d::SpriteFactory::Instance()->create(symbol);
		sprite->Load(spr_val);
		if (!base_path.empty()) {
			BaseFileUD* ud = new BaseFileUD(base_path);
			sprite->SetUserData(ud);
			sprite->editable = false;
		}
		CheckSpriteName(sprite);
		m_sprites.Insert(sprite);

		LoadShapesUD(spr_val, sprite);

		sprite->Release();
		symbol->Release();

		spr_val = val[idx++];
	}
}

void Layer::LoadShapes(const Json::Value& val, const std::string& dir,
					   const std::string& base_path)
{
	int idx = 0;
	Json::Value shape_val = val[idx++];
	while (!shape_val.isNull())
	{
		d2d::IShape* shape = libshape::ShapeFactory::CreateShapeFromFile(shape_val, dir);
		if (!base_path.empty()) {
			BaseFileUD* ud = new BaseFileUD(base_path);
			shape->SetUserData(ud);
		}
		m_shapes.Insert(shape);
		shape->Release();
		shape_val = val[idx++];
	}
}

void Layer::LoadFromBaseFile(int layer_idx, const std::string& filepath, const std::string& dir)
{
	std::string filepath_full = dir + "\\" + filepath;

	Json::Value value;
	Json::Reader reader;
	std::locale::global(std::locale(""));
	std::ifstream fin(filepath_full.c_str());
	std::locale::global(std::locale("C"));
	reader.parse(fin, value);
	fin.close();

	const Json::Value& layer_val = value["layer"][layer_idx];
	if (!layer_val["base filepath"].isNull()) {
		std::string base_path = layer_val["base filepath"].asString();
		LoadFromBaseFile(layer_idx, base_path, dir);
	}

	LoadSprites(layer_val["sprite"], dir, filepath);
	LoadShapes(layer_val["shape"], dir, filepath);
}

void Layer::CheckSpriteName(d2d::ISprite* spr)
{
	std::set<std::string>::iterator itr
		= m_name_set.find(spr->name);
	if (itr != m_name_set.end())
	{
		spr->name = "_sprite"+wxString::FromDouble(++m_next_id);
		assert(m_name_set.find(spr->name) == m_name_set.end());
	}
	else
	{
		int pos = spr->name.find("_sprite");
		if (pos != std::string::npos) {
			std::string str = spr->name.substr(pos + 7);
			int num = atoi(str.c_str());
			if (m_next_id < num) {
				m_next_id = num;
			}
		}
	}
	m_name_set.insert(spr->name);
}

void Layer::LoadShapesUD(const Json::Value& spr_val, d2d::ISprite* spr) const
{
	if (spr_val["ud"].isNull()) {
		return;
	}

	ShapesUD* ud = new ShapesUD;

	const Json::Value& ud_val = spr_val["ud"];
	ud->layer_id = ud_val["layer"].asInt();
	int idx = 0;
	Json::Value shape_val = ud_val["shape"][idx++];
	while (!shape_val.isNull()) {
		ud->shape_names.push_back(shape_val.asString());
		shape_val = ud_val["shape"][idx++];
	}

	spr->SetUserData(ud);
}

void Layer::StoreShapesUD(d2d::ISprite* spr, Json::Value& spr_val) const
{
	if (!spr->GetUserData()) {
		return;
	}

	UserData* ud = static_cast<UserData*>(spr->GetUserData());
	if (ud->type == UT_BASE_FILE) {
		return;
	}

	Json::Value val;
	ShapesUD* sud = static_cast<ShapesUD*>(ud);
	val["layer"] = sud->layer_id;
	for (int i = 0, n = sud->shape_names.size(); i < n; ++i) {
		val["shape"][i] = sud->shape_names[i];
	}

	spr_val["ud"] = val;
}

//////////////////////////////////////////////////////////////////////////
// class Layer::QueryNameVisitor
//////////////////////////////////////////////////////////////////////////

template<typename T>
Layer::QueryNameVisitor<T>::
QueryNameVisitor(const std::string& name)
	: m_name(name)
	, m_result(NULL)
{
}

template<typename T>
void Layer::QueryNameVisitor<T>::
Visit(Object* object, bool& bFetchNext)
{
	T* t = static_cast<T*>(object);
	if (t->name == m_name) {
		m_result = t;
		bFetchNext = false;
	} else {
		bFetchNext = true;
	}
}

}<commit_msg>[FIXED] spr tag copy from shape<commit_after>#include "Layer.h"
#include "ShapesUD.h"
#include "BaseFileUD.h"

#include "view/LibraryPanel.h"

#include <easyshape.h>

namespace lr
{

Layer::Layer(int id, LibraryPanel* library)
	: m_id(id)
	, m_library(library)
	, m_editable(true)
	, m_visible(true)
	, m_next_id(0)
{
}

void Layer::TraverseSprite(d2d::IVisitor& visitor, bool order/* = true*/) const
{
	m_sprites.Traverse(visitor, order);
}

void Layer::TraverseSprite(d2d::IVisitor& visitor, d2d::DataTraverseType type, bool order) const
{
	m_sprites.Traverse(visitor, type, order);
}

bool Layer::RemoveSprite(Object* obj)
{
	d2d::ISprite* spr = static_cast<d2d::ISprite*>(obj);
	m_name_set.erase(spr->name);
	return m_sprites.Remove(spr);
}

bool Layer::InsertSprite(Object* obj, int idx)
{
	d2d::ISprite* spr = static_cast<d2d::ISprite*>(obj);
	CheckSpriteName(spr);
	return m_sprites.Insert(spr, idx);
}

bool Layer::ClearSprite()
{
	m_next_id = 0;
	m_name_set.clear();

	return m_sprites.Clear();
}

bool Layer::ResetOrderSprite(const Object* obj, bool up)
{
	return m_sprites.ResetOrder(static_cast<const d2d::ISprite*>(obj), up);
}

void Layer::TraverseShape(d2d::IVisitor& visitor, bool order) const
{
	m_shapes.Traverse(visitor, order);
}

bool Layer::RemoveShape(Object* obj)
{
	return m_shapes.Remove(static_cast<d2d::IShape*>(obj));
}

bool Layer::InsertShape(Object* obj)
{
	return m_shapes.Insert(static_cast<d2d::IShape*>(obj));
}

bool Layer::ClearShape()
{
	return m_shapes.Clear();
}

void Layer::LoadFromFile(const Json::Value& val, const std::string& dir, int layer_idx)
{
	m_name = val["name"].asString();
	m_editable = val["editable"].asBool();
	m_visible = val["visible"].asBool();

	if (!val["base filepath"].isNull()) {
		m_base_filepath = val["base filepath"].asString();
		LoadFromBaseFile(layer_idx, m_base_filepath, dir);
	}

	LoadSprites(val["sprite"], dir);
	LoadShapes(val["shape"], dir);
}

void Layer::StoreToFile(Json::Value& val, const std::string& dir) const
{
	val["name"] = m_name;
	val["visible"] = m_visible;
	val["editable"] = m_editable;
	if (!m_base_filepath.empty()) {
		val["base filepath"] = m_base_filepath;
	}

	std::vector<d2d::ISprite*> sprites;
	m_sprites.Traverse(d2d::FetchAllVisitor<d2d::ISprite>(sprites), d2d::DT_ALL);
	int count = 0;
	for (int i = 0, n = sprites.size(); i < n; ++i)
	{
		d2d::ISprite* spr = sprites[i];
		if (spr->GetUserData()) {
			UserData* ud = static_cast<UserData*>(spr->GetUserData());
			if (ud->type == UT_BASE_FILE) {
				return;
			}
		}

		if (!IsValidFloat(spr->GetPosition().x) ||
			!IsValidFloat(spr->GetPosition().y)) {
			continue;
		}

		Json::Value spr_val;
		spr_val["filepath"] = d2d::FilenameTools::getRelativePath(dir,
			spr->GetSymbol().GetFilepath()).ToStdString();
		spr->Store(spr_val);
		StoreShapesUD(spr, spr_val);

		val["sprite"][count++] = spr_val;
	}

	std::vector<d2d::IShape*> shapes;
	m_shapes.Traverse(d2d::FetchAllVisitor<d2d::IShape>(shapes), true);
	count = 0;
	for (int i = 0, n = shapes.size(); i < n; ++i) {
		d2d::IShape* shape = shapes[i];
		if (shape->GetUserData()) {
			UserData* ud = static_cast<UserData*>(shape->GetUserData());
			if (ud->type == UT_BASE_FILE) {
				return;
			}
		}
		shape->StoreToFile(val["shape"][count++], dir);
	}
}

bool Layer::Update(int version)
{
	bool ret = false;

	std::vector<d2d::ISprite*> sprites;
	TraverseSprite(d2d::FetchAllVisitor<d2d::ISprite>(sprites), true);
	for (int i = 0, n = sprites.size(); i < n; ++i) {
		bool dirty = sprites[i]->Update(version);
		if (dirty) {
			ret = true;
		}
	}

	if (!m_visible) {
		ret = false;
	}
	return ret;
}

d2d::ISprite* Layer::QuerySprite(const std::string& name) const
{
	QueryNameVisitor<d2d::ISprite> visitor(name);
	m_sprites.Traverse(visitor, true);
	return visitor.GetResult();
}

d2d::IShape* Layer::QueryShape(const std::string& name) const
{
	QueryNameVisitor<d2d::IShape> visitor(name);
	m_shapes.Traverse(visitor, true);
	return visitor.GetResult();
}

bool Layer::IsValidFloat(float f)
{
	return (f == f) && (f <= FLT_MAX && f >= -FLT_MAX);
}

void Layer::LoadSprites(const Json::Value& val, const std::string& dir,
						const std::string& base_path)
{
	int idx = 0;
	Json::Value spr_val = val[idx++];
	while (!spr_val.isNull())
	{
		std::string filepath = d2d::SymbolSearcher::GetSymbolPath(dir, spr_val);
		if (filepath.empty()) {
			std::string filepath = spr_val["filepath"].asString();
			throw d2d::Exception("filepath err: %s", filepath.c_str());
		}
		d2d::ISymbol* symbol = NULL;

		std::string shape_tag = d2d::FileNameParser::getFileTag(d2d::FileNameParser::e_shape);
		std::string shape_filepath = d2d::FilenameTools::getFilenameAddTag(filepath, shape_tag, "json");
		std::string spr_tag;
		if (d2d::FilenameTools::IsFileExist(shape_filepath)) {
			symbol = d2d::SymbolMgr::Instance()->FetchSymbol(shape_filepath);
			const std::vector<d2d::IShape*>& shapes = static_cast<libshape::Symbol*>(symbol)->GetShapes();
			if (!shapes.empty()) {
				spr_tag = shapes[0]->name;
			}
		} else {
			symbol = d2d::SymbolMgr::Instance()->FetchSymbol(filepath);
		}

		if (!symbol) {
			throw d2d::Exception("create symbol err: %s", filepath.c_str());
		}

		d2d::ISprite* sprite = d2d::SpriteFactory::Instance()->create(symbol);
		sprite->Load(spr_val);

		if (!sprite->tag.empty() && sprite->tag[sprite->tag.size()-1] != ';') {
			sprite->tag += ";";
		}
		sprite->tag += spr_tag;

		if (!base_path.empty()) {
			BaseFileUD* ud = new BaseFileUD(base_path);
			sprite->SetUserData(ud);
			sprite->editable = false;
		}
		CheckSpriteName(sprite);
		m_sprites.Insert(sprite);

		LoadShapesUD(spr_val, sprite);

		sprite->Release();
		symbol->Release();

		spr_val = val[idx++];
	}
}

void Layer::LoadShapes(const Json::Value& val, const std::string& dir,
					   const std::string& base_path)
{
	int idx = 0;
	Json::Value shape_val = val[idx++];
	while (!shape_val.isNull())
	{
		d2d::IShape* shape = libshape::ShapeFactory::CreateShapeFromFile(shape_val, dir);
		if (!base_path.empty()) {
			BaseFileUD* ud = new BaseFileUD(base_path);
			shape->SetUserData(ud);
		}
		m_shapes.Insert(shape);
		shape->Release();
		shape_val = val[idx++];
	}
}

void Layer::LoadFromBaseFile(int layer_idx, const std::string& filepath, const std::string& dir)
{
	std::string filepath_full = dir + "\\" + filepath;

	Json::Value value;
	Json::Reader reader;
	std::locale::global(std::locale(""));
	std::ifstream fin(filepath_full.c_str());
	std::locale::global(std::locale("C"));
	reader.parse(fin, value);
	fin.close();

	const Json::Value& layer_val = value["layer"][layer_idx];
	if (!layer_val["base filepath"].isNull()) {
		std::string base_path = layer_val["base filepath"].asString();
		LoadFromBaseFile(layer_idx, base_path, dir);
	}

	LoadSprites(layer_val["sprite"], dir, filepath);
	LoadShapes(layer_val["shape"], dir, filepath);
}

void Layer::CheckSpriteName(d2d::ISprite* spr)
{
	std::set<std::string>::iterator itr
		= m_name_set.find(spr->name);
	if (itr != m_name_set.end())
	{
		spr->name = "_sprite"+wxString::FromDouble(++m_next_id);
		assert(m_name_set.find(spr->name) == m_name_set.end());
	}
	else
	{
		int pos = spr->name.find("_sprite");
		if (pos != std::string::npos) {
			std::string str = spr->name.substr(pos + 7);
			int num = atoi(str.c_str());
			if (m_next_id < num) {
				m_next_id = num;
			}
		}
	}
	m_name_set.insert(spr->name);
}

void Layer::LoadShapesUD(const Json::Value& spr_val, d2d::ISprite* spr) const
{
	if (spr_val["ud"].isNull()) {
		return;
	}

	ShapesUD* ud = new ShapesUD;

	const Json::Value& ud_val = spr_val["ud"];
	ud->layer_id = ud_val["layer"].asInt();
	int idx = 0;
	Json::Value shape_val = ud_val["shape"][idx++];
	while (!shape_val.isNull()) {
		ud->shape_names.push_back(shape_val.asString());
		shape_val = ud_val["shape"][idx++];
	}

	spr->SetUserData(ud);
}

void Layer::StoreShapesUD(d2d::ISprite* spr, Json::Value& spr_val) const
{
	if (!spr->GetUserData()) {
		return;
	}

	UserData* ud = static_cast<UserData*>(spr->GetUserData());
	if (ud->type == UT_BASE_FILE) {
		return;
	}

	Json::Value val;
	ShapesUD* sud = static_cast<ShapesUD*>(ud);
	val["layer"] = sud->layer_id;
	for (int i = 0, n = sud->shape_names.size(); i < n; ++i) {
		val["shape"][i] = sud->shape_names[i];
	}

	spr_val["ud"] = val;
}

//////////////////////////////////////////////////////////////////////////
// class Layer::QueryNameVisitor
//////////////////////////////////////////////////////////////////////////

template<typename T>
Layer::QueryNameVisitor<T>::
QueryNameVisitor(const std::string& name)
	: m_name(name)
	, m_result(NULL)
{
}

template<typename T>
void Layer::QueryNameVisitor<T>::
Visit(Object* object, bool& bFetchNext)
{
	T* t = static_cast<T*>(object);
	if (t->name == m_name) {
		m_result = t;
		bFetchNext = false;
	} else {
		bFetchNext = true;
	}
}

}<|endoftext|>


<commit_before>#include <iostream>
#include "../parser.hpp"

using std::cin;
using std::cout;
using std::endl;

int main(int argc, char ** argv) {
  doorman::init();
  doorman::parser_t parser;

  unsigned int bit;

  while (!cin.eof()) {
    cin >> bit;

    if (parser.consume(bit)) {
      cout << "Expected bit " << bit << endl;
      if (parser.is_ready()) {
        cout << "Parser ready!" << endl;
        cout << parser.bits[0] << parser.bits[1] << parser.bits[2] << parser.bits[2] <<
            parser.bits[4] << parser.bits[5] << parser.bits[6] << parser.bits[7] << parser.bits[8] << parser.bits[9] << parser.bits[10] << parser.bits[11] << endl;
        parser.reset();
      }
    } else {
      cout << "Unexpected bit " << bit << endl;
      parser.reset();
    }
  }

  return 0;
}
<commit_msg>improved test binary<commit_after>#include <iostream>
#include "../parser.hpp"

using std::cin;
using std::cout;
using std::endl;

#define print_parser \
  for (int __i = 0; __i < parser.length; __i++) {\
    cout << parser.bits[__i];\
  }\
  cout << endl;

int main(int argc, char ** argv) {
  doorman::init();
  doorman::parser_t parser;

  unsigned int bit;

  while (!cin.eof()) {
    cin >> bit;

    if (parser.consume(bit)) {
      cout << "Expected bit " << bit << endl;
      if (parser.is_ready()) {
        cout << "Parser ready!" << endl;
        print_parser
        parser.reset();
      } else {
        print_parser
      }
    } else {
      cout << "Unexpected bit " << bit << endl;
      parser.reset();
    }
  }

  return 0;
}
<|endoftext|>


<commit_before>#include "ModernGL.hpp"

#include "OpenGL.hpp"

PyObject * NewFramebuffer(PyObject * self, PyObject * args, PyObject * kwargs) {
	int width = 0;
	int height = 0;

	static const char * kwlist[] = {"width", "height", 0};

	if (!PyArg_ParseTupleAndKeywords(args, kwargs, "|ii:NewFramebuffer", (char **)kwlist, &width, &height)) {
		return 0;
	}

	int framebuffer = 0;
	int color = 0;
	int depth = 0;

	OpenGL::glGenFramebuffers(1, (OpenGL::GLuint *)&framebuffer);
	OpenGL::glBindFramebuffer(OpenGL::GL_FRAMEBUFFER, framebuffer);

	if (!width && !height) {
		width = activeViewportWidth;
		height = activeViewportHeight;
	}

	OpenGL::glGenTextures(1, (OpenGL::GLuint *)&color);
	OpenGL::glBindTexture(OpenGL::GL_TEXTURE_2D, color);

	OpenGL::glTexParameteri(OpenGL::GL_TEXTURE_2D, OpenGL::GL_TEXTURE_MIN_FILTER, OpenGL::GL_LINEAR);
	OpenGL::glTexParameteri(OpenGL::GL_TEXTURE_2D, OpenGL::GL_TEXTURE_MAG_FILTER, OpenGL::GL_LINEAR);
	OpenGL::glTexImage2D(OpenGL::GL_TEXTURE_2D, 0, OpenGL::GL_RGBA, width, height, 0, OpenGL::GL_RGBA, OpenGL::GL_FLOAT, 0);
	OpenGL::glFramebufferTexture2D(OpenGL::GL_FRAMEBUFFER, OpenGL::GL_COLOR_ATTACHMENT0, OpenGL::GL_TEXTURE_2D, color, 0);

	OpenGL::glGenTextures(1, (OpenGL::GLuint *)&depth);
	OpenGL::glBindTexture(OpenGL::GL_TEXTURE_2D, depth);
	OpenGL::glTexParameteri(OpenGL::GL_TEXTURE_2D, OpenGL::GL_TEXTURE_MIN_FILTER, OpenGL::GL_LINEAR);
	OpenGL::glTexParameteri(OpenGL::GL_TEXTURE_2D, OpenGL::GL_TEXTURE_MAG_FILTER, OpenGL::GL_LINEAR);
	OpenGL::glTexImage2D(OpenGL::GL_TEXTURE_2D, 0, OpenGL::GL_DEPTH_COMPONENT, width, height, 0, OpenGL::GL_DEPTH_COMPONENT, OpenGL::GL_FLOAT, 0);
	OpenGL::glFramebufferTexture2D(OpenGL::GL_FRAMEBUFFER, OpenGL::GL_DEPTH_ATTACHMENT, OpenGL::GL_TEXTURE_2D, depth, 0);

	OpenGL::glBindFramebuffer(OpenGL::GL_FRAMEBUFFER, defaultFramebuffer);

	PyObject * fbo = CreateFramebufferType(framebuffer, color, depth);
	PyObject * colorTexture = CreateTextureType(color, width, height, 4);
	PyObject * depthTexture = CreateTextureType(depth, width, height, 1);

	return Py_BuildValue("OOO", fbo, colorTexture, depthTexture);
}

PyObject * DeleteFramebuffer(PyObject * self, PyObject * args) {
	Framebuffer * fbo;

	if (!PyArg_ParseTuple(args, "O:DeleteFramebuffer", &fbo)) {
		return 0;
	}

	CHECK_AND_REPORT_ARG_TYPE_ERROR("fbo", fbo, FramebufferType);

	OpenGL::glDeleteFramebuffers(1, (OpenGL::GLuint *)&fbo->fbo);
	OpenGL::glDeleteTextures(1, (OpenGL::GLuint *)&fbo->color);
	OpenGL::glDeleteTextures(1, (OpenGL::GLuint *)&fbo->depth);
	Py_RETURN_NONE;
}

PyObject * UseFramebuffer(PyObject * self, PyObject * args) {
	Framebuffer * fbo;

	if (!PyArg_ParseTuple(args, "O:UseFramebuffer", &fbo)) {
		return 0;
	}

	CHECK_AND_REPORT_ARG_TYPE_ERROR("fbo", fbo, FramebufferType);

	OpenGL::glBindFramebuffer(OpenGL::GL_FRAMEBUFFER, fbo->fbo);
	activeProgram = fbo->fbo;
	Py_RETURN_NONE;
}

PyObject * GetDefaultFramebuffer(PyObject * self) {
	OpenGL::glGetIntegerv(OpenGL::GL_DRAW_FRAMEBUFFER_BINDING, (OpenGL::GLint *)&defaultFramebuffer);
	Py_RETURN_NONE;
}

PyObject * UseDefaultFramebuffer(PyObject * self) {
	OpenGL::glBindFramebuffer(OpenGL::GL_FRAMEBUFFER, defaultFramebuffer);
	Py_RETURN_NONE;
}

PyObject * ReadPixels(PyObject * self, PyObject * args, PyObject * kwargs) {
	int x;
	int y;
	int width;
	int height;
	int components = 3;

	static const char * kwlist[] = {"x", "y", "width", "height", "components", 0};

	if (!PyArg_ParseTupleAndKeywords(args, kwargs, "iiii|i:ReadPixels", (char **)kwlist, &x, &y, &width, &height, &components)) {
		return 0;
	}

	CHECK_AND_REPORT_ARG_VALUE_ERROR(width < 1, "width", width);
	CHECK_AND_REPORT_ARG_VALUE_ERROR(height < 1, "height", height);
	CHECK_AND_REPORT_ARG_VALUE_ERROR(components < 1 || components > 4, "components", components);

	int size = height * ((width * components + 3) & ~3);

	const int formats[] = {0, OpenGL::GL_RED, OpenGL::GL_RG, OpenGL::GL_RGB, OpenGL::GL_RGBA};
	int format = formats[components];

	PyObject * bytes = PyBytes_FromStringAndSize(0, size);
	char * data = PyBytes_AS_STRING(bytes);

	OpenGL::glReadPixels(x, y, width, height, format, OpenGL::GL_UNSIGNED_BYTE, data);
	data[size] = 0;

	return bytes;
}

PyObject * ReadDepthPixels(PyObject * self, PyObject * args, PyObject * kwargs) {
	int x;
	int y;
	int width;
	int height;

	static const char * kwlist[] = {"x", "y", "width", "height", 0};

	if (!PyArg_ParseTupleAndKeywords(args, kwargs, "iiii:ReadDepthPixels", (char **)kwlist, &x, &y, &width, &height)) {
		return 0;
	}

	CHECK_AND_REPORT_ARG_VALUE_ERROR(width < 1, "width", width);
	CHECK_AND_REPORT_ARG_VALUE_ERROR(height < 1, "height", height);

	int size = height * height * 4;
	float * pixels = ModernGL::ReadDepthPixels(x, y, width, height);
	PyObject * data = PyBytes_FromStringAndSize((const char *)pixels, size);
	free(pixels);

	PyObject * bytes = PyBytes_FromStringAndSize(0, size);
	char * data = PyBytes_AS_STRING(bytes);
	OpenGL::glReadPixels(x, y, width, height, OpenGL::GL_DEPTH_COMPONENT, OpenGL::GL_FLOAT, data);
	data[size] = 0;

	return bytes;
}

PyObject * ReadPixel(PyObject * self, PyObject * args, PyObject * kwargs) {
	int x;
	int y;

	static const char * kwlist[] = {"x", "y", 0};

	if (!PyArg_ParseTupleAndKeywords(args, kwargs, "ii:ReadPixel", (char **)kwlist, &x, &y)) {
		return 0;
	}

	unsigned rgba = 0;
	OpenGL::glReadPixels(x, y, 1, 1, OpenGL::GL_RGBA, OpenGL::GL_UNSIGNED_BYTE, &rgba);
	return PyLong_FromUnsignedLong(rgba);
}

PyObject * ReadDepthPixel(PyObject * self, PyObject * args, PyObject * kwargs) {
	int x;
	int y;

	static const char * kwlist[] = {"x", "y", 0};

	if (!PyArg_ParseTupleAndKeywords(args, kwargs, "ii:ReadDepthPixel", (char **)kwlist, &x, &y)) {
		return 0;
	}

	float depth = 0.0;
	OpenGL::glReadPixels(x, y, 1, 1, OpenGL::GL_DEPTH_COMPONENT, OpenGL::GL_FLOAT, &depth);
	return PyFloat_FromDouble(depth);
}
<commit_msg>checks still needed<commit_after>#include "ModernGL.hpp"

#include "OpenGL.hpp"

PyObject * NewFramebuffer(PyObject * self, PyObject * args, PyObject * kwargs) {
	int width = 0;
	int height = 0;

	static const char * kwlist[] = {"width", "height", 0};

	if (!PyArg_ParseTupleAndKeywords(args, kwargs, "|ii:NewFramebuffer", (char **)kwlist, &width, &height)) {
		return 0;
	}

	if (!width && !height) {
		width = activeViewportWidth;
		height = activeViewportHeight;
	}

	CHECK_AND_REPORT_ARG_VALUE_ERROR(width < 1, "width", width);
	CHECK_AND_REPORT_ARG_VALUE_ERROR(height < 1, "height", height);

	int framebuffer = 0;
	int color = 0;
	int depth = 0;

	OpenGL::glGenFramebuffers(1, (OpenGL::GLuint *)&framebuffer);
	OpenGL::glBindFramebuffer(OpenGL::GL_FRAMEBUFFER, framebuffer);

	OpenGL::glGenTextures(1, (OpenGL::GLuint *)&color);
	OpenGL::glBindTexture(OpenGL::GL_TEXTURE_2D, color);

	OpenGL::glTexParameteri(OpenGL::GL_TEXTURE_2D, OpenGL::GL_TEXTURE_MIN_FILTER, OpenGL::GL_LINEAR);
	OpenGL::glTexParameteri(OpenGL::GL_TEXTURE_2D, OpenGL::GL_TEXTURE_MAG_FILTER, OpenGL::GL_LINEAR);
	OpenGL::glTexImage2D(OpenGL::GL_TEXTURE_2D, 0, OpenGL::GL_RGBA, width, height, 0, OpenGL::GL_RGBA, OpenGL::GL_FLOAT, 0);
	OpenGL::glFramebufferTexture2D(OpenGL::GL_FRAMEBUFFER, OpenGL::GL_COLOR_ATTACHMENT0, OpenGL::GL_TEXTURE_2D, color, 0);

	OpenGL::glGenTextures(1, (OpenGL::GLuint *)&depth);
	OpenGL::glBindTexture(OpenGL::GL_TEXTURE_2D, depth);
	OpenGL::glTexParameteri(OpenGL::GL_TEXTURE_2D, OpenGL::GL_TEXTURE_MIN_FILTER, OpenGL::GL_LINEAR);
	OpenGL::glTexParameteri(OpenGL::GL_TEXTURE_2D, OpenGL::GL_TEXTURE_MAG_FILTER, OpenGL::GL_LINEAR);
	OpenGL::glTexImage2D(OpenGL::GL_TEXTURE_2D, 0, OpenGL::GL_DEPTH_COMPONENT, width, height, 0, OpenGL::GL_DEPTH_COMPONENT, OpenGL::GL_FLOAT, 0);
	OpenGL::glFramebufferTexture2D(OpenGL::GL_FRAMEBUFFER, OpenGL::GL_DEPTH_ATTACHMENT, OpenGL::GL_TEXTURE_2D, depth, 0);

	OpenGL::glBindFramebuffer(OpenGL::GL_FRAMEBUFFER, defaultFramebuffer);

	PyObject * fbo = CreateFramebufferType(framebuffer, color, depth);
	PyObject * colorTexture = CreateTextureType(color, width, height, 4);
	PyObject * depthTexture = CreateTextureType(depth, width, height, 1);

	return Py_BuildValue("OOO", fbo, colorTexture, depthTexture);
}

PyObject * DeleteFramebuffer(PyObject * self, PyObject * args) {
	Framebuffer * fbo;

	if (!PyArg_ParseTuple(args, "O:DeleteFramebuffer", &fbo)) {
		return 0;
	}

	CHECK_AND_REPORT_ARG_TYPE_ERROR("fbo", fbo, FramebufferType);

	OpenGL::glDeleteFramebuffers(1, (OpenGL::GLuint *)&fbo->fbo);
	OpenGL::glDeleteTextures(1, (OpenGL::GLuint *)&fbo->color);
	OpenGL::glDeleteTextures(1, (OpenGL::GLuint *)&fbo->depth);
	Py_RETURN_NONE;
}

PyObject * UseFramebuffer(PyObject * self, PyObject * args) {
	Framebuffer * fbo;

	if (!PyArg_ParseTuple(args, "O:UseFramebuffer", &fbo)) {
		return 0;
	}

	CHECK_AND_REPORT_ARG_TYPE_ERROR("fbo", fbo, FramebufferType);

	OpenGL::glBindFramebuffer(OpenGL::GL_FRAMEBUFFER, fbo->fbo);
	activeProgram = fbo->fbo;
	Py_RETURN_NONE;
}

PyObject * GetDefaultFramebuffer(PyObject * self) {
	OpenGL::glGetIntegerv(OpenGL::GL_DRAW_FRAMEBUFFER_BINDING, (OpenGL::GLint *)&defaultFramebuffer);
	Py_RETURN_NONE;
}

PyObject * UseDefaultFramebuffer(PyObject * self) {
	OpenGL::glBindFramebuffer(OpenGL::GL_FRAMEBUFFER, defaultFramebuffer);
	Py_RETURN_NONE;
}

PyObject * ReadPixels(PyObject * self, PyObject * args, PyObject * kwargs) {
	int x;
	int y;
	int width;
	int height;
	int components = 3;

	static const char * kwlist[] = {"x", "y", "width", "height", "components", 0};

	if (!PyArg_ParseTupleAndKeywords(args, kwargs, "iiii|i:ReadPixels", (char **)kwlist, &x, &y, &width, &height, &components)) {
		return 0;
	}

	CHECK_AND_REPORT_ARG_VALUE_ERROR(width < 1, "width", width);
	CHECK_AND_REPORT_ARG_VALUE_ERROR(height < 1, "height", height);
	CHECK_AND_REPORT_ARG_VALUE_ERROR(components < 1 || components > 4, "components", components);

	int size = height * ((width * components + 3) & ~3);

	const int formats[] = {0, OpenGL::GL_RED, OpenGL::GL_RG, OpenGL::GL_RGB, OpenGL::GL_RGBA};
	int format = formats[components];

	PyObject * bytes = PyBytes_FromStringAndSize(0, size);
	char * data = PyBytes_AS_STRING(bytes);

	OpenGL::glReadPixels(x, y, width, height, format, OpenGL::GL_UNSIGNED_BYTE, data);
	data[size] = 0;

	return bytes;
}

PyObject * ReadDepthPixels(PyObject * self, PyObject * args, PyObject * kwargs) {
	int x;
	int y;
	int width;
	int height;

	static const char * kwlist[] = {"x", "y", "width", "height", 0};

	if (!PyArg_ParseTupleAndKeywords(args, kwargs, "iiii:ReadDepthPixels", (char **)kwlist, &x, &y, &width, &height)) {
		return 0;
	}

	CHECK_AND_REPORT_ARG_VALUE_ERROR(width < 1, "width", width);
	CHECK_AND_REPORT_ARG_VALUE_ERROR(height < 1, "height", height);

	int size = height * height * 4;
	float * pixels = ModernGL::ReadDepthPixels(x, y, width, height);
	PyObject * data = PyBytes_FromStringAndSize((const char *)pixels, size);
	free(pixels);

	PyObject * bytes = PyBytes_FromStringAndSize(0, size);
	char * data = PyBytes_AS_STRING(bytes);
	OpenGL::glReadPixels(x, y, width, height, OpenGL::GL_DEPTH_COMPONENT, OpenGL::GL_FLOAT, data);
	data[size] = 0;

	return bytes;
}

PyObject * ReadPixel(PyObject * self, PyObject * args, PyObject * kwargs) {
	int x;
	int y;

	static const char * kwlist[] = {"x", "y", 0};

	if (!PyArg_ParseTupleAndKeywords(args, kwargs, "ii:ReadPixel", (char **)kwlist, &x, &y)) {
		return 0;
	}

	unsigned rgba = 0;
	OpenGL::glReadPixels(x, y, 1, 1, OpenGL::GL_RGBA, OpenGL::GL_UNSIGNED_BYTE, &rgba);
	return PyLong_FromUnsignedLong(rgba);
}

PyObject * ReadDepthPixel(PyObject * self, PyObject * args, PyObject * kwargs) {
	int x;
	int y;

	static const char * kwlist[] = {"x", "y", 0};

	if (!PyArg_ParseTupleAndKeywords(args, kwargs, "ii:ReadDepthPixel", (char **)kwlist, &x, &y)) {
		return 0;
	}

	float depth = 0.0;
	OpenGL::glReadPixels(x, y, 1, 1, OpenGL::GL_DEPTH_COMPONENT, OpenGL::GL_FLOAT, &depth);
	return PyFloat_FromDouble(depth);
}
<|endoftext|>


<commit_before>// Copyright 2013 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#include "content/renderer/pepper/resource_converter.h"

#include "base/bind.h"
#include "base/message_loop/message_loop.h"
#include "content/public/renderer/renderer_ppapi_host.h"
#include "content/renderer/pepper/pepper_file_system_host.h"
#include "content/renderer/pepper/pepper_media_stream_audio_track_host.h"
#include "content/renderer/pepper/pepper_media_stream_video_track_host.h"
#include "ipc/ipc_message.h"
#include "ppapi/host/ppapi_host.h"
#include "ppapi/host/resource_host.h"
#include "ppapi/proxy/ppapi_messages.h"
#include "ppapi/shared_impl/resource_var.h"
#include "ppapi/shared_impl/scoped_pp_var.h"
#include "third_party/WebKit/public/platform/WebFileSystem.h"
#include "third_party/WebKit/public/platform/WebMediaStreamSource.h"
#include "third_party/WebKit/public/web/WebDOMFileSystem.h"
#include "third_party/WebKit/public/web/WebDOMMediaStreamTrack.h"
#include "third_party/WebKit/public/web/WebFrame.h"
#include "webkit/common/fileapi/file_system_util.h"

using ppapi::ResourceVar;

namespace content {
namespace {

void FlushComplete(
    const base::Callback<void(bool)>& callback,
    const std::vector<scoped_refptr<content::HostResourceVar> >& browser_vars,
    const std::vector<int>& pending_host_ids) {
  CHECK(browser_vars.size() == pending_host_ids.size());
  for (size_t i = 0; i < browser_vars.size(); ++i) {
    browser_vars[i]->set_pending_browser_host_id(pending_host_ids[i]);
  }
  callback.Run(true);
}

// Converts a blink::WebFileSystem::Type to a PP_FileSystemType.
PP_FileSystemType WebFileSystemTypeToPPAPI(blink::WebFileSystem::Type type) {
  switch (type) {
    case blink::WebFileSystem::TypeTemporary:
      return PP_FILESYSTEMTYPE_LOCALTEMPORARY;
    case blink::WebFileSystem::TypePersistent:
      return PP_FILESYSTEMTYPE_LOCALPERSISTENT;
    case blink::WebFileSystem::TypeIsolated:
      return PP_FILESYSTEMTYPE_ISOLATED;
    case blink::WebFileSystem::TypeExternal:
      return PP_FILESYSTEMTYPE_EXTERNAL;
    default:
      NOTREACHED();
      return PP_FILESYSTEMTYPE_LOCALTEMPORARY;
  }
}

// Converts a fileapi::FileSystemType to a blink::WebFileSystemType.
// Returns true on success, false if |type| does not correspond to a
// WebFileSystemType.
bool FileApiFileSystemTypeToWebFileSystemType(
    fileapi::FileSystemType type,
    blink::WebFileSystemType* result_type) {
  switch (type) {
    case fileapi::kFileSystemTypeTemporary:
      *result_type = blink::WebFileSystemTypeTemporary;
      return true;
    case fileapi::kFileSystemTypePersistent:
      *result_type = blink::WebFileSystemTypePersistent;
      return true;
    case fileapi::kFileSystemTypeIsolated:
      *result_type = blink::WebFileSystemTypeIsolated;
      return true;
    case fileapi::kFileSystemTypeExternal:
      *result_type = blink::WebFileSystemTypeExternal;
      return true;
    default:
      return false;
  }
}

// Given a V8 value containing a DOMFileSystem, creates a resource host and
// returns the resource information for serialization.
// On error, false.
bool DOMFileSystemToResource(
    PP_Instance instance,
    RendererPpapiHost* host,
    const blink::WebDOMFileSystem& dom_file_system,
    int* pending_renderer_id,
    scoped_ptr<IPC::Message>* create_message,
    scoped_ptr<IPC::Message>* browser_host_create_message) {
  DCHECK(!dom_file_system.isNull());

  PP_FileSystemType file_system_type =
      WebFileSystemTypeToPPAPI(dom_file_system.type());
  GURL root_url = dom_file_system.rootURL();

  // External file systems are not currently supported. (Without this check,
  // there would be a CHECK-fail in FileRefResource.)
  // TODO(mgiuca): Support external file systems.
  if (file_system_type == PP_FILESYSTEMTYPE_EXTERNAL)
    return false;

  *pending_renderer_id = host->GetPpapiHost()->AddPendingResourceHost(
      scoped_ptr<ppapi::host::ResourceHost>(
          new PepperFileSystemHost(host, instance, 0, root_url,
              file_system_type)));
  if (*pending_renderer_id == 0)
    return false;

  create_message->reset(
      new PpapiPluginMsg_FileSystem_CreateFromPendingHost(file_system_type));

  browser_host_create_message->reset(
      new PpapiHostMsg_FileSystem_CreateFromRenderer(root_url.spec(),
                                                     file_system_type));
  return true;
}

bool ResourceHostToDOMFileSystem(
    content::PepperFileSystemHost* file_system_host,
    v8::Handle<v8::Context> context,
    v8::Handle<v8::Value>* dom_file_system) {
  GURL root_url = file_system_host->GetRootUrl();
  GURL origin;
  fileapi::FileSystemType type;
  base::FilePath virtual_path;
  fileapi::ParseFileSystemSchemeURL(root_url, &origin, &type, &virtual_path);

  std::string name = fileapi::GetFileSystemName(origin, type);
  blink::WebFileSystemType blink_type;
  if (!FileApiFileSystemTypeToWebFileSystemType(type, &blink_type))
    return false;
  blink::WebFrame* frame = blink::WebFrame::frameForContext(context);
  blink::WebDOMFileSystem web_dom_file_system = blink::WebDOMFileSystem::create(
      frame,
      blink_type,
      blink::WebString::fromUTF8(name),
      root_url,
      blink::WebDOMFileSystem::SerializableTypeSerializable);
  *dom_file_system = web_dom_file_system.toV8Value();
  return true;
}

bool DOMMediaStreamTrackToResource(
    PP_Instance instance,
    RendererPpapiHost* host,
    const blink::WebDOMMediaStreamTrack& dom_media_stream_track,
    int* pending_renderer_id,
    scoped_ptr<IPC::Message>* create_message) {
  DCHECK(!dom_media_stream_track.isNull());
  *pending_renderer_id = 0;

  const blink::WebMediaStreamTrack track = dom_media_stream_track.component();
  const std::string id = track.source().id().utf8();

  if (track.source().type() == blink::WebMediaStreamSource::TypeVideo) {
    *pending_renderer_id = host->GetPpapiHost()->AddPendingResourceHost(
        scoped_ptr<ppapi::host::ResourceHost>(
            new PepperMediaStreamVideoTrackHost(host, instance, 0, track)));
    if (*pending_renderer_id == 0)
      return false;

    create_message->reset(
        new PpapiPluginMsg_MediaStreamVideoTrack_CreateFromPendingHost(id));
    return true;
  } else if (track.source().type() == blink::WebMediaStreamSource::TypeAudio) {
    *pending_renderer_id = host->GetPpapiHost()->AddPendingResourceHost(
        scoped_ptr<ppapi::host::ResourceHost>(
            new PepperMediaStreamAudioTrackHost(host, instance, 0, track)));
    if (*pending_renderer_id == 0)
      return false;

    create_message->reset(
        new PpapiPluginMsg_MediaStreamAudioTrack_CreateFromPendingHost(id));
    return true;
  }

  return false;
}

}  // namespace

ResourceConverter::~ResourceConverter() {}

ResourceConverterImpl::ResourceConverterImpl(PP_Instance instance,
                                             RendererPpapiHost* host)
    : instance_(instance),
      host_(host) {
}

ResourceConverterImpl::~ResourceConverterImpl() {
  // Verify Flush() was called.
  DCHECK(browser_host_create_messages_.empty());
  DCHECK(browser_vars.empty());
}

bool ResourceConverterImpl::FromV8Value(v8::Handle<v8::Object> val,
                                        v8::Handle<v8::Context> context,
                                        PP_Var* result,
                                        bool* was_resource) {
  v8::Context::Scope context_scope(context);
  v8::HandleScope handle_scope(context->GetIsolate());

  *was_resource = false;

  blink::WebDOMFileSystem dom_file_system =
      blink::WebDOMFileSystem::fromV8Value(val);
  if (!dom_file_system.isNull()) {
    int pending_renderer_id;
    scoped_ptr<IPC::Message> create_message;
    scoped_ptr<IPC::Message> browser_host_create_message;
    if (!DOMFileSystemToResource(instance_, host_, dom_file_system,
                                 &pending_renderer_id, &create_message,
                                 &browser_host_create_message)) {
      return false;
    }
    DCHECK(create_message);
    DCHECK(browser_host_create_message);
    scoped_refptr<HostResourceVar> result_var =
        CreateResourceVarWithBrowserHost(
            pending_renderer_id, *create_message, *browser_host_create_message);
    *result = result_var->GetPPVar();
    *was_resource = true;
    return true;
  }

  blink::WebDOMMediaStreamTrack dom_media_stream_track =
      blink::WebDOMMediaStreamTrack::fromV8Value(val);
  if (!dom_media_stream_track.isNull()) {
    int pending_renderer_id;
    scoped_ptr<IPC::Message> create_message;
    if (!DOMMediaStreamTrackToResource(instance_, host_, dom_media_stream_track,
                                       &pending_renderer_id, &create_message)) {
      return false;
    }
    DCHECK(create_message);
    scoped_refptr<HostResourceVar> result_var = CreateResourceVar(
        pending_renderer_id, *create_message);
    *result = result_var->GetPPVar();
    *was_resource = true;
    return true;
  }

  // The value was not convertible to a resource. Return true with
  // |was_resource| set to false. As per the interface of FromV8Value, |result|
  // may be left unmodified in this case.
  return true;
}

void ResourceConverterImpl::Flush(const base::Callback<void(bool)>& callback) {
  host_->CreateBrowserResourceHosts(
      instance_,
      browser_host_create_messages_,
      base::Bind(&FlushComplete, callback, browser_vars));
  browser_host_create_messages_.clear();
  browser_vars.clear();
}

bool ResourceConverterImpl::ToV8Value(const PP_Var& var,
                                      v8::Handle<v8::Context> context,
                                      v8::Handle<v8::Value>* result) {
  DCHECK(var.type == PP_VARTYPE_RESOURCE);

  ResourceVar* resource = ResourceVar::FromPPVar(var);
  if (!resource) {
    NOTREACHED();
    return false;
  }
  PP_Resource resource_id = resource->GetPPResource();

  // Get the renderer-side resource host for this resource.
  content::RendererPpapiHost* renderer_ppapi_host =
      content::RendererPpapiHost::GetForPPInstance(instance_);
  if (!renderer_ppapi_host) {
    // This should never happen: the RendererPpapiHost is owned by the module
    // and should outlive instances associated with it. However, if it doesn't
    // for some reason, we do not want to crash.
    NOTREACHED();
    return false;
  }
  ::ppapi::host::PpapiHost* ppapi_host =
      renderer_ppapi_host->GetPpapiHost();
  ::ppapi::host::ResourceHost* resource_host =
      ppapi_host->GetResourceHost(resource_id);
  if (resource_host == NULL) {
    LOG(ERROR) << "No resource host for resource #" << resource_id;
    return false;
  }

  // Convert to the appropriate type of resource host.
  if (resource_host->IsFileSystemHost()) {
    return ResourceHostToDOMFileSystem(
        static_cast<content::PepperFileSystemHost*>(resource_host),
        context,
        result);
  } else {
    LOG(ERROR) << "The type of resource #" << resource_id
               << " cannot be converted to a JavaScript object.";
    return false;
  }
}

scoped_refptr<HostResourceVar> ResourceConverterImpl::CreateResourceVar(
    int pending_renderer_id,
    const IPC::Message& create_message) {
  return new HostResourceVar(pending_renderer_id, create_message);
}

scoped_refptr<HostResourceVar>
ResourceConverterImpl::CreateResourceVarWithBrowserHost(
    int pending_renderer_id,
    const IPC::Message& create_message,
    const IPC::Message& browser_host_create_message) {
  scoped_refptr<HostResourceVar> result =
      CreateResourceVar(pending_renderer_id, create_message);
  browser_host_create_messages_.push_back(browser_host_create_message);
  browser_vars.push_back(result);
  return result;
}

}  // namespace content
<commit_msg>Turn off WebRTC feature should not break the build on Linux<commit_after>// Copyright 2013 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#include "content/renderer/pepper/resource_converter.h"

#include "base/bind.h"
#include "base/message_loop/message_loop.h"
#include "content/public/renderer/renderer_ppapi_host.h"
#include "content/renderer/pepper/pepper_file_system_host.h"
#include "content/renderer/pepper/pepper_media_stream_audio_track_host.h"
#include "content/renderer/pepper/pepper_media_stream_video_track_host.h"
#include "ipc/ipc_message.h"
#include "ppapi/host/ppapi_host.h"
#include "ppapi/host/resource_host.h"
#include "ppapi/proxy/ppapi_messages.h"
#include "ppapi/shared_impl/resource_var.h"
#include "ppapi/shared_impl/scoped_pp_var.h"
#include "third_party/WebKit/public/platform/WebFileSystem.h"
#include "third_party/WebKit/public/platform/WebMediaStreamSource.h"
#include "third_party/WebKit/public/web/WebDOMFileSystem.h"
#include "third_party/WebKit/public/web/WebDOMMediaStreamTrack.h"
#include "third_party/WebKit/public/web/WebFrame.h"
#include "webkit/common/fileapi/file_system_util.h"

using ppapi::ResourceVar;

namespace content {
namespace {

void FlushComplete(
    const base::Callback<void(bool)>& callback,
    const std::vector<scoped_refptr<content::HostResourceVar> >& browser_vars,
    const std::vector<int>& pending_host_ids) {
  CHECK(browser_vars.size() == pending_host_ids.size());
  for (size_t i = 0; i < browser_vars.size(); ++i) {
    browser_vars[i]->set_pending_browser_host_id(pending_host_ids[i]);
  }
  callback.Run(true);
}

// Converts a blink::WebFileSystem::Type to a PP_FileSystemType.
PP_FileSystemType WebFileSystemTypeToPPAPI(blink::WebFileSystem::Type type) {
  switch (type) {
    case blink::WebFileSystem::TypeTemporary:
      return PP_FILESYSTEMTYPE_LOCALTEMPORARY;
    case blink::WebFileSystem::TypePersistent:
      return PP_FILESYSTEMTYPE_LOCALPERSISTENT;
    case blink::WebFileSystem::TypeIsolated:
      return PP_FILESYSTEMTYPE_ISOLATED;
    case blink::WebFileSystem::TypeExternal:
      return PP_FILESYSTEMTYPE_EXTERNAL;
    default:
      NOTREACHED();
      return PP_FILESYSTEMTYPE_LOCALTEMPORARY;
  }
}

// Converts a fileapi::FileSystemType to a blink::WebFileSystemType.
// Returns true on success, false if |type| does not correspond to a
// WebFileSystemType.
bool FileApiFileSystemTypeToWebFileSystemType(
    fileapi::FileSystemType type,
    blink::WebFileSystemType* result_type) {
  switch (type) {
    case fileapi::kFileSystemTypeTemporary:
      *result_type = blink::WebFileSystemTypeTemporary;
      return true;
    case fileapi::kFileSystemTypePersistent:
      *result_type = blink::WebFileSystemTypePersistent;
      return true;
    case fileapi::kFileSystemTypeIsolated:
      *result_type = blink::WebFileSystemTypeIsolated;
      return true;
    case fileapi::kFileSystemTypeExternal:
      *result_type = blink::WebFileSystemTypeExternal;
      return true;
    default:
      return false;
  }
}

// Given a V8 value containing a DOMFileSystem, creates a resource host and
// returns the resource information for serialization.
// On error, false.
bool DOMFileSystemToResource(
    PP_Instance instance,
    RendererPpapiHost* host,
    const blink::WebDOMFileSystem& dom_file_system,
    int* pending_renderer_id,
    scoped_ptr<IPC::Message>* create_message,
    scoped_ptr<IPC::Message>* browser_host_create_message) {
  DCHECK(!dom_file_system.isNull());

  PP_FileSystemType file_system_type =
      WebFileSystemTypeToPPAPI(dom_file_system.type());
  GURL root_url = dom_file_system.rootURL();

  // External file systems are not currently supported. (Without this check,
  // there would be a CHECK-fail in FileRefResource.)
  // TODO(mgiuca): Support external file systems.
  if (file_system_type == PP_FILESYSTEMTYPE_EXTERNAL)
    return false;

  *pending_renderer_id = host->GetPpapiHost()->AddPendingResourceHost(
      scoped_ptr<ppapi::host::ResourceHost>(
          new PepperFileSystemHost(host, instance, 0, root_url,
              file_system_type)));
  if (*pending_renderer_id == 0)
    return false;

  create_message->reset(
      new PpapiPluginMsg_FileSystem_CreateFromPendingHost(file_system_type));

  browser_host_create_message->reset(
      new PpapiHostMsg_FileSystem_CreateFromRenderer(root_url.spec(),
                                                     file_system_type));
  return true;
}

bool ResourceHostToDOMFileSystem(
    content::PepperFileSystemHost* file_system_host,
    v8::Handle<v8::Context> context,
    v8::Handle<v8::Value>* dom_file_system) {
  GURL root_url = file_system_host->GetRootUrl();
  GURL origin;
  fileapi::FileSystemType type;
  base::FilePath virtual_path;
  fileapi::ParseFileSystemSchemeURL(root_url, &origin, &type, &virtual_path);

  std::string name = fileapi::GetFileSystemName(origin, type);
  blink::WebFileSystemType blink_type;
  if (!FileApiFileSystemTypeToWebFileSystemType(type, &blink_type))
    return false;
  blink::WebFrame* frame = blink::WebFrame::frameForContext(context);
  blink::WebDOMFileSystem web_dom_file_system = blink::WebDOMFileSystem::create(
      frame,
      blink_type,
      blink::WebString::fromUTF8(name),
      root_url,
      blink::WebDOMFileSystem::SerializableTypeSerializable);
  *dom_file_system = web_dom_file_system.toV8Value();
  return true;
}

bool DOMMediaStreamTrackToResource(
    PP_Instance instance,
    RendererPpapiHost* host,
    const blink::WebDOMMediaStreamTrack& dom_media_stream_track,
    int* pending_renderer_id,
    scoped_ptr<IPC::Message>* create_message) {
  DCHECK(!dom_media_stream_track.isNull());
  *pending_renderer_id = 0;
#if defined(ENABLE_WEBRTC)
  const blink::WebMediaStreamTrack track = dom_media_stream_track.component();
  const std::string id = track.source().id().utf8();

  if (track.source().type() == blink::WebMediaStreamSource::TypeVideo) {
    *pending_renderer_id = host->GetPpapiHost()->AddPendingResourceHost(
        scoped_ptr<ppapi::host::ResourceHost>(
            new PepperMediaStreamVideoTrackHost(host, instance, 0, track)));
    if (*pending_renderer_id == 0)
      return false;

    create_message->reset(
        new PpapiPluginMsg_MediaStreamVideoTrack_CreateFromPendingHost(id));
    return true;
  } else if (track.source().type() == blink::WebMediaStreamSource::TypeAudio) {
    *pending_renderer_id = host->GetPpapiHost()->AddPendingResourceHost(
        scoped_ptr<ppapi::host::ResourceHost>(
            new PepperMediaStreamAudioTrackHost(host, instance, 0, track)));
    if (*pending_renderer_id == 0)
      return false;

    create_message->reset(
        new PpapiPluginMsg_MediaStreamAudioTrack_CreateFromPendingHost(id));
    return true;
  }
#endif
  return false;
}

}  // namespace

ResourceConverter::~ResourceConverter() {}

ResourceConverterImpl::ResourceConverterImpl(PP_Instance instance,
                                             RendererPpapiHost* host)
    : instance_(instance),
      host_(host) {
}

ResourceConverterImpl::~ResourceConverterImpl() {
  // Verify Flush() was called.
  DCHECK(browser_host_create_messages_.empty());
  DCHECK(browser_vars.empty());
}

bool ResourceConverterImpl::FromV8Value(v8::Handle<v8::Object> val,
                                        v8::Handle<v8::Context> context,
                                        PP_Var* result,
                                        bool* was_resource) {
  v8::Context::Scope context_scope(context);
  v8::HandleScope handle_scope(context->GetIsolate());

  *was_resource = false;

  blink::WebDOMFileSystem dom_file_system =
      blink::WebDOMFileSystem::fromV8Value(val);
  if (!dom_file_system.isNull()) {
    int pending_renderer_id;
    scoped_ptr<IPC::Message> create_message;
    scoped_ptr<IPC::Message> browser_host_create_message;
    if (!DOMFileSystemToResource(instance_, host_, dom_file_system,
                                 &pending_renderer_id, &create_message,
                                 &browser_host_create_message)) {
      return false;
    }
    DCHECK(create_message);
    DCHECK(browser_host_create_message);
    scoped_refptr<HostResourceVar> result_var =
        CreateResourceVarWithBrowserHost(
            pending_renderer_id, *create_message, *browser_host_create_message);
    *result = result_var->GetPPVar();
    *was_resource = true;
    return true;
  }

  blink::WebDOMMediaStreamTrack dom_media_stream_track =
      blink::WebDOMMediaStreamTrack::fromV8Value(val);
  if (!dom_media_stream_track.isNull()) {
    int pending_renderer_id;
    scoped_ptr<IPC::Message> create_message;
    if (!DOMMediaStreamTrackToResource(instance_, host_, dom_media_stream_track,
                                       &pending_renderer_id, &create_message)) {
      return false;
    }
    DCHECK(create_message);
    scoped_refptr<HostResourceVar> result_var = CreateResourceVar(
        pending_renderer_id, *create_message);
    *result = result_var->GetPPVar();
    *was_resource = true;
    return true;
  }

  // The value was not convertible to a resource. Return true with
  // |was_resource| set to false. As per the interface of FromV8Value, |result|
  // may be left unmodified in this case.
  return true;
}

void ResourceConverterImpl::Flush(const base::Callback<void(bool)>& callback) {
  host_->CreateBrowserResourceHosts(
      instance_,
      browser_host_create_messages_,
      base::Bind(&FlushComplete, callback, browser_vars));
  browser_host_create_messages_.clear();
  browser_vars.clear();
}

bool ResourceConverterImpl::ToV8Value(const PP_Var& var,
                                      v8::Handle<v8::Context> context,
                                      v8::Handle<v8::Value>* result) {
  DCHECK(var.type == PP_VARTYPE_RESOURCE);

  ResourceVar* resource = ResourceVar::FromPPVar(var);
  if (!resource) {
    NOTREACHED();
    return false;
  }
  PP_Resource resource_id = resource->GetPPResource();

  // Get the renderer-side resource host for this resource.
  content::RendererPpapiHost* renderer_ppapi_host =
      content::RendererPpapiHost::GetForPPInstance(instance_);
  if (!renderer_ppapi_host) {
    // This should never happen: the RendererPpapiHost is owned by the module
    // and should outlive instances associated with it. However, if it doesn't
    // for some reason, we do not want to crash.
    NOTREACHED();
    return false;
  }
  ::ppapi::host::PpapiHost* ppapi_host =
      renderer_ppapi_host->GetPpapiHost();
  ::ppapi::host::ResourceHost* resource_host =
      ppapi_host->GetResourceHost(resource_id);
  if (resource_host == NULL) {
    LOG(ERROR) << "No resource host for resource #" << resource_id;
    return false;
  }

  // Convert to the appropriate type of resource host.
  if (resource_host->IsFileSystemHost()) {
    return ResourceHostToDOMFileSystem(
        static_cast<content::PepperFileSystemHost*>(resource_host),
        context,
        result);
  } else {
    LOG(ERROR) << "The type of resource #" << resource_id
               << " cannot be converted to a JavaScript object.";
    return false;
  }
}

scoped_refptr<HostResourceVar> ResourceConverterImpl::CreateResourceVar(
    int pending_renderer_id,
    const IPC::Message& create_message) {
  return new HostResourceVar(pending_renderer_id, create_message);
}

scoped_refptr<HostResourceVar>
ResourceConverterImpl::CreateResourceVarWithBrowserHost(
    int pending_renderer_id,
    const IPC::Message& create_message,
    const IPC::Message& browser_host_create_message) {
  scoped_refptr<HostResourceVar> result =
      CreateResourceVar(pending_renderer_id, create_message);
  browser_host_create_messages_.push_back(browser_host_create_message);
  browser_vars.push_back(result);
  return result;
}

}  // namespace content
<|endoftext|>


<commit_before>#include "BallFinder.h"

BallFinder::BallFinder()
{
}

BallFinder::~BallFinder()
{
}

bool BallFinder::Locate(cv::Mat &imgThresholded, cv::Mat &frameHSV, cv::Mat &frameBGR, std::vector<cv::Point2d> &objectCoords) {

	cv::Point2d notValidPosition = cv::Point2d(-1.0, -1.0);

	int smallestBallArea = 4;
	cv::Point2d center(-1, -1);

	if (imgThresholded.rows == 0){
		std::cout << "Image thresholding has failed" << std::endl;
		return false;
	}
	cv::Mat dst(imgThresholded.rows, imgThresholded.cols, CV_8U, cv::Scalar::all(0));

	std::vector<std::vector<cv::Point>> contours; // Vector for storing contour
	std::vector<cv::Vec4i> hierarchy;

	cv::Scalar blackColor(0, 0, 0);
	cv::Scalar whiteColor(255, 255, 255);
	cv::Scalar redColor(0, 0, 255);

	findContours(imgThresholded, contours, hierarchy, cv::RETR_EXTERNAL, cv::CHAIN_APPROX_SIMPLE); // Find the contours in the image

	if (contours.size() == 0){ //if no contours found
		return false;
	}
	int ballsUpdatedCount = 0;
	cv::Point2d frameCenter = cv::Point2d(frameHSV.size()) / 2;

	for (unsigned int i = 0; i < contours.size(); i++)
	{
		int ballArea = (int)(cv::contourArea(contours[i], false));
		if (ballArea >= smallestBallArea) {
			cv::Moments M = cv::moments(contours[i]);
			cv::Rect bounding_rect = cv::boundingRect(contours[i]);
			rectangle(frameBGR, bounding_rect.tl(), bounding_rect.br(), redColor, 1, 8, 0);
			try{
			objectCoords.push_back(cv::Point2d((M.m10 / M.m00), (M.m01 / M.m00)) - frameCenter);
			}
			catch(cv::Exception ex){
				return false;
			   std::cout<< ex.msg;
			}
			ballsUpdatedCount++;
		}
	}
	return true;
}

bool BallFinder::validateBall(ThresholdedImages &HSVRanges, cv::Point2d endPoint, cv::Mat &frameHSV, cv::Mat &frameBGR)
{
	cv::Mat innerThresholded = HSVRanges[INNER_BORDER];
	cv::Mat outerThresholded = HSVRanges[OUTER_BORDER];
	cv::Mat fieldThresholded = HSVRanges[FIELD];

	cv::circle(innerThresholded, cv::Point(innerThresholded.size() / 2), 70, cv::Scalar(0, 255, 0), -1);
	cv::circle(outerThresholded, cv::Point(outerThresholded.size() / 2), 70, cv::Scalar(0, 255, 0), -1);
	cv::circle(fieldThresholded, cv::Point(fieldThresholded.size() / 2), 70, cv::Scalar(0, 255, 0), -1);

	cv::Point startPoint;
	startPoint.x = frameHSV.cols / 2;
	startPoint.y = frameHSV.rows / 2;
	endPoint += cv::Point2d(frameHSV.size()) / 2;

	cv::LineIterator iterator(frameHSV, startPoint, endPoint, 8);
	int behindLineCount = 0;
	int alterIterator = -10;
	for (int n = 0; n < 10; n++){
		cv::Point2d lastInner = { 0, 0 };
		cv::Point2d firstInner = { 0, 0 };
		cv::Point2d lastOuter = { 0, 0 };
		cv::Point2d firstOuter = { 0, 0 };

		std::string state = "inner";
		bool Hinrange = false;
		bool Sinrange = false;
		bool Vinrange = false;
		bool firstFound = false;
		bool fieldFound = false;
		cv::Point start2 = cv::Point(startPoint.x + alterIterator, startPoint.y);
		cv::Point end2 = cv::Point(endPoint.x + alterIterator, endPoint.y);

		iterator = cv::LineIterator{ frameHSV, start2, end2, 8 };
		for (int i = 0; i < iterator.count; i++, ++iterator)
		{
			if (state == "inner"){
				//std::cout << iterator.pos() << " : " << (innerThresholded.ptr<uchar>(iterator.pos().y)[iterator.pos().x] ? 1:0) << std::endl;

				bool inRange = innerThresholded.ptr<uchar>(iterator.pos().y)[iterator.pos().x] == 255;
				if (inRange){
					firstInner = iterator.pos();
					state = "outer";
				}
			}
			else if (state == "outer") {
				bool inRange = outerThresholded.ptr<uchar>(iterator.pos().y)[iterator.pos().x] == 255;
				bool fieldInRange = fieldThresholded.ptr<uchar>(iterator.pos().y)[iterator.pos().x] == 255;
				if (fieldInRange && !fieldFound){
					if (!firstFound){
						fieldFound = true; //Found field between inner and outer
					}
				}
				else if (inRange && !firstFound){
					firstFound = true;
					firstOuter = iterator.pos();
				}
				else if (inRange){
					lastOuter = iterator.pos();
				}
				inRange = innerThresholded.ptr<uchar>(iterator.pos().y)[iterator.pos().x] == 255;
				if (inRange){
					lastInner = iterator.pos();
				}

			}
		}//lineiterator end
		alterIterator = alterIterator + 2;
		cv::circle(frameBGR, firstOuter, 5, cv::Scalar(0, 0, 0), -1);
		cv::circle(frameBGR, lastInner, 5, cv::Scalar(200, 200, 200), -1);

		double distLiFo = cv::norm(lastInner - firstOuter);

		if (!firstFound || fieldFound){
			continue;
		}
		if (distLiFo < 20){
			behindLineCount++;
		}
	}//ten times end

	return !(behindLineCount >= 4);
}
<commit_msg>Better crash fix maybe<commit_after>#include "BallFinder.h"

BallFinder::BallFinder()
{
}

BallFinder::~BallFinder()
{
}

bool BallFinder::Locate(cv::Mat &imgThresholded, cv::Mat &frameHSV, cv::Mat &frameBGR, std::vector<cv::Point2d> &objectCoords) {

	try{
		cv::Point2d notValidPosition = cv::Point2d(-1.0, -1.0);

		int smallestBallArea = 4;
		cv::Point2d center(-1, -1);

		if (imgThresholded.rows == 0){
			std::cout << "Image thresholding has failed" << std::endl;
			return false;
		}
		cv::Mat dst(imgThresholded.rows, imgThresholded.cols, CV_8U, cv::Scalar::all(0));

		std::vector<std::vector<cv::Point>> contours; // Vector for storing contour
		std::vector<cv::Vec4i> hierarchy;

		cv::Scalar blackColor(0, 0, 0);
		cv::Scalar whiteColor(255, 255, 255);
		cv::Scalar redColor(0, 0, 255);

		findContours(imgThresholded, contours, hierarchy, cv::RETR_EXTERNAL, cv::CHAIN_APPROX_SIMPLE); // Find the contours in the image

		if (contours.size() == 0){ //if no contours found
			return false;
		}
		int ballsUpdatedCount = 0;
		cv::Point2d frameCenter = cv::Point2d(frameHSV.size()) / 2;

		for (unsigned int i = 0; i < contours.size(); i++)
		{
			int ballArea = (int)(cv::contourArea(contours[i], false));
			if (ballArea >= smallestBallArea) {
				cv::Moments M = cv::moments(contours[i]);
				cv::Rect bounding_rect = cv::boundingRect(contours[i]);
				rectangle(frameBGR, bounding_rect.tl(), bounding_rect.br(), redColor, 1, 8, 0);
				try{objectCoords.push_back(cv::Point2d((M.m10 / M.m00), (M.m01 / M.m00)) - frameCenter);}
				catch(cv::Exception ex){return false;}
				ballsUpdatedCount++;
			}
		}
		return true;
	}catch (cv::Exception ex){ return false; }
}

bool BallFinder::validateBall(ThresholdedImages &HSVRanges, cv::Point2d endPoint, cv::Mat &frameHSV, cv::Mat &frameBGR)
{
	cv::Mat innerThresholded = HSVRanges[INNER_BORDER];
	cv::Mat outerThresholded = HSVRanges[OUTER_BORDER];
	cv::Mat fieldThresholded = HSVRanges[FIELD];

	cv::circle(innerThresholded, cv::Point(innerThresholded.size() / 2), 70, cv::Scalar(0, 255, 0), -1);
	cv::circle(outerThresholded, cv::Point(outerThresholded.size() / 2), 70, cv::Scalar(0, 255, 0), -1);
	cv::circle(fieldThresholded, cv::Point(fieldThresholded.size() / 2), 70, cv::Scalar(0, 255, 0), -1);

	cv::Point startPoint;
	startPoint.x = frameHSV.cols / 2;
	startPoint.y = frameHSV.rows / 2;
	endPoint += cv::Point2d(frameHSV.size()) / 2;

	cv::LineIterator iterator(frameHSV, startPoint, endPoint, 8);
	int behindLineCount = 0;
	int alterIterator = -10;
	for (int n = 0; n < 10; n++){
		cv::Point2d lastInner = { 0, 0 };
		cv::Point2d firstInner = { 0, 0 };
		cv::Point2d lastOuter = { 0, 0 };
		cv::Point2d firstOuter = { 0, 0 };

		std::string state = "inner";
		bool Hinrange = false;
		bool Sinrange = false;
		bool Vinrange = false;
		bool firstFound = false;
		bool fieldFound = false;
		cv::Point start2 = cv::Point(startPoint.x + alterIterator, startPoint.y);
		cv::Point end2 = cv::Point(endPoint.x + alterIterator, endPoint.y);

		iterator = cv::LineIterator{ frameHSV, start2, end2, 8 };
		for (int i = 0; i < iterator.count; i++, ++iterator)
		{
			if (state == "inner"){
				//std::cout << iterator.pos() << " : " << (innerThresholded.ptr<uchar>(iterator.pos().y)[iterator.pos().x] ? 1:0) << std::endl;

				bool inRange = innerThresholded.ptr<uchar>(iterator.pos().y)[iterator.pos().x] == 255;
				if (inRange){
					firstInner = iterator.pos();
					state = "outer";
				}
			}
			else if (state == "outer") {
				bool inRange = outerThresholded.ptr<uchar>(iterator.pos().y)[iterator.pos().x] == 255;
				bool fieldInRange = fieldThresholded.ptr<uchar>(iterator.pos().y)[iterator.pos().x] == 255;
				if (fieldInRange && !fieldFound){
					if (!firstFound){
						fieldFound = true; //Found field between inner and outer
					}
				}
				else if (inRange && !firstFound){
					firstFound = true;
					firstOuter = iterator.pos();
				}
				else if (inRange){
					lastOuter = iterator.pos();
				}
				inRange = innerThresholded.ptr<uchar>(iterator.pos().y)[iterator.pos().x] == 255;
				if (inRange){
					lastInner = iterator.pos();
				}

			}
		}//lineiterator end
		alterIterator = alterIterator + 2;
		cv::circle(frameBGR, firstOuter, 5, cv::Scalar(0, 0, 0), -1);
		cv::circle(frameBGR, lastInner, 5, cv::Scalar(200, 200, 200), -1);

		double distLiFo = cv::norm(lastInner - firstOuter);

		if (!firstFound || fieldFound){
			continue;
		}
		if (distLiFo < 20){
			behindLineCount++;
		}
	}//ten times end

	return !(behindLineCount >= 4);
}
<|endoftext|>


<commit_before>#ifndef _SNARKFRONT_BITWISE_AST_HPP_
#define _SNARKFRONT_BITWISE_AST_HPP_

#include <array>
#include <cassert>
#include <climits>
#include "Alg.hpp"
#include "AST.hpp"

namespace snarkfront {

////////////////////////////////////////////////////////////////////////////////
// operations on AST nodes
// (templated algorithm parameter)
//
// T is: Alg_uint8, Alg_uint32, Alg_uint64
//

template <typename T>
class BitwiseAST
{
    // Note: Every member function is templated to accept both
    // reference and pointer arguments.

    typedef typename T::ValueType VAL;
    typedef typename T::FrType FR;

public:
    // bitwise complement
    template <typename X>
    static AST_Op<T> CMPLMNT(const X& x) {
        return AST_Op<T>(T::OpType::CMPLMNT, x);
    }

    template <typename X>
    static AST_Op<T>* _CMPLMNT(const X& x) {
        return new AST_Op<T>(T::OpType::CMPLMNT, x);
    }

#define DEFN_OPXY(NAME)                                         \
    template <typename X, typename Y>                           \
    static AST_Op<T> NAME (const X& x, const Y& y) {            \
        return objOp(T::OpType:: NAME , x, y);                  \
    }                                                           \
    template <typename X, typename Y>                           \
    static AST_Op<T>* _ ## NAME (const X& x, const Y& y) {      \
        return ptrOp(T::OpType:: NAME , x, y);                  \
    }

    // AND, OR, XOR, ADDMOD
    DEFN_OPXY(AND)
    DEFN_OPXY(OR)
    DEFN_OPXY(XOR)
    DEFN_OPXY(ADDMOD)

#undef DEFN_OPXY

#define DEFN_SHIFT(NAME)                                                \
    template <typename X>                                               \
    static AST_Op<T> NAME (const X& x, const unsigned int n) {          \
        return objOp(T::OpType:: NAME , x, _constant(n));               \
    }                                                                   \
    template <typename X>                                               \
    static AST_Op<T>* _ ## NAME (const X& x, const unsigned int n) {    \
        return ptrOp(T::OpType:: NAME , x, _constant(n));               \
    }

    // SHL, SHR
    DEFN_SHIFT(SHL)
    DEFN_SHIFT(SHR)

#undef DEFN_SHIFT

    // ROTL
    template <typename X>
    static AST_Op<T> ROTL(const X& x, const unsigned int n) {
#ifdef USE_ASSERT
    assert(n <= sizeof(VAL) * CHAR_BIT);
#endif
        return objOp(T::OpType::ROTL, x, _constant(n));
    }

    template <typename X>
    static AST_Op<T>* _ROTL(const X& x, const unsigned int n) {
#ifdef USE_ASSERT
    assert(n <= sizeof(VAL) * CHAR_BIT);
#endif
        return ptrOp(T::OpType::ROTL, x, _constant(n));
    }

    // ROTR
    template <typename X>
    static AST_Op<T> ROTR(const X& x, const unsigned int n) {
#ifdef USE_ASSERT
    assert(n <= sizeof(VAL) * CHAR_BIT);
#endif
        return objOp(T::OpType::ROTR, x, _constant(n));
    }

    template <typename X>
    static AST_Op<T>* _ROTR(const X& x, const unsigned int n) {
#ifdef USE_ASSERT
    assert(n <= sizeof(VAL) * CHAR_BIT);
#endif
        return ptrOp(T::OpType::ROTR, x, _constant(n));
    }

    // literal value
    template <typename X>
    static AST_Const<T> constant(const X& x) { return AST_Const<T>(x); }

    template <typename X>
    static AST_Const<T>* _constant(const X& x) { return new AST_Const<T>(x); }

    // conversion between unsigned integer types
    template <typename X, typename U>
    static AST_X<U> xword(const X& x, const U& dummy) {
        return AST_X<U>(x);
    }

    template <typename X, typename U>
    static AST_X<U>* _xword(const X& x, const U& dummy) {
        return new AST_X<U>(x);
    }

    // all mask bits take value of same bool
    template <typename B>
    static AST_X<T> bitmask(const B& b) {
        return AST_X<T>(b);
    }

    template <typename B>
    static AST_X<T>* _bitmask(const B& b) {
        return new AST_X<T>(b);
    }

    // ternary
    template <typename B, typename X, typename Y>
    static AST_Op<T> ternary(const B& b, const X& x, const Y& y) {
        // (x & xword(b)) | (y & ~xword(b))
        return OR(
            _AND(x, _bitmask(b)),
            _AND(y, _CMPLMNT(_bitmask(b))));
    }

    template <typename B, typename X, typename Y>
    static AST_Op<T>* _ternary(const B& b, const X& x, const Y& y) {
        // (x & xword(b)) | (y & ~xword(b))
        return _OR(
            _AND(x, _bitmask(b)),
            _AND(y, _CMPLMNT(_bitmask(b))));
    }

    // test bit
    template <typename X>
    static AST_X<Alg_bool<FR>> testbit(const X& x, const unsigned int n) {
#ifdef USE_ASSERT
        assert(n < sizeof(VAL) * CHAR_BIT);
#endif
        return AST_X<Alg_bool<FR>>(SHR(x, n));
    }

    template <typename X>
    static AST_X<Alg_bool<FR>>* _testbit(const X& x, const unsigned int n) {
#ifdef USE_ASSERT
        assert(n < sizeof(VAL) * CHAR_BIT);
#endif
        return new AST_X<Alg_bool<FR>>(SHR(x, n));
    }

    // multiplication by x in GF(2^n)
    template <typename X, typename M>
    static AST_Op<T> xtime(const X& a, const M& modpoly) {
        return XOR(
            _SHL(a, 1),
            _AND(modpoly, _bitmask(testbit(a, sizeof(VAL) * CHAR_BIT - 1))));
    }

    template <typename X, typename M>
    static AST_Op<T>* _xtime(const X& a, const M& modpoly) {
        return _XOR(
            _SHL(a, 1),
            _AND(modpoly, _bitmask(testbit(a, sizeof(VAL) * CHAR_BIT - 1))));
    }

    // multiplication by GF(2^n)
    template <typename X, typename Y, typename M>
    static AST_Op<T> multiply(const X& a, const Y& b, const M& modpoly) {
        return XOR(multiply_internal(a, b, modpoly),
                   _AND(a, bitmask(testbit(b, 0))));
    }

    template <typename X, typename Y, typename M>
    static AST_Op<T>* _multiply(const X& a, const Y& b, const M& modpoly) {
        return _XOR(multiply_internal(a, b, modpoly),
                    _AND(a, bitmask(testbit(b, 0))));
    }

private:
    template <typename X, typename Y, typename M>
    static AST_Op<T>* multiply_internal(const X& a, const Y& b, const M& modpoly) {
        constexpr std::size_t N = sizeof(VAL) * CHAR_BIT;

        // multiplication by x in GF(2^n) for each bit position in b
        std::array<AST_Op<T>*, N> xtmp;
        xtmp[1] = _xtime(a, modpoly);
        for (std::size_t i = 2; i < N; ++i) {
            xtmp[i] = _xtime(xtmp[i - 1], modpoly);
        }

        // apply bits of b
        std::array<AST_Op<T>*, N> btmp;
        for (std::size_t i = 1; i < N; ++i) {
            btmp[i] = _AND(xtmp[i], _bitmask(testbit(b, i)));
        }

        // sum components up to last one
        auto* xorsum = btmp[N - 1];
        for (std::size_t i = N - 2; i > 0; --i) {
            xorsum = _XOR(xorsum, btmp[i]);
        }

        return xorsum;
    }

    // AST nodes at statement scope are on stack
    template <typename X, typename Y>
    static AST_Op<T> objOp(const typename T::OpType op, const X& x, const Y& y) {
        return AST_Op<T>(op, x, y);
    }

    // AST nodes nested below statement scope are on the heap
    template <typename X, typename Y>
    static AST_Op<T>* ptrOp(const typename T::OpType op, const X& x, const Y& y) {
        return new AST_Op<T>(op, x, y);
    }
};

} // namespace snarkfront

#endif
<commit_msg>scope header file paths<commit_after>#ifndef _SNARKFRONT_BITWISE_AST_HPP_
#define _SNARKFRONT_BITWISE_AST_HPP_

#include <array>
#include <cassert>
#include <climits>

#include <snarkfront/Alg.hpp>
#include <snarkfront/AST.hpp>

namespace snarkfront {

////////////////////////////////////////////////////////////////////////////////
// operations on AST nodes
// (templated algorithm parameter)
//
// T is: Alg_uint8, Alg_uint32, Alg_uint64
//

template <typename T>
class BitwiseAST
{
    // Note: Every member function is templated to accept both
    // reference and pointer arguments.

    typedef typename T::ValueType VAL;
    typedef typename T::FrType FR;

public:
    // bitwise complement
    template <typename X>
    static AST_Op<T> CMPLMNT(const X& x) {
        return AST_Op<T>(T::OpType::CMPLMNT, x);
    }

    template <typename X>
    static AST_Op<T>* _CMPLMNT(const X& x) {
        return new AST_Op<T>(T::OpType::CMPLMNT, x);
    }

#define DEFN_OPXY(NAME)                                         \
    template <typename X, typename Y>                           \
    static AST_Op<T> NAME (const X& x, const Y& y) {            \
        return objOp(T::OpType:: NAME , x, y);                  \
    }                                                           \
    template <typename X, typename Y>                           \
    static AST_Op<T>* _ ## NAME (const X& x, const Y& y) {      \
        return ptrOp(T::OpType:: NAME , x, y);                  \
    }

    // AND, OR, XOR, ADDMOD
    DEFN_OPXY(AND)
    DEFN_OPXY(OR)
    DEFN_OPXY(XOR)
    DEFN_OPXY(ADDMOD)

#undef DEFN_OPXY

#define DEFN_SHIFT(NAME)                                                \
    template <typename X>                                               \
    static AST_Op<T> NAME (const X& x, const unsigned int n) {          \
        return objOp(T::OpType:: NAME , x, _constant(n));               \
    }                                                                   \
    template <typename X>                                               \
    static AST_Op<T>* _ ## NAME (const X& x, const unsigned int n) {    \
        return ptrOp(T::OpType:: NAME , x, _constant(n));               \
    }

    // SHL, SHR
    DEFN_SHIFT(SHL)
    DEFN_SHIFT(SHR)

#undef DEFN_SHIFT

    // ROTL
    template <typename X>
    static AST_Op<T> ROTL(const X& x, const unsigned int n) {
#ifdef USE_ASSERT
    assert(n <= sizeof(VAL) * CHAR_BIT);
#endif
        return objOp(T::OpType::ROTL, x, _constant(n));
    }

    template <typename X>
    static AST_Op<T>* _ROTL(const X& x, const unsigned int n) {
#ifdef USE_ASSERT
    assert(n <= sizeof(VAL) * CHAR_BIT);
#endif
        return ptrOp(T::OpType::ROTL, x, _constant(n));
    }

    // ROTR
    template <typename X>
    static AST_Op<T> ROTR(const X& x, const unsigned int n) {
#ifdef USE_ASSERT
    assert(n <= sizeof(VAL) * CHAR_BIT);
#endif
        return objOp(T::OpType::ROTR, x, _constant(n));
    }

    template <typename X>
    static AST_Op<T>* _ROTR(const X& x, const unsigned int n) {
#ifdef USE_ASSERT
    assert(n <= sizeof(VAL) * CHAR_BIT);
#endif
        return ptrOp(T::OpType::ROTR, x, _constant(n));
    }

    // literal value
    template <typename X>
    static AST_Const<T> constant(const X& x) { return AST_Const<T>(x); }

    template <typename X>
    static AST_Const<T>* _constant(const X& x) { return new AST_Const<T>(x); }

    // conversion between unsigned integer types
    template <typename X, typename U>
    static AST_X<U> xword(const X& x, const U& dummy) {
        return AST_X<U>(x);
    }

    template <typename X, typename U>
    static AST_X<U>* _xword(const X& x, const U& dummy) {
        return new AST_X<U>(x);
    }

    // all mask bits take value of same bool
    template <typename B>
    static AST_X<T> bitmask(const B& b) {
        return AST_X<T>(b);
    }

    template <typename B>
    static AST_X<T>* _bitmask(const B& b) {
        return new AST_X<T>(b);
    }

    // ternary
    template <typename B, typename X, typename Y>
    static AST_Op<T> ternary(const B& b, const X& x, const Y& y) {
        // (x & xword(b)) | (y & ~xword(b))
        return OR(
            _AND(x, _bitmask(b)),
            _AND(y, _CMPLMNT(_bitmask(b))));
    }

    template <typename B, typename X, typename Y>
    static AST_Op<T>* _ternary(const B& b, const X& x, const Y& y) {
        // (x & xword(b)) | (y & ~xword(b))
        return _OR(
            _AND(x, _bitmask(b)),
            _AND(y, _CMPLMNT(_bitmask(b))));
    }

    // test bit
    template <typename X>
    static AST_X<Alg_bool<FR>> testbit(const X& x, const unsigned int n) {
#ifdef USE_ASSERT
        assert(n < sizeof(VAL) * CHAR_BIT);
#endif
        return AST_X<Alg_bool<FR>>(SHR(x, n));
    }

    template <typename X>
    static AST_X<Alg_bool<FR>>* _testbit(const X& x, const unsigned int n) {
#ifdef USE_ASSERT
        assert(n < sizeof(VAL) * CHAR_BIT);
#endif
        return new AST_X<Alg_bool<FR>>(SHR(x, n));
    }

    // multiplication by x in GF(2^n)
    template <typename X, typename M>
    static AST_Op<T> xtime(const X& a, const M& modpoly) {
        return XOR(
            _SHL(a, 1),
            _AND(modpoly, _bitmask(testbit(a, sizeof(VAL) * CHAR_BIT - 1))));
    }

    template <typename X, typename M>
    static AST_Op<T>* _xtime(const X& a, const M& modpoly) {
        return _XOR(
            _SHL(a, 1),
            _AND(modpoly, _bitmask(testbit(a, sizeof(VAL) * CHAR_BIT - 1))));
    }

    // multiplication by GF(2^n)
    template <typename X, typename Y, typename M>
    static AST_Op<T> multiply(const X& a, const Y& b, const M& modpoly) {
        return XOR(multiply_internal(a, b, modpoly),
                   _AND(a, bitmask(testbit(b, 0))));
    }

    template <typename X, typename Y, typename M>
    static AST_Op<T>* _multiply(const X& a, const Y& b, const M& modpoly) {
        return _XOR(multiply_internal(a, b, modpoly),
                    _AND(a, bitmask(testbit(b, 0))));
    }

private:
    template <typename X, typename Y, typename M>
    static AST_Op<T>* multiply_internal(const X& a, const Y& b, const M& modpoly) {
        constexpr std::size_t N = sizeof(VAL) * CHAR_BIT;

        // multiplication by x in GF(2^n) for each bit position in b
        std::array<AST_Op<T>*, N> xtmp;
        xtmp[1] = _xtime(a, modpoly);
        for (std::size_t i = 2; i < N; ++i) {
            xtmp[i] = _xtime(xtmp[i - 1], modpoly);
        }

        // apply bits of b
        std::array<AST_Op<T>*, N> btmp;
        for (std::size_t i = 1; i < N; ++i) {
            btmp[i] = _AND(xtmp[i], _bitmask(testbit(b, i)));
        }

        // sum components up to last one
        auto* xorsum = btmp[N - 1];
        for (std::size_t i = N - 2; i > 0; --i) {
            xorsum = _XOR(xorsum, btmp[i]);
        }

        return xorsum;
    }

    // AST nodes at statement scope are on stack
    template <typename X, typename Y>
    static AST_Op<T> objOp(const typename T::OpType op, const X& x, const Y& y) {
        return AST_Op<T>(op, x, y);
    }

    // AST nodes nested below statement scope are on the heap
    template <typename X, typename Y>
    static AST_Op<T>* ptrOp(const typename T::OpType op, const X& x, const Y& y) {
        return new AST_Op<T>(op, x, y);
    }
};

} // namespace snarkfront

#endif
<|endoftext|>


<commit_before>#include <unittest++/UnitTest++.h>
<commit_msg>Made destructor of PersistentObject virtual. Started work on PersistentObject test file.<commit_after>#include <unittest++/UnitTest++.h>

namespace sqloxx
{

class

}  // namespace sqloxx

<|endoftext|>


<commit_before>
#pragma once

#include <string>
#include <tuple>
#include <type_traits>
#include <vector>

#include "astronomy/orbital_elements.hpp"
#include "geometry/grassmann.hpp"
#include "geometry/point.hpp"
#include "geometry/quaternion.hpp"
#include "geometry/r3_element.hpp"
#include "numerics/fixed_arrays.hpp"
#include "physics/degrees_of_freedom.hpp"
#include "quantities/elementary_functions.hpp"
#include "quantities/quantities.hpp"
#include "quantities/tuples.hpp"

namespace principia {
namespace mathematica {
namespace internal_mathematica {

using geometry::Bivector;
using geometry::Point;
using geometry::Quaternion;
using geometry::R3Element;
using geometry::Vector;
using numerics::FixedVector;
using physics::DegreesOfFreedom;
using quantities::Amount;
using quantities::Angle;
using quantities::Current;
using quantities::Exponentiation;
using quantities::is_tuple_v;
using quantities::Length;
using quantities::LuminousIntensity;
using quantities::Mass;
using quantities::Pow;
using quantities::Quantity;
using quantities::Quotient;
using quantities::Temperature;
using quantities::Time;

// A helper class for type erasure of quantities.  It may be used with the
// functions in this file to remove the dimensions of quantities (we know that
// Mathematica is sluggish when processing quantities).  Usage:
//
//   ToMathematica(... , ExpressIn(Metre, Second, Degree));
//
// The construction parameters must be for the base SI units.  They may be in
// any order.  If not enough parameters are specified for complete type erasure
// of the argument, compilation fails.  An object with no template parameters
// may be used to indicate that type erasure should not happen.
template<typename... Qs>
class ExpressIn {
 public:
  static constexpr bool is_default = sizeof...(Qs) == 0;

  // Check that only base SI units are specified.  If a unit is specified
  // multiple times, the calls to std::get in operator() won't compile.
  static_assert(
      is_default ||
      ((std::is_same_v<Qs, Length> || std::is_same_v<Qs, Mass> ||
        std::is_same_v<Qs, Time> || std::is_same_v<Qs, Current> ||
        std::is_same_v<Qs, Temperature> || std::is_same_v<Qs, Amount> ||
        std::is_same_v<Qs, LuminousIntensity> || std::is_same_v<Qs, Angle>) ||
       ...));

  ExpressIn(Qs const&... qs);

  template<typename Q>
  double operator()(Q const& q) const;

 private:
  template<std::int64_t exponent, typename Q1, typename Q2>
  Quotient<Q2, Exponentiation<Q1, exponent>> Divide(Q2 const& q2) const;

  std::tuple<Qs...> units_;
};

std::string Apply(std::string const& function,
                  std::vector<std::string> const& arguments);

template<typename T, typename... Qs>
std::string Option(std::string const& name,
                   T const& right,
                   ExpressIn<Qs...> express_in = {});

template<typename T, typename... Qs>
std::string Assign(std::string const& name,
                   T const& right,
                   ExpressIn<Qs...> express_in = {});

template<typename T, typename U, typename... Qs>
std::string PlottableDataset(std::vector<T> const& x,
                             std::vector<U> const& y,
                             ExpressIn<Qs...> express_in = {});

template<typename T, typename... Qs>
std::string ToMathematica(std::vector<T> const& list,
                          ExpressIn<Qs...> express_in = {});

template<typename It, typename... Qs>
std::string ToMathematica(It begin, It end,
                          ExpressIn<Qs...> express_in = {});

template<typename... Qs>
std::string ToMathematica(double real,
                          ExpressIn<Qs...> express_in = {});

template<typename T, int size, typename... Qs>
std::string ToMathematica(FixedVector<T, size> const& fixed_vector,
                          ExpressIn<Qs...> express_in = {});

template<typename T, typename... Qs>
std::string ToMathematica(R3Element<T> const& r3_element,
                          ExpressIn<Qs...> express_in = {});

template<typename... Qs>
std::string ToMathematica(Quaternion const& quaternion,
                          ExpressIn<Qs...> express_in = {});

template<typename D, typename... Qs>
std::string ToMathematica(Quantity<D> const& quantity,
                          ExpressIn<Qs...> express_in = {});

template<typename S, typename F, typename... Qs>
std::string ToMathematica(Vector<S, F> const& vector,
                          ExpressIn<Qs...> express_in = {});

template<typename S, typename F, typename... Qs>
std::string ToMathematica(Bivector<S, F> const& bivector,
                          ExpressIn<Qs...> express_in = {});

template<typename V, typename... Qs>
std::string ToMathematica(Point<V> const& point,
                          ExpressIn<Qs...> express_in = {});

template<typename F, typename... Qs>
std::string ToMathematica(DegreesOfFreedom<F> const& degrees_of_freedom,
                          ExpressIn<Qs...> express_in = {});

template<typename Tuple,
         typename = std::enable_if_t<is_tuple_v<Tuple>>,
         typename... Qs>
std::string ToMathematica(Tuple const& tuple,
                          ExpressIn<Qs...> express_in = {});

template<typename R,
         typename = std::void_t<decltype(std::declval<R>().time)>,
         typename = std::void_t<decltype(std::declval<R>().degrees_of_freedom)>,
         typename... Qs>
std::string ToMathematica(R ref,
                          ExpressIn<Qs...> express_in = {});

template<typename... Qs>
std::string ToMathematica(
    astronomy::OrbitalElements::EquinoctialElements const& elements,
    ExpressIn<Qs...> express_in = {});

// Returns its argument.
template<typename... Qs>
std::string ToMathematica(std::string const& str,
                          ExpressIn<Qs...> express_in = {});

// Wraps the string in quotes.
// TODO(egg): escape things properly.
std::string Escape(std::string const& str);

}  // namespace internal_mathematica

using internal_mathematica::Apply;
using internal_mathematica::Assign;
using internal_mathematica::Escape;
using internal_mathematica::ExpressIn;
using internal_mathematica::Option;
using internal_mathematica::PlottableDataset;
using internal_mathematica::ToMathematica;

}  // namespace mathematica
}  // namespace principia

#include "mathematica/mathematica_body.hpp"
<commit_msg>Lint.<commit_after>
#pragma once

#include <string>
#include <tuple>
#include <type_traits>
#include <vector>

#include "astronomy/orbital_elements.hpp"
#include "geometry/grassmann.hpp"
#include "geometry/point.hpp"
#include "geometry/quaternion.hpp"
#include "geometry/r3_element.hpp"
#include "numerics/fixed_arrays.hpp"
#include "physics/degrees_of_freedom.hpp"
#include "quantities/elementary_functions.hpp"
#include "quantities/quantities.hpp"
#include "quantities/tuples.hpp"

namespace principia {
namespace mathematica {
namespace internal_mathematica {

using geometry::Bivector;
using geometry::Point;
using geometry::Quaternion;
using geometry::R3Element;
using geometry::Vector;
using numerics::FixedVector;
using physics::DegreesOfFreedom;
using quantities::Amount;
using quantities::Angle;
using quantities::Current;
using quantities::Exponentiation;
using quantities::is_tuple_v;
using quantities::Length;
using quantities::LuminousIntensity;
using quantities::Mass;
using quantities::Pow;
using quantities::Quantity;
using quantities::Quotient;
using quantities::Temperature;
using quantities::Time;

// A helper class for type erasure of quantities.  It may be used with the
// functions in this file to remove the dimensions of quantities (we know that
// Mathematica is sluggish when processing quantities).  Usage:
//
//   ToMathematica(... , ExpressIn(Metre, Second, Degree));
//
// The construction parameters must be for the base SI units.  They may be in
// any order.  If not enough parameters are specified for complete type erasure
// of the argument, compilation fails.  An object with no template parameters
// may be used to indicate that type erasure should not happen.
template<typename... Qs>
class ExpressIn {
 public:
  static constexpr bool is_default = sizeof...(Qs) == 0;

  // Check that only base SI units are specified.  If a unit is specified
  // multiple times, the calls to std::get in operator() won't compile.
  static_assert(
      is_default ||
      ((std::is_same_v<Qs, Length> || std::is_same_v<Qs, Mass> ||
        std::is_same_v<Qs, Time> || std::is_same_v<Qs, Current> ||
        std::is_same_v<Qs, Temperature> || std::is_same_v<Qs, Amount> ||
        std::is_same_v<Qs, LuminousIntensity> || std::is_same_v<Qs, Angle>) ||
       ...));

  ExpressIn(Qs const&... qs);  // NOLINT(runtime/explicit)

  template<typename Q>
  double operator()(Q const& q) const;

 private:
  template<std::int64_t exponent, typename Q1, typename Q2>
  Quotient<Q2, Exponentiation<Q1, exponent>> Divide(Q2 const& q2) const;

  std::tuple<Qs...> units_;
};

std::string Apply(std::string const& function,
                  std::vector<std::string> const& arguments);

template<typename T, typename... Qs>
std::string Option(std::string const& name,
                   T const& right,
                   ExpressIn<Qs...> express_in = {});

template<typename T, typename... Qs>
std::string Assign(std::string const& name,
                   T const& right,
                   ExpressIn<Qs...> express_in = {});

template<typename T, typename U, typename... Qs>
std::string PlottableDataset(std::vector<T> const& x,
                             std::vector<U> const& y,
                             ExpressIn<Qs...> express_in = {});

template<typename T, typename... Qs>
std::string ToMathematica(std::vector<T> const& list,
                          ExpressIn<Qs...> express_in = {});

template<typename It, typename... Qs>
std::string ToMathematica(It begin, It end,
                          ExpressIn<Qs...> express_in = {});

template<typename... Qs>
std::string ToMathematica(double real,
                          ExpressIn<Qs...> express_in = {});

template<typename T, int size, typename... Qs>
std::string ToMathematica(FixedVector<T, size> const& fixed_vector,
                          ExpressIn<Qs...> express_in = {});

template<typename T, typename... Qs>
std::string ToMathematica(R3Element<T> const& r3_element,
                          ExpressIn<Qs...> express_in = {});

template<typename... Qs>
std::string ToMathematica(Quaternion const& quaternion,
                          ExpressIn<Qs...> express_in = {});

template<typename D, typename... Qs>
std::string ToMathematica(Quantity<D> const& quantity,
                          ExpressIn<Qs...> express_in = {});

template<typename S, typename F, typename... Qs>
std::string ToMathematica(Vector<S, F> const& vector,
                          ExpressIn<Qs...> express_in = {});

template<typename S, typename F, typename... Qs>
std::string ToMathematica(Bivector<S, F> const& bivector,
                          ExpressIn<Qs...> express_in = {});

template<typename V, typename... Qs>
std::string ToMathematica(Point<V> const& point,
                          ExpressIn<Qs...> express_in = {});

template<typename F, typename... Qs>
std::string ToMathematica(DegreesOfFreedom<F> const& degrees_of_freedom,
                          ExpressIn<Qs...> express_in = {});

template<typename Tuple,
         typename = std::enable_if_t<is_tuple_v<Tuple>>,
         typename... Qs>
std::string ToMathematica(Tuple const& tuple,
                          ExpressIn<Qs...> express_in = {});

template<typename R,
         typename = std::void_t<decltype(std::declval<R>().time)>,
         typename = std::void_t<decltype(std::declval<R>().degrees_of_freedom)>,
         typename... Qs>
std::string ToMathematica(R ref,
                          ExpressIn<Qs...> express_in = {});

template<typename... Qs>
std::string ToMathematica(
    astronomy::OrbitalElements::EquinoctialElements const& elements,
    ExpressIn<Qs...> express_in = {});

// Returns its argument.
template<typename... Qs>
std::string ToMathematica(std::string const& str,
                          ExpressIn<Qs...> express_in = {});

// Wraps the string in quotes.
// TODO(egg): escape things properly.
std::string Escape(std::string const& str);

}  // namespace internal_mathematica

using internal_mathematica::Apply;
using internal_mathematica::Assign;
using internal_mathematica::Escape;
using internal_mathematica::ExpressIn;
using internal_mathematica::Option;
using internal_mathematica::PlottableDataset;
using internal_mathematica::ToMathematica;

}  // namespace mathematica
}  // namespace principia

#include "mathematica/mathematica_body.hpp"
<|endoftext|>